diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..ce75319 Binary files /dev/null and b/.DS_Store differ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1bd47c1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +/secrets.py +/node/live_variables.js +/node/variables.js +/stack/ +/origin/images/ +/electron/dist/ +/electron/node_modules/ +/node/node_modules/ +/scripts/node_modules/ +*.pyc +*.pem +*.pub +/scripts/test.js \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..bdf8a87 --- /dev/null +++ b/LICENSE @@ -0,0 +1,24 @@ +LICENSE: AdventureLandOnlyUse + +Adventure Land Only Use: + +- You can't sell the source code or files +- You can use or modify the source code or files without permission, this license still applies to the modified source code or files +- You can sell game copies, subscriptions without permission, but can't sell the source code or files itself +- Usage of the source code or files or any modification can be revoked and you accept that you'll immediately seize usage +- You are responsible for any legal issues and costs arising from the use of this code or files +- You are responsible for all legal costs of AdventureLandOnlyUse licensing disputes +- You are free of this license if you completely rewrite a derivative game from scratch using different technologies and a new Codebase +- Updates to this license are binding for existing copies of this code and it's up to the user of the code to keep up to date +- Attribution is required. If there is a website, a crawlable link back to https://adventure.land is required +- Notification of a public launched version is required. Please email hello@adventure.land before or after publishing your game. Your game can be showcased or promoted without permission. +- Ethical use is required. Games shouldn't promote discrimination, hatred etc. +- With permission you can brand under https://adventure.land to kickstart your game without any asset licensing worries, but you are solely responsible for your own game + +Goodwill Income Sharing: + +If you choose so, you can send 5% of gross income or 10% of net. income to me via any means, Wise is preferred or email hello@adventure.land for a method. This is completely optional. + +Explanation: + +I've open sourced my game with the hope that it can kickstart new experimental MMORPG dynamics in days rather than years, so developers can even use the code commercially without any worries and significant obligations. This license is mainly to prevent unethical usages. diff --git a/README.md b/README.md index c09d675..2269f6d 100644 --- a/README.md +++ b/README.md @@ -1,101 +1,143 @@ -# adventureland -CODE Documentation for Adventure Land MMORPG https://adventure.land +# Adventure Land - The Open Source CODE MMORPG +https://adventure.land +The Source Code is now available to anyone, even for commercial use! (License applies) +**Please consider supporting Adventure Land on Patreon: https://www.patreon.com/AdventureLand** -Ps. Right now the documentation is in-game at https://adventure.land/docs +## Discussion -Ps 2. Type /codes in the Steam or Mac client, the auto synced folder also includes relevant libraries +Consider using the #development channel on Discord or messaging me directly on Discord as it's an easy way to communicate: https://discord.gg/hz25Kz9FsH +## Installation - +Clone the game files into the adventureland folder: +```sh +git clone https://github.com/kaansoral/adventureland adventureland +``` +Clone a modified copy of Python2 App Engine Local App Server into the python folder along with an initialized database with map files: -### Character / Players / Monsters +```sh +git clone https://github.com/kaansoral/adventureland-appserver appserver +``` +You'll need to download Python2.7 and use the command that comes along with it - it could be ./python or python.exe depending on your setup method +Here's the download page: https://www.python.org/downloads/release/python-2718/ +For Linux: +```sh +apt update +apt upgrade -y -* Properties - * .real_x - * .real_y - * .hp / .max_hp - * .mp / .max_mp - * .xp / .max_xp - * .party / .name / .rip / .afk / .code / .target / .id / .moving + more -* show_json(character) to see all the properties +apt install python2.7 git -y -### Things to Inspect +wget https://bootstrap.pypa.io/pip/2.7/get-pip.py +sudo python2.7 get-pip.py +pip2.7 check +``` -Replace everything on CODE with these show_json's +For MacOS pyenv makes sense as it prevents clash between Python versions and allows local versioning by just adding a .python-version to the folder https://github.com/pyenv/pyenv -* `show_json(character)` -* `show_json(character.items)` -* `show_json(character.slots)` -* `show_json(get_target())` -* `show_json(parent.G.monsters)` -* `show_json(parent.G.items)` -* `show_json(parent.G.skills)` -* `show_json(parent.G.npcs)` -* `show_json(parent.M)` +Make sure to install lxml afterwards: +```sh +pip2.7 install lxml +``` -### Provided Functions +Run the Python2.7 backend - includes an HTTP server, datastore, various utilities - emulates Google App Engine: +```sh +python2.7 appserver/sdk/dev_appserver.py --storage_path=appserver/storage/ --blobstore_path=appserver/storage/blobstore/ --datastore_path=appserver/storage/db.rdbms --host=0.0.0.0 --port=8083 adventureland/ --require_indexes --skip_sdk_update_check +``` -#### move(character.real_x,character.real_y) -Moves the character +Set up the NodeJS project for helpful scripts: +```sh +npm install adventureland/scripts/ +``` -#### get_nearest_monster({max_att:100,min_xp:10,target:"Name",no_target:true}) -Return's the nearest monster, you might want to target that return value with `change_target` +Set up the NodeJS game server: +```sh +npm install adventureland/node/ +``` -target: Picks monsters that only target that name +Edit the paths in `adventureland/node/variables.js` -no_target: Picks monster that aren't targeting anyone +Run a server: +```sh +node adventureland/node/server.js EU I 8022 +``` -#### use_hp_or_mp() -Uses a very basic logic to either use hp or mp pot +You should be able to access the game at: http://0.0.0.0:8083/ -#### get_target() -Returns your current target +The **useful/** folder has useful commands -#### get_target_of(entity) -New, powerful feature, returns the target entity for both players and monsters +`secrets.py` has the secrets -Suggestion for Fun: Code your characters to target and attack what you are targeting, even if you don't engage a monster, you can make your characters (or side-characters) engage by just clicking :) +## Network -#### change_target(target) -Targets the player or monster +Add these to your /etc/hosts file: +```sh +0.0.0.0 thegame.com +0.0.0.0 www.thegame.com +``` -#### loot() -Loots the chests on the map +And setup nginx with a conf such as: +```sh +worker_processes 3; -#### attack(target) -Attacks the target +events { + worker_connections 2048; +} -#### heal(target) -Heals the target +http { + include mime.types; + default_type application/octet-stream; -#### game_log(message,color) -Adds a message to game's right log + sendfile on; -#### show_json(character.items) -Renders the argument as json, to inspect, learn, use + keepalive_timeout 0; + proxy_read_timeout 200; + proxy_connect_timeout 30; + proxy_send_timeout 200; -#### set_message("Code Active") -Sets the IFrame message, the one in the right bottom corner + server { + listen 8080; + server_name thegame.com; + location / { + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Host $http_host; + proxy_redirect off; + proxy_pass http://localhost:8083; + expires -1; + } + } -#### runner_functions.js -There are more functions, examples in runner_functions.js and on the game's main CODE + include servers/*; +} +``` -### Future Plans -As the game progresses, the CODE feature will refine, you will be able to create/save your own code in-game, and hopefully much much more +This way you can run multiple different projects at once and reach them using a local url of your choice, my choice was thegame.com -With the introduction of PVP, Trade, Events and similar stuff, the CODE capabilities should get pretty interesting +If you choose to go live with the development server, make sure to block external access to every `login: admin` url you see in **app.yaml**. You could do this via a custom authentication or via nginx etc. -I'm also planning to add Networking between characters, so one might create a small team of bot helpers, or create a PVP team that consist entirely of bots +## How to Contribute -### Usage / Notes -* You have to keep the browser focused -* Otherwise browsers slow down the game -* Opening the game in a new window might be a good idea -* Keep in mind that CODE is currently an early prototype -* CODE runs in an IFrame, feel free to interact with **parent** -* You are free to inspect the client game code -* You can freely emulate a regular player -* Please don't use the CODE to hinder other players or the server -* You should be safe as long as the interval is 250ms -* Feel free to use Github Issues for Questions -* Ideally, at each Interval, move, attack, use/buy only once :) +This repository is the live version of the game. Any changes made will be live when the game is updated. Please create a Discord discussion in the **#development** channel before working on any big changes so your efforts aren't wasted or clash with the efforts of another contributor. Alternatively you can create a Github Issue if you don't use Discord. + +Content additions are very welcome, if you inspect the map data, there are many zones created yet not integrated. I'd be very happy to guide potential contributors in adopting and authoring a new zone, a new event, a new monster, a new mechanic and so on. + +I will include graphical assets, new item images manually. Please email them to hello@adventure.land + +## Suggestions + +I suggest you go live with this development codebase and approach development in a very agile manner, you can then move onto cloud if you wish to. My suggestion is to never move onto cloud and building a custom infrastructure using cheap dedicated servers with unlimited bandwidths. + +The main problem with traditional MMORPG's is people seeking power and while an offline game can provide this for everyone, an online game cannot. Pretty soon new players will avoid such MMORPG's and existing players will also dwindle. In my opinion there are 2 solutions, you could introduce a decay mechanic to overcome this, or concentrate your innovations and additions to make a more social game rather than a game for power hungry people. Originally I intended to add a lot more social integrations, for example browser notifications integrated to the social hub of the game and easy drop ins to friends playing the game etc. So making a more idle and more social game, with new custom art and a new direction could also be a good option, it's definitely the more serene option that anyone can pursue. + +## Freelancers + +Adventure Land's map designer is available for freelance work or for hire. Contact: markjlacandula@gmail.com + +I'm also available for working freelance on an hourly basis. Contact: hello@adventure.land + +If you have specific requirements, for example a unique cloud architecture in mind, I can help you find someone within our community that can handle the job. If you are an artist/designer and looking for a programmer to work on a game with, our Discord is also a good place to find someone! + +## License + +https://github.com/kaansoral/adventureland/blob/master/LICENSE \ No newline at end of file diff --git a/TODO.txt b/TODO.txt new file mode 100644 index 0000000..29f18d4 --- /dev/null +++ b/TODO.txt @@ -0,0 +1,12 @@ +- X button for mobile CODE to be able to hide +- TUTORIAL STEP: ITEM UI +- Merchant skills give XP +- Re-visit server.js 'creward' / 'ureward' +- Make spawns spawn on people who attacked +- IDEA: A lobby for A/B Testing +- Fix renaming of character code files, renaming one in the game UI breaks things + + +- SPIKE 2400 HP + +There's a character with an item that has a "name" set as an [] array - find and fix it [28/06/23] \ No newline at end of file diff --git a/WEEK.txt b/WEEK.txt new file mode 100644 index 0000000..cd42b05 --- /dev/null +++ b/WEEK.txt @@ -0,0 +1,5 @@ +- All the negative conditions are now affected by "stresistance" and sent as a "condition" character event +- There's a new very aggressive male Harpy +- Cuteness adds a negative aggro difference - this way >1 aggro values make some sense too +- Bling adds a positive aggro difference - this way even peaceful monsters could attack you +- New Item: Harpy Bow - along with its own crafting recipe, Harpy's both drop the crafting material and the bow itself, so it's not just low-RNG based and there'll be a slow but steady progress too \ No newline at end of file diff --git a/admin.py b/admin.py new file mode 100644 index 0000000..86c0b23 --- /dev/null +++ b/admin.py @@ -0,0 +1,190 @@ +from config import * +from functions import * + +class Renderer(webapp.RequestHandler): + @ndb.toplevel + def get(self): + whtml(self,"utility/htmls/renderer.html",domain=gdi(self)) + def post(self): self.get() + +class Events(webapp.RequestHandler): + @ndb.toplevel + def get(self,tag): + cursor=gdmul(self,"cursor") + if not tag: tag="noteworthy" + if tag=="all": events=Event.query().order(-Event.created) + else: events=Event.query(Event.tag==tag).order(-Event.created) + if cursor: events,ncursor,more=events.fetch_page(100,start_cursor=ndb.Cursor(urlsafe=cursor)) + else: events,ncursor,more=events.fetch_page(100) + ncursor=more and ncursor.urlsafe() + whtml(self,"utility/htmls/events.html",domain=gdi(self),events=events,ncursor=ncursor) + def post(self,tag): self.get(tag) + +def executor_task(the_code): + self=None + try: + exec(the_code) + except: + #admin_email(domain,"executor_task failed") + log_trace() + +class Executor(webapp.RequestHandler): + @ndb.toplevel + def get(self): + whtml(self,"utility/htmls/executor.html",domain=gdi(self)) + @ndb.toplevel + def post(self): + the_none="the_none_output_48" + the_code,is_task=gdmul(self,"code","is_task"); output=the_none; json_output=None; json_size=0; html_output=the_none; output_html=the_none; inspect=the_none; ess=datetime.now() + logging=custom_logging() + #logging=code_logs + if is_task: + deferred.defer(executor_task,the_code,_queue="default") + output="executor_task triggered" + else: + try: + exec(the_code) + except DeadlineExceededError: logging.error("Deadline Exceeded") + except: + log_trace_i("",logging) + if json_output!=None: json_size=olen(json_output); json_output=json.dumps(recursive_datetime_conversion(json_output)) + if html_output!=the_none: output_html=html_output + whtml(self,"utility/htmls/executor_output.html",logs=logging.output(),created=datetime.now(),ess_ms=mssince(ess), + output=output,json=json_output,json_size=json_size,html_output=output_html,inspector_output=(inspect!=the_none and ginspect(inspect,force_inspection=1))) + +class CommunityMapEditor(webapp.RequestHandler): + @ndb.toplevel + def get(self,name): + if not name: return + name=name.split("/")[0] + #if not ((name in community_maps) or name.startswith("jayson_")): return + domain=gdi(self); user=get_user(self,domain) + #if name.startswith("jayson_") and (not user or (user.k()+"") not in inner_circle): return + map=get_by_iid("map|%s"%name) + whtml(self,"utility/htmls/map_editor.html",domain=domain,name="main",map=map,tilesets=tilesets,community=1) + @ndb.toplevel + def post(self,name): + data=self.request.get("data") + name=name.split("/")[0] + if not ((name in community_maps) or name.startswith("jayson_")): return self.response.out.write("Not Permitted!") + domain=gdi(self); user=get_user(self,domain) + if name.startswith("jayson_") and (not user or (user.k()+"") not in inner_circle): return self.response.out.write("Not Permitted!") + map=get_by_iid("map|%s"%name) + if not map: map=Map(key=ndb.Key(Map,name),info=GG()) + map.info.data=json.loads(data) + process_map(map) + map.updated=datetime.now() + map.put() + copy_map(name,"test") + self.response.out.write(to_pretty_num(olen(map.info.data))) + +class MapEditor(webapp.RequestHandler): + @ndb.toplevel + def get(self,name): + if not name: self.redirect("/admin/map_editor/main"); return + name=name.split("/")[0] + map=get_by_iid("map|%s"%name) + whtml(self,"utility/htmls/map_editor.html",domain=gdi(self),name="main",map=map,tilesets=tilesets) + @ndb.toplevel + def post(self,name): + data=self.request.get("data") + name=name.split("/")[0] + map=get_by_iid("map|%s"%name) + if not map: map=Map(key=ndb.Key(Map,name),info=GG()) + map.info.data=json.loads(data) + process_map(map) + map.updated=datetime.now() + map.put() + copy_map(name,"test") + self.response.out.write(to_pretty_num(olen(map.info.data))) + +class Selector(webapp.RequestHandler): #NOTICE: << Publicly available at /communityselector! >> [10/10/16] + @ndb.toplevel + def get(self,name): + if not name: self.redirect("/admin/selector/pack_1a"); return + name=name.split("/")[0] + file=imagesets[name]["file"] + size=imagesets[name]["size"] + width=imagesets[name]["columns"]*size + height=imagesets[name]["rows"]*size + xs=[]; ys=[] + for i in xrange(width/size): xs.append(i) + for j in xrange(height/size): ys.append(j) + whtml(self,"utility/htmls/selector.html",domain=gdi(self),name=name,file=file,size=size,width=width,height=height,xs=xs,ys=ys,scale=3) + def post(self,name): self.get(name) + +class PhotoUpload(blobstore_handlers.BlobstoreUploadHandler): + @ndb.toplevel + def post(self): + domain=gdi(self); user=get_user(self,domain) + if security_threat(self,domain): return + upload_files = self.get_file_infos('image'); file_info = upload_files[0]; blob_key=blobstore.create_gs_key_async(file_info.gs_object_name) + key=gdmul(self,"key"); + logging.info("Image Upload %s"%(key)) + upload=get_by_iid("upload|%s"%key); blob_key=blob_key.get_result() + if not upload: upload=Upload(key=ndb.Key(Upload,key),info=GG()) + + + if file_info.content_type in ["image/jpg","image/jpeg","image/jpe","image/png","image/gif"]: + if gf(upload,"blob_key"): + try: + blobstore.delete(blob_keys=upload.info.blob_key) + logging.info("Old image deleted") + except: log_trace() + + url=get_serving_url(blob_key,size=images.IMG_SERVING_SIZES_LIMIT) + size=get_image_size(blob_key,encoding=filetype_to_image_encoding(file_info.content_type)) + + upload.info.blob_key=blob_key + upload.info.content_type=file_info.content_type + upload.info.gs_object_name=file_info.gs_object_name + upload.info.url=url + upload.info.width=size.width + upload.info.height=size.height + + self.response.out.write("{
 '%s':{'url':'%s','width':%s,'height':%s},
}"%(key,url,size.width,size.height)) + upload.put() + else: + blobstore.delete(blob_keys=blob_key) + self.response.out.write("Not an image") + def get(self): self.post() + +class PhotoUploader(webapp.RequestHandler): + @ndb.toplevel + def get(self): + domain=gdi(self); user=get_user(self,domain) + if security_threat(self,domain): return + upload_url=blobstore.create_upload_url('/admin/upload/handler',gs_bucket_name=domain.gcs_bucket+"/files") + whtml(self,"utility/htmls/uploader.html",domain=domain,upload_url=upload_url) + +class Items(webapp.RequestHandler): #NOTICE: << Publicly available at /communityitems! >> [10/10/16] + @ndb.toplevel + def get(self): + domain=gdi(self) + #if not is_current_user_admin(): + # user=get_user(self,domain) + # if not user or user.k()+"" not in [ellian_id,hello_id]: return + mode,items=gdmul(self,"mode","items") + whtml(self,"utility/htmls/items.html",domain=domain,mode=mode,items=items) + def post(self): self.get() + +class Backups(webapp.RequestHandler): + @ndb.toplevel + def get(self,m,id): + domain=gdi(self) + backups=Backup.query(Backup.backup_item_id=="%s|%s"%(m,id)).order(-Backup.backup_created).fetch(50) + whtml(self,"utility/htmls/backups.html",domain=domain,backups=backups) + def post(self,m,id): self.get(m,id) + +application = webapp.WSGIApplication([ + ('/admin/renderer', Renderer), + ('/admin/executor', Executor), + ('/admin/items', Items), + ('/admin/upload', PhotoUploader), + ('/admin/upload/handler', PhotoUpload), + ('/admin/backups/(.*)/(.*)', Backups), + ('/admin/events/?(.*)', Events), + ('/admin/map_editor/?(.*)', MapEditor), + ('/admin/selector/?(.*)', Selector), + ('/admin/items', Items), + ],debug=is_sdk) \ No newline at end of file diff --git a/api.py b/api.py new file mode 100644 index 0000000..baccc96 --- /dev/null +++ b/api.py @@ -0,0 +1,1738 @@ +from config import * +from functions import * + +def signup_or_login_api(**args): + #time.sleep(10) + self,domain,email,password,only_login,only_signup,mobile=gdmuld(args,"self","domain","email","password","only_login","only_signup","mobile") + logging.info("Signup or Login") + + try: email=purify_email(email) + except: return jhtmle(self,"Invalid Email") + + if not password: + jjson(self,{"type":"eval","code":"$('.passwordui').show()"}) + jhtmle(self,"No Password Entered"); + return + + existing=get_user(email=email,phrase_check=True) + + if existing and existing.server: + if msince(existing.last_online)>15 and msince(gf(existing,"last_auth",really_old))>15: pass # [15/05/22] + else: jhtmle(self,"Can't login while inside the bank"); return + if not domain.electron and not only_login and not domain.is_sdk: jhtmle(self,"Can't signup on web"); return + + if existing and not only_signup: + if existing.password==password or existing.password==hash_password(password,gf(existing,"salt","5")): + def login_transaction(): + user=get_by_iid(existing.k('i')) + auth=get_new_auth(self,user,domain) + user.put() + return user,auth + user=ndb.transaction(login_transaction,xg=True,retries=12) + if user: + user,auth=user + set_cookie(self,"auth","%s-%s"%(user.k(),auth)) + if mobile: + return jhtml(self,[{"type":"refresh"}]); + jhtml(self,[ + {"type":"message","message":"Logged In!" }, + selection_info(self,user,domain), + ]) + else: + jhtmle(self,"Login Failed. Please Retry Later.") + return + jjson(self,{"type":"eval","code":"$('.passwordui').show()"}) + jhtmle(self,"Wrong Password") + return + + if not email: return jhtmle(self,"No Email Entered") + + if only_login: return jhtmle(self,"Email Not Found In Records") + + signupth=get_signupth() + ip=get_ip_info(self) + referrer=get_referrer(self,ip) + + if gf(ip,"limit_signups",0)>=3: return jhtmle(self,"Too many signups from this IP. Please wait a couple hours or use a non-public network") + + if only_signup and existing: + return jhtmle(self,"Email already signed up! Please login instead.") + + def signup_transaction(): + markedphrase=get_by_iid("markedphrase|%s"%dgt("email",email)) + if markedphrase: return False + salt=randomStr(20) + hpassword=hash_password(password,salt) + user=User(name="#%s"%signupth,password=hpassword,email=[email],info=cGG(gold=1000,salt=salt)) + user.referrer=(referrer and "%s"%referrer.k()) or "" + user.info.signupth=signupth + user.info.email=email + user.info.ip=get_ip(self); user.info.country=get_country(self) + user.info.characters=[]; user.info.slots=5 + if domain.electron: user.info.slots=8 + user.info.items=[] + user.info.everification=randomStr(12) + auth=get_new_auth(self,user,domain) + user.put() + mark_phrase(user,"email",email) + return user,auth + user=ndb.transaction(signup_transaction,xg=True,retries=12) + + if not user: return jhtmle(self,"Signup Failed") + + user,auth=user + set_cookie(self,"auth","%s-%s"%(user.k(),auth)) + send_verification_email(domain,user) + jhtml(self,[ + {"type":"success","message":"Signup Complete!" }, + selection_info(self,user,domain), + ]) + add_event(user,"signup",["new","noteworthy"],self=self,info=cGG(message="Signup %s"%(user.info.email)),async=True) + increase_signupth() + + try: + ip=get_ip_info(self) + ip.info.limit_signups=gf(ip,"limit_signups",0)+1 + put_ip_info(ip,user=user) + except: + log_trace() + +def settings_api(**args): + self,domain,user,setting,value=gdmuld(args,"self","domain","user","setting","value") + if not user: return + if user.server: return jhtmle(self,"Can't make changes while inside the bank") + def setting_transaction(): + nuser=get_by_iid(user.k('i')) + if setting=="email": + if value: nuser.info.dont_send_emails=False + else: nuser.info.dont_send_emails=True + domain.section="email" + nuser.put() + return nuser + user=ndb.transaction(setting_transaction,xg=True,retries=0) + jhtml(self,[ + {"type":"success","message":"Setting changed!" }, + selection_info(self,user,domain), + ]) + +def change_email_api(**args): + self,domain,user,email=gdmuld(args,"self","domain","user","email") + if not user: return + + try: email=purify_email(email) + except: return jhtmle(self,"Invalid Email") + + existing=get_user(email=email,phrase_check=True) + + if existing: + if existing.k()!=user.k(): return jhtmle(self,"Email might be registered to someone else") + if gf(user,"verified",0): return jhtmle(self,"This email is already verified") + + if user.server: return jhtmle(self,"Can't make changes while inside the bank") + if gf(user,"last_email_change") and hsince(gf(user,"last_email_change"))<18: jhtmle(self,"You can change your email once every 18 hours"); return + def change_email_transaction(): + delete_phrase_mark("email",user.info.email) + markedphrase=get_by_iid("markedphrase|%s"%dgt("email",email)) + if markedphrase: return False + nuser=get_by_iid(user.k('i')) + nuser.email=[email] + nuser.info.email=email + nuser.info.last_email_change=datetime.now() + if gf(nuser,"verified",0): del nuser.info.verified + nuser.info.everification=randomStr(12) + nuser.put() + mark_phrase(nuser,"email",email) + return nuser + + user=ndb.transaction(change_email_transaction,xg=True,retries=2) + if not user: return jhtmle(self,"Operation failed") + send_verification_email(domain,user) + jhtml(self,[ + {"type":"success","message":"Email changed! Verification email re-sent. Refresh the page."}, + selection_info(self,user,domain), + ]) + +def change_password_api(**args): + self,domain,user,epass,newpass1,newpass2=gdmuld(args,"self","domain","user","epass","newpass1","newpass2") + if not user: return + if user.server: return jhtmle(self,"Can't make changes while inside the bank") + if user.password!=epass and user.password!=hash_password(epass,gf(user,"salt","5")): jhtmle(self,"Wrong Password"); return + if not newpass1 or newpass1!=newpass2: jhtmle(self,"Passwords don't match"); return + def password_transaction(): + nuser=get_by_iid(user.k('i')) + nuser.info.salt=randomStr(20) + nuser.password=hash_password(newpass1,nuser.info.salt) + nuser.put() + return nuser + user=ndb.transaction(password_transaction,xg=True,retries=0) + jhtml(self,[ + {"type":"success","message":"Password changed!" }, + selection_info(self,user,domain), + ]) + +def reset_password_api(**args): + self,domain,id,key,newpass1,newpass2=gdmuld(args,"self","domain","id","key","newpass1","newpass2") + if not newpass1 or newpass1!=newpass2: jhtmle(self,"Passwords don't match"); return + user=get_by_iid("user|%s"%id) + if not user or gf(user,"password_key")!=key: jhtmle(self,"Invalid key"); return + if user.server: return jhtmle(self,"Can't make changes while inside the bank") + def password_transaction(): + nuser=get_by_iid(user.k('i')) + nuser.info.salt=randomStr(20) + nuser.password=hash_password(newpass1,nuser.info.salt) + nuser.info.password_key=randomStr(20) + nuser.put() + return nuser + user=ndb.transaction(password_transaction,xg=True,retries=0) + jhtmls(self,"New password set!") + +def password_reminder_api(**args): + self,domain,email=gdmuld(args,"self","domain","email") + try: email=purify_email(email) + except: jhtmle(self,"Invalid Email"); return + existing=get_user(email=email,phrase_check=True) + if not existing: jhtmle(self,"Email not found"); return + if existing.server: return jhtmle(self,"Can't make changes while inside the bank") + if hsince(gf(existing,"last_password_reminder",really_old))<24: jhtmle(self,"Already sent a reminder recently (24 hours)"); return + def pmark_transaction(): + user=get_by_iid(existing.k('i')) + user.info.last_password_reminder=datetime.now() + user.info.password_key=randomStr(20) + user.put() + return user + user=ndb.transaction(pmark_transaction,xg=True,retries=2) + send_password_reminder_email(domain,user) + jhtmls(self,"Emailed password reset instructions") + +def account_change_api(**args): + self,domain,user=gdmuld(args,"self","domain","user") + jhtmlm(self,"Coming Soon: Re-Verification, Email Change, Password Change - For now, if you need something, just email hello@adventure.land") + +def log_error_api(**args): + self,domain,user,server,type,err,info=gdmuld(args,"self","domain","user","server","type","err","info") + logging.info(server) + if user and type not in ["api_call_error"]: return + if server and type not in ["appengine_call_error"]: return + if user: + add_event(user,"client_error",["error",type],self=self,info=cGG(message="[%s] %s"%(type,err),info=info)) + if server: + add_event(server,"server_error",["error",type],self=self,info=cGG(message="[%s] %s"%(type,err),info=info)) + jhtml(self) + +def servers_and_characters_api(**args): + self,domain,user=gdmuld(args,"self","domain","user") + if not user: jhtmle(self,"No User"); return + + user_data=get_user_data(user) #no need for async, as get_user prefetches the data + + characters_data=get_characters(user) + characters=characters_to_client(characters_data) + + servers_data=get_servers() + servers=servers_to_client(domain,servers_data) + + mail=gf(user_data,"mail",0) + + logging.info("servers_and_characters") + jhtml(self,[{"type":"servers_and_characters","servers":servers,"characters":characters,"tutorial":data_to_tutorial(user_data),"code_list":gf(user_data,"code_list",{}),"mail":mail,"rewards":gf(user,"rewards",[])}]) + +def save_code_api(**args): + self,domain,user,code,slot,name,log,auto,electron=gdmuld(args,"self","domain","user","code","slot","name","log","auto","electron") + if not user: return + to_delete=False; old_name=name; character=None + data=get_user_data(user) + if not gf(data,"code_list"): data.info.code_list={} + if not code: code="" + if not slot: + jhtmle(self,"CODE save operation failed. No slot provided") + try: + slot=int(slot); found=False + for c in gf(user,"characters",[]): + if int(c["id"])==slot: + found=True + character=c["name"] + if data.info.code_list.get(slot) and name=="DELETE": found=True + if not found: slot=max(1,min(100,slot)) + except: + return jhtmle(self,"Slot needs to be a number") + if not name: name=data.info.code_list.get(slot,[None])[0] + if not name: name="%s"%(character or slot) + old_name=data.info.code_list.get(slot,[name])[0] + name=to_filename(name)[:100] #without this, one could duplicate items [23/10/18] + #if slot>2 and not gf(user,"code_unlocked"): jhtmlc(self,"An 'Ancient Computer' unlocks code slots 3 to 100. You can freely use slots 1 and 2.","#3386CF"); return + try: + def save_transaction(): + idata=get_user_data(user) + if not gf(idata,"code_list"): idata.info.code_list={} + if name=="DELETE": + try: + del idata.info.code_list[slot] + ndb.Key(InfoElement,"USERCODE-%s-%s"%(user.k(),slot)).delete() + except: pass + else: + InfoElement(key=ndb.Key(InfoElement,"USERCODE-%s-%s"%(user.k(),slot)),info=cGG(code=code)).put() + idata.info.code_list[slot]=[name,int(idata.info.code_list.get(slot,[None,0])[1])+1] + logging.info("Slot changed from %s to %s"%(idata.info.code_list.get(slot,None),name)) + idata.put() + return idata + result=ndb.transaction(save_transaction,xg=True,retries=2) + if result: data=result + except: + log_trace() + return jhtmle(self,"CODE save operation failed. If your CODE is larger than 1MB, you need to shrink it, otherwise retry in a minute.") + if name=="DELETE": + jjson(self,{"type":"code_info","num":slot,"delete":True}); + if not electron: jeval(self,"code_slot=0;code_change=false;") + if log: jhtmlc(self,"Deleted %s.%s.js"%(old_name,slot),"gray") + else: jhtmlchat(self,"Deleted %s.%s.js"%(old_name,slot),"gray") + else: + jjson(self,{"type":"code_info","num":slot,"name":data.info.code_list[slot][0],"v":data.info.code_list[slot][1]}); + if not electron: jeval(self,"code_slot=%s;code_change=false;"%(slot)) + if log: jhtmlc(self,"Saved %s.%s.js"%(name,slot),"#E13758") + elif auto and character: jhtmlc(self,"Auto-saved [%s]"%(character),"#96E8A7") + elif auto: jhtmlc(self,"Auto-saved %s.%s.js"%(name,slot),"#96E8A7") + else: jhtmlchat(self,"Saved %s.%s.js"%(name,slot),"#E13758") + +def load_code_api(**args): + self,domain,user,name,run,log,pure,save=gdmuld(args,"self","domain","user","name","run","log","pure","save") + name=to_filename("%s"%name) + if not user: return + data=get_user_data(user) + if name in [0,"0"]: + if pure: return shtml("htmls/contents/codes/default_code.js") + jjson(self,{"type":"code","code":shtml("htmls/contents/codes/default_code.js"),"run":run,"slot":0,"save":save}); + if save: jhtml(self) + elif log: jhtmlc(self,"Loaded the default code","#32A3B0") + else: jhtmlchat(self,"Loaded the default code","#32A3B0") + return + for slot in gf(data,"code_list",{}): + if str(slot)=="%s"%name or ("%s"%data.info.code_list[slot][0]).lower()==("%s"%name).lower(): + code=ndb.Key(InfoElement,"USERCODE-%s-%s"%(user.k(),slot)).get() + if code: + if pure: return code.info.code + jjson(self,{"type":"code","code":code.info.code,"run":run,"slot":slot,"save":save,"name":data.info.code_list[slot][0],"v":data.info.code_list[slot][1]}); + if save: jhtml(self) + elif log: jhtmlc(self,"Loaded %s.%s.js"%(data.info.code_list[slot][0],slot),"#32A3B0") + else: jhtmlchat(self,"Loaded %s.%s.js"%(data.info.code_list[slot][0],slot),"#32A3B0") + return + if pure: return "say('Code not found'); set_status('Not Found')" + jhtmlchat(self,"Not Found","#AD3844") + +def load_libraries_api(**args): + self,domain,user=gdmuld(args,"self","domain","user") + jjson(self,{ + "type":"libraries", + "default_code":shtml("htmls/contents/codes/default_code.js"), + "runner_functions":shtml("htmls/contents/codes/runner_functions.js"), + "runner_compat":shtml("htmls/contents/codes/runner_compat.js"), + "common_functions":shtml("htmls/contents/codes/common_functions.js") + }); + jhtml(self) + +def tutorial_api(**args): + self,domain,user,task,step=gdmuld(args,"self","domain","user","task","step") + def data_transaction(): + data=get_user_data(user) + if task: + if task in docs["tasks"] and task not in data.info.completed_tasks: + data.info.completed_tasks.append(task) + data.put() + return ["Task '%s' Complete!"%docs["tasks"][task],"#85C76B",data,1] + else: + if task in docs["tasks"]: return ["Task '%s' Complete!"%docs["tasks"][task],"gray",data,1] + else: return ["Invalid task '%s'"%task,"gray",data,0] + else: + data.info.tutorial_step=int(step) + data.put() + return ["Lesson '%s' Complete!"%docs["tutorial"][int(step)-1]["title"],"#85C76B",data,2] + result=ndb.transaction(data_transaction,xg=True,retries=2) + if result: + info=data_to_tutorial(result[2]); + info["type"]="tutorial_data" + if result[3]==1: info["success"]=True + if result[3]==2: info["next"]=True + jjson(self,info) + jhtmlc(self,result[0],result[1]) + else: + jhtmle(self,"Failed") + +def reset_tutorial_api(**args): + self,domain,user,task,step=gdmuld(args,"self","domain","user","task","step") + def data_transaction(): + return reset_tutorial(user) + result=ndb.transaction(data_transaction,xg=True,retries=2) + if result: + info=data_to_tutorial(result) + info["type"]="tutorial_data" + jjson(self,info) + jhtmlc(self,"Tutorial Reset!","#F7B32F") + else: + jhtmle(self,"Failed") + +def load_map_api(**args): + self,domain,user,key=gdmuld(args,"self","domain","user","key") + map=get_by_iid("map|%s"%key) + if not map or not gf(map,"resort"): jhtmlc(self,"Deck not found","#AE384D") + jjson(self,{"type":"map","data":map.info.data,"run":run}) + jhtml(self) + +def load_article_api(**args): + #logging.info(col) + self,domain,user,name,func,tutorial,guide,url=gdmuld(args,"self","domain","user","name","func","tutorial","guide","url") + if tutorial: jjson(self,{"type":"article","html":shtml("docs/tutorial/%s.html"%name),"tutorial":tutorial,"url":url}) + elif guide: + from docs.directory import docs + col=[]; prev=None; next=None; found=False + def traverse(entry): + if type(entry[0])==type([]): + for e in entry: + traverse(e) + else: + if len(entry)==5 and entry[4]: + traverse(entry[4]) + else: + col.append(entry[0]) + traverse(docs["guide"]) + #logging.info(col) + for i in xrange(0,len(col)): + if col[i]==name: + found=True + if i+1!=len(col): next=col[i+1] + break + prev=col[i] + #logging.info([prev,next]) + try: jjson(self,{"type":"article","html":shtml("docs/guide/%s.html"%name),"guide":guide,"url":url,"prev":found and prev,"next":found and next}) + except: jjson(self,{"type":"article","html":shtml("docs/articles/%s.html"%name),"url":url,"prev":found and prev,"next":found and next}) + elif func: jjson(self,{"type":"article","html":shtml("docs/functions/%s.html"%name),"func":name,"url":url}) + else: jjson(self,{"type":"article","html":shtml("docs/articles/%s.html"%name),"url":url}) + jhtml(self) + +def load_gcode_api(**args): + self,domain,user,file,run=gdmuld(args,"self","domain","user","file","run") + if run: jjson(self,{"type":"code","code":shtml("docs%s"%file),"run":True}) + else: jjson(self,{"type":"gcode","code":shtml("docs%s"%file)}) + jhtml(self) + +def list_codes_api(**args): + self,domain,user,purpose=gdmuld(args,"self","domain","user","purpose") + if not user: return + data=get_user_data(user) + jhtml(self,[{"type":"code_list","purpose":purpose,"list":gf(data,"code_list",{})}]) + +def can_create_character(self,user): + ip=get_ip_info(self) + if user.pid: user.info.slots=max(gf(user,"slots",8),8) + if gf(ip,"limit_create_character",0)>12: return False,"ip" + if len(gf(user,"characters",[]))>=18: return False,"abs" + if len(gf(user,"characters",[]))>=gf(user,"slots",5): + if user.cash>=200: return True,True + return False,"limit" + return True,True + +def is_name_allowed(name): + try: + if int(name): return False + except: pass + for c in name: + if c not in allowed_name_characters: + return False + if len(name)<4: return False + if len(name)>12: return False + return True + +def create_character_api(**args): + self,domain,user,name,char,look=gdmuld(args,"self","domain","user","name","char","look") + if char not in character_types: jhtmle(self,"Character type not allowed"); return + if len(classes[char]["looks"])<=int(look): jhtmle(self,"Invalid look"); return + #if gender not in gender_types: jhtmle(self,"Gender unknown"); return + if not name: jhtmle(self,"Please enter a name"); return + name=name.replace(" ","").replace("\t","") + if not is_name_allowed(name): jhtmle(self,"Invalid character name, may be too short, too long, or include invalid characters"); return + if get_character(name,phrase_check=True): jhtmlm(self,"%s is used"%name); return + if user.server: return jhtmle(self,"Can't make changes while inside the bank") + creatable,reason=can_create_character(self,user) + if not creatable: + if reason=="ip": jhtmle(self,"Too many characters from this IP. Please wait a couple hours or use a non-public network"); return + if reason=="abs": jhtmle(self,"You can't create more than 18 characters"); return + jhtmlm(self,"You've reached the current limit of free characters. You can freely create 5 characters. Delete a character you don't want to use. Recreate another character."); return + characterth=get_characterth() + def new_character_transaction(): + markedphrase=get_by_iid("markedphrase|%s"%dgt("character",simplify_name(name))) + owner=get_by_iid(user.k('i')) + if markedphrase: return False + base=classes[char] + character=Character(name=simplify_name(name),owner=user.k(),type=char,referrer=owner.referrer,info=GG()) + character.info.characterth=characterth + character.info.name=name + character.info.gold=0 + character.info.items=[{"name":"hpot0","q":200,"gift":1},{"name":"mpot0","q":200,"gift":1}] + character.info.slots=copy.deepcopy(base["base_slots"]) + if 1: + character.info.slots["helmet"]={"name":"helmet","level":0,"gift":1} + character.info.slots["shoes"]={"name":"shoes","level":0,"gift":1} + character.info.stats={} + #character.info.gender=gender + character.info.skin=base["looks"][look][0] + character.info.cx=base["looks"][look][1] + character.info.map="main" + setattr(character.info,"in","main") + character.info.x,character.info.y=maps["main"]["spawns"][maps["main"].get("on_death",["main",0])[1]] + character.put() + if not len(owner.info.characters): owner.name=name + if len(owner.info.characters)>=gf(owner,"slots",5): + owner.info.slots=gf(owner,"slots",5)+1 + owner.cash-=200 + owner.info.characters.append(character_to_dict(character)) + if not owner.name or owner.name.startswith("#"): owner.name=name + if not gf(owner,"server_data"): + logging.info("created Player for %s"%owner.k()) + + owner.put() + mark_phrase(character,"character",simplify_name(name)) + return character,owner + character=ndb.transaction(new_character_transaction,xg=True,retries=12) + if not character: jhtmle(self,"Creation Failed"); return + character,owner=character + try: + ip=get_ip_info(self) + ip.info.limit_create_character=gf(ip,"limit_create_character",0)+1 + put_ip_info(ip,user=user,character=character) + except: + log_trace() + jhtml(self,[ + {"type":"success","message":"%s is alive!"%name }, + selection_info(self,owner,domain), + ]) + add_event(owner,"new_character",["characters","noteworthy"],self=self,info=cGG(message="New Character %s from %s"%(character.info.name,user.info.email)),backup=True,async=True) + increase_characterth() + +def sort_characters_api(**args): + self,domain,user,l=gdmuld(args,"self","domain","user","characters") + if not user: return + rest=Character.query(Character.owner==user.k()).fetch(100) + characters=[] + for name in ("%s"%l).split(","): + for c in rest: + if simplify_name(name)==simplify_name(c.name): + characters.append(c) + rest.remove(c) + break + characters.extend(rest) + # for c in characters: + # logging.info(c.name) + # jhtmls(self,"OK") + def sort_transaction(): + owner=get_by_iid(user.k('i')); first=False; firstp=False + owner.info.characters=[] + for c in characters: + if not first: owner.name=c.info.name; first=True + if not firstp and not c.private: owner.name=c.info.name; firstp=True + owner.info.characters.append(character_to_dict(c)) + owner.info.transfer_auth=randomStr(10) + owner.put() + return owner + result=ndb.transaction(sort_transaction,xg=True,retries=1) + if result: + jhtml(self,[ + {"type":"message","message":"Done!"}, + selection_info(self,result,domain), + ]) + else: + jhtmlm(self,"Something went wrong") + +def is_name_xallowed(name): + try: + if int(name): return False + except: pass + for c in name: + if c not in allowed_name_characters: + return False + if len(name)<1: return False + if len(name)>12: return False + return True + +def quote_name_api(**args): + self,domain,user,name,nname=gdmuld(args,"self","domain","user","name","nname") + + if not nname or not is_name_xallowed(nname): return jhtmle(self,"Invalid name") + if get_character(nname,phrase_check=True): return jhtmle(self,"%s is used"%nname) + + character=get_character(name) + + price=400 + if len(nname)==1: price=160000 + elif len(nname)==2: price=48000 + elif len(nname)==3: price=24000 + elif len(nname)==4: price=2400 + else: + if character and not gf(character,"last_rename",None) and (character.level<60 or hsince(character.created)<72): price=0 + price=640 + jeval(self,"show_alert('Costs %s shells')"%to_pretty_num(price)); jhtml(self) + +def rename_character_api(**args): + self,domain,user,name,nname=gdmuld(args,"self","domain","user","name","nname") + + character=get_character(name) + if not character: return jhtmle(self,"No character with that name.") + if character.owner!=user.k(): return jhtmle(self,"You don't own that character.") + if is_in_game(character): return jhtmle(self,"Character is in game.") + if hsince(gf(character,"last_rename",really_old))<32: return jhtmle(self,"You can rename once every 32 hours!") + + if not nname or not is_name_xallowed(nname): return jhtmle(self,"Invalid name") + if get_character(nname,phrase_check=True): return jhtmle(self,"%s is used"%nname) + + if user.server: return jhtmle(self,"Can't make changes while inside the bank") + + price=400 + if len(nname)==1: price=160000 + elif len(nname)==2: price=48000 + elif len(nname)==3: price=24000 + elif len(nname)==4: price=2400 + else: + if not gf(character,"last_rename",None) and (character.level<60 or hsince(character.created)<72): price=0 + price=640 + + if user.cash0 and element.cash0: add_event(result,"bill",["cashflow"],self=self,info=cGG(message="%s [%s] spent %s shells for: %s"%(name,user.k(),amount,reason),amount=amount,reason=reason),async=True) + else: add_event(result,"ishells",["cashflow"],self=self,info=cGG(message="%s [%s] received %s shells from: %s"%(name,user.k(),-amount,reason),amount=-amount,reason=reason),async=True) + try: deferred.defer(update_characters,result) + except: log_trace() + else: + jhtmlm(self,"Purchase failed") + +def bill_user_api(**args): + self,domain,user,server,amount,reason,name,override=gdmuld(args,"self","domain","user","server","amount","reason","name","override") + #amount=max(0,int(amount)) + amount=int(amount) + if not server: jhtml(self,{"failed":1,"reason":"noserver"}); return + if not user: jhtml(self,{"failed":1,"reason":"nouser"}); return + if user.server and not override: jhtml(self,{"failed":1,"reason":"inthebank"}); return + def bill_user_transaction(): + element=get_by_iid(user.k('i')) + if amount>0 and element.cash0: add_event(result,"bill",["cashflow"],self=self,info=cGG(message="%s [%s] spent %s shells for: %s"%(name,user.k(),amount,reason),amount=amount,reason=reason),async=True) + else: add_event(result,"ishells",["cashflow"],self=self,info=cGG(message="%s [%s] received %s shells from: %s"%(name,user.k(),-amount,reason),amount=-amount,reason=reason),async=True) + try: deferred.defer(update_characters,result) + except: log_trace() + else: + jhtml(self,{"failed":1,"reason":"unknown"}) + +def can_reload_api(**args): + self,domain,user,pvp,region,name=gdmuld(args,"self","domain","user","pvp","region","name") + if not user: return jhtml(self,[]) + servers=get_servers() + for server in servers: + if server.region==region and name==server.name and (pvp and gf(server,"pvp") or not pvp and not gf(server,"pvp")): + return jhtml(self,[{"type":"reload","ip":server.ip,"port":server.port}]) + return jhtml(self,[]) + +def pull_guild_api(**args): + self,domain,user=gdmuld(args,"self","domain","user") + online_chars=[]; server_name={} + if not user: return + servers=get_servers() + for server in servers: + server_name[server.k()]=server.region+" "+server.name + online=Character.query(Character.guild == ""+user.guild,Character.online == True) + for character in online: + if character.private: continue + friend={"name":character.info.name,"level":character.level,"type":character.type,"afk":gf(character,"afk",False),"owner_name":gf(character,"owner_name"),"owner":character.owner} + if server_name.get(character.server): + friend["server"]=server_name.get(character.server) + online_chars.append(friend) + jhtml(self,[{"type":"guild","chars":online_chars}]) + +def pull_friends_api(**args): + self,domain,user=gdmuld(args,"self","domain","user") + online_chars=[]; server_name={} + if not user: return + servers=get_servers() + for server in servers: + server_name[server.k()]=server.region+" "+server.name + online=Character.query(Character.friends == ""+user.k(),Character.online == True) + for character in online: + if character.private: continue + friend={"name":character.info.name,"level":character.level,"type":character.type,"afk":gf(character,"afk",False),"owner_name":gf(character,"owner_name"),"owner":character.owner} + if server_name.get(character.server): + friend["server"]=server_name.get(character.server) + online_chars.append(friend) + jhtml(self,[{"type":"friends","chars":online_chars}]) + +def pull_merchants_api(**args): + self,domain,user=gdmuld(args,"self","domain","user") + online_chars=[]; server_name={} + if not user: jhtml(self,{"failed":1,"reason":"nouser"}); return + servers=get_servers() + for server in servers: + server_name[server.k()]=server.region+" "+server.name + online=Character.query(Character.type=="merchant",Character.online == True) + for character in online: + if not gf(character,"p",0) or not character.info.p.get("stand",0): continue + #logging.info(character.info.p["stand"]) + friend={"name":character.info.name,"level":character.level,"afk":gf(character,"afk",False),"skin":character.info.skin,"cx":gf(character,"cx",{}),"stand":character.info.p["stand"],"x":character.info.x,"y":character.info.y,"map":character.info.map,"server":character.server} + friend["slots"]={} + for i in xrange(1,1+48): + if character.info.slots.get("trade%d"%i): + friend["slots"]["trade%d"%i]=simplify_item(character.info.slots["trade%d"%i]) + if server_name.get(character.server): + friend["server"]=server_name.get(character.server) + online_chars.append(friend) + jhtml(self,[{"type":"merchants","chars":online_chars}]) + +def read_mail_api(**args): + self,domain,user,mail_id=gdmuld(args,"self","domain","user","mail") + if not user: jhtml(self,{"failed":1,"reason":"nouser"}); return + user_data=get_user_data(user) + def mail_transaction(): + mail=get_by_iid("mail|%s"%mail_id) + if mail and not mail.read and gf(mail,"receiver")==user.k(): + mail.read=True + mail.put() + return True + if ndb.transaction(mail_transaction,retries=1) or 1: + old=gf(user_data,"mail",-1) + user_data.info.mail=max(0,len(Mail.query(Mail.owner==user.k(),Mail.read==False).fetch(100,keys_only=True))-1) + if old!=user_data.info.mail: user_data.put_async() + jhtml(self,[{"type":"unread","count":user_data.info.mail}]) + +def simplify_item(item): + x=item + if type(x)==type('') or type(x)==type(u''): + x=json.loads(x) + for p in ["grace","gf","list","o","oo","src"]: #"price","b","rid","giveaway" + if p in x: + del x[p] + x="%s"%json.dumps(x) + else: + for p in ["grace","gf","list","o","oo","src"]: + if p in x: + del x[p] + return x + +def pull_mail_api(**args): + self,domain,user,cursor=gdmuld(args,"self","domain","user","cursor") + data={"type":"mail","mail":[],"more":False,"cursor":None,"cursored":False}; page=40 + if not user: jhtml(self,{"failed":1,"reason":"nouser"}); return + if cursor: + mails,new_cursor,new_more=Mail.query(Mail.owner==user.k()).order(-Mail.created).fetch_page(page,start_cursor=ndb.Cursor(urlsafe=cursor)) + data["cursored"]=True + else: + mails,new_cursor,new_more=Mail.query(Mail.owner==user.k()).order(-Mail.created).fetch_page(page) + for mail in mails: + mail_data={"fro":mail.fro,"to":mail.to,"message":mail.info.message,"subject":mail.info.subject,"sent":"%s"%mail.created,"id":mail.k()} + if mail.item: + mail_data["item"]=simplify_item(mail.info.item) + mail_data["taken"]=mail.taken + data["mail"].append(mail_data) + if new_cursor: data["cursor"]=new_cursor.urlsafe() + if new_more: data["more"]=True + jhtml(self,[data]) + +def take_item_from_mail_api(**args): + self,domain,server,owner,mid=gdmuld(args,"self","domain","server","owner","mid") + user=get_by_iid("user|%s"%owner); + mail=get_by_iid("mail|%s"%mid) + if not server: return jhtml(self,{"failed":1,"reason":"noserver"}) + if not user: return jhtml(self,{"failed":1,"reason":"nouser"}) + if not mail: return jhtml(self,{"failed":1,"reason":"nomail"}) + def retrieve_item_transaction(): + m=get_by_iid(mail.k('i')) + if not m.item or m.taken: return False + m.taken=True + m.put() + return m.info.item + result=ndb.transaction(retrieve_item_transaction,xg=True,retries=1) + if result: + jhtml(self,{"success":1,"item":result}) + else: + jhtml(self,{"failed":1,"reason":"failed"}) + +def delete_mail_api(**args): + self,domain,user,mid=gdmuld(args,"self","domain","user","mid") + mail=get_by_iid("mail|%s"%mid) + if not user or not mail or not user.k() in mail.owner: return jhtmle(self,"Can't delete.") + mail.key.delete() + jhtmlm(self,"Mail deleted.") + +def send_mail_api(**args): + self,domain,fro,to,server,subject,message,rid,item,type=gdmuld(args,"self","domain","fro","to","server","subject","message","rid","item","type") + if fro: frop=get_character(fro); + top=get_character(to) + if fro and not frop or not top: return jhtml(self,{"failed":1,"reason":"nocharacter","return":True}) + if fro: user1=get_by_iid_async("user|%s"%frop.owner); + user2=get_by_iid("user|%s"%top.owner) + ud2=get_user_data(user2,async=True); c2=Mail.query(Mail.owner==user2.k(),Mail.read==False).fetch_async(98,keys_only=True) + if fro: user1=user1.get_result() + if not server: return jhtml(self,{"failed":1,"reason":"noserver"}) + if fro and not user1 or not user2: return jhtml(self,{"failed":1,"reason":"nouser","return":True}) + try: + subject=unicodedata.normalize('NFD',subject).encode('ascii','ignore') + if len(subject)>72: subject=subject[:72]+".." + message=unicodedata.normalize('NFD',message).encode('ascii','ignore')[:1000] + if len(message)>1000: message=message[:1000]+"[truncated-too-long]" + except: + log_trace_i() + return jhtml(self,{"failed":1,"reason":"englishification_failed","return":True}) + def send_mail_transaction(): + mail=ndb.Key(Mail,rid).get() + if mail: return mail + if type=="system": + mail=Mail(fro="mainframe",to=to,type="system",owner=[user2.k()],info=cGG(message=message,subject=subject,sender="!",receiver=user2.k()),key=ndb.Key(Mail,rid)) + else: + mail=Mail(fro=fro,to=to,type="mail",owner=[user1.k(),user2.k()],info=cGG(message=message,subject=subject,sender=user1.k(),receiver=user2.k()),key=ndb.Key(Mail,rid)) + if item: + mail.item=True + mail.info.item=item + mail.taken=False + mail.put() + return mail + result=ndb.transaction(send_mail_transaction,xg=True,retries=24) + if result: + ud2=ud2.get_result(); ud2=process_user_data(user2,ud2); ud2.info.mail=len(c2.get_result())+1; ud2.put_async() + jhtml(self,{"success":1}) + else: + jhtml(self,{"failed":1,"reason":"unknown"}) + +def pull_messages_api(**args): + self,domain,user,type,cursor=gdmuld(args,"self","domain","user","type","cursor") + if not type: type="all" + data={"type":"messages","messages":[],"more":False,"cursor":None,"cursored":False,"mtype":type}; page=200 + if not user: jhtml(self,{"failed":1,"reason":"nouser"}); return + query=Message.query() + if type in ["private","party"]: + query=query.filter(Message.owner==user.k()) + query=query.filter(Message.type==type) + elif type=="all": + query=query.filter(Message.owner==user.k()) + else: + query=query.filter(Message.owner=="~%s"%type) + query=query.order(-Message.created) + if cursor: + messages,new_cursor,new_more=query.fetch_page(page,start_cursor=ndb.Cursor(urlsafe=cursor)) + data["cursored"]=True + else: + messages,new_cursor,new_more=query.fetch_page(page) + for message in messages: + m_data={"fro":message.fro,"to":message.to,"message":message.info.message,"type":message.type,"id":message.k(),"server":message.server,"date":"%s"%message.created.strftime('%Y-%m-%dT%H:%M:%SZ')} + data["messages"].append(m_data) + #logging.info(m_data) + if new_cursor: data["cursor"]=new_cursor.urlsafe() + if new_more: data["more"]=True + jhtml(self,[data]) + +def log_chat_api(**args): + self,domain,server,fro,to,type,message,author=gdmuld(args,"self","domain","server","fro","to","type","message","author") + if not server: return jhtml(self,{"failed":1,"reason":"noserver"}) + + if type=="server": + Message(owner="~%s"%server.k(),author=author,fro=fro,type="server",info=cGG(message=message),server=server.k()).put() + Message(owner="~global",author=author,fro=fro,type="server",info=cGG(message=message),server=server.k()).put() + elif type=="private": + Message(owner=to[0],author=author,fro=fro,to=[to[1]],type=type,info=cGG(message=message),server=server.k()).put() + if to[0]!=author: + Message(owner=author,author=author,fro=fro,to=[to[1]],type=type,info=cGG(message=message),server=server.k()).put() + elif type=="xprivate": + to[0]=get_owner(to[1]) + if not to[0]: return jhtml(self,{"failed":1,"reason":"nocharacter"}) + to[0]="%s"%to[0].k(); character=get_character(to[1]) + if character.server: server_eval_safe(get_by_iid("server|%s"%character.server),"get_player(data.name).socket.emit('pm',{owner:data.owner,message:data.message,id:data.owner,xserver:true});",data={"owner":fro,"name":to[1],"message":message}) + Message(owner=to[0],author=author,fro=fro,to=[to[1]],type="private",info=cGG(message=message),server=server.k()).put() + if to[0]!=author: + Message(owner=author,author=author,fro=fro,to=[to[1]],type="private",info=cGG(message=message),server=server.k()).put() + else: + for on in to: + owner,names=on + Message(owner=owner,author=author,fro=fro,to=names,type=type,info=cGG(message=message),server=server.k()).put() + + jhtml(self,{"success":1}) + +def set_friends_api(**args): + self,domain,user1,user2,server=gdmuld(args,"self","domain","user1","user2","server") + user1=get_by_iid_async("user|%s"%user1); user2=get_by_iid("user|%s"%user2); user1=user1.get_result() + if not server: jhtml(self,{"failed":1,"reason":"noserver"}); return + if not user1 or not user2: jhtml(self,{"failed":1,"reason":"nouser"}); return + # if ssince(user1,"last_change",really_old)<10 or ssince(user2,"last_change",really_old)<10: jhtml(self,{"failed":1,"reason":"wait"}); return + if len(user1.friends)>=100 or len(user2.friends)>=100: jhtml(self,{"failed":1,"reason":"100limit"}); return + if user1.server or user2.server: return jhtml(self,{"failed":1,"reason":"bank"}) + def set_friends_transaction(): + e1=get_by_iid(user1.k('i')) + e2=get_by_iid(user2.k('i')) + if ""+e2.k() not in e1.friends: + e1.friends.append(""+e2.k()) + e1.put() + if ""+e1.k() not in e2.friends: + e2.friends.append(""+e1.k()) + e2.put() + return [e1,e2] + result=ndb.transaction(set_friends_transaction,xg=True,retries=0) + if result: + deferred.defer(update_characters,result[0],reason="friends",name=result[1].name) + deferred.defer(update_characters,result[1],reason="friends",name=result[0].name) + jhtml(self,{"success":1}) + else: + jhtml(self,{"failed":1,"reason":"unknown"}) + +def not_friends_api(**args): + self,domain,user1,user2,server=gdmuld(args,"self","domain","user1","user2","server") + u2=user2; user1=get_by_iid_async("user|%s"%user1); user2=get_by_iid("user|%s"%(user2 or "-")); user1=user1.get_result() + if not user2: + char=get_character(u2 or "-") + if char: user2=get_by_iid("user|%s"%char.owner) + if not server: jhtml(self,{"failed":1,"reason":"noserver"}); return + if not user1 or not user2: jhtml(self,{"failed":1,"reason":"nouser"}); return + if user1.server or user2.server: return jhtml(self,{"failed":1,"reason":"bank"}) + def unfriend_transaction(): + e1=get_by_iid(user1.k('i')) + e2=get_by_iid(user2.k('i')) + if ""+e2.k() in e1.friends: + e1.friends.remove(""+e2.k()) + e1.put() + if ""+e1.k() in e2.friends: + e2.friends.remove(""+e1.k()) + e2.put() + return [e1,e2] + result=ndb.transaction(unfriend_transaction,xg=True,retries=0) + if result: + deferred.defer(update_characters,result[0],reason="not_friends",name=result[1].name) + deferred.defer(update_characters,result[1],reason="not_friends",name=result[0].name) + jhtml(self,{"success":1}) + else: + jhtml(self,{"failed":1,"reason":"unknown"}) + +def stripe_payment_api(**args): #TODO: Patch for .server checks [10/07/18] + self,domain,user,response,usd=gdmuld(args,"self","domain","user","response","usd") + if not user: + jfunc(self,"stripe_result",["failed"]) + jhtmle(self,"User not found, credit card not charged.") + return + token=response and hasattr(response,"get") and response.get("id","") + if not token or not usd: + jfunc(self,"stripe_result",["failed"]); + jhtmle(self,"Issue with token or usd, please email hello@adventure.land") + return + usd=max(1,int(usd)) + shells=usd*80 + if usd>=500: shells=int(shells*1.24) + elif usd>=100: shells=int(shells*1.16) + elif usd>=25: shells=int(shells*1.08) + if extra_shells: + shells=int(shells*(100+extra_shells)/100.0) + try: + charge = stripe.Charge.create( + amount=int(usd*100), #Amount in cents + currency="usd", + description="%s SHELLS for %s USD"%(shells,usd), + source=token) + add_event(user,"stripe",["payments","cashflow"],self=self,info=cGG(message="STRIPE! %s spent %s USD!"%(user.name,usd),usd=usd,token=token,response=response),async=True) + def stripe_transaction(): + element=get_by_iid(user.k('i')) + element.cash+=int(shells) + element.put() + return element + result=ndb.transaction(stripe_transaction,xg=True,retries=120) + if result: + add_event(result,"shells",["cashflow"],self=self,info=cGG(message="STRIPE! %s received %s SHELLS!"%(user.name,shells),usd=usd,token=token),async=True) + jfunc(self,"stripe_result",["success",result.cash]) + jhtmls(self,"You received %s SHELLS!"%shells) + try: deferred.defer(add_cash,result.k(),int(shells),referrer=True,only_referrer=True) + except: log_trace() + try: deferred.defer(add_sales_bonus,int(usd*0.16)) + except: log_trace() + return + else: + pass + except stripe.error.CardError as e: + #The card has been declined + logging.info("Card declined %s"%e) + jfunc(self,"stripe_result",["declined"]) + jhtmle(self,"Your card has been declined.") + return + except stripe.error.StripeError as e: + logging.info("Other Error %s"%e) + jfunc(self,"stripe_result",["failed"]) + jhtmle(self,"Payment failed.") + return + except: + log_trace() + pass + jfunc(self,"stripe_result",["failed"]) + jhtmlm(self,"An unforeseen issue, please email hello@adventure.land with details. Apologies.") + +def mount_user_api(**args): #mounts the user into the bank of the server [01/09/16] + #IDEA: a seperate unlock_user_api + # time.sleep(10) - great way to test routines [17/08/18] + self,domain,user,server,id,to=gdmuld(args,"self","domain","user","server","character","to") + if not server: jhtml(self,{"failed":1,"reason":"noserver"}); return + if not user: jhtml(self,{"failed":1,"reason":"nouser"}); return + if server.gameplay=="hardcore" or server.gameplay=="test": return + if user.server: + if gf(user,"mounted_to")=="character|%s"%id: + time.sleep(6) #GTODO: #IMPORTANT: Re-fetch and check user here, without the ndb cache [09/09/16] + logging.error("Force-mount routine character|%s"%id) + else: + character=get_by_iid(user.info.mounted_to) + logging.info("%s is already in the bank"%(character and character.info.name)) + return jhtml(self,{"failed":1,"reason":"mounted","name":character and character.info.name}) + if to!="bank" and not (gf(user,"unlocked") and user.info.unlocked.get(to)): + return jhtml(self,{"failed":1,"reason":"locked"}) + def mount_user_transaction(): + element=get_by_iid(user.k('i')) + char=get_by_iid("character|%s"%id) + if not char or char.server!=server.k(): return False + if element.server and gf(element,"mounted_to")!="character|%s"%id: return False + element.server=server.k() + element.info.mounted_to="character|%s"%id + element.put() + return element + result=ndb.transaction(mount_user_transaction,xg=True,retries=12) + if result: + jhtml(self,{"done":1,"user":user_to_server(result)}) + else: + jhtml(self,{"failed":1,"reason":"already_mounted"}) + + +def start_character_api(**args): + self,domain,user,server,id,ip_a,secret,code_slot,auth=gdmuld(args,"self","domain","user","server","character","ip","secret","code_slot","auth"); guild=None; code=None; code_version=0 + blocked=None + try: ip_a=ip_a.replace("::ffff:","") + except: + log_trace() + jhtml(self,{"failed":1,"reason":"ip_ex"}); return + if not server: jhtml(self,{"failed":1,"reason":"noserver"}); return + if not user or auth.replace('"',"").split("-")[1] not in gf(user,"auths",[]): jhtml(self,{"failed":1,"reason":"nouser"}); return + if user.pid: blocked=User.query(User.pid==user.pid,User.banned==True).get_async() + user_data=get_user_data(user) + characters=get_characters(user) + stats=get_stats(characters) + character=get_by_iid("character|%s"%id) + if not character or character.owner!=user.k(): jhtml(self,{"failed":1,"reason":"nocharacter"}); return + + if gf(user,"blocked_until",really_old)>datetime.now(): + jhtml(self,{"failed":1,"reason":"Account Temporarily Blocked | Reason: %s | Remaining: %s | For appeals, explanations, email: hello@adventure.land"%(gf(user,"blocked_reason","None"),pretty_timeleft(gf(user,"blocked_until",really_old)))}); return + if user.banned: user.banned=False; user.put() + if blocked: + blocked=blocked.get_result() + if blocked: + user.info.blocked_reason="blocked_account" + user.info.blocked_until=datetime.now()+timedelta(seconds=int(40*365*24*60*60)) + user.banned=True + user.put() + send_email(domain,"kaansoral@gmail.com",html="%s %s"%(user.name,user.info.email),title="Adventure Land: Auto Block") + jhtml(self,{"failed":1,"reason":"Account Temporarily Blocked | Reason: %s | Remaining: %s | For appeals, explanations, email: hello@adventure.land"%(gf(user,"blocked_reason","None"),pretty_timeleft(gf(user,"blocked_until",really_old)))}); + return + + if code_slot: + logging.info(code_slot) + if not gf(user_data,"code_list",{}).get(sint(code_slot)): + filename=code_slot; code_slot=None + for slot in gf(user_data,"code_list",{}): + if user_data.info.code_list[slot][0]==to_filename(filename): + logging.info(slot) + code_slot=slot + if code_slot: + code_slot=int(code_slot) + code_version=user_data.info.code_list[code_slot][1] + code=ndb.Key(InfoElement,"USERCODE-%s-%s"%(user.k(),code_slot)).get_async() + if server.gameplay=="hardcore" or server.gameplay=="test": + data={"done":1,"character":character_to_info(character,user=user)} + if code: code=code.get_result() + if code: + #logging.info(code.info.code) + data["code"]=code.info.code + data["code_slot"]=code_slot + data["code_version"]=code_version + return jhtml(self,data) + if is_in_game(character): jhtml(self,{"failed":1,"reason":"ingame"}); return + if not is_sdk and ssince(gf(character,"last_start",really_old))<40: jhtml(self,{"failed":1,"reason":"wait_%d_seconds"%(40-ssince(gf(character,"last_start",really_old)))}); return + add_event(character,"start",["activity"],self=self,info=cGG(message="%s [LV.%s] logged into %s %s"%(character.info.name,character.level,server.region,server.name),server=server.k('i')),async=True) + if user.guild: guild=get_by_iid_async("guild|%s"%user.guild) + def start_character_transaction(): + element=get_by_iid(character.k('i')) + if element.server and msince(character.last_sync)<12: return False + element.server=server.k() + if not arr_arr_same(user.friends,element.friends): element.friends=user.friends + element.guild=user.guild + element.last_sync=datetime.now() + element.online=True + element.info.afk=True #"code" was getting stuck [20/05/18] + element.last_online=datetime.now() + element.info.secret=secret + element.info.last_start=datetime.now() + element.put() + return element + result=ndb.transaction(start_character_transaction,xg=True,retries=12) + if result: + data={"done":1,"character":character_to_info(result,user=user,ip=get_ip_info(ip_a),guild=guild and guild.get_result()),"stats":stats} + if code: code=code.get_result() + if code: + #logging.info(code.info.code) + data["code"]=code.info.code + data["code_slot"]=code_slot + data["code_version"]=code_version + jhtml(self,data) + if result.friends and not result.private: deferred.defer(notify_friends,result,"%s %s"%(server_regions[server.region],server.name)) + else: + jhtml(self,{"failed":1,"reason":"ingame_or_temporarily_stuck"}) + +def stop_character_api(**args): + self,domain,user,server,id,data,user_data=gdmuld(args,"self","domain","user","server","character","data","user_data"); retries=6 + if user_data: retries=50 + if not server: jhtml(self,{"failed":1,"reason":"noserver"}); return + if not user: logging.critical("No User"); jhtml(self,{"failed":1,"reason":"nouser"}); return + character=get_by_iid("character|%s"%id) + if not character or character.owner!=user.k(): jhtml(self,{"failed":1,"reason":"nocharacter","done":1}); return + if character.server!=server.k(): jhtml(self,{"failed":1,"reason":"notingame","done":1}); return + if server.gameplay=="hardcore" or server.gameplay=="test": return + + reward_referrer_logic(user) + + def stop_character_transaction(): + element=get_by_iid(character.k('i')) + element.server="" + element.online=False + element.to_backup=True + element.last_online=datetime.now() + if not arr_arr_same(user.friends,element.friends): element.friends=user.friends + if data: + update_character(element,data,user) #if observer hangs up, no need to sync data + update_pids(element,data,user) + element.put() + + if user_data: + owner=get_by_iid(user.k('i')) + for i in xrange(len(owner.info.characters)): + char=owner.info.characters[i] + if element.k()==char["id"]: owner.info.characters[i]=character_to_dict(element) + if gf(owner,"mounted_to")==element.k('i') and user_data: + logging.info("Unmounting in stop") + owner.server=""; owner.info.mounted_to="" + update_user_data(owner,user_data) + elif user_data and gf(owner,"mounted_to")!=element.k('i'): + logging.error("Has user_data at stop but mounted to: %s"%gf(owner,"mounted_to")) + elif not user_data and gf(owner,"mounted_to")==element.k('i'): + logging.error("Don't have user_data at stop: %s"%gf(owner,"mounted_to")) + owner.last_online=datetime.now() + owner.to_backup=True + owner.put() + return element + + result=ndb.transaction(stop_character_transaction,xg=True,retries=retries) + if result: + character=result + jhtml(self,{"done":1,"name":character.info.name}) + add_event(character,"stop",["activity"],self=self,info=cGG(message="%s [LV.%s] logged out of %s %s"%(character.info.name,character.level,server.region,server.name),server=server.k('i')),async=True) + else: + jhtml(self,{"failed":1,"reason":"unknown"}) + +def sync_character_api(**args): + self,domain,user,server,id,data,user_data,unmount=gdmuld(args,"self","domain","user","server","character","data","user_data","unmount"); retries=3 + if unmount: + logging.info("Unmount mode") + retries=16 + if not server: jhtml(self,{"failed":1,"reason":"noserver"}); return + if not user: jhtml(self,{"failed":1,"reason":"nouser"}); return + character=get_by_iid("character|%s"%id) + if not character or character.owner!=user.k(): jhtml(self,{"failed":1,"reason":"nocharacter"}); return + if character.server!=server.k(): jhtml(self,{"failed":1,"reason":"notingame"}); return + if server.gameplay=="hardcore" or server.gameplay=="test": return + def sync_character_transaction(): + element=get_by_iid(character.k('i')) + if element.server!=server.k(): + logging.info("stop_character_api executed after") + return False + element.last_sync=datetime.now() + element.last_online=datetime.now() + if not arr_arr_same(user.friends,element.friends): element.friends=user.friends + element.to_backup=True + update_character(element,data,user) + update_pids(element,data,user) + element.put() + + if user_data: + owner=get_by_iid(user.k('i')) + for i in xrange(len(owner.info.characters)): + char=owner.info.characters[i] + if str(element.k())==str(char["id"]): owner.info.characters[i]=character_to_dict(element) + if gf(owner,"mounted_to")==element.k('i') and user_data: + #thanks to the gf(owner,"mounted_to")==element.k('i') check, the ordering isn't crucial in normal circumstances [18/09/16] + if unmount: + logging.info("Unmounting in sync") + owner.server=""; owner.info.mounted_to="" + update_user_data(owner,user_data) + elif user_data and gf(owner,"mounted_to")!=element.k('i'): + logging.error("Has user_data at sync but mounted to: %s"%gf(owner,"mounted_to")) + elif not user_data and gf(owner,"mounted_to")==element.k('i'): + logging.error("Don't have user_data at sync: %s"%gf(owner,"mounted_to")) + owner.last_online=datetime.now() + owner.to_backup=True + owner.put() + return element + result=ndb.transaction(sync_character_transaction,xg=True,retries=retries) + if result: + jhtml(self,{"done":1}) + else: + jhtml(self,{"failed":1,"reason":"unknown"}) + +def logout_api(**args): #TODO: Probably re-visit this [10/07/18] + #time.sleep(10) + self=gdmuld(args,"self") + delete_cookie(self,"auth") + jhtmlm(self,"Logged Out") + +def reload_server_api(**args): + self,domain,keyword=gdmuld(args,"self","domain","keyword") + if keyword!=secrets.SERVER_MASTER: jhtml(self,{"failed":1}); return + geometry={} + for name in maps: + key=maps[name]["key"] + if maps[name].get("ignore"): continue + geometry[name]=get_by_iid("map|%s"%key).info.data + jhtml(self,{ + "game":{ + "version":game_version, + "achievements":achievements, + "animations":animations, + "monsters":monsters, + "sprites":sprites, + "maps":maps, + "geometry":geometry, + "npcs":npcs, + "tilesets":tilesets, + "imagesets":imagesets, + "items":items, + "sets":sets, + "craft":craft, + "titles":titles, + "tokens":tokens, + "dismantle":dismantle, + "conditions":conditions, + "cosmetics":cosmetics, + "emotions":emotions, + "projectiles":projectiles, + "classes":classes, + "dimensions":dimensions, + "levels":levels, + "positions":positions, + "skills":skills, + "games":games, + "events":events, + "images":precomputed.images, + "multipliers":multipliers, + }, + "dynamics":{ + "upgrades":upgrades, + "drops":drops, + "compounds":compounds, + "monster_gold":monster_gold, + }, + }) + +def create_server_api(**args): + self,domain,keyword,port,region,pvp,gameplay,sname=gdmuld(args,"self","domain","keyword","port","region","pvp","gameplay","name") + if keyword!=secrets.SERVER_MASTER: jhtml(self,{"failed":1}); return + actual_ip=ip=self.request.remote_addr; server_name="XX" + if is_sdk: actual_ip=ip=domain.server_ip + if domain.https_mode: ip="%s.%s.%s"%(ip_to_subdomain.get(ip,ip),live_domain[1],live_domain[2]) + lat,lon=(self.request.headers.get("X-Appengine-Citylatlong")or"0,0").split(",") + try: lat,lon=float(lat),float(lon) + except: lat,lon=0,0 + + if lat==0 and lon==0: + if region=="ASIA": lat,lon=[1.3, 103.8] + if region=="US": lat,lon=[37, -100] + if region=="EU": lat,lon=[50, 8] + + if 0: + names=copy.copy(server_names) + for e in Server.query(Server.online==True,Server.region==region): + try: names.remove(e.name) + except: pass + for e in get_servers(): #memcache soft-pierces eventual consistency + if e.region==region: + try: logging.info("Name not found: %s"%e.name) + except: pass + if len(names): server_name=names[0] + else: logging.error("ran out of server names, using XX") + + if gameplay=="hardcore": server_name="HARDCORE" + elif gameplay=="test": server_name="TEST" + elif int(port)==8091: server_name="PVP" + elif int(port)==8098: server_name="TEST" + else: + server_name=sname + + data={} + server=get_by_iid("server|%s%s"%(region,server_name)) + if server: + if server.online and msince(server.last_update)<12: return jhtml(self,{"exists":True}); + data=server.info.data + server=Server(key=ndb.Key(Server,"%s%s"%(region,server_name)),info=cGG(players=0,observers=0,total_players=0,lat=lat,lon=lon,pvp=pvp,data=data),name=server_name,region=region,version=to_str(game_version),ip=ip,actual_ip=actual_ip,port=int(port),online=True,gameplay=gameplay) + server.info.auth=randomStr(20) + server.put() + geometry={} + for name in maps: + key=maps[name]["key"] + if maps[name].get("ignore"): continue + geometry[name]=get_by_iid("map|%s"%key).info.data + jhtml(self,{ + "id":server.k(), + "auth":server.info.auth, + "name":server_name, + "data":server.info.data, + "game":{ + "version":game_version, + "achievements":achievements, + "animations":animations, + "monsters":monsters, + "sprites":sprites, + "maps":maps, + "geometry":geometry, + "npcs":npcs, + "tilesets":tilesets, + "imagesets":imagesets, + "items":items, + "sets":sets, + "craft":craft, + "titles":titles, + "tokens":tokens, + "dismantle":dismantle, + "conditions":conditions, + "cosmetics":cosmetics, + "emotions":emotions, + "projectiles":projectiles, + "classes":classes, + "dimensions":dimensions, + "levels":levels, + "positions":positions, + "skills":skills, + "games":games, + "events":events, + "images":precomputed.images, + "multipliers":multipliers, + }, + "dynamics":{ + "upgrades":upgrades, + "drops":drops, + "compounds":compounds, + "monster_gold":monster_gold, + "odds":odds, + }, + }) + + try: set_servers(server) + except: log_trace() + +def update_server_api(**args): + #dsfasdfsad=fasdfsadf + self,domain,keyword,server_id,players,observers,merchants,total_players,data=gdmuld(args,"self","domain","keyword","id","players","observers","merchants","total_players","data") + if keyword!=secrets.SERVER_MASTER: jhtml(self,{"failed":1}); return + def update_server_transaction(): + revival=False + server=get_by_iid("server|%s"%server_id) + if not server.online: + server.created=datetime.now() + revival=True + server.online=True + server.info.players=players + server.info.observers=observers + server.info.merchants=merchants + server.info.total_players=total_players + server.info.data=data + server.last_update=datetime.now() + server.put() + return server,revival + server,set_to_online=ndb.transaction(update_server_transaction,xg=True,retries=4) + if set_to_online: + send_email(gdi(),"kaansoral@gmail.com",html="%s"%server,title="REVIVED SERVER") + logging.info("Updated %s"%server) + jhtml(self,{"done":1}) + + try: set_servers() + except: log_trace() + +def stop_server_api(**args): + self,domain,keyword,server_id,data=gdmuld(args,"self","domain","keyword","id","data") + if keyword!=secrets.SERVER_MASTER: jhtml(self,{"failed":1}); return + def close_server_transaction(): + server=get_by_iid("server|%s"%server_id) + if not server: return False + server.info.data=data + server.online=False + server.put() + return server + server=ndb.transaction(close_server_transaction,xg=True,retries=12) + logging.info("Stopped %s"%server) + jhtml(self,{"done":1}) + + try: set_servers() + except: log_trace() + +def server_event_api(**args): + self,domain,keyword,server_id,event,message,color=gdmuld(args,"self","domain","keyword","id","event","message","color") + # event is "announcement" + if keyword!=secrets.SERVER_MASTER: jhtml(self,{"failed":1}); return + server=get_by_iid("server|%s"%server_id) + if event in ["server_message","notice"]: + message="%s %s: %s"%(server.region,server.name,message) + if event=="notice": + send_email(domain,"kaansoral@gmail.com",html=message,title="Adventure Land - SEVERE",text=message) + add_event(server,event,["noteworthy"],info=cGG(message=message,color=color),self=self) + if event in ["pvp","violation"]: + add_event(server,event,[],info=cGG(message="%s %s: %s"%(server.region,server.name,message),color=color),self=self) + jhtml(self,{"done":1}) + +def add_message_api(**args): + self,domain,keyword,server_id,event,message,color=gdmuld(args,"self","domain","keyword","id","event","message","color") + # event is "announcement" + if keyword!=secrets.SERVER_MASTER: jhtml(self,{"failed":1}); return + server=get_by_iid("server|%s"%server_id) + if event in ["server_message","notice"]: + message="%s %s: %s"%(server.region,server.name,message) + if event=="notice": + send_email(domain,"kaansoral@gmail.com",html=message,title="Adventure Land - SEVERE",text=message) + add_event(server,event,["noteworthy"],info=cGG(message=message,color=color),self=self) + if event in ["pvp","violation"]: + add_event(server,event,[],info=cGG(message="%s %s: %s"%(server.region,server.name,message),color=color),self=self) + jhtml(self,{"done":1}) + +def get_servers_api(**args): + self,domain=gdmuld(args,"self","domain") + server_list=get_servers(); servers=[] + for server in server_list: + servers.append({"ip":server.ip,"port":server.port,"region":server.region,"name":server.name,"pvp":server.info.pvp,"gameplay":server.gameplay}) + #return servers + jhtmls(self,servers) + +def copy_map_api(**args): + self,user,server,domain,f,t=gdmuld(args,"self","user","server","domain","f","t") + if not user or not gf(user,"map_editor"): return jhtmle(self,"Failed") + for m in maps: + if maps[m]["key"]==t: + return jhtmle(self,"You can't copy over a map in use") + copy_map(f,t) + jhtml(self,[{"type":"success","message":"Done!"},selection_info(self,user,domain)]) + +def delete_map_api(**args): + self,user,server,domain,n=gdmuld(args,"self","user","server","domain","n") + if not user or not gf(user,"map_editor"): return jhtmle(self,"Failed") + for m in maps: + if maps[m]["key"]==n: + return jhtmle(self,"You can't delete a map in use") + map=get_by_iid("map|%s"%n) + if map: + backup_item(map) + map.key.delete() + jhtml(self,[{"type":"success","message":"Done!"},selection_info(self,user,domain)]) + +def test_api(**args): + asdfdfsa=dsfafsd + self,user,server,domain=gdmuld(args,"self","user","server","domain") + logging.info("test") + jfunc(self,"alert",["lol"]) + jhtmls(self,"test") + +def simplify_args_for_logging(args): + try: + new_args={} + for id in args: + if id=="data" and args[id]: + new_args["data"]={"redacted":True} + elif id=="user_data" and args[id]: + new_args["user_data"]={"redacted":True} + else: + new_args[id]=args[id] + return new_args + except: + return args + +class APICall(webapp.RequestHandler): + @ndb.toplevel + def post(self): + domain=gdi(self) + server=get_server(self,domain) + args,method=gdmul(self,"arguments","method") + if security_threat(self,domain): return + user=get_user(self,domain,api_override=(server and method and method!="start_character")) # only "start_character" has an auth check, the rest doesn't re-check user auths #IMPORTANT! [09/08/20] + method="%s_api"%method + if args: args=json.loads(args) + if not args: args={} + logging.info("\n\nAPI Method Called: %s Arguments: %s\n"%(method,simplify_args_for_logging(args))) + #logging.info(self.request.cookies.get("auth")) + if not user and method not in ["log_error_api","signup_or_login_api","load_article_api","get_server_api","test_api","create_server_api","stop_server_api","update_server_api","reload_server_api","set_friends_api","not_friends_api","password_reminder_api","server_event_api","reset_password_api","ban_user_api","send_mail_api","log_chat_api","take_item_from_mail_api","broadcast_api"]: + if self.request.get("server_auth"): jhtml(self,{"failed":1,"reason":"nouser"}); return + jhtml(self,[{"type":"func","func":"add_log","args":["Not logged in."]}]); return + function=globals().get(method) + args["domain"]=domain + args["user"]=user + args["server"]=server + args["self"]=self + if user and not server and gf(user,"blocked_until",really_old)>datetime.now() and method not in ["logout_api_X"]: return jhtml(self,[{"type":"func","func":"add_log","args":["Blocked"]}]) + if function: function(**args) + else: + if args.get("dataType")=="json": jhtml(self,[{"type":"ui_log","message":"Invalid method"}]) + else: logging.error("no function") + safe_commit(user); safe_commit(server); domain_routine(domain) + +application = webapp.WSGIApplication([ + ('/api.*',APICall), + ],debug=is_sdk) \ No newline at end of file diff --git a/app.yaml b/app.yaml new file mode 100644 index 0000000..43b7b16 --- /dev/null +++ b/app.yaml @@ -0,0 +1,62 @@ +application: twodimensionalgame +version: 3 #2-new UI | 3-new font dynamics +runtime: python27 +threadsafe: true +api_version: 1 +builtins: +#- appstats: on +#- remote_api: on +- deferred: on +inbound_services: +- warmup + +#F2/F4: same warmup handler performance [14/10/14] +instance_class: F2 +automatic_scaling: + min_idle_instances: 0 + max_idle_instances: 1 + min_pending_latency: 6000ms + max_pending_latency: 12000ms + +default_expiration: "4d" + +handlers: +#- url: /robots.txt +# script: stuff.application +- url: /favicon\.ico + static_files: images/favicon.ico + upload: favicon\.ico +- url: /css + static_dir: css +- url: /images + static_dir: images +- url: /img/ + static_dir: images/screenshots +- url: /sounds + static_dir: sounds +- url: /js + static_dir: js +- url: /api.* + script: api.application +- url: /admin.* + script: admin.application + login: admin +- url: /cr/.* + script: crons.application + login: admin +- url: /tasks.* + script: tasks.application +- url: /test.* + script: tests.application +- url: .* + script: main.application + +libraries: +- name: jinja2 + version: latest +- name: markupsafe + version: latest +- name: lxml + version: latest +- name: ssl + version: latest \ No newline at end of file diff --git a/config.py b/config.py new file mode 100644 index 0000000..672afa0 --- /dev/null +++ b/config.py @@ -0,0 +1,250 @@ +# This Python file uses the following encoding: utf-8 +from __future__ import with_statement +import os,logging,cgi +if os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'): + try: + from google.appengine.tools.dev_appserver import HardenedModulesHook + HardenedModulesHook._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt'] + except: pass +import sys,json,random,time,re,math,copy,base64,cPickle,jinja2,types,urllib,operator,pickle,unicodedata +import gc as gbc +from lxml import etree as lxmletree +import datetime as rdatetime +import time as rtime +from datetime import datetime,timedelta,date +from google.appengine.api.users import is_current_user_admin +from google.appengine.ext.webapp import blobstore_handlers # template,util, +from google.appengine.api import memcache,urlfetch,urlfetch_errors,mail,taskqueue,images,files,namespace_manager,search,modules,logservice +from google.appengine.ext import webapp,ndb,blobstore,deferred +from google.appengine.runtime import DeadlineExceededError +from google.appengine.runtime.apiproxy_errors import DeadlineExceededError as DeadlineExceededError2 +from google.appengine.datastore.datastore_query import Cursor + +class mj2u(jinja2.Undefined): + def __str__(self): 0 and logging.info("Non existing variable"); return "" + def __call__(self,*a,**d): 0 and logging.info("Non existing variables non existing call with a %s d %s"%(a,d)); return "";mj2u() + def __getattr__(self,*d,**f): + return mj2u() +j2_loader=jinja2.FileSystemLoader(os.path.dirname(__file__)) +class GG(): pass + +import secrets + +from libraries.country_to_latlon import c_to_ll +from libraries import stripe +from libraries import amazon_ses +#from libraries import get_image_size + +if os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'): + is_sdk=True; is_production=is_appengine=False + stripe.verify_ssl_certs = False + stripe.api_key=secrets.stripe_test_api_key + stripe_pkey=secrets.stripe_test_pkey +else: + is_sdk=False; is_production=is_appengine=True + stripe.api_key=secrets.stripe_pkey #secret-key + stripe_pkey=secrets.stripe_api_key #publishable-key +steam_web_apikey=secrets.steam_web_apikey #for domain adventure.land: https://partner.steamgames.com/doc/webapi_overview/auth#create_publisher_key +steam_publisher_web_apikey=secrets.steam_publisher_web_apikey #from: https://partner.steamgames.com/pub/group/48241/61965/ + +from design.animations import * +from design.achievements import * +from design.game import * +from design.sprites import * +from design.dimensions import * +from design.monsters import * +from design.maps import * +from design.npcs import * +from design.items import * +from design.classes import * +from design.levels import * +from design.upgrades import * +from design.drops import * +from design.skills import * +from design.events import * +from design.recipes import * +from design.titles import * +from design.tokens import * +from design.games import * +from design.conditions import * +from design.cosmetics import * +from design.emotions import * +from design.projectiles import * +from design.multipliers import * +import design.precomputed as precomputed +from docs.directory import * +from utility.gallery import * + +if is_production: + #maps["desertland"]["key"]="jayson_desertland_copy" + pass + +game_version=779 +SALES=4+5+388+5101+125/20 #donation+manual+macos+steam+sales +update_notes=[ + "Halloween Event!", + "Last Update [October 13th]", + "Open sourcing the game this weekend!", +] +ip_to_subdomain={ #IMPORTANT: SPECIAL PAGE RULES ARE NEEDED: https://dash.cloudflare.com/b6f5a13bded5fdd273e4a1cd3777162d/adventure.land/page-rules - uss1 / eus1 was best + "35.187.255.184":"asia1", + "35.246.244.105":"eu1", + "35.228.96.241":"eu2", + "35.234.72.136":"eupvp", + "35.184.37.35":"us1", + "34.67.188.57":"us2", + "34.75.5.124":"us3", + "34.67.187.11":"uspvp", + "195.201.181.245":"eud1", + "158.69.23.127":"usd1", +} +HTTPS_MODE=True #IMPORTANT: converts server IP's to subdomain urls at create_server_api [17/11/18] +always_amazon_ses=True +SCREENSHOT_MODE=is_sdk and False +game_name="Adventure Land" +appengine_id="twodimensionalgame" +live_domain=["www","adventure","land"] +sdk_domain=["www","thegame","com"] +SDK_UPLOAD_PASSWORD=ELEMENT_PASSWORD=secrets.sdk_password + +def gdi(self=None): + domain=GG() + if is_sdk: + domain.base_url=self and "http://%s"%self.request.headers.get("Host") or "http://%s.%s"%(sdk_domain[1],sdk_domain[2]) + domain.pref_url=self and "http://%s"%self.request.headers.get("Host") or "http://%s.%s"%(sdk_domain[1],sdk_domain[2]) + domain.server_ip="192.168.1.125" + domain.stripe_pkey=stripe_pkey + domain.stripe_enabled=False + domain.https_mode=False + domain.domain=self and ["www",self.request.headers.get("Host").split(".")[0],self.request.headers.get("Host").split(".")[1]] or sdk_domain + else: + protocol="http" + if self and "https" in (self.request.headers.get("Cf-Visitor") or ""): protocol="https" + domain.base_url="%s://%s.%s"%(protocol,live_domain[1],live_domain[2]) + domain.pref_url="https://%s.%s"%(live_domain[1],live_domain[2]) + domain.stripe_pkey=stripe_pkey + domain.stripe_enabled=False + domain.https_mode=HTTPS_MODE + domain.domain=live_domain + domain.imagesets=imagesets #for caching [12/07/20] + domain.sales=SALES + domain.ip_to_subdomain=ip_to_subdomain + domain.https=False + domain.secure_base_url=domain.base_url.replace("http://","https://") + domain.discord_url="https://discord.gg/44yUVeU" + domain.is_sdk=is_sdk + domain.io_version="4.2.0" #upgraded from 1.4.5 now [18/03/17] upgraded from 1.7.2 now [31/12/17] upgraded from 2.1.0 now [20/06/19] 2.3.0 [28/06/20] 4.0.0 [18/03/21] + domain.cm_version="5.65.1" + domain.jquery_version="3.2.0" #for some reason the previous version was 2.2.4 instead of 3.1.0 [10/04/17] + domain.howler_version="2.0.13" + domain.pixi_version="4.8.2-roundpixels" # Re-visit #PIXI's at updates + TOWN/Server change to test - 4.0.3-dev has weird click + # LTS: "4.8.2-roundpixels" + # 4.8.9-custom has an artifact appearing on t2bow + domain.pixi_fversion="" + domain.pixi_display_version="v4" + domain.pixi_layers_version="0.1.7.2" + domain.pixi_lights_version="2.0.3" + domain.pixi_filters_version="3.1.1" and "2.6.0c0" + domain.interact_version="1.2.6" + domain.gcs_bucket="2dimages" + domain.v=game_version + domain.cash=True + domain.name=game_name + domain.title=domain.name + domain.gender_types=gender_types + domain.character_types=character_types + domain.screenshot=SCREENSHOT_MODE + domain.recording_mode=False + domain.music_on=False + domain.sfx_on=False + domain.perfect_pixels=True + domain.fast_mode=True + domain.engine_mode="" + domain.d_lines=True + domain.sd_lines=True + domain.newcomer_ui=False + domain.new_attacks=True + domain.no_html=False + domain.is_bot=False + domain.is_cli=False + domain.no_graphics=False + domain.border_mode=False + domain.purchase_mode=True + domain.tutorial=True + domain.boost=0 + domain.access_master=secrets.ACCESS_MASTER + domain.servers=[] + domain.characters=[] + try: domain.scale=int(float(self and self.request.get("scale") or 2)) + except: domain.scale=2 + try: domain.times=int(self and self.request.get("times") or 0) + except: domain.times=0 + domain.load_character=self and self.request.get("load") or "" + domain.electron=False + domain.platform="web" + domain.update_notes=update_notes + if self: + if "Electron" in self.request.headers.get("User-Agent",""): + domain.electron=True + if self.request.get("buildid") and "win32" in self.request.get("buildid"): domain.platform="steam" + if self.request.get("buildid") and "darwin" in self.request.get("buildid"): domain.platform="mac" + if self.request.cookies.get("music")!="off": domain.music_on=True + if self.request.cookies.get("sfx")!="off": domain.sfx_on=True + domain.url=self.request.url + domain.section=self.request.get("section") + if self.request.get("test_clicks"): domain.test_clicks=True; domain.pixi_version="4.0.2" + if self.request.get("no_cache"): domain.v=100000+random.randrange(0,100000000) + if self.request.get("no_html"): domain.no_html=True + if self.request.get("no_html")=="bot": domain.no_html="bot" + if self.request.get("is_bot"): domain.is_bot=True + if self.request.get("is_cli"): domain.is_cli=True + if self.request.get("recording_mode"): domain.recording_mode=True; domain.boost=20; domain.sfx_on=False; domain.music_on=False + if self.request.get("no_graphics") or domain.no_html: + domain.no_graphics=True; + domain.pixi_version="fake" #NOGTODO is the hashtag + domain.pixi_fversion="?v=%s"%game_version + if self.request.get("borders") or self.request.get("border_mode"): domain.border_mode=True + if self.request.cookies.get("perfect_pixels_off") and not SCREENSHOT_MODE: + domain.perfect_pixels=False + if self.request.cookies.get("d_lines_off"): + domain.d_lines=False + if self.request.cookies.get("no_tutorial"): + domain.tutorial=False + if self.request.cookies.get("no_fast_mode"): + domain.fast_mode=False + if self.request.get("engine") or self.request.cookies.get("engine_mode"): + domain.engine_mode=self.request.get("engine") or self.request.cookies.get("engine_mode") + if self.request.cookies.get("sd_lines_off"): + domain.sd_lines=False + if self.request.cookies.get("pro_mode"): + domain.newcomer_ui=False + if self.request.cookies.get("no_weapons"): + domain.new_attacks=False + if self.request.cookies.get("manual_reload"): + domain.auto_reload="off" + else: + domain.auto_reload="auto" + if self.request.scheme=="https" or self.request.headers.get("Cf-Visitor") and self.request.headers.get("Cf-Visitor").find("https")!=-1: + domain.https=True + return domain +secure_cookies=False #not is_sdk + +if SCREENSHOT_MODE: + update_notes=[ + "Last Update [Nth of Month]", + "Update notes appear here", + "Usually weekly or daily updates" + ] + +j2=jinja2.Environment(loader=j2_loader,undefined=mj2u,autoescape=True,auto_reload=is_sdk,cache_size=-1) + +def jrf(f): #jinja_register_filter + j2.filters[f.__name__]=f + return f + +def jrg(f): #jinja_register_global [21/12/14] + j2.globals[f.__name__]=f + return f + +really_old=datetime(1970,1,1) +distant_future=datetime(2048,1,1) \ No newline at end of file diff --git a/cron.yaml b/cron.yaml new file mode 100644 index 0000000..1afbe36 --- /dev/null +++ b/cron.yaml @@ -0,0 +1,13 @@ +cron: +- description: check_servers + url: /cr/check_servers + schedule: every 1 minutes +- description: unstuck_players + url: /cr/unstuck + schedule: every 5 minutes +- description: hourly + url: /cr/hourly + schedule: every 60 minutes +- description: backups + url: /cr/all/backups + schedule: every 23 hours \ No newline at end of file diff --git a/crons.py b/crons.py new file mode 100644 index 0000000..4a4bbe6 --- /dev/null +++ b/crons.py @@ -0,0 +1,314 @@ +# This Python file uses the following encoding: utf-8 +from config import * +from functions import * + +def send_halloween_email(user): + domain=gdi() + send_email(domain,user.info.email,html=shtml("htmls/contents/announcement_email.html",purpose="halloween",domain=domain,user=user),title=u"🎃 Hey Adventurer! Check out our new Halloween Zone! 🎃",text="Adventure Land has a new Halloween Zone!") + +def send_xmas_email(user): + try: + domain=gdi() + send_email(domain,user.info.email,html=shtml("htmls/contents/announcement_email.html",purpose="xmas",domain=domain,user=user),title=u"🎄 Hey Adventurer! Winterland is Here. Xmas Drops are Everywhere! +Steam Greenlight 🎄",text="Adventure Land's Xmas Event is Here'!") + except: + logging.info("Email failed: %s"%user.k()) + log_trace() + +def send_xmas2_email(user): + try: + domain=gdi() + send_email(domain,user.info.email,html=shtml("htmls/contents/announcement_email.html",purpose="xmas2",domain=domain,user=user),title=u"🎄 Hey Adventurers! Our Xmas Event is Live! 🎄",text="Adventure Land's Xmas Event is Here'!") + except: + logging.info("Email failed: %s"%user.k()) + log_trace() + +def send_xmas3_email(user): + try: + domain=gdi() + send_email(domain,user.info.email,html=shtml("htmls/contents/announcement_email.html",purpose="xmas3",domain=domain,user=user),title=u"🎄 Hey Adventurers! Our Holiday Season Event is Here and We have Snowballs Now! ☃️",text="Adventure Land's Holiday Season Event is Here'!") + except: + logging.info("Email failed: %s"%user.k()) + log_trace() + +def send_cvalentines_email(user): + try: + domain=gdi() + send_email(domain,user.info.email,html=shtml("htmls/contents/announcement_email.html",purpose="cvalentines",domain=domain,user=user),title=u"⛩️ Chinese New Year + Valentine's Day Events! Grand Prize: Dragon Armor 💘",text="Adventure Land's Chinese New Year Event is Here'!") + except: + logging.info("Email failed: %s"%user.k()) + log_trace() + +def send_easter_email(user): + try: + domain=gdi() + send_email(domain,user.info.email,html=shtml("htmls/contents/announcement_email.html",purpose="easter",domain=domain,user=user),title=u"🐰 🥚 Easter Event on Adventure Land! +Map Editor 🗺️ 🐰",text="Adventure Land's Easter Event is Here'!") + except: + logging.info("Email failed: %s"%user.k()) + log_trace() + +def send_easter_email2(user): + try: + domain=gdi() + send_email(domain,user.info.email,html=shtml("htmls/contents/announcement_email.html",purpose="easter2",domain=domain,user=user),title=u"🐰 Adventure Land's Easter Event is Here! 🥚",text="Adventure Land's Easter Event is Here!") + except: + logging.info("Email failed: %s"%user.k()) + log_trace() + +def send_anniversary_email(user): + try: + domain=gdi() + send_email(domain,user.info.email,html=shtml("htmls/contents/announcement_email.html",purpose="anniversary",domain=domain,user=user),title=u"🎂 🎁 Anniversary Event on Adventure Land! 🎉 🍰",text="Adventure Land's Anniversary Event is Here'!") + except: + logging.info("Email failed: %s"%user.k()) + log_trace() + +def send_halloween_email2(user): + try: + domain=gdi() + send_email(domain,user.info.email,html=shtml("htmls/contents/announcement_email.html",purpose="halloween2",domain=domain,user=user),title=u"New Map: Spooky Town on Adventure Land, Mummies, Franky, Ghosts, New Drops! Test 🎃 😱",text="Adventure Land has a new map!") + except: + logging.info("Email failed: %s"%user.k()) + log_trace() + +def send_halloween_email3(user): + try: + domain=gdi() + send_email(domain,user.info.email,html=shtml("htmls/contents/announcement_email.html",purpose="halloween3",domain=domain,user=user),title=u"Halloween Event on Adventure Land! New Cooperative Boss: Franky 🎃",text="Adventure Land has a new boss!") + except: + logging.info("Email failed: %s"%user.k()) + log_trace() + + +def all_user_cron(num): + rpcs=[] + for user in User.query(User.random_number==num): + #logging.info(user) + if len(user.info.characters): + user.name=user.info.characters[0]["name"] + else: + user.name="#%s"%user.info.signupth + rpcs.append(user.put_async()) + if len(rpcs)>=50: #SDK-old + for rpc in rpcs: rpc.wait() + rpcs=[] + for rpc in rpcs: rpc.wait() #SDK-old + +def all_user_cron(num): #<datetime.now(): + user.banned=True + user.put() + +def all_character_cron(num): + for character in Character.query(Character.random_number==num): + if gf(character,"map") in ["main","batcave"]: + character.info.map="main" + character.info.x=0 + character.info.y=0 + character.put() + +def all_character_cron(num): + for character in Character.query(Character.random_number==num): + element=character; change=False + if gf(element,"p") and element.info.p.get("acx") and element.info.p["acx"].get("wing102"): + del element.info.p["acx"]["wing102"] + change=True + for slot in gf(element,"slots",{}): + item=element.info.slots[slot] + if item and item["name"].endswith("booster") and not item.get("expires"): + element.info.slots[slot]=None + #item["level"]=max(0,int(item["level"]/2)-1) + change=True + for i in xrange(len(gf(element,"items",[]))): + item=gf(element,"items",[])[i] + if item and item["name"].endswith("booster") and not item.get("expires"): + gf(element,"items",[])[i]=None + #item["level"]=max(0,int(item["level"]/2)-1) + change=True + if change: element.put() + +def all_character_cron(num): + for character in Character.query(Character.random_number==num): + element=character; change=False + for slot in gf(element,"slots",{}): + item=element.info.slots[slot] + if item and not item.get("oo"): + item["oo"]=element.info.name + change=True + for i in xrange(len(gf(element,"items",[]))): + item=gf(element,"items",[])[i] + if item and not item.get("oo"): + item["oo"]=element.info.name + change=True + if change: element.put() + +def all_cbackup_cron(num): + rpcs=[] + for character in Character.query(Character.random_number==num,Character.to_backup==True): + def backup_transaction(): + element=get_by_iid(character.k('i')) + element.to_backup=False + element.put() + rpcs.append(backup_item(character,async=True)) + rpcs.append(ndb.transaction_async(backup_transaction,retries=0)) + for rpc in rpcs: rpc.wait() + +def all_process_cron(num): + rpcs=[] + for character in Character.query(Character.random_number==num,Character.to_backup==True): + def backup_transaction(): + element=get_by_iid(character.k('i')) + element.to_backup=False + element.put() + rpcs.append(backup_item(character,async=True)) + rpcs.append(ndb.transaction_async(backup_transaction,retries=0)) + for rpc in rpcs: rpc.wait() + +def all_ubackup_cron(num): + rpcs=[] + for user in User.query(User.random_number==num,User.to_backup==True): + def backup_transaction(): + element=get_by_iid(user.k('i')) + element.to_backup=False + element.put() + rpcs.append(backup_item(user,async=True)) + rpcs.append(ndb.transaction_async(backup_transaction,retries=0)) + for rpc in rpcs: rpc.wait() + +class AllCron(webapp.RequestHandler): + @ndb.toplevel + def get(self,mname): + if mname=="user": + for n in range(1,101): + deferred.defer(all_user_cron,n,_queue="important") + if mname=="mail": + for n in range(1,101): + deferred.defer(all_mail_cron,n,_queue="important") + if mname=="character": + for n in range(1,101): + deferred.defer(all_character_cron,n,_queue="important") + if mname=="backups": + #originally, backups were on-access, but they need to be all at the same time, so a reversal restores the ~whole state of the game [19/11/18] + for n in range(1,101): + deferred.defer(all_ubackup_cron,n,_queue="important") + deferred.defer(all_cbackup_cron,n,_queue="important") + if mname=="process_backups": + for n in range(1,101): + deferred.defer(all_process_cron,n,_queue="important") + def post(self,mname): self.get(mname) + +class CheckServers(webapp.RequestHandler): + @ndb.toplevel + def get(self): check_servers() + def post(self): self.get() + +class UnstuckPlayers(webapp.RequestHandler): + @ndb.toplevel + def get(self): + servers=get_servers() + for server in servers: + if msince(server.created)>10: #no widespread network issue + characters=Character.query(Character.online==True, Character.server == server.k(), Character.last_sync < datetime.now()-timedelta(minutes=30)).fetch() + for character in characters: + m=msince(character.last_sync) + character.online=False + character.server="" + character.put() + send_email(gdi(),"kaansoral@gmail.com",html="Stuck for %s minutes"%m,title="UNSTUCK %s from %s"%(character.name,server.k())) + + def post(self): self.get() + +class Hourly(webapp.RequestHandler): + @ndb.toplevel + def get(self): + deferred.defer(verify_steam_installs) + return + if random.randrange(0,20)==2: + user=get_by_iid("user|%s"%get_character("Wizard").owner) + if random.randrange(0,20)==2: + add_cash(user,100*random.randrange(1,50)) + else: + add_cash(user,200) + if random.randrange(0,20)==2: + user=get_by_iid("user|%s"%get_character("Oragon").owner) + if random.randrange(0,20)==2: + add_cash(user,100*random.randrange(1,50)) + else: + add_cash(user,200) + #user=get_by_iid("user|%s"%get_character("Trexnamedtod").owner) + #add_cash(user,25) + #user=get_by_iid("user|%s"%get_character("Emerald").owner) + #add_cash(user,5) + def post(self): self.get() + +application = webapp.WSGIApplication([ + ('/cr/check_servers', CheckServers), + ('/cr/hourly', Hourly), + ('/cr/unstuck', UnstuckPlayers), + ('/cr/all/([^/]*)/?', AllCron), + ],debug=is_sdk) \ No newline at end of file diff --git a/css/.DS_Store b/css/.DS_Store new file mode 100644 index 0000000..2244668 Binary files /dev/null and b/css/.DS_Store differ diff --git a/css/common.css b/css/common.css new file mode 100644 index 0000000..b6ab18c --- /dev/null +++ b/css/common.css @@ -0,0 +1,176 @@ +@font-face { + font-family: pixel; + /*src: url(/css/fonts/pixel_unicode/Pixel-UniCode.ttf);*/ + src: url(/css/fonts/m5x7.ttf); + font-weight: normal; + font-style: normal; +} +.disableclicks{ + pointer-events: none; +} +.gamebutton,.enableclicks,.slimbutton,.tinybutton{ + pointer-events: auto; +} +.noselect,.button,.whiteheader,.textbutton,.gamebutton,.tinybutton{ + -webkit-touch-callout: none; + -webkit-user-select: none; + -khtml-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} +.yesselect,.label,.klabel,pre{ + -webkit-touch-callout: text; + -webkit-user-select: text; + -khtml-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; +} +.shstring { color: green; } +.shnumber { color: darkorange; } +.shboolean { color: blue; } +.shnull { color: magenta; } +.shkey { color: red; } + +.shstring { color: #CCC11E; } +.shnumber { color: #44C2C7; } +.shboolean { color: #CD6C2A; } +.shnull { color: #44C2C7; } +.shkey { color: #DC4D7B; } + +/*.shcontainer {color : #DC4D7B;}*/ + +.borderbox{ + box-sizing: border-box; +} +.vtop{ + vertical-align:top; +} +.hidden, .showwithmodals{ + display:none; +} +.bshadow{ + -webkit-text-shadow: 0 0 1px #3B3B3B; + -moz-text-shadow: 0 0 1px #3B3B3B; + text-shadow: 0 0 1px #3B3B3B; +} +.bshadow2{ + -webkit-text-shadow: 0 0 1px #646464; + -moz-text-shadow: 0 0 1px #646464; + text-shadow: 0 0 1px #646464; +} +.fright{ + float: right; +} +.gray{ + color: gray; +} +.gyellow{ + color: #A19D50; +} +.ggreen{ + color: #6BA75E; +} +.gold{ + color: gold; +} +.inline-block{ + display: inline-block; +} +.block{ + display: block; +} +.mb2{margin-bottom: 2px;} +.mb4{margin-bottom: 4px;} +.mb5{margin-bottom: 5px;} +.mb10{margin-bottom: 10px;} +.mb15{margin-bottom: 15px;} +.px1{width: 1px;display: inline-block;} +.px15{width: 1.5px;display: inline-block;} +.px2{width: 2px;display: inline-block;} +.px4{width: 4px;display: inline-block;} +.mb10{margin-bottom: 10px;} +.ml5{margin-left: 5px;} +.mr5{margin-right: 5px;} +.ml2{margin-left: 2px;} +.mt4{margin-top: 4px;} +.mt5{margin-top: 5px;} +.mt10{margin-top: 10px;} +.mt15{margin-top: 15px;} +.brd2{border: 2px solid gray;} +.brd5{border: 5px solid gray;} +.hspace4+.hspace5{ + margin-left: 4px; +} + +.cancela,.cancela:link,.cancela:visited,.cancela:hover,.cancela:focus,.cancela:active{ + color: inherit; + text-decoration: none; +} +.clickable,.button,.clickable{ + cursor:pointer; +} +.gamebutton[onclick],.blockbutton[onclick],.slimbutton[onclick],.textbutton[onclick],.tinybutton[onclick]{ + cursor:pointer; +} +pre, .pre{ + /* https://stackoverflow.com/questions/248011/how-do-i-wrap-text-in-a-pre-tag [19/06/18] */ + white-space: pre-wrap; /* Since CSS 2.1 */ + white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ + white-space: -pre-wrap; /* Opera 4-6 */ + white-space: -o-pre-wrap; /* Opera 7 */ + word-wrap: break-word; /* Internet Explorer 5.5+ */ + tab-size: 1.25em; +} +.moveable{cursor:move;} +.disable{cursor: default;} +.rotate2{ /*leaning left <- */ + -webkit-transform:rotate(270deg); + -moz-transform:rotate(270deg); + -o-transform:rotate(270deg); + -ms-transform:rotate(270deg); + transform:rotate(270deg); +} +.rotate4{ /*upside down*/ + -webkit-transform:rotate(180deg); + -moz-transform:rotate(180deg); + -o-transform:rotate(180deg); + -ms-transform:rotate(180deg); + transform:rotate(180deg); +} +.rotate6{ /*leaning right -> */ + -webkit-transform:rotate(90deg); + -moz-transform:rotate(90deg); + -o-transform:rotate(90deg); + -ms-transform:rotate(90deg); + transform:rotate(90deg); +} +.rotate8{ /*vertical flip*/ /*upside-down mirror*/ + -moz-transform: scale(1, -1); + -webkit-transform: scale(1, -1); + -o-transform: scale(1, -1); + -ms-transform: scale(1, -1); + transform: scale(1, -1); +} +.rotate10{ /*vertical flip*/ /*upside-down*/ + -moz-transform: rotate(90deg) scale(1, -1); + -webkit-transform: rotate(90deg) scale(1, -1); + -o-transform: rotate(90deg) scale(1, -1); + -ms-transform: rotate(90deg) scale(1, -1); + transform: rotate(90deg) scale(1, -1); +} +.rotate12{ /*horizontal flip*/ /*left-right mirror*/ + -moz-transform: scale(-1, 1); + -webkit-transform: scale(-1, 1); + -o-transform: scale(-1, 1); + -ms-transform: scale(-1, 1); + transform: scale(-1, 1); +} +.rotate14{ /*horizontal flip*/ /*left-right mirror*/ + -moz-transform: rotate(90deg) scale(-1, 1); + -webkit-transform: rotate(90deg) scale(-1, 1); + -o-transform: rotate(90deg) scale(-1, 1); + -ms-transform: rotate(90deg) scale(-1, 1); + transform: rotate(90deg) scale(-1, 1); +} \ No newline at end of file diff --git a/css/fonts/.DS_Store b/css/fonts/.DS_Store new file mode 100644 index 0000000..cae0d4c Binary files /dev/null and b/css/fonts/.DS_Store differ diff --git a/css/fonts/m5x7.atlas/100.png b/css/fonts/m5x7.atlas/100.png new file mode 100644 index 0000000..fb6c154 Binary files /dev/null and b/css/fonts/m5x7.atlas/100.png differ diff --git a/css/fonts/m5x7.atlas/101.png b/css/fonts/m5x7.atlas/101.png new file mode 100644 index 0000000..d1e2f5f Binary files /dev/null and b/css/fonts/m5x7.atlas/101.png differ diff --git a/css/fonts/m5x7.atlas/102.png b/css/fonts/m5x7.atlas/102.png new file mode 100644 index 0000000..ef25c8d Binary files /dev/null and b/css/fonts/m5x7.atlas/102.png differ diff --git a/css/fonts/m5x7.atlas/103.png b/css/fonts/m5x7.atlas/103.png new file mode 100644 index 0000000..9374115 Binary files /dev/null and b/css/fonts/m5x7.atlas/103.png differ diff --git a/css/fonts/m5x7.atlas/104.png b/css/fonts/m5x7.atlas/104.png new file mode 100644 index 0000000..746caa3 Binary files /dev/null and b/css/fonts/m5x7.atlas/104.png differ diff --git a/css/fonts/m5x7.atlas/105.png b/css/fonts/m5x7.atlas/105.png new file mode 100644 index 0000000..db8117a Binary files /dev/null and b/css/fonts/m5x7.atlas/105.png differ diff --git a/css/fonts/m5x7.atlas/106.png b/css/fonts/m5x7.atlas/106.png new file mode 100644 index 0000000..962fdf8 Binary files /dev/null and b/css/fonts/m5x7.atlas/106.png differ diff --git a/css/fonts/m5x7.atlas/107.png b/css/fonts/m5x7.atlas/107.png new file mode 100644 index 0000000..458a0a2 Binary files /dev/null and b/css/fonts/m5x7.atlas/107.png differ diff --git a/css/fonts/m5x7.atlas/108.png b/css/fonts/m5x7.atlas/108.png new file mode 100644 index 0000000..6bb152d Binary files /dev/null and b/css/fonts/m5x7.atlas/108.png differ diff --git a/css/fonts/m5x7.atlas/109.png b/css/fonts/m5x7.atlas/109.png new file mode 100644 index 0000000..52bef1b Binary files /dev/null and b/css/fonts/m5x7.atlas/109.png differ diff --git a/css/fonts/m5x7.atlas/110.png b/css/fonts/m5x7.atlas/110.png new file mode 100644 index 0000000..7e0a018 Binary files /dev/null and b/css/fonts/m5x7.atlas/110.png differ diff --git a/css/fonts/m5x7.atlas/111.png b/css/fonts/m5x7.atlas/111.png new file mode 100644 index 0000000..aa05cbd Binary files /dev/null and b/css/fonts/m5x7.atlas/111.png differ diff --git a/css/fonts/m5x7.atlas/112.png b/css/fonts/m5x7.atlas/112.png new file mode 100644 index 0000000..39b5a76 Binary files /dev/null and b/css/fonts/m5x7.atlas/112.png differ diff --git a/css/fonts/m5x7.atlas/113.png b/css/fonts/m5x7.atlas/113.png new file mode 100644 index 0000000..d7998b6 Binary files /dev/null and b/css/fonts/m5x7.atlas/113.png differ diff --git a/css/fonts/m5x7.atlas/114.png b/css/fonts/m5x7.atlas/114.png new file mode 100644 index 0000000..6fe2cf3 Binary files /dev/null and b/css/fonts/m5x7.atlas/114.png differ diff --git a/css/fonts/m5x7.atlas/115.png b/css/fonts/m5x7.atlas/115.png new file mode 100644 index 0000000..62be762 Binary files /dev/null and b/css/fonts/m5x7.atlas/115.png differ diff --git a/css/fonts/m5x7.atlas/116.png b/css/fonts/m5x7.atlas/116.png new file mode 100644 index 0000000..def8440 Binary files /dev/null and b/css/fonts/m5x7.atlas/116.png differ diff --git a/css/fonts/m5x7.atlas/117.png b/css/fonts/m5x7.atlas/117.png new file mode 100644 index 0000000..cf9510f Binary files /dev/null and b/css/fonts/m5x7.atlas/117.png differ diff --git a/css/fonts/m5x7.atlas/118.png b/css/fonts/m5x7.atlas/118.png new file mode 100644 index 0000000..744aa1f Binary files /dev/null and b/css/fonts/m5x7.atlas/118.png differ diff --git a/css/fonts/m5x7.atlas/119.png b/css/fonts/m5x7.atlas/119.png new file mode 100644 index 0000000..a69dd01 Binary files /dev/null and b/css/fonts/m5x7.atlas/119.png differ diff --git a/css/fonts/m5x7.atlas/120.png b/css/fonts/m5x7.atlas/120.png new file mode 100644 index 0000000..81ebe36 Binary files /dev/null and b/css/fonts/m5x7.atlas/120.png differ diff --git a/css/fonts/m5x7.atlas/121.png b/css/fonts/m5x7.atlas/121.png new file mode 100644 index 0000000..3cb317e Binary files /dev/null and b/css/fonts/m5x7.atlas/121.png differ diff --git a/css/fonts/m5x7.atlas/122.png b/css/fonts/m5x7.atlas/122.png new file mode 100644 index 0000000..518d740 Binary files /dev/null and b/css/fonts/m5x7.atlas/122.png differ diff --git a/css/fonts/m5x7.atlas/123.png b/css/fonts/m5x7.atlas/123.png new file mode 100644 index 0000000..83fd0fc Binary files /dev/null and b/css/fonts/m5x7.atlas/123.png differ diff --git a/css/fonts/m5x7.atlas/124.png b/css/fonts/m5x7.atlas/124.png new file mode 100644 index 0000000..d67b19d Binary files /dev/null and b/css/fonts/m5x7.atlas/124.png differ diff --git a/css/fonts/m5x7.atlas/125.png b/css/fonts/m5x7.atlas/125.png new file mode 100644 index 0000000..c68b0fa Binary files /dev/null and b/css/fonts/m5x7.atlas/125.png differ diff --git a/css/fonts/m5x7.atlas/126.png b/css/fonts/m5x7.atlas/126.png new file mode 100644 index 0000000..47fd066 Binary files /dev/null and b/css/fonts/m5x7.atlas/126.png differ diff --git a/css/fonts/m5x7.atlas/32.png b/css/fonts/m5x7.atlas/32.png new file mode 100644 index 0000000..9040868 Binary files /dev/null and b/css/fonts/m5x7.atlas/32.png differ diff --git a/css/fonts/m5x7.atlas/33.png b/css/fonts/m5x7.atlas/33.png new file mode 100644 index 0000000..5adc1f9 Binary files /dev/null and b/css/fonts/m5x7.atlas/33.png differ diff --git a/css/fonts/m5x7.atlas/34.png b/css/fonts/m5x7.atlas/34.png new file mode 100644 index 0000000..49397d0 Binary files /dev/null and b/css/fonts/m5x7.atlas/34.png differ diff --git a/css/fonts/m5x7.atlas/35.png b/css/fonts/m5x7.atlas/35.png new file mode 100644 index 0000000..a535702 Binary files /dev/null and b/css/fonts/m5x7.atlas/35.png differ diff --git a/css/fonts/m5x7.atlas/36.png b/css/fonts/m5x7.atlas/36.png new file mode 100644 index 0000000..41b5f0d Binary files /dev/null and b/css/fonts/m5x7.atlas/36.png differ diff --git a/css/fonts/m5x7.atlas/37.png b/css/fonts/m5x7.atlas/37.png new file mode 100644 index 0000000..d570547 Binary files /dev/null and b/css/fonts/m5x7.atlas/37.png differ diff --git a/css/fonts/m5x7.atlas/38.png b/css/fonts/m5x7.atlas/38.png new file mode 100644 index 0000000..20af5f7 Binary files /dev/null and b/css/fonts/m5x7.atlas/38.png differ diff --git a/css/fonts/m5x7.atlas/39.png b/css/fonts/m5x7.atlas/39.png new file mode 100644 index 0000000..5c9d00c Binary files /dev/null and b/css/fonts/m5x7.atlas/39.png differ diff --git a/css/fonts/m5x7.atlas/40.png b/css/fonts/m5x7.atlas/40.png new file mode 100644 index 0000000..0b4d12c Binary files /dev/null and b/css/fonts/m5x7.atlas/40.png differ diff --git a/css/fonts/m5x7.atlas/41.png b/css/fonts/m5x7.atlas/41.png new file mode 100644 index 0000000..ad06187 Binary files /dev/null and b/css/fonts/m5x7.atlas/41.png differ diff --git a/css/fonts/m5x7.atlas/42.png b/css/fonts/m5x7.atlas/42.png new file mode 100644 index 0000000..91f6b48 Binary files /dev/null and b/css/fonts/m5x7.atlas/42.png differ diff --git a/css/fonts/m5x7.atlas/43.png b/css/fonts/m5x7.atlas/43.png new file mode 100644 index 0000000..ff993c3 Binary files /dev/null and b/css/fonts/m5x7.atlas/43.png differ diff --git a/css/fonts/m5x7.atlas/44.png b/css/fonts/m5x7.atlas/44.png new file mode 100644 index 0000000..668dcf4 Binary files /dev/null and b/css/fonts/m5x7.atlas/44.png differ diff --git a/css/fonts/m5x7.atlas/45.png b/css/fonts/m5x7.atlas/45.png new file mode 100644 index 0000000..542334f Binary files /dev/null and b/css/fonts/m5x7.atlas/45.png differ diff --git a/css/fonts/m5x7.atlas/46.png b/css/fonts/m5x7.atlas/46.png new file mode 100644 index 0000000..0bec49c Binary files /dev/null and b/css/fonts/m5x7.atlas/46.png differ diff --git a/css/fonts/m5x7.atlas/47.png b/css/fonts/m5x7.atlas/47.png new file mode 100644 index 0000000..598422d Binary files /dev/null and b/css/fonts/m5x7.atlas/47.png differ diff --git a/css/fonts/m5x7.atlas/48.png b/css/fonts/m5x7.atlas/48.png new file mode 100644 index 0000000..8221674 Binary files /dev/null and b/css/fonts/m5x7.atlas/48.png differ diff --git a/css/fonts/m5x7.atlas/49.png b/css/fonts/m5x7.atlas/49.png new file mode 100644 index 0000000..d360710 Binary files /dev/null and b/css/fonts/m5x7.atlas/49.png differ diff --git a/css/fonts/m5x7.atlas/50.png b/css/fonts/m5x7.atlas/50.png new file mode 100644 index 0000000..19b30f4 Binary files /dev/null and b/css/fonts/m5x7.atlas/50.png differ diff --git a/css/fonts/m5x7.atlas/51.png b/css/fonts/m5x7.atlas/51.png new file mode 100644 index 0000000..66a78c1 Binary files /dev/null and b/css/fonts/m5x7.atlas/51.png differ diff --git a/css/fonts/m5x7.atlas/52.png b/css/fonts/m5x7.atlas/52.png new file mode 100644 index 0000000..7798432 Binary files /dev/null and b/css/fonts/m5x7.atlas/52.png differ diff --git a/css/fonts/m5x7.atlas/53.png b/css/fonts/m5x7.atlas/53.png new file mode 100644 index 0000000..041cbb8 Binary files /dev/null and b/css/fonts/m5x7.atlas/53.png differ diff --git a/css/fonts/m5x7.atlas/54.png b/css/fonts/m5x7.atlas/54.png new file mode 100644 index 0000000..5a074b3 Binary files /dev/null and b/css/fonts/m5x7.atlas/54.png differ diff --git a/css/fonts/m5x7.atlas/55.png b/css/fonts/m5x7.atlas/55.png new file mode 100644 index 0000000..ce79ef8 Binary files /dev/null and b/css/fonts/m5x7.atlas/55.png differ diff --git a/css/fonts/m5x7.atlas/56.png b/css/fonts/m5x7.atlas/56.png new file mode 100644 index 0000000..82402c6 Binary files /dev/null and b/css/fonts/m5x7.atlas/56.png differ diff --git a/css/fonts/m5x7.atlas/57.png b/css/fonts/m5x7.atlas/57.png new file mode 100644 index 0000000..61f7ff1 Binary files /dev/null and b/css/fonts/m5x7.atlas/57.png differ diff --git a/css/fonts/m5x7.atlas/58.png b/css/fonts/m5x7.atlas/58.png new file mode 100644 index 0000000..013bc50 Binary files /dev/null and b/css/fonts/m5x7.atlas/58.png differ diff --git a/css/fonts/m5x7.atlas/59.png b/css/fonts/m5x7.atlas/59.png new file mode 100644 index 0000000..8cb6a14 Binary files /dev/null and b/css/fonts/m5x7.atlas/59.png differ diff --git a/css/fonts/m5x7.atlas/60.png b/css/fonts/m5x7.atlas/60.png new file mode 100644 index 0000000..ec6d43a Binary files /dev/null and b/css/fonts/m5x7.atlas/60.png differ diff --git a/css/fonts/m5x7.atlas/61.png b/css/fonts/m5x7.atlas/61.png new file mode 100644 index 0000000..eb33434 Binary files /dev/null and b/css/fonts/m5x7.atlas/61.png differ diff --git a/css/fonts/m5x7.atlas/62.png b/css/fonts/m5x7.atlas/62.png new file mode 100644 index 0000000..b9816b0 Binary files /dev/null and b/css/fonts/m5x7.atlas/62.png differ diff --git a/css/fonts/m5x7.atlas/63.png b/css/fonts/m5x7.atlas/63.png new file mode 100644 index 0000000..91999c8 Binary files /dev/null and b/css/fonts/m5x7.atlas/63.png differ diff --git a/css/fonts/m5x7.atlas/64.png b/css/fonts/m5x7.atlas/64.png new file mode 100644 index 0000000..1b230e0 Binary files /dev/null and b/css/fonts/m5x7.atlas/64.png differ diff --git a/css/fonts/m5x7.atlas/65.png b/css/fonts/m5x7.atlas/65.png new file mode 100644 index 0000000..a26d300 Binary files /dev/null and b/css/fonts/m5x7.atlas/65.png differ diff --git a/css/fonts/m5x7.atlas/66.png b/css/fonts/m5x7.atlas/66.png new file mode 100644 index 0000000..5599883 Binary files /dev/null and b/css/fonts/m5x7.atlas/66.png differ diff --git a/css/fonts/m5x7.atlas/67.png b/css/fonts/m5x7.atlas/67.png new file mode 100644 index 0000000..b5f77db Binary files /dev/null and b/css/fonts/m5x7.atlas/67.png differ diff --git a/css/fonts/m5x7.atlas/68.png b/css/fonts/m5x7.atlas/68.png new file mode 100644 index 0000000..aee4af7 Binary files /dev/null and b/css/fonts/m5x7.atlas/68.png differ diff --git a/css/fonts/m5x7.atlas/69.png b/css/fonts/m5x7.atlas/69.png new file mode 100644 index 0000000..505c23c Binary files /dev/null and b/css/fonts/m5x7.atlas/69.png differ diff --git a/css/fonts/m5x7.atlas/70.png b/css/fonts/m5x7.atlas/70.png new file mode 100644 index 0000000..6b9bb8c Binary files /dev/null and b/css/fonts/m5x7.atlas/70.png differ diff --git a/css/fonts/m5x7.atlas/71.png b/css/fonts/m5x7.atlas/71.png new file mode 100644 index 0000000..d2bb9aa Binary files /dev/null and b/css/fonts/m5x7.atlas/71.png differ diff --git a/css/fonts/m5x7.atlas/72.png b/css/fonts/m5x7.atlas/72.png new file mode 100644 index 0000000..0db9d50 Binary files /dev/null and b/css/fonts/m5x7.atlas/72.png differ diff --git a/css/fonts/m5x7.atlas/73.png b/css/fonts/m5x7.atlas/73.png new file mode 100644 index 0000000..1ac396c Binary files /dev/null and b/css/fonts/m5x7.atlas/73.png differ diff --git a/css/fonts/m5x7.atlas/74.png b/css/fonts/m5x7.atlas/74.png new file mode 100644 index 0000000..088d488 Binary files /dev/null and b/css/fonts/m5x7.atlas/74.png differ diff --git a/css/fonts/m5x7.atlas/75.png b/css/fonts/m5x7.atlas/75.png new file mode 100644 index 0000000..42ac85d Binary files /dev/null and b/css/fonts/m5x7.atlas/75.png differ diff --git a/css/fonts/m5x7.atlas/76.png b/css/fonts/m5x7.atlas/76.png new file mode 100644 index 0000000..5ca63f4 Binary files /dev/null and b/css/fonts/m5x7.atlas/76.png differ diff --git a/css/fonts/m5x7.atlas/77.png b/css/fonts/m5x7.atlas/77.png new file mode 100644 index 0000000..ca51d74 Binary files /dev/null and b/css/fonts/m5x7.atlas/77.png differ diff --git a/css/fonts/m5x7.atlas/78.png b/css/fonts/m5x7.atlas/78.png new file mode 100644 index 0000000..c44d24c Binary files /dev/null and b/css/fonts/m5x7.atlas/78.png differ diff --git a/css/fonts/m5x7.atlas/79.png b/css/fonts/m5x7.atlas/79.png new file mode 100644 index 0000000..8221674 Binary files /dev/null and b/css/fonts/m5x7.atlas/79.png differ diff --git a/css/fonts/m5x7.atlas/80.png b/css/fonts/m5x7.atlas/80.png new file mode 100644 index 0000000..ab69bc1 Binary files /dev/null and b/css/fonts/m5x7.atlas/80.png differ diff --git a/css/fonts/m5x7.atlas/81.png b/css/fonts/m5x7.atlas/81.png new file mode 100644 index 0000000..bcc4562 Binary files /dev/null and b/css/fonts/m5x7.atlas/81.png differ diff --git a/css/fonts/m5x7.atlas/82.png b/css/fonts/m5x7.atlas/82.png new file mode 100644 index 0000000..12a0a0e Binary files /dev/null and b/css/fonts/m5x7.atlas/82.png differ diff --git a/css/fonts/m5x7.atlas/83.png b/css/fonts/m5x7.atlas/83.png new file mode 100644 index 0000000..15b99cf Binary files /dev/null and b/css/fonts/m5x7.atlas/83.png differ diff --git a/css/fonts/m5x7.atlas/84.png b/css/fonts/m5x7.atlas/84.png new file mode 100644 index 0000000..b1ba0c0 Binary files /dev/null and b/css/fonts/m5x7.atlas/84.png differ diff --git a/css/fonts/m5x7.atlas/85.png b/css/fonts/m5x7.atlas/85.png new file mode 100644 index 0000000..23f8e79 Binary files /dev/null and b/css/fonts/m5x7.atlas/85.png differ diff --git a/css/fonts/m5x7.atlas/86.png b/css/fonts/m5x7.atlas/86.png new file mode 100644 index 0000000..af3c4bd Binary files /dev/null and b/css/fonts/m5x7.atlas/86.png differ diff --git a/css/fonts/m5x7.atlas/87.png b/css/fonts/m5x7.atlas/87.png new file mode 100644 index 0000000..b78e793 Binary files /dev/null and b/css/fonts/m5x7.atlas/87.png differ diff --git a/css/fonts/m5x7.atlas/88.png b/css/fonts/m5x7.atlas/88.png new file mode 100644 index 0000000..ce867af Binary files /dev/null and b/css/fonts/m5x7.atlas/88.png differ diff --git a/css/fonts/m5x7.atlas/89.png b/css/fonts/m5x7.atlas/89.png new file mode 100644 index 0000000..42e1be3 Binary files /dev/null and b/css/fonts/m5x7.atlas/89.png differ diff --git a/css/fonts/m5x7.atlas/90.png b/css/fonts/m5x7.atlas/90.png new file mode 100644 index 0000000..398d275 Binary files /dev/null and b/css/fonts/m5x7.atlas/90.png differ diff --git a/css/fonts/m5x7.atlas/91.png b/css/fonts/m5x7.atlas/91.png new file mode 100644 index 0000000..161ebec Binary files /dev/null and b/css/fonts/m5x7.atlas/91.png differ diff --git a/css/fonts/m5x7.atlas/92.png b/css/fonts/m5x7.atlas/92.png new file mode 100644 index 0000000..7fa44b6 Binary files /dev/null and b/css/fonts/m5x7.atlas/92.png differ diff --git a/css/fonts/m5x7.atlas/93.png b/css/fonts/m5x7.atlas/93.png new file mode 100644 index 0000000..7e09690 Binary files /dev/null and b/css/fonts/m5x7.atlas/93.png differ diff --git a/css/fonts/m5x7.atlas/94.png b/css/fonts/m5x7.atlas/94.png new file mode 100644 index 0000000..09e5546 Binary files /dev/null and b/css/fonts/m5x7.atlas/94.png differ diff --git a/css/fonts/m5x7.atlas/95.png b/css/fonts/m5x7.atlas/95.png new file mode 100644 index 0000000..e9347e5 Binary files /dev/null and b/css/fonts/m5x7.atlas/95.png differ diff --git a/css/fonts/m5x7.atlas/96.png b/css/fonts/m5x7.atlas/96.png new file mode 100644 index 0000000..1789108 Binary files /dev/null and b/css/fonts/m5x7.atlas/96.png differ diff --git a/css/fonts/m5x7.atlas/97.png b/css/fonts/m5x7.atlas/97.png new file mode 100644 index 0000000..71fc7d1 Binary files /dev/null and b/css/fonts/m5x7.atlas/97.png differ diff --git a/css/fonts/m5x7.atlas/98.png b/css/fonts/m5x7.atlas/98.png new file mode 100644 index 0000000..f0d8c50 Binary files /dev/null and b/css/fonts/m5x7.atlas/98.png differ diff --git a/css/fonts/m5x7.atlas/99.png b/css/fonts/m5x7.atlas/99.png new file mode 100644 index 0000000..48c7592 Binary files /dev/null and b/css/fonts/m5x7.atlas/99.png differ diff --git a/css/fonts/m5x7.fnt b/css/fonts/m5x7.fnt new file mode 100644 index 0000000..e6fd95c --- /dev/null +++ b/css/fonts/m5x7.fnt @@ -0,0 +1,99 @@ +info face="m5x7" size=50 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=0,0 +common lineHeight=40 base=34 scaleW=256 scaleH=192 pages=1 packed=0 +page id=0 file="m5x7.png" +chars count=95 +char id=32 x=22 y=80 width=0 height=0 xoffset=0 yoffset=34 xadvance=16 page=0 chnl=0 +char id=33 x=190 y=160 width=6 height=24 xoffset=0 yoffset=12 xadvance=7 page=0 chnl=0 +char id=34 x=2 y=178 width=12 height=10 xoffset=0 yoffset=10 xadvance=13 page=0 chnl=0 +char id=35 x=114 y=80 width=18 height=22 xoffset=0 yoffset=14 xadvance=19 page=0 chnl=0 +char id=36 x=114 y=54 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=37 x=234 y=28 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=38 x=2 y=54 width=22 height=24 xoffset=0 yoffset=12 xadvance=22 page=0 chnl=0 +char id=39 x=228 y=122 width=6 height=10 xoffset=0 yoffset=10 xadvance=7 page=0 chnl=0 +char id=40 x=178 y=100 width=10 height=28 xoffset=0 yoffset=11 xadvance=10 page=0 chnl=0 +char id=41 x=166 y=160 width=10 height=28 xoffset=0 yoffset=11 xadvance=10 page=0 chnl=0 +char id=42 x=202 y=114 width=12 height=12 xoffset=0 yoffset=11 xadvance=13 page=0 chnl=0 +char id=43 x=228 y=80 width=18 height=18 xoffset=0 yoffset=14 xadvance=19 page=0 chnl=0 +char id=44 x=216 y=122 width=10 height=10 xoffset=0 yoffset=29 xadvance=10 page=0 chnl=0 +char id=45 x=216 y=114 width=18 height=6 xoffset=0 yoffset=20 xadvance=19 page=0 chnl=0 +char id=46 x=178 y=182 width=6 height=6 xoffset=0 yoffset=30 xadvance=7 page=0 chnl=0 +char id=47 x=148 y=140 width=12 height=24 xoffset=0 yoffset=12 xadvance=13 page=0 chnl=0 +char id=48 x=214 y=28 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=49 x=194 y=28 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=50 x=174 y=28 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=51 x=154 y=28 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=52 x=134 y=28 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=53 x=114 y=28 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=54 x=94 y=158 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=55 x=94 y=132 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=56 x=94 y=106 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=57 x=94 y=80 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=58 x=236 y=114 width=6 height=16 xoffset=0 yoffset=20 xadvance=7 page=0 chnl=0 +char id=59 x=190 y=114 width=10 height=18 xoffset=0 yoffset=21 xadvance=10 page=0 chnl=0 +char id=60 x=148 y=166 width=12 height=18 xoffset=0 yoffset=14 xadvance=13 page=0 chnl=0 +char id=61 x=230 y=100 width=16 height=12 xoffset=0 yoffset=17 xadvance=16 page=0 chnl=0 +char id=62 x=134 y=166 width=12 height=18 xoffset=0 yoffset=14 xadvance=13 page=0 chnl=0 +char id=63 x=94 y=54 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=64 x=94 y=28 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=65 x=74 y=158 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=66 x=74 y=132 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=67 x=74 y=106 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=68 x=74 y=80 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=69 x=74 y=54 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=70 x=74 y=28 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=71 x=234 y=2 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=72 x=214 y=2 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=73 x=194 y=2 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=74 x=174 y=2 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=75 x=154 y=2 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=76 x=134 y=2 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=77 x=2 y=28 width=24 height=24 xoffset=0 yoffset=12 xadvance=25 page=0 chnl=0 +char id=78 x=114 y=2 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=79 x=94 y=2 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=80 x=74 y=2 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=81 x=54 y=158 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=82 x=54 y=132 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=83 x=54 y=106 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=84 x=54 y=80 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=85 x=54 y=54 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=86 x=54 y=28 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=87 x=2 y=2 width=24 height=24 xoffset=0 yoffset=12 xadvance=25 page=0 chnl=0 +char id=88 x=54 y=2 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=89 x=28 y=152 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=90 x=28 y=126 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=91 x=166 y=130 width=10 height=28 xoffset=0 yoffset=11 xadvance=10 page=0 chnl=0 +char id=92 x=134 y=140 width=12 height=24 xoffset=0 yoffset=12 xadvance=13 page=0 chnl=0 +char id=93 x=166 y=100 width=10 height=28 xoffset=0 yoffset=11 xadvance=10 page=0 chnl=0 +char id=94 x=210 y=100 width=18 height=12 xoffset=0 yoffset=11 xadvance=19 page=0 chnl=0 +char id=95 x=28 y=178 width=18 height=6 xoffset=0 yoffset=30 xadvance=19 page=0 chnl=0 +char id=96 x=16 y=178 width=10 height=10 xoffset=0 yoffset=10 xadvance=10 page=0 chnl=0 +char id=97 x=208 y=80 width=18 height=18 xoffset=0 yoffset=18 xadvance=19 page=0 chnl=0 +char id=98 x=28 y=100 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=99 x=148 y=120 width=16 height=18 xoffset=0 yoffset=18 xadvance=16 page=0 chnl=0 +char id=100 x=28 y=74 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=101 x=188 y=80 width=18 height=18 xoffset=0 yoffset=18 xadvance=19 page=0 chnl=0 +char id=102 x=134 y=54 width=16 height=24 xoffset=0 yoffset=12 xadvance=16 page=0 chnl=0 +char id=103 x=28 y=48 width=18 height=24 xoffset=0 yoffset=18 xadvance=19 page=0 chnl=0 +char id=104 x=28 y=22 width=18 height=24 xoffset=0 yoffset=12 xadvance=19 page=0 chnl=0 +char id=105 x=178 y=156 width=10 height=24 xoffset=0 yoffset=12 xadvance=10 page=0 chnl=0 +char id=106 x=114 y=156 width=12 height=32 xoffset=0 yoffset=10 xadvance=13 page=0 chnl=0 +char id=107 x=114 y=130 width=16 height=24 xoffset=0 yoffset=12 xadvance=16 page=0 chnl=0 +char id=108 x=178 y=130 width=10 height=24 xoffset=0 yoffset=12 xadvance=10 page=0 chnl=0 +char id=109 x=28 y=2 width=24 height=18 xoffset=0 yoffset=18 xadvance=25 page=0 chnl=0 +char id=110 x=168 y=80 width=18 height=18 xoffset=0 yoffset=18 xadvance=19 page=0 chnl=0 +char id=111 x=148 y=80 width=18 height=18 xoffset=0 yoffset=18 xadvance=19 page=0 chnl=0 +char id=112 x=2 y=152 width=18 height=24 xoffset=0 yoffset=18 xadvance=19 page=0 chnl=0 +char id=113 x=2 y=126 width=18 height=24 xoffset=0 yoffset=18 xadvance=19 page=0 chnl=0 +char id=114 x=148 y=100 width=16 height=18 xoffset=0 yoffset=18 xadvance=16 page=0 chnl=0 +char id=115 x=232 y=54 width=18 height=18 xoffset=0 yoffset=18 xadvance=19 page=0 chnl=0 +char id=116 x=114 y=104 width=16 height=24 xoffset=0 yoffset=12 xadvance=16 page=0 chnl=0 +char id=117 x=212 y=54 width=18 height=18 xoffset=0 yoffset=18 xadvance=19 page=0 chnl=0 +char id=118 x=192 y=54 width=18 height=18 xoffset=0 yoffset=18 xadvance=19 page=0 chnl=0 +char id=119 x=2 y=106 width=24 height=18 xoffset=0 yoffset=18 xadvance=25 page=0 chnl=0 +char id=120 x=172 y=54 width=18 height=18 xoffset=0 yoffset=18 xadvance=19 page=0 chnl=0 +char id=121 x=2 y=80 width=18 height=24 xoffset=0 yoffset=18 xadvance=19 page=0 chnl=0 +char id=122 x=152 y=54 width=18 height=18 xoffset=0 yoffset=18 xadvance=19 page=0 chnl=0 +char id=123 x=134 y=110 width=12 height=28 xoffset=0 yoffset=11 xadvance=13 page=0 chnl=0 +char id=124 x=190 y=134 width=6 height=24 xoffset=0 yoffset=12 xadvance=7 page=0 chnl=0 +char id=125 x=134 y=80 width=12 height=28 xoffset=0 yoffset=11 xadvance=13 page=0 chnl=0 +char id=126 x=190 y=100 width=18 height=12 xoffset=0 yoffset=17 xadvance=19 page=0 chnl=0 diff --git a/css/fonts/m5x7.png b/css/fonts/m5x7.png new file mode 100644 index 0000000..c1c193f Binary files /dev/null and b/css/fonts/m5x7.png differ diff --git a/css/fonts/m5x7.ttf b/css/fonts/m5x7.ttf new file mode 100644 index 0000000..2ed774d Binary files /dev/null and b/css/fonts/m5x7.ttf differ diff --git a/css/fonts/m5x7.xml b/css/fonts/m5x7.xml new file mode 100644 index 0000000..bcd7563 --- /dev/null +++ b/css/fonts/m5x7.xml @@ -0,0 +1,105 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/css/fonts/m5x7test.bmglyph b/css/fonts/m5x7test.bmglyph new file mode 100644 index 0000000..e9c6a79 Binary files /dev/null and b/css/fonts/m5x7test.bmglyph differ diff --git a/css/fonts/m5x7w.png b/css/fonts/m5x7w.png new file mode 100644 index 0000000..f6f5d56 Binary files /dev/null and b/css/fonts/m5x7w.png differ diff --git a/css/fonts/pixel_unicode/Pixel-UniCode.ttf b/css/fonts/pixel_unicode/Pixel-UniCode.ttf new file mode 100755 index 0000000..5b4d3cb Binary files /dev/null and b/css/fonts/pixel_unicode/Pixel-UniCode.ttf differ diff --git a/css/fonts/pixel_unicode/license.txt b/css/fonts/pixel_unicode/license.txt new file mode 100755 index 0000000..810b524 --- /dev/null +++ b/css/fonts/pixel_unicode/license.txt @@ -0,0 +1,4 @@ +The FontStruction “Pixel UniCode” +(http://fontstruct.com/fontstructions/show/908795) by “ivancr72” is licensed +under a Creative Commons Attribution license +(http://creativecommons.org/licenses/by/3.0/). diff --git a/css/fonts/pixel_unicode/readme.txt b/css/fonts/pixel_unicode/readme.txt new file mode 100755 index 0000000..c449b42 --- /dev/null +++ b/css/fonts/pixel_unicode/readme.txt @@ -0,0 +1,26 @@ +The font file in this archive was created using Fontstruct the free, online +font-building tool. +This font was created by “ivancr72”. +This font has a homepage where this archive and other versions may be found: +http://fontstruct.com/fontstructions/show/908795 + +Try Fontstruct at http://fontstruct.com +It’s easy and it’s fun. + +NOTE FOR FLASH USERS: Fontstruct fonts (fontstructions) are optimized for Flash. +If the font in this archive is a pixel font, it is best displayed at a font-size +of 16. + +Fontstruct is sponsored by FontShop. +Visit them at http://fontshop.com +FontShop is the original independent font retailer. We’ve been around since +the dawn of digital type. Whether you need the right font or need to create the +right font from scratch, let our 23 years of experience work for you. + +Fontstruct is copyright ©2013-2014 Rob Meek + +LEGAL NOTICE: +In using this font you must comply with the licensing terms described in the +file “license.txt” included with this archive. +If you redistribute the font file in this archive, it must be accompanied by all +the other files from this archive, including this one. diff --git a/css/index.css b/css/index.css new file mode 100644 index 0000000..83c646f --- /dev/null +++ b/css/index.css @@ -0,0 +1,830 @@ +img{ /* makes a change, noticeable [28/05/16] */ + image-rendering: optimizeSpeed; + image-rendering: -moz-crisp-edges; + image-rendering: -webkit-optimize-contrast; + image-rendering: optimize-contrast; + image-rendering: pixelated; + -ms-interpolation-mode: nearest-neighbor; +} +body{ + -webkit-touch-callout: none; + -webkit-user-select: none; + -khtml-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} +div[contenteditable],span[contenteditable]{ + -webkit-touch-callout: auto; + -webkit-user-select: auto; + -khtml-user-select: auto; + -moz-user-select: auto; + -ms-user-select: auto; + user-select: auto; +} +::-webkit-scrollbar{background:transparent;} +::-webkit-scrollbar-track{ + background:transparent; +} +::-webkit-scrollbar-thumb { + background:rgba(200,200,200,0.8); +} +.noscroll::-webkit-scrollbar{ + background:black; +} + +/* *{font-weight:normal !important;} */ +/* best to abandon all "bold" texts [12/08/16] */ + +html,body{ + margin:0 0 0 0; + padding:0 0 0 0; + width: 100%; + height: 100%; + overflow: hidden; /* temporary solution [16/05/16]*/ + font-family: pixel; + color: white; + word-wrap: break-word; + + /*text-rendering: optimizeLegibility !important; + -webkit-font-smoothing: antialiased !important;*/ + + -webkit-font-smoothing: subpixel-antialiased; + /* this makes safari render fonts thicker, wanted */ + + /*-moz-osx-font-smoothing: grayscale;*/ + /* this makes regular fonts thinner in osx firefox, not wanted [12/08/16] */ + + /*font-smooth: never; + -webkit-font-smoothing : none; */ + /* + NOTE: Chrome renders fonts thicker as default, it's nice, the other browsers render then reall thin ... ignoring the difference for the time being; [05/08/16] + */ + +} +::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */ + color: #A9ACAC; + opacity: 1; /* Firefox */ +} + +:-ms-input-placeholder { /* Internet Explorer 10-11 */ + color: #A9ACAC; +} +canvas { display:block; } /*replaces the overflow: hidden solution [07/07/16] */ +.psuccess{ + color: #5DAC40; +} +.pfail{ + color: #AC393E; +} +.iqui{ /*item quantity ui*/ + color: white; + border: 2px solid gray; background: black; padding: 1px 2px 1px 3px; + position:absolute; right:-2px; bottom:-2px; text-align: center; + line-height: 16px; font-size: 24px; height: 16px; +} +.iqhp{ + color: #F37A87; +} +.iqdbf{ + color: #343792; +} +.iqmp{ + color: #66B3F6; +} +.iuui{ /*item upgrade ui*/ + border: 2px solid gray; background: black; padding: 1px 2px 1px 3px; + position:absolute; left:-2px; bottom:-2px; text-align: center; + line-height: 16px; font-size: 24px; height: 16px; + color: gray; +} +.truui{ /*item upgrade ui*/ + border: 2px solid gray; background: black; padding: 1px 2px 1px 3px; + position:absolute; left:-2px; top:-2px; text-align: center; + line-height: 16px; font-size: 24px; height: 16px; + color: gray; +} +.trruui{ + border: 2px solid gray; background: black; padding: 1px 2px 1px 3px; + position:absolute; right:-2px; top:-2px; text-align: center; + line-height: 16px; font-size: 24px; height: 16px; + color: gray; +} +.imu{ + color:#64B867; +} +.ivu{ + color:#D3391E; +} +.itu{ + color:gold; + color:#E6C409; + color:#389261; + color:#398F2E; + color:#FFFFFF; + color:#398F2E; +} +.ibu{ + color:#5D688F; + color:#808C8F; + color:#D96C0E; + color:#DA8F20; +} +.igu{ + color:#D96EDC; +} +.ixu{ + color:#5C5D5E; + color:#B3AFB4; +} +.ilsu{ + color:#B3AFB4; + color:#8C7A36; + color:#C9AE5D; + color:#A28D4C; +} +.iluu{ + color:#B3AFB4; + color:#949698; + color:#5C5D5E; +} +.ering{ + border: 2px solid gray; + padding: 8px; + display: inline-block; +} +.clevel4{ + color: #FFC949; +} +.clevel5{ + color: #B753C7; +} +.clevelA{ + color: #FFC949; +} +.clevelB{ + color: #4A9AFF; +} +.clevelC{ + color: #FC4546; +} +.clevelD{ + color: #9353FF; +} +.clevelE{ + color: #FD8915; +} +.clevelW{ + color: #5BAD59; +} +.clevel6{ + color: #FC2F72; +} +.clevel7{ + color: #FD6A19; +} +.clevel7{ + color: #D71D41; +} +.ulevel8{ + color: #FFC949; +} +.ulevel9{ + color: #E64D31; +} +.ulevel10{ + color: #B753C7; +} +.ulevel11{ + color: #E0DE58; + color: #B753C7; +} +.ulevel12{ + color: #2096D8; + color: #B753C7; +} +.infop{ + color: #9E9E9E; +} +.mw{ + color: #FFFFFF; +} +.infot{ + margin-top: 4px; +} +.itemnumi{ /* input */ + vertical-align: middle; + width: 40px; + height: 16px; + line-height: 16px; + font-size: 16px; + font-family: Pixel; + margin-right: 5px; + display: inline-block; + border:0; + padding-left: 5px; + background: #7D7D7D; + color: white; +} +.cinput{ /* code save */ + height: 48px; + line-height: 36px; + font-size: 36px; + font-family: Pixel; + display: inline-block; + border:0; + padding: 12px; + background: #7D7D7D; + background: #2D2D2E; + border: 4px solid gray; + color: white; + margin-right: 4px; + vertical-align: top; +} + +/* #toprightcorner .gamebutton{ margin-left: -9px; } */ + +#gamelog,#chatlog,#codelog{ + /*z-index: 300; + position: fixed; + bottom: 0px; + right: 0px;*/ + height: 208px; + width: 300px; + background: rgb(0,0,0); + line-height: 24px; + font-size: 24px; + text-align: left; + vertical-align: middle; + padding: 10px; + overflow-y: scroll; + border: 5px solid gray; + /*letter-spacing: 0.8px;*/ +} +#xcodehint{ + z-index: 400; + height: 36px; + width: 320px; /*300+15+5*/ + right: 0px; + position: fixed; + border: 5px solid gray; + bottom: 192px; /*208+15-36+5*/ + overflow: hidden; + background: black; + font-size: 36px; + line-height: 36px; + text-align: center; +} +.codesearch::placeholder { + color: gray; + opacity: 1; +} +.chatlog{ + line-height: 24px; + font-size: 24px; + text-align: left; + vertical-align: middle; + padding: 10px; + overflow-y: scroll; + height: 190px; + width: 300px; /* .chatinput is 314+3x2 - this one is 300+10x2 */ +} +#chatinput{ + position: fixed; + z-index:99; + bottom: 5px; + left: 5px; + width: 314px; + height: 30px; + font-size: 24px; + font-family: Pixel; + display: inline-block; + background: #404040; + color: white; + border: none; + padding: 3px; +} +.chatinput{ + width: 314px; + height: 30px; + font-size: 24px; + font-family: Pixel; + display: inline-block; + background: #404040; + color: white; + border: none; + padding: 3px; +} +.ccinput,.ccinput:focus{ + border: none; + outline: none; + background: none; + /*background: #8653D8;*/ + padding: 5px 12px 5px 12px; + color: white; + font-size: 36px; + font-family: Pixel; +} +.newmessage{ + color: green; +} +.tint{ + position: relative; + z-index:1; + overflow: hidden; +} +.ontint{ + position: relative; + z-index:2; +} +.gameentry{ +} +#chatlog{ + z-index:98; + left: 0px; + /*direction:rtl;*/ +} +.chatentry{ + /*direction: ltr;*/ + margin-bottom: 30px; +} +.chatentry+.chatentry{ + margin-top: -30px; +} +#topleftcorner{ + z-index: 109; + top: 0px; + left: 0px; + position: fixed; + pointer-events: none; +} +.mimicker{ + position: fixed; + font-size: 0px; + display: inline-block; + cursor: pointer; + /* background-color: rgba(0,200,0,0.5); */ + z-index: 400; +} +/*#topleftcornerui > *{ + pointer-events: auto; +}*/ +#toprightcorner{ + z-index: 100; + top: 0px; + right: 0px; + position: fixed; +} +#bottomrightcorner{ + z-index: 300; + bottom: 0px; + right: 0px; + position: fixed; +} +#bottomrightcodecorner{ + z-index: 300; + bottom: 0px; + right: 325px; + position: fixed; + display: none; +} +#bottomleftcorner2{ + z-index: 99; + bottom: 0px; + left: 0px; + position: fixed; +} +.xclicks{ + cursor: none; +} +.bpclicks{ /* Block Parent Clicks - Only [24/07/18] */ + pointer-events: none !important; /* if !important is not set, the '> *' takes priority */ +} +.bpclicks > *{ + pointer-events: auto; +} +#bottomleftcorner{ + z-index: 100; + bottom: 0px; + left: 0px; + position: fixed; +} +.label,.klabel{ + padding: 0px 4px 2px 4px; + background: #808080; + color: white; + border-radius: 1px; + margin-bottom: 2px; + display: inline-block; + vertical-align: middle; +} +.klabel{ + margin: 1px; + background: #E13758; +} +.clabel,.xlabel,.rlabel,.jlabel,.dlabel,.redlabel,.hlabel,.elabel{ + margin-left: -4px; + margin-right: -2px; + padding: 0px 2px 2px 6px; + line-height: 22px; /* with padding's bottom adjustment, reduces the top padding, as -2px top padding doesn't work */ + display: inline-block; + border-radius: 1px; + color: white; + background: #888888; + -webkit-touch-callout: text; + -webkit-user-select: text; + -khtml-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; +} +.clabel[onclick],.xlabel[onclick],.rlabel[onclick],.jlabel[onclick],.redlabel[onclick],.hlabel[onclick],.elabel[onclick]{ + cursor:pointer; +} +.xlabel{ + background: #77A6C3; +} +.rlabel{ + background: #E5680D; +} +.jlabel{ + background: #49BD74; +} +.hlabel{ + background: #B9AB63; +} +.elabel{ + background: #46BE2E; +} +.dlabel{ + background: #3C9BC4; +} +.redlabel{ + background: #C01941; +} +.slimbutton{ + display: inline-block; + border: 2px solid gray; + font-size: 24px; + line-height: 24px; + padding: 5px 10px 5px 10px; + background: black; + text-align: center; + color: white; +} +.tinybutton{ + display: inline-block; + border: 2px solid gray; + font-size: 16px; + line-height: 16px; + padding: 4px 7px 4px 7px; + background: black; + text-align: center; + color: white; + margin: 4px; +} +.gamebutton{ + display: inline-block; + border: 4px solid gray; + font-size: 24px; + line-height: 24px; + padding: 12px; + background: black; + text-align: center; + color: white; +} +.largerfont{ + font-size: 32px; + line-height: 24px; + vertical-align: bottom; +} +.blockbutton{ + display: block; + border: 4px solid gray; + font-size: 24px; + line-height: 24px; + padding: 12px; + background: black; + text-align: center; +} +a.textbutton{ + color: inherit; + text-decoration:none; +} +a.gamebutton{ + color: inherit; + text-decoration:none; +} +.redborder{ + border-color: orange; +} +.orangeborder{ + border-color: orange; +} +.gamebutton.active{ + border-color: green; +} +.gamebutton.active2{ + border-color: #FFFFFF; +} +.gamebutton.active3{ + border-color: #42AFDE; +} +.gamebutton-large{ + font-size: 36px; + line-height: 36px; +} +.gamebutton-small{ + padding: 4px 8px 4px 8px; + border: 2px solid gray; + margin-bottom: 4px; +} +.gamebutton-active.gamebutton-small{ + border: 2px solid #EAF1EC; +} +#pagewrapped{ + margin-top: 400px; + width: 400px; + z-index:205; + display: inline-block; +} +.loginorselection{ + text-align: center; + -webkit-text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4); + -moz-text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4); + text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4); +} +#codeui{ + position: fixed; + top: 0px; + bottom: 0px; + bottom: 37px; + left: 0px; + width: 800px; + display: none; + z-index: 401; + -webkit-box-shadow: 0 0 6px #555960; + -moz-box-shadow: 0 0 6px #555960; + box-shadow: 0 0 6px #555960; +} +.CodeMirror{ + height: 100%; + width: 100%; + font-family: Pixel; + font-size: 24px; + letter-spacing: 1px; /* more readable */ +} +.engagebutton,.dengagebutton{ + position: absolute; + right: 5px; + bottom: 5px; + z-index: 200; +} +.cslotbutton{ + position: absolute; + right: 5px; + top: 5px; + z-index: 200; +} +.loginorselection,#features,#codeui,.largeborder{ + background: black; + border: 5px solid gray; + padding: 10px; +} +#selection{ +} +#pagewrapper{ + z-index:200; + position: fixed; + top: 0px; + left: 0px; + right: 0px; + bottom: 0px; + vertical-align:middle; + text-align: center; + /*background: rgba(0,0,0,0.3);*/ +} +#features{ + position: fixed; + bottom: 0px; + left: 0px; + z-index: 201; + /* padding-right: 40px; WHY?! */ +} +#topui{ + position: fixed; + top: 0px; + left: 0px; + z-index: 202; +} +#backbutton{ + position: fixed; + top: 0px; + right: 0px; + z-index: 201; +} +.input{ + padding: 20px; + font-size: 18px; +} +.button{ + background: #4C3634; + padding: 20px; + font-size: 18px; + font-weight: bold; + border:none; +} +.button.disable{ + background: #2E4C28; +} +.textbutton,.whiteheader{ + font-size: 24px; +} +.textbutton.disable{ + color: #3A783E; +} +.logout.disable{ + color: #787878; +} +.textheader{ + font-size: 32px; + padding: 4px; + margin-bottom: 2px; + font-family: pixel; + text-align: center; +} +.input,.button{ + /*font-family: pixel;*/ + border:none !important; +} +.selectioninput{ + font-size: 24px; + padding: 2px; + font-family: pixel; + text-align: center; +} +.selectiontextarea{ + font-size: 24px; + padding: 2px; + font-family: pixel; + text-align: left; +} +.chartype{ + border: 2px solid black; + display: inline-block; + padding: 4px 6px 4px 8px; + margin: 3px 0px 2px 3px; +} +.chartype.selected{ + border: 2px solid gray; +} +.gendertype{ + border: 2px solid black; + display: inline-block; + padding: 4px 6px 4px 8px; + margin: 3px 0px 2px 3px; +} +.gendertype.selected{ + border: 2px solid gray; +} +.lookstype{ + border: 2px solid black; + display: inline-block; + padding: 4px 6px 4px 8px; + margin: 3px 0px 2px 3px; +} +.lookstype.selected{ + border: 2px solid gray; +} +input:focus, button:focus, div:focus { + outline: none !important; + box-shadow: none !important; +} +.block{ + box-sizing: border-box; + width: 100%; +} +li{ + font-size: 24px; +} + +.vtopx{ + margin-bottom: 0px; + margin-top: 0px; + vertical-align: top; +} + +.glow8{ + -webkit-box-shadow: 0 0 3px orange; + -moz-box-shadow: 0 0 3px orange; + box-shadow: 0 0 3px orange; +} +.glow9{ + -webkit-box-shadow: 0 0 5px #E6434B; + -moz-box-shadow: 0 0 5px #E6434B; + box-shadow: 0 0 5px #E6434B; +} +.glow10{ + -webkit-box-shadow: 0 0 7px #ffe000; + -moz-box-shadow: 0 0 7px #ffe000; + box-shadow: 0 0 7px #ffe000; +} + +.textglow{ + animation: textglow 4s infinite alternate; +} + +@keyframes textglow { + to { + text-shadow: 0 0 2px orange; + } +} + +.boxglow{ + animation: boxglow 3s infinite alternate; +} + +@keyframes boxglow { + from { + box-shadow: 0 0 1px orange; + } + to { + box-shadow: 0 0 4px orange; + } +} + +@keyframes boxglow2 { + from { + box-shadow: 0 0 12px #E3C410; + background-color: #000000; + } + 50% { + box-shadow: 0 0 1px #E3C410; + background-color: #8B8C96; + } + to { + box-shadow: 0 0 12px #E3C410; + background-color: #000000; + } +} + +@keyframes bg1 { + from { + background-color: #000000; + } + 50% { + background-color: #599BC3; + } + to { + background-color: #000000; + } +} + +@keyframes flashpa { + from { + background-color: #3A968E; + } + 50% { + background-color: #56F0E7; + } + to { + background-color: #3A968E; + } +} + +.flashp{ + animation: flashpa 5s infinite linear; +} + +@keyframes flashta { + from { + background-color: #3D386C; + } + 50% { + background-color: #746AD9; + } + to { + background-color: #3D386C; + } +} + +.flasht{ + animation: flashta 3s infinite linear; +} + + +.loading{ + animation: boxglow2 2s infinite ease-in-out; +} + +@media only screen and (max-height: 640px) { + .loginfeatures{ + top: 59px; + overflow: auto; + } +} +.mailsubject + .mailsubject{ + border-top: 1px dashed gray; + padding-top: 4px; + margin-top: 4px; +} \ No newline at end of file diff --git a/design/.DS_Store b/design/.DS_Store new file mode 100644 index 0000000..a4f6702 Binary files /dev/null and b/design/.DS_Store differ diff --git a/design/__init__.py b/design/__init__.py new file mode 100644 index 0000000..fef66b5 --- /dev/null +++ b/design/__init__.py @@ -0,0 +1 @@ +#!/usr/bin/env python \ No newline at end of file diff --git a/design/achievements.py b/design/achievements.py new file mode 100644 index 0000000..ef68f2d --- /dev/null +++ b/design/achievements.py @@ -0,0 +1,82 @@ +achievements={ + "reach40":{ + "name":"Become Level 40", + "item":"gem1", + }, + "reach50":{ + "name":"Become Level 50", + "shells":50, + }, + "reach60":{ + "name":"Become Level 60", + "shells":100, + }, + "reach70":{ + "name":"Become Level 70", + "shells":200, + }, + "reach80":{ + "name":"Become Level 80", + "shells":200, + }, + "reach90":{ + "name":"Is it even possible?!", + "explanation":"Reach Level 90", + "shells":20000, + }, + "upgrade10":{ + "name":"The Final Frontier", + }, + "100boss":{ + "name":"100th Boss", + "explanation":"Defeat 100 Bosses", + }, + "abtesting":{ + "name":"1000 Test Kills", + "explanation":"Get 1000 kills during the A/B Testing Event", + "title":"abtesting", + "count":1000, + }, + "1000boss":{ + "name":"1000th Boss", + "explanation":"Defeat 1,000 Bosses", + }, + "monsterhunter":{ + "name":"Monster Hunter", + "explanation":"Kill 1,000,000 Monsters", + }, + "discoverlair":{ + "name":"[Discover] Lair", + "explanation":"Find the lair of the Spider Queen." + }, + "firehazard":{ + "name":"Fire Hazard", + "count":20000, + "explanation":"Last hit 20,000 monsters consecutively with only burn damage using same weapon!", + "title":"firehazard", + }, + "lucky":{ + "name":"Lucky", + "explanation":"Succeed with the exact % on an upgrade or compound.", + "title":"lucky", + }, + "stomped":{ + "name":"Stomped", + "count":1200, + "explanation":"Get hit 1,200 times randomly by Stompy, without getting hit by any other monster!", + "title":"stomped", + }, + "gooped":{ + "name":"Gooped", + "count":60000000, + "rr":40000, + "explanation":"Receive 60M damage from Goo's", + "title":"gooped", + }, + "festive":{ + "name":"Festive", + "count":400000, + "explanation":"Deal 400K damage to Grinch", + "title":"festive", + }, +} \ No newline at end of file diff --git a/design/animations.py b/design/animations.py new file mode 100644 index 0000000..bb76197 --- /dev/null +++ b/design/animations.py @@ -0,0 +1,544 @@ +animations={ + "block":{ + "file":"/images/sprites/animations/Block.png", #sparks ... + "frames":11, + }, + "explode_c":{ + "file":"/images/sprites/animations/ExplodeC.png", #perfect explosion + "frames":12, + }, + "explode_b":{ + "file":"/images/sprites/animations/ExplodeB.png", + "frames":12, + }, + "explode_p":{ + "file":"/images/sprites/animations/ExplodeP2.png", #priest explosion + "frames":12, + }, + "explode_up":{ + "file":"/images/sprites/animations/ExplodeUCS.png", #priest explosion + "frames":12, + }, + "explode_a":{ + "file":"/images/sprites/animations/ExplodeA.png", #perfect explosion + "frames":12, + }, + "rain":{ + "file":"/images/sprites/weather/wsheet_rain1_1.png", + "frames":4, + }, + "snow":{ + "file":"/images/sprites/weather/wsheet_snow_1.png", + "frames":4, + }, + "fog":{ + "file":"/images/sprites/weather/fog.png", + "frames":2, + }, + #"crackle":{ + # "file":"/images/tiles/animations/custom/crackle1.png", + # "frames":6, + #}, + "crackle":{ + "file":"/images/sprites/animations/GlintF.png", + "frames":4, + }, + "egg":{ + "file":"/images/sprites/animations/egg_splash.png", #priest explosion + "frames":3, + }, + "hearts_single":{ + "file":"/images/sprites/emotions/heart_rise_single.png", + "frames":10, + "y":-10, + "size":2, + "alpha":1, + }, + "starkiller":{ + "file":"/images/sprites/animations/attack3.png", #perfect explosion + "frames":12, + "aspeed":"mild", + "alpha":0.8, + }, + "spark0":{ + "file":"/images/sprites/animations/Spark0.png", # nice animation, death-like + "frames":10, + }, + "slash0":{ + "file":"/images/sprites/animations/Slash0.png", # nice animation, damage-like + "frames":7, + }, + "slash1":{ + "file":"/images/sprites/animations/Slash1.png", # nice animation, damage-like + "frames":7, + }, + "slash3":{ + "file":"/images/sprites/animations/Slash3.png", # mp color + "frames":7, + }, + "slash2":{ + "file":"/images/sprites/animations/Slash2Quick.png", + "frames":7, + "alpha":0.9, + "size":0.75, + "aspeed":"fast", + }, + "snowflake":{ + "file":"/images/sprites/animations/snowflake.png", + "frames":7, + }, + "snowball":{ + "file":"/images/sprites/animations/snowball_projectile.png", + "frames":4, + "continuous":True, + "directional":True, + "speed":500, + "size":0.75, + }, + "snowball_hit":{ + "file":"/images/sprites/animations/snowball_hit.png", + "frames":4, + "aspeed":"slow", + "alpha":1, + "exact":True, + "y":-10, + }, + "pinky":{ + "file":"/images/sprites/animations/pinky.png?v=2", + "frames":3, + "continuous":True, + "directional":True, + "speed":1200, + }, + "wandy":{ + "file":"/images/sprites/animations/wandy.png?v=2", + "frames":3, + "continuous":True, + "directional":True, + "speed":1200, + }, + "carrow":{ + "file":"/images/sprites/animations/CArrow.png", + "frames":3, + "continuous":True, + "directional":True, + "speed":1200, + }, + "garrow":{ + "file":"/images/sprites/animations/garrow.png", + "frames":4, + "continuous":True, + "directional":True, + "speed":1200, + }, + "arrow1":{ + "file":"/images/sprites/animations/arrow1.png", + "frames":4, + "continuous":True, + "directional":True, + "speed":1200, + }, + "superarrow":{ + "file":"/images/sprites/animations/arrow2.png", + "frames":4, + "continuous":True, + "directional":True, + "speed":1200, + "scale":1.5, + }, + "firearrow":{ + "file":"/images/sprites/animations/fireArrow.png", + "frames":4, + "continuous":True, + "directional":True, + "speed":1000, + "scale":0.75, + }, + "poucharrow":{ + "file":"/images/sprites/animations/pouchArrow.png", + "frames":4, + "continuous":True, + "directional":True, + "speed":1000, + "scale":0.75, + }, + "frostarrow":{ + "file":"/images/sprites/animations/frostArrow.png", + "frames":4, + "continuous":True, + "directional":True, + "speed":1000, + "scale":0.75, + }, + "acid":{ + "file":"/images/sprites/animations/terrorAcid.png", + "frames":4, + "continuous":True, + "speed":800, + "scale":0.75, + }, + "cuarrow":{ + "file":"/images/sprites/animations/heartedArrow.png", + "frames":3, + "continuous":True, + "directional":True, + "speed":1200, + }, + "pblob":{ + "file":"/images/sprites/animations/PBlob.png", + "frames":3, + "continuous":True, + "directional":True, + "speed":1200, + }, + "mblob":{ + "file":"/images/sprites/animations/MBlob.png", + "frames":3, + "continuous":True, + "directional":True, + "speed":800, + }, + "mblob_purplish":{ + "file":"/images/sprites/animations/MBlobP.png", + "frames":3, + "continuous":True, + "directional":True, + "speed":600, + }, + "mblob_red":{ + "file":"/images/sprites/animations/MBlobR.png", + "frames":3, + "continuous":True, + "directional":True, + "speed":800, + "framefps":9, # since 9<16, changes every frame + #"scale":0.75, + }, + "magic0":{ + "file":"/images/sprites/animations/magic0.png", + "frames":4, + "continuous":True, + "directional":True, + "speed":800, + "framefps":9, # since 9<16, changes every frame + #"scale":0.75, + }, + "magic1":{ + "file":"/images/sprites/animations/magic1.png", + "frames":4, + "continuous":True, + "directional":True, + "speed":800, + "framefps":9, # since 9<16, changes every frame + #"scale":0.75, + }, + "magic2":{ + "file":"/images/sprites/animations/magic2.png", + "frames":4, + "continuous":True, + "directional":True, + "speed":800, + "framefps":9, # since 9<16, changes every frame + #"scale":0.75, + }, + "magic3":{ + "file":"/images/sprites/animations/magic3.png", + "frames":4, + "continuous":True, + "directional":True, + "speed":800, + "framefps":9, + }, + "magic4":{ + "file":"/images/sprites/animations/magic4.png", + "frames":4, + "continuous":True, + "directional":True, + "speed":800, + "framefps":9, + }, + "slash":{ + "file":"/images/sprites/animations/slash.png", + "frames":3, + "continuous":True, + "directional":True, + "speed":260, + "front":True, + }, + "wslash":{ + "file":"/images/sprites/animations/wslash.png", + "frames":3, + "continuous":True, + "directional":True, + "speed":260, + "front":True, + }, + "heal_projectile":{ + "file":"/images/sprites/animations/healAttack.png", + "frames":4, + "continuous":True, + "speed":190, + "scale":0.5, + }, + "curse_projectile":{ + "file":"/images/sprites/animations/curseAttack.png", + "frames":3, + "continuous":True, + "speed":190, + "framefps":1, + }, + "fireball":{ + "file":"/images/sprites/animations/fireball.png", + "frames":4, + "continuous":True, + "directional":True, + "speed":400, + }, + "frostball":{ + "file":"/images/sprites/animations/frostball.png", + "frames":4, + "continuous":True, + "directional":True, + "speed":400, + }, + "gold":{ + "file":"/images/sprites/animations/gold.png", + "frames":1, + "continuous":True, + "directional":True, + "speed":160, + "front":True, + }, + "arrow_hit":{ + "file":"/images/sprites/animations/Slash0Arrow.png", # nice animation, damage-like + "frames":7, + "alpha":0.9, + "size":0.8, + }, + "icecrack":{ + "file":"/images/sprites/animations/crackingIce.png", # nice animation, damage-like + "frames":6, + "alpha":1, + "size":1, + "y":2, + }, + "supershot":{ + "file":"/images/sprites/animations/Slash0Super.png", # nice animation, damage-like + "frames":7, + "alpha":0.9, + }, + "party_heal":{ + "file":"/images/sprites/animations/partyHeal.png", + "frames":9, + "alpha":1, + "aspeed":"slow", + "exact":True, + "y":6, + }, + "curse_new":{ + "file":"/images/sprites/animations/curse.png", + "frames":6, + "alpha":1, + "aspeed":"slow", + "exact":True, + "y":6, + }, + "transport":{ + "file":"/images/sprites/animations/Teleport2.png", + "frames":9, + "alpha":0.8, + "continuous":True, + }, + "typing":{ + "file":"/images/sprites/animations/typingAnim.png", + "frames":4, + "alpha":1, + "aspeed":"slow", + "continuous":True, + "bubble":True, + }, + "revival":{ + "file":"/images/sprites/animations/Teleport1P.png", + "frames":12, + "alpha":0.8, + "speeding":True, + "continuous":True, + }, + # "invincible":{ + # "file":"/images/sprites/animations/TeleportInv.png", #Doesn't look very good + # "frames":9, + # "alpha":0.8, + # }, + "invincible":{ + "file":"/images/sprites/animations/Shield1.png", + "frames":9, + "alpha":0.8, + "continuous":True, + }, + "gm":{ + "file":"/images/sprites/animations/Shield_Invincible.png", + "frames":9, + "alpha":0.8, + "continuous":True, + }, + "hardshell":{ + "file":"/images/sprites/animations/warrior_shield.png", + "frames":9, + "alpha":0.8, + "aspeed":"slow", + "continuous":True, + }, + "reflection":{ + "file":"/images/sprites/animations/reflection.png", + "frames":9, + "alpha":0.8, + "aspeed":"slow", + "continuous":True, + }, + "tiling_burst":{ + "file":"/images/sprites/animations/burst.png", + "frames":1, + "alpha":1, + "fade":True, + "tiling":True, + }, + "tiling_burst_g":{ #green + "file":"/images/sprites/animations/eburst.png", + "frames":1, + "alpha":1, + "fade":True, + "tiling":True, + }, + "tiling_burstj":{ + "file":"/images/sprites/animations/lightningBurst3.png", + "frames":1, + "alpha":1, + "fade":True, + "tiling":True, + }, + "light":{ + "file":"/images/sprites/animations/Light.png", + "frames":11, + "alpha":0.7, + }, + # "success":{ + # "file":"/images/sprites/animations/CGreen_Spark0.png", #custom, upgrade success [10/08/16] + # "frames":10, + # }, + # "failure":{ + # "file":"/images/sprites/animations/CRed_Spark0.png", #custom, upgrade failure [10/08/16] + # "frames":10, + # }, + "success":{ + "file":"/images/sprites/animations/CGreen_Spark3.png", + "frames":10, + }, + "failure":{ + "file":"/images/sprites/animations/CRed_Spark5.png", + "frames":10, + }, + # "purple_success":{ + # "file":"/images/sprites/animations/CPurple_Spark.png", + # "frames":10, + # }, + "mluck":{ + "file":"/images/sprites/animations/Consume0.png", + "frames":13, + }, + "gold_anim":{ + "file":"/images/sprites/animations/gold_anim.png", + "frames":13, + }, + "rspeed":{ + #"file":"/images/sprites/animations/PuffR.png", + #"frames":14, + "file":"/images/sprites/animations/ConsumeR.png", + "frames":13, + }, + "exchange":{ + "file":"/images/sprites/animations/Consume2.png", + "frames":13, + }, + "heal":{ + "file":"/images/sprites/animations/ConsumeP.png", + "frames":13, + }, + "taunt":{ + "file":"/images/sprites/animations/Puff.png", + "frames":7, + "alpha":1, + }, + "burst":{ + "file":"/images/sprites/animations/Electric.png", + "frames":6, + "alpha":0.7, + }, + "gburst":{ + "file":"/images/sprites/animations/ElectricG.png", + "frames":6, + "alpha":0.7, + }, + "flare_blue":{ + "file":"/images/sprites/animations/flare_effect_blue.png", + "frames":9, + "alpha":0.7, + }, + "flare_yellow":{ + "file":"/images/sprites/animations/flare_effect_yellow.png", + "frames":9, + "alpha":0.7, + }, + "tangle":{ + "file":"/images/sprites/animations/Tangle.png", + "frames":6, + "alpha":1, + "alpha":1, + "proportional":True, + "continuous":True, + "aspeed":"slow", + }, + "dampened":{ + "file":"/images/sprites/animations/Dampen.png", + "frames":6, + "alpha":1, + "alpha":1, + "proportional":True, + "continuous":True, + "aspeed":"slow", + }, + "curse":{ + "file":"/images/sprites/animations/Poison.png", + "frames":8, + "alpha":0.9, + "proportional":True, + "aspeed":"slow", + }, + "stunned":{ + "file":"/images/sprites/animations/NuclearA1.png", + "frames":6, + "alpha":0.4, + }, + # "cursed":{ + # "file":"/images/sprites/animations/Sick.png", + # "frames":4, + # "alpha":0.9, + # } + # "blood0":{ + # "file":"/images/sprites/animations/BloodSplatter0.png", # physical-hit + # "frames":9, + # }, + # "blood3":{ + # "file":"/images/sprites/animations/BloodSplatter3.png", # physical-hit + # "frames":7, + # }, + "confetti":{ + "file":"/images/sprites/animations/confetti2.png", + "frames":12, + "alpha":0.4, + }, +} + +from projectiles import projectiles +for id in projectiles: + if projectiles[id].has_key("animation") and animations[projectiles[id]["animation"]].has_key("speed"): + animations[projectiles[id]["animation"]]["speed"]=projectiles[id]["speed"] \ No newline at end of file diff --git a/design/classes.py b/design/classes.py new file mode 100644 index 0000000..a591a73 --- /dev/null +++ b/design/classes.py @@ -0,0 +1,515 @@ +classes={ + "warrior":{ + "description":"Warriors are strong melee characters. Ideal for both PVE and PVP. Can't go wrong with a warrior.", + "stats":{ + "str":10, + "dex":2, + "int":2, + "vit":4, + "for":2, + }, + "lstats":{ + "str":1, + "dex":0.25, + "int":0.25, + "vit":0.4, + "for":0.025, + }, + "main_stat":"str", + #"skins":{"male":"mwarrior2","female":"fwarrior","unknown":""}, + "looks":[ + ["marmor6d",{"head":"makeup117","hair":"hairdo105"}], + ["sarmor2d",{"head":"fmakeup01","hair":"hairdo120"}], + ["marmor6d",{"head":"makeup105","hair":"hairdo105"}], + ["sarmor2d",{"head":"fmakeup03","hair":"hairdo120"}], + ], + #"rewards":{ + # "l60":{"level":60,"reward":[[1,"open","cosmo0"]]}, + #}, + "xcx":[], #auto populated + "phresistance":10, + "attack":60, + "output":100, + "armor":20, + "resistance":2, + "range":18, + "hp":200, + "mp":20, + "speed":55, + "damage_type":"physical", + "frequency":0.5, + "mp_cost":1, + "mainhand":{ + "spear":{ + "speed":-2, + }, + "short_sword":{ + }, + "sword":{ + "speed":-5, + }, + "fist":{ + "frequency":6, + }, + "mace":{ + "speed":-4, + "frequency":-8, + }, + }, + "doublehand":{ + "rapier":{ + "frequency":60, + "miss":2, + "mp_cost":4, + }, + "bow":{ + "miss":50, + "speed":-12, + "frequency":-40, + }, + "axe":{ + "frequency":-10, + "mp_cost":6, + "speed":-7, + }, + "scythe":{ + "frequency":-11, + "mp_cost":8, + "speed":-6, + }, + "basher":{ + "frequency":-12, + "mp_cost":12, + "speed":-12, + }, + "great_sword":{ + "frequency":-8, + "mp_cost":6, + "speed":-5, + }, + }, + "offhand":{ + "shield":{ + "speed":-2, + }, + "short_sword":{ + "speed":-5, + }, + "sword":{ + "speed":-5, + }, + "misc_offhand":{ + "frequency":-12, + "speed":-8, + }, + "fist":{ + "frequency":6, + }, + "mace":{ + "speed":-5, + "frequency":-6, + }, + }, + "base_slots":{"mainhand":{"name":"blade","level":0,"gift":1}}, + "brave":True, + "projectile": "momentum", + "courage":5, + "mcourage":2, + "pcourage":2, + }, + "paladin":{ + "description":"Paladins are an unbalanced mix-use class!", + "stats":{ + "str":10, + "dex":2, + "int":10, + "vit":4, + "for":5, + }, + "lstats":{ + "str":1, + "dex":0.05, + "int":1, + "vit":0.4, + "for":0.2, + }, + "main_stat":"str", + "side_stat":"int", + "looks":[ + ["marmor4b",{"head":"makeup117","hair":"hairdo515"}], + ["marmor4b",{"head":"fmakeup01","hair":"hairdo405"}], + ["marmor4b",{"head":"makeup105","hair":"hairdo515"}], + ["marmor4b",{"head":"fmakeup03","hair":"hairdo405"}], + ], + "attack":60, + "output":100, + "stresistance":10, + "bmresistance":10, + "armor":20, + "resistance":2, + "range":15, + "hp":300, + "mp":50, + "speed":45, + "damage_type":"physical", + "frequency":0.4, + "mp_cost":2, + "mainhand":{ + "mace":{ + }, + "short_sword":{ + "speed":-3, + "output":-5, + }, + "sword":{ + "speed":-7, + "frequency":-5, + "output":-5, + }, + }, + "doublehand":{ + }, + "offhand":{ + "shield":{ + "speed":-3, + }, + "source":{}, + "misc_offhand":{}, + }, + "base_slots":{"mainhand":{"name":"mace","level":0,"gift":1}}, + "projectile": "momentum", + "courage":2, + "mcourage":4, + "pcourage":5, + }, + "rogue":{ + "description":"Rogue's are the ideal assassins. Their invis ability makes them super-fun for PVP. They are fast. Not ideal for beginners.", + "stats":{ + "str":4, + "dex":10, + "int":3, + "vit":3, + "for":2, + }, + "lstats":{ + "str":0.20, + "dex":1, + "int":0.20, + "vit":0.3, + "for":0.025, + }, + "main_stat":"dex", + # "mrogue", "frogue" + "looks":[ + ["sbody1c",{"head":"makeup117","hair":"hairdo522","chin":"beard112"}], + ["sarmor1h",{"head":"fmakeup01","hair":"hairdo210"}], + ["sbody1c",{"head":"makeup105","hair":"hairdo522","chin":"beard112"}], + ["sarmor1h",{"head":"fmakeup03","hair":"hairdo210"}], + ], + "attack":45, + "output":100, + "armor":15, + "resistance":10, + "fzresistance":10, + "range":15, + "hp":120, + "mp":30, + "speed":50, + "damage_type":"physical", + "frequency":0.45, + "mp_cost":1, + "mainhand":{ + "fist":{}, + "dagger":{}, + "stars":{ + "frequency":20, + }, + }, + "doublehand":{ + "rapier":{ + "frequency":70, + }, + "bow":{ + "miss":30, + "speed":-10, + "frequency":-30, + }, + "spear":{ + "speed":-3, + "frequency":16, + }, + "short_sword":{}, + }, + "offhand":{ + "fist":{}, + "dagger":{}, + "stars":{}, + "misc_offhand":{ + "speed":-4, + }, + }, + "base_slots":{"mainhand":{"name":"claw","level":0,"gift":1}}, + "projectile": "momentum", + "courage":2, + "mcourage":2, + "pcourage":2, + }, + "ranger":{ + "description":"Rangers are skilled archers. Expert trackers. Their high range makes them very suitable for beginners.", + "stats":{ + "str":3, + "dex":10, + "int":8, + "vit":2, + "for":1, + }, + "lstats":{ + "str":0.20, + "dex":1, + "int":0.25, + "vit":0.3, + "for":0.020, + }, + "main_stat":"dex", + # "mranger2", "franger" + "looks":[ + ["marmor5a",{"head":"makeup117","hair":"hairdo106"}], + ["mbody2b",{"head":"fmakeup01","hair":"hairdo206","makeup":"facemakeup02"}], + ["marmor5a",{"head":"makeup105","hair":"hairdo106"}], + ["mbody2b",{"head":"fmakeup03","hair":"hairdo206","makeup":"facemakeup02"}], + ], + "attack":45, + "output":100, + "armor":10, + "pnresistance":10, + "resistance":80, + "range":15, + "hp":160, + "mp":60, + "speed":45, + "damage_type":"physical", + "frequency":0.40, + "mp_cost":2, + "mainhand":{ + "bow":{ + "speed":-3, + }, + "crossbow":{ + "apiercing":120, + "frequency":-36, + } + }, + "doublehand":{ + "fist":{}, + "dagger":{}, + }, + "offhand":{ + "quiver":{}, + }, + "base_slots":{"mainhand":{"name":"bow","level":0,"gift":1}}, + "projectile": "momentum", + "courage":2, + "mcourage":2, + "pcourage":2, + }, + "mage":{ + "description":"Mage's are the ideal characters for beginners. They are easy and fun to play. Both PVE and PVP.", + "stats":{ + "str":2, + "dex":3, + "int":10, + "vit":3, + "for":2, + }, + "lstats":{ + "str":0.20, + "dex":0.20, + "int":1, + "vit":0.3, + "for":0.020, + }, + "main_stat":"int", + # "mmage", "fmage" + "looks":[ + ["marmor12d",{"head":"makeup117"}], + ["mbody5f",{"head":"fmakeup01"}], + ["marmor12d",{"head":"makeup105"}], + ["mbody5f",{"head":"fmakeup03"}], + ], + "xcx":["marmor12f","mbody5h","hairdo402"], + "attack":30, + "output":100, + "armor":2, + "resistance":5, + "range":120, + "hp":70, + "mp":300, + "speed":45, + "damage_type":"magical", + "frequency":0.35, + "mp_cost":5, + "mainhand":{ + "staff":{ + "speed":-4, + }, + "wblade":{ + "speed":-5, + }, + "wand":{ + "frequency":60, + "mp_cost":-18, + } + }, + # "overload":{ + # "great_staff":{ + # "speed":-6, + # "frequency":-20, + # }, + # }, + "doublehand":{ + "great_staff":{ + "speed":-12, + "frequency":-10, + "mp_cost":160, + }, + }, + "offhand":{ + "source":{}, + "misc_offhand":{ + "speed":-4, + }, + }, + "base_slots":{"mainhand":{"name":"staff","level":0,"gift":1}}, + "projectile": "magic", + "courage":2, + "mcourage":3, + "pcourage":2, + }, + "priest":{ + "description":"Priest's are the healers of the realm. They are not ideal for beginners or solo players. They can't inflict a lot of damage. Every serious party needs at least one priest.", + "stats":{ + "str":2, + "dex":3, + "int":10, + "vit":4, + "for":3, + }, + "lstats":{ + "str":0.20, + "dex":0.20, + "int":1, + "vit":0.4, + "for":0.025, + }, + "main_stat":"int", + # "mpriest", "fpriest" + "looks":[ + ["marmor12c",{"head":"makeup117"}], + ["mbody5e",{"head":"fmakeup01"}], + ["marmor12c",{"head":"makeup105"}], + ["mbody5e",{"head":"fmakeup03"}], + ], + "xcx":["marmor12e","mbody5g","hairdo402"], + "attack":30, + "output":40, + "armor":2, + "resistance":5, + "range":120, + "hp":70, + "mp":300, + "speed":45, + "damage_type":"magical", + "frequency":0.35, + "mp_cost":5, + "mainhand":{ + "pmace":{ + "speed":-2, + }, + "staff":{ + "speed":-4, + }, + }, + "doublehand":{ + "wand":{ + "frequency":40, + } + }, + "offhand":{ + "shield":{ + "speed":-5, + }, + "source":{}, + "misc_offhand":{ + "speed":-4, + }, + }, + "base_slots":{"mainhand":{"name":"staff","level":0,"gift":1}}, + "projectile": "pmagic", + "courage":2, + "mcourage":5, + "pcourage":2, + }, + "merchant":{ + "description":"While your main characters are out there adventuring, merchants can wait in town and market your loots. Server and character limits don't apply to merchants. They gain experience when they sell or buy something.", + "stats":{ + "str":1, + "dex":4, + "int":12, + "vit":1, + "for":0, + }, + "lstats":{ + "str":0.10, + "dex":0.40, + "int":1, + "vit":0.25, + "for":0, + }, + "main_stat":"int", + # "mmerchant", "fmerchant" + "looks":[ + ["marmor12a",{"head":"makeup117","hair":"hairdo521","hat":"hat404"}], + ["marmor12b",{"head":"fmakeup01","hair":"hairdo520"}], + ["marmor12a",{"head":"makeup105","hair":"hairdo521","hat":"hat404"}], + ["marmor12b",{"head":"fmakeup03","hair":"hairdo520"}], + ], + "attack":10, + "output":10, + "armor":20, + "resistance":20, + "range":20, + "hp":40, + "mp":200, + "speed":55, + "damage_type":"none", + "frequency":0.05, + "mp_cost":10, + "mainhand":{ + "mace":{"speed":-10}, + "staff":{"speed":-4}, + "bow":{"speed":-6}, + "spear":{"speed":-5}, + "short_sword":{"speed":-5}, + "fist":{"speed":-2}, + "dartgun":{}, + "dagger":{"speed":-3}, + }, + "doublehand":{ + "rod":{"speed":-20}, + "pickaxe":{"speed":-20}, + "axe":{"speed":-20}, + "basher":{"speed":-26}, + }, + "offhand":{ + "shield":{"speed":-8}, + "source":{}, + "quiver":{"speed":-2}, + "misc_offhand":{"speed":-3}, + }, + "base_slots":{"mainhand":{"name":"staff","level":0,"gift":1}}, + "projectile": "momentum", + "courage":1, + "mcourage":0, + "pcourage":0, + }, +} \ No newline at end of file diff --git a/design/conditions.py b/design/conditions.py new file mode 100644 index 0000000..4d15dfa --- /dev/null +++ b/design/conditions.py @@ -0,0 +1,640 @@ +from design.games import games + +conditions={ + "tangled":{ + "name":"Tangled", + "skin":"condition_bad", + "ui":False, + "debuff":True, + "set_speed":24, + "duration":12000, + }, + "sugarrush":{ + "skin":"candycanesword", + "name":"Sugar Rush", + "frequency":240, + "duration":10*1000, + "mp_cost":-200, + "buff":True, + "ui":True, + }, + "power":{ + "skin":"powerglove", + "name":"Power", + "frequency":360, + "duration":4*1000, + "mp_cost":-200, + "buff":True, + "ui":True, + }, + "weakness":{ + "skin":"condition_bad", + "name":"Weakness", + "debuff":True, + "ui":True, + "speed":-30, + "dex":-10, + "str":-10, + "duration":20000, + }, + "xpower":{ + "skin":"goldenpowerglove", + "name":"Power", + "frequency":480, + "duration":6*1000, + "mp_cost":-300, + "buff":True, + "ui":True, + }, + "stack":{ + "skin":"skill_stack", + "name":"Pure Damage", + "explanation":"Bonus damage for each rogue attack", + "debuff":True, + }, + "woven":{ + "skin":"spidersilk", + "name":"Woven", + "explanation":"Slowed down from all the spider silk sticking around.", + "ui":True, + "debuff":True, + "speed":-10, + "duration":1000, + }, + "energized":{ + "skin":"skill_energize", + "name":"Energized", + "buff":True, + "frequency":80, + "duration":800, + "buff":True, + "ui":True, + }, + "mcourage":{ + "skin":"skill_mcourage", + "name":"Merchant's Courage", + "speed":25, + "evasion":40, + "courage":5, + "mcourage":5, + "pcourage":5, + "duration":10000, + "ui":True, + "buff":True, + }, + "mfrenzy":{ + "skin":"skill_mfrenzy", + "name":"Merchant's Frenzy", + "frequency":800, + "duration":5000, + "mp_cost":-20, + "output":40, + "ui":True, + "buff":True, + }, + "mshield":{ + "skin":"skill_mshield", + "name":"Mana Shield", + "ui":True, + "buff":True, + }, + "phasedout":{ + "skin":"skill_phaseout", + "name":"Phased Out", + "frequency":-40, + "speed":-16, + "evasion":64, + "duration":5000, + "ui":True, + "buff":True, + }, + "hardshell":{ + "skin":"skill_hardshell", + "name":"Hard Shell", + "armor":800, + "set_speed":10, + "duration":8000, + "buff":True, + }, + "reflection":{ + "skin":"buff_reflection", + "name":"Reflective Shield", + "reflection":20, + "cap_reflection":50, + "duration":5000, + "ui":True, + "buff":True, + }, + "eburn":{ + "skin":"essenceoffire", + "name":"Burn", + "intensity":"burnd", + "interval":200, + "damage":50, + "duration":12*1000, + "speed":5, + "ui":True, + "debuff":True, + }, + "newcomersblessing":{ + "skin":"newcomersblessing", + "name":"Newcomers' Blessing", + "duration":30*60*1000, + "luck":10, + "gold":10, + "xp":10, + "aura":True, + "ui":True, + "persistent":True, + }, + "eheal":{ + "skin":"essenceoflife", + "name":"Rejuvenate", + "interval":320, + "heal":200, + "duration":4*1000, + "ui":True, + "buff":True, + }, + "rspeed":{ + "skin":"buff_speed", + "name":"Rogue Swiftness", + "speed":7, + "frequency":8, + "duration":45*60*1000, + "buff":True, + "ui":True, + }, + "massproduction":{ + "skin":"skill_massproduction", + "name":"Mass Production", + "explanation":"Speeds up the next upgrade or compound 50%", + "duration":10*1000, + "buff":True, + "ui":True, + }, + "massproductionpp":{ + "skin":"skill_massproductionpp", + "name":"Mass Production++", + "explanation":"Speeds up the next upgrade or compound 90%", + "duration":10*1000, + "buff":True, + "ui":True, + }, + "darkblessing":{ + "skin":"skill_dbuff", + "name":"Dark Blessing", + "output":25, + "duration":8*1000, + "buff":True, + "ui":True, + }, + "warcry":{ + "skin":"skill_warcry", + "name":"War Cry", + "frequency":10, + "speed":20, + "armor":160, + "resistance":160, + "duration":8*1000, + "buff":True, + "ui":True, + }, + "purifier":{ + "skin":"skill_purify", + "name":"Purifier", + "frequency":20, + "output":20, + "str":30, + "duration":8*1000, + "buff":True, + "ui":True, + }, + "mluck":{ + "skin":"buff_luck", + "name":"Good Luck", + "luck":12, + "duration":60*60*1000, + "buff":True, + "ui":True, + "persistent":True, + }, + "withdrawal":{ + "skin":"withdrawal", + "name":"Withdrawal", + "speed":-20, + "frequency":-30, + "dex":-20, + "str":-5, + "mp":-300, + "duration":180*60*1000, + "ui":True, + "debuff":True, + "persistent":True, + }, + "penalty_cd":{ + "skin":"condition_bad", + "name":"Penalty Cooldown", + "explanation":"The remaining duration of this condition is added any skill you use. Teleporting adds 3s, magiporting adds around 800ms, some item operations add 100-200ms.", + "debuff":True, + }, + "xshotted":{ + "skin":"xshotted", + "name":"X-Shot", + "explanation":"Good luck trying to find a tavern to play in.", + "duration":12*60*60*1000, + "debuff":True, + "ui":True, + "persistent":True, + }, + "notverified":{ + "skin":"notverified", + "name":"Not Verified", + "explanation":"Reduced luck and gold until the associated email address is verified.", + "luck":-25, + "gold":-25, + "debuff":True, + "technical":True, + "ui":True, + "persistent":True, + }, + "authfail":{ + "skin":"notverified", + "name":"Authorization Failure", + "explanation":"Your account has failed an internal authorization routine. This might've happened if you haven't logged on from Steam or Mac App Store since this new system was implemented. So just opening the non-web game client once, starting one character, hanging 1-2 minutes on a server and logging out will be enough to correct this mistake. If it persists unexpectedly email hello@adventure.land", + "luck":-85, + "gold":-85, + "xp":-20, + "debuff":True, + "technical":True, + "ui":True, + "persistent":True, + }, + "hopsickness":{ + "skin":"condition_bad", + "name":"Hop Sickness", + "explanation":"You are not in your home server! Go see Bean in Mainland square for a change.", + "luck":-80, + "gold":-80, + "xp":-80, + "output":-20, + "ui":True, + "debuff":True, + "persistent":True, + "duration":1000*60*12, + "special":"snakeoil", + }, + "fullguard":{ + "skin":"fullguard", + "name":"Full Guard", + "ui":True, + "resistance":10000, + "armor":10000, + "buff":True, + "persistent":True, + }, + "fullguardx":{ + "skin":"fullguard", + "name":"Full Guard", + "ui":True, + "avoidance":99, + "buff":True, + "persistent":True, + }, + "stunned":{ + "name":"Stunned", + "skin":"condition_bad", + "ui":True, + "blocked":True, + "debuff":True, + "duration":3200, + }, + "deepfreezed":{ + "name":"Deepfreezed", + "skin":"condition_bad", + "duration":12000, + "ui":True, + "blocked":True, + "debuff":True, + }, + "invincible":{ + "name":"Invincible", + "skin":"condition_positive", + "explanation":"When you spawn in a PVP area. This prevents you from receiving damage or marked as engaged in PVP. If you get attacked, disconnect before this runs out - or fight!", + "duration":6000, + "persistent":True, + }, + "frozen":{ + "name":"Frozen", + "skin":"frostbow", + "ui":True, + "debuff":True, + "duration":5000, + }, + "burned":{ + "name":"Burned", + "skin":"fireblade", + "interval":210, + "ui":True, + "debuff":True, + }, + "shocked":{ + "name":"Shocked", + "skin":"essenceofthunder", + "explanation":"Imminent magical damage", + "duration":1600, + "ui":True, + "debuff":True, + }, + "fingered":{ + "name":"Deep Meditation", + "skin":"condition_neutral", + "resistance":1600, + "evasion":96, + "blocked":True, + "debuff":True, + }, + "stoned":{ + "name":"Stoned", + "skin":"condition_neutral", + "duration":4000, + "blocked":True, + "debuff":True, + }, + "easterluck":{ + "skin":"easterluck", + "name":"Easter Luck", + "luck":100, + "duration":24*60*60*1000, + "buff":True, + "ui":True, + "persistent":True, + }, + "sanguine":{ + "skin":"sanguine", + "lifesteal":1, + "name":"Vampiric Aura", + "attr0":"lifesteal", + "buff":True, + "ui":True, + "aura":True, + "duration":30*1000, + }, + "mlifesteal":{ + "skin":"lifestealscroll", + "name":"Lifesteal", + "lifesteal":2.5, + "duration":60*60*1000, + "buff":True, + "ui":True, + }, + "holidayspirit":{ + "skin":"holidayspirit", + #"name":"Xmas Spirit", + "name":"Holiday Spirit", + "luck":20, + "gold":20, + "xp":20, + "duration":24*60*60*1000, + "buff":True, + "ui":True, + "persistent":True, + }, + "halloween0":{ + "skin":"halloween0", + "name":"Halloween Spirit", + "luck":5, + "gold":5, + "xp":100, + "duration":48*60*60*1000, + "buff":True, + "ui":True, + "persistent":True, + }, + "halloween1":{ + "skin":"halloween1", + "name":"Halloween Spirit", + "luck":5, + "gold":5, + "xp":50, + "output":2, + "duration":24*60*60*1000, + "buff":True, + "ui":True, + "persistent":True, + }, + "halloween2":{ + "skin":"halloween2", + "name":"Halloween Spirit", + "output":3, + "luck":5, + "gold":5, + "xp":10, + "duration":8*60*60*1000, + "buff":True, + "ui":True, + "persistent":True, + }, + # "xmas":{ + # "skin":"xmas", + # #"name":"Xmas Spirit", + # "name":"Blessing of 2018", + # "luck":200, + # "gold":200, + # "xp":200, + # "duration":24*60*60*1000, + # "buff":True, + # "ui":True, + # }, + # "xmas2":{ + # "skin":"xmas", + # #"name":"Xmas Spirit", + # "name":"Blessing of 2019", + # "luck":50, + # "gold":50, + # "xp":50, + # "evasion":10, + # #"ability":"secondchance", + # #"attr0":20, + # "duration":48*60*60*1000, + # "buff":True, + # "ui":True, + # "note":"Technically our third new year, second year of our tree and the buff :)" + # }, + "slowness":{ + "skin":"slowness", + "name":"Slowness", + "skin":"condition_neutral", + "explanation":"Things like spiderwebs cause you to slow down.", + "speed":-40, + "ui":True, + "debuff":True, + }, + "poisoned":{ + "name":"Poison", + "skin":"poison", + "duration":5000, + "frequencym":0.8, + "potionsm":0.5, + "healm":0.25, + "debuff":True, + }, + "cursed":{ + "name":"Cursed", + "skin":"condition_bad", + "output":-20, + "incdmgamp":20, + "speed":-20, + "duration":5000, + "debuff":True, + }, + "dampened":{ + "name":"Dampened", + "skin":"dampened", + "explanation":"Can't blink or teleport", + "duration":300, + "debuff":True, + }, + "poisonous":{ + "skin":"skill_pcoat", + "name":"Poisonous", + "ui":True, + "buff":True, + "duration":5000, + }, + "invis":{ + "skin":"skill_invis", + "name":"Invisible", + "explanation":"Hidden from everyone else until you attack", + "buff":True, + }, + "licenced":{ + "skin":"licence", + "name":"Licenced to Kill", + "explanation":"A special, temporary immunity", + "ui":True, + "buff":True, + }, + "charmed":{ + "skin":"charmer", + "name":"Charmed", + "explanation":"Mellow like a warm kitty", + "ui":True, + "duration":30000, + "debuff":True, + }, + "monsterhunt":{ + "skin":"quest_monsterhunt", + "name":"On The Hunt", + "ui":True, + "duration":1800000, + "persistent":True, + }, + "marked":{ + "skin":"skill_huntersmark", + "name":"Marked", + "explanation":"Marked by a ranger for death. Receive 10% more damage and can't stealth.", + "ui":True, + "incdmgamp":10, + "duration":10000, + "debuff":True, + }, + "charging":{ + "name":"Charging", + "skin":"condition_positive", + "speed":30, + "duration":3200, + }, + "dash":{ + "name":"Dashing", + "skin":"condition_positive", + "set_speed":500, + "persistent":True, + }, + "blink":{ + "name":"Blinking", + "skin":"condition_positive", + "explanation":"Blink in progress", + }, + "block":{ + "name":"PVP Block", + "skin":"condition_neutral", + "explanation":"After engaging in PVP, blocked from safely leaving!", + "debuff":True, + "persistent":True, + }, + "town":{ + "name":"Town", + "skin":"condition_positive", + "explanation":"Town in progress", + "channel":True, + "can_move":True, + "duration":3000, + }, + "fishing":{ + "name":"Fishing", + "skin":"skill_fishing", + "explanation":"Fishing in progress", + "channel":True, + "duration_min":5000, + "duration":15000, + }, + "mining":{ + "name":"Mining", + "skin":"skill_mining", + "explanation":"Mining in progress", + "channel":True, + "duration_min":5000, + "duration":15000, + }, + "pickpocket":{ + "name":"Pickpocket", + "skin":"skill_pickpocket", + "explanation":"Pickpocket in progress", + "channel":True, + "duration_min":200, + "duration":2200, + }, + "sleeping":{ + "debuff":True, + "name":"Sleeping", + "duration_min":3000, + "duration":8000, + }, +} + +if 0: + for name in games["tarot"]["cards"]: + conditions["tarot_%s"%name]={"skin":"tarot","name":"Tarot Card","type":"tarot","ui":True} + for (num,val) in [["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9],["10",10],["ace",20],["king",15],["knight",17],["page",12],["queen",14]]: + color="" + if num in name and "swords" in name: + conditions["tarot_%s"%name]["str"]=val; color="swords" + if num in name and "wands" in name: + conditions["tarot_%s"%name]["int"]=val; color="wands" + if num in name and "cups" in name: + conditions["tarot_%s"%name]["dex"]=val; color="cups" + if num in name and "pentacles" in name: + conditions["tarot_%s"%name]["vit"]=-val; color="pentacles" + if color: + conditions["tarot_%s"%name]["minor"]="%s_%s"%(num,color) + conditions["tarot_%s"%name]["card"]="%s of %s"%(color.title(),num.title()) + if name=="fool": + conditions["tarot_%s"%name]["miss"]=50 + if name=="chariot": + conditions["tarot_%s"%name]["speed"]=16 + if name=="death": + conditions["tarot_%s"%name]["vit"]=-30 + conditions["tarot_%s"%name]["frequency"]=-30 + conditions["tarot_%s"%name]["speed"]=-20 + if name=="devil": + conditions["tarot_%s"%name]["xp"]=-99 + conditions["tarot_%s"%name]["luck"]=-99 + conditions["tarot_%s"%name]["vit"]=10 + conditions["tarot_%s"%name]["str"]=10 + if not conditions["tarot_%s"%name].get("minor"): + conditions["tarot_%s"%name]["card"]=name.title() + conditions["tarot_%s"%name]["major"]=name + + + diff --git a/design/cosmetics.py b/design/cosmetics.py new file mode 100644 index 0000000..9f061b5 --- /dev/null +++ b/design/cosmetics.py @@ -0,0 +1,252 @@ +cosmetics={ + "default_head_place":7, + "default_hair_place":7, #previously 6 [01/05/20] + "default_hat_place":7, + "default_face_position":8, + "default_makeup_position":0, + "default_beard_position":0, + "no_upper":[], + "map":{ + "old":"new", + }, + "bundle":{ + "rogueb":["sbody1c","sarmor1h"], + "blackw":["mbody6b","mbody6c","blackhead"], + "pinkb":["mbody2g","mbody2h"], + }, + "prop":{ + #Sizes(SSU): "bulky", "slender" + #"hair": Can have hair + #"no_upper": Can't wear other clothes + #"no_hair": Can't put on hair + #"no_hat": Can't put on hat + #"covers": Head appears underneath + "lchar1b":["hair"], + "lchar1d":["bulky"], + "lchar1e":["female"], + "lchar1f":["no_upper"], + "lchar1g":["no_upper"], + "lchar1h":["bulky","hair"], + "marmor12b":["slender"], + "marmor12c":["covers","no_hair"], + "marmor12d":["covers","no_hair"], + "mbody5e":["covers","no_hair"], + "mbody5f":["covers","no_hair"], + "mbody6b":["covers","no_hair"], + "mbody6c":["covers"], + "mbody2g":["covers","no_hair"], + #"mbody2h":["covers"], + "bathat":["manim","fast"], + }, + "head":{ #small, normal, large, dh + "bwhead":["sskin1e","mbw","lskin1d"], + "makeup100":["sskin1e","mskin1e","lskin1d"], + "makeup101":["sskin1e","mskin1e","lskin1d",1], + "makeup102":["sskin1c","mskin1c","lskin1c"], + "mmakeup04":["sskin1c","mskin1c","lskin1c"], + "mmakeup05":["sskin1c","mskin1c","lskin1c"], + "makeup103":["sskin1c","mskin1c","lskin1c",1], + "fmakeup10":["sskin1b","mskin1b","lskin1b",1], + "fmakeup11":["sskin1b","mskin1b","lskin1b",1], + "makeup104":["sskin1b","mskin1b","lskin1b",1], + "makeup105":["sskin1b","mskin1b","lskin1b"], + "fmakeup02":["sskin1b","mskin1b","lskin1b"], + "fmakeup03":["sskin1b","mskin1b","lskin1b"], + #"newfmakeup00":["sskin1e","mskin1e","lskin1d"], + #"newfmakeup01":["sskin1e","mskin1e","lskin1d"], + "makeup106":["sskin1d","mskin1d","lskin1d",1], + "blackhead":["sskin1d","mskin1d","lskin1d"], + "makeup107":["sskin1d","mskin1d","lskin1d"], + "makeup108":["sskin1b","mskin1b","lskin1b",1], + "makeup109":["sskin1b","mskin1b","lskin1b"], + "fmakeup07":["sskin1e","mskin1e","lskin1d",1], + "fmakeup08":["sskin1e","mskin1e","lskin1d",1], + "fmakeup09":["sskin1e","mskin1e","lskin1d",1], + "fmakeup12":["sskin1e","mskin1e","lskin1d",1], + "makeup110":["sskin1e","mskin1e","lskin1d",1], + "makeup111":["sskin1e","mskin1e","lskin1d"], + "mmakeup10":["sskin1f","mskin1f","lskin1a",1], + "makeup112":["sskin1f","mskin1f","lskin1a",1], + "makeup113":["sskin1f","mskin1f","lskin1a"], + "fmakeup05":["sskin1c","mskin1c","lskin1c"], + "makeup114":["sskin1c","mskin1c","lskin1c"], + "makeup115":["sskin1c","mskin1c","lskin1c"], + "makeup116":["sskin1a","mskin1a","lskin1a",1], + "makeup117":["sskin1a","mskin1a","lskin1a"], + "makeup118":["sskin1e","mskin1e","lskin1d"], + "makeup119":["sskin1e","mskin1e","lskin1d",1], + "mmakeup07":["sskin1h","mskin1h","lskin1d",1], + "makeup120":["sskin1h","mskin1h","lskin1d",1], + "makeup121":["sskin1h","mskin1h","lskin1d"], + "makeup122":["sskin1d","mskin1d","lskin1d"], + "makeup123":["sskin1e","mskin1e","lskin1d"], + "makeup124":["sskin1b","mskin1b","lskin1b"], + "makeup125":["sskin1b","mskin1b","lskin1b"], + "makeup126":["sskin1e","mskin1e","lskin1d"], + "makeup127":["sskin1e","mskin1e","lskin1d"], + "makeup128":["sskin1c","mskin1c","lskin1c"], + "makeup129":["sskin1c","mskin1c","lskin1c",1], + "makeup130":["sskin1g","mskin1g","lskin1a"], + "fmakeup06":["sskin1g","mskin1g","lskin1a"], + "makeup131":["sskin1g","mskin1g","lskin1a"], + "makeup132":["sskin1b","mskin1b","lskin1b",1], + "makeup133":["sskin1e","mskin1e","lskin1d"], + "makeup134":["sskin1e","mskin1e","lskin1d",1], + "mmakeup01":["sskin1b","mskin1b","lskin1b"], + "mmakeup02":["sskin1b","mskin1b","lskin1b"], + "mmakeup06":["sskin1b","mskin1b","lskin1b"], + "mmakeup08":["sskin1b","mskin1b","lskin1b"], + "mmakeup12":["sskin1b","mskin1b","lskin1b"], + "makeup135":["sskin1b","mskin1b","lskin1b"], + "makeup136":["sskin1e","mskin1e","lskin1d"], + "makeup137":["sskin1b","mskin1b","lskin1b"], + "makeup138":["sskin1b","mskin1b","lskin1b"], + "makeup139":["sskin1d","mskin1d","lskin1d"], + "mmakeup09":["sskin1d","mskin1d","lskin1d"], + "mmakeup11":["sskin1d","mskin1d","lskin1d"], + "mmakeup13":["sskin1d","mskin1d","lskin1d"], + "makeup140":["sskin1d","mskin1d","lskin1d"], + "smakeup00":["sskin1a","mskin1a","lskin1a",-1], + }, + # Easiest way to calibrate: servers_eval('reload_server(1,data.reason);',data={'reason':'cx'}) + "hair":{ #dy, dh #after improving the sprite system, all dy's are now 0! [03/07/19] + "bwhair":[-2,1], + "hairdo100":[0,0], + "hairdo101":[0,1], + "hairdo102":[0,2], + "hairdo103":[0,0], + "hairdo104":[0,1], + "hairdo105":[0,0], + "hairdo106":[0,1], + "hairdo107":[0,1], + "hairdo108":[0,1], + "hairdo109":[0,1], + "hairdo110":[0,1], + "hairdo111":[0,0], + "hairdo112":[0,0], + "hairdo113":[0,0], + "hairdo114":[0,0], + "hairdo115":[0,3], + "hairdo116":[0,1], + "hairdo117":[0,2], + "hairdo118":[0,2], + "hairdo119":[0,1], + "hairdo120":[0,1], + "hairdo121":[0,2], + "hairdo122":[0,2], + "hairdo123":[0,0], + "hairdo124":[0,0], + "hairdo200":[0,1], + "hairdo201":[0,1], + "hairdo202":[0,2], + "hairdo203":[0,1], + "hairdo204":[0,1], + "hairdo205":[0,2], + "hairdo206":[0,0], + "hairdo207":[0,0], + "hairdo208":[0,0], + "hairdo209":[0,1], + "hairdo210":[0,0], + "hairdo211":[0,1], + "hairdo212":[0,0], + "hairdo213":[0,2], + "hairdo214":[0,0], + "hairdo215":[0,0], + "hairdo216":[0,1], + "hairdo217":[0,0], + "hairdo218":[0,0], + "hairdo219":[0,0], + "hairdo220":[0,0], + "hairdo221":[0,0], + "hairdo222":[0,0], + "hairdo223":[0,0], + "hairdo224":[0,3], + "hairdo300":[0,0], + "hairdo301":[0,1], + "hairdo302":[0,0], + "hairdo303":[0,1], + "hairdo304":[0,1], + "hairdo305":[0,0], + "hairdo306":[0,0], + "hairdo307":[0,1], + "hairdo308":[0,0], + "hairdo309":[0,1], + "hairdo310":[0,0], + "hairdo311":[0,0], + "hairdo312":[0,0], + "hairdo313":[0,0], + "hairdo314":[0,0], + "hairdo315":[0,0], + "hairdo316":[0,2], + "hairdo317":[0,0], + "hairdo318":[0,0], + "hairdo319":[0,0], + "hairdo320":[0,0], + "hairdo321":[0,1], + "hairdo322":[0,0], + "hairdo323":[0,0], + "hairdo324":[0,0], + "hairdo400":[0,1], + "hairdo401":[0,1], + "hairdo402":[0,4], + "hairdo403":[0,0], + "hairdo404":[0,0], + "hairdo405":[0,3], + "hairdo406":[0,0], + "hairdo407":[0,0], + "hairdo408":[0,0], + "hairdo409":[0,0], + "hairdo410":[0,0], + "hairdo411":[0,0], + "hairdo412":[0,2], + "hairdo413":[0,3], + "hairdo414":[0,0], + "hairdo415":[0,0], + "hairdo416":[0,0], + "hairdo417":[0,0], + "hairdo418":[0,0], + "hairdo419":[0,3], + "hairdo420":[0,2], + "hairdo421":[0,0], + "hairdo422":[0,0], + "hairdo423":[0,0], + "hairdo424":[0,0], + "hairdo500":[0,0], + "hairdo501":[0,1], + "hairdo502":[0,2], + "hairdo503":[0,3], + "hairdo504":[0,0], + "hairdo505":[0,0], + "hairdo506":[0,0], + "hairdo507":[0,1], + "hairdo508":[0,2], + "hairdo509":[0,2], + "hairdo510":[0,2], + "hairdo511":[0,3], + "hairdo512":[0,1], + "hairdo513":[0,1], + "hairdo514":[0,0], + "hairdo515":[0,0], + "hairdo516":[0,1], + "hairdo517":[0,2], + "hairdo518":[0,1], + "hairdo519":[0,0], + "hairdo520":[0,0], + "hairdo521":[0,1], + "hairdo522":[0,1], + "hairdo523":[0,1], + }, + "hat":{ #dy + "hat100":0, + }, + #gravestones + "gravestone":{ + "gravestone":19, + "gravestonea":19, + "xgravestone0":21, + "xgravestone1":21, + "xgravestone2":21, + "xgravestone3":21, + "xgravestone4":21, + }, +} \ No newline at end of file diff --git a/design/crafting.txt b/design/crafting.txt new file mode 100644 index 0000000..a5585e9 --- /dev/null +++ b/design/crafting.txt @@ -0,0 +1,16 @@ +[Kanashikoe] +Basher+Sword=Axe +Axe+Spear=Polearm +Spear+Bow= Crossbow +Bow+FireStaff=Fireshooter Bow +Staff+Spear= Bo Staff +CupidBow+Bow=LongBow +vitring+strring+dexrin+intring= Ring of great joys +[Weapon]+[Weapon]=Greater [Weapon] +Shield+Book= Sage Orb +Sword+Staff=Battle Staff + + + + +Network Card + 100x Electronic Scraps + 85x Mechanical Keycaps = Ancient Computer \ No newline at end of file diff --git a/design/dimensions.py b/design/dimensions.py new file mode 100644 index 0000000..760b079 --- /dev/null +++ b/design/dimensions.py @@ -0,0 +1,1004 @@ +dimensions={ #by trial+error using game.js/border_mode=true + #width, height, width-disp, base.h, base.v + # sprite: [3] positive-> goes left | negative-> goes right + "default_character":[26,35], + "goo":[23,22,-3,1,6], + "goo0":[23,22,0,-1], + "rat":[30,22,-1], + "prat":[30,22,5,6], + "wabbit":[30,22], + "mole":[30,20,-1], + "cgoo":[23,22,-3], + "pinkgoo":[23,22,-1], + "minimush":[23,22,-3], + "bee":[26,33], + "arcticbee":[26,33], + "squig":[34,26,-10,1], + "crabx":[36,26,-1], + "oneeye":[30,40], + "harpy":[44,32,2], + #"crab" dimensions are accurate natively at game.js and default 24,24 at server.js is ok. [03/10/16] + "armadillo":[36,34,-4], + "poisio":[36,34,-4], + "squigtoad":[36,30,-4], + "spider":[30,20,1.5], + "osnake":[30,22,-1], + "snake":[30,24,-1], + "stoneworm":[30,24,-1], + "scorpion":[30,30,1.5], + "bscorpion":[30,30], + "gscorpion":[30,30,1.5], + "xscorpion":[30,30,1.5], + "bat":[38,36,-1], + "grinch":[23,36], + "dknight2":[47,48], + "skeletor":[24,36,-4], + "phoenix":[61,55], + "ghost":[27,35,-2], + "wolfie":[60,48,-3], + "wolf":[60,48,-3], + "iceroamer":[22,36,-2], + "fireroamer":[24,40,-3], + "bbpompom":[32,35,1], + "boar":[42,36,-4], + "croc":[45,32,-3], + "tortoise":[36,27,-3], + "frog":[36,24,-4], + "bigbird":[58,54], + "puppy1":[20,20,0,6,5], + "plantoid":[30,36,-2], + "hen":[20,20], + "rooster":[20,20], + "mechagnome":[18,26], + "rudolph":[60,64,-3], + "ent":[47,50,-3], + "tiger":[42,30], + "pinkgoblin":[26,30], +} +for name in ["puppy2","puppy3","puppy4","kitty1","kitty2","kitty3","kitty4"]: dimensions[name]=dimensions["puppy1"] +for name in ["goo1","goo2","goo3","goo4","goo5","goo6","goo7","goo8","gooD"]: dimensions[name]=dimensions["goo0"] +dimensions["rharpy"]=dimensions["harpy"] +dimensions["harpy_fly"]=dimensions["harpy"] +dimensions["rharpy_fly"]=dimensions["harpy"] +dimensions["jrat"]=dimensions["rat"] +dimensions["goldenbat"]=dimensions["bat"] +dimensions["pppompom"]=dimensions["minimush"]; dimensions["pppompom"][2]=-1 + +positions={ + #UI + "textures":["stone","stand0_texture","standx_texture","standg_texture","cstand_texture","wstand_texture","fstand_texture"], # these are loaded into textures{} in load_game [07/02/17] + "stone":["outside",672,104,16,20], + "stand0_texture":["stands",26*2,0,26,36], + "standx_texture":["stands",26*0,36,26,36], + "standg_texture":["stands",26*2,36,26,36], + "cstand_texture":["stands",26*0,36*2,26,36], + "wstand_texture":["stands",26*0,36*3,26,36], + "fstand_texture":["stands",26*1,36*3,26,36], + "door0":[ + ["custom",0,8*16,32,32], + ["custom",32,8*16,32,32], + ["custom",64,8*16,32,32], + ["custom",96,8*16,32,32], + ["custom",128,8*16,32,32], + ["custom",160,8*16,32,32], + ], + "lever0":[ + ["puzzle",6*16,4*16+8,16,24], + ["puzzle",7*16,4*16+8,16,24], + ["puzzle",8*16,4*16+8,16,24], + ], + #representations + "gold":["",15,26], + "shells":["",3,25], + #npcs + "shrine":["dungeon",45*16,19*16,32,48], + "shrine2":["dungeon",45*16,8*16,32,48], + "lichteaser":["licht",47,0,47,50], + #placeholder + "placeholder_m":["",15,24], #custom fog + "placeholder":["custom",3,1], + #crafting + "cscale":["",4,32], + #items + "shade_gold":["pack_1a",12,14], + "shade_gold":["",8,35], + "shade_cring":["pack_1a",8,64], + "shade_cring":["",7,19], + "shade_uweapon":["pack_1a",14,98], + "shade_uweapon":["",5,8], + "shade_seal":["",11,9], + "shade_lock":["",1,37], + "shade_unlock":["",8,6], + #"shade_cscroll":["pack_1a",2,52], + #"shade_scroll":["pack_1a",11,52], + "shade_cscroll":["",1,24], + "shade_scroll":["",14,23], + #"shade_offering":["pack_1a",0,28], + "shade_offering":["",6,26],#["pack_1a",14,113], + #"shade_helmet":["pack_1a",12,23], + "shade_helmet":["",0,31], + #"shade_pants":["pack_1a",6,4], + #"shade_pants":["pack_1a",2,112], + "shade_pants":["",2,31], + #"shade_chest":["pack_1a",12,4], + "shade_chest":["",6,1], + #"shade_shoes":["pack_1a",13,10], + "shade_shoes":["",3,31], + #"shade_amulet":["pack_1a",7,0], + "shade_amulet":["",12,31], + #"shade_earring":["pack_1a",5,2], + "shade_earring":["",5,17], + #"shade_gloves":["pack_1a",10,22], + "shade_gloves":["",10,2], + #"shade_offhand":["pack_1a",8,73], + "shade_offhand":["",6,31], + #"shade_ring":["pack_1a",9,64], + "shade_ring":["",13,31], + #"shade_mainhand":["pack_1a",15,104], + "shade_mainhand":["",5,31], + "shade_orb":["pack_1a",10,28], + "shade_elixir":["pack_1a",12,40], + "shade_tome":["pack_1a",2,114], + #"shade_belt":["pack_1a",1,0], + "shade_belt":["",4,3], + "shade_exchange":["pack_1a",14,112], + "shade_exchange":["",9,30], + "shade_exchange":["",1,35], + "shade20_cape":["",4,6], + "shade20_orb":["",2,25], + "shade20_elixir":["",0,27], + #"hpot0":["pack_1a",10,38], + #"mpot0":["pack_1a",15,38], + #"hpot1":["pack_1a",8,39], + #"mpot1":["pack_1a",13,39], + "hpot0":["",4,21], + "mpot0":["",5,21], + "hpot1":["",6,21], + "mpot1":["",7,21], + "hpotx":["",12,21], + "mpotx":["",13,21], + #quest-items + "seashell":["",5,25], + "leather":["",6,25], + "gemfragment":["",7,25], + "lostearring":["",4,25], + "glitch":["",9,24], + #gems+boxes + "armorbox":["",1,26], + "weaponbox":["",3,26], + #"gem0":["pack_1a",12,112], #green + "gem0":["",13,25], + #"gem1":["pack_1a",13,114], #pvp-tiny ruby + "gem1":["",10,25], + "gem2":["",13,40], + "gem3":["",14,40], + #"candy0":["pack_1a",10,17], + "candy0":["",13,29], + #"candy1":["pack_1a",2,17], + "candy1":["",12,29], + "candycane":["",4,29], + "ornament":["",2,29], + "mistletoe":["",5,29], + #boosters + "xpbooster":["",2,27], + "xpbooster_a":["",3,27], + "luckbooster":["",6,27], + "luckbooster_a":["",7,27], + "goldbooster":["",4,27], + "goldbooster_a":["",5,27], + #armors + "cape0":["",0,6], + "cape1":["",6,6], + "stealthcape":["",1,6], + "chest0":["pack_1a",11,112],#original + "chest1":["pack_1a",8,113],#most-flashy one + "chest2":["pack_1a",9,113],#small + "chest3":["pack_1a",9,114],#small+gold + #"pants":["pack_1a",6,4], + #"helmet":["pack_1a",3,23], #t1 + "fury":["",0,0], + "helmet":["",2,0], + #"helmet1":["pack_1a",6,23], #t2 + "helmet1":["",3,0], + #"hhelmet":["pack_1a",9,23], #t3 + "hhelmet":["",4,0], + #"xhelmet":["pack_1a",13,23], #t4 + "xhelmet":["",5,0], + #"phelmet":["pack_1a",5,116], #pumpkin + "phelmet":["",11,29], + #"coat":["pack_1a",8,3], #t1 + "coat":["",2,1], + #"coat1":["pack_1a",12,3], #t2 + "coat1":["",3,1], + #"harmor":["pack_1a",0,4], #t3 + "harmor":["",4,1], + #"xarmor":["pack_1a",14,4], #t4 + "xarmor":["",5,1], + #"mcape":["pack_1a",9,5], #dracul + "mcape":["",11,1], + "warpvest":["",10,1], + #"pants":["pack_1a",0,112], #t1 + "pants":["",2,4], #t1 + #"pants1":["pack_1a",0,113], #t2 + "pants1":["",3,4], + #"hpants":["pack_1a",1,113], #t3 + "hpants":["",4,4], + #"xpants":["pack_1a",2,113], #t4 + "xpants":["",5,4], + #"shoes":["pack_1a",5,10], #t1 + "shoes":["",2,5], + #"shoes1":["pack_1a",8,10], #t2 + "shoes1":["",3,5], + #"hboots":["pack_1a",11,10], #t3 + "hboots":["",4,5], + #"xboots":["pack_1a",4,113], #t4 + "xboots":["",5,5], + #"gloves":["pack_1a",9,20], #t1 + "gloves":["",2,2], + #"gloves1":["pack_1a",12,20], #t2 + "gloves1":["",3,2], + #"hgloves":["pack_1a",11,22], #t3 + "hgloves":["",4,2], + #"xgloves":["pack_1a",0,114], #t4 + "xgloves":["",5,2], + #"scroll0":["pack_1a",0,53], + #"scroll1":["pack_1a",15,52], + #"scroll2":["pack_1a",8,116], + #"cscroll0":["pack_1a",4,52], + #"cscroll1":["pack_1a",3,52], + #"cscroll2":["pack_1a",9,116], + #"strscroll":["pack_1a",14,50], + #"intscroll":["pack_1a",3,51], + #"dexscroll":["pack_1a",2,51], + #"vitscroll":["pack_1a",5,51], + "scroll0":["",13,23], + "scroll1":["",12,23], + "scroll2":["",14,23], + "cscroll0":["",0,24], + "cscroll1":["",15,23], + "cscroll2":["",1,24], + "strscroll":["",11,23], + "intscroll":["",8,23], + "dexscroll":["",9,23], + "vitscroll":["",6,23], + "speedscroll":["",0,41], + "lifestealscroll":["",1,41], + "manastealscroll":["",2,41], + "critscroll":["",3,41], + "dreturnscroll":["",4,41], + "frequencyscroll":["",5,41], + "mpcostscroll":["",6,41], + "outputscroll":["",7,41], + "forscroll":["",8,41], + "xpscroll":["",9,41], + "goldscroll":["",10,41], + "luckscroll":["",11,41], + "armorscroll":["",12,41], + "resistancescroll":["",13,41], + "apiercingscroll":["",14,41], + "rpiercingscroll":["",15,41], + "reflectionscroll":["",7,23], + "evasionscroll":["",10,23], + #"bow":["pack_1a",3,93], + #"quiver":["pack_1a",7,114], + #"claw":["pack_1a",1,95], + #"spear":["pack_1a",7,103], + "spear":["",3,7], + #"blade":["pack_1a",15,96], + #"fireblade":["pack_1a",0,97], + "fireblade":["",1,8], + "fireblade_r":["",1,58], + #"basher":["pack_1a",2,101], + "basher":["",5,10], + #"staff":["pack_1a",7,100], + "staff":["",2,10], + #"firestaff":["pack_1a",8,100], + "firestaff":["",3,10], + "firestaff_r":["",3,58], + "wblade":["pack_1a",8,108], #ethereal blade + "wblade":["",8,8], + #"pmace":["pack_1a",5,114], + "pmace":["",4,10], + "amulet":["pack_1a",14,1], + #"stramulet":["pack_1a",12,1], + #"dexamulet":["pack_1a",8,1], + #"intamulet":["pack_1a",9,1], + "amuletofm":["",14,19], + "mpxamulet":["",6,20], + "mpxgloves":["",6,2], + #"ring":["pack_1a",14,65,8], + #"vitring":["pack_1a",13,65,8], + #"strring":["pack_1a",8,65,8], + #"intring":["pack_1a",11,65,8], + #"dexring":["pack_1a",10,65,8], + "ring":["",12,15], + "vitring":["",13,15], + "strring":["",0,16], + "intring":["",15,15], + "dexring":["",14,15], + "redorb":["pack_1a",10,28], + "blueorb":["pack_1a",15,28], + "orangeorb":["pack_1a",11,28], + #"shield":["pack_1a",0,71], + #"intearring":["pack_1a",5,2], + #"strearring":["pack_1a",8,2], + #"dexearring":["pack_1a",4,2], + "belt":["pack_1a",1,0], + "hpbelt":["",10,3], + "mpxbelt":["",6,3], + "strbelt":["",11,3], + "intbelt":["",12,3], + "dexbelt":["",13,3], + #"wbook0":["pack_1a",4,61], + #"tokenofcode":["pack_1a",6,112], + "stoneofxp":["pack_1a",12,113], + "stoneofxp_a":["pack_1a",12,114], + "stoneofgold":["pack_1a",11,114], + "stoneofluck":["pack_1a",10,114], + "xptome":["",14,27], + #"stand0":["pack_1a",1,115], + "stand0":["",14,24], + "tarot":["",11,24], + #"ancientcomputer":["pack_1a",6,115], + "ancientcomputer":["",0,26], + "tracker":["",11,40], + #"stick":["pack_1a",0,110], + #"coal":["pack_1a",9,28], + "stick":["",4,26], + "coal":["",9,25], + "test":["",9,17], + "testv2":["",11,17], + #skills + #"use_hp":["pack_1a",4,48], + #"use_mp":["pack_1a",9,48], + #"use_town":["pack_1a",13,86], + #"skill_burst":["pack_1a",10,78], + #"skill_taunt":["pack_1a",8,85], + #"skill_charge":["pack_1a",2,84], + #"skill_curse":["pack_1a",11,83], + #"skill_supershot":["pack_1a",8,88], + #"skill_invis":["pack_1a",5,78], + #"skill_invis_active":["pack_1a",6,82], + #"skill_light":["pack_1a",5,77], + #"skill_parrow":["pack_1a",2,91], + #"skill_pcoat":["pack_1a",15,85], + + #skills 20x20 + "use_hp":["skills",2,7], + "use_mp":["skills",2,8], + "use_town":["skills",0,6], + "snippet":["",13,24], + "attack":["skills",1,6], + "heal":["skills",2,6], + "character":["skills",3,6], + "stats":["skills",4,6], + "gm":["skills",4,6], + "interact":["skills",5,6], + "inventory":["skills",6,6], + "travel":["skills",7,6], + "esc":["skills",8,6], + "stop":["skills",9,6], + "stop_g":["skills",10,6], #orange: [15,5] + "up":["skills",11,6], + "down":["skills",12,6], + "left":["skills",13,6], + "right":["skills",14,6], + "code":["skills",0,10], + "run_code":["skills",1,10], + "snippet":["skills",2,10], + "run_snippet0":["skills",3,10], + "run_eval0":["skills",4,10], + "run_snippet1":["skills",5,10], + "run_eval1":["skills",6,10], + "run_snippet2":["skills",7,10], + "run_eval2":["skills",8,10], + "run_snippet3":["skills",9,10], + "run_eval3":["skills",10,10], + "run_snippet4":["skills",11,10], + "run_eval4":["skills",12,10], + "run_snippet5":["skills",13,10], + "run_eval5":["skills",14,10], + "run_emotion":["skills",13,10], + "citizens":["skills",6,9], + "regen_hp":["skills",8,7], + "regen_mp":["skills",8,8], + "condition_good":["skills",11,9], + "condition_neutral":["skills",12,9], + "condition_bad":["skills",13,9], + "newcomersblessing":["skills",11,9], + "buff_blueorb":["custom",0,7], + "buff_redorb":["custom",1,7], + "buff_greenorb":["custom",2,7], + "buff_yelloworb":["custom",3,7], + + #mage + "skill_light":["skills",0,0], + "skill_burst":["skills",1,0], + "skill_cburst":["skills",2,0], + "skill_blink":["skills",3,0], + "skill_teleport":["skills",4,0], + "skill_energize":["skills",6,0], + "buff_reflection":["skills",7,0], + "skill_entangle":["skills",8,0], + "skill_alchemy":["skills",9,0], + + #warrior + "skill_strength":["skills",0,1], + "skill_taunt":["skills",1,1], + "skill_cleave":["skills",2,1], + "skill_stomp":["skills",3,1], + "skill_hardshell":["skills",4,1], + "skill_charge":["skills",5,1], + "skill_warcry":["skills",6,1], + "skill_agitate":["skills",7,1], + "skill_dash":["skills",9,1], + + #ranger + "skill_track":["skills",2,3], + "skill_supershot":["skills",0,2], + "skill_3shot":["skills",1,2], + "skill_5shot":["skills",2,2], + "skill_poisonarrow":["skills",3,2], + "skill_tame":["skills",4,2], + "skill_4fingers":["skills",5,2], + "skill_huntersmark":["skills",6,2], + "skill_piercingshot":["skills",7,2], + + #rogue + "skill_pcoat":["skills",0,3], + "skill_invis":["skills",1,3], + "skill_invis_active":["skills",0,1], + "skill_quickstab":["skills",3,3], + "skill_quickpunch":["skills",4,3], + "skill_abuff":["skills",5,3], + "skill_pstrike":["skills",6,3], + "skill_shadowstrike":["skills",8,3], + "skill_stack":["skills",6,3], + "skill_mentalburst":["skills",9,3], + + #priest + "skill_curse":["skills",0,4], + "skill_pheal":["skills",1,4], + "skill_sacrifice":["skills",2,4], + "skill_revive":["skills",3,4], + "skill_dbuff":["skills",4,4], + "skill_corrosion":["skills",4,4], + "skill_absorbsins":["skills",6,4], + "skill_phaseout":["skills",7,4], + + #merchant + "skill_mcourage":["skills",0,5], + "skill_throw":["skills",1,5], + "skill_massproduction":["skills",2,5], + "skill_massproductionpp":["skills",3,5], + + #paladin + "skill_mshield":["skills",0,11], + "skill_selfheal":["skills",1,11], + "skill_purify":["skills",2,11], + "skill_smash":["skills",3,11], + + #items + "skill_scare":["",13,38], + + #quests + "quest_monsterhunt":["skills",7,9], + + + #buffs 20x20 + "holidayspirit":["skills",2,9], + "buff_luck":["skills",0,9], + "buff_speed":["skills",1,9], + "withdrawal":["skills",4,9], + "notverified":["skills",3,9], + + "poison":["",8,21], + "shadowstone":["",14,28], + #20x20 + "eggnog":["",0,29], + "orbofsc":["",1,29], + "xmashat":["",6,29], + "xmassweater":["",7,29], + "xmaspants":["",9,29], + "xmasshoes":["",10,29], + "mittens":["",8,29], + "goldglove":["",10,2], + + #materials + "essenceoffrost":["",10,34], + "essenceoffire":["",9,34], + "essenceofnature":["",8,34], + "essenceofpower":["",14,34], + "essenceofdarkness":["",11,34], + "essenceoflight":["",7,34], + "essenceofthunder":["",12,34], + "essenceofdesire":["",13,34], + "essenceoflife":["",14,34], + "emptyjar":["",14,35], + "cxjar":["custom",2,1], + "emotionjar":["custom",5,1], + "bottleofxp":["",15,35], + "feather0":["",1,33], + "bronzeingot":["",2,35], + "goldingot":["",3,35], + "platinumingot":["",4,35], + "bronzenugget":["",5,35], + "goldnugget":["",6,35], + "platinumnugget":["",7,35], + "qubics":["",0,36], + "networkcard":["",1,36], + "electronics":["",4,36], + + #crafting + "wingedboots":["",10,5], + + #cosmetics + "cxjar":["",8,62], + "emotionjar":["",9,62], + + #easter + "egg0":["",0,30], + "egg1":["",1,30], + "egg2":["",2,30], + "egg3":["",3,30], + "egg4":["",4,30], + "egg5":["",5,30], + "egg6":["",6,30], + "egg7":["",7,30], + "egg8":["",8,30], + "goldenegg":["",9,30], + "basketofeggs":["",10,30], + "carrotsword":["",11,30], + "carrotsword_c":["",0,58], + "bunnyelixir":["",15,30], + "bunnyears":["",12,30], + "pyjamas":["",13,30], + "rabbitsfoot":["",14,30], + "harbringer":["",7,10], + "harbringer_r":["",9,58], + "oozingterror":["",6,10], + "bataxe":["",2,8], + + #easter2019 + "eears":["",2,42], + "epyjamas":["",2,43], + "ecape":["",2,47], + "eslippers":["",2,46], + "easterluck":["custom",2,0], + "fullguard":["",4,12], + + #anniversary + "gift0":["",1,32], + "gift1":["",0,32], + "confetti":["",6,32], + "poker":["",5,32], + "partyhat":["",11,0], + "ftrinket":["",3,32], + "scroll3":["",3,24], + "cscroll3":["",2,24], + "felixir":["",15,31], + "tristone":["",1,16], + "tristone_a":["",2,16], + "darktristone":["",3,16], + "darktristone_a":["",4,16], + "mysterybox":["",2,26], + "cake":["",12,28], + + #halloween2 + "greenbomb":["",11,32], + "bowofthedead":["",15,9], + "swordofthedead":["",15,8], + "maceofthedead":["",15,11], + "staffofthedead":["",15,10], + "daggerofthedead":["",15,7], + + #halloween3 + "gbow":["",10,58], + + #halloween4 + "hdagger":["",7,7], + + #halloween5 + "halloween0":["skills",1,12], + "halloween1":["skills",2,12], + "halloween2":["skills",0,12], + "pmaceofthedead":["",0,61], + "broom":["",4,61], + "sbelt":["",14,3], + "skullamulet":["",7,20], + "spookyamulet":["",8,20], + + "swirlipop":["",15,32], + "gphelmet":["",15,29], + "smoke":["",10,21], + #"lantern":["",13,28], + "lantern":["",9,12], + "pumpkinspice":["",9,21], + "essenceofether":["",0,33], + + "starkillers":["",6,4], + + "powerglove":["",13,2], + "goldenpowerglove":["",15,2], + + "exoarm":["",8,11], + + #xmas2 + "supermittens":["",2,33], + "xbox":["",3,33], + "x0":["",4,33], + "x1":["",5,33], + "x2":["",6,33], + "x3":["",7,33], + "x4":["",8,33], + "x5":["",9,33], + "x6":["",10,33], + "x7":["",11,33], + "x8":["",12,33], + "angelwings":["",8,6], + "hotchocolate":["",11,21], + "warmscarf":["",0,20], + "santasbelt":["",3,3], + "candycanesword":["",7,8], + "rednose":["",10,0], + "ornamentstaff":["",6,11], + + #xmas3 + "merry":["",14,9], + "mshield":["",10,12], + + #xmas4 + "gcape":["",15,6], + "xmace":["",12,11], + "northstar":["",5,20], + "mearring":["",9,17], + "snowball":["",7,37], + "snowball_r":["",11,37], + "snowflakes":["",6,37], + "snowflakes_r":["",10,37], + + #xmas5 + "ringhs":["",11,62], + "wbookhs":["",4,14], + "sweaterhs":["",10,62], + + "firestars":["",5,37], + "firestars_r":["",9,37], + "iceskates":["",15,5], + "snowboots":["",14,5], + + + #elixirs + "elixirvit0":["",0,27], + "elixirvit1":["",0,28], + "elixirvit2":["",1,28], + "elixirstr0":["",2,28], + "elixirstr1":["",3,28], + "elixirstr2":["",4,28], + "elixirint0":["",5,28], + "elixirint1":["",6,28], + "elixirint2":["",7,28], + "elixirdex0":["",8,28], + "elixirdex1":["",9,28], + "elixirdex2":["",10,28], + "elixirluck":["",15,31], + + "belt":["",2,3], + + "blade":["",0,7], + "bow":["",0,9], + "t2bow":["",3,9], + "claw":["",1,11], + "fclaw":["",3,11], + "fclaw_r":["",8,58], + "froststaff":["",8,10], + "froststaff_r":["",4,58], + "throwingstars":["",4,9], + "t2fist":["",2,11], + "shield":["",0,12], + "xshield":["",6,12], + "wshield":["",7,12], + "sshield":["",1,12], #Spiked + "quiver":["",0,13], + "t2quiver":["",1,13], + "wbook0":["",1,14], + "wbook1":["",3,14], + "cupid":["",14,29], + + "suckerpunch":["",11,15], + "molesteeth":["",5,17], + "stramulet":["",8,19], + "dexamulet":["",10,19], + "intamulet":["",9,19], + "hpamulet":["",4,19], + "intearring":["",7,17], + "strearring":["",6,17], + "dexearring":["",8,17], + "vitearring":["",0,17], + "t2stramulet":["",11,19], + "t2intamulet":["",12,19], + "t2dexamulet":["",13,19], + + "hammer":["",12,10], + + "funtoken":["",9,32], + "pvptoken":["",8,32], + "scroll4":["",4,24], + + #chinese new year 2018 + "redenvelope":["",13,33], + "dragonarmor":["",14,1], + "puppyer":["",14,33], + + #chinese new year 2019 + "redenvelopev2":["",9,39], + "firecrackers":["",10,39], + "dragondagger":["",10,7], + + "redenvelopev3":["",15,39], + + "redenvelopev4":["",15,62], + "tigerhelmet":["",11,12], + "tigercape":["",10,6], + "tigershield":["",12,12], + "tigerstone":["",5,48], + + "greenenvelope":["",15,40], + "oxhelmet":["",7,0], + "lmace":["",11,11], + + "greenenvelopev2":["custom",5,3], + + #valentines + "solitaire":["",5,16], + + #valentines 2019 + "emptyheart":["",13,39], + "charmer":["",12,39], + "candypop":["",11,39], + + #halloween 2018 + "jacko":["",12,38], + "talkingskull":["",14,38], + "frankypants":["",11,4], + "vblood":["",0,22], + + #wanderers set + "wcap":["",0,42], + "wattire":["",0,43], + "wgloves":["",0,44], + "wbreeches":["",0,45], + "wshoes":["",0,46], + + #samples + "helmet20":["",0,0], + "coat20":["",2,4], + "gloves20":["",2,5], + "pants20":["",3,5], + "shoes20":["",4,5], + "amulet20":["",4,8], + "ring120":["",0,9], + "ring220":["",1,10], + "earring120":["",5,10], + "earring220":["",1,6], + "belt20":["",3,7], + "blade20":["",1,11], + "shield20":["",3,11], + "orb20":["",4,6], + "elixir20":["",4,13], + "stone20":["",5,5], + "shard20":["",6,6], + "star20":["",6,7], + + #collectables + "brownegg":["",0,50], + "whiteegg":["",1,50], + "gslime":["",2,50], + "crabclaw":["",3,50], + "beewings":["",4,50], + "pleather":["",5,50], + "spores":["",6,50], + "lotusf":["",7,50], + "frogt":["",8,50], + "snakefang":["",9,50], + #"snakeoil":["",10,50], + "rattail":["",11,50], + "ascale":["",12,50], + #"cscale":["",13,50], + "ink":["",14,50], + "ijx":["",15,50], + "smush":["",0,51], + "carrot":["",1,51], + "bfur":["",2,51], + "bandages":["",3,51], + "cocoon":["",4,51], + "tshell":["",5,51], + "dstones":["",6,51], + "bwing":["",7,51], + "bfang":["",8,51], + "sstinger":["",9,51], + "svenom":["",10,51], + "pstem":["",11,51], + "watercore":["",12,51], + "ectoplasm":["",13,51], + "rfur":["",14,51], + "cshell":["",15,51], + "bcandle":["",0,52], + "lspores":["",1,52], + "trinkets":["",2,52], + "rfangs":["",3,52], + "btusk":["",4,52], + "drapes":["",5,52], + + #orbs + "orbofstr":["",0,48], + "orbofdex":["",1,48], + "orbofint":["",2,48], + "orbofvit":["",3,48], + + #tshirts + "tshirt0":["",2,38], + "tshirt1":["",3,38], + "tshirt2":["",4,38], + "tshirt3":["",5,38], + "tshirt4":["",6,38], + "tshirt88":["",7,38], + "tshirt6":["",8,38], + "tshirt7":["",9,38], + "tshirt8":["",10,38], + "tshirt9":["",11,38], + + #normal + "frozenstone":["",8,26], + "flute":["",14,26], + "stonekey":["",9,35], + "dartgun":["",4,37], + "snakeoil":["",15,28], + "5bucks":["",8,36], + "gum":["",9,36], + "espresso":["",11,36], + "whiskey":["",15,36], + "wine":["",14,36], + "ale":["",10,36], + "pico":["",12,36], + "blue":["",13,36], + "monstertoken":["",0,38], + "luckyt":["",0,1], + "troll":["",1,38], + "cosmo0":["",0,39], + "cosmo1":["",1,39], + "cosmo2":["",2,39], + "cosmo3":["",3,39], + "cosmo4":["",4,39], + "licence":["",2,23], + "bugbountybox":["",5,39], + "apologybox":["",6,39], + "spidersilk":["",8,39], + "woodensword":["",10,8], + "ghatb":["custom",3,0], + "ghatp":["custom",4,0], + "ringofluck":["",6,16], + "slimestaff":["",2,55], + "mushroomstaff":["",6,55], + "hbow":["",5,55], + "cclaw":["",3,55], + "mwhelmet":["",3,42], + "mwarmor":["",3,43], + "mwgloves":["",3,44], + "mwpants":["",3,45], + "mwboots":["",3,46], + "mmhat":["",4,42], + "mmarmor":["",4,43], + "mmgloves":["",4,44], + "mmpants":["",4,45], + "mmshoes":["",4,46], + "mphat":["",5,42], + "mparmor":["",5,43], + "mpgloves":["",5,44], + "mppants":["",5,45], + "mpshoes":["",5,46], + "mrnhat":["",6,42], + "mrnarmor":["",6,43], + "mrngloves":["",6,44], + "mrnpants":["",6,45], + "mrnboots":["",6,46], + "mrhood":["",7,42], + "mrarmor":["",7,43], + "mrgloves":["",7,44], + "mrpants":["",7,45], + "mrboots":["",7,46], + "mchat":["",8,42], + "mcarmor":["",8,43], + "mcgloves":["",8,44], + "mcpants":["",8,45], + "mcboots":["",8,46], + "nheart":["",10,40], + "orbg":["",4,48], + "resistancering":["",13,16], + "armorring":["",12,16], + "pball":["custom",1,1], + "chry":["custom",0,1], + "fierygloves":["",7,2], + "firebow":["",11,9], + "firebow_r":["",2,58], + "frostbow":["",12,9], + "frostbow_r":["",6,58], + "snring":["",1,20], + "rapier":["",11,7], + "pinkie":["",13,58], + "pinkie_r":["",12,58], + "wand":["",14,58], + "crossbow":["",6,9], + "t3bow":["",5,9], + "bow4":["",10,9], + "axe3":["",11,10], + "xshot":["",1,22], + "xshotted":["",3,22], + "dagger":["",6,7], + "sword":["",2,7], + "fsword":["",5,7], + "fsword_r":["",5,58], + "stinger":["",4,55], + "swifty":["",7,55], + "lbelt":["",2,3], + "scythe":["",12,7], + "bkey":["",2,59], + "ukey":["",3,59], + "dkey":["",4,59], + "mbones":["",1,59], + "spearofthedead":["",13,7], + "mace":["",14,11], + "wbasher":["",13,11], + "fcape":["",9,6], + "test_orb":["",14,49], + #"fieldgen0x":["custom",0,2], + "fieldgen0":["",0,62], + "fallen":["",0,4], + "dexearringx":["",1,17], + "goldenring":["",7,15], + "sanguine":["",4,20], + "heartwood":["",12,8], + #"offeringx":["custom",1,2], + "offeringx":["",3,62], + #"offeringp":["custom",2,2], + "offeringp":["",1,62], + "essenceofgreed":["",13,34], + "weaver":["",13,9], + "blaster":["",0,10], + "pouchbow":["",5,59], + "elixirfires":["",5,62], + "elixirfzres":["",6,62], + "elixirpnres":["",4,62], + "trigger":["",15,16], + "mbelt":["",4,3], + + "cryptkey":["custom",0,3], + "tombkey":["custom",1,3], + "frozenkey":["custom",2,3], + "cyber":["custom",3,3], + "vattire":["custom",0,4], + "vgloves":["custom",1,4], + "vboots":["custom",2,4], + "vcape":["custom",3,4], + "vhammer":["custom",0,5], + "vdagger":["custom",1,5], + "vsword":["custom",2,5], + "vstaff":["custom",3,5], + "cring":["custom",0,6], + "cearring":["custom",1,6], + "vring":["custom",2,6], + "vorb":["custom",3,6], + "rod":["",6,61], + "skill_fishing":["",6,61], + "pickaxe":["",5,61], + "skill_mining":["",5,61], + + "glolipop":["",2,61], + "ololipop":["",1,61], + + #trial + #"dragondagger":["",15,42], + #"claw":["",13,42], + + "friendtoken":["",15,33], +} \ No newline at end of file diff --git a/design/docs/.DS_Store b/design/docs/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/design/docs/.DS_Store differ diff --git a/design/docs/MARKETING.txt b/design/docs/MARKETING.txt new file mode 100644 index 0000000..f3fc1d7 --- /dev/null +++ b/design/docs/MARKETING.txt @@ -0,0 +1,116 @@ +SSCREENSHOTS: +[Steam]: 1080p +[Mac App Store]: 2880 x 1800 or 2560 x 1600 + +[Titles / Themes for Screenshots] +[1] Ever Expanding 2D Pixel World +[2] Upgrade / Combine / Craft Items +[2.1] [Small Things] Gamble in Tavern - Rare Drops from Monsters - Seasonal Events - Easter Egg Mechanics +[3] Player driven economy with Merchant class +[4] Freely move between PVE / PVP Servers +[5] Party and Play with your Friends! + +[9] Play it safe in PvE or risk it all in PvP and reap the rewards! +Dive deep into the underground labyrinth of caves to tackle the unknown... +Group up with players to take down powerful opponents! (Queue epic battle screenshot) + +STEAM MAIN: + +Adventure Land is an experimental Indie MMORPG, in which you can CODE your character! You don't need to know programming either, you can learn from the community! You can play simultaneously with 3 Characters and one Merchant. Going open-source at 50,000 installs! + +Adventure Land is an experimental Indie MMORPG. ANYONE can Code. And not just one character, but up to 3 Characters and one Merchant! You can play manually, use the default Code, or start learning coding to do more! Going open-source at 50,000 installs! + +Adventure Land is an experimental Indie MMORPG. ANYONE can Code not just one, but up to 3 Characters and one Merchant! You can play manually, use the default Code, or start learning coding to do more! Going open-source at 50,000 installs! + +Jonyboys: Where ANYONE + +Mark: Adventure Land is an experimental Indie MMORPG. ANYONE can Code not just one, but up to 4 characters! You can play manually, use the given default Code, or use JavaScript to customize your characters behavior! Going open-source at 50,000 installs! + +Adventure Land is an experimental Indie MMORPG. ANYONE can Code not just one, but up to 4 characters! You can play manually, use the given default Code, or learn programming to do more! Going open-source at 50,000 installs! + +[h2]A Simple MMORPG[/h2] +There are no quests, no guides you have to strictly follow to the letter. No objectives either. You can do anything you want. Even farming the lowest monster will yield satisfactory results! You can trade, gamble in tavern, party with friends, pvp solo with your rouge or go after rare loots! + +[h2]Origins of Code[/h2] +Adventure Land wasn't originally a Code based game, during early development, it ended up a bit like a Clicker MMORPG, simple but fun. Then came Code, to let machines do the clicking! So it's not something extremely complex no one can understand, it's just basic automation with Javascript! + +[h2]6 Classes[/h2] +Mage, Warrior, Rogue, Ranger, Priest and Merchant. All with different, easy to understand, but unique skills. There are no skill trees or the need to pick attributes, it's all automatic to keep things simple. Items provide some depth, and Code adds some variation to the mix. + +[h2]Upcoming[/h2] +There's a lot to work on. Daily Events, Paladin Class, Pets, Guilds (or Familias, as they will be small), New Zones, New Items, New Skills. All features are shaped and vetted by the playerbase. + +[h2]Anti Pay to Win[/h2] +Adventure Land had a lengthy early development period, one lesson was the clearest, the gameplay should never include things that are even remotely pay to win. The game however needs to amortise its costs, and as a prospective player, you deserve to know exactly how! So, There will be cosmetics, extra bank slots, and some account operations unlockable by premium currency. But nothing that directly affect game performance. (Ps. You can also farm premium currency in-game, from Goo's, and as rare drops) + +DESCRIPTION: + +Adventure Land is a new kind of MMORPG, where you can CODE your character, so everyone can automate the endless grinding that's usually associated with the genre. + +[Anti P2W + Cosmetics/Storage-Only Income] +Adventure Land is a very challenging game from a Business perspective, in normal MMORPG's, players are allowed one regular character, in Adventure Land, you can play 24/7, with 4 characters, for months, without any monthly charges. As the player, you deserve to know how exactly the game intends to make money. + +As an indie developer, I hope the income from game sales will cover my expenses, help pay those who work on the game, and help me build a better life. + +To cover the ongoing expenses and server costs, the game will sell cosmetics, and extra bank slots for SHELLS, our premium in-game currency. + +It's really important to generate income in a fair way, so I continually gather feedback, and shape the game accordingly, for example, you can always find SHELLS in-game too, so even if the game intends to sell cosmetics, you can always attain them other ways too! + +[Who's Adventure Land For?] +If you like coding, like coding games, or just want to learn coding, this is the game for you! +If you like idle games, clicker games, this is the game for you! +If you are just looking to experience a unique and experimental 2D Pixel MMORPG, be part of a small community, leave game afk 24/7, check on your characters progress from time to time, it's definitely the game for you! :) + +[Who's Adventure Land Not For?] +If you're looking for a well balanced, well thought, perfect mmorpg, where you can be the best, and win because you have the best skills, this is definitely not the game for you. +If you are very competitive, this is not the game for you. (There's no level cap, while levelling is highly non-linear, those who spend more time in-game will technically be ahead of you) +Adventure Land is ultimately a Code to Win, or Grind to Win game, our PVP is very unbalanced too, it will certainly improve over time, but currently, unless you are Code assisted, it's almost impossible to dive solo into a Code'd group and leave alive :) +So TL;DR: If you are looking for the perfect MMORPG, Adventure Land is likely not it, If you are looking for something new, something different, come on in! :) + +[Final Words] +I try my best to shape Adventure Land into a better game every single day, there are many aspects of Adventure Land, ultimately I'm very proud of the educational aspect. + + + + + + + + + + +[EARLY ACCESS] +- Why Early Access? +Adventure Land is at a sweet spot in its development journey. Most of the major challenges have been tackled and lately all the feedback has been positive. I believe and hope early adopters will enjoy the game, and at the same time, the game will benefit from a growing community. We're finally ready for the last sprint. + +-Approximately how long will this game be in Early Access? +Hopefully 6 months + +-How is the full version planned to differ from the Early Access version? +Planning on introducing more content to increase non-AFK engagement between players. Daily events, encounters that require 8-character parties, and so on. On the code side of things, after the gameplay improvements are finalised, going to complete the Code documentation and tutorial. As an Early Access player, you will likely use our Discord a lot to improve your Code and learn about the game, while the full version of the game is intended to be more guiding. + +-What is the current state of the Early Access version? +The game is very refined at this point in terms of gameplay and performance. It's heavily tested. What we currently lack is more content, both game content, and more documentation. +----- +Gameplay - Refined and Final +CODE - Fully Functional +Item Upgrade System - Completed +Item Compound System - Completed +Item Crafting System - Functional but lacking content +CODE Documentation - Work in Progress +Cosmetics System - Work in Progress +Daily Events - Work in Progress + +-Will the game be priced differently during and after Early Access? +No pricing changes planned, if operating costs are higher than expected, the price might slightly increase. +----- +Price can fluctuate but it won't dramatically increase or decrease, it's safe to expect a fluctuation around 30% of the current price + +-How are you planning on involving the Community in your development process? +We have a Discord with #feedback and #new_ideas channels. I reply to each and every email, take each request into consideration, reply to every GitHub issue. The main challenge for me as a developer is introducing new content without creating balance issues. I intend to create a public group of people within the Discord community called Refiners, there'll be strict rules, the process will be transparent, fair, and Refiners will take ideas from #new_ideas, and convert them into #refined_ideas. + + + + + + diff --git a/design/docs/TODO.txt b/design/docs/TODO.txt new file mode 100644 index 0000000..70962fa --- /dev/null +++ b/design/docs/TODO.txt @@ -0,0 +1,45 @@ +Discord message pool [12/12/20] +Specify Code Limits [13/12/20] +A separate git for db.rdbms [15/12/20] + +Check out Steam Points Shop https://steamcommunity.com/groups/steamworks/announcements/detail/2924488121712219462 [11/01/21] + +Integrate: NEW STYLE EMOTION ANIMATIONS [26/11/20] +Integrate the new Desertland [25/07/20] +New Ent-like Monster - Armor Box Drops [30/06/20] +Integrate the building rooms [01/07/20] +/untie for Steam [02/07/20] +Promisify exchange + sell [06/07/20] +Look into disabling mouse4/mouse5 [08/08/20] + +Make monsters pathfind back to their spawns [20/08/20] + +IDEA: Instances where if you die, you can't repeat, so multi-chars are heavily promoted [11/08/20] + +CLI's smart_move blocks character update processing [04/07/20] +Promised equip with guaranteed pre-refreshed .items [11/07/20] + +Make all user_data updates transactional [12/09/20] + +Goblin Minion [30/06/20] +First Time Task Buffs: First +8 -> 100% Luck [30/06/20] +Make Low Spawn Monsters Have - difficulty Multiplier [30/06/20] + +Franger's weird text alignment - roundPixels is bad, false is good, rare issue [19/08/20] + +Make projectiles adopt the modifiers like crit/burn [11/08/20] +Weapon/Armor achievements - 100M damage taken -> +5% armor/res - 1,000 unique kills -> +2 damage [14/07/20] + - Lucky - for exact %-hit + - Holy - for heals + - Stalwart - for tanking + - Bloody - for PK's + - 1M consecutive kills over 200 range + + Chromium/BOT: Test the cli_time checks [29/07/20] + Announce stealth cape events delayed and anonymous [02/08/20] + + +Ellian: + Skill: + - Rogue Pickpocket + diff --git a/design/docs/item_dynamics_original.htm b/design/docs/item_dynamics_original.htm new file mode 100644 index 0000000..4fea8bd --- /dev/null +++ b/design/docs/item_dynamics_original.htm @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + +
+
Stone of Wisdom
Increases experience gain by 50%. Needs to be activated. Can be morphed into other stones.
Trinket of Faith
Strength: 2
Intelligence: 2
Dexterity: 2
Vitality: 2
Armor: 5
Speed: +1
Good things come to those who wait
7,200 GOLD
SELL
Trinket of Faith +1
Strength: 2
Intelligence: 2
Dexterity: 2
Vitality: 5
Armor: 10
Speed: +2
Grade: High
Good things come to those who wait
23,040 GOLD
SELL
Trinket of Faith +2
Strength: 2
Intelligence: 2
Dexterity: 2
Vitality: 8
Armor: 15
Speed: +3
Grade: High
Good things come to those who wait
73,728 GOLD
SELL
Trinket of Faith +3
Strength: 2
Intelligence: 2
Dexterity: 2
Vitality: 11
Armor: 20
Speed: +4
Grade: Rare
Good things come to those who wait
235,930 GOLD
SELL
Trinket of Faith +4
Strength: 2
Intelligence: 2
Dexterity: 2
Vitality: 14
Armor: 25
Speed: +5
Grade: Rare
Good things come to those who wait
754,975 GOLD
SELL
Trinket of Faith +5
Strength: 2
Intelligence: 2
Dexterity: 2
Vitality: 18
Armor: 31
Speed: +6
Grade: Rare
Good things come to those who wait
2,415,919 GOLD
SELL
Tri-Stone
Strength: 1
Intelligence: 1
Dexterity: 1
Vitality: 1
A.Piercing: 5
R.Piercing: 5
3,000 GOLD
SELL
Tri-Stone +1
Strength: 2
Intelligence: 2
Dexterity: 2
Vitality: 2
A.Piercing: 10
R.Piercing: 10
Grade: High
9,600 GOLD
SELL
Tri-Stone +2
Strength: 3
Intelligence: 3
Dexterity: 3
Vitality: 3
A.Piercing: 15
R.Piercing: 15
Grade: High
30,720 GOLD
SELL
Tri-Stone +3
Strength: 4
Intelligence: 4
Dexterity: 4
Vitality: 4
A.Piercing: 20
R.Piercing: 20
Grade: High
98,304 GOLD
SELL
Tri-Stone +4
Strength: 5
Intelligence: 5
Dexterity: 5
Vitality: 5
A.Piercing: 25
R.Piercing: 25
Grade: Rare
314,573 GOLD
SELL
Tri-Stone +5
Strength: 6
Intelligence: 6
Dexterity: 6
Vitality: 6
A.Piercing: 31
R.Piercing: 31
Grade: Rare
1,006,633 GOLD
SELL
Elixir of Greater Dexterity
Dexterity: 8
Hours: 24
Elixir of Greater Intelligence
Intelligence: 8
Hours: 24
Green Bomb
Crit: 10%
Strength: 50
Dexterity: 120
Resistance: -800
Speed: +30
Hours: 0.002
It's a candy with very questionable ingredients, might be addictive.
Luck Booster
Luck: +25%
Increases your chances of looting something from a monster.
2,395,200 GOLD
SELL
Luck Booster +1
Luck: +45%
Increases your chances of looting something from a monster.
7,664,640 GOLD
SELL
Luck Booster +2
Luck: +65%
Increases your chances of looting something from a monster.
24,526,848 GOLD
SELL
Luck Booster +3
Luck: +85%
Increases your chances of looting something from a monster.
78,485,914 GOLD
SELL
Luck Booster +4
Luck: +105%
Increases your chances of looting something from a monster.
251,154,924 GOLD
SELL
Luck Booster +5
Luck: +130%
Increases your chances of looting something from a monster.
803,695,755 GOLD
SELL
Hot Chocolate
Vitality: 30
Armor: 30
Resistance: 30
Hours: 1
Fills your heart with warmth.
Heavy Gloves
Stat: 1
Armor: 24
Resistance: 12
Grade: Rare
204,000 GOLD
SELL
Heavy Gloves +1
Stat: 2
Armor: 28
Resistance: 16
Grade: Rare
204,000 GOLD
SELL
Heavy Gloves +2
Stat: 3
Armor: 33
Resistance: 21
Grade: Rare
204,000 GOLD
SELL
Heavy Gloves +3
Stat: 4
Armor: 37
Resistance: 25
Grade: Rare
204,000 GOLD
SELL
Heavy Gloves +4
Stat: 5
Armor: 41
Resistance: 29
Grade: Rare
204,000 GOLD
SELL
Heavy Gloves +5
Stat: 6
Armor: 45
Resistance: 33
Grade: Rare
408,000 GOLD
SELL
Heavy Gloves +6
Stat: 7
Armor: 50
Resistance: 38
Grade: Rare
816,000 GOLD
SELL
Heavy Gloves +7
Stat: 9
Armor: 55
Resistance: 43
Grade: Rare
1,632,000 GOLD
SELL
Heavy Gloves +8
Stat: 12
Armor: 61
Resistance: 49
Grade: Rare
3,264,000 GOLD
SELL
Heavy Gloves +9
Stat: 15
Armor: 70
Resistance: 58
Grade: Rare
6,528,000 GOLD
SELL
Heavy Gloves +10
Stat: 19
Armor: 82
Resistance: 70
Grade: Rare
13,056,000 GOLD
SELL
Sucker Punch
Lifesteal: 2%
Crit: 2%
A.Piercing: 20
Grade: Rare
1,920,000 GOLD
SELL
Sucker Punch +1
Lifesteal: 3%
Crit: 3%
A.Piercing: 40
Grade: Rare
6,144,000 GOLD
SELL
Sucker Punch +2
Lifesteal: 4%
Crit: 4%
A.Piercing: 60
Grade: Rare
19,660,800 GOLD
SELL
Sucker Punch +3
Lifesteal: 5%
Crit: 5%
A.Piercing: 80
Grade: Rare
62,914,560 GOLD
SELL
Sucker Punch +4
Lifesteal: 6%
Crit: 6%
A.Piercing: 100
Grade: Rare
201,326,592 GOLD
SELL
Sucker Punch +5
Lifesteal: 7.25%
Crit: 7.25%
A.Piercing: 125
Grade: Rare
644,245,094 GOLD
SELL
Xmas Pants
Vitality: 2
Stat: 1
Armor: 15
Resistance: 9
10,680 GOLD
SELL
Xmas Pants +1
Vitality: 2
Stat: 2
Armor: 17
Resistance: 11
10,680 GOLD
SELL
Xmas Pants +2
Vitality: 2
Stat: 3
Armor: 19
Resistance: 13
10,680 GOLD
SELL
Xmas Pants +3
Vitality: 2
Stat: 4
Armor: 21
Resistance: 15
10,680 GOLD
SELL
Xmas Pants +4
Vitality: 2
Stat: 5
Armor: 23
Resistance: 17
Grade: High
10,680 GOLD
SELL
Xmas Pants +5
Vitality: 2
Stat: 6
Armor: 24
Resistance: 18
Grade: High
21,360 GOLD
SELL
Xmas Pants +6
Vitality: 2
Stat: 7
Armor: 26
Resistance: 20
Grade: High
42,720 GOLD
SELL
Xmas Pants +7
Vitality: 2
Stat: 9
Armor: 29
Resistance: 23
Grade: High
85,440 GOLD
SELL
Xmas Pants +8
Vitality: 2
Stat: 12
Armor: 31
Resistance: 25
Grade: Rare
170,880 GOLD
SELL
Xmas Pants +9
Vitality: 2
Stat: 15
Armor: 35
Resistance: 29
Grade: Rare
341,760 GOLD
SELL
Xmas Pants +10
Vitality: 2
Stat: 19
Armor: 41
Resistance: 35
Grade: Rare
683,520 GOLD
SELL
Orb of Intelligence
Intelligence: 5
144,000 GOLD
SELL
Orb of Intelligence +1
Intelligence: 10
460,800 GOLD
SELL
Orb of Intelligence +2
Intelligence: 15
1,474,560 GOLD
SELL
Orb of Intelligence +3
Intelligence: 20
4,718,592 GOLD
SELL
Orb of Intelligence +4
Intelligence: 25
15,099,494 GOLD
SELL
Orb of Intelligence +5
Intelligence: 31
48,318,382 GOLD
SELL
Rare Candy
A rare candy. Xyn in New Town could give you something exciting in exchange!
Darkforge Helmet
Stat: 1
Armor: 28
Resistance: 32
Grade: Rare
1,920,000 GOLD
SELL
Darkforge Helmet +1
Stat: 2
Armor: 34
Resistance: 38
Grade: Rare
1,920,000 GOLD
SELL
Darkforge Helmet +2
Stat: 3
Armor: 39
Resistance: 43
Grade: Rare
1,920,000 GOLD
SELL
Darkforge Helmet +3
Stat: 4
Armor: 45
Resistance: 49
Grade: Rare
1,920,000 GOLD
SELL
Darkforge Helmet +4
Stat: 5
Armor: 50
Resistance: 54
Grade: Rare
1,920,000 GOLD
SELL
Darkforge Helmet +5
Stat: 6
Armor: 56
Resistance: 60
Grade: Rare
3,840,000 GOLD
SELL
Darkforge Helmet +6
Stat: 7
Armor: 61
Resistance: 65
Grade: Rare
7,680,000 GOLD
SELL
Darkforge Helmet +7
Stat: 9
Armor: 68
Resistance: 72
Grade: Rare
15,360,000 GOLD
SELL
Darkforge Helmet +8
Stat: 12
Armor: 76
Resistance: 80
Grade: Rare
30,720,000 GOLD
SELL
Darkforge Helmet +9
Stat: 15
Armor: 87
Resistance: 91
Grade: Rare
61,440,000 GOLD
SELL
Darkforge Helmet +10
Stat: 19
Armor: 104
Resistance: 108
Grade: Rare
122,880,000 GOLD
SELL
Strength Scroll
Adds Stength to an armor with a Stat attribute.
Merchant Stand
You can become a merchant using this item.
Merchant Stand [Sell+Buy]
You can become a merchant using this item.
Armor Box
Can be exchanged for a random, rare armor.
Elixir of Extreme Intelligence
Intelligence: 12
Hours: 48
Empty Jar
Always nice to have some empty jars lying around, you never know when you'll need one!
Pants
Stat: 1
Armor: 10
Resistance: 6
4,680 GOLD
SELL
Pants +1
Stat: 2
Armor: 11
Resistance: 7
4,680 GOLD
SELL
Pants +2
Stat: 3
Armor: 13
Resistance: 9
4,680 GOLD
SELL
Pants +3
Stat: 4
Armor: 14
Resistance: 10
4,680 GOLD
SELL
Pants +4
Stat: 5
Armor: 15
Resistance: 11
4,680 GOLD
SELL
Pants +5
Stat: 6
Armor: 16
Resistance: 12
9,360 GOLD
SELL
Pants +6
Stat: 7
Armor: 18
Resistance: 14
18,720 GOLD
SELL
Pants +7
Stat: 9
Armor: 19
Resistance: 15
Grade: High
37,440 GOLD
SELL
Pants +8
Stat: 12
Armor: 21
Resistance: 17
Grade: High
74,880 GOLD
SELL
Pants +9
Stat: 15
Armor: 23
Resistance: 19
Grade: Rare
149,760 GOLD
SELL
Pants +10
Stat: 19
Armor: 27
Resistance: 23
Grade: Rare
299,520 GOLD
SELL
Compound Scroll
Scroll to combine 3 rare accessories.
XP Booster
XP: +20%
Increases experience gain. Needs to be activated. Can be shifted into other boosters.
2,395,200 GOLD
SELL
XP Booster +1
XP: +35%
Increases experience gain. Needs to be activated. Can be shifted into other boosters.
7,664,640 GOLD
SELL
XP Booster +2
XP: +50%
Increases experience gain. Needs to be activated. Can be shifted into other boosters.
24,526,848 GOLD
SELL
XP Booster +3
XP: +65%
Increases experience gain. Needs to be activated. Can be shifted into other boosters.
78,485,914 GOLD
SELL
XP Booster +4
XP: +80%
Increases experience gain. Needs to be activated. Can be shifted into other boosters.
251,154,924 GOLD
SELL
XP Booster +5
XP: +99%
Increases experience gain. Needs to be activated. Can be shifted into other boosters.
803,695,755 GOLD
SELL
Compound Scroll
Scroll to combine 3 accessories. Things get challenging after +1.
Compound Scroll
Scroll to combine 3 high grade accessories.
Egg
A vibrant egg, it's inhabitant seems eager to get out.
Xmas Hat
Vitality: 2
Stat: 1
Armor: 11
Resistance: 12
7,920 GOLD
SELL
Xmas Hat +1
Vitality: 2
Stat: 2
Armor: 12
Resistance: 14
7,920 GOLD
SELL
Xmas Hat +2
Vitality: 2
Stat: 3
Armor: 14
Resistance: 16
7,920 GOLD
SELL
Xmas Hat +3
Vitality: 2
Stat: 4
Armor: 16
Resistance: 18
7,920 GOLD
SELL
Xmas Hat +4
Vitality: 2
Stat: 5
Armor: 18
Resistance: 20
Grade: High
7,920 GOLD
SELL
Xmas Hat +5
Vitality: 2
Stat: 6
Armor: 20
Resistance: 21
Grade: High
15,840 GOLD
SELL
Xmas Hat +6
Vitality: 2
Stat: 7
Armor: 22
Resistance: 23
Grade: High
31,680 GOLD
SELL
Xmas Hat +7
Vitality: 2
Stat: 9
Armor: 24
Resistance: 26
Grade: High
63,360 GOLD
SELL
Xmas Hat +8
Vitality: 2
Stat: 12
Armor: 27
Resistance: 28
Grade: Rare
126,720 GOLD
SELL
Xmas Hat +9
Vitality: 2
Stat: 15
Armor: 31
Resistance: 32
Grade: Rare
253,440 GOLD
SELL
Xmas Hat +10
Vitality: 2
Stat: 19
Armor: 36
Resistance: 38
Grade: Rare
506,880 GOLD
SELL
Ring of Dexterity
Dexterity: 2
14,400 GOLD
SELL
Ring of Dexterity +1
Dexterity: 4
46,080 GOLD
SELL
Ring of Dexterity +2
Dexterity: 6
147,456 GOLD
SELL
Ring of Dexterity +3
Dexterity: 8
Grade: High
471,859 GOLD
SELL
Ring of Dexterity +4
Dexterity: 10
Grade: High
1,509,949 GOLD
SELL
Ring of Dexterity +5
Dexterity: 13
Grade: Rare
4,831,838 GOLD
SELL
Mittens
Stat: 1
Armor: 12
A.Piercing: 20
R.Piercing: 20
Resistance: 6
Cute but deadly.
20,400 GOLD
SELL
Mittens +1
Stat: 2
Armor: 14
A.Piercing: 22
R.Piercing: 22
Resistance: 8
Cute but deadly.
20,400 GOLD
SELL
Mittens +2
Stat: 3
Armor: 16
A.Piercing: 24
R.Piercing: 24
Resistance: 10
Cute but deadly.
20,400 GOLD
SELL
Mittens +3
Stat: 4
Armor: 18
A.Piercing: 26
R.Piercing: 26
Resistance: 12
Cute but deadly.
20,400 GOLD
SELL
Mittens +4
Stat: 5
Armor: 20
A.Piercing: 28
R.Piercing: 28
Resistance: 14
Grade: High
Cute but deadly.
20,400 GOLD
SELL
Mittens +5
Stat: 6
Armor: 21
A.Piercing: 30
R.Piercing: 30
Resistance: 15
Grade: High
Cute but deadly.
40,800 GOLD
SELL
Mittens +6
Stat: 7
Armor: 23
A.Piercing: 32
R.Piercing: 32
Resistance: 17
Grade: High
Cute but deadly.
81,600 GOLD
SELL
Mittens +7
Stat: 9
Armor: 26
A.Piercing: 35
R.Piercing: 35
Resistance: 20
Grade: High
Cute but deadly.
163,200 GOLD
SELL
Mittens +8
Stat: 12
Armor: 28
A.Piercing: 38
R.Piercing: 38
Resistance: 22
Grade: Rare
Cute but deadly.
326,400 GOLD
SELL
Mittens +9
Stat: 15
Armor: 32
A.Piercing: 42
R.Piercing: 42
Resistance: 26
Grade: Rare
Cute but deadly.
652,800 GOLD
SELL
Mittens +10
Stat: 19
Armor: 38
A.Piercing: 48
R.Piercing: 48
Resistance: 32
Grade: Rare
Cute but deadly.
1,305,600 GOLD
SELL
Spiked Shield
D.Return: 3%
Armor: 60
Resistance: 20
14,400 GOLD
SELL
Spiked Shield +1
D.Return: 5%
Armor: 70
Resistance: 27
14,400 GOLD
SELL
Spiked Shield +2
D.Return: 6%
Armor: 80
Resistance: 34
14,400 GOLD
SELL
Spiked Shield +3
D.Return: 8%
Armor: 90
Resistance: 41
14,400 GOLD
SELL
Spiked Shield +4
D.Return: 9%
Armor: 100
Resistance: 48
Grade: High
14,400 GOLD
SELL
Spiked Shield +5
D.Return: 11%
Armor: 110
Resistance: 55
Grade: High
28,800 GOLD
SELL
Spiked Shield +6
D.Return: 12%
Armor: 120
Resistance: 62
Grade: High
57,600 GOLD
SELL
Spiked Shield +7
D.Return: 14%
Armor: 133
Resistance: 71
Grade: High
115,200 GOLD
SELL
Spiked Shield +8
D.Return: 16%
Armor: 148
Resistance: 81
Grade: Rare
230,400 GOLD
SELL
Spiked Shield +9
D.Return: 19%
Armor: 168
Resistance: 95
Grade: Rare
460,800 GOLD
SELL
Spiked Shield +10
D.Return: 24%
Armor: 198
Resistance: 116
Grade: Rare
921,600 GOLD
SELL
Ring of Vitality
Vitality: 2
14,400 GOLD
SELL
Ring of Vitality +1
Vitality: 4
46,080 GOLD
SELL
Ring of Vitality +2
Vitality: 6
147,456 GOLD
SELL
Ring of Vitality +3
Vitality: 8
Grade: High
471,859 GOLD
SELL
Ring of Vitality +4
Vitality: 10
Grade: High
1,509,949 GOLD
SELL
Ring of Vitality +5
Vitality: 13
Grade: Rare
4,831,838 GOLD
SELL
Amulet of the Eager Warrior
Strength: 5
Resistance: 30
Grade: High
36,000 GOLD
SELL
Amulet of the Eager Warrior +1
Strength: 8
Resistance: 50
Grade: High
115,200 GOLD
SELL
Amulet of the Eager Warrior +2
Strength: 11
Resistance: 70
Grade: High
368,640 GOLD
SELL
Amulet of the Eager Warrior +3
Strength: 14
Resistance: 90
Grade: Rare
1,179,648 GOLD
SELL
Amulet of the Eager Warrior +4
Strength: 17
Resistance: 110
Grade: Rare
3,774,874 GOLD
SELL
Amulet of the Eager Warrior +5
Strength: 21
Resistance: 135
Grade: Rare
12,079,596 GOLD
SELL
The Ethereal Blade of Destiny
Evasion: 10%
Damage: 48
Range: +30
R.Piercing: 40
Grade: Rare
2,934,000 GOLD
SELL
The Ethereal Blade of Destiny +1
Evasion: 11%
Damage: 56
Range: +32
R.Piercing: 56
Grade: Rare
2,934,000 GOLD
SELL
The Ethereal Blade of Destiny +2
Evasion: 12%
Damage: 64
Range: +34
R.Piercing: 72
Grade: Rare
2,934,000 GOLD
SELL
The Ethereal Blade of Destiny +3
Evasion: 13%
Damage: 72
Range: +36
R.Piercing: 88
Grade: Rare
2,934,000 GOLD
SELL
The Ethereal Blade of Destiny +4
Evasion: 14%
Damage: 80
Range: +38
R.Piercing: 104
Grade: Rare
2,934,000 GOLD
SELL
The Ethereal Blade of Destiny +5
Evasion: 15%
Damage: 88
Range: +40
R.Piercing: 120
Grade: Rare
5,868,000 GOLD
SELL
The Ethereal Blade of Destiny +6
Evasion: 16%
Damage: 96
Range: +42
R.Piercing: 136
Grade: Rare
11,736,000 GOLD
SELL
The Ethereal Blade of Destiny +7
Evasion: 17.25%
Damage: 106
Range: +45
R.Piercing: 156
Grade: Rare
23,472,000 GOLD
SELL
The Ethereal Blade of Destiny +8
Evasion: 18.75%
Damage: 118
Range: +48
R.Piercing: 180
Grade: Rare
46,944,000 GOLD
SELL
The Ethereal Blade of Destiny +9
Evasion: 20.75%
Damage: 134
Range: +52
R.Piercing: 212
Grade: Rare
93,888,000 GOLD
SELL
The Ethereal Blade of Destiny +10
Evasion: 23.75%
Damage: 158
Range: +58
R.Piercing: 260
Grade: Rare
187,776,000 GOLD
SELL
Sturdy Coat
Stat: 1
Armor: 24
Resistance: 16
Grade: High
28,800 GOLD
SELL
Sturdy Coat +1
Stat: 2
Armor: 27
Resistance: 19
Grade: High
28,800 GOLD
SELL
Sturdy Coat +2
Stat: 3
Armor: 29
Resistance: 21
Grade: High
28,800 GOLD
SELL
Sturdy Coat +3
Stat: 4
Armor: 32
Resistance: 24
Grade: High
28,800 GOLD
SELL
Sturdy Coat +4
Stat: 5
Armor: 34
Resistance: 26
Grade: High
28,800 GOLD
SELL
Sturdy Coat +5
Stat: 6
Armor: 37
Resistance: 29
Grade: High
57,600 GOLD
SELL
Sturdy Coat +6
Stat: 7
Armor: 39
Resistance: 31
Grade: High
115,200 GOLD
SELL
Sturdy Coat +7
Stat: 9
Armor: 42
Resistance: 34
Grade: Rare
230,400 GOLD
SELL
Sturdy Coat +8
Stat: 12
Armor: 46
Resistance: 38
Grade: Rare
460,800 GOLD
SELL
Sturdy Coat +9
Stat: 15
Armor: 51
Resistance: 43
Grade: Rare
921,600 GOLD
SELL
Sturdy Coat +10
Stat: 19
Armor: 58
Resistance: 50
Grade: Rare
1,843,200 GOLD
SELL
Pumpkin Spice Latte
Reflection: 2%
Crit: 5%
MP: -400
Hours: 8
Produced in bulk during the Halloween season. WARNING: The pumpkin comes from a non-vegetable source
Xmas Box
Finally... They all came together. A unique gift lies within this box. Take it to Xyn to be unlocked.
Band of Fury
Crit: 6%
Dexterity: 2
Stat: 1
Armor: 11
A.Piercing: 20
Resistance: 12
Grade: Rare
3,840,000 GOLD
SELL
Band of Fury +1
Crit: 6.5%
Dexterity: 2
Stat: 2
Armor: 12
A.Piercing: 30
Resistance: 14
Grade: Rare
3,840,000 GOLD
SELL
Band of Fury +2
Crit: 7%
Dexterity: 2
Stat: 3
Armor: 14
A.Piercing: 40
Resistance: 16
Grade: Rare
3,840,000 GOLD
SELL
Band of Fury +3
Crit: 7.5%
Dexterity: 2
Stat: 4
Armor: 16
A.Piercing: 50
Resistance: 18
Grade: Rare
3,840,000 GOLD
SELL
Band of Fury +4
Crit: 8%
Dexterity: 2
Stat: 5
Armor: 18
A.Piercing: 60
Resistance: 20
Grade: Rare
3,840,000 GOLD
SELL
Band of Fury +5
Crit: 8.5%
Dexterity: 2
Stat: 6
Armor: 20
A.Piercing: 70
Resistance: 21
Grade: Rare
7,680,000 GOLD
SELL
Band of Fury +6
Crit: 9%
Dexterity: 2
Stat: 7
Armor: 22
A.Piercing: 80
Resistance: 23
Grade: Rare
15,360,000 GOLD
SELL
Band of Fury +7
Crit: 9.625%
Dexterity: 2
Stat: 9
Armor: 24
A.Piercing: 93
Resistance: 26
Grade: Rare
30,720,000 GOLD
SELL
Band of Fury +8
Crit: 10.375%
Dexterity: 2
Stat: 12
Armor: 27
A.Piercing: 108
Resistance: 28
Grade: Rare
61,440,000 GOLD
SELL
Band of Fury +9
Crit: 11.375%
Dexterity: 2
Stat: 15
Armor: 31
A.Piercing: 128
Resistance: 32
Grade: Rare
122,880,000 GOLD
SELL
Band of Fury +10
Crit: 12.875%
Dexterity: 2
Stat: 19
Armor: 36
A.Piercing: 158
Resistance: 38
Grade: Rare
245,760,000 GOLD
SELL
Darkforge Boots
Stat: 1
Armor: 16
Resistance: 8
Speed: +8
Grade: Rare
7,440,000 GOLD
SELL
Darkforge Boots +1
Stat: 2
Armor: 22
Resistance: 11
Speed: +9
Grade: Rare
7,440,000 GOLD
SELL
Darkforge Boots +2
Stat: 3
Armor: 27
Resistance: 14
Speed: +11
Grade: Rare
7,440,000 GOLD
SELL
Darkforge Boots +3
Stat: 4
Armor: 33
Resistance: 16
Speed: +12
Grade: Rare
7,440,000 GOLD
SELL
Darkforge Boots +4
Stat: 5
Armor: 38
Resistance: 19
Speed: +14
Grade: Rare
7,440,000 GOLD
SELL
Darkforge Boots +5
Stat: 6
Armor: 44
Resistance: 22
Speed: +15
Grade: Rare
14,880,000 GOLD
SELL
Darkforge Boots +6
Stat: 7
Armor: 49
Resistance: 25
Speed: +16
Grade: Rare
29,760,000 GOLD
SELL
Darkforge Boots +7
Stat: 9
Armor: 56
Resistance: 28
Speed: +18
Grade: Rare
59,520,000 GOLD
SELL
Darkforge Boots +8
Stat: 12
Armor: 64
Resistance: 32
Speed: +20
Grade: Rare
119,040,000 GOLD
SELL
Darkforge Boots +9
Stat: 15
Armor: 75
Resistance: 38
Speed: +23
Grade: Rare
238,080,000 GOLD
SELL
Darkforge Boots +10
Stat: 19
Armor: 92
Resistance: 46
Speed: +27
Grade: Rare
476,160,000 GOLD
SELL
Earring of Vitality
Vitality: 3
30,000 GOLD
SELL
Earring of Vitality +1
Vitality: 5
96,000 GOLD
SELL
Earring of Vitality +2
Vitality: 7
Grade: High
307,200 GOLD
SELL
Earring of Vitality +3
Vitality: 9
Grade: High
983,040 GOLD
SELL
Earring of Vitality +4
Vitality: 11
Grade: High
3,145,728 GOLD
SELL
Earring of Vitality +5
Vitality: 14
Grade: Rare
10,066,330 GOLD
SELL
Weapon Box
Can be exchanged for a random, rare weapon.
Ledger
Every decent merchant needs one!
Amulet of Intelligence
Intelligence: 4
18,000 GOLD
SELL
Amulet of Intelligence +1
Intelligence: 7
57,600 GOLD
SELL
Amulet of Intelligence +2
Intelligence: 10
184,320 GOLD
SELL
Amulet of Intelligence +3
Intelligence: 13
Grade: High
589,824 GOLD
SELL
Amulet of Intelligence +4
Intelligence: 16
Grade: High
1,887,437 GOLD
SELL
Amulet of Intelligence +5
Intelligence: 20
Grade: Rare
6,039,798 GOLD
SELL
Frozen Stone
It's strangely not cold, must be a magical artifact.
Ghastly Battle Axe
Reflection: 4%
Damage: 36
Range: +8
Speed: Slow
Grade: High
43,200 GOLD
SELL
Ghastly Battle Axe +1
Reflection: 4%
Damage: 46
Range: +9
Speed: Slow
Grade: High
43,200 GOLD
SELL
Ghastly Battle Axe +2
Reflection: 4%
Damage: 55
Range: +10
Speed: Slow
Grade: High
43,200 GOLD
SELL
Ghastly Battle Axe +3
Reflection: 4%
Damage: 65
Range: +11
Speed: Slow
Grade: High
43,200 GOLD
SELL
Ghastly Battle Axe +4
Reflection: 4%
Damage: 74
Range: +12
Speed: Slow
Grade: High
43,200 GOLD
SELL
Ghastly Battle Axe +5
Reflection: 4%
Damage: 84
Range: +13
Speed: Slow
Grade: High
86,400 GOLD
SELL
Ghastly Battle Axe +6
Reflection: 4%
Damage: 93
Range: +14
Speed: Slow
Grade: Rare
172,800 GOLD
SELL
Ghastly Battle Axe +7
Reflection: 4%
Damage: 105
Range: +15
Speed: Slow
Grade: Rare
345,600 GOLD
SELL
Ghastly Battle Axe +8
Reflection: 4%
Damage: 119
Range: +17
Speed: Slow
Grade: Rare
691,200 GOLD
SELL
Ghastly Battle Axe +9
Reflection: 4%
Damage: 138
Range: +19
Speed: Slow
Grade: Rare
1,382,400 GOLD
SELL
Ghastly Battle Axe +10
Reflection: 4%
Damage: 167
Range: +22
Speed: Slow
Grade: Rare
2,764,800 GOLD
SELL
Bunny Energy Drink
HP: 200
Dexterity: 4
Vitality: 15
MP: 300
Speed: +12
Hours: 2
Ingredients: Rabbit sweat, bubble gum flavour
Earring of Dexterity
Dexterity: 3
30,000 GOLD
SELL
Earring of Dexterity +1
Dexterity: 5
96,000 GOLD
SELL
Earring of Dexterity +2
Dexterity: 7
Grade: High
307,200 GOLD
SELL
Earring of Dexterity +3
Dexterity: 9
Grade: High
983,040 GOLD
SELL
Earring of Dexterity +4
Dexterity: 11
Grade: High
3,145,728 GOLD
SELL
Earring of Dexterity +5
Dexterity: 14
Grade: Rare
10,066,330 GOLD
SELL
Elixir of Dexterity
Dexterity: 6
Hours: 12
Darkforge Gloves
Stat: 1
Armor: 32
Resistance: 16
Grade: Rare
2,040,000 GOLD
SELL
Darkforge Gloves +1
Stat: 2
Armor: 38
Resistance: 22
Grade: Rare
2,040,000 GOLD
SELL
Darkforge Gloves +2
Stat: 3
Armor: 43
Resistance: 27
Grade: Rare
2,040,000 GOLD
SELL
Darkforge Gloves +3
Stat: 4
Armor: 49
Resistance: 33
Grade: Rare
2,040,000 GOLD
SELL
Darkforge Gloves +4
Stat: 5
Armor: 54
Resistance: 38
Grade: Rare
2,040,000 GOLD
SELL
Darkforge Gloves +5
Stat: 6
Armor: 60
Resistance: 44
Grade: Rare
4,080,000 GOLD
SELL
Darkforge Gloves +6
Stat: 7
Armor: 65
Resistance: 49
Grade: Rare
8,160,000 GOLD
SELL
Darkforge Gloves +7
Stat: 9
Armor: 72
Resistance: 56
Grade: Rare
16,320,000 GOLD
SELL
Darkforge Gloves +8
Stat: 12
Armor: 80
Resistance: 64
Grade: Rare
32,640,000 GOLD
SELL
Darkforge Gloves +9
Stat: 15
Armor: 91
Resistance: 75
Grade: Rare
65,280,000 GOLD
SELL
Darkforge Gloves +10
Stat: 19
Armor: 108
Resistance: 92
Grade: Rare
130,560,000 GOLD
SELL
Elixir of Extreme Dexterity
Dexterity: 12
Hours: 48
Mistletoe
Maybe someone could give you a kiss in exchange...
Stone of Luck
Increases your chances to loot something from a monster by 20%.
Mole's Teeth
A.Piercing: 15
Grade: High
300,000 GOLD
SELL
Mole's Teeth +1
A.Piercing: 30
Grade: Rare
960,000 GOLD
SELL
Mole's Teeth +2
A.Piercing: 45
Grade: Rare
3,072,000 GOLD
SELL
Mole's Teeth +3
A.Piercing: 60
Grade: Rare
9,830,400 GOLD
SELL
Mole's Teeth +4
A.Piercing: 75
Grade: Rare
31,457,280 GOLD
SELL
Mole's Teeth +5
A.Piercing: 94
Grade: Rare
100,663,296 GOLD
SELL
Orb of Strength
Strength: 5
144,000 GOLD
SELL
Orb of Strength +1
Strength: 10
460,800 GOLD
SELL
Orb of Strength +2
Strength: 15
1,474,560 GOLD
SELL
Orb of Strength +3
Strength: 20
4,718,592 GOLD
SELL
Orb of Strength +4
Strength: 25
15,099,494 GOLD
SELL
Orb of Strength +5
Strength: 31
48,318,382 GOLD
SELL
Book of Knowledge
Intelligence: 6
7,200 GOLD
SELL
Book of Knowledge +1
Intelligence: 11
23,040 GOLD
SELL
Book of Knowledge +2
Intelligence: 16
73,728 GOLD
SELL
Book of Knowledge +3
Intelligence: 21
235,930 GOLD
SELL
Book of Knowledge +4
Intelligence: 26
754,975 GOLD
SELL
Book of Knowledge +5
Intelligence: 32
2,415,919 GOLD
SELL
Book of Secrets
Reflection: 2%
Intelligence: 16
Vitality: 6
Grade: High
7,200 GOLD
SELL
Book of Secrets +1
Reflection: 3%
Intelligence: 21
Vitality: 8
Grade: High
23,040 GOLD
SELL
Book of Secrets +2
Reflection: 4%
Intelligence: 26
Vitality: 10
Grade: Rare
73,728 GOLD
SELL
Book of Secrets +3
Reflection: 5%
Intelligence: 31
Vitality: 12
Grade: Rare
235,930 GOLD
SELL
Book of Secrets +4
Reflection: 6%
Intelligence: 36
Vitality: 14
Grade: Rare
754,975 GOLD
SELL
Book of Secrets +5
Reflection: 7.25%
Intelligence: 42
Vitality: 17
Grade: Rare
2,415,919 GOLD
SELL
Flute
The sound of each flute is unique and mesmerizing. Your pets will easily recognize the sound of yours and come to your call.
Cupid's Bow
Damage: 29
Range: +60
Vitality: 10
Grade: High
36,000 GOLD
SELL
Cupid's Bow +1
Damage: 34
Range: +68
Vitality: 12
Grade: High
36,000 GOLD
SELL
Cupid's Bow +2
Damage: 39
Range: +76
Vitality: 14
Grade: High
36,000 GOLD
SELL
Cupid's Bow +3
Damage: 44
Range: +84
Vitality: 16
Grade: High
36,000 GOLD
SELL
Cupid's Bow +4
Damage: 50
Range: +92
Vitality: 18
Grade: High
36,000 GOLD
SELL
Cupid's Bow +5
Damage: 55
Range: +100
Vitality: 20
Grade: High
72,000 GOLD
SELL
Cupid's Bow +6
Damage: 60
Range: +108
Vitality: 22
Grade: Rare
144,000 GOLD
SELL
Cupid's Bow +7
Damage: 66
Range: +118
Vitality: 25
Grade: Rare
288,000 GOLD
SELL
Cupid's Bow +8
Damage: 74
Range: +130
Vitality: 28
Grade: Rare
576,000 GOLD
SELL
Cupid's Bow +9
Damage: 84
Range: +146
Vitality: 32
Grade: Rare
1,152,000 GOLD
SELL
Cupid's Bow +10
Damage: 99
Range: +170
Vitality: 38
Grade: Rare
2,304,000 GOLD
SELL
Elixir of Greater Vitality
Vitality: 12
Hours: 24
Eggnog
Evasion: 2.5%
HP: 600
Hours: 48
Fills your heart with warmth and joy.
Warm Scarf
Strength: 2
Intelligence: 2
Dexterity: 2
Armor: 10
A.Piercing: 5
R.Piercing: 5
Resistance: 10
Stylish and deadly!
6,000 GOLD
SELL
Warm Scarf +1
Strength: 2
Intelligence: 2
Dexterity: 2
Armor: 10
A.Piercing: 6
R.Piercing: 6
Resistance: 10
Stylish and deadly!
6,000 GOLD
SELL
Warm Scarf +2
Strength: 2
Intelligence: 2
Dexterity: 2
Armor: 10
A.Piercing: 8
R.Piercing: 8
Resistance: 10
Stylish and deadly!
6,000 GOLD
SELL
Warm Scarf +3
Strength: 2
Intelligence: 2
Dexterity: 2
Armor: 10
A.Piercing: 9
R.Piercing: 9
Resistance: 10
Stylish and deadly!
6,000 GOLD
SELL
Warm Scarf +4
Strength: 2
Intelligence: 2
Dexterity: 2
Armor: 10
A.Piercing: 10
R.Piercing: 10
Resistance: 10
Stylish and deadly!
6,000 GOLD
SELL
Warm Scarf +5
Strength: 2
Intelligence: 2
Dexterity: 2
Armor: 10
A.Piercing: 11
R.Piercing: 11
Resistance: 10
Stylish and deadly!
12,000 GOLD
SELL
Warm Scarf +6
Strength: 2
Intelligence: 2
Dexterity: 2
Armor: 10
A.Piercing: 13
R.Piercing: 13
Resistance: 10
Stylish and deadly!
24,000 GOLD
SELL
Warm Scarf +7
Strength: 2
Intelligence: 2
Dexterity: 2
Armor: 10
A.Piercing: 14
R.Piercing: 14
Resistance: 10
Grade: High
Stylish and deadly!
48,000 GOLD
SELL
Warm Scarf +8
Strength: 2
Intelligence: 2
Dexterity: 2
Armor: 10
A.Piercing: 16
R.Piercing: 16
Resistance: 10
Grade: High
Stylish and deadly!
96,000 GOLD
SELL
Warm Scarf +9
Strength: 2
Intelligence: 2
Dexterity: 2
Armor: 10
A.Piercing: 18
R.Piercing: 18
Resistance: 10
Grade: Rare
Stylish and deadly!
192,000 GOLD
SELL
Warm Scarf +10
Strength: 2
Intelligence: 2
Dexterity: 2
Armor: 10
A.Piercing: 22
R.Piercing: 22
Resistance: 10
Grade: Rare
Stylish and deadly!
384,000 GOLD
SELL
Gem Fragment
Beautiful, yet broken. Would be extremely valuable if they were whole.
Wooden Shield
Stat: 2
Armor: 40
Resistance: 15
2,880 GOLD
SELL
Wooden Shield +1
Stat: 2
Armor: 48
Resistance: 20
2,880 GOLD
SELL
Wooden Shield +2
Stat: 2
Armor: 56
Resistance: 25
2,880 GOLD
SELL
Wooden Shield +3
Stat: 2
Armor: 64
Resistance: 30
2,880 GOLD
SELL
Wooden Shield +4
Stat: 2
Armor: 72
Resistance: 35
2,880 GOLD
SELL
Wooden Shield +5
Stat: 2
Armor: 80
Resistance: 40
5,760 GOLD
SELL
Wooden Shield +6
Stat: 2
Armor: 88
Resistance: 45
11,520 GOLD
SELL
Wooden Shield +7
Stat: 2
Armor: 98
Resistance: 51
Grade: High
23,040 GOLD
SELL
Wooden Shield +8
Stat: 2
Armor: 110
Resistance: 59
Grade: High
46,080 GOLD
SELL
Wooden Shield +9
Stat: 2
Armor: 126
Resistance: 69
Grade: Rare
92,160 GOLD
SELL
Wooden Shield +10
Stat: 2
Armor: 150
Resistance: 84
Grade: Rare
184,320 GOLD
SELL
MP Potion
MP: +500
Helmet
Stat: 1
Armor: 7
Resistance: 8
1,920 GOLD
SELL
Helmet +1
Stat: 2
Armor: 8
Resistance: 9
1,920 GOLD
SELL
Helmet +2
Stat: 3
Armor: 10
Resistance: 11
1,920 GOLD
SELL
Helmet +3
Stat: 4
Armor: 11
Resistance: 12
1,920 GOLD
SELL
Helmet +4
Stat: 5
Armor: 12
Resistance: 13
1,920 GOLD
SELL
Helmet +5
Stat: 6
Armor: 13
Resistance: 14
3,840 GOLD
SELL
Helmet +6
Stat: 7
Armor: 15
Resistance: 16
7,680 GOLD
SELL
Helmet +7
Stat: 9
Armor: 16
Resistance: 17
Grade: High
15,360 GOLD
SELL
Helmet +8
Stat: 12
Armor: 18
Resistance: 19
Grade: High
30,720 GOLD
SELL
Helmet +9
Stat: 15
Armor: 20
Resistance: 21
Grade: Rare
61,440 GOLD
SELL
Helmet +10
Stat: 19
Armor: 24
Resistance: 25
Grade: Rare
122,880 GOLD
SELL
Dark Tri-Stone
Evasion: 3%
Strength: 1
Intelligence: 1
Dexterity: 1
Vitality: 1
A.Piercing: 5
R.Piercing: 5
3,000 GOLD
SELL
Dark Tri-Stone +1
Evasion: 3%
Strength: 2
Intelligence: 2
Dexterity: 2
Vitality: 2
A.Piercing: 10
R.Piercing: 10
Grade: High
9,600 GOLD
SELL
Dark Tri-Stone +2
Evasion: 3%
Strength: 3
Intelligence: 3
Dexterity: 3
Vitality: 3
A.Piercing: 15
R.Piercing: 15
Grade: High
30,720 GOLD
SELL
Dark Tri-Stone +3
Evasion: 3%
Strength: 4
Intelligence: 4
Dexterity: 4
Vitality: 4
A.Piercing: 20
R.Piercing: 20
Grade: High
98,304 GOLD
SELL
Dark Tri-Stone +4
Evasion: 3%
Strength: 5
Intelligence: 5
Dexterity: 5
Vitality: 5
A.Piercing: 25
R.Piercing: 25
Grade: Rare
314,573 GOLD
SELL
Dark Tri-Stone +5
Evasion: 3%
Strength: 6
Intelligence: 6
Dexterity: 6
Vitality: 6
A.Piercing: 31
R.Piercing: 31
Grade: Rare
1,006,633 GOLD
SELL
HP Potion
HP: +200
Basher
Damage: 24
Range: +5
Armor: 20
Speed: Slow
Run Speed: -15
Grade: High
Ability: Bash
Stuns the opponent for 1 seconds with 0.5% chance.
43,200 GOLD
SELL
Basher +1
Damage: 32
Range: +6
Armor: 24
Speed: Slow
Run Speed: -14
Grade: High
Ability: Bash
Stuns the opponent for 1.2 seconds with 0.9% chance.
43,200 GOLD
SELL
Basher +2
Damage: 40
Range: +7
Armor: 28
Speed: Slow
Run Speed: -13
Grade: High
Ability: Bash
Stuns the opponent for 1.4 seconds with 1.3% chance.
43,200 GOLD
SELL
Basher +3
Damage: 48
Range: +8
Armor: 32
Speed: Slow
Run Speed: -12
Grade: High
Ability: Bash
Stuns the opponent for 1.6 seconds with 1.7000000000000002% chance.
43,200 GOLD
SELL
Basher +4
Damage: 56
Range: +9
Armor: 36
Speed: Slow
Run Speed: -11
Grade: High
Ability: Bash
Stuns the opponent for 1.8 seconds with 2.1% chance.
43,200 GOLD
SELL
Basher +5
Damage: 64
Range: +10
Armor: 40
Speed: Slow
Run Speed: -10
Grade: High
Ability: Bash
Stuns the opponent for 2 seconds with 2.5% chance.
86,400 GOLD
SELL
Basher +6
Damage: 72
Range: +11
Armor: 44
Speed: Slow
Run Speed: -9
Grade: High
Ability: Bash
Stuns the opponent for 2.2 seconds with 2.9% chance.
172,800 GOLD
SELL
Basher +7
Damage: 82
Range: +12
Armor: 49
Speed: Slow
Run Speed: -8
Grade: Rare
Ability: Bash
Stuns the opponent for 2.45 seconds with 3.4% chance.
345,600 GOLD
SELL
Basher +8
Damage: 94
Range: +14
Armor: 55
Speed: Slow
Run Speed: -6
Grade: Rare
Ability: Bash
Stuns the opponent for 2.75 seconds with 4% chance.
691,200 GOLD
SELL
Basher +9
Damage: 110
Range: +16
Armor: 63
Speed: Slow
Run Speed: -4
Grade: Rare
Ability: Bash
Stuns the opponent for 3.15 seconds with 4.8% chance.
1,382,400 GOLD
SELL
Basher +10
Damage: 134
Range: +19
Armor: 75
Speed: Slow
Run Speed: -1
Grade: Rare
Ability: Bash
Stuns the opponent for 3.75 seconds with 6% chance.
2,764,800 GOLD
SELL
Agile Quiver
Evasion: 1%
Range: +20
Dexterity: 9
Armor: 12
Grade: High
72,000 GOLD
SELL
Agile Quiver +1
Evasion: 1%
Range: +24
Dexterity: 11
Armor: 15
Grade: High
72,000 GOLD
SELL
Agile Quiver +2
Evasion: 1%
Range: +27
Dexterity: 12
Armor: 18
Grade: High
72,000 GOLD
SELL
Agile Quiver +3
Evasion: 1%
Range: +31
Dexterity: 14
Armor: 21
Grade: High
72,000 GOLD
SELL
Agile Quiver +4
Evasion: 1%
Range: +34
Dexterity: 15
Armor: 24
Grade: Rare
72,000 GOLD
SELL
Agile Quiver +5
Evasion: 1%
Range: +38
Dexterity: 17
Armor: 27
Grade: Rare
144,000 GOLD
SELL
Agile Quiver +6
Evasion: 1%
Range: +41
Dexterity: 18
Armor: 30
Grade: Rare
288,000 GOLD
SELL
Agile Quiver +7
Evasion: 1%
Range: +45
Dexterity: 20
Armor: 34
Grade: Rare
576,000 GOLD
SELL
Agile Quiver +8
Evasion: 1%
Range: +51
Dexterity: 22
Armor: 38
Grade: Rare
1,152,000 GOLD
SELL
Agile Quiver +9
Evasion: 1%
Range: +58
Dexterity: 25
Armor: 44
Grade: Rare
2,304,000 GOLD
SELL
Agile Quiver +10
Evasion: 1%
Range: +68
Dexterity: 30
Armor: 53
Grade: Rare
4,608,000 GOLD
SELL
Candy Cane Sword
Damage: 20
Range: +3
Grade: High
Ability: Sugar Rush
Trigger a Sugar Rush on attack with 0.25% chance. Gain 240 Attack Speed for 10 seconds!
43,200 GOLD
SELL
Candy Cane Sword +1
Damage: 25
Range: +4
Grade: High
Ability: Sugar Rush
Trigger a Sugar Rush on attack with 0.25% chance. Gain 240 Attack Speed for 10 seconds!
43,200 GOLD
SELL
Candy Cane Sword +2
Damage: 29
Range: +5
Grade: High
Ability: Sugar Rush
Trigger a Sugar Rush on attack with 0.25% chance. Gain 240 Attack Speed for 10 seconds!
43,200 GOLD
SELL
Candy Cane Sword +3
Damage: 34
Range: +6
Grade: High
Ability: Sugar Rush
Trigger a Sugar Rush on attack with 0.25% chance. Gain 240 Attack Speed for 10 seconds!
43,200 GOLD
SELL
Candy Cane Sword +4
Damage: 38
Range: +7
Grade: High
Ability: Sugar Rush
Trigger a Sugar Rush on attack with 0.25% chance. Gain 240 Attack Speed for 10 seconds!
43,200 GOLD
SELL
Candy Cane Sword +5
Damage: 43
Range: +8
Grade: High
Ability: Sugar Rush
Trigger a Sugar Rush on attack with 0.25% chance. Gain 240 Attack Speed for 10 seconds!
86,400 GOLD
SELL
Candy Cane Sword +6
Damage: 47
Range: +9
Grade: High
Ability: Sugar Rush
Trigger a Sugar Rush on attack with 0.25% chance. Gain 240 Attack Speed for 10 seconds!
172,800 GOLD
SELL
Candy Cane Sword +7
Damage: 53
Range: +10
Grade: High
Ability: Sugar Rush
Trigger a Sugar Rush on attack with 0.25% chance. Gain 240 Attack Speed for 10 seconds!
345,600 GOLD
SELL
Candy Cane Sword +8
Damage: 59
Range: +12
Grade: Rare
Ability: Sugar Rush
Trigger a Sugar Rush on attack with 0.25% chance. Gain 240 Attack Speed for 10 seconds!
691,200 GOLD
SELL
Candy Cane Sword +9
Damage: 68
Range: +14
Grade: Rare
Ability: Sugar Rush
Trigger a Sugar Rush on attack with 0.25% chance. Gain 240 Attack Speed for 10 seconds!
1,382,400 GOLD
SELL
Candy Cane Sword +10
Damage: 82
Range: +17
Grade: Rare
Ability: Sugar Rush
Trigger a Sugar Rush on attack with 0.25% chance. Gain 240 Attack Speed for 10 seconds!
2,764,800 GOLD
SELL
Magical Feather
Holding this, you understand how those huge birds can fly, it's not a normal feather!
Quantum Piece
A unique component of a curious puzzle
HP Potion
HP: +400
Reflection Scroll
Adds Reflection to an armor with a Stat attribute.
Ornament Staff
Damage: 30
Range: +60
MP Cost: -40
Awesomeness: 99
Grade: High
72,000 GOLD
SELL
Ornament Staff +1
Damage: 36
Range: +63
MP Cost: -40
Awesomeness: 99
Grade: High
72,000 GOLD
SELL
Ornament Staff +2
Damage: 42
Range: +66
MP Cost: -40
Awesomeness: 99
Grade: High
72,000 GOLD
SELL
Ornament Staff +3
Damage: 48
Range: +69
MP Cost: -40
Awesomeness: 99
Grade: High
72,000 GOLD
SELL
Ornament Staff +4
Damage: 54
Range: +72
MP Cost: -40
Awesomeness: 99
Grade: High
72,000 GOLD
SELL
Ornament Staff +5
Damage: 60
Range: +75
MP Cost: -40
Awesomeness: 100
Grade: High
144,000 GOLD
SELL
Ornament Staff +6
Damage: 66
Range: +78
MP Cost: -40
Awesomeness: 100
Grade: High
288,000 GOLD
SELL
Ornament Staff +7
Damage: 74
Range: +82
MP Cost: -40
Awesomeness: 100
Grade: Rare
576,000 GOLD
SELL
Ornament Staff +8
Damage: 83
Range: +86
MP Cost: -40
Awesomeness: 100
Grade: Rare
1,152,000 GOLD
SELL
Ornament Staff +9
Damage: 95
Range: +92
MP Cost: -40
Awesomeness: 100
Grade: Rare
2,304,000 GOLD
SELL
Ornament Staff +10
Damage: 113
Range: +101
MP Cost: -40
Awesomeness: 100
Grade: Rare
4,608,000 GOLD
SELL
Orb of Second Chances
Strength: 2
Intelligence: 2
Dexterity: 2
Vitality: 2
MP: 200
Grade: Rare
Ability: Second Chance
Avoid death with a 1% chance.
72,000 GOLD
SELL
Orb of Second Chances +1
Strength: 3
Intelligence: 4
Dexterity: 3
Vitality: 3
MP: 300
Grade: Rare
Ability: Second Chance
Avoid death with a 2% chance.
230,400 GOLD
SELL
Orb of Second Chances +2
Strength: 4
Intelligence: 6
Dexterity: 4
Vitality: 4
MP: 400
Grade: Rare
Ability: Second Chance
Avoid death with a 3% chance.
737,280 GOLD
SELL
Orb of Second Chances +3
Strength: 5
Intelligence: 8
Dexterity: 5
Vitality: 5
MP: 500
Grade: Rare
Ability: Second Chance
Avoid death with a 4% chance.
2,359,296 GOLD
SELL
Orb of Second Chances +4
Strength: 6
Intelligence: 10
Dexterity: 6
Vitality: 6
MP: 600
Grade: Rare
Ability: Second Chance
Avoid death with a 5% chance.
7,549,747 GOLD
SELL
Orb of Second Chances +5
Strength: 7
Intelligence: 13
Dexterity: 7
Vitality: 7
MP: 725
Grade: Rare
Ability: Second Chance
Avoid death with a 6.25% chance.
24,159,191 GOLD
SELL
T4 Bow
Damage: 38
Range: +60
9,600 GOLD
SELL
T4 Bow +1
Damage: 44
Range: +68
9,600 GOLD
SELL
T4 Bow +2
Damage: 51
Range: +76
9,600 GOLD
SELL
T4 Bow +3
Damage: 57
Range: +84
9,600 GOLD
SELL
T4 Bow +4
Damage: 63
Range: +92
9,600 GOLD
SELL
T4 Bow +5
Damage: 69
Range: +100
19,200 GOLD
SELL
T4 Bow +6
Damage: 76
Range: +108
38,400 GOLD
SELL
T4 Bow +7
Damage: 83
Range: +118
Grade: High
76,800 GOLD
SELL
T4 Bow +8
Damage: 93
Range: +130
Grade: High
153,600 GOLD
SELL
T4 Bow +9
Damage: 105
Range: +146
Grade: Rare
307,200 GOLD
SELL
T4 Bow +10
Damage: 124
Range: +170
Grade: Rare
614,400 GOLD
SELL
Gold Earring
Grade: High
Looks valuable
72,000 GOLD
SELL
Gold Earring +1
Grade: Rare
Looks valuable
230,400 GOLD
SELL
Gold Earring +2
Grade: Rare
Looks valuable
737,280 GOLD
SELL
Gold Earring +3
Grade: Rare
Looks valuable
2,359,296 GOLD
SELL
Gold Earring +4
Grade: Rare
Looks valuable
7,549,747 GOLD
SELL
Gold Earring +5
Grade: Rare
Looks valuable
24,159,191 GOLD
SELL
Oozing Terror
Reflection: 1%
Damage: 40
Range: +50
Intelligence: 20
Vitality: -30
Grade: High
It drains the life energy of the user
173,400 GOLD
SELL
Oozing Terror +1
Reflection: 1.25%
Damage: 46
Range: +53
Intelligence: 21
Vitality: -30
Grade: High
It drains the life energy of the user
173,400 GOLD
SELL
Oozing Terror +2
Reflection: 1.5%
Damage: 52
Range: +56
Intelligence: 22
Vitality: -30
Grade: High
It drains the life energy of the user
173,400 GOLD
SELL
Oozing Terror +3
Reflection: 1.75%
Damage: 58
Range: +59
Intelligence: 23
Vitality: -30
Grade: High
It drains the life energy of the user
173,400 GOLD
SELL
Oozing Terror +4
Reflection: 2%
Damage: 64
Range: +62
Intelligence: 24
Vitality: -30
Grade: High
It drains the life energy of the user
173,400 GOLD
SELL
Oozing Terror +5
Reflection: 2.25%
Damage: 70
Range: +65
Intelligence: 25
Vitality: -30
Grade: High
It drains the life energy of the user
346,800 GOLD
SELL
Oozing Terror +6
Reflection: 2.5%
Damage: 76
Range: +68
Intelligence: 26
Vitality: -30
Grade: Rare
It drains the life energy of the user
693,600 GOLD
SELL
Oozing Terror +7
Reflection: 2.8125%
Damage: 84
Range: +72
Intelligence: 27
Vitality: -30
Grade: Rare
It drains the life energy of the user
1,387,200 GOLD
SELL
Oozing Terror +8
Reflection: 3.1875%
Damage: 93
Range: +76
Intelligence: 29
Vitality: -30
Grade: Rare
It drains the life energy of the user
2,774,400 GOLD
SELL
Oozing Terror +9
Reflection: 3.6875%
Damage: 105
Range: +82
Intelligence: 31
Vitality: -30
Grade: Rare
It drains the life energy of the user
5,548,800 GOLD
SELL
Oozing Terror +10
Reflection: 4.4375%
Damage: 123
Range: +91
Intelligence: 34
Vitality: -30
Grade: Rare
It drains the life energy of the user
11,097,600 GOLD
SELL
Ring of Intelligence
Intelligence: 2
14,400 GOLD
SELL
Ring of Intelligence +1
Intelligence: 4
46,080 GOLD
SELL
Ring of Intelligence +2
Intelligence: 6
147,456 GOLD
SELL
Ring of Intelligence +3
Intelligence: 8
Grade: High
471,859 GOLD
SELL
Ring of Intelligence +4
Intelligence: 10
Grade: High
1,509,949 GOLD
SELL
Ring of Intelligence +5
Intelligence: 13
Grade: Rare
4,831,838 GOLD
SELL
Xmas Sweater
Evasion: 0.5%
Stat: 1
Armor: 18
Resistance: 12
Such a beautiful vest. But for some reason, every time you wear this, people seem to avoid you.
9,600 GOLD
SELL
Xmas Sweater +1
Evasion: 0.75%
Stat: 2
Armor: 20
Resistance: 14
Such a beautiful vest. But for some reason, every time you wear this, people seem to avoid you.
9,600 GOLD
SELL
Xmas Sweater +2
Evasion: 1%
Stat: 3
Armor: 22
Resistance: 16
Such a beautiful vest. But for some reason, every time you wear this, people seem to avoid you.
9,600 GOLD
SELL
Xmas Sweater +3
Evasion: 1.25%
Stat: 4
Armor: 24
Resistance: 18
Such a beautiful vest. But for some reason, every time you wear this, people seem to avoid you.
9,600 GOLD
SELL
Xmas Sweater +4
Evasion: 1.5%
Stat: 5
Armor: 26
Resistance: 20
Grade: High
Such a beautiful vest. But for some reason, every time you wear this, people seem to avoid you.
9,600 GOLD
SELL
Xmas Sweater +5
Evasion: 1.75%
Stat: 6
Armor: 27
Resistance: 21
Grade: High
Such a beautiful vest. But for some reason, every time you wear this, people seem to avoid you.
19,200 GOLD
SELL
Xmas Sweater +6
Evasion: 2%
Stat: 7
Armor: 29
Resistance: 23
Grade: High
Such a beautiful vest. But for some reason, every time you wear this, people seem to avoid you.
38,400 GOLD
SELL
Xmas Sweater +7
Evasion: 2.3125%
Stat: 9
Armor: 32
Resistance: 26
Grade: High
Such a beautiful vest. But for some reason, every time you wear this, people seem to avoid you.
76,800 GOLD
SELL
Xmas Sweater +8
Evasion: 2.6875%
Stat: 12
Armor: 34
Resistance: 28
Grade: Rare
Such a beautiful vest. But for some reason, every time you wear this, people seem to avoid you.
153,600 GOLD
SELL
Xmas Sweater +9
Evasion: 3.1875%
Stat: 15
Armor: 38
Resistance: 32
Grade: Rare
Such a beautiful vest. But for some reason, every time you wear this, people seem to avoid you.
307,200 GOLD
SELL
Xmas Sweater +10
Evasion: 3.9375%
Stat: 19
Armor: 44
Resistance: 38
Grade: Rare
Such a beautiful vest. But for some reason, every time you wear this, people seem to avoid you.
614,400 GOLD
SELL
Orb of Resistance
Resistance: 40
144,000 GOLD
SELL
Orb of Resistance +1
Resistance: 60
460,800 GOLD
SELL
Orb of Resistance +2
Resistance: 80
1,474,560 GOLD
SELL
Orb of Resistance +3
Resistance: 100
4,718,592 GOLD
SELL
Orb of Resistance +4
Resistance: 120
15,099,494 GOLD
SELL
Orb of Resistance +5
Resistance: 145
48,318,382 GOLD
SELL
Ethereal Essence
A ghostly essence, maybe it could allow you to shift from this world momentarily
Poison Sack
This could be used to coat weapons or arrows one day...
Storage Box
It's a nifty little box
Mace of the Dead
Grade: High
A weapon none in the realm can wield!
74,400 GOLD
SELL
Mace of the Dead +1
Grade: High
A weapon none in the realm can wield!
74,400 GOLD
SELL
Mace of the Dead +2
Grade: High
A weapon none in the realm can wield!
74,400 GOLD
SELL
Mace of the Dead +3
Grade: High
A weapon none in the realm can wield!
74,400 GOLD
SELL
Mace of the Dead +4
Grade: High
A weapon none in the realm can wield!
74,400 GOLD
SELL
Mace of the Dead +5
Grade: High
A weapon none in the realm can wield!
148,800 GOLD
SELL
Mace of the Dead +6
Grade: Rare
A weapon none in the realm can wield!
297,600 GOLD
SELL
Mace of the Dead +7
Grade: Rare
A weapon none in the realm can wield!
595,200 GOLD
SELL
Mace of the Dead +8
Grade: Rare
A weapon none in the realm can wield!
1,190,400 GOLD
SELL
Mace of the Dead +9
Grade: Rare
A weapon none in the realm can wield!
2,380,800 GOLD
SELL
Mace of the Dead +10
Grade: Rare
A weapon none in the realm can wield!
4,761,600 GOLD
SELL
A Glitch
Huh?! Wtf.
Stick
...
6 GOLD
SELL
Stick +1
...
6 GOLD
SELL
Stick +2
...
6 GOLD
SELL
Stick +3
...
6 GOLD
SELL
Stick +4
Grade: High
...
6 GOLD
SELL
Stick +5
Grade: High
...
12 GOLD
SELL
Stick +6
Grade: High
...
24 GOLD
SELL
Stick +7
Grade: Rare
...
48 GOLD
SELL
Stick +8
Grade: Rare
...
96 GOLD
SELL
Stick +9
Grade: Rare
...
192 GOLD
SELL
Stick +10
Grade: Rare
...
384 GOLD
SELL
Candy
Halloween candy. Can be exchanged for random treasures.
Rare Candy
A rare Halloween candy. Can be exchanged for random treasures.
Mystery Box
It looks super cool, but you have no idea what to do with it!
Bow
Damage: 20
Range: +60
9,600 GOLD
SELL
Bow +1
Damage: 24
Range: +68
9,600 GOLD
SELL
Bow +2
Damage: 28
Range: +76
9,600 GOLD
SELL
Bow +3
Damage: 32
Range: +84
9,600 GOLD
SELL
Bow +4
Damage: 36
Range: +92
9,600 GOLD
SELL
Bow +5
Damage: 40
Range: +100
19,200 GOLD
SELL
Bow +6
Damage: 44
Range: +108
38,400 GOLD
SELL
Bow +7
Damage: 49
Range: +118
Grade: High
76,800 GOLD
SELL
Bow +8
Damage: 55
Range: +130
Grade: High
153,600 GOLD
SELL
Bow +9
Damage: 63
Range: +146
Grade: Rare
307,200 GOLD
SELL
Bow +10
Damage: 75
Range: +170
Grade: Rare
614,400 GOLD
SELL
Green Pumpkin Head
Luck: -20%
Lifesteal: 2%
Reflection: 1%
Crit: 0.5%
Stat: 1
Armor: 14
R.Piercing: 10
Resistance: 16
Grade: Rare
19,200 GOLD
SELL
Green Pumpkin Head +1
Luck: -20%
Lifesteal: 2%
Reflection: 1.4%
Crit: 0.6%
Stat: 2
Armor: 17
R.Piercing: 10
Resistance: 19
Grade: Rare
19,200 GOLD
SELL
Green Pumpkin Head +2
Luck: -20%
Lifesteal: 2%
Reflection: 1.8%
Crit: 0.7%
Stat: 3
Armor: 19
R.Piercing: 10
Resistance: 21
Grade: Rare
19,200 GOLD
SELL
Green Pumpkin Head +3
Luck: -20%
Lifesteal: 2%
Reflection: 2.2%
Crit: 0.8%
Stat: 4
Armor: 22
R.Piercing: 10
Resistance: 24
Grade: Rare
19,200 GOLD
SELL
Green Pumpkin Head +4
Luck: -20%
Lifesteal: 2%
Reflection: 2.6%
Crit: 0.9%
Stat: 5
Armor: 24
R.Piercing: 10
Resistance: 26
Grade: Rare
19,200 GOLD
SELL
Green Pumpkin Head +5
Luck: -20%
Lifesteal: 2%
Reflection: 3%
Crit: 1%
Stat: 6
Armor: 27
R.Piercing: 10
Resistance: 29
Grade: Rare
38,400 GOLD
SELL
Green Pumpkin Head +6
Luck: -20%
Lifesteal: 2%
Reflection: 3.4%
Crit: 1.1%
Stat: 7
Armor: 29
R.Piercing: 10
Resistance: 31
Grade: Rare
76,800 GOLD
SELL
Green Pumpkin Head +7
Luck: -20%
Lifesteal: 2%
Reflection: 3.9%
Crit: 1.225%
Stat: 9
Armor: 32
R.Piercing: 10
Resistance: 34
Grade: Rare
153,600 GOLD
SELL
Green Pumpkin Head +8
Luck: -20%
Lifesteal: 2%
Reflection: 4.5%
Crit: 1.375%
Stat: 12
Armor: 36
R.Piercing: 10
Resistance: 38
Grade: Rare
307,200 GOLD
SELL
Green Pumpkin Head +9
Luck: -20%
Lifesteal: 2%
Reflection: 5.3%
Crit: 1.575%
Stat: 15
Armor: 41
R.Piercing: 10
Resistance: 43
Grade: Rare
614,400 GOLD
SELL
Green Pumpkin Head +10
Luck: -20%
Lifesteal: 2%
Reflection: 6.5%
Crit: 1.875%
Stat: 19
Armor: 48
R.Piercing: 10
Resistance: 50
Grade: Rare
1,228,800 GOLD
SELL
Earring of Intelligence
Intelligence: 3
30,000 GOLD
SELL
Earring of Intelligence +1
Intelligence: 5
96,000 GOLD
SELL
Earring of Intelligence +2
Intelligence: 7
Grade: High
307,200 GOLD
SELL
Earring of Intelligence +3
Intelligence: 9
Grade: High
983,040 GOLD
SELL
Earring of Intelligence +4
Intelligence: 11
Grade: High
3,145,728 GOLD
SELL
Earring of Intelligence +5
Intelligence: 14
Grade: Rare
10,066,330 GOLD
SELL
Bow of the Dead
Crit: 1%
Damage: 26
Range: +50
Strength: 20
Vitality: -2
Run Speed: -12
Grade: High
A weapon of death
28,800 GOLD
SELL
Bow of the Dead +1
Crit: 1.2%
Damage: 31
Range: +57
Strength: 20
Vitality: -2
Run Speed: -12
Grade: High
A weapon of death
28,800 GOLD
SELL
Bow of the Dead +2
Crit: 1.4%
Damage: 36
Range: +64
Strength: 20
Vitality: -2
Run Speed: -12
Grade: High
A weapon of death
28,800 GOLD
SELL
Bow of the Dead +3
Crit: 1.6%
Damage: 40
Range: +71
Strength: 20
Vitality: -2
Run Speed: -12
Grade: High
A weapon of death
28,800 GOLD
SELL
Bow of the Dead +4
Crit: 1.8%
Damage: 45
Range: +78
Strength: 20
Vitality: -2
Run Speed: -12
Grade: High
A weapon of death
28,800 GOLD
SELL
Bow of the Dead +5
Crit: 2%
Damage: 50
Range: +85
Strength: 20
Vitality: -2
Run Speed: -12
Grade: High
A weapon of death
57,600 GOLD
SELL
Bow of the Dead +6
Crit: 2.2%
Damage: 55
Range: +92
Strength: 20
Vitality: -2
Run Speed: -12
Grade: Rare
A weapon of death
115,200 GOLD
SELL
Bow of the Dead +7
Crit: 2.45%
Damage: 60
Range: +101
Strength: 20
Vitality: -2
Run Speed: -12
Grade: Rare
A weapon of death
230,400 GOLD
SELL
Bow of the Dead +8
Crit: 2.75%
Damage: 68
Range: +111
Strength: 20
Vitality: -2
Run Speed: -12
Grade: Rare
A weapon of death
460,800 GOLD
SELL
Bow of the Dead +9
Crit: 3.15%
Damage: 77
Range: +125
Strength: 20
Vitality: -2
Run Speed: -12
Grade: Rare
A weapon of death
921,600 GOLD
SELL
Bow of the Dead +10
Crit: 3.75%
Damage: 91
Range: +146
Strength: 20
Vitality: -2
Run Speed: -12
Grade: Rare
A weapon of death
1,843,200 GOLD
SELL
Leather
A Leather piece.
Stone of Riches
Helps you find up to 40% more gold from monsters.
Amulet of Strength
Strength: 4
18,000 GOLD
SELL
Amulet of Strength +1
Strength: 6
57,600 GOLD
SELL
Amulet of Strength +2
Strength: 8
184,320 GOLD
SELL
Amulet of Strength +3
Strength: 10
Grade: High
589,824 GOLD
SELL
Amulet of Strength +4
Strength: 12
Grade: High
1,887,437 GOLD
SELL
Amulet of Strength +5
Strength: 15
Grade: Rare
6,039,798 GOLD
SELL
Essence of Fire
So fierce, so mesmerizing
Xmas Ornament
A beautiful ornament. A bunch of these could decorate the trees of Winterland.
Piece of Cake
HP: 1200
Speed: -30
Hours: 6
Delicious.
Upgrade Scroll
Scroll to upgrade a rare weapon or armor.
Legendary Upgrade Scroll
A mysterious upgrade scroll, you can feel that it's very powerful.
Ring of Small Joys
Strength: 1
Intelligence: 1
Dexterity: 1
Resistance: 5
14,400 GOLD
SELL
Ring of Small Joys +1
Strength: 2
Intelligence: 2
Dexterity: 2
Resistance: 10
46,080 GOLD
SELL
Ring of Small Joys +2
Strength: 3
Intelligence: 3
Dexterity: 3
Resistance: 15
147,456 GOLD
SELL
Ring of Small Joys +3
Strength: 4
Intelligence: 4
Dexterity: 4
Resistance: 20
Grade: High
471,859 GOLD
SELL
Ring of Small Joys +4
Strength: 5
Intelligence: 5
Dexterity: 5
Resistance: 25
Grade: High
1,509,949 GOLD
SELL
Ring of Small Joys +5
Strength: 6
Intelligence: 6
Dexterity: 6
Resistance: 31
Grade: Rare
4,831,838 GOLD
SELL
Upgrade Scroll
Scroll to upgrade a high grade weapon or armor.
Easter Egg
A uniquely painted Egg!
Easter Egg
A uniquely painted Egg!
Easter Egg
A uniquely painted Egg!
Cape
Stat: 4
Armor: 10
Resistance: 8
Grade: High
12,000 GOLD
SELL
Cape +1
Stat: 4
Armor: 12
Resistance: 9
Grade: High
12,000 GOLD
SELL
Cape +2
Stat: 4
Armor: 14
Resistance: 10
Grade: High
12,000 GOLD
SELL
Cape +3
Stat: 4
Armor: 16
Resistance: 11
Grade: High
12,000 GOLD
SELL
Cape +4
Stat: 4
Armor: 18
Resistance: 12
Grade: High
12,000 GOLD
SELL
Cape +5
Stat: 4
Armor: 20
Resistance: 13
Grade: High
24,000 GOLD
SELL
Cape +6
Stat: 4
Armor: 22
Resistance: 14
Grade: High
48,000 GOLD
SELL
Cape +7
Stat: 4
Armor: 25
Resistance: 15
Grade: High
96,000 GOLD
SELL
Cape +8
Stat: 4
Armor: 28
Resistance: 17
Grade: Rare
192,000 GOLD
SELL
Cape +9
Stat: 4
Armor: 32
Resistance: 19
Grade: Rare
384,000 GOLD
SELL
Cape +10
Stat: 4
Armor: 38
Resistance: 22
Grade: Rare
768,000 GOLD
SELL
Easter Egg
A uniquely painted Egg!
Easter Egg
A uniquely painted Egg!
Easter Egg
A uniquely painted Egg!
Easter Egg
A uniquely painted Egg!
Basket of Easter Eggs
A basket full of unique easter eggs. You can probably exchange this for a cool reward.
Easter Egg
A uniquely painted Egg!
Croc Scale
A very hard scale, can be sewn onto armors.
Harbringer
Damage: 40
Range: +50
R.Piercing: 10
Grade: High
Pure, unfiltered power!
173,400 GOLD
SELL
Harbringer +1
Damage: 46
Range: +53
R.Piercing: 15
Grade: High
Pure, unfiltered power!
173,400 GOLD
SELL
Harbringer +2
Damage: 52
Range: +56
R.Piercing: 20
Grade: High
Pure, unfiltered power!
173,400 GOLD
SELL
Harbringer +3
Damage: 58
Range: +59
R.Piercing: 25
Grade: High
Pure, unfiltered power!
173,400 GOLD
SELL
Harbringer +4
Damage: 64
Range: +62
R.Piercing: 30
Grade: High
Pure, unfiltered power!
173,400 GOLD
SELL
Harbringer +5
Damage: 70
Range: +65
R.Piercing: 35
Grade: High
Pure, unfiltered power!
346,800 GOLD
SELL
Harbringer +6
Damage: 76
Range: +68
R.Piercing: 40
Grade: Rare
Pure, unfiltered power!
693,600 GOLD
SELL
Harbringer +7
Damage: 84
Range: +72
R.Piercing: 46
Grade: Rare
Pure, unfiltered power!
1,387,200 GOLD
SELL
Harbringer +8
Damage: 93
Range: +76
R.Piercing: 54
Grade: Rare
Pure, unfiltered power!
2,774,400 GOLD
SELL
Harbringer +9
Damage: 105
Range: +82
R.Piercing: 64
Grade: Rare
Pure, unfiltered power!
5,548,800 GOLD
SELL
Harbringer +10
Damage: 123
Range: +91
R.Piercing: 79
Grade: Rare
Pure, unfiltered power!
11,097,600 GOLD
SELL
Priest's Mace
Damage: 25
Range: +10
Intelligence: 8
Dexterity: 4
Grade: High
53,400 GOLD
SELL
Priest's Mace +1
Damage: 31
Range: +15
Intelligence: 10
Dexterity: 5
Grade: High
53,400 GOLD
SELL
Priest's Mace +2
Damage: 37
Range: +20
Intelligence: 12
Dexterity: 6
Grade: High
53,400 GOLD
SELL
Priest's Mace +3
Damage: 43
Range: +25
Intelligence: 14
Dexterity: 7
Grade: High
53,400 GOLD
SELL
Priest's Mace +4
Damage: 49
Range: +30
Intelligence: 16
Dexterity: 8
Grade: High
53,400 GOLD
SELL
Priest's Mace +5
Damage: 55
Range: +35
Intelligence: 18
Dexterity: 9
Grade: High
106,800 GOLD
SELL
Priest's Mace +6
Damage: 61
Range: +40
Intelligence: 20
Dexterity: 10
Grade: High
213,600 GOLD
SELL
Priest's Mace +7
Damage: 69
Range: +46
Intelligence: 23
Dexterity: 11
Grade: High
427,200 GOLD
SELL
Priest's Mace +8
Damage: 78
Range: +54
Intelligence: 26
Dexterity: 13
Grade: Rare
854,400 GOLD
SELL
Priest's Mace +9
Damage: 90
Range: +64
Intelligence: 30
Dexterity: 15
Grade: Rare
1,708,800 GOLD
SELL
Priest's Mace +10
Damage: 108
Range: +79
Intelligence: 36
Dexterity: 18
Grade: Rare
3,417,600 GOLD
SELL
Sturdy Helmet
Stat: 1
Armor: 14
Resistance: 16
Grade: High
19,200 GOLD
SELL
Sturdy Helmet +1
Stat: 2
Armor: 17
Resistance: 19
Grade: High
19,200 GOLD
SELL
Sturdy Helmet +2
Stat: 3
Armor: 19
Resistance: 21
Grade: High
19,200 GOLD
SELL
Sturdy Helmet +3
Stat: 4
Armor: 22
Resistance: 24
Grade: High
19,200 GOLD
SELL
Sturdy Helmet +4
Stat: 5
Armor: 24
Resistance: 26
Grade: High
19,200 GOLD
SELL
Sturdy Helmet +5
Stat: 6
Armor: 27
Resistance: 29
Grade: High
38,400 GOLD
SELL
Sturdy Helmet +6
Stat: 7
Armor: 29
Resistance: 31
Grade: High
76,800 GOLD
SELL
Sturdy Helmet +7
Stat: 9
Armor: 32
Resistance: 34
Grade: Rare
153,600 GOLD
SELL
Sturdy Helmet +8
Stat: 12
Armor: 36
Resistance: 38
Grade: Rare
307,200 GOLD
SELL
Sturdy Helmet +9
Stat: 15
Armor: 41
Resistance: 43
Grade: Rare
614,400 GOLD
SELL
Sturdy Helmet +10
Stat: 19
Armor: 48
Resistance: 50
Grade: Rare
1,228,800 GOLD
SELL
Tome of Protection
Significantly reduces experience loss on death. If the owner is defeated by another player, the victor receives a portion of the Tome's cost.
Vitality Scroll
Adds Vitality to an armor with a Stat attribute.
Dracul's Attire
Lifesteal: 1%
HP: 80
Stat: 1
Armor: 24
Resistance: 16
Grade: High
288,000 GOLD
SELL
Dracul's Attire +1
Lifesteal: 1.2%
HP: 95
Stat: 2
Armor: 27
Resistance: 19
Grade: High
288,000 GOLD
SELL
Dracul's Attire +2
Lifesteal: 1.4%
HP: 110
Stat: 3
Armor: 29
Resistance: 21
Grade: High
288,000 GOLD
SELL
Dracul's Attire +3
Lifesteal: 1.6%
HP: 125
Stat: 4
Armor: 32
Resistance: 24
Grade: High
288,000 GOLD
SELL
Dracul's Attire +4
Lifesteal: 1.8%
HP: 140
Stat: 5
Armor: 34
Resistance: 26
Grade: High
288,000 GOLD
SELL
Dracul's Attire +5
Lifesteal: 2%
HP: 155
Stat: 6
Armor: 37
Resistance: 29
Grade: High
576,000 GOLD
SELL
Dracul's Attire +6
Lifesteal: 2.2%
HP: 170
Stat: 7
Armor: 39
Resistance: 31
Grade: Rare
1,152,000 GOLD
SELL
Dracul's Attire +7
Lifesteal: 2.45%
HP: 189
Stat: 9
Armor: 42
Resistance: 34
Grade: Rare
2,304,000 GOLD
SELL
Dracul's Attire +8
Lifesteal: 2.75%
HP: 211
Stat: 12
Armor: 46
Resistance: 38
Grade: Rare
4,608,000 GOLD
SELL
Dracul's Attire +9
Lifesteal: 3.15%
HP: 241
Stat: 15
Armor: 51
Resistance: 43
Grade: Rare
9,216,000 GOLD
SELL
Dracul's Attire +10
Lifesteal: 3.75%
HP: 286
Stat: 19
Armor: 58
Resistance: 50
Grade: Rare
18,432,000 GOLD
SELL
Heavy Underarmor
Stat: 1
Armor: 30
Resistance: 18
Grade: Rare
468,000 GOLD
SELL
Heavy Underarmor +1
Stat: 2
Armor: 34
Resistance: 22
Grade: Rare
468,000 GOLD
SELL
Heavy Underarmor +2
Stat: 3
Armor: 39
Resistance: 27
Grade: Rare
468,000 GOLD
SELL
Heavy Underarmor +3
Stat: 4
Armor: 43
Resistance: 31
Grade: Rare
468,000 GOLD
SELL
Heavy Underarmor +4
Stat: 5
Armor: 47
Resistance: 35
Grade: Rare
468,000 GOLD
SELL
Heavy Underarmor +5
Stat: 6
Armor: 51
Resistance: 39
Grade: Rare
936,000 GOLD
SELL
Heavy Underarmor +6
Stat: 7
Armor: 56
Resistance: 44
Grade: Rare
1,872,000 GOLD
SELL
Heavy Underarmor +7
Stat: 9
Armor: 61
Resistance: 49
Grade: Rare
3,744,000 GOLD
SELL
Heavy Underarmor +8
Stat: 12
Armor: 67
Resistance: 55
Grade: Rare
7,488,000 GOLD
SELL
Heavy Underarmor +9
Stat: 15
Armor: 76
Resistance: 64
Grade: Rare
14,976,000 GOLD
SELL
Heavy Underarmor +10
Stat: 19
Armor: 88
Resistance: 76
Grade: Rare
29,952,000 GOLD
SELL
Poker
Crit: 0.5%
Stat: 1
Armor: 12
Resistance: 6
Pokey pokey!
4,800 GOLD
SELL
Poker +1
Crit: 0.5%
Stat: 2
Armor: 14
Resistance: 8
Pokey pokey!
4,800 GOLD
SELL
Poker +2
Crit: 0.5%
Stat: 3
Armor: 16
Resistance: 10
Pokey pokey!
4,800 GOLD
SELL
Poker +3
Crit: 0.5%
Stat: 4
Armor: 18
Resistance: 12
Pokey pokey!
4,800 GOLD
SELL
Poker +4
Crit: 0.5%
Stat: 5
Armor: 20
Resistance: 14
Grade: High
Pokey pokey!
4,800 GOLD
SELL
Poker +5
Crit: 0.5%
Stat: 6
Armor: 21
Resistance: 15
Grade: High
Pokey pokey!
9,600 GOLD
SELL
Poker +6
Crit: 0.5%
Stat: 7
Armor: 23
Resistance: 17
Grade: High
Pokey pokey!
19,200 GOLD
SELL
Poker +7
Crit: 0.5%
Stat: 9
Armor: 26
Resistance: 20
Grade: High
Pokey pokey!
38,400 GOLD
SELL
Poker +8
Crit: 0.5%
Stat: 12
Armor: 28
Resistance: 22
Grade: Rare
Pokey pokey!
76,800 GOLD
SELL
Poker +9
Crit: 0.5%
Stat: 15
Armor: 32
Resistance: 26
Grade: Rare
Pokey pokey!
153,600 GOLD
SELL
Poker +10
Crit: 0.5%
Stat: 19
Armor: 38
Resistance: 32
Grade: Rare
Pokey pokey!
307,200 GOLD
SELL
Coal
...
6 GOLD
SELL
Coal +1
...
19 GOLD
SELL
Coal +2
...
61 GOLD
SELL
Coal +3
...
197 GOLD
SELL
Coal +4
...
629 GOLD
SELL
Coal +5
...
2,013 GOLD
SELL
Belt of Dexterity
Dexterity: 4
30,000 GOLD
SELL
Belt of Dexterity +1
Dexterity: 7
96,000 GOLD
SELL
Belt of Dexterity +2
Dexterity: 10
Grade: High
307,200 GOLD
SELL
Belt of Dexterity +3
Dexterity: 13
Grade: High
983,040 GOLD
SELL
Belt of Dexterity +4
Dexterity: 16
Grade: High
3,145,728 GOLD
SELL
Belt of Dexterity +5
Dexterity: 20
Grade: Rare
10,066,330 GOLD
SELL
Elixir of Extreme Vitality
Vitality: 18
Hours: 48
Primordial Essence
The essence contained within can be transferred to items during upgrades and compounds. Significantly increases the chance to succeed.
Elixir of Vitality
Vitality: 8
Hours: 12
Coat
Stat: 1
Armor: 12
Resistance: 8
3,600 GOLD
SELL
Coat +1
Stat: 2
Armor: 13
Resistance: 9
3,600 GOLD
SELL
Coat +2
Stat: 3
Armor: 15
Resistance: 11
3,600 GOLD
SELL
Coat +3
Stat: 4
Armor: 16
Resistance: 12
3,600 GOLD
SELL
Coat +4
Stat: 5
Armor: 17
Resistance: 13
3,600 GOLD
SELL
Coat +5
Stat: 6
Armor: 18
Resistance: 14
7,200 GOLD
SELL
Coat +6
Stat: 7
Armor: 20
Resistance: 16
14,400 GOLD
SELL
Coat +7
Stat: 9
Armor: 21
Resistance: 17
Grade: High
28,800 GOLD
SELL
Coat +8
Stat: 12
Armor: 23
Resistance: 19
Grade: High
57,600 GOLD
SELL
Coat +9
Stat: 15
Armor: 25
Resistance: 21
Grade: Rare
115,200 GOLD
SELL
Coat +10
Stat: 19
Armor: 29
Resistance: 25
Grade: Rare
230,400 GOLD
SELL
Easter Egg
A uniquely painted Egg!
Candy
A delicious candy. Xyn in New Town could give you something in exchange!
Pyjamas
HP: 200
Stat: 1
Armor: 24
Resistance: 16
Charisma: -5
Comfortable.
288,000 GOLD
SELL
Pyjamas +1
HP: 225
Stat: 2
Armor: 27
Resistance: 19
Charisma: -5
Comfortable.
288,000 GOLD
SELL
Pyjamas +2
HP: 250
Stat: 3
Armor: 29
Resistance: 21
Charisma: -5
Comfortable.
288,000 GOLD
SELL
Pyjamas +3
HP: 275
Stat: 4
Armor: 32
Resistance: 24
Charisma: -5
Comfortable.
288,000 GOLD
SELL
Pyjamas +4
HP: 300
Stat: 5
Armor: 34
Resistance: 26
Charisma: -5
Grade: High
Comfortable.
288,000 GOLD
SELL
Pyjamas +5
HP: 325
Stat: 6
Armor: 37
Resistance: 29
Charisma: -5
Grade: High
Comfortable.
576,000 GOLD
SELL
Pyjamas +6
HP: 350
Stat: 7
Armor: 39
Resistance: 31
Charisma: -5
Grade: High
Comfortable.
1,152,000 GOLD
SELL
Pyjamas +7
HP: 381
Stat: 9
Armor: 42
Resistance: 34
Charisma: -5
Grade: High
Comfortable.
2,304,000 GOLD
SELL
Pyjamas +8
HP: 419
Stat: 12
Armor: 46
Resistance: 38
Charisma: -5
Grade: Rare
Comfortable.
4,608,000 GOLD
SELL
Pyjamas +9
HP: 469
Stat: 15
Armor: 51
Resistance: 43
Charisma: -5
Grade: Rare
Comfortable.
9,216,000 GOLD
SELL
Pyjamas +10
HP: 544
Stat: 19
Armor: 58
Resistance: 50
Charisma: -5
Grade: Rare
Comfortable.
18,432,000 GOLD
SELL
Upgrade Scroll
Scroll to upgrade a weapon or armor. If the upgrade fails, the item is lost.
Heavy Boots
Stat: 1
Armor: 12
Resistance: 6
Speed: +7
Grade: Rare
744,000 GOLD
SELL
Heavy Boots +1
Stat: 2
Armor: 16
Resistance: 8
Speed: +8
Grade: Rare
744,000 GOLD
SELL
Heavy Boots +2
Stat: 3
Armor: 21
Resistance: 10
Speed: +9
Grade: Rare
744,000 GOLD
SELL
Heavy Boots +3
Stat: 4
Armor: 25
Resistance: 12
Speed: +10
Grade: Rare
744,000 GOLD
SELL
Heavy Boots +4
Stat: 5
Armor: 29
Resistance: 15
Speed: +12
Grade: Rare
744,000 GOLD
SELL
Heavy Boots +5
Stat: 6
Armor: 33
Resistance: 17
Speed: +13
Grade: Rare
1,488,000 GOLD
SELL
Heavy Boots +6
Stat: 7
Armor: 38
Resistance: 19
Speed: +14
Grade: Rare
2,976,000 GOLD
SELL
Heavy Boots +7
Stat: 9
Armor: 43
Resistance: 21
Speed: +15
Grade: Rare
5,952,000 GOLD
SELL
Heavy Boots +8
Stat: 12
Armor: 49
Resistance: 25
Speed: +17
Grade: Rare
11,904,000 GOLD
SELL
Heavy Boots +9
Stat: 15
Armor: 58
Resistance: 29
Speed: +19
Grade: Rare
23,808,000 GOLD
SELL
Heavy Boots +10
Stat: 19
Armor: 70
Resistance: 35
Speed: +22
Grade: Rare
47,616,000 GOLD
SELL
Heavy Helmet
Stat: 1
Armor: 21
Resistance: 24
Grade: Rare
192,000 GOLD
SELL
Heavy Helmet +1
Stat: 2
Armor: 25
Resistance: 28
Grade: Rare
192,000 GOLD
SELL
Heavy Helmet +2
Stat: 3
Armor: 30
Resistance: 33
Grade: Rare
192,000 GOLD
SELL
Heavy Helmet +3
Stat: 4
Armor: 34
Resistance: 37
Grade: Rare
192,000 GOLD
SELL
Heavy Helmet +4
Stat: 5
Armor: 38
Resistance: 41
Grade: Rare
192,000 GOLD
SELL
Heavy Helmet +5
Stat: 6
Armor: 42
Resistance: 45
Grade: Rare
384,000 GOLD
SELL
Heavy Helmet +6
Stat: 7
Armor: 47
Resistance: 50
Grade: Rare
768,000 GOLD
SELL
Heavy Helmet +7
Stat: 9
Armor: 52
Resistance: 55
Grade: Rare
1,536,000 GOLD
SELL
Heavy Helmet +8
Stat: 12
Armor: 58
Resistance: 61
Grade: Rare
3,072,000 GOLD
SELL
Heavy Helmet +9
Stat: 15
Armor: 67
Resistance: 70
Grade: Rare
6,144,000 GOLD
SELL
Heavy Helmet +10
Stat: 19
Armor: 79
Resistance: 82
Grade: Rare
12,288,000 GOLD
SELL
Staff of the Dead
Damage: 40
Range: +50
Strength: 32
Run Speed: -6
Grade: High
74,400 GOLD
SELL
Staff of the Dead +1
Damage: 46
Range: +53
Strength: 32
Run Speed: -6
Grade: High
74,400 GOLD
SELL
Staff of the Dead +2
Damage: 52
Range: +55
Strength: 32
Run Speed: -6
Grade: High
74,400 GOLD
SELL
Staff of the Dead +3
Damage: 58
Range: +58
Strength: 32
Run Speed: -6
Grade: High
74,400 GOLD
SELL
Staff of the Dead +4
Damage: 64
Range: +60
Strength: 32
Run Speed: -6
Grade: High
74,400 GOLD
SELL
Staff of the Dead +5
Damage: 70
Range: +63
Strength: 32
Run Speed: -6
Grade: High
148,800 GOLD
SELL
Staff of the Dead +6
Damage: 76
Range: +65
Strength: 32
Run Speed: -6
Grade: Rare
297,600 GOLD
SELL
Staff of the Dead +7
Damage: 84
Range: +68
Strength: 32
Run Speed: -6
Grade: Rare
595,200 GOLD
SELL
Staff of the Dead +8
Damage: 93
Range: +72
Strength: 32
Run Speed: -6
Grade: Rare
1,190,400 GOLD
SELL
Staff of the Dead +9
Damage: 105
Range: +77
Strength: 32
Run Speed: -6
Grade: Rare
2,380,800 GOLD
SELL
Staff of the Dead +10
Damage: 123
Range: +84
Strength: 32
Run Speed: -6
Grade: Rare
4,761,600 GOLD
SELL
Egg
A vibrant egg, it's inhabitant seems eager to get out.
Gloves
Stat: 1
Armor: 8
Resistance: 4
2,040 GOLD
SELL
Gloves +1
Stat: 2
Armor: 9
Resistance: 5
2,040 GOLD
SELL
Gloves +2
Stat: 3
Armor: 11
Resistance: 7
2,040 GOLD
SELL
Gloves +3
Stat: 4
Armor: 12
Resistance: 8
2,040 GOLD
SELL
Gloves +4
Stat: 5
Armor: 13
Resistance: 9
2,040 GOLD
SELL
Gloves +5
Stat: 6
Armor: 14
Resistance: 10
4,080 GOLD
SELL
Gloves +6
Stat: 7
Armor: 16
Resistance: 12
8,160 GOLD
SELL
Gloves +7
Stat: 9
Armor: 17
Resistance: 13
Grade: High
16,320 GOLD
SELL
Gloves +8
Stat: 12
Armor: 19
Resistance: 15
Grade: High
32,640 GOLD
SELL
Gloves +9
Stat: 15
Armor: 21
Resistance: 17
Grade: Rare
65,280 GOLD
SELL
Gloves +10
Stat: 19
Armor: 25
Resistance: 21
Grade: Rare
130,560 GOLD
SELL
MP Potion
MP: +300
Earring of Strength
Strength: 3
30,000 GOLD
SELL
Earring of Strength +1
Strength: 5
96,000 GOLD
SELL
Earring of Strength +2
Strength: 7
Grade: High
307,200 GOLD
SELL
Earring of Strength +3
Strength: 9
Grade: High
983,040 GOLD
SELL
Earring of Strength +4
Strength: 11
Grade: High
3,145,728 GOLD
SELL
Earring of Strength +5
Strength: 14
Grade: Rare
10,066,330 GOLD
SELL
Seashell
A beautiful seashell.
Swirlipop
Evasion: 90%
Resistance: -300
Hours: 0.008
A dizzying candy, has some benefits.
Well-Crafted Bow
Damage: 26
Range: +60
Grade: High
Crafted with the finest of materials
28,800 GOLD
SELL
Well-Crafted Bow +1
Damage: 31
Range: +68
Grade: High
Crafted with the finest of materials
28,800 GOLD
SELL
Well-Crafted Bow +2
Damage: 36
Range: +76
Grade: High
Crafted with the finest of materials
28,800 GOLD
SELL
Well-Crafted Bow +3
Damage: 40
Range: +84
Grade: High
Crafted with the finest of materials
28,800 GOLD
SELL
Well-Crafted Bow +4
Damage: 45
Range: +92
Grade: High
Crafted with the finest of materials
28,800 GOLD
SELL
Well-Crafted Bow +5
Damage: 50
Range: +100
Grade: High
Crafted with the finest of materials
57,600 GOLD
SELL
Well-Crafted Bow +6
Damage: 55
Range: +108
Grade: High
Crafted with the finest of materials
115,200 GOLD
SELL
Well-Crafted Bow +7
Damage: 60
Range: +118
Grade: Rare
Crafted with the finest of materials
230,400 GOLD
SELL
Well-Crafted Bow +8
Damage: 68
Range: +130
Grade: Rare
Crafted with the finest of materials
460,800 GOLD
SELL
Well-Crafted Bow +9
Damage: 77
Range: +146
Grade: Rare
Crafted with the finest of materials
921,600 GOLD
SELL
Well-Crafted Bow +10
Damage: 91
Range: +170
Grade: Rare
Crafted with the finest of materials
1,843,200 GOLD
SELL
Frost Staff
Damage: 30
Range: +50
Intelligence: 2
Grade: High
Ability: Freeze
Freezes the opponent with a 10.2% chance.
293,400 GOLD
SELL
Frost Staff +1
Damage: 36
Range: +53
Intelligence: 3
Grade: High
Ability: Freeze
Freezes the opponent with a 10.299999999999999% chance.
293,400 GOLD
SELL
Frost Staff +2
Damage: 41
Range: +56
Intelligence: 4
Grade: High
Ability: Freeze
Freezes the opponent with a 10.399999999999999% chance.
293,400 GOLD
SELL
Frost Staff +3
Damage: 47
Range: +59
Intelligence: 5
Grade: High
Ability: Freeze
Freezes the opponent with a 10.5% chance.
293,400 GOLD
SELL
Frost Staff +4
Damage: 52
Range: +62
Intelligence: 6
Grade: High
Ability: Freeze
Freezes the opponent with a 10.6% chance.
293,400 GOLD
SELL
Frost Staff +5
Damage: 58
Range: +65
Intelligence: 7
Grade: High
Ability: Freeze
Freezes the opponent with a 10.7% chance.
586,800 GOLD
SELL
Frost Staff +6
Damage: 63
Range: +68
Intelligence: 8
Grade: High
Ability: Freeze
Freezes the opponent with a 10.799999999999999% chance.
1,173,600 GOLD
SELL
Frost Staff +7
Damage: 70
Range: +72
Intelligence: 9
Grade: High
Ability: Freeze
Freezes the opponent with a 10.924999999999999% chance.
2,347,200 GOLD
SELL
Frost Staff +8
Damage: 78
Range: +76
Intelligence: 11
Grade: Rare
Ability: Freeze
Freezes the opponent with a 11.075% chance.
4,694,400 GOLD
SELL
Frost Staff +9
Damage: 89
Range: +82
Intelligence: 13
Grade: Rare
Ability: Freeze
Freezes the opponent with a 11.274999999999999% chance.
9,388,800 GOLD
SELL
Frost Staff +10
Damage: 106
Range: +91
Intelligence: 16
Grade: Rare
Ability: Freeze
Freezes the opponent with a 11.575% chance.
18,777,600 GOLD
SELL
Fiery Staff
Damage: 30
Range: +50
Grade: High
173,400 GOLD
SELL
Fiery Staff +1
Damage: 36
Range: +53
Grade: High
173,400 GOLD
SELL
Fiery Staff +2
Damage: 41
Range: +56
Grade: High
173,400 GOLD
SELL
Fiery Staff +3
Damage: 47
Range: +59
Grade: High
173,400 GOLD
SELL
Fiery Staff +4
Damage: 52
Range: +62
Grade: High
173,400 GOLD
SELL
Fiery Staff +5
Damage: 58
Range: +65
Grade: High
346,800 GOLD
SELL
Fiery Staff +6
Damage: 63
Range: +68
Grade: High
693,600 GOLD
SELL
Fiery Staff +7
Damage: 70
Range: +72
Grade: High
1,387,200 GOLD
SELL
Fiery Staff +8
Damage: 78
Range: +76
Grade: Rare
2,774,400 GOLD
SELL
Fiery Staff +9
Damage: 89
Range: +82
Grade: Rare
5,548,800 GOLD
SELL
Fiery Staff +10
Damage: 106
Range: +91
Grade: Rare
11,097,600 GOLD
SELL
Jewellery Box
Can be exchanged for a random acessory.
Test
An item to test item looks, just set the 'skin' property.
Super Mittens
Stat: 1
Armor: 16
A.Piercing: 32
R.Piercing: 32
Resistance: 8
Grade: Rare
Swift and lethal!
20,400 GOLD
SELL
Super Mittens +1
Stat: 2
Armor: 19
A.Piercing: 35
R.Piercing: 35
Resistance: 11
Grade: Rare
Swift and lethal!
20,400 GOLD
SELL
Super Mittens +2
Stat: 3
Armor: 21
A.Piercing: 38
R.Piercing: 38
Resistance: 13
Grade: Rare
Swift and lethal!
20,400 GOLD
SELL
Super Mittens +3
Stat: 4
Armor: 24
A.Piercing: 41
R.Piercing: 41
Resistance: 16
Grade: Rare
Swift and lethal!
20,400 GOLD
SELL
Super Mittens +4
Stat: 5
Armor: 26
A.Piercing: 44
R.Piercing: 44
Resistance: 18
Grade: Rare
Swift and lethal!
20,400 GOLD
SELL
Super Mittens +5
Stat: 6
Armor: 29
A.Piercing: 47
R.Piercing: 47
Resistance: 21
Grade: Rare
Swift and lethal!
40,800 GOLD
SELL
Super Mittens +6
Stat: 7
Armor: 31
A.Piercing: 50
R.Piercing: 50
Resistance: 23
Grade: Rare
Swift and lethal!
81,600 GOLD
SELL
Super Mittens +7
Stat: 9
Armor: 34
A.Piercing: 54
R.Piercing: 54
Resistance: 26
Grade: Rare
Swift and lethal!
163,200 GOLD
SELL
Super Mittens +8
Stat: 12
Armor: 38
A.Piercing: 58
R.Piercing: 58
Resistance: 30
Grade: Rare
Swift and lethal!
326,400 GOLD
SELL
Super Mittens +9
Stat: 15
Armor: 43
A.Piercing: 64
R.Piercing: 64
Resistance: 35
Grade: Rare
Swift and lethal!
652,800 GOLD
SELL
Super Mittens +10
Stat: 19
Armor: 50
A.Piercing: 73
R.Piercing: 73
Resistance: 42
Grade: Rare
Swift and lethal!
1,305,600 GOLD
SELL
Bunny Ears
Evasion: 1%
Vitality: 4
Stat: 1
Armor: 14
Resistance: 16
Cuteness: 12
19,200 GOLD
SELL
Bunny Ears +1
Evasion: 1.2%
Vitality: 4
Stat: 2
Armor: 17
Resistance: 19
Cuteness: 12
19,200 GOLD
SELL
Bunny Ears +2
Evasion: 1.4%
Vitality: 4
Stat: 3
Armor: 19
Resistance: 21
Cuteness: 12
19,200 GOLD
SELL
Bunny Ears +3
Evasion: 1.6%
Vitality: 4
Stat: 4
Armor: 22
Resistance: 24
Cuteness: 12
19,200 GOLD
SELL
Bunny Ears +4
Evasion: 1.8%
Vitality: 4
Stat: 5
Armor: 24
Resistance: 26
Cuteness: 12
Grade: High
19,200 GOLD
SELL
Bunny Ears +5
Evasion: 2%
Vitality: 4
Stat: 6
Armor: 27
Resistance: 29
Cuteness: 12
Grade: High
38,400 GOLD
SELL
Bunny Ears +6
Evasion: 2.2%
Vitality: 4
Stat: 7
Armor: 29
Resistance: 31
Cuteness: 12
Grade: High
76,800 GOLD
SELL
Bunny Ears +7
Evasion: 2.45%
Vitality: 4
Stat: 9
Armor: 32
Resistance: 34
Cuteness: 12
Grade: High
153,600 GOLD
SELL
Bunny Ears +8
Evasion: 2.75%
Vitality: 4
Stat: 12
Armor: 36
Resistance: 38
Cuteness: 12
Grade: Rare
307,200 GOLD
SELL
Bunny Ears +9
Evasion: 3.15%
Vitality: 4
Stat: 15
Armor: 41
Resistance: 43
Cuteness: 12
Grade: Rare
614,400 GOLD
SELL
Bunny Ears +10
Evasion: 3.75%
Vitality: 4
Stat: 19
Armor: 48
Resistance: 50
Cuteness: 12
Grade: Rare
1,228,800 GOLD
SELL
Amulet of the Fierce Mage
Intelligence: 5
Armor: 30
Grade: High
36,000 GOLD
SELL
Amulet of the Fierce Mage +1
Intelligence: 7
Armor: 50
Grade: High
115,200 GOLD
SELL
Amulet of the Fierce Mage +2
Intelligence: 9
Armor: 70
Grade: High
368,640 GOLD
SELL
Amulet of the Fierce Mage +3
Intelligence: 11
Armor: 90
Grade: Rare
1,179,648 GOLD
SELL
Amulet of the Fierce Mage +4
Intelligence: 13
Armor: 110
Grade: Rare
3,774,874 GOLD
SELL
Amulet of the Fierce Mage +5
Intelligence: 16
Armor: 135
Grade: Rare
12,079,596 GOLD
SELL
Heavy Armor
Stat: 1
Armor: 36
Resistance: 24
Grade: Rare
288,000 GOLD
SELL
Heavy Armor +1
Stat: 2
Armor: 40
Resistance: 28
Grade: Rare
288,000 GOLD
SELL
Heavy Armor +2
Stat: 3
Armor: 45
Resistance: 33
Grade: Rare
288,000 GOLD
SELL
Heavy Armor +3
Stat: 4
Armor: 49
Resistance: 37
Grade: Rare
288,000 GOLD
SELL
Heavy Armor +4
Stat: 5
Armor: 53
Resistance: 41
Grade: Rare
288,000 GOLD
SELL
Heavy Armor +5
Stat: 6
Armor: 57
Resistance: 45
Grade: Rare
576,000 GOLD
SELL
Heavy Armor +6
Stat: 7
Armor: 62
Resistance: 50
Grade: Rare
1,152,000 GOLD
SELL
Heavy Armor +7
Stat: 9
Armor: 67
Resistance: 55
Grade: Rare
2,304,000 GOLD
SELL
Heavy Armor +8
Stat: 12
Armor: 73
Resistance: 61
Grade: Rare
4,608,000 GOLD
SELL
Heavy Armor +9
Stat: 15
Armor: 82
Resistance: 70
Grade: Rare
9,216,000 GOLD
SELL
Heavy Armor +10
Stat: 19
Armor: 94
Resistance: 82
Grade: Rare
18,432,000 GOLD
SELL
Hand of Midas
Gold: +10%
Armor: 28
Resistance: 14
Speed: -20
Grade: Rare
You can feel the thirst for gold move through your veins.
480,000 GOLD
SELL
Hand of Midas +1
Gold: +11%
Armor: 33
Resistance: 19
Speed: -20
Grade: Rare
You can feel the thirst for gold move through your veins.
480,000 GOLD
SELL
Hand of Midas +2
Gold: +12%
Armor: 38
Resistance: 24
Speed: -20
Grade: Rare
You can feel the thirst for gold move through your veins.
480,000 GOLD
SELL
Hand of Midas +3
Gold: +13%
Armor: 43
Resistance: 29
Speed: -20
Grade: Rare
You can feel the thirst for gold move through your veins.
480,000 GOLD
SELL
Hand of Midas +4
Gold: +14%
Armor: 48
Resistance: 34
Speed: -20
Grade: Rare
You can feel the thirst for gold move through your veins.
480,000 GOLD
SELL
Hand of Midas +5
Gold: +15%
Armor: 52
Resistance: 38
Speed: -20
Grade: Rare
You can feel the thirst for gold move through your veins.
960,000 GOLD
SELL
Hand of Midas +6
Gold: +16%
Armor: 57
Resistance: 43
Speed: -20
Grade: Rare
You can feel the thirst for gold move through your veins.
1,920,000 GOLD
SELL
Hand of Midas +7
Gold: +17%
Armor: 63
Resistance: 49
Speed: -20
Grade: Rare
You can feel the thirst for gold move through your veins.
3,840,000 GOLD
SELL
Hand of Midas +8
Gold: +19%
Armor: 71
Resistance: 57
Speed: -20
Grade: Rare
You can feel the thirst for gold move through your veins.
7,680,000 GOLD
SELL
Hand of Midas +9
Gold: +21%
Armor: 80
Resistance: 66
Speed: -20
Grade: Rare
You can feel the thirst for gold move through your veins.
15,360,000 GOLD
SELL
Hand of Midas +10
Gold: +24%
Armor: 95
Resistance: 81
Speed: -20
Grade: Rare
You can feel the thirst for gold move through your veins.
30,720,000 GOLD
SELL
Stealth Cape
Stat: 3
Resistance: 42
Grade: High
Thanks to it's stealth capabilities, no one can track your endeavours any more.
120,000 GOLD
SELL
Stealth Cape +1
Stat: 3
Resistance: 43
Grade: High
Thanks to it's stealth capabilities, no one can track your endeavours any more.
120,000 GOLD
SELL
Stealth Cape +2
Stat: 3
Resistance: 44
Grade: High
Thanks to it's stealth capabilities, no one can track your endeavours any more.
120,000 GOLD
SELL
Stealth Cape +3
Stat: 3
Resistance: 45
Grade: High
Thanks to it's stealth capabilities, no one can track your endeavours any more.
120,000 GOLD
SELL
Stealth Cape +4
Stat: 3
Resistance: 46
Grade: Rare
Thanks to it's stealth capabilities, no one can track your endeavours any more.
120,000 GOLD
SELL
Stealth Cape +5
Stat: 3
Resistance: 47
Grade: Rare
Thanks to it's stealth capabilities, no one can track your endeavours any more.
240,000 GOLD
SELL
Stealth Cape +6
Stat: 3
Resistance: 48
Grade: Rare
Thanks to it's stealth capabilities, no one can track your endeavours any more.
480,000 GOLD
SELL
Stealth Cape +7
Stat: 3
Resistance: 49
Grade: Rare
Thanks to it's stealth capabilities, no one can track your endeavours any more.
960,000 GOLD
SELL
Stealth Cape +8
Stat: 3
Resistance: 51
Grade: Rare
Thanks to it's stealth capabilities, no one can track your endeavours any more.
1,920,000 GOLD
SELL
Stealth Cape +9
Stat: 3
Resistance: 53
Grade: Rare
Thanks to it's stealth capabilities, no one can track your endeavours any more.
3,840,000 GOLD
SELL
Stealth Cape +10
Stat: 3
Resistance: 56
Grade: Rare
Thanks to it's stealth capabilities, no one can track your endeavours any more.
7,680,000 GOLD
SELL
Shoes
Stat: 1
Armor: 4
Speed: +5
7,260 GOLD
SELL
Shoes +1
Stat: 2
Armor: 5
Speed: +6
7,260 GOLD
SELL
Shoes +2
Stat: 3
Armor: 7
Speed: +6
7,260 GOLD
SELL
Shoes +3
Stat: 4
Armor: 8
Speed: +7
7,260 GOLD
SELL
Shoes +4
Stat: 5
Armor: 9
Speed: +8
7,260 GOLD
SELL
Shoes +5
Stat: 6
Armor: 10
Speed: +8
14,520 GOLD
SELL
Shoes +6
Stat: 7
Armor: 12
Speed: +9
29,040 GOLD
SELL
Shoes +7
Stat: 9
Armor: 13
Speed: +10
Grade: High
58,080 GOLD
SELL
Shoes +8
Stat: 12
Armor: 15
Speed: +10
Grade: High
116,160 GOLD
SELL
Shoes +9
Stat: 15
Armor: 17
Speed: +12
Grade: Rare
232,320 GOLD
SELL
Shoes +10
Stat: 19
Armor: 21
Speed: +14
Grade: Rare
464,640 GOLD
SELL
Frozen Claw
Damage: 14
Range: +5
Intelligence: 8
Grade: High
Ability: Freeze
Freezes the opponent with a 0.2% chance.
43,200 GOLD
SELL
Frozen Claw +1
Damage: 18
Range: +7
Intelligence: 8
Grade: High
Ability: Freeze
Freezes the opponent with a 0.30000000000000004% chance.
43,200 GOLD
SELL
Frozen Claw +2
Damage: 22
Range: +8
Intelligence: 8
Grade: High
Ability: Freeze
Freezes the opponent with a 0.4% chance.
43,200 GOLD
SELL
Frozen Claw +3
Damage: 26
Range: +10
Intelligence: 8
Grade: High
Ability: Freeze
Freezes the opponent with a 0.5% chance.
43,200 GOLD
SELL
Frozen Claw +4
Damage: 30
Range: +11
Intelligence: 8
Grade: High
Ability: Freeze
Freezes the opponent with a 0.6000000000000001% chance.
43,200 GOLD
SELL
Frozen Claw +5
Damage: 34
Range: +13
Intelligence: 8
Grade: High
Ability: Freeze
Freezes the opponent with a 0.7% chance.
86,400 GOLD
SELL
Frozen Claw +6
Damage: 38
Range: +14
Intelligence: 8
Grade: High
Ability: Freeze
Freezes the opponent with a 0.8% chance.
172,800 GOLD
SELL
Frozen Claw +7
Damage: 43
Range: +16
Intelligence: 8
Grade: Rare
Ability: Freeze
Freezes the opponent with a 0.925% chance.
345,600 GOLD
SELL
Frozen Claw +8
Damage: 49
Range: +18
Intelligence: 8
Grade: Rare
Ability: Freeze
Freezes the opponent with a 1.075% chance.
691,200 GOLD
SELL
Frozen Claw +9
Damage: 57
Range: +21
Intelligence: 8
Grade: Rare
Ability: Freeze
Freezes the opponent with a 1.275% chance.
1,382,400 GOLD
SELL
Frozen Claw +10
Damage: 69
Range: +26
Intelligence: 8
Grade: Rare
Ability: Freeze
Freezes the opponent with a 1.575% chance.
2,764,800 GOLD
SELL
Quiver
Range: +20
Dexterity: 2
Armor: 10
7,200 GOLD
SELL
Quiver +1
Range: +24
Dexterity: 3
Armor: 12
7,200 GOLD
SELL
Quiver +2
Range: +27
Dexterity: 4
Armor: 14
7,200 GOLD
SELL
Quiver +3
Range: +31
Dexterity: 5
Armor: 16
Grade: High
7,200 GOLD
SELL
Quiver +4
Range: +34
Dexterity: 6
Armor: 18
Grade: High
7,200 GOLD
SELL
Quiver +5
Range: +38
Dexterity: 7
Armor: 20
Grade: High
14,400 GOLD
SELL
Quiver +6
Range: +41
Dexterity: 8
Armor: 22
Grade: High
28,800 GOLD
SELL
Quiver +7
Range: +45
Dexterity: 9
Armor: 25
Grade: Rare
57,600 GOLD
SELL
Quiver +8
Range: +51
Dexterity: 11
Armor: 28
Grade: Rare
115,200 GOLD
SELL
Quiver +9
Range: +58
Dexterity: 13
Armor: 32
Grade: Rare
230,400 GOLD
SELL
Quiver +10
Range: +68
Dexterity: 16
Armor: 38
Grade: Rare
460,800 GOLD
SELL
Staff
Damage: 25
Range: +50
7,440 GOLD
SELL
Staff +1
Damage: 30
Range: +53
7,440 GOLD
SELL
Staff +2
Damage: 35
Range: +56
7,440 GOLD
SELL
Staff +3
Damage: 40
Range: +59
7,440 GOLD
SELL
Staff +4
Damage: 45
Range: +62
7,440 GOLD
SELL
Staff +5
Damage: 50
Range: +65
14,880 GOLD
SELL
Staff +6
Damage: 55
Range: +68
29,760 GOLD
SELL
Staff +7
Damage: 61
Range: +72
Grade: High
59,520 GOLD
SELL
Staff +8
Damage: 69
Range: +76
Grade: High
119,040 GOLD
SELL
Staff +9
Damage: 79
Range: +82
Grade: Rare
238,080 GOLD
SELL
Staff +10
Damage: 94
Range: +91
Grade: Rare
476,160 GOLD
SELL
Test
An item to test item looks, just set the 'skin' property.
Shield
Armor: 60
Resistance: 20
14,400 GOLD
SELL
Shield +1
Armor: 73
Resistance: 28
14,400 GOLD
SELL
Shield +2
Armor: 85
Resistance: 35
14,400 GOLD
SELL
Shield +3
Armor: 98
Resistance: 43
14,400 GOLD
SELL
Shield +4
Armor: 110
Resistance: 50
Grade: High
14,400 GOLD
SELL
Shield +5
Armor: 123
Resistance: 58
Grade: High
28,800 GOLD
SELL
Shield +6
Armor: 135
Resistance: 65
Grade: High
57,600 GOLD
SELL
Shield +7
Armor: 151
Resistance: 74
Grade: High
115,200 GOLD
SELL
Shield +8
Armor: 169
Resistance: 86
Grade: Rare
230,400 GOLD
SELL
Shield +9
Armor: 194
Resistance: 101
Grade: Rare
460,800 GOLD
SELL
Shield +10
Armor: 232
Resistance: 123
Grade: Rare
921,600 GOLD
SELL
Xmas Shoes
Vitality: 2
Stat: 1
Armor: 6
Speed: +6
21,600 GOLD
SELL
Xmas Shoes +1
Vitality: 2
Stat: 2
Armor: 8
Speed: +7
21,600 GOLD
SELL
Xmas Shoes +2
Vitality: 2
Stat: 3
Armor: 10
Speed: +8
21,600 GOLD
SELL
Xmas Shoes +3
Vitality: 2
Stat: 4
Armor: 12
Speed: +8
21,600 GOLD
SELL
Xmas Shoes +4
Vitality: 2
Stat: 5
Armor: 14
Speed: +9
Grade: High
21,600 GOLD
SELL
Xmas Shoes +5
Vitality: 2
Stat: 6
Armor: 15
Speed: +10
Grade: High
43,200 GOLD
SELL
Xmas Shoes +6
Vitality: 2
Stat: 7
Armor: 17
Speed: +11
Grade: High
86,400 GOLD
SELL
Xmas Shoes +7
Vitality: 2
Stat: 9
Armor: 20
Speed: +11
Grade: High
172,800 GOLD
SELL
Xmas Shoes +8
Vitality: 2
Stat: 12
Armor: 22
Speed: +13
Grade: Rare
345,600 GOLD
SELL
Xmas Shoes +9
Vitality: 2
Stat: 15
Armor: 26
Speed: +14
Grade: Rare
691,200 GOLD
SELL
Xmas Shoes +10
Vitality: 2
Stat: 19
Armor: 32
Speed: +16
Grade: Rare
1,382,400 GOLD
SELL
Blade
Damage: 15
Range: +5
5,040 GOLD
SELL
Blade +1
Damage: 19
Range: +7
5,040 GOLD
SELL
Blade +2
Damage: 23
Range: +8
5,040 GOLD
SELL
Blade +3
Damage: 27
Range: +10
5,040 GOLD
SELL
Blade +4
Damage: 31
Range: +11
5,040 GOLD
SELL
Blade +5
Damage: 35
Range: +13
10,080 GOLD
SELL
Blade +6
Damage: 39
Range: +14
20,160 GOLD
SELL
Blade +7
Damage: 44
Range: +16
Grade: High
40,320 GOLD
SELL
Blade +8
Damage: 50
Range: +18
Grade: High
80,640 GOLD
SELL
Blade +9
Damage: 58
Range: +21
Grade: Rare
161,280 GOLD
SELL
Blade +10
Damage: 70
Range: +26
Grade: Rare
322,560 GOLD
SELL
Sturdy Gloves
Stat: 1
Armor: 16
Resistance: 8
Grade: High
20,400 GOLD
SELL
Sturdy Gloves +1
Stat: 2
Armor: 19
Resistance: 11
Grade: High
20,400 GOLD
SELL
Sturdy Gloves +2
Stat: 3
Armor: 21
Resistance: 13
Grade: High
20,400 GOLD
SELL
Sturdy Gloves +3
Stat: 4
Armor: 24
Resistance: 16
Grade: High
20,400 GOLD
SELL
Sturdy Gloves +4
Stat: 5
Armor: 26
Resistance: 18
Grade: High
20,400 GOLD
SELL
Sturdy Gloves +5
Stat: 6
Armor: 29
Resistance: 21
Grade: High
40,800 GOLD
SELL
Sturdy Gloves +6
Stat: 7
Armor: 31
Resistance: 23
Grade: High
81,600 GOLD
SELL
Sturdy Gloves +7
Stat: 9
Armor: 34
Resistance: 26
Grade: Rare
163,200 GOLD
SELL
Sturdy Gloves +8
Stat: 12
Armor: 38
Resistance: 30
Grade: Rare
326,400 GOLD
SELL
Sturdy Gloves +9
Stat: 15
Armor: 43
Resistance: 35
Grade: Rare
652,800 GOLD
SELL
Sturdy Gloves +10
Stat: 19
Armor: 50
Resistance: 42
Grade: Rare
1,305,600 GOLD
SELL
Essence of Frost
It's like an ice storm in a bottle
Dagger of the Dead
Damage: 18
Range: +5
Strength: 20
Vitality: -6
A.Piercing: 20
Run Speed: -2
Grade: High
A deadly weapon
74,400 GOLD
SELL
Dagger of the Dead +1
Damage: 23
Range: +7
Strength: 20
Vitality: -6
A.Piercing: 20
Run Speed: -2
Grade: High
A deadly weapon
74,400 GOLD
SELL
Dagger of the Dead +2
Damage: 27
Range: +9
Strength: 20
Vitality: -6
A.Piercing: 20
Run Speed: -2
Grade: High
A deadly weapon
74,400 GOLD
SELL
Dagger of the Dead +3
Damage: 32
Range: +11
Strength: 20
Vitality: -6
A.Piercing: 20
Run Speed: -2
Grade: High
A deadly weapon
74,400 GOLD
SELL
Dagger of the Dead +4
Damage: 36
Range: +13
Strength: 20
Vitality: -6
A.Piercing: 20
Run Speed: -2
Grade: High
A deadly weapon
74,400 GOLD
SELL
Dagger of the Dead +5
Damage: 41
Range: +15
Strength: 20
Vitality: -6
A.Piercing: 20
Run Speed: -2
Grade: High
A deadly weapon
148,800 GOLD
SELL
Dagger of the Dead +6
Damage: 45
Range: +17
Strength: 20
Vitality: -6
A.Piercing: 20
Run Speed: -2
Grade: Rare
A deadly weapon
297,600 GOLD
SELL
Dagger of the Dead +7
Damage: 51
Range: +20
Strength: 20
Vitality: -6
A.Piercing: 20
Run Speed: -2
Grade: Rare
A deadly weapon
595,200 GOLD
SELL
Dagger of the Dead +8
Damage: 57
Range: +23
Strength: 20
Vitality: -6
A.Piercing: 20
Run Speed: -2
Grade: Rare
A deadly weapon
1,190,400 GOLD
SELL
Dagger of the Dead +9
Damage: 66
Range: +27
Strength: 20
Vitality: -6
A.Piercing: 20
Run Speed: -2
Grade: Rare
A deadly weapon
2,380,800 GOLD
SELL
Dagger of the Dead +10
Damage: 80
Range: +33
Strength: 20
Vitality: -6
A.Piercing: 20
Run Speed: -2
Grade: Rare
A deadly weapon
4,761,600 GOLD
SELL
Elixir of Extreme Strength
Strength: 12
Hours: 48
Elixir of Strength
Strength: 6
Hours: 12
Elixir of Greater Strength
Strength: 8
Hours: 24
Amulet of Dexterity
Dexterity: 4
18,000 GOLD
SELL
Amulet of Dexterity +1
Dexterity: 7
57,600 GOLD
SELL
Amulet of Dexterity +2
Dexterity: 10
184,320 GOLD
SELL
Amulet of Dexterity +3
Dexterity: 13
Grade: High
589,824 GOLD
SELL
Amulet of Dexterity +4
Dexterity: 16
Grade: High
1,887,437 GOLD
SELL
Amulet of Dexterity +5
Dexterity: 20
Grade: Rare
6,039,798 GOLD
SELL
Candy Cane
The old man in Winterland was looking for sweets.
Rudolph's Red Nose
Range: +3
Cuteness: 9
3,840 GOLD
SELL
Rudolph's Red Nose +1
Range: +7
Cuteness: 12
12,288 GOLD
SELL
Rudolph's Red Nose +2
Range: +11
Cuteness: 15
Grade: High
39,322 GOLD
SELL
Rudolph's Red Nose +3
Range: +15
Cuteness: 18
Grade: High
125,829 GOLD
SELL
Rudolph's Red Nose +4
Range: +19
Cuteness: 21
Grade: High
402,653 GOLD
SELL
Rudolph's Red Nose +5
Range: +24
Cuteness: 25
Grade: Rare
1,288,490 GOLD
SELL
Intelligence Scroll
Adds Intelligence to an armor with a Stat attribute.
Spear
Damage: 15
Range: +15
A.Piercing: 10
43,200 GOLD
SELL
Spear +1
Damage: 19
Range: +17
A.Piercing: 15
43,200 GOLD
SELL
Spear +2
Damage: 24
Range: +19
A.Piercing: 20
43,200 GOLD
SELL
Spear +3
Damage: 28
Range: +21
A.Piercing: 25
Grade: High
43,200 GOLD
SELL
Spear +4
Damage: 32
Range: +23
A.Piercing: 30
Grade: High
43,200 GOLD
SELL
Spear +5
Damage: 36
Range: +25
A.Piercing: 35
Grade: High
86,400 GOLD
SELL
Spear +6
Damage: 41
Range: +27
A.Piercing: 40
Grade: High
172,800 GOLD
SELL
Spear +7
Damage: 46
Range: +30
A.Piercing: 46
Grade: High
345,600 GOLD
SELL
Spear +8
Damage: 52
Range: +33
A.Piercing: 54
Grade: Rare
691,200 GOLD
SELL
Spear +9
Damage: 61
Range: +37
A.Piercing: 64
Grade: Rare
1,382,400 GOLD
SELL
Spear +10
Damage: 73
Range: +43
A.Piercing: 79
Grade: Rare
2,764,800 GOLD
SELL
Carrot Sword
Damage: 20
Range: +3
Dexterity: 12
Charisma: -20
Grade: High
43,200 GOLD
SELL
Carrot Sword +1
Damage: 25
Range: +4
Dexterity: 12
Charisma: -20
Grade: High
43,200 GOLD
SELL
Carrot Sword +2
Damage: 29
Range: +5
Dexterity: 12
Charisma: -20
Grade: High
43,200 GOLD
SELL
Carrot Sword +3
Damage: 34
Range: +6
Dexterity: 12
Charisma: -20
Grade: High
43,200 GOLD
SELL
Carrot Sword +4
Damage: 38
Range: +7
Dexterity: 12
Charisma: -20
Grade: High
43,200 GOLD
SELL
Carrot Sword +5
Damage: 43
Range: +8
Dexterity: 12
Charisma: -20
Grade: High
86,400 GOLD
SELL
Carrot Sword +6
Damage: 47
Range: +9
Dexterity: 12
Charisma: -20
Grade: High
172,800 GOLD
SELL
Carrot Sword +7
Damage: 53
Range: +10
Dexterity: 12
Charisma: -20
Grade: Rare
345,600 GOLD
SELL
Carrot Sword +8
Damage: 59
Range: +12
Dexterity: 12
Charisma: -20
Grade: Rare
691,200 GOLD
SELL
Carrot Sword +9
Damage: 68
Range: +14
Dexterity: 12
Charisma: -20
Grade: Rare
1,382,400 GOLD
SELL
Carrot Sword +10
Damage: 82
Range: +17
Dexterity: 12
Charisma: -20
Grade: Rare
2,764,800 GOLD
SELL
Claw
Damage: 10
Range: +5
4,320 GOLD
SELL
Claw +1
Damage: 13
Range: +7
4,320 GOLD
SELL
Claw +2
Damage: 16
Range: +8
4,320 GOLD
SELL
Claw +3
Damage: 19
Range: +10
4,320 GOLD
SELL
Claw +4
Damage: 22
Range: +11
4,320 GOLD
SELL
Claw +5
Damage: 25
Range: +13
8,640 GOLD
SELL
Claw +6
Damage: 28
Range: +14
17,280 GOLD
SELL
Claw +7
Damage: 32
Range: +16
Grade: High
34,560 GOLD
SELL
Claw +8
Damage: 36
Range: +18
Grade: High
69,120 GOLD
SELL
Claw +9
Damage: 42
Range: +21
Grade: Rare
138,240 GOLD
SELL
Claw +10
Damage: 51
Range: +26
Grade: Rare
276,480 GOLD
SELL
Sturdy Shoes
Stat: 1
Armor: 8
Speed: +6
Grade: High
72,000 GOLD
SELL
Sturdy Shoes +1
Stat: 2
Armor: 11
Speed: +7
Grade: High
72,000 GOLD
SELL
Sturdy Shoes +2
Stat: 3
Armor: 13
Speed: +8
Grade: High
72,000 GOLD
SELL
Sturdy Shoes +3
Stat: 4
Armor: 16
Speed: +9
Grade: High
72,000 GOLD
SELL
Sturdy Shoes +4
Stat: 5
Armor: 18
Speed: +10
Grade: High
72,000 GOLD
SELL
Sturdy Shoes +5
Stat: 6
Armor: 21
Speed: +10
Grade: High
144,000 GOLD
SELL
Sturdy Shoes +6
Stat: 7
Armor: 23
Speed: +11
Grade: High
288,000 GOLD
SELL
Sturdy Shoes +7
Stat: 9
Armor: 26
Speed: +12
Grade: Rare
576,000 GOLD
SELL
Sturdy Shoes +8
Stat: 12
Armor: 30
Speed: +14
Grade: Rare
1,152,000 GOLD
SELL
Sturdy Shoes +9
Stat: 15
Armor: 35
Speed: +15
Grade: Rare
2,304,000 GOLD
SELL
Sturdy Shoes +10
Stat: 19
Armor: 42
Speed: +18
Grade: Rare
4,608,000 GOLD
SELL
Warp Vest
Stat: 1
Armor: 36
Resistance: 24
Grade: Rare
Warps space-time. Ancient Computer unlocks only a fraction of it's capabilities. Needs to be recharged in order to initiate a jump.
2,880,000 GOLD
SELL
Warp Vest +1
Strength: 10
Intelligence: 10
Dexterity: 10
Vitality: 10
Stat: 2
Armor: 40
Resistance: 28
Grade: Rare
Warps space-time. Ancient Computer unlocks only a fraction of it's capabilities. Needs to be recharged in order to initiate a jump.
2,880,000 GOLD
SELL
Warp Vest +2
Strength: 20
Intelligence: 20
Dexterity: 20
Vitality: 20
Stat: 3
Armor: 45
Resistance: 33
Grade: Rare
Warps space-time. Ancient Computer unlocks only a fraction of it's capabilities. Needs to be recharged in order to initiate a jump.
2,880,000 GOLD
SELL
Warp Vest +3
Strength: 30
Intelligence: 30
Dexterity: 30
Vitality: 30
Stat: 4
Armor: 49
Resistance: 37
Grade: Rare
Warps space-time. Ancient Computer unlocks only a fraction of it's capabilities. Needs to be recharged in order to initiate a jump.
2,880,000 GOLD
SELL
Warp Vest +4
Strength: 40
Intelligence: 40
Dexterity: 40
Vitality: 40
Stat: 5
Armor: 53
Resistance: 41
Grade: Rare
Warps space-time. Ancient Computer unlocks only a fraction of it's capabilities. Needs to be recharged in order to initiate a jump.
2,880,000 GOLD
SELL
Warp Vest +5
Strength: 50
Intelligence: 50
Dexterity: 50
Vitality: 50
Stat: 6
Armor: 57
Resistance: 45
Grade: Rare
Warps space-time. Ancient Computer unlocks only a fraction of it's capabilities. Needs to be recharged in order to initiate a jump.
5,760,000 GOLD
SELL
Warp Vest +6
Strength: 60
Intelligence: 60
Dexterity: 60
Vitality: 60
Stat: 7
Armor: 62
Resistance: 50
Grade: Rare
Warps space-time. Ancient Computer unlocks only a fraction of it's capabilities. Needs to be recharged in order to initiate a jump.
11,520,000 GOLD
SELL
Warp Vest +7
Strength: 73
Intelligence: 73
Dexterity: 73
Vitality: 73
Stat: 9
Armor: 67
Resistance: 55
Grade: Rare
Warps space-time. Ancient Computer unlocks only a fraction of it's capabilities. Needs to be recharged in order to initiate a jump.
23,040,000 GOLD
SELL
Warp Vest +8
Strength: 88
Intelligence: 88
Dexterity: 88
Vitality: 88
Stat: 12
Armor: 73
Resistance: 61
Grade: Rare
Warps space-time. Ancient Computer unlocks only a fraction of it's capabilities. Needs to be recharged in order to initiate a jump.
46,080,000 GOLD
SELL
Warp Vest +9
Strength: 108
Intelligence: 108
Dexterity: 108
Vitality: 108
Stat: 15
Armor: 82
Resistance: 70
Grade: Rare
Warps space-time. Ancient Computer unlocks only a fraction of it's capabilities. Needs to be recharged in order to initiate a jump.
92,160,000 GOLD
SELL
Warp Vest +10
Strength: 138
Intelligence: 138
Dexterity: 138
Vitality: 138
Stat: 19
Armor: 94
Resistance: 82
Grade: Rare
Warps space-time. Ancient Computer unlocks only a fraction of it's capabilities. Needs to be recharged in order to initiate a jump.
184,320,000 GOLD
SELL
Belt of HP
HP: 80
12,000 GOLD
SELL
Belt of HP +1
HP: 200
38,400 GOLD
SELL
Belt of HP +2
HP: 320
122,880 GOLD
SELL
Belt of HP +3
HP: 440
Grade: High
393,216 GOLD
SELL
Belt of HP +4
HP: 560
Grade: High
1,258,291 GOLD
SELL
Belt of HP +5
HP: 710
Grade: Rare
4,026,532 GOLD
SELL
Darkforge Underarmor
Stat: 1
Armor: 40
Resistance: 24
Grade: Rare
4,680,000 GOLD
SELL
Darkforge Underarmor +1
Stat: 2
Armor: 46
Resistance: 30
Grade: Rare
4,680,000 GOLD
SELL
Darkforge Underarmor +2
Stat: 3
Armor: 51
Resistance: 35
Grade: Rare
4,680,000 GOLD
SELL
Darkforge Underarmor +3
Stat: 4
Armor: 57
Resistance: 41
Grade: Rare
4,680,000 GOLD
SELL
Darkforge Underarmor +4
Stat: 5
Armor: 62
Resistance: 46
Grade: Rare
4,680,000 GOLD
SELL
Darkforge Underarmor +5
Stat: 6
Armor: 68
Resistance: 52
Grade: Rare
9,360,000 GOLD
SELL
Darkforge Underarmor +6
Stat: 7
Armor: 73
Resistance: 57
Grade: Rare
18,720,000 GOLD
SELL
Darkforge Underarmor +7
Stat: 9
Armor: 80
Resistance: 64
Grade: Rare
37,440,000 GOLD
SELL
Darkforge Underarmor +8
Stat: 12
Armor: 88
Resistance: 72
Grade: Rare
74,880,000 GOLD
SELL
Darkforge Underarmor +9
Stat: 15
Armor: 99
Resistance: 83
Grade: Rare
149,760,000 GOLD
SELL
Darkforge Underarmor +10
Stat: 19
Armor: 116
Resistance: 100
Grade: Rare
299,520,000 GOLD
SELL
Evasion Scroll
Adds Evasion to an armor with a Stat attribute.
Dexterity Scroll
Adds Dexterity to an armor with a Stat attribute.
Winged Boots
Stat: 1
Armor: 6
Resistance: 20
Speed: +8
A.Speed: 3
Grade: High
216,000 GOLD
SELL
Winged Boots +1
Stat: 2
Armor: 8
Resistance: 22
Speed: +9
A.Speed: 4
Grade: High
216,000 GOLD
SELL
Winged Boots +2
Stat: 3
Armor: 10
Resistance: 24
Speed: +10
A.Speed: 4
Grade: High
216,000 GOLD
SELL
Winged Boots +3
Stat: 4
Armor: 12
Resistance: 26
Speed: +11
A.Speed: 5
Grade: High
216,000 GOLD
SELL
Winged Boots +4
Stat: 5
Armor: 14
Resistance: 28
Speed: +12
A.Speed: 6
Grade: High
216,000 GOLD
SELL
Winged Boots +5
Stat: 6
Armor: 15
Resistance: 29
Speed: +13
A.Speed: 6
Grade: High
432,000 GOLD
SELL
Winged Boots +6
Stat: 7
Armor: 17
Resistance: 31
Speed: +14
A.Speed: 7
Grade: High
864,000 GOLD
SELL
Winged Boots +7
Stat: 9
Armor: 20
Resistance: 34
Speed: +15
A.Speed: 8
Grade: Rare
1,728,000 GOLD
SELL
Winged Boots +8
Stat: 12
Armor: 22
Resistance: 36
Speed: +17
A.Speed: 8
Grade: Rare
3,456,000 GOLD
SELL
Winged Boots +9
Stat: 15
Armor: 26
Resistance: 40
Speed: +19
A.Speed: 10
Grade: Rare
6,912,000 GOLD
SELL
Winged Boots +10
Stat: 19
Armor: 32
Resistance: 46
Speed: +22
A.Speed: 12
Grade: Rare
13,824,000 GOLD
SELL
Essence of Nature
Lively energy, waiting to spring
Pack of Confetti's
To celebrate good times
Pumpkin Head
Reflection: 1%
Stat: 1
Armor: 14
Resistance: 16
Grade: High
19,200 GOLD
SELL
Pumpkin Head +1
Reflection: 1.4%
Stat: 2
Armor: 17
Resistance: 19
Grade: High
19,200 GOLD
SELL
Pumpkin Head +2
Reflection: 1.8%
Stat: 3
Armor: 19
Resistance: 21
Grade: High
19,200 GOLD
SELL
Pumpkin Head +3
Reflection: 2.2%
Stat: 4
Armor: 22
Resistance: 24
Grade: High
19,200 GOLD
SELL
Pumpkin Head +4
Reflection: 2.6%
Stat: 5
Armor: 24
Resistance: 26
Grade: High
19,200 GOLD
SELL
Pumpkin Head +5
Reflection: 3%
Stat: 6
Armor: 27
Resistance: 29
Grade: High
38,400 GOLD
SELL
Pumpkin Head +6
Reflection: 3.4%
Stat: 7
Armor: 29
Resistance: 31
Grade: High
76,800 GOLD
SELL
Pumpkin Head +7
Reflection: 3.9%
Stat: 9
Armor: 32
Resistance: 34
Grade: Rare
153,600 GOLD
SELL
Pumpkin Head +8
Reflection: 4.5%
Stat: 12
Armor: 36
Resistance: 38
Grade: Rare
307,200 GOLD
SELL
Pumpkin Head +9
Reflection: 5.3%
Stat: 15
Armor: 41
Resistance: 43
Grade: Rare
614,400 GOLD
SELL
Pumpkin Head +10
Reflection: 6.5%
Stat: 19
Armor: 48
Resistance: 50
Grade: Rare
1,228,800 GOLD
SELL
Well-Crafted Cape
Stat: 5
Armor: 18
Resistance: 12
Grade: High
60,000 GOLD
SELL
Well-Crafted Cape +1
Stat: 5
Armor: 21
Resistance: 14
Grade: High
60,000 GOLD
SELL
Well-Crafted Cape +2
Stat: 5
Armor: 24
Resistance: 16
Grade: High
60,000 GOLD
SELL
Well-Crafted Cape +3
Stat: 5
Armor: 27
Resistance: 18
Grade: High
60,000 GOLD
SELL
Well-Crafted Cape +4
Stat: 5
Armor: 30
Resistance: 20
Grade: Rare
60,000 GOLD
SELL
Well-Crafted Cape +5
Stat: 5
Armor: 33
Resistance: 22
Grade: Rare
120,000 GOLD
SELL
Well-Crafted Cape +6
Stat: 5
Armor: 36
Resistance: 24
Grade: Rare
240,000 GOLD
SELL
Well-Crafted Cape +7
Stat: 5
Armor: 40
Resistance: 27
Grade: Rare
480,000 GOLD
SELL
Well-Crafted Cape +8
Stat: 5
Armor: 44
Resistance: 30
Grade: Rare
960,000 GOLD
SELL
Well-Crafted Cape +9
Stat: 5
Armor: 50
Resistance: 34
Grade: Rare
1,920,000 GOLD
SELL
Well-Crafted Cape +10
Stat: 5
Armor: 59
Resistance: 40
Grade: Rare
3,840,000 GOLD
SELL
Belt of Strength
Strength: 4
30,000 GOLD
SELL
Belt of Strength +1
Strength: 7
96,000 GOLD
SELL
Belt of Strength +2
Strength: 10
Grade: High
307,200 GOLD
SELL
Belt of Strength +3
Strength: 13
Grade: High
983,040 GOLD
SELL
Belt of Strength +4
Strength: 16
Grade: High
3,145,728 GOLD
SELL
Belt of Strength +5
Strength: 20
Grade: Rare
10,066,330 GOLD
SELL
Ancient Computer
Networks you to NPC's and extends the CODE capabilities.
T3 Bow
Damage: 32
Range: +60
9,600 GOLD
SELL
T3 Bow +1
Damage: 38
Range: +68
9,600 GOLD
SELL
T3 Bow +2
Damage: 43
Range: +76
9,600 GOLD
SELL
T3 Bow +3
Damage: 49
Range: +84
9,600 GOLD
SELL
T3 Bow +4
Damage: 54
Range: +92
9,600 GOLD
SELL
T3 Bow +5
Damage: 60
Range: +100
19,200 GOLD
SELL
T3 Bow +6
Damage: 65
Range: +108
38,400 GOLD
SELL
T3 Bow +7
Damage: 72
Range: +118
Grade: High
76,800 GOLD
SELL
T3 Bow +8
Damage: 80
Range: +130
Grade: High
153,600 GOLD
SELL
T3 Bow +9
Damage: 91
Range: +146
Grade: Rare
307,200 GOLD
SELL
T3 Bow +10
Damage: 108
Range: +170
Grade: Rare
614,400 GOLD
SELL
Amulet of HP
HP: 100
12,000 GOLD
SELL
Amulet of HP +1
HP: 220
38,400 GOLD
SELL
Amulet of HP +2
HP: 340
122,880 GOLD
SELL
Amulet of HP +3
HP: 460
Grade: High
393,216 GOLD
SELL
Amulet of HP +4
HP: 580
Grade: High
1,258,291 GOLD
SELL
Amulet of HP +5
HP: 730
Grade: Rare
4,026,532 GOLD
SELL
Golden Egg
Nope, it's not painted, an actual golden egg!
Sword of the Dead
Damage: 30
Range: +8
Strength: 12
Vitality: -8
Resistance: 20
Grade: High
74,400 GOLD
SELL
Sword of the Dead +1
Damage: 35
Range: +10
Strength: 12
Vitality: -8
Resistance: 23
Grade: High
74,400 GOLD
SELL
Sword of the Dead +2
Damage: 40
Range: +12
Strength: 12
Vitality: -8
Resistance: 25
Grade: High
74,400 GOLD
SELL
Sword of the Dead +3
Damage: 45
Range: +13
Strength: 12
Vitality: -8
Resistance: 28
Grade: High
74,400 GOLD
SELL
Sword of the Dead +4
Damage: 50
Range: +15
Strength: 12
Vitality: -8
Resistance: 30
Grade: High
74,400 GOLD
SELL
Sword of the Dead +5
Damage: 55
Range: +17
Strength: 12
Vitality: -8
Resistance: 33
Grade: High
148,800 GOLD
SELL
Sword of the Dead +6
Damage: 60
Range: +19
Strength: 12
Vitality: -8
Resistance: 35
Grade: Rare
297,600 GOLD
SELL
Sword of the Dead +7
Damage: 66
Range: +21
Strength: 12
Vitality: -8
Resistance: 38
Grade: Rare
595,200 GOLD
SELL
Sword of the Dead +8
Damage: 74
Range: +23
Strength: 12
Vitality: -8
Resistance: 42
Grade: Rare
1,190,400 GOLD
SELL
Sword of the Dead +9
Damage: 84
Range: +27
Strength: 12
Vitality: -8
Resistance: 47
Grade: Rare
2,380,800 GOLD
SELL
Sword of the Dead +10
Damage: 99
Range: +32
Strength: 12
Vitality: -8
Resistance: 54
Grade: Rare
4,761,600 GOLD
SELL
Rabbit's Foot
Luck: +10%
Grade: Rare
Taken from a rabbit who lived a long and happy life, after the natural death occurred, with pre-consent
72,000 GOLD
SELL
Rabbit's Foot +1
Luck: +15%
Grade: Rare
Taken from a rabbit who lived a long and happy life, after the natural death occurred, with pre-consent
230,400 GOLD
SELL
Rabbit's Foot +2
Luck: +20%
Grade: Rare
Taken from a rabbit who lived a long and happy life, after the natural death occurred, with pre-consent
737,280 GOLD
SELL
Rabbit's Foot +3
Luck: +25%
Grade: Rare
Taken from a rabbit who lived a long and happy life, after the natural death occurred, with pre-consent
2,359,296 GOLD
SELL
Rabbit's Foot +4
Luck: +30%
Grade: Rare
Taken from a rabbit who lived a long and happy life, after the natural death occurred, with pre-consent
7,549,747 GOLD
SELL
Rabbit's Foot +5
Luck: +36%
Grade: Rare
Taken from a rabbit who lived a long and happy life, after the natural death occurred, with pre-consent
24,159,191 GOLD
SELL
Darkforge Armor
Stat: 1
Armor: 48
Resistance: 32
Grade: Rare
2,880,000 GOLD
SELL
Darkforge Armor +1
Stat: 2
Armor: 54
Resistance: 38
Grade: Rare
2,880,000 GOLD
SELL
Darkforge Armor +2
Stat: 3
Armor: 59
Resistance: 43
Grade: Rare
2,880,000 GOLD
SELL
Darkforge Armor +3
Stat: 4
Armor: 65
Resistance: 49
Grade: Rare
2,880,000 GOLD
SELL
Darkforge Armor +4
Stat: 5
Armor: 70
Resistance: 54
Grade: Rare
2,880,000 GOLD
SELL
Darkforge Armor +5
Stat: 6
Armor: 76
Resistance: 60
Grade: Rare
5,760,000 GOLD
SELL
Darkforge Armor +6
Stat: 7
Armor: 81
Resistance: 65
Grade: Rare
11,520,000 GOLD
SELL
Darkforge Armor +7
Stat: 9
Armor: 88
Resistance: 72
Grade: Rare
23,040,000 GOLD
SELL
Darkforge Armor +8
Stat: 12
Armor: 96
Resistance: 80
Grade: Rare
46,080,000 GOLD
SELL
Darkforge Armor +9
Stat: 15
Armor: 107
Resistance: 91
Grade: Rare
92,160,000 GOLD
SELL
Darkforge Armor +10
Stat: 19
Armor: 124
Resistance: 108
Grade: Rare
184,320,000 GOLD
SELL
Quantum Piece
A unique component of a curious puzzle
Quantum Piece
A unique component of a curious puzzle
Quantum Piece
A unique component of a curious puzzle
The Lantern
Evasion: 10%
Resistance: 120
Grade: Rare
Forged from a naturally vibrating metal
288,000 GOLD
SELL
The Lantern +1
Evasion: 15%
Resistance: 130
Grade: Rare
Forged from a naturally vibrating metal
921,600 GOLD
SELL
The Lantern +2
Evasion: 20%
Resistance: 140
Grade: Rare
Forged from a naturally vibrating metal
2,949,120 GOLD
SELL
The Lantern +3
Evasion: 25%
Resistance: 150
Grade: Rare
Forged from a naturally vibrating metal
9,437,184 GOLD
SELL
The Lantern +4
Evasion: 30%
Resistance: 160
Grade: Rare
Forged from a naturally vibrating metal
30,198,989 GOLD
SELL
The Lantern +5
Evasion: 36.25%
Resistance: 173
Grade: Rare
Forged from a naturally vibrating metal
96,636,764 GOLD
SELL
Quantum Piece
A unique component of a curious puzzle
Quantum Piece
A unique component of a curious puzzle
Quantum Piece
A unique component of a curious puzzle
Quantum Piece
A unique component of a curious puzzle
Party Hat
Stat: 1
Armor: 7
Resistance: 8
7,200 GOLD
SELL
Party Hat +1
Stat: 2
Armor: 8
Resistance: 9
7,200 GOLD
SELL
Party Hat +2
Stat: 3
Armor: 10
Resistance: 11
7,200 GOLD
SELL
Party Hat +3
Strength: 1
Intelligence: 1
Dexterity: 1
Stat: 4
Armor: 11
Resistance: 12
7,200 GOLD
SELL
Party Hat +4
Strength: 1
Intelligence: 1
Dexterity: 1
Stat: 5
Armor: 12
Resistance: 13
7,200 GOLD
SELL
Party Hat +5
Strength: 1
Intelligence: 1
Dexterity: 1
Vitality: 1
Stat: 6
Armor: 13
Resistance: 14
14,400 GOLD
SELL
Party Hat +6
Strength: 1
Intelligence: 1
Dexterity: 1
Vitality: 1
Stat: 7
Armor: 15
Resistance: 16
28,800 GOLD
SELL
Party Hat +7
Strength: 1
Intelligence: 1
Dexterity: 1
Vitality: 1
Stat: 9
Armor: 16
Resistance: 17
Grade: High
57,600 GOLD
SELL
Party Hat +8
Strength: 2
Intelligence: 2
Dexterity: 2
Vitality: 1
Stat: 12
Armor: 18
Resistance: 19
Grade: High
115,200 GOLD
SELL
Party Hat +9
Strength: 2
Intelligence: 2
Dexterity: 2
Vitality: 1
Stat: 15
Armor: 20
Resistance: 21
Grade: Rare
230,400 GOLD
SELL
Party Hat +10
Strength: 3
Intelligence: 3
Dexterity: 3
Vitality: 1
Stat: 19
Armor: 24
Resistance: 25
Grade: Rare
460,800 GOLD
SELL
Gift
A Gift to celebrate our Anniversary!
Rare Gift
A Rare Gift to celebrate our Anniversary!
Quantum Piece
A unique component of a curious puzzle
Santa's Belt
Evasion: 4%
Dexterity: 3
Grade: High
38,400 GOLD
SELL
Santa's Belt +1
Evasion: 4%
Dexterity: 5
Grade: High
122,880 GOLD
SELL
Santa's Belt +2
Evasion: 4%
Dexterity: 7
Grade: High
393,216 GOLD
SELL
Santa's Belt +3
Evasion: 4%
Dexterity: 9
Grade: High
1,258,291 GOLD
SELL
Santa's Belt +4
Evasion: 4%
Dexterity: 11
Grade: Rare
4,026,532 GOLD
SELL
Santa's Belt +5
Evasion: 4%
Dexterity: 14
Grade: Rare
12,884,902 GOLD
SELL
Throwing Stars
Damage: 5
Range: +50
43,200 GOLD
SELL
Throwing Stars +1
Damage: 8
Range: +54
43,200 GOLD
SELL
Throwing Stars +2
Damage: 10
Range: +58
43,200 GOLD
SELL
Throwing Stars +3
Damage: 13
Range: +62
43,200 GOLD
SELL
Throwing Stars +4
Damage: 15
Range: +66
43,200 GOLD
SELL
Throwing Stars +5
Damage: 18
Range: +70
86,400 GOLD
SELL
Throwing Stars +6
Damage: 20
Range: +74
172,800 GOLD
SELL
Throwing Stars +7
Damage: 23
Range: +79
Grade: High
345,600 GOLD
SELL
Throwing Stars +8
Damage: 27
Range: +85
Grade: High
691,200 GOLD
SELL
Throwing Stars +9
Damage: 32
Range: +93
Grade: Rare
1,382,400 GOLD
SELL
Throwing Stars +10
Damage: 39
Range: +105
Grade: Rare
2,764,800 GOLD
SELL
Amulet of the Stubborn Ranger
Dexterity: 6
Vitality: 5
Grade: High
36,000 GOLD
SELL
Amulet of the Stubborn Ranger +1
Dexterity: 9
Vitality: 8
Grade: High
115,200 GOLD
SELL
Amulet of the Stubborn Ranger +2
Dexterity: 12
Vitality: 11
Grade: High
368,640 GOLD
SELL
Amulet of the Stubborn Ranger +3
Dexterity: 15
Vitality: 14
Grade: Rare
1,179,648 GOLD
SELL
Amulet of the Stubborn Ranger +4
Dexterity: 18
Vitality: 17
Grade: Rare
3,774,874 GOLD
SELL
Amulet of the Stubborn Ranger +5
Dexterity: 22
Vitality: 21
Grade: Rare
12,079,596 GOLD
SELL
Angel Wings
Evasion: 1%
Stat: 3
Resistance: 8
Speed: +1
Grade: High
12,000 GOLD
SELL
Angel Wings +1
Evasion: 1.2%
Stat: 3
Resistance: 9
Speed: +1
Grade: High
12,000 GOLD
SELL
Angel Wings +2
Evasion: 1.4%
Stat: 3
Resistance: 10
Speed: +1
Grade: High
12,000 GOLD
SELL
Angel Wings +3
Evasion: 1.6%
Stat: 3
Resistance: 11
Speed: +2
Grade: High
12,000 GOLD
SELL
Angel Wings +4
Evasion: 1.8%
Stat: 3
Resistance: 12
Speed: +2
Grade: High
12,000 GOLD
SELL
Angel Wings +5
Evasion: 2%
Stat: 3
Resistance: 13
Speed: +2
Grade: High
24,000 GOLD
SELL
Angel Wings +6
Evasion: 2.2%
Stat: 3
Resistance: 14
Speed: +2
Grade: Rare
48,000 GOLD
SELL
Angel Wings +7
Evasion: 2.45%
Stat: 3
Resistance: 15
Speed: +2
Grade: Rare
96,000 GOLD
SELL
Angel Wings +8
Evasion: 2.75%
Stat: 3
Resistance: 17
Speed: +3
Grade: Rare
192,000 GOLD
SELL
Angel Wings +9
Evasion: 3.15%
Stat: 3
Resistance: 19
Speed: +3
Grade: Rare
384,000 GOLD
SELL
Angel Wings +10
Evasion: 3.75%
Stat: 3
Resistance: 22
Speed: +4
Grade: Rare
768,000 GOLD
SELL
Tiny Ruby
A hard to find gem. Can be exchanged for random treasures.
Raw Emerald
A very rare gem. Can be exchanged for random treasures.
Star Killer's Pants
Crit: 2%
Vitality: 10
Stat: 1
Armor: 30
R.Piercing: 80
Resistance: 18
Grade: Rare
4,680,000 GOLD
SELL
Star Killer's Pants +1
Crit: 2.2%
Vitality: 10
Stat: 2
Armor: 34
R.Piercing: 85
Resistance: 22
Grade: Rare
4,680,000 GOLD
SELL
Star Killer's Pants +2
Crit: 2.4%
Vitality: 10
Stat: 3
Armor: 39
R.Piercing: 90
Resistance: 27
Grade: Rare
4,680,000 GOLD
SELL
Star Killer's Pants +3
Crit: 2.6%
Vitality: 10
Stat: 4
Armor: 43
R.Piercing: 95
Resistance: 31
Grade: Rare
4,680,000 GOLD
SELL
Star Killer's Pants +4
Crit: 2.8%
Vitality: 10
Stat: 5
Armor: 47
R.Piercing: 100
Resistance: 35
Grade: Rare
4,680,000 GOLD
SELL
Star Killer's Pants +5
Crit: 3%
Vitality: 10
Stat: 6
Armor: 51
R.Piercing: 105
Resistance: 39
Grade: Rare
9,360,000 GOLD
SELL
Star Killer's Pants +6
Crit: 3.2%
Vitality: 10
Stat: 7
Armor: 56
R.Piercing: 110
Resistance: 44
Grade: Rare
18,720,000 GOLD
SELL
Star Killer's Pants +7
Crit: 3.45%
Vitality: 10
Stat: 9
Armor: 61
R.Piercing: 116
Resistance: 49
Grade: Rare
37,440,000 GOLD
SELL
Star Killer's Pants +8
Crit: 3.75%
Vitality: 10
Stat: 12
Armor: 67
R.Piercing: 124
Resistance: 55
Grade: Rare
74,880,000 GOLD
SELL
Star Killer's Pants +9
Crit: 4.15%
Vitality: 10
Stat: 15
Armor: 76
R.Piercing: 134
Resistance: 64
Grade: Rare
149,760,000 GOLD
SELL
Star Killer's Pants +10
Crit: 4.75%
Vitality: 10
Stat: 19
Armor: 88
R.Piercing: 149
Resistance: 76
Grade: Rare
299,520,000 GOLD
SELL
Pouch of Poof
A pyrotechnic pouch developed for those who want to feel like Rogue's
Gold Booster
Gold: +30%
Boosts gold loot from chests.
2,395,200 GOLD
SELL
Gold Booster +1
Gold: +40%
Boosts gold loot from chests.
7,664,640 GOLD
SELL
Gold Booster +2
Gold: +50%
Boosts gold loot from chests.
24,526,848 GOLD
SELL
Gold Booster +3
Gold: +60%
Boosts gold loot from chests.
78,485,914 GOLD
SELL
Gold Booster +4
Gold: +70%
Boosts gold loot from chests.
251,154,924 GOLD
SELL
Gold Booster +5
Gold: +83%
Boosts gold loot from chests.
803,695,755 GOLD
SELL
Ring of Strength
Strength: 2
14,400 GOLD
SELL
Ring of Strength +1
Strength: 4
46,080 GOLD
SELL
Ring of Strength +2
Strength: 6
147,456 GOLD
SELL
Ring of Strength +3
Strength: 8
Grade: High
471,859 GOLD
SELL
Ring of Strength +4
Strength: 10
Grade: High
1,509,949 GOLD
SELL
Ring of Strength +5
Strength: 13
Grade: Rare
4,831,838 GOLD
SELL
Orb of Vitality
HP: 120
72,000 GOLD
SELL
Orb of Vitality +1
HP: 240
230,400 GOLD
SELL
Orb of Vitality +2
HP: 360
737,280 GOLD
SELL
Orb of Vitality +3
HP: 480
2,359,296 GOLD
SELL
Orb of Vitality +4
HP: 600
7,549,747 GOLD
SELL
Orb of Vitality +5
HP: 750
24,159,191 GOLD
SELL
Elixir of Intelligence
Intelligence: 6
Hours: 12
The Stone Key
A stone key, imbued with magical energy.
Belt of Intelligence
Intelligence: 4
30,000 GOLD
SELL
Belt of Intelligence +1
Intelligence: 7
96,000 GOLD
SELL
Belt of Intelligence +2
Intelligence: 10
Grade: High
307,200 GOLD
SELL
Belt of Intelligence +3
Intelligence: 13
Grade: High
983,040 GOLD
SELL
Belt of Intelligence +4
Intelligence: 16
Grade: High
3,145,728 GOLD
SELL
Belt of Intelligence +5
Intelligence: 20
Grade: Rare
10,066,330 GOLD
SELL
Rugged Pants
Stat: 1
Armor: 20
Resistance: 12
Grade: High
46,800 GOLD
SELL
Rugged Pants +1
Stat: 2
Armor: 23
Resistance: 15
Grade: High
46,800 GOLD
SELL
Rugged Pants +2
Stat: 3
Armor: 25
Resistance: 17
Grade: High
46,800 GOLD
SELL
Rugged Pants +3
Stat: 4
Armor: 28
Resistance: 20
Grade: High
46,800 GOLD
SELL
Rugged Pants +4
Stat: 5
Armor: 30
Resistance: 22
Grade: High
46,800 GOLD
SELL
Rugged Pants +5
Stat: 6
Armor: 33
Resistance: 25
Grade: High
93,600 GOLD
SELL
Rugged Pants +6
Stat: 7
Armor: 35
Resistance: 27
Grade: High
187,200 GOLD
SELL
Rugged Pants +7
Stat: 9
Armor: 38
Resistance: 30
Grade: Rare
374,400 GOLD
SELL
Rugged Pants +8
Stat: 12
Armor: 42
Resistance: 34
Grade: Rare
748,800 GOLD
SELL
Rugged Pants +9
Stat: 15
Armor: 47
Resistance: 39
Grade: Rare
1,497,600 GOLD
SELL
Rugged Pants +10
Stat: 19
Armor: 54
Resistance: 46
Grade: Rare
2,995,200 GOLD
SELL
Amulet of Mystery
Evasion: 2%
Reflection: 0.5%
D.Return: 1%
Crit: 2%
HP: 40
Strength: 1
Intelligence: 1
Dexterity: 1
Armor: 10
384,000 GOLD
SELL
Amulet of Mystery +1
Evasion: 3%
Reflection: 1%
D.Return: 2%
Crit: 3%
HP: 100
Strength: 2
Intelligence: 2
Dexterity: 2
Armor: 12
1,228,800 GOLD
SELL
Amulet of Mystery +2
Evasion: 4%
Reflection: 1.5%
D.Return: 2%
Crit: 4%
HP: 160
Strength: 3
Intelligence: 3
Dexterity: 3
Armor: 14
3,932,160 GOLD
SELL
Amulet of Mystery +3
Evasion: 5%
Reflection: 2%
D.Return: 3%
Crit: 5%
HP: 220
Strength: 4
Intelligence: 4
Dexterity: 4
Armor: 16
Grade: High
12,582,912 GOLD
SELL
Amulet of Mystery +4
Evasion: 6%
Reflection: 2.5%
D.Return: 3%
Crit: 6%
HP: 280
Strength: 5
Intelligence: 5
Dexterity: 5
Armor: 18
Grade: High
40,265,318 GOLD
SELL
Amulet of Mystery +5
Evasion: 7.25%
Reflection: 3.125%
D.Return: 4%
Crit: 7.25%
HP: 355
Strength: 6
Intelligence: 6
Dexterity: 6
Armor: 21
Grade: Rare
128,849,019 GOLD
SELL
Fiery Blade
Damage: 18
Range: +5
Grade: High
43,200 GOLD
SELL
Fiery Blade +1
Damage: 23
Range: +7
Grade: High
43,200 GOLD
SELL
Fiery Blade +2
Damage: 27
Range: +8
Grade: High
43,200 GOLD
SELL
Fiery Blade +3
Damage: 32
Range: +10
Grade: High
43,200 GOLD
SELL
Fiery Blade +4
Damage: 36
Range: +11
Grade: High
43,200 GOLD
SELL
Fiery Blade +5
Damage: 41
Range: +13
Grade: High
86,400 GOLD
SELL
Fiery Blade +6
Damage: 45
Range: +14
Grade: High
172,800 GOLD
SELL
Fiery Blade +7
Damage: 51
Range: +16
Grade: High
345,600 GOLD
SELL
Fiery Blade +8
Damage: 57
Range: +18
Grade: Rare
691,200 GOLD
SELL
Fiery Blade +9
Damage: 66
Range: +21
Grade: Rare
1,382,400 GOLD
SELL
Fiery Blade +10
Damage: 80
Range: +26
Grade: Rare
2,764,800 GOLD
SELL
+ + \ No newline at end of file diff --git a/design/docs/mgolds0.txt b/design/docs/mgolds0.txt new file mode 100644 index 0000000..22b95d0 --- /dev/null +++ b/design/docs/mgolds0.txt @@ -0,0 +1,97 @@ +dungeon0 goo gold: 5 gold/hp: 0.05 +goobrawl goo gold: 5 gold/hp: 0.05 +cave bat gold: 277 gold/hp: 0.11541666666666667 +cave bat gold: 277 gold/hp: 0.11541666666666667 +cave bat gold: 277 gold/hp: 0.11541666666666667 +cave bat gold: 277 gold/hp: 0.11541666666666667 +cave bat gold: 277 gold/hp: 0.11541666666666667 +cave mvampire gold: 12000 gold/hp: 0.05 +batcave bat gold: 383 gold/hp: 0.15958333333333333 +batcave mvampire gold: 13900 gold/hp: 0.057916666666666665 +halloween osnake gold: 36 gold/hp: 0.05 +halloween osnake gold: 36 gold/hp: 0.05 +halloween snake gold: 36 gold/hp: 0.05 +halloween greenjr gold: 210 gold/hp: 0.05 +halloween minimush gold: 34 gold/hp: 0.068 +halloween xscorpion gold: 3880 gold/hp: 0.16166666666666665 +halloween snake gold: 36 gold/hp: 0.05 +halloween osnake gold: 36 gold/hp: 0.05 +halloween ghost gold: 1210 gold/hp: 0.10083333333333333 +halloween ghost gold: 1210 gold/hp: 0.10083333333333333 +halloween fvampire gold: 14968 gold/hp: 0.06236666666666667 +halloween ghost gold: 1210 gold/hp: 0.10083333333333333 +old_main goo gold: 5 gold/hp: 0.05 +old_main spider gold: 366 gold/hp: 0.20333333333333334 +old_main scorpion gold: 435 gold/hp: 0.18125 +old_main bat gold: 383 gold/hp: 0.15958333333333333 +old_main dknight2 gold: 1463 gold/hp: 0.182875 +old_main phoenix gold: 3000 gold/hp: 0.05 +arena cgoo gold: 60 gold/hp: 0.05 +arena cgoo gold: 60 gold/hp: 0.05 +arena skeletor gold: 12960 gold/hp: 0.162 +arena cgoo gold: 60 gold/hp: 0.05 +arena cgoo gold: 60 gold/hp: 0.05 +winterland stompy gold: 333919 gold/hp: 0.5217484375 +winterland wolf gold: 7798 gold/hp: 0.3249166666666667 +winterland arcticbee gold: 131 gold/hp: 0.081875 +winterland wolfie gold: 3971 gold/hp: 0.20682291666666666 +winterland wolfie gold: 3971 gold/hp: 0.20682291666666666 +winterland boar gold: 1908 gold/hp: 0.159 +winterland iceroamer gold: 374 gold/hp: 0.10388888888888889 +winterland iceroamer gold: 374 gold/hp: 0.10388888888888889 +tunnel mole gold: 3216 gold/hp: 0.2593548387096774 +tunnel mole gold: 3216 gold/hp: 0.2593548387096774 +desertland plantoid gold: 34559 gold/hp: 0.4319875 +winter_cave bbpompom gold: 1012 gold/hp: 0.158125 +winter_cave bbpompom gold: 1012 gold/hp: 0.158125 +main crab gold: 10 gold/hp: 0.05 +main squig gold: 79 gold/hp: 0.079 +main squigtoad gold: 30 gold/hp: 0.05 +main tortoise gold: 214 gold/hp: 0.107 +main frog gold: 30 gold/hp: 0.05 +main crabx gold: 441 gold/hp: 0.105 +main target gold: 8533 gold/hp: 0.17066 +main target_a500 gold: 11033 gold/hp: 0.22066 +main target_a750 gold: 12283 gold/hp: 0.24566 +main target_r500 gold: 11033 gold/hp: 0.22066 +main target_r750 gold: 12283 gold/hp: 0.24566 +main target_ar900 gold: 17533 gold/hp: 0.35066 +main target_ar500red gold: 13533 gold/hp: 0.27066 +main goo gold: 5 gold/hp: 0.05 +main bee gold: 15 gold/hp: 0.05 +main bee gold: 15 gold/hp: 0.05 +main bee gold: 15 gold/hp: 0.05 +main bee gold: 15 gold/hp: 0.05 +main bee gold: 15 gold/hp: 0.05 +main poisio gold: 138 gold/hp: 0.115 +main croc gold: 82 gold/hp: 0.082 +main armadillo gold: 81 gold/hp: 0.09 +main snake gold: 36 gold/hp: 0.05 +main bigbird gold: 5457 gold/hp: 0.17053125 +main spider gold: 259 gold/hp: 0.1438888888888889 +main scorpion gold: 293 gold/hp: 0.12208333333333334 +main phoenix gold: 3000 gold/hp: 0.05 +main greenfairy gold: 1123601 gold/hp: 0.3121113888888889 +main redfairy gold: 2164801 gold/hp: 0.4510002083333333 +main bluefairy gold: 1070667 gold/hp: 0.26766675 +main puppy1 gold: 5016 gold/hp: 50.16 +main puppy2 gold: 5016 gold/hp: 50.16 +main puppy3 gold: 5016 gold/hp: 50.16 +main puppy4 gold: 5016 gold/hp: 50.16 +main kitty1 gold: 5016 gold/hp: 50.16 +main kitty2 gold: 5016 gold/hp: 50.16 +main kitty3 gold: 5016 gold/hp: 50.16 +main kitty4 gold: 5016 gold/hp: 50.16 +jail jrat gold: 1014 gold/hp: 0.2535 +mansion rat gold: 122 gold/hp: 0.14878048780487804 +mansion rat gold: 122 gold/hp: 0.14878048780487804 +mansion rat gold: 122 gold/hp: 0.14878048780487804 +mansion rat gold: 122 gold/hp: 0.14878048780487804 +mansion rat gold: 122 gold/hp: 0.14878048780487804 +mansion rat gold: 122 gold/hp: 0.14878048780487804 +mansion rat gold: 122 gold/hp: 0.14878048780487804 +spookytown mummy gold: 1460 gold/hp: 0.12166666666666667 +spookytown booboo gold: 222 gold/hp: 0.0555 +spookytown stoneworm gold: 201 gold/hp: 0.09136363636363637 +spookytown stoneworm gold: 201 gold/hp: 0.09136363636363637 +spookytown jr gold: 160 gold/hp: 0.05 \ No newline at end of file diff --git a/design/docs/mgolds1.txt b/design/docs/mgolds1.txt new file mode 100644 index 0000000..319d444 --- /dev/null +++ b/design/docs/mgolds1.txt @@ -0,0 +1,96 @@ +arena cgoo gold: 60 gold/hp: 0.05 +arena cgoo gold: 60 gold/hp: 0.05 +arena skeletor gold: 4000 gold/hp: 0.05 +arena cgoo gold: 60 gold/hp: 0.05 +arena cgoo gold: 60 gold/hp: 0.05 +desertland plantoid gold: 17279 gold/hp: 0.2159875 +tunnel mole gold: 1694 gold/hp: 0.13661290322580646 +tunnel mole gold: 1694 gold/hp: 0.13661290322580646 +winterland stompy gold: 146319 gold/hp: 0.2286234375 +winterland wolf gold: 3350 gold/hp: 0.13958333333333334 +winterland arcticbee gold: 80 gold/hp: 0.05 +winterland wolfie gold: 1546 gold/hp: 0.08052083333333333 +winterland wolfie gold: 1546 gold/hp: 0.08052083333333333 +winterland boar gold: 684 gold/hp: 0.057 +winterland iceroamer gold: 180 gold/hp: 0.05 +winterland iceroamer gold: 180 gold/hp: 0.05 +winter_cave bbpompom gold: 361 gold/hp: 0.05640625 +winter_cave bbpompom gold: 361 gold/hp: 0.05640625 +goobrawl goo gold: 10 gold/hp: 0.1 +dungeon0 goo gold: 10 gold/hp: 0.1 +spookytown mummy gold: 600 gold/hp: 0.05 +spookytown booboo gold: 200 gold/hp: 0.05 +spookytown stoneworm gold: 110 gold/hp: 0.05 +spookytown stoneworm gold: 110 gold/hp: 0.05 +spookytown jr gold: 160 gold/hp: 0.05 +main crab gold: 20 gold/hp: 0.1 +main squig gold: 62 gold/hp: 0.062 +main squigtoad gold: 45 gold/hp: 0.075 +main tortoise gold: 100 gold/hp: 0.05 +main frog gold: 45 gold/hp: 0.075 +main crabx gold: 210 gold/hp: 0.05 +main target gold: 2783 gold/hp: 0.05566 +main target_a500 gold: 4033 gold/hp: 0.08066 +main target_a750 gold: 4658 gold/hp: 0.09316 +main target_r500 gold: 4033 gold/hp: 0.08066 +main target_r750 gold: 4658 gold/hp: 0.09316 +main target_ar900 gold: 7283 gold/hp: 0.14566 +main target_ar500red gold: 5283 gold/hp: 0.10566 +main goo gold: 10 gold/hp: 0.1 +main bee gold: 30 gold/hp: 0.1 +main bee gold: 30 gold/hp: 0.1 +main bee gold: 30 gold/hp: 0.1 +main bee gold: 30 gold/hp: 0.1 +main bee gold: 30 gold/hp: 0.1 +main poisio gold: 60 gold/hp: 0.05 +main croc gold: 62 gold/hp: 0.062 +main armadillo gold: 56 gold/hp: 0.06222222222222222 +main snake gold: 45 gold/hp: 0.0625 +main bigbird gold: 1773 gold/hp: 0.05540625 +main spider gold: 90 gold/hp: 0.05 +main scorpion gold: 120 gold/hp: 0.05 +main phoenix gold: 3000 gold/hp: 0.05 +main greenfairy gold: 275001 gold/hp: 0.07638916666666666 +main redfairy gold: 760001 gold/hp: 0.15833354166666666 +main bluefairy gold: 236667 gold/hp: 0.05916675 +main puppy1 gold: 5010 gold/hp: 50.1 +main puppy2 gold: 5010 gold/hp: 50.1 +main puppy3 gold: 5010 gold/hp: 50.1 +main puppy4 gold: 5010 gold/hp: 50.1 +main kitty1 gold: 5010 gold/hp: 50.1 +main kitty2 gold: 5010 gold/hp: 50.1 +main kitty3 gold: 5010 gold/hp: 50.1 +main kitty4 gold: 5010 gold/hp: 50.1 +old_main goo gold: 10 gold/hp: 0.1 +old_main spider gold: 183 gold/hp: 0.10166666666666667 +old_main scorpion gold: 209 gold/hp: 0.08708333333333333 +old_main bat gold: 162 gold/hp: 0.0675 +old_main dknight2 gold: 541 gold/hp: 0.067625 +old_main phoenix gold: 3000 gold/hp: 0.05 +cave bat gold: 120 gold/hp: 0.05 +cave bat gold: 120 gold/hp: 0.05 +cave bat gold: 120 gold/hp: 0.05 +cave bat gold: 120 gold/hp: 0.05 +cave bat gold: 120 gold/hp: 0.05 +cave mvampire gold: 12000 gold/hp: 0.05 +mansion rat gold: 70 gold/hp: 0.08536585365853659 +mansion rat gold: 70 gold/hp: 0.08536585365853659 +mansion rat gold: 70 gold/hp: 0.08536585365853659 +mansion rat gold: 70 gold/hp: 0.08536585365853659 +mansion rat gold: 70 gold/hp: 0.08536585365853659 +mansion rat gold: 70 gold/hp: 0.08536585365853659 +mansion rat gold: 70 gold/hp: 0.08536585365853659 +batcave bat gold: 162 gold/hp: 0.0675 +batcave mvampire gold: 12000 gold/hp: 0.05 +halloween osnake gold: 45 gold/hp: 0.0625 +halloween osnake gold: 45 gold/hp: 0.0625 +halloween snake gold: 45 gold/hp: 0.0625 +halloween greenjr gold: 210 gold/hp: 0.05 +halloween minimush gold: 37 gold/hp: 0.074 +halloween xscorpion gold: 1232 gold/hp: 0.051333333333333335 +halloween snake gold: 45 gold/hp: 0.0625 +halloween osnake gold: 45 gold/hp: 0.0625 +halloween ghost gold: 600 gold/hp: 0.05 +halloween ghost gold: 600 gold/hp: 0.05 +halloween fvampire gold: 12000 gold/hp: 0.05 +halloween ghost gold: 600 gold/hp: 0.05 \ No newline at end of file diff --git a/design/docs/movement_design.txt b/design/docs/movement_design.txt new file mode 100644 index 0000000..4f3a7f3 --- /dev/null +++ b/design/docs/movement_design.txt @@ -0,0 +1,26 @@ +[BLOCKS] +400x400 Blocks for line, player, monster caching + +[APPEARANCE] +Challenging + +[MOVEMENT/LINES] +1- When a new direction/point arrives + a- Verify it + b- Calculate a new path + + + +>> NEW [04/03/17] + +[VISION] +1300x820 for everyone (slightly above 5K) + +[BLOCKS] +400x400 - 12 Blocks for one player + +[RESEND] +When block changes - or ~100PX + +[PULL] +When block changes - or ~100PX \ No newline at end of file diff --git a/design/docs/old_SCHEDULE.txt b/design/docs/old_SCHEDULE.txt new file mode 100644 index 0000000..f000bd3 --- /dev/null +++ b/design/docs/old_SCHEDULE.txt @@ -0,0 +1,8 @@ +[18/08/17]: Prepare + Launch the underground +[19/08/17]: Game Tutorial +[20/08/17]: Improve Code with Events +[21/08/17]: Code Tutorial V1 +[22/08/17]: Code Documentation V1 +[23/08/17]: Winterland Event +[24/08/17]: Sounds + Music - Re-Visit +[25/08/17]: Standalone Client Re-Visit + Steam Research \ No newline at end of file diff --git a/design/docs/s8090.out b/design/docs/s8090.out new file mode 100644 index 0000000..ba93db9 --- /dev/null +++ b/design/docs/s8090.out @@ -0,0 +1,5950 @@ +Server Live: I USI (Fri Aug 31 2018 14:11:50 GMT+0000 (Coordinated Universal Time)) +Node Version: v10.5.0 (Fri Aug 31 2018 14:11:50 GMT+0000 (Coordinated Universal Time)) +tunnel mole gold: 793 gold/hp: 0.0639516129032258 +tunnel mole gold: 793 gold/hp: 0.0639516129032258 +goobrawl goo gold: 10 gold/hp: 0.1 +dungeon0 goo gold: 10 gold/hp: 0.1 +halloween osnake gold: 45 gold/hp: 0.0625 +halloween osnake gold: 45 gold/hp: 0.0625 +halloween snake gold: 45 gold/hp: 0.0625 +halloween greenjr gold: 126 gold/hp: 0.03 +halloween minimush gold: 37 gold/hp: 0.074 +halloween xscorpion gold: 720 gold/hp: 0.03 +halloween snake gold: 45 gold/hp: 0.0625 +halloween osnake gold: 45 gold/hp: 0.0625 +halloween ghost gold: 360 gold/hp: 0.03 +halloween ghost gold: 360 gold/hp: 0.03 +halloween fvampire gold: 7200 gold/hp: 0.03 +halloween ghost gold: 360 gold/hp: 0.03 +winterland stompy gold: 56784 gold/hp: 0.088725 +winterland wolf gold: 1992 gold/hp: 0.083 +winterland arcticbee gold: 80 gold/hp: 0.05 +winterland wolfie gold: 1116 gold/hp: 0.058125 +winterland wolfie gold: 1116 gold/hp: 0.058125 +winterland boar gold: 456 gold/hp: 0.038 +winterland iceroamer gold: 108 gold/hp: 0.03 +winterland iceroamer gold: 108 gold/hp: 0.03 +spookytown mummy gold: 360 gold/hp: 0.03 +spookytown booboo gold: 120 gold/hp: 0.03 +spookytown stoneworm gold: 66 gold/hp: 0.03 +spookytown stoneworm gold: 66 gold/hp: 0.03 +spookytown jr gold: 96 gold/hp: 0.03 +mansion rat gold: 51 gold/hp: 0.06219512195121951 +mansion rat gold: 51 gold/hp: 0.06219512195121951 +mansion rat gold: 51 gold/hp: 0.06219512195121951 +mansion rat gold: 51 gold/hp: 0.06219512195121951 +mansion rat gold: 51 gold/hp: 0.06219512195121951 +mansion rat gold: 51 gold/hp: 0.06219512195121951 +mansion rat gold: 51 gold/hp: 0.06219512195121951 +batcave bat gold: 123 gold/hp: 0.05125 +batcave mvampire gold: 7200 gold/hp: 0.03 +arena cgoo gold: 60 gold/hp: 0.05 +arena cgoo gold: 60 gold/hp: 0.05 +arena skeletor gold: 2400 gold/hp: 0.03 +arena cgoo gold: 60 gold/hp: 0.05 +arena cgoo gold: 60 gold/hp: 0.05 +old_main goo gold: 10 gold/hp: 0.1 +old_main spider gold: 143 gold/hp: 0.07944444444444444 +old_main scorpion gold: 167 gold/hp: 0.06958333333333333 +old_main bat gold: 123 gold/hp: 0.05125 +old_main dknight2 gold: 382 gold/hp: 0.04775 +old_main phoenix gold: 1800 gold/hp: 0.03 +desertland plantoid gold: 5207 gold/hp: 0.0650875 +cave bat gold: 72 gold/hp: 0.03 +cave bat gold: 72 gold/hp: 0.03 +cave bat gold: 72 gold/hp: 0.03 +cave bat gold: 72 gold/hp: 0.03 +cave bat gold: 72 gold/hp: 0.03 +cave mvampire gold: 7200 gold/hp: 0.03 +jail jrat gold: 228 gold/hp: 0.057 +winter_cave bbpompom gold: 234 gold/hp: 0.0365625 +winter_cave bbpompom gold: 234 gold/hp: 0.0365625 +main crab gold: 20 gold/hp: 0.1 +main squig gold: 62 gold/hp: 0.062 +main squigtoad gold: 45 gold/hp: 0.075 +main tortoise gold: 60 gold/hp: 0.03 +main frog gold: 45 gold/hp: 0.075 +main crabx gold: 126 gold/hp: 0.03 +main target gold: 20 gold/hp: 0.0004 +main target_a500 gold: 20 gold/hp: 0.0004 +main target_a750 gold: 20 gold/hp: 0.0004 +main target_r500 gold: 20 gold/hp: 0.0004 +main target_r750 gold: 20 gold/hp: 0.0004 +main target_ar900 gold: 20 gold/hp: 0.0004 +main target_ar500red gold: 20 gold/hp: 0.00004 +main goo gold: 10 gold/hp: 0.1 +main bee gold: 30 gold/hp: 0.1 +main bee gold: 30 gold/hp: 0.1 +main bee gold: 30 gold/hp: 0.1 +main bee gold: 30 gold/hp: 0.1 +main bee gold: 30 gold/hp: 0.1 +main poisio gold: 60 gold/hp: 0.05 +main croc gold: 62 gold/hp: 0.062 +main armadillo gold: 56 gold/hp: 0.06222222222222222 +main snake gold: 45 gold/hp: 0.0625 +main bigbird gold: 1009 gold/hp: 0.03153125 +main spider gold: 90 gold/hp: 0.05 +main scorpion gold: 72 gold/hp: 0.03 +main phoenix gold: 1800 gold/hp: 0.03 +main greenfairy gold: 108000 gold/hp: 0.03 +main redfairy gold: 148001 gold/hp: 0.030833541666666665 +main bluefairy gold: 120000 gold/hp: 0.03 +main puppy1 gold: 20 gold/hp: 0.2 +main puppy2 gold: 20 gold/hp: 0.2 +main puppy3 gold: 20 gold/hp: 0.2 +main puppy4 gold: 20 gold/hp: 0.2 +main kitty1 gold: 20 gold/hp: 0.2 +main kitty2 gold: 20 gold/hp: 0.2 +main kitty3 gold: 20 gold/hp: 0.2 +main kitty4 gold: 20 gold/hp: 0.2 +shellsisland kitty1 gold: 20 gold/hp: 0.2 +shellsisland kitty2 gold: 20 gold/hp: 0.2 +shellsisland kitty3 gold: 20 gold/hp: 0.2 +shellsisland kitty4 gold: 20 gold/hp: 0.2 +shellsisland puppy1 gold: 20 gold/hp: 0.2 +shellsisland puppy2 gold: 20 gold/hp: 0.2 +shellsisland puppy3 gold: 20 gold/hp: 0.2 +shellsisland puppy4 gold: 20 gold/hp: 0.2 +Created an instance of main (Fri Aug 31 2018 14:11:53 GMT+0000 (Coordinated Universal Time)) +Created an instance of tunnel (Fri Aug 31 2018 14:11:53 GMT+0000 (Coordinated Universal Time)) +Created an instance of cave (Fri Aug 31 2018 14:11:54 GMT+0000 (Coordinated Universal Time)) +Created an instance of tavern (Fri Aug 31 2018 14:11:55 GMT+0000 (Coordinated Universal Time)) +Created an instance of resort_e (Fri Aug 31 2018 14:11:55 GMT+0000 (Coordinated Universal Time)) +Created an instance of resort (Fri Aug 31 2018 14:11:55 GMT+0000 (Coordinated Universal Time)) +Created an instance of mansion (Fri Aug 31 2018 14:11:55 GMT+0000 (Coordinated Universal Time)) +Created an instance of woffice (Fri Aug 31 2018 14:11:55 GMT+0000 (Coordinated Universal Time)) +Created an instance of halloween (Fri Aug 31 2018 14:11:57 GMT+0000 (Coordinated Universal Time)) +Created an instance of spookytown (Fri Aug 31 2018 14:11:59 GMT+0000 (Coordinated Universal Time)) +Created an instance of test (Fri Aug 31 2018 14:11:59 GMT+0000 (Coordinated Universal Time)) +Created an instance of jail (Fri Aug 31 2018 14:11:59 GMT+0000 (Coordinated Universal Time)) +Created an instance of arena (Fri Aug 31 2018 14:12:00 GMT+0000 (Coordinated Universal Time)) +Created an instance of bank (Fri Aug 31 2018 14:12:00 GMT+0000 (Coordinated Universal Time)) +Created an instance of winterland (Fri Aug 31 2018 14:12:03 GMT+0000 (Coordinated Universal Time)) +Created an instance of winter_inn (Fri Aug 31 2018 14:12:04 GMT+0000 (Coordinated Universal Time)) +Created an instance of winter_inn_rooms (Fri Aug 31 2018 14:12:04 GMT+0000 (Coordinated Universal Time)) +Created an instance of winter_cave (Fri Aug 31 2018 14:12:04 GMT+0000 (Coordinated Universal Time)) +desertland is either un-bounded or the spawn point is too close to an edge (Fri Aug 31 2018 14:12:07 GMT+0000 (Coordinated Universal Time)) +Created an instance of desertland (Fri Aug 31 2018 14:12:07 GMT+0000 (Coordinated Universal Time)) +Created an instance of level1 (Fri Aug 31 2018 14:12:07 GMT+0000 (Coordinated Universal Time)) +Created an instance of level2 (Fri Aug 31 2018 14:12:08 GMT+0000 (Coordinated Universal Time)) +Spawn [level2n,0,0] is 7.9999999 close to a line! >=12 is a must. +Created an instance of level2n (Fri Aug 31 2018 14:12:08 GMT+0000 (Coordinated Universal Time)) +Spawn [level2e,0,0] is 7.9999999 close to a line! >=12 is a must. +Created an instance of level2e (Fri Aug 31 2018 14:12:08 GMT+0000 (Coordinated Universal Time)) +Created an instance of level2s (Fri Aug 31 2018 14:12:08 GMT+0000 (Coordinated Universal Time)) +Spawn [level2w,0,0] is 7.9999999 close to a line! >=12 is a must. +Created an instance of level2w (Fri Aug 31 2018 14:12:08 GMT+0000 (Coordinated Universal Time)) +Created an instance of level3 (Fri Aug 31 2018 14:12:09 GMT+0000 (Coordinated Universal Time)) +Created an instance of level4 (Fri Aug 31 2018 14:12:09 GMT+0000 (Coordinated Universal Time)) +Calculations took: 19068ms +Main loop took 25ms (Fri Aug 31 2018 14:12:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Business" (Fri Aug 31 2018 14:12:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtod" (Fri Aug 31 2018 14:12:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Protector" (Fri Aug 31 2018 14:12:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Lootbot" (Fri Aug 31 2018 14:12:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Wizard" (Fri Aug 31 2018 14:12:19 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Fri Aug 31 2018 14:12:20 GMT+0000 (Coordinated Universal Time)) +Abrupt stop for 0x00 (Fri Aug 31 2018 14:12:20 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Fri Aug 31 2018 14:12:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Fri Aug 31 2018 14:12:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Death" (Fri Aug 31 2018 14:12:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Fri Aug 31 2018 14:12:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Fri Aug 31 2018 14:12:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Fri Aug 31 2018 14:12:28 GMT+0000 (Coordinated Universal Time)) +start_character: "MuppPriest" (Fri Aug 31 2018 14:12:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Mupp" (Fri Aug 31 2018 14:12:29 GMT+0000 (Coordinated Universal Time)) +Main loop took 23ms (Fri Aug 31 2018 14:12:35 GMT+0000 (Coordinated Universal Time)) +start_character: "MuppArch" (Fri Aug 31 2018 14:12:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: a8NHduSnRCM7zJ2cAAAD Business Calls: 43 (Fri Aug 31 2018 14:12:40 GMT+0000 (Coordinated Universal Time)) +stop_character: Business owner: 5752754626625536 bank: false (Fri Aug 31 2018 14:12:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Ploob" (Fri Aug 31 2018 14:12:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Fri Aug 31 2018 14:12:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: LUtDzXDk1pTzjGlaAAAM Pluu Calls: 3 (Fri Aug 31 2018 14:12:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Fri Aug 31 2018 14:12:45 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Fri Aug 31 2018 14:12:45 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Fri Aug 31 2018 14:13:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Fri Aug 31 2018 14:13:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Business" (Fri Aug 31 2018 14:17:39 GMT+0000 (Coordinated Universal Time)) +#C cheater: 0x00 current: 0[-15.215451749372386,-15.215451749372386] going: undefined[999999999999999,999999999999999] at tavern (Fri Aug 31 2018 14:25:10 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Fri Aug 31 2018 14:25:39 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Fri Aug 31 2018 14:25:42 GMT+0000 (Coordinated Universal Time)) +#C cheater: 0x00 current: 0[-39.542719533126615,-39.542719533126615] going: undefined[999999999999999,999999999999999] at tavern (Fri Aug 31 2018 14:27:00 GMT+0000 (Coordinated Universal Time)) +start_character: "0x07" (Fri Aug 31 2018 14:27:01 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x07 owner: 5457622628040704 (Fri Aug 31 2018 14:27:09 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x07 owner: 5457622628040704 (Fri Aug 31 2018 14:27:15 GMT+0000 (Coordinated Universal Time)) +start_character: "Oragon" (Fri Aug 31 2018 14:32:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fmj_OxgTyAH2tZezAAAd Oragon Calls: 200 (Fri Aug 31 2018 14:38:41 GMT+0000 (Coordinated Universal Time)) +stop_character: Oragon owner: 6243983994912768 bank: false (Fri Aug 31 2018 14:38:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Fri Aug 31 2018 14:42:15 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Fri Aug 31 2018 14:42:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Fri Aug 31 2018 14:42:20 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Fri Aug 31 2018 14:42:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 14:42:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: i5lfb_PQObhHtwBKAAAi Troll Calls: 5 (Fri Aug 31 2018 14:42:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 14:42:34 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Fri Aug 31 2018 14:42:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 14:43:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ew8fotMaT2QW5w2uAAAm Troll Calls: 20 (Fri Aug 31 2018 14:43:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 14:43:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yrpCjnMFy8-SmeZyAAAI Lootbot Calls: 41779 (Fri Aug 31 2018 14:43:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0M3WUBvUs2_80zlSAAAf Curse Calls: 562 (Fri Aug 31 2018 14:43:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vRO1Sh_gl_i6t7LdAAAg Sinstrite Calls: 559 (Fri Aug 31 2018 14:43:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Eh1BwT-bcVsfRs-2AAAh Shield Calls: 538 (Fri Aug 31 2018 14:43:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Fri Aug 31 2018 14:43:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Fri Aug 31 2018 14:43:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Fri Aug 31 2018 14:43:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Lootbot owner: 5145329831772160 bank: false (Fri Aug 31 2018 14:43:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Fri Aug 31 2018 14:44:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Fri Aug 31 2018 14:44:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Lootbot" (Fri Aug 31 2018 14:44:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Fri Aug 31 2018 14:44:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 14:44:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 1kEYG1gC6zmMsNNcAAAr Troll Calls: 18 (Fri Aug 31 2018 14:44:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 14:44:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: hoyGVQsr-g8aXErjAAAc 0x07 Calls: 271 (Fri Aug 31 2018 14:45:03 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x07 owner: 5457622628040704 bank: false (Fri Aug 31 2018 14:45:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: lXEk41e1D_ZCk0zTAAAq Shield Calls: 269 (Fri Aug 31 2018 14:45:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: pPeAQUH7sz9qJ3bBAAAp Sinstrite Calls: 416 (Fri Aug 31 2018 14:45:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 95tAlLMmVU0LKB0KAAAn Curse Calls: 313 (Fri Aug 31 2018 14:45:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Fri Aug 31 2018 14:45:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Fri Aug 31 2018 14:45:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Fri Aug 31 2018 14:45:16 GMT+0000 (Coordinated Universal Time)) +start_character: "Laxus" (Fri Aug 31 2018 14:51:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Bs7goDCUnuBBVO6vAAAu Laxus Calls: 227 (Fri Aug 31 2018 14:52:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Laxus owner: 5179846254657536 bank: false (Fri Aug 31 2018 14:52:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Rocky" (Fri Aug 31 2018 14:54:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YBRud-8bIlnoy3OpAAAv Rocky Calls: 102 (Fri Aug 31 2018 14:55:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Rocky owner: 4832405143683072 bank: false (Fri Aug 31 2018 14:55:09 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3KGpw3HtMNmp0mNUAAAZ 0x00 Calls: 3067 (Fri Aug 31 2018 14:57:32 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Fri Aug 31 2018 14:57:32 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Fri Aug 31 2018 14:57:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Rocky" (Fri Aug 31 2018 14:59:08 GMT+0000 (Coordinated Universal Time)) +mount_user: Rocky owner: 4832405143683072 (Fri Aug 31 2018 14:59:16 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Rocky owner: 4832405143683072 (Fri Aug 31 2018 15:00:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OXwnGKKHef3Qs6uDAAAw 0x00 Calls: 454 (Fri Aug 31 2018 15:02:39 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Fri Aug 31 2018 15:02:39 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Fri Aug 31 2018 15:05:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: sooQYqyA7pxZAdrWAAAQ Foaly Calls: 5 (Fri Aug 31 2018 15:11:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Fri Aug 31 2018 15:11:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Fri Aug 31 2018 15:12:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Fri Aug 31 2018 15:12:51 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Fri Aug 31 2018 15:13:34 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Fri Aug 31 2018 15:14:58 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Fri Aug 31 2018 15:15:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: aecsoCPairF1fQDHAAA8 SweetPea Calls: 83 (Fri Aug 31 2018 15:17:32 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Fri Aug 31 2018 15:17:32 GMT+0000 (Coordinated Universal Time)) +start_character: "random" (Fri Aug 31 2018 15:17:46 GMT+0000 (Coordinated Universal Time)) +start_character: "Chara" (Fri Aug 31 2018 15:18:08 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Fri Aug 31 2018 15:18:21 GMT+0000 (Coordinated Universal Time)) +start_character: "NameIsUsed" (Fri Aug 31 2018 15:18:29 GMT+0000 (Coordinated Universal Time)) +mount_user: Rocky owner: 4832405143683072 (Fri Aug 31 2018 15:18:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Sqwoq8oP1JOoQBMCAAAx Rocky Calls: 353 (Fri Aug 31 2018 15:18:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Rocky owner: 4832405143683072 bank: true (Fri Aug 31 2018 15:18:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: i64HxQD9r0mV8tABAABU random Calls: 375 (Fri Aug 31 2018 15:24:23 GMT+0000 (Coordinated Universal Time)) +stop_character: random owner: 5106310615924736 bank: false (Fri Aug 31 2018 15:24:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vLy4ns2vFUeJhY8uAABb NameIsUsed Calls: 381 (Fri Aug 31 2018 15:24:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7ZufNDZQ7g1d_a72AABY Chara Calls: 480 (Fri Aug 31 2018 15:24:24 GMT+0000 (Coordinated Universal Time)) +stop_character: NameIsUsed owner: 5106310615924736 bank: false (Fri Aug 31 2018 15:24:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Chara owner: 5106310615924736 bank: false (Fri Aug 31 2018 15:24:24 GMT+0000 (Coordinated Universal Time)) +start_character: "Chara" (Fri Aug 31 2018 15:27:21 GMT+0000 (Coordinated Universal Time)) +start_character: "random" (Fri Aug 31 2018 15:27:22 GMT+0000 (Coordinated Universal Time)) +start_character: "NameIsUsed" (Fri Aug 31 2018 15:27:28 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Fri Aug 31 2018 15:30:24 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Fri Aug 31 2018 15:30:28 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Fri Aug 31 2018 15:30:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 15:30:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: umvaa26lKkUqeGiuAACm Troll Calls: 23 (Fri Aug 31 2018 15:30:49 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 15:30:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 15:31:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vLFARbtobvmuAGhpAACu Troll Calls: 14 (Fri Aug 31 2018 15:31:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 15:31:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: AMeHqjVPZJI9oKMIAAAo Lootbot Calls: 58818 (Fri Aug 31 2018 15:31:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6Agre1IHrdUoQFkDAACh Curse Calls: 477 (Fri Aug 31 2018 15:31:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: lZ5wdtKvkx0TWtbAAACi Sinstrite Calls: 463 (Fri Aug 31 2018 15:31:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: W9oi-I-z4LKRbOCoAACj Shield Calls: 447 (Fri Aug 31 2018 15:31:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Lootbot owner: 5145329831772160 bank: false (Fri Aug 31 2018 15:31:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Fri Aug 31 2018 15:31:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Fri Aug 31 2018 15:31:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Fri Aug 31 2018 15:31:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Fri Aug 31 2018 15:32:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Fri Aug 31 2018 15:32:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Lootbot" (Fri Aug 31 2018 15:32:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Fri Aug 31 2018 15:32:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: nKiDRWlegGRpH_n4AAC6 Sinstrite Calls: 134 (Fri Aug 31 2018 15:33:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tchLIoQGh2TITvZHAAC1 Curse Calls: 170 (Fri Aug 31 2018 15:33:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -glSLeuAINMi6qOaAAC5 Shield Calls: 150 (Fri Aug 31 2018 15:33:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Fri Aug 31 2018 15:33:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Fri Aug 31 2018 15:33:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Fri Aug 31 2018 15:33:09 GMT+0000 (Coordinated Universal Time)) +start_character: "batman43549" (Fri Aug 31 2018 15:34:28 GMT+0000 (Coordinated Universal Time)) +start_character: "Buttercup" (Fri Aug 31 2018 15:34:30 GMT+0000 (Coordinated Universal Time)) +start_character: "riverdusty" (Fri Aug 31 2018 15:34:44 GMT+0000 (Coordinated Universal Time)) +start_character: "LambChop" (Fri Aug 31 2018 15:34:51 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Fri Aug 31 2018 15:35:43 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Lootbot (Fri Aug 31 2018 15:36:09 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: S0DhQvhtHRl1jd1HAAC3 Lootbot Calls: 5059 (Fri Aug 31 2018 15:36:09 GMT+0000 (Coordinated Universal Time)) +stop_character: Lootbot owner: 5145329831772160 bank: true (Fri Aug 31 2018 15:36:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Lootbot" (Fri Aug 31 2018 15:36:16 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Fri Aug 31 2018 15:36:26 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Fri Aug 31 2018 15:36:56 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Fri Aug 31 2018 15:36:59 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Fri Aug 31 2018 15:37:15 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonbeck" (Fri Aug 31 2018 15:37:15 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Fri Aug 31 2018 15:38:03 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Fri Aug 31 2018 15:38:09 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Fri Aug 31 2018 15:38:23 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Fri Aug 31 2018 15:38:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: z_07WNDvWSvVQymBAADI riverdusty Calls: 156 (Fri Aug 31 2018 15:39:09 GMT+0000 (Coordinated Universal Time)) +stop_character: riverdusty owner: 5736224816889856 bank: false (Fri Aug 31 2018 15:39:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: D5SQ6I-_IFjOA5BzAADJ LambChop Calls: 339 (Fri Aug 31 2018 15:39:11 GMT+0000 (Coordinated Universal Time)) +stop_character: LambChop owner: 5736224816889856 bank: false (Fri Aug 31 2018 15:39:11 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7bs6QKdx2EXJyblRAADF Buttercup Calls: 575 (Fri Aug 31 2018 15:39:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Buttercup owner: 5736224816889856 bank: false (Fri Aug 31 2018 15:39:12 GMT+0000 (Coordinated Universal Time)) +mount_user: batman43549 owner: 5307438548910080 (Fri Aug 31 2018 15:39:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: snxGb3yn31ksV1_6AACN random Calls: 1054 (Fri Aug 31 2018 15:39:58 GMT+0000 (Coordinated Universal Time)) +stop_character: random owner: 5106310615924736 bank: false (Fri Aug 31 2018 15:39:59 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: batman43549 owner: 5307438548910080 (Fri Aug 31 2018 15:40:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IO7Kceb7dQZJ_yZ0AADD batman43549 Calls: 616 (Fri Aug 31 2018 15:40:20 GMT+0000 (Coordinated Universal Time)) +stop_character: batman43549 owner: 5307438548910080 bank: false (Fri Aug 31 2018 15:40:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: S3GoM70OQGNi76Q4AABZ SweetPea Calls: 103 (Fri Aug 31 2018 15:45:21 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Fri Aug 31 2018 15:45:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: JaaTLnio-Stemp0JAADY Jonbeck Calls: 357 (Fri Aug 31 2018 15:45:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonbeck owner: 4717337833897984 bank: false (Fri Aug 31 2018 15:45:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0RXixH_pHf7ob7mzAACQ Chara Calls: 1104 (Fri Aug 31 2018 15:45:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: k0bgpj0urQg48eKJAACP NameIsUsed Calls: 1239 (Fri Aug 31 2018 15:45:42 GMT+0000 (Coordinated Universal Time)) +stop_character: Chara owner: 5106310615924736 bank: false (Fri Aug 31 2018 15:45:42 GMT+0000 (Coordinated Universal Time)) +stop_character: NameIsUsed owner: 5106310615924736 bank: false (Fri Aug 31 2018 15:45:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Jadestone" (Fri Aug 31 2018 15:47:35 GMT+0000 (Coordinated Universal Time)) +start_character: "SansSupport" (Fri Aug 31 2018 15:47:58 GMT+0000 (Coordinated Universal Time)) +start_character: "POOF" (Fri Aug 31 2018 15:50:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: z3nbByTlQ3QP5ALEAAEV SansSupport Calls: 2888 (Fri Aug 31 2018 15:57:43 GMT+0000 (Coordinated Universal Time)) +stop_character: SansSupport owner: 6609080732876800 bank: false (Fri Aug 31 2018 15:57:43 GMT+0000 (Coordinated Universal Time)) +start_character: "SansSupport" (Fri Aug 31 2018 15:57:59 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Fri Aug 31 2018 15:58:59 GMT+0000 (Coordinated Universal Time)) +mount_user: MOBSans owner: 6609080732876800 (Fri Aug 31 2018 16:01:44 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MOBSans owner: 6609080732876800 (Fri Aug 31 2018 16:02:27 GMT+0000 (Coordinated Universal Time)) +mount_user: MOBSans owner: 6609080732876800 (Fri Aug 31 2018 16:03:19 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MOBSans owner: 6609080732876800 (Fri Aug 31 2018 16:03:31 GMT+0000 (Coordinated Universal Time)) +mount_user: MOBSans owner: 6609080732876800 (Fri Aug 31 2018 16:04:52 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MOBSans owner: 6609080732876800 (Fri Aug 31 2018 16:05:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZFCGg23L-7FtKb7DAAAE Trexnamedtod Calls: 28 (Fri Aug 31 2018 16:06:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZSNDjnSFych1Qg1EAAAT Trexnamedtom Calls: 87505 (Fri Aug 31 2018 16:06:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NWVMdo2_O_Wlxo9bAAAO Trexnamedtut Calls: 86914 (Fri Aug 31 2018 16:06:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: K7-osI_SbbknIhCkAAAP Trexnamedted Calls: 87114 (Fri Aug 31 2018 16:06:41 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:06:42 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:06:42 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:06:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtod owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:06:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Fri Aug 31 2018 16:06:59 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Fri Aug 31 2018 16:07:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Fri Aug 31 2018 16:07:07 GMT+0000 (Coordinated Universal Time)) +mount_user: MOBSans owner: 6609080732876800 (Fri Aug 31 2018 16:08:40 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MOBSans owner: 6609080732876800 (Fri Aug 31 2018 16:08:49 GMT+0000 (Coordinated Universal Time)) +mount_user: MOBSans owner: 6609080732876800 (Fri Aug 31 2018 16:10:04 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MOBSans owner: 6609080732876800 (Fri Aug 31 2018 16:10:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 1TM0WZNZwKGizw5VAAA2 Cozi Calls: 64085 (Fri Aug 31 2018 16:12:44 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Fri Aug 31 2018 16:12:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Fri Aug 31 2018 16:12:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Chara" (Fri Aug 31 2018 16:12:53 GMT+0000 (Coordinated Universal Time)) +start_character: "NameIsUsed" (Fri Aug 31 2018 16:12:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SfrG4gLZ5WOh6tI3AAGD Trexnamedtom Calls: 5726 (Fri Aug 31 2018 16:16:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:16:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wk2dSBcQvkYrQdaMAAGC Trexnamedted Calls: 7250 (Fri Aug 31 2018 16:16:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:16:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rZP8o6i099hciGxGAAGA Trexnamedtut Calls: 7242 (Fri Aug 31 2018 16:16:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:16:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtod" (Fri Aug 31 2018 16:16:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Fri Aug 31 2018 16:16:39 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Fri Aug 31 2018 16:16:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Fri Aug 31 2018 16:16:42 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Fri Aug 31 2018 16:17:02 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Fri Aug 31 2018 16:17:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: gy3qWIznDpzm6oS6AAG- Trexnamedted Calls: 1103 (Fri Aug 31 2018 16:17:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: baDGx8pRy0JNAlD7AAHA Trexnamedtom Calls: 1075 (Fri Aug 31 2018 16:17:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: kSOGKKIcrICaoYqpAAG_ Trexnamedtut Calls: 1076 (Fri Aug 31 2018 16:17:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: qDaa6zI8COTJqdsWAAG9 Trexnamedtod Calls: 7 (Fri Aug 31 2018 16:17:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:17:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:17:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtod owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:18:00 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:18:00 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtes" (Fri Aug 31 2018 16:18:06 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Fri Aug 31 2018 16:18:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Fri Aug 31 2018 16:18:27 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Fri Aug 31 2018 16:18:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Fri Aug 31 2018 16:18:33 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Fri Aug 31 2018 16:18:39 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 16:18:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: H57wJgPK8YtDasxJAAHR Troll Calls: 20 (Fri Aug 31 2018 16:18:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 16:18:57 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Fri Aug 31 2018 16:19:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: RxePe5xxQarvHOVRAAHO Sinstrite Calls: 307 (Fri Aug 31 2018 16:19:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: utwKIfz0z5aBbMI3AAHN Shield Calls: 315 (Fri Aug 31 2018 16:19:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: RkMC3scLlKBp_twsAAHM Curse Calls: 332 (Fri Aug 31 2018 16:19:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Fri Aug 31 2018 16:19:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Fri Aug 31 2018 16:19:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Fri Aug 31 2018 16:19:14 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtes owner: 5209159389675520 (Fri Aug 31 2018 16:19:36 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: z_bxCbwjYwIVOSgLAAHJ Trexnamedtes Calls: 28 (Fri Aug 31 2018 16:20:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtes owner: 5209159389675520 bank: true (Fri Aug 31 2018 16:20:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Fri Aug 31 2018 16:21:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6-Klfypu9uYuFHd5AAFV MOBSans Calls: 1969 (Fri Aug 31 2018 16:21:47 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Fri Aug 31 2018 16:21:47 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtom owner: 5209159389675520 (Fri Aug 31 2018 16:21:50 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Fri Aug 31 2018 16:21:54 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtom owner: 5209159389675520 (Fri Aug 31 2018 16:22:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Fri Aug 31 2018 16:23:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Fri Aug 31 2018 16:23:44 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Fri Aug 31 2018 16:24:42 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Fri Aug 31 2018 16:24:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 002OhIHOJVpgbwH_AAHd Trexnamedtom Calls: 1677 (Fri Aug 31 2018 16:25:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:25:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ah_3lnue70amWYwkAAHt Trexnamedted Calls: 1377 (Fri Aug 31 2018 16:25:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:25:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: N7DR---hm-58igWeAAHu Trexnamedtut Calls: 1224 (Fri Aug 31 2018 16:25:20 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:25:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtod" (Fri Aug 31 2018 16:25:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Fri Aug 31 2018 16:25:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Fri Aug 31 2018 16:25:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Fri Aug 31 2018 16:25:33 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Fri Aug 31 2018 16:25:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0wCf52wvQppUT0twAAGm Chara Calls: 1184 (Fri Aug 31 2018 16:27:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SYielmJE2t-NpsvoAAGn NameIsUsed Calls: 828 (Fri Aug 31 2018 16:27:29 GMT+0000 (Coordinated Universal Time)) +stop_character: NameIsUsed owner: 5106310615924736 bank: false (Fri Aug 31 2018 16:27:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Chara owner: 5106310615924736 bank: false (Fri Aug 31 2018 16:27:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5h6t5Jr7YtNAHxTNAAAy 0x00 Calls: 3307 (Fri Aug 31 2018 16:29:31 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Fri Aug 31 2018 16:29:31 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Fri Aug 31 2018 16:30:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KZXTDySqU--gnGQUAAHk MOBSans Calls: 775 (Fri Aug 31 2018 16:31:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: seqqCdda1S5XLt6TAAFO SansSupport Calls: 23130 (Fri Aug 31 2018 16:31:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: _6Ryg1gPibZlrQe2AAEj POOF Calls: 11215 (Fri Aug 31 2018 16:31:30 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Fri Aug 31 2018 16:31:31 GMT+0000 (Coordinated Universal Time)) +stop_character: SansSupport owner: 6609080732876800 bank: false (Fri Aug 31 2018 16:31:31 GMT+0000 (Coordinated Universal Time)) +stop_character: POOF owner: 6609080732876800 bank: false (Fri Aug 31 2018 16:31:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 80TC5O0xhAOOv_ooAAES Jadestone Calls: 3467 (Fri Aug 31 2018 16:32:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Jadestone owner: 6434714321682432 bank: false (Fri Aug 31 2018 16:32:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Chara" (Fri Aug 31 2018 16:33:57 GMT+0000 (Coordinated Universal Time)) +start_character: "NameIsUsed" (Fri Aug 31 2018 16:34:03 GMT+0000 (Coordinated Universal Time)) +start_character: "SansSupport" (Fri Aug 31 2018 16:34:28 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Fri Aug 31 2018 16:34:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Carolina" (Fri Aug 31 2018 16:35:07 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtod owner: 5209159389675520 (Fri Aug 31 2018 16:35:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: F95CAhVuI2JEYxrwAAH8 Trexnamedted Calls: 8066 (Fri Aug 31 2018 16:36:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ef9PgUNttlWtswrVAAH- Trexnamedtut Calls: 7980 (Fri Aug 31 2018 16:36:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: WL33AnQa_Y7LQOPAAAH9 Trexnamedtom Calls: 7965 (Fri Aug 31 2018 16:36:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: hV7sCraiF5j9k2qPAAH7 Trexnamedtod Calls: 469 (Fri Aug 31 2018 16:36:00 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:36:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:36:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtod owner: 5209159389675520 bank: true (Fri Aug 31 2018 16:36:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:36:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Fri Aug 31 2018 16:36:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Fri Aug 31 2018 16:36:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Fri Aug 31 2018 16:36:40 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtom owner: 5209159389675520 (Fri Aug 31 2018 16:36:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: oE2N6t0Jl5WteZo4AAIu Chara Calls: 224 (Fri Aug 31 2018 16:37:10 GMT+0000 (Coordinated Universal Time)) +stop_character: Chara owner: 5106310615924736 bank: false (Fri Aug 31 2018 16:37:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: BTK06Mu-BB-J94VyAAIv NameIsUsed Calls: 190 (Fri Aug 31 2018 16:37:11 GMT+0000 (Coordinated Universal Time)) +stop_character: NameIsUsed owner: 5106310615924736 bank: false (Fri Aug 31 2018 16:37:11 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedted owner: 5209159389675520 (Fri Aug 31 2018 16:37:17 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Trexnamedted in-bank: Trexnamedtom (Fri Aug 31 2018 16:37:17 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtom owner: 5209159389675520 (Fri Aug 31 2018 16:37:18 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedted owner: 5209159389675520 (Fri Aug 31 2018 16:37:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zOIgF7LkAQrzRR8kAAAb Business Calls: 119 (Fri Aug 31 2018 16:37:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Business owner: 5752754626625536 bank: false (Fri Aug 31 2018 16:37:28 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtut owner: 5209159389675520 (Fri Aug 31 2018 16:37:36 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Trexnamedtut in-bank: Trexnamedted (Fri Aug 31 2018 16:37:36 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedted owner: 5209159389675520 (Fri Aug 31 2018 16:37:40 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtut owner: 5209159389675520 (Fri Aug 31 2018 16:37:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vlXNhBLWENWEt3AaAAI1 MOBSans Calls: 174 (Fri Aug 31 2018 16:37:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 16:37:42 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Fri Aug 31 2018 16:37:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Fri Aug 31 2018 16:37:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 4SO8QCD_suvEo4p5AAI_ Trexnamedtom Calls: 86 (Fri Aug 31 2018 16:38:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:38:01 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtut owner: 5209159389675520 (Fri Aug 31 2018 16:38:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonnyboy777" (Fri Aug 31 2018 16:38:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: sAZQgoIYMVyPADwlAAJA Trexnamedted Calls: 70 (Fri Aug 31 2018 16:38:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:38:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IwV7L6ujk_DpdbRdAAJD Trexnamedtut Calls: 82 (Fri Aug 31 2018 16:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Fri Aug 31 2018 16:38:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtod" (Fri Aug 31 2018 16:38:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Fri Aug 31 2018 16:38:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Fri Aug 31 2018 16:38:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Fri Aug 31 2018 16:38:47 GMT+0000 (Coordinated Universal Time)) +mount_user: Carolina owner: 6609080732876800 (Fri Aug 31 2018 16:39:23 GMT+0000 (Coordinated Universal Time)) +mount_user: Jonnyboy777 owner: 4717337833897984 (Fri Aug 31 2018 16:39:33 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Carolina owner: 6609080732876800 (Fri Aug 31 2018 16:40:01 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Jonnyboy777 owner: 4717337833897984 (Fri Aug 31 2018 16:40:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonbeck" (Fri Aug 31 2018 16:42:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -SdPZHYqMnFmTqqgAAJp Jonbeck Calls: 4 (Fri Aug 31 2018 16:42:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonbeck owner: 4717337833897984 bank: false (Fri Aug 31 2018 16:42:02 GMT+0000 (Coordinated Universal Time)) +start_character: "JonBeck777" (Fri Aug 31 2018 16:42:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: B3VEiYkGl9A3UuJcAAJq JonBeck777 Calls: 24 (Fri Aug 31 2018 16:42:22 GMT+0000 (Coordinated Universal Time)) +stop_character: JonBeck777 owner: 4717337833897984 bank: false (Fri Aug 31 2018 16:42:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonbeck" (Fri Aug 31 2018 16:42:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: XpWjJ4vJ3lUwYa9WAAJw Jonbeck Calls: 3 (Fri Aug 31 2018 16:42:48 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonbeck owner: 4717337833897984 bank: false (Fri Aug 31 2018 16:42:49 GMT+0000 (Coordinated Universal Time)) +start_character: "JonBeck777" (Fri Aug 31 2018 16:43:09 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: kTGRzNldqAt_gldOAAJx JonBeck777 Calls: 5 (Fri Aug 31 2018 16:43:09 GMT+0000 (Coordinated Universal Time)) +stop_character: JonBeck777 owner: 4717337833897984 bank: false (Fri Aug 31 2018 16:43:10 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonbeck" (Fri Aug 31 2018 16:43:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: H1Fj5ZJiq8wBbWteAAJ3 Jonbeck Calls: 3 (Fri Aug 31 2018 16:43:42 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonbeck owner: 4717337833897984 bank: false (Fri Aug 31 2018 16:43:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonbeck" (Fri Aug 31 2018 16:44:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: iJbws2NJ-ByGg7O6AAJ- Jonbeck Calls: 3 (Fri Aug 31 2018 16:44:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonbeck owner: 4717337833897984 bank: false (Fri Aug 31 2018 16:44:31 GMT+0000 (Coordinated Universal Time)) +start_character: "lissandra" (Fri Aug 31 2018 16:44:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: iTn6oJxmNJEuYMHZAAKA lissandra Calls: 12 (Fri Aug 31 2018 16:45:10 GMT+0000 (Coordinated Universal Time)) +stop_character: lissandra owner: 5793534377459712 bank: false (Fri Aug 31 2018 16:45:11 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonbeck" (Fri Aug 31 2018 16:45:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TBPBqCZBXMDm7LH6AAKG Jonbeck Calls: 3 (Fri Aug 31 2018 16:45:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonbeck owner: 4717337833897984 bank: false (Fri Aug 31 2018 16:45:16 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonbeck" (Fri Aug 31 2018 16:46:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: FTHmgRPaPuQiCswLAAKM Jonbeck Calls: 3 (Fri Aug 31 2018 16:46:04 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonbeck owner: 4717337833897984 bank: false (Fri Aug 31 2018 16:46:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonbeck" (Fri Aug 31 2018 16:46:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: cUOP1Fhp-a45zDJZAAKS Jonbeck Calls: 3 (Fri Aug 31 2018 16:46:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonbeck owner: 4717337833897984 bank: false (Fri Aug 31 2018 16:46:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SQunUxcgP0iGH24uAAIy SansSupport Calls: 1790 (Fri Aug 31 2018 16:47:35 GMT+0000 (Coordinated Universal Time)) +stop_character: SansSupport owner: 6609080732876800 bank: false (Fri Aug 31 2018 16:47:35 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: nRAO0vKWFI8omYOwAAI2 Carolina Calls: 174 (Fri Aug 31 2018 16:47:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Carolina owner: 6609080732876800 bank: false (Fri Aug 31 2018 16:47:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonbeck" (Fri Aug 31 2018 16:47:39 GMT+0000 (Coordinated Universal Time)) +start_character: "Chara" (Fri Aug 31 2018 16:49:39 GMT+0000 (Coordinated Universal Time)) +start_character: "NameIsUsed" (Fri Aug 31 2018 16:49:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: m_a6vc49OnXx_ba-AAKm NameIsUsed Calls: 208 (Fri Aug 31 2018 16:52:25 GMT+0000 (Coordinated Universal Time)) +stop_character: NameIsUsed owner: 5106310615924736 bank: false (Fri Aug 31 2018 16:52:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: nXn19rVfhC9mQWUmAAKk Chara Calls: 349 (Fri Aug 31 2018 16:54:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Chara owner: 5106310615924736 bank: false (Fri Aug 31 2018 16:54:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Buttercup" (Fri Aug 31 2018 16:56:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZdZOT6BbFY58RTjTAALO Buttercup Calls: 11 (Fri Aug 31 2018 16:56:41 GMT+0000 (Coordinated Universal Time)) +stop_character: Buttercup owner: 5736224816889856 bank: false (Fri Aug 31 2018 16:56:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Chara" (Fri Aug 31 2018 16:57:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Wasp" (Fri Aug 31 2018 16:58:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VF6xVB3ILx7QaTKdAAJO Jonnyboy777 Calls: 100 (Fri Aug 31 2018 17:03:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonnyboy777 owner: 4717337833897984 bank: false (Fri Aug 31 2018 17:03:09 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Zg7GTW2ZrfjoOxFJAAKY Jonbeck Calls: 130 (Fri Aug 31 2018 17:03:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonbeck owner: 4717337833897984 bank: false (Fri Aug 31 2018 17:03:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6cTnsIOpbWkNnKL_AALW Chara Calls: 465 (Fri Aug 31 2018 17:04:11 GMT+0000 (Coordinated Universal Time)) +stop_character: Chara owner: 5106310615924736 bank: false (Fri Aug 31 2018 17:04:11 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Fri Aug 31 2018 17:04:25 GMT+0000 (Coordinated Universal Time)) +start_character: "NameIsUsed" (Fri Aug 31 2018 17:04:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Fri Aug 31 2018 17:04:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Fri Aug 31 2018 17:04:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: idwF2Xiwtgh3S4RpAAMA Shield Calls: 234 (Fri Aug 31 2018 17:04:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: HI1ySq_hovpV2DkRAAL- Curse Calls: 221 (Fri Aug 31 2018 17:04:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7X-2jid3-y4rdgTNAAL_ Sinstrite Calls: 335 (Fri Aug 31 2018 17:04:56 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Fri Aug 31 2018 17:04:56 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Fri Aug 31 2018 17:04:56 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Fri Aug 31 2018 17:04:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Fri Aug 31 2018 17:05:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Fri Aug 31 2018 17:05:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Fri Aug 31 2018 17:05:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 17:05:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rCP8pADqeuwzSXNbAAMM Troll Calls: 78 (Fri Aug 31 2018 17:05:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 17:05:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yxY8lRiZVH72fEMEAAMH Shield Calls: 540 (Fri Aug 31 2018 17:06:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: hIXyaDRa9JrTepe2AAMG Sinstrite Calls: 519 (Fri Aug 31 2018 17:06:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mozodWx2BP7VpCzoAAMD Curse Calls: 544 (Fri Aug 31 2018 17:06:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Fri Aug 31 2018 17:06:25 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Fri Aug 31 2018 17:06:25 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Fri Aug 31 2018 17:06:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonbeck" (Fri Aug 31 2018 17:06:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonnyboy777" (Fri Aug 31 2018 17:06:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: HoWyGiXJfceABpqSAAMS Jonbeck Calls: 52 (Fri Aug 31 2018 17:08:00 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonbeck owner: 4717337833897984 bank: false (Fri Aug 31 2018 17:08:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PAZYWfZ4s3_1oCrDAAMT Jonnyboy777 Calls: 6 (Fri Aug 31 2018 17:08:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonnyboy777 owner: 4717337833897984 bank: false (Fri Aug 31 2018 17:08:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Ej20JwrbcP7kV5hOAAJV Trexnamedted Calls: 23178 (Fri Aug 31 2018 17:08:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mDBmN_h5m-TS4k7nAAJU Trexnamedtom Calls: 22990 (Fri Aug 31 2018 17:08:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZWU-5ScdpRZOI1MCAAJW Trexnamedtut Calls: 23022 (Fri Aug 31 2018 17:08:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 8QEfk3Dga8QwyesNAAJT Trexnamedtod Calls: 90 (Fri Aug 31 2018 17:08:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtod owner: 5209159389675520 bank: false (Fri Aug 31 2018 17:08:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Fri Aug 31 2018 17:08:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Fri Aug 31 2018 17:08:55 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Fri Aug 31 2018 17:08:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Fri Aug 31 2018 17:08:59 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Fri Aug 31 2018 17:09:28 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Fri Aug 31 2018 17:09:50 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonbeck" (Fri Aug 31 2018 17:09:50 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 17:09:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: e6UG_v13YmIVv854AAJK Scythe Calls: 71034 (Fri Aug 31 2018 17:09:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 17:09:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: gEpnWou8vdlVySYOAAJN Silent Calls: 24341 (Fri Aug 31 2018 17:09:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Fri Aug 31 2018 17:09:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonnyboy777" (Fri Aug 31 2018 17:09:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtom owner: 5209159389675520 (Fri Aug 31 2018 17:10:08 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtom owner: 5209159389675520 (Fri Aug 31 2018 17:10:19 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtut owner: 5209159389675520 (Fri Aug 31 2018 17:10:25 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtut owner: 5209159389675520 (Fri Aug 31 2018 17:10:37 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedted owner: 5209159389675520 (Fri Aug 31 2018 17:10:46 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedted owner: 5209159389675520 (Fri Aug 31 2018 17:11:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 17:11:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KX12aTyWS1b-XK7iAAMg Trexnamedtom Calls: 176 (Fri Aug 31 2018 17:11:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Fri Aug 31 2018 17:11:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: j9gVNr4YJ8oeunJpAAMk Trexnamedtut Calls: 122 (Fri Aug 31 2018 17:11:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Fri Aug 31 2018 17:11:15 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Fri Aug 31 2018 17:11:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: lW22C93WeCRKhCjjAAMn Trexnamedted Calls: 143 (Fri Aug 31 2018 17:12:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Fri Aug 31 2018 17:12:27 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtod" (Fri Aug 31 2018 17:12:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Fri Aug 31 2018 17:12:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Fri Aug 31 2018 17:12:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Fri Aug 31 2018 17:12:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6Avff6oklnTyz3UsAAGl Cozi Calls: 64561 (Fri Aug 31 2018 17:12:44 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Fri Aug 31 2018 17:12:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Fri Aug 31 2018 17:12:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fis5gRCH-e9FNHyaAAMp Jonnyboy777 Calls: 7 (Fri Aug 31 2018 17:17:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonnyboy777 owner: 4717337833897984 bank: false (Fri Aug 31 2018 17:17:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vtZARLx0cLVtZAEOAAMm Jonbeck Calls: 178 (Fri Aug 31 2018 17:17:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonbeck owner: 4717337833897984 bank: false (Fri Aug 31 2018 17:17:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonnyboy777" (Fri Aug 31 2018 17:19:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonbeck" (Fri Aug 31 2018 17:19:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -WK2XVsc00fE1J07AAAL Ploob Calls: 8527 (Fri Aug 31 2018 17:19:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VIz6c-4JhxdDV3sCAANB Cozi Calls: 7307 (Fri Aug 31 2018 17:19:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Fri Aug 31 2018 17:19:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Ploob owner: 4572509340958720 bank: false (Fri Aug 31 2018 17:19:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Ploob" (Fri Aug 31 2018 17:19:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 1I2RCE4THpbKe5hdAALV Wasp Calls: 1646 (Fri Aug 31 2018 17:19:35 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0-Uj0BEa5uxmljhhAAL9 NameIsUsed Calls: 1210 (Fri Aug 31 2018 17:19:35 GMT+0000 (Coordinated Universal Time)) +stop_character: NameIsUsed owner: 5106310615924736 bank: false (Fri Aug 31 2018 17:19:35 GMT+0000 (Coordinated Universal Time)) +stop_character: Wasp owner: 5106310615924736 bank: false (Fri Aug 31 2018 17:19:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Fri Aug 31 2018 17:19:52 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtod owner: 5209159389675520 (Fri Aug 31 2018 17:23:30 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtod owner: 5209159389675520 (Fri Aug 31 2018 17:24:52 GMT+0000 (Coordinated Universal Time)) +start_character: "Emerald" (Fri Aug 31 2018 17:37:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: sgm6VBks86vcc0EqAANp Emerald Calls: 5 (Fri Aug 31 2018 17:37:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Emerald owner: 6474009906511872 bank: false (Fri Aug 31 2018 17:37:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Fri Aug 31 2018 17:51:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Fri Aug 31 2018 17:51:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Fri Aug 31 2018 17:51:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2UQLR3i_CMy8rUPSAANk Jonnyboy777 Calls: 58 (Fri Aug 31 2018 17:51:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6rTqHJo_YFor5bubAANj Jonbeck Calls: 285 (Fri Aug 31 2018 17:51:49 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonnyboy777 owner: 4717337833897984 bank: false (Fri Aug 31 2018 17:51:49 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonbeck owner: 4717337833897984 bank: false (Fri Aug 31 2018 17:51:50 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 17:52:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: pu3tCh1zUMIsdScYAANt Troll Calls: 22 (Fri Aug 31 2018 17:52:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 17:52:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 17:52:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 1D-O1I13EN2xVYknAANy Troll Calls: 13 (Fri Aug 31 2018 17:52:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 17:52:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7L6QHMtH6Byg5qVfAANs Shield Calls: 852 (Fri Aug 31 2018 17:53:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OyK4ypdSwoqASNg0AANq Curse Calls: 871 (Fri Aug 31 2018 17:53:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Uf7BpaOL2N3wZL_qAANr Sinstrite Calls: 854 (Fri Aug 31 2018 17:53:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Fri Aug 31 2018 17:53:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Fri Aug 31 2018 17:53:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Fri Aug 31 2018 17:53:24 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 18:01:45 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: i8zaMQqsOnibLm7lAAMx Scythe Calls: 111383 (Fri Aug 31 2018 18:01:45 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 18:01:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7WjWKEI1j1W_fo1AAAM0 Silent Calls: 38455 (Fri Aug 31 2018 18:01:46 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Fri Aug 31 2018 18:01:46 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 18:02:56 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 18:03:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: A5lRTv8I7eC0B-TmAAN0 Scythe Calls: 358 (Fri Aug 31 2018 18:03:05 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 18:03:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 18:04:12 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 18:04:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: hb8Zkp6DpmYJBnaQAAN1 Scythe Calls: 374 (Fri Aug 31 2018 18:04:21 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 18:04:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 18:05:33 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 18:05:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rqHQ1X2NVtqLMzccAAN2 Scythe Calls: 322 (Fri Aug 31 2018 18:05:41 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 18:05:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 18:07:12 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 18:07:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xLjMkPgqsBBJvl7kAAN3 Scythe Calls: 360 (Fri Aug 31 2018 18:07:21 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 18:07:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 18:08:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: eHzRydOnCOthSM1jAAM7 Trexnamedtod Calls: 108 (Fri Aug 31 2018 18:08:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: EESkJ_WD6BEoS7buAAM8 Trexnamedted Calls: 42944 (Fri Aug 31 2018 18:08:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NegUyRQ3jmShNpPIAAM- Trexnamedtut Calls: 42780 (Fri Aug 31 2018 18:08:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zfaR1LC7gyTIpzVPAAM9 Trexnamedtom Calls: 42626 (Fri Aug 31 2018 18:08:46 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Fri Aug 31 2018 18:08:46 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Fri Aug 31 2018 18:08:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtod owner: 5209159389675520 bank: false (Fri Aug 31 2018 18:08:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Fri Aug 31 2018 18:08:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Fri Aug 31 2018 18:08:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Business" (Fri Aug 31 2018 18:19:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fk9M_HE4y1sN2QSoAANo Cozi Calls: 64678 (Fri Aug 31 2018 18:19:35 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Fri Aug 31 2018 18:19:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Fri Aug 31 2018 18:19:40 GMT+0000 (Coordinated Universal Time)) +mount_user: Business owner: 5752754626625536 (Fri Aug 31 2018 18:20:34 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Business owner: 5752754626625536 (Fri Aug 31 2018 18:20:45 GMT+0000 (Coordinated Universal Time)) +mount_user: Business owner: 5752754626625536 (Fri Aug 31 2018 18:22:40 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Business owner: 5752754626625536 (Fri Aug 31 2018 18:23:10 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonnyboy777" (Fri Aug 31 2018 18:27:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Jonbeck" (Fri Aug 31 2018 18:28:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yfgdxAS-MXg15pt7AAOs Jonbeck Calls: 151 (Fri Aug 31 2018 18:38:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonbeck owner: 4717337833897984 bank: false (Fri Aug 31 2018 18:38:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: gtKRtbYGJHwbKTldAAOr Jonnyboy777 Calls: 7 (Fri Aug 31 2018 18:38:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Jonnyboy777 owner: 4717337833897984 bank: false (Fri Aug 31 2018 18:38:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Fri Aug 31 2018 18:38:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Fri Aug 31 2018 18:38:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Fri Aug 31 2018 18:38:28 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 18:38:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uCuGU5n3aJK5qt79AAN4 Scythe Calls: 66264 (Fri Aug 31 2018 18:38:49 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 18:38:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dTjgR2URrzvXKiWLAAN5 Silent Calls: 22872 (Fri Aug 31 2018 18:38:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Fri Aug 31 2018 18:38:50 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 18:39:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OmE655NX7H3PQjxMAAPt Troll Calls: 18 (Fri Aug 31 2018 18:39:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 18:39:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtex" (Fri Aug 31 2018 18:39:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 18:39:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: eWHLm5CqbniBgzr7AAP2 Troll Calls: 14 (Fri Aug 31 2018 18:39:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 18:39:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: gwB_chBf-M2wXZ2RAAPq Shield Calls: 822 (Fri Aug 31 2018 18:40:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wt1GPd-gvyl37Y2zAAPo Sinstrite Calls: 865 (Fri Aug 31 2018 18:40:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6L0K64YvekHm7zPVAAPm Curse Calls: 884 (Fri Aug 31 2018 18:40:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Fri Aug 31 2018 18:40:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Fri Aug 31 2018 18:40:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Fri Aug 31 2018 18:40:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 18:44:07 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 18:44:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: I5cwsLeVQxYJGFIqAAQP Scythe Calls: 398 (Fri Aug 31 2018 18:44:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 18:44:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 18:54:05 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 18:54:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zdtO4apI4R-aq6FLAARG Scythe Calls: 310 (Fri Aug 31 2018 18:54:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 18:54:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 18:55:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Fri Aug 31 2018 18:55:44 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 18:59:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2dQ9tR_0-nEj5Gv9AARP Scythe Calls: 7839 (Fri Aug 31 2018 18:59:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 18:59:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mhxuhCAKBb0FnooCAARR Silent Calls: 2519 (Fri Aug 31 2018 18:59:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Fri Aug 31 2018 18:59:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:00:34 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:00:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: D4yiBDZFwGONy6BbAARs Scythe Calls: 278 (Fri Aug 31 2018 19:00:41 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:00:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:01:58 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:02:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: A3Mx42oXQ8Q11yVQAAR0 Scythe Calls: 290 (Fri Aug 31 2018 19:02:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:02:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:03:26 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:03:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: _DF4YLIws07DtvVdAAR9 Scythe Calls: 258 (Fri Aug 31 2018 19:03:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:03:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:04:48 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:06:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: f81ESX6SPesBuxyvAASG Scythe Calls: 3077 (Fri Aug 31 2018 19:06:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:06:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:07:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Fri Aug 31 2018 19:07:56 GMT+0000 (Coordinated Universal Time)) +start_character: "UsUcKBRo" (Fri Aug 31 2018 19:08:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Gj5MkVAfB0mTrEZZAAN9 Cozi Calls: 64472 (Fri Aug 31 2018 19:19:35 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Fri Aug 31 2018 19:19:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Fri Aug 31 2018 19:19:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: pHoeEbYMu3AwOPyZAASP UsUcKBRo Calls: 909 (Fri Aug 31 2018 19:21:18 GMT+0000 (Coordinated Universal Time)) +stop_character: UsUcKBRo owner: 4850435912368128 bank: false (Fri Aug 31 2018 19:21:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Tycoon" (Fri Aug 31 2018 19:21:53 GMT+0000 (Coordinated Universal Time)) +Abrupt stop for Tycoon (Fri Aug 31 2018 19:21:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Tycoon owner: 5145329831772160 bank: false (Fri Aug 31 2018 19:21:53 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Fri Aug 31 2018 19:25:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Fri Aug 31 2018 19:25:24 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Fri Aug 31 2018 19:25:25 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Fri Aug 31 2018 19:25:37 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Fri Aug 31 2018 19:25:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 19:25:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0zHHODNrbP11z-N4AAUE Troll Calls: 20 (Fri Aug 31 2018 19:25:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 19:25:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tuV0MknTj_wKD3FzAAT_ Curse Calls: 507 (Fri Aug 31 2018 19:26:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TofiIF340cSgQgnFAAUB Shield Calls: 474 (Fri Aug 31 2018 19:26:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 25GJI2bwiQc4bUhCAAUA Sinstrite Calls: 700 (Fri Aug 31 2018 19:26:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Fri Aug 31 2018 19:26:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Fri Aug 31 2018 19:26:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Fri Aug 31 2018 19:26:28 GMT+0000 (Coordinated Universal Time)) +start_character: "warjab" (Fri Aug 31 2018 19:28:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: jTLN-hL9v8-vW_BLAAT3 warjab Calls: 560 (Fri Aug 31 2018 19:32:55 GMT+0000 (Coordinated Universal Time)) +stop_character: warjab owner: 5738970928381952 bank: false (Fri Aug 31 2018 19:32:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZY1vJt5Y4x8osabSAAAz Foaly Calls: 6 (Fri Aug 31 2018 19:37:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Fri Aug 31 2018 19:37:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Fri Aug 31 2018 19:38:43 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:40:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 90gm6K26gBNd7f3-AASY Scythe Calls: 71888 (Fri Aug 31 2018 19:40:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: T8rRpxmxOcRy0FI_AASb Silent Calls: 24919 (Fri Aug 31 2018 19:40:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:40:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:40:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:42:05 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:42:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: acbN7M9HsE9MMM9mAAVg Scythe Calls: 315 (Fri Aug 31 2018 19:42:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:42:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:43:37 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:43:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NwDjbbjDCVDYLFa8AAVp Scythe Calls: 343 (Fri Aug 31 2018 19:43:46 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:43:46 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:45:17 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:45:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: _9JrxDJfJ43I6VzOAAV0 Scythe Calls: 344 (Fri Aug 31 2018 19:45:25 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:45:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Fri Aug 31 2018 19:45:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vDGl_qiRBXrtqXEjAAV3 Silent Calls: 3 (Fri Aug 31 2018 19:45:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:45:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:46:48 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:46:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: lwm3AibIS0ZAsUCJAAV- Scythe Calls: 394 (Fri Aug 31 2018 19:46:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:46:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:48:12 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:48:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 8AyG1Z-0l02tYEQgAAWH Scythe Calls: 208 (Fri Aug 31 2018 19:48:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:48:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:49:47 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:49:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wARual8mSyoLLcWPAAWQ Scythe Calls: 248 (Fri Aug 31 2018 19:49:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:49:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:51:08 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:51:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Gn8LKzb_ImsKoFviAAWZ Scythe Calls: 190 (Fri Aug 31 2018 19:51:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:51:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:52:48 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:52:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: u6tCGzgaOTJtpdMOAAWi Scythe Calls: 357 (Fri Aug 31 2018 19:52:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:52:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:54:23 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:54:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Pwsbz6cY7jcFWc0AAAWt Scythe Calls: 255 (Fri Aug 31 2018 19:54:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:54:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:55:52 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:55:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: H9lrD9jR1MPSxkZqAAW2 Scythe Calls: 211 (Fri Aug 31 2018 19:55:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:55:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:57:15 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:57:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -us1oCPcovAdfLcfAAW_ Scythe Calls: 225 (Fri Aug 31 2018 19:57:22 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:57:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 19:58:42 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 19:58:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2igxoCUSRf6-UwZCAAXI Scythe Calls: 282 (Fri Aug 31 2018 19:58:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 19:58:50 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 20:00:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Fri Aug 31 2018 20:00:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Fri Aug 31 2018 20:11:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Fri Aug 31 2018 20:11:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Fri Aug 31 2018 20:11:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 20:12:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VuzYCGvHddnCgKZXAAYW Troll Calls: 25 (Fri Aug 31 2018 20:12:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 20:12:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 20:12:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: nY0xf0wtS-7hIOMeAAYe Troll Calls: 13 (Fri Aug 31 2018 20:12:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 20:12:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 8reDuR--6TA2PKFjAAYS Shield Calls: 755 (Fri Aug 31 2018 20:13:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ao_h4bhlK8yn3p1TAAYP Curse Calls: 743 (Fri Aug 31 2018 20:13:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5jr4UkpMFd3llf3SAAYT Sinstrite Calls: 734 (Fri Aug 31 2018 20:13:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Fri Aug 31 2018 20:13:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Fri Aug 31 2018 20:13:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Fri Aug 31 2018 20:13:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0zO_kw8QOEIEl33eAATb Cozi Calls: 64161 (Fri Aug 31 2018 20:19:35 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Fri Aug 31 2018 20:19:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Fri Aug 31 2018 20:19:40 GMT+0000 (Coordinated Universal Time)) +start_character: "SiDeWaYs2o1o" (Fri Aug 31 2018 20:37:13 GMT+0000 (Coordinated Universal Time)) +mount_user: SiDeWaYs2o1o owner: 4791692741836800 (Fri Aug 31 2018 20:43:03 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SiDeWaYs2o1o owner: 4791692741836800 (Fri Aug 31 2018 20:45:21 GMT+0000 (Coordinated Universal Time)) +start_character: "SiDeWaYs3" (Fri Aug 31 2018 20:54:43 GMT+0000 (Coordinated Universal Time)) +mount_user: SiDeWaYs3 owner: 4791692741836800 (Fri Aug 31 2018 20:55:12 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SiDeWaYs3 owner: 4791692741836800 (Fri Aug 31 2018 20:55:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: aSwV0WBD66dn0zswAAPV Trexnamedtex Calls: 20277 (Fri Aug 31 2018 20:56:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtex owner: 5209159389675520 bank: false (Fri Aug 31 2018 20:56:31 GMT+0000 (Coordinated Universal Time)) +mount_user: SiDeWaYs3 owner: 4791692741836800 (Fri Aug 31 2018 20:57:27 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SiDeWaYs3 owner: 4791692741836800 (Fri Aug 31 2018 20:58:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Fri Aug 31 2018 20:58:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Fri Aug 31 2018 20:58:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Fri Aug 31 2018 20:58:27 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 20:58:40 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7sDwmXTyjWPrd-njAAcg Troll Calls: 19 (Fri Aug 31 2018 20:58:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 20:58:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 20:59:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IoMZKvbKo8dUcCuwAAcr Troll Calls: 18 (Fri Aug 31 2018 20:59:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 20:59:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yFZI9zm63GNUGlaKAAcc Curse Calls: 758 (Fri Aug 31 2018 21:00:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: o5PI91G3lAjn_W-uAAcf Sinstrite Calls: 1011 (Fri Aug 31 2018 21:00:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VzJnVbkd0dLmXUH1AAce Shield Calls: 734 (Fri Aug 31 2018 21:00:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Fri Aug 31 2018 21:00:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Fri Aug 31 2018 21:00:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Fri Aug 31 2018 21:00:08 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 21:13:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: cq8VdF63qdrtOdlkAAXR Scythe Calls: 160087 (Fri Aug 31 2018 21:13:05 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 21:13:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Iwf6kb9LJH0_AmmwAAXU Silent Calls: 55372 (Fri Aug 31 2018 21:13:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Fri Aug 31 2018 21:13:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 21:14:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Fri Aug 31 2018 21:14:34 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 21:17:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Ac91OeMUHFDqDoqwAAd7 Scythe Calls: 7589 (Fri Aug 31 2018 21:17:46 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 21:17:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mgeffuTqivSqvlMxAAd- Silent Calls: 2436 (Fri Aug 31 2018 21:17:46 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Fri Aug 31 2018 21:17:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 21:19:08 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 21:19:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rH0udRiuZ5CUAnTiAAeX Scythe Calls: 209 (Fri Aug 31 2018 21:19:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 21:19:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YQ5KFqT3FYIVHI48AAZI Cozi Calls: 64206 (Fri Aug 31 2018 21:19:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Fri Aug 31 2018 21:19:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Fri Aug 31 2018 21:19:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 21:20:35 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 21:20:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bQ6L0oSAxCLUM5_-AAei Scythe Calls: 249 (Fri Aug 31 2018 21:20:42 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 21:20:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 21:22:12 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 21:22:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: P1FIFS4k8T7WorWlAAer Scythe Calls: 370 (Fri Aug 31 2018 21:22:21 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 21:22:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 21:23:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Fri Aug 31 2018 21:23:56 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 21:36:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: JZ-xKZwpaxtvKxI2AAe1 Scythe Calls: 27594 (Fri Aug 31 2018 21:36:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 21:36:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: iNEvMSF2GpL86K1IAAe4 Silent Calls: 9661 (Fri Aug 31 2018 21:36:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Fri Aug 31 2018 21:36:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 21:38:00 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 21:38:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xjo5t-d9jSkmkpjYAAgF Scythe Calls: 207 (Fri Aug 31 2018 21:38:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 21:38:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 21:39:15 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 21:39:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xReCCo5aLdGGdDyTAAgL Scythe Calls: 272 (Fri Aug 31 2018 21:39:21 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 21:39:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 21:40:57 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 21:41:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: oECtUQ_r0p6uaXFUAAgV Scythe Calls: 343 (Fri Aug 31 2018 21:41:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 21:41:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 21:42:19 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 21:42:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: LawYsRiB5UGnmnU_AAgd Scythe Calls: 228 (Fri Aug 31 2018 21:42:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 21:42:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 21:43:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Fri Aug 31 2018 21:43:48 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Fri Aug 31 2018 21:45:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Fri Aug 31 2018 21:45:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Fri Aug 31 2018 21:45:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 21:45:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yenPQ_pnKjQdGZZuAAg0 Troll Calls: 25 (Fri Aug 31 2018 21:45:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 21:45:28 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 21:46:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 4u9IGCXIS4ju9z4hAAg9 Troll Calls: 14 (Fri Aug 31 2018 21:46:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 21:46:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fgJLhqgzJvXv0rHbAAgy Sinstrite Calls: 690 (Fri Aug 31 2018 21:46:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: i0RM_gAfv2FnQ97IAAgv Curse Calls: 723 (Fri Aug 31 2018 21:46:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: iK_3cObvBNN_0p75AAgx Shield Calls: 710 (Fri Aug 31 2018 21:46:42 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Fri Aug 31 2018 21:46:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Fri Aug 31 2018 21:46:44 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Fri Aug 31 2018 21:46:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wXWuuTCNr7dD3FwcAAaj SiDeWaYs2o1o Calls: 7460 (Fri Aug 31 2018 21:50:37 GMT+0000 (Coordinated Universal Time)) +stop_character: SiDeWaYs2o1o owner: 4791692741836800 bank: false (Fri Aug 31 2018 21:50:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: R2_vs9U21yZkunNZAAcG SiDeWaYs3 Calls: 374 (Fri Aug 31 2018 21:50:38 GMT+0000 (Coordinated Universal Time)) +stop_character: SiDeWaYs3 owner: 4791692741836800 bank: false (Fri Aug 31 2018 21:50:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wBK2JCz-HZxEChUeAAed Cozi Calls: 64010 (Fri Aug 31 2018 22:19:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Fri Aug 31 2018 22:19:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Fri Aug 31 2018 22:19:40 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: e2sm_A4aX2fvpIujAAgm Scythe Calls: 87829 (Fri Aug 31 2018 22:23:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tL6QI-jLp-RqSGlJAAgn Silent Calls: 30365 (Fri Aug 31 2018 22:23:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:23:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:23:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:25:13 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:25:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SU0kRXfQpMf64HG1AAkT Scythe Calls: 495 (Fri Aug 31 2018 22:25:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:25:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:26:46 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:26:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: aUkbdL4g2-0l1Cr1AAkf Scythe Calls: 217 (Fri Aug 31 2018 22:26:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:26:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:28:15 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:28:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Rbl-YB6IVpvl5tLkAAkn Scythe Calls: 412 (Fri Aug 31 2018 22:28:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:28:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:29:46 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:29:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: loWMUkJ2IfEO0nX3AAkx Scythe Calls: 205 (Fri Aug 31 2018 22:29:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:29:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:31:19 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:31:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0dz0srhDf1APSucPAAk6 Scythe Calls: 219 (Fri Aug 31 2018 22:31:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:31:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Fri Aug 31 2018 22:31:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Fri Aug 31 2018 22:31:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Fri Aug 31 2018 22:31:46 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 22:32:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SgOoexXC9x6f2crEAAlE Troll Calls: 17 (Fri Aug 31 2018 22:32:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 22:32:27 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:32:52 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:33:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -YM-9mdYV7jLHJ72AAlJ Scythe Calls: 277 (Fri Aug 31 2018 22:33:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:33:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 22:33:11 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2eKwuyzpia3HKd1jAAlO Troll Calls: 19 (Fri Aug 31 2018 22:33:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 22:33:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: EmenZQTsOHsEufPFAAk- Shield Calls: 903 (Fri Aug 31 2018 22:33:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3sLYbA9eHDh_yROuAAk_ Sinstrite Calls: 1218 (Fri Aug 31 2018 22:33:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3rO7Z5Rt8bvfUGecAAk9 Curse Calls: 905 (Fri Aug 31 2018 22:33:48 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Fri Aug 31 2018 22:33:48 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Fri Aug 31 2018 22:33:48 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Fri Aug 31 2018 22:33:48 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:34:16 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:34:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: M5wMGEwEmYcQKg58AAlW Scythe Calls: 211 (Fri Aug 31 2018 22:34:22 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:34:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:35:50 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:35:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0cWyPbTPyYLtgNWpAAlf Scythe Calls: 298 (Fri Aug 31 2018 22:35:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:35:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:37:31 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:37:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Jcm-iV4fp5E263ZFAAlp Scythe Calls: 223 (Fri Aug 31 2018 22:37:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:37:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:38:58 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:39:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rkcLCeidoY3Dhu7uAAlx Scythe Calls: 360 (Fri Aug 31 2018 22:39:10 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:39:10 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:40:27 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:40:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7NQYx2o4t6ioNcASAAl6 Scythe Calls: 216 (Fri Aug 31 2018 22:40:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:40:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:42:43 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:42:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: BYNDQAcqyQqMKKbLAAmH Scythe Calls: 400 (Fri Aug 31 2018 22:42:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:42:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:44:23 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:44:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yQjUF3Vvo4Exjk6RAAmS Scythe Calls: 188 (Fri Aug 31 2018 22:44:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:44:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:46:28 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Fri Aug 31 2018 22:46:44 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:46:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: K74oHU0KerrnG4vDAAme Scythe Calls: 792 (Fri Aug 31 2018 22:46:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: u_HmQHFvXAAiIe3NAAmg Silent Calls: 61 (Fri Aug 31 2018 22:46:51 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:46:51 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:46:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:48:16 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:48:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fGZm3VIsGgxx3w7NAAmp Scythe Calls: 307 (Fri Aug 31 2018 22:48:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:48:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:49:56 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:50:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: nmyj1tNVKjdgyaYfAAm0 Scythe Calls: 213 (Fri Aug 31 2018 22:50:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:50:02 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Fri Aug 31 2018 22:50:26 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Fri Aug 31 2018 22:50:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: nVnNVo706vHawK3OAAId 0x00 Calls: 15921 (Fri Aug 31 2018 22:51:26 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Fri Aug 31 2018 22:51:27 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:51:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Fri Aug 31 2018 22:51:45 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 22:51:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: b7GmP4WYl2o50iMPAAm9 Scythe Calls: 452 (Fri Aug 31 2018 22:51:46 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:51:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: _IXFwa6sKRW_xz5MAAnA Silent Calls: 5 (Fri Aug 31 2018 22:51:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Fri Aug 31 2018 22:51:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 22:53:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Fri Aug 31 2018 22:53:20 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Fri Aug 31 2018 22:57:54 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Fri Aug 31 2018 23:08:23 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Fri Aug 31 2018 23:09:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Fri Aug 31 2018 23:18:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Fri Aug 31 2018 23:18:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Fri Aug 31 2018 23:18:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 23:19:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UqSy-mTLMPUiQRm9AApW Troll Calls: 22 (Fri Aug 31 2018 23:19:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 23:19:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Lm_vji1oIMusC62xAAj1 Cozi Calls: 64401 (Fri Aug 31 2018 23:19:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Fri Aug 31 2018 23:19:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Fri Aug 31 2018 23:19:39 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Fri Aug 31 2018 23:19:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0S7WkIyjNWRXhVBgAApg Troll Calls: 15 (Fri Aug 31 2018 23:19:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Fri Aug 31 2018 23:19:57 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Fri Aug 31 2018 23:20:12 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Fri Aug 31 2018 23:20:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: lEmleWMSyss7tBNOAApR Curse Calls: 724 (Fri Aug 31 2018 23:20:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dS67Kj-0d7hdJG8BAApT Sinstrite Calls: 1007 (Fri Aug 31 2018 23:20:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: AptpaY7_7wchjQzYAApS Shield Calls: 716 (Fri Aug 31 2018 23:20:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Fri Aug 31 2018 23:20:25 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Fri Aug 31 2018 23:20:25 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Fri Aug 31 2018 23:20:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KFt-BTkSaQoz7sn9AAAN Mupp Calls: 88013 (Fri Aug 31 2018 23:24:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: w4w9Vq9s_rLAFshaAAAJ MuppPriest Calls: 87227 (Fri Aug 31 2018 23:24:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7V9b-_Hp4xrLe1eYAAAU MuppArch Calls: 6 (Fri Aug 31 2018 23:24:27 GMT+0000 (Coordinated Universal Time)) +stop_character: MuppPriest owner: 5552666278100992 bank: false (Fri Aug 31 2018 23:24:28 GMT+0000 (Coordinated Universal Time)) +stop_character: MuppArch owner: 5552666278100992 bank: false (Fri Aug 31 2018 23:24:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Mupp owner: 5552666278100992 bank: false (Fri Aug 31 2018 23:24:28 GMT+0000 (Coordinated Universal Time)) +Main loop took 23ms (Fri Aug 31 2018 23:24:28 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Fri Aug 31 2018 23:24:56 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Fri Aug 31 2018 23:24:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Miggy" (Fri Aug 31 2018 23:43:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: U1zQGKHSGAgKk1a6AArV Miggy Calls: 231 (Fri Aug 31 2018 23:47:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Miggy owner: 5111336821325824 bank: false (Fri Aug 31 2018 23:47:19 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 23:51:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: B9fBx-bKud6suwVbAAnH Scythe Calls: 128299 (Fri Aug 31 2018 23:51:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: QSzI0p66kyOLaRebAAnK Silent Calls: 44297 (Fri Aug 31 2018 23:51:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 23:51:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Fri Aug 31 2018 23:51:28 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Fri Aug 31 2018 23:52:31 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Fri Aug 31 2018 23:52:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 23:52:49 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Fri Aug 31 2018 23:53:00 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Fri Aug 31 2018 23:53:01 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Fri Aug 31 2018 23:53:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: LIiTLLQoJpsyXTf5AAsS Scythe Calls: 441 (Fri Aug 31 2018 23:53:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Fri Aug 31 2018 23:53:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: qb9PGshVEQuJ6uosAAsT Silent Calls: 6 (Fri Aug 31 2018 23:53:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Fri Aug 31 2018 23:53:03 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Fri Aug 31 2018 23:53:06 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Fri Aug 31 2018 23:53:18 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Fri Aug 31 2018 23:53:39 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Fri Aug 31 2018 23:53:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Fri Aug 31 2018 23:54:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Fri Aug 31 2018 23:54:39 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Fri Aug 31 2018 23:57:00 GMT+0000 (Coordinated Universal Time)) +start_character: "Emerald" (Fri Aug 31 2018 23:57:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 9fPweHGbv3fTETvaAAss Emerald Calls: 5 (Fri Aug 31 2018 23:57:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Emerald owner: 6474009906511872 bank: false (Fri Aug 31 2018 23:57:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Emerald" (Fri Aug 31 2018 23:57:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vpiteDE6RZERQb57AAsy Emerald Calls: 8 (Fri Aug 31 2018 23:57:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Emerald owner: 6474009906511872 bank: false (Fri Aug 31 2018 23:58:00 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Fri Aug 31 2018 23:58:09 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Fri Aug 31 2018 23:58:13 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Fri Aug 31 2018 23:58:32 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Fri Aug 31 2018 23:59:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Emerald" (Fri Aug 31 2018 23:59:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: JqpOwBqDRBKkXaWIAAs- Emerald Calls: 5 (Fri Aug 31 2018 23:59:40 GMT+0000 (Coordinated Universal Time)) +stop_character: Emerald owner: 6474009906511872 bank: false (Fri Aug 31 2018 23:59:41 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Sat Sep 01 2018 00:01:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Emerald" (Sat Sep 01 2018 00:01:48 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Sat Sep 01 2018 00:02:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: kFPF50OL8Gm4r8iTAAtK Emerald Calls: 14 (Sat Sep 01 2018 00:02:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Emerald owner: 6474009906511872 bank: false (Sat Sep 01 2018 00:02:17 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Sat Sep 01 2018 00:02:23 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Sat Sep 01 2018 00:02:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Emerald" (Sat Sep 01 2018 00:03:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wuDdP48wCUGfxly0AAtV Emerald Calls: 5 (Sat Sep 01 2018 00:03:45 GMT+0000 (Coordinated Universal Time)) +stop_character: Emerald owner: 6474009906511872 bank: false (Sat Sep 01 2018 00:03:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 00:05:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 00:05:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 00:05:28 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 00:05:40 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bTmqsR7Uij96dn-3AAtj Troll Calls: 20 (Sat Sep 01 2018 00:05:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 00:05:48 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 00:06:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NmhdPjFawTl9BY3OAAtr Troll Calls: 13 (Sat Sep 01 2018 00:06:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 00:06:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: W8tCyXciqRItGtl_AAtg Shield Calls: 634 (Sat Sep 01 2018 00:06:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: qtSUoqtAbkqZTapTAAtf Sinstrite Calls: 898 (Sat Sep 01 2018 00:06:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -aiI6X4cBTBbdn2OAAte Curse Calls: 665 (Sat Sep 01 2018 00:06:55 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 00:06:55 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 00:06:56 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 00:06:56 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 00:13:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: lId3F3ZyqQodWDk5AAsc Scythe Calls: 43037 (Sat Sep 01 2018 00:13:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 00:13:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: R9cSZFoD3ggzF74iAAsf Silent Calls: 14734 (Sat Sep 01 2018 00:13:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 00:13:59 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 00:15:11 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 00:15:35 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 00:15:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: k4LSnNIi-Ckfy3tiAAub Scythe Calls: 1353 (Sat Sep 01 2018 00:15:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 00:15:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: eWZIjnhG5FnI5PTIAAue Silent Calls: 346 (Sat Sep 01 2018 00:16:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 00:16:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 00:17:16 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 00:17:32 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 00:18:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bUrljyiVmuaFoNs7AAup Scythe Calls: 3653 (Sat Sep 01 2018 00:18:49 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 00:18:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: pOdSErE07CWjFW6hAAuq Silent Calls: 989 (Sat Sep 01 2018 00:18:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 00:18:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6FEProuZd1T9T3NgAApc Cozi Calls: 64709 (Sat Sep 01 2018 00:19:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 00:19:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 00:19:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 00:20:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 00:20:38 GMT+0000 (Coordinated Universal Time)) +start_character: "BuyMyThings" (Sat Sep 01 2018 00:20:39 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Sat Sep 01 2018 00:21:27 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Sat Sep 01 2018 00:21:39 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Sat Sep 01 2018 00:22:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YN0wNg4WSTggLZiJAAu8 Scythe Calls: 3449 (Sat Sep 01 2018 00:22:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xVpTi9-PF1DAMwNnAAvA Silent Calls: 987 (Sat Sep 01 2018 00:22:20 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 00:22:20 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 00:22:20 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Sat Sep 01 2018 00:22:34 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Sat Sep 01 2018 00:22:37 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Sat Sep 01 2018 00:22:40 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Sat Sep 01 2018 00:23:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: qHv5NHfVxad6atpYAAu_ BuyMyThings Calls: 111 (Sat Sep 01 2018 00:23:28 GMT+0000 (Coordinated Universal Time)) +stop_character: BuyMyThings owner: 4687219387269120 bank: true (Sat Sep 01 2018 00:23:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 00:23:52 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 00:24:00 GMT+0000 (Coordinated Universal Time)) +start_character: "BuyMyThings" (Sat Sep 01 2018 00:24:55 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Sat Sep 01 2018 00:28:07 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Sat Sep 01 2018 00:28:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 8-9KhoI968V1ewEIAAvZ BuyMyThings Calls: 236 (Sat Sep 01 2018 00:30:16 GMT+0000 (Coordinated Universal Time)) +stop_character: BuyMyThings owner: 4687219387269120 bank: false (Sat Sep 01 2018 00:30:17 GMT+0000 (Coordinated Universal Time)) +start_character: "BuyMyThings" (Sat Sep 01 2018 00:30:21 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Sat Sep 01 2018 00:31:52 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Sat Sep 01 2018 00:31:56 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Sat Sep 01 2018 00:32:31 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Sat Sep 01 2018 00:33:10 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 00:34:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rHu7EOqDfyNcp_yrAAvS Scythe Calls: 22690 (Sat Sep 01 2018 00:34:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 00:34:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: H21C58aaY8mYlNnQAAvU Silent Calls: 8065 (Sat Sep 01 2018 00:34:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 00:34:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 00:36:06 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 00:36:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xgYQMG5JLfGjngQtAAwX Scythe Calls: 265 (Sat Sep 01 2018 00:36:22 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 00:36:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 00:37:48 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 00:37:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 27fdJXiplqivqRYaAAwi Scythe Calls: 283 (Sat Sep 01 2018 00:37:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 00:37:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 00:39:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 00:39:12 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Sat Sep 01 2018 00:45:14 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Sat Sep 01 2018 00:45:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: muqLHkbpu7Hx3zvCAAv4 BuyMyThings Calls: 375 (Sat Sep 01 2018 00:49:23 GMT+0000 (Coordinated Universal Time)) +stop_character: BuyMyThings owner: 4687219387269120 bank: false (Sat Sep 01 2018 00:49:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtod" (Sat Sep 01 2018 00:50:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Sat Sep 01 2018 00:50:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Sat Sep 01 2018 00:50:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Sat Sep 01 2018 00:50:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 00:51:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 00:51:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 00:51:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 00:52:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: BY8LVUUaFeF9GUDMAAx5 Troll Calls: 20 (Sat Sep 01 2018 00:52:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 00:52:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 00:53:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: C9aWKV84y7-pVfuVAAyD Troll Calls: 13 (Sat Sep 01 2018 00:53:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 00:53:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0QKLQOpJFIaw1M5oAAx2 Sinstrite Calls: 1031 (Sat Sep 01 2018 00:53:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: QURjutu6iYCEQ6wKAAx3 Shield Calls: 709 (Sat Sep 01 2018 00:53:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YjIjvWvqDxCOhCmvAAx0 Curse Calls: 740 (Sat Sep 01 2018 00:53:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 00:53:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 00:53:35 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 00:53:35 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: XiPeN9uSa_HlXjJ_AAu5 Cozi Calls: 64467 (Sat Sep 01 2018 01:19:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 01:19:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 01:19:41 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Sat Sep 01 2018 01:19:44 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Sat Sep 01 2018 01:19:56 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Sat Sep 01 2018 01:20:00 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Sat Sep 01 2018 01:20:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 01:38:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 01:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 01:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 01:39:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dCT4BQH-P5C1nvxtAA2E Troll Calls: 20 (Sat Sep 01 2018 01:39:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 01:39:27 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 01:40:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -jVfoUJjNhL2MPmuAA2K Troll Calls: 19 (Sat Sep 01 2018 01:40:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 01:40:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IaxUIhKDh7yAIASrAA17 Curse Calls: 907 (Sat Sep 01 2018 01:40:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: e4HO8HjImasFgV3gAA1- Shield Calls: 935 (Sat Sep 01 2018 01:40:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DWkXzmHhqio6_03MAA1_ Sinstrite Calls: 1248 (Sat Sep 01 2018 01:40:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 01:40:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 01:40:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 01:40:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7-JEEajmcefFAEhfAA0W Cozi Calls: 64745 (Sat Sep 01 2018 02:19:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 02:19:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 02:19:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 02:25:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 02:25:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 02:25:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 02:25:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: eXU6BSETWEWlKRC3AA6K Troll Calls: 78 (Sat Sep 01 2018 02:25:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 02:25:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: kENWw8zbRjHk0vTIAA6F Curse Calls: 268 (Sat Sep 01 2018 02:26:09 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PzsSyRg8TRiUgznSAA6H Sinstrite Calls: 367 (Sat Sep 01 2018 02:26:09 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NLLn8xCXwUCP9TQVAA6I Shield Calls: 245 (Sat Sep 01 2018 02:26:09 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 02:26:10 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 02:26:10 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 02:26:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fkSDaOdwX3lT_gaoAA5m Cozi Calls: 11070 (Sat Sep 01 2018 02:29:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 02:29:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 02:30:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -dauRcJ_hla8t2BKAAAa Pluu Calls: 793521 (Sat Sep 01 2018 02:30:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 02:30:39 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 02:30:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vNLdCj_TnPPK7cFtAA6k Cozi Calls: 7895 (Sat Sep 01 2018 02:37:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 02:37:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 02:37:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UmXjiPcgFJakBd5BAAwq Scythe Calls: 288641 (Sat Sep 01 2018 02:50:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: sfRsyexXB8mHgZYKAAwt Silent Calls: 100397 (Sat Sep 01 2018 02:50:48 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 02:50:49 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 02:50:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 03:11:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 03:11:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 03:11:28 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 03:11:40 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Fs-O4Ho9lNrRt72JAA8b Troll Calls: 39 (Sat Sep 01 2018 03:11:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 03:11:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: oRLUD8Nyjj_spcGiAA8Z Sinstrite Calls: 501 (Sat Sep 01 2018 03:12:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: MdN-cLmiDsLJf8RVAA8X Curse Calls: 375 (Sat Sep 01 2018 03:12:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KIqXdxpPTw7_r8CeAA8Y Shield Calls: 354 (Sat Sep 01 2018 03:12:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 03:12:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 03:12:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 03:12:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: WSk2mWSxRGOrkIPjAA6n Pluu Calls: 52294 (Sat Sep 01 2018 03:19:36 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: qLc-XWWiMvoJncIjAA67 Cozi Calls: 45086 (Sat Sep 01 2018 03:19:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 03:19:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 03:19:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 03:19:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 03:19:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 03:48:11 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 03:48:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 03:57:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 03:57:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 03:57:19 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Sat Sep 01 2018 03:57:24 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Sat Sep 01 2018 03:57:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 03:57:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fZCGUYg45XAF2yIBAA-g Troll Calls: 40 (Sat Sep 01 2018 03:57:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 03:57:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: iWrIaVYMKP5azm0HAA-d Sinstrite Calls: 702 (Sat Sep 01 2018 03:58:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: K0UeW3vTJDfWmgO2AA-e Shield Calls: 487 (Sat Sep 01 2018 03:58:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Bs1S48dhEc5poSTWAA-c Curse Calls: 521 (Sat Sep 01 2018 03:58:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 03:58:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 03:58:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 03:58:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7k63OC7O0rGfQ-lGAAnk 0x00 Calls: 15769 (Sat Sep 01 2018 04:05:32 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Sat Sep 01 2018 04:05:33 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Sat Sep 01 2018 04:06:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DZLT0G0E4JwbRQaIAA8y Pluu Calls: 64674 (Sat Sep 01 2018 04:19:36 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: kAfaO3SKEsayKUGoAA8z Cozi Calls: 64686 (Sat Sep 01 2018 04:19:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 04:19:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 04:19:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 04:19:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 04:19:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 04:43:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 04:43:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 04:43:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 04:43:40 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: I7-5t47r0hlw4jtKABAl Troll Calls: 38 (Sat Sep 01 2018 04:43:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 04:43:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: LIt3WrK1VV_iK0jdABAj Shield Calls: 358 (Sat Sep 01 2018 04:44:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YdgXcFbyxre3XJ2PABAh Curse Calls: 384 (Sat Sep 01 2018 04:44:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dWjlCVTRacXeFpAxABAi Sinstrite Calls: 567 (Sat Sep 01 2018 04:44:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 04:44:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 04:44:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 04:44:13 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtod owner: 5209159389675520 (Sat Sep 01 2018 04:56:48 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtod owner: 5209159389675520 (Sat Sep 01 2018 04:57:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: LeylQhwCnlRHBCt9AAxu Trexnamedted Calls: 188843 (Sat Sep 01 2018 04:57:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: RI-4Zmw0wSVDgtyaAAxs Trexnamedtom Calls: 187300 (Sat Sep 01 2018 04:57:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dO1Uk0I9j0dnFf3vAAxv Trexnamedtut Calls: 187677 (Sat Sep 01 2018 04:57:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Od5lMDY3zIazfGqhAAxq Trexnamedtod Calls: 102 (Sat Sep 01 2018 04:57:48 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Sat Sep 01 2018 04:57:48 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Sat Sep 01 2018 04:57:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Sat Sep 01 2018 04:57:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtod owner: 5209159389675520 bank: false (Sat Sep 01 2018 04:57:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Sat Sep 01 2018 04:57:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtom owner: 5209159389675520 (Sat Sep 01 2018 04:58:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Sat Sep 01 2018 04:59:07 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtom owner: 5209159389675520 (Sat Sep 01 2018 04:59:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Sat Sep 01 2018 04:59:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VJM-icO3WeNtR8PgABBM Trexnamedtom Calls: 122 (Sat Sep 01 2018 04:59:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Sat Sep 01 2018 04:59:38 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedted owner: 5209159389675520 (Sat Sep 01 2018 04:59:50 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedted owner: 5209159389675520 (Sat Sep 01 2018 04:59:59 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtut owner: 5209159389675520 (Sat Sep 01 2018 05:00:23 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtut owner: 5209159389675520 (Sat Sep 01 2018 05:00:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zpufaqTCwJx3UWf4ABBQ Trexnamedted Calls: 86 (Sat Sep 01 2018 05:00:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Sat Sep 01 2018 05:00:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZBz_6nWBcAFGaXp1ABBS Trexnamedtut Calls: 92 (Sat Sep 01 2018 05:01:10 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Sat Sep 01 2018 05:01:10 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtod" (Sat Sep 01 2018 05:01:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Sat Sep 01 2018 05:01:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Sat Sep 01 2018 05:01:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Sat Sep 01 2018 05:01:23 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 05:09:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: _uNE55JTKuxH_ON1AA-B Scythe Calls: 179643 (Sat Sep 01 2018 05:09:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 05:09:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0xqRuIIb54PzvxjqAA-D Silent Calls: 62264 (Sat Sep 01 2018 05:09:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 05:09:59 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 05:12:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 05:12:31 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 05:12:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: BKhKDCxU-aMkAL2iABB6 Scythe Calls: 585 (Sat Sep 01 2018 05:12:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 05:12:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uUtXe4OntkOclLLLABB8 Silent Calls: 144 (Sat Sep 01 2018 05:12:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 05:12:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 05:13:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 05:13:51 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 05:13:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: x278G3rjFjc2LERzABCA Scythe Calls: 230 (Sat Sep 01 2018 05:13:51 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 05:13:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: A5khYvzbnjaB_zjqABCB Silent Calls: 3 (Sat Sep 01 2018 05:14:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 05:14:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 05:15:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 05:15:07 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 05:15:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: AD43KkApxygDJPQTABCF Scythe Calls: 225 (Sat Sep 01 2018 05:15:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 05:15:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: EH0Yg5bQWMkYLk7IABCH Silent Calls: 3 (Sat Sep 01 2018 05:15:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 05:15:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 05:16:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 05:16:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: EqMBS0BwjC3mhfdeAA_e Pluu Calls: 64717 (Sat Sep 01 2018 05:19:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: AzUOVKZKBtXONosOAA_g Cozi Calls: 64292 (Sat Sep 01 2018 05:19:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 05:19:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 05:19:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 05:19:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 05:19:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 05:29:11 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 05:29:16 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 05:29:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 05:29:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tywZKeGyMgLej8mcABC2 Troll Calls: 39 (Sat Sep 01 2018 05:29:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 05:29:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: CidLFFUwzvkBCUxrABC0 Sinstrite Calls: 500 (Sat Sep 01 2018 05:30:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: O4NQFOdTwwStqb4eABCy Curse Calls: 383 (Sat Sep 01 2018 05:30:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Qlb3t0be_sSTIkLTABCz Shield Calls: 368 (Sat Sep 01 2018 05:30:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 05:30:04 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 05:30:04 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 05:30:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: N6OxSDabzF1DJRnwAA-7 0x00 Calls: 3637 (Sat Sep 01 2018 05:37:32 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Sat Sep 01 2018 05:37:32 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Sat Sep 01 2018 05:38:48 GMT+0000 (Coordinated Universal Time)) +start_character: "yeahaa" (Sat Sep 01 2018 05:48:25 GMT+0000 (Coordinated Universal Time)) +start_character: "crionic" (Sat Sep 01 2018 05:53:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: K_t10DIBEmGNaNIsABD5 crionic Calls: 177 (Sat Sep 01 2018 05:55:09 GMT+0000 (Coordinated Universal Time)) +stop_character: crionic owner: 4765522570772480 bank: false (Sat Sep 01 2018 05:55:10 GMT+0000 (Coordinated Universal Time)) +start_character: "choko" (Sat Sep 01 2018 06:00:37 GMT+0000 (Coordinated Universal Time)) +start_character: "crionic" (Sat Sep 01 2018 06:00:55 GMT+0000 (Coordinated Universal Time)) +mount_user: crionic owner: 4765522570772480 (Sat Sep 01 2018 06:01:30 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: crionic owner: 4765522570772480 (Sat Sep 01 2018 06:03:00 GMT+0000 (Coordinated Universal Time)) +mount_user: crionic owner: 4765522570772480 (Sat Sep 01 2018 06:03:45 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: crionic owner: 4765522570772480 (Sat Sep 01 2018 06:04:08 GMT+0000 (Coordinated Universal Time)) +mount_user: crionic owner: 4765522570772480 (Sat Sep 01 2018 06:04:35 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: crionic owner: 4765522570772480 (Sat Sep 01 2018 06:04:40 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IpypYlR3Zhx83LwBABER crionic Calls: 143 (Sat Sep 01 2018 06:04:53 GMT+0000 (Coordinated Universal Time)) +stop_character: crionic owner: 4765522570772480 bank: false (Sat Sep 01 2018 06:04:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -LjXJHT6JX79O_cqABEP choko Calls: 1249 (Sat Sep 01 2018 06:09:41 GMT+0000 (Coordinated Universal Time)) +stop_character: choko owner: 4765522570772480 bank: false (Sat Sep 01 2018 06:09:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 06:14:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 06:15:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 06:15:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 06:15:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: _s_HV-dyxQGXIYQ5ABE9 Troll Calls: 38 (Sat Sep 01 2018 06:15:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 06:15:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: woS4QTcWF-926atbABE5 Shield Calls: 526 (Sat Sep 01 2018 06:16:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: aTeNG_1VTutHaqOuABE6 Sinstrite Calls: 701 (Sat Sep 01 2018 06:16:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: p7lQlxCaLbR3wsr0ABE4 Curse Calls: 538 (Sat Sep 01 2018 06:16:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 06:16:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 06:16:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 06:16:14 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 06:18:11 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7XtUZ8K_qp9LeOqaABCL Scythe Calls: 135949 (Sat Sep 01 2018 06:18:11 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 06:18:11 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -4o2ymuft0C900TEABCM Silent Calls: 47186 (Sat Sep 01 2018 06:18:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 06:18:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 06:19:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 9a75pkyzvdMeuaiwABCW Pluu Calls: 64340 (Sat Sep 01 2018 06:19:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zqI7ZP4dO048bUyWABCY Cozi Calls: 64296 (Sat Sep 01 2018 06:19:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 06:19:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 06:19:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 06:19:39 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 06:19:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 06:19:43 GMT+0000 (Coordinated Universal Time)) +mount_user: yeahaa owner: 4765522570772480 (Sat Sep 01 2018 06:20:30 GMT+0000 (Coordinated Universal Time)) +start_character: "choko" (Sat Sep 01 2018 06:25:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 80Ntec4-avVsph6FABFf choko Calls: 98 (Sat Sep 01 2018 06:26:39 GMT+0000 (Coordinated Universal Time)) +stop_character: choko owner: 4765522570772480 bank: false (Sat Sep 01 2018 06:26:42 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: yeahaa owner: 4765522570772480 (Sat Sep 01 2018 06:27:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Buttercup" (Sat Sep 01 2018 06:33:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: GfgeDtnWVG-s3uswABF7 Buttercup Calls: 12 (Sat Sep 01 2018 06:33:42 GMT+0000 (Coordinated Universal Time)) +stop_character: Buttercup owner: 5736224816889856 bank: false (Sat Sep 01 2018 06:33:43 GMT+0000 (Coordinated Universal Time)) +mount_user: yeahaa owner: 4765522570772480 (Sat Sep 01 2018 06:34:22 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: yeahaa owner: 4765522570772480 (Sat Sep 01 2018 06:35:51 GMT+0000 (Coordinated Universal Time)) +mount_user: yeahaa owner: 4765522570772480 (Sat Sep 01 2018 06:37:22 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: yeahaa owner: 4765522570772480 (Sat Sep 01 2018 06:37:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 07:01:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 07:01:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 07:01:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 07:01:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PWc8-xtY6nj_d0OCABHL Troll Calls: 39 (Sat Sep 01 2018 07:01:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 07:01:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: cJ7-_cjASggZQmlWABHJ Sinstrite Calls: 575 (Sat Sep 01 2018 07:02:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: XE84QJgUvx8I3f-lABHK Shield Calls: 380 (Sat Sep 01 2018 07:02:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: jE792Ny1MLQGaq9OABHH Curse Calls: 407 (Sat Sep 01 2018 07:02:04 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 07:02:05 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 07:02:05 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 07:02:06 GMT+0000 (Coordinated Universal Time)) +start_character: "choko" (Sat Sep 01 2018 07:12:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Ya93B3IlAJt9YvU0ABFM Pluu Calls: 64132 (Sat Sep 01 2018 07:19:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: qgjqUAjz0EL9QZNwABFN Cozi Calls: 64185 (Sat Sep 01 2018 07:19:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 07:19:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 07:19:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 07:19:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 07:19:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: F9YbIYWg_23oIJpeABHr choko Calls: 1618 (Sat Sep 01 2018 07:22:17 GMT+0000 (Coordinated Universal Time)) +stop_character: choko owner: 4765522570772480 bank: false (Sat Sep 01 2018 07:22:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 07:46:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 07:47:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 07:47:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 07:47:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KO-AbboRWJXJkrewABJQ Troll Calls: 38 (Sat Sep 01 2018 07:47:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 07:47:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: _l8LCNdQyvWnCovcABJN Sinstrite Calls: 806 (Sat Sep 01 2018 07:48:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rhsXgc_BXVsyCigCABJO Shield Calls: 546 (Sat Sep 01 2018 07:48:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: kWk1-HdG8B80xXGkABJL Curse Calls: 538 (Sat Sep 01 2018 07:48:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 07:48:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 07:48:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 07:48:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: MoDcE-aqKXpSO30TABDs yeahaa Calls: 224 (Sat Sep 01 2018 08:15:47 GMT+0000 (Coordinated Universal Time)) +stop_character: yeahaa owner: 4765522570772480 bank: false (Sat Sep 01 2018 08:15:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7Wg_ktubP3jibBCaABH_ Pluu Calls: 64517 (Sat Sep 01 2018 08:19:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PkIZpEjFiTfuYZBPABIB Cozi Calls: 64222 (Sat Sep 01 2018 08:19:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 08:19:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 08:19:39 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 08:19:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 08:19:41 GMT+0000 (Coordinated Universal Time)) +Main loop took 26ms (Sat Sep 01 2018 08:26:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 08:33:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 08:33:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 08:33:11 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 08:33:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DI2c65kNgy9w866PABLU Troll Calls: 39 (Sat Sep 01 2018 08:33:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 08:33:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: t08NfJO5e0u4uqUsABLR Shield Calls: 342 (Sat Sep 01 2018 08:33:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: znE4Ti1p60EOkEsHABLS Sinstrite Calls: 441 (Sat Sep 01 2018 08:33:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: RYXGEclhqo37goS3ABLQ Curse Calls: 352 (Sat Sep 01 2018 08:33:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 08:33:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 08:33:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 08:33:54 GMT+0000 (Coordinated Universal Time)) +start_character: "lissandra" (Sat Sep 01 2018 08:37:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ciSoEdVTA_jrg5g5ABLh lissandra Calls: 70 (Sat Sep 01 2018 08:38:04 GMT+0000 (Coordinated Universal Time)) +stop_character: lissandra owner: 5793534377459712 bank: false (Sat Sep 01 2018 08:38:05 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 08:38:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YfpziZlCVU5lVFyNABFJ Scythe Calls: 305144 (Sat Sep 01 2018 08:38:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 08:38:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YcN8sJs4UAub1Ez2ABFK Silent Calls: 106178 (Sat Sep 01 2018 08:38:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 08:38:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 08:40:00 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 08:40:06 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sat Sep 01 2018 08:40:27 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sat Sep 01 2018 08:40:46 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sat Sep 01 2018 08:41:08 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sat Sep 01 2018 08:41:42 GMT+0000 (Coordinated Universal Time)) +start_character: "BuyMyThings" (Sat Sep 01 2018 08:51:40 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 08:52:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KfwWS-fnDvo4qzx7ABLp Scythe Calls: 27133 (Sat Sep 01 2018 08:52:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0IzmOw2OkG-EWaDqABLq Silent Calls: 9268 (Sat Sep 01 2018 08:52:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 08:52:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 08:52:16 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Sat Sep 01 2018 08:52:39 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Sat Sep 01 2018 08:52:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: WbucmX-tcjpTTBZYABML BuyMyThings Calls: 61 (Sat Sep 01 2018 08:52:56 GMT+0000 (Coordinated Universal Time)) +stop_character: BuyMyThings owner: 4687219387269120 bank: false (Sat Sep 01 2018 08:52:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 08:53:34 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 08:54:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fkdaZVFC-6sFzkvrABMR Scythe Calls: 1210 (Sat Sep 01 2018 08:54:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 08:54:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 08:56:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 08:56:11 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 08:56:11 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: pKTR2rXgioJqJDH7ABMZ Scythe Calls: 242 (Sat Sep 01 2018 08:56:11 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 08:56:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: e59BpmClWekb8I9JABMa Silent Calls: 3 (Sat Sep 01 2018 08:56:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 08:56:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 08:57:29 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 08:57:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: COPhIY_bjurvFNADABMe Scythe Calls: 248 (Sat Sep 01 2018 08:57:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 08:57:39 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 08:58:48 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 08:58:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: u5jTolsxeUf3QAqrABMj Scythe Calls: 308 (Sat Sep 01 2018 08:58:55 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 08:58:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 09:00:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 09:00:26 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 09:02:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: jS5Qo1kpDbF-9RjGABMo Scythe Calls: 5879 (Sat Sep 01 2018 09:02:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 09:02:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: LZ4x3GL_l7kK-2e4ABMq Silent Calls: 1971 (Sat Sep 01 2018 09:03:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 09:03:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 09:04:09 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 09:04:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: n8n5fYbqRz0b8QUoABM1 Scythe Calls: 210 (Sat Sep 01 2018 09:04:15 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 09:04:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 09:04:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vgvqhNSnydiYldiqABM2 Silent Calls: 3 (Sat Sep 01 2018 09:04:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 09:04:39 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 09:05:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 09:05:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 4XgMtToWeir0ZvqtABDR 0x00 Calls: 8630 (Sat Sep 01 2018 09:07:03 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Sat Sep 01 2018 09:07:04 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Sat Sep 01 2018 09:11:00 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sat Sep 01 2018 09:11:56 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sat Sep 01 2018 09:11:59 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 09:13:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fBY0XZp0uZR1slGMABM7 Scythe Calls: 16980 (Sat Sep 01 2018 09:13:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 09:13:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rMSgEpVLycibN5zjABM8 Silent Calls: 5706 (Sat Sep 01 2018 09:13:20 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 09:13:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 09:14:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 09:14:46 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 09:18:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 09:18:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 09:18:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 09:19:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: LbMv6624_vNpnBl1ABNp Troll Calls: 39 (Sat Sep 01 2018 09:19:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 09:19:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Rft_2KBQ0YNs8M5VABKp Pluu Calls: 64230 (Sat Sep 01 2018 09:19:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mnafhS4QPNex_HTNABKq Cozi Calls: 64287 (Sat Sep 01 2018 09:19:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 09:19:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 09:19:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 09:19:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 09:19:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: BMmdUdGtZkE_vI-VABNm Sinstrite Calls: 544 (Sat Sep 01 2018 09:19:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: hBVaziaebw5MG0dcABNn Shield Calls: 365 (Sat Sep 01 2018 09:19:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UTMgxuKH_RM2d2RrABNl Curse Calls: 394 (Sat Sep 01 2018 09:19:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 09:19:44 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 09:19:45 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 09:19:45 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 09:51:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 8EsXiy49PPqIvneZABNX Scythe Calls: 81622 (Sat Sep 01 2018 09:51:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tbIraM5Hcm7YrUcjABNZ Silent Calls: 28415 (Sat Sep 01 2018 09:52:00 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 09:52:00 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 09:52:00 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 09:53:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 09:53:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 10:04:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 10:04:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 10:04:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 10:05:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0ZlnvYQQVL-kRN0EABPv Troll Calls: 38 (Sat Sep 01 2018 10:05:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 10:05:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: g5iNfEdA3TIuKlmYABPr Curse Calls: 419 (Sat Sep 01 2018 10:05:35 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: lV_MKigJUUx7AskOABPs Sinstrite Calls: 556 (Sat Sep 01 2018 10:05:35 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: snpAIKJ3XZ1Sub8pABPt Shield Calls: 387 (Sat Sep 01 2018 10:05:35 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 10:05:35 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 10:05:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 10:05:36 GMT+0000 (Coordinated Universal Time)) +start_character: "SpadarFaar" (Sat Sep 01 2018 10:12:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Brutus" (Sat Sep 01 2018 10:12:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Maela" (Sat Sep 01 2018 10:12:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 76h9nzFVOBZL0OW9ABQF SpadarFaar Calls: 3889 (Sat Sep 01 2018 10:17:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Ckz3O3YZnbFz84gqABQG Brutus Calls: 3842 (Sat Sep 01 2018 10:17:59 GMT+0000 (Coordinated Universal Time)) +stop_character: SpadarFaar owner: 4909785279365120 bank: false (Sat Sep 01 2018 10:17:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Brutus owner: 4909785279365120 bank: false (Sat Sep 01 2018 10:18:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yeIxx7n7GtezGaDdABQH Maela Calls: 2979 (Sat Sep 01 2018 10:18:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Maela owner: 4909785279365120 bank: false (Sat Sep 01 2018 10:18:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3MG2VgClkLN5sa61ABNs Pluu Calls: 64761 (Sat Sep 01 2018 10:19:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OP8AVOkxbEuDt0kDABNt Cozi Calls: 64102 (Sat Sep 01 2018 10:19:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 10:19:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 10:19:39 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 10:19:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 10:19:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Buttercup" (Sat Sep 01 2018 10:29:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wZeXpWLnJPF_JXxRABQ9 Buttercup Calls: 10 (Sat Sep 01 2018 10:29:46 GMT+0000 (Coordinated Universal Time)) +stop_character: Buttercup owner: 5736224816889856 bank: false (Sat Sep 01 2018 10:29:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Daisy" (Sat Sep 01 2018 10:36:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dYnAM6AuSu3778soABRU Daisy Calls: 13 (Sat Sep 01 2018 10:36:44 GMT+0000 (Coordinated Universal Time)) +stop_character: Daisy owner: 5736224816889856 bank: false (Sat Sep 01 2018 10:36:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 10:50:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 10:50:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 10:50:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 10:50:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ayPVUwBeL7PSsBlbABR_ Troll Calls: 40 (Sat Sep 01 2018 10:50:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 10:50:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6xEfRp1xgUVvezLMABR- Sinstrite Calls: 536 (Sat Sep 01 2018 10:51:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: G2xVuX73wPBlQqDxABR7 Curse Calls: 387 (Sat Sep 01 2018 10:51:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2fPpedyWHRFGAdF_ABR9 Shield Calls: 370 (Sat Sep 01 2018 10:51:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 10:51:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 10:51:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 10:51:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ha2qxwZrgNep0_QrABPK Scythe Calls: 144151 (Sat Sep 01 2018 10:59:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -HOwChF4RNIdybwQABPM Silent Calls: 50053 (Sat Sep 01 2018 10:59:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 10:59:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 10:59:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 11:00:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 11:00:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xPcAgNo9ETLfCqrEABQe Pluu Calls: 64165 (Sat Sep 01 2018 11:19:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: MNUQPASxuG3Mu3ycABQg Cozi Calls: 64284 (Sat Sep 01 2018 11:19:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 11:19:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 11:19:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 11:19:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 11:19:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 11:36:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 11:36:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 11:36:23 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Sat Sep 01 2018 11:36:29 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Sat Sep 01 2018 11:36:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 11:36:40 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5SuZRX9kTBVujBODABUG Troll Calls: 38 (Sat Sep 01 2018 11:36:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 11:36:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: S6VCCdEAaaWpLbQbABUD Shield Calls: 402 (Sat Sep 01 2018 11:37:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: q0OvxrECFdDn6LU6ABUC Curse Calls: 423 (Sat Sep 01 2018 11:37:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3o_An0OIhKCc6ntAABUE Sinstrite Calls: 526 (Sat Sep 01 2018 11:37:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 11:37:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 11:37:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 11:37:16 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 11:39:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: nDX9iGlAneWDsc_VABSb Scythe Calls: 85774 (Sat Sep 01 2018 11:39:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 11:39:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wbbkQ7ngEPy467dWABSc Silent Calls: 29652 (Sat Sep 01 2018 11:39:20 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 11:39:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 11:40:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 11:40:52 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 11:45:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: W3Tn6MSbMcDncEQGABUT Scythe Calls: 10215 (Sat Sep 01 2018 11:45:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VvyXE81D-uboL-3xABUU Silent Calls: 3453 (Sat Sep 01 2018 11:45:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 11:45:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 11:45:24 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 11:46:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 11:47:06 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 11:47:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Nu6MXP0HfGCXsSfvABUl Scythe Calls: 1166 (Sat Sep 01 2018 11:47:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 11:47:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: kKfaLZxplM7ldnX9ABUn Silent Calls: 245 (Sat Sep 01 2018 11:47:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 11:47:28 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 11:48:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 11:48:49 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 11:48:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: BTrk14q1GNKxDuHNABUs Scythe Calls: 362 (Sat Sep 01 2018 11:48:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 11:48:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: AzOdP4d4hcb8u5p8ABUu Silent Calls: 6 (Sat Sep 01 2018 11:48:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 11:48:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 11:50:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 11:50:14 GMT+0000 (Coordinated Universal Time)) +start_character: "yeahaa" (Sat Sep 01 2018 12:09:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5A_W70hFuS6RmjR3ABVo yeahaa Calls: 20 (Sat Sep 01 2018 12:18:52 GMT+0000 (Coordinated Universal Time)) +stop_character: yeahaa owner: 4765522570772480 bank: false (Sat Sep 01 2018 12:18:53 GMT+0000 (Coordinated Universal Time)) +start_character: "yeahaa" (Sat Sep 01 2018 12:19:59 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 12:22:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 12:22:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 12:22:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 12:22:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: aNzbR5HK4owtJVRYABWT Troll Calls: 39 (Sat Sep 01 2018 12:22:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 12:22:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fYS0HHG2VNpOLAaoABWQ Shield Calls: 499 (Sat Sep 01 2018 12:23:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DKAqYKfo_uROLsW6ABWP Sinstrite Calls: 772 (Sat Sep 01 2018 12:23:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mToIyAQ89V2RDMwaABWO Curse Calls: 536 (Sat Sep 01 2018 12:23:22 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 12:23:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 12:23:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 12:23:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: j6YsJrJThIoDhgNqABTS Pluu Calls: 96860 (Sat Sep 01 2018 12:50:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: gTnCHZSuQ85rVosNABTT Cozi Calls: 96889 (Sat Sep 01 2018 12:50:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 12:50:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 12:50:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 12:50:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 12:50:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7NQD15SqzsNO-cSyABUy Scythe Calls: 137341 (Sat Sep 01 2018 12:52:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: S8_E6iBrR5aiZLzOABU0 Silent Calls: 47715 (Sat Sep 01 2018 12:52:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 12:52:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 12:52:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 12:53:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 12:53:52 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 12:53:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KFD9Jv4abZ3n484pABXq Scythe Calls: 256 (Sat Sep 01 2018 12:53:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 12:53:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ggJtIJ2Y0KCWWl2sABXs Silent Calls: 4 (Sat Sep 01 2018 12:53:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 12:53:53 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 12:55:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 12:55:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TZvpyKgzK2754VdwABWH yeahaa Calls: 6 (Sat Sep 01 2018 12:59:41 GMT+0000 (Coordinated Universal Time)) +stop_character: yeahaa owner: 4765522570772480 bank: false (Sat Sep 01 2018 12:59:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 13:08:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 13:08:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 13:08:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 13:08:40 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OtM2tsUQtrZlfhhnABYa Troll Calls: 38 (Sat Sep 01 2018 13:08:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 13:08:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: beJbTobhASXkj4uFABYY Sinstrite Calls: 563 (Sat Sep 01 2018 13:09:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: I62yRorfKUhGRNJBABYZ Shield Calls: 361 (Sat Sep 01 2018 13:09:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: gR-2udw5y0bqM7XHABYW Curse Calls: 393 (Sat Sep 01 2018 13:09:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 13:09:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 13:09:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 13:09:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: k3lOjOK9GPlabtSmABXw Scythe Calls: 117605 (Sat Sep 01 2018 13:48:36 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: pK8AJA1GODxJaSHhABXy Silent Calls: 40717 (Sat Sep 01 2018 13:48:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 13:48:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 13:48:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3JKSLbQU9J4vEf9WABXe Pluu Calls: 64612 (Sat Sep 01 2018 13:50:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bAp9aCu6FEe8SOHFABXg Cozi Calls: 64514 (Sat Sep 01 2018 13:50:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 13:50:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 13:50:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 13:50:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 13:50:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Buttercup" (Sat Sep 01 2018 13:53:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3GggoKat-eYT6gZ9ABaY Buttercup Calls: 59 (Sat Sep 01 2018 13:53:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Buttercup owner: 5736224816889856 bank: false (Sat Sep 01 2018 13:53:50 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 13:54:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 13:54:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 13:54:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 13:55:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fjDpwvSwfJdvnyXbABaj Troll Calls: 39 (Sat Sep 01 2018 13:55:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 13:55:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Buttercup" (Sat Sep 01 2018 13:55:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: JLmBhcZbeqJxxfo5ABaf Sinstrite Calls: 1129 (Sat Sep 01 2018 13:56:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: sKGkkMCi3g8N4MAVABac Curse Calls: 738 (Sat Sep 01 2018 13:56:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: i42t4qsFAYERB0o7ABae Shield Calls: 662 (Sat Sep 01 2018 13:56:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 13:56:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 13:56:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 13:56:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YXqRS_Llu4IFlzROABam Buttercup Calls: 10 (Sat Sep 01 2018 13:56:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Buttercup owner: 5736224816889856 bank: false (Sat Sep 01 2018 13:56:09 GMT+0000 (Coordinated Universal Time)) +start_character: "MuppPriest" (Sat Sep 01 2018 13:58:45 GMT+0000 (Coordinated Universal Time)) +start_character: "MuppArch" (Sat Sep 01 2018 13:58:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Mupp" (Sat Sep 01 2018 13:58:47 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Sat Sep 01 2018 14:18:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 14:21:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 14:21:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: l0W_oUwZ9Zh-AkwCABbo SweetPea Calls: 29 (Sat Sep 01 2018 14:26:08 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Sat Sep 01 2018 14:26:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: _BnJohBYRiOkqUSxAAVM Foaly Calls: 6 (Sat Sep 01 2018 14:33:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Sat Sep 01 2018 14:33:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Sat Sep 01 2018 14:34:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 14:41:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 14:41:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 14:41:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 14:41:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: HhMwwHDQ8nSpsh_SABcu Troll Calls: 38 (Sat Sep 01 2018 14:41:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 14:41:28 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtod owner: 5209159389675520 (Sat Sep 01 2018 14:41:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UJ53ky_6OhSnOWl-ABcr Curse Calls: 381 (Sat Sep 01 2018 14:41:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OKtECgCXm5wo0WxHABcs Sinstrite Calls: 395 (Sat Sep 01 2018 14:41:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: AFYK3r1v3asYYAgZABct Shield Calls: 355 (Sat Sep 01 2018 14:41:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 14:41:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 14:41:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 14:41:53 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtod owner: 5209159389675520 (Sat Sep 01 2018 14:42:48 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sat Sep 01 2018 14:44:08 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sat Sep 01 2018 14:44:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Q6xn7RtWDOsqapjqABaN Pluu Calls: 64149 (Sat Sep 01 2018 14:50:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ek9wMJS-b-Swq30kABaO Cozi Calls: 64505 (Sat Sep 01 2018 14:50:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 14:50:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 14:50:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 14:50:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 14:50:07 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Sat Sep 01 2018 15:05:37 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Sat Sep 01 2018 15:06:42 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Sat Sep 01 2018 15:11:21 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Sat Sep 01 2018 15:12:51 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Sat Sep 01 2018 15:13:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5tXuRLjP0tV37mkzABd5 SweetPea Calls: 282 (Sat Sep 01 2018 15:14:03 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Sat Sep 01 2018 15:14:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 15:26:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 15:26:53 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 15:26:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 15:27:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: MAiFofoMblOqykF7ABe4 Troll Calls: 39 (Sat Sep 01 2018 15:27:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 15:27:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: W2DBUXgVPUlhS8X-ABNM 0x00 Calls: 16450 (Sat Sep 01 2018 15:27:33 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Sat Sep 01 2018 15:27:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SAG3zKVIR2tx6m9qABe2 Shield Calls: 375 (Sat Sep 01 2018 15:27:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Ocs7zHwea0pYfkGaABe1 Sinstrite Calls: 390 (Sat Sep 01 2018 15:27:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xGAJdOH_J8smhu6AABe0 Curse Calls: 390 (Sat Sep 01 2018 15:27:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 15:27:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 15:27:44 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 15:27:44 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Sat Sep 01 2018 15:28:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rW3PoXasfXIJnjN6ABdJ Pluu Calls: 64689 (Sat Sep 01 2018 15:50:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yGuUrFtj9NksK4gSABdK Cozi Calls: 64373 (Sat Sep 01 2018 15:50:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 15:50:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 15:50:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 15:50:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 15:50:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 16:12:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 16:12:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 16:12:46 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 16:14:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 4AWUoUfIgJoRw2SeABhB Troll Calls: 39 (Sat Sep 01 2018 16:14:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 16:14:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Oou2yN2mrE-OvdbhABg7 Sinstrite Calls: 934 (Sat Sep 01 2018 16:14:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5-cL0XHeyiWYn8QXABg6 Shield Calls: 1074 (Sat Sep 01 2018 16:14:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: V4kYee0_Rv6ZIyPJABg5 Curse Calls: 949 (Sat Sep 01 2018 16:14:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 16:14:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 16:14:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 16:14:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: gKKl24TePU4IjvrvABf5 Pluu Calls: 64426 (Sat Sep 01 2018 16:50:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bnFyiMW6SfE4d2IEABf6 Cozi Calls: 64423 (Sat Sep 01 2018 16:50:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 16:50:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 16:50:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 16:50:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 16:50:07 GMT+0000 (Coordinated Universal Time)) +mount_user: MuppPriest owner: 5552666278100992 (Sat Sep 01 2018 16:52:29 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MuppPriest owner: 5552666278100992 (Sat Sep 01 2018 16:52:35 GMT+0000 (Coordinated Universal Time)) +mount_user: MuppPriest owner: 5552666278100992 (Sat Sep 01 2018 16:52:51 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MuppPriest owner: 5552666278100992 (Sat Sep 01 2018 16:54:21 GMT+0000 (Coordinated Universal Time)) +mount_user: MuppArch owner: 5552666278100992 (Sat Sep 01 2018 16:55:04 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MuppArch owner: 5552666278100992 (Sat Sep 01 2018 16:55:21 GMT+0000 (Coordinated Universal Time)) +mount_user: Mupp owner: 5552666278100992 (Sat Sep 01 2018 16:55:38 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Mupp owner: 5552666278100992 (Sat Sep 01 2018 16:55:52 GMT+0000 (Coordinated Universal Time)) +mount_user: Mupp owner: 5552666278100992 (Sat Sep 01 2018 16:56:07 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Mupp owner: 5552666278100992 (Sat Sep 01 2018 16:56:21 GMT+0000 (Coordinated Universal Time)) +mount_user: Mupp owner: 5552666278100992 (Sat Sep 01 2018 16:56:47 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Mupp owner: 5552666278100992 (Sat Sep 01 2018 16:57:15 GMT+0000 (Coordinated Universal Time)) +start_character: "lissandra" (Sat Sep 01 2018 16:58:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: kBTN1v4NF-gy_k9VABi_ lissandra Calls: 39 (Sat Sep 01 2018 16:59:19 GMT+0000 (Coordinated Universal Time)) +stop_character: lissandra owner: 5793534377459712 bank: false (Sat Sep 01 2018 16:59:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 16:59:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 16:59:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 16:59:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 17:00:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 95RMvk90lgISa1bTABjG Troll Calls: 39 (Sat Sep 01 2018 17:00:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 17:00:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: i4BwQIXazondd8sVABjD Shield Calls: 384 (Sat Sep 01 2018 17:00:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: q4KAXTn5k6f-PjhYABjC Curse Calls: 384 (Sat Sep 01 2018 17:00:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IO9jYZ9xCW6TG0p3ABjE Sinstrite Calls: 366 (Sat Sep 01 2018 17:00:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 17:00:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 17:00:44 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 17:00:44 GMT+0000 (Coordinated Universal Time)) +mount_user: MuppArch owner: 5552666278100992 (Sat Sep 01 2018 17:08:18 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MuppArch owner: 5552666278100992 (Sat Sep 01 2018 17:08:56 GMT+0000 (Coordinated Universal Time)) +mount_user: MuppArch owner: 5552666278100992 (Sat Sep 01 2018 17:09:10 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MuppArch owner: 5552666278100992 (Sat Sep 01 2018 17:09:13 GMT+0000 (Coordinated Universal Time)) +mount_user: MuppArch owner: 5552666278100992 (Sat Sep 01 2018 17:09:22 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MuppArch owner: 5552666278100992 (Sat Sep 01 2018 17:13:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Qz7Lu9zhCKF7x3_gABe- 0x00 Calls: 5411 (Sat Sep 01 2018 17:43:33 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Sat Sep 01 2018 17:43:33 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Sat Sep 01 2018 17:44:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 9OoYBSOolJJGWDqqABBb Trexnamedted Calls: 583531 (Sat Sep 01 2018 17:44:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: GszBoSMSFehZX4RrABBa Trexnamedtom Calls: 579109 (Sat Sep 01 2018 17:44:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 8HG6pVKpaMXKw5l0ABBZ Trexnamedtut Calls: 580405 (Sat Sep 01 2018 17:44:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: nQfWjDGSWnuaACBrABBY Trexnamedtod Calls: 210 (Sat Sep 01 2018 17:44:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Sat Sep 01 2018 17:44:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtod owner: 5209159389675520 bank: false (Sat Sep 01 2018 17:44:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Sat Sep 01 2018 17:44:55 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Sat Sep 01 2018 17:44:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Sat Sep 01 2018 17:44:57 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtom owner: 5209159389675520 (Sat Sep 01 2018 17:45:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 17:45:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 17:45:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 17:45:46 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 17:46:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: BS0o5o-jzO7OzH7gABlK Troll Calls: 39 (Sat Sep 01 2018 17:46:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 17:46:08 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtom owner: 5209159389675520 (Sat Sep 01 2018 17:46:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: U-gG1XJra60hVBRrABlH Shield Calls: 364 (Sat Sep 01 2018 17:46:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 9HrQP-1_3fF0bIPHABlI Sinstrite Calls: 364 (Sat Sep 01 2018 17:46:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: eS47f6UBkO8O7Q-yABlG Curse Calls: 385 (Sat Sep 01 2018 17:46:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 17:46:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 17:46:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 17:46:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Sat Sep 01 2018 17:47:07 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedted owner: 5209159389675520 (Sat Sep 01 2018 17:47:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Sat Sep 01 2018 17:48:18 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedted owner: 5209159389675520 (Sat Sep 01 2018 17:48:22 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtut owner: 5209159389675520 (Sat Sep 01 2018 17:49:12 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtut owner: 5209159389675520 (Sat Sep 01 2018 17:49:16 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtut owner: 5209159389675520 (Sat Sep 01 2018 17:49:32 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtut owner: 5209159389675520 (Sat Sep 01 2018 17:49:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PgiRAYfP1V1bULXTABim Pluu Calls: 64123 (Sat Sep 01 2018 17:50:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: In6vZkzEd1XzvI65ABil Cozi Calls: 64509 (Sat Sep 01 2018 17:50:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 17:50:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 17:50:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 17:50:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 17:50:06 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtut owner: 5209159389675520 (Sat Sep 01 2018 17:51:18 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtut owner: 5209159389675520 (Sat Sep 01 2018 17:51:47 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Lootbot (Sat Sep 01 2018 17:57:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xGXC0pVbBGfLa4GkAADS Lootbot Calls: 1788521 (Sat Sep 01 2018 17:57:04 GMT+0000 (Coordinated Universal Time)) +stop_character: Lootbot owner: 5145329831772160 bank: false (Sat Sep 01 2018 17:57:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Lootbot" (Sat Sep 01 2018 17:57:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: cJ1WjZKP320OFRo5ABlw Lootbot Calls: 39567 (Sat Sep 01 2018 18:28:10 GMT+0000 (Coordinated Universal Time)) +stop_character: Lootbot owner: 5145329831772160 bank: false (Sat Sep 01 2018 18:28:11 GMT+0000 (Coordinated Universal Time)) +start_character: "Lootbot" (Sat Sep 01 2018 18:28:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 18:31:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 18:31:59 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 18:32:01 GMT+0000 (Coordinated Universal Time)) +start_character: "lissandra" (Sat Sep 01 2018 18:32:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 18:32:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: LvZ7pBMjs6ZrCEWAABnU lissandra Calls: 235 (Sat Sep 01 2018 18:32:38 GMT+0000 (Coordinated Universal Time)) +stop_character: lissandra owner: 5793534377459712 bank: false (Sat Sep 01 2018 18:32:40 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rYwi1gYiVCuSa6VLABnW Troll Calls: 39 (Sat Sep 01 2018 18:32:45 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 18:32:45 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zmwVyLCzByvvMr6UABnS Sinstrite Calls: 539 (Sat Sep 01 2018 18:33:11 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2gSKqx0gKjrmruoMABnQ Curse Calls: 561 (Sat Sep 01 2018 18:33:11 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SW9lYtgCNb64fGSvABnT Shield Calls: 543 (Sat Sep 01 2018 18:33:11 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 18:33:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 18:33:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 18:33:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OBzmVJluQF23jIfXABlZ Pluu Calls: 64242 (Sat Sep 01 2018 18:50:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: z3ZjMWnUBf8Bmcm8ABlb Cozi Calls: 64424 (Sat Sep 01 2018 18:50:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 18:50:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 18:50:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 18:50:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 18:50:07 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 18:53:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: gIi7S0wKfbJD6w67ABbw Scythe Calls: 595552 (Sat Sep 01 2018 18:53:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 18:53:23 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Silent (Sat Sep 01 2018 18:53:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: qS0tySYIiuA7uKfzABbx Silent Calls: 207503 (Sat Sep 01 2018 18:53:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 18:53:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 18:54:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 18:54:46 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Sat Sep 01 2018 18:58:31 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Sat Sep 01 2018 18:58:51 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Sat Sep 01 2018 18:58:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uWDJd93-IOTOwwQDABoj SweetPea Calls: 220 (Sat Sep 01 2018 19:01:41 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Sat Sep 01 2018 19:01:42 GMT+0000 (Coordinated Universal Time)) +start_character: "SiDeWaYs2o1o" (Sat Sep 01 2018 19:13:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KN1catzfj_LKzWmpABpN SiDeWaYs2o1o Calls: 713 (Sat Sep 01 2018 19:15:12 GMT+0000 (Coordinated Universal Time)) +stop_character: SiDeWaYs2o1o owner: 4791692741836800 bank: false (Sat Sep 01 2018 19:15:13 GMT+0000 (Coordinated Universal Time)) +start_character: "SiDeWaYs2o1o" (Sat Sep 01 2018 19:15:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: inxeF7zjRBJwmEAEABpT SiDeWaYs2o1o Calls: 124 (Sat Sep 01 2018 19:15:34 GMT+0000 (Coordinated Universal Time)) +stop_character: SiDeWaYs2o1o owner: 4791692741836800 bank: false (Sat Sep 01 2018 19:15:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 19:18:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 19:18:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 19:18:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 19:18:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: eG8Fo0oMJJnH5xp5ABpi Troll Calls: 38 (Sat Sep 01 2018 19:18:35 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 19:18:36 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: XvFsuQsaQB8_txX1ABpf Sinstrite Calls: 374 (Sat Sep 01 2018 19:19:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: MDl1U9TOEF7JfHrNABpe Curse Calls: 379 (Sat Sep 01 2018 19:19:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: lWZvkKdes1XechZlABpg Shield Calls: 348 (Sat Sep 01 2018 19:19:00 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 19:19:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 19:19:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 19:19:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xBNxitT2tq_dL1ZFABlD Trexnamedtom Calls: 77959 (Sat Sep 01 2018 19:29:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Sat Sep 01 2018 19:29:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 1I_J4PXqss_XdCrYABlP Trexnamedted Calls: 77548 (Sat Sep 01 2018 19:29:46 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Sat Sep 01 2018 19:29:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tN8RIR8K7u9Zr7OeABlS Trexnamedtut Calls: 74480 (Sat Sep 01 2018 19:29:51 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Sat Sep 01 2018 19:29:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtod" (Sat Sep 01 2018 19:29:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Sat Sep 01 2018 19:29:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Sat Sep 01 2018 19:30:00 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Sat Sep 01 2018 19:30:00 GMT+0000 (Coordinated Universal Time)) +start_character: "Fafnar" (Sat Sep 01 2018 19:45:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: x0x9H1cdVa_j1SmqABoK Pluu Calls: 64288 (Sat Sep 01 2018 19:50:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wXNko-QEGZ4ijX1sABoJ Cozi Calls: 64372 (Sat Sep 01 2018 19:50:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 19:50:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 19:50:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 19:50:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 19:50:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: eK1azcwuyyvwbEOEABqx Fafnar Calls: 195 (Sat Sep 01 2018 19:50:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Fafnar owner: 5699542062202880 bank: false (Sat Sep 01 2018 19:51:00 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 20:04:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 20:04:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 20:04:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 20:05:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YnMv6QeXI_paQc1WABnF Lootbot Calls: 125882 (Sat Sep 01 2018 20:05:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3Ibm15yBpnIts-VTABro Curse Calls: 467 (Sat Sep 01 2018 20:05:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: o7cx4doVOUuUACJSABrp Sinstrite Calls: 623 (Sat Sep 01 2018 20:05:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: i8kUSgqCX809at86ABrq Shield Calls: 422 (Sat Sep 01 2018 20:05:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6v7KX0-0EBpGyDQHABrt Troll Calls: 39 (Sat Sep 01 2018 20:05:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 20:05:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 20:05:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 20:05:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Lootbot owner: 5145329831772160 bank: false (Sat Sep 01 2018 20:05:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 20:05:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 20:06:39 GMT+0000 (Coordinated Universal Time)) +start_character: "Lootbot" (Sat Sep 01 2018 20:06:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 20:06:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 20:06:45 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vJmbxc8xQ8X6RcPMABr0 Sinstrite Calls: 294 (Sat Sep 01 2018 20:07:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ijEGJyEhwgxvY8IvABrx Curse Calls: 214 (Sat Sep 01 2018 20:07:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: S5XypNl_DEQrHoagABr1 Shield Calls: 175 (Sat Sep 01 2018 20:07:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 20:07:09 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 20:07:09 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 20:07:09 GMT+0000 (Coordinated Universal Time)) +start_character: "SiDeWaYs3" (Sat Sep 01 2018 20:10:23 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Sat Sep 01 2018 20:11:59 GMT+0000 (Coordinated Universal Time)) +start_character: "POOF" (Sat Sep 01 2018 20:12:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: EA5MSWXGZ1pydPxIABr_ SiDeWaYs3 Calls: 70 (Sat Sep 01 2018 20:12:49 GMT+0000 (Coordinated Universal Time)) +stop_character: SiDeWaYs3 owner: 4791692741836800 bank: false (Sat Sep 01 2018 20:12:49 GMT+0000 (Coordinated Universal Time)) +start_character: "MatrixGlitch" (Sat Sep 01 2018 20:13:49 GMT+0000 (Coordinated Universal Time)) +mount_user: MOBSans owner: 6609080732876800 (Sat Sep 01 2018 20:15:28 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MOBSans owner: 6609080732876800 (Sat Sep 01 2018 20:15:30 GMT+0000 (Coordinated Universal Time)) +mount_user: MOBSans owner: 6609080732876800 (Sat Sep 01 2018 20:17:34 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MOBSans owner: 6609080732876800 (Sat Sep 01 2018 20:17:37 GMT+0000 (Coordinated Universal Time)) +mount_user: MOBSans owner: 6609080732876800 (Sat Sep 01 2018 20:17:43 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MOBSans owner: 6609080732876800 (Sat Sep 01 2018 20:17:53 GMT+0000 (Coordinated Universal Time)) +start_character: "sophia" (Sat Sep 01 2018 20:21:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 33HCy_YZhDSG7RQRABsF MOBSans Calls: 2424 (Sat Sep 01 2018 20:21:45 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Sat Sep 01 2018 20:21:46 GMT+0000 (Coordinated Universal Time)) +mount_user: POOF owner: 6609080732876800 (Sat Sep 01 2018 20:21:53 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: POOF owner: 6609080732876800 (Sat Sep 01 2018 20:22:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Bl0As63bC3g2PJyZABsH POOF Calls: 43 (Sat Sep 01 2018 20:22:10 GMT+0000 (Coordinated Universal Time)) +stop_character: POOF owner: 6609080732876800 bank: false (Sat Sep 01 2018 20:22:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 9WxPpLHl4rWhDqarABsi sophia Calls: 87 (Sat Sep 01 2018 20:22:21 GMT+0000 (Coordinated Universal Time)) +stop_character: sophia owner: 5793534377459712 bank: false (Sat Sep 01 2018 20:22:22 GMT+0000 (Coordinated Universal Time)) +start_character: "evelyn" (Sat Sep 01 2018 20:23:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 9jzeot0pZuGVZaigABsM MatrixGlitch Calls: 13 (Sat Sep 01 2018 20:23:55 GMT+0000 (Coordinated Universal Time)) +stop_character: MatrixGlitch owner: 5192957260988416 bank: false (Sat Sep 01 2018 20:23:55 GMT+0000 (Coordinated Universal Time)) +mount_user: evelyn owner: 5793534377459712 (Sat Sep 01 2018 20:25:55 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: evelyn owner: 5793534377459712 (Sat Sep 01 2018 20:26:23 GMT+0000 (Coordinated Universal Time)) +start_character: "BuyMyThings" (Sat Sep 01 2018 20:33:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: P--bXXhS_O5hKMBOABtF BuyMyThings Calls: 44 (Sat Sep 01 2018 20:41:21 GMT+0000 (Coordinated Universal Time)) +mount_user: evelyn owner: 5793534377459712 (Sat Sep 01 2018 20:41:21 GMT+0000 (Coordinated Universal Time)) +stop_character: BuyMyThings owner: 4687219387269120 bank: false (Sat Sep 01 2018 20:41:21 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: evelyn owner: 5793534377459712 (Sat Sep 01 2018 20:41:56 GMT+0000 (Coordinated Universal Time)) +mount_user: evelyn owner: 5793534377459712 (Sat Sep 01 2018 20:42:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Zjpaj2w3SISGMDtRABsp evelyn Calls: 306 (Sat Sep 01 2018 20:42:36 GMT+0000 (Coordinated Universal Time)) +stop_character: evelyn owner: 5793534377459712 bank: true (Sat Sep 01 2018 20:42:36 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6Hv_xGB5ODWI2AXeABq_ Pluu Calls: 64413 (Sat Sep 01 2018 20:50:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: WMHa89yiJOvfP3SKABq- Cozi Calls: 64884 (Sat Sep 01 2018 20:50:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 20:50:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 20:50:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 20:50:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 20:50:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 20:52:27 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 20:52:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 20:52:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 20:52:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: hD9stt7chsQD5g1RABuB Troll Calls: 39 (Sat Sep 01 2018 20:52:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 20:52:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: K4Bfe_3v4H6KiymcABt_ Sinstrite Calls: 346 (Sat Sep 01 2018 20:53:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2QdEAlrqqG_3wDJkABt- Shield Calls: 371 (Sat Sep 01 2018 20:53:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: qP0j0K1RYPSua6QQABt9 Curse Calls: 378 (Sat Sep 01 2018 20:53:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 20:53:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 20:53:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 20:53:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 21:38:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 21:38:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 21:38:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 21:38:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Eve64c_7NZr1GhHRABwE Troll Calls: 38 (Sat Sep 01 2018 21:38:42 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 21:38:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VdHS_p8bscrkvcy8ABwC Sinstrite Calls: 362 (Sat Sep 01 2018 21:39:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: o6KIlprwX8B-9N5LABwB Shield Calls: 372 (Sat Sep 01 2018 21:39:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Ze-aXWPo-bE423X-ABwA Curse Calls: 390 (Sat Sep 01 2018 21:39:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 21:39:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 21:39:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 21:39:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uoD04ehBND2qqX7pABt1 Pluu Calls: 64217 (Sat Sep 01 2018 21:50:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: XIJg8PYWTxUoJ2QLABt2 Cozi Calls: 64629 (Sat Sep 01 2018 21:50:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 21:50:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 21:50:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 21:50:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 21:50:07 GMT+0000 (Coordinated Universal Time)) +start_character: "BuyMyThings" (Sat Sep 01 2018 21:56:11 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NK0CVUyjz7E0mB-GABw4 BuyMyThings Calls: 25 (Sat Sep 01 2018 21:57:14 GMT+0000 (Coordinated Universal Time)) +stop_character: BuyMyThings owner: 4687219387269120 bank: false (Sat Sep 01 2018 21:57:15 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 22:24:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 22:24:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 22:24:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 22:24:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: hYJQORYbRv_RLLq0AByH Troll Calls: 39 (Sat Sep 01 2018 22:24:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 22:24:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5kq5voRIEDU1fopkAByF Sinstrite Calls: 527 (Sat Sep 01 2018 22:24:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0IWqSVt36Y0ZEwXgAByG Shield Calls: 364 (Sat Sep 01 2018 22:24:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: neCvWefW_lBl3RPhAByD Curse Calls: 382 (Sat Sep 01 2018 22:24:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 22:24:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 22:24:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 22:24:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TAhhvXgv_sJfk0DyABwn Pluu Calls: 64379 (Sat Sep 01 2018 22:50:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bMmX7vPSHR06DjKHABwm Cozi Calls: 64576 (Sat Sep 01 2018 22:50:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 22:50:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 22:50:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 22:50:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 22:50:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YMJ4KTC5zQ_ztdBZAAAV Pure Calls: 1976426 (Sat Sep 01 2018 22:53:46 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sat Sep 01 2018 22:53:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sat Sep 01 2018 22:53:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 23:09:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 23:09:59 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 23:10:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 23:10:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mtWDWbBPsdEGlpmhAB0J Troll Calls: 38 (Sat Sep 01 2018 23:10:22 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 23:10:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -QzXzioIZvxpMR_FAB0H Sinstrite Calls: 368 (Sat Sep 01 2018 23:10:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: K4fNjas80g_7b3NNAB0G Shield Calls: 370 (Sat Sep 01 2018 23:10:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VJL_TMEcqpHYnLn1AB0F Curse Calls: 393 (Sat Sep 01 2018 23:10:49 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 23:10:49 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 23:10:49 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 23:10:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7S2blgOwQyP6MWRhABcZ Foaly Calls: 5 (Sat Sep 01 2018 23:11:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Sat Sep 01 2018 23:11:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Sat Sep 01 2018 23:12:38 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sat Sep 01 2018 23:21:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mJdKRrmxi5mBvHvkABoX Scythe Calls: 586185 (Sat Sep 01 2018 23:21:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sat Sep 01 2018 23:21:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NNCLAJRJc7yhUU0WABoY Silent Calls: 203800 (Sat Sep 01 2018 23:21:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sat Sep 01 2018 23:21:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sat Sep 01 2018 23:23:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sat Sep 01 2018 23:23:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6dp3Nm30ymCQoPjMABzO Pluu Calls: 64438 (Sat Sep 01 2018 23:50:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: qWpvLd1rdqkPa3F8ABzN Cozi Calls: 64539 (Sat Sep 01 2018 23:50:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sat Sep 01 2018 23:50:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sat Sep 01 2018 23:50:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sat Sep 01 2018 23:50:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sat Sep 01 2018 23:50:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sat Sep 01 2018 23:55:46 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sat Sep 01 2018 23:55:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sat Sep 01 2018 23:55:50 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sat Sep 01 2018 23:56:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: pImKEcv_KhV4x8l-AB2Q Troll Calls: 39 (Sat Sep 01 2018 23:56:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sat Sep 01 2018 23:56:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2ALGp05_ULZzEUp4AB2N Sinstrite Calls: 395 (Sat Sep 01 2018 23:56:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UyrSwj0uKjtPIoJjAB2M Curse Calls: 378 (Sat Sep 01 2018 23:56:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: llJPSLF0wQXpPvFPAB2O Shield Calls: 359 (Sat Sep 01 2018 23:56:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sat Sep 01 2018 23:56:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sat Sep 01 2018 23:56:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sat Sep 01 2018 23:56:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DJwXY0Um3m1KW6JwAB0R Foaly Calls: 5 (Sun Sep 02 2018 00:01:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Sun Sep 02 2018 00:01:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Sun Sep 02 2018 00:02:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 00:41:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 00:41:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 00:41:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 00:41:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: e2mVm1-hfPJdhmGHAB4S Troll Calls: 38 (Sun Sep 02 2018 00:42:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 00:42:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5ueWj4_Ceqz0VEreAB4Q Sinstrite Calls: 362 (Sun Sep 02 2018 00:42:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Ua23QklhPg8hJOsHAB4R Shield Calls: 346 (Sun Sep 02 2018 00:42:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DXtONJ5_uz2QQBiqAB4O Curse Calls: 372 (Sun Sep 02 2018 00:42:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 00:42:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 00:42:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 00:42:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OzzAfnn47ac4pz2IAB16 Pluu Calls: 64539 (Sun Sep 02 2018 00:50:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UcvdakbBNFEt6gIdAB17 Cozi Calls: 64428 (Sun Sep 02 2018 00:50:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 00:50:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 00:50:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 00:50:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 00:50:08 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Sun Sep 02 2018 01:02:04 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Sun Sep 02 2018 01:02:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: JkcmY8xlHutdV5yzABzZ Pure Calls: 139607 (Sun Sep 02 2018 01:04:10 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 01:04:11 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: MHdVrieFaRNVBqVzAB4q Pluu Calls: 15123 (Sun Sep 02 2018 01:04:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 01:04:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZJrzL-hHFqc2mSpKAB4r Cozi Calls: 15098 (Sun Sep 02 2018 01:04:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 01:04:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: HivVAJ_6LvCfsb08AANn Ploob Calls: 88122 (Sun Sep 02 2018 01:04:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Ploob owner: 4572509340958720 bank: false (Sun Sep 02 2018 01:04:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Ploob" (Sun Sep 02 2018 01:05:00 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 01:05:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 01:05:10 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 01:05:13 GMT+0000 (Coordinated Universal Time)) +start_character: "adbjhfchcfgf" (Sun Sep 02 2018 01:06:43 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 01:14:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: hyNjej5AMv1o0BWqAB0v Scythe Calls: 244531 (Sun Sep 02 2018 01:14:56 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 01:14:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: cs7UGTf6Jbz5eXn5AB0x Silent Calls: 85241 (Sun Sep 02 2018 01:14:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 01:14:57 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Sun Sep 02 2018 01:15:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Carolina" (Sun Sep 02 2018 01:15:59 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 01:16:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 01:16:28 GMT+0000 (Coordinated Universal Time)) +start_character: "TexTheTank" (Sun Sep 02 2018 01:18:49 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Sun Sep 02 2018 01:18:56 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Sun Sep 02 2018 01:20:29 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Sun Sep 02 2018 01:21:05 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Carolina (Sun Sep 02 2018 01:22:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: HJVtK3I1AKA9P2yGAB5X Carolina Calls: 436 (Sun Sep 02 2018 01:22:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZynbG2bS7-uoqEEQAB5c TexTheTank Calls: 108 (Sun Sep 02 2018 01:22:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NS97sDmc36s1HiSlAB5d BlazingSnip Calls: 10 (Sun Sep 02 2018 01:22:04 GMT+0000 (Coordinated Universal Time)) +stop_character: Carolina owner: 6609080732876800 bank: false (Sun Sep 02 2018 01:22:05 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Sun Sep 02 2018 01:22:05 GMT+0000 (Coordinated Universal Time)) +stop_character: TexTheTank owner: 6609080732876800 bank: false (Sun Sep 02 2018 01:22:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Carolina" (Sun Sep 02 2018 01:22:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ASt8T4yvUlHvCUygAB5Q adbjhfchcfgf Calls: 1493 (Sun Sep 02 2018 01:22:17 GMT+0000 (Coordinated Universal Time)) +stop_character: adbjhfchcfgf owner: 5548174556004352 bank: false (Sun Sep 02 2018 01:22:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 01:27:27 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 01:27:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 01:27:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 01:27:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: CgkqDxjure0otlZUAB5i Troll Calls: 39 (Sun Sep 02 2018 01:27:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 01:27:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: LjF1S3fj0fHDbb9cAB5f Curse Calls: 264 (Sun Sep 02 2018 01:28:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Bi4aQTEajf0VESVMAB5h Shield Calls: 242 (Sun Sep 02 2018 01:28:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3K3-MxKibrxC_ZmJAB5g Sinstrite Calls: 277 (Sun Sep 02 2018 01:28:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 01:28:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 01:28:05 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 01:28:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: idtGcLJUQMSGQaI_AB5Y MOBSans Calls: 14 (Sun Sep 02 2018 01:29:11 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Sun Sep 02 2018 01:29:11 GMT+0000 (Coordinated Universal Time)) +start_character: "SansSupport" (Sun Sep 02 2018 01:30:49 GMT+0000 (Coordinated Universal Time)) +mount_user: SansSupport owner: 6609080732876800 (Sun Sep 02 2018 01:30:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: LQI7P4fmYGGgUj5VAB5k SansSupport Calls: 15 (Sun Sep 02 2018 01:31:00 GMT+0000 (Coordinated Universal Time)) +stop_character: SansSupport owner: 6609080732876800 bank: true (Sun Sep 02 2018 01:31:00 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Sun Sep 02 2018 01:33:59 GMT+0000 (Coordinated Universal Time)) +start_character: "TexTheTank" (Sun Sep 02 2018 01:36:57 GMT+0000 (Coordinated Universal Time)) +mount_user: Carolina owner: 6609080732876800 (Sun Sep 02 2018 01:37:37 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Carolina owner: 6609080732876800 (Sun Sep 02 2018 01:37:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: cQvIiDeS__I9lGo8AB5l BlazingSnip Calls: 2824 (Sun Sep 02 2018 01:46:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: W_fZELOngSt6NxNwAB5m TexTheTank Calls: 2229 (Sun Sep 02 2018 01:46:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zYz01mrtL6pivdDyAB5e Carolina Calls: 1958 (Sun Sep 02 2018 01:46:02 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Sun Sep 02 2018 01:46:04 GMT+0000 (Coordinated Universal Time)) +stop_character: Carolina owner: 6609080732876800 bank: false (Sun Sep 02 2018 01:46:04 GMT+0000 (Coordinated Universal Time)) +stop_character: TexTheTank owner: 6609080732876800 bank: false (Sun Sep 02 2018 01:46:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Carolina" (Sun Sep 02 2018 01:46:08 GMT+0000 (Coordinated Universal Time)) +start_character: "TexTheTank" (Sun Sep 02 2018 01:51:06 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Sun Sep 02 2018 01:51:14 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Sun Sep 02 2018 01:51:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: RTqwreybESKDABNZAB5a Scythe Calls: 78917 (Sun Sep 02 2018 01:52:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mFIr31s6bVuMm4cbAB5b Silent Calls: 27380 (Sun Sep 02 2018 01:52:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 01:52:25 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 01:52:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 01:53:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 01:54:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: N2J4sp4E-7l_0MeOAB5r MOBSans Calls: 7 (Sun Sep 02 2018 02:00:22 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Sun Sep 02 2018 02:00:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: D6-7pauZ0D0oGdwxAB5U Pluu Calls: 64479 (Sun Sep 02 2018 02:05:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2Q06PPCE18i6y0yjAB5V Pure Calls: 64486 (Sun Sep 02 2018 02:05:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ewStuEzbQDs5EPQzAB5W Cozi Calls: 64051 (Sun Sep 02 2018 02:05:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 02:05:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 02:05:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 02:05:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 02:05:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 02:05:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 02:05:09 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Sun Sep 02 2018 02:06:29 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Sun Sep 02 2018 02:06:47 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Sun Sep 02 2018 02:08:19 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Sun Sep 02 2018 02:08:33 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Sun Sep 02 2018 02:08:44 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Sun Sep 02 2018 02:08:59 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 02:13:15 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 02:13:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 02:13:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 02:13:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZICD4FEG4t9vanwpAB50 Troll Calls: 39 (Sun Sep 02 2018 02:14:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 02:14:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 9ovJjQV0DJeoXlNeAB5y Sinstrite Calls: 554 (Sun Sep 02 2018 02:14:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uXBvu1fqGVP-lyl8AB5x Curse Calls: 526 (Sun Sep 02 2018 02:14:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: eqQhOqH5Ojt86eC3AB5z Shield Calls: 496 (Sun Sep 02 2018 02:14:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 02:14:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 02:14:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 02:14:30 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Sun Sep 02 2018 02:18:24 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 02:18:27 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Sun Sep 02 2018 02:18:39 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 02:18:46 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 02:18:50 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 02:19:04 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Sun Sep 02 2018 02:20:09 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Sun Sep 02 2018 02:20:33 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Sun Sep 02 2018 02:20:43 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Sun Sep 02 2018 02:21:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: FM2_QQSsRnpKGFJLAB5s Scythe Calls: 64512 (Sun Sep 02 2018 02:23:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: epL89SlNr7heOENbAB5t Silent Calls: 22260 (Sun Sep 02 2018 02:23:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 02:23:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 02:23:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 02:25:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 02:25:27 GMT+0000 (Coordinated Universal Time)) +start_character: "BuyMyThings" (Sun Sep 02 2018 02:30:36 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Sun Sep 02 2018 02:33:00 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Sun Sep 02 2018 02:33:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ifmeXsWZCEIbTxMIAB5u Pluu Calls: 33197 (Sun Sep 02 2018 02:35:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 02:35:40 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: MJLgWQ8Z6lSCHjKOAB5T Ploob Calls: 4245 (Sun Sep 02 2018 02:36:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Ploob owner: 4572509340958720 bank: false (Sun Sep 02 2018 02:36:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: BDjZq6abuVLwZuUuAB5w Cozi Calls: 33111 (Sun Sep 02 2018 02:36:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: QS7X3e4hDbGET_VtAB5v Pure Calls: 33189 (Sun Sep 02 2018 02:36:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 02:36:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 02:36:18 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Sun Sep 02 2018 02:36:42 GMT+0000 (Coordinated Universal Time)) +mount_user: MOBSans owner: 6609080732876800 (Sun Sep 02 2018 02:37:05 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MOBSans owner: 6609080732876800 (Sun Sep 02 2018 02:37:48 GMT+0000 (Coordinated Universal Time)) +start_character: "Ploob" (Sun Sep 02 2018 02:38:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TcGGN57iUAgb0c9tAB55 MOBSans Calls: 193 (Sun Sep 02 2018 02:40:21 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Sun Sep 02 2018 02:40:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: J6u5gL5VWGyYElTQABav Mupp Calls: 122096 (Sun Sep 02 2018 02:41:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Qd_pP0lhoPpGADYvABau MuppPriest Calls: 120490 (Sun Sep 02 2018 02:41:15 GMT+0000 (Coordinated Universal Time)) +Main loop took 23ms (Sun Sep 02 2018 02:41:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Mupp owner: 5552666278100992 bank: false (Sun Sep 02 2018 02:41:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: FoJRvPffFQZx7WbtABaw MuppArch Calls: 220 (Sun Sep 02 2018 02:41:16 GMT+0000 (Coordinated Universal Time)) +stop_character: MuppPriest owner: 5552666278100992 bank: false (Sun Sep 02 2018 02:41:16 GMT+0000 (Coordinated Universal Time)) +stop_character: MuppArch owner: 5552666278100992 bank: false (Sun Sep 02 2018 02:41:16 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 02:44:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 02:44:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: RlwlTI_ioUide-1aAB58 Pluu Calls: 160 (Sun Sep 02 2018 02:44:42 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 02:44:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: BLGk7HNzqxNiQxFjAB54 BuyMyThings Calls: 254 (Sun Sep 02 2018 02:44:58 GMT+0000 (Coordinated Universal Time)) +stop_character: BuyMyThings owner: 4687219387269120 bank: false (Sun Sep 02 2018 02:44:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: QK_SFIjgRzmqjytrAB59 Pure Calls: 86 (Sun Sep 02 2018 02:45:10 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 02:45:10 GMT+0000 (Coordinated Universal Time)) +mount_user: Carolina owner: 6609080732876800 (Sun Sep 02 2018 02:49:59 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Sun Sep 02 2018 02:50:18 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Sun Sep 02 2018 02:50:50 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Carolina owner: 6609080732876800 (Sun Sep 02 2018 02:50:52 GMT+0000 (Coordinated Universal Time)) +start_character: "IsaacSantana" (Sun Sep 02 2018 02:55:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: m-f2eoI27C2w5ORVAB2l Foaly Calls: 448 (Sun Sep 02 2018 02:55:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Sun Sep 02 2018 02:56:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TaMKu42ggsrLs-DWAB5p TexTheTank Calls: 24628 (Sun Sep 02 2018 02:56:41 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC _observer (Sun Sep 02 2018 02:56:41 GMT+0000 (Coordinated Universal Time)) +stop_character: TexTheTank owner: 6609080732876800 bank: false (Sun Sep 02 2018 02:56:41 GMT+0000 (Coordinated Universal Time)) +start_character: "TexTheTank" (Sun Sep 02 2018 02:56:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: aH5qXq-_0eYOzH4hAB6A TexTheTank Calls: 5 (Sun Sep 02 2018 02:58:12 GMT+0000 (Coordinated Universal Time)) +stop_character: TexTheTank owner: 6609080732876800 bank: false (Sun Sep 02 2018 02:58:13 GMT+0000 (Coordinated Universal Time)) +start_character: "SansSupport" (Sun Sep 02 2018 02:58:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IixO-vXzoEzAz3GFAB6D SansSupport Calls: 7 (Sun Sep 02 2018 02:58:37 GMT+0000 (Coordinated Universal Time)) +stop_character: SansSupport owner: 6609080732876800 bank: false (Sun Sep 02 2018 02:58:37 GMT+0000 (Coordinated Universal Time)) +start_character: "TexTheTank" (Sun Sep 02 2018 02:59:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 02:59:27 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 02:59:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 02:59:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Sun Sep 02 2018 03:00:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 03:00:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fTF512mxVLUcKn14AB6I Troll Calls: 39 (Sun Sep 02 2018 03:00:22 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 03:00:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rHBDz2N_11QRLRU8AB6G Sinstrite Calls: 831 (Sun Sep 02 2018 03:00:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mhBKO-de0zRq0J9_AB6H Shield Calls: 537 (Sun Sep 02 2018 03:00:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: cA2erOO9ODzTkzOvAB6F Curse Calls: 582 (Sun Sep 02 2018 03:00:46 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 03:00:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 03:00:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 03:00:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: r5HkJzPU0wfUIWLlAB5_ IsaacSantana Calls: 925 (Sun Sep 02 2018 03:01:25 GMT+0000 (Coordinated Universal Time)) +stop_character: IsaacSantana owner: 6738306504065024 bank: false (Sun Sep 02 2018 03:01:25 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Sun Sep 02 2018 03:09:54 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Sun Sep 02 2018 03:12:37 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 03:16:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: gI5btd05NTBcA2hwAB52 Scythe Calls: 111160 (Sun Sep 02 2018 03:16:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 03:16:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: iP7fDCs4DDjZY6KoAB53 Silent Calls: 38649 (Sun Sep 02 2018 03:16:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 03:16:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 03:17:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 03:17:27 GMT+0000 (Coordinated Universal Time)) +Main loop took 30ms (Sun Sep 02 2018 03:19:04 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 03:27:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ouLUrCltMQXsc7W6AB6J Scythe Calls: 21280 (Sun Sep 02 2018 03:27:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SRJqyod81pIk6VTaAB6K Silent Calls: 7361 (Sun Sep 02 2018 03:27:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 03:27:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 03:27:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 03:28:25 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 03:28:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ecBZTJqVBCiE8MU0AB6M Scythe Calls: 186 (Sun Sep 02 2018 03:28:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 03:28:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 03:29:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 03:29:49 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 03:29:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: MyDFXDX2IBYjIDsBAB6O Scythe Calls: 248 (Sun Sep 02 2018 03:29:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 03:29:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: f96f3FHCNNd6RCYoAB6P Silent Calls: 5 (Sun Sep 02 2018 03:29:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 03:29:50 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 03:31:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 03:31:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 03:38:34 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Sun Sep 02 2018 03:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 03:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 03:38:35 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Sun Sep 02 2018 03:38:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: F36Qt4OPmlB8U5NiAB6V Cozi Calls: 357 (Sun Sep 02 2018 03:39:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 03:39:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: WopOqc2kOwKYftmMAB6U Pure Calls: 362 (Sun Sep 02 2018 03:39:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 03:39:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 03:39:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: f7x1MtF594lALS2HAB6Z Pure Calls: 134 (Sun Sep 02 2018 03:40:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 03:40:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 03:40:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: l6XuVFyw2QHgWeTvAB6Y Cozi Calls: 124 (Sun Sep 02 2018 03:41:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 03:41:16 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 03:41:24 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 03:41:26 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 03:45:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rLCy-LQGDqajN5BDAB6R Scythe Calls: 30743 (Sun Sep 02 2018 03:45:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: pS1Vhqq23_SOWbsKAB6S Silent Calls: 10581 (Sun Sep 02 2018 03:45:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 03:45:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 03:45:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 03:45:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Maela" (Sun Sep 02 2018 03:45:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 03:45:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 03:45:48 GMT+0000 (Coordinated Universal Time)) +start_character: "SpadarFaar" (Sun Sep 02 2018 03:45:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: RuvCoOXky_KVgi4YAB6b Cozi Calls: 5188 (Sun Sep 02 2018 03:46:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 03:46:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 03:46:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: hmvn4NK7MteIPpReAB6k Troll Calls: 39 (Sun Sep 02 2018 03:46:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Paloo" (Sun Sep 02 2018 03:46:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 03:46:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Brutus" (Sun Sep 02 2018 03:46:14 GMT+0000 (Coordinated Universal Time)) +mount_user: Paloo owner: 4572509340958720 (Sun Sep 02 2018 03:46:15 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 03:46:23 GMT+0000 (Coordinated Universal Time)) +mount_user: Maela owner: 4909785279365120 (Sun Sep 02 2018 03:46:26 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:27 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:27 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:28 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:28 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:28 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:28 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:28 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:28 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:28 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:28 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:28 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:28 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:29 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:29 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:29 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:29 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:29 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:29 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:29 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 03:46:30 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:30 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:30 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:30 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:30 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:30 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:30 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:30 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:30 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:30 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:30 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:31 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:31 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:31 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:31 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:31 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:31 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:31 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:31 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:31 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:31 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:31 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:31 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:32 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:32 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:32 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:32 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:32 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:32 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:32 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:32 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:32 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:32 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:33 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:33 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:33 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:33 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:33 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:33 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:33 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:33 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:33 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:33 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:34 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:34 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:34 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:34 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:34 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:34 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:34 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:34 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:34 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:34 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:35 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:35 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 03:46:35 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: SpadarFaar in-bank: Maela (Sun Sep 02 2018 03:46:35 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Maela owner: 4909785279365120 (Sun Sep 02 2018 03:46:35 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: j5hjFb-wvdZ-KR4vAB6g Sinstrite Calls: 565 (Sun Sep 02 2018 03:46:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: EB763nNFIxvNKZ0jAB6e Curse Calls: 398 (Sun Sep 02 2018 03:46:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: a0nGIYD-uP9toA7aAB6i Shield Calls: 369 (Sun Sep 02 2018 03:46:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 03:46:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 03:46:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 03:46:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Jyb_5WeD389rzx1sAB6h SpadarFaar Calls: 614 (Sun Sep 02 2018 03:46:43 GMT+0000 (Coordinated Universal Time)) +stop_character: SpadarFaar owner: 4909785279365120 bank: false (Sun Sep 02 2018 03:46:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: hCSa7HI5te8ng2PAAB6f Maela Calls: 374 (Sun Sep 02 2018 03:46:45 GMT+0000 (Coordinated Universal Time)) +stop_character: Maela owner: 4909785279365120 bank: false (Sun Sep 02 2018 03:46:45 GMT+0000 (Coordinated Universal Time)) +start_character: "SpadarFaar" (Sun Sep 02 2018 03:47:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Maela" (Sun Sep 02 2018 03:47:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dl7ORtCd1prN836eAB6l Paloo Calls: 15 (Sun Sep 02 2018 03:47:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Paloo owner: 4572509340958720 bank: true (Sun Sep 02 2018 03:47:53 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluet" (Sun Sep 02 2018 03:47:57 GMT+0000 (Coordinated Universal Time)) +mount_user: Pluet owner: 4572509340958720 (Sun Sep 02 2018 03:48:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: phru6IbvjpCgy9FPAB6v Pluet Calls: 20 (Sun Sep 02 2018 03:48:22 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluet owner: 4572509340958720 bank: true (Sun Sep 02 2018 03:48:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 03:48:27 GMT+0000 (Coordinated Universal Time)) +mount_user: Cozi owner: 4572509340958720 (Sun Sep 02 2018 03:48:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 1lmRnhVNaFDnP0LEAB6w Cozi Calls: 54 (Sun Sep 02 2018 03:48:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: true (Sun Sep 02 2018 03:48:51 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Sun Sep 02 2018 03:49:06 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Sun Sep 02 2018 03:49:12 GMT+0000 (Coordinated Universal Time)) +start_character: "SansSupport" (Sun Sep 02 2018 03:49:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: JqnmFHZeh0J2UQMFAB6x SansSupport Calls: 3 (Sun Sep 02 2018 03:49:15 GMT+0000 (Coordinated Universal Time)) +stop_character: SansSupport owner: 6609080732876800 bank: false (Sun Sep 02 2018 03:49:15 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Sun Sep 02 2018 03:49:24 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Sun Sep 02 2018 03:49:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: z-orFRutMjIYE0kIAB5q BlazingSnip Calls: 14979 (Sun Sep 02 2018 03:49:34 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Sun Sep 02 2018 03:49:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Paloo" (Sun Sep 02 2018 03:49:35 GMT+0000 (Coordinated Universal Time)) +mount_user: Paloo owner: 4572509340958720 (Sun Sep 02 2018 03:49:39 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Paloo owner: 4572509340958720 (Sun Sep 02 2018 03:49:58 GMT+0000 (Coordinated Universal Time)) +start_character: "SansSupport" (Sun Sep 02 2018 03:49:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: MIDYhQeIkVFwFCf1AB6y SansSupport Calls: 275 (Sun Sep 02 2018 03:54:04 GMT+0000 (Coordinated Universal Time)) +stop_character: SansSupport owner: 6609080732876800 bank: false (Sun Sep 02 2018 03:54:04 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Sun Sep 02 2018 03:54:21 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Sun Sep 02 2018 03:55:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: hTAjvw1cpgkD8al3AB61 BlazingSnip Calls: 366 (Sun Sep 02 2018 03:56:07 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Sun Sep 02 2018 03:56:07 GMT+0000 (Coordinated Universal Time)) +start_character: "SansSupport" (Sun Sep 02 2018 03:56:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 79pO4WUB7FRu4uXmAB6z Paloo Calls: 766 (Sun Sep 02 2018 04:02:11 GMT+0000 (Coordinated Universal Time)) +stop_character: Paloo owner: 4572509340958720 bank: false (Sun Sep 02 2018 04:02:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Paloo" (Sun Sep 02 2018 04:02:16 GMT+0000 (Coordinated Universal Time)) +mount_user: SpadarFaar owner: 4909785279365120 (Sun Sep 02 2018 04:06:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wWxiDcWxCkrcvICyAB6s SpadarFaar Calls: 12077 (Sun Sep 02 2018 04:07:10 GMT+0000 (Coordinated Universal Time)) +stop_character: SpadarFaar owner: 4909785279365120 bank: true (Sun Sep 02 2018 04:07:11 GMT+0000 (Coordinated Universal Time)) +start_character: "Conrad" (Sun Sep 02 2018 04:07:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bYZFU8iHdSXvNQ9mAB63 SansSupport Calls: 3310 (Sun Sep 02 2018 04:07:28 GMT+0000 (Coordinated Universal Time)) +stop_character: SansSupport owner: 6609080732876800 bank: false (Sun Sep 02 2018 04:07:28 GMT+0000 (Coordinated Universal Time)) +mount_user: Conrad owner: 4909785279365120 (Sun Sep 02 2018 04:07:36 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: WbtPxtyrbt5AoQD-AB65 Conrad Calls: 28 (Sun Sep 02 2018 04:07:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Conrad owner: 4909785279365120 bank: true (Sun Sep 02 2018 04:07:52 GMT+0000 (Coordinated Universal Time)) +start_character: "SansSupport" (Sun Sep 02 2018 04:07:53 GMT+0000 (Coordinated Universal Time)) +start_character: "Meadow" (Sun Sep 02 2018 04:08:22 GMT+0000 (Coordinated Universal Time)) +mount_user: Meadow owner: 4909785279365120 (Sun Sep 02 2018 04:08:31 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Meadow owner: 4909785279365120 (Sun Sep 02 2018 04:09:24 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Sun Sep 02 2018 04:10:18 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Sun Sep 02 2018 04:10:23 GMT+0000 (Coordinated Universal Time)) +mount_user: Meadow owner: 4909785279365120 (Sun Sep 02 2018 04:10:33 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Meadow owner: 4909785279365120 (Sun Sep 02 2018 04:10:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: opZUtYvhNui1DRejAB67 Meadow Calls: 122 (Sun Sep 02 2018 04:11:40 GMT+0000 (Coordinated Universal Time)) +stop_character: Meadow owner: 4909785279365120 bank: false (Sun Sep 02 2018 04:11:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rOtvaF0jDUI1v3jAAB66 SansSupport Calls: 66 (Sun Sep 02 2018 04:11:42 GMT+0000 (Coordinated Universal Time)) +stop_character: SansSupport owner: 6609080732876800 bank: false (Sun Sep 02 2018 04:11:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Meadow" (Sun Sep 02 2018 04:11:44 GMT+0000 (Coordinated Universal Time)) +mount_user: Meadow owner: 4909785279365120 (Sun Sep 02 2018 04:11:54 GMT+0000 (Coordinated Universal Time)) + +==================== +Exception[socket.on: code]: +Cannot set property 'code' of undefined +Stacktrace: +TypeError: Cannot set property 'code' of undefined + at /home/ubuntu/server/server.js:1960:27 + at Socket.g (/home/ubuntu/server/server.js:1812:10) + at Socket.emit (events.js:182:13) + at /home/ubuntu/node_modules/socket.io/lib/socket.js:528:12 + at process._tickCallback (internal/process/next_tick.js:61:11) +==================== + +start_character: "BlazingSnip" (Sun Sep 02 2018 04:11:58 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Meadow owner: 4909785279365120 (Sun Sep 02 2018 04:12:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fMoYY4tbpiWS0S4tAB62 MOBSans Calls: 759 (Sun Sep 02 2018 04:12:19 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Sun Sep 02 2018 04:12:19 GMT+0000 (Coordinated Universal Time)) +mount_user: Meadow owner: 4909785279365120 (Sun Sep 02 2018 04:12:36 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Meadow owner: 4909785279365120 (Sun Sep 02 2018 04:12:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vohDFdzn64DXl_JSAB6W Pluu Calls: 38852 (Sun Sep 02 2018 04:14:11 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 04:14:11 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 04:15:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 9na6p6dx8xXzqjs3AB64 Paloo Calls: 419 (Sun Sep 02 2018 04:16:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Paloo owner: 4572509340958720 bank: false (Sun Sep 02 2018 04:16:24 GMT+0000 (Coordinated Universal Time)) +start_character: "Paloo" (Sun Sep 02 2018 04:16:28 GMT+0000 (Coordinated Universal Time)) +mount_user: Maela owner: 4909785279365120 (Sun Sep 02 2018 04:17:44 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:44 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:44 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:45 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:45 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:45 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:45 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:45 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:45 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:46 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:46 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:46 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:46 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:46 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:46 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:46 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:46 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:47 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:47 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:47 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:47 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:47 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:47 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:47 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:47 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:47 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:47 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:48 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:48 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:48 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:48 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:48 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:48 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:48 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:48 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:49 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:49 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:49 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:49 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:49 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:49 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:49 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:49 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:50 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:50 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:50 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:50 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:50 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:50 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:50 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:50 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:51 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:51 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:51 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:51 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:51 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:51 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:51 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:51 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:51 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:51 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:52 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:52 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:52 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:52 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:52 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:52 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:53 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:53 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:53 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:53 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:53 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:53 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:53 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:53 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:54 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:54 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:54 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:54 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:54 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:54 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:54 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:54 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:54 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:54 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:55 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:55 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:55 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:55 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:55 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:56 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:56 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:56 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:56 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:56 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:56 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:56 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:56 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:56 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:56 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:57 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:57 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:57 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:57 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:57 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:57 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:57 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:57 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:58 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:58 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:58 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:58 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:58 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:58 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:58 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:58 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:59 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:59 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:59 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:59 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:59 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:59 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:59 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:59 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:17:59 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:17:59 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:00 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:00 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:00 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:00 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:00 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:00 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:00 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:00 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:01 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:01 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:01 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:01 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:01 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:01 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:01 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:01 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:02 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:02 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:02 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:02 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:02 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:02 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:02 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:02 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:02 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:02 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:03 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:03 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:03 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:03 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:03 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:03 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:03 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:03 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:04 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:04 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:04 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:04 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:18:04 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:18:04 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Maela owner: 4909785279365120 (Sun Sep 02 2018 04:18:04 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 04:24:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ieY1OYwNclPx30vTAB6n Scythe Calls: 82727 (Sun Sep 02 2018 04:24:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 04:24:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vjoyhabgWrKrT4_3AB6o Silent Calls: 28722 (Sun Sep 02 2018 04:24:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 04:24:07 GMT+0000 (Coordinated Universal Time)) +mount_user: Paloo owner: 4572509340958720 (Sun Sep 02 2018 04:24:34 GMT+0000 (Coordinated Universal Time)) +mount_user: Maela owner: 4909785279365120 (Sun Sep 02 2018 04:24:38 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:39 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:39 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:39 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:39 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:39 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:39 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:39 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:39 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:40 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:40 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:40 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:40 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:40 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:40 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:40 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:40 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:40 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:40 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:41 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:41 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:41 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:41 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:41 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:41 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:41 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:41 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:42 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:42 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:42 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:42 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:42 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:42 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:42 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:42 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:43 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:43 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:43 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:43 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:43 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:43 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:43 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:43 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:43 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:43 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:44 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:44 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:44 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:44 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:44 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:44 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:44 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:44 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:45 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:45 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:45 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:45 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:45 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:45 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:45 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:45 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:46 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:46 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:46 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:46 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:46 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:46 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:46 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:46 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:47 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:47 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:47 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:47 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:47 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:47 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:47 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:47 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:48 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:48 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:48 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:48 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:48 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:48 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:48 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:48 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:48 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:48 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:49 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:49 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:49 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:49 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:49 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:49 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:49 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:49 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:50 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:50 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:50 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:50 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:50 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:50 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:50 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:50 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:51 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:51 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:51 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:51 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:51 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:51 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:51 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:51 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:52 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:52 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:52 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:52 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:52 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:52 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:52 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:52 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:53 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:53 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:53 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:53 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:53 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:53 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:53 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:53 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:54 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:54 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:54 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:54 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:54 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:54 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:54 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:54 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:55 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:55 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:55 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:55 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:55 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:56 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:56 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:56 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:56 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:56 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:56 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:56 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:56 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:57 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:57 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:57 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:57 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:57 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:57 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:57 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yUw6Ci8zE8Hxd_21AB6_ Paloo Calls: 316 (Sun Sep 02 2018 04:24:58 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:58 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:58 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:58 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:58 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:59 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:59 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:59 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Paloo owner: 4572509340958720 bank: true (Sun Sep 02 2018 04:24:59 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:59 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:59 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:59 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:59 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:24:59 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:24:59 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:00 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:00 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:00 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:00 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:00 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:00 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:00 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:00 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Sun Sep 02 2018 04:25:01 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:01 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:01 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:01 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:01 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:01 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 04:25:02 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:02 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:02 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:02 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:02 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:02 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:02 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:02 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:02 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:02 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:02 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:03 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:03 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:03 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:03 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:03 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:03 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:03 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:03 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:03 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:03 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:04 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:04 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:04 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:04 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:04 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:04 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:04 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:04 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:04 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:04 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:04 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:04 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:05 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:05 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:05 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:05 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:05 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:05 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:05 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:05 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:05 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:05 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:06 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:06 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Sun Sep 02 2018 04:25:06 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:06 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:06 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:07 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:07 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:07 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:07 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:07 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:07 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:07 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:07 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:08 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:08 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:08 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:08 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:08 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:08 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:08 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:08 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:08 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:08 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:09 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:09 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:09 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:09 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:09 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:09 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:09 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:09 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:09 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:09 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:10 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:10 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:10 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:10 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:10 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:10 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:10 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:10 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:10 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:10 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:11 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:11 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:11 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:11 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:11 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:11 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:11 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:11 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:12 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:25:12 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Maela owner: 4909785279365120 (Sun Sep 02 2018 04:25:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 04:25:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 04:25:25 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:26 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:25:33 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Sun Sep 02 2018 04:26:01 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Sun Sep 02 2018 04:26:06 GMT+0000 (Coordinated Universal Time)) +mount_user: Cozi owner: 4572509340958720 (Sun Sep 02 2018 04:26:11 GMT+0000 (Coordinated Universal Time)) +mount_user: Meadow owner: 4909785279365120 (Sun Sep 02 2018 04:26:16 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Cozi owner: 4572509340958720 (Sun Sep 02 2018 04:26:18 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Meadow owner: 4909785279365120 (Sun Sep 02 2018 04:26:35 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: d__qL2nrs25xvqgxAB68 Meadow Calls: 334 (Sun Sep 02 2018 04:26:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Meadow owner: 4909785279365120 bank: false (Sun Sep 02 2018 04:26:39 GMT+0000 (Coordinated Universal Time)) +start_character: "SpadarFaar" (Sun Sep 02 2018 04:26:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: suOynDDoEGwU2I98AB7A Cozi Calls: 115 (Sun Sep 02 2018 04:26:48 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 04:26:48 GMT+0000 (Coordinated Universal Time)) +start_character: "Haunted" (Sun Sep 02 2018 04:26:54 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Sun Sep 02 2018 04:27:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KxaHRJ0LE5d5Kk2wAB7E Haunted Calls: 37 (Sun Sep 02 2018 04:27:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Haunted owner: 4572509340958720 bank: false (Sun Sep 02 2018 04:27:26 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Sun Sep 02 2018 04:27:26 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Sun Sep 02 2018 04:27:49 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Sun Sep 02 2018 04:27:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Maela owner: 4909785279365120 (Sun Sep 02 2018 04:28:11 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:12 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:12 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:12 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:12 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:13 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:13 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:13 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:13 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:13 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:13 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:13 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:13 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:13 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:13 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:14 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:14 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:14 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:14 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:14 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:14 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:14 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:14 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:15 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:15 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:15 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:15 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:15 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:15 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:15 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:15 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:16 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:16 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:16 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:16 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:16 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:16 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:16 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:16 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:16 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:16 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:17 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:17 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:17 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:17 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:17 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:17 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:17 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:17 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:17 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:17 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:18 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:18 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:18 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:18 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:18 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:18 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:18 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:18 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:18 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:18 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:19 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:19 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:19 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:19 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:19 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:19 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:19 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:19 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:20 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:20 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:20 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:20 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:20 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:20 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:20 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:20 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:20 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:20 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:21 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:21 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:21 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:21 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:21 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:21 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:21 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:21 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:21 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:21 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:22 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:22 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:22 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:22 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:22 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:22 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:22 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:22 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:22 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:22 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:23 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:23 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:23 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:23 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:23 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:23 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:23 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:23 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:24 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:24 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:24 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:24 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:24 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:24 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:24 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:24 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:25 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:25 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:25 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:25 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:25 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:25 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:25 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:25 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:25 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:25 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:26 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:26 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:26 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:26 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:26 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:26 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:26 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:26 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:27 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:27 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:27 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:27 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:27 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:27 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:27 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:27 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:28 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:28 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:28 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:28 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:28 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:28 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:28 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:28 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:28 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:28 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:29 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:29 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:29 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:29 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:29 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:29 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:30 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:30 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:30 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:30 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:30 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:30 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:30 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:30 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:30 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:30 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:31 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:31 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:31 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:31 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:31 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:31 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:31 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:31 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:32 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:32 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:32 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:32 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Maela owner: 4909785279365120 (Sun Sep 02 2018 04:28:32 GMT+0000 (Coordinated Universal Time)) +mount_user: Maela owner: 4909785279365120 (Sun Sep 02 2018 04:28:36 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:38 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:38 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:38 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:38 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:38 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:38 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:38 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:38 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:39 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:39 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:39 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:39 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:39 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:39 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:39 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:39 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:39 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:39 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:40 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:40 GMT+0000 (Coordinated Universal Time)) +mount_user: Brutus owner: 4909785279365120 (Sun Sep 02 2018 04:28:40 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: Brutus in-bank: Maela (Sun Sep 02 2018 04:28:40 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Maela owner: 4909785279365120 (Sun Sep 02 2018 04:28:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Trin" (Sun Sep 02 2018 04:29:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yT0H9YqVJK32gQJ8AB7G Trin Calls: 12 (Sun Sep 02 2018 04:29:41 GMT+0000 (Coordinated Universal Time)) +stop_character: Trin owner: 4909785279365120 bank: false (Sun Sep 02 2018 04:29:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 04:29:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5KWafHS1eUwEU4dOAB7D SpadarFaar Calls: 2070 (Sun Sep 02 2018 04:29:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7tq6EJ3GiZdgGXMJAB6m Brutus Calls: 1521 (Sun Sep 02 2018 04:29:57 GMT+0000 (Coordinated Universal Time)) +stop_character: SpadarFaar owner: 4909785279365120 bank: false (Sun Sep 02 2018 04:29:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Brutus owner: 4909785279365120 bank: false (Sun Sep 02 2018 04:29:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3iTPVb6Z66rBjZO0AB6t Maela Calls: 11476 (Sun Sep 02 2018 04:29:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Maela owner: 4909785279365120 bank: false (Sun Sep 02 2018 04:29:59 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Sun Sep 02 2018 04:30:43 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Sun Sep 02 2018 04:30:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bGxeC7PpM52Q2xqWAB6C Foaly Calls: 215 (Sun Sep 02 2018 04:30:51 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Sun Sep 02 2018 04:30:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 04:31:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 04:31:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 04:31:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 04:31:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UyzbaOWAnBgZK4ZvAB7O Troll Calls: 39 (Sun Sep 02 2018 04:32:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 04:32:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: cW1ALjbCOi_l2ZGcAB7M Shield Calls: 377 (Sun Sep 02 2018 04:32:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: si03Iw2xTirf-Dr0AB7N Sinstrite Calls: 513 (Sun Sep 02 2018 04:32:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DypC4KvDhZLYaHSDAB7L Curse Calls: 383 (Sun Sep 02 2018 04:32:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 04:32:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 04:32:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 04:32:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Sun Sep 02 2018 04:36:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 1EEmxCDPQifnWjPXAB6- Pluu Calls: 25259 (Sun Sep 02 2018 04:38:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZCLPJTuog_LrBFhRAB6c Pure Calls: 61770 (Sun Sep 02 2018 04:38:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: RCFybYXPfnofpE80AB7I Cozi Calls: 9359 (Sun Sep 02 2018 04:38:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 04:38:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 04:38:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Wolf773" (Sun Sep 02 2018 04:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 04:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 04:38:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 04:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 04:39:03 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 04:45:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: eC5QhcDKF0ju-1MiAB7B Scythe Calls: 43648 (Sun Sep 02 2018 04:45:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 04:45:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 41o9PxfvMbSzCj2pAB7C Silent Calls: 15014 (Sun Sep 02 2018 04:45:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 04:45:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 04:46:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 04:46:27 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 04:58:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 22IRipCKZrDnOz1wAB7V Scythe Calls: 25938 (Sun Sep 02 2018 04:58:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 04:58:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: g0UwvaHMDyRqqOVrAB7W Silent Calls: 9036 (Sun Sep 02 2018 04:58:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 04:58:15 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 04:59:20 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 04:59:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: EnYsfC2j8fHtx2cBAB7X Scythe Calls: 242 (Sun Sep 02 2018 04:59:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 04:59:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 05:00:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Mq6NhKex3-TkUoE4AB7Q Wolf773 Calls: 1737 (Sun Sep 02 2018 05:00:51 GMT+0000 (Coordinated Universal Time)) +stop_character: Wolf773 owner: 5947761083023360 bank: false (Sun Sep 02 2018 05:00:52 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 05:00:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: d4jZbKwUODl7Xr3HAB7Y Scythe Calls: 274 (Sun Sep 02 2018 05:00:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 05:00:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 05:02:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 05:02:24 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 05:11:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yaDfNuLSy6bjirtgAB7a Scythe Calls: 19964 (Sun Sep 02 2018 05:11:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 05:11:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: u1FfMOeR-c5iWaxLAB7b Silent Calls: 6757 (Sun Sep 02 2018 05:11:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 05:11:16 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 05:12:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 05:13:08 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 05:13:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: V1F0s01M8MWOT_X4AB7c Scythe Calls: 1789 (Sun Sep 02 2018 05:13:46 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 05:13:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: k2POhheYWi61sXD-AB7d Silent Calls: 485 (Sun Sep 02 2018 05:13:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 05:13:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 05:15:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 05:15:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 05:17:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 05:17:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 05:17:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 05:17:44 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 05:17:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mluXZmGpoKkkYzY1AB7e Scythe Calls: 5945 (Sun Sep 02 2018 05:17:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 05:17:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: JV-NoUWUtnenqIpxAB7j Troll Calls: 39 (Sun Sep 02 2018 05:17:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 05:17:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PbB7kOqfe5LNYSHYAB7f Silent Calls: 1970 (Sun Sep 02 2018 05:17:55 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 05:17:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UfnZVyTISEHVi6s3AB7i Shield Calls: 357 (Sun Sep 02 2018 05:18:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rqfh43uaK1uXTZtfAB7h Sinstrite Calls: 527 (Sun Sep 02 2018 05:18:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SKB5r4gV9UvtZPqlAB7g Curse Calls: 382 (Sun Sep 02 2018 05:18:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 05:18:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 05:18:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 05:18:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 05:19:10 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 05:19:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: oTFVM7eD1RaLnkBwAB7k Scythe Calls: 237 (Sun Sep 02 2018 05:19:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 05:19:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 05:20:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 05:20:48 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 05:26:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 61eQlAhSmCwHRXsdAB7m Scythe Calls: 12442 (Sun Sep 02 2018 05:26:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 05:26:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ogZGYWvpR2XgprlRAB7n Silent Calls: 4221 (Sun Sep 02 2018 05:26:20 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 05:26:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 05:27:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 05:27:31 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 05:28:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7IWIEDJ3VN_RWhgwAB7o Scythe Calls: 2192 (Sun Sep 02 2018 05:28:22 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 05:28:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uiJOopOyH3EalPfLAB7p Silent Calls: 672 (Sun Sep 02 2018 05:28:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 05:28:24 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 05:29:45 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 05:29:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mwWEsmu7escPJt0hAB7q Scythe Calls: 335 (Sun Sep 02 2018 05:29:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 05:29:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 05:31:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 05:31:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NMWgDLS5RBR7ovxdABlC 0x00 Calls: 29484 (Sun Sep 02 2018 05:33:33 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Sun Sep 02 2018 05:33:34 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Sun Sep 02 2018 05:34:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TUd3OdsnsHhkch7CAB7R Pluu Calls: 64680 (Sun Sep 02 2018 05:38:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zRrRBi06XbYZ_cK2AB7U Pure Calls: 63850 (Sun Sep 02 2018 05:38:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: WE_UcHVuLroZAQqHAB7T Cozi Calls: 64383 (Sun Sep 02 2018 05:38:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 05:38:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 05:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 05:38:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 05:38:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 05:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 05:38:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 06:03:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 06:03:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 06:03:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 06:04:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: lr-2TIPsPXSJp7NyAB71 Troll Calls: 39 (Sun Sep 02 2018 06:04:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 06:04:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: WWEJv25fmteOjHxkAB7z Sinstrite Calls: 1051 (Sun Sep 02 2018 06:04:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xK3b0zzyN9jVcC3XAB7y Curse Calls: 875 (Sun Sep 02 2018 06:04:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DcnlT5NCFLmFzlzxAB70 Shield Calls: 709 (Sun Sep 02 2018 06:04:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 06:04:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 06:04:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 06:04:59 GMT+0000 (Coordinated Universal Time)) +start_character: "yeahaa" (Sun Sep 02 2018 06:08:51 GMT+0000 (Coordinated Universal Time)) +start_character: "crionic" (Sun Sep 02 2018 06:13:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dPRvfPAPZ3DK-18BAB73 crionic Calls: 73 (Sun Sep 02 2018 06:14:52 GMT+0000 (Coordinated Universal Time)) +stop_character: crionic owner: 4765522570772480 bank: false (Sun Sep 02 2018 06:14:52 GMT+0000 (Coordinated Universal Time)) +start_character: "Brutus" (Sun Sep 02 2018 06:18:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Maela" (Sun Sep 02 2018 06:18:05 GMT+0000 (Coordinated Universal Time)) +start_character: "SpadarFaar" (Sun Sep 02 2018 06:18:07 GMT+0000 (Coordinated Universal Time)) +start_character: "crionic" (Sun Sep 02 2018 06:19:38 GMT+0000 (Coordinated Universal Time)) +mount_user: crionic owner: 4765522570772480 (Sun Sep 02 2018 06:21:15 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: crionic owner: 4765522570772480 (Sun Sep 02 2018 06:22:01 GMT+0000 (Coordinated Universal Time)) +mount_user: crionic owner: 4765522570772480 (Sun Sep 02 2018 06:22:52 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: crionic owner: 4765522570772480 (Sun Sep 02 2018 06:22:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SxpCmpkQhn8rsCp-AB76 SpadarFaar Calls: 4199 (Sun Sep 02 2018 06:23:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yN18iL-h9PByirr9AB74 Brutus Calls: 589 (Sun Sep 02 2018 06:23:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yAUlCPwKOo_CQrV1AB75 Maela Calls: 3012 (Sun Sep 02 2018 06:23:49 GMT+0000 (Coordinated Universal Time)) +stop_character: Maela owner: 4909785279365120 bank: false (Sun Sep 02 2018 06:23:49 GMT+0000 (Coordinated Universal Time)) +stop_character: SpadarFaar owner: 4909785279365120 bank: false (Sun Sep 02 2018 06:23:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Brutus owner: 4909785279365120 bank: false (Sun Sep 02 2018 06:23:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: z2L4ACeH6gMn2gzeAB78 crionic Calls: 209 (Sun Sep 02 2018 06:24:19 GMT+0000 (Coordinated Universal Time)) +stop_character: crionic owner: 4765522570772480 bank: false (Sun Sep 02 2018 06:24:19 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Sun Sep 02 2018 06:26:41 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 06:27:00 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 06:27:10 GMT+0000 (Coordinated Universal Time)) +start_character: "crionic" (Sun Sep 02 2018 06:27:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YQrh69_Ii2yFizZPAB7_ crionic Calls: 39 (Sun Sep 02 2018 06:28:18 GMT+0000 (Coordinated Universal Time)) +stop_character: crionic owner: 4765522570772480 bank: false (Sun Sep 02 2018 06:28:19 GMT+0000 (Coordinated Universal Time)) +start_character: "chin" (Sun Sep 02 2018 06:31:24 GMT+0000 (Coordinated Universal Time)) +mount_user: yeahaa owner: 4765522570772480 (Sun Sep 02 2018 06:32:24 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: yeahaa owner: 4765522570772480 (Sun Sep 02 2018 06:33:20 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 06:35:57 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 06:36:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: riFeMGaEJZPInilqAB7x Pluu Calls: 64177 (Sun Sep 02 2018 06:38:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dGm5h6Z-wfXtHIazAB7v Pure Calls: 64135 (Sun Sep 02 2018 06:38:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OwFFzBTALp7L1p9-AB7w Cozi Calls: 64705 (Sun Sep 02 2018 06:38:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 06:38:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 06:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 06:38:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 06:38:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 06:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 06:38:35 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Sun Sep 02 2018 06:40:54 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Sun Sep 02 2018 06:41:07 GMT+0000 (Coordinated Universal Time)) +mount_user: chin owner: 4765522570772480 (Sun Sep 02 2018 06:43:53 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: chin owner: 4765522570772480 (Sun Sep 02 2018 06:44:06 GMT+0000 (Coordinated Universal Time)) +mount_user: yeahaa owner: 4765522570772480 (Sun Sep 02 2018 06:44:26 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: yeahaa owner: 4765522570772480 (Sun Sep 02 2018 06:44:43 GMT+0000 (Coordinated Universal Time)) +mount_user: chin owner: 4765522570772480 (Sun Sep 02 2018 06:44:55 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: chin owner: 4765522570772480 (Sun Sep 02 2018 06:45:06 GMT+0000 (Coordinated Universal Time)) +mount_user: chin owner: 4765522570772480 (Sun Sep 02 2018 06:45:54 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: chin owner: 4765522570772480 (Sun Sep 02 2018 06:45:58 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 06:46:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xusKuZA6vASiNn4vAB7s Scythe Calls: 164740 (Sun Sep 02 2018 06:46:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UcpEtRdSgYFaHDhFAB7t Silent Calls: 57272 (Sun Sep 02 2018 06:46:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 06:46:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 06:46:15 GMT+0000 (Coordinated Universal Time)) +mount_user: chin owner: 4765522570772480 (Sun Sep 02 2018 06:46:34 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: chin owner: 4765522570772480 (Sun Sep 02 2018 06:46:39 GMT+0000 (Coordinated Universal Time)) +mount_user: chin owner: 4765522570772480 (Sun Sep 02 2018 06:46:47 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: chin owner: 4765522570772480 (Sun Sep 02 2018 06:46:51 GMT+0000 (Coordinated Universal Time)) +mount_user: chin owner: 4765522570772480 (Sun Sep 02 2018 06:47:07 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: chin owner: 4765522570772480 (Sun Sep 02 2018 06:47:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 06:47:32 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 06:47:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 4NMoovyGyDiZkljlAB8J Scythe Calls: 234 (Sun Sep 02 2018 06:47:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 06:47:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 06:47:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TpvmZiTMbDEsSxXeAB8K Silent Calls: 4 (Sun Sep 02 2018 06:47:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 06:47:39 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 06:48:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 06:49:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 06:49:53 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 06:49:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 06:49:59 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 06:50:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ddYfafDbOEpWJDmkAB8R Troll Calls: 38 (Sun Sep 02 2018 06:50:22 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 06:50:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: qtCMxZJg0qRXaiPmAB8P Shield Calls: 383 (Sun Sep 02 2018 06:50:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VGQSa2BqYtW7B4YFAB8Q Sinstrite Calls: 542 (Sun Sep 02 2018 06:50:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VXzdrtbE9uvIBQrbAB8O Curse Calls: 395 (Sun Sep 02 2018 06:50:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 06:50:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 06:50:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 06:50:48 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 06:51:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zGju3gIeMqOv5vhmAB8M Scythe Calls: 6152 (Sun Sep 02 2018 06:51:46 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 06:51:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KCdVnGW2m9aGSO5fAB8N Silent Calls: 2079 (Sun Sep 02 2018 06:51:48 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 06:51:48 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 06:53:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 06:53:10 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 06:54:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Gbp-EFlIKFFZZtVCAB8S Scythe Calls: 2978 (Sun Sep 02 2018 06:54:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 06:54:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: CY3WrV-FgJr4YqXFAB8T Silent Calls: 1005 (Sun Sep 02 2018 06:54:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 06:54:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 06:55:50 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 06:55:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Hhd2qIe55JtFNlzjAB8C chin Calls: 826 (Sun Sep 02 2018 06:56:28 GMT+0000 (Coordinated Universal Time)) +stop_character: chin owner: 4765522570772480 bank: false (Sun Sep 02 2018 06:56:30 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 06:56:45 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 06:56:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: LR3bNeKJcGmc1YVUAB8U Scythe Calls: 2214 (Sun Sep 02 2018 06:56:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 1efDHHI8lmqPfB_ZAB8V Silent Calls: 689 (Sun Sep 02 2018 06:56:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 06:56:51 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 06:56:51 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 06:57:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TMut_SWciCrYYyqjAB7- SweetPea Calls: 194 (Sun Sep 02 2018 06:57:51 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Sun Sep 02 2018 06:57:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 06:58:12 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 06:58:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TOA8JPeahtdNVgqzAB8W Scythe Calls: 213 (Sun Sep 02 2018 06:58:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 06:58:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 06:59:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 06:59:47 GMT+0000 (Coordinated Universal Time)) +mount_user: yeahaa owner: 4765522570772480 (Sun Sep 02 2018 07:01:16 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: yeahaa owner: 4765522570772480 (Sun Sep 02 2018 07:02:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VQqv8QuFPF4pWFuGAB72 yeahaa Calls: 133 (Sun Sep 02 2018 07:04:20 GMT+0000 (Coordinated Universal Time)) +stop_character: yeahaa owner: 4765522570772480 bank: false (Sun Sep 02 2018 07:04:20 GMT+0000 (Coordinated Universal Time)) +start_character: "yeahaa" (Sun Sep 02 2018 07:05:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: H_dSEfRa_IVcsyB9AB5o Carolina Calls: 66714 (Sun Sep 02 2018 07:05:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Carolina owner: 6609080732876800 bank: false (Sun Sep 02 2018 07:05:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: MLop8oEKrxxkzMT8AB6E TexTheTank Calls: 78832 (Sun Sep 02 2018 07:05:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: O34Ntl7rtQnYz25iAB69 BlazingSnip Calls: 34594 (Sun Sep 02 2018 07:05:59 GMT+0000 (Coordinated Universal Time)) +stop_character: TexTheTank owner: 6609080732876800 bank: false (Sun Sep 02 2018 07:06:00 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Sun Sep 02 2018 07:06:00 GMT+0000 (Coordinated Universal Time)) +start_character: "Carolina" (Sun Sep 02 2018 07:08:06 GMT+0000 (Coordinated Universal Time)) +start_character: "choko" (Sun Sep 02 2018 07:16:32 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 07:19:13 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 07:19:18 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 07:30:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Xr1HX_52NFS5hY14AB8Y Scythe Calls: 67708 (Sun Sep 02 2018 07:30:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 07:30:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: pEpZBtdkwTAFKG8RAB8Z Silent Calls: 23406 (Sun Sep 02 2018 07:30:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 07:30:28 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 07:32:02 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 07:32:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: oyyQVYsY4XRH4JOBAB8d Scythe Calls: 339 (Sun Sep 02 2018 07:32:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 07:32:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SaiX9yLR26llG18mAB7u 0x00 Calls: 23878 (Sun Sep 02 2018 07:34:23 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Sun Sep 02 2018 07:34:23 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Sun Sep 02 2018 07:34:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 07:35:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 07:35:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 07:35:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 07:36:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: WXKPJ834eI2MRVgjAB8k Troll Calls: 39 (Sun Sep 02 2018 07:36:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 07:36:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZezDNa-6c_IPEFs8AB8j Shield Calls: 514 (Sun Sep 02 2018 07:36:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: quAEUKiXwSUJWo8KAB8i Sinstrite Calls: 761 (Sun Sep 02 2018 07:36:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5C8lZv6fCwkE5l5hAB8h Curse Calls: 527 (Sun Sep 02 2018 07:36:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 07:36:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 07:36:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 07:36:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7XCyj62-yP4vpNgbAB8F Pluu Calls: 64267 (Sun Sep 02 2018 07:38:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TmesbMDS8WlX4Q1DAB8H Pure Calls: 64423 (Sun Sep 02 2018 07:38:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: O2-RnYutNzYyoqlOAB8G Cozi Calls: 64336 (Sun Sep 02 2018 07:38:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 07:38:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 07:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 07:38:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 07:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 07:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 07:38:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: G-Fc-S1QXnG11QLHAB8g 0x00 Calls: 23949 (Sun Sep 02 2018 07:49:34 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Sun Sep 02 2018 07:49:34 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Sun Sep 02 2018 07:50:39 GMT+0000 (Coordinated Universal Time)) +start_character: "BuyMyThings" (Sun Sep 02 2018 07:58:30 GMT+0000 (Coordinated Universal Time)) +start_character: "lissandra" (Sun Sep 02 2018 08:03:36 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SFINbue79Wbwko8zAB8q lissandra Calls: 81 (Sun Sep 02 2018 08:04:08 GMT+0000 (Coordinated Universal Time)) +stop_character: lissandra owner: 5793534377459712 bank: false (Sun Sep 02 2018 08:04:09 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: brXMBTcvoBB0YelAAB8c choko Calls: 5160 (Sun Sep 02 2018 08:11:01 GMT+0000 (Coordinated Universal Time)) +stop_character: choko owner: 4765522570772480 bank: false (Sun Sep 02 2018 08:11:01 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Sun Sep 02 2018 08:11:04 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Sun Sep 02 2018 08:11:21 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Sun Sep 02 2018 08:11:25 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Sun Sep 02 2018 08:11:37 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Sun Sep 02 2018 08:11:57 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Sun Sep 02 2018 08:12:02 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Sun Sep 02 2018 08:13:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7AELFDOO4sPNIRI_AB8p BuyMyThings Calls: 129 (Sun Sep 02 2018 08:13:21 GMT+0000 (Coordinated Universal Time)) +stop_character: BuyMyThings owner: 4687219387269120 bank: true (Sun Sep 02 2018 08:13:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 08:21:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 08:21:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 08:21:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 08:22:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 1qVs9542uz0OHivDAB8u Troll Calls: 39 (Sun Sep 02 2018 08:22:22 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 08:22:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: EmByCXlYYrsZKiBMAB8s Sinstrite Calls: 546 (Sun Sep 02 2018 08:22:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: CPs9qzYmjdvU9Gl5AB8t Shield Calls: 367 (Sun Sep 02 2018 08:22:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PSOWlaTJU6MGH7gAAB8r Curse Calls: 392 (Sun Sep 02 2018 08:22:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 08:22:48 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 08:22:48 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 08:22:48 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 08:30:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 08:30:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PVHipv0AHdD58IanAB8l Pluu Calls: 64401 (Sun Sep 02 2018 08:38:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5EbzupzdCgxJ_aiwAB8m Pure Calls: 64110 (Sun Sep 02 2018 08:38:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: BX9sdn_HpRLUzWNHAB8n Cozi Calls: 64602 (Sun Sep 02 2018 08:38:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 08:38:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 08:38:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 08:38:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 08:38:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 08:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 08:38:35 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Sun Sep 02 2018 08:44:09 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Sun Sep 02 2018 08:44:10 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Sun Sep 02 2018 08:56:19 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Sun Sep 02 2018 08:56:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zLZkk7XD86urdMGdAB8x Silent Calls: 21547 (Sun Sep 02 2018 08:58:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 08:58:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 08:58:48 GMT+0000 (Coordinated Universal Time)) +mount_user: Scythe owner: 6243983994912768 (Sun Sep 02 2018 09:00:00 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Scythe owner: 6243983994912768 (Sun Sep 02 2018 09:00:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: m57Ht2jmw8gtzaEkAB8w Scythe Calls: 62718 (Sun Sep 02 2018 09:01:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uAS7AryWI7C0sUPLAB81 Silent Calls: 2555 (Sun Sep 02 2018 09:01:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 09:01:25 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 09:01:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 09:01:38 GMT+0000 (Coordinated Universal Time)) +mount_user: Scythe owner: 6243983994912768 (Sun Sep 02 2018 09:01:53 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Scythe owner: 6243983994912768 (Sun Sep 02 2018 09:02:21 GMT+0000 (Coordinated Universal Time)) +mount_user: Scythe owner: 6243983994912768 (Sun Sep 02 2018 09:02:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Rocky" (Sun Sep 02 2018 09:04:23 GMT+0000 (Coordinated Universal Time)) +mount_user: Rocky owner: 4832405143683072 (Sun Sep 02 2018 09:04:56 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Rocky owner: 4832405143683072 (Sun Sep 02 2018 09:05:12 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Scythe owner: 6243983994912768 (Sun Sep 02 2018 09:05:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 09:05:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 09:07:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 09:07:46 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 09:07:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SSqYhK5xyDXgf9U9AB84 Silent Calls: 2438 (Sun Sep 02 2018 09:07:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 09:07:53 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 09:07:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: N5gS06Zz1w2lVVdqAB88 Silent Calls: 163 (Sun Sep 02 2018 09:08:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 09:08:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 09:08:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TX8s5Lyu7Mkpn_uIAB8- Troll Calls: 39 (Sun Sep 02 2018 09:08:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 09:08:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 09:08:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: AdCQax8BWpvYJ8ksAB86 Shield Calls: 560 (Sun Sep 02 2018 09:08:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xRmG4RTih1EWjJDSAB87 Sinstrite Calls: 770 (Sun Sep 02 2018 09:08:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vUc7RZUEwPOPYb4JAB85 Curse Calls: 552 (Sun Sep 02 2018 09:08:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 09:08:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 09:08:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 09:08:59 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 09:21:48 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 09:21:51 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 09:22:03 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 09:22:09 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 09:22:11 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 09:22:17 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 09:22:45 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 09:22:50 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC 0x00 (Sun Sep 02 2018 09:23:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: gqRsqG812rYHqZWeAB8o 0x00 Calls: 29513 (Sun Sep 02 2018 09:23:07 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Sun Sep 02 2018 09:23:07 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Sun Sep 02 2018 09:23:16 GMT+0000 (Coordinated Universal Time)) +mount_user: Rocky owner: 4832405143683072 (Sun Sep 02 2018 09:24:28 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Rocky owner: 4832405143683072 (Sun Sep 02 2018 09:24:40 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: sERPq0RyY-3Q8TSiAB83 Rocky Calls: 3797 (Sun Sep 02 2018 09:24:48 GMT+0000 (Coordinated Universal Time)) +stop_character: Rocky owner: 4832405143683072 bank: false (Sun Sep 02 2018 09:24:48 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 09:24:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: RZTxzfc1-Dp7lz6BAB82 Scythe Calls: 37470 (Sun Sep 02 2018 09:24:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 09:24:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: H_nkUCgSWNvSgERCAB9A Silent Calls: 12300 (Sun Sep 02 2018 09:24:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 09:24:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 09:26:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 09:26:18 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 09:29:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: hfJW8OpP0WQasW3GAB9C Scythe Calls: 7921 (Sun Sep 02 2018 09:29:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0OHsVbahVBia0FVaAB9D Silent Calls: 2706 (Sun Sep 02 2018 09:29:51 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 09:29:51 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 09:29:52 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 09:30:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 09:31:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 928RQDLfdmab2jbcAB8a yeahaa Calls: 125 (Sun Sep 02 2018 09:37:32 GMT+0000 (Coordinated Universal Time)) +stop_character: yeahaa owner: 4765522570772480 bank: false (Sun Sep 02 2018 09:37:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Olx4I_LJl0_Ui4R5AB8y Pluu Calls: 64841 (Sun Sep 02 2018 09:38:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: lwdOMczNSB6fGO_bAB8z Pure Calls: 64272 (Sun Sep 02 2018 09:38:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: m414CnXQCZtpcjnJAB80 Cozi Calls: 64077 (Sun Sep 02 2018 09:38:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 09:38:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 09:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 09:38:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 09:38:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 09:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 09:38:35 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Sun Sep 02 2018 09:41:58 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 09:42:23 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 09:42:31 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 09:42:58 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 09:43:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: LUI7DpId7r1WmbaMAB9J SweetPea Calls: 178 (Sun Sep 02 2018 09:44:01 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Sun Sep 02 2018 09:44:02 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 09:44:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Tmo9eGQlbG_hOdq0AB9E Scythe Calls: 29355 (Sun Sep 02 2018 09:44:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 09:44:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: khozHY329ygZ8rwjAB9F Silent Calls: 10094 (Sun Sep 02 2018 09:44:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 09:44:15 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 09:45:35 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 09:45:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xbWct7P7AT0QFF0PAB9K Scythe Calls: 244 (Sun Sep 02 2018 09:45:42 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 09:45:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 09:47:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 09:47:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 09:53:54 GMT+0000 (Coordinated Universal Time)) +start_character: "MuppPriest" (Sun Sep 02 2018 09:53:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Mupp" (Sun Sep 02 2018 09:53:57 GMT+0000 (Coordinated Universal Time)) +start_character: "MuppArch" (Sun Sep 02 2018 09:53:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 09:53:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 09:53:59 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Sun Sep 02 2018 09:54:05 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Sun Sep 02 2018 09:54:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 09:54:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0tPHPbAShGjVkjbmAB9T Troll Calls: 39 (Sun Sep 02 2018 09:54:22 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 09:54:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: MnJexhOxeVekmrLaAB9R Shield Calls: 381 (Sun Sep 02 2018 09:54:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 07qHfgjtP4M0eBVoAB9S Sinstrite Calls: 375 (Sun Sep 02 2018 09:54:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: XC6Aml16XjDUbg76AB9Q Curse Calls: 411 (Sun Sep 02 2018 09:54:48 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 09:54:48 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 09:54:48 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 09:54:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: eWYaij5qjwz8ADDVAB9B 0x00 Calls: 2076 (Sun Sep 02 2018 10:05:34 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Sun Sep 02 2018 10:05:34 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Sun Sep 02 2018 10:06:56 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 10:26:01 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 10:26:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: AkjrcXmlv2nx0V5bAB9I Pluu Calls: 64561 (Sun Sep 02 2018 10:38:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KCh57kBpXeYBZEoUAB9H Pure Calls: 64196 (Sun Sep 02 2018 10:38:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UugGhCx1ULPnUwsrAB9G Cozi Calls: 64307 (Sun Sep 02 2018 10:38:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 10:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 10:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 10:38:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 10:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 10:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 10:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 10:39:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 10:39:46 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 10:39:48 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 10:40:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 1h79JuNqeLPouGtIAB9c Troll Calls: 39 (Sun Sep 02 2018 10:40:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 10:40:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: A0k9zwhofdGiRy3gAB9b Sinstrite Calls: 392 (Sun Sep 02 2018 10:40:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: c7xXV2Wb9KdTP3Y5AB9Z Curse Calls: 421 (Sun Sep 02 2018 10:40:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: n31NrvyjriftcqvTAB9a Shield Calls: 408 (Sun Sep 02 2018 10:40:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 10:40:40 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 10:40:40 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 10:40:40 GMT+0000 (Coordinated Universal Time)) +start_character: "BuyMyThings" (Sun Sep 02 2018 10:59:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 4aP_CvkpPiZrNm5HAB9e BuyMyThings Calls: 38 (Sun Sep 02 2018 11:01:00 GMT+0000 (Coordinated Universal Time)) +stop_character: BuyMyThings owner: 4687219387269120 bank: false (Sun Sep 02 2018 11:01:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 11:25:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 11:25:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 11:25:39 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 11:25:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dKLGwLRFwuPT94_SAB9i Troll Calls: 39 (Sun Sep 02 2018 11:26:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 11:26:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: S3Myh3s5-sRUo71bAB9f Curse Calls: 400 (Sun Sep 02 2018 11:26:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: BIp4WDebtMUuwRqKAB9h Shield Calls: 359 (Sun Sep 02 2018 11:26:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 9LW25kSYOpEi1yQjAB9g Sinstrite Calls: 564 (Sun Sep 02 2018 11:26:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 11:26:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 11:26:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 11:26:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IdM_Rc6DAYE7FLn7AB9P MuppArch Calls: 28 (Sun Sep 02 2018 11:35:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: A_kiBYiWBGWvMwE5AB9N MuppPriest Calls: 15498 (Sun Sep 02 2018 11:35:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: I5PA9FUD4hzr2hkqAB9O Mupp Calls: 15588 (Sun Sep 02 2018 11:35:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Mupp owner: 5552666278100992 bank: false (Sun Sep 02 2018 11:35:18 GMT+0000 (Coordinated Universal Time)) +stop_character: MuppPriest owner: 5552666278100992 bank: false (Sun Sep 02 2018 11:35:18 GMT+0000 (Coordinated Universal Time)) +stop_character: MuppArch owner: 5552666278100992 bank: false (Sun Sep 02 2018 11:35:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uyi2p5NTp39fVaflAB9Y Pluu Calls: 64436 (Sun Sep 02 2018 11:38:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: EvtQ2fYm5h3UYgrLAB9W Pure Calls: 64480 (Sun Sep 02 2018 11:38:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fj-j7V8H_iyvJe4lAB9X Cozi Calls: 64259 (Sun Sep 02 2018 11:38:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 11:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 11:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 11:38:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 11:38:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 11:38:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 11:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "BuyMyThings" (Sun Sep 02 2018 12:01:32 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Sun Sep 02 2018 12:02:12 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Sun Sep 02 2018 12:02:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 8aaNevGTeZevkwR9AB9m BuyMyThings Calls: 55 (Sun Sep 02 2018 12:02:26 GMT+0000 (Coordinated Universal Time)) +stop_character: BuyMyThings owner: 4687219387269120 bank: false (Sun Sep 02 2018 12:02:28 GMT+0000 (Coordinated Universal Time)) +start_character: "TexTheTank" (Sun Sep 02 2018 12:07:56 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Sun Sep 02 2018 12:08:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 12:11:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 12:11:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 12:11:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 12:11:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 9APeTfgfqCwazAVsAB9s Troll Calls: 39 (Sun Sep 02 2018 12:11:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 12:11:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0jWtWNpsGERPE_l7AB9r Sinstrite Calls: 273 (Sun Sep 02 2018 12:12:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: oe0ve2jaWmTLVHfFAB9q Shield Calls: 305 (Sun Sep 02 2018 12:12:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SR4UlbxHrCcoX-rbAB9p Curse Calls: 303 (Sun Sep 02 2018 12:12:05 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 12:12:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 12:12:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 12:12:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SZO8Ox0rrfARdzeUAB9o BlazingSnip Calls: 3001 (Sun Sep 02 2018 12:28:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 8NjbF3aWAnfXCXlTAB8b Carolina Calls: 81869 (Sun Sep 02 2018 12:28:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mqQav3WRd4zmeP6vAB9n TexTheTank Calls: 5596 (Sun Sep 02 2018 12:28:34 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Sun Sep 02 2018 12:28:35 GMT+0000 (Coordinated Universal Time)) +stop_character: Carolina owner: 6609080732876800 bank: false (Sun Sep 02 2018 12:28:35 GMT+0000 (Coordinated Universal Time)) +stop_character: TexTheTank owner: 6609080732876800 bank: false (Sun Sep 02 2018 12:28:38 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Sun Sep 02 2018 12:28:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Carolina" (Sun Sep 02 2018 12:29:07 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Sun Sep 02 2018 12:29:12 GMT+0000 (Coordinated Universal Time)) +start_character: "TexTheTank" (Sun Sep 02 2018 12:29:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PTdNKuUHRAuQURCNAB9l Pluu Calls: 64270 (Sun Sep 02 2018 12:38:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: qEN7HukqiNu1iaTcAB9k Pure Calls: 64012 (Sun Sep 02 2018 12:38:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7br6JYdKBM0HxMQkAB9j Cozi Calls: 64596 (Sun Sep 02 2018 12:38:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 12:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 12:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 12:38:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 12:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 12:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 12:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 12:57:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 12:57:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 12:57:19 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Sun Sep 02 2018 12:57:24 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Sun Sep 02 2018 12:57:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 12:57:35 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: iooxP0a8j-qnBkfRAB95 Troll Calls: 39 (Sun Sep 02 2018 12:57:42 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 12:57:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tXehI8dnSOccQCxVAB93 Sinstrite Calls: 532 (Sun Sep 02 2018 12:58:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YGyXuKbJKVepSQmpAB94 Shield Calls: 364 (Sun Sep 02 2018 12:58:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: M2avkYwgfNY-q-KzAB92 Curse Calls: 405 (Sun Sep 02 2018 12:58:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 12:58:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 12:58:09 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 12:58:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Buttercup" (Sun Sep 02 2018 13:34:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UZamSmtB-p1Yz5oFAB97 Buttercup Calls: 19 (Sun Sep 02 2018 13:34:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Buttercup owner: 5736224816889856 bank: false (Sun Sep 02 2018 13:34:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Buttercup" (Sun Sep 02 2018 13:36:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: JHNWQKLWB-pcIGczAB98 Buttercup Calls: 15 (Sun Sep 02 2018 13:36:45 GMT+0000 (Coordinated Universal Time)) +stop_character: Buttercup owner: 5736224816889856 bank: false (Sun Sep 02 2018 13:36:45 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: c02URgzFnw6s2d4RAB9z Pluu Calls: 64478 (Sun Sep 02 2018 13:38:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VRsms0LgzQ7zOr3IAB90 Pure Calls: 63913 (Sun Sep 02 2018 13:38:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: h2vLV8KlQGOej_cVAB91 Cozi Calls: 64311 (Sun Sep 02 2018 13:38:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 13:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 13:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 13:38:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 13:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 13:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 13:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Sun Sep 02 2018 13:40:14 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 13:43:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 13:43:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 13:43:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 13:43:11 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 13:43:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 13:43:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: lAjhW7B9grm6PuaoAB-E Troll Calls: 39 (Sun Sep 02 2018 13:43:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 13:43:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2ujCZuilMp5J_AGBABry Lootbot Calls: 1410081 (Sun Sep 02 2018 13:43:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KeRfxq99l8TSMSlTAB-B Curse Calls: 217 (Sun Sep 02 2018 13:43:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VNAwe7pwGxj1WnjAAB-C Sinstrite Calls: 195 (Sun Sep 02 2018 13:43:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: q-8ZGOTNrZ1cWE_YAB-D Shield Calls: 178 (Sun Sep 02 2018 13:43:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Lootbot owner: 5145329831772160 bank: false (Sun Sep 02 2018 13:43:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 13:43:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 13:43:35 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 13:43:35 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Zb16cdP1FeX_8cTdAB-A SweetPea Calls: 190 (Sun Sep 02 2018 13:44:01 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Sun Sep 02 2018 13:44:02 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Sun Sep 02 2018 13:44:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 13:45:00 GMT+0000 (Coordinated Universal Time)) +start_character: "Lootbot" (Sun Sep 02 2018 13:45:00 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 13:45:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 13:45:06 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 13:45:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: XWqauXnidg9OaYYoAB-I Curse Calls: 186 (Sun Sep 02 2018 13:45:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 9W2m1tBav5FiPO3dAB-K Sinstrite Calls: 225 (Sun Sep 02 2018 13:45:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NrY1Kh0q6LjYuXzfAB-J Shield Calls: 166 (Sun Sep 02 2018 13:45:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 13:45:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 13:45:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 13:45:26 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 13:47:59 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 14:30:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 14:30:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 14:30:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 14:31:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: gkr1-IE0_uSCT1KDAB-P Troll Calls: 39 (Sun Sep 02 2018 14:31:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 14:31:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: S1BN6w38ihC2IDY9AB-O Shield Calls: 356 (Sun Sep 02 2018 14:31:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: iOU30BgFHyfwT7keAB-N Sinstrite Calls: 563 (Sun Sep 02 2018 14:31:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: iLOhN-_D1C_1uIMMAB-M Curse Calls: 386 (Sun Sep 02 2018 14:31:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 14:31:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 14:31:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 14:31:40 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Sun Sep 02 2018 14:36:00 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Sun Sep 02 2018 14:36:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: kPdSRQ8h-cgFGBYPAB9V 0x00 Calls: 10967 (Sun Sep 02 2018 14:37:35 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Sun Sep 02 2018 14:37:35 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7GsOQo0Pl2cby0TrAB99 Pluu Calls: 64363 (Sun Sep 02 2018 14:38:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: i0zVB8-ifClJEHiPAB9- Pure Calls: 64614 (Sun Sep 02 2018 14:38:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dujgsPI-5y4MwDQcAB9_ Cozi Calls: 64161 (Sun Sep 02 2018 14:38:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 14:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 14:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 14:38:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 14:38:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 14:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 14:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Sun Sep 02 2018 14:38:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 9Huq0HytTOyYUCirAB-G SweetPea Calls: 140 (Sun Sep 02 2018 15:13:10 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Sun Sep 02 2018 15:13:10 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 15:16:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 15:16:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 15:16:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 15:16:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 4_tgLhyR8CiUlbpsAB-Y Troll Calls: 38 (Sun Sep 02 2018 15:17:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 15:17:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bV0VuYMC2eYbmYQAAB-X Sinstrite Calls: 350 (Sun Sep 02 2018 15:17:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Pwz-Ok5bAiMUXjroAB-V Curse Calls: 270 (Sun Sep 02 2018 15:17:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uUvhO6zgbF4gWu8NAB-W Shield Calls: 260 (Sun Sep 02 2018 15:17:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 15:17:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 15:17:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 15:17:15 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 15:29:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: QL5nCOisc_36cVhDAB9L Scythe Calls: 749354 (Sun Sep 02 2018 15:29:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 15:29:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OLPc_mzBtywVewh0AB9M Silent Calls: 260802 (Sun Sep 02 2018 15:29:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 15:29:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: X3z-NIOUwyrqBhjcAB9w Carolina Calls: 46641 (Sun Sep 02 2018 15:29:56 GMT+0000 (Coordinated Universal Time)) +stop_character: Carolina owner: 6609080732876800 bank: false (Sun Sep 02 2018 15:29:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: C0QkTBMizN87ncxpAB9y TexTheTank Calls: 61561 (Sun Sep 02 2018 15:29:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5xOdosDnn8UizfukAB9x BlazingSnip Calls: 20728 (Sun Sep 02 2018 15:29:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YIJfR9fXqz_CwwHSAB9v MOBSans Calls: 1024 (Sun Sep 02 2018 15:29:59 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Sun Sep 02 2018 15:30:00 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Sun Sep 02 2018 15:30:00 GMT+0000 (Coordinated Universal Time)) +stop_character: TexTheTank owner: 6609080732876800 bank: false (Sun Sep 02 2018 15:30:00 GMT+0000 (Coordinated Universal Time)) +start_character: "Carolina" (Sun Sep 02 2018 15:30:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 15:30:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 15:30:27 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Sun Sep 02 2018 15:30:36 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ztBlR9uK9eC7EhFAAB-d MOBSans Calls: 5 (Sun Sep 02 2018 15:31:03 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Sun Sep 02 2018 15:31:03 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Sun Sep 02 2018 15:31:35 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vmA8gg-IVKZPlIJDAB-a Carolina Calls: 283 (Sun Sep 02 2018 15:32:44 GMT+0000 (Coordinated Universal Time)) +stop_character: Carolina owner: 6609080732876800 bank: false (Sun Sep 02 2018 15:32:45 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 15:34:45 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 15:35:11 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 15:35:43 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 15:36:44 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 15:37:02 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 15:37:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yLfFZxipS3HIIEauAB-b Scythe Calls: 15388 (Sun Sep 02 2018 15:37:20 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 15:37:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5SDT4KaYu8Pw-kg4AB-c Silent Calls: 5240 (Sun Sep 02 2018 15:37:20 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 15:37:21 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 15:37:26 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 15:37:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: b10H9fdd3a7N-0LnAB-R Pluu Calls: 64312 (Sun Sep 02 2018 15:38:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IyOsbfv0bBlO8KpCAB-S Pure Calls: 64768 (Sun Sep 02 2018 15:38:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Y8Q1R5LHugXie5b9AB-T Cozi Calls: 64954 (Sun Sep 02 2018 15:38:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 15:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 15:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 15:38:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 15:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 15:38:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 15:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 15:38:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 15:38:51 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 15:38:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: kgi09nHP4ACETgcUAB-i Scythe Calls: 221 (Sun Sep 02 2018 15:38:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YORazwSmZ5v__cPzAB-j Silent Calls: 4 (Sun Sep 02 2018 15:38:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 15:38:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 15:38:52 GMT+0000 (Coordinated Universal Time)) +start_character: "Carolina" (Sun Sep 02 2018 15:39:08 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Sun Sep 02 2018 15:39:13 GMT+0000 (Coordinated Universal Time)) +start_character: "TexTheTank" (Sun Sep 02 2018 15:39:59 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 15:40:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 15:40:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 16:02:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 16:02:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 16:02:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 16:03:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KYu_ydiwaBuIX1gxAB-u Troll Calls: 39 (Sun Sep 02 2018 16:03:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 16:03:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: iqBhPssEydXYg4CRAB-s Sinstrite Calls: 771 (Sun Sep 02 2018 16:03:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: b5OqRFJs7UaCVzTUAB-r Curse Calls: 516 (Sun Sep 02 2018 16:03:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: RtdMBNAUczCsrcCHAB-t Shield Calls: 532 (Sun Sep 02 2018 16:03:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 16:03:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 16:03:40 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 16:03:40 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Sun Sep 02 2018 16:07:46 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Sun Sep 02 2018 16:07:48 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 16:09:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5yDHlTA2wk6yBFsEAB-n Scythe Calls: 65648 (Sun Sep 02 2018 16:09:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 16:09:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: d9th4dCmzmEPmVhZAB-o Silent Calls: 22529 (Sun Sep 02 2018 16:09:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 16:09:48 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 16:10:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 16:10:47 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 16:11:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bGQ3AICbeCy4eXpiAB-v Scythe Calls: 1567 (Sun Sep 02 2018 16:11:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Dy3HuiZpPaRfnC10AB-w Silent Calls: 344 (Sun Sep 02 2018 16:11:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 16:11:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 16:11:16 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 16:12:47 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 16:12:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: pBfEv24IZMX_gmnuAB-x Scythe Calls: 359 (Sun Sep 02 2018 16:12:55 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 16:12:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Sun Sep 02 2018 16:14:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Sun Sep 02 2018 16:14:26 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Sun Sep 02 2018 16:14:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: qUEHiEeDar5Jr5CWAB-y Scythe Calls: 954 (Sun Sep 02 2018 16:14:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: aKXFkd0Wy3LbXUrZAB-z Silent Calls: 222 (Sun Sep 02 2018 16:14:44 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Sun Sep 02 2018 16:14:44 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Sun Sep 02 2018 16:14:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Mupp" (Sun Sep 02 2018 16:21:07 GMT+0000 (Coordinated Universal Time)) +start_character: "MuppPriest" (Sun Sep 02 2018 16:21:17 GMT+0000 (Coordinated Universal Time)) +start_character: "MuppArch" (Sun Sep 02 2018 16:21:18 GMT+0000 (Coordinated Universal Time)) +Main loop took 28ms (Sun Sep 02 2018 16:31:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Sentry" (Sun Sep 02 2018 16:31:33 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Sun Sep 02 2018 16:36:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Sentry owner: 5792989285711872 (Sun Sep 02 2018 16:37:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: t6-tMf51tIc5Zn_gAB-f Pluu Calls: 64380 (Sun Sep 02 2018 16:38:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IiOLuuoYB2z4SF4uAB-g Pure Calls: 64684 (Sun Sep 02 2018 16:38:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bVNjf3-J7iyoEf_aAB-h Cozi Calls: 64873 (Sun Sep 02 2018 16:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 16:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 16:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 16:38:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 16:38:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 16:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 16:38:37 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Sentry owner: 5792989285711872 (Sun Sep 02 2018 16:42:24 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Sun Sep 02 2018 16:42:41 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 16:42:52 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 16:43:09 GMT+0000 (Coordinated Universal Time)) +mount_user: Sentry owner: 5792989285711872 (Sun Sep 02 2018 16:44:08 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 16:44:14 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 16:44:24 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Sentry owner: 5792989285711872 (Sun Sep 02 2018 16:44:30 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 16:44:34 GMT+0000 (Coordinated Universal Time)) +mount_user: Sentry owner: 5792989285711872 (Sun Sep 02 2018 16:45:31 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Sentry owner: 5792989285711872 (Sun Sep 02 2018 16:45:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 16:48:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 16:48:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 16:48:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: pDo8o0sGTvhqYC0VAB-5 Sentry Calls: 447 (Sun Sep 02 2018 16:48:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Sentry owner: 5792989285711872 bank: false (Sun Sep 02 2018 16:48:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 16:48:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Uw3ycNEqM_lTnHFMAB_A Troll Calls: 38 (Sun Sep 02 2018 16:49:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 16:49:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VJHUf1nHauBzrAHpAB-- Sinstrite Calls: 357 (Sun Sep 02 2018 16:49:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6dOSUgaw0ZI1ZRBVAB-_ Shield Calls: 332 (Sun Sep 02 2018 16:49:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Fz2dXGi2rNgolHfxAB-9 Curse Calls: 360 (Sun Sep 02 2018 16:49:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 16:49:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 16:49:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 16:49:29 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 17:03:56 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 17:04:10 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 17:04:18 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 17:04:34 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 17:04:41 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 17:05:04 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 17:05:11 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 17:05:18 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 17:05:27 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 17:05:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 17:34:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 17:34:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 17:34:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 17:34:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vhwAlxdprgxairDUAB_E Troll Calls: 39 (Sun Sep 02 2018 17:34:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 17:34:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: gLanmbiroHBvJ-KDAB_C Shield Calls: 350 (Sun Sep 02 2018 17:35:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: JtFQbVQFCiiFvEL8AB_D Sinstrite Calls: 489 (Sun Sep 02 2018 17:35:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mp6VX2JOhXd_yBS3AB_B Curse Calls: 374 (Sun Sep 02 2018 17:35:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 17:35:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 17:35:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 17:35:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2yC2vy6bUWbv6NzqAB-6 Pluu Calls: 64390 (Sun Sep 02 2018 17:38:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bZdIQWsiLXo0vCqQAB-7 Pure Calls: 64522 (Sun Sep 02 2018 17:38:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OIZMQbj3fr1e2DG3AB-8 Cozi Calls: 64094 (Sun Sep 02 2018 17:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 17:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 17:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 17:38:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 17:38:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 17:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 17:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 18:20:16 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 18:20:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 18:20:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 18:20:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dUD01rc64Cx4lCDWAB_L Troll Calls: 38 (Sun Sep 02 2018 18:20:42 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 18:20:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PYRhKNSBgluj6lLIAB_J Sinstrite Calls: 397 (Sun Sep 02 2018 18:21:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 46GYenf0LHS6gpPBAB_K Shield Calls: 346 (Sun Sep 02 2018 18:21:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Zqs5wcBmuQ_wCpn8AB_I Curse Calls: 369 (Sun Sep 02 2018 18:21:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 18:21:09 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 18:21:09 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 18:21:09 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vVcw7ZErJj2ri3uaABqG Trexnamedted Calls: 1057499 (Sun Sep 02 2018 18:33:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: JL4DdonjEravOItMABqE Trexnamedtom Calls: 1049265 (Sun Sep 02 2018 18:33:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: l73GlKYfS5F5pzA9ABqF Trexnamedtut Calls: 1051911 (Sun Sep 02 2018 18:33:42 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Sun Sep 02 2018 18:33:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Sun Sep 02 2018 18:33:44 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Sun Sep 02 2018 18:33:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Sun Sep 02 2018 18:33:46 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Sun Sep 02 2018 18:33:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Sun Sep 02 2018 18:33:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: GfxxGus7kq6UVAx7AB_G Pluu Calls: 64238 (Sun Sep 02 2018 18:38:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZG_5E9jTgkXkg1gZAB_F Pure Calls: 64702 (Sun Sep 02 2018 18:38:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: f8IfjESabRuIuTb2AB_H Cozi Calls: 64725 (Sun Sep 02 2018 18:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 18:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 18:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 18:38:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 18:38:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 18:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 18:38:37 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtod owner: 5209159389675520 (Sun Sep 02 2018 18:46:31 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtod owner: 5209159389675520 (Sun Sep 02 2018 18:46:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DhUCP3KJjYdMw_YfAB_N Trexnamedted Calls: 10183 (Sun Sep 02 2018 18:47:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: jrqj5H5IXYfCQemzAB_O Trexnamedtom Calls: 10091 (Sun Sep 02 2018 18:47:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NGkPUMoasmlCsnteAB_P Trexnamedtut Calls: 10109 (Sun Sep 02 2018 18:47:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7ThG1Gj4DNcwgLZoABqD Trexnamedtod Calls: 519 (Sun Sep 02 2018 18:47:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Sun Sep 02 2018 18:47:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Sun Sep 02 2018 18:47:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Sun Sep 02 2018 18:47:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtod owner: 5209159389675520 bank: false (Sun Sep 02 2018 18:47:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Sun Sep 02 2018 18:47:16 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Sun Sep 02 2018 18:47:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: w2qack7XCwvi1yFqAB_U Trexnamedtut Calls: 49 (Sun Sep 02 2018 18:47:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Sun Sep 02 2018 18:47:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Sun Sep 02 2018 18:47:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZYobv0HKi3CQtiKKAB_T Trexnamedted Calls: 60 (Sun Sep 02 2018 18:47:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Sun Sep 02 2018 18:47:44 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtom owner: 5209159389675520 (Sun Sep 02 2018 18:48:04 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtom owner: 5209159389675520 (Sun Sep 02 2018 18:48:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: u_uf0OD_ueWUT4XAAB_V Trexnamedtom Calls: 238 (Sun Sep 02 2018 18:49:00 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Sun Sep 02 2018 18:49:00 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtod" (Sun Sep 02 2018 18:49:06 GMT+0000 (Coordinated Universal Time)) +mount_user: Trexnamedtod owner: 5209159389675520 (Sun Sep 02 2018 18:49:09 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Trexnamedtod owner: 5209159389675520 (Sun Sep 02 2018 18:49:20 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 18:50:01 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 18:50:08 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 18:50:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Sun Sep 02 2018 18:50:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Sun Sep 02 2018 18:50:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Sun Sep 02 2018 18:50:24 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 18:50:31 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Sun Sep 02 2018 19:00:38 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 19:00:54 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 19:00:59 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 19:01:28 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Sun Sep 02 2018 19:01:45 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6Jen9bKiX98GPPtpAB_a SweetPea Calls: 108 (Sun Sep 02 2018 19:02:57 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Sun Sep 02 2018 19:02:58 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 19:05:04 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 19:05:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 19:06:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 19:06:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 19:06:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 19:06:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -k5s3Yh6JFsMHMU8AB_f Troll Calls: 39 (Sun Sep 02 2018 19:06:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 19:06:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: C9Q5IR7zfSrxiUnqAB_c Shield Calls: 372 (Sun Sep 02 2018 19:06:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: hxmhx_gwC6xxRS7iAB_b Curse Calls: 396 (Sun Sep 02 2018 19:06:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: GB-TvS9ZFSl9I-yyAB_d Sinstrite Calls: 370 (Sun Sep 02 2018 19:06:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 19:06:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 19:06:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 19:06:59 GMT+0000 (Coordinated Universal Time)) +start_character: "lissandra" (Sun Sep 02 2018 19:18:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: eJB-kmR_Sz37La4LAB_g lissandra Calls: 296 (Sun Sep 02 2018 19:19:36 GMT+0000 (Coordinated Universal Time)) +stop_character: lissandra owner: 5793534377459712 bank: false (Sun Sep 02 2018 19:19:36 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 19:20:10 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Sun Sep 02 2018 19:20:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 93vPSnGh5LjlTHimAB7P Foaly Calls: 191 (Sun Sep 02 2018 19:27:35 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Sun Sep 02 2018 19:27:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Sun Sep 02 2018 19:29:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: C2Iw-36OI9qX5XsoAB_h Foaly Calls: 11 (Sun Sep 02 2018 19:37:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Sun Sep 02 2018 19:37:36 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: O8Vi6ZFxfQhGZAF6AB_Q Pluu Calls: 64669 (Sun Sep 02 2018 19:38:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: CI8nwj4lggRjeG3RAB_R Pure Calls: 64204 (Sun Sep 02 2018 19:38:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: D3buTE9gy4DStg-sAB_S Cozi Calls: 64027 (Sun Sep 02 2018 19:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 19:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 19:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 19:38:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 19:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 19:38:39 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 19:38:39 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Sun Sep 02 2018 19:38:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 19:51:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 19:51:59 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 19:52:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 19:52:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3-UsPQ2BqX5LgPwRAB_r Troll Calls: 38 (Sun Sep 02 2018 19:52:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 19:52:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0TyA2rD-vMP-cCrXAB_q Sinstrite Calls: 380 (Sun Sep 02 2018 19:52:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: jT9zZBy5Vq_g6FuvAB_o Curse Calls: 404 (Sun Sep 02 2018 19:52:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xmRyxo1Pq40klIauAB_p Shield Calls: 390 (Sun Sep 02 2018 19:52:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 19:52:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 19:52:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 19:52:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 20:37:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 20:37:53 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 20:37:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 20:38:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0qrcp9rAbM2V4xp4AB_w Troll Calls: 39 (Sun Sep 02 2018 20:38:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 20:38:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: WsLNU2xv7lejkyxxAB_m Pluu Calls: 64234 (Sun Sep 02 2018 20:38:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 1WWV0WS0D4bnPko-AB_k Pure Calls: 64222 (Sun Sep 02 2018 20:38:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mEoDTMtIe6fZGU53AB_l Cozi Calls: 64282 (Sun Sep 02 2018 20:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 20:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 20:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 20:38:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 20:38:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 20:38:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 20:38:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mWOG2_jaQCDYYQ5nAB_t Curse Calls: 379 (Sun Sep 02 2018 20:38:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: m9T7ssRpyJzXszUdAB_u Sinstrite Calls: 513 (Sun Sep 02 2018 20:38:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xpwAWtKx7FtG1uwcAB_v Shield Calls: 350 (Sun Sep 02 2018 20:38:41 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 20:38:41 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 20:38:41 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 20:38:41 GMT+0000 (Coordinated Universal Time)) +start_character: "finder" (Sun Sep 02 2018 20:43:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KNpr8x6eAYLtkpNmAB_1 finder Calls: 22 (Sun Sep 02 2018 20:52:12 GMT+0000 (Coordinated Universal Time)) +stop_character: finder owner: 5187166690869248 bank: false (Sun Sep 02 2018 20:52:12 GMT+0000 (Coordinated Universal Time)) +start_character: "finder" (Sun Sep 02 2018 20:53:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: kvmqO9IvsLnrxxaPAB_2 finder Calls: 11 (Sun Sep 02 2018 20:54:05 GMT+0000 (Coordinated Universal Time)) +stop_character: finder owner: 5187166690869248 bank: false (Sun Sep 02 2018 20:54:06 GMT+0000 (Coordinated Universal Time)) +start_character: "finder" (Sun Sep 02 2018 20:55:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: qhkJBFxp36c9BaH7AB_3 finder Calls: 12 (Sun Sep 02 2018 20:55:58 GMT+0000 (Coordinated Universal Time)) +stop_character: finder owner: 5187166690869248 bank: false (Sun Sep 02 2018 20:55:58 GMT+0000 (Coordinated Universal Time)) +start_character: "finder" (Sun Sep 02 2018 20:58:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 21:23:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 21:23:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 21:23:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 21:23:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: f7i2DZ145VTmbcjQAB_8 Troll Calls: 38 (Sun Sep 02 2018 21:24:04 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 21:24:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xKeDMHC13sGK3MMiAB_6 Sinstrite Calls: 362 (Sun Sep 02 2018 21:24:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 92cxjUea8803GoMxAB_7 Shield Calls: 348 (Sun Sep 02 2018 21:24:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: sBk55CMHrCYvfYmfAB_5 Curse Calls: 384 (Sun Sep 02 2018 21:24:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 21:24:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 21:24:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 21:24:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: pjnqhLTBtMBbczsAAB_4 finder Calls: 398 (Sun Sep 02 2018 21:34:21 GMT+0000 (Coordinated Universal Time)) +stop_character: finder owner: 5187166690869248 bank: false (Sun Sep 02 2018 21:34:22 GMT+0000 (Coordinated Universal Time)) +start_character: "finder" (Sun Sep 02 2018 21:34:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: FU19ly5FIrh653s5AB_y Pluu Calls: 64200 (Sun Sep 02 2018 21:38:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: EKNo9XHXExFBdjLgAB_z Pure Calls: 64395 (Sun Sep 02 2018 21:38:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tneaQuw1FapW1WbpAB_0 Cozi Calls: 64203 (Sun Sep 02 2018 21:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 21:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 21:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 21:38:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 21:38:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 21:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 21:38:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: FyTYWs_8droE90CvAB_- finder Calls: 25 (Sun Sep 02 2018 21:49:57 GMT+0000 (Coordinated Universal Time)) +stop_character: finder owner: 5187166690869248 bank: false (Sun Sep 02 2018 21:49:57 GMT+0000 (Coordinated Universal Time)) +start_character: "BuyMyThings" (Sun Sep 02 2018 22:00:45 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Sun Sep 02 2018 22:01:27 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Sun Sep 02 2018 22:01:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 9sJJnN3QCIdDVuQvACAC BuyMyThings Calls: 91 (Sun Sep 02 2018 22:04:30 GMT+0000 (Coordinated Universal Time)) +stop_character: BuyMyThings owner: 4687219387269120 bank: false (Sun Sep 02 2018 22:04:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 22:09:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 22:09:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 22:09:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 22:09:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: LaGd4rcBQ4R5QWVwACAG Troll Calls: 39 (Sun Sep 02 2018 22:09:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 22:09:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: e4ILcWOdmvlpURkKACAD Curse Calls: 414 (Sun Sep 02 2018 22:10:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: C4gOa1s_Y18Hhi9lACAF Shield Calls: 388 (Sun Sep 02 2018 22:10:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2K_cBzjP0BbSuNCXACAE Sinstrite Calls: 406 (Sun Sep 02 2018 22:10:22 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 22:10:22 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 22:10:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 22:10:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 4PoixdvCgLXsP0_bACAA Pluu Calls: 64579 (Sun Sep 02 2018 22:38:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: XmNPAQiQETBKrZfYACAB Pure Calls: 64119 (Sun Sep 02 2018 22:38:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: JSYLSoSEf_t1NcJWAB__ Cozi Calls: 64118 (Sun Sep 02 2018 22:38:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 22:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 22:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 22:38:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 22:38:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 22:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 22:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 22:55:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 22:55:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 22:55:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 22:55:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: eCm4mya62HbDY7_FACAO Troll Calls: 39 (Sun Sep 02 2018 22:55:44 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 22:55:45 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DjPgDEuPLLyowYCMACAN Shield Calls: 367 (Sun Sep 02 2018 22:56:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5kX9J4O-t6cfNfOjACAM Sinstrite Calls: 570 (Sun Sep 02 2018 22:56:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2jZjw-NPTmTZOz9uACAL Curse Calls: 402 (Sun Sep 02 2018 22:56:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 22:56:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 22:56:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 22:56:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PnRGraatqTDHilomACAI Pluu Calls: 64735 (Sun Sep 02 2018 23:38:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: txqArpFWBLjS4vtLACAK Pure Calls: 64290 (Sun Sep 02 2018 23:38:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YqhtKqZuAxhwYie0ACAJ Cozi Calls: 63883 (Sun Sep 02 2018 23:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Sun Sep 02 2018 23:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Sun Sep 02 2018 23:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Sun Sep 02 2018 23:38:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Sun Sep 02 2018 23:38:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Sun Sep 02 2018 23:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Sun Sep 02 2018 23:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Sun Sep 02 2018 23:41:10 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Sun Sep 02 2018 23:41:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Sun Sep 02 2018 23:41:15 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Sun Sep 02 2018 23:41:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zH5ozucL1HIP3q_JACAX Troll Calls: 39 (Sun Sep 02 2018 23:42:04 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Sun Sep 02 2018 23:42:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: kZT5N7y2qL9aLXwJACAU Curse Calls: 601 (Sun Sep 02 2018 23:42:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: CUd11jdxZRJuB80qACAV Sinstrite Calls: 587 (Sun Sep 02 2018 23:42:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0GZ2mMgJHIk3K5PFACAW Shield Calls: 563 (Sun Sep 02 2018 23:42:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Sun Sep 02 2018 23:42:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Sun Sep 02 2018 23:42:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Sun Sep 02 2018 23:42:32 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Sun Sep 02 2018 23:45:37 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Sun Sep 02 2018 23:45:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 8dwrb5XmR6fkGOTIAB-1 Mupp Calls: 71234 (Sun Sep 02 2018 23:53:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IeRrAOOt86yZNY1VAB-3 MuppArch Calls: 11 (Sun Sep 02 2018 23:53:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: D7ZqcpQwFLR8P3f9AB-2 MuppPriest Calls: 68399 (Sun Sep 02 2018 23:53:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Mupp owner: 5552666278100992 bank: false (Sun Sep 02 2018 23:53:03 GMT+0000 (Coordinated Universal Time)) +stop_character: MuppArch owner: 5552666278100992 bank: false (Sun Sep 02 2018 23:53:04 GMT+0000 (Coordinated Universal Time)) +stop_character: MuppPriest owner: 5552666278100992 bank: false (Sun Sep 02 2018 23:53:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 00:27:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 00:27:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 00:27:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 00:27:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7MZwnrXjH6DPNNx0ACAc Troll Calls: 39 (Mon Sep 03 2018 00:27:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 00:27:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0aKrO0RMPQwtcWY_ACAZ Curse Calls: 378 (Mon Sep 03 2018 00:28:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: quqGhBLUP5weT1cxACAa Sinstrite Calls: 514 (Mon Sep 03 2018 00:28:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IevoKXL4l0TuMvU1ACAb Shield Calls: 341 (Mon Sep 03 2018 00:28:20 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 00:28:20 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 00:28:21 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 00:28:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ITCUQAi8VQSGfqotACAR Pluu Calls: 64299 (Mon Sep 03 2018 00:38:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: HdmxKmWwVIazi7CiACAS Pure Calls: 64902 (Mon Sep 03 2018 00:38:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Y5RvmFmgKIikzmKaACAT Cozi Calls: 64834 (Mon Sep 03 2018 00:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 00:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 00:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 00:38:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 00:38:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 00:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 00:38:37 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 00:58:35 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 00:58:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Maela" (Mon Sep 03 2018 01:10:11 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Mon Sep 03 2018 01:12:48 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Mon Sep 03 2018 01:12:52 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 01:13:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 01:13:24 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 01:13:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 01:13:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KyIn1sSXAIOXcqkxACAl Troll Calls: 39 (Mon Sep 03 2018 01:14:04 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 01:14:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bTYDWjCEK88jsSk6ACAj Sinstrite Calls: 702 (Mon Sep 03 2018 01:14:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3mFwvEMyCGYG8X0hACAk Shield Calls: 506 (Mon Sep 03 2018 01:14:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: C_K0ujKvjrV9PNYCACAi Curse Calls: 508 (Mon Sep 03 2018 01:14:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 01:14:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 01:14:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 01:14:31 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Mon Sep 03 2018 01:19:06 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Mon Sep 03 2018 01:19:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Uwp2TP242FfS3tzlACAh Maela Calls: 707 (Mon Sep 03 2018 01:19:40 GMT+0000 (Coordinated Universal Time)) +stop_character: Maela owner: 4909785279365120 bank: false (Mon Sep 03 2018 01:19:41 GMT+0000 (Coordinated Universal Time)) +start_character: "BuyMyThings" (Mon Sep 03 2018 01:25:13 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Mon Sep 03 2018 01:26:34 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Mon Sep 03 2018 01:26:46 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 01:26:46 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 01:26:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: F6pBgDY9Kn3GXI0_ACAp BuyMyThings Calls: 127 (Mon Sep 03 2018 01:26:56 GMT+0000 (Coordinated Universal Time)) +stop_character: BuyMyThings owner: 4687219387269120 bank: false (Mon Sep 03 2018 01:26:57 GMT+0000 (Coordinated Universal Time)) +start_character: "BuyMyThings" (Mon Sep 03 2018 01:27:00 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Mon Sep 03 2018 01:28:17 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Mon Sep 03 2018 01:28:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7pnAipfj1Ycs15IeACAq BuyMyThings Calls: 75 (Mon Sep 03 2018 01:29:05 GMT+0000 (Coordinated Universal Time)) +stop_character: BuyMyThings owner: 4687219387269120 bank: false (Mon Sep 03 2018 01:29:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 01:36:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 01:37:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vYE5JcOVNLguRW4zACAe Pluu Calls: 64178 (Mon Sep 03 2018 01:38:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: x1QcBdaFYUpT45llACAf Pure Calls: 64155 (Mon Sep 03 2018 01:38:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: FZRQxpsxvdT3fHlxACAg Cozi Calls: 64833 (Mon Sep 03 2018 01:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 01:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 01:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 01:38:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 01:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 01:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 01:38:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: M0Q8rzVm7Pyv8yWnAB_Z Trexnamedted Calls: 313794 (Mon Sep 03 2018 01:40:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: lfHsw4zFxNEUPvzaAB_X Trexnamedtom Calls: 311286 (Mon Sep 03 2018 01:40:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vEDTtfxTlDvMo-G6AB_W Trexnamedtod Calls: 218 (Mon Sep 03 2018 01:40:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VfeRpyet5A0a11WoAB_Y Trexnamedtut Calls: 311828 (Mon Sep 03 2018 01:40:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Mon Sep 03 2018 01:40:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtod owner: 5209159389675520 bank: false (Mon Sep 03 2018 01:40:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Mon Sep 03 2018 01:40:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Mon Sep 03 2018 01:40:40 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TFJ4x2xX5mU-KoPhAB-k Carolina Calls: 216594 (Mon Sep 03 2018 01:41:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: pCjnTMAR-qhhm9zGAB-l BlazingSnip Calls: 60193 (Mon Sep 03 2018 01:41:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ovt2P7MZBT6YubgiAB-m TexTheTank Calls: 123201 (Mon Sep 03 2018 01:41:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zhGP_5Rf7IT8uxK4AB-e MOBSans Calls: 24703 (Mon Sep 03 2018 01:41:10 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Mon Sep 03 2018 01:41:10 GMT+0000 (Coordinated Universal Time)) +stop_character: TexTheTank owner: 6609080732876800 bank: false (Mon Sep 03 2018 01:41:10 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Mon Sep 03 2018 01:41:11 GMT+0000 (Coordinated Universal Time)) +stop_character: Carolina owner: 6609080732876800 bank: false (Mon Sep 03 2018 01:41:11 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Mon Sep 03 2018 01:41:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Carolina" (Mon Sep 03 2018 01:41:24 GMT+0000 (Coordinated Universal Time)) +mount_user: Carolina owner: 6609080732876800 (Mon Sep 03 2018 01:41:39 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Carolina owner: 6609080732876800 (Mon Sep 03 2018 01:41:45 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Mon Sep 03 2018 01:41:48 GMT+0000 (Coordinated Universal Time)) +start_character: "TexTheTank" (Mon Sep 03 2018 01:41:50 GMT+0000 (Coordinated Universal Time)) +mount_user: BlazingSnip owner: 6609080732876800 (Mon Sep 03 2018 01:42:45 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BlazingSnip owner: 6609080732876800 (Mon Sep 03 2018 01:42:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2aVOpk5OeYBlzdHJACA2 BlazingSnip Calls: 27 (Mon Sep 03 2018 01:42:56 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Mon Sep 03 2018 01:42:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YCU47Qwu3BArMXE4ACAz MOBSans Calls: 7 (Mon Sep 03 2018 01:42:58 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Mon Sep 03 2018 01:42:58 GMT+0000 (Coordinated Universal Time)) +mount_user: TexTheTank owner: 6609080732876800 (Mon Sep 03 2018 01:46:39 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: TexTheTank owner: 6609080732876800 (Mon Sep 03 2018 01:46:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tA1ybWzgMUiOp4gPACA1 TexTheTank Calls: 165 (Mon Sep 03 2018 01:48:06 GMT+0000 (Coordinated Universal Time)) +stop_character: TexTheTank owner: 6609080732876800 bank: false (Mon Sep 03 2018 01:48:06 GMT+0000 (Coordinated Universal Time)) +start_character: "TexTheTank" (Mon Sep 03 2018 01:48:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ElfUjknQzPqZjW5cACA3 TexTheTank Calls: 5 (Mon Sep 03 2018 01:49:12 GMT+0000 (Coordinated Universal Time)) +stop_character: TexTheTank owner: 6609080732876800 bank: false (Mon Sep 03 2018 01:49:12 GMT+0000 (Coordinated Universal Time)) +start_character: "TexTheTank" (Mon Sep 03 2018 01:49:26 GMT+0000 (Coordinated Universal Time)) +start_character: "SansSupport" (Mon Sep 03 2018 01:50:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: iXZssL7p4JtWFTYPACA5 SansSupport Calls: 5 (Mon Sep 03 2018 01:50:35 GMT+0000 (Coordinated Universal Time)) +stop_character: SansSupport owner: 6609080732876800 bank: false (Mon Sep 03 2018 01:50:35 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Mon Sep 03 2018 01:50:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ekyushY_x1TgKuoNACA6 BlazingSnip Calls: 5 (Mon Sep 03 2018 01:50:48 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Mon Sep 03 2018 01:50:48 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Mon Sep 03 2018 01:51:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KSoy2kvkLcn5sZWWACA7 MOBSans Calls: 127 (Mon Sep 03 2018 01:53:24 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Mon Sep 03 2018 01:53:24 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Mon Sep 03 2018 01:54:03 GMT+0000 (Coordinated Universal Time)) +mount_user: Carolina owner: 6609080732876800 (Mon Sep 03 2018 01:56:59 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Carolina owner: 6609080732876800 (Mon Sep 03 2018 01:57:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 01:59:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 01:59:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 01:59:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 02:00:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TXwlHrkzCVfv-KVAACBA Troll Calls: 39 (Mon Sep 03 2018 02:00:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 02:00:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: EueC1DRbGdwfgA5rACA- Shield Calls: 573 (Mon Sep 03 2018 02:00:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PS3mVe7SkuNEVfrqACA_ Sinstrite Calls: 808 (Mon Sep 03 2018 02:00:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mqfEAWkfDncsyu2WACA9 Curse Calls: 601 (Mon Sep 03 2018 02:00:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 02:00:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 02:00:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 02:00:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: RyFjkgySJksyBi7DACA8 BlazingSnip Calls: 138 (Mon Sep 03 2018 02:03:58 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Mon Sep 03 2018 02:03:58 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Mon Sep 03 2018 02:04:15 GMT+0000 (Coordinated Universal Time)) +start_character: "Maela" (Mon Sep 03 2018 02:23:57 GMT+0000 (Coordinated Universal Time)) +start_character: "SpadarFaar" (Mon Sep 03 2018 02:23:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Brutus" (Mon Sep 03 2018 02:23:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dYCthFSmfCmgGSYSACAr Scythe Calls: 108340 (Mon Sep 03 2018 02:26:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uNFFjwtaFLLKWehpACAs Silent Calls: 37681 (Mon Sep 03 2018 02:26:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 02:26:25 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 02:26:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yEQ9Z-Yzjj9NEiMUACBE Brutus Calls: 603 (Mon Sep 03 2018 02:30:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Q7EAq-EbCHMN4446ACBF SpadarFaar Calls: 822 (Mon Sep 03 2018 02:30:01 GMT+0000 (Coordinated Universal Time)) +stop_character: SpadarFaar owner: 4909785279365120 bank: false (Mon Sep 03 2018 02:30:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Brutus owner: 4909785279365120 bank: false (Mon Sep 03 2018 02:30:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IFmBISQOUc4OEYaLACBG Maela Calls: 3100 (Mon Sep 03 2018 02:30:04 GMT+0000 (Coordinated Universal Time)) +stop_character: Maela owner: 4909785279365120 bank: false (Mon Sep 03 2018 02:30:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: sfIa7f6AfvJh-fK-ACAt Pluu Calls: 64510 (Mon Sep 03 2018 02:38:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ylkCdIE-0GjeZgGgACAu Pure Calls: 64187 (Mon Sep 03 2018 02:38:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 9EOwvHFDBDNxYHbFACAv Cozi Calls: 64512 (Mon Sep 03 2018 02:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 02:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 02:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 02:38:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 02:38:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 02:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 02:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 02:45:46 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 02:45:50 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 02:45:52 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 02:46:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tjSg04FjpqI3yo0YACBS Troll Calls: 38 (Mon Sep 03 2018 02:46:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 02:46:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rDvo1XlKPiFOW2U7ACBR Shield Calls: 272 (Mon Sep 03 2018 02:46:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: apJGOsluI6jIDC66ACBQ Sinstrite Calls: 395 (Mon Sep 03 2018 02:46:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3n4No2sqJ2hqR9ZWACBP Curse Calls: 318 (Mon Sep 03 2018 02:46:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 02:46:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 02:46:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 02:46:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 03:13:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 03:13:16 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 03:13:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ND6KnjqWADAD5TjmACBW Scythe Calls: 1253 (Mon Sep 03 2018 03:13:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: enWUf6tIm2F9hEkYACBX Silent Calls: 300 (Mon Sep 03 2018 03:13:41 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 03:13:41 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 03:13:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 03:14:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 03:15:01 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 03:15:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: XdkN2pvipG8r9HXuACBY Scythe Calls: 253 (Mon Sep 03 2018 03:15:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 03:15:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -xRnzVmmlammf9VJACBZ Silent Calls: 3 (Mon Sep 03 2018 03:15:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 03:15:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 03:16:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 03:16:27 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 03:31:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 03:31:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 03:31:46 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 03:32:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 8K0brsFRtQBnGcZSACBg Troll Calls: 38 (Mon Sep 03 2018 03:32:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 03:32:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: aRpJF8eKCJTb57cmACBd Curse Calls: 517 (Mon Sep 03 2018 03:32:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tTHcu1zUfKe5k1iBACBf Shield Calls: 508 (Mon Sep 03 2018 03:32:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Ed8R93BrkbEGUHP_ACBe Sinstrite Calls: 719 (Mon Sep 03 2018 03:32:51 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 03:32:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 03:32:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 03:32:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: cSXW9Jkyj7e_PGjfACBL Pluu Calls: 64518 (Mon Sep 03 2018 03:38:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: k-1pTDnlTrfJmzdKACBM Pure Calls: 64522 (Mon Sep 03 2018 03:38:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IA7aWMzWhD0c9eoaACBN Cozi Calls: 64053 (Mon Sep 03 2018 03:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 03:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 03:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 03:38:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 03:38:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 03:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 03:38:37 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 04:03:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UiHkzTDyADXQV2KZACBa Scythe Calls: 102819 (Mon Sep 03 2018 04:03:21 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 04:03:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: HM9lMOJ9PYNUXNGkACBb Silent Calls: 35791 (Mon Sep 03 2018 04:03:22 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 04:03:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 04:04:35 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 04:04:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: olOOGXxKykcyCgxfACBm Scythe Calls: 221 (Mon Sep 03 2018 04:04:41 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 04:04:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 04:06:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 04:06:16 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 04:12:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xiBej568_Tf1YJp-ACBn Scythe Calls: 15128 (Mon Sep 03 2018 04:12:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 04:12:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -pteogtfNGY5dXwIACBo Silent Calls: 5143 (Mon Sep 03 2018 04:13:04 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 04:13:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 04:14:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 04:14:24 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 04:17:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 04:17:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 04:17:52 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 04:18:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rT6gDnRRNerxzZSLACBu Troll Calls: 38 (Mon Sep 03 2018 04:18:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 04:18:35 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PaE64FogRye-UjVyACBs Sinstrite Calls: 748 (Mon Sep 03 2018 04:19:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Cei8X0MvI5m9mwFqACBt Shield Calls: 528 (Mon Sep 03 2018 04:19:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zkPP0Hw72nPaRPIVACBr Curse Calls: 539 (Mon Sep 03 2018 04:19:00 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 04:19:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 04:19:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 04:19:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtod" (Mon Sep 03 2018 04:35:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Mon Sep 03 2018 04:35:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Mon Sep 03 2018 04:35:27 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Mon Sep 03 2018 04:35:29 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 04:37:35 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 04:37:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: K6TCpuGC6-a236HzACBi Pluu Calls: 64065 (Mon Sep 03 2018 04:38:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ErjJGZumQb7EVejAACBk Pure Calls: 64275 (Mon Sep 03 2018 04:38:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: v0p7L9hsAi6ryu3tACBj Cozi Calls: 64635 (Mon Sep 03 2018 04:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 04:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 04:38:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 04:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 04:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 04:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 04:38:39 GMT+0000 (Coordinated Universal Time)) +start_character: "yeahaa" (Mon Sep 03 2018 04:46:58 GMT+0000 (Coordinated Universal Time)) +start_character: "crionic" (Mon Sep 03 2018 04:48:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DE--nJ034lpj_6iRACB4 crionic Calls: 128 (Mon Sep 03 2018 04:50:19 GMT+0000 (Coordinated Universal Time)) +stop_character: crionic owner: 4765522570772480 bank: false (Mon Sep 03 2018 04:50:20 GMT+0000 (Coordinated Universal Time)) +start_character: "crionic" (Mon Sep 03 2018 04:54:01 GMT+0000 (Coordinated Universal Time)) +mount_user: crionic owner: 4765522570772480 (Mon Sep 03 2018 04:54:29 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: crionic owner: 4765522570772480 (Mon Sep 03 2018 04:54:36 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OirceX7jNy70FhmDACB5 crionic Calls: 52 (Mon Sep 03 2018 04:54:46 GMT+0000 (Coordinated Universal Time)) +stop_character: crionic owner: 4765522570772480 bank: false (Mon Sep 03 2018 04:54:46 GMT+0000 (Coordinated Universal Time)) +mount_user: yeahaa owner: 4765522570772480 (Mon Sep 03 2018 04:59:09 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: yeahaa owner: 4765522570772480 (Mon Sep 03 2018 04:59:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 05:03:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 05:03:59 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 05:04:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 05:04:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: e4pWScFWlOGytA7xACB9 Troll Calls: 39 (Mon Sep 03 2018 05:04:45 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 05:04:45 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NTiOSK-LkrPH9lPgACB8 Sinstrite Calls: 773 (Mon Sep 03 2018 05:05:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: HMRJX1Y6UukBke6AACB7 Shield Calls: 526 (Mon Sep 03 2018 05:05:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YUR-hmDIaxcyFxjnACB6 Curse Calls: 543 (Mon Sep 03 2018 05:05:10 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 05:05:10 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 05:05:11 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 05:05:11 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Oj195WfahtH8VybgAB-U 0x00 Calls: 34195 (Mon Sep 03 2018 05:13:35 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Mon Sep 03 2018 05:13:36 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Mon Sep 03 2018 05:14:51 GMT+0000 (Coordinated Universal Time)) +mount_user: Business owner: 5752754626625536 (Mon Sep 03 2018 05:15:54 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Business owner: 5752754626625536 (Mon Sep 03 2018 05:16:43 GMT+0000 (Coordinated Universal Time)) +mount_user: Business owner: 5752754626625536 (Mon Sep 03 2018 05:17:31 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Business owner: 5752754626625536 (Mon Sep 03 2018 05:18:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: w4CKHdNd8tqfIUmvAB_n Foaly Calls: 91 (Mon Sep 03 2018 05:23:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Mon Sep 03 2018 05:23:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Mon Sep 03 2018 05:24:45 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7g6Z34EEEqT2L1oDACB0 Pluu Calls: 64256 (Mon Sep 03 2018 05:38:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: qSKFBfI9RS8PU2t0ACB2 Pure Calls: 64334 (Mon Sep 03 2018 05:38:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: _dIv5NPs4sy9bE43ACB1 Cozi Calls: 64365 (Mon Sep 03 2018 05:38:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 05:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 05:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 05:38:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 05:38:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 05:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 05:38:38 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Mon Sep 03 2018 05:38:51 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Mon Sep 03 2018 05:39:08 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Mon Sep 03 2018 05:39:14 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Mon Sep 03 2018 05:39:48 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Mon Sep 03 2018 05:40:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IoCl3AEExZOGMQ0KACCF SweetPea Calls: 116 (Mon Sep 03 2018 05:42:01 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Mon Sep 03 2018 05:42:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 05:50:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 05:50:11 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 05:50:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 05:50:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: hPeNeQa856ExPAEkACCJ Troll Calls: 39 (Mon Sep 03 2018 05:50:35 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 05:50:35 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YF3ctFKW-SwlIttOACCI Sinstrite Calls: 545 (Mon Sep 03 2018 05:51:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vLBLpRfeHFEZH6MhACCH Shield Calls: 378 (Mon Sep 03 2018 05:51:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -_6fmwg6a8YlCBp2ACCG Curse Calls: 396 (Mon Sep 03 2018 05:51:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 05:51:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 05:51:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 05:51:01 GMT+0000 (Coordinated Universal Time)) +start_character: "BuyMyThings" (Mon Sep 03 2018 05:51:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: sFbCTgwfcgjM332IACCL BuyMyThings Calls: 37 (Mon Sep 03 2018 05:52:33 GMT+0000 (Coordinated Universal Time)) +stop_character: BuyMyThings owner: 4687219387269120 bank: false (Mon Sep 03 2018 05:52:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: iMozsfHclAL8LamzACB3 yeahaa Calls: 80 (Mon Sep 03 2018 06:03:23 GMT+0000 (Coordinated Universal Time)) +stop_character: yeahaa owner: 4765522570772480 bank: false (Mon Sep 03 2018 06:03:23 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 06:17:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uwTfXVwHZeSnf873ACBp Scythe Calls: 269630 (Mon Sep 03 2018 06:17:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 06:17:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3NkjDdASuY4p51BKACBq Silent Calls: 93933 (Mon Sep 03 2018 06:17:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 06:17:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 06:18:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 06:18:49 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 06:18:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PsUOGjA5auaWC-8zACCM Scythe Calls: 243 (Mon Sep 03 2018 06:18:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 06:18:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: roug5trb1vox7m2fACCN Silent Calls: 6 (Mon Sep 03 2018 06:18:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 06:18:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 06:19:48 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 06:19:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 06:35:59 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 06:36:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 06:36:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 06:36:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KD8pte5mXXLPbEEhACCU Troll Calls: 39 (Mon Sep 03 2018 06:36:45 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 06:36:45 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tBnObmlMxQaIZo73ACCT Sinstrite Calls: 719 (Mon Sep 03 2018 06:37:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZTuTQXAE8vnJW8PAACCS Shield Calls: 527 (Mon Sep 03 2018 06:37:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NheTqJPoeKRg2S0-ACCR Curse Calls: 518 (Mon Sep 03 2018 06:37:10 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 06:37:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 06:37:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 06:37:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 1Ie7agWDB-GRnzRdACCD Pluu Calls: 64328 (Mon Sep 03 2018 06:38:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: BrwTT8_BmqlLkjobACCE Pure Calls: 64445 (Mon Sep 03 2018 06:38:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wEkO50B3VgsnaGngACCC Cozi Calls: 64449 (Mon Sep 03 2018 06:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 06:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 06:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 06:38:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 06:38:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 06:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 06:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "yeahaa" (Mon Sep 03 2018 07:06:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Q4YkZi2m7Mop9q59ACB_ 0x00 Calls: 4843 (Mon Sep 03 2018 07:15:35 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Mon Sep 03 2018 07:15:36 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Mon Sep 03 2018 07:16:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 07:22:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 07:22:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 07:22:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 07:22:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Toz6vs5iLbu6V4bLACCe Troll Calls: 39 (Mon Sep 03 2018 07:22:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 07:22:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: iPaCYn7N8jKA8ihLACCb Curse Calls: 342 (Mon Sep 03 2018 07:22:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZzYDMg3ZNJE0Rv00ACCd Sinstrite Calls: 471 (Mon Sep 03 2018 07:22:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: HTBZqLixhDLi-ZwXACCc Shield Calls: 328 (Mon Sep 03 2018 07:22:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 07:22:55 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 07:22:55 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 07:22:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 07:34:36 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 07:35:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OaZFq4eu5zYWBLjSACCX Pluu Calls: 64688 (Mon Sep 03 2018 07:38:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: nn4EChPmLvtFXhmuACCY Pure Calls: 64497 (Mon Sep 03 2018 07:38:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: MuJ7wXN-6tdPGKbfACCW Cozi Calls: 64719 (Mon Sep 03 2018 07:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 07:38:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 07:38:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 07:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 07:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 07:38:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 07:38:40 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 07:39:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZDZkEQuL0gVWkfflACCP Scythe Calls: 174746 (Mon Sep 03 2018 07:39:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: aswOXHNtwW9GOWMrACCQ Silent Calls: 60677 (Mon Sep 03 2018 07:39:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 07:39:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 07:39:27 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 07:40:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 07:40:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 08:07:50 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 08:07:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 08:07:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 08:08:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: L8ebnyqS_68KhCpeACCo Troll Calls: 39 (Mon Sep 03 2018 08:08:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 08:08:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UvcBQTlim-nm7mlNACCn Shield Calls: 508 (Mon Sep 03 2018 08:09:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: n2pdf-Yuqgwemk1KACCm Sinstrite Calls: 785 (Mon Sep 03 2018 08:09:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2haKscTbOb6C6HlHACCl Curse Calls: 552 (Mon Sep 03 2018 08:09:04 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 08:09:05 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 08:09:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 08:09:06 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 08:10:40 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 08:10:49 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 08:10:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: P2a_VZ29X46OvUWbACCZ yeahaa Calls: 55 (Mon Sep 03 2018 08:11:03 GMT+0000 (Coordinated Universal Time)) +stop_character: yeahaa owner: 4765522570772480 bank: false (Mon Sep 03 2018 08:11:04 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 08:11:04 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 08:11:15 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 08:11:18 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 08:11:26 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 08:11:53 GMT+0000 (Coordinated Universal Time)) +start_character: "yeahaa" (Mon Sep 03 2018 08:36:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IO6dHO9hdw6kpIJjACCg Pluu Calls: 64478 (Mon Sep 03 2018 08:38:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: nGV4NufgbIZAu5j1ACCh Pure Calls: 64659 (Mon Sep 03 2018 08:38:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tuu2bjoGnujo5JbyACCi Cozi Calls: 64029 (Mon Sep 03 2018 08:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 08:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 08:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 08:38:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 08:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 08:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 08:38:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6pYXrR3A-4X5mQ1OACCA Foaly Calls: 10 (Mon Sep 03 2018 08:51:35 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Mon Sep 03 2018 08:51:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Mon Sep 03 2018 08:52:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 08:54:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 08:54:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 08:54:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 08:54:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: l2Ggr2EZaW7C1xx9ACCz Troll Calls: 39 (Mon Sep 03 2018 08:54:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 08:54:29 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Mon Sep 03 2018 08:54:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UplbT8v9lD-3l0BaACCy Sinstrite Calls: 492 (Mon Sep 03 2018 08:54:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Je0JPwH3-Bx8OJuhACCw Curse Calls: 379 (Mon Sep 03 2018 08:54:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: iywomVz1AGB9prBGACCx Shield Calls: 357 (Mon Sep 03 2018 08:54:55 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 08:54:56 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 08:54:56 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 08:54:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: qaox_2GPsaio07hJACC1 SweetPea Calls: 40 (Mon Sep 03 2018 08:55:07 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Mon Sep 03 2018 08:55:08 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Mon Sep 03 2018 09:02:03 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Mon Sep 03 2018 09:02:32 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Mon Sep 03 2018 09:02:50 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Mon Sep 03 2018 09:03:01 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Mon Sep 03 2018 09:03:34 GMT+0000 (Coordinated Universal Time)) +mount_user: SweetPea owner: 5736224816889856 (Mon Sep 03 2018 09:04:52 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: SweetPea owner: 5736224816889856 (Mon Sep 03 2018 09:05:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IaY0u1FBC4yVkbbBACC2 SweetPea Calls: 219 (Mon Sep 03 2018 09:06:44 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Mon Sep 03 2018 09:06:45 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: lT5GX7UNmVYoAz4NACCq yeahaa Calls: 7 (Mon Sep 03 2018 09:31:24 GMT+0000 (Coordinated Universal Time)) +stop_character: yeahaa owner: 4765522570772480 bank: false (Mon Sep 03 2018 09:31:25 GMT+0000 (Coordinated Universal Time)) +start_character: "yeahaa" (Mon Sep 03 2018 09:32:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: XeMyCFeZgLiXI9ULACCr Pluu Calls: 64665 (Mon Sep 03 2018 09:38:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YWmzvjrgpYxGA9DfACCs Pure Calls: 64386 (Mon Sep 03 2018 09:38:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: BRbRJOJdS5LE7oRbACCt Cozi Calls: 64329 (Mon Sep 03 2018 09:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 09:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 09:38:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 09:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 09:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 09:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 09:38:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 09:39:50 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 09:39:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 09:39:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 09:40:01 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 09:40:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 09:40:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: cKzm12GKmdtjIlHDACC- Troll Calls: 38 (Mon Sep 03 2018 09:40:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 09:40:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ZgMvfllF9sKgXxHuACC8 Shield Calls: 695 (Mon Sep 03 2018 09:41:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rdew3r57Jhr_NJwBACC9 Sinstrite Calls: 1174 (Mon Sep 03 2018 09:41:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Q61vIW-AE_KJ1VEAACC7 Curse Calls: 682 (Mon Sep 03 2018 09:41:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 09:41:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 09:41:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 09:41:24 GMT+0000 (Coordinated Universal Time)) +mount_user: yeahaa owner: 4765522570772480 (Mon Sep 03 2018 10:00:16 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: yeahaa owner: 4765522570772480 (Mon Sep 03 2018 10:00:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DUAxmc3p7F-2mmuTACC3 yeahaa Calls: 33 (Mon Sep 03 2018 10:03:15 GMT+0000 (Coordinated Universal Time)) +stop_character: yeahaa owner: 4765522570772480 bank: false (Mon Sep 03 2018 10:03:16 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 10:26:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 10:26:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 10:26:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 10:26:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: oSj3nwLa-f0-nAOOACDD Troll Calls: 38 (Mon Sep 03 2018 10:26:49 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 10:26:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: azlIsJJBFlkocDcbACDC Shield Calls: 362 (Mon Sep 03 2018 10:27:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: feE2rOvgqzlLhj0IACDB Sinstrite Calls: 559 (Mon Sep 03 2018 10:27:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: X84kFz9BGiyei5v9ACDA Curse Calls: 392 (Mon Sep 03 2018 10:27:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 10:27:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 10:27:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 10:27:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Gv4H1C5ppntGhSORACC4 Pluu Calls: 64788 (Mon Sep 03 2018 10:38:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: AT7o_yzsHddVpSJtACC5 Pure Calls: 64182 (Mon Sep 03 2018 10:38:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SwV4a-lX7BDQhNEvACC6 Cozi Calls: 64166 (Mon Sep 03 2018 10:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 10:38:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 10:38:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 10:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 10:38:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 10:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 10:38:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 11:12:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 11:12:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 11:12:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 11:13:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5DdRUqocZnscys1CACDL Troll Calls: 38 (Mon Sep 03 2018 11:13:09 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 11:13:09 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 9z1fNREfwJnqgNsdACDJ Sinstrite Calls: 816 (Mon Sep 03 2018 11:13:35 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: oNHOt8ZNbZ0fWyamACDI Curse Calls: 597 (Mon Sep 03 2018 11:13:35 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Z_21FHMgIueLNjjvACDK Shield Calls: 594 (Mon Sep 03 2018 11:13:35 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 11:13:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 11:13:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 11:13:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: pV-mkb56JxcpuxQiACCu Foaly Calls: 8 (Mon Sep 03 2018 11:25:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Mon Sep 03 2018 11:25:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Mon Sep 03 2018 11:26:42 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 11:32:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 8sJQB1HqD5RMON1FACCj Scythe Calls: 507735 (Mon Sep 03 2018 11:32:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 11:32:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UcpEVzWWWZsW2b0dACCk Silent Calls: 176753 (Mon Sep 03 2018 11:32:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 11:32:28 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 11:33:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 11:34:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: oXnD-AUTeNV7-kiwACDF Pluu Calls: 64303 (Mon Sep 03 2018 11:38:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UvOVHgzhRk23MK1HACDH Pure Calls: 64355 (Mon Sep 03 2018 11:38:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: HHidOkXZzzle1DbKACDG Cozi Calls: 64466 (Mon Sep 03 2018 11:38:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 11:38:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 11:38:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 11:38:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 11:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 11:38:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 11:38:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: HPDY2piWyiigLSc9ACDS Cozi Calls: 6878 (Mon Sep 03 2018 11:44:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 11:44:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 11:45:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: u2tmCOt976n5vr23ACDV Cozi Calls: 547 (Mon Sep 03 2018 11:45:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 11:45:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: GJC-SVSHHfUcXVAVACDT Pure Calls: 7702 (Mon Sep 03 2018 11:45:42 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 11:45:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 11:45:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 11:46:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mTTDd-4sAwy6rAxiACDX Pure Calls: 235 (Mon Sep 03 2018 11:46:04 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 11:46:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: BITBa7sdt676U0qXACDR Pluu Calls: 8173 (Mon Sep 03 2018 11:46:09 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 11:46:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 11:46:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3IzNbeDpkHu-dtqVACDa Pluu Calls: 275 (Mon Sep 03 2018 11:46:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 11:46:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 11:46:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 11:47:02 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 11:47:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mpisQeDhOc4Z8upzACDP Scythe Calls: 29868 (Mon Sep 03 2018 11:47:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ESsKC59W6b6SLk86ACDQ Silent Calls: 10153 (Mon Sep 03 2018 11:47:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 11:47:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 11:47:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 11:48:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 11:48:46 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 11:48:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: InLlR787lPHTJgKyACDe Scythe Calls: 243 (Mon Sep 03 2018 11:48:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: A-9UrsYTKDZNPcYNACDf Silent Calls: 4 (Mon Sep 03 2018 11:48:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 11:48:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 11:48:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 11:49:59 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 11:50:05 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 11:50:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: cKR-Q6z7QfsJUdKpACDg Scythe Calls: 274 (Mon Sep 03 2018 11:50:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 4Y6qEsKuqWghNP-sACDh Silent Calls: 6 (Mon Sep 03 2018 11:50:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 11:50:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 11:50:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 11:51:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 11:51:29 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Mon Sep 03 2018 11:52:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2CnD77a-hMkYmQHLACDk SweetPea Calls: 25 (Mon Sep 03 2018 11:52:48 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Mon Sep 03 2018 11:52:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Buttercup" (Mon Sep 03 2018 11:55:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2AzpB72TxJ-2QQYVACDm Buttercup Calls: 13 (Mon Sep 03 2018 11:55:40 GMT+0000 (Coordinated Universal Time)) +stop_character: Buttercup owner: 5736224816889856 bank: false (Mon Sep 03 2018 11:55:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Buttercup" (Mon Sep 03 2018 11:57:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dxaPDL7oDOX6D39CACDn Buttercup Calls: 17 (Mon Sep 03 2018 11:57:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Buttercup owner: 5736224816889856 bank: false (Mon Sep 03 2018 11:57:53 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 11:58:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 11:58:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 11:58:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 11:59:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yjwxOvnLWn_wLxHVACDr Troll Calls: 39 (Mon Sep 03 2018 11:59:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 11:59:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -L2OdEtj5B9fcg-PACDq Sinstrite Calls: 806 (Mon Sep 03 2018 11:59:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: c515COrDvGeVsMSZACDp Shield Calls: 613 (Mon Sep 03 2018 11:59:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: B7JA1NuL6TC2YQ5FACDo Curse Calls: 587 (Mon Sep 03 2018 11:59:55 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 11:59:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 11:59:57 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 11:59:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: QHLYq-kek7aUnfOHACDN Foaly Calls: 6 (Mon Sep 03 2018 12:05:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Mon Sep 03 2018 12:05:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Mon Sep 03 2018 12:06:55 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Mon Sep 03 2018 12:12:54 GMT+0000 (Coordinated Universal Time)) +start_character: "riverdusty" (Mon Sep 03 2018 12:16:14 GMT+0000 (Coordinated Universal Time)) +mount_user: riverdusty owner: 5736224816889856 (Mon Sep 03 2018 12:16:21 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: riverdusty owner: 5736224816889856 (Mon Sep 03 2018 12:16:27 GMT+0000 (Coordinated Universal Time)) +start_character: "MuppPriest" (Mon Sep 03 2018 12:16:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Mupp" (Mon Sep 03 2018 12:16:32 GMT+0000 (Coordinated Universal Time)) +start_character: "MuppArch" (Mon Sep 03 2018 12:16:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7Q4gDxsRYF92kFWvACDx riverdusty Calls: 28 (Mon Sep 03 2018 12:16:50 GMT+0000 (Coordinated Universal Time)) +stop_character: riverdusty owner: 5736224816889856 bank: false (Mon Sep 03 2018 12:16:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: nljec4OuR8WlQx5CACDv SweetPea Calls: 52 (Mon Sep 03 2018 12:40:42 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Mon Sep 03 2018 12:40:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 12:44:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 12:44:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 12:45:00 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 12:45:05 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 12:45:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 12:46:11 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IHdM5xTnmTBXJXtHACD5 Troll Calls: 39 (Mon Sep 03 2018 12:46:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 12:46:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: lRTmpGJPSm7fkCG2ACD3 Sinstrite Calls: 785 (Mon Sep 03 2018 12:46:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3ka47pdqe92KQAEhACD4 Shield Calls: 785 (Mon Sep 03 2018 12:46:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KDGerkpYHKpTE9ZOACD2 Curse Calls: 799 (Mon Sep 03 2018 12:46:44 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 12:46:46 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 12:46:46 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 12:46:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wmVJymSUgHyNGfR-ACDd Pluu Calls: 73201 (Mon Sep 03 2018 12:55:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 66xTf3uLbX1ZBhn3ACDb Pure Calls: 73660 (Mon Sep 03 2018 12:55:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zrTOgrZrAh618hlZACDY Cozi Calls: 74810 (Mon Sep 03 2018 12:55:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 12:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 12:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 12:55:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 12:55:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 12:55:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 12:55:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: K069cAQbztBfCCPeACA4 TexTheTank Calls: 89966 (Mon Sep 03 2018 12:56:20 GMT+0000 (Coordinated Universal Time)) +stop_character: TexTheTank owner: 6609080732876800 bank: false (Mon Sep 03 2018 12:56:20 GMT+0000 (Coordinated Universal Time)) +mount_user: Carolina owner: 6609080732876800 (Mon Sep 03 2018 12:58:22 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Carolina owner: 6609080732876800 (Mon Sep 03 2018 12:59:24 GMT+0000 (Coordinated Universal Time)) +mount_user: Carolina owner: 6609080732876800 (Mon Sep 03 2018 13:02:10 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Carolina owner: 6609080732876800 (Mon Sep 03 2018 13:02:19 GMT+0000 (Coordinated Universal Time)) +mount_user: Carolina owner: 6609080732876800 (Mon Sep 03 2018 13:02:32 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Carolina owner: 6609080732876800 (Mon Sep 03 2018 13:03:04 GMT+0000 (Coordinated Universal Time)) +start_character: "TexTheTank" (Mon Sep 03 2018 13:06:17 GMT+0000 (Coordinated Universal Time)) +mount_user: TexTheTank owner: 6609080732876800 (Mon Sep 03 2018 13:06:33 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: TexTheTank owner: 6609080732876800 (Mon Sep 03 2018 13:07:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bYirTms89lGz6J_IACD- TexTheTank Calls: 219 (Mon Sep 03 2018 13:09:07 GMT+0000 (Coordinated Universal Time)) +stop_character: TexTheTank owner: 6609080732876800 bank: false (Mon Sep 03 2018 13:09:07 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 13:18:53 GMT+0000 (Coordinated Universal Time)) +start_character: "SansSupport" (Mon Sep 03 2018 13:22:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 13:31:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 13:31:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 13:31:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 13:32:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rKEL45DalAcx7q1dACED Troll Calls: 39 (Mon Sep 03 2018 13:32:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 13:32:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: kknNJ-F4lQZ2RzDTACEC Sinstrite Calls: 737 (Mon Sep 03 2018 13:32:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: BwR8smoI-4WOC_bRACEA Curse Calls: 514 (Mon Sep 03 2018 13:32:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: FF-ZscTfDSkqRualACEB Shield Calls: 508 (Mon Sep 03 2018 13:32:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 13:32:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 13:32:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 13:32:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NVZo2k4WbwxjIbWIACDi Scythe Calls: 226736 (Mon Sep 03 2018 13:36:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: HfgZWbxldnjG2ca0ACDj Silent Calls: 79139 (Mon Sep 03 2018 13:36:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 13:36:12 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 13:36:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 13:38:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 13:38:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YoDInzjkJ6B31iISACEG Silent Calls: 220 (Mon Sep 03 2018 13:38:40 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 4vuSET-xM8OIQk8IACEF Scythe Calls: 431 (Mon Sep 03 2018 13:38:40 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 13:38:40 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 13:38:41 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 13:38:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 13:39:02 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 13:39:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7oePduXy6Keg-eifACEH Scythe Calls: 240 (Mon Sep 03 2018 13:39:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 13:39:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Lzpk_kZFWZzlZT7mACEI Silent Calls: 6 (Mon Sep 03 2018 13:39:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 13:39:04 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC BlazingSnip (Mon Sep 03 2018 13:39:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: s78ZBWpNPM95uTfMACBC BlazingSnip Calls: 442691 (Mon Sep 03 2018 13:39:55 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Mon Sep 03 2018 13:39:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 13:40:10 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 13:40:16 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Mon Sep 03 2018 13:41:15 GMT+0000 (Coordinated Universal Time)) +start_character: "lissandra" (Mon Sep 03 2018 13:46:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 638q0Ht-XytTap0ZACEM lissandra Calls: 49 (Mon Sep 03 2018 13:46:38 GMT+0000 (Coordinated Universal Time)) +stop_character: lissandra owner: 5793534377459712 bank: false (Mon Sep 03 2018 13:46:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uzmN0tkjFFgJKzcwACD9 Pluu Calls: 64072 (Mon Sep 03 2018 13:55:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: hH5otcxzBO6qS0A0ACD7 Pure Calls: 64975 (Mon Sep 03 2018 13:55:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 07c2wz9dMcCSDrotACD8 Cozi Calls: 64154 (Mon Sep 03 2018 13:55:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 13:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 13:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 13:55:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 13:55:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 13:55:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 13:55:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 14:17:51 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 14:17:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 14:17:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 14:18:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: EDLrkAH9xjZtQGo-ACET Troll Calls: 38 (Mon Sep 03 2018 14:18:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 14:18:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Z7uRE1MhadRX9m3QACES Sinstrite Calls: 527 (Mon Sep 03 2018 14:19:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TTrpqzY6zq-WLKMrACER Shield Calls: 566 (Mon Sep 03 2018 14:19:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: CATyq3Ar-sbSPsVKACEQ Curse Calls: 539 (Mon Sep 03 2018 14:19:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 14:19:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 14:19:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 14:19:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Voc5mZTQOXxLfvF2ACEL BlazingSnip Calls: 195 (Mon Sep 03 2018 14:20:08 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Mon Sep 03 2018 14:20:08 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Mon Sep 03 2018 14:20:19 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 14:31:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: C6fYdKt_R9DjZd6gACEJ Scythe Calls: 113343 (Mon Sep 03 2018 14:31:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xW9o89yJ7dNcU6gAACEK Silent Calls: 39303 (Mon Sep 03 2018 14:31:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:31:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:31:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 14:32:52 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 14:32:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OoiPCKsZ1vkdJ8b-ACEX Scythe Calls: 221 (Mon Sep 03 2018 14:32:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:32:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: cmZfmtWiFoVyJFv3ACCa 0x00 Calls: 17925 (Mon Sep 03 2018 14:33:36 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: true (Mon Sep 03 2018 14:33:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 14:34:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 14:34:24 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Mon Sep 03 2018 14:34:45 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 14:34:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xFUxycLv5hOb5WsJACEY Scythe Calls: 1223 (Mon Sep 03 2018 14:34:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:34:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 3MQEFHsTI2u5MWN1ACEZ Silent Calls: 284 (Mon Sep 03 2018 14:34:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:34:48 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 14:36:01 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 14:36:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: adRql6KIi0WFjcDhACEb Scythe Calls: 343 (Mon Sep 03 2018 14:36:10 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:36:11 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 14:37:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 14:37:43 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 14:37:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: MnG0TF-QQOj4bf10ACEd Scythe Calls: 369 (Mon Sep 03 2018 14:37:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YAUyZlcAxP6FmKqXACEe Silent Calls: 5 (Mon Sep 03 2018 14:37:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:37:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:37:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 14:38:56 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 14:39:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KoS2AiWOvbdur7XoACEf Scythe Calls: 265 (Mon Sep 03 2018 14:39:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:39:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 14:40:17 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 14:40:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mSaZRcW6ufcW2KgZACEg Scythe Calls: 214 (Mon Sep 03 2018 14:40:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:40:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 14:41:39 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 14:41:47 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TgJOPApimuPD6mBwACEh Scythe Calls: 260 (Mon Sep 03 2018 14:41:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:41:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 14:43:07 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 14:43:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: sA3Iwo__PbT2EYcKACEi Scythe Calls: 312 (Mon Sep 03 2018 14:43:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:43:15 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 14:44:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 14:44:47 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 14:53:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mgHF5qlRq1f6YCDHACEk Scythe Calls: 19669 (Mon Sep 03 2018 14:53:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:53:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DQl0nB1PUo_uOFMPACEl Silent Calls: 6660 (Mon Sep 03 2018 14:53:32 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:53:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 14:54:53 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 14:54:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UbEcFaZhT7Tx3PhlACEm Scythe Calls: 210 (Mon Sep 03 2018 14:54:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:55:00 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 1vGZGGToF__jtfMeACEP Pluu Calls: 64930 (Mon Sep 03 2018 14:55:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uqredwfNVtPxjyBEACEO Pure Calls: 64100 (Mon Sep 03 2018 14:55:17 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: RuFZH4a9pFJ4GMXfACEN Cozi Calls: 64082 (Mon Sep 03 2018 14:55:17 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 14:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 14:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 14:55:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 14:55:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 14:55:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 14:55:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 14:56:24 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 14:56:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NguAd725gEakbmHKACEq Scythe Calls: 215 (Mon Sep 03 2018 14:56:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:56:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 14:57:36 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 14:57:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Kc_Lbu-5pI9PpPr6ACEr Scythe Calls: 239 (Mon Sep 03 2018 14:57:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 14:57:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 14:59:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 14:59:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 15:04:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 15:04:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 15:04:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 15:04:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wZ_XqfiR9GoS_2QKACEx Troll Calls: 39 (Mon Sep 03 2018 15:04:49 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 15:04:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: M-IQpuXUf5eiPKAKACEv Sinstrite Calls: 507 (Mon Sep 03 2018 15:05:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OkaKfUoPOp7I-tCiACEu Curse Calls: 534 (Mon Sep 03 2018 15:05:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: sh0DdOc7Wou0Ex82ACEw Shield Calls: 512 (Mon Sep 03 2018 15:05:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 15:05:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 15:05:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 15:05:15 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Mon Sep 03 2018 15:11:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bdAWZN1h9AF-l0mJACE0 SweetPea Calls: 7 (Mon Sep 03 2018 15:12:06 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Mon Sep 03 2018 15:12:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 4L1it-9KAh2Sd5PAACEa 0x00 Calls: 1528 (Mon Sep 03 2018 15:12:27 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Mon Sep 03 2018 15:12:27 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Mon Sep 03 2018 15:17:15 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 15:18:03 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 15:18:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xlL0Oy8mHtZXzuAWACDt Foaly Calls: 48 (Mon Sep 03 2018 15:33:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Mon Sep 03 2018 15:33:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Mon Sep 03 2018 15:34:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fitL_jQT1FinZS92ACE2 Foaly Calls: 35 (Mon Sep 03 2018 15:37:11 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Mon Sep 03 2018 15:37:11 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Mon Sep 03 2018 15:38:40 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC SansSupport (Mon Sep 03 2018 15:46:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dtWJih7n91fm9DP1ACD_ SansSupport Calls: 244987 (Mon Sep 03 2018 15:46:22 GMT+0000 (Coordinated Universal Time)) +stop_character: SansSupport owner: 6609080732876800 bank: false (Mon Sep 03 2018 15:46:22 GMT+0000 (Coordinated Universal Time)) +start_character: "SansSupport" (Mon Sep 03 2018 15:47:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 15:50:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 15:50:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 15:50:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 15:50:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Hktn5Q5tr8sPnRi2ACE_ Troll Calls: 38 (Mon Sep 03 2018 15:50:39 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 15:50:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: K3NnjPoKZuZE8qs3ACE8 Curse Calls: 389 (Mon Sep 03 2018 15:51:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Hl3OHH1uiVRWcezfACE- Sinstrite Calls: 366 (Mon Sep 03 2018 15:51:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TnYuIOfwCw95s_xMACE9 Shield Calls: 374 (Mon Sep 03 2018 15:51:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 15:51:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 15:51:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 15:51:07 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Mon Sep 03 2018 15:51:07 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 15:51:43 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 15:51:45 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: iV0lzgLUhEjRX7Q_ACFB SweetPea Calls: 17 (Mon Sep 03 2018 15:51:53 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Mon Sep 03 2018 15:51:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: CNiT2AWnP331EPd_ACEn Pluu Calls: 64832 (Mon Sep 03 2018 15:55:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PZ4oQgqVlzPz0xpKACEp Pure Calls: 64143 (Mon Sep 03 2018 15:55:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: AU_zGux1HTUK9mirACEo Cozi Calls: 64944 (Mon Sep 03 2018 15:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 15:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 15:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 15:55:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 15:55:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 15:55:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 15:55:22 GMT+0000 (Coordinated Universal Time)) +start_character: "lissandra" (Mon Sep 03 2018 16:03:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 4e1__F65Z-ZxccgSACFG lissandra Calls: 90 (Mon Sep 03 2018 16:03:43 GMT+0000 (Coordinated Universal Time)) +stop_character: lissandra owner: 5793534377459712 bank: false (Mon Sep 03 2018 16:03:43 GMT+0000 (Coordinated Universal Time)) +start_character: "lissandra" (Mon Sep 03 2018 16:05:37 GMT+0000 (Coordinated Universal Time)) +mount_user: lissandra owner: 5793534377459712 (Mon Sep 03 2018 16:08:01 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: lissandra owner: 5793534377459712 (Mon Sep 03 2018 16:08:11 GMT+0000 (Coordinated Universal Time)) +mount_user: lissandra owner: 5793534377459712 (Mon Sep 03 2018 16:09:02 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: lissandra owner: 5793534377459712 (Mon Sep 03 2018 16:10:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 16:36:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 16:36:10 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 16:36:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 16:37:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vjyWeGELibyd9MonACFM Troll Calls: 39 (Mon Sep 03 2018 16:37:59 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 16:37:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Fl-0-1brvWky74QIACFK Sinstrite Calls: 1159 (Mon Sep 03 2018 16:38:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OJcccSZa6bC2pk-8ACFL Shield Calls: 1138 (Mon Sep 03 2018 16:38:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0LZI8zMbWg3hjhI4ACFJ Curse Calls: 994 (Mon Sep 03 2018 16:38:25 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 16:38:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 16:38:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 16:38:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vtLlGscuSxDdoOouACFC Pluu Calls: 64083 (Mon Sep 03 2018 16:55:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TQrrPGMIZy9IeI0pACFD Pure Calls: 64369 (Mon Sep 03 2018 16:55:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: lfHM6t0bZj4qJtQxACFE Cozi Calls: 64682 (Mon Sep 03 2018 16:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 16:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 16:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 16:55:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 16:55:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 16:55:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 16:55:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OTneJE75oUXrIxZJACFI lissandra Calls: 7690 (Mon Sep 03 2018 17:01:22 GMT+0000 (Coordinated Universal Time)) +stop_character: lissandra owner: 5793534377459712 bank: false (Mon Sep 03 2018 17:01:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bBlY-IdAx4NssJiNACEt Silent Calls: 93819 (Mon Sep 03 2018 17:02:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 1048p4ClcxVhVTIHACEs Scythe Calls: 269755 (Mon Sep 03 2018 17:02:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 17:02:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 17:02:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 17:06:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 17:06:22 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ePWr_sJWmsVuePXdACFS Scythe Calls: 11623 (Mon Sep 03 2018 17:11:35 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: a6zoHbkfGnMsl3CyACFT Silent Calls: 3973 (Mon Sep 03 2018 17:11:35 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 17:11:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 17:11:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 17:12:03 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 17:12:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Rocky" (Mon Sep 03 2018 17:21:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 17:23:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 17:23:27 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 17:23:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 17:23:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PtciSFWNN5pWnd6LACFa Troll Calls: 39 (Mon Sep 03 2018 17:23:49 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 17:23:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: U3DGCrmwyUFGj6z6ACFZ Shield Calls: 358 (Mon Sep 03 2018 17:24:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ViB5-3mkuAw-_ANSACFY Sinstrite Calls: 372 (Mon Sep 03 2018 17:24:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: jgtSFNKLD0sFeyo1ACFX Curse Calls: 383 (Mon Sep 03 2018 17:24:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 17:24:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 17:24:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 17:24:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 1yZe9IVw9ooLOcY2ACFW Rocky Calls: 304 (Mon Sep 03 2018 17:24:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Rocky owner: 4832405143683072 bank: false (Mon Sep 03 2018 17:24:23 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 17:25:23 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 17:26:44 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 17:26:48 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 17:26:56 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 17:27:20 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 17:27:24 GMT+0000 (Coordinated Universal Time)) +mount_user: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 17:27:31 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: 0x00 owner: 5457622628040704 (Mon Sep 03 2018 17:28:39 GMT+0000 (Coordinated Universal Time)) +start_character: "lissandra" (Mon Sep 03 2018 17:32:38 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 17:32:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: FdXe5Ez4V52_8ZEcACFU Scythe Calls: 45311 (Mon Sep 03 2018 17:32:42 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 17:32:42 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tA3fweRxnOnq6RBoACFV Silent Calls: 15682 (Mon Sep 03 2018 17:32:42 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 17:32:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: T4kKGHOv12WI8W37ACFc lissandra Calls: 65 (Mon Sep 03 2018 17:33:05 GMT+0000 (Coordinated Universal Time)) +stop_character: lissandra owner: 5793534377459712 bank: false (Mon Sep 03 2018 17:33:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 17:34:00 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 17:34:06 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xSJJcQmfjFAs9omzACE5 Foaly Calls: 37 (Mon Sep 03 2018 17:37:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Mon Sep 03 2018 17:37:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Mon Sep 03 2018 17:39:00 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Mon Sep 03 2018 17:43:56 GMT+0000 (Coordinated Universal Time)) +Main loop took 21ms (Mon Sep 03 2018 17:46:27 GMT+0000 (Coordinated Universal Time)) +mount_user: MuppPriest owner: 5552666278100992 (Mon Sep 03 2018 17:46:29 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MuppPriest owner: 5552666278100992 (Mon Sep 03 2018 17:46:41 GMT+0000 (Coordinated Universal Time)) +mount_user: MuppPriest owner: 5552666278100992 (Mon Sep 03 2018 17:46:56 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MuppPriest owner: 5552666278100992 (Mon Sep 03 2018 17:47:03 GMT+0000 (Coordinated Universal Time)) +mount_user: MuppPriest owner: 5552666278100992 (Mon Sep 03 2018 17:47:36 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MuppPriest owner: 5552666278100992 (Mon Sep 03 2018 17:47:39 GMT+0000 (Coordinated Universal Time)) +mount_user: Mupp owner: 5552666278100992 (Mon Sep 03 2018 17:49:08 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Mupp owner: 5552666278100992 (Mon Sep 03 2018 17:49:28 GMT+0000 (Coordinated Universal Time)) +mount_user: Mupp owner: 5552666278100992 (Mon Sep 03 2018 17:49:53 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Mupp owner: 5552666278100992 (Mon Sep 03 2018 17:50:08 GMT+0000 (Coordinated Universal Time)) +mount_user: Mupp owner: 5552666278100992 (Mon Sep 03 2018 17:50:24 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Mupp owner: 5552666278100992 (Mon Sep 03 2018 17:50:39 GMT+0000 (Coordinated Universal Time)) +mount_user: Mupp owner: 5552666278100992 (Mon Sep 03 2018 17:51:09 GMT+0000 (Coordinated Universal Time)) +mount_user: MuppArch owner: 5552666278100992 (Mon Sep 03 2018 17:51:18 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: MuppArch in-bank: Mupp (Mon Sep 03 2018 17:51:18 GMT+0000 (Coordinated Universal Time)) +mount_user: MuppArch owner: 5552666278100992 (Mon Sep 03 2018 17:51:19 GMT+0000 (Coordinated Universal Time)) +mount_user[failed]: MuppArch in-bank: Mupp (Mon Sep 03 2018 17:51:19 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Mupp owner: 5552666278100992 (Mon Sep 03 2018 17:51:36 GMT+0000 (Coordinated Universal Time)) +mount_user: MuppArch owner: 5552666278100992 (Mon Sep 03 2018 17:52:42 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: MuppArch owner: 5552666278100992 (Mon Sep 03 2018 17:52:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mOmt525evRFPY7ZHACFO Pluu Calls: 64615 (Mon Sep 03 2018 17:55:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: _8RFxSVYYpwrAEf4ACFQ Pure Calls: 64369 (Mon Sep 03 2018 17:55:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SZr4K13N2FW8OmADACFP Cozi Calls: 64055 (Mon Sep 03 2018 17:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 17:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 17:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 17:55:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 17:55:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 17:55:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 17:55:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Ifc2I8fILhI5MmW4ACFh SweetPea Calls: 22 (Mon Sep 03 2018 17:58:18 GMT+0000 (Coordinated Universal Time)) +stop_character: SweetPea owner: 5736224816889856 bank: false (Mon Sep 03 2018 17:58:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7jggf9Npa1Qo-gCeACFf Foaly Calls: 8 (Mon Sep 03 2018 17:58:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Mon Sep 03 2018 17:58:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Mon Sep 03 2018 18:01:39 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Mon Sep 03 2018 18:02:11 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Mon Sep 03 2018 18:02:25 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Mon Sep 03 2018 18:02:48 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Mon Sep 03 2018 18:02:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Mon Sep 03 2018 18:02:59 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Mon Sep 03 2018 18:03:05 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Mon Sep 03 2018 18:03:50 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Mon Sep 03 2018 18:03:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Mon Sep 03 2018 18:04:49 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Mon Sep 03 2018 18:04:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zyRck85CDIfq3XGKACFn Foaly Calls: 197 (Mon Sep 03 2018 18:05:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Mon Sep 03 2018 18:05:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 18:09:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 18:09:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 18:09:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 18:09:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: jLTZIlH98etNcZT4AB-H Lootbot Calls: 2432584 (Mon Sep 03 2018 18:09:36 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: APMyBy6e_OuamDKvACFr Curse Calls: 175 (Mon Sep 03 2018 18:09:36 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: QL0ZjK47Qv96-uOTACFs Sinstrite Calls: 203 (Mon Sep 03 2018 18:09:36 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: FUWQsk5-v_FelU7dACFt Shield Calls: 142 (Mon Sep 03 2018 18:09:36 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: k2s_6wMepTGcyJHCACFw Troll Calls: 37 (Mon Sep 03 2018 18:09:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Lootbot owner: 5145329831772160 bank: false (Mon Sep 03 2018 18:09:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 18:09:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 18:09:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 18:09:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 18:09:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Maela" (Mon Sep 03 2018 18:10:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 18:10:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Lootbot" (Mon Sep 03 2018 18:10:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 18:10:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 18:10:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zMrScxXNjqLYbcZLACFx Maela Calls: 500 (Mon Sep 03 2018 18:11:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Maela owner: 4909785279365120 bank: false (Mon Sep 03 2018 18:11:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: MnVmlncvoFQfPbnlACF1 Sinstrite Calls: 227 (Mon Sep 03 2018 18:11:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IilONojyUmKtehnPACF2 Shield Calls: 207 (Mon Sep 03 2018 18:11:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wTtdDclZ4gcHyG_NACFz Curse Calls: 235 (Mon Sep 03 2018 18:11:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 18:11:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 18:11:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 18:11:16 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Mon Sep 03 2018 18:12:53 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 18:18:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tQCOBazA01N8cw5_ACFd Scythe Calls: 97559 (Mon Sep 03 2018 18:18:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 18:18:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: faDQw9ISxLa9NOXnACFe Silent Calls: 33734 (Mon Sep 03 2018 18:18:21 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 18:18:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 18:19:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 18:19:40 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 18:25:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UkVVKcD_uRlmMp6FACF6 Scythe Calls: 13839 (Mon Sep 03 2018 18:25:51 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 18:25:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wZc5zDkpBiD6KE4tACF7 Silent Calls: 4797 (Mon Sep 03 2018 18:25:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 18:25:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 18:27:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 18:27:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Goldbot" (Mon Sep 03 2018 18:29:02 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PqEhqEo28SyZzMFdACGA Goldbot Calls: 3 (Mon Sep 03 2018 18:29:02 GMT+0000 (Coordinated Universal Time)) +stop_character: Goldbot owner: 5145329831772160 bank: false (Mon Sep 03 2018 18:29:02 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 18:29:40 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SNPFdVJnQgB6qp0FACF- Scythe Calls: 5322 (Mon Sep 03 2018 18:29:40 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 18:29:40 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OHfpvAI6tOdJqNYrACF_ Silent Calls: 1775 (Mon Sep 03 2018 18:29:40 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 18:29:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 18:30:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 18:31:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Tycoon" (Mon Sep 03 2018 18:34:50 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: cdDJJNtHAucbse_yACGF Tycoon Calls: 3 (Mon Sep 03 2018 18:34:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Tycoon owner: 5145329831772160 bank: false (Mon Sep 03 2018 18:34:50 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Mon Sep 03 2018 18:43:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: U6b0hqoHvYaVoUXtACGC Scythe Calls: 27368 (Mon Sep 03 2018 18:43:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Mon Sep 03 2018 18:43:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 25EP8rNPVHRP0Ye_ACGD Silent Calls: 9535 (Mon Sep 03 2018 18:43:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Mon Sep 03 2018 18:43:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Mon Sep 03 2018 18:43:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Mon Sep 03 2018 18:43:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: IPxgv8DrDVpouCinACF0 Lootbot Calls: 43287 (Mon Sep 03 2018 18:44:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Lootbot owner: 5145329831772160 bank: false (Mon Sep 03 2018 18:44:17 GMT+0000 (Coordinated Universal Time)) +start_character: "Lootbot" (Mon Sep 03 2018 18:44:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: H0kfUt3Z3y5UAN-BACFm Pluu Calls: 64007 (Mon Sep 03 2018 18:55:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: -lqy17_Y3kGj3sxMACFl Pure Calls: 65000 (Mon Sep 03 2018 18:55:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: u3dQPvNGw2x8FqLuACFk Cozi Calls: 64030 (Mon Sep 03 2018 18:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 18:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 18:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 18:55:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 18:55:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 18:55:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 18:55:24 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 18:56:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 18:56:39 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 18:56:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 18:56:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NxTh6iVD5UoIb9usACGQ Troll Calls: 78 (Mon Sep 03 2018 18:56:56 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 18:56:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: RiYWDVRQc7xwUc3DACGO Sinstrite Calls: 360 (Mon Sep 03 2018 18:57:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: y7JznJSmxTZxJS7jACGP Shield Calls: 330 (Mon Sep 03 2018 18:57:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ELVgTiA8mdPI3H5mACGN Curse Calls: 357 (Mon Sep 03 2018 18:57:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 18:57:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 18:57:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 18:57:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6PGTg5og7opmdjGDACE7 SansSupport Calls: 8 (Mon Sep 03 2018 19:08:53 GMT+0000 (Coordinated Universal Time)) +stop_character: SansSupport owner: 6609080732876800 bank: false (Mon Sep 03 2018 19:08:53 GMT+0000 (Coordinated Universal Time)) +start_character: "SansSupport" (Mon Sep 03 2018 19:09:00 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Mon Sep 03 2018 19:18:16 GMT+0000 (Coordinated Universal Time)) +start_character: "BuyMyThings" (Mon Sep 03 2018 19:34:00 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Mon Sep 03 2018 19:36:19 GMT+0000 (Coordinated Universal Time)) +mount_user: Foaly owner: 4909785279365120 (Mon Sep 03 2018 19:36:26 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Mon Sep 03 2018 19:36:30 GMT+0000 (Coordinated Universal Time)) +mount_user: BuyMyThings owner: 4687219387269120 (Mon Sep 03 2018 19:36:33 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: BuyMyThings owner: 4687219387269120 (Mon Sep 03 2018 19:36:44 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Foaly owner: 4909785279365120 (Mon Sep 03 2018 19:36:45 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: WPHUkyfoQmUVHAKCACGV BuyMyThings Calls: 115 (Mon Sep 03 2018 19:36:50 GMT+0000 (Coordinated Universal Time)) +stop_character: BuyMyThings owner: 4687219387269120 bank: false (Mon Sep 03 2018 19:36:51 GMT+0000 (Coordinated Universal Time)) +start_character: "BuyMyThings" (Mon Sep 03 2018 19:36:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: l9BGDmeuuFjHu7QGACGW BuyMyThings Calls: 7 (Mon Sep 03 2018 19:37:18 GMT+0000 (Coordinated Universal Time)) +stop_character: BuyMyThings owner: 4687219387269120 bank: false (Mon Sep 03 2018 19:37:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 19:42:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 19:42:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 19:42:28 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 19:42:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: HlnLswCuyHd8W60zACGa Troll Calls: 39 (Mon Sep 03 2018 19:43:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 19:43:06 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 19:43:15 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 19:43:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dSkQofqF_bPjcHJkACGY Shield Calls: 502 (Mon Sep 03 2018 19:43:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wxLs1nFswzBc2BdhACGX Curse Calls: 493 (Mon Sep 03 2018 19:43:30 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KzeptUxj2oI-C-UqACGZ Sinstrite Calls: 468 (Mon Sep 03 2018 19:43:30 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 19:43:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 19:43:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 19:43:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: kPmc5hZOVmJqxJ7yACGL Pluu Calls: 64348 (Mon Sep 03 2018 19:55:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2y1plEX3nT3dKx90ACGK Pure Calls: 64861 (Mon Sep 03 2018 19:55:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wJFzlMEg1_VYpQrLACGM Cozi Calls: 63942 (Mon Sep 03 2018 19:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 19:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 19:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 19:55:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 19:55:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 19:55:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 19:55:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uGE17JjJ16HkSRl3ACGT MOBSans Calls: 94 (Mon Sep 03 2018 20:01:21 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Mon Sep 03 2018 20:01:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 20:28:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 20:28:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 20:28:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 20:28:48 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5PK1qTNvCmTmNYHoACGi Troll Calls: 39 (Mon Sep 03 2018 20:28:56 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 20:28:56 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ja_ZrT0H8pCw1N5AACGf Curse Calls: 372 (Mon Sep 03 2018 20:29:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: WGhQUWrngdI3o-mZACGh Sinstrite Calls: 342 (Mon Sep 03 2018 20:29:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YGkEJ3zfxNL8CykLACGg Shield Calls: 352 (Mon Sep 03 2018 20:29:21 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 20:29:21 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 20:29:21 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 20:29:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: aNoB2FjIxyCerE17ACGJ Lootbot Calls: 146404 (Mon Sep 03 2018 20:38:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Lootbot owner: 5145329831772160 bank: false (Mon Sep 03 2018 20:38:50 GMT+0000 (Coordinated Universal Time)) +start_character: "Lootbot" (Mon Sep 03 2018 20:39:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 47IqiV6NCwJ0jMzVACGd Pluu Calls: 64825 (Mon Sep 03 2018 20:55:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TwAzZPaMjNuIAUJuACGc Pure Calls: 64645 (Mon Sep 03 2018 20:55:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0VOTd-vi4B5pIl2uACGe Cozi Calls: 64350 (Mon Sep 03 2018 20:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 20:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 20:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 20:55:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 20:55:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 20:55:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 20:55:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DD91ZVbVri4RHwk6ACE1 0x00 Calls: 14603 (Mon Sep 03 2018 21:07:36 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Mon Sep 03 2018 21:07:37 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Mon Sep 03 2018 21:07:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 21:14:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 21:14:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 21:14:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 21:15:20 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 80GT5KzkTjJB_FlRACGv Troll Calls: 38 (Mon Sep 03 2018 21:15:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 21:15:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7KaATSVu2TdHvkWKACGu Shield Calls: 648 (Mon Sep 03 2018 21:15:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mZEvXkiSuEJfpLaRACGs Curse Calls: 658 (Mon Sep 03 2018 21:15:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zCKb7GwL96n0S7xAACGt Sinstrite Calls: 993 (Mon Sep 03 2018 21:15:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 21:15:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 21:15:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 21:15:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: oBmdYR-r1gdZyIQQACBy Trexnamedted Calls: 768676 (Mon Sep 03 2018 21:21:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: eyvTiCGU4EJqh-PeACBz Trexnamedtom Calls: 762049 (Mon Sep 03 2018 21:21:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: JH2rodfhtwOsd9KmACBx Trexnamedtut Calls: 764164 (Mon Sep 03 2018 21:21:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tN0dAkRSl4Fq7zSkACBw Trexnamedtod Calls: 215 (Mon Sep 03 2018 21:21:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Mon Sep 03 2018 21:21:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Mon Sep 03 2018 21:21:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Mon Sep 03 2018 21:21:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtod owner: 5209159389675520 bank: false (Mon Sep 03 2018 21:21:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: BwFj30H1wi_uaJaqACGn Pluu Calls: 64466 (Mon Sep 03 2018 21:55:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 4DVQH_aqT6EoOIbqACGo Pure Calls: 64858 (Mon Sep 03 2018 21:55:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UAw3bwc34bGzfMWtACGp Cozi Calls: 64945 (Mon Sep 03 2018 21:55:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 21:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 21:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 21:55:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 21:55:24 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 21:55:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 21:55:26 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtod" (Mon Sep 03 2018 21:59:52 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Mon Sep 03 2018 21:59:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Mon Sep 03 2018 21:59:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Mon Sep 03 2018 21:59:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 22:00:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 22:01:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 22:01:02 GMT+0000 (Coordinated Universal Time)) +mount_user: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 22:01:08 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Lootbot owner: 5145329831772160 (Mon Sep 03 2018 22:01:10 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 22:01:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: btYvBTPoE3TjfudiACG7 Troll Calls: 38 (Mon Sep 03 2018 22:01:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 22:01:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tZFaLUkgrPd4xoAqACG6 Sinstrite Calls: 506 (Mon Sep 03 2018 22:01:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KBdUUfW5e79w0VHWACG4 Curse Calls: 487 (Mon Sep 03 2018 22:01:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zkHbc-4Gwx8ksaDKACG5 Shield Calls: 510 (Mon Sep 03 2018 22:01:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 22:01:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 22:01:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 22:01:54 GMT+0000 (Coordinated Universal Time)) +start_character: "SpadarFaar" (Mon Sep 03 2018 22:30:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Brutus" (Mon Sep 03 2018 22:30:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Maela" (Mon Sep 03 2018 22:30:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: RszYksM6-yzJNKz3ACG8 SpadarFaar Calls: 786 (Mon Sep 03 2018 22:35:40 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Z2Ttv3vg6mEQHskQACG9 Brutus Calls: 551 (Mon Sep 03 2018 22:35:40 GMT+0000 (Coordinated Universal Time)) +stop_character: Brutus owner: 4909785279365120 bank: false (Mon Sep 03 2018 22:35:41 GMT+0000 (Coordinated Universal Time)) +stop_character: SpadarFaar owner: 4909785279365120 bank: false (Mon Sep 03 2018 22:35:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: bMLKBo4uIaDcNFsMACG- Maela Calls: 2756 (Mon Sep 03 2018 22:35:41 GMT+0000 (Coordinated Universal Time)) +stop_character: Maela owner: 4909785279365120 bank: false (Mon Sep 03 2018 22:35:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 22:46:53 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 22:46:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 22:46:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 22:47:11 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: iBEmhxRUI6AheLF4ACHG Troll Calls: 38 (Mon Sep 03 2018 22:47:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 22:47:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Wy9OJpbq8kaBhX2vACHD Curse Calls: 426 (Mon Sep 03 2018 22:47:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: tiaFd0PDY4PzVKqMACHF Sinstrite Calls: 431 (Mon Sep 03 2018 22:47:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vynpPkiYz0aMDLT3ACHE Shield Calls: 461 (Mon Sep 03 2018 22:47:43 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 22:47:44 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 22:47:44 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 22:47:44 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: jYSBEy3EWTvNYxBOACGx Pluu Calls: 64544 (Mon Sep 03 2018 22:55:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: CmKbtZLna-UHCHKcACGy Pure Calls: 64221 (Mon Sep 03 2018 22:55:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yS1VmSz1EE9lcVaoACGz Cozi Calls: 64912 (Mon Sep 03 2018 22:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 22:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 22:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 22:55:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 22:55:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 22:55:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 22:55:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PDPKgk9OrWs6KzvjACGS SansSupport Calls: 303681 (Mon Sep 03 2018 23:14:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ydRSVtAYS7DANWPJACA0 Carolina Calls: 360819 (Mon Sep 03 2018 23:14:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: XWefloQw5ly8rBWrACEW BlazingSnip Calls: 379198 (Mon Sep 03 2018 23:14:55 GMT+0000 (Coordinated Universal Time)) +stop_character: Carolina owner: 6609080732876800 bank: false (Mon Sep 03 2018 23:14:55 GMT+0000 (Coordinated Universal Time)) +stop_character: SansSupport owner: 6609080732876800 bank: false (Mon Sep 03 2018 23:14:55 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Mon Sep 03 2018 23:14:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Mon Sep 03 2018 23:32:43 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Mon Sep 03 2018 23:32:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Mon Sep 03 2018 23:32:48 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Mon Sep 03 2018 23:33:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 5Lks9LtousL94duvACHQ Troll Calls: 38 (Mon Sep 03 2018 23:33:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Mon Sep 03 2018 23:33:09 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Y8EFvdxzyJOfDM-qACHP Shield Calls: 431 (Mon Sep 03 2018 23:33:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: c3rp1_SU5AmLwWP_ACHO Sinstrite Calls: 587 (Mon Sep 03 2018 23:33:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: jDjECFWySinubo8mACHN Curse Calls: 424 (Mon Sep 03 2018 23:33:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Mon Sep 03 2018 23:33:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Mon Sep 03 2018 23:33:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Mon Sep 03 2018 23:33:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: W-qD0D7hdYssbcPKACHI Pluu Calls: 64955 (Mon Sep 03 2018 23:55:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: nbCc6-0NbZXIDnOGACHJ Pure Calls: 64252 (Mon Sep 03 2018 23:55:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ILPVAyuCkpMEqomrACHK Cozi Calls: 64110 (Mon Sep 03 2018 23:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Mon Sep 03 2018 23:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Mon Sep 03 2018 23:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Mon Sep 03 2018 23:55:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Mon Sep 03 2018 23:55:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Mon Sep 03 2018 23:55:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Mon Sep 03 2018 23:55:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: hRM2OMgkUfjO7KKfACF5 Foaly Calls: 88 (Tue Sep 04 2018 00:03:36 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Tue Sep 04 2018 00:03:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Tue Sep 04 2018 00:04:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: m9By6osVUdHSbl4nACD0 MuppArch Calls: 58 (Tue Sep 04 2018 00:07:31 GMT+0000 (Coordinated Universal Time)) +stop_character: MuppArch owner: 5552666278100992 bank: false (Tue Sep 04 2018 00:07:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VyopcqSbt0EmcIDHACDy Mupp Calls: 114725 (Tue Sep 04 2018 00:07:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: XtcFDFYPPud0H8gDACDz MuppPriest Calls: 112124 (Tue Sep 04 2018 00:07:31 GMT+0000 (Coordinated Universal Time)) +stop_character: Mupp owner: 5552666278100992 bank: false (Tue Sep 04 2018 00:07:32 GMT+0000 (Coordinated Universal Time)) +stop_character: MuppPriest owner: 5552666278100992 bank: false (Tue Sep 04 2018 00:07:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Tue Sep 04 2018 00:18:32 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Tue Sep 04 2018 00:18:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Tue Sep 04 2018 00:18:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Tue Sep 04 2018 00:18:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: C4twNMoOsBBKhBL5ACHb Troll Calls: 39 (Tue Sep 04 2018 00:18:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Tue Sep 04 2018 00:18:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6fGtHn3DN2AFybjEACHa Sinstrite Calls: 557 (Tue Sep 04 2018 00:19:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uVQomptGRpgl5TR9ACHZ Shield Calls: 450 (Tue Sep 04 2018 00:19:23 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: v7BZ5bTjWsVr41IuACHY Curse Calls: 422 (Tue Sep 04 2018 00:19:23 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Tue Sep 04 2018 00:19:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Tue Sep 04 2018 00:19:24 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Tue Sep 04 2018 00:19:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PB5xZHkrN_nY_U0DACHU Pluu Calls: 64306 (Tue Sep 04 2018 00:55:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: SHAWth1jm7rh4vJ2ACHS Pure Calls: 64171 (Tue Sep 04 2018 00:55:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: GYTe50ZanpaOabvJACHT Cozi Calls: 64586 (Tue Sep 04 2018 00:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Tue Sep 04 2018 00:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Tue Sep 04 2018 00:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Tue Sep 04 2018 00:55:19 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Tue Sep 04 2018 00:55:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Tue Sep 04 2018 00:55:24 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Tue Sep 04 2018 00:55:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Tue Sep 04 2018 01:04:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Tue Sep 04 2018 01:04:24 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Tue Sep 04 2018 01:04:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Tue Sep 04 2018 01:04:41 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mqlPjjTUcGQDu3xLACHl Troll Calls: 39 (Tue Sep 04 2018 01:04:48 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Tue Sep 04 2018 01:04:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TFjN6YliBZ11H0HBACHj Shield Calls: 469 (Tue Sep 04 2018 01:05:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: vydK6LR135Z_GXavACHk Sinstrite Calls: 584 (Tue Sep 04 2018 01:05:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 0sDq7uePgcmJCBiIACHi Curse Calls: 448 (Tue Sep 04 2018 01:05:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Tue Sep 04 2018 01:05:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Tue Sep 04 2018 01:05:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Tue Sep 04 2018 01:05:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Carolina" (Tue Sep 04 2018 01:07:33 GMT+0000 (Coordinated Universal Time)) +start_character: "SansSupport" (Tue Sep 04 2018 01:07:49 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DeG6BnwzeIBBCQ3JACHo SansSupport Calls: 5 (Tue Sep 04 2018 01:08:32 GMT+0000 (Coordinated Universal Time)) +stop_character: SansSupport owner: 6609080732876800 bank: false (Tue Sep 04 2018 01:08:32 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Tue Sep 04 2018 01:08:50 GMT+0000 (Coordinated Universal Time)) +start_character: "SansSupport" (Tue Sep 04 2018 01:08:52 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: oHepxmzYC9iN2sOJACHp BlazingSnip Calls: 81 (Tue Sep 04 2018 01:13:16 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Tue Sep 04 2018 01:13:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Ck5hINw0FNPqfJFyACHq SansSupport Calls: 105 (Tue Sep 04 2018 01:13:18 GMT+0000 (Coordinated Universal Time)) +stop_character: SansSupport owner: 6609080732876800 bank: false (Tue Sep 04 2018 01:13:18 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Tue Sep 04 2018 01:16:39 GMT+0000 (Coordinated Universal Time)) +start_character: "TexTheTank" (Tue Sep 04 2018 01:16:46 GMT+0000 (Coordinated Universal Time)) +start_character: "nobodymerch" (Tue Sep 04 2018 01:19:55 GMT+0000 (Coordinated Universal Time)) +mount_user: nobodymerch owner: 6211132113027072 (Tue Sep 04 2018 01:21:13 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: nobodymerch owner: 6211132113027072 (Tue Sep 04 2018 01:22:07 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TN6FtbOFlscReg5RACHr BlazingSnip Calls: 654 (Tue Sep 04 2018 01:22:10 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Tue Sep 04 2018 01:22:10 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Tue Sep 04 2018 01:22:18 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Uhn2uM_sPclj7EM_ACHs TexTheTank Calls: 1066 (Tue Sep 04 2018 01:23:17 GMT+0000 (Coordinated Universal Time)) +stop_character: TexTheTank owner: 6609080732876800 bank: false (Tue Sep 04 2018 01:23:18 GMT+0000 (Coordinated Universal Time)) +start_character: "TexTheTank" (Tue Sep 04 2018 01:23:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uH_Hv9TNXmJVgQ16ACHu nobodymerch Calls: 243 (Tue Sep 04 2018 01:26:05 GMT+0000 (Coordinated Universal Time)) +stop_character: nobodymerch owner: 6211132113027072 bank: false (Tue Sep 04 2018 01:26:05 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Tue Sep 04 2018 01:26:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Sentry" (Tue Sep 04 2018 01:29:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: _lELe9zy1zaA4yraACHz Sentry Calls: 167 (Tue Sep 04 2018 01:31:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Sentry owner: 5792989285711872 bank: false (Tue Sep 04 2018 01:31:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Tue Sep 04 2018 01:50:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Sentry" (Tue Sep 04 2018 01:50:16 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Tue Sep 04 2018 01:50:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Tue Sep 04 2018 01:50:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Tue Sep 04 2018 01:50:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: siHSJGYFZopQcuLnACH4 Troll Calls: 39 (Tue Sep 04 2018 01:50:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Tue Sep 04 2018 01:50:39 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: d1KeEhCSksvPbhg9ACH3 Sinstrite Calls: 561 (Tue Sep 04 2018 01:51:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: x0HK8CGNhdi5SL4yACH2 Shield Calls: 434 (Tue Sep 04 2018 01:51:03 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ptiR5LbQh7FoggRqACH1 Curse Calls: 407 (Tue Sep 04 2018 01:51:03 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Tue Sep 04 2018 01:51:04 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Tue Sep 04 2018 01:51:04 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Tue Sep 04 2018 01:51:04 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: y0i7cikqZIOgQHwqACH0 Sentry Calls: 89 (Tue Sep 04 2018 01:52:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Sentry owner: 5792989285711872 bank: false (Tue Sep 04 2018 01:52:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: pw8UBv31Sxv8vBZkACHh Pluu Calls: 64334 (Tue Sep 04 2018 01:55:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: R1ybFWhG06aUEYymACHf Pure Calls: 64230 (Tue Sep 04 2018 01:55:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: M3kvWeyRvrHGcAMWACHg Cozi Calls: 64397 (Tue Sep 04 2018 01:55:19 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Tue Sep 04 2018 01:55:20 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Tue Sep 04 2018 01:55:20 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Tue Sep 04 2018 01:55:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Tue Sep 04 2018 01:55:22 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Tue Sep 04 2018 01:55:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Tue Sep 04 2018 01:55:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 4LEWs05rwMbrb2zcACG0 Trexnamedtod Calls: 31 (Tue Sep 04 2018 02:06:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: QrxYQF0tj27DNo0ZACG2 Trexnamedtut Calls: 187870 (Tue Sep 04 2018 02:06:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zbwNWtywMrTTITTRACG3 Trexnamedtom Calls: 187470 (Tue Sep 04 2018 02:06:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Tak61swOyaFOcgVmACG1 Trexnamedted Calls: 188882 (Tue Sep 04 2018 02:06:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtut owner: 5209159389675520 bank: false (Tue Sep 04 2018 02:06:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedted owner: 5209159389675520 bank: false (Tue Sep 04 2018 02:06:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtod owner: 5209159389675520 bank: false (Tue Sep 04 2018 02:06:58 GMT+0000 (Coordinated Universal Time)) +stop_character: Trexnamedtom owner: 5209159389675520 bank: false (Tue Sep 04 2018 02:06:58 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: O7ePdqag3XX7G97TACGq 0x00 Calls: 12172 (Tue Sep 04 2018 02:09:36 GMT+0000 (Coordinated Universal Time)) +stop_character: 0x00 owner: 5457622628040704 bank: false (Tue Sep 04 2018 02:09:36 GMT+0000 (Coordinated Universal Time)) +start_character: "0x00" (Tue Sep 04 2018 02:10:50 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Tue Sep 04 2018 02:36:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Tue Sep 04 2018 02:36:04 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Tue Sep 04 2018 02:36:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Tue Sep 04 2018 02:36:21 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: AdbVhJHffBSgZaicACIC Troll Calls: 38 (Tue Sep 04 2018 02:36:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Tue Sep 04 2018 02:36:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 57cY5BSJKM_wOo4jACIA Shield Calls: 468 (Tue Sep 04 2018 02:36:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: zzjBFn9rptGqnIZHACIB Sinstrite Calls: 596 (Tue Sep 04 2018 02:36:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 4w9XA0-Hq8xtRB2lACH_ Curse Calls: 442 (Tue Sep 04 2018 02:36:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Tue Sep 04 2018 02:36:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Tue Sep 04 2018 02:36:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Tue Sep 04 2018 02:36:55 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Tue Sep 04 2018 02:37:59 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Tue Sep 04 2018 02:38:11 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Tue Sep 04 2018 02:44:38 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Tue Sep 04 2018 02:44:52 GMT+0000 (Coordinated Universal Time)) +start_character: "nobodymerch" (Tue Sep 04 2018 02:48:15 GMT+0000 (Coordinated Universal Time)) +mount_user: nobodymerch owner: 6211132113027072 (Tue Sep 04 2018 02:48:33 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: nobodymerch owner: 6211132113027072 (Tue Sep 04 2018 02:49:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: UfVGSSVG09DMVheyACID nobodymerch Calls: 49 (Tue Sep 04 2018 02:49:16 GMT+0000 (Coordinated Universal Time)) +stop_character: nobodymerch owner: 6211132113027072 bank: false (Tue Sep 04 2018 02:49:16 GMT+0000 (Coordinated Universal Time)) +start_character: "Mormegil" (Tue Sep 04 2018 02:49:38 GMT+0000 (Coordinated Universal Time)) +mount_user: Mormegil owner: 5743070469423104 (Tue Sep 04 2018 02:49:50 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Mormegil owner: 5743070469423104 (Tue Sep 04 2018 02:50:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TO26FAcunDKqy8f3ACIF Mormegil Calls: 84 (Tue Sep 04 2018 02:54:49 GMT+0000 (Coordinated Universal Time)) +stop_character: Mormegil owner: 5743070469423104 bank: false (Tue Sep 04 2018 02:54:49 GMT+0000 (Coordinated Universal Time)) +start_character: "Sentry" (Tue Sep 04 2018 02:55:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NTTEhnjp-6LDJh1iACIH Sentry Calls: 70 (Tue Sep 04 2018 02:56:20 GMT+0000 (Coordinated Universal Time)) +stop_character: Sentry owner: 5792989285711872 bank: false (Tue Sep 04 2018 02:56:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Sentry" (Tue Sep 04 2018 02:56:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ISjbfKJj8rAYGxuRACHx MOBSans Calls: 84 (Tue Sep 04 2018 03:09:01 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Tue Sep 04 2018 03:09:01 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Tue Sep 04 2018 03:09:12 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: nDp5K6v1TNbNCJ5fACIJ MOBSans Calls: 136 (Tue Sep 04 2018 03:11:22 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Tue Sep 04 2018 03:11:22 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Tue Sep 04 2018 03:11:31 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DWnYPNI6bd-cF01KACIK MOBSans Calls: 115 (Tue Sep 04 2018 03:13:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 79bYeGEtAofFlezTACHw TexTheTank Calls: 13245 (Tue Sep 04 2018 03:13:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Z6pu25PFunaX6BqiACHv BlazingSnip Calls: 24163 (Tue Sep 04 2018 03:13:14 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ECyJsUHvd_nTGGC3ACHn Carolina Calls: 22851 (Tue Sep 04 2018 03:13:14 GMT+0000 (Coordinated Universal Time)) +stop_character: Carolina owner: 6609080732876800 bank: false (Tue Sep 04 2018 03:13:14 GMT+0000 (Coordinated Universal Time)) +stop_character: TexTheTank owner: 6609080732876800 bank: false (Tue Sep 04 2018 03:13:14 GMT+0000 (Coordinated Universal Time)) +stop_character: BlazingSnip owner: 6609080732876800 bank: false (Tue Sep 04 2018 03:13:14 GMT+0000 (Coordinated Universal Time)) +stop_character: MOBSans owner: 6609080732876800 bank: false (Tue Sep 04 2018 03:13:14 GMT+0000 (Coordinated Universal Time)) +start_character: "Carolina" (Tue Sep 04 2018 03:13:26 GMT+0000 (Coordinated Universal Time)) +start_character: "BlazingSnip" (Tue Sep 04 2018 03:13:53 GMT+0000 (Coordinated Universal Time)) +start_character: "SansSupport" (Tue Sep 04 2018 03:14:40 GMT+0000 (Coordinated Universal Time)) +start_character: "MOBSans" (Tue Sep 04 2018 03:15:04 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Tue Sep 04 2018 03:16:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: nbVqiIE7KbTYo5J2ACGH Scythe Calls: 1124586 (Tue Sep 04 2018 03:16:25 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Tue Sep 04 2018 03:16:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 4DMCexek5dtMsamTACGI Silent Calls: 391071 (Tue Sep 04 2018 03:16:25 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Tue Sep 04 2018 03:16:25 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Tue Sep 04 2018 03:17:45 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Tue Sep 04 2018 03:17:52 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Tue Sep 04 2018 03:18:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: guY_-alxQao5AmezACIP Scythe Calls: 616 (Tue Sep 04 2018 03:18:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Tue Sep 04 2018 03:18:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6H0Eea2vvIqMsGtoACIQ Silent Calls: 97 (Tue Sep 04 2018 03:18:01 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Tue Sep 04 2018 03:18:01 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Tue Sep 04 2018 03:19:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Tue Sep 04 2018 03:19:18 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Tue Sep 04 2018 03:21:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Tue Sep 04 2018 03:21:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Tue Sep 04 2018 03:21:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Tue Sep 04 2018 03:22:11 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ciJnFn4yterpLZ2hACIW Troll Calls: 39 (Tue Sep 04 2018 03:22:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Tue Sep 04 2018 03:22:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: OdWxMiZtS8zLzt6iACIU Sinstrite Calls: 397 (Tue Sep 04 2018 03:22:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: oLdCzI4Nvl95RG_zACIV Shield Calls: 286 (Tue Sep 04 2018 03:22:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: gsuVFPRZamAUVqRiACIT Curse Calls: 285 (Tue Sep 04 2018 03:22:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Tue Sep 04 2018 03:22:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Tue Sep 04 2018 03:22:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Tue Sep 04 2018 03:22:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtod" (Tue Sep 04 2018 03:25:42 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedted" (Tue Sep 04 2018 03:25:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtut" (Tue Sep 04 2018 03:25:48 GMT+0000 (Coordinated Universal Time)) +start_character: "Trexnamedtom" (Tue Sep 04 2018 03:25:49 GMT+0000 (Coordinated Universal Time)) +mount_user: Ploob owner: 4572509340958720 (Tue Sep 04 2018 03:49:55 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Ploob owner: 4572509340958720 (Tue Sep 04 2018 03:50:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: U6b0vlEOzD8BZPRHACII Sentry Calls: 721 (Tue Sep 04 2018 03:54:33 GMT+0000 (Coordinated Universal Time)) +stop_character: Sentry owner: 5792989285711872 bank: false (Tue Sep 04 2018 03:54:33 GMT+0000 (Coordinated Universal Time)) +start_character: "Sentry" (Tue Sep 04 2018 03:54:33 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: M3O5Sd3h6nZfjWWKACHW Foaly Calls: 6 (Tue Sep 04 2018 03:57:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Tue Sep 04 2018 03:57:37 GMT+0000 (Coordinated Universal Time)) +start_character: "nobodyhere" (Tue Sep 04 2018 03:58:02 GMT+0000 (Coordinated Universal Time)) +mount_user: nobodyhere owner: 5743070469423104 (Tue Sep 04 2018 03:58:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VnK_X1E1J7Xus1cqACIf nobodyhere Calls: 10 (Tue Sep 04 2018 03:58:30 GMT+0000 (Coordinated Universal Time)) +stop_character: nobodyhere owner: 5743070469423104 bank: true (Tue Sep 04 2018 03:58:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Turin" (Tue Sep 04 2018 03:58:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Tue Sep 04 2018 03:58:57 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: USRl0HpFXQt8iTY7ACIg Turin Calls: 9 (Tue Sep 04 2018 03:59:11 GMT+0000 (Coordinated Universal Time)) +stop_character: Turin owner: 5743070469423104 bank: false (Tue Sep 04 2018 03:59:12 GMT+0000 (Coordinated Universal Time)) +start_character: "Galadriel" (Tue Sep 04 2018 03:59:16 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: K2xFaFvVoBkTHv8TACIj Galadriel Calls: 6 (Tue Sep 04 2018 03:59:26 GMT+0000 (Coordinated Universal Time)) +stop_character: Galadriel owner: 5743070469423104 bank: false (Tue Sep 04 2018 03:59:27 GMT+0000 (Coordinated Universal Time)) +start_character: "Mormegil" (Tue Sep 04 2018 03:59:30 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Tue Sep 04 2018 04:05:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: k-9YYtA9OvYWs3d6ACIR Scythe Calls: 102125 (Tue Sep 04 2018 04:05:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Tue Sep 04 2018 04:05:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xCpxZPkr-ugdwq2SACIS Silent Calls: 35371 (Tue Sep 04 2018 04:05:40 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Tue Sep 04 2018 04:05:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Tue Sep 04 2018 04:07:04 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Tue Sep 04 2018 04:07:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: flpfDT-GkKlWPMVJACIl Scythe Calls: 308 (Tue Sep 04 2018 04:07:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Tue Sep 04 2018 04:07:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Tue Sep 04 2018 04:07:13 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NDizFU6Ld1vEOK6yACIm Silent Calls: 3 (Tue Sep 04 2018 04:07:13 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Tue Sep 04 2018 04:07:13 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Tue Sep 04 2018 04:08:02 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Tue Sep 04 2018 04:08:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Tue Sep 04 2018 04:08:07 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Tue Sep 04 2018 04:08:21 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Tue Sep 04 2018 04:08:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: X-ugxFlMea7qX6H2ACIq Troll Calls: 39 (Tue Sep 04 2018 04:08:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Tue Sep 04 2018 04:08:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Tue Sep 04 2018 04:08:32 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6VhEL_viOOQ24M7LACIo Sinstrite Calls: 609 (Tue Sep 04 2018 04:08:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: rr4LQKF04WHT3einACIn Curse Calls: 438 (Tue Sep 04 2018 04:08:54 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: PwmbRQnOe8NPXZjsACIp Shield Calls: 452 (Tue Sep 04 2018 04:08:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Tue Sep 04 2018 04:08:55 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Tue Sep 04 2018 04:08:55 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Tue Sep 04 2018 04:08:55 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: brHszWbtlEzdt-sTACId Sentry Calls: 47 (Tue Sep 04 2018 04:18:28 GMT+0000 (Coordinated Universal Time)) +stop_character: Sentry owner: 5792989285711872 bank: false (Tue Sep 04 2018 04:18:29 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 97GFBu9rZ305Ilm2ACIk Mormegil Calls: 34 (Tue Sep 04 2018 04:19:10 GMT+0000 (Coordinated Universal Time)) +stop_character: Mormegil owner: 5743070469423104 bank: false (Tue Sep 04 2018 04:19:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: N6qgBdta7A9M50xuACH6 Pluu Calls: 188705 (Tue Sep 04 2018 04:50:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: MGGObJVXE2ZlEEL_ACH7 Pure Calls: 188960 (Tue Sep 04 2018 04:50:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DMKhaS7Jkkx1QhzwACH8 Cozi Calls: 188996 (Tue Sep 04 2018 04:50:51 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Tue Sep 04 2018 04:50:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Tue Sep 04 2018 04:50:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Tue Sep 04 2018 04:50:52 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Tue Sep 04 2018 04:50:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Tue Sep 04 2018 04:50:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Tue Sep 04 2018 04:50:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Tue Sep 04 2018 04:53:52 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Tue Sep 04 2018 04:53:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Tue Sep 04 2018 04:53:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Tue Sep 04 2018 04:54:11 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 24UtZbxz4aUaED6nACIz Troll Calls: 38 (Tue Sep 04 2018 04:54:18 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Tue Sep 04 2018 04:54:19 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: jIIOs64Qjw4hi6eJACIy Sinstrite Calls: 625 (Tue Sep 04 2018 04:54:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 54HCaiEoxnk_yA9UACIw Curse Calls: 462 (Tue Sep 04 2018 04:54:46 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: skDRsYyMjGHS7O4dACIx Shield Calls: 504 (Tue Sep 04 2018 04:54:46 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Tue Sep 04 2018 04:54:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Tue Sep 04 2018 04:54:47 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Tue Sep 04 2018 04:54:47 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Tue Sep 04 2018 05:39:40 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Tue Sep 04 2018 05:39:44 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Tue Sep 04 2018 05:39:46 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Tue Sep 04 2018 05:40:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: wQIW5jzJj5y3zV67ACI5 Troll Calls: 37 (Tue Sep 04 2018 05:40:09 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Tue Sep 04 2018 05:40:09 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: TyNgJhFXU0dWLGe-ACI4 Shield Calls: 464 (Tue Sep 04 2018 05:40:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ycWVxNxf5tXAYwnFACI3 Sinstrite Calls: 628 (Tue Sep 04 2018 05:40:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 6WKbyAXvsTXvtQhqACI2 Curse Calls: 443 (Tue Sep 04 2018 05:40:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Tue Sep 04 2018 05:40:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Tue Sep 04 2018 05:40:34 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Tue Sep 04 2018 05:40:34 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: eQgMMBES-a1EmkaAACIt Pluu Calls: 64181 (Tue Sep 04 2018 05:50:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: kC7g7LV8TyNMwD_pACIv Pure Calls: 64372 (Tue Sep 04 2018 05:50:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 7cktforRoXlw0r01ACIu Cozi Calls: 64477 (Tue Sep 04 2018 05:50:51 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Tue Sep 04 2018 05:50:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Tue Sep 04 2018 05:50:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Tue Sep 04 2018 05:50:53 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Tue Sep 04 2018 05:50:55 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Tue Sep 04 2018 05:50:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Tue Sep 04 2018 05:50:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Vlox" (Tue Sep 04 2018 06:19:44 GMT+0000 (Coordinated Universal Time)) +mount_user: Vlox owner: 5172873845014528 (Tue Sep 04 2018 06:21:24 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: DAOcZdh7jZ5RZJ8OACI_ Vlox Calls: 71 (Tue Sep 04 2018 06:22:07 GMT+0000 (Coordinated Universal Time)) +stop_character: Vlox owner: 5172873845014528 bank: true (Tue Sep 04 2018 06:22:08 GMT+0000 (Coordinated Universal Time)) +start_character: "Vlox" (Tue Sep 04 2018 06:22:10 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: NJfAJgapnOI7NwseACJA Vlox Calls: 103 (Tue Sep 04 2018 06:23:52 GMT+0000 (Coordinated Universal Time)) +stop_character: Vlox owner: 5172873845014528 bank: false (Tue Sep 04 2018 06:23:52 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Tue Sep 04 2018 06:25:30 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Tue Sep 04 2018 06:25:36 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Tue Sep 04 2018 06:25:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Tue Sep 04 2018 06:25:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: LtlTse5NcpQU2PBLACJE Troll Calls: 38 (Tue Sep 04 2018 06:26:00 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Tue Sep 04 2018 06:26:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: yO5z4yzCjP9ceeUxACJD Shield Calls: 446 (Tue Sep 04 2018 06:26:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: ch3UyD-waYtna0kbACJB Curse Calls: 439 (Tue Sep 04 2018 06:26:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 2w_-JR5gWlIsTQP4ACJC Sinstrite Calls: 614 (Tue Sep 04 2018 06:26:25 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Tue Sep 04 2018 06:26:25 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Tue Sep 04 2018 06:26:25 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Tue Sep 04 2018 06:26:26 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: lbxe17m_U-CkZ3T-ACI8 Pluu Calls: 64926 (Tue Sep 04 2018 06:50:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: YMQY9jxJGEehx0FiACI9 Pure Calls: 64252 (Tue Sep 04 2018 06:50:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VDNBPsFoo7zv4SdsACI- Cozi Calls: 64905 (Tue Sep 04 2018 06:50:51 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Tue Sep 04 2018 06:50:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Tue Sep 04 2018 06:50:53 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Tue Sep 04 2018 06:50:53 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Tue Sep 04 2018 06:50:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Tue Sep 04 2018 06:50:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Tue Sep 04 2018 06:50:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Tue Sep 04 2018 07:12:28 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Tue Sep 04 2018 07:12:34 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Tue Sep 04 2018 07:12:35 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Tue Sep 04 2018 07:12:53 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: uCEhTd07zDs6RsGZACJM Troll Calls: 39 (Tue Sep 04 2018 07:13:00 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Tue Sep 04 2018 07:13:01 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: aKcktM1o4GXnD6KKACJK Sinstrite Calls: 645 (Tue Sep 04 2018 07:13:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: FHDheFweSnXcQgq0ACJL Shield Calls: 482 (Tue Sep 04 2018 07:13:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fmPvkAhZLgGs4PB6ACJJ Curse Calls: 468 (Tue Sep 04 2018 07:13:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Tue Sep 04 2018 07:13:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Tue Sep 04 2018 07:13:27 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Tue Sep 04 2018 07:13:27 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Tue Sep 04 2018 07:25:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: MYuvfpcDcMxxBOAUACIr Scythe Calls: 431863 (Tue Sep 04 2018 07:25:08 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Tue Sep 04 2018 07:25:08 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: JbAi3A7uQfiJXMt_ACIs Silent Calls: 149963 (Tue Sep 04 2018 07:25:09 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC _observer (Tue Sep 04 2018 07:25:09 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Tue Sep 04 2018 07:25:09 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Tue Sep 04 2018 07:26:20 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Tue Sep 04 2018 07:26:27 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dTYaJj9uNf0WC6yxACIi Foaly Calls: 6 (Tue Sep 04 2018 07:29:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Foaly owner: 4909785279365120 bank: false (Tue Sep 04 2018 07:29:37 GMT+0000 (Coordinated Universal Time)) +start_character: "Foaly" (Tue Sep 04 2018 07:30:59 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 8xYXb3t_A6RFxDmLACJP Silent Calls: 4767 (Tue Sep 04 2018 07:33:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: VXJIqAWYsCz28jrtACJO Scythe Calls: 14029 (Tue Sep 04 2018 07:33:05 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Tue Sep 04 2018 07:33:05 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Tue Sep 04 2018 07:33:05 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Tue Sep 04 2018 07:34:15 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Tue Sep 04 2018 07:34:22 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Tue Sep 04 2018 07:34:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: xGKrJT07ID0qot0sACJS Scythe Calls: 559 (Tue Sep 04 2018 07:34:28 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: fmZELA0Np9aJDKHnACJT Silent Calls: 73 (Tue Sep 04 2018 07:34:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Tue Sep 04 2018 07:34:29 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Tue Sep 04 2018 07:34:29 GMT+0000 (Coordinated Universal Time)) +mount_user: Business owner: 5752754626625536 (Tue Sep 04 2018 07:34:41 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Business owner: 5752754626625536 (Tue Sep 04 2018 07:34:53 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Tue Sep 04 2018 07:35:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Tue Sep 04 2018 07:36:01 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Tue Sep 04 2018 07:36:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: h0q9439SwX1QtTLvACJU Scythe Calls: 367 (Tue Sep 04 2018 07:36:05 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Upaalr_ZzQT0tJYoACJV Silent Calls: 46 (Tue Sep 04 2018 07:36:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Tue Sep 04 2018 07:36:06 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Tue Sep 04 2018 07:36:06 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Tue Sep 04 2018 07:37:31 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Tue Sep 04 2018 07:37:37 GMT+0000 (Coordinated Universal Time)) +>>> LIMITDC Scythe (Tue Sep 04 2018 07:37:37 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: dyHaSeWZY1UuEJ0hACJW Scythe Calls: 229 (Tue Sep 04 2018 07:37:37 GMT+0000 (Coordinated Universal Time)) +stop_character: Scythe owner: 6243983994912768 bank: false (Tue Sep 04 2018 07:37:38 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 8h-XMEDdkr6W8chUACJX Silent Calls: 6 (Tue Sep 04 2018 07:37:38 GMT+0000 (Coordinated Universal Time)) +stop_character: Silent owner: 6243983994912768 bank: false (Tue Sep 04 2018 07:37:38 GMT+0000 (Coordinated Universal Time)) +start_character: "Scythe" (Tue Sep 04 2018 07:38:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Silent" (Tue Sep 04 2018 07:39:04 GMT+0000 (Coordinated Universal Time)) +mount_user: Business owner: 5752754626625536 (Tue Sep 04 2018 07:40:21 GMT+0000 (Coordinated Universal Time)) +unmount_user[sync]: Business owner: 5752754626625536 (Tue Sep 04 2018 07:40:25 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: KMbxPkw4RmXVpWB7ACJG Pluu Calls: 64111 (Tue Sep 04 2018 07:50:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: Y5HLFzhueY9eTRTqACJI Pure Calls: 64368 (Tue Sep 04 2018 07:50:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: HwPcb3JJKqM0YpdIACJH Cozi Calls: 64511 (Tue Sep 04 2018 07:50:51 GMT+0000 (Coordinated Universal Time)) +stop_character: Pure owner: 4572509340958720 bank: false (Tue Sep 04 2018 07:50:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Cozi owner: 4572509340958720 bank: false (Tue Sep 04 2018 07:50:54 GMT+0000 (Coordinated Universal Time)) +stop_character: Pluu owner: 4572509340958720 bank: false (Tue Sep 04 2018 07:50:54 GMT+0000 (Coordinated Universal Time)) +start_character: "Pure" (Tue Sep 04 2018 07:50:56 GMT+0000 (Coordinated Universal Time)) +start_character: "Pluu" (Tue Sep 04 2018 07:50:57 GMT+0000 (Coordinated Universal Time)) +start_character: "Cozi" (Tue Sep 04 2018 07:50:58 GMT+0000 (Coordinated Universal Time)) +start_character: "Curse" (Tue Sep 04 2018 07:58:23 GMT+0000 (Coordinated Universal Time)) +start_character: "Shield" (Tue Sep 04 2018 07:58:27 GMT+0000 (Coordinated Universal Time)) +start_character: "Sinstrite" (Tue Sep 04 2018 07:58:29 GMT+0000 (Coordinated Universal Time)) +start_character: "Troll" (Tue Sep 04 2018 07:58:43 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: 8PDh3cxaWv9ahM9zACJg Troll Calls: 39 (Tue Sep 04 2018 07:58:50 GMT+0000 (Coordinated Universal Time)) +stop_character: Troll owner: 5145329831772160 bank: false (Tue Sep 04 2018 07:58:51 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: gn0L7GLWqmPPAcYLACJf Sinstrite Calls: 569 (Tue Sep 04 2018 07:59:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: mmU2jvxJN_pfaQNjACJd Curse Calls: 430 (Tue Sep 04 2018 07:59:15 GMT+0000 (Coordinated Universal Time)) +Disconnected Player: d0986ktNH9oixlFgACJe Shield Calls: 466 (Tue Sep 04 2018 07:59:15 GMT+0000 (Coordinated Universal Time)) +stop_character: Shield owner: 5145329831772160 bank: false (Tue Sep 04 2018 07:59:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Sinstrite owner: 5145329831772160 bank: false (Tue Sep 04 2018 07:59:16 GMT+0000 (Coordinated Universal Time)) +stop_character: Curse owner: 5145329831772160 bank: false (Tue Sep 04 2018 07:59:16 GMT+0000 (Coordinated Universal Time)) +start_character: "SweetPea" (Tue Sep 04 2018 08:19:21 GMT+0000 (Coordinated Universal Time)) diff --git a/design/docs/test.png b/design/docs/test.png new file mode 100644 index 0000000..626a656 Binary files /dev/null and b/design/docs/test.png differ diff --git a/design/drops.py b/design/drops.py new file mode 100644 index 0000000..15a7ecd --- /dev/null +++ b/design/drops.py @@ -0,0 +1,1286 @@ +import copy +from items import items + +drops={ + "gold":{ + "base":0.64,#originally 0.75 + "random":0.8,#originally 1 + "x10":(1.0/32),#originally 1/12 - later 1/15 - later 1/20 - now 1/32 [03/02/17] + "x50":(1.0/480),#originally 1/200 - later 1/300 - later 1/400 - now 1/480 [03/02/17] + }, + "maps":{ + "global_static":[ + + ], + "global":[ + #[0.00001,"ornament"], + #[0.00003,"mistletoe"], + #[0.00001,"candycane"], + #[0.000001,"open","xN"], + #[0.00006,"ornament"], + #[0.00018,"mistletoe"], + #[0.00005,"candycane"], + #[0.00001,"open","xN"], + [0.00005,"candy0"], #originally 4X [11/10/19] + [0.00125,"candy1"], #originally 4X [11/10/19] + #[0.000015,"goldenegg"], #originally 0.000005 + #[0.000001,"5bucks"], + #[0.0002,"gift0"], + #[0.004,"gift1"], + #[0.0006,"ornament"], + #[0.0018,"mistletoe"], + #[0.0005,"candycane"], + #[0.0001,"open","xN"], + #[0.0004,"redenvelope"], + #[0.00005,"goldenegg"], + #[0.009,"open","eastereggs"], #originally 0.009 + #[0.0001,"redenvelopev2"], + #[0.0001,"redenvelopev3"], + #[0.00005,"greenenvelope"], + #[0.0001,"redenvelopev4"], + #[0.001,"candypop"], + ], + "main":[ + [0.0007,"ringsj"], + [0.0006,"hpamulet"], + [0.0006,"hpbelt"], + [0.00007,"gem0"], + [0.0001,"wcap"], + [0.0001,"wshoes"], + #[0.00005,"goldenegg"], + #[0.009,"open","eastereggs"], + #[0.0012,"ornament"], + #[0.001,"mistletoe"], + #[0.001,"candycane"], + ], + "winter_cave":[ + [0.0005,"open","statring"], + [0.000001,"angelwings"], + #[0.002,"ornament"], + #[0.001,"mistletoe"], + #[0.001,"candycane"], + ], + "winterland":[ + [0.0001,"wattire"], + [0.0005,"open","statring"], #previously 0.0003 + #[0.00005,"goldenegg"], + #[0.009,"open","eastereggs"], + #[0.002,"ornament"], + #[0.001,"mistletoe"], + #[0.001,"candycane"], + ], + "halloween":[ + [0.0001,"wgloves"], + [0.0001,"wbreeches"], + [0.0007,"open","statamulet"], + #[0.00005,"goldenegg"], + #[0.009,"open","eastereggs"], + #[0.0004,"intamulet"], + #[0.0004,"stramulet"], + #[0.0001,"candy0"], #originally 0.0002 + #[0.002,"candy1"], #originally 0.004 + #[0.001,"ornament"], + #[0.001,"mistletoe"], + #[0.001,"candycane"], + #[0.0001,"candy0v2"], #originally 0.0002 + #[0.002,"candy1v2"], #originally 0.004 + ], + "spookytown":[ + [0.0001,"wbreeches"], + #[0.0002,"candy0v2"], #originally 0.0002 + #[0.003,"candy1v2"], + [0.0007,"open","statbelt"], + ], + "cave":[ + [0.0001,"wattire"], + [0.0001,"wgloves"], + [0.0004,"ringsj"], + [0.0006,"hpamulet"], + [0.0006,"hpbelt"], + [0.00008,"gem0"], + [1.0/600000,"cryptkey"] + #[0.001,"ornament"], + #[0.001,"mistletoe"], + #[0.001,"candycane"], + ], + "maintest":[ + [0.001,"ringsj"], + [0.0007,"hpamulet"], + [0.0007,"hpbelt"], + ], + "arena":[ + [0.00008,"gem0"], + ], + "mansion":[ + [0.0001,"wbreeches"], + [12.0/100000,"lostearring"], + ], + }, + "monsters":{ + "hen":[ + [1.0,"whiteegg"], + [0.1,"whiteegg"], + ], + "rooster":[ + [1.0/10000,"brownegg"], + ], + "goo":[ + #[0.1/10,"shells",50], + [0.1/800000,"shells",50], + [1.0/5000,"slimestaff"], + [1.0/1000,"gslime"], #1 .0/1000 + #[100,"emotionjar",1,"hearts_single"], + #[1.0,"emotionjar",1,"drop_egg"], + #[1.0/10,"cxjar",1,"wings102"], + #[1.0,"cxjar",1,"hat100"], + ], #,[0.5,"open","lightmage"] + "crab":[ + [2.0/10000000,"suckerpunch"], + [5.0/1000,"seashell"], + [1.0/1000,"crabclaw"], + [1.0/20000,"cclaw"], + ], + "bee":[ + [1.0/100,"beewings"], + [1.0/6000,"stinger"], + ], + "porcupine":[ + [1.0/1000,"pleather"], + [1.0/5000,"hbow"], + ], + "stoneworm":[ + [1.0/12000,"swifty"], + [1.0/300,"dstones"], + ], + "minimush":[ + [1.0/60,"spores"], + [1.0/5000,"mushroomstaff"], + [1.0/9000000,"cxjar",1,"hat407"], + [1.0/60000000,"cxjar",1,"hat406"], + ], + "frog":[ + [16.0/100,"seashell"], + [1/100000.0,"5bucks"], + [1/400.0,"lotusf"] + ], + "squigtoad":[ + [5.0/100,"seashell"], + [1.0/400,"frogt"], + ], + "osnake":[ + [1.0/10000,"snakeoil"], + [1.0/2000,"snakefang"], + ], + "snake":[ + [1.0/100000,"snakeoil"], + ], + "rat":[ + [1.0/500,"rattail"], + ], + "armadillo":[ + [1.0/20000,"sshield"], + [8.0/10000,"ascale"], + ], + "squig":[ + [12.0/1000,"seashell"], + [1.0/20000,"ink"], + ], + "cgoo":[ + [8.0/1000,"gem1"], + [0.00008,"shadowstone"], + [1.0/20000,"ijx"], + ], + "poisio":[ + [3.2/1000,"poison"], + [1.0/3000,"smush"] + ], + "snowman":[ + [0.01,"iceskates"], + [0.05,"xmace"], + [0.3,"candycane"], + [0.2,"candycane"], + [0.1,"candycane"], + [0.1,"candycane"], + [0.1,"candycane"], + [0.1,"mistletoe"], + [0.00075,"offering"], + [1,"carrot"], + [1,"snowball"], + [1,"snowball"], + [0.0025,"wbookhs"], + ], + "tiger":[#every hit + [0.1,"tigerhelmet"], + [0.001,"tigercape"], + [0.001,"tigerstone"], + [0.01,"tigershield"], + ], + "arcticbee":[ + [0.00005,"essenceoffrost"], + [1.0/1000,"bfur"], + ], + "mole":[ + [0.012,"gemfragment"], + [2.0/100000,"molesteeth"] + ], + "oneeye":[ + [1.0/500000,"amuletofm"], + [1.0/3000000,"mpxbelt"] + ], + "crabx":[ + [4.0/10000000,"suckerpunch"], + [2.0/100,"seashell"], + [1.0/500,"cclaw"], + [1.0/10000,"cshell"], + ], + "crabxx":[ + [4.0/10000,"suckerpunch"], + [100,"seashell"], + [100,"seashell"], + [500,"cclaw"], + [10000,"cshell"], + [1000,"funtoken"], + [1000,"funtoken"], + [1000,"funtoken"], + [10,"funtoken"], + [10,"funtoken"], + ], + "rgoo":[ + [20,"funtoken"], + [0.025,"open","lglitch"] + ], + "bgoo":[ + [0.25,"funtoken"], + ], + "croc":[ + [9.0/10000,"cscale"], + ], + "prat":[ + [10.0*8/10000000,"platinumnugget"], + [5.0/1000,"rfangs"], + ], + "boar":[[0.01,"leather"],[1.0/200000,"btusk"]], + "tortoise":[[2.0/10000,"shield"],[1.0/1000,"seashell"]], + "wolf":[[1.0/40,"leather"]], + "wolfie":[[1.0/50,"leather"]], + "stompy":[[1,"leather"],[1,"leather"],[1,"leather"],[1,"leather"],[1.0/500,"snring"]], #[0.3,"mistletoe"],[0.4,"candycane"],[1,"ornament"],[1,"ornament"], + "dknight2":[ + [0.01,"shield"], #0.025 before [03/12/16] + [0.0008,"fireblade"], #0.0016 before + ], + "mvampire":[[0.10,"intearring"],[0.10,"strearring"],[0.10,"dexearring"],[0.05,"firestaff"],[0.03,"mcape"],[0.01,"forscroll"],[1.0/400000,"cxjar",1,"coolblueg"],[1.0/80000,"sanguine"]], + "fvampire":[[0.30,"open","statamulet"],[0.04,"firestaff"],[0.01,"mcape"],[0.01,"armorbox"],[0.01,"forscroll"],[1.0/200000,"cxjar",1,"catbatg"],[1.0/40,"offeringp"],[1.0/50000,"sanguine"]], + #"phoenix":[[0.08,"intearring"],[0.08,"strearring"],[0.08,"dexearring"],[0.02,"firestaff"],[0.02,"fireblade"]], + "phoenix":[[0.7,"vitscroll"],[0.12,"intearring"],[0.12,"strearring"],[0.12,"dexearring"],[0.12,"vitearring"],[0.04,"firestaff"],[0.04,"fireblade"],[1.0/120000,"fcape"],[1.0/600,"offeringp"],[1.0/64000000,"cxjar",1,"hairdo606"]], + "mechagnome":[[0.2,"electronics"],[0.2,"electronics"],[0.2,"electronics"],[0.00001,"networkcard"],[1.0/10000000,"mpxamulet"]], + "bat":[[4.0/1000,"wbook0"],[5.0/1000,"bwing"],[1.0/100000000,"cxjar",1,"wings102"]], + "scorpion":[ + [6.0/10000,"quiver"], + [1.0/4000,"sstinger"], + ], + "pinkgoblin":[ + [1.0/24000,"bkey"], + ], + "spider":[[0.001,"spidersilk"],[1.0/500000,"offeringp"]], + "tinyp":[[1.0/1,"offeringp"]], + "gscorpion":[[0.002,"quiver"]], + "xscorpion":[[0.0024,"quiver"],[0.00024,"vitscroll"],[2.0/1000000,"glitch"],[8.0/100000,"svenom"]], + "bscorpion":[[1.0/20,"offeringp"]], + #"ghost":[[0.001,"candy0"]], + "ghost":[[0.0002,"pmace"]], #0.001 was tooooo high + "booboo":[[0.005,"essenceofether"],[5.0/100000,"ectoplasm"]], + "mummy":[ + [1.0/4000,"open","weaponofthedead"], + [1.0/500,"bandages"], + ], + "iceroamer":[ + [0.0001,"essenceoffrost"], + [0.00001,"frozenkey"], + ], + "icegolem":[ + [5,"frozenkey"], + [10,"essenceoffrost"], + ], + "fireroamer":[ + [1.0/1442,"orbofstr"], + [1.0/1442,"orbofdex"], + [1.0/64,"essenceoffire"], + ], + "pppompom":[ + [1.0/1000,"orbofint"], + [1.0/1000,"orbofvit"], + ], + "mrpumpkin":[[100,"candy0"],[100,"candy1"],[100,"candy1"],[10,"phelmet"],[10.0/100000,"cxjar",1,"gcandle"],[10.0/100000,"cxjar",1,"breyes"],], + "mrgreen":[[100,"candy0"],[100,"candy1"],[100,"candy1"],[10,"gphelmet"],[15.0/100000,"cxjar",1,"bathat"],[1.0/100,"hdagger"]], + "jr":[ + #[1,"swirlipop"], + [0.1,"candy0"],[0.1,"candy1"], #[1,"candy1v2"],[1,"candy1v2"],[1,"candy1v2"],[1,"candy1v2"], + [1,"pstem"], + [1.0/1000,"hdagger"], + [1,"ololipop"], + ], + "greenjr":[ + #[1,"greenbomb"], + [0.1,"candy0"],[0.1,"candy1"], #[1,"candy1v2"],[1,"candy1v2"],[1,"candy1v2"],[1,"candy1v2"], + [1.0/1000,"bcandle"], + [1.0/1000,"hdagger"], + [1,"glolipop"], + ], + "slenderman":[ + [1.0/200,"cxjar",1,"mmakeup13"], + [1.0/20,"sbelt"], + [100,"candy0"], + [100,"candy1"], + ], + "bbpompom":[ + [0.0004,"essenceoffrost"], + [6.0/1000,"lspores"], + [1.0/1000000,"cxjar",1,"hat407"], + [1.0/20000000,"cxjar",1,"hat406"], + ], + "skeletor":[[0.5,"gem1"],[0.10,"gem1"],[0.10,"gem1"],[0.10,"gem1"],[0.02,"weaponbox"],[0.05,"armorbox"],[0.01,"shadowstone"],[1.0/5000,"scythe"]], + "greenfairy":[[1,"stick"]], + "redfairy":[[1,"stick"]], + "bluefairy":[[1,"stick"]], + "rudolph":[[1,"coal"],[1,"rednose"],[1,"iceskates"]], + "pinkgoo":[ + [0.3,"cupid"], + [0.001,"emptyheart"], + [0.0005,"solitaire"], + ], + "target_ar500red":[ + [1,"shadowstone"], + [0.5,"shadowstone"], + [0.25,"shadowstone"], + [0.125,"shadowstone"], + [0.0625,"shadowstone"], + ], + "franky":[ + [30,"cryptkey"], + [20,"candy0"], + [20,"candy0"], + [20,"candy0"], + [20,"candy0"], + [200,"candy1"], + [200,"candy1"], + [200,"candy1"], + [200,"candy1"], + [10,"frankypants"], + [1.0/2000,"mpxgloves"], + [1.0/5000,"ukey"], + [1.0/8000,"cxjar",1,"marmor3h"], + ], + "dragold":[ + [3,"goldenegg"], + [3,"goldenegg"], + [3,"goldenegg"], + [50,"essenceoffire"], + [40,"essenceoffire"], + [30,"essenceoffire"], + [20,"essenceoffire"], + [10,"essenceoffire"], + [10,"essenceoffire"], + [0.2,"offering"], + [0.5,"lmace"], + [2.0/4/1000/1000,"cxjar",1,"hat400"], + [2.0/6/1000/1000,"chrysalis0"], + ], + "ent":[ + [1,"essenceofnature"], + [0.02,"woodensword"], + [1/100000.0,"stick"], + [1/200000.0,"nheart"], + ], + "plantoid":[ + [0.004,"essenceofnature"], + [7.0/10000000,"ringofluck"], + ], + "grinch":[ + [0.6/100,"ringhs"], + [10,"wbookhs"], + [20.0,"gcape"], + [1.0/10000,"northstar"], + [1.0/10000,"dkey"], + [10,"iceskates"], + [1,"sweaterhs"], + ], + "bigbird":[ + [0.05,"feather0"], + ], + "harpy":[ + [0.01,"feather1"], + [0.01,"feather1"], + [0.01,"feather1"], + [0.01,"feather1"], + [0.01/600.0,"harpybow"], + [0.1,"essenceoffrost"], + [1.0/2000,"harbringer"], + ], + "rharpy":[ + [0.05,"feather1"], + [0.05,"feather1"], + [0.05,"feather1"], + [0.05,"feather1"], + [0.05/100.0,"harpybow"], + [1,"essenceoffrost"], + [1,"essenceoffrost"], + ], + "wabbit":[ + [10,"open","eastereggs"], + [10,"open","eastereggs"], + [10,"open","eastereggs"], + [10,"open","eastereggs"], + [10,"open","eastereggs"], + [10,"open","eastereggs"], + + [1,"open","eastereggs"], + [0.9,"open","eastereggs"], + [0.8,"open","eastereggs"], + [0.2,"open","eastereggs"], + [0.2,"open","eastereggs"], + [0.2,"open","eastereggs"], + [0.01,"goldenegg"], #originally 0.02 [11/04/19] + [0.01,"open","basketofeggs"], + [0.001,"emotionjar",1,"drop_egg"], + ], + "goldenbat":[ + [0.8,"handofmidas"], + [1,"bataxe"], + [0.01,"bfang"], + ], + "a1":[ + [1.0/20000,"vring"], + [1.0/2000,"vorb"], + [1.0/1000,"vcape"], + [1.0/10,"vattire"], + [0.001,"vblood"], + ], + "a2":[ + [1.0/20000,"vring"], + [1.0/2000,"cxjar",1,"hairdo607"], + [1.0/200,"vdagger"], + [1.0/200,"vdagger"], + [0.001,"vblood"], + ], + "a3":[ + [1.0/10,"vgloves"], + [1.0/200,"vhammer"], + [1.0/200,"vhammer"], + [0.001,"vblood"], + ], + "a4":[ + [1.0/1000,"vorb"], + [1.0/200,"cyber"], + [1.0/20000,"cxjar",1,"mask104"], + [0.001,"vblood"], + ], + "a5":[ + [1.0/10,"vboots"], + [1.0/2000,"cxjar",1,"hairdo608"], + [0.001,"vblood"], + [1.0/10000,"sbelt"], + ], + "a6":[ + [1.0/10,"mbelt"], + [1.0/200,"cyber"], + [1.0/20000,"cxjar",1,"mask105"], + [0.001,"vblood"], + ], + "a7":[ + [1.0,"fieldgen0"], + [1.0,"oozingterror"], + [0.001,"vblood"], + ], + "a8":[ + [1.0/10,"vgloves"], + [1.0/100,"vstaff"], + [0.001,"vblood"], + [1.0/4000,"sbelt"], + ], + "vbat":[ + [1.0/2,"cearring"], + [1.0/2,"cring"], + ], + "xmagex":[ + [1.0/50,"zapper"], + [1.0/5000,"trigger"], + [1.0/500,"mpxamulet"], + [1.0/500,"mpxgloves"], + [1.0/200000,"warpvest"], + [1.0/500,"starkillers"], + [1.0/100,"sbelt"], + ], + }, + "konami":[ + [6.0/10000000,"powerglove"], + [2.0/1000000000,"goldenpowerglove"], + ], + "statamulet":[ + [1,"intamulet"], + [1.2,"stramulet"], + [1,"dexamulet"], + ], + "statbelt":[ + [1,"intbelt"], + [1.05,"strbelt"], + [1,"dexbelt"], + ], + "statring":[ + [1,"intring"], + [1,"vitring"], + [1,"dexring"], + [1.2,"strring"], + ], + "basicelixir":[ + [1,"elixirvit0"], + [0.1,"elixirvit1"], + [0.01,"elixirvit2"], + [1,"elixirstr0"], + [0.1,"elixirstr1"], + [0.01,"elixirstr2"], + [1,"elixirdex0"], + [0.1,"elixirdex1"], + [0.01,"elixirdex2"], + [1,"elixirint0"], + [0.1,"elixirint1"], + [0.01,"elixirint2"], + ], + #quests + "glitch":[], #populated below + "lglitch":[], + "gemfragment":[ + [0.5,"gem0"], + [0.00001,"fury"], + [1,"t2stramulet"], + [1,"t2intamulet"], + [1,"t2dexamulet"], + ], + "seashell":[ + [0.000001,"vitscroll",10], + [1,"open","basicelixir"], + [0.00002,"fury"], + ], + "leather":[ + [20,"cape"], + [1,"bcape"], + [0.5,"open","armorbox"], + ], + "lostearring0":[ #0 + [1,"open","armorbox"], + ], + "lostearring1":[ #300k - 3X + [1,"open","weaponbox"], + ], + "lostearring2":[ #9.2m - 9X + [1,"wbook1"], + [0.25,"t2quiver"], + ], + "lostearring3":[ #36m - 27X + [0.5,"fury"], + [5,"handofmidas"], + ], + "lostearring4":[ #~120m - 81X + [1,"hhelmet"], #tier3 + [0.8,"harmor"], + [1,"hpants"], + [1.1,"hgloves"], + [0.5,"hboots"], + [0.1,"xhelmet"], #tier4 + [0.08,"xarmor"], + [0.1,"xpants"], + [0.11,"xgloves"], + [0.05,"xboots"], + ], + #events + "mistletoe":[ + [0.12,"eggnog"], + [1,"hotchocolate"], + [1,"warmscarf"], + [1,"snowball",10], + [0.1,"santasbelt"], + [1,"candycanesword"], + [1,"ornamentstaff"], + [0.8,"merry"], + [0.05,"mshield"], + [1,"rednose"], + [1,"xmashat"], + [1,"xmasshoes"], + [0.8,"xmassweater"], + [1,"xmaspants"], + [0.8,"mittens"], + [0.02,"angelwings"], + #[0.1,"orbofsc"], + [0.008,"supermittens"], + [0.0001,"mearring"], + [3.6,"open","gem0"], + ], + "candycane":[ + [0.05,"open","xN"], + [0.1,"eggnog"], + [1,"hotchocolate"], + [1,"warmscarf"], + [1,"snowball",10], + [0.1,"snowflakes"], + [0.1,"santasbelt"], + [1,"candycanesword"], + [1,"ornamentstaff"], + [0.8,"merry"], + [0.05,"mshield"], + [1,"rednose"], + [1,"xmashat"], + [1,"xmasshoes"], + [1,"xmassweater"], + [1,"xmaspants"], + [1,"mittens"], + [0.02,"angelwings"], + #[0.1,"orbofsc"], + [0.008,"supermittens"], + [3.6,"open","gem0"], + [0.00001,"northstar"], + [0.01,"shells",200], + ], + "5bucks":[ + [0.02,"5bucks",2], + [1,"shells",800], + ], + "ornament":[ + [0.1,"eggnog"], + [1,"hotchocolate"], + [1,"warmscarf"], + [1,"snowball",10], + [0.1,"santasbelt"], + [1,"candycanesword"], + [1,"ornamentstaff"], + [0.05,"mshield"], + [0.8,"merry"], + [1,"rednose"], + [1,"xmashat"], + [1,"xmasshoes"], + [0.8,"xmassweater"], + [1,"xmaspants"], + [0.8,"mittens"], + [0.02,"angelwings"], + #[0.1,"orbofsc"], + [0.012,"supermittens"], + [3.6,"open","gem0"], + ], + "xbox":[ + [1,"open","armorx"], + [1,"harbringer"], + [1,"t2quiver"], + [0.1,"exoarm"], + [0.06,"fury"], + [0.12,"starkillers"], + [0.01,"northstar"], + ], + "redenvelope":[ + [1000,"gold",500000], + [1,"gold",100000000], + [10,"cdragon"], + [40,"puppyer"], + ], + "redenvelopev2_shouldhavebeen":[ + [2000,"gold",50000], + [1,"gold",10000000], + [300,"firecrackers"], + [0.1,"dragondagger"], + [1,"cdragon"], + ], + "redenvelopev2":[ + [2000,"gold",500000], + [2,"gold",10000000], + [3000,"firecrackers"], + [1,"dragondagger"], + [1,"cdragon"], + ], + "redenvelopev3":[ + [2000,"gold",50000], + [1,"gold",10000000], + [300,"firecrackers"], + [0.1,"dragondagger"], + [1,"cdragon"], + ], + "redenvelopev4":[ + [2000,"gold",50000], + [1,"gold",10000000], + [300,"firecrackers"], + [0.1,"dragondagger"], + [1,"cdragon"], + ], + "greenenvelope":[ + [2000,"gold",50000], + [1,"gold",10000000], + [300,"firecrackers"], + [0.1,"dragondagger"], + [0.3,"lmace"], + [1,"oxhelmet"], + [0.1,"cdragon"], + ], + "eastereggs":[ + [1,"egg0"], + [1,"egg1"], + [1,"egg2"], + [1,"egg3"], + [1,"egg4"], + [1,"egg5"], + [1,"egg6"], + [1,"egg7"], + [1,"egg8"], + ], + "xN":[ + [1,"x0"], + [1,"x1"], + [1,"x2"], + [1,"x3"], + [1,"x4"], + [1,"x5"], + [1,"x6"], + [1,"x7"], + [1,"x8"], + ], + "goldenegg":[ + [100,"gold",1000000], + [10,"gold",10000000], + [1,"gold",100000000], + ], + "basketofeggs":[ + [1,"bunnyelixir"], + #[1,"bunnyears"], + #[1,"pyjamas"], + [1,"eears"], + [1,"epyjamas"], + [1,"ecape"], + [1,"eslippers"], + [0.5,"carrotsword"], + [0.1,"bataxe"], + [0.04,"pinkie"], + [0.04,"oozingterror"], + [0.04,"harbringer"], + [0.001,"rabbitsfoot"], #originally 0.02 + ], + "gift0":[ + #[1,"tristone"], + [1,"ftrinket"], + [1,"poker"], + [0.5,"partyhat"], + [0.008,"mysterybox"], + [0.1,"cake"], + [0.5,"open","armorx"], + [0.18,"scroll3"], + ], + "gift1":[ + [1,"open","thrash"], + [0.4,"cake"], + [0.2,"poker"], + [1,"confetti"], + #[1,"tristone"], + [0.8,"partyhat"], + [0.1,"gift0"], + [0.1,"open","armorbox"], + [0.05,"ftrinket"], + [0.006,"scroll3"], + [0.006,"mysterybox"], + [0.002,"offering"], + [0.0003,"luckbooster"], + ], + #thrash + "thrash":[ + [1,"coat"], + [1,"shoes"], + [1,"pants"], + [1,"gloves"], + [1,"helmet"], + [1,"empty"], + ], + #gems + "gem0":[ + [0.5,"weaponbox"], + [1.5,"armorbox"], + [0.5,"gold",100000], + [1,"gold",200000], + [1,"gold",200000], + [1,"gold",400000], + [0.5,"gold",800000], + [0.10,"gold",1600000], + [0.10,"gold",3200000], + [0.05,"gold",6400000], + [0.05,"offering"], + [1,"scroll1",10], + [0.5,"cscroll1",4], + [0.001,"shells",200], + [0.0001,"scroll3",1], + [0.0001,"cscroll3",1], + ], + "gem1_old":[ + [0.1,"weaponbox"], + [0.3,"armorbox"], + [0.1,"gem0"], + [3,"gold",50000], + [2,"gold",100000], + [0.5,"gold",200000], + [0.1,"gold",400000], + [0.01,"gold",800000], + [0.001,"gold",1600000], + [0.001,"gold",3200000], + [0.001,"offering"], + [0.5,"scroll0",75], + [0.5,"cscroll0",8], + [0.2,"scroll1",2], + [0.2,"cscroll1",1], + [0.001,"shells",50], + ], + "gem1":[ + [0.1,"weaponbox"], + [0.3,"armorbox"], + [0.001,"offering"], + [0.001,"shells",50], + [1,"open","thrash"], + [0.012,"gemfragment"], + ], + "candypop":[ + [1,"weaponbox"], + [1,"armorbox"], + [10,"gold",10000], + [10,"hpot1",100], + [10,"mpot1",100], + [10,"scroll0",5], + [5,"cscroll0",2], + [1,"scroll1",1], + [0.5,"cscroll1",1], + [0.0001,"shells",50], + [0.1,"emptyheart"], + [1,"cupid"], + ], + "candy0":[ + [1,"pmaceofthedead"], + [0.008,"spookyamulet"], + [1,"gold",480000], + [0.0005,"cxjar",1,"hat410"], + [0.001,"vblood"], + [0.12,"lantern"], + [0.1,"talkingskull"], + [1,"jacko"], + [0.1,"gphelmet"], + [1,"throwingstars"], + [2,"pumpkinspice"], + [0.1,"candy0",5], + [1,"open","weaponofthedead"], + [0.008,"mysterybox"], + [0.001,"gbow"], + [0.0005,"starkillers"], + [0.002,"swirlipop"], + [0.002,"greenbomb"], + [0.0005,"fury"], + [0.1,"open","armorx"], + ], + "candy1":[ + [0.8,"skullamulet"], + [0.05,"broom"], + [1,"gold",80000], + [0.03,"lantern"], + [0.8,"phelmet"], + [4.5,"smoke"], + [4.5,"pumpkinspice"], + [0.4,"candy0"], + [0.002,"swirlipop"], + [0.002,"greenbomb"], + [0.0001,"starkillers"], + [0.0001,"fury"], + [0.0012,"handofmidas"], + [0.007,"harbringer"], + [0.008,"oozingterror"], + [0.001,"open","armorx"], + [0.0001,"cxjar",1,"hairdo609"], + ], + "candy0v2":[ + [0.12,"lantern"], + [1,"gphelmet"], + [1,"throwingstars"], + [2,"pumpkinspice"], + [0.1,"candy0v2",5], + [1,"open","weaponofthedead"], + [0.008,"mysterybox"], + [0.002,"starkillers"], + [0.002,"swirlipop"], + [0.002,"greenbomb"], + [0.001,"fury"], + [0.1,"open","armorx"], + ], + "candy1v2":[ + [0.03,"lantern"], + [0.8,"phelmet"], + [4.5,"smoke"], + [4.5,"pumpkinspice"], + [0.4,"candy0v2"], + [0.002,"swirlipop"], + [0.002,"greenbomb"], + [0.0012,"starkillers"], + [0.0012,"fury"], + [0.0012,"handofmidas"], + [0.004,"harbringer"], + [0.001,"open","armorx"], + ], + "candy0v3":[ + [1,"gold",480000], + [0.001,"vblood"], + [0.12,"lantern"], + [0.1,"talkingskull"], + [1,"jacko"], + [0.1,"gphelmet"], + [1,"throwingstars"], + [2,"pumpkinspice"], + [0.1,"candy0v3",5], + [1,"open","weaponofthedead"], + [0.008,"mysterybox"], + [0.002,"starkillers"], + [0.002,"swirlipop"], + [0.002,"greenbomb"], + [0.001,"fury"], + [0.1,"open","armorx"], + ], + "candy1v3":[ + [1,"gold",80000], + [0.03,"lantern"], + [0.8,"phelmet"], + [4.5,"smoke"], + [4.5,"pumpkinspice"], + [0.4,"candy0v3"], + [0.002,"swirlipop"], + [0.002,"greenbomb"], + [0.0012,"starkillers"], + [0.0012,"fury"], + [0.0012,"handofmidas"], + [0.004,"harbringer"], + [0.001,"open","armorx"], + ], + "abtesting":[ + [1,"pvptoken"], + [1,"pvptoken",2], + [1,"pvptoken",3], + [0.5,"pvptoken",4], + [0.25,"pvptoken",5], + [0.125,"pvptoken",6], + [0.0675,"pvptoken",20], + [0.0025,"fury"], + ], + "abtesting_loser":[ + [1,"pvptoken"], + [0.5,"empty"], + ], + "weaponofthedead":[ + [0.85,"bowofthedead"], + [0.35,"swordofthedead"], + [1,"maceofthedead"], + [0.1,"pmaceofthedead"], + [1,"staffofthedead"], + [1,"daggerofthedead"], + ], + "bugbountybox":[ + [1,"glitch"], + ], + "apologybox":[ + [1,"glitch"], + ], + "f1":[ + [14,"coat1"], + [22,"helmet1"], + [20,"pants1"], + [22,"gloves1"], + [14,"shoes1"], + [0.5,"open","lglitch"], + ], + "m1":[ + [200,"gemfragment"], + [1,"bronzenugget"], + [0.5,"goldnugget"], + [0.1,"platinumnugget"], + #[0.5,"open","glitch"], + [0.1,"emotionjar",1,"hearts_single"], + ], + "m2":[ + [100,"empty"], + [10,"wbook0"], + [0.1,"wbook1"], + ], + "armorbox":[ + [14,"coat1"], + [22,"helmet1"], + [20,"pants1"], + + [1,"hhelmet"], #tier3 + [0.8,"harmor"], + [1,"hpants"], + [1.1,"hgloves"], + [0.5,"hboots"], + + [22,"gloves1"], + + [0.1,"xhelmet"], #tier4 + [0.08,"xarmor"], + [0.1,"xpants"], + [0.11,"xgloves"], + [0.05,"xboots"], + + [0.005,"fury"], + [0.005,"starkillers"], + + [14,"shoes1"], + ], + "armorx":[ + [1,"hhelmet"], #tier3 + [0.8,"harmor"], + [1,"hpants"], + [1.1,"hgloves"], + [0.5,"hboots"], + [0.1,"xhelmet"], #tier4 + [0.08,"xarmor"], + [0.1,"xpants"], + [0.11,"xgloves"], + [0.05,"xboots"], + ], + "mysterybox":[ + [70,"open","armorx"], + [20,"scroll3"], + [4,"cscroll3"], + [1,"warpvest"], + [1,"scroll4"], + ], + "test":[ + [1,"armorbox"], + [1,"open","lightmage"] + ], + "lightmage":[ + [1,"hpot0"], + [1,"mpot0"], + ], + "weaponbox":[ + [1,"throwingstars"], + [0.05,"harbringer"], + [0.04,"oozingterror"], + [1.4,"t2bow"], + [1,"basher"], + [1,"spear"], + [1,"dagger"], + [0.5,"pmace"], + [1,"fireblade"], + [0.8,"firestaff"], + [0.04,"t3bow"], + [0.02,"hammer"], + [0.1,"rapier"], + [1,"sword"], + [0.2,"crossbow"], + ], + "jewellerybox":[ + [1,"hpamulet"], + [1,"hpbelt"], + ], + "quiver":[ + [1,"leather"], + [0.5,"leather"], + ], + "troll":[ + [100,"tshirt0"], + [100,"tshirt1"], + [100,"tshirt2"], + [20,"tshirt3"], + [10,"tshirt4"], + [0.1,"tshirt88"], + [1,"tshirt6"], + [1,"tshirt7"], + [0.8,"tshirt8"], + [0.8,"tshirt9"], + [0.0001,"luckyt"], + ], + "skins":{ + #gold 0.05 - perfect ones + "gold":[ + ], + #silver 0.1 - good ones + "silver":[ + "mwarrior_cool","mnwarrior", + ], + #bronze 0.80 - nice/usable ones + "bronze":[ + + ], + #normal 0.05 - mostly NPC's + "normal":[ + ], + }, + "cosmo0":[ + #[1.0,"cxbundle","rogueb"], + #[1,"cx","lchar1b"], + [1.0/2,"cx","marmor10a"], + [1.0,"cx","marmor10b"], + [1.0/1.2,"cx","marmor10c"], + [1.0,"cx","marmor10g"], + [1.0,"cx","marmor10h"], + [1.0,"cx","marmor11a"], + [1.0/2,"cx","marmor11b"], + [1.0,"cx","marmor11c"], + [1.0/2,"cx","marmor11d"], + [1.0/2,"cx","marmor11e"], + [1.0,"cx","marmor11f"], + [1.0,"cx","marmor11g"], + [1.0,"cx","marmor11h"], + [1.0/2,"cx","marmor1b"], + [1.0/2,"cx","marmor1c"], + [1.0,"cx","marmor2a"], + [1.0,"cx","marmor2b"], + [1.0/5,"cx","marmor2e"], + [1.0/2,"cx","marmor2f"], + [1.0,"cx","marmor2g"], + [1.0/10,"cx","marmor2h"], + [1.0,"cx","marmor3a"], + [1.0,"cx","marmor3b"], + [1.0,"cx","marmor3c"], + [1.0,"cx","marmor3d"], + [1.0,"cx","marmor3g"], + [1.0,"cx","marmor4c"], + [1.0,"cx","marmor4d"], + [1.0/3,"cx","marmor4e"], + [1.0,"cx","marmor4g"], + [1.0/1.2,"cx","marmor4h"], + [1.0/10,"cx","marmor5b"], + [1.0,"cx","marmor5c"], + [1.0,"cx","marmor5f"], + [1.0,"cx","marmor5g"], + [1.0,"cx","marmor5h"], + [1.0/3,"cx","marmor5e"], + [1.0,"cx","marmor6g"], + [1.0,"cx","marmor6h"], + [1.0,"cx","marmor7a"], + [1.0,"cx","marmor7b"], + [1.0,"cx","marmor7c"], + [1.0,"cx","marmor7d"], + [1.0,"cx","marmor7e"], + [1.0,"cx","marmor7f"], + [1.0,"cx","marmor7g"], + [1.0,"cx","marmor7h"], + [1.0,"cx","marmor8a"], + [1.0,"cx","marmor8b"], + [1.0,"cx","marmor8c"], + [1.0,"cx","marmor8d"], + [1.0,"cx","marmor8e"], + [1.0,"cx","marmor8f"], + [1.0,"cx","marmor8g"], + [1.0,"cx","marmor8h"], + [1.0/3,"cx","marmor9a"], + [1.0/5,"cx","marmor9b"], + [1.0,"cx","marmor9c"], + [1.0,"cx","marmor9d"], + [1.0/10,"cx","marmor9e"], + [1.0/9,"cx","marmor9f"], + [1.0/12,"cx","marmor9g"], + [1.0/3,"cx","marmor9h"], + [1.0,"cx","sarmor1a"], + [1.0,"cx","sarmor1c"], + [1.0,"cx","sarmor1d"], + [1.0,"cx","sarmor1e"], + [1.0,"cx","sarmor1f"], + [1.0,"cx","sarmor1g"], + [1.0,"cx","sarmor2a"], + [1.0,"cx","sarmor2b"], + [1.0,"cx","sarmor2c"], + [1.0/32,"cx","mbody1a"], + [1.0/4,"cx","mbody1b"], + [1.0/8,"cx","mbody1c"], + [1.0,"cx","mbody1d"], + [1.0/5,"cx","mbody1e"], + [1.0,"cx","mbody1f"], + [1.0/3,"cx","mbody1g"], + [1.0,"cx","mbody1h"], + [1.0,"cx","mbody2a"], + [1.0,"cx","mbody2d"], + [1.0,"cx","mbody2e"], + [1.0/20,"cx","mbody2f"], + [1.0/12,"cx","mbody3a"], + [1.0/16,"cx","mbody3b"], + [1.0/48,"cx","mbody3d"], + [1.0/72,"cx","mbody3e"], + [1.0/1.2,"cx","mbody4a"], + [1.0/5,"cx","mbody4e"], + [1.0,"cx","mbody4g"], + [1.0,"cx","mbody4d"], + [1.0/10,"cx","mbody4h"], + [1.0/10,"cx","mbody5a"], + [1.0/10,"cx","mbody5c"], + [1.0/6,"cx","mbody5d"], + [1.0/10,"cx","mbody6a"], + [1.0,"cx","sbody1d"], + [1.0,"cx","sbody1e"], + [1.0/12,"cxbundle","pinkb"], + [1.0/40,"cxbundle","blackw"], + ], + "cosmo1":[ + [1,"cx","mmakeup0"], + ], + "cosmo2":[ + ], + "cosmo3":[ + ], +} + +for n,nm in [[1,25],[2,25],[3,25],[4,25],[5,22]]: + for num in xrange(nm): + if "%s%.2d"%(n,num) in ["122","203","404"]: continue + drops["cosmo2"].append([1,"cx","hairdo%s%.2d"%(n,num)]) + +drops["cosmo2"].append([1.0/2,"cx","hairdo122"]) +drops["cosmo2"].append([1.0/3,"cx","hairdo404"]) +drops["cosmo2"].append([1.0/10,"cx","hairdo203"]) + +for n,nm in [[1,16],[2,25],[3,24],[4,8]]: + for num in xrange(nm): + if "%s%.2d"%(n,num) in ["100","114","115","102","106","113","310","309","318","400","405"]: continue + drops["cosmo3"].append([1,"cx","hat%s%.2d"%(n,num)]) + +drops["cosmo3"].append([1.0/2,"cx","hat106"]) +drops["cosmo3"].append([1.0/3,"cx","hat310"]) +drops["cosmo3"].append([1.0/5,"cx","hat102"]) +drops["cosmo3"].append([1.0/8,"cx","hat318"]) +drops["cosmo3"].append([1.0/10,"cx","hat113"]) +drops["cosmo3"].append([1.0/12,"cx","hat309"]) +drops["cosmo3"].append([1.0/12,"cx","hat400"]) +drops["cosmo3"].append([1.0/12,"cx","hat405"]) + +for key in drops.keys(): + if key.find(",")!=-1: + t=drops[key] + del drops[key] + key=key.split(","); key.sort() + key=",".join(key) + drops[key]=t + +for name in items: + if not items[name].get("ignore") and not items[name].get("exclusive"): + if items[name].get("grades") and (items[name].get("upgrade") and items[name]["grades"][2]<8 or items[name].get("compound") and items[name]["grades"][2]<3): + drops["glitch"].append([0.1,name]) + elif items[name].get("grades") and items[name]["grades"][2]==0: + drops["glitch"].append([0.1,name]) + elif items[name].get("grades") and items[name]["grades"][1]==0: + drops["glitch"].append([0.25,name]) + else: + drops["glitch"].append([1,name]) + +for name in items: + if not items[name].has_key("g"): + import logging + logging.error(name) + if not items[name].get("ignore") and not items[name].get("exclusive"): + if items[name].get("grades") and (items[name].get("upgrade") and items[name]["grades"][2]<8 or items[name].get("compound") and items[name]["grades"][2]<3) or items[name].get("g",0)>5000000: + drops["lglitch"].append([0.01,name]) + elif items[name].get("grades") and items[name]["grades"][2]==0: + drops["lglitch"].append([0.05,name]) + elif items[name].get("grades") and items[name]["grades"][1]==0 or items[name].get("g",0)>50000: + drops["lglitch"].append([0.1,name]) + else: + drops["lglitch"].append([1,name]) + +drops["glitch"].append([5,"glitch",2]) +drops["monsters"]["cutebee"]=[[1,"open","lglitch"]] +drops["monsters"]["cutebee"].append([1,"funtoken"]) +#drops["candy0"]=copy.deepcopy(drops["gem0"]) +#drops["candy0"].append([2,"phelmet"]) +#drops["candy1"]=copy.deepcopy(drops["gem1"]) +#drops["candy1"].append([0.32,"phelmet"]) diff --git a/design/emotions.py b/design/emotions.py new file mode 100644 index 0000000..a52884c --- /dev/null +++ b/design/emotions.py @@ -0,0 +1,10 @@ +emotions={ + "drop_egg":{ + "fx":"drop_egg", + "cooldown":2000, + }, + "hearts_single":{ + "fx":"hearts_single", + "cooldown":2000, + }, +} \ No newline at end of file diff --git a/design/events.py b/design/events.py new file mode 100644 index 0000000..d7a8409 --- /dev/null +++ b/design/events.py @@ -0,0 +1,82 @@ +events={ + "abtesting":{ + "name":"A/B Testing", + "modal":"event-abtesting", + "sprite":"thehelmet", + "duration":8*60, + "join":True, + "type":"daily", + }, + "goobrawl":{ + "name":"Goo Brawl", + "modal":"event-goobrawl", + "sprite":"rgoo", + "duration":9*60, + "join":True, + "type":"daily", + }, + "crabxx":{ + "name":"Giga Crab", + "modal":"event-crabxx", + "sprite":"crabxx", + "duration":60*40, + "join":True, + "type":"daily", + }, + "franky":{ + "name":"Franky", + "modal":"event-franky", + "sprite":"franky", + "duration":60*40, + "join":True, + "type":"nightly", + }, + "icegolem":{ + "name":"Ice Golem", + "modal":"event-icegolem", + "sprite":"icegolem", + "duration":60*40, + "join":True, + "type":"nightly", + }, + "holidayseason":{ + "name":"Holiday Season", + "modal":"event-holidayseason", + "sprite":"grinch", + "duration":60*60*24*30, + #"join":True, + "type":"seasonal", + }, + "lunarnewyear":{ + "name":"Lunar New Year", + "modal":"event-lunarnewyear", + "sprite":"redenvelopev4", + "duration":60*60*24*15, + #"join":True, + "type":"seasonal", + }, + "valentines":{ + "name":"Valentines", + "modal":"event-valentines", + "sprite":"cupid", + "duration":60*60*24*10, + #"join":True, + "type":"seasonal", + }, + "egghunt":{ + "name":"Egg Hunt", + "modal":"event-egghunt", + "sprite":"basketofeggs", + "duration":60*60*24*15, + #"join":True, + "type":"seasonal", + }, + "halloween":{ + "name":"Halloween", + "modal":"event-halloween", + "sprite":"candy0", + "duration":60*60*24*30, + #"join":True, + "type":"seasonal", + }, +} \ No newline at end of file diff --git a/design/events.txt b/design/events.txt new file mode 100644 index 0000000..f5e92db --- /dev/null +++ b/design/events.txt @@ -0,0 +1,55 @@ +Mystery House +1) Entry room, small cozy room, just 3 doors, player picks one to enter a random room +2) [Random] Haunted room, there are 2-4 doors, there are 5-8 ghosts inside, this is a ~large room, the player can engage ghosts or just escape, ghosts are extremely aggressive - there might be 1-2 random chests inside the room +3) [Random] Chest room, the player got lucky, he found a chest, there are 2-3 doors to select to exit +4) [Random] Boss room, there is a random boss inside, there are 2-3 doors to escape from +5) [Random] Gateway room, there are 3-7 doors inside, there might or might not be a random chest too +6) Exit room, players luck has ran out, the exit room has just one door, and that teleport the player to the entrance + +In (3) and (5), the chests might spawn a super strong boss, it will likely kill the player, so they shouldn’t be super tiny rooms, there should be space for a random spawning vicious monster + +> Survival Mode Daily Event [01/03/17] + + + + + +``` +The Rush +1) Potion Zone (Monsters drop potions in this room) +2) Scroll Zone (Monsters drop scrolls in this room/area) +3) Item Zone (Monsters/Bosses drop accessories, weapons, armors in this area) +4) Upgrade/Compound Zone - There is one bust or monument, players can upgrade or compound here +Players need potions as the +100/+200 potionless bonuses are +10/+20 in this area, and they can't bring potions inside +Players need scrolls as to leave this zone with anything, the upgraded items need to be at least +8, accessories need to be +2 (or +1, if it's rare, not sure yet) +Players have a total of 15 minutes inside the zone +They could choose to go after the bosses for better drops, or, they could slay normal monsters for worse accessories, weapons, armors etc. +We could divide (3) into 2 zones, bosses and monsters, unsure yet +``` + + +Anniversary: + +Confetti Pack - Can be thrown anywhere +Poke Glove - Ability: Poke +Party Hat - Random Coloured Lines +Scroll 3 - +11 +Trinket of Faith - Good things come to those who wait - 120 MP - 2 Int/Str/Vit - 0.5 Speed +T3/T4 armors +Tri-Color-Ring - 5 Armor Piercing - 5 Res Piercing - 1 Int - 1 Str - 1 Int - 1 Vit + +Daily Events: [2X Each Day ~30mins each] [8PM-9PM] +- Goo Brawl [PVE] +- A/B Testing [PVP] +- Come up with more [TODO] + +Daily Zones: [9PM-12PM] +Monday - Mansion Mystery [Done] +Tuesday - The Castle [Done] +Wednesday - Cloudland +Thursday - Dracul's Lair +Friday - [?] +Saturday - The Island with the Tall Tower +Sunday - Pirate Ship [PVP] [Done] + +Everyday [12PM-1AM] - [PVP] A multi-level dungeon opens for 1 hour \ No newline at end of file diff --git a/design/extended_properties.txt b/design/extended_properties.txt new file mode 100644 index 0000000..96d7562 --- /dev/null +++ b/design/extended_properties.txt @@ -0,0 +1,29 @@ +New Properties +mpower: Magic Power +5% (Like Damage Output, but just for magical damage) +shock: Delayed Magic Crit +5% +shockdamage: Shock Damage +50% +stresistance: Status Resistance +10% (10% lower debuff duration) +pnresistance: Poison Resistance +20% (20% chance to resist, 20% less duration) +fzresistance: Cold Resistance +20% (20% chance to resist, 20% less affliction) +firesistance: Fire Resistance +20% (20% chance to resist, 20% less damage) +phresistance: Impact Resistance +10% (Resist Stuns, future physical moves) +bmresistance: Black Magic R. +20% (Resist Curse, Stone etc.) +cuteness: /bmresistance (Minor amounts) Aggro Reduction +awesomeness: /phresistance +charisma: /-firesistance +bling: /-stresistance + + +Special Armor Scrolls [Flat] +Gold Digger: +2% Gold +Armory: 10 Armor +Reflector: +2% Reflection +Healio: +20% Healing Received +Evasion Piercer: +10% Evasion Piercing + + +Special Weapon Scrolls +Humanoid Hunter: +5% Damage to Humanoids +Desert Dweller: +8% Damage in Desertland +Armor Piercer: 40 Armor Piercing +Resistance Piercer: 40 Resistance Piercing diff --git a/design/game.py b/design/game.py new file mode 100644 index 0000000..231729b --- /dev/null +++ b/design/game.py @@ -0,0 +1,35 @@ +character_types=["warrior","paladin","mage","priest","rogue","ranger","merchant"] #,"assassin","paladin","archer","priest"] +#STR -> Warrior, Paladin - Paladin hits 50%/50% Physical/Magical - Hits magical on high ranges, can't wield heavy items +#DEX -> Assasin, Archer +#INT -> Mage, Priest - Priest can heal players aggressively + slows on damage +gender_types=["male","female"] +allowed_name_characters="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" +item_grades={ + "low":{"color":"grey"}, + "mid":{"color":"blue"}, + "high":{"color":"green"}, + "rare":{"color":"orange"}, + "unique":{"color":"purple"}, +} + +party_xp=[0,1,1.10,0.9,0.75,0.6,0.5,0.40,0.3] +server_regions={ + "US":"Americas", + "EU":"Europas", + "ASIA":"Eastlands", +} +server_names=["I","II","III","IV","V","VI","VII","VIII","IX","X","XI","XII"] + +community_maps=[ #to look for map creator talent, to show the editor to pixel artists + "test481612",#oragon + "test421421",#mine + "test468122",#range +] + +ellian_id="5941620885159936" +hello_id="6218930913804288" #hello@adventure.land +inner_circle=[ + "5752754626625536", #me + "6243983994912768", #json + "5818821692620800", #me-sdk +] \ No newline at end of file diff --git a/design/games.py b/design/games.py new file mode 100644 index 0000000..e864322 --- /dev/null +++ b/design/games.py @@ -0,0 +1,45 @@ +games={ + "tarot":{ + "npc":"twitch", + "cards":["chariot","death","devil","emperor","empress","fool","fortune","hangman","hermit","hierophant","judgment","justice","lovers","magician","moon","priestess","star","strength","sun","temperance","theworld","tower"], + "hours":23, + }, + "dice":{ + + }, + "wheel":{ + "gold":1000000, + "slices":[ + ["g0","gold",250000,"gold"], + ["g1","gold",500000,"gold"], + ["g2","gold",1000000,"gold"], + ["g3","gold",2000000,"gold"], + ["g4","gold",5000000,"gold"], + ["g5","gold",10000000,"gold"], + ["g6","gold",20000000,"gold"], + ["g7","gold",50000000,"gold"], + ["g7","gold",100000000,"gold"], + ["g8","gold",250000000,"gold"], + ["g9","gold",1000000000,"gold"], + ["gg","item","glitch","#1398D3"], + ["ow","item","funtoken","gold"], + ], + }, + "slots":{ + "gold":1000000, + "glyphs":["1","2","3","4","5","6","7","8","A","L"], + }, +} + +odds={ + "slots":1.0/640, + "slots_good":1.0/525, +} + + + +for c in ["2","3","4","5","6","7","8","9","10","ace","king","knight","page","queen"]: + games["tarot"]["cards"].append("%scups"%c) + games["tarot"]["cards"].append("%spentacles"%c) + games["tarot"]["cards"].append("%sswords"%c) + games["tarot"]["cards"].append("%swands"%c) \ No newline at end of file diff --git a/design/items.py b/design/items.py new file mode 100644 index 0000000..9726704 --- /dev/null +++ b/design/items.py @@ -0,0 +1,7183 @@ +import math +# "s" Stackable +# "e" Exchangable +# "a" Announce + High Grade +# "a" 2 - Announce Within the Map +items={ + "test":{ + "type":"test", + "skin":"test", + "ignore":True, + "name":"Test", + "explanation":"An item to test item looks, just set the 'skin' property.", + "g":1, + }, + "test2":{ + "type":"orb", + "skin":"shells", + "ignore":True, + "name":"Test", + "for":120, + "manasteal":2, + "critdamage":60, + #"luck":9999999999, + "explanation":"An item to test properties!", + "g":1, + }, + "test_orb":{ + "type":"orb", + "skin":"test_orb", + "name":"Orb of Testing", + #"manasteal":0.25, + "fzresistance":20, + "firesistance":20, + #"mp_reduction":20, + #"ability":"restore_mp", + #"attr0":8, + "compound":{ + }, + "grades":[0,0], + "g":1, + }, + "placeholder":{ + "type":"placeholder", + "skin":"placeholder", + "ignore":True, + "name":"Placeholder", + "g":1, + }, + "placeholder_m":{ + "type":"placeholder", + "skin":"placeholder_m", + "ignore":True, + "name":"Placeholder", + "g":1, + }, + "stealthcape":{ + "type":"cape", + "skin":"stealthcape", + "resistance":42, + "stat":3, + "name":"Stealth Cape", + "upgrade":{ + "resistance":1, + "stat":0.30, + }, + "explanation":"Thanks to it's stealth capabilities, no one can track your endeavours any more.", + "grades":[0,4], + "g":2000000, + }, + "cape":{ + "type":"cape", + "skin":"cape0", + "armor":10, + "resistance":8, + "stat":4, + "name":"Cape", + "upgrade":{ + "armor":2, + "resistance":1, + "stat":0.10, + }, + "grades":[0,8], + "g":20000, + }, + "fcape":{ + "type":"cape", + "skin":"fcape", + "armor":10, + "resistance":8, + "firesistance":4, + "stat":6, + "name":"Fiery Cape", + "upgrade":{ + "armor":2, + "resistance":2, + "stat":0.10, + "firesistance":4, + }, + "grades":[0,0], + "g":16000000, + }, + "ecape":{ + "set":"bunny", + "type":"cape", + "skin":"ecape", + "armor":10, + "resistance":8, + "stat":5, + "cuteness":20, + "name":"Fluffy Blanket", + "upgrade":{ + "cuteness":3, + "armor":2, + "resistance":1, + "stat":0.10, + }, + "grades":[0,7], + "g":20000, + }, + "gcape":{ + "type":"cape", + "skin":"gcape", + "resistance":8, + "stat":4, + "pnresistance":5, + "evasion":1, + "reflection":1, + "speed":-2, + "name":"Grinch's Cape", + "upgrade":{ + "resistance":4, + "pnresistance":1, + "stat":0.10, + }, + "grades":[0,7], + "g":8008, + }, + "angelwings":{ + "type":"cape", + "skin":"angelwings", + "resistance":8, + "stat":3, + "speed":1, + "evasion":1, + "name":"Angel Wings", + "upgrade":{ + "resistance":1, + "evasion":0.2, + "speed":0.2, + "stat":0.10, + }, + "grades":[0,6], + "g":120000, + "a":True, + "action":"FLAP", + "onclick":"socket.emit('activate',{slot:$(this).data('id')})" + }, + "tigercape":{ + "set":"tiger", + "type":"cape", + "skin":"tigercape", + "armor":18, + "resistance":12, + "speed":1, + "str":1, + "dex":1, + "stat":4, + "name":"Cape of the Tiger", + "upgrade":{ + "armor":3, + "resistance":2, + "stat":0.10, + }, + "grades":[0,4], + "a":True, + "g":2400000, + }, + "bcape":{ + "type":"cape", + "skin":"cape1", + "armor":18, + "resistance":12, + "stat":5, + "name":"Well-Crafted Cape", + "upgrade":{ + "armor":3, + "resistance":2, + "stat":0.10, + }, + "grades":[0,4], + "a":True, + "g":2400000, + }, +} + +armor={ + "fury":{ + "set":"fury", + "tier":1.5, + "type":"helmet", + "class":["rogue","warrior"], + "skin":"fury", + "scroll":True, + #"evasion":1, + "dex":2, + "crit":6, + "apiercing":20, + "upgrade":{ + "crit":0.5, + "apiercing":10, + }, + "legacy":{ + "class":None, + "set":None, + }, + "name":"Band of Fury", + "grades":[0,0], + "g":6400000, + "a":True, + }, + "tigerhelmet":{ + "set":"tiger", + "tier":2, + "type":"helmet", + "skin":"tigerhelmet", + "scroll":True, + "crit":0.5, + "speed":2, + "rogue":{ + "crit":2, + "upgrade":{ + "crit":0.25, + } + }, + "upgrade":{ + }, + "name":"Helmet of the Tiger", + "grades":[0,6], + "g":640000, + "a":True, + }, + "mageshood":{ + "tier":2, + "type":"helmet", + "class":["mage"], + "skin":"mageshood", + "scroll":True, + "crit":0.5, + "upgrade":{ + "rpiercing":10, + }, + "name":"Mage's Hood", + "grades":[0,8], + "g":640000, + "a":True, + "ignore":True, + }, + "rednose":{ + "type":"helmet", + "skin":"rednose", + "scroll":True, + "range":3, + "cuteness":9, + "compound":{ + "range":4, + "cuteness":3, + }, + "name":"Rudolph's Red Nose", + "grades":[2,4], + "g":32000, + "a":True, + }, + "helmet":{ + #"set":"base", + "tier":1, + "type":"helmet", + "skin":"helmet", + "scroll":True, + "upgrade":{ + }, + "name":"Helmet", + "g":3200, + }, + "cyber":{ + "dex":2, + "str":2, + "int":6, + "pnresistance":4, + "mcourage":1, + "pcourage":1, + "tier":3, + "type":"helmet", + "skin":"cyber", + "scroll":True, + "upgrade":{ + }, + "name":"Cybernetic Implants", + "g":320000, + }, + "wcap":{ + "set":"wanderers", + "tier":1, + "type":"helmet", + "skin":"wcap", + "hp":120, + "scroll":True, + "upgrade":{ + }, + "name":"Wanderer's Cap", + "g":6400, + }, + "xmashat":{ + "set":"holidays", + "tier":1.5, + "type":"helmet", + "skin":"xmashat", + "scroll":True, + "vit":2, + "upgrade":{ + }, + "name":"Xmas Hat", + "xcx":["hat100"], + "g":13200, + "a":True, + }, + "ghatb":{ + "type":"helmet", + "skin":"ghatb", + "hat":"hat114", + "vit":24, + "name":"Hat of Generosity", + "explanation":"If you put on this hat, you can run item giveaways!", + "g":128000, + }, + "ghatp":{ + "type":"helmet", + "skin":"ghatp", + "hat":"hat115", + "vit":24, + "name":"Hat of Generosity", + "explanation":"If you put on this hat, you can run item giveaways!", + "g":128000, + }, + "helmet1":{ + "set":"rugged", + "tier":2, + "type":"helmet", + "skin":"helmet1", + "scroll":True, + "upgrade":{ + }, + "name":"Rugged Helmet", + "g":32000, + "a":2, + }, + "mwhelmet":{ + "class":["warrior"], + "set":"mwarrior", + "tier":2.625, + "type":"helmet", + "skin":"mwhelmet", + "scroll":True, + "upgrade":{ + }, + "name":"Helmet of the Hunter Warrior", + "explanation":"You served our realm well", + "g":64000, + }, + "mmhat":{ + "rpiercing":40, + "class":["mage"], + "set":"mmage", + "tier":2.125, + "type":"helmet", + "skin":"mmhat", + "scroll":True, + "upgrade":{ + }, + "name":"Hat of the Hunter Mage", + "explanation":"You served our realm well", + "g":64000, + }, + "mphat":{ + "class":["priest"], + "set":"mpriest", + "tier":2.125, + "type":"helmet", + "skin":"mphat", + "scroll":True, + "upgrade":{ + }, + "name":"Hat of the Hunter Priest", + "explanation":"You served our realm well", + "g":64000, + }, + "mrnhat":{ + "class":["ranger"], + "set":"mranger", + "tier":2.25, + "type":"helmet", + "skin":"mrnhat", + "scroll":True, + "upgrade":{ + }, + "name":"Hat of the Hunter Ranger", + "explanation":"You served our realm well", + "g":64000, + }, + "mrhood":{ + "evasion":5, + "class":["rogue"], + "set":"mrogue", + "tier":2.25, + "type":"helmet", + "skin":"mrhood", + "scroll":True, + "upgrade":{ + }, + "name":"Hood of the Hunter Rogue", + "explanation":"You served our realm well", + "g":64000, + }, + "mchat":{ + "class":["merchant"], + "set":"mmerchant", + "tier":2.25, + "type":"helmet", + "skin":"mchat", + "scroll":True, + "upgrade":{ + }, + "name":"Hat of the Hunter Merchant", + "explanation":"Your comrades served our realm well", + "g":64000, + }, + "partyhat":{ + "tier":1, + "type":"helmet", + "skin":"partyhat", + "scroll":True, + "upgrade":{ + "str":0.2, + "int":0.2, + "dex":0.2, + "vit":0.1, + }, + "name":"Party Hat", + "g":12000, + "a":2, + }, + "phelmet":{ + "tier":2, + "extra_stat":0, + "type":"helmet", + "skin":"phelmet", + "scroll":True, + "reflection":1, + "upgrade":{ + "reflection":0.4, + }, + "name":"Pumpkin Head", + "g":72000, + "a":2, + "grades":[0,7], + }, + "gphelmet":{ + "tier":2, + "extra_stat":0, + "type":"helmet", + "skin":"gphelmet", + "scroll":True, + "luck":-4, + "reflection":1, + "lifesteal":2, + "crit":0.5, + "rpiercing":10, + "upgrade":{ + "reflection":0.4, + "crit":0.1, + }, + "name":"Green Pumpkin Head", + "g":32000, + "a":2, + "grades":[0,0], + }, + "bunnyears":{ + "tier":2, + "type":"helmet", + "skin":"bunnyears", + "scroll":True, + "cuteness":12, + "vit":4, + "evasion":1, + "upgrade":{ + "cuteness":2, + "evasion":0.20, + }, + "name":"Legacy Bunny Ears", + "g":32000, + "a":2, + "grades":[4,8], + }, + "eears":{ + "set":"bunny", + "tier":1.5, + "type":"helmet", + "skin":"eears", + "scroll":True, + "cuteness":12, + "vit":2, + "evasion":1, + "upgrade":{ + "cuteness":2, + "evasion":0.20, + }, + "name":"Bunny Ears", + "g":32000, + "a":2, + "grades":[6,9], + }, + "hhelmet":{ + "set":"wt3", + "tier":3, + "type":"helmet", + "skin":"hhelmet", + "scroll":True, + "upgrade":{ + }, + "name":"Heavy Helmet", + "g":320000, + "a":2, + }, + "xhelmet":{ + "set":"wt4", + "tier":4, + "type":"helmet", + "skin":"xhelmet", + "xscroll":True, + "scroll":True, + "upgrade":{ + }, + "name":"Darkforge Helmet", + "g":3200000, + "a":2, + }, + "luckyt":{ + #"set":"base", + "type":"chest", + "skin":"luckyt", + "resistance":20, + "luck":7, + "xp":5, + "scroll":True, + "upgrade":{ + "resistance":10, + "luck":1.75, + "xp":1, + }, + "grades":[0,0,0], + "name":"Lucky T-Shirt", + "g":120000, + }, + "tshirt0":{ + "type":"chest", + "skin":"tshirt0", + "int":5, + "upgrade":{ + "int":1.25, + }, + "name":"T-Shirt", + "grades":[0,6], + "g":120, + }, + "tshirt1":{ + "type":"chest", + "skin":"tshirt1", + "dex":5, + "upgrade":{ + "dex":1.25, + }, + "name":"T-Shirt", + "grades":[0,6], + "g":120, + }, + "tshirt2":{ + "type":"chest", + "skin":"tshirt2", + "str":5, + "upgrade":{ + "str":1.25, + }, + "name":"T-Shirt", + "grades":[0,6], + "g":120, + }, + "tshirt3":{ + "type":"chest", + "skin":"tshirt3", + "xp":2, + "upgrade":{ + "xp":0.75, + }, + "name":"T-Shirt", + "grades":[0,6], + "g":120, + }, + "tshirt4":{ + "type":"chest", + "skin":"tshirt4", + "speed":3, + "upgrade":{ + "speed":0.5, + }, + "name":"T-Shirt", + "grades":[0,6], + "g":120, + }, + "tshirt88":{ + "type":"chest", + "skin":"tshirt88", + "speed":3, + "luck":12, + "xp":5, + "dex":5, + "str":5, + "int":5, + "upgrade":{ + "int":1, + "str":1, + "dex":1, + }, + "name":"T-Shirt", + "grades":[0,6], + "g":120, + }, + "tshirt6":{ + "type":"chest", + "skin":"tshirt6", + "rpiercing":30, + "upgrade":{ + "rpiercing":5, + }, + "name":"T-Shirt", + "grades":[0,6], + "g":120, + }, + "tshirt7":{ + "type":"chest", + "skin":"tshirt7", + "apiercing":30, + "upgrade":{ + "apiercing":5, + }, + "name":"T-Shirt", + "grades":[0,6], + "g":120, + }, + "tshirt8":{ + "type":"chest", + "skin":"tshirt8", + "mp_cost":-5, + "upgrade":{ + "mp_cost":-2, + }, + "name":"T-Shirt", + "grades":[0,6], + "g":120, + }, + "tshirt9":{ + "type":"chest", + "skin":"tshirt9", + "manasteal":1, + "upgrade":{ + "manasteal":0.1, + }, + "name":"T-Shirt", + "grades":[0,6], + "g":120, + }, + "coat":{ + #"set":"base", + "tier":1, + "type":"chest", + "skin":"coat", + "scroll":True, + "upgrade":{ + }, + "name":"Coat", + "g":6000, + }, + "wattire":{ + "set":"wanderers", + "tier":1, + "type":"chest", + "skin":"wattire", + "mp":80, + "scroll":True, + "upgrade":{ + }, + "name":"Wanderer's Attire", + "g":12000, + }, + "xmassweater":{ + "set":"holidays", + "tier":1.5, + "type":"chest", + "skin":"xmassweater", + "evasion":0.5, + "scroll":True, + "upgrade":{ + "evasion":0.25, + }, + "explanation":"Such a beautiful vest. But for some reason, every time you wear this, people seem to avoid you.", + "name":"Xmas Sweater", + "g":16000, + "a":True, + }, + "sweaterhs":{ + "set":"holidays", + "tier":2.5, + "vit":12, + "speed":-1, + "mp":240, + "type":"chest", + "skin":"sweaterhs", + "scroll":True, + "upgrade":{ + + }, + "name":"Super Sweater", + "g":160000, + "a":True, + }, + "coat1":{ + "set":"rugged", + "tier":2, + "type":"chest", + "skin":"coat1", + "scroll":True, + "upgrade":{ + }, + "name":"Rugged Coat", + "g":48000, + "a":2, + }, + "mwarmor":{ + "class":["warrior"], + "set":"mwarrior", + "tier":2.625, + "type":"chest", + "skin":"mwarmor", + "scroll":True, + "upgrade":{ + }, + "name":"Armor of the Hunter Warrior", + "explanation":"You served our realm well", + "g":96000, + }, + "mmarmor":{ + "class":["mage"], + "set":"mmage", + "tier":2.125, + "type":"chest", + "skin":"mmarmor", + "scroll":True, + "upgrade":{ + }, + "name":"Armor of the Hunter Mage", + "explanation":"You served our realm well", + "g":96000, + }, + "mparmor":{ + "class":["priest"], + "set":"mpriest", + "tier":2.125, + "type":"chest", + "skin":"mparmor", + "scroll":True, + "upgrade":{ + }, + "name":"Armor of the Hunter Priest", + "explanation":"You served our realm well", + "g":96000, + }, + "mrnarmor":{ + "frequency":1, + "class":["ranger"], + "set":"mranger", + "tier":2.25, + "type":"chest", + "skin":"mrnarmor", + "scroll":True, + "upgrade":{ + }, + "name":"Armor of the Hunter Ranger", + "explanation":"You served our realm well", + "g":96000, + }, + "mrarmor":{ + "class":["rogue"], + "set":"mrogue", + "tier":2.25, + "type":"chest", + "skin":"mrarmor", + "scroll":True, + "upgrade":{ + }, + "name":"Armor of the Hunter Rogue", + "explanation":"You served our realm well", + "g":96000, + }, + "mcarmor":{ + "class":["merchant"], + "set":"mmerchant", + "tier":2.25, + "type":"chest", + "skin":"mcarmor", + "scroll":True, + "upgrade":{ + }, + "name":"Armor of the Hunter Merchant", + "explanation":"Your comrades served our realm well", + "g":96000, + }, + "harmor":{ + "set":"wt3", + "tier":3, + "type":"chest", + "skin":"harmor", + "scroll":True, + "upgrade":{ + }, + "name":"Heavy Armor", + "g":480000, + "a":2, + }, + "cdragon":{ + "type":"chest", + "skin":"dragonarmor", + "armor":40, + "resistance":32, + "str":10, + "int":10, + "dex":10, + "vit":2, + "apiercing":16, + "rpiercing":16, + "dreturn":3, + "name":"Dragon Armor", + "g":8900000, + "a":2, + "grades":[0,0], + }, + "oxhelmet":{ + "type":"helmet", + "skin":"oxhelmet", + "armor":55, + "resistance":12, + "str":10, + "int":10, + "dex":10, + "vit":2, + "output":1, + "firesistance":3, + "name":"OX Helmet", + "g":8900000, + "a":2, + "grades":[0,0], + }, + "xarmor":{ + "set":"wt4", + "tier":4, + "type":"chest", + "skin":"xarmor", + "scroll":True, + "upgrade":{ + }, + "name":"Darkforge Armor", + "g":4800000, + "a":2, + }, + "mcape":{ + "set":"vampires", + "tier":2, + "type":"chest", + "skin":"mcape", + "scroll":True, + "hp":160, + "lifesteal":1, + #"manaburn":10, + "upgrade":{ + "lifesteal":0.2, + #"manaburn":2, + "hp":30, + }, + "name":"Dracul's Attire", + "g":480000, + "a":2, + "grades":[0,6], + }, + "vattire":{ + "set":"vampires", + "tier":3, + "type":"chest", + "skin":"vattire", + "scroll":True, + "hp":1600, + "lifesteal":2, + #"manaburn":10, + "upgrade":{ + "lifesteal":0.2, + #"manaburn":2, + "hp":300, + }, + "name":"Spike's Attire", + "g":4800000, + }, + "warpvest":{ + "set":"legends", + "tier":3, + "extra_stat":0, + "type":"chest", + "skin":"warpvest", + "scroll":True, + #"manaburn":10, + "upgrade":{ + "int":0.64, + "str":0.64, + "dex":0.64, + "vit":0.64, + "for":1, + }, + "name":"Warp Vest", + "explanation":"Warps space-time. Ancient Computer unlocks only a fraction of it's capabilities. Needs to be recharged in order to initiate a jump.", + "ability":"warp", + "charge":1, + "g":36400000, + "a":2, + "edge":5, + "grades":[0,0,6,10], + }, + "pyjamas":{ + "tier":2, + "type":"chest", + "skin":"pyjamas", + "scroll":True, + "hp":400, + "charisma":-5, + #"manaburn":10, + "upgrade":{ + "hp":50, + }, + "name":"Legacy Pyjamas", + "g":480000, + "a":2, + "grades":[4,8], + "explanation":"Comfortable." + }, + "epyjamas":{ + "set":"bunny", + "tier":1.5, + "type":"chest", + "skin":"epyjamas", + "scroll":True, + "hp":400, + "charisma":-5, + #"manaburn":10, + "upgrade":{ + "hp":50, + }, + "name":"Pyjamas", + "g":48000, + "a":2, + "grades":[5,8], + "explanation":"Comfortable." + }, + "pants":{ + #"set":"base", + "tier":1, + "type":"pants", + "skin":"pants", + "scroll":True, + "upgrade":{ + }, + "name":"Pants", + "g":7800, + }, + "fallen":{ + "set":"fury", + "tier":1.5, + "type":"pants", + "class":["rogue","warrior"], + "skin":"fallen", + "scroll":True, + "dex":4, + "crit":2, + "frequency":6, + "speed":3, + "upgrade":{ + "crit":0.5, + }, + "name":"Pants of the Fallen Master", + "grades":[0,0,8,10], + "g":6400000, + "a":True, + }, + "wbreeches":{ + "set":"wanderers", + "tier":1, + "type":"pants", + "skin":"wbreeches", + "speed":1, + "scroll":True, + "upgrade":{ + }, + "name":"Wanderer's Breeches", + "g":15600, + }, + "xmaspants":{ + "set":"holidays", + "tier":1.5, + "type":"pants", + "skin":"xmaspants", + "vit":2, + "scroll":True, + "upgrade":{ + }, + "name":"Xmas Pants", + "g":17800, + "a":True, + }, + "pants1":{ + "set":"rugged", + "tier":2, + "type":"pants", + "skin":"pants1", + "scroll":True, + "upgrade":{ + }, + "name":"Rugged Pants", + "g":78000, + "a":2, + }, + "mwpants":{ + "class":["warrior"], + "set":"mwarrior", + "tier":2.625, + "type":"pants", + "skin":"mwpants", + "scroll":True, + "upgrade":{ + }, + "name":"Underarmor of the Hunter Warrior", + "explanation":"You served our realm well", + "g":128000, + }, + "mmpants":{ + "class":["mage"], + "set":"mmage", + "tier":2.125, + "type":"pants", + "skin":"mmpants", + "scroll":True, + "upgrade":{ + }, + "name":"Pants of the Hunter Mage", + "explanation":"You served our realm well", + "g":128000, + }, + "mmpants":{ + "class":["mage"], + "set":"mmage", + "tier":2.125, + "type":"pants", + "skin":"mmpants", + "scroll":True, + "upgrade":{ + }, + "name":"Pants of the Hunter Mage", + "explanation":"You served our realm well", + "g":128000, + }, + "mppants":{ + "class":["priest"], + "set":"mpriest", + "tier":2.125, + "type":"pants", + "skin":"mppants", + "scroll":True, + "upgrade":{ + }, + "name":"Pants of the Hunter Priest", + "explanation":"You served our realm well", + "g":128000, + }, + "mrnpants":{ + "class":["ranger"], + "set":"mranger", + "tier":2.25, + "type":"pants", + "skin":"mrnpants", + "scroll":True, + "upgrade":{ + }, + "name":"Pants of the Hunter Ranger", + "explanation":"You served our realm well", + "g":128000, + }, + "mrpants":{ + "class":["rogue"], + "set":"mrogue", + "tier":2.25, + "type":"pants", + "skin":"mrpants", + "scroll":True, + "upgrade":{ + }, + "name":"Pants of the Hunter Rogue", + "explanation":"You served our realm well", + "g":128000, + }, + "mcpants":{ + "class":["merchant"], + "set":"mmerchant", + "tier":2.25, + "type":"pants", + "skin":"mcpants", + "scroll":True, + "upgrade":{ + }, + "name":"Pants of the Hunter Merchant", + "explanation":"Your comrades served our realm well", + "g":128000, + }, + "starkillers":{ + "set":"legends", + "class":["mage","priest"], + "tier":3, + "extra_stat":0, + "type":"pants", + "skin":"starkillers", + "rpiercing":80, + "crit":2, + "vit":10, + "scroll":True, + "upgrade":{ + "rpiercing":5, + "crit":0.2, + }, + "legacy":{ + "class":None, + "set":None, + }, + "name":"Star Killer's Pants", + "g":7800000, + "a":2, + }, + "hpants":{ + "set":"wt3", + "tier":3, + "type":"pants", + "skin":"hpants", + "scroll":True, + "upgrade":{ + }, + "name":"Heavy Underarmor", + "g":780000, + "a":2, + }, + "frankypants":{ + "tier":3, + "type":"pants", + "skin":"frankypants", + "vit":6, + "speed":1, + "scroll":True, + "upgrade":{ + }, + "name":"Franky Pants", + "g":780000, + "a":2, + }, + "xpants":{ + "set":"wt4", + "tier":4, + "type":"pants", + "skin":"xpants", + "scroll":True, + "upgrade":{ + }, + "name":"Darkforge Underarmor", + "g":7800000, + "a":2, + }, + "shoes":{ + #"set":"base", + "tier":1, + "type":"shoes", + "skin":"shoes", + "scroll":True, + "upgrade":{ + }, + "name":"Shoes", + "g":12100, + }, + "wshoes":{ + "set":"wanderers", + "tier":1, + "type":"shoes", + "skin":"wshoes", + "scroll":True, + "upgrade":{ + }, + "name":"Wanderer's Shoes", + "g":24200, + }, + "iceskates":{ + "tier":2, + "type":"shoes", + "skin":"iceskates", + "scroll":True, + "speed":-10, + "winterland":{ + "speed":25, + "upgrade":{ + "speed":1, + }, + }, + "upgrade":{ + "speed":1, + }, + "name":"Ice Skates", + "g":920000, + }, + "snowboots":{ + "tier":2, + "type":"shoes", + "skin":"snowboots", + "scroll":True, + "fzresistance":10, + "upgrade":{ + "fzresistance":1, + }, + "name":"Snow Boots", + "g":720000, + }, + "eslippers":{ + "set":"bunny", + "tier":1.5, + "type":"shoes", + "skin":"eslippers", + "scroll":True, + "cuteness":24, + "upgrade":{ + "cuteness":2, + }, + "grades":[7,9], + "name":"Fluffy Slippers", + "g":24200, + }, + "wingedboots":{ + "set":"swift", + "tier":1.5, + "type":"shoes", + "skin":"wingedboots", + "frequency":3, + "speed":8, + "resistance":20, + "scroll":True, + "upgrade":{ + "frequency":0.625, + "speed":1, + }, + "name":"Winged Boots", + "g":150000, + "credit":"Pluet", + }, + "xmasshoes":{ + "set":"holidays", + "tier":1.5, + "type":"shoes", + "skin":"xmasshoes", + "vit":2, + "scroll":True, + "upgrade":{ + }, + "name":"Xmas Shoes", + "g":36000, + "a":True, + }, + "shoes1":{ + "set":"rugged", + "tier":2, + "type":"shoes", + "skin":"shoes1", + "scroll":True, + "upgrade":{ + }, + "name":"Rugged Shoes", + "g":120000, + "a":2, + }, + "mwboots":{ + "class":["warrior"], + "set":"mwarrior", + "tier":2.625, + "type":"shoes", + "skin":"mwboots", + "scroll":True, + "upgrade":{ + }, + "name":"Boots of the Hunter Warrior", + "explanation":"You served our realm well", + "g":240000, + }, + "mmshoes":{ + "class":["mage"], + "set":"mmage", + "tier":2.125, + "type":"shoes", + "skin":"mmshoes", + "scroll":True, + "upgrade":{ + }, + "name":"Shoes of the Hunter Mage", + "explanation":"You served our realm well", + "g":240000, + }, + "mpshoes":{ + "class":["priest"], + "set":"mpriest", + "tier":2.125, + "type":"shoes", + "skin":"mpshoes", + "scroll":True, + "upgrade":{ + }, + "name":"Shoes of the Hunter Priest", + "explanation":"You served our realm well", + "g":240000, + }, + "mrnboots":{ + "class":["ranger"], + "set":"mranger", + "tier":2.25, + "type":"shoes", + "skin":"mrnboots", + "scroll":True, + "upgrade":{ + }, + "name":"Boots of the Hunter Ranger", + "explanation":"You served our realm well", + "g":240000, + }, + "mrboots":{ + "class":["rogue"], + "set":"mrogue", + "tier":2.25, + "type":"shoes", + "skin":"mrboots", + "scroll":True, + "upgrade":{ + }, + "name":"Boots of the Hunter Rogue", + "explanation":"You served our realm well", + "g":240000, + }, + "mcboots":{ + "for":8, + "class":["merchant"], + "set":"mmerchant", + "tier":2.75, + "type":"shoes", + "skin":"mcboots", + "scroll":True, + "upgrade":{ + }, + "name":"Boots of the Hunter Merchant", + "explanation":"Your comrades served our realm well", + "g":240000, + }, + "hboots":{ + "set":"wt3", + "tier":3, + "type":"shoes", + "skin":"hboots", + "scroll":True, + "upgrade":{ + }, + "name":"Heavy Boots", + "g":1240000, + "a":2, + }, + "xboots":{ + "set":"wt4", + "tier":4, + "type":"shoes", + "skin":"xboots", + "scroll":True, + "upgrade":{ + }, + "name":"Darkforge Boots", + "g":12400000, + "a":2, + }, + "gloves":{ + #"set":"base", + "tier":1, + "type":"gloves", + "skin":"gloves", + "scroll":True, + "upgrade":{ + }, + "name":"Gloves", + "g":3400, + }, + "vgloves":{ + "set":"vampires", + "int":3, + "str":3, + "fzresistance":4, + "tier":3, + "type":"gloves", + "skin":"vgloves", + "scroll":True, + "upgrade":{ + }, + "name":"Vampiric Gloves", + "g":340000, + }, + "vboots":{ + "set":"vampires", + "dex":3, + "str":3, + "firesistance":8, + "tier":3, + "type":"shoes", + "skin":"vboots", + "scroll":True, + "upgrade":{ + }, + "name":"Vampiric Boots", + "g":340000, + }, + "vcape":{ + "set":"vampires", + "tier":4, + "type":"cape", + "skin":"vcape", + "scroll":True, + "upgrade":{ + }, + "name":"Vampiric Cape", + "g":340000, + }, + "fierygloves":{ + "set":"swift", + "tier":1.5, + "type":"gloves", + "skin":"fierygloves", + "scroll":True, + "frequency":2, + "upgrade":{ + "frequency":0.125, + }, + "grades":[0,7], + "name":"Fiery Gloves", + "g":144000, + }, + "wgloves":{ + "set":"wanderers", + "tier":1, + "type":"gloves", + "skin":"wgloves", + "scroll":True, + "upgrade":{ + }, + "name":"Wanderer's Gloves", + "g":6800, + }, + "mittens":{ + "set":"holidays", + "tier":1.5, + "type":"gloves", + "skin":"mittens", + "apiercing":20, + "rpiercing":20, + "scroll":True, + "upgrade":{ + "apiercing":2, + "rpiercing":2, + }, + "name":"Mittens", + "explanation":"Cute but deadly.", + "g":34000, + "a":True, + }, + "supermittens":{ + "set":"holidays", + "tier":2, + "extra_stat":0, + "type":"gloves", + "skin":"supermittens", + "apiercing":32, + "rpiercing":32, + "frequency":2, + "scroll":True, + "upgrade":{ + "apiercing":3, + "rpiercing":3, + "frequency":0.2, + }, + "name":"Super Mittens", + "explanation":"Swift and lethal!", + "g":340000, + "a":True, + "grades":[0,0], + }, + "powerglove":{ + "set":"legends", + "tier":2, + "extra_stat":0, + "type":"gloves", + "skin":"powerglove", + "apiercing":16, + "rpiercing":16, + "frequency":2, + "scroll":True, + "upgrade":{ + "apiercing":2, + "rpiercing":2, + "frequency":0.2, + }, + "ability":"power", + "charge":120, + "name":"Power Glove", + "g":1600000, + "a":True, + "grades":[0,0], + }, + "goldenpowerglove":{ + "set":"legends", + "tier":4, + "extra_stat":1, + "type":"gloves", + "skin":"goldenpowerglove", + "apiercing":64, + "rpiercing":64, + "stat":6, + "frequency":5, + "scroll":True, + "upgrade":{ + "apiercing":4, + "rpiercing":4, + "frequency":0.2, + }, + "ability":"xpower", + "charge":90, + "name":"Golden Power Glove", + "g":16000000, + "a":True, + "grades":[0,0], + }, + "handofmidas":{ + "tier":3.5, + "type":"gloves", + "skin":"goldglove", + "speed":-20, + "gold":10, + "upgrade":{ + "gold":1, + }, + "name":"Hand of Midas", + "explanation":"You can feel the thirst for gold move through your veins.", + "grades":[0,0], + "g":800000, + "a":True, + }, + "poker":{ + "tier":1.5, + "type":"gloves", + "skin":"poker", + "crit":0.5, + "ability":"poke", + "scroll":True, + "upgrade":{ + }, + "name":"Poker", + "explanation":"Pokey pokey!", + #"action":"POKE!", + #"onclick":"socket.emit('poke',{name:(ctarget||character).name})", + "g":16000, + "a":True, + }, + "gloves1":{ + "set":"rugged", + "tier":2, + "type":"gloves", + "skin":"gloves1", + "scroll":True, + "upgrade":{ + }, + "name":"Rugged Gloves", + "g":34000, + "a":2, + }, + "mpxgloves":{ + "set":"mpx", + "tier":2, + "type":"gloves", + "skin":"mpxgloves", + "ability":"restore_mp", + "attr0":2, + "scroll":True, + "upgrade":{ + "attr0":0.5, + }, + "name":"Mana Gloves", + "explanation":"The powers of this glove grow fivefold against humanoids!", + "grades":[0,0,9], + "g":34000000, + }, + "mwgloves":{ + "crit":1, + "class":["warrior"], + "set":"mwarrior", + "tier":2.625, + "type":"gloves", + "skin":"mwgloves", + "scroll":True, + "upgrade":{ + }, + "name":"Gloves of the Hunter Warrior", + "explanation":"You served our realm well", + "g":68000, + }, + "mmgloves":{ + "class":["mage"], + "set":"mmage", + "tier":2.125, + "type":"gloves", + "skin":"mmgloves", + "scroll":True, + "upgrade":{ + }, + "name":"Gloves of the Hunter Mage", + "explanation":"You served our realm well", + "g":68000, + }, + "mpgloves":{ + "output":5, + "class":["priest"], + "set":"mpriest", + "tier":2.125, + "type":"gloves", + "skin":"mpgloves", + "scroll":True, + "upgrade":{ + }, + "name":"Gloves of the Hunter Priest", + "explanation":"You served our realm well", + "g":68000, + }, + "mrngloves":{ + "class":["ranger"], + "set":"mranger", + "tier":2.25, + "type":"gloves", + "skin":"mrngloves", + "scroll":True, + "upgrade":{ + }, + "name":"Gloves of the Hunter Ranger", + "explanation":"You served our realm well", + "g":68000, + }, + "mrgloves":{ + "class":["rogue"], + "set":"mrogue", + "tier":2.25, + "type":"gloves", + "skin":"mrgloves", + "scroll":True, + "upgrade":{ + }, + "name":"Gloves of the Hunter Rogue", + "explanation":"You served our realm well", + "g":68000, + }, + "mcgloves":{ + "gold":5, + "class":["merchant"], + "set":"mmerchant", + "tier":2.25, + "type":"gloves", + "skin":"mcgloves", + "scroll":True, + "upgrade":{ + }, + "name":"Gloves of the Hunter Merchant", + "explanation":"Your comrades served our realm well", + "g":68000, + }, + "hgloves":{ + "set":"wt3", + "tier":3, + "type":"gloves", + "skin":"hgloves", + "scroll":True, + "upgrade":{ + }, + "name":"Heavy Gloves", + "g":340000, + "a":2, + }, + "xgloves":{ + "set":"wt4", + "tier":4, + "type":"gloves", + "skin":"xgloves", + "scroll":True, + "upgrade":{ + }, + "name":"Darkforge Gloves", + "g":3400000, + "a":2, + } +} +for name in armor.keys(): + #import logging; logging.info(name) + current=armor[name] + if not current.get("tier",0): continue + tier=current["tier"] + ftier=int(math.floor(tier)) + ctier=int(math.ceil(tier)) + #armor_gains=[0,1.25,2.5,4.25,5.5] + #res_gains=[0,1.25,2.5,4.25,5.5] + armor_gains=[0,0.5,2.5,5.5,7.5] + res_gains=[0,0.5,2.5,5.5,7.5] + xtier=([0.5,0.5,2,3.4,4.5,6][ftier]+[0.5,0.5,2,4,5,6][ctier]+tier)/3.0 + #if not current.has_key("edge") and tier>1: current["edge"]=(tier-1)*2 + if tier<=1.25 and not current.has_key("grades"): current["grades"]=[7,9] + elif tier<=1.5 and not current.has_key("grades"): current["grades"]=[4,8] + elif tier<=2.4 and not current.has_key("grades"): current["grades"]=[0,7] + elif tier<=2.75 and not current.has_key("grades"): current["grades"]=[0,5] + elif not current.has_key("grades"): current["grades"]=[0,0] + if len(current["grades"])==2: + current["grades"].append(10); current["grades"].append(12) + if tier>=4: + current["grades"][2]=8 + current["grades"][3]=10 + elif tier>=3: + current["grades"][2]=9 + current["grades"][3]=10 + if current.get("scroll"): + if not current.get("stat"): + current["stat"]=1 + current["upgrade"]["stat"]=1 + if current.get("extra_stat",-1)==-1 and tier>=2: + current["extra_stat"]=min(ftier,4)-1 + current["stat"]+=min(ftier,4)-1 + if current["type"]=="chest": + current["armor"]=xtier*12 + current["resistance"]=xtier*8 + if current["type"]=="helmet": + current["armor"]=xtier*7 + current["resistance"]=xtier*8 + if current["resistance"]>=15: + current["protection"]=True + if current["type"]=="pants": + current["armor"]=xtier*10 + current["resistance"]=xtier*6 + if current["type"]=="shoes": + current["armor"]=xtier*4 + if not current.get("speed"): + current["speed"]=round(4+tier*1) + current["upgrade"]["speed"]=0.375+tier/4.0 + if current["type"]=="gloves": + current["armor"]=xtier*8 + current["resistance"]=xtier*4 + if current.get("resistance"): + current["upgrade"]["resistance"]=(res_gains[int(math.floor(tier))]+res_gains[int(math.ceil(tier))])/2.0 + if current.get("armor"): + current["upgrade"]["armor"]=(armor_gains[int(math.floor(tier))]+armor_gains[int(math.ceil(tier))])/2.0 + if current["type"]=="shoes" and tier>2: + current["resistance"]=tier*2 + current["upgrade"]["resistance"]=(res_gains[int(math.floor(tier))]+res_gains[int(math.ceil(tier))])/4.0 + if current.get("armor"): current["armor"]=int(math.ceil(current["armor"])) + if current.get("resistance"): current["resistance"]=int(math.ceil(current["resistance"])) + +#for(var i=0;i<42;i++) if(player.items[i] && player.items[i].level) player.items[i].level=8 + +accessories={ + "amuletofm":{ + "type":"amulet", + "skin":"amuletofm", + "evasion":2, + "reflection":0.5, + "manasteal":0.5, + "crit":2, + "int":6, + "str":4, + "dex":3, + "hp":400, + "armor":10, + "dreturn":1, + "compound":{ + "evasion":2, + "crit":1, + "dreturn":0.75, + "int":1, + "str":1, + "dex":1, + "hp":120, + "armor":2, + }, + "name":"Amulet of Mystery", + "grades":[0,0], + "g":6400000, + "a":True, + }, + "northstar":{ + "type":"amulet", + "skin":"northstar", + "xp":10, + "compound":{ + "xp":5, + }, + "name":"The North Star", + "grades":[0,0], + "g":64000000, + "a":True, + }, + "bfangamulet":{ + "type":"amulet", + "skin":"bfangamulet", + "lifesteal":2, + "critdamage":4, + "apiercing":20, + "compound":{ + "lifesteal":1, + "critdamage":4, + "apiercing":20, + }, + "name":"Ghastly Bat Fang", + "grades":[0,0], + "g":6400000, + "a":True, + }, + "mpxamulet":{ + "set":"mpx", + "type":"amulet", + "skin":"mpxamulet", + "mp_cost":-5, + "mp_reduction":12, + "compound":{ + "mp_cost":-2, + "mp_reduction":2, + }, + "name":"Amulet of MP", + "grades":[0,0], + "g":56000000, + "a":True, + }, + "suckerpunch":{ + "set":"fury", + "type":"ring", + "skin":"suckerpunch", + "crit":2, + "apiercing":20, + "lifesteal":2, + "compound":{ + "apiercing":20, + "crit":1, + "lifesteal":1, + }, + "name":"Sucker Punch", + "g":3200000, + "grades":[0,0], + "a":True, + }, + "vring":{ + "set":"vampires", + "type":"ring", + "skin":"vring", + "str":12, + "dreturn":9, + "lifesteal":6, + "vit":6, + "armor":10, + "pnresistance":4, + "courage":1, + "compound":{ + "str":4, + }, + "name":"Vampiring", + "g":4200000, + "grades":[0,0], + "a":True, + }, + "trigger":{ + "type":"ring", + "skin":"trigger", + "stun":1.5, + "str":6, + "apiercing":10, + "compound":{ + "stun":0.75, + "str":2, + "apiercing":2, + }, + "name":"The Trigger", + "g":6400000, + "grades":[0,0,1,3], + "a":True, + }, + "zapper":{ + "type":"ring", + "skin":"trigger", + "rpiercing":10, + "int":10, + "str":5, + "resistance":30, + "compound":{ + "int":3, + "rpiercing":4, + }, + "name":"The Zapper", + "ability":"zapperzap", + "g":6400000, + "grades":[0,0,1,3], + "a":True, + }, + # "supermagicalring":{ + # "type":"ring", + # "skin":"supermagicalring", + # "armor":20, + # "compound":{ + # "armor":6, + # "dreturn":0.125, + # }, + # "name":"Ring of Armor", + # "g":1200000, + # "a":True, + # }, + "goldring":{ + "type":"ring", + "skin":"goldenring", + "gold":4, + "compound":{ + "gold":2, + }, + "name":"Ring of Gold", + "grades":[0,2], + "g":28000000, + "a":True, + }, + "armorring":{ + "type":"ring", + "skin":"armorring", + "armor":24, + "compound":{ + "armor":9, + "dreturn":0.250, + }, + "name":"Ring of Armor", + "grades":[1,4], + "g":180000, + "a":True, + }, + "resistancering":{ + "type":"ring", + "skin":"resistancering", + "resistance":24, + "compound":{ + "resistance":9, + "reflection":0.125, + }, + "name":"Ring of Resistance", + "grades":[1,4], + "g":180000, + "a":True, + }, + "ringofluck":{ + "type":"ring", + "skin":"ringofluck", + "luck":10, + "compound":{ + "luck":5, + }, + "name":"Ring of Luck", + "g":6400000, + "grades":[0,0], + "a":True, + }, + "ringhs":{ + "set":"holidays", + "type":"ring", + "skin":"ringhs", + "luck":8, + "str":4, + "int":4, + "dex":4, + "vit":10, + "ability":"secondchance", + "attr0":3, + "compound":{ + "luck":3, + "vit":5, + }, + "name":"Ring of Holidays", + "g":6400000, + "grades":[0,0], + "a":True, + }, + "molesteeth":{ + "type":"earring", + "skin":"molesteeth", + "apiercing":15, + "compound":{ + "apiercing":15, + }, + "name":"Mole's Teeth", + "g":500000, + "grades":[0,1], + "a":True, + }, + "mearring":{ + "set":"holidays", + "type":"earring", + "skin":"mearring", + "luck":8, + "compound":{ + "luck":1, + }, + "name":"Mistletoe Earring", + "g":12000000, + "grades":[0,0], + "a":True, + }, + "tristone":{ + "type":"ring", + "skin":"tristone", + "skin_a":"tristone_a", + "apiercing":5, + "rpiercing":5, + "int":1, + "str":1, + "dex":1, + "vit":1, + "compound":{ + "apiercing":5, + "rpiercing":5, + "int":1, + "str":1, + "dex":1, + "vit":1, + }, + "name":"Legacy Tri-Stone", + "ignore":True, + "g":50000, + "grades":[1,4], + "action":"ACTIVATE!", + "onclick":"socket.emit('activate',{slot:$(this).data('id')})" + }, + "ctristone":{ + "type":"ring", + "skin":"tristone", + "apiercing":5, + "rpiercing":5, + "int":1, + "str":1, + "dex":1, + "vit":1, + "compound":{ + "apiercing":5, + "rpiercing":5, + "int":1, + "str":1, + "dex":1, + "vit":1, + }, + "name":"Tri-Stone", + "g":50000, + "grades":[1,4], + }, + "darktristone":{ + "type":"ring", + "skin":"darktristone", + "skin_a":"darktristone_a", + "apiercing":5, + "rpiercing":5, + "int":1, + "str":1, + "dex":1, + "vit":1, + "evasion":3, + "compound":{ + "apiercing":5, + "rpiercing":5, + "int":1, + "str":1, + "dex":1, + "vit":1, + }, + "name":"Legacy Dark Tri-Stone", + "ignore":True, + "g":50000, + "grades":[1,4], + "action":"ACTIVATE!", + "onclick":"socket.emit('activate',{slot:$(this).data('id')})" + }, + "cdarktristone":{ + "type":"ring", + "skin":"darktristone", + "apiercing":5, + "rpiercing":5, + "int":1, + "str":1, + "dex":1, + "vit":1, + "evasion":3, + "compound":{ + "apiercing":5, + "rpiercing":5, + "int":1, + "str":1, + "dex":1, + "vit":1, + }, + "name":"Dark Tri-Stone", + "g":50000, + "grades":[1,4], + }, + "skullamulet":{ + "type":"amulet", + "skin":"skullamulet", + "hp":200, + "armor":10, + "for":4, + "str":1, + "int":1, + "dex":1, + "compound":{ + "armor":5, + "for":1, + "hp":320, + "str":1, + "int":1, + "dex":1, + }, + "name":"Skull Amulet", + "grades":[2,4], + "g":30000, + "a":True, + }, + "spookyamulet":{ + "type":"amulet", + "skin":"spookyamulet", + "name":"Amulet of Spooks", + "reflection":2, + "evasion":5, + "xp":2, + "gold":2, + "luck":2, + "g":320000, + "a":True, + }, + "hpamulet":{ + "type":"amulet", + "skin":"hpamulet", + "hp":200, + "compound":{ + "hp":240, + }, + "name":"Amulet of HP", + "g":20000, + }, + "snring":{ + "type":"amulet", + "skin":"snring", + "str":14, + "dex":2, + "armor":20, + "compound":{ + "str":2, + "dex":1, + "armor":5, + }, + "name":"Stompy's Nose Ring", + "g":2400000, + "grades":[0,0], + }, + "sanguine":{ + "type":"amulet", + "skin":"sanguine", + "dex":5, + "int":5, + "str":5, + "attr0":1, + "hp":1200, + "aura":"sanguine", + "compound":{ + "attr0":0.5, + "str":1, + "int":1, + "dex":1, + "hp":300, + }, + "name":"Sanguine Amulet", + "grades":[0,0], + "g":32000000, + }, + "dexamulet":{ + "type":"amulet", + "skin":"dexamulet", + "dex":4, + "compound":{ + "dex":3, + }, + "name":"Amulet of Dexterity", + "g":30000, + }, + "stramulet":{ + "type":"amulet", + "skin":"stramulet", + "str":4, + "compound":{ + "str":2, + }, + "name":"Amulet of Strength", + "g":30000, + }, + "intamulet":{ + "type":"amulet", + "skin":"intamulet", + "int":4, + "compound":{ + "int":3, + }, + "name":"Amulet of Intelligence", + "g":30000, + }, + "t2stramulet":{ + "type":"amulet", + "skin":"t2stramulet", + "str":5, + "resistance":30, + "compound":{ + "str":3, + "resistance":20, + }, + "name":"Amulet of the Eager Warrior", + "g":160000, + "edge":-1, + "grades":[0,2], + }, + "t2intamulet":{ + "type":"amulet", + "skin":"t2intamulet", + "int":5, + "armor":30, + "compound":{ + "int":2, + "armor":20, + }, + "name":"Amulet of the Fierce Mage", + "g":160000, + "edge":-1, + "grades":[0,2], + }, + "t2dexamulet":{ + "type":"amulet", + "skin":"t2dexamulet", + "dex":6, + "vit":5, + "compound":{ + "dex":3, + "vit":3, + }, + "name":"Amulet of the Stubborn Ranger", + "g":160000, + "edge":-1, + "grades":[0,2], + }, + "warmscarf":{ + "type":"amulet", + "skin":"warmscarf", + "armor":10, + "resistance":10, + "int":2, + "str":2, + "dex":2, + "apiercing":5, + "rpiercing":5, + "upgrade":{ + "apiercing":1.25, + "rpiercing":1.25, + }, + "name":"Warm Scarf", + "explanation":"Stylish and deadly!", + "g":20000, + "a":True, + "grades":[7,9], + }, + "hpbelt":{ + "type":"belt", + "skin":"hpbelt", + "hp":160, + "compound":{ + "hp":240, + }, + "name":"Belt of HP", + "g":20000, + }, + "mpxbelt":{ + "set":"mpx", + "type":"belt", + "skin":"mpxbelt", + "mp_cost":-5, + "mp_reduction":10, + "compound":{ + "mp_cost":-1, + "mp_reduction":5, + }, + "name":"Belt of MP Reduction", + "grades":[0,0], + "g":1200000, + }, + "lbelt":{ + "type":"belt", + "skin":"lbelt", + "speed":1, + "armor":15, + "compound":{ + "speed":1.10, + "armor":5, + }, + "name":"Belt", + "explanation":"A belt that can actually hold your pants in place!", + "g":40000, + }, + "strbelt":{ + "type":"belt", + "skin":"strbelt", + "str":4, + "compound":{ + "str":3, + }, + "name":"Belt of Strength", + "g":50000, + "grades":[2,5], + }, + "mbelt":{ + "type":"belt", + "skin":"mbelt", + "int":8, + "dex":8, + "speed":1, + "armor":15, + "compound":{ + "speed":1.10, + "armor":10, + }, + "a":True, + "name":"Well-Crafted Belt", + "g":640000, + "grades":[0,1], + }, + "sbelt":{ + "type":"belt", + "skin":"sbelt", + "for":12, + "int":8, + "dex":8, + "str":8, + "resistance":15, + "armor":15, + "compound":{ + "int":2, + "dex":2, + "str":2, + "resistance":10, + "armor":10, + }, + "a":True, + "name":"Belt of Hallowed Trials", + "g":640000, + "grades":[0,1], + }, + "santasbelt":{ + "set":"holidays", + "type":"belt", + "skin":"santasbelt", + "evasion":4, + "dex":3, + "compound":{ + "dex":2, + }, + "a":True, + "name":"Santa's Belt", + "g":640000, + "grades":[0,3], + }, + "dexbelt":{ + "type":"belt", + "skin":"dexbelt", + "dex":4, + "compound":{ + "dex":3, + }, + "name":"Belt of Dexterity", + "g":50000, + "grades":[2,5], + }, + "intbelt":{ + "type":"belt", + "skin":"intbelt", + "int":4, + "compound":{ + "int":3, + }, + "name":"Belt of Intelligence", + "g":50000, + "grades":[2,5], + }, + "ringsj":{ + "type":"ring", + "skin":"ring", + "int":1, + "str":1, + "dex":1, + "resistance":5, + "compound":{ + "int":1, + "str":1, + "dex":1, + "resistance":5, + }, + "name":"Ring of Small Joys", + "g":24000, + }, + "solitaire":{ + "type":"ring", + "skin":"solitaire", + "bling":10, + "compound":{ + "bling":30, + }, + "name":"Solitaire Ring", + "explanation":"The diamond is mesmerizing", + "g":1200000, + "grades":[0,0], + "event":True, + }, + "vitring":{ + "type":"ring", + "skin":"vitring", + "vit":2, + "compound":{ + "vit":2, + }, + "name":"Ring of Vitality", + "g":24000, + }, + "strring":{ + "type":"ring", + "skin":"strring", + "str":2, + "compound":{ + "str":2, + }, + "name":"Ring of Strength", + "g":24000, + }, + "intring":{ + "type":"ring", + "skin":"intring", + "int":2, + "compound":{ + "int":2, + }, + "name":"Ring of Intelligence", + "g":24000, + }, + "dexring":{ + "type":"ring", + "skin":"dexring", + "dex":2, + "compound":{ + "dex":2, + }, + "name":"Ring of Dexterity", + "g":24000, + }, + "cring":{ + "type":"ring", + "skin":"cring", + "dex":4, + "int":4, + "compound":{ + "dex":2, + "int":2, + }, + "edge":-2, + "name":"Ring of The Crypt", + "g":240000, + "grades":[0,4], + }, + "cearring":{ + "type":"earring", + "skin":"cearring", + "str":5, + "int":5, + "compound":{ + "str":2, + "int":2, + }, + "edge":-2, + "name":"Earring of The Crypt", + "g":380000, + "grades":[0,4], + }, + "intearring":{ + "type":"earring", + "skin":"intearring", + "int":3, + "compound":{ + "int":2, + }, + "name":"Earring of Intelligence", + "g":38000, + "grades":[2,5], + }, + "strearring":{ + "type":"earring", + "skin":"strearring", + "str":3, + "compound":{ + "str":2, + }, + "name":"Earring of Strength", + "g":38000, + "grades":[2,5], + }, + "dexearring":{ + "type":"earring", + "skin":"dexearring", + "dex":3, + "compound":{ + "dex":2, + }, + "name":"Earring of Dexterity", + "g":38000, + "grades":[2,5], + }, + "dexearringx":{ + "type":"earring", + "skin":"dexearringx", + "dex":6, + "luck":2, + "speed":1, + "compound":{ + "dex":2, + "luck":2, + }, + "name":"Enchanted Earring", + "g":38000, + "grades":[0,2], + }, + "vitearring":{ + "type":"earring", + "skin":"vitearring", + "vit":3, + "compound":{ + "vit":2, + }, + "name":"Earring of Vitality", + "g":38000, + "grades":[2,5], + }, +} + +for name in accessories.keys(): + current=accessories[name] + if not current.has_key("grades"): current["grades"]=[3,5] + +#Ring of Mage PVP: 30 Armor, 10 Res. Piercing, 120HP +#Ring of Warrior PVP: 20 Res, 10 Armor, 10 Armor. Piercing + +weapons={ + "claw":{ + "type":"weapon", + "wtype":"fist", + "tier":1, + "skin":"claw", + "damage_type":"physical", + "upgrade":{ + }, + "name":"Claw", + "g":7200, + }, + "cclaw":{ + "type":"weapon", + "wtype":"fist", + "tier":1.5, + "skin":"cclaw", + "apiercing":20, + "damage_type":"physical", + "upgrade":{ + "apiercing":4, + }, + "name":"Crab Claw", + "g":9600, + }, + "throwingstars":{ + "type":"weapon", + "wtype":"stars", + "tier":1, + "skin":"throwingstars", + "damage_type":"physical", + "upgrade":{ + }, + "name":"Throwing Stars", + "g":72000, + }, + "snowflakes":{ + "type":"weapon", + "wtype":"stars", + "tier":2, + "ability":"freeze", + "attr0":1, + "skin":"snowflakes", + "skin_r":"snowflakes_r", + "damage_type":"physical", + "upgrade":{ + "attr0":1, + }, + "name":"Snowflakes", + "g":92000, + }, + "firestars":{ + "type":"weapon", + "wtype":"stars", + "tier":2.5, + "skin":"firestars", + "skin_r":"firestars_r", + "damage_type":"physical", + "ability":"burn", + "attr0":1.5, + "upgrade":{ + "attr0":0.5, + }, + "name":"Fiery Throwing Stars", + "g":290000, + }, + "fclaw":{ + "type":"weapon", + "wtype":"fist", + "tier":2, + "skin":"fclaw", + "skin_r":"fclaw_r", + "damage_type":"physical", + "ability":"freeze", + "attr0":0.2, + "int":8, + "upgrade":{ + "attr0":0.1, + }, + "name":"Frozen Claw", + "g":72000, + "a":True, + "grades":[0,7], + }, + "stinger":{ + "type":"weapon", + "wtype":"dagger", + "tier":1.4, + "str":12, + "skin":"stinger", + "damage_type":"physical", + "upgrade":{ + }, + "name":"Stinger", + "g":16000, + "cx":{"accent":"#96783E"}, + }, + "dagger":{ + "type":"weapon", + "wtype":"dagger", + "tier":2, + "skin":"dagger", + "damage_type":"physical", + "upgrade":{ + }, + "name":"Dagger", + "g":167000, + "a":True, + "cx":{"accent":"#3B9A5C"}, + }, + "daggerofthedead":{ + "type":"weapon", + "wtype":"dagger", + "tier":2.4, + "skin":"daggerofthedead", + "vit":-6, + "speed":-2, + "apiercing":20, + "str":20, + "damage_type":"physical", + "upgrade":{ + }, + "name":"Dagger of the Dead", + "explanation":"A deadly weapon", + "g":224000, + "a":True, + "grades":[0,6], + "cx":{"accent":"#D87F0E"}, + }, + "dragondagger":{ + "type":"weapon", + "wtype":"dagger", + "tier":3, + "skin":"dragondagger", + "range":4, + "armor":40, + "str":20, + "damage_type":"physical", + "upgrade":{ + "armor":4, + }, + "name":"Dragon Dagger", + "g":2400000, + "a":True, + "grades":[0,0], + "explanation":"Majestic", + "cx":{"accent":"#D19FDA"}, + }, + "hdagger":{ + "type":"weapon", + "wtype":"dagger", + "tier":3, + "class":["rogue"], + "skin":"hdagger", + "firesistance":15, + "range":4, + "damage_type":"physical", + "upgrade":{ + }, + "name":"Dagger of Hallowing", + "g":2400000, + "a":True, + "grades":[0,0], + "cx":{"accent":"#847ADA"}, + }, + "dartgun":{ + "type":"weapon", + "wtype":"dartgun", + "tier":3, + "skin":"dartgun", + "damage_type":"physical", + "upgrade":{ + }, + "projectile": "stone", + "name":"Golden Dart Gun", + "explanation":"Don't let the looks fool you. It's a solid weapon with most components forged from gold. The barrel and trigger mechanism is a platinum alloy. Can shoot anything that fits it's barrel, like actual gold.", + "g":20000000, + "grades":[0,0], + "cx":{ + "scale":0.5, + "extension":True, + }, + }, + "rod":{ + "type":"tool", + "wtype":"rod", + "tier":1, + "skin":"rod", + "name":"Fishing Rod", + "breaks":1, + "g":2000, + "upgrade":{ + "breaks":-0.064, + }, + }, + "pickaxe":{ + "type":"tool", + "wtype":"pickaxe", + "tier":1, + "skin":"pickaxe", + "name":"Pickaxe", + "breaks":1, + "g":2000, + "upgrade":{ + "breaks":-0.064, + }, + }, + "bow":{ + "type":"weapon", + "wtype":"bow", + "skin":"bow", + "tier":1, + "damage_type":"physical", + "upgrade":{ + }, + "name":"Bow", + "g":16000, + "cx":{"accent":"#AF2131"}, + }, + "pouchbow":{ + "type":"weapon", + "wtype":"bow", + "skin":"pouchbow", + "tier":0.2, + "explosion":10, + "mp_reduction":-10, + "projectile":"pouch", + "damage_type":"physical", + "upgrade":{ + "explosion":2, + }, + "name":"Poucher", + "g":24000, + "cx":{"accent":"#9D7B1B"}, + }, + "weaver":{ + "type":"weapon", + "wtype":"bow", + "skin":"weaver", + "tier":1.75, + "ability":"weave", + "attr0":4, + "attr1":1, + "damage_type":"physical", + "upgrade":{ + "attr0":2, + "attr1":0.2, + }, + "name":"Bow of the Weaver", + "g":36000, + "cx":{"accent":"#AF2131"}, + }, + "crossbow":{ + "type":"weapon", + "wtype":"crossbow", + "skin":"crossbow", + "tier":2, + "damage_type":"physical", + "upgrade":{ + }, + "name":"Crossbow", + "g":480000, + "projectile":"crossbowarrow", + }, + "hbow":{ + "type":"weapon", + "wtype":"bow", + "skin":"hbow", + "tier":1.5, + "range":20, + "apiercing":40, + "damage_type":"physical", + "upgrade":{ + "apiercing":5 + }, + "name":"Hunting Bow", + "g":16000, + "cx":{"accent":"#8B7FD6"}, + }, + "merry":{ + "set":"holidays", + "type":"weapon", + "wtype":"bow", + "skin":"merry", + "ability":"secondchance", + "attr0":10, + "tier":1.5, + "damage_type":"physical", + "upgrade":{ + "attr0":2, + }, + "name":"Bow of The Merry Ranger", + "g":124000, + "grades":[0,8], + "cx":{"accent":"#289E4D"}, + }, + "cupid":{ + "type":"weapon", + "wtype":"bow", + "skin":"cupid", + "projectile":"cupid", + "tier":2.5, + "range":-20, + "vit":10, + "damage_type":"heal", + "upgrade":{ + "vit":2, + }, + "grades":[0,6], + "name":"Cupid's Bow", + "g":90000, + "a":True, + "event":True, + "cx":{ + "accent":"#DB2A86", + #"large":True, + } + }, + "firebow":{ + "type":"weapon", + "wtype":"bow", + "skin":"firebow", + "skin_r":"firebow_r", + "projectile":"firearrow", + "tier":2, + "range":-20, + "damage_type":"physical", + "ability":"burn", + "attr0":2, + "upgrade":{ + "attr0":0.5, + }, + "name":"Fire Bow", + "explanation":"Rains fire upon the enemy", + "g":178000, + "grades":[0,7], + "a":True, + "cx":{"accent":"#E34C25"}, + #"cx":{"accent":"#D3001E"}, + }, + "frostbow":{ + "type":"weapon", + "wtype":"bow", + "skin":"frostbow", + "skin_r":"frostbow_r", + "projectile":"frostarrow", + "tier":2, + "damage_type":"physical", + "ability":"freeze", + "attr0":2, + "upgrade":{ + "attr0":0.5, + }, + "name":"Frost Bow", + "explanation":"Let your enemy feel the cold", + "g":78000, + "grades":[0,7], + "a":True, + "cx":{"accent":"#2D9DE5"}, + }, + "t2bow":{ + "type":"weapon", + "wtype":"bow", + "skin":"t2bow", + "tier":2, + "damage_type":"physical", + "upgrade":{ + }, + "name":"Well-Crafted Bow", + "explanation":"Crafted with the finest of materials", + "g":78000, + "grades":[0,7], + "a":True, + "cx":{"accent":"#CD3F3B"}, + }, + "harpybow":{ + "type":"weapon", + "wtype":"bow", + "tier":3, + "speed":2, + "evasion":5, + "skin":"t3bow", + "damage_type":"physical", + "upgrade":{ + }, + "name":"Harpy Bow", + "explanation":"A bow decorated with exclusive Harpy feathers!", + "g":780000, + "a":True, + "cx":{"accent":"#DE6F22"}, + }, + "t3bow":{ + "type":"weapon", + "wtype":"bow", + "tier":3, + "skin":"t3bow", + "damage_type":"physical", + "critdamage":12, + "upgrade":{ + }, + "name":"Artisan's Bow", + "explanation":"Crafted by the finest of bowmasters", + "g":780000, + "a":True, + "cx":{"accent":"#DE6F22"}, + }, + "bowofthedead":{ + "type":"weapon", + "wtype":"bow", + "skin":"bowofthedead", + "tier":2.4, + "crit":1, + "str":20, + "vit":-2, + "speed":-12, + "range":-10, + "damage_type":"physical", + "upgrade":{ + "crit":0.2, + }, + "name":"Bow of the Dead", + "explanation":"A weapon of death", + "g":228000, + "a":True, + "cx":{"accent":"#D87F0E"}, + }, + "gbow":{ + "type":"weapon", + "wtype":"bow", + "skin":"gbow", + "projectile":"garrow", + "tier":2.5, + "str":3, + "damage_type":"physical", + "upgrade":{ + }, + "name":"Bow of the Feared Ranger", + "g":3200000, + "grades":[0,0], + "a":True, + "cx":{ + "accent":"#DF6915", + #"lightborder":True, + "border":1, + }, + }, + "bow4":{ + "type":"weapon", + "wtype":"bow", + "skin":"bow4", + "tier":4, + "damage_type":"physical", + "upgrade":{ + }, + "name":"T4 Bow", + "g":16000, + "ignore":True, + "cx":{"accent":"#E4B81D"}, + }, + "spear":{ + "type":"weapon", + "wtype":"spear", + "tier":1.25, + "skin":"spear", + "apiercing":10, + "damage_type":"physical", + "upgrade":{ + "apiercing":5, + }, + "name":"Spear", + "g":72000, + "a":2, + "grades":[3,8], + "cx":{"accent":"#AE4731"}, + }, + "spearofthedead":{ + "type":"weapon", + "wtype":"spear", + "tier":2.4, + "skin":"spearofthedead", + "str":8, + "for":3, + "apiercing":12, + "damage_type":"physical", + "upgrade":{ + }, + "name":"Spear of the Dead", + "explanation":"A deadly weapon", + "g":724000, + "a":True, + "cx":{"accent":"#D87F0E"}, + }, + "scythe":{ + "type":"weapon", + "wtype":"scythe", + "tier":3, + "skin":"scythe", + "damage_type":"physical", + "upgrade":{ + }, + "name":"Skeletor's Scythe", + "g":8600000, + "cx":{"accent":"#5AAEED"}, + }, + "blade":{ + "type":"weapon", + "wtype":"short_sword", + "tier":1, + "skin":"blade", + "damage_type":"physical", + "upgrade":{ + }, + "name":"Blade", + "g":8400, + }, + "sword":{ + "type":"weapon", + "wtype":"short_sword", + "tier":2.5, + "skin":"sword", + "damage_type":"physical", + "upgrade":{ + }, + "name":"Short Sword", + "g":48000, + "cx":{"accent":"#CC5A10"}, + }, + "swifty":{ + "type":"weapon", + "wtype":"sword", + "tier":1.75, + "dex":12, + "skin":"swifty", + "damage_type":"physical", + "upgrade":{ + }, + "name":"Swifty", + "g":48000, + "cx":{"accent":"#CC54B2"}, + }, + "fsword":{ + "type":"weapon", + "wtype":"short_sword", + "tier":2, + "skin":"fsword", + "skin_r":"fsword_r", + "damage_type":"physical", + "ability":"freeze", + "attr0":0.2, + "int":8, + "upgrade":{ + "attr0":0.1, + }, + "name":"Frozen Sword", + "g":72000, + }, + "rapier":{ + "type":"weapon", + "wtype":"rapier", + "tier":2, + "skin":"rapier", + "damage_type":"physical", + "upgrade":{ + }, + "name":"Rapier", + "g":84000, + "cx":{ + "scale":0.75, + #"small":True, + "large":True, + }, + "cx":{"accent":"#5085B0"}, + }, + "basher":{ + "type":"weapon", + "wtype":"basher", + "tier":2, + "skin":"basher", + "damage_type":"physical", + "armor":20, + "stun":0.5, + #"attr0":0.5, #probability + #"attr1":1, #duration + #"ability":"bash", + "upgrade":{ + "stun":0.5, + #"attr0":0.4, + #"attr1":0.2, + "armor":4, + "speed":1, + }, + "name":"Basher", + "g":72000, + "a":True, + "grades":[0,7], + "cx":{"accent":"#5085B0"}, + }, + "bataxe":{ + "type":"weapon", + "wtype":"axe", + "tier":2.25, + "skin":"bataxe", + "damage_type":"physical", + "reflection":4, + "upgrade":{ + }, + "name":"Ghastly Battle Axe", + "g":124000, + "a":True, + "grades":[0,6], + "delia":"Now you see me, now you see the floor", + "cx":{ + "accent":"#DF6915", + "lightborder":True, + }, + }, + "axe3":{ + "type":"weapon", + "wtype":"axe", + "tier":3, + "skin":"axe3", + "damage_type":"physical", + "reflection":4, + "upgrade":{ + }, + "name":"T3 Axe", + "g":124000, + "a":True, + "cx":{ + "accent":"#DF6915", + "lightborder":True, + }, + "ignore":True, + }, + "fireblade":{ + "type":"weapon", + "wtype":"short_sword", + "tier":2, + "skin":"fireblade", + "skin_r":"fireblade_r", + "damage_type":"physical", + "ability":"burn", + "attr0":1.5, + "upgrade":{ + "attr0":0.5, + }, + "name":"Fiery Blade", + "g":96000, + "a":True, + "grades":[0,8], + #"cx":{"accent":"#D3001E"}, + "cx":{"accent":"#E34C25"}, + }, + "swordofthedead":{ + "type":"weapon", + "wtype":"short_sword", + "tier":2.5, + "skin":"swordofthedead", + "damage_type":"physical", + "resistance":20, + "attack":2, + "str":10, + "vit":-12, + "upgrade":{ + "resistance":2.5, + }, + "name":"Sword of the Dead", + "g":224000, + "a":True, + "cx":{"accent":"#D87F0E"}, + }, + "woodensword":{ + "type":"weapon", + "wtype":"sword", + "tier":2, + "skin":"woodensword", + "damage_type":"physical", + "dex":20, + "upgrade":{ + "dex":2, + }, + "name":"Wooden Sword", + "g":224000, + "a":True, + "cx":{"accent":"#155E0C"}, + }, + "heartwood":{ + "type":"weapon", + "wtype":"sword", + "tier":3.5, + "skin":"heartwood", + "damage_type":"physical", + "ability":"tangle", + "dex":20, + "speed":4, + "upgrade":{ + "dex":4, + }, + "name":"Heartwood", + "explanation":"One with nature", + "g":18700000, + "a":True, + "cx":{"accent":"#155E0C"}, + }, + "glolipop":{ + "type":"weapon", + "wtype":"mace", + "tier":0, + "dex":24, + "explosion":20, + "skin":"glolipop", + "ability":"sugarrush", + "damage_type":"physical", + "upgrade":{ + "explosion":2, + }, + "name":"Lolipop Mace", + "g":16000, + "cx":{"accent":"#64B553"}, + }, + "ololipop":{ + "type":"weapon", + "wtype":"mace", + "tier":0, + "str":24, + "explosion":20, + "skin":"ololipop", + "damage_type":"physical", + "ability":"sugarrush", + "upgrade":{ + "explosion":2, + }, + "name":"Lolipop Mace", + "g":16000, + "cx":{"accent":"#DB763B"}, + }, + "mace":{ + "type":"weapon", + "wtype":"mace", + "tier":1, + "skin":"mace", + "damage_type":"physical", + "upgrade":{ + }, + "name":"Mace", + "g":3700, + "cx":{"accent":"#AF2131"}, + }, + "xmace":{ + "set":"holidays", + "type":"weapon", + "wtype":"mace", + "tier":2.25, + "stun":2, + "skin":"xmace", + "damage_type":"physical", + "upgrade":{ + }, + "name":"Merry Mace", + "g":37000, + "cx":{"accent":"#AF2131"}, + }, + "wbasher":{ + "type":"weapon", + "wtype":"basher", + "tier":1, + "skin":"wbasher", + "damage_type":"physical", + "upgrade":{ + }, + "name":"Wooden Basher", + "g":4900, + "cx":{"accent":"#AF2131"}, + }, + "hammer":{ + "type":"weapon", + "wtype":"mace", + "tier":3, + "skin":"hammer", + "damage_type":"physical", + "upgrade":{ + }, + "name":"Hammer", + "g":960000, + "cx":{"accent":"#7A44A2"}, + }, + "vhammer":{ + "set":"vampires", + "type":"weapon", + "wtype":"mace", + "tier":3, + "lifesteal":3, + "explosion":10, + "skin":"vhammer", + "damage_type":"physical", + "upgrade":{ + "explosion":2, + }, + "name":"Vampiric Hammer", + "g":9600000, + "cx":{"accent":"#B91A6A"}, + }, + "vstaff":{ + "set":"vampires", + "type":"weapon", + "wtype":"staff", + "tier":3.25, + "speed":8, + "armor":120, + "skin":"vstaff", + "damage_type":"magical", + "upgrade":{ + }, + "name":"Vampiric Staff", + "g":9600000, + "cx":{"accent":"#B91A6A"}, + }, + "vdagger":{ + "set":"vampires", + "type":"weapon", + "wtype":"dagger", + "tier":3.25, + "lifesteal":5, + "skin":"vdagger", + "damage_type":"physical", + "upgrade":{ + }, + "name":"Vampiric Dagger", + "g":9600000, + "cx":{"accent":"#B91A6A"}, + }, + "vsword":{ + "set":"vampires", + "type":"weapon", + "wtype":"sword", + "tier":3.25, + "lifesteal":5, + "speed":1, + "skin":"vsword", + "damage_type":"physical", + "upgrade":{ + }, + "name":"Vampiric Sword", + "g":9600000, + "cx":{"accent":"#B91A6A"}, + }, + "maceofthedead":{ + "type":"weapon", + "tier":2.4, + "wtype":"mace", + "skin":"maceofthedead", + "str":6, + "speed":-3, + "vit":-8, + "damage_type":"physical", + "upgrade":{ + }, + "name":"Mace of the Dead", + "g":224000, + "a":True, + "cx":{"accent":"#D87F0E"}, + }, + "pmaceofthedead":{ + "type":"weapon", + "tier":3, + "wtype":"pmace", + "skin":"pmaceofthedead", + "str":20, + "speed":-3, + "damage_type":"magical", + "upgrade":{ + }, + "name":"Hand of the Dead", + "g":824000, + "a":True, + "cx":{"accent":"#D87F0E"}, + }, + "carrotsword":{ + "set":"bunny", + "type":"weapon", + "wtype":"short_sword", + "tier":2, + "skin":"carrotsword", + "skin_c":"carrotsword_c", + "range":-4, + "dex":12, + "charisma":-20, + "damage_type":"physical", + "upgrade":{ + "range":-0.25, + }, + "name":"Carrot Sword", + "g":92000, + "a":True, + "grades":[0,7], + "cx":{ + "accent":"#E9711A", + #"scale":0.75, + }, + }, + "candycanesword":{ + "set":"holidays", + "type":"weapon", + "wtype":"short_sword", + "tier":2, + "range":-2, + "skin":"candycanesword", + "damage_type":"physical", + "ability":"sugarrush", + "upgrade":{ + "range":-0.5, + }, + "name":"Candy Cane Sword", + "g":72000, + "a":True, + "grades":[0,8], + }, + "pinkie":{ + "set":"bunny", + "type":"weapon", + "wtype":"wand", + "tier":1.75, + "skin":"pinkie", + "skin_r":"pinkie_r", + "charisma":-100, + "speed":2, + "damage_type":"magical", + "upgrade":{ + }, + "name":"Pink Wand", + "grades":[0,7], + "g":124000, + "cx":{ + "accent":"#DF33EC", + "scale":0.5, + "extension":True, + }, + "projectile":"pinky", + }, + "wand":{ + "type":"weapon", + "wtype":"wand", + "tier":1, + "skin":"wand", + "damage_type":"magical", + "upgrade":{ + }, + "name":"Wand", + "g":48600, + "cx":{ + "accent":"#EA6238", + "scale":0.5, + "extension":True, + }, + "projectile":"wandy", + }, + "broom":{ + "type":"weapon", + "wtype":"staff", + "tier":0, + "speed":2, + "evasion":5, + "skin":"broom", + "damage_type":"magical", + "upgrade":{ + "speed":1, + "evasion":1, + }, + "name":"Broom", + "g":128, + "cx":{"accent":"#7B68A5"}, + }, + "staff":{ + "type":"weapon", + "wtype":"staff", + "tier":1, + "skin":"staff", + "damage_type":"magical", + "upgrade":{ + }, + "name":"Staff", + "g":12400, + "cx":{"accent":"#AF2131"}, + }, + "gstaff":{ + "type":"weapon", + "wtype":"great_staff", + "projectile":"bigmagic", + "tier":3, + "blast":40, + "skin":"blaster", + "damage_type":"magical", + "upgrade":{ + "blast":5, + }, + "name":"Blaster", + "explanation":"[Warning] Highly volatile - might lose it's power suddenly!", + "g":1240000, + "cx":{"accent":"#AF2131"}, + }, + "staff2":{ + "type":"weapon", + "wtype":"staff", + "tier":2, + "skin":"staff", + "damage_type":"magical", + "upgrade":{ + }, + "name":"T2 Staff", + "g":12400, + "cx":{"accent":"#AF2131"}, + "ignore":True, + }, + "staff3":{ + "type":"weapon", + "wtype":"staff", + "tier":3, + "skin":"staff", + "damage_type":"magical", + "upgrade":{ + }, + "name":"T3 Staff", + "g":12400, + "cx":{"accent":"#AF2131"}, + "ignore":True, + }, + "staff4":{ + "type":"weapon", + "wtype":"staff", + "tier":4, + "skin":"staff", + "damage_type":"magical", + "upgrade":{ + }, + "name":"T4 Staff", + "g":12400, + "cx":{"accent":"#AF2131"}, + "ignore":True, + }, + "slimestaff":{ + "class":["priest"], + "type":"weapon", + "wtype":"staff", + "tier":1.5, + "skin":"slimestaff", + "dex":5, + "speed":-5, + "damage_type":"magical", + "upgrade":{ + "dex":2, + }, + "name":"Slime Staff", + "g":16400, + "cx":{"accent":"#48A763"}, + }, + "mushroomstaff":{ + "class":["mage"], + "type":"weapon", + "wtype":"staff", + "tier":1.25, + "skin":"mushroomstaff", + "rpiercing":40, + "damage_type":"magical", + "upgrade":{ + }, + "name":"Mushroom Staff", + "g":16400, + "cx":{"accent":"#D34C57"}, + }, + "firestaff":{ + "type":"weapon", + "wtype":"staff", + "tier":2, + "skin":"firestaff", + "skin_r":"firestaff_r", + "projectile": "fireball", + "damage_type":"magical", + "ability":"burn", + "attr0":2, + "upgrade":{ + "attr0":0.5, + }, + "name":"Fiery Staff", + "g":189000, + "a":True, + "grades":[0,8], + "cx":{"accent":"#D3001E"}, + }, + "ornamentstaff":{ + "set":"holidays", + "type":"weapon", + "wtype":"staff", + "tier":2, + "skin":"ornamentstaff", + "mp_cost":-40, + "awesomeness":99, + "damage_type":"magical", + "upgrade":{ + "awesomeness":0.1, + }, + "name":"Ornament Staff", + "g":120000, + "a":True, + "grades":[0,7], + "cx":{"accent":"#0B5818"}, + }, + "staffofthedead":{ + "type":"weapon", + "wtype":"staff", + "tier":2.5, + "skin":"staffofthedead", + "str":32, + "speed":-6, + "damage_type":"magical", + "upgrade":{ + }, + "name":"Staff of the Dead", + "g":224000, + "a":True, + "grades":[0,6], + "cx":{"accent":"#D87F0E"}, + }, + "froststaff":{ + "type":"weapon", + "wtype":"staff", + "tier":2, + "skin":"froststaff", + "skin_r":"froststaff_r", + "projectile":"frostball", + "damage_type":"magical", + "int":2, + "ability":"freeze", + "attr0":4, + "upgrade":{ + "int":0.2, + "attr0":1.25, + }, + "name":"Frost Staff", + "g":289000, + "a":True, + "grades":[0,8], + }, + "oozingterror":{ + "type":"weapon", + "wtype":"staff", + "tier":2.75, + "skin":"oozingterror", + "projectile_test":"acid", + "projectile":"magic_purple", + "reflection":1, + "vit":-30, + "int":20, + "damage_type":"magical", + "ability":"posion", + "attr0":0.1, + "upgrade":{ + "reflection":0.25, + "int":1, + "attr0":0.02, + }, + "name":"Oozing Terror", + "g":289000, + "a":True, + "grades":[0,5], + "explanation":"It drains the life energy of the user", + "nopo":"Mutates the brain to maximize its potential, sapping the user's life in the process.", + "cx":{"accent":"#745DD6"}, + }, + "harbringer":{ + "type":"weapon", + "wtype":"staff", + "tier":2.75, + "skin":"harbringer", + "skin_r":"harbringer_r", + "projectile":"magic_divine", + "rpiercing":10, + "damage_type":"magical", + "upgrade":{ + "rpiercing":5, + }, + "name":"Harbringer", + "g":289000, + "a":True, + "grades":[0,5], + "explanation":"Pure, unfiltered power!", + "trex":"This staff is a relic of a past age long forgotten. Thought to be forged by the God of Lighting. Those who have seen this staff claim it radiates powerful energy. Though this staff is only wielded by few, it is feared by all.", + }, + "wblade":{ + "type":"weapon", + "wtype":"wblade", + "tier":4, + "skin":"wblade", + "rpiercing":40, + "evasion":10, + "damage_type":"magical", + "upgrade":{ + "evasion":1, + "rpiercing":16, + }, + "name":"Ethereal Blade of Destiny", + "g":48900000, + "a":True, + "exclusive":True, + "grades":[0,0], + "projectile":"wmomentum", + }, + "pmace":{ + "type":"weapon", + "wtype":"pmace", + "tier":2, + "skin":"pmace", + "class":["priest"], + "int":8, + "dex":4, + "damage_type":"magical", + "upgrade":{ + "int":2, + "dex":1, + }, + "name":"Priest's Mace", + "g":89000, + "a":True, + "grades":[0,8], + }, + "lmace":{ + "type":"weapon", + "wtype":"pmace", + "tier":3, + "skin":"lmace", + "int":8, + "str":6, + "luck":6, + "class":["priest"], + "damage_type":"magical", + "upgrade":{ + "int":2, + "str":1, + }, + "name":"Lunar Mace", + "explanation":"Majestic", + "g":890000, + "a":True, + "grades":[0,0], + }, +} + +for name in weapons.keys(): + current=weapons[name]; tier=current.get("tier",1) + if not current.has_key("upgrade"): continue + if not current.has_key("grades"): + if tier<1: current["grades"]=[8,9] + elif tier<=1: current["grades"]=[7,9] + elif tier<=1.5: current["grades"]=[5,8] + elif tier<=1.75: current["grades"]=[4,7] + elif tier<=2: current["grades"]=[0,7] + elif tier<=2.25: current["grades"]=[0,6] + elif tier<=2.4: current["grades"]=[0,5] + elif tier<=2.5: current["grades"]=[0,4] + elif tier<=2.75: current["grades"]=[0,3] + else: current["grades"]=[0,0] + if len(current["grades"])==2: + current["grades"].append(10) + current["grades"].append(12) + if tier>=4: + current["grades"][2]=8 + current["grades"][3]=10 + elif tier>=3: + current["grades"][2]=9 + current["grades"][3]=10 + #elif tier>=2: + # current["grades"][2]=10 + # current["grades"][3]=11 + originals=[current.get("range",0),current["upgrade"].get("range",0),current.get("attack",0),current["upgrade"].get("attack",0)] + if current.get("wtype") in ["rod","pickaxe"]: continue + if current.get("wtype") not in ["short_sword","rapier","spear","sword","axe","scythe","great_sword","basher","fist","dagger","stars","dartgun","mace","bow","staff","great_staff","wblade","pmace","crossbow","wand"]: + import logging + logging.info("CONVERT WTYPE: %s for %s"%(current.get("wtype"),name)) + continue + if current.get("wtype")=="short_sword": + current["range"]=5+(tier-1)*2 + current["upgrade"]["range"]=1.5 + current["attack"]=15+(tier-1)*6 + current["upgrade"]["attack"]=4+(tier-1)*0.5 + if current.get("wtype")=="rapier": + current["range"]=5+(tier-1)*2 + current["upgrade"]["range"]=1.5 + current["attack"]=10+(tier-1)*5 + current["upgrade"]["attack"]=2+(tier-1)*0.5 + if current.get("wtype")=="spear": + current["range"]=15+(tier-1)*2 + current["upgrade"]["range"]=2 + current["attack"]=15+(tier-1)*5 + current["upgrade"]["attack"]=4.25+(tier-1)*0.7 + if current.get("wtype")=="fist": + current["range"]=5+(tier-1)*1 + current["upgrade"]["range"]=1.5 + current["attack"]=10+(tier-1)*4 + current["upgrade"]["attack"]=3+(tier-1)*1 + if current.get("wtype")=="dagger": + current["range"]=5+(tier-1)*1 + current["upgrade"]["range"]=2 + current["attack"]=12+(tier-1)*5 + current["upgrade"]["attack"]=3+(tier-1)*1 + if current.get("wtype")=="stars": + current["range"]=50+(tier-1)*10 + current["upgrade"]["range"]=4+(tier-1)*1 + current["attack"]=5+(tier-1)*2 + current["upgrade"]["attack"]=2.5+(tier-1)*0.8 + if current.get("wtype")=="dartgun": + current["range"]=30+(tier-1)*10 + current["upgrade"]["range"]=20 + current["attack"]=10 + current["upgrade"]["attack"]=5+(tier-1)*2.5 + if current.get("wtype")=="sword": + current["range"]=5+(tier-1)*3 + current["upgrade"]["range"]=1.5 + current["attack"]=15+(tier-1)*5 + current["upgrade"]["attack"]=4+(tier-1)*1 + if current.get("wtype")=="axe" or current.get("wtype")=="basher" or current.get("wtype")=="great_sword" or current.get("wtype")=="scythe": #Like 2X Sword + current["range"]=5+(tier-1)*3 + current["upgrade"]["range"]=1 + current["attack"]=30+(tier-1)*9 + current["upgrade"]["attack"]=7+(tier-1)*2.5 + if current.get("wtype")=="great_sword": + current["attack"]+=4 + current["upgrade"]["attack"]-=0.5 + if current.get("wtype")=="basher": + current["range"]-=2 + current["attack"]-=4 + current["upgrade"]["attack"]-=0.5 + if current.get("wtype")=="scythe": + current["range"]+=2 + if current.get("wtype")=="mace": + current["range"]=5+(tier-1)*1 + current["upgrade"]["range"]=1 + current["attack"]=20+(tier-1)*6 + current["upgrade"]["attack"]=4+(tier-1)*1.1 + if current.get("wtype")=="bow": + current["range"]=55+(tier-1)*10 + current["upgrade"]["range"]=4+current["range"]*4.0/60 + current["attack"]=20+(tier-1)*6 + current["upgrade"]["attack"]=4+(tier-1)*0.8 + current["projectile"]=current.get("projectile","arrow") + if current.get("wtype")=="staff": + current["range"]=50+(tier-1)*6 + current["upgrade"]["range"]=3+(tier-1)*0.5 + current["attack"]=25+(tier-1)*10 + current["upgrade"]["attack"]=5+(tier-1)*0.5 + if current.get("wtype")=="great_staff": + current["range"]=70+(tier-1)*8 + current["upgrade"]["range"]=3+(tier-1)*1 + current["attack"]=35+(tier-1)*16 + current["upgrade"]["attack"]=6+(tier-1)*1 + if current.get("wtype")=="wblade": + current["range"]=12+(tier-1)*6 + current["upgrade"]["range"]=2 + current["attack"]=24+(tier-1)*8 + current["upgrade"]["attack"]=5+(tier-1)*1 + if current.get("wtype")=="pmace": + current["range"]=5+(tier-1)*5 + current["upgrade"]["range"]=4+(tier-1)*1 + current["attack"]=20+(tier-1)*5 + current["upgrade"]["attack"]=5+(tier-1)*1 + if current.get("wtype")=="crossbow": #Like 1.4X Bow's + current["range"]=85+(tier-1)*16 + current["upgrade"]["range"]=4+current["range"]*4.0/60 + current["attack"]=30+(tier-1)*7 + current["upgrade"]["attack"]=5.5+(tier-1)*0.8 + current["projectile"]=current.get("projectile","arrow") + if current.get("wtype")=="wand": + current["range"]=30+(tier-1)*5 + current["upgrade"]["range"]=4+current["range"]*4.0/60 + current["attack"]=16+(tier-1)*5 + current["upgrade"]["attack"]=3+(tier-1)*0.6 + current["range"]+=originals[0]; current["upgrade"]["range"]+=originals[1]; current["attack"]+=originals[2]; current["upgrade"]["attack"]+=originals[3] + +offhands={ + "shield":{ + "type":"shield", + "tier":2, + "skin":"shield", + "armor":60, + "resistance":20, + "upgrade":{ + "armor":12.5, + "resistance":7.5, + }, + "name":"Shield", + "g":24000, + "grades":[4,8], + }, + "tigershield":{ + "set":"tiger", + "type":"shield", + "tier":2.5, + "speed":2, + "skin":"tigershield", + "armor":80, + "resistance":30, + "upgrade":{ + "armor":13.5, + "resistance":8.5, + }, + "name":"Shield of the Tiger", + "g":240000, + "grades":[0,6], + }, + "xshield":{ + "type":"shield", + "tier":3, + "skin":"xshield", + "resistance":24, + "evasion":4, + "int":4, + "dex":6, + "str":8, + "crit":1, + "speed":5, + "xp":8, + "upgrade":{ + "resistance":6, + "str":1, + }, + "name":"Shield X", + "explanation":"A metallurgical failure but a magical marvel", + "g":1200000, + "grades":[0,0], + "cx":{"accent":"#4D828F"}, + }, + "mshield":{ + "type":"shield", + "tier":3, + "skin":"mshield", + "armor":20, + "luck":8, + "stat":5, + "upgrade":{ + "luck":1, + "stat":1.25, + "armor":5, + }, + "name":"Shield M", + "g":1200000, + "grades":[0,0], + "cx":{"accent":"#E90010"}, + }, + "exoarm":{ + "type":"misc_offhand", + "tier":3, + "skin":"exoarm", + "int":20, + "str":24, + "armor":80, + "compound":{ + "int":6, + "str":6, + }, + "name":"Exoskeletal Arm", + "explanation":"It does more than just enhance your natural movements, almost like has a mind of it's own", + "g":48000000, + "grades":[0,0], + "cx":{ + } + }, + "lantern":{ + "type":"misc_offhand", + "tier":3, + "skin":"lantern", + "resistance":120, + "evasion":10, + "compound":{ + "resistance":10, + "evasion":5, + }, + "name":"The Lantern", + "explanation":"Forged from a naturally vibrating metal", + "g":480000, + "grades":[0,0], + "cx":{ + "scale":0.5, + #"extension":True, + } + }, + "sshield":{ + "type":"shield", + "tier":2, + "skin":"sshield", + "armor":60, + "resistance":20, + "dreturn":3, + "upgrade":{ + "dreturn":1.5, + "armor":10, + "resistance":7, + }, + "name":"Spiked Shield", + "g":24000, + "grades":[4,8], + }, + "wshield":{ + "type":"shield", + "tier":1, + "skin":"wshield", + "armor":40, + "resistance":15, + "stat":2, + "upgrade":{ + "armor":8, + "resistance":5, + }, + "name":"Wooden Shield", + "g":4800, + "grades":[7,9], + "cx":{"accent":"#3D923A"}, + }, + "wbook0":{ + "type":"source", + "tier":1, + "skin":"wbook0", + "int":6, + "compound":{ + "int":5, + }, + "name":"Book of Knowledge", + "g":12000, + "grades":[4,5], + "cx":{ + "scale":0.5, + "extension":True, + } + }, + "wbook1":{ + "type":"source", + "tier":2, + "skin":"wbook1", + "int":16, + "reflection":2, + "vit":6, + "compound":{ + "int":5, + "reflection":1, + "vit":2, + }, + "name":"Book of Secrets", + "g":960000, + "grades":[0,2], + "cx":{ + "scale":0.5, + "extension":True, + } + }, + "wbookhs":{ + "set":"holidays", + "type":"source", + "tier":2, + "skin":"wbookhs", + "dex":16, + "vit":16, + "resistance":120, + "compound":{ + "dex":6, + "vit":6, + "resistance":30, + }, + "name":"Book of Cheer", + "g":960000, + "grades":[0,2], + "cx":{ + "scale":0.5, + "extension":True, + } + }, + "quiver":{ + "type":"quiver", + "tier":1, + "skin":"quiver", + "dex":2, + "range":20, + "armor":10, + "upgrade":{ + "dex":1, + "armor":2, + "range":3.5, + }, + "name":"Quiver", + "g":24000, + "grades":[3,7], + }, + "t2quiver":{ + "type":"quiver", + "tier":2, + "skin":"t2quiver", + "dex":9, + "range":20, + "armor":12, + "evasion":1, + "upgrade":{ + "dex":1.5, + "armor":3, + "range":3.5, + }, + "name":"Agile Quiver", + "g":960000, + "grades":[0,4], + "a":True, + }, +} + +collectables={ + "brownegg":{ + "type":"material", + "skin":"brownegg", + "name":"Brown Egg", + "s":100, + "g":1000, + }, + "whiteegg":{ + "type":"material", + "skin":"whiteegg", + "name":"White Egg", + "s":2000, + "g":5, + "throw":True, + "action":"THROW!", + "onclick":"socket.emit('throw',{num:locate_item('whiteegg'),x:character.real_x,y:character.real_y}); push_deferred('throw')", + }, + "gslime":{ + "type":"material", + "skin":"gslime", + "name":"Slime Core", + "s":True, + "g":20, + }, + "crabclaw":{ + "type":"material", + "skin":"crabclaw", + "name":"Crab Claw", + "s":True, + "g":120, + }, + "beewings":{ + "type":"material", + "skin":"beewings", + "name":"Bee Wings", + "s":True, + "g":25, + }, + "pleather":{ + "type":"material", + "skin":"pleather", + "name":"Porcupine Leather", + "s":True, + "g":400, + }, + "spores":{ + "type":"material", + "skin":"spores", + "name":"Spores", + "s":True, + "g":120, + }, + "lotusf":{ + "type":"material", + "skin":"lotusf", + "name":"Lotus Flower", + "s":True, + "g":12000, + }, + "frogt":{ + "type":"material", + "skin":"frogt", + "name":"Frog Tongue", + "s":True, + "g":3, + }, + "snakefang":{ + "type":"material", + "skin":"snakefang", + "name":"Snake Fang", + "s":True, + "g":1200, + }, + "rattail":{ + "type":"material", + "skin":"rattail", + "name":"Rat Tail", + "s":True, + "g":2, + }, + "ascale":{ + "type":"material", + "skin":"ascale", + "name":"Armadillo Scale", + "s":True, + "g":500, + }, + "ink":{ + "type":"material", + "skin":"ink", + "name":"Ink", + "s":True, + "g":5000, + }, + "ijx":{ + "type":"material", + "skin":"ijx", + "name":"Irradium", + "s":True, + "g":360000, + }, + "smush":{ + "type":"material", + "skin":"smush", + "name":"Small Mushroom", + "s":True, + "g":87, + }, + "carrot":{ + "type":"material", + "skin":"carrot", + "name":"Carrot", + "s":True, + "g":4, + }, + "bfur":{ + "type":"material", + "skin":"bfur", + "name":"Bee Fur", + "s":True, + "g":5, + }, + "bandages":{ + "type":"material", + "skin":"bandages", + "name":"Bandages", + "s":True, + "g":26, + }, + "cocoon":{ + "type":"material", + "skin":"cocoon", + "name":"Cocoon", + "s":True, + "g":200, + }, + "tshell":{ + "type":"material", + "skin":"tshell", + "name":"Turtle Shell", + "s":True, + "g":1200, + }, + "dstones":{ + "type":"material", + "skin":"dstones", + "name":"Digestive Stones", + "s":True, + "g":90, + }, + "bwing":{ + "type":"material", + "skin":"bwing", + "name":"Bat Wing", + "s":True, + "g":120, + }, + "bfang":{ + "type":"material", + "skin":"bfang", + "name":"Bat Fang", + "s":True, + "g":24000, + }, + "sstinger":{ + "type":"material", + "skin":"sstinger", + "name":"Scorpion Stinger", + "s":True, + "g":4000, + }, + "svenom":{ + "type":"material", + "skin":"svenom", + "name":"Scorpion Venom", + "s":True, + "g":12000, + }, + "pstem":{ + "type":"material", + "skin":"pstem", + "name":"Pumpkin Stem", + "s":True, + "g":5, + }, + "watercore":{ + "type":"material", + "skin":"watercore", + "name":"Water Core", + "s":True, + "g":800000, + }, + "ectoplasm":{ + "type":"material", + "skin":"ectoplasm", + "name":"Ectoplasm", + "s":True, + "g":60000, + }, + "rfur":{ + "type":"material", + "skin":"rfur", + "name":"Rat Fur", + "s":True, + "g":40, + }, + "cshell":{ + "type":"material", + "skin":"cshell", + "name":"Crab Shell", + "s":True, + "g":32000, + }, + "bcandle":{ + "type":"material", + "skin":"bcandle", + "name":"Burning Candle", + "s":True, + "g":420000, + }, + "lspores":{ + "type":"material", + "skin":"lspores", + "name":"Large Spores", + "s":True, + "g":160, + }, + "trinkets":{ + "type":"material", + "skin":"trinkets", + "name":"Trinkets", + "s":True, + "g":200000, + }, + "rfangs":{ + "type":"material", + "skin":"rfangs", + "name":"Rat Fangs", + "s":True, + "g":12000, + }, + "btusk":{ + "type":"material", + "skin":"btusk", + "name":"Boar Tusk", + "s":True, + "g":50000, + }, + "drapes":{ + "type":"material", + "skin":"drapes", + "name":"Drapes", + "s":True, + "g":480, + }, +} + +materials={ + "essenceoffrost":{ + "type":"material", + "skin":"essenceoffrost", + "name":"Essence of Frost", + "explanation":"It's like an ice storm in a bottle", + "s":True, + "g":40000, + }, + "essenceoffire":{ + "type":"material", + "skin":"essenceoffire", + "name":"Essence of Fire", + "explanation":"So fierce, so mesmerizing", + "s":True, + "g":40000, + }, + "essenceofether":{ + "type":"material", + "skin":"essenceofether", + "name":"Ethereal Essence", + "explanation":"A ghostly essence, maybe it could allow you to shift from this world momentarily", + "s":True, + "g":40000, + }, + "essenceofnature":{ + "type":"material", + "skin":"essenceofnature", + "name":"Essence of Nature", + "explanation":"Earthly energy, waiting to spring", + "s":True, + "g":5000, + }, + "essenceoflife":{ + "type":"material", + "skin":"essenceoflife", + "name":"Essence of Life", + "explanation":"Full of life, literally.", + "s":True, + "g":1, + }, + "essenceofgreed":{ + "type":"material", + "skin":"essenceofgreed", + "name":"Essence of Greed", + "explanation":"A peculiar material.", + "s":True, + "g":13441344, + }, + "emptyjar":{ + "type":"jar", + "skin":"emptyjar", + "name":"Empty Jar", + "explanation":"Always nice to have some empty jars lying around, you never know when you'll need one!", + "s":True, + "g":1, + }, + "cxjar":{ + "type":"jar", + "skin":"cxjar", + "name":"CX Jar", + "explanation":"An appearance liquified and stored inside a jar.", + "exclusive":True, + "s":True, + "g":1, + }, + "emotionjar":{ + "type":"jar", + "skin":"emotionjar", + "name":"Emotion Jar", + "explanation":"An emotion liquified and stored inside a jar.", + "exclusive":True, + "s":True, + "g":1, + }, + "bottleofxp":{ + "type":"xp", + "skin":"bottleofxp", + "name":"Bottle of XP", + "gives":[["xp",100000000]], + "explanation":"One hundred million memories, experiences, bits and pieces of information.", + "s":20, + "g":12000000, + }, + "nheart":{ + "type":"material", + "skin":"nheart", + "name":"Heartwood Core", + "explanation":"An ancient source of life. A small piece of a magnificent being that spanned life across our realm eons ago.", + "s":True, + "g":12000000, + }, + "ledger":{ + "type":"misc", + "skin":"ledger", + "name":"Ledger", + "explanation":"Every decent merchant needs one!", + "ignore":True, + "g":12000, + }, + "storagebox":{ + "type":"misc", + "skin":"storagebox", + "name":"Storage Box", + "ignore":True, + "explanation":"It's a nifty little box", + "s":True, + "g":9000, + }, + "mysterybox":{ + "type":"misc", + "skin":"mysterybox", + "name":"Mystery Box", + "explanation":"It looks super cool, but you have no idea what to do with it! Exchange now or wait? No idea.", + "g":12000000, + "s":True, + "e":1, + }, + "troll":{ + "type":"misc", + "skin":"troll", + "name":"T-Shirt Roll", + "explanation":"A random T-Shirt!", + "g":12000, + "e":1, + "s":True, + }, +} + +pots={ + "hpot0":{ + "type":"pot", + "skin":"hpot0", + "gives":[["hp",200]], + "name":"HP Potion", + "cooldown":2000, + "s":True, + "g":20, + }, + "mpot0":{ + "type":"pot", + "skin":"mpot0", + "gives":[["mp",300]], + "name":"MP Potion", + "cooldown":2000, + "s":True, + "g":20, + }, + "hpot1":{ + "type":"pot", + "skin":"hpot1", + "gives":[["hp",400]], + "name":"HP Potion", + "cooldown":2000, + "s":True, + "g":100, + }, + "mpot1":{ + "type":"pot", + "skin":"mpot1", + "gives":[["mp",500]], + "name":"MP Potion", + "cooldown":2000, + "s":True, + "g":100, + }, + "hpotx":{ + "type":"pot", + "skin":"hpotx", + "gives":[["hp",10000]], + "name":"Super HP Potion", + "cooldown":2000, + "s":True, + "g":20000, + }, + "mpotx":{ + "type":"pot", + "skin":"mpotx", + "gives":[["mp",10000]], + "name":"Super MP Potion", + "cooldown":2000, + "s":True, + "g":20000, + }, +} + +scrolls={ + "cscroll0":{ + "type":"cscroll", + "skin":"cscroll0", + "grade":0, + "name":"Compound Scroll", + "explanation":"Scroll to combine 3 accessories. Things get challenging after +1. If the combination fails, the item is lost.", + "s":True, + "g":6400, + }, + "cscroll1":{ + "type":"cscroll", + "skin":"cscroll1", + "grade":1, + "name":"High Compound Scroll", + "explanation":"Scroll to combine 3 high grade accessories. If the combination fails, the item is lost.", + "s":True, + "g":240000, + }, + "cscroll2":{ + "type":"cscroll", + "skin":"cscroll2", + "grade":2, + "name":"Rare Compound Scroll", + "explanation":"Scroll to combine 3 rare accessories. If the combination fails, the item is lost.", + "s":True, + "g":9200000, + }, + "cscroll3":{ + "type":"cscroll", + "skin":"cscroll3", + "grade":3, + "name":"Legendary Compound Scroll", + "explanation":"A mysterious compound scroll, you can feel that it's very powerful. If the combination fails, the item is lost.", + "a":True, + "s":True, + "markup":20, + "g":1840000000, + }, + "scroll0":{ + "type":"uscroll", + "skin":"scroll0", + "grade":0, + "name":"Upgrade Scroll", + "explanation":"Scroll to upgrade a weapon or armor. If the upgrade fails, the item is lost.", + "s":True, + "g":1000, + }, + "scroll1":{ + "type":"uscroll", + "skin":"scroll1", + "grade":1, + "name":"High Upgrade Scroll", + "explanation":"Scroll to upgrade a high grade weapon or armor. If the upgrade fails, the item is lost.", + "s":True, + "g":40000, + }, + "scroll2":{ + "type":"uscroll", + "skin":"scroll2", + "grade":2, + "name":"Rare Upgrade Scroll", + "explanation":"Scroll to upgrade a rare weapon or armor. If the upgrade fails, the item is lost.", + "s":True, + "g":1600000, + }, + "scroll3":{ + "type":"uscroll", + "skin":"scroll3", + "grade":3, + "name":"Legendary Upgrade Scroll", + "explanation":"A mysterious upgrade scroll, you can feel that it's very powerful. If the upgrade fails, the item is lost.", + "a":True, + "s":True, + "g":480000000, + "markup":10, + }, + "scroll4":{ + "type":"uscroll", + "skin":"scroll4", + "grade":3.6, #must be synced in server.js/'upgrade' + "name":"Ultimate Upgrade Scroll", + "explanation":"A scroll passed down from ancient times. Long believed to be extinct. Powers beyond imagination.", + "a":True, + "s":True, + "g":640000000, + "exclusive":True, + }, + "strscroll":{ + "type":"pscroll", + "skin":"strscroll", + "stat":"str", + "name":"Strength Scroll", + "explanation":"Adds Stength to an armor with a Stat attribute.", + "multiplier":1, + "s":True, + "g":8000, + }, + "intscroll":{ + "type":"pscroll", + "skin":"intscroll", + "stat":"int", + "name":"Intelligence Scroll", + "explanation":"Adds Intelligence to an armor with a Stat attribute.", + "multiplier":1, + "s":True, + "g":8000, + }, + "dexscroll":{ + "type":"pscroll", + "skin":"dexscroll", + "stat":"dex", + "name":"Dexterity Scroll", + "explanation":"Adds Dexterity to an armor with a Stat attribute.", + "multiplier":1, + "s":True, + "g":8000, + }, + "vitscroll":{ + "type":"pscroll", + "skin":"vitscroll", + "stat":"vit", + "name":"Vitality Scroll", + "explanation":"Adds Vitality to an armor with a Stat attribute.", + "multiplier":1, + "s":True, + "g":8000, + }, + "forscroll":{ + "type":"pscroll", + "skin":"forscroll", + "stat":"for", + "name":"Fortitude Scroll", + "explanation":"Adds Fortitude to an armor with a Stat attribute.", + "multiplier":1, + "s":True, + "g":8000, + }, + "evasionscroll":{ + "type":"pscroll", + "skin":"evasionscroll", + "stat":"evasion", + "name":"Evasion Scroll", + "explanation":"Adds Evasion to an armor with a Special Stat attribute.", + "evasion":2, + "s":True, + "g":8000, + }, + "reflectionscroll":{ + "type":"pscroll", + "skin":"reflectionscroll", + "stat":"reflection", + "name":"Reflection Scroll", + "explanation":"Adds Reflection to an armor with a Stat attribute.", + "multiplier":0.125, + "s":True, + "g":8000, + }, + "goldscroll":{ + "type":"pscroll", + "skin":"goldscroll", + "stat":"gold", + "name":"Gold Scroll", + "explanation":"Adds Gold bonus to an armor with a Stat attribute.", + "multiplier":0.5, + "s":True, + "g":8000, + }, + "luckscroll":{ + "type":"pscroll", + "skin":"luckscroll", + "stat":"luck", + "name":"Luck Scroll", + "explanation":"Adds Luck to an armor with a Stat attribute.", + "multiplier":1, + "s":True, + "g":8000, + }, + "xpscroll":{ + "type":"pscroll", + "skin":"xpscroll", + "stat":"xp", + "name":"XP Scroll", + "explanation":"Adds XP bonus to an armor with a Stat attribute.", + "multiplier":0.5, + "s":True, + "g":8000, + }, + "armorscroll":{ + "type":"pscroll", + "skin":"armorscroll", + "stat":"armor", + "name":"Armor Scroll", + "explanation":"Adds Armor to an armor with a Stat attribute.", + "multiplier":2.25, + "s":True, + "g":8000, + }, + "resistancescroll":{ + "type":"pscroll", + "skin":"resistancescroll", + "stat":"resistance", + "name":"Resistance Scroll", + "explanation":"Adds Resistance to an armor with a Stat attribute.", + "multiplier":2.25, + "s":True, + "g":8000, + }, + "speedscroll":{ + "type":"pscroll", + "skin":"speedscroll", + "stat":"speed", + "name":"Speed Scroll", + "explanation":"Adds Speed to an armor with a Stat attribute.", + "multiplier":0.325, + "s":True, + "g":8000, + }, + "lifestealscroll":{ + "type":"pscroll", + "skin":"lifestealscroll", + "stat":"lifesteal", + "name":"Lifesteal Scroll", + "explanation":"Adds Lifesteal to an armor with a Stat attribute.", + "multiplier":0.15, + "s":True, + "g":8000, + }, + "manastealscroll":{ + "type":"pscroll", + "skin":"manastealscroll", + "stat":"manasteal", + "name":"Manasteal Scroll", + "explanation":"Adds Manasteal to an armor with a Stat attribute.", + "multiplier":0.040, + "s":True, + "g":8000, + }, + "rpiercingscroll":{ + "type":"pscroll", + "skin":"rpiercingscroll", + "stat":"rpiercing", + "name":"Resistance Piercing Scroll", + "explanation":"Adds Resistance Piercing to an armor with a Stat attribute.", + "multiplier":2.25, + "s":True, + "g":8000, + }, + "apiercingscroll":{ + "type":"pscroll", + "skin":"apiercingscroll", + "stat":"apiercing", + "name":"Armor Piercing Scroll", + "explanation":"Adds Armor Piercing to an armor with a Stat attribute.", + "multiplier":2.25, + "s":True, + "g":8000, + }, + "critscroll":{ + "type":"pscroll", + "skin":"critscroll", + "stat":"crit", + "name":"Critical Hit Scroll", + "explanation":"Adds Critical Hit to an armor with a Stat attribute.", + "multiplier":0.125, + "s":True, + "g":8000, + }, + "dreturnscroll":{ + "type":"pscroll", + "skin":"dreturnscroll", + "stat":"dreturn", + "name":"Damage Return Scroll", + "explanation":"Adds Damage Return to an armor with a Stat attribute.", + "multiplier":0.5, + "s":True, + "g":8000, + }, + "frequencyscroll":{ + "type":"pscroll", + "skin":"frequencyscroll", + "stat":"frequency", + "name":"Attack Speed Scroll", + "explanation":"Adds Attack Speed to an armor with a Stat attribute.", + "multiplier":0.325, + "s":True, + "g":8000, + }, + "mpcostscroll":{ + "type":"pscroll", + "skin":"mpcostscroll", + "stat":"mp_cost", + "name":"MP Cost Reduction Scroll", + "explanation":"Adds MP Cost Reduction to an armor with a Stat attribute.", + "multiplier":0.6, + "s":True, + "g":8000, + }, + "outputscroll":{ + "type":"pscroll", + "skin":"outputscroll", + "stat":"output", + "name":"Output Increase Scroll", + "explanation":"Adds Output Increase to an armor with a Stat attribute.", + "multiplier":0.175, + "s":True, + "g":8000, + }, +} + +premiums={ + "offering":{ + "type":"offering", + "skin":"shade_offering", + "name":"Primordial Essence", + #"explanation":"The essence contained within the shard can be transferred to items during upgrades and compounds. Significantly increases the chance to succeed.", + "explanation":"The essence contained within can be transferred to items during upgrades and compounds. Significantly increases the chance to succeed.", + "s":100, + "a":True, + "grade":2, + "g":27420000,#16720000, + #"e":1, + }, + "offeringp":{ + "type":"offering", + "skin":"offeringp", + "name":"Primling", + #"explanation":"The essence contained within the shard can be transferred to items during upgrades and compounds. Significantly increases the chance to succeed.", + "explanation":"A tiny cute essence that can be transferred to items during upgrades and compounds. Significantly increases the chance to succeed.", + "s":1000, + "a":True, + "grade":1, + "g":480000, + #"ignore":True, + #"e":1, + }, + "offeringx":{ + "type":"offering", + "skin":"offeringx", + "name":"Primordial X", + #"explanation":"The essence contained within the shard can be transferred to items during upgrades and compounds. Significantly increases the chance to succeed.", + "explanation":"The most powerful essence that can be transferred to items during upgrades and compounds. Significantly increases the chance to succeed.", + "s":10, + "a":True, + "grade":3, + "g":242064000, + #"ignore":True, + #"e":1, + }, + "cosmo0":{ + "type":"cosmetics", + "skin":"cosmo0", + "cash":289, #89 + "g":10000000, + "name":"New Armor", + "explanation":"Give this to NPC Haila to receive a new look. Heads-up! It's random, you may or may-not like it. [Work in progress - PRICE/DROPS MIGHT CHANGE!]", + "quest":"cx", + "s":True, + "e":1, + "quest":"cx", + }, + "cosmo1":{ + "type":"cosmetics", + "skin":"cosmo1", + "cash":459, #149 + "g":10000000, + "name":"New Make-up", + "explanation":"Give this to NPC Haila to receive a new make-up. Heads-up! It's random, you may or may-not like it. [Work in progress - Not functional yet.]", + "s":True, + #"e":1, + "quest":"cx", + }, + "cosmo2":{ + "type":"cosmetics", + "skin":"cosmo2", + "cash":129, + "g":10000000, + "name":"New Hairdo", + "explanation":"Give this to NPC Haila to receive a new hairdo. Heads-up! It's random, you may or may-not like it. [Work in progress - PRICE/DROPS MIGHT CHANGE!]", + "s":True, + "e":1, + "quest":"cx", + }, + "cosmo3":{ + "type":"cosmetics", + "skin":"cosmo3", + "cash":399, #99 + "g":10000000, + "name":"New Hat", + "explanation":"Give this to NPC Haila to receive a new hat. Heads-up! It's random, you may or may-not like it. [Work in progress - PRICE/DROPS MIGHT CHANGE!]", + "s":True, + "e":1, + "quest":"cx", + }, + "cosmo4":{ + "type":"cosmetics", + "skin":"cosmo4", + "cash":1399, #399 + "g":10000000, + "name":"New Accessory", + "explanation":"Give this to NPC Haila to receive a unique accessory. Heads-up! It's random, you may or may-not like it. [Work in progress - Not functional yet.]", + "s":True, + #"e":1, + "quest":"cx", + }, + "stoneofxp":{ + "type":"stone", + "skin":"stoneofxp", + "skin_a":"stoneofxp_a", + #"gain":"xp", + "g":100000000, #These were 1200 originally [17/01/18] + "name":"Stone of Wisdom", + "days":30, + "explanation":"Increases experience gain by 50%. Needs to be activated. Can be morphed into other stones.", + #"e":1, + "ignore":True, + }, + "stoneofgold":{ + "type":"stone", + "skin":"stoneofgold", + "skin_a":"stoneofgold", + #"gain":"gold", + "g":100000000, + "name":"Stone of Riches", + "days":30, + "explanation":"Helps you find up to 40% more gold from monsters.", + "ignore":True, + }, + "stoneofluck":{ + "type":"stone", + "skin":"stoneofluck", + "skin_a":"stoneofluck", + #"gain":"luck", + "g":100000000, + "name":"Stone of Luck", + "days":30, + "explanation":"Increases your chances to loot something from a monster by 20%.", + "ignore":True, + }, + # "tokenofcode":{ + # "type":"token", + # "skin":"tokenofcode", + # "minutes":240, + # "cash":5, + # "name":"Token of Code", + # "explanation":"Gives your character 240 minutes of additional CODE. This is a ~4 months old prototype people, but yeah, I'm considering limiting the free CODE hours to 8 or 12 hours a day. Might leave it unlimited too, undecided.", + # "s":True, + # }, + "xptome":{ + "type":"tome", + "skin":"xptome", + "reward":2, + "name":"Tome of Protection", + "explanation":"Significantly reduces experience loss on death. If the owner is defeated by another player, the victor receives a portion of the Tome's cost.", + "s":True, + "g":3200000, + }, + "licence":{ + "type":"licence", + "skin":"licence", + #"gain":"luck", + "name":"Licence to Kill", + "explanation":"With this licence, you gain a unique immunity for 7 minutes. No one can bother you for having too many comrades in this realm!", + "g":25000000, + "s":True, + }, + "xpbooster":{ + "type":"booster", + "skin":"xpbooster", + "skin_a":"xpbooster_a", + "gain":"xp", + "xp":20, + "compound":{ + "xp":12, + }, + "grades":[0,10], + "g":79840000, + "name":"XP Booster", + "days":30, + "explanation":"Increases experience gain. Needs to be activated. Can be shifted into other boosters.", + }, + "luckbooster":{ + "type":"booster", + "skin":"luckbooster", + "skin_a":"luckbooster_a", + "gain":"luck", + "luck":20, + "compound":{ + "luck":8, + }, + "grades":[0,10], + "g":79840000, + "name":"Luck Booster", + "days":30, + "explanation":"Increases your chances of looting something from a monster.", + "legacy":{ + "luck":15, + } + }, + "goldbooster":{ + "type":"booster", + "skin":"goldbooster", + "skin_a":"goldbooster_a", + "gain":"gold", + "gold":20, + "compound":{ + "gold":8, + }, + "grades":[0,10], + "g":79840000, + "name":"Gold Booster", + "days":30, + "explanation":"Boosts gold loot from chests.", + "legacy":{ + "gold":10, + } + }, + "networkcard":{ + "s":True, + "type":"material", + "skin":"networkcard", + "g":24000000, + "name":"Network Card", + "explanation":"A critical component that is able to interact with the fabric of our universe. Possibly quantum technology.", + }, + "qubics":{ + "type":"qubics", + "skin":"qubics", + "name":"Qubics", + "explanation":"Unique bio-electronic components, it's almost like they are alive. Can yield unexpected results if you introduce them to other materials!", + "s":True, + "a":True, + "g":5120000, + }, +} + +gems={ + "gem0":{ + "type":"gem", + "skin":"gem0", + "name":"Raw Emerald", + "explanation":"A very rare gem. Can be exchanged for random treasures.", + "g":240000, + "e":1, + "s":True, + "a":True, + }, + "gem1":{ + "type":"gem", + "skin":"gem1", + "name":"Tiny Ruby", + "explanation":"A hard to find gem. Can be exchanged for random treasures.", + "g":24000, + "e":1, + "s":True, + "a":2, + }, + "gem2":{ + "type":"gem", + "skin":"gem2", + "name":"Raw Diamond", + "explanation":"A precious gem. Can be exchanged for random treasures.", + "g":360000, + #"e":1, + "s":True, + "a":2, + }, + "gem3":{ + "type":"gem", + "skin":"gem3", + "name":"Raw Colourful Diamond", + "explanation":"A hard to find gem. Can be exchanged for random treasures.", + "g":4800000, + #"e":1, + "s":True, + "a":2, + }, + "candypop":{ + "type":"elixir", + "skin":"candypop", + "skin_a":"candypop", + "name":"Candy Pop", + "luck":12, + "vit":10, + "int":6, + "duration":1, + "g":120, + "e":10, + "eat":True, + "s":True, + "explanation":"You can eat it. Gift it. Exchange 10 of them at Xyn for a small reward.", + }, + "candy0":{ + "type":"gem", + "skin":"candy0", + "name":"Rare Candy", + "explanation":"A rare candy! Can be exchanged for random treasures.", + "g":240000, + "e":1, + "s":True, + "a":2, + #"event":True, + }, + "candy1":{ + "type":"gem", + "skin":"candy1", + "name":"Candy", + "explanation":"Candy! Can be exchanged for random treasures.", + "g":24000, + "e":1, + "s":True, + "a":2, + }, + "candy0v2":{ + "type":"gem", + "skin":"candy0", + "name":"Rare Candy [h2]", + "explanation":"A rare candy. Xyn in New Town could give you something exciting in exchange!", + "g":12000, + "e":1, + "s":True, + #"a":2, + "ignore":True, + }, + "candy1v2":{ + "type":"gem", + "skin":"candy1", + "name":"Candy [h2]", + "explanation":"A delicious candy. Xyn in New Town could give you something in exchange!", + "g":2400, + "e":1, + "s":True, + #"a":2, + "ignore":True, + }, + "candy0v3":{ + "type":"gem", + "skin":"candy0", + "name":"Rare Candy", + "explanation":"A rare candy. Xyn in New Town could give you something exciting in exchange!", + "g":12000, + "e":1, + "s":True, + "ignore":True, + #"a":2, + #"event":True, + }, + "candy1v3":{ + "type":"gem", + "skin":"candy1", + "name":"Candy", + "explanation":"A delicious candy. Xyn in New Town could give you something in exchange!", + "g":2400, + "e":1, + "s":True, + "ignore":True, + #"a":2, + }, + "bugbountybox":{ + "type":"box", + "skin":"bugbountybox",#"chest0", + "name":"Bug Bounty Box", + "explanation":"Rewarded for assisting in the hunt against the bugs.", + "g":120000, + "event":True, + "a":2, + "s":True, + "e":1, + }, + "apologybox":{ + "type":"box", + "skin":"apologybox",#"chest0", + "name":"Apology Box", + "explanation":"This box represents an official apology. Sorry.", + "g":120000, + "event":True, + "ignore":True, + "a":2, + "s":True, + "e":1, + }, + "weaponbox":{ + "type":"box", + "skin":"weaponbox",#"chest1", + "name":"Weapon Box", + "explanation":"Can be exchanged for a random, rare weapon.", + #"cash":320, + "g":320000, + "e":1, + "a":True, + "s":True, + }, + "armorbox":{ + "type":"box", + "skin":"armorbox",#"chest0", + "name":"Armor Box", + "explanation":"Can be exchanged for a random, rare armor.", + #"cash":120, + "g":120000, + "e":1, + "a":True, + "s":True, + }, + "jewellerybox":{ + "type":"box", + "skin":"chest3", + "name":"Jewellery Box", + "explanation":"Can be exchanged for a random acessory.", + #"cash":2320, + "ignore":True, + "g":80000, + "e":1, + "a":True, + "s":True, + }, + "mistletoe":{ + "type":"gem", + "skin":"mistletoe", + "name":"Mistletoe", + "explanation":"Maybe someone could give you a kiss in exchange...", + #"cash":2320, + "g":20000, + "e":1, + "a":True, + "s":True, + #"event":True, + #"quest":"mistletoe", #xmas + }, + "candycane":{ + "type":"gem", + "skin":"candycane", + "name":"Candy Cane", + "explanation":"The old man in Winterland was looking for sweets.", + "g":24000, + "e":1, + "s":True, + "a":True, + #"event":True, + #"quest":"candycane", #xmas + }, + "gift0":{ + "type":"gem", + "skin":"gift0", + "name":"Rare Gift", + "explanation":"A Rare Gift to celebrate our Anniversary!", + "g":2400, + "e":1, + "s":True, + "a":True, + }, + "gift1":{ + "type":"gem", + "skin":"gift1", + "name":"Gift", + "explanation":"A Gift to celebrate our Anniversary!", + "g":100, + "e":1, + "s":True, + "a":2, + }, + "redenvelope":{ + "type":"gem", + "skin":"redenvelope", + "name":"Red Envelope", + "explanation":"Congratulations and prosperity", + "g":24000, + "e":1, + "s":True, + "a":True, + "event":True, + }, + "redenvelopev2":{ + "type":"gem", + "skin":"redenvelopev2", + "name":"Red Envelope", + "explanation":"Congratulations and prosperity", + "g":24000, + "e":1, + "s":True, + "a":True, + "event":True, + }, + "redenvelopev3":{ + "type":"gem", + "skin":"redenvelopev3", + "name":"Red Envelope", + "explanation":"Congratulations and prosperity", + "g":24000, + "e":1, + "s":True, + "a":True, + "event":True, + }, + "redenvelopev4":{ + "type":"gem", + "skin":"redenvelopev4", + "name":"Red Envelope", + "explanation":"Congratulations and prosperity", + "g":24000, + "e":1, + "s":True, + "a":True, + "event":True, + }, + "greenenvelope":{ + "type":"gem", + "skin":"greenenvelope", + "name":"Green Envelope", + "explanation":"Congratulations and prosperity", + "g":24000, + "e":1, + "s":True, + "a":True, + "event":True, + }, + # "greenenvelopev2":{ + # "type":"gem", + # "skin":"greenenvelope", + # "name":"Green Envelope", + # "explanation":"Congratulations and prosperity", + # "g":24000, + # "e":1, + # "s":True, + # "a":True, + # "event":True, + # }, +} + +misc={ + "stand0":{ + "type":"stand", + "skin":"stand0", + "stand":"stand0", + "name":"Merchant Stand", + "explanation":"You can become a merchant using this item.", + #"cash":2320, + "g":40000, + }, + "stand1":{ + "type":"stand", + "skin":"stand1", + "stand":"stand1", + "name":"Merchant Stand [Sell+Buy]", + "explanation":"You can become a merchant using this item.", + "ignore":True, + #"cash":2320, + "g":400000, + }, + "tracker":{ + "type":"tracker", + "skin":"tracker", + "name":"Tracktrix", + "explanation":"A tool that tracks all your experiences and encounters in Adventure Land so you can learn from them and grow as an adventurer!", + #"ignore":True, + "special":True, + "g":12, + "acolor":"#B969CE", + "action":"INTERFACE!", + "onclick":"socket.emit('tracker')", + }, + "computer":{ + "type":"computer", + "skin":"ancientcomputer", + #"cash":1600, + "name":"Ancient Computer", + "special":True, + "stand":"cstand", #currently hardcoded at get_trade_slots + "explanation":"Networks you to NPC's and extends the CODE capabilities.", + "g":64000000, + }, + "supercomputer":{ + "type":"computer", + "skin":"ancientcomputer", + #"cash":1600, + "name":"Super Computer", + "special":True, + "stand":"cstand", #currently hardcoded at get_trade_slots + "explanation":"Networks you to NPC's, extends the CODE capabilities and tracks your encounters.", + "g":64000000, + }, + "stick":{ + "type":"misc", + "skin":"stick", + "g":299999, + "name":"Stick", + "explanation":"...", + "a":True, + "upgrade":{ + + }, + "grades":[4,7], + }, + "coal":{ + "type":"misc", + "skin":"coal", + "g":10, + "name":"Coal", + "explanation":"...", + "a":True, + "compound":{ + + } + }, + "glitch":{ + "type":"misc", + "skin":"glitch", + "g":10000, + "name":"A Glitch", + "explanation":"Huh?! ??!", + "ignore":True, + "event":True, + "a":True, + "e":1, + }, + "5bucks":{ + "type":"misc", + "skin":"5bucks", + "g":5, + "name":"Old Paper Money", + "explanation":"It's not gold. Must be worthless.", + "s":True, + "rare":True, + "e":1, + }, + "confetti":{ + "type":"throw", + "skin":"confetti", + "g":20, + "name":"Pack of Confetti's", + "explanation":"To celebrate good times", + "s":True, + "throw":True, + "action":"THROW!", + "onclick":"socket.emit('throw',{num:locate_item('confetti'),x:character.real_x,y:character.real_y}); push_deferred('throw')", + }, + "firecrackers":{ + "type":"throw", + "skin":"firecrackers", + "g":20, + "name":"Firecracker", + "explanation":"Scary but harmless", + "s":True, + "throw":True, + "action":"THROW!", + "onclick":"socket.emit('throw',{num:locate_item('firecrackers'),x:character.real_x,y:character.real_y}); push_deferred('throw')", + }, + "smoke":{ + "type":"throw", + "skin":"smoke", + "g":20, + "name":"Pouch of Poof", + "explanation":"A pyrotechnic pouch developed for those who want to feel like Rogue's", + "s":100, + "throw":True, + "action":"THROW!", + "onclick":"socket.emit('throw',{num:locate_item('smoke'),x:character.real_x,y:character.real_y}); push_deferred('throw')", + }, + "snowball":{ + "type":"throw", + "skin":"snowball", + "g":1, + "name":"Snowball", + "explanation":"Be careful not to hit someone in the ear!", + "s":200, + }, + "figurine":{ + "type":"spawner", + "skin":"figurine", + "spawn":"terracota", + "name":"Terracota Army Figurine", + "ignore":True, + "note":"Summons an ancient soldier to fight for you", + "action":"BREAK!", + "s":True, + "g":40000, + }, + "pvptoken":{ + "type":"token", + "skin":"pvptoken", + "name":"PVP Token", + "explanation":"A token representing valour in battles. Collect them from PVP events and exchange them for treasures!", + "s":True, + "g":24000, + }, + "funtoken":{ + "type":"token", + "skin":"funtoken", + "name":"Fun Token", + "explanation":"A token representing fun with friends. Collect them from Daily events and exchange them for treasures!", + "s":True, + "g":12000, + }, + "monstertoken":{ + "type":"token", + "skin":"monstertoken", + "name":"Monster Token", + "explanation":"A token representing the hunt. You made Adventure Land a safer place for all. Be proud!", + "npc":"monsterhunter", + "s":True, + "g":12000, + }, + "friendtoken":{ + "type":"token", + "skin":"friendtoken", + "name":"Friend Token", + "explanation":"A token representing friendship. Awarded each time a friend joins the adventure!", + "s":True, + "g":36000, + }, + "emptyheart":{ + "type":"material", + "skin":"emptyheart", + "name":"Empty Heart", + "explanation":"A cold empty stone heart", + "s":True, + "g":12000, + "event":True, + }, + "fieldgen0":{ + "type":"spawner", + "skin":"fieldgen0", + "spawn":"fieldgen0", + "name":"Dampening Field Generator", + "explanation":"Summon a robot generating a dampening field that prevents teleportation of any kind!", + "g":2000000, + }, +} + +quest={ + "seashell":{ + "type":"quest", + "skin":"seashell", + "name":"Seashell", + "explanation":"A beautiful seashell.", + "g":800, + "e":20, + "s":True, + "quest":"seashell", + }, + "leather":{ + "type":"quest", + "skin":"leather", + "name":"Leather", + "explanation":"A Leather piece.", + "g":3000, + "e":40, + "s":True, + "quest":"leather", + }, + "gemfragment":{ + "type":"quest", + "skin":"gemfragment", + "name":"Gem Fragment", + "explanation":"Beautiful, yet broken. Would be extremely valuable if they were whole.", + "g":32000, + "e":50, + "s":True, + "quest":"gemfragment", + }, + "ornament":{ + "type":"quest", + "skin":"ornament", + "name":"Xmas Ornament", + "explanation":"A beautiful ornament. A bunch of these could decorate the trees of Winterland.", + "g":3000, + "e":20, + "s":True, + #"quest":"ornament", #xmas + }, + "lostearring":{ + "type":"earring", + "skin":"lostearring", + "name":"Gold Earring", + "explanation":"Looks valuable", + "g":360000, + "grades":[0,2], + "e":1, + "edge":-2, + "a":True, + "compound":{}, + "quest":"lostearring", + }, + "stonekey":{ + "type":"dungeon_key", + "skin":"stonekey", + "name":"The Stone Key", + "opens":"therush", + #"ignore":True, + "g":50000, + "explanation":"A stone key, imbued with magical energy.", + "s":10, + }, + "cryptkey":{ + "type":"dungeon_key", + "skin":"cryptkey", + "name":"The Crypt Key", + "opens":"crypt", + #"ignore":True, + "g":50000, + "explanation":"A key, imbued with magical energy.", + "s":10, + }, + "frozenkey":{ + "type":"dungeon_key", + "skin":"frozenkey", + "name":"The Frozen Cave Key", + "opens":"winter_instance", + #"ignore":True, + "g":50000, + "explanation":"A key, imbued with magical energy.", + "s":10, + }, + "tombkey":{ + "type":"dungeon_key", + "skin":"tombkey", + "name":"The Tomb Key", + "opens":"tomb", + #"ignore":True, + "g":50000, + "explanation":"A key, imbued with magical energy.", + "s":10, + }, + "bkey":{ + "type":"bank_key", + "skin":"bkey", + "name":"The Bank Key", + "unlocks":"bank_b", + #"ignore":True, + "g":5000000, + "s":5, + "explanation":"Key to the bank's basement", + "action":"UNLOCK", + "onclick":"socket.emit('activate',{num:locate_item('bkey')})", + }, + "ukey":{ + "type":"bank_key", + "skin":"ukey", + "name":"The Bank Key", + "unlocks":"bank_u", + #"ignore":True, + "s":3, + "g":50000000, + "explanation":"Key to the bank's underground", + "action":"UNLOCK", + "onclick":"socket.emit('activate',{num:locate_item('ukey')})", + }, + "dkey":{ + "type":"bank_key", + "skin":"dkey", + "name":"Diamond Key", + #"ignore":True, + "s":2, + "g":72000000, + "explanation":"A key that unlocks any teller!", + "action":"UNLOCK", + "onclick":"socket.emit('activate',{num:locate_item('dkey')})", + }, + "x0":{ + "type":"quest", + "skin":"x0", + "name":"Quantum Piece", + "g":4000, + "s":True, + "a":True, + "event":True, + "explanation":"A unique component of a curious puzzle", + }, + "x1":{ + "type":"quest", + "skin":"x1", + "name":"Quantum Piece", + "g":4000, + "s":True, + "a":True, + "event":True, + "explanation":"A unique component of a curious puzzle", + }, + "x2":{ + "type":"quest", + "skin":"x2", + "name":"Quantum Piece", + "g":4000, + "s":True, + "a":True, + "event":True, + "explanation":"A unique component of a curious puzzle", + }, + "x3":{ + "type":"quest", + "skin":"x3", + "name":"Quantum Piece", + "g":4000, + "s":True, + "a":True, + "event":True, + "explanation":"A unique component of a curious puzzle", + }, + "x4":{ + "type":"quest", + "skin":"x4", + "name":"Quantum Piece", + "g":4000, + "s":True, + "a":True, + "event":True, + "explanation":"A unique component of a curious puzzle", + }, + "x5":{ + "type":"quest", + "skin":"x5", + "name":"Quantum Piece", + "g":4000, + "s":True, + "a":True, + "event":True, + "explanation":"A unique component of a curious puzzle", + }, + "x6":{ + "type":"quest", + "skin":"x6", + "name":"Quantum Piece", + "g":4000, + "s":True, + "a":True, + "event":True, + "explanation":"A unique component of a curious puzzle", + }, + "x7":{ + "type":"quest", + "skin":"x7", + "name":"Quantum Piece", + "g":4000, + "s":True, + "a":True, + "event":True, + "explanation":"A unique component of a curious puzzle", + }, + "x8":{ + "type":"quest", + "skin":"x8", + "name":"Quantum Piece", + "g":4000, + "s":True, + "a":True, + "event":True, + "explanation":"A unique component of a curious puzzle", + }, + "xbox":{ + "type":"quest", + "skin":"xbox", + "name":"Xmas Box", + "g":1000000, + "e":1, + "s":True, + "a":True, + "explanation":"Finally... They all came together. A unique gift lies within this box. Take it to Xyn to be unlocked.", + }, + "egg0":{ + "type":"quest", + "skin":"egg0", + "name":"Easter Egg", + "g":4000, + "s":True, + "explanation":"A uniquely painted Egg!", + }, + "egg1":{ + "type":"quest", + "skin":"egg1", + "name":"Easter Egg", + "g":4000, + "s":True, + "explanation":"A uniquely painted Egg!", + }, + "egg2":{ + "type":"quest", + "skin":"egg2", + "name":"Easter Egg", + "g":4000, + "s":True, + "explanation":"A uniquely painted Egg!", + }, + "egg3":{ + "type":"quest", + "skin":"egg3", + "name":"Easter Egg", + "g":4000, + "s":True, + "explanation":"A uniquely painted Egg!", + }, + "egg4":{ + "type":"quest", + "skin":"egg4", + "name":"Easter Egg", + "g":4000, + "s":True, + "explanation":"A uniquely painted Egg!", + }, + "egg5":{ + "type":"quest", + "skin":"egg5", + "name":"Easter Egg", + "g":4000, + "s":True, + "explanation":"A uniquely painted Egg!", + }, + "egg6":{ + "type":"quest", + "skin":"egg6", + "name":"Easter Egg", + "g":4000, + "s":True, + "explanation":"A uniquely painted Egg!", + }, + "egg7":{ + "type":"quest", + "skin":"egg7", + "name":"Easter Egg", + "g":4000, + "s":True, + "explanation":"A uniquely painted Egg!", + }, + "egg8":{ + "type":"quest", + "skin":"egg8", + "name":"Easter Egg", + "g":4000, + "s":True, + "explanation":"A uniquely painted Egg!", + }, + "goldenegg":{ + "type":"quest", + "skin":"goldenegg", + "name":"Golden Egg", + "g":60000, + "e":1, + "event":True, + "s":True, + "a":True, + "explanation":"Nope, it's not painted, an actual golden egg!", + }, + "basketofeggs":{ + "type":"quest", + "skin":"basketofeggs", + "name":"Basket of Easter Eggs", + "g":20000, + "e":1, + "s":True, + #"a":True, + "explanation":"A basket full of unique easter eggs. You can probably exchange this for a cool reward.", + }, + "frozenstone":{ + "type":"activator", + "skin":"frozenstone", + "name":"Frozen Stone", + "g":20000, + "s":True, + #"a":True, + "explanation":"It's strangely not cold, must be a magical artifact.", + "action":"SHAKE", + "onclick":"socket.emit('activate',{num:locate_item('frozenstone')})", + }, +} + +pets={ + "flute":{ + "type":"flute", + "skin":"flute", + "name":"Flute", + "explanation":"The sound of each flute is unique and mesmerizing. Your pets will easily recognize the sound of yours and come to your call.", + "g":200000000, + }, + "puppyer":{ + "type":"petlicence", + "skin":"puppyer", + #"gain":"luck", + "name":"Licence to Adopt a Puppy", + "explanation":"Lets you adopt a puppy once they are ready. You'll have to wait a bit until they are ready to be adopted tho!", + "g":10000, + "s":True, + }, + "chrysalis0":{ + "type":"chrysalis", + "skin":"goldenegg", + "name":"Dragold's Chrysalis", + "ignore":True, + "monster":"dragold", + #"explanation":"", + "g":40000, + "grade":0, + "a":True, + }, + "puppy1":{ + "type":"chrysalis", + "skin":"egg2", + "name":"Egg", + "ignore":True, + "monster":"puppy1", + "explanation":"A vibrant egg, it's inhabitant seems eager to get out.", + "g":40000, + "grade":0, + "a":True, + }, + "kitty1":{ + "type":"chrysalis", + "skin":"egg1", + "name":"Egg", + "monster":"kitty1", + "ignore":True, + "explanation":"A vibrant egg, it's inhabitant seems eager to get out.", + "g":40000, + "grade":0, + "a":True, + }, + "monsterbox":{ + "type":"container", + "ignore":True, + "skin":"armorbox", + "name":"Monster Box", + "explanation":"A magical pet world inside a box.", + "g":120000, + "grade":0, + }, +} + +orbs={ + "orbg":{ + "type":"orb", + "skin":"orbg", + "str":2, + "int":2, + "dex":2, + "compound":{ + "str":1, + "int":1, + "dex":1, + }, + "name":"Orb of Beginnings", + "g":60000, + "grades":[4,6], + }, + "tigerstone":{ + "set":"tiger", + "type":"orb", + "skin":"tigerstone", + "vit":10, + "armor":30, + "str":2, + "int":1, + "dex":2, + "speed":1, + "compound":{ + "vit":4, + "str":1, + "int":0.5, + "dex":1, + }, + "name":"Tiger Stone", + "g":600000, + "grades":[0,1], + }, + "vorb":{ + "set":"vampires", + "type":"orb", + "skin":"vorb", + "courage":1, + "pcourage":1, + "compound":{ + "courage":1, + }, + "name":"Vampiric Canine Teeth", + "g":12000000, + "grades":[0,0], + }, + "orbofvit":{ + "type":"orb", + "skin":"orbofvit", + "vit":10, + "compound":{ + "vit":4, + }, + "name":"Orb of Vitality", + "g":240000, + "grades":[1,4], + "edge":-2, + }, + "orbofint":{ + "type":"orb", + "skin":"orbofint", + "int":4, + "compound":{ + "int":3, + }, + "name":"Orb of Intelligence", + "g":240000, + "grades":[1,4], + "edge":-2, + }, + "orbofstr":{ + "type":"orb", + "skin":"orbofstr", + "str":4, + "compound":{ + "str":3, + }, + "name":"Orb of Strength", + "g":240000, + "grades":[1,4], + "edge":-2, + }, + "orbofdex":{ + "type":"orb", + "skin":"orbofdex", + "dex":4, + "compound":{ + "dex":3, + }, + "name":"Orb of Dexterity", + "g":240000, + "grades":[1,4], + "edge":-2, + }, + "orbofsc":{ + "set":"holidays", + "type":"orb", + "skin":"orbofsc", + "mp":200, + "ability":"secondchance", + "attr0":1, + "vit":2, + "str":2, + "int":2, + "dex":2, + "compound":{ + "mp":100, + "attr0":1, + "vit":1, + "str":1, + "int":2, + "dex":1, + }, + "name":"Orb of Second Chances", + "g":120000, + "grades":[0,0], + "a":True, + }, + "charmer":{ + "type":"orb", + "skin":"charmer", + "name":"Charmer", + "vit":10, + "ability":"charm", + "attr0":1, + "compound":{ + "vit":10, + "attr0":1, + }, + "g":120000, + "grades":[0,3], + "event":True, + }, + "rabbitsfoot":{ + "type":"orb", + "skin":"rabbitsfoot", + "luck":10, + "compound":{ + "luck":5, + }, + "name":"Rabbit's Foot", + "g":120000, + "grades":[0,0], + "a":True, + "explanation":"Taken from a rabbit who lived a long and happy life, after the natural death occurred, with pre-consent", + }, + "talkingskull":{ + "type":"orb", + "skin":"talkingskull", + "xp":5, + "compound":{ + "xp":5, + }, + "name":"Yorick the Talking Skull", + "explanation":"Endless wisdom", + "g":96000, + "grades":[1,2], + "a":True, + }, + "jacko":{ + "type":"orb", + "skin":"jacko", + "rpiercing":20, + "compound":{ + "rpiercing":15, + }, + "name":"Jack-o Lantern", + #"explanation":"Before the halloween event comes to an end, the Jack-o shall receive it's true power!", + "ability":"scare", + "g":96000, + "grades":[2,4], + "a":True, + "cx":{ + "scale":0.5, + #"extension":True, + } + }, + "ftrinket":{ + "type":"orb", + "skin":"ftrinket", + "vit":2, + "str":2, + "int":2, + "dex":2, + "armor":5, + "speed":0.5, + "compound":{ + "armor":5, + "vit":3, + "speed":1, + }, + "name":"Trinket of Faith", + "explanation":"Good things come to those who wait", + "g":96000, + "grades":[1,3], + "a":True, + }, +} + +#Orb of Vitality: 120 +120 +#Orb of Armor: 40 +20 +#Orb of Res.: 40 +20 +#Orb of Int.: 6 +4 +#Orb of Str.: 6 +4 +#Orb of Dex.: 6 +4 +#Orb of Swift.: 1% Evasion + Speed+3 | 2%/+1 +#Orb of Refl.: 1% Reflection + 4 Dex | 2% Reflection + 2 Dex +#Orb of Rage.: 1% Crit + 30 A.Piercing + 30 R.Piercing || 1% Crit + 10 + 10 +#Orb of Lifesteal: 2% Lifesteal + 120HP | 1% + 60HP + +elixirs={ + "eggnog":{ + "type":"elixir", + "skin":"eggnog", + "hp":1200, + "evasion":2.5, + #"armor":-40, + #"resistance":-60, + "duration":48, + "name":"Eggnog", + "explanation":"Fills your heart with warmth and joy.", + "s":True, + "g":6000, + }, + "vblood":{ + "set":"vampires", + "type":"elixir", + "skin":"vblood", + "lifesteal":20, + #"armor":-40, + #"resistance":-60, + "duration":1, + "name":"Vampire's Blood", + "explanation":"Just a tiny sip", + "s":True, + "g":240000, + "withdrawal":"withdrawal", + }, + "gum":{ + "type":"elixir", + "skin":"gum", + "hp":40, + "reflection":0.2, + "duration":120, + "name":"Gum", + "explanation":"Nice flavour", + "s":True, + "eat":True, + "g":100, + }, + "hotchocolate":{ + "type":"elixir", + "skin":"hotchocolate", + "vit":30, + "armor":30, + "resistance":30, + "duration":1, + "name":"Hot Chocolate", + "explanation":"Fills your heart with warmth.", + "s":True, + "g":6000, + }, + "pumpkinspice":{ + "type":"elixir", + "skin":"pumpkinspice", + "mp":-400, + "crit":5, + "reflection":2, + "duration":8, + "name":"Pumpkin Spice Latte", + "explanation":"Produced in bulk during the Halloween season. WARNING: The pumpkin comes from a non-vegetable source", + "s":True, + "g":200, + }, + "cake":{ + "type":"elixir", + "skin":"cake", + "hp":2400, + "speed":-30, + "duration":6, + "name":"Piece of Cake", + "explanation":"Delicious.",#" [Note from Wizard: I forgot to buy the Cake. Have this placeholder for now instead :]", + "s":True, + "eat":True, + "g":100, + }, + "greenbomb":{ + "type":"elixir", + "skin":"greenbomb", + "dex":120, + "str":50, + "crit":10, + "speed":30, + "resistance":-800, + "duration":0.002, + "name":"Green Bomb", + "explanation":"It's a candy with very questionable ingredients, might be addictive.", + "a":True, + "s":True, + "eat":True, + "withdrawal":"withdrawal", + "g":10000, + }, + "swirlipop":{ + "type":"elixir", + "skin":"swirlipop", + "evasion":90, + "resistance":-300, + "int":-40, + "duration":0.008, + "name":"Swirlipop", + "explanation":"A dizzying candy, has some benefits.", + "a":True, + "s":True, + "eat":True, + "withdrawal":"withdrawal", + "g":10000, + }, + "xshot":{ + "type":"elixir", + "skin":"xshot", + "duration":0.000000000001, + "name":"X-Shot", + "explanation":"Increases your luck in gambling a hundredfold! Warning: Some establishments might screen you before taking a bet. Can be detected in your blood for 12 hours", + "s":40, + "g":1, + "withdrawal":"xshotted", + }, + "espresso":{ + "type":"elixir", + "skin":"espresso", + "speed":24, + "duration":0.0005, + "name":"Espresso", + "s":True, + "g":12000, + }, + "whiskey":{ + "type":"elixir", + "skin":"whiskey", + "speed":-12, + "miss":50, + "apiercing":500, + "duration":0.1, + "name":"Whiskey On The Rocks", + "s":True, + "g":120000, + }, + "wine":{ + "type":"elixir", + "skin":"wine", + "speed":-12, + "miss":32, + "vit":32, + "duration":0.1, + "name":"Red Wine", + "s":True, + "g":40000, + }, + "ale":{ + "type":"elixir", + "skin":"ale", + "speed":-6, + "miss":20, + "str":24, + "duration":0.05, + "name":"Ale", + "s":True, + "g":24000, + }, + "pico":{ + "type":"elixir", + "skin":"pico", + "miss":15, + "crit":20, + "rpiercing":100, + "duration":0.05, + "name":"Pixel Colada", + "s":True, + "g":150000, + }, + "blue":{ + "type":"elixir", + "skin":"blue", + "miss":24, + "evasion":50, + "duration":0.05, + "name":"Blue Horizon", + "s":True, + "g":150000, + }, + "bunnyelixir":{ + "type":"elixir", + "skin":"bunnyelixir", + "hp":400, + "dex":4, + "vit":15, + "mp":300, + "speed":12, + #"armor":-40, + #"resistance":-60, + "duration":2, + "name":"Bunny Energy Drink", + "explanation":"Ingredients: Rabbit sweat, bubble gum flavour", + "s":True, + "g":6000, + }, + "elixirvit0":{ + "type":"elixir", + "skin":"elixirvit0", + "vit":8, + "duration":12, + "name":"Elixir of Vitality", + "s":True, + "g":6000, + }, + "elixirvit1":{ + "type":"elixir", + "skin":"elixirvit1", + "vit":12, + "duration":24, + "name":"Elixir of Greater Vitality", + "s":True, + "g":20000, + }, + "elixirvit2":{ + "type":"elixir", + "skin":"elixirvit2", + "vit":18, + "duration":48, + "name":"Elixir of Extreme Vitality", + "s":True, + "g":120000, + "a":True, + }, + "elixirstr0":{ + "type":"elixir", + "skin":"elixirstr0", + "str":6, + "duration":12, + "name":"Elixir of Strength", + "s":True, + "g":6000, + }, + "elixirstr1":{ + "type":"elixir", + "skin":"elixirstr1", + "str":8, + "duration":24, + "name":"Elixir of Greater Strength", + "s":True, + "g":20000, + }, + "elixirstr2":{ + "type":"elixir", + "skin":"elixirstr2", + "str":12, + "duration":48, + "name":"Elixir of Extreme Strength", + "s":True, + "g":120000, + "a":True, + }, + "elixirdex0":{ + "type":"elixir", + "skin":"elixirdex0", + "dex":6, + "duration":12, + "name":"Elixir of Dexterity", + "s":True, + "g":6000, + }, + "elixirdex1":{ + "type":"elixir", + "skin":"elixirdex1", + "dex":8, + "duration":24, + "name":"Elixir of Greater Dexterity", + "s":True, + "g":20000, + }, + "elixirdex2":{ + "type":"elixir", + "skin":"elixirdex2", + "dex":12, + "duration":48, + "name":"Elixir of Extreme Dexterity", + "s":True, + "g":120000, + "a":True, + }, + "elixirint0":{ + "type":"elixir", + "skin":"elixirint0", + "int":6, + "duration":12, + "name":"Elixir of Intelligence", + "s":True, + "g":6000, + }, + "elixirint1":{ + "type":"elixir", + "skin":"elixirint1", + "int":8, + "duration":24, + "name":"Elixir of Greater Intelligence", + "s":True, + "g":20000, + }, + "elixirint2":{ + "type":"elixir", + "skin":"elixirint2", + "int":12, + "duration":48, + "name":"Elixir of Extreme Intelligence", + "s":True, + "g":120000, + "a":True, + }, + "elixirluck":{ + "type":"elixir", + "skin":"elixirluck", + "luck":16, + "duration":12, + "name":"Liquid Luck", + "s":True, + "g":240000, + "a":True, + }, + "elixirfires":{ + "type":"elixir", + "skin":"elixirfires", + "firesistance":30, + "duration":2, + "name":"Elixir of Fire Resistance", + "s":40, + "g":240000, + "a":True, + }, + "elixirfzres":{ + "type":"elixir", + "skin":"elixirfzres", + "fzresistance":30, + "duration":2, + "name":"Elixir of Freeze Resistance", + "s":40, + "g":240000, + "a":True, + }, + "elixirpnres":{ + "type":"elixir", + "skin":"elixirpnres", + "pnresistance":30, + "duration":2, + "name":"Elixir of Poison Resistance", + "s":40, + "g":240000, + "a":True, + }, +} + +for name in elixirs: + elixirs[name]["skin_a"]=elixirs[name]["skin"] + +skill_items={ + "poison":{ + "type":"skill_item", + "name":"Poison Sack", + "skin":"poison", + "explanation":"An organic poison sack, can be used to coat weapons or arrows.", + "s":True, + "g":1000, + }, + "shadowstone":{ + "type":"skill_item", + "name":"Shadow Stone", + "skin":"shadowstone", + "explanation":"A stone piece with curious properties, allows the bearer to shift to a parallel reality.", + "s":True, + "g":800, + } +} + +crafting_items={ + "mbones":{ + "type":"material", + "name":"Mummy Bones", + "skin":"mbones", + "explanation":"Scattered, ugly bones.", + "s":True, + "g":16, + }, + "cscale":{ + "type":"material", + "name":"Croc Scale", + "skin":"cscale", + "explanation":"A very hard scale, can be sewn onto armors.", + "s":True, + "g":200, + }, + "snakeoil":{ + "type":"pot", + "name":"Snake Oil", + "skin":"snakeoil", + "gives":[["hp",-100]], + #"explanation":"?", + "debuff":True, + "rare":True, + "s":True, + "g":200, + }, + "feather0":{ + "type":"material", + "name":"Magical Feather", + "skin":"feather0", + "explanation":"Holding this, you understand how those huge birds can fly, it's not a normal feather!", + "s":True, + "g":800, + }, + "feather1":{ + "type":"material", + "name":"Harpy Feather", + "skin":"feather0", + "explanation":"Holding this, you understand how those huge harpies can fly, it's not a normal feather!", + "s":True, + "g":800, + }, + "bronzeingot":{ + "type":"material", + "name":"Bronze Ingot", + "skin":"bronzeingot", + "explanation":"Solid Bronze", + "offering":0.1, + "s":100, + "g":40000, + }, + "goldingot":{ + "type":"material", + "name":"Gold Ingot", + "skin":"goldingot", + "explanation":"Solid Gold", + "offering":1.1, + "s":100, + "g":2000000, + }, + "platinumingot":{ + "type":"material", + "name":"Platinum Ingot", + "skin":"platinumingot", + "explanation":"Solid Platinum", + "offering":2, + "s":100, + "g":40000000, + }, + "bronzenugget":{ + "type":"material", + "name":"Bronze Nugget", + "skin":"bronzenugget", + "explanation":"Ideal for crafting", + "s":1000, + "g":3200, + }, + "goldnugget":{ + "type":"material", + "name":"Gold Nugget", + "skin":"goldnugget", + "explanation":"Ideal for crafting", + "offering":0, + "s":1000, + "g":120000, + }, + "platinumnugget":{ + "type":"material", + "name":"Platinum Nugget", + "skin":"platinumnugget", + "explanation":"Ideal for crafting", + "offering":1, + "s":1000, + "g":5200000, #5.2 so it gets announced [21/08/18] + }, + "electronics":{ + "type":"material", + "name":"Electronics", + "skin":"electronics", + "explanation":"Various random electronic components", + "s":True, + "g":7, + }, + "spidersilk":{ + "type":"material", + "name":"Spider Silk", + "skin":"spidersilk", + "explanation":"A durable yet sticky material", + "s":True, + "g":300, + } +} + +sets={ + "tiger":{ + "name":"Tigers'", + "items":["tigerhelmet","tigershield","tigercape","tigerstone"], + "1":{ + + }, + "2":{ + "vit":1, + }, + "3":{ + "str":5, + "int":5, + "dex":5, + }, + "4":{ + "speed":3, + } + }, + "vampires":{ + "name":"Vampires", + "items":["mcape","vgloves","vboots","vattire","vcape","vorb","vhammer","vdagger","vstaff","vsword","vblood","vring"], + "1":{ + + }, + "2":{ + "vit":10, + }, + "3":{ + "lifesteal":1, + }, + }, + "mpx":{ + "name":"MP X", + "items":["mpxbelt","mpxgloves","mpxamulet"], + "1":{ + + }, + "2":{ + "mp":100, + }, + "3":{ + "mp":500, + "speed":1, + "rpiercing":20, + }, + }, + "fury":{ + "name":"Rage and Fury", + "items":["suckerpunch","suckerpunch","fury","fallen"], + "1":{ + + }, + "2":{ + "str":1, + }, + "3":{ + "dex":2, + }, + "4":{ + "apiercing":32, + }, + }, + "legends":{ + "name":"The Legends", + "items":["warpvest","starkillers","powerglove","goldenpowerglove"], + "1":{ + }, + "2":{ + }, + "3":{ + "for":10, + }, + "4":{ + "for":2, + }, + }, + "swift":{ + "name":"Swift Judgement", + "items":["wingedboots","fierygloves"], + "1":{ + }, + "2":{ + "dex":1, + }, + }, + "holidays":{ + "name":"Holiday Spirit", + "items":["xmashat","xmassweater","xmasshoes","xmaspants","mittens","supermittens","santasbelt","ornamentstaff","candycanesword","merry","orbofsc","mearring","xmace","ringhs","sweaterhs","wbookhs"], + "explanation":"Every month is December with this set!", + "1":{ + }, + "2":{ + "dex":1, + }, + "3":{ + "vit":1, + }, + "4":{ + "luck":6, + }, + "5":{ + + }, + 6:{ + + }, + "7":{ + + } + }, + "wanderers":{ + "name":"Wanderer's Set", + "items":["wcap","wattire","wbreeches","wgloves","wshoes"], + "explanation":"Wanderer was a curious adventurer. Traveling from place to place. The items he left over make up a very lucky set when they are combined.", + "1":{ + }, + "2":{ + "hp":200, + }, + "3":{ + "mp":100, + }, + "4":{ + "gold":10, + }, + "5":{ + "luck":16, + #"apiercing":40, + } + }, + "wt3":{ + "name":"Heavy Armor", + "items":["hhelmet","harmor","hboots","hgloves","hpants"], + "1":{ + "for":2, + }, + "2":{ + "for":4, + }, + "3":{ + "for":6, + }, + "4":{ + "for":10, + }, + "5":{ + "for":16, + } + }, + "wt4":{ + "name":"Darkforge Armor", + "items":["xhelmet","xarmor","xboots","xgloves","xpants"], + "1":{ + "for":3, + }, + "2":{ + "for":5, + }, + "3":{ + "for":7, + }, + "4":{ + "for":15, + }, + "5":{ + "for":22, + } + }, + "rugged":{ + "name":"Rugged Set", + "items":["helmet1","coat1","shoes1","gloves1","pants1"], + "explanation":"Just the right amount of protection for the agile wearer", + "1":{ + }, + "2":{ + "str":1, + "dex":1, + "int":1, + }, + "3":{ + "armor":20, + "resistance":20, + "range":2, + }, + "4":{ + "for":8, + }, + "5":{ + "speed":4, + "phresistance":25, + "stresistance":20, + } + }, + "mwarrior":{ + "name":"Monster Hunter Warrior", + "items":["mwhelmet","mwarmor","mwgloves","mwpants","mwboots"], + "explanation":"A set for a noble warrior who serves our realm!", + "1":{ + }, + "2":{ + "str":2, + }, + "3":{ + "speed":1, + "str":3, + }, + "4":{ + "apiercing":40, + }, + "5":{ + "crit":5, + "phresistance":25, + "stresistance":20, + } + }, + "mmage":{ + "name":"Monster Hunter Mage", + "items":["mmhat","mmarmor","mmgloves","mmpants","mmshoes"], + "explanation":"A set for a noble mage who serves our realm!", + "1":{ + }, + "2":{ + "int":2, + }, + "3":{ + "speed":2, + "int":3, + }, + "4":{ + "rpiercing":40, + }, + "5":{ + "crit":2, + "phresistance":25, + "stresistance":20, + } + }, + "mpriest":{ + "name":"Monster Hunter Priest", + "items":["mphat","mparmor","mpgloves","mppants","mpshoes"], + "explanation":"A set for a noble priest who serves our realm!", + "1":{ + }, + "2":{ + "int":3, + }, + "3":{ + "speed":2, + "int":3, + }, + "4":{ + "rpiercing":120, + }, + "5":{ + "mp":2000, + "phresistance":25, + "stresistance":20, + } + }, + "mranger":{ + "name":"Monster Hunter Ranger", + "items":["mrnhat","mrnarmor","mrngloves","mrnpants","mrnboots"], + "explanation":"A set for a noble ranger who serves our realm!", + "1":{ + }, + "2":{ + "dex":3, + }, + "3":{ + "speed":2, + "dex":3, + }, + "4":{ + "apiercing":60, + }, + "5":{ + "resistance":100, + "phresistance":25, + "stresistance":20, + } + }, + "mrogue":{ + "name":"Monster Hunter Rogue", + "items":["mrhood","mrarmor","mrgloves","mrpants","mrboots"], + "explanation":"A set for a noble rogue who serves our realm!", + "1":{ + }, + "2":{ + "dex":6, + }, + "3":{ + "speed":3, + "dex":4, + }, + "4":{ + "apiercing":80, + }, + "5":{ + "crit":5, + "phresistance":25, + "stresistance":20, + } + }, + "mmerchant":{ + "name":"Monster Hunter Merchant", + "items":["mchat","mcarmor","mcgloves","mcpants","mcboots"], + "explanation":"A set for a noble merchant who has some friends that serve our realm!", + "1":{ + }, + "2":{ + "vit":6, + "courage":1, + "mcourage":1, + "pcourage":1, + }, + "3":{ + "speed":2, + "vit":8, + "str":3, + }, + "4":{ + "evasion":6, + }, + "5":{ + "for":32, + "courage":2, + "mcourage":2, + "pcourage":2, + "phresistance":25, + "stresistance":20, + } + }, + "bunny":{ + "name":"Bunny Set", + "items":["eears","ecape","epyjamas","eslippers","pinkie","carrotsword"], + "explanation":"An Easter / Bunny themed set!", + "1":{}, + "2":{ + "luck":5, + }, + "3":{ + "vit":3, + }, + "4":{ + "speed":2, + }, + "5":{ + "vit":2, + "cuteness":50, + }, + "6":{ + "vit":2, + }, + }, + # "base":{ + # "name":"Base Items", + # "items":["helmet","coat","pants","gloves","shoes"], + # 1:{ + # "int":10, + # }, + # 2:{ + # "str":10, + # }, + # 3:{ + # "dex":10, + # }, + # 4:{ + # "vit":10, + # }, + # 5:{ + # "evasion":10, + # #"apiercing":40, + # } + # } +} + +for wid in weapons: + weapon=weapons[wid] + if weapon.get("wtype","") in ["dagger","fist","stars"]: + weapon["cx"]=weapon.get("cx",{}) + weapon["cx"]["scale"]=0.5 + #weapon["cx"]["small"]=True + weapon["cx"]["extension"]=True + if weapon.get("wtype","") in ["axe","basher"]: + weapon["cx"]=weapon.get("cx",{}) + weapon["cx"]["large"]=True + +items.update(pots) +items.update(armor) +items.update(weapons) +items.update(offhands) +items.update(accessories) +items.update(scrolls) +items.update(premiums) +items.update(gems) +items.update(materials) +items.update(collectables) +items.update(misc) +items.update(quest) +items.update(orbs) +items.update(elixirs) +items.update(skill_items) +items.update(crafting_items) +items.update(pets) + +for iid in items: + if items[iid].get("grades") and len(items[iid]["grades"])==2: + items[iid]["grades"].append(10) + if items[iid].get("grades") and len(items[iid]["grades"])==3: + items[iid]["grades"].append(12) + if items[iid].get("compound"): + items[iid]["grades"][2]=min(6,items[iid]["grades"][2]) + items[iid]["grades"][3]=min(7,items[iid]["grades"][3]) + if items[iid].get("s",False)==True: + items[iid]["s"]=9999 diff --git a/design/items.txt b/design/items.txt new file mode 100644 index 0000000..6dd0adc --- /dev/null +++ b/design/items.txt @@ -0,0 +1,150 @@ +[RINGS] +>NORMAL +Ring of Small Joys +>HIGH +Ring of Armor Piercing - 40+20 Armor Piercing +Ring of Resistence Piercing - 40+20 Resistence Piercing + +>RARE +"Sucker Punch" 2%+1% Lifesteal | 3%+1% Crit | 30+10 Armor Piercing + +[BELTS] +> NORMAL +Belt of HP +> HIGH +Belt of Evasion 3% + 2% +Belt of Anti-Hex 3% + 2% Reflection +> RARE +Belt of the Warrior - 12+3 Str - 20+10 Armor + +[EARRINGS] +Earring of Vitality - 3+2 Vitality +Earring of Dexterity - 3+2 Dexterity +Earring of Strength - 3+2 Strength +Earring of Intelligence - 3+2 Int + +[ORBS] +Orb of Vitality - 7+3 Vitality +Orb of Strength - 6+3 Strength +Orb of Dexterity - 6+3 Dexterity +Orb of Intelligence - 7+3 Intelligence + +[CAPES] +Cape - 20+2 Armor - 4 Stat - 3+1 Vitality + +[QUEST ITEMS] +Leather x 20 | Rope x 5 = Cape +Seashell x 20 = Sea Quest +Ring + Amulet + Earring = House Quest +Old Coin = Desertland Quest + +[SHIELDS] +Shield - + +[WARRIOR WEAPONS] +Blade - T1 - 1H +Fiery Blade - T2 - 1H + + +[Stat Scrolls] +Vitality Scroll +Armor Piercing Scroll - 2X per stat +Resistence Piercing Scroll - 2X per stat +Evasion Scroll - 0.1% per stat +Reflection Scroll - 0.1% per stat + +[Elixirs] +For 4 Stats: + Elixir of Vitality - 5 Vitality + Elixir of Greater Vitality - 10 Vitality + Elixit of Extreme Vitality - 15 Vitality +Elixir of the Dark Mage - 100 Resistence Piercing +Hero's Juice - 100 Armor Piercing + +[Christmas] +Mistletoe - Very, very rare +Candy Cane +Ornament x20 = Quest +[Items] +Mittens +Fluffy Shoes +Orb of Good Spirits - Vitality | All Stats | Ability: Second Chances +Elixir: Eggnog - Speed: -4 Armor: -40 Resistance: -20 HP: 1000 + +[Anniversary] +Orb - 2 Vitality 3 Speed +T3/T4 Items +Birthday Hat +A Ring - Rare + +[Halloween] +Green Pumpkin Head (Green version of the existing Orange one) +Ethereal Essence (Bottled Essence, drops from ghosts) +Ethereal Amulet (Activates a temporary ghost form with high evasion) +Pumpkin Spice Latte (Elixir) +Assassin's Pouch (A Pouch, A Smoke bomb, when dropped, splits smoke, cosmetic item) +A Dagger that drops from Mummies (These weapons are up to your imagination) +A Staff that drops from Mummies +A Sword that drops from Mummies +A Bow that drops from Mummies +A Mace that drops from Mummies +Franky's Belt (Frankestein's Belt, source of his power) +Tuxedo Pants + +[Xmas] +Super Mittens +Quantum Box - Xbox +9 pieces of Xbox +Angel's Wings (Cape) +Hot Chocolate +Warm Scarf +Santa's Belt +Candy Cane Sword +Rudolph's Red Nose (Head Slot / Helmet) +Ornament Staff + +[Buffs] +Server Jump Penalty +Drug Addiction Penalty +Xmas Spirit / Joy +Luck Buff (From Merchants) +Speed Buff + +[Valentines] +Solitaire Ring (Single stone http://www.kay.com/images/products/1508/150866806_MV_ZM.jpg) + +[Chinese New Year] +Red Envelope (Gol scribings) https://i.pinimg.com/originals/de/e6/dd/dee6dd8183be64e4f41985684e7a2054.jpg +License to Adopt a Puppy (A piece of paper / license, it will allow players to get a puppy pet once they are released) +Dragon Scale Armor (Dark coloured, cool looking, hefty armor, chest slot) + +[Game] +Fun Token (We prepared PVP Tokens before, coins, this one will be similar to those, but a colourful coin/token, it will be a reward from daily events) + +[Halloween 2018] +essense of fire and pumpkin heads - create jackolanterns. jackolanterns have a 5% chance to scare the stuff in your vicinity. mobs would run away for 3 seconds and players would "drop" some gold as a chest you can loot when they get a fright and jump. <- removes all targets + +Name: Yorick the Talking Skull +Type: Orb +Stats: +5% EXP + +vampire's blood: potion slot- gives you vampirism 100, scariness 50, strength 50, intelligence 50, dexterity 50, duration 30 mins (or 1 hour), can be combined to increase the duration time (increases by 4 times so ppl wouldn't drink 3 potions to get increased duration, or maybe add in 5 more to stats) and scariness to 60. <- elixir + +Golden Fleece [Cape] + +Philosopher's Stone [Orb] + +Weaver's Bow [Spider-y Bow, or Web-y, casts a web with a %] + +Ethereal Amulet [Introduce] + +Franky Items [Introduce] + +[Halloween] +• Jack-o Lantern - Orb Slot - (Scares away monsters when activated) +• Yorick the Talking Skull (Orb slot, an actual talking skull, logs things in-game, gives +Experience) +• Vampire's Blood (Elixir, gives lifesteal) +• Weaver's Bow (Spider-y Bow, or Web-y, casts a web with a %) +[Others] +• Golden Fleece (Cape) +• Philosopher's Stone (Orb) \ No newline at end of file diff --git a/design/levels.py b/design/levels.py new file mode 100644 index 0000000..136f39e --- /dev/null +++ b/design/levels.py @@ -0,0 +1,267 @@ +# xp=200 +# levels={} +# if 1: +# if 1: +# if 1: +# for i in xrange(200): +# new_xp=xp +# while new_xp>=100: new_xp/=10 +# new_xp=int(new_xp) +# while new_xp*10<=xp: new_xp*=10 +# xp=new_xp +# #self.response.out.write("level %s %sxp %s worms %s 40K's
"%((i+1),xp,xp/200.0,xp/40000.0)) +# skill=1; level=i+1 +# if level>=80: skill=4 +# elif level>=60: skill=3 +# elif level>=40: skill=2 +# levels[i+1]={"xp":xp,"point":skill} +# xp*=1.25 +# json_output=levels + +#NEW ONE: + +# xp=200 +# levels={} +# if 1: +# if 1: +# if 1: +# for i in xrange(200): +# new_xp=xp +# while new_xp>=100: new_xp/=10 +# new_xp=int(new_xp) +# while new_xp*10<=xp: new_xp*=10 +# xp=new_xp +# self.response.out.write("level %s %sxp %s worms %s 40K's
"%((i+1),to_pretty_num(xp),xp/200.0,xp/40000.0)) +# level=i+1 +# levels[i+1]=xp +# if level<60: xp*=1.25 +# elif level<80: xp*=1.2 +# elif level<100: xp*=1.1 +# else: xp*=1.08 +# json_output=levels + +#NEW NEW ONE: [07/10/16] +# xp=200 +# levels={} +# if 1: +# if 1: +# if 1: +# for i in xrange(200): +# new_xp=xp +# while new_xp>=100: new_xp/=10 +# new_xp=int(new_xp) +# while new_xp*10<=xp: new_xp*=10 +# xp=new_xp +# self.response.out.write("level %s %sxp %s worms %s 40K's
"%((i+1),to_pretty_num(xp),xp/200.0,xp/40000.0)) +# level=i+1 +# levels[i+1]=xp +# if level<60: xp*=1.25 +# elif level<75: xp*=1.225 +# elif level<80: xp*=1.2 +# elif level<90: xp*=1.275 +# elif level<100: xp*=1.375 +# else: xp*=1.1 +# json_output=levels + +levels={ + "1": 200, + "2": 250, + "3": 310, + "4": 380, + "5": 470, + "6": 580, + "7": 720, + "8": 900, + "9": 1100, + "10": 1300, + "11": 1600, + "12": 2000, + "13": 2500, + "14": 3100, + "15": 3800, + "16": 4700, + "17": 5800, + "18": 7200, + "19": 9000, + "20": 11000, + "21": 13000, + "22": 16000, + "23": 20000, + "24": 25000, + "25": 31000, + "26": 38000, + "27": 47000, + "28": 58000, + "29": 72000, + "30": 90000, + "31": 110000, + "32": 130000, + "33": 160000, + "34": 200000, + "35": 250000, + "36": 310000, + "37": 380000, + "38": 470000, + "39": 580000, + "40": 720000, + "41": 900000, + "42": 1100000, + "43": 1300000, + "44": 1600000, + "45": 2000000, + "46": 2500000, + "47": 3100000, + "48": 3800000, + "49": 4700000, + "50": 5800000, + "51": 7200000, + "52": 9000000, + "53": 11000000, + "54": 13000000, + "55": 16000000, + "56": 20000000, + "57": 25000000, + "58": 31000000, + "59": 38000000, + "60": 47000000, + "61": 57000000, + "62": 69000000, + "63": 84000000, + "64": 100000000, + "65": 120000000, + "66": 140000000, + "67": 170000000, + "68": 200000000, + "69": 240000000, + "70": 290000000, + "71": 350000000, + "72": 420000000, + "73": 510000000, + "74": 620000000, + "75": 750000000, + "76": 900000000, + "77": 1000000000, + "78": 1200000000, + "79": 1400000000, + "80": 1600000000, + "81": 2000000000, + "82": 2500000000, + "83": 3100000000, + "84": 3900000000, + "85": 4900000000, + "86": 6200000000, + "87": 7900000000, + "88": 10000000000, + "89": 12000000000, + "90": 15000000000, + "91": 20000000000, + "92": 27000000000, + "93": 37000000000, + "94": 50000000000, + "95": 68000000000, + "96": 93000000000, + "97": 120000000000, + "98": 160000000000, + "99": 220000000000, + "100": 300000000000, + "101": 330000000000, + "102": 360000000000, + "103": 390000000000, + "104": 420000000000, + "105": 460000000000, + "106": 500000000000, + "107": 550000000000, + "108": 600000000000, + "109": 660000000000, + "110": 720000000000, + "111": 790000000000, + "112": 860000000000, + "113": 940000000000, + "114": 1000000000000, + "115": 1100000000000, + "116": 1200000000000, + "117": 1300000000000, + "118": 1400000000000, + "119": 1500000000000, + "120": 1600000000000, + "121": 1700000000000, + "122": 1800000000000, + "123": 1900000000000, + "124": 2000000000000, + "125": 2200000000000, + "126": 2400000000000, + "127": 2600000000000, + "128": 2800000000000, + "129": 3000000000000, + "130": 3300000000000, + "131": 3600000000000, + "132": 3900000000000, + "133": 4200000000000, + "134": 4600000000000, + "135": 5000000000000, + "136": 5500000000000, + "137": 6000000000000, + "138": 6600000000000, + "139": 7200000000000, + "140": 7900000000000, + "141": 8600000000000, + "142": 9400000000000, + "143": 10000000000000, + "144": 11000000000000, + "145": 12000000000000, + "146": 13000000000000, + "147": 14000000000000, + "148": 15000000000000, + "149": 16000000000000, + "150": 17000000000000, + "151": 18000000000000, + "152": 19000000000000, + "153": 20000000000000, + "154": 22000000000000, + "155": 24000000000000, + "156": 26000000000000, + "157": 28000000000000, + "158": 30000000000000, + "159": 33000000000000, + "160": 36000000000000, + "161": 39000000000000, + "162": 42000000000000, + "163": 46000000000000, + "164": 50000000000000, + "165": 55000000000000, + "166": 60000000000000, + "167": 66000000000000, + "168": 72000000000000, + "169": 79000000000000, + "170": 86000000000000, + "171": 94000000000000, + "172": 100000000000000, + "173": 110000000000000, + "174": 120000000000000, + "175": 130000000000000, + "176": 140000000000000, + "177": 150000000000000, + "178": 160000000000000, + "179": 170000000000000, + "180": 180000000000000, + "181": 190000000000000, + "182": 200000000000000, + "183": 220000000000000, + "184": 240000000000000, + "185": 260000000000000, + "186": 280000000000000, + "187": 300000000000000, + "188": 330000000000000, + "189": 360000000000000, + "190": 390000000000000, + "191": 420000000000000, + "192": 460000000000000, + "193": 500000000000000, + "194": 550000000000000, + "195": 600000000000000, + "196": 660000000000000, + "197": 720000000000000, + "198": 790000000000000, + "199": 860000000000000, + "200": 940000000000000 +} \ No newline at end of file diff --git a/design/maps.py b/design/maps.py new file mode 100644 index 0000000..94f9466 --- /dev/null +++ b/design/maps.py @@ -0,0 +1,1640 @@ +# 0 front, 1 left, 2 right, 3 back + +#main7 - copy of the long-used production map [27/08/16] +#new_main2+new_main3 - floating shrine prototype +#main8 - main7 with castle + small path/island removed + +maps={ + "old_main":{ + "key":"main5", + "name":"Old Town", + "npcs": + [ + {"name":"Pots","id":"pots","position":[10,10]}, + {"name":"Come Scroll Away","id":"scrolls","position":[112,-152]}, + {"name":"Shrine of Gods","id":"shrine","position":[4,-155]}, + {"name":"Shrine of Combinations","id":"compound","position":[46,-155]}, + {"name":"Armorz","id":"armors","position":[-20,10]}, + {"name":"Weaponz","id":"weapons","position":[40,10]}, + {"name":"Transporter","id":"transporter","position":[180,-210]}, + ], + "monsters":[ + {"type":"goo","position":[-400,0],"radius":220,"count":10}, + {"type":"spider","position":[-300,100],"radius":180,"count":6}, + {"type":"scorpion","position":[-100,100],"radius":180,"count":12}, + {"type":"bat","position":[200,100],"radius":180,"count":5}, + {"type":"dknight2","position":[300,-100],"radius":160,"count":4}, + {"type":"phoenix","position":[0,0],"radius":1200,"count":1}, + ], + "spawns":[[100,100]], + "ignore":True, + }, + "original_main":{ + "ignore":True, + "key":"main", + "name":"Town", + "npcs":[ + {"name":"Shrine of Gods","id":"shrine","position":[319,-178]}, #0 - server.js + {"name":"Shrine of Combinations","id":"compound","position":[362,-178]}, #1 - server.js + + {"name":"Pots","id":"pots","position":[112,40]}, + + #{"name":"Transporter","id":"transporter","position":[163,-197]}, + {"name":"Exchanger","id":"exchange","position":[163,-197]}, + {"name":"Come Scroll Away","id":"scrolls","position":[241,-215]}, + + {"name":"Armorz","id":"armors","position":[-106,-211]}, + {"name":"Weaponz","id":"weapons","position":[61,-220]}, + #{"name":"Ship","id":"ship","position":[832,119]}, + + # {"name":"Firstc","id":"firstc","position":[-106,-180]}, + + {"name":"Lich","id":"lichteaser","position":[1352,64]}, + + {"name":"Zen Girl","id":"appearance","position":[792,800]}, + + {"id":"pvp","positions":[ [-375,-104],[-482,-10,2] ]}, #currently the direction is hard-coded at update_sprite [30/08/16] + + {"name":"Transporter","id":"transporter","position":[409,36]}, + ], + "old_monsters":[ + {"type":"goo","boundary":[-84,95,255,234],"count":12}, + #{"type":"pinkgoo","boundary":[-84,95,255,234],"count":1}, + #{"type":"goblin","boundary":[-84,95,255,234],"count":1}, + {"type":"squig","boundary":[279,201,718,333],"count":7}, + {"type":"bee","boundary":[464,37,744,190],"count":10}, + + {"type":"armadillo","boundary":[-20,295,221,529],"count":6}, + {"type":"squigtoad","boundary":[50,473,534,676],"count":4}, + {"type":"bee","boundary":[440,377,752,567],"count":10}, + + {"type":"spider","boundary":[1045,423,1371,713],"count":9}, + {"type":"scorpion","boundary":[997,733,1374,911],"count":9}, + #{"type":"dknight2","boundary":[820,165,1375,465],"count":6}, + {"type":"croc","boundary":[820,165,1375,465],"count":6}, + + #{"type":"greenfairy","boundary":[690,745,895,850],"count":1}, + {"type":"greenfairy","boundary":[690,745,895,775],"count":1}, + {"type":"redfairy","boundary":[690,745,742,850],"count":1}, + {"type":"bluefairy","boundary":[840,745,895,850],"count":1}, + + #{"type":"phoenix","boundaries":[["main",1042,155,1375,912],["main",820,160,1378,466],["batcave",-210,-170,342,185]],"count":1,"stype":"randomrespawn"}, + ], + "spawns":[ + [41,-71], #0-town + [-271,-9,0], #1-cave exit + [-376,-99,0], #2-arena exit + [-460,63,2], #3-pvp death + [224,48], #4-main death + [600,-42],#5-bank-exit + [408,62,3],#6-front of the transporter + ], + "on_death":["original_main",4], + "doors":[ + [-273,-25,24,30,"batcave",0,1], + [-374,-113,24,30,"arena",0,2], + [600,-69,32,40,"bank",0,5], + ], + "quirks":[ + [664,-55,20,16,"sign","An Offshore Bank"], + ], + "pvp":False, + "drop_norm":700, + "instance":True, + }, + "test":{ + "key":"test_large", + "key":"resort_default", + "key":"jayson_PirateShip0", + "key":"test", + "name":"Test", + "npcs":[ + {"name":"Transporter","id":"transporter","position":[-50,-50]}, + ], + "monsters":[], + "spawns":[[0,0]], + "no_bounds":True, + "irregular":True, + "day":True, + }, + "crypt":{ + "key":"jayson_instance_dungeon1", + "name":"The Crypt [Cave]", + "npcs":[ + ], + "monsters":[ + {"type":"a1","boundary":[2243.92,325.27,2689.64,505.06],"count":1}, + {"type":"a7","boundary":[726.81,-1076.19,726.81,-1076.19],"count":1,"roam":True}, + {"type":"a3","boundary":[1790.79,-1480.39,1790.79,-1480.39],"count":1,"roam":True}, + {"type":"a6","boundary":[2746.91,-1734.86,2746.91,-1734.86],"count":1,"roam":True}, + {"type":"a5","boundary":[2736.38,-1090.91,2736.38,-1090.91],"count":1,"roam":True}, + {"type":"a2","boundary":[1109.81,-632.68,1109.81,-632.68],"count":1,"roam":True}, + {"type":"a4","boundary":[2745.11,-655.82,2745.11,-655.82],"count":1,"roam":True}, + {"type":"a8","boundary":[2042.91,-883.27,2042.91,-883.27],"count":1,"roam":True}, + {"type":"vbat","boundary":[903.57,-465.05,1479.2,-304.03],"count":7}, + ], + "spawns":[ + [0,0], + ], + "on_death":["cave",2], + "on_exit":["cave",2], + "doors":[ + [-1.54,105.6,126.56,56.96,"cave",2,0], + ], + "instance":True, + }, + "goobrawl":{ + "key":"jayson_GooIsland", + "name":"Goo Brawl!", + "npcs":[ + {"id":"transporter","position":[-347,-483]}, + ], + "monsters":[ + {"type":"rgoo","boundary":[-432,-472,448,208],"count":0,"polygon":[[-344,192],[-288,192],[-288,208],[184,208],[376,208],[376,184],[416,184],[416,-96],[448,-96],[448,-240],[400,-240],[400,-344],[288,-344],[288,-264],[264,-264],[264,-240],[232,-240],[232,-184],[200,-184],[200,-152],[16,-152],[16,-128],[-128,-128],[-128,-168],[-192,-168],[-192,-216],[-248,-216],[-248,-240],[-288,-240],[-288,-408],[-320,-408],[-320,-472],[-408,-472],[-408,-416],[-432,-416],[-432,-112],[-400,-112],[-400,136],[-384,136],[-384,168],[-344,168]]}, + ], + "spawns":[ + [0,0], + ], + "event":"goobrawl", + "code":"join('goobrawl')", + "on_death":["goobrawl",0], + "doors":[ + ], + "outside":True, + #"instance":True, + }, + "abtesting":{ + "key":"jayson_vs_arena", + "name":"A/B Testing", + "npcs":[ + ], + "monsters":[ + ], + "spawns":[ + [0,0], + [0,-232], + [-832,0,2,160], #scatter 100 + [832,0,1,160], + ], + "on_death":["abtesting",1], + "doors":[ + ], + "event":"abtesting", + "code":"join('abtesting')", + "pvp":True, + "instance":True, + "lux":0.8, + }, + "dungeon0":{ + "key":"dungeon0", + "name":"Dungeon", + "npcs":[ + ], + "monsters":[ + {"type":"goo","boundary":[-50,-50,50,50],"count":5}, + ], + "spawns":[ + [0,0], + ], + "on_death":["dungeon0",0], + "doors":[ + ], + "pvp":True, + "no_bounds":True, + "instance":True, + "lux":0.7, + }, + "cgallery":{ + "key":"cgallery", + "name":"Cosmetics Gallery", + "npcs":[ + ], + "monsters":[ + ], + "spawns":[ + [0,0], + ], + "doors":[ + ], + "pvp":True, + "no_bounds":True, + "instance":True, + "lux":1, + }, + "old_bank":{ + "key":"bank0", + "name":"The Bank", + "npcs":[ + {"id":"goldnpc","position":[57,0]}, + {"id":"items0","position":[-24,49]}, #can be 48 too + {"id":"items1","position":[128,49]}, + ], + "monsters":[ + ], + "spawns":[ + [56,129,3], + ], + "doors":[ + [56,187,64,40,"main",5,0], + ], + "quirks":[ + [56,-52,16,34,"log","It's time."], + ], + "mount":True, + "ignore":True, + }, + "bank":{ + "key":"jayson_bank", + "key":"jayson_bank0", + #"key":"jayson_bank_xmas", + #"key":"jayson_bank0.Xmas", #xmas + "name":"The Bank", + "npcs":[ + {"id":"goldnpc","position":[1,-416]}, + {"id":"items4","position":[-64,-415]}, + {"id":"items5","position":[64,-415]}, + {"id":"items6","position":[-128,-415]}, + {"id":"items7","position":[128,-415]}, + #bottom row + {"id":"items0","position":[-64,-191]}, #can be 48 too + {"id":"items1","position":[64,-191]}, + {"id":"items2","position":[-128,-191]}, + {"id":"items3","position":[128,-191]}, + {"id":"rewards","position":[155,-105,1]}, + ], + "monsters":[ + ], + "spawns":[ + [0,-37,3], + [0.75,-435.79], + ], + "doors":[ + [0,-8,40,20,"main",3,0], + [0.13,-444.39,34.3,52.27,"bank_b",0,1,"ulocked"], + ], + "quirks":[ + [-40.34,-448.85,26.77,42.69,"log","It's time."], + ], + "on_exit":["main",3], + "mount":True, + "safe":True, + "lux":0.8, + #"ignore":True, + }, + "bank_b":{ + "key":"jayson_theBank1", + "name":"The Bank [Basement]", + "npcs":[ + {"id":"items8","position":[-592.5,-300]}, + {"id":"items9","position":[-528,-318]}, + {"id":"items10","position":[-464,-333]}, + {"id":"items11","position":[-400.5,-350]}, + + {"id":"items12","position":[-128.5,-429.5]}, + {"id":"items13","position":[-64.5,-413.5]}, + {"id":"items14","position":[-0.5,-398]}, + {"id":"items15","position":[63,-381.5]}, + + {"id":"items16","position":[-480.5,50]}, + {"id":"items17","position":[-416.5,65.5]}, + {"id":"items18","position":[-352.5,81.5]}, + {"id":"items19","position":[-288.5,97.5]}, + + {"id":"items20","position":[-16.5,-14]}, + {"id":"items21","position":[47.5,-14]}, + {"id":"items22","position":[111,-14]}, + {"id":"items23","position":[175,-14]}, + ], + "monsters":[ + ], + "spawns":[ + [-264.38,-411.81], + [-103.51,-170.63], + ], + "doors":[ + [-264.04,-421.14,66.84,65.15,"bank",1,0], + [-104.49,-179.73,32.05,45.25,"bank_u",1,1,"ulocked"], + ], + "quirks":[ + ], + "on_exit":["main",3], + "lux":0.7, + "mount":True, + "safe":True, + }, + "bank_u":{ + "key":"jayson_theBank2", + "name":"The Bank [Underground]", + "npcs":[ + ], + "monsters":[ + ], + "spawns":[ + [-479.47,-25.02], + [-0.4,-41.24], + ], + "doors":[ + [-479.82,-36.54,31,49.64,"level2",6,0,"ulocked","complicated"], + [0.22,-50.06,64.89,63.09,"bank_b",1,1,"ulocked"] + ], + "quirks":[ + ], + "on_exit":["level2",6], + "mount":True, + "safe":True, + "lux":0.6, + }, + "ship0":{ + "key":"jayson_PirateShip0", + "name":"The Pirate Ship", + "npcs":[ + ], + "monsters":[ + ], + "spawns":[ + [0,0], + ], + "doors":[ + ], + "quirks":[ + ], + "event":"pirateship", + "outside":True, + }, + "d2":{ #prototype + "key":"d2", + "name":"Dark World", + "npcs":[ + ], + "monsters":[ + {"type":"d_wiz","boundary":[-49,-679,51,-640],"count":1,"gatekeeper":True,"rage":[-172,-685,219,-437]}, + ], + "spawns":[ + [0,-15], + [0,-671] + ], + "doors":[ + [0,22,40,40,"d1",1,0], + [0,-684,20,50,"d3",0,1,"protected"], + ], + "quirks":[ + ], + "ignore":True, + }, + "d_e":{ + "key":"jayson_pvpDungeonTest", + "key":"jayson_pvpDungeon_entrance", + "safe":True, + "fx":"storm", + "weather":"rain", + "name":"Dungeon [Entrance]", + "npcs":[ + {"id":"transporter","position":[-9,0]}, + ], + "monsters":[ + ], + "spawns":[ + [-9.2,-0.91], + [0.08,-291.85], + ], + "doors":[ + [-0.15,-299.63,35.39,51.17,"d_g",0,1], + ], + "quirks":[ + ], + "world":"dungeon", + }, + "d_g":{ + "key":"jayson_pvpDungeon_gateway", + "name":"Dungeon [Gateway]", + "npcs":[ + ], + "monsters":[ + #{"type":"bat","boundary":[-120,-207,108,17],"count":6}, + ], + "spawns":[ + [0.03,1.13,3], + [-319.17,-102.09,3], + ], + "doors":[ + [0.14,47.88,46.19,36.62,"d_e",1,0], + [-320.6,-39.93,64.22,59.29,"d_b1",0,1], + ], + "quirks":[ + [-320.64,-213.45,67.59,82.61,"log","The passage is blocked"], + ], + "world":"dungeon", + }, + "d_b1":{ + "key":"jayson_pvpDungeon_b1", + "name":"Dungeon", + "npcs":[ + ], + "monsters":[ + ], + "spawns":[ + [-0.28,10.19,3], + [-192.16,-1655.63], + ], + "doors":[ + [0.09,83.59,66.6,63.26,"d_g",1,0], + [-192.9,-1666.24,59.7,45.23,"d_a1",0,1], + ], + "quirks":[ + [190.54,-1628.83,59.88,85.03,"log","The passage is blocked"], + ], + "world":"dungeon", + "traps":[ + {"type":"debuff","polygon":[[-336,-1136],[-192,-1136],[-192,-1160],[-168,-1160],[-168,-1152],[-120,-1152],[-120,-1168],[-112,-1168],[-112,-1240],[-72,-1240],[-72,-1256],[-56,-1256],[-56,-1288],[0,-1288],[0,-1272],[16,-1272],[16,-1208],[88,-1208],[88,-1088],[200,-1088],[200,-1128],[336,-1128],[336,-1368],[240,-1368],[240,-1336],[216,-1336],[216,-1320],[160,-1320],[160,-1400],[128,-1400],[128,-1448],[144,-1448],[144,-1512],[88,-1512],[88,-1496],[64,-1496],[64,-1440],[40,-1440],[40,-1432],[0,-1432],[0,-1464],[-40,-1464],[-40,-1480],[-64,-1480],[-64,-1512],[-144,-1512],[-144,-1560],[-176,-1560],[-176,-1576],[-216,-1576],[-216,-1544],[-264,-1544],[-264,-1480],[-288,-1480],[-288,-1456],[-296,-1456],[-296,-1432],[-328,-1432],[-328,-1152],[-336,-1152]]}, + ] + }, + "d_a1":{ + "key":"jayson_pvpDungeon_a1", + "name":"Dungeon", + "npcs":[ + ], + "monsters":[ + ], + "spawns":[ + [-2.2,1.48,3], + [255.6,-905.1], + ], + "doors":[ + [0.21,79.75,54.39,66.5,"d_b1",1,0], + [254.82,-916.88,61.73,99.0,"d_a2",0,1], + ], + "quirks":[ + ], + "world":"dungeon", + }, + "d_a2":{ + "key":"jayson_pvpDungeon_a2", + "name":"Dungeon", + "npcs":[ + ], + "monsters":[ + ], + "spawns":[ + [-2.12,-0.39,3] + ], + "doors":[ + [0.6,77.16,56.2,64.21,"d_a1",1,0], + ], + "quirks":[ + ], + "world":"dungeon", + }, + "cave":{ + "key":"jayson_cave02", + "name":"Cave of Darkness", + "npcs":[ + #{"name":"Transporter","id":"transporter","position":[100,100]}, + ], + "monsters":[ + {"type":"bat","boundary":[-396,-594,8,-328],"count":6}, + {"type":"bat","boundary":[182,-1282,465,-932],"count":7}, + {"type":"bat","boundary":[1018,-940,1385,-624],"count":8}, + {"type":"bat","boundary":[1066,-132,1420,78],"count":5}, + {"type":"bat","boundary":[964,11,1252,107],"count":2}, + {"type":"mvampire","boundaries":[["cave",-367,-1296,-14,-1057],["cave",1068,-123,1420,78]],"count":1,"stype":"randomrespawn"}, + #{"type":"dknight2","boundary":[0,0,0,0],"count":1,"roam":True}, + ], + "spawns":[ + [0,0,3], + [1877,-1078], #1-level1 + [-193.41,-1295.83], #2-crypt - HARD REFERENCED AT server.js + ], # 1 left, 2 right, 3 back + "doors":[ + [0,33,36,20,"main",4,0], #.spawns[4] + [1880,-1086,32,32,"level1",3,1], + [-192.22,-1308.2,50.35,56.23,"crypt",0,2,"key","cryptkey"], + ], + "quirks":[ + [-192,-1309,48,64,"log","Is this a gateway?"], + [-193.41,-1295.83,0,0,"info","crypt"], + ], + "drop_norm":4500, + "lux":0.45, + }, + "mtunnel":{ + "key":"jayson_mainlandTunnel", + "name":"Underground [Tunnel]", + "npcs":[ + #{"name":"Transporter","id":"transporter","position":[100,100]}, + ], + "monsters":[ + ], + "spawns":[ + [0,8], #0-entrance + [671,-225,3], #1-main17 + [1169,-55,3], #1-main18 + ], # 1 left, 2 right, 3 back + "doors":[ + [0,-3,24,60,"main",16,0], #main16 + [656,-240,24,60,"main",17,1], #main17 + [1168,-65,24,60,"main",18,2], #main18 + ], + "quirks":[ + ], + "drop_norm":4500, + "lux":0.6, + }, + "main":{ + "key":"jayson_ALMap2_v2", + #"key":"jayson_ALMap2_v2.Xmas", + #"key":"jayson_ALMap2_v2.CNewYear", + #"key":"jayson_ALMap2_v2_xmas", #xmas + #"key":"jayson_ALMap2_v2.lunarNewYear", + "name":"Mainland", + "npcs":[ + #{"id":"newupgrade","position":[-203,-174]}, + {"id":"newupgrade","position":[-207,-220]}, + {"name":"Exchanger","id":"exchange","position":[-25,-478]}, + {"name":"Come Scroll Away","id":"scrolls","position":[-464,-96]}, + {"id":"lotterylady","position":[-341,168]}, + {"id":"fisherman","position":[-1572,552,1]}, + #{"id":"fancypots","position":[56,-169]}, + {"id":"fancypots","position":[-35,-162]}, + #{"id":"basics","position":[-56,-144]}, + {"id":"basics","position":[-89,-165]}, + {"id":"premium","position":[192,-564]}, + #{"id":"tavern","position":[-472,138]}, + #{"id":"transporter","position":[-551,-372]}, + {"id":"transporter","position":[-83,-441]}, + {"id":"standmerchant","position":[-193,680]}, + {"name":"Zen Girl","id":"appearance","position":[-361,-832]}, + {"id":"pvp","positions":[ [232,388],[325,499,1] ]}, #currently the direction is hard-coded at update_sprite [30/08/16] + #{"id":"guard","position":[889,-664]}, #dungeon + #{"id":"guard","position":[1588,-534]}, #dark forest 1 + #{"id":"guard","position":[1610,-534]}, #dark forest 2 + #{"id":"guard","position":[616,613]}, #mansion + {"id":"craftsman","position":[92,670]}, + {"id":"pete","position":[-776,1256]}, + #{"id":"citizen0","position":[-152,152]}, + {"id":"citizen0","position":[0,0]}, + {"id":"citizen2","position":[0,0]}, + {"id":"citizen3","position":[0,0]}, + {"id":"citizen4","position":[0,0]}, + {"id":"antip2w","position":[274,-554]}, #shellsguy" + {"id":"friendtokens","position":[120,-560]}, + {"id":"funtokens","position":[303,-87] or [105,-34] or [220,-151]}, + #{"id":"funtokens","position":[225,-105]}, + {"id":"bean","position":[74,-34],"boundary":[-100,-100,100,100]}, + #{"id":"bean","positions":[ [-94,-47],[98,-50],[5,83] ],"loop":True}, # ,"manual":True + {"id":"secondhands","position":[106,-47] or [74,-34]}, + {"id":"pvptokens","position":[159,403]}, + {"id":"monsterhunter","position":[126,-413]}, + {"id":"mcollector","position":[81,-283,1]}, + #{"id":"newyear_tree","position":[64,-88]}, #xmas + ], + "monsters":[ + #square + #{"type":"tiger","boundary":[-118,-100,118,100],"count":1}, #,"rage":[-118,-100,118,100]}, + + #beach + {"type":"crab","boundary":[-1353,-254,-1052,122],"count":8,"grow":True}, + {"type":"squig","boundary":[-1353,126,-998,718],"count":6,"grow":True}, + {"type":"squigtoad","boundary":[-1353,126,-998,718],"count":2}, + {"type":"tortoise","boundary":[-1353,720,-896,1516],"count":6}, + {"type":"frog","boundary":[-1353,720,-896,1516],"count":2}, + {"type":"crabx","boundary":[-1256,1520,-712,2004],"count":5}, + {"type":"crabxx","boundary":[-1256,1520,-712,2004],"count":0}, + + #targets + {"type":"target","boundary":[-571,323,-571,323],"count":1}, + {"type":"target_a500","boundary":[-290,280,-290,280],"count":1}, + {"type":"target_a750","boundary":[-270,280,-270,280],"count":1}, + {"type":"target_r500","boundary":[-250,280,-250,280],"count":1}, + {"type":"target_r750","boundary":[-230,280,-230,280],"count":1}, + {"type":"target_ar900","boundary":[-210,280,-210,280],"count":1}, + {"type":"target_ar500red","boundary":[-150,400,-150,400],"count":1}, + + #middle + {"type":"goo","boundary":[-282,702,218,872],"count":9,"grow":True}, + #{"type":"slenderman","boundary":[-282,702,218,872],"count":1}, + #{"type":"chestm","boundary":[-282,702,218,872],"count":3}, + #{"type":"aqueen","boundary":[-282,702,218,872],"count":1}, + #{"type":"pinkgoo","boundary":[-282,702,218,872],"count":1}, + #{"type":"wabbit","boundary":[-282,702,218,872],"count":1}, + {"type":"bee","boundary":[424,1014,668,1104],"count":4,"grow":True}, + {"type":"bee","boundary":[418,994,570,1208],"count":3,"grow":True}, + {"type":"bee","boundary":[52,1426,252,1548],"count":5,"grow":True}, + {"type":"bee","boundary":[448,694,592,812],"count":3,"grow":True}, + {"type":"bee","boundary":[678,676,796,764],"count":2,"grow":True}, + {"type":"poisio","boundary":[-262,1198,20,1522],"count":5,"grow":True}, + {"type":"croc","boundary":[696,1498,906,1922],"count":6,"grow":True}, + {"type":"armadillo","boundary":[376,1696,676,1996],"count":6,"grow":True}, + {"type":"snake","boundary":[-254,1812,90,1990],"count":6,"grow":True}, + + #final + {"type":"bigbird","boundary":[1100,160,1586,336],"count":5}, + {"type":"spider","boundary":[700,-282,1196,-6],"count":7,"grow":True}, + {"type":"scorpion","boundary":[1485,-390,1670,54],"count":6,"grow":True}, + + #phoenix + {"type":"phoenix", + "boundaries":[ + ["main",708,-300,1668,-86], + ["main",378,1686,904,1920], + ["main",-1358,-118,-1010,1680], + ["halloween",-166,453,182,808], + ["cave",-375,-1287,14,-1041], + #["tunnel",-210,-1291,238,-853] + ],"count":1,"stype":"randomrespawn"}, + #fairies + {"type":"greenfairy","boundary":[-460,-908,-260,-710],"count":1}, + {"type":"redfairy","boundary":[-460,-908,-260,-710],"count":1}, + {"type":"bluefairy","boundary":[-460,-908,-260,-710],"count":1}, + #pets + {"type":"puppy1","boundary":[-766,1072,-643,1210],"count":1}, + {"type":"puppy2","boundary":[-766,1072,-643,1210],"count":1}, + {"type":"puppy3","boundary":[-766,1072,-643,1210],"count":1}, + {"type":"puppy4","boundary":[-766,1072,-643,1210],"count":1}, + {"type":"kitty1","boundary":[-766,1072,-643,1210],"count":1}, + {"type":"kitty2","boundary":[-766,1072,-643,1210],"count":1}, + {"type":"kitty3","boundary":[-766,1072,-643,1210],"count":1}, + {"type":"kitty4","boundary":[-766,1072,-643,1210],"count":1}, + + #tavern area + #{"type":"porcupine","boundary":[-585,305,-146,547],"count":1}, + + #little farm + {"type":"hen","boundary":[-118,-317,-5,-247],"count":2}, + {"type":"rooster","boundary":[-118,-317,-5,-247],"count":1}, + ], + "doors":[ + [-965,-176,24,30,"woffice",0,1], + [536,1665,64,32,"tunnel",0,2], + [168,-149,32,40,"bank",0,3], + [160,1370,24,32,"cave",0,4], + [232,384,24,30,"arena",0,6], + [-472,131,24,30,"tavern",0,8], + [616,610,32,40,"mansion",0,10], + [1936,-23,24,24,"level1",1,11], + [169,-404,24,40,"hut",0,14], + [1600,-547,60,40,"halloween",4,15], + [312,-335,32,32,"mtunnel",0,16], + [967,-584,32,32,"mtunnel",1,17], + [1472,-434,32,32,"mtunnel",2,18], + ], + "traps":[ + {"type":"spikes","position":[-472,286]}, + ], + "spawns":[ + [0,0,0,100], + [-968,-163], #1-outside woffice + [535,1677], #2-tunnel + [168,-134], #3-outside the bank + [160,1381], #4-outside the cave + [-87,673], #5-on-death + [232,397], #6-outside the arena <- this one was the un-bounded problem [232,388] Added a new line_distance logic now [19/07/18] + [294,498], #7-arena death + [-472,149], #8-tavern-exit + #[-556,-271,3], #9-transporter-npc + [-85,-389,3], #9-transporter-npc + [616,621], #10-mansion + [1937,-12], #11-underground + [-1104,-924], #12-the island + [-551,-375], #13-old teleporter - new empty area + [169,-385], #14-hut + [1600,-524], #15-forest + [294,-347,1], #16-mtunnel + [968,-577], #17-mtunnel + [1471,-424], #18-mtunnel + ], + "quirks":[ + [-236,-189,24,24,"upgrade"], + [-179,-189,24,24,"compound"], + [350,424,30,24,"list_pvp"], + [-200,15,24,42,"log","A relic from an old era"], + [200,15,24,42,"log","A relic from an old era"], + [1689,-494,20,16,"note","The Dark Forest. A curious place."], + [681,624,20,16,"sign","The Mansion"], + [65,544,20,16,"sign","Welcome to The New Town!"], + [-150,154,20,16,"sign","Town Square"], + [-365,144,20,16,"sign","Tavern"], + ], + "animatables":{ + "the_door":{"x":888,"y":-672,"position":"door0"}, + }, + "on_death":["main",5], + "on_exit":["main",0], + "drop_norm":1000, + "ref":{ + "u_mid":[-235,-203], + "c_mid":[-180,-203], + "cx":[-479.65,-919.23,-240.96,-697.72], + }, + "zones":[ + { + "type":"fishing", + "drop":"f1", + "polygon":[[-880,-352],[-1064,-352],[-1064,-336],[-1080,-336],[-1080,-320],[-1096,-320],[-1096,-304],[-1224,-304],[-1224,-288],[-1368,-288],[-1368,-272],[-1384,-272],[-1384,600],[-1424,600],[-1424,456],[-1616,456],[-1616,592],[-1536,592],[-1536,680],[-1384,680],[-1384,1648],[-1368,1648],[-1368,1744],[-1352,1744],[-1352,1760],[-1336,1760],[-1336,1872],[-1320,1872],[-1320,1952],[-1304,1952],[-1304,2016],[-1288,2016],[-1288,2032],[-1208,2032],[-1208,2048],[-1064,2048],[-1064,2064],[-920,2064],[-920,2080],[-904,2080],[-904,2096],[-808,2096],[-808,2112],[-736,2112],[-728,2112],[-728,2128],[-456,2128],[-456,2032],[-424,2032],[-424,2440],[-1880,2440],[-1880,-528],[-872,-528],[-872,-352]], + } + ], + "outside":True, + }, + "mansion":{ + "key":"jayson_Mansion", + "name":"The Mansion", + "npcs":[ + {"id":"pwincess","position":[0,-303]}, + ], + "monsters":[ + {"type":"rat","boundary":[-217,-272,200,-24],"count":5}, + {"type":"rat","boundary":[-408,-102,-158,27],"count":3}, + {"type":"rat","boundary":[160,-97,402,29],"count":3}, + {"type":"rat","boundary":[-388,-610,-282,-197],"count":3}, + {"type":"rat","boundary":[-388,-610,-282,-197],"count":3}, + {"type":"rat","boundary":[283,-604,382,-200],"count":3}, + {"type":"rat","boundary":[-240,-487,249,-401],"count":4}, + ], + "doors":[ + [-1,12,40,24,"main",10,0], + [-0.05,-493.95,31.8,46.7,"tomb",0,1,"key","tombkey"] + ], + "spawns":[ + [0,-21,3], + [-0.18,-481.98] + ], + "quirks":[ + [-335,-111,30,40,"log","Locked"], + [338,-111,30,40,"log","Locked"], + [-334,-618,30,40,"log","Locked"], + [338,-618,30,40,"log","Locked"], + [338,-618,30,40,"log","Hotdamn. This one is locked too..."], + #[2,-490,30,40,"log","Locked."], + ], + "drop_norm":1000, + "lux":0.8, + }, + "tomb":{ + "key":"jayson_MansionCrypt", + "name":"The Tomb", + "monsters":[ + {"type":"gredpro","boundary":[-484.75,-400.63,-165.11,-188.4],"count":1}, + {"type":"ggreenpro","boundary":[-378.79,44.16,-115.78,308.73],"count":1}, + {"type":"gbluepro","boundary":[198.5,-402.6,490.12,-43.68],"count":1}, + {"type":"gpurplepro","boundary":[-137.74,-531.49,235.49,-476.06],"count":1}, + ], + "doors":[ + [0,-68.83,33.4,57.5,"mansion",1,0] + ], + "spawns":[ + [0.82,-53.5] + ], + "instance":True, + "lux":0.8, + }, + "jail":{ + "key":"jayson_al_jail", + "name":"Jail", + "npcs":[ + {"id":"jailer","position":[191,-156]}, + ], + "monsters":[ + {"type":"jrat","boundary":[-223,-140,225,156],"count":3}, + ], + "doors":[ + ], + "quirks":[ + [-81,-165,30,40,"log","Locked"], + ], + "spawns":[ + [-79,-153], + ], + "drop_norm":1000, + "irregular":True, + "lux":0.5, + }, + "cyberland":{ + "key":"cyberland", + "name":"Cyberland", + "npcs":[ + ], + "monsters":[ + {"type":"mechagnome","boundary":[-16,-88,-17,-89],"count":1}, + {"type":"mechagnome","boundary":[-6,-96,-7,-95],"count":1}, + {"type":"mechagnome","boundary":[8,-96,7,-95],"count":1}, + {"type":"mechagnome","boundary":[18,-88,17,-89],"count":1}, + ], + "doors":[ + [224,-162,16,16,"main",9,1], + ], + "quirks":[ + [0,-100,80,30,"mainframe"], + ], + "spawns":[ + [0,0,3], + [224,-162,3], + ], + "drop_norm":1000, + "irregular":True, + "lux":0.8, + }, + "duelland":{ + "key":"jayson_arena_pvp", + "key":"jayson_duel_arena", + "name":"Duelland", + "npcs":[ + ], + "monsters":[ + ], + "doors":[ + [0,16,32,20,"main",7,0], + ], + "quirks":[ + ], + "spawns":[ + [0,0,3], + [-712,-800,0,40], + [712,-800,0,40], + ], + "drop_norm":1000, + "irregular":True, + "instance":True, + "pvp":True, + "loss":False, + "lux":0.8, + }, + "hut":{ + "key":"jayson_smallHut", + "name":"The Hut", + "npcs":[ + ], + "monsters":[ + ], + "doors":[ + [0,17,32,24,"main",14,0], + ], + "spawns":[ + [0,-9,3], + ], + "drop_norm":1000, + "safe":True, + "lux":0.6, + }, + "woffice":{ + "key":"jayson_smallNPCcave", + "name":"Wizard's Crib", + "npcs":[ + {"id":"lostandfound","position":[-24,-178]}, + {"id":"wnpc","position":[32,-178,3]}, + ], + "monsters":[ + {"type":"grinch","boundary":[-112,-142,60,-16],"count":1,"special":True}, + ], + "doors":[ + [-29,112,48,40,"main",1,0], + ], + "spawns":[ + [-24,83,3], + ], + "zones":[ + { + "type":"mining", + "drop":"m2", + "polygon":[[-184,-232],[-128,-232],[-128,-184],[-184,-184]], + }], + "lux":0.6, + "drop_norm":1000, + "safe":True, + }, + "tavern":{ + #"ignore":True, + "key":"jayson_tavern02", + "name":"The Tavern", + "npcs":[ + {"id":"tbartender","position":[150,-202]}, + {"id":"bouncer","position":[208,-156]}, + ], + "monsters":[ + ], + "doors":[ + [1,23,48,20,"main",8,0], + [272,-220,28,36,"resort_e",0,1], + ], + "spawns":[ + [0,-8,3], + [272,-200], #1-resort_e + ], + "quirks":[ + [136,-215,32,40,"log","Impossible to reach. This is probably where they keep all the rare items."], + [-103,-229,20,16,"tavern_info"], + ], + "machines":[ + { + "type":"dice", + "set":"custom", #sprite + "frames":[ + [0,16*16,5*16,44], + [5*16,16*16,5*16,44], + [10*16,16*16,5*16,44], + [15*16,16*16,5*16,44], + [20*16,16*16,5*16,44], + [25*16,16*16,5*16,44], + ], + "subframes":[ + [11,301,7,14], #0 + [11+11,301,7,14], #1 + [11+11*2,301,7,14], #2 + [11+11*3,301,7,14], #3 + [11+11*4,301,7,14], #4 + [11+11*5,301,7,14], #5 + [11+11*6,301,7,14], #6 + [11+11*7,301,7,14], #7 + [11+11*8,301,7,14], #8 + [11+11*9,301,7,14], #9 + [5,310,1,1], #. - manually calibrated all of these, it wasn't easy [07/02/18] + ], + "x":-169, + "y":-209, + }, + { + "type":"slots", + "set":"custom", + "frames":[ + [0,20*16,2*16,3*16], + [2*16,20*16,2*16,3*16], + [4*16,20*16,2*16,3*16], + ], + "x":-272, + "y":-216, + }, + { + "type":"wheel", + "set":"custom", + "frames":[ + [0,23*16,2*16,3*16], + [2*16,23*16,2*16,3*16], + [4*16,23*16,2*16,3*16], + ], + "x":-64, + "y":-216, + } + ], + "drop_norm":1000, + "lux":0.8, + }, + "resort_e":{ + #"ignore":True, + "key":"resort_e", + "name":"Holo Resort", + "npcs":[ + ], + "animatables":{ + "the_lever":{"x":-8,"y":-92,"position":"lever0"}, + }, + "monsters":[ + ], + "doors":[ + [-8,120,40,24,"tavern",1,0], + ], + "spawns":[ + [-8,91,3], + ], + "quirks":[ + [-8,-92,20,24,"the_lever"], + ], + "drop_norm":1000, + "lux":1, + }, + "resort":{ + #"ignore":True, + "key":"resort", + "name":"Holo Resort", + "npcs":[ + {"id":"holo","position":[-8,-108]}, + #{"id":"lostandfound","position":[77,-96]}, + {"id":"holo0","position":[-8,0]}, + {"id":"holo1","position":[-8,0]}, + {"id":"holo2","position":[-8,0]}, + {"id":"holo3","position":[-8,0]}, + {"id":"holo4","position":[-8,0]}, + {"id":"holo5","position":[-8,0]}, + ], + "monsters":[ + ], + "doors":[ + [-8,120,40,24,"tavern",1,0], + ], + "spawns":[ + [-8,91,3], + ], + "quirks":[ + ], + "drop_norm":1000, + "irregular":True, + "lux":0.75, + }, + "winter_inn":{ + "key":"jayson_winter_inn", + "name":"Wanderers' Inn", + "npcs":[ + {"id":"wbartender","position":[-143,-220]}, + {"id":"citizen1","position":[0,-5]}, + {"id":"citizen5","position":[0,-5]}, + {"id":"citizen6","position":[0,-5]}, + #{"id":"mistletoe","position":[94,-181,2]}, #xmas + ], + "monsters":[ + ], + "doors":[ + [0,29,24,20,"winterland",2,0], + [47,-228,28,36,"winter_inn_rooms",0,1], + ], + "spawns":[ + [0,-5,3], + [28,-208], #1-winter_inn_rooms + ], + "quirks":[ + #[48,-232,26,36,"log","Locked"], + ], + "drop_norm":1000, + "lux":0.75, + }, + "winter_inn_rooms":{ + "key":"jayson_winter_inn_room1", + "name":"Rooms", + "npcs":[ + ], + "monsters":[ + ], + "doors":[ + [0,25,24,20,"winter_inn",1,0], + ], + "spawns":[ + [-0,-8,3], + ], + "quirks":[ + ], + "drop_norm":1000, + "unlist":True, + "lux":0.6, + }, + "winter_cave":{ + "key":"jayson_xmas_cave1", + "name":"Frozen Cave", + "npcs":[ + ], + "monsters":[ + {"type":"bbpompom","boundary":[-234,-300,336,-28],"count":6}, + {"type":"bbpompom","boundary":[-318,-1112,153,-786],"count":7}, + ], + "doors":[ + [3,41,36,20,"winterland",3,0], + [-170,-1157,32.5,36.5,"winter_cove",0,1], + ], + "spawns":[ + [0,11,3], + [-169,-1144], + ], + "quirks":[ + ], + "drop_norm":4000, + "lux":0.5, + }, + "winter_cove":{ + "key":"jayson_frozenCave", + "name":"Frozen Cove", + "npcs":[ + ], + "monsters":[ + {"type":"harpy","boundary":[-3.38,-398.22,273.25,-223.83],"count":5,"roam":True,"random":True}, + {"type":"rharpy","boundary":[-3.38,-398.22,273.25,-223.83],"count":1,"roam":True}, + ], + "doors":[ + [-9,64,51,37.5,"winter_cave",1,0], + ], + "spawns":[ + [-7.5,9.5,3], + [509.71,-228.7], + [253.08,-1849], + [59,-2242.92], + [-216.35,-1952.95], + [-695.12,-1935.26], + [248.55,-1487.53], + [37.21,-1338.83], + [210.45,-1225.44], + [71.03,-1143.93], + [-154.29,-1355.28], + [-285.29,-972.74], + [-894.25,-485.67], + [-590.74,-1532.24] + + ], + "quirks":[ + ], + "drop_norm":4000, + "lux":0.5, + }, + "winter_instance":{ + "key":"jayson_winterInstance", + "name":"Lair of the Dark Mage", + "npcs":[ + ], + "monsters":[ + {"type":"xmagefz","boundary":[-255.17,-261.64,239.07,221.4],"count":1}, + {"type":"xmagefi","boundary":[-255.17,-261.64,239.07,221.4],"count":0}, + {"type":"xmagen","boundary":[-255.17,-261.64,239.07,221.4],"count":0}, + {"type":"xmagex","boundary":[-255.17,-261.64,239.07,221.4],"count":0}, + ], + "on_exit":["winterland",5], + "doors":[ + [-7.23,250.26,38.15,28.55,"winterland",5,0], + ], + "spawns":[ + [-8,216,3], + ], + "quirks":[ + ], + "drop_norm":4000, + "instance":True, + "lux":0.75, + }, + "winterland":{ + #"key":"jayson_IceLandPrototype", + "key":"jayson_WinterLandV2", + "name":"Winterland", + #"weather":"snow", + "freeze_multiplier":1.5, + "burn_multiplier":0.6, + "npcs":[ + {"id":"leathermerchant","position":[262,-48.5]}, + {"id":"transporter","position":[-73,-393]}, + #{"id":"santa","position":[1242,-1631]}, #xmas + #{"id":"ornaments","position":[-137,-193,1]}, #xmas + {"id":"guard","position":[1065,-2015]}, + {"id":"citizen7","position":[-15,5]}, + {"id":"citizen8","position":[-15,5]}, + {"id":"citizen9","position":[-15,5]}, + {"id":"citizen10","position":[-15,5]}, + ], + "monsters":[ + {"type":"stompy","boundary":[30,-2954,836,-2536],"count":1}, + {"type":"wolf","boundary":[30,-2954,836,-2536],"count":7}, + #{"type":"rudolph","boundary":[1065,-1598,1418,-1449],"count":1}, #xmas + {"type":"arcticbee","boundary":[682,-967,1482,-779],"count":10,"grow":True}, + {"type":"wolfie","boundary":[-367,-2234,29,-1819],"count":4}, + {"type":"wolfie","boundary":[236,-2232,460,-1847],"count":3}, + {"type":"boar","boundary":[-173,-1488,212,-730],"count":8}, + {"type":"iceroamer","boundary":[550,-240,1097,149],"count":5}, + {"type":"iceroamer","boundary":[1335,-71,1689,278],"count":4}, + {"type":"icegolem","boundary":[782.25,395.96,888.71,450.28],"count":0,"roam":True}, + ], + "doors":[ + [-280,-132,32,40,"winter_inn",0,2], + [602,-1289,24,30,"winter_cave",0,3], + [-864,-1570,24,24,"level2n",2,4], + [1064.28,-2017.79,31.66,47.45,"winter_instance",0,5,"key","frozenkey"], + ], + "spawns":[ + [0,0], + [-8,-337,3], #1-transports NPC + [-280,-123], #2-winter inn + [600,-1275], #3-xmas_cave1 + [-864,-1614,3], #4-level2n + [1063,-2007], #5-winter_instance - HARD REFERENCED at server.js + [864.5,429.50], #6- ice golem + [1018.5,401.5], #7- island + ], + "quirks":[ + [-247,-73,20,16,"sign","The Wanderers' Inn"], + [202,-56,20,16,"sign","Leather Shop. If I'm not outside, check inside!"], + [65,-1601,20,16,"sign","Dangers Ahead. Beware!"], + [465,-2296,20,16,"note","Stompy and his companions defeated me many times. However, I've discovered that If I stay just around the corner they can't even reach me! HAHA!"], + [-230,95,20,16,"log","Old Man's House"], + [168,-83,32,40,"log","Locked"], + [138,223,32,40,"log","Locked. This is probably where the guards stay"], + [413,-3080,24,30,"log","Can't reach. This might be Stompy's lair"], + [600.5,-1273,0,0,"info","darkmage"], + ], + "drop_norm":3000, + "lux":0.9, + "outside":True, + }, + "desertland":{ + "key":"jayson_desertlandW", + "freeze_multiplier":0.4, + "burn_multiplier":1.6, + "name":"Desertland", + "npcs":[ + {"id":"transporter","position":[-14,-477]}, + {"id":"locksmith","position":[316,-270]}, + ], + "monsters":[ + {"type":"plantoid","boundary":[-1013,-472,-575,-130],"count":4}, + {"type":"plantoid","boundary":[-1013,-624,-762,-137],"count":4}, + {"type":"porcupine","boundary":[-992,-58,-666,328],"count":8,"grow":True}, + {"type":"ent","boundary":[-757,-2034,-70,-1888],"count":3}, + {"type":"fireroamer","boundary":[91,-952,353,-702],"count":4}, + {"type":"fireroamer","boundary":[161,-868,453,-697],"count":2}, + {"type":"scorpion","boundary":[220.31,-1569.2,561.04,-1275.72],"count":6}, + {"type":"bscorpion","boundary":[-522.44,-1340.19,-295.2,-1183.31],"count":1}, + ], + "spawns":[ + [0,0], + [10,-386], + [601,-2365], #2-desertland + ], + "doors":[ + [600,-2383,40,40,"level2s",1,2], + ], + #"irregular":True, + "drop_norm":1000, + "outside":True, + }, + "shellsisland":{ + "key":"jayson_shells_island01", + "name":"New Town!", + "npcs":[ + {"id":"wizardrepeater","position":[-190,26]}, + ], + "monsters":[ + {"type":"kitty1","boundary":[123,-235,270,-176],"count":1}, + {"type":"kitty2","boundary":[123,-235,270,-176],"count":1}, + {"type":"kitty3","boundary":[123,-235,270,-176],"count":1}, + {"type":"kitty4","boundary":[123,-235,270,-176],"count":1}, + {"type":"puppy1","boundary":[211,-234,271,-100],"count":1}, + {"type":"puppy2","boundary":[211,-234,271,-100],"count":1}, + {"type":"puppy3","boundary":[211,-234,271,-100],"count":1}, + {"type":"puppy4","boundary":[211,-234,271,-100],"count":1}, + ], + "spawns":[ + [0,0], + ], + "drop_norm":1000, + "instance":True, + "outside":True, + }, + "halloween":{ + "key":"jayson_holloweenmap", + "key":"jayson_SpookyForestV2.2", + "name":"Spooky Forest", + "npcs":[ + {"name":"Fancy Pots","id":"fancypots","position":[201,-180]}, + #{"name":"Transporter","id":"transporter","position":[582,-117]}, + {"name":"Transporter","id":"transporter","position":[-97,-330]}, + {"id":"witch","position":[858,-160]}, + {"id":"citizen11","position":[201,-160]}, + {"id":"citizen12","position":[201,-160]}, + {"id":"citizen13","position":[201,-160]}, + ], + "monsters":[ + {"type":"osnake","boundary":[-654,-384,-525,-287],"count":2}, + {"type":"osnake","boundary":[-620,-986,-356,-431],"count":4}, + #{"type":"snake","boundary":[-620,-986,-356,-431],"count":9,"grow":True}, + {"type":"snake","boundary":[-720,-820,-418,-203],"count":9,"grow":True}, + {"type":"greenjr","boundary":[-720,-820,-418,-203],"count":1}, + + {"type":"minimush","boundary":[-166,453,182,808],"count":8,"grow":True}, + {"type":"mrpumpkin","boundary":[-671,571,-300,800],"count":1,"special":True}, + {"type":"xscorpion","boundary":[-671,571,-300,800],"count":6}, + + {"type":"snake","boundary":[141,-792,552,-702],"count":6,"grow":True}, + {"type":"osnake","boundary":[141,-792,552,-702],"count":2}, + {"type":"tinyp","boundary":[141,-792,552,-702],"count":1}, + + {"type":"ghost","boundary":[284,-1351,446,-1189],"count":5}, + {"type":"ghost","boundary":[54,-1277,237,-1078],"count":5}, + + {"type":"fvampire","boundary":[-664,-1808,-147,-1477],"count":1}, + {"type":"ghost","boundary":[-664,-1808,-147,-1477],"count":9}, + ], + "spawns":[ + [0,0], + [-38,-283,2], #1-teleporter + #[103,-263,2], #2-spooky + [784,-1060], #2-spooky + [-1071,-1485], #3-level1 + [1212,101,3], #4-main + ], + "doors":[ + #[108,-260,32,32,"spookytown",1,2], + [784,-1085,80,40,"spookytown",1,2], + [-1071,-1496,40,40,"level1",2,3], + [1212,150,200,36,"main",15,4], + ], + "quirks":[ + [-228,-178,32,40,"log","Locked but there are noises coming from inside"], + [331,-210,32,40,"log","Locked"], + [128,-251,20,16,"sign","Beware! Don't fall down!"], + ], + #"filter":"halloween", + "drop_norm":4000, + "outside":True, + "lux":0.9, + }, + "spookytown":{ + "key":"jayson_holloweenmap2", + "name":"Spooky Town", + "npcs":[ + {"id":"citizen15","position":[300,-700],"boundary":[281,-836,508,-570]}, + #{"id":"citizen15","position":[200,-1400],"boundary":[31,-1571,480,-1293]}, + {"id":"citizen14","position":[0,0],"boundary":[-283,-222,289,234]}, + ], + "monsters":[ + {"type":"mummy","boundary":[31,-1571,480,-1293],"count":9,"rage":[-124,-1631,614,-1130]}, + {"type":"booboo","boundary":[286,-842,544,-562],"count":5,"rage":[286,-842,544,-562]}, + + {"type":"stoneworm","boundary":[501,61,852,197],"count":4}, + {"type":"stoneworm","boundary":[773,-198,1216,-68],"count":4}, + + {"type":"mrgreen","boundary":[524,860,748,1129],"count":1,"special":True}, + {"type":"jr","boundary":[-970,-413,-597,-189],"count":1}, + ], + "spawns":[ + [0,0], + #[71,-68], #1-halloween + [32,1404,3], #1-halloween + [192,-194,1], #2-level2 + ], + "doors":[ + #[72,-80,32,40,"halloween",2,1], + [34,1449,80,30,"halloween",2,1], + [240,-181,48,32,"level2",5,2], + ], + "quirks":[ + [-63,-44,30,24,"invisible_statue"], + ], + "ref":{ + "poof":{"map":"spookytown","in":"spookytown","x":-63,"y":-44}, + }, + "drop_norm":4000, + "outside":True, + "lux":0.9, + }, + "tunnel":{ + "key":"jayson_miningtunnel_new", + "name":"Mining Tunnel", + "npcs":[ + {"id":"gemmerchant","position":[-264,-96,2]}, + ], + "monsters":[ + {"type":"mole","boundary":[-210,-1291,238,-853],"count":8}, + {"type":"mole","boundary":[-238,-638,207,-21],"count":7}, + ], + "spawns":[[0,-16,3]], # 1 left, 2 right, 3 back + "doors":[ + [2,18,64,32,"main",2,0], #.spawns[1] + ], + "quirks":[ + [50,-678,20,16,"sign","Beware: Mole's Bite"], + [64,-1341,24,30,"log","Gloomy"], + ], + "drop_norm":5000, + "zones":[ + { + "type":"mining", + "drop":"m1", + "polygon":[[296,-16],[296,-128],[256,-128],[256,-280],[272,-280],[272,-360],[264,-360],[264,-520],[296,-520],[296,-680],[120,-680],[120,-840],[280,-840],[280,-904],[272,-904],[272,-1224],[296,-1224],[296,-1288],[280,-1288],[280,-1304],[200,-1304],[200,-1328],[-64,-1328],[-64,-1320],[-200,-1320],[-200,-1328],[-288,-1328],[-288,-1160],[-248,-1160],[-240,-1160],[-240,-952],[-288,-952],[-288,-840],[-152,-840],[-144,-840],[-144,-808],[-112,-808],[-112,-680],[-288,-680],[-288,-504],[-272,-504],[-272,-168],[-288,-168],[-288,8],[-424,8],[-424,-1440],[384,-1440],[384,-16]], + } + ], + "lux":0.65, + }, + "batcave":{ + "ignore":True, + "key":"batcave", + "name":"Cave of Beginnings", + "npcs":[ + #{"name":"Transporter","id":"transporter","position":[100,100]}, + ], + "monsters":[ + {"type":"bat","boundary":[-210,-170,342,185],"count":12}, + {"type":"mvampire","boundary":[-210,-170,342,185],"count":1}, + ], + "spawns":[[-200,190,3]], # 1 left, 2 right, 3 back + "doors":[ + [-195,213,24,20,"main",1], #.spawns[1] + ], + "drop_norm":4500, + }, + "arena":{ + "key":"arena3", + "name":"Arena", + "npcs":[ + #{"name":"Transporter","id":"transporter","position":[-50,-50]}, + ], + "monsters":[ + {"type":"cgoo","boundary":[-376,-888,1144,48],"polygon":[[-376,48],[1144,48],[1144,-888],[248,-888],[248,-776],[520,-776],[520,-560],[248,-560],[248,-376],[288,-376],[288,-336],[328,-336],[328,-304],[480,-304],[480,-344],[512,-344],[512,-368],[720,-368],[720,-192],[688,-192],[688,-152],[608,-152],[608,-120],[272,-120],[272,-152],[104,-152],[104,-200],[-128,-200],[-128,-400],[240,-400],[240,-888],[-376,-888]],"count":32}, + {"type":"skeletor","boundary":[259,-764,500,-579],"count":1}, + ], + "spawns":[[151.6,40.82]], + "doors":[ + [152.99,85.42,60.9,40.55,"main",6,0], + ], + "on_death":["main",7], #pvp death main.spawns[3] + "safe_pvp":True, + "pvp":True, + "drop_norm":2000, + "lux":0.45, + }, + # Name Ideas: The Entrance, Bog, The Depraved Waters, Underground Cove, Soul Nexus, Subterrane + "level1":{ + "key":"jayson_underground_level1v2", + "name":"Underground [Entrance]", + "npcs":[ + ], + "monsters":[ + {"type":"prat","boundary":[-86,17,64,212],"count":5}, + {"type":"prat","boundary":[-308,629,0,762],"count":5}, + ], + "spawns":[ + [149,87,1], + [0,9], #1-main + [-408,-258,3], #2-halloween + [-863,89,3], #3-cave + [-327,511,3], #4-level2 + ], # 1 left, 2 right, 3 back + "doors":[ + [0,-4,20,50,"main",11,1], + [-408,-275,20,50,"halloween",3,2], + [-865,77,20,50,"cave",1,3], + [-313,544,24,24,"level2",1,4], + ], + "quirks":[ + ], + "drop_norm":5000, + "small_steps":True, + "lux":0.4, + }, + "level2":{ + "key":"jayson_underground_level2.2", + #"key":"jayson_underground_level2", + "name":"Underground [Passing]", + "npcs":[ + {"id":"thief","position":[-133,-187]}, + {"id":"citizen16","position":[-46,-168]}, + ], + "monsters":[ + ], + "spawns":[ + [39,177,3], #0-level3 + [1,-5], #1-level1 + [-87,256,3], #2-level2s + [216,170,1], #3-level2e + [-303,-69,2], #4-level2w + [75,56], #5-spookytown + [-279.95,-249.15], #6-bank_u + ], + "doors":[ + [40,219,24,24,"level3",0,0], + [0,-20,20,50,"level1",4,1], + [-87,300,80,40,"level2s",0,2], + [247,193,40,110,"level2e",1,3], + [-327,-45,40,110,"level2w",0,4], + [79,41,20,50,"spookytown",2,5], + [-280.14,-260.37,34.84,51.33,"bank_u",0,6,"ulocked","complicated"], + ], + "quirks":[ + ], + "drop_norm":5000, + "unlist":True, + "lux":0.4, + }, + "level2n":{ + "key":"jayson_underground_level2_northv2", + "name":"Underground [North]", + "npcs":[ + ], + "monsters":[ + {"type":"pppompom","boundary":[-621,-241,-234,-65],"count":6}, + {"type":"pppompom","boundary":[153,-303,432,-75],"count":7}, + ], + "spawns":[ + [0,0,3], #0-level2w + [-416,0,3], #1-level2w + [-112,-676], #2-winterland + ], + "doors":[ + [0,38,120,45,"level2w",1,0], + [-416,38,60,45,"level2w",2,1], + [-112,-691,20,40,"winterland",4,2], + ], + "quirks":[ + ], + "drop_norm":5000, + "unlist":True, + "lux":0.4, + }, + "level2e":{ + "key":"jayson_underground_level2_eastv2", + "name":"Underground [East]", + "npcs":[ + ], + "monsters":[ + {"type":"pinkgoblin","polygon":[[384,-96],[464,-96],[464,-64],[608,-64],[608,144],[568,144],[568,304],[464,304],[464,328],[368,328],[368,208],[344,208],[344,160],[384,160]],"boundary":[344,-96,608,328],"count":3} + ], + "spawns":[ + [18.5,459.5,2], #0-level2s + [3.5,0,2], #1-level2 + ], + "doors":[ + [-7,502,40,140,"level2s",2,0], + [-23,40,40,140,"level2",3,1], + ], + "quirks":[ + ], + "drop_norm":5000, + "unlist":True, + "lux":0.4, + }, + "level2s":{ + "key":"jayson_underground_level2_southv2", + "name":"Underground [South]", + "npcs":[ + ], + "monsters":[ + {"type":"cgoo","boundary":[-52.5,359.33,120.29,646.25],"count":8}, + ], + "spawns":[ + [0,-14], #0-level2 + [-240,681], #1-desertland + [383,539,1], #2-level2e + ], + "doors":[ + [0,-20,40,40,"level2",2,0], + [-240,668,20,50,"desertland",2,1], + [406,580,40,140,"level2e",0,2], + ], + "quirks":[ + ], + "drop_norm":5000, + "unlist":True, + "lux":0.4, + }, + "level2w":{ + "key":"jayson_underground_level2_westv2", + "name":"Underground [West]", + "npcs":[ + ], + "monsters":[ + {"type":"oneeye","boundary":[-447,9,-208,323],"count":5}, + {"type":"franky","boundary":[-447,9,-208,323],"count":0,"special":True}, + ], + "spawns":[ + [16,9,1], #0-level2 + [-96,-184], #1-level2n + [-528,-184], #2-level2n + ], + "doors":[ + [39,53,40,140,"level2",4,0], + [-96,-197,60,40,"level2n",0,1], + [-528,-197,60,40,"level2n",1,2], + ], + "quirks":[ + ], + "drop_norm":5000, + "unlist":True, + "lux":0.4, + }, + "level3":{ + "key":"jayson_underground_level3v2", + "name":"Underground [Deeps]", + "npcs":[ + ], + "monsters":[ + {"type":"mummy","boundary":[-451.21,-397.41,-240.59,-65.16],"count":3}, + {"type":"bbpompom","boundary":[131.97,-368.95,398.99,-56.88],"count":4}, + ], + "spawns":[ + [0,10], #0-level2 + [-28,-438,2], #1-level4 + ], + "doors":[ + [0,-5,20,50,"level2",0,0], + [-8,-409,24,24,"level4",0,1], + ], + "quirks":[ + ], + "drop_norm":5000, + "unlist":True, + "lux":0.4, + }, + "level4":{ + "key":"jayson_underground_level4v2", + "name":"Underground [Abyss]", + "npcs":[ + ], + "monsters":[ + {"type":"cgoo","boundary":[-366.74,-395.74,-109.59,-152.68],"count":6}, + {"type":"mummy","boundary":[119.92,-4.27,378.46,338.17],"count":3}, + ], + "spawns":[ + [0,14], + [291,-140], #jump point + ], + "doors":[ + [0,-3,20,50,"level3",1,0], + ], + "quirks":[ + ], + "drop_norm":5000, + "unlist":True, + "lux":0.4, + }, + +} +for name in maps: + if not maps[name].get("doors"): maps[name]["doors"]=[] + if not maps[name].get("npcs"): maps[name]["npcs"]=[] \ No newline at end of file diff --git a/design/monsters.py b/design/monsters.py new file mode 100644 index 0000000..1a36012 --- /dev/null +++ b/design/monsters.py @@ -0,0 +1,1333 @@ +import math +monsters={ + "goo":{ + "name":"Goo","speed":6,"charge":12,"hp":100,"xp":100,"attack":5,"damage_type":"physical","respawn":1,"gold":20,"range":15,"frequency":0.4,"aggro":0,"aa":1, + #"immune":True, + #"respawn_as":"bee", + #"explosion":2000, + "achievements":[ + [10,"stat","hp",5], + [100,"stat","hp",10], + [1000,"stat","mp",5], + [10000,"stat","dex",1], + [100000,"stat","str",1], + [1000000,"stat","int",1], + [10000000,"stat","speed",0.25], + ], + }, + "bee":{ + "name":"Bee","speed":12,"hp":300,"xp":400,"attack":16,"damage_type":"physical","respawn":2,"gold":40,"range":20,"frequency":0.5,"aggro":1,"aa":1,"rage":0.1, + "phresistance":60, + #"respawn_as":"goo", + "achievements":[ + [10,"stat","hp",5], + [100,"stat","mp",5], + [1000,"stat","mp",5], + [10000,"stat","attack",2], + [100000,"stat","apiercing",2], + [1000000,"stat","attack",3], + [10000000,"stat","xp",1], + ] + }, + "cutebee":{ + "name":"Cute Bee","speed":12,"hp":300,"xp":400,"attack":16,"damage_type":"physical","respawn":-1,"gold":40,"range":20,"frequency":0.5,"aggro":1,"aa":1,"rage":0.05, + "phresistance":60, + "explanation":"Spawns in Mainland around every 480,000 Bee spawns", + #"for":912, + "avoidance":99.9, + "achievements":[ + [1,"stat","hp",10], + [20,"stat","for",1], + ], + "cute":True, + }, + "squig":{ + "name":"Squig","speed":10,"hp":1000,"xp":600,"attack":7,"damage_type":"physical","respawn":12,"gold":100,"range":15,"frequency":0.5,"aggro":0,"aa":1, + "achievements":[ + [10,"stat","mp",5], + [100,"stat","mp",5], + [1000,"stat","mp",10], + [10000,"stat","mp",10], + [100000,"stat","evasion",0.25], + [1000000,"stat","resistance",5], + [10000000,"stat","evasion",1], + ] + }, + "squigtoad":{ + "name":"Squigtoad","speed":16,"hp":9600,"xp":32000,"attack":24,"damage_type":"physical","respawn":120,"gold":200,"range":20,"frequency":0.6,"aggro":0, + "difficulty":3, + "achievements":[ + [10,"stat","mp",5], + [100,"stat","mp",5], + [1000,"stat","mp",5], + [10000,"stat","evasion",0.25], + [100000,"stat","int",1], + [1000000,"stat","attack",5], + [10000000,"stat","evasion",1], + ] + }, + "tortoise":{ + "name":"Tortoise","speed":10,"hp":7200,"xp":5200,"attack":36,"damage_type":"physical","respawn":12,"gold":60,"range":15,"frequency":0.5,"aggro":0,"armor":200, + "achievements":[ + [10,"stat","hp",10], + [100,"stat","mp",10], + [1000,"stat","hp",20], + [10000,"stat","armor",5], + [100000,"stat","str",1], + [1000000,"stat","speed",0.5], + [10000000,"stat","armor",10], + ] + }, + "frog":{ + "name":"Froggie","speed":10,"hp":600,"xp":7200,"attack":24,"damage_type":"physical","respawn":960,"gold":300,"range":15,"frequency":0.5,"aggro":0,"evasion":99, + "difficulty":12, + "achievements":[ + [10,"stat","mp",10], + [100,"stat","vit",1], + [1000,"stat","int",1], + [10000,"stat","evasion",0.5], + [100000,"stat","int",3], + [1000000,"stat","vit",4], + [10000000,"stat","evasion",1], + ] + }, + "rat":{ + "name":"Rat","speed":12,"hp":820,"xp":640,"attack":80,"damage_type":"physical","respawn":2,"gold":32,"range":40,"frequency":0.5,"aggro":1,"rage":1, + "difficulty":1.4, + "achievements":[ + [10,"stat","hp",10], + [100,"stat","mp",5], + [1000,"stat","armor",2], + [10000,"stat","gold",0.5], + [100000,"stat","attack",5], + [1000000,"stat","rpiercing",3], + [10000000,"stat","attack",20], + ] + }, + "jrat":{ + "name":"Rat","skin":"rat","speed":12,"hp":4000,"xp":100,"attack":240,"damage_type":"physical","respawn":42,"gold":5,"range":40,"frequency":0.5,"aggro":0, + "difficulty":0.2, + "achievements":[ + [1000000,"stat","for",5], + ] + }, + "croc":{ + "name":"Croc","speed":10,"hp":3200,"xp":3600,"attack":48,"damage_type":"physical","respawn":6,"gold":55,"range":15,"frequency":0.5,"aggro":0.2,"rage":1,"aa":0, + "armor":40, + "achievements":[ + [10,"stat","hp",10], + [100,"stat","hp",10], + [1000,"stat","resistance",1], + [10000,"stat","for",1], + [100000,"stat","speed",0.25], + [1000000,"stat","attack",10], + [10000000,"stat","dreturn",1], + ] + }, + "mole":{ + "name":"Mole","speed":18,"charge":60,"hp":12400,"xp":8000,"attack":480,"damage_type":"physical","respawn":6,"gold":120,"range":15,"frequency":0.8,"aggro":1,"rage":1,"apiercing":320, + "difficulty":1.2, + "achievements":[ + [10,"stat","hp",10], + [100,"stat","mp",10], + [1000,"stat","for",1], + [10000,"stat","str",1], + [100000,"stat","attack",5], + [1000000,"stat","apiercing",5], + [10000000,"stat","gold",1], + ] + }, + "crab":{ + "name":"Tiny Crab","speed":6,"hp":400,"xp":500,"attack":24,"damage_type":"physical","respawn":0.64,"gold":30,"range":15,"frequency":0.4,"aggro":0.2,"size":0.5, + "armor":160, + "achievements":[ + [10,"stat","hp",10], + [100,"stat","hp",10], + [1000,"stat","mp",5], + [10000,"stat","attack",5], + [100000,"stat","hp",200], + [1000000,"stat","rpiercing",3], + [10000000,"stat","range",2], + [100000000,"stat","hp",5], + ] + }, + "crabx":{ + "name":"Huge Crab","speed":8,"charge":30,"hp":4200,"xp":3600,"attack":240,"damage_type":"physical","respawn":4,"gold":120,"range":15,"frequency":0.3,"aggro":0.5, + "armor":210, + "achievements":[ + [10,"stat","hp",10], + [100,"stat","hp",10], + [1000,"stat","armor",1], + [10000,"stat","str",1], + [100000,"stat","speed",0.5], + [1000000,"stat","luck",0.5], + [10000000,"stat","hp",400], + ] + }, + "crabxx":{ + "skin":"crabx", + "name":"Giga Crab","speed":30,"charge":80,"hp":960000,"xp":720000,"attack":16000,"damage_type":"physical","respawn":-1,"gold":120,"range":45,"size":1.5,"frequency":0.3,"aggro":0, + "armor":320, + "difficulty":10, + "special":True, + "phresistance":30, + "announce":"#B73237", + "spawns":[[1000,"crabx"]], + "cooperative":True, + "achievements":[ + [1,"stat","hp",10], + [100,"stat","luck",1], + ] + }, + "armadillo":{ + "name":"Armadillo","speed":14,"hp":1600,"xp":1720,"attack":20,"damage_type":"physical","respawn":3,"gold":80,"range":20,"frequency":0.5,"aggro":0,"dreturn":30, + "armor":60, + "difficulty":1.1, + "achievements":[ + [10,"stat","hp",10], + [100,"stat","hp",10], + [1000,"stat","armor",1], + [10000,"stat","for",1], + [100000,"stat","dreturn",0.5], + [1000000,"stat","armor",10], + [10000000,"stat","dreturn",1], + ] + }, + "porcupine":{ + "name":"Porcupine","speed":10,"charge":30,"hp":3800,"xp":3200,"attack":16,"damage_type":"physical","respawn":2,"gold":40,"range":20,"frequency":0.5,"aggro":1,"rage":0.4,"dreturn":4800, + "armor":120, + "difficulty":1.2, + "achievements":[ + [10,"stat","hp",10], + [100,"stat","hp",10], + [1000,"stat","for",1], + [10000,"stat","for",1], + [100000,"stat","dreturn",0.5], + [1000000,"stat","hp",300], + [10000000,"stat","armor",10], + ] + }, + "hen":{ + "name":"Chicken","speed":10,"hp":60,"xp":10,"attack":48,"damage_type":"physical","respawn":200,"gold":40,"range":20,"frequency":1.5,"aggro":1,"rage":0.2,"cute":True, + "achievements":[ + [1000,"stat","gold",2], + ] + }, + "rooster":{ + "name":"Chicken","speed":7,"hp":60,"xp":10,"attack":48,"damage_type":"physical","respawn":200,"gold":40,"range":20,"frequency":1.5,"aggro":1,"rage":0.2,"cute":True, + "achievements":[ + [1000,"stat","for",1], + ] + }, + "osnake":{ + "name":"Snake","speed":12,"hp":720,"xp":1600,"attack":24,"damage_type":"physical","respawn":60,"gold":150,"range":20,"frequency":0.6,"aggro":0, + "difficulty":2, + "achievements":[ + [10,"stat","mp",10], + [100,"stat","hp",20], + [1000,"stat","vit",1], + [10000,"stat","str",1], + [100000,"stat","speed",0.25], + [1000000,"stat","armor",5], + [10000000,"stat","xp",1], + ] + }, + "snake":{ + "name":"Snake","speed":12,"hp":720,"xp":960,"attack":24,"damage_type":"physical","respawn":3,"gold":60,"range":20,"frequency":0.6,"aggro":0, + "achievements":[ + [10,"stat","mp",5], + [100,"stat","hp",10], + [1000,"stat","vit",1], + [10000,"stat","dex",1], + [100000,"stat","speed",0.25], + [1000000,"stat","armor",5], + [10000000,"stat","resistance",10], + ] + }, + "scorpion":{ + "name":"Scorpion","speed":24,"hp":24000,"xp":20000,"attack":100,"damage_type":"physical","respawn":6,"gold":100,"range":32,"frequency":0.8,"aggro":0.3, + "armor":200, + "achievements":[ + [10,"stat","mp",10], + [100,"stat","hp",20], + [1000,"stat","armor",1], + [10000,"stat","dex",1], + [100000,"stat","int",1], + [1000000,"stat","str",1], + [10000000,"stat","attack",15], + ] + }, + "gscorpion":{ + "name":"Scorpion","speed":24,"hp":32000,"xp":48000,"attack":120,"damage_type":"physical","respawn":6,"gold":240,"range":32,"frequency":0.8,"aggro":0.3, + "armor":300, + "achievements":[ + [10,"stat","hp",10], + [100,"stat","mp",20], + [1000,"stat","mp",10], + [10000,"stat","int",1], + [100000,"stat","dex",1], + [1000000,"stat","vit",2], + [10000000,"stat","attack",30], + ] + }, + "xscorpion":{ + "name":"Scorpion","speed":24,"hp":140000,"xp":172000,"attack":720,"damage_type":"physical","respawn":16,"gold":920,"range":32,"frequency":0.8,"aggro":0.3, + "armor":400, + "achievements":[ + [10,"stat","mp",10], + [100,"stat","mp",30], + [1000,"stat","dex",1], + [10000,"stat","apiercing",2], + [100000,"stat","rpiercing",3], + [1000000,"stat","frequency",2], + [10000000,"stat","attack",25], + ], + }, + "bscorpion":{ + "name":"Black Scorpion","speed":24,"hp":576900,"xp":634800,"armor":600,"resistance":400,"attack":3200,"damage_type":"physical","respawn":6,"gold":920,"range":32,"frequency":0.6,"aggro":0.8, + "armor":500, + "resistance":240, + "crit":10, + "poisonous":True, + "abilities":{ + "weakness_aura":{ + "aura":True, + "condition":"weakness", + "radius":100, + "cooldown":4000, + } + }, + "achievements":[ + [10,"stat","mp",10], + [100,"stat","mp",10], + [1000,"stat","dex",0.5], + [10000,"stat","dex",0.5], + ], + }, + "ghost":{ + "name":"Ghost","speed":12,"hp":12000,"xp":16000,"attack":200,"damage_type":"magical","respawn":4,"gold":600,"range":120,"frequency":1,"aggro":0.05,"hit":"explode_p","evasion":20,"resistance":400, + "phresistance":90, + "achievements":[ + [10,"stat","mp",10], + [100,"stat","mp",10], + [1000,"stat","for",1], + [10000,"stat","int",1], + [100000,"stat","int",1], + [1000000,"stat","hp",300], + [10000000,"stat","resistance",10], + ] + }, + "harpy":{ + "name":"Harpy","speed":12,"charge":96,"hp":160000,"xp":192000,"attack":1720,"damage_type":"magical","respawn":4,"gold":600,"range":220,"frequency":0.8,"aggro":0.01,"hit":"explode_p","resistance":600,"armor":160, + #"cooperative":True, + "difficulty":2, + "rpiercing":160, + "phresistance":40, + "charge_skin":"harpy_fly", + "slots":{"mainhand":{"name":"harbringer","level":6}}, + "abilities":{"warp_on_hit":{"unlimited":True,"attr0":0.8/10}}, + "achievements":[ + [10,"stat","hp",10], + [1000,"stat","fzresistance",0.5], + [10000,"stat","fzresistance",0.5], + [100000,"stat","fzresistance",0.5], + [200000,"stat","speed",0.25], + ] + }, + "rharpy":{ + "name":"Rebel Harpy","speed":18,"charge":116,"hp":320000,"xp":332000,"attack":1420,"damage_type":"magical","respawn":400,"gold":600,"range":30,"frequency":0.7,"aggro":1.2,"rage":1.2,"hit":"momentum","resistance":240,"armor":360, + "cooperative":True, + "difficulty":3, + "apiercing":160, + "phresistance":60, + "charge_skin":"rharpy_fly", + "slots":{"mainhand":{"name":"basher","level":9}}, + "achievements":[ + [1,"stat","mp",5], + [10,"stat","attack",2], + [1000,"stat","stresistance",1], + [10000,"stat","stresistance",1], + [20000,"stat","speed",0.25], + ] + }, + "fvampire":{ + "name":"Ms. Dracul","speed":40,"hp":240000,"xp":200000,"attack":875,"damage_type":"magical","respawn":24*60,"gold":24000,"range":120,"frequency":1.2,"aggro":0.05,"hit":"explode_c","prefix":"","resistance":300,"armor":100, + "humanoid":True, + "rbuff":"mlifesteal", + "achievements":[ + [1,"stat","hp",10], + [100,"stat","mp",20], + [1000,"stat","attack",5], + [10000,"stat","for",1], + [100000,"stat","xp",2.5], + [1000000,"stat","lifesteal",1], + [10000000,"stat","lifesteal",2.5], + ] + }, + "minimush":{ + "name":"Pom Pom","speed":12,"hp":500,"xp":600,"attack":120,"damage_type":"magical","respawn":4,"gold":70,"range":120,"frequency":1,"aggro":0.05,"hit":"explode_p", + "resistance":120, + "achievements":[ + [10,"stat","hp",10], + [100,"stat","hp",20], + [1000,"stat","for",1], + [10000,"stat","frequency",0.25], + [100000,"stat","resistance",5], + [1000000,"stat","str",2], + [10000000,"stat","speed",1], + ] + }, + "spider":{ + "name":"Spider","speed":24,"hp":18000,"xp":12000,"attack":80,"damage_type":"physical","respawn":14,"gold":180,"range":32,"frequency":1,"aggro":0.3, + "achievements":[ + [10,"stat","mp",10], + [100,"stat","mp",10], + [1000,"stat","armor",1], + [10000,"stat","for",1], + [100000,"stat","str",1], + [1000000,"stat","crit",0.25], + [10000000,"stat","vit",8], + ] + }, + "bat":{ + "name":"Bat","speed":24,"hp":9600,"xp":8000,"attack":50,"damage_type":"physical","respawn":12,"gold":120,"range":35,"frequency":0.7,"aggro":0.3,"aa":1, + "resistance":120, + "phresistance":35, + "achievements":[ + [10,"stat","hp",10], + [100,"stat","hp",20], + [1000,"stat","armor",1], + [10000,"stat","dex",1], + [100000,"stat","str",2], + [1000000,"stat","gold",0.5], + [10000000,"stat","lifesteal",1], + ] + }, + "nerfedbat":{ + "skin":"bat", + "name":"Bat","speed":24,"hp":2400,"xp":400,"attack":50,"damage_type":"physical","respawn":12,"gold":120,"range":35,"frequency":0.7,"aggro":0.3,"aa":1, + "resistance":120, + "phresistance":35, + "achievements":[ + [100000,"stat","dex",1], + [1000000,"stat","luck",0.5], + ] + }, + "dknight2":{ + "name":"Dark Knight","speed":28,"hp":86000,"xp":72000,"attack":2275,"damage_type":"physical","respawn":40,"gold":800,"range":32,"frequency":1.2,"aggro":0.3,"armor":200,"hide":True, + "achievements":[ + [1,"stat","luck",50], + ] + }, + "mvampire":{ + "name":"Dracul","speed":40,"hp":240000,"xp":200000,"attack":245,"damage_type":"magical","respawn":18*60,"gold":16000,"range":120,"frequency":1.2,"aggro":0.05,"hit":"explode_c","prefix":"","resistance":150,"armor":90, + "humanoid":True, + "rbuff":"mlifesteal", + "achievements":[ + [1,"stat","hp",10], + [100,"stat","mp",20], + [1000,"stat","attack",5], + [10000,"stat","resistance",5], + [100000,"stat","resistance",5], + [1000000,"stat","lifesteal",1], + [10000000,"stat","lifesteal",2.5], + ] + }, + "phoenix":{ + "name":"Phoenix","speed":50,"hp":160000,"xp":180000,"attack":125,"damage_type":"magical","respawn":32,"gold":7200,"range":120,"frequency":1.2,"aggro":0.2,"aa":1,"hit":"explode_a","prefix":"the", + "phresistance":40, + "resistance":160, + "cooperative":True, + "achievements":[ + [1,"stat","hp",10], + [100,"stat","hp",20], + [1000,"stat","vit",1], + [10000,"stat","int",1], + [100000,"stat","resistance",5], + [1000000,"stat","resistance",10], + [10000000,"stat","frequency",1], + ] + }, + "cgoo":{ + "name":"Irradiated Goo","speed":9,"hp":2400,"xp":4800,"attack":320,"damage_type":"physical","respawn":48,"gold":240,"range":64,"frequency":1.2,"aggro":0.1,"aa":1, + "resistance":260, + "difficulty":6, + "achievements":[ + [10,"stat","hp",20], + [100,"stat","vit",1], + [1000,"stat","for",1], + [10000,"stat","hp",100], + [100000,"stat","for",2], + [1000000,"stat","vit",3], + [10000000,"stat","for",5], + ] + }, + "bgoo":{ + "name":"Brawl Goo","skin":"goo4","speed":6,"charge":12,"hp":100000,"xp":100000,"attack":5,"damage_type":"physical","respawn":-1,"gold":20,"range":15,"frequency":0.4,"aggro":0,"aa":1, + "armor":200, + "resistance":200, + "cooperative":True, + "special":True, + "size":1.5, + #"immune":True, + #"respawn_as":"bee", + #"explosion":2000, + "achievements":[ + [1000,"stat","vit",1], + ], + }, + "rgoo":{ + "name":"Rainbow Goo","skin":"gooD","speed":9,"hp":1000000,"xp":48000000,"attack":320,"damage_type":"physical","respawn":-1,"gold":240,"range":64,"frequency":1.2,"aggro":0.1,"aa":1, + "armor":300, + "resistance":300, + "size":1.5, + "cooperative":True, + "special":True, + "achievements":[ + [1,"stat","hp",20], + [100,"stat","for",1], + ] + }, + "skeletor":{ + "name":"Skeletor","speed":40,"hp":80000,"xp":120000,"attack":1800,"damage_type":"physical","respawn":16*60,"gold":20000,"range":80,"frequency":1.2,"aggro":0.2, + "slots":{"mainhand":{"name":"scythe","level":8}}, + "achievements":[ + [1,"stat","for",1], + [100,"stat","vit",1], + [1000,"stat","for",2], + [10000,"stat","vit",3], + [100000,"stat","crit",0.25], + [1000000,"stat","for",10], + [10000000,"stat","for",20], + ] + }, + "ligerx":{ + "name":"Liger X","speed":30,"hp":80000,"xp":120000,"attack":1800,"damage_type":"physical","respawn":16*60,"gold":20000,"range":80,"frequency":1.2,"aggro":0.2,"charge":60,"explanation":"A genetically modified and cybernetically enhanced beast!", + "achievements":[ + [1,"stat","luck",50], + ] + }, + + #main2 + "bigbird":{ + "name":"Hawk","speed":24,"charge":52,"hp":32000,"xp":30000,"attack":480,"damage_type":"physical","respawn":12,"gold":480,"range":20,"frequency":0.8,"aggro":1,"rage":0.4,"evasion":20,"aa":1, + "phresistance":30, + "achievements":[ + [10,"stat","mp",10], + [100,"stat","mp",30], + [1000,"stat","vit",1], + [10000,"stat","evasion",0.25], + [100000,"stat","resistance",5], + [1000000,"stat","speed",0.5], + [10000000,"stat","evasion",1], + ] + }, + "poisio":{ + "name":"Poisio","speed":24,"hp":3600,"xp":4000,"attack":240,"damage_type":"physical","respawn":6,"gold":80,"range":20,"frequency":0.6,"aggro":1,"rage":0.2, + "achievements":[ + [10,"stat","mp",10], + [100,"stat","hp",20], + [1000,"stat","armor",2], + [10000,"stat","dex",1], + [100000,"stat","rpiercing",5], + [1000000,"stat","crit",0.5], + [10000000,"stat","frequency",1], + ] + }, + #winter + "stompy":{ + "name":"Stompy","speed":40,"charge":80,"hp":640000,"xp":600000,"attack":3600,"damage_type":"physical","respawn":36*60,"gold":80000,"range":64,"frequency":0.8,"aggro":0.2, + "achievements":[ + [1,"stat","hp",50], + [100,"stat","mp",20], + [1000,"stat","speed",0.25], + [10000,"stat","range",0.5], + [100000,"stat","mp",50], + [1000000,"stat","frequency",1], + [10000000,"stat","attack",200], + ] + }, + "arcticbee":{ + "name":"Arctic Bee","speed":12,"hp":1600,"xp":1800,"attack":64,"damage_type":"physical","respawn":1,"gold":60,"range":20,"frequency":0.6,"aggro":1,"aa":1,"rage":0.05, + "phresistance":50, + "achievements":[ + [10,"stat","mp",10], + [100,"stat","mp",10], + [1000,"stat","resistance",1], + [10000,"stat","int",1], + [100000,"stat","dex",2], + [1000000,"stat","resistance",5], + [10000000,"stat","range",2.5], + ] + }, + "wolf":{ + "name":"White Wolf","speed":24,"charge":152,"hp":48000,"xp":48800,"attack":480,"damage_type":"physical","respawn":12,"gold":480,"range":20,"frequency":0.8,"aggro":1,"rage":1,"resistance":200,"armor":300, + "achievements":[ + [1,"stat","hp",20], + [100,"stat","mp",20], + [1000,"stat","for",1], + [10000,"stat","resistance",5], + [100000,"stat","vit",3], + [1000000,"stat","xp",1], + [10000000,"stat","speed",2], + ], + #"supporter":True, + }, + "wolfie":{ + "name":"Dark Hound","speed":24,"charge":52,"hp":19200,"xp":16400,"attack":320,"damage_type":"physical","respawn":12,"gold":360,"range":20,"frequency":0.8,"aggro":1,"rage":1,"resistance":100,"armor":200, + "achievements":[ + [1,"stat","hp",20], + [100,"stat","mp",20], + [1000,"stat","hp",30], + [10000,"stat","str",1], + [100000,"stat","vit",1], + [1000000,"stat","armor",5], + [10000000,"stat","mp",500], + ] + }, + "boar":{ + "name":"Wild Boar","speed":20,"charge":40,"hp":12000,"xp":10800,"attack":240,"damage_type":"physical","respawn":10,"gold":240,"range":24,"frequency":0.7,"aggro":1,"rage":1,"armor":100, + "achievements":[ + [10,"stat","hp",10], + [100,"stat","mp",20], + [1000,"stat","vit",1], + [10000,"stat","str",1], + [100000,"stat","int",2], + [1000000,"stat","vit",5], + [10000000,"stat","armor",12], + ] + }, + "iceroamer":{ + "name":"Water Spirit","speed":20,"hp":3600,"xp":4200,"attack":120,"damage_type":"magical","respawn":2,"gold":180,"range":100,"frequency":0.7,"aggro":0.2,"reflection":8,"rpiercing":320,"evasion":10,"hit":"explode_p", + "phresistance":50, + "achievements":[ + [10,"stat","mp",10], + [100,"stat","mp",10], + [1000,"stat","vit",1], + [10000,"stat","int",1], + [100000,"stat","for",2], + [1000000,"stat","reflection",0.5], + [10000000,"stat","rpiercing",20], + ] + }, + "fireroamer":{ + "name":"Fire Spirit","speed":24,"hp":84000,"xp":64200,"attack":320,"damage_type":"magical","respawn":2,"gold":180,"range":280,"frequency":1.2,"aggro":0.2,"rpiercing":320,"evasion":4,"resistance":320,"armor":120,"hit":"explode_p", + "phresistance":50, + "difficulty":1.1, + "abilities":{"burn":{"unlimited":True,"attr0":100}}, + "achievements":[ + [10,"stat","mp",10], + [100,"stat","mp",10], + [1000,"stat","vit",1], + [10000,"stat","int",1], + [100000,"stat","for",2], + [1000000,"stat","evasion",0.5], + [10000000,"stat","apiercing",20], + ] + }, + "bbpompom":{ + "name":"Pom Pom","speed":18,"hp":6400,"xp":6000,"attack":320,"damage_type":"magical","respawn":4,"gold":280,"range":280,"frequency":0.6,"aggro":0.2,"resistance":160,"hit":"explode_p", + "achievements":[ + [10,"stat","mp",10], + [100,"stat","mp",20], + [1000,"stat","vit",1], + [10000,"stat","int",1], + [100000,"stat","int",2], + [1000000,"stat","resistance",5], + [10000000,"stat","range",2], + ] + }, + #underground + "prat":{ + "name":"Vampire Rat","speed":12,"charge":86,"hp":9200,"xp":7600,"attack":320,"armor":160,"damage_type":"physical","respawn":4,"range":32,"frequency":1.6,"aggro":1,"rage":0.4,"lifesteal":120, + "achievements":[ + [1,"stat","hp",10], + [100,"stat","hp",20], + [1000,"stat","vit",1], + [10000,"stat","dex",1], + [100000,"stat","attack",5], + [1000000,"stat","vit",5], + [10000000,"stat","lifesteal",1.25], + ] + }, + "pppompom":{ + "name":"Pom Pom","speed":18,"hp":64000,"xp":62400,"attack":920,"damage_type":"physical","respawn":4,"gold":280,"range":300,"frequency":1.32,"aggro":0.2,"resistance":480,"hit":"explode_p", + "difficulty":1.20, + "poisonous":True, + "achievements":[ + [10,"stat","mp",10], + [100,"stat","mp",20], + [1000,"stat","vit",1], + [10000,"stat","int",1], + [100000,"stat","int",2], + [1000000,"stat","resistance",5], + [10000000,"stat","range",2], + ] + }, + "oneeye":{ + "name":"One Eye","speed":24,"hp":420000,"xp":582000,"armor":160,"resistance":160,"attack":480,"damage_type":"physical","respawn":4,"gold":32,"range":40,"frequency":3,"aggro":1,"rage":0, + "phresistance":30, + "difficulty":1.20, + "abilities":{ + "stone":{"cooldown":6400} + }, + "achievements":[ + [1,"stat","for",1], + [100,"stat","mp",25], + [1000,"stat","attack",5], + [10000,"stat","int",1], + [100000,"stat","resistance",5], + [1000000,"stat","frequency",1], + [10000000,"stat","attack",50], + ] + }, + #halloween2 + "mummy":{ + "name":"Mummy","speed":16,"charge":96,"hp":12000,"xp":16000,"attack":420,"damage_type":"physical","respawn":24,"gold":100,"range":48,"frequency":1.2,"aggro":1.5,"rage":1.5, + "difficulty":2, + "achievements":[ + [1,"stat","hp",20], + [100,"stat","vit",1], + [1000,"stat","str",1], + [10000,"stat","attack",5], + [100000,"stat","speed",0.5], + [1000000,"stat","attack",25], + [10000000,"stat","evasion",1], + ] + }, + "nerfedmummy":{ + "skin":"mummy","name":"Mummy","speed":96,"charge":96,"hp":1600,"xp":1800,"attack":240,"damage_type":"physical","respawn":24,"gold":100,"range":48,"frequency":0.9,"aggro":1,"rage":1, + "achievements":[ + [1,"stat","hp",10], + [100,"stat","hp",20], + [1000,"stat","hp",30], + [10000,"stat","vit",1], + [100000,"stat","vit",2], + [1000000,"stat","crit",0.5], + [10000000,"stat","manasteal",0.25], + ] + }, + "booboo":{ + "name":"Boo Boo","speed":16,"charge":96,"hp":8000,"xp":12000,"attack":220,"damage_type":"pure","respawn":48,"gold":30,"range":420,"frequency":1.2,"aggro":1.5,"aa":1,"rage":1.5, + "phresistance":50, + "difficulty":1.25, + "achievements":[ + [1,"stat","mp",10], + [100,"stat","mp",20], + [1000,"stat","vit",1], + [10000,"stat","for",1], + [100000,"stat","str",2], + [1000000,"stat","speed",0.5], + [10000000,"stat","range",2.25], + ] + }, + "pinkgoblin":{ + "name":"Pink Goblin","speed":40,"hp":420000,"xp":460000, + "attack":2400, + "damage_type":"magical","respawn":40,"gold":16000,"range":240,"frequency":0.4,"aggro":0,"hit":"explode_p","prefix":"","resistance":350,"armor":200, + "abilities":{"self_healing":{"heal":96000,"cooldown":4000}}, + "difficulty":2, + "slots":{"mainhand":{"name":"pmace","level":8}}, + "achievements":[ + [1000,"stat","mp",10], + [2000,"stat","vit",1], + [10000,"stat","for",1], + [100000,"stat","str",2], + [1000000,"stat","speed",0.5], + [10000000,"stat","range",1.25], + ] + }, + "stoneworm":{ + "name":"Stone Worm","speed":12,"charge":46,"hp":2200,"xp":2400,"attack":360,"damage_type":"physical","respawn":1,"gold":64,"range":20,"frequency":0.6,"aggro":1,"rage":1,"apiercing":800,"balance":"Spadar", + "achievements":[ + [10,"stat","hp",10], + [100,"stat","mp",20], + [1000,"stat","hp",30], + [10000,"stat","for",1], + [100000,"stat","for",2], + [1000000,"stat","apiercing",5], + [10000000,"stat","resistance",10], + ] + }, + "mrgreen":{ + "name":"Mr. Green","speed":40,"charge":90,"hp":36000000,"xp":48000000,"attack":1200,"damage_type":"physical", + "respawn":94*60, + "gold":16000,"range":620,"frequency":1.6,"aggro":1,"rage":1,"apiercing":320,"resistance":900,"cooperative":True,"announce":"#256943", + "cbuff":[[60,"halloween0"],[70,"halloween1"],[200,"halloween2"]], + "slots":{"mainhand":{"name":"gbow","level":10}}, + "achievements":[ + [1,"stat","hp",10], + [10,"stat","mp",20], + [100,"stat","vit",1], + [1000,"stat","dex",1], + [10000,"stat","armor",10], + [100000,"stat","rpiercing",10], + [1000000,"stat","manasteal",0.32], + ] + }, + "slenderman":{ + "name":"Slenderman","speed":280,"hp":66666,"xp":4800,"attack":3600,"damage_type":"physical","respawn":60*10,"gold":16000,"range":52,"frequency":0.3,"aggro":0.05, + "reflection":96, + "immune":True, + "special":True, + "cooperative":True, + "phresistance":95, + "announce":"#3D3C81", + "cbuff":[[60,"halloween0"],[70,"halloween1"],[200,"halloween2"]], + "achievements":[ + [1,"stat","hp",10], + [10,"stat","mp",10], + [100,"stat","for",1], + ] + }, + "mrpumpkin":{ + "name":"Mr. Pumpkin","speed":40,"hp":36000000,"xp":48000000,"attack":1200,"damage_type":"magical", + "respawn":54*60, + "phresistance":30, + "gold":16000,"range":520,"frequency":1,"aggro":0.05,"hit":"explode_c","cooperative":True,"announce":"#FD8940", + "cbuff":[[60,"halloween0"],[70,"halloween1"],[200,"halloween2"]], + "slots":{"mainhand":{"name":"oozingterror","level":8}}, + "achievements":[ + [1,"stat","hp",10], + [10,"stat","mp",20], + [100,"stat","vit",1], + [1000,"stat","str",1], + [10000,"stat","resistance",10], + [100000,"stat","apiercing",10], + [1000000,"stat","crit",1], + ] + }, + "greenjr":{ + "name":"Green Jr.","speed":60,"charge":120,"hp":4200,"xp":120000,"attack":30,"damage_type":"physical", + "cbuff":[[60,"halloween0"],[70,"halloween1"],[200,"halloween2"]], + "respawn":480 and 12*72*60, #sprocess_game_data + "gold":16000,"range":80,"frequency":20,"aggro":1,"rage":1,"rpiercing":420,"resistance":400,"evasion":40,"reflection":4, + "difficulty":2, + "achievements":[ + [1,"stat","mp",10], + [10,"stat","vit",1], + [100,"stat","armor",10], + [1000,"stat","resistance",15], + [10000,"stat","for",3], + [100000,"stat","frequency",1], + [1000000,"stat","speed",1], + ] + }, + "jr":{ + "name":"Jr.","speed":40,"charge":90,"hp":3200,"xp":80000,"attack":10,"damage_type":"magical", + "cbuff":[[60,"halloween0"],[70,"halloween1"],[200,"halloween2"]], + "respawn":480 and 6*72*60, #sprocess_game_data + "gold":6000,"range":30,"frequency":20,"aggro":1,"rage":1,"resistance":400,"evasion":80, + "difficulty":2, + "achievements":[ + [1,"stat","mp",10], + [10,"stat","vit",1], + [100,"stat","resistance",10], + [1000,"stat","armor",8], + [10000,"stat","attack",20], + [100000,"stat","luck",1], + [1000000,"stat","speed",1], + ] + }, + + #tests + "chestm":{"name":"Angry Chest","speed":4,"hp":6400,"xp":6000,"attack":320,"damage_type":"magical","respawn":4,"gold":280,"range":280,"frequency":0.6,"aggro":0.2,"resistance":160,"hit":"explode_p","hide":True}, + + #prototypes + "plantoid":{ + "name":"Sprawling","speed":20,"hp":120000,"xp":96000,"attack":640,"damage_type":"physical","respawn":18,"gold":1,"range":80,"frequency":1.2,"aggro":0.2,"armor":160,"resistance":190, + "achievements":[ + [1,"stat","mp",10], + [100,"stat","hp",20], + [1000,"stat","int",1], + [10000,"stat","mp",40], + [100000,"stat","dex",1], + [1000000,"stat","resistance",5], + [10000000,"stat","mp",250], + ] + }, + "icegolem":{ + "name":"Ice Golem","speed":12,"charge":48,"hp":16000000,"xp":92000000,"attack":2400,"damage_type":"physical","respawn":-1,"gold":1,"range":64,"frequency":1.2,"aggro":0.2,"resistance":800,"armor":800, + "announce":True, + "special":True, + "phresistance":40, + "difficulty":12, + "cooperative":True, + "abilities":{"multi_freeze":{"cooldown":2000,"damage":2000}}, + "achievements":[ + [1,"stat","hp",10], + [10,"stat","hp",30], + ] + }, + "ent":{ + "name":"Ent","speed":12,"charge":48,"hp":8000000,"xp":9200000,"attack":3600,"damage_type":"physical","respawn":12,"gold":1,"range":64,"frequency":1.2,"aggro":0.2,"resistance":100,"armor":100, + "phresistance":15, + "abilities":{ + "mtangle":{"cooldown":3200} + }, + "achievements":[ + [1,"stat","hp",10], + [100,"stat","hp",30], + [1000,"stat","vit",1], + [10000,"stat","for",3], + [100000,"stat","resistance",10], + [1000000,"stat","attack",25], + [10000000,"stat","speed",2], + ] + }, + "welemental":{"name":"Water Elemental","speed":20,"hp":80000,"xp":10,"attack":1800,"damage_type":"physical","respawn":1,"gold":1,"range":80,"frequency":1.2,"aggro":0.2,"evasion":80}, + "felemental":{"name":"Fire Elemental","speed":20,"hp":80000,"xp":10,"attack":1800,"damage_type":"physical","respawn":1,"gold":1,"range":80,"frequency":1.2,"aggro":0.2,"evasion":80}, + "nelemental":{"name":"Nature Elemental","speed":20,"hp":80000,"xp":10,"attack":1800,"damage_type":"physical","respawn":1,"gold":1,"range":80,"frequency":1.2,"aggro":0.2,"evasion":80}, + "eelemental":{"name":"Earth Elemental","speed":20,"hp":80000,"xp":10,"attack":1800,"damage_type":"physical","respawn":1,"gold":1,"range":80,"frequency":1.2,"aggro":0.2,"evasion":80}, + + #misc + "greenfairy":{ + "phresistance":70, + "name":"Fairy","speed":10,"hp":3600000,"xp":2000000,"attack":3000,"damage_type":"magical","respawn":0,"gold":1000,"range":999999,"frequency":100,"aggro":0,"hit":"explode_c","aa":1, + "achievements":[ + [10,"stat","luck",2], + ], + }, + "redfairy":{ + "phresistance":70, + "name":"Fairy","speed":10,"hp":4800000,"xp":2000000,"attack":4000,"damage_type":"magical","respawn":0,"gold":1000,"range":999999,"frequency":100,"aggro":0,"hit":"explode_c","aa":1, + "achievements":[ + [10,"stat","gold",2], + ], + "abilities":{"heal":{"heal":20000,"cooldown":1000}} + }, + "bluefairy":{ + "phresistance":70, + "name":"Fairy","speed":10,"hp":4000000,"xp":2000000,"attack":2400,"damage_type":"magical","respawn":0,"gold":1000,"range":999999,"frequency":100,"aggro":0,"hit":"explode_c","aa":1, + "achievements":[ + [10,"stat","xp",2], + ], + }, + "rudolph":{ + "name":"Reindeer","speed":24,"hp":12000000,"xp":2000000,"attack":1600,"damage_type":"magical","respawn":60*60,"gold":10000,"range":999999,"frequency":10,"aggro":0,"hit":"explode_c","prefix":"the", + "resistance":1200, + "armor":1200, + "achievements":[ + [100,"stat","for",2], + [1000,"stat","for",2], + ] + }, + "grinch":{ + "name":"Grinch","speed":40,"hp":24000000,"xp":12000, + "humanoid":True, + "cooperative":True, + "global":True, #chest spawns on player + "attack":9, + "damage_type":"magical","respawn":12*60*60,"gold":16000,"range":120,"frequency":0.5,"aggro":0,"hit":"explode_c","prefix":"","resistance":150, + "special":True,"passive":True,"abilities":{"portal":{"cooldown":0},"self_healing":{"heal":8008,"cooldown":8008}},"goldsteal":1, + "phresistance":90, + #"good":True,"attack":1200, + "slots":{"mainhand":{"name":"ornamentstaff","level":13}}, + "announce":"#C82F17", + "achievements":[ + [1,"stat","hp",20], + [100,"stat","fzresistance",1], + [1000,"stat","pnresistance",1], + ] + }, + + + #killmany + "goldenbat":{ + "name":"Golden Bat","speed":24,"hp":24000,"xp":20000,"attack":50,"damage_type":"physical","respawn":-1,"gold":120000,"range":35,"frequency":0.7,"aggro":0.3,"aa":1, + "difficulty":100, + "phresistance":70, + "explanation":"Spawns in Cave of Darkness around every 80,000 Bat spawns", + "achievements":[ + [1,"stat","gold",1], + [10,"stat","luck",1], + [100,"stat","gold",1], + [1000,"stat","range",1], + [2000,"stat","frequency",1], + [5000,"stat","gold",5], + ] + }, + "tinyp":{ + "name":"Fairy","speed":24,"hp":5600,"xp":12000,"attack":240,"damage_type":"physical","respawn":-1,"gold":120000,"range":35,"frequency":5,"aggro":0.3,"aa":1, + "escapist":True,"roam":True,"cute":True, + "abilities":{"self_healing":{"heal":1200,"cooldown":10}}, + "special":True,"immune":True, + "phresistance":98, + "achievements":[ + [1,"stat","for",0.25], + [10,"stat","luck",0.5], + ], + }, + + #bosses + #"aqueen":{"name":"Arachnid Queen","speed":24,"hp":2400,"xp":2000,"attack":50,"damage_type":"physical","respawn":-1,"gold":120000,"range":35,"frequency":0.7,"aggro":0.3,"aa":1}, + + #specials + "tiger":{ + "name":"Tiger","speed":24,"hp":12000,"xp":24800,"attack":960,"damage_type":"physical","respawn":30*60,"gold":480,"range":20,"frequency":0.8,"aggro":0,"rage":0,"reflection":100,"armor":540, + "announce":"#D65A3A", + "cute": True, + "explanation":"Legendary animal, rarely appears to players.", + "cooperative":True, + "avoidance":99, + "special":True,"immune":True, + "phresistance":60, + "drop_on_hit":True, + "peaceful":True, + "roam":True, + "achievements":[ + [1,"stat","vit",1], + ], + #"supporter":True, + }, + "goblin":{ + "name":"Sneaky Goblin","speed":30,"hp":50,"xp":640000,"attack":0,"damage_type":"physical","respawn":-1,"gold":4000000,"range":2,"frequency":1,"aggro":0,"evasion":99.95,"reflection":99.95,"special":True,"immune":True, + "phresistance":30, + "achievements":[ + [1,"stat","gold",2], + [100,"stat","xp",5], + [1000,"stat","gold",5], + [5000,"stat","reflection",2], + ] + }, + "pinkgoo":{ + "name":"Love Goo","speed":8,"hp":40,"xp":12000,"attack":100,"damage_type":"physical","respawn":60*60,"gold":10000,"range":20,"frequency":1,"aggro":0,"avoidance":98.0,"special":True,"immune":True,"1hp":True,"cooperative":True, + "phresistance":30, + "achievements":[ + [10,"stat","vit",1], + [100,"stat","speed",0.5], + [1000,"stat","hp",200], + [10000,"stat","armor",10], + ] + }, + "snowman":{ + "name":"Snowman","speed":8,"hp":1200,"xp":12000,"attack":80,"damage_type":"physical","respawn":60*60,"gold":10000,"range":20,"frequency":1,"aggro":0,"special":True,"immune":True,"cooperative":True,"1hp":True,"announce":"#B1DCEF", + "s":{"fullguardx":{"ms":5*60*1000}}, + "achievements":[ + [10,"stat","mp",10], + [100,"stat","resistance",3], + [1000,"stat","resistance",5], + [10000,"stat","attack",5], + [100000,"stat","speed",1.75], + [1000000,"stat","luck",5], + ] + }, + "dragold":{ + "name":"Dragold","speed":22,"hp":12800000*2,"xp":12000000*2,"attack":800,"damage_type":"magical","respawn":3*60*60,"gold":10000,"range":320,"frequency":1,"aggro":0,"special":True,"cooperative":True,"announce":"#D7B717","armor":240,"resistance":320, + "s":{"fullguardx":{"ms":2*60*1000}}, + "phresistance":65, + "abilities":{"multi_burn":{"cooldown":24000,"damage":4000}}, + "achievements":[ + [1,"stat","gold",1], + [10,"stat","for",0.5], + [20,"stat","luck",1], + ], + "projectile":"fireball", + }, + "wabbit":{ + "name":"Wabbit","speed":60,"hp":32000,"armor":180,"resistance":180,"xp":1000000,"attack":60,"damage_type":"physical","respawn":60*60,"gold":1000,"range":20,"frequency":1,"aggro":0,"avoidance":98.8,"special":True,"immune":True,"cooperative":True,"operator":True,"rbuff":"easterluck","s":{"fullguard":{"ms":5*60*1000}}, + "phresistance":70, + "achievements":[ + [1,"stat","xp",1], + [100,"stat","xp",1], + [1000,"stat","luck",1], + [5000,"stat","luck",1], + [10000,"stat","speed",0.75], + [100000,"stat","speed",1], + ] + + }, + "franky":{ + "name":"Franky","speed":48,"charge":64,"hp":120000000,"xp":200000000,"attack":2910,"damage_type":"magical","hit":"explode_c","respawn":-1,"gold":10000,"range":948,"frequency":1.6,"aggro":1,"rage":0,"special":True,"cooperative":True,"spawns":[[200,"nerfedmummy"]],"announce":"#9D99EF", + "phresistance":70, + "humanoid":True, + "achievements":[ + [1,"stat","for",1], + [100,"stat","attack",10], + [1000,"stat","attack",20], + [10000,"stat","frequency",1], + [100000,"stat","xp",2], + [1000000,"stat","range",1], + ] + }, + "gredpro":{ + "name":"Protector of Fire","speed":48,"charge":84,"hp":2400000,"xp":3200000,"attack":120,"damage_type":"magical","hit":"explode_c","respawn":10*60,"gold":10000,"range":948,"frequency":1.2,"aggro":1,"rage":0, + "slots":{"mainhand":{"name":"firestaff","level":12}}, + "abilities":{"burn":{"unlimited":True,"attr0":100}}, + }, + "ggreenpro":{ + "name":"Protector of Nature","speed":48,"charge":64,"hp":1600000,"xp":9600000,"attack":1120,"damage_type":"physical","hit":"explode_c","respawn":60*60,"gold":10000,"range":948,"frequency":3,"aggro":1,"rage":0, + "slots":{"mainhand":{"name":"woodensword","level":12}}, + "abilities":{ + "tangle":{"cooldown":1600}, + "self_healing":{"heal":48000,"cooldown":2000}, + }, + }, + "gbluepro":{ + "name":"Protector of Frost","speed":48,"charge":84,"hp":3200000,"xp":7200000,"attack":9600,"damage_type":"magical","hit":"explode_c","respawn":5*60,"gold":10000,"range":948,"frequency":1.2,"aggro":1,"rage":0, + "cooperative":True, + "slots":{"mainhand":{"name":"froststaff","level":12}}, + "abilities":{"multi_freeze":{"cooldown":4000,"damage":800}}, + "article":"event-mae", + }, + "gpurplepro":{ + "name":"Protector of Darkness","speed":48,"charge":84,"hp":4300000,"xp":8200000,"attack":4893,"damage_type":"magical","hit":"explode_c","respawn":7*60,"gold":10000,"range":948,"frequency":2,"aggro":1,"rage":0, + "cooperative":True, + "slots":{"mainhand":{"name":"oozingterror","level":12}}, + "abilities":{"putrid":{"curse":True,"poison":True}}, + "article":"event-mae", + }, + #crypt + "a1":{ + "name":"Spike","speed":32,"charge":67,"hp":18700000,"xp":32000000,"difficulty":8,"attack":4240,"damage_type":"magical","respawn":-1,"gold":120000,"range":147,"frequency":1.2,"aggro":1,"rage":1,"roam":True, + "phresistance":10, + "armor":120,"resistance":260, + "slots":{"mainhand":{"name":"vstaff","level":10}}, + "humanoid":True, + "spawns":[[200,"nerfedbat"]], + }, + "a2":{ + "name":"Bill","speed":32,"charge":96,"hp":420000,"xp":1200000,"difficulty":8,"attack":2240,"damage_type":"physical","respawn":-1,"gold":120000,"range":35,"frequency":1.4,"aggro":1,"rage":1,"roam":True, + "armor":220,"resistance":160, + "phresistance":15, + "slots":{"mainhand":{"name":"vdagger","level":9},"offhand":{"name":"vdagger","level":10}}, + "abilities":{ + "anger":{"cooldown":8000,"radius":300}, + }, + "poisonous":True, + "humanoid":True, + }, + "a3":{ + "name":"Lestat","speed":32,"charge":80,"hp":342000,"xp":9600000,"difficulty":8,"attack":1520,"damage_type":"physical","respawn":-1,"gold":120000,"range":35,"frequency":1.2,"aggro":1,"rage":1,"roam":True, + "phresistance":20, + "armor":220,"resistance":160, + "slots":{"mainhand":{"name":"vhammer","level":10},"offhand":{"name":"vhammer","level":10}}, + "explosion":20, + "abilities":{ + "anger":{"cooldown":8000,"radius":300} + }, + "humanoid":True, + }, + "a4":{ + "name":"Orlok","speed":42,"charge":86,"hp":560000,"xp":1600000,"difficulty":8,"attack":720,"damage_type":"physical","respawn":-1,"gold":120000,"range":35,"frequency":1.5,"aggro":1,"rage":1,"roam":True, + "phresistance":25, + "armor":320,"resistance":160, + "slots":{"mainhand":{"name":"scythe","level":9}}, + "humanoid":True, + "spawns":[[1600,"zapper0"]], + }, + "a5":{ + "name":"Elena","speed":32,"charge":76,"hp":230000,"xp":1200000,"difficulty":8,"attack":240,"damage_type":"magical","respawn":-1,"gold":120000,"range":135,"frequency":0.3,"aggro":1,"rage":1,"roam":True, + "phresistance":25, + "armor":60,"resistance":240, + "abilities":{ + "healing":{"heal":66000,"cooldown":800} + }, + "slots":{"mainhand":{"name":"lmace","level":10}}, + "humanoid":True, + "supporter":True, + }, + "a6":{ + "name":"Marceline","speed":32,"charge":86,"hp":320000,"xp":880000,"difficulty":8,"attack":8960,"damage_type":"physical","respawn":-1,"gold":120000,"range":35,"frequency":2,"aggro":1,"rage":1,"roam":True, + "phresistance":30, + "armor":220,"resistance":120, + "slots":{"mainhand":{"name":"scythe","level":9}}, + "abilities":{ + "weakness_aura":{ + "aura":True, + "condition":"weakness", + "radius":100, + "cooldown":4000, + } + }, + "humanoid":True, + }, + "a7":{ + "name":"Lucinda","speed":32,"charge":72,"hp":720000,"xp":1200000,"difficulty":8,"attack":910,"damage_type":"magical","respawn":-1,"gold":120000,"range":135,"frequency":1.2,"aggro":1,"rage":1,"roam":True, + "phresistance":30, + "armor":50,"resistance":200, + "slots":{"mainhand":{"name":"oozingterror","level":10}}, + "abilities":{ + "dampening_aura":{"radius":300,"cooldown":180,"aura":True,"condition":"dampened"}, + "mlight":{"cooldown":3000}, + }, + "humanoid":True, + }, + "a8":{ + "name":"Angel","speed":32,"charge":76,"hp":560000,"xp":1200000,"difficulty":8,"attack":2680,"damage_type":"physical","respawn":-1,"gold":120000,"range":35,"frequency":4,"aggro":1,"rage":1,"roam":True, + "phresistance":35, + "armor":220,"resistance":220, + "slots":{"mainhand":{"name":"pinkie","level":10},"offhand":{"name":"pinkie","level":10}}, + "abilities":{ + "curse_aura":{"radius":300,"cooldown":4000,"aura":True,"condition":"cursed"}, + }, + "humanoid":True, + }, + "vbat":{ + "phresistance":70, + "name":"Vampireling","speed":24,"charge":84,"hp":156000,"xp":720000,"difficulty":17,"attack":1240,"damage_type":"physical","respawn":-1,"gold":120000,"range":35,"frequency":1.56,"aggro":0.3,"rage":0.1,"aa":1, + }, + #mage + "xmagefz":{ + "hide":True, + "immune":True, + "phresistance":20, + "name":"Mage","speed":24,"charge":84,"hp":4800000,"xp":7200000,"attack":1640,"damage_type":"magical","respawn":0,"gold":120000,"range":135,"frequency":1.26,"aggro":1.8,"rage":1.8, + "armor":120,"resistance":360, + "respawn_as":"xmagefi", + "slots":{"mainhand":{"name":"vstaff","level":13}}, + "difficulty":0, + "abilities":{ + "deepfreeze":{"cooldown":6000,"radius":300}, + }, + }, + "xmagefi":{ + "hide":True, + "immune":True, + "phresistance":35, + "name":"Mage","speed":24,"charge":84,"hp":5600000,"xp":1440000,"difficulty":0,"attack":2240,"damage_type":"magical","respawn":0,"gold":120000,"range":135,"frequency":1.46,"aggro":1.8,"rage":1.8, + "armor":220,"resistance":360, + "slots":{"mainhand":{"name":"firestaff","level":13}}, + "respawn_as":"xmagen", + "abilities":{ + "anger":{"cooldown":8000,"radius":300}, + "multi_burn":{"cooldown":4000,"damage":4000}, + }, + }, + "xmagen":{ + "hide":True, + "immune":True, + "phresistance":50, + "name":"Mage","speed":24,"charge":84,"hp":6400000,"xp":21600000,"difficulty":0,"attack":2440,"damage_type":"magical","respawn":0,"gold":120000,"range":135,"frequency":1.66,"aggro":1.8,"rage":1.8, + "reflection":30, + "armor":320,"resistance":360, + "slots":{"mainhand":{"name":"mushroomstaff","level":13}}, + "respawn_as":"xmagex", + "poisonous":True, + "abilities":{ + "self_healing":{"heal":4800,"cooldown":2000}, + "mtangle":{"cooldown":3200}, + }, + + }, + "xmagex":{ + "name":"Dark Mage","speed":24,"charge":84,"hp":7200000,"xp":28800000,"difficulty":64,"attack":10640,"damage_type":"magical","respawn":-1,"gold":120000,"range":135,"frequency":1.56,"aggro":1.8,"rage":1.8, + "phresistance":65, + "armor":360,"resistance":420, + "immune":True, + "slots":{"mainhand":{"name":"oozingterror","level":13}}, + "abilities":{ + "anger":{"cooldown":8000,"radius":300}, + "warpstomp":{"cooldown":4000,"radius":160,"stun":1500}, + }, + "achievements":[ + [1,"stat","fzresistance",1], + [5,"stat","firesistance",1], + [10,"stat","phresistance",1], + [100,"stat","frequency",1], + [1000,"stat","xp",2], + [10000,"stat","gold",2], + ] + }, + #cyberland + "mechagnome":{ + "name":"Mech-a Gnome","speed":1,"charge":120,"hp":164000,"xp":80000,"attack":48,"damage_type":"physical","respawn":480,"gold":6000,"range":30,"frequency":4,"aggro":0,"rage":0,"resistance":600,"armor":600,"abilities":{"portal":{"cooldown":0}}, + "achievements":[ + [1,"stat","hp",10], + [100,"stat","hp",20], + [1000,"stat","vit",1], + [10000,"stat","dex",1], + [100000,"stat","attack",5], + [1000000,"stat","vit",5], + [10000000,"stat","lifesteal",1.25], + ] + }, + + #humanoids + "d_wiz":{"name":"Dark Wizard","skin":"shadow","speed":12,"charge":90,"hp":100000,"xp":10000,"attack":5200,"damage_type":"magical","respawn":6000,"gold":20,"range":240,"frequency":2,"aggro":1, + "slots":{"mainhand":{"name":"oozingterror","level":13}},"abilities":{"self_healing":{"heal":4800,"cooldown":2000}}, + "unlist":True,"armor":560,"resistance":920, + }, + + #targets + "target":{"name":"Target Automatron","speed":12,"hp":50000,"xp":1000,"attack":0,"damage_type":"physical","respawn":0,"gold":20,"range":1,"frequency":0.1,"aggro":0,"stationary":True,"orientation":2,"humanoid":True,"phresistance":50,}, + "target_a500":{"name":"Target Automatron","speed":12,"hp":50000,"xp":1000,"armor":500,"attack":0,"damage_type":"physical","respawn":0,"gold":20,"range":1,"frequency":0.1,"aggro":0,"stationary":True,"orientation":0,"humanoid":True,"immune":True}, + "target_a750":{"name":"Target Automatron","speed":12,"hp":50000,"xp":1000,"armor":750,"attack":0,"damage_type":"physical","respawn":0,"gold":20,"range":1,"frequency":0.1,"aggro":0,"stationary":True,"orientation":0,"humanoid":True,}, + "target_r500":{"name":"Target Automatron","speed":12,"hp":50000,"xp":1000,"resistance":500,"evasion":50,"attack":0,"damage_type":"physical","respawn":0,"gold":20,"range":1,"frequency":0.1,"aggro":0,"stationary":True,"orientation":0,"humanoid":True,}, + "target_r750":{"name":"Target Automatron","speed":36,"hp":50000,"xp":1000,"resistance":750,"attack":0,"damage_type":"physical","respawn":0,"gold":20,"range":1,"frequency":0.1,"aggro":0,"stationary":True,"orientation":0,"abilities":{"portal":{"cooldown":0}},"humanoid":True,}, + "target_ar900":{ + "name":"Target Automatron","speed":12,"hp":50000,"xp":1000,"resistance":900,"armor":900,"attack":0,"damage_type":"physical","respawn":0,"gold":20,"range":1,"frequency":0.1,"aggro":0,"stationary":True,"orientation":0, + "achievements":[ + [100,"stat","for",1], + ], + "humanoid":True, + + # "abilities":{ + # "deepfreeze":{"cooldown":6000,"radius":300}, + # }, + }, + "target_ar500red":{"name":"Target Automatron","speed":12,"hp":500000,"xp":1000,"resistance":500,"armor":500,"reflection":50,"evasion":50,"dreturn":50,"attack":0,"damage_type":"physical","respawn":0,"gold":20,"range":1,"frequency":0.1,"aggro":0,"stationary":True,"orientation":1,"abilities":{"self_healing":{"heal":100000,"cooldown":10000}},"humanoid":True,}, + + #POSITIVE + + + + #pets + "puppy1":{"name":"Puppy","speed":16,"charge":12,"hp":100,"xp":-500,"attack":5,"damage_type":"physical","respawn":6000,"gold":20,"range":15,"frequency":0.4,"aggro":0,"aa":0,"cute":True}, + "puppy2":{"name":"Puppy","speed":16,"charge":12,"hp":100,"xp":-500,"attack":5,"damage_type":"physical","respawn":6000,"gold":20,"range":15,"frequency":0.4,"aggro":0,"aa":0,"cute":True}, + "puppy3":{"name":"Puppy","speed":16,"charge":12,"hp":100,"xp":-500,"attack":5,"damage_type":"physical","respawn":6000,"gold":20,"range":15,"frequency":0.4,"aggro":0,"aa":0,"cute":True}, + "puppy4":{"name":"Puppy","speed":16,"charge":12,"hp":100,"xp":-500,"attack":5,"damage_type":"physical","respawn":6000,"gold":20,"range":15,"frequency":0.4,"aggro":0,"aa":0,"cute":True}, + "kitty1":{"name":"Kitty","speed":14,"charge":12,"hp":100,"xp":-500,"attack":5,"damage_type":"physical","respawn":6000,"gold":20,"range":15,"frequency":0.4,"aggro":0,"aa":0,"cute":True}, + "kitty2":{"name":"Kitty","speed":14,"charge":12,"hp":100,"xp":-500,"attack":5,"damage_type":"physical","respawn":6000,"gold":20,"range":15,"frequency":0.4,"aggro":0,"aa":0,"cute":True}, + "kitty3":{"name":"Kitty","speed":14,"charge":12,"hp":100,"xp":-500,"attack":5,"damage_type":"physical","respawn":6000,"gold":20,"range":15,"frequency":0.4,"aggro":0,"aa":0,"cute":True}, + "kitty4":{"name":"Kitty","speed":14,"charge":12,"hp":100,"xp":-500,"attack":5,"damage_type":"physical","respawn":6000,"gold":20,"range":15,"frequency":0.4,"aggro":0,"aa":0,"cute":True}, + + #traps + "fieldgen0":{"trap":True,"hide":True,"name":"Field Generator","speed":0,"hp":6400,"armor":2200,"resistance":1600,"xp":0,"attack":0,"damage_type":"pure","respawn":-1,"range":0,"frequency":0,"aggro":0,"aa":1, + "abilities":{ + "dampening_aura":{"radius":300,"cooldown":180,"aura":True,"condition":"dampened"}, + "degen":{"amount":60,"cooldown":200}, + }, + }, + "zapper0":{"trap":True,"hide":True,"name":"Zapper","speed":0,"hp":6400,"armor":2200,"resistance":1600,"xp":0,"attack":0,"damage_type":"pure","respawn":-1,"range":0,"frequency":0,"aggro":0,"aa":1, + "abilities":{ + "zap":{"amount":1200,"pure":True,"cooldown":1000,"radius":300}, + "degen":{"amount":20,"cooldown":200}, + }, + } + +} + +for m in ["puppy1","puppy2","puppy3","puppy3"]: + monsters[m]["pet"]={ + "level":{ + "speed":2, + "charge":3, + "attack":40, + "hp":300, + "armor":20, + "resistance":30, + "evasion":5, + }, + "xp":1000, + "exponential":True, + "aggression":[10,100], + "passion":[50,100], + "courage":[80,100], + "obedience":[0,50], + "chatter":[20,100], + "brightness":1/100, #XP Rate + } + +monster_gold={ + +} + +for name in monsters: + if not monsters[name].get("skin"): monsters[name]["skin"]=name + if not monsters[name].get("rage"): monsters[name]["rage"]=0 + if not monsters[name].get("aggro"): monsters[name]["aggro"]=0 + if not monsters[name].get("mp"): monsters[name]["mp"]=math.ceil(monsters[name]["hp"]*2/100) + monster_gold[name]=monsters[name].get("gold",1) + try: del monsters[name]["gold"] + except: pass \ No newline at end of file diff --git a/design/multipliers.py b/design/multipliers.py new file mode 100644 index 0000000..304bb1a --- /dev/null +++ b/design/multipliers.py @@ -0,0 +1,9 @@ +extra_shells=0 +multipliers={ + "extra_shells":extra_shells, + "shells_to_gold":32000, + "buy_to_sell":0.6, + "secondhands_mult":2, + "secondhands_cash_mult":3, + "lostandfound_mult":4, +} \ No newline at end of file diff --git a/design/npcs.py b/design/npcs.py new file mode 100644 index 0000000..818b54d --- /dev/null +++ b/design/npcs.py @@ -0,0 +1,938 @@ +# This Python file uses the following encoding: utf-8 +npcs={ + "pots":{ + "role":"merchant", + "items":[ + "hpot0","mpot0","hpot1","mpot1",None, + None,None,None,None,None, + None,None,None,None,None, + None,None,None,None,None, + ], + "skin":"yellowlady", + "atype":"once", + "stopframe":1, + "says":"Oh, Hello", + "ignore":True, + }, + "standmerchant":{ + "role":"standmerchant", + "items":[ + "stand0",None,None,"ghatb","ghatp", + None,None,None,None,None, + None,None,None,None,None, + None,None,None,None,"test_orb", + ], + "skin":"purplelady", + #"atype":"once", + #"stopframe":1, + "type":"fullstatic", + "cx":{"hat":"hat221"}, + "says":"Huu Huu", + "color":"#3FEEA2", + "name":"Divian", + }, + "pvptokens":{ + "role":"pvptokens", + "skin":"pvptokens", + "token":"pvptoken", + "says":"Grrr", + "color":"#9C201C", + #"atype":"flow", + "stand":"wstand_texture", + "aspeed":"slow", + "name":"Gn. Spence", + "side_interaction":{"auto":True,"skin":"pknight","message":"These tokens of honor represent victory. Make sure to join all the PVP events and spend some time in PVP realms. Glorious!"}, + }, + "funtokens":{ + "role":"funtokens", + "skin":"funtokens", + "token":"funtoken", + "says":"Hihihi", + "color":"#92D467", + "atype":"flow", + "stand":"standg_texture", + "aspeed":"slow", + "name":"Tricksy", + "side_interaction":{"auto":True,"skin":"ftokener","message":"Bring your fun tokens to me and I'll give you some exciting items!"}, + }, + "friendtokens":{ + "role":"friendtokens", + "skin":"xxschar2h", + "token":"friendtoken", + "says":"Hihihi", + "color":"#92D467", + "atype":"flow", + "stand":"fstand_texture", + "aspeed":"slow", + "name":"Fvona", + "side_interaction":{"auto":True,"skin":"xxschar2h","message":"Invite your friends to Adventure Land to win some of these goodie goodies!"}, + }, + "shellsguy":{ + "role":"shells", + "name":"Mr. Dworf", + "skin":"fancyd", + "type":"fullstatic", + "says":"Sup", + }, + "monsterhunter":{ + "role":"monstertokens", + "token":"monstertoken", + "name":"Daisy", + "skin":"daisy", + "type":"fullstatic", + "says":"Hi!", + "color":"#B4FAA0", + }, + "mcollector":{ + "role":"mcollector", + "quest":"mcollector", + "name":"Cole", + "skin":"proft", + "type":"fullstatic", + "says":"Hmm", + "color":"#67A464", + }, + "thief":{ + "role":"merchant", + "items":[ + "licence",None,None,None,None, + None,None,None,None,None, + None,None,None,None,None, + None,None,None,"scroll3","cscroll3", + ], + "skin":"thief", + #"skin":"test_a", + "type":"fullstatic", + "says":"Careful", + "color":"#E7E2E7", + "name":"Crun", + }, + "fancypots":{ + "role":"merchant", + "items":[ + "hpot0","mpot0","hpot1","mpot1",None, + None,None,None,None,None, + None,None,None,None,None, + None,None,None,None,None, + ], + "skin":"fancypots", + #"skin":"test_a", + "atype":"flow", + "says":"Woo. Hic.", + "color":"#E57636", + "name":"Ernis", + "side_interaction":{"auto":True,"skin":"potiongirl","message":"Hello there. Are you injured or in need of some potions? My family and I pride ourselves with having the best quality potions and elixirs around. Take as much as you need. *hic*"}, + }, + "tbartender":{ + "role":"merchant", + "items":[ + "whiskey","wine","ale",None,None, + "pico","blue",None,None,None, + "espresso",None,None,None,None, + None,None,None,None,"xshot", + ], + "skin":"showoffi", + "type":"fullstatic", + "says":"Hello there", + "color":"#EBECEE", + "name":"Jaqk", + "side_interaction":{"auto":True,"skin":"showoffi","message":"Hello there, partner! Care for a drink? Good luck on the games! Don't lose all your gold at once, heh."}, + }, + "wbartender":{ + "role":"merchant", + "items":[ + "hpot0","mpot0","hpot1","mpot1",None, + "elixirluck",None,None,None,None, + None,None,None,None,None, + None,None,None,None,None, + ], + "skin":"npc63", + "says":"Welcome!", + "color":"#67CCB2", + "type":"fullstatic", + "name":"Warin", + }, + "scrolls":{ + "role":"merchant", + "items":[ + "scroll0","cscroll0","strscroll","intscroll","dexscroll", + "scroll1","cscroll1",None,None,None, + #None,None,None,None,None, + "scroll2","cscroll2",None,None, + ], + "skin":"scrolls", + "says":"Good Luck", + "name":"Lucas", + }, + "secondhands":{ + "role":"secondhands", + "skin":"blingbling", + "type":"fullstatic", + "says":"There's some good stuff in here", + "color":"#7E65D3", + "name":"Ponty", + "side_interaction":{"auto":True,"skin":"blingbling","message":"They sell them. I buy them. You buy them from me for higher prices. Win win. I win. Bling!"}, + }, + "rewards":{ + "role":"rewards", + "skin":"marmor9h", + "cx":{ + "head": "makeup107", + "hair": "hairdo518", + "face": "coolblueg", + "hat": "hat400" + }, + "type":"fullstatic", + "says":"Rewards!", + "color":"#7E65D3", + "name":"Werdars", + }, + "lostandfound":{ + "role":"lostandfound", + "skin":"goblin", + "type":"fullstatic", + "says":"Finders keepers", + "color":"#7E65D3", + "name":"Ron", + }, + "holo":{ + "role":"resort", + "skin":"holo", + "type":"fullstatic", + "says":u"△ ▽ ▲ ▼", + "color":"#EBECEE", + "name":"Z", + }, + "tavern":{ + "role":"tavern", + "skin":"showoffi", + "type":"fullstatic", + "says":"Hi", + "color":"#EBECEE", + "name":"Jaqk", + }, + "pete":{ + "name":"Pete", + "role":"petkeeper", + "skin":"lionsuit", + "type":"fullstatic", + "says":"Purr", + "color":"#EBECEE", + }, + "guard":{ + "name":"Guard", + "role":"guard", + "says":"...", + "skin":"thehelmet", + "type":"fullstatic", + }, + "ship":{ + "role":"ship", + "skin":"ship", + "says":"Ahoy", + "aspeed":"slower", + "atype":"flow", + }, + "newyear_tree":{ + "role":"newyear_tree", + "skin":"newyear_tree", + "says":"*Tin* *Tin* *Tin* *Tin*", + "aspeed":"fast", + "atype":"flow", + "color":"#B7161F", + "name":"New Year Tree", + }, + "lotterylady":{ + "role":"lottery", + "skin":"llady", + "type":"fullstatic", + "says":"Hi Dear", + "color":"#DF5AC5", + "name":"Rose", + }, + "mistletoe":{ + "role":"quest", + "quest":"mistletoe", + "skin":"pink", + "type":"fullstatic", + "says":"Uhhh", + "color":"#E376E5", + "name":"Faith", + }, + "ornaments":{ + "role":"quest", + "quest":"ornament", + "skin":"splithair", + "type":"fullstatic", + "says":"Hmm. Hmm. Hmm.", + "color":"#E56D39", + "name":"Jayson", + }, + "santa":{ + "role":"santa", + "quest":"candycane", + "skin":"santa", + "says":"Ho Ho Ho", + "color":"#DF2A2F", + "name":"Santa", + }, + "witch":{ + "role":"witch", + "quest":"witch", + "skin":"brewingwitch", + "says":"Brew Brew Brew", + "color":"#AF6AE2", + "aspeed":"slow", + "name":"Witch", + }, + "jailer":{ + "role":"jailer", + "skin":"thehelmet", + "type":"fullstatic", + "says":"Tu-tu-tu", + "color":"#62C3DF", + "name":"Jailord", + }, + "leathermerchant":{ + "role":"quest", + "quest":"leather", + "skin":"lmerchant", + "type":"fullstatic", + "says":"Have leathers?", + "color":"#6E4430", + "name":"Landon", + }, + "gemmerchant":{ + "role":"quest", + "quest":"gemfragment", + "skin":"gemmerchant", + "type":"fullstatic", + "says":"Bling", + "color":"#A058DF", + "name":"Mine Heathcliff", + }, + "fisherman":{ + "role":"quest", + "quest":"seashell", + "skin":"fisherman", + "type":"fullstatic", + "says":"Beautiful", + "color":"#429DDF", + "name":"Tristian", + }, + "pwincess":{ + "role":"quest", + "quest":"lostearring", + "skin":"pwincess", + "type":"fullstatic", + "says":"eek", + "color":"#FECDF7", + "name":"Wynifreed", + }, + "firstc":{ + "role":"companion", + "says":["I've heard Goo's drop Amulets.","I'm strictly on a goo-only diet."], + "skin":"lady1", + "type":"fullstatic", + }, + "pvpblocker":{ + "role":"blocker", + "says":"I will leave when there are* 4 people around.", + "skin":"thehelmet", + "type":"fullstatic", + }, + "pvp":{ + "role":"pvp_announcer", + "name":"Ace", + "allow":False, + "speed":40, + "hp":5000, + "skin":"thehelmet", + "type":"fullstatic", + }, + "bean":{ + "role":"events", + "name":"Bean", + "allow":False, + "speed":30, + "hp":3200, + "skin":"lionsuit", + "type":"fullstatic", + "moving":True, + }, + "citizen0":{ + "name":"Kane", #can't change this name, hardcoded to server_loot + "role":"citizen", + "skin":"greencap", + "type":"fullstatic", + "seek":"thrill", + "says":"Hello", + "speed":30, + #"speed":3200, + "hp":3200, + "delay":1200, + #"delay":0, + "level":12, + "says":["Heyoo","Greetings","I want a Puppy!","I want a Kitten!","Sup","Nice day","I wonder why everyone's sitting on my head all of a sudden ..."], + "interaction":["Hey There! This town is the safest place around. Outside can be dangerous.","Heyo, I don't understand how those shop owners can just stand around all day. I got to be moving. Kind of restless.","Just finished school and I've got to go get a real job now. I might become an adventurer since they seem to make a lot of money.","A friend of mine said the frog thingies in the beach drop some old money or sth like that."], + "aura":{ + "luck":200, + }, + }, + "citizen1":{ + "name":"Kilgore", + "role":"citizen", + "skin":"fxrogue", + "type":"fullstatic", + "says":"Grrrr", + "speed":40, + "hp":13200, + "delay":1200, + "steps":12, #defaultis 40, the walking multiplier + "level":120, + "says":["What is your name","Bartender give me your strongest liquor","How are you stranger","I wonder what my wife is doing at home","This inns food isn't as good homemade","Don't buy the food here","Do I smell","Good day","Greetings","Hello Stranger","Welcome","Its warm in here","*rubs beard*","Id like a beer","What beer should I buy","I need to rent a room","This place is pretty nice","Hi there"], + "interaction":["If you don't have a beer in your hand then what are you doing in here!?","Sit down and tell me a tale!","If you can't handle the cold then stay inside.. not saying I can't handle the cold.."], + }, + "citizen2":{ + "name":"Stewart", + "role":"citizen", + "skin":"oldcitizen", + "type":"fullstatic", + "says":["Freaking youngens","Go away - Kill some monsters","Stop","Someone needs to fix this place up","I don't have time for this","I need to go take a nap","Uhhh","Mmmehh","Ugg","Noob","Young yipper snappers"], + "speed":10, + "hp":2400, + "delay":12000, + "level":32, + "interaction":["Ehh. Back in my day we didn't have all these fancy additions in town, we had the essentials and that's it."], + }, + "citizen3":{ + "name":"Reny", + "role":"citizen", + "skin":"renaldo", + "type":"fullstatic", + "says":["Do you even lift bro","Broooo","Yah I work out","Sup","I need to buy some protein","Lap 203","Grind 24/7 all day everyday","You like my headband","Where are my shoes at","Where is the gym at","Nice day to work out","Wanna work out","Red headband for the win","Winners are not losers and I'm a winner","No I never give up"], + "speed":55, + "hp":3200, + "delay":3600, + "level":32, + "interaction":["I Grind 24 hours a day! 7 days a week! Never Stop! Never Give up! Always Training!!","My body fat ratio is just 18%. Can you believe it? Yes!","Do you even lift Bro.","Hi, I do laps around this town all the time. Gotta stay in shape."], + }, + "citizen4":{ + "name":"Angel", + "role":"citizen", + "skin":"angel", + "type":"fullstatic", + "seek":"gold", + "says":["Ohh look who walked into my life","Single and ready to mingle","No um I don't own a shop","Such a nice town","*fixes dress*","*gets flustered*","Would you like a potion sorry","Ohh look who walked into my life","Single and ready to mingle","No um I don't own a shop","Such a nice town","*fixes dress*","*gets flustered*","Would you like a potion sorry","No potion for you","Stop cat calling","*rolls eyes*Hey sweetie","Nice day","Sweet thing are you lost","Oh hi there cutie","Lovely weather today","Do you like my dress","Welcome to the town"], + "speed":20, + "hp":24000, + "delay":6000, + "level":80, + "interaction":["I used to sell potions around here, but I decided to retire.","Always nice to see smiling new faces.","Are you new here? Welcome.","This town has grown a lot, I was around when it was just one small block of land."], + "aura":{ + "gold":200, + }, + "modal":"npc-angel", + }, + "citizen5":{ + "name":"Grundur", + "role":"citizen", + "skin":"generalg", + "type":"fullstatic", + "says":["I remember the battle of the beards","Hello","Greetings","Good day","Pretty cold outside ay","Do you like my outfit","Hi there","Tomorrow is a new day","Ive seen some real shit","Back in my day ...","Stompy better die","*yawns*","So much snow around here","*drinks beer*",], + "speed":30, + "hp":18600, + "delay":1200, + "steps":12, + "level":90, + "interaction":["It is pretty cold outside. I should invest in a hat.","I came here to pursue a beast called \"Stompy\". I've heard this creature lives in the Ice Mountains nearby.","I came here for adventure, but now I'm stuck in this bar due to the cold."], + }, + "citizen6":{ + "name":"Fredric", + "role":"citizen", + "skin":"mailman", + "type":"fullstatic", + "says":["*searches through mail bag*","*hums to self*","*whisles*","Are you new here","Ohh you're an adventurer","Good day adventurer","I like love letters they are sweet","Um I don't read your letters","Hey stranger"], + "speed":30, + "hp":18600, + "delay":1200, + "steps":12, + "level":90, + "interaction":["Hi, I'm a mail man! But no one sends mail out here much. So I guess it's a pretty easy job.","Careful it's cold outside. But it's nice and warm in here."], + }, + "citizen7":{ + "name":"Lucy", + "role":"citizen", + "skin":"lucy", + "type":"fullstatic", + "says":["Do you like my scarf","My mom made my scarf","Do you know who santa is","I wonder where santa lives","I'm used to the cold here","Hi","Im going to move to a warmer place one day","This scarf makes me warm","Don't hit on me","I have a boyfriend","The leather guy is my boyfriend","I think Stompy is just misunderstood"], + "speed":30, + "hp":3200, + "delay":1200, + "level":48, + "interaction":["Hi! Would you like to know a secret? I love the snow.","Make sure you keep moving, don't want to catch a cold out here.","I have heard that Santa sometimes visits here during Xmas!"], + }, + "citizen8":{ + "name":"Wyr", + "role":"citizen", + "skin":"frozenrogue", + "type":"fullstatic", + "says":["How are you","*wipes snow off himself*","It's cold here","*shivers*","This is a pretty small village","I've meet a real elf","Don't go swimming here it's cold"], + "speed":38, + "hp":16000, + "delay":1200, + "level":78, + "interaction":["Are you here to kill Stompy too? Well I guess let the best adventurer get to him first!","My hair was actually black, before it happened."], + }, + "citizen9":{ + "name":"Lilith", + "role":"citizen", + "skin":"lilith", + "type":"fullstatic", + "says":["Oh you like my hair","Are you here to serve","I'm sure I can fight off stompy","Stompy doesn't scare me","Wizard is my boss","Good day","Oh it's snowing","Snow is nice","Don't bother the guards building","Don't flirt with me","I protect and serve","I'm a commander","Greetings stranger","Hello stranger","Hi stranger","I serve the mighty Wizard","I was instructed to keep this village safe","The cold doesn't bother me"], + "speed":32, + "hp":12000, + "delay":1200, + "level":92, + "interaction":["Greetings Adventurer, are you here to kill some monsters? Great! Always looking for help keeping this land safe.","Believe it or not. I am the highest ranking officer in these parts. I work hard to keep this town operating and safe."], + }, + "citizen10":{ + "name":"Caroline", + "role":"citizen", + "skin":"pink", + "type":"fullstatic", + "says":["Hi","My coat keeps me super warm","Stompy used to be my favorite boar","I wish stompy would come home","That inn over there is always a great place","I want to be everyone's friend","Do you need a hug","Hugs keep you warm","*gives you a hug*","Free hugs","This village is mostly boar farmers","Hey","Hello","*wiggles in pink coat*","Pink is my favorite color","I'd love to work for Santa"], + "speed":28, + "hp":12000, + "delay":1200, + "level":92, + "heal":2400, + "seek":"cuteness", + "class":"priest", + "interaction":["Hey Hey guess what! I like the color Pink! I bet you couldn't guess that.","If Santa ever comes back, I hope I could be his little helper.","Make sure you wear warm clothes, it's a little chilly out here."], + }, + "citizen11":{ + "name":"Baron", + "role":"citizen", + "skin":"baron", + "class":"priest", + "seek":"low_hp", + "type":"fullstatic", + "says":["Stranger","Where is mother","Cursed land","Stay clear","Go away","Back away","*stares blankly*","*stares coldly*","...",".....","........","Halt","Must protect","Never forget","Defend","Protect","For honor"], + "speed":28, + "attack":1800, + "range":320, + "hp":120000, + "delay":12000, + "level":120, + "interaction":["Guard. Village. Protect. Innocents.","Brothers. Rest. Here. Protect. Over. Their. Graves.","Remember. The. Fallen. Never. Forget. Their. Sacrifices.","Heal. The. Fallen."], + }, + "citizen12":{ + "name":"Marven", + "role":"citizen", + "skin":"marven", + "type":"fullstatic", + "says":["I'd hate to find you dead *wink*","Bloody hell","What are you doing here","Who the hell would like living here","Where is my shovel","Stay out of the graveyard","Go home kid","Seen any good junk around","Whatca looking for","Go away","This isn't the place for you","Ever heard of minding your own business","Ever seen a dead man","Hhehehe","Finders keepers"], + "speed":32, + "hp":1200, + "delay":3200, + "level":42, + "interaction":["I watch over the graves. Sometimes people leave 'gifts' on a grave. Ehhh, sometimes I clean the graves of these items."], + }, + "citizen13":{ + "name":"Divian", + "role":"citizen", + "skin":"grogue", + "type":"fullstatic", + "says":["I see dead people","Ghosts speak to me","Are zombies real","R.I.P. Such nice letters","*evil glare*","I serve Death","Death is my leader","All Hail Death","Danger awaits you","Dracul please take me as your bride","Death isn't the end","Do you know of any cults","Wizard could go to hell I serve Death","It never rains here, I'm only happy when it rains","My eyes are blood red","My favorite color is red","I'd like to meet my demons"], + "speed":32, + "hp":1200, + "delay":3200, + "level":42, + "interaction":["I am a firm believer that the dark arts would solve a lot of problems if it was acceptable to practice them.","Did you know that Ms. Dracul used to be a member of this village... before she transcended the limitations of mankind. I wish I had the courage to do the rituals required.","Dracul is a very well-known name around these parts. I wish I could be like them..","I heard there is a way to get +13 items, anything can turn into one, but you can't even see it ..."], + }, + "citizen14":{ + "name":"Violet", + "role":"citizen", + "skin":"spkw", + "type":"fullstatic", + "speed":28, + "hp":4000, + "delay":4000, + "level":70, + "says":["Hello there","Where's that boy?","SON!!!","Play time is over!","Welcome","Same old same old","Ohh a visitor","Well hi there","It's getting late","Home sweet home","Are you hungry?"], + "interaction":["Have you seen my son? He should be around here somewhere.","It's not a very nice neighborhood around here, But the rent is cheap!","I heard somewhere that's there's some sort of pumpkin person walking around? That just sounds silly to me"], + }, + "citizen15":{ + "name":"Timmy", + "role":"citizen", + "skin":"spkc", + "type":"fullstatic", + "speed":16, + "hp":200, + "delay":200, + "level":4, + "says":["I think I saw a pumpkin move!!","I like pumpkins","Size doesn't matter!","You found me","Boo!!","Weee","Hello","*Mumble Mumble*"], + "interaction":["Be careful around here? It's really dangerous up to the north.","I like to play with the pumpkins, but sometimes they don't want to play and just walk away..","My imaginary friend is real! And a pumpkin!!"], + }, + "citizen16":{ + "name":"Cunn", + "role":"citizen", + "skin":"cunn", + "class":"ranger", + "seek":"dragondagger", + "transport":True, + "type":"fullstatic", + "slots":{ + "mainhand":{"name":"crossbow","level":7}, + }, + "says":["Yo"], + "speed":36, + "attack":1200, + "range":320, + "hp":12000, + "delay":1000, + "level":72, + "interaction":["What? What? WHAT?!","I don't really have much tolerance for anyone.","I follow only the most badass!"], + }, + "holo0":{ + "name":"Green", + "role":"citizen", + "skin":"greengreen", + "type":"fullstatic", + "speed":24, + "hp":6000, + "delay":5000, + "level":0, + "says":["rbin"], + "interaction":["rbin"], + }, + "holo1":{ + "name":"Pink", + "role":"citizen", + "skin":"pinkie", + "type":"fullstatic", + "speed":24, + "hp":6000, + "delay":5000, + "level":0, + "says":["rbin"], + "interaction":["rbin"], + }, + "holo2":{ + "name":"Purple", + "role":"citizen", + "skin":"purpo", + "type":"fullstatic", + "speed":30, + "hp":6000, + "delay":7000, + "level":0, + "says":["rbin"], + "interaction":["rbin"], + }, + "holo3":{ + "name":"Scarf", + "role":"citizen", + "skin":"scarf", + "type":"fullstatic", + "speed":24, + "hp":6000, + "delay":3000, + "level":0, + "says":["rbin"], + "interaction":["rbin"], + }, + "holo4":{ + "name":"Twig", + "role":"citizen", + "skin":"twig", + "type":"fullstatic", + "speed":48, + "hp":6000, + "delay":24000, + "level":0, + "says":["rbin"], + "interaction":["rbin"], + }, + "holo5":{ + "name":"Bobo", + "role":"citizen", + "skin":"bobo", + "type":"fullstatic", + "speed":16, + "hp":6000, + "delay":8000, + "level":0, + "says":["rbin"], + "interaction":["rbin"], + }, + "princess":{ + "name":"Princess", + "role":"citizen", + "skin":"princess", + "type":"fullstatic", + "speed":24, + "hp":6000, + "delay":5000, + "level":72, + "says":["Oh, Hello!"], + "interaction":["Wanna taste my daggers?"], + }, + "bouncer":{ + "name":"Wogue", + "role":"bouncer", + "skin":"bouncer", + "type":"fullstatic", + "level":88, + "says":["What?","BOUNCE"], + "interaction":["Wanna taste my daggers? One move out of line. And you will!","Come on! One sexist word out of your mouth. Just one. Let's see what your tombstone looks like."], + }, + "goldnpc":{ + "name":"Mr. Rich", + "role":"gold", + "skin":"goblin_a", + "says":"GOLD!", + "color":"#E0B427", + "aspeed":"slow", + }, + "wizardrepeater":{ + "name":"Wizard", + "role":"repeater", + "skin":"wizard", + "color":"#66BB52", + "says":"SHELLS!", + "type":"fullstatic", + "interval":3000, + }, + "wnpc":{ + "name":"Wizard", + "role":"thesearch", + "quest":"glitch", + "skin":"wizard", + #"color":"#23B0AB", + #"says":"Hmm", + "color":"#D96643", + "says":"Help", + "type":"fullstatic", + }, + "craftsman":{ + "name":"Joe", + "role":"craftsman", + "skin":"npcc", + "color":"#9EACAE", + "says":"Give it to me", + "type":"fullstatic", + "name":"Leo", + }, + "items0":{ + "name":"Gabrielle", + "role":"items", + "pack":"items0", + "skin":"gabrielle", + #"skin":"goblin_a", + "color":"#E0D8A5", + "type":"fullstatic", + }, + "items1":{ + "name":"Gabriella", + "role":"items", + "pack":"items1", + "skin":"gabrielle", + #"skin":"goblin_a", + "color":"#E0D8A5", + "type":"fullstatic", + }, + "items2":{ + "name":"Ledia", + "role":"items", + "pack":"items2", + "skin":"lady3", + #"skin":"goblin_a", + "color":"#E0D8A5", + "type":"fullstatic", + }, + "items3":{ + "name":"Lidia", + "role":"items", + "pack":"items3", + "skin":"lady3", + #"skin":"goblin_a", + "color":"#E0D8A5", + "type":"fullstatic", + }, + "items4":{ + "name":"Christie", + "role":"items", + "pack":"items4", + "skin":"lady4", + #"skin":"goblin_a", + "color":"#E0D8A5", + "type":"fullstatic", + }, + "items5":{ + "name":"Christina", + "role":"items", + "pack":"items5", + "skin":"lady4", + #"skin":"goblin_a", + "color":"#E0D8A5", + "type":"fullstatic", + }, + "items6":{ + "name":"Jane", + "role":"items", + "pack":"items6", + "skin":"lady2", + #"skin":"goblin_a", + "color":"#E0D8A5", + "type":"fullstatic", + }, + "items7":{ + "name":"Janet", + "role":"items", + "pack":"items7", + "skin":"lady2", + #"skin":"goblin_a", + "color":"#E0D8A5", + "type":"fullstatic", + }, + "basics":{ + "role":"merchant", + "items":[ + "helmet","shoes","gloves","pants","coat", + "blade","claw","staff","bow","wshield", + "wand","mace","wbasher", + ], + "skin":"daggers", + "says":"Blades, blades, blades", + "atype":"flow", + "name":"Gabriel", + }, + "premium":{ + "old_role":"premium", + "role":"merchant", + "items":[ + "xpbooster","goldbooster","luckbooster",None,None, + "xptome","offering",None,None,None, + "qubics",None,None,None,None, + None,None,None,None,None + + ], + "skin":"pflow", + "says":"MMM", + "atype":"flow", + "name":"Garwyn", + }, + "antip2w":{ + "old_role":"merchant", + "role":"premium", + "old_items":[ + "xpbooster","goldbooster","luckbooster",None,None, + "xptome","offering",None,None,None, + "qubics",None,None,None, + + ], + #"items":["cosmo0","cosmo1","cosmo2",None,None,"cosmo3","cosmo4"], + "items":["cosmo0","cosmo2","cosmo3"], + "skin":"fancyd", + "says":"Sup", + "type":"fullstatic", + "name":"Mr. Dworf", + "old_side_interaction":{"auto":True,"skin":"fancyd","message":"I'm the Anti-P2W Authority around here. Making sure all critical items can be bought with gold. Prices can fluctuate based on inflation."}, + "side_interaction":{"auto":True,"skin":"fancyd","message":"Hey there, good looking fellow. Would you be interested in looking better?"}, + }, + "armors":{ + "role":"merchant", + "items":[ + #"helmet","shoes","gloves","pants","coat", + ], + "skin":"armorguy", + "says":"YESS", + "atype":"flow", + }, + "weapons":{ + "role":"merchant", + "items":[ + "blade","claw","staff","bow", + ], + "skin":"daggers", + "says":"Blades, blades, blades", + "atype":"flow", + "ignore":True, + }, + "exchange":{ + "role":"exchange", + "skin":"magic", + "says":"Good Luck!", + "name":"Xyn", + }, + "shrine":{ + "role":"shrine", + "skin":"shrine", + "type":"static", + }, + "compound":{ + "role":"compound", + "skin":"shrine2", + "type":"static", + }, + "newupgrade":{ + "role":"newupgrade", + "skin":"newupgrade", + "says":"+1", + "atype":"flow", + "name":"Cue", + }, + "locksmith":{ + "role":"locksmith", + "skin":"asoldier", + "says":"X", + "type":"fullstatic", + "name":"Smith", + }, + "transporter":{ + "role":"transport", + "skin":"spell", + "says":"Woo", + "color":"#7965C6", + "places":{ + "winterland":1, + "main":9, + #"halloween":1, + "desertland":1, + "cyberland":0, + "test":0, + "d_e":0, + }, + "name":"Alia", + }, + "appearance":{ + "role":"cx", + "quest":"cx", + "skin":"zengirl", + "says":"Now!", + "name":"Haila", + "color":"#D95CB4", + "aspeed":"slow", + }, + "lichteaser":{ + "role":"tease", + "skin":"lichteaser", + "type":"static", + "says":"Soon", + "color":"#5A1D7F", + }, +} +for i in range(8,48): + npcs["items%d"%i]={ + "name":"X%d"%i, + "role":"items", + "pack":"items%d"%i, + "skin":"mabw", + "cx":{"head":"bwhead"}, + "color":"#E0D8A5", + "type":"fullstatic", + } +for npc in npcs: + npcs[npc]["id"]=npc diff --git a/design/precomputed.py b/design/precomputed.py new file mode 100644 index 0000000..d5e64ba --- /dev/null +++ b/design/precomputed.py @@ -0,0 +1,2 @@ +# Fri Oct 13 2023 21:25:15 GMT+0300 (GMT+03:00) +images={"/images/tiles/characters/ninja_turtles.png":{"height":144,"width":312,"type":"png"},"/images/cosmetics/makeup/makeup1.png":{"height":120,"width":1134,"type":"png"},"/images/cosmetics/hairdo/bwhair.png":{"height":120,"width":27,"type":"png"},"/images/cosmetics/beardo/burningeyes1_anim.png":{"height":120,"width":81,"type":"png"},"/images/cosmetics/beardo/burningeyes2_anim.png":{"height":120,"width":81,"type":"png"},"/images/cosmetics/hats/bathat_anim.png":{"height":120,"width":81,"type":"png"},"/images/cosmetics/hats/gcandle_anim.png":{"height":120,"width":81,"type":"png"},"/images/cosmetics/hats/halo_anim.png":{"height":120,"width":81,"type":"png"},"/images/cosmetics/makeup/kunique.png":{"height":120,"width":108,"type":"png"},"/images/cosmetics/skins/mbw.png":{"height":144,"width":81,"type":"png"},"/images/cosmetics/armors/mabw.png":{"height":144,"width":162,"type":"png"},"/images/cosmetics/accessories/kglasses.png":{"height":120,"width":108,"type":"png"},"/images/cosmetics/gravestones/gravestone.png":{"height":64,"width":160,"type":"png"},"/images/tiles/monsters/deep_sea_king.png":{"height":320,"width":318,"type":"png"},"/images/tiles/characters/adversaries.png":{"height":288,"width":324,"type":"png"},"/images/tiles/characters/angel_wingless.png":{"height":288,"width":456,"type":"png"},"/images/tiles/characters/winners_jpa.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/winners_jpb.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/sheet_winnersa.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/sheet_winnersb.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/collection1.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/collection2.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/collection3.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/collectionx.png":{"height":288,"width":456,"type":"png"},"/images/tiles/monsters/snowman.png":{"height":144,"width":76,"type":"png"},"/images/tiles/monsters/Dragold.png":{"height":212,"width":156,"type":"png"},"/images/tiles/monsters/blackscorpion.png":{"height":256,"width":176,"type":"png"},"/images/tiles/monsters/coboldProto.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/liger_x.png":{"height":184,"width":150,"type":"png"},"/images/tiles/monsters/tiger.png":{"height":184,"width":150,"type":"png"},"/images/tiles/monsters/slenderman.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/frankenstein.png":{"height":144,"width":76,"type":"png"},"/images/tiles/characters/custom1.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/custom2.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/custom3.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/others/jsonX.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/mecha_gnome.png":{"height":144,"width":78,"type":"png"},"/images/tiles/monsters/harpy_b_1.png":{"height":212,"width":156,"type":"png"},"/images/tiles/monsters/harpy_b_fly_1.png":{"height":212,"width":156,"type":"png"},"/images/tiles/monsters/harpy_a_1.png":{"height":212,"width":156,"type":"png"},"/images/tiles/monsters/harpy_a_fly_1.png":{"height":212,"width":156,"type":"png"},"/images/tiles/characters/others/ship2.png":{"height":64,"width":201,"type":"png"},"/images/tiles/characters/others/newyear_tree.png":{"height":64,"width":144,"type":"png"},"/images/tiles/characters/bonus1.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/military2.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/military3.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/knights.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/chara2.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/chara3.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/chara4.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/chara6.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/chara7.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/chara8.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/automatron2.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/npc1.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/npc3.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/npc4.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/npc5.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/npc6.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/dwarf2.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/tristone_m.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/tristone_f.png":{"height":288,"width":312,"type":"png"},"/images/tiles/characters/mystics.png":{"height":144,"width":312,"type":"png"},"/images/tiles/monsters/creatures1.png":{"height":144,"width":312,"type":"png"},"/images/tiles/monsters/creatures2.png":{"height":424,"width":624,"type":"png"},"/images/tiles/monsters/jrpumpkins.png":{"height":144,"width":155,"type":"png"},"/images/tiles/characters/chara5.png":{"height":288,"width":312,"type":"png"},"/images/tiles/items/chests.png":{"height":288,"width":504,"type":"png"},"/images/tiles/characters/animationc.png":{"height":400,"width":564,"type":"png"},"/images/tiles/characters/animation1i.png":{"height":400,"width":564,"type":"png"},"/images/tiles/characters/animation2.png":{"height":400,"width":564,"type":"png"},"/images/tiles/characters/animation3.png":{"height":400,"width":564,"type":"png"},"/images/tiles/monsters/elemental.png":{"height":512,"width":720,"type":"png"},"/images/tiles/monsters/monster_dknight1.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/monster_dknight2.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/fairies.png":{"height":288,"width":312,"type":"png"},"/images/tiles/monsters/monster_bird1.png":{"height":228,"width":183,"type":"png"},"/images/tiles/monsters/monster_bird2.png":{"height":228,"width":183,"type":"png"},"/images/tiles/monsters/monster_bird3.png":{"height":228,"width":183,"type":"png"},"/images/tiles/monsters/monster_boar.png":{"height":264,"width":195,"type":"png"},"/images/tiles/monsters/monster_cacto.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/rudolphi.png":{"height":264,"width":195,"type":"png"},"/images/tiles/monsters/monster_elk.png":{"height":264,"width":195,"type":"png"},"/images/tiles/monsters/monster_golem1.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/monster_golem2.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/monster_lich.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/monster_lizardman1.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/monster_lizardman2.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/stompy3.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/monster_minotaur.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/monster_phoenix.png":{"height":228,"width":183,"type":"png"},"/images/tiles/monsters/monster_raptor1.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/monster_raptor2.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/grinch.png":{"height":144,"width":82,"type":"png"},"/images/tiles/monsters/monster_treant.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/monster_wolf1.png":{"height":264,"width":195,"type":"png"},"/images/tiles/monsters/monster_wolf2.png":{"height":264,"width":195,"type":"png"},"/images/tiles/monsters/json.png":{"height":228,"width":183,"type":"png"},"/images/tiles/monsters/custom1.png":{"height":512,"width":720,"type":"png"},"/images/tiles/monsters/custom2.png":{"height":512,"width":720,"type":"png"},"/images/tiles/monsters/goos.png":{"height":256,"width":360,"type":"png"},"/images/tiles/monsters/monster1.png":{"height":512,"width":720,"type":"png"},"/images/tiles/monsters/animals1.png":{"height":288,"width":312,"type":"png"},"/images/tiles/monsters/animals2.png":{"height":288,"width":504,"type":"png"},"/images/tiles/monsters/birds1_modded.png":{"height":288,"width":504,"type":"png"},"/images/tiles/monsters/goblinos.png":{"height":288,"width":312,"type":"png"},"/images/tiles/monsters/goblinkingb.png":{"height":212,"width":156,"type":"png"},"/images/tiles/monsters/monsterc6.png":{"height":512,"width":692,"type":"png"},"/images/tiles/monsters/tinyfairies.png":{"height":288,"width":312,"type":"png"},"/images/tiles/monsters/monsterc2.png":{"height":400,"width":564,"type":"png"},"/images/tiles/monsters/robots.png":{"height":288,"width":372,"type":"png"},"/images/tiles/monsters/mage.png":{"height":288,"width":312,"type":"png"},"/images/tiles/monsters/monster2.png":{"height":512,"width":720,"type":"png"},"/images/tiles/monsters/monster3c.png":{"height":512,"width":720,"type":"png"},"/images/tiles/monsters/monster4.png":{"height":512,"width":720,"type":"png"},"/images/tiles/monsters/vampire2d.png":{"height":288,"width":312,"type":"png"},"/images/tiles/monsters/mr_pumpkin.png":{"height":144,"width":80,"type":"png"},"/images/tiles/monsters/cbee.png":{"height":144,"width":78,"type":"png"},"/images/tiles/monsters/iceGolem.png":{"height":200,"width":141,"type":"png"},"/images/tiles/monsters/green.png":{"height":144,"width":80,"type":"png"},"/images/sprites/emblems/emblems.png":{"height":96,"width":480,"type":"png"},"/images/cosmetics/skins/sskin1.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/skins/mskin1.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/skins/lskin1.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/sbody1.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/mbody1.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/mbody2.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/mbody3.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/mbody4.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/mbody5.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/mbody6.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/sarmor1.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/sarmor2.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/marmor1.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/marmor2.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/marmor3.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/marmor4.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/marmor5.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/marmor6.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/marmor7.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/marmor8.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/marmor9.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/marmor10.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/marmor11.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/marmor12.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/armors/larmor1.png":{"height":288,"width":324,"type":"png"},"/images/all_characters/lchar1.png":{"height":288,"width":324,"type":"png"},"/images/all_characters/mchar16.png":{"height":288,"width":324,"type":"png"},"/images/all_characters/schar7.png":{"height":288,"width":324,"type":"png"},"/images/all_characters/xschar2.png":{"height":288,"width":324,"type":"png"},"/images/all_characters/xxschar2.png":{"height":288,"width":324,"type":"png"},"/images/cosmetics/hairdo/hairdo1.png":{"height":120,"width":675,"type":"png"},"/images/cosmetics/hairdo/hairdo2.png":{"height":120,"width":675,"type":"png"},"/images/cosmetics/hairdo/hairdo3.png":{"height":120,"width":675,"type":"png"},"/images/cosmetics/hairdo/hairdo4.png":{"height":120,"width":675,"type":"png"},"/images/cosmetics/hairdo/hairdo5.png":{"height":120,"width":675,"type":"png"},"/images/cosmetics/hairdo/hairdo6.png":{"height":120,"width":675,"type":"png"},"/images/cosmetics/hats/hats1.png":{"height":120,"width":675,"type":"png"},"/images/cosmetics/hats/hats2.png":{"height":120,"width":675,"type":"png"},"/images/cosmetics/hats/hats3.png":{"height":120,"width":675,"type":"png"},"/images/cosmetics/hats/hats4.png":{"height":120,"width":675,"type":"png"},"/images/cosmetics/wings/wings1.png":{"height":144,"width":185,"type":"png"},"/images/cosmetics/wings/wings2.png":{"height":144,"width":128,"type":"png"},"/images/cosmetics/wings/wings3.png":{"height":144,"width":185,"type":"png"},"/images/cosmetics/wings/backpacks.png":{"height":144,"width":185,"type":"png"},"/images/cosmetics/wings/backpack2.png":{"height":144,"width":185,"type":"png"},"/images/cosmetics/tails/wolftail.png":{"height":144,"width":108,"type":"png"},"/images/cosmetics/tails/wolftail2.png":{"height":144,"width":108,"type":"png"},"/images/cosmetics/tails/wolftail3.png":{"height":144,"width":108,"type":"png"},"/images/cosmetics/makeup/smakeup.png":{"height":120,"width":27,"type":"png"},"/images/cosmetics/makeup/malemakeup.png":{"height":120,"width":378,"type":"png"},"/images/cosmetics/makeup/femalemakeupv2.png":{"height":120,"width":351,"type":"png"},"/images/cosmetics/makeup/fmakeup.png":{"height":120,"width":351,"type":"png"},"/images/cosmetics/accessories/eyeglasses.png":{"height":120,"width":1107,"type":"png"},"/images/cosmetics/beardo/beard1.png":{"height":120,"width":1107,"type":"png"},"/images/cosmetics/beardo/mask1.png":{"height":120,"width":675,"type":"png"},"/images/cosmetics/beardo/facemakeup.png":{"height":120,"width":675,"type":"png"},"/images/cosmetics/makeup/male_makeup.png":{"height":120,"width":567,"type":"png"},"/images/cosmetics/makeup/female_makeup.png":{"height":120,"width":621,"type":"png"},"/images/cosmetics/makeup/unisex_makeup.png":{"height":120,"width":648,"type":"png"},"/images/tiles/items/pack_1a.png":{"height":2048,"width":256,"type":"png"},"/images/tiles/items/pack_20vt8.png":{"height":1280,"width":320,"type":"png"},"/images/tiles/items/skills_20v6.png":{"height":260,"width":320,"type":"png"},"/images/tiles/items/custom.png":{"height":180,"width":140,"type":"png"},"/images/tiles/map/castle.png":{"height":512,"width":544,"type":"png"},"/images/tiles/map/custom2.png":{"height":560,"width":752,"type":"png"},"/images/tiles/map/custom.png":{"height":480,"width":480,"type":"png"},"/images/tiles/map/custom_a.png":{"height":320,"width":320,"type":"png"},"/images/tiles/map/doors.png":{"height":256,"width":192,"type":"png"},"/images/tiles/map/dungeon.png":{"height":416,"width":912,"type":"png"},"/images/tiles/map/house.png":{"height":1168,"width":1104,"type":"png"},"/images/tiles/map/inside.png":{"height":816,"width":832,"type":"png"},"/images/tiles/map/outside.png":{"height":832,"width":904,"type":"png"},"/images/tiles/map/puzzle.png":{"height":320,"width":336,"type":"png"},"/images/tiles/map/water_updated.png":{"height":1200,"width":704,"type":"png"},"/images/tiles/map/winter.png":{"height":640,"width":912,"type":"png"},"/images/tiles/map/fort.png":{"height":832,"width":656,"type":"png"},"/images/tiles/map/beach_v2.png":{"height":416,"width":576,"type":"png"},"/images/tiles/map/world.png":{"height":288,"width":432,"type":"png"},"/images/tiles/items/stands.png":{"height":144,"width":78,"type":"png"},"/images/tiles/map/new.png":{"height":480,"width":672,"type":"png"},"/images/tiles/map/dark_dimension.png":{"height":336,"width":464,"type":"png"},"/images/tiles/map/jungle.png":{"height":336,"width":496,"type":"png"},"/images/tiles/map/ship.png":{"height":448,"width":864,"type":"png"},"/images/tiles/map/ashlands.png":{"height":336,"width":640,"type":"png"},"/images/tiles/map/ruins.png":{"height":832,"width":704,"type":"png"},"/images/tiles/map/tree.png":{"height":576,"width":544,"type":"png"},"/images/tiles/map/lights.png":{"height":480,"width":640,"type":"png"}} diff --git a/design/projectiles.py b/design/projectiles.py new file mode 100644 index 0000000..7f2ff54 --- /dev/null +++ b/design/projectiles.py @@ -0,0 +1,187 @@ +projectiles={ + "momentum":{ + "animation":"slash", + "speed":320, + "hit_animation":"slash1", + }, + "quickpunch":{ + "animation":"slash", + "speed":420, + "hit_animation":"slash2", + "hit_text":["PUNCH!","#41338B"], + }, + "quickstab":{ + "animation":"slash", + "speed":420, + "hit_animation":"slash2", + "hit_text":["STAB!","#41338B"], + }, + "smash":{ + "animation":"slash", + "speed":420, + "hit_animation":"slash2", + "hit_text":["SMASH!","#CBB892"], + }, + "wmomentum":{ + "animation":"wslash", + "speed":520, + "hit_animation":"slash3", + }, + "arrow":{ + "animation":"carrow", + "speed":500, + "hit_animation":"arrow_hit", + }, + "crossbowarrow":{ + "animation":"carrow", + "speed":700, + "hit_animation":"arrow_hit", + }, + "garrow":{ + "animation":"garrow", + "speed":640, + "hit_animation":"arrow_hit", + }, + "poisonarrow":{ + "animation":"arrow1", + "speed":400, + "hit_animation":"arrow_hit", + "hit_text":["POISONED!","poison"], + }, + "pouch":{ + "animation":"poucharrow", + "speed":300, + "hit_animation":"explode_b", + }, + "firearrow":{ + "animation":"firearrow", + "speed":460, + "hit_animation":"arrow_hit", + }, + "frostarrow":{ + "animation":"frostarrow", + "speed":580, + "hit_animation":"icecrack", + }, + "acid":{ + "animation":"acid", + "speed":280, + }, + "supershot":{ + "animation":"superarrow", + "speed":600, + "hit_animation":"supershot", + "hit_text":["SUPERSHOT!","#9B172E"], + }, + "magic":{ + "animation":"magic1", + "speed":400, + "hit_animation":"explode_c", + }, + "bigmagic":{ + "animation":"magic0", + "speed":320, + "hit_animation":"explode_c", + }, + "wandy":{ + "animation":"wandy", + "speed":560, + "hit_animation":"explode_c", + }, + "pinky":{ + "animation":"pinky", + "speed":460, + "hit_animation":"explode_c", + }, + "magic_purple":{ + "animation":"magic3", + "speed":400, + "hit_animation":"explode_c", + }, + "magic_divine":{ + "animation":"magic4", + "speed":480, + "hit_animation":"explode_c", + }, + "mmagic":{ + "animation":"mblob_purplish", + "speed":400, + "hit_animation":"explode_p", + }, + "pmagic":{ + "animation":"magic2", + "speed":360, + "hit_animation":"explode_p", + }, + "stone":{ + "animation":"pblob", + "speed":320, + "hit_animation":"slash1", + }, + "stone_k":{ + "animation":"pblob", + "speed":320, + "hit_animation":"explode_b", + }, + "fireball":{ + "animation":"fireball", + "speed":320, + "hit_animation":"explode_c", + }, + "frostball":{ + "animation":"frostball", + "speed":420, + "hit_animation":"explode_c", + }, + "snowball":{ + "speed":180, + "animation":"snowball", + "hit_animation":"snowball_hit", + "pure":True, + }, + "plight":{ + "animation":"heal_projectile", + "speed":120, + "hit_animation":"heal", + }, + "curse":{ + "animation":"curse_projectile", + "speed":240, + "hit_animation":"curse_new", + }, + "cupid":{ + "animation":"cuarrow", + "speed":320, + "hit_animation":"heal", + }, + "mentalburst":{ + "instant":True, + "ray":"tiling_burstj", + "kill_text":["POW!","#4C9AE0"], + "hit_animation":"burst", + }, + "purify":{ + "instant":True, + "hit_text":["PURIFIED!","#DDCC7B"], + "hit_animation":"flare_yellow", + }, + "burst":{ + "instant":True, + "ray":"tiling_burstj", + "hit_animation":"burst", + }, + "sburst":{ #small burst + "instant":True, + "ray":"tiling_burst", + "hit_animation":"burst", + }, + "gburst":{ + "instant":True, + "ray":"tiling_burst_g", + "hit_animation":"gburst", + }, + "partyheal":{ + "instant":True, + "hit_animation":"party_heal", + } +} \ No newline at end of file diff --git a/design/prototypes/.DS_Store b/design/prototypes/.DS_Store new file mode 100644 index 0000000..a2c6333 Binary files /dev/null and b/design/prototypes/.DS_Store differ diff --git a/design/prototypes/global_luck.txt b/design/prototypes/global_luck.txt new file mode 100644 index 0000000..d2a15b6 --- /dev/null +++ b/design/prototypes/global_luck.txt @@ -0,0 +1,22 @@ +Players Buff +100 +10% +150 +15% +200 +20% +250 +25% +300 +30% +400 +35% +500 +40% +600 +50% +800 +60% +1000 +70% +1250 +75% +1500 +80% +2000 +85% +2500 +90% +3000 +95% +4000 +100% +5000 +120% +6000 +130% +8000 +140% +10000 +150% +20000 +200% \ No newline at end of file diff --git a/design/prototypes/hardcore_rewards.txt b/design/prototypes/hardcore_rewards.txt new file mode 100644 index 0000000..38e7d66 --- /dev/null +++ b/design/prototypes/hardcore_rewards.txt @@ -0,0 +1,52 @@ +Top 5 by Level +1- +2- +3- +4- +5- + +Most Unique Kills +- + +Top Warrior +- + +Top Mage +- + +Top Rogue +- + +Top Ranger +- + +Top Paladin +- + +Top Priest +- + +First Warrior to Level 70 +- ++ ... + +First +9 +- + +First +10 +- + +First +11 +- + +First +12 +- + +First +13 +- + +First +5 Accessory +- + +Most Gold +- \ No newline at end of file diff --git a/design/prototypes/test.rtf b/design/prototypes/test.rtf new file mode 100644 index 0000000..ef4b1fd --- /dev/null +++ b/design/prototypes/test.rtf @@ -0,0 +1,10 @@ +{\rtf1\ansi\ansicpg1252\cocoartf2513 +\cocoatextscaling0\cocoaplatform0{\fonttbl\f0\fswiss\fcharset0 Helvetica;} +{\colortbl;\red255\green255\blue255;\red32\green0\blue99;\red255\green255\blue51;} +{\*\expandedcolortbl;;\cssrgb\c17067\c7357\c46453;\cssrgb\c99946\c98636\c25320;} +\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0 +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0 + +\f0\fs24 \cf2 gg\ +\ +\cf3 lol} \ No newline at end of file diff --git a/design/recipes.py b/design/recipes.py new file mode 100644 index 0000000..199d9fe --- /dev/null +++ b/design/recipes.py @@ -0,0 +1,639 @@ +craft={ + "basketofeggs":{ + "items":[ + [1,"egg0"], + [1,"egg1"], + [1,"egg2"], + [1,"egg3"], + [1,"egg4"], + [1,"egg5"], + [1,"egg6"], + [1,"egg7"], + [1,"egg8"], + ], + "cost":100, + }, + "xbox":{ + "items":[ + [1,"x0"], + [1,"x1"], + [1,"x2"], + [1,"x3"], + [1,"x4"], + [1,"x5"], + [1,"x6"], + [1,"x7"], + [1,"x8"], + ], + "cost":1200, + }, + "carrotsword":{ + "items":[ + [1,"blade"], + [1,"carrot"], + ], + "cost":500, + }, + "wblade":{ + "items":[ + [1,"stick",9], + [1,"blade",9], + [800,"essenceoffrost"], + ], + "cost":24000000, + }, + "rod":{ + "items":[ + [1,"staff"], + [1,"spidersilk"], + ], + "cost":100, + }, + "pickaxe":{ + "items":[ + [1,"staff"], + [1,"spidersilk"], + [1,"blade"], + ], + "cost":100, + }, + "stealthcape":{ + "items":[ + [1,"bcape",7], + [5,"shadowstone"], + [200,"essenceofnature"], + [1000,"cscale"], + ], + "cost":2000000, + }, + "cake":{ + "items":[ + [10,"whiteegg"], + ], + "cost":5, + }, + "bfangamulet":{ + "items":[ + [1,"bfang"], + [5000,"bwing"], + ], + "cost":4000000, + }, + # "stand1":{ + # "items":[ + # [1,"stand0"], + # [1,"ledger"], + # [6,"storagebox"], + # ], + # "cost":6400000, + # }, + "wingedboots":{ + "items":[ + [1,"shoes"], + [20,"feather0"], + ], + "cost":120000, + }, + "fierygloves":{ + "items":[ + [1,"gloves"], + [20,"feather0"], + [2,"essenceoffire"], + ], + "cost":120000, + }, + "fclaw":{ + "items":[ + [1,"claw"], + [2,"essenceoffrost"], + ], + "cost":20000, + }, + "fsword":{ + "items":[ + [1,"blade"], + [2,"essenceoffrost"], + ], + "cost":20000, + }, + "froststaff":{ + "items":[ + [1,"staff"], + [2,"essenceoffrost"], + ], + "cost":20000, + }, + "snowflakes":{ + "items":[ + [1,"throwingstars"], + [1,"essenceoffrost"], + ], + "cost":20000, + }, + "frostbow":{ + "items":[ + [1,"bow"], + [3,"essenceoffrost"], + ], + "cost":40000, + }, + "firebow":{ + "items":[ + [1,"bow"], + [2,"essenceoffire"], + ], + "cost":40000, + }, + "fireblade":{ + "items":[ + [1,"blade"], + [1,"essenceoffire"], + ], + "cost":20000, + }, + "firestaff":{ + "items":[ + [1,"staff"], + [1,"essenceoffire"], + ], + "cost":20000, + }, + "firestars":{ + "items":[ + [1,"throwingstars"], + [1,"essenceoffire"], + ], + "cost":180000, + }, + "heartwood":{ + "items":[ + [1,"woodensword",8], + [1,"nheart"], + ], + "cost":120000000, + }, + "offeringx":{ + "items":[ + [10,"offering"], + [1200,"essenceofnature"], + [200,"essenceoflife"], + [1,"essenceofgreed"], + ], + "cost":32000000, + }, + "computer":{ + "items":[ + [1,"networkcard"], + [8,"qubics"], + [1,"platinumnugget"], + [12,"goldnugget"], + [100,"electronics"], + ], + "cost":120000000, + }, + "supercomputer":{ + "items":[ + [1,"computer"], + [1,"tracker"], + [3,"qubics"], + [2000,"electronics"], + ], + "cost":4800000000, + }, + "dartgun":{ + "items":[ + [1,"blade",9], + [12,"qubics"], + [4,"platinumnugget"], + [20,"goldnugget"], + ], + "cost":32000000, + }, + "bronzeingot":{ + "items":[ + [16,"bronzenugget"], + ], + "cost":360000, + }, + "goldingot":{ + "items":[ + [12,"goldnugget"], + ], + "cost":3600000, + }, + "platinumingot":{ + "items":[ + [8,"platinumnugget"], + ], + "cost":36000000, + }, + "candycanesword":{ + "items":[ + [1,"blade",7], + [1,"candycane"], + ], + "cost":480000, + }, + "merry":{ + "items":[ + [1,"bow"], + [1,"candycane"], + [1,"mistletoe"], + ], + "cost":480000, + }, + "harpybow":{ + "items":[ + [1,"t2bow"], + [100,"feather1"], + ], + "cost":1640000, + }, + "gstaff":{ + "items":[ + [1,"staff",8], + [1,"essenceofgreed"], + ], + "cost":180000, + }, + "pouchbow":{ + "items":[ + [1,"bow"], + [1,"smoke"], + ], + "cost":180000, + }, + "ornamentstaff":{ + "items":[ + [1,"staff"], + [1,"ornament"], + [20,"confetti"], + ], + "cost":120000, + }, + "charmer":{ + "items":[ + [1,"goldnugget"], + [20,"gem1"], + [1,"emptyheart"], + ], + "cost":80000, + }, + "ctristone":{ + "items":[ + [1,"strring"], + [1,"intring"], + [1,"dexring"], + [10,"vitscroll"], + ], + "cost":20000, + }, + "cclaw":{ + "items":[ + [1,"claw"], + [1,"crabclaw"], + ], + "cost":24000, + }, + "slimestaff":{ + "items":[ + [1,"staff"], + [10,"gslime"], + ], + "cost":24000, + }, + "mushroomstaff":{ + "items":[ + [1,"staff"], + [2,"smush"], + ], + "cost":24000, + }, + "wcap":{ + "items":[ + [50,"beewings"], + [3,"gslime"], + ], + "cost":0, + "quest":"mcollector", + }, + "wgloves":{ + "items":[ + [60,"beewings"], + [20,"spores"], + ], + "cost":0, + "quest":"mcollector", + }, + "wbreeches":{ + "items":[ + [10,"crabclaw"], + [100,"spores"], + ], + "cost":0, + "quest":"mcollector", + }, + "wattire":{ + "items":[ + [100,"gslime"], + [200,"crabclaw"], + ], + "cost":0, + "quest":"mcollector", + }, + "wshoes":{ + "items":[ + [5,"frogt"], + [500,"beewings"], + [100,"crabclaw"], + ], + "cost":0, + "quest":"mcollector", + }, + "quiver":{ + "items":[ + [1,"ascale"], + [200,"beewings"], + ], + "cost":0, + "quest":"mcollector", + }, + "orbg":{ + "items":[ + [1,"ascale"], + [1,"pleather"], + [1,"cscale"], + [1,"bfur"], + ], + "cost":0, + "quest":"mcollector", + }, + "armorring":{ + "items":[ + [1,"snakefang"], + [1,"lotusf"], + [1,"vitring",2], + ], + "cost":0, + "quest":"mcollector", + }, + "resistancering":{ + "items":[ + [1,"ink"], + [5,"ascale"], + [1,"vitring",2], + ], + "cost":0, + "quest":"mcollector", + }, + "lbelt":{ + "items":[ + [100,"bfur"], + [1,"hpbelt",2], + ], + "cost":0, + "quest":"mcollector", + }, + "stinger":{ + "items":[ + [12,"feather0"], + ], + "cost":0, + "quest":"mcollector", + }, + "hbow":{ + "items":[ + [40,"dstones"], + [2,"pleather"], + [1,"feather0"], + ], + "cost":0, + "quest":"mcollector", + }, + "snakeoil":{ + "items":[ + [40,"dstones"], + [9000,"rattail"], + ], + "cost":0, + "quest":"witch", + }, + "elixirfires":{ + "items":[ + [1,"cshell"], + [2000,"hpot0"], + ], + "cost":0, + "quest":"witch", + }, + "elixirfzres":{ + "items":[ + [50,"bfur"], + [10,"mpot0"], + ], + "cost":0, + "quest":"witch", + }, + "elixirpnres":{ + "items":[ + [500,"bwing"], + [1,"hpot0"], + ], + "cost":0, + "quest":"witch", + }, + "daggerofthedead":{ + "items":[ + [1,"mbones"], + [1,"wand"], + ], + "cost":24000, + }, + "spearofthedead":{ + "items":[ + [2,"mbones"], + [1,"spear"], + ], + "cost":24000, + }, + "staffofthedead":{ + "items":[ + [1,"mbones"], + [1,"staff"], + ], + "cost":120000, + }, + "bowofthedead":{ + "items":[ + [1,"mbones"], + [1,"bow"], + ], + "cost":120000, + }, + "swordofthedead":{ + "items":[ + [1,"mbones"], + [1,"sword"], + ], + "cost":24000, + }, + "maceofthedead":{ + "items":[ + [1,"mbones"], + [1,"wbasher"], + ], + "cost":240000, + }, + "pmaceofthedead":{ + "items":[ + [1,"mbones"], + [1,"pmace"], + ], + "cost":24000, + }, + "elixirint1":{"items":[[10,"elixirint0"]],"cost":1000}, + "elixirdex1":{"items":[[10,"elixirdex0"]],"cost":1000}, + "elixirvit1":{"items":[[10,"elixirvit0"]],"cost":1000}, + "elixirstr1":{"items":[[10,"elixirstr0"]],"cost":1000}, + "elixirint2":{"items":[[10,"elixirint1"]],"cost":2400}, + "elixirdex2":{"items":[[10,"elixirdex1"]],"cost":2400}, + "elixirvit2":{"items":[[10,"elixirvit1"]],"cost":2400}, + "elixirstr2":{"items":[[10,"elixirstr1"]],"cost":2400}, +} + +dismantle={ + "daggerofthedead":{ + "items":[ + [1,"mbones"], + ], + "cost":40, + }, + "swordofthedead":{ + "items":[ + [1,"mbones"], + ], + "cost":40, + }, + "staffofthedead":{ + "items":[ + [1,"mbones"], + ], + "cost":40, + }, + "bowofthedead":{ + "items":[ + [1,"mbones"], + ], + "cost":40, + }, + "maceofthedead":{ + "items":[ + [1,"mbones"], + ], + "cost":40, + }, + "pmaceofthedead":{ + "items":[ + [1,"mbones"], + ], + "cost":40, + }, + "spearofthedead":{ + "items":[ + [2,"mbones"], + ], + "cost":40, + }, + "fireblade":{ + "items":[ + [1,"essenceoffire"], + ], + "cost":10000, + }, + "firestaff":{ + "items":[ + [1,"essenceoffire"], + ], + "cost":10000, + }, + "firestars":{ + "items":[ + [1,"essenceoffire"], + ], + "cost":10000, + }, + "essenceoffrost":{ + "items":[ + [1,"emptyjar"], + ], + "cost":10, + }, + "essenceoflife":{ + "items":[ + [1,"emptyjar"], + ], + "cost":10, + }, + "essenceoffire":{ + "items":[ + [1,"emptyjar"], + ], + "cost":10, + }, + "essenceofnature":{ + "items":[ + [1,"emptyjar"], + ], + "cost":10, + }, + "bronzeingot":{ + "items":[ + [16,"bronzenugget"], + ], + "cost":120000, + }, + "goldingot":{ + "items":[ + [12,"goldnugget"], + ], + "cost":1200000, + }, + "platinumingot":{ + "items":[ + [8,"platinumnugget"], + ], + "cost":12000000, + }, + "lostearring":{ + "items":[ + [0.12,"goldnugget"], + ], + "cost":36000, + }, + "goldenegg":{ + "items":[ + [1,"goldnugget"], + [0.5,"goldnugget"], + ], + "cost":120000, + }, + "molesteeth":{ + "items":[ + [0.1,"platinumnugget"], + ], + "cost":100000, + }, + # "ringsj":{ + # "items":[ + # [1,"wshield"], + # [1,"wshield"], + # ], + # "cost":100000, + # }, + # "offering":{ + # "items":[ + # [1,"emptyjar"], + # ], + # "cost":20, + # }, +} \ No newline at end of file diff --git a/design/skills.py b/design/skills.py new file mode 100644 index 0000000..3720a60 --- /dev/null +++ b/design/skills.py @@ -0,0 +1,1176 @@ +from design.conditions import conditions + +skills={ + #Monsters + "portal":{ + "type":"monster", + "name":"Portal", + "explanation":"Open a portal to different maps and instances", + }, + "self_healing":{ + "type":"monster", + "name":"Healing", + "explanation":"Periodical self healing", + }, + "healing":{ + "type":"monster", + "name":"Healing", + "explanation":"Heals an ally or self", + }, + "anger":{ + "type":"monster", + "name":"Anger", + "explanation":"Randomly targets someone", + "hostile":True, + }, + "zap":{ + "type":"monster", + "name":"Zap", + "explanation":"Zaps you with a pure damage ray", + "damage":1200, + "hostile":True, + "projectile":"sburst", + "damage_type":"pure", + }, + "fireball":{ + "type":"monster", + "name":"Fireball", + "explanation":"Hurls a fireball!", + "damage":4000, + "hostile":True, + "projectile":"magic", + "damage_type":"magical", + }, + "frostball":{ + "type":"monster", + "name":"Frostball", + "explanation":"Hurls a frostball!", + "damage":800, + "hostile":True, + "projectile":"frostball", + "damage_type":"magical", + }, + "warpstomp":{ + "type":"monster", + "name":"Warpstomp", + "explanation":"Warps to a random player nearby and stomps players in vicinity", + "hostile":True, + }, + "deepfreeze":{ + "type":"monster", + "name":"Deepfreeze", + "explanation":"Randomly freezes a nearby opponent", + "damage":1200, + "hostile":True, + "projectile":"burst", + "damage_type":"pure", + }, + "multi_burn":{ + "type":"monster", + "name":"Multi Burn", + "explanation":"Hurl a fireball at everyone who dared attack him and burn them!", + "ui":True, + "hostile":True, + "skin":"essenceoffire", + "damage_type":"magical", + }, + "mlight":{ + "type":"monster", + "name":"Light", + "explanation":"Reveals invisible entities nearby and prevents them from going invisible again for 12 seconds.", + "ui":True, + "hostile":True, + "skin":"skill_light", + }, + "dampening_aura":{ + "type":"monster", + "name":"Dampening", + "explanation":"Prevents teleports", + "condition":"dampened", + "aura":True, + "hostile":True, + "passive":True, + "skin":"condition_neutral", + }, + "weakness_aura":{ + "type":"monster", + "name":"Weakness", + "explanation":"Weakens", + "condition":"weakness", + "aura":True, + "hostile":True, + "passive":True, + "skin":"condition_bad", + }, + "curse_aura":{ + "type":"monster", + "name":"Curse", + "explanation":"A wretched aura", + "condition":"cursed", + "aura":True, + "hostile":True, + "passive":True, + "skin":"condition_bad", + }, + "multi_freeze":{ + "type":"monster", + "name":"Multi Freeze", + "explanation":"Hurl a frostball at everyone who dared attack him and freeze them!", + "hostile":True, + "ui":True, + "skin":"essenceoffrost", + "damage_type":"magical", + }, + "mtangle":{ + "type":"monster", + "name":"Tangle", + "explanation":"Communicates through spores to activate dormant plants underneath. Slows down opponents significantly.", + "mp":360, + "range":480, + "cooldown":40000, + "duration":5000, + "condition":"tangled", + "target":True, + "monsters":True, + "hostile":True, + }, + "stone":{ + "type":"monster", + "name":"Stone", + "explanation":"Looking into his eye for too long turns you to stone!", + "condition":"stoned", + "hostile":True, + }, + #Players + "snowball":{ + "type":"skill", + "skin":"snowball", + "inventory":["snowball"], + "name":"Snowball", + "explanation":"Throw a snowball at someone!", + "condition":"frozen", + "damage":1, + "mp":120, + "cooldown":180, + "range":720, + "projectile":"snowball", + "target":True, + "merchant_use":True, + }, + "scare":{ + "type":"skill", + "skin":"skill_scare", + "slot":[["orb","jacko"]], + "name":"Scare", + "explanation":"Activate your Jack-o Lantern to scare away monsters targeting you!", + "mp":50, + "cooldown":5000, + }, + "power":{ + "type":"skill", + "skin":"powerglove", + "slot":[["gloves","powerglove"]], + "name":"Power", + "explanation":"Unleash the power", + "mp":320, + "cooldown":500, + "condition":"power", + }, + "xpower":{ + "type":"skill", + "skin":"goldenpowerglove", + "slot":[["gloves","goldenpowerglove"]], + "name":"Power", + "explanation":"Unleash the power", + "mp":320, + "cooldown":500, + "condition":"xpower", + }, + "warp":{ + "type":"skill", + "skin":"warpvest", + "slot":[["chest","warpvest"]], + "name":"Warp", + "explanation":"Warp space to jump into any location", + "mp":40, + "cooldown":200, + }, + "zapperzap":{ + "type":"skill", + "skin":"trigger", + "slot":[["ring1","zapper"],["ring2","zapper"]], + "name":"Zap", + "explanation":"Zap your target for 200 damage", + "damage":200, + "damage_type":"magical", + "mp":140, + "cooldown":200, + "range":420, + "projectile":"gburst", + "target":True, + "hostile":True, + }, + "charm":{ + "type":"skill", + "skin":"charmer", + "slot":[["orb","charmer"]], + "name":"Charm", + "explanation":"Charm a monster [%]", + "condition":"charmed", + "mp":40, + "cooldown":60000, + "target":"monster", + "hostile":True, + }, + "tangle":{ + "type":"skill", + "skin":"heartwood", + "slot":[["mainhand","heartwood"],["offhand","heartwood"]], + "name":"Tangle", + "explanation":"Unleash the contained powers of nature to hinder an opponent.", + "mp":40, + "cooldown":60000, + "target":True, + "hostile":True, + }, + "rspeed":{ + "type":"skill", + "skin":"buff_speed", + "condition":"rspeed", + "class":["rogue"], + "name":"Rogue Swiftness", + "explanation":"Buff a target to increase their speed.", + "mp":320, + "range":320, + "level":40, + "cooldown":100, + "target":"player", + }, + "reflection":{ + "type":"skill", + "skin":"buff_reflection", + "condition":"reflection", + "class":["mage"], + "name":"Reflective Shield", + "explanation":"Erects a magical shield around the target to grant them +20% Reflection for the duration.", + "mp":540, + "range":320, + "level":60, + "cooldown":30000, + "target":"player", + }, + "pickpocket":{ + "type":"skill", + "skin":"skill_pickpocket", + "class":["rogue"], + "name":"Pickpocket", + "explanation":"Try to steal a single PVP marked item from the target!", + "range":15, + "level":16, + "mp":10, + "reuse_cooldown":2*60*1000, + "duration_min":200, + "duration_max":2000, + "target":"player", + "persistent":True, + }, + "fishing":{ + "type":"skill", + "skin":"skill_fishing", + "class":["merchant"], + "wtype":["rod"], + "name":"Fishing", + "explanation":"Swing your rod and catch some fish!", + "range":15, + "level":16, + "mp":120, + "reuse_cooldown":48*60*1000, + "duration_min":5000, + "duration_max":15000, + "persistent":True, + }, + "mining":{ + "type":"skill", + "skin":"skill_mining", + "class":["merchant"], + "wtype":["pickaxe"], + "name":"Mining", + "explanation":"Use your pickaxe to mine some mines!", + "range":15, + "level":16, + "mp":120, + "reuse_cooldown":124*60*1000, + "duration_min":5000, + "duration_max":15000, + "persistent":True, + }, + "mluck":{ + "type":"skill", + "skin":"buff_luck", + "condition":"mluck", + "class":["merchant"], + "name":"Merchant's Luck", + "explanation":"Buff a target to increase their luck. 2% chance for you to receive a duplicate of their looted items!", + "level":40, + "mp":10, + "range":320, + "cooldown":100, + "target":"player", + }, + "mcourage":{ + "type":"skill", + "skin":"skill_mcourage", + "condition":"mcourage", + "class":["merchant"], + "name":"Merchant's Courage", + "explanation":"When you sense danger, you know what to do...", + "level":70, + "mp":2400, + "cooldown":2000, + }, + "mfrenzy":{ + "type":"skill", + "skin":"skill_mfrenzy", + "condition":"mfrenzy", + "class":["merchant"], + "name":"Merchant's Frenzy", + "explanation":"When you sense danger, you know what to do!", + "level":85, + "mp":400, + "cooldown":20000, + }, + "massproduction":{ + "type":"skill", + "skin":"skill_massproduction", + "condition":"massproduction", + "class":["merchant"], + "name":"Mass Production", + "explanation":"Adds a 1-time use buff that speeds up the next upgrade or compound by 50%. The buff expires in 10 seconds if not used.", + "level":30, + "mp":20, + "cooldown":50, + }, + "massproductionpp":{ + "type":"skill", + "skin":"skill_massproductionpp", + "condition":"massproductionpp", + "class":["merchant"], + "name":"Mass Production++", + "explanation":"Adds a 1-time use buff that speeds up the next upgrade or compound by 90%. The buff expires in 10 seconds if not used.", + "level":60, + "mp":200, + "cooldown":50, + }, + "throw":{ + "type":"skill", + "skin":"skill_throw", + "class":["merchant"], + "name":"Throw Stuff", + "explanation":"Terrified? Just throw whatever you can find at your opponent!", + "range":200, + "code":"range=character.level+200", + "positive":["essenceoflife"], + "negative":["essenceoffire"], + "nprop":["attack","armor"], + "damage_type":"physical", + "level":60, + "mp":200, + "cooldown":400, + "hostile":True, + "target":True, + "pierces_immunity":True, + }, + "burst":{ + "type":"skill", + "skin":"skill_burst", + "class":["mage"], + "name":"Mana Burst", + "explanation":"Converts your entire mana pool to pure damage. Deals 0.555 pure damage for each MP.", + "mp":0, + "ratio":0.555, + "cooldown":6000, + "target":True, + "damage_type":"pure", + "hostile":True, + "projectile":"burst", + "use_range":True, + }, + "cburst":{ + "type":"skill", + "skin":"skill_cburst", + "class":["mage"], + "name":"Controlled Mana Burst", + "level":75, + "explanation":"A skill for experienced mages. Allows you to control and channel your most powerful ability.", + "mp":80, + "ratio":0.5, + "cooldown":240, + "list":True, + "hostile":True, + "projectile":"burst", + "use_range":True, + "damage_type":"magical", + }, + "energize":{ + "type":"skill", + "skin":"skill_energize", + "class":["mage"], + "name":"Energize", + "range":320, + "level":20, + "explanation":"Transfers mana to a target. As a side effect the target gains high attack speed for a short duration.", + "cooldown":4000, + "condition":"energized", + "target":"player", + }, + "light":{ + "type":"skill", + "skin":"skill_light", + "class":["mage"], + "name":"Light", + "explanation":"Reveals invisible entities nearby and prevents them from going invisible again for 12 seconds.", + "mp":2000, + "cooldown":0, + "hostile":True, + }, + "blink":{ + "type":"skill", + "skin":"skill_blink", + "class":["mage"], + "name":"Blink", + "explanation":"Teleport to a nearby location.", + "mp":1600, + "cooldown":1200, + }, + "magiport":{ + "type":"skill", + "skin":"skill_teleport", + "class":["mage"], + "name":"Magiport", + "explanation":"Pull someone to your location using the magical paths that surround our world.", + "complementary":"Unless the target doesn't have a T2+ helmet, high intelligence, or a low level, it can't resist being magiported. (Reverted [03/07/18])", + "mp":900, + "cooldown":0, + "target":"player", + "global":True, + }, + "charge":{ + "type":"skill", + "skin":"skill_charge", + "class":["warrior"], + "name":"Charge", + "explanation":"Gain 30 Speed for a short duration.", + "mp":0, + "condition":"charging", + "cooldown":40000, + }, + "dash":{ + "type":"skill", + "skin":"skill_dash", + "class":["warrior"], + "name":"Dash", + "explanation":"Push forward, jumping over obstacles, climbing hills, defying physics!", + "mp":120, + "set_speed":500, + "cooldown":0, + }, + "taunt":{ + "type":"skill", + "skin":"skill_taunt", + "class":["warrior"], + "name":"Taunt", + "explanation":"Taunts an enemy. Steals aggro from friendly targets.", #Prevents players from escaping in pvp. + "range":200, + "mp":40, + "cooldown":3000, + "damage":1, + "target":True, + "hostile":True, + "projectile":"stone", + "pierces_immunity":True, + }, + "agitate":{ + "type":"skill", + "skin":"skill_agitate", + "class":["warrior"], + "name":"Agitate", + "explanation":"Taunts all nearby monsters.", + "range":320, + "level":68, + "mp":420, + "cooldown":2200, + "hostile":True, + }, + "hardshell":{ + "type":"skill", + "skin":"skill_hardshell", + "class":["warrior"], + "name":"Hard Shell", + "explanation":"Use everything at your disposal to protect yourself from physical attacks for a short duration.", + "condition":"hardshell", + "level":60, + "mp":480, + "cooldown":16000, + }, + "cleave":{ + "type":"skill", + "skin":"skill_cleave", + "class":["warrior"], + "wtype":["axe","scythe"], + "name":"Cleave", + "explanation":"Swing your axe in a flurry to damage all enemies nearby!", + "range":160, + "level":52, + "mp":720, + "cooldown":1200, + "hostile":True, + "pierces_immunity":True, + "damage_type":"physical", + "procs":True, + }, + "stomp":{ + "type":"skill", + "skin":"skill_stomp", + "class":["warrior"], + "wtype":"basher", + "name":"Stomp", + "explanation":"Use your basher to Stomp the ground to Stun enemies nearby!", + "condition":"stunned", + "range":400, + "level":52, + "mp":120, + "cooldown":24000, + "duration":3200, + "hostile":True, + "damage_type":"physical", + }, + "warcry":{ + "type":"skill", + "skin":"skill_warcry", + "class":["warrior"], + "name":"War Cry", + "explanation":"Motivate your allies to fight!", + "level":70, + "mp":320, + "range":600, + "cooldown":60000, + "condition":"warcry", + }, + "poisonarrow":{ + "type":"skill", + "skin":"skill_poisonarrow", + "class":["ranger"], + "name":"Poison Arrow", + "explanation":"Fire a single low damage but poison coated arrow at your opponent.", + "wtype":["bow","crossbow"], + "cooldown":300, + "damage":200, + "mp":360, + "consume":"poison", + "target":True, + "hostile":True, + "use_range":True, + "projectile":"poisonarrow", + "damage_type":"physical", + "condition":"poisoned", + "procs":True, + }, + "piercingshot":{ + "type":"skill", + "skin":"skill_piercingshot", + "class":["ranger"], + "name":"Piercing Shot", + "explanation":"Fire heavy, armor piercing arrows at your opponent. They deal 75% of the damage but pierce through 500 armor.", + "wtype":["bow","crossbow"], + "apiercing":500, + "damage_multiplier":0.75, + "mp":64, + "level":72, + "cooldown_multiplier":1, + "share":"attack", + "use_range":True, + "target":True, + "hostile":True, + "damage_type":"physical", + "procs":True, + "pierces_immunity":True, + }, + "huntersmark":{ + "type":"skill", + "skin":"skill_huntersmark", + "class":["ranger"], + "name":"Hunter's Mark", + "explanation":"Mark an opponent for death, prevent them from stealthing away and increase damage done by 10%", + "mp":240, + "condition":"marked", + "cooldown":10000, + "target":True, + "hostile":True, + }, + "pcoat":{ + "type":"skill", + "skin":"skill_pcoat", + "class":["rogue"], + "name":"A Poisonous Touch", + "explanation":"Coat your blade with a poison sack. Poison everyone you damage before the venom dissipates.", + "condition":"poisonous", + "cooldown":50000, + "duration":7000, + "mp":600, + "consume":"poison", + }, + "invis":{ + "type":"skill", + "skin":"skill_invis", + "class":["rogue"], + "name":"Assassin's Smoke", + "explanation":"Disappear into the shadows. Deal 1.25X damage when you sneak up on an enemy. Cooldown starts when you re-appear.", + "reuse_cooldown":12000, + }, + "mentalburst":{ + "type":"skill", + "skin":"skill_mentalburst", + "class":["rogue"], + "name":"Mental Burst", + "explanation":"Channel your mental abilities for a magical blow. If the target is defeated, the damage dealt is converted to mana.", + "damage_type":"magical", + "cooldown":900, + "damage_multiplier":0.6, + "range_multiplier":1.2, + "range_bonus":32, + "mp":180, + "target":True, + "requirements":{"int":64}, + "warning":"Highly unbalanced skill, could get nerfed or modified", + "hostile":True, + "projectile":"mentalburst", + }, + "quickpunch":{ + "type":"skill", + "skin":"skill_quickpunch", + "class":["rogue"], + "name":"Quick Punch", + "explanation":"Use your agility to quickly punch your opponent between your devastating attacks!", + "wtype":"fist", + "cooldown":250, + "damage_multiplier":0.25, + "mp":240, + "use_range":True, + "target":True, + "hostile":True, + "projectile":"quickpunch", + "damage_type":"physical", + "pierces_immunity":True, + #"procs":True, + }, + "quickstab":{ + "type":"skill", + "skin":"skill_quickstab", + "class":["rogue"], + "name":"Quick Stab", + "explanation":"Use your agility to quickly stab your opponent between your devastating attacks!", + "wtype":"dagger", + "cooldown":250, + "share":"quickpunch", + "damage_multiplier":0.36, + "mp":320, + "use_range":True, + "target":True, + "hostile":True, + "projectile":"quickstab", + "damage_type":"physical", + "procs":True, + "pierces_immunity":True, + }, + "stack":{ + "type":"passive", + "skin":"skill_stack", + "class":["rogue"], + "name":"Stacked Damage", + "explanation":"Slowly learning the ways of your opponent each rogue attack deals one more damage.", + "max":2000, + }, + "shadowstrike":{ + "type":"skill", + "skin":"skill_shadowstrike", + "class":["rogue"], + "name":"Shadow Strike", + "explanation":"Use a shadow stone to strike a random enemy in a parallel universe!", + "range":360, + "level":70, + "mp":320, + "cooldown":1200, + "consume":"shadowstone", + "hostile":True, + "damage_type":"physical", + }, + "entangle":{ + "type":"skill", + "skin":"skill_entangle", + "class":["mage"], + "name":"Entangle", + "explanation":"Unleash the contained powers of nature to hinder an opponent.", + "level":72, + "mp":360, + "range":480, + "cooldown":40000, + "duration":5000, + "condition":"tangled", + "target":True, + "monsters":True, + "consume":"essenceofnature", + "hostile":True, + }, + "track":{ + "type":"skill", + "skin":"skill_track", + "class":["ranger"], + "name":"Track", + "explanation":"Use your fine-tuned senses to detect others.", + "cooldown":1600, + "range":1440, + "mp":80, + }, + "supershot":{ + "type":"skill", + "skin":"skill_supershot", + "class":["ranger"], + "name":"Supershot", + "explanation":"Deals 1.5X instant damage from an incredible distance.", + "wtype":["bow","crossbow"], + "damage_multiplier":1.5, + "cooldown":30000, + "range_multiplier":3, + "mp":400, + "target":True, + "hostile":True, + "pierces_immunity":True, + "damage_type":"physical", + "procs":True, + }, + "3shot":{ + "type":"skill", + "skin":"skill_3shot", + "class":["ranger"], + "name":"3-Shot", + "explanation":"Hits 3 targets at once! Deals 0.7X damage to each target.", + "wtype":["bow","crossbow"], + "damage_multiplier":0.7, + "level":60, + "mp":200, + "cooldown_multiplier":1, + "multi":True, + "share":"attack", + "hostile":True, + "pierces_immunity":True, + "damage_type":"physical", + "procs":True, + "use_range":True, + }, + "5shot":{ + "type":"skill", + "skin":"skill_5shot", + "class":["ranger"], + "name":"5-Shot", + "explanation":"Hits 5 targets at once! Deals 0.5X damage to each target.", + "wtype":["bow","crossbow"], + "damage_multiplier":0.5, + "level":75, + "mp":320, + "cooldown_multiplier":1, + "multi":True, + "share":"attack", + "hostile":True, + "pierces_immunity":True, + "damage_type":"physical", + "procs":True, + "use_range":True, + }, + "4fingers":{ + "type":"skill", + "skin":"skill_4fingers", + "class":["ranger"], + "name":"4 Finger Technique", + "explanation":"Use the ancient arts to send the target to a deep meditation state. Just several taps to key chakra points does the job!", + "level":64, + "mp":260, + "range":120, + "cooldown":40000, + "duration":5000, + "condition":"fingered", + "target":"player", + "monsters":False, + "hostile":True, + }, + "curse":{ + "type":"skill", + "skin":"skill_curse", + "class":["priest"], + "name":"Curse", + "explanation":"Cursed opponents receive 20% more damage, deal 20% less damage and they slow down by 20.", + "mp":400, + "duration":5000, + "cooldown":5000, + "condition":"cursed", + "target":True, + "hostile":True, + "projectile":"curse", + "damage_type":"magical", + }, + "phaseout":{ + "type":"skill", + "skin":"skill_phaseout", + "class":["priest"], + "name":"Phase Out", + "explanation":"Absorb a shadow stone to phase yourself out from this universe.", + "level":64, + "duration":5000, + "cooldown":4000, + "mp":200, + "consume":"shadowstone", + "condition":"phasedout", + }, + "darkblessing":{ + "type":"skill", + "skin":"skill_dbuff", + "class":["priest"], + "name":"Dark Blessing", + "explanation":"Increases damage by 25% for the duration.", + "level":70, + "mp":900, + "range":600, + "duration":8000, + "cooldown":60000, + "condition":"darkblessing", + }, + "absorb":{ + "type":"skill", + "skin":"skill_absorbsins", + "class":["priest"], + "name":"Absorb Sins", + "explanation":"Pulls all targets from a friendly character.", + "range":240, + "cooldown":400, + "mp":200, + "level":55, + "target":"player", + }, + "partyheal":{ + "type":"skill", + "skin":"skill_pheal", + "class":["priest"], + "name":"Party Heal", + "explanation":"Heals all the party members.", + "output":400, + "action":"heal", + "levels":[ + [0,500], + [60,600], + [72,720], + [80,800], + ], + "mp":400, + "cooldown":200, + "party":True, + "projectile":"partyheal", + "damage_type":"magical", + "heal":True, + "multi":True, + }, + "selfheal":{ + "type":"skill", + "skin":"skill_selfheal", + "class":["paladin"], + "name":"Heal", + "explanation":"Heal yourself", + "output":400, + "action":"heal", + "levels":[ + [0,500], + [60,600], + [72,720], + [80,800], + ], + "mp":20, + "cooldown":1200, + "projectile":"partyheal", + "damage_type":"magical", + "heal":True, + }, + "mshield":{ + "type":"skill", + "skin":"skill_mshield", + "class":["paladin"], + "name":"Mana Shield", + "explanation":"Create a magical shield around yourself to absorb damage [Toggle]", + "condition":"mshield", + "toggle":True, + "mp":0, + "duration":999999999, + "cooldown":0, + }, + "purify":{ + "type":"skill", + "skin":"skill_purify", + "class":["paladin"], + "name":"Purify", + "level":60, + "damage":2000, + "damage_type":"pure", + "explanation":"Deals 2000 pure damage purifying the target, removes all buffs and debuffs dealing additional 400 damage for each and receive the Purifier buff if the target is defeated!", + "kill_buff":"purifier", + "projectile":"purify", + "hostile":True, + "target":True, + "mp":360, + "cooldown":24000, + "range":480, + }, + "smash":{ + "type":"skill", + "skin":"skill_smash", + "class":["paladin"], + "name":"Smash", + "explanation":"Smash your opponent using your mace!", + "wtype":"mace", + "cooldown":320, + "level":10, + "damage_multiplier":0.36, + "mp":380, + "use_range":True, + "target":True, + "hostile":True, + "projectile":"smash", + "damage_type":"physical", + "procs":True, + "pierces_immunity":True, + }, + "alchemy":{ + "type":"skill", + "skin":"skill_alchemy", + "class":["mage"], + "name":"Alchemy", + "explanation":"Dangerous skill, use with caution! Converts your firstfound item into pure gold!", + "variance":0.2, + "output":0.8, + "action":"rate", + "levels":[ + [40,0.8], + [50,0.86], + [60,0.92], + [70,1.0], + [80,1.06], + [90,1.10], + [100,1.12], + ], + "level":40, + "mp":347, + "cooldown":8000, + "party":True, + }, + "revive":{ + "type":"skill", + "skin":"skill_revive", + "class":["priest"], + "name":"Revive!", + "explanation":"If a fallen comrade's gravestone has been healed fully, revives them using an Essence of Life!", + "mp":500, + "cooldown":200, + "range":240, + "consume":"essenceoflife", + "target":"player", + }, + "regen_hp":{ + "type":"ability", + "skin":"regen_hp", + "name":"Regenerate HP", + "share":"use_hp", + "cooldown_multiplier":2, + "explanation":"Regenerate 50 HP without using potions.", + }, + "regen_mp":{ + "type":"ability", + "skin":"regen_mp", + "name":"Regenerate MP", + "share":"use_mp", + "cooldown_multiplier":2, + "explanation":"Regenerate 100 MP without using potions.", + }, + "use_mp":{ + "type":"ability", + "skin":"use_mp", + "name":"Use MP Potion", + "explanation":"Uses an MP potion from your inventory. If there are multiple potions, the last one is used. If there are no potions, your character regenerates a small amount of MP with a high cooldown.", + "cooldown":2000, + }, + "use_hp":{ + "type":"ability", + "skin":"use_hp", + "name":"Use HP Potion", + "explanation":"Uses an HP potion from your inventory. If there are multiple potions, the last one is used. If there are no potions, your character regenerates a small amount of HP with a high cooldown.", + "cooldown":2000, + }, + "use_town":{ + "type":"ability", + "skin":"use_town", + "name":"Town", + "explanation":"Teleports you to the center of the map.", + "cooldown":0, + }, + "attack":{ + "type":"ability", + "skin":"attack", + "name":"Attack", + "explanation":"Attack the target", + "target":True, + "hostile":True, + "pierces_immunity": True, + "use_range":True, + "projectile":"momentum", + "procs":True, + }, + "heal":{ + "type":"ability", + "skin":"heal", + "name":"Heal", + "class":["priest"], + "explanation":"Heal the target", + "cooldown_multiplier":1, + "share":"attack", + "target":True, + "use_range":True, + "pierces_immunity": True, + "projectile":"plight", + "damage_type":"magical", + "heal":True, + "procs":True, + }, + "travel":{ + "type":"ability", + "skin":"travel", + "name":"Travel!", + "explanation":"Where would you like to visit?", + }, + "stop":{ + "type":"ability", + "skin":"stop_g", + "name":"Stop", + "explanation":"Stops your character. Cancels all channeling abilities and active skills.", + "cooldown":0, + }, + "snippet":{ + "type":"utility", + "skin":"run_snippet1", + "name":"Snippet", + "explanation":"Maps a code snippet to a keypress.", + "skins":["run_snippet0","run_snippet1","run_snippet2"], + "code":True, + }, + "emotion":{ + "type":"utility", + "skin":"run_emotion", + "name":"Emotion", + "explanation":"Show a random emotion you've unlocked!", + }, + "pure_eval":{ + "type":"utility", + "skin":"run_eval0", + "name":"Pure Eval", + "explanation":"[Advanced] Maps a code snippet to be run directly inside the game, rather than using CODE. (Not to be confused with the text command, /eval, which evals inside the Code iframe)", + "skins":["run_eval0","run_eval1","run_eval2"], + "code":True, + }, + "esc":{ + "type":"utility", + "skin":"esc", + "name":"ESC", + "explanation":"Calls the esc_pressed() function inside the game. Major functionality.", + "ui":False, + }, + "move_up":{ + "type":"utility", + "skin":"up", + "name":"Move Up", + "explanation":"Moves the character upwards", + "ui":False, + }, + "move_down":{ + "type":"utility", + "skin":"down", + "name":"Move Down", + "explanation":"Moves the character downwards", + "ui":False, + }, + "move_left":{ + "type":"utility", + "skin":"left", + "name":"Move Left", + "explanation":"Moves the character leftwards", + "ui":False, + }, + "move_right":{ + "type":"utility", + "skin":"right", + "name":"Move Right", + "explanation":"Moves the character rightwards", + "ui":False, + }, + "toggle_code":{ + "skin":"code", + "name":"Toggle Code", + "ui":False, + }, + "toggle_run_code":{ + "skin":"run_code", + "name":"Engage/Disengage Code", + "ui":False, + }, + "toggle_inventory":{ + "type":"utility", + "skin":"inventory", + "name":"Toggle Inventory", + "explanation":"Toggles the inventory", + "ui":False, + }, + "toggle_stats":{ + "type":"utility", + "skin":"stats", + "name":"Toggle Stats", + "explanation":"Toggles the character sheet", + "ui":False, + }, + "toggle_character":{ + "type":"utility", + "skin":"character", + "name":"Toggle Character", + "explanation":"Toggles the character focus", + "ui":False, + }, + "open_snippet":{ + "type":"utility", + "skin":"snippet", + "name":"Open Snippet", + "explanation":"Open the Code Snippet interface", + "ui":False, + }, + "interact":{ + "type":"utility", + "skin":"interact", + "name":"Interact", + "explanation":"Interact with the nearest game entity, a door, doorway, or NPC.", + "ui":False, + }, + "gm":{ + "type":"gm", + "skin":"gm", + "name":"GM Abilities", + "explanation":"Jump, Jail, Mute, Use Any Skill", + } +} +for name in skills: + if skills[name].has_key("condition") and not skills[name].has_key("duration") and conditions.has_key(skills[name]["condition"]) and conditions[skills[name]["condition"]]: + try: + skills[name]["duration"]=conditions[skills[name]["condition"]]["duration"] + except: + import logging + logging.error("%s has no duration"%conditions[skills[name]["condition"]]) \ No newline at end of file diff --git a/design/skills.txt b/design/skills.txt new file mode 100644 index 0000000..e9f88c2 --- /dev/null +++ b/design/skills.txt @@ -0,0 +1,10 @@ +Warrior +1200 MP - 50% Evasion for 4 seconds - 60 second CD +800MP - War Cry - +10 Speed - 200 Armor - 200 Res - Party - 3 seconds - 80 second CD +500MP - Cleave +500MP - Stomp + + +Priest +Party Heal +Mana Burn - Burns Mana + Damage - 60 second CD - maybe DOT \ No newline at end of file diff --git a/design/sprites.py b/design/sprites.py new file mode 100644 index 0000000..22a5b22 --- /dev/null +++ b/design/sprites.py @@ -0,0 +1,1139 @@ +sprites={ + "test":{ + #"ignore":True, + "file":"/images/tiles/characters/ninja_turtles.png", + "rows":1, + "columns":4, + "matrix":[ + #["test"], + ["t1","test","t3","t4"], + ] + }, + "makeup1":{ + "file":"/images/cosmetics/makeup/makeup1.png?v=6", + "rows":1, + "columns":42, + "type":"head", + "matrix":[[]], #looped below + }, + "bwhair":{ + "file":"/images/cosmetics/hairdo/bwhair.png?v=2", + "rows":1, + "columns":1, + "type":"hair", + "matrix":[["bwhair"]], + }, + "burningeyes1":{ + "file":"/images/cosmetics/beardo/burningeyes1_anim.png", + "rows":1, + "columns":1, + "type":"a_makeup", + "matrix":[["breyes"]], + }, + "burningeyes2":{ + "file":"/images/cosmetics/beardo/burningeyes2_anim.png", + "rows":1, + "columns":1, + "type":"a_makeup", + "matrix":[["bbeyes"]], + }, + "bathat":{ + "file":"/images/cosmetics/hats/bathat_anim.png", + "rows":1, + "columns":1, + "type":"a_hat", + "matrix":[["bathat"]], + }, + "gcandle":{ + "file":"/images/cosmetics/hats/gcandle_anim.png", + "rows":1, + "columns":1, + "type":"a_hat", + "matrix":[["gcandle"]], + }, + "halo":{ + "file":"/images/cosmetics/hats/halo_anim.png", + "rows":1, + "columns":1, + "type":"a_hat", + "matrix":[["halo"]], + }, + "kunique":{ + "file":"/images/cosmetics/makeup/kunique.png?v=2", + "rows":1, + "columns":4, + "type":"head", + "matrix":[["bwhead","blackhead","testm1","testm2"]], + }, + "mbw":{ + "file":"/images/cosmetics/skins/mbw.png", + "rows":1, + "columns":1, + "type":"skin", + "size":"normal", + "matrix":[["mbw"]], + }, + "mabw":{ + "file":"/images/cosmetics/armors/mabw.png?v=2", + "rows":1, + "columns":2, + "type":"armor", + "size":"normal", + "matrix":[["mabw","nothing"]], + }, + "kglasses":{ + "file":"/images/cosmetics/accessories/kglasses.png?v=3", + "rows":1, + "columns":4, + "type":"face", + "matrix":[["bwglasses","tortoise_g","catbatg","coolblueg"]], + }, + "gravestones":{ + "rskip":True, + "file":"/images/cosmetics/gravestones/gravestone.png", + "rows":2, + "columns":10, + "type":"gravestone", + "matrix":[ + ["gravestonea","gravestone","xgravestone0","xgravestone1","xgravestone2","xgravestone3","xgravestone4",None,None,None], + [None,None,None,None,None,None,None,None,None,None], + ] + }, + "deepsea":{ + #"ignore":True, + "file":"/images/tiles/monsters/deep_sea_king.png", + "rows":1, + "columns":1, + "matrix":[ + ["deepsea"], + #["t1","test","t3","t4"], + ] + }, + "adversaries":{ + #"ignore":True, + "file":"/images/tiles/characters/adversaries.png", + "rows":2, + "columns":4, + "matrix":[ + ["a1","a2","a3","a4"], + ["a5","a6","a7","a8"], + ] + }, + "angel_wingless":{ + "file":"/images/tiles/characters/angel_wingless.png", + "rows":2, + "columns":4, + "matrix":[ + [None,"bangel",None,None], + [None,None,None,None], + ] + }, + "jpa":{ + "file":"/images/tiles/characters/winners_jpa.png", + "rows":2, + "columns":4, + "matrix":[ + [None,"greengreen",None,None], + [None,None,None,None], + ] + }, + "jpb":{ + "file":"/images/tiles/characters/winners_jpb.png", + "rows":2, + "columns":4, + "matrix":[ + [None,"pinkie",None,"purpo"], + [None,None,None,None], + ] + }, + "swa":{ + "file":"/images/tiles/characters/sheet_winnersa.png", + "rows":2, + "columns":4, + "matrix":[ + [None,"scarf",None,None], + [None,None,"proft","twig"], + ] + }, + "swb":{ + "file":"/images/tiles/characters/sheet_winnersb.png", + "rows":2, + "columns":4, + "matrix":[ + [None,None,None,"bobo"], + [None,None,None,None], + ] + }, + "collection1":{ + "file":"/images/tiles/characters/collection1.png", + "rows":2, + "columns":4, + "matrix":[ + ["daisy",None,None,None], + [None,None,"cunn","robbie"], + ] + }, + "collection2":{ + "file":"/images/tiles/characters/collection2.png", + "rows":2, + "columns":4, + "matrix":[ + ["sir",None,None,None], + [None,None,"naked",None], + ] + }, + # "collection3":{ + # "file":"/images/tiles/characters/collection3.png", + # "rows":2, + # "columns":4, + # "matrix":[ + # [None,None,None,None], + # [None,None,None,None], + # ] + # }, + "collectionx":{ + "file":"/images/tiles/characters/collectionx.png", + "rows":2, + "columns":4, + "matrix":[ + [None,"snow_angel",None,None], + ["creator",None,None,None], + ] + }, + "snowman":{ + "file":"/images/tiles/monsters/snowman.png", + "rows":1, + "columns":1, + "matrix":[ + ["snowman"], + ] + }, + "dragold":{ + "file":"/images/tiles/monsters/Dragold.png?v=2", + "rows":1, + "columns":1, + "matrix":[ + ["dragold"], + ] + }, + "bscorpion":{ + "file":"/images/tiles/monsters/blackscorpion.png", + "rows":1, + "columns":1, + "matrix":[ + ["bscorpion"], + ] + }, + "cobold":{ + "file":"/images/tiles/monsters/coboldProto.png", + "rows":1, + "columns":1, + "matrix":[ + ["cobold"], + ] + }, + "ligerx":{ + "file":"/images/tiles/monsters/liger_x.png", + "rows":1, + "columns":1, + "matrix":[ + ["ligerx"], + ] + }, + "tiger":{ + "file":"/images/tiles/monsters/tiger.png", + "rows":1, + "columns":1, + "matrix":[ + ["tiger"], + ] + }, + "slenderman":{ + "file":"/images/tiles/monsters/slenderman.png", + "rows":1, + "columns":1, + "matrix":[ + ["slenderman"], + ] + }, + "franky":{ + "file":"/images/tiles/monsters/frankenstein.png", + "rows":1, + "columns":1, + "matrix":[ + ["franky"], + ] + }, + "custom1":{ + "file":"/images/tiles/characters/custom1.png?v=11", + "rows":2, + "columns":4, + "matrix":[ + ["mwarrior2","mranger2","fpriest","trexw"], + ["showoffi","bpri","mmage","enterrr"] + ] + }, + "custom2":{ + "file":"/images/tiles/characters/custom2.png?v=4", + "rows":2, + "columns":4, + "matrix":[ + ["trexp",None,None,None], + ["konami","potiongirl","j2",None] + ] + }, + "custom3":{ + "file":"/images/tiles/characters/custom3.png?v=1", + "rows":2, + "columns":4, + "matrix":[ + ["spkc","spkw","bunny","bouncer"], + [None,None,None,None] + ] + }, + "jsonx":{ + "file":"/images/tiles/characters/others/jsonX.png", + "rows":1, + "columns":1, + "matrix":[ + ["jsonx"], + ] + }, + "mechagnome":{ + "file":"/images/tiles/monsters/mecha_gnome.png", + "rows":1, + "columns":1, + "matrix":[ + ["mechagnome"], + ] + }, + "harpy":{ + "file":"/images/tiles/monsters/harpy_b_1.png", + "rows":1, + "columns":1, + "matrix":[ + ["harpy"], + ] + }, + "harpy_fly":{ + "file":"/images/tiles/monsters/harpy_b_fly_1.png", + "rows":1, + "columns":1, + "matrix":[ + ["harpy_fly"], + ] + }, + "rharpy":{ + "file":"/images/tiles/monsters/harpy_a_1.png", + "rows":1, + "columns":1, + "matrix":[ + ["rharpy"], + ] + }, + "rharpy_fly":{ + "file":"/images/tiles/monsters/harpy_a_fly_1.png", + "rows":1, + "columns":1, + "matrix":[ + ["rharpy_fly"], + ] + }, + "ship1":{ + "file":"/images/tiles/characters/others/ship2.png", + "rows":1, + "columns":1, + "type":"animation", + "matrix":[ + ["ship"], + ] + }, + "newyear_tree":{ + "file":"/images/tiles/characters/others/newyear_tree.png", + "rows":1, + "columns":1, + "type":"animation", + "matrix":[ + ["newyear_tree"], + ] + }, + "bonus1":{ + "file":"/images/tiles/characters/bonus1.png", + "rows":2, + "columns":4, + "matrix":[ + [None,None,None,None], + [None,None,"mranger","holo"], + ] + }, + "military2":{ + "file":"/images/tiles/characters/military2.png", + "rows":2, + "columns":4, + "matrix":[ + [None,"nexus",None,None], + [None,None,None,None], + ] + }, + "military3":{ + "file":"/images/tiles/characters/military3.png", + "rows":2, + "columns":4, + "matrix":[ + [None,None,None,None], + [None,"asoldier",None,None], + ] + }, + "knights":{ + "file":"/images/tiles/characters/knights.png", + "rows":2, + "columns":4, + "matrix":[ + ["pknight",None,"baron",None], + [None,None,None,None], + ] + }, + "chara2":{ + "file":"/images/tiles/characters/chara2.png", + "rows":2, + "columns":4, + "matrix":[ + [None,None,"thief","fxrogue"], + [None,None,"generalg","prince"], + ] + }, + "chara3":{ + "file":"/images/tiles/characters/chara3.png", + "rows":2, + "columns":4, + "matrix":[ + [None,None,"franger","lilith"], + [None,None,"frogue",None], + ] + }, + "chara4":{ + "file":"/images/tiles/characters/chara4.png", + "rows":2, + "columns":4, + "matrix":[ + [None,"ftokener","grogue",None], + ["shadow","angel",None,None], + ] + }, + "chara6":{ + "file":"/images/tiles/characters/chara6.png", + "rows":2, + "columns":4, + "matrix":[ + ["mwarrior","mnwarrior","mwarrior_cool","fpaladin"], + ["fkid","redhead","mrogue","mpaladin_kid"] + ] + }, + "chara7":{ + "file":"/images/tiles/characters/chara7.png", + "rows":2, + "columns":4, + "matrix":[ + ["frozenrogue",None,"fmage",None], + ["marven","fwarrior","blingbling","lionsuit"] + ] + }, + "chara8":{ + "file":"/images/tiles/characters/chara8.png", + "rows":2, + "columns":4, + "matrix":[ + ["pink","splithair","wizard","pwincess"], + ["greencap",None,None,None] + ] + }, + "automatron":{ + "file":"/images/tiles/characters/automatron2.png", + "rows":2, + "columns":4, + "matrix":[ + ["target_a500","target_a750","target_r500","target_r750"], + ["target_ar900","target_ar500red",None,"target"] + ] + }, + "npc1":{ + "file":"/images/tiles/characters/npc1.png", + "rows":2, + "columns":4, + "matrix":[ + ["gcitizen","oldcitizen",None,None], + ["fisherman",None,"gemmerchant",None] + ] + }, + "npc3":{ + "file":"/images/tiles/characters/npc3.png", + "rows":2, + "columns":4, + "matrix":[ + [None,"mailman",None,None], + [None,None,None,None] + ] + }, + "npc4":{ + "file":"/images/tiles/characters/npc4.png", + "rows":2, + "columns":4, + "matrix":[ + ["lady1","lady2","gabrielle","gabriella"], + ["lady3",None,"lady4",None] + ] + }, + "npc5":{ + "file":"/images/tiles/characters/npc5.png", + "rows":2, + "columns":4, + "matrix":[ + ["npcc","lmerchant","mmerchant","purplelady"], + [None,None,None,None] + ] + }, + "npc6":{ + "file":"/images/tiles/characters/npc6.png", + "rows":2, + "columns":4, + "matrix":[ + ["showoff","fmerchant","npc63","llady"], + ["renaldo",None,"lucy",None] + ] + }, + "dwarf2":{ + "file":"/images/tiles/characters/dwarf2.png", + "rows":2, + "columns":4, + "matrix":[ + [None,None,None,None], + ["fancyd",None,None,None] + ] + }, + "tristone_m":{ + "file":"/images/tiles/characters/tristone_m.png", + "rows":2, + "columns":4, + "matrix":[ + ["tm_red","tm_brown","tm_yellow","tm_green"], + ["tm_gray","tm_blue","tm_purple","tm_white"] + ] + }, + "tristone_f":{ + "file":"/images/tiles/characters/tristone_f.png", + "rows":2, + "columns":4, + "matrix":[ + ["tf_pink","tf_blue","tf_green","tf_orange"], + ["tf_purple",None,None,None] + ] + }, + "mystics":{ + "file":"/images/tiles/characters/mystics.png", + "rows":1, + "columns":4, + "matrix":[ + ["mm_blue","mf_blue","mm_yellow","mf_yellow"], + ] + }, + "creatures1":{ + "file":"/images/tiles/monsters/creatures1.png", + "rows":1,"columns":4, + "matrix":[[None,None,"mummy","booboo"]], + }, + "creatures2":{ + "file":"/images/tiles/monsters/creatures2.png", + "rows":2,"columns":4, + "matrix":[ + ["oneeye",None,None,None], + [None,None,None,None] + ], + }, + "jrpumpkins":{ + "file":"/images/tiles/monsters/jrpumpkins.png", + "rows":1,"columns":2, + "matrix":[["jr","greenjr"]], + }, + "chara5":{ + "file":"/images/tiles/characters/chara5.png", + "rows":2, + "columns":4, + "matrix":[ + [None,None,None,"thehelmet"], + [None,"mpriest","reaper","goblin"] + ] + }, + "chests":{ + "file":"/images/tiles/items/chests.png?v=2", + "rows":2, + "columns":12, + "matrix":[ + ["chestp","chest1",None,None,"chest2",None,None,"chest3",None,None,"chest4",None], + [None,"chest5",None,None,"chest6",None,None,"chest7",None,None,"chest8",None] + ], + "type":"v_animation", #new logic [02/07/18] + }, + "animationc":{ + "file":"/images/tiles/characters/animationc.png?v=4", + "rows":8, + "columns":4, + "type":"animation", + "matrix":[ + ["santa","pvptokens",None,None], + ["brewingwitch","funtokens",None,None], + ["test_a",None,"test_b",None], + [None,None,None,None], + [None,None,None,None], + [None,None,None,None], + [None,None,None,None], + [None,None,None,None] + ] + }, + "animation1":{ + "file":"/images/tiles/characters/animation1i.png", + "rows":8, + "columns":4, + "type":"animation", + "matrix":[ + [None,"pflow","sidesword","flute"], + [None,"fancypots","pike","doublesword"], + [None,None,"daggers","hammer"], + [None,None,"swdagger","miniharp"], + ["bow","spell","powerup","magic"], + ["bow2","sth1","tricks","yellowlady"], + ["praise","drunk","hairs","yellowwarrior"], + ["femalesword","femalelongsword","scrolls","double-axe"] + ] + }, + "animation2":{ + "file":"/images/tiles/characters/animation2.png", + "rows":8, + "columns":4, + "type":"animation", + "matrix":[ + ["armorguy","zengirl",None,None,], + [None,None,None,None,], + [None,None,None,None,], + [None,"goblin_a",None,None,], + [None,None,None,None,], + [None,None,None,None,], + [None,None,None,None,], + [None,None,None,None,] + ] + }, + "animation3":{ + "file":"/images/tiles/characters/animation3.png", + "rows":8, + "columns":4, + "type":"animation", + "matrix":[ + [None,None,None,None,], + [None,None,None,None,], + [None,None,None,None,], + ["geekgirl",None,None,None,], + [None,None,None,None,], + [None,"exchanger",None,None,], + [None,None,None,None,], + [None,"newupgrade",None,None,] + ] + }, + "elementals":{ + "file":"/images/tiles/monsters/elemental.png", + "rows":2, + "columns":4, + "matrix":[ + ["welemental","felemental","nelemental","eelemental"], + [None,None,None,None] + ] + }, + "dknight1":{ + "skip":1, + "file":"/images/tiles/monsters/monster_dknight1.png", + "rows":1,"columns":1,"matrix":[["dknight1"]] + }, + "dknight2":{ + "file":"/images/tiles/monsters/monster_dknight2.png", + "rows":1,"columns":1,"matrix":[["dknight2"]] + }, + "fairies":{ + "file":"/images/tiles/monsters/fairies.png", + "rows":2, + "columns":4, + "matrix":[ + ["greenfairy","redfairy","bluefairy","darkfairy"], + [None,None,None,None] + ] + }, + "monsterbird1":{ + "file":"/images/tiles/monsters/monster_bird1.png", + "rows":1,"columns":1,"matrix":[["bigbird"]] + }, + "monsterbird2":{ + "skip":1, + "file":"/images/tiles/monsters/monster_bird2.png", + "rows":1,"columns":1,"matrix":[["blackbird"]] + }, + "monsterbird3":{ + "skip":1, + "file":"/images/tiles/monsters/monster_bird3.png", + "rows":1,"columns":1,"matrix":[["turkeybird"]] + }, + "boar":{ + "file":"/images/tiles/monsters/monster_boar.png", + "rows":1,"columns":1,"matrix":[["boar"]] + }, + "cacto":{ + "skip":1, + "file":"/images/tiles/monsters/monster_cacto.png", + "rows":1,"columns":1,"matrix":[["cactusman"]] + }, + "rudolph":{ + "file":"/images/tiles/monsters/rudolphi.png", + "rows":1,"columns":1,"matrix":[["rudolph"]] + }, + "elk":{ + "skip":1, + "file":"/images/tiles/monsters/monster_elk.png", + "rows":1,"columns":1,"matrix":[["elk"]] + }, + "golem1":{ + "skip":1, + "file":"/images/tiles/monsters/monster_golem1.png", + "rows":1,"columns":1,"matrix":[["stone_golem"]] + }, + "golem2":{ + "skip":1, + "file":"/images/tiles/monsters/monster_golem2.png", + "rows":1,"columns":1,"matrix":[["tree_golem"]] + }, + # "lich":{ + # "file":"/images/tiles/monsters/monster_lich.png", + # "rows":1,"columns":1,"matrix":[["lich"]] + # }, + "lizardman1":{ + "skip":1, + "file":"/images/tiles/monsters/monster_lizardman1.png", + "rows":1,"columns":1,"matrix":[["greenlizardman"]] + }, + "lizardman2":{ + "skip":1, + "file":"/images/tiles/monsters/monster_lizardman2.png", + "rows":1,"columns":1,"matrix":[["redlizardman"]] + }, + "stompy":{ + "file":"/images/tiles/monsters/stompy3.png", + "rows":1,"columns":1,"matrix":[["stompy"]] + }, + "minotaur":{ + "skip":1, + "file":"/images/tiles/monsters/monster_minotaur.png", + "rows":1,"columns":1,"matrix":[["minotaur"]] + }, + "phoenix":{ + "file":"/images/tiles/monsters/monster_phoenix.png", + "rows":1,"columns":1,"matrix":[["phoenix"]] + }, + "raptor1":{ + "skip":1, + "file":"/images/tiles/monsters/monster_raptor1.png", + "rows":1,"columns":1,"matrix":[["greenlizard"]] + }, + "raptor2":{ + "skip":1, + "file":"/images/tiles/monsters/monster_raptor2.png", + "rows":1,"columns":1,"matrix":[["redlizard"]] + }, + "grinch":{ + "file":"/images/tiles/monsters/grinch.png", + "rows":1,"columns":1,"matrix":[["grinch"]] + }, + "treant":{ + "skip":1, + "file":"/images/tiles/monsters/monster_treant.png", + "rows":1,"columns":1,"matrix":[["treant"]] + }, + "wolf1":{ + "file":"/images/tiles/monsters/monster_wolf1.png", + "rows":1,"columns":1,"matrix":[["wolf"]] + }, + "wolf2":{ + "file":"/images/tiles/monsters/monster_wolf2.png", + "rows":1,"columns":1,"matrix":[["wolfie"]] + }, + "json":{ + "file":"/images/tiles/monsters/json.png", + "rows":1,"columns":1,"matrix":[["json"]] + }, + "mcustom1":{ + "file":"/images/tiles/monsters/custom1.png?v=6", + "rows":2, + "columns":4, + "matrix":[ + ["cgoo","crabx","bbpompom","gscorpion"], + ["osnake","mole","xscorpion","arcticbee"], + ] + }, + "mcustom2":{ + "file":"/images/tiles/monsters/custom2.png?v=5", + "rows":2, + "columns":4, + "matrix":[ + ["pinkgooi","pinkgoo",None,None], + ["goldenbat","wabbit",None,"stoneworm"], + ] + }, + "goos":{ + "file":"/images/tiles/monsters/goos.png", + "rows":2, + "columns":5, + "matrix":[ + ["goo0","goo1","goo2","goo3","goo4"], + ["goo5","goo6","goo7","goo8","gooD"] + ] + }, + "monsters1":{ + "file":"/images/tiles/monsters/monster1.png", + "rows":2, + "columns":4, + "matrix":[ + ["goo","rat","spider","scorpion"], + ["bloodworm","snake","bee","bat"] + ] + }, + "animals1":{ + "file":"/images/tiles/monsters/animals1.png", + "rows":2, + "columns":4, + "matrix":[ + ["puppy1","puppy2","puppy3","puppy4"], + ["kitty1","kitty2","kitty3","kitty4"], + ] + }, + "animals2":{ + "file":"/images/tiles/monsters/animals2.png", + "rows":2, + "columns":4, + "matrix":[ + [None,None,None,None], + ["porcupine",None,None,None], + ] + }, + "birds1":{ + "file":"/images/tiles/monsters/birds1_modded.png", + "rows":2, + "columns":4, + "matrix":[ + ["hen","rooster",None,None], + [None,None,None,None], + ] + }, + "goblinos":{ + "file":"/images/tiles/monsters/goblinos.png", + "rows":2, + "columns":4, + "matrix":[ + [None,None,"gredpro","ggreenpro"], + [None,None,"gpurplepro","gbluepro"], + ] + }, + "gking":{ + "file":"/images/tiles/monsters/goblinkingb.png", + "rows":1,"columns":1,"matrix":[["gking"]] + }, + "monsterc6":{ + "file":"/images/tiles/monsters/monsterc6.png?v=2", + "rows":2, + "columns":4, + "matrix":[ + ["prat","pppompom","spompom","mighty"], + ["slither","deadgob","pinkgoblin","red"] + ] + }, + "tinyfairies":{ + "file":"/images/tiles/monsters/tinyfairies.png", + "rows":2, + "columns":4, + "matrix":[ + ["tinyp",None,None,None], + [None,None,None,None] + ] + }, + "monsterc2":{ + "file":"/images/tiles/monsters/monsterc2.png", + "rows":2, + "columns":4, + "matrix":[ + [None,"ent",None,None], + [None,None,None,None], + ] + }, + "robots":{ + "file":"/images/tiles/monsters/robots.png", + "rows":2, + "columns":4, + "matrix":[ + [None,None,"zapper0",None], + [None,None,None,"fieldgen0"], + ] + }, + "mage":{ + "file":"/images/tiles/monsters/mage.png", + "rows":2, + "columns":4, + "matrix":[ + ["xmagefz","xmagefi","xmagen","xmagex"], + [None,None,None,None], + ] + }, + "monsters2":{ + "file":"/images/tiles/monsters/monster2.png?v=3", + "rows":2, + "columns":4, + "matrix":[ + ["crab","tortoise","squig","croc"], + ["frog","squigtoad","poisio","armadillo"] + ] + }, + "monsters3":{ + "file":"/images/tiles/monsters/monster3c.png", + "rows":2, + "columns":4, + "matrix":[ + ["minimush","midimush","plantoid","uglyplant"], + ["iceroamer","fireroamer","chestm","chestx"] #"trapchest1","trapchest2" + ] + }, + "monsters4":{ + "file":"/images/tiles/monsters/monster4.png", + "rows":2, + "columns":4, + "matrix":[ + ["ghost",None,None,"skeletor"], + [None,None,None,None], + ] + }, + "vampires":{ + "file":"/images/tiles/monsters/vampire2d.png", + "rows":2, + "columns":4, + "matrix":[ + ["mvampire","fvampire",None,None], + [None,None,"vbat",None], + ] + }, + "mrpumpkin":{ + "file":"/images/tiles/monsters/mr_pumpkin.png", + "rows":1, + "columns":1, + "matrix":[ + ["mrpumpkin"], + ] + }, + "cbee":{ + "file":"/images/tiles/monsters/cbee.png", + "rows":1, + "columns":1, + "matrix":[ + ["cutebee"], + ] + }, + "icegolem":{ + "file":"/images/tiles/monsters/iceGolem.png", + "rows":1, + "columns":1, + "matrix":[ + ["icegolem"], + ] + }, + "mrgreen":{ + "file":"/images/tiles/monsters/green.png", + "rows":1, + "columns":1, + "matrix":[ + ["mrgreen"], + ] + }, + "emblems":{ + "file":"/images/sprites/emblems/emblems.png?v=6", + "type":"emblem", + "rows":2, + "columns":10, + "matrix":[ + ["c1","c2","c3","c4","b1","r1","rr1","dp1",None,None], + ["m1","m2","m3","m4","b2","br1","o1","j1",None,None], + ] + }, + +} +bodysets=[ + #skin + ["sskin1","skin","small",8,"/images/cosmetics/skins/sskin1.png"], + ["mskin1","skin","normal",8,"/images/cosmetics/skins/mskin1.png"], + ["lskin1","skin","large",4,"/images/cosmetics/skins/lskin1.png"], + #body + ["sbody1","body","small",5,"/images/cosmetics/armors/sbody1.png?v=4"], + ["mbody1","body","normal",8,"/images/cosmetics/armors/mbody1.png?v=2"], + ["mbody2","body","normal",8,"/images/cosmetics/armors/mbody2.png?v=6"], + ["mbody3","body","normal",8,"/images/cosmetics/armors/mbody3.png?v=3"], + ["mbody4","body","normal",8,"/images/cosmetics/armors/mbody4.png?v=3"], + ["mbody5","body","normal",8,"/images/cosmetics/armors/mbody5.png?v=3"], + ["mbody6","body","normal",3,"/images/cosmetics/armors/mbody6.png"], + #armor + ["sarmor1","armor","small",8,"/images/cosmetics/armors/sarmor1.png?v=2"], + ["sarmor2","armor","small",4,"/images/cosmetics/armors/sarmor2.png?v=2"], + ["marmor1","armor","normal",8,"/images/cosmetics/armors/marmor1.png?v=2"], + ["marmor2","armor","normal",8,"/images/cosmetics/armors/marmor2.png?v=3"], + ["marmor3","armor","normal",8,"/images/cosmetics/armors/marmor3.png?v=2"], + ["marmor4","armor","normal",8,"/images/cosmetics/armors/marmor4.png?v=4"], + ["marmor5","armor","normal",8,"/images/cosmetics/armors/marmor5.png?v=4"], + ["marmor6","armor","normal",8,"/images/cosmetics/armors/marmor6.png?v=3"], + ["marmor7","armor","normal",8,"/images/cosmetics/armors/marmor7.png?v=2"], + ["marmor8","armor","normal",8,"/images/cosmetics/armors/marmor8.png?v=2"], + ["marmor9","armor","normal",8,"/images/cosmetics/armors/marmor9.png?v=2"], + ["marmor10","armor","normal",8,"/images/cosmetics/armors/marmor10.png"], + ["marmor11","armor","normal",8,"/images/cosmetics/armors/marmor11.png"], + ["marmor12","armor","normal",6,"/images/cosmetics/armors/marmor12.png"], + ["larmor1","armor","large",2,"/images/cosmetics/armors/larmor1.png"], + #character + ["lchar1","character","large",8,"/images/all_characters/lchar1.png"], + ["mchar16","character","normal",8,"/images/all_characters/mchar16.png"], + ["schar7","character","small",8,"/images/all_characters/schar7.png"], + ["xschar2","character","xsmall",8,"/images/all_characters/xschar2.png"], + ["xxschar2","character","xxsmall",8,"/images/all_characters/xxschar2.png"], +] + +for s in bodysets: + sprites[s[0]]={ + "file":s[4], + "type":s[1], + "size":s[2], + "rows":2, + "columns":4, + "matrix":[ + [None,None,None,None], + [None,None,None,None], + ] + } + last=0 + nmap={0:"a",1:"b",2:"c",3:"d",4:"e",5:"f",6:"g",7:"h"} + for i in xrange(2): + for j in xrange(4): + if last +show_json(data); + + +

Paragraph

+ +

item_grade <- reference label

+ +

G.classes <- json label

+ +

Move There <- execute label

+ +

"hit" <- display

+ +

Hint: <- hint

+ +
+ +
Left bottom corner indicates the item level
+ +Here[GitHUB] + +

+ The snowman spawns every hour. Snowman is a collaborative boss, everyone who participates gets a reward. You can only deal 1 damage to Snowman - better participate at each spawn for the common good! +

+ + \ No newline at end of file diff --git a/docs/__init__.py b/docs/__init__.py new file mode 100644 index 0000000..fef66b5 --- /dev/null +++ b/docs/__init__.py @@ -0,0 +1 @@ +#!/usr/bin/env python \ No newline at end of file diff --git a/docs/articles/.DS_Store b/docs/articles/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/docs/articles/.DS_Store differ diff --git a/docs/articles/1-easy.html b/docs/articles/1-easy.html new file mode 100644 index 0000000..26e386e --- /dev/null +++ b/docs/articles/1-easy.html @@ -0,0 +1,14 @@ +

[Learning Coding is Easy]

+ +

Before you start the journey, let me assure you that learning how to Code is super easy, anyone can do it, you can easily do it, just stick along :)

+ +{#

Programming Languages are a lot like Microsoft Word, there are a lot of itsy bitsy features, imagine seeing Microsoft Word for the first time, all those functionalities, interfaces that you don't know what to do.. They would intimidate you, right? Yes it would. But anyone can use a text editor, you just type stuff, maybe make it bold, italic, If you are a pro at it, maybe align the text a bit, and that's it! <- Well coding is a lot like that too!

+ +

If you are not a coder, all the things that you don't know must be scaring you, scaring you so much that you could be believing that you can't do it. Well, know this: Things you don't know are a lot like the stupid functionalities Microsoft Word has, no normal person is going to use them, you don't need to know them, you can write a masterpiece novel and not know anything about them.

#} + +

Coding is a lot like using a Text Editor, or a Calculator, it's just a tool to help you automate, to make computers do things for you, and in Adventure Land, you can make Code play the game for you :)

+ +

The Secret: You don't need to learn everything about a programming language, you just need to learn very little, and the rest, you can Google!

+ +

Adventure Land is written in Javascript, and you'll learn Javascript.

+ diff --git a/docs/articles/2-javascript.html b/docs/articles/2-javascript.html new file mode 100644 index 0000000..fc0724a --- /dev/null +++ b/docs/articles/2-javascript.html @@ -0,0 +1,19 @@ +

Using Javascript is as simple as:

+ +
+a=5; +b=7; +c=a*b; +alert(c); +
+ +

As you probably guessed, we used Javascript like a Calculator, the above program alerts "35".

+ +

Some more explanation:

+ +
+a=5; // "a" is now a variable that holds the value 5 +b=7; // "b" is now a variable that holds the value 7 +c=a*b; // "c" is a new variable, it's calculated as 5x7 - it's equal to 35, it's the value it's holding now +alert(c); // "alert" is a function that makes the browser pop up whatever you put in there, annoyingly, you probably saw them before :) +
\ No newline at end of file diff --git a/docs/articles/3-security.html b/docs/articles/3-security.html new file mode 100644 index 0000000..7120fc6 --- /dev/null +++ b/docs/articles/3-security.html @@ -0,0 +1,40 @@ +

[Security First!]

+ +

In our daily lives, we run codes, programs, games - all from different resources. And we assume these will be safe, and others will make sure they are safe.

+ +

You have no other choice, as you can't see or inspect everything your computer runs.

+ +

However on Adventure Land you have the chance to quickly glance at every line of a Code you'll copy-paste from a fellow player, and you must!

+ +

Doesn't matter if you are a Coder or not, it's usually easy to spot malicious Code!

+ +

Here's a quick Checklist:

+ +
+	1. Make sure there are no external links inside the Code
+	2. Make sure the Code is simple, understandable
+	3. Make sure the Code doesn't have anything funky
+	4. If you are not sure, ask someone you trust to make sure
+
+ +

If you can't be sure, you must-not! copy-paste Code from someone else, and run it!

+ +

One example of a bad / malicious Code:

+ +
+parent.$("body").append(" + + +{%endblock%} \ No newline at end of file diff --git a/htmls/drmfree.html b/htmls/drmfree.html new file mode 100644 index 0000000..33628b3 --- /dev/null +++ b/htmls/drmfree.html @@ -0,0 +1,120 @@ + + + + DRM-Free + + + + + + + + + + + {% if not domain.is_sdk %} + + {% endif %} + + +
+
The Game is DRM-Free. [02/05/19]
+ +
+

And yes, it makes the game open to abuse, it's a sacrifice. This issue comes up a lot, so I decided to write an article about it, explaining the reasoning, potential loopholes, potential issues - and give insight.

+ +
+

What is DRM-Free? DRM means Digital Rights Management - DRM-Free means the game intentionally doesn't try to enforce that you actually purchased the game so that you can play the game. Why? Let's say you buy an old EA game from Steam, you open the game, the game not only requires Steam DRM, but it also forces you to create an EA account, verify the CD-Key, each time you play the game, enter the EA account's cryptic password you forgot and so on. Imagine all the bad karma they receive. Anyone who opens the game, would instantly hate everyone involved with it. Now imagine a GOG.com game, no DRM, you can purchase it once, keep it on your computer, and in 30 years, when potentially the seller of the game, or maker of the game is no more, you can still play it. How beautiful. Good karma.

+ +
+

What DRM-Free isn't? It's not free. So even though you can play the game without purchasing, or worse yet, you purchase the game, refund it, still keep playing it. Doesn't mean that it's a free game. It's about your own morals.

+ +
+

A Sacrifice Making a game DRM-Free is a sacrifice, those who abuse such a system, both hurt the game makers and worse yet hurt those who play the game. If you are a game maker reading this. I suggest you DRM your game, or at least give the illusion that you DRM'ed your game and things can be DRM'ed (they can't).

+ +
+

Some Technical Reasons Steam's DRM system is strong, so if the game was on Steam-only, it could've been DRM'ed, I'm not saying I'd DRM the game, but it could be done. As a result you would occasionally get wiped out if there was a problem with Steam auth, but it would be possible. However, the game is already on Mac App Store, and even from my own analysis, the Apple's auth system is undocumentedly weak and abusable, there are easy to discover loopholes that enable you to multiply invoices, infinitely repeat authorizations and so on (manually patched for our game). I also consider putting the game on GOG one day, and I'd do it without DRM, or sell the game from other sources. I don't want to deal with each of their DRM/auth systems individually, so DRM-free it is. Also: Those who play Adventure Land are all very technically capable, so better to have no DRM, rather than to have a DRM and get it busted and having to reply to all the messages related to that, why it happens, why it can't be prevented and so on, so this scenario is simpler

+ +
+

What DRM is good-for, and how we use it! Not DRM, but a "Purchase Authorization" is actually a very valuable service, so far, only Steam provides it in a non-easily-spoofable and dynamic manner, so things like "IP Limits Bypassing" is possible thanks to Steam. If you purchased the game from Steam, you can play the game with 10 friends on the same network. For a single player game, "Purchase Authorization"=DRM - but for an online game, "Purchase Authorization"="Abuse Protection". Otherwise, if CLI gameplay was allowed without purchase authorization, one could easily rent 100 virtual servers and potentially ruin my life.

+ +
+

Why let Multiple Account Signups? This comes up a lot, a player registers to the game with his/her email. Logs out, registers again. Then sends an email or discord message saying: "I found a very critical issue" - which I assume to be an endgame loophole, but 99% of the time ends up being this issue. The main reason it's allowed: You can sign-up with the wrong email. Logout, correct your email, continue with the new account, with the intention of moving your old characters to your new account if you created any. You could change your email, forgot the old email details, re-signup with your new email to contact hello@adventure.land later on to recover your old account. Or maybe, 2 players are playing with different accounts, but from the same computer / one purchased copy. It's a valid scenario. TL;DR: The scenarios are endless. TL;DR-WHY: To let players freely make account changes or corrections

+ +
+

(Bonus) The Free Mis-Perception Whenever a regular players discovers that the game can be abused and can be played without purchasing (or purchase + refund), they instantly assume the game is free (Like 70% of players does this) and either start approaching the game in a negative manner, or expect the game to provide something more to those who verifiably purchased the game. Thankfully I discovered this phenomenon early on. Otherwise, originally, the game intended to let anyone sign up freely, but only for educational use, so kids who don't have money to purchase the game, could play the game anyway, and maybe learn coding. But early trials showed that this was also perceived as the game being free, and caused serious backlash and negative feedback (potential negative reviews and so on) - so disabled this feature before Steam release.

+ +
+

(Bonus) Intentions and Analysis I do intend to make things more strict in the future. I don't judge the 70% who have a different world view. I'm here to serve as a developer. And honestly, making things more strict => more money => a better quality game. So in a way it's nice that the majority actually wants more restrictions. It won't be DRM-level, but abuse protection will definitely get more strict. I'm also glad I wasn't naive enough to launch the game with a "Free Educational Sign-Up". I now suspect that it would just halve the sales and enrage the general playerbase. It's also important to note that Adventure Land has the most positive playerbase any player has ever seen. Everyone helps each other, there's minimal flaming and so on. So if you are a game developer reading this, the logical thing to do is to just DRM your game, restrict your game and move on with your life, it seems to me that no one cares about the sacrifices, they just hurt you and your game/community.

+ +
+

Adventure Land will hopefully stay DRM-Free, I'll try to keep it as it is, but it doesn't mean it lets any account do whatever it wants. The "Limits Enforcer" system will get more strict in the future. Especially if CLI-gameplay is ever officially introduced. Also it's likely that the game has responses in place that give delayed or periodic responses. So if you are a fresh tester, you'll likely not discover them until you attempt to run a scheme 24/7.

+ +
+
Wizard
+
+ + + \ No newline at end of file diff --git a/htmls/email.html b/htmls/email.html new file mode 100644 index 0000000..6a8d0b0 --- /dev/null +++ b/htmls/email.html @@ -0,0 +1,23 @@ + + + + +
+ {% if purpose == "password" %} + To Reset Your Password Please Visit:

+ {{url}}

+ If you haven't initiated this routine, please ignore this email. + {% elif purpose == "verification" %} +
To Verify Your Email
+ {{url}} +
Some Suggestions!
+
+
+
1) Check out the GUIDE, you can type /guide in chat
+
2) Check out the CODE, you don't need to be a programmer to use CODE!
+
3) Join us on Discord, the game is in active development, there is an active and helpful community on Discord, for gameplay, trade and coding help!
+
4) You are able to play with multiple characters simultaneously, you can have 3 regular characters and a merchant, freely, for as long as you want!
+
+
+ {% endif %} +
\ No newline at end of file diff --git a/htmls/executor.html b/htmls/executor.html new file mode 100644 index 0000000..36b4556 --- /dev/null +++ b/htmls/executor.html @@ -0,0 +1,55 @@ + + + + + {% if domain.electron%}{% endif %} + + + + + + +
Initiating
+ +
x
+ + \ No newline at end of file diff --git a/htmls/index.html b/htmls/index.html new file mode 100644 index 0000000..ae15faa --- /dev/null +++ b/htmls/index.html @@ -0,0 +1,362 @@ + + + + {{domain.name}} + {% if domain.electron and domain.no_html %}{% endif %} + + + + + + + + + + + + + {% if not domain.no_graphics and 0 %} {% endif %} + {% if not domain.no_graphics and 1 %} {% endif %} + {% if not domain.no_graphics %} {% endif %} + {% if not domain.no_graphics and 0 %} {% endif %} + + + {% if not domain.no_html %} + + + + + {% endif %} + + + {# #} + {%if 0%} {%endif%} + {% if not domain.no_html %} + + + + + + + {% else %} + + {% endif %} + + + + + + + + {% if user.admin %}{% endif %} + {% if not domain.no_html %} {% endif %} + + {% include "htmls/base_script.html" %} + {% if not domain.no_html %} {% endif %} + {% if domain.no_html %} + + {% endif %} + {% if domain.recording_mode %} + + {% endif %} + + + {% if domain.no_html %} +
{{domain.character_name|upper}}
+
+ 0% +
+ {% else %} +
{% if not user %}{% include "htmls/contents/login.html" %}{%else%}{% include "htmls/contents/selection.html" %}{% endif %}
+ {# {% include "htmls/contents/guide.html"%} #} + {% include "htmls/contents/hardcore_guide.html"%} + {% include "htmls/contents/booster_howto.html"%} + {% include "htmls/contents/shells_info.html"%} + {% include "htmls/contents/keymap_guide.html"%} + + + + + + + + + + + +
+
+ +
+ + +
+
+
+
+
?
+
+ + + + +
DOCS
+
+
+
+
+
+
+
+
+
+
+
+ + {#
Wizard.js
+
ENGAGE
+ #} + +
+
+
Save As
+
+
Load
+
+
Character
+
+
Default Code
+
Engage!
+ +
+
+
+ + + + {% include "htmls/contents/settings.html" %} + + {##} + {% endif %} + + {%for k in domain.imagesets %} + + {% endfor %} + + + \ No newline at end of file diff --git a/htmls/linux.html b/htmls/linux.html new file mode 100644 index 0000000..3ebbbcd --- /dev/null +++ b/htmls/linux.html @@ -0,0 +1,103 @@ + + + + Linux: How to Make it Work + + + + + + + + + + + {% if not domain.is_sdk %} + + {% endif %} + + +
+

Linux: Common and Distro-Specific Issues

+ +

Adventure Land uses Electron. When you stumble onto an issue, you can google the issue by combining error phrases with "electron". Sadly each distro and setup has it's own various issues, but they are usually easy to solve.

+ +
+
Black or Blank Screen
+

First thing to try is to find the Steam games directory and simply run Adventure Land from the command line. For some reason it usually works. You can also try the --disable-gpu flag. If the game works when you disable the GPU, the issues are most likely related to GPU/driver issues. When you run the game from command line once, make sure to go back and test it from Steam again. Some players reported the game starting to work from Steam, only after they ran it from command line once. Mysterious.

+
+ +
+
Disable Steam Overlay Modification
+

Find main.js - It's the Electron code/logic of Adventure Land - comment out the line with "app.commandLine.appendSwitch("in-process-gpu");" - this is needed to render the Steam overlay, but it can also cause issues. Currently it's disabled by default.

+
+ +
+
[07/03/19]: version `ZLIB_1.2.9' not found (required by /nix/store/parrh56r6sr4ccp9ypl4sh7h5b19rijg-libpng-apng-1.6.36/lib/libpng16.so.16)
+

User "foldM_" on Discord stumbled onto this issue on NixOS - his solution was to set Steam to launch the game with: LD_LIBRARY_PATH=/lib:$LD_LIBRARY_PATH %command% (from Steam's Game Properties > Launch Options)

+
+ +

If you find and solve an issue, or just stumble onto an issue you can't solve, please email hello@adventure.land with details

+ +
+ + + \ No newline at end of file diff --git a/htmls/logs.html b/htmls/logs.html new file mode 100644 index 0000000..4456203 --- /dev/null +++ b/htmls/logs.html @@ -0,0 +1,1137 @@ + + + + Development <!--Logs-->Blog* + + + + + + + + + + + {% if not domain.is_sdk %} + + {% endif %} + + +
+ + + + + {# + [19/12/19]: Grinch made babies cry today :/ + #} + + {#
+
[14/08/19]: Signs
+

Can't say that the last few months were super productive, in fact, they were only minimally productive, there's progress, but not enough to shape the game fast enough.

+

Back in 2015, before I started working on Adventure Land, I decided to cross an item off my bucket list, which was to gather the best gaming pc I could - I always wanted to have a high performance gaming system. After all the hurdles, one night, everything was finally coming together, it was time to update the motherboard's bios. I figured, since there was no power outage in the last 2 years, and the electrical infrastructure now seemed pretty reliable, it was a safe operation. It takes 30 seconds anyway. Started the bios update, and around 20 seconds later, right when it was just passing 60%, I sat in complete darkness, the power was gone... motherboard corrupted. A minute later, the power was back on - no outages again for a long long time.

+

Back then, I attributed this experience to my extreme luck, but later on, I started seeing it more as a sign. That gaming system ended up being both a time and money pit, affected my life significantly, possibly put me in a much worse course.

+

On 29th of July, I was outside on empty fields with my dog, there's a very serene place nearby, lots of hills, natural water and so on. It was around 19 pm, I started thinking about the power outage, kinda wished I received another sign like that, wishing it would pull me out of this endless loop of procrastination vs. progress.

+

This was the day and exact time when a player found a Sucker Punch, 6 times in a row, a one in a million chance proc'ing 6 times in a row, an impossibility. Suffice to say, I choose to see this as a sign too. To get things back on track.

+

Turns out, if you combine the -25% Luck from the non-verified email status, and the -85% Luck from the steam/mac authorization failure debuff, it dropped the Luck multiplier below 0, and caused the game to drop everything possible from monsters, but still, since this loophole was introduced months ago, it's quite a coincidence that it happened when it happened.

+

I was finally able to get things back on track some days ago, ultimately, I ended up eliminating all the sources of procrastination from my life. The last one was watching an excessive amount of movies and tv shows. Currently I either work on the game, or spend time outside/exercise. So even if I'm not in the mood to work, I end up exercising instead, so it's a win win scenario.

+
#} + +
+
[28/02/19]: Summer Mode On
+

Finally mostly healed, took some time off last week. Last 2 weeks was harsh, but I believe I have a clear vision of what to do now. Going to completely revamp the initial player experience, add a unique, code assisted tutorial that accompanies the player when they first start playing. I'm still very much anti-(must complete tutorial) and anti-(starting zone), so this tutorial will be unintrusive and optional. Each step will both teach the player of the things they can do in-game, and show them how it's done in Code. Use smart_move to move them from place to place, on their command.

+

Today I started working 8 hours a week again, the weather is better, my energy is up, I believe I can keep it up for the months to come. With this new tutorial, ongoing code documentation and changes, pressing need to introduce new game content, I certainly need the strict work schedule.

+
+ +
+
[05/02/19]: Steam Release and a New Era
+

Never expected such a successful release. Steam is truly a one of a kind platform. For example the game sold 5-6 copies on Mac App Store, and as far as I guess, they were all direct sales and not discovery sales. But with Steam, the game started selling 30-40 copies a day. Without any promotional effort, and for an indie game, I find these numbers to be extraordinary. If you are reading this, consider making a unique, alluring, single player game for Steam (like a unique rogue-like), it would be the optimal scenario. Multiplayer games are always challenging.

+

If it goes like this, and I hope it does, it seems Adventure Land will be cash positive. I've been burning through my savings for the last 4 years, going through $1-2K every month. I really look forward to being profitable once again. Thanks to such a positive outcome, I feel like I'm healing faster too, I do believe the immune system functions better with high motivation.

+

Current plan is to address the initial experience first. While the feedback has been positive until now, I believe initial players are struggling, they need more guidance. Especially with CODE. I really hate games with tutorials. But it's being requested too, not sure what to do about it yet. Adventure Land is a do whatever you want type of game. Not everyone likes it. Some want a tutorial and strict things to do. Some want purpose. First stage will likely be improving the CODE documentation and guiding new players through the process. After it's done, might introduce the game tutorial through code too, providing small snippets to walk the player through simple tasks.

+

Meanwhile launched the Chinese New Year event. Also going to post updates every week during Early Access.

+
+ +
+
[05/02/19]: Just before the Steam Release
+

Military service wasn't kind, started around -10 degrees, even saw 30+'s momentarily at one point, started with snow and ice, moved onto cold rains, everyday had a different kind of challenge. The only good thing about it was the dogs, there were many happy dogs that tagged along wherever you went. Never experienced such a dog culture before. In the end, managed to get away with pharyngitis, sinusitis, eye and ear infections, luckily got vaccinated for meningitis, or it would have been endgame.

+

Returned home 25th of January, and started the last preparations for the Steam release on 28th of January.

+
+ +
+
[04/02/19]: Up to January
+

I had a good thing going until October, but when the cold winter arrived, it became a challenge to wake up at 7am and prepare to start working at 8am. I couldn't maintain that work schedule for long. If I lived alone and had the opportunity to concentrate in a healthy and serene work environment, it would have been possible, but sadly, it ended.

+

Started working more in a free manner, which has it's own advantages, you get to make better high level decisions. Immediately decided to concentrate on the Steam release and nothing else. Started pushing small things to completion, polished whatever I can. Fast forward to November, still wasn't ready. As Steam has a lot of requirements, decided to release on Mac App Store first. For me, the hardest part of releases are always taking screenshots, recording videos and preparing optimal descriptions. Marketing doesn't come easy. Released on the Mac App Store around 12th of December. One good thing about the Mac App Store release: I was originally planning a very complex introductory video, it had a lot of tiers, promoted various aspects of the game, basically I was being crushed under that responsibility, however, after discovering that Mac App Store only allows videos to be 30 seconds long, I decided to only showcase the core part of the game, the coding and multi-character aspect, and ended up with a very simple yet concentrated and explanatory video, which I ended up using for Steam too.

+

In Turkey, males have to serve in the military, I had enrolled for a paid short term beforehand, and the lottery hit me at 7th of January, which complicated things further. I had the opportunity to release on Steam around the 20th of December, but as I needed to be away for ~20 days, delayed the release until I returned. In hindsight, one needs to complete the Steam Store listing page weeks before the actual release. You learn these things once you go through with the process.

+

Apart from these, December was a really bad month, I got subjected to an extreme amount of injustice from Facebook, had really old apps that lived on their platform, they decided to completely remove one of them for no reason, became really ill from sadness, couldn't sleep most of the time.

+
+ +
+
[07/09/18]: Cloud vs. Dedicated
+

I'll start this small informal blog post about issues and ramblings about Cloud.

+

First, App Engine: Normally I was a big fan of App Engine, in the early days, they were extremely dynamic, at their peak, even Guido van Rossum was part of the team and the entire team interacted with developers. Nowadays, it's just a shadow of those glorious days. Total neglect and incompetence. It's clear that the team, if there's a team, has no grip on the product. Is it still the best cloud product out there? Most probably. And if you push enough, you get things recognized. If you push really hard? maybe you could get problems solved.

+

Spadar, one of our hardcore players has been complaining about 500 errors that didn't manifest themselves in logs. After quite a bit of investment, I managed to track these errors, got the issues recognized, but while it's a beyond major issue and a major breach of trust, the respond from Google was along the lines of "meh, it happenz, let it be, it's smallz". I sincerely hope they clean their house and we see those old glorious days once again.

+

Second, AWS: I had 15k$'s of AWS Activate credits, and used 8k$ of that credits up until August. Many thanks to Amazon for their help, thanks to them, I got to develop Adventure Land for 2 years without worrying about server costs. When the September bill arrived tho, it's clear that a change was necessary. ~$80 each for 3x 2-core servers. $240. And an extreme amount of data charges. Up until this point, I honestly didn't even bother calculating feasability. But on Monday, after the bill, calculated it alright. What's more bothersome was the data charges.

+

At this point in time, we have only 40 active characters (Very healthy number for prolonged development in my opinion, fyi) - anyway - the $240 server charge isn't that bothersome, as servers are unutilised, but the $40 data charge was bothersome, it means each character costs $1, since one player can have 4 characters, it meant that each player cost $4/monthly in just data. Beyond infeasible. I first thought something was amiss. As the game uses miniscule amounts of data. Like 5-10kb/s. But when you make the calculations. Even those small amounts end up being 10-20GB per month. As characters are online 24/7. So a new old-era has started, Dedicated Servers.

+

I started web development with Dedicated Servers, those were the days. I had 3-4 ServerLoft dedicated servers at my peak. It was a pain manually scaling things. That's why I moved to App Engine later on. More expensive, but could be 1:1 and more practical if you use it well. After reseach, 2 candidates popped up, Hetzner and OVH groups. They provide the best performance-bucks ratio possible.

+

As players prefer the US servers, I chose OVH's child company SoYouStart and got a i7-4790K game server for just 35 euro/mo. Comes with 250Mbps of unmetered/unlimited/free bandwidth. So basically no more data charges.

+

So I'm a Computer Engineer and all, but, as a shame, I don't hold information in my brain, so I ended up googleing core/thread dynamics and how the 4-core, 8-thread processor can be best utilised. The main question was, for a pure-cpu workload, whether the 8 threads provided any value. To inform the reader, the 2 threads per core enables 2 processes to use a single core in an efficient way, so for a pure computing workload, the threads aren't ground breakingly useful. I concluded that I'll run 5 servers on a single machine. 4 PVE and 1 PVP. I assume each PVE server will utilise a single core to it's fullest and the PVP server will hang in there.

+

The server has an initial pre-computing stage, on my local i7-7700HQ, it's computed in ~13000ms, on the top AWS servers, it was around 20000ms, on the i7-4790K, it was an impressive 6900ms, double the performance of my i7-7700HQ, shame and hurray. Back in earlier tests, the AWS servers crumbled with ~70 players in one server (I improved the server logic afterwards, to slowdown ticks dynamically, fyi) - with the dedicated server, loaded 80 characters myself, it's the limit for my own internet bandwidth to handle, and the CPU utilisation was just around 30%. So I suspect the new servers could even handle 200 non-abusive players, but realistically, set the new limit at 96 players, as most players thrash the servers hard :)

+

So basically that's a huge problem solved, 35 euros for 500 characters, it's like $0.3/mo (worst case) for player (4ch for 1p). Considering the game will be for $12.99 on Steam. We're feasible now. By the way, each game server will try to gather $20-$50 each month with shells sales, so don't quote my calculations here and blame me for overselling things :)

+
+ +
+
[07/09/18]: A New Era
+

Around December 2016, I kind of broke myself, I had a very strict work approach, It was forcing me to work every day, every hour, the stress was unbearable, I decided to just set myself free and see how it goes. It didn't go well. It eliminated the stress, but the stress became anxiety due to neglecting work.

+

After 1.5 years of bad performance, around June, a new approach started forming as an idea, and on June 21st, I started a new system of work.

+

Basically I work only weekdays, wake up at 7am, have a breakfast, brew a coffee until 8am, work from 8am to 12am, have a lunch, watch some TLC or sth, then work from 1pm to 5pm and leisure time afterwards. It's basically working wonders. No stress. No anxiety. But some energy issues due to waking up so early. In order to wake up early, one must prepare well before sleep, that part I didn't quite yet master.

+

Thanks to this new system, last 2 months have been beyond awesome.

+
+ +
[22/05/17]
+

Today's Feature: Hardcore Mode

+ +
[21/05/17]
+

Today's Feature: Player

+

This is more of an internal change, enables a certain usage, and makes it almost impossible to achieve something very specific. Basically, there is the "User", and "Character"s, this change adds a new model/entity called "Player" in-between. As it is, this doesn't add much to the game, but I believe, in the future, it will simplify certain things a lot, make things flexible, allow 1+ realms.

+ +
[20/05/17]
+

Today's Feature: Mail

+

Implementing the "Mail" routines. There will be multiple types of mails, most needed one (from my side) is game-to-player mails, for example, the game needs a "Recruitment Actions" interface, they will be in-game mails instead, when you recruit someone, when someone you recruit achieves something, you will receive an in-game Mail, possibly for a lot of other things too.

+

Considered handling all incoming PM's as Mail's too, yet, it seems like an overkill.

+

I have a lot more to write about in the coming days, possibly a hefty blogpost.

+ +
+
[22/04/17]: "Development Logs" becomes the "Development Blog"
+

As a habit, I take a lot of notes, mostly in the form of entries, kind of like a diary, it's part a habit, part an obsession. It's a work thing. You know, sometimes, you feel like you've experienced a time slip, it feels like months have passed, and you've achieved nothing? Probably every student will know the feeling, when the semester starts, everyone is generally very relaxed, but, when the midterms or the first exams arrive, even though likely 2 months have passed, it feels like no time has passed at all, it's a time slip. Anyway, I've started this note-taking habit to prevent these time slips from happening, and kind of force myself to work. About 7 years ago, I was developing Facebook apps, at one point, Facebook started a crusade against apps and app developers, they disabled, removed apps from their platform without reason. It was devastating. Every time it happened, it caused a form of depression that caused something similar to these time slips, It was hard coping with loss, after these happened, I would discover that weeks, or months have passed since I've done anything to achieve my goals. Anyway, long story short, I write down pretty much everything work related I do, on Moleskine notebooks, this way, the work keeps on going no matter what, it works, but it has it's issues too, after years of doing this, I wonder whether it's more natural to just let time slip.

+

Anyway, you've probably wondered what this has to do with Adventure Land, when I first started developing Adventure Land, there was just development, there wasn't a significant playerbase, there was no playerbase to satisfy, to retain, to grow, after our first Reddit announcement, things changed quite a bit, actually, pretty much everything changed. So, TL;DR: It's no longer possible to aggregate my physical notes into daily notes, list of changes for the game. I loved doing it, it was good while it lasted

+

From now on, without any format, I will use this page as an occasional blog, to write about things, thoughts, feelings - and of course, about the game

+

A lot has happened in these last 4 months, the game has improved significantly, old players are amazed when they re-visit, the most important and determining decision was to postpone the Steam release, instead of releasing as Early Access, I decided to "complete" and "perfect" the game first, in hindsight, this might not have been a good decision, time will tell.

+

I sincerely hope it ends up being a good decision, on the bright side, games are timeless, so additional time spent working on a game could tip the scales significantly in the long run, received a lot of feedback, experienced a feedback overload, some were really good, some were misleading, demotivating, but in the end, spotted a lot of core issues, it was a great learning experience, I can tell you this much

+
+ +
[16/01/17]
+

Today's Highlight: Launch of the New Town!

+

After the midnight, updated the "notes", "looking forward to" sections, made last minute checks, corrections, everything was ready for the New Town, + Deployed!

+

This was the first update that refactored all the characters beforehand, those who were in the old town needed to be reset to positions in the new town.

+

After the update some players were experiencing transport/movement issues, fixed that issue, Added an "is_code" flag, separated the Code logic in one of the common functions.

+

Discovered another PIXI bug, "Curse" started causing issues, two filters can no longer be combined, there are other reported issues too, WebGL crashes are continuing.

+

Preparing to convert all existing 16x16 items to new 20x20 ones with Ellian.

+ +
[15/01/17]
+

Today's Features: Live Reload! + New Town! + Well-Crafted Bow, Sucker Punch, Mole's Teeth Earring!

+

Today was a long and productive day, started by integrating the new elixirs, adding quirks to the new town. Decided to add the "Live Reload" feature before launch, as it allows on-the-fly changes to the server data, like adding new items, modifying existing items. I was doing these kind of things manually, but after the "Orb of Second Chances" incident, it was clear something better was needed.

+

The "Live Reload" feature both refreshes the server data and at the same time triggers a data reload at every connected game client. So when a new item/drop is added, existing players don't need to reconnect and the servers don't need to be updated anymore! (+ Some other internal perks, like modifying the drop rates practically)

+

Added all the planned items, completed/re-visited all the new quests, monsters, drops. There's still a lot to be added/integrated to the game. Didn't add the new armor sets yet.

+ +
[14/01/17]
+

Today's Feature: Attack Animation: Nudge

+

Continuing with the integrations.

+

Got the idea to add a new attack animation, non-moving entities now nudge forwards when they attack. Monsters that don't have an idle animation really needed this.

+ +
[13/01/17]
+

Today's Highlights: New Town's Integrations + Vitality Earring

+

Added the Tavern/Premium-Items NPC's. Set the phoenix spawn points, improved the stats and drops of the Phoenix. Improved the seashells quest, enriching the new town.

+ +
[12/01/17]
+

Today's Highlights: Band of Fury + Evasion/Reflection Scrolls

+

Added the Reflection/Evasion scrolls, they have custom/balanced multipliers. Added the "Band of Fury" head-slot item, very rare and very powerful. Originally, it was meant to be a Tier0 item.

+

Tested Jayson's tavern entities, including the roulette table, slot machine and spin-game, impressive. Converted/Unified the "transport" responses.

+

Crated the new upgrade/compound animation, it iterates over the existing assassin_smoke method. Finalised the exchange/upgrade/compound integrations for the new town.

+ +
[02/02/17]: Last 2 weeks, I've been working on the friends system, code system, new skills, valentine's day event, and several other things, going to update the /logs soon++ | Additionally, planning to add another page to the game, as it's being requested a lot, something like a /todo or a /roadmap - Current roadmap includes, Friends System, Guilds System, Skills System, Tavern, Daily Events, Skin/Looks System, Steam Release, Achievements/Statistics/Leaderboards, Code Tutorials and more - The community should have a way to track all these
+ +
[15/01/17]: I've been working on the new town non-stop for the last few days, going to update the /logs soon
+ +
[11/01/17]
+

Month in Review

+

Caught up with my logs today and had the opportunity to review last month. I love December, overall I took a lot of time to relax and slack before and after new year's eve. It wasn't unproductive either, yet, I could've crammed a couple of days here and there to work all day and get a lot of stuff done. December 10th/11th was the last time that happened. I feel ashamed that the new town is still not integrated, even though all the content was ready for weeks. I experience something similar to a writer's block whenever there is new content to add to the game.

+

Jayson prepared the first prototype for a slot machine. It's a nice one. He seems to be recovering from the motorcycle accident. While he initially told me it wasn't serious, as I understand it was a serious accident. I keep on wishing we could have an active stream of communication, but at this point, I've settled with bursts of collaboration too. I think another burst of collaboration/creation is imminent, as we are both hungry to add some new stuff to the game.

+

Received an awesome suggestion list from "Trexnamedtom" on Discord for Achievements. It's the best suggestion list I've received so far. Usually while reading suggestion lists, I absorb 10%-20% of the ideas, and the rest clash with my vision and direction for the game (or they require more effort than what's possible on indie levels), some suggestion lists are completely uncoupled from the game, that's why Trexnamedtom's suggestions really suprised me, we share the same vision, I love all of the achievement ideas and intend to work on them. Previously, "Aelwrath" also sent an incredible suggestion document, just re-visited it again, I should integrate some of his ideas, most of them are very high level, but on the lowest level, there are some intriguing item ideas and the MOBA/Code event idea is unique.

+ +
[10/01/17]
+

Catching up with the /logs + Finalised the improved transport system - It's not possible to move or re-transport during a transport now, applied at the client level.

+ +
[09/01/17]
+

Today's Highlight: How Machines Can be Misunderstood

+

Some time ago I've received a report, that showed "Gleich" cheating in game. After that, I personally noticed the same behaviour myself. It was upsetting, as, while a bit controversial, Gleich probably played the game most as non-afk. It doesn't make sense for him to cheat.

+

I've asked Gleich about the situation, didn't want to take action, and as it turns out, it was a bug/shortcoming, causing the misunderstanding. With the investigation of Deliagwath; Gleich, theZhoul and Deliagwath managed to replicate the bug. During a transport, there's a brief time where the client is in the old position, after the server moves the character to the new position, when the client moves during that short time period, it was possible to move outside the map unintentionally.

+

Gleich's code was pretty innocent too, the coded behaviour was to escape when someone is spotted, but, for a human, the observed behaviour was a cheater/stalker (as the character is outside the map boundaries, in the bank) exiting the game when he spots someone, which was very creepy.

+

Designed an improvement to overcome this scenario.

+ +
[08/01/17]
+

Today's Highlights: Injustice I've Caused + Bugfix Relief

+

Deliagwath brought to my attention that the grades of the "Orb of Second Chances" is [0,0] for the client and [0,1] for the servers. Ideally, I should update the server and the clients together, during an intermediary update I sent to the game clients, I forgot about the updated grades. As a result, a lot of people spent more gold compared to others that realised the server still references the [0,1] "grades" property. I can't describe how bad it felt. Corrected the issue, but, what's done is done, started adding a live-reload ability to the servers.

+

Patched the pvp/combo routines. It seems some rogue's are making teams kill their teammates. Ingenious but patched at the next update.

+

Today's highlight comes from "theZhoul" on Discord, he discovered that consecutive "move"s are to blame for the "move" discrepancies that we discovered thanks to the location correction routine. He did this externally. Internally, running the "mode.debug_moves" routine, it's indeed the case. Reason: There is an internal move timer, it resets every time a move command arrives, the fix is to reset the timer only when the player isn't already moving. I love patches/bugfixes like these. Simple yet great.

+ +
[07/01/17]
+

Integrated our new cave. The design is impressive. Dracul currently occupies the prime area, yet, he will probably become a random and frequently spawning boss, and that awesome area could be used in a different way, maybe a global event triggered through an item.

+ +
[06/01/17]
+

Integrated the NPC's to the new town, combined the basic armor and weapons merchants, added direct access to Upgrade and Compound through the wells near the combined upgrade and compound NPC.

+

Due to weather conditions Jayson wasn't around for the last 2 weeks. He's also been in a motorcycle accident recently. He says he's ok but I'm not sure. I sincerely hope he gets well soon.

+ +
[05/01/17]
+

Started designing the new movement and vision system. The vision aspect improves performance, the movement one is complex and strict.

+

Updated most of our existing items to the new looks.

+ +
[04/01/17]
+

Today's Feature: Temporary Account Blockage + Analysis Routines

+

There are 3 ways to violate the rules, 1 of them is through abusive behaviour, the second one is using 1+ accounts to overcome the 1+1 allowance for siblings, the other one is to violate the map lines. I've been receiving a lot of reports for people using 2 accounts to party in the same server, with this feature added, blocked the secondary accounts. In the future, the servers will issue temporary blockages too, for various scenarios.

+

Added 2 new internal analysis routines, one of them analyses the game in general, the other one is for individual accounts, helpful for moderation and monitoring.

+ +
[03/01/17]
+

Researched possible games for the Tavern today, read Wikipedia pages for various games, inspected some patents. {#The thing I love most about developing Adventure Land is gaining experiences in such unexpected fields.#} Learned a lot on chance games design today. Most of the real life challenges doesn't exist in our game, still, there are a lot to apply.

+

Earlier, I made some performance improvements to the game, an oversight was causing the inventory size not to be re-calculated after upgrades and compounds, fixed that issue and applied the same performance improvements to other places.

+ +
[02/01/17]
+

Today's Feature: Tavern: Roulette

+

Implemented the Roulette, it can be played through Code, the UI will arrive later on, I'm thinking a monster running on a mill with numbers, when the monster stops, a number is selected.

+

I had 180M on my local test character, lost it, added another 400M, lost it, so Roulette itself is a fun gold sink, verified. Not all games will be like this tho, the next game will likely be player-vs-player and similar to this game.

+

Life: Yesterday a pigeon entered the house from the air duct, struggled a lot there, she looked cheerful when we rescued her, ate, drank, tried to let her go today, she wasn't able to fly, and tonight, she passed away, buried her, it was devastating.

+ +
[01/01/17]
+

Today's Highlight: Tavern: First Step

+

Implemented/Started the internal architecture for the Tavern, started building the Roulette.

+ +
[31/12/16]
+

New Year's Eve!

+

Inspired. Started the Tavern. Improved the game performance when the window is minimised.

+

Looking Back: On a personal level, 2016 didn't start well, I was working on a project for 4+ years, I was continually failing to gain traction or recognition, I was stuck inside a fruitless loop, It was time to start doing something else, not to abandon the project, but to do something more productive. It was around May when I started creating Adventure Land, and in June I fully committed to the project. It was an incredible journey for me, along the way, I paid my emotional debt, normalised my life ambitions and goals, broke my obsessions, and thanks to the game, became a better person with insights into unexpected fields and various unexpected experiences. I was expecting game development to be mostly about development, but it was more about, economy, psychology, sociology, business, and even politics. Trying to build an enjoyable game, I started appreciating life a lot more too. In many ways life is a lot like a game, but much greater than any of us can even dream of building.

+

Going Forward: Code/Teaching aspect of the game inspired me to go back to university and complete my master's degree and continue on from there. I wish to start a family too, during my emotional turmoil in 2016, I concluded that business endeavours shouldn't be primary objectives, but rather, secondary bonuses. For the game, tavern, daily events, code improvements, communicator, skills, items - there are a lot of exciting stuff to work on. My mistake these couple of months was to set clear objectives and deadlines, they killed my productivity, stressed me, going forward, I intend to continue on with a more scattered approach. As an aspiring game developer, I couldn't wish for a better community, I'm extremely thankful. Thanks to you all, it's a joy working on the game with all the feedback, suggestions and the company. Looking forward to our Steam release.

+ +
[30/12/16]
+

Today's Highlights: New Year's Eve Boost + Next Iteration of Limits Enforcer

+

Boosted the Mistletoe, Candy Cane drops significantly.

+

Improved the global limits enforcer once again, it's a lot more complicated and refined now.

+ +
[29/12/16]
+

Today's Highlight: Greenlit!

+

The game is Greenlit on Steam, so fast, and such a relief :)

+

Integrated the new looks for the armors, sent an early UI update.

+ +
[28/12/16]
+

Today's Highlight: New Items with Ellian

+

Created the graphics for our new items with Ellian.

+ +
[27/12/16]
+

Today's Feature: The Second Chance Ability

+

Improved the integration of the new town, finalised the items that will initially arrive with the new town.

+

Implemented the "Second Chance" ability, it's a fun one, the Orb's increase code complexity too, which is a direction I aim for, even if one gets a better Orb in the future, it makes sense to equip the Xmas Orb's just before death. Modified the "Orb of Second Chances" to be rare at +0, the modification will be live after new year's eve when the event is over.

+

Reproduced the movement issue we've been hunting with Mark, it does happen consistently, I didn't have a chance to inspect it deeply yet, glad I added the "Location Correction" routine, otherwise it's an issue that would go unnoticed.

+ +
[26/12/16]
+

Today's Feature: Stacked Listings for Merchant's!

+

Added/Calibrated the "Spiked Shield" item. Upgraded to OSX Sierra, seems stable, using WebGL heavily, UI glitches started happening more frequently, Sierra seems stable.

+

Improved the trade system to allow listings for 1+/Stacked items. All trade/exchange routines have to be perfect, even the smallest oversight could be fatal for the economy.

+ +
[25/12/16]
+

Today's Highlight: Weapon Tiering System

+

Designed the system that will govern the weapon tiering. Calibrated the T2 Bow which is heavily requested by the community.

+ +
[24/12/16]
+

Today's Highlight: The Mining Tunnel

+

Created/Integrated the mining tunnel + drops. Mole's aren't easy to farm, yet, in the long run, farming them will be very rewarding.

+ +
[23/12/16]
+

Today's Highlight: Json's Wings

+

This was a productive day for Jayson, wish his productive days are more frequent, the wing idea is an impressive one, can't wait to add a "wing logic" that adds wings to any character.

+

Improved the Friends/Server/Guildies interface, it's one step closer to production. Mostly worked on new tiles and the integration of the new town and monsters.

+

Side Note: The world is becoming darker and darker, there are terrorist attacks almost every week in Europe/Middle-East, the country I live in is also suffering heavily, trying not to lose hope, the solution in my opinion is to be positive, nurturing, affect other's live's in positive ways, be forgiving, patient.

+ +
[22/12/16]
+

Today's Feature: Dynamic Spawn Bosses

+

Woke up early to a semi-nightmare. It occurred to me that I might've set a high gold drop for Rudolph. Checked the statistics, it wasn't the case, but it was still higher than intended rates, Mark also noticed it and started farming it, ended up patching the drop rate.

+

Today's feature is the ability for bosses to spawn in random locations. This enables me to increase boss drops, it also encourages players to write smarter Code's.

+

Integrating new monsters. Improved the way game calls functions inside the Code, added error handling, otherwise, for the "on_draw" function, Code exceptions had fatal results.

+ +
[21/12/16]
+

Improved the design of the New Town. Discovered a visibility issue, in the original town, when someone moves from a certain point to the merchant area, some merchants are invisible, patched the issue.

+

Working on an improved movement and visibility system. Current system is a bit complex, it's the 4th or 5th iteration, I really want to make some time and move to a 6th iteration.

+ +
[20/12/16]
+

Today's Highlight: Xmas Email + Interaction

+

Send our Xmas email today. Increased the drops for the Ornament quest. Promoted the Steam Greenlight page in-game. Updated Reddit/Twitter/FB.

+ +
[19/12/16]
+

Today's Highlight: Steam Greenlight Page!

+

Interacted with our new players until 4AM, It's always a joy to see new players enjoy the game, the initial feedback is also very important, at this point, I'm confident the game is going in the right direction.

+

Created the screenshots I was planning for the Steam Greenlight page, wrote the descriptions, launched the page, it's a relief. Changed the game's Twitter username to @CodeMMORPG from @PixelMMORPG.

+ +
[18/12/16]
+

Today's Highlight: Second Reddit Announcement

+

Preparing the Steam Greenlight page, Improved the Code functions a bit.

+

Highlight of the day is our second Reddit announcement, once again, it was a joy to start welcoming new players

+ +
[17/12/16]
+

Today's Highlight: Code Video

+

Executed the small giveaway I was planning, both players and I are probably getting very fluent at creating small functional scripts. In the past, I used to add features/code to projects I work on, for even the smallest task, nowadays everything has a small script - Interestingly, the game is very similar too, for different gaming occasions, one can whip up a modified Code.

+

Today's main task was the preparation of the "Code Showcase" for the Steam Greenlight page, marketing material for any kind challenges me, but preparing the video ended up being fun, I wish I did this a month earlier.

+ +
[16/12/16]
+

Today's Feature: Dynamic Observation

+

Previously the login/character-selection page only showed the merchant area, with this new system, random players are shown. It's nice to shuffle through the server a bit this way.

+

Improved the new bank, added the Clerk's, Finalised the unlock routines.

+

Added a "Booster Guide" and accompanying Code functions. Through code, it's possible to utilise one booster to benefit from everything, it should be fun implementing this strategy.

+

Updated the game, fixed the issues.

+ +
[15/12/16]
+

Today's Highlight: Boosters

+

Caught up with these /logs again, normally I was updating them daily now, but the events on [02/12/16] caused another delay.

+

The "Taunt" now takes the aggro from monsters that are targeting allies, thanks to Mark's reminder :]

+

Integrated/Improved the new boosters, simplified the internals, going to document a "How to Use" section along with Code methods soon.

+

Monster XP's now factor in the .xpm XP Modifier of players. Useful for PVP. Going to add another notice to PVP soon, advertising the increased luck and gold too.

+

Improved the Guide, added a Limits section.

+ +
[14/12/16]
+

Started finalising the new "Booster" items, they are the improved version of "Stone"s.

+

Today is a big day for me personally, I completed my personal quest, the future seems brighter now. Going to celebrate this in-game soon.

+ +
[13/12/16]
+

Servers are performing very well. Improved the bank design with Jayson. Interacted with the community, debugged a movement issue, it turned out to be a false alarm, yet, ended up adding a "Location Correction" feature. It should be triggered if a high amount of delay causes a character's client-position differ from the server-position by >100px's. The movement system was designed to make the game fluent even when there are high delays, but this system requires compromises, as an example, line/border violations are allowed, if a player is experiencing a minor amount of delay, they should be able to play the game without issues, but this system causes a lot of headaches for me, so I might end up replacing our movement system with a new one at one point. Can't be soon tho.

+

Last few days, I've been on a personal quest, it materialised on [06/12/16], and it's been a source of motivation and much-needed distraction for the past month, it's finally nearing completion.

+ +
[12/12/16]
+

Today's Feature: Bank Slots

+

Started relaxing, going to take it easy for a few days.

+

Implemented the system for additional bank slots. They can be unlocked with Gold or Shells. Jayson created the first version of the new bank with 8 Clerks.

+

Fixed the count for the leather quest. Fixed an issue affecting the .cursed,.stunned properties for monsters, they weren't being removed, and monsters stayed cursed or stunned.

+ +
[11/12/16]
+

Today's Highlight: Xmas Launch

+

Finalising the new drops, added the stat ring drops, previously, all stat based drops were diverse, a stramulet and intamulet had the same drop rate, this is no longer the case.

+

Added a "Well-Crafted Cape" - a rare but achievable exchange from the leather quest.

+

Calibrated the new monsters, added properties, most monsters will have it's own challenges as game progresses, based on properties, aggressiveness, spawn rates, drops and competition.

+

Added guard NPCs as a placeholders, they will guard un-launched zones/caves/places.

+

Replaced "Dark Knight"s with "Croc"s, I added "Dark Knight"s in July when I first launched the game, they were the first monsters too, however, having them in the Town never made sense, they will serve in the Underworld in the future.

+

Said goodbye to Mercury, he was a really positive player, helped form the Wikia, left the game to concentrate on his studies. I wish all goodbyes could be civil like his.

+

Further enriched the leather quest, there are other very rare armors too. Might increase the droprate of the armors.

+

Calibrated/Finalised all the Xmas items and drops, getting excited.

+

Set the update notes, deployed the improvements, updated the servers.

+

It was delighting to see so many players rushing and exploring the game as soon as the update went live. Moments like these make me proud. I cherished every moment.

+ +
[10/12/16]
+

Today's Highlight: Xmas Push

+

Added the "Would you like to turn on the Xmas Tunes?" prompt, after hunting the perfect tune, I want it to be enjoyed :)

+

Added the initial integration of music/fx levels, currently internal, reduced the music_level;

+

Completed the new "Upgrade or Compound" NPC, I think simple is better, instead of statues that are hard to discover, this new NPC/design is very easy to discover, and explains things in a very basic form.

+

Completed the Cape/Orb equip logic.

+

Perfected the "Winter Inn".

+

Added a new feature to NPC's, they can now change direction when you interact with them, in the future, they will have their own routines, they will at least walk, and hopefully a lot more. Currently only "Ace" has a pre-set movement. I think it would be nice to have several NPC's that are just there to add color, they could give small tips.

+

Improving the game client / server interactions, ideally, server should never send text to the client, all text and responses should be on the client, this will make it easier to translate the game at one point.

+

Turns out I was mis-spelling "Mistletoe" all this time, I thought it was "Misletoe", lol.

+

Added the "Transport Lady" to Winterland, the "Captain" is ready too, yet, for the time being, transport is more practical than sea travel.

+

Completed all the details for the Winterland and Winter Inn.

+

Integrated/Improved all the new quests and monsters, yet, there's still a lot that needs to be done, a lot of polishing and enriching and testing.

+ +
[09/12/16]
+

Today's Highlight: Xmas Rush

+

Created/Integrated "Rudolph", added the drop. Integrating the "Winter Inn". We've created a strong synergy with Jayson. I really don't want to delay the December 10th goal of launching the Xmas event. I've already far-missed my timeline for the Steam Greenlight launch.

+

Added the "Orb of Second Chances" - our first Orb, has the ability to prevent death with a %.

+

Created Tier 1.5 for the Xmas items, based on the Halloween experience, releasing a unique T2 armor with a high-drop rate wasn't a good idea, comparatively, Xmas items are much easier to achieve, much easier to upgrade thanks to their initially normal grade, and T1.5 doesn't wreck the game balance.

+

Slowed players in Winterland.

+

Added the leather merchant, polishing the quest system. Improved "Stompy". Jayson improved my Rudolph a lot.

+

Added a ".rage" property, similar to ".aggro", when ".aggro" happens, ".rage" is the probability of the monster targeting the player.

+

Unified all NPC interactions, I love refactoring.

+

Today was an extremely productive and satisfying day, one personal lesson is, it's a good idea to live a relaxed life, as long as you can squeeze in 10x productive days like these every once in a while.

+ +
[08/12/16]
+

Today's Highlight: Xmas Rush

+

We've started working with Jayson heavily, sadly, Sun Pixels didn't deliver on his promises, so it's up to us to achieve the Xmas goals. Luckily, the items Ellian prepared for Xmas are perfect.

+

I've improved the internal "Drops and Exchange" system of the game, now it's more like a "Forest" in computer science terms, makes it really practical to design and set drops.

+

Added the "Cape" - an exciting item, yet, really hard to acquire, the leather quest isn't an easy one.

+

To fix a small issue, I've deployed an update to the game, forgetting the new limits enforcer, the enforcer discontinued almost everyone, but on the bright side, I got to improve/fix the new system. Developing a live game really isn't easy, the game almost always gets judged by it's current state, however, if the game wasn't live, I couldn't develop this efficiently, so it's definitely worth it.

+ +
[07/12/16]
+

Fixed a memory leak that affected HP Bar's and Name Tag's. The leak only became noticeable after making Name Tag's toggle on/off and dynamic.

+

Started creating the first quests, the xmas quests.

+

Improved the IP Limitations layer. Improved the server, added the "Convert to Shells" routine for items that are being discontinued.

+

Lately I've been very stressed, so instead of working ~10 hours a day on the game, I've reduced this amount to 3-4 hours, and in the remaining time, I've been working towards a life achievement/goal, when you are young, concentrating purely on work is manageable, yet, as time passes, the desire for something more grows.

+ +
[06/12/16]
+

Today's Feature: Targeting Aggressive Monsters

+

Up to now, some monsters only attacked players and moved on, with this improvement, they might target the player too.

+

Improved the HP Bar's and Name Tag's.

+

Started refactoring the character status flags, like .cursed etc.. Improved/fortified the server.

+

Added the "Candy Cane" and blue "Pom Pom"s.

+

Outside the game, a very positive development happened, I've been looking for something and finally found the perfect candidate.

+ +
[05/12/16]
+

Today's Feature: Damage Return

+

Added some new cache's to the game to improve performance. Improved/Re-Visited some server routines, refactoring/improving existing code is always enjoyable, serene.

+

Implemented the "Damage Return" property, Armadillo is going to receive it, and in the future, there will be items that add "Damage Return" to players. It's physical and melee only, however, it might affect close-range ranged attacks at one point too.

+

Added the "Eggnog".

+ +
[04/12/16]
+

Today's Highlight: Improved Password Routines

+

Improved the NPC animations, they flow better now.

+

Re-Implemented the password routines, passwords are hashed with random salts now. Implemented a supplementary, new password reset routine. Deployed, Tested the changes and refactored all existing passwords.

+ +
[03/12/16]
+

Today's Highlights: Random Respawns and other stuff ...

+

The Phoenix is going to spawn in random spots when the system is completed.

+

Worked with Jayson a bit, I encouraged him a lot to improve his pixel art skills in the past, contribute to the map tiles, he designed some tiles today, they ended up great.

+

Improving the game designs, the winterland, the desertland, and everything else.

+

Improved the IP security layer of the game.

+

I have a relaxed and simple approach to security, my assumption was, if people are challenged too much while recovering their passwords, they might quit instead, this is why I initially chose to keep passwords in plain text, it seems the practice is heavily frowned upon, live and learn, we lost a valued member today, as I predicted earlier, the lifetime of the game is 60 days for most people, which is more than enough, I just wish, after bonding, getting to know each other, people would quit in a more joyful manner. Game moderation, development, is more challenging than I thought.

+

After working non-stop for almost 6 years, I think I need a break, maybe a vacation - and definitely some changes in my routines. I used to have a very relaxed approach to work, it's probably best to go back to my roots.

+ +
[11/12/16]: It's been a hectic week, especially this last 2 days were great, we've achieved a lot with Jayson, going to update the logs soon, I've been integrating, polishing Winterland, Xmas stuff for the last 12 hours, It's finally complete, I'm very proud, at the same time, I'm very anxious at times like these, a lot changed with the game, I hope I don't wake up to offline servers tomorrow :)
+ +
[02/12/16]
+

Today's Highlights: Elixirs, Christmas Items and Improved Item Speeds

+

Implemented the Elixir logic, the usage, expiry, integrations.

+

Finalised the Christmas Events and Items, the most exciting item is an Orb, Orb of Good Spirits, in addition to stats, it also has an ability called "Second Chances" - with a % chance, revives the player when HP hits 0.

+

Made my decision on the game "Limits" - this topic is very heated, I decided to limit free characters to 1 PVE + 1 PVP + 1 Merchant, and even with the new xp/gold/luck booster item that costs $8, the limit is 3, so for $16/mo, a player can play with 3 characters. In the past, when the limits were added, then reduced, there was always a backlash, yet, after 1-2 days, the game always improved, became more social, economy metrics improved. So I'm confident this change will be positive too. It will go into effect along with the Christmas Event and new maps.

+

Reduced the monster charge speeds, for Squig, increasing the speed from 10 to 20 was displeasing, reduced multipliers.

+

Basher's speed reduction now shows up on stats, the speed reduction also decreases with upgrade. The "Slow" weapon speed is now a multiplier, currently 0.8 for Basher, but soon, all weapons will receive a Speed stat. Going to balance the dynamics once all weapons are designed. "Very Slow", "Slow", "Normal", "Fast", "Very Fast" are the options. Might simplify things and go with "Slow", "Normal", "Fast".

+

Integrated the Christmas Event sounds.

+

Discovered and fixed a rare server issue, newly introduced, improved the server system, now PVP and TEST servers have unique names (not I,II,II etc.).

+ +
[01/12/16]
+

Today's Highlights: Paid the Logs Debt + Combined Damage Warnings

+

Today was a slow and relaxing day, caught up with the /logs. In the background, I'm constantly weighing alternatives and options about the game's direction. If past has proved anything, bad decisions are costly.

+

Checked out AWS re:invent, Adventure Land uses C4 EC2 instances, the new C5 instances are very exciting, can't wait to make the switch.

+

Added combined damage warnings + "on_combined_damage" callback for Code.

+

Picked a tune for the Christmas Event, I love it, going to add a "Do you want to turn the Music on?" prompt soon.

+

The new Pokemon game seems like a flop, I'm guessing they cater to the newer Pokemon GO generation now, the 3D and directed gameplay wasn't enjoyable for me, I would rather have 2D and free gameplay, no matter how repetitive it is.

+

Spent a lot of time outside, bought some new years lottery tickets, I always loved December, if everything goes according to plan, we are going to have a new years lottery in-game too :)

+ +
[30/11/16]
+

Today's Highlight: Fisherman(?) NPC

+

Continually designing our new items.

+

Improved the "Exchange" system to support Quests too. Added the "Seashell" item, drops on the beach, the Fisherman NPC collects them, you can turn over 20 to receive a random rewards. These NPC Quests will be the only source of some items. Some Elixirs, Some Rare Accessories, Some Scrolls.

+

There will be 3-4 Quests like these. One of them will be inside the "Mystery House" - It's not a mystery house any more, there will be rats inside that ate all the jewels of an NPC, she's looking for her jewels back. Each zone will likely have rare "Key" drops too, to unlock the "Dungeon" of that Region/Map. All in all, design-wise, I'm really satisfied with the direction.

+

Found some nice solutions to some of the PVP challenges, asked for feedback on Discord. The main challenge is always healing, Priest's heals are over-powered, considering future levels of armor and res, the heals will only become more powerful. So today's idea is to start adding abilities, skills to block heals. The obvious one is Priest's own Curse, another one is, a "Hex Arrow" for Ranger's. It will be a rare item that needs to be farmed. Some weapons, items might also receive similar abilities of their own.

+

Received the new Pokemon games, Moon for myself, Sun for my brother. We've been following Pokemon again since the XY times, each game provides 30 hours of fun. I guess, a lot of people like 2D/Pixel games because of the original Pokemon games too. Learned about "Star Trek: Discovery". There's a lot to look forward to.

+ +
[29/11/16]
+

Today's Addition: The Sneaky Goblin

+

The Sneaky Goblin has high Evasion, Reflection, 1 HP, no ATT, a mean attitude, and a hefty drop. After being hit ~100 times, he just laughs and teleports to a different place. It will be a small server-wide event. It's really hard to land a successful hit, and after it escapes, it's not that easy to find where it went :)

+

Added a "Line Check" feature to our map editor, I always enjoy adding small technical features like these. The bad news is, apart from the gap "Mr. Clean" found, there aren't any more gaps. Finding one more gap would have been enjoyable. As it is, I suspect, there might be a special case where our current `calculate_move` moves people outside the lines.

+

Added the "skin" property to monsters, basically, two monster definitions will be able to share the same looks, the first example is normal rats and jail rats.

+

Took care of some things I was delaying, Announcing our Merchant Class, a Debit Card application for the company. Paypal really hurt everyone in Turkey, more than it needs to, there is nothing preventing them from simply charging credit cards, apart from their online wallet, you realise everyone uses Paypal when you lose the ability to use Paypal. Most of my issues these past 2 months originated from Paypal challenges too, almost all Pixel Artists, Freelancers, use Paypal to get paid. Even though I have a relative abroad to make payments on my behalf. It's still very challenging. Not everyone is understanding either. Now, only finalising the "Community Code" video and preparing the Steam Greenlight page remains. Taking screenshots, preparing videos, any kind of pr/marketing, these are the tasks that I always hate and delay. They really don't come easy to me.

+ +
[28/11/16]
+

Preparing the elementals, they will likely be random spawning bosses, rather than set-spawn/set-interval bosses.

+

Considering alternative movement systems, algorithms, our system is custom, very robust, it serves us well, the downside is that violating the system is possible, and it upsets everyone when someone does that, so for the next generation, not going to settle with anything less then perfect.

+

Negotiated with Sun Pixels/Leo, he's going to be our pixel artist for the map details, characters, monsters. If everything goes according to plan. However, if my limited experience taught me anything, things usually don't go according to plans. As a backup, Jayson is working on some new stuff. Previously, Revangale was going to be the pixel artist, but we had issues with the first sample, and later on he left due to personal reasons, he did a great job on the "Ship" tho, we had potential, that's why I started being cautious, in terms of delays and expectations, I've also learned not to be specific, and let artists use their creativity. On the bright side, I can rely on Ellian for our items, he also said he can help with other stuff if need be.

+ +
[27/11/16]
+

Today's Feature: Monsters with Properties + Charging Monsters

+

Improved our internal map editor, added the ability to visualise monster packs on the map, it eases map design significantly.

+

Added Armor, Resistance, Evasion, Reflection to monsters. Feels great. As an example, a monster with high Evasion could only be farmable with Mage's/Priest's, while, a monster with high Reflection wouldn't easily be farmable by a magical class. It's always good to have some variety.

+

Added a charge behaviour to monsters, it's dynamic, low speed monsters speed up 2X when targeting someone, the multiplier is much lower for high speed monsters. I might further dial it down. I don't want to prevent kiting, but slow monsters aren't very fun either, so there's a balance in between.

+ +
[26/11/16]
+

Today's Highlight: Post Server Update Stuff

+

Server updates are always stressful, a lot changes between updates, there are lots of new features, improvements, and almost always, there are things that needs to be fixed fast. Suprisingly, this update wasn't that eventful. There are 2 bugs introduced, one is an innocent one. I didn't deem them worthy of a hotfix.

+

Spent some time with Allegaea, he seemed disruptive at first, as I received a violation report earlier about him, a map/line violation, yet, he turned out to be very kind and helpful. We inspected the server's IP response together, thanks to him, I discovered an interesting issue regarding dynamic IP's. I had dynamic IP's handled, yet, one edge case still remains.

+

Life-wise, getting things back on track, slowly boosting my morale, game-wise, it's becoming easier too, stress levels are reducing, the community is maturing. Spent half of this day tidying my surroundings. My greatest hobby is mechanical keyboards, I had a project laying around for almost a year, the parts are there, yet it takes 3 full days to build a keyboard, and I won't have 3 spare days for some time, so wrapped all the parts, keycaps and stored them in the attic. Cleaned the room and got a haircut afterwards. Feels like a new beginning.

+ +
[25/11/16]
+

Today's Feature: Sales Tax!

+

Worked on our Community Code video. Adjusted the upgrade/compound rates slightly.

+

Decided to add a small Sales Tax, mainly for fun, I think it will be educating for our young players too. With higher character level, the tax decreases.

+

Jayson designed a beautiful "Shells Island" - it's the background for /shells.

+

Tier2 armors now become "Rare" at +7.

+

Perfected the combo/aggro check routine, the logic is different for PVP/PVE, in PVE, you can't just get close to a stranger and get them killed, but in PVP, you might do that, not that it makes sense to do it.

+

Updating this /logs - It's really challenging, there are a lot of changes every day, and when I neglect to update the logs even for a week, it becomes an extreme chore :)

+

Tested our latest changes, made some last minute fixes, and updated the servers!

+ +
[24/11/16]
+

Today's Highlights: More PVP Improvements + Vitality Scroll + Lottery Lady! + Jail!! + Quirks

+

Added a 12-second respawn cooldown. Improved the "use_town" skill, it reflects the cooldowns now.

+

Added a re-log cooldown, some players were using the agility of the system to their advantage. Improving this re-log blockage, at first it was based on logout, currently, it's based on login, this way, when someone wants to join a friend in another server after a while, s/he won't have to wait.

+

Added the "Vitality Scroll" - for the time being, it only drops from the strong Scorpion's.

+

Added our Lottery Lady, after working on the game for this long, I started wanting NPC Dialogues too, and adding the dialogue for the Lottery Lady was refreshing.

+

There are players who commit minor offences, like walking past the lines, so decided to add a cute jail to our game, anyone can just walk out the jail, it's more of a friendly warning, for actual offences, the best course of action is to block accounts for a duration, or, just disable them. Again, considering we live in a world where online actions have no consequences, countries with dynamic IP's, it's a saddening challenge with no real solution.

+

Maps had "Signs", replaced that system with "Quirks", Quirks can be anything, signs, unimportant but fun map interactions etc.

+ +
[23/11/16]
+

Today's Feature: COMBO's!! (or, Penalties)

+

Combo's aren't exactly what they sound like, it's basically an extension to the internal attack system, with one attack, it's now possible to hit multiple targets, so it's kind of a server improvement.

+

Terrified/Petrified: There is a new property on character's, .targets, when you target multiple entities, your character now starts getting terrified, it slows down, and each attack from monsters deal an increasing amount of damage, this is to prevent the practice of tagging multiple monsters, stealing loots and getting away with it. It's much harder to do now, manually, maybe possible, but with Code, definitely not easy.

+

No More Stacking: This is a very major change, an extremely common practice for both PVE and PVP was to put all party characters in one spot, for a bystander, it's very displeasing, you can't see who's who, for PVP, it was extremely advantageous, you can't easily execute a strategy against 6 characters in one spot, without Code, you can't even target them, so with this new system, each attack to stacked players increases the count by 1, similar to terrified/petrified state, but, for the group, the total damage is calculated from the cumulative count, so basically, on PVP, even a single Rogue can eliminate a stacked party with a Supershot+Shot.

+

Both systems aren't perfect yet, the first one doesn't have to be, but the stack prevention system is very aggressive, I'm planning to add both Code + Game Log warnings soon.

+ +
[22/11/16]
+

Today's Highlights: Server Refactoring + New Layer(s) + Trade Protection

+

I love refactoring, today was a fun day. Added a new layer on top of all items, this was something I wanted to do for a long time, It ended up being a lot simpler and fun than I thought it would be. Also had the opportunity to improve the performance and bandwidth along with these improvements.

+

Added a .rid property to trade items, it changes each time the trade slot is modified, this prevents continually swapping items to trick Code'd merchants into buying something that didn't mean to buy. Congratulations to Vehn for achieving this, he did it for the fun of it, and returned the gold. I kind of wanted this to happen, it's a fun method, and it coincidentally happened today, independent from my .rid improvement.

+

Improved the trade slots, the data for the slots isn't sent when the slots aren't visible any more.

+

Jayson decided to stop playing on PVP Servers and become more active as a GM. It's a good decision and it was good to hear. Tho, I will miss seeing him on the PVP servers. And I wish the bullying from the community didn't contribute to his decision. We probably need a "PVP Etiquette" too. PVP is tooo controversial.

+

Started adding yet another layer to prevent abuse, it's not completed or integrated yet, however, I think we are going to need this layer a lot in the future. I really wish I didn't need to spend this much effort into protective layers like these, but when you think about the state of the world, they are really needed, online, there is no such thing as "responsibility", people aren't responsible for their actions, there is no system to attribute minor abusive actions to individuals. For a developer, it's a nightmare.

+ +
[21/11/16]
+

Today's Highlight: Addressed the PVP Issues

+

Processed the video, asked for feedback, the video ended up being a bit too simple, so started planning a secondary video that showcases the Code aspect of the game more. Thanks to Delia's suggestion.

+

Spent some time outside, I realised I've been putting myself under a lot of stress lately, I have certain rules for myself, one of them is "Don't screw yourself", I realised, with high expectations, self-imposed deadlines, I've been doing just that. Going to try and enjoy the journey, stop worrying about things.

+

Improved PVP dynamics further, .invincible deals 45% damage, both Supershot and Mana Burst received an initial cooldown.

+ +
[20/11/16]
+

Today's Highlights: Agile Parties + Added the "PM" Button + Greenlight Gameplay Video

+

Observed the first referral transaction, it's a nice milestone, a player referring another player, new player making a purchase, and the referrer receiving credit for it.

+

While designing the new items, decided to give Basher a push, boosted the damage significantly. Improved my internal items interface, added filtering, it's easier to compare and improve items now.

+

Improved the party system, now any member of a party can invite others, also, a higher member can kick a lower one. Additionally, it's possible to "REQUEST" to become a party member. Basically, considering people usually afk and check back in from time to time, this will enable parties to evolve more easily.

+

Integrating the new maps, mainly to slowly prepare for the re-launch, start polishing things

+

Created the first example code: https://github.com/kaansoral/adventureland/blob/master/examples/simple_but_improved.js It's simple, yet it covers most of the early player questions, has conservative potion usage, target and path checks.

+

We finally synchronised and recorded a short, simple Gameplay video for the Steam Greenlight page, Thanks to Json, Muhnch, Grim, draivin, Deliagwath, Aelwrath and everyone who participated in the earlier versions.

+ +
[19/11/16]
+

Today's Highlight: Friends System Materialising +

Started implementing the friends system, implemented the interface, received feedback from the community, added .afk info to the system, started designing the Guilds system, interaction-wise, It's going to be very similar to Friends.

+

Collaborated with Jayson, he has been extremely productive in November, in October we lost our synergy for a while, turns out he's also going through tough times like me.

+

I'm spending a lot of time outside lately, normally I concentrate on work, but becoming 26 hit me hard, when you are young, you can take a lot of risks easily, but I feel like I can't use work as an excuse any more, there's also the constant feeling of stress, and I feel like I've under-achieved. On the bright side, there are a lot to be grateful for, I've started receiving emotional support from friends and family, so things are progressing well.

+ +
[18/11/16]
+

Today's Highlight: Item Designs +

Designing our high and rare grade items. The challenge is mainly the acquisition and economy. Rare grade items should truly be rare and High Grade items should be hard to find. There are a magnitude of options. The easiest ones are having them as more seldom drops, or having them as rng/chest drops. Another idea that started shaping is small/local quests. Instead of monsters dropping stuff, they could drop quest items which can be exchanged for random rewards in some quantities.

+

draivin has been helping me a lot behind the scenes, he first came to me with his performance analysis around our October rush, it was a very pleasant surprise to receive an external performance analysis and suggestions for improvements, with his encouragement, I accelerated our new map/draw system, which has now been launched and matured, otherwise, I was going to postpone that system for some time. After that, instead of my calculate_move, we moved onto his optimised version of calculate_move, and today, he contributed another component to the game, one that will check for line violations. I truly appreciate his help. I never expected to get outside help at these levels. Thanks to his help, I can concentrate on the design aspect of the game more.

+

On the side, my existential crisis has been growing, my priorities have been shifting, without the game, I could've been crushed already, but the game showed me new beginnings are always possible. However, building the game isn't an all peachy experience either.

+

After 3 years away from the hobby, received a new fountain pen today, a Pilot Custom Heritage 912 with Falcon Nib, engaging with the pen boosted my morale.

+ +
[17/11/16]
+

Today's Highlight: First Version of the Steam Greenlight Video + Smooth Walk

+

I'm already behind my schedule for our Steam release, like 2 weeks late, so with an impulse decision, decided to just go ahead and shoot a gameplay video for Steam Greenlight, thanks to our awesome community, we recorded one in 15 minutes. Turns out my OSX recording solution had a lot of issues, FPS was very low, but it still felt great, we had a lot of fun, and gained a lot of experience for the next try.

+

The company I formed is both adding to my stress, and hard to maintain at the same time, it's also extremely costly and slow. I really wish being an individual and making business was possible. Yet it's impossible.

+

Implemented a "Smooth Walk" routine, some Code's walk in 1px/2px, it ends up being very displeasing, for such short movements, the walking animation can't even start, so rigged something up to try and merge those short walks. The ultimate solution is probably to disregard such short walks. And I think we need a "Code Etiquette" guide.

+ +
[16/11/16]
+

Today's Feature: Minimap

+

With our new map architecture, adding a minimap ended up being trivial, yet, since our maps are cozy, there is no point in adding one, so I temporarily axed the minimap.

+

Spent some time servicing other projects, as a life rule I learned, it's important to not commit 100% into one thing, even 90% is a lot, 80%/20% is healthier, I'm currently at ~95% with the game. The reason for the rule is, doing other things alleviates the stress, makes you more creative, opens up horizons - and - more specifically, if a project is making you money, you have to care for it regularly. I've never abandoned a project, yet neglect is equally bad. So I tried to work on all my projects daily, weekly, or at least, monthly.

+ +
[15/11/16]
+

Today's Feature: Vitality Attribute + First NPC Dialog

+

I previously decided against it, yet, as PVP became further tested, it seems increasing the character HP's will be a good idea, it also allows stronger weapons.

+

As the hp caps increases, priests became more powerful, so a heal nerf might be needed, or a weapon/orb with a heal blocking ability.

+

Hot-patched some game issues, improved my workflow to allow more hot-patches like these, manually patched OSX/Firefox to use Canvas instead of WebGL.

+

Improved the design of our new items. Have an items.txt that I'm continually improving.

+

Received some inspiring feedback on Reddit, decided to go forward with the NPC Dialogues and created our first one. Unlike our all-black interfaces, NPC dialogues have light backgrounds, I love them.

+

Receiving feedback about our booster items, the new design is almost finalised, it will likely be a $8 stone with higher Gold/Luck bonuses but less XP bonuses.

+

Improved https://adventure.land/shells. There is a new map in the background. Going to integrate this soon.

+ +
[14/11/16]
+

Today's Feature: CRIT + Complicated Upgrades

+

Added the "Crit" property/logic.

+

Further balanced the PVP, the respawn MP is now 50%.

+

Added the "use_town" skill.

+

Fixed our new/smooth movement routine.

+

Designed + Implemented the first version of the new upgrade system. It ended up being too unbalanced, needs some balancing :]

+

The items retain a hefty history now, exposing this history would spoil the fun, so some hefty game system improvements are needed.

+ +
[13/11/16]
+

Today's Improvement: PVP Balancing + Evasion/Reflection

+

Character names now appear on the browser tab titles.

+

Improved PVP dynamics significantly, xp and gold loss now factors the attacker's xp and gold. Both attacker and target are now blocked from escaping for 3.6 seconds. These improvements make combats more honourable. Considering adding a delay to server hopping too.

+

Added a prompt when a player tries to close the tab during a PVP combat, escaping results in defeat, so this prompt and the accompanying message will raise awareness.

+

Pre-Ordered the new Pokemon 3DS games and re-indulged my fountain pen addiction with a new pen, my morale is fully back up now :]

+

Since I've touched the combat routines, decided to implement evasion + reflection too, evasion is simple, yet reflection seemed complicated, in the end, both of them ended up being simple and fun. They work on PVE too, since all current bosses are magical, the Pumpkin Helmet's from our Halloween event are going to shine :]

+ +
[12/11/16]
+

Today's Topic: It Is What It Is

+

Deployed the improvements of the last 10 days, including the Merchant class, skillbar, chat dialogs.

+

Had to make a lot of restarts, for small improvements, things seemed stable afterwards, went to sleep. - Woke up to only 2 servers alive, Checked Discord, apparently there was a very simple and obvious issue that a player discovered. Normally server exceptions were handled, this issue broke that routine. Revised/Improved exception handling and re-deployed. Now exceptions cost 10 calls.

+

Dealt with a user drama, thanks to a few players, my morale is usually pretty low lately, I keep dealing with same issues over and over again. To not deal with these issues again, wrote this: It Is What It Is

+

It includes various pre-confessions that will let me develop the game in peace, It feels great getting these out of my chest.

+ +
[20/10/16]
+ +
[19/10/16]
+

Today's Highlight: Europas I Down

+

Continuing the Reddit Day, took a break around 2am, I was really exhausted. Around 4am, when I continued greeting new players, RedSky mentioned he couldn't click anywhere, and while we were talking JourneyOver also stated he was never able to click anything, and he thought the game was Code-only. This was extremely worrisome, as in the past, I saw players who never moved and left after a while, It was a serious cause of concern for me. Since our early players mostly weren't native english speakers, none of them mentioned the issue either, they just left. Anyway, after exchanging 10's of emails with RedSky, we pin-pointed the issue, it was PIXI, something was introduced after 4.0.2 that broke all interactions for players with browsers that support "pointer events". I couldn't thank RedSky enough for reporting this issue, and helping me relentlessly during the process. "themoonrat" from the PIXI project also deserves a mention, it's the second time he introduced something into PIXI that turned out to be catastrophic like this. In hindsight, this issue hurt Adventure Land when it mattered the most, our initial boost...

+

I went to sleep, but woke up early, anxiously, during sleep, I was constantly worried about the servers, and when I woke up, indeed, the servers were down.

+

When the server went down, players defaulted to Europas II, which was a PVP server at the time, and they got wiped out, a lot of players thought the game was pvp-only during that time. After this experience, I improved the server selection logic, to prioritise PVE servers over PVP.

+

Researched why the server went down, the most logical explanation is extreme load, since the game has "Observers", even if people don't login, each visitor adds a load to the server, it seems, along with ~100 players and 100's of observers, Europas I just gave up.

+

Spent most of this day interacting with players, replying to emails and messages.

+ +
[18/10/16]
+

Today's Highlight: The Reddit Day!!!

+

[01/12/16]: Writing these lines, more than a month later, let me state that [18/10/16] was a monumental day for Adventure Land. The day didn't start well, but in the end, It ended up being a day I will always remember.

+

Discovering the email issue the day before, my morale was down, I started integrating Amazon's SES, and email integrations are usually very challenging, it involves DNS changes, integration, testing, custom systems to send emails in a robust manner. Luckily, the integration+testing parts were a breeze. I also had existing routines that sent a small amount of emails from Amazon SES, that helped too.

+

Improved the recruits system, as I hoped the Halloween Event would create a rush, added/integrated new internal systems and added "Your Recruits" to the menu.

+

Converted our .wav sound files to .ogg's. While the Sound/FX system is experimental, no need to make people download huge .wav files.

+

Integrated the "Pumpkin Helmet" Jayson designed, this was another moment I will always remember, he really made me proud, he was aspiring to become a pixel artist, yet, I wasn't expecting results this fast. The "Pumpkin Helmet" ticked all the boxes, simple, good use of colors, looks great. Integrated it into the game, added "Reflection" as a unique stat.

+

Fixed our new Ranger/Warrior characters, they had 1-2 pixel issues that were only noticeable when they walked.

+

Added the "Fancy Pots" NPC to the Spooky Forest. Added the "Pom Pom"s. Calibrated the drops one last time.

+

Finally deployed the game, made early tests, and triggered the email sender routine. Checked the logs, and got devastated when I found out about the 14 emails/second limit Amazon SES has, most of the emails were wasted, and since I didn't track email routine completion, there was no easy way to retry. If I retried, some players would receive the email twice. Devastated, I went to sleep.

+

Woke up around 8PM, our regulars were enjoying the Halloween Zone, spent some time with them, I wasn't sure whether I should retry the email routine, started browsing Reddit, got the idea to announce the game on r/mmorpg, It was something I was planning to do, but not this early on, however, I really wanted our new Halloween Zone to be enjoyed and remembered, so I just prepared an introduction, from the bottom of my heart and posted it: https://www.reddit.com/r/MMORPG/comments/5855bd/adventure_land_an_mmorpg_in_which_you_can_code/

+

It was an impulse decision, normally, I prepare and obsess over announcements like these. I wasn't expecting such a positive feedback. From the first moment I posted, people started appearing on Europas I, greeted everyone individually, It was so very exciting. I really wasn't expecting such a positive turnover, people seemed to be loving the game, embracing the Code, asking questions, making suggestions. It was truly an "It's Happening" moment for me. Time flied.

+ +
[17/10/16]
+

Today's Feature: Announcement Emails

+

Implemented an email system to email all players. Created a Halloween Event announcement email.

+

Added the Str/Int/Dex amulets. Improved Mr. Pumpkin. Polishing the zone, monsters, drops. Added the "Ghost".

+

Added the Tier3/4 Armor Drops to the Armor Box.

+

Discovered that App Engine's mail deprecation affects the game too, can't send all those emails tomorrow, I'm deeply saddened and worried.

+ + --- + +
[16/10/16]
+

Today's Highlights: Ms. Dracul + Mobile Improvements + Low-FPS Improvements + Improved Interactions

+

Added Ms. Dracul, Improved the Halloween Zone.

+

Improved the gameplay on mobile devices, fixed some minor issues, the web version isn't supposed to be played on mobile devices, yet, it doesn't hurt to polish things a bit. Imporoved draw routines to support sub-60fps framerates. Previously, timings always assumed FPS around 60. Currently, they are based on milliseconds.

+

Improved the Inventory interactions, previously, click events were dynamically added, moving to static events, to increase performance and simplify things.

+ +
[15/10/16]
+

Today's Feature: Transport NPC: Red Lady

+

Moved the party invites to the left, tested Jayson's ranger+warrior, some pixels need to be fixed, going to fix them soon.

+

An extreme amount of thinking on Clans/Guilds.

+

Created the Transport NPC, added the orange snakes to the Halloween map.

+ +
[14/10/16]
+

Obsessed over a resizing issue for hours, even wrote a custom routine to manually resize images in a pixel perfect way, no matter what I did, the result was the same, turns out, the image I was trying to resize had 3x3 pixels for each actual pixel, and I was dividing by 2, instead of 3, wasted 2 hours like this, but on the bright side, got to acquire skills to manually manipulate/create images with code.

+

Updated our map tilesets and refactored our maps.

+

Improved the skillbar prototype, tested PVP, the movement routine improvements worked. Started designing the Halloween zone, updated these logs.

+ +
[13/10/16]
+

Today's Feature: Ancient Computer

+

Jayson prepared new Ranger and Warrior looks, again, very impressive.

+

Inspired by his work, I created the Ancient Computer myself, it was super fun, If I had enough time, or, if we had enough time, like 1-2 years, Self-sufficiency in terms of pixel art would have been possible.

+

Reference, Dolch Computer: https://www.google.com/search?q=dolch+computer

+ +
[12/10/16]
+

Today's Feature: Skillbar Prototype

+

Another slow day, updated my iPad to iOS10, to test stuff on iOS10.

+

Created the first skillbar prototype, items can be dropped onto the skillbar.

+ +
[11/10/16]
+

Jayson designed a Quiver, I was very proud, it was beautiful, we started using Aseprite earlier, I think Aseprite inspired him.

+

Decided to make Quiver upgradeable, instead of compound like the Mage offhands, the distinction was unclear, I decided to determine the upgrade/compound difference based on size, small items should be combined. Combining 3 books make sense to me, yet combining 3 Quiver's doesn't.

+

Added Supershot, Ranger attack animations, set the line colors, integrated and calibrated all of Ranger's stuff.

+

Spent some time outside, checked out a house, want to have my own home, maybe start a family one day.

+ +
[10/10/16]
+

Today's Feature: Supershot

+

Today was a slow day, Improved Rogue's SNEAK! attack, added the damage modifier.

+

Updated the game, collaborated with Jayson, improved the conversation with Ellian, announced the Rogue class.

+

Added Supershot to Ranger's as today's feature, brainstormed possible recruitment rewards, level based rewards are pretty challenging.

+ +
[09/10/16]
+

Today's Feature: Class Previews at Creation

+

Working on the orb design, 3X Orb's just doesn't seem nice, it's too lazy, had the idea to convert one Orb to an Elixir slot, it will be a long-duration booster potion.

+

Brainstormed various alternatives for stats/attributes, decided not to add Vitality for now.

+

Added the "Quiver" item, improved character deletion, tested shadows for disappearing texts.

+

Experimented with class previews at character creation, the idea developed quickly, completed all classes.

+ +
Slowly catching up with the earlier logs [14/11/16]
+ +
[08/10/16]
+

Today's Feature: Ranger

+

Checked the halloween map, perfect, opened a dialog with Ellian.

+

Researching the Ranger on a philosophical level, decided to let Rogue equip a single Warrior weapon double-handed, and similarly, allow a Ranger to equip a single Rogue weapon double-handed.

+

Added the ability to create 5+ characters.

+

Added the welcoming CODE comment to encourage new players to learn coding, to make it all more welcoming.

+

Added the Ranger class, the Bow, the attack animation, started playing and balancing a Ranger.

+

Added multiple Orb's to test the dynamics. Implemented the orb dynamics, so only unique Orb's can be equipped.

+

#NEWIDEA: A potion that replenishes both HP and MP, I should remember this one.

+ +
[30/10/16] WHEW ...
+

It's been the most exciting, joyful, interesting, stressful, productive 12 days I've had in ... probably years ... It all started with: https://www.reddit.com/r/MMORPG/comments/5855bd/adventure_land_an_mmorpg_in_which_you_can_code/

+

I was hoping, but wasn't expecting such a rush, going to pay my logs debt soon, I have the habit of taking regular notes, so at one point, I'm going to re-visit and summarise the story here

+ +
[07/10/16]
+

Today's Feature: Rogue!!

+

I've been trapped in the "Next Feature Fallacy" loop once again, I know that the game needs more adventure, events, the launch of the new maps that Jayson prepared, but it's easier to make/build/add other things. (Also new players, friends system etc. to keep the momentum going)

+

Re-Calibrated the XP/Level dynamics. After Level 70, Things are ever slightly harder now. A Level 70 Character becomes pretty agile, A Level 80 Character is pretty over-powered. So I think this hardness is deserved. We can always re-balance the dynamics and refactor existing users, so I shouldn't worry too much.

+

Started designing the new items, pixel art became a bottleneck. Emailed @ThisIsEllian - I admire his work on pixel items. It would be nice to have him onboard.

+

I've talked to a lot of players by now, received feedback, they asked questions, but, interestingly, no one asked about the "3 Unknown Slots", well they are Orb's, tested some alternative Orb's today, felt the balance, thought about the dynamics, not sure I'm going to keep to the original idea of adding Orb's as items. Postponing this decision.

+

And, today's highlight, Rogue!! - Added the Rogue class, which uses the already available Invis ability, and an accompanying "Claw" item, It's a fist weapon, no daggers yet. :]

+ +
[06/10/16]
+

Today's Theme: Endgame Re-Balancing

+

Without piercing properties, 950 armor = 95% Reduction in Physical Damage, 950 Resistance = 95% Reduction in Magic Damage. So, the challenge is, all armors should be useful, relevant, yet it should be challenging to get close to high armor/resistance levels. Ideally, ~50% should be achievable by a dedicated player who plays the game for weeks.

+

Completed and ~balanced the armor tiers today. Also adjusted the res./armor/speed/hp gains of classes. Increased the hp gain by level.

+

Ideally, a warrior shouldn't one-hit a mage and the current dynamics are balanced, maybe not super-well-balanced, but at least it's fun-balanced.

+

Added new features to our in-house map_editor. It has various zoom controls now. And some performance improvements thanks to pixel-perfect TilingSprite's.

+ +
[05/10/16]
+

Today's Feature: Tier 1/2/3/4 Armors

+

Preparing the rogue class. Decided to push the game design further. There will be 4 main tiers of armors, this applies to the resistance and armor dynamics. For example the "Dracul's Cape" is a Tier2 Chest armor. Unique armors like these will most probably be Tier3 at most, since they have additional properties.

+ +
[04/10/16]
+

Today's Feature: "Your Recruits"

+

Added passive character abilities, currently only "Stun" is adopted from the weapon. Implemented the actual "Stun" ability today, the logic, the effects, everything. I guess I can add "Crit" as another passive ability soon, maybe from a specific ring.

+

Pushed both "Stun" and "Curse" as far as I can take them, both for players and monsters.

+

Updated these logs, I hadn't synchronised them since 26/09, so this was basically a debt-day.

+

Viewed Jayson's second version of the town map, he surprises me with every new thing he shows, I really wasn't expecting an iteration of the town map, I just got used to the first version (which is actually, maybe the 5th iteration, but at least it was the first version of that iteration up until now). Now the beach has large trees. The upgrade/compound house is bigger. I'm still not sure whether I preferred the original version tho.

+

Today's feature is actually more of a word, "Recruit", rather then "Refer/Referral". "Recruit" is a cool, game-worthy word, I hated "Refer".

+ +
[03/10/16]
+

Today's Feature: Tiny Crab's (and in future, Spiderling's)

+

Added "Crab"s to the beach, but they are really huge, so, instead, shrinked them to half their size as "Tiny Crab"s, the actual "Crab"s are now "Huge Crab"s, because they are huge, and not cute.

+

PIXI has a new TilingSprite improvement, by Ivan, tested it, it seems Adventure Land is going to get a HUGE performance boost once it hits the production build. Great news. Currently all tiles are individual Sprite's. As TilingSprite quality was much inferior.

+

Calibrated "Tiny Crab"s. It's actually challenging, they are irregular, compared to other monsters, the Sprite's are shrinked in half, I decided to take the easy route and fit them in manually for now, works great.

+

Re-Visited the walking/line routines. Inner corners were challenging, they amplify the shortcomings of the design. I re-wrote the boundary logic a couple of times, in the end, made a patch, seemed to work, I'm settling for now.

+ +
[02/10/16]
+

Today's Feature: New Attribute: Armor Piercing (and Resistance Piercing)

+

I really like "Armor Piercing", added it to the "Spear", makes a lot of sense too, since a "Spear" could pierce an armor. Practically, 50 armor piercing, increases damage by ~5%, which is a lot.

+

Picked up the "Random Looks" logic, fixed it, improved it, verified it.

+

Implemented "skin"/"Looks" selection, it works, yet I need to add a client routine to update the looks for both the player and others nearby.

+

I'm really worried that people will feel cheated by "Random Looks", you might prefer a male look, but you can also get a female look, I considered letting people choose/buy a specific look. Still not sure. I personally like chaos, taking my chances, so It's probably best to stick with the current dynamics.

+

Added new routines for checking the "disable" flags, like stun, .rip etc. Improved the CODE too.

+

Imported Jayson's town as "main2", It will exist along with the current town for now.

+ +
[01/10/16]
+

Today's Feature: First Item Ability: Stun!

+

A new month reminds me of the passage of time, I don't like it, It would have been great to just enter a time dilation field, build a product, get out of the time dilation field, show the world the product. Get in the time dilation field again, cry a bit, revise the product, and cram the entire process in a day. And maybe a solution to the ageing issue while we're at it.

+

I think I'm just adding a new feature every day to procrastinate, so I asked the regulars what they thought about "Item Ability"'s, so basically I asked Aiek and Oragon, they were around at the time, they both liked the idea. I like it too now. It ~complicates the game, but let's hope in a good way.

+

Mostly added the ability to the "Item" sheet, and added the "Stunned" animation today, and the upgrade dynamics, when the item is upgraded, both the chance and duration increases. The "Basher" item makes more sense now.

+ +
[30/09/16]
+

Today's Feature: Defeat on Escape

+

This was more of an ideas day, Added a "SHELLS" UI/Info to premium items. It seems, just having the "SHELLS" button on inventory was a mistake, most people just don't discover it.

+

Generated many improvement ideas, most are related to Premium Items, and how they need to look, I Just stopped liking my placeholder/improvised images. Going to turn these items into variations of the "Tome of Protection" image/design that I love. The tome with different scriblings on them.

+

Found/Reported an Electron bug, Researched browser notifications. Chrome notifications are more complex than I thought. The background listener part. Going to pull the trigger and start integrating at one point tho.

+

Added "Defeat on Escape", basically, on PVP, one emerging method was closing the browser just before escape. Now the player is auto-defeated when this happens, within the PVP-block duration.

+ +
[29/09/16]
+

Today's Feature: Curse

+

Today was a busy day for me, not in a good way, I need to enrol in a university every semester, for reasons specific to my country :[

+

We improved the "Mystery House" design with Jayson, he was already working on the rooms, but it seems we needed to synchronise. I got the chance to improve my design.

+

Implemented the "Curse" ability for Priest's. It's a first on many fronts. The attack routine was improved with amplifications, de-amplifications. Integrated it with animations, added a custom line color, added a custom filter to change the cursed entity color. Added a "[C]" indicator to the focus interface. The curse both slows, reduces attack and increases damage taken. Especially useful for PVP.

+ +
[28/09/16]
+

Today's Feature: Merchanting! with "Merchant Stand"s + "[AFK]"

+

Well this was a productive day.

+

Implemented the "Charge" effect that leaves disappearing clone's in it's wake.

+

Started experimenting with trade carts, drew one from scratch, didn't really fit in well with the game, It looked like an arcade cabinet tho, so that was a plus. In the future, when there is time. There will be around 12 unique trade carts, or merchant stands as I finalised the naming.

+

Added the "[AFK]" notice and logic. There are a lot of players who use CODE, when new players visit the game, if they don't see that those players are afk, the first impression isn't well.

+

Adjusted a wooden box to be the first "Merchant Stand", it looks great, fits well into the game, when a player opens the "Merchant Stand", it's like the player is a Trade NPC. :]

+

Added "Trade History", integrated it to the "Merchant Stand" item, previously it was a mystery who bought items, now the Trade History logs the last 40 trades.

+

Implemented a speed recalculation logic at both server and client, this is a revelating improvement, as dynamic speed adjustments are super practical now. It was needed for Charge, Curse abilities too.

+

http://adventure.land/img/merchant.png

+ + +
[27/09/16]
+

Today's Feature: Charge

+

Another day, another map_editor improvement, with similar specs, I can open 10X+ map_editor's on Windows/OSX, but Jayson always complains of the performance, anyway, normally, since map_editor was going to be an internal tool for myself, performance wasn't a concern, but it sadly became a concern, this last improvement adds texture caching, pushing the performance close to maximum levels with this draw-all architecture. It's also interesting that a GT750M on OSX can handle 10-15 things at once at 60fps, yet a GTX960 on Windows can't do one.

+

New Item: Earring of Dexterity + Improved the Pumpkin Helmet item, mainly the 16x16 image. Getting better at pixel-art, at least I hope. My biggest mistake it using too many colors and not having a palette. Going to stick to few colors on my next try.

+

New Ability: Charge for Warriors

+

Received/Inspected a bug report from a player, Teoman, he found a way to consistently go outside the boundaries, it seems inner corners are easy to break-free from.

+

The new maps are progressing well.

+ +
[26/09/16]
+

Today's Feature: Random Looks Routine

+

Improved/Patched many of the server routines. These improvements are to make the game glitch-free, and in-future, abuse-free.

+

Calibrated Boss cooldowns and drops. Implemented the "Random Look" routine internally, this routine will give player random looks. It will be integrated to the "Looks" NPC.

+ +
[25/09/16]
+

Today's Feature(s): Dracul's Cape + Lifesteal + Basher

+

Added a new item, "Dracul's Cape", this is a major change for the game, decided to add random/rare drops like this for most bosses, monsters. The cape has +HP that benefits Mage's/Priest's significantly. The "Lifesteal" attribute is new too. Very small for the Cape, as attributes are cumulative.

+

Added the "Basher" item, and the "Weapon Speed"/"Slow" routines. "Basher" adds armor, it's the first two-handed weapon, would be ideal for Tank's.

+

Made a lot of internal improvements, testing, fixes for the new additions, overall this was a productive day.

+

Side Note: After reading my own logs, and writing this /logs summary on [03/10/16], I wonder whether I should let go off my productivity obsession, yes it produces short-term results, but I can't help but wonder whether it's worth all the stress, in the long-run.

+ +
[24/09/16]
+

Today's Feature: Character Operations

+

Slow day, mostly minor improvements, Improved login/selection, Added "Character Operations" and Implemented character deletion.

+ +
[23/09/16]
+

Today's Feature: Referrals!

+

Mostly fixed newly introduced issues today. Improved/Simplified the shutdown routine of the server, It's much cleaner/simpler now. Reviewed the bank routines, found/patched another possible loophole. I want to be confident that the bank transactions are solid now.

+

Struggling with game and map design, the "Newcomer Experience" is extremely important, the new maps are beautiful, yet I'm not sure about the main town design. I'm also unsure whether the town should be stand-alone and players should teleport to different zones - or whether the main town should be super-large that houses multiple regions in one map. Probably something in between. A large but not huge main town.

+

I don't know whether it's the case, or just what I feel, but user acquisition is a real struggle in the age we are in. Things weren't like this, let's say, 5 years ago. My solution is to give players something for helping the game grow. While I have a very humble ad running, the real growth is from player-to-player sharing. People enjoying the game and inviting their friends. So my strategy from this point forwards is to give SHELLS to players for inviting their friends, hence the "Referral" system. I might find a cooler name for it.

+

Also briefly started the "Achievements" system, and debating "Quests" with Jayson, I honestly can't think of many meaningful quests. In almost all online games, quests are sugar-coated grinding, so I was against quests originally. Not anymore tho. I feel like small/local quests could add some color to the game.

+ +
[22/09/16]
+

Today's Feature: Tome of Protection!

+

So PVP is super-fun. Yet it's a bit extreme, you currently lose 4% of your XP on death. If you are LV.60+ - that's a lot of XP. This "Tome of Protection" costs 20 SHELLS, significantly reduces the XP loss, and to make things fun and fair, on PVP, the opponent gets 10 SHELLS if a Tome is consumed.

+

Applied a simple fix so the game can handle "disappear"+"reappear" on the same frame. Otherwise due to the design it wasn't an easy problem to fix. Updated PIXI, made some small improvements, patched the `.destroy` routine so it doesn't cause crashes.

+

Aided Jayson on the issues he was having, the new maps are finally progressing well. Not having to worry about the map design aspect of the game is a relief.

+

Side Note: I'm an OSX User myself, It's sad that Windows/Hardware field is still ridiculed with various repeating issues, it forces everyone to become a superuser, maybe it's a good thing, but It's definitely not easy.

+ +
[21/09/16]
+

Today's Feature: PVP Servers!

+

Americas/Europas II's weren't too useful. The 6-people PVP Arena limit is mostly too much early on. So decided to make the II's all-pvp servers for now. With higher "Luck"/"Gold"/"XP" gain stats.

+

Started catching up on the "Development Diary", the last update was on [05/09/16], I REALLY need to do some things daily, It's really hard to generate proper updates, especially social media, hate social media now. Intending to create a GIF with some abilities, disappearing lines soon, and to announce the PVP servers.

+ +
[20/09/16]
+

Today's Feature: Mana Burst!

+

Implemented, Calibrated the "Mana Burst" ability for Mage's. Added a custom animation and a custom disappearing line. When used, it converts half the mana to damage. It's intended to be used during PVP. I find the ability pretty balanced. It's only super-useful for 1V1 encounters where a Mana Burst is enough to kill the opponent. After the burst, a pot usage is needed to attack again. The ability doesn't affect the attack cooldown.

+

Added the "A"/"Q"/"R" keypresses. "A" is Attack, "Q" is Taunt for warriors, "R" is mana burst for mages. "Q"/"R" are misc for now. The game doesn't have official abilities yet.

+ +
[19/09/16]
+

Today's Feature: Taunt

+

It's a ranged attack for warriors, inflicts only one damage, but prevents the opponent from escaping and taunts monsters.

+

Re-written/unified all the attack routines, both PVE and PVP, I love refactoring, this simplifies things a lot, especially for abilities.

+

Disabled Stripe for now, I need to refactor servers to use secure connections, it's not trivial, I'm also unsure whether the overhead is significant. The practical Stripe UX I implemented just used an overlay on top fo the game, so it was HTTP, against Stripe's rules. For now Super Rewards seems more than enough.

+ +
[18/09/16]
+

Finally caught the bank issue, it was more extreme than I thought, on one side, I'm glad that it was an obvious issue, on another side, It's a shame that I let such a major issue pass. It happened because I was improving the synchronization routine, jumped onto something else, then left a simple yet deadly routine in place. Basically, every 5 minutes, the bank was automatically unmounted. So if a player got into the bank, wait 5 minutes, took everything, those items/gold would still be there.

+

I had improvements in-mind that would push the bank routines from 99.5% to 99.99% (hopeful, made-up numbers) - so I ended up making those. Now it seems almost impossible to cause a discrepancy. Even in extreme circumstances.

+

Found and started investigating a serious Electron issue, It seems it could be related to the CODE issue I was experiencing myself. I use OSX, most players are on Windows, so the issues are not always shared.

+

No "Today's Feature" today, but the bank issue was pretty major, and the fix/improvements were hefty. #TODO: Review all trade routines once more

+ +
[17/09/16]
+

Today's Feature: Invis!

+

Improved/Finalised the PVP Indicator UI. Started designing the "Friends" UI/UX. It's not simple yet. It should be simple and fun.

+

Implemented "Abilities", "Invis" is the first one, and probably would be the most challenging one, but it turned out pretty simple. When the "Assassin" class is added. The "Invis" will be their edge.

+

Improved, Simplified, Extended the character effects/filters. Like the existing item-glows, invis fade-away, etc.

+ +
[16/09/16]
+

A lot of minor things, some post-deployment stuff, where issues pop-up.

+

Experienced a bank dejavu, I wasn't sure, but it seemed like the bank rolled back. Extremely concerning. Trade routines have to be flawless. I investigated but couldn't reproduce.

+

Decided to add a major, or rather, significant, preferably player-facing feature every day, as I feel like the progress is slowing down.

+

Today's Feature: PVP Hit Indicator + Escape Prevention

+

Basically, when you get hit, your name becomes red and the indicator fades away, you can't TOWN or Escape when you are hit, so the PVP is now more fun :]

+ +
[15/09/16]
+

Another Productive Day!

+

Improved and completed the Stripe payment system integration+UI/UX/logic. I love how Stripe makes credit card payments simple.

+

Implemented a simple Mapping routine, as the Map in Mapreduce, I love to reinvent the wheel whenever possible, especially for data processing. The mapping routine for Adventure Land is both super simple and robust.

+

Added "SHELLS" drops to monsters, gems. Completed and deployed the premium currency of Adventure Land. A monumental day.

+

Tested both payment routines myself, made fixes, improvements, calibrations.

+

I play the game as any other player, so while the premium items existed, I didn't/couldn't get any, this was kind of the reason why I launched SHELLS this early, to get some premium items myself as I couldn't wait any more. I set the game to give me 200 SHELLS every hour. To experience the dynamics first hand.

+ +
[14/09/16]
+

Implemented the "Noob Mode", one of the main issues of the game is that people don't interact with interfaces too much, to see what does what, back in the day, game interfaces was cryptic as hell, nowadays, smallest challenge and you lose a player. So this mode puts INV/CHAR/STATS/GUIDE buttons to the top. While the "Pro Mode" replaces them with CODE/PING.

+

Improved the Stripe integration, Integrated Super Rewards, so far Super Rewards seem great, very easy to integrate, simple, clean, it looks like there are many free offers too.

+

Pixel Art/ist research. Got some inspiration.

+ +
[13/09/16]
+

Minor bugfixes, improvements. Created the "Amulet of Mystery". It will be a rare drop from the "House of Mystery". It has various stats + evasion/reflection. Properties that don't exist yet :]

+ +
[12/09/16]
+

Today is my birthday, getting old, birthdays are stressful now, to me, they indicate another passing year without an achievement. My goal in life has become seeking success through products I built. Not healthy, maybe not logical, but it is what it is. My time with Adventure Land was rejuvenating tho, without Adventure Land, things could've been harder.

+

Calibrated/Improved the new monster aggression routines, disappearing lines and the new server/client data routines.

+

Improved the login/selection interface, Added "Last Update Notes".

+

Jayson was having issues with the map_editor, tested various alternatives, none seemed to work, so we invested in a new laptop.

+ +
[11/09/16]
+

Super Productive Day! I needed one.

+

Added flexible+persistent properties to characters. Not used yet, but will be needed when there are daily events, multiple looks, options etc.

+

Implemented "Aggressiveness". This is a simple yet major update. The underlying system is also remarkably efficient, otherwise it would have been costly to make each monster find someone to attack whenever it's able to do so. The same system/method/data-structure might also increase the game performance significantly at a future rewrite -but- the main movement/map logic is much more complex for this method to be easily accessible. I got the idea from Geobird, it's "geo-hashing", both simple and efficient/effective when calibrated.

+

Refactored the monster+player information routines, initially, things were excluded, this made it easy to develop the game, now, things are included, so each property that are sent to clients are manually added to the list.

+

Added a new "is_in_front" logic, so monsters only show aggression towards what are in front of them, the same check could be added to other things too, but things are fun the way they are.

+

Disappearing Lines! There was no way to know who attacked who before. I initially didn't like these too much, now I can't imagine the game without them. I like scripting a party with CODE, now it's much more enjoyable, watching the interactions through lines :]

+ +
[10/09/16]
+

Met "Zenn" in-game, we literally debugged an issue together for 3 hours. The inventory was never shown for him. Which is bizarre, as I keep the UI as simple as it goes. For whatever reason, the `position:fixed` inventory never showed up for him. I researched, deployed alternatives 10's of times, he tested and tested, it never showed up - And this is on Chrome, his solution was to use IE. - I ended up re-creating a unique inventory each time, instead of using an existing "div", that solved the issue. - The cause is still a mystery tho, in hindsight, I neglected to ask whether he had any 3rd party plugins.

+

Made some other drag/drop, item related improvements.

+

Created the first custom map animations, a small fire, iterated it, added a blue version too. Then tested some lava/fire pools. I love pixel animations, the game will be filled with them in the future.

+ +
[09/09/16]
+

Found a bank issue. Added retry+fail logic to the bank routines, and other routines while at it. Improved the character start/sync/stop routines. Fixed some newly introduced bugs.

+ +
[08/09/16]
+

Sick day, took care of some external things I needed to take care of in the meantime. Overall ~3 days affected, yesterday, today, ~tomorrow.

+ +
[07/09/16]
+

Explored the casino/tavern options a bit. I want the game to have a communal place for chance games, nothing serious. just a place in a 2D pixel world where people could hang out casually. Such a place should have basic but fun games. Some single player, some multiplayer.

+

Wrapping up the bugfixes, research, testing.

+

Started feeling dizzy, It happens ~every 3-4 months, when I don't eat healthy for extended periods of time, I've been addicted to Wasa bars lately, you would expect it to be ~healthy, but apparently not.

+ +
[06/09/16]
+

Added an "Under Mode" to the map_editor, really eases the map_editor usage and extends it's capabilities.

+

Started inspecting/improving the right click logic, currently it's pretty complicated, the game is 2D, when a character shadows a monster, in some cases the click should propagate through, but in certain cases it shouldn't. Tested things for hours, it seems I need to modify/extend the existing PIXI Interaction routines at one point. They mimic DOM Events 1:1 and it's not a good thing.

+

Side Note: I could've never imagined 3 months of game development could extend my horizon this much

+

Side Note 2: Since in the past I've lost so much time with minor issues/obsessions like these, I try to improve as much as I can and move on fast, but still, each issue can still consume 1-2 days

+ +
[05/09/16]
+

Mostly catching up with things, small fixes, I really need to do some things daily, like updating these logs, and preparing game updates/screenshots.

+ +
[04/09/16]
+

Completed the bank, a proud moment.

+

Perfected the drag/drop and right_click routines, another proud moment. Now drag/drop and right_click works everywhere, internally things are much simpler too. These routines are so robust now that I feel like I can utilise them when the time comes to build iOS, Android versions of the game. +

Improved the "auth" and "transport" routines of the server. Patched the game so re-calling some routines are safe. So it won't be possible to cause glitches whether intentionally or unintentionally.

+

Improved the map_editor to ease working with "entities", which are 3D. Probably not the right term, but basically they are things that you can also get under, like statues, trees, houses, gates. I used them sparingly, as I didn't optimise the tiling routine to dynamically add/remove them, Jayson enjoys using them wherever possible, results in a more lively map.

+

Deployed the bank!: http://adventure.land/img/bank.png

+ +
[03/09/16]
+

Started working with Jayson, it seems I neglected to give him a proper tutorial on how to use the in-house map_editor, features, limitations, how to design with these in mind etc.

+

Tested his "worldmap", while impressive, it had too many overlapped tiles, an unnecessary performance hog, but, on the bright side, the map inspired me to improve the map tiling routine, it turns out PIXI children are an array, so batching the deletion improved the performance significantly, luckily this was possible without any modifications, since all map entities were naturally adjacent.

+

Made other small improvements to tiling, and generated some major improvement ideas, It's super challenging to cram everything to 16ms, to keep the game flawlessly 60ms, even a 20ms frame is noticeable. The next improvement will involve pre-calculations.

+

Started inspecting a CODE issue, it seems to only affect me, might be a Chrome bug, various elements of the iFrame doesn't load most of the time.

+

Added "signs" to the game! - The first one is for the "Offshore Bank" :]

+

Implemented the Gold NPC, and "withdraw"/"deposit".

+

Designed the bank map, the counters, interior design, I just love the bank.

+

Started implementing the item storage routines, completed the "swap" operation, which happens between the inventory and storage.

+ +
[02/09/16]
+

Implemented the internal bank connections, persistence, server logic. All trade systems have to be flawless, even the smallest oversight could devastate the game economy.

+ +
[01/09/16]
+

Deployed the improvements, fixed the initial issues, re-balanced the pvp zone, increased gem drops

+

During the last few days, the "Bank" design in my mind became clearer, started implementing the internal systems

+

PVP(Zone): http://adventure.land/img/instances.png

+ +
[31/08/16]
+

Added the pvp announcements, logic, starting to wrap things up, re-calibrated drops, valuations.

+

Created "Skeletor", the boss of the pvp region, he's super tough, but very kiteable by mages, however, since the region is PVP, a warrior can suprise and "pwn" the mage, so I feel it balances things.

+

Made some small fixes and improvements, mainly to the items system. Overflowing the inventory was possible, it was even a feature in the early days.

+

Experimented with "Bitmap Text"s - fonts converted to images, going to convert names to bitmap texts at one point in the future, probably.

+ +
[30/08/16]
+

Created a new internal system that I call "ACCESS", I build systems like these for all my projects (basically Geobird and Adventure Land), existing systems are Renderer, Executor, Viewer(s), this one is new, it gives practical remote access to the game server, a running process. I couldn't find a cooler name for it yet.

+

Created the first "Live NPC" - so basically a NPC that is technically a player, the pvp blocker NPC will be live, he will move from the cave entrance to the revival zone when there are enough players for the pvp zone to unlock.

+

Created the "Priest's Mace", along with the image. Created a new pants image.

+

Finalised the "Tier 2" armors, they will drop mainly from the "Armor Box", named them with "Sturdy" and "Rugged" prefixes, "Leather" would have been more appropriate. Going to rename and re-style them in the future.

+

Added a "Spear" to the game, can only be equipped to the mainhand of warriors, compared to a "Blade", has a much higher range.

+

Created the images of "Armor Box" and "Weapon Box" (Also "Jewellery Box", to-be-launched)

+

NOTE: Starter items intentionally don't look super cool, I'm unsure whether I should make them look cool, probably not, I plan to make rare items look cool.

+ + +
[29/08/16]
+

Fixed a bug that eluded me for some time, along with the bugfix, made some performance improvements to the mapping, the bug occurred when a tile had uneven width/height.

+

Improved and highly simplified player right clicks, Implemented "PVP Death Loss" dynamics, currently both xp and gold are transfered.

+

To procrastinate, completed the "Names" feature, now, whenever "N" is pressed, names show up. A needed feature but it wasn't crucial. Perfecting the text rendering is super challenging.

+

Created the "Tiny Ruby" for the pvp zone.

+

Created "Irradiated Goo"s - The game will become 50 Shades of Goo's when I'm done.

+

BIG UPDATE: Jayson is now a part of the team, or this one man operation now becomes a team, in the short span of 2-3 days, he designed remarkable map entities. It's great to have someone to work with. "Map Design" was a heavy burden for me, It's a form of art that one needs to dedicate him/herself to. Not simple, as I plan to mature the game in 6 months, and we are already 3 months in. (1 month start, 1 month development, ~1 month since the launch)

+

WOW, just realised it has been a month since the launch, we've come a long way since then, I see the game as a community now, met a lot of people, made a lot of friends, my entire vision changed, and not just about the game too, about life in general, about development. Let's just say I'm more hopeful now, about many things :)

+ + +
[28/08/16]
+

Improving the PVP region, dynamics and the surrounding routines

+

Community member Jayson, a.k.a Oragon/Premier shared his first map, It was incredibly promising, and motivating. Gave me a lot of hope for the future of the game.

+

I realised I should do what I do/enjoy the best and collaborate with others who are better at things I struggle at. In this regard, the "Community Map Editor" proved to be extremely useful.

+ +
[27/08/16]
+

Improved the "main" map / cave area. Tested alternative map designs. Started implementing the new PVP region that unlocks only if there are enough players around.

+ +
[26/08/16]
+

Fun day for me: Refactoring

+

Implemented "instances" to replace "maps", this new system isolates maps, increases performance, also allows things like "dungeons", spontaneous server events, solo zones, party zones, and so on. :]

+

Created the first test dungeon, "dungeon0", it was a joyful moment, no bugs, It just worked (It's a small rectangle with some Goo's)

+ +
[25/08/16]
+

Implemented the "Stone of Wisdom/Luck/Riches" dynamics, calibrated, created images for the stone's (used Primordial Shard as a starting point)

+

Started implementing a "Community Map Editor"

+ +
[24/08/16]
+

Tested some new routines to improve the map performance

+

Created the "Stone of Wisdom", along with "activate"/"morph" capabilities

+ +
[23/08/16]
+

Tested/Improved the new routines, Implemented new internal interfaces

+

Added a re-focus routine to the game, when the browser window is re-focused, the monster/player focus was lost, now it's recovered.

+

Balanced monsters and drops

+ +
[22/08/16]
+

Pursued the implementation and integration of the new event/backup systems.

+

Implemented new payment routines and interfaces, Improved the existing ones, going to roll them out with the next major update.

+

By design, Adventure Land isn't pay to win, the current progress of the game is proof, as everyone who got to know the game is both enjoying the game and learning a lot from the experience.

+

The addition of "SHELLS" won't change this, on the contrary, If there is inward cash flow, I will better be able to promote the game when the time comes, and strengthen the community.

+ +
[21/08/16]
+

The day started experimental, improved SFX a bit, created a Slack community for contributors, created a community map editor, the game needs another community tho, might create a forum.

+

Started implementing internal event and backup routines, for analysis and disaster recovery

+ +
[20/08/16]
+

Became really obsessed with the memory leak and performance issues. Re-Visited every single routine available. Made a lot of improvements, found 2 major things to fix. They weren't the cause of the major leak.

+

After eliminating everything, started introducing things one by one, Text's turned out to be the leak source, the disappearing texts in game, manually patched the issue and reported it to the pixijs project.

+

While I was at it, tested several new methods that will improve the game performance, but decided to delay these endeavours, gameplay should come first, the game is already 60fps in most systems.

+

Added shadows to the maps, still experimental, first usage is in the cave.

+

First event designed: "Goo Brawl"! :] Everyone is teleported to a small island with Super Goo's that have super drops. 5 minutes.

+ +
[19/08/16]
+

Started hunting memory leaks and performance issues.

+

Designing a new map and new server events

+

Disabled the chaotic cross-party +XP messages, where the +XP would show up on every member of the party, it was initially cool tho, I will later add it as an option.

+

Stackable items can now be traded, individually.

+ +
[18/08/16]
+

New NPC + Feature: Gems + Exchange. The first gem, "Raw Emerald" drops from any monster. It's super rare tho.

+

First game refactoring, refactored item formats and routines, there were no casualties, it was a smooth operation.

+

Rare items and high-level items are "High Grade" now, added new "High Grade" upgrade scrolls and a new "Dexterity" scroll. The dexterity scroll is pretty fun, there are no dexterity classes yet, however, if someone is farming bee's, switching the armor stats to dexterity makes a lot of sense, in terms of speed. :]

+

Created new images for future gems, one more common, one only drops at the soon-to-be launched PVP map.

+

Perfected the standalone version of the game.

+

EXCHANGE: http://adventure.land/img/exchange.png

+ +
[17/08/16]
+

The Party-Player buttons are now functional. It's Heal for Priests and Focus for others.

+

Improved CODE, added new functions: heal, buy, upgrade, get_player(name)

+

Created a standalone executable with Electron, patched things a bit to make it work, it was much simpler than I imagined it would be. It's much more fun playing the game in a separate window, browsers are super annoying, as they don't draw when the window/tab is out of focus. These standalone executables are perfect for CODE, and for casual playing, as playing in the browser can be distracting, if you are working and taking small breaks to venture in Adventure Land.

+ +
[16/08/16]
+

Another day of huge improvements! Animated Death + Priest Class on the same day!

+

Moved away from bold texts, now all texts are uniform. Also increased text_quality for everyone on default. This results in crisper yet thinner texts. I was so used to the illegible bold disappearing texts, so it wasn't easy to let go ;]

+

I personally don't like how "TOWN" works right now, without any animation you just re-appear in the main spawn point, so cold. For this reason I decided to make death colourful and fun (actually the opposite). When you die, you turn into a tombstone, the game becomes black and white, but you can still talk with others until you press "RESPAWN".

+

With death in the picture, game became much harder, the logical next step was introducing the Priest class. I already knew how I wanted to implement/integrate the Priest and just decided to make it happen today. I personally love the new priest class. It's just right click to heal and similarly right-click to attack, however the attack only does 40% of the heal. Improved the interfaces to include "HEAL".

+

Introduced new animations and skins

+

The HEAL/ATT button on the middle UI is now functional. It's needed for priests to self-heal. But it might also help players who use touch devices and can't right click easily.

+

Next Step: Passive abilities that extend to party members. These will show up in STATS. For example the Priest might add damage reduction to the party.

+

Death: http://adventure.land/img/death.png

+ +
[15/08/16]
+

Created a small island with 3 overpowered fairies and the soon-to-be appearance NPC.

+

Fixed the character movement boundary checks. Previously it was possible to walk outside boundaries in rare circumstances.

+

Started implementing/testing an actual death routine.

+ +
[14/08/16]
+

New server side boundary checks for monsters! No more walking on water :] This is kind of the reason why I designed the initial town as an island cluster, better pass water instead of walking through a wall. With this update, it will be possible to extend the cave and create more extensive maps. For some reason I have the desire to build a farm map, monsters inside their own fences and a simple NPC that herds them.

+

Implemented the definite fix to the consecutive item upgrade issues. On slow systems, it was still possible to re-upgrade items before the game was re-drawn. Not anymore :)

+

Much thicker upgrade animations, the thin ones were barely visible.

+

Improved the server failure routine, players are no longer immediately unlocked, they unlock automatically in 12 minutes. Another iteration is needed, luckily the server is solid now, no more unexpected exceptions.

+ +
[13/08/16]
+

Very stressful day, only researched PeerJS, would be a nice addition to CODE.

+ +
[12/08/16]
+

Ideally "font" worries should be delayed, but I indulged myself. Found an extremely simple method to perfect the font-rendering in-game. Basically you draw texts 2x or 4x and shrink them. I might post it on Stack Overflow at one point. It's a simple solution to haunting blurry Canvas text issues.

+

Closed the gap between browser font differences slightly. I think, in the end, there won't be any "bold" fonts. So Chrome texts will thin-down a bit, yet things will look the same across all browsers. I'm really used to how things look now. So I didn't make any changes at this point.

+

Re-Implemented character names as it was requested, it's not launched yet, but they look great! I think I will add it to button "N", it will be hold-to-show.

+ +
[11/08/16]
+

Implemented the initial fix for the consequent upgrade issue that came up a lot. Diverted a portion of my efforts back to Geobird. My performance will drop until I re-balance.

+ +
[10/08/16]
+

SFX is finally not totally horrendous, managed to rig-up and integrate some slightly pleasing effects. It's interesting that the game was totally silent all this time, yet no one even mentioned it, I wonder whether a non-perfect Sound/Music adds to a game, or takes from a game (probably the latter). Anyway, until things are more satisfying, SFX/Music needs to be toggled ON each time.

+

Spending too much time in-game, it really reduces my performance, tho, receiving lots and lots of awesome feedback and suggestions, caught up with logs today, also starting to take a more active approach for sharing on Reddit/Twitter/FB. I hate FB beyond imagination. Yet it's probably a necessary evil for a game, there is engagement even at this scale. I might revise the social media strategy in a future time. I would personally like to have only a subreddit.

+

+ A Comparison between old and new: + http://adventure.land/img/early.png + http://adventure.land/img/new_crowded.png +

+ +
[09/08/16]
+

Implemented "CONF" for game settings, along with default-off Music/SFX switches

+

Implemented the SFX logic, Improved the Music logic

+

Added the "Perfect Pixels" switch and logic, as my Dell P2415Q monitor can't handle perfect pixels at 4K, no matter what I try, I was playing the game anti-aliased during development, the same routine made it's way to production, now, on default, players will see a perfectly pixellized game. The "OFF" option provides a potentially more blurry/soothing game play. The behaviour might change from system to system, and it might be ineffective for non-retina screens. There will be another option for Retina screens soon, as non-Chrome browsers need a different solution for perfect pixels.

+ +
[08/08/16]
+

Finally added range checks to attacks, I intentionally left it unchecked originally, even now it needs another iteration before PVP becomes serious, currently it's heavy lag-friendly

+

Experimented with some alternative character graphics, ones that iterate over existing ones

+

Improved the server offline detection routine, It marked live servers offline by mistake, Probably a glitch based on minutely differences between instances and db #TODO: Iterate once more

+

First version of Music!

+ +
[07/08/16]
+

An eventless day of community engagement, bug fixes, design and re-balancing

+

Patched an issue that occasionally took a server offline

+ +
[06/08/16]
+

The day of HUGE improvements. Maybe a turning point in the game. My most productive day in a long time. A ~24 Hour sprint.

+

Started by designing, implementing the party logic, had no intention of completing the entire system in one day, but things came to fruition fast.

+

Really proud of how the party design evolved, they are simple to form, simple to manage, when the leader leaves the next one in line become the leader, the XP isn't reduced significantly, so people have a strong incentive to team up.

+

All hp bars of team members are visible, so when Priests arrive they will have an easy time targeting people to heal, when a monster attacks a team member, again it's indicated by it's visible hp bar, all xp gains of party members are shown as purple disappearing texts, all in all, in my opinion, it's beautifully chaotic, I love it

+

While spending time with the early players, Trade was requested again, players really need to transfer items to their friends and alt-characters, so decided to push the day further and add a basic trade too. It's not "Trade", but rather, a way to practically showcase and sell items

+

Added a "SHOW/HIDE" interface, and 4 showcase/sell slots to the Character interface.

+

Improved the drag/equip dynamics a lot further, now things can be dragged to the Character slots, and vice versa. Previously drag was only inside the inventory.

+

Discovered game's first "not cheater" with his own words, "Sammy", I was super proud, It was such a happy moment. To build a game, and have a cheater this fast, almost brought me to tears.

+

Improved NPC's to be left-clickable, they activate, in future they should have a different left-click behaviour, probably a name and a story.

+

Tested Adventure Land on Safari/Firefox, made lots of fixes/improvements.

+

+ http://adventure.land/img/p_b.png + http://adventure.land/img/trui.png +

+ +
[05/08/16]
+

Big changes today, re-designed and implemented the entire game interface

+

The original interface had the ATT, XP, HP, MP all as buttons with texts, with cooldown animations underneath the buttons, I personally liked them, they weren't perfect, but they were awesome placeholders

+

The new interface has HP/MP/Character/Inventory/Attack interfaces in the middle section. The Attack and Inventory have a recharging animation that lights up when it's active.

+

The XP interface is now a bar, like HP,MP, it's above the game log. The Server/Map information section is moved to the left, above the chat section, with a toggle on/off coordinate interface

+

Improved the guide a bit too, added the "Attributes" section, + populated it further

+

http://adventure.land/img/ui_new.png

+ +
[04/08/16]
+

Added the "Fiery Blade" and "Fiery Staff" items, they are very rare, so they don't affect the game balance, yet make the game more fun

+

Improved the UI a bit, STATS now toggle the Character Sheet, Calibrated the z-index of UI elements, matters a lot for low-width screens

+

Shown the "CODE" to the new players, now everyone is CODE'ing, Improved the game logic so the CODE keeps half-working in the background

+

Connected the 1st Island to the 3rd Island, re-balanced monsters, Cave is still the best spot

+

Next Feature: Everyone wants to party + +

[03/08/16]
+

Met with new players, the initial feedback is very positive, so motivating, I couldn't even sleep, woke up early on to check the game

+

Most confusing part of the game is right clicking it seems, for this reason added colors to the game guide, also started showing the game guide automatically to every level 1 player

+

Replaced the coordinates interface with coordinates, map name, server name. Next Step: New XP/Character/Attack/Use interfaces

+

Re-Improved the movement system + teleports, It seems perfect now, character directions are also synced

+

Improved the server upgrade routines, the chat, game logs are left in place, there's also a disconnect reason provided

+

Implemented "F"/Activate Nearest NPC - It's possible to block NPC's, this should solve that challenge

+ +
[02/08/16]
+

Improved the server registry system, server numbering, naming

+

Implemented the multi-server UI/logic, server switching

+

Implemented auto server selection based on rough distance

+

Deployed/Tested/Verified Americas I,II and Europas I,II!! - The ping is down to 70ms for me. Next location: Eastlands

+ +
[01/08/16]
+

Created a very basic game guide

+ +
[31/07/16]
+

Improved the main town, brought down the front walls, added a second bridge, Improved the map editor in the progress

+

Moving towards a multi-server UI + Patched the live server shutdown routine to be clean, there were some unforeseen issues

+

Implemented a password reminder email feature, the button shows up when you fail to enter your password

+ +
[30/07/16]
+

Planning a remake of the map

+

Improved monster/player movements, now there is an abrupt stop logic and dynamic speed calibrations

+

Improving the disappearing texts, font-rendering is still ...

+

Refactored/Simplified most of the server/client events, routines

+

Players, monsters now change direction on attack if they are not moving - Next step: An attack animation or indicator, especially for pvp

+ +
[29/07/16]
+

Receiving feedbacks, started writing a small guide, preparing to make server connections secure, added a percentage based loader

+

Improved Code/runner features, populated https://github.com/kaansoral/adventureland

+ +
[28/07/16]
+

An early launch for adventure.land, mainly to test the network, configured the communications between systems, set up hello@adventure.land, solved some minor server challenges

+

Honestly, it was super fun

+

It's apparent that US/EU/Asia servers are needed even in this early stage, Implemented ping, it was 150ms

+ +
Back Story: Coming Soon [01/12/16]
+
+ + + \ No newline at end of file diff --git a/htmls/macos.html b/htmls/macos.html new file mode 100644 index 0000000..6ad15d9 --- /dev/null +++ b/htmls/macos.html @@ -0,0 +1,115 @@ + + + + MacOS: How to Make it Work + + + + + + + + + + + {% if not domain.is_sdk %} + + {% endif %} + + +
+ +

Adventure Land uses Electron. When you stumble onto an issue, you can google the issue by combining error phrases with "electron".

+ +
+
Just Re-Open or Re-Install
+

Very rarely Steam glitches and the game can't connect to Steamworks, so restarting Steam is a must. Sometimes simply doing a clean install could be the solution.

+
+ +
+
Steam: Run from the Command Line
+

Copy paste this to Terminal by inserting your own system user: /Users/YOUR_USER/Library/Application\ Support/Steam/steamapps/common/adventureland/Adventure\ Land.app/Contents/MacOS/Adventure\ Land
+ You'll likely stumble onto the issue that you can report/search +

+
+ +
+
App Store: Run from the Command Line
+

Copy paste this to Terminal: /Applications/Adventure\ Land.app/Contents/MacOS/Adventure\ Land +

+
+ +
+
App Store: Can't Install - "Unable to Download App"
+

Please email hello@adventure.land

+
+ +
+
src/common/pipes.cpp (883) : fatal stalled cross-thread pipe.
+

Restart Steam

+
+ +

If you find and solve an issue, or just stumble onto an issue you can't solve, please email hello@adventure.land with details

+ +
+ + + \ No newline at end of file diff --git a/htmls/macros.html b/htmls/macros.html new file mode 100644 index 0000000..0f8c8fb --- /dev/null +++ b/htmls/macros.html @@ -0,0 +1,2 @@ +{% macro skill(name, value='', type='text') -%} +{%- endmacro %} \ No newline at end of file diff --git a/htmls/page.html b/htmls/page.html new file mode 100644 index 0000000..6e822d4 --- /dev/null +++ b/htmls/page.html @@ -0,0 +1,23 @@ +{%extends "htmls/base.html"%} +{%block body%} + + + +
+
+ {% if content=="privacy"%} + {% include "htmls/contents/privacy.html" %} + {% elif content=="terms"%} + {% include "htmls/contents/terms.html" %} + {% elif content=="credits"%} + {% include "htmls/contents/credits.html" %} + {% elif content=="contact"%} + You can always email me at hello@adventure.land + + Also check out our Discord! - You can PM Wizard on Discord for faster and more informal replies :) + {%endif%} +
+
+{%endblock%} \ No newline at end of file diff --git a/htmls/payments.html b/htmls/payments.html new file mode 100644 index 0000000..2b9ba7a --- /dev/null +++ b/htmls/payments.html @@ -0,0 +1,100 @@ + + + + {{domain.name}} + + + + + + + + + + + + {% if domain.test_clicks %} {# or 1 and not domain.test_fast #} + + {% else %} + + {% endif %} + {% if 1%}{% endif %} + + + + + + + + {##} + {%if 0%}{%endif%} + {% if 1%} + + + + + + {% endif %} + + + + + + + + + + {% include "htmls/base_script.html" %} + + + + {% set inside = "payments" %} +
{% include "htmls/contents/payments.html" %}
+ + + + \ No newline at end of file diff --git a/htmls/player.html b/htmls/player.html new file mode 100644 index 0000000..398eae3 --- /dev/null +++ b/htmls/player.html @@ -0,0 +1,23 @@ +{%extends "htmls/base.html"%} +{%block body%} + + + +
+ {% for character in characters %} + {%include "htmls/contents/character.html" %} + {% endfor %} +
+ +{%endblock%} \ No newline at end of file diff --git a/htmls/roadmap.html b/htmls/roadmap.html new file mode 100644 index 0000000..c47b411 --- /dev/null +++ b/htmls/roadmap.html @@ -0,0 +1,107 @@ + + + + Planned Features + + + + + + + + + + + {% if not domain.is_sdk %} + + {% endif %} + + +
+
Planned Features Last Update [12/02/17]
+
Steam
+

While the standalone version of the game has been ready for some time, decided to postpone the Steam release until the game is fuller, basically, I think, "Daily Events", "Tavern", "Documented Code", "Improved Sound/FX" should be completed beforehand.

+
Tavern
+

Purpose: A place to relax,

+

Last Status: Code design and the server implementation is ready, working on Animations/UI.

+
PVP
+

In Progress: Working on balance changes, new skills, new methods to improve PVP. Likely going to limit the XP exchange and introduce "Item Drops" from players. Basically, "Newly Acquired" items will have a chance to drop on death.

+
Daily Events
+

Purpose: Every server is going to run an event every day at 9:20PM. While the game is mostly an idle/afk/coding game, these daily events will be an opportunity to socialise and have some fun.

+

Last Status: The "Goo Brawl" event is ready, working on the first PVP event.

+
Achievements/Statistics/Leaderboards
+

Observing the gameplay and the needs of the players, this feature is heavily needed and requested, I'm not 100% sure how to go forward with the Achievements and Awards, going to start with basic Statistics and Leaderboards first.

+
Sound/FX
+

Ever since I've launched the game, with the exception of the Xmas Tune, the tunes and fx has been the same, going to improve the fx logic, and re-visit all the sound/fx selections at one point. It's challenging.

+
Communicator
+

In Progress: The friends system is complete, the Communicator needs serious improvements on the interface/usability side of things. Going to add additional features to the server so players have a way to communicate, get to know new players.

+
Content: New Items, Events, Quests
+

In Progress: Continually working on adding new content to the game, most of the cave entrances in game are unused at the moment. Planning on adding triggerable events like dungeons.

+
The Resort
+

This is the feature I'm second most excited about, first one being the Tavern. The Resort is kind of like the holodecks in Star Trek. Everyone will be able to design their own maps/rooms, and hopefully Code for them too. While the "Community Map Editor" is ready, the Code part, security is the challenge.

+
+ + + \ No newline at end of file diff --git a/htmls/runner.html b/htmls/runner.html new file mode 100644 index 0000000..312bc05 --- /dev/null +++ b/htmls/runner.html @@ -0,0 +1,59 @@ + + + + {% if domain.electron%}{% endif %} + + + + + + + + +
CODE
+
Initiating
+ + + \ No newline at end of file diff --git a/htmls/simple_message.html b/htmls/simple_message.html new file mode 100644 index 0000000..d01acc1 --- /dev/null +++ b/htmls/simple_message.html @@ -0,0 +1,28 @@ + + + + {{domain.name}} + + + + + + + + + + + + + + +
{{message}}
+ + \ No newline at end of file diff --git a/images/.DS_Store b/images/.DS_Store new file mode 100644 index 0000000..a1ff795 Binary files /dev/null and b/images/.DS_Store differ diff --git a/images/all_characters/.DS_Store b/images/all_characters/.DS_Store new file mode 100644 index 0000000..ef739bf Binary files /dev/null and b/images/all_characters/.DS_Store differ diff --git a/images/all_characters/lchar1.png b/images/all_characters/lchar1.png new file mode 100644 index 0000000..2d99c87 Binary files /dev/null and b/images/all_characters/lchar1.png differ diff --git a/images/all_characters/mchar1.png b/images/all_characters/mchar1.png new file mode 100644 index 0000000..8b755dc Binary files /dev/null and b/images/all_characters/mchar1.png differ diff --git a/images/all_characters/mchar10.png b/images/all_characters/mchar10.png new file mode 100644 index 0000000..1a8516b Binary files /dev/null and b/images/all_characters/mchar10.png differ diff --git a/images/all_characters/mchar11.png b/images/all_characters/mchar11.png new file mode 100644 index 0000000..906ad00 Binary files /dev/null and b/images/all_characters/mchar11.png differ diff --git a/images/all_characters/mchar12.png b/images/all_characters/mchar12.png new file mode 100644 index 0000000..38660be Binary files /dev/null and b/images/all_characters/mchar12.png differ diff --git a/images/all_characters/mchar13.png b/images/all_characters/mchar13.png new file mode 100644 index 0000000..708b531 Binary files /dev/null and b/images/all_characters/mchar13.png differ diff --git a/images/all_characters/mchar14.png b/images/all_characters/mchar14.png new file mode 100644 index 0000000..928ffc2 Binary files /dev/null and b/images/all_characters/mchar14.png differ diff --git a/images/all_characters/mchar15.png b/images/all_characters/mchar15.png new file mode 100644 index 0000000..7a365a3 Binary files /dev/null and b/images/all_characters/mchar15.png differ diff --git a/images/all_characters/mchar16.png b/images/all_characters/mchar16.png new file mode 100644 index 0000000..e34bc20 Binary files /dev/null and b/images/all_characters/mchar16.png differ diff --git a/images/all_characters/mchar17.png b/images/all_characters/mchar17.png new file mode 100644 index 0000000..346c3cd Binary files /dev/null and b/images/all_characters/mchar17.png differ diff --git a/images/all_characters/mchar18.png b/images/all_characters/mchar18.png new file mode 100644 index 0000000..83319fe Binary files /dev/null and b/images/all_characters/mchar18.png differ diff --git a/images/all_characters/mchar19.png b/images/all_characters/mchar19.png new file mode 100644 index 0000000..732e268 Binary files /dev/null and b/images/all_characters/mchar19.png differ diff --git a/images/all_characters/mchar2.png b/images/all_characters/mchar2.png new file mode 100644 index 0000000..32f7698 Binary files /dev/null and b/images/all_characters/mchar2.png differ diff --git a/images/all_characters/mchar20.png b/images/all_characters/mchar20.png new file mode 100644 index 0000000..b2138cf Binary files /dev/null and b/images/all_characters/mchar20.png differ diff --git a/images/all_characters/mchar21.png b/images/all_characters/mchar21.png new file mode 100644 index 0000000..5005cff Binary files /dev/null and b/images/all_characters/mchar21.png differ diff --git a/images/all_characters/mchar22.png b/images/all_characters/mchar22.png new file mode 100644 index 0000000..f700185 Binary files /dev/null and b/images/all_characters/mchar22.png differ diff --git a/images/all_characters/mchar23.png b/images/all_characters/mchar23.png new file mode 100644 index 0000000..25bb6ac Binary files /dev/null and b/images/all_characters/mchar23.png differ diff --git a/images/all_characters/mchar24.png b/images/all_characters/mchar24.png new file mode 100644 index 0000000..9954a8c Binary files /dev/null and b/images/all_characters/mchar24.png differ diff --git a/images/all_characters/mchar25.png b/images/all_characters/mchar25.png new file mode 100644 index 0000000..9bdda82 Binary files /dev/null and b/images/all_characters/mchar25.png differ diff --git a/images/all_characters/mchar26.png b/images/all_characters/mchar26.png new file mode 100644 index 0000000..19ea09c Binary files /dev/null and b/images/all_characters/mchar26.png differ diff --git a/images/all_characters/mchar27.png b/images/all_characters/mchar27.png new file mode 100644 index 0000000..239d75e Binary files /dev/null and b/images/all_characters/mchar27.png differ diff --git a/images/all_characters/mchar28.png b/images/all_characters/mchar28.png new file mode 100644 index 0000000..66f91a6 Binary files /dev/null and b/images/all_characters/mchar28.png differ diff --git a/images/all_characters/mchar29.png b/images/all_characters/mchar29.png new file mode 100644 index 0000000..6b5d522 Binary files /dev/null and b/images/all_characters/mchar29.png differ diff --git a/images/all_characters/mchar3.png b/images/all_characters/mchar3.png new file mode 100644 index 0000000..3669555 Binary files /dev/null and b/images/all_characters/mchar3.png differ diff --git a/images/all_characters/mchar30.png b/images/all_characters/mchar30.png new file mode 100644 index 0000000..670daf1 Binary files /dev/null and b/images/all_characters/mchar30.png differ diff --git a/images/all_characters/mchar31.png b/images/all_characters/mchar31.png new file mode 100644 index 0000000..2714d94 Binary files /dev/null and b/images/all_characters/mchar31.png differ diff --git a/images/all_characters/mchar32.png b/images/all_characters/mchar32.png new file mode 100644 index 0000000..3f85ae8 Binary files /dev/null and b/images/all_characters/mchar32.png differ diff --git a/images/all_characters/mchar33.png b/images/all_characters/mchar33.png new file mode 100644 index 0000000..02134a6 Binary files /dev/null and b/images/all_characters/mchar33.png differ diff --git a/images/all_characters/mchar34.png b/images/all_characters/mchar34.png new file mode 100644 index 0000000..8c1b322 Binary files /dev/null and b/images/all_characters/mchar34.png differ diff --git a/images/all_characters/mchar35.png b/images/all_characters/mchar35.png new file mode 100644 index 0000000..3b82b58 Binary files /dev/null and b/images/all_characters/mchar35.png differ diff --git a/images/all_characters/mchar36.png b/images/all_characters/mchar36.png new file mode 100644 index 0000000..e46743e Binary files /dev/null and b/images/all_characters/mchar36.png differ diff --git a/images/all_characters/mchar37.png b/images/all_characters/mchar37.png new file mode 100644 index 0000000..58163ae Binary files /dev/null and b/images/all_characters/mchar37.png differ diff --git a/images/all_characters/mchar4.png b/images/all_characters/mchar4.png new file mode 100644 index 0000000..3169fde Binary files /dev/null and b/images/all_characters/mchar4.png differ diff --git a/images/all_characters/mchar5.png b/images/all_characters/mchar5.png new file mode 100644 index 0000000..f2fdcf7 Binary files /dev/null and b/images/all_characters/mchar5.png differ diff --git a/images/all_characters/mchar6.png b/images/all_characters/mchar6.png new file mode 100644 index 0000000..ad1ae32 Binary files /dev/null and b/images/all_characters/mchar6.png differ diff --git a/images/all_characters/mchar7.png b/images/all_characters/mchar7.png new file mode 100644 index 0000000..74e21f2 Binary files /dev/null and b/images/all_characters/mchar7.png differ diff --git a/images/all_characters/mchar8.png b/images/all_characters/mchar8.png new file mode 100644 index 0000000..03300d1 Binary files /dev/null and b/images/all_characters/mchar8.png differ diff --git a/images/all_characters/mchar9.png b/images/all_characters/mchar9.png new file mode 100644 index 0000000..765fc8a Binary files /dev/null and b/images/all_characters/mchar9.png differ diff --git a/images/all_characters/schar1.png b/images/all_characters/schar1.png new file mode 100644 index 0000000..18a0a12 Binary files /dev/null and b/images/all_characters/schar1.png differ diff --git a/images/all_characters/schar10.png b/images/all_characters/schar10.png new file mode 100644 index 0000000..256822b Binary files /dev/null and b/images/all_characters/schar10.png differ diff --git a/images/all_characters/schar2.png b/images/all_characters/schar2.png new file mode 100644 index 0000000..b297b08 Binary files /dev/null and b/images/all_characters/schar2.png differ diff --git a/images/all_characters/schar3.png b/images/all_characters/schar3.png new file mode 100644 index 0000000..8861c85 Binary files /dev/null and b/images/all_characters/schar3.png differ diff --git a/images/all_characters/schar4.png b/images/all_characters/schar4.png new file mode 100644 index 0000000..069382c Binary files /dev/null and b/images/all_characters/schar4.png differ diff --git a/images/all_characters/schar5.png b/images/all_characters/schar5.png new file mode 100644 index 0000000..8f1529a Binary files /dev/null and b/images/all_characters/schar5.png differ diff --git a/images/all_characters/schar6.png b/images/all_characters/schar6.png new file mode 100644 index 0000000..632f27f Binary files /dev/null and b/images/all_characters/schar6.png differ diff --git a/images/all_characters/schar7.png b/images/all_characters/schar7.png new file mode 100644 index 0000000..f0d8e7b Binary files /dev/null and b/images/all_characters/schar7.png differ diff --git a/images/all_characters/schar8.png b/images/all_characters/schar8.png new file mode 100644 index 0000000..956470f Binary files /dev/null and b/images/all_characters/schar8.png differ diff --git a/images/all_characters/schar9.png b/images/all_characters/schar9.png new file mode 100644 index 0000000..59d3278 Binary files /dev/null and b/images/all_characters/schar9.png differ diff --git a/images/all_characters/xschar1.png b/images/all_characters/xschar1.png new file mode 100644 index 0000000..a96a2b4 Binary files /dev/null and b/images/all_characters/xschar1.png differ diff --git a/images/all_characters/xschar2.png b/images/all_characters/xschar2.png new file mode 100644 index 0000000..d7ec95f Binary files /dev/null and b/images/all_characters/xschar2.png differ diff --git a/images/all_characters/xschar3.png b/images/all_characters/xschar3.png new file mode 100644 index 0000000..21e07d2 Binary files /dev/null and b/images/all_characters/xschar3.png differ diff --git a/images/all_characters/xschar4.png b/images/all_characters/xschar4.png new file mode 100644 index 0000000..31d8a74 Binary files /dev/null and b/images/all_characters/xschar4.png differ diff --git a/images/all_characters/xxschar1.png b/images/all_characters/xxschar1.png new file mode 100644 index 0000000..1318034 Binary files /dev/null and b/images/all_characters/xxschar1.png differ diff --git a/images/all_characters/xxschar2.png b/images/all_characters/xxschar2.png new file mode 100644 index 0000000..876f311 Binary files /dev/null and b/images/all_characters/xxschar2.png differ diff --git a/images/all_characters/xxschar3.png b/images/all_characters/xxschar3.png new file mode 100644 index 0000000..fb0116e Binary files /dev/null and b/images/all_characters/xxschar3.png differ diff --git a/images/cards/.DS_Store b/images/cards/.DS_Store new file mode 100644 index 0000000..dc1a6e0 Binary files /dev/null and b/images/cards/.DS_Store differ diff --git a/images/cards/tarot/.DS_Store b/images/cards/tarot/.DS_Store new file mode 100644 index 0000000..7e97464 Binary files /dev/null and b/images/cards/tarot/.DS_Store differ diff --git a/images/cards/tarot/README.txt b/images/cards/tarot/README.txt new file mode 100755 index 0000000..a5e899e --- /dev/null +++ b/images/cards/tarot/README.txt @@ -0,0 +1,34 @@ +-=-=-=- +PIXEL TAROT CARD DECK +-==-=- + +Thank you for buying this asset pack! + +The pixel tarot deck includes every card in the tarot deck, major arcana and all four suits of minor arcana. +Everything is drawn in a classic 16-bit pixel artstyle. + +The individual cards are 48x80 pixels. The files themselves are 58x90 with a transparent bleed. +Also includes a card back and frames for a spinning animation and a well-organized PSD file. + +In this pack: +- all 78 Cards in a Tarot deck +- individual .PNG files for each card (Major and Minor Arcana) +- .PNG file for card back +- .PNG frames for card spin and flash animations +- organized .PSD file with all cards and animations for use in Adobe Photoshop + + + + +------------------------- +Artist's Website + finalbossblues.com + timefantasy.net +Twitter + @finalbossblues +Facebook + finalbossblues +Patreon + patreon.com/finalbossblues +------------------------- + diff --git a/images/cards/tarot/animation_preview.gif b/images/cards/tarot/animation_preview.gif new file mode 100755 index 0000000..9f18ea5 Binary files /dev/null and b/images/cards/tarot/animation_preview.gif differ diff --git a/images/cards/tarot/animations/tarot__flash_1.png b/images/cards/tarot/animations/tarot__flash_1.png new file mode 100755 index 0000000..3be78b5 Binary files /dev/null and b/images/cards/tarot/animations/tarot__flash_1.png differ diff --git a/images/cards/tarot/animations/tarot__flash_2.png b/images/cards/tarot/animations/tarot__flash_2.png new file mode 100755 index 0000000..334f5a6 Binary files /dev/null and b/images/cards/tarot/animations/tarot__flash_2.png differ diff --git a/images/cards/tarot/animations/tarot__flash_3.png b/images/cards/tarot/animations/tarot__flash_3.png new file mode 100755 index 0000000..ad6f720 Binary files /dev/null and b/images/cards/tarot/animations/tarot__flash_3.png differ diff --git a/images/cards/tarot/animations/tarot__flash_4.png b/images/cards/tarot/animations/tarot__flash_4.png new file mode 100755 index 0000000..33316b1 Binary files /dev/null and b/images/cards/tarot/animations/tarot__flash_4.png differ diff --git a/images/cards/tarot/animations/tarot__spin_1.png b/images/cards/tarot/animations/tarot__spin_1.png new file mode 100755 index 0000000..7fba407 Binary files /dev/null and b/images/cards/tarot/animations/tarot__spin_1.png differ diff --git a/images/cards/tarot/animations/tarot__spin_10.png b/images/cards/tarot/animations/tarot__spin_10.png new file mode 100755 index 0000000..8b984e3 Binary files /dev/null and b/images/cards/tarot/animations/tarot__spin_10.png differ diff --git a/images/cards/tarot/animations/tarot__spin_11.png b/images/cards/tarot/animations/tarot__spin_11.png new file mode 100755 index 0000000..23aef68 Binary files /dev/null and b/images/cards/tarot/animations/tarot__spin_11.png differ diff --git a/images/cards/tarot/animations/tarot__spin_2.png b/images/cards/tarot/animations/tarot__spin_2.png new file mode 100755 index 0000000..aa1d32e Binary files /dev/null and b/images/cards/tarot/animations/tarot__spin_2.png differ diff --git a/images/cards/tarot/animations/tarot__spin_3.png b/images/cards/tarot/animations/tarot__spin_3.png new file mode 100755 index 0000000..6a7b70a Binary files /dev/null and b/images/cards/tarot/animations/tarot__spin_3.png differ diff --git a/images/cards/tarot/animations/tarot__spin_4.png b/images/cards/tarot/animations/tarot__spin_4.png new file mode 100755 index 0000000..d0f41f5 Binary files /dev/null and b/images/cards/tarot/animations/tarot__spin_4.png differ diff --git a/images/cards/tarot/animations/tarot__spin_5.png b/images/cards/tarot/animations/tarot__spin_5.png new file mode 100755 index 0000000..7521818 Binary files /dev/null and b/images/cards/tarot/animations/tarot__spin_5.png differ diff --git a/images/cards/tarot/animations/tarot__spin_6.png b/images/cards/tarot/animations/tarot__spin_6.png new file mode 100755 index 0000000..d042fd9 Binary files /dev/null and b/images/cards/tarot/animations/tarot__spin_6.png differ diff --git a/images/cards/tarot/animations/tarot__spin_7.png b/images/cards/tarot/animations/tarot__spin_7.png new file mode 100755 index 0000000..8077b2f Binary files /dev/null and b/images/cards/tarot/animations/tarot__spin_7.png differ diff --git a/images/cards/tarot/animations/tarot__spin_8.png b/images/cards/tarot/animations/tarot__spin_8.png new file mode 100755 index 0000000..9e83516 Binary files /dev/null and b/images/cards/tarot/animations/tarot__spin_8.png differ diff --git a/images/cards/tarot/animations/tarot__spin_9.png b/images/cards/tarot/animations/tarot__spin_9.png new file mode 100755 index 0000000..2f7a29e Binary files /dev/null and b/images/cards/tarot/animations/tarot__spin_9.png differ diff --git a/images/cards/tarot/major_arcana/tarot__chariot.png b/images/cards/tarot/major_arcana/tarot__chariot.png new file mode 100755 index 0000000..0123bd4 Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__chariot.png differ diff --git a/images/cards/tarot/major_arcana/tarot__death.png b/images/cards/tarot/major_arcana/tarot__death.png new file mode 100755 index 0000000..e910a9e Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__death.png differ diff --git a/images/cards/tarot/major_arcana/tarot__devil.png b/images/cards/tarot/major_arcana/tarot__devil.png new file mode 100755 index 0000000..a2b795d Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__devil.png differ diff --git a/images/cards/tarot/major_arcana/tarot__emperor.png b/images/cards/tarot/major_arcana/tarot__emperor.png new file mode 100755 index 0000000..57a115a Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__emperor.png differ diff --git a/images/cards/tarot/major_arcana/tarot__empress.png b/images/cards/tarot/major_arcana/tarot__empress.png new file mode 100755 index 0000000..63ea879 Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__empress.png differ diff --git a/images/cards/tarot/major_arcana/tarot__fool.png b/images/cards/tarot/major_arcana/tarot__fool.png new file mode 100755 index 0000000..801df0a Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__fool.png differ diff --git a/images/cards/tarot/major_arcana/tarot__fortune.png b/images/cards/tarot/major_arcana/tarot__fortune.png new file mode 100755 index 0000000..ebc99c5 Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__fortune.png differ diff --git a/images/cards/tarot/major_arcana/tarot__hangman.png b/images/cards/tarot/major_arcana/tarot__hangman.png new file mode 100755 index 0000000..35f8445 Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__hangman.png differ diff --git a/images/cards/tarot/major_arcana/tarot__hermit.png b/images/cards/tarot/major_arcana/tarot__hermit.png new file mode 100755 index 0000000..ac0eac2 Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__hermit.png differ diff --git a/images/cards/tarot/major_arcana/tarot__hierophant.png b/images/cards/tarot/major_arcana/tarot__hierophant.png new file mode 100755 index 0000000..f810d32 Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__hierophant.png differ diff --git a/images/cards/tarot/major_arcana/tarot__judgment.png b/images/cards/tarot/major_arcana/tarot__judgment.png new file mode 100755 index 0000000..1e987f4 Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__judgment.png differ diff --git a/images/cards/tarot/major_arcana/tarot__justice.png b/images/cards/tarot/major_arcana/tarot__justice.png new file mode 100755 index 0000000..8fc08b2 Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__justice.png differ diff --git a/images/cards/tarot/major_arcana/tarot__lovers.png b/images/cards/tarot/major_arcana/tarot__lovers.png new file mode 100755 index 0000000..0b7332a Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__lovers.png differ diff --git a/images/cards/tarot/major_arcana/tarot__magician.png b/images/cards/tarot/major_arcana/tarot__magician.png new file mode 100755 index 0000000..44d7e6c Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__magician.png differ diff --git a/images/cards/tarot/major_arcana/tarot__moon.png b/images/cards/tarot/major_arcana/tarot__moon.png new file mode 100755 index 0000000..135d3f9 Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__moon.png differ diff --git a/images/cards/tarot/major_arcana/tarot__priestess.png b/images/cards/tarot/major_arcana/tarot__priestess.png new file mode 100755 index 0000000..fe655d1 Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__priestess.png differ diff --git a/images/cards/tarot/major_arcana/tarot__star.png b/images/cards/tarot/major_arcana/tarot__star.png new file mode 100755 index 0000000..5945c86 Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__star.png differ diff --git a/images/cards/tarot/major_arcana/tarot__strength.png b/images/cards/tarot/major_arcana/tarot__strength.png new file mode 100755 index 0000000..ada5aa8 Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__strength.png differ diff --git a/images/cards/tarot/major_arcana/tarot__sun.png b/images/cards/tarot/major_arcana/tarot__sun.png new file mode 100755 index 0000000..d0489dd Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__sun.png differ diff --git a/images/cards/tarot/major_arcana/tarot__temperance.png b/images/cards/tarot/major_arcana/tarot__temperance.png new file mode 100755 index 0000000..cced282 Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__temperance.png differ diff --git a/images/cards/tarot/major_arcana/tarot__theworld.png b/images/cards/tarot/major_arcana/tarot__theworld.png new file mode 100755 index 0000000..efcd412 Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__theworld.png differ diff --git a/images/cards/tarot/major_arcana/tarot__tower.png b/images/cards/tarot/major_arcana/tarot__tower.png new file mode 100755 index 0000000..eec3ba8 Binary files /dev/null and b/images/cards/tarot/major_arcana/tarot__tower.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__10_cups.png b/images/cards/tarot/minor_arcana/tarot__10_cups.png new file mode 100755 index 0000000..001fdbf Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__10_cups.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__10_pentacles.png b/images/cards/tarot/minor_arcana/tarot__10_pentacles.png new file mode 100755 index 0000000..1a6ad83 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__10_pentacles.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__10_swords.png b/images/cards/tarot/minor_arcana/tarot__10_swords.png new file mode 100755 index 0000000..9f6a604 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__10_swords.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__10_wands.png b/images/cards/tarot/minor_arcana/tarot__10_wands.png new file mode 100755 index 0000000..81bb9d5 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__10_wands.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__2_cups.png b/images/cards/tarot/minor_arcana/tarot__2_cups.png new file mode 100755 index 0000000..48ce887 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__2_cups.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__2_pentacles.png b/images/cards/tarot/minor_arcana/tarot__2_pentacles.png new file mode 100755 index 0000000..996a3fa Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__2_pentacles.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__2_swords.png b/images/cards/tarot/minor_arcana/tarot__2_swords.png new file mode 100755 index 0000000..0c4c084 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__2_swords.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__2_wands.png b/images/cards/tarot/minor_arcana/tarot__2_wands.png new file mode 100755 index 0000000..840268d Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__2_wands.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__3_cups.png b/images/cards/tarot/minor_arcana/tarot__3_cups.png new file mode 100755 index 0000000..02c6174 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__3_cups.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__3_pentacles.png b/images/cards/tarot/minor_arcana/tarot__3_pentacles.png new file mode 100755 index 0000000..b3f2621 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__3_pentacles.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__3_swords.png b/images/cards/tarot/minor_arcana/tarot__3_swords.png new file mode 100755 index 0000000..981e5d7 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__3_swords.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__3_wands.png b/images/cards/tarot/minor_arcana/tarot__3_wands.png new file mode 100755 index 0000000..0c98ede Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__3_wands.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__4_cups.png b/images/cards/tarot/minor_arcana/tarot__4_cups.png new file mode 100755 index 0000000..2c51b85 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__4_cups.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__4_pentacles.png b/images/cards/tarot/minor_arcana/tarot__4_pentacles.png new file mode 100755 index 0000000..4ffb414 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__4_pentacles.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__4_swords.png b/images/cards/tarot/minor_arcana/tarot__4_swords.png new file mode 100755 index 0000000..d8ebc7d Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__4_swords.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__4_wands.png b/images/cards/tarot/minor_arcana/tarot__4_wands.png new file mode 100755 index 0000000..2f0a5a5 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__4_wands.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__5_cups.png b/images/cards/tarot/minor_arcana/tarot__5_cups.png new file mode 100755 index 0000000..fe3a674 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__5_cups.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__5_pentacles.png b/images/cards/tarot/minor_arcana/tarot__5_pentacles.png new file mode 100755 index 0000000..9fe67b7 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__5_pentacles.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__5_swords.png b/images/cards/tarot/minor_arcana/tarot__5_swords.png new file mode 100755 index 0000000..27d7333 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__5_swords.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__5_wands.png b/images/cards/tarot/minor_arcana/tarot__5_wands.png new file mode 100755 index 0000000..a078d4e Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__5_wands.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__6_cups.png b/images/cards/tarot/minor_arcana/tarot__6_cups.png new file mode 100755 index 0000000..57598c6 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__6_cups.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__6_pentacles.png b/images/cards/tarot/minor_arcana/tarot__6_pentacles.png new file mode 100755 index 0000000..ce9e849 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__6_pentacles.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__6_swords.png b/images/cards/tarot/minor_arcana/tarot__6_swords.png new file mode 100755 index 0000000..41d5599 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__6_swords.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__6_wands.png b/images/cards/tarot/minor_arcana/tarot__6_wands.png new file mode 100755 index 0000000..4302577 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__6_wands.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__7_cups.png b/images/cards/tarot/minor_arcana/tarot__7_cups.png new file mode 100755 index 0000000..b599712 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__7_cups.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__7_pentacles.png b/images/cards/tarot/minor_arcana/tarot__7_pentacles.png new file mode 100755 index 0000000..6e0dcf9 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__7_pentacles.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__7_swords.png b/images/cards/tarot/minor_arcana/tarot__7_swords.png new file mode 100755 index 0000000..cdd201a Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__7_swords.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__7_wands.png b/images/cards/tarot/minor_arcana/tarot__7_wands.png new file mode 100755 index 0000000..0c58229 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__7_wands.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__8_cups.png b/images/cards/tarot/minor_arcana/tarot__8_cups.png new file mode 100755 index 0000000..17f3cba Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__8_cups.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__8_pentacles.png b/images/cards/tarot/minor_arcana/tarot__8_pentacles.png new file mode 100755 index 0000000..5d01e53 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__8_pentacles.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__8_swords.png b/images/cards/tarot/minor_arcana/tarot__8_swords.png new file mode 100755 index 0000000..0a4d64a Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__8_swords.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__8_wands.png b/images/cards/tarot/minor_arcana/tarot__8_wands.png new file mode 100755 index 0000000..4f1854b Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__8_wands.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__9_cups.png b/images/cards/tarot/minor_arcana/tarot__9_cups.png new file mode 100755 index 0000000..ae9320f Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__9_cups.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__9_pentacles.png b/images/cards/tarot/minor_arcana/tarot__9_pentacles.png new file mode 100755 index 0000000..5493292 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__9_pentacles.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__9_swords.png b/images/cards/tarot/minor_arcana/tarot__9_swords.png new file mode 100755 index 0000000..d3478c2 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__9_swords.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__9_wands.png b/images/cards/tarot/minor_arcana/tarot__9_wands.png new file mode 100755 index 0000000..43ad9a5 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__9_wands.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__ace_cups.png b/images/cards/tarot/minor_arcana/tarot__ace_cups.png new file mode 100755 index 0000000..92b6ac1 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__ace_cups.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__ace_pentacles.png b/images/cards/tarot/minor_arcana/tarot__ace_pentacles.png new file mode 100755 index 0000000..9c6e17f Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__ace_pentacles.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__ace_swords.png b/images/cards/tarot/minor_arcana/tarot__ace_swords.png new file mode 100755 index 0000000..66a67b3 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__ace_swords.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__ace_wands.png b/images/cards/tarot/minor_arcana/tarot__ace_wands.png new file mode 100755 index 0000000..a824786 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__ace_wands.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__king_cups.png b/images/cards/tarot/minor_arcana/tarot__king_cups.png new file mode 100755 index 0000000..74d4166 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__king_cups.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__king_pentacles.png b/images/cards/tarot/minor_arcana/tarot__king_pentacles.png new file mode 100755 index 0000000..80a4803 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__king_pentacles.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__king_swords.png b/images/cards/tarot/minor_arcana/tarot__king_swords.png new file mode 100755 index 0000000..9c2b9b9 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__king_swords.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__king_wands.png b/images/cards/tarot/minor_arcana/tarot__king_wands.png new file mode 100755 index 0000000..517f37c Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__king_wands.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__knight_cups.png b/images/cards/tarot/minor_arcana/tarot__knight_cups.png new file mode 100755 index 0000000..de068d0 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__knight_cups.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__knight_pentacles.png b/images/cards/tarot/minor_arcana/tarot__knight_pentacles.png new file mode 100755 index 0000000..1061101 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__knight_pentacles.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__knight_swords.png b/images/cards/tarot/minor_arcana/tarot__knight_swords.png new file mode 100755 index 0000000..6e6d703 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__knight_swords.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__knight_wands.png b/images/cards/tarot/minor_arcana/tarot__knight_wands.png new file mode 100755 index 0000000..3091b18 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__knight_wands.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__page_cups.png b/images/cards/tarot/minor_arcana/tarot__page_cups.png new file mode 100755 index 0000000..9da537a Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__page_cups.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__page_pentacles.png b/images/cards/tarot/minor_arcana/tarot__page_pentacles.png new file mode 100755 index 0000000..57208d6 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__page_pentacles.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__page_swords.png b/images/cards/tarot/minor_arcana/tarot__page_swords.png new file mode 100755 index 0000000..e0eb1ca Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__page_swords.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__page_wands.png b/images/cards/tarot/minor_arcana/tarot__page_wands.png new file mode 100755 index 0000000..aaaa91b Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__page_wands.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__queen_cups.png b/images/cards/tarot/minor_arcana/tarot__queen_cups.png new file mode 100755 index 0000000..e74be75 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__queen_cups.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__queen_pentacles.png b/images/cards/tarot/minor_arcana/tarot__queen_pentacles.png new file mode 100755 index 0000000..b89ad1c Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__queen_pentacles.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__queen_swords.png b/images/cards/tarot/minor_arcana/tarot__queen_swords.png new file mode 100755 index 0000000..19a65f7 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__queen_swords.png differ diff --git a/images/cards/tarot/minor_arcana/tarot__queen_wands.png b/images/cards/tarot/minor_arcana/tarot__queen_wands.png new file mode 100755 index 0000000..f0e2fe5 Binary files /dev/null and b/images/cards/tarot/minor_arcana/tarot__queen_wands.png differ diff --git a/images/cards/tarot/tarot__back.png b/images/cards/tarot/tarot__back.png new file mode 100755 index 0000000..a0a8394 Binary files /dev/null and b/images/cards/tarot/tarot__back.png differ diff --git a/images/cards/tarot/tarot_deck.psd b/images/cards/tarot/tarot_deck.psd new file mode 100755 index 0000000..ebcf2d0 Binary files /dev/null and b/images/cards/tarot/tarot_deck.psd differ diff --git a/images/characters/.DS_Store b/images/characters/.DS_Store new file mode 100644 index 0000000..0743b8a Binary files /dev/null and b/images/characters/.DS_Store differ diff --git a/images/characters/mc1.png b/images/characters/mc1.png new file mode 100644 index 0000000..05e05af Binary files /dev/null and b/images/characters/mc1.png differ diff --git a/images/characters/template.pxm b/images/characters/template.pxm new file mode 100644 index 0000000..3b3eebc Binary files /dev/null and b/images/characters/template.pxm differ diff --git a/images/cosmetics/.DS_Store b/images/cosmetics/.DS_Store new file mode 100644 index 0000000..34384cd Binary files /dev/null and b/images/cosmetics/.DS_Store differ diff --git a/images/cosmetics/accessories/.DS_Store b/images/cosmetics/accessories/.DS_Store new file mode 100644 index 0000000..3724cc8 Binary files /dev/null and b/images/cosmetics/accessories/.DS_Store differ diff --git a/images/cosmetics/accessories/eyeglasses.png b/images/cosmetics/accessories/eyeglasses.png new file mode 100644 index 0000000..f2cc59a Binary files /dev/null and b/images/cosmetics/accessories/eyeglasses.png differ diff --git a/images/cosmetics/accessories/kglasses.png b/images/cosmetics/accessories/kglasses.png new file mode 100644 index 0000000..e3058ce Binary files /dev/null and b/images/cosmetics/accessories/kglasses.png differ diff --git a/images/cosmetics/accessories/kglasses.pxm b/images/cosmetics/accessories/kglasses.pxm new file mode 100644 index 0000000..6111058 Binary files /dev/null and b/images/cosmetics/accessories/kglasses.pxm differ diff --git a/images/cosmetics/armors/.DS_Store b/images/cosmetics/armors/.DS_Store new file mode 100644 index 0000000..c050557 Binary files /dev/null and b/images/cosmetics/armors/.DS_Store differ diff --git a/images/cosmetics/armors/larmor1.png b/images/cosmetics/armors/larmor1.png new file mode 100644 index 0000000..390ec45 Binary files /dev/null and b/images/cosmetics/armors/larmor1.png differ diff --git a/images/cosmetics/armors/mabw.png b/images/cosmetics/armors/mabw.png new file mode 100644 index 0000000..b9ecbc6 Binary files /dev/null and b/images/cosmetics/armors/mabw.png differ diff --git a/images/cosmetics/armors/mabw.pxm b/images/cosmetics/armors/mabw.pxm new file mode 100644 index 0000000..e5fe631 Binary files /dev/null and b/images/cosmetics/armors/mabw.pxm differ diff --git a/images/cosmetics/armors/marmor1.png b/images/cosmetics/armors/marmor1.png new file mode 100644 index 0000000..814bba6 Binary files /dev/null and b/images/cosmetics/armors/marmor1.png differ diff --git a/images/cosmetics/armors/marmor10.png b/images/cosmetics/armors/marmor10.png new file mode 100644 index 0000000..dcc5f98 Binary files /dev/null and b/images/cosmetics/armors/marmor10.png differ diff --git a/images/cosmetics/armors/marmor11.png b/images/cosmetics/armors/marmor11.png new file mode 100644 index 0000000..1ad60b4 Binary files /dev/null and b/images/cosmetics/armors/marmor11.png differ diff --git a/images/cosmetics/armors/marmor12.png b/images/cosmetics/armors/marmor12.png new file mode 100644 index 0000000..abc913f Binary files /dev/null and b/images/cosmetics/armors/marmor12.png differ diff --git a/images/cosmetics/armors/marmor2.png b/images/cosmetics/armors/marmor2.png new file mode 100644 index 0000000..ed5e5f2 Binary files /dev/null and b/images/cosmetics/armors/marmor2.png differ diff --git a/images/cosmetics/armors/marmor3.png b/images/cosmetics/armors/marmor3.png new file mode 100644 index 0000000..c46fc82 Binary files /dev/null and b/images/cosmetics/armors/marmor3.png differ diff --git a/images/cosmetics/armors/marmor4.png b/images/cosmetics/armors/marmor4.png new file mode 100644 index 0000000..d57c4c3 Binary files /dev/null and b/images/cosmetics/armors/marmor4.png differ diff --git a/images/cosmetics/armors/marmor5.png b/images/cosmetics/armors/marmor5.png new file mode 100644 index 0000000..415d03d Binary files /dev/null and b/images/cosmetics/armors/marmor5.png differ diff --git a/images/cosmetics/armors/marmor6.png b/images/cosmetics/armors/marmor6.png new file mode 100644 index 0000000..93da99c Binary files /dev/null and b/images/cosmetics/armors/marmor6.png differ diff --git a/images/cosmetics/armors/marmor7.png b/images/cosmetics/armors/marmor7.png new file mode 100644 index 0000000..c9708c8 Binary files /dev/null and b/images/cosmetics/armors/marmor7.png differ diff --git a/images/cosmetics/armors/marmor8.png b/images/cosmetics/armors/marmor8.png new file mode 100644 index 0000000..89a5df1 Binary files /dev/null and b/images/cosmetics/armors/marmor8.png differ diff --git a/images/cosmetics/armors/marmor9.png b/images/cosmetics/armors/marmor9.png new file mode 100644 index 0000000..2a58a4d Binary files /dev/null and b/images/cosmetics/armors/marmor9.png differ diff --git a/images/cosmetics/armors/mbody1.png b/images/cosmetics/armors/mbody1.png new file mode 100644 index 0000000..2f329ae Binary files /dev/null and b/images/cosmetics/armors/mbody1.png differ diff --git a/images/cosmetics/armors/mbody2.png b/images/cosmetics/armors/mbody2.png new file mode 100644 index 0000000..e76c95a Binary files /dev/null and b/images/cosmetics/armors/mbody2.png differ diff --git a/images/cosmetics/armors/mbody3.png b/images/cosmetics/armors/mbody3.png new file mode 100644 index 0000000..54ff8cc Binary files /dev/null and b/images/cosmetics/armors/mbody3.png differ diff --git a/images/cosmetics/armors/mbody4.png b/images/cosmetics/armors/mbody4.png new file mode 100644 index 0000000..1fa6728 Binary files /dev/null and b/images/cosmetics/armors/mbody4.png differ diff --git a/images/cosmetics/armors/mbody5.png b/images/cosmetics/armors/mbody5.png new file mode 100644 index 0000000..9734ec6 Binary files /dev/null and b/images/cosmetics/armors/mbody5.png differ diff --git a/images/cosmetics/armors/mbody6.png b/images/cosmetics/armors/mbody6.png new file mode 100644 index 0000000..84c707e Binary files /dev/null and b/images/cosmetics/armors/mbody6.png differ diff --git a/images/cosmetics/armors/sarmor1.png b/images/cosmetics/armors/sarmor1.png new file mode 100644 index 0000000..2c24220 Binary files /dev/null and b/images/cosmetics/armors/sarmor1.png differ diff --git a/images/cosmetics/armors/sarmor2.png b/images/cosmetics/armors/sarmor2.png new file mode 100644 index 0000000..a50f5de Binary files /dev/null and b/images/cosmetics/armors/sarmor2.png differ diff --git a/images/cosmetics/armors/sbody1.png b/images/cosmetics/armors/sbody1.png new file mode 100644 index 0000000..308516d Binary files /dev/null and b/images/cosmetics/armors/sbody1.png differ diff --git a/images/cosmetics/beardo/.DS_Store b/images/cosmetics/beardo/.DS_Store new file mode 100644 index 0000000..a881e7c Binary files /dev/null and b/images/cosmetics/beardo/.DS_Store differ diff --git a/images/cosmetics/beardo/beard1.png b/images/cosmetics/beardo/beard1.png new file mode 100644 index 0000000..e72250b Binary files /dev/null and b/images/cosmetics/beardo/beard1.png differ diff --git a/images/cosmetics/beardo/beards.png b/images/cosmetics/beardo/beards.png new file mode 100644 index 0000000..7022d98 Binary files /dev/null and b/images/cosmetics/beardo/beards.png differ diff --git a/images/cosmetics/beardo/beards_original.png b/images/cosmetics/beardo/beards_original.png new file mode 100644 index 0000000..d8d820b Binary files /dev/null and b/images/cosmetics/beardo/beards_original.png differ diff --git a/images/cosmetics/beardo/burningeyes1_anim.png b/images/cosmetics/beardo/burningeyes1_anim.png new file mode 100644 index 0000000..0aa5495 Binary files /dev/null and b/images/cosmetics/beardo/burningeyes1_anim.png differ diff --git a/images/cosmetics/beardo/burningeyes2_anim.png b/images/cosmetics/beardo/burningeyes2_anim.png new file mode 100644 index 0000000..b7c879b Binary files /dev/null and b/images/cosmetics/beardo/burningeyes2_anim.png differ diff --git a/images/cosmetics/beardo/facemakeup.png b/images/cosmetics/beardo/facemakeup.png new file mode 100644 index 0000000..c0de43b Binary files /dev/null and b/images/cosmetics/beardo/facemakeup.png differ diff --git a/images/cosmetics/beardo/mask1.png b/images/cosmetics/beardo/mask1.png new file mode 100644 index 0000000..bde0a64 Binary files /dev/null and b/images/cosmetics/beardo/mask1.png differ diff --git a/images/cosmetics/gravestones/gravestone.png b/images/cosmetics/gravestones/gravestone.png new file mode 100644 index 0000000..a9ae841 Binary files /dev/null and b/images/cosmetics/gravestones/gravestone.png differ diff --git a/images/cosmetics/hairdo/.DS_Store b/images/cosmetics/hairdo/.DS_Store new file mode 100644 index 0000000..e2a260f Binary files /dev/null and b/images/cosmetics/hairdo/.DS_Store differ diff --git a/images/cosmetics/hairdo/bwhair.png b/images/cosmetics/hairdo/bwhair.png new file mode 100644 index 0000000..d3fb039 Binary files /dev/null and b/images/cosmetics/hairdo/bwhair.png differ diff --git a/images/cosmetics/hairdo/hairdo1.png b/images/cosmetics/hairdo/hairdo1.png new file mode 100644 index 0000000..71abb8f Binary files /dev/null and b/images/cosmetics/hairdo/hairdo1.png differ diff --git a/images/cosmetics/hairdo/hairdo1_my.png b/images/cosmetics/hairdo/hairdo1_my.png new file mode 100644 index 0000000..d45a2c2 Binary files /dev/null and b/images/cosmetics/hairdo/hairdo1_my.png differ diff --git a/images/cosmetics/hairdo/hairdo2.png b/images/cosmetics/hairdo/hairdo2.png new file mode 100644 index 0000000..cff3eca Binary files /dev/null and b/images/cosmetics/hairdo/hairdo2.png differ diff --git a/images/cosmetics/hairdo/hairdo2_old.png b/images/cosmetics/hairdo/hairdo2_old.png new file mode 100644 index 0000000..345a1c2 Binary files /dev/null and b/images/cosmetics/hairdo/hairdo2_old.png differ diff --git a/images/cosmetics/hairdo/hairdo3.png b/images/cosmetics/hairdo/hairdo3.png new file mode 100644 index 0000000..044ec5e Binary files /dev/null and b/images/cosmetics/hairdo/hairdo3.png differ diff --git a/images/cosmetics/hairdo/hairdo3_old.png b/images/cosmetics/hairdo/hairdo3_old.png new file mode 100644 index 0000000..b2439b9 Binary files /dev/null and b/images/cosmetics/hairdo/hairdo3_old.png differ diff --git a/images/cosmetics/hairdo/hairdo4.png b/images/cosmetics/hairdo/hairdo4.png new file mode 100644 index 0000000..862c388 Binary files /dev/null and b/images/cosmetics/hairdo/hairdo4.png differ diff --git a/images/cosmetics/hairdo/hairdo4_old.png b/images/cosmetics/hairdo/hairdo4_old.png new file mode 100644 index 0000000..5727794 Binary files /dev/null and b/images/cosmetics/hairdo/hairdo4_old.png differ diff --git a/images/cosmetics/hairdo/hairdo5.png b/images/cosmetics/hairdo/hairdo5.png new file mode 100644 index 0000000..8ebce54 Binary files /dev/null and b/images/cosmetics/hairdo/hairdo5.png differ diff --git a/images/cosmetics/hairdo/hairdo5_old.png b/images/cosmetics/hairdo/hairdo5_old.png new file mode 100644 index 0000000..18d2a00 Binary files /dev/null and b/images/cosmetics/hairdo/hairdo5_old.png differ diff --git a/images/cosmetics/hairdo/hairdo6.png b/images/cosmetics/hairdo/hairdo6.png new file mode 100644 index 0000000..9758bda Binary files /dev/null and b/images/cosmetics/hairdo/hairdo6.png differ diff --git a/images/cosmetics/hats/.DS_Store b/images/cosmetics/hats/.DS_Store new file mode 100644 index 0000000..1e2d430 Binary files /dev/null and b/images/cosmetics/hats/.DS_Store differ diff --git a/images/cosmetics/hats/bathat_anim.png b/images/cosmetics/hats/bathat_anim.png new file mode 100644 index 0000000..2df5809 Binary files /dev/null and b/images/cosmetics/hats/bathat_anim.png differ diff --git a/images/cosmetics/hats/gcandle_anim.png b/images/cosmetics/hats/gcandle_anim.png new file mode 100644 index 0000000..64fa371 Binary files /dev/null and b/images/cosmetics/hats/gcandle_anim.png differ diff --git a/images/cosmetics/hats/halo_anim.png b/images/cosmetics/hats/halo_anim.png new file mode 100644 index 0000000..1f9c269 Binary files /dev/null and b/images/cosmetics/hats/halo_anim.png differ diff --git a/images/cosmetics/hats/hats1.png b/images/cosmetics/hats/hats1.png new file mode 100644 index 0000000..1744d06 Binary files /dev/null and b/images/cosmetics/hats/hats1.png differ diff --git a/images/cosmetics/hats/hats2.png b/images/cosmetics/hats/hats2.png new file mode 100644 index 0000000..24b1b93 Binary files /dev/null and b/images/cosmetics/hats/hats2.png differ diff --git a/images/cosmetics/hats/hats3.png b/images/cosmetics/hats/hats3.png new file mode 100644 index 0000000..73ecb01 Binary files /dev/null and b/images/cosmetics/hats/hats3.png differ diff --git a/images/cosmetics/hats/hats4.png b/images/cosmetics/hats/hats4.png new file mode 100644 index 0000000..4c902c5 Binary files /dev/null and b/images/cosmetics/hats/hats4.png differ diff --git a/images/cosmetics/makeup/.DS_Store b/images/cosmetics/makeup/.DS_Store new file mode 100644 index 0000000..3b59f71 Binary files /dev/null and b/images/cosmetics/makeup/.DS_Store differ diff --git a/images/cosmetics/makeup/female_makeup.png b/images/cosmetics/makeup/female_makeup.png new file mode 100644 index 0000000..2c4ba26 Binary files /dev/null and b/images/cosmetics/makeup/female_makeup.png differ diff --git a/images/cosmetics/makeup/femalemakeup.png b/images/cosmetics/makeup/femalemakeup.png new file mode 100644 index 0000000..8cd837f Binary files /dev/null and b/images/cosmetics/makeup/femalemakeup.png differ diff --git a/images/cosmetics/makeup/femalemakeupv2.png b/images/cosmetics/makeup/femalemakeupv2.png new file mode 100644 index 0000000..d41076d Binary files /dev/null and b/images/cosmetics/makeup/femalemakeupv2.png differ diff --git a/images/cosmetics/makeup/femalemakeupv2.pxm b/images/cosmetics/makeup/femalemakeupv2.pxm new file mode 100644 index 0000000..a9f12b5 Binary files /dev/null and b/images/cosmetics/makeup/femalemakeupv2.pxm differ diff --git a/images/cosmetics/makeup/fmakeup.png b/images/cosmetics/makeup/fmakeup.png new file mode 100644 index 0000000..1e60b90 Binary files /dev/null and b/images/cosmetics/makeup/fmakeup.png differ diff --git a/images/cosmetics/makeup/kunique.png b/images/cosmetics/makeup/kunique.png new file mode 100644 index 0000000..010eae1 Binary files /dev/null and b/images/cosmetics/makeup/kunique.png differ diff --git a/images/cosmetics/makeup/kunique.pxm b/images/cosmetics/makeup/kunique.pxm new file mode 100644 index 0000000..dae1183 Binary files /dev/null and b/images/cosmetics/makeup/kunique.pxm differ diff --git a/images/cosmetics/makeup/makeup1.png b/images/cosmetics/makeup/makeup1.png new file mode 100644 index 0000000..34a9082 Binary files /dev/null and b/images/cosmetics/makeup/makeup1.png differ diff --git a/images/cosmetics/makeup/makeup1.pxm b/images/cosmetics/makeup/makeup1.pxm new file mode 100644 index 0000000..b675261 Binary files /dev/null and b/images/cosmetics/makeup/makeup1.pxm differ diff --git a/images/cosmetics/makeup/makeup1_old.png b/images/cosmetics/makeup/makeup1_old.png new file mode 100644 index 0000000..403c536 Binary files /dev/null and b/images/cosmetics/makeup/makeup1_old.png differ diff --git a/images/cosmetics/makeup/male_makeup.png b/images/cosmetics/makeup/male_makeup.png new file mode 100644 index 0000000..cf46b1b Binary files /dev/null and b/images/cosmetics/makeup/male_makeup.png differ diff --git a/images/cosmetics/makeup/malemakeup.png b/images/cosmetics/makeup/malemakeup.png new file mode 100644 index 0000000..1d4b551 Binary files /dev/null and b/images/cosmetics/makeup/malemakeup.png differ diff --git a/images/cosmetics/makeup/smakeup.png b/images/cosmetics/makeup/smakeup.png new file mode 100644 index 0000000..dea5b66 Binary files /dev/null and b/images/cosmetics/makeup/smakeup.png differ diff --git a/images/cosmetics/makeup/unisex_makeup.png b/images/cosmetics/makeup/unisex_makeup.png new file mode 100644 index 0000000..e9abe99 Binary files /dev/null and b/images/cosmetics/makeup/unisex_makeup.png differ diff --git a/images/cosmetics/skins/.DS_Store b/images/cosmetics/skins/.DS_Store new file mode 100644 index 0000000..258122c Binary files /dev/null and b/images/cosmetics/skins/.DS_Store differ diff --git a/images/cosmetics/skins/lskin1.png b/images/cosmetics/skins/lskin1.png new file mode 100644 index 0000000..8e31a59 Binary files /dev/null and b/images/cosmetics/skins/lskin1.png differ diff --git a/images/cosmetics/skins/mbw.png b/images/cosmetics/skins/mbw.png new file mode 100644 index 0000000..2dde702 Binary files /dev/null and b/images/cosmetics/skins/mbw.png differ diff --git a/images/cosmetics/skins/mskin1.png b/images/cosmetics/skins/mskin1.png new file mode 100644 index 0000000..9bbb1bb Binary files /dev/null and b/images/cosmetics/skins/mskin1.png differ diff --git a/images/cosmetics/skins/sskin1.png b/images/cosmetics/skins/sskin1.png new file mode 100644 index 0000000..0429a10 Binary files /dev/null and b/images/cosmetics/skins/sskin1.png differ diff --git a/images/cosmetics/tails/wolftail.png b/images/cosmetics/tails/wolftail.png new file mode 100644 index 0000000..72acb96 Binary files /dev/null and b/images/cosmetics/tails/wolftail.png differ diff --git a/images/cosmetics/tails/wolftail2.png b/images/cosmetics/tails/wolftail2.png new file mode 100644 index 0000000..9e47aa8 Binary files /dev/null and b/images/cosmetics/tails/wolftail2.png differ diff --git a/images/cosmetics/tails/wolftail3.png b/images/cosmetics/tails/wolftail3.png new file mode 100644 index 0000000..7d2c483 Binary files /dev/null and b/images/cosmetics/tails/wolftail3.png differ diff --git a/images/cosmetics/wings/.DS_Store b/images/cosmetics/wings/.DS_Store new file mode 100644 index 0000000..afe0ac9 Binary files /dev/null and b/images/cosmetics/wings/.DS_Store differ diff --git a/images/cosmetics/wings/backpack2.png b/images/cosmetics/wings/backpack2.png new file mode 100644 index 0000000..7725f92 Binary files /dev/null and b/images/cosmetics/wings/backpack2.png differ diff --git a/images/cosmetics/wings/backpacks.png b/images/cosmetics/wings/backpacks.png new file mode 100644 index 0000000..7585ce8 Binary files /dev/null and b/images/cosmetics/wings/backpacks.png differ diff --git a/images/cosmetics/wings/wings1.png b/images/cosmetics/wings/wings1.png new file mode 100644 index 0000000..85f8e80 Binary files /dev/null and b/images/cosmetics/wings/wings1.png differ diff --git a/images/cosmetics/wings/wings2.png b/images/cosmetics/wings/wings2.png new file mode 100644 index 0000000..e56275b Binary files /dev/null and b/images/cosmetics/wings/wings2.png differ diff --git a/images/cosmetics/wings/wings3.png b/images/cosmetics/wings/wings3.png new file mode 100644 index 0000000..5aa2fe1 Binary files /dev/null and b/images/cosmetics/wings/wings3.png differ diff --git a/images/docs.png b/images/docs.png new file mode 100644 index 0000000..7b0ea49 Binary files /dev/null and b/images/docs.png differ diff --git a/images/docs.pxm b/images/docs.pxm new file mode 100644 index 0000000..fe65def Binary files /dev/null and b/images/docs.pxm differ diff --git a/images/favicon.png b/images/favicon.png new file mode 100644 index 0000000..9f44bdb Binary files /dev/null and b/images/favicon.png differ diff --git a/images/favicon2.png b/images/favicon2.png new file mode 100644 index 0000000..2a9d237 Binary files /dev/null and b/images/favicon2.png differ diff --git a/images/favicon3.png b/images/favicon3.png new file mode 100644 index 0000000..5513730 Binary files /dev/null and b/images/favicon3.png differ diff --git a/images/first_logo.png b/images/first_logo.png new file mode 100644 index 0000000..75fe6a9 Binary files /dev/null and b/images/first_logo.png differ diff --git a/images/misc/.DS_Store b/images/misc/.DS_Store new file mode 100644 index 0000000..0a46659 Binary files /dev/null and b/images/misc/.DS_Store differ diff --git a/images/misc/2-1_axe.png b/images/misc/2-1_axe.png new file mode 100644 index 0000000..2870b80 Binary files /dev/null and b/images/misc/2-1_axe.png differ diff --git a/images/misc/2-1_fishing_cast.png b/images/misc/2-1_fishing_cast.png new file mode 100644 index 0000000..c3078aa Binary files /dev/null and b/images/misc/2-1_fishing_cast.png differ diff --git a/images/misc/2-1_fishing_reel.png b/images/misc/2-1_fishing_reel.png new file mode 100644 index 0000000..3d65ba2 Binary files /dev/null and b/images/misc/2-1_fishing_reel.png differ diff --git a/images/misc/2-1_fishing_wait.png b/images/misc/2-1_fishing_wait.png new file mode 100644 index 0000000..c1435bc Binary files /dev/null and b/images/misc/2-1_fishing_wait.png differ diff --git a/images/misc/2-1_hammer.png b/images/misc/2-1_hammer.png new file mode 100644 index 0000000..f42c810 Binary files /dev/null and b/images/misc/2-1_hammer.png differ diff --git a/images/misc/2-1_hoe.png b/images/misc/2-1_hoe.png new file mode 100644 index 0000000..02eef0d Binary files /dev/null and b/images/misc/2-1_hoe.png differ diff --git a/images/misc/2-1_net.png b/images/misc/2-1_net.png new file mode 100644 index 0000000..8aff54c Binary files /dev/null and b/images/misc/2-1_net.png differ diff --git a/images/misc/2-1_pickaxe.png b/images/misc/2-1_pickaxe.png new file mode 100644 index 0000000..dd1039f Binary files /dev/null and b/images/misc/2-1_pickaxe.png differ diff --git a/images/misc/2-1_scythe.png b/images/misc/2-1_scythe.png new file mode 100644 index 0000000..354178c Binary files /dev/null and b/images/misc/2-1_scythe.png differ diff --git a/images/misc/2-1_wateringcan.png b/images/misc/2-1_wateringcan.png new file mode 100644 index 0000000..97dd3b1 Binary files /dev/null and b/images/misc/2-1_wateringcan.png differ diff --git a/images/misc/8U+Umx.png b/images/misc/8U+Umx.png new file mode 100644 index 0000000..23ca888 Binary files /dev/null and b/images/misc/8U+Umx.png differ diff --git a/images/misc/NPC6-2_emote.png b/images/misc/NPC6-2_emote.png new file mode 100644 index 0000000..459406f Binary files /dev/null and b/images/misc/NPC6-2_emote.png differ diff --git a/images/misc/Owe0E7.png b/images/misc/Owe0E7.png new file mode 100644 index 0000000..10008e2 Binary files /dev/null and b/images/misc/Owe0E7.png differ diff --git a/images/misc/airshipA_1.png b/images/misc/airshipA_1.png new file mode 100644 index 0000000..c1aa63f Binary files /dev/null and b/images/misc/airshipA_1.png differ diff --git a/images/misc/airshipA_shadow_1.png b/images/misc/airshipA_shadow_1.png new file mode 100644 index 0000000..c1a0bc5 Binary files /dev/null and b/images/misc/airshipA_shadow_1.png differ diff --git a/images/misc/aqueen.png b/images/misc/aqueen.png new file mode 100644 index 0000000..2b8ec8f Binary files /dev/null and b/images/misc/aqueen.png differ diff --git a/images/misc/attack_animations/tf_charsheet_atk_shadow.png b/images/misc/attack_animations/tf_charsheet_atk_shadow.png new file mode 100755 index 0000000..b7ece03 Binary files /dev/null and b/images/misc/attack_animations/tf_charsheet_atk_shadow.png differ diff --git a/images/misc/attack_animations/tf_charsheet_atk_shadowless.png b/images/misc/attack_animations/tf_charsheet_atk_shadowless.png new file mode 100755 index 0000000..9007046 Binary files /dev/null and b/images/misc/attack_animations/tf_charsheet_atk_shadowless.png differ diff --git a/images/misc/attack_animations/weaponsheet_dagger.png b/images/misc/attack_animations/weaponsheet_dagger.png new file mode 100755 index 0000000..83ff892 Binary files /dev/null and b/images/misc/attack_animations/weaponsheet_dagger.png differ diff --git a/images/misc/attack_animations/weaponsheet_spear.png b/images/misc/attack_animations/weaponsheet_spear.png new file mode 100755 index 0000000..609f7ec Binary files /dev/null and b/images/misc/attack_animations/weaponsheet_spear.png differ diff --git a/images/misc/attack_animations/weaponsheet_staff.png b/images/misc/attack_animations/weaponsheet_staff.png new file mode 100755 index 0000000..c285258 Binary files /dev/null and b/images/misc/attack_animations/weaponsheet_staff.png differ diff --git a/images/misc/attack_animations/weaponsheet_sword.png b/images/misc/attack_animations/weaponsheet_sword.png new file mode 100755 index 0000000..a9795d6 Binary files /dev/null and b/images/misc/attack_animations/weaponsheet_sword.png differ diff --git a/images/misc/attack_animations/weaponsheet_wand.png b/images/misc/attack_animations/weaponsheet_wand.png new file mode 100755 index 0000000..0cc9a27 Binary files /dev/null and b/images/misc/attack_animations/weaponsheet_wand.png differ diff --git a/images/misc/babies_A_1.png b/images/misc/babies_A_1.png new file mode 100644 index 0000000..d8f26a4 Binary files /dev/null and b/images/misc/babies_A_1.png differ diff --git a/images/misc/babies_B_1.png b/images/misc/babies_B_1.png new file mode 100644 index 0000000..64e01a8 Binary files /dev/null and b/images/misc/babies_B_1.png differ diff --git a/images/misc/bakery_foods_1.png b/images/misc/bakery_foods_1.png new file mode 100644 index 0000000..5ce9c84 Binary files /dev/null and b/images/misc/bakery_foods_1.png differ diff --git a/images/misc/balloons.png b/images/misc/balloons.png new file mode 100644 index 0000000..414dd4b Binary files /dev/null and b/images/misc/balloons.png differ diff --git a/images/misc/base_anim_axeswing_1.png b/images/misc/base_anim_axeswing_1.png new file mode 100644 index 0000000..fb696b1 Binary files /dev/null and b/images/misc/base_anim_axeswing_1.png differ diff --git a/images/misc/base_anim_axeswing_emptyhanded_1.png b/images/misc/base_anim_axeswing_emptyhanded_1.png new file mode 100644 index 0000000..84a1273 Binary files /dev/null and b/images/misc/base_anim_axeswing_emptyhanded_1.png differ diff --git a/images/misc/base_climb_1.png b/images/misc/base_climb_1.png new file mode 100644 index 0000000..0ede5b0 Binary files /dev/null and b/images/misc/base_climb_1.png differ diff --git a/images/misc/base_fishing_cast_1.png b/images/misc/base_fishing_cast_1.png new file mode 100644 index 0000000..ccdfc46 Binary files /dev/null and b/images/misc/base_fishing_cast_1.png differ diff --git a/images/misc/base_fishing_reel_1.png b/images/misc/base_fishing_reel_1.png new file mode 100644 index 0000000..0a121ca Binary files /dev/null and b/images/misc/base_fishing_reel_1.png differ diff --git a/images/misc/base_fishing_wait_1.png b/images/misc/base_fishing_wait_1.png new file mode 100644 index 0000000..d3e5a1f Binary files /dev/null and b/images/misc/base_fishing_wait_1.png differ diff --git a/images/misc/base_jockey_f_single_1.png b/images/misc/base_jockey_f_single_1.png new file mode 100644 index 0000000..b7fabbc Binary files /dev/null and b/images/misc/base_jockey_f_single_1.png differ diff --git a/images/misc/base_jockey_m_single_1.png b/images/misc/base_jockey_m_single_1.png new file mode 100644 index 0000000..22b19e7 Binary files /dev/null and b/images/misc/base_jockey_m_single_1.png differ diff --git a/images/misc/base_jump_1.png b/images/misc/base_jump_1.png new file mode 100644 index 0000000..4e85efc Binary files /dev/null and b/images/misc/base_jump_1.png differ diff --git a/images/misc/base_run_shadow_1.png b/images/misc/base_run_shadow_1.png new file mode 100644 index 0000000..40b951c Binary files /dev/null and b/images/misc/base_run_shadow_1.png differ diff --git a/images/misc/base_run_shadowless_1.png b/images/misc/base_run_shadowless_1.png new file mode 100644 index 0000000..c2128ed Binary files /dev/null and b/images/misc/base_run_shadowless_1.png differ diff --git a/images/misc/base_staff_1x.png b/images/misc/base_staff_1x.png new file mode 100644 index 0000000..003e585 Binary files /dev/null and b/images/misc/base_staff_1x.png differ diff --git a/images/misc/base_sword_1x.png b/images/misc/base_sword_1x.png new file mode 100644 index 0000000..1e46507 Binary files /dev/null and b/images/misc/base_sword_1x.png differ diff --git a/images/misc/bat_elf-2_6_sheet.png b/images/misc/bat_elf-2_6_sheet.png new file mode 100644 index 0000000..0f72bae Binary files /dev/null and b/images/misc/bat_elf-2_6_sheet.png differ diff --git a/images/misc/bat_lichcrusades_angel2.png b/images/misc/bat_lichcrusades_angel2.png new file mode 100644 index 0000000..cee12c7 Binary files /dev/null and b/images/misc/bat_lichcrusades_angel2.png differ diff --git a/images/misc/beholder_a_1.png b/images/misc/beholder_a_1.png new file mode 100644 index 0000000..ccb7fb8 Binary files /dev/null and b/images/misc/beholder_a_1.png differ diff --git a/images/misc/beholder_b_1.png b/images/misc/beholder_b_1.png new file mode 100644 index 0000000..5088196 Binary files /dev/null and b/images/misc/beholder_b_1.png differ diff --git a/images/misc/bellydancers_1.png b/images/misc/bellydancers_1.png new file mode 100644 index 0000000..47aee45 Binary files /dev/null and b/images/misc/bellydancers_1.png differ diff --git a/images/misc/birds_sitting_1.png b/images/misc/birds_sitting_1.png new file mode 100644 index 0000000..7f6879d Binary files /dev/null and b/images/misc/birds_sitting_1.png differ diff --git a/images/misc/blackknight_sheet.png b/images/misc/blackknight_sheet.png new file mode 100644 index 0000000..7b256d3 Binary files /dev/null and b/images/misc/blackknight_sheet.png differ diff --git a/images/misc/blood1.png b/images/misc/blood1.png new file mode 100644 index 0000000..920ac96 Binary files /dev/null and b/images/misc/blood1.png differ diff --git a/images/misc/blueshaman_emotes_single.png b/images/misc/blueshaman_emotes_single.png new file mode 100644 index 0000000..6670989 Binary files /dev/null and b/images/misc/blueshaman_emotes_single.png differ diff --git a/images/misc/bughero_emotes_1.png b/images/misc/bughero_emotes_1.png new file mode 100644 index 0000000..7551a43 Binary files /dev/null and b/images/misc/bughero_emotes_1.png differ diff --git a/images/misc/buttonset1.png b/images/misc/buttonset1.png new file mode 100644 index 0000000..388fe83 Binary files /dev/null and b/images/misc/buttonset1.png differ diff --git a/images/misc/candles_shee_1.png b/images/misc/candles_shee_1.png new file mode 100644 index 0000000..6bf62e2 Binary files /dev/null and b/images/misc/candles_shee_1.png differ diff --git a/images/misc/casting_basea_1.png b/images/misc/casting_basea_1.png new file mode 100644 index 0000000..c9bac1c Binary files /dev/null and b/images/misc/casting_basea_1.png differ diff --git a/images/misc/casting_baseb_1.png b/images/misc/casting_baseb_1.png new file mode 100644 index 0000000..25a1044 Binary files /dev/null and b/images/misc/casting_baseb_1.png differ diff --git a/images/misc/christmaspresents_1.png b/images/misc/christmaspresents_1.png new file mode 100644 index 0000000..d98f322 Binary files /dev/null and b/images/misc/christmaspresents_1.png differ diff --git a/images/misc/christmastiles_1.png b/images/misc/christmastiles_1.png new file mode 100644 index 0000000..90b1487 Binary files /dev/null and b/images/misc/christmastiles_1.png differ diff --git a/images/misc/cloudcity_worldmap_1.png b/images/misc/cloudcity_worldmap_1.png new file mode 100644 index 0000000..625c3b5 Binary files /dev/null and b/images/misc/cloudcity_worldmap_1.png differ diff --git a/images/misc/colosseum_world_1.png b/images/misc/colosseum_world_1.png new file mode 100644 index 0000000..5fa5f17 Binary files /dev/null and b/images/misc/colosseum_world_1.png differ diff --git a/images/misc/corgan_1.png b/images/misc/corgan_1.png new file mode 100644 index 0000000..052ef34 Binary files /dev/null and b/images/misc/corgan_1.png differ diff --git a/images/misc/crl0hZ.png b/images/misc/crl0hZ.png new file mode 100644 index 0000000..0d7e302 Binary files /dev/null and b/images/misc/crl0hZ.png differ diff --git a/images/misc/crystalorb_rm_1_green.png b/images/misc/crystalorb_rm_1_green.png new file mode 100644 index 0000000..f0479ad Binary files /dev/null and b/images/misc/crystalorb_rm_1_green.png differ diff --git a/images/misc/crystalorb_rm_1_red.png b/images/misc/crystalorb_rm_1_red.png new file mode 100644 index 0000000..e86b52b Binary files /dev/null and b/images/misc/crystalorb_rm_1_red.png differ diff --git a/images/misc/crystalorb_rm_1_yellow.png b/images/misc/crystalorb_rm_1_yellow.png new file mode 100644 index 0000000..af13892 Binary files /dev/null and b/images/misc/crystalorb_rm_1_yellow.png differ diff --git a/images/misc/daigintwallpreview.png b/images/misc/daigintwallpreview.png new file mode 100644 index 0000000..5399284 Binary files /dev/null and b/images/misc/daigintwallpreview.png differ diff --git a/images/misc/demking_battler_1.png b/images/misc/demking_battler_1.png new file mode 100644 index 0000000..ace0cbb Binary files /dev/null and b/images/misc/demking_battler_1.png differ diff --git a/images/misc/demon_1.png b/images/misc/demon_1.png new file mode 100644 index 0000000..5e83957 Binary files /dev/null and b/images/misc/demon_1.png differ diff --git a/images/misc/demonking.png b/images/misc/demonking.png new file mode 100644 index 0000000..5dbbb9a Binary files /dev/null and b/images/misc/demonking.png differ diff --git a/images/misc/demonking_1.png b/images/misc/demonking_1.png new file mode 100644 index 0000000..be1c956 Binary files /dev/null and b/images/misc/demonking_1.png differ diff --git a/images/misc/demonking_full_nowings_1.png b/images/misc/demonking_full_nowings_1.png new file mode 100644 index 0000000..c20a8ad Binary files /dev/null and b/images/misc/demonking_full_nowings_1.png differ diff --git a/images/misc/demonking_full_wings_1.png b/images/misc/demonking_full_wings_1.png new file mode 100644 index 0000000..ecb8778 Binary files /dev/null and b/images/misc/demonking_full_wings_1.png differ diff --git a/images/misc/demonkingb_full_mowings_1.png b/images/misc/demonkingb_full_mowings_1.png new file mode 100644 index 0000000..d74905c Binary files /dev/null and b/images/misc/demonkingb_full_mowings_1.png differ diff --git a/images/misc/demonkingb_full_wings_1.png b/images/misc/demonkingb_full_wings_1.png new file mode 100644 index 0000000..0b2730d Binary files /dev/null and b/images/misc/demonkingb_full_wings_1.png differ diff --git a/images/misc/diag_1.png b/images/misc/diag_1.png new file mode 100644 index 0000000..235c8d2 Binary files /dev/null and b/images/misc/diag_1.png differ diff --git a/images/misc/diag_side_bookcase_1.png b/images/misc/diag_side_bookcase_1.png new file mode 100644 index 0000000..92a4e03 Binary files /dev/null and b/images/misc/diag_side_bookcase_1.png differ diff --git a/images/misc/diagfull_1.png b/images/misc/diagfull_1.png new file mode 100644 index 0000000..5c3b397 Binary files /dev/null and b/images/misc/diagfull_1.png differ diff --git a/images/misc/doors_new_1.png b/images/misc/doors_new_1.png new file mode 100644 index 0000000..f4dea96 Binary files /dev/null and b/images/misc/doors_new_1.png differ diff --git a/images/misc/dotd_skulls_1.png b/images/misc/dotd_skulls_1.png new file mode 100644 index 0000000..9d86bd5 Binary files /dev/null and b/images/misc/dotd_skulls_1.png differ diff --git a/images/misc/down1_1.png b/images/misc/down1_1.png new file mode 100644 index 0000000..287a37a Binary files /dev/null and b/images/misc/down1_1.png differ diff --git a/images/misc/down2_1.png b/images/misc/down2_1.png new file mode 100644 index 0000000..3e5f5e7 Binary files /dev/null and b/images/misc/down2_1.png differ diff --git a/images/misc/down_npc_a_1.png b/images/misc/down_npc_a_1.png new file mode 100644 index 0000000..7839ce8 Binary files /dev/null and b/images/misc/down_npc_a_1.png differ diff --git a/images/misc/down_patreonspecial_1.png b/images/misc/down_patreonspecial_1.png new file mode 100644 index 0000000..8f51bea Binary files /dev/null and b/images/misc/down_patreonspecial_1.png differ diff --git a/images/misc/down_patreonspecial_1_updated.png b/images/misc/down_patreonspecial_1_updated.png new file mode 100644 index 0000000..e6e0cf6 Binary files /dev/null and b/images/misc/down_patreonspecial_1_updated.png differ diff --git a/images/misc/downm_1.png b/images/misc/downm_1.png new file mode 100644 index 0000000..f5efc0f Binary files /dev/null and b/images/misc/downm_1.png differ diff --git a/images/misc/dragon.png b/images/misc/dragon.png new file mode 100644 index 0000000..f534ce1 Binary files /dev/null and b/images/misc/dragon.png differ diff --git a/images/misc/elder_dead_1.png b/images/misc/elder_dead_1.png new file mode 100644 index 0000000..0be7672 Binary files /dev/null and b/images/misc/elder_dead_1.png differ diff --git a/images/misc/examples.pxm b/images/misc/examples.pxm new file mode 100644 index 0000000..ad323ce Binary files /dev/null and b/images/misc/examples.pxm differ diff --git a/images/misc/facs_mv1.png b/images/misc/facs_mv1.png new file mode 100644 index 0000000..a4636db Binary files /dev/null and b/images/misc/facs_mv1.png differ diff --git a/images/misc/flagpoles_1.png b/images/misc/flagpoles_1.png new file mode 100644 index 0000000..fb882af Binary files /dev/null and b/images/misc/flagpoles_1.png differ diff --git a/images/misc/food_1.png b/images/misc/food_1.png new file mode 100644 index 0000000..56ae491 Binary files /dev/null and b/images/misc/food_1.png differ diff --git a/images/misc/genie_emotes_single.png b/images/misc/genie_emotes_single.png new file mode 100644 index 0000000..cd74613 Binary files /dev/null and b/images/misc/genie_emotes_single.png differ diff --git a/images/misc/genielamp_1.png b/images/misc/genielamp_1.png new file mode 100644 index 0000000..3a54c56 Binary files /dev/null and b/images/misc/genielamp_1.png differ diff --git a/images/misc/gob_spear.png b/images/misc/gob_spear.png new file mode 100644 index 0000000..0f796ca Binary files /dev/null and b/images/misc/gob_spear.png differ diff --git a/images/misc/gob_spear_shield.png b/images/misc/gob_spear_shield.png new file mode 100644 index 0000000..9acb183 Binary files /dev/null and b/images/misc/gob_spear_shield.png differ diff --git a/images/misc/gwasp_1.png b/images/misc/gwasp_1.png new file mode 100644 index 0000000..e3c1951 Binary files /dev/null and b/images/misc/gwasp_1.png differ diff --git a/images/misc/hallowicons_1.png b/images/misc/hallowicons_1.png new file mode 100644 index 0000000..bfb3505 Binary files /dev/null and b/images/misc/hallowicons_1.png differ diff --git a/images/misc/horsecart_1.png b/images/misc/horsecart_1.png new file mode 100644 index 0000000..e43b9b4 Binary files /dev/null and b/images/misc/horsecart_1.png differ diff --git a/images/misc/horseman_a_1.png b/images/misc/horseman_a_1.png new file mode 100644 index 0000000..5f81e45 Binary files /dev/null and b/images/misc/horseman_a_1.png differ diff --git a/images/misc/horseman_b_1.png b/images/misc/horseman_b_1.png new file mode 100644 index 0000000..0a1bc9e Binary files /dev/null and b/images/misc/horseman_b_1.png differ diff --git a/images/misc/horseman_c_1.png b/images/misc/horseman_c_1.png new file mode 100644 index 0000000..6f8467f Binary files /dev/null and b/images/misc/horseman_c_1.png differ diff --git a/images/misc/hotairballoon_1.png b/images/misc/hotairballoon_1.png new file mode 100644 index 0000000..0e52306 Binary files /dev/null and b/images/misc/hotairballoon_1.png differ diff --git a/images/misc/humanwolfcharA_emot_1.png b/images/misc/humanwolfcharA_emot_1.png new file mode 100644 index 0000000..ef6dd75 Binary files /dev/null and b/images/misc/humanwolfcharA_emot_1.png differ diff --git a/images/misc/humanwolfcharB_emot_1.png b/images/misc/humanwolfcharB_emot_1.png new file mode 100644 index 0000000..7348b7a Binary files /dev/null and b/images/misc/humanwolfcharB_emot_1.png differ diff --git a/images/misc/icons_accessoriesA_16.png b/images/misc/icons_accessoriesA_16.png new file mode 100644 index 0000000..a8bf3d9 Binary files /dev/null and b/images/misc/icons_accessoriesA_16.png differ diff --git a/images/misc/icons_armorset_16.png b/images/misc/icons_armorset_16.png new file mode 100644 index 0000000..d1b131c Binary files /dev/null and b/images/misc/icons_armorset_16.png differ diff --git a/images/misc/icons_cloaks_16.png b/images/misc/icons_cloaks_16.png new file mode 100644 index 0000000..400dfc5 Binary files /dev/null and b/images/misc/icons_cloaks_16.png differ diff --git a/images/misc/icons_feet_16.png b/images/misc/icons_feet_16.png new file mode 100644 index 0000000..a24e911 Binary files /dev/null and b/images/misc/icons_feet_16.png differ diff --git a/images/misc/icons_formalclothes_16.png b/images/misc/icons_formalclothes_16.png new file mode 100644 index 0000000..3404942 Binary files /dev/null and b/images/misc/icons_formalclothes_16.png differ diff --git a/images/misc/icons_full_16.png b/images/misc/icons_full_16.png new file mode 100644 index 0000000..076d33d Binary files /dev/null and b/images/misc/icons_full_16.png differ diff --git a/images/misc/icons_gloves_16.png b/images/misc/icons_gloves_16.png new file mode 100644 index 0000000..a7571e0 Binary files /dev/null and b/images/misc/icons_gloves_16.png differ diff --git a/images/misc/icons_hammers_16_fc.png b/images/misc/icons_hammers_16_fc.png new file mode 100644 index 0000000..08c2593 Binary files /dev/null and b/images/misc/icons_hammers_16_fc.png differ diff --git a/images/misc/icons_helm_16.png b/images/misc/icons_helm_16.png new file mode 100644 index 0000000..e44247b Binary files /dev/null and b/images/misc/icons_helm_16.png differ diff --git a/images/misc/icons_lightarmor_16.png b/images/misc/icons_lightarmor_16.png new file mode 100644 index 0000000..7e724d7 Binary files /dev/null and b/images/misc/icons_lightarmor_16.png differ diff --git a/images/misc/icons_midarmor_16.png b/images/misc/icons_midarmor_16.png new file mode 100644 index 0000000..f96ed2f Binary files /dev/null and b/images/misc/icons_midarmor_16.png differ diff --git a/images/misc/icons_misc1_16.png b/images/misc/icons_misc1_16.png new file mode 100644 index 0000000..36a8c8f Binary files /dev/null and b/images/misc/icons_misc1_16.png differ diff --git a/images/misc/icons_misc2_16.png b/images/misc/icons_misc2_16.png new file mode 100644 index 0000000..45f18cf Binary files /dev/null and b/images/misc/icons_misc2_16.png differ diff --git a/images/misc/icons_misc3_16.png b/images/misc/icons_misc3_16.png new file mode 100644 index 0000000..053f0a1 Binary files /dev/null and b/images/misc/icons_misc3_16.png differ diff --git a/images/misc/icons_skillsa_16.png b/images/misc/icons_skillsa_16.png new file mode 100644 index 0000000..0e8293b Binary files /dev/null and b/images/misc/icons_skillsa_16.png differ diff --git a/images/misc/icons_tf_16.png b/images/misc/icons_tf_16.png new file mode 100644 index 0000000..98d8c30 Binary files /dev/null and b/images/misc/icons_tf_16.png differ diff --git a/images/misc/icons_tools_16.png b/images/misc/icons_tools_16.png new file mode 100644 index 0000000..6495f5d Binary files /dev/null and b/images/misc/icons_tools_16.png differ diff --git a/images/misc/icons_ui_16.png b/images/misc/icons_ui_16.png new file mode 100644 index 0000000..4b983ea Binary files /dev/null and b/images/misc/icons_ui_16.png differ diff --git a/images/misc/jacko_b_1.png b/images/misc/jacko_b_1.png new file mode 100644 index 0000000..57c9d2d Binary files /dev/null and b/images/misc/jacko_b_1.png differ diff --git a/images/misc/jacko_c_1.png b/images/misc/jacko_c_1.png new file mode 100644 index 0000000..4ab7a6a Binary files /dev/null and b/images/misc/jacko_c_1.png differ diff --git a/images/misc/japan.png b/images/misc/japan.png new file mode 100644 index 0000000..a687661 Binary files /dev/null and b/images/misc/japan.png differ diff --git a/images/misc/judge_hammer_single_1.png b/images/misc/judge_hammer_single_1.png new file mode 100644 index 0000000..5b4cfa5 Binary files /dev/null and b/images/misc/judge_hammer_single_1.png differ diff --git a/images/misc/magic_circles_1.png b/images/misc/magic_circles_1.png new file mode 100644 index 0000000..a2777fc Binary files /dev/null and b/images/misc/magic_circles_1.png differ diff --git a/images/misc/marrows_icon16.png b/images/misc/marrows_icon16.png new file mode 100644 index 0000000..70602c2 Binary files /dev/null and b/images/misc/marrows_icon16.png differ diff --git a/images/misc/mer_8_1.png b/images/misc/mer_8_1.png new file mode 100644 index 0000000..7b5fd9e Binary files /dev/null and b/images/misc/mer_8_1.png differ diff --git a/images/misc/mer_8_chars1.png b/images/misc/mer_8_chars1.png new file mode 100644 index 0000000..24864c9 Binary files /dev/null and b/images/misc/mer_8_chars1.png differ diff --git a/images/misc/milk-icons-1.png b/images/misc/milk-icons-1.png new file mode 100644 index 0000000..2bb24b8 Binary files /dev/null and b/images/misc/milk-icons-1.png differ diff --git a/images/misc/minecart_char_1.png b/images/misc/minecart_char_1.png new file mode 100644 index 0000000..d349dae Binary files /dev/null and b/images/misc/minecart_char_1.png differ diff --git a/images/misc/mining-anim-base_1.png b/images/misc/mining-anim-base_1.png new file mode 100644 index 0000000..c524098 Binary files /dev/null and b/images/misc/mining-anim-base_1.png differ diff --git a/images/misc/motorbike_blue_1.png b/images/misc/motorbike_blue_1.png new file mode 100644 index 0000000..b39f2ee Binary files /dev/null and b/images/misc/motorbike_blue_1.png differ diff --git a/images/misc/motorbike_red_1.png b/images/misc/motorbike_red_1.png new file mode 100644 index 0000000..02e130a Binary files /dev/null and b/images/misc/motorbike_red_1.png differ diff --git a/images/misc/motorbike_riderbase_1.png b/images/misc/motorbike_riderbase_1.png new file mode 100644 index 0000000..5543b89 Binary files /dev/null and b/images/misc/motorbike_riderbase_1.png differ diff --git a/images/misc/motorbike_yellow_1.png b/images/misc/motorbike_yellow_1.png new file mode 100644 index 0000000..cb52b37 Binary files /dev/null and b/images/misc/motorbike_yellow_1.png differ diff --git a/images/misc/mshields_icon16.png b/images/misc/mshields_icon16.png new file mode 100644 index 0000000..24aceb5 Binary files /dev/null and b/images/misc/mshields_icon16.png differ diff --git a/images/misc/mskills2_icon16.png b/images/misc/mskills2_icon16.png new file mode 100644 index 0000000..05b580c Binary files /dev/null and b/images/misc/mskills2_icon16.png differ diff --git a/images/misc/mskills_icon16.png b/images/misc/mskills_icon16.png new file mode 100644 index 0000000..f223ee5 Binary files /dev/null and b/images/misc/mskills_icon16.png differ diff --git a/images/misc/mspears_icon16.png b/images/misc/mspears_icon16.png new file mode 100644 index 0000000..0d111ec Binary files /dev/null and b/images/misc/mspears_icon16.png differ diff --git a/images/misc/mstaffs_icon16.png b/images/misc/mstaffs_icon16.png new file mode 100644 index 0000000..0fb7a86 Binary files /dev/null and b/images/misc/mstaffs_icon16.png differ diff --git a/images/misc/mswords_icon16.png b/images/misc/mswords_icon16.png new file mode 100644 index 0000000..9d7805b Binary files /dev/null and b/images/misc/mswords_icon16.png differ diff --git a/images/misc/newchests-mimics_1.png b/images/misc/newchests-mimics_1.png new file mode 100644 index 0000000..cf0329e Binary files /dev/null and b/images/misc/newchests-mimics_1.png differ diff --git a/images/misc/npc5-6_emotes_single.png b/images/misc/npc5-6_emotes_single.png new file mode 100644 index 0000000..08ad4e6 Binary files /dev/null and b/images/misc/npc5-6_emotes_single.png differ diff --git a/images/misc/pickuptrucks_1.png b/images/misc/pickuptrucks_1.png new file mode 100644 index 0000000..2ee1bfc Binary files /dev/null and b/images/misc/pickuptrucks_1.png differ diff --git a/images/misc/pinktrees_1x.png b/images/misc/pinktrees_1x.png new file mode 100644 index 0000000..58a4233 Binary files /dev/null and b/images/misc/pinktrees_1x.png differ diff --git a/images/misc/pointersb_1.png b/images/misc/pointersb_1.png new file mode 100644 index 0000000..c475912 Binary files /dev/null and b/images/misc/pointersb_1.png differ diff --git a/images/misc/portal_blue_1.png b/images/misc/portal_blue_1.png new file mode 100644 index 0000000..30fb568 Binary files /dev/null and b/images/misc/portal_blue_1.png differ diff --git a/images/misc/portal_blue_close_1.png b/images/misc/portal_blue_close_1.png new file mode 100644 index 0000000..2278979 Binary files /dev/null and b/images/misc/portal_blue_close_1.png differ diff --git a/images/misc/portal_blue_open_1.png b/images/misc/portal_blue_open_1.png new file mode 100644 index 0000000..7f370a3 Binary files /dev/null and b/images/misc/portal_blue_open_1.png differ diff --git a/images/misc/portal_purple_1.png b/images/misc/portal_purple_1.png new file mode 100644 index 0000000..5d2e460 Binary files /dev/null and b/images/misc/portal_purple_1.png differ diff --git a/images/misc/portal_purple_close_1.png b/images/misc/portal_purple_close_1.png new file mode 100644 index 0000000..ea692a1 Binary files /dev/null and b/images/misc/portal_purple_close_1.png differ diff --git a/images/misc/portal_purple_open_1.png b/images/misc/portal_purple_open_1.png new file mode 100644 index 0000000..7cc078f Binary files /dev/null and b/images/misc/portal_purple_open_1.png differ diff --git a/images/misc/portal_red_1.png b/images/misc/portal_red_1.png new file mode 100644 index 0000000..d54a299 Binary files /dev/null and b/images/misc/portal_red_1.png differ diff --git a/images/misc/portal_red_close_1.png b/images/misc/portal_red_close_1.png new file mode 100644 index 0000000..f1e5a26 Binary files /dev/null and b/images/misc/portal_red_close_1.png differ diff --git a/images/misc/portal_red_open_1.png b/images/misc/portal_red_open_1.png new file mode 100644 index 0000000..675b08a Binary files /dev/null and b/images/misc/portal_red_open_1.png differ diff --git a/images/misc/portal_stone_1.png b/images/misc/portal_stone_1.png new file mode 100644 index 0000000..fe60b7f Binary files /dev/null and b/images/misc/portal_stone_1.png differ diff --git a/images/misc/portal_stone_close_1.png b/images/misc/portal_stone_close_1.png new file mode 100644 index 0000000..97bf6d1 Binary files /dev/null and b/images/misc/portal_stone_close_1.png differ diff --git a/images/misc/portal_stone_open_1.png b/images/misc/portal_stone_open_1.png new file mode 100644 index 0000000..279d23a Binary files /dev/null and b/images/misc/portal_stone_open_1.png differ diff --git a/images/misc/priestess_single_1.png b/images/misc/priestess_single_1.png new file mode 100644 index 0000000..79f1c37 Binary files /dev/null and b/images/misc/priestess_single_1.png differ diff --git a/images/misc/priestess_single_emote_1.png b/images/misc/priestess_single_emote_1.png new file mode 100644 index 0000000..667c9cc Binary files /dev/null and b/images/misc/priestess_single_emote_1.png differ diff --git a/images/misc/sharkmouth.png b/images/misc/sharkmouth.png new file mode 100644 index 0000000..4dfa25f Binary files /dev/null and b/images/misc/sharkmouth.png differ diff --git a/images/misc/shoot/frames/char_north_shoot_1.png b/images/misc/shoot/frames/char_north_shoot_1.png new file mode 100755 index 0000000..7875bdd Binary files /dev/null and b/images/misc/shoot/frames/char_north_shoot_1.png differ diff --git a/images/misc/shoot/frames/char_north_shoot_2.png b/images/misc/shoot/frames/char_north_shoot_2.png new file mode 100755 index 0000000..ebf4e26 Binary files /dev/null and b/images/misc/shoot/frames/char_north_shoot_2.png differ diff --git a/images/misc/shoot/frames/char_north_shoot_3.png b/images/misc/shoot/frames/char_north_shoot_3.png new file mode 100755 index 0000000..aa4f986 Binary files /dev/null and b/images/misc/shoot/frames/char_north_shoot_3.png differ diff --git a/images/misc/shoot/frames/char_side_shoot_1.png b/images/misc/shoot/frames/char_side_shoot_1.png new file mode 100755 index 0000000..c405b9e Binary files /dev/null and b/images/misc/shoot/frames/char_side_shoot_1.png differ diff --git a/images/misc/shoot/frames/char_side_shoot_2.png b/images/misc/shoot/frames/char_side_shoot_2.png new file mode 100755 index 0000000..a0fa566 Binary files /dev/null and b/images/misc/shoot/frames/char_side_shoot_2.png differ diff --git a/images/misc/shoot/frames/char_side_shoot_3.png b/images/misc/shoot/frames/char_side_shoot_3.png new file mode 100755 index 0000000..9be4408 Binary files /dev/null and b/images/misc/shoot/frames/char_side_shoot_3.png differ diff --git a/images/misc/shoot/frames/char_south_shoot_1.png b/images/misc/shoot/frames/char_south_shoot_1.png new file mode 100755 index 0000000..5a03558 Binary files /dev/null and b/images/misc/shoot/frames/char_south_shoot_1.png differ diff --git a/images/misc/shoot/frames/char_south_shoot_2.png b/images/misc/shoot/frames/char_south_shoot_2.png new file mode 100755 index 0000000..a34bdc6 Binary files /dev/null and b/images/misc/shoot/frames/char_south_shoot_2.png differ diff --git a/images/misc/shoot/frames/char_south_shoot_3.png b/images/misc/shoot/frames/char_south_shoot_3.png new file mode 100755 index 0000000..948392b Binary files /dev/null and b/images/misc/shoot/frames/char_south_shoot_3.png differ diff --git a/images/misc/shoot/frames/shadow.png b/images/misc/shoot/frames/shadow.png new file mode 100755 index 0000000..25eb08f Binary files /dev/null and b/images/misc/shoot/frames/shadow.png differ diff --git a/images/misc/shoot/frames/weapons/bow_north_shoot1.png b/images/misc/shoot/frames/weapons/bow_north_shoot1.png new file mode 100755 index 0000000..ab4cf33 Binary files /dev/null and b/images/misc/shoot/frames/weapons/bow_north_shoot1.png differ diff --git a/images/misc/shoot/frames/weapons/bow_north_shoot2.png b/images/misc/shoot/frames/weapons/bow_north_shoot2.png new file mode 100755 index 0000000..9821bdb Binary files /dev/null and b/images/misc/shoot/frames/weapons/bow_north_shoot2.png differ diff --git a/images/misc/shoot/frames/weapons/bow_north_shoot3.png b/images/misc/shoot/frames/weapons/bow_north_shoot3.png new file mode 100755 index 0000000..304cf54 Binary files /dev/null and b/images/misc/shoot/frames/weapons/bow_north_shoot3.png differ diff --git a/images/misc/shoot/frames/weapons/bow_side_shoot1.png b/images/misc/shoot/frames/weapons/bow_side_shoot1.png new file mode 100755 index 0000000..a30c94f Binary files /dev/null and b/images/misc/shoot/frames/weapons/bow_side_shoot1.png differ diff --git a/images/misc/shoot/frames/weapons/bow_side_shoot2.png b/images/misc/shoot/frames/weapons/bow_side_shoot2.png new file mode 100755 index 0000000..ab890e9 Binary files /dev/null and b/images/misc/shoot/frames/weapons/bow_side_shoot2.png differ diff --git a/images/misc/shoot/frames/weapons/bow_side_shoot3.png b/images/misc/shoot/frames/weapons/bow_side_shoot3.png new file mode 100755 index 0000000..28b7b2a Binary files /dev/null and b/images/misc/shoot/frames/weapons/bow_side_shoot3.png differ diff --git a/images/misc/shoot/frames/weapons/bow_south_shoot1.png b/images/misc/shoot/frames/weapons/bow_south_shoot1.png new file mode 100755 index 0000000..06d3ddf Binary files /dev/null and b/images/misc/shoot/frames/weapons/bow_south_shoot1.png differ diff --git a/images/misc/shoot/frames/weapons/bow_south_shoot2.png b/images/misc/shoot/frames/weapons/bow_south_shoot2.png new file mode 100755 index 0000000..39d82e6 Binary files /dev/null and b/images/misc/shoot/frames/weapons/bow_south_shoot2.png differ diff --git a/images/misc/shoot/frames/weapons/bow_south_shoot3.png b/images/misc/shoot/frames/weapons/bow_south_shoot3.png new file mode 100755 index 0000000..169239b Binary files /dev/null and b/images/misc/shoot/frames/weapons/bow_south_shoot3.png differ diff --git a/images/misc/shoot/frames/weapons/crossbow_north_shoot1.png b/images/misc/shoot/frames/weapons/crossbow_north_shoot1.png new file mode 100755 index 0000000..ebd24ea Binary files /dev/null and b/images/misc/shoot/frames/weapons/crossbow_north_shoot1.png differ diff --git a/images/misc/shoot/frames/weapons/crossbow_north_shoot2.png b/images/misc/shoot/frames/weapons/crossbow_north_shoot2.png new file mode 100755 index 0000000..a38952e Binary files /dev/null and b/images/misc/shoot/frames/weapons/crossbow_north_shoot2.png differ diff --git a/images/misc/shoot/frames/weapons/crossbow_north_shoot3.png b/images/misc/shoot/frames/weapons/crossbow_north_shoot3.png new file mode 100755 index 0000000..68b5fdf Binary files /dev/null and b/images/misc/shoot/frames/weapons/crossbow_north_shoot3.png differ diff --git a/images/misc/shoot/frames/weapons/crossbow_side_shoot1.png b/images/misc/shoot/frames/weapons/crossbow_side_shoot1.png new file mode 100755 index 0000000..f31364c Binary files /dev/null and b/images/misc/shoot/frames/weapons/crossbow_side_shoot1.png differ diff --git a/images/misc/shoot/frames/weapons/crossbow_side_shoot2.png b/images/misc/shoot/frames/weapons/crossbow_side_shoot2.png new file mode 100755 index 0000000..854d91b Binary files /dev/null and b/images/misc/shoot/frames/weapons/crossbow_side_shoot2.png differ diff --git a/images/misc/shoot/frames/weapons/crossbow_side_shoot3.png b/images/misc/shoot/frames/weapons/crossbow_side_shoot3.png new file mode 100755 index 0000000..a40165e Binary files /dev/null and b/images/misc/shoot/frames/weapons/crossbow_side_shoot3.png differ diff --git a/images/misc/shoot/frames/weapons/crossbow_south_shoot1.png b/images/misc/shoot/frames/weapons/crossbow_south_shoot1.png new file mode 100755 index 0000000..0120426 Binary files /dev/null and b/images/misc/shoot/frames/weapons/crossbow_south_shoot1.png differ diff --git a/images/misc/shoot/frames/weapons/crossbow_south_shoot2.png b/images/misc/shoot/frames/weapons/crossbow_south_shoot2.png new file mode 100755 index 0000000..6d4b9b0 Binary files /dev/null and b/images/misc/shoot/frames/weapons/crossbow_south_shoot2.png differ diff --git a/images/misc/shoot/frames/weapons/crossbow_south_shoot3.png b/images/misc/shoot/frames/weapons/crossbow_south_shoot3.png new file mode 100755 index 0000000..74fae15 Binary files /dev/null and b/images/misc/shoot/frames/weapons/crossbow_south_shoot3.png differ diff --git a/images/misc/shoot/frames/weapons/rifle_north_shoot1.png b/images/misc/shoot/frames/weapons/rifle_north_shoot1.png new file mode 100755 index 0000000..2d92075 Binary files /dev/null and b/images/misc/shoot/frames/weapons/rifle_north_shoot1.png differ diff --git a/images/misc/shoot/frames/weapons/rifle_north_shoot2.png b/images/misc/shoot/frames/weapons/rifle_north_shoot2.png new file mode 100755 index 0000000..976ad63 Binary files /dev/null and b/images/misc/shoot/frames/weapons/rifle_north_shoot2.png differ diff --git a/images/misc/shoot/frames/weapons/rifle_north_shoot3.png b/images/misc/shoot/frames/weapons/rifle_north_shoot3.png new file mode 100755 index 0000000..82323d5 Binary files /dev/null and b/images/misc/shoot/frames/weapons/rifle_north_shoot3.png differ diff --git a/images/misc/shoot/frames/weapons/rifle_side_shoot1.png b/images/misc/shoot/frames/weapons/rifle_side_shoot1.png new file mode 100755 index 0000000..462668c Binary files /dev/null and b/images/misc/shoot/frames/weapons/rifle_side_shoot1.png differ diff --git a/images/misc/shoot/frames/weapons/rifle_side_shoot2.png b/images/misc/shoot/frames/weapons/rifle_side_shoot2.png new file mode 100755 index 0000000..ecec26c Binary files /dev/null and b/images/misc/shoot/frames/weapons/rifle_side_shoot2.png differ diff --git a/images/misc/shoot/frames/weapons/rifle_side_shoot3.png b/images/misc/shoot/frames/weapons/rifle_side_shoot3.png new file mode 100755 index 0000000..3077fb1 Binary files /dev/null and b/images/misc/shoot/frames/weapons/rifle_side_shoot3.png differ diff --git a/images/misc/shoot/frames/weapons/rifle_south_shoot1.png b/images/misc/shoot/frames/weapons/rifle_south_shoot1.png new file mode 100755 index 0000000..acf6b7f Binary files /dev/null and b/images/misc/shoot/frames/weapons/rifle_south_shoot1.png differ diff --git a/images/misc/shoot/frames/weapons/rifle_south_shoot2.png b/images/misc/shoot/frames/weapons/rifle_south_shoot2.png new file mode 100755 index 0000000..b1619c6 Binary files /dev/null and b/images/misc/shoot/frames/weapons/rifle_south_shoot2.png differ diff --git a/images/misc/shoot/frames/weapons/rifle_south_shoot3.png b/images/misc/shoot/frames/weapons/rifle_south_shoot3.png new file mode 100755 index 0000000..3e0f7f7 Binary files /dev/null and b/images/misc/shoot/frames/weapons/rifle_south_shoot3.png differ diff --git a/images/misc/shoot/rmsheets/tf_charsheet_shoot_shadow.png b/images/misc/shoot/rmsheets/tf_charsheet_shoot_shadow.png new file mode 100755 index 0000000..d9f6b8b Binary files /dev/null and b/images/misc/shoot/rmsheets/tf_charsheet_shoot_shadow.png differ diff --git a/images/misc/shoot/rmsheets/tf_charsheet_shoot_shadowless.png b/images/misc/shoot/rmsheets/tf_charsheet_shoot_shadowless.png new file mode 100755 index 0000000..eeed501 Binary files /dev/null and b/images/misc/shoot/rmsheets/tf_charsheet_shoot_shadowless.png differ diff --git a/images/misc/shoot/rmsheets/weaponsheet_bow.png b/images/misc/shoot/rmsheets/weaponsheet_bow.png new file mode 100755 index 0000000..e33aa3c Binary files /dev/null and b/images/misc/shoot/rmsheets/weaponsheet_bow.png differ diff --git a/images/misc/shoot/rmsheets/weaponsheet_crossbow.png b/images/misc/shoot/rmsheets/weaponsheet_crossbow.png new file mode 100755 index 0000000..762cd47 Binary files /dev/null and b/images/misc/shoot/rmsheets/weaponsheet_crossbow.png differ diff --git a/images/misc/shoot/rmsheets/weaponsheet_rifle.png b/images/misc/shoot/rmsheets/weaponsheet_rifle.png new file mode 100755 index 0000000..dabc4cd Binary files /dev/null and b/images/misc/shoot/rmsheets/weaponsheet_rifle.png differ diff --git a/images/misc/sittingbase_single.png b/images/misc/sittingbase_single.png new file mode 100644 index 0000000..fa8956c Binary files /dev/null and b/images/misc/sittingbase_single.png differ diff --git a/images/misc/skeletonarmy_down_1.png b/images/misc/skeletonarmy_down_1.png new file mode 100644 index 0000000..ef120aa Binary files /dev/null and b/images/misc/skeletonarmy_down_1.png differ diff --git a/images/misc/spookyscarecrow_1.png b/images/misc/spookyscarecrow_1.png new file mode 100644 index 0000000..029be11 Binary files /dev/null and b/images/misc/spookyscarecrow_1.png differ diff --git a/images/misc/spqrbanners_1.png b/images/misc/spqrbanners_1.png new file mode 100644 index 0000000..5a3e323 Binary files /dev/null and b/images/misc/spqrbanners_1.png differ diff --git a/images/misc/steamcar_1.png b/images/misc/steamcar_1.png new file mode 100644 index 0000000..5af52ce Binary files /dev/null and b/images/misc/steamcar_1.png differ diff --git a/images/misc/steamcarb_1.png b/images/misc/steamcarb_1.png new file mode 100644 index 0000000..71a9924 Binary files /dev/null and b/images/misc/steamcarb_1.png differ diff --git a/images/misc/steamtractor_1.png b/images/misc/steamtractor_1.png new file mode 100644 index 0000000..8f17afc Binary files /dev/null and b/images/misc/steamtractor_1.png differ diff --git a/images/misc/sv_81_1.png b/images/misc/sv_81_1.png new file mode 100644 index 0000000..4428800 Binary files /dev/null and b/images/misc/sv_81_1.png differ diff --git a/images/misc/sv_82_1.png b/images/misc/sv_82_1.png new file mode 100644 index 0000000..d53256b Binary files /dev/null and b/images/misc/sv_82_1.png differ diff --git a/images/misc/sv_83_1.png b/images/misc/sv_83_1.png new file mode 100644 index 0000000..7669637 Binary files /dev/null and b/images/misc/sv_83_1.png differ diff --git a/images/misc/sv_84_1.png b/images/misc/sv_84_1.png new file mode 100644 index 0000000..abe0948 Binary files /dev/null and b/images/misc/sv_84_1.png differ diff --git a/images/misc/sv_NPC5_1.png b/images/misc/sv_NPC5_1.png new file mode 100644 index 0000000..18366fc Binary files /dev/null and b/images/misc/sv_NPC5_1.png differ diff --git a/images/misc/sv_NPC6-2.png b/images/misc/sv_NPC6-2.png new file mode 100644 index 0000000..1697fee Binary files /dev/null and b/images/misc/sv_NPC6-2.png differ diff --git a/images/misc/sv_bard_female.png b/images/misc/sv_bard_female.png new file mode 100644 index 0000000..5866ed1 Binary files /dev/null and b/images/misc/sv_bard_female.png differ diff --git a/images/misc/sv_bard_male.png b/images/misc/sv_bard_male.png new file mode 100644 index 0000000..2b41e21 Binary files /dev/null and b/images/misc/sv_bard_male.png differ diff --git a/images/misc/sv_blueshaman.png b/images/misc/sv_blueshaman.png new file mode 100644 index 0000000..a85e0e9 Binary files /dev/null and b/images/misc/sv_blueshaman.png differ diff --git a/images/misc/sv_future_cowboy_1.png b/images/misc/sv_future_cowboy_1.png new file mode 100644 index 0000000..491a2ba Binary files /dev/null and b/images/misc/sv_future_cowboy_1.png differ diff --git a/images/misc/sv_genie.png b/images/misc/sv_genie.png new file mode 100644 index 0000000..4e69d41 Binary files /dev/null and b/images/misc/sv_genie.png differ diff --git a/images/misc/sv_monk1.png b/images/misc/sv_monk1.png new file mode 100644 index 0000000..f4b3746 Binary files /dev/null and b/images/misc/sv_monk1.png differ diff --git a/images/misc/sv_orc1-7.png b/images/misc/sv_orc1-7.png new file mode 100644 index 0000000..8aabc74 Binary files /dev/null and b/images/misc/sv_orc1-7.png differ diff --git a/images/misc/sv_orc1-8.png b/images/misc/sv_orc1-8.png new file mode 100644 index 0000000..a338394 Binary files /dev/null and b/images/misc/sv_orc1-8.png differ diff --git a/images/misc/sv_orc1_1a.png b/images/misc/sv_orc1_1a.png new file mode 100644 index 0000000..69abe02 Binary files /dev/null and b/images/misc/sv_orc1_1a.png differ diff --git a/images/misc/sv_orc1_1b.png b/images/misc/sv_orc1_1b.png new file mode 100644 index 0000000..2ff5140 Binary files /dev/null and b/images/misc/sv_orc1_1b.png differ diff --git a/images/misc/sv_orc1_2.png b/images/misc/sv_orc1_2.png new file mode 100644 index 0000000..28d13b5 Binary files /dev/null and b/images/misc/sv_orc1_2.png differ diff --git a/images/misc/sv_orc1_3.png b/images/misc/sv_orc1_3.png new file mode 100644 index 0000000..eb71d60 Binary files /dev/null and b/images/misc/sv_orc1_3.png differ diff --git a/images/misc/sv_orc1_5.png b/images/misc/sv_orc1_5.png new file mode 100644 index 0000000..abaa0b3 Binary files /dev/null and b/images/misc/sv_orc1_5.png differ diff --git a/images/misc/sv_orc1_6.png b/images/misc/sv_orc1_6.png new file mode 100644 index 0000000..c804685 Binary files /dev/null and b/images/misc/sv_orc1_6.png differ diff --git a/images/misc/sv_orc2-1.png b/images/misc/sv_orc2-1.png new file mode 100644 index 0000000..e30196c Binary files /dev/null and b/images/misc/sv_orc2-1.png differ diff --git a/images/misc/sv_orc2-2.png b/images/misc/sv_orc2-2.png new file mode 100644 index 0000000..89bbc76 Binary files /dev/null and b/images/misc/sv_orc2-2.png differ diff --git a/images/misc/sv_orc2-3.png b/images/misc/sv_orc2-3.png new file mode 100644 index 0000000..285e515 Binary files /dev/null and b/images/misc/sv_orc2-3.png differ diff --git a/images/misc/sv_orc2-4.png b/images/misc/sv_orc2-4.png new file mode 100644 index 0000000..9cf469d Binary files /dev/null and b/images/misc/sv_orc2-4.png differ diff --git a/images/misc/sv_orc2-8.png b/images/misc/sv_orc2-8.png new file mode 100644 index 0000000..e61404b Binary files /dev/null and b/images/misc/sv_orc2-8.png differ diff --git a/images/misc/sv_pirate-1.png b/images/misc/sv_pirate-1.png new file mode 100644 index 0000000..04a07a1 Binary files /dev/null and b/images/misc/sv_pirate-1.png differ diff --git a/images/misc/sv_priestess_1.png b/images/misc/sv_priestess_1.png new file mode 100644 index 0000000..519a213 Binary files /dev/null and b/images/misc/sv_priestess_1.png differ diff --git a/images/misc/svbattler_ninja_sheet.png b/images/misc/svbattler_ninja_sheet.png new file mode 100644 index 0000000..d33f756 Binary files /dev/null and b/images/misc/svbattler_ninja_sheet.png differ diff --git a/images/misc/sword_overlay_bodybase_1.png b/images/misc/sword_overlay_bodybase_1.png new file mode 100644 index 0000000..d338e21 Binary files /dev/null and b/images/misc/sword_overlay_bodybase_1.png differ diff --git a/images/misc/tf_char6_1.png b/images/misc/tf_char6_1.png new file mode 100644 index 0000000..c54c674 Binary files /dev/null and b/images/misc/tf_char6_1.png differ diff --git a/images/misc/tf_char7_1.png b/images/misc/tf_char7_1.png new file mode 100644 index 0000000..e782f19 Binary files /dev/null and b/images/misc/tf_char7_1.png differ diff --git a/images/misc/tficons_full_16_pbeta.png b/images/misc/tficons_full_16_pbeta.png new file mode 100644 index 0000000..8bde720 Binary files /dev/null and b/images/misc/tficons_full_16_pbeta.png differ diff --git a/images/misc/tficons_limited_16_pbeta.png b/images/misc/tficons_limited_16_pbeta.png new file mode 100644 index 0000000..f40e847 Binary files /dev/null and b/images/misc/tficons_limited_16_pbeta.png differ diff --git a/images/misc/theblackknighthorseback_1.png b/images/misc/theblackknighthorseback_1.png new file mode 100644 index 0000000..2249a7c Binary files /dev/null and b/images/misc/theblackknighthorseback_1.png differ diff --git a/images/misc/theblackknightmini_1.png b/images/misc/theblackknightmini_1.png new file mode 100644 index 0000000..95f1589 Binary files /dev/null and b/images/misc/theblackknightmini_1.png differ diff --git a/images/misc/tileA5_world_1_new.png b/images/misc/tileA5_world_1_new.png new file mode 100644 index 0000000..bcabb2c Binary files /dev/null and b/images/misc/tileA5_world_1_new.png differ diff --git a/images/misc/tileB_world_1_new.png b/images/misc/tileB_world_1_new.png new file mode 100644 index 0000000..29e24e9 Binary files /dev/null and b/images/misc/tileB_world_1_new.png differ diff --git a/images/misc/tileB_world_extras_1.png b/images/misc/tileB_world_extras_1.png new file mode 100644 index 0000000..750ce72 Binary files /dev/null and b/images/misc/tileB_world_extras_1.png differ diff --git a/images/misc/tiles_kitchen.png b/images/misc/tiles_kitchen.png new file mode 100755 index 0000000..bb7fc91 Binary files /dev/null and b/images/misc/tiles_kitchen.png differ diff --git a/images/misc/tool_hammer_1.png b/images/misc/tool_hammer_1.png new file mode 100644 index 0000000..8777526 Binary files /dev/null and b/images/misc/tool_hammer_1.png differ diff --git a/images/misc/tool_hoe_1.png b/images/misc/tool_hoe_1.png new file mode 100644 index 0000000..915d999 Binary files /dev/null and b/images/misc/tool_hoe_1.png differ diff --git a/images/misc/tool_net_1.png b/images/misc/tool_net_1.png new file mode 100644 index 0000000..c8d8a27 Binary files /dev/null and b/images/misc/tool_net_1.png differ diff --git a/images/misc/tool_scythe_1.png b/images/misc/tool_scythe_1.png new file mode 100644 index 0000000..62935d5 Binary files /dev/null and b/images/misc/tool_scythe_1.png differ diff --git a/images/misc/tool_watering_1.png b/images/misc/tool_watering_1.png new file mode 100644 index 0000000..f24b009 Binary files /dev/null and b/images/misc/tool_watering_1.png differ diff --git a/images/misc/tower_tileB_1.png b/images/misc/tower_tileB_1.png new file mode 100644 index 0000000..ee94cf9 Binary files /dev/null and b/images/misc/tower_tileB_1.png differ diff --git a/images/misc/trees_1x.png b/images/misc/trees_1x.png new file mode 100644 index 0000000..fe36d53 Binary files /dev/null and b/images/misc/trees_1x.png differ diff --git a/images/misc/twwqe1.png b/images/misc/twwqe1.png new file mode 100644 index 0000000..657d1a0 Binary files /dev/null and b/images/misc/twwqe1.png differ diff --git a/images/misc/underwater_tiles_1.png b/images/misc/underwater_tiles_1.png new file mode 100644 index 0000000..ece5295 Binary files /dev/null and b/images/misc/underwater_tiles_1.png differ diff --git a/images/misc/unnamed (1).png b/images/misc/unnamed (1).png new file mode 100644 index 0000000..3a10f84 Binary files /dev/null and b/images/misc/unnamed (1).png differ diff --git a/images/misc/unnamed.png b/images/misc/unnamed.png new file mode 100644 index 0000000..d292ce5 Binary files /dev/null and b/images/misc/unnamed.png differ diff --git a/images/misc/vampires_down_1.png b/images/misc/vampires_down_1.png new file mode 100644 index 0000000..a7b030a Binary files /dev/null and b/images/misc/vampires_down_1.png differ diff --git a/images/misc/wagonhorses_1.png b/images/misc/wagonhorses_1.png new file mode 100644 index 0000000..43f944a Binary files /dev/null and b/images/misc/wagonhorses_1.png differ diff --git a/images/misc/wagons_world_1.png b/images/misc/wagons_world_1.png new file mode 100644 index 0000000..af0b6dc Binary files /dev/null and b/images/misc/wagons_world_1.png differ diff --git a/images/misc/wagonshseetb_1.png b/images/misc/wagonshseetb_1.png new file mode 100644 index 0000000..6572fda Binary files /dev/null and b/images/misc/wagonshseetb_1.png differ diff --git a/images/misc/werewolf_svsheet_gray.png b/images/misc/werewolf_svsheet_gray.png new file mode 100644 index 0000000..184dc5c Binary files /dev/null and b/images/misc/werewolf_svsheet_gray.png differ diff --git a/images/misc/windmill_1.png b/images/misc/windmill_1.png new file mode 100644 index 0000000..d2a0e5b Binary files /dev/null and b/images/misc/windmill_1.png differ diff --git a/images/misc/wmountainpath_1.png b/images/misc/wmountainpath_1.png new file mode 100644 index 0000000..08f31de Binary files /dev/null and b/images/misc/wmountainpath_1.png differ diff --git a/images/misc/wolfman_a_1.png b/images/misc/wolfman_a_1.png new file mode 100644 index 0000000..181003c Binary files /dev/null and b/images/misc/wolfman_a_1.png differ diff --git a/images/misc/wolfman_b_1.png b/images/misc/wolfman_b_1.png new file mode 100644 index 0000000..d30e46b Binary files /dev/null and b/images/misc/wolfman_b_1.png differ diff --git a/images/misc/world-canyonaddon_1.png b/images/misc/world-canyonaddon_1.png new file mode 100644 index 0000000..cf6bf28 Binary files /dev/null and b/images/misc/world-canyonaddon_1.png differ diff --git a/images/misc/world_addon_treeatlantis_1.png b/images/misc/world_addon_treeatlantis_1.png new file mode 100644 index 0000000..d882ab7 Binary files /dev/null and b/images/misc/world_addon_treeatlantis_1.png differ diff --git a/images/misc/world_modernroads_1.png b/images/misc/world_modernroads_1.png new file mode 100644 index 0000000..2ac17e0 Binary files /dev/null and b/images/misc/world_modernroads_1.png differ diff --git a/images/misc/world_modernroads_n1.png b/images/misc/world_modernroads_n1.png new file mode 100644 index 0000000..0e0eec1 Binary files /dev/null and b/images/misc/world_modernroads_n1.png differ diff --git a/images/misc/world_portalhenge_1.png b/images/misc/world_portalhenge_1.png new file mode 100644 index 0000000..3bfa782 Binary files /dev/null and b/images/misc/world_portalhenge_1.png differ diff --git a/images/misc/world_ruinsB_1.png b/images/misc/world_ruinsB_1.png new file mode 100644 index 0000000..7c5d9a3 Binary files /dev/null and b/images/misc/world_ruinsB_1.png differ diff --git a/images/misc/world_ruinsC_1.png b/images/misc/world_ruinsC_1.png new file mode 100644 index 0000000..8a1af0d Binary files /dev/null and b/images/misc/world_ruinsC_1.png differ diff --git a/images/misc/worldhorses_1.png b/images/misc/worldhorses_1.png new file mode 100644 index 0000000..81cf8e5 Binary files /dev/null and b/images/misc/worldhorses_1.png differ diff --git a/images/misc/worldhoses_wagon_1.png b/images/misc/worldhoses_wagon_1.png new file mode 100644 index 0000000..78cd7df Binary files /dev/null and b/images/misc/worldhoses_wagon_1.png differ diff --git a/images/misc/worldmap_B_japan_treeatlantis_1.png b/images/misc/worldmap_B_japan_treeatlantis_1.png new file mode 100644 index 0000000..1b3a700 Binary files /dev/null and b/images/misc/worldmap_B_japan_treeatlantis_1.png differ diff --git a/images/misc/worldmap_japan_addon_sheet.png b/images/misc/worldmap_japan_addon_sheet.png new file mode 100644 index 0000000..c75a879 Binary files /dev/null and b/images/misc/worldmap_japan_addon_sheet.png differ diff --git a/images/misc/worldmap_path_diagonaladdon_1.png b/images/misc/worldmap_path_diagonaladdon_1.png new file mode 100644 index 0000000..3b78a5e Binary files /dev/null and b/images/misc/worldmap_path_diagonaladdon_1.png differ diff --git a/images/misc/worldmapminis_char8_1.png b/images/misc/worldmapminis_char8_1.png new file mode 100644 index 0000000..2c6057c Binary files /dev/null and b/images/misc/worldmapminis_char8_1.png differ diff --git a/images/misc/worldmapminis_future1_1.png b/images/misc/worldmapminis_future1_1.png new file mode 100644 index 0000000..658ff7a Binary files /dev/null and b/images/misc/worldmapminis_future1_1.png differ diff --git a/images/misc/worldmapminis_future2_1.png b/images/misc/worldmapminis_future2_1.png new file mode 100644 index 0000000..0dc2919 Binary files /dev/null and b/images/misc/worldmapminis_future2_1.png differ diff --git a/images/misc/worldmapminis_monks_1.png b/images/misc/worldmapminis_monks_1.png new file mode 100644 index 0000000..2e90c85 Binary files /dev/null and b/images/misc/worldmapminis_monks_1.png differ diff --git a/images/misc/worldmapminis_npc5_1.png b/images/misc/worldmapminis_npc5_1.png new file mode 100644 index 0000000..758e5bb Binary files /dev/null and b/images/misc/worldmapminis_npc5_1.png differ diff --git a/images/misc/worldmapminis_orcs_1.png b/images/misc/worldmapminis_orcs_1.png new file mode 100644 index 0000000..2db90e3 Binary files /dev/null and b/images/misc/worldmapminis_orcs_1.png differ diff --git a/images/misc/worldmapminis_set2_1.png b/images/misc/worldmapminis_set2_1.png new file mode 100644 index 0000000..14a18f0 Binary files /dev/null and b/images/misc/worldmapminis_set2_1.png differ diff --git a/images/misc/worldmapminis_set3_1.png b/images/misc/worldmapminis_set3_1.png new file mode 100644 index 0000000..31ae684 Binary files /dev/null and b/images/misc/worldmapminis_set3_1.png differ diff --git a/images/misc/worldmapminis_set4_1.png b/images/misc/worldmapminis_set4_1.png new file mode 100644 index 0000000..0d4e66d Binary files /dev/null and b/images/misc/worldmapminis_set4_1.png differ diff --git a/images/misc/worldmapminis_set5_1.png b/images/misc/worldmapminis_set5_1.png new file mode 100644 index 0000000..49426a8 Binary files /dev/null and b/images/misc/worldmapminis_set5_1.png differ diff --git a/images/misc/worldmapminis_set6_1.png b/images/misc/worldmapminis_set6_1.png new file mode 100644 index 0000000..962ff6b Binary files /dev/null and b/images/misc/worldmapminis_set6_1.png differ diff --git a/images/misc/worldmapminis_set7_1.png b/images/misc/worldmapminis_set7_1.png new file mode 100644 index 0000000..270c620 Binary files /dev/null and b/images/misc/worldmapminis_set7_1.png differ diff --git a/images/misc/worldmapminis_shamans_1.png b/images/misc/worldmapminis_shamans_1.png new file mode 100644 index 0000000..5cc9500 Binary files /dev/null and b/images/misc/worldmapminis_shamans_1.png differ diff --git a/images/misc/worldmapminis_soldiers1_1.png b/images/misc/worldmapminis_soldiers1_1.png new file mode 100644 index 0000000..a0b51fa Binary files /dev/null and b/images/misc/worldmapminis_soldiers1_1.png differ diff --git a/images/misc/worldmapminis_soldiers2_1.png b/images/misc/worldmapminis_soldiers2_1.png new file mode 100644 index 0000000..76ea5d4 Binary files /dev/null and b/images/misc/worldmapminis_soldiers2_1.png differ diff --git a/images/misc/worldmapminis_soldiers3_1.png b/images/misc/worldmapminis_soldiers3_1.png new file mode 100644 index 0000000..7ad4bd1 Binary files /dev/null and b/images/misc/worldmapminis_soldiers3_1.png differ diff --git a/images/misc/worldmapsheet_upd_2018.png b/images/misc/worldmapsheet_upd_2018.png new file mode 100644 index 0000000..361d392 Binary files /dev/null and b/images/misc/worldmapsheet_upd_2018.png differ diff --git a/images/misc/worldmaptowns_extras_1.png b/images/misc/worldmaptowns_extras_1.png new file mode 100644 index 0000000..b3ac77e Binary files /dev/null and b/images/misc/worldmaptowns_extras_1.png differ diff --git a/images/old_icon.png b/images/old_icon.png new file mode 100644 index 0000000..54b912a Binary files /dev/null and b/images/old_icon.png differ diff --git a/images/screenshots/.DS_Store b/images/screenshots/.DS_Store new file mode 100644 index 0000000..54cfdba Binary files /dev/null and b/images/screenshots/.DS_Store differ diff --git a/images/screenshots/20x20b2.png b/images/screenshots/20x20b2.png new file mode 100644 index 0000000..95abc54 Binary files /dev/null and b/images/screenshots/20x20b2.png differ diff --git a/images/screenshots/bank.png b/images/screenshots/bank.png new file mode 100644 index 0000000..9a82e4f Binary files /dev/null and b/images/screenshots/bank.png differ diff --git a/images/screenshots/code_characters.png b/images/screenshots/code_characters.png new file mode 100644 index 0000000..c7ef513 Binary files /dev/null and b/images/screenshots/code_characters.png differ diff --git a/images/screenshots/craft.png b/images/screenshots/craft.png new file mode 100644 index 0000000..3d468e5 Binary files /dev/null and b/images/screenshots/craft.png differ diff --git a/images/screenshots/cvalentines.png b/images/screenshots/cvalentines.png new file mode 100644 index 0000000..4cf3ae6 Binary files /dev/null and b/images/screenshots/cvalentines.png differ diff --git a/images/screenshots/death.png b/images/screenshots/death.png new file mode 100644 index 0000000..def6b48 Binary files /dev/null and b/images/screenshots/death.png differ diff --git a/images/screenshots/early.png b/images/screenshots/early.png new file mode 100644 index 0000000..26bd75a Binary files /dev/null and b/images/screenshots/early.png differ diff --git a/images/screenshots/exchange.png b/images/screenshots/exchange.png new file mode 100644 index 0000000..9519697 Binary files /dev/null and b/images/screenshots/exchange.png differ diff --git a/images/screenshots/first_loophole.png b/images/screenshots/first_loophole.png new file mode 100644 index 0000000..fcff767 Binary files /dev/null and b/images/screenshots/first_loophole.png differ diff --git a/images/screenshots/hardcore.png b/images/screenshots/hardcore.png new file mode 100644 index 0000000..ea3e894 Binary files /dev/null and b/images/screenshots/hardcore.png differ diff --git a/images/screenshots/instances.png b/images/screenshots/instances.png new file mode 100644 index 0000000..37b09b1 Binary files /dev/null and b/images/screenshots/instances.png differ diff --git a/images/screenshots/merchant.png b/images/screenshots/merchant.png new file mode 100644 index 0000000..09c1f40 Binary files /dev/null and b/images/screenshots/merchant.png differ diff --git a/images/screenshots/merchantc.png b/images/screenshots/merchantc.png new file mode 100644 index 0000000..e262a1f Binary files /dev/null and b/images/screenshots/merchantc.png differ diff --git a/images/screenshots/mr_dworf.png b/images/screenshots/mr_dworf.png new file mode 100644 index 0000000..db7c753 Binary files /dev/null and b/images/screenshots/mr_dworf.png differ diff --git a/images/screenshots/new_crowded.png b/images/screenshots/new_crowded.png new file mode 100644 index 0000000..84de80b Binary files /dev/null and b/images/screenshots/new_crowded.png differ diff --git a/images/screenshots/new_skills.png b/images/screenshots/new_skills.png new file mode 100644 index 0000000..bf71686 Binary files /dev/null and b/images/screenshots/new_skills.png differ diff --git a/images/screenshots/new_ui.png b/images/screenshots/new_ui.png new file mode 100644 index 0000000..02903e4 Binary files /dev/null and b/images/screenshots/new_ui.png differ diff --git a/images/screenshots/p_b.png b/images/screenshots/p_b.png new file mode 100644 index 0000000..6f12dd3 Binary files /dev/null and b/images/screenshots/p_b.png differ diff --git a/images/screenshots/pack20.png b/images/screenshots/pack20.png new file mode 100644 index 0000000..4b5501b Binary files /dev/null and b/images/screenshots/pack20.png differ diff --git a/images/screenshots/the_bank.png b/images/screenshots/the_bank.png new file mode 100644 index 0000000..65ba085 Binary files /dev/null and b/images/screenshots/the_bank.png differ diff --git a/images/screenshots/therogue.png b/images/screenshots/therogue.png new file mode 100644 index 0000000..31140a3 Binary files /dev/null and b/images/screenshots/therogue.png differ diff --git a/images/screenshots/trui.png b/images/screenshots/trui.png new file mode 100644 index 0000000..b90eb7f Binary files /dev/null and b/images/screenshots/trui.png differ diff --git a/images/screenshots/ui_new.png b/images/screenshots/ui_new.png new file mode 100644 index 0000000..f273a13 Binary files /dev/null and b/images/screenshots/ui_new.png differ diff --git a/images/screenshots/winter.png b/images/screenshots/winter.png new file mode 100644 index 0000000..82e40e7 Binary files /dev/null and b/images/screenshots/winter.png differ diff --git a/images/screenshots/wow.png b/images/screenshots/wow.png new file mode 100644 index 0000000..b3a2ac6 Binary files /dev/null and b/images/screenshots/wow.png differ diff --git a/images/sprites/.DS_Store b/images/sprites/.DS_Store new file mode 100644 index 0000000..da1a2ee Binary files /dev/null and b/images/sprites/.DS_Store differ diff --git a/images/sprites/animations/.DS_Store b/images/sprites/animations/.DS_Store new file mode 100644 index 0000000..75b1c8c Binary files /dev/null and b/images/sprites/animations/.DS_Store differ diff --git a/images/sprites/animations/Block.png b/images/sprites/animations/Block.png new file mode 100755 index 0000000..543c66d Binary files /dev/null and b/images/sprites/animations/Block.png differ diff --git a/images/sprites/animations/BloodSplatter0.png b/images/sprites/animations/BloodSplatter0.png new file mode 100755 index 0000000..78f4b80 Binary files /dev/null and b/images/sprites/animations/BloodSplatter0.png differ diff --git a/images/sprites/animations/BloodSplatter1.png b/images/sprites/animations/BloodSplatter1.png new file mode 100755 index 0000000..04fc92b Binary files /dev/null and b/images/sprites/animations/BloodSplatter1.png differ diff --git a/images/sprites/animations/BloodSplatter2.png b/images/sprites/animations/BloodSplatter2.png new file mode 100755 index 0000000..0e7e5a3 Binary files /dev/null and b/images/sprites/animations/BloodSplatter2.png differ diff --git a/images/sprites/animations/BloodSplatter3.png b/images/sprites/animations/BloodSplatter3.png new file mode 100755 index 0000000..2b5ad15 Binary files /dev/null and b/images/sprites/animations/BloodSplatter3.png differ diff --git a/images/sprites/animations/Box.png b/images/sprites/animations/Box.png new file mode 100755 index 0000000..7665469 Binary files /dev/null and b/images/sprites/animations/Box.png differ diff --git a/images/sprites/animations/Bubble.png b/images/sprites/animations/Bubble.png new file mode 100755 index 0000000..ad65cea Binary files /dev/null and b/images/sprites/animations/Bubble.png differ diff --git a/images/sprites/animations/CArrow.png b/images/sprites/animations/CArrow.png new file mode 100644 index 0000000..05c2305 Binary files /dev/null and b/images/sprites/animations/CArrow.png differ diff --git a/images/sprites/animations/CArrow.pxm b/images/sprites/animations/CArrow.pxm new file mode 100644 index 0000000..3271b68 Binary files /dev/null and b/images/sprites/animations/CArrow.pxm differ diff --git a/images/sprites/animations/CGreen_Spark0.png b/images/sprites/animations/CGreen_Spark0.png new file mode 100644 index 0000000..dece80f Binary files /dev/null and b/images/sprites/animations/CGreen_Spark0.png differ diff --git a/images/sprites/animations/CGreen_Spark1.png b/images/sprites/animations/CGreen_Spark1.png new file mode 100644 index 0000000..12f590d Binary files /dev/null and b/images/sprites/animations/CGreen_Spark1.png differ diff --git a/images/sprites/animations/CGreen_Spark2.png b/images/sprites/animations/CGreen_Spark2.png new file mode 100644 index 0000000..0237404 Binary files /dev/null and b/images/sprites/animations/CGreen_Spark2.png differ diff --git a/images/sprites/animations/CGreen_Spark3.png b/images/sprites/animations/CGreen_Spark3.png new file mode 100644 index 0000000..a8a7e74 Binary files /dev/null and b/images/sprites/animations/CGreen_Spark3.png differ diff --git a/images/sprites/animations/CPurple_Spark.png b/images/sprites/animations/CPurple_Spark.png new file mode 100644 index 0000000..772e5d2 Binary files /dev/null and b/images/sprites/animations/CPurple_Spark.png differ diff --git a/images/sprites/animations/CPurple_Spark.pxm b/images/sprites/animations/CPurple_Spark.pxm new file mode 100644 index 0000000..d77fe4e Binary files /dev/null and b/images/sprites/animations/CPurple_Spark.pxm differ diff --git a/images/sprites/animations/CRed_Spark0.png b/images/sprites/animations/CRed_Spark0.png new file mode 100644 index 0000000..31cac8b Binary files /dev/null and b/images/sprites/animations/CRed_Spark0.png differ diff --git a/images/sprites/animations/CRed_Spark1.png b/images/sprites/animations/CRed_Spark1.png new file mode 100644 index 0000000..e3fd613 Binary files /dev/null and b/images/sprites/animations/CRed_Spark1.png differ diff --git a/images/sprites/animations/CRed_Spark2.png b/images/sprites/animations/CRed_Spark2.png new file mode 100644 index 0000000..eeea04b Binary files /dev/null and b/images/sprites/animations/CRed_Spark2.png differ diff --git a/images/sprites/animations/CRed_Spark3.png b/images/sprites/animations/CRed_Spark3.png new file mode 100644 index 0000000..6182bfa Binary files /dev/null and b/images/sprites/animations/CRed_Spark3.png differ diff --git a/images/sprites/animations/CRed_Spark4.png b/images/sprites/animations/CRed_Spark4.png new file mode 100644 index 0000000..1cfb99c Binary files /dev/null and b/images/sprites/animations/CRed_Spark4.png differ diff --git a/images/sprites/animations/CRed_Spark5.png b/images/sprites/animations/CRed_Spark5.png new file mode 100644 index 0000000..7d5a36f Binary files /dev/null and b/images/sprites/animations/CRed_Spark5.png differ diff --git a/images/sprites/animations/Circle.png b/images/sprites/animations/Circle.png new file mode 100755 index 0000000..347b6d6 Binary files /dev/null and b/images/sprites/animations/Circle.png differ diff --git a/images/sprites/animations/Claw.png b/images/sprites/animations/Claw.png new file mode 100755 index 0000000..e109eb3 Binary files /dev/null and b/images/sprites/animations/Claw.png differ diff --git a/images/sprites/animations/Consume0.png b/images/sprites/animations/Consume0.png new file mode 100755 index 0000000..b5b8c3e Binary files /dev/null and b/images/sprites/animations/Consume0.png differ diff --git a/images/sprites/animations/Consume1.png b/images/sprites/animations/Consume1.png new file mode 100755 index 0000000..580ce30 Binary files /dev/null and b/images/sprites/animations/Consume1.png differ diff --git a/images/sprites/animations/Consume2.png b/images/sprites/animations/Consume2.png new file mode 100755 index 0000000..d27ddd4 Binary files /dev/null and b/images/sprites/animations/Consume2.png differ diff --git a/images/sprites/animations/ConsumeP.png b/images/sprites/animations/ConsumeP.png new file mode 100644 index 0000000..2cee95b Binary files /dev/null and b/images/sprites/animations/ConsumeP.png differ diff --git a/images/sprites/animations/ConsumeR.png b/images/sprites/animations/ConsumeR.png new file mode 100644 index 0000000..0679ed7 Binary files /dev/null and b/images/sprites/animations/ConsumeR.png differ diff --git a/images/sprites/animations/ConsumeR.pxm b/images/sprites/animations/ConsumeR.pxm new file mode 100644 index 0000000..ccb0a90 Binary files /dev/null and b/images/sprites/animations/ConsumeR.pxm differ diff --git a/images/sprites/animations/Dampen.png b/images/sprites/animations/Dampen.png new file mode 100644 index 0000000..a6c5046 Binary files /dev/null and b/images/sprites/animations/Dampen.png differ diff --git a/images/sprites/animations/Dark.png b/images/sprites/animations/Dark.png new file mode 100755 index 0000000..b8b05f5 Binary files /dev/null and b/images/sprites/animations/Dark.png differ diff --git a/images/sprites/animations/Earth0.png b/images/sprites/animations/Earth0.png new file mode 100755 index 0000000..fcc5d72 Binary files /dev/null and b/images/sprites/animations/Earth0.png differ diff --git a/images/sprites/animations/Earth1.png b/images/sprites/animations/Earth1.png new file mode 100755 index 0000000..c8a254f Binary files /dev/null and b/images/sprites/animations/Earth1.png differ diff --git a/images/sprites/animations/Earth2.png b/images/sprites/animations/Earth2.png new file mode 100755 index 0000000..7614dc9 Binary files /dev/null and b/images/sprites/animations/Earth2.png differ diff --git a/images/sprites/animations/Electric.png b/images/sprites/animations/Electric.png new file mode 100755 index 0000000..18d9dd4 Binary files /dev/null and b/images/sprites/animations/Electric.png differ diff --git a/images/sprites/animations/ElectricG.png b/images/sprites/animations/ElectricG.png new file mode 100644 index 0000000..6d4fc46 Binary files /dev/null and b/images/sprites/animations/ElectricG.png differ diff --git a/images/sprites/animations/ExplodeA.png b/images/sprites/animations/ExplodeA.png new file mode 100755 index 0000000..1d25080 Binary files /dev/null and b/images/sprites/animations/ExplodeA.png differ diff --git a/images/sprites/animations/ExplodeB.png b/images/sprites/animations/ExplodeB.png new file mode 100755 index 0000000..1b568d8 Binary files /dev/null and b/images/sprites/animations/ExplodeB.png differ diff --git a/images/sprites/animations/ExplodeC.png b/images/sprites/animations/ExplodeC.png new file mode 100755 index 0000000..86c6dd5 Binary files /dev/null and b/images/sprites/animations/ExplodeC.png differ diff --git a/images/sprites/animations/ExplodeD.png b/images/sprites/animations/ExplodeD.png new file mode 100755 index 0000000..b03477a Binary files /dev/null and b/images/sprites/animations/ExplodeD.png differ diff --git a/images/sprites/animations/ExplodeE.png b/images/sprites/animations/ExplodeE.png new file mode 100755 index 0000000..5472278 Binary files /dev/null and b/images/sprites/animations/ExplodeE.png differ diff --git a/images/sprites/animations/ExplodeP.png b/images/sprites/animations/ExplodeP.png new file mode 100644 index 0000000..bf928c4 Binary files /dev/null and b/images/sprites/animations/ExplodeP.png differ diff --git a/images/sprites/animations/ExplodeP2.png b/images/sprites/animations/ExplodeP2.png new file mode 100644 index 0000000..3e964e8 Binary files /dev/null and b/images/sprites/animations/ExplodeP2.png differ diff --git a/images/sprites/animations/ExplodeUCS.png b/images/sprites/animations/ExplodeUCS.png new file mode 100644 index 0000000..d22ae8f Binary files /dev/null and b/images/sprites/animations/ExplodeUCS.png differ diff --git a/images/sprites/animations/Fire0.png b/images/sprites/animations/Fire0.png new file mode 100755 index 0000000..18a8599 Binary files /dev/null and b/images/sprites/animations/Fire0.png differ diff --git a/images/sprites/animations/Fire1.png b/images/sprites/animations/Fire1.png new file mode 100755 index 0000000..fe72b7e Binary files /dev/null and b/images/sprites/animations/Fire1.png differ diff --git a/images/sprites/animations/Fire2.png b/images/sprites/animations/Fire2.png new file mode 100755 index 0000000..35cac07 Binary files /dev/null and b/images/sprites/animations/Fire2.png differ diff --git a/images/sprites/animations/Flame.png b/images/sprites/animations/Flame.png new file mode 100755 index 0000000..7802247 Binary files /dev/null and b/images/sprites/animations/Flame.png differ diff --git a/images/sprites/animations/FlameAlt.png b/images/sprites/animations/FlameAlt.png new file mode 100755 index 0000000..e6717b7 Binary files /dev/null and b/images/sprites/animations/FlameAlt.png differ diff --git a/images/sprites/animations/Footprints.png b/images/sprites/animations/Footprints.png new file mode 100755 index 0000000..0532d0b Binary files /dev/null and b/images/sprites/animations/Footprints.png differ diff --git a/images/sprites/animations/FootprintsSand.png b/images/sprites/animations/FootprintsSand.png new file mode 100755 index 0000000..1eeb25d Binary files /dev/null and b/images/sprites/animations/FootprintsSand.png differ diff --git a/images/sprites/animations/FootprintsSandNight.png b/images/sprites/animations/FootprintsSandNight.png new file mode 100755 index 0000000..de84530 Binary files /dev/null and b/images/sprites/animations/FootprintsSandNight.png differ diff --git a/images/sprites/animations/Glint.png b/images/sprites/animations/Glint.png new file mode 100755 index 0000000..0ea5d98 Binary files /dev/null and b/images/sprites/animations/Glint.png differ diff --git a/images/sprites/animations/GlintF.png b/images/sprites/animations/GlintF.png new file mode 100644 index 0000000..aead437 Binary files /dev/null and b/images/sprites/animations/GlintF.png differ diff --git a/images/sprites/animations/HalfClaw.png b/images/sprites/animations/HalfClaw.png new file mode 100644 index 0000000..b168b3a Binary files /dev/null and b/images/sprites/animations/HalfClaw.png differ diff --git a/images/sprites/animations/Heal0Back.png b/images/sprites/animations/Heal0Back.png new file mode 100755 index 0000000..d6cb5f7 Binary files /dev/null and b/images/sprites/animations/Heal0Back.png differ diff --git a/images/sprites/animations/Heal0Fore.png b/images/sprites/animations/Heal0Fore.png new file mode 100755 index 0000000..ddc29a9 Binary files /dev/null and b/images/sprites/animations/Heal0Fore.png differ diff --git a/images/sprites/animations/Heal1Back.png b/images/sprites/animations/Heal1Back.png new file mode 100755 index 0000000..b3b91d2 Binary files /dev/null and b/images/sprites/animations/Heal1Back.png differ diff --git a/images/sprites/animations/Heal1Fore.png b/images/sprites/animations/Heal1Fore.png new file mode 100755 index 0000000..a790624 Binary files /dev/null and b/images/sprites/animations/Heal1Fore.png differ diff --git a/images/sprites/animations/Ice0.png b/images/sprites/animations/Ice0.png new file mode 100755 index 0000000..b8fae75 Binary files /dev/null and b/images/sprites/animations/Ice0.png differ diff --git a/images/sprites/animations/Ice1.png b/images/sprites/animations/Ice1.png new file mode 100755 index 0000000..2d78eeb Binary files /dev/null and b/images/sprites/animations/Ice1.png differ diff --git a/images/sprites/animations/Ice2.png b/images/sprites/animations/Ice2.png new file mode 100755 index 0000000..c801b60 Binary files /dev/null and b/images/sprites/animations/Ice2.png differ diff --git a/images/sprites/animations/Light.png b/images/sprites/animations/Light.png new file mode 100644 index 0000000..4b5c5ce Binary files /dev/null and b/images/sprites/animations/Light.png differ diff --git a/images/sprites/animations/Lightning.png b/images/sprites/animations/Lightning.png new file mode 100755 index 0000000..5b1df6d Binary files /dev/null and b/images/sprites/animations/Lightning.png differ diff --git a/images/sprites/animations/MBlob.png b/images/sprites/animations/MBlob.png new file mode 100644 index 0000000..3a81ee7 Binary files /dev/null and b/images/sprites/animations/MBlob.png differ diff --git a/images/sprites/animations/MBlob.pxm b/images/sprites/animations/MBlob.pxm new file mode 100644 index 0000000..9233d4d Binary files /dev/null and b/images/sprites/animations/MBlob.pxm differ diff --git a/images/sprites/animations/MBlobP.png b/images/sprites/animations/MBlobP.png new file mode 100644 index 0000000..f8654b3 Binary files /dev/null and b/images/sprites/animations/MBlobP.png differ diff --git a/images/sprites/animations/MBlobP.pxm b/images/sprites/animations/MBlobP.pxm new file mode 100644 index 0000000..1eac232 Binary files /dev/null and b/images/sprites/animations/MBlobP.pxm differ diff --git a/images/sprites/animations/MBlobR.png b/images/sprites/animations/MBlobR.png new file mode 100644 index 0000000..4843485 Binary files /dev/null and b/images/sprites/animations/MBlobR.png differ diff --git a/images/sprites/animations/MBlobR.pxm b/images/sprites/animations/MBlobR.pxm new file mode 100644 index 0000000..252a258 Binary files /dev/null and b/images/sprites/animations/MBlobR.pxm differ diff --git a/images/sprites/animations/NuclearA0.png b/images/sprites/animations/NuclearA0.png new file mode 100755 index 0000000..0d026ff Binary files /dev/null and b/images/sprites/animations/NuclearA0.png differ diff --git a/images/sprites/animations/NuclearA1.png b/images/sprites/animations/NuclearA1.png new file mode 100755 index 0000000..213caca Binary files /dev/null and b/images/sprites/animations/NuclearA1.png differ diff --git a/images/sprites/animations/NuclearB0.png b/images/sprites/animations/NuclearB0.png new file mode 100755 index 0000000..a320d5d Binary files /dev/null and b/images/sprites/animations/NuclearB0.png differ diff --git a/images/sprites/animations/NuclearB1.png b/images/sprites/animations/NuclearB1.png new file mode 100755 index 0000000..be940ba Binary files /dev/null and b/images/sprites/animations/NuclearB1.png differ diff --git a/images/sprites/animations/PBlob.png b/images/sprites/animations/PBlob.png new file mode 100644 index 0000000..1ae04d4 Binary files /dev/null and b/images/sprites/animations/PBlob.png differ diff --git a/images/sprites/animations/PBlob.pxm b/images/sprites/animations/PBlob.pxm new file mode 100644 index 0000000..0820008 Binary files /dev/null and b/images/sprites/animations/PBlob.pxm differ diff --git a/images/sprites/animations/Path.png b/images/sprites/animations/Path.png new file mode 100755 index 0000000..a602948 Binary files /dev/null and b/images/sprites/animations/Path.png differ diff --git a/images/sprites/animations/Poison.png b/images/sprites/animations/Poison.png new file mode 100755 index 0000000..3ecf530 Binary files /dev/null and b/images/sprites/animations/Poison.png differ diff --git a/images/sprites/animations/Puff.png b/images/sprites/animations/Puff.png new file mode 100755 index 0000000..9fb03fd Binary files /dev/null and b/images/sprites/animations/Puff.png differ diff --git a/images/sprites/animations/PuffR.png b/images/sprites/animations/PuffR.png new file mode 100644 index 0000000..fc3a89d Binary files /dev/null and b/images/sprites/animations/PuffR.png differ diff --git a/images/sprites/animations/PuffR.pxm b/images/sprites/animations/PuffR.pxm new file mode 100644 index 0000000..2c61ba0 Binary files /dev/null and b/images/sprites/animations/PuffR.pxm differ diff --git a/images/sprites/animations/Select0.png b/images/sprites/animations/Select0.png new file mode 100755 index 0000000..c7db241 Binary files /dev/null and b/images/sprites/animations/Select0.png differ diff --git a/images/sprites/animations/Select1.png b/images/sprites/animations/Select1.png new file mode 100755 index 0000000..9d97ba0 Binary files /dev/null and b/images/sprites/animations/Select1.png differ diff --git a/images/sprites/animations/Shield0.png b/images/sprites/animations/Shield0.png new file mode 100755 index 0000000..aba360a Binary files /dev/null and b/images/sprites/animations/Shield0.png differ diff --git a/images/sprites/animations/Shield1.png b/images/sprites/animations/Shield1.png new file mode 100755 index 0000000..1407dd4 Binary files /dev/null and b/images/sprites/animations/Shield1.png differ diff --git a/images/sprites/animations/Shield2.png b/images/sprites/animations/Shield2.png new file mode 100755 index 0000000..33b43bd Binary files /dev/null and b/images/sprites/animations/Shield2.png differ diff --git a/images/sprites/animations/Shield3.png b/images/sprites/animations/Shield3.png new file mode 100755 index 0000000..a20a484 Binary files /dev/null and b/images/sprites/animations/Shield3.png differ diff --git a/images/sprites/animations/Shield_Invincible.png b/images/sprites/animations/Shield_Invincible.png new file mode 100644 index 0000000..751ce4c Binary files /dev/null and b/images/sprites/animations/Shield_Invincible.png differ diff --git a/images/sprites/animations/Sick.png b/images/sprites/animations/Sick.png new file mode 100755 index 0000000..721c27a Binary files /dev/null and b/images/sprites/animations/Sick.png differ diff --git a/images/sprites/animations/Slash0.png b/images/sprites/animations/Slash0.png new file mode 100755 index 0000000..c4a013f Binary files /dev/null and b/images/sprites/animations/Slash0.png differ diff --git a/images/sprites/animations/Slash0Arrow.png b/images/sprites/animations/Slash0Arrow.png new file mode 100644 index 0000000..25585bf Binary files /dev/null and b/images/sprites/animations/Slash0Arrow.png differ diff --git a/images/sprites/animations/Slash0Super.png b/images/sprites/animations/Slash0Super.png new file mode 100644 index 0000000..75fd443 Binary files /dev/null and b/images/sprites/animations/Slash0Super.png differ diff --git a/images/sprites/animations/Slash1.png b/images/sprites/animations/Slash1.png new file mode 100755 index 0000000..93f8fb4 Binary files /dev/null and b/images/sprites/animations/Slash1.png differ diff --git a/images/sprites/animations/Slash2Quick.png b/images/sprites/animations/Slash2Quick.png new file mode 100644 index 0000000..041e2d5 Binary files /dev/null and b/images/sprites/animations/Slash2Quick.png differ diff --git a/images/sprites/animations/Slash3.png b/images/sprites/animations/Slash3.png new file mode 100644 index 0000000..f368a62 Binary files /dev/null and b/images/sprites/animations/Slash3.png differ diff --git a/images/sprites/animations/Slash3.pxm b/images/sprites/animations/Slash3.pxm new file mode 100644 index 0000000..e754e54 Binary files /dev/null and b/images/sprites/animations/Slash3.pxm differ diff --git a/images/sprites/animations/Sleep.png b/images/sprites/animations/Sleep.png new file mode 100755 index 0000000..a539d9a Binary files /dev/null and b/images/sprites/animations/Sleep.png differ diff --git a/images/sprites/animations/SleepFlip.png b/images/sprites/animations/SleepFlip.png new file mode 100755 index 0000000..46f7c5f Binary files /dev/null and b/images/sprites/animations/SleepFlip.png differ diff --git a/images/sprites/animations/SlimeSplatter0.png b/images/sprites/animations/SlimeSplatter0.png new file mode 100755 index 0000000..6ff45eb Binary files /dev/null and b/images/sprites/animations/SlimeSplatter0.png differ diff --git a/images/sprites/animations/SlimeSplatter1.png b/images/sprites/animations/SlimeSplatter1.png new file mode 100755 index 0000000..ea6c2dc Binary files /dev/null and b/images/sprites/animations/SlimeSplatter1.png differ diff --git a/images/sprites/animations/SlimeSplatter2.png b/images/sprites/animations/SlimeSplatter2.png new file mode 100755 index 0000000..f7ba753 Binary files /dev/null and b/images/sprites/animations/SlimeSplatter2.png differ diff --git a/images/sprites/animations/SlimeSplatter3.png b/images/sprites/animations/SlimeSplatter3.png new file mode 100755 index 0000000..d1cae31 Binary files /dev/null and b/images/sprites/animations/SlimeSplatter3.png differ diff --git a/images/sprites/animations/Spark0.png b/images/sprites/animations/Spark0.png new file mode 100755 index 0000000..80369b9 Binary files /dev/null and b/images/sprites/animations/Spark0.png differ diff --git a/images/sprites/animations/Spark1.png b/images/sprites/animations/Spark1.png new file mode 100755 index 0000000..a3e1ccf Binary files /dev/null and b/images/sprites/animations/Spark1.png differ diff --git a/images/sprites/animations/Square0Back.png b/images/sprites/animations/Square0Back.png new file mode 100755 index 0000000..df606ba Binary files /dev/null and b/images/sprites/animations/Square0Back.png differ diff --git a/images/sprites/animations/Square0Fore.png b/images/sprites/animations/Square0Fore.png new file mode 100755 index 0000000..40e431b Binary files /dev/null and b/images/sprites/animations/Square0Fore.png differ diff --git a/images/sprites/animations/Square1Back.png b/images/sprites/animations/Square1Back.png new file mode 100755 index 0000000..39cfb35 Binary files /dev/null and b/images/sprites/animations/Square1Back.png differ diff --git a/images/sprites/animations/Square1Fore.png b/images/sprites/animations/Square1Fore.png new file mode 100755 index 0000000..1e62941 Binary files /dev/null and b/images/sprites/animations/Square1Fore.png differ diff --git a/images/sprites/animations/Star.png b/images/sprites/animations/Star.png new file mode 100755 index 0000000..0ca4001 Binary files /dev/null and b/images/sprites/animations/Star.png differ diff --git a/images/sprites/animations/StarReverse.png b/images/sprites/animations/StarReverse.png new file mode 100644 index 0000000..94474a8 Binary files /dev/null and b/images/sprites/animations/StarReverse.png differ diff --git a/images/sprites/animations/TEST.png b/images/sprites/animations/TEST.png new file mode 100644 index 0000000..012309d Binary files /dev/null and b/images/sprites/animations/TEST.png differ diff --git a/images/sprites/animations/Tangle.png b/images/sprites/animations/Tangle.png new file mode 100644 index 0000000..530b483 Binary files /dev/null and b/images/sprites/animations/Tangle.png differ diff --git a/images/sprites/animations/Tangle.pxm b/images/sprites/animations/Tangle.pxm new file mode 100644 index 0000000..a574673 Binary files /dev/null and b/images/sprites/animations/Tangle.pxm differ diff --git a/images/sprites/animations/Teleport0.png b/images/sprites/animations/Teleport0.png new file mode 100755 index 0000000..5e0a2d1 Binary files /dev/null and b/images/sprites/animations/Teleport0.png differ diff --git a/images/sprites/animations/Teleport1.png b/images/sprites/animations/Teleport1.png new file mode 100755 index 0000000..542b61c Binary files /dev/null and b/images/sprites/animations/Teleport1.png differ diff --git a/images/sprites/animations/Teleport1P.png b/images/sprites/animations/Teleport1P.png new file mode 100644 index 0000000..3a48309 Binary files /dev/null and b/images/sprites/animations/Teleport1P.png differ diff --git a/images/sprites/animations/Teleport1P.pxm b/images/sprites/animations/Teleport1P.pxm new file mode 100644 index 0000000..bfb1d34 Binary files /dev/null and b/images/sprites/animations/Teleport1P.pxm differ diff --git a/images/sprites/animations/Teleport2.png b/images/sprites/animations/Teleport2.png new file mode 100755 index 0000000..dda9d25 Binary files /dev/null and b/images/sprites/animations/Teleport2.png differ diff --git a/images/sprites/animations/TeleportInv.png b/images/sprites/animations/TeleportInv.png new file mode 100644 index 0000000..77e68ac Binary files /dev/null and b/images/sprites/animations/TeleportInv.png differ diff --git a/images/sprites/animations/Touch0.png b/images/sprites/animations/Touch0.png new file mode 100755 index 0000000..cbcfc9e Binary files /dev/null and b/images/sprites/animations/Touch0.png differ diff --git a/images/sprites/animations/Touch1.png b/images/sprites/animations/Touch1.png new file mode 100755 index 0000000..f72074c Binary files /dev/null and b/images/sprites/animations/Touch1.png differ diff --git a/images/sprites/animations/Warp0.png b/images/sprites/animations/Warp0.png new file mode 100755 index 0000000..45bbd9b Binary files /dev/null and b/images/sprites/animations/Warp0.png differ diff --git a/images/sprites/animations/Warp1.png b/images/sprites/animations/Warp1.png new file mode 100755 index 0000000..0539344 Binary files /dev/null and b/images/sprites/animations/Warp1.png differ diff --git a/images/sprites/animations/Water.png b/images/sprites/animations/Water.png new file mode 100755 index 0000000..e6454b1 Binary files /dev/null and b/images/sprites/animations/Water.png differ diff --git a/images/sprites/animations/WebBack.png b/images/sprites/animations/WebBack.png new file mode 100755 index 0000000..1210e34 Binary files /dev/null and b/images/sprites/animations/WebBack.png differ diff --git a/images/sprites/animations/WebFore.png b/images/sprites/animations/WebFore.png new file mode 100755 index 0000000..81544d8 Binary files /dev/null and b/images/sprites/animations/WebFore.png differ diff --git a/images/sprites/animations/arrow1.png b/images/sprites/animations/arrow1.png new file mode 100644 index 0000000..9bee760 Binary files /dev/null and b/images/sprites/animations/arrow1.png differ diff --git a/images/sprites/animations/arrow2.png b/images/sprites/animations/arrow2.png new file mode 100644 index 0000000..2c11f6c Binary files /dev/null and b/images/sprites/animations/arrow2.png differ diff --git a/images/sprites/animations/attack2.png b/images/sprites/animations/attack2.png new file mode 100644 index 0000000..5a4b121 Binary files /dev/null and b/images/sprites/animations/attack2.png differ diff --git a/images/sprites/animations/attack3.png b/images/sprites/animations/attack3.png new file mode 100644 index 0000000..40c7142 Binary files /dev/null and b/images/sprites/animations/attack3.png differ diff --git a/images/sprites/animations/burst.png b/images/sprites/animations/burst.png new file mode 100644 index 0000000..99a314a Binary files /dev/null and b/images/sprites/animations/burst.png differ diff --git a/images/sprites/animations/burst.pxm b/images/sprites/animations/burst.pxm new file mode 100644 index 0000000..00df001 Binary files /dev/null and b/images/sprites/animations/burst.pxm differ diff --git a/images/sprites/animations/confetti.png b/images/sprites/animations/confetti.png new file mode 100644 index 0000000..fd87f61 Binary files /dev/null and b/images/sprites/animations/confetti.png differ diff --git a/images/sprites/animations/confetti2.png b/images/sprites/animations/confetti2.png new file mode 100644 index 0000000..7787b85 Binary files /dev/null and b/images/sprites/animations/confetti2.png differ diff --git a/images/sprites/animations/crackingIce.png b/images/sprites/animations/crackingIce.png new file mode 100644 index 0000000..970b6c1 Binary files /dev/null and b/images/sprites/animations/crackingIce.png differ diff --git a/images/sprites/animations/curse.png b/images/sprites/animations/curse.png new file mode 100644 index 0000000..326dd78 Binary files /dev/null and b/images/sprites/animations/curse.png differ diff --git a/images/sprites/animations/curseAttack.png b/images/sprites/animations/curseAttack.png new file mode 100644 index 0000000..2682666 Binary files /dev/null and b/images/sprites/animations/curseAttack.png differ diff --git a/images/sprites/animations/eburst.png b/images/sprites/animations/eburst.png new file mode 100644 index 0000000..4e5b999 Binary files /dev/null and b/images/sprites/animations/eburst.png differ diff --git a/images/sprites/animations/egg_splash.png b/images/sprites/animations/egg_splash.png new file mode 100644 index 0000000..09e259b Binary files /dev/null and b/images/sprites/animations/egg_splash.png differ diff --git a/images/sprites/animations/fireArrow.png b/images/sprites/animations/fireArrow.png new file mode 100644 index 0000000..42c4733 Binary files /dev/null and b/images/sprites/animations/fireArrow.png differ diff --git a/images/sprites/animations/fireball.png b/images/sprites/animations/fireball.png new file mode 100644 index 0000000..2acf3a0 Binary files /dev/null and b/images/sprites/animations/fireball.png differ diff --git a/images/sprites/animations/fireball_3frames.png b/images/sprites/animations/fireball_3frames.png new file mode 100644 index 0000000..f461c1b Binary files /dev/null and b/images/sprites/animations/fireball_3frames.png differ diff --git a/images/sprites/animations/flare_effect_blue.png b/images/sprites/animations/flare_effect_blue.png new file mode 100644 index 0000000..537ba34 Binary files /dev/null and b/images/sprites/animations/flare_effect_blue.png differ diff --git a/images/sprites/animations/flare_effect_red.png b/images/sprites/animations/flare_effect_red.png new file mode 100644 index 0000000..c48b782 Binary files /dev/null and b/images/sprites/animations/flare_effect_red.png differ diff --git a/images/sprites/animations/flare_effect_yellow.png b/images/sprites/animations/flare_effect_yellow.png new file mode 100644 index 0000000..6e5c4d5 Binary files /dev/null and b/images/sprites/animations/flare_effect_yellow.png differ diff --git a/images/sprites/animations/frostArrow.png b/images/sprites/animations/frostArrow.png new file mode 100644 index 0000000..35dc5e0 Binary files /dev/null and b/images/sprites/animations/frostArrow.png differ diff --git a/images/sprites/animations/frostball.png b/images/sprites/animations/frostball.png new file mode 100644 index 0000000..84d2338 Binary files /dev/null and b/images/sprites/animations/frostball.png differ diff --git a/images/sprites/animations/garrow.png b/images/sprites/animations/garrow.png new file mode 100644 index 0000000..8c5e0e9 Binary files /dev/null and b/images/sprites/animations/garrow.png differ diff --git a/images/sprites/animations/garrow.pxm b/images/sprites/animations/garrow.pxm new file mode 100644 index 0000000..309e80a Binary files /dev/null and b/images/sprites/animations/garrow.pxm differ diff --git a/images/sprites/animations/gold.png b/images/sprites/animations/gold.png new file mode 100644 index 0000000..8b40060 Binary files /dev/null and b/images/sprites/animations/gold.png differ diff --git a/images/sprites/animations/gold.pxm b/images/sprites/animations/gold.pxm new file mode 100644 index 0000000..812fe1d Binary files /dev/null and b/images/sprites/animations/gold.pxm differ diff --git a/images/sprites/animations/gold_anim.png b/images/sprites/animations/gold_anim.png new file mode 100644 index 0000000..0fd2c62 Binary files /dev/null and b/images/sprites/animations/gold_anim.png differ diff --git a/images/sprites/animations/gold_anim.pxm b/images/sprites/animations/gold_anim.pxm new file mode 100644 index 0000000..5f8eb12 Binary files /dev/null and b/images/sprites/animations/gold_anim.pxm differ diff --git a/images/sprites/animations/healAttack.png b/images/sprites/animations/healAttack.png new file mode 100644 index 0000000..c325bcf Binary files /dev/null and b/images/sprites/animations/healAttack.png differ diff --git a/images/sprites/animations/heartedArrow.png b/images/sprites/animations/heartedArrow.png new file mode 100644 index 0000000..3c91df1 Binary files /dev/null and b/images/sprites/animations/heartedArrow.png differ diff --git a/images/sprites/animations/lightningBurst3.png b/images/sprites/animations/lightningBurst3.png new file mode 100644 index 0000000..0569dec Binary files /dev/null and b/images/sprites/animations/lightningBurst3.png differ diff --git a/images/sprites/animations/magic0.png b/images/sprites/animations/magic0.png new file mode 100644 index 0000000..9011b73 Binary files /dev/null and b/images/sprites/animations/magic0.png differ diff --git a/images/sprites/animations/magic1.png b/images/sprites/animations/magic1.png new file mode 100644 index 0000000..0367d0a Binary files /dev/null and b/images/sprites/animations/magic1.png differ diff --git a/images/sprites/animations/magic2.png b/images/sprites/animations/magic2.png new file mode 100644 index 0000000..139a52e Binary files /dev/null and b/images/sprites/animations/magic2.png differ diff --git a/images/sprites/animations/magic3.png b/images/sprites/animations/magic3.png new file mode 100644 index 0000000..5bcf969 Binary files /dev/null and b/images/sprites/animations/magic3.png differ diff --git a/images/sprites/animations/magic4.png b/images/sprites/animations/magic4.png new file mode 100644 index 0000000..19161de Binary files /dev/null and b/images/sprites/animations/magic4.png differ diff --git a/images/sprites/animations/partyHeal.png b/images/sprites/animations/partyHeal.png new file mode 100644 index 0000000..65750e9 Binary files /dev/null and b/images/sprites/animations/partyHeal.png differ diff --git a/images/sprites/animations/pinky.png b/images/sprites/animations/pinky.png new file mode 100644 index 0000000..cf3b4ae Binary files /dev/null and b/images/sprites/animations/pinky.png differ diff --git a/images/sprites/animations/pouchArrow.png b/images/sprites/animations/pouchArrow.png new file mode 100644 index 0000000..86432a5 Binary files /dev/null and b/images/sprites/animations/pouchArrow.png differ diff --git a/images/sprites/animations/reflection.png b/images/sprites/animations/reflection.png new file mode 100644 index 0000000..9cd752b Binary files /dev/null and b/images/sprites/animations/reflection.png differ diff --git a/images/sprites/animations/reflection.pxm b/images/sprites/animations/reflection.pxm new file mode 100644 index 0000000..3e495f4 Binary files /dev/null and b/images/sprites/animations/reflection.pxm differ diff --git a/images/sprites/animations/slash.png b/images/sprites/animations/slash.png new file mode 100644 index 0000000..9844ac7 Binary files /dev/null and b/images/sprites/animations/slash.png differ diff --git a/images/sprites/animations/snowball_hit.png b/images/sprites/animations/snowball_hit.png new file mode 100644 index 0000000..7d242b9 Binary files /dev/null and b/images/sprites/animations/snowball_hit.png differ diff --git a/images/sprites/animations/snowball_projectile.png b/images/sprites/animations/snowball_projectile.png new file mode 100644 index 0000000..33c8d81 Binary files /dev/null and b/images/sprites/animations/snowball_projectile.png differ diff --git a/images/sprites/animations/snowflake.png b/images/sprites/animations/snowflake.png new file mode 100644 index 0000000..254c0ce Binary files /dev/null and b/images/sprites/animations/snowflake.png differ diff --git a/images/sprites/animations/terrorAcid.png b/images/sprites/animations/terrorAcid.png new file mode 100644 index 0000000..58dee73 Binary files /dev/null and b/images/sprites/animations/terrorAcid.png differ diff --git a/images/sprites/animations/typingAnim.png b/images/sprites/animations/typingAnim.png new file mode 100644 index 0000000..9bdc8bf Binary files /dev/null and b/images/sprites/animations/typingAnim.png differ diff --git a/images/sprites/animations/wandy.png b/images/sprites/animations/wandy.png new file mode 100644 index 0000000..0d159ac Binary files /dev/null and b/images/sprites/animations/wandy.png differ diff --git a/images/sprites/animations/warrior_shield.png b/images/sprites/animations/warrior_shield.png new file mode 100644 index 0000000..81faffb Binary files /dev/null and b/images/sprites/animations/warrior_shield.png differ diff --git a/images/sprites/animations/wslash.png b/images/sprites/animations/wslash.png new file mode 100644 index 0000000..5a2897d Binary files /dev/null and b/images/sprites/animations/wslash.png differ diff --git a/images/sprites/emblems/emblems.png b/images/sprites/emblems/emblems.png new file mode 100644 index 0000000..45de389 Binary files /dev/null and b/images/sprites/emblems/emblems.png differ diff --git a/images/sprites/emblems/emblems.pxm b/images/sprites/emblems/emblems.pxm new file mode 100644 index 0000000..2c1ebec Binary files /dev/null and b/images/sprites/emblems/emblems.pxm differ diff --git a/images/sprites/emotions/heart_burst.png b/images/sprites/emotions/heart_burst.png new file mode 100644 index 0000000..937d8bb Binary files /dev/null and b/images/sprites/emotions/heart_burst.png differ diff --git a/images/sprites/emotions/heart_rise_multi.png b/images/sprites/emotions/heart_rise_multi.png new file mode 100644 index 0000000..a9b4e89 Binary files /dev/null and b/images/sprites/emotions/heart_rise_multi.png differ diff --git a/images/sprites/emotions/heart_rise_single.png b/images/sprites/emotions/heart_rise_single.png new file mode 100644 index 0000000..e76a386 Binary files /dev/null and b/images/sprites/emotions/heart_rise_single.png differ diff --git a/images/sprites/emotions/star_burst.png b/images/sprites/emotions/star_burst.png new file mode 100644 index 0000000..6a4ea96 Binary files /dev/null and b/images/sprites/emotions/star_burst.png differ diff --git a/images/sprites/emotions/star_rise_multi.png b/images/sprites/emotions/star_rise_multi.png new file mode 100644 index 0000000..a6b5144 Binary files /dev/null and b/images/sprites/emotions/star_rise_multi.png differ diff --git a/images/sprites/emotions/star_rise_single.png b/images/sprites/emotions/star_rise_single.png new file mode 100644 index 0000000..f42588f Binary files /dev/null and b/images/sprites/emotions/star_rise_single.png differ diff --git a/images/sprites/flare_effect_sheet_1.png b/images/sprites/flare_effect_sheet_1.png new file mode 100644 index 0000000..7e1a03d Binary files /dev/null and b/images/sprites/flare_effect_sheet_1.png differ diff --git a/images/sprites/lilsparkles_rm_1x.png b/images/sprites/lilsparkles_rm_1x.png new file mode 100644 index 0000000..57abf1a Binary files /dev/null and b/images/sprites/lilsparkles_rm_1x.png differ diff --git a/images/sprites/liltileflash_rm_1x.png b/images/sprites/liltileflash_rm_1x.png new file mode 100644 index 0000000..3c02198 Binary files /dev/null and b/images/sprites/liltileflash_rm_1x.png differ diff --git a/images/sprites/new-emote-animations-set2-sheet.png b/images/sprites/new-emote-animations-set2-sheet.png new file mode 100644 index 0000000..f2e6559 Binary files /dev/null and b/images/sprites/new-emote-animations-set2-sheet.png differ diff --git a/images/sprites/new-emote-animations-sheet.png b/images/sprites/new-emote-animations-sheet.png new file mode 100644 index 0000000..7d2e265 Binary files /dev/null and b/images/sprites/new-emote-animations-sheet.png differ diff --git a/images/sprites/speechbubble_strip8.png b/images/sprites/speechbubble_strip8.png new file mode 100644 index 0000000..e4d36c8 Binary files /dev/null and b/images/sprites/speechbubble_strip8.png differ diff --git a/images/sprites/speechnext_strip8.png b/images/sprites/speechnext_strip8.png new file mode 100644 index 0000000..b82f064 Binary files /dev/null and b/images/sprites/speechnext_strip8.png differ diff --git a/images/sprites/unlock_animation_1.png b/images/sprites/unlock_animation_1.png new file mode 100644 index 0000000..5882c1c Binary files /dev/null and b/images/sprites/unlock_animation_1.png differ diff --git a/images/sprites/weather/fog.png b/images/sprites/weather/fog.png new file mode 100644 index 0000000..da256c7 Binary files /dev/null and b/images/sprites/weather/fog.png differ diff --git a/images/sprites/weather/fog.pxm b/images/sprites/weather/fog.pxm new file mode 100644 index 0000000..fd52f20 Binary files /dev/null and b/images/sprites/weather/fog.pxm differ diff --git a/images/sprites/weather/wsheet_drop1_1.png b/images/sprites/weather/wsheet_drop1_1.png new file mode 100644 index 0000000..955e209 Binary files /dev/null and b/images/sprites/weather/wsheet_drop1_1.png differ diff --git a/images/sprites/weather/wsheet_rain1_1.png b/images/sprites/weather/wsheet_rain1_1.png new file mode 100644 index 0000000..e14af8b Binary files /dev/null and b/images/sprites/weather/wsheet_rain1_1.png differ diff --git a/images/sprites/weather/wsheet_rain2_1.png b/images/sprites/weather/wsheet_rain2_1.png new file mode 100644 index 0000000..f1298a1 Binary files /dev/null and b/images/sprites/weather/wsheet_rain2_1.png differ diff --git a/images/sprites/weather/wsheet_snow_1.png b/images/sprites/weather/wsheet_snow_1.png new file mode 100644 index 0000000..265407b Binary files /dev/null and b/images/sprites/weather/wsheet_snow_1.png differ diff --git a/images/tiles/.DS_Store b/images/tiles/.DS_Store new file mode 100644 index 0000000..7ef579a Binary files /dev/null and b/images/tiles/.DS_Store differ diff --git a/images/tiles/animations/.DS_Store b/images/tiles/animations/.DS_Store new file mode 100644 index 0000000..e866e2a Binary files /dev/null and b/images/tiles/animations/.DS_Store differ diff --git a/images/tiles/animations/arrow.png b/images/tiles/animations/arrow.png new file mode 100755 index 0000000..663a038 Binary files /dev/null and b/images/tiles/animations/arrow.png differ diff --git a/images/tiles/animations/claw_bite.png b/images/tiles/animations/claw_bite.png new file mode 100755 index 0000000..fdfd90a Binary files /dev/null and b/images/tiles/animations/claw_bite.png differ diff --git a/images/tiles/animations/custom/crackle1.png b/images/tiles/animations/custom/crackle1.png new file mode 100644 index 0000000..783fe34 Binary files /dev/null and b/images/tiles/animations/custom/crackle1.png differ diff --git a/images/tiles/animations/custom/crackle1.pxm b/images/tiles/animations/custom/crackle1.pxm new file mode 100644 index 0000000..a5a5ff3 Binary files /dev/null and b/images/tiles/animations/custom/crackle1.pxm differ diff --git a/images/tiles/animations/darkness.png b/images/tiles/animations/darkness.png new file mode 100755 index 0000000..e3cb247 Binary files /dev/null and b/images/tiles/animations/darkness.png differ diff --git a/images/tiles/animations/dust.png b/images/tiles/animations/dust.png new file mode 100755 index 0000000..bbdb935 Binary files /dev/null and b/images/tiles/animations/dust.png differ diff --git a/images/tiles/animations/earth1.png b/images/tiles/animations/earth1.png new file mode 100755 index 0000000..57639fa Binary files /dev/null and b/images/tiles/animations/earth1.png differ diff --git a/images/tiles/animations/earth2.png b/images/tiles/animations/earth2.png new file mode 100755 index 0000000..5e0cecc Binary files /dev/null and b/images/tiles/animations/earth2.png differ diff --git a/images/tiles/animations/explosion.png b/images/tiles/animations/explosion.png new file mode 100755 index 0000000..5be1c31 Binary files /dev/null and b/images/tiles/animations/explosion.png differ diff --git a/images/tiles/animations/fire.png b/images/tiles/animations/fire.png new file mode 100755 index 0000000..ecebd9d Binary files /dev/null and b/images/tiles/animations/fire.png differ diff --git a/images/tiles/animations/fireworksA_1.png b/images/tiles/animations/fireworksA_1.png new file mode 100644 index 0000000..9520dae Binary files /dev/null and b/images/tiles/animations/fireworksA_1.png differ diff --git a/images/tiles/animations/fireworksB_1.png b/images/tiles/animations/fireworksB_1.png new file mode 100644 index 0000000..e4241f9 Binary files /dev/null and b/images/tiles/animations/fireworksB_1.png differ diff --git a/images/tiles/animations/fireworksC_1.png b/images/tiles/animations/fireworksC_1.png new file mode 100644 index 0000000..4827666 Binary files /dev/null and b/images/tiles/animations/fireworksC_1.png differ diff --git a/images/tiles/animations/heal.png b/images/tiles/animations/heal.png new file mode 100755 index 0000000..6443e4a Binary files /dev/null and b/images/tiles/animations/heal.png differ diff --git a/images/tiles/animations/holy.png b/images/tiles/animations/holy.png new file mode 100755 index 0000000..46c640a Binary files /dev/null and b/images/tiles/animations/holy.png differ diff --git a/images/tiles/animations/ice.png b/images/tiles/animations/ice.png new file mode 100755 index 0000000..29ca914 Binary files /dev/null and b/images/tiles/animations/ice.png differ diff --git a/images/tiles/animations/impact1.png b/images/tiles/animations/impact1.png new file mode 100755 index 0000000..c547b67 Binary files /dev/null and b/images/tiles/animations/impact1.png differ diff --git a/images/tiles/animations/impact2.png b/images/tiles/animations/impact2.png new file mode 100755 index 0000000..62f2983 Binary files /dev/null and b/images/tiles/animations/impact2.png differ diff --git a/images/tiles/animations/lightning.png b/images/tiles/animations/lightning.png new file mode 100755 index 0000000..af4ae32 Binary files /dev/null and b/images/tiles/animations/lightning.png differ diff --git a/images/tiles/animations/smoke.png b/images/tiles/animations/smoke.png new file mode 100755 index 0000000..9688e24 Binary files /dev/null and b/images/tiles/animations/smoke.png differ diff --git a/images/tiles/animations/status_1.png b/images/tiles/animations/status_1.png new file mode 100755 index 0000000..fe7d3b1 Binary files /dev/null and b/images/tiles/animations/status_1.png differ diff --git a/images/tiles/animations/status_2.png b/images/tiles/animations/status_2.png new file mode 100755 index 0000000..318644d Binary files /dev/null and b/images/tiles/animations/status_2.png differ diff --git a/images/tiles/animations/water.png b/images/tiles/animations/water.png new file mode 100755 index 0000000..30bfd9d Binary files /dev/null and b/images/tiles/animations/water.png differ diff --git a/images/tiles/animations/weapons_1.png b/images/tiles/animations/weapons_1.png new file mode 100755 index 0000000..33e5117 Binary files /dev/null and b/images/tiles/animations/weapons_1.png differ diff --git a/images/tiles/animations/weapons_2.png b/images/tiles/animations/weapons_2.png new file mode 100755 index 0000000..a801107 Binary files /dev/null and b/images/tiles/animations/weapons_2.png differ diff --git a/images/tiles/animations/weapons_3.png b/images/tiles/animations/weapons_3.png new file mode 100755 index 0000000..360cd61 Binary files /dev/null and b/images/tiles/animations/weapons_3.png differ diff --git a/images/tiles/characters/.DS_Store b/images/tiles/characters/.DS_Store new file mode 100644 index 0000000..ccf85a1 Binary files /dev/null and b/images/tiles/characters/.DS_Store differ diff --git a/images/tiles/characters/adversaries.png b/images/tiles/characters/adversaries.png new file mode 100644 index 0000000..9384901 Binary files /dev/null and b/images/tiles/characters/adversaries.png differ diff --git a/images/tiles/characters/angel.png b/images/tiles/characters/angel.png new file mode 100755 index 0000000..4955994 Binary files /dev/null and b/images/tiles/characters/angel.png differ diff --git a/images/tiles/characters/angel_wingless.png b/images/tiles/characters/angel_wingless.png new file mode 100755 index 0000000..4e3928f Binary files /dev/null and b/images/tiles/characters/angel_wingless.png differ diff --git a/images/tiles/characters/animation1i.png b/images/tiles/characters/animation1i.png new file mode 100644 index 0000000..dd597a7 Binary files /dev/null and b/images/tiles/characters/animation1i.png differ diff --git a/images/tiles/characters/animation2.png b/images/tiles/characters/animation2.png new file mode 100755 index 0000000..20ad1af Binary files /dev/null and b/images/tiles/characters/animation2.png differ diff --git a/images/tiles/characters/animation3.png b/images/tiles/characters/animation3.png new file mode 100755 index 0000000..add9d97 Binary files /dev/null and b/images/tiles/characters/animation3.png differ diff --git a/images/tiles/characters/animationc.png b/images/tiles/characters/animationc.png new file mode 100644 index 0000000..15db580 Binary files /dev/null and b/images/tiles/characters/animationc.png differ diff --git a/images/tiles/characters/animationc.pxm b/images/tiles/characters/animationc.pxm new file mode 100644 index 0000000..5441bf5 Binary files /dev/null and b/images/tiles/characters/animationc.pxm differ diff --git a/images/tiles/characters/astronaut_walk_shadow_tf.png b/images/tiles/characters/astronaut_walk_shadow_tf.png new file mode 100644 index 0000000..32e7914 Binary files /dev/null and b/images/tiles/characters/astronaut_walk_shadow_tf.png differ diff --git a/images/tiles/characters/astronaut_walk_tf.png b/images/tiles/characters/astronaut_walk_tf.png new file mode 100644 index 0000000..3a9c9c8 Binary files /dev/null and b/images/tiles/characters/astronaut_walk_tf.png differ diff --git a/images/tiles/characters/automatron.png b/images/tiles/characters/automatron.png new file mode 100644 index 0000000..16ea180 Binary files /dev/null and b/images/tiles/characters/automatron.png differ diff --git a/images/tiles/characters/automatron2.png b/images/tiles/characters/automatron2.png new file mode 100644 index 0000000..593a3c8 Binary files /dev/null and b/images/tiles/characters/automatron2.png differ diff --git a/images/tiles/characters/bandits_1.png b/images/tiles/characters/bandits_1.png new file mode 100644 index 0000000..a5c43b9 Binary files /dev/null and b/images/tiles/characters/bandits_1.png differ diff --git a/images/tiles/characters/bard_female_1.png b/images/tiles/characters/bard_female_1.png new file mode 100644 index 0000000..5fc46c2 Binary files /dev/null and b/images/tiles/characters/bard_female_1.png differ diff --git a/images/tiles/characters/bardo_1.png b/images/tiles/characters/bardo_1.png new file mode 100644 index 0000000..b6bba99 Binary files /dev/null and b/images/tiles/characters/bardo_1.png differ diff --git a/images/tiles/characters/base_female_single_1.png b/images/tiles/characters/base_female_single_1.png new file mode 100644 index 0000000..64b1e3e Binary files /dev/null and b/images/tiles/characters/base_female_single_1.png differ diff --git a/images/tiles/characters/beekeeper_1.png b/images/tiles/characters/beekeeper_1.png new file mode 100644 index 0000000..923ed01 Binary files /dev/null and b/images/tiles/characters/beekeeper_1.png differ diff --git a/images/tiles/characters/blacksmith_updated_1.png b/images/tiles/characters/blacksmith_updated_1.png new file mode 100644 index 0000000..c7cc4c3 Binary files /dev/null and b/images/tiles/characters/blacksmith_updated_1.png differ diff --git a/images/tiles/characters/bonus1.png b/images/tiles/characters/bonus1.png new file mode 100755 index 0000000..e4d7d9f Binary files /dev/null and b/images/tiles/characters/bonus1.png differ diff --git a/images/tiles/characters/bughero_walking_1.png b/images/tiles/characters/bughero_walking_1.png new file mode 100644 index 0000000..67ab09f Binary files /dev/null and b/images/tiles/characters/bughero_walking_1.png differ diff --git a/images/tiles/characters/bugtribe_base_1.png b/images/tiles/characters/bugtribe_base_1.png new file mode 100644 index 0000000..1458154 Binary files /dev/null and b/images/tiles/characters/bugtribe_base_1.png differ diff --git a/images/tiles/characters/bugtribe_chars_1.png b/images/tiles/characters/bugtribe_chars_1.png new file mode 100644 index 0000000..aed5177 Binary files /dev/null and b/images/tiles/characters/bugtribe_chars_1.png differ diff --git a/images/tiles/characters/char_fisherman1_1.png b/images/tiles/characters/char_fisherman1_1.png new file mode 100644 index 0000000..c05a16a Binary files /dev/null and b/images/tiles/characters/char_fisherman1_1.png differ diff --git a/images/tiles/characters/char_fisherman2_1.png b/images/tiles/characters/char_fisherman2_1.png new file mode 100644 index 0000000..05545a1 Binary files /dev/null and b/images/tiles/characters/char_fisherman2_1.png differ diff --git a/images/tiles/characters/chara2.png b/images/tiles/characters/chara2.png new file mode 100755 index 0000000..411af48 Binary files /dev/null and b/images/tiles/characters/chara2.png differ diff --git a/images/tiles/characters/chara3.png b/images/tiles/characters/chara3.png new file mode 100755 index 0000000..929d52e Binary files /dev/null and b/images/tiles/characters/chara3.png differ diff --git a/images/tiles/characters/chara4.png b/images/tiles/characters/chara4.png new file mode 100755 index 0000000..e951073 Binary files /dev/null and b/images/tiles/characters/chara4.png differ diff --git a/images/tiles/characters/chara5.png b/images/tiles/characters/chara5.png new file mode 100755 index 0000000..816ae86 Binary files /dev/null and b/images/tiles/characters/chara5.png differ diff --git a/images/tiles/characters/chara6.png b/images/tiles/characters/chara6.png new file mode 100755 index 0000000..26ecf43 Binary files /dev/null and b/images/tiles/characters/chara6.png differ diff --git a/images/tiles/characters/chara7.png b/images/tiles/characters/chara7.png new file mode 100755 index 0000000..a2471e0 Binary files /dev/null and b/images/tiles/characters/chara7.png differ diff --git a/images/tiles/characters/chara8.png b/images/tiles/characters/chara8.png new file mode 100755 index 0000000..c64269d Binary files /dev/null and b/images/tiles/characters/chara8.png differ diff --git a/images/tiles/characters/children1.png b/images/tiles/characters/children1.png new file mode 100644 index 0000000..2bafae3 Binary files /dev/null and b/images/tiles/characters/children1.png differ diff --git a/images/tiles/characters/coatguy_1.png b/images/tiles/characters/coatguy_1.png new file mode 100644 index 0000000..ad506e0 Binary files /dev/null and b/images/tiles/characters/coatguy_1.png differ diff --git a/images/tiles/characters/collection1.png b/images/tiles/characters/collection1.png new file mode 100644 index 0000000..920ad45 Binary files /dev/null and b/images/tiles/characters/collection1.png differ diff --git a/images/tiles/characters/collection1.pxm b/images/tiles/characters/collection1.pxm new file mode 100644 index 0000000..a23e9b1 Binary files /dev/null and b/images/tiles/characters/collection1.pxm differ diff --git a/images/tiles/characters/collection2.png b/images/tiles/characters/collection2.png new file mode 100644 index 0000000..f682a6a Binary files /dev/null and b/images/tiles/characters/collection2.png differ diff --git a/images/tiles/characters/collection2.pxm b/images/tiles/characters/collection2.pxm new file mode 100644 index 0000000..5ec44f7 Binary files /dev/null and b/images/tiles/characters/collection2.pxm differ diff --git a/images/tiles/characters/collection3.png b/images/tiles/characters/collection3.png new file mode 100644 index 0000000..5805b1e Binary files /dev/null and b/images/tiles/characters/collection3.png differ diff --git a/images/tiles/characters/collection3.pxm b/images/tiles/characters/collection3.pxm new file mode 100644 index 0000000..f63deb3 Binary files /dev/null and b/images/tiles/characters/collection3.pxm differ diff --git a/images/tiles/characters/collectionx.png b/images/tiles/characters/collectionx.png new file mode 100644 index 0000000..0922163 Binary files /dev/null and b/images/tiles/characters/collectionx.png differ diff --git a/images/tiles/characters/collectionx.pxm b/images/tiles/characters/collectionx.pxm new file mode 100644 index 0000000..1924605 Binary files /dev/null and b/images/tiles/characters/collectionx.pxm differ diff --git a/images/tiles/characters/cossack_1.png b/images/tiles/characters/cossack_1.png new file mode 100644 index 0000000..cab0f0f Binary files /dev/null and b/images/tiles/characters/cossack_1.png differ diff --git a/images/tiles/characters/cultists_1.png b/images/tiles/characters/cultists_1.png new file mode 100644 index 0000000..7ed729e Binary files /dev/null and b/images/tiles/characters/cultists_1.png differ diff --git a/images/tiles/characters/custom1.png b/images/tiles/characters/custom1.png new file mode 100644 index 0000000..f22fe32 Binary files /dev/null and b/images/tiles/characters/custom1.png differ diff --git a/images/tiles/characters/custom1.pxm b/images/tiles/characters/custom1.pxm new file mode 100644 index 0000000..475cdab Binary files /dev/null and b/images/tiles/characters/custom1.pxm differ diff --git a/images/tiles/characters/custom2.png b/images/tiles/characters/custom2.png new file mode 100644 index 0000000..8510008 Binary files /dev/null and b/images/tiles/characters/custom2.png differ diff --git a/images/tiles/characters/custom2.pxm b/images/tiles/characters/custom2.pxm new file mode 100644 index 0000000..c3ceba3 Binary files /dev/null and b/images/tiles/characters/custom2.pxm differ diff --git a/images/tiles/characters/custom3.png b/images/tiles/characters/custom3.png new file mode 100644 index 0000000..ed5c057 Binary files /dev/null and b/images/tiles/characters/custom3.png differ diff --git a/images/tiles/characters/custom3.pxm b/images/tiles/characters/custom3.pxm new file mode 100644 index 0000000..6cb42f1 Binary files /dev/null and b/images/tiles/characters/custom3.pxm differ diff --git a/images/tiles/characters/darkelf1_1.png b/images/tiles/characters/darkelf1_1.png new file mode 100644 index 0000000..b038a25 Binary files /dev/null and b/images/tiles/characters/darkelf1_1.png differ diff --git a/images/tiles/characters/dotd_dancers_1.png b/images/tiles/characters/dotd_dancers_1.png new file mode 100644 index 0000000..955c6f1 Binary files /dev/null and b/images/tiles/characters/dotd_dancers_1.png differ diff --git a/images/tiles/characters/dryad_skin_1.png b/images/tiles/characters/dryad_skin_1.png new file mode 100644 index 0000000..cc67e33 Binary files /dev/null and b/images/tiles/characters/dryad_skin_1.png differ diff --git a/images/tiles/characters/dwarf1.png b/images/tiles/characters/dwarf1.png new file mode 100755 index 0000000..703de16 Binary files /dev/null and b/images/tiles/characters/dwarf1.png differ diff --git a/images/tiles/characters/dwarf2.png b/images/tiles/characters/dwarf2.png new file mode 100755 index 0000000..9447e9f Binary files /dev/null and b/images/tiles/characters/dwarf2.png differ diff --git a/images/tiles/characters/dwarfgirls_1.png b/images/tiles/characters/dwarfgirls_1.png new file mode 100644 index 0000000..6b974fb Binary files /dev/null and b/images/tiles/characters/dwarfgirls_1.png differ diff --git a/images/tiles/characters/elf1.png b/images/tiles/characters/elf1.png new file mode 100755 index 0000000..1ea6041 Binary files /dev/null and b/images/tiles/characters/elf1.png differ diff --git a/images/tiles/characters/elf2.png b/images/tiles/characters/elf2.png new file mode 100755 index 0000000..18412e8 Binary files /dev/null and b/images/tiles/characters/elf2.png differ diff --git a/images/tiles/characters/emotes/.DS_Store b/images/tiles/characters/emotes/.DS_Store new file mode 100644 index 0000000..4575b7a Binary files /dev/null and b/images/tiles/characters/emotes/.DS_Store differ diff --git a/images/tiles/characters/emotes/angel_emote_1.png b/images/tiles/characters/emotes/angel_emote_1.png new file mode 100644 index 0000000..49fa3c5 Binary files /dev/null and b/images/tiles/characters/emotes/angel_emote_1.png differ diff --git a/images/tiles/characters/emotes/angel_wingless_emote_1.png b/images/tiles/characters/emotes/angel_wingless_emote_1.png new file mode 100644 index 0000000..23b42c0 Binary files /dev/null and b/images/tiles/characters/emotes/angel_wingless_emote_1.png differ diff --git a/images/tiles/characters/emotes/dwarf1_emote.png b/images/tiles/characters/emotes/dwarf1_emote.png new file mode 100755 index 0000000..9cc7a43 Binary files /dev/null and b/images/tiles/characters/emotes/dwarf1_emote.png differ diff --git a/images/tiles/characters/emotes/dwarf2_emote.png b/images/tiles/characters/emotes/dwarf2_emote.png new file mode 100755 index 0000000..2f3cdf4 Binary files /dev/null and b/images/tiles/characters/emotes/dwarf2_emote.png differ diff --git a/images/tiles/characters/emotes/elf1_emote.png b/images/tiles/characters/emotes/elf1_emote.png new file mode 100755 index 0000000..323df2a Binary files /dev/null and b/images/tiles/characters/emotes/elf1_emote.png differ diff --git a/images/tiles/characters/emotes/elf2_emote.png b/images/tiles/characters/emotes/elf2_emote.png new file mode 100755 index 0000000..880d232 Binary files /dev/null and b/images/tiles/characters/emotes/elf2_emote.png differ diff --git a/images/tiles/characters/emotes/emote2.png b/images/tiles/characters/emotes/emote2.png new file mode 100755 index 0000000..f2f514c Binary files /dev/null and b/images/tiles/characters/emotes/emote2.png differ diff --git a/images/tiles/characters/emotes/emote3.png b/images/tiles/characters/emotes/emote3.png new file mode 100755 index 0000000..756147e Binary files /dev/null and b/images/tiles/characters/emotes/emote3.png differ diff --git a/images/tiles/characters/emotes/emote4.png b/images/tiles/characters/emotes/emote4.png new file mode 100755 index 0000000..120c910 Binary files /dev/null and b/images/tiles/characters/emotes/emote4.png differ diff --git a/images/tiles/characters/emotes/emote5.png b/images/tiles/characters/emotes/emote5.png new file mode 100755 index 0000000..f9d3494 Binary files /dev/null and b/images/tiles/characters/emotes/emote5.png differ diff --git a/images/tiles/characters/emotes/emote6.png b/images/tiles/characters/emotes/emote6.png new file mode 100755 index 0000000..9ae3007 Binary files /dev/null and b/images/tiles/characters/emotes/emote6.png differ diff --git a/images/tiles/characters/emotes/emote7.png b/images/tiles/characters/emotes/emote7.png new file mode 100755 index 0000000..61dfe5d Binary files /dev/null and b/images/tiles/characters/emotes/emote7.png differ diff --git a/images/tiles/characters/emotes/emote8.png b/images/tiles/characters/emotes/emote8.png new file mode 100755 index 0000000..d0bf79d Binary files /dev/null and b/images/tiles/characters/emotes/emote8.png differ diff --git a/images/tiles/characters/emotes/khan.pxm b/images/tiles/characters/emotes/khan.pxm new file mode 100644 index 0000000..dc51426 Binary files /dev/null and b/images/tiles/characters/emotes/khan.pxm differ diff --git a/images/tiles/characters/executioner_axe_1.png b/images/tiles/characters/executioner_axe_1.png new file mode 100644 index 0000000..9ad5eba Binary files /dev/null and b/images/tiles/characters/executioner_axe_1.png differ diff --git a/images/tiles/characters/fatNPCs_1.png b/images/tiles/characters/fatNPCs_1.png new file mode 100644 index 0000000..3205004 Binary files /dev/null and b/images/tiles/characters/fatNPCs_1.png differ diff --git a/images/tiles/characters/fatbase_1.png b/images/tiles/characters/fatbase_1.png new file mode 100644 index 0000000..3770835 Binary files /dev/null and b/images/tiles/characters/fatbase_1.png differ diff --git a/images/tiles/characters/fatbasew_1.png b/images/tiles/characters/fatbasew_1.png new file mode 100644 index 0000000..4741826 Binary files /dev/null and b/images/tiles/characters/fatbasew_1.png differ diff --git a/images/tiles/characters/fatmena_1.png b/images/tiles/characters/fatmena_1.png new file mode 100644 index 0000000..33069e9 Binary files /dev/null and b/images/tiles/characters/fatmena_1.png differ diff --git a/images/tiles/characters/fatnobles_sheet_1.png b/images/tiles/characters/fatnobles_sheet_1.png new file mode 100644 index 0000000..24ab570 Binary files /dev/null and b/images/tiles/characters/fatnobles_sheet_1.png differ diff --git a/images/tiles/characters/goblinslayer_single_1.png b/images/tiles/characters/goblinslayer_single_1.png new file mode 100644 index 0000000..7593610 Binary files /dev/null and b/images/tiles/characters/goblinslayer_single_1.png differ diff --git a/images/tiles/characters/hank_single_1.png b/images/tiles/characters/hank_single_1.png new file mode 100644 index 0000000..fe30635 Binary files /dev/null and b/images/tiles/characters/hank_single_1.png differ diff --git a/images/tiles/characters/hazmat_1.png b/images/tiles/characters/hazmat_1.png new file mode 100644 index 0000000..8c8a755 Binary files /dev/null and b/images/tiles/characters/hazmat_1.png differ diff --git a/images/tiles/characters/horse1.png b/images/tiles/characters/horse1.png new file mode 100755 index 0000000..65934f5 Binary files /dev/null and b/images/tiles/characters/horse1.png differ diff --git a/images/tiles/characters/imported/BunnyHostess.png b/images/tiles/characters/imported/BunnyHostess.png new file mode 100644 index 0000000..7aab071 Binary files /dev/null and b/images/tiles/characters/imported/BunnyHostess.png differ diff --git a/images/tiles/characters/imported/HeadMerch.png b/images/tiles/characters/imported/HeadMerch.png new file mode 100644 index 0000000..157778a Binary files /dev/null and b/images/tiles/characters/imported/HeadMerch.png differ diff --git a/images/tiles/characters/imported/butler_1.png b/images/tiles/characters/imported/butler_1.png new file mode 100644 index 0000000..1e4815f Binary files /dev/null and b/images/tiles/characters/imported/butler_1.png differ diff --git a/images/tiles/characters/imported/chef_1.png b/images/tiles/characters/imported/chef_1.png new file mode 100644 index 0000000..18c603c Binary files /dev/null and b/images/tiles/characters/imported/chef_1.png differ diff --git a/images/tiles/characters/imported/creator.png b/images/tiles/characters/imported/creator.png new file mode 100644 index 0000000..582f112 Binary files /dev/null and b/images/tiles/characters/imported/creator.png differ diff --git a/images/tiles/characters/imported/elfgirl_1.png b/images/tiles/characters/imported/elfgirl_1.png new file mode 100644 index 0000000..82a6646 Binary files /dev/null and b/images/tiles/characters/imported/elfgirl_1.png differ diff --git a/images/tiles/characters/imported/executioner_1.png b/images/tiles/characters/imported/executioner_1.png new file mode 100644 index 0000000..4127149 Binary files /dev/null and b/images/tiles/characters/imported/executioner_1.png differ diff --git a/images/tiles/characters/imported/maid_1.png b/images/tiles/characters/imported/maid_1.png new file mode 100644 index 0000000..ebff189 Binary files /dev/null and b/images/tiles/characters/imported/maid_1.png differ diff --git a/images/tiles/characters/imported/ninja_1.png b/images/tiles/characters/imported/ninja_1.png new file mode 100644 index 0000000..64619f0 Binary files /dev/null and b/images/tiles/characters/imported/ninja_1.png differ diff --git a/images/tiles/characters/imported/priestess_1.png b/images/tiles/characters/imported/priestess_1.png new file mode 100644 index 0000000..d30f767 Binary files /dev/null and b/images/tiles/characters/imported/priestess_1.png differ diff --git a/images/tiles/characters/imported/reaper_1.png b/images/tiles/characters/imported/reaper_1.png new file mode 100644 index 0000000..a46db44 Binary files /dev/null and b/images/tiles/characters/imported/reaper_1.png differ diff --git a/images/tiles/characters/imported/reaper_blade_1.png b/images/tiles/characters/imported/reaper_blade_1.png new file mode 100644 index 0000000..2de6459 Binary files /dev/null and b/images/tiles/characters/imported/reaper_blade_1.png differ diff --git a/images/tiles/characters/imported/samurai_1.png b/images/tiles/characters/imported/samurai_1.png new file mode 100644 index 0000000..e0c3072 Binary files /dev/null and b/images/tiles/characters/imported/samurai_1.png differ diff --git a/images/tiles/characters/imported/shopkeep_singlesheet_1.png b/images/tiles/characters/imported/shopkeep_singlesheet_1.png new file mode 100644 index 0000000..777d788 Binary files /dev/null and b/images/tiles/characters/imported/shopkeep_singlesheet_1.png differ diff --git a/images/tiles/characters/imported/singleRosalia_a_1.png b/images/tiles/characters/imported/singleRosalia_a_1.png new file mode 100644 index 0000000..c80828f Binary files /dev/null and b/images/tiles/characters/imported/singleRosalia_a_1.png differ diff --git a/images/tiles/characters/imported/singleRosalia_b_1.png b/images/tiles/characters/imported/singleRosalia_b_1.png new file mode 100644 index 0000000..1010cad Binary files /dev/null and b/images/tiles/characters/imported/singleRosalia_b_1.png differ diff --git a/images/tiles/characters/imported/snow_angel.png b/images/tiles/characters/imported/snow_angel.png new file mode 100644 index 0000000..f3c1abf Binary files /dev/null and b/images/tiles/characters/imported/snow_angel.png differ diff --git a/images/tiles/characters/imported/terracotta_army.png b/images/tiles/characters/imported/terracotta_army.png new file mode 100644 index 0000000..9fbdb14 Binary files /dev/null and b/images/tiles/characters/imported/terracotta_army.png differ diff --git a/images/tiles/characters/imported/tf_template.png b/images/tiles/characters/imported/tf_template.png new file mode 100755 index 0000000..1b7c47e Binary files /dev/null and b/images/tiles/characters/imported/tf_template.png differ diff --git a/images/tiles/characters/imported/xmas_jesus_1.png b/images/tiles/characters/imported/xmas_jesus_1.png new file mode 100644 index 0000000..c6630b1 Binary files /dev/null and b/images/tiles/characters/imported/xmas_jesus_1.png differ diff --git a/images/tiles/characters/imported/xmas_misses_1.png b/images/tiles/characters/imported/xmas_misses_1.png new file mode 100644 index 0000000..524c0dc Binary files /dev/null and b/images/tiles/characters/imported/xmas_misses_1.png differ diff --git a/images/tiles/characters/imported/xmas_santa_1.png b/images/tiles/characters/imported/xmas_santa_1.png new file mode 100644 index 0000000..55e6e5f Binary files /dev/null and b/images/tiles/characters/imported/xmas_santa_1.png differ diff --git a/images/tiles/characters/jubchan_1.png b/images/tiles/characters/jubchan_1.png new file mode 100644 index 0000000..6b17e67 Binary files /dev/null and b/images/tiles/characters/jubchan_1.png differ diff --git a/images/tiles/characters/judge_walk_single_1.png b/images/tiles/characters/judge_walk_single_1.png new file mode 100644 index 0000000..d0a1dfe Binary files /dev/null and b/images/tiles/characters/judge_walk_single_1.png differ diff --git a/images/tiles/characters/jumping_base.png b/images/tiles/characters/jumping_base.png new file mode 100644 index 0000000..146c833 Binary files /dev/null and b/images/tiles/characters/jumping_base.png differ diff --git a/images/tiles/characters/kings_1.png b/images/tiles/characters/kings_1.png new file mode 100644 index 0000000..8954cf8 Binary files /dev/null and b/images/tiles/characters/kings_1.png differ diff --git a/images/tiles/characters/kingsqueens_1.png b/images/tiles/characters/kingsqueens_1.png new file mode 100644 index 0000000..4af1bf8 Binary files /dev/null and b/images/tiles/characters/kingsqueens_1.png differ diff --git a/images/tiles/characters/knight_factions_1.png b/images/tiles/characters/knight_factions_1.png new file mode 100644 index 0000000..ab8f452 Binary files /dev/null and b/images/tiles/characters/knight_factions_1.png differ diff --git a/images/tiles/characters/knights.png b/images/tiles/characters/knights.png new file mode 100644 index 0000000..920ed19 Binary files /dev/null and b/images/tiles/characters/knights.png differ diff --git a/images/tiles/characters/lich.png b/images/tiles/characters/lich.png new file mode 100755 index 0000000..3a3fc85 Binary files /dev/null and b/images/tiles/characters/lich.png differ diff --git a/images/tiles/characters/maledancers_sheet_1x.png b/images/tiles/characters/maledancers_sheet_1x.png new file mode 100644 index 0000000..3762eef Binary files /dev/null and b/images/tiles/characters/maledancers_sheet_1x.png differ diff --git a/images/tiles/characters/mer_8_shadow_1.png b/images/tiles/characters/mer_8_shadow_1.png new file mode 100644 index 0000000..87b064f Binary files /dev/null and b/images/tiles/characters/mer_8_shadow_1.png differ diff --git a/images/tiles/characters/mer_base_1.png b/images/tiles/characters/mer_base_1.png new file mode 100644 index 0000000..0d5ff6b Binary files /dev/null and b/images/tiles/characters/mer_base_1.png differ diff --git a/images/tiles/characters/mer_base_female_1.png b/images/tiles/characters/mer_base_female_1.png new file mode 100644 index 0000000..b544b2c Binary files /dev/null and b/images/tiles/characters/mer_base_female_1.png differ diff --git a/images/tiles/characters/mer_human_1.png b/images/tiles/characters/mer_human_1.png new file mode 100644 index 0000000..93439e6 Binary files /dev/null and b/images/tiles/characters/mer_human_1.png differ diff --git a/images/tiles/characters/merch_male_cart1.png b/images/tiles/characters/merch_male_cart1.png new file mode 100644 index 0000000..22551b9 Binary files /dev/null and b/images/tiles/characters/merch_male_cart1.png differ diff --git a/images/tiles/characters/military1.png b/images/tiles/characters/military1.png new file mode 100755 index 0000000..926138d Binary files /dev/null and b/images/tiles/characters/military1.png differ diff --git a/images/tiles/characters/military2.png b/images/tiles/characters/military2.png new file mode 100755 index 0000000..64c6d8d Binary files /dev/null and b/images/tiles/characters/military2.png differ diff --git a/images/tiles/characters/military3.png b/images/tiles/characters/military3.png new file mode 100755 index 0000000..8cff83e Binary files /dev/null and b/images/tiles/characters/military3.png differ diff --git a/images/tiles/characters/miners_1.png b/images/tiles/characters/miners_1.png new file mode 100644 index 0000000..2479a75 Binary files /dev/null and b/images/tiles/characters/miners_1.png differ diff --git a/images/tiles/characters/miners_full_1.png b/images/tiles/characters/miners_full_1.png new file mode 100644 index 0000000..525ffa5 Binary files /dev/null and b/images/tiles/characters/miners_full_1.png differ diff --git a/images/tiles/characters/monks_1.png b/images/tiles/characters/monks_1.png new file mode 100644 index 0000000..ca37703 Binary files /dev/null and b/images/tiles/characters/monks_1.png differ diff --git a/images/tiles/characters/mount1.png b/images/tiles/characters/mount1.png new file mode 100755 index 0000000..c6cfd6b Binary files /dev/null and b/images/tiles/characters/mount1.png differ diff --git a/images/tiles/characters/mount2.png b/images/tiles/characters/mount2.png new file mode 100755 index 0000000..0f139b0 Binary files /dev/null and b/images/tiles/characters/mount2.png differ diff --git a/images/tiles/characters/mystics.png b/images/tiles/characters/mystics.png new file mode 100644 index 0000000..c65dc1c Binary files /dev/null and b/images/tiles/characters/mystics.png differ diff --git a/images/tiles/characters/ninja_turtles.png b/images/tiles/characters/ninja_turtles.png new file mode 100644 index 0000000..77e6b72 Binary files /dev/null and b/images/tiles/characters/ninja_turtles.png differ diff --git a/images/tiles/characters/npc1.png b/images/tiles/characters/npc1.png new file mode 100755 index 0000000..d2dfef7 Binary files /dev/null and b/images/tiles/characters/npc1.png differ diff --git a/images/tiles/characters/npc2.png b/images/tiles/characters/npc2.png new file mode 100755 index 0000000..9a9aaf5 Binary files /dev/null and b/images/tiles/characters/npc2.png differ diff --git a/images/tiles/characters/npc3.png b/images/tiles/characters/npc3.png new file mode 100755 index 0000000..d82fd41 Binary files /dev/null and b/images/tiles/characters/npc3.png differ diff --git a/images/tiles/characters/npc4.png b/images/tiles/characters/npc4.png new file mode 100755 index 0000000..d52f7ec Binary files /dev/null and b/images/tiles/characters/npc4.png differ diff --git a/images/tiles/characters/npc5.png b/images/tiles/characters/npc5.png new file mode 100755 index 0000000..e0163d1 Binary files /dev/null and b/images/tiles/characters/npc5.png differ diff --git a/images/tiles/characters/npc6.png b/images/tiles/characters/npc6.png new file mode 100755 index 0000000..0f7c410 Binary files /dev/null and b/images/tiles/characters/npc6.png differ diff --git a/images/tiles/characters/npcactionsB_1.png b/images/tiles/characters/npcactionsB_1.png new file mode 100644 index 0000000..8bc8e23 Binary files /dev/null and b/images/tiles/characters/npcactionsB_1.png differ diff --git a/images/tiles/characters/npcactions_1.png b/images/tiles/characters/npcactions_1.png new file mode 100644 index 0000000..86ade84 Binary files /dev/null and b/images/tiles/characters/npcactions_1.png differ diff --git a/images/tiles/characters/npcs/actions1.png b/images/tiles/characters/npcs/actions1.png new file mode 100755 index 0000000..efeae61 Binary files /dev/null and b/images/tiles/characters/npcs/actions1.png differ diff --git a/images/tiles/characters/npcs/actions2.png b/images/tiles/characters/npcs/actions2.png new file mode 100755 index 0000000..53efd56 Binary files /dev/null and b/images/tiles/characters/npcs/actions2.png differ diff --git a/images/tiles/characters/npcs/bard.png b/images/tiles/characters/npcs/bard.png new file mode 100755 index 0000000..33786eb Binary files /dev/null and b/images/tiles/characters/npcs/bard.png differ diff --git a/images/tiles/characters/npcs/blacksmith.png b/images/tiles/characters/npcs/blacksmith.png new file mode 100755 index 0000000..c2316f1 Binary files /dev/null and b/images/tiles/characters/npcs/blacksmith.png differ diff --git a/images/tiles/characters/npcs/carrying.png b/images/tiles/characters/npcs/carrying.png new file mode 100755 index 0000000..cc99613 Binary files /dev/null and b/images/tiles/characters/npcs/carrying.png differ diff --git a/images/tiles/characters/npcs/children.png b/images/tiles/characters/npcs/children.png new file mode 100755 index 0000000..1832d37 Binary files /dev/null and b/images/tiles/characters/npcs/children.png differ diff --git a/images/tiles/characters/npcs/eating.png b/images/tiles/characters/npcs/eating.png new file mode 100755 index 0000000..d9cc720 Binary files /dev/null and b/images/tiles/characters/npcs/eating.png differ diff --git a/images/tiles/characters/npcs/elder.png b/images/tiles/characters/npcs/elder.png new file mode 100755 index 0000000..0539637 Binary files /dev/null and b/images/tiles/characters/npcs/elder.png differ diff --git a/images/tiles/characters/npcs/executioner.png b/images/tiles/characters/npcs/executioner.png new file mode 100755 index 0000000..e06f274 Binary files /dev/null and b/images/tiles/characters/npcs/executioner.png differ diff --git a/images/tiles/characters/npcs/farmer.png b/images/tiles/characters/npcs/farmer.png new file mode 100755 index 0000000..e7a751e Binary files /dev/null and b/images/tiles/characters/npcs/farmer.png differ diff --git a/images/tiles/characters/npcs/household.png b/images/tiles/characters/npcs/household.png new file mode 100755 index 0000000..98910ce Binary files /dev/null and b/images/tiles/characters/npcs/household.png differ diff --git a/images/tiles/characters/npcs/knights.png b/images/tiles/characters/npcs/knights.png new file mode 100755 index 0000000..eecaf33 Binary files /dev/null and b/images/tiles/characters/npcs/knights.png differ diff --git a/images/tiles/characters/npcs/knights2.png b/images/tiles/characters/npcs/knights2.png new file mode 100755 index 0000000..3cf6788 Binary files /dev/null and b/images/tiles/characters/npcs/knights2.png differ diff --git a/images/tiles/characters/npcs/townsfolk.png b/images/tiles/characters/npcs/townsfolk.png new file mode 100755 index 0000000..b6a9a0b Binary files /dev/null and b/images/tiles/characters/npcs/townsfolk.png differ diff --git a/images/tiles/characters/oldnpcs_1.png b/images/tiles/characters/oldnpcs_1.png new file mode 100644 index 0000000..aa49264 Binary files /dev/null and b/images/tiles/characters/oldnpcs_1.png differ diff --git a/images/tiles/characters/others/.DS_Store b/images/tiles/characters/others/.DS_Store new file mode 100644 index 0000000..f0d1dc2 Binary files /dev/null and b/images/tiles/characters/others/.DS_Store differ diff --git a/images/tiles/characters/others/jsonX.png b/images/tiles/characters/others/jsonX.png new file mode 100644 index 0000000..a314129 Binary files /dev/null and b/images/tiles/characters/others/jsonX.png differ diff --git a/images/tiles/characters/others/newyear_tree.png b/images/tiles/characters/others/newyear_tree.png new file mode 100644 index 0000000..741e6e6 Binary files /dev/null and b/images/tiles/characters/others/newyear_tree.png differ diff --git a/images/tiles/characters/others/ship1.png b/images/tiles/characters/others/ship1.png new file mode 100644 index 0000000..72d5121 Binary files /dev/null and b/images/tiles/characters/others/ship1.png differ diff --git a/images/tiles/characters/others/ship2.png b/images/tiles/characters/others/ship2.png new file mode 100644 index 0000000..112160f Binary files /dev/null and b/images/tiles/characters/others/ship2.png differ diff --git a/images/tiles/characters/others/test.png b/images/tiles/characters/others/test.png new file mode 100644 index 0000000..0fc133f Binary files /dev/null and b/images/tiles/characters/others/test.png differ diff --git a/images/tiles/characters/others/test2.png b/images/tiles/characters/others/test2.png new file mode 100644 index 0000000..96ee6a6 Binary files /dev/null and b/images/tiles/characters/others/test2.png differ diff --git a/images/tiles/characters/others/tristone_f.png b/images/tiles/characters/others/tristone_f.png new file mode 100644 index 0000000..6a18e2f Binary files /dev/null and b/images/tiles/characters/others/tristone_f.png differ diff --git a/images/tiles/characters/others/x_5wp.png b/images/tiles/characters/others/x_5wp.png new file mode 100644 index 0000000..b249d80 Binary files /dev/null and b/images/tiles/characters/others/x_5wp.png differ diff --git a/images/tiles/characters/paladin.png b/images/tiles/characters/paladin.png new file mode 100755 index 0000000..462cac6 Binary files /dev/null and b/images/tiles/characters/paladin.png differ diff --git a/images/tiles/characters/pirates.png b/images/tiles/characters/pirates.png new file mode 100644 index 0000000..e1dcd30 Binary files /dev/null and b/images/tiles/characters/pirates.png differ diff --git a/images/tiles/characters/pj_kids_1.png b/images/tiles/characters/pj_kids_1.png new file mode 100644 index 0000000..1e9eb52 Binary files /dev/null and b/images/tiles/characters/pj_kids_1.png differ diff --git a/images/tiles/characters/prince_1.png b/images/tiles/characters/prince_1.png new file mode 100644 index 0000000..e7c4abc Binary files /dev/null and b/images/tiles/characters/prince_1.png differ diff --git a/images/tiles/characters/princess_1.png b/images/tiles/characters/princess_1.png new file mode 100644 index 0000000..c1cbe7f Binary files /dev/null and b/images/tiles/characters/princess_1.png differ diff --git a/images/tiles/characters/princess_1_f.png b/images/tiles/characters/princess_1_f.png new file mode 100644 index 0000000..5e68ba8 Binary files /dev/null and b/images/tiles/characters/princess_1_f.png differ diff --git a/images/tiles/characters/runechars_reg.png b/images/tiles/characters/runechars_reg.png new file mode 100644 index 0000000..c575393 Binary files /dev/null and b/images/tiles/characters/runechars_reg.png differ diff --git a/images/tiles/characters/shamans.png b/images/tiles/characters/shamans.png new file mode 100644 index 0000000..fbc286a Binary files /dev/null and b/images/tiles/characters/shamans.png differ diff --git a/images/tiles/characters/sheet_winnersa.png b/images/tiles/characters/sheet_winnersa.png new file mode 100644 index 0000000..87608f7 Binary files /dev/null and b/images/tiles/characters/sheet_winnersa.png differ diff --git a/images/tiles/characters/sheet_winnersb.png b/images/tiles/characters/sheet_winnersb.png new file mode 100644 index 0000000..a82b90f Binary files /dev/null and b/images/tiles/characters/sheet_winnersb.png differ diff --git a/images/tiles/characters/skeletonarmy.png b/images/tiles/characters/skeletonarmy.png new file mode 100755 index 0000000..fc6b81f Binary files /dev/null and b/images/tiles/characters/skeletonarmy.png differ diff --git a/images/tiles/characters/sonichu_1.png b/images/tiles/characters/sonichu_1.png new file mode 100644 index 0000000..fd0e3b0 Binary files /dev/null and b/images/tiles/characters/sonichu_1.png differ diff --git a/images/tiles/characters/tf_swimbase_single_1.png b/images/tiles/characters/tf_swimbase_single_1.png new file mode 100644 index 0000000..5f8bc33 Binary files /dev/null and b/images/tiles/characters/tf_swimbase_single_1.png differ diff --git a/images/tiles/characters/the-child_star-wars_gallery_5f8ded41cd26f.jpg b/images/tiles/characters/the-child_star-wars_gallery_5f8ded41cd26f.jpg new file mode 100644 index 0000000..03221cb Binary files /dev/null and b/images/tiles/characters/the-child_star-wars_gallery_5f8ded41cd26f.jpg differ diff --git a/images/tiles/characters/travelmerchant1_1.png b/images/tiles/characters/travelmerchant1_1.png new file mode 100644 index 0000000..5e62199 Binary files /dev/null and b/images/tiles/characters/travelmerchant1_1.png differ diff --git a/images/tiles/characters/travelmerchant2_1.png b/images/tiles/characters/travelmerchant2_1.png new file mode 100644 index 0000000..acff06a Binary files /dev/null and b/images/tiles/characters/travelmerchant2_1.png differ diff --git a/images/tiles/characters/tribes/beast_hero_1.png b/images/tiles/characters/tribes/beast_hero_1.png new file mode 100755 index 0000000..6ba17bb Binary files /dev/null and b/images/tiles/characters/tribes/beast_hero_1.png differ diff --git a/images/tiles/characters/tribes/beast_hero_1_emote.png b/images/tiles/characters/tribes/beast_hero_1_emote.png new file mode 100755 index 0000000..e15bef5 Binary files /dev/null and b/images/tiles/characters/tribes/beast_hero_1_emote.png differ diff --git a/images/tiles/characters/tribes/beast_hero_2.png b/images/tiles/characters/tribes/beast_hero_2.png new file mode 100755 index 0000000..46b6e19 Binary files /dev/null and b/images/tiles/characters/tribes/beast_hero_2.png differ diff --git a/images/tiles/characters/tribes/beast_hero_2_emote.png b/images/tiles/characters/tribes/beast_hero_2_emote.png new file mode 100755 index 0000000..82cf133 Binary files /dev/null and b/images/tiles/characters/tribes/beast_hero_2_emote.png differ diff --git a/images/tiles/characters/tribes/beast_hero_3.png b/images/tiles/characters/tribes/beast_hero_3.png new file mode 100755 index 0000000..0fb5da2 Binary files /dev/null and b/images/tiles/characters/tribes/beast_hero_3.png differ diff --git a/images/tiles/characters/tribes/beast_hero_3_emote.png b/images/tiles/characters/tribes/beast_hero_3_emote.png new file mode 100755 index 0000000..d6b42ad Binary files /dev/null and b/images/tiles/characters/tribes/beast_hero_3_emote.png differ diff --git a/images/tiles/characters/tribes/beast_hero_4.png b/images/tiles/characters/tribes/beast_hero_4.png new file mode 100755 index 0000000..ed87e84 Binary files /dev/null and b/images/tiles/characters/tribes/beast_hero_4.png differ diff --git a/images/tiles/characters/tribes/beast_hero_4_emote.png b/images/tiles/characters/tribes/beast_hero_4_emote.png new file mode 100755 index 0000000..1a22b64 Binary files /dev/null and b/images/tiles/characters/tribes/beast_hero_4_emote.png differ diff --git a/images/tiles/characters/tribes/beast_hero_5.png b/images/tiles/characters/tribes/beast_hero_5.png new file mode 100755 index 0000000..ae9d762 Binary files /dev/null and b/images/tiles/characters/tribes/beast_hero_5.png differ diff --git a/images/tiles/characters/tribes/beast_hero_5_emote.png b/images/tiles/characters/tribes/beast_hero_5_emote.png new file mode 100755 index 0000000..f76b2c1 Binary files /dev/null and b/images/tiles/characters/tribes/beast_hero_5_emote.png differ diff --git a/images/tiles/characters/tribes/beast_tribe_1.png b/images/tiles/characters/tribes/beast_tribe_1.png new file mode 100755 index 0000000..68b7894 Binary files /dev/null and b/images/tiles/characters/tribes/beast_tribe_1.png differ diff --git a/images/tiles/characters/tribes/beast_tribe_2.png b/images/tiles/characters/tribes/beast_tribe_2.png new file mode 100755 index 0000000..bab4f48 Binary files /dev/null and b/images/tiles/characters/tribes/beast_tribe_2.png differ diff --git a/images/tiles/characters/tribes/beast_tribe_3.png b/images/tiles/characters/tribes/beast_tribe_3.png new file mode 100755 index 0000000..77ef2b1 Binary files /dev/null and b/images/tiles/characters/tribes/beast_tribe_3.png differ diff --git a/images/tiles/characters/tribes/beast_tribe_4.png b/images/tiles/characters/tribes/beast_tribe_4.png new file mode 100755 index 0000000..8c8fe48 Binary files /dev/null and b/images/tiles/characters/tribes/beast_tribe_4.png differ diff --git a/images/tiles/characters/tribes/beast_tribe_5.png b/images/tiles/characters/tribes/beast_tribe_5.png new file mode 100755 index 0000000..c26c7ce Binary files /dev/null and b/images/tiles/characters/tribes/beast_tribe_5.png differ diff --git a/images/tiles/characters/tribes/sv_battler/beast_hero_1_sv.png b/images/tiles/characters/tribes/sv_battler/beast_hero_1_sv.png new file mode 100755 index 0000000..6612651 Binary files /dev/null and b/images/tiles/characters/tribes/sv_battler/beast_hero_1_sv.png differ diff --git a/images/tiles/characters/tribes/sv_battler/beast_hero_2_sv.png b/images/tiles/characters/tribes/sv_battler/beast_hero_2_sv.png new file mode 100755 index 0000000..5935939 Binary files /dev/null and b/images/tiles/characters/tribes/sv_battler/beast_hero_2_sv.png differ diff --git a/images/tiles/characters/tribes/sv_battler/beast_hero_3_sv.png b/images/tiles/characters/tribes/sv_battler/beast_hero_3_sv.png new file mode 100755 index 0000000..5d5ed34 Binary files /dev/null and b/images/tiles/characters/tribes/sv_battler/beast_hero_3_sv.png differ diff --git a/images/tiles/characters/tribes/sv_battler/beast_hero_4_sv.png b/images/tiles/characters/tribes/sv_battler/beast_hero_4_sv.png new file mode 100755 index 0000000..524c201 Binary files /dev/null and b/images/tiles/characters/tribes/sv_battler/beast_hero_4_sv.png differ diff --git a/images/tiles/characters/tribes/sv_battler/beast_hero_5_sv.png b/images/tiles/characters/tribes/sv_battler/beast_hero_5_sv.png new file mode 100755 index 0000000..0c10aba Binary files /dev/null and b/images/tiles/characters/tribes/sv_battler/beast_hero_5_sv.png differ diff --git a/images/tiles/characters/tristone_f.png b/images/tiles/characters/tristone_f.png new file mode 100644 index 0000000..f16447a Binary files /dev/null and b/images/tiles/characters/tristone_f.png differ diff --git a/images/tiles/characters/tristone_m.png b/images/tiles/characters/tristone_m.png new file mode 100644 index 0000000..0d743c0 Binary files /dev/null and b/images/tiles/characters/tristone_m.png differ diff --git a/images/tiles/characters/winners_jpa.png b/images/tiles/characters/winners_jpa.png new file mode 100644 index 0000000..541dd10 Binary files /dev/null and b/images/tiles/characters/winners_jpa.png differ diff --git a/images/tiles/characters/winners_jpb.png b/images/tiles/characters/winners_jpb.png new file mode 100644 index 0000000..f5bf026 Binary files /dev/null and b/images/tiles/characters/winners_jpb.png differ diff --git a/images/tiles/characters/worldmapminis_base_1.png b/images/tiles/characters/worldmapminis_base_1.png new file mode 100644 index 0000000..bd473c4 Binary files /dev/null and b/images/tiles/characters/worldmapminis_base_1.png differ diff --git a/images/tiles/characters/worldmapminis_set1_1.png b/images/tiles/characters/worldmapminis_set1_1.png new file mode 100644 index 0000000..2a170a8 Binary files /dev/null and b/images/tiles/characters/worldmapminis_set1_1.png differ diff --git a/images/tiles/examples/.DS_Store b/images/tiles/examples/.DS_Store new file mode 100644 index 0000000..938c76b Binary files /dev/null and b/images/tiles/examples/.DS_Store differ diff --git a/images/tiles/examples/1 (1).gif b/images/tiles/examples/1 (1).gif new file mode 100644 index 0000000..d739fc2 Binary files /dev/null and b/images/tiles/examples/1 (1).gif differ diff --git a/images/tiles/examples/1 (1).png b/images/tiles/examples/1 (1).png new file mode 100644 index 0000000..1df86c6 Binary files /dev/null and b/images/tiles/examples/1 (1).png differ diff --git a/images/tiles/examples/1 (2).png b/images/tiles/examples/1 (2).png new file mode 100644 index 0000000..9d41789 Binary files /dev/null and b/images/tiles/examples/1 (2).png differ diff --git a/images/tiles/examples/1 (3).png b/images/tiles/examples/1 (3).png new file mode 100644 index 0000000..49b9ed3 Binary files /dev/null and b/images/tiles/examples/1 (3).png differ diff --git a/images/tiles/examples/1 (4).png b/images/tiles/examples/1 (4).png new file mode 100644 index 0000000..d9b1166 Binary files /dev/null and b/images/tiles/examples/1 (4).png differ diff --git a/images/tiles/examples/1 (5).png b/images/tiles/examples/1 (5).png new file mode 100644 index 0000000..fabcb62 Binary files /dev/null and b/images/tiles/examples/1 (5).png differ diff --git a/images/tiles/examples/1.gif b/images/tiles/examples/1.gif new file mode 100644 index 0000000..33a7cf8 Binary files /dev/null and b/images/tiles/examples/1.gif differ diff --git a/images/tiles/examples/1.png b/images/tiles/examples/1.png new file mode 100644 index 0000000..a830599 Binary files /dev/null and b/images/tiles/examples/1.png differ diff --git a/images/tiles/examples/1661804015_0SkBQnbv4r.gif b/images/tiles/examples/1661804015_0SkBQnbv4r.gif new file mode 100644 index 0000000..9c9fd4f Binary files /dev/null and b/images/tiles/examples/1661804015_0SkBQnbv4r.gif differ diff --git a/images/tiles/examples/2.png b/images/tiles/examples/2.png new file mode 100644 index 0000000..c669206 Binary files /dev/null and b/images/tiles/examples/2.png differ diff --git a/images/tiles/examples/20171023_144323_b.gif b/images/tiles/examples/20171023_144323_b.gif new file mode 100644 index 0000000..ea66ea4 Binary files /dev/null and b/images/tiles/examples/20171023_144323_b.gif differ diff --git a/images/tiles/examples/20180514_194853.gif b/images/tiles/examples/20180514_194853.gif new file mode 100644 index 0000000..37db451 Binary files /dev/null and b/images/tiles/examples/20180514_194853.gif differ diff --git a/images/tiles/examples/20180809_192504.gif b/images/tiles/examples/20180809_192504.gif new file mode 100644 index 0000000..768f0b2 Binary files /dev/null and b/images/tiles/examples/20180809_192504.gif differ diff --git a/images/tiles/examples/20181216_225643.gif b/images/tiles/examples/20181216_225643.gif new file mode 100644 index 0000000..9e852c0 Binary files /dev/null and b/images/tiles/examples/20181216_225643.gif differ diff --git a/images/tiles/examples/3dyLuq.png b/images/tiles/examples/3dyLuq.png new file mode 100644 index 0000000..60bfce0 Binary files /dev/null and b/images/tiles/examples/3dyLuq.png differ diff --git a/images/tiles/examples/86hfsp.png b/images/tiles/examples/86hfsp.png new file mode 100644 index 0000000..eaa675a Binary files /dev/null and b/images/tiles/examples/86hfsp.png differ diff --git a/images/tiles/examples/8dirpromo.gif b/images/tiles/examples/8dirpromo.gif new file mode 100644 index 0000000..0064d39 Binary files /dev/null and b/images/tiles/examples/8dirpromo.gif differ diff --git a/images/tiles/examples/8hLRXU.png b/images/tiles/examples/8hLRXU.png new file mode 100644 index 0000000..def285c Binary files /dev/null and b/images/tiles/examples/8hLRXU.png differ diff --git a/images/tiles/examples/Balloon_100.png b/images/tiles/examples/Balloon_100.png new file mode 100644 index 0000000..414dd4b Binary files /dev/null and b/images/tiles/examples/Balloon_100.png differ diff --git a/images/tiles/examples/D671r+.png b/images/tiles/examples/D671r+.png new file mode 100644 index 0000000..ea2c33b Binary files /dev/null and b/images/tiles/examples/D671r+.png differ diff --git a/images/tiles/examples/DONTIMPORT_birch.png b/images/tiles/examples/DONTIMPORT_birch.png new file mode 100644 index 0000000..9aa39ce Binary files /dev/null and b/images/tiles/examples/DONTIMPORT_birch.png differ diff --git a/images/tiles/examples/aeronaut_preview.gif b/images/tiles/examples/aeronaut_preview.gif new file mode 100644 index 0000000..a234f9a Binary files /dev/null and b/images/tiles/examples/aeronaut_preview.gif differ diff --git a/images/tiles/examples/ash_terrain_preview.png b/images/tiles/examples/ash_terrain_preview.png new file mode 100644 index 0000000..0293382 Binary files /dev/null and b/images/tiles/examples/ash_terrain_preview.png differ diff --git a/images/tiles/examples/ashgrass_x.png b/images/tiles/examples/ashgrass_x.png new file mode 100644 index 0000000..a0c0a81 Binary files /dev/null and b/images/tiles/examples/ashgrass_x.png differ diff --git a/images/tiles/examples/astronaut_p.gif b/images/tiles/examples/astronaut_p.gif new file mode 100644 index 0000000..6924fb0 Binary files /dev/null and b/images/tiles/examples/astronaut_p.gif differ diff --git a/images/tiles/examples/avTegi.gif b/images/tiles/examples/avTegi.gif new file mode 100644 index 0000000..00ec560 Binary files /dev/null and b/images/tiles/examples/avTegi.gif differ diff --git a/images/tiles/examples/backstairs_p.png b/images/tiles/examples/backstairs_p.png new file mode 100644 index 0000000..96325c0 Binary files /dev/null and b/images/tiles/examples/backstairs_p.png differ diff --git a/images/tiles/examples/bar_preview.png b/images/tiles/examples/bar_preview.png new file mode 100644 index 0000000..11d297a Binary files /dev/null and b/images/tiles/examples/bar_preview.png differ diff --git a/images/tiles/examples/barrel_p.gif b/images/tiles/examples/barrel_p.gif new file mode 100644 index 0000000..068ab4a Binary files /dev/null and b/images/tiles/examples/barrel_p.gif differ diff --git a/images/tiles/examples/battlebkac_test.gif b/images/tiles/examples/battlebkac_test.gif new file mode 100644 index 0000000..b314539 Binary files /dev/null and b/images/tiles/examples/battlebkac_test.gif differ diff --git a/images/tiles/examples/battler.gif b/images/tiles/examples/battler.gif new file mode 100644 index 0000000..092258b Binary files /dev/null and b/images/tiles/examples/battler.gif differ diff --git a/images/tiles/examples/beaverdam_preview.png b/images/tiles/examples/beaverdam_preview.png new file mode 100644 index 0000000..4069760 Binary files /dev/null and b/images/tiles/examples/beaverdam_preview.png differ diff --git a/images/tiles/examples/belly2.png b/images/tiles/examples/belly2.png new file mode 100644 index 0000000..c16dfdd Binary files /dev/null and b/images/tiles/examples/belly2.png differ diff --git a/images/tiles/examples/berribushes_3.png b/images/tiles/examples/berribushes_3.png new file mode 100644 index 0000000..0a005cb Binary files /dev/null and b/images/tiles/examples/berribushes_3.png differ diff --git a/images/tiles/examples/bgpreview.png b/images/tiles/examples/bgpreview.png new file mode 100644 index 0000000..03fd34a Binary files /dev/null and b/images/tiles/examples/bgpreview.png differ diff --git a/images/tiles/examples/bigroofs.png b/images/tiles/examples/bigroofs.png new file mode 100644 index 0000000..032ca9c Binary files /dev/null and b/images/tiles/examples/bigroofs.png differ diff --git a/images/tiles/examples/bio-caves-preview-timefantasy.png b/images/tiles/examples/bio-caves-preview-timefantasy.png new file mode 100644 index 0000000..77bc27b Binary files /dev/null and b/images/tiles/examples/bio-caves-preview-timefantasy.png differ diff --git a/images/tiles/examples/biocavespreview2.png b/images/tiles/examples/biocavespreview2.png new file mode 100644 index 0000000..44864ba Binary files /dev/null and b/images/tiles/examples/biocavespreview2.png differ diff --git a/images/tiles/examples/birch.png b/images/tiles/examples/birch.png new file mode 100644 index 0000000..0c43b72 Binary files /dev/null and b/images/tiles/examples/birch.png differ diff --git a/images/tiles/examples/birds_takeoff.gif b/images/tiles/examples/birds_takeoff.gif new file mode 100644 index 0000000..b287931 Binary files /dev/null and b/images/tiles/examples/birds_takeoff.gif differ diff --git a/images/tiles/examples/blood1.png b/images/tiles/examples/blood1.png new file mode 100644 index 0000000..920ac96 Binary files /dev/null and b/images/tiles/examples/blood1.png differ diff --git a/images/tiles/examples/brushland.png b/images/tiles/examples/brushland.png new file mode 100644 index 0000000..5702d88 Binary files /dev/null and b/images/tiles/examples/brushland.png differ diff --git a/images/tiles/examples/bush_p.gif b/images/tiles/examples/bush_p.gif new file mode 100644 index 0000000..f643733 Binary files /dev/null and b/images/tiles/examples/bush_p.gif differ diff --git a/images/tiles/examples/cactus-promo.png b/images/tiles/examples/cactus-promo.png new file mode 100644 index 0000000..e38ad8a Binary files /dev/null and b/images/tiles/examples/cactus-promo.png differ diff --git a/images/tiles/examples/castlestairs_preview.png b/images/tiles/examples/castlestairs_preview.png new file mode 100644 index 0000000..27b8bad Binary files /dev/null and b/images/tiles/examples/castlestairs_preview.png differ diff --git a/images/tiles/examples/cauldron_preview.gif b/images/tiles/examples/cauldron_preview.gif new file mode 100644 index 0000000..a43383a Binary files /dev/null and b/images/tiles/examples/cauldron_preview.gif differ diff --git a/images/tiles/examples/chesspreview.png b/images/tiles/examples/chesspreview.png new file mode 100644 index 0000000..e82aac1 Binary files /dev/null and b/images/tiles/examples/chesspreview.png differ diff --git a/images/tiles/examples/chestmimics.gif b/images/tiles/examples/chestmimics.gif new file mode 100644 index 0000000..e1eaf6f Binary files /dev/null and b/images/tiles/examples/chestmimics.gif differ diff --git a/images/tiles/examples/chests_new_preview.gif b/images/tiles/examples/chests_new_preview.gif new file mode 100644 index 0000000..660d5ef Binary files /dev/null and b/images/tiles/examples/chests_new_preview.gif differ diff --git a/images/tiles/examples/cliff_drop.png b/images/tiles/examples/cliff_drop.png new file mode 100644 index 0000000..d96ece2 Binary files /dev/null and b/images/tiles/examples/cliff_drop.png differ diff --git a/images/tiles/examples/cliffdoor_secret.gif b/images/tiles/examples/cliffdoor_secret.gif new file mode 100644 index 0000000..a153aa5 Binary files /dev/null and b/images/tiles/examples/cliffdoor_secret.gif differ diff --git a/images/tiles/examples/cliffsgif.gif b/images/tiles/examples/cliffsgif.gif new file mode 100644 index 0000000..da81629 Binary files /dev/null and b/images/tiles/examples/cliffsgif.gif differ diff --git a/images/tiles/examples/conductor_p.gif b/images/tiles/examples/conductor_p.gif new file mode 100644 index 0000000..a38f640 Binary files /dev/null and b/images/tiles/examples/conductor_p.gif differ diff --git a/images/tiles/examples/crystalorb.gif b/images/tiles/examples/crystalorb.gif new file mode 100644 index 0000000..5bcd3c7 Binary files /dev/null and b/images/tiles/examples/crystalorb.gif differ diff --git a/images/tiles/examples/current_vs_better.png b/images/tiles/examples/current_vs_better.png new file mode 100644 index 0000000..4ee200c Binary files /dev/null and b/images/tiles/examples/current_vs_better.png differ diff --git a/images/tiles/examples/deckpreview.png b/images/tiles/examples/deckpreview.png new file mode 100644 index 0000000..e51bf30 Binary files /dev/null and b/images/tiles/examples/deckpreview.png differ diff --git a/images/tiles/examples/demonkingpreview.gif b/images/tiles/examples/demonkingpreview.gif new file mode 100644 index 0000000..9c005e5 Binary files /dev/null and b/images/tiles/examples/demonkingpreview.gif differ diff --git a/images/tiles/examples/diagfull_1.png b/images/tiles/examples/diagfull_1.png new file mode 100644 index 0000000..5c3b397 Binary files /dev/null and b/images/tiles/examples/diagfull_1.png differ diff --git a/images/tiles/examples/dialogs.gif b/images/tiles/examples/dialogs.gif new file mode 100644 index 0000000..bdeb2e3 Binary files /dev/null and b/images/tiles/examples/dialogs.gif differ diff --git a/images/tiles/examples/ebnwfemb.png b/images/tiles/examples/ebnwfemb.png new file mode 100644 index 0000000..abf25ac Binary files /dev/null and b/images/tiles/examples/ebnwfemb.png differ diff --git a/images/tiles/examples/emote_anims_preview.gif b/images/tiles/examples/emote_anims_preview.gif new file mode 100644 index 0000000..33269fc Binary files /dev/null and b/images/tiles/examples/emote_anims_preview.gif differ diff --git a/images/tiles/examples/emotes-set2-preview.gif b/images/tiles/examples/emotes-set2-preview.gif new file mode 100644 index 0000000..41b6ace Binary files /dev/null and b/images/tiles/examples/emotes-set2-preview.gif differ diff --git a/images/tiles/examples/firebeacontowerpreview.gif b/images/tiles/examples/firebeacontowerpreview.gif new file mode 100644 index 0000000..1056112 Binary files /dev/null and b/images/tiles/examples/firebeacontowerpreview.gif differ diff --git a/images/tiles/examples/fish_preview.gif b/images/tiles/examples/fish_preview.gif new file mode 100644 index 0000000..f364ea0 Binary files /dev/null and b/images/tiles/examples/fish_preview.gif differ diff --git a/images/tiles/examples/flagpreview.gif b/images/tiles/examples/flagpreview.gif new file mode 100644 index 0000000..9087606 Binary files /dev/null and b/images/tiles/examples/flagpreview.gif differ diff --git a/images/tiles/examples/flames.gif b/images/tiles/examples/flames.gif new file mode 100644 index 0000000..b524b9f Binary files /dev/null and b/images/tiles/examples/flames.gif differ diff --git a/images/tiles/examples/flare.gif b/images/tiles/examples/flare.gif new file mode 100644 index 0000000..d44f8cc Binary files /dev/null and b/images/tiles/examples/flare.gif differ diff --git a/images/tiles/examples/fountainprev.gif b/images/tiles/examples/fountainprev.gif new file mode 100644 index 0000000..0224e1e Binary files /dev/null and b/images/tiles/examples/fountainprev.gif differ diff --git a/images/tiles/examples/gYfr2n.png b/images/tiles/examples/gYfr2n.png new file mode 100644 index 0000000..34e379e Binary files /dev/null and b/images/tiles/examples/gYfr2n.png differ diff --git a/images/tiles/examples/greenhouse_int_preview.png b/images/tiles/examples/greenhouse_int_preview.png new file mode 100644 index 0000000..d1e5b74 Binary files /dev/null and b/images/tiles/examples/greenhouse_int_preview.png differ diff --git a/images/tiles/examples/greenplants.png b/images/tiles/examples/greenplants.png new file mode 100644 index 0000000..f2033e0 Binary files /dev/null and b/images/tiles/examples/greenplants.png differ diff --git a/images/tiles/examples/guide.png b/images/tiles/examples/guide.png new file mode 100755 index 0000000..7502546 Binary files /dev/null and b/images/tiles/examples/guide.png differ diff --git a/images/tiles/examples/guilopromo.png b/images/tiles/examples/guilopromo.png new file mode 100644 index 0000000..1c1285d Binary files /dev/null and b/images/tiles/examples/guilopromo.png differ diff --git a/images/tiles/examples/hobbit.png b/images/tiles/examples/hobbit.png new file mode 100644 index 0000000..8a765cc Binary files /dev/null and b/images/tiles/examples/hobbit.png differ diff --git a/images/tiles/examples/igloo_inside_promo.png b/images/tiles/examples/igloo_inside_promo.png new file mode 100644 index 0000000..ccbec63 Binary files /dev/null and b/images/tiles/examples/igloo_inside_promo.png differ diff --git a/images/tiles/examples/igloo_promo.png b/images/tiles/examples/igloo_promo.png new file mode 100644 index 0000000..ecf86d0 Binary files /dev/null and b/images/tiles/examples/igloo_promo.png differ diff --git a/images/tiles/examples/insidebelly_tentas_gif.gif b/images/tiles/examples/insidebelly_tentas_gif.gif new file mode 100644 index 0000000..d43993d Binary files /dev/null and b/images/tiles/examples/insidebelly_tentas_gif.gif differ diff --git a/images/tiles/examples/ironchefp.gif b/images/tiles/examples/ironchefp.gif new file mode 100644 index 0000000..8fd65df Binary files /dev/null and b/images/tiles/examples/ironchefp.gif differ diff --git a/images/tiles/examples/kingpromoqueen.png b/images/tiles/examples/kingpromoqueen.png new file mode 100644 index 0000000..af9052e Binary files /dev/null and b/images/tiles/examples/kingpromoqueen.png differ diff --git a/images/tiles/examples/kitchen_int_promo.png b/images/tiles/examples/kitchen_int_promo.png new file mode 100644 index 0000000..907c029 Binary files /dev/null and b/images/tiles/examples/kitchen_int_promo.png differ diff --git a/images/tiles/examples/kitchenfireplacepreview.gif b/images/tiles/examples/kitchenfireplacepreview.gif new file mode 100644 index 0000000..3e0d0d4 Binary files /dev/null and b/images/tiles/examples/kitchenfireplacepreview.gif differ diff --git a/images/tiles/examples/levers.gif b/images/tiles/examples/levers.gif new file mode 100644 index 0000000..8cd147b Binary files /dev/null and b/images/tiles/examples/levers.gif differ diff --git a/images/tiles/examples/luchadorp.gif b/images/tiles/examples/luchadorp.gif new file mode 100644 index 0000000..8af409e Binary files /dev/null and b/images/tiles/examples/luchadorp.gif differ diff --git a/images/tiles/examples/magic_circle_preview.gif b/images/tiles/examples/magic_circle_preview.gif new file mode 100644 index 0000000..97b2711 Binary files /dev/null and b/images/tiles/examples/magic_circle_preview.gif differ diff --git a/images/tiles/examples/mansion_interior_extras_promo.png b/images/tiles/examples/mansion_interior_extras_promo.png new file mode 100644 index 0000000..ca68ac0 Binary files /dev/null and b/images/tiles/examples/mansion_interior_extras_promo.png differ diff --git a/images/tiles/examples/mbelly.gif b/images/tiles/examples/mbelly.gif new file mode 100644 index 0000000..2b3de6d Binary files /dev/null and b/images/tiles/examples/mbelly.gif differ diff --git a/images/tiles/examples/mbelly2.gif b/images/tiles/examples/mbelly2.gif new file mode 100644 index 0000000..d5fd34e Binary files /dev/null and b/images/tiles/examples/mbelly2.gif differ diff --git a/images/tiles/examples/minecartscreenshot.png b/images/tiles/examples/minecartscreenshot.png new file mode 100644 index 0000000..6ab7564 Binary files /dev/null and b/images/tiles/examples/minecartscreenshot.png differ diff --git a/images/tiles/examples/morebenches.png b/images/tiles/examples/morebenches.png new file mode 100644 index 0000000..9adf107 Binary files /dev/null and b/images/tiles/examples/morebenches.png differ diff --git a/images/tiles/examples/newfloor_preview_patreon.png b/images/tiles/examples/newfloor_preview_patreon.png new file mode 100644 index 0000000..05ab5d2 Binary files /dev/null and b/images/tiles/examples/newfloor_preview_patreon.png differ diff --git a/images/tiles/examples/newpineforestpreview.png b/images/tiles/examples/newpineforestpreview.png new file mode 100644 index 0000000..c1b51d6 Binary files /dev/null and b/images/tiles/examples/newpineforestpreview.png differ diff --git a/images/tiles/examples/newsnesforest_preview.png b/images/tiles/examples/newsnesforest_preview.png new file mode 100644 index 0000000..cdf0de6 Binary files /dev/null and b/images/tiles/examples/newsnesforest_preview.png differ diff --git a/images/tiles/examples/onionboss_p.gif b/images/tiles/examples/onionboss_p.gif new file mode 100644 index 0000000..7661c7e Binary files /dev/null and b/images/tiles/examples/onionboss_p.gif differ diff --git a/images/tiles/examples/others/.DS_Store b/images/tiles/examples/others/.DS_Store new file mode 100644 index 0000000..c447a3d Binary files /dev/null and b/images/tiles/examples/others/.DS_Store differ diff --git a/images/tiles/examples/others/itch_cover.png b/images/tiles/examples/others/itch_cover.png new file mode 100644 index 0000000..43bf269 Binary files /dev/null and b/images/tiles/examples/others/itch_cover.png differ diff --git a/images/tiles/examples/others/lichpromo.png b/images/tiles/examples/others/lichpromo.png new file mode 100644 index 0000000..f00ccc4 Binary files /dev/null and b/images/tiles/examples/others/lichpromo.png differ diff --git a/images/tiles/examples/p_bite.gif b/images/tiles/examples/p_bite.gif new file mode 100644 index 0000000..122d565 Binary files /dev/null and b/images/tiles/examples/p_bite.gif differ diff --git a/images/tiles/examples/p_bushestall_shot.png b/images/tiles/examples/p_bushestall_shot.png new file mode 100644 index 0000000..06e8d9c Binary files /dev/null and b/images/tiles/examples/p_bushestall_shot.png differ diff --git a/images/tiles/examples/p_earth.gif b/images/tiles/examples/p_earth.gif new file mode 100644 index 0000000..b7cf6c3 Binary files /dev/null and b/images/tiles/examples/p_earth.gif differ diff --git a/images/tiles/examples/p_fire.gif b/images/tiles/examples/p_fire.gif new file mode 100644 index 0000000..7c69d0f Binary files /dev/null and b/images/tiles/examples/p_fire.gif differ diff --git a/images/tiles/examples/p_water.gif b/images/tiles/examples/p_water.gif new file mode 100644 index 0000000..6d18b8b Binary files /dev/null and b/images/tiles/examples/p_water.gif differ diff --git a/images/tiles/examples/patreon_shop_expansion_promo.png b/images/tiles/examples/patreon_shop_expansion_promo.png new file mode 100644 index 0000000..0ccb52c Binary files /dev/null and b/images/tiles/examples/patreon_shop_expansion_promo.png differ diff --git a/images/tiles/examples/pigmanp.gif b/images/tiles/examples/pigmanp.gif new file mode 100644 index 0000000..9f85252 Binary files /dev/null and b/images/tiles/examples/pigmanp.gif differ diff --git a/images/tiles/examples/pineforest.png b/images/tiles/examples/pineforest.png new file mode 100644 index 0000000..168d9f8 Binary files /dev/null and b/images/tiles/examples/pineforest.png differ diff --git a/images/tiles/examples/portalpreviewg.gif b/images/tiles/examples/portalpreviewg.gif new file mode 100644 index 0000000..6e595bd Binary files /dev/null and b/images/tiles/examples/portalpreviewg.gif differ diff --git a/images/tiles/examples/ramps.png b/images/tiles/examples/ramps.png new file mode 100644 index 0000000..0d45318 Binary files /dev/null and b/images/tiles/examples/ramps.png differ diff --git a/images/tiles/examples/savepoint.gif b/images/tiles/examples/savepoint.gif new file mode 100644 index 0000000..c99fbf5 Binary files /dev/null and b/images/tiles/examples/savepoint.gif differ diff --git a/images/tiles/examples/screen4_b.png b/images/tiles/examples/screen4_b.png new file mode 100644 index 0000000..1a9c3c5 Binary files /dev/null and b/images/tiles/examples/screen4_b.png differ diff --git a/images/tiles/examples/screenshot1.png b/images/tiles/examples/screenshot1.png new file mode 100755 index 0000000..0c6918e Binary files /dev/null and b/images/tiles/examples/screenshot1.png differ diff --git a/images/tiles/examples/screenshot2.png b/images/tiles/examples/screenshot2.png new file mode 100755 index 0000000..5876565 Binary files /dev/null and b/images/tiles/examples/screenshot2.png differ diff --git a/images/tiles/examples/screenshot_3.png b/images/tiles/examples/screenshot_3.png new file mode 100644 index 0000000..80ac098 Binary files /dev/null and b/images/tiles/examples/screenshot_3.png differ diff --git a/images/tiles/examples/screenshot_4.png b/images/tiles/examples/screenshot_4.png new file mode 100644 index 0000000..57ff1a4 Binary files /dev/null and b/images/tiles/examples/screenshot_4.png differ diff --git a/images/tiles/examples/sealechestpreview.gif b/images/tiles/examples/sealechestpreview.gif new file mode 100644 index 0000000..8f800b9 Binary files /dev/null and b/images/tiles/examples/sealechestpreview.gif differ diff --git a/images/tiles/examples/sewers.png b/images/tiles/examples/sewers.png new file mode 100644 index 0000000..54d6ffd Binary files /dev/null and b/images/tiles/examples/sewers.png differ diff --git a/images/tiles/examples/shoe_woman.gif b/images/tiles/examples/shoe_woman.gif new file mode 100644 index 0000000..8762459 Binary files /dev/null and b/images/tiles/examples/shoe_woman.gif differ diff --git a/images/tiles/examples/signguyp.gif b/images/tiles/examples/signguyp.gif new file mode 100644 index 0000000..fac74e4 Binary files /dev/null and b/images/tiles/examples/signguyp.gif differ diff --git a/images/tiles/examples/skullhead.gif b/images/tiles/examples/skullhead.gif new file mode 100644 index 0000000..27d7d18 Binary files /dev/null and b/images/tiles/examples/skullhead.gif differ diff --git a/images/tiles/examples/skulls.gif b/images/tiles/examples/skulls.gif new file mode 100644 index 0000000..ffc5b16 Binary files /dev/null and b/images/tiles/examples/skulls.gif differ diff --git a/images/tiles/examples/slimez.gif b/images/tiles/examples/slimez.gif new file mode 100644 index 0000000..a69076f Binary files /dev/null and b/images/tiles/examples/slimez.gif differ diff --git a/images/tiles/examples/smallboat_single_200.png b/images/tiles/examples/smallboat_single_200.png new file mode 100644 index 0000000..ead1337 Binary files /dev/null and b/images/tiles/examples/smallboat_single_200.png differ diff --git a/images/tiles/examples/snake.gif b/images/tiles/examples/snake.gif new file mode 100644 index 0000000..cdd0359 Binary files /dev/null and b/images/tiles/examples/snake.gif differ diff --git a/images/tiles/examples/snakecharmer.gif b/images/tiles/examples/snakecharmer.gif new file mode 100644 index 0000000..a2c509a Binary files /dev/null and b/images/tiles/examples/snakecharmer.gif differ diff --git a/images/tiles/examples/sparklesandshines.gif b/images/tiles/examples/sparklesandshines.gif new file mode 100644 index 0000000..0792d1e Binary files /dev/null and b/images/tiles/examples/sparklesandshines.gif differ diff --git a/images/tiles/examples/spidercave.png b/images/tiles/examples/spidercave.png new file mode 100644 index 0000000..7e5556f Binary files /dev/null and b/images/tiles/examples/spidercave.png differ diff --git a/images/tiles/examples/spikeblockwallanim_promo.gif b/images/tiles/examples/spikeblockwallanim_promo.gif new file mode 100644 index 0000000..b6a8855 Binary files /dev/null and b/images/tiles/examples/spikeblockwallanim_promo.gif differ diff --git a/images/tiles/examples/stonehenge_screenshot.png b/images/tiles/examples/stonehenge_screenshot.png new file mode 100644 index 0000000..f86d5b7 Binary files /dev/null and b/images/tiles/examples/stonehenge_screenshot.png differ diff --git a/images/tiles/examples/stoneportal_p.gif b/images/tiles/examples/stoneportal_p.gif new file mode 100644 index 0000000..3ddbf12 Binary files /dev/null and b/images/tiles/examples/stoneportal_p.gif differ diff --git a/images/tiles/examples/sumo.gif b/images/tiles/examples/sumo.gif new file mode 100644 index 0000000..cf10b17 Binary files /dev/null and b/images/tiles/examples/sumo.gif differ diff --git a/images/tiles/examples/sunandmoo_pn.gif b/images/tiles/examples/sunandmoo_pn.gif new file mode 100644 index 0000000..43724ac Binary files /dev/null and b/images/tiles/examples/sunandmoo_pn.gif differ diff --git a/images/tiles/examples/tarot_promo_small.png b/images/tiles/examples/tarot_promo_small.png new file mode 100644 index 0000000..6789b46 Binary files /dev/null and b/images/tiles/examples/tarot_promo_small.png differ diff --git a/images/tiles/examples/thegangp.gif b/images/tiles/examples/thegangp.gif new file mode 100644 index 0000000..a81f222 Binary files /dev/null and b/images/tiles/examples/thegangp.gif differ diff --git a/images/tiles/examples/train-new-compa.png b/images/tiles/examples/train-new-compa.png new file mode 100644 index 0000000..6bb70a7 Binary files /dev/null and b/images/tiles/examples/train-new-compa.png differ diff --git a/images/tiles/examples/trenchcoat_p.gif b/images/tiles/examples/trenchcoat_p.gif new file mode 100644 index 0000000..db5b259 Binary files /dev/null and b/images/tiles/examples/trenchcoat_p.gif differ diff --git a/images/tiles/examples/twins_p.gif b/images/tiles/examples/twins_p.gif new file mode 100644 index 0000000..d8f75ef Binary files /dev/null and b/images/tiles/examples/twins_p.gif differ diff --git a/images/tiles/examples/unlockpreview.gif b/images/tiles/examples/unlockpreview.gif new file mode 100644 index 0000000..6745a1b Binary files /dev/null and b/images/tiles/examples/unlockpreview.gif differ diff --git a/images/tiles/examples/unnamed (1).gif b/images/tiles/examples/unnamed (1).gif new file mode 100644 index 0000000..4fe26dc Binary files /dev/null and b/images/tiles/examples/unnamed (1).gif differ diff --git a/images/tiles/examples/unnamed (1).png b/images/tiles/examples/unnamed (1).png new file mode 100644 index 0000000..8c98c69 Binary files /dev/null and b/images/tiles/examples/unnamed (1).png differ diff --git a/images/tiles/examples/unnamed (2).gif b/images/tiles/examples/unnamed (2).gif new file mode 100644 index 0000000..1af7aaf Binary files /dev/null and b/images/tiles/examples/unnamed (2).gif differ diff --git a/images/tiles/examples/unnamed (5).gif b/images/tiles/examples/unnamed (5).gif new file mode 100644 index 0000000..0fdd1ef Binary files /dev/null and b/images/tiles/examples/unnamed (5).gif differ diff --git a/images/tiles/examples/unnamed-dr.gif b/images/tiles/examples/unnamed-dr.gif new file mode 100644 index 0000000..8b95f95 Binary files /dev/null and b/images/tiles/examples/unnamed-dr.gif differ diff --git a/images/tiles/examples/unnamed.gif b/images/tiles/examples/unnamed.gif new file mode 100644 index 0000000..cbc08e1 Binary files /dev/null and b/images/tiles/examples/unnamed.gif differ diff --git a/images/tiles/examples/unnamed.png b/images/tiles/examples/unnamed.png new file mode 100644 index 0000000..37653d5 Binary files /dev/null and b/images/tiles/examples/unnamed.png differ diff --git a/images/tiles/examples/unnamed2.gif b/images/tiles/examples/unnamed2.gif new file mode 100644 index 0000000..4a3458a Binary files /dev/null and b/images/tiles/examples/unnamed2.gif differ diff --git a/images/tiles/examples/wOZu0u.png b/images/tiles/examples/wOZu0u.png new file mode 100644 index 0000000..c227d3f Binary files /dev/null and b/images/tiles/examples/wOZu0u.png differ diff --git a/images/tiles/examples/w_snow.gif b/images/tiles/examples/w_snow.gif new file mode 100644 index 0000000..a9a568d Binary files /dev/null and b/images/tiles/examples/w_snow.gif differ diff --git a/images/tiles/examples/waterfall_MV_preview.gif b/images/tiles/examples/waterfall_MV_preview.gif new file mode 100644 index 0000000..d0a8a5e Binary files /dev/null and b/images/tiles/examples/waterfall_MV_preview.gif differ diff --git a/images/tiles/examples/weather_preview.gif b/images/tiles/examples/weather_preview.gif new file mode 100644 index 0000000..51c175c Binary files /dev/null and b/images/tiles/examples/weather_preview.gif differ diff --git a/images/tiles/examples/westerndoors_opreview.gif b/images/tiles/examples/westerndoors_opreview.gif new file mode 100644 index 0000000..d95eb48 Binary files /dev/null and b/images/tiles/examples/westerndoors_opreview.gif differ diff --git a/images/tiles/examples/westhouse.png b/images/tiles/examples/westhouse.png new file mode 100644 index 0000000..ef88654 Binary files /dev/null and b/images/tiles/examples/westhouse.png differ diff --git a/images/tiles/examples/windmill.gif b/images/tiles/examples/windmill.gif new file mode 100644 index 0000000..3ddfe9e Binary files /dev/null and b/images/tiles/examples/windmill.gif differ diff --git a/images/tiles/examples/wizard.gif b/images/tiles/examples/wizard.gif new file mode 100644 index 0000000..83f6e82 Binary files /dev/null and b/images/tiles/examples/wizard.gif differ diff --git a/images/tiles/examples/workbenches.png b/images/tiles/examples/workbenches.png new file mode 100644 index 0000000..6cde7bf Binary files /dev/null and b/images/tiles/examples/workbenches.png differ diff --git a/images/tiles/examples/y1PgA0.png b/images/tiles/examples/y1PgA0.png new file mode 100644 index 0000000..c4d4920 Binary files /dev/null and b/images/tiles/examples/y1PgA0.png differ diff --git a/images/tiles/examples/yoKpEy.gif b/images/tiles/examples/yoKpEy.gif new file mode 100644 index 0000000..6e4b066 Binary files /dev/null and b/images/tiles/examples/yoKpEy.gif differ diff --git a/images/tiles/examples/zcliffp2.png b/images/tiles/examples/zcliffp2.png new file mode 100644 index 0000000..947d56d Binary files /dev/null and b/images/tiles/examples/zcliffp2.png differ diff --git a/images/tiles/examples/zcliffpreview.png b/images/tiles/examples/zcliffpreview.png new file mode 100644 index 0000000..e23207a Binary files /dev/null and b/images/tiles/examples/zcliffpreview.png differ diff --git a/images/tiles/items/.DS_Store b/images/tiles/items/.DS_Store new file mode 100644 index 0000000..ed1b44d Binary files /dev/null and b/images/tiles/items/.DS_Store differ diff --git a/images/tiles/items/ancient.pxm b/images/tiles/items/ancient.pxm new file mode 100644 index 0000000..134ec32 Binary files /dev/null and b/images/tiles/items/ancient.pxm differ diff --git a/images/tiles/items/cart.pxm b/images/tiles/items/cart.pxm new file mode 100644 index 0000000..3f562a3 Binary files /dev/null and b/images/tiles/items/cart.pxm differ diff --git a/images/tiles/items/chests.png b/images/tiles/items/chests.png new file mode 100755 index 0000000..3743c58 Binary files /dev/null and b/images/tiles/items/chests.png differ diff --git a/images/tiles/items/chests.pxm b/images/tiles/items/chests.pxm new file mode 100644 index 0000000..5337751 Binary files /dev/null and b/images/tiles/items/chests.pxm differ diff --git a/images/tiles/items/chests_8_new_1.png b/images/tiles/items/chests_8_new_1.png new file mode 100644 index 0000000..ccd6e26 Binary files /dev/null and b/images/tiles/items/chests_8_new_1.png differ diff --git a/images/tiles/items/chests_locked_1.png b/images/tiles/items/chests_locked_1.png new file mode 100644 index 0000000..5510c7c Binary files /dev/null and b/images/tiles/items/chests_locked_1.png differ diff --git a/images/tiles/items/custom.png b/images/tiles/items/custom.png new file mode 100644 index 0000000..312bdfb Binary files /dev/null and b/images/tiles/items/custom.png differ diff --git a/images/tiles/items/custom.pxm b/images/tiles/items/custom.pxm new file mode 100644 index 0000000..d113a93 Binary files /dev/null and b/images/tiles/items/custom.pxm differ diff --git a/images/tiles/items/makeup1.png b/images/tiles/items/makeup1.png new file mode 100644 index 0000000..b33c3ca Binary files /dev/null and b/images/tiles/items/makeup1.png differ diff --git a/images/tiles/items/pack_1a.png b/images/tiles/items/pack_1a.png new file mode 100755 index 0000000..98849f2 Binary files /dev/null and b/images/tiles/items/pack_1a.png differ diff --git a/images/tiles/items/pack_1a.pxm b/images/tiles/items/pack_1a.pxm new file mode 100644 index 0000000..ded2e6b Binary files /dev/null and b/images/tiles/items/pack_1a.pxm differ diff --git a/images/tiles/items/pack_1a_original.png b/images/tiles/items/pack_1a_original.png new file mode 100755 index 0000000..c9f8c6a Binary files /dev/null and b/images/tiles/items/pack_1a_original.png differ diff --git a/images/tiles/items/pack_1b.png b/images/tiles/items/pack_1b.png new file mode 100755 index 0000000..0025c47 Binary files /dev/null and b/images/tiles/items/pack_1b.png differ diff --git a/images/tiles/items/pack_20.png b/images/tiles/items/pack_20.png new file mode 100644 index 0000000..2d45268 Binary files /dev/null and b/images/tiles/items/pack_20.png differ diff --git a/images/tiles/items/pack_20.pxm b/images/tiles/items/pack_20.pxm new file mode 100644 index 0000000..dfc01f0 Binary files /dev/null and b/images/tiles/items/pack_20.pxm differ diff --git a/images/tiles/items/pack_20v0.png b/images/tiles/items/pack_20v0.png new file mode 100644 index 0000000..bfb1879 Binary files /dev/null and b/images/tiles/items/pack_20v0.png differ diff --git a/images/tiles/items/pack_20v2.png b/images/tiles/items/pack_20v2.png new file mode 100644 index 0000000..bbd7761 Binary files /dev/null and b/images/tiles/items/pack_20v2.png differ diff --git a/images/tiles/items/pack_20v4.png b/images/tiles/items/pack_20v4.png new file mode 100644 index 0000000..26e632b Binary files /dev/null and b/images/tiles/items/pack_20v4.png differ diff --git a/images/tiles/items/pack_20v5.png b/images/tiles/items/pack_20v5.png new file mode 100644 index 0000000..689ea6e Binary files /dev/null and b/images/tiles/items/pack_20v5.png differ diff --git a/images/tiles/items/pack_20v6.png b/images/tiles/items/pack_20v6.png new file mode 100644 index 0000000..f15168e Binary files /dev/null and b/images/tiles/items/pack_20v6.png differ diff --git a/images/tiles/items/pack_20v7.png b/images/tiles/items/pack_20v7.png new file mode 100644 index 0000000..b28f33f Binary files /dev/null and b/images/tiles/items/pack_20v7.png differ diff --git a/images/tiles/items/pack_20vt.png b/images/tiles/items/pack_20vt.png new file mode 100644 index 0000000..c63085a Binary files /dev/null and b/images/tiles/items/pack_20vt.png differ diff --git a/images/tiles/items/pack_20vt.pxm b/images/tiles/items/pack_20vt.pxm new file mode 100644 index 0000000..83b9e5a Binary files /dev/null and b/images/tiles/items/pack_20vt.pxm differ diff --git a/images/tiles/items/pack_20vt2.png b/images/tiles/items/pack_20vt2.png new file mode 100644 index 0000000..ed45fcb Binary files /dev/null and b/images/tiles/items/pack_20vt2.png differ diff --git a/images/tiles/items/pack_20vt3.png b/images/tiles/items/pack_20vt3.png new file mode 100644 index 0000000..f770130 Binary files /dev/null and b/images/tiles/items/pack_20vt3.png differ diff --git a/images/tiles/items/pack_20vt4.png b/images/tiles/items/pack_20vt4.png new file mode 100644 index 0000000..c48aedc Binary files /dev/null and b/images/tiles/items/pack_20vt4.png differ diff --git a/images/tiles/items/pack_20vt5.png b/images/tiles/items/pack_20vt5.png new file mode 100644 index 0000000..caa8c5d Binary files /dev/null and b/images/tiles/items/pack_20vt5.png differ diff --git a/images/tiles/items/pack_20vt6.png b/images/tiles/items/pack_20vt6.png new file mode 100644 index 0000000..13b56e4 Binary files /dev/null and b/images/tiles/items/pack_20vt6.png differ diff --git a/images/tiles/items/pack_20vt7.png b/images/tiles/items/pack_20vt7.png new file mode 100644 index 0000000..f447135 Binary files /dev/null and b/images/tiles/items/pack_20vt7.png differ diff --git a/images/tiles/items/pack_20vt8.png b/images/tiles/items/pack_20vt8.png new file mode 100644 index 0000000..f9d0dca Binary files /dev/null and b/images/tiles/items/pack_20vt8.png differ diff --git a/images/tiles/items/pumpkin.pxm b/images/tiles/items/pumpkin.pxm new file mode 100644 index 0000000..d9527e8 Binary files /dev/null and b/images/tiles/items/pumpkin.pxm differ diff --git a/images/tiles/items/sealedchests_tf_1.png b/images/tiles/items/sealedchests_tf_1.png new file mode 100644 index 0000000..dfd8d4f Binary files /dev/null and b/images/tiles/items/sealedchests_tf_1.png differ diff --git a/images/tiles/items/skills.png b/images/tiles/items/skills.png new file mode 100644 index 0000000..bbe360c Binary files /dev/null and b/images/tiles/items/skills.png differ diff --git a/images/tiles/items/skills_20.png b/images/tiles/items/skills_20.png new file mode 100644 index 0000000..d3eb6c7 Binary files /dev/null and b/images/tiles/items/skills_20.png differ diff --git a/images/tiles/items/skills_20.pxm b/images/tiles/items/skills_20.pxm new file mode 100644 index 0000000..22c7f3d Binary files /dev/null and b/images/tiles/items/skills_20.pxm differ diff --git a/images/tiles/items/skills_20v2.png b/images/tiles/items/skills_20v2.png new file mode 100644 index 0000000..01e4c0a Binary files /dev/null and b/images/tiles/items/skills_20v2.png differ diff --git a/images/tiles/items/skills_20v3.png b/images/tiles/items/skills_20v3.png new file mode 100644 index 0000000..1d9a8e4 Binary files /dev/null and b/images/tiles/items/skills_20v3.png differ diff --git a/images/tiles/items/skills_20v3.pxm b/images/tiles/items/skills_20v3.pxm new file mode 100644 index 0000000..336faf5 Binary files /dev/null and b/images/tiles/items/skills_20v3.pxm differ diff --git a/images/tiles/items/skills_20v4.png b/images/tiles/items/skills_20v4.png new file mode 100644 index 0000000..7cd9f98 Binary files /dev/null and b/images/tiles/items/skills_20v4.png differ diff --git a/images/tiles/items/skills_20v5.png b/images/tiles/items/skills_20v5.png new file mode 100644 index 0000000..2b62ac9 Binary files /dev/null and b/images/tiles/items/skills_20v5.png differ diff --git a/images/tiles/items/skills_20v6.png b/images/tiles/items/skills_20v6.png new file mode 100644 index 0000000..8e3e5dd Binary files /dev/null and b/images/tiles/items/skills_20v6.png differ diff --git a/images/tiles/items/stands.png b/images/tiles/items/stands.png new file mode 100644 index 0000000..4e22d4b Binary files /dev/null and b/images/tiles/items/stands.png differ diff --git a/images/tiles/items/stands.pxm b/images/tiles/items/stands.pxm new file mode 100644 index 0000000..78faa4b Binary files /dev/null and b/images/tiles/items/stands.pxm differ diff --git a/images/tiles/items/test.png b/images/tiles/items/test.png new file mode 100644 index 0000000..bf55bf6 Binary files /dev/null and b/images/tiles/items/test.png differ diff --git a/images/tiles/map/.DS_Store b/images/tiles/map/.DS_Store new file mode 100644 index 0000000..9ccfb2c Binary files /dev/null and b/images/tiles/map/.DS_Store differ diff --git a/images/tiles/map/TOIMPORT_anvil_sheet_1.png b/images/tiles/map/TOIMPORT_anvil_sheet_1.png new file mode 100644 index 0000000..873801e Binary files /dev/null and b/images/tiles/map/TOIMPORT_anvil_sheet_1.png differ diff --git a/images/tiles/map/TOIMPORT_atlantis.png b/images/tiles/map/TOIMPORT_atlantis.png new file mode 100755 index 0000000..0cd85e4 Binary files /dev/null and b/images/tiles/map/TOIMPORT_atlantis.png differ diff --git a/images/tiles/map/TOIMPORT_autumnbrush_1.png b/images/tiles/map/TOIMPORT_autumnbrush_1.png new file mode 100644 index 0000000..aaecda3 Binary files /dev/null and b/images/tiles/map/TOIMPORT_autumnbrush_1.png differ diff --git a/images/tiles/map/TOIMPORT_b_tileset_1b.png b/images/tiles/map/TOIMPORT_b_tileset_1b.png new file mode 100644 index 0000000..f42a708 Binary files /dev/null and b/images/tiles/map/TOIMPORT_b_tileset_1b.png differ diff --git a/images/tiles/map/TOIMPORT_b_tileset_1b_door.png b/images/tiles/map/TOIMPORT_b_tileset_1b_door.png new file mode 100644 index 0000000..ed49042 Binary files /dev/null and b/images/tiles/map/TOIMPORT_b_tileset_1b_door.png differ diff --git a/images/tiles/map/TOIMPORT_bakery_tiles_1.png b/images/tiles/map/TOIMPORT_bakery_tiles_1.png new file mode 100644 index 0000000..d5a99d0 Binary files /dev/null and b/images/tiles/map/TOIMPORT_bakery_tiles_1.png differ diff --git a/images/tiles/map/TOIMPORT_bathroom_1.png b/images/tiles/map/TOIMPORT_bathroom_1.png new file mode 100644 index 0000000..b03dfd9 Binary files /dev/null and b/images/tiles/map/TOIMPORT_bathroom_1.png differ diff --git a/images/tiles/map/TOIMPORT_bathroom_more.png b/images/tiles/map/TOIMPORT_bathroom_more.png new file mode 100644 index 0000000..e2706f3 Binary files /dev/null and b/images/tiles/map/TOIMPORT_bathroom_more.png differ diff --git a/images/tiles/map/TOIMPORT_bathroom_sinks_char.png b/images/tiles/map/TOIMPORT_bathroom_sinks_char.png new file mode 100644 index 0000000..dfb17c8 Binary files /dev/null and b/images/tiles/map/TOIMPORT_bathroom_sinks_char.png differ diff --git a/images/tiles/map/TOIMPORT_bathroom_tub_char.png b/images/tiles/map/TOIMPORT_bathroom_tub_char.png new file mode 100644 index 0000000..021af73 Binary files /dev/null and b/images/tiles/map/TOIMPORT_bathroom_tub_char.png differ diff --git a/images/tiles/map/TOIMPORT_beartrap_1.png b/images/tiles/map/TOIMPORT_beartrap_1.png new file mode 100644 index 0000000..282c3cf Binary files /dev/null and b/images/tiles/map/TOIMPORT_beartrap_1.png differ diff --git a/images/tiles/map/TOIMPORT_beaverdambridge_tiles_1.png b/images/tiles/map/TOIMPORT_beaverdambridge_tiles_1.png new file mode 100644 index 0000000..23da443 Binary files /dev/null and b/images/tiles/map/TOIMPORT_beaverdambridge_tiles_1.png differ diff --git a/images/tiles/map/TOIMPORT_beehives_1.png b/images/tiles/map/TOIMPORT_beehives_1.png new file mode 100644 index 0000000..b07f055 Binary files /dev/null and b/images/tiles/map/TOIMPORT_beehives_1.png differ diff --git a/images/tiles/map/TOIMPORT_bell.png b/images/tiles/map/TOIMPORT_bell.png new file mode 100644 index 0000000..a37a07c Binary files /dev/null and b/images/tiles/map/TOIMPORT_bell.png differ diff --git a/images/tiles/map/TOIMPORT_berribushes_1.png b/images/tiles/map/TOIMPORT_berribushes_1.png new file mode 100644 index 0000000..6d08f44 Binary files /dev/null and b/images/tiles/map/TOIMPORT_berribushes_1.png differ diff --git a/images/tiles/map/TOIMPORT_bettercaveentry.png b/images/tiles/map/TOIMPORT_bettercaveentry.png new file mode 100644 index 0000000..27ffbd8 Binary files /dev/null and b/images/tiles/map/TOIMPORT_bettercaveentry.png differ diff --git a/images/tiles/map/TOIMPORT_biocaves_full_1.png b/images/tiles/map/TOIMPORT_biocaves_full_1.png new file mode 100644 index 0000000..da0a6a5 Binary files /dev/null and b/images/tiles/map/TOIMPORT_biocaves_full_1.png differ diff --git a/images/tiles/map/TOIMPORT_book_savepoint_1.png b/images/tiles/map/TOIMPORT_book_savepoint_1.png new file mode 100644 index 0000000..e87fbfd Binary files /dev/null and b/images/tiles/map/TOIMPORT_book_savepoint_1.png differ diff --git a/images/tiles/map/TOIMPORT_book_savepoint_blue_1.png b/images/tiles/map/TOIMPORT_book_savepoint_blue_1.png new file mode 100644 index 0000000..79db667 Binary files /dev/null and b/images/tiles/map/TOIMPORT_book_savepoint_blue_1.png differ diff --git a/images/tiles/map/TOIMPORT_book_savepoint_purple_1.png b/images/tiles/map/TOIMPORT_book_savepoint_purple_1.png new file mode 100644 index 0000000..2aac5aa Binary files /dev/null and b/images/tiles/map/TOIMPORT_book_savepoint_purple_1.png differ diff --git a/images/tiles/map/TOIMPORT_bubblebath_tiles_1.png b/images/tiles/map/TOIMPORT_bubblebath_tiles_1.png new file mode 100644 index 0000000..924b0ce Binary files /dev/null and b/images/tiles/map/TOIMPORT_bubblebath_tiles_1.png differ diff --git a/images/tiles/map/TOIMPORT_buzzsaw_horz_1.png b/images/tiles/map/TOIMPORT_buzzsaw_horz_1.png new file mode 100644 index 0000000..43259a6 Binary files /dev/null and b/images/tiles/map/TOIMPORT_buzzsaw_horz_1.png differ diff --git a/images/tiles/map/TOIMPORT_buzzsaw_vert_1.png b/images/tiles/map/TOIMPORT_buzzsaw_vert_1.png new file mode 100644 index 0000000..6d8386a Binary files /dev/null and b/images/tiles/map/TOIMPORT_buzzsaw_vert_1.png differ diff --git a/images/tiles/map/TOIMPORT_cactia_1.png b/images/tiles/map/TOIMPORT_cactia_1.png new file mode 100644 index 0000000..5edfa27 Binary files /dev/null and b/images/tiles/map/TOIMPORT_cactia_1.png differ diff --git a/images/tiles/map/TOIMPORT_cactib_1.png b/images/tiles/map/TOIMPORT_cactib_1.png new file mode 100644 index 0000000..a545ca5 Binary files /dev/null and b/images/tiles/map/TOIMPORT_cactib_1.png differ diff --git a/images/tiles/map/TOIMPORT_castledoor_sheet_1.png b/images/tiles/map/TOIMPORT_castledoor_sheet_1.png new file mode 100644 index 0000000..0aa3077 Binary files /dev/null and b/images/tiles/map/TOIMPORT_castledoor_sheet_1.png differ diff --git a/images/tiles/map/TOIMPORT_chalk-cliffs_1.png b/images/tiles/map/TOIMPORT_chalk-cliffs_1.png new file mode 100644 index 0000000..d6c938f Binary files /dev/null and b/images/tiles/map/TOIMPORT_chalk-cliffs_1.png differ diff --git a/images/tiles/map/TOIMPORT_chess_tf_sheet.png b/images/tiles/map/TOIMPORT_chess_tf_sheet.png new file mode 100644 index 0000000..a88bef7 Binary files /dev/null and b/images/tiles/map/TOIMPORT_chess_tf_sheet.png differ diff --git a/images/tiles/map/TOIMPORT_cliffdrop_addon_1.png b/images/tiles/map/TOIMPORT_cliffdrop_addon_1.png new file mode 100644 index 0000000..1423551 Binary files /dev/null and b/images/tiles/map/TOIMPORT_cliffdrop_addon_1.png differ diff --git a/images/tiles/map/TOIMPORT_coffins.png b/images/tiles/map/TOIMPORT_coffins.png new file mode 100644 index 0000000..e7da651 Binary files /dev/null and b/images/tiles/map/TOIMPORT_coffins.png differ diff --git a/images/tiles/map/TOIMPORT_coolbushes_1.png b/images/tiles/map/TOIMPORT_coolbushes_1.png new file mode 100644 index 0000000..f873803 Binary files /dev/null and b/images/tiles/map/TOIMPORT_coolbushes_1.png differ diff --git a/images/tiles/map/TOIMPORT_crafting-workbench-cartoalch_1.png b/images/tiles/map/TOIMPORT_crafting-workbench-cartoalch_1.png new file mode 100644 index 0000000..cba3655 Binary files /dev/null and b/images/tiles/map/TOIMPORT_crafting-workbench-cartoalch_1.png differ diff --git a/images/tiles/map/TOIMPORT_crafting-workbench-tiles_1.png b/images/tiles/map/TOIMPORT_crafting-workbench-tiles_1.png new file mode 100644 index 0000000..6dacca2 Binary files /dev/null and b/images/tiles/map/TOIMPORT_crafting-workbench-tiles_1.png differ diff --git a/images/tiles/map/TOIMPORT_crystalorb_rm_1_blue.png b/images/tiles/map/TOIMPORT_crystalorb_rm_1_blue.png new file mode 100644 index 0000000..6887392 Binary files /dev/null and b/images/tiles/map/TOIMPORT_crystalorb_rm_1_blue.png differ diff --git a/images/tiles/map/TOIMPORT_crystalshrines_extended_tf_1.png b/images/tiles/map/TOIMPORT_crystalshrines_extended_tf_1.png new file mode 100644 index 0000000..56646ca Binary files /dev/null and b/images/tiles/map/TOIMPORT_crystalshrines_extended_tf_1.png differ diff --git a/images/tiles/map/TOIMPORT_cshrines_1.png b/images/tiles/map/TOIMPORT_cshrines_1.png new file mode 100644 index 0000000..08ee036 Binary files /dev/null and b/images/tiles/map/TOIMPORT_cshrines_1.png differ diff --git a/images/tiles/map/TOIMPORT_deck_addon_1.png b/images/tiles/map/TOIMPORT_deck_addon_1.png new file mode 100644 index 0000000..b8fef41 Binary files /dev/null and b/images/tiles/map/TOIMPORT_deck_addon_1.png differ diff --git a/images/tiles/map/TOIMPORT_doors21_a_1.png b/images/tiles/map/TOIMPORT_doors21_a_1.png new file mode 100644 index 0000000..abdc200 Binary files /dev/null and b/images/tiles/map/TOIMPORT_doors21_a_1.png differ diff --git a/images/tiles/map/TOIMPORT_doors21_b_1.png b/images/tiles/map/TOIMPORT_doors21_b_1.png new file mode 100644 index 0000000..c81425e Binary files /dev/null and b/images/tiles/map/TOIMPORT_doors21_b_1.png differ diff --git a/images/tiles/map/TOIMPORT_farmsoil_updated_1.png b/images/tiles/map/TOIMPORT_farmsoil_updated_1.png new file mode 100644 index 0000000..9016eca Binary files /dev/null and b/images/tiles/map/TOIMPORT_farmsoil_updated_1.png differ diff --git a/images/tiles/map/TOIMPORT_fishmonger.png b/images/tiles/map/TOIMPORT_fishmonger.png new file mode 100644 index 0000000..40baa99 Binary files /dev/null and b/images/tiles/map/TOIMPORT_fishmonger.png differ diff --git a/images/tiles/map/TOIMPORT_forest_snowaddon_1.png b/images/tiles/map/TOIMPORT_forest_snowaddon_1.png new file mode 100644 index 0000000..03e6e7a Binary files /dev/null and b/images/tiles/map/TOIMPORT_forest_snowaddon_1.png differ diff --git a/images/tiles/map/TOIMPORT_fountain_animated.png b/images/tiles/map/TOIMPORT_fountain_animated.png new file mode 100644 index 0000000..d98aee0 Binary files /dev/null and b/images/tiles/map/TOIMPORT_fountain_animated.png differ diff --git a/images/tiles/map/TOIMPORT_fountaintiles1.png b/images/tiles/map/TOIMPORT_fountaintiles1.png new file mode 100644 index 0000000..2572af0 Binary files /dev/null and b/images/tiles/map/TOIMPORT_fountaintiles1.png differ diff --git a/images/tiles/map/TOIMPORT_future.png b/images/tiles/map/TOIMPORT_future.png new file mode 100755 index 0000000..0e6cd37 Binary files /dev/null and b/images/tiles/map/TOIMPORT_future.png differ diff --git a/images/tiles/map/TOIMPORT_gallowsfloor_1.png b/images/tiles/map/TOIMPORT_gallowsfloor_1.png new file mode 100644 index 0000000..534e067 Binary files /dev/null and b/images/tiles/map/TOIMPORT_gallowsfloor_1.png differ diff --git a/images/tiles/map/TOIMPORT_giantworm_1.png b/images/tiles/map/TOIMPORT_giantworm_1.png new file mode 100644 index 0000000..1b351e1 Binary files /dev/null and b/images/tiles/map/TOIMPORT_giantworm_1.png differ diff --git a/images/tiles/map/TOIMPORT_gpoisonwater.png b/images/tiles/map/TOIMPORT_gpoisonwater.png new file mode 100644 index 0000000..aa86bba Binary files /dev/null and b/images/tiles/map/TOIMPORT_gpoisonwater.png differ diff --git a/images/tiles/map/TOIMPORT_grassalpha.png b/images/tiles/map/TOIMPORT_grassalpha.png new file mode 100644 index 0000000..03fa5f4 Binary files /dev/null and b/images/tiles/map/TOIMPORT_grassalpha.png differ diff --git a/images/tiles/map/TOIMPORT_greenhouse_1.png b/images/tiles/map/TOIMPORT_greenhouse_1.png new file mode 100644 index 0000000..57c3bf3 Binary files /dev/null and b/images/tiles/map/TOIMPORT_greenhouse_1.png differ diff --git a/images/tiles/map/TOIMPORT_greenhouseplants_char_1.png b/images/tiles/map/TOIMPORT_greenhouseplants_char_1.png new file mode 100644 index 0000000..30003cc Binary files /dev/null and b/images/tiles/map/TOIMPORT_greenhouseplants_char_1.png differ diff --git a/images/tiles/map/TOIMPORT_gypsywagonsheet_1.png b/images/tiles/map/TOIMPORT_gypsywagonsheet_1.png new file mode 100644 index 0000000..0d34440 Binary files /dev/null and b/images/tiles/map/TOIMPORT_gypsywagonsheet_1.png differ diff --git a/images/tiles/map/TOIMPORT_heartbeat_1.png b/images/tiles/map/TOIMPORT_heartbeat_1.png new file mode 100644 index 0000000..57d9e5e Binary files /dev/null and b/images/tiles/map/TOIMPORT_heartbeat_1.png differ diff --git a/images/tiles/map/TOIMPORT_helltextures_1.png b/images/tiles/map/TOIMPORT_helltextures_1.png new file mode 100644 index 0000000..c039f48 Binary files /dev/null and b/images/tiles/map/TOIMPORT_helltextures_1.png differ diff --git a/images/tiles/map/TOIMPORT_hobbitdoor_1.png b/images/tiles/map/TOIMPORT_hobbitdoor_1.png new file mode 100644 index 0000000..9cbf217 Binary files /dev/null and b/images/tiles/map/TOIMPORT_hobbitdoor_1.png differ diff --git a/images/tiles/map/TOIMPORT_hobbithouseb_1.png b/images/tiles/map/TOIMPORT_hobbithouseb_1.png new file mode 100644 index 0000000..30f45eb Binary files /dev/null and b/images/tiles/map/TOIMPORT_hobbithouseb_1.png differ diff --git a/images/tiles/map/TOIMPORT_hotsprings.png b/images/tiles/map/TOIMPORT_hotsprings.png new file mode 100644 index 0000000..c955314 Binary files /dev/null and b/images/tiles/map/TOIMPORT_hotsprings.png differ diff --git a/images/tiles/map/TOIMPORT_house_roofs_2021_1.png b/images/tiles/map/TOIMPORT_house_roofs_2021_1.png new file mode 100644 index 0000000..07133fa Binary files /dev/null and b/images/tiles/map/TOIMPORT_house_roofs_2021_1.png differ diff --git a/images/tiles/map/TOIMPORT_insidebelly_addon_1.png b/images/tiles/map/TOIMPORT_insidebelly_addon_1.png new file mode 100644 index 0000000..c8d6584 Binary files /dev/null and b/images/tiles/map/TOIMPORT_insidebelly_addon_1.png differ diff --git a/images/tiles/map/TOIMPORT_insidebelly_addon_ext_1.png b/images/tiles/map/TOIMPORT_insidebelly_addon_ext_1.png new file mode 100644 index 0000000..23785c9 Binary files /dev/null and b/images/tiles/map/TOIMPORT_insidebelly_addon_ext_1.png differ diff --git a/images/tiles/map/TOIMPORT_insidebelly_doors_1.png b/images/tiles/map/TOIMPORT_insidebelly_doors_1.png new file mode 100644 index 0000000..d5b03e1 Binary files /dev/null and b/images/tiles/map/TOIMPORT_insidebelly_doors_1.png differ diff --git a/images/tiles/map/TOIMPORT_insidebelly_tentacle_1.png b/images/tiles/map/TOIMPORT_insidebelly_tentacle_1.png new file mode 100644 index 0000000..bd142e7 Binary files /dev/null and b/images/tiles/map/TOIMPORT_insidebelly_tentacle_1.png differ diff --git a/images/tiles/map/TOIMPORT_insidebelly_tileB_1.png b/images/tiles/map/TOIMPORT_insidebelly_tileB_1.png new file mode 100644 index 0000000..e217014 Binary files /dev/null and b/images/tiles/map/TOIMPORT_insidebelly_tileB_1.png differ diff --git a/images/tiles/map/TOIMPORT_interiordiagonalwalls_1.png b/images/tiles/map/TOIMPORT_interiordiagonalwalls_1.png new file mode 100644 index 0000000..0982c6a Binary files /dev/null and b/images/tiles/map/TOIMPORT_interiordiagonalwalls_1.png differ diff --git a/images/tiles/map/TOIMPORT_japanstairs.png b/images/tiles/map/TOIMPORT_japanstairs.png new file mode 100644 index 0000000..0ce7aab Binary files /dev/null and b/images/tiles/map/TOIMPORT_japanstairs.png differ diff --git a/images/tiles/map/TOIMPORT_judgebench_tiles_1.png b/images/tiles/map/TOIMPORT_judgebench_tiles_1.png new file mode 100644 index 0000000..beb00ef Binary files /dev/null and b/images/tiles/map/TOIMPORT_judgebench_tiles_1.png differ diff --git a/images/tiles/map/TOIMPORT_kitchenextra.png b/images/tiles/map/TOIMPORT_kitchenextra.png new file mode 100644 index 0000000..53182ab Binary files /dev/null and b/images/tiles/map/TOIMPORT_kitchenextra.png differ diff --git a/images/tiles/map/TOIMPORT_kitchenfire.png b/images/tiles/map/TOIMPORT_kitchenfire.png new file mode 100644 index 0000000..ce84f30 Binary files /dev/null and b/images/tiles/map/TOIMPORT_kitchenfire.png differ diff --git a/images/tiles/map/TOIMPORT_levers_sheet_1.png b/images/tiles/map/TOIMPORT_levers_sheet_1.png new file mode 100644 index 0000000..2adcd89 Binary files /dev/null and b/images/tiles/map/TOIMPORT_levers_sheet_1.png differ diff --git a/images/tiles/map/TOIMPORT_levers_sheet_exp_1.png b/images/tiles/map/TOIMPORT_levers_sheet_exp_1.png new file mode 100644 index 0000000..14f3fd4 Binary files /dev/null and b/images/tiles/map/TOIMPORT_levers_sheet_exp_1.png differ diff --git a/images/tiles/map/TOIMPORT_mangroves_1.png b/images/tiles/map/TOIMPORT_mangroves_1.png new file mode 100644 index 0000000..d0692fd Binary files /dev/null and b/images/tiles/map/TOIMPORT_mangroves_1.png differ diff --git a/images/tiles/map/TOIMPORT_meatrack_1.png b/images/tiles/map/TOIMPORT_meatrack_1.png new file mode 100644 index 0000000..e337435 Binary files /dev/null and b/images/tiles/map/TOIMPORT_meatrack_1.png differ diff --git a/images/tiles/map/TOIMPORT_mining-ores-tf_1.png b/images/tiles/map/TOIMPORT_mining-ores-tf_1.png new file mode 100644 index 0000000..96bf16e Binary files /dev/null and b/images/tiles/map/TOIMPORT_mining-ores-tf_1.png differ diff --git a/images/tiles/map/TOIMPORT_new-pine-tree-1.png b/images/tiles/map/TOIMPORT_new-pine-tree-1.png new file mode 100644 index 0000000..3a63b41 Binary files /dev/null and b/images/tiles/map/TOIMPORT_new-pine-tree-1.png differ diff --git a/images/tiles/map/TOIMPORT_newflames_1.png b/images/tiles/map/TOIMPORT_newflames_1.png new file mode 100644 index 0000000..1dfd1ea Binary files /dev/null and b/images/tiles/map/TOIMPORT_newflames_1.png differ diff --git a/images/tiles/map/TOIMPORT_newterrain_sheet_1.png b/images/tiles/map/TOIMPORT_newterrain_sheet_1.png new file mode 100644 index 0000000..e4ea532 Binary files /dev/null and b/images/tiles/map/TOIMPORT_newterrain_sheet_1.png differ diff --git a/images/tiles/map/TOIMPORT_oaktrees_1.png b/images/tiles/map/TOIMPORT_oaktrees_1.png new file mode 100644 index 0000000..6a24f2a Binary files /dev/null and b/images/tiles/map/TOIMPORT_oaktrees_1.png differ diff --git a/images/tiles/map/TOIMPORT_poisonwater.png b/images/tiles/map/TOIMPORT_poisonwater.png new file mode 100644 index 0000000..1733c1b Binary files /dev/null and b/images/tiles/map/TOIMPORT_poisonwater.png differ diff --git a/images/tiles/map/TOIMPORT_portcullis1.png b/images/tiles/map/TOIMPORT_portcullis1.png new file mode 100644 index 0000000..ae7836b Binary files /dev/null and b/images/tiles/map/TOIMPORT_portcullis1.png differ diff --git a/images/tiles/map/TOIMPORT_rockwallchar_1.png b/images/tiles/map/TOIMPORT_rockwallchar_1.png new file mode 100644 index 0000000..a80615f Binary files /dev/null and b/images/tiles/map/TOIMPORT_rockwallchar_1.png differ diff --git a/images/tiles/map/TOIMPORT_rockwallsmash_1.png b/images/tiles/map/TOIMPORT_rockwallsmash_1.png new file mode 100644 index 0000000..a0566cb Binary files /dev/null and b/images/tiles/map/TOIMPORT_rockwallsmash_1.png differ diff --git a/images/tiles/map/TOIMPORT_scorch_1.png b/images/tiles/map/TOIMPORT_scorch_1.png new file mode 100644 index 0000000..0009314 Binary files /dev/null and b/images/tiles/map/TOIMPORT_scorch_1.png differ diff --git a/images/tiles/map/TOIMPORT_sealeddoorA_tf_1.png b/images/tiles/map/TOIMPORT_sealeddoorA_tf_1.png new file mode 100644 index 0000000..e2c266c Binary files /dev/null and b/images/tiles/map/TOIMPORT_sealeddoorA_tf_1.png differ diff --git a/images/tiles/map/TOIMPORT_sealeddoorB_tf_1.png b/images/tiles/map/TOIMPORT_sealeddoorB_tf_1.png new file mode 100644 index 0000000..b78c3d7 Binary files /dev/null and b/images/tiles/map/TOIMPORT_sealeddoorB_tf_1.png differ diff --git a/images/tiles/map/TOIMPORT_secret_bookshelf_b_1.png b/images/tiles/map/TOIMPORT_secret_bookshelf_b_1.png new file mode 100644 index 0000000..44f1351 Binary files /dev/null and b/images/tiles/map/TOIMPORT_secret_bookshelf_b_1.png differ diff --git a/images/tiles/map/TOIMPORT_secretcave.png b/images/tiles/map/TOIMPORT_secretcave.png new file mode 100644 index 0000000..5f776fa Binary files /dev/null and b/images/tiles/map/TOIMPORT_secretcave.png differ diff --git a/images/tiles/map/TOIMPORT_sewers.png b/images/tiles/map/TOIMPORT_sewers.png new file mode 100644 index 0000000..e6c249e Binary files /dev/null and b/images/tiles/map/TOIMPORT_sewers.png differ diff --git a/images/tiles/map/TOIMPORT_skullhead_doors_1.png b/images/tiles/map/TOIMPORT_skullhead_doors_1.png new file mode 100644 index 0000000..962263a Binary files /dev/null and b/images/tiles/map/TOIMPORT_skullhead_doors_1.png differ diff --git a/images/tiles/map/TOIMPORT_skullhead_tiles_1.png b/images/tiles/map/TOIMPORT_skullhead_tiles_1.png new file mode 100644 index 0000000..80cbd7b Binary files /dev/null and b/images/tiles/map/TOIMPORT_skullhead_tiles_1.png differ diff --git a/images/tiles/map/TOIMPORT_spikes.png b/images/tiles/map/TOIMPORT_spikes.png new file mode 100644 index 0000000..79761b2 Binary files /dev/null and b/images/tiles/map/TOIMPORT_spikes.png differ diff --git a/images/tiles/map/TOIMPORT_stairs_1.png b/images/tiles/map/TOIMPORT_stairs_1.png new file mode 100644 index 0000000..4ac0d16 Binary files /dev/null and b/images/tiles/map/TOIMPORT_stairs_1.png differ diff --git a/images/tiles/map/TOIMPORT_stairs_1_up.png b/images/tiles/map/TOIMPORT_stairs_1_up.png new file mode 100644 index 0000000..182e95f Binary files /dev/null and b/images/tiles/map/TOIMPORT_stairs_1_up.png differ diff --git a/images/tiles/map/TOIMPORT_stawrooftiles_1.png b/images/tiles/map/TOIMPORT_stawrooftiles_1.png new file mode 100644 index 0000000..4b13bbb Binary files /dev/null and b/images/tiles/map/TOIMPORT_stawrooftiles_1.png differ diff --git a/images/tiles/map/TOIMPORT_swordits_1.png b/images/tiles/map/TOIMPORT_swordits_1.png new file mode 100644 index 0000000..f9a28db Binary files /dev/null and b/images/tiles/map/TOIMPORT_swordits_1.png differ diff --git a/images/tiles/map/TOIMPORT_tf_ff_doors_1.png b/images/tiles/map/TOIMPORT_tf_ff_doors_1.png new file mode 100644 index 0000000..56784b3 Binary files /dev/null and b/images/tiles/map/TOIMPORT_tf_ff_doors_1.png differ diff --git a/images/tiles/map/TOIMPORT_tf_insidebelly_doors_1.png b/images/tiles/map/TOIMPORT_tf_insidebelly_doors_1.png new file mode 100644 index 0000000..8a58918 Binary files /dev/null and b/images/tiles/map/TOIMPORT_tf_insidebelly_doors_1.png differ diff --git a/images/tiles/map/TOIMPORT_tf_insidebelly_fullsheet.png b/images/tiles/map/TOIMPORT_tf_insidebelly_fullsheet.png new file mode 100644 index 0000000..402d547 Binary files /dev/null and b/images/tiles/map/TOIMPORT_tf_insidebelly_fullsheet.png differ diff --git a/images/tiles/map/TOIMPORT_tf_japan_master.png b/images/tiles/map/TOIMPORT_tf_japan_master.png new file mode 100644 index 0000000..356b9f9 Binary files /dev/null and b/images/tiles/map/TOIMPORT_tf_japan_master.png differ diff --git a/images/tiles/map/TOIMPORT_tf_newsnesforest_tilesheet1.png b/images/tiles/map/TOIMPORT_tf_newsnesforest_tilesheet1.png new file mode 100644 index 0000000..325d3dc Binary files /dev/null and b/images/tiles/map/TOIMPORT_tf_newsnesforest_tilesheet1.png differ diff --git a/images/tiles/map/TOIMPORT_train-updated_bsheet_1.png b/images/tiles/map/TOIMPORT_train-updated_bsheet_1.png new file mode 100644 index 0000000..eef1103 Binary files /dev/null and b/images/tiles/map/TOIMPORT_train-updated_bsheet_1.png differ diff --git a/images/tiles/map/TOIMPORT_train_sheet_1.png b/images/tiles/map/TOIMPORT_train_sheet_1.png new file mode 100644 index 0000000..83553c8 Binary files /dev/null and b/images/tiles/map/TOIMPORT_train_sheet_1.png differ diff --git a/images/tiles/map/TOIMPORT_traintrax1.png b/images/tiles/map/TOIMPORT_traintrax1.png new file mode 100644 index 0000000..7a2e9d3 Binary files /dev/null and b/images/tiles/map/TOIMPORT_traintrax1.png differ diff --git a/images/tiles/map/TOIMPORT_tree_growth_stages_1.png b/images/tiles/map/TOIMPORT_tree_growth_stages_1.png new file mode 100644 index 0000000..fb472ab Binary files /dev/null and b/images/tiles/map/TOIMPORT_tree_growth_stages_1.png differ diff --git a/images/tiles/map/TOIMPORT_wagonshseeta_1.png b/images/tiles/map/TOIMPORT_wagonshseeta_1.png new file mode 100644 index 0000000..5d48135 Binary files /dev/null and b/images/tiles/map/TOIMPORT_wagonshseeta_1.png differ diff --git a/images/tiles/map/TOIMPORT_westerndoorsB_1.png b/images/tiles/map/TOIMPORT_westerndoorsB_1.png new file mode 100644 index 0000000..fd53047 Binary files /dev/null and b/images/tiles/map/TOIMPORT_westerndoorsB_1.png differ diff --git a/images/tiles/map/TOIMPORT_westerndoors_1.png b/images/tiles/map/TOIMPORT_westerndoors_1.png new file mode 100644 index 0000000..74988c6 Binary files /dev/null and b/images/tiles/map/TOIMPORT_westerndoors_1.png differ diff --git a/images/tiles/map/TOIMPORT_westerntown_sheetA_1.png b/images/tiles/map/TOIMPORT_westerntown_sheetA_1.png new file mode 100644 index 0000000..9e9de84 Binary files /dev/null and b/images/tiles/map/TOIMPORT_westerntown_sheetA_1.png differ diff --git a/images/tiles/map/TOIMPORT_westerntown_sheetB_1.png b/images/tiles/map/TOIMPORT_westerntown_sheetB_1.png new file mode 100644 index 0000000..34ec324 Binary files /dev/null and b/images/tiles/map/TOIMPORT_westerntown_sheetB_1.png differ diff --git a/images/tiles/map/TOIMPORT_westerntown_sheetC_1.png b/images/tiles/map/TOIMPORT_westerntown_sheetC_1.png new file mode 100644 index 0000000..0652777 Binary files /dev/null and b/images/tiles/map/TOIMPORT_westerntown_sheetC_1.png differ diff --git a/images/tiles/map/TOIMPORT_westerntowntiles_1.png b/images/tiles/map/TOIMPORT_westerntowntiles_1.png new file mode 100644 index 0000000..b669cb6 Binary files /dev/null and b/images/tiles/map/TOIMPORT_westerntowntiles_1.png differ diff --git a/images/tiles/map/TOIMPORT_windmill_mechanism_tiles_1.png b/images/tiles/map/TOIMPORT_windmill_mechanism_tiles_1.png new file mode 100644 index 0000000..d67bfa6 Binary files /dev/null and b/images/tiles/map/TOIMPORT_windmill_mechanism_tiles_1.png differ diff --git a/images/tiles/map/TOIMPORT_wring_tf_1.png b/images/tiles/map/TOIMPORT_wring_tf_1.png new file mode 100644 index 0000000..076e5e9 Binary files /dev/null and b/images/tiles/map/TOIMPORT_wring_tf_1.png differ diff --git a/images/tiles/map/TOIMPORT_xmastoytiles.png b/images/tiles/map/TOIMPORT_xmastoytiles.png new file mode 100644 index 0000000..da170c4 Binary files /dev/null and b/images/tiles/map/TOIMPORT_xmastoytiles.png differ diff --git a/images/tiles/map/TOIMPORT_zcliffs_1.png b/images/tiles/map/TOIMPORT_zcliffs_1.png new file mode 100644 index 0000000..84dec59 Binary files /dev/null and b/images/tiles/map/TOIMPORT_zcliffs_1.png differ diff --git a/images/tiles/map/TOIMPORT_zcliffs_addon_1.png b/images/tiles/map/TOIMPORT_zcliffs_addon_1.png new file mode 100644 index 0000000..c3d373c Binary files /dev/null and b/images/tiles/map/TOIMPORT_zcliffs_addon_1.png differ diff --git a/images/tiles/map/TOMIMPORT_flyingcarpet-extratiles-1.png b/images/tiles/map/TOMIMPORT_flyingcarpet-extratiles-1.png new file mode 100644 index 0000000..a523a81 Binary files /dev/null and b/images/tiles/map/TOMIMPORT_flyingcarpet-extratiles-1.png differ diff --git a/images/tiles/map/TOMPORT_crossroad_signs_1.png b/images/tiles/map/TOMPORT_crossroad_signs_1.png new file mode 100644 index 0000000..a68b27f Binary files /dev/null and b/images/tiles/map/TOMPORT_crossroad_signs_1.png differ diff --git a/images/tiles/map/ancient_device.pxm b/images/tiles/map/ancient_device.pxm new file mode 100644 index 0000000..93201a7 Binary files /dev/null and b/images/tiles/map/ancient_device.pxm differ diff --git a/images/tiles/map/ashlands.png b/images/tiles/map/ashlands.png new file mode 100644 index 0000000..1661c32 Binary files /dev/null and b/images/tiles/map/ashlands.png differ diff --git a/images/tiles/map/ashlands.pxm b/images/tiles/map/ashlands.pxm new file mode 100644 index 0000000..cf8a3d6 Binary files /dev/null and b/images/tiles/map/ashlands.pxm differ diff --git a/images/tiles/map/beach.png b/images/tiles/map/beach.png new file mode 100755 index 0000000..c9f6d52 Binary files /dev/null and b/images/tiles/map/beach.png differ diff --git a/images/tiles/map/beach_v2.png b/images/tiles/map/beach_v2.png new file mode 100644 index 0000000..5b35247 Binary files /dev/null and b/images/tiles/map/beach_v2.png differ diff --git a/images/tiles/map/beach_v2.pxm b/images/tiles/map/beach_v2.pxm new file mode 100644 index 0000000..01b750e Binary files /dev/null and b/images/tiles/map/beach_v2.pxm differ diff --git a/images/tiles/map/castle.png b/images/tiles/map/castle.png new file mode 100755 index 0000000..b2962d8 Binary files /dev/null and b/images/tiles/map/castle.png differ diff --git a/images/tiles/map/castle.pxm b/images/tiles/map/castle.pxm new file mode 100644 index 0000000..85163ff Binary files /dev/null and b/images/tiles/map/castle.pxm differ diff --git a/images/tiles/map/custom.png b/images/tiles/map/custom.png new file mode 100644 index 0000000..2138221 Binary files /dev/null and b/images/tiles/map/custom.png differ diff --git a/images/tiles/map/custom.pxm b/images/tiles/map/custom.pxm new file mode 100644 index 0000000..ef73f76 Binary files /dev/null and b/images/tiles/map/custom.pxm differ diff --git a/images/tiles/map/custom2.png b/images/tiles/map/custom2.png new file mode 100644 index 0000000..118e0f6 Binary files /dev/null and b/images/tiles/map/custom2.png differ diff --git a/images/tiles/map/custom2.pxm b/images/tiles/map/custom2.pxm new file mode 100644 index 0000000..54b49b0 Binary files /dev/null and b/images/tiles/map/custom2.pxm differ diff --git a/images/tiles/map/custom_a.png b/images/tiles/map/custom_a.png new file mode 100644 index 0000000..6b91d37 Binary files /dev/null and b/images/tiles/map/custom_a.png differ diff --git a/images/tiles/map/custom_a.pxm b/images/tiles/map/custom_a.pxm new file mode 100644 index 0000000..9782eea Binary files /dev/null and b/images/tiles/map/custom_a.pxm differ diff --git a/images/tiles/map/dark_dimension.png b/images/tiles/map/dark_dimension.png new file mode 100644 index 0000000..bd232a9 Binary files /dev/null and b/images/tiles/map/dark_dimension.png differ diff --git a/images/tiles/map/doors.png b/images/tiles/map/doors.png new file mode 100755 index 0000000..0792a4b Binary files /dev/null and b/images/tiles/map/doors.png differ diff --git a/images/tiles/map/dungeon.png b/images/tiles/map/dungeon.png new file mode 100755 index 0000000..9367e40 Binary files /dev/null and b/images/tiles/map/dungeon.png differ diff --git a/images/tiles/map/dungeon.pxm b/images/tiles/map/dungeon.pxm new file mode 100644 index 0000000..f4f5ad9 Binary files /dev/null and b/images/tiles/map/dungeon.pxm differ diff --git a/images/tiles/map/experiments.pxm b/images/tiles/map/experiments.pxm new file mode 100644 index 0000000..9cb4a89 Binary files /dev/null and b/images/tiles/map/experiments.pxm differ diff --git a/images/tiles/map/fort.png b/images/tiles/map/fort.png new file mode 100755 index 0000000..23501f9 Binary files /dev/null and b/images/tiles/map/fort.png differ diff --git a/images/tiles/map/fort.pxm b/images/tiles/map/fort.pxm new file mode 100644 index 0000000..cd1d753 Binary files /dev/null and b/images/tiles/map/fort.pxm differ diff --git a/images/tiles/map/house.png b/images/tiles/map/house.png new file mode 100755 index 0000000..73b7e21 Binary files /dev/null and b/images/tiles/map/house.png differ diff --git a/images/tiles/map/house.pxm b/images/tiles/map/house.pxm new file mode 100644 index 0000000..672f5cb Binary files /dev/null and b/images/tiles/map/house.pxm differ diff --git a/images/tiles/map/inside.png b/images/tiles/map/inside.png new file mode 100644 index 0000000..8b5528e Binary files /dev/null and b/images/tiles/map/inside.png differ diff --git a/images/tiles/map/inside.pxm b/images/tiles/map/inside.pxm new file mode 100644 index 0000000..6279143 Binary files /dev/null and b/images/tiles/map/inside.pxm differ diff --git a/images/tiles/map/inside_updates.png b/images/tiles/map/inside_updates.png new file mode 100755 index 0000000..ff0d634 Binary files /dev/null and b/images/tiles/map/inside_updates.png differ diff --git a/images/tiles/map/jungle.png b/images/tiles/map/jungle.png new file mode 100755 index 0000000..a7d25a3 Binary files /dev/null and b/images/tiles/map/jungle.png differ diff --git a/images/tiles/map/jungle.pxm b/images/tiles/map/jungle.pxm new file mode 100644 index 0000000..212ab74 Binary files /dev/null and b/images/tiles/map/jungle.pxm differ diff --git a/images/tiles/map/lights.png b/images/tiles/map/lights.png new file mode 100644 index 0000000..c8e29f2 Binary files /dev/null and b/images/tiles/map/lights.png differ diff --git a/images/tiles/map/lights.pxm b/images/tiles/map/lights.pxm new file mode 100644 index 0000000..f5469ab Binary files /dev/null and b/images/tiles/map/lights.pxm differ diff --git a/images/tiles/map/new.png b/images/tiles/map/new.png new file mode 100644 index 0000000..7b29d8a Binary files /dev/null and b/images/tiles/map/new.png differ diff --git a/images/tiles/map/new.pxm b/images/tiles/map/new.pxm new file mode 100644 index 0000000..8286584 Binary files /dev/null and b/images/tiles/map/new.pxm differ diff --git a/images/tiles/map/original_inside.png b/images/tiles/map/original_inside.png new file mode 100755 index 0000000..52de10a Binary files /dev/null and b/images/tiles/map/original_inside.png differ diff --git a/images/tiles/map/original_outside.png b/images/tiles/map/original_outside.png new file mode 100755 index 0000000..c34b8dc Binary files /dev/null and b/images/tiles/map/original_outside.png differ diff --git a/images/tiles/map/outside.png b/images/tiles/map/outside.png new file mode 100644 index 0000000..49283bf Binary files /dev/null and b/images/tiles/map/outside.png differ diff --git a/images/tiles/map/outside.pxm b/images/tiles/map/outside.pxm new file mode 100644 index 0000000..e4394df Binary files /dev/null and b/images/tiles/map/outside.pxm differ diff --git a/images/tiles/map/puzzle.png b/images/tiles/map/puzzle.png new file mode 100755 index 0000000..3a8ab8e Binary files /dev/null and b/images/tiles/map/puzzle.png differ diff --git a/images/tiles/map/puzzle.pxm b/images/tiles/map/puzzle.pxm new file mode 100644 index 0000000..6e35195 Binary files /dev/null and b/images/tiles/map/puzzle.pxm differ diff --git a/images/tiles/map/resort_default.png b/images/tiles/map/resort_default.png new file mode 100644 index 0000000..d15bc12 Binary files /dev/null and b/images/tiles/map/resort_default.png differ diff --git a/images/tiles/map/resort_default.pxm b/images/tiles/map/resort_default.pxm new file mode 100644 index 0000000..ea23d5a Binary files /dev/null and b/images/tiles/map/resort_default.pxm differ diff --git a/images/tiles/map/resort_default_a.png b/images/tiles/map/resort_default_a.png new file mode 100644 index 0000000..2ec0218 Binary files /dev/null and b/images/tiles/map/resort_default_a.png differ diff --git a/images/tiles/map/resort_default_a.pxm b/images/tiles/map/resort_default_a.pxm new file mode 100644 index 0000000..17eab49 Binary files /dev/null and b/images/tiles/map/resort_default_a.pxm differ diff --git a/images/tiles/map/ruins.png b/images/tiles/map/ruins.png new file mode 100644 index 0000000..cdeca35 Binary files /dev/null and b/images/tiles/map/ruins.png differ diff --git a/images/tiles/map/ruins.pxm b/images/tiles/map/ruins.pxm new file mode 100644 index 0000000..a766ecc Binary files /dev/null and b/images/tiles/map/ruins.pxm differ diff --git a/images/tiles/map/secret_bookshelf_1.png b/images/tiles/map/secret_bookshelf_1.png new file mode 100644 index 0000000..96cae35 Binary files /dev/null and b/images/tiles/map/secret_bookshelf_1.png differ diff --git a/images/tiles/map/ship.png b/images/tiles/map/ship.png new file mode 100755 index 0000000..da07532 Binary files /dev/null and b/images/tiles/map/ship.png differ diff --git a/images/tiles/map/ship_test.png b/images/tiles/map/ship_test.png new file mode 100644 index 0000000..52bfb45 Binary files /dev/null and b/images/tiles/map/ship_test.png differ diff --git a/images/tiles/map/tree.png b/images/tiles/map/tree.png new file mode 100755 index 0000000..9cd093d Binary files /dev/null and b/images/tiles/map/tree.png differ diff --git a/images/tiles/map/water.png b/images/tiles/map/water.png new file mode 100755 index 0000000..f3e22ce Binary files /dev/null and b/images/tiles/map/water.png differ diff --git a/images/tiles/map/water_updated.png b/images/tiles/map/water_updated.png new file mode 100644 index 0000000..6f6d895 Binary files /dev/null and b/images/tiles/map/water_updated.png differ diff --git a/images/tiles/map/water_updated.pxm b/images/tiles/map/water_updated.pxm new file mode 100644 index 0000000..ff9f79f Binary files /dev/null and b/images/tiles/map/water_updated.pxm differ diff --git a/images/tiles/map/winter.png b/images/tiles/map/winter.png new file mode 100644 index 0000000..64c6a42 Binary files /dev/null and b/images/tiles/map/winter.png differ diff --git a/images/tiles/map/winter.pxm b/images/tiles/map/winter.pxm new file mode 100644 index 0000000..2c85346 Binary files /dev/null and b/images/tiles/map/winter.pxm differ diff --git a/images/tiles/map/world.png b/images/tiles/map/world.png new file mode 100755 index 0000000..387b982 Binary files /dev/null and b/images/tiles/map/world.png differ diff --git a/images/tiles/monsters/.DS_Store b/images/tiles/monsters/.DS_Store new file mode 100644 index 0000000..1e39417 Binary files /dev/null and b/images/tiles/monsters/.DS_Store differ diff --git a/images/tiles/monsters/Dragold.png b/images/tiles/monsters/Dragold.png new file mode 100644 index 0000000..1a33eb6 Binary files /dev/null and b/images/tiles/monsters/Dragold.png differ diff --git a/images/tiles/monsters/alien_new_1.png b/images/tiles/monsters/alien_new_1.png new file mode 100644 index 0000000..911d0e2 Binary files /dev/null and b/images/tiles/monsters/alien_new_1.png differ diff --git a/images/tiles/monsters/animals1.png b/images/tiles/monsters/animals1.png new file mode 100755 index 0000000..b7cf575 Binary files /dev/null and b/images/tiles/monsters/animals1.png differ diff --git a/images/tiles/monsters/animals2.png b/images/tiles/monsters/animals2.png new file mode 100755 index 0000000..dd39c3b Binary files /dev/null and b/images/tiles/monsters/animals2.png differ diff --git a/images/tiles/monsters/animals2/bee.png b/images/tiles/monsters/animals2/bee.png new file mode 100644 index 0000000..dd7003a Binary files /dev/null and b/images/tiles/monsters/animals2/bee.png differ diff --git a/images/tiles/monsters/animals2/birds_8sheet.png b/images/tiles/monsters/animals2/birds_8sheet.png new file mode 100644 index 0000000..00f36c8 Binary files /dev/null and b/images/tiles/monsters/animals2/birds_8sheet.png differ diff --git a/images/tiles/monsters/animals2/bison.png b/images/tiles/monsters/animals2/bison.png new file mode 100644 index 0000000..e093ca6 Binary files /dev/null and b/images/tiles/monsters/animals2/bison.png differ diff --git a/images/tiles/monsters/animals2/buffalo.png b/images/tiles/monsters/animals2/buffalo.png new file mode 100644 index 0000000..25228cb Binary files /dev/null and b/images/tiles/monsters/animals2/buffalo.png differ diff --git a/images/tiles/monsters/animals2/bugs_8sheet.png b/images/tiles/monsters/animals2/bugs_8sheet.png new file mode 100644 index 0000000..ba0934d Binary files /dev/null and b/images/tiles/monsters/animals2/bugs_8sheet.png differ diff --git a/images/tiles/monsters/animals2/camel_a.png b/images/tiles/monsters/animals2/camel_a.png new file mode 100644 index 0000000..87b9bcb Binary files /dev/null and b/images/tiles/monsters/animals2/camel_a.png differ diff --git a/images/tiles/monsters/animals2/camel_a_pack.png b/images/tiles/monsters/animals2/camel_a_pack.png new file mode 100644 index 0000000..cff89b6 Binary files /dev/null and b/images/tiles/monsters/animals2/camel_a_pack.png differ diff --git a/images/tiles/monsters/animals2/camel_b.png b/images/tiles/monsters/animals2/camel_b.png new file mode 100644 index 0000000..8f44fba Binary files /dev/null and b/images/tiles/monsters/animals2/camel_b.png differ diff --git a/images/tiles/monsters/animals2/camel_b_pack.png b/images/tiles/monsters/animals2/camel_b_pack.png new file mode 100644 index 0000000..3acaa05 Binary files /dev/null and b/images/tiles/monsters/animals2/camel_b_pack.png differ diff --git a/images/tiles/monsters/animals2/crab.png b/images/tiles/monsters/animals2/crab.png new file mode 100644 index 0000000..b1938a1 Binary files /dev/null and b/images/tiles/monsters/animals2/crab.png differ diff --git a/images/tiles/monsters/animals2/crocodile.png b/images/tiles/monsters/animals2/crocodile.png new file mode 100644 index 0000000..b39d8c8 Binary files /dev/null and b/images/tiles/monsters/animals2/crocodile.png differ diff --git a/images/tiles/monsters/animals2/crocodile_water.png b/images/tiles/monsters/animals2/crocodile_water.png new file mode 100644 index 0000000..573696a Binary files /dev/null and b/images/tiles/monsters/animals2/crocodile_water.png differ diff --git a/images/tiles/monsters/animals2/elephant.png b/images/tiles/monsters/animals2/elephant.png new file mode 100644 index 0000000..9a01995 Binary files /dev/null and b/images/tiles/monsters/animals2/elephant.png differ diff --git a/images/tiles/monsters/animals2/elephant_baby.png b/images/tiles/monsters/animals2/elephant_baby.png new file mode 100644 index 0000000..519f25d Binary files /dev/null and b/images/tiles/monsters/animals2/elephant_baby.png differ diff --git a/images/tiles/monsters/animals2/fish_8sheet.png b/images/tiles/monsters/animals2/fish_8sheet.png new file mode 100644 index 0000000..15e9a63 Binary files /dev/null and b/images/tiles/monsters/animals2/fish_8sheet.png differ diff --git a/images/tiles/monsters/animals2/frog.png b/images/tiles/monsters/animals2/frog.png new file mode 100644 index 0000000..3e3b096 Binary files /dev/null and b/images/tiles/monsters/animals2/frog.png differ diff --git a/images/tiles/monsters/animals2/gorilla.png b/images/tiles/monsters/animals2/gorilla.png new file mode 100644 index 0000000..e4f8f13 Binary files /dev/null and b/images/tiles/monsters/animals2/gorilla.png differ diff --git a/images/tiles/monsters/animals2/hippo.png b/images/tiles/monsters/animals2/hippo.png new file mode 100644 index 0000000..88183ef Binary files /dev/null and b/images/tiles/monsters/animals2/hippo.png differ diff --git a/images/tiles/monsters/animals2/hippo_water.png b/images/tiles/monsters/animals2/hippo_water.png new file mode 100644 index 0000000..9d9f48c Binary files /dev/null and b/images/tiles/monsters/animals2/hippo_water.png differ diff --git a/images/tiles/monsters/animals2/horseshoe_crab.png b/images/tiles/monsters/animals2/horseshoe_crab.png new file mode 100644 index 0000000..8018c55 Binary files /dev/null and b/images/tiles/monsters/animals2/horseshoe_crab.png differ diff --git a/images/tiles/monsters/animals2/kangaroo.png b/images/tiles/monsters/animals2/kangaroo.png new file mode 100644 index 0000000..3280c5b Binary files /dev/null and b/images/tiles/monsters/animals2/kangaroo.png differ diff --git a/images/tiles/monsters/animals2/lion.png b/images/tiles/monsters/animals2/lion.png new file mode 100644 index 0000000..b924bb1 Binary files /dev/null and b/images/tiles/monsters/animals2/lion.png differ diff --git a/images/tiles/monsters/animals2/lion_cub.png b/images/tiles/monsters/animals2/lion_cub.png new file mode 100644 index 0000000..e7beca1 Binary files /dev/null and b/images/tiles/monsters/animals2/lion_cub.png differ diff --git a/images/tiles/monsters/animals2/lioness.png b/images/tiles/monsters/animals2/lioness.png new file mode 100644 index 0000000..0fc0c95 Binary files /dev/null and b/images/tiles/monsters/animals2/lioness.png differ diff --git a/images/tiles/monsters/animals2/lizard.png b/images/tiles/monsters/animals2/lizard.png new file mode 100644 index 0000000..0cee25d Binary files /dev/null and b/images/tiles/monsters/animals2/lizard.png differ diff --git a/images/tiles/monsters/animals2/mammoth.png b/images/tiles/monsters/animals2/mammoth.png new file mode 100644 index 0000000..2bd46a7 Binary files /dev/null and b/images/tiles/monsters/animals2/mammoth.png differ diff --git a/images/tiles/monsters/animals2/monkey_8sheet.png b/images/tiles/monsters/animals2/monkey_8sheet.png new file mode 100644 index 0000000..4e95a13 Binary files /dev/null and b/images/tiles/monsters/animals2/monkey_8sheet.png differ diff --git a/images/tiles/monsters/animals2/owl_fly.png b/images/tiles/monsters/animals2/owl_fly.png new file mode 100644 index 0000000..2d2158e Binary files /dev/null and b/images/tiles/monsters/animals2/owl_fly.png differ diff --git a/images/tiles/monsters/animals2/owl_sit.png b/images/tiles/monsters/animals2/owl_sit.png new file mode 100644 index 0000000..54a4dd2 Binary files /dev/null and b/images/tiles/monsters/animals2/owl_sit.png differ diff --git a/images/tiles/monsters/animals2/panther.png b/images/tiles/monsters/animals2/panther.png new file mode 100644 index 0000000..668dc15 Binary files /dev/null and b/images/tiles/monsters/animals2/panther.png differ diff --git a/images/tiles/monsters/animals2/panther_cub.png b/images/tiles/monsters/animals2/panther_cub.png new file mode 100644 index 0000000..04d4365 Binary files /dev/null and b/images/tiles/monsters/animals2/panther_cub.png differ diff --git a/images/tiles/monsters/animals2/parrot_fly.png b/images/tiles/monsters/animals2/parrot_fly.png new file mode 100644 index 0000000..6512048 Binary files /dev/null and b/images/tiles/monsters/animals2/parrot_fly.png differ diff --git a/images/tiles/monsters/animals2/parrot_sit.png b/images/tiles/monsters/animals2/parrot_sit.png new file mode 100644 index 0000000..9d7a96a Binary files /dev/null and b/images/tiles/monsters/animals2/parrot_sit.png differ diff --git a/images/tiles/monsters/animals2/penguin.png b/images/tiles/monsters/animals2/penguin.png new file mode 100644 index 0000000..04fdfa0 Binary files /dev/null and b/images/tiles/monsters/animals2/penguin.png differ diff --git a/images/tiles/monsters/animals2/penguin_baby.png b/images/tiles/monsters/animals2/penguin_baby.png new file mode 100644 index 0000000..972244d Binary files /dev/null and b/images/tiles/monsters/animals2/penguin_baby.png differ diff --git a/images/tiles/monsters/animals2/pufferfish_big.png b/images/tiles/monsters/animals2/pufferfish_big.png new file mode 100644 index 0000000..b77c77f Binary files /dev/null and b/images/tiles/monsters/animals2/pufferfish_big.png differ diff --git a/images/tiles/monsters/animals2/pufferfish_small.png b/images/tiles/monsters/animals2/pufferfish_small.png new file mode 100644 index 0000000..08f8d04 Binary files /dev/null and b/images/tiles/monsters/animals2/pufferfish_small.png differ diff --git a/images/tiles/monsters/animals2/ray.png b/images/tiles/monsters/animals2/ray.png new file mode 100644 index 0000000..5c9c7ba Binary files /dev/null and b/images/tiles/monsters/animals2/ray.png differ diff --git a/images/tiles/monsters/animals2/rhinoceros.png b/images/tiles/monsters/animals2/rhinoceros.png new file mode 100644 index 0000000..130ba3e Binary files /dev/null and b/images/tiles/monsters/animals2/rhinoceros.png differ diff --git a/images/tiles/monsters/animals2/sabretooth.png b/images/tiles/monsters/animals2/sabretooth.png new file mode 100644 index 0000000..b0c5891 Binary files /dev/null and b/images/tiles/monsters/animals2/sabretooth.png differ diff --git a/images/tiles/monsters/animals2/seal.png b/images/tiles/monsters/animals2/seal.png new file mode 100644 index 0000000..30b9a5c Binary files /dev/null and b/images/tiles/monsters/animals2/seal.png differ diff --git a/images/tiles/monsters/animals2/seaturtle.png b/images/tiles/monsters/animals2/seaturtle.png new file mode 100644 index 0000000..3fb0d31 Binary files /dev/null and b/images/tiles/monsters/animals2/seaturtle.png differ diff --git a/images/tiles/monsters/animals2/shark_fin_blue_1.png b/images/tiles/monsters/animals2/shark_fin_blue_1.png new file mode 100644 index 0000000..8aa3a60 Binary files /dev/null and b/images/tiles/monsters/animals2/shark_fin_blue_1.png differ diff --git a/images/tiles/monsters/animals2/shark_fin_brown_1.png b/images/tiles/monsters/animals2/shark_fin_brown_1.png new file mode 100644 index 0000000..2285a58 Binary files /dev/null and b/images/tiles/monsters/animals2/shark_fin_brown_1.png differ diff --git a/images/tiles/monsters/animals2/shark_finshadow_blue_1.png b/images/tiles/monsters/animals2/shark_finshadow_blue_1.png new file mode 100644 index 0000000..0f7a419 Binary files /dev/null and b/images/tiles/monsters/animals2/shark_finshadow_blue_1.png differ diff --git a/images/tiles/monsters/animals2/shark_finshadow_brown_1.png b/images/tiles/monsters/animals2/shark_finshadow_brown_1.png new file mode 100644 index 0000000..ed5adc0 Binary files /dev/null and b/images/tiles/monsters/animals2/shark_finshadow_brown_1.png differ diff --git a/images/tiles/monsters/animals2/shark_full_blue_1.png b/images/tiles/monsters/animals2/shark_full_blue_1.png new file mode 100644 index 0000000..62995e9 Binary files /dev/null and b/images/tiles/monsters/animals2/shark_full_blue_1.png differ diff --git a/images/tiles/monsters/animals2/shark_full_brown_1.png b/images/tiles/monsters/animals2/shark_full_brown_1.png new file mode 100644 index 0000000..873e5fb Binary files /dev/null and b/images/tiles/monsters/animals2/shark_full_brown_1.png differ diff --git a/images/tiles/monsters/animals2/swordfish.png b/images/tiles/monsters/animals2/swordfish.png new file mode 100644 index 0000000..7a3f5cc Binary files /dev/null and b/images/tiles/monsters/animals2/swordfish.png differ diff --git a/images/tiles/monsters/animals2/tiger.png b/images/tiles/monsters/animals2/tiger.png new file mode 100644 index 0000000..dbabee1 Binary files /dev/null and b/images/tiles/monsters/animals2/tiger.png differ diff --git a/images/tiles/monsters/animals2/tiger_cub.png b/images/tiles/monsters/animals2/tiger_cub.png new file mode 100644 index 0000000..58c2b42 Binary files /dev/null and b/images/tiles/monsters/animals2/tiger_cub.png differ diff --git a/images/tiles/monsters/animals2/toucan_fly.png b/images/tiles/monsters/animals2/toucan_fly.png new file mode 100644 index 0000000..bb8b0fb Binary files /dev/null and b/images/tiles/monsters/animals2/toucan_fly.png differ diff --git a/images/tiles/monsters/animals2/toucan_sit.png b/images/tiles/monsters/animals2/toucan_sit.png new file mode 100644 index 0000000..4761c0f Binary files /dev/null and b/images/tiles/monsters/animals2/toucan_sit.png differ diff --git a/images/tiles/monsters/animals2/turtle.png b/images/tiles/monsters/animals2/turtle.png new file mode 100644 index 0000000..e01157c Binary files /dev/null and b/images/tiles/monsters/animals2/turtle.png differ diff --git a/images/tiles/monsters/animals2/vulture_fly.png b/images/tiles/monsters/animals2/vulture_fly.png new file mode 100644 index 0000000..bc1bd79 Binary files /dev/null and b/images/tiles/monsters/animals2/vulture_fly.png differ diff --git a/images/tiles/monsters/animals2/vulture_sit.png b/images/tiles/monsters/animals2/vulture_sit.png new file mode 100644 index 0000000..540b1e3 Binary files /dev/null and b/images/tiles/monsters/animals2/vulture_sit.png differ diff --git a/images/tiles/monsters/animals2/walrus.png b/images/tiles/monsters/animals2/walrus.png new file mode 100644 index 0000000..6622c28 Binary files /dev/null and b/images/tiles/monsters/animals2/walrus.png differ diff --git a/images/tiles/monsters/animals2/zebra.png b/images/tiles/monsters/animals2/zebra.png new file mode 100644 index 0000000..652c71b Binary files /dev/null and b/images/tiles/monsters/animals2/zebra.png differ diff --git a/images/tiles/monsters/animals3.png b/images/tiles/monsters/animals3.png new file mode 100755 index 0000000..478a3b1 Binary files /dev/null and b/images/tiles/monsters/animals3.png differ diff --git a/images/tiles/monsters/animals4.png b/images/tiles/monsters/animals4.png new file mode 100755 index 0000000..116414b Binary files /dev/null and b/images/tiles/monsters/animals4.png differ diff --git a/images/tiles/monsters/animals5.png b/images/tiles/monsters/animals5.png new file mode 100755 index 0000000..3bcc5d9 Binary files /dev/null and b/images/tiles/monsters/animals5.png differ diff --git a/images/tiles/monsters/beaver_single_1.png b/images/tiles/monsters/beaver_single_1.png new file mode 100644 index 0000000..c3baab2 Binary files /dev/null and b/images/tiles/monsters/beaver_single_1.png differ diff --git a/images/tiles/monsters/beaver_swim_1.png b/images/tiles/monsters/beaver_swim_1.png new file mode 100644 index 0000000..1693b07 Binary files /dev/null and b/images/tiles/monsters/beaver_swim_1.png differ diff --git a/images/tiles/monsters/beaver_swim_wood_1.png b/images/tiles/monsters/beaver_swim_wood_1.png new file mode 100644 index 0000000..fda48e9 Binary files /dev/null and b/images/tiles/monsters/beaver_swim_wood_1.png differ diff --git a/images/tiles/monsters/bigskullA_1.png b/images/tiles/monsters/bigskullA_1.png new file mode 100644 index 0000000..5dfd6dd Binary files /dev/null and b/images/tiles/monsters/bigskullA_1.png differ diff --git a/images/tiles/monsters/bigskullB_1.png b/images/tiles/monsters/bigskullB_1.png new file mode 100644 index 0000000..28eed23 Binary files /dev/null and b/images/tiles/monsters/bigskullB_1.png differ diff --git a/images/tiles/monsters/bigskullC_1.png b/images/tiles/monsters/bigskullC_1.png new file mode 100644 index 0000000..15f431b Binary files /dev/null and b/images/tiles/monsters/bigskullC_1.png differ diff --git a/images/tiles/monsters/bigskullD_1.png b/images/tiles/monsters/bigskullD_1.png new file mode 100644 index 0000000..8989422 Binary files /dev/null and b/images/tiles/monsters/bigskullD_1.png differ diff --git a/images/tiles/monsters/bigturkey1.png b/images/tiles/monsters/bigturkey1.png new file mode 100644 index 0000000..6620891 Binary files /dev/null and b/images/tiles/monsters/bigturkey1.png differ diff --git a/images/tiles/monsters/birds1.png b/images/tiles/monsters/birds1.png new file mode 100755 index 0000000..a780a78 Binary files /dev/null and b/images/tiles/monsters/birds1.png differ diff --git a/images/tiles/monsters/birds1_modded.png b/images/tiles/monsters/birds1_modded.png new file mode 100644 index 0000000..cf004c4 Binary files /dev/null and b/images/tiles/monsters/birds1_modded.png differ diff --git a/images/tiles/monsters/birds1_modded.pxm b/images/tiles/monsters/birds1_modded.pxm new file mode 100644 index 0000000..88dce0f Binary files /dev/null and b/images/tiles/monsters/birds1_modded.pxm differ diff --git a/images/tiles/monsters/birds2.png b/images/tiles/monsters/birds2.png new file mode 100755 index 0000000..8160595 Binary files /dev/null and b/images/tiles/monsters/birds2.png differ diff --git a/images/tiles/monsters/blackscorpion.png b/images/tiles/monsters/blackscorpion.png new file mode 100644 index 0000000..4ab0b72 Binary files /dev/null and b/images/tiles/monsters/blackscorpion.png differ diff --git a/images/tiles/monsters/blue_demon.png b/images/tiles/monsters/blue_demon.png new file mode 100644 index 0000000..9decd87 Binary files /dev/null and b/images/tiles/monsters/blue_demon.png differ diff --git a/images/tiles/monsters/bugz_1.png b/images/tiles/monsters/bugz_1.png new file mode 100644 index 0000000..ba0934d Binary files /dev/null and b/images/tiles/monsters/bugz_1.png differ diff --git a/images/tiles/monsters/camel2_single_1.png b/images/tiles/monsters/camel2_single_1.png new file mode 100644 index 0000000..8f44fba Binary files /dev/null and b/images/tiles/monsters/camel2_single_1.png differ diff --git a/images/tiles/monsters/camel_single_1.png b/images/tiles/monsters/camel_single_1.png new file mode 100644 index 0000000..87b9bcb Binary files /dev/null and b/images/tiles/monsters/camel_single_1.png differ diff --git a/images/tiles/monsters/cbee.png b/images/tiles/monsters/cbee.png new file mode 100644 index 0000000..dd7003a Binary files /dev/null and b/images/tiles/monsters/cbee.png differ diff --git a/images/tiles/monsters/cellmonsters_1.png b/images/tiles/monsters/cellmonsters_1.png new file mode 100644 index 0000000..ce82732 Binary files /dev/null and b/images/tiles/monsters/cellmonsters_1.png differ diff --git a/images/tiles/monsters/chocobos_saddle_1.png b/images/tiles/monsters/chocobos_saddle_1.png new file mode 100644 index 0000000..61487b1 Binary files /dev/null and b/images/tiles/monsters/chocobos_saddle_1.png differ diff --git a/images/tiles/monsters/chungus1.png b/images/tiles/monsters/chungus1.png new file mode 100644 index 0000000..e2c268e Binary files /dev/null and b/images/tiles/monsters/chungus1.png differ diff --git a/images/tiles/monsters/cloudballs_1.png b/images/tiles/monsters/cloudballs_1.png new file mode 100644 index 0000000..af6acf0 Binary files /dev/null and b/images/tiles/monsters/cloudballs_1.png differ diff --git a/images/tiles/monsters/coboldProto.png b/images/tiles/monsters/coboldProto.png new file mode 100644 index 0000000..547287f Binary files /dev/null and b/images/tiles/monsters/coboldProto.png differ diff --git a/images/tiles/monsters/creatures1.png b/images/tiles/monsters/creatures1.png new file mode 100644 index 0000000..49bda59 Binary files /dev/null and b/images/tiles/monsters/creatures1.png differ diff --git a/images/tiles/monsters/creatures2.png b/images/tiles/monsters/creatures2.png new file mode 100644 index 0000000..c7c0a39 Binary files /dev/null and b/images/tiles/monsters/creatures2.png differ diff --git a/images/tiles/monsters/creatures3.png b/images/tiles/monsters/creatures3.png new file mode 100644 index 0000000..90e8f64 Binary files /dev/null and b/images/tiles/monsters/creatures3.png differ diff --git a/images/tiles/monsters/custom1.png b/images/tiles/monsters/custom1.png new file mode 100644 index 0000000..3b96d98 Binary files /dev/null and b/images/tiles/monsters/custom1.png differ diff --git a/images/tiles/monsters/custom1.pxm b/images/tiles/monsters/custom1.pxm new file mode 100644 index 0000000..e05f612 Binary files /dev/null and b/images/tiles/monsters/custom1.pxm differ diff --git a/images/tiles/monsters/custom2.png b/images/tiles/monsters/custom2.png new file mode 100644 index 0000000..205a8e9 Binary files /dev/null and b/images/tiles/monsters/custom2.png differ diff --git a/images/tiles/monsters/custom2.pxm b/images/tiles/monsters/custom2.pxm new file mode 100644 index 0000000..072b5f2 Binary files /dev/null and b/images/tiles/monsters/custom2.pxm differ diff --git a/images/tiles/monsters/deep_sea_king.png b/images/tiles/monsters/deep_sea_king.png new file mode 100644 index 0000000..894f866 Binary files /dev/null and b/images/tiles/monsters/deep_sea_king.png differ diff --git a/images/tiles/monsters/demonking_fullfix.png b/images/tiles/monsters/demonking_fullfix.png new file mode 100644 index 0000000..56662ba Binary files /dev/null and b/images/tiles/monsters/demonking_fullfix.png differ diff --git a/images/tiles/monsters/demonkingt2.png b/images/tiles/monsters/demonkingt2.png new file mode 100644 index 0000000..de03f87 Binary files /dev/null and b/images/tiles/monsters/demonkingt2.png differ diff --git a/images/tiles/monsters/dotd_skeletonsheet_1.png b/images/tiles/monsters/dotd_skeletonsheet_1.png new file mode 100644 index 0000000..0d57ce2 Binary files /dev/null and b/images/tiles/monsters/dotd_skeletonsheet_1.png differ diff --git a/images/tiles/monsters/dragon_big_green.png b/images/tiles/monsters/dragon_big_green.png new file mode 100644 index 0000000..2386c2f Binary files /dev/null and b/images/tiles/monsters/dragon_big_green.png differ diff --git a/images/tiles/monsters/dragon_big_red.png b/images/tiles/monsters/dragon_big_red.png new file mode 100644 index 0000000..3df3335 Binary files /dev/null and b/images/tiles/monsters/dragon_big_red.png differ diff --git a/images/tiles/monsters/dryad_green_1.png b/images/tiles/monsters/dryad_green_1.png new file mode 100644 index 0000000..28f32ae Binary files /dev/null and b/images/tiles/monsters/dryad_green_1.png differ diff --git a/images/tiles/monsters/elemental.png b/images/tiles/monsters/elemental.png new file mode 100755 index 0000000..bbaaee8 Binary files /dev/null and b/images/tiles/monsters/elemental.png differ diff --git a/images/tiles/monsters/elfa_1.png b/images/tiles/monsters/elfa_1.png new file mode 100644 index 0000000..8141ca2 Binary files /dev/null and b/images/tiles/monsters/elfa_1.png differ diff --git a/images/tiles/monsters/elfb_1.png b/images/tiles/monsters/elfb_1.png new file mode 100644 index 0000000..e15e2c2 Binary files /dev/null and b/images/tiles/monsters/elfb_1.png differ diff --git a/images/tiles/monsters/fairies.png b/images/tiles/monsters/fairies.png new file mode 100644 index 0000000..096ad39 Binary files /dev/null and b/images/tiles/monsters/fairies.png differ diff --git a/images/tiles/monsters/femaledjinn_1.png b/images/tiles/monsters/femaledjinn_1.png new file mode 100644 index 0000000..3339e34 Binary files /dev/null and b/images/tiles/monsters/femaledjinn_1.png differ diff --git a/images/tiles/monsters/fishes.png b/images/tiles/monsters/fishes.png new file mode 100644 index 0000000..15e9a63 Binary files /dev/null and b/images/tiles/monsters/fishes.png differ diff --git a/images/tiles/monsters/flyingcarpet-big-1.png b/images/tiles/monsters/flyingcarpet-big-1.png new file mode 100644 index 0000000..ef0d842 Binary files /dev/null and b/images/tiles/monsters/flyingcarpet-big-1.png differ diff --git a/images/tiles/monsters/flyingcarpet-world-1.png b/images/tiles/monsters/flyingcarpet-world-1.png new file mode 100644 index 0000000..cc2aa7f Binary files /dev/null and b/images/tiles/monsters/flyingcarpet-world-1.png differ diff --git a/images/tiles/monsters/forestboysB_tfcolor.png b/images/tiles/monsters/forestboysB_tfcolor.png new file mode 100644 index 0000000..66e4942 Binary files /dev/null and b/images/tiles/monsters/forestboysB_tfcolor.png differ diff --git a/images/tiles/monsters/forestboys_tfcolor.png b/images/tiles/monsters/forestboys_tfcolor.png new file mode 100644 index 0000000..bc7d326 Binary files /dev/null and b/images/tiles/monsters/forestboys_tfcolor.png differ diff --git a/images/tiles/monsters/frankenstein.png b/images/tiles/monsters/frankenstein.png new file mode 100644 index 0000000..c1c958a Binary files /dev/null and b/images/tiles/monsters/frankenstein.png differ diff --git a/images/tiles/monsters/frost_golem.png b/images/tiles/monsters/frost_golem.png new file mode 100644 index 0000000..abf586c Binary files /dev/null and b/images/tiles/monsters/frost_golem.png differ diff --git a/images/tiles/monsters/gargoyle_1.png b/images/tiles/monsters/gargoyle_1.png new file mode 100644 index 0000000..7853e7a Binary files /dev/null and b/images/tiles/monsters/gargoyle_1.png differ diff --git a/images/tiles/monsters/geniea_1.png b/images/tiles/monsters/geniea_1.png new file mode 100644 index 0000000..75be1d8 Binary files /dev/null and b/images/tiles/monsters/geniea_1.png differ diff --git a/images/tiles/monsters/genieb_1.png b/images/tiles/monsters/genieb_1.png new file mode 100644 index 0000000..e765807 Binary files /dev/null and b/images/tiles/monsters/genieb_1.png differ diff --git a/images/tiles/monsters/giantspider_1.png b/images/tiles/monsters/giantspider_1.png new file mode 100644 index 0000000..58ba3a9 Binary files /dev/null and b/images/tiles/monsters/giantspider_1.png differ diff --git a/images/tiles/monsters/giantspider_shadow_1.png b/images/tiles/monsters/giantspider_shadow_1.png new file mode 100644 index 0000000..bc54d86 Binary files /dev/null and b/images/tiles/monsters/giantspider_shadow_1.png differ diff --git a/images/tiles/monsters/giantsquirrel_single_brown_1.png b/images/tiles/monsters/giantsquirrel_single_brown_1.png new file mode 100644 index 0000000..a073f33 Binary files /dev/null and b/images/tiles/monsters/giantsquirrel_single_brown_1.png differ diff --git a/images/tiles/monsters/giantsquirrel_single_gray_1.png b/images/tiles/monsters/giantsquirrel_single_gray_1.png new file mode 100644 index 0000000..aa8f8dd Binary files /dev/null and b/images/tiles/monsters/giantsquirrel_single_gray_1.png differ diff --git a/images/tiles/monsters/giantworm_1.png b/images/tiles/monsters/giantworm_1.png new file mode 100644 index 0000000..1b351e1 Binary files /dev/null and b/images/tiles/monsters/giantworm_1.png differ diff --git a/images/tiles/monsters/gknight.png b/images/tiles/monsters/gknight.png new file mode 100644 index 0000000..0ddade2 Binary files /dev/null and b/images/tiles/monsters/gknight.png differ diff --git a/images/tiles/monsters/gnomea_reg.png b/images/tiles/monsters/gnomea_reg.png new file mode 100644 index 0000000..998bebc Binary files /dev/null and b/images/tiles/monsters/gnomea_reg.png differ diff --git a/images/tiles/monsters/gnomeb_reg.png b/images/tiles/monsters/gnomeb_reg.png new file mode 100644 index 0000000..4e02333 Binary files /dev/null and b/images/tiles/monsters/gnomeb_reg.png differ diff --git a/images/tiles/monsters/goblinkinga_1.png b/images/tiles/monsters/goblinkinga_1.png new file mode 100644 index 0000000..2536434 Binary files /dev/null and b/images/tiles/monsters/goblinkinga_1.png differ diff --git a/images/tiles/monsters/goblinkingb.png b/images/tiles/monsters/goblinkingb.png new file mode 100644 index 0000000..f9b679c Binary files /dev/null and b/images/tiles/monsters/goblinkingb.png differ diff --git a/images/tiles/monsters/goblinos.png b/images/tiles/monsters/goblinos.png new file mode 100644 index 0000000..d01fa62 Binary files /dev/null and b/images/tiles/monsters/goblinos.png differ diff --git a/images/tiles/monsters/goos.png b/images/tiles/monsters/goos.png new file mode 100644 index 0000000..07cf675 Binary files /dev/null and b/images/tiles/monsters/goos.png differ diff --git a/images/tiles/monsters/green.png b/images/tiles/monsters/green.png new file mode 100644 index 0000000..762000f Binary files /dev/null and b/images/tiles/monsters/green.png differ diff --git a/images/tiles/monsters/grinch.png b/images/tiles/monsters/grinch.png new file mode 100644 index 0000000..c7281d8 Binary files /dev/null and b/images/tiles/monsters/grinch.png differ diff --git a/images/tiles/monsters/gryphon_1.png b/images/tiles/monsters/gryphon_1.png new file mode 100644 index 0000000..e889f29 Binary files /dev/null and b/images/tiles/monsters/gryphon_1.png differ diff --git a/images/tiles/monsters/gryphon_baby_1.png b/images/tiles/monsters/gryphon_baby_1.png new file mode 100644 index 0000000..2f81be3 Binary files /dev/null and b/images/tiles/monsters/gryphon_baby_1.png differ diff --git a/images/tiles/monsters/gwasp_1.png b/images/tiles/monsters/gwasp_1.png new file mode 100644 index 0000000..e3c1951 Binary files /dev/null and b/images/tiles/monsters/gwasp_1.png differ diff --git a/images/tiles/monsters/harpy_a_1.png b/images/tiles/monsters/harpy_a_1.png new file mode 100644 index 0000000..7237168 Binary files /dev/null and b/images/tiles/monsters/harpy_a_1.png differ diff --git a/images/tiles/monsters/harpy_a_fly_1.png b/images/tiles/monsters/harpy_a_fly_1.png new file mode 100644 index 0000000..2e88a4d Binary files /dev/null and b/images/tiles/monsters/harpy_a_fly_1.png differ diff --git a/images/tiles/monsters/harpy_b_1.png b/images/tiles/monsters/harpy_b_1.png new file mode 100644 index 0000000..cd40997 Binary files /dev/null and b/images/tiles/monsters/harpy_b_1.png differ diff --git a/images/tiles/monsters/harpy_b_fly_1.png b/images/tiles/monsters/harpy_b_fly_1.png new file mode 100644 index 0000000..ed1c72c Binary files /dev/null and b/images/tiles/monsters/harpy_b_fly_1.png differ diff --git a/images/tiles/monsters/horse1.png b/images/tiles/monsters/horse1.png new file mode 100755 index 0000000..b766d6f Binary files /dev/null and b/images/tiles/monsters/horse1.png differ diff --git a/images/tiles/monsters/hydra_3_1.png b/images/tiles/monsters/hydra_3_1.png new file mode 100644 index 0000000..f088734 Binary files /dev/null and b/images/tiles/monsters/hydra_3_1.png differ diff --git a/images/tiles/monsters/hydra_5_1.png b/images/tiles/monsters/hydra_5_1.png new file mode 100644 index 0000000..c2ebf1b Binary files /dev/null and b/images/tiles/monsters/hydra_5_1.png differ diff --git a/images/tiles/monsters/iceGolem.png b/images/tiles/monsters/iceGolem.png new file mode 100644 index 0000000..40ea99c Binary files /dev/null and b/images/tiles/monsters/iceGolem.png differ diff --git a/images/tiles/monsters/jackalopes_1.png b/images/tiles/monsters/jackalopes_1.png new file mode 100644 index 0000000..e970864 Binary files /dev/null and b/images/tiles/monsters/jackalopes_1.png differ diff --git a/images/tiles/monsters/jacko_a_1.png b/images/tiles/monsters/jacko_a_1.png new file mode 100644 index 0000000..a9ea987 Binary files /dev/null and b/images/tiles/monsters/jacko_a_1.png differ diff --git a/images/tiles/monsters/jrpumpkins.png b/images/tiles/monsters/jrpumpkins.png new file mode 100644 index 0000000..68d7004 Binary files /dev/null and b/images/tiles/monsters/jrpumpkins.png differ diff --git a/images/tiles/monsters/json.png b/images/tiles/monsters/json.png new file mode 100644 index 0000000..1d3defc Binary files /dev/null and b/images/tiles/monsters/json.png differ diff --git a/images/tiles/monsters/kappa_single_walk_1.png b/images/tiles/monsters/kappa_single_walk_1.png new file mode 100644 index 0000000..2092f90 Binary files /dev/null and b/images/tiles/monsters/kappa_single_walk_1.png differ diff --git a/images/tiles/monsters/kitsune.png b/images/tiles/monsters/kitsune.png new file mode 100644 index 0000000..b8a9bf0 Binary files /dev/null and b/images/tiles/monsters/kitsune.png differ diff --git a/images/tiles/monsters/liger_x.png b/images/tiles/monsters/liger_x.png new file mode 100644 index 0000000..3cf1363 Binary files /dev/null and b/images/tiles/monsters/liger_x.png differ diff --git a/images/tiles/monsters/lion_1.png b/images/tiles/monsters/lion_1.png new file mode 100644 index 0000000..9ae1725 Binary files /dev/null and b/images/tiles/monsters/lion_1.png differ diff --git a/images/tiles/monsters/lioness_1.png b/images/tiles/monsters/lioness_1.png new file mode 100644 index 0000000..a3f7da1 Binary files /dev/null and b/images/tiles/monsters/lioness_1.png differ diff --git a/images/tiles/monsters/mage.png b/images/tiles/monsters/mage.png new file mode 100755 index 0000000..ecaf63c Binary files /dev/null and b/images/tiles/monsters/mage.png differ diff --git a/images/tiles/monsters/mecha_gnome.png b/images/tiles/monsters/mecha_gnome.png new file mode 100644 index 0000000..3b79d4f Binary files /dev/null and b/images/tiles/monsters/mecha_gnome.png differ diff --git a/images/tiles/monsters/mecha_gnome.pxm b/images/tiles/monsters/mecha_gnome.pxm new file mode 100644 index 0000000..9295d25 Binary files /dev/null and b/images/tiles/monsters/mecha_gnome.pxm differ diff --git a/images/tiles/monsters/mghoulA_1.png b/images/tiles/monsters/mghoulA_1.png new file mode 100644 index 0000000..66b83f6 Binary files /dev/null and b/images/tiles/monsters/mghoulA_1.png differ diff --git a/images/tiles/monsters/mghoulB_1.png b/images/tiles/monsters/mghoulB_1.png new file mode 100644 index 0000000..0895a16 Binary files /dev/null and b/images/tiles/monsters/mghoulB_1.png differ diff --git a/images/tiles/monsters/mondinos_1.png b/images/tiles/monsters/mondinos_1.png new file mode 100644 index 0000000..3ec5def Binary files /dev/null and b/images/tiles/monsters/mondinos_1.png differ diff --git a/images/tiles/monsters/mondinos_saddle_1.png b/images/tiles/monsters/mondinos_saddle_1.png new file mode 100644 index 0000000..2959aba Binary files /dev/null and b/images/tiles/monsters/mondinos_saddle_1.png differ diff --git a/images/tiles/monsters/monke_1.png b/images/tiles/monsters/monke_1.png new file mode 100644 index 0000000..ab2a767 Binary files /dev/null and b/images/tiles/monsters/monke_1.png differ diff --git a/images/tiles/monsters/monke_upd_1.png b/images/tiles/monsters/monke_upd_1.png new file mode 100644 index 0000000..4e95a13 Binary files /dev/null and b/images/tiles/monsters/monke_upd_1.png differ diff --git a/images/tiles/monsters/monster1.png b/images/tiles/monsters/monster1.png new file mode 100755 index 0000000..3dd67cb Binary files /dev/null and b/images/tiles/monsters/monster1.png differ diff --git a/images/tiles/monsters/monster2.png b/images/tiles/monsters/monster2.png new file mode 100755 index 0000000..6ca0b37 Binary files /dev/null and b/images/tiles/monsters/monster2.png differ diff --git a/images/tiles/monsters/monster2.pxm b/images/tiles/monsters/monster2.pxm new file mode 100644 index 0000000..a8f9a55 Binary files /dev/null and b/images/tiles/monsters/monster2.pxm differ diff --git a/images/tiles/monsters/monster2c.png b/images/tiles/monsters/monster2c.png new file mode 100644 index 0000000..013deea Binary files /dev/null and b/images/tiles/monsters/monster2c.png differ diff --git a/images/tiles/monsters/monster3.png b/images/tiles/monsters/monster3.png new file mode 100755 index 0000000..3e8ac39 Binary files /dev/null and b/images/tiles/monsters/monster3.png differ diff --git a/images/tiles/monsters/monster3.pxm b/images/tiles/monsters/monster3.pxm new file mode 100644 index 0000000..f2b05e7 Binary files /dev/null and b/images/tiles/monsters/monster3.pxm differ diff --git a/images/tiles/monsters/monster3c.png b/images/tiles/monsters/monster3c.png new file mode 100644 index 0000000..ceff424 Binary files /dev/null and b/images/tiles/monsters/monster3c.png differ diff --git a/images/tiles/monsters/monster4.png b/images/tiles/monsters/monster4.png new file mode 100755 index 0000000..cbdee9a Binary files /dev/null and b/images/tiles/monsters/monster4.png differ diff --git a/images/tiles/monsters/monster_bird1.png b/images/tiles/monsters/monster_bird1.png new file mode 100755 index 0000000..9083c77 Binary files /dev/null and b/images/tiles/monsters/monster_bird1.png differ diff --git a/images/tiles/monsters/monster_bird2.png b/images/tiles/monsters/monster_bird2.png new file mode 100755 index 0000000..77f8944 Binary files /dev/null and b/images/tiles/monsters/monster_bird2.png differ diff --git a/images/tiles/monsters/monster_bird3.png b/images/tiles/monsters/monster_bird3.png new file mode 100755 index 0000000..59085c7 Binary files /dev/null and b/images/tiles/monsters/monster_bird3.png differ diff --git a/images/tiles/monsters/monster_boar.png b/images/tiles/monsters/monster_boar.png new file mode 100755 index 0000000..48a2674 Binary files /dev/null and b/images/tiles/monsters/monster_boar.png differ diff --git a/images/tiles/monsters/monster_cacto.png b/images/tiles/monsters/monster_cacto.png new file mode 100755 index 0000000..f886794 Binary files /dev/null and b/images/tiles/monsters/monster_cacto.png differ diff --git a/images/tiles/monsters/monster_dknight1.png b/images/tiles/monsters/monster_dknight1.png new file mode 100755 index 0000000..d56d559 Binary files /dev/null and b/images/tiles/monsters/monster_dknight1.png differ diff --git a/images/tiles/monsters/monster_dknight2.png b/images/tiles/monsters/monster_dknight2.png new file mode 100755 index 0000000..b591acd Binary files /dev/null and b/images/tiles/monsters/monster_dknight2.png differ diff --git a/images/tiles/monsters/monster_elk.png b/images/tiles/monsters/monster_elk.png new file mode 100755 index 0000000..41decb7 Binary files /dev/null and b/images/tiles/monsters/monster_elk.png differ diff --git a/images/tiles/monsters/monster_golem1.png b/images/tiles/monsters/monster_golem1.png new file mode 100755 index 0000000..3ab9e4c Binary files /dev/null and b/images/tiles/monsters/monster_golem1.png differ diff --git a/images/tiles/monsters/monster_golem2.png b/images/tiles/monsters/monster_golem2.png new file mode 100755 index 0000000..c19eb48 Binary files /dev/null and b/images/tiles/monsters/monster_golem2.png differ diff --git a/images/tiles/monsters/monster_lich.png b/images/tiles/monsters/monster_lich.png new file mode 100755 index 0000000..d3d7fa7 Binary files /dev/null and b/images/tiles/monsters/monster_lich.png differ diff --git a/images/tiles/monsters/monster_lizardman1.png b/images/tiles/monsters/monster_lizardman1.png new file mode 100755 index 0000000..2d7a6d5 Binary files /dev/null and b/images/tiles/monsters/monster_lizardman1.png differ diff --git a/images/tiles/monsters/monster_lizardman2.png b/images/tiles/monsters/monster_lizardman2.png new file mode 100755 index 0000000..739b02a Binary files /dev/null and b/images/tiles/monsters/monster_lizardman2.png differ diff --git a/images/tiles/monsters/monster_minotaur.png b/images/tiles/monsters/monster_minotaur.png new file mode 100755 index 0000000..3002138 Binary files /dev/null and b/images/tiles/monsters/monster_minotaur.png differ diff --git a/images/tiles/monsters/monster_phoenix.png b/images/tiles/monsters/monster_phoenix.png new file mode 100755 index 0000000..a59ad93 Binary files /dev/null and b/images/tiles/monsters/monster_phoenix.png differ diff --git a/images/tiles/monsters/monster_raptor1.png b/images/tiles/monsters/monster_raptor1.png new file mode 100755 index 0000000..099aa9b Binary files /dev/null and b/images/tiles/monsters/monster_raptor1.png differ diff --git a/images/tiles/monsters/monster_raptor2.png b/images/tiles/monsters/monster_raptor2.png new file mode 100755 index 0000000..eefc036 Binary files /dev/null and b/images/tiles/monsters/monster_raptor2.png differ diff --git a/images/tiles/monsters/monster_treant.png b/images/tiles/monsters/monster_treant.png new file mode 100755 index 0000000..b8a14af Binary files /dev/null and b/images/tiles/monsters/monster_treant.png differ diff --git a/images/tiles/monsters/monster_wolf1.png b/images/tiles/monsters/monster_wolf1.png new file mode 100755 index 0000000..111f4a7 Binary files /dev/null and b/images/tiles/monsters/monster_wolf1.png differ diff --git a/images/tiles/monsters/monster_wolf2.png b/images/tiles/monsters/monster_wolf2.png new file mode 100755 index 0000000..e1a89cb Binary files /dev/null and b/images/tiles/monsters/monster_wolf2.png differ diff --git a/images/tiles/monsters/monsterc1.png b/images/tiles/monsters/monsterc1.png new file mode 100644 index 0000000..c2fb6a6 Binary files /dev/null and b/images/tiles/monsters/monsterc1.png differ diff --git a/images/tiles/monsters/monsterc2.png b/images/tiles/monsters/monsterc2.png new file mode 100644 index 0000000..5aad98a Binary files /dev/null and b/images/tiles/monsters/monsterc2.png differ diff --git a/images/tiles/monsters/monsterc3.png b/images/tiles/monsters/monsterc3.png new file mode 100644 index 0000000..b608861 Binary files /dev/null and b/images/tiles/monsters/monsterc3.png differ diff --git a/images/tiles/monsters/monsterc4.png b/images/tiles/monsters/monsterc4.png new file mode 100644 index 0000000..9122ee9 Binary files /dev/null and b/images/tiles/monsters/monsterc4.png differ diff --git a/images/tiles/monsters/monsterc5.png b/images/tiles/monsters/monsterc5.png new file mode 100644 index 0000000..2c04069 Binary files /dev/null and b/images/tiles/monsters/monsterc5.png differ diff --git a/images/tiles/monsters/monsterc6.png b/images/tiles/monsters/monsterc6.png new file mode 100644 index 0000000..8b091cf Binary files /dev/null and b/images/tiles/monsters/monsterc6.png differ diff --git a/images/tiles/monsters/monsterc7.png b/images/tiles/monsters/monsterc7.png new file mode 100644 index 0000000..de17694 Binary files /dev/null and b/images/tiles/monsters/monsterc7.png differ diff --git a/images/tiles/monsters/mr_pumpkin.png b/images/tiles/monsters/mr_pumpkin.png new file mode 100644 index 0000000..1e54664 Binary files /dev/null and b/images/tiles/monsters/mr_pumpkin.png differ diff --git a/images/tiles/monsters/mr_pumpkin.pxm b/images/tiles/monsters/mr_pumpkin.pxm new file mode 100644 index 0000000..bf538c6 Binary files /dev/null and b/images/tiles/monsters/mr_pumpkin.pxm differ diff --git a/images/tiles/monsters/mythical1.png b/images/tiles/monsters/mythical1.png new file mode 100644 index 0000000..28b5acb Binary files /dev/null and b/images/tiles/monsters/mythical1.png differ diff --git a/images/tiles/monsters/mzombies_1.png b/images/tiles/monsters/mzombies_1.png new file mode 100644 index 0000000..7d1bd11 Binary files /dev/null and b/images/tiles/monsters/mzombies_1.png differ diff --git a/images/tiles/monsters/mzombies_ground_a_1.png b/images/tiles/monsters/mzombies_ground_a_1.png new file mode 100644 index 0000000..d5c1845 Binary files /dev/null and b/images/tiles/monsters/mzombies_ground_a_1.png differ diff --git a/images/tiles/monsters/nightmare_run_1.png b/images/tiles/monsters/nightmare_run_1.png new file mode 100644 index 0000000..948dd57 Binary files /dev/null and b/images/tiles/monsters/nightmare_run_1.png differ diff --git a/images/tiles/monsters/nightmare_stand_1.png b/images/tiles/monsters/nightmare_stand_1.png new file mode 100644 index 0000000..9bea1f9 Binary files /dev/null and b/images/tiles/monsters/nightmare_stand_1.png differ diff --git a/images/tiles/monsters/ogre_1.png b/images/tiles/monsters/ogre_1.png new file mode 100644 index 0000000..4cd1844 Binary files /dev/null and b/images/tiles/monsters/ogre_1.png differ diff --git a/images/tiles/monsters/opossum_1.png b/images/tiles/monsters/opossum_1.png new file mode 100644 index 0000000..60dd0d0 Binary files /dev/null and b/images/tiles/monsters/opossum_1.png differ diff --git a/images/tiles/monsters/orc1.png b/images/tiles/monsters/orc1.png new file mode 100755 index 0000000..ca8ee55 Binary files /dev/null and b/images/tiles/monsters/orc1.png differ diff --git a/images/tiles/monsters/orc2.png b/images/tiles/monsters/orc2.png new file mode 100755 index 0000000..473ade2 Binary files /dev/null and b/images/tiles/monsters/orc2.png differ diff --git a/images/tiles/monsters/packcamel_b_1.png b/images/tiles/monsters/packcamel_b_1.png new file mode 100644 index 0000000..3acaa05 Binary files /dev/null and b/images/tiles/monsters/packcamel_b_1.png differ diff --git a/images/tiles/monsters/peacons.png b/images/tiles/monsters/peacons.png new file mode 100644 index 0000000..8f9f45c Binary files /dev/null and b/images/tiles/monsters/peacons.png differ diff --git a/images/tiles/monsters/reindeer_1.png b/images/tiles/monsters/reindeer_1.png new file mode 100644 index 0000000..2e8e950 Binary files /dev/null and b/images/tiles/monsters/reindeer_1.png differ diff --git a/images/tiles/monsters/reindeer_child_1.png b/images/tiles/monsters/reindeer_child_1.png new file mode 100644 index 0000000..c99c1af Binary files /dev/null and b/images/tiles/monsters/reindeer_child_1.png differ diff --git a/images/tiles/monsters/robots.png b/images/tiles/monsters/robots.png new file mode 100644 index 0000000..5f9398f Binary files /dev/null and b/images/tiles/monsters/robots.png differ diff --git a/images/tiles/monsters/robots_walkin_A_1.png b/images/tiles/monsters/robots_walkin_A_1.png new file mode 100644 index 0000000..28ef876 Binary files /dev/null and b/images/tiles/monsters/robots_walkin_A_1.png differ diff --git a/images/tiles/monsters/robots_walkin_B_1.png b/images/tiles/monsters/robots_walkin_B_1.png new file mode 100644 index 0000000..fef748f Binary files /dev/null and b/images/tiles/monsters/robots_walkin_B_1.png differ diff --git a/images/tiles/monsters/roboz_1x.png b/images/tiles/monsters/roboz_1x.png new file mode 100644 index 0000000..a55eaeb Binary files /dev/null and b/images/tiles/monsters/roboz_1x.png differ diff --git a/images/tiles/monsters/rudolph.png b/images/tiles/monsters/rudolph.png new file mode 100644 index 0000000..0b80892 Binary files /dev/null and b/images/tiles/monsters/rudolph.png differ diff --git a/images/tiles/monsters/rudolph_adult_1.png b/images/tiles/monsters/rudolph_adult_1.png new file mode 100644 index 0000000..b816375 Binary files /dev/null and b/images/tiles/monsters/rudolph_adult_1.png differ diff --git a/images/tiles/monsters/rudolph_child_1.png b/images/tiles/monsters/rudolph_child_1.png new file mode 100644 index 0000000..55c6f3e Binary files /dev/null and b/images/tiles/monsters/rudolph_child_1.png differ diff --git a/images/tiles/monsters/rudolphi.png b/images/tiles/monsters/rudolphi.png new file mode 100644 index 0000000..5a769f8 Binary files /dev/null and b/images/tiles/monsters/rudolphi.png differ diff --git a/images/tiles/monsters/sasquatch_1.png b/images/tiles/monsters/sasquatch_1.png new file mode 100644 index 0000000..210f4a3 Binary files /dev/null and b/images/tiles/monsters/sasquatch_1.png differ diff --git a/images/tiles/monsters/shark_fin_blue_1.png b/images/tiles/monsters/shark_fin_blue_1.png new file mode 100644 index 0000000..8aa3a60 Binary files /dev/null and b/images/tiles/monsters/shark_fin_blue_1.png differ diff --git a/images/tiles/monsters/shark_fin_brown_1.png b/images/tiles/monsters/shark_fin_brown_1.png new file mode 100644 index 0000000..2285a58 Binary files /dev/null and b/images/tiles/monsters/shark_fin_brown_1.png differ diff --git a/images/tiles/monsters/shark_finshadow_blue_1.png b/images/tiles/monsters/shark_finshadow_blue_1.png new file mode 100644 index 0000000..0f7a419 Binary files /dev/null and b/images/tiles/monsters/shark_finshadow_blue_1.png differ diff --git a/images/tiles/monsters/shark_finshadow_brown_1.png b/images/tiles/monsters/shark_finshadow_brown_1.png new file mode 100644 index 0000000..ed5adc0 Binary files /dev/null and b/images/tiles/monsters/shark_finshadow_brown_1.png differ diff --git a/images/tiles/monsters/shark_full_blue_1.png b/images/tiles/monsters/shark_full_blue_1.png new file mode 100644 index 0000000..62995e9 Binary files /dev/null and b/images/tiles/monsters/shark_full_blue_1.png differ diff --git a/images/tiles/monsters/shark_full_brown_1.png b/images/tiles/monsters/shark_full_brown_1.png new file mode 100644 index 0000000..873e5fb Binary files /dev/null and b/images/tiles/monsters/shark_full_brown_1.png differ diff --git a/images/tiles/monsters/slenderman.png b/images/tiles/monsters/slenderman.png new file mode 100644 index 0000000..5e25907 Binary files /dev/null and b/images/tiles/monsters/slenderman.png differ diff --git a/images/tiles/monsters/slime_big_single.png b/images/tiles/monsters/slime_big_single.png new file mode 100644 index 0000000..d8facc4 Binary files /dev/null and b/images/tiles/monsters/slime_big_single.png differ diff --git a/images/tiles/monsters/slime_king_single.png b/images/tiles/monsters/slime_king_single.png new file mode 100644 index 0000000..92462a4 Binary files /dev/null and b/images/tiles/monsters/slime_king_single.png differ diff --git a/images/tiles/monsters/slimevariants_1.png b/images/tiles/monsters/slimevariants_1.png new file mode 100644 index 0000000..454bffc Binary files /dev/null and b/images/tiles/monsters/slimevariants_1.png differ diff --git a/images/tiles/monsters/snowman.png b/images/tiles/monsters/snowman.png new file mode 100644 index 0000000..a800219 Binary files /dev/null and b/images/tiles/monsters/snowman.png differ diff --git a/images/tiles/monsters/snowmonster_1.png b/images/tiles/monsters/snowmonster_1.png new file mode 100644 index 0000000..befacd3 Binary files /dev/null and b/images/tiles/monsters/snowmonster_1.png differ diff --git a/images/tiles/monsters/stompy.png b/images/tiles/monsters/stompy.png new file mode 100644 index 0000000..100382d Binary files /dev/null and b/images/tiles/monsters/stompy.png differ diff --git a/images/tiles/monsters/stompy2.png b/images/tiles/monsters/stompy2.png new file mode 100644 index 0000000..09605ac Binary files /dev/null and b/images/tiles/monsters/stompy2.png differ diff --git a/images/tiles/monsters/stompy3.png b/images/tiles/monsters/stompy3.png new file mode 100644 index 0000000..786d563 Binary files /dev/null and b/images/tiles/monsters/stompy3.png differ diff --git a/images/tiles/monsters/theblackknight_1.png b/images/tiles/monsters/theblackknight_1.png new file mode 100644 index 0000000..15d481a Binary files /dev/null and b/images/tiles/monsters/theblackknight_1.png differ diff --git a/images/tiles/monsters/theblackknightshorse_1.png b/images/tiles/monsters/theblackknightshorse_1.png new file mode 100644 index 0000000..6c9fafc Binary files /dev/null and b/images/tiles/monsters/theblackknightshorse_1.png differ diff --git a/images/tiles/monsters/thornbeetle_1.png b/images/tiles/monsters/thornbeetle_1.png new file mode 100644 index 0000000..8ebe28d Binary files /dev/null and b/images/tiles/monsters/thornbeetle_1.png differ diff --git a/images/tiles/monsters/tiger.png b/images/tiles/monsters/tiger.png new file mode 100644 index 0000000..6900ba7 Binary files /dev/null and b/images/tiles/monsters/tiger.png differ diff --git a/images/tiles/monsters/tinyfairies.png b/images/tiles/monsters/tinyfairies.png new file mode 100644 index 0000000..246cb78 Binary files /dev/null and b/images/tiles/monsters/tinyfairies.png differ diff --git a/images/tiles/monsters/troll1a_1.png b/images/tiles/monsters/troll1a_1.png new file mode 100644 index 0000000..7fc5da3 Binary files /dev/null and b/images/tiles/monsters/troll1a_1.png differ diff --git a/images/tiles/monsters/troll1b_1.png b/images/tiles/monsters/troll1b_1.png new file mode 100644 index 0000000..a59fd6d Binary files /dev/null and b/images/tiles/monsters/troll1b_1.png differ diff --git a/images/tiles/monsters/troll2a_1.png b/images/tiles/monsters/troll2a_1.png new file mode 100644 index 0000000..a12d2f7 Binary files /dev/null and b/images/tiles/monsters/troll2a_1.png differ diff --git a/images/tiles/monsters/troll2b_1.png b/images/tiles/monsters/troll2b_1.png new file mode 100644 index 0000000..11f1340 Binary files /dev/null and b/images/tiles/monsters/troll2b_1.png differ diff --git a/images/tiles/monsters/tyw_monster1_1.png b/images/tiles/monsters/tyw_monster1_1.png new file mode 100644 index 0000000..bc36eb8 Binary files /dev/null and b/images/tiles/monsters/tyw_monster1_1.png differ diff --git a/images/tiles/monsters/tyw_monster2a_1.png b/images/tiles/monsters/tyw_monster2a_1.png new file mode 100644 index 0000000..86e99e9 Binary files /dev/null and b/images/tiles/monsters/tyw_monster2a_1.png differ diff --git a/images/tiles/monsters/tyw_monster2b_1.png b/images/tiles/monsters/tyw_monster2b_1.png new file mode 100644 index 0000000..8ce43ee Binary files /dev/null and b/images/tiles/monsters/tyw_monster2b_1.png differ diff --git a/images/tiles/monsters/ugknuckles_1.png b/images/tiles/monsters/ugknuckles_1.png new file mode 100644 index 0000000..3dcf448 Binary files /dev/null and b/images/tiles/monsters/ugknuckles_1.png differ diff --git a/images/tiles/monsters/unicorn1.png b/images/tiles/monsters/unicorn1.png new file mode 100644 index 0000000..d3395fd Binary files /dev/null and b/images/tiles/monsters/unicorn1.png differ diff --git a/images/tiles/monsters/vampire2d.png b/images/tiles/monsters/vampire2d.png new file mode 100644 index 0000000..d79940a Binary files /dev/null and b/images/tiles/monsters/vampire2d.png differ diff --git a/images/tiles/monsters/warden_1.png b/images/tiles/monsters/warden_1.png new file mode 100644 index 0000000..0557bb3 Binary files /dev/null and b/images/tiles/monsters/warden_1.png differ diff --git a/images/tiles/monsters/warden_walk_blue_shadow_1.png b/images/tiles/monsters/warden_walk_blue_shadow_1.png new file mode 100644 index 0000000..b2dc63f Binary files /dev/null and b/images/tiles/monsters/warden_walk_blue_shadow_1.png differ diff --git a/images/tiles/monsters/werewolf_8sheet_1.png b/images/tiles/monsters/werewolf_8sheet_1.png new file mode 100644 index 0000000..f6943a5 Binary files /dev/null and b/images/tiles/monsters/werewolf_8sheet_1.png differ diff --git a/images/tiles/monsters/werewolf_single_brown_1.png b/images/tiles/monsters/werewolf_single_brown_1.png new file mode 100644 index 0000000..c82c635 Binary files /dev/null and b/images/tiles/monsters/werewolf_single_brown_1.png differ diff --git a/images/tiles/monsters/werewolf_single_gray_1.png b/images/tiles/monsters/werewolf_single_gray_1.png new file mode 100644 index 0000000..3398084 Binary files /dev/null and b/images/tiles/monsters/werewolf_single_gray_1.png differ diff --git a/images/tiles/monsters/witchqueen_red_hat_1.png b/images/tiles/monsters/witchqueen_red_hat_1.png new file mode 100644 index 0000000..18f0788 Binary files /dev/null and b/images/tiles/monsters/witchqueen_red_hat_1.png differ diff --git a/images/tiles/monsters/wyvern_single_green_1.png b/images/tiles/monsters/wyvern_single_green_1.png new file mode 100644 index 0000000..9783626 Binary files /dev/null and b/images/tiles/monsters/wyvern_single_green_1.png differ diff --git a/images/tiles/monsters/wyvern_single_red_1.png b/images/tiles/monsters/wyvern_single_red_1.png new file mode 100644 index 0000000..59f8ddf Binary files /dev/null and b/images/tiles/monsters/wyvern_single_red_1.png differ diff --git a/images/tiles/monsters/wyverns_1.png b/images/tiles/monsters/wyverns_1.png new file mode 100644 index 0000000..423c0b6 Binary files /dev/null and b/images/tiles/monsters/wyverns_1.png differ diff --git a/images/tiles/npcs/aeronaut_tf_1.png b/images/tiles/npcs/aeronaut_tf_1.png new file mode 100644 index 0000000..495b908 Binary files /dev/null and b/images/tiles/npcs/aeronaut_tf_1.png differ diff --git a/images/tiles/npcs/astronaut_tf.png b/images/tiles/npcs/astronaut_tf.png new file mode 100644 index 0000000..881155c Binary files /dev/null and b/images/tiles/npcs/astronaut_tf.png differ diff --git a/images/tiles/npcs/barrel_tf.png b/images/tiles/npcs/barrel_tf.png new file mode 100644 index 0000000..4a0b923 Binary files /dev/null and b/images/tiles/npcs/barrel_tf.png differ diff --git a/images/tiles/npcs/barrelgob_tf.png b/images/tiles/npcs/barrelgob_tf.png new file mode 100644 index 0000000..852484d Binary files /dev/null and b/images/tiles/npcs/barrelgob_tf.png differ diff --git a/images/tiles/npcs/barrelman_tf.png b/images/tiles/npcs/barrelman_tf.png new file mode 100644 index 0000000..81603d1 Binary files /dev/null and b/images/tiles/npcs/barrelman_tf.png differ diff --git a/images/tiles/npcs/bellydancers_1 (1).png b/images/tiles/npcs/bellydancers_1 (1).png new file mode 100644 index 0000000..47aee45 Binary files /dev/null and b/images/tiles/npcs/bellydancers_1 (1).png differ diff --git a/images/tiles/npcs/bush_tf.png b/images/tiles/npcs/bush_tf.png new file mode 100644 index 0000000..1b81eff Binary files /dev/null and b/images/tiles/npcs/bush_tf.png differ diff --git a/images/tiles/npcs/cobra_tf_1.png b/images/tiles/npcs/cobra_tf_1.png new file mode 100644 index 0000000..a851072 Binary files /dev/null and b/images/tiles/npcs/cobra_tf_1.png differ diff --git a/images/tiles/npcs/conductor_tf_1.png b/images/tiles/npcs/conductor_tf_1.png new file mode 100644 index 0000000..0916217 Binary files /dev/null and b/images/tiles/npcs/conductor_tf_1.png differ diff --git a/images/tiles/npcs/dancerA_single_1.png b/images/tiles/npcs/dancerA_single_1.png new file mode 100644 index 0000000..00baccb Binary files /dev/null and b/images/tiles/npcs/dancerA_single_1.png differ diff --git a/images/tiles/npcs/dancerB_single_1.png b/images/tiles/npcs/dancerB_single_1.png new file mode 100644 index 0000000..3d2f329 Binary files /dev/null and b/images/tiles/npcs/dancerB_single_1.png differ diff --git a/images/tiles/npcs/dancerC_single_1.png b/images/tiles/npcs/dancerC_single_1.png new file mode 100644 index 0000000..5143257 Binary files /dev/null and b/images/tiles/npcs/dancerC_single_1.png differ diff --git a/images/tiles/npcs/dancerD_single_1.png b/images/tiles/npcs/dancerD_single_1.png new file mode 100644 index 0000000..90d6f72 Binary files /dev/null and b/images/tiles/npcs/dancerD_single_1.png differ diff --git a/images/tiles/npcs/foodboys_tf.png b/images/tiles/npcs/foodboys_tf.png new file mode 100644 index 0000000..f45f019 Binary files /dev/null and b/images/tiles/npcs/foodboys_tf.png differ diff --git a/images/tiles/npcs/ironchef_tf.png b/images/tiles/npcs/ironchef_tf.png new file mode 100644 index 0000000..afa47d1 Binary files /dev/null and b/images/tiles/npcs/ironchef_tf.png differ diff --git a/images/tiles/npcs/ironchef_walk_tf.png b/images/tiles/npcs/ironchef_walk_tf.png new file mode 100644 index 0000000..637c8b9 Binary files /dev/null and b/images/tiles/npcs/ironchef_walk_tf.png differ diff --git a/images/tiles/npcs/lucha_shadow_tf.png b/images/tiles/npcs/lucha_shadow_tf.png new file mode 100644 index 0000000..2d51b66 Binary files /dev/null and b/images/tiles/npcs/lucha_shadow_tf.png differ diff --git a/images/tiles/npcs/onionboss_tf_shadow.png b/images/tiles/npcs/onionboss_tf_shadow.png new file mode 100644 index 0000000..442b130 Binary files /dev/null and b/images/tiles/npcs/onionboss_tf_shadow.png differ diff --git a/images/tiles/npcs/pigman_tf.png b/images/tiles/npcs/pigman_tf.png new file mode 100644 index 0000000..75bdcf8 Binary files /dev/null and b/images/tiles/npcs/pigman_tf.png differ diff --git a/images/tiles/npcs/shoewoman_tf_1.png b/images/tiles/npcs/shoewoman_tf_1.png new file mode 100644 index 0000000..9218bc1 Binary files /dev/null and b/images/tiles/npcs/shoewoman_tf_1.png differ diff --git a/images/tiles/npcs/signguy_tf.png b/images/tiles/npcs/signguy_tf.png new file mode 100644 index 0000000..cb3f5e1 Binary files /dev/null and b/images/tiles/npcs/signguy_tf.png differ diff --git a/images/tiles/npcs/snakecharmer_tf_1.png b/images/tiles/npcs/snakecharmer_tf_1.png new file mode 100644 index 0000000..3038dec Binary files /dev/null and b/images/tiles/npcs/snakecharmer_tf_1.png differ diff --git a/images/tiles/npcs/snakecharmer_walk_1.png b/images/tiles/npcs/snakecharmer_walk_1.png new file mode 100644 index 0000000..3dcb3c5 Binary files /dev/null and b/images/tiles/npcs/snakecharmer_walk_1.png differ diff --git a/images/tiles/npcs/sumo_tf_1.png b/images/tiles/npcs/sumo_tf_1.png new file mode 100644 index 0000000..cf38966 Binary files /dev/null and b/images/tiles/npcs/sumo_tf_1.png differ diff --git a/images/tiles/npcs/sunandmoon_tf_1.png b/images/tiles/npcs/sunandmoon_tf_1.png new file mode 100644 index 0000000..10ce993 Binary files /dev/null and b/images/tiles/npcs/sunandmoon_tf_1.png differ diff --git a/images/tiles/npcs/trenchcoat_tf_1.png b/images/tiles/npcs/trenchcoat_tf_1.png new file mode 100644 index 0000000..bb9bd73 Binary files /dev/null and b/images/tiles/npcs/trenchcoat_tf_1.png differ diff --git a/images/tiles/npcs/twins_tf.png b/images/tiles/npcs/twins_tf.png new file mode 100644 index 0000000..c3ccf79 Binary files /dev/null and b/images/tiles/npcs/twins_tf.png differ diff --git a/images/tiles/npcs/veildancers_1.png b/images/tiles/npcs/veildancers_1.png new file mode 100644 index 0000000..49b745d Binary files /dev/null and b/images/tiles/npcs/veildancers_1.png differ diff --git a/images/tiles/skins/.DS_Store b/images/tiles/skins/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/images/tiles/skins/.DS_Store differ diff --git a/images/tiles/skins/lskin1.png b/images/tiles/skins/lskin1.png new file mode 100644 index 0000000..8e31a59 Binary files /dev/null and b/images/tiles/skins/lskin1.png differ diff --git a/images/tiles/skins/mskin1.png b/images/tiles/skins/mskin1.png new file mode 100644 index 0000000..9bbb1bb Binary files /dev/null and b/images/tiles/skins/mskin1.png differ diff --git a/images/tiles/skins/sskin1.png b/images/tiles/skins/sskin1.png new file mode 100644 index 0000000..0429a10 Binary files /dev/null and b/images/tiles/skins/sskin1.png differ diff --git a/index.yaml b/index.yaml new file mode 100644 index 0000000..88a35ac --- /dev/null +++ b/index.yaml @@ -0,0 +1,50 @@ +indexes: + +- kind: Character #UnstuckPlayers + properties: + - name: online + - name: server + - name: last_sync + +- kind: Character #verify_steam_installs() + properties: + - name: platform + - name: last_online + direction: desc + +- kind: Event + properties: + - name: tag + - name: created + direction: desc + +- kind: Backup + properties: + - name: backup_item_id + - name: backup_created + direction: desc + +- kind: Mail + properties: + - name: owner + - name: created + direction: desc + +- kind: Message + properties: + - name: owner + - name: created + direction: desc + +- kind: Message + properties: + - name: author + - name: created + direction: desc + +- kind: Message + properties: + - name: owner + - name: type + - name: created + direction: desc \ No newline at end of file diff --git a/js/.DS_Store b/js/.DS_Store new file mode 100644 index 0000000..7ad1e5e Binary files /dev/null and b/js/.DS_Store differ diff --git a/js/admin.js b/js/admin.js new file mode 100644 index 0000000..e3a8745 --- /dev/null +++ b/js/admin.js @@ -0,0 +1,81 @@ +function drop_to_html(def,mult,color) +{ + var html=""; + if(def[1]=="open") + { + D.drops[def[2]].forEach(function(d){ + html+=drop_to_html(d,mult*def[0],color); + }); + return html; + } + html+="
"; + var skin="",prob=parseInt(1/(def[0]*mult)); + if(G.items[def[1]]) skin=G.items[def[1]].skin; + else if(def[1]=="shells") skin="shells"; + else if(def[1]=="gold") skin="gold"; + html+=item_container({skin:skin}); + html+="
1 / "+to_pretty_num(prob)+"
"; + html+="
"; + return html; +} + +function item_analysis() +{ + var html=""; + ["weapon","shield","offhand","helmet"].forEach(function(type){ + var items=[]; + for(var id in G.items) + { + if(G.items[id].type==type) + items.push(id); + } + html+="
"+type+"
"; + items.forEach(function(id){ + html+=item_container({skin:G.items[id].skin},{name:id}); + }) + }); + show_modal(html); +} + +function visualize() +{ + if(!window.D) return pull_D(); + var html="
"; + object_sort(G.maps).forEach(function(io){ + var mname=io[0],map=G.maps[mname],pc={},mc={},m={},first=false,mx=false; + if(!(D.drops.maps[mname] || map.monsters && map.monsters.length) || G.maps[mname].ignore) return; + html+="
"+map.name+"
"; + for(var i=0;i<(D.drops.maps[mname]||[]).length;i++) + { + html+=drop_to_html(D.drops.maps[mname][i],1,"#858B8E"); mx=true; + } + if(mx) html+="
"; + html+="
"; + for(var i=0;i<(map.monsters||[]).length;i++) + { + var m_def=map.monsters[i],monster=G.monsters[m_def.type]; + pc[m_def.type]=(pc[m_def.type]||0)+1; + mc[m_def.type]=(mc[m_def.type]||0)+m_def.count; + } + for(var i=0;i<(map.monsters||[]).length;i++) + { + var m_def=map.monsters[i],monster=G.monsters[m_def.type],drop=false; + if(m[m_def.type]) continue; + if(!monster) alert("no "+JSON.stringify(m_def)); + html+="
"+sprite(monster.skin)+"
"+monster.name+" ["+mc[m_def.type]+"]
"; + html+="
"; + for(var j=0;j<(D.drops.monsters[m_def.type]||[]).length;j++) + { + html+=drop_to_html(D.drops.monsters[m_def.type][j],1,"#858B8E"); + drop=true; + } + if(!drop) html+="
No Drop
"; + else html+="
"; + html+="
"; + m[m_def.type]=true; + } + if(!first) html+="
"; first=true; + }); + html+="
" + show_modal(html); +} \ No newline at end of file diff --git a/js/codemirror/.DS_Store b/js/codemirror/.DS_Store new file mode 100644 index 0000000..f3ba8e6 Binary files /dev/null and b/js/codemirror/.DS_Store differ diff --git a/js/codemirror/5.15.2/codemirror.css b/js/codemirror/5.15.2/codemirror.css new file mode 100644 index 0000000..4bd815e --- /dev/null +++ b/js/codemirror/5.15.2/codemirror.css @@ -0,0 +1,338 @@ +/* BASICS */ + +.CodeMirror { + /* Set height, width, borders, and global font properties here */ + font-family: monospace; + height: 300px; + color: black; +} + +/* PADDING */ + +.CodeMirror-lines { + padding: 4px 0; /* Vertical padding around content */ +} +.CodeMirror pre { + padding: 0 4px; /* Horizontal padding of content */ +} + +.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + background-color: white; /* The little square between H and V scrollbars */ +} + +/* GUTTER */ + +.CodeMirror-gutters { + border-right: 1px solid #ddd; + background-color: #f7f7f7; + white-space: nowrap; +} +.CodeMirror-linenumbers {} +.CodeMirror-linenumber { + padding: 0 3px 0 5px; + min-width: 20px; + text-align: right; + color: #999; + white-space: nowrap; +} + +.CodeMirror-guttermarker { color: black; } +.CodeMirror-guttermarker-subtle { color: #999; } + +/* CURSOR */ + +.CodeMirror-cursor { + border-left: 1px solid black; + border-right: none; + width: 0; +} +/* Shown when moving in bi-directional text */ +.CodeMirror div.CodeMirror-secondarycursor { + border-left: 1px solid silver; +} +.cm-fat-cursor .CodeMirror-cursor { + width: auto; + border: 0 !important; + background: #7e7; +} +.cm-fat-cursor div.CodeMirror-cursors { + z-index: 1; +} + +.cm-animate-fat-cursor { + width: auto; + border: 0; + -webkit-animation: blink 1.06s steps(1) infinite; + -moz-animation: blink 1.06s steps(1) infinite; + animation: blink 1.06s steps(1) infinite; + background-color: #7e7; +} +@-moz-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@-webkit-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} + +/* Can style cursor different in overwrite (non-insert) mode */ +.CodeMirror-overwrite .CodeMirror-cursor {} + +.cm-tab { display: inline-block; text-decoration: inherit; } + +.CodeMirror-ruler { + border-left: 1px solid #ccc; + position: absolute; +} + +/* DEFAULT THEME */ + +.cm-s-default .cm-header {color: blue;} +.cm-s-default .cm-quote {color: #090;} +.cm-negative {color: #d44;} +.cm-positive {color: #292;} +.cm-header, .cm-strong {font-weight: bold;} +.cm-em {font-style: italic;} +.cm-link {text-decoration: underline;} +.cm-strikethrough {text-decoration: line-through;} + +.cm-s-default .cm-keyword {color: #708;} +.cm-s-default .cm-atom {color: #219;} +.cm-s-default .cm-number {color: #164;} +.cm-s-default .cm-def {color: #00f;} +.cm-s-default .cm-variable, +.cm-s-default .cm-punctuation, +.cm-s-default .cm-property, +.cm-s-default .cm-operator {} +.cm-s-default .cm-variable-2 {color: #05a;} +.cm-s-default .cm-variable-3 {color: #085;} +.cm-s-default .cm-comment {color: #a50;} +.cm-s-default .cm-string {color: #a11;} +.cm-s-default .cm-string-2 {color: #f50;} +.cm-s-default .cm-meta {color: #555;} +.cm-s-default .cm-qualifier {color: #555;} +.cm-s-default .cm-builtin {color: #30a;} +.cm-s-default .cm-bracket {color: #997;} +.cm-s-default .cm-tag {color: #170;} +.cm-s-default .cm-attribute {color: #00c;} +.cm-s-default .cm-hr {color: #999;} +.cm-s-default .cm-link {color: #00c;} + +.cm-s-default .cm-error {color: #f00;} +.cm-invalidchar {color: #f00;} + +.CodeMirror-composing { border-bottom: 2px solid; } + +/* Default styles for common addons */ + +div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} +div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} +.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } +.CodeMirror-activeline-background {background: #e8f2ff;} + +/* STOP */ + +/* The rest of this file contains styles related to the mechanics of + the editor. You probably shouldn't touch them. */ + +.CodeMirror { + position: relative; + overflow: hidden; + background: white; +} + +.CodeMirror-scroll { + overflow: scroll !important; /* Things will break if this is overridden */ + /* 30px is the magic margin used to hide the element's real scrollbars */ + /* See overflow: hidden in .CodeMirror */ + margin-bottom: -30px; margin-right: -30px; + padding-bottom: 30px; + height: 100%; + outline: none; /* Prevent dragging from highlighting the element */ + position: relative; +} +.CodeMirror-sizer { + position: relative; + border-right: 30px solid transparent; +} + +/* The fake, visible scrollbars. Used to force redraw during scrolling + before actual scrolling happens, thus preventing shaking and + flickering artifacts. */ +.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + position: absolute; + z-index: 6; + display: none; +} +.CodeMirror-vscrollbar { + right: 0; top: 0; + overflow-x: hidden; + overflow-y: scroll; +} +.CodeMirror-hscrollbar { + bottom: 0; left: 0; + overflow-y: hidden; + overflow-x: scroll; +} +.CodeMirror-scrollbar-filler { + right: 0; bottom: 0; +} +.CodeMirror-gutter-filler { + left: 0; bottom: 0; +} + +.CodeMirror-gutters { + position: absolute; left: 0; top: 0; + min-height: 100%; + z-index: 3; +} +.CodeMirror-gutter { + white-space: normal; + height: 100%; + display: inline-block; + vertical-align: top; + margin-bottom: -30px; + /* Hack to make IE7 behave */ + *zoom:1; + *display:inline; +} +.CodeMirror-gutter-wrapper { + position: absolute; + z-index: 4; + background: none !important; + border: none !important; +} +.CodeMirror-gutter-background { + position: absolute; + top: 0; bottom: 0; + z-index: 4; +} +.CodeMirror-gutter-elt { + position: absolute; + cursor: default; + z-index: 4; +} +.CodeMirror-gutter-wrapper { + -webkit-user-select: none; + -moz-user-select: none; + user-select: none; +} + +.CodeMirror-lines { + cursor: text; + min-height: 1px; /* prevents collapsing before first draw */ +} +.CodeMirror pre { + /* Reset some styles that the rest of the page might have set */ + -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; + border-width: 0; + background: transparent; + font-family: inherit; + font-size: inherit; + margin: 0; + white-space: pre; + word-wrap: normal; + line-height: inherit; + color: inherit; + z-index: 2; + position: relative; + overflow: visible; + -webkit-tap-highlight-color: transparent; + -webkit-font-variant-ligatures: none; + font-variant-ligatures: none; +} +.CodeMirror-wrap pre { + word-wrap: break-word; + white-space: pre-wrap; + word-break: normal; +} + +.CodeMirror-linebackground { + position: absolute; + left: 0; right: 0; top: 0; bottom: 0; + z-index: 0; +} + +.CodeMirror-linewidget { + position: relative; + z-index: 2; + overflow: auto; +} + +.CodeMirror-widget {} + +.CodeMirror-code { + outline: none; +} + +/* Force content-box sizing for the elements where we expect it */ +.CodeMirror-scroll, +.CodeMirror-sizer, +.CodeMirror-gutter, +.CodeMirror-gutters, +.CodeMirror-linenumber { + -moz-box-sizing: content-box; + box-sizing: content-box; +} + +.CodeMirror-measure { + position: absolute; + width: 100%; + height: 0; + overflow: hidden; + visibility: hidden; +} + +.CodeMirror-cursor { position: absolute; } +.CodeMirror-measure pre { position: static; } + +div.CodeMirror-cursors { + visibility: hidden; + position: relative; + z-index: 3; +} +div.CodeMirror-dragcursors { + visibility: visible; +} + +.CodeMirror-focused div.CodeMirror-cursors { + visibility: visible; +} + +.CodeMirror-selected { background: #d9d9d9; } +.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } +.CodeMirror-crosshair { cursor: crosshair; } +.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; } +.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; } + +.cm-searching { + background: #ffa; + background: rgba(255, 255, 0, .4); +} + +/* IE7 hack to prevent it from returning funny offsetTops on the spans */ +.CodeMirror span { *vertical-align: text-bottom; } + +/* Used to force a border model for a node */ +.cm-force-border { padding-right: .1px; } + +@media print { + /* Hide the cursor when printing */ + .CodeMirror div.CodeMirror-cursors { + visibility: hidden; + } +} + +/* See issue #2901 */ +.cm-tab-wrap-hack:after { content: ''; } + +/* Help users use markselection to safely style text background */ +span.CodeMirror-selectedtext { background: none; } diff --git a/js/codemirror/5.15.2/codemirror.js b/js/codemirror/5.15.2/codemirror.js new file mode 100644 index 0000000..deae93a --- /dev/null +++ b/js/codemirror/5.15.2/codemirror.js @@ -0,0 +1,8908 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// This is CodeMirror (http://codemirror.net), a code editor +// implemented in JavaScript on top of the browser's DOM. +// +// You can find some technical background for some of the code below +// at http://marijnhaverbeke.nl/blog/#cm-internals . + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + module.exports = mod(); + else if (typeof define == "function" && define.amd) // AMD + return define([], mod); + else // Plain browser env + (this || window).CodeMirror = mod(); +})(function() { + "use strict"; + + // BROWSER SNIFFING + + // Kludges for bugs and behavior differences that can't be feature + // detected are enabled based on userAgent etc sniffing. + var userAgent = navigator.userAgent; + var platform = navigator.platform; + + var gecko = /gecko\/\d/i.test(userAgent); + var ie_upto10 = /MSIE \d/.test(userAgent); + var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); + var ie = ie_upto10 || ie_11up; + var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]); + var webkit = /WebKit\//.test(userAgent); + var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); + var chrome = /Chrome\//.test(userAgent); + var presto = /Opera\//.test(userAgent); + var safari = /Apple Computer/.test(navigator.vendor); + var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); + var phantom = /PhantomJS/.test(userAgent); + + var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent); + // This is woefully incomplete. Suggestions for alternative methods welcome. + var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); + var mac = ios || /Mac/.test(platform); + var chromeOS = /\bCrOS\b/.test(userAgent); + var windows = /win/i.test(platform); + + var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); + if (presto_version) presto_version = Number(presto_version[1]); + if (presto_version && presto_version >= 15) { presto = false; webkit = true; } + // Some browsers use the wrong event properties to signal cmd/ctrl on OS X + var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); + var captureRightClick = gecko || (ie && ie_version >= 9); + + // Optimize some code when these features are not used. + var sawReadOnlySpans = false, sawCollapsedSpans = false; + + // EDITOR CONSTRUCTOR + + // A CodeMirror instance represents an editor. This is the object + // that user code is usually dealing with. + + function CodeMirror(place, options) { + if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); + + this.options = options = options ? copyObj(options) : {}; + // Determine effective options based on given values and defaults. + copyObj(defaults, options, false); + setGuttersForLineNumbers(options); + + var doc = options.value; + if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator); + this.doc = doc; + + var input = new CodeMirror.inputStyles[options.inputStyle](this); + var display = this.display = new Display(place, doc, input); + display.wrapper.CodeMirror = this; + updateGutters(this); + themeChanged(this); + if (options.lineWrapping) + this.display.wrapper.className += " CodeMirror-wrap"; + if (options.autofocus && !mobile) display.input.focus(); + initScrollbars(this); + + this.state = { + keyMaps: [], // stores maps added by addKeyMap + overlays: [], // highlighting overlays, as added by addOverlay + modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info + overwrite: false, + delayingBlurEvent: false, + focused: false, + suppressEdits: false, // used to disable editing during key handlers when in readOnly mode + pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll + selectingText: false, + draggingText: false, + highlight: new Delayed(), // stores highlight worker timeout + keySeq: null, // Unfinished key sequence + specialChars: null + }; + + var cm = this; + + // Override magic textarea content restore that IE sometimes does + // on our hidden textarea on reload + if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20); + + registerEventHandlers(this); + ensureGlobalHandlers(); + + startOperation(this); + this.curOp.forceUpdate = true; + attachDoc(this, doc); + + if ((options.autofocus && !mobile) || cm.hasFocus()) + setTimeout(bind(onFocus, this), 20); + else + onBlur(this); + + for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt)) + optionHandlers[opt](this, options[opt], Init); + maybeUpdateLineNumberWidth(this); + if (options.finishInit) options.finishInit(this); + for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); + endOperation(this); + // Suppress optimizelegibility in Webkit, since it breaks text + // measuring on line wrapping boundaries. + if (webkit && options.lineWrapping && + getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") + display.lineDiv.style.textRendering = "auto"; + } + + // DISPLAY CONSTRUCTOR + + // The display handles the DOM integration, both for input reading + // and content drawing. It holds references to DOM nodes and + // display-related state. + + function Display(place, doc, input) { + var d = this; + this.input = input; + + // Covers bottom-right square when both scrollbars are present. + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); + d.scrollbarFiller.setAttribute("cm-not-content", "true"); + // Covers bottom of gutter when coverGutterNextToScrollbar is on + // and h scrollbar is present. + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); + d.gutterFiller.setAttribute("cm-not-content", "true"); + // Will contain the actual code, positioned to cover the viewport. + d.lineDiv = elt("div", null, "CodeMirror-code"); + // Elements are added to these to represent selection and cursors. + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); + d.cursorDiv = elt("div", null, "CodeMirror-cursors"); + // A visibility: hidden element used to find the size of things. + d.measure = elt("div", null, "CodeMirror-measure"); + // When lines outside of the viewport are measured, they are drawn in this. + d.lineMeasure = elt("div", null, "CodeMirror-measure"); + // Wraps everything that needs to exist inside the vertically-padded coordinate system + d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], + null, "position: relative; outline: none"); + // Moved around its parent to cover visible view. + d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); + // Set to the height of the document, allowing scrolling. + d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); + d.sizerWidth = null; + // Behavior of elts with overflow: auto and padding is + // inconsistent across browsers. This is used to ensure the + // scrollable area is big enough. + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); + // Will contain the gutters, if any. + d.gutters = elt("div", null, "CodeMirror-gutters"); + d.lineGutter = null; + // Actual scrollable element. + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); + d.scroller.setAttribute("tabIndex", "-1"); + // The element in which the editor lives. + d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); + + // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) + if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } + if (!webkit && !(gecko && mobile)) d.scroller.draggable = true; + + if (place) { + if (place.appendChild) place.appendChild(d.wrapper); + else place(d.wrapper); + } + + // Current rendered range (may be bigger than the view window). + d.viewFrom = d.viewTo = doc.first; + d.reportedViewFrom = d.reportedViewTo = doc.first; + // Information about the rendered lines. + d.view = []; + d.renderedView = null; + // Holds info about a single rendered line when it was rendered + // for measurement, while not in view. + d.externalMeasured = null; + // Empty space (in pixels) above the view + d.viewOffset = 0; + d.lastWrapHeight = d.lastWrapWidth = 0; + d.updateLineNumbers = null; + + d.nativeBarWidth = d.barHeight = d.barWidth = 0; + d.scrollbarsClipped = false; + + // Used to only resize the line number gutter when necessary (when + // the amount of lines crosses a boundary that makes its width change) + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; + // Set to true when a non-horizontal-scrolling line widget is + // added. As an optimization, line widget aligning is skipped when + // this is false. + d.alignWidgets = false; + + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + + // Tracks the maximum line length so that the horizontal scrollbar + // can be kept static when scrolling. + d.maxLine = null; + d.maxLineLength = 0; + d.maxLineChanged = false; + + // Used for measuring wheel scrolling granularity + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; + + // True when shift is held down. + d.shift = false; + + // Used to track whether anything happened since the context menu + // was opened. + d.selForContextMenu = null; + + d.activeTouch = null; + + input.init(d); + } + + // STATE UPDATES + + // Used to get the editor into a consistent state again when options change. + + function loadMode(cm) { + cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); + resetModeState(cm); + } + + function resetModeState(cm) { + cm.doc.iter(function(line) { + if (line.stateAfter) line.stateAfter = null; + if (line.styles) line.styles = null; + }); + cm.doc.frontier = cm.doc.first; + startWorker(cm, 100); + cm.state.modeGen++; + if (cm.curOp) regChange(cm); + } + + function wrappingChanged(cm) { + if (cm.options.lineWrapping) { + addClass(cm.display.wrapper, "CodeMirror-wrap"); + cm.display.sizer.style.minWidth = ""; + cm.display.sizerWidth = null; + } else { + rmClass(cm.display.wrapper, "CodeMirror-wrap"); + findMaxLine(cm); + } + estimateLineHeights(cm); + regChange(cm); + clearCaches(cm); + setTimeout(function(){updateScrollbars(cm);}, 100); + } + + // Returns a function that estimates the height of a line, to use as + // first approximation until the line becomes visible (and is thus + // properly measurable). + function estimateHeight(cm) { + var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; + var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); + return function(line) { + if (lineIsHidden(cm.doc, line)) return 0; + + var widgetsHeight = 0; + if (line.widgets) for (var i = 0; i < line.widgets.length; i++) { + if (line.widgets[i].height) widgetsHeight += line.widgets[i].height; + } + + if (wrapping) + return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th; + else + return widgetsHeight + th; + }; + } + + function estimateLineHeights(cm) { + var doc = cm.doc, est = estimateHeight(cm); + doc.iter(function(line) { + var estHeight = est(line); + if (estHeight != line.height) updateLineHeight(line, estHeight); + }); + } + + function themeChanged(cm) { + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); + clearCaches(cm); + } + + function guttersChanged(cm) { + updateGutters(cm); + regChange(cm); + setTimeout(function(){alignHorizontally(cm);}, 20); + } + + // Rebuild the gutter elements, ensure the margin to the left of the + // code matches their width. + function updateGutters(cm) { + var gutters = cm.display.gutters, specs = cm.options.gutters; + removeChildren(gutters); + for (var i = 0; i < specs.length; ++i) { + var gutterClass = specs[i]; + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); + if (gutterClass == "CodeMirror-linenumbers") { + cm.display.lineGutter = gElt; + gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; + } + } + gutters.style.display = i ? "" : "none"; + updateGutterSpace(cm); + } + + function updateGutterSpace(cm) { + var width = cm.display.gutters.offsetWidth; + cm.display.sizer.style.marginLeft = width + "px"; + } + + // Compute the character length of a line, taking into account + // collapsed ranges (see markText) that might hide parts, and join + // other lines onto it. + function lineLength(line) { + if (line.height == 0) return 0; + var len = line.text.length, merged, cur = line; + while (merged = collapsedSpanAtStart(cur)) { + var found = merged.find(0, true); + cur = found.from.line; + len += found.from.ch - found.to.ch; + } + cur = line; + while (merged = collapsedSpanAtEnd(cur)) { + var found = merged.find(0, true); + len -= cur.text.length - found.from.ch; + cur = found.to.line; + len += cur.text.length - found.to.ch; + } + return len; + } + + // Find the longest line in the document. + function findMaxLine(cm) { + var d = cm.display, doc = cm.doc; + d.maxLine = getLine(doc, doc.first); + d.maxLineLength = lineLength(d.maxLine); + d.maxLineChanged = true; + doc.iter(function(line) { + var len = lineLength(line); + if (len > d.maxLineLength) { + d.maxLineLength = len; + d.maxLine = line; + } + }); + } + + // Make sure the gutters options contains the element + // "CodeMirror-linenumbers" when the lineNumbers option is true. + function setGuttersForLineNumbers(options) { + var found = indexOf(options.gutters, "CodeMirror-linenumbers"); + if (found == -1 && options.lineNumbers) { + options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); + } else if (found > -1 && !options.lineNumbers) { + options.gutters = options.gutters.slice(0); + options.gutters.splice(found, 1); + } + } + + // SCROLLBARS + + // Prepare DOM reads needed to update the scrollbars. Done in one + // shot to minimize update/measure roundtrips. + function measureForScrollbars(cm) { + var d = cm.display, gutterW = d.gutters.offsetWidth; + var docH = Math.round(cm.doc.height + paddingVert(cm.display)); + return { + clientHeight: d.scroller.clientHeight, + viewHeight: d.wrapper.clientHeight, + scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, + viewWidth: d.wrapper.clientWidth, + barLeft: cm.options.fixedGutter ? gutterW : 0, + docHeight: docH, + scrollHeight: docH + scrollGap(cm) + d.barHeight, + nativeBarWidth: d.nativeBarWidth, + gutterWidth: gutterW + }; + } + + function NativeScrollbars(place, scroll, cm) { + this.cm = cm; + var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); + var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); + place(vert); place(horiz); + + on(vert, "scroll", function() { + if (vert.clientHeight) scroll(vert.scrollTop, "vertical"); + }); + on(horiz, "scroll", function() { + if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal"); + }); + + this.checkedZeroWidth = false; + // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). + if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; + } + + NativeScrollbars.prototype = copyObj({ + update: function(measure) { + var needsH = measure.scrollWidth > measure.clientWidth + 1; + var needsV = measure.scrollHeight > measure.clientHeight + 1; + var sWidth = measure.nativeBarWidth; + + if (needsV) { + this.vert.style.display = "block"; + this.vert.style.bottom = needsH ? sWidth + "px" : "0"; + var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); + // A bug in IE8 can cause this value to be negative, so guard it. + this.vert.firstChild.style.height = + Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; + } else { + this.vert.style.display = ""; + this.vert.firstChild.style.height = "0"; + } + + if (needsH) { + this.horiz.style.display = "block"; + this.horiz.style.right = needsV ? sWidth + "px" : "0"; + this.horiz.style.left = measure.barLeft + "px"; + var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); + this.horiz.firstChild.style.width = + (measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; + } else { + this.horiz.style.display = ""; + this.horiz.firstChild.style.width = "0"; + } + + if (!this.checkedZeroWidth && measure.clientHeight > 0) { + if (sWidth == 0) this.zeroWidthHack(); + this.checkedZeroWidth = true; + } + + return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}; + }, + setScrollLeft: function(pos) { + if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos; + if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz); + }, + setScrollTop: function(pos) { + if (this.vert.scrollTop != pos) this.vert.scrollTop = pos; + if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert); + }, + zeroWidthHack: function() { + var w = mac && !mac_geMountainLion ? "12px" : "18px"; + this.horiz.style.height = this.vert.style.width = w; + this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; + this.disableHoriz = new Delayed; + this.disableVert = new Delayed; + }, + enableZeroWidthBar: function(bar, delay) { + bar.style.pointerEvents = "auto"; + function maybeDisable() { + // To find out whether the scrollbar is still visible, we + // check whether the element under the pixel in the bottom + // left corner of the scrollbar box is the scrollbar box + // itself (when the bar is still visible) or its filler child + // (when the bar is hidden). If it is still visible, we keep + // it enabled, if it's hidden, we disable pointer events. + var box = bar.getBoundingClientRect(); + var elt = document.elementFromPoint(box.left + 1, box.bottom - 1); + if (elt != bar) bar.style.pointerEvents = "none"; + else delay.set(1000, maybeDisable); + } + delay.set(1000, maybeDisable); + }, + clear: function() { + var parent = this.horiz.parentNode; + parent.removeChild(this.horiz); + parent.removeChild(this.vert); + } + }, NativeScrollbars.prototype); + + function NullScrollbars() {} + + NullScrollbars.prototype = copyObj({ + update: function() { return {bottom: 0, right: 0}; }, + setScrollLeft: function() {}, + setScrollTop: function() {}, + clear: function() {} + }, NullScrollbars.prototype); + + CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; + + function initScrollbars(cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear(); + if (cm.display.scrollbars.addClass) + rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); + } + + cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) { + cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); + // Prevent clicks in the scrollbars from killing focus + on(node, "mousedown", function() { + if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0); + }); + node.setAttribute("cm-not-content", "true"); + }, function(pos, axis) { + if (axis == "horizontal") setScrollLeft(cm, pos); + else setScrollTop(cm, pos); + }, cm); + if (cm.display.scrollbars.addClass) + addClass(cm.display.wrapper, cm.display.scrollbars.addClass); + } + + function updateScrollbars(cm, measure) { + if (!measure) measure = measureForScrollbars(cm); + var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; + updateScrollbarsInner(cm, measure); + for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { + if (startWidth != cm.display.barWidth && cm.options.lineWrapping) + updateHeightsInViewport(cm); + updateScrollbarsInner(cm, measureForScrollbars(cm)); + startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; + } + } + + // Re-synchronize the fake scrollbars with the actual size of the + // content. + function updateScrollbarsInner(cm, measure) { + var d = cm.display; + var sizes = d.scrollbars.update(measure); + + d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; + d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; + d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent" + + if (sizes.right && sizes.bottom) { + d.scrollbarFiller.style.display = "block"; + d.scrollbarFiller.style.height = sizes.bottom + "px"; + d.scrollbarFiller.style.width = sizes.right + "px"; + } else d.scrollbarFiller.style.display = ""; + if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { + d.gutterFiller.style.display = "block"; + d.gutterFiller.style.height = sizes.bottom + "px"; + d.gutterFiller.style.width = measure.gutterWidth + "px"; + } else d.gutterFiller.style.display = ""; + } + + // Compute the lines that are visible in a given viewport (defaults + // the the current scroll position). viewport may contain top, + // height, and ensure (see op.scrollToPos) properties. + function visibleLines(display, doc, viewport) { + var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; + top = Math.floor(top - paddingTop(display)); + var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; + + var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); + // Ensure is a {from: {line, ch}, to: {line, ch}} object, and + // forces those lines into the viewport (if possible). + if (viewport && viewport.ensure) { + var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; + if (ensureFrom < from) { + from = ensureFrom; + to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); + } else if (Math.min(ensureTo, doc.lastLine()) >= to) { + from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); + to = ensureTo; + } + } + return {from: from, to: Math.max(to, from + 1)}; + } + + // LINE NUMBERS + + // Re-align line numbers and gutter marks to compensate for + // horizontal scrolling. + function alignHorizontally(cm) { + var display = cm.display, view = display.view; + if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; + var gutterW = display.gutters.offsetWidth, left = comp + "px"; + for (var i = 0; i < view.length; i++) if (!view[i].hidden) { + if (cm.options.fixedGutter && view[i].gutter) + view[i].gutter.style.left = left; + var align = view[i].alignable; + if (align) for (var j = 0; j < align.length; j++) + align[j].style.left = left; + } + if (cm.options.fixedGutter) + display.gutters.style.left = (comp + gutterW) + "px"; + } + + // Used to ensure that the line number gutter is still the right + // size for the current document size. Returns true when an update + // is needed. + function maybeUpdateLineNumberWidth(cm) { + if (!cm.options.lineNumbers) return false; + var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild(elt("div", [elt("div", last)], + "CodeMirror-linenumber CodeMirror-gutter-elt")); + var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; + display.lineGutter.style.width = ""; + display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; + display.lineNumWidth = display.lineNumInnerWidth + padding; + display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; + display.lineGutter.style.width = display.lineNumWidth + "px"; + updateGutterSpace(cm); + return true; + } + return false; + } + + function lineNumberFor(options, i) { + return String(options.lineNumberFormatter(i + options.firstLineNumber)); + } + + // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, + // but using getBoundingClientRect to get a sub-pixel-accurate + // result. + function compensateForHScroll(display) { + return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; + } + + // DISPLAY DRAWING + + function DisplayUpdate(cm, viewport, force) { + var display = cm.display; + + this.viewport = viewport; + // Store some values that we'll need later (but don't want to force a relayout for) + this.visible = visibleLines(display, cm.doc, viewport); + this.editorIsHidden = !display.wrapper.offsetWidth; + this.wrapperHeight = display.wrapper.clientHeight; + this.wrapperWidth = display.wrapper.clientWidth; + this.oldDisplayWidth = displayWidth(cm); + this.force = force; + this.dims = getDimensions(cm); + this.events = []; + } + + DisplayUpdate.prototype.signal = function(emitter, type) { + if (hasHandler(emitter, type)) + this.events.push(arguments); + }; + DisplayUpdate.prototype.finish = function() { + for (var i = 0; i < this.events.length; i++) + signal.apply(null, this.events[i]); + }; + + function maybeClipScrollbars(cm) { + var display = cm.display; + if (!display.scrollbarsClipped && display.scroller.offsetWidth) { + display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; + display.heightForcer.style.height = scrollGap(cm) + "px"; + display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; + display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; + display.scrollbarsClipped = true; + } + } + + // Does the actual updating of the line display. Bails out + // (returning false) when there is nothing to be done and forced is + // false. + function updateDisplayIfNeeded(cm, update) { + var display = cm.display, doc = cm.doc; + + if (update.editorIsHidden) { + resetView(cm); + return false; + } + + // Bail out if the visible area is already rendered and nothing changed. + if (!update.force && + update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && + display.renderedView == display.view && countDirtyView(cm) == 0) + return false; + + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm); + update.dims = getDimensions(cm); + } + + // Compute a suitable new viewport (from & to) + var end = doc.first + doc.size; + var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); + var to = Math.min(end, update.visible.to + cm.options.viewportMargin); + if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom); + if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo); + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from); + to = visualLineEndNo(cm.doc, to); + } + + var different = from != display.viewFrom || to != display.viewTo || + display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; + adjustView(cm, from, to); + + display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); + // Position the mover div to align with the current scroll position + cm.display.mover.style.top = display.viewOffset + "px"; + + var toUpdate = countDirtyView(cm); + if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) + return false; + + // For big changes, we hide the enclosing element during the + // update, since that speeds up the operations on most browsers. + var focused = activeElt(); + if (toUpdate > 4) display.lineDiv.style.display = "none"; + patchDisplay(cm, display.updateLineNumbers, update.dims); + if (toUpdate > 4) display.lineDiv.style.display = ""; + display.renderedView = display.view; + // There might have been a widget with a focused element that got + // hidden or updated, if so re-focus it. + if (focused && activeElt() != focused && focused.offsetHeight) focused.focus(); + + // Prevent selection and cursors from interfering with the scroll + // width and height. + removeChildren(display.cursorDiv); + removeChildren(display.selectionDiv); + display.gutters.style.height = display.sizer.style.minHeight = 0; + + if (different) { + display.lastWrapHeight = update.wrapperHeight; + display.lastWrapWidth = update.wrapperWidth; + startWorker(cm, 400); + } + + display.updateLineNumbers = null; + + return true; + } + + function postUpdateDisplay(cm, update) { + var viewport = update.viewport; + + for (var first = true;; first = false) { + if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { + // Clip forced viewport to actual scrollable area. + if (viewport && viewport.top != null) + viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; + // Updated line heights might result in the drawn area not + // actually covering the viewport. Keep looping until it does. + update.visible = visibleLines(cm.display, cm.doc, viewport); + if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) + break; + } + if (!updateDisplayIfNeeded(cm, update)) break; + updateHeightsInViewport(cm); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + updateScrollbars(cm, barMeasure); + setDocumentHeight(cm, barMeasure); + } + + update.signal(cm, "update", cm); + if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { + update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); + cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; + } + } + + function updateDisplaySimple(cm, viewport) { + var update = new DisplayUpdate(cm, viewport); + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm); + postUpdateDisplay(cm, update); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + updateScrollbars(cm, barMeasure); + setDocumentHeight(cm, barMeasure); + update.finish(); + } + } + + function setDocumentHeight(cm, measure) { + cm.display.sizer.style.minHeight = measure.docHeight + "px"; + cm.display.heightForcer.style.top = measure.docHeight + "px"; + cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"; + } + + // Read the actual heights of the rendered lines, and update their + // stored heights to match. + function updateHeightsInViewport(cm) { + var display = cm.display; + var prevBottom = display.lineDiv.offsetTop; + for (var i = 0; i < display.view.length; i++) { + var cur = display.view[i], height; + if (cur.hidden) continue; + if (ie && ie_version < 8) { + var bot = cur.node.offsetTop + cur.node.offsetHeight; + height = bot - prevBottom; + prevBottom = bot; + } else { + var box = cur.node.getBoundingClientRect(); + height = box.bottom - box.top; + } + var diff = cur.line.height - height; + if (height < 2) height = textHeight(display); + if (diff > .001 || diff < -.001) { + updateLineHeight(cur.line, height); + updateWidgetHeight(cur.line); + if (cur.rest) for (var j = 0; j < cur.rest.length; j++) + updateWidgetHeight(cur.rest[j]); + } + } + } + + // Read and store the height of line widgets associated with the + // given line. + function updateWidgetHeight(line) { + if (line.widgets) for (var i = 0; i < line.widgets.length; ++i) + line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight; + } + + // Do a bulk-read of the DOM positions and sizes needed to draw the + // view, so that we don't interleave reading and writing to the DOM. + function getDimensions(cm) { + var d = cm.display, left = {}, width = {}; + var gutterLeft = d.gutters.clientLeft; + for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { + left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; + width[cm.options.gutters[i]] = n.clientWidth; + } + return {fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth}; + } + + // Sync the actual display DOM structure with display.view, removing + // nodes for lines that are no longer in view, and creating the ones + // that are not there yet, and updating the ones that are out of + // date. + function patchDisplay(cm, updateNumbersFrom, dims) { + var display = cm.display, lineNumbers = cm.options.lineNumbers; + var container = display.lineDiv, cur = container.firstChild; + + function rm(node) { + var next = node.nextSibling; + // Works around a throw-scroll bug in OS X Webkit + if (webkit && mac && cm.display.currentWheelTarget == node) + node.style.display = "none"; + else + node.parentNode.removeChild(node); + return next; + } + + var view = display.view, lineN = display.viewFrom; + // Loop over the elements in the view, syncing cur (the DOM nodes + // in display.lineDiv) with the view as we go. + for (var i = 0; i < view.length; i++) { + var lineView = view[i]; + if (lineView.hidden) { + } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet + var node = buildLineElement(cm, lineView, lineN, dims); + container.insertBefore(node, cur); + } else { // Already drawn + while (cur != lineView.node) cur = rm(cur); + var updateNumber = lineNumbers && updateNumbersFrom != null && + updateNumbersFrom <= lineN && lineView.lineNumber; + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false; + updateLineForChanges(cm, lineView, lineN, dims); + } + if (updateNumber) { + removeChildren(lineView.lineNumber); + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); + } + cur = lineView.node.nextSibling; + } + lineN += lineView.size; + } + while (cur) cur = rm(cur); + } + + // When an aspect of a line changes, a string is added to + // lineView.changes. This updates the relevant part of the line's + // DOM structure. + function updateLineForChanges(cm, lineView, lineN, dims) { + for (var j = 0; j < lineView.changes.length; j++) { + var type = lineView.changes[j]; + if (type == "text") updateLineText(cm, lineView); + else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims); + else if (type == "class") updateLineClasses(lineView); + else if (type == "widget") updateLineWidgets(cm, lineView, dims); + } + lineView.changes = null; + } + + // Lines with gutter elements, widgets or a background class need to + // be wrapped, and have the extra elements added to the wrapper div + function ensureLineWrapped(lineView) { + if (lineView.node == lineView.text) { + lineView.node = elt("div", null, null, "position: relative"); + if (lineView.text.parentNode) + lineView.text.parentNode.replaceChild(lineView.node, lineView.text); + lineView.node.appendChild(lineView.text); + if (ie && ie_version < 8) lineView.node.style.zIndex = 2; + } + return lineView.node; + } + + function updateLineBackground(lineView) { + var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; + if (cls) cls += " CodeMirror-linebackground"; + if (lineView.background) { + if (cls) lineView.background.className = cls; + else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } + } else if (cls) { + var wrap = ensureLineWrapped(lineView); + lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); + } + } + + // Wrapper around buildLineContent which will reuse the structure + // in display.externalMeasured when possible. + function getLineContent(cm, lineView) { + var ext = cm.display.externalMeasured; + if (ext && ext.line == lineView.line) { + cm.display.externalMeasured = null; + lineView.measure = ext.measure; + return ext.built; + } + return buildLineContent(cm, lineView); + } + + // Redraw the line's text. Interacts with the background and text + // classes because the mode may output tokens that influence these + // classes. + function updateLineText(cm, lineView) { + var cls = lineView.text.className; + var built = getLineContent(cm, lineView); + if (lineView.text == lineView.node) lineView.node = built.pre; + lineView.text.parentNode.replaceChild(built.pre, lineView.text); + lineView.text = built.pre; + if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { + lineView.bgClass = built.bgClass; + lineView.textClass = built.textClass; + updateLineClasses(lineView); + } else if (cls) { + lineView.text.className = cls; + } + } + + function updateLineClasses(lineView) { + updateLineBackground(lineView); + if (lineView.line.wrapClass) + ensureLineWrapped(lineView).className = lineView.line.wrapClass; + else if (lineView.node != lineView.text) + lineView.node.className = ""; + var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; + lineView.text.className = textClass || ""; + } + + function updateLineGutter(cm, lineView, lineN, dims) { + if (lineView.gutter) { + lineView.node.removeChild(lineView.gutter); + lineView.gutter = null; + } + if (lineView.gutterBackground) { + lineView.node.removeChild(lineView.gutterBackground); + lineView.gutterBackground = null; + } + if (lineView.line.gutterClass) { + var wrap = ensureLineWrapped(lineView); + lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, + "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + + "px; width: " + dims.gutterTotalWidth + "px"); + wrap.insertBefore(lineView.gutterBackground, lineView.text); + } + var markers = lineView.line.gutterMarkers; + if (cm.options.lineNumbers || markers) { + var wrap = ensureLineWrapped(lineView); + var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"); + cm.display.input.setUneditable(gutterWrap); + wrap.insertBefore(gutterWrap, lineView.text); + if (lineView.line.gutterClass) + gutterWrap.className += " " + lineView.line.gutterClass; + if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) + lineView.lineNumber = gutterWrap.appendChild( + elt("div", lineNumberFor(cm.options, lineN), + "CodeMirror-linenumber CodeMirror-gutter-elt", + "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + + cm.display.lineNumInnerWidth + "px")); + if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) { + var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; + if (found) + gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); + } + } + } + + function updateLineWidgets(cm, lineView, dims) { + if (lineView.alignable) lineView.alignable = null; + for (var node = lineView.node.firstChild, next; node; node = next) { + var next = node.nextSibling; + if (node.className == "CodeMirror-linewidget") + lineView.node.removeChild(node); + } + insertLineWidgets(cm, lineView, dims); + } + + // Build a line's DOM representation from scratch + function buildLineElement(cm, lineView, lineN, dims) { + var built = getLineContent(cm, lineView); + lineView.text = lineView.node = built.pre; + if (built.bgClass) lineView.bgClass = built.bgClass; + if (built.textClass) lineView.textClass = built.textClass; + + updateLineClasses(lineView); + updateLineGutter(cm, lineView, lineN, dims); + insertLineWidgets(cm, lineView, dims); + return lineView.node; + } + + // A lineView may contain multiple logical lines (when merged by + // collapsed spans). The widgets for all of them need to be drawn. + function insertLineWidgets(cm, lineView, dims) { + insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); + if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) + insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); + } + + function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { + if (!line.widgets) return; + var wrap = ensureLineWrapped(lineView); + for (var i = 0, ws = line.widgets; i < ws.length; ++i) { + var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); + if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true"); + positionLineWidget(widget, node, lineView, dims); + cm.display.input.setUneditable(node); + if (allowAbove && widget.above) + wrap.insertBefore(node, lineView.gutter || lineView.text); + else + wrap.appendChild(node); + signalLater(widget, "redraw"); + } + } + + function positionLineWidget(widget, node, lineView, dims) { + if (widget.noHScroll) { + (lineView.alignable || (lineView.alignable = [])).push(node); + var width = dims.wrapperWidth; + node.style.left = dims.fixedPos + "px"; + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth; + node.style.paddingLeft = dims.gutterTotalWidth + "px"; + } + node.style.width = width + "px"; + } + if (widget.coverGutter) { + node.style.zIndex = 5; + node.style.position = "relative"; + if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; + } + } + + // POSITION OBJECT + + // A Pos instance represents a position within the text. + var Pos = CodeMirror.Pos = function(line, ch) { + if (!(this instanceof Pos)) return new Pos(line, ch); + this.line = line; this.ch = ch; + }; + + // Compare two positions, return 0 if they are the same, a negative + // number when a is less, and a positive number otherwise. + var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; }; + + function copyPos(x) {return Pos(x.line, x.ch);} + function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; } + function minPos(a, b) { return cmp(a, b) < 0 ? a : b; } + + // INPUT HANDLING + + function ensureFocus(cm) { + if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } + } + + // This will be set to a {lineWise: bool, text: [string]} object, so + // that, when pasting, we know what kind of selections the copied + // text was made out of. + var lastCopied = null; + + function applyTextInput(cm, inserted, deleted, sel, origin) { + var doc = cm.doc; + cm.display.shift = false; + if (!sel) sel = doc.sel; + + var paste = cm.state.pasteIncoming || origin == "paste"; + var textLines = doc.splitLines(inserted), multiPaste = null + // When pasing N lines into N selections, insert one line per selection + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.text.join("\n") == inserted) { + if (sel.ranges.length % lastCopied.text.length == 0) { + multiPaste = []; + for (var i = 0; i < lastCopied.text.length; i++) + multiPaste.push(doc.splitLines(lastCopied.text[i])); + } + } else if (textLines.length == sel.ranges.length) { + multiPaste = map(textLines, function(l) { return [l]; }); + } + } + + // Normal behavior is to insert the new text into every selection + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i]; + var from = range.from(), to = range.to(); + if (range.empty()) { + if (deleted && deleted > 0) // Handle deletion + from = Pos(from.line, from.ch - deleted); + else if (cm.state.overwrite && !paste) // Handle overwrite + to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); + else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) + from = to = Pos(from.line, 0) + } + var updateInput = cm.curOp.updateInput; + var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; + makeChange(cm.doc, changeEvent); + signalLater(cm, "inputRead", cm, changeEvent); + } + if (inserted && !paste) + triggerElectric(cm, inserted); + + ensureCursorVisible(cm); + cm.curOp.updateInput = updateInput; + cm.curOp.typing = true; + cm.state.pasteIncoming = cm.state.cutIncoming = false; + } + + function handlePaste(e, cm) { + var pasted = e.clipboardData && e.clipboardData.getData("text/plain"); + if (pasted) { + e.preventDefault(); + if (!cm.isReadOnly() && !cm.options.disableInput) + runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); }); + return true; + } + } + + function triggerElectric(cm, inserted) { + // When an 'electric' character is inserted, immediately trigger a reindent + if (!cm.options.electricChars || !cm.options.smartIndent) return; + var sel = cm.doc.sel; + + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i]; + if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue; + var mode = cm.getModeAt(range.head); + var indented = false; + if (mode.electricChars) { + for (var j = 0; j < mode.electricChars.length; j++) + if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range.head.line, "smart"); + break; + } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) + indented = indentLine(cm, range.head.line, "smart"); + } + if (indented) signalLater(cm, "electricInput", cm, range.head.line); + } + } + + function copyableRanges(cm) { + var text = [], ranges = []; + for (var i = 0; i < cm.doc.sel.ranges.length; i++) { + var line = cm.doc.sel.ranges[i].head.line; + var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; + ranges.push(lineRange); + text.push(cm.getRange(lineRange.anchor, lineRange.head)); + } + return {text: text, ranges: ranges}; + } + + function disableBrowserMagic(field) { + field.setAttribute("autocorrect", "off"); + field.setAttribute("autocapitalize", "off"); + field.setAttribute("spellcheck", "false"); + } + + // TEXTAREA INPUT STYLE + + function TextareaInput(cm) { + this.cm = cm; + // See input.poll and input.reset + this.prevInput = ""; + + // Flag that indicates whether we expect input to appear real soon + // now (after some event like 'keypress' or 'input') and are + // polling intensively. + this.pollingFast = false; + // Self-resetting timeout for the poller + this.polling = new Delayed(); + // Tracks when input.reset has punted to just putting a short + // string into the textarea instead of the full selection. + this.inaccurateSelection = false; + // Used to work around IE issue with selection being forgotten when focus moves away from textarea + this.hasSelection = false; + this.composing = null; + }; + + function hiddenTextarea() { + var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none"); + var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); + // The textarea is kept positioned near the cursor to prevent the + // fact that it'll be scrolled into view on input from scrolling + // our fake cursor out of view. On webkit, when wrap=off, paste is + // very slow. So make the area wide instead. + if (webkit) te.style.width = "1000px"; + else te.setAttribute("wrap", "off"); + // If border: 0; -- iOS fails to open keyboard (issue #1287) + if (ios) te.style.border = "1px solid black"; + disableBrowserMagic(te); + return div; + } + + TextareaInput.prototype = copyObj({ + init: function(display) { + var input = this, cm = this.cm; + + // Wraps and hides input textarea + var div = this.wrapper = hiddenTextarea(); + // The semihidden textarea that is focused when the editor is + // focused, and receives input. + var te = this.textarea = div.firstChild; + display.wrapper.insertBefore(div, display.wrapper.firstChild); + + // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) + if (ios) te.style.width = "0px"; + + on(te, "input", function() { + if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null; + input.poll(); + }); + + on(te, "paste", function(e) { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return + + cm.state.pasteIncoming = true; + input.fastPoll(); + }); + + function prepareCopyCut(e) { + if (signalDOMEvent(cm, e)) return + if (cm.somethingSelected()) { + lastCopied = {lineWise: false, text: cm.getSelections()}; + if (input.inaccurateSelection) { + input.prevInput = ""; + input.inaccurateSelection = false; + te.value = lastCopied.text.join("\n"); + selectInput(te); + } + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + lastCopied = {lineWise: true, text: ranges.text}; + if (e.type == "cut") { + cm.setSelections(ranges.ranges, null, sel_dontScroll); + } else { + input.prevInput = ""; + te.value = ranges.text.join("\n"); + selectInput(te); + } + } + if (e.type == "cut") cm.state.cutIncoming = true; + } + on(te, "cut", prepareCopyCut); + on(te, "copy", prepareCopyCut); + + on(display.scroller, "paste", function(e) { + if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return; + cm.state.pasteIncoming = true; + input.focus(); + }); + + // Prevent normal selection in the editor (we handle our own) + on(display.lineSpace, "selectstart", function(e) { + if (!eventInWidget(display, e)) e_preventDefault(e); + }); + + on(te, "compositionstart", function() { + var start = cm.getCursor("from"); + if (input.composing) input.composing.range.clear() + input.composing = { + start: start, + range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) + }; + }); + on(te, "compositionend", function() { + if (input.composing) { + input.poll(); + input.composing.range.clear(); + input.composing = null; + } + }); + }, + + prepareSelection: function() { + // Redraw the selection and/or cursor + var cm = this.cm, display = cm.display, doc = cm.doc; + var result = prepareSelection(cm); + + // Move the hidden textarea near the cursor to prevent scrolling artifacts + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); + var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); + result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, + headPos.top + lineOff.top - wrapOff.top)); + result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, + headPos.left + lineOff.left - wrapOff.left)); + } + + return result; + }, + + showSelection: function(drawn) { + var cm = this.cm, display = cm.display; + removeChildrenAndAdd(display.cursorDiv, drawn.cursors); + removeChildrenAndAdd(display.selectionDiv, drawn.selection); + if (drawn.teTop != null) { + this.wrapper.style.top = drawn.teTop + "px"; + this.wrapper.style.left = drawn.teLeft + "px"; + } + }, + + // Reset the input to correspond to the selection (or to be empty, + // when not typing and nothing is selected) + reset: function(typing) { + if (this.contextMenuPending) return; + var minimal, selected, cm = this.cm, doc = cm.doc; + if (cm.somethingSelected()) { + this.prevInput = ""; + var range = doc.sel.primary(); + minimal = hasCopyEvent && + (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000); + var content = minimal ? "-" : selected || cm.getSelection(); + this.textarea.value = content; + if (cm.state.focused) selectInput(this.textarea); + if (ie && ie_version >= 9) this.hasSelection = content; + } else if (!typing) { + this.prevInput = this.textarea.value = ""; + if (ie && ie_version >= 9) this.hasSelection = null; + } + this.inaccurateSelection = minimal; + }, + + getField: function() { return this.textarea; }, + + supportsTouch: function() { return false; }, + + focus: function() { + if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { + try { this.textarea.focus(); } + catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM + } + }, + + blur: function() { this.textarea.blur(); }, + + resetPosition: function() { + this.wrapper.style.top = this.wrapper.style.left = 0; + }, + + receivedFocus: function() { this.slowPoll(); }, + + // Poll for input changes, using the normal rate of polling. This + // runs as long as the editor is focused. + slowPoll: function() { + var input = this; + if (input.pollingFast) return; + input.polling.set(this.cm.options.pollInterval, function() { + input.poll(); + if (input.cm.state.focused) input.slowPoll(); + }); + }, + + // When an event has just come in that is likely to add or change + // something in the input textarea, we poll faster, to ensure that + // the change appears on the screen quickly. + fastPoll: function() { + var missed = false, input = this; + input.pollingFast = true; + function p() { + var changed = input.poll(); + if (!changed && !missed) {missed = true; input.polling.set(60, p);} + else {input.pollingFast = false; input.slowPoll();} + } + input.polling.set(20, p); + }, + + // Read input from the textarea, and update the document to match. + // When something is selected, it is present in the textarea, and + // selected (unless it is huge, in which case a placeholder is + // used). When nothing is selected, the cursor sits after previously + // seen text (can be empty), which is stored in prevInput (we must + // not reset the textarea when typing, because that breaks IME). + poll: function() { + var cm = this.cm, input = this.textarea, prevInput = this.prevInput; + // Since this is called a *lot*, try to bail out as cheaply as + // possible when it is clear that nothing happened. hasSelection + // will be the case when there is a lot of text in the textarea, + // in which case reading its value would be expensive. + if (this.contextMenuPending || !cm.state.focused || + (hasSelection(input) && !prevInput && !this.composing) || + cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) + return false; + + var text = input.value; + // If nothing changed, bail. + if (text == prevInput && !cm.somethingSelected()) return false; + // Work around nonsensical selection resetting in IE9/10, and + // inexplicable appearance of private area unicode characters on + // some key combos in Mac (#2689). + if (ie && ie_version >= 9 && this.hasSelection === text || + mac && /[\uf700-\uf7ff]/.test(text)) { + cm.display.input.reset(); + return false; + } + + if (cm.doc.sel == cm.display.selForContextMenu) { + var first = text.charCodeAt(0); + if (first == 0x200b && !prevInput) prevInput = "\u200b"; + if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); } + } + // Find the part of the input that is actually new + var same = 0, l = Math.min(prevInput.length, text.length); + while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; + + var self = this; + runInOp(cm, function() { + applyTextInput(cm, text.slice(same), prevInput.length - same, + null, self.composing ? "*compose" : null); + + // Don't leave long text in the textarea, since it makes further polling slow + if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = ""; + else self.prevInput = text; + + if (self.composing) { + self.composing.range.clear(); + self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"), + {className: "CodeMirror-composing"}); + } + }); + return true; + }, + + ensurePolled: function() { + if (this.pollingFast && this.poll()) this.pollingFast = false; + }, + + onKeyPress: function() { + if (ie && ie_version >= 9) this.hasSelection = null; + this.fastPoll(); + }, + + onContextMenu: function(e) { + var input = this, cm = input.cm, display = cm.display, te = input.textarea; + var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; + if (!pos || presto) return; // Opera is difficult. + + // Reset the current text selection only if the click is done outside of the selection + // and 'resetSelectionOnContextMenu' option is true. + var reset = cm.options.resetSelectionOnContextMenu; + if (reset && cm.doc.sel.contains(pos) == -1) + operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); + + var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText; + input.wrapper.style.cssText = "position: absolute" + var wrapperBox = input.wrapper.getBoundingClientRect() + te.style.cssText = "position: absolute; width: 30px; height: 30px; top: " + (e.clientY - wrapperBox.top - 5) + + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px; z-index: 1000; background: " + + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + + "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; + if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712) + display.input.focus(); + if (webkit) window.scrollTo(null, oldScrollY); + display.input.reset(); + // Adds "Select all" to context menu in FF + if (!cm.somethingSelected()) te.value = input.prevInput = " "; + input.contextMenuPending = true; + display.selForContextMenu = cm.doc.sel; + clearTimeout(display.detectingSelectAll); + + // Select-all will be greyed out if there's nothing to select, so + // this adds a zero-width space so that we can later check whether + // it got selected. + function prepareSelectAllHack() { + if (te.selectionStart != null) { + var selected = cm.somethingSelected(); + var extval = "\u200b" + (selected ? te.value : ""); + te.value = "\u21da"; // Used to catch context-menu undo + te.value = extval; + input.prevInput = selected ? "" : "\u200b"; + te.selectionStart = 1; te.selectionEnd = extval.length; + // Re-set this, in case some other handler touched the + // selection in the meantime. + display.selForContextMenu = cm.doc.sel; + } + } + function rehide() { + input.contextMenuPending = false; + input.wrapper.style.cssText = oldWrapperCSS + te.style.cssText = oldCSS; + if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); + + // Try to detect the user choosing select-all + if (te.selectionStart != null) { + if (!ie || (ie && ie_version < 9)) prepareSelectAllHack(); + var i = 0, poll = function() { + if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && + te.selectionEnd > 0 && input.prevInput == "\u200b") + operation(cm, commands.selectAll)(cm); + else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500); + else display.input.reset(); + }; + display.detectingSelectAll = setTimeout(poll, 200); + } + } + + if (ie && ie_version >= 9) prepareSelectAllHack(); + if (captureRightClick) { + e_stop(e); + var mouseup = function() { + off(window, "mouseup", mouseup); + setTimeout(rehide, 20); + }; + on(window, "mouseup", mouseup); + } else { + setTimeout(rehide, 50); + } + }, + + readOnlyChanged: function(val) { + if (!val) this.reset(); + }, + + setUneditable: nothing, + + needsContentAttribute: false + }, TextareaInput.prototype); + + // CONTENTEDITABLE INPUT STYLE + + function ContentEditableInput(cm) { + this.cm = cm; + this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; + this.polling = new Delayed(); + this.gracePeriod = false; + } + + ContentEditableInput.prototype = copyObj({ + init: function(display) { + var input = this, cm = input.cm; + var div = input.div = display.lineDiv; + disableBrowserMagic(div); + + on(div, "paste", function(e) { + if (!signalDOMEvent(cm, e)) handlePaste(e, cm); + }) + + on(div, "compositionstart", function(e) { + var data = e.data; + input.composing = {sel: cm.doc.sel, data: data, startData: data}; + if (!data) return; + var prim = cm.doc.sel.primary(); + var line = cm.getLine(prim.head.line); + var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length)); + if (found > -1 && found <= prim.head.ch) + input.composing.sel = simpleSelection(Pos(prim.head.line, found), + Pos(prim.head.line, found + data.length)); + }); + on(div, "compositionupdate", function(e) { + input.composing.data = e.data; + }); + on(div, "compositionend", function(e) { + var ours = input.composing; + if (!ours) return; + if (e.data != ours.startData && !/\u200b/.test(e.data)) + ours.data = e.data; + // Need a small delay to prevent other code (input event, + // selection polling) from doing damage when fired right after + // compositionend. + setTimeout(function() { + if (!ours.handled) + input.applyComposition(ours); + if (input.composing == ours) + input.composing = null; + }, 50); + }); + + on(div, "touchstart", function() { + input.forceCompositionEnd(); + }); + + on(div, "input", function() { + if (input.composing) return; + if (cm.isReadOnly() || !input.pollContent()) + runInOp(input.cm, function() {regChange(cm);}); + }); + + function onCopyCut(e) { + if (signalDOMEvent(cm, e)) return + if (cm.somethingSelected()) { + lastCopied = {lineWise: false, text: cm.getSelections()}; + if (e.type == "cut") cm.replaceSelection("", null, "cut"); + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + lastCopied = {lineWise: true, text: ranges.text}; + if (e.type == "cut") { + cm.operation(function() { + cm.setSelections(ranges.ranges, 0, sel_dontScroll); + cm.replaceSelection("", null, "cut"); + }); + } + } + // iOS exposes the clipboard API, but seems to discard content inserted into it + if (e.clipboardData && !ios) { + e.preventDefault(); + e.clipboardData.clearData(); + e.clipboardData.setData("text/plain", lastCopied.text.join("\n")); + } else { + // Old-fashioned briefly-focus-a-textarea hack + var kludge = hiddenTextarea(), te = kludge.firstChild; + cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); + te.value = lastCopied.text.join("\n"); + var hadFocus = document.activeElement; + selectInput(te); + setTimeout(function() { + cm.display.lineSpace.removeChild(kludge); + hadFocus.focus(); + }, 50); + } + } + on(div, "copy", onCopyCut); + on(div, "cut", onCopyCut); + }, + + prepareSelection: function() { + var result = prepareSelection(this.cm, false); + result.focus = this.cm.state.focused; + return result; + }, + + showSelection: function(info, takeFocus) { + if (!info || !this.cm.display.view.length) return; + if (info.focus || takeFocus) this.showPrimarySelection(); + this.showMultipleSelections(info); + }, + + showPrimarySelection: function() { + var sel = window.getSelection(), prim = this.cm.doc.sel.primary(); + var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset); + var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset); + if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && + cmp(minPos(curAnchor, curFocus), prim.from()) == 0 && + cmp(maxPos(curAnchor, curFocus), prim.to()) == 0) + return; + + var start = posToDOM(this.cm, prim.from()); + var end = posToDOM(this.cm, prim.to()); + if (!start && !end) return; + + var view = this.cm.display.view; + var old = sel.rangeCount && sel.getRangeAt(0); + if (!start) { + start = {node: view[0].measure.map[2], offset: 0}; + } else if (!end) { // FIXME dangerously hacky + var measure = view[view.length - 1].measure; + var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; + end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}; + } + + try { var rng = range(start.node, start.offset, end.offset, end.node); } + catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible + if (rng) { + if (!gecko && this.cm.state.focused) { + sel.collapse(start.node, start.offset); + if (!rng.collapsed) sel.addRange(rng); + } else { + sel.removeAllRanges(); + sel.addRange(rng); + } + if (old && sel.anchorNode == null) sel.addRange(old); + else if (gecko) this.startGracePeriod(); + } + this.rememberSelection(); + }, + + startGracePeriod: function() { + var input = this; + clearTimeout(this.gracePeriod); + this.gracePeriod = setTimeout(function() { + input.gracePeriod = false; + if (input.selectionChanged()) + input.cm.operation(function() { input.cm.curOp.selectionChanged = true; }); + }, 20); + }, + + showMultipleSelections: function(info) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); + }, + + rememberSelection: function() { + var sel = window.getSelection(); + this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; + this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; + }, + + selectionInEditor: function() { + var sel = window.getSelection(); + if (!sel.rangeCount) return false; + var node = sel.getRangeAt(0).commonAncestorContainer; + return contains(this.div, node); + }, + + focus: function() { + if (this.cm.options.readOnly != "nocursor") this.div.focus(); + }, + blur: function() { this.div.blur(); }, + getField: function() { return this.div; }, + + supportsTouch: function() { return true; }, + + receivedFocus: function() { + var input = this; + if (this.selectionInEditor()) + this.pollSelection(); + else + runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; }); + + function poll() { + if (input.cm.state.focused) { + input.pollSelection(); + input.polling.set(input.cm.options.pollInterval, poll); + } + } + this.polling.set(this.cm.options.pollInterval, poll); + }, + + selectionChanged: function() { + var sel = window.getSelection(); + return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || + sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; + }, + + pollSelection: function() { + if (!this.composing && !this.gracePeriod && this.selectionChanged()) { + var sel = window.getSelection(), cm = this.cm; + this.rememberSelection(); + var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var head = domToPos(cm, sel.focusNode, sel.focusOffset); + if (anchor && head) runInOp(cm, function() { + setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); + if (anchor.bad || head.bad) cm.curOp.selectionChanged = true; + }); + } + }, + + pollContent: function() { + var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); + var from = sel.from(), to = sel.to(); + if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false; + + var fromIndex; + if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { + var fromLine = lineNo(display.view[0].line); + var fromNode = display.view[0].node; + } else { + var fromLine = lineNo(display.view[fromIndex].line); + var fromNode = display.view[fromIndex - 1].node.nextSibling; + } + var toIndex = findViewIndex(cm, to.line); + if (toIndex == display.view.length - 1) { + var toLine = display.viewTo - 1; + var toNode = display.lineDiv.lastChild; + } else { + var toLine = lineNo(display.view[toIndex + 1].line) - 1; + var toNode = display.view[toIndex + 1].node.previousSibling; + } + + var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); + var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } + else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } + else break; + } + + var cutFront = 0, cutEnd = 0; + var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); + while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) + ++cutFront; + var newBot = lst(newText), oldBot = lst(oldText); + var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), + oldBot.length - (oldText.length == 1 ? cutFront : 0)); + while (cutEnd < maxCutEnd && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) + ++cutEnd; + + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd); + newText[0] = newText[0].slice(cutFront); + + var chFrom = Pos(fromLine, cutFront); + var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input"); + return true; + } + }, + + ensurePolled: function() { + this.forceCompositionEnd(); + }, + reset: function() { + this.forceCompositionEnd(); + }, + forceCompositionEnd: function() { + if (!this.composing || this.composing.handled) return; + this.applyComposition(this.composing); + this.composing.handled = true; + this.div.blur(); + this.div.focus(); + }, + applyComposition: function(composing) { + if (this.cm.isReadOnly()) + operation(this.cm, regChange)(this.cm) + else if (composing.data && composing.data != composing.startData) + operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel); + }, + + setUneditable: function(node) { + node.contentEditable = "false" + }, + + onKeyPress: function(e) { + e.preventDefault(); + if (!this.cm.isReadOnly()) + operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); + }, + + readOnlyChanged: function(val) { + this.div.contentEditable = String(val != "nocursor") + }, + + onContextMenu: nothing, + resetPosition: nothing, + + needsContentAttribute: true + }, ContentEditableInput.prototype); + + function posToDOM(cm, pos) { + var view = findViewForLine(cm, pos.line); + if (!view || view.hidden) return null; + var line = getLine(cm.doc, pos.line); + var info = mapFromLineView(view, line, pos.line); + + var order = getOrder(line), side = "left"; + if (order) { + var partPos = getBidiPartAt(order, pos.ch); + side = partPos % 2 ? "right" : "left"; + } + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); + result.offset = result.collapse == "right" ? result.end : result.start; + return result; + } + + function badPos(pos, bad) { if (bad) pos.bad = true; return pos; } + + function domToPos(cm, node, offset) { + var lineNode; + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset]; + if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); + node = null; offset = 0; + } else { + for (lineNode = node;; lineNode = lineNode.parentNode) { + if (!lineNode || lineNode == cm.display.lineDiv) return null; + if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break; + } + } + for (var i = 0; i < cm.display.view.length; i++) { + var lineView = cm.display.view[i]; + if (lineView.node == lineNode) + return locateNodeInLineView(lineView, node, offset); + } + } + + function locateNodeInLineView(lineView, node, offset) { + var wrapper = lineView.text.firstChild, bad = false; + if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true); + if (node == wrapper) { + bad = true; + node = wrapper.childNodes[offset]; + offset = 0; + if (!node) { + var line = lineView.rest ? lst(lineView.rest) : lineView.line; + return badPos(Pos(lineNo(line), line.text.length), bad); + } + } + + var textNode = node.nodeType == 3 ? node : null, topNode = node; + if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { + textNode = node.firstChild; + if (offset) offset = textNode.nodeValue.length; + } + while (topNode.parentNode != wrapper) topNode = topNode.parentNode; + var measure = lineView.measure, maps = measure.maps; + + function find(textNode, topNode, offset) { + for (var i = -1; i < (maps ? maps.length : 0); i++) { + var map = i < 0 ? measure.map : maps[i]; + for (var j = 0; j < map.length; j += 3) { + var curNode = map[j + 2]; + if (curNode == textNode || curNode == topNode) { + var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); + var ch = map[j] + offset; + if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)]; + return Pos(line, ch); + } + } + } + } + var found = find(textNode, topNode, offset); + if (found) return badPos(found, bad); + + // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems + for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { + found = find(after, after.firstChild, 0); + if (found) + return badPos(Pos(found.line, found.ch - dist), bad); + else + dist += after.textContent.length; + } + for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) { + found = find(before, before.firstChild, -1); + if (found) + return badPos(Pos(found.line, found.ch + dist), bad); + else + dist += after.textContent.length; + } + } + + function domTextBetween(cm, from, to, fromLine, toLine) { + var text = "", closing = false, lineSep = cm.doc.lineSeparator(); + function recognizeMarker(id) { return function(marker) { return marker.id == id; }; } + function walk(node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text"); + if (cmText != null) { + if (cmText == "") cmText = node.textContent.replace(/\u200b/g, ""); + text += cmText; + return; + } + var markerID = node.getAttribute("cm-marker"), range; + if (markerID) { + var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); + if (found.length && (range = found[0].find())) + text += getBetween(cm.doc, range.from, range.to).join(lineSep); + return; + } + if (node.getAttribute("contenteditable") == "false") return; + for (var i = 0; i < node.childNodes.length; i++) + walk(node.childNodes[i]); + if (/^(pre|div|p)$/i.test(node.nodeName)) + closing = true; + } else if (node.nodeType == 3) { + var val = node.nodeValue; + if (!val) return; + if (closing) { + text += lineSep; + closing = false; + } + text += val; + } + } + for (;;) { + walk(from); + if (from == to) break; + from = from.nextSibling; + } + return text; + } + + CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; + + // SELECTION / CURSOR + + // Selection objects are immutable. A new one is created every time + // the selection changes. A selection is one or more non-overlapping + // (and non-touching) ranges, sorted, and an integer that indicates + // which one is the primary selection (the one that's scrolled into + // view, that getCursor returns, etc). + function Selection(ranges, primIndex) { + this.ranges = ranges; + this.primIndex = primIndex; + } + + Selection.prototype = { + primary: function() { return this.ranges[this.primIndex]; }, + equals: function(other) { + if (other == this) return true; + if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false; + for (var i = 0; i < this.ranges.length; i++) { + var here = this.ranges[i], there = other.ranges[i]; + if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false; + } + return true; + }, + deepCopy: function() { + for (var out = [], i = 0; i < this.ranges.length; i++) + out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); + return new Selection(out, this.primIndex); + }, + somethingSelected: function() { + for (var i = 0; i < this.ranges.length; i++) + if (!this.ranges[i].empty()) return true; + return false; + }, + contains: function(pos, end) { + if (!end) end = pos; + for (var i = 0; i < this.ranges.length; i++) { + var range = this.ranges[i]; + if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) + return i; + } + return -1; + } + }; + + function Range(anchor, head) { + this.anchor = anchor; this.head = head; + } + + Range.prototype = { + from: function() { return minPos(this.anchor, this.head); }, + to: function() { return maxPos(this.anchor, this.head); }, + empty: function() { + return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; + } + }; + + // Take an unsorted, potentially overlapping set of ranges, and + // build a selection out of it. 'Consumes' ranges array (modifying + // it). + function normalizeSelection(ranges, primIndex) { + var prim = ranges[primIndex]; + ranges.sort(function(a, b) { return cmp(a.from(), b.from()); }); + primIndex = indexOf(ranges, prim); + for (var i = 1; i < ranges.length; i++) { + var cur = ranges[i], prev = ranges[i - 1]; + if (cmp(prev.to(), cur.from()) >= 0) { + var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); + var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; + if (i <= primIndex) --primIndex; + ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); + } + } + return new Selection(ranges, primIndex); + } + + function simpleSelection(anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0); + } + + // Most of the external API clips given positions to make sure they + // actually exist within the document. + function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} + function clipPos(doc, pos) { + if (pos.line < doc.first) return Pos(doc.first, 0); + var last = doc.first + doc.size - 1; + if (pos.line > last) return Pos(last, getLine(doc, last).text.length); + return clipToLen(pos, getLine(doc, pos.line).text.length); + } + function clipToLen(pos, linelen) { + var ch = pos.ch; + if (ch == null || ch > linelen) return Pos(pos.line, linelen); + else if (ch < 0) return Pos(pos.line, 0); + else return pos; + } + function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} + function clipPosArray(doc, array) { + for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]); + return out; + } + + // SELECTION UPDATES + + // The 'scroll' parameter given to many of these indicated whether + // the new cursor position should be scrolled into view after + // modifying the selection. + + // If shift is held or the extend flag is set, extends a range to + // include a given position (and optionally a second position). + // Otherwise, simply returns the range between the given positions. + // Used for cursor motion and such. + function extendRange(doc, range, head, other) { + if (doc.cm && doc.cm.display.shift || doc.extend) { + var anchor = range.anchor; + if (other) { + var posBefore = cmp(head, anchor) < 0; + if (posBefore != (cmp(other, anchor) < 0)) { + anchor = head; + head = other; + } else if (posBefore != (cmp(head, other) < 0)) { + head = other; + } + } + return new Range(anchor, head); + } else { + return new Range(other || head, head); + } + } + + // Extend the primary selection range, discard the rest. + function extendSelection(doc, head, other, options) { + setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options); + } + + // Extend all selections (pos is an array of selections with length + // equal the number of selections) + function extendSelections(doc, heads, options) { + for (var out = [], i = 0; i < doc.sel.ranges.length; i++) + out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null); + var newSel = normalizeSelection(out, doc.sel.primIndex); + setSelection(doc, newSel, options); + } + + // Updates a single range in the selection. + function replaceOneSelection(doc, i, range, options) { + var ranges = doc.sel.ranges.slice(0); + ranges[i] = range; + setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); + } + + // Reset the selection to a single range. + function setSimpleSelection(doc, anchor, head, options) { + setSelection(doc, simpleSelection(anchor, head), options); + } + + // Give beforeSelectionChange handlers a change to influence a + // selection update. + function filterSelectionChange(doc, sel, options) { + var obj = { + ranges: sel.ranges, + update: function(ranges) { + this.ranges = []; + for (var i = 0; i < ranges.length; i++) + this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), + clipPos(doc, ranges[i].head)); + }, + origin: options && options.origin + }; + signal(doc, "beforeSelectionChange", doc, obj); + if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); + if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1); + else return sel; + } + + function setSelectionReplaceHistory(doc, sel, options) { + var done = doc.history.done, last = lst(done); + if (last && last.ranges) { + done[done.length - 1] = sel; + setSelectionNoUndo(doc, sel, options); + } else { + setSelection(doc, sel, options); + } + } + + // Set a new selection. + function setSelection(doc, sel, options) { + setSelectionNoUndo(doc, sel, options); + addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); + } + + function setSelectionNoUndo(doc, sel, options) { + if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) + sel = filterSelectionChange(doc, sel, options); + + var bias = options && options.bias || + (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); + setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); + + if (!(options && options.scroll === false) && doc.cm) + ensureCursorVisible(doc.cm); + } + + function setSelectionInner(doc, sel) { + if (sel.equals(doc.sel)) return; + + doc.sel = sel; + + if (doc.cm) { + doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; + signalCursorActivity(doc.cm); + } + signalLater(doc, "cursorActivity", doc); + } + + // Verify that the selection does not partially select any atomic + // marked ranges. + function reCheckSelection(doc) { + setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll); + } + + // Return a selection that does not partially select any atomic + // ranges. + function skipAtomicInSelection(doc, sel, bias, mayClear) { + var out; + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i]; + var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]; + var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear); + var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear); + if (out || newAnchor != range.anchor || newHead != range.head) { + if (!out) out = sel.ranges.slice(0, i); + out[i] = new Range(newAnchor, newHead); + } + } + return out ? normalizeSelection(out, sel.primIndex) : sel; + } + + function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { + var line = getLine(doc, pos.line); + if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { + var sp = line.markedSpans[i], m = sp.marker; + if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && + (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) { + if (mayClear) { + signal(m, "beforeCursorEnter"); + if (m.explicitlyCleared) { + if (!line.markedSpans) break; + else {--i; continue;} + } + } + if (!m.atomic) continue; + + if (oldPos) { + var near = m.find(dir < 0 ? 1 : -1), diff; + if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft) + near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); + if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) + return skipAtomicInner(doc, near, pos, dir, mayClear); + } + + var far = m.find(dir < 0 ? -1 : 1); + if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight) + far = movePos(doc, far, dir, far.line == pos.line ? line : null); + return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null; + } + } + return pos; + } + + // Ensure a given position is not inside an atomic range. + function skipAtomic(doc, pos, oldPos, bias, mayClear) { + var dir = bias || 1; + var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || + (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || + skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || + (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)); + if (!found) { + doc.cantEdit = true; + return Pos(doc.first, 0); + } + return found; + } + + function movePos(doc, pos, dir, line) { + if (dir < 0 && pos.ch == 0) { + if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1)); + else return null; + } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { + if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0); + else return null; + } else { + return new Pos(pos.line, pos.ch + dir); + } + } + + // SELECTION DRAWING + + function updateSelection(cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()); + } + + function prepareSelection(cm, primary) { + var doc = cm.doc, result = {}; + var curFragment = result.cursors = document.createDocumentFragment(); + var selFragment = result.selection = document.createDocumentFragment(); + + for (var i = 0; i < doc.sel.ranges.length; i++) { + if (primary === false && i == doc.sel.primIndex) continue; + var range = doc.sel.ranges[i]; + if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) continue; + var collapsed = range.empty(); + if (collapsed || cm.options.showCursorWhenSelecting) + drawSelectionCursor(cm, range.head, curFragment); + if (!collapsed) + drawSelectionRange(cm, range, selFragment); + } + return result; + } + + // Draws a cursor for the given range + function drawSelectionCursor(cm, head, output) { + var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); + + var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); + cursor.style.left = (pos.left-(window.heartbeat && 2 || 0)) + "px"; + cursor.style.top = (pos.top+(window.heartbeat && 5 || 0)) + "px"; //#CUSTOM + cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; + + if (pos.other) { + // Secondary cursor, shown when on a 'jump' in bi-directional text + var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); + otherCursor.style.display = ""; + otherCursor.style.left = pos.other.left + "px"; + otherCursor.style.top = pos.other.top + "px"; + otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; + } + } + + // Draws the given range as a highlighted selection + function drawSelectionRange(cm, range, output) { + var display = cm.display, doc = cm.doc; + var fragment = document.createDocumentFragment(); + var padding = paddingH(cm.display), leftSide = padding.left; + var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; + + function add(left, top, width, bottom) { + if (top < 0) top = 0; + top = Math.round(top); + bottom = Math.round(bottom); + fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + + "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) + + "px; height: " + (bottom - top) + "px")); + } + + function drawForLine(line, fromArg, toArg) { + var lineObj = getLine(doc, line); + var lineLen = lineObj.text.length; + var start, end; + function coords(ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias); + } + + iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { + var leftPos = coords(from, "left"), rightPos, left, right; + if (from == to) { + rightPos = leftPos; + left = right = leftPos.left; + } else { + rightPos = coords(to - 1, "right"); + if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } + left = leftPos.left; + right = rightPos.right; + } + if (fromArg == null && from == 0) left = leftSide; + if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part + add(left, leftPos.top, null, leftPos.bottom); + left = leftSide; + if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); + } + if (toArg == null && to == lineLen) right = rightSide; + if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) + start = leftPos; + if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) + end = rightPos; + if (left < leftSide + 1) left = leftSide; + add(left, rightPos.top, right - left, rightPos.bottom); + }); + return {start: start, end: end}; + } + + var sFrom = range.from(), sTo = range.to(); + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch); + } else { + var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); + var singleVLine = visualLine(fromLine) == visualLine(toLine); + var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; + var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); + add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); + } + } + if (leftEnd.bottom < rightStart.top) + add(leftSide, leftEnd.bottom, null, rightStart.top); + } + + output.appendChild(fragment); + } + + // Cursor-blinking + function restartBlink(cm) { + if (!cm.state.focused) return; + var display = cm.display; + clearInterval(display.blinker); + var on = true; + display.cursorDiv.style.visibility = ""; + if (cm.options.cursorBlinkRate > 0) + display.blinker = setInterval(function() { + display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; + }, cm.options.cursorBlinkRate); + else if (cm.options.cursorBlinkRate < 0) + display.cursorDiv.style.visibility = "hidden"; + } + + // HIGHLIGHT WORKER + + function startWorker(cm, time) { + if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) + cm.state.highlight.set(time, bind(highlightWorker, cm)); + } + + function highlightWorker(cm) { + var doc = cm.doc; + if (doc.frontier < doc.first) doc.frontier = doc.first; + if (doc.frontier >= cm.display.viewTo) return; + var end = +new Date + cm.options.workTime; + var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); + var changedLines = []; + + doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) { + if (doc.frontier >= cm.display.viewFrom) { // Visible + var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength; + var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true); + line.styles = highlighted.styles; + var oldCls = line.styleClasses, newCls = highlighted.classes; + if (newCls) line.styleClasses = newCls; + else if (oldCls) line.styleClasses = null; + var ischange = !oldStyles || oldStyles.length != line.styles.length || + oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); + for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; + if (ischange) changedLines.push(doc.frontier); + line.stateAfter = tooLong ? state : copyState(doc.mode, state); + } else { + if (line.text.length <= cm.options.maxHighlightLength) + processLine(cm, line.text, state); + line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; + } + ++doc.frontier; + if (+new Date > end) { + startWorker(cm, cm.options.workDelay); + return true; + } + }); + if (changedLines.length) runInOp(cm, function() { + for (var i = 0; i < changedLines.length; i++) + regLineChange(cm, changedLines[i], "text"); + }); + } + + // Finds the line to start with when starting a parse. Tries to + // find a line with a stateAfter, so that it can start with a + // valid state. If that fails, it returns the line with the + // smallest indentation, which tends to need the least context to + // parse correctly. + function findStartLine(cm, n, precise) { + var minindent, minline, doc = cm.doc; + var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); + for (var search = n; search > lim; --search) { + if (search <= doc.first) return doc.first; + var line = getLine(doc, search - 1); + if (line.stateAfter && (!precise || search <= doc.frontier)) return search; + var indented = countColumn(line.text, null, cm.options.tabSize); + if (minline == null || minindent > indented) { + minline = search - 1; + minindent = indented; + } + } + return minline; + } + + function getStateBefore(cm, n, precise) { + var doc = cm.doc, display = cm.display; + if (!doc.mode.startState) return true; + var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter; + if (!state) state = startState(doc.mode); + else state = copyState(doc.mode, state); + doc.iter(pos, n, function(line) { + processLine(cm, line.text, state); + var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo; + line.stateAfter = save ? copyState(doc.mode, state) : null; + ++pos; + }); + if (precise) doc.frontier = pos; + return state; + } + + // POSITION MEASUREMENT + + function paddingTop(display) {return display.lineSpace.offsetTop;} + function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} + function paddingH(display) { + if (display.cachedPaddingH) return display.cachedPaddingH; + var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); + var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; + var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; + if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data; + return data; + } + + function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; } + function displayWidth(cm) { + return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; + } + function displayHeight(cm) { + return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; + } + + // Ensure the lineView.wrapping.heights array is populated. This is + // an array of bottom offsets for the lines that make up a drawn + // line. When lineWrapping is on, there might be more than one + // height. + function ensureLineHeights(cm, lineView, rect) { + var wrapping = cm.options.lineWrapping; + var curWidth = wrapping && displayWidth(cm); + if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { + var heights = lineView.measure.heights = []; + if (wrapping) { + lineView.measure.width = curWidth; + var rects = lineView.text.firstChild.getClientRects(); + for (var i = 0; i < rects.length - 1; i++) { + var cur = rects[i], next = rects[i + 1]; + if (Math.abs(cur.bottom - next.bottom) > 2) + heights.push((cur.bottom + next.top) / 2 - rect.top); + } + } + heights.push(rect.bottom - rect.top); + } + } + + // Find a line map (mapping character offsets to text nodes) and a + // measurement cache for the given line number. (A line view might + // contain multiple lines when collapsed ranges are present.) + function mapFromLineView(lineView, line, lineN) { + if (lineView.line == line) + return {map: lineView.measure.map, cache: lineView.measure.cache}; + for (var i = 0; i < lineView.rest.length; i++) + if (lineView.rest[i] == line) + return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]}; + for (var i = 0; i < lineView.rest.length; i++) + if (lineNo(lineView.rest[i]) > lineN) + return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true}; + } + + // Render a line into the hidden node display.externalMeasured. Used + // when measurement is needed for a line that's not in the viewport. + function updateExternalMeasurement(cm, line) { + line = visualLine(line); + var lineN = lineNo(line); + var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); + view.lineN = lineN; + var built = view.built = buildLineContent(cm, view); + view.text = built.pre; + removeChildrenAndAdd(cm.display.lineMeasure, built.pre); + return view; + } + + // Get a {top, bottom, left, right} box (in line-local coordinates) + // for a given character. + function measureChar(cm, line, ch, bias) { + return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); + } + + // Find a line view that corresponds to the given line number. + function findViewForLine(cm, lineN) { + if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) + return cm.display.view[findViewIndex(cm, lineN)]; + var ext = cm.display.externalMeasured; + if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) + return ext; + } + + // Measurement can be split in two steps, the set-up work that + // applies to the whole line, and the measurement of the actual + // character. Functions like coordsChar, that need to do a lot of + // measurements in a row, can thus ensure that the set-up work is + // only done once. + function prepareMeasureForLine(cm, line) { + var lineN = lineNo(line); + var view = findViewForLine(cm, lineN); + if (view && !view.text) { + view = null; + } else if (view && view.changes) { + updateLineForChanges(cm, view, lineN, getDimensions(cm)); + cm.curOp.forceUpdate = true; + } + if (!view) + view = updateExternalMeasurement(cm, line); + + var info = mapFromLineView(view, line, lineN); + return { + line: line, view: view, rect: null, + map: info.map, cache: info.cache, before: info.before, + hasHeights: false + }; + } + + // Given a prepared measurement object, measures the position of an + // actual character (or fetches it from the cache). + function measureCharPrepared(cm, prepared, ch, bias, varHeight) { + if (prepared.before) ch = -1; + var key = ch + (bias || ""), found; + if (prepared.cache.hasOwnProperty(key)) { + found = prepared.cache[key]; + } else { + if (!prepared.rect) + prepared.rect = prepared.view.text.getBoundingClientRect(); + if (!prepared.hasHeights) { + ensureLineHeights(cm, prepared.view, prepared.rect); + prepared.hasHeights = true; + } + found = measureCharInner(cm, prepared, ch, bias); + if (!found.bogus) prepared.cache[key] = found; + } + return {left: found.left, right: found.right, + top: varHeight ? found.rtop : found.top, + bottom: varHeight ? found.rbottom : found.bottom}; + } + + var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; + + function nodeAndOffsetInLineMap(map, ch, bias) { + var node, start, end, collapse; + // First, search the line map for the text node corresponding to, + // or closest to, the target character. + for (var i = 0; i < map.length; i += 3) { + var mStart = map[i], mEnd = map[i + 1]; + if (ch < mStart) { + start = 0; end = 1; + collapse = "left"; + } else if (ch < mEnd) { + start = ch - mStart; + end = start + 1; + } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { + end = mEnd - mStart; + start = end - 1; + if (ch >= mEnd) collapse = "right"; + } + if (start != null) { + node = map[i + 2]; + if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) + collapse = bias; + if (bias == "left" && start == 0) + while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { + node = map[(i -= 3) + 2]; + collapse = "left"; + } + if (bias == "right" && start == mEnd - mStart) + while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { + node = map[(i += 3) + 2]; + collapse = "right"; + } + break; + } + } + return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}; + } + + function measureCharInner(cm, prepared, ch, bias) { + var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); + var node = place.node, start = place.start, end = place.end, collapse = place.collapse; + + var rect; + if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. + for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned + while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start; + while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end; + if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { + rect = node.parentNode.getBoundingClientRect(); + } else if (ie && cm.options.lineWrapping) { + var rects = range(node, start, end).getClientRects(); + if (rects.length) + rect = rects[bias == "right" ? rects.length - 1 : 0]; + else + rect = nullRect; + } else { + rect = range(node, start, end).getBoundingClientRect() || nullRect; + } + if (rect.left || rect.right || start == 0) break; + end = start; + start = start - 1; + collapse = "right"; + } + if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect); + } else { // If it is a widget, simply get the box for the whole widget. + if (start > 0) collapse = bias = "right"; + var rects; + if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) + rect = rects[bias == "right" ? rects.length - 1 : 0]; + else + rect = node.getBoundingClientRect(); + } + if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { + var rSpan = node.parentNode.getClientRects()[0]; + if (rSpan) + rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; + else + rect = nullRect; + } + + var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; + var mid = (rtop + rbot) / 2; + var heights = prepared.view.measure.heights; + for (var i = 0; i < heights.length - 1; i++) + if (mid < heights[i]) break; + var top = i ? heights[i - 1] : 0, bot = heights[i]; + var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, + right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, + top: top, bottom: bot}; + if (!rect.left && !rect.right) result.bogus = true; + if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } + + return result; + } + + // Work around problem with bounding client rects on ranges being + // returned incorrectly when zoomed on IE10 and below. + function maybeUpdateRectForZooming(measure, rect) { + if (!window.screen || screen.logicalXDPI == null || + screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) + return rect; + var scaleX = screen.logicalXDPI / screen.deviceXDPI; + var scaleY = screen.logicalYDPI / screen.deviceYDPI; + return {left: rect.left * scaleX, right: rect.right * scaleX, + top: rect.top * scaleY, bottom: rect.bottom * scaleY}; + } + + function clearLineMeasurementCacheFor(lineView) { + if (lineView.measure) { + lineView.measure.cache = {}; + lineView.measure.heights = null; + if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) + lineView.measure.caches[i] = {}; + } + } + + function clearLineMeasurementCache(cm) { + cm.display.externalMeasure = null; + removeChildren(cm.display.lineMeasure); + for (var i = 0; i < cm.display.view.length; i++) + clearLineMeasurementCacheFor(cm.display.view[i]); + } + + function clearCaches(cm) { + clearLineMeasurementCache(cm); + cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; + if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; + cm.display.lineNumChars = null; + } + + function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } + function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } + + // Converts a {top, bottom, left, right} box from line-local + // coordinates into another coordinate system. Context may be one of + // "line", "div" (display.lineDiv), "local"/null (editor), "window", + // or "page". + function intoCoordSystem(cm, lineObj, rect, context) { + if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { + var size = widgetHeight(lineObj.widgets[i]); + rect.top += size; rect.bottom += size; + } + if (context == "line") return rect; + if (!context) context = "local"; + var yOff = heightAtLine(lineObj); + if (context == "local") yOff += paddingTop(cm.display); + else yOff -= cm.display.viewOffset; + if (context == "page" || context == "window") { + var lOff = cm.display.lineSpace.getBoundingClientRect(); + yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); + var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); + rect.left += xOff; rect.right += xOff; + } + rect.top += yOff; rect.bottom += yOff; + return rect; + } + + // Coverts a box from "div" coords to another coordinate system. + // Context may be "window", "page", "div", or "local"/null. + function fromCoordSystem(cm, coords, context) { + if (context == "div") return coords; + var left = coords.left, top = coords.top; + // First move into "page" coordinate system + if (context == "page") { + left -= pageScrollX(); + top -= pageScrollY(); + } else if (context == "local" || !context) { + var localBox = cm.display.sizer.getBoundingClientRect(); + left += localBox.left; + top += localBox.top; + } + + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); + return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; + } + + function charCoords(cm, pos, context, lineObj, bias) { + if (!lineObj) lineObj = getLine(cm.doc, pos.line); + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); + } + + // Returns a box for a given cursor position, which may have an + // 'other' property containing the position of the secondary cursor + // on a bidi boundary. + function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { + lineObj = lineObj || getLine(cm.doc, pos.line); + if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj); + function get(ch, right) { + var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); + if (right) m.left = m.right; else m.right = m.left; + return intoCoordSystem(cm, lineObj, m, context); + } + function getBidi(ch, partPos) { + var part = order[partPos], right = part.level % 2; + if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { + part = order[--partPos]; + ch = bidiRight(part) - (part.level % 2 ? 0 : 1); + right = true; + } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { + part = order[++partPos]; + ch = bidiLeft(part) - part.level % 2; + right = false; + } + if (right && ch == part.to && ch > part.from) return get(ch - 1); + return get(ch, right); + } + var order = getOrder(lineObj), ch = pos.ch; + if (!order) return get(ch); + var partPos = getBidiPartAt(order, ch); + var val = getBidi(ch, partPos); + if (bidiOther != null) val.other = getBidi(ch, bidiOther); + return val; + } + + // Used to cheaply estimate the coordinates for a position. Used for + // intermediate scroll updates. + function estimateCoords(cm, pos) { + var left = 0, pos = clipPos(cm.doc, pos); + if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch; + var lineObj = getLine(cm.doc, pos.line); + var top = heightAtLine(lineObj) + paddingTop(cm.display); + return {left: left, right: left, top: top, bottom: top + lineObj.height}; + } + + // Positions returned by coordsChar contain some extra information. + // xRel is the relative x position of the input coordinates compared + // to the found position (so xRel > 0 means the coordinates are to + // the right of the character position, for example). When outside + // is true, that means the coordinates lie outside the line's + // vertical range. + function PosWithInfo(line, ch, outside, xRel) { + var pos = Pos(line, ch); + pos.xRel = xRel; + if (outside) pos.outside = true; + return pos; + } + + // Compute the character position closest to the given coordinates. + // Input must be lineSpace-local ("div" coordinate system). + function coordsChar(cm, x, y) { + var doc = cm.doc; + y += cm.display.viewOffset; + if (y < 0) return PosWithInfo(doc.first, 0, true, -1); + var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; + if (lineN > last) + return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1); + if (x < 0) x = 0; + + var lineObj = getLine(doc, lineN); + for (;;) { + var found = coordsCharInner(cm, lineObj, lineN, x, y); + var merged = collapsedSpanAtEnd(lineObj); + var mergedPos = merged && merged.find(0, true); + if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) + lineN = lineNo(lineObj = mergedPos.to.line); + else + return found; + } + } + + function coordsCharInner(cm, lineObj, lineNo, x, y) { + var innerOff = y - heightAtLine(lineObj); + var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; + var preparedMeasure = prepareMeasureForLine(cm, lineObj); + + function getX(ch) { + var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure); + wrongLine = true; + if (innerOff > sp.bottom) return sp.left - adjust; + else if (innerOff < sp.top) return sp.left + adjust; + else wrongLine = false; + return sp.left; + } + + var bidi = getOrder(lineObj), dist = lineObj.text.length; + var from = lineLeft(lineObj), to = lineRight(lineObj); + var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; + + if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); + // Do a binary search between these bounds. + for (;;) { + if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { + var ch = x < fromX || x - fromX <= toX - x ? from : to; + var xDiff = x - (ch == from ? fromX : toX); + while (isExtendingChar(lineObj.text.charAt(ch))) ++ch; + var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, + xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0); + return pos; + } + var step = Math.ceil(dist / 2), middle = from + step; + if (bidi) { + middle = from; + for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); + } + var middleX = getX(middle); + if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} + else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} + } + } + + var measureText; + // Compute the default text height. + function textHeight(display) { + if (display.cachedTextHeight != null) return display.cachedTextHeight; + if (measureText == null) { + measureText = elt("pre"); + // Measure a bunch of lines, for browsers that compute + // fractional heights. + for (var i = 0; i < 49; ++i) { + measureText.appendChild(document.createTextNode("x")); + measureText.appendChild(elt("br")); + } + measureText.appendChild(document.createTextNode("x")); + } + removeChildrenAndAdd(display.measure, measureText); + var height = measureText.offsetHeight / 50; + if (height > 3) display.cachedTextHeight = height; + removeChildren(display.measure); + return height || 1; + } + + // Compute the default character width. + function charWidth(display) { + if (display.cachedCharWidth != null) return display.cachedCharWidth; + var anchor = elt("span", "xxxxxxxxxx"); + var pre = elt("pre", [anchor]); + removeChildrenAndAdd(display.measure, pre); + var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; + if (width > 2) display.cachedCharWidth = width; + return width || 10; + } + + // OPERATIONS + + // Operations are used to wrap a series of changes to the editor + // state in such a way that each change won't have to update the + // cursor and display (which would be awkward, slow, and + // error-prone). Instead, display updates are batched and then all + // combined and executed at once. + + var operationGroup = null; + + var nextOpId = 0; + // Start a new operation. + function startOperation(cm) { + cm.curOp = { + cm: cm, + viewChanged: false, // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, // Used to detect need to update scrollbar + forceUpdate: false, // Used to force a redraw + updateInput: null, // Whether to reset the input textarea + typing: false, // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, // Accumulated changes, for firing change events + cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already + selectionChanged: false, // Whether the selection needs to be redrawn + updateMaxLine: false, // Set when the widest line needs to be determined anew + scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, // Used to scroll to a specific position + focus: false, + id: ++nextOpId // Unique ID + }; + if (operationGroup) { + operationGroup.ops.push(cm.curOp); + } else { + cm.curOp.ownsGroup = operationGroup = { + ops: [cm.curOp], + delayedCallbacks: [] + }; + } + } + + function fireCallbacksForOps(group) { + // Calls delayed callbacks and cursorActivity handlers until no + // new ones appear + var callbacks = group.delayedCallbacks, i = 0; + do { + for (; i < callbacks.length; i++) + callbacks[i].call(null); + for (var j = 0; j < group.ops.length; j++) { + var op = group.ops[j]; + if (op.cursorActivityHandlers) + while (op.cursorActivityCalled < op.cursorActivityHandlers.length) + op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); + } + } while (i < callbacks.length); + } + + // Finish an operation, updating the display and signalling delayed events + function endOperation(cm) { + var op = cm.curOp, group = op.ownsGroup; + if (!group) return; + + try { fireCallbacksForOps(group); } + finally { + operationGroup = null; + for (var i = 0; i < group.ops.length; i++) + group.ops[i].cm.curOp = null; + endOperations(group); + } + } + + // The DOM updates done when an operation finishes are batched so + // that the minimum number of relayouts are required. + function endOperations(group) { + var ops = group.ops; + for (var i = 0; i < ops.length; i++) // Read DOM + endOperation_R1(ops[i]); + for (var i = 0; i < ops.length; i++) // Write DOM (maybe) + endOperation_W1(ops[i]); + for (var i = 0; i < ops.length; i++) // Read DOM + endOperation_R2(ops[i]); + for (var i = 0; i < ops.length; i++) // Write DOM (maybe) + endOperation_W2(ops[i]); + for (var i = 0; i < ops.length; i++) // Read DOM + endOperation_finish(ops[i]); + } + + function endOperation_R1(op) { + var cm = op.cm, display = cm.display; + maybeClipScrollbars(cm); + if (op.updateMaxLine) findMaxLine(cm); + + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || + op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || + op.scrollToPos.to.line >= display.viewTo) || + display.maxLineChanged && cm.options.lineWrapping; + op.update = op.mustUpdate && + new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); + } + + function endOperation_W1(op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); + } + + function endOperation_R2(op) { + var cm = op.cm, display = cm.display; + if (op.updatedDisplay) updateHeightsInViewport(cm); + + op.barMeasure = measureForScrollbars(cm); + + // If the max line changed since it was last measured, measure it, + // and ensure the document's width matches it. + // updateDisplay_W2 will use these properties to do the actual resizing + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; + cm.display.sizerWidth = op.adjustWidthTo; + op.barMeasure.scrollWidth = + Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); + op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); + } + + if (op.updatedDisplay || op.selectionChanged) + op.preparedSelection = display.input.prepareSelection(op.focus); + } + + function endOperation_W2(op) { + var cm = op.cm; + + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; + if (op.maxScrollLeft < cm.doc.scrollLeft) + setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); + cm.display.maxLineChanged = false; + } + + var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus()) + if (op.preparedSelection) + cm.display.input.showSelection(op.preparedSelection, takeFocus); + if (op.updatedDisplay || op.startHeight != cm.doc.height) + updateScrollbars(cm, op.barMeasure); + if (op.updatedDisplay) + setDocumentHeight(cm, op.barMeasure); + + if (op.selectionChanged) restartBlink(cm); + + if (cm.state.focused && op.updateInput) + cm.display.input.reset(op.typing); + if (takeFocus) ensureFocus(op.cm); + } + + function endOperation_finish(op) { + var cm = op.cm, display = cm.display, doc = cm.doc; + + if (op.updatedDisplay) postUpdateDisplay(cm, op.update); + + // Abort mouse wheel delta measurement, when scrolling explicitly + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) + display.wheelStartX = display.wheelStartY = null; + + // Propagate the scroll position to the actual DOM scroller + if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) { + doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)); + display.scrollbars.setScrollTop(doc.scrollTop); + display.scroller.scrollTop = doc.scrollTop; + } + if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) { + doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft)); + display.scrollbars.setScrollLeft(doc.scrollLeft); + display.scroller.scrollLeft = doc.scrollLeft; + alignHorizontally(cm); + } + // If we need to scroll a specific position into view, do so. + if (op.scrollToPos) { + var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), + clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); + if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords); + } + + // Fire events for markers that are hidden/unidden by editing or + // undoing + var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; + if (hidden) for (var i = 0; i < hidden.length; ++i) + if (!hidden[i].lines.length) signal(hidden[i], "hide"); + if (unhidden) for (var i = 0; i < unhidden.length; ++i) + if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); + + if (display.wrapper.offsetHeight) + doc.scrollTop = cm.display.scroller.scrollTop; + + // Fire change events, and delayed event handlers + if (op.changeObjs) + signal(cm, "changes", cm, op.changeObjs); + if (op.update) + op.update.finish(); + } + + // Run the given function in an operation + function runInOp(cm, f) { + if (cm.curOp) return f(); + startOperation(cm); + try { return f(); } + finally { endOperation(cm); } + } + // Wraps a function in an operation. Returns the wrapped function. + function operation(cm, f) { + return function() { + if (cm.curOp) return f.apply(cm, arguments); + startOperation(cm); + try { return f.apply(cm, arguments); } + finally { endOperation(cm); } + }; + } + // Used to add methods to editor and doc instances, wrapping them in + // operations. + function methodOp(f) { + return function() { + if (this.curOp) return f.apply(this, arguments); + startOperation(this); + try { return f.apply(this, arguments); } + finally { endOperation(this); } + }; + } + function docMethodOp(f) { + return function() { + var cm = this.cm; + if (!cm || cm.curOp) return f.apply(this, arguments); + startOperation(cm); + try { return f.apply(this, arguments); } + finally { endOperation(cm); } + }; + } + + // VIEW TRACKING + + // These objects are used to represent the visible (currently drawn) + // part of the document. A LineView may correspond to multiple + // logical lines, if those are connected by collapsed ranges. + function LineView(doc, line, lineN) { + // The starting line + this.line = line; + // Continuing lines, if any + this.rest = visualLineContinued(line); + // Number of logical lines in this visual line + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; + this.node = this.text = null; + this.hidden = lineIsHidden(doc, line); + } + + // Create a range of LineView objects for the given lines. + function buildViewArray(cm, from, to) { + var array = [], nextPos; + for (var pos = from; pos < to; pos = nextPos) { + var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); + nextPos = pos + view.size; + array.push(view); + } + return array; + } + + // Updates the display.view data structure for a given change to the + // document. From and to are in pre-change coordinates. Lendiff is + // the amount of lines added or subtracted by the change. This is + // used for changes that span multiple lines, or change the way + // lines are divided into visual lines. regLineChange (below) + // registers single-line changes. + function regChange(cm, from, to, lendiff) { + if (from == null) from = cm.doc.first; + if (to == null) to = cm.doc.first + cm.doc.size; + if (!lendiff) lendiff = 0; + + var display = cm.display; + if (lendiff && to < display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers > from)) + display.updateLineNumbers = from; + + cm.curOp.viewChanged = true; + + if (from >= display.viewTo) { // Change after + if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) + resetView(cm); + } else if (to <= display.viewFrom) { // Change before + if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { + resetView(cm); + } else { + display.viewFrom += lendiff; + display.viewTo += lendiff; + } + } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap + resetView(cm); + } else if (from <= display.viewFrom) { // Top overlap + var cut = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cut) { + display.view = display.view.slice(cut.index); + display.viewFrom = cut.lineN; + display.viewTo += lendiff; + } else { + resetView(cm); + } + } else if (to >= display.viewTo) { // Bottom overlap + var cut = viewCuttingPoint(cm, from, from, -1); + if (cut) { + display.view = display.view.slice(0, cut.index); + display.viewTo = cut.lineN; + } else { + resetView(cm); + } + } else { // Gap in the middle + var cutTop = viewCuttingPoint(cm, from, from, -1); + var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cutTop && cutBot) { + display.view = display.view.slice(0, cutTop.index) + .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) + .concat(display.view.slice(cutBot.index)); + display.viewTo += lendiff; + } else { + resetView(cm); + } + } + + var ext = display.externalMeasured; + if (ext) { + if (to < ext.lineN) + ext.lineN += lendiff; + else if (from < ext.lineN + ext.size) + display.externalMeasured = null; + } + } + + // Register a change to a single line. Type must be one of "text", + // "gutter", "class", "widget" + function regLineChange(cm, line, type) { + cm.curOp.viewChanged = true; + var display = cm.display, ext = cm.display.externalMeasured; + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) + display.externalMeasured = null; + + if (line < display.viewFrom || line >= display.viewTo) return; + var lineView = display.view[findViewIndex(cm, line)]; + if (lineView.node == null) return; + var arr = lineView.changes || (lineView.changes = []); + if (indexOf(arr, type) == -1) arr.push(type); + } + + // Clear the view. + function resetView(cm) { + cm.display.viewFrom = cm.display.viewTo = cm.doc.first; + cm.display.view = []; + cm.display.viewOffset = 0; + } + + // Find the view element corresponding to a given line. Return null + // when the line isn't visible. + function findViewIndex(cm, n) { + if (n >= cm.display.viewTo) return null; + n -= cm.display.viewFrom; + if (n < 0) return null; + var view = cm.display.view; + for (var i = 0; i < view.length; i++) { + n -= view[i].size; + if (n < 0) return i; + } + } + + function viewCuttingPoint(cm, oldN, newN, dir) { + var index = findViewIndex(cm, oldN), diff, view = cm.display.view; + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) + return {index: index, lineN: newN}; + for (var i = 0, n = cm.display.viewFrom; i < index; i++) + n += view[i].size; + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) return null; + diff = (n + view[index].size) - oldN; + index++; + } else { + diff = n - oldN; + } + oldN += diff; newN += diff; + } + while (visualLineNo(cm.doc, newN) != newN) { + if (index == (dir < 0 ? 0 : view.length - 1)) return null; + newN += dir * view[index - (dir < 0 ? 1 : 0)].size; + index += dir; + } + return {index: index, lineN: newN}; + } + + // Force the view to cover a given range, adding empty view element + // or clipping off existing ones as needed. + function adjustView(cm, from, to) { + var display = cm.display, view = display.view; + if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { + display.view = buildViewArray(cm, from, to); + display.viewFrom = from; + } else { + if (display.viewFrom > from) + display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); + else if (display.viewFrom < from) + display.view = display.view.slice(findViewIndex(cm, from)); + display.viewFrom = from; + if (display.viewTo < to) + display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); + else if (display.viewTo > to) + display.view = display.view.slice(0, findViewIndex(cm, to)); + } + display.viewTo = to; + } + + // Count the number of lines in the view whose DOM representation is + // out of date (or nonexistent). + function countDirtyView(cm) { + var view = cm.display.view, dirty = 0; + for (var i = 0; i < view.length; i++) { + var lineView = view[i]; + if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty; + } + return dirty; + } + + // EVENT HANDLERS + + // Attach the necessary event handlers when initializing the editor + function registerEventHandlers(cm) { + var d = cm.display; + on(d.scroller, "mousedown", operation(cm, onMouseDown)); + // Older IE's will not fire a second mousedown for a double click + if (ie && ie_version < 11) + on(d.scroller, "dblclick", operation(cm, function(e) { + if (signalDOMEvent(cm, e)) return; + var pos = posFromMouse(cm, e); + if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; + e_preventDefault(e); + var word = cm.findWordAt(pos); + extendSelection(cm.doc, word.anchor, word.head); + })); + else + on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); }); + // Some browsers fire contextmenu *after* opening the menu, at + // which point we can't mess with it anymore. Context menu is + // handled in onMouseDown for these browsers. + if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); + + // Used to suppress mouse event handling when a touch happens + var touchFinished, prevTouch = {end: 0}; + function finishTouch() { + if (d.activeTouch) { + touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000); + prevTouch = d.activeTouch; + prevTouch.end = +new Date; + } + }; + function isMouseLikeTouchEvent(e) { + if (e.touches.length != 1) return false; + var touch = e.touches[0]; + return touch.radiusX <= 1 && touch.radiusY <= 1; + } + function farAway(touch, other) { + if (other.left == null) return true; + var dx = other.left - touch.left, dy = other.top - touch.top; + return dx * dx + dy * dy > 20 * 20; + } + on(d.scroller, "touchstart", function(e) { + if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) { + clearTimeout(touchFinished); + var now = +new Date; + d.activeTouch = {start: now, moved: false, + prev: now - prevTouch.end <= 300 ? prevTouch : null}; + if (e.touches.length == 1) { + d.activeTouch.left = e.touches[0].pageX; + d.activeTouch.top = e.touches[0].pageY; + } + } + }); + on(d.scroller, "touchmove", function() { + if (d.activeTouch) d.activeTouch.moved = true; + }); + on(d.scroller, "touchend", function(e) { + var touch = d.activeTouch; + if (touch && !eventInWidget(d, e) && touch.left != null && + !touch.moved && new Date - touch.start < 300) { + var pos = cm.coordsChar(d.activeTouch, "page"), range; + if (!touch.prev || farAway(touch, touch.prev)) // Single tap + range = new Range(pos, pos); + else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap + range = cm.findWordAt(pos); + else // Triple tap + range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); + cm.setSelection(range.anchor, range.head); + cm.focus(); + e_preventDefault(e); + } + finishTouch(); + }); + on(d.scroller, "touchcancel", finishTouch); + + // Sync scrolling between fake scrollbars and real scrollable + // area, ensure viewport is updated when scrolling. + on(d.scroller, "scroll", function() { + if (d.scroller.clientHeight) { + setScrollTop(cm, d.scroller.scrollTop); + setScrollLeft(cm, d.scroller.scrollLeft, true); + signal(cm, "scroll", cm); + } + }); + + // Listen to wheel events in order to try and update the viewport on time. + on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); + on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); + + // Prevent wrapper from ever scrolling + on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); + + d.dragFunctions = { + enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);}, + over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, + start: function(e){onDragStart(cm, e);}, + drop: operation(cm, onDrop), + leave: function(e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }} + }; + + var inp = d.input.getField(); + on(inp, "keyup", function(e) { onKeyUp.call(cm, e); }); + on(inp, "keydown", operation(cm, onKeyDown)); + on(inp, "keypress", operation(cm, onKeyPress)); + on(inp, "focus", bind(onFocus, cm)); + on(inp, "blur", bind(onBlur, cm)); + } + + function dragDropChanged(cm, value, old) { + var wasOn = old && old != CodeMirror.Init; + if (!value != !wasOn) { + var funcs = cm.display.dragFunctions; + var toggle = value ? on : off; + toggle(cm.display.scroller, "dragstart", funcs.start); + toggle(cm.display.scroller, "dragenter", funcs.enter); + toggle(cm.display.scroller, "dragover", funcs.over); + toggle(cm.display.scroller, "dragleave", funcs.leave); + toggle(cm.display.scroller, "drop", funcs.drop); + } + } + + // Called when the window resizes + function onResize(cm) { + var d = cm.display; + if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) + return; + // Might be a text scaling operation, clear size caches. + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + d.scrollbarsClipped = false; + cm.setSize(); + } + + // MOUSE EVENTS + + // Return true when the given mouse event happened in a widget + function eventInWidget(display, e) { + for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { + if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || + (n.parentNode == display.sizer && n != display.mover)) + return true; + } + } + + // Given a mouse event, find the corresponding position. If liberal + // is false, it checks whether a gutter or scrollbar was clicked, + // and returns null if it was. forRect is used by rectangular + // selections, and tries to estimate a character position even for + // coordinates beyond the right of the text. + function posFromMouse(cm, e, liberal, forRect) { + var display = cm.display; + if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null; + + var x, y, space = display.lineSpace.getBoundingClientRect(); + // Fails unpredictably on IE[67] when mouse is dragged around quickly. + try { x = e.clientX - space.left; y = e.clientY - space.top; } + catch (e) { return null; } + var coords = coordsChar(cm, x, y), line; + if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { + var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; + coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); + } + return coords; + } + + // A mouse down can be a single click, double click, triple click, + // start of selection drag, start of text drag, new cursor + // (ctrl-click), rectangle drag (alt-drag), or xwin + // middle-click-paste. Or it might be a click on something we should + // not interfere with, such as a scrollbar or widget. + function onMouseDown(e) { + var cm = this, display = cm.display; + if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) return; + display.shift = e.shiftKey; + + if (eventInWidget(display, e)) { + if (!webkit) { + // Briefly turn off draggability, to allow widgets to do + // normal dragging things. + display.scroller.draggable = false; + setTimeout(function(){display.scroller.draggable = true;}, 100); + } + return; + } + if (clickInGutter(cm, e)) return; + var start = posFromMouse(cm, e); + window.focus(); + + switch (e_button(e)) { + case 1: + // #3261: make sure, that we're not starting a second selection + if (cm.state.selectingText) + cm.state.selectingText(e); + else if (start) + leftButtonDown(cm, e, start); + else if (e_target(e) == display.scroller) + e_preventDefault(e); + break; + case 2: + if (webkit) cm.state.lastMiddleDown = +new Date; + if (start) extendSelection(cm.doc, start); + setTimeout(function() {display.input.focus();}, 20); + e_preventDefault(e); + break; + case 3: + if (captureRightClick) onContextMenu(cm, e); + else delayBlurEvent(cm); + break; + } + } + + var lastClick, lastDoubleClick; + function leftButtonDown(cm, e, start) { + if (ie) setTimeout(bind(ensureFocus, cm), 0); + else cm.curOp.focus = activeElt(); + + var now = +new Date, type; + if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { + type = "triple"; + } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { + type = "double"; + lastDoubleClick = {time: now, pos: start}; + } else { + type = "single"; + lastClick = {time: now, pos: start}; + } + + var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained; + if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && + type == "single" && (contained = sel.contains(start)) > -1 && + (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) && + (cmp(contained.to(), start) > 0 || start.xRel < 0)) + leftButtonStartDrag(cm, e, start, modifier); + else + leftButtonSelect(cm, e, start, type, modifier); + } + + // Start a text drag. When it ends, see if any dragging actually + // happen, and treat as a click if it didn't. + function leftButtonStartDrag(cm, e, start, modifier) { + var display = cm.display, startTime = +new Date; + var dragEnd = operation(cm, function(e2) { + if (webkit) display.scroller.draggable = false; + cm.state.draggingText = false; + off(document, "mouseup", dragEnd); + off(display.scroller, "drop", dragEnd); + if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { + e_preventDefault(e2); + if (!modifier && +new Date - 200 < startTime) + extendSelection(cm.doc, start); + // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) + if (webkit || ie && ie_version == 9) + setTimeout(function() {document.body.focus(); display.input.focus();}, 20); + else + display.input.focus(); + } + }); + // Let the drag handler handle this. + if (webkit) display.scroller.draggable = true; + cm.state.draggingText = dragEnd; + // IE's approach to draggable + if (display.scroller.dragDrop) display.scroller.dragDrop(); + on(document, "mouseup", dragEnd); + on(display.scroller, "drop", dragEnd); + } + + // Normal selection, as opposed to text dragging. + function leftButtonSelect(cm, e, start, type, addNew) { + var display = cm.display, doc = cm.doc; + e_preventDefault(e); + + var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; + if (addNew && !e.shiftKey) { + ourIndex = doc.sel.contains(start); + if (ourIndex > -1) + ourRange = ranges[ourIndex]; + else + ourRange = new Range(start, start); + } else { + ourRange = doc.sel.primary(); + ourIndex = doc.sel.primIndex; + } + + if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) { + type = "rect"; + if (!addNew) ourRange = new Range(start, start); + start = posFromMouse(cm, e, true, true); + ourIndex = -1; + } else if (type == "double") { + var word = cm.findWordAt(start); + if (cm.display.shift || doc.extend) + ourRange = extendRange(doc, ourRange, word.anchor, word.head); + else + ourRange = word; + } else if (type == "triple") { + var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))); + if (cm.display.shift || doc.extend) + ourRange = extendRange(doc, ourRange, line.anchor, line.head); + else + ourRange = line; + } else { + ourRange = extendRange(doc, ourRange, start); + } + + if (!addNew) { + ourIndex = 0; + setSelection(doc, new Selection([ourRange], 0), sel_mouse); + startSel = doc.sel; + } else if (ourIndex == -1) { + ourIndex = ranges.length; + setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), + {scroll: false, origin: "*mouse"}); + } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) { + setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), + {scroll: false, origin: "*mouse"}); + startSel = doc.sel; + } else { + replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); + } + + var lastPos = start; + function extendTo(pos) { + if (cmp(lastPos, pos) == 0) return; + lastPos = pos; + + if (type == "rect") { + var ranges = [], tabSize = cm.options.tabSize; + var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); + var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); + var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); + for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); + line <= end; line++) { + var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); + if (left == right) + ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); + else if (text.length > leftPos) + ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); + } + if (!ranges.length) ranges.push(new Range(start, start)); + setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), + {origin: "*mouse", scroll: false}); + cm.scrollIntoView(pos); + } else { + var oldRange = ourRange; + var anchor = oldRange.anchor, head = pos; + if (type != "single") { + if (type == "double") + var range = cm.findWordAt(pos); + else + var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))); + if (cmp(range.anchor, anchor) > 0) { + head = range.head; + anchor = minPos(oldRange.from(), range.anchor); + } else { + head = range.anchor; + anchor = maxPos(oldRange.to(), range.head); + } + } + var ranges = startSel.ranges.slice(0); + ranges[ourIndex] = new Range(clipPos(doc, anchor), head); + setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse); + } + } + + var editorSize = display.wrapper.getBoundingClientRect(); + // Used to ensure timeout re-tries don't fire when another extend + // happened in the meantime (clearTimeout isn't reliable -- at + // least on Chrome, the timeouts still happen even when cleared, + // if the clear happens after their scheduled firing time). + var counter = 0; + + function extend(e) { + var curCount = ++counter; + var cur = posFromMouse(cm, e, true, type == "rect"); + if (!cur) return; + if (cmp(cur, lastPos) != 0) { + cm.curOp.focus = activeElt(); + extendTo(cur); + var visible = visibleLines(display, doc); + if (cur.line >= visible.to || cur.line < visible.from) + setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); + } else { + var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; + if (outside) setTimeout(operation(cm, function() { + if (counter != curCount) return; + display.scroller.scrollTop += outside; + extend(e); + }), 50); + } + } + + function done(e) { + cm.state.selectingText = false; + counter = Infinity; + e_preventDefault(e); + display.input.focus(); + off(document, "mousemove", move); + off(document, "mouseup", up); + doc.history.lastSelOrigin = null; + } + + var move = operation(cm, function(e) { + if (!e_button(e)) done(e); + else extend(e); + }); + var up = operation(cm, done); + cm.state.selectingText = up; + on(document, "mousemove", move); + on(document, "mouseup", up); + } + + // Determines whether an event happened in the gutter, and fires the + // handlers for the corresponding event. + function gutterEvent(cm, e, type, prevent) { + try { var mX = e.clientX, mY = e.clientY; } + catch(e) { return false; } + if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false; + if (prevent) e_preventDefault(e); + + var display = cm.display; + var lineBox = display.lineDiv.getBoundingClientRect(); + + if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e); + mY -= lineBox.top - display.viewOffset; + + for (var i = 0; i < cm.options.gutters.length; ++i) { + var g = display.gutters.childNodes[i]; + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY); + var gutter = cm.options.gutters[i]; + signal(cm, type, cm, line, gutter, e); + return e_defaultPrevented(e); + } + } + } + + function clickInGutter(cm, e) { + return gutterEvent(cm, e, "gutterClick", true); + } + + // Kludge to work around strange IE behavior where it'll sometimes + // re-fire a series of drag-related events right after the drop (#1551) + var lastDrop = 0; + + function onDrop(e) { + var cm = this; + clearDragCursor(cm); + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) + return; + e_preventDefault(e); + if (ie) lastDrop = +new Date; + var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; + if (!pos || cm.isReadOnly()) return; + // Might be a file drop, in which case we simply extract the text + // and insert it. + if (files && files.length && window.FileReader && window.File) { + var n = files.length, text = Array(n), read = 0; + var loadFile = function(file, i) { + if (cm.options.allowDropFileTypes && + indexOf(cm.options.allowDropFileTypes, file.type) == -1) + return; + + var reader = new FileReader; + reader.onload = operation(cm, function() { + var content = reader.result; + if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = ""; + text[i] = content; + if (++read == n) { + pos = clipPos(cm.doc, pos); + var change = {from: pos, to: pos, + text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), + origin: "paste"}; + makeChange(cm.doc, change); + setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); + } + }); + reader.readAsText(file); + }; + for (var i = 0; i < n; ++i) loadFile(files[i], i); + } else { // Normal drop + // Don't do a replace if the drop happened inside of the selected text. + if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { + cm.state.draggingText(e); + // Ensure the editor is re-focused + setTimeout(function() {cm.display.input.focus();}, 20); + return; + } + try { + var text = e.dataTransfer.getData("Text"); + if (text) { + if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey)) + var selected = cm.listSelections(); + setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); + if (selected) for (var i = 0; i < selected.length; ++i) + replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag"); + cm.replaceSelection(text, "around", "paste"); + cm.display.input.focus(); + } + } + catch(e){} + } + } + + function onDragStart(cm, e) { + if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; + + e.dataTransfer.setData("Text", cm.getSelection()); + e.dataTransfer.effectAllowed = "copyMove" + + // Use dummy image instead of default browsers image. + // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. + if (e.dataTransfer.setDragImage && !safari) { + var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); + img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; + if (presto) { + img.width = img.height = 1; + cm.display.wrapper.appendChild(img); + // Force a relayout, or Opera won't use our image for some obscure reason + img._top = img.offsetTop; + } + e.dataTransfer.setDragImage(img, 0, 0); + if (presto) img.parentNode.removeChild(img); + } + } + + function onDragOver(cm, e) { + var pos = posFromMouse(cm, e); + if (!pos) return; + var frag = document.createDocumentFragment(); + drawSelectionCursor(cm, pos, frag); + if (!cm.display.dragCursor) { + cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); + cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); + } + removeChildrenAndAdd(cm.display.dragCursor, frag); + } + + function clearDragCursor(cm) { + if (cm.display.dragCursor) { + cm.display.lineSpace.removeChild(cm.display.dragCursor); + cm.display.dragCursor = null; + } + } + + // SCROLL EVENTS + + // Sync the scrollable area and scrollbars, ensure the viewport + // covers the visible area. + function setScrollTop(cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) return; + cm.doc.scrollTop = val; + if (!gecko) updateDisplaySimple(cm, {top: val}); + if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; + cm.display.scrollbars.setScrollTop(val); + if (gecko) updateDisplaySimple(cm); + startWorker(cm, 100); + } + // Sync scroller and scrollbar, ensure the gutter elements are + // aligned. + function setScrollLeft(cm, val, isScroller) { + if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; + val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); + cm.doc.scrollLeft = val; + alignHorizontally(cm); + if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; + cm.display.scrollbars.setScrollLeft(val); + } + + // Since the delta values reported on mouse wheel events are + // unstandardized between browsers and even browser versions, and + // generally horribly unpredictable, this code starts by measuring + // the scroll effect that the first few mouse wheel events have, + // and, from that, detects the way it can convert deltas to pixel + // offsets afterwards. + // + // The reason we want to know the amount a wheel event will scroll + // is that it gives us a chance to update the display before the + // actual scrolling happens, reducing flickering. + + var wheelSamples = 0, wheelPixelsPerUnit = null; + // Fill in a browser-detected starting value on browsers where we + // know one. These don't have to be accurate -- the result of them + // being wrong would just be a slight flicker on the first wheel + // scroll (if it is large enough). + if (ie) wheelPixelsPerUnit = -.53; + else if (gecko) wheelPixelsPerUnit = 15; + else if (chrome) wheelPixelsPerUnit = -.7; + else if (safari) wheelPixelsPerUnit = -1/3; + + var wheelEventDelta = function(e) { + var dx = e.wheelDeltaX, dy = e.wheelDeltaY; + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; + else if (dy == null) dy = e.wheelDelta; + return {x: dx, y: dy}; + }; + CodeMirror.wheelEventPixels = function(e) { + var delta = wheelEventDelta(e); + delta.x *= wheelPixelsPerUnit; + delta.y *= wheelPixelsPerUnit; + return delta; + }; + + function onScrollWheel(cm, e) { + var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; + + var display = cm.display, scroll = display.scroller; + // Quit if there's nothing to scroll here + var canScrollX = scroll.scrollWidth > scroll.clientWidth; + var canScrollY = scroll.scrollHeight > scroll.clientHeight; + if (!(dx && canScrollX || dy && canScrollY)) return; + + // Webkit browsers on OS X abort momentum scrolls when the target + // of the scroll event is removed from the scrollable element. + // This hack (see related code in patchDisplay) makes sure the + // element is kept around. + if (dy && mac && webkit) { + outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + for (var i = 0; i < view.length; i++) { + if (view[i].node == cur) { + cm.display.currentWheelTarget = cur; + break outer; + } + } + } + } + + // On some browsers, horizontal scrolling will cause redraws to + // happen before the gutter has been realigned, causing it to + // wriggle around in a most unseemly way. When we have an + // estimated pixels/delta value, we just handle horizontal + // scrolling entirely here. It'll be slightly off from native, but + // better than glitching out. + if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { + if (dy && canScrollY) + setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); + setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); + // Only prevent default scrolling if vertical scrolling is + // actually possible. Otherwise, it causes vertical scroll + // jitter on OSX trackpads when deltaX is small and deltaY + // is large (issue #3579) + if (!dy || (dy && canScrollY)) + e_preventDefault(e); + display.wheelStartX = null; // Abort measurement, if in progress + return; + } + + // 'Project' the visible viewport to cover the area that is being + // scrolled into view (if we know enough to estimate it). + if (dy && wheelPixelsPerUnit != null) { + var pixels = dy * wheelPixelsPerUnit; + var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; + if (pixels < 0) top = Math.max(0, top + pixels - 50); + else bot = Math.min(cm.doc.height, bot + pixels + 50); + updateDisplaySimple(cm, {top: top, bottom: bot}); + } + + if (wheelSamples < 20) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; + display.wheelDX = dx; display.wheelDY = dy; + setTimeout(function() { + if (display.wheelStartX == null) return; + var movedX = scroll.scrollLeft - display.wheelStartX; + var movedY = scroll.scrollTop - display.wheelStartY; + var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || + (movedX && display.wheelDX && movedX / display.wheelDX); + display.wheelStartX = display.wheelStartY = null; + if (!sample) return; + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); + ++wheelSamples; + }, 200); + } else { + display.wheelDX += dx; display.wheelDY += dy; + } + } + } + + // KEY EVENTS + + // Run a handler that was bound to a key. + function doHandleBinding(cm, bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound]; + if (!bound) return false; + } + // Ensure previous input has been read, so that the handler sees a + // consistent view of the document + cm.display.input.ensurePolled(); + var prevShift = cm.display.shift, done = false; + try { + if (cm.isReadOnly()) cm.state.suppressEdits = true; + if (dropShift) cm.display.shift = false; + done = bound(cm) != Pass; + } finally { + cm.display.shift = prevShift; + cm.state.suppressEdits = false; + } + return done; + } + + function lookupKeyForEditor(cm, name, handle) { + for (var i = 0; i < cm.state.keyMaps.length; i++) { + var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); + if (result) return result; + } + return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) + || lookupKey(name, cm.options.keyMap, handle, cm); + } + + var stopSeq = new Delayed; + function dispatchKey(cm, name, e, handle) { + var seq = cm.state.keySeq; + if (seq) { + if (isModifierKey(name)) return "handled"; + stopSeq.set(50, function() { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null; + cm.display.input.reset(); + } + }); + name = seq + " " + name; + } + var result = lookupKeyForEditor(cm, name, handle); + + if (result == "multi") + cm.state.keySeq = name; + if (result == "handled") + signalLater(cm, "keyHandled", cm, name, e); + + if (result == "handled" || result == "multi") { + e_preventDefault(e); + restartBlink(cm); + } + + if (seq && !result && /\'$/.test(name)) { + e_preventDefault(e); + return true; + } + return !!result; + } + + // Handle a key from the keydown event. + function handleKeyBinding(cm, e) { + var name = keyName(e, true); + if (!name) return false; + + if (e.shiftKey && !cm.state.keySeq) { + // First try to resolve full name (including 'Shift-'). Failing + // that, see if there is a cursor-motion command (starting with + // 'go') bound to the keyname without 'Shift-'. + return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);}) + || dispatchKey(cm, name, e, function(b) { + if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) + return doHandleBinding(cm, b); + }); + } else { + return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); }); + } + } + + // Handle a key from the keypress event + function handleCharBinding(cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, + function(b) { return doHandleBinding(cm, b, true); }); + } + + var lastStoppedKey = null; + function onKeyDown(e) { + var cm = this; + cm.curOp.focus = activeElt(); + if (signalDOMEvent(cm, e)) return; + // IE does strange things with escape. + if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false; + var code = e.keyCode; + cm.display.shift = code == 16 || e.shiftKey; + var handled = handleKeyBinding(cm, e); + if (presto) { + lastStoppedKey = handled ? code : null; + // Opera has no cut event... we try to at least catch the key combo + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) + cm.replaceSelection("", null, "cut"); + } + + // Turn mouse into crosshair when Alt is held on Mac. + if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) + showCrossHair(cm); + } + + function showCrossHair(cm) { + var lineDiv = cm.display.lineDiv; + addClass(lineDiv, "CodeMirror-crosshair"); + + function up(e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair"); + off(document, "keyup", up); + off(document, "mouseover", up); + } + } + on(document, "keyup", up); + on(document, "mouseover", up); + } + + function onKeyUp(e) { + if (e.keyCode == 16) this.doc.sel.shift = false; + signalDOMEvent(this, e); + } + + function onKeyPress(e) { + var cm = this; + if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return; + var keyCode = e.keyCode, charCode = e.charCode; + if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} + if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return; + var ch = String.fromCharCode(charCode == null ? keyCode : charCode); + if (handleCharBinding(cm, e, ch)) return; + cm.display.input.onKeyPress(e); + } + + // FOCUS/BLUR EVENTS + + function delayBlurEvent(cm) { + cm.state.delayingBlurEvent = true; + setTimeout(function() { + if (cm.state.delayingBlurEvent) { + cm.state.delayingBlurEvent = false; + onBlur(cm); + } + }, 100); + } + + function onFocus(cm) { + if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false; + + if (cm.options.readOnly == "nocursor") return; + if (!cm.state.focused) { + signal(cm, "focus", cm); + cm.state.focused = true; + addClass(cm.display.wrapper, "CodeMirror-focused"); + // This test prevents this from firing when a context + // menu is closed (since the input reset would kill the + // select-all detection hack) + if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { + cm.display.input.reset(); + if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730 + } + cm.display.input.receivedFocus(); + } + restartBlink(cm); + } + function onBlur(cm) { + if (cm.state.delayingBlurEvent) return; + + if (cm.state.focused) { + signal(cm, "blur", cm); + cm.state.focused = false; + rmClass(cm.display.wrapper, "CodeMirror-focused"); + } + clearInterval(cm.display.blinker); + setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150); + } + + // CONTEXT MENU HANDLING + + // To make the context menu work, we need to briefly unhide the + // textarea (making it as unobtrusive as possible) to let the + // right-click take effect on it. + function onContextMenu(cm, e) { + if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return; + if (signalDOMEvent(cm, e, "contextmenu")) return; + cm.display.input.onContextMenu(e); + } + + function contextMenuInGutter(cm, e) { + if (!hasHandler(cm, "gutterContextMenu")) return false; + return gutterEvent(cm, e, "gutterContextMenu", false); + } + + // UPDATING + + // Compute the position of the end of a change (its 'to' property + // refers to the pre-change end). + var changeEnd = CodeMirror.changeEnd = function(change) { + if (!change.text) return change.to; + return Pos(change.from.line + change.text.length - 1, + lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); + }; + + // Adjust a position to refer to the post-change position of the + // same text, or the end of the change if the change covers it. + function adjustForChange(pos, change) { + if (cmp(pos, change.from) < 0) return pos; + if (cmp(pos, change.to) <= 0) return changeEnd(change); + + var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; + if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch; + return Pos(line, ch); + } + + function computeSelAfterChange(doc, change) { + var out = []; + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i]; + out.push(new Range(adjustForChange(range.anchor, change), + adjustForChange(range.head, change))); + } + return normalizeSelection(out, doc.sel.primIndex); + } + + function offsetPos(pos, old, nw) { + if (pos.line == old.line) + return Pos(nw.line, pos.ch - old.ch + nw.ch); + else + return Pos(nw.line + (pos.line - old.line), pos.ch); + } + + // Used by replaceSelections to allow moving the selection to the + // start or around the replaced test. Hint may be "start" or "around". + function computeReplacedSel(doc, changes, hint) { + var out = []; + var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + var from = offsetPos(change.from, oldPrev, newPrev); + var to = offsetPos(changeEnd(change), oldPrev, newPrev); + oldPrev = change.to; + newPrev = to; + if (hint == "around") { + var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; + out[i] = new Range(inv ? to : from, inv ? from : to); + } else { + out[i] = new Range(from, from); + } + } + return new Selection(out, doc.sel.primIndex); + } + + // Allow "beforeChange" event handlers to influence a change + function filterChange(doc, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function() { this.canceled = true; } + }; + if (update) obj.update = function(from, to, text, origin) { + if (from) this.from = clipPos(doc, from); + if (to) this.to = clipPos(doc, to); + if (text) this.text = text; + if (origin !== undefined) this.origin = origin; + }; + signal(doc, "beforeChange", doc, obj); + if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); + + if (obj.canceled) return null; + return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; + } + + // Apply a change to a document, and add it to the document's + // history, and propagating it to all linked documents. + function makeChange(doc, change, ignoreReadOnly) { + if (doc.cm) { + if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); + if (doc.cm.state.suppressEdits) return; + } + + if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { + change = filterChange(doc, change, true); + if (!change) return; + } + + // Possibly split or suppress the update based on the presence + // of read-only spans in its range. + var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); + if (split) { + for (var i = split.length - 1; i >= 0; --i) + makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}); + } else { + makeChangeInner(doc, change); + } + } + + function makeChangeInner(doc, change) { + if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return; + var selAfter = computeSelAfterChange(doc, change); + addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); + + makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); + var rebased = []; + + linkedDocs(doc, function(doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); + }); + } + + // Revert a change stored in a document's history. + function makeChangeFromHistory(doc, type, allowSelectionOnly) { + if (doc.cm && doc.cm.state.suppressEdits) return; + + var hist = doc.history, event, selAfter = doc.sel; + var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; + + // Verify that there is a useable event (so that ctrl-z won't + // needlessly clear selection events) + for (var i = 0; i < source.length; i++) { + event = source[i]; + if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) + break; + } + if (i == source.length) return; + hist.lastOrigin = hist.lastSelOrigin = null; + + for (;;) { + event = source.pop(); + if (event.ranges) { + pushSelectionToHistory(event, dest); + if (allowSelectionOnly && !event.equals(doc.sel)) { + setSelection(doc, event, {clearRedo: false}); + return; + } + selAfter = event; + } + else break; + } + + // Build up a reverse change object to add to the opposite history + // stack (redo when undoing, and vice versa). + var antiChanges = []; + pushSelectionToHistory(selAfter, dest); + dest.push({changes: antiChanges, generation: hist.generation}); + hist.generation = event.generation || ++hist.maxGeneration; + + var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); + + for (var i = event.changes.length - 1; i >= 0; --i) { + var change = event.changes[i]; + change.origin = type; + if (filter && !filterChange(doc, change, false)) { + source.length = 0; + return; + } + + antiChanges.push(historyChangeFromChange(doc, change)); + + var after = i ? computeSelAfterChange(doc, change) : lst(source); + makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); + if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); + var rebased = []; + + // Propagate to the linked documents + linkedDocs(doc, function(doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); + }); + } + } + + // Sub-views need their line numbers shifted when text is added + // above or below them in the parent document. + function shiftDoc(doc, distance) { + if (distance == 0) return; + doc.first += distance; + doc.sel = new Selection(map(doc.sel.ranges, function(range) { + return new Range(Pos(range.anchor.line + distance, range.anchor.ch), + Pos(range.head.line + distance, range.head.ch)); + }), doc.sel.primIndex); + if (doc.cm) { + regChange(doc.cm, doc.first, doc.first - distance, distance); + for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) + regLineChange(doc.cm, l, "gutter"); + } + } + + // More lower-level change function, handling only a single document + // (not linked ones). + function makeChangeSingleDoc(doc, change, selAfter, spans) { + if (doc.cm && !doc.cm.curOp) + return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); + + if (change.to.line < doc.first) { + shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); + return; + } + if (change.from.line > doc.lastLine()) return; + + // Clip the change to the size of this doc + if (change.from.line < doc.first) { + var shift = change.text.length - 1 - (doc.first - change.from.line); + shiftDoc(doc, shift); + change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], origin: change.origin}; + } + var last = doc.lastLine(); + if (change.to.line > last) { + change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), + text: [change.text[0]], origin: change.origin}; + } + + change.removed = getBetween(doc, change.from, change.to); + + if (!selAfter) selAfter = computeSelAfterChange(doc, change); + if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans); + else updateDoc(doc, change, spans); + setSelectionNoUndo(doc, selAfter, sel_dontScroll); + } + + // Handle the interaction of a change to a document with the editor + // that this document is part of. + function makeChangeSingleDocInEditor(cm, change, spans) { + var doc = cm.doc, display = cm.display, from = change.from, to = change.to; + + var recomputeMaxLength = false, checkWidthStart = from.line; + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); + doc.iter(checkWidthStart, to.line + 1, function(line) { + if (line == display.maxLine) { + recomputeMaxLength = true; + return true; + } + }); + } + + if (doc.sel.contains(change.from, change.to) > -1) + signalCursorActivity(cm); + + updateDoc(doc, change, spans, estimateHeight(cm)); + + if (!cm.options.lineWrapping) { + doc.iter(checkWidthStart, from.line + change.text.length, function(line) { + var len = lineLength(line); + if (len > display.maxLineLength) { + display.maxLine = line; + display.maxLineLength = len; + display.maxLineChanged = true; + recomputeMaxLength = false; + } + }); + if (recomputeMaxLength) cm.curOp.updateMaxLine = true; + } + + // Adjust frontier, schedule worker + doc.frontier = Math.min(doc.frontier, from.line); + startWorker(cm, 400); + + var lendiff = change.text.length - (to.line - from.line) - 1; + // Remember that these lines changed, for updating the display + if (change.full) + regChange(cm); + else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) + regLineChange(cm, from.line, "text"); + else + regChange(cm, from.line, to.line + 1, lendiff); + + var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); + if (changeHandler || changesHandler) { + var obj = { + from: from, to: to, + text: change.text, + removed: change.removed, + origin: change.origin + }; + if (changeHandler) signalLater(cm, "change", cm, obj); + if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); + } + cm.display.selForContextMenu = null; + } + + function replaceRange(doc, code, from, to, origin) { + if (!to) to = from; + if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } + if (typeof code == "string") code = doc.splitLines(code); + makeChange(doc, {from: from, to: to, text: code, origin: origin}); + } + + // SCROLLING THINGS INTO VIEW + + // If an editor sits on the top or bottom of the window, partially + // scrolled out of view, this ensures that the cursor is visible. + function maybeScrollWindow(cm, coords) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) return; + + var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; + if (coords.top + box.top < 0) doScroll = true; + else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; + if (doScroll != null && !phantom) { + var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " + + (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " + + (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " + + coords.left + "px; width: 2px;"); + cm.display.lineSpace.appendChild(scrollNode); + scrollNode.scrollIntoView(doScroll); + cm.display.lineSpace.removeChild(scrollNode); + } + } + + // Scroll a given position into view (immediately), verifying that + // it actually became visible (as line heights are accurately + // measured, the position of something may 'drift' during drawing). + function scrollPosIntoView(cm, pos, end, margin) { + if (margin == null) margin = 0; + for (var limit = 0; limit < 5; limit++) { + var changed = false, coords = cursorCoords(cm, pos); + var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); + var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), + Math.min(coords.top, endCoords.top) - margin, + Math.max(coords.left, endCoords.left), + Math.max(coords.bottom, endCoords.bottom) + margin); + var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; + if (scrollPos.scrollTop != null) { + setScrollTop(cm, scrollPos.scrollTop); + if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; + } + if (!changed) break; + } + return coords; + } + + // Scroll a given set of coordinates into view (immediately). + function scrollIntoView(cm, x1, y1, x2, y2) { + var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); + if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); + if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); + } + + // Calculate a new scroll position needed to scroll the given + // rectangle into view. Returns an object with scrollTop and + // scrollLeft properties. When these are undefined, the + // vertical/horizontal position does not need to be adjusted. + function calculateScrollPos(cm, x1, y1, x2, y2) { + var display = cm.display, snapMargin = textHeight(cm.display); + if (y1 < 0) y1 = 0; + var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; + var screen = displayHeight(cm), result = {}; + if (y2 - y1 > screen) y2 = y1 + screen; + var docBottom = cm.doc.height + paddingVert(display); + var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; + if (y1 < screentop) { + result.scrollTop = atTop ? 0 : y1; + } else if (y2 > screentop + screen) { + var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); + if (newTop != screentop) result.scrollTop = newTop; + } + + var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; + var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); + var tooWide = x2 - x1 > screenw; + if (tooWide) x2 = x1 + screenw; + if (x1 < 10) + result.scrollLeft = 0; + else if (x1 < screenleft) + result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)); + else if (x2 > screenw + screenleft - 3) + result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw; + return result; + } + + // Store a relative adjustment to the scroll position in the current + // operation (to be applied when the operation finishes). + function addToScrollPos(cm, left, top) { + if (left != null || top != null) resolveScrollToPos(cm); + if (left != null) + cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left; + if (top != null) + cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; + } + + // Make sure that at the end of the operation the current cursor is + // shown. + function ensureCursorVisible(cm) { + resolveScrollToPos(cm); + var cur = cm.getCursor(), from = cur, to = cur; + if (!cm.options.lineWrapping) { + from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; + to = Pos(cur.line, cur.ch + 1); + } + cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}; + } + + // When an operation has its scrollToPos property set, and another + // scroll action is applied before the end of the operation, this + // 'simulates' scrolling that position into view in a cheap way, so + // that the effect of intermediate scroll commands is not ignored. + function resolveScrollToPos(cm) { + var range = cm.curOp.scrollToPos; + if (range) { + cm.curOp.scrollToPos = null; + var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); + var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), + Math.min(from.top, to.top) - range.margin, + Math.max(from.right, to.right), + Math.max(from.bottom, to.bottom) + range.margin); + cm.scrollTo(sPos.scrollLeft, sPos.scrollTop); + } + } + + // API UTILITIES + + // Indent the given line. The how parameter can be "smart", + // "add"/null, "subtract", or "prev". When aggressive is false + // (typically set to true for forced single-line indents), empty + // lines are not indented, and places where the mode returns Pass + // are left alone. + function indentLine(cm, n, how, aggressive) { + var doc = cm.doc, state; + if (how == null) how = "add"; + if (how == "smart") { + // Fall back to "prev" when the mode doesn't have an indentation + // method. + if (!doc.mode.indent) how = "prev"; + else state = getStateBefore(cm, n); + } + + var tabSize = cm.options.tabSize; + var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); + if (line.stateAfter) line.stateAfter = null; + var curSpaceString = line.text.match(/^\s*/)[0], indentation; + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0; + how = "not"; + } else if (how == "smart") { + indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); + if (indentation == Pass || indentation > 150) { + if (!aggressive) return; + how = "prev"; + } + } + if (how == "prev") { + if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); + else indentation = 0; + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit; + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit; + } else if (typeof how == "number") { + indentation = curSpace + how; + } + indentation = Math.max(0, indentation); + + var indentString = "", pos = 0; + if (cm.options.indentWithTabs) + for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} + if (pos < indentation) indentString += spaceStr(indentation - pos); + + if (indentString != curSpaceString) { + replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); + line.stateAfter = null; + return true; + } else { + // Ensure that, if the cursor was in the whitespace at the start + // of the line, it is moved to the end of that space. + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i]; + if (range.head.line == n && range.head.ch < curSpaceString.length) { + var pos = Pos(n, curSpaceString.length); + replaceOneSelection(doc, i, new Range(pos, pos)); + break; + } + } + } + } + + // Utility for applying a change to a line by handle or number, + // returning the number and optionally registering the line as + // changed. + function changeLine(doc, handle, changeType, op) { + var no = handle, line = handle; + if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); + else no = lineNo(handle); + if (no == null) return null; + if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType); + return line; + } + + // Helper for deleting text near the selection(s), used to implement + // backspace, delete, and similar functionality. + function deleteNearSelection(cm, compute) { + var ranges = cm.doc.sel.ranges, kill = []; + // Build up a set of ranges to kill first, merging overlapping + // ranges. + for (var i = 0; i < ranges.length; i++) { + var toKill = compute(ranges[i]); + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + var replaced = kill.pop(); + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from; + break; + } + } + kill.push(toKill); + } + // Next, remove those actual ranges. + runInOp(cm, function() { + for (var i = kill.length - 1; i >= 0; i--) + replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); + ensureCursorVisible(cm); + }); + } + + // Used for horizontal relative motion. Dir is -1 or 1 (left or + // right), unit can be "char", "column" (like char, but doesn't + // cross line boundaries), "word" (across next word), or "group" (to + // the start of next group of word or non-word-non-whitespace + // chars). The visually param controls whether, in right-to-left + // text, direction 1 means to move towards the next index in the + // string, or towards the character to the right of the current + // position. The resulting position will have a hitSide=true + // property if it reached the end of the document. + function findPosH(doc, pos, dir, unit, visually) { + var line = pos.line, ch = pos.ch, origDir = dir; + var lineObj = getLine(doc, line); + function findNextLine() { + var l = line + dir; + if (l < doc.first || l >= doc.first + doc.size) return false + line = l; + return lineObj = getLine(doc, l); + } + function moveOnce(boundToLine) { + var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); + if (next == null) { + if (!boundToLine && findNextLine()) { + if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); + else ch = dir < 0 ? lineObj.text.length : 0; + } else return false + } else ch = next; + return true; + } + + if (unit == "char") { + moveOnce() + } else if (unit == "column") { + moveOnce(true) + } else if (unit == "word" || unit == "group") { + var sawType = null, group = unit == "group"; + var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); + for (var first = true;; first = false) { + if (dir < 0 && !moveOnce(!first)) break; + var cur = lineObj.text.charAt(ch) || "\n"; + var type = isWordChar(cur, helper) ? "w" + : group && cur == "\n" ? "n" + : !group || /\s/.test(cur) ? null + : "p"; + if (group && !first && !type) type = "s"; + if (sawType && sawType != type) { + if (dir < 0) {dir = 1; moveOnce();} + break; + } + + if (type) sawType = type; + if (dir > 0 && !moveOnce(!first)) break; + } + } + var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true); + if (!cmp(pos, result)) result.hitSide = true; + return result; + } + + // For relative vertical movement. Dir may be -1 or 1. Unit can be + // "page" or "line". The resulting position will have a hitSide=true + // property if it reached the end of the document. + function findPosV(cm, pos, dir, unit) { + var doc = cm.doc, x = pos.left, y; + if (unit == "page") { + var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); + y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display)); + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3; + } + for (;;) { + var target = coordsChar(cm, x, y); + if (!target.outside) break; + if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } + y += dir * 5; + } + return target; + } + + // EDITOR METHODS + + // The publicly visible API. Note that methodOp(f) means + // 'wrap f in an operation, performed on its `this` parameter'. + + // This is not the complete set of editor methods. Most of the + // methods defined on the Doc type are also injected into + // CodeMirror.prototype, for backwards compatibility and + // convenience. + + CodeMirror.prototype = { + constructor: CodeMirror, + focus: function(){window.focus(); this.display.input.focus();}, + + setOption: function(option, value) { + var options = this.options, old = options[option]; + if (options[option] == value && option != "mode") return; + options[option] = value; + if (optionHandlers.hasOwnProperty(option)) + operation(this, optionHandlers[option])(this, value, old); + }, + + getOption: function(option) {return this.options[option];}, + getDoc: function() {return this.doc;}, + + addKeyMap: function(map, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)); + }, + removeKeyMap: function(map) { + var maps = this.state.keyMaps; + for (var i = 0; i < maps.length; ++i) + if (maps[i] == map || maps[i].name == map) { + maps.splice(i, 1); + return true; + } + }, + + addOverlay: methodOp(function(spec, options) { + var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); + if (mode.startState) throw new Error("Overlays may not be stateful."); + this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); + this.state.modeGen++; + regChange(this); + }), + removeOverlay: methodOp(function(spec) { + var overlays = this.state.overlays; + for (var i = 0; i < overlays.length; ++i) { + var cur = overlays[i].modeSpec; + if (cur == spec || typeof spec == "string" && cur.name == spec) { + overlays.splice(i, 1); + this.state.modeGen++; + regChange(this); + return; + } + } + }), + + indentLine: methodOp(function(n, dir, aggressive) { + if (typeof dir != "string" && typeof dir != "number") { + if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; + else dir = dir ? "add" : "subtract"; + } + if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); + }), + indentSelection: methodOp(function(how) { + var ranges = this.doc.sel.ranges, end = -1; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (!range.empty()) { + var from = range.from(), to = range.to(); + var start = Math.max(end, from.line); + end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; + for (var j = start; j < end; ++j) + indentLine(this, j, how); + var newRanges = this.doc.sel.ranges; + if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) + replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); + } else if (range.head.line > end) { + indentLine(this, range.head.line, how, true); + end = range.head.line; + if (i == this.doc.sel.primIndex) ensureCursorVisible(this); + } + } + }), + + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function(pos, precise) { + return takeToken(this, pos, precise); + }, + + getLineTokens: function(line, precise) { + return takeToken(this, Pos(line), precise, true); + }, + + getTokenTypeAt: function(pos) { + pos = clipPos(this.doc, pos); + var styles = getLineStyles(this, getLine(this.doc, pos.line)); + var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; + var type; + if (ch == 0) type = styles[2]; + else for (;;) { + var mid = (before + after) >> 1; + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; + else if (styles[mid * 2 + 1] < ch) before = mid + 1; + else { type = styles[mid * 2 + 2]; break; } + } + var cut = type ? type.indexOf("cm-overlay ") : -1; + return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); + }, + + getModeAt: function(pos) { + var mode = this.doc.mode; + if (!mode.innerMode) return mode; + return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; + }, + + getHelper: function(pos, type) { + return this.getHelpers(pos, type)[0]; + }, + + getHelpers: function(pos, type) { + var found = []; + if (!helpers.hasOwnProperty(type)) return found; + var help = helpers[type], mode = this.getModeAt(pos); + if (typeof mode[type] == "string") { + if (help[mode[type]]) found.push(help[mode[type]]); + } else if (mode[type]) { + for (var i = 0; i < mode[type].length; i++) { + var val = help[mode[type][i]]; + if (val) found.push(val); + } + } else if (mode.helperType && help[mode.helperType]) { + found.push(help[mode.helperType]); + } else if (help[mode.name]) { + found.push(help[mode.name]); + } + for (var i = 0; i < help._global.length; i++) { + var cur = help._global[i]; + if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) + found.push(cur.val); + } + return found; + }, + + getStateAfter: function(line, precise) { + var doc = this.doc; + line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); + return getStateBefore(this, line + 1, precise); + }, + + cursorCoords: function(start, mode) { + var pos, range = this.doc.sel.primary(); + if (start == null) pos = range.head; + else if (typeof start == "object") pos = clipPos(this.doc, start); + else pos = start ? range.from() : range.to(); + return cursorCoords(this, pos, mode || "page"); + }, + + charCoords: function(pos, mode) { + return charCoords(this, clipPos(this.doc, pos), mode || "page"); + }, + + coordsChar: function(coords, mode) { + coords = fromCoordSystem(this, coords, mode || "page"); + return coordsChar(this, coords.left, coords.top); + }, + + lineAtHeight: function(height, mode) { + height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; + return lineAtHeight(this.doc, height + this.display.viewOffset); + }, + heightAtLine: function(line, mode) { + var end = false, lineObj; + if (typeof line == "number") { + var last = this.doc.first + this.doc.size - 1; + if (line < this.doc.first) line = this.doc.first; + else if (line > last) { line = last; end = true; } + lineObj = getLine(this.doc, line); + } else { + lineObj = line; + } + return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top + + (end ? this.doc.height - heightAtLine(lineObj) : 0); + }, + + defaultTextHeight: function() { return textHeight(this.display); }, + defaultCharWidth: function() { return charWidth(this.display); }, + + setGutterMarker: methodOp(function(line, gutterID, value) { + return changeLine(this.doc, line, "gutter", function(line) { + var markers = line.gutterMarkers || (line.gutterMarkers = {}); + markers[gutterID] = value; + if (!value && isEmpty(markers)) line.gutterMarkers = null; + return true; + }); + }), + + clearGutter: methodOp(function(gutterID) { + var cm = this, doc = cm.doc, i = doc.first; + doc.iter(function(line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + line.gutterMarkers[gutterID] = null; + regLineChange(cm, i, "gutter"); + if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; + } + ++i; + }); + }), + + lineInfo: function(line) { + if (typeof line == "number") { + if (!isLine(this.doc, line)) return null; + var n = line; + line = getLine(this.doc, line); + if (!line) return null; + } else { + var n = lineNo(line); + if (n == null) return null; + } + return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, + textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, + widgets: line.widgets}; + }, + + getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};}, + + addWidget: function(pos, node, scroll, vert, horiz) { + var display = this.display; + pos = cursorCoords(this, clipPos(this.doc, pos)); + var top = pos.bottom, left = pos.left; + node.style.position = "absolute"; + node.setAttribute("cm-ignore-events", "true"); + this.display.input.setUneditable(node); + display.sizer.appendChild(node); + if (vert == "over") { + top = pos.top; + } else if (vert == "above" || vert == "near") { + var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), + hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); + // Default to positioning above (if specified and possible); otherwise default to positioning below + if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) + top = pos.top - node.offsetHeight; + else if (pos.bottom + node.offsetHeight <= vspace) + top = pos.bottom; + if (left + node.offsetWidth > hspace) + left = hspace - node.offsetWidth; + } + node.style.top = top + "px"; + node.style.left = node.style.right = ""; + if (horiz == "right") { + left = display.sizer.clientWidth - node.offsetWidth; + node.style.right = "0px"; + } else { + if (horiz == "left") left = 0; + else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; + node.style.left = left + "px"; + } + if (scroll) + scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight); + }, + + triggerOnKeyDown: methodOp(onKeyDown), + triggerOnKeyPress: methodOp(onKeyPress), + triggerOnKeyUp: onKeyUp, + + execCommand: function(cmd) { + if (commands.hasOwnProperty(cmd)) + return commands[cmd].call(null, this); + }, + + triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), + + findPosH: function(from, amount, unit, visually) { + var dir = 1; + if (amount < 0) { dir = -1; amount = -amount; } + for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { + cur = findPosH(this.doc, cur, dir, unit, visually); + if (cur.hitSide) break; + } + return cur; + }, + + moveH: methodOp(function(dir, unit) { + var cm = this; + cm.extendSelectionsBy(function(range) { + if (cm.display.shift || cm.doc.extend || range.empty()) + return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually); + else + return dir < 0 ? range.from() : range.to(); + }, sel_move); + }), + + deleteH: methodOp(function(dir, unit) { + var sel = this.doc.sel, doc = this.doc; + if (sel.somethingSelected()) + doc.replaceSelection("", null, "+delete"); + else + deleteNearSelection(this, function(range) { + var other = findPosH(doc, range.head, dir, unit, false); + return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}; + }); + }), + + findPosV: function(from, amount, unit, goalColumn) { + var dir = 1, x = goalColumn; + if (amount < 0) { dir = -1; amount = -amount; } + for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { + var coords = cursorCoords(this, cur, "div"); + if (x == null) x = coords.left; + else coords.left = x; + cur = findPosV(this, coords, dir, unit); + if (cur.hitSide) break; + } + return cur; + }, + + moveV: methodOp(function(dir, unit) { + var cm = this, doc = this.doc, goals = []; + var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected(); + doc.extendSelectionsBy(function(range) { + if (collapse) + return dir < 0 ? range.from() : range.to(); + var headPos = cursorCoords(cm, range.head, "div"); + if (range.goalColumn != null) headPos.left = range.goalColumn; + goals.push(headPos.left); + var pos = findPosV(cm, headPos, dir, unit); + if (unit == "page" && range == doc.sel.primary()) + addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top); + return pos; + }, sel_move); + if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++) + doc.sel.ranges[i].goalColumn = goals[i]; + }), + + // Find the word at the given position (as returned by coordsChar). + findWordAt: function(pos) { + var doc = this.doc, line = getLine(doc, pos.line).text; + var start = pos.ch, end = pos.ch; + if (line) { + var helper = this.getHelper(pos, "wordChars"); + if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; + var startChar = line.charAt(start); + var check = isWordChar(startChar, helper) + ? function(ch) { return isWordChar(ch, helper); } + : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} + : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; + while (start > 0 && check(line.charAt(start - 1))) --start; + while (end < line.length && check(line.charAt(end))) ++end; + } + return new Range(Pos(pos.line, start), Pos(pos.line, end)); + }, + + toggleOverwrite: function(value) { + if (value != null && value == this.state.overwrite) return; + if (this.state.overwrite = !this.state.overwrite) + addClass(this.display.cursorDiv, "CodeMirror-overwrite"); + else + rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); + + signal(this, "overwriteToggle", this, this.state.overwrite); + }, + hasFocus: function() { return this.display.input.getField() == activeElt(); }, + isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit); }, + + scrollTo: methodOp(function(x, y) { + if (x != null || y != null) resolveScrollToPos(this); + if (x != null) this.curOp.scrollLeft = x; + if (y != null) this.curOp.scrollTop = y; + }), + getScrollInfo: function() { + var scroller = this.display.scroller; + return {left: scroller.scrollLeft, top: scroller.scrollTop, + height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, + width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, + clientHeight: displayHeight(this), clientWidth: displayWidth(this)}; + }, + + scrollIntoView: methodOp(function(range, margin) { + if (range == null) { + range = {from: this.doc.sel.primary().head, to: null}; + if (margin == null) margin = this.options.cursorScrollMargin; + } else if (typeof range == "number") { + range = {from: Pos(range, 0), to: null}; + } else if (range.from == null) { + range = {from: range, to: null}; + } + if (!range.to) range.to = range.from; + range.margin = margin || 0; + + if (range.from.line != null) { + resolveScrollToPos(this); + this.curOp.scrollToPos = range; + } else { + var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left), + Math.min(range.from.top, range.to.top) - range.margin, + Math.max(range.from.right, range.to.right), + Math.max(range.from.bottom, range.to.bottom) + range.margin); + this.scrollTo(sPos.scrollLeft, sPos.scrollTop); + } + }), + + setSize: methodOp(function(width, height) { + var cm = this; + function interpret(val) { + return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; + } + if (width != null) cm.display.wrapper.style.width = interpret(width); + if (height != null) cm.display.wrapper.style.height = interpret(height); + if (cm.options.lineWrapping) clearLineMeasurementCache(this); + var lineNo = cm.display.viewFrom; + cm.doc.iter(lineNo, cm.display.viewTo, function(line) { + if (line.widgets) for (var i = 0; i < line.widgets.length; i++) + if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; } + ++lineNo; + }); + cm.curOp.forceUpdate = true; + signal(cm, "refresh", this); + }), + + operation: function(f){return runInOp(this, f);}, + + refresh: methodOp(function() { + var oldHeight = this.display.cachedTextHeight; + regChange(this); + this.curOp.forceUpdate = true; + clearCaches(this); + this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop); + updateGutterSpace(this); + if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) + estimateLineHeights(this); + signal(this, "refresh", this); + }), + + swapDoc: methodOp(function(doc) { + var old = this.doc; + old.cm = null; + attachDoc(this, doc); + clearCaches(this); + this.display.input.reset(); + this.scrollTo(doc.scrollLeft, doc.scrollTop); + this.curOp.forceScroll = true; + signalLater(this, "swapDoc", this, old); + return old; + }), + + getInputField: function(){return this.display.input.getField();}, + getWrapperElement: function(){return this.display.wrapper;}, + getScrollerElement: function(){return this.display.scroller;}, + getGutterElement: function(){return this.display.gutters;} + }; + eventMixin(CodeMirror); + + // OPTION DEFAULTS + + // The default configuration options. + var defaults = CodeMirror.defaults = {}; + // Functions to run when options are changed. + var optionHandlers = CodeMirror.optionHandlers = {}; + + function option(name, deflt, handle, notOnInit) { + CodeMirror.defaults[name] = deflt; + if (handle) optionHandlers[name] = + notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; + } + + // Passed to option handlers when there is no old value. + var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; + + // These two are, on init, called from the constructor because they + // have to be initialized before the editor can start at all. + option("value", "", function(cm, val) { + cm.setValue(val); + }, true); + option("mode", null, function(cm, val) { + cm.doc.modeOption = val; + loadMode(cm); + }, true); + + option("indentUnit", 2, loadMode, true); + option("indentWithTabs", false); + option("smartIndent", true); + option("tabSize", 4, function(cm) { + resetModeState(cm); + clearCaches(cm); + regChange(cm); + }, true); + option("lineSeparator", null, function(cm, val) { + cm.doc.lineSep = val; + if (!val) return; + var newBreaks = [], lineNo = cm.doc.first; + cm.doc.iter(function(line) { + for (var pos = 0;;) { + var found = line.text.indexOf(val, pos); + if (found == -1) break; + pos = found + val.length; + newBreaks.push(Pos(lineNo, found)); + } + lineNo++; + }); + for (var i = newBreaks.length - 1; i >= 0; i--) + replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) + }); + option("specialChars", /[\u0000-\u001f\u007f\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) { + cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); + if (old != CodeMirror.Init) cm.refresh(); + }); + option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true); + option("electricChars", true); + option("inputStyle", mobile ? "contenteditable" : "textarea", function() { + throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME + }, true); + option("rtlMoveVisually", !windows); + option("wholeLineUpdateBefore", true); + + option("theme", "default", function(cm) { + themeChanged(cm); + guttersChanged(cm); + }, true); + option("keyMap", "default", function(cm, val, old) { + var next = getKeyMap(val); + var prev = old != CodeMirror.Init && getKeyMap(old); + if (prev && prev.detach) prev.detach(cm, next); + if (next.attach) next.attach(cm, prev || null); + }); + option("extraKeys", null); + + option("lineWrapping", false, wrappingChanged, true); + option("gutters", [], function(cm) { + setGuttersForLineNumbers(cm.options); + guttersChanged(cm); + }, true); + option("fixedGutter", true, function(cm, val) { + cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; + cm.refresh(); + }, true); + option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true); + option("scrollbarStyle", "native", function(cm) { + initScrollbars(cm); + updateScrollbars(cm); + cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); + cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); + }, true); + option("lineNumbers", false, function(cm) { + setGuttersForLineNumbers(cm.options); + guttersChanged(cm); + }, true); + option("firstLineNumber", 1, guttersChanged, true); + option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true); + option("showCursorWhenSelecting", false, updateSelection, true); + + option("resetSelectionOnContextMenu", true); + option("lineWiseCopyCut", true); + + option("readOnly", false, function(cm, val) { + if (val == "nocursor") { + onBlur(cm); + cm.display.input.blur(); + cm.display.disabled = true; + } else { + cm.display.disabled = false; + } + cm.display.input.readOnlyChanged(val) + }); + option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true); + option("dragDrop", true, dragDropChanged); + option("allowDropFileTypes", null); + + option("cursorBlinkRate", 530); + option("cursorScrollMargin", 0); + option("cursorHeight", 1, updateSelection, true); + option("singleCursorHeightPerLine", true, updateSelection, true); + option("workTime", 100); + option("workDelay", 100); + option("flattenSpans", true, resetModeState, true); + option("addModeClass", false, resetModeState, true); + option("pollInterval", 100); + option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;}); + option("historyEventDelay", 1250); + option("viewportMargin", 10, function(cm){cm.refresh();}, true); + option("maxHighlightLength", 10000, resetModeState, true); + option("moveInputWithCursor", true, function(cm, val) { + if (!val) cm.display.input.resetPosition(); + }); + + option("tabindex", null, function(cm, val) { + cm.display.input.getField().tabIndex = val || ""; + }); + option("autofocus", null); + + // MODE DEFINITION AND QUERYING + + // Known modes, by name and by MIME + var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; + + // Extra arguments are stored as the mode's dependencies, which is + // used by (legacy) mechanisms like loadmode.js to automatically + // load a mode. (Preferred mechanism is the require/define calls.) + CodeMirror.defineMode = function(name, mode) { + if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; + if (arguments.length > 2) + mode.dependencies = Array.prototype.slice.call(arguments, 2); + modes[name] = mode; + }; + + CodeMirror.defineMIME = function(mime, spec) { + mimeModes[mime] = spec; + }; + + // Given a MIME type, a {name, ...options} config object, or a name + // string, return a mode config object. + CodeMirror.resolveMode = function(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec]; + } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { + var found = mimeModes[spec.name]; + if (typeof found == "string") found = {name: found}; + spec = createObj(found, spec); + spec.name = found.name; + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return CodeMirror.resolveMode("application/xml"); + } + if (typeof spec == "string") return {name: spec}; + else return spec || {name: "null"}; + }; + + // Given a mode spec (anything that resolveMode accepts), find and + // initialize an actual mode object. + CodeMirror.getMode = function(options, spec) { + var spec = CodeMirror.resolveMode(spec); + var mfactory = modes[spec.name]; + if (!mfactory) return CodeMirror.getMode(options, "text/plain"); + var modeObj = mfactory(options, spec); + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name]; + for (var prop in exts) { + if (!exts.hasOwnProperty(prop)) continue; + if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; + modeObj[prop] = exts[prop]; + } + } + modeObj.name = spec.name; + if (spec.helperType) modeObj.helperType = spec.helperType; + if (spec.modeProps) for (var prop in spec.modeProps) + modeObj[prop] = spec.modeProps[prop]; + + return modeObj; + }; + + // Minimal default mode. + CodeMirror.defineMode("null", function() { + return {token: function(stream) {stream.skipToEnd();}}; + }); + CodeMirror.defineMIME("text/plain", "null"); + + // This can be used to attach properties to mode objects from + // outside the actual mode definition. + var modeExtensions = CodeMirror.modeExtensions = {}; + CodeMirror.extendMode = function(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); + copyObj(properties, exts); + }; + + // EXTENSIONS + + CodeMirror.defineExtension = function(name, func) { + CodeMirror.prototype[name] = func; + }; + CodeMirror.defineDocExtension = function(name, func) { + Doc.prototype[name] = func; + }; + CodeMirror.defineOption = option; + + var initHooks = []; + CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; + + var helpers = CodeMirror.helpers = {}; + CodeMirror.registerHelper = function(type, name, value) { + if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []}; + helpers[type][name] = value; + }; + CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { + CodeMirror.registerHelper(type, name, value); + helpers[type]._global.push({pred: predicate, val: value}); + }; + + // MODE STATE HANDLING + + // Utility functions for working with state. Exported because nested + // modes need to do this for their inner modes. + + var copyState = CodeMirror.copyState = function(mode, state) { + if (state === true) return state; + if (mode.copyState) return mode.copyState(state); + var nstate = {}; + for (var n in state) { + var val = state[n]; + if (val instanceof Array) val = val.concat([]); + nstate[n] = val; + } + return nstate; + }; + + var startState = CodeMirror.startState = function(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true; + }; + + // Given a mode and a state (for that mode), find the inner mode and + // state at the position that the state refers to. + CodeMirror.innerMode = function(mode, state) { + while (mode.innerMode) { + var info = mode.innerMode(state); + if (!info || info.mode == mode) break; + state = info.state; + mode = info.mode; + } + return info || {mode: mode, state: state}; + }; + + // STANDARD COMMANDS + + // Commands are parameter-less actions that can be performed on an + // editor, mostly used for keybindings. + var commands = CodeMirror.commands = { + selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);}, + singleSelection: function(cm) { + cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); + }, + killLine: function(cm) { + deleteNearSelection(cm, function(range) { + if (range.empty()) { + var len = getLine(cm.doc, range.head.line).text.length; + if (range.head.ch == len && range.head.line < cm.lastLine()) + return {from: range.head, to: Pos(range.head.line + 1, 0)}; + else + return {from: range.head, to: Pos(range.head.line, len)}; + } else { + return {from: range.from(), to: range.to()}; + } + }); + }, + deleteLine: function(cm) { + deleteNearSelection(cm, function(range) { + return {from: Pos(range.from().line, 0), + to: clipPos(cm.doc, Pos(range.to().line + 1, 0))}; + }); + }, + delLineLeft: function(cm) { + deleteNearSelection(cm, function(range) { + return {from: Pos(range.from().line, 0), to: range.from()}; + }); + }, + delWrappedLineLeft: function(cm) { + deleteNearSelection(cm, function(range) { + var top = cm.charCoords(range.head, "div").top + 5; + var leftPos = cm.coordsChar({left: 0, top: top}, "div"); + return {from: leftPos, to: range.from()}; + }); + }, + delWrappedLineRight: function(cm) { + deleteNearSelection(cm, function(range) { + var top = cm.charCoords(range.head, "div").top + 5; + var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); + return {from: range.from(), to: rightPos }; + }); + }, + undo: function(cm) {cm.undo();}, + redo: function(cm) {cm.redo();}, + undoSelection: function(cm) {cm.undoSelection();}, + redoSelection: function(cm) {cm.redoSelection();}, + goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, + goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, + goLineStart: function(cm) { + cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); }, + {origin: "+move", bias: 1}); + }, + goLineStartSmart: function(cm) { + cm.extendSelectionsBy(function(range) { + return lineStartSmart(cm, range.head); + }, {origin: "+move", bias: 1}); + }, + goLineEnd: function(cm) { + cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); }, + {origin: "+move", bias: -1}); + }, + goLineRight: function(cm) { + cm.extendSelectionsBy(function(range) { + var top = cm.charCoords(range.head, "div").top + 5; + return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); + }, sel_move); + }, + goLineLeft: function(cm) { + cm.extendSelectionsBy(function(range) { + var top = cm.charCoords(range.head, "div").top + 5; + return cm.coordsChar({left: 0, top: top}, "div"); + }, sel_move); + }, + goLineLeftSmart: function(cm) { + cm.extendSelectionsBy(function(range) { + var top = cm.charCoords(range.head, "div").top + 5; + var pos = cm.coordsChar({left: 0, top: top}, "div"); + if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head); + return pos; + }, sel_move); + }, + goLineUp: function(cm) {cm.moveV(-1, "line");}, + goLineDown: function(cm) {cm.moveV(1, "line");}, + goPageUp: function(cm) {cm.moveV(-1, "page");}, + goPageDown: function(cm) {cm.moveV(1, "page");}, + goCharLeft: function(cm) {cm.moveH(-1, "char");}, + goCharRight: function(cm) {cm.moveH(1, "char");}, + goColumnLeft: function(cm) {cm.moveH(-1, "column");}, + goColumnRight: function(cm) {cm.moveH(1, "column");}, + goWordLeft: function(cm) {cm.moveH(-1, "word");}, + goGroupRight: function(cm) {cm.moveH(1, "group");}, + goGroupLeft: function(cm) {cm.moveH(-1, "group");}, + goWordRight: function(cm) {cm.moveH(1, "word");}, + delCharBefore: function(cm) {cm.deleteH(-1, "char");}, + delCharAfter: function(cm) {cm.deleteH(1, "char");}, + delWordBefore: function(cm) {cm.deleteH(-1, "word");}, + delWordAfter: function(cm) {cm.deleteH(1, "word");}, + delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, + delGroupAfter: function(cm) {cm.deleteH(1, "group");}, + indentAuto: function(cm) {cm.indentSelection("smart");}, + indentMore: function(cm) {cm.indentSelection("add");}, + indentLess: function(cm) {cm.indentSelection("subtract");}, + insertTab: function(cm) {cm.replaceSelection("\t");}, + insertSoftTab: function(cm) { + var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; + for (var i = 0; i < ranges.length; i++) { + var pos = ranges[i].from(); + var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); + spaces.push(spaceStr(tabSize - col % tabSize)); + } + cm.replaceSelections(spaces); + }, + defaultTab: function(cm) { + if (cm.somethingSelected()) cm.indentSelection("add"); + else cm.execCommand("insertTab"); + }, + transposeChars: function(cm) { + runInOp(cm, function() { + var ranges = cm.listSelections(), newSel = []; + for (var i = 0; i < ranges.length; i++) { + var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; + if (line) { + if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1); + if (cur.ch > 0) { + cur = new Pos(cur.line, cur.ch + 1); + cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), + Pos(cur.line, cur.ch - 2), cur, "+transpose"); + } else if (cur.line > cm.doc.first) { + var prev = getLine(cm.doc, cur.line - 1).text; + if (prev) + cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + + prev.charAt(prev.length - 1), + Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose"); + } + } + newSel.push(new Range(cur, cur)); + } + cm.setSelections(newSel); + }); + }, + newlineAndIndent: function(cm) { + runInOp(cm, function() { + var len = cm.listSelections().length; + for (var i = 0; i < len; i++) { + var range = cm.listSelections()[i]; + cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input"); + cm.indentLine(range.from().line + 1, null, true); + } + ensureCursorVisible(cm); + }); + }, + openLine: function(cm) {cm.replaceSelection("\n", "start")}, + toggleOverwrite: function(cm) {cm.toggleOverwrite();} + }; + + + // STANDARD KEYMAPS + + var keyMap = CodeMirror.keyMap = {}; + + keyMap.basic = { + "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", + "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", + "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", + "Tab": "defaultTab", "Shift-Tab": "indentAuto", + "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", + "Esc": "singleSelection" + }; + // Note that the save and find-related commands aren't defined by + // default. User code or addons can define them. Unknown commands + // are simply ignored. + keyMap.pcDefault = { + "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", + "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", + "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", + "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", + "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", + fallthrough: "basic" + }; + // Very basic readline/emacs-style bindings, which are standard on Mac. + keyMap.emacsy = { + "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", + "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", + "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", + "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", + "Ctrl-O": "openLine" + }; + keyMap.macDefault = { + "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", + "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", + "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", + "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", + "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", + "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", + fallthrough: ["basic", "emacsy"] + }; + keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; + + // KEYMAP DISPATCH + + function normalizeKeyName(name) { + var parts = name.split(/-(?!$)/), name = parts[parts.length - 1]; + var alt, ctrl, shift, cmd; + for (var i = 0; i < parts.length - 1; i++) { + var mod = parts[i]; + if (/^(cmd|meta|m)$/i.test(mod)) cmd = true; + else if (/^a(lt)?$/i.test(mod)) alt = true; + else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true; + else if (/^s(hift)$/i.test(mod)) shift = true; + else throw new Error("Unrecognized modifier name: " + mod); + } + if (alt) name = "Alt-" + name; + if (ctrl) name = "Ctrl-" + name; + if (cmd) name = "Cmd-" + name; + if (shift) name = "Shift-" + name; + return name; + } + + // This is a kludge to keep keymaps mostly working as raw objects + // (backwards compatibility) while at the same time support features + // like normalization and multi-stroke key bindings. It compiles a + // new normalized keymap, and then updates the old object to reflect + // this. + CodeMirror.normalizeKeyMap = function(keymap) { + var copy = {}; + for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) { + var value = keymap[keyname]; + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue; + if (value == "...") { delete keymap[keyname]; continue; } + + var keys = map(keyname.split(" "), normalizeKeyName); + for (var i = 0; i < keys.length; i++) { + var val, name; + if (i == keys.length - 1) { + name = keys.join(" "); + val = value; + } else { + name = keys.slice(0, i + 1).join(" "); + val = "..."; + } + var prev = copy[name]; + if (!prev) copy[name] = val; + else if (prev != val) throw new Error("Inconsistent bindings for " + name); + } + delete keymap[keyname]; + } + for (var prop in copy) keymap[prop] = copy[prop]; + return keymap; + }; + + var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) { + map = getKeyMap(map); + var found = map.call ? map.call(key, context) : map[key]; + if (found === false) return "nothing"; + if (found === "...") return "multi"; + if (found != null && handle(found)) return "handled"; + + if (map.fallthrough) { + if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") + return lookupKey(key, map.fallthrough, handle, context); + for (var i = 0; i < map.fallthrough.length; i++) { + var result = lookupKey(key, map.fallthrough[i], handle, context); + if (result) return result; + } + } + }; + + // Modifier key presses don't count as 'real' key presses for the + // purpose of keymap fallthrough. + var isModifierKey = CodeMirror.isModifierKey = function(value) { + var name = typeof value == "string" ? value : keyNames[value.keyCode]; + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; + }; + + // Look up the name of a key as indicated by an event object. + var keyName = CodeMirror.keyName = function(event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) return false; + var base = keyNames[event.keyCode], name = base; + if (name == null || event.altGraphKey) return false; + if (event.altKey && base != "Alt") name = "Alt-" + name; + if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name; + if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name; + if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name; + return name; + }; + + function getKeyMap(val) { + return typeof val == "string" ? keyMap[val] : val; + } + + // FROMTEXTAREA + + CodeMirror.fromTextArea = function(textarea, options) { + options = options ? copyObj(options) : {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabIndex) + options.tabindex = textarea.tabIndex; + if (!options.placeholder && textarea.placeholder) + options.placeholder = textarea.placeholder; + // Set autofocus to true if this textarea is focused, or if it has + // autofocus and no other element is focused. + if (options.autofocus == null) { + var hasFocus = activeElt(); + options.autofocus = hasFocus == textarea || + textarea.getAttribute("autofocus") != null && hasFocus == document.body; + } + + function save() {textarea.value = cm.getValue();} + if (textarea.form) { + on(textarea.form, "submit", save); + // Deplorable hack to make the submit method do the right thing. + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form, realSubmit = form.submit; + try { + var wrappedSubmit = form.submit = function() { + save(); + form.submit = realSubmit; + form.submit(); + form.submit = wrappedSubmit; + }; + } catch(e) {} + } + } + + options.finishInit = function(cm) { + cm.save = save; + cm.getTextArea = function() { return textarea; }; + cm.toTextArea = function() { + cm.toTextArea = isNaN; // Prevent this from being ran twice + save(); + textarea.parentNode.removeChild(cm.getWrapperElement()); + textarea.style.display = ""; + if (textarea.form) { + off(textarea.form, "submit", save); + if (typeof textarea.form.submit == "function") + textarea.form.submit = realSubmit; + } + }; + }; + + textarea.style.display = "none"; + var cm = CodeMirror(function(node) { + textarea.parentNode.insertBefore(node, textarea.nextSibling); + }, options); + return cm; + }; + + // STRING STREAM + + // Fed to the mode parsers, provides helper functions to make + // parsers more succinct. + + var StringStream = CodeMirror.StringStream = function(string, tabSize) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + this.lastColumnPos = this.lastColumnValue = 0; + this.lineStart = 0; + }; + + StringStream.prototype = { + eol: function() {return this.pos >= this.string.length;}, + sol: function() {return this.pos == this.lineStart;}, + peek: function() {return this.string.charAt(this.pos) || undefined;}, + next: function() { + if (this.pos < this.string.length) + return this.string.charAt(this.pos++); + }, + eat: function(match) { + var ch = this.string.charAt(this.pos); + if (typeof match == "string") var ok = ch == match; + else var ok = ch && (match.test ? match.test(ch) : match(ch)); + if (ok) {++this.pos; return ch;} + }, + eatWhile: function(match) { + var start = this.pos; + while (this.eat(match)){} + return this.pos > start; + }, + eatSpace: function() { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; + return this.pos > start; + }, + skipToEnd: function() {this.pos = this.string.length;}, + skipTo: function(ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) {this.pos = found; return true;} + }, + backUp: function(n) {this.pos -= n;}, + column: function() { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); + this.lastColumnPos = this.start; + } + return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }, + indentation: function() { + return countColumn(this.string, null, this.tabSize) - + (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }, + match: function(pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) this.pos += pattern.length; + return true; + } + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) return null; + if (match && consume !== false) this.pos += match[0].length; + return match; + } + }, + current: function(){return this.string.slice(this.start, this.pos);}, + hideFirstChars: function(n, inner) { + this.lineStart += n; + try { return inner(); } + finally { this.lineStart -= n; } + } + }; + + // TEXTMARKERS + + // Created with markText and setBookmark methods. A TextMarker is a + // handle that can be used to clear or find a marked position in the + // document. Line objects hold arrays (markedSpans) containing + // {from, to, marker} object pointing to such marker objects, and + // indicating that such a marker is present on that line. Multiple + // lines may point to the same marker when it spans across lines. + // The spans will have null for their from/to properties when the + // marker continues beyond the start/end of the line. Markers have + // links back to the lines they currently touch. + + var nextMarkerId = 0; + + var TextMarker = CodeMirror.TextMarker = function(doc, type) { + this.lines = []; + this.type = type; + this.doc = doc; + this.id = ++nextMarkerId; + }; + eventMixin(TextMarker); + + // Clear the marker. + TextMarker.prototype.clear = function() { + if (this.explicitlyCleared) return; + var cm = this.doc.cm, withOp = cm && !cm.curOp; + if (withOp) startOperation(cm); + if (hasHandler(this, "clear")) { + var found = this.find(); + if (found) signalLater(this, "clear", found.from, found.to); + } + var min = null, max = null; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text"); + else if (cm) { + if (span.to != null) max = lineNo(line); + if (span.from != null) min = lineNo(line); + } + line.markedSpans = removeMarkedSpan(line.markedSpans, span); + if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) + updateLineHeight(line, textHeight(cm.display)); + } + if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) { + var visual = visualLine(this.lines[i]), len = lineLength(visual); + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual; + cm.display.maxLineLength = len; + cm.display.maxLineChanged = true; + } + } + + if (min != null && cm && this.collapsed) regChange(cm, min, max + 1); + this.lines.length = 0; + this.explicitlyCleared = true; + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false; + if (cm) reCheckSelection(cm.doc); + } + if (cm) signalLater(cm, "markerCleared", cm, this); + if (withOp) endOperation(cm); + if (this.parent) this.parent.clear(); + }; + + // Find the position of the marker in the document. Returns a {from, + // to} object by default. Side can be passed to get a specific side + // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the + // Pos objects returned contain a line object, rather than a line + // number (used to prevent looking up the same line twice). + TextMarker.prototype.find = function(side, lineObj) { + if (side == null && this.type == "bookmark") side = 1; + var from, to; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from); + if (side == -1) return from; + } + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to); + if (side == 1) return to; + } + } + return from && {from: from, to: to}; + }; + + // Signals that the marker's widget changed, and surrounding layout + // should be recomputed. + TextMarker.prototype.changed = function() { + var pos = this.find(-1, true), widget = this, cm = this.doc.cm; + if (!pos || !cm) return; + runInOp(cm, function() { + var line = pos.line, lineN = lineNo(pos.line); + var view = findViewForLine(cm, lineN); + if (view) { + clearLineMeasurementCacheFor(view); + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; + } + cm.curOp.updateMaxLine = true; + if (!lineIsHidden(widget.doc, line) && widget.height != null) { + var oldHeight = widget.height; + widget.height = null; + var dHeight = widgetHeight(widget) - oldHeight; + if (dHeight) + updateLineHeight(line, line.height + dHeight); + } + }); + }; + + TextMarker.prototype.attachLine = function(line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) + (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); + } + this.lines.push(line); + }; + TextMarker.prototype.detachLine = function(line) { + this.lines.splice(indexOf(this.lines, line), 1); + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); + } + }; + + // Collapsed markers have unique ids, in order to be able to order + // them, which is needed for uniquely determining an outer marker + // when they overlap (they may nest, but not partially overlap). + var nextMarkerId = 0; + + // Create a marker, wire it up to the right lines, and + function markText(doc, from, to, options, type) { + // Shared markers (across linked documents) are handled separately + // (markTextShared will call out to this again, once per + // document). + if (options && options.shared) return markTextShared(doc, from, to, options, type); + // Ensure we are in an operation. + if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); + + var marker = new TextMarker(doc, type), diff = cmp(from, to); + if (options) copyObj(options, marker, false); + // Don't connect empty markers unless clearWhenEmpty is false + if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) + return marker; + if (marker.replacedWith) { + // Showing up as a widget implies collapsed (widget replaces text) + marker.collapsed = true; + marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget"); + if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true"); + if (options.insertLeft) marker.widgetNode.insertLeft = true; + } + if (marker.collapsed) { + if (conflictingCollapsedRange(doc, from.line, from, to, marker) || + from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) + throw new Error("Inserting collapsed marker partially overlapping an existing one"); + sawCollapsedSpans = true; + } + + if (marker.addToHistory) + addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); + + var curLine = from.line, cm = doc.cm, updateMaxLine; + doc.iter(curLine, to.line + 1, function(line) { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) + updateMaxLine = true; + if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0); + addMarkedSpan(line, new MarkedSpan(marker, + curLine == from.line ? from.ch : null, + curLine == to.line ? to.ch : null)); + ++curLine; + }); + // lineIsHidden depends on the presence of the spans, so needs a second pass + if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { + if (lineIsHidden(doc, line)) updateLineHeight(line, 0); + }); + + if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); }); + + if (marker.readOnly) { + sawReadOnlySpans = true; + if (doc.history.done.length || doc.history.undone.length) + doc.clearHistory(); + } + if (marker.collapsed) { + marker.id = ++nextMarkerId; + marker.atomic = true; + } + if (cm) { + // Sync editor state + if (updateMaxLine) cm.curOp.updateMaxLine = true; + if (marker.collapsed) + regChange(cm, from.line, to.line + 1); + else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) + for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text"); + if (marker.atomic) reCheckSelection(cm.doc); + signalLater(cm, "markerAdded", cm, marker); + } + return marker; + } + + // SHARED TEXTMARKERS + + // A shared marker spans multiple linked documents. It is + // implemented as a meta-marker-object controlling multiple normal + // markers. + var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) { + this.markers = markers; + this.primary = primary; + for (var i = 0; i < markers.length; ++i) + markers[i].parent = this; + }; + eventMixin(SharedTextMarker); + + SharedTextMarker.prototype.clear = function() { + if (this.explicitlyCleared) return; + this.explicitlyCleared = true; + for (var i = 0; i < this.markers.length; ++i) + this.markers[i].clear(); + signalLater(this, "clear"); + }; + SharedTextMarker.prototype.find = function(side, lineObj) { + return this.primary.find(side, lineObj); + }; + + function markTextShared(doc, from, to, options, type) { + options = copyObj(options); + options.shared = false; + var markers = [markText(doc, from, to, options, type)], primary = markers[0]; + var widget = options.widgetNode; + linkedDocs(doc, function(doc) { + if (widget) options.widgetNode = widget.cloneNode(true); + markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); + for (var i = 0; i < doc.linked.length; ++i) + if (doc.linked[i].isParent) return; + primary = lst(markers); + }); + return new SharedTextMarker(markers, primary); + } + + function findSharedMarkers(doc) { + return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), + function(m) { return m.parent; }); + } + + function copySharedMarkers(doc, markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], pos = marker.find(); + var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); + if (cmp(mFrom, mTo)) { + var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); + marker.markers.push(subMark); + subMark.parent = marker; + } + } + } + + function detachSharedMarkers(markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], linked = [marker.primary.doc];; + linkedDocs(marker.primary.doc, function(d) { linked.push(d); }); + for (var j = 0; j < marker.markers.length; j++) { + var subMarker = marker.markers[j]; + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null; + marker.markers.splice(j--, 1); + } + } + } + } + + // TEXTMARKER SPANS + + function MarkedSpan(marker, from, to) { + this.marker = marker; + this.from = from; this.to = to; + } + + // Search an array of spans for a span matching the given marker. + function getMarkedSpanFor(spans, marker) { + if (spans) for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.marker == marker) return span; + } + } + // Remove a span from an array, returning undefined if no spans are + // left (we don't store arrays for lines without spans). + function removeMarkedSpan(spans, span) { + for (var r, i = 0; i < spans.length; ++i) + if (spans[i] != span) (r || (r = [])).push(spans[i]); + return r; + } + // Add a span to a line. + function addMarkedSpan(line, span) { + line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; + span.marker.attachLine(line); + } + + // Used for the algorithm that adjusts markers for a change in the + // document. These functions cut an array of spans at a given + // character position, returning an array of remaining chunks (or + // undefined if nothing remains). + function markedSpansBefore(old, startCh, isInsert) { + if (old) for (var i = 0, nw; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); + if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); + (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); + } + } + return nw; + } + function markedSpansAfter(old, endCh, isInsert) { + if (old) for (var i = 0, nw; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); + if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); + (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, + span.to == null ? null : span.to - endCh)); + } + } + return nw; + } + + // Given a change object, compute the new set of marker spans that + // cover the line in which the change took place. Removes spans + // entirely within the change, reconnects spans belonging to the + // same marker that appear on both sides of the change, and cuts off + // spans partially within the change. Returns an array of span + // arrays with one element for each line in (after) the change. + function stretchSpansOverChange(doc, change) { + if (change.full) return null; + var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; + var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; + if (!oldFirst && !oldLast) return null; + + var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; + // Get the spans that 'stick out' on both sides + var first = markedSpansBefore(oldFirst, startCh, isInsert); + var last = markedSpansAfter(oldLast, endCh, isInsert); + + // Next, merge those two ends + var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); + if (first) { + // Fix up .to properties of first + for (var i = 0; i < first.length; ++i) { + var span = first[i]; + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker); + if (!found) span.to = startCh; + else if (sameLine) span.to = found.to == null ? null : found.to + offset; + } + } + } + if (last) { + // Fix up .from in last (or move them into first in case of sameLine) + for (var i = 0; i < last.length; ++i) { + var span = last[i]; + if (span.to != null) span.to += offset; + if (span.from == null) { + var found = getMarkedSpanFor(first, span.marker); + if (!found) { + span.from = offset; + if (sameLine) (first || (first = [])).push(span); + } + } else { + span.from += offset; + if (sameLine) (first || (first = [])).push(span); + } + } + } + // Make sure we didn't create any zero-length spans + if (first) first = clearEmptySpans(first); + if (last && last != first) last = clearEmptySpans(last); + + var newMarkers = [first]; + if (!sameLine) { + // Fill gap with whole-line-spans + var gap = change.text.length - 2, gapMarkers; + if (gap > 0 && first) + for (var i = 0; i < first.length; ++i) + if (first[i].to == null) + (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null)); + for (var i = 0; i < gap; ++i) + newMarkers.push(gapMarkers); + newMarkers.push(last); + } + return newMarkers; + } + + // Remove spans that are empty and don't have a clearWhenEmpty + // option of false. + function clearEmptySpans(spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) + spans.splice(i--, 1); + } + if (!spans.length) return null; + return spans; + } + + // Used for un/re-doing changes from the history. Combines the + // result of computing the existing spans with the set of spans that + // existed in the history (so that deleting around a span and then + // undoing brings back the span). + function mergeOldSpans(doc, change) { + var old = getOldSpans(doc, change); + var stretched = stretchSpansOverChange(doc, change); + if (!old) return stretched; + if (!stretched) return old; + + for (var i = 0; i < old.length; ++i) { + var oldCur = old[i], stretchCur = stretched[i]; + if (oldCur && stretchCur) { + spans: for (var j = 0; j < stretchCur.length; ++j) { + var span = stretchCur[j]; + for (var k = 0; k < oldCur.length; ++k) + if (oldCur[k].marker == span.marker) continue spans; + oldCur.push(span); + } + } else if (stretchCur) { + old[i] = stretchCur; + } + } + return old; + } + + // Used to 'clip' out readOnly ranges when making a change. + function removeReadOnlyRanges(doc, from, to) { + var markers = null; + doc.iter(from.line, to.line + 1, function(line) { + if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { + var mark = line.markedSpans[i].marker; + if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) + (markers || (markers = [])).push(mark); + } + }); + if (!markers) return null; + var parts = [{from: from, to: to}]; + for (var i = 0; i < markers.length; ++i) { + var mk = markers[i], m = mk.find(0); + for (var j = 0; j < parts.length; ++j) { + var p = parts[j]; + if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue; + var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); + if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) + newParts.push({from: p.from, to: m.from}); + if (dto > 0 || !mk.inclusiveRight && !dto) + newParts.push({from: m.to, to: p.to}); + parts.splice.apply(parts, newParts); + j += newParts.length - 1; + } + } + return parts; + } + + // Connect or disconnect spans from a line. + function detachMarkedSpans(line) { + var spans = line.markedSpans; + if (!spans) return; + for (var i = 0; i < spans.length; ++i) + spans[i].marker.detachLine(line); + line.markedSpans = null; + } + function attachMarkedSpans(line, spans) { + if (!spans) return; + for (var i = 0; i < spans.length; ++i) + spans[i].marker.attachLine(line); + line.markedSpans = spans; + } + + // Helpers used when computing which overlapping collapsed span + // counts as the larger one. + function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; } + function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; } + + // Returns a number indicating which of two overlapping collapsed + // spans is larger (and thus includes the other). Falls back to + // comparing ids when the spans cover exactly the same range. + function compareCollapsedMarkers(a, b) { + var lenDiff = a.lines.length - b.lines.length; + if (lenDiff != 0) return lenDiff; + var aPos = a.find(), bPos = b.find(); + var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); + if (fromCmp) return -fromCmp; + var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); + if (toCmp) return toCmp; + return b.id - a.id; + } + + // Find out whether a line ends or starts in a collapsed span. If + // so, return the marker for that span. + function collapsedSpanAtSide(line, start) { + var sps = sawCollapsedSpans && line.markedSpans, found; + if (sps) for (var sp, i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && + (!found || compareCollapsedMarkers(found, sp.marker) < 0)) + found = sp.marker; + } + return found; + } + function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); } + function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); } + + // Test whether there exists a collapsed span that partially + // overlaps (covers the start or end, but not both) of a new span. + // Such overlap is not allowed. + function conflictingCollapsedRange(doc, lineNo, from, to, marker) { + var line = getLine(doc, lineNo); + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) for (var i = 0; i < sps.length; ++i) { + var sp = sps[i]; + if (!sp.marker.collapsed) continue; + var found = sp.marker.find(0); + var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); + var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); + if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue; + if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || + fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) + return true; + } + } + + // A visual line is a line as drawn on the screen. Folding, for + // example, can cause multiple logical lines to appear on the same + // visual line. This finds the start of the visual line that the + // given line is part of (usually that is the line itself). + function visualLine(line) { + var merged; + while (merged = collapsedSpanAtStart(line)) + line = merged.find(-1, true).line; + return line; + } + + // Returns an array of logical lines that continue the visual line + // started by the argument, or undefined if there are no such lines. + function visualLineContinued(line) { + var merged, lines; + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + (lines || (lines = [])).push(line); + } + return lines; + } + + // Get the line number of the start of the visual line that the + // given line number is part of. + function visualLineNo(doc, lineN) { + var line = getLine(doc, lineN), vis = visualLine(line); + if (line == vis) return lineN; + return lineNo(vis); + } + // Get the line number of the start of the next visual line after + // the given line. + function visualLineEndNo(doc, lineN) { + if (lineN > doc.lastLine()) return lineN; + var line = getLine(doc, lineN), merged; + if (!lineIsHidden(doc, line)) return lineN; + while (merged = collapsedSpanAtEnd(line)) + line = merged.find(1, true).line; + return lineNo(line) + 1; + } + + // Compute whether a line is hidden. Lines count as hidden when they + // are part of a visual line that starts with another line, or when + // they are entirely covered by collapsed, non-widget span. + function lineIsHidden(doc, line) { + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) for (var sp, i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (!sp.marker.collapsed) continue; + if (sp.from == null) return true; + if (sp.marker.widgetNode) continue; + if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) + return true; + } + } + function lineIsHiddenInner(doc, line, span) { + if (span.to == null) { + var end = span.marker.find(1, true); + return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); + } + if (span.marker.inclusiveRight && span.to == line.text.length) + return true; + for (var sp, i = 0; i < line.markedSpans.length; ++i) { + sp = line.markedSpans[i]; + if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && + (sp.to == null || sp.to != span.from) && + (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && + lineIsHiddenInner(doc, line, sp)) return true; + } + } + + // LINE WIDGETS + + // Line widgets are block elements displayed above or below a line. + + var LineWidget = CodeMirror.LineWidget = function(doc, node, options) { + if (options) for (var opt in options) if (options.hasOwnProperty(opt)) + this[opt] = options[opt]; + this.doc = doc; + this.node = node; + }; + eventMixin(LineWidget); + + function adjustScrollWhenAboveVisible(cm, line, diff) { + if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) + addToScrollPos(cm, null, diff); + } + + LineWidget.prototype.clear = function() { + var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); + if (no == null || !ws) return; + for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); + if (!ws.length) line.widgets = null; + var height = widgetHeight(this); + updateLineHeight(line, Math.max(0, line.height - height)); + if (cm) runInOp(cm, function() { + adjustScrollWhenAboveVisible(cm, line, -height); + regLineChange(cm, no, "widget"); + }); + }; + LineWidget.prototype.changed = function() { + var oldH = this.height, cm = this.doc.cm, line = this.line; + this.height = null; + var diff = widgetHeight(this) - oldH; + if (!diff) return; + updateLineHeight(line, line.height + diff); + if (cm) runInOp(cm, function() { + cm.curOp.forceUpdate = true; + adjustScrollWhenAboveVisible(cm, line, diff); + }); + }; + + function widgetHeight(widget) { + if (widget.height != null) return widget.height; + var cm = widget.doc.cm; + if (!cm) return 0; + if (!contains(document.body, widget.node)) { + var parentStyle = "position: relative;"; + if (widget.coverGutter) + parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; + if (widget.noHScroll) + parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; + removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); + } + return widget.height = widget.node.parentNode.offsetHeight; + } + + function addLineWidget(doc, handle, node, options) { + var widget = new LineWidget(doc, node, options); + var cm = doc.cm; + if (cm && widget.noHScroll) cm.display.alignWidgets = true; + changeLine(doc, handle, "widget", function(line) { + var widgets = line.widgets || (line.widgets = []); + if (widget.insertAt == null) widgets.push(widget); + else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); + widget.line = line; + if (cm && !lineIsHidden(doc, line)) { + var aboveVisible = heightAtLine(line) < doc.scrollTop; + updateLineHeight(line, line.height + widgetHeight(widget)); + if (aboveVisible) addToScrollPos(cm, null, widget.height); + cm.curOp.forceUpdate = true; + } + return true; + }); + return widget; + } + + // LINE DATA STRUCTURE + + // Line objects. These hold state related to a line, including + // highlighting info (the styles array). + var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) { + this.text = text; + attachMarkedSpans(this, markedSpans); + this.height = estimateHeight ? estimateHeight(this) : 1; + }; + eventMixin(Line); + Line.prototype.lineNo = function() { return lineNo(this); }; + + // Change the content (text, markers) of a line. Automatically + // invalidates cached information and tries to re-estimate the + // line's height. + function updateLine(line, text, markedSpans, estimateHeight) { + line.text = text; + if (line.stateAfter) line.stateAfter = null; + if (line.styles) line.styles = null; + if (line.order != null) line.order = null; + detachMarkedSpans(line); + attachMarkedSpans(line, markedSpans); + var estHeight = estimateHeight ? estimateHeight(line) : 1; + if (estHeight != line.height) updateLineHeight(line, estHeight); + } + + // Detach a line from the document tree and its markers. + function cleanUpLine(line) { + line.parent = null; + detachMarkedSpans(line); + } + + function extractLineClasses(type, output) { + if (type) for (;;) { + var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); + if (!lineClass) break; + type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); + var prop = lineClass[1] ? "bgClass" : "textClass"; + if (output[prop] == null) + output[prop] = lineClass[2]; + else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) + output[prop] += " " + lineClass[2]; + } + return type; + } + + function callBlankLine(mode, state) { + if (mode.blankLine) return mode.blankLine(state); + if (!mode.innerMode) return; + var inner = CodeMirror.innerMode(mode, state); + if (inner.mode.blankLine) return inner.mode.blankLine(inner.state); + } + + function readToken(mode, stream, state, inner) { + for (var i = 0; i < 10; i++) { + if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode; + var style = mode.token(stream, state); + if (stream.pos > stream.start) return style; + } + throw new Error("Mode " + mode.name + " failed to advance stream."); + } + + // Utility for getTokenAt and getLineTokens + function takeToken(cm, pos, precise, asArray) { + function getObj(copy) { + return {start: stream.start, end: stream.pos, + string: stream.current(), + type: style || null, + state: copy ? copyState(doc.mode, state) : state}; + } + + var doc = cm.doc, mode = doc.mode, style; + pos = clipPos(doc, pos); + var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise); + var stream = new StringStream(line.text, cm.options.tabSize), tokens; + if (asArray) tokens = []; + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos; + style = readToken(mode, stream, state); + if (asArray) tokens.push(getObj(true)); + } + return asArray ? tokens : getObj(); + } + + // Run the given mode's parser over a line, calling f for each token. + function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) { + var flattenSpans = mode.flattenSpans; + if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; + var curStart = 0, curStyle = null; + var stream = new StringStream(text, cm.options.tabSize), style; + var inner = cm.options.addModeClass && [null]; + if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses); + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false; + if (forceToEnd) processLine(cm, text, state, stream.pos); + stream.pos = text.length; + style = null; + } else { + style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses); + } + if (inner) { + var mName = inner[0].name; + if (mName) style = "m-" + (style ? mName + " " + style : mName); + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 50000); + f(curStart, curStyle); + } + curStyle = style; + } + stream.start = stream.pos; + } + while (curStart < stream.pos) { + // Webkit seems to refuse to render text nodes longer than 57444 characters + var pos = Math.min(stream.pos, curStart + 50000); + f(pos, curStyle); + curStart = pos; + } + } + + // Compute a style array (an array starting with a mode generation + // -- for invalidation -- followed by pairs of end positions and + // style strings), which is used to highlight the tokens on the + // line. + function highlightLine(cm, line, state, forceToEnd) { + // A styles array always starts with a number identifying the + // mode/overlays that it is based on (for easy invalidation). + var st = [cm.state.modeGen], lineClasses = {}; + // Compute the base array of styles + runMode(cm, line.text, cm.doc.mode, state, function(end, style) { + st.push(end, style); + }, lineClasses, forceToEnd); + + // Run overlays, adjust style array. + for (var o = 0; o < cm.state.overlays.length; ++o) { + var overlay = cm.state.overlays[o], i = 1, at = 0; + runMode(cm, line.text, overlay.mode, true, function(end, style) { + var start = i; + // Ensure there's a token end at the current position, and that i points at it + while (at < end) { + var i_end = st[i]; + if (i_end > end) + st.splice(i, 1, end, st[i+1], i_end); + i += 2; + at = Math.min(end, i_end); + } + if (!style) return; + if (overlay.opaque) { + st.splice(start, i - start, end, "cm-overlay " + style); + i = start + 2; + } else { + for (; start < i; start += 2) { + var cur = st[start+1]; + st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style; + } + } + }, lineClasses); + } + + return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}; + } + + function getLineStyles(cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + var state = getStateBefore(cm, lineNo(line)); + var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state); + line.stateAfter = state; + line.styles = result.styles; + if (result.classes) line.styleClasses = result.classes; + else if (line.styleClasses) line.styleClasses = null; + if (updateFrontier === cm.doc.frontier) cm.doc.frontier++; + } + return line.styles; + } + + // Lightweight form of highlight -- proceed over this line and + // update state, but don't save a style array. Used for lines that + // aren't currently visible. + function processLine(cm, text, state, startAt) { + var mode = cm.doc.mode; + var stream = new StringStream(text, cm.options.tabSize); + stream.start = stream.pos = startAt || 0; + if (text == "") callBlankLine(mode, state); + while (!stream.eol()) { + readToken(mode, stream, state); + stream.start = stream.pos; + } + } + + // Convert a style as returned by a mode (either null, or a string + // containing one or more styles) to a CSS style. This is cached, + // and also looks for line-wide styles. + var styleToClassCache = {}, styleToClassCacheWithMode = {}; + function interpretTokenStyle(style, options) { + if (!style || /^\s*$/.test(style)) return null; + var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; + return cache[style] || + (cache[style] = style.replace(/\S+/g, "cm-$&")); + } + + // Render the DOM representation of the text of a line. Also builds + // up a 'line map', which points at the DOM nodes that represent + // specific stretches of text, and is used by the measuring code. + // The returned object contains the DOM node, this map, and + // information about line-wide styles that were set by the mode. + function buildLineContent(cm, lineView) { + // The padding-right forces the element to have a 'border', which + // is needed on Webkit to be able to get line-level bounding + // rectangles for it (in measureChar). + var content = elt("span", null, null, webkit ? "padding-right: .1px" : null); + var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content, + col: 0, pos: 0, cm: cm, + splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}; + lineView.measure = {}; + + // Iterate over the logical lines that make up this visual line. + for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { + var line = i ? lineView.rest[i - 1] : lineView.line, order; + builder.pos = 0; + builder.addToken = buildToken; + // Optionally wire in some hacks into the token-rendering + // algorithm, to deal with browser quirks. + if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) + builder.addToken = buildTokenBadBidi(builder.addToken, order); + builder.map = []; + var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); + insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); + if (line.styleClasses) { + if (line.styleClasses.bgClass) + builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); + if (line.styleClasses.textClass) + builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); + } + + // Ensure at least a single node is present, for measuring. + if (builder.map.length == 0) + builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); + + // Store the map and a cache object for the current logical line + if (i == 0) { + lineView.measure.map = builder.map; + lineView.measure.cache = {}; + } else { + (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); + (lineView.measure.caches || (lineView.measure.caches = [])).push({}); + } + } + + // See issue #2901 + if (webkit) { + var last = builder.content.lastChild + if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) + builder.content.className = "cm-tab-wrap-hack"; + } + + signal(cm, "renderLine", cm, lineView.line, builder.pre); + if (builder.pre.className) + builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); + + return builder; + } + + function defaultSpecialCharPlaceholder(ch) { + var token = elt("span", "\u2022", "cm-invalidchar"); + token.title = "\\u" + ch.charCodeAt(0).toString(16); + token.setAttribute("aria-label", token.title); + return token; + } + + // Build up the DOM representation for a single token, and add it to + // the line map. Takes care to render special characters separately. + function buildToken(builder, text, style, startStyle, endStyle, title, css) { + if (!text) return; + var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text; + var special = builder.cm.state.specialChars, mustWrap = false; + if (!special.test(text)) { + builder.col += text.length; + var content = document.createTextNode(displayText); + builder.map.push(builder.pos, builder.pos + text.length, content); + if (ie && ie_version < 9) mustWrap = true; + builder.pos += text.length; + } else { + var content = document.createDocumentFragment(), pos = 0; + while (true) { + special.lastIndex = pos; + var m = special.exec(text); + var skipped = m ? m.index - pos : text.length - pos; + if (skipped) { + var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); + if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); + else content.appendChild(txt); + builder.map.push(builder.pos, builder.pos + skipped, txt); + builder.col += skipped; + builder.pos += skipped; + } + if (!m) break; + pos += skipped + 1; + if (m[0] == "\t") { + var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; + var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); + txt.setAttribute("role", "presentation"); + txt.setAttribute("cm-text", "\t"); + builder.col += tabWidth; + } else if (m[0] == "\r" || m[0] == "\n") { + var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); + txt.setAttribute("cm-text", m[0]); + builder.col += 1; + } else { + var txt = builder.cm.options.specialCharPlaceholder(m[0]); + txt.setAttribute("cm-text", m[0]); + if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); + else content.appendChild(txt); + builder.col += 1; + } + builder.map.push(builder.pos, builder.pos + 1, txt); + builder.pos++; + } + } + if (style || startStyle || endStyle || mustWrap || css) { + var fullStyle = style || ""; + if (startStyle) fullStyle += startStyle; + if (endStyle) fullStyle += endStyle; + var token = elt("span", [content], fullStyle, css); + if (title) token.title = title; + return builder.content.appendChild(token); + } + builder.content.appendChild(content); + } + + function splitSpaces(old) { + var out = " "; + for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; + out += " "; + return out; + } + + // Work around nonsense dimensions being reported for stretches of + // right-to-left text. + function buildTokenBadBidi(inner, order) { + return function(builder, text, style, startStyle, endStyle, title, css) { + style = style ? style + " cm-force-border" : "cm-force-border"; + var start = builder.pos, end = start + text.length; + for (;;) { + // Find the part that overlaps with the start of this text + for (var i = 0; i < order.length; i++) { + var part = order[i]; + if (part.to > start && part.from <= start) break; + } + if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css); + inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css); + startStyle = null; + text = text.slice(part.to - start); + start = part.to; + } + }; + } + + function buildCollapsedSpan(builder, size, marker, ignoreWidget) { + var widget = !ignoreWidget && marker.widgetNode; + if (widget) builder.map.push(builder.pos, builder.pos + size, widget); + if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { + if (!widget) + widget = builder.content.appendChild(document.createElement("span")); + widget.setAttribute("cm-marker", marker.id); + } + if (widget) { + builder.cm.display.input.setUneditable(widget); + builder.content.appendChild(widget); + } + builder.pos += size; + } + + // Outputs a number of spans to make up a line, taking highlighting + // and marked text into account. + function insertLineContent(line, builder, styles) { + var spans = line.markedSpans, allText = line.text, at = 0; + if (!spans) { + for (var i = 1; i < styles.length; i+=2) + builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options)); + return; + } + + var len = allText.length, pos = 0, i = 1, text = "", style, css; + var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = title = css = ""; + collapsed = null; nextChange = Infinity; + var foundBookmarks = [], endStyles + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], m = sp.marker; + if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { + foundBookmarks.push(m); + } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { + if (sp.to != null && sp.to != pos && nextChange > sp.to) { + nextChange = sp.to; + spanEndStyle = ""; + } + if (m.className) spanStyle += " " + m.className; + if (m.css) css = (css ? css + ";" : "") + m.css; + if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; + if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to) + if (m.title && !title) title = m.title; + if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) + collapsed = sp; + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from; + } + } + if (endStyles) for (var j = 0; j < endStyles.length; j += 2) + if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j] + + if (!collapsed || collapsed.from == pos) for (var j = 0; j < foundBookmarks.length; ++j) + buildCollapsedSpan(builder, 0, foundBookmarks[j]); + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, + collapsed.marker, collapsed.from == null); + if (collapsed.to == null) return; + if (collapsed.to == pos) collapsed = false; + } + } + if (pos >= len) break; + + var upto = Math.min(len, nextChange); + while (true) { + if (text) { + var end = pos + text.length; + if (!collapsed) { + var tokenText = end > upto ? text.slice(0, upto - pos) : text; + builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, + spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css); + } + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} + pos = end; + spanStartStyle = ""; + } + text = allText.slice(at, at = styles[i++]); + style = interpretTokenStyle(styles[i++], builder.cm.options); + } + } + } + + // DOCUMENT DATA STRUCTURE + + // By default, updates that start and end at the beginning of a line + // are treated specially, in order to make the association of line + // widgets and marker elements with the text behave more intuitive. + function isWholeLineUpdate(doc, change) { + return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && + (!doc.cm || doc.cm.options.wholeLineUpdateBefore); + } + + // Perform a change on the document data structure. + function updateDoc(doc, change, markedSpans, estimateHeight) { + function spansFor(n) {return markedSpans ? markedSpans[n] : null;} + function update(line, text, spans) { + updateLine(line, text, spans, estimateHeight); + signalLater(line, "change", line, change); + } + function linesFor(start, end) { + for (var i = start, result = []; i < end; ++i) + result.push(new Line(text[i], spansFor(i), estimateHeight)); + return result; + } + + var from = change.from, to = change.to, text = change.text; + var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); + var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; + + // Adjust the line structure + if (change.full) { + doc.insert(0, linesFor(0, text.length)); + doc.remove(text.length, doc.size - text.length); + } else if (isWholeLineUpdate(doc, change)) { + // This is a whole-line replace. Treated specially to make + // sure line objects move the way they are supposed to. + var added = linesFor(0, text.length - 1); + update(lastLine, lastLine.text, lastSpans); + if (nlines) doc.remove(from.line, nlines); + if (added.length) doc.insert(from.line, added); + } else if (firstLine == lastLine) { + if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); + } else { + var added = linesFor(1, text.length - 1); + added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + doc.insert(from.line + 1, added); + } + } else if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); + doc.remove(from.line + 1, nlines); + } else { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); + var added = linesFor(1, text.length - 1); + if (nlines > 1) doc.remove(from.line + 1, nlines - 1); + doc.insert(from.line + 1, added); + } + + signalLater(doc, "change", doc, change); + } + + // The document is represented as a BTree consisting of leaves, with + // chunk of lines in them, and branches, with up to ten leaves or + // other branch nodes below them. The top node is always a branch + // node, and is the document object itself (meaning it has + // additional methods and properties). + // + // All nodes have parent links. The tree is used both to go from + // line numbers to line objects, and to go from objects to numbers. + // It also indexes by height, and is used to convert between height + // and line object, and to find the total height of the document. + // + // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html + + function LeafChunk(lines) { + this.lines = lines; + this.parent = null; + for (var i = 0, height = 0; i < lines.length; ++i) { + lines[i].parent = this; + height += lines[i].height; + } + this.height = height; + } + + LeafChunk.prototype = { + chunkSize: function() { return this.lines.length; }, + // Remove the n lines at offset 'at'. + removeInner: function(at, n) { + for (var i = at, e = at + n; i < e; ++i) { + var line = this.lines[i]; + this.height -= line.height; + cleanUpLine(line); + signalLater(line, "delete"); + } + this.lines.splice(at, n); + }, + // Helper used to collapse a small branch into a single leaf. + collapse: function(lines) { + lines.push.apply(lines, this.lines); + }, + // Insert the given array of lines at offset 'at', count them as + // having the given height. + insertInner: function(at, lines, height) { + this.height += height; + this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); + for (var i = 0; i < lines.length; ++i) lines[i].parent = this; + }, + // Used to iterate over a part of the tree. + iterN: function(at, n, op) { + for (var e = at + n; at < e; ++at) + if (op(this.lines[at])) return true; + } + }; + + function BranchChunk(children) { + this.children = children; + var size = 0, height = 0; + for (var i = 0; i < children.length; ++i) { + var ch = children[i]; + size += ch.chunkSize(); height += ch.height; + ch.parent = this; + } + this.size = size; + this.height = height; + this.parent = null; + } + + BranchChunk.prototype = { + chunkSize: function() { return this.size; }, + removeInner: function(at, n) { + this.size -= n; + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var rm = Math.min(n, sz - at), oldHeight = child.height; + child.removeInner(at, rm); + this.height -= oldHeight - child.height; + if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } + if ((n -= rm) == 0) break; + at = 0; + } else at -= sz; + } + // If the result is smaller than 25 lines, ensure that it is a + // single leaf node. + if (this.size - n < 25 && + (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { + var lines = []; + this.collapse(lines); + this.children = [new LeafChunk(lines)]; + this.children[0].parent = this; + } + }, + collapse: function(lines) { + for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines); + }, + insertInner: function(at, lines, height) { + this.size += lines.length; + this.height += height; + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at <= sz) { + child.insertInner(at, lines, height); + if (child.lines && child.lines.length > 50) { + // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. + // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. + var remaining = child.lines.length % 25 + 25 + for (var pos = remaining; pos < child.lines.length;) { + var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); + child.height -= leaf.height; + this.children.splice(++i, 0, leaf); + leaf.parent = this; + } + child.lines = child.lines.slice(0, remaining); + this.maybeSpill(); + } + break; + } + at -= sz; + } + }, + // When a node has grown, check whether it should be split. + maybeSpill: function() { + if (this.children.length <= 10) return; + var me = this; + do { + var spilled = me.children.splice(me.children.length - 5, 5); + var sibling = new BranchChunk(spilled); + if (!me.parent) { // Become the parent node + var copy = new BranchChunk(me.children); + copy.parent = me; + me.children = [copy, sibling]; + me = copy; + } else { + me.size -= sibling.size; + me.height -= sibling.height; + var myIndex = indexOf(me.parent.children, me); + me.parent.children.splice(myIndex + 1, 0, sibling); + } + sibling.parent = me.parent; + } while (me.children.length > 10); + me.parent.maybeSpill(); + }, + iterN: function(at, n, op) { + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var used = Math.min(n, sz - at); + if (child.iterN(at, used, op)) return true; + if ((n -= used) == 0) break; + at = 0; + } else at -= sz; + } + } + }; + + var nextDocId = 0; + var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) { + if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep); + if (firstLine == null) firstLine = 0; + + BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); + this.first = firstLine; + this.scrollTop = this.scrollLeft = 0; + this.cantEdit = false; + this.cleanGeneration = 1; + this.frontier = firstLine; + var start = Pos(firstLine, 0); + this.sel = simpleSelection(start); + this.history = new History(null); + this.id = ++nextDocId; + this.modeOption = mode; + this.lineSep = lineSep; + this.extend = false; + + if (typeof text == "string") text = this.splitLines(text); + updateDoc(this, {from: start, to: start, text: text}); + setSelection(this, simpleSelection(start), sel_dontScroll); + }; + + Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + // Iterate over the document. Supports two forms -- with only one + // argument, it calls that for each line in the document. With + // three, it iterates over the range given by the first two (with + // the second being non-inclusive). + iter: function(from, to, op) { + if (op) this.iterN(from - this.first, to - from, op); + else this.iterN(this.first, this.first + this.size, from); + }, + + // Non-public interface for adding and removing lines. + insert: function(at, lines) { + var height = 0; + for (var i = 0; i < lines.length; ++i) height += lines[i].height; + this.insertInner(at - this.first, lines, height); + }, + remove: function(at, n) { this.removeInner(at - this.first, n); }, + + // From here, the methods are part of the public interface. Most + // are also available from CodeMirror (editor) instances. + + getValue: function(lineSep) { + var lines = getLines(this, this.first, this.first + this.size); + if (lineSep === false) return lines; + return lines.join(lineSep || this.lineSeparator()); + }, + setValue: docMethodOp(function(code) { + var top = Pos(this.first, 0), last = this.first + this.size - 1; + makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), + text: this.splitLines(code), origin: "setValue", full: true}, true); + setSelection(this, simpleSelection(top)); + }), + replaceRange: function(code, from, to, origin) { + from = clipPos(this, from); + to = to ? clipPos(this, to) : from; + replaceRange(this, code, from, to, origin); + }, + getRange: function(from, to, lineSep) { + var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); + if (lineSep === false) return lines; + return lines.join(lineSep || this.lineSeparator()); + }, + + getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, + + getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);}, + getLineNumber: function(line) {return lineNo(line);}, + + getLineHandleVisualStart: function(line) { + if (typeof line == "number") line = getLine(this, line); + return visualLine(line); + }, + + lineCount: function() {return this.size;}, + firstLine: function() {return this.first;}, + lastLine: function() {return this.first + this.size - 1;}, + + clipPos: function(pos) {return clipPos(this, pos);}, + + getCursor: function(start) { + var range = this.sel.primary(), pos; + if (start == null || start == "head") pos = range.head; + else if (start == "anchor") pos = range.anchor; + else if (start == "end" || start == "to" || start === false) pos = range.to(); + else pos = range.from(); + return pos; + }, + listSelections: function() { return this.sel.ranges; }, + somethingSelected: function() {return this.sel.somethingSelected();}, + + setCursor: docMethodOp(function(line, ch, options) { + setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); + }), + setSelection: docMethodOp(function(anchor, head, options) { + setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); + }), + extendSelection: docMethodOp(function(head, other, options) { + extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); + }), + extendSelections: docMethodOp(function(heads, options) { + extendSelections(this, clipPosArray(this, heads), options); + }), + extendSelectionsBy: docMethodOp(function(f, options) { + var heads = map(this.sel.ranges, f); + extendSelections(this, clipPosArray(this, heads), options); + }), + setSelections: docMethodOp(function(ranges, primary, options) { + if (!ranges.length) return; + for (var i = 0, out = []; i < ranges.length; i++) + out[i] = new Range(clipPos(this, ranges[i].anchor), + clipPos(this, ranges[i].head)); + if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex); + setSelection(this, normalizeSelection(out, primary), options); + }), + addSelection: docMethodOp(function(anchor, head, options) { + var ranges = this.sel.ranges.slice(0); + ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); + setSelection(this, normalizeSelection(ranges, ranges.length - 1), options); + }), + + getSelection: function(lineSep) { + var ranges = this.sel.ranges, lines; + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this, ranges[i].from(), ranges[i].to()); + lines = lines ? lines.concat(sel) : sel; + } + if (lineSep === false) return lines; + else return lines.join(lineSep || this.lineSeparator()); + }, + getSelections: function(lineSep) { + var parts = [], ranges = this.sel.ranges; + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this, ranges[i].from(), ranges[i].to()); + if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator()); + parts[i] = sel; + } + return parts; + }, + replaceSelection: function(code, collapse, origin) { + var dup = []; + for (var i = 0; i < this.sel.ranges.length; i++) + dup[i] = code; + this.replaceSelections(dup, collapse, origin || "+input"); + }, + replaceSelections: docMethodOp(function(code, collapse, origin) { + var changes = [], sel = this.sel; + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i]; + changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin}; + } + var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); + for (var i = changes.length - 1; i >= 0; i--) + makeChange(this, changes[i]); + if (newSel) setSelectionReplaceHistory(this, newSel); + else if (this.cm) ensureCursorVisible(this.cm); + }), + undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), + redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), + undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), + redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), + + setExtending: function(val) {this.extend = val;}, + getExtending: function() {return this.extend;}, + + historySize: function() { + var hist = this.history, done = 0, undone = 0; + for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done; + for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone; + return {undo: done, redo: undone}; + }, + clearHistory: function() {this.history = new History(this.history.maxGeneration);}, + + markClean: function() { + this.cleanGeneration = this.changeGeneration(true); + }, + changeGeneration: function(forceSplit) { + if (forceSplit) + this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; + return this.history.generation; + }, + isClean: function (gen) { + return this.history.generation == (gen || this.cleanGeneration); + }, + + getHistory: function() { + return {done: copyHistoryArray(this.history.done), + undone: copyHistoryArray(this.history.undone)}; + }, + setHistory: function(histData) { + var hist = this.history = new History(this.history.maxGeneration); + hist.done = copyHistoryArray(histData.done.slice(0), null, true); + hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); + }, + + addLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass"; + if (!line[prop]) line[prop] = cls; + else if (classTest(cls).test(line[prop])) return false; + else line[prop] += " " + cls; + return true; + }); + }), + removeLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass"; + var cur = line[prop]; + if (!cur) return false; + else if (cls == null) line[prop] = null; + else { + var found = cur.match(classTest(cls)); + if (!found) return false; + var end = found.index + found[0].length; + line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; + } + return true; + }); + }), + + addLineWidget: docMethodOp(function(handle, node, options) { + return addLineWidget(this, handle, node, options); + }), + removeLineWidget: function(widget) { widget.clear(); }, + + markText: function(from, to, options) { + return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range"); + }, + setBookmark: function(pos, options) { + var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft, + clearWhenEmpty: false, shared: options && options.shared, + handleMouseEvents: options && options.handleMouseEvents}; + pos = clipPos(this, pos); + return markText(this, pos, pos, realOpts, "bookmark"); + }, + findMarksAt: function(pos) { + pos = clipPos(this, pos); + var markers = [], spans = getLine(this, pos.line).markedSpans; + if (spans) for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if ((span.from == null || span.from <= pos.ch) && + (span.to == null || span.to >= pos.ch)) + markers.push(span.marker.parent || span.marker); + } + return markers; + }, + findMarks: function(from, to, filter) { + from = clipPos(this, from); to = clipPos(this, to); + var found = [], lineNo = from.line; + this.iter(from.line, to.line + 1, function(line) { + var spans = line.markedSpans; + if (spans) for (var i = 0; i < spans.length; i++) { + var span = spans[i]; + if (!(span.to != null && lineNo == from.line && from.ch >= span.to || + span.from == null && lineNo != from.line || + span.from != null && lineNo == to.line && span.from >= to.ch) && + (!filter || filter(span.marker))) + found.push(span.marker.parent || span.marker); + } + ++lineNo; + }); + return found; + }, + getAllMarks: function() { + var markers = []; + this.iter(function(line) { + var sps = line.markedSpans; + if (sps) for (var i = 0; i < sps.length; ++i) + if (sps[i].from != null) markers.push(sps[i].marker); + }); + return markers; + }, + + posFromIndex: function(off) { + var ch, lineNo = this.first, sepSize = this.lineSeparator().length; + this.iter(function(line) { + var sz = line.text.length + sepSize; + if (sz > off) { ch = off; return true; } + off -= sz; + ++lineNo; + }); + return clipPos(this, Pos(lineNo, ch)); + }, + indexFromPos: function (coords) { + coords = clipPos(this, coords); + var index = coords.ch; + if (coords.line < this.first || coords.ch < 0) return 0; + var sepSize = this.lineSeparator().length; + this.iter(this.first, coords.line, function (line) { + index += line.text.length + sepSize; + }); + return index; + }, + + copy: function(copyHistory) { + var doc = new Doc(getLines(this, this.first, this.first + this.size), + this.modeOption, this.first, this.lineSep); + doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; + doc.sel = this.sel; + doc.extend = false; + if (copyHistory) { + doc.history.undoDepth = this.history.undoDepth; + doc.setHistory(this.getHistory()); + } + return doc; + }, + + linkedDoc: function(options) { + if (!options) options = {}; + var from = this.first, to = this.first + this.size; + if (options.from != null && options.from > from) from = options.from; + if (options.to != null && options.to < to) to = options.to; + var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep); + if (options.sharedHist) copy.history = this.history; + (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); + copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; + copySharedMarkers(copy, findSharedMarkers(this)); + return copy; + }, + unlinkDoc: function(other) { + if (other instanceof CodeMirror) other = other.doc; + if (this.linked) for (var i = 0; i < this.linked.length; ++i) { + var link = this.linked[i]; + if (link.doc != other) continue; + this.linked.splice(i, 1); + other.unlinkDoc(this); + detachSharedMarkers(findSharedMarkers(this)); + break; + } + // If the histories were shared, split them again + if (other.history == this.history) { + var splitIds = [other.id]; + linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); + other.history = new History(null); + other.history.done = copyHistoryArray(this.history.done, splitIds); + other.history.undone = copyHistoryArray(this.history.undone, splitIds); + } + }, + iterLinkedDocs: function(f) {linkedDocs(this, f);}, + + getMode: function() {return this.mode;}, + getEditor: function() {return this.cm;}, + + splitLines: function(str) { + if (this.lineSep) return str.split(this.lineSep); + return splitLinesAuto(str); + }, + lineSeparator: function() { return this.lineSep || "\n"; } + }); + + // Public alias. + Doc.prototype.eachLine = Doc.prototype.iter; + + // Set up methods on CodeMirror's prototype to redirect to the editor's document. + var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); + for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) + CodeMirror.prototype[prop] = (function(method) { + return function() {return method.apply(this.doc, arguments);}; + })(Doc.prototype[prop]); + + eventMixin(Doc); + + // Call f for all linked documents. + function linkedDocs(doc, f, sharedHistOnly) { + function propagate(doc, skip, sharedHist) { + if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { + var rel = doc.linked[i]; + if (rel.doc == skip) continue; + var shared = sharedHist && rel.sharedHist; + if (sharedHistOnly && !shared) continue; + f(rel.doc, shared); + propagate(rel.doc, doc, shared); + } + } + propagate(doc, null, true); + } + + // Attach a document to an editor. + function attachDoc(cm, doc) { + if (doc.cm) throw new Error("This document is already in use."); + cm.doc = doc; + doc.cm = cm; + estimateLineHeights(cm); + loadMode(cm); + if (!cm.options.lineWrapping) findMaxLine(cm); + cm.options.mode = doc.modeOption; + regChange(cm); + } + + // LINE UTILITIES + + // Find the line object corresponding to the given line number. + function getLine(doc, n) { + n -= doc.first; + if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document."); + for (var chunk = doc; !chunk.lines;) { + for (var i = 0;; ++i) { + var child = chunk.children[i], sz = child.chunkSize(); + if (n < sz) { chunk = child; break; } + n -= sz; + } + } + return chunk.lines[n]; + } + + // Get the part of a document between two positions, as an array of + // strings. + function getBetween(doc, start, end) { + var out = [], n = start.line; + doc.iter(start.line, end.line + 1, function(line) { + var text = line.text; + if (n == end.line) text = text.slice(0, end.ch); + if (n == start.line) text = text.slice(start.ch); + out.push(text); + ++n; + }); + return out; + } + // Get the lines between from and to, as array of strings. + function getLines(doc, from, to) { + var out = []; + doc.iter(from, to, function(line) { out.push(line.text); }); + return out; + } + + // Update the height of a line, propagating the height change + // upwards to parent nodes. + function updateLineHeight(line, height) { + var diff = height - line.height; + if (diff) for (var n = line; n; n = n.parent) n.height += diff; + } + + // Given a line object, find its line number by walking up through + // its parent links. + function lineNo(line) { + if (line.parent == null) return null; + var cur = line.parent, no = indexOf(cur.lines, line); + for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { + for (var i = 0;; ++i) { + if (chunk.children[i] == cur) break; + no += chunk.children[i].chunkSize(); + } + } + return no + cur.first; + } + + // Find the line at the given vertical position, using the height + // information in the document tree. + function lineAtHeight(chunk, h) { + var n = chunk.first; + outer: do { + for (var i = 0; i < chunk.children.length; ++i) { + var child = chunk.children[i], ch = child.height; + if (h < ch) { chunk = child; continue outer; } + h -= ch; + n += child.chunkSize(); + } + return n; + } while (!chunk.lines); + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i], lh = line.height; + if (h < lh) break; + h -= lh; + } + return n + i; + } + + + // Find the height above the given line. + function heightAtLine(lineObj) { + lineObj = visualLine(lineObj); + + var h = 0, chunk = lineObj.parent; + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i]; + if (line == lineObj) break; + else h += line.height; + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i = 0; i < p.children.length; ++i) { + var cur = p.children[i]; + if (cur == chunk) break; + else h += cur.height; + } + } + return h; + } + + // Get the bidi ordering for the given line (and cache it). Returns + // false for lines that are fully left-to-right, and an array of + // BidiSpan objects otherwise. + function getOrder(line) { + var order = line.order; + if (order == null) order = line.order = bidiOrdering(line.text); + return order; + } + + // HISTORY + + function History(startGen) { + // Arrays of change events and selections. Doing something adds an + // event to done and clears undo. Undoing moves events from done + // to undone, redoing moves them in the other direction. + this.done = []; this.undone = []; + this.undoDepth = Infinity; + // Used to track when changes can be merged into a single undo + // event + this.lastModTime = this.lastSelTime = 0; + this.lastOp = this.lastSelOp = null; + this.lastOrigin = this.lastSelOrigin = null; + // Used by the isClean() method + this.generation = this.maxGeneration = startGen || 1; + } + + // Create a history change event from an updateDoc-style change + // object. + function historyChangeFromChange(doc, change) { + var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; + attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); + linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); + return histChange; + } + + // Pop all selection events off the end of a history array. Stop at + // a change event. + function clearSelectionEvents(array) { + while (array.length) { + var last = lst(array); + if (last.ranges) array.pop(); + else break; + } + } + + // Find the top change event in the history. Pop off selection + // events that are in the way. + function lastChangeEvent(hist, force) { + if (force) { + clearSelectionEvents(hist.done); + return lst(hist.done); + } else if (hist.done.length && !lst(hist.done).ranges) { + return lst(hist.done); + } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { + hist.done.pop(); + return lst(hist.done); + } + } + + // Register a change in the history. Merges changes that are within + // a single operation, ore are close together with an origin that + // allows merging (starting with "+") into a single event. + function addChangeToHistory(doc, change, selAfter, opId) { + var hist = doc.history; + hist.undone.length = 0; + var time = +new Date, cur; + + if ((hist.lastOp == opId || + hist.lastOrigin == change.origin && change.origin && + ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || + change.origin.charAt(0) == "*")) && + (cur = lastChangeEvent(hist, hist.lastOp == opId))) { + // Merge this change into the last event + var last = lst(cur.changes); + if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { + // Optimized case for simple insertion -- don't want to add + // new changesets for every character typed + last.to = changeEnd(change); + } else { + // Add new sub-event + cur.changes.push(historyChangeFromChange(doc, change)); + } + } else { + // Can not be merged, start a new event. + var before = lst(hist.done); + if (!before || !before.ranges) + pushSelectionToHistory(doc.sel, hist.done); + cur = {changes: [historyChangeFromChange(doc, change)], + generation: hist.generation}; + hist.done.push(cur); + while (hist.done.length > hist.undoDepth) { + hist.done.shift(); + if (!hist.done[0].ranges) hist.done.shift(); + } + } + hist.done.push(selAfter); + hist.generation = ++hist.maxGeneration; + hist.lastModTime = hist.lastSelTime = time; + hist.lastOp = hist.lastSelOp = opId; + hist.lastOrigin = hist.lastSelOrigin = change.origin; + + if (!last) signal(doc, "historyAdded"); + } + + function selectionEventCanBeMerged(doc, origin, prev, sel) { + var ch = origin.charAt(0); + return ch == "*" || + ch == "+" && + prev.ranges.length == sel.ranges.length && + prev.somethingSelected() == sel.somethingSelected() && + new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); + } + + // Called whenever the selection changes, sets the new selection as + // the pending selection in the history, and pushes the old pending + // selection into the 'done' array when it was significantly + // different (in number of selected ranges, emptiness, or time). + function addSelectionToHistory(doc, sel, opId, options) { + var hist = doc.history, origin = options && options.origin; + + // A new event is started when the previous origin does not match + // the current, or the origins don't allow matching. Origins + // starting with * are always merged, those starting with + are + // merged when similar and close together in time. + if (opId == hist.lastSelOp || + (origin && hist.lastSelOrigin == origin && + (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || + selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) + hist.done[hist.done.length - 1] = sel; + else + pushSelectionToHistory(sel, hist.done); + + hist.lastSelTime = +new Date; + hist.lastSelOrigin = origin; + hist.lastSelOp = opId; + if (options && options.clearRedo !== false) + clearSelectionEvents(hist.undone); + } + + function pushSelectionToHistory(sel, dest) { + var top = lst(dest); + if (!(top && top.ranges && top.equals(sel))) + dest.push(sel); + } + + // Used to store marked span information in the history. + function attachLocalSpans(doc, change, from, to) { + var existing = change["spans_" + doc.id], n = 0; + doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) { + if (line.markedSpans) + (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; + ++n; + }); + } + + // When un/re-doing restores text containing marked spans, those + // that have been explicitly cleared should not be restored. + function removeClearedSpans(spans) { + if (!spans) return null; + for (var i = 0, out; i < spans.length; ++i) { + if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } + else if (out) out.push(spans[i]); + } + return !out ? spans : out.length ? out : null; + } + + // Retrieve and filter the old marked spans stored in a change event. + function getOldSpans(doc, change) { + var found = change["spans_" + doc.id]; + if (!found) return null; + for (var i = 0, nw = []; i < change.text.length; ++i) + nw.push(removeClearedSpans(found[i])); + return nw; + } + + // Used both to provide a JSON-safe object in .getHistory, and, when + // detaching a document, to split the history in two + function copyHistoryArray(events, newGroup, instantiateSel) { + for (var i = 0, copy = []; i < events.length; ++i) { + var event = events[i]; + if (event.ranges) { + copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); + continue; + } + var changes = event.changes, newChanges = []; + copy.push({changes: newChanges}); + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], m; + newChanges.push({from: change.from, to: change.to, text: change.text}); + if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop] = change[prop]; + delete change[prop]; + } + } + } + } + return copy; + } + + // Rebasing/resetting history to deal with externally-sourced changes + + function rebaseHistSelSingle(pos, from, to, diff) { + if (to < pos.line) { + pos.line += diff; + } else if (from < pos.line) { + pos.line = from; + pos.ch = 0; + } + } + + // Tries to rebase an array of history events given a change in the + // document. If the change touches the same lines as the event, the + // event, and everything 'behind' it, is discarded. If the change is + // before the event, the event's positions are updated. Uses a + // copy-on-write scheme for the positions, to avoid having to + // reallocate them all on every rebase, but also avoid problems with + // shared position objects being unsafely updated. + function rebaseHistArray(array, from, to, diff) { + for (var i = 0; i < array.length; ++i) { + var sub = array[i], ok = true; + if (sub.ranges) { + if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } + for (var j = 0; j < sub.ranges.length; j++) { + rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); + rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); + } + continue; + } + for (var j = 0; j < sub.changes.length; ++j) { + var cur = sub.changes[j]; + if (to < cur.from.line) { + cur.from = Pos(cur.from.line + diff, cur.from.ch); + cur.to = Pos(cur.to.line + diff, cur.to.ch); + } else if (from <= cur.to.line) { + ok = false; + break; + } + } + if (!ok) { + array.splice(0, i + 1); + i = 0; + } + } + } + + function rebaseHist(hist, change) { + var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; + rebaseHistArray(hist.done, from, to, diff); + rebaseHistArray(hist.undone, from, to, diff); + } + + // EVENT UTILITIES + + // Due to the fact that we still support jurassic IE versions, some + // compatibility wrappers are needed. + + var e_preventDefault = CodeMirror.e_preventDefault = function(e) { + if (e.preventDefault) e.preventDefault(); + else e.returnValue = false; + }; + var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) { + if (e.stopPropagation) e.stopPropagation(); + else e.cancelBubble = true; + }; + function e_defaultPrevented(e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; + } + var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);}; + + function e_target(e) {return e.target || e.srcElement;} + function e_button(e) { + var b = e.which; + if (b == null) { + if (e.button & 1) b = 1; + else if (e.button & 2) b = 3; + else if (e.button & 4) b = 2; + } + if (mac && e.ctrlKey && b == 1) b = 3; + return b; + } + + // EVENT HANDLING + + // Lightweight event framework. on/off also work on DOM nodes, + // registering native DOM handlers. + + var on = CodeMirror.on = function(emitter, type, f) { + if (emitter.addEventListener) + emitter.addEventListener(type, f, false); + else if (emitter.attachEvent) + emitter.attachEvent("on" + type, f); + else { + var map = emitter._handlers || (emitter._handlers = {}); + var arr = map[type] || (map[type] = []); + arr.push(f); + } + }; + + var noHandlers = [] + function getHandlers(emitter, type, copy) { + var arr = emitter._handlers && emitter._handlers[type] + if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers + else return arr || noHandlers + } + + var off = CodeMirror.off = function(emitter, type, f) { + if (emitter.removeEventListener) + emitter.removeEventListener(type, f, false); + else if (emitter.detachEvent) + emitter.detachEvent("on" + type, f); + else { + var handlers = getHandlers(emitter, type, false) + for (var i = 0; i < handlers.length; ++i) + if (handlers[i] == f) { handlers.splice(i, 1); break; } + } + }; + + var signal = CodeMirror.signal = function(emitter, type /*, values...*/) { + var handlers = getHandlers(emitter, type, true) + if (!handlers.length) return; + var args = Array.prototype.slice.call(arguments, 2); + for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args); + }; + + var orphanDelayedCallbacks = null; + + // Often, we want to signal events at a point where we are in the + // middle of some work, but don't want the handler to start calling + // other methods on the editor, which might be in an inconsistent + // state or simply not expect any other events to happen. + // signalLater looks whether there are any handlers, and schedules + // them to be executed when the last operation ends, or, if no + // operation is active, when a timeout fires. + function signalLater(emitter, type /*, values...*/) { + var arr = getHandlers(emitter, type, false) + if (!arr.length) return; + var args = Array.prototype.slice.call(arguments, 2), list; + if (operationGroup) { + list = operationGroup.delayedCallbacks; + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks; + } else { + list = orphanDelayedCallbacks = []; + setTimeout(fireOrphanDelayed, 0); + } + function bnd(f) {return function(){f.apply(null, args);};}; + for (var i = 0; i < arr.length; ++i) + list.push(bnd(arr[i])); + } + + function fireOrphanDelayed() { + var delayed = orphanDelayedCallbacks; + orphanDelayedCallbacks = null; + for (var i = 0; i < delayed.length; ++i) delayed[i](); + } + + // The DOM events that CodeMirror handles can be overridden by + // registering a (non-DOM) handler on the editor for the event name, + // and preventDefault-ing the event in that handler. + function signalDOMEvent(cm, e, override) { + if (typeof e == "string") + e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; + signal(cm, override || e.type, cm, e); + return e_defaultPrevented(e) || e.codemirrorIgnore; + } + + function signalCursorActivity(cm) { + var arr = cm._handlers && cm._handlers.cursorActivity; + if (!arr) return; + var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); + for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1) + set.push(arr[i]); + } + + function hasHandler(emitter, type) { + return getHandlers(emitter, type).length > 0 + } + + // Add on and off methods to a constructor's prototype, to make + // registering events on such objects more convenient. + function eventMixin(ctor) { + ctor.prototype.on = function(type, f) {on(this, type, f);}; + ctor.prototype.off = function(type, f) {off(this, type, f);}; + } + + // MISC UTILITIES + + // Number of pixels added to scroller and sizer to hide scrollbar + var scrollerGap = 30; + + // Returned or thrown by various protocols to signal 'I'm not + // handling this'. + var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; + + // Reused option objects for setSelection & friends + var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; + + function Delayed() {this.id = null;} + Delayed.prototype.set = function(ms, f) { + clearTimeout(this.id); + this.id = setTimeout(f, ms); + }; + + // Counts the column offset in a string, taking tabs into account. + // Used mostly to find indentation. + var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) end = string.length; + } + for (var i = startIndex || 0, n = startValue || 0;;) { + var nextTab = string.indexOf("\t", i); + if (nextTab < 0 || nextTab >= end) + return n + (end - i); + n += nextTab - i; + n += tabSize - (n % tabSize); + i = nextTab + 1; + } + }; + + // The inverse of countColumn -- find the offset that corresponds to + // a particular column. + var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) { + for (var pos = 0, col = 0;;) { + var nextTab = string.indexOf("\t", pos); + if (nextTab == -1) nextTab = string.length; + var skipped = nextTab - pos; + if (nextTab == string.length || col + skipped >= goal) + return pos + Math.min(skipped, goal - col); + col += nextTab - pos; + col += tabSize - (col % tabSize); + pos = nextTab + 1; + if (col >= goal) return pos; + } + } + + var spaceStrs = [""]; + function spaceStr(n) { + while (spaceStrs.length <= n) + spaceStrs.push(lst(spaceStrs) + " "); + return spaceStrs[n]; + } + + function lst(arr) { return arr[arr.length-1]; } + + var selectInput = function(node) { node.select(); }; + if (ios) // Mobile Safari apparently has a bug where select() is broken. + selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; + else if (ie) // Suppress mysterious IE10 errors + selectInput = function(node) { try { node.select(); } catch(_e) {} }; + + function indexOf(array, elt) { + for (var i = 0; i < array.length; ++i) + if (array[i] == elt) return i; + return -1; + } + function map(array, f) { + var out = []; + for (var i = 0; i < array.length; i++) out[i] = f(array[i], i); + return out; + } + + function nothing() {} + + function createObj(base, props) { + var inst; + if (Object.create) { + inst = Object.create(base); + } else { + nothing.prototype = base; + inst = new nothing(); + } + if (props) copyObj(props, inst); + return inst; + }; + + function copyObj(obj, target, overwrite) { + if (!target) target = {}; + for (var prop in obj) + if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) + target[prop] = obj[prop]; + return target; + } + + function bind(f) { + var args = Array.prototype.slice.call(arguments, 1); + return function(){return f.apply(null, args);}; + } + + var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + var isWordCharBasic = CodeMirror.isWordChar = function(ch) { + return /\w/.test(ch) || ch > "\x80" && + (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); + }; + function isWordChar(ch, helper) { + if (!helper) return isWordCharBasic(ch); + if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true; + return helper.test(ch); + } + + function isEmpty(obj) { + for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; + return true; + } + + // Extending unicode characters. A series of a non-extending char + + // any number of extending chars is treated as a single unit as far + // as editing and measuring is concerned. This is not fully correct, + // since some scripts/fonts/browsers also treat other configurations + // of code points as a group. + var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; + function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); } + + // DOM UTILITIES + + function elt(tag, content, className, style) { + var e = document.createElement(tag); + if (className) e.className = className; + if (style) e.style.cssText = style; + if (typeof content == "string") e.appendChild(document.createTextNode(content)); + else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); + return e; + } + + var range; + if (document.createRange) range = function(node, start, end, endNode) { + var r = document.createRange(); + r.setEnd(endNode || node, end); + r.setStart(node, start); + return r; + }; + else range = function(node, start, end) { + var r = document.body.createTextRange(); + try { r.moveToElementText(node.parentNode); } + catch(e) { return r; } + r.collapse(true); + r.moveEnd("character", end); + r.moveStart("character", start); + return r; + }; + + function removeChildren(e) { + for (var count = e.childNodes.length; count > 0; --count) + e.removeChild(e.firstChild); + return e; + } + + function removeChildrenAndAdd(parent, e) { + return removeChildren(parent).appendChild(e); + } + + var contains = CodeMirror.contains = function(parent, child) { + if (child.nodeType == 3) // Android browser always returns false when child is a textnode + child = child.parentNode; + if (parent.contains) + return parent.contains(child); + do { + if (child.nodeType == 11) child = child.host; + if (child == parent) return true; + } while (child = child.parentNode); + }; + + function activeElt() { + var activeElement = document.activeElement; + while (activeElement && activeElement.root && activeElement.root.activeElement) + activeElement = activeElement.root.activeElement; + return activeElement; + } + // Older versions of IE throws unspecified error when touching + // document.activeElement in some cases (during loading, in iframe) + if (ie && ie_version < 11) activeElt = function() { + try { return document.activeElement; } + catch(e) { return document.body; } + }; + + function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); } + var rmClass = CodeMirror.rmClass = function(node, cls) { + var current = node.className; + var match = classTest(cls).exec(current); + if (match) { + var after = current.slice(match.index + match[0].length); + node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); + } + }; + var addClass = CodeMirror.addClass = function(node, cls) { + var current = node.className; + if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls; + }; + function joinClasses(a, b) { + var as = a.split(" "); + for (var i = 0; i < as.length; i++) + if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i]; + return b; + } + + // WINDOW-WIDE EVENTS + + // These must be handled carefully, because naively registering a + // handler for each editor will cause the editors to never be + // garbage collected. + + function forEachCodeMirror(f) { + if (!document.body.getElementsByClassName) return; + var byClass = document.body.getElementsByClassName("CodeMirror"); + for (var i = 0; i < byClass.length; i++) { + var cm = byClass[i].CodeMirror; + if (cm) f(cm); + } + } + + var globalsRegistered = false; + function ensureGlobalHandlers() { + if (globalsRegistered) return; + registerGlobalHandlers(); + globalsRegistered = true; + } + function registerGlobalHandlers() { + // When the window resizes, we need to refresh active editors. + var resizeTimer; + on(window, "resize", function() { + if (resizeTimer == null) resizeTimer = setTimeout(function() { + resizeTimer = null; + forEachCodeMirror(onResize); + }, 100); + }); + // When the window loses focus, we want to show the editor as blurred + on(window, "blur", function() { + forEachCodeMirror(onBlur); + }); + } + + // FEATURE DETECTION + + // Detect drag-and-drop + var dragAndDrop = function() { + // There is *some* kind of drag-and-drop support in IE6-8, but I + // couldn't get it to work yet. + if (ie && ie_version < 9) return false; + var div = elt('div'); + return "draggable" in div || "dragDrop" in div; + }(); + + var zwspSupported; + function zeroWidthElement(measure) { + if (zwspSupported == null) { + var test = elt("span", "\u200b"); + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); + if (measure.firstChild.offsetHeight != 0) + zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); + } + var node = zwspSupported ? elt("span", "\u200b") : + elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); + node.setAttribute("cm-text", ""); + return node; + } + + // Feature-detect IE's crummy client rect reporting for bidi text + var badBidiRects; + function hasBadBidiRects(measure) { + if (badBidiRects != null) return badBidiRects; + var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); + var r0 = range(txt, 0, 1).getBoundingClientRect(); + if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780) + var r1 = range(txt, 1, 2).getBoundingClientRect(); + return badBidiRects = (r1.right - r0.right < 3); + } + + // See if "".split is the broken IE version, if so, provide an + // alternative way to split lines. + var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { + var pos = 0, result = [], l = string.length; + while (pos <= l) { + var nl = string.indexOf("\n", pos); + if (nl == -1) nl = string.length; + var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); + var rt = line.indexOf("\r"); + if (rt != -1) { + result.push(line.slice(0, rt)); + pos += rt + 1; + } else { + result.push(line); + pos = nl + 1; + } + } + return result; + } : function(string){return string.split(/\r\n?|\n/);}; + + var hasSelection = window.getSelection ? function(te) { + try { return te.selectionStart != te.selectionEnd; } + catch(e) { return false; } + } : function(te) { + try {var range = te.ownerDocument.selection.createRange();} + catch(e) {} + if (!range || range.parentElement() != te) return false; + return range.compareEndPoints("StartToEnd", range) != 0; + }; + + var hasCopyEvent = (function() { + var e = elt("div"); + if ("oncopy" in e) return true; + e.setAttribute("oncopy", "return;"); + return typeof e.oncopy == "function"; + })(); + + var badZoomedRects = null; + function hasBadZoomedRects(measure) { + if (badZoomedRects != null) return badZoomedRects; + var node = removeChildrenAndAdd(measure, elt("span", "x")); + var normal = node.getBoundingClientRect(); + var fromRange = range(node, 0, 1).getBoundingClientRect(); + return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; + } + + // KEY NAMES + + var keyNames = CodeMirror.keyNames = { + 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", + 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", + 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", + 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", + 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", + 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", + 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", + 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" + }; + (function() { + // Number keys + for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i); + // Alphabetic keys + for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); + // Function keys + for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; + })(); + + // BIDI HELPERS + + function iterateBidiSections(order, from, to, f) { + if (!order) return f(from, to, "ltr"); + var found = false; + for (var i = 0; i < order.length; ++i) { + var part = order[i]; + if (part.from < to && part.to > from || from == to && part.to == from) { + f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); + found = true; + } + } + if (!found) f(from, to, "ltr"); + } + + function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } + function bidiRight(part) { return part.level % 2 ? part.from : part.to; } + + function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } + function lineRight(line) { + var order = getOrder(line); + if (!order) return line.text.length; + return bidiRight(lst(order)); + } + + function lineStart(cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLine(line); + if (visual != line) lineN = lineNo(visual); + var order = getOrder(visual); + var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); + return Pos(lineN, ch); + } + function lineEnd(cm, lineN) { + var merged, line = getLine(cm.doc, lineN); + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + lineN = null; + } + var order = getOrder(line); + var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); + return Pos(lineN == null ? lineNo(line) : lineN, ch); + } + function lineStartSmart(cm, pos) { + var start = lineStart(cm, pos.line); + var line = getLine(cm.doc, start.line); + var order = getOrder(line); + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(0, line.text.search(/\S/)); + var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; + return Pos(start.line, inWS ? 0 : firstNonWS); + } + return start; + } + + function compareBidiLevel(order, a, b) { + var linedir = order[0].level; + if (a == linedir) return true; + if (b == linedir) return false; + return a < b; + } + var bidiOther; + function getBidiPartAt(order, pos) { + bidiOther = null; + for (var i = 0, found; i < order.length; ++i) { + var cur = order[i]; + if (cur.from < pos && cur.to > pos) return i; + if ((cur.from == pos || cur.to == pos)) { + if (found == null) { + found = i; + } else if (compareBidiLevel(order, cur.level, order[found].level)) { + if (cur.from != cur.to) bidiOther = found; + return i; + } else { + if (cur.from != cur.to) bidiOther = i; + return found; + } + } + } + return found; + } + + function moveInLine(line, pos, dir, byUnit) { + if (!byUnit) return pos + dir; + do pos += dir; + while (pos > 0 && isExtendingChar(line.text.charAt(pos))); + return pos; + } + + // This is needed in order to move 'visually' through bi-directional + // text -- i.e., pressing left should make the cursor go left, even + // when in RTL text. The tricky part is the 'jumps', where RTL and + // LTR text touch each other. This often requires the cursor offset + // to move more than one unit, in order to visually move one unit. + function moveVisually(line, start, dir, byUnit) { + var bidi = getOrder(line); + if (!bidi) return moveLogically(line, start, dir, byUnit); + var pos = getBidiPartAt(bidi, start), part = bidi[pos]; + var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); + + for (;;) { + if (target > part.from && target < part.to) return target; + if (target == part.from || target == part.to) { + if (getBidiPartAt(bidi, target) == pos) return target; + part = bidi[pos += dir]; + return (dir > 0) == part.level % 2 ? part.to : part.from; + } else { + part = bidi[pos += dir]; + if (!part) return null; + if ((dir > 0) == part.level % 2) + target = moveInLine(line, part.to, -1, byUnit); + else + target = moveInLine(line, part.from, 1, byUnit); + } + } + } + + function moveLogically(line, start, dir, byUnit) { + var target = start + dir; + if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir; + return target < 0 || target > line.text.length ? null : target; + } + + // Bidirectional ordering algorithm + // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm + // that this (partially) implements. + + // One-char codes used for character types: + // L (L): Left-to-Right + // R (R): Right-to-Left + // r (AL): Right-to-Left Arabic + // 1 (EN): European Number + // + (ES): European Number Separator + // % (ET): European Number Terminator + // n (AN): Arabic Number + // , (CS): Common Number Separator + // m (NSM): Non-Spacing Mark + // b (BN): Boundary Neutral + // s (B): Paragraph Separator + // t (S): Segment Separator + // w (WS): Whitespace + // N (ON): Other Neutrals + + // Returns null if characters are ordered as they appear + // (left-to-right), or an array of sections ({from, to, level} + // objects) in the order in which they occur visually. + var bidiOrdering = (function() { + // Character types for codepoints 0 to 0xff + var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; + // Character types for codepoints 0x600 to 0x6ff + var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm"; + function charType(code) { + if (code <= 0xf7) return lowTypes.charAt(code); + else if (0x590 <= code && code <= 0x5f4) return "R"; + else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600); + else if (0x6ee <= code && code <= 0x8ac) return "r"; + else if (0x2000 <= code && code <= 0x200b) return "w"; + else if (code == 0x200c) return "b"; + else return "L"; + } + + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; + var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; + // Browsers seem to always treat the boundaries of block elements as being L. + var outerType = "L"; + + function BidiSpan(level, from, to) { + this.level = level; + this.from = from; this.to = to; + } + + return function(str) { + if (!bidiRE.test(str)) return false; + var len = str.length, types = []; + for (var i = 0, type; i < len; ++i) + types.push(type = charType(str.charCodeAt(i))); + + // W1. Examine each non-spacing mark (NSM) in the level run, and + // change the type of the NSM to the type of the previous + // character. If the NSM is at the start of the level run, it will + // get the type of sor. + for (var i = 0, prev = outerType; i < len; ++i) { + var type = types[i]; + if (type == "m") types[i] = prev; + else prev = type; + } + + // W2. Search backwards from each instance of a European number + // until the first strong type (R, L, AL, or sor) is found. If an + // AL is found, change the type of the European number to Arabic + // number. + // W3. Change all ALs to R. + for (var i = 0, cur = outerType; i < len; ++i) { + var type = types[i]; + if (type == "1" && cur == "r") types[i] = "n"; + else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } + } + + // W4. A single European separator between two European numbers + // changes to a European number. A single common separator between + // two numbers of the same type changes to that type. + for (var i = 1, prev = types[0]; i < len - 1; ++i) { + var type = types[i]; + if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; + else if (type == "," && prev == types[i+1] && + (prev == "1" || prev == "n")) types[i] = prev; + prev = type; + } + + // W5. A sequence of European terminators adjacent to European + // numbers changes to all European numbers. + // W6. Otherwise, separators and terminators change to Other + // Neutral. + for (var i = 0; i < len; ++i) { + var type = types[i]; + if (type == ",") types[i] = "N"; + else if (type == "%") { + for (var end = i + 1; end < len && types[end] == "%"; ++end) {} + var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; + for (var j = i; j < end; ++j) types[j] = replace; + i = end - 1; + } + } + + // W7. Search backwards from each instance of a European number + // until the first strong type (R, L, or sor) is found. If an L is + // found, then change the type of the European number to L. + for (var i = 0, cur = outerType; i < len; ++i) { + var type = types[i]; + if (cur == "L" && type == "1") types[i] = "L"; + else if (isStrong.test(type)) cur = type; + } + + // N1. A sequence of neutrals takes the direction of the + // surrounding strong text if the text on both sides has the same + // direction. European and Arabic numbers act as if they were R in + // terms of their influence on neutrals. Start-of-level-run (sor) + // and end-of-level-run (eor) are used at level run boundaries. + // N2. Any remaining neutrals take the embedding direction. + for (var i = 0; i < len; ++i) { + if (isNeutral.test(types[i])) { + for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} + var before = (i ? types[i-1] : outerType) == "L"; + var after = (end < len ? types[end] : outerType) == "L"; + var replace = before || after ? "L" : "R"; + for (var j = i; j < end; ++j) types[j] = replace; + i = end - 1; + } + } + + // Here we depart from the documented algorithm, in order to avoid + // building up an actual levels array. Since there are only three + // levels (0, 1, 2) in an implementation that doesn't take + // explicit embedding into account, we can build up the order on + // the fly, without following the level-based algorithm. + var order = [], m; + for (var i = 0; i < len;) { + if (countsAsLeft.test(types[i])) { + var start = i; + for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} + order.push(new BidiSpan(0, start, i)); + } else { + var pos = i, at = order.length; + for (++i; i < len && types[i] != "L"; ++i) {} + for (var j = pos; j < i;) { + if (countsAsNum.test(types[j])) { + if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j)); + var nstart = j; + for (++j; j < i && countsAsNum.test(types[j]); ++j) {} + order.splice(at, 0, new BidiSpan(2, nstart, j)); + pos = j; + } else ++j; + } + if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i)); + } + } + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length; + order.unshift(new BidiSpan(0, 0, m[0].length)); + } + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length; + order.push(new BidiSpan(0, len - m[0].length, len)); + } + if (order[0].level == 2) + order.unshift(new BidiSpan(1, order[0].to, order[0].to)); + if (order[0].level != lst(order).level) + order.push(new BidiSpan(order[0].level, len, len)); + + return order; + }; + })(); + + // THE END + + CodeMirror.version = "5.15.2"; + + return CodeMirror; +}); diff --git a/js/codemirror/5.15.2/css.js b/js/codemirror/5.15.2/css.js new file mode 100644 index 0000000..ea7bd01 --- /dev/null +++ b/js/codemirror/5.15.2/css.js @@ -0,0 +1,825 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("css", function(config, parserConfig) { + var inline = parserConfig.inline + if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css"); + + var indentUnit = config.indentUnit, + tokenHooks = parserConfig.tokenHooks, + documentTypes = parserConfig.documentTypes || {}, + mediaTypes = parserConfig.mediaTypes || {}, + mediaFeatures = parserConfig.mediaFeatures || {}, + mediaValueKeywords = parserConfig.mediaValueKeywords || {}, + propertyKeywords = parserConfig.propertyKeywords || {}, + nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {}, + fontProperties = parserConfig.fontProperties || {}, + counterDescriptors = parserConfig.counterDescriptors || {}, + colorKeywords = parserConfig.colorKeywords || {}, + valueKeywords = parserConfig.valueKeywords || {}, + allowNested = parserConfig.allowNested, + supportsAtComponent = parserConfig.supportsAtComponent === true; + + var type, override; + function ret(style, tp) { type = tp; return style; } + + // Tokenizers + + function tokenBase(stream, state) { + var ch = stream.next(); + if (tokenHooks[ch]) { + var result = tokenHooks[ch](stream, state); + if (result !== false) return result; + } + if (ch == "@") { + stream.eatWhile(/[\w\\\-]/); + return ret("def", stream.current()); + } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) { + return ret(null, "compare"); + } else if (ch == "\"" || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "#") { + stream.eatWhile(/[\w\\\-]/); + return ret("atom", "hash"); + } else if (ch == "!") { + stream.match(/^\s*\w*/); + return ret("keyword", "important"); + } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (ch === "-") { + if (/[\d.]/.test(stream.peek())) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (stream.match(/^-[\w\\\-]+/)) { + stream.eatWhile(/[\w\\\-]/); + if (stream.match(/^\s*:/, false)) + return ret("variable-2", "variable-definition"); + return ret("variable-2", "variable"); + } else if (stream.match(/^\w+-/)) { + return ret("meta", "meta"); + } + } else if (/[,+>*\/]/.test(ch)) { + return ret(null, "select-op"); + } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) { + return ret("qualifier", "qualifier"); + } else if (/[:;{}\[\]\(\)]/.test(ch)) { + return ret(null, ch); + } else if ((ch == "u" && stream.match(/rl(-prefix)?\(/)) || + (ch == "d" && stream.match("omain(")) || + (ch == "r" && stream.match("egexp("))) { + stream.backUp(1); + state.tokenize = tokenParenthesized; + return ret("property", "word"); + } else if (/[\w\\\-]/.test(ch)) { + stream.eatWhile(/[\w\\\-]/); + return ret("property", "word"); + } else { + return ret(null, null); + } + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) { + if (quote == ")") stream.backUp(1); + break; + } + escaped = !escaped && ch == "\\"; + } + if (ch == quote || !escaped && quote != ")") state.tokenize = null; + return ret("string", "string"); + }; + } + + function tokenParenthesized(stream, state) { + stream.next(); // Must be '(' + if (!stream.match(/\s*[\"\')]/, false)) + state.tokenize = tokenString(")"); + else + state.tokenize = null; + return ret(null, "("); + } + + // Context management + + function Context(type, indent, prev) { + this.type = type; + this.indent = indent; + this.prev = prev; + } + + function pushContext(state, stream, type, indent) { + state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context); + return type; + } + + function popContext(state) { + if (state.context.prev) + state.context = state.context.prev; + return state.context.type; + } + + function pass(type, stream, state) { + return states[state.context.type](type, stream, state); + } + function popAndPass(type, stream, state, n) { + for (var i = n || 1; i > 0; i--) + state.context = state.context.prev; + return pass(type, stream, state); + } + + // Parser + + function wordAsValue(stream) { + var word = stream.current().toLowerCase(); + if (valueKeywords.hasOwnProperty(word)) + override = "atom"; + else if (colorKeywords.hasOwnProperty(word)) + override = "keyword"; + else + override = "variable"; + } + + var states = {}; + + states.top = function(type, stream, state) { + if (type == "{") { + return pushContext(state, stream, "block"); + } else if (type == "}" && state.context.prev) { + return popContext(state); + } else if (supportsAtComponent && /@component/.test(type)) { + return pushContext(state, stream, "atComponentBlock"); + } else if (/^@(-moz-)?document$/.test(type)) { + return pushContext(state, stream, "documentTypes"); + } else if (/^@(media|supports|(-moz-)?document|import)$/.test(type)) { + return pushContext(state, stream, "atBlock"); + } else if (/^@(font-face|counter-style)/.test(type)) { + state.stateArg = type; + return "restricted_atBlock_before"; + } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) { + return "keyframes"; + } else if (type && type.charAt(0) == "@") { + return pushContext(state, stream, "at"); + } else if (type == "hash") { + override = "builtin"; + } else if (type == "word") { + override = "tag"; + } else if (type == "variable-definition") { + return "maybeprop"; + } else if (type == "interpolation") { + return pushContext(state, stream, "interpolation"); + } else if (type == ":") { + return "pseudo"; + } else if (allowNested && type == "(") { + return pushContext(state, stream, "parens"); + } + return state.context.type; + }; + + states.block = function(type, stream, state) { + if (type == "word") { + var word = stream.current().toLowerCase(); + if (propertyKeywords.hasOwnProperty(word)) { + override = "property"; + return "maybeprop"; + } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) { + override = "string-2"; + return "maybeprop"; + } else if (allowNested) { + override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag"; + return "block"; + } else { + override += " error"; + return "maybeprop"; + } + } else if (type == "meta") { + return "block"; + } else if (!allowNested && (type == "hash" || type == "qualifier")) { + override = "error"; + return "block"; + } else { + return states.top(type, stream, state); + } + }; + + states.maybeprop = function(type, stream, state) { + if (type == ":") return pushContext(state, stream, "prop"); + return pass(type, stream, state); + }; + + states.prop = function(type, stream, state) { + if (type == ";") return popContext(state); + if (type == "{" && allowNested) return pushContext(state, stream, "propBlock"); + if (type == "}" || type == "{") return popAndPass(type, stream, state); + if (type == "(") return pushContext(state, stream, "parens"); + + if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) { + override += " error"; + } else if (type == "word") { + wordAsValue(stream); + } else if (type == "interpolation") { + return pushContext(state, stream, "interpolation"); + } + return "prop"; + }; + + states.propBlock = function(type, _stream, state) { + if (type == "}") return popContext(state); + if (type == "word") { override = "property"; return "maybeprop"; } + return state.context.type; + }; + + states.parens = function(type, stream, state) { + if (type == "{" || type == "}") return popAndPass(type, stream, state); + if (type == ")") return popContext(state); + if (type == "(") return pushContext(state, stream, "parens"); + if (type == "interpolation") return pushContext(state, stream, "interpolation"); + if (type == "word") wordAsValue(stream); + return "parens"; + }; + + states.pseudo = function(type, stream, state) { + if (type == "word") { + override = "variable-3"; + return state.context.type; + } + return pass(type, stream, state); + }; + + states.documentTypes = function(type, stream, state) { + if (type == "word" && documentTypes.hasOwnProperty(stream.current())) { + override = "tag"; + return state.context.type; + } else { + return states.atBlock(type, stream, state); + } + }; + + states.atBlock = function(type, stream, state) { + if (type == "(") return pushContext(state, stream, "atBlock_parens"); + if (type == "}" || type == ";") return popAndPass(type, stream, state); + if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top"); + + if (type == "interpolation") return pushContext(state, stream, "interpolation"); + + if (type == "word") { + var word = stream.current().toLowerCase(); + if (word == "only" || word == "not" || word == "and" || word == "or") + override = "keyword"; + else if (mediaTypes.hasOwnProperty(word)) + override = "attribute"; + else if (mediaFeatures.hasOwnProperty(word)) + override = "property"; + else if (mediaValueKeywords.hasOwnProperty(word)) + override = "keyword"; + else if (propertyKeywords.hasOwnProperty(word)) + override = "property"; + else if (nonStandardPropertyKeywords.hasOwnProperty(word)) + override = "string-2"; + else if (valueKeywords.hasOwnProperty(word)) + override = "atom"; + else if (colorKeywords.hasOwnProperty(word)) + override = "keyword"; + else + override = "error"; + } + return state.context.type; + }; + + states.atComponentBlock = function(type, stream, state) { + if (type == "}") + return popAndPass(type, stream, state); + if (type == "{") + return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false); + if (type == "word") + override = "error"; + return state.context.type; + }; + + states.atBlock_parens = function(type, stream, state) { + if (type == ")") return popContext(state); + if (type == "{" || type == "}") return popAndPass(type, stream, state, 2); + return states.atBlock(type, stream, state); + }; + + states.restricted_atBlock_before = function(type, stream, state) { + if (type == "{") + return pushContext(state, stream, "restricted_atBlock"); + if (type == "word" && state.stateArg == "@counter-style") { + override = "variable"; + return "restricted_atBlock_before"; + } + return pass(type, stream, state); + }; + + states.restricted_atBlock = function(type, stream, state) { + if (type == "}") { + state.stateArg = null; + return popContext(state); + } + if (type == "word") { + if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) || + (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase()))) + override = "error"; + else + override = "property"; + return "maybeprop"; + } + return "restricted_atBlock"; + }; + + states.keyframes = function(type, stream, state) { + if (type == "word") { override = "variable"; return "keyframes"; } + if (type == "{") return pushContext(state, stream, "top"); + return pass(type, stream, state); + }; + + states.at = function(type, stream, state) { + if (type == ";") return popContext(state); + if (type == "{" || type == "}") return popAndPass(type, stream, state); + if (type == "word") override = "tag"; + else if (type == "hash") override = "builtin"; + return "at"; + }; + + states.interpolation = function(type, stream, state) { + if (type == "}") return popContext(state); + if (type == "{" || type == ";") return popAndPass(type, stream, state); + if (type == "word") override = "variable"; + else if (type != "variable" && type != "(" && type != ")") override = "error"; + return "interpolation"; + }; + + return { + startState: function(base) { + return {tokenize: null, + state: inline ? "block" : "top", + stateArg: null, + context: new Context(inline ? "block" : "top", base || 0, null)}; + }, + + token: function(stream, state) { + if (!state.tokenize && stream.eatSpace()) return null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style && typeof style == "object") { + type = style[1]; + style = style[0]; + } + override = style; + state.state = states[state.state](type, stream, state); + return override; + }, + + indent: function(state, textAfter) { + var cx = state.context, ch = textAfter && textAfter.charAt(0); + var indent = cx.indent; + if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev; + if (cx.prev) { + if (ch == "}" && (cx.type == "block" || cx.type == "top" || + cx.type == "interpolation" || cx.type == "restricted_atBlock")) { + // Resume indentation from parent context. + cx = cx.prev; + indent = cx.indent; + } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") || + ch == "{" && (cx.type == "at" || cx.type == "atBlock")) { + // Dedent relative to current context. + indent = Math.max(0, cx.indent - indentUnit); + cx = cx.prev; + } + } + return indent; + }, + + electricChars: "}", + blockCommentStart: "/*", + blockCommentEnd: "*/", + fold: "brace" + }; +}); + + function keySet(array) { + var keys = {}; + for (var i = 0; i < array.length; ++i) { + keys[array[i]] = true; + } + return keys; + } + + var documentTypes_ = [ + "domain", "regexp", "url", "url-prefix" + ], documentTypes = keySet(documentTypes_); + + var mediaTypes_ = [ + "all", "aural", "braille", "handheld", "print", "projection", "screen", + "tty", "tv", "embossed" + ], mediaTypes = keySet(mediaTypes_); + + var mediaFeatures_ = [ + "width", "min-width", "max-width", "height", "min-height", "max-height", + "device-width", "min-device-width", "max-device-width", "device-height", + "min-device-height", "max-device-height", "aspect-ratio", + "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio", + "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color", + "max-color", "color-index", "min-color-index", "max-color-index", + "monochrome", "min-monochrome", "max-monochrome", "resolution", + "min-resolution", "max-resolution", "scan", "grid", "orientation", + "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio", + "pointer", "any-pointer", "hover", "any-hover" + ], mediaFeatures = keySet(mediaFeatures_); + + var mediaValueKeywords_ = [ + "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover", + "interlace", "progressive" + ], mediaValueKeywords = keySet(mediaValueKeywords_); + + var propertyKeywords_ = [ + "align-content", "align-items", "align-self", "alignment-adjust", + "alignment-baseline", "anchor-point", "animation", "animation-delay", + "animation-direction", "animation-duration", "animation-fill-mode", + "animation-iteration-count", "animation-name", "animation-play-state", + "animation-timing-function", "appearance", "azimuth", "backface-visibility", + "background", "background-attachment", "background-blend-mode", "background-clip", + "background-color", "background-image", "background-origin", "background-position", + "background-repeat", "background-size", "baseline-shift", "binding", + "bleed", "bookmark-label", "bookmark-level", "bookmark-state", + "bookmark-target", "border", "border-bottom", "border-bottom-color", + "border-bottom-left-radius", "border-bottom-right-radius", + "border-bottom-style", "border-bottom-width", "border-collapse", + "border-color", "border-image", "border-image-outset", + "border-image-repeat", "border-image-slice", "border-image-source", + "border-image-width", "border-left", "border-left-color", + "border-left-style", "border-left-width", "border-radius", "border-right", + "border-right-color", "border-right-style", "border-right-width", + "border-spacing", "border-style", "border-top", "border-top-color", + "border-top-left-radius", "border-top-right-radius", "border-top-style", + "border-top-width", "border-width", "bottom", "box-decoration-break", + "box-shadow", "box-sizing", "break-after", "break-before", "break-inside", + "caption-side", "clear", "clip", "color", "color-profile", "column-count", + "column-fill", "column-gap", "column-rule", "column-rule-color", + "column-rule-style", "column-rule-width", "column-span", "column-width", + "columns", "content", "counter-increment", "counter-reset", "crop", "cue", + "cue-after", "cue-before", "cursor", "direction", "display", + "dominant-baseline", "drop-initial-after-adjust", + "drop-initial-after-align", "drop-initial-before-adjust", + "drop-initial-before-align", "drop-initial-size", "drop-initial-value", + "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis", + "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap", + "float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings", + "font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust", + "font-stretch", "font-style", "font-synthesis", "font-variant", + "font-variant-alternates", "font-variant-caps", "font-variant-east-asian", + "font-variant-ligatures", "font-variant-numeric", "font-variant-position", + "font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow", + "grid-auto-rows", "grid-column", "grid-column-end", "grid-column-gap", + "grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap", + "grid-row-start", "grid-template", "grid-template-areas", "grid-template-columns", + "grid-template-rows", "hanging-punctuation", "height", "hyphens", + "icon", "image-orientation", "image-rendering", "image-resolution", + "inline-box-align", "justify-content", "left", "letter-spacing", + "line-break", "line-height", "line-stacking", "line-stacking-ruby", + "line-stacking-shift", "line-stacking-strategy", "list-style", + "list-style-image", "list-style-position", "list-style-type", "margin", + "margin-bottom", "margin-left", "margin-right", "margin-top", + "marker-offset", "marks", "marquee-direction", "marquee-loop", + "marquee-play-count", "marquee-speed", "marquee-style", "max-height", + "max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index", + "nav-left", "nav-right", "nav-up", "object-fit", "object-position", + "opacity", "order", "orphans", "outline", + "outline-color", "outline-offset", "outline-style", "outline-width", + "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y", + "padding", "padding-bottom", "padding-left", "padding-right", "padding-top", + "page", "page-break-after", "page-break-before", "page-break-inside", + "page-policy", "pause", "pause-after", "pause-before", "perspective", + "perspective-origin", "pitch", "pitch-range", "play-during", "position", + "presentation-level", "punctuation-trim", "quotes", "region-break-after", + "region-break-before", "region-break-inside", "region-fragment", + "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness", + "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang", + "ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin", + "shape-outside", "size", "speak", "speak-as", "speak-header", + "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set", + "tab-size", "table-layout", "target", "target-name", "target-new", + "target-position", "text-align", "text-align-last", "text-decoration", + "text-decoration-color", "text-decoration-line", "text-decoration-skip", + "text-decoration-style", "text-emphasis", "text-emphasis-color", + "text-emphasis-position", "text-emphasis-style", "text-height", + "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow", + "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position", + "text-wrap", "top", "transform", "transform-origin", "transform-style", + "transition", "transition-delay", "transition-duration", + "transition-property", "transition-timing-function", "unicode-bidi", + "vertical-align", "visibility", "voice-balance", "voice-duration", + "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress", + "voice-volume", "volume", "white-space", "widows", "width", "word-break", + "word-spacing", "word-wrap", "z-index", + // SVG-specific + "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color", + "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events", + "color-interpolation", "color-interpolation-filters", + "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering", + "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke", + "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", + "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering", + "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal", + "glyph-orientation-vertical", "text-anchor", "writing-mode" + ], propertyKeywords = keySet(propertyKeywords_); + + var nonStandardPropertyKeywords_ = [ + "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color", + "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color", + "scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside", + "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", + "searchfield-results-decoration", "zoom" + ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_); + + var fontProperties_ = [ + "font-family", "src", "unicode-range", "font-variant", "font-feature-settings", + "font-stretch", "font-weight", "font-style" + ], fontProperties = keySet(fontProperties_); + + var counterDescriptors_ = [ + "additive-symbols", "fallback", "negative", "pad", "prefix", "range", + "speak-as", "suffix", "symbols", "system" + ], counterDescriptors = keySet(counterDescriptors_); + + var colorKeywords_ = [ + "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", + "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", + "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", + "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", + "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", + "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", + "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", + "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", + "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", + "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew", + "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", + "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", + "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink", + "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", + "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", + "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", + "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", + "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", + "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", + "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", + "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", + "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown", + "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", + "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", + "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", + "whitesmoke", "yellow", "yellowgreen" + ], colorKeywords = keySet(colorKeywords_); + + var valueKeywords_ = [ + "above", "absolute", "activeborder", "additive", "activecaption", "afar", + "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate", + "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", + "arabic-indic", "armenian", "asterisks", "attr", "auto", "avoid", "avoid-column", "avoid-page", + "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary", + "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box", + "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel", + "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian", + "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", + "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch", + "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", + "col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse", + "compact", "condensed", "contain", "content", + "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop", + "cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal", + "decimal-leading-zero", "default", "default-button", "dense", "destination-atop", + "destination-in", "destination-out", "destination-over", "devanagari", "difference", + "disc", "discard", "disclosure-closed", "disclosure-open", "document", + "dot-dash", "dot-dot-dash", + "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", + "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", + "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er", + "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", + "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et", + "ethiopic-halehame-gez", "ethiopic-halehame-om-et", + "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et", + "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig", + "ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed", + "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes", + "forwards", "from", "geometricPrecision", "georgian", "graytext", "grid", "groove", + "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew", + "help", "hidden", "hide", "higher", "highlight", "highlighttext", + "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "icon", "ignore", + "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", + "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", + "inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert", + "italic", "japanese-formal", "japanese-informal", "justify", "kannada", + "katakana", "katakana-iroha", "keep-all", "khmer", + "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal", + "landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten", + "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem", + "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", + "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian", + "lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "match", "matrix", "matrix3d", + "media-controls-background", "media-current-time-display", + "media-fullscreen-button", "media-mute-button", "media-play-button", + "media-return-to-realtime-button", "media-rewind-button", + "media-seek-back-button", "media-seek-forward-button", "media-slider", + "media-sliderthumb", "media-time-remaining-display", "media-volume-slider", + "media-volume-slider-container", "media-volume-sliderthumb", "medium", + "menu", "menulist", "menulist-button", "menulist-text", + "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic", + "mix", "mongolian", "monospace", "move", "multiple", "multiply", "myanmar", "n-resize", + "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", + "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", + "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote", + "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", + "outside", "outside-shape", "overlay", "overline", "padding", "padding-box", + "painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter", + "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", + "progress", "push-button", "radial-gradient", "radio", "read-only", + "read-write", "read-write-plaintext-only", "rectangle", "region", + "relative", "repeat", "repeating-linear-gradient", + "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse", + "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY", + "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running", + "s-resize", "sans-serif", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen", + "scroll", "scrollbar", "se-resize", "searchfield", + "searchfield-cancel-button", "searchfield-decoration", + "searchfield-results-button", "searchfield-results-decoration", + "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama", + "simp-chinese-formal", "simp-chinese-informal", "single", + "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal", + "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", + "small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali", + "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "spell-out", "square", + "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub", + "subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "table", + "table-caption", "table-cell", "table-column", "table-column-group", + "table-footer-group", "table-header-group", "table-row", "table-row-group", + "tamil", + "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai", + "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight", + "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er", + "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top", + "trad-chinese-formal", "trad-chinese-informal", + "translate", "translate3d", "translateX", "translateY", "translateZ", + "transparent", "ultra-condensed", "ultra-expanded", "underline", "up", + "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", + "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", + "var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted", + "visibleStroke", "visual", "w-resize", "wait", "wave", "wider", + "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor", + "xx-large", "xx-small" + ], valueKeywords = keySet(valueKeywords_); + + var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_) + .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_) + .concat(valueKeywords_); + CodeMirror.registerHelper("hintWords", "css", allWords); + + function tokenCComment(stream, state) { + var maybeEnd = false, ch; + while ((ch = stream.next()) != null) { + if (maybeEnd && ch == "/") { + state.tokenize = null; + break; + } + maybeEnd = (ch == "*"); + } + return ["comment", "comment"]; + } + + CodeMirror.defineMIME("text/css", { + documentTypes: documentTypes, + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + fontProperties: fontProperties, + counterDescriptors: counterDescriptors, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + tokenHooks: { + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + }, + name: "css" + }); + + CodeMirror.defineMIME("text/x-scss", { + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + fontProperties: fontProperties, + allowNested: true, + tokenHooks: { + "/": function(stream, state) { + if (stream.eat("/")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } else if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else { + return ["operator", "operator"]; + } + }, + ":": function(stream) { + if (stream.match(/\s*\{/)) + return [null, "{"]; + return false; + }, + "$": function(stream) { + stream.match(/^[\w-]+/); + if (stream.match(/^\s*:/, false)) + return ["variable-2", "variable-definition"]; + return ["variable-2", "variable"]; + }, + "#": function(stream) { + if (!stream.eat("{")) return false; + return [null, "interpolation"]; + } + }, + name: "css", + helperType: "scss" + }); + + CodeMirror.defineMIME("text/x-less", { + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + fontProperties: fontProperties, + allowNested: true, + tokenHooks: { + "/": function(stream, state) { + if (stream.eat("/")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } else if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else { + return ["operator", "operator"]; + } + }, + "@": function(stream) { + if (stream.eat("{")) return [null, "interpolation"]; + if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/, false)) return false; + stream.eatWhile(/[\w\\\-]/); + if (stream.match(/^\s*:/, false)) + return ["variable-2", "variable-definition"]; + return ["variable-2", "variable"]; + }, + "&": function() { + return ["atom", "atom"]; + } + }, + name: "css", + helperType: "less" + }); + + CodeMirror.defineMIME("text/x-gss", { + documentTypes: documentTypes, + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + fontProperties: fontProperties, + counterDescriptors: counterDescriptors, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + supportsAtComponent: true, + tokenHooks: { + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + }, + name: "css", + helperType: "gss" + }); + +}); diff --git a/js/codemirror/5.15.2/htmlmixed.js b/js/codemirror/5.15.2/htmlmixed.js new file mode 100644 index 0000000..d74083e --- /dev/null +++ b/js/codemirror/5.15.2/htmlmixed.js @@ -0,0 +1,152 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("../xml/xml"), require("../javascript/javascript"), require("../css/css")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript", "../css/css"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var defaultTags = { + script: [ + ["lang", /(javascript|babel)/i, "javascript"], + ["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i, "javascript"], + ["type", /./, "text/plain"], + [null, null, "javascript"] + ], + style: [ + ["lang", /^css$/i, "css"], + ["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"], + ["type", /./, "text/plain"], + [null, null, "css"] + ] + }; + + function maybeBackup(stream, pat, style) { + var cur = stream.current(), close = cur.search(pat); + if (close > -1) { + stream.backUp(cur.length - close); + } else if (cur.match(/<\/?$/)) { + stream.backUp(cur.length); + if (!stream.match(pat, false)) stream.match(cur); + } + return style; + } + + var attrRegexpCache = {}; + function getAttrRegexp(attr) { + var regexp = attrRegexpCache[attr]; + if (regexp) return regexp; + return attrRegexpCache[attr] = new RegExp("\\s+" + attr + "\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*"); + } + + function getAttrValue(text, attr) { + var match = text.match(getAttrRegexp(attr)) + return match ? match[2] : "" + } + + function getTagRegexp(tagName, anchored) { + return new RegExp((anchored ? "^" : "") + "<\/\s*" + tagName + "\s*>", "i"); + } + + function addTags(from, to) { + for (var tag in from) { + var dest = to[tag] || (to[tag] = []); + var source = from[tag]; + for (var i = source.length - 1; i >= 0; i--) + dest.unshift(source[i]) + } + } + + function findMatchingMode(tagInfo, tagText) { + for (var i = 0; i < tagInfo.length; i++) { + var spec = tagInfo[i]; + if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2]; + } + } + + CodeMirror.defineMode("htmlmixed", function (config, parserConfig) { + var htmlMode = CodeMirror.getMode(config, { + name: "xml", + htmlMode: true, + multilineTagIndentFactor: parserConfig.multilineTagIndentFactor, + multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag + }); + + var tags = {}; + var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes; + addTags(defaultTags, tags); + if (configTags) addTags(configTags, tags); + if (configScript) for (var i = configScript.length - 1; i >= 0; i--) + tags.script.unshift(["type", configScript[i].matches, configScript[i].mode]) + + function html(stream, state) { + var style = htmlMode.token(stream, state.htmlState), tag = /\btag\b/.test(style), tagName + if (tag && !/[<>\s\/]/.test(stream.current()) && + (tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) && + tags.hasOwnProperty(tagName)) { + state.inTag = tagName + " " + } else if (state.inTag && tag && />$/.test(stream.current())) { + var inTag = /^([\S]+) (.*)/.exec(state.inTag) + state.inTag = null + var modeSpec = stream.current() == ">" && findMatchingMode(tags[inTag[1]], inTag[2]) + var mode = CodeMirror.getMode(config, modeSpec) + var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false); + state.token = function (stream, state) { + if (stream.match(endTagA, false)) { + state.token = html; + state.localState = state.localMode = null; + return null; + } + return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState)); + }; + state.localMode = mode; + state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, "")); + } else if (state.inTag) { + state.inTag += stream.current() + if (stream.eol()) state.inTag += " " + } + return style; + }; + + return { + startState: function () { + var state = CodeMirror.startState(htmlMode); + return {token: html, inTag: null, localMode: null, localState: null, htmlState: state}; + }, + + copyState: function (state) { + var local; + if (state.localState) { + local = CodeMirror.copyState(state.localMode, state.localState); + } + return {token: state.token, inTag: state.inTag, + localMode: state.localMode, localState: local, + htmlState: CodeMirror.copyState(htmlMode, state.htmlState)}; + }, + + token: function (stream, state) { + return state.token(stream, state); + }, + + indent: function (state, textAfter) { + if (!state.localMode || /^\s*<\//.test(textAfter)) + return htmlMode.indent(state.htmlState, textAfter); + else if (state.localMode.indent) + return state.localMode.indent(state.localState, textAfter); + else + return CodeMirror.Pass; + }, + + innerMode: function (state) { + return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode}; + } + }; + }, "xml", "javascript", "css"); + + CodeMirror.defineMIME("text/html", "htmlmixed"); +}); diff --git a/js/codemirror/5.15.2/javascript.js b/js/codemirror/5.15.2/javascript.js new file mode 100644 index 0000000..ca87541 --- /dev/null +++ b/js/codemirror/5.15.2/javascript.js @@ -0,0 +1,748 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// TODO actually recognize syntax of TypeScript constructs + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +function expressionAllowed(stream, state, backUp) { + return /^(?:operator|sof|keyword c|case|new|[\[{}\(,;:]|=>)$/.test(state.lastType) || + (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0)))) +} + +CodeMirror.defineMode("javascript", function(config, parserConfig) { + var indentUnit = config.indentUnit; + var statementIndent = parserConfig.statementIndent; + var jsonldMode = parserConfig.jsonld; + var jsonMode = parserConfig.json || jsonldMode; + var isTS = parserConfig.typescript; + var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; + + // Tokenizer + + var keywords = function(){ + function kw(type) {return {type: type, style: "keyword"};} + var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"); + var operator = kw("operator"), atom = {type: "atom", style: "atom"}; + + var jsKeywords = { + "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, + "return": C, "break": C, "continue": C, "new": kw("new"), "delete": C, "throw": C, "debugger": C, + "var": kw("var"), "const": kw("var"), "let": kw("var"), + "function": kw("function"), "catch": kw("catch"), + "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), + "in": operator, "typeof": operator, "instanceof": operator, + "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, + "this": kw("this"), "class": kw("class"), "super": kw("atom"), + "yield": C, "export": kw("export"), "import": kw("import"), "extends": C, + "await": C, "async": kw("async") + }; + + // Extend the 'normal' keywords with the TypeScript language extensions + if (isTS) { + var type = {type: "variable", style: "variable-3"}; + var tsKeywords = { + // object-like things + "interface": kw("class"), + "implements": C, + "namespace": C, + "module": kw("module"), + "enum": kw("module"), + + // scope modifiers + "public": kw("modifier"), + "private": kw("modifier"), + "protected": kw("modifier"), + "abstract": kw("modifier"), + + // operators + "as": operator, + + // types + "string": type, "number": type, "boolean": type, "any": type + }; + + for (var attr in tsKeywords) { + jsKeywords[attr] = tsKeywords[attr]; + } + } + + return jsKeywords; + }(); + + var isOperatorChar = /[+\-*&%=<>!?|~^]/; + var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; + + function readRegexp(stream) { + var escaped = false, next, inSet = false; + while ((next = stream.next()) != null) { + if (!escaped) { + if (next == "/" && !inSet) return; + if (next == "[") inSet = true; + else if (inSet && next == "]") inSet = false; + } + escaped = !escaped && next == "\\"; + } + } + + // Used as scratch variables to communicate multiple values without + // consing up tons of objects. + var type, content; + function ret(tp, style, cont) { + type = tp; content = cont; + return style; + } + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) { + return ret("number", "number"); + } else if (ch == "." && stream.match("..")) { + return ret("spread", "meta"); + } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + return ret(ch); + } else if (ch == "=" && stream.eat(">")) { + return ret("=>", "operator"); + } else if (ch == "0" && stream.eat(/x/i)) { + stream.eatWhile(/[\da-f]/i); + return ret("number", "number"); + } else if (ch == "0" && stream.eat(/o/i)) { + stream.eatWhile(/[0-7]/i); + return ret("number", "number"); + } else if (ch == "0" && stream.eat(/b/i)) { + stream.eatWhile(/[01]/i); + return ret("number", "number"); + } else if (/\d/.test(ch)) { + stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); + return ret("number", "number"); + } else if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } else if (stream.eat("/")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } else if (expressionAllowed(stream, state, 1)) { + readRegexp(stream); + stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/); + return ret("regexp", "string-2"); + } else { + stream.eatWhile(isOperatorChar); + return ret("operator", "operator", stream.current()); + } + } else if (ch == "`") { + state.tokenize = tokenQuasi; + return tokenQuasi(stream, state); + } else if (ch == "#") { + stream.skipToEnd(); + return ret("error", "error"); + } else if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return ret("operator", "operator", stream.current()); + } else if (wordRE.test(ch)) { + stream.eatWhile(wordRE); + var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; + return (known && state.lastType != ".") ? ret(known.type, known.style, word) : + ret("variable", "variable", word); + } + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next; + if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ + state.tokenize = tokenBase; + return ret("jsonld-keyword", "meta"); + } + while ((next = stream.next()) != null) { + if (next == quote && !escaped) break; + escaped = !escaped && next == "\\"; + } + if (!escaped) state.tokenize = tokenBase; + return ret("string", "string"); + }; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return ret("comment", "comment"); + } + + function tokenQuasi(stream, state) { + var escaped = false, next; + while ((next = stream.next()) != null) { + if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { + state.tokenize = tokenBase; + break; + } + escaped = !escaped && next == "\\"; + } + return ret("quasi", "string-2", stream.current()); + } + + var brackets = "([{}])"; + // This is a crude lookahead trick to try and notice that we're + // parsing the argument patterns for a fat-arrow function before we + // actually hit the arrow token. It only works if the arrow is on + // the same line as the arguments and there's no strange noise + // (comments) in between. Fallback is to only notice when we hit the + // arrow, and not declare the arguments as locals for the arrow + // body. + function findFatArrow(stream, state) { + if (state.fatArrowAt) state.fatArrowAt = null; + var arrow = stream.string.indexOf("=>", stream.start); + if (arrow < 0) return; + + var depth = 0, sawSomething = false; + for (var pos = arrow - 1; pos >= 0; --pos) { + var ch = stream.string.charAt(pos); + var bracket = brackets.indexOf(ch); + if (bracket >= 0 && bracket < 3) { + if (!depth) { ++pos; break; } + if (--depth == 0) break; + } else if (bracket >= 3 && bracket < 6) { + ++depth; + } else if (wordRE.test(ch)) { + sawSomething = true; + } else if (/["'\/]/.test(ch)) { + return; + } else if (sawSomething && !depth) { + ++pos; + break; + } + } + if (sawSomething && !depth) state.fatArrowAt = pos; + } + + // Parser + + var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; + + function JSLexical(indented, column, type, align, prev, info) { + this.indented = indented; + this.column = column; + this.type = type; + this.prev = prev; + this.info = info; + if (align != null) this.align = align; + } + + function inScope(state, varname) { + for (var v = state.localVars; v; v = v.next) + if (v.name == varname) return true; + for (var cx = state.context; cx; cx = cx.prev) { + for (var v = cx.vars; v; v = v.next) + if (v.name == varname) return true; + } + } + + function parseJS(state, style, type, content, stream) { + var cc = state.cc; + // Communicate our context to the combinators. + // (Less wasteful than consing up a hundred closures on every call.) + cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; + + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = true; + + while(true) { + var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; + if (combinator(type, content)) { + while(cc.length && cc[cc.length - 1].lex) + cc.pop()(); + if (cx.marked) return cx.marked; + if (type == "variable" && inScope(state, content)) return "variable-2"; + return style; + } + } + } + + // Combinator utils + + var cx = {state: null, column: null, marked: null, cc: null}; + function pass() { + for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); + } + function cont() { + pass.apply(null, arguments); + return true; + } + function register(varname) { + function inList(list) { + for (var v = list; v; v = v.next) + if (v.name == varname) return true; + return false; + } + var state = cx.state; + cx.marked = "def"; + if (state.context) { + if (inList(state.localVars)) return; + state.localVars = {name: varname, next: state.localVars}; + } else { + if (inList(state.globalVars)) return; + if (parserConfig.globalVars) + state.globalVars = {name: varname, next: state.globalVars}; + } + } + + // Combinators + + var defaultVars = {name: "this", next: {name: "arguments"}}; + function pushcontext() { + cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; + cx.state.localVars = defaultVars; + } + function popcontext() { + cx.state.localVars = cx.state.context.vars; + cx.state.context = cx.state.context.prev; + } + function pushlex(type, info) { + var result = function() { + var state = cx.state, indent = state.indented; + if (state.lexical.type == "stat") indent = state.lexical.indented; + else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) + indent = outer.indented; + state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); + }; + result.lex = true; + return result; + } + function poplex() { + var state = cx.state; + if (state.lexical.prev) { + if (state.lexical.type == ")") + state.indented = state.lexical.indented; + state.lexical = state.lexical.prev; + } + } + poplex.lex = true; + + function expect(wanted) { + function exp(type) { + if (type == wanted) return cont(); + else if (wanted == ";") return pass(); + else return cont(exp); + }; + return exp; + } + + function statement(type, value) { + if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex); + if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex); + if (type == "keyword b") return cont(pushlex("form"), statement, poplex); + if (type == "{") return cont(pushlex("}"), block, poplex); + if (type == ";") return cont(); + if (type == "if") { + if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) + cx.state.cc.pop()(); + return cont(pushlex("form"), expression, statement, poplex, maybeelse); + } + if (type == "function") return cont(functiondef); + if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); + if (type == "variable") return cont(pushlex("stat"), maybelabel); + if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), + block, poplex, poplex); + if (type == "case") return cont(expression, expect(":")); + if (type == "default") return cont(expect(":")); + if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), + statement, poplex, popcontext); + if (type == "class") return cont(pushlex("form"), className, poplex); + if (type == "export") return cont(pushlex("stat"), afterExport, poplex); + if (type == "import") return cont(pushlex("stat"), afterImport, poplex); + if (type == "module") return cont(pushlex("form"), pattern, pushlex("}"), expect("{"), block, poplex, poplex) + if (type == "async") return cont(statement) + return pass(pushlex("stat"), expression, expect(";"), poplex); + } + function expression(type) { + return expressionInner(type, false); + } + function expressionNoComma(type) { + return expressionInner(type, true); + } + function expressionInner(type, noComma) { + if (cx.state.fatArrowAt == cx.stream.start) { + var body = noComma ? arrowBodyNoComma : arrowBody; + if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext); + else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); + } + + var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; + if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); + if (type == "function") return cont(functiondef, maybeop); + if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression); + if (type == "(") return cont(pushlex(")"), maybeexpression, comprehension, expect(")"), poplex, maybeop); + if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); + if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); + if (type == "{") return contCommasep(objprop, "}", null, maybeop); + if (type == "quasi") return pass(quasi, maybeop); + if (type == "new") return cont(maybeTarget(noComma)); + return cont(); + } + function maybeexpression(type) { + if (type.match(/[;\}\)\],]/)) return pass(); + return pass(expression); + } + function maybeexpressionNoComma(type) { + if (type.match(/[;\}\)\],]/)) return pass(); + return pass(expressionNoComma); + } + + function maybeoperatorComma(type, value) { + if (type == ",") return cont(expression); + return maybeoperatorNoComma(type, value, false); + } + function maybeoperatorNoComma(type, value, noComma) { + var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; + var expr = noComma == false ? expression : expressionNoComma; + if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); + if (type == "operator") { + if (/\+\+|--/.test(value)) return cont(me); + if (value == "?") return cont(expression, expect(":"), expr); + return cont(expr); + } + if (type == "quasi") { return pass(quasi, me); } + if (type == ";") return; + if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); + if (type == ".") return cont(property, me); + if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); + } + function quasi(type, value) { + if (type != "quasi") return pass(); + if (value.slice(value.length - 2) != "${") return cont(quasi); + return cont(expression, continueQuasi); + } + function continueQuasi(type) { + if (type == "}") { + cx.marked = "string-2"; + cx.state.tokenize = tokenQuasi; + return cont(quasi); + } + } + function arrowBody(type) { + findFatArrow(cx.stream, cx.state); + return pass(type == "{" ? statement : expression); + } + function arrowBodyNoComma(type) { + findFatArrow(cx.stream, cx.state); + return pass(type == "{" ? statement : expressionNoComma); + } + function maybeTarget(noComma) { + return function(type) { + if (type == ".") return cont(noComma ? targetNoComma : target); + else return pass(noComma ? expressionNoComma : expression); + }; + } + function target(_, value) { + if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); } + } + function targetNoComma(_, value) { + if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); } + } + function maybelabel(type) { + if (type == ":") return cont(poplex, statement); + return pass(maybeoperatorComma, expect(";"), poplex); + } + function property(type) { + if (type == "variable") {cx.marked = "property"; return cont();} + } + function objprop(type, value) { + if (type == "variable" || cx.style == "keyword") { + cx.marked = "property"; + if (value == "get" || value == "set") return cont(getterSetter); + return cont(afterprop); + } else if (type == "number" || type == "string") { + cx.marked = jsonldMode ? "property" : (cx.style + " property"); + return cont(afterprop); + } else if (type == "jsonld-keyword") { + return cont(afterprop); + } else if (type == "modifier") { + return cont(objprop) + } else if (type == "[") { + return cont(expression, expect("]"), afterprop); + } else if (type == "spread") { + return cont(expression); + } + } + function getterSetter(type) { + if (type != "variable") return pass(afterprop); + cx.marked = "property"; + return cont(functiondef); + } + function afterprop(type) { + if (type == ":") return cont(expressionNoComma); + if (type == "(") return pass(functiondef); + } + function commasep(what, end) { + function proceed(type, value) { + if (type == ",") { + var lex = cx.state.lexical; + if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; + return cont(what, proceed); + } + if (type == end || value == end) return cont(); + return cont(expect(end)); + } + return function(type, value) { + if (type == end || value == end) return cont(); + return pass(what, proceed); + }; + } + function contCommasep(what, end, info) { + for (var i = 3; i < arguments.length; i++) + cx.cc.push(arguments[i]); + return cont(pushlex(end, info), commasep(what, end), poplex); + } + function block(type) { + if (type == "}") return cont(); + return pass(statement, block); + } + function maybetype(type) { + if (isTS && type == ":") return cont(typeexpr); + } + function maybedefault(_, value) { + if (value == "=") return cont(expressionNoComma); + } + function typeexpr(type) { + if (type == "variable") {cx.marked = "variable-3"; return cont(afterType);} + } + function afterType(type, value) { + if (value == "<") return cont(commasep(typeexpr, ">"), afterType) + if (type == "[") return cont(expect("]"), afterType) + } + function vardef() { + return pass(pattern, maybetype, maybeAssign, vardefCont); + } + function pattern(type, value) { + if (type == "modifier") return cont(pattern) + if (type == "variable") { register(value); return cont(); } + if (type == "spread") return cont(pattern); + if (type == "[") return contCommasep(pattern, "]"); + if (type == "{") return contCommasep(proppattern, "}"); + } + function proppattern(type, value) { + if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { + register(value); + return cont(maybeAssign); + } + if (type == "variable") cx.marked = "property"; + if (type == "spread") return cont(pattern); + if (type == "}") return pass(); + return cont(expect(":"), pattern, maybeAssign); + } + function maybeAssign(_type, value) { + if (value == "=") return cont(expressionNoComma); + } + function vardefCont(type) { + if (type == ",") return cont(vardef); + } + function maybeelse(type, value) { + if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); + } + function forspec(type) { + if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex); + } + function forspec1(type) { + if (type == "var") return cont(vardef, expect(";"), forspec2); + if (type == ";") return cont(forspec2); + if (type == "variable") return cont(formaybeinof); + return pass(expression, expect(";"), forspec2); + } + function formaybeinof(_type, value) { + if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } + return cont(maybeoperatorComma, forspec2); + } + function forspec2(type, value) { + if (type == ";") return cont(forspec3); + if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } + return pass(expression, expect(";"), forspec3); + } + function forspec3(type) { + if (type != ")") cont(expression); + } + function functiondef(type, value) { + if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} + if (type == "variable") {register(value); return cont(functiondef);} + if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, maybetype, statement, popcontext); + } + function funarg(type) { + if (type == "spread") return cont(funarg); + return pass(pattern, maybetype, maybedefault); + } + function className(type, value) { + if (type == "variable") {register(value); return cont(classNameAfter);} + } + function classNameAfter(type, value) { + if (value == "extends") return cont(expression, classNameAfter); + if (type == "{") return cont(pushlex("}"), classBody, poplex); + } + function classBody(type, value) { + if (type == "variable" || cx.style == "keyword") { + if (value == "static") { + cx.marked = "keyword"; + return cont(classBody); + } + cx.marked = "property"; + if (value == "get" || value == "set") return cont(classGetterSetter, functiondef, classBody); + return cont(functiondef, classBody); + } + if (value == "*") { + cx.marked = "keyword"; + return cont(classBody); + } + if (type == ";") return cont(classBody); + if (type == "}") return cont(); + } + function classGetterSetter(type) { + if (type != "variable") return pass(); + cx.marked = "property"; + return cont(); + } + function afterExport(_type, value) { + if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } + if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } + return pass(statement); + } + function afterImport(type) { + if (type == "string") return cont(); + return pass(importSpec, maybeFrom); + } + function importSpec(type, value) { + if (type == "{") return contCommasep(importSpec, "}"); + if (type == "variable") register(value); + if (value == "*") cx.marked = "keyword"; + return cont(maybeAs); + } + function maybeAs(_type, value) { + if (value == "as") { cx.marked = "keyword"; return cont(importSpec); } + } + function maybeFrom(_type, value) { + if (value == "from") { cx.marked = "keyword"; return cont(expression); } + } + function arrayLiteral(type) { + if (type == "]") return cont(); + return pass(expressionNoComma, maybeArrayComprehension); + } + function maybeArrayComprehension(type) { + if (type == "for") return pass(comprehension, expect("]")); + if (type == ",") return cont(commasep(maybeexpressionNoComma, "]")); + return pass(commasep(expressionNoComma, "]")); + } + function comprehension(type) { + if (type == "for") return cont(forspec, comprehension); + if (type == "if") return cont(expression, comprehension); + } + + function isContinuedStatement(state, textAfter) { + return state.lastType == "operator" || state.lastType == "," || + isOperatorChar.test(textAfter.charAt(0)) || + /[,.]/.test(textAfter.charAt(0)); + } + + // Interface + + return { + startState: function(basecolumn) { + var state = { + tokenize: tokenBase, + lastType: "sof", + cc: [], + lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), + localVars: parserConfig.localVars, + context: parserConfig.localVars && {vars: parserConfig.localVars}, + indented: basecolumn || 0 + }; + if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") + state.globalVars = parserConfig.globalVars; + return state; + }, + + token: function(stream, state) { + if (stream.sol()) { + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = false; + state.indented = stream.indentation(); + findFatArrow(stream, state); + } + if (state.tokenize != tokenComment && stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (type == "comment") return style; + state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; + return parseJS(state, style, type, content, stream); + }, + + indent: function(state, textAfter) { + if (state.tokenize == tokenComment) return CodeMirror.Pass; + if (state.tokenize != tokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; + // Kludge to prevent 'maybelse' from blocking lexical scope pops + if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { + var c = state.cc[i]; + if (c == poplex) lexical = lexical.prev; + else if (c != maybeelse) break; + } + if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; + if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") + lexical = lexical.prev; + var type = lexical.type, closing = firstChar == type; + + if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0); + else if (type == "form" && firstChar == "{") return lexical.indented; + else if (type == "form") return lexical.indented + indentUnit; + else if (type == "stat") + return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); + else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) + return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); + else if (lexical.align) return lexical.column + (closing ? 0 : 1); + else return lexical.indented + (closing ? 0 : indentUnit); + }, + + electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, + blockCommentStart: jsonMode ? null : "/*", + blockCommentEnd: jsonMode ? null : "*/", + lineComment: jsonMode ? null : "//", + fold: "brace", + closeBrackets: "()[]{}''\"\"``", + + helperType: jsonMode ? "json" : "javascript", + jsonldMode: jsonldMode, + jsonMode: jsonMode, + + expressionAllowed: expressionAllowed, + skipExpression: function(state) { + var top = state.cc[state.cc.length - 1] + if (top == expression || top == expressionNoComma) state.cc.pop() + } + }; +}); + +CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); + +CodeMirror.defineMIME("text/javascript", "javascript"); +CodeMirror.defineMIME("text/ecmascript", "javascript"); +CodeMirror.defineMIME("application/javascript", "javascript"); +CodeMirror.defineMIME("application/x-javascript", "javascript"); +CodeMirror.defineMIME("application/ecmascript", "javascript"); +CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); +CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); +CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); +CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); +CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); + +}); diff --git a/js/codemirror/5.15.2/material.css b/js/codemirror/5.15.2/material.css new file mode 100644 index 0000000..91ed6ce --- /dev/null +++ b/js/codemirror/5.15.2/material.css @@ -0,0 +1,53 @@ +/* + + Name: material + Author: Michael Kaminsky (http://github.com/mkaminsky11) + + Original material color scheme by Mattia Astorino (https://github.com/equinusocio/material-theme) + +*/ + +.cm-s-material { + background-color: #263238; + color: rgba(233, 237, 237, 1); +} +.cm-s-material .CodeMirror-gutters { + background: #263238; + color: rgb(83,127,126); + border: none; +} +.cm-s-material .CodeMirror-guttermarker, .cm-s-material .CodeMirror-guttermarker-subtle, .cm-s-material .CodeMirror-linenumber { color: rgb(83,127,126); } +.cm-s-material .CodeMirror-cursor { border-left: 1px solid #f8f8f0; } +.cm-s-material div.CodeMirror-selected { background: rgba(255, 255, 255, 0.15); } +.cm-s-material.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.10); } +.cm-s-material .CodeMirror-line::selection, .cm-s-material .CodeMirror-line > span::selection, .cm-s-material .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); } +.cm-s-material .CodeMirror-line::-moz-selection, .cm-s-material .CodeMirror-line > span::-moz-selection, .cm-s-material .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); } + +.cm-s-material .CodeMirror-activeline-background { background: rgba(0, 0, 0, 0); } +.cm-s-material .cm-keyword { color: rgba(199, 146, 234, 1); } +.cm-s-material .cm-operator { color: rgba(233, 237, 237, 1); } +.cm-s-material .cm-variable-2 { color: #80CBC4; } +.cm-s-material .cm-variable-3 { color: #82B1FF; } +.cm-s-material .cm-builtin { color: #DECB6B; } +.cm-s-material .cm-atom { color: #F77669; } +.cm-s-material .cm-number { color: #F77669; } +.cm-s-material .cm-def { color: rgba(233, 237, 237, 1); } +.cm-s-material .cm-string { color: #C3E88D; } +.cm-s-material .cm-string-2 { color: #80CBC4; } +.cm-s-material .cm-comment { color: #546E7A; } +.cm-s-material .cm-variable { color: #82B1FF; } +.cm-s-material .cm-tag { color: #80CBC4; } +.cm-s-material .cm-meta { color: #80CBC4; } +.cm-s-material .cm-attribute { color: #FFCB6B; } +.cm-s-material .cm-property { color: #80CBAE; } +.cm-s-material .cm-qualifier { color: #DECB6B; } +.cm-s-material .cm-variable-3 { color: #DECB6B; } +.cm-s-material .cm-tag { color: rgba(255, 83, 112, 1); } +.cm-s-material .cm-error { + color: rgba(255, 255, 255, 1.0); + background-color: #EC5F67; +} +.cm-s-material .CodeMirror-matchingbracket { + text-decoration: underline; + color: white !important; +} diff --git a/js/codemirror/5.15.2/monokai.css b/js/codemirror/5.15.2/monokai.css new file mode 100644 index 0000000..7c8a4c5 --- /dev/null +++ b/js/codemirror/5.15.2/monokai.css @@ -0,0 +1,36 @@ +/* Based on Sublime Text's Monokai theme */ + +.cm-s-monokai.CodeMirror { background: #272822; color: #f8f8f2; } +.cm-s-monokai div.CodeMirror-selected { background: #49483E; } +.cm-s-monokai .CodeMirror-line::selection, .cm-s-monokai .CodeMirror-line > span::selection, .cm-s-monokai .CodeMirror-line > span > span::selection { background: rgba(73, 72, 62, .99); } +.cm-s-monokai .CodeMirror-line::-moz-selection, .cm-s-monokai .CodeMirror-line > span::-moz-selection, .cm-s-monokai .CodeMirror-line > span > span::-moz-selection { background: rgba(73, 72, 62, .99); } +.cm-s-monokai .CodeMirror-gutters { background: #272822; border-right: 0px; } +.cm-s-monokai .CodeMirror-guttermarker { color: white; } +.cm-s-monokai .CodeMirror-guttermarker-subtle { color: #d0d0d0; } +.cm-s-monokai .CodeMirror-linenumber { color: #d0d0d0; } +.cm-s-monokai .CodeMirror-cursor { border-left: 1px solid #f8f8f0; } + +.cm-s-monokai span.cm-comment { color: #75715e; } +.cm-s-monokai span.cm-atom { color: #ae81ff; } +.cm-s-monokai span.cm-number { color: #ae81ff; } + +.cm-s-monokai span.cm-property, .cm-s-monokai span.cm-attribute { color: #a6e22e; } +.cm-s-monokai span.cm-keyword { color: #f92672; } +.cm-s-monokai span.cm-builtin { color: #66d9ef; } +.cm-s-monokai span.cm-string { color: #e6db74; } + +.cm-s-monokai span.cm-variable { color: #f8f8f2; } +.cm-s-monokai span.cm-variable-2 { color: #9effff; } +.cm-s-monokai span.cm-variable-3 { color: #66d9ef; } +.cm-s-monokai span.cm-def { color: #fd971f; } +.cm-s-monokai span.cm-bracket { color: #f8f8f2; } +.cm-s-monokai span.cm-tag { color: #f92672; } +.cm-s-monokai span.cm-header { color: #ae81ff; } +.cm-s-monokai span.cm-link { color: #ae81ff; } +.cm-s-monokai span.cm-error { background: #f92672; color: #f8f8f0; } + +.cm-s-monokai .CodeMirror-activeline-background { background: #373831; } +.cm-s-monokai .CodeMirror-matchingbracket { + text-decoration: underline; + color: white !important; +} diff --git a/js/codemirror/5.15.2/python.js b/js/codemirror/5.15.2/python.js new file mode 100644 index 0000000..ec662b1 --- /dev/null +++ b/js/codemirror/5.15.2/python.js @@ -0,0 +1,340 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + function wordRegexp(words) { + return new RegExp("^((" + words.join(")|(") + "))\\b"); + } + + var wordOperators = wordRegexp(["and", "or", "not", "is"]); + var commonKeywords = ["as", "assert", "break", "class", "continue", + "def", "del", "elif", "else", "except", "finally", + "for", "from", "global", "if", "import", + "lambda", "pass", "raise", "return", + "try", "while", "with", "yield", "in"]; + var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr", + "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod", + "enumerate", "eval", "filter", "float", "format", "frozenset", + "getattr", "globals", "hasattr", "hash", "help", "hex", "id", + "input", "int", "isinstance", "issubclass", "iter", "len", + "list", "locals", "map", "max", "memoryview", "min", "next", + "object", "oct", "open", "ord", "pow", "property", "range", + "repr", "reversed", "round", "set", "setattr", "slice", + "sorted", "staticmethod", "str", "sum", "super", "tuple", + "type", "vars", "zip", "__import__", "NotImplemented", + "Ellipsis", "__debug__"]; + CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins)); + + function top(state) { + return state.scopes[state.scopes.length - 1]; + } + + CodeMirror.defineMode("python", function(conf, parserConf) { + var ERRORCLASS = "error"; + + var singleDelimiters = parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.]/; + var doubleOperators = parserConf.doubleOperators || /^([!<>]==|<>|<<|>>|\/\/|\*\*)/; + var doubleDelimiters = parserConf.doubleDelimiters || /^(\+=|\-=|\*=|%=|\/=|&=|\|=|\^=)/; + var tripleDelimiters = parserConf.tripleDelimiters || /^(\/\/=|>>=|<<=|\*\*=)/; + + var hangingIndent = parserConf.hangingIndent || conf.indentUnit; + + var myKeywords = commonKeywords, myBuiltins = commonBuiltins; + if (parserConf.extra_keywords != undefined) + myKeywords = myKeywords.concat(parserConf.extra_keywords); + + if (parserConf.extra_builtins != undefined) + myBuiltins = myBuiltins.concat(parserConf.extra_builtins); + + var py3 = parserConf.version && parseInt(parserConf.version, 10) == 3 + if (py3) { + // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator + var singleOperators = parserConf.singleOperators || /^[\+\-\*\/%&|\^~<>!@]/; + var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/; + myKeywords = myKeywords.concat(["nonlocal", "False", "True", "None", "async", "await"]); + myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]); + var stringPrefixes = new RegExp("^(([rbuf]|(br))?('{3}|\"{3}|['\"]))", "i"); + } else { + var singleOperators = parserConf.singleOperators || /^[\+\-\*\/%&|\^~<>!]/; + var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/; + myKeywords = myKeywords.concat(["exec", "print"]); + myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile", + "file", "intern", "long", "raw_input", "reduce", "reload", + "unichr", "unicode", "xrange", "False", "True", "None"]); + var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i"); + } + var keywords = wordRegexp(myKeywords); + var builtins = wordRegexp(myBuiltins); + + // tokenizers + function tokenBase(stream, state) { + if (stream.sol()) state.indent = stream.indentation() + // Handle scope changes + if (stream.sol() && top(state).type == "py") { + var scopeOffset = top(state).offset; + if (stream.eatSpace()) { + var lineOffset = stream.indentation(); + if (lineOffset > scopeOffset) + pushPyScope(state); + else if (lineOffset < scopeOffset && dedent(stream, state)) + state.errorToken = true; + return null; + } else { + var style = tokenBaseInner(stream, state); + if (scopeOffset > 0 && dedent(stream, state)) + style += " " + ERRORCLASS; + return style; + } + } + return tokenBaseInner(stream, state); + } + + function tokenBaseInner(stream, state) { + if (stream.eatSpace()) return null; + + var ch = stream.peek(); + + // Handle Comments + if (ch == "#") { + stream.skipToEnd(); + return "comment"; + } + + // Handle Number Literals + if (stream.match(/^[0-9\.]/, false)) { + var floatLiteral = false; + // Floats + if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; } + if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; } + if (stream.match(/^\.\d+/)) { floatLiteral = true; } + if (floatLiteral) { + // Float literals may be "imaginary" + stream.eat(/J/i); + return "number"; + } + // Integers + var intLiteral = false; + // Hex + if (stream.match(/^0x[0-9a-f]+/i)) intLiteral = true; + // Binary + if (stream.match(/^0b[01]+/i)) intLiteral = true; + // Octal + if (stream.match(/^0o[0-7]+/i)) intLiteral = true; + // Decimal + if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) { + // Decimal literals may be "imaginary" + stream.eat(/J/i); + // TODO - Can you have imaginary longs? + intLiteral = true; + } + // Zero by itself with no other piece of number. + if (stream.match(/^0(?![\dx])/i)) intLiteral = true; + if (intLiteral) { + // Integer literals may be "long" + stream.eat(/L/i); + return "number"; + } + } + + // Handle Strings + if (stream.match(stringPrefixes)) { + state.tokenize = tokenStringFactory(stream.current()); + return state.tokenize(stream, state); + } + + // Handle operators and Delimiters + if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) + return "punctuation"; + + if (stream.match(doubleOperators) || stream.match(singleOperators)) + return "operator"; + + if (stream.match(singleDelimiters)) + return "punctuation"; + + if (state.lastToken == "." && stream.match(identifiers)) + return "property"; + + if (stream.match(keywords) || stream.match(wordOperators)) + return "keyword"; + + if (stream.match(builtins)) + return "builtin"; + + if (stream.match(/^(self|cls)\b/)) + return "variable-2"; + + if (stream.match(identifiers)) { + if (state.lastToken == "def" || state.lastToken == "class") + return "def"; + return "variable"; + } + + // Handle non-detected items + stream.next(); + return ERRORCLASS; + } + + function tokenStringFactory(delimiter) { + while ("rub".indexOf(delimiter.charAt(0).toLowerCase()) >= 0) + delimiter = delimiter.substr(1); + + var singleline = delimiter.length == 1; + var OUTCLASS = "string"; + + function tokenString(stream, state) { + while (!stream.eol()) { + stream.eatWhile(/[^'"\\]/); + if (stream.eat("\\")) { + stream.next(); + if (singleline && stream.eol()) + return OUTCLASS; + } else if (stream.match(delimiter)) { + state.tokenize = tokenBase; + return OUTCLASS; + } else { + stream.eat(/['"]/); + } + } + if (singleline) { + if (parserConf.singleLineStringErrors) + return ERRORCLASS; + else + state.tokenize = tokenBase; + } + return OUTCLASS; + } + tokenString.isString = true; + return tokenString; + } + + function pushPyScope(state) { + while (top(state).type != "py") state.scopes.pop() + state.scopes.push({offset: top(state).offset + conf.indentUnit, + type: "py", + align: null}) + } + + function pushBracketScope(stream, state, type) { + var align = stream.match(/^([\s\[\{\(]|#.*)*$/, false) ? null : stream.column() + 1 + state.scopes.push({offset: state.indent + hangingIndent, + type: type, + align: align}) + } + + function dedent(stream, state) { + var indented = stream.indentation(); + while (top(state).offset > indented) { + if (top(state).type != "py") return true; + state.scopes.pop(); + } + return top(state).offset != indented; + } + + function tokenLexer(stream, state) { + if (stream.sol()) state.beginningOfLine = true; + + var style = state.tokenize(stream, state); + var current = stream.current(); + + // Handle decorators + if (state.beginningOfLine && current == "@") + return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS; + + if (/\S/.test(current)) state.beginningOfLine = false; + + if ((style == "variable" || style == "builtin") + && state.lastToken == "meta") + style = "meta"; + + // Handle scope changes. + if (current == "pass" || current == "return") + state.dedent += 1; + + if (current == "lambda") state.lambda = true; + if (current == ":" && !state.lambda && top(state).type == "py") + pushPyScope(state); + + var delimiter_index = current.length == 1 ? "[({".indexOf(current) : -1; + if (delimiter_index != -1) + pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1)); + + delimiter_index = "])}".indexOf(current); + if (delimiter_index != -1) { + if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent + else return ERRORCLASS; + } + if (state.dedent > 0 && stream.eol() && top(state).type == "py") { + if (state.scopes.length > 1) state.scopes.pop(); + state.dedent -= 1; + } + + return style; + } + + var external = { + startState: function(basecolumn) { + return { + tokenize: tokenBase, + scopes: [{offset: basecolumn || 0, type: "py", align: null}], + indent: basecolumn || 0, + lastToken: null, + lambda: false, + dedent: 0 + }; + }, + + token: function(stream, state) { + var addErr = state.errorToken; + if (addErr) state.errorToken = false; + var style = tokenLexer(stream, state); + + if (style && style != "comment") + state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style; + if (style == "punctuation") style = null; + + if (stream.eol() && state.lambda) + state.lambda = false; + return addErr ? style + " " + ERRORCLASS : style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase) + return state.tokenize.isString ? CodeMirror.Pass : 0; + + var scope = top(state), closing = scope.type == textAfter.charAt(0) + if (scope.align != null) + return scope.align - (closing ? 1 : 0) + else + return scope.offset - (closing ? hangingIndent : 0) + }, + + electricInput: /^\s*[\}\]\)]$/, + closeBrackets: {triples: "'\""}, + lineComment: "#", + fold: "indent" + }; + return external; + }); + + CodeMirror.defineMIME("text/x-python", "python"); + + var words = function(str) { return str.split(" "); }; + + CodeMirror.defineMIME("text/x-cython", { + name: "python", + extra_keywords: words("by cdef cimport cpdef ctypedef enum except"+ + "extern gil include nogil property public"+ + "readonly struct union DEF IF ELIF ELSE") + }); + +}); diff --git a/js/codemirror/5.15.2/xml.js b/js/codemirror/5.15.2/xml.js new file mode 100644 index 0000000..f987a3a --- /dev/null +++ b/js/codemirror/5.15.2/xml.js @@ -0,0 +1,394 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +var htmlConfig = { + autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true, + 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true, + 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, + 'track': true, 'wbr': true, 'menuitem': true}, + implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true, + 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true, + 'th': true, 'tr': true}, + contextGrabbers: { + 'dd': {'dd': true, 'dt': true}, + 'dt': {'dd': true, 'dt': true}, + 'li': {'li': true}, + 'option': {'option': true, 'optgroup': true}, + 'optgroup': {'optgroup': true}, + 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true, + 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true, + 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true, + 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true, + 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true}, + 'rp': {'rp': true, 'rt': true}, + 'rt': {'rp': true, 'rt': true}, + 'tbody': {'tbody': true, 'tfoot': true}, + 'td': {'td': true, 'th': true}, + 'tfoot': {'tbody': true}, + 'th': {'td': true, 'th': true}, + 'thead': {'tbody': true, 'tfoot': true}, + 'tr': {'tr': true} + }, + doNotIndent: {"pre": true}, + allowUnquoted: true, + allowMissing: true, + caseFold: true +} + +var xmlConfig = { + autoSelfClosers: {}, + implicitlyClosed: {}, + contextGrabbers: {}, + doNotIndent: {}, + allowUnquoted: false, + allowMissing: false, + caseFold: false +} + +CodeMirror.defineMode("xml", function(editorConf, config_) { + var indentUnit = editorConf.indentUnit + var config = {} + var defaults = config_.htmlMode ? htmlConfig : xmlConfig + for (var prop in defaults) config[prop] = defaults[prop] + for (var prop in config_) config[prop] = config_[prop] + + // Return variables for tokenizers + var type, setStyle; + + function inText(stream, state) { + function chain(parser) { + state.tokenize = parser; + return parser(stream, state); + } + + var ch = stream.next(); + if (ch == "<") { + if (stream.eat("!")) { + if (stream.eat("[")) { + if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>")); + else return null; + } else if (stream.match("--")) { + return chain(inBlock("comment", "-->")); + } else if (stream.match("DOCTYPE", true, true)) { + stream.eatWhile(/[\w\._\-]/); + return chain(doctype(1)); + } else { + return null; + } + } else if (stream.eat("?")) { + stream.eatWhile(/[\w\._\-]/); + state.tokenize = inBlock("meta", "?>"); + return "meta"; + } else { + type = stream.eat("/") ? "closeTag" : "openTag"; + state.tokenize = inTag; + return "tag bracket"; + } + } else if (ch == "&") { + var ok; + if (stream.eat("#")) { + if (stream.eat("x")) { + ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); + } else { + ok = stream.eatWhile(/[\d]/) && stream.eat(";"); + } + } else { + ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); + } + return ok ? "atom" : "error"; + } else { + stream.eatWhile(/[^&<]/); + return null; + } + } + inText.isInText = true; + + function inTag(stream, state) { + var ch = stream.next(); + if (ch == ">" || (ch == "/" && stream.eat(">"))) { + state.tokenize = inText; + type = ch == ">" ? "endTag" : "selfcloseTag"; + return "tag bracket"; + } else if (ch == "=") { + type = "equals"; + return null; + } else if (ch == "<") { + state.tokenize = inText; + state.state = baseState; + state.tagName = state.tagStart = null; + var next = state.tokenize(stream, state); + return next ? next + " tag error" : "tag error"; + } else if (/[\'\"]/.test(ch)) { + state.tokenize = inAttribute(ch); + state.stringStartCol = stream.column(); + return state.tokenize(stream, state); + } else { + stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/); + return "word"; + } + } + + function inAttribute(quote) { + var closure = function(stream, state) { + while (!stream.eol()) { + if (stream.next() == quote) { + state.tokenize = inTag; + break; + } + } + return "string"; + }; + closure.isInAttribute = true; + return closure; + } + + function inBlock(style, terminator) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.match(terminator)) { + state.tokenize = inText; + break; + } + stream.next(); + } + return style; + }; + } + function doctype(depth) { + return function(stream, state) { + var ch; + while ((ch = stream.next()) != null) { + if (ch == "<") { + state.tokenize = doctype(depth + 1); + return state.tokenize(stream, state); + } else if (ch == ">") { + if (depth == 1) { + state.tokenize = inText; + break; + } else { + state.tokenize = doctype(depth - 1); + return state.tokenize(stream, state); + } + } + } + return "meta"; + }; + } + + function Context(state, tagName, startOfLine) { + this.prev = state.context; + this.tagName = tagName; + this.indent = state.indented; + this.startOfLine = startOfLine; + if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent)) + this.noIndent = true; + } + function popContext(state) { + if (state.context) state.context = state.context.prev; + } + function maybePopContext(state, nextTagName) { + var parentTagName; + while (true) { + if (!state.context) { + return; + } + parentTagName = state.context.tagName; + if (!config.contextGrabbers.hasOwnProperty(parentTagName) || + !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { + return; + } + popContext(state); + } + } + + function baseState(type, stream, state) { + if (type == "openTag") { + state.tagStart = stream.column(); + return tagNameState; + } else if (type == "closeTag") { + return closeTagNameState; + } else { + return baseState; + } + } + function tagNameState(type, stream, state) { + if (type == "word") { + state.tagName = stream.current(); + setStyle = "tag"; + return attrState; + } else { + setStyle = "error"; + return tagNameState; + } + } + function closeTagNameState(type, stream, state) { + if (type == "word") { + var tagName = stream.current(); + if (state.context && state.context.tagName != tagName && + config.implicitlyClosed.hasOwnProperty(state.context.tagName)) + popContext(state); + if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) { + setStyle = "tag"; + return closeState; + } else { + setStyle = "tag error"; + return closeStateErr; + } + } else { + setStyle = "error"; + return closeStateErr; + } + } + + function closeState(type, _stream, state) { + if (type != "endTag") { + setStyle = "error"; + return closeState; + } + popContext(state); + return baseState; + } + function closeStateErr(type, stream, state) { + setStyle = "error"; + return closeState(type, stream, state); + } + + function attrState(type, _stream, state) { + if (type == "word") { + setStyle = "attribute"; + return attrEqState; + } else if (type == "endTag" || type == "selfcloseTag") { + var tagName = state.tagName, tagStart = state.tagStart; + state.tagName = state.tagStart = null; + if (type == "selfcloseTag" || + config.autoSelfClosers.hasOwnProperty(tagName)) { + maybePopContext(state, tagName); + } else { + maybePopContext(state, tagName); + state.context = new Context(state, tagName, tagStart == state.indented); + } + return baseState; + } + setStyle = "error"; + return attrState; + } + function attrEqState(type, stream, state) { + if (type == "equals") return attrValueState; + if (!config.allowMissing) setStyle = "error"; + return attrState(type, stream, state); + } + function attrValueState(type, stream, state) { + if (type == "string") return attrContinuedState; + if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;} + setStyle = "error"; + return attrState(type, stream, state); + } + function attrContinuedState(type, stream, state) { + if (type == "string") return attrContinuedState; + return attrState(type, stream, state); + } + + return { + startState: function(baseIndent) { + var state = {tokenize: inText, + state: baseState, + indented: baseIndent || 0, + tagName: null, tagStart: null, + context: null} + if (baseIndent != null) state.baseIndent = baseIndent + return state + }, + + token: function(stream, state) { + if (!state.tagName && stream.sol()) + state.indented = stream.indentation(); + + if (stream.eatSpace()) return null; + type = null; + var style = state.tokenize(stream, state); + if ((style || type) && style != "comment") { + setStyle = null; + state.state = state.state(type || style, stream, state); + if (setStyle) + style = setStyle == "error" ? style + " error" : setStyle; + } + return style; + }, + + indent: function(state, textAfter, fullLine) { + var context = state.context; + // Indent multi-line strings (e.g. css). + if (state.tokenize.isInAttribute) { + if (state.tagStart == state.indented) + return state.stringStartCol + 1; + else + return state.indented + indentUnit; + } + if (context && context.noIndent) return CodeMirror.Pass; + if (state.tokenize != inTag && state.tokenize != inText) + return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; + // Indent the starts of attribute names. + if (state.tagName) { + if (config.multilineTagIndentPastTag !== false) + return state.tagStart + state.tagName.length + 2; + else + return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1); + } + if (config.alignCDATA && /$/, + blockCommentStart: "", + + configuration: config.htmlMode ? "html" : "xml", + helperType: config.htmlMode ? "html" : "xml", + + skipAttribute: function(state) { + if (state.state == attrValueState) + state.state = attrState + } + }; +}); + +CodeMirror.defineMIME("text/xml", "xml"); +CodeMirror.defineMIME("application/xml", "xml"); +if (!CodeMirror.mimeModes.hasOwnProperty("text/html")) + CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true}); + +}); diff --git a/js/codemirror/5.40.2/codemirror.css b/js/codemirror/5.40.2/codemirror.css new file mode 100644 index 0000000..c7a8ae7 --- /dev/null +++ b/js/codemirror/5.40.2/codemirror.css @@ -0,0 +1,346 @@ +/* BASICS */ + +.CodeMirror { + /* Set height, width, borders, and global font properties here */ + font-family: monospace; + height: 300px; + color: black; + direction: ltr; +} + +/* PADDING */ + +.CodeMirror-lines { + padding: 4px 0; /* Vertical padding around content */ +} +.CodeMirror pre { + padding: 0 4px; /* Horizontal padding of content */ +} + +.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + background-color: white; /* The little square between H and V scrollbars */ +} + +/* GUTTER */ + +.CodeMirror-gutters { + border-right: 1px solid #ddd; + background-color: #f7f7f7; + white-space: nowrap; +} +.CodeMirror-linenumbers {} +.CodeMirror-linenumber { + padding: 0 3px 0 5px; + min-width: 20px; + text-align: right; + color: #999; + white-space: nowrap; +} + +.CodeMirror-guttermarker { color: black; } +.CodeMirror-guttermarker-subtle { color: #999; } + +/* CURSOR */ + +.CodeMirror-cursor { + border-left: 1px solid black; + border-right: none; + width: 0; +} +/* Shown when moving in bi-directional text */ +.CodeMirror div.CodeMirror-secondarycursor { + border-left: 1px solid silver; +} +.cm-fat-cursor .CodeMirror-cursor { + width: auto; + border: 0 !important; + background: #7e7; +} +.cm-fat-cursor div.CodeMirror-cursors { + z-index: 1; +} +.cm-fat-cursor-mark { + background-color: rgba(20, 255, 20, 0.5); + -webkit-animation: blink 1.06s steps(1) infinite; + -moz-animation: blink 1.06s steps(1) infinite; + animation: blink 1.06s steps(1) infinite; +} +.cm-animate-fat-cursor { + width: auto; + border: 0; + -webkit-animation: blink 1.06s steps(1) infinite; + -moz-animation: blink 1.06s steps(1) infinite; + animation: blink 1.06s steps(1) infinite; + background-color: #7e7; +} +@-moz-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@-webkit-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} + +/* Can style cursor different in overwrite (non-insert) mode */ +.CodeMirror-overwrite .CodeMirror-cursor {} + +.cm-tab { display: inline-block; text-decoration: inherit; } + +.CodeMirror-rulers { + position: absolute; + left: 0; right: 0; top: -50px; bottom: -20px; + overflow: hidden; +} +.CodeMirror-ruler { + border-left: 1px solid #ccc; + top: 0; bottom: 0; + position: absolute; +} + +/* DEFAULT THEME */ + +.cm-s-default .cm-header {color: blue;} +.cm-s-default .cm-quote {color: #090;} +.cm-negative {color: #d44;} +.cm-positive {color: #292;} +.cm-header, .cm-strong {font-weight: bold;} +.cm-em {font-style: italic;} +.cm-link {text-decoration: underline;} +.cm-strikethrough {text-decoration: line-through;} + +.cm-s-default .cm-keyword {color: #708;} +.cm-s-default .cm-atom {color: #219;} +.cm-s-default .cm-number {color: #164;} +.cm-s-default .cm-def {color: #00f;} +.cm-s-default .cm-variable, +.cm-s-default .cm-punctuation, +.cm-s-default .cm-property, +.cm-s-default .cm-operator {} +.cm-s-default .cm-variable-2 {color: #05a;} +.cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;} +.cm-s-default .cm-comment {color: #a50;} +.cm-s-default .cm-string {color: #a11;} +.cm-s-default .cm-string-2 {color: #f50;} +.cm-s-default .cm-meta {color: #555;} +.cm-s-default .cm-qualifier {color: #555;} +.cm-s-default .cm-builtin {color: #30a;} +.cm-s-default .cm-bracket {color: #997;} +.cm-s-default .cm-tag {color: #170;} +.cm-s-default .cm-attribute {color: #00c;} +.cm-s-default .cm-hr {color: #999;} +.cm-s-default .cm-link {color: #00c;} + +.cm-s-default .cm-error {color: #f00;} +.cm-invalidchar {color: #f00;} + +.CodeMirror-composing { border-bottom: 2px solid; } + +/* Default styles for common addons */ + +div.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;} +div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;} +.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } +.CodeMirror-activeline-background {background: #e8f2ff;} + +/* STOP */ + +/* The rest of this file contains styles related to the mechanics of + the editor. You probably shouldn't touch them. */ + +.CodeMirror { + position: relative; + overflow: hidden; + background: white; +} + +.CodeMirror-scroll { + overflow: scroll !important; /* Things will break if this is overridden */ + /* 30px is the magic margin used to hide the element's real scrollbars */ + /* See overflow: hidden in .CodeMirror */ + margin-bottom: -30px; margin-right: -30px; + padding-bottom: 30px; + height: 100%; + outline: none; /* Prevent dragging from highlighting the element */ + position: relative; +} +.CodeMirror-sizer { + position: relative; + border-right: 30px solid transparent; +} + +/* The fake, visible scrollbars. Used to force redraw during scrolling + before actual scrolling happens, thus preventing shaking and + flickering artifacts. */ +.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + position: absolute; + z-index: 6; + display: none; +} +.CodeMirror-vscrollbar { + right: 0; top: 0; + overflow-x: hidden; + overflow-y: scroll; +} +.CodeMirror-hscrollbar { + bottom: 0; left: 0; + overflow-y: hidden; + overflow-x: scroll; +} +.CodeMirror-scrollbar-filler { + right: 0; bottom: 0; +} +.CodeMirror-gutter-filler { + left: 0; bottom: 0; +} + +.CodeMirror-gutters { + position: absolute; left: 0; top: 0; + min-height: 100%; + z-index: 3; +} +.CodeMirror-gutter { + white-space: normal; + height: 100%; + display: inline-block; + vertical-align: top; + margin-bottom: -30px; +} +.CodeMirror-gutter-wrapper { + position: absolute; + z-index: 4; + background: none !important; + border: none !important; +} +.CodeMirror-gutter-background { + position: absolute; + top: 0; bottom: 0; + z-index: 4; +} +.CodeMirror-gutter-elt { + position: absolute; + cursor: default; + z-index: 4; +} +.CodeMirror-gutter-wrapper ::selection { background-color: transparent } +.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent } + +.CodeMirror-lines { + cursor: text; + min-height: 1px; /* prevents collapsing before first draw */ +} +.CodeMirror pre { + /* Reset some styles that the rest of the page might have set */ + -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; + border-width: 0; + background: transparent; + font-family: inherit; + font-size: inherit; + margin: 0; + white-space: pre; + word-wrap: normal; + line-height: inherit; + color: inherit; + z-index: 2; + position: relative; + overflow: visible; + -webkit-tap-highlight-color: transparent; + -webkit-font-variant-ligatures: contextual; + font-variant-ligatures: contextual; +} +.CodeMirror-wrap pre { + word-wrap: break-word; + white-space: pre-wrap; + word-break: normal; +} + +.CodeMirror-linebackground { + position: absolute; + left: 0; right: 0; top: 0; bottom: 0; + z-index: 0; +} + +.CodeMirror-linewidget { + position: relative; + z-index: 2; + padding: 0.1px; /* Force widget margins to stay inside of the container */ +} + +.CodeMirror-widget {} + +.CodeMirror-rtl pre { direction: rtl; } + +.CodeMirror-code { + outline: none; +} + +/* Force content-box sizing for the elements where we expect it */ +.CodeMirror-scroll, +.CodeMirror-sizer, +.CodeMirror-gutter, +.CodeMirror-gutters, +.CodeMirror-linenumber { + -moz-box-sizing: content-box; + box-sizing: content-box; +} + +.CodeMirror-measure { + position: absolute; + width: 100%; + height: 0; + overflow: hidden; + visibility: hidden; +} + +.CodeMirror-cursor { + position: absolute; + pointer-events: none; +} +.CodeMirror-measure pre { position: static; } + +div.CodeMirror-cursors { + visibility: hidden; + position: relative; + z-index: 3; +} +div.CodeMirror-dragcursors { + visibility: visible; +} + +.CodeMirror-focused div.CodeMirror-cursors { + visibility: visible; +} + +.CodeMirror-selected { background: #d9d9d9; } +.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } +.CodeMirror-crosshair { cursor: crosshair; } +.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; } +.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; } + +.cm-searching { + background-color: #ffa; + background-color: rgba(255, 255, 0, .4); +} + +/* Used to force a border model for a node */ +.cm-force-border { padding-right: .1px; } + +@media print { + /* Hide the cursor when printing */ + .CodeMirror div.CodeMirror-cursors { + visibility: hidden; + } +} + +/* See issue #2901 */ +.cm-tab-wrap-hack:after { content: ''; } + +/* Help users use markselection to safely style text background */ +span.CodeMirror-selectedtext { background: none; } diff --git a/js/codemirror/5.40.2/codemirror.js b/js/codemirror/5.40.2/codemirror.js new file mode 100644 index 0000000..8b52f51 --- /dev/null +++ b/js/codemirror/5.40.2/codemirror.js @@ -0,0 +1,9693 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +// This is CodeMirror (https://codemirror.net), a code editor +// implemented in JavaScript on top of the browser's DOM. +// +// You can find some technical background for some of the code below +// at http://marijnhaverbeke.nl/blog/#cm-internals . + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.CodeMirror = factory()); +}(this, (function () { 'use strict'; + +// Kludges for bugs and behavior differences that can't be feature +// detected are enabled based on userAgent etc sniffing. +var userAgent = navigator.userAgent +var platform = navigator.platform + +var gecko = /gecko\/\d/i.test(userAgent) +var ie_upto10 = /MSIE \d/.test(userAgent) +var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent) +var edge = /Edge\/(\d+)/.exec(userAgent) +var ie = ie_upto10 || ie_11up || edge +var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]) +var webkit = !edge && /WebKit\//.test(userAgent) +var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent) +var chrome = !edge && /Chrome\//.test(userAgent) +var presto = /Opera\//.test(userAgent) +var safari = /Apple Computer/.test(navigator.vendor) +var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent) +var phantom = /PhantomJS/.test(userAgent) + +var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent) +var android = /Android/.test(userAgent) +// This is woefully incomplete. Suggestions for alternative methods welcome. +var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent) +var mac = ios || /Mac/.test(platform) +var chromeOS = /\bCrOS\b/.test(userAgent) +var windows = /win/i.test(platform) + +var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/) +if (presto_version) { presto_version = Number(presto_version[1]) } +if (presto_version && presto_version >= 15) { presto = false; webkit = true } +// Some browsers use the wrong event properties to signal cmd/ctrl on OS X +var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)) +var captureRightClick = gecko || (ie && ie_version >= 9) + +function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } + +var rmClass = function(node, cls) { + var current = node.className + var match = classTest(cls).exec(current) + if (match) { + var after = current.slice(match.index + match[0].length) + node.className = current.slice(0, match.index) + (after ? match[1] + after : "") + } +} + +function removeChildren(e) { + for (var count = e.childNodes.length; count > 0; --count) + { e.removeChild(e.firstChild) } + return e +} + +function removeChildrenAndAdd(parent, e) { + return removeChildren(parent).appendChild(e) +} + +function elt(tag, content, className, style) { + var e = document.createElement(tag) + if (className) { e.className = className } + if (style) { e.style.cssText = style } + if (typeof content == "string") { e.appendChild(document.createTextNode(content)) } + else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]) } } + return e +} +// wrapper for elt, which removes the elt from the accessibility tree +function eltP(tag, content, className, style) { + var e = elt(tag, content, className, style) + e.setAttribute("role", "presentation") + return e +} + +var range +if (document.createRange) { range = function(node, start, end, endNode) { + var r = document.createRange() + r.setEnd(endNode || node, end) + r.setStart(node, start) + return r +} } +else { range = function(node, start, end) { + var r = document.body.createTextRange() + try { r.moveToElementText(node.parentNode) } + catch(e) { return r } + r.collapse(true) + r.moveEnd("character", end) + r.moveStart("character", start) + return r +} } + +function contains(parent, child) { + if (child.nodeType == 3) // Android browser always returns false when child is a textnode + { child = child.parentNode } + if (parent.contains) + { return parent.contains(child) } + do { + if (child.nodeType == 11) { child = child.host } + if (child == parent) { return true } + } while (child = child.parentNode) +} + +function activeElt() { + // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. + // IE < 10 will throw when accessed while the page is loading or in an iframe. + // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. + var activeElement + try { + activeElement = document.activeElement + } catch(e) { + activeElement = document.body || null + } + while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) + { activeElement = activeElement.shadowRoot.activeElement } + return activeElement +} + +function addClass(node, cls) { + var current = node.className + if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls } +} +function joinClasses(a, b) { + var as = a.split(" ") + for (var i = 0; i < as.length; i++) + { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i] } } + return b +} + +var selectInput = function(node) { node.select() } +if (ios) // Mobile Safari apparently has a bug where select() is broken. + { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length } } +else if (ie) // Suppress mysterious IE10 errors + { selectInput = function(node) { try { node.select() } catch(_e) {} } } + +function bind(f) { + var args = Array.prototype.slice.call(arguments, 1) + return function(){return f.apply(null, args)} +} + +function copyObj(obj, target, overwrite) { + if (!target) { target = {} } + for (var prop in obj) + { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) + { target[prop] = obj[prop] } } + return target +} + +// Counts the column offset in a string, taking tabs into account. +// Used mostly to find indentation. +function countColumn(string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/) + if (end == -1) { end = string.length } + } + for (var i = startIndex || 0, n = startValue || 0;;) { + var nextTab = string.indexOf("\t", i) + if (nextTab < 0 || nextTab >= end) + { return n + (end - i) } + n += nextTab - i + n += tabSize - (n % tabSize) + i = nextTab + 1 + } +} + +var Delayed = function() {this.id = null}; +Delayed.prototype.set = function (ms, f) { + clearTimeout(this.id) + this.id = setTimeout(f, ms) +}; + +function indexOf(array, elt) { + for (var i = 0; i < array.length; ++i) + { if (array[i] == elt) { return i } } + return -1 +} + +// Number of pixels added to scroller and sizer to hide scrollbar +var scrollerGap = 30 + +// Returned or thrown by various protocols to signal 'I'm not +// handling this'. +var Pass = {toString: function(){return "CodeMirror.Pass"}} + +// Reused option objects for setSelection & friends +var sel_dontScroll = {scroll: false}; +var sel_mouse = {origin: "*mouse"}; +var sel_move = {origin: "+move"}; +// The inverse of countColumn -- find the offset that corresponds to +// a particular column. +function findColumn(string, goal, tabSize) { + for (var pos = 0, col = 0;;) { + var nextTab = string.indexOf("\t", pos) + if (nextTab == -1) { nextTab = string.length } + var skipped = nextTab - pos + if (nextTab == string.length || col + skipped >= goal) + { return pos + Math.min(skipped, goal - col) } + col += nextTab - pos + col += tabSize - (col % tabSize) + pos = nextTab + 1 + if (col >= goal) { return pos } + } +} + +var spaceStrs = [""] +function spaceStr(n) { + while (spaceStrs.length <= n) + { spaceStrs.push(lst(spaceStrs) + " ") } + return spaceStrs[n] +} + +function lst(arr) { return arr[arr.length-1] } + +function map(array, f) { + var out = [] + for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i) } + return out +} + +function insertSorted(array, value, score) { + var pos = 0, priority = score(value) + while (pos < array.length && score(array[pos]) <= priority) { pos++ } + array.splice(pos, 0, value) +} + +function nothing() {} + +function createObj(base, props) { + var inst + if (Object.create) { + inst = Object.create(base) + } else { + nothing.prototype = base + inst = new nothing() + } + if (props) { copyObj(props, inst) } + return inst +} + +var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/ +function isWordCharBasic(ch) { + return /\w/.test(ch) || ch > "\x80" && + (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)) +} +function isWordChar(ch, helper) { + if (!helper) { return isWordCharBasic(ch) } + if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true } + return helper.test(ch) +} + +function isEmpty(obj) { + for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } } + return true +} + +// Extending unicode characters. A series of a non-extending char + +// any number of extending chars is treated as a single unit as far +// as editing and measuring is concerned. This is not fully correct, +// since some scripts/fonts/browsers also treat other configurations +// of code points as a group. +var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/ +function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) } + +// Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range. +function skipExtendingChars(str, pos, dir) { + while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir } + return pos +} + +// Returns the value from the range [`from`; `to`] that satisfies +// `pred` and is closest to `from`. Assumes that at least `to` +// satisfies `pred`. Supports `from` being greater than `to`. +function findFirst(pred, from, to) { + // At any point we are certain `to` satisfies `pred`, don't know + // whether `from` does. + var dir = from > to ? -1 : 1 + for (;;) { + if (from == to) { return from } + var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF) + if (mid == from) { return pred(mid) ? from : to } + if (pred(mid)) { to = mid } + else { from = mid + dir } + } +} + +// The display handles the DOM integration, both for input reading +// and content drawing. It holds references to DOM nodes and +// display-related state. + +function Display(place, doc, input) { + var d = this + this.input = input + + // Covers bottom-right square when both scrollbars are present. + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler") + d.scrollbarFiller.setAttribute("cm-not-content", "true") + // Covers bottom of gutter when coverGutterNextToScrollbar is on + // and h scrollbar is present. + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler") + d.gutterFiller.setAttribute("cm-not-content", "true") + // Will contain the actual code, positioned to cover the viewport. + d.lineDiv = eltP("div", null, "CodeMirror-code") + // Elements are added to these to represent selection and cursors. + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1") + d.cursorDiv = elt("div", null, "CodeMirror-cursors") + // A visibility: hidden element used to find the size of things. + d.measure = elt("div", null, "CodeMirror-measure") + // When lines outside of the viewport are measured, they are drawn in this. + d.lineMeasure = elt("div", null, "CodeMirror-measure") + // Wraps everything that needs to exist inside the vertically-padded coordinate system + d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], + null, "position: relative; outline: none") + var lines = eltP("div", [d.lineSpace], "CodeMirror-lines") + // Moved around its parent to cover visible view. + d.mover = elt("div", [lines], null, "position: relative") + // Set to the height of the document, allowing scrolling. + d.sizer = elt("div", [d.mover], "CodeMirror-sizer") + d.sizerWidth = null + // Behavior of elts with overflow: auto and padding is + // inconsistent across browsers. This is used to ensure the + // scrollable area is big enough. + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;") + // Will contain the gutters, if any. + d.gutters = elt("div", null, "CodeMirror-gutters") + d.lineGutter = null + // Actual scrollable element. + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll") + d.scroller.setAttribute("tabIndex", "-1") + // The element in which the editor lives. + d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror") + + // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) + if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 } + if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true } + + if (place) { + if (place.appendChild) { place.appendChild(d.wrapper) } + else { place(d.wrapper) } + } + + // Current rendered range (may be bigger than the view window). + d.viewFrom = d.viewTo = doc.first + d.reportedViewFrom = d.reportedViewTo = doc.first + // Information about the rendered lines. + d.view = [] + d.renderedView = null + // Holds info about a single rendered line when it was rendered + // for measurement, while not in view. + d.externalMeasured = null + // Empty space (in pixels) above the view + d.viewOffset = 0 + d.lastWrapHeight = d.lastWrapWidth = 0 + d.updateLineNumbers = null + + d.nativeBarWidth = d.barHeight = d.barWidth = 0 + d.scrollbarsClipped = false + + // Used to only resize the line number gutter when necessary (when + // the amount of lines crosses a boundary that makes its width change) + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null + // Set to true when a non-horizontal-scrolling line widget is + // added. As an optimization, line widget aligning is skipped when + // this is false. + d.alignWidgets = false + + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null + + // Tracks the maximum line length so that the horizontal scrollbar + // can be kept static when scrolling. + d.maxLine = null + d.maxLineLength = 0 + d.maxLineChanged = false + + // Used for measuring wheel scrolling granularity + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null + + // True when shift is held down. + d.shift = false + + // Used to track whether anything happened since the context menu + // was opened. + d.selForContextMenu = null + + d.activeTouch = null + + input.init(d) +} + +// Find the line object corresponding to the given line number. +function getLine(doc, n) { + n -= doc.first + if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") } + var chunk = doc + while (!chunk.lines) { + for (var i = 0;; ++i) { + var child = chunk.children[i], sz = child.chunkSize() + if (n < sz) { chunk = child; break } + n -= sz + } + } + return chunk.lines[n] +} + +// Get the part of a document between two positions, as an array of +// strings. +function getBetween(doc, start, end) { + var out = [], n = start.line + doc.iter(start.line, end.line + 1, function (line) { + var text = line.text + if (n == end.line) { text = text.slice(0, end.ch) } + if (n == start.line) { text = text.slice(start.ch) } + out.push(text) + ++n + }) + return out +} +// Get the lines between from and to, as array of strings. +function getLines(doc, from, to) { + var out = [] + doc.iter(from, to, function (line) { out.push(line.text) }) // iter aborts when callback returns truthy value + return out +} + +// Update the height of a line, propagating the height change +// upwards to parent nodes. +function updateLineHeight(line, height) { + var diff = height - line.height + if (diff) { for (var n = line; n; n = n.parent) { n.height += diff } } +} + +// Given a line object, find its line number by walking up through +// its parent links. +function lineNo(line) { + if (line.parent == null) { return null } + var cur = line.parent, no = indexOf(cur.lines, line) + for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { + for (var i = 0;; ++i) { + if (chunk.children[i] == cur) { break } + no += chunk.children[i].chunkSize() + } + } + return no + cur.first +} + +// Find the line at the given vertical position, using the height +// information in the document tree. +function lineAtHeight(chunk, h) { + var n = chunk.first + outer: do { + for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) { + var child = chunk.children[i$1], ch = child.height + if (h < ch) { chunk = child; continue outer } + h -= ch + n += child.chunkSize() + } + return n + } while (!chunk.lines) + var i = 0 + for (; i < chunk.lines.length; ++i) { + var line = chunk.lines[i], lh = line.height + if (h < lh) { break } + h -= lh + } + return n + i +} + +function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size} + +function lineNumberFor(options, i) { + return String(options.lineNumberFormatter(i + options.firstLineNumber)) +} + +// A Pos instance represents a position within the text. +function Pos(line, ch, sticky) { + if ( sticky === void 0 ) sticky = null; + + if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) } + this.line = line + this.ch = ch + this.sticky = sticky +} + +// Compare two positions, return 0 if they are the same, a negative +// number when a is less, and a positive number otherwise. +function cmp(a, b) { return a.line - b.line || a.ch - b.ch } + +function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 } + +function copyPos(x) {return Pos(x.line, x.ch)} +function maxPos(a, b) { return cmp(a, b) < 0 ? b : a } +function minPos(a, b) { return cmp(a, b) < 0 ? a : b } + +// Most of the external API clips given positions to make sure they +// actually exist within the document. +function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))} +function clipPos(doc, pos) { + if (pos.line < doc.first) { return Pos(doc.first, 0) } + var last = doc.first + doc.size - 1 + if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) } + return clipToLen(pos, getLine(doc, pos.line).text.length) +} +function clipToLen(pos, linelen) { + var ch = pos.ch + if (ch == null || ch > linelen) { return Pos(pos.line, linelen) } + else if (ch < 0) { return Pos(pos.line, 0) } + else { return pos } +} +function clipPosArray(doc, array) { + var out = [] + for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]) } + return out +} + +// Optimize some code when these features are not used. +var sawReadOnlySpans = false; +var sawCollapsedSpans = false; +function seeReadOnlySpans() { + sawReadOnlySpans = true +} + +function seeCollapsedSpans() { + sawCollapsedSpans = true +} + +// TEXTMARKER SPANS + +function MarkedSpan(marker, from, to) { + this.marker = marker + this.from = from; this.to = to +} + +// Search an array of spans for a span matching the given marker. +function getMarkedSpanFor(spans, marker) { + if (spans) { for (var i = 0; i < spans.length; ++i) { + var span = spans[i] + if (span.marker == marker) { return span } + } } +} +// Remove a span from an array, returning undefined if no spans are +// left (we don't store arrays for lines without spans). +function removeMarkedSpan(spans, span) { + var r + for (var i = 0; i < spans.length; ++i) + { if (spans[i] != span) { (r || (r = [])).push(spans[i]) } } + return r +} +// Add a span to a line. +function addMarkedSpan(line, span) { + line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span] + span.marker.attachLine(line) +} + +// Used for the algorithm that adjusts markers for a change in the +// document. These functions cut an array of spans at a given +// character position, returning an array of remaining chunks (or +// undefined if nothing remains). +function markedSpansBefore(old, startCh, isInsert) { + var nw + if (old) { for (var i = 0; i < old.length; ++i) { + var span = old[i], marker = span.marker + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh) + if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh) + ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)) + } + } } + return nw +} +function markedSpansAfter(old, endCh, isInsert) { + var nw + if (old) { for (var i = 0; i < old.length; ++i) { + var span = old[i], marker = span.marker + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh) + if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh) + ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, + span.to == null ? null : span.to - endCh)) + } + } } + return nw +} + +// Given a change object, compute the new set of marker spans that +// cover the line in which the change took place. Removes spans +// entirely within the change, reconnects spans belonging to the +// same marker that appear on both sides of the change, and cuts off +// spans partially within the change. Returns an array of span +// arrays with one element for each line in (after) the change. +function stretchSpansOverChange(doc, change) { + if (change.full) { return null } + var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans + var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans + if (!oldFirst && !oldLast) { return null } + + var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0 + // Get the spans that 'stick out' on both sides + var first = markedSpansBefore(oldFirst, startCh, isInsert) + var last = markedSpansAfter(oldLast, endCh, isInsert) + + // Next, merge those two ends + var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0) + if (first) { + // Fix up .to properties of first + for (var i = 0; i < first.length; ++i) { + var span = first[i] + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker) + if (!found) { span.to = startCh } + else if (sameLine) { span.to = found.to == null ? null : found.to + offset } + } + } + } + if (last) { + // Fix up .from in last (or move them into first in case of sameLine) + for (var i$1 = 0; i$1 < last.length; ++i$1) { + var span$1 = last[i$1] + if (span$1.to != null) { span$1.to += offset } + if (span$1.from == null) { + var found$1 = getMarkedSpanFor(first, span$1.marker) + if (!found$1) { + span$1.from = offset + if (sameLine) { (first || (first = [])).push(span$1) } + } + } else { + span$1.from += offset + if (sameLine) { (first || (first = [])).push(span$1) } + } + } + } + // Make sure we didn't create any zero-length spans + if (first) { first = clearEmptySpans(first) } + if (last && last != first) { last = clearEmptySpans(last) } + + var newMarkers = [first] + if (!sameLine) { + // Fill gap with whole-line-spans + var gap = change.text.length - 2, gapMarkers + if (gap > 0 && first) + { for (var i$2 = 0; i$2 < first.length; ++i$2) + { if (first[i$2].to == null) + { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)) } } } + for (var i$3 = 0; i$3 < gap; ++i$3) + { newMarkers.push(gapMarkers) } + newMarkers.push(last) + } + return newMarkers +} + +// Remove spans that are empty and don't have a clearWhenEmpty +// option of false. +function clearEmptySpans(spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i] + if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) + { spans.splice(i--, 1) } + } + if (!spans.length) { return null } + return spans +} + +// Used to 'clip' out readOnly ranges when making a change. +function removeReadOnlyRanges(doc, from, to) { + var markers = null + doc.iter(from.line, to.line + 1, function (line) { + if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { + var mark = line.markedSpans[i].marker + if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) + { (markers || (markers = [])).push(mark) } + } } + }) + if (!markers) { return null } + var parts = [{from: from, to: to}] + for (var i = 0; i < markers.length; ++i) { + var mk = markers[i], m = mk.find(0) + for (var j = 0; j < parts.length; ++j) { + var p = parts[j] + if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue } + var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to) + if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) + { newParts.push({from: p.from, to: m.from}) } + if (dto > 0 || !mk.inclusiveRight && !dto) + { newParts.push({from: m.to, to: p.to}) } + parts.splice.apply(parts, newParts) + j += newParts.length - 3 + } + } + return parts +} + +// Connect or disconnect spans from a line. +function detachMarkedSpans(line) { + var spans = line.markedSpans + if (!spans) { return } + for (var i = 0; i < spans.length; ++i) + { spans[i].marker.detachLine(line) } + line.markedSpans = null +} +function attachMarkedSpans(line, spans) { + if (!spans) { return } + for (var i = 0; i < spans.length; ++i) + { spans[i].marker.attachLine(line) } + line.markedSpans = spans +} + +// Helpers used when computing which overlapping collapsed span +// counts as the larger one. +function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 } +function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 } + +// Returns a number indicating which of two overlapping collapsed +// spans is larger (and thus includes the other). Falls back to +// comparing ids when the spans cover exactly the same range. +function compareCollapsedMarkers(a, b) { + var lenDiff = a.lines.length - b.lines.length + if (lenDiff != 0) { return lenDiff } + var aPos = a.find(), bPos = b.find() + var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b) + if (fromCmp) { return -fromCmp } + var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b) + if (toCmp) { return toCmp } + return b.id - a.id +} + +// Find out whether a line ends or starts in a collapsed span. If +// so, return the marker for that span. +function collapsedSpanAtSide(line, start) { + var sps = sawCollapsedSpans && line.markedSpans, found + if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { + sp = sps[i] + if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && + (!found || compareCollapsedMarkers(found, sp.marker) < 0)) + { found = sp.marker } + } } + return found +} +function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) } +function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) } + +function collapsedSpanAround(line, ch) { + var sps = sawCollapsedSpans && line.markedSpans, found + if (sps) { for (var i = 0; i < sps.length; ++i) { + var sp = sps[i] + if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && + (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker } + } } + return found +} + +// Test whether there exists a collapsed span that partially +// overlaps (covers the start or end, but not both) of a new span. +// Such overlap is not allowed. +function conflictingCollapsedRange(doc, lineNo, from, to, marker) { + var line = getLine(doc, lineNo) + var sps = sawCollapsedSpans && line.markedSpans + if (sps) { for (var i = 0; i < sps.length; ++i) { + var sp = sps[i] + if (!sp.marker.collapsed) { continue } + var found = sp.marker.find(0) + var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker) + var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker) + if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue } + if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || + fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) + { return true } + } } +} + +// A visual line is a line as drawn on the screen. Folding, for +// example, can cause multiple logical lines to appear on the same +// visual line. This finds the start of the visual line that the +// given line is part of (usually that is the line itself). +function visualLine(line) { + var merged + while (merged = collapsedSpanAtStart(line)) + { line = merged.find(-1, true).line } + return line +} + +function visualLineEnd(line) { + var merged + while (merged = collapsedSpanAtEnd(line)) + { line = merged.find(1, true).line } + return line +} + +// Returns an array of logical lines that continue the visual line +// started by the argument, or undefined if there are no such lines. +function visualLineContinued(line) { + var merged, lines + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line + ;(lines || (lines = [])).push(line) + } + return lines +} + +// Get the line number of the start of the visual line that the +// given line number is part of. +function visualLineNo(doc, lineN) { + var line = getLine(doc, lineN), vis = visualLine(line) + if (line == vis) { return lineN } + return lineNo(vis) +} + +// Get the line number of the start of the next visual line after +// the given line. +function visualLineEndNo(doc, lineN) { + if (lineN > doc.lastLine()) { return lineN } + var line = getLine(doc, lineN), merged + if (!lineIsHidden(doc, line)) { return lineN } + while (merged = collapsedSpanAtEnd(line)) + { line = merged.find(1, true).line } + return lineNo(line) + 1 +} + +// Compute whether a line is hidden. Lines count as hidden when they +// are part of a visual line that starts with another line, or when +// they are entirely covered by collapsed, non-widget span. +function lineIsHidden(doc, line) { + var sps = sawCollapsedSpans && line.markedSpans + if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { + sp = sps[i] + if (!sp.marker.collapsed) { continue } + if (sp.from == null) { return true } + if (sp.marker.widgetNode) { continue } + if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) + { return true } + } } +} +function lineIsHiddenInner(doc, line, span) { + if (span.to == null) { + var end = span.marker.find(1, true) + return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)) + } + if (span.marker.inclusiveRight && span.to == line.text.length) + { return true } + for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) { + sp = line.markedSpans[i] + if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && + (sp.to == null || sp.to != span.from) && + (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && + lineIsHiddenInner(doc, line, sp)) { return true } + } +} + +// Find the height above the given line. +function heightAtLine(lineObj) { + lineObj = visualLine(lineObj) + + var h = 0, chunk = lineObj.parent + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i] + if (line == lineObj) { break } + else { h += line.height } + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i$1 = 0; i$1 < p.children.length; ++i$1) { + var cur = p.children[i$1] + if (cur == chunk) { break } + else { h += cur.height } + } + } + return h +} + +// Compute the character length of a line, taking into account +// collapsed ranges (see markText) that might hide parts, and join +// other lines onto it. +function lineLength(line) { + if (line.height == 0) { return 0 } + var len = line.text.length, merged, cur = line + while (merged = collapsedSpanAtStart(cur)) { + var found = merged.find(0, true) + cur = found.from.line + len += found.from.ch - found.to.ch + } + cur = line + while (merged = collapsedSpanAtEnd(cur)) { + var found$1 = merged.find(0, true) + len -= cur.text.length - found$1.from.ch + cur = found$1.to.line + len += cur.text.length - found$1.to.ch + } + return len +} + +// Find the longest line in the document. +function findMaxLine(cm) { + var d = cm.display, doc = cm.doc + d.maxLine = getLine(doc, doc.first) + d.maxLineLength = lineLength(d.maxLine) + d.maxLineChanged = true + doc.iter(function (line) { + var len = lineLength(line) + if (len > d.maxLineLength) { + d.maxLineLength = len + d.maxLine = line + } + }) +} + +// BIDI HELPERS + +function iterateBidiSections(order, from, to, f) { + if (!order) { return f(from, to, "ltr", 0) } + var found = false + for (var i = 0; i < order.length; ++i) { + var part = order[i] + if (part.from < to && part.to > from || from == to && part.to == from) { + f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i) + found = true + } + } + if (!found) { f(from, to, "ltr") } +} + +var bidiOther = null +function getBidiPartAt(order, ch, sticky) { + var found + bidiOther = null + for (var i = 0; i < order.length; ++i) { + var cur = order[i] + if (cur.from < ch && cur.to > ch) { return i } + if (cur.to == ch) { + if (cur.from != cur.to && sticky == "before") { found = i } + else { bidiOther = i } + } + if (cur.from == ch) { + if (cur.from != cur.to && sticky != "before") { found = i } + else { bidiOther = i } + } + } + return found != null ? found : bidiOther +} + +// Bidirectional ordering algorithm +// See http://unicode.org/reports/tr9/tr9-13.html for the algorithm +// that this (partially) implements. + +// One-char codes used for character types: +// L (L): Left-to-Right +// R (R): Right-to-Left +// r (AL): Right-to-Left Arabic +// 1 (EN): European Number +// + (ES): European Number Separator +// % (ET): European Number Terminator +// n (AN): Arabic Number +// , (CS): Common Number Separator +// m (NSM): Non-Spacing Mark +// b (BN): Boundary Neutral +// s (B): Paragraph Separator +// t (S): Segment Separator +// w (WS): Whitespace +// N (ON): Other Neutrals + +// Returns null if characters are ordered as they appear +// (left-to-right), or an array of sections ({from, to, level} +// objects) in the order in which they occur visually. +var bidiOrdering = (function() { + // Character types for codepoints 0 to 0xff + var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN" + // Character types for codepoints 0x600 to 0x6f9 + var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111" + function charType(code) { + if (code <= 0xf7) { return lowTypes.charAt(code) } + else if (0x590 <= code && code <= 0x5f4) { return "R" } + else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) } + else if (0x6ee <= code && code <= 0x8ac) { return "r" } + else if (0x2000 <= code && code <= 0x200b) { return "w" } + else if (code == 0x200c) { return "b" } + else { return "L" } + } + + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/ + var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/ + + function BidiSpan(level, from, to) { + this.level = level + this.from = from; this.to = to + } + + return function(str, direction) { + var outerType = direction == "ltr" ? "L" : "R" + + if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false } + var len = str.length, types = [] + for (var i = 0; i < len; ++i) + { types.push(charType(str.charCodeAt(i))) } + + // W1. Examine each non-spacing mark (NSM) in the level run, and + // change the type of the NSM to the type of the previous + // character. If the NSM is at the start of the level run, it will + // get the type of sor. + for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) { + var type = types[i$1] + if (type == "m") { types[i$1] = prev } + else { prev = type } + } + + // W2. Search backwards from each instance of a European number + // until the first strong type (R, L, AL, or sor) is found. If an + // AL is found, change the type of the European number to Arabic + // number. + // W3. Change all ALs to R. + for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) { + var type$1 = types[i$2] + if (type$1 == "1" && cur == "r") { types[i$2] = "n" } + else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R" } } + } + + // W4. A single European separator between two European numbers + // changes to a European number. A single common separator between + // two numbers of the same type changes to that type. + for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { + var type$2 = types[i$3] + if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1" } + else if (type$2 == "," && prev$1 == types[i$3+1] && + (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1 } + prev$1 = type$2 + } + + // W5. A sequence of European terminators adjacent to European + // numbers changes to all European numbers. + // W6. Otherwise, separators and terminators change to Other + // Neutral. + for (var i$4 = 0; i$4 < len; ++i$4) { + var type$3 = types[i$4] + if (type$3 == ",") { types[i$4] = "N" } + else if (type$3 == "%") { + var end = (void 0) + for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} + var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N" + for (var j = i$4; j < end; ++j) { types[j] = replace } + i$4 = end - 1 + } + } + + // W7. Search backwards from each instance of a European number + // until the first strong type (R, L, or sor) is found. If an L is + // found, then change the type of the European number to L. + for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { + var type$4 = types[i$5] + if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L" } + else if (isStrong.test(type$4)) { cur$1 = type$4 } + } + + // N1. A sequence of neutrals takes the direction of the + // surrounding strong text if the text on both sides has the same + // direction. European and Arabic numbers act as if they were R in + // terms of their influence on neutrals. Start-of-level-run (sor) + // and end-of-level-run (eor) are used at level run boundaries. + // N2. Any remaining neutrals take the embedding direction. + for (var i$6 = 0; i$6 < len; ++i$6) { + if (isNeutral.test(types[i$6])) { + var end$1 = (void 0) + for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} + var before = (i$6 ? types[i$6-1] : outerType) == "L" + var after = (end$1 < len ? types[end$1] : outerType) == "L" + var replace$1 = before == after ? (before ? "L" : "R") : outerType + for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1 } + i$6 = end$1 - 1 + } + } + + // Here we depart from the documented algorithm, in order to avoid + // building up an actual levels array. Since there are only three + // levels (0, 1, 2) in an implementation that doesn't take + // explicit embedding into account, we can build up the order on + // the fly, without following the level-based algorithm. + var order = [], m + for (var i$7 = 0; i$7 < len;) { + if (countsAsLeft.test(types[i$7])) { + var start = i$7 + for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} + order.push(new BidiSpan(0, start, i$7)) + } else { + var pos = i$7, at = order.length + for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} + for (var j$2 = pos; j$2 < i$7;) { + if (countsAsNum.test(types[j$2])) { + if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)) } + var nstart = j$2 + for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} + order.splice(at, 0, new BidiSpan(2, nstart, j$2)) + pos = j$2 + } else { ++j$2 } + } + if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)) } + } + } + if (direction == "ltr") { + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length + order.unshift(new BidiSpan(0, 0, m[0].length)) + } + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length + order.push(new BidiSpan(0, len - m[0].length, len)) + } + } + + return direction == "rtl" ? order.reverse() : order + } +})() + +// Get the bidi ordering for the given line (and cache it). Returns +// false for lines that are fully left-to-right, and an array of +// BidiSpan objects otherwise. +function getOrder(line, direction) { + var order = line.order + if (order == null) { order = line.order = bidiOrdering(line.text, direction) } + return order +} + +// EVENT HANDLING + +// Lightweight event framework. on/off also work on DOM nodes, +// registering native DOM handlers. + +var noHandlers = [] + +var on = function(emitter, type, f) { + if (emitter.addEventListener) { + emitter.addEventListener(type, f, false) + } else if (emitter.attachEvent) { + emitter.attachEvent("on" + type, f) + } else { + var map = emitter._handlers || (emitter._handlers = {}) + map[type] = (map[type] || noHandlers).concat(f) + } +} + +function getHandlers(emitter, type) { + return emitter._handlers && emitter._handlers[type] || noHandlers +} + +function off(emitter, type, f) { + if (emitter.removeEventListener) { + emitter.removeEventListener(type, f, false) + } else if (emitter.detachEvent) { + emitter.detachEvent("on" + type, f) + } else { + var map = emitter._handlers, arr = map && map[type] + if (arr) { + var index = indexOf(arr, f) + if (index > -1) + { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)) } + } + } +} + +function signal(emitter, type /*, values...*/) { + var handlers = getHandlers(emitter, type) + if (!handlers.length) { return } + var args = Array.prototype.slice.call(arguments, 2) + for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args) } +} + +// The DOM events that CodeMirror handles can be overridden by +// registering a (non-DOM) handler on the editor for the event name, +// and preventDefault-ing the event in that handler. +function signalDOMEvent(cm, e, override) { + if (typeof e == "string") + { e = {type: e, preventDefault: function() { this.defaultPrevented = true }} } + signal(cm, override || e.type, cm, e) + return e_defaultPrevented(e) || e.codemirrorIgnore +} + +function signalCursorActivity(cm) { + var arr = cm._handlers && cm._handlers.cursorActivity + if (!arr) { return } + var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []) + for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1) + { set.push(arr[i]) } } +} + +function hasHandler(emitter, type) { + return getHandlers(emitter, type).length > 0 +} + +// Add on and off methods to a constructor's prototype, to make +// registering events on such objects more convenient. +function eventMixin(ctor) { + ctor.prototype.on = function(type, f) {on(this, type, f)} + ctor.prototype.off = function(type, f) {off(this, type, f)} +} + +// Due to the fact that we still support jurassic IE versions, some +// compatibility wrappers are needed. + +function e_preventDefault(e) { + if (e.preventDefault) { e.preventDefault() } + else { e.returnValue = false } +} +function e_stopPropagation(e) { + if (e.stopPropagation) { e.stopPropagation() } + else { e.cancelBubble = true } +} +function e_defaultPrevented(e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false +} +function e_stop(e) {e_preventDefault(e); e_stopPropagation(e)} + +function e_target(e) {return e.target || e.srcElement} +function e_button(e) { + var b = e.which + if (b == null) { + if (e.button & 1) { b = 1 } + else if (e.button & 2) { b = 3 } + else if (e.button & 4) { b = 2 } + } + if (mac && e.ctrlKey && b == 1) { b = 3 } + return b +} + +// Detect drag-and-drop +var dragAndDrop = function() { + // There is *some* kind of drag-and-drop support in IE6-8, but I + // couldn't get it to work yet. + if (ie && ie_version < 9) { return false } + var div = elt('div') + return "draggable" in div || "dragDrop" in div +}() + +var zwspSupported +function zeroWidthElement(measure) { + if (zwspSupported == null) { + var test = elt("span", "\u200b") + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])) + if (measure.firstChild.offsetHeight != 0) + { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8) } + } + var node = zwspSupported ? elt("span", "\u200b") : + elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px") + node.setAttribute("cm-text", "") + return node +} + +// Feature-detect IE's crummy client rect reporting for bidi text +var badBidiRects +function hasBadBidiRects(measure) { + if (badBidiRects != null) { return badBidiRects } + var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")) + var r0 = range(txt, 0, 1).getBoundingClientRect() + var r1 = range(txt, 1, 2).getBoundingClientRect() + removeChildren(measure) + if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780) + return badBidiRects = (r1.right - r0.right < 3) +} + +// See if "".split is the broken IE version, if so, provide an +// alternative way to split lines. +var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { + var pos = 0, result = [], l = string.length + while (pos <= l) { + var nl = string.indexOf("\n", pos) + if (nl == -1) { nl = string.length } + var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl) + var rt = line.indexOf("\r") + if (rt != -1) { + result.push(line.slice(0, rt)) + pos += rt + 1 + } else { + result.push(line) + pos = nl + 1 + } + } + return result +} : function (string) { return string.split(/\r\n?|\n/); } + +var hasSelection = window.getSelection ? function (te) { + try { return te.selectionStart != te.selectionEnd } + catch(e) { return false } +} : function (te) { + var range + try {range = te.ownerDocument.selection.createRange()} + catch(e) {} + if (!range || range.parentElement() != te) { return false } + return range.compareEndPoints("StartToEnd", range) != 0 +} + +var hasCopyEvent = (function () { + var e = elt("div") + if ("oncopy" in e) { return true } + e.setAttribute("oncopy", "return;") + return typeof e.oncopy == "function" +})() + +var badZoomedRects = null +function hasBadZoomedRects(measure) { + if (badZoomedRects != null) { return badZoomedRects } + var node = removeChildrenAndAdd(measure, elt("span", "x")) + var normal = node.getBoundingClientRect() + var fromRange = range(node, 0, 1).getBoundingClientRect() + return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 +} + +var modes = {}; +var mimeModes = {}; +// Extra arguments are stored as the mode's dependencies, which is +// used by (legacy) mechanisms like loadmode.js to automatically +// load a mode. (Preferred mechanism is the require/define calls.) +function defineMode(name, mode) { + if (arguments.length > 2) + { mode.dependencies = Array.prototype.slice.call(arguments, 2) } + modes[name] = mode +} + +function defineMIME(mime, spec) { + mimeModes[mime] = spec +} + +// Given a MIME type, a {name, ...options} config object, or a name +// string, return a mode config object. +function resolveMode(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec] + } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { + var found = mimeModes[spec.name] + if (typeof found == "string") { found = {name: found} } + spec = createObj(found, spec) + spec.name = found.name + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return resolveMode("application/xml") + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { + return resolveMode("application/json") + } + if (typeof spec == "string") { return {name: spec} } + else { return spec || {name: "null"} } +} + +// Given a mode spec (anything that resolveMode accepts), find and +// initialize an actual mode object. +function getMode(options, spec) { + spec = resolveMode(spec) + var mfactory = modes[spec.name] + if (!mfactory) { return getMode(options, "text/plain") } + var modeObj = mfactory(options, spec) + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name] + for (var prop in exts) { + if (!exts.hasOwnProperty(prop)) { continue } + if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop] } + modeObj[prop] = exts[prop] + } + } + modeObj.name = spec.name + if (spec.helperType) { modeObj.helperType = spec.helperType } + if (spec.modeProps) { for (var prop$1 in spec.modeProps) + { modeObj[prop$1] = spec.modeProps[prop$1] } } + + return modeObj +} + +// This can be used to attach properties to mode objects from +// outside the actual mode definition. +var modeExtensions = {} +function extendMode(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}) + copyObj(properties, exts) +} + +function copyState(mode, state) { + if (state === true) { return state } + if (mode.copyState) { return mode.copyState(state) } + var nstate = {} + for (var n in state) { + var val = state[n] + if (val instanceof Array) { val = val.concat([]) } + nstate[n] = val + } + return nstate +} + +// Given a mode and a state (for that mode), find the inner mode and +// state at the position that the state refers to. +function innerMode(mode, state) { + var info + while (mode.innerMode) { + info = mode.innerMode(state) + if (!info || info.mode == mode) { break } + state = info.state + mode = info.mode + } + return info || {mode: mode, state: state} +} + +function startState(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true +} + +// STRING STREAM + +// Fed to the mode parsers, provides helper functions to make +// parsers more succinct. + +var StringStream = function(string, tabSize, lineOracle) { + this.pos = this.start = 0 + this.string = string + this.tabSize = tabSize || 8 + this.lastColumnPos = this.lastColumnValue = 0 + this.lineStart = 0 + this.lineOracle = lineOracle +}; + +StringStream.prototype.eol = function () {return this.pos >= this.string.length}; +StringStream.prototype.sol = function () {return this.pos == this.lineStart}; +StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined}; +StringStream.prototype.next = function () { + if (this.pos < this.string.length) + { return this.string.charAt(this.pos++) } +}; +StringStream.prototype.eat = function (match) { + var ch = this.string.charAt(this.pos) + var ok + if (typeof match == "string") { ok = ch == match } + else { ok = ch && (match.test ? match.test(ch) : match(ch)) } + if (ok) {++this.pos; return ch} +}; +StringStream.prototype.eatWhile = function (match) { + var start = this.pos + while (this.eat(match)){} + return this.pos > start +}; +StringStream.prototype.eatSpace = function () { + var this$1 = this; + + var start = this.pos + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos } + return this.pos > start +}; +StringStream.prototype.skipToEnd = function () {this.pos = this.string.length}; +StringStream.prototype.skipTo = function (ch) { + var found = this.string.indexOf(ch, this.pos) + if (found > -1) {this.pos = found; return true} +}; +StringStream.prototype.backUp = function (n) {this.pos -= n}; +StringStream.prototype.column = function () { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue) + this.lastColumnPos = this.start + } + return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) +}; +StringStream.prototype.indentation = function () { + return countColumn(this.string, null, this.tabSize) - + (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) +}; +StringStream.prototype.match = function (pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; } + var substr = this.string.substr(this.pos, pattern.length) + if (cased(substr) == cased(pattern)) { + if (consume !== false) { this.pos += pattern.length } + return true + } + } else { + var match = this.string.slice(this.pos).match(pattern) + if (match && match.index > 0) { return null } + if (match && consume !== false) { this.pos += match[0].length } + return match + } +}; +StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)}; +StringStream.prototype.hideFirstChars = function (n, inner) { + this.lineStart += n + try { return inner() } + finally { this.lineStart -= n } +}; +StringStream.prototype.lookAhead = function (n) { + var oracle = this.lineOracle + return oracle && oracle.lookAhead(n) +}; +StringStream.prototype.baseToken = function () { + var oracle = this.lineOracle + return oracle && oracle.baseToken(this.pos) +}; + +var SavedContext = function(state, lookAhead) { + this.state = state + this.lookAhead = lookAhead +}; + +var Context = function(doc, state, line, lookAhead) { + this.state = state + this.doc = doc + this.line = line + this.maxLookAhead = lookAhead || 0 + this.baseTokens = null + this.baseTokenPos = 1 +}; + +Context.prototype.lookAhead = function (n) { + var line = this.doc.getLine(this.line + n) + if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n } + return line +}; + +Context.prototype.baseToken = function (n) { + var this$1 = this; + + if (!this.baseTokens) { return null } + while (this.baseTokens[this.baseTokenPos] <= n) + { this$1.baseTokenPos += 2 } + var type = this.baseTokens[this.baseTokenPos + 1] + return {type: type && type.replace(/( |^)overlay .*/, ""), + size: this.baseTokens[this.baseTokenPos] - n} +}; + +Context.prototype.nextLine = function () { + this.line++ + if (this.maxLookAhead > 0) { this.maxLookAhead-- } +}; + +Context.fromSaved = function (doc, saved, line) { + if (saved instanceof SavedContext) + { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) } + else + { return new Context(doc, copyState(doc.mode, saved), line) } +}; + +Context.prototype.save = function (copy) { + var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state + return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state +}; + + +// Compute a style array (an array starting with a mode generation +// -- for invalidation -- followed by pairs of end positions and +// style strings), which is used to highlight the tokens on the +// line. +function highlightLine(cm, line, context, forceToEnd) { + // A styles array always starts with a number identifying the + // mode/overlays that it is based on (for easy invalidation). + var st = [cm.state.modeGen], lineClasses = {} + // Compute the base array of styles + runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); }, + lineClasses, forceToEnd) + var state = context.state + + // Run overlays, adjust style array. + var loop = function ( o ) { + context.baseTokens = st + var overlay = cm.state.overlays[o], i = 1, at = 0 + context.state = true + runMode(cm, line.text, overlay.mode, context, function (end, style) { + var start = i + // Ensure there's a token end at the current position, and that i points at it + while (at < end) { + var i_end = st[i] + if (i_end > end) + { st.splice(i, 1, end, st[i+1], i_end) } + i += 2 + at = Math.min(end, i_end) + } + if (!style) { return } + if (overlay.opaque) { + st.splice(start, i - start, end, "overlay " + style) + i = start + 2 + } else { + for (; start < i; start += 2) { + var cur = st[start+1] + st[start+1] = (cur ? cur + " " : "") + "overlay " + style + } + } + }, lineClasses) + context.state = state + context.baseTokens = null + context.baseTokenPos = 1 + }; + + for (var o = 0; o < cm.state.overlays.length; ++o) loop( o ); + + return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} +} + +function getLineStyles(cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + var context = getContextBefore(cm, lineNo(line)) + var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state) + var result = highlightLine(cm, line, context) + if (resetState) { context.state = resetState } + line.stateAfter = context.save(!resetState) + line.styles = result.styles + if (result.classes) { line.styleClasses = result.classes } + else if (line.styleClasses) { line.styleClasses = null } + if (updateFrontier === cm.doc.highlightFrontier) + { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier) } + } + return line.styles +} + +function getContextBefore(cm, n, precise) { + var doc = cm.doc, display = cm.display + if (!doc.mode.startState) { return new Context(doc, true, n) } + var start = findStartLine(cm, n, precise) + var saved = start > doc.first && getLine(doc, start - 1).stateAfter + var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start) + + doc.iter(start, n, function (line) { + processLine(cm, line.text, context) + var pos = context.line + line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null + context.nextLine() + }) + if (precise) { doc.modeFrontier = context.line } + return context +} + +// Lightweight form of highlight -- proceed over this line and +// update state, but don't save a style array. Used for lines that +// aren't currently visible. +function processLine(cm, text, context, startAt) { + var mode = cm.doc.mode + var stream = new StringStream(text, cm.options.tabSize, context) + stream.start = stream.pos = startAt || 0 + if (text == "") { callBlankLine(mode, context.state) } + while (!stream.eol()) { + readToken(mode, stream, context.state) + stream.start = stream.pos + } +} + +function callBlankLine(mode, state) { + if (mode.blankLine) { return mode.blankLine(state) } + if (!mode.innerMode) { return } + var inner = innerMode(mode, state) + if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) } +} + +function readToken(mode, stream, state, inner) { + for (var i = 0; i < 10; i++) { + if (inner) { inner[0] = innerMode(mode, state).mode } + var style = mode.token(stream, state) + if (stream.pos > stream.start) { return style } + } + throw new Error("Mode " + mode.name + " failed to advance stream.") +} + +var Token = function(stream, type, state) { + this.start = stream.start; this.end = stream.pos + this.string = stream.current() + this.type = type || null + this.state = state +}; + +// Utility for getTokenAt and getLineTokens +function takeToken(cm, pos, precise, asArray) { + var doc = cm.doc, mode = doc.mode, style + pos = clipPos(doc, pos) + var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise) + var stream = new StringStream(line.text, cm.options.tabSize, context), tokens + if (asArray) { tokens = [] } + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos + style = readToken(mode, stream, context.state) + if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))) } + } + return asArray ? tokens : new Token(stream, style, context.state) +} + +function extractLineClasses(type, output) { + if (type) { for (;;) { + var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/) + if (!lineClass) { break } + type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length) + var prop = lineClass[1] ? "bgClass" : "textClass" + if (output[prop] == null) + { output[prop] = lineClass[2] } + else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) + { output[prop] += " " + lineClass[2] } + } } + return type +} + +// Run the given mode's parser over a line, calling f for each token. +function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { + var flattenSpans = mode.flattenSpans + if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans } + var curStart = 0, curStyle = null + var stream = new StringStream(text, cm.options.tabSize, context), style + var inner = cm.options.addModeClass && [null] + if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses) } + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false + if (forceToEnd) { processLine(cm, text, context, stream.pos) } + stream.pos = text.length + style = null + } else { + style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses) + } + if (inner) { + var mName = inner[0].name + if (mName) { style = "m-" + (style ? mName + " " + style : mName) } + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 5000) + f(curStart, curStyle) + } + curStyle = style + } + stream.start = stream.pos + } + while (curStart < stream.pos) { + // Webkit seems to refuse to render text nodes longer than 57444 + // characters, and returns inaccurate measurements in nodes + // starting around 5000 chars. + var pos = Math.min(stream.pos, curStart + 5000) + f(pos, curStyle) + curStart = pos + } +} + +// Finds the line to start with when starting a parse. Tries to +// find a line with a stateAfter, so that it can start with a +// valid state. If that fails, it returns the line with the +// smallest indentation, which tends to need the least context to +// parse correctly. +function findStartLine(cm, n, precise) { + var minindent, minline, doc = cm.doc + var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100) + for (var search = n; search > lim; --search) { + if (search <= doc.first) { return doc.first } + var line = getLine(doc, search - 1), after = line.stateAfter + if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) + { return search } + var indented = countColumn(line.text, null, cm.options.tabSize) + if (minline == null || minindent > indented) { + minline = search - 1 + minindent = indented + } + } + return minline +} + +function retreatFrontier(doc, n) { + doc.modeFrontier = Math.min(doc.modeFrontier, n) + if (doc.highlightFrontier < n - 10) { return } + var start = doc.first + for (var line = n - 1; line > start; line--) { + var saved = getLine(doc, line).stateAfter + // change is on 3 + // state on line 1 looked ahead 2 -- so saw 3 + // test 1 + 2 < 3 should cover this + if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { + start = line + 1 + break + } + } + doc.highlightFrontier = Math.min(doc.highlightFrontier, start) +} + +// LINE DATA STRUCTURE + +// Line objects. These hold state related to a line, including +// highlighting info (the styles array). +var Line = function(text, markedSpans, estimateHeight) { + this.text = text + attachMarkedSpans(this, markedSpans) + this.height = estimateHeight ? estimateHeight(this) : 1 +}; + +Line.prototype.lineNo = function () { return lineNo(this) }; +eventMixin(Line) + +// Change the content (text, markers) of a line. Automatically +// invalidates cached information and tries to re-estimate the +// line's height. +function updateLine(line, text, markedSpans, estimateHeight) { + line.text = text + if (line.stateAfter) { line.stateAfter = null } + if (line.styles) { line.styles = null } + if (line.order != null) { line.order = null } + detachMarkedSpans(line) + attachMarkedSpans(line, markedSpans) + var estHeight = estimateHeight ? estimateHeight(line) : 1 + if (estHeight != line.height) { updateLineHeight(line, estHeight) } +} + +// Detach a line from the document tree and its markers. +function cleanUpLine(line) { + line.parent = null + detachMarkedSpans(line) +} + +// Convert a style as returned by a mode (either null, or a string +// containing one or more styles) to a CSS style. This is cached, +// and also looks for line-wide styles. +var styleToClassCache = {}; +var styleToClassCacheWithMode = {}; +function interpretTokenStyle(style, options) { + if (!style || /^\s*$/.test(style)) { return null } + var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache + return cache[style] || + (cache[style] = style.replace(/\S+/g, "cm-$&")) +} + +// Render the DOM representation of the text of a line. Also builds +// up a 'line map', which points at the DOM nodes that represent +// specific stretches of text, and is used by the measuring code. +// The returned object contains the DOM node, this map, and +// information about line-wide styles that were set by the mode. +function buildLineContent(cm, lineView) { + // The padding-right forces the element to have a 'border', which + // is needed on Webkit to be able to get line-level bounding + // rectangles for it (in measureChar). + var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null) + var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content, + col: 0, pos: 0, cm: cm, + trailingSpace: false, + splitSpaces: cm.getOption("lineWrapping")} + lineView.measure = {} + + // Iterate over the logical lines that make up this visual line. + for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { + var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0) + builder.pos = 0 + builder.addToken = buildToken + // Optionally wire in some hacks into the token-rendering + // algorithm, to deal with browser quirks. + if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) + { builder.addToken = buildTokenBadBidi(builder.addToken, order) } + builder.map = [] + var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line) + insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)) + if (line.styleClasses) { + if (line.styleClasses.bgClass) + { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "") } + if (line.styleClasses.textClass) + { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "") } + } + + // Ensure at least a single node is present, for measuring. + if (builder.map.length == 0) + { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))) } + + // Store the map and a cache object for the current logical line + if (i == 0) { + lineView.measure.map = builder.map + lineView.measure.cache = {} + } else { + ;(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) + ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}) + } + } + + // See issue #2901 + if (webkit) { + var last = builder.content.lastChild + if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) + { builder.content.className = "cm-tab-wrap-hack" } + } + + signal(cm, "renderLine", cm, lineView.line, builder.pre) + if (builder.pre.className) + { builder.textClass = joinClasses(builder.pre.className, builder.textClass || "") } + + return builder +} + +function defaultSpecialCharPlaceholder(ch) { + var token = elt("span", "\u2022", "cm-invalidchar") + token.title = "\\u" + ch.charCodeAt(0).toString(16) + token.setAttribute("aria-label", token.title) + return token +} + +// Build up the DOM representation for a single token, and add it to +// the line map. Takes care to render special characters separately. +function buildToken(builder, text, style, startStyle, endStyle, title, css) { + if (!text) { return } + var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text + var special = builder.cm.state.specialChars, mustWrap = false + var content + if (!special.test(text)) { + builder.col += text.length + content = document.createTextNode(displayText) + builder.map.push(builder.pos, builder.pos + text.length, content) + if (ie && ie_version < 9) { mustWrap = true } + builder.pos += text.length + } else { + content = document.createDocumentFragment() + var pos = 0 + while (true) { + special.lastIndex = pos + var m = special.exec(text) + var skipped = m ? m.index - pos : text.length - pos + if (skipped) { + var txt = document.createTextNode(displayText.slice(pos, pos + skipped)) + if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])) } + else { content.appendChild(txt) } + builder.map.push(builder.pos, builder.pos + skipped, txt) + builder.col += skipped + builder.pos += skipped + } + if (!m) { break } + pos += skipped + 1 + var txt$1 = (void 0) + if (m[0] == "\t") { + var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize + txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")) + txt$1.setAttribute("role", "presentation") + txt$1.setAttribute("cm-text", "\t") + builder.col += tabWidth + } else if (m[0] == "\r" || m[0] == "\n") { + txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")) + txt$1.setAttribute("cm-text", m[0]) + builder.col += 1 + } else { + txt$1 = builder.cm.options.specialCharPlaceholder(m[0]) + txt$1.setAttribute("cm-text", m[0]) + if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])) } + else { content.appendChild(txt$1) } + builder.col += 1 + } + builder.map.push(builder.pos, builder.pos + 1, txt$1) + builder.pos++ + } + } + builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32 + if (style || startStyle || endStyle || mustWrap || css) { + var fullStyle = style || "" + if (startStyle) { fullStyle += startStyle } + if (endStyle) { fullStyle += endStyle } + var token = elt("span", [content], fullStyle, css) + if (title) { token.title = title } + return builder.content.appendChild(token) + } + builder.content.appendChild(content) +} + +// Change some spaces to NBSP to prevent the browser from collapsing +// trailing spaces at the end of a line when rendering text (issue #1362). +function splitSpaces(text, trailingBefore) { + if (text.length > 1 && !/ /.test(text)) { return text } + var spaceBefore = trailingBefore, result = "" + for (var i = 0; i < text.length; i++) { + var ch = text.charAt(i) + if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) + { ch = "\u00a0" } + result += ch + spaceBefore = ch == " " + } + return result +} + +// Work around nonsense dimensions being reported for stretches of +// right-to-left text. +function buildTokenBadBidi(inner, order) { + return function (builder, text, style, startStyle, endStyle, title, css) { + style = style ? style + " cm-force-border" : "cm-force-border" + var start = builder.pos, end = start + text.length + for (;;) { + // Find the part that overlaps with the start of this text + var part = (void 0) + for (var i = 0; i < order.length; i++) { + part = order[i] + if (part.to > start && part.from <= start) { break } + } + if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) } + inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css) + startStyle = null + text = text.slice(part.to - start) + start = part.to + } + } +} + +function buildCollapsedSpan(builder, size, marker, ignoreWidget) { + var widget = !ignoreWidget && marker.widgetNode + if (widget) { builder.map.push(builder.pos, builder.pos + size, widget) } + if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { + if (!widget) + { widget = builder.content.appendChild(document.createElement("span")) } + widget.setAttribute("cm-marker", marker.id) + } + if (widget) { + builder.cm.display.input.setUneditable(widget) + builder.content.appendChild(widget) + } + builder.pos += size + builder.trailingSpace = false +} + +// Outputs a number of spans to make up a line, taking highlighting +// and marked text into account. +function insertLineContent(line, builder, styles) { + var spans = line.markedSpans, allText = line.text, at = 0 + if (!spans) { + for (var i$1 = 1; i$1 < styles.length; i$1+=2) + { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)) } + return + } + + var len = allText.length, pos = 0, i = 1, text = "", style, css + var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = title = css = "" + collapsed = null; nextChange = Infinity + var foundBookmarks = [], endStyles = (void 0) + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], m = sp.marker + if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { + foundBookmarks.push(m) + } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { + if (sp.to != null && sp.to != pos && nextChange > sp.to) { + nextChange = sp.to + spanEndStyle = "" + } + if (m.className) { spanStyle += " " + m.className } + if (m.css) { css = (css ? css + ";" : "") + m.css } + if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle } + if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to) } + if (m.title && !title) { title = m.title } + if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) + { collapsed = sp } + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from + } + } + if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) + { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1] } } } + + if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) + { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]) } } + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, + collapsed.marker, collapsed.from == null) + if (collapsed.to == null) { return } + if (collapsed.to == pos) { collapsed = false } + } + } + if (pos >= len) { break } + + var upto = Math.min(len, nextChange) + while (true) { + if (text) { + var end = pos + text.length + if (!collapsed) { + var tokenText = end > upto ? text.slice(0, upto - pos) : text + builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, + spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css) + } + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break} + pos = end + spanStartStyle = "" + } + text = allText.slice(at, at = styles[i++]) + style = interpretTokenStyle(styles[i++], builder.cm.options) + } + } +} + + +// These objects are used to represent the visible (currently drawn) +// part of the document. A LineView may correspond to multiple +// logical lines, if those are connected by collapsed ranges. +function LineView(doc, line, lineN) { + // The starting line + this.line = line + // Continuing lines, if any + this.rest = visualLineContinued(line) + // Number of logical lines in this visual line + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1 + this.node = this.text = null + this.hidden = lineIsHidden(doc, line) +} + +// Create a range of LineView objects for the given lines. +function buildViewArray(cm, from, to) { + var array = [], nextPos + for (var pos = from; pos < to; pos = nextPos) { + var view = new LineView(cm.doc, getLine(cm.doc, pos), pos) + nextPos = pos + view.size + array.push(view) + } + return array +} + +var operationGroup = null + +function pushOperation(op) { + if (operationGroup) { + operationGroup.ops.push(op) + } else { + op.ownsGroup = operationGroup = { + ops: [op], + delayedCallbacks: [] + } + } +} + +function fireCallbacksForOps(group) { + // Calls delayed callbacks and cursorActivity handlers until no + // new ones appear + var callbacks = group.delayedCallbacks, i = 0 + do { + for (; i < callbacks.length; i++) + { callbacks[i].call(null) } + for (var j = 0; j < group.ops.length; j++) { + var op = group.ops[j] + if (op.cursorActivityHandlers) + { while (op.cursorActivityCalled < op.cursorActivityHandlers.length) + { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm) } } + } + } while (i < callbacks.length) +} + +function finishOperation(op, endCb) { + var group = op.ownsGroup + if (!group) { return } + + try { fireCallbacksForOps(group) } + finally { + operationGroup = null + endCb(group) + } +} + +var orphanDelayedCallbacks = null + +// Often, we want to signal events at a point where we are in the +// middle of some work, but don't want the handler to start calling +// other methods on the editor, which might be in an inconsistent +// state or simply not expect any other events to happen. +// signalLater looks whether there are any handlers, and schedules +// them to be executed when the last operation ends, or, if no +// operation is active, when a timeout fires. +function signalLater(emitter, type /*, values...*/) { + var arr = getHandlers(emitter, type) + if (!arr.length) { return } + var args = Array.prototype.slice.call(arguments, 2), list + if (operationGroup) { + list = operationGroup.delayedCallbacks + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks + } else { + list = orphanDelayedCallbacks = [] + setTimeout(fireOrphanDelayed, 0) + } + var loop = function ( i ) { + list.push(function () { return arr[i].apply(null, args); }) + }; + + for (var i = 0; i < arr.length; ++i) + loop( i ); +} + +function fireOrphanDelayed() { + var delayed = orphanDelayedCallbacks + orphanDelayedCallbacks = null + for (var i = 0; i < delayed.length; ++i) { delayed[i]() } +} + +// When an aspect of a line changes, a string is added to +// lineView.changes. This updates the relevant part of the line's +// DOM structure. +function updateLineForChanges(cm, lineView, lineN, dims) { + for (var j = 0; j < lineView.changes.length; j++) { + var type = lineView.changes[j] + if (type == "text") { updateLineText(cm, lineView) } + else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims) } + else if (type == "class") { updateLineClasses(cm, lineView) } + else if (type == "widget") { updateLineWidgets(cm, lineView, dims) } + } + lineView.changes = null +} + +// Lines with gutter elements, widgets or a background class need to +// be wrapped, and have the extra elements added to the wrapper div +function ensureLineWrapped(lineView) { + if (lineView.node == lineView.text) { + lineView.node = elt("div", null, null, "position: relative") + if (lineView.text.parentNode) + { lineView.text.parentNode.replaceChild(lineView.node, lineView.text) } + lineView.node.appendChild(lineView.text) + if (ie && ie_version < 8) { lineView.node.style.zIndex = 2 } + } + return lineView.node +} + +function updateLineBackground(cm, lineView) { + var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass + if (cls) { cls += " CodeMirror-linebackground" } + if (lineView.background) { + if (cls) { lineView.background.className = cls } + else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null } + } else if (cls) { + var wrap = ensureLineWrapped(lineView) + lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild) + cm.display.input.setUneditable(lineView.background) + } +} + +// Wrapper around buildLineContent which will reuse the structure +// in display.externalMeasured when possible. +function getLineContent(cm, lineView) { + var ext = cm.display.externalMeasured + if (ext && ext.line == lineView.line) { + cm.display.externalMeasured = null + lineView.measure = ext.measure + return ext.built + } + return buildLineContent(cm, lineView) +} + +// Redraw the line's text. Interacts with the background and text +// classes because the mode may output tokens that influence these +// classes. +function updateLineText(cm, lineView) { + var cls = lineView.text.className + var built = getLineContent(cm, lineView) + if (lineView.text == lineView.node) { lineView.node = built.pre } + lineView.text.parentNode.replaceChild(built.pre, lineView.text) + lineView.text = built.pre + if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { + lineView.bgClass = built.bgClass + lineView.textClass = built.textClass + updateLineClasses(cm, lineView) + } else if (cls) { + lineView.text.className = cls + } +} + +function updateLineClasses(cm, lineView) { + updateLineBackground(cm, lineView) + if (lineView.line.wrapClass) + { ensureLineWrapped(lineView).className = lineView.line.wrapClass } + else if (lineView.node != lineView.text) + { lineView.node.className = "" } + var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass + lineView.text.className = textClass || "" +} + +function updateLineGutter(cm, lineView, lineN, dims) { + if (lineView.gutter) { + lineView.node.removeChild(lineView.gutter) + lineView.gutter = null + } + if (lineView.gutterBackground) { + lineView.node.removeChild(lineView.gutterBackground) + lineView.gutterBackground = null + } + if (lineView.line.gutterClass) { + var wrap = ensureLineWrapped(lineView) + lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, + ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px")) + cm.display.input.setUneditable(lineView.gutterBackground) + wrap.insertBefore(lineView.gutterBackground, lineView.text) + } + var markers = lineView.line.gutterMarkers + if (cm.options.lineNumbers || markers) { + var wrap$1 = ensureLineWrapped(lineView) + var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px")) + cm.display.input.setUneditable(gutterWrap) + wrap$1.insertBefore(gutterWrap, lineView.text) + if (lineView.line.gutterClass) + { gutterWrap.className += " " + lineView.line.gutterClass } + if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) + { lineView.lineNumber = gutterWrap.appendChild( + elt("div", lineNumberFor(cm.options, lineN), + "CodeMirror-linenumber CodeMirror-gutter-elt", + ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))) } + if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) { + var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id] + if (found) + { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", + ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))) } + } } + } +} + +function updateLineWidgets(cm, lineView, dims) { + if (lineView.alignable) { lineView.alignable = null } + for (var node = lineView.node.firstChild, next = (void 0); node; node = next) { + next = node.nextSibling + if (node.className == "CodeMirror-linewidget") + { lineView.node.removeChild(node) } + } + insertLineWidgets(cm, lineView, dims) +} + +// Build a line's DOM representation from scratch +function buildLineElement(cm, lineView, lineN, dims) { + var built = getLineContent(cm, lineView) + lineView.text = lineView.node = built.pre + if (built.bgClass) { lineView.bgClass = built.bgClass } + if (built.textClass) { lineView.textClass = built.textClass } + + updateLineClasses(cm, lineView) + updateLineGutter(cm, lineView, lineN, dims) + insertLineWidgets(cm, lineView, dims) + return lineView.node +} + +// A lineView may contain multiple logical lines (when merged by +// collapsed spans). The widgets for all of them need to be drawn. +function insertLineWidgets(cm, lineView, dims) { + insertLineWidgetsFor(cm, lineView.line, lineView, dims, true) + if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) + { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false) } } +} + +function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { + if (!line.widgets) { return } + var wrap = ensureLineWrapped(lineView) + for (var i = 0, ws = line.widgets; i < ws.length; ++i) { + var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget") + if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true") } + positionLineWidget(widget, node, lineView, dims) + cm.display.input.setUneditable(node) + if (allowAbove && widget.above) + { wrap.insertBefore(node, lineView.gutter || lineView.text) } + else + { wrap.appendChild(node) } + signalLater(widget, "redraw") + } +} + +function positionLineWidget(widget, node, lineView, dims) { + if (widget.noHScroll) { + ;(lineView.alignable || (lineView.alignable = [])).push(node) + var width = dims.wrapperWidth + node.style.left = dims.fixedPos + "px" + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth + node.style.paddingLeft = dims.gutterTotalWidth + "px" + } + node.style.width = width + "px" + } + if (widget.coverGutter) { + node.style.zIndex = 5 + node.style.position = "relative" + if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px" } + } +} + +function widgetHeight(widget) { + if (widget.height != null) { return widget.height } + var cm = widget.doc.cm + if (!cm) { return 0 } + if (!contains(document.body, widget.node)) { + var parentStyle = "position: relative;" + if (widget.coverGutter) + { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;" } + if (widget.noHScroll) + { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;" } + removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)) + } + return widget.height = widget.node.parentNode.offsetHeight +} + +// Return true when the given mouse event happened in a widget +function eventInWidget(display, e) { + for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { + if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || + (n.parentNode == display.sizer && n != display.mover)) + { return true } + } +} + +// POSITION MEASUREMENT + +function paddingTop(display) {return display.lineSpace.offsetTop} +function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight} +function paddingH(display) { + if (display.cachedPaddingH) { return display.cachedPaddingH } + var e = removeChildrenAndAdd(display.measure, elt("pre", "x")) + var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle + var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)} + if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data } + return data +} + +function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth } +function displayWidth(cm) { + return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth +} +function displayHeight(cm) { + return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight +} + +// Ensure the lineView.wrapping.heights array is populated. This is +// an array of bottom offsets for the lines that make up a drawn +// line. When lineWrapping is on, there might be more than one +// height. +function ensureLineHeights(cm, lineView, rect) { + var wrapping = cm.options.lineWrapping + var curWidth = wrapping && displayWidth(cm) + if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { + var heights = lineView.measure.heights = [] + if (wrapping) { + lineView.measure.width = curWidth + var rects = lineView.text.firstChild.getClientRects() + for (var i = 0; i < rects.length - 1; i++) { + var cur = rects[i], next = rects[i + 1] + if (Math.abs(cur.bottom - next.bottom) > 2) + { heights.push((cur.bottom + next.top) / 2 - rect.top) } + } + } + heights.push(rect.bottom - rect.top) + } +} + +// Find a line map (mapping character offsets to text nodes) and a +// measurement cache for the given line number. (A line view might +// contain multiple lines when collapsed ranges are present.) +function mapFromLineView(lineView, line, lineN) { + if (lineView.line == line) + { return {map: lineView.measure.map, cache: lineView.measure.cache} } + for (var i = 0; i < lineView.rest.length; i++) + { if (lineView.rest[i] == line) + { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } } + for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) + { if (lineNo(lineView.rest[i$1]) > lineN) + { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } } +} + +// Render a line into the hidden node display.externalMeasured. Used +// when measurement is needed for a line that's not in the viewport. +function updateExternalMeasurement(cm, line) { + line = visualLine(line) + var lineN = lineNo(line) + var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN) + view.lineN = lineN + var built = view.built = buildLineContent(cm, view) + view.text = built.pre + removeChildrenAndAdd(cm.display.lineMeasure, built.pre) + return view +} + +// Get a {top, bottom, left, right} box (in line-local coordinates) +// for a given character. +function measureChar(cm, line, ch, bias) { + return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias) +} + +// Find a line view that corresponds to the given line number. +function findViewForLine(cm, lineN) { + if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) + { return cm.display.view[findViewIndex(cm, lineN)] } + var ext = cm.display.externalMeasured + if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) + { return ext } +} + +// Measurement can be split in two steps, the set-up work that +// applies to the whole line, and the measurement of the actual +// character. Functions like coordsChar, that need to do a lot of +// measurements in a row, can thus ensure that the set-up work is +// only done once. +function prepareMeasureForLine(cm, line) { + var lineN = lineNo(line) + var view = findViewForLine(cm, lineN) + if (view && !view.text) { + view = null + } else if (view && view.changes) { + updateLineForChanges(cm, view, lineN, getDimensions(cm)) + cm.curOp.forceUpdate = true + } + if (!view) + { view = updateExternalMeasurement(cm, line) } + + var info = mapFromLineView(view, line, lineN) + return { + line: line, view: view, rect: null, + map: info.map, cache: info.cache, before: info.before, + hasHeights: false + } +} + +// Given a prepared measurement object, measures the position of an +// actual character (or fetches it from the cache). +function measureCharPrepared(cm, prepared, ch, bias, varHeight) { + if (prepared.before) { ch = -1 } + var key = ch + (bias || ""), found + if (prepared.cache.hasOwnProperty(key)) { + found = prepared.cache[key] + } else { + if (!prepared.rect) + { prepared.rect = prepared.view.text.getBoundingClientRect() } + if (!prepared.hasHeights) { + ensureLineHeights(cm, prepared.view, prepared.rect) + prepared.hasHeights = true + } + found = measureCharInner(cm, prepared, ch, bias) + if (!found.bogus) { prepared.cache[key] = found } + } + return {left: found.left, right: found.right, + top: varHeight ? found.rtop : found.top, + bottom: varHeight ? found.rbottom : found.bottom} +} + +var nullRect = {left: 0, right: 0, top: 0, bottom: 0} + +function nodeAndOffsetInLineMap(map, ch, bias) { + var node, start, end, collapse, mStart, mEnd + // First, search the line map for the text node corresponding to, + // or closest to, the target character. + for (var i = 0; i < map.length; i += 3) { + mStart = map[i] + mEnd = map[i + 1] + if (ch < mStart) { + start = 0; end = 1 + collapse = "left" + } else if (ch < mEnd) { + start = ch - mStart + end = start + 1 + } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { + end = mEnd - mStart + start = end - 1 + if (ch >= mEnd) { collapse = "right" } + } + if (start != null) { + node = map[i + 2] + if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) + { collapse = bias } + if (bias == "left" && start == 0) + { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { + node = map[(i -= 3) + 2] + collapse = "left" + } } + if (bias == "right" && start == mEnd - mStart) + { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { + node = map[(i += 3) + 2] + collapse = "right" + } } + break + } + } + return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd} +} + +function getUsefulRect(rects, bias) { + var rect = nullRect + if (bias == "left") { for (var i = 0; i < rects.length; i++) { + if ((rect = rects[i]).left != rect.right) { break } + } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) { + if ((rect = rects[i$1]).left != rect.right) { break } + } } + return rect +} + +function measureCharInner(cm, prepared, ch, bias) { + var place = nodeAndOffsetInLineMap(prepared.map, ch, bias) + var node = place.node, start = place.start, end = place.end, collapse = place.collapse + + var rect + if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. + for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned + while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start } + while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end } + if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) + { rect = node.parentNode.getBoundingClientRect() } + else + { rect = getUsefulRect(range(node, start, end).getClientRects(), bias) } + if (rect.left || rect.right || start == 0) { break } + end = start + start = start - 1 + collapse = "right" + } + if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect) } + } else { // If it is a widget, simply get the box for the whole widget. + if (start > 0) { collapse = bias = "right" } + var rects + if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) + { rect = rects[bias == "right" ? rects.length - 1 : 0] } + else + { rect = node.getBoundingClientRect() } + } + if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { + var rSpan = node.parentNode.getClientRects()[0] + if (rSpan) + { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom} } + else + { rect = nullRect } + } + + var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top + var mid = (rtop + rbot) / 2 + var heights = prepared.view.measure.heights + var i = 0 + for (; i < heights.length - 1; i++) + { if (mid < heights[i]) { break } } + var top = i ? heights[i - 1] : 0, bot = heights[i] + var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, + right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, + top: top, bottom: bot} + if (!rect.left && !rect.right) { result.bogus = true } + if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot } + + return result +} + +// Work around problem with bounding client rects on ranges being +// returned incorrectly when zoomed on IE10 and below. +function maybeUpdateRectForZooming(measure, rect) { + if (!window.screen || screen.logicalXDPI == null || + screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) + { return rect } + var scaleX = screen.logicalXDPI / screen.deviceXDPI + var scaleY = screen.logicalYDPI / screen.deviceYDPI + return {left: rect.left * scaleX, right: rect.right * scaleX, + top: rect.top * scaleY, bottom: rect.bottom * scaleY} +} + +function clearLineMeasurementCacheFor(lineView) { + if (lineView.measure) { + lineView.measure.cache = {} + lineView.measure.heights = null + if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) + { lineView.measure.caches[i] = {} } } + } +} + +function clearLineMeasurementCache(cm) { + cm.display.externalMeasure = null + removeChildren(cm.display.lineMeasure) + for (var i = 0; i < cm.display.view.length; i++) + { clearLineMeasurementCacheFor(cm.display.view[i]) } +} + +function clearCaches(cm) { + clearLineMeasurementCache(cm) + cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null + if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true } + cm.display.lineNumChars = null +} + +function pageScrollX() { + // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206 + // which causes page_Offset and bounding client rects to use + // different reference viewports and invalidate our calculations. + if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) } + return window.pageXOffset || (document.documentElement || document.body).scrollLeft +} +function pageScrollY() { + if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) } + return window.pageYOffset || (document.documentElement || document.body).scrollTop +} + +function widgetTopHeight(lineObj) { + var height = 0 + if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) + { height += widgetHeight(lineObj.widgets[i]) } } } + return height +} + +// Converts a {top, bottom, left, right} box from line-local +// coordinates into another coordinate system. Context may be one of +// "line", "div" (display.lineDiv), "local"./null (editor), "window", +// or "page". +function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { + if (!includeWidgets) { + var height = widgetTopHeight(lineObj) + rect.top += height; rect.bottom += height + } + if (context == "line") { return rect } + if (!context) { context = "local" } + var yOff = heightAtLine(lineObj) + if (context == "local") { yOff += paddingTop(cm.display) } + else { yOff -= cm.display.viewOffset } + if (context == "page" || context == "window") { + var lOff = cm.display.lineSpace.getBoundingClientRect() + yOff += lOff.top + (context == "window" ? 0 : pageScrollY()) + var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()) + rect.left += xOff; rect.right += xOff + } + rect.top += yOff; rect.bottom += yOff + return rect +} + +// Coverts a box from "div" coords to another coordinate system. +// Context may be "window", "page", "div", or "local"./null. +function fromCoordSystem(cm, coords, context) { + if (context == "div") { return coords } + var left = coords.left, top = coords.top + // First move into "page" coordinate system + if (context == "page") { + left -= pageScrollX() + top -= pageScrollY() + } else if (context == "local" || !context) { + var localBox = cm.display.sizer.getBoundingClientRect() + left += localBox.left + top += localBox.top + } + + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect() + return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} +} + +function charCoords(cm, pos, context, lineObj, bias) { + if (!lineObj) { lineObj = getLine(cm.doc, pos.line) } + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context) +} + +// Returns a box for a given cursor position, which may have an +// 'other' property containing the position of the secondary cursor +// on a bidi boundary. +// A cursor Pos(line, char, "before") is on the same visual line as `char - 1` +// and after `char - 1` in writing order of `char - 1` +// A cursor Pos(line, char, "after") is on the same visual line as `char` +// and before `char` in writing order of `char` +// Examples (upper-case letters are RTL, lower-case are LTR): +// Pos(0, 1, ...) +// before after +// ab a|b a|b +// aB a|B aB| +// Ab |Ab A|b +// AB B|A B|A +// Every position after the last character on a line is considered to stick +// to the last character on the line. +function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { + lineObj = lineObj || getLine(cm.doc, pos.line) + if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj) } + function get(ch, right) { + var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight) + if (right) { m.left = m.right; } else { m.right = m.left } + return intoCoordSystem(cm, lineObj, m, context) + } + var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky + if (ch >= lineObj.text.length) { + ch = lineObj.text.length + sticky = "before" + } else if (ch <= 0) { + ch = 0 + sticky = "after" + } + if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") } + + function getBidi(ch, partPos, invert) { + var part = order[partPos], right = part.level == 1 + return get(invert ? ch - 1 : ch, right != invert) + } + var partPos = getBidiPartAt(order, ch, sticky) + var other = bidiOther + var val = getBidi(ch, partPos, sticky == "before") + if (other != null) { val.other = getBidi(ch, other, sticky != "before") } + return val +} + +// Used to cheaply estimate the coordinates for a position. Used for +// intermediate scroll updates. +function estimateCoords(cm, pos) { + var left = 0 + pos = clipPos(cm.doc, pos) + if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch } + var lineObj = getLine(cm.doc, pos.line) + var top = heightAtLine(lineObj) + paddingTop(cm.display) + return {left: left, right: left, top: top, bottom: top + lineObj.height} +} + +// Positions returned by coordsChar contain some extra information. +// xRel is the relative x position of the input coordinates compared +// to the found position (so xRel > 0 means the coordinates are to +// the right of the character position, for example). When outside +// is true, that means the coordinates lie outside the line's +// vertical range. +function PosWithInfo(line, ch, sticky, outside, xRel) { + var pos = Pos(line, ch, sticky) + pos.xRel = xRel + if (outside) { pos.outside = true } + return pos +} + +// Compute the character position closest to the given coordinates. +// Input must be lineSpace-local ("div" coordinate system). +function coordsChar(cm, x, y) { + var doc = cm.doc + y += cm.display.viewOffset + if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) } + var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1 + if (lineN > last) + { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) } + if (x < 0) { x = 0 } + + var lineObj = getLine(doc, lineN) + for (;;) { + var found = coordsCharInner(cm, lineObj, lineN, x, y) + var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0)) + if (!collapsed) { return found } + var rangeEnd = collapsed.find(1) + if (rangeEnd.line == lineN) { return rangeEnd } + lineObj = getLine(doc, lineN = rangeEnd.line) + } +} + +function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { + y -= widgetTopHeight(lineObj) + var end = lineObj.text.length + var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0) + end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end) + return {begin: begin, end: end} +} + +function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { + if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj) } + var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top + return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop) +} + +// Returns true if the given side of a box is after the given +// coordinates, in top-to-bottom, left-to-right order. +function boxIsAfter(box, x, y, left) { + return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x +} + +function coordsCharInner(cm, lineObj, lineNo, x, y) { + // Move y into line-local coordinate space + y -= heightAtLine(lineObj) + var preparedMeasure = prepareMeasureForLine(cm, lineObj) + // When directly calling `measureCharPrepared`, we have to adjust + // for the widgets at this line. + var widgetHeight = widgetTopHeight(lineObj) + var begin = 0, end = lineObj.text.length, ltr = true + + var order = getOrder(lineObj, cm.doc.direction) + // If the line isn't plain left-to-right text, first figure out + // which bidi section the coordinates fall into. + if (order) { + var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart) + (cm, lineObj, lineNo, preparedMeasure, order, x, y) + ltr = part.level != 1 + // The awkward -1 offsets are needed because findFirst (called + // on these below) will treat its first bound as inclusive, + // second as exclusive, but we want to actually address the + // characters in the part's range + begin = ltr ? part.from : part.to - 1 + end = ltr ? part.to : part.from - 1 + } + + // A binary search to find the first character whose bounding box + // starts after the coordinates. If we run across any whose box wrap + // the coordinates, store that. + var chAround = null, boxAround = null + var ch = findFirst(function (ch) { + var box = measureCharPrepared(cm, preparedMeasure, ch) + box.top += widgetHeight; box.bottom += widgetHeight + if (!boxIsAfter(box, x, y, false)) { return false } + if (box.top <= y && box.left <= x) { + chAround = ch + boxAround = box + } + return true + }, begin, end) + + var baseX, sticky, outside = false + // If a box around the coordinates was found, use that + if (boxAround) { + // Distinguish coordinates nearer to the left or right side of the box + var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr + ch = chAround + (atStart ? 0 : 1) + sticky = atStart ? "after" : "before" + baseX = atLeft ? boxAround.left : boxAround.right + } else { + // (Adjust for extended bound, if necessary.) + if (!ltr && (ch == end || ch == begin)) { ch++ } + // To determine which side to associate with, get the box to the + // left of the character and compare it's vertical position to the + // coordinates + sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : + (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ? + "after" : "before" + // Now get accurate coordinates for this place, in order to get a + // base X position + var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure) + baseX = coords.left + outside = y < coords.top || y >= coords.bottom + } + + ch = skipExtendingChars(lineObj.text, ch, 1) + return PosWithInfo(lineNo, ch, sticky, outside, x - baseX) +} + +function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) { + // Bidi parts are sorted left-to-right, and in a non-line-wrapping + // situation, we can take this ordering to correspond to the visual + // ordering. This finds the first part whose end is after the given + // coordinates. + var index = findFirst(function (i) { + var part = order[i], ltr = part.level != 1 + return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"), + "line", lineObj, preparedMeasure), x, y, true) + }, 0, order.length - 1) + var part = order[index] + // If this isn't the first part, the part's start is also after + // the coordinates, and the coordinates aren't on the same line as + // that start, move one part back. + if (index > 0) { + var ltr = part.level != 1 + var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"), + "line", lineObj, preparedMeasure) + if (boxIsAfter(start, x, y, true) && start.top > y) + { part = order[index - 1] } + } + return part +} + +function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { + // In a wrapped line, rtl text on wrapping boundaries can do things + // that don't correspond to the ordering in our `order` array at + // all, so a binary search doesn't work, and we want to return a + // part that only spans one line so that the binary search in + // coordsCharInner is safe. As such, we first find the extent of the + // wrapped line, and then do a flat search in which we discard any + // spans that aren't on the line. + var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); + var begin = ref.begin; + var end = ref.end; + if (/\s/.test(lineObj.text.charAt(end - 1))) { end-- } + var part = null, closestDist = null + for (var i = 0; i < order.length; i++) { + var p = order[i] + if (p.from >= end || p.to <= begin) { continue } + var ltr = p.level != 1 + var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right + // Weigh against spans ending before this, so that they are only + // picked if nothing ends after + var dist = endX < x ? x - endX + 1e9 : endX - x + if (!part || closestDist > dist) { + part = p + closestDist = dist + } + } + if (!part) { part = order[order.length - 1] } + // Clip the part to the wrapped line. + if (part.from < begin) { part = {from: begin, to: part.to, level: part.level} } + if (part.to > end) { part = {from: part.from, to: end, level: part.level} } + return part +} + +var measureText +// Compute the default text height. +function textHeight(display) { + if (display.cachedTextHeight != null) { return display.cachedTextHeight } + if (measureText == null) { + measureText = elt("pre") + // Measure a bunch of lines, for browsers that compute + // fractional heights. + for (var i = 0; i < 49; ++i) { + measureText.appendChild(document.createTextNode("x")) + measureText.appendChild(elt("br")) + } + measureText.appendChild(document.createTextNode("x")) + } + removeChildrenAndAdd(display.measure, measureText) + var height = measureText.offsetHeight / 50 + if (height > 3) { display.cachedTextHeight = height } + removeChildren(display.measure) + return height || 1 +} + +// Compute the default character width. +function charWidth(display) { + if (display.cachedCharWidth != null) { return display.cachedCharWidth } + var anchor = elt("span", "xxxxxxxxxx") + var pre = elt("pre", [anchor]) + removeChildrenAndAdd(display.measure, pre) + var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10 + if (width > 2) { display.cachedCharWidth = width } + return width || 10 +} + +// Do a bulk-read of the DOM positions and sizes needed to draw the +// view, so that we don't interleave reading and writing to the DOM. +function getDimensions(cm) { + var d = cm.display, left = {}, width = {} + var gutterLeft = d.gutters.clientLeft + for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { + left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft + width[cm.options.gutters[i]] = n.clientWidth + } + return {fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth} +} + +// Computes display.scroller.scrollLeft + display.gutters.offsetWidth, +// but using getBoundingClientRect to get a sub-pixel-accurate +// result. +function compensateForHScroll(display) { + return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left +} + +// Returns a function that estimates the height of a line, to use as +// first approximation until the line becomes visible (and is thus +// properly measurable). +function estimateHeight(cm) { + var th = textHeight(cm.display), wrapping = cm.options.lineWrapping + var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3) + return function (line) { + if (lineIsHidden(cm.doc, line)) { return 0 } + + var widgetsHeight = 0 + if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { + if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height } + } } + + if (wrapping) + { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th } + else + { return widgetsHeight + th } + } +} + +function estimateLineHeights(cm) { + var doc = cm.doc, est = estimateHeight(cm) + doc.iter(function (line) { + var estHeight = est(line) + if (estHeight != line.height) { updateLineHeight(line, estHeight) } + }) +} + +// Given a mouse event, find the corresponding position. If liberal +// is false, it checks whether a gutter or scrollbar was clicked, +// and returns null if it was. forRect is used by rectangular +// selections, and tries to estimate a character position even for +// coordinates beyond the right of the text. +function posFromMouse(cm, e, liberal, forRect) { + var display = cm.display + if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null } + + var x, y, space = display.lineSpace.getBoundingClientRect() + // Fails unpredictably on IE[67] when mouse is dragged around quickly. + try { x = e.clientX - space.left; y = e.clientY - space.top } + catch (e) { return null } + var coords = coordsChar(cm, x, y), line + if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { + var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length + coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)) + } + return coords +} + +// Find the view element corresponding to a given line. Return null +// when the line isn't visible. +function findViewIndex(cm, n) { + if (n >= cm.display.viewTo) { return null } + n -= cm.display.viewFrom + if (n < 0) { return null } + var view = cm.display.view + for (var i = 0; i < view.length; i++) { + n -= view[i].size + if (n < 0) { return i } + } +} + +function updateSelection(cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()) +} + +function prepareSelection(cm, primary) { + if ( primary === void 0 ) primary = true; + + var doc = cm.doc, result = {} + var curFragment = result.cursors = document.createDocumentFragment() + var selFragment = result.selection = document.createDocumentFragment() + + for (var i = 0; i < doc.sel.ranges.length; i++) { + if (!primary && i == doc.sel.primIndex) { continue } + var range = doc.sel.ranges[i] + if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue } + var collapsed = range.empty() + if (collapsed || cm.options.showCursorWhenSelecting) + { drawSelectionCursor(cm, range.head, curFragment) } + if (!collapsed) + { drawSelectionRange(cm, range, selFragment) } + } + return result +} + +// Draws a cursor for the given range +function drawSelectionCursor(cm, head, output) { + var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine) + + var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")) + cursor.style.left = (pos.left-(window.heartbeat && 2 || 0)) + "px"; + cursor.style.top = (pos.top+(window.heartbeat && 5 || 0)) + "px"; // #CUSTOM + cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px" + + if (pos.other) { + // Secondary cursor, shown when on a 'jump' in bi-directional text + var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")) + otherCursor.style.display = ""; + otherCursor.style.left = (pos.other.left-(window.heartbeat && 2 || 0)) + "px"; + otherCursor.style.top = (pos.other.top+(window.heartbeat && 5 || 0)) + "px"; // #CUSTOM + otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px" + } +} + +function cmpCoords(a, b) { return a.top - b.top || a.left - b.left } + +// Draws the given range as a highlighted selection +function drawSelectionRange(cm, range, output) { + var display = cm.display, doc = cm.doc + var fragment = document.createDocumentFragment() + var padding = paddingH(cm.display), leftSide = padding.left + var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right + var docLTR = doc.direction == "ltr" + + function add(left, top, width, bottom) { + if (top < 0) { top = 0 } + top = Math.round(top) + bottom = Math.round(bottom) + fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px"))) + } + + function drawForLine(line, fromArg, toArg) { + var lineObj = getLine(doc, line) + var lineLen = lineObj.text.length + var start, end + function coords(ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias) + } + + function wrapX(pos, dir, side) { + var extent = wrappedLineExtentChar(cm, lineObj, null, pos) + var prop = (dir == "ltr") == (side == "after") ? "left" : "right" + var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1) + return coords(ch, prop)[prop] + } + + var order = getOrder(lineObj, doc.direction) + iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) { + var ltr = dir == "ltr" + var fromPos = coords(from, ltr ? "left" : "right") + var toPos = coords(to - 1, ltr ? "right" : "left") + + var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen + var first = i == 0, last = !order || i == order.length - 1 + if (toPos.top - fromPos.top <= 3) { // Single line + var openLeft = (docLTR ? openStart : openEnd) && first + var openRight = (docLTR ? openEnd : openStart) && last + var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left + var right = openRight ? rightSide : (ltr ? toPos : fromPos).right + add(left, fromPos.top, right - left, fromPos.bottom) + } else { // Multiple lines + var topLeft, topRight, botLeft, botRight + if (ltr) { + topLeft = docLTR && openStart && first ? leftSide : fromPos.left + topRight = docLTR ? rightSide : wrapX(from, dir, "before") + botLeft = docLTR ? leftSide : wrapX(to, dir, "after") + botRight = docLTR && openEnd && last ? rightSide : toPos.right + } else { + topLeft = !docLTR ? leftSide : wrapX(from, dir, "before") + topRight = !docLTR && openStart && first ? rightSide : fromPos.right + botLeft = !docLTR && openEnd && last ? leftSide : toPos.left + botRight = !docLTR ? rightSide : wrapX(to, dir, "after") + } + add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom) + if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top) } + add(botLeft, toPos.top, botRight - botLeft, toPos.bottom) + } + + if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos } + if (cmpCoords(toPos, start) < 0) { start = toPos } + if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos } + if (cmpCoords(toPos, end) < 0) { end = toPos } + }) + return {start: start, end: end} + } + + var sFrom = range.from(), sTo = range.to() + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch) + } else { + var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line) + var singleVLine = visualLine(fromLine) == visualLine(toLine) + var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end + var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom) + add(leftSide, rightStart.top, rightStart.left, rightStart.bottom) + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom) + } + } + if (leftEnd.bottom < rightStart.top) + { add(leftSide, leftEnd.bottom, null, rightStart.top) } + } + + output.appendChild(fragment) +} + +// Cursor-blinking +function restartBlink(cm) { + if (!cm.state.focused) { return } + var display = cm.display + clearInterval(display.blinker) + var on = true + display.cursorDiv.style.visibility = "" + if (cm.options.cursorBlinkRate > 0) + { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; }, + cm.options.cursorBlinkRate) } + else if (cm.options.cursorBlinkRate < 0) + { display.cursorDiv.style.visibility = "hidden" } +} + +function ensureFocus(cm) { + if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm) } +} + +function delayBlurEvent(cm) { + cm.state.delayingBlurEvent = true + setTimeout(function () { if (cm.state.delayingBlurEvent) { + cm.state.delayingBlurEvent = false + onBlur(cm) + } }, 100) +} + +function onFocus(cm, e) { + if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false } + + if (cm.options.readOnly == "nocursor") { return } + if (!cm.state.focused) { + signal(cm, "focus", cm, e) + cm.state.focused = true + addClass(cm.display.wrapper, "CodeMirror-focused") + // This test prevents this from firing when a context + // menu is closed (since the input reset would kill the + // select-all detection hack) + if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { + cm.display.input.reset() + if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20) } // Issue #1730 + } + cm.display.input.receivedFocus() + } + restartBlink(cm) +} +function onBlur(cm, e) { + if (cm.state.delayingBlurEvent) { return } + + if (cm.state.focused) { + signal(cm, "blur", cm, e) + cm.state.focused = false + rmClass(cm.display.wrapper, "CodeMirror-focused") + } + clearInterval(cm.display.blinker) + setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false } }, 150) +} + +// Read the actual heights of the rendered lines, and update their +// stored heights to match. +function updateHeightsInViewport(cm) { + var display = cm.display + var prevBottom = display.lineDiv.offsetTop + for (var i = 0; i < display.view.length; i++) { + var cur = display.view[i], height = (void 0) + if (cur.hidden) { continue } + if (ie && ie_version < 8) { + var bot = cur.node.offsetTop + cur.node.offsetHeight + height = bot - prevBottom + prevBottom = bot + } else { + var box = cur.node.getBoundingClientRect() + height = box.bottom - box.top + } + var diff = cur.line.height - height + if (height < 2) { height = textHeight(display) } + if (diff > .005 || diff < -.005) { + updateLineHeight(cur.line, height) + updateWidgetHeight(cur.line) + if (cur.rest) { for (var j = 0; j < cur.rest.length; j++) + { updateWidgetHeight(cur.rest[j]) } } + } + } +} + +// Read and store the height of line widgets associated with the +// given line. +function updateWidgetHeight(line) { + if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) { + var w = line.widgets[i], parent = w.node.parentNode + if (parent) { w.height = parent.offsetHeight } + } } +} + +// Compute the lines that are visible in a given viewport (defaults +// the the current scroll position). viewport may contain top, +// height, and ensure (see op.scrollToPos) properties. +function visibleLines(display, doc, viewport) { + var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop + top = Math.floor(top - paddingTop(display)) + var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight + + var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom) + // Ensure is a {from: {line, ch}, to: {line, ch}} object, and + // forces those lines into the viewport (if possible). + if (viewport && viewport.ensure) { + var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line + if (ensureFrom < from) { + from = ensureFrom + to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight) + } else if (Math.min(ensureTo, doc.lastLine()) >= to) { + from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight) + to = ensureTo + } + } + return {from: from, to: Math.max(to, from + 1)} +} + +// Re-align line numbers and gutter marks to compensate for +// horizontal scrolling. +function alignHorizontally(cm) { + var display = cm.display, view = display.view + if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return } + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft + var gutterW = display.gutters.offsetWidth, left = comp + "px" + for (var i = 0; i < view.length; i++) { if (!view[i].hidden) { + if (cm.options.fixedGutter) { + if (view[i].gutter) + { view[i].gutter.style.left = left } + if (view[i].gutterBackground) + { view[i].gutterBackground.style.left = left } + } + var align = view[i].alignable + if (align) { for (var j = 0; j < align.length; j++) + { align[j].style.left = left } } + } } + if (cm.options.fixedGutter) + { display.gutters.style.left = (comp + gutterW) + "px" } +} + +// Used to ensure that the line number gutter is still the right +// size for the current document size. Returns true when an update +// is needed. +function maybeUpdateLineNumberWidth(cm) { + if (!cm.options.lineNumbers) { return false } + var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild(elt("div", [elt("div", last)], + "CodeMirror-linenumber CodeMirror-gutter-elt")) + var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW + display.lineGutter.style.width = "" + display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1 + display.lineNumWidth = display.lineNumInnerWidth + padding + display.lineNumChars = display.lineNumInnerWidth ? last.length : -1 + display.lineGutter.style.width = display.lineNumWidth + "px" + updateGutterSpace(cm) + return true + } + return false +} + +// SCROLLING THINGS INTO VIEW + +// If an editor sits on the top or bottom of the window, partially +// scrolled out of view, this ensures that the cursor is visible. +function maybeScrollWindow(cm, rect) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) { return } + + var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null + if (rect.top + box.top < 0) { doScroll = true } + else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false } + if (doScroll != null && !phantom) { + var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;")) + cm.display.lineSpace.appendChild(scrollNode) + scrollNode.scrollIntoView(doScroll) + cm.display.lineSpace.removeChild(scrollNode) + } +} + +// Scroll a given position into view (immediately), verifying that +// it actually became visible (as line heights are accurately +// measured, the position of something may 'drift' during drawing). +function scrollPosIntoView(cm, pos, end, margin) { + if (margin == null) { margin = 0 } + var rect + if (!cm.options.lineWrapping && pos == end) { + // Set pos and end to the cursor positions around the character pos sticks to + // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch + // If pos == Pos(_, 0, "before"), pos and end are unchanged + pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos + end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos + } + for (var limit = 0; limit < 5; limit++) { + var changed = false + var coords = cursorCoords(cm, pos) + var endCoords = !end || end == pos ? coords : cursorCoords(cm, end) + rect = {left: Math.min(coords.left, endCoords.left), + top: Math.min(coords.top, endCoords.top) - margin, + right: Math.max(coords.left, endCoords.left), + bottom: Math.max(coords.bottom, endCoords.bottom) + margin} + var scrollPos = calculateScrollPos(cm, rect) + var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft + if (scrollPos.scrollTop != null) { + updateScrollTop(cm, scrollPos.scrollTop) + if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true } + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft) + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true } + } + if (!changed) { break } + } + return rect +} + +// Scroll a given set of coordinates into view (immediately). +function scrollIntoView(cm, rect) { + var scrollPos = calculateScrollPos(cm, rect) + if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop) } + if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft) } +} + +// Calculate a new scroll position needed to scroll the given +// rectangle into view. Returns an object with scrollTop and +// scrollLeft properties. When these are undefined, the +// vertical/horizontal position does not need to be adjusted. +function calculateScrollPos(cm, rect) { + var display = cm.display, snapMargin = textHeight(cm.display) + if (rect.top < 0) { rect.top = 0 } + var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop + var screen = displayHeight(cm), result = {} + if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen } + var docBottom = cm.doc.height + paddingVert(display) + var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin + if (rect.top < screentop) { + result.scrollTop = atTop ? 0 : rect.top + } else if (rect.bottom > screentop + screen) { + var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen) + if (newTop != screentop) { result.scrollTop = newTop } + } + + var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft + var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0) + var tooWide = rect.right - rect.left > screenw + if (tooWide) { rect.right = rect.left + screenw } + if (rect.left < 10) + { result.scrollLeft = 0 } + else if (rect.left < screenleft) + { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)) } + else if (rect.right > screenw + screenleft - 3) + { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw } + return result +} + +// Store a relative adjustment to the scroll position in the current +// operation (to be applied when the operation finishes). +function addToScrollTop(cm, top) { + if (top == null) { return } + resolveScrollToPos(cm) + cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top +} + +// Make sure that at the end of the operation the current cursor is +// shown. +function ensureCursorVisible(cm) { + resolveScrollToPos(cm) + var cur = cm.getCursor() + cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin} +} + +function scrollToCoords(cm, x, y) { + if (x != null || y != null) { resolveScrollToPos(cm) } + if (x != null) { cm.curOp.scrollLeft = x } + if (y != null) { cm.curOp.scrollTop = y } +} + +function scrollToRange(cm, range) { + resolveScrollToPos(cm) + cm.curOp.scrollToPos = range +} + +// When an operation has its scrollToPos property set, and another +// scroll action is applied before the end of the operation, this +// 'simulates' scrolling that position into view in a cheap way, so +// that the effect of intermediate scroll commands is not ignored. +function resolveScrollToPos(cm) { + var range = cm.curOp.scrollToPos + if (range) { + cm.curOp.scrollToPos = null + var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to) + scrollToCoordsRange(cm, from, to, range.margin) + } +} + +function scrollToCoordsRange(cm, from, to, margin) { + var sPos = calculateScrollPos(cm, { + left: Math.min(from.left, to.left), + top: Math.min(from.top, to.top) - margin, + right: Math.max(from.right, to.right), + bottom: Math.max(from.bottom, to.bottom) + margin + }) + scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop) +} + +// Sync the scrollable area and scrollbars, ensure the viewport +// covers the visible area. +function updateScrollTop(cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) { return } + if (!gecko) { updateDisplaySimple(cm, {top: val}) } + setScrollTop(cm, val, true) + if (gecko) { updateDisplaySimple(cm) } + startWorker(cm, 100) +} + +function setScrollTop(cm, val, forceScroll) { + val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val) + if (cm.display.scroller.scrollTop == val && !forceScroll) { return } + cm.doc.scrollTop = val + cm.display.scrollbars.setScrollTop(val) + if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val } +} + +// Sync scroller and scrollbar, ensure the gutter elements are +// aligned. +function setScrollLeft(cm, val, isScroller, forceScroll) { + val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth) + if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return } + cm.doc.scrollLeft = val + alignHorizontally(cm) + if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val } + cm.display.scrollbars.setScrollLeft(val) +} + +// SCROLLBARS + +// Prepare DOM reads needed to update the scrollbars. Done in one +// shot to minimize update/measure roundtrips. +function measureForScrollbars(cm) { + var d = cm.display, gutterW = d.gutters.offsetWidth + var docH = Math.round(cm.doc.height + paddingVert(cm.display)) + return { + clientHeight: d.scroller.clientHeight, + viewHeight: d.wrapper.clientHeight, + scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, + viewWidth: d.wrapper.clientWidth, + barLeft: cm.options.fixedGutter ? gutterW : 0, + docHeight: docH, + scrollHeight: docH + scrollGap(cm) + d.barHeight, + nativeBarWidth: d.nativeBarWidth, + gutterWidth: gutterW + } +} + +var NativeScrollbars = function(place, scroll, cm) { + this.cm = cm + var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar") + var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar") + vert.tabIndex = horiz.tabIndex = -1 + place(vert); place(horiz) + + on(vert, "scroll", function () { + if (vert.clientHeight) { scroll(vert.scrollTop, "vertical") } + }) + on(horiz, "scroll", function () { + if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal") } + }) + + this.checkedZeroWidth = false + // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). + if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px" } +}; + +NativeScrollbars.prototype.update = function (measure) { + var needsH = measure.scrollWidth > measure.clientWidth + 1 + var needsV = measure.scrollHeight > measure.clientHeight + 1 + var sWidth = measure.nativeBarWidth + + if (needsV) { + this.vert.style.display = "block" + this.vert.style.bottom = needsH ? sWidth + "px" : "0" + var totalHeight = measure.viewHeight - (needsH ? sWidth : 0) + // A bug in IE8 can cause this value to be negative, so guard it. + this.vert.firstChild.style.height = + Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px" + } else { + this.vert.style.display = "" + this.vert.firstChild.style.height = "0" + } + + if (needsH) { + this.horiz.style.display = "block" + this.horiz.style.right = needsV ? sWidth + "px" : "0" + this.horiz.style.left = measure.barLeft + "px" + var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0) + this.horiz.firstChild.style.width = + Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px" + } else { + this.horiz.style.display = "" + this.horiz.firstChild.style.width = "0" + } + + if (!this.checkedZeroWidth && measure.clientHeight > 0) { + if (sWidth == 0) { this.zeroWidthHack() } + this.checkedZeroWidth = true + } + + return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} +}; + +NativeScrollbars.prototype.setScrollLeft = function (pos) { + if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos } + if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz") } +}; + +NativeScrollbars.prototype.setScrollTop = function (pos) { + if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos } + if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert") } +}; + +NativeScrollbars.prototype.zeroWidthHack = function () { + var w = mac && !mac_geMountainLion ? "12px" : "18px" + this.horiz.style.height = this.vert.style.width = w + this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none" + this.disableHoriz = new Delayed + this.disableVert = new Delayed +}; + +NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { + bar.style.pointerEvents = "auto" + function maybeDisable() { + // To find out whether the scrollbar is still visible, we + // check whether the element under the pixel in the bottom + // right corner of the scrollbar box is the scrollbar box + // itself (when the bar is still visible) or its filler child + // (when the bar is hidden). If it is still visible, we keep + // it enabled, if it's hidden, we disable pointer events. + var box = bar.getBoundingClientRect() + var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) + : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1) + if (elt != bar) { bar.style.pointerEvents = "none" } + else { delay.set(1000, maybeDisable) } + } + delay.set(1000, maybeDisable) +}; + +NativeScrollbars.prototype.clear = function () { + var parent = this.horiz.parentNode + parent.removeChild(this.horiz) + parent.removeChild(this.vert) +}; + +var NullScrollbars = function () {}; + +NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} }; +NullScrollbars.prototype.setScrollLeft = function () {}; +NullScrollbars.prototype.setScrollTop = function () {}; +NullScrollbars.prototype.clear = function () {}; + +function updateScrollbars(cm, measure) { + if (!measure) { measure = measureForScrollbars(cm) } + var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight + updateScrollbarsInner(cm, measure) + for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { + if (startWidth != cm.display.barWidth && cm.options.lineWrapping) + { updateHeightsInViewport(cm) } + updateScrollbarsInner(cm, measureForScrollbars(cm)) + startWidth = cm.display.barWidth; startHeight = cm.display.barHeight + } +} + +// Re-synchronize the fake scrollbars with the actual size of the +// content. +function updateScrollbarsInner(cm, measure) { + var d = cm.display + var sizes = d.scrollbars.update(measure) + + d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px" + d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px" + d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent" + + if (sizes.right && sizes.bottom) { + d.scrollbarFiller.style.display = "block" + d.scrollbarFiller.style.height = sizes.bottom + "px" + d.scrollbarFiller.style.width = sizes.right + "px" + } else { d.scrollbarFiller.style.display = "" } + if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { + d.gutterFiller.style.display = "block" + d.gutterFiller.style.height = sizes.bottom + "px" + d.gutterFiller.style.width = measure.gutterWidth + "px" + } else { d.gutterFiller.style.display = "" } +} + +var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars} + +function initScrollbars(cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear() + if (cm.display.scrollbars.addClass) + { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass) } + } + + cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { + cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller) + // Prevent clicks in the scrollbars from killing focus + on(node, "mousedown", function () { + if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0) } + }) + node.setAttribute("cm-not-content", "true") + }, function (pos, axis) { + if (axis == "horizontal") { setScrollLeft(cm, pos) } + else { updateScrollTop(cm, pos) } + }, cm) + if (cm.display.scrollbars.addClass) + { addClass(cm.display.wrapper, cm.display.scrollbars.addClass) } +} + +// Operations are used to wrap a series of changes to the editor +// state in such a way that each change won't have to update the +// cursor and display (which would be awkward, slow, and +// error-prone). Instead, display updates are batched and then all +// combined and executed at once. + +var nextOpId = 0 +// Start a new operation. +function startOperation(cm) { + cm.curOp = { + cm: cm, + viewChanged: false, // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, // Used to detect need to update scrollbar + forceUpdate: false, // Used to force a redraw + updateInput: null, // Whether to reset the input textarea + typing: false, // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, // Accumulated changes, for firing change events + cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already + selectionChanged: false, // Whether the selection needs to be redrawn + updateMaxLine: false, // Set when the widest line needs to be determined anew + scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, // Used to scroll to a specific position + focus: false, + id: ++nextOpId // Unique ID + } + pushOperation(cm.curOp) +} + +// Finish an operation, updating the display and signalling delayed events +function endOperation(cm) { + var op = cm.curOp + finishOperation(op, function (group) { + for (var i = 0; i < group.ops.length; i++) + { group.ops[i].cm.curOp = null } + endOperations(group) + }) +} + +// The DOM updates done when an operation finishes are batched so +// that the minimum number of relayouts are required. +function endOperations(group) { + var ops = group.ops + for (var i = 0; i < ops.length; i++) // Read DOM + { endOperation_R1(ops[i]) } + for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe) + { endOperation_W1(ops[i$1]) } + for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM + { endOperation_R2(ops[i$2]) } + for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe) + { endOperation_W2(ops[i$3]) } + for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM + { endOperation_finish(ops[i$4]) } +} + +function endOperation_R1(op) { + var cm = op.cm, display = cm.display + maybeClipScrollbars(cm) + if (op.updateMaxLine) { findMaxLine(cm) } + + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || + op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || + op.scrollToPos.to.line >= display.viewTo) || + display.maxLineChanged && cm.options.lineWrapping + op.update = op.mustUpdate && + new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate) +} + +function endOperation_W1(op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update) +} + +function endOperation_R2(op) { + var cm = op.cm, display = cm.display + if (op.updatedDisplay) { updateHeightsInViewport(cm) } + + op.barMeasure = measureForScrollbars(cm) + + // If the max line changed since it was last measured, measure it, + // and ensure the document's width matches it. + // updateDisplay_W2 will use these properties to do the actual resizing + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3 + cm.display.sizerWidth = op.adjustWidthTo + op.barMeasure.scrollWidth = + Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth) + op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)) + } + + if (op.updatedDisplay || op.selectionChanged) + { op.preparedSelection = display.input.prepareSelection() } +} + +function endOperation_W2(op) { + var cm = op.cm + + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px" + if (op.maxScrollLeft < cm.doc.scrollLeft) + { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) } + cm.display.maxLineChanged = false + } + + var takeFocus = op.focus && op.focus == activeElt() + if (op.preparedSelection) + { cm.display.input.showSelection(op.preparedSelection, takeFocus) } + if (op.updatedDisplay || op.startHeight != cm.doc.height) + { updateScrollbars(cm, op.barMeasure) } + if (op.updatedDisplay) + { setDocumentHeight(cm, op.barMeasure) } + + if (op.selectionChanged) { restartBlink(cm) } + + if (cm.state.focused && op.updateInput) + { cm.display.input.reset(op.typing) } + if (takeFocus) { ensureFocus(op.cm) } +} + +function endOperation_finish(op) { + var cm = op.cm, display = cm.display, doc = cm.doc + + if (op.updatedDisplay) { postUpdateDisplay(cm, op.update) } + + // Abort mouse wheel delta measurement, when scrolling explicitly + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) + { display.wheelStartX = display.wheelStartY = null } + + // Propagate the scroll position to the actual DOM scroller + if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll) } + + if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true) } + // If we need to scroll a specific position into view, do so. + if (op.scrollToPos) { + var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), + clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin) + maybeScrollWindow(cm, rect) + } + + // Fire events for markers that are hidden/unidden by editing or + // undoing + var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers + if (hidden) { for (var i = 0; i < hidden.length; ++i) + { if (!hidden[i].lines.length) { signal(hidden[i], "hide") } } } + if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1) + { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide") } } } + + if (display.wrapper.offsetHeight) + { doc.scrollTop = cm.display.scroller.scrollTop } + + // Fire change events, and delayed event handlers + if (op.changeObjs) + { signal(cm, "changes", cm, op.changeObjs) } + if (op.update) + { op.update.finish() } +} + +// Run the given function in an operation +function runInOp(cm, f) { + if (cm.curOp) { return f() } + startOperation(cm) + try { return f() } + finally { endOperation(cm) } +} +// Wraps a function in an operation. Returns the wrapped function. +function operation(cm, f) { + return function() { + if (cm.curOp) { return f.apply(cm, arguments) } + startOperation(cm) + try { return f.apply(cm, arguments) } + finally { endOperation(cm) } + } +} +// Used to add methods to editor and doc instances, wrapping them in +// operations. +function methodOp(f) { + return function() { + if (this.curOp) { return f.apply(this, arguments) } + startOperation(this) + try { return f.apply(this, arguments) } + finally { endOperation(this) } + } +} +function docMethodOp(f) { + return function() { + var cm = this.cm + if (!cm || cm.curOp) { return f.apply(this, arguments) } + startOperation(cm) + try { return f.apply(this, arguments) } + finally { endOperation(cm) } + } +} + +// Updates the display.view data structure for a given change to the +// document. From and to are in pre-change coordinates. Lendiff is +// the amount of lines added or subtracted by the change. This is +// used for changes that span multiple lines, or change the way +// lines are divided into visual lines. regLineChange (below) +// registers single-line changes. +function regChange(cm, from, to, lendiff) { + if (from == null) { from = cm.doc.first } + if (to == null) { to = cm.doc.first + cm.doc.size } + if (!lendiff) { lendiff = 0 } + + var display = cm.display + if (lendiff && to < display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers > from)) + { display.updateLineNumbers = from } + + cm.curOp.viewChanged = true + + if (from >= display.viewTo) { // Change after + if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) + { resetView(cm) } + } else if (to <= display.viewFrom) { // Change before + if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { + resetView(cm) + } else { + display.viewFrom += lendiff + display.viewTo += lendiff + } + } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap + resetView(cm) + } else if (from <= display.viewFrom) { // Top overlap + var cut = viewCuttingPoint(cm, to, to + lendiff, 1) + if (cut) { + display.view = display.view.slice(cut.index) + display.viewFrom = cut.lineN + display.viewTo += lendiff + } else { + resetView(cm) + } + } else if (to >= display.viewTo) { // Bottom overlap + var cut$1 = viewCuttingPoint(cm, from, from, -1) + if (cut$1) { + display.view = display.view.slice(0, cut$1.index) + display.viewTo = cut$1.lineN + } else { + resetView(cm) + } + } else { // Gap in the middle + var cutTop = viewCuttingPoint(cm, from, from, -1) + var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1) + if (cutTop && cutBot) { + display.view = display.view.slice(0, cutTop.index) + .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) + .concat(display.view.slice(cutBot.index)) + display.viewTo += lendiff + } else { + resetView(cm) + } + } + + var ext = display.externalMeasured + if (ext) { + if (to < ext.lineN) + { ext.lineN += lendiff } + else if (from < ext.lineN + ext.size) + { display.externalMeasured = null } + } +} + +// Register a change to a single line. Type must be one of "text", +// "gutter", "class", "widget" +function regLineChange(cm, line, type) { + cm.curOp.viewChanged = true + var display = cm.display, ext = cm.display.externalMeasured + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) + { display.externalMeasured = null } + + if (line < display.viewFrom || line >= display.viewTo) { return } + var lineView = display.view[findViewIndex(cm, line)] + if (lineView.node == null) { return } + var arr = lineView.changes || (lineView.changes = []) + if (indexOf(arr, type) == -1) { arr.push(type) } +} + +// Clear the view. +function resetView(cm) { + cm.display.viewFrom = cm.display.viewTo = cm.doc.first + cm.display.view = [] + cm.display.viewOffset = 0 +} + +function viewCuttingPoint(cm, oldN, newN, dir) { + var index = findViewIndex(cm, oldN), diff, view = cm.display.view + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) + { return {index: index, lineN: newN} } + var n = cm.display.viewFrom + for (var i = 0; i < index; i++) + { n += view[i].size } + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) { return null } + diff = (n + view[index].size) - oldN + index++ + } else { + diff = n - oldN + } + oldN += diff; newN += diff + } + while (visualLineNo(cm.doc, newN) != newN) { + if (index == (dir < 0 ? 0 : view.length - 1)) { return null } + newN += dir * view[index - (dir < 0 ? 1 : 0)].size + index += dir + } + return {index: index, lineN: newN} +} + +// Force the view to cover a given range, adding empty view element +// or clipping off existing ones as needed. +function adjustView(cm, from, to) { + var display = cm.display, view = display.view + if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { + display.view = buildViewArray(cm, from, to) + display.viewFrom = from + } else { + if (display.viewFrom > from) + { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view) } + else if (display.viewFrom < from) + { display.view = display.view.slice(findViewIndex(cm, from)) } + display.viewFrom = from + if (display.viewTo < to) + { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)) } + else if (display.viewTo > to) + { display.view = display.view.slice(0, findViewIndex(cm, to)) } + } + display.viewTo = to +} + +// Count the number of lines in the view whose DOM representation is +// out of date (or nonexistent). +function countDirtyView(cm) { + var view = cm.display.view, dirty = 0 + for (var i = 0; i < view.length; i++) { + var lineView = view[i] + if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty } + } + return dirty +} + +// HIGHLIGHT WORKER + +function startWorker(cm, time) { + if (cm.doc.highlightFrontier < cm.display.viewTo) + { cm.state.highlight.set(time, bind(highlightWorker, cm)) } +} + +function highlightWorker(cm) { + var doc = cm.doc + if (doc.highlightFrontier >= cm.display.viewTo) { return } + var end = +new Date + cm.options.workTime + var context = getContextBefore(cm, doc.highlightFrontier) + var changedLines = [] + + doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { + if (context.line >= cm.display.viewFrom) { // Visible + var oldStyles = line.styles + var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null + var highlighted = highlightLine(cm, line, context, true) + if (resetState) { context.state = resetState } + line.styles = highlighted.styles + var oldCls = line.styleClasses, newCls = highlighted.classes + if (newCls) { line.styleClasses = newCls } + else if (oldCls) { line.styleClasses = null } + var ischange = !oldStyles || oldStyles.length != line.styles.length || + oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass) + for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i] } + if (ischange) { changedLines.push(context.line) } + line.stateAfter = context.save() + context.nextLine() + } else { + if (line.text.length <= cm.options.maxHighlightLength) + { processLine(cm, line.text, context) } + line.stateAfter = context.line % 5 == 0 ? context.save() : null + context.nextLine() + } + if (+new Date > end) { + startWorker(cm, cm.options.workDelay) + return true + } + }) + doc.highlightFrontier = context.line + doc.modeFrontier = Math.max(doc.modeFrontier, context.line) + if (changedLines.length) { runInOp(cm, function () { + for (var i = 0; i < changedLines.length; i++) + { regLineChange(cm, changedLines[i], "text") } + }) } +} + +// DISPLAY DRAWING + +var DisplayUpdate = function(cm, viewport, force) { + var display = cm.display + + this.viewport = viewport + // Store some values that we'll need later (but don't want to force a relayout for) + this.visible = visibleLines(display, cm.doc, viewport) + this.editorIsHidden = !display.wrapper.offsetWidth + this.wrapperHeight = display.wrapper.clientHeight + this.wrapperWidth = display.wrapper.clientWidth + this.oldDisplayWidth = displayWidth(cm) + this.force = force + this.dims = getDimensions(cm) + this.events = [] +}; + +DisplayUpdate.prototype.signal = function (emitter, type) { + if (hasHandler(emitter, type)) + { this.events.push(arguments) } +}; +DisplayUpdate.prototype.finish = function () { + var this$1 = this; + + for (var i = 0; i < this.events.length; i++) + { signal.apply(null, this$1.events[i]) } +}; + +function maybeClipScrollbars(cm) { + var display = cm.display + if (!display.scrollbarsClipped && display.scroller.offsetWidth) { + display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth + display.heightForcer.style.height = scrollGap(cm) + "px" + display.sizer.style.marginBottom = -display.nativeBarWidth + "px" + display.sizer.style.borderRightWidth = scrollGap(cm) + "px" + display.scrollbarsClipped = true + } +} + +function selectionSnapshot(cm) { + if (cm.hasFocus()) { return null } + var active = activeElt() + if (!active || !contains(cm.display.lineDiv, active)) { return null } + var result = {activeElt: active} + if (window.getSelection) { + var sel = window.getSelection() + if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { + result.anchorNode = sel.anchorNode + result.anchorOffset = sel.anchorOffset + result.focusNode = sel.focusNode + result.focusOffset = sel.focusOffset + } + } + return result +} + +function restoreSelection(snapshot) { + if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return } + snapshot.activeElt.focus() + if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { + var sel = window.getSelection(), range = document.createRange() + range.setEnd(snapshot.anchorNode, snapshot.anchorOffset) + range.collapse(false) + sel.removeAllRanges() + sel.addRange(range) + sel.extend(snapshot.focusNode, snapshot.focusOffset) + } +} + +// Does the actual updating of the line display. Bails out +// (returning false) when there is nothing to be done and forced is +// false. +function updateDisplayIfNeeded(cm, update) { + var display = cm.display, doc = cm.doc + + if (update.editorIsHidden) { + resetView(cm) + return false + } + + // Bail out if the visible area is already rendered and nothing changed. + if (!update.force && + update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && + display.renderedView == display.view && countDirtyView(cm) == 0) + { return false } + + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm) + update.dims = getDimensions(cm) + } + + // Compute a suitable new viewport (from & to) + var end = doc.first + doc.size + var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first) + var to = Math.min(end, update.visible.to + cm.options.viewportMargin) + if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom) } + if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo) } + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from) + to = visualLineEndNo(cm.doc, to) + } + + var different = from != display.viewFrom || to != display.viewTo || + display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth + adjustView(cm, from, to) + + display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)) + // Position the mover div to align with the current scroll position + cm.display.mover.style.top = display.viewOffset + "px" + + var toUpdate = countDirtyView(cm) + if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) + { return false } + + // For big changes, we hide the enclosing element during the + // update, since that speeds up the operations on most browsers. + var selSnapshot = selectionSnapshot(cm) + if (toUpdate > 4) { display.lineDiv.style.display = "none" } + patchDisplay(cm, display.updateLineNumbers, update.dims) + if (toUpdate > 4) { display.lineDiv.style.display = "" } + display.renderedView = display.view + // There might have been a widget with a focused element that got + // hidden or updated, if so re-focus it. + restoreSelection(selSnapshot) + + // Prevent selection and cursors from interfering with the scroll + // width and height. + removeChildren(display.cursorDiv) + removeChildren(display.selectionDiv) + display.gutters.style.height = display.sizer.style.minHeight = 0 + + if (different) { + display.lastWrapHeight = update.wrapperHeight + display.lastWrapWidth = update.wrapperWidth + startWorker(cm, 400) + } + + display.updateLineNumbers = null + + return true +} + +function postUpdateDisplay(cm, update) { + var viewport = update.viewport + + for (var first = true;; first = false) { + if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { + // Clip forced viewport to actual scrollable area. + if (viewport && viewport.top != null) + { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)} } + // Updated line heights might result in the drawn area not + // actually covering the viewport. Keep looping until it does. + update.visible = visibleLines(cm.display, cm.doc, viewport) + if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) + { break } + } + if (!updateDisplayIfNeeded(cm, update)) { break } + updateHeightsInViewport(cm) + var barMeasure = measureForScrollbars(cm) + updateSelection(cm) + updateScrollbars(cm, barMeasure) + setDocumentHeight(cm, barMeasure) + update.force = false + } + + update.signal(cm, "update", cm) + if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { + update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo) + cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo + } +} + +function updateDisplaySimple(cm, viewport) { + var update = new DisplayUpdate(cm, viewport) + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm) + postUpdateDisplay(cm, update) + var barMeasure = measureForScrollbars(cm) + updateSelection(cm) + updateScrollbars(cm, barMeasure) + setDocumentHeight(cm, barMeasure) + update.finish() + } +} + +// Sync the actual display DOM structure with display.view, removing +// nodes for lines that are no longer in view, and creating the ones +// that are not there yet, and updating the ones that are out of +// date. +function patchDisplay(cm, updateNumbersFrom, dims) { + var display = cm.display, lineNumbers = cm.options.lineNumbers + var container = display.lineDiv, cur = container.firstChild + + function rm(node) { + var next = node.nextSibling + // Works around a throw-scroll bug in OS X Webkit + if (webkit && mac && cm.display.currentWheelTarget == node) + { node.style.display = "none" } + else + { node.parentNode.removeChild(node) } + return next + } + + var view = display.view, lineN = display.viewFrom + // Loop over the elements in the view, syncing cur (the DOM nodes + // in display.lineDiv) with the view as we go. + for (var i = 0; i < view.length; i++) { + var lineView = view[i] + if (lineView.hidden) { + } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet + var node = buildLineElement(cm, lineView, lineN, dims) + container.insertBefore(node, cur) + } else { // Already drawn + while (cur != lineView.node) { cur = rm(cur) } + var updateNumber = lineNumbers && updateNumbersFrom != null && + updateNumbersFrom <= lineN && lineView.lineNumber + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false } + updateLineForChanges(cm, lineView, lineN, dims) + } + if (updateNumber) { + removeChildren(lineView.lineNumber) + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))) + } + cur = lineView.node.nextSibling + } + lineN += lineView.size + } + while (cur) { cur = rm(cur) } +} + +function updateGutterSpace(cm) { + var width = cm.display.gutters.offsetWidth + cm.display.sizer.style.marginLeft = width + "px" +} + +function setDocumentHeight(cm, measure) { + cm.display.sizer.style.minHeight = measure.docHeight + "px" + cm.display.heightForcer.style.top = measure.docHeight + "px" + cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px" +} + +// Rebuild the gutter elements, ensure the margin to the left of the +// code matches their width. +function updateGutters(cm) { + var gutters = cm.display.gutters, specs = cm.options.gutters + removeChildren(gutters) + var i = 0 + for (; i < specs.length; ++i) { + var gutterClass = specs[i] + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)) + if (gutterClass == "CodeMirror-linenumbers") { + cm.display.lineGutter = gElt + gElt.style.width = (cm.display.lineNumWidth || 1) + "px" + } + } + gutters.style.display = i ? "" : "none" + updateGutterSpace(cm) +} + +// Make sure the gutters options contains the element +// "CodeMirror-linenumbers" when the lineNumbers option is true. +function setGuttersForLineNumbers(options) { + var found = indexOf(options.gutters, "CodeMirror-linenumbers") + if (found == -1 && options.lineNumbers) { + options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]) + } else if (found > -1 && !options.lineNumbers) { + options.gutters = options.gutters.slice(0) + options.gutters.splice(found, 1) + } +} + +var wheelSamples = 0; +var wheelPixelsPerUnit = null; +// Fill in a browser-detected starting value on browsers where we +// know one. These don't have to be accurate -- the result of them +// being wrong would just be a slight flicker on the first wheel +// scroll (if it is large enough). +if (ie) { wheelPixelsPerUnit = -.53 } +else if (gecko) { wheelPixelsPerUnit = 15 } +else if (chrome) { wheelPixelsPerUnit = -.7 } +else if (safari) { wheelPixelsPerUnit = -1/3 } + +function wheelEventDelta(e) { + var dx = e.wheelDeltaX, dy = e.wheelDeltaY + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail } + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail } + else if (dy == null) { dy = e.wheelDelta } + return {x: dx, y: dy} +} +function wheelEventPixels(e) { + var delta = wheelEventDelta(e) + delta.x *= wheelPixelsPerUnit + delta.y *= wheelPixelsPerUnit + return delta +} + +function onScrollWheel(cm, e) { + var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y + + var display = cm.display, scroll = display.scroller + // Quit if there's nothing to scroll here + var canScrollX = scroll.scrollWidth > scroll.clientWidth + var canScrollY = scroll.scrollHeight > scroll.clientHeight + if (!(dx && canScrollX || dy && canScrollY)) { return } + + // Webkit browsers on OS X abort momentum scrolls when the target + // of the scroll event is removed from the scrollable element. + // This hack (see related code in patchDisplay) makes sure the + // element is kept around. + if (dy && mac && webkit) { + outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + for (var i = 0; i < view.length; i++) { + if (view[i].node == cur) { + cm.display.currentWheelTarget = cur + break outer + } + } + } + } + + // On some browsers, horizontal scrolling will cause redraws to + // happen before the gutter has been realigned, causing it to + // wriggle around in a most unseemly way. When we have an + // estimated pixels/delta value, we just handle horizontal + // scrolling entirely here. It'll be slightly off from native, but + // better than glitching out. + if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { + if (dy && canScrollY) + { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)) } + setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit)) + // Only prevent default scrolling if vertical scrolling is + // actually possible. Otherwise, it causes vertical scroll + // jitter on OSX trackpads when deltaX is small and deltaY + // is large (issue #3579) + if (!dy || (dy && canScrollY)) + { e_preventDefault(e) } + display.wheelStartX = null // Abort measurement, if in progress + return + } + + // 'Project' the visible viewport to cover the area that is being + // scrolled into view (if we know enough to estimate it). + if (dy && wheelPixelsPerUnit != null) { + var pixels = dy * wheelPixelsPerUnit + var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight + if (pixels < 0) { top = Math.max(0, top + pixels - 50) } + else { bot = Math.min(cm.doc.height, bot + pixels + 50) } + updateDisplaySimple(cm, {top: top, bottom: bot}) + } + + if (wheelSamples < 20) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop + display.wheelDX = dx; display.wheelDY = dy + setTimeout(function () { + if (display.wheelStartX == null) { return } + var movedX = scroll.scrollLeft - display.wheelStartX + var movedY = scroll.scrollTop - display.wheelStartY + var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || + (movedX && display.wheelDX && movedX / display.wheelDX) + display.wheelStartX = display.wheelStartY = null + if (!sample) { return } + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1) + ++wheelSamples + }, 200) + } else { + display.wheelDX += dx; display.wheelDY += dy + } + } +} + +// Selection objects are immutable. A new one is created every time +// the selection changes. A selection is one or more non-overlapping +// (and non-touching) ranges, sorted, and an integer that indicates +// which one is the primary selection (the one that's scrolled into +// view, that getCursor returns, etc). +var Selection = function(ranges, primIndex) { + this.ranges = ranges + this.primIndex = primIndex +}; + +Selection.prototype.primary = function () { return this.ranges[this.primIndex] }; + +Selection.prototype.equals = function (other) { + var this$1 = this; + + if (other == this) { return true } + if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false } + for (var i = 0; i < this.ranges.length; i++) { + var here = this$1.ranges[i], there = other.ranges[i] + if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false } + } + return true +}; + +Selection.prototype.deepCopy = function () { + var this$1 = this; + + var out = [] + for (var i = 0; i < this.ranges.length; i++) + { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)) } + return new Selection(out, this.primIndex) +}; + +Selection.prototype.somethingSelected = function () { + var this$1 = this; + + for (var i = 0; i < this.ranges.length; i++) + { if (!this$1.ranges[i].empty()) { return true } } + return false +}; + +Selection.prototype.contains = function (pos, end) { + var this$1 = this; + + if (!end) { end = pos } + for (var i = 0; i < this.ranges.length; i++) { + var range = this$1.ranges[i] + if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) + { return i } + } + return -1 +}; + +var Range = function(anchor, head) { + this.anchor = anchor; this.head = head +}; + +Range.prototype.from = function () { return minPos(this.anchor, this.head) }; +Range.prototype.to = function () { return maxPos(this.anchor, this.head) }; +Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch }; + +// Take an unsorted, potentially overlapping set of ranges, and +// build a selection out of it. 'Consumes' ranges array (modifying +// it). +function normalizeSelection(ranges, primIndex) { + var prim = ranges[primIndex] + ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }) + primIndex = indexOf(ranges, prim) + for (var i = 1; i < ranges.length; i++) { + var cur = ranges[i], prev = ranges[i - 1] + if (cmp(prev.to(), cur.from()) >= 0) { + var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()) + var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head + if (i <= primIndex) { --primIndex } + ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)) + } + } + return new Selection(ranges, primIndex) +} + +function simpleSelection(anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0) +} + +// Compute the position of the end of a change (its 'to' property +// refers to the pre-change end). +function changeEnd(change) { + if (!change.text) { return change.to } + return Pos(change.from.line + change.text.length - 1, + lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) +} + +// Adjust a position to refer to the post-change position of the +// same text, or the end of the change if the change covers it. +function adjustForChange(pos, change) { + if (cmp(pos, change.from) < 0) { return pos } + if (cmp(pos, change.to) <= 0) { return changeEnd(change) } + + var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch + if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch } + return Pos(line, ch) +} + +function computeSelAfterChange(doc, change) { + var out = [] + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i] + out.push(new Range(adjustForChange(range.anchor, change), + adjustForChange(range.head, change))) + } + return normalizeSelection(out, doc.sel.primIndex) +} + +function offsetPos(pos, old, nw) { + if (pos.line == old.line) + { return Pos(nw.line, pos.ch - old.ch + nw.ch) } + else + { return Pos(nw.line + (pos.line - old.line), pos.ch) } +} + +// Used by replaceSelections to allow moving the selection to the +// start or around the replaced test. Hint may be "start" or "around". +function computeReplacedSel(doc, changes, hint) { + var out = [] + var oldPrev = Pos(doc.first, 0), newPrev = oldPrev + for (var i = 0; i < changes.length; i++) { + var change = changes[i] + var from = offsetPos(change.from, oldPrev, newPrev) + var to = offsetPos(changeEnd(change), oldPrev, newPrev) + oldPrev = change.to + newPrev = to + if (hint == "around") { + var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0 + out[i] = new Range(inv ? to : from, inv ? from : to) + } else { + out[i] = new Range(from, from) + } + } + return new Selection(out, doc.sel.primIndex) +} + +// Used to get the editor into a consistent state again when options change. + +function loadMode(cm) { + cm.doc.mode = getMode(cm.options, cm.doc.modeOption) + resetModeState(cm) +} + +function resetModeState(cm) { + cm.doc.iter(function (line) { + if (line.stateAfter) { line.stateAfter = null } + if (line.styles) { line.styles = null } + }) + cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first + startWorker(cm, 100) + cm.state.modeGen++ + if (cm.curOp) { regChange(cm) } +} + +// DOCUMENT DATA STRUCTURE + +// By default, updates that start and end at the beginning of a line +// are treated specially, in order to make the association of line +// widgets and marker elements with the text behave more intuitive. +function isWholeLineUpdate(doc, change) { + return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && + (!doc.cm || doc.cm.options.wholeLineUpdateBefore) +} + +// Perform a change on the document data structure. +function updateDoc(doc, change, markedSpans, estimateHeight) { + function spansFor(n) {return markedSpans ? markedSpans[n] : null} + function update(line, text, spans) { + updateLine(line, text, spans, estimateHeight) + signalLater(line, "change", line, change) + } + function linesFor(start, end) { + var result = [] + for (var i = start; i < end; ++i) + { result.push(new Line(text[i], spansFor(i), estimateHeight)) } + return result + } + + var from = change.from, to = change.to, text = change.text + var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line) + var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line + + // Adjust the line structure + if (change.full) { + doc.insert(0, linesFor(0, text.length)) + doc.remove(text.length, doc.size - text.length) + } else if (isWholeLineUpdate(doc, change)) { + // This is a whole-line replace. Treated specially to make + // sure line objects move the way they are supposed to. + var added = linesFor(0, text.length - 1) + update(lastLine, lastLine.text, lastSpans) + if (nlines) { doc.remove(from.line, nlines) } + if (added.length) { doc.insert(from.line, added) } + } else if (firstLine == lastLine) { + if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans) + } else { + var added$1 = linesFor(1, text.length - 1) + added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)) + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)) + doc.insert(from.line + 1, added$1) + } + } else if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)) + doc.remove(from.line + 1, nlines) + } else { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)) + update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans) + var added$2 = linesFor(1, text.length - 1) + if (nlines > 1) { doc.remove(from.line + 1, nlines - 1) } + doc.insert(from.line + 1, added$2) + } + + signalLater(doc, "change", doc, change) +} + +// Call f for all linked documents. +function linkedDocs(doc, f, sharedHistOnly) { + function propagate(doc, skip, sharedHist) { + if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) { + var rel = doc.linked[i] + if (rel.doc == skip) { continue } + var shared = sharedHist && rel.sharedHist + if (sharedHistOnly && !shared) { continue } + f(rel.doc, shared) + propagate(rel.doc, doc, shared) + } } + } + propagate(doc, null, true) +} + +// Attach a document to an editor. +function attachDoc(cm, doc) { + if (doc.cm) { throw new Error("This document is already in use.") } + cm.doc = doc + doc.cm = cm + estimateLineHeights(cm) + loadMode(cm) + setDirectionClass(cm) + if (!cm.options.lineWrapping) { findMaxLine(cm) } + cm.options.mode = doc.modeOption + regChange(cm) +} + +function setDirectionClass(cm) { + ;(cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl") +} + +function directionChanged(cm) { + runInOp(cm, function () { + setDirectionClass(cm) + regChange(cm) + }) +} + +function History(startGen) { + // Arrays of change events and selections. Doing something adds an + // event to done and clears undo. Undoing moves events from done + // to undone, redoing moves them in the other direction. + this.done = []; this.undone = [] + this.undoDepth = Infinity + // Used to track when changes can be merged into a single undo + // event + this.lastModTime = this.lastSelTime = 0 + this.lastOp = this.lastSelOp = null + this.lastOrigin = this.lastSelOrigin = null + // Used by the isClean() method + this.generation = this.maxGeneration = startGen || 1 +} + +// Create a history change event from an updateDoc-style change +// object. +function historyChangeFromChange(doc, change) { + var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)} + attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1) + linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true) + return histChange +} + +// Pop all selection events off the end of a history array. Stop at +// a change event. +function clearSelectionEvents(array) { + while (array.length) { + var last = lst(array) + if (last.ranges) { array.pop() } + else { break } + } +} + +// Find the top change event in the history. Pop off selection +// events that are in the way. +function lastChangeEvent(hist, force) { + if (force) { + clearSelectionEvents(hist.done) + return lst(hist.done) + } else if (hist.done.length && !lst(hist.done).ranges) { + return lst(hist.done) + } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { + hist.done.pop() + return lst(hist.done) + } +} + +// Register a change in the history. Merges changes that are within +// a single operation, or are close together with an origin that +// allows merging (starting with "+") into a single event. +function addChangeToHistory(doc, change, selAfter, opId) { + var hist = doc.history + hist.undone.length = 0 + var time = +new Date, cur + var last + + if ((hist.lastOp == opId || + hist.lastOrigin == change.origin && change.origin && + ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) || + change.origin.charAt(0) == "*")) && + (cur = lastChangeEvent(hist, hist.lastOp == opId))) { + // Merge this change into the last event + last = lst(cur.changes) + if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { + // Optimized case for simple insertion -- don't want to add + // new changesets for every character typed + last.to = changeEnd(change) + } else { + // Add new sub-event + cur.changes.push(historyChangeFromChange(doc, change)) + } + } else { + // Can not be merged, start a new event. + var before = lst(hist.done) + if (!before || !before.ranges) + { pushSelectionToHistory(doc.sel, hist.done) } + cur = {changes: [historyChangeFromChange(doc, change)], + generation: hist.generation} + hist.done.push(cur) + while (hist.done.length > hist.undoDepth) { + hist.done.shift() + if (!hist.done[0].ranges) { hist.done.shift() } + } + } + hist.done.push(selAfter) + hist.generation = ++hist.maxGeneration + hist.lastModTime = hist.lastSelTime = time + hist.lastOp = hist.lastSelOp = opId + hist.lastOrigin = hist.lastSelOrigin = change.origin + + if (!last) { signal(doc, "historyAdded") } +} + +function selectionEventCanBeMerged(doc, origin, prev, sel) { + var ch = origin.charAt(0) + return ch == "*" || + ch == "+" && + prev.ranges.length == sel.ranges.length && + prev.somethingSelected() == sel.somethingSelected() && + new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500) +} + +// Called whenever the selection changes, sets the new selection as +// the pending selection in the history, and pushes the old pending +// selection into the 'done' array when it was significantly +// different (in number of selected ranges, emptiness, or time). +function addSelectionToHistory(doc, sel, opId, options) { + var hist = doc.history, origin = options && options.origin + + // A new event is started when the previous origin does not match + // the current, or the origins don't allow matching. Origins + // starting with * are always merged, those starting with + are + // merged when similar and close together in time. + if (opId == hist.lastSelOp || + (origin && hist.lastSelOrigin == origin && + (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || + selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) + { hist.done[hist.done.length - 1] = sel } + else + { pushSelectionToHistory(sel, hist.done) } + + hist.lastSelTime = +new Date + hist.lastSelOrigin = origin + hist.lastSelOp = opId + if (options && options.clearRedo !== false) + { clearSelectionEvents(hist.undone) } +} + +function pushSelectionToHistory(sel, dest) { + var top = lst(dest) + if (!(top && top.ranges && top.equals(sel))) + { dest.push(sel) } +} + +// Used to store marked span information in the history. +function attachLocalSpans(doc, change, from, to) { + var existing = change["spans_" + doc.id], n = 0 + doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { + if (line.markedSpans) + { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans } + ++n + }) +} + +// When un/re-doing restores text containing marked spans, those +// that have been explicitly cleared should not be restored. +function removeClearedSpans(spans) { + if (!spans) { return null } + var out + for (var i = 0; i < spans.length; ++i) { + if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i) } } + else if (out) { out.push(spans[i]) } + } + return !out ? spans : out.length ? out : null +} + +// Retrieve and filter the old marked spans stored in a change event. +function getOldSpans(doc, change) { + var found = change["spans_" + doc.id] + if (!found) { return null } + var nw = [] + for (var i = 0; i < change.text.length; ++i) + { nw.push(removeClearedSpans(found[i])) } + return nw +} + +// Used for un/re-doing changes from the history. Combines the +// result of computing the existing spans with the set of spans that +// existed in the history (so that deleting around a span and then +// undoing brings back the span). +function mergeOldSpans(doc, change) { + var old = getOldSpans(doc, change) + var stretched = stretchSpansOverChange(doc, change) + if (!old) { return stretched } + if (!stretched) { return old } + + for (var i = 0; i < old.length; ++i) { + var oldCur = old[i], stretchCur = stretched[i] + if (oldCur && stretchCur) { + spans: for (var j = 0; j < stretchCur.length; ++j) { + var span = stretchCur[j] + for (var k = 0; k < oldCur.length; ++k) + { if (oldCur[k].marker == span.marker) { continue spans } } + oldCur.push(span) + } + } else if (stretchCur) { + old[i] = stretchCur + } + } + return old +} + +// Used both to provide a JSON-safe object in .getHistory, and, when +// detaching a document, to split the history in two +function copyHistoryArray(events, newGroup, instantiateSel) { + var copy = [] + for (var i = 0; i < events.length; ++i) { + var event = events[i] + if (event.ranges) { + copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event) + continue + } + var changes = event.changes, newChanges = [] + copy.push({changes: newChanges}) + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], m = (void 0) + newChanges.push({from: change.from, to: change.to, text: change.text}) + if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop] = change[prop] + delete change[prop] + } + } } } + } + } + return copy +} + +// The 'scroll' parameter given to many of these indicated whether +// the new cursor position should be scrolled into view after +// modifying the selection. + +// If shift is held or the extend flag is set, extends a range to +// include a given position (and optionally a second position). +// Otherwise, simply returns the range between the given positions. +// Used for cursor motion and such. +function extendRange(range, head, other, extend) { + if (extend) { + var anchor = range.anchor + if (other) { + var posBefore = cmp(head, anchor) < 0 + if (posBefore != (cmp(other, anchor) < 0)) { + anchor = head + head = other + } else if (posBefore != (cmp(head, other) < 0)) { + head = other + } + } + return new Range(anchor, head) + } else { + return new Range(other || head, head) + } +} + +// Extend the primary selection range, discard the rest. +function extendSelection(doc, head, other, options, extend) { + if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend) } + setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options) +} + +// Extend all selections (pos is an array of selections with length +// equal the number of selections) +function extendSelections(doc, heads, options) { + var out = [] + var extend = doc.cm && (doc.cm.display.shift || doc.extend) + for (var i = 0; i < doc.sel.ranges.length; i++) + { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend) } + var newSel = normalizeSelection(out, doc.sel.primIndex) + setSelection(doc, newSel, options) +} + +// Updates a single range in the selection. +function replaceOneSelection(doc, i, range, options) { + var ranges = doc.sel.ranges.slice(0) + ranges[i] = range + setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options) +} + +// Reset the selection to a single range. +function setSimpleSelection(doc, anchor, head, options) { + setSelection(doc, simpleSelection(anchor, head), options) +} + +// Give beforeSelectionChange handlers a change to influence a +// selection update. +function filterSelectionChange(doc, sel, options) { + var obj = { + ranges: sel.ranges, + update: function(ranges) { + var this$1 = this; + + this.ranges = [] + for (var i = 0; i < ranges.length; i++) + { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), + clipPos(doc, ranges[i].head)) } + }, + origin: options && options.origin + } + signal(doc, "beforeSelectionChange", doc, obj) + if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj) } + if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) } + else { return sel } +} + +function setSelectionReplaceHistory(doc, sel, options) { + var done = doc.history.done, last = lst(done) + if (last && last.ranges) { + done[done.length - 1] = sel + setSelectionNoUndo(doc, sel, options) + } else { + setSelection(doc, sel, options) + } +} + +// Set a new selection. +function setSelection(doc, sel, options) { + setSelectionNoUndo(doc, sel, options) + addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options) +} + +function setSelectionNoUndo(doc, sel, options) { + if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) + { sel = filterSelectionChange(doc, sel, options) } + + var bias = options && options.bias || + (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1) + setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)) + + if (!(options && options.scroll === false) && doc.cm) + { ensureCursorVisible(doc.cm) } +} + +function setSelectionInner(doc, sel) { + if (sel.equals(doc.sel)) { return } + + doc.sel = sel + + if (doc.cm) { + doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true + signalCursorActivity(doc.cm) + } + signalLater(doc, "cursorActivity", doc) +} + +// Verify that the selection does not partially select any atomic +// marked ranges. +function reCheckSelection(doc) { + setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)) +} + +// Return a selection that does not partially select any atomic +// ranges. +function skipAtomicInSelection(doc, sel, bias, mayClear) { + var out + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i] + var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i] + var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear) + var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear) + if (out || newAnchor != range.anchor || newHead != range.head) { + if (!out) { out = sel.ranges.slice(0, i) } + out[i] = new Range(newAnchor, newHead) + } + } + return out ? normalizeSelection(out, sel.primIndex) : sel +} + +function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { + var line = getLine(doc, pos.line) + if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { + var sp = line.markedSpans[i], m = sp.marker + if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && + (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) { + if (mayClear) { + signal(m, "beforeCursorEnter") + if (m.explicitlyCleared) { + if (!line.markedSpans) { break } + else {--i; continue} + } + } + if (!m.atomic) { continue } + + if (oldPos) { + var near = m.find(dir < 0 ? 1 : -1), diff = (void 0) + if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft) + { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null) } + if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) + { return skipAtomicInner(doc, near, pos, dir, mayClear) } + } + + var far = m.find(dir < 0 ? -1 : 1) + if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight) + { far = movePos(doc, far, dir, far.line == pos.line ? line : null) } + return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null + } + } } + return pos +} + +// Ensure a given position is not inside an atomic range. +function skipAtomic(doc, pos, oldPos, bias, mayClear) { + var dir = bias || 1 + var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || + (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || + skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || + (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)) + if (!found) { + doc.cantEdit = true + return Pos(doc.first, 0) + } + return found +} + +function movePos(doc, pos, dir, line) { + if (dir < 0 && pos.ch == 0) { + if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) } + else { return null } + } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { + if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) } + else { return null } + } else { + return new Pos(pos.line, pos.ch + dir) + } +} + +function selectAll(cm) { + cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll) +} + +// UPDATING + +// Allow "beforeChange" event handlers to influence a change +function filterChange(doc, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function () { return obj.canceled = true; } + } + if (update) { obj.update = function (from, to, text, origin) { + if (from) { obj.from = clipPos(doc, from) } + if (to) { obj.to = clipPos(doc, to) } + if (text) { obj.text = text } + if (origin !== undefined) { obj.origin = origin } + } } + signal(doc, "beforeChange", doc, obj) + if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj) } + + if (obj.canceled) { return null } + return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} +} + +// Apply a change to a document, and add it to the document's +// history, and propagating it to all linked documents. +function makeChange(doc, change, ignoreReadOnly) { + if (doc.cm) { + if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) } + if (doc.cm.state.suppressEdits) { return } + } + + if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { + change = filterChange(doc, change, true) + if (!change) { return } + } + + // Possibly split or suppress the update based on the presence + // of read-only spans in its range. + var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to) + if (split) { + for (var i = split.length - 1; i >= 0; --i) + { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}) } + } else { + makeChangeInner(doc, change) + } +} + +function makeChangeInner(doc, change) { + if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return } + var selAfter = computeSelAfterChange(doc, change) + addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN) + + makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)) + var rebased = [] + + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change) + rebased.push(doc.history) + } + makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)) + }) +} + +// Revert a change stored in a document's history. +function makeChangeFromHistory(doc, type, allowSelectionOnly) { + var suppress = doc.cm && doc.cm.state.suppressEdits + if (suppress && !allowSelectionOnly) { return } + + var hist = doc.history, event, selAfter = doc.sel + var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done + + // Verify that there is a useable event (so that ctrl-z won't + // needlessly clear selection events) + var i = 0 + for (; i < source.length; i++) { + event = source[i] + if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) + { break } + } + if (i == source.length) { return } + hist.lastOrigin = hist.lastSelOrigin = null + + for (;;) { + event = source.pop() + if (event.ranges) { + pushSelectionToHistory(event, dest) + if (allowSelectionOnly && !event.equals(doc.sel)) { + setSelection(doc, event, {clearRedo: false}) + return + } + selAfter = event + } else if (suppress) { + source.push(event) + return + } else { break } + } + + // Build up a reverse change object to add to the opposite history + // stack (redo when undoing, and vice versa). + var antiChanges = [] + pushSelectionToHistory(selAfter, dest) + dest.push({changes: antiChanges, generation: hist.generation}) + hist.generation = event.generation || ++hist.maxGeneration + + var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange") + + var loop = function ( i ) { + var change = event.changes[i] + change.origin = type + if (filter && !filterChange(doc, change, false)) { + source.length = 0 + return {} + } + + antiChanges.push(historyChangeFromChange(doc, change)) + + var after = i ? computeSelAfterChange(doc, change) : lst(source) + makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)) + if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}) } + var rebased = [] + + // Propagate to the linked documents + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change) + rebased.push(doc.history) + } + makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)) + }) + }; + + for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { + var returned = loop( i$1 ); + + if ( returned ) return returned.v; + } +} + +// Sub-views need their line numbers shifted when text is added +// above or below them in the parent document. +function shiftDoc(doc, distance) { + if (distance == 0) { return } + doc.first += distance + doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range( + Pos(range.anchor.line + distance, range.anchor.ch), + Pos(range.head.line + distance, range.head.ch) + ); }), doc.sel.primIndex) + if (doc.cm) { + regChange(doc.cm, doc.first, doc.first - distance, distance) + for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) + { regLineChange(doc.cm, l, "gutter") } + } +} + +// More lower-level change function, handling only a single document +// (not linked ones). +function makeChangeSingleDoc(doc, change, selAfter, spans) { + if (doc.cm && !doc.cm.curOp) + { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) } + + if (change.to.line < doc.first) { + shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)) + return + } + if (change.from.line > doc.lastLine()) { return } + + // Clip the change to the size of this doc + if (change.from.line < doc.first) { + var shift = change.text.length - 1 - (doc.first - change.from.line) + shiftDoc(doc, shift) + change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], origin: change.origin} + } + var last = doc.lastLine() + if (change.to.line > last) { + change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), + text: [change.text[0]], origin: change.origin} + } + + change.removed = getBetween(doc, change.from, change.to) + + if (!selAfter) { selAfter = computeSelAfterChange(doc, change) } + if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans) } + else { updateDoc(doc, change, spans) } + setSelectionNoUndo(doc, selAfter, sel_dontScroll) +} + +// Handle the interaction of a change to a document with the editor +// that this document is part of. +function makeChangeSingleDocInEditor(cm, change, spans) { + var doc = cm.doc, display = cm.display, from = change.from, to = change.to + + var recomputeMaxLength = false, checkWidthStart = from.line + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(getLine(doc, from.line))) + doc.iter(checkWidthStart, to.line + 1, function (line) { + if (line == display.maxLine) { + recomputeMaxLength = true + return true + } + }) + } + + if (doc.sel.contains(change.from, change.to) > -1) + { signalCursorActivity(cm) } + + updateDoc(doc, change, spans, estimateHeight(cm)) + + if (!cm.options.lineWrapping) { + doc.iter(checkWidthStart, from.line + change.text.length, function (line) { + var len = lineLength(line) + if (len > display.maxLineLength) { + display.maxLine = line + display.maxLineLength = len + display.maxLineChanged = true + recomputeMaxLength = false + } + }) + if (recomputeMaxLength) { cm.curOp.updateMaxLine = true } + } + + retreatFrontier(doc, from.line) + startWorker(cm, 400) + + var lendiff = change.text.length - (to.line - from.line) - 1 + // Remember that these lines changed, for updating the display + if (change.full) + { regChange(cm) } + else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) + { regLineChange(cm, from.line, "text") } + else + { regChange(cm, from.line, to.line + 1, lendiff) } + + var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change") + if (changeHandler || changesHandler) { + var obj = { + from: from, to: to, + text: change.text, + removed: change.removed, + origin: change.origin + } + if (changeHandler) { signalLater(cm, "change", cm, obj) } + if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj) } + } + cm.display.selForContextMenu = null +} + +function replaceRange(doc, code, from, to, origin) { + if (!to) { to = from } + if (cmp(to, from) < 0) { var assign; + (assign = [to, from], from = assign[0], to = assign[1], assign) } + if (typeof code == "string") { code = doc.splitLines(code) } + makeChange(doc, {from: from, to: to, text: code, origin: origin}) +} + +// Rebasing/resetting history to deal with externally-sourced changes + +function rebaseHistSelSingle(pos, from, to, diff) { + if (to < pos.line) { + pos.line += diff + } else if (from < pos.line) { + pos.line = from + pos.ch = 0 + } +} + +// Tries to rebase an array of history events given a change in the +// document. If the change touches the same lines as the event, the +// event, and everything 'behind' it, is discarded. If the change is +// before the event, the event's positions are updated. Uses a +// copy-on-write scheme for the positions, to avoid having to +// reallocate them all on every rebase, but also avoid problems with +// shared position objects being unsafely updated. +function rebaseHistArray(array, from, to, diff) { + for (var i = 0; i < array.length; ++i) { + var sub = array[i], ok = true + if (sub.ranges) { + if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true } + for (var j = 0; j < sub.ranges.length; j++) { + rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff) + rebaseHistSelSingle(sub.ranges[j].head, from, to, diff) + } + continue + } + for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { + var cur = sub.changes[j$1] + if (to < cur.from.line) { + cur.from = Pos(cur.from.line + diff, cur.from.ch) + cur.to = Pos(cur.to.line + diff, cur.to.ch) + } else if (from <= cur.to.line) { + ok = false + break + } + } + if (!ok) { + array.splice(0, i + 1) + i = 0 + } + } +} + +function rebaseHist(hist, change) { + var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1 + rebaseHistArray(hist.done, from, to, diff) + rebaseHistArray(hist.undone, from, to, diff) +} + +// Utility for applying a change to a line by handle or number, +// returning the number and optionally registering the line as +// changed. +function changeLine(doc, handle, changeType, op) { + var no = handle, line = handle + if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)) } + else { no = lineNo(handle) } + if (no == null) { return null } + if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType) } + return line +} + +// The document is represented as a BTree consisting of leaves, with +// chunk of lines in them, and branches, with up to ten leaves or +// other branch nodes below them. The top node is always a branch +// node, and is the document object itself (meaning it has +// additional methods and properties). +// +// All nodes have parent links. The tree is used both to go from +// line numbers to line objects, and to go from objects to numbers. +// It also indexes by height, and is used to convert between height +// and line object, and to find the total height of the document. +// +// See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html + +function LeafChunk(lines) { + var this$1 = this; + + this.lines = lines + this.parent = null + var height = 0 + for (var i = 0; i < lines.length; ++i) { + lines[i].parent = this$1 + height += lines[i].height + } + this.height = height +} + +LeafChunk.prototype = { + chunkSize: function chunkSize() { return this.lines.length }, + + // Remove the n lines at offset 'at'. + removeInner: function removeInner(at, n) { + var this$1 = this; + + for (var i = at, e = at + n; i < e; ++i) { + var line = this$1.lines[i] + this$1.height -= line.height + cleanUpLine(line) + signalLater(line, "delete") + } + this.lines.splice(at, n) + }, + + // Helper used to collapse a small branch into a single leaf. + collapse: function collapse(lines) { + lines.push.apply(lines, this.lines) + }, + + // Insert the given array of lines at offset 'at', count them as + // having the given height. + insertInner: function insertInner(at, lines, height) { + var this$1 = this; + + this.height += height + this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)) + for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1 } + }, + + // Used to iterate over a part of the tree. + iterN: function iterN(at, n, op) { + var this$1 = this; + + for (var e = at + n; at < e; ++at) + { if (op(this$1.lines[at])) { return true } } + } +} + +function BranchChunk(children) { + var this$1 = this; + + this.children = children + var size = 0, height = 0 + for (var i = 0; i < children.length; ++i) { + var ch = children[i] + size += ch.chunkSize(); height += ch.height + ch.parent = this$1 + } + this.size = size + this.height = height + this.parent = null +} + +BranchChunk.prototype = { + chunkSize: function chunkSize() { return this.size }, + + removeInner: function removeInner(at, n) { + var this$1 = this; + + this.size -= n + for (var i = 0; i < this.children.length; ++i) { + var child = this$1.children[i], sz = child.chunkSize() + if (at < sz) { + var rm = Math.min(n, sz - at), oldHeight = child.height + child.removeInner(at, rm) + this$1.height -= oldHeight - child.height + if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null } + if ((n -= rm) == 0) { break } + at = 0 + } else { at -= sz } + } + // If the result is smaller than 25 lines, ensure that it is a + // single leaf node. + if (this.size - n < 25 && + (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { + var lines = [] + this.collapse(lines) + this.children = [new LeafChunk(lines)] + this.children[0].parent = this + } + }, + + collapse: function collapse(lines) { + var this$1 = this; + + for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines) } + }, + + insertInner: function insertInner(at, lines, height) { + var this$1 = this; + + this.size += lines.length + this.height += height + for (var i = 0; i < this.children.length; ++i) { + var child = this$1.children[i], sz = child.chunkSize() + if (at <= sz) { + child.insertInner(at, lines, height) + if (child.lines && child.lines.length > 50) { + // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. + // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. + var remaining = child.lines.length % 25 + 25 + for (var pos = remaining; pos < child.lines.length;) { + var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)) + child.height -= leaf.height + this$1.children.splice(++i, 0, leaf) + leaf.parent = this$1 + } + child.lines = child.lines.slice(0, remaining) + this$1.maybeSpill() + } + break + } + at -= sz + } + }, + + // When a node has grown, check whether it should be split. + maybeSpill: function maybeSpill() { + if (this.children.length <= 10) { return } + var me = this + do { + var spilled = me.children.splice(me.children.length - 5, 5) + var sibling = new BranchChunk(spilled) + if (!me.parent) { // Become the parent node + var copy = new BranchChunk(me.children) + copy.parent = me + me.children = [copy, sibling] + me = copy + } else { + me.size -= sibling.size + me.height -= sibling.height + var myIndex = indexOf(me.parent.children, me) + me.parent.children.splice(myIndex + 1, 0, sibling) + } + sibling.parent = me.parent + } while (me.children.length > 10) + me.parent.maybeSpill() + }, + + iterN: function iterN(at, n, op) { + var this$1 = this; + + for (var i = 0; i < this.children.length; ++i) { + var child = this$1.children[i], sz = child.chunkSize() + if (at < sz) { + var used = Math.min(n, sz - at) + if (child.iterN(at, used, op)) { return true } + if ((n -= used) == 0) { break } + at = 0 + } else { at -= sz } + } + } +} + +// Line widgets are block elements displayed above or below a line. + +var LineWidget = function(doc, node, options) { + var this$1 = this; + + if (options) { for (var opt in options) { if (options.hasOwnProperty(opt)) + { this$1[opt] = options[opt] } } } + this.doc = doc + this.node = node +}; + +LineWidget.prototype.clear = function () { + var this$1 = this; + + var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line) + if (no == null || !ws) { return } + for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1) } } + if (!ws.length) { line.widgets = null } + var height = widgetHeight(this) + updateLineHeight(line, Math.max(0, line.height - height)) + if (cm) { + runInOp(cm, function () { + adjustScrollWhenAboveVisible(cm, line, -height) + regLineChange(cm, no, "widget") + }) + signalLater(cm, "lineWidgetCleared", cm, this, no) + } +}; + +LineWidget.prototype.changed = function () { + var this$1 = this; + + var oldH = this.height, cm = this.doc.cm, line = this.line + this.height = null + var diff = widgetHeight(this) - oldH + if (!diff) { return } + if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff) } + if (cm) { + runInOp(cm, function () { + cm.curOp.forceUpdate = true + adjustScrollWhenAboveVisible(cm, line, diff) + signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line)) + }) + } +}; +eventMixin(LineWidget) + +function adjustScrollWhenAboveVisible(cm, line, diff) { + if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) + { addToScrollTop(cm, diff) } +} + +function addLineWidget(doc, handle, node, options) { + var widget = new LineWidget(doc, node, options) + var cm = doc.cm + if (cm && widget.noHScroll) { cm.display.alignWidgets = true } + changeLine(doc, handle, "widget", function (line) { + var widgets = line.widgets || (line.widgets = []) + if (widget.insertAt == null) { widgets.push(widget) } + else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget) } + widget.line = line + if (cm && !lineIsHidden(doc, line)) { + var aboveVisible = heightAtLine(line) < doc.scrollTop + updateLineHeight(line, line.height + widgetHeight(widget)) + if (aboveVisible) { addToScrollTop(cm, widget.height) } + cm.curOp.forceUpdate = true + } + return true + }) + if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)) } + return widget +} + +// TEXTMARKERS + +// Created with markText and setBookmark methods. A TextMarker is a +// handle that can be used to clear or find a marked position in the +// document. Line objects hold arrays (markedSpans) containing +// {from, to, marker} object pointing to such marker objects, and +// indicating that such a marker is present on that line. Multiple +// lines may point to the same marker when it spans across lines. +// The spans will have null for their from/to properties when the +// marker continues beyond the start/end of the line. Markers have +// links back to the lines they currently touch. + +// Collapsed markers have unique ids, in order to be able to order +// them, which is needed for uniquely determining an outer marker +// when they overlap (they may nest, but not partially overlap). +var nextMarkerId = 0 + +var TextMarker = function(doc, type) { + this.lines = [] + this.type = type + this.doc = doc + this.id = ++nextMarkerId +}; + +// Clear the marker. +TextMarker.prototype.clear = function () { + var this$1 = this; + + if (this.explicitlyCleared) { return } + var cm = this.doc.cm, withOp = cm && !cm.curOp + if (withOp) { startOperation(cm) } + if (hasHandler(this, "clear")) { + var found = this.find() + if (found) { signalLater(this, "clear", found.from, found.to) } + } + var min = null, max = null + for (var i = 0; i < this.lines.length; ++i) { + var line = this$1.lines[i] + var span = getMarkedSpanFor(line.markedSpans, this$1) + if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text") } + else if (cm) { + if (span.to != null) { max = lineNo(line) } + if (span.from != null) { min = lineNo(line) } + } + line.markedSpans = removeMarkedSpan(line.markedSpans, span) + if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm) + { updateLineHeight(line, textHeight(cm.display)) } + } + if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) { + var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual) + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual + cm.display.maxLineLength = len + cm.display.maxLineChanged = true + } + } } + + if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1) } + this.lines.length = 0 + this.explicitlyCleared = true + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false + if (cm) { reCheckSelection(cm.doc) } + } + if (cm) { signalLater(cm, "markerCleared", cm, this, min, max) } + if (withOp) { endOperation(cm) } + if (this.parent) { this.parent.clear() } +}; + +// Find the position of the marker in the document. Returns a {from, +// to} object by default. Side can be passed to get a specific side +// -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the +// Pos objects returned contain a line object, rather than a line +// number (used to prevent looking up the same line twice). +TextMarker.prototype.find = function (side, lineObj) { + var this$1 = this; + + if (side == null && this.type == "bookmark") { side = 1 } + var from, to + for (var i = 0; i < this.lines.length; ++i) { + var line = this$1.lines[i] + var span = getMarkedSpanFor(line.markedSpans, this$1) + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from) + if (side == -1) { return from } + } + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to) + if (side == 1) { return to } + } + } + return from && {from: from, to: to} +}; + +// Signals that the marker's widget changed, and surrounding layout +// should be recomputed. +TextMarker.prototype.changed = function () { + var this$1 = this; + + var pos = this.find(-1, true), widget = this, cm = this.doc.cm + if (!pos || !cm) { return } + runInOp(cm, function () { + var line = pos.line, lineN = lineNo(pos.line) + var view = findViewForLine(cm, lineN) + if (view) { + clearLineMeasurementCacheFor(view) + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true + } + cm.curOp.updateMaxLine = true + if (!lineIsHidden(widget.doc, line) && widget.height != null) { + var oldHeight = widget.height + widget.height = null + var dHeight = widgetHeight(widget) - oldHeight + if (dHeight) + { updateLineHeight(line, line.height + dHeight) } + } + signalLater(cm, "markerChanged", cm, this$1) + }) +}; + +TextMarker.prototype.attachLine = function (line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) + { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this) } + } + this.lines.push(line) +}; + +TextMarker.prototype.detachLine = function (line) { + this.lines.splice(indexOf(this.lines, line), 1) + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp + ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this) + } +}; +eventMixin(TextMarker) + +// Create a marker, wire it up to the right lines, and +function markText(doc, from, to, options, type) { + // Shared markers (across linked documents) are handled separately + // (markTextShared will call out to this again, once per + // document). + if (options && options.shared) { return markTextShared(doc, from, to, options, type) } + // Ensure we are in an operation. + if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) } + + var marker = new TextMarker(doc, type), diff = cmp(from, to) + if (options) { copyObj(options, marker, false) } + // Don't connect empty markers unless clearWhenEmpty is false + if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) + { return marker } + if (marker.replacedWith) { + // Showing up as a widget implies collapsed (widget replaces text) + marker.collapsed = true + marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget") + if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true") } + if (options.insertLeft) { marker.widgetNode.insertLeft = true } + } + if (marker.collapsed) { + if (conflictingCollapsedRange(doc, from.line, from, to, marker) || + from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) + { throw new Error("Inserting collapsed marker partially overlapping an existing one") } + seeCollapsedSpans() + } + + if (marker.addToHistory) + { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN) } + + var curLine = from.line, cm = doc.cm, updateMaxLine + doc.iter(curLine, to.line + 1, function (line) { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) + { updateMaxLine = true } + if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0) } + addMarkedSpan(line, new MarkedSpan(marker, + curLine == from.line ? from.ch : null, + curLine == to.line ? to.ch : null)) + ++curLine + }) + // lineIsHidden depends on the presence of the spans, so needs a second pass + if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) { + if (lineIsHidden(doc, line)) { updateLineHeight(line, 0) } + }) } + + if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }) } + + if (marker.readOnly) { + seeReadOnlySpans() + if (doc.history.done.length || doc.history.undone.length) + { doc.clearHistory() } + } + if (marker.collapsed) { + marker.id = ++nextMarkerId + marker.atomic = true + } + if (cm) { + // Sync editor state + if (updateMaxLine) { cm.curOp.updateMaxLine = true } + if (marker.collapsed) + { regChange(cm, from.line, to.line + 1) } + else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) + { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text") } } + if (marker.atomic) { reCheckSelection(cm.doc) } + signalLater(cm, "markerAdded", cm, marker) + } + return marker +} + +// SHARED TEXTMARKERS + +// A shared marker spans multiple linked documents. It is +// implemented as a meta-marker-object controlling multiple normal +// markers. +var SharedTextMarker = function(markers, primary) { + var this$1 = this; + + this.markers = markers + this.primary = primary + for (var i = 0; i < markers.length; ++i) + { markers[i].parent = this$1 } +}; + +SharedTextMarker.prototype.clear = function () { + var this$1 = this; + + if (this.explicitlyCleared) { return } + this.explicitlyCleared = true + for (var i = 0; i < this.markers.length; ++i) + { this$1.markers[i].clear() } + signalLater(this, "clear") +}; + +SharedTextMarker.prototype.find = function (side, lineObj) { + return this.primary.find(side, lineObj) +}; +eventMixin(SharedTextMarker) + +function markTextShared(doc, from, to, options, type) { + options = copyObj(options) + options.shared = false + var markers = [markText(doc, from, to, options, type)], primary = markers[0] + var widget = options.widgetNode + linkedDocs(doc, function (doc) { + if (widget) { options.widgetNode = widget.cloneNode(true) } + markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)) + for (var i = 0; i < doc.linked.length; ++i) + { if (doc.linked[i].isParent) { return } } + primary = lst(markers) + }) + return new SharedTextMarker(markers, primary) +} + +function findSharedMarkers(doc) { + return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; }) +} + +function copySharedMarkers(doc, markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], pos = marker.find() + var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to) + if (cmp(mFrom, mTo)) { + var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type) + marker.markers.push(subMark) + subMark.parent = marker + } + } +} + +function detachSharedMarkers(markers) { + var loop = function ( i ) { + var marker = markers[i], linked = [marker.primary.doc] + linkedDocs(marker.primary.doc, function (d) { return linked.push(d); }) + for (var j = 0; j < marker.markers.length; j++) { + var subMarker = marker.markers[j] + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null + marker.markers.splice(j--, 1) + } + } + }; + + for (var i = 0; i < markers.length; i++) loop( i ); +} + +var nextDocId = 0 +var Doc = function(text, mode, firstLine, lineSep, direction) { + if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) } + if (firstLine == null) { firstLine = 0 } + + BranchChunk.call(this, [new LeafChunk([new Line("", null)])]) + this.first = firstLine + this.scrollTop = this.scrollLeft = 0 + this.cantEdit = false + this.cleanGeneration = 1 + this.modeFrontier = this.highlightFrontier = firstLine + var start = Pos(firstLine, 0) + this.sel = simpleSelection(start) + this.history = new History(null) + this.id = ++nextDocId + this.modeOption = mode + this.lineSep = lineSep + this.direction = (direction == "rtl") ? "rtl" : "ltr" + this.extend = false + + if (typeof text == "string") { text = this.splitLines(text) } + updateDoc(this, {from: start, to: start, text: text}) + setSelection(this, simpleSelection(start), sel_dontScroll) +} + +Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + // Iterate over the document. Supports two forms -- with only one + // argument, it calls that for each line in the document. With + // three, it iterates over the range given by the first two (with + // the second being non-inclusive). + iter: function(from, to, op) { + if (op) { this.iterN(from - this.first, to - from, op) } + else { this.iterN(this.first, this.first + this.size, from) } + }, + + // Non-public interface for adding and removing lines. + insert: function(at, lines) { + var height = 0 + for (var i = 0; i < lines.length; ++i) { height += lines[i].height } + this.insertInner(at - this.first, lines, height) + }, + remove: function(at, n) { this.removeInner(at - this.first, n) }, + + // From here, the methods are part of the public interface. Most + // are also available from CodeMirror (editor) instances. + + getValue: function(lineSep) { + var lines = getLines(this, this.first, this.first + this.size) + if (lineSep === false) { return lines } + return lines.join(lineSep || this.lineSeparator()) + }, + setValue: docMethodOp(function(code) { + var top = Pos(this.first, 0), last = this.first + this.size - 1 + makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), + text: this.splitLines(code), origin: "setValue", full: true}, true) + if (this.cm) { scrollToCoords(this.cm, 0, 0) } + setSelection(this, simpleSelection(top), sel_dontScroll) + }), + replaceRange: function(code, from, to, origin) { + from = clipPos(this, from) + to = to ? clipPos(this, to) : from + replaceRange(this, code, from, to, origin) + }, + getRange: function(from, to, lineSep) { + var lines = getBetween(this, clipPos(this, from), clipPos(this, to)) + if (lineSep === false) { return lines } + return lines.join(lineSep || this.lineSeparator()) + }, + + getLine: function(line) {var l = this.getLineHandle(line); return l && l.text}, + + getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }}, + getLineNumber: function(line) {return lineNo(line)}, + + getLineHandleVisualStart: function(line) { + if (typeof line == "number") { line = getLine(this, line) } + return visualLine(line) + }, + + lineCount: function() {return this.size}, + firstLine: function() {return this.first}, + lastLine: function() {return this.first + this.size - 1}, + + clipPos: function(pos) {return clipPos(this, pos)}, + + getCursor: function(start) { + var range = this.sel.primary(), pos + if (start == null || start == "head") { pos = range.head } + else if (start == "anchor") { pos = range.anchor } + else if (start == "end" || start == "to" || start === false) { pos = range.to() } + else { pos = range.from() } + return pos + }, + listSelections: function() { return this.sel.ranges }, + somethingSelected: function() {return this.sel.somethingSelected()}, + + setCursor: docMethodOp(function(line, ch, options) { + setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options) + }), + setSelection: docMethodOp(function(anchor, head, options) { + setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options) + }), + extendSelection: docMethodOp(function(head, other, options) { + extendSelection(this, clipPos(this, head), other && clipPos(this, other), options) + }), + extendSelections: docMethodOp(function(heads, options) { + extendSelections(this, clipPosArray(this, heads), options) + }), + extendSelectionsBy: docMethodOp(function(f, options) { + var heads = map(this.sel.ranges, f) + extendSelections(this, clipPosArray(this, heads), options) + }), + setSelections: docMethodOp(function(ranges, primary, options) { + var this$1 = this; + + if (!ranges.length) { return } + var out = [] + for (var i = 0; i < ranges.length; i++) + { out[i] = new Range(clipPos(this$1, ranges[i].anchor), + clipPos(this$1, ranges[i].head)) } + if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex) } + setSelection(this, normalizeSelection(out, primary), options) + }), + addSelection: docMethodOp(function(anchor, head, options) { + var ranges = this.sel.ranges.slice(0) + ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))) + setSelection(this, normalizeSelection(ranges, ranges.length - 1), options) + }), + + getSelection: function(lineSep) { + var this$1 = this; + + var ranges = this.sel.ranges, lines + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()) + lines = lines ? lines.concat(sel) : sel + } + if (lineSep === false) { return lines } + else { return lines.join(lineSep || this.lineSeparator()) } + }, + getSelections: function(lineSep) { + var this$1 = this; + + var parts = [], ranges = this.sel.ranges + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()) + if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()) } + parts[i] = sel + } + return parts + }, + replaceSelection: function(code, collapse, origin) { + var dup = [] + for (var i = 0; i < this.sel.ranges.length; i++) + { dup[i] = code } + this.replaceSelections(dup, collapse, origin || "+input") + }, + replaceSelections: docMethodOp(function(code, collapse, origin) { + var this$1 = this; + + var changes = [], sel = this.sel + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i] + changes[i] = {from: range.from(), to: range.to(), text: this$1.splitLines(code[i]), origin: origin} + } + var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse) + for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) + { makeChange(this$1, changes[i$1]) } + if (newSel) { setSelectionReplaceHistory(this, newSel) } + else if (this.cm) { ensureCursorVisible(this.cm) } + }), + undo: docMethodOp(function() {makeChangeFromHistory(this, "undo")}), + redo: docMethodOp(function() {makeChangeFromHistory(this, "redo")}), + undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true)}), + redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true)}), + + setExtending: function(val) {this.extend = val}, + getExtending: function() {return this.extend}, + + historySize: function() { + var hist = this.history, done = 0, undone = 0 + for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done } } + for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone } } + return {undo: done, redo: undone} + }, + clearHistory: function() {this.history = new History(this.history.maxGeneration)}, + + markClean: function() { + this.cleanGeneration = this.changeGeneration(true) + }, + changeGeneration: function(forceSplit) { + if (forceSplit) + { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null } + return this.history.generation + }, + isClean: function (gen) { + return this.history.generation == (gen || this.cleanGeneration) + }, + + getHistory: function() { + return {done: copyHistoryArray(this.history.done), + undone: copyHistoryArray(this.history.undone)} + }, + setHistory: function(histData) { + var hist = this.history = new History(this.history.maxGeneration) + hist.done = copyHistoryArray(histData.done.slice(0), null, true) + hist.undone = copyHistoryArray(histData.undone.slice(0), null, true) + }, + + setGutterMarker: docMethodOp(function(line, gutterID, value) { + return changeLine(this, line, "gutter", function (line) { + var markers = line.gutterMarkers || (line.gutterMarkers = {}) + markers[gutterID] = value + if (!value && isEmpty(markers)) { line.gutterMarkers = null } + return true + }) + }), + + clearGutter: docMethodOp(function(gutterID) { + var this$1 = this; + + this.iter(function (line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + changeLine(this$1, line, "gutter", function () { + line.gutterMarkers[gutterID] = null + if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null } + return true + }) + } + }) + }), + + lineInfo: function(line) { + var n + if (typeof line == "number") { + if (!isLine(this, line)) { return null } + n = line + line = getLine(this, line) + if (!line) { return null } + } else { + n = lineNo(line) + if (n == null) { return null } + } + return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, + textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, + widgets: line.widgets} + }, + + addLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass" + if (!line[prop]) { line[prop] = cls } + else if (classTest(cls).test(line[prop])) { return false } + else { line[prop] += " " + cls } + return true + }) + }), + removeLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass" + var cur = line[prop] + if (!cur) { return false } + else if (cls == null) { line[prop] = null } + else { + var found = cur.match(classTest(cls)) + if (!found) { return false } + var end = found.index + found[0].length + line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null + } + return true + }) + }), + + addLineWidget: docMethodOp(function(handle, node, options) { + return addLineWidget(this, handle, node, options) + }), + removeLineWidget: function(widget) { widget.clear() }, + + markText: function(from, to, options) { + return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range") + }, + setBookmark: function(pos, options) { + var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft, + clearWhenEmpty: false, shared: options && options.shared, + handleMouseEvents: options && options.handleMouseEvents} + pos = clipPos(this, pos) + return markText(this, pos, pos, realOpts, "bookmark") + }, + findMarksAt: function(pos) { + pos = clipPos(this, pos) + var markers = [], spans = getLine(this, pos.line).markedSpans + if (spans) { for (var i = 0; i < spans.length; ++i) { + var span = spans[i] + if ((span.from == null || span.from <= pos.ch) && + (span.to == null || span.to >= pos.ch)) + { markers.push(span.marker.parent || span.marker) } + } } + return markers + }, + findMarks: function(from, to, filter) { + from = clipPos(this, from); to = clipPos(this, to) + var found = [], lineNo = from.line + this.iter(from.line, to.line + 1, function (line) { + var spans = line.markedSpans + if (spans) { for (var i = 0; i < spans.length; i++) { + var span = spans[i] + if (!(span.to != null && lineNo == from.line && from.ch >= span.to || + span.from == null && lineNo != from.line || + span.from != null && lineNo == to.line && span.from >= to.ch) && + (!filter || filter(span.marker))) + { found.push(span.marker.parent || span.marker) } + } } + ++lineNo + }) + return found + }, + getAllMarks: function() { + var markers = [] + this.iter(function (line) { + var sps = line.markedSpans + if (sps) { for (var i = 0; i < sps.length; ++i) + { if (sps[i].from != null) { markers.push(sps[i].marker) } } } + }) + return markers + }, + + posFromIndex: function(off) { + var ch, lineNo = this.first, sepSize = this.lineSeparator().length + this.iter(function (line) { + var sz = line.text.length + sepSize + if (sz > off) { ch = off; return true } + off -= sz + ++lineNo + }) + return clipPos(this, Pos(lineNo, ch)) + }, + indexFromPos: function (coords) { + coords = clipPos(this, coords) + var index = coords.ch + if (coords.line < this.first || coords.ch < 0) { return 0 } + var sepSize = this.lineSeparator().length + this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value + index += line.text.length + sepSize + }) + return index + }, + + copy: function(copyHistory) { + var doc = new Doc(getLines(this, this.first, this.first + this.size), + this.modeOption, this.first, this.lineSep, this.direction) + doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft + doc.sel = this.sel + doc.extend = false + if (copyHistory) { + doc.history.undoDepth = this.history.undoDepth + doc.setHistory(this.getHistory()) + } + return doc + }, + + linkedDoc: function(options) { + if (!options) { options = {} } + var from = this.first, to = this.first + this.size + if (options.from != null && options.from > from) { from = options.from } + if (options.to != null && options.to < to) { to = options.to } + var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction) + if (options.sharedHist) { copy.history = this.history + ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}) + copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}] + copySharedMarkers(copy, findSharedMarkers(this)) + return copy + }, + unlinkDoc: function(other) { + var this$1 = this; + + if (other instanceof CodeMirror) { other = other.doc } + if (this.linked) { for (var i = 0; i < this.linked.length; ++i) { + var link = this$1.linked[i] + if (link.doc != other) { continue } + this$1.linked.splice(i, 1) + other.unlinkDoc(this$1) + detachSharedMarkers(findSharedMarkers(this$1)) + break + } } + // If the histories were shared, split them again + if (other.history == this.history) { + var splitIds = [other.id] + linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true) + other.history = new History(null) + other.history.done = copyHistoryArray(this.history.done, splitIds) + other.history.undone = copyHistoryArray(this.history.undone, splitIds) + } + }, + iterLinkedDocs: function(f) {linkedDocs(this, f)}, + + getMode: function() {return this.mode}, + getEditor: function() {return this.cm}, + + splitLines: function(str) { + if (this.lineSep) { return str.split(this.lineSep) } + return splitLinesAuto(str) + }, + lineSeparator: function() { return this.lineSep || "\n" }, + + setDirection: docMethodOp(function (dir) { + if (dir != "rtl") { dir = "ltr" } + if (dir == this.direction) { return } + this.direction = dir + this.iter(function (line) { return line.order = null; }) + if (this.cm) { directionChanged(this.cm) } + }) +}) + +// Public alias. +Doc.prototype.eachLine = Doc.prototype.iter + +// Kludge to work around strange IE behavior where it'll sometimes +// re-fire a series of drag-related events right after the drop (#1551) +var lastDrop = 0 + +function onDrop(e) { + var cm = this + clearDragCursor(cm) + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) + { return } + e_preventDefault(e) + if (ie) { lastDrop = +new Date } + var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files + if (!pos || cm.isReadOnly()) { return } + // Might be a file drop, in which case we simply extract the text + // and insert it. + if (files && files.length && window.FileReader && window.File) { + var n = files.length, text = Array(n), read = 0 + var loadFile = function (file, i) { + if (cm.options.allowDropFileTypes && + indexOf(cm.options.allowDropFileTypes, file.type) == -1) + { return } + + var reader = new FileReader + reader.onload = operation(cm, function () { + var content = reader.result + if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = "" } + text[i] = content + if (++read == n) { + pos = clipPos(cm.doc, pos) + var change = {from: pos, to: pos, + text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), + origin: "paste"} + makeChange(cm.doc, change) + setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))) + } + }) + reader.readAsText(file) + } + for (var i = 0; i < n; ++i) { loadFile(files[i], i) } + } else { // Normal drop + // Don't do a replace if the drop happened inside of the selected text. + if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { + cm.state.draggingText(e) + // Ensure the editor is re-focused + setTimeout(function () { return cm.display.input.focus(); }, 20) + return + } + try { + var text$1 = e.dataTransfer.getData("Text") + if (text$1) { + var selected + if (cm.state.draggingText && !cm.state.draggingText.copy) + { selected = cm.listSelections() } + setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)) + if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1) + { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag") } } + cm.replaceSelection(text$1, "around", "paste") + cm.display.input.focus() + } + } + catch(e){} + } +} + +function onDragStart(cm, e) { + if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return } + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } + + e.dataTransfer.setData("Text", cm.getSelection()) + e.dataTransfer.effectAllowed = "copyMove" + + // Use dummy image instead of default browsers image. + // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. + if (e.dataTransfer.setDragImage && !safari) { + var img = elt("img", null, null, "position: fixed; left: 0; top: 0;") + img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" + if (presto) { + img.width = img.height = 1 + cm.display.wrapper.appendChild(img) + // Force a relayout, or Opera won't use our image for some obscure reason + img._top = img.offsetTop + } + e.dataTransfer.setDragImage(img, 0, 0) + if (presto) { img.parentNode.removeChild(img) } + } +} + +function onDragOver(cm, e) { + var pos = posFromMouse(cm, e) + if (!pos) { return } + var frag = document.createDocumentFragment() + drawSelectionCursor(cm, pos, frag) + if (!cm.display.dragCursor) { + cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors") + cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv) + } + removeChildrenAndAdd(cm.display.dragCursor, frag) +} + +function clearDragCursor(cm) { + if (cm.display.dragCursor) { + cm.display.lineSpace.removeChild(cm.display.dragCursor) + cm.display.dragCursor = null + } +} + +// These must be handled carefully, because naively registering a +// handler for each editor will cause the editors to never be +// garbage collected. + +function forEachCodeMirror(f) { + if (!document.getElementsByClassName) { return } + var byClass = document.getElementsByClassName("CodeMirror") + for (var i = 0; i < byClass.length; i++) { + var cm = byClass[i].CodeMirror + if (cm) { f(cm) } + } +} + +var globalsRegistered = false +function ensureGlobalHandlers() { + if (globalsRegistered) { return } + registerGlobalHandlers() + globalsRegistered = true +} +function registerGlobalHandlers() { + // When the window resizes, we need to refresh active editors. + var resizeTimer + on(window, "resize", function () { + if (resizeTimer == null) { resizeTimer = setTimeout(function () { + resizeTimer = null + forEachCodeMirror(onResize) + }, 100) } + }) + // When the window loses focus, we want to show the editor as blurred + on(window, "blur", function () { return forEachCodeMirror(onBlur); }) +} +// Called when the window resizes +function onResize(cm) { + var d = cm.display + // Might be a text scaling operation, clear size caches. + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null + d.scrollbarsClipped = false + cm.setSize() +} + +var keyNames = { + 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", + 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", + 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", + 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", + 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", 145: "ScrollLock", + 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", + 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", + 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" +} + +// Number keys +for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i) } +// Alphabetic keys +for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1) } +// Function keys +for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2 } + +var keyMap = {} + +keyMap.basic = { + "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", + "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", + "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", + "Tab": "defaultTab", "Shift-Tab": "indentAuto", + "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", + "Esc": "singleSelection" +} +// Note that the save and find-related commands aren't defined by +// default. User code or addons can define them. Unknown commands +// are simply ignored. +keyMap.pcDefault = { + "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", + "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", + "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", + "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", + "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", + "fallthrough": "basic" +} +// Very basic readline/emacs-style bindings, which are standard on Mac. +keyMap.emacsy = { + "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", + "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", + "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", + "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", + "Ctrl-O": "openLine" +} +keyMap.macDefault = { + "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", + "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", + "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", + "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", + "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", + "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", + "fallthrough": ["basic", "emacsy"] +} +keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault + +// KEYMAP DISPATCH + +function normalizeKeyName(name) { + var parts = name.split(/-(?!$)/) + name = parts[parts.length - 1] + var alt, ctrl, shift, cmd + for (var i = 0; i < parts.length - 1; i++) { + var mod = parts[i] + if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true } + else if (/^a(lt)?$/i.test(mod)) { alt = true } + else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true } + else if (/^s(hift)?$/i.test(mod)) { shift = true } + else { throw new Error("Unrecognized modifier name: " + mod) } + } + if (alt) { name = "Alt-" + name } + if (ctrl) { name = "Ctrl-" + name } + if (cmd) { name = "Cmd-" + name } + if (shift) { name = "Shift-" + name } + return name +} + +// This is a kludge to keep keymaps mostly working as raw objects +// (backwards compatibility) while at the same time support features +// like normalization and multi-stroke key bindings. It compiles a +// new normalized keymap, and then updates the old object to reflect +// this. +function normalizeKeyMap(keymap) { + var copy = {} + for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) { + var value = keymap[keyname] + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue } + if (value == "...") { delete keymap[keyname]; continue } + + var keys = map(keyname.split(" "), normalizeKeyName) + for (var i = 0; i < keys.length; i++) { + var val = (void 0), name = (void 0) + if (i == keys.length - 1) { + name = keys.join(" ") + val = value + } else { + name = keys.slice(0, i + 1).join(" ") + val = "..." + } + var prev = copy[name] + if (!prev) { copy[name] = val } + else if (prev != val) { throw new Error("Inconsistent bindings for " + name) } + } + delete keymap[keyname] + } } + for (var prop in copy) { keymap[prop] = copy[prop] } + return keymap +} + +function lookupKey(key, map, handle, context) { + map = getKeyMap(map) + var found = map.call ? map.call(key, context) : map[key] + if (found === false) { return "nothing" } + if (found === "...") { return "multi" } + if (found != null && handle(found)) { return "handled" } + + if (map.fallthrough) { + if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") + { return lookupKey(key, map.fallthrough, handle, context) } + for (var i = 0; i < map.fallthrough.length; i++) { + var result = lookupKey(key, map.fallthrough[i], handle, context) + if (result) { return result } + } + } +} + +// Modifier key presses don't count as 'real' key presses for the +// purpose of keymap fallthrough. +function isModifierKey(value) { + var name = typeof value == "string" ? value : keyNames[value.keyCode] + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" +} + +function addModifierNames(name, event, noShift) { + var base = name + if (event.altKey && base != "Alt") { name = "Alt-" + name } + if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name } + if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name } + if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name } + return name +} + +// Look up the name of a key as indicated by an event object. +function keyName(event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) { return false } + var name = keyNames[event.keyCode] + if (name == null || event.altGraphKey) { return false } + // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause, + // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+) + if (event.keyCode == 3 && event.code) { name = event.code } + return addModifierNames(name, event, noShift) +} + +function getKeyMap(val) { + return typeof val == "string" ? keyMap[val] : val +} + +// Helper for deleting text near the selection(s), used to implement +// backspace, delete, and similar functionality. +function deleteNearSelection(cm, compute) { + var ranges = cm.doc.sel.ranges, kill = [] + // Build up a set of ranges to kill first, merging overlapping + // ranges. + for (var i = 0; i < ranges.length; i++) { + var toKill = compute(ranges[i]) + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + var replaced = kill.pop() + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from + break + } + } + kill.push(toKill) + } + // Next, remove those actual ranges. + runInOp(cm, function () { + for (var i = kill.length - 1; i >= 0; i--) + { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete") } + ensureCursorVisible(cm) + }) +} + +function moveCharLogically(line, ch, dir) { + var target = skipExtendingChars(line.text, ch + dir, dir) + return target < 0 || target > line.text.length ? null : target +} + +function moveLogically(line, start, dir) { + var ch = moveCharLogically(line, start.ch, dir) + return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before") +} + +function endOfLine(visually, cm, lineObj, lineNo, dir) { + if (visually) { + var order = getOrder(lineObj, cm.doc.direction) + if (order) { + var part = dir < 0 ? lst(order) : order[0] + var moveInStorageOrder = (dir < 0) == (part.level == 1) + var sticky = moveInStorageOrder ? "after" : "before" + var ch + // With a wrapped rtl chunk (possibly spanning multiple bidi parts), + // it could be that the last bidi part is not on the last visual line, + // since visual lines contain content order-consecutive chunks. + // Thus, in rtl, we are looking for the first (content-order) character + // in the rtl chunk that is on the last line (that is, the same line + // as the last (content-order) character). + if (part.level > 0 || cm.doc.direction == "rtl") { + var prep = prepareMeasureForLine(cm, lineObj) + ch = dir < 0 ? lineObj.text.length - 1 : 0 + var targetTop = measureCharPrepared(cm, prep, ch).top + ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch) + if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1) } + } else { ch = dir < 0 ? part.to : part.from } + return new Pos(lineNo, ch, sticky) + } + } + return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after") +} + +function moveVisually(cm, line, start, dir) { + var bidi = getOrder(line, cm.doc.direction) + if (!bidi) { return moveLogically(line, start, dir) } + if (start.ch >= line.text.length) { + start.ch = line.text.length + start.sticky = "before" + } else if (start.ch <= 0) { + start.ch = 0 + start.sticky = "after" + } + var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos] + if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { + // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines, + // nothing interesting happens. + return moveLogically(line, start, dir) + } + + var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); } + var prep + var getWrappedLineExtent = function (ch) { + if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} } + prep = prep || prepareMeasureForLine(cm, line) + return wrappedLineExtentChar(cm, line, prep, ch) + } + var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch) + + if (cm.doc.direction == "rtl" || part.level == 1) { + var moveInStorageOrder = (part.level == 1) == (dir < 0) + var ch = mv(start, moveInStorageOrder ? 1 : -1) + if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) { + // Case 2: We move within an rtl part or in an rtl editor on the same visual line + var sticky = moveInStorageOrder ? "before" : "after" + return new Pos(start.line, ch, sticky) + } + } + + // Case 3: Could not move within this bidi part in this visual line, so leave + // the current bidi part + + var searchInVisualLine = function (partPos, dir, wrappedLineExtent) { + var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder + ? new Pos(start.line, mv(ch, 1), "before") + : new Pos(start.line, ch, "after"); } + + for (; partPos >= 0 && partPos < bidi.length; partPos += dir) { + var part = bidi[partPos] + var moveInStorageOrder = (dir > 0) == (part.level != 1) + var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1) + if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) } + ch = moveInStorageOrder ? part.from : mv(part.to, -1) + if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) } + } + } + + // Case 3a: Look for other bidi parts on the same visual line + var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent) + if (res) { return res } + + // Case 3b: Look for other bidi parts on the next visual line + var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1) + if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { + res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)) + if (res) { return res } + } + + // Case 4: Nowhere to move + return null +} + +// Commands are parameter-less actions that can be performed on an +// editor, mostly used for keybindings. +var commands = { + selectAll: selectAll, + singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); }, + killLine: function (cm) { return deleteNearSelection(cm, function (range) { + if (range.empty()) { + var len = getLine(cm.doc, range.head.line).text.length + if (range.head.ch == len && range.head.line < cm.lastLine()) + { return {from: range.head, to: Pos(range.head.line + 1, 0)} } + else + { return {from: range.head, to: Pos(range.head.line, len)} } + } else { + return {from: range.from(), to: range.to()} + } + }); }, + deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({ + from: Pos(range.from().line, 0), + to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) + }); }); }, + delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({ + from: Pos(range.from().line, 0), to: range.from() + }); }); }, + delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5 + var leftPos = cm.coordsChar({left: 0, top: top}, "div") + return {from: leftPos, to: range.from()} + }); }, + delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5 + var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") + return {from: range.from(), to: rightPos } + }); }, + undo: function (cm) { return cm.undo(); }, + redo: function (cm) { return cm.redo(); }, + undoSelection: function (cm) { return cm.undoSelection(); }, + redoSelection: function (cm) { return cm.redoSelection(); }, + goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); }, + goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); }, + goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, + {origin: "+move", bias: 1} + ); }, + goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); }, + {origin: "+move", bias: 1} + ); }, + goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, + {origin: "+move", bias: -1} + ); }, + goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.cursorCoords(range.head, "div").top + 5 + return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") + }, sel_move); }, + goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.cursorCoords(range.head, "div").top + 5 + return cm.coordsChar({left: 0, top: top}, "div") + }, sel_move); }, + goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.cursorCoords(range.head, "div").top + 5 + var pos = cm.coordsChar({left: 0, top: top}, "div") + if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) } + return pos + }, sel_move); }, + goLineUp: function (cm) { return cm.moveV(-1, "line"); }, + goLineDown: function (cm) { return cm.moveV(1, "line"); }, + goPageUp: function (cm) { return cm.moveV(-1, "page"); }, + goPageDown: function (cm) { return cm.moveV(1, "page"); }, + goCharLeft: function (cm) { return cm.moveH(-1, "char"); }, + goCharRight: function (cm) { return cm.moveH(1, "char"); }, + goColumnLeft: function (cm) { return cm.moveH(-1, "column"); }, + goColumnRight: function (cm) { return cm.moveH(1, "column"); }, + goWordLeft: function (cm) { return cm.moveH(-1, "word"); }, + goGroupRight: function (cm) { return cm.moveH(1, "group"); }, + goGroupLeft: function (cm) { return cm.moveH(-1, "group"); }, + goWordRight: function (cm) { return cm.moveH(1, "word"); }, + delCharBefore: function (cm) { return cm.deleteH(-1, "char"); }, + delCharAfter: function (cm) { return cm.deleteH(1, "char"); }, + delWordBefore: function (cm) { return cm.deleteH(-1, "word"); }, + delWordAfter: function (cm) { return cm.deleteH(1, "word"); }, + delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); }, + delGroupAfter: function (cm) { return cm.deleteH(1, "group"); }, + indentAuto: function (cm) { return cm.indentSelection("smart"); }, + indentMore: function (cm) { return cm.indentSelection("add"); }, + indentLess: function (cm) { return cm.indentSelection("subtract"); }, + insertTab: function (cm) { return cm.replaceSelection("\t"); }, + insertSoftTab: function (cm) { + var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize + for (var i = 0; i < ranges.length; i++) { + var pos = ranges[i].from() + var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize) + spaces.push(spaceStr(tabSize - col % tabSize)) + } + cm.replaceSelections(spaces) + }, + defaultTab: function (cm) { + if (cm.somethingSelected()) { cm.indentSelection("add") } + else { cm.execCommand("insertTab") } + }, + // Swap the two chars left and right of each selection's head. + // Move cursor behind the two swapped characters afterwards. + // + // Doesn't consider line feeds a character. + // Doesn't scan more than one line above to find a character. + // Doesn't do anything on an empty line. + // Doesn't do anything with non-empty selections. + transposeChars: function (cm) { return runInOp(cm, function () { + var ranges = cm.listSelections(), newSel = [] + for (var i = 0; i < ranges.length; i++) { + if (!ranges[i].empty()) { continue } + var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text + if (line) { + if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1) } + if (cur.ch > 0) { + cur = new Pos(cur.line, cur.ch + 1) + cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), + Pos(cur.line, cur.ch - 2), cur, "+transpose") + } else if (cur.line > cm.doc.first) { + var prev = getLine(cm.doc, cur.line - 1).text + if (prev) { + cur = new Pos(cur.line, 1) + cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + + prev.charAt(prev.length - 1), + Pos(cur.line - 1, prev.length - 1), cur, "+transpose") + } + } + } + newSel.push(new Range(cur, cur)) + } + cm.setSelections(newSel) + }); }, + newlineAndIndent: function (cm) { return runInOp(cm, function () { + var sels = cm.listSelections() + for (var i = sels.length - 1; i >= 0; i--) + { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input") } + sels = cm.listSelections() + for (var i$1 = 0; i$1 < sels.length; i$1++) + { cm.indentLine(sels[i$1].from().line, null, true) } + ensureCursorVisible(cm) + }); }, + openLine: function (cm) { return cm.replaceSelection("\n", "start"); }, + toggleOverwrite: function (cm) { return cm.toggleOverwrite(); } +} + + +function lineStart(cm, lineN) { + var line = getLine(cm.doc, lineN) + var visual = visualLine(line) + if (visual != line) { lineN = lineNo(visual) } + return endOfLine(true, cm, visual, lineN, 1) +} +function lineEnd(cm, lineN) { + var line = getLine(cm.doc, lineN) + var visual = visualLineEnd(line) + if (visual != line) { lineN = lineNo(visual) } + return endOfLine(true, cm, line, lineN, -1) +} +function lineStartSmart(cm, pos) { + var start = lineStart(cm, pos.line) + var line = getLine(cm.doc, start.line) + var order = getOrder(line, cm.doc.direction) + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(0, line.text.search(/\S/)) + var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch + return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky) + } + return start +} + +// Run a handler that was bound to a key. +function doHandleBinding(cm, bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound] + if (!bound) { return false } + } + // Ensure previous input has been read, so that the handler sees a + // consistent view of the document + cm.display.input.ensurePolled() + var prevShift = cm.display.shift, done = false + try { + if (cm.isReadOnly()) { cm.state.suppressEdits = true } + if (dropShift) { cm.display.shift = false } + done = bound(cm) != Pass + } finally { + cm.display.shift = prevShift + cm.state.suppressEdits = false + } + return done +} + +function lookupKeyForEditor(cm, name, handle) { + for (var i = 0; i < cm.state.keyMaps.length; i++) { + var result = lookupKey(name, cm.state.keyMaps[i], handle, cm) + if (result) { return result } + } + return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) + || lookupKey(name, cm.options.keyMap, handle, cm) +} + +// Note that, despite the name, this function is also used to check +// for bound mouse clicks. + +var stopSeq = new Delayed + +function dispatchKey(cm, name, e, handle) { + var seq = cm.state.keySeq + if (seq) { + if (isModifierKey(name)) { return "handled" } + if (/\'$/.test(name)) + { cm.state.keySeq = null } + else + { stopSeq.set(50, function () { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null + cm.display.input.reset() + } + }) } + if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true } + } + return dispatchKeyInner(cm, name, e, handle) +} + +function dispatchKeyInner(cm, name, e, handle) { + var result = lookupKeyForEditor(cm, name, handle) + + if (result == "multi") + { cm.state.keySeq = name } + if (result == "handled") + { signalLater(cm, "keyHandled", cm, name, e) } + + if (result == "handled" || result == "multi") { + e_preventDefault(e) + restartBlink(cm) + } + + return !!result +} + +// Handle a key from the keydown event. +function handleKeyBinding(cm, e) { + var name = keyName(e, true) + if (!name) { return false } + + if (e.shiftKey && !cm.state.keySeq) { + // First try to resolve full name (including 'Shift-'). Failing + // that, see if there is a cursor-motion command (starting with + // 'go') bound to the keyname without 'Shift-'. + return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); }) + || dispatchKey(cm, name, e, function (b) { + if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) + { return doHandleBinding(cm, b) } + }) + } else { + return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }) + } +} + +// Handle a key from the keypress event +function handleCharBinding(cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); }) +} + +var lastStoppedKey = null +function onKeyDown(e) { + var cm = this + cm.curOp.focus = activeElt() + if (signalDOMEvent(cm, e)) { return } + // IE does strange things with escape. + if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false } + var code = e.keyCode + cm.display.shift = code == 16 || e.shiftKey + var handled = handleKeyBinding(cm, e) + if (presto) { + lastStoppedKey = handled ? code : null + // Opera has no cut event... we try to at least catch the key combo + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) + { cm.replaceSelection("", null, "cut") } + } + + // Turn mouse into crosshair when Alt is held on Mac. + if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) + { showCrossHair(cm) } +} + +function showCrossHair(cm) { + var lineDiv = cm.display.lineDiv + addClass(lineDiv, "CodeMirror-crosshair") + + function up(e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair") + off(document, "keyup", up) + off(document, "mouseover", up) + } + } + on(document, "keyup", up) + on(document, "mouseover", up) +} + +function onKeyUp(e) { + if (e.keyCode == 16) { this.doc.sel.shift = false } + signalDOMEvent(this, e) +} + +function onKeyPress(e) { + var cm = this + if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return } + var keyCode = e.keyCode, charCode = e.charCode + if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} + if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return } + var ch = String.fromCharCode(charCode == null ? keyCode : charCode) + // Some browsers fire keypress events for backspace + if (ch == "\x08") { return } + if (handleCharBinding(cm, e, ch)) { return } + cm.display.input.onKeyPress(e) +} + +var DOUBLECLICK_DELAY = 400 + +var PastClick = function(time, pos, button) { + this.time = time + this.pos = pos + this.button = button +}; + +PastClick.prototype.compare = function (time, pos, button) { + return this.time + DOUBLECLICK_DELAY > time && + cmp(pos, this.pos) == 0 && button == this.button +}; + +var lastClick; +var lastDoubleClick; +function clickRepeat(pos, button) { + var now = +new Date + if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { + lastClick = lastDoubleClick = null + return "triple" + } else if (lastClick && lastClick.compare(now, pos, button)) { + lastDoubleClick = new PastClick(now, pos, button) + lastClick = null + return "double" + } else { + lastClick = new PastClick(now, pos, button) + lastDoubleClick = null + return "single" + } +} + +// A mouse down can be a single click, double click, triple click, +// start of selection drag, start of text drag, new cursor +// (ctrl-click), rectangle drag (alt-drag), or xwin +// middle-click-paste. Or it might be a click on something we should +// not interfere with, such as a scrollbar or widget. +function onMouseDown(e) { + var cm = this, display = cm.display + if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return } + display.input.ensurePolled() + display.shift = e.shiftKey + + if (eventInWidget(display, e)) { + if (!webkit) { + // Briefly turn off draggability, to allow widgets to do + // normal dragging things. + display.scroller.draggable = false + setTimeout(function () { return display.scroller.draggable = true; }, 100) + } + return + } + var button = e_button(e) + if (button == 3 && captureRightClick ? contextMenuInGutter(cm, e) : clickInGutter(cm, e)) { return } + var pos = posFromMouse(cm, e), repeat = pos ? clickRepeat(pos, button) : "single" + window.focus() + + // #3261: make sure, that we're not starting a second selection + if (button == 1 && cm.state.selectingText) + { cm.state.selectingText(e) } + + if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return } + + if (button == 1) { + if (pos) { leftButtonDown(cm, pos, repeat, e) } + else if (e_target(e) == display.scroller) { e_preventDefault(e) } + } else if (button == 2) { + if (pos) { extendSelection(cm.doc, pos) } + setTimeout(function () { return display.input.focus(); }, 20) + } else if (button == 3) { + if (captureRightClick) { onContextMenu(cm, e) } + else { delayBlurEvent(cm) } + } +} + +function handleMappedButton(cm, button, pos, repeat, event) { + var name = "Click" + if (repeat == "double") { name = "Double" + name } + else if (repeat == "triple") { name = "Triple" + name } + name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name + + return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { + if (typeof bound == "string") { bound = commands[bound] } + if (!bound) { return false } + var done = false + try { + if (cm.isReadOnly()) { cm.state.suppressEdits = true } + done = bound(cm, pos) != Pass + } finally { + cm.state.suppressEdits = false + } + return done + }) +} + +function configureMouse(cm, repeat, event) { + var option = cm.getOption("configureMouse") + var value = option ? option(cm, repeat, event) : {} + if (value.unit == null) { + var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey + value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line" + } + if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey } + if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey } + if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey) } + return value +} + +function leftButtonDown(cm, pos, repeat, event) { + if (ie) { setTimeout(bind(ensureFocus, cm), 0) } + else { cm.curOp.focus = activeElt() } + + var behavior = configureMouse(cm, repeat, event) + + var sel = cm.doc.sel, contained + if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && + repeat == "single" && (contained = sel.contains(pos)) > -1 && + (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && + (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) + { leftButtonStartDrag(cm, event, pos, behavior) } + else + { leftButtonSelect(cm, event, pos, behavior) } +} + +// Start a text drag. When it ends, see if any dragging actually +// happen, and treat as a click if it didn't. +function leftButtonStartDrag(cm, event, pos, behavior) { + var display = cm.display, moved = false + var dragEnd = operation(cm, function (e) { + if (webkit) { display.scroller.draggable = false } + cm.state.draggingText = false + off(display.wrapper.ownerDocument, "mouseup", dragEnd) + off(display.wrapper.ownerDocument, "mousemove", mouseMove) + off(display.scroller, "dragstart", dragStart) + off(display.scroller, "drop", dragEnd) + if (!moved) { + e_preventDefault(e) + if (!behavior.addNew) + { extendSelection(cm.doc, pos, null, null, behavior.extend) } + // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) + if (webkit || ie && ie_version == 9) + { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus()}, 20) } + else + { display.input.focus() } + } + }) + var mouseMove = function(e2) { + moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10 + } + var dragStart = function () { return moved = true; } + // Let the drag handler handle this. + if (webkit) { display.scroller.draggable = true } + cm.state.draggingText = dragEnd + dragEnd.copy = !behavior.moveOnDrag + // IE's approach to draggable + if (display.scroller.dragDrop) { display.scroller.dragDrop() } + on(display.wrapper.ownerDocument, "mouseup", dragEnd) + on(display.wrapper.ownerDocument, "mousemove", mouseMove) + on(display.scroller, "dragstart", dragStart) + on(display.scroller, "drop", dragEnd) + + delayBlurEvent(cm) + setTimeout(function () { return display.input.focus(); }, 20) +} + +function rangeForUnit(cm, pos, unit) { + if (unit == "char") { return new Range(pos, pos) } + if (unit == "word") { return cm.findWordAt(pos) } + if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) } + var result = unit(cm, pos) + return new Range(result.from, result.to) +} + +// Normal selection, as opposed to text dragging. +function leftButtonSelect(cm, event, start, behavior) { + var display = cm.display, doc = cm.doc + e_preventDefault(event) + + var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges + if (behavior.addNew && !behavior.extend) { + ourIndex = doc.sel.contains(start) + if (ourIndex > -1) + { ourRange = ranges[ourIndex] } + else + { ourRange = new Range(start, start) } + } else { + ourRange = doc.sel.primary() + ourIndex = doc.sel.primIndex + } + + if (behavior.unit == "rectangle") { + if (!behavior.addNew) { ourRange = new Range(start, start) } + start = posFromMouse(cm, event, true, true) + ourIndex = -1 + } else { + var range = rangeForUnit(cm, start, behavior.unit) + if (behavior.extend) + { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend) } + else + { ourRange = range } + } + + if (!behavior.addNew) { + ourIndex = 0 + setSelection(doc, new Selection([ourRange], 0), sel_mouse) + startSel = doc.sel + } else if (ourIndex == -1) { + ourIndex = ranges.length + setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), + {scroll: false, origin: "*mouse"}) + } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { + setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), + {scroll: false, origin: "*mouse"}) + startSel = doc.sel + } else { + replaceOneSelection(doc, ourIndex, ourRange, sel_mouse) + } + + var lastPos = start + function extendTo(pos) { + if (cmp(lastPos, pos) == 0) { return } + lastPos = pos + + if (behavior.unit == "rectangle") { + var ranges = [], tabSize = cm.options.tabSize + var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize) + var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize) + var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol) + for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); + line <= end; line++) { + var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize) + if (left == right) + { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))) } + else if (text.length > leftPos) + { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))) } + } + if (!ranges.length) { ranges.push(new Range(start, start)) } + setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), + {origin: "*mouse", scroll: false}) + cm.scrollIntoView(pos) + } else { + var oldRange = ourRange + var range = rangeForUnit(cm, pos, behavior.unit) + var anchor = oldRange.anchor, head + if (cmp(range.anchor, anchor) > 0) { + head = range.head + anchor = minPos(oldRange.from(), range.anchor) + } else { + head = range.anchor + anchor = maxPos(oldRange.to(), range.head) + } + var ranges$1 = startSel.ranges.slice(0) + ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head)) + setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse) + } + } + + var editorSize = display.wrapper.getBoundingClientRect() + // Used to ensure timeout re-tries don't fire when another extend + // happened in the meantime (clearTimeout isn't reliable -- at + // least on Chrome, the timeouts still happen even when cleared, + // if the clear happens after their scheduled firing time). + var counter = 0 + + function extend(e) { + var curCount = ++counter + var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle") + if (!cur) { return } + if (cmp(cur, lastPos) != 0) { + cm.curOp.focus = activeElt() + extendTo(cur) + var visible = visibleLines(display, doc) + if (cur.line >= visible.to || cur.line < visible.from) + { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e) }}), 150) } + } else { + var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0 + if (outside) { setTimeout(operation(cm, function () { + if (counter != curCount) { return } + display.scroller.scrollTop += outside + extend(e) + }), 50) } + } + } + + function done(e) { + cm.state.selectingText = false + counter = Infinity + e_preventDefault(e) + display.input.focus() + off(display.wrapper.ownerDocument, "mousemove", move) + off(display.wrapper.ownerDocument, "mouseup", up) + doc.history.lastSelOrigin = null + } + + var move = operation(cm, function (e) { + if (e.buttons === 0 || !e_button(e)) { done(e) } + else { extend(e) } + }) + var up = operation(cm, done) + cm.state.selectingText = up + on(display.wrapper.ownerDocument, "mousemove", move) + on(display.wrapper.ownerDocument, "mouseup", up) +} + +// Used when mouse-selecting to adjust the anchor to the proper side +// of a bidi jump depending on the visual position of the head. +function bidiSimplify(cm, range) { + var anchor = range.anchor; + var head = range.head; + var anchorLine = getLine(cm.doc, anchor.line) + if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range } + var order = getOrder(anchorLine) + if (!order) { return range } + var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index] + if (part.from != anchor.ch && part.to != anchor.ch) { return range } + var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1) + if (boundary == 0 || boundary == order.length) { return range } + + // Compute the relative visual position of the head compared to the + // anchor (<0 is to the left, >0 to the right) + var leftSide + if (head.line != anchor.line) { + leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0 + } else { + var headIndex = getBidiPartAt(order, head.ch, head.sticky) + var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1) + if (headIndex == boundary - 1 || headIndex == boundary) + { leftSide = dir < 0 } + else + { leftSide = dir > 0 } + } + + var usePart = order[boundary + (leftSide ? -1 : 0)] + var from = leftSide == (usePart.level == 1) + var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before" + return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head) +} + + +// Determines whether an event happened in the gutter, and fires the +// handlers for the corresponding event. +function gutterEvent(cm, e, type, prevent) { + var mX, mY + if (e.touches) { + mX = e.touches[0].clientX + mY = e.touches[0].clientY + } else { + try { mX = e.clientX; mY = e.clientY } + catch(e) { return false } + } + if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false } + if (prevent) { e_preventDefault(e) } + + var display = cm.display + var lineBox = display.lineDiv.getBoundingClientRect() + + if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) } + mY -= lineBox.top - display.viewOffset + + for (var i = 0; i < cm.options.gutters.length; ++i) { + var g = display.gutters.childNodes[i] + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY) + var gutter = cm.options.gutters[i] + signal(cm, type, cm, line, gutter, e) + return e_defaultPrevented(e) + } + } +} + +function clickInGutter(cm, e) { + return gutterEvent(cm, e, "gutterClick", true) +} + +// CONTEXT MENU HANDLING + +// To make the context menu work, we need to briefly unhide the +// textarea (making it as unobtrusive as possible) to let the +// right-click take effect on it. +function onContextMenu(cm, e) { + if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return } + if (signalDOMEvent(cm, e, "contextmenu")) { return } + cm.display.input.onContextMenu(e) +} + +function contextMenuInGutter(cm, e) { + if (!hasHandler(cm, "gutterContextMenu")) { return false } + return gutterEvent(cm, e, "gutterContextMenu", false) +} + +function themeChanged(cm) { + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-") + clearCaches(cm) +} + +var Init = {toString: function(){return "CodeMirror.Init"}} + +var defaults = {} +var optionHandlers = {} + +function defineOptions(CodeMirror) { + var optionHandlers = CodeMirror.optionHandlers + + function option(name, deflt, handle, notOnInit) { + CodeMirror.defaults[name] = deflt + if (handle) { optionHandlers[name] = + notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old) }} : handle } + } + + CodeMirror.defineOption = option + + // Passed to option handlers when there is no old value. + CodeMirror.Init = Init + + // These two are, on init, called from the constructor because they + // have to be initialized before the editor can start at all. + option("value", "", function (cm, val) { return cm.setValue(val); }, true) + option("mode", null, function (cm, val) { + cm.doc.modeOption = val + loadMode(cm) + }, true) + + option("indentUnit", 2, loadMode, true) + option("indentWithTabs", false) + option("smartIndent", true) + option("tabSize", 4, function (cm) { + resetModeState(cm) + clearCaches(cm) + regChange(cm) + }, true) + + option("lineSeparator", null, function (cm, val) { + cm.doc.lineSep = val + if (!val) { return } + var newBreaks = [], lineNo = cm.doc.first + cm.doc.iter(function (line) { + for (var pos = 0;;) { + var found = line.text.indexOf(val, pos) + if (found == -1) { break } + pos = found + val.length + newBreaks.push(Pos(lineNo, found)) + } + lineNo++ + }) + for (var i = newBreaks.length - 1; i >= 0; i--) + { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) } + }) + option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) { + cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g") + if (old != Init) { cm.refresh() } + }) + option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true) + option("electricChars", true) + option("inputStyle", mobile ? "contenteditable" : "textarea", function () { + throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME + }, true) + option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true) + option("rtlMoveVisually", !windows) + option("wholeLineUpdateBefore", true) + + option("theme", "default", function (cm) { + themeChanged(cm) + guttersChanged(cm) + }, true) + option("keyMap", "default", function (cm, val, old) { + var next = getKeyMap(val) + var prev = old != Init && getKeyMap(old) + if (prev && prev.detach) { prev.detach(cm, next) } + if (next.attach) { next.attach(cm, prev || null) } + }) + option("extraKeys", null) + option("configureMouse", null) + + option("lineWrapping", false, wrappingChanged, true) + option("gutters", [], function (cm) { + setGuttersForLineNumbers(cm.options) + guttersChanged(cm) + }, true) + option("fixedGutter", true, function (cm, val) { + cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0" + cm.refresh() + }, true) + option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true) + option("scrollbarStyle", "native", function (cm) { + initScrollbars(cm) + updateScrollbars(cm) + cm.display.scrollbars.setScrollTop(cm.doc.scrollTop) + cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft) + }, true) + option("lineNumbers", false, function (cm) { + setGuttersForLineNumbers(cm.options) + guttersChanged(cm) + }, true) + option("firstLineNumber", 1, guttersChanged, true) + option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true) + option("showCursorWhenSelecting", false, updateSelection, true) + + option("resetSelectionOnContextMenu", true) + option("lineWiseCopyCut", true) + option("pasteLinesPerSelection", true) + + option("readOnly", false, function (cm, val) { + if (val == "nocursor") { + onBlur(cm) + cm.display.input.blur() + } + cm.display.input.readOnlyChanged(val) + }) + option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset() }}, true) + option("dragDrop", true, dragDropChanged) + option("allowDropFileTypes", null) + + option("cursorBlinkRate", 530) + option("cursorScrollMargin", 0) + option("cursorHeight", 1, updateSelection, true) + option("singleCursorHeightPerLine", true, updateSelection, true) + option("workTime", 100) + option("workDelay", 100) + option("flattenSpans", true, resetModeState, true) + option("addModeClass", false, resetModeState, true) + option("pollInterval", 100) + option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; }) + option("historyEventDelay", 1250) + option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true) + option("maxHighlightLength", 10000, resetModeState, true) + option("moveInputWithCursor", true, function (cm, val) { + if (!val) { cm.display.input.resetPosition() } + }) + + option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; }) + option("autofocus", null) + option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true) + option("phrases", null) +} + +function guttersChanged(cm) { + updateGutters(cm) + regChange(cm) + alignHorizontally(cm) +} + +function dragDropChanged(cm, value, old) { + var wasOn = old && old != Init + if (!value != !wasOn) { + var funcs = cm.display.dragFunctions + var toggle = value ? on : off + toggle(cm.display.scroller, "dragstart", funcs.start) + toggle(cm.display.scroller, "dragenter", funcs.enter) + toggle(cm.display.scroller, "dragover", funcs.over) + toggle(cm.display.scroller, "dragleave", funcs.leave) + toggle(cm.display.scroller, "drop", funcs.drop) + } +} + +function wrappingChanged(cm) { + if (cm.options.lineWrapping) { + addClass(cm.display.wrapper, "CodeMirror-wrap") + cm.display.sizer.style.minWidth = "" + cm.display.sizerWidth = null + } else { + rmClass(cm.display.wrapper, "CodeMirror-wrap") + findMaxLine(cm) + } + estimateLineHeights(cm) + regChange(cm) + clearCaches(cm) + setTimeout(function () { return updateScrollbars(cm); }, 100) +} + +// A CodeMirror instance represents an editor. This is the object +// that user code is usually dealing with. + +function CodeMirror(place, options) { + var this$1 = this; + + if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) } + + this.options = options = options ? copyObj(options) : {} + // Determine effective options based on given values and defaults. + copyObj(defaults, options, false) + setGuttersForLineNumbers(options) + + var doc = options.value + if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction) } + else if (options.mode) { doc.modeOption = options.mode } + this.doc = doc + + var input = new CodeMirror.inputStyles[options.inputStyle](this) + var display = this.display = new Display(place, doc, input) + display.wrapper.CodeMirror = this + updateGutters(this) + themeChanged(this) + if (options.lineWrapping) + { this.display.wrapper.className += " CodeMirror-wrap" } + initScrollbars(this) + + this.state = { + keyMaps: [], // stores maps added by addKeyMap + overlays: [], // highlighting overlays, as added by addOverlay + modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info + overwrite: false, + delayingBlurEvent: false, + focused: false, + suppressEdits: false, // used to disable editing during key handlers when in readOnly mode + pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll + selectingText: false, + draggingText: false, + highlight: new Delayed(), // stores highlight worker timeout + keySeq: null, // Unfinished key sequence + specialChars: null + } + + if (options.autofocus && !mobile) { display.input.focus() } + + // Override magic textarea content restore that IE sometimes does + // on our hidden textarea on reload + if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20) } + + registerEventHandlers(this) + ensureGlobalHandlers() + + startOperation(this) + this.curOp.forceUpdate = true + attachDoc(this, doc) + + if ((options.autofocus && !mobile) || this.hasFocus()) + { setTimeout(bind(onFocus, this), 20) } + else + { onBlur(this) } + + for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt)) + { optionHandlers[opt](this$1, options[opt], Init) } } + maybeUpdateLineNumberWidth(this) + if (options.finishInit) { options.finishInit(this) } + for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1) } + endOperation(this) + // Suppress optimizelegibility in Webkit, since it breaks text + // measuring on line wrapping boundaries. + if (webkit && options.lineWrapping && + getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") + { display.lineDiv.style.textRendering = "auto" } +} + +// The default configuration options. +CodeMirror.defaults = defaults +// Functions to run when options are changed. +CodeMirror.optionHandlers = optionHandlers + +// Attach the necessary event handlers when initializing the editor +function registerEventHandlers(cm) { + var d = cm.display + on(d.scroller, "mousedown", operation(cm, onMouseDown)) + // Older IE's will not fire a second mousedown for a double click + if (ie && ie_version < 11) + { on(d.scroller, "dblclick", operation(cm, function (e) { + if (signalDOMEvent(cm, e)) { return } + var pos = posFromMouse(cm, e) + if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return } + e_preventDefault(e) + var word = cm.findWordAt(pos) + extendSelection(cm.doc, word.anchor, word.head) + })) } + else + { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }) } + // Some browsers fire contextmenu *after* opening the menu, at + // which point we can't mess with it anymore. Context menu is + // handled in onMouseDown for these browsers. + if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }) } + + // Used to suppress mouse event handling when a touch happens + var touchFinished, prevTouch = {end: 0} + function finishTouch() { + if (d.activeTouch) { + touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000) + prevTouch = d.activeTouch + prevTouch.end = +new Date + } + } + function isMouseLikeTouchEvent(e) { + if (e.touches.length != 1) { return false } + var touch = e.touches[0] + return touch.radiusX <= 1 && touch.radiusY <= 1 + } + function farAway(touch, other) { + if (other.left == null) { return true } + var dx = other.left - touch.left, dy = other.top - touch.top + return dx * dx + dy * dy > 20 * 20 + } + on(d.scroller, "touchstart", function (e) { + if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { + d.input.ensurePolled() + clearTimeout(touchFinished) + var now = +new Date + d.activeTouch = {start: now, moved: false, + prev: now - prevTouch.end <= 300 ? prevTouch : null} + if (e.touches.length == 1) { + d.activeTouch.left = e.touches[0].pageX + d.activeTouch.top = e.touches[0].pageY + } + } + }) + on(d.scroller, "touchmove", function () { + if (d.activeTouch) { d.activeTouch.moved = true } + }) + on(d.scroller, "touchend", function (e) { + var touch = d.activeTouch + if (touch && !eventInWidget(d, e) && touch.left != null && + !touch.moved && new Date - touch.start < 300) { + var pos = cm.coordsChar(d.activeTouch, "page"), range + if (!touch.prev || farAway(touch, touch.prev)) // Single tap + { range = new Range(pos, pos) } + else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap + { range = cm.findWordAt(pos) } + else // Triple tap + { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) } + cm.setSelection(range.anchor, range.head) + cm.focus() + e_preventDefault(e) + } + finishTouch() + }) + on(d.scroller, "touchcancel", finishTouch) + + // Sync scrolling between fake scrollbars and real scrollable + // area, ensure viewport is updated when scrolling. + on(d.scroller, "scroll", function () { + if (d.scroller.clientHeight) { + updateScrollTop(cm, d.scroller.scrollTop) + setScrollLeft(cm, d.scroller.scrollLeft, true) + signal(cm, "scroll", cm) + } + }) + + // Listen to wheel events in order to try and update the viewport on time. + on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); }) + on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); }) + + // Prevent wrapper from ever scrolling + on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }) + + d.dragFunctions = { + enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e) }}, + over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e) }}, + start: function (e) { return onDragStart(cm, e); }, + drop: operation(cm, onDrop), + leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm) }} + } + + var inp = d.input.getField() + on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); }) + on(inp, "keydown", operation(cm, onKeyDown)) + on(inp, "keypress", operation(cm, onKeyPress)) + on(inp, "focus", function (e) { return onFocus(cm, e); }) + on(inp, "blur", function (e) { return onBlur(cm, e); }) +} + +var initHooks = [] +CodeMirror.defineInitHook = function (f) { return initHooks.push(f); } + +// Indent the given line. The how parameter can be "smart", +// "add"/null, "subtract", or "prev". When aggressive is false +// (typically set to true for forced single-line indents), empty +// lines are not indented, and places where the mode returns Pass +// are left alone. +function indentLine(cm, n, how, aggressive) { + var doc = cm.doc, state + if (how == null) { how = "add" } + if (how == "smart") { + // Fall back to "prev" when the mode doesn't have an indentation + // method. + if (!doc.mode.indent) { how = "prev" } + else { state = getContextBefore(cm, n).state } + } + + var tabSize = cm.options.tabSize + var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize) + if (line.stateAfter) { line.stateAfter = null } + var curSpaceString = line.text.match(/^\s*/)[0], indentation + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0 + how = "not" + } else if (how == "smart") { + indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text) + if (indentation == Pass || indentation > 150) { + if (!aggressive) { return } + how = "prev" + } + } + if (how == "prev") { + if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize) } + else { indentation = 0 } + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit + } else if (typeof how == "number") { + indentation = curSpace + how + } + indentation = Math.max(0, indentation) + + var indentString = "", pos = 0 + if (cm.options.indentWithTabs) + { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t"} } + if (pos < indentation) { indentString += spaceStr(indentation - pos) } + + if (indentString != curSpaceString) { + replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input") + line.stateAfter = null + return true + } else { + // Ensure that, if the cursor was in the whitespace at the start + // of the line, it is moved to the end of that space. + for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) { + var range = doc.sel.ranges[i$1] + if (range.head.line == n && range.head.ch < curSpaceString.length) { + var pos$1 = Pos(n, curSpaceString.length) + replaceOneSelection(doc, i$1, new Range(pos$1, pos$1)) + break + } + } + } +} + +// This will be set to a {lineWise: bool, text: [string]} object, so +// that, when pasting, we know what kind of selections the copied +// text was made out of. +var lastCopied = null + +function setLastCopied(newLastCopied) { + lastCopied = newLastCopied +} + +function applyTextInput(cm, inserted, deleted, sel, origin) { + var doc = cm.doc + cm.display.shift = false + if (!sel) { sel = doc.sel } + + var paste = cm.state.pasteIncoming || origin == "paste" + var textLines = splitLinesAuto(inserted), multiPaste = null + // When pasting N lines into N selections, insert one line per selection + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.text.join("\n") == inserted) { + if (sel.ranges.length % lastCopied.text.length == 0) { + multiPaste = [] + for (var i = 0; i < lastCopied.text.length; i++) + { multiPaste.push(doc.splitLines(lastCopied.text[i])) } + } + } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { + multiPaste = map(textLines, function (l) { return [l]; }) + } + } + + var updateInput + // Normal behavior is to insert the new text into every selection + for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) { + var range = sel.ranges[i$1] + var from = range.from(), to = range.to() + if (range.empty()) { + if (deleted && deleted > 0) // Handle deletion + { from = Pos(from.line, from.ch - deleted) } + else if (cm.state.overwrite && !paste) // Handle overwrite + { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)) } + else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) + { from = to = Pos(from.line, 0) } + } + updateInput = cm.curOp.updateInput + var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")} + makeChange(cm.doc, changeEvent) + signalLater(cm, "inputRead", cm, changeEvent) + } + if (inserted && !paste) + { triggerElectric(cm, inserted) } + + ensureCursorVisible(cm) + cm.curOp.updateInput = updateInput + cm.curOp.typing = true + cm.state.pasteIncoming = cm.state.cutIncoming = false +} + +function handlePaste(e, cm) { + var pasted = e.clipboardData && e.clipboardData.getData("Text") + if (pasted) { + e.preventDefault() + if (!cm.isReadOnly() && !cm.options.disableInput) + { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }) } + return true + } +} + +function triggerElectric(cm, inserted) { + // When an 'electric' character is inserted, immediately trigger a reindent + if (!cm.options.electricChars || !cm.options.smartIndent) { return } + var sel = cm.doc.sel + + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i] + if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue } + var mode = cm.getModeAt(range.head) + var indented = false + if (mode.electricChars) { + for (var j = 0; j < mode.electricChars.length; j++) + { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range.head.line, "smart") + break + } } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) + { indented = indentLine(cm, range.head.line, "smart") } + } + if (indented) { signalLater(cm, "electricInput", cm, range.head.line) } + } +} + +function copyableRanges(cm) { + var text = [], ranges = [] + for (var i = 0; i < cm.doc.sel.ranges.length; i++) { + var line = cm.doc.sel.ranges[i].head.line + var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)} + ranges.push(lineRange) + text.push(cm.getRange(lineRange.anchor, lineRange.head)) + } + return {text: text, ranges: ranges} +} + +function disableBrowserMagic(field, spellcheck) { + field.setAttribute("autocorrect", "off") + field.setAttribute("autocapitalize", "off") + field.setAttribute("spellcheck", !!spellcheck) +} + +function hiddenTextarea() { + var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none") + var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;") + // The textarea is kept positioned near the cursor to prevent the + // fact that it'll be scrolled into view on input from scrolling + // our fake cursor out of view. On webkit, when wrap=off, paste is + // very slow. So make the area wide instead. + if (webkit) { te.style.width = "1000px" } + else { te.setAttribute("wrap", "off") } + // If border: 0; -- iOS fails to open keyboard (issue #1287) + if (ios) { te.style.border = "1px solid black" } + disableBrowserMagic(te) + return div +} + +// The publicly visible API. Note that methodOp(f) means +// 'wrap f in an operation, performed on its `this` parameter'. + +// This is not the complete set of editor methods. Most of the +// methods defined on the Doc type are also injected into +// CodeMirror.prototype, for backwards compatibility and +// convenience. + +function addEditorMethods(CodeMirror) { + var optionHandlers = CodeMirror.optionHandlers + + var helpers = CodeMirror.helpers = {} + + CodeMirror.prototype = { + constructor: CodeMirror, + focus: function(){window.focus(); this.display.input.focus()}, + + setOption: function(option, value) { + var options = this.options, old = options[option] + if (options[option] == value && option != "mode") { return } + options[option] = value + if (optionHandlers.hasOwnProperty(option)) + { operation(this, optionHandlers[option])(this, value, old) } + signal(this, "optionChange", this, option) + }, + + getOption: function(option) {return this.options[option]}, + getDoc: function() {return this.doc}, + + addKeyMap: function(map, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)) + }, + removeKeyMap: function(map) { + var maps = this.state.keyMaps + for (var i = 0; i < maps.length; ++i) + { if (maps[i] == map || maps[i].name == map) { + maps.splice(i, 1) + return true + } } + }, + + addOverlay: methodOp(function(spec, options) { + var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec) + if (mode.startState) { throw new Error("Overlays may not be stateful.") } + insertSorted(this.state.overlays, + {mode: mode, modeSpec: spec, opaque: options && options.opaque, + priority: (options && options.priority) || 0}, + function (overlay) { return overlay.priority; }) + this.state.modeGen++ + regChange(this) + }), + removeOverlay: methodOp(function(spec) { + var this$1 = this; + + var overlays = this.state.overlays + for (var i = 0; i < overlays.length; ++i) { + var cur = overlays[i].modeSpec + if (cur == spec || typeof spec == "string" && cur.name == spec) { + overlays.splice(i, 1) + this$1.state.modeGen++ + regChange(this$1) + return + } + } + }), + + indentLine: methodOp(function(n, dir, aggressive) { + if (typeof dir != "string" && typeof dir != "number") { + if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev" } + else { dir = dir ? "add" : "subtract" } + } + if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive) } + }), + indentSelection: methodOp(function(how) { + var this$1 = this; + + var ranges = this.doc.sel.ranges, end = -1 + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i] + if (!range.empty()) { + var from = range.from(), to = range.to() + var start = Math.max(end, from.line) + end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1 + for (var j = start; j < end; ++j) + { indentLine(this$1, j, how) } + var newRanges = this$1.doc.sel.ranges + if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) + { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll) } + } else if (range.head.line > end) { + indentLine(this$1, range.head.line, how, true) + end = range.head.line + if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1) } + } + } + }), + + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function(pos, precise) { + return takeToken(this, pos, precise) + }, + + getLineTokens: function(line, precise) { + return takeToken(this, Pos(line), precise, true) + }, + + getTokenTypeAt: function(pos) { + pos = clipPos(this.doc, pos) + var styles = getLineStyles(this, getLine(this.doc, pos.line)) + var before = 0, after = (styles.length - 1) / 2, ch = pos.ch + var type + if (ch == 0) { type = styles[2] } + else { for (;;) { + var mid = (before + after) >> 1 + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid } + else if (styles[mid * 2 + 1] < ch) { before = mid + 1 } + else { type = styles[mid * 2 + 2]; break } + } } + var cut = type ? type.indexOf("overlay ") : -1 + return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1) + }, + + getModeAt: function(pos) { + var mode = this.doc.mode + if (!mode.innerMode) { return mode } + return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode + }, + + getHelper: function(pos, type) { + return this.getHelpers(pos, type)[0] + }, + + getHelpers: function(pos, type) { + var this$1 = this; + + var found = [] + if (!helpers.hasOwnProperty(type)) { return found } + var help = helpers[type], mode = this.getModeAt(pos) + if (typeof mode[type] == "string") { + if (help[mode[type]]) { found.push(help[mode[type]]) } + } else if (mode[type]) { + for (var i = 0; i < mode[type].length; i++) { + var val = help[mode[type][i]] + if (val) { found.push(val) } + } + } else if (mode.helperType && help[mode.helperType]) { + found.push(help[mode.helperType]) + } else if (help[mode.name]) { + found.push(help[mode.name]) + } + for (var i$1 = 0; i$1 < help._global.length; i$1++) { + var cur = help._global[i$1] + if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1) + { found.push(cur.val) } + } + return found + }, + + getStateAfter: function(line, precise) { + var doc = this.doc + line = clipLine(doc, line == null ? doc.first + doc.size - 1: line) + return getContextBefore(this, line + 1, precise).state + }, + + cursorCoords: function(start, mode) { + var pos, range = this.doc.sel.primary() + if (start == null) { pos = range.head } + else if (typeof start == "object") { pos = clipPos(this.doc, start) } + else { pos = start ? range.from() : range.to() } + return cursorCoords(this, pos, mode || "page") + }, + + charCoords: function(pos, mode) { + return charCoords(this, clipPos(this.doc, pos), mode || "page") + }, + + coordsChar: function(coords, mode) { + coords = fromCoordSystem(this, coords, mode || "page") + return coordsChar(this, coords.left, coords.top) + }, + + lineAtHeight: function(height, mode) { + height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top + return lineAtHeight(this.doc, height + this.display.viewOffset) + }, + heightAtLine: function(line, mode, includeWidgets) { + var end = false, lineObj + if (typeof line == "number") { + var last = this.doc.first + this.doc.size - 1 + if (line < this.doc.first) { line = this.doc.first } + else if (line > last) { line = last; end = true } + lineObj = getLine(this.doc, line) + } else { + lineObj = line + } + return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top + + (end ? this.doc.height - heightAtLine(lineObj) : 0) + }, + + defaultTextHeight: function() { return textHeight(this.display) }, + defaultCharWidth: function() { return charWidth(this.display) }, + + getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, + + addWidget: function(pos, node, scroll, vert, horiz) { + var display = this.display + pos = cursorCoords(this, clipPos(this.doc, pos)) + var top = pos.bottom, left = pos.left + node.style.position = "absolute" + node.setAttribute("cm-ignore-events", "true") + this.display.input.setUneditable(node) + display.sizer.appendChild(node) + if (vert == "over") { + top = pos.top + } else if (vert == "above" || vert == "near") { + var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), + hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth) + // Default to positioning above (if specified and possible); otherwise default to positioning below + if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) + { top = pos.top - node.offsetHeight } + else if (pos.bottom + node.offsetHeight <= vspace) + { top = pos.bottom } + if (left + node.offsetWidth > hspace) + { left = hspace - node.offsetWidth } + } + node.style.top = top + "px" + node.style.left = node.style.right = "" + if (horiz == "right") { + left = display.sizer.clientWidth - node.offsetWidth + node.style.right = "0px" + } else { + if (horiz == "left") { left = 0 } + else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2 } + node.style.left = left + "px" + } + if (scroll) + { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}) } + }, + + triggerOnKeyDown: methodOp(onKeyDown), + triggerOnKeyPress: methodOp(onKeyPress), + triggerOnKeyUp: onKeyUp, + triggerOnMouseDown: methodOp(onMouseDown), + + execCommand: function(cmd) { + if (commands.hasOwnProperty(cmd)) + { return commands[cmd].call(null, this) } + }, + + triggerElectric: methodOp(function(text) { triggerElectric(this, text) }), + + findPosH: function(from, amount, unit, visually) { + var this$1 = this; + + var dir = 1 + if (amount < 0) { dir = -1; amount = -amount } + var cur = clipPos(this.doc, from) + for (var i = 0; i < amount; ++i) { + cur = findPosH(this$1.doc, cur, dir, unit, visually) + if (cur.hitSide) { break } + } + return cur + }, + + moveH: methodOp(function(dir, unit) { + var this$1 = this; + + this.extendSelectionsBy(function (range) { + if (this$1.display.shift || this$1.doc.extend || range.empty()) + { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) } + else + { return dir < 0 ? range.from() : range.to() } + }, sel_move) + }), + + deleteH: methodOp(function(dir, unit) { + var sel = this.doc.sel, doc = this.doc + if (sel.somethingSelected()) + { doc.replaceSelection("", null, "+delete") } + else + { deleteNearSelection(this, function (range) { + var other = findPosH(doc, range.head, dir, unit, false) + return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other} + }) } + }), + + findPosV: function(from, amount, unit, goalColumn) { + var this$1 = this; + + var dir = 1, x = goalColumn + if (amount < 0) { dir = -1; amount = -amount } + var cur = clipPos(this.doc, from) + for (var i = 0; i < amount; ++i) { + var coords = cursorCoords(this$1, cur, "div") + if (x == null) { x = coords.left } + else { coords.left = x } + cur = findPosV(this$1, coords, dir, unit) + if (cur.hitSide) { break } + } + return cur + }, + + moveV: methodOp(function(dir, unit) { + var this$1 = this; + + var doc = this.doc, goals = [] + var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected() + doc.extendSelectionsBy(function (range) { + if (collapse) + { return dir < 0 ? range.from() : range.to() } + var headPos = cursorCoords(this$1, range.head, "div") + if (range.goalColumn != null) { headPos.left = range.goalColumn } + goals.push(headPos.left) + var pos = findPosV(this$1, headPos, dir, unit) + if (unit == "page" && range == doc.sel.primary()) + { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top) } + return pos + }, sel_move) + if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++) + { doc.sel.ranges[i].goalColumn = goals[i] } } + }), + + // Find the word at the given position (as returned by coordsChar). + findWordAt: function(pos) { + var doc = this.doc, line = getLine(doc, pos.line).text + var start = pos.ch, end = pos.ch + if (line) { + var helper = this.getHelper(pos, "wordChars") + if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end } + var startChar = line.charAt(start) + var check = isWordChar(startChar, helper) + ? function (ch) { return isWordChar(ch, helper); } + : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); } + : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); } + while (start > 0 && check(line.charAt(start - 1))) { --start } + while (end < line.length && check(line.charAt(end))) { ++end } + } + return new Range(Pos(pos.line, start), Pos(pos.line, end)) + }, + + toggleOverwrite: function(value) { + if (value != null && value == this.state.overwrite) { return } + if (this.state.overwrite = !this.state.overwrite) + { addClass(this.display.cursorDiv, "CodeMirror-overwrite") } + else + { rmClass(this.display.cursorDiv, "CodeMirror-overwrite") } + + signal(this, "overwriteToggle", this, this.state.overwrite) + }, + hasFocus: function() { return this.display.input.getField() == activeElt() }, + isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, + + scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y) }), + getScrollInfo: function() { + var scroller = this.display.scroller + return {left: scroller.scrollLeft, top: scroller.scrollTop, + height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, + width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, + clientHeight: displayHeight(this), clientWidth: displayWidth(this)} + }, + + scrollIntoView: methodOp(function(range, margin) { + if (range == null) { + range = {from: this.doc.sel.primary().head, to: null} + if (margin == null) { margin = this.options.cursorScrollMargin } + } else if (typeof range == "number") { + range = {from: Pos(range, 0), to: null} + } else if (range.from == null) { + range = {from: range, to: null} + } + if (!range.to) { range.to = range.from } + range.margin = margin || 0 + + if (range.from.line != null) { + scrollToRange(this, range) + } else { + scrollToCoordsRange(this, range.from, range.to, range.margin) + } + }), + + setSize: methodOp(function(width, height) { + var this$1 = this; + + var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; } + if (width != null) { this.display.wrapper.style.width = interpret(width) } + if (height != null) { this.display.wrapper.style.height = interpret(height) } + if (this.options.lineWrapping) { clearLineMeasurementCache(this) } + var lineNo = this.display.viewFrom + this.doc.iter(lineNo, this.display.viewTo, function (line) { + if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) + { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } } + ++lineNo + }) + this.curOp.forceUpdate = true + signal(this, "refresh", this) + }), + + operation: function(f){return runInOp(this, f)}, + startOperation: function(){return startOperation(this)}, + endOperation: function(){return endOperation(this)}, + + refresh: methodOp(function() { + var oldHeight = this.display.cachedTextHeight + regChange(this) + this.curOp.forceUpdate = true + clearCaches(this) + scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop) + updateGutterSpace(this) + if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) + { estimateLineHeights(this) } + signal(this, "refresh", this) + }), + + swapDoc: methodOp(function(doc) { + var old = this.doc + old.cm = null + attachDoc(this, doc) + clearCaches(this) + this.display.input.reset() + scrollToCoords(this, doc.scrollLeft, doc.scrollTop) + this.curOp.forceScroll = true + signalLater(this, "swapDoc", this, old) + return old + }), + + phrase: function(phraseText) { + var phrases = this.options.phrases + return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText + }, + + getInputField: function(){return this.display.input.getField()}, + getWrapperElement: function(){return this.display.wrapper}, + getScrollerElement: function(){return this.display.scroller}, + getGutterElement: function(){return this.display.gutters} + } + eventMixin(CodeMirror) + + CodeMirror.registerHelper = function(type, name, value) { + if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []} } + helpers[type][name] = value + } + CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { + CodeMirror.registerHelper(type, name, value) + helpers[type]._global.push({pred: predicate, val: value}) + } +} + +// Used for horizontal relative motion. Dir is -1 or 1 (left or +// right), unit can be "char", "column" (like char, but doesn't +// cross line boundaries), "word" (across next word), or "group" (to +// the start of next group of word or non-word-non-whitespace +// chars). The visually param controls whether, in right-to-left +// text, direction 1 means to move towards the next index in the +// string, or towards the character to the right of the current +// position. The resulting position will have a hitSide=true +// property if it reached the end of the document. +function findPosH(doc, pos, dir, unit, visually) { + var oldPos = pos + var origDir = dir + var lineObj = getLine(doc, pos.line) + function findNextLine() { + var l = pos.line + dir + if (l < doc.first || l >= doc.first + doc.size) { return false } + pos = new Pos(l, pos.ch, pos.sticky) + return lineObj = getLine(doc, l) + } + function moveOnce(boundToLine) { + var next + if (visually) { + next = moveVisually(doc.cm, lineObj, pos, dir) + } else { + next = moveLogically(lineObj, pos, dir) + } + if (next == null) { + if (!boundToLine && findNextLine()) + { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir) } + else + { return false } + } else { + pos = next + } + return true + } + + if (unit == "char") { + moveOnce() + } else if (unit == "column") { + moveOnce(true) + } else if (unit == "word" || unit == "group") { + var sawType = null, group = unit == "group" + var helper = doc.cm && doc.cm.getHelper(pos, "wordChars") + for (var first = true;; first = false) { + if (dir < 0 && !moveOnce(!first)) { break } + var cur = lineObj.text.charAt(pos.ch) || "\n" + var type = isWordChar(cur, helper) ? "w" + : group && cur == "\n" ? "n" + : !group || /\s/.test(cur) ? null + : "p" + if (group && !first && !type) { type = "s" } + if (sawType && sawType != type) { + if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after"} + break + } + + if (type) { sawType = type } + if (dir > 0 && !moveOnce(!first)) { break } + } + } + var result = skipAtomic(doc, pos, oldPos, origDir, true) + if (equalCursorPos(oldPos, result)) { result.hitSide = true } + return result +} + +// For relative vertical movement. Dir may be -1 or 1. Unit can be +// "page" or "line". The resulting position will have a hitSide=true +// property if it reached the end of the document. +function findPosV(cm, pos, dir, unit) { + var doc = cm.doc, x = pos.left, y + if (unit == "page") { + var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight) + var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3) + y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount + + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3 + } + var target + for (;;) { + target = coordsChar(cm, x, y) + if (!target.outside) { break } + if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break } + y += dir * 5 + } + return target +} + +// CONTENTEDITABLE INPUT STYLE + +var ContentEditableInput = function(cm) { + this.cm = cm + this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null + this.polling = new Delayed() + this.composing = null + this.gracePeriod = false + this.readDOMTimeout = null +}; + +ContentEditableInput.prototype.init = function (display) { + var this$1 = this; + + var input = this, cm = input.cm + var div = input.div = display.lineDiv + disableBrowserMagic(div, cm.options.spellcheck) + + on(div, "paste", function (e) { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } + // IE doesn't fire input events, so we schedule a read for the pasted content in this way + if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20) } + }) + + on(div, "compositionstart", function (e) { + this$1.composing = {data: e.data, done: false} + }) + on(div, "compositionupdate", function (e) { + if (!this$1.composing) { this$1.composing = {data: e.data, done: false} } + }) + on(div, "compositionend", function (e) { + if (this$1.composing) { + if (e.data != this$1.composing.data) { this$1.readFromDOMSoon() } + this$1.composing.done = true + } + }) + + on(div, "touchstart", function () { return input.forceCompositionEnd(); }) + + on(div, "input", function () { + if (!this$1.composing) { this$1.readFromDOMSoon() } + }) + + function onCopyCut(e) { + if (signalDOMEvent(cm, e)) { return } + if (cm.somethingSelected()) { + setLastCopied({lineWise: false, text: cm.getSelections()}) + if (e.type == "cut") { cm.replaceSelection("", null, "cut") } + } else if (!cm.options.lineWiseCopyCut) { + return + } else { + var ranges = copyableRanges(cm) + setLastCopied({lineWise: true, text: ranges.text}) + if (e.type == "cut") { + cm.operation(function () { + cm.setSelections(ranges.ranges, 0, sel_dontScroll) + cm.replaceSelection("", null, "cut") + }) + } + } + if (e.clipboardData) { + e.clipboardData.clearData() + var content = lastCopied.text.join("\n") + // iOS exposes the clipboard API, but seems to discard content inserted into it + e.clipboardData.setData("Text", content) + if (e.clipboardData.getData("Text") == content) { + e.preventDefault() + return + } + } + // Old-fashioned briefly-focus-a-textarea hack + var kludge = hiddenTextarea(), te = kludge.firstChild + cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild) + te.value = lastCopied.text.join("\n") + var hadFocus = document.activeElement + selectInput(te) + setTimeout(function () { + cm.display.lineSpace.removeChild(kludge) + hadFocus.focus() + if (hadFocus == div) { input.showPrimarySelection() } + }, 50) + } + on(div, "copy", onCopyCut) + on(div, "cut", onCopyCut) +}; + +ContentEditableInput.prototype.prepareSelection = function () { + var result = prepareSelection(this.cm, false) + result.focus = this.cm.state.focused + return result +}; + +ContentEditableInput.prototype.showSelection = function (info, takeFocus) { + if (!info || !this.cm.display.view.length) { return } + if (info.focus || takeFocus) { this.showPrimarySelection() } + this.showMultipleSelections(info) +}; + +ContentEditableInput.prototype.getSelection = function () { + return this.cm.display.wrapper.ownerDocument.getSelection() +}; + +ContentEditableInput.prototype.showPrimarySelection = function () { + var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary() + var from = prim.from(), to = prim.to() + + if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { + sel.removeAllRanges() + return + } + + var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset) + var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset) + if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && + cmp(minPos(curAnchor, curFocus), from) == 0 && + cmp(maxPos(curAnchor, curFocus), to) == 0) + { return } + + var view = cm.display.view + var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) || + {node: view[0].measure.map[2], offset: 0} + var end = to.line < cm.display.viewTo && posToDOM(cm, to) + if (!end) { + var measure = view[view.length - 1].measure + var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map + end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]} + } + + if (!start || !end) { + sel.removeAllRanges() + return + } + + var old = sel.rangeCount && sel.getRangeAt(0), rng + try { rng = range(start.node, start.offset, end.offset, end.node) } + catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible + if (rng) { + if (!gecko && cm.state.focused) { + sel.collapse(start.node, start.offset) + if (!rng.collapsed) { + sel.removeAllRanges() + sel.addRange(rng) + } + } else { + sel.removeAllRanges() + sel.addRange(rng) + } + if (old && sel.anchorNode == null) { sel.addRange(old) } + else if (gecko) { this.startGracePeriod() } + } + this.rememberSelection() +}; + +ContentEditableInput.prototype.startGracePeriod = function () { + var this$1 = this; + + clearTimeout(this.gracePeriod) + this.gracePeriod = setTimeout(function () { + this$1.gracePeriod = false + if (this$1.selectionChanged()) + { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }) } + }, 20) +}; + +ContentEditableInput.prototype.showMultipleSelections = function (info) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors) + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection) +}; + +ContentEditableInput.prototype.rememberSelection = function () { + var sel = this.getSelection() + this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset + this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset +}; + +ContentEditableInput.prototype.selectionInEditor = function () { + var sel = this.getSelection() + if (!sel.rangeCount) { return false } + var node = sel.getRangeAt(0).commonAncestorContainer + return contains(this.div, node) +}; + +ContentEditableInput.prototype.focus = function () { + if (this.cm.options.readOnly != "nocursor") { + if (!this.selectionInEditor()) + { this.showSelection(this.prepareSelection(), true) } + this.div.focus() + } +}; +ContentEditableInput.prototype.blur = function () { this.div.blur() }; +ContentEditableInput.prototype.getField = function () { return this.div }; + +ContentEditableInput.prototype.supportsTouch = function () { return true }; + +ContentEditableInput.prototype.receivedFocus = function () { + var input = this + if (this.selectionInEditor()) + { this.pollSelection() } + else + { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }) } + + function poll() { + if (input.cm.state.focused) { + input.pollSelection() + input.polling.set(input.cm.options.pollInterval, poll) + } + } + this.polling.set(this.cm.options.pollInterval, poll) +}; + +ContentEditableInput.prototype.selectionChanged = function () { + var sel = this.getSelection() + return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || + sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset +}; + +ContentEditableInput.prototype.pollSelection = function () { + if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return } + var sel = this.getSelection(), cm = this.cm + // On Android Chrome (version 56, at least), backspacing into an + // uneditable block element will put the cursor in that element, + // and then, because it's not editable, hide the virtual keyboard. + // Because Android doesn't allow us to actually detect backspace + // presses in a sane way, this code checks for when that happens + // and simulates a backspace press in this case. + if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) { + this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs}) + this.blur() + this.focus() + return + } + if (this.composing) { return } + this.rememberSelection() + var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset) + var head = domToPos(cm, sel.focusNode, sel.focusOffset) + if (anchor && head) { runInOp(cm, function () { + setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll) + if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true } + }) } +}; + +ContentEditableInput.prototype.pollContent = function () { + if (this.readDOMTimeout != null) { + clearTimeout(this.readDOMTimeout) + this.readDOMTimeout = null + } + + var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary() + var from = sel.from(), to = sel.to() + if (from.ch == 0 && from.line > cm.firstLine()) + { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length) } + if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) + { to = Pos(to.line + 1, 0) } + if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false } + + var fromIndex, fromLine, fromNode + if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { + fromLine = lineNo(display.view[0].line) + fromNode = display.view[0].node + } else { + fromLine = lineNo(display.view[fromIndex].line) + fromNode = display.view[fromIndex - 1].node.nextSibling + } + var toIndex = findViewIndex(cm, to.line) + var toLine, toNode + if (toIndex == display.view.length - 1) { + toLine = display.viewTo - 1 + toNode = display.lineDiv.lastChild + } else { + toLine = lineNo(display.view[toIndex + 1].line) - 1 + toNode = display.view[toIndex + 1].node.previousSibling + } + + if (!fromNode) { return false } + var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)) + var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)) + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine-- } + else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++ } + else { break } + } + + var cutFront = 0, cutEnd = 0 + var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length) + while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) + { ++cutFront } + var newBot = lst(newText), oldBot = lst(oldText) + var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), + oldBot.length - (oldText.length == 1 ? cutFront : 0)) + while (cutEnd < maxCutEnd && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) + { ++cutEnd } + // Try to move start of change to start of selection if ambiguous + if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { + while (cutFront && cutFront > from.ch && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { + cutFront-- + cutEnd++ + } + } + + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "") + newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "") + + var chFrom = Pos(fromLine, cutFront) + var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0) + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input") + return true + } +}; + +ContentEditableInput.prototype.ensurePolled = function () { + this.forceCompositionEnd() +}; +ContentEditableInput.prototype.reset = function () { + this.forceCompositionEnd() +}; +ContentEditableInput.prototype.forceCompositionEnd = function () { + if (!this.composing) { return } + clearTimeout(this.readDOMTimeout) + this.composing = null + this.updateFromDOM() + this.div.blur() + this.div.focus() +}; +ContentEditableInput.prototype.readFromDOMSoon = function () { + var this$1 = this; + + if (this.readDOMTimeout != null) { return } + this.readDOMTimeout = setTimeout(function () { + this$1.readDOMTimeout = null + if (this$1.composing) { + if (this$1.composing.done) { this$1.composing = null } + else { return } + } + this$1.updateFromDOM() + }, 80) +}; + +ContentEditableInput.prototype.updateFromDOM = function () { + var this$1 = this; + + if (this.cm.isReadOnly() || !this.pollContent()) + { runInOp(this.cm, function () { return regChange(this$1.cm); }) } +}; + +ContentEditableInput.prototype.setUneditable = function (node) { + node.contentEditable = "false" +}; + +ContentEditableInput.prototype.onKeyPress = function (e) { + if (e.charCode == 0 || this.composing) { return } + e.preventDefault() + if (!this.cm.isReadOnly()) + { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0) } +}; + +ContentEditableInput.prototype.readOnlyChanged = function (val) { + this.div.contentEditable = String(val != "nocursor") +}; + +ContentEditableInput.prototype.onContextMenu = function () {}; +ContentEditableInput.prototype.resetPosition = function () {}; + +ContentEditableInput.prototype.needsContentAttribute = true + +function posToDOM(cm, pos) { + var view = findViewForLine(cm, pos.line) + if (!view || view.hidden) { return null } + var line = getLine(cm.doc, pos.line) + var info = mapFromLineView(view, line, pos.line) + + var order = getOrder(line, cm.doc.direction), side = "left" + if (order) { + var partPos = getBidiPartAt(order, pos.ch) + side = partPos % 2 ? "right" : "left" + } + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side) + result.offset = result.collapse == "right" ? result.end : result.start + return result +} + +function isInGutter(node) { + for (var scan = node; scan; scan = scan.parentNode) + { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } } + return false +} + +function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos } + +function domTextBetween(cm, from, to, fromLine, toLine) { + var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false + function recognizeMarker(id) { return function (marker) { return marker.id == id; } } + function close() { + if (closing) { + text += lineSep + if (extraLinebreak) { text += lineSep } + closing = extraLinebreak = false + } + } + function addText(str) { + if (str) { + close() + text += str + } + } + function walk(node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text") + if (cmText) { + addText(cmText) + return + } + var markerID = node.getAttribute("cm-marker"), range + if (markerID) { + var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)) + if (found.length && (range = found[0].find(0))) + { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)) } + return + } + if (node.getAttribute("contenteditable") == "false") { return } + var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName) + if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return } + + if (isBlock) { close() } + for (var i = 0; i < node.childNodes.length; i++) + { walk(node.childNodes[i]) } + + if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true } + if (isBlock) { closing = true } + } else if (node.nodeType == 3) { + addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " ")) + } + } + for (;;) { + walk(from) + if (from == to) { break } + from = from.nextSibling + extraLinebreak = false + } + return text +} + +function domToPos(cm, node, offset) { + var lineNode + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset] + if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) } + node = null; offset = 0 + } else { + for (lineNode = node;; lineNode = lineNode.parentNode) { + if (!lineNode || lineNode == cm.display.lineDiv) { return null } + if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break } + } + } + for (var i = 0; i < cm.display.view.length; i++) { + var lineView = cm.display.view[i] + if (lineView.node == lineNode) + { return locateNodeInLineView(lineView, node, offset) } + } +} + +function locateNodeInLineView(lineView, node, offset) { + var wrapper = lineView.text.firstChild, bad = false + if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) } + if (node == wrapper) { + bad = true + node = wrapper.childNodes[offset] + offset = 0 + if (!node) { + var line = lineView.rest ? lst(lineView.rest) : lineView.line + return badPos(Pos(lineNo(line), line.text.length), bad) + } + } + + var textNode = node.nodeType == 3 ? node : null, topNode = node + if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { + textNode = node.firstChild + if (offset) { offset = textNode.nodeValue.length } + } + while (topNode.parentNode != wrapper) { topNode = topNode.parentNode } + var measure = lineView.measure, maps = measure.maps + + function find(textNode, topNode, offset) { + for (var i = -1; i < (maps ? maps.length : 0); i++) { + var map = i < 0 ? measure.map : maps[i] + for (var j = 0; j < map.length; j += 3) { + var curNode = map[j + 2] + if (curNode == textNode || curNode == topNode) { + var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]) + var ch = map[j] + offset + if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)] } + return Pos(line, ch) + } + } + } + } + var found = find(textNode, topNode, offset) + if (found) { return badPos(found, bad) } + + // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems + for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { + found = find(after, after.firstChild, 0) + if (found) + { return badPos(Pos(found.line, found.ch - dist), bad) } + else + { dist += after.textContent.length } + } + for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { + found = find(before, before.firstChild, -1) + if (found) + { return badPos(Pos(found.line, found.ch + dist$1), bad) } + else + { dist$1 += before.textContent.length } + } +} + +// TEXTAREA INPUT STYLE + +var TextareaInput = function(cm) { + this.cm = cm + // See input.poll and input.reset + this.prevInput = "" + + // Flag that indicates whether we expect input to appear real soon + // now (after some event like 'keypress' or 'input') and are + // polling intensively. + this.pollingFast = false + // Self-resetting timeout for the poller + this.polling = new Delayed() + // Used to work around IE issue with selection being forgotten when focus moves away from textarea + this.hasSelection = false + this.composing = null +}; + +TextareaInput.prototype.init = function (display) { + var this$1 = this; + + var input = this, cm = this.cm + this.createField(display) + var te = this.textarea + + display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild) + + // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) + if (ios) { te.style.width = "0px" } + + on(te, "input", function () { + if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null } + input.poll() + }) + + on(te, "paste", function (e) { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } + + cm.state.pasteIncoming = true + input.fastPoll() + }) + + function prepareCopyCut(e) { + if (signalDOMEvent(cm, e)) { return } + if (cm.somethingSelected()) { + setLastCopied({lineWise: false, text: cm.getSelections()}) + } else if (!cm.options.lineWiseCopyCut) { + return + } else { + var ranges = copyableRanges(cm) + setLastCopied({lineWise: true, text: ranges.text}) + if (e.type == "cut") { + cm.setSelections(ranges.ranges, null, sel_dontScroll) + } else { + input.prevInput = "" + te.value = ranges.text.join("\n") + selectInput(te) + } + } + if (e.type == "cut") { cm.state.cutIncoming = true } + } + on(te, "cut", prepareCopyCut) + on(te, "copy", prepareCopyCut) + + on(display.scroller, "paste", function (e) { + if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return } + cm.state.pasteIncoming = true + input.focus() + }) + + // Prevent normal selection in the editor (we handle our own) + on(display.lineSpace, "selectstart", function (e) { + if (!eventInWidget(display, e)) { e_preventDefault(e) } + }) + + on(te, "compositionstart", function () { + var start = cm.getCursor("from") + if (input.composing) { input.composing.range.clear() } + input.composing = { + start: start, + range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) + } + }) + on(te, "compositionend", function () { + if (input.composing) { + input.poll() + input.composing.range.clear() + input.composing = null + } + }) +}; + +TextareaInput.prototype.createField = function (_display) { + // Wraps and hides input textarea + this.wrapper = hiddenTextarea() + // The semihidden textarea that is focused when the editor is + // focused, and receives input. + this.textarea = this.wrapper.firstChild +}; + +TextareaInput.prototype.prepareSelection = function () { + // Redraw the selection and/or cursor + var cm = this.cm, display = cm.display, doc = cm.doc + var result = prepareSelection(cm) + + // Move the hidden textarea near the cursor to prevent scrolling artifacts + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, doc.sel.primary().head, "div") + var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect() + result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, + headPos.top + lineOff.top - wrapOff.top)) + result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, + headPos.left + lineOff.left - wrapOff.left)) + } + + return result +}; + +TextareaInput.prototype.showSelection = function (drawn) { + var cm = this.cm, display = cm.display + removeChildrenAndAdd(display.cursorDiv, drawn.cursors) + removeChildrenAndAdd(display.selectionDiv, drawn.selection) + if (drawn.teTop != null) { + this.wrapper.style.top = drawn.teTop + "px" + this.wrapper.style.left = drawn.teLeft + "px" + } +}; + +// Reset the input to correspond to the selection (or to be empty, +// when not typing and nothing is selected) +TextareaInput.prototype.reset = function (typing) { + if (this.contextMenuPending || this.composing) { return } + var cm = this.cm + if (cm.somethingSelected()) { + this.prevInput = "" + var content = cm.getSelection() + this.textarea.value = content + if (cm.state.focused) { selectInput(this.textarea) } + if (ie && ie_version >= 9) { this.hasSelection = content } + } else if (!typing) { + this.prevInput = this.textarea.value = "" + if (ie && ie_version >= 9) { this.hasSelection = null } + } +}; + +TextareaInput.prototype.getField = function () { return this.textarea }; + +TextareaInput.prototype.supportsTouch = function () { return false }; + +TextareaInput.prototype.focus = function () { + if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { + try { this.textarea.focus() } + catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM + } +}; + +TextareaInput.prototype.blur = function () { this.textarea.blur() }; + +TextareaInput.prototype.resetPosition = function () { + this.wrapper.style.top = this.wrapper.style.left = 0 +}; + +TextareaInput.prototype.receivedFocus = function () { this.slowPoll() }; + +// Poll for input changes, using the normal rate of polling. This +// runs as long as the editor is focused. +TextareaInput.prototype.slowPoll = function () { + var this$1 = this; + + if (this.pollingFast) { return } + this.polling.set(this.cm.options.pollInterval, function () { + this$1.poll() + if (this$1.cm.state.focused) { this$1.slowPoll() } + }) +}; + +// When an event has just come in that is likely to add or change +// something in the input textarea, we poll faster, to ensure that +// the change appears on the screen quickly. +TextareaInput.prototype.fastPoll = function () { + var missed = false, input = this + input.pollingFast = true + function p() { + var changed = input.poll() + if (!changed && !missed) {missed = true; input.polling.set(60, p)} + else {input.pollingFast = false; input.slowPoll()} + } + input.polling.set(20, p) +}; + +// Read input from the textarea, and update the document to match. +// When something is selected, it is present in the textarea, and +// selected (unless it is huge, in which case a placeholder is +// used). When nothing is selected, the cursor sits after previously +// seen text (can be empty), which is stored in prevInput (we must +// not reset the textarea when typing, because that breaks IME). +TextareaInput.prototype.poll = function () { + var this$1 = this; + + var cm = this.cm, input = this.textarea, prevInput = this.prevInput + // Since this is called a *lot*, try to bail out as cheaply as + // possible when it is clear that nothing happened. hasSelection + // will be the case when there is a lot of text in the textarea, + // in which case reading its value would be expensive. + if (this.contextMenuPending || !cm.state.focused || + (hasSelection(input) && !prevInput && !this.composing) || + cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) + { return false } + + var text = input.value + // If nothing changed, bail. + if (text == prevInput && !cm.somethingSelected()) { return false } + // Work around nonsensical selection resetting in IE9/10, and + // inexplicable appearance of private area unicode characters on + // some key combos in Mac (#2689). + if (ie && ie_version >= 9 && this.hasSelection === text || + mac && /[\uf700-\uf7ff]/.test(text)) { + cm.display.input.reset() + return false + } + + if (cm.doc.sel == cm.display.selForContextMenu) { + var first = text.charCodeAt(0) + if (first == 0x200b && !prevInput) { prevInput = "\u200b" } + if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") } + } + // Find the part of the input that is actually new + var same = 0, l = Math.min(prevInput.length, text.length) + while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same } + + runInOp(cm, function () { + applyTextInput(cm, text.slice(same), prevInput.length - same, + null, this$1.composing ? "*compose" : null) + + // Don't leave long text in the textarea, since it makes further polling slow + if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = "" } + else { this$1.prevInput = text } + + if (this$1.composing) { + this$1.composing.range.clear() + this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), + {className: "CodeMirror-composing"}) + } + }) + return true +}; + +TextareaInput.prototype.ensurePolled = function () { + if (this.pollingFast && this.poll()) { this.pollingFast = false } +}; + +TextareaInput.prototype.onKeyPress = function () { + if (ie && ie_version >= 9) { this.hasSelection = null } + this.fastPoll() +}; + +TextareaInput.prototype.onContextMenu = function (e) { + var input = this, cm = input.cm, display = cm.display, te = input.textarea + var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop + if (!pos || presto) { return } // Opera is difficult. + + // Reset the current text selection only if the click is done outside of the selection + // and 'resetSelectionOnContextMenu' option is true. + var reset = cm.options.resetSelectionOnContextMenu + if (reset && cm.doc.sel.contains(pos) == -1) + { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll) } + + var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText + input.wrapper.style.cssText = "position: absolute" + var wrapperBox = input.wrapper.getBoundingClientRect() + te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);" + var oldScrollY + if (webkit) { oldScrollY = window.scrollY } // Work around Chrome issue (#2712) + display.input.focus() + if (webkit) { window.scrollTo(null, oldScrollY) } + display.input.reset() + // Adds "Select all" to context menu in FF + if (!cm.somethingSelected()) { te.value = input.prevInput = " " } + input.contextMenuPending = true + display.selForContextMenu = cm.doc.sel + clearTimeout(display.detectingSelectAll) + + // Select-all will be greyed out if there's nothing to select, so + // this adds a zero-width space so that we can later check whether + // it got selected. + function prepareSelectAllHack() { + if (te.selectionStart != null) { + var selected = cm.somethingSelected() + var extval = "\u200b" + (selected ? te.value : "") + te.value = "\u21da" // Used to catch context-menu undo + te.value = extval + input.prevInput = selected ? "" : "\u200b" + te.selectionStart = 1; te.selectionEnd = extval.length + // Re-set this, in case some other handler touched the + // selection in the meantime. + display.selForContextMenu = cm.doc.sel + } + } + function rehide() { + input.contextMenuPending = false + input.wrapper.style.cssText = oldWrapperCSS + te.style.cssText = oldCSS + if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos) } + + // Try to detect the user choosing select-all + if (te.selectionStart != null) { + if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack() } + var i = 0, poll = function () { + if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && + te.selectionEnd > 0 && input.prevInput == "\u200b") { + operation(cm, selectAll)(cm) + } else if (i++ < 10) { + display.detectingSelectAll = setTimeout(poll, 500) + } else { + display.selForContextMenu = null + display.input.reset() + } + } + display.detectingSelectAll = setTimeout(poll, 200) + } + } + + if (ie && ie_version >= 9) { prepareSelectAllHack() } + if (captureRightClick) { + e_stop(e) + var mouseup = function () { + off(window, "mouseup", mouseup) + setTimeout(rehide, 20) + } + on(window, "mouseup", mouseup) + } else { + setTimeout(rehide, 50) + } +}; + +TextareaInput.prototype.readOnlyChanged = function (val) { + if (!val) { this.reset() } + this.textarea.disabled = val == "nocursor" +}; + +TextareaInput.prototype.setUneditable = function () {}; + +TextareaInput.prototype.needsContentAttribute = false + +function fromTextArea(textarea, options) { + options = options ? copyObj(options) : {} + options.value = textarea.value + if (!options.tabindex && textarea.tabIndex) + { options.tabindex = textarea.tabIndex } + if (!options.placeholder && textarea.placeholder) + { options.placeholder = textarea.placeholder } + // Set autofocus to true if this textarea is focused, or if it has + // autofocus and no other element is focused. + if (options.autofocus == null) { + var hasFocus = activeElt() + options.autofocus = hasFocus == textarea || + textarea.getAttribute("autofocus") != null && hasFocus == document.body + } + + function save() {textarea.value = cm.getValue()} + + var realSubmit + if (textarea.form) { + on(textarea.form, "submit", save) + // Deplorable hack to make the submit method do the right thing. + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form + realSubmit = form.submit + try { + var wrappedSubmit = form.submit = function () { + save() + form.submit = realSubmit + form.submit() + form.submit = wrappedSubmit + } + } catch(e) {} + } + } + + options.finishInit = function (cm) { + cm.save = save + cm.getTextArea = function () { return textarea; } + cm.toTextArea = function () { + cm.toTextArea = isNaN // Prevent this from being ran twice + save() + textarea.parentNode.removeChild(cm.getWrapperElement()) + textarea.style.display = "" + if (textarea.form) { + off(textarea.form, "submit", save) + if (typeof textarea.form.submit == "function") + { textarea.form.submit = realSubmit } + } + } + } + + textarea.style.display = "none" + var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); }, + options) + return cm +} + +function addLegacyProps(CodeMirror) { + CodeMirror.off = off + CodeMirror.on = on + CodeMirror.wheelEventPixels = wheelEventPixels + CodeMirror.Doc = Doc + CodeMirror.splitLines = splitLinesAuto + CodeMirror.countColumn = countColumn + CodeMirror.findColumn = findColumn + CodeMirror.isWordChar = isWordCharBasic + CodeMirror.Pass = Pass + CodeMirror.signal = signal + CodeMirror.Line = Line + CodeMirror.changeEnd = changeEnd + CodeMirror.scrollbarModel = scrollbarModel + CodeMirror.Pos = Pos + CodeMirror.cmpPos = cmp + CodeMirror.modes = modes + CodeMirror.mimeModes = mimeModes + CodeMirror.resolveMode = resolveMode + CodeMirror.getMode = getMode + CodeMirror.modeExtensions = modeExtensions + CodeMirror.extendMode = extendMode + CodeMirror.copyState = copyState + CodeMirror.startState = startState + CodeMirror.innerMode = innerMode + CodeMirror.commands = commands + CodeMirror.keyMap = keyMap + CodeMirror.keyName = keyName + CodeMirror.isModifierKey = isModifierKey + CodeMirror.lookupKey = lookupKey + CodeMirror.normalizeKeyMap = normalizeKeyMap + CodeMirror.StringStream = StringStream + CodeMirror.SharedTextMarker = SharedTextMarker + CodeMirror.TextMarker = TextMarker + CodeMirror.LineWidget = LineWidget + CodeMirror.e_preventDefault = e_preventDefault + CodeMirror.e_stopPropagation = e_stopPropagation + CodeMirror.e_stop = e_stop + CodeMirror.addClass = addClass + CodeMirror.contains = contains + CodeMirror.rmClass = rmClass + CodeMirror.keyNames = keyNames +} + +// EDITOR CONSTRUCTOR + +defineOptions(CodeMirror) + +addEditorMethods(CodeMirror) + +// Set up methods on CodeMirror's prototype to redirect to the editor's document. +var dontDelegate = "iter insert remove copy getEditor constructor".split(" ") +for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) + { CodeMirror.prototype[prop] = (function(method) { + return function() {return method.apply(this.doc, arguments)} + })(Doc.prototype[prop]) } } + +eventMixin(Doc) + +// INPUT HANDLING + +CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput} + +// MODE DEFINITION AND QUERYING + +// Extra arguments are stored as the mode's dependencies, which is +// used by (legacy) mechanisms like loadmode.js to automatically +// load a mode. (Preferred mechanism is the require/define calls.) +CodeMirror.defineMode = function(name/*, mode, …*/) { + if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name } + defineMode.apply(this, arguments) +} + +CodeMirror.defineMIME = defineMIME + +// Minimal default mode. +CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }) +CodeMirror.defineMIME("text/plain", "null") + +// EXTENSIONS + +CodeMirror.defineExtension = function (name, func) { + CodeMirror.prototype[name] = func +} +CodeMirror.defineDocExtension = function (name, func) { + Doc.prototype[name] = func +} + +CodeMirror.fromTextArea = fromTextArea + +addLegacyProps(CodeMirror) + +CodeMirror.version = "5.40.2" + +return CodeMirror; + +}))); \ No newline at end of file diff --git a/js/codemirror/5.40.2/css.js b/js/codemirror/5.40.2/css.js new file mode 100644 index 0000000..8b57229 --- /dev/null +++ b/js/codemirror/5.40.2/css.js @@ -0,0 +1,832 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("css", function(config, parserConfig) { + var inline = parserConfig.inline + if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css"); + + var indentUnit = config.indentUnit, + tokenHooks = parserConfig.tokenHooks, + documentTypes = parserConfig.documentTypes || {}, + mediaTypes = parserConfig.mediaTypes || {}, + mediaFeatures = parserConfig.mediaFeatures || {}, + mediaValueKeywords = parserConfig.mediaValueKeywords || {}, + propertyKeywords = parserConfig.propertyKeywords || {}, + nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {}, + fontProperties = parserConfig.fontProperties || {}, + counterDescriptors = parserConfig.counterDescriptors || {}, + colorKeywords = parserConfig.colorKeywords || {}, + valueKeywords = parserConfig.valueKeywords || {}, + allowNested = parserConfig.allowNested, + lineComment = parserConfig.lineComment, + supportsAtComponent = parserConfig.supportsAtComponent === true; + + var type, override; + function ret(style, tp) { type = tp; return style; } + + // Tokenizers + + function tokenBase(stream, state) { + var ch = stream.next(); + if (tokenHooks[ch]) { + var result = tokenHooks[ch](stream, state); + if (result !== false) return result; + } + if (ch == "@") { + stream.eatWhile(/[\w\\\-]/); + return ret("def", stream.current()); + } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) { + return ret(null, "compare"); + } else if (ch == "\"" || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "#") { + stream.eatWhile(/[\w\\\-]/); + return ret("atom", "hash"); + } else if (ch == "!") { + stream.match(/^\s*\w*/); + return ret("keyword", "important"); + } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (ch === "-") { + if (/[\d.]/.test(stream.peek())) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (stream.match(/^-[\w\\\-]+/)) { + stream.eatWhile(/[\w\\\-]/); + if (stream.match(/^\s*:/, false)) + return ret("variable-2", "variable-definition"); + return ret("variable-2", "variable"); + } else if (stream.match(/^\w+-/)) { + return ret("meta", "meta"); + } + } else if (/[,+>*\/]/.test(ch)) { + return ret(null, "select-op"); + } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) { + return ret("qualifier", "qualifier"); + } else if (/[:;{}\[\]\(\)]/.test(ch)) { + return ret(null, ch); + } else if (((ch == "u" || ch == "U") && stream.match(/rl(-prefix)?\(/i)) || + ((ch == "d" || ch == "D") && stream.match("omain(", true, true)) || + ((ch == "r" || ch == "R") && stream.match("egexp(", true, true))) { + stream.backUp(1); + state.tokenize = tokenParenthesized; + return ret("property", "word"); + } else if (/[\w\\\-]/.test(ch)) { + stream.eatWhile(/[\w\\\-]/); + return ret("property", "word"); + } else { + return ret(null, null); + } + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) { + if (quote == ")") stream.backUp(1); + break; + } + escaped = !escaped && ch == "\\"; + } + if (ch == quote || !escaped && quote != ")") state.tokenize = null; + return ret("string", "string"); + }; + } + + function tokenParenthesized(stream, state) { + stream.next(); // Must be '(' + if (!stream.match(/\s*[\"\')]/, false)) + state.tokenize = tokenString(")"); + else + state.tokenize = null; + return ret(null, "("); + } + + // Context management + + function Context(type, indent, prev) { + this.type = type; + this.indent = indent; + this.prev = prev; + } + + function pushContext(state, stream, type, indent) { + state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context); + return type; + } + + function popContext(state) { + if (state.context.prev) + state.context = state.context.prev; + return state.context.type; + } + + function pass(type, stream, state) { + return states[state.context.type](type, stream, state); + } + function popAndPass(type, stream, state, n) { + for (var i = n || 1; i > 0; i--) + state.context = state.context.prev; + return pass(type, stream, state); + } + + // Parser + + function wordAsValue(stream) { + var word = stream.current().toLowerCase(); + if (valueKeywords.hasOwnProperty(word)) + override = "atom"; + else if (colorKeywords.hasOwnProperty(word)) + override = "keyword"; + else + override = "variable"; + } + + var states = {}; + + states.top = function(type, stream, state) { + if (type == "{") { + return pushContext(state, stream, "block"); + } else if (type == "}" && state.context.prev) { + return popContext(state); + } else if (supportsAtComponent && /@component/i.test(type)) { + return pushContext(state, stream, "atComponentBlock"); + } else if (/^@(-moz-)?document$/i.test(type)) { + return pushContext(state, stream, "documentTypes"); + } else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) { + return pushContext(state, stream, "atBlock"); + } else if (/^@(font-face|counter-style)/i.test(type)) { + state.stateArg = type; + return "restricted_atBlock_before"; + } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) { + return "keyframes"; + } else if (type && type.charAt(0) == "@") { + return pushContext(state, stream, "at"); + } else if (type == "hash") { + override = "builtin"; + } else if (type == "word") { + override = "tag"; + } else if (type == "variable-definition") { + return "maybeprop"; + } else if (type == "interpolation") { + return pushContext(state, stream, "interpolation"); + } else if (type == ":") { + return "pseudo"; + } else if (allowNested && type == "(") { + return pushContext(state, stream, "parens"); + } + return state.context.type; + }; + + states.block = function(type, stream, state) { + if (type == "word") { + var word = stream.current().toLowerCase(); + if (propertyKeywords.hasOwnProperty(word)) { + override = "property"; + return "maybeprop"; + } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) { + override = "string-2"; + return "maybeprop"; + } else if (allowNested) { + override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag"; + return "block"; + } else { + override += " error"; + return "maybeprop"; + } + } else if (type == "meta") { + return "block"; + } else if (!allowNested && (type == "hash" || type == "qualifier")) { + override = "error"; + return "block"; + } else { + return states.top(type, stream, state); + } + }; + + states.maybeprop = function(type, stream, state) { + if (type == ":") return pushContext(state, stream, "prop"); + return pass(type, stream, state); + }; + + states.prop = function(type, stream, state) { + if (type == ";") return popContext(state); + if (type == "{" && allowNested) return pushContext(state, stream, "propBlock"); + if (type == "}" || type == "{") return popAndPass(type, stream, state); + if (type == "(") return pushContext(state, stream, "parens"); + + if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) { + override += " error"; + } else if (type == "word") { + wordAsValue(stream); + } else if (type == "interpolation") { + return pushContext(state, stream, "interpolation"); + } + return "prop"; + }; + + states.propBlock = function(type, _stream, state) { + if (type == "}") return popContext(state); + if (type == "word") { override = "property"; return "maybeprop"; } + return state.context.type; + }; + + states.parens = function(type, stream, state) { + if (type == "{" || type == "}") return popAndPass(type, stream, state); + if (type == ")") return popContext(state); + if (type == "(") return pushContext(state, stream, "parens"); + if (type == "interpolation") return pushContext(state, stream, "interpolation"); + if (type == "word") wordAsValue(stream); + return "parens"; + }; + + states.pseudo = function(type, stream, state) { + if (type == "meta") return "pseudo"; + + if (type == "word") { + override = "variable-3"; + return state.context.type; + } + return pass(type, stream, state); + }; + + states.documentTypes = function(type, stream, state) { + if (type == "word" && documentTypes.hasOwnProperty(stream.current())) { + override = "tag"; + return state.context.type; + } else { + return states.atBlock(type, stream, state); + } + }; + + states.atBlock = function(type, stream, state) { + if (type == "(") return pushContext(state, stream, "atBlock_parens"); + if (type == "}" || type == ";") return popAndPass(type, stream, state); + if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top"); + + if (type == "interpolation") return pushContext(state, stream, "interpolation"); + + if (type == "word") { + var word = stream.current().toLowerCase(); + if (word == "only" || word == "not" || word == "and" || word == "or") + override = "keyword"; + else if (mediaTypes.hasOwnProperty(word)) + override = "attribute"; + else if (mediaFeatures.hasOwnProperty(word)) + override = "property"; + else if (mediaValueKeywords.hasOwnProperty(word)) + override = "keyword"; + else if (propertyKeywords.hasOwnProperty(word)) + override = "property"; + else if (nonStandardPropertyKeywords.hasOwnProperty(word)) + override = "string-2"; + else if (valueKeywords.hasOwnProperty(word)) + override = "atom"; + else if (colorKeywords.hasOwnProperty(word)) + override = "keyword"; + else + override = "error"; + } + return state.context.type; + }; + + states.atComponentBlock = function(type, stream, state) { + if (type == "}") + return popAndPass(type, stream, state); + if (type == "{") + return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false); + if (type == "word") + override = "error"; + return state.context.type; + }; + + states.atBlock_parens = function(type, stream, state) { + if (type == ")") return popContext(state); + if (type == "{" || type == "}") return popAndPass(type, stream, state, 2); + return states.atBlock(type, stream, state); + }; + + states.restricted_atBlock_before = function(type, stream, state) { + if (type == "{") + return pushContext(state, stream, "restricted_atBlock"); + if (type == "word" && state.stateArg == "@counter-style") { + override = "variable"; + return "restricted_atBlock_before"; + } + return pass(type, stream, state); + }; + + states.restricted_atBlock = function(type, stream, state) { + if (type == "}") { + state.stateArg = null; + return popContext(state); + } + if (type == "word") { + if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) || + (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase()))) + override = "error"; + else + override = "property"; + return "maybeprop"; + } + return "restricted_atBlock"; + }; + + states.keyframes = function(type, stream, state) { + if (type == "word") { override = "variable"; return "keyframes"; } + if (type == "{") return pushContext(state, stream, "top"); + return pass(type, stream, state); + }; + + states.at = function(type, stream, state) { + if (type == ";") return popContext(state); + if (type == "{" || type == "}") return popAndPass(type, stream, state); + if (type == "word") override = "tag"; + else if (type == "hash") override = "builtin"; + return "at"; + }; + + states.interpolation = function(type, stream, state) { + if (type == "}") return popContext(state); + if (type == "{" || type == ";") return popAndPass(type, stream, state); + if (type == "word") override = "variable"; + else if (type != "variable" && type != "(" && type != ")") override = "error"; + return "interpolation"; + }; + + return { + startState: function(base) { + return {tokenize: null, + state: inline ? "block" : "top", + stateArg: null, + context: new Context(inline ? "block" : "top", base || 0, null)}; + }, + + token: function(stream, state) { + if (!state.tokenize && stream.eatSpace()) return null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style && typeof style == "object") { + type = style[1]; + style = style[0]; + } + override = style; + if (type != "comment") + state.state = states[state.state](type, stream, state); + return override; + }, + + indent: function(state, textAfter) { + var cx = state.context, ch = textAfter && textAfter.charAt(0); + var indent = cx.indent; + if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev; + if (cx.prev) { + if (ch == "}" && (cx.type == "block" || cx.type == "top" || + cx.type == "interpolation" || cx.type == "restricted_atBlock")) { + // Resume indentation from parent context. + cx = cx.prev; + indent = cx.indent; + } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") || + ch == "{" && (cx.type == "at" || cx.type == "atBlock")) { + // Dedent relative to current context. + indent = Math.max(0, cx.indent - indentUnit); + } + } + return indent; + }, + + electricChars: "}", + blockCommentStart: "/*", + blockCommentEnd: "*/", + blockCommentContinue: " * ", + lineComment: lineComment, + fold: "brace" + }; +}); + + function keySet(array) { + var keys = {}; + for (var i = 0; i < array.length; ++i) { + keys[array[i].toLowerCase()] = true; + } + return keys; + } + + var documentTypes_ = [ + "domain", "regexp", "url", "url-prefix" + ], documentTypes = keySet(documentTypes_); + + var mediaTypes_ = [ + "all", "aural", "braille", "handheld", "print", "projection", "screen", + "tty", "tv", "embossed" + ], mediaTypes = keySet(mediaTypes_); + + var mediaFeatures_ = [ + "width", "min-width", "max-width", "height", "min-height", "max-height", + "device-width", "min-device-width", "max-device-width", "device-height", + "min-device-height", "max-device-height", "aspect-ratio", + "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio", + "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color", + "max-color", "color-index", "min-color-index", "max-color-index", + "monochrome", "min-monochrome", "max-monochrome", "resolution", + "min-resolution", "max-resolution", "scan", "grid", "orientation", + "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio", + "pointer", "any-pointer", "hover", "any-hover" + ], mediaFeatures = keySet(mediaFeatures_); + + var mediaValueKeywords_ = [ + "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover", + "interlace", "progressive" + ], mediaValueKeywords = keySet(mediaValueKeywords_); + + var propertyKeywords_ = [ + "align-content", "align-items", "align-self", "alignment-adjust", + "alignment-baseline", "anchor-point", "animation", "animation-delay", + "animation-direction", "animation-duration", "animation-fill-mode", + "animation-iteration-count", "animation-name", "animation-play-state", + "animation-timing-function", "appearance", "azimuth", "backface-visibility", + "background", "background-attachment", "background-blend-mode", "background-clip", + "background-color", "background-image", "background-origin", "background-position", + "background-repeat", "background-size", "baseline-shift", "binding", + "bleed", "bookmark-label", "bookmark-level", "bookmark-state", + "bookmark-target", "border", "border-bottom", "border-bottom-color", + "border-bottom-left-radius", "border-bottom-right-radius", + "border-bottom-style", "border-bottom-width", "border-collapse", + "border-color", "border-image", "border-image-outset", + "border-image-repeat", "border-image-slice", "border-image-source", + "border-image-width", "border-left", "border-left-color", + "border-left-style", "border-left-width", "border-radius", "border-right", + "border-right-color", "border-right-style", "border-right-width", + "border-spacing", "border-style", "border-top", "border-top-color", + "border-top-left-radius", "border-top-right-radius", "border-top-style", + "border-top-width", "border-width", "bottom", "box-decoration-break", + "box-shadow", "box-sizing", "break-after", "break-before", "break-inside", + "caption-side", "caret-color", "clear", "clip", "color", "color-profile", "column-count", + "column-fill", "column-gap", "column-rule", "column-rule-color", + "column-rule-style", "column-rule-width", "column-span", "column-width", + "columns", "content", "counter-increment", "counter-reset", "crop", "cue", + "cue-after", "cue-before", "cursor", "direction", "display", + "dominant-baseline", "drop-initial-after-adjust", + "drop-initial-after-align", "drop-initial-before-adjust", + "drop-initial-before-align", "drop-initial-size", "drop-initial-value", + "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis", + "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap", + "float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings", + "font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust", + "font-stretch", "font-style", "font-synthesis", "font-variant", + "font-variant-alternates", "font-variant-caps", "font-variant-east-asian", + "font-variant-ligatures", "font-variant-numeric", "font-variant-position", + "font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow", + "grid-auto-rows", "grid-column", "grid-column-end", "grid-column-gap", + "grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap", + "grid-row-start", "grid-template", "grid-template-areas", "grid-template-columns", + "grid-template-rows", "hanging-punctuation", "height", "hyphens", + "icon", "image-orientation", "image-rendering", "image-resolution", + "inline-box-align", "justify-content", "justify-items", "justify-self", "left", "letter-spacing", + "line-break", "line-height", "line-stacking", "line-stacking-ruby", + "line-stacking-shift", "line-stacking-strategy", "list-style", + "list-style-image", "list-style-position", "list-style-type", "margin", + "margin-bottom", "margin-left", "margin-right", "margin-top", + "marks", "marquee-direction", "marquee-loop", + "marquee-play-count", "marquee-speed", "marquee-style", "max-height", + "max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index", + "nav-left", "nav-right", "nav-up", "object-fit", "object-position", + "opacity", "order", "orphans", "outline", + "outline-color", "outline-offset", "outline-style", "outline-width", + "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y", + "padding", "padding-bottom", "padding-left", "padding-right", "padding-top", + "page", "page-break-after", "page-break-before", "page-break-inside", + "page-policy", "pause", "pause-after", "pause-before", "perspective", + "perspective-origin", "pitch", "pitch-range", "place-content", "place-items", "place-self", "play-during", "position", + "presentation-level", "punctuation-trim", "quotes", "region-break-after", + "region-break-before", "region-break-inside", "region-fragment", + "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness", + "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang", + "ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin", + "shape-outside", "size", "speak", "speak-as", "speak-header", + "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set", + "tab-size", "table-layout", "target", "target-name", "target-new", + "target-position", "text-align", "text-align-last", "text-decoration", + "text-decoration-color", "text-decoration-line", "text-decoration-skip", + "text-decoration-style", "text-emphasis", "text-emphasis-color", + "text-emphasis-position", "text-emphasis-style", "text-height", + "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow", + "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position", + "text-wrap", "top", "transform", "transform-origin", "transform-style", + "transition", "transition-delay", "transition-duration", + "transition-property", "transition-timing-function", "unicode-bidi", + "user-select", "vertical-align", "visibility", "voice-balance", "voice-duration", + "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress", + "voice-volume", "volume", "white-space", "widows", "width", "will-change", "word-break", + "word-spacing", "word-wrap", "z-index", + // SVG-specific + "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color", + "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events", + "color-interpolation", "color-interpolation-filters", + "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering", + "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke", + "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", + "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering", + "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal", + "glyph-orientation-vertical", "text-anchor", "writing-mode" + ], propertyKeywords = keySet(propertyKeywords_); + + var nonStandardPropertyKeywords_ = [ + "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color", + "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color", + "scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside", + "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", + "searchfield-results-decoration", "zoom" + ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_); + + var fontProperties_ = [ + "font-family", "src", "unicode-range", "font-variant", "font-feature-settings", + "font-stretch", "font-weight", "font-style" + ], fontProperties = keySet(fontProperties_); + + var counterDescriptors_ = [ + "additive-symbols", "fallback", "negative", "pad", "prefix", "range", + "speak-as", "suffix", "symbols", "system" + ], counterDescriptors = keySet(counterDescriptors_); + + var colorKeywords_ = [ + "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", + "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", + "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", + "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", + "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", + "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", + "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", + "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", + "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", + "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew", + "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", + "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", + "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink", + "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", + "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", + "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", + "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", + "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", + "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", + "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", + "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", + "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown", + "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", + "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", + "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", + "whitesmoke", "yellow", "yellowgreen" + ], colorKeywords = keySet(colorKeywords_); + + var valueKeywords_ = [ + "above", "absolute", "activeborder", "additive", "activecaption", "afar", + "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate", + "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", + "arabic-indic", "armenian", "asterisks", "attr", "auto", "auto-flow", "avoid", "avoid-column", "avoid-page", + "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary", + "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box", + "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel", + "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian", + "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", + "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch", + "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", + "col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse", + "compact", "condensed", "contain", "content", "contents", + "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop", + "cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal", + "decimal-leading-zero", "default", "default-button", "dense", "destination-atop", + "destination-in", "destination-out", "destination-over", "devanagari", "difference", + "disc", "discard", "disclosure-closed", "disclosure-open", "document", + "dot-dash", "dot-dot-dash", + "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", + "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", + "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er", + "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", + "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et", + "ethiopic-halehame-gez", "ethiopic-halehame-om-et", + "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et", + "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig", + "ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed", + "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes", + "forwards", "from", "geometricPrecision", "georgian", "graytext", "grid", "groove", + "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew", + "help", "hidden", "hide", "higher", "highlight", "highlighttext", + "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "icon", "ignore", + "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", + "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", + "inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert", + "italic", "japanese-formal", "japanese-informal", "justify", "kannada", + "katakana", "katakana-iroha", "keep-all", "khmer", + "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal", + "landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten", + "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem", + "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", + "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian", + "lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "match", "matrix", "matrix3d", + "media-controls-background", "media-current-time-display", + "media-fullscreen-button", "media-mute-button", "media-play-button", + "media-return-to-realtime-button", "media-rewind-button", + "media-seek-back-button", "media-seek-forward-button", "media-slider", + "media-sliderthumb", "media-time-remaining-display", "media-volume-slider", + "media-volume-slider-container", "media-volume-sliderthumb", "medium", + "menu", "menulist", "menulist-button", "menulist-text", + "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic", + "mix", "mongolian", "monospace", "move", "multiple", "multiply", "myanmar", "n-resize", + "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", + "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", + "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "opacity", "open-quote", + "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", + "outside", "outside-shape", "overlay", "overline", "padding", "padding-box", + "painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter", + "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", + "progress", "push-button", "radial-gradient", "radio", "read-only", + "read-write", "read-write-plaintext-only", "rectangle", "region", + "relative", "repeat", "repeating-linear-gradient", + "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse", + "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY", + "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running", + "s-resize", "sans-serif", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen", + "scroll", "scrollbar", "scroll-position", "se-resize", "searchfield", + "searchfield-cancel-button", "searchfield-decoration", + "searchfield-results-button", "searchfield-results-decoration", "self-start", "self-end", + "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama", + "simp-chinese-formal", "simp-chinese-informal", "single", + "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal", + "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", + "small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali", + "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "space-evenly", "spell-out", "square", + "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub", + "subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "system-ui", "table", + "table-caption", "table-cell", "table-column", "table-column-group", + "table-footer-group", "table-header-group", "table-row", "table-row-group", + "tamil", + "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai", + "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight", + "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er", + "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top", + "trad-chinese-formal", "trad-chinese-informal", "transform", + "translate", "translate3d", "translateX", "translateY", "translateZ", + "transparent", "ultra-condensed", "ultra-expanded", "underline", "unset", "up", + "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", + "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", + "var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted", + "visibleStroke", "visual", "w-resize", "wait", "wave", "wider", + "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor", + "xx-large", "xx-small" + ], valueKeywords = keySet(valueKeywords_); + + var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_) + .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_) + .concat(valueKeywords_); + CodeMirror.registerHelper("hintWords", "css", allWords); + + function tokenCComment(stream, state) { + var maybeEnd = false, ch; + while ((ch = stream.next()) != null) { + if (maybeEnd && ch == "/") { + state.tokenize = null; + break; + } + maybeEnd = (ch == "*"); + } + return ["comment", "comment"]; + } + + CodeMirror.defineMIME("text/css", { + documentTypes: documentTypes, + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + fontProperties: fontProperties, + counterDescriptors: counterDescriptors, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + tokenHooks: { + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + }, + name: "css" + }); + + CodeMirror.defineMIME("text/x-scss", { + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + fontProperties: fontProperties, + allowNested: true, + lineComment: "//", + tokenHooks: { + "/": function(stream, state) { + if (stream.eat("/")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } else if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else { + return ["operator", "operator"]; + } + }, + ":": function(stream) { + if (stream.match(/\s*\{/, false)) + return [null, null] + return false; + }, + "$": function(stream) { + stream.match(/^[\w-]+/); + if (stream.match(/^\s*:/, false)) + return ["variable-2", "variable-definition"]; + return ["variable-2", "variable"]; + }, + "#": function(stream) { + if (!stream.eat("{")) return false; + return [null, "interpolation"]; + } + }, + name: "css", + helperType: "scss" + }); + + CodeMirror.defineMIME("text/x-less", { + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + fontProperties: fontProperties, + allowNested: true, + lineComment: "//", + tokenHooks: { + "/": function(stream, state) { + if (stream.eat("/")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } else if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else { + return ["operator", "operator"]; + } + }, + "@": function(stream) { + if (stream.eat("{")) return [null, "interpolation"]; + if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i, false)) return false; + stream.eatWhile(/[\w\\\-]/); + if (stream.match(/^\s*:/, false)) + return ["variable-2", "variable-definition"]; + return ["variable-2", "variable"]; + }, + "&": function() { + return ["atom", "atom"]; + } + }, + name: "css", + helperType: "less" + }); + + CodeMirror.defineMIME("text/x-gss", { + documentTypes: documentTypes, + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + fontProperties: fontProperties, + counterDescriptors: counterDescriptors, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + supportsAtComponent: true, + tokenHooks: { + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + }, + name: "css", + helperType: "gss" + }); + +}); diff --git a/js/codemirror/5.40.2/htmlmixed.js b/js/codemirror/5.40.2/htmlmixed.js new file mode 100644 index 0000000..c992538 --- /dev/null +++ b/js/codemirror/5.40.2/htmlmixed.js @@ -0,0 +1,152 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("../xml/xml"), require("../javascript/javascript"), require("../css/css")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript", "../css/css"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var defaultTags = { + script: [ + ["lang", /(javascript|babel)/i, "javascript"], + ["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i, "javascript"], + ["type", /./, "text/plain"], + [null, null, "javascript"] + ], + style: [ + ["lang", /^css$/i, "css"], + ["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"], + ["type", /./, "text/plain"], + [null, null, "css"] + ] + }; + + function maybeBackup(stream, pat, style) { + var cur = stream.current(), close = cur.search(pat); + if (close > -1) { + stream.backUp(cur.length - close); + } else if (cur.match(/<\/?$/)) { + stream.backUp(cur.length); + if (!stream.match(pat, false)) stream.match(cur); + } + return style; + } + + var attrRegexpCache = {}; + function getAttrRegexp(attr) { + var regexp = attrRegexpCache[attr]; + if (regexp) return regexp; + return attrRegexpCache[attr] = new RegExp("\\s+" + attr + "\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*"); + } + + function getAttrValue(text, attr) { + var match = text.match(getAttrRegexp(attr)) + return match ? /^\s*(.*?)\s*$/.exec(match[2])[1] : "" + } + + function getTagRegexp(tagName, anchored) { + return new RegExp((anchored ? "^" : "") + "<\/\s*" + tagName + "\s*>", "i"); + } + + function addTags(from, to) { + for (var tag in from) { + var dest = to[tag] || (to[tag] = []); + var source = from[tag]; + for (var i = source.length - 1; i >= 0; i--) + dest.unshift(source[i]) + } + } + + function findMatchingMode(tagInfo, tagText) { + for (var i = 0; i < tagInfo.length; i++) { + var spec = tagInfo[i]; + if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2]; + } + } + + CodeMirror.defineMode("htmlmixed", function (config, parserConfig) { + var htmlMode = CodeMirror.getMode(config, { + name: "xml", + htmlMode: true, + multilineTagIndentFactor: parserConfig.multilineTagIndentFactor, + multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag + }); + + var tags = {}; + var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes; + addTags(defaultTags, tags); + if (configTags) addTags(configTags, tags); + if (configScript) for (var i = configScript.length - 1; i >= 0; i--) + tags.script.unshift(["type", configScript[i].matches, configScript[i].mode]) + + function html(stream, state) { + var style = htmlMode.token(stream, state.htmlState), tag = /\btag\b/.test(style), tagName + if (tag && !/[<>\s\/]/.test(stream.current()) && + (tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) && + tags.hasOwnProperty(tagName)) { + state.inTag = tagName + " " + } else if (state.inTag && tag && />$/.test(stream.current())) { + var inTag = /^([\S]+) (.*)/.exec(state.inTag) + state.inTag = null + var modeSpec = stream.current() == ">" && findMatchingMode(tags[inTag[1]], inTag[2]) + var mode = CodeMirror.getMode(config, modeSpec) + var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false); + state.token = function (stream, state) { + if (stream.match(endTagA, false)) { + state.token = html; + state.localState = state.localMode = null; + return null; + } + return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState)); + }; + state.localMode = mode; + state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, "")); + } else if (state.inTag) { + state.inTag += stream.current() + if (stream.eol()) state.inTag += " " + } + return style; + }; + + return { + startState: function () { + var state = CodeMirror.startState(htmlMode); + return {token: html, inTag: null, localMode: null, localState: null, htmlState: state}; + }, + + copyState: function (state) { + var local; + if (state.localState) { + local = CodeMirror.copyState(state.localMode, state.localState); + } + return {token: state.token, inTag: state.inTag, + localMode: state.localMode, localState: local, + htmlState: CodeMirror.copyState(htmlMode, state.htmlState)}; + }, + + token: function (stream, state) { + return state.token(stream, state); + }, + + indent: function (state, textAfter, line) { + if (!state.localMode || /^\s*<\//.test(textAfter)) + return htmlMode.indent(state.htmlState, textAfter); + else if (state.localMode.indent) + return state.localMode.indent(state.localState, textAfter, line); + else + return CodeMirror.Pass; + }, + + innerMode: function (state) { + return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode}; + } + }; + }, "xml", "javascript", "css"); + + CodeMirror.defineMIME("text/html", "htmlmixed"); +}); diff --git a/js/codemirror/5.40.2/javascript.js b/js/codemirror/5.40.2/javascript.js new file mode 100644 index 0000000..b0a27ce --- /dev/null +++ b/js/codemirror/5.40.2/javascript.js @@ -0,0 +1,899 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("javascript", function(config, parserConfig) { + var indentUnit = config.indentUnit; + var statementIndent = parserConfig.statementIndent; + var jsonldMode = parserConfig.jsonld; + var jsonMode = parserConfig.json || jsonldMode; + var isTS = parserConfig.typescript; + var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; + + // Tokenizer + + var keywords = function(){ + function kw(type) {return {type: type, style: "keyword"};} + var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d"); + var operator = kw("operator"), atom = {type: "atom", style: "atom"}; + + return { + "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, + "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C, + "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"), + "function": kw("function"), "catch": kw("catch"), + "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), + "in": operator, "typeof": operator, "instanceof": operator, + "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, + "this": kw("this"), "class": kw("class"), "super": kw("atom"), + "yield": C, "export": kw("export"), "import": kw("import"), "extends": C, + "await": C + }; + }(); + + var isOperatorChar = /[+\-*&%=<>!?|~^@]/; + var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; + + function readRegexp(stream) { + var escaped = false, next, inSet = false; + while ((next = stream.next()) != null) { + if (!escaped) { + if (next == "/" && !inSet) return; + if (next == "[") inSet = true; + else if (inSet && next == "]") inSet = false; + } + escaped = !escaped && next == "\\"; + } + } + + // Used as scratch variables to communicate multiple values without + // consing up tons of objects. + var type, content; + function ret(tp, style, cont) { + type = tp; content = cont; + return style; + } + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) { + return ret("number", "number"); + } else if (ch == "." && stream.match("..")) { + return ret("spread", "meta"); + } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + return ret(ch); + } else if (ch == "=" && stream.eat(">")) { + return ret("=>", "operator"); + } else if (ch == "0" && stream.match(/^(?:x[\da-f]+|o[0-7]+|b[01]+)n?/i)) { + return ret("number", "number"); + } else if (/\d/.test(ch)) { + stream.match(/^\d*(?:n|(?:\.\d*)?(?:[eE][+\-]?\d+)?)?/); + return ret("number", "number"); + } else if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } else if (stream.eat("/")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } else if (expressionAllowed(stream, state, 1)) { + readRegexp(stream); + stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); + return ret("regexp", "string-2"); + } else { + stream.eat("="); + return ret("operator", "operator", stream.current()); + } + } else if (ch == "`") { + state.tokenize = tokenQuasi; + return tokenQuasi(stream, state); + } else if (ch == "#") { + stream.skipToEnd(); + return ret("error", "error"); + } else if (isOperatorChar.test(ch)) { + if (ch != ">" || !state.lexical || state.lexical.type != ">") { + if (stream.eat("=")) { + if (ch == "!" || ch == "=") stream.eat("=") + } else if (/[<>*+\-]/.test(ch)) { + stream.eat(ch) + if (ch == ">") stream.eat(ch) + } + } + return ret("operator", "operator", stream.current()); + } else if (wordRE.test(ch)) { + stream.eatWhile(wordRE); + var word = stream.current() + if (state.lastType != ".") { + if (keywords.propertyIsEnumerable(word)) { + var kw = keywords[word] + return ret(kw.type, kw.style, word) + } + if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/, false)) + return ret("async", "keyword", word) + } + return ret("variable", "variable", word) + } + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next; + if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ + state.tokenize = tokenBase; + return ret("jsonld-keyword", "meta"); + } + while ((next = stream.next()) != null) { + if (next == quote && !escaped) break; + escaped = !escaped && next == "\\"; + } + if (!escaped) state.tokenize = tokenBase; + return ret("string", "string"); + }; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return ret("comment", "comment"); + } + + function tokenQuasi(stream, state) { + var escaped = false, next; + while ((next = stream.next()) != null) { + if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { + state.tokenize = tokenBase; + break; + } + escaped = !escaped && next == "\\"; + } + return ret("quasi", "string-2", stream.current()); + } + + var brackets = "([{}])"; + // This is a crude lookahead trick to try and notice that we're + // parsing the argument patterns for a fat-arrow function before we + // actually hit the arrow token. It only works if the arrow is on + // the same line as the arguments and there's no strange noise + // (comments) in between. Fallback is to only notice when we hit the + // arrow, and not declare the arguments as locals for the arrow + // body. + function findFatArrow(stream, state) { + if (state.fatArrowAt) state.fatArrowAt = null; + var arrow = stream.string.indexOf("=>", stream.start); + if (arrow < 0) return; + + if (isTS) { // Try to skip TypeScript return type declarations after the arguments + var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)) + if (m) arrow = m.index + } + + var depth = 0, sawSomething = false; + for (var pos = arrow - 1; pos >= 0; --pos) { + var ch = stream.string.charAt(pos); + var bracket = brackets.indexOf(ch); + if (bracket >= 0 && bracket < 3) { + if (!depth) { ++pos; break; } + if (--depth == 0) { if (ch == "(") sawSomething = true; break; } + } else if (bracket >= 3 && bracket < 6) { + ++depth; + } else if (wordRE.test(ch)) { + sawSomething = true; + } else if (/["'\/]/.test(ch)) { + return; + } else if (sawSomething && !depth) { + ++pos; + break; + } + } + if (sawSomething && !depth) state.fatArrowAt = pos; + } + + // Parser + + var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; + + function JSLexical(indented, column, type, align, prev, info) { + this.indented = indented; + this.column = column; + this.type = type; + this.prev = prev; + this.info = info; + if (align != null) this.align = align; + } + + function inScope(state, varname) { + for (var v = state.localVars; v; v = v.next) + if (v.name == varname) return true; + for (var cx = state.context; cx; cx = cx.prev) { + for (var v = cx.vars; v; v = v.next) + if (v.name == varname) return true; + } + } + + function parseJS(state, style, type, content, stream) { + var cc = state.cc; + // Communicate our context to the combinators. + // (Less wasteful than consing up a hundred closures on every call.) + cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; + + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = true; + + while(true) { + var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; + if (combinator(type, content)) { + while(cc.length && cc[cc.length - 1].lex) + cc.pop()(); + if (cx.marked) return cx.marked; + if (type == "variable" && inScope(state, content)) return "variable-2"; + return style; + } + } + } + + // Combinator utils + + var cx = {state: null, column: null, marked: null, cc: null}; + function pass() { + for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); + } + function cont() { + pass.apply(null, arguments); + return true; + } + function inList(name, list) { + for (var v = list; v; v = v.next) if (v.name == name) return true + return false; + } + function register(varname) { + var state = cx.state; + cx.marked = "def"; + if (state.context) { + if (state.lexical.info == "var" && state.context && state.context.block) { + // FIXME function decls are also not block scoped + var newContext = registerVarScoped(varname, state.context) + if (newContext != null) { + state.context = newContext + return + } + } else if (!inList(varname, state.localVars)) { + state.localVars = new Var(varname, state.localVars) + return + } + } + // Fall through means this is global + if (parserConfig.globalVars && !inList(varname, state.globalVars)) + state.globalVars = new Var(varname, state.globalVars) + } + function registerVarScoped(varname, context) { + if (!context) { + return null + } else if (context.block) { + var inner = registerVarScoped(varname, context.prev) + if (!inner) return null + if (inner == context.prev) return context + return new Context(inner, context.vars, true) + } else if (inList(varname, context.vars)) { + return context + } else { + return new Context(context.prev, new Var(varname, context.vars), false) + } + } + + function isModifier(name) { + return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly" + } + + // Combinators + + function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block } + function Var(name, next) { this.name = name; this.next = next } + + var defaultVars = new Var("this", new Var("arguments", null)) + function pushcontext() { + cx.state.context = new Context(cx.state.context, cx.state.localVars, false) + cx.state.localVars = defaultVars + } + function pushblockcontext() { + cx.state.context = new Context(cx.state.context, cx.state.localVars, true) + cx.state.localVars = null + } + function popcontext() { + cx.state.localVars = cx.state.context.vars + cx.state.context = cx.state.context.prev + } + popcontext.lex = true + function pushlex(type, info) { + var result = function() { + var state = cx.state, indent = state.indented; + if (state.lexical.type == "stat") indent = state.lexical.indented; + else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) + indent = outer.indented; + state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); + }; + result.lex = true; + return result; + } + function poplex() { + var state = cx.state; + if (state.lexical.prev) { + if (state.lexical.type == ")") + state.indented = state.lexical.indented; + state.lexical = state.lexical.prev; + } + } + poplex.lex = true; + + function expect(wanted) { + function exp(type) { + if (type == wanted) return cont(); + else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass(); + else return cont(exp); + }; + return exp; + } + + function statement(type, value) { + if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex); + if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); + if (type == "keyword b") return cont(pushlex("form"), statement, poplex); + if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); + if (type == "debugger") return cont(expect(";")); + if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext); + if (type == ";") return cont(); + if (type == "if") { + if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) + cx.state.cc.pop()(); + return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); + } + if (type == "function") return cont(functiondef); + if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); + if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), className, poplex); } + if (type == "variable") { + if (isTS && value == "declare") { + cx.marked = "keyword" + return cont(statement) + } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { + cx.marked = "keyword" + if (value == "enum") return cont(enumdef); + else if (value == "type") return cont(typeexpr, expect("operator"), typeexpr, expect(";")); + else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex) + } else if (isTS && value == "namespace") { + cx.marked = "keyword" + return cont(pushlex("form"), expression, block, poplex) + } else if (isTS && value == "abstract") { + cx.marked = "keyword" + return cont(statement) + } else { + return cont(pushlex("stat"), maybelabel); + } + } + if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext, + block, poplex, poplex, popcontext); + if (type == "case") return cont(expression, expect(":")); + if (type == "default") return cont(expect(":")); + if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext); + if (type == "export") return cont(pushlex("stat"), afterExport, poplex); + if (type == "import") return cont(pushlex("stat"), afterImport, poplex); + if (type == "async") return cont(statement) + if (value == "@") return cont(expression, statement) + return pass(pushlex("stat"), expression, expect(";"), poplex); + } + function maybeCatchBinding(type) { + if (type == "(") return cont(funarg, expect(")")) + } + function expression(type, value) { + return expressionInner(type, value, false); + } + function expressionNoComma(type, value) { + return expressionInner(type, value, true); + } + function parenExpr(type) { + if (type != "(") return pass() + return cont(pushlex(")"), expression, expect(")"), poplex) + } + function expressionInner(type, value, noComma) { + if (cx.state.fatArrowAt == cx.stream.start) { + var body = noComma ? arrowBodyNoComma : arrowBody; + if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext); + else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); + } + + var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; + if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); + if (type == "function") return cont(functiondef, maybeop); + if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); } + if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression); + if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); + if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); + if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); + if (type == "{") return contCommasep(objprop, "}", null, maybeop); + if (type == "quasi") return pass(quasi, maybeop); + if (type == "new") return cont(maybeTarget(noComma)); + if (type == "import") return cont(expression); + return cont(); + } + function maybeexpression(type) { + if (type.match(/[;\}\)\],]/)) return pass(); + return pass(expression); + } + + function maybeoperatorComma(type, value) { + if (type == ",") return cont(expression); + return maybeoperatorNoComma(type, value, false); + } + function maybeoperatorNoComma(type, value, noComma) { + var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; + var expr = noComma == false ? expression : expressionNoComma; + if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); + if (type == "operator") { + if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me); + if (isTS && value == "<" && cx.stream.match(/^([^>]|<.*?>)*>\s*\(/, false)) + return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me); + if (value == "?") return cont(expression, expect(":"), expr); + return cont(expr); + } + if (type == "quasi") { return pass(quasi, me); } + if (type == ";") return; + if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); + if (type == ".") return cont(property, me); + if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); + if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) } + if (type == "regexp") { + cx.state.lastType = cx.marked = "operator" + cx.stream.backUp(cx.stream.pos - cx.stream.start - 1) + return cont(expr) + } + } + function quasi(type, value) { + if (type != "quasi") return pass(); + if (value.slice(value.length - 2) != "${") return cont(quasi); + return cont(expression, continueQuasi); + } + function continueQuasi(type) { + if (type == "}") { + cx.marked = "string-2"; + cx.state.tokenize = tokenQuasi; + return cont(quasi); + } + } + function arrowBody(type) { + findFatArrow(cx.stream, cx.state); + return pass(type == "{" ? statement : expression); + } + function arrowBodyNoComma(type) { + findFatArrow(cx.stream, cx.state); + return pass(type == "{" ? statement : expressionNoComma); + } + function maybeTarget(noComma) { + return function(type) { + if (type == ".") return cont(noComma ? targetNoComma : target); + else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma) + else return pass(noComma ? expressionNoComma : expression); + }; + } + function target(_, value) { + if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); } + } + function targetNoComma(_, value) { + if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); } + } + function maybelabel(type) { + if (type == ":") return cont(poplex, statement); + return pass(maybeoperatorComma, expect(";"), poplex); + } + function property(type) { + if (type == "variable") {cx.marked = "property"; return cont();} + } + function objprop(type, value) { + if (type == "async") { + cx.marked = "property"; + return cont(objprop); + } else if (type == "variable" || cx.style == "keyword") { + cx.marked = "property"; + if (value == "get" || value == "set") return cont(getterSetter); + var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params + if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) + cx.state.fatArrowAt = cx.stream.pos + m[0].length + return cont(afterprop); + } else if (type == "number" || type == "string") { + cx.marked = jsonldMode ? "property" : (cx.style + " property"); + return cont(afterprop); + } else if (type == "jsonld-keyword") { + return cont(afterprop); + } else if (isTS && isModifier(value)) { + cx.marked = "keyword" + return cont(objprop) + } else if (type == "[") { + return cont(expression, maybetype, expect("]"), afterprop); + } else if (type == "spread") { + return cont(expressionNoComma, afterprop); + } else if (value == "*") { + cx.marked = "keyword"; + return cont(objprop); + } else if (type == ":") { + return pass(afterprop) + } + } + function getterSetter(type) { + if (type != "variable") return pass(afterprop); + cx.marked = "property"; + return cont(functiondef); + } + function afterprop(type) { + if (type == ":") return cont(expressionNoComma); + if (type == "(") return pass(functiondef); + } + function commasep(what, end, sep) { + function proceed(type, value) { + if (sep ? sep.indexOf(type) > -1 : type == ",") { + var lex = cx.state.lexical; + if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; + return cont(function(type, value) { + if (type == end || value == end) return pass() + return pass(what) + }, proceed); + } + if (type == end || value == end) return cont(); + return cont(expect(end)); + } + return function(type, value) { + if (type == end || value == end) return cont(); + return pass(what, proceed); + }; + } + function contCommasep(what, end, info) { + for (var i = 3; i < arguments.length; i++) + cx.cc.push(arguments[i]); + return cont(pushlex(end, info), commasep(what, end), poplex); + } + function block(type) { + if (type == "}") return cont(); + return pass(statement, block); + } + function maybetype(type, value) { + if (isTS) { + if (type == ":") return cont(typeexpr); + if (value == "?") return cont(maybetype); + } + } + function mayberettype(type) { + if (isTS && type == ":") { + if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr) + else return cont(typeexpr) + } + } + function isKW(_, value) { + if (value == "is") { + cx.marked = "keyword" + return cont() + } + } + function typeexpr(type, value) { + if (value == "keyof" || value == "typeof") { + cx.marked = "keyword" + return cont(value == "keyof" ? typeexpr : expressionNoComma) + } + if (type == "variable" || value == "void") { + cx.marked = "type" + return cont(afterType) + } + if (type == "string" || type == "number" || type == "atom") return cont(afterType); + if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType) + if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType) + if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType) + if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr) + } + function maybeReturnType(type) { + if (type == "=>") return cont(typeexpr) + } + function typeprop(type, value) { + if (type == "variable" || cx.style == "keyword") { + cx.marked = "property" + return cont(typeprop) + } else if (value == "?") { + return cont(typeprop) + } else if (type == ":") { + return cont(typeexpr) + } else if (type == "[") { + return cont(expression, maybetype, expect("]"), typeprop) + } + } + function typearg(type, value) { + if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg) + if (type == ":") return cont(typeexpr) + return pass(typeexpr) + } + function afterType(type, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) + if (value == "|" || type == "." || value == "&") return cont(typeexpr) + if (type == "[") return cont(expect("]"), afterType) + if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) } + } + function maybeTypeArgs(_, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) + } + function typeparam() { + return pass(typeexpr, maybeTypeDefault) + } + function maybeTypeDefault(_, value) { + if (value == "=") return cont(typeexpr) + } + function vardef(_, value) { + if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)} + return pass(pattern, maybetype, maybeAssign, vardefCont); + } + function pattern(type, value) { + if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) } + if (type == "variable") { register(value); return cont(); } + if (type == "spread") return cont(pattern); + if (type == "[") return contCommasep(eltpattern, "]"); + if (type == "{") return contCommasep(proppattern, "}"); + } + function proppattern(type, value) { + if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { + register(value); + return cont(maybeAssign); + } + if (type == "variable") cx.marked = "property"; + if (type == "spread") return cont(pattern); + if (type == "}") return pass(); + return cont(expect(":"), pattern, maybeAssign); + } + function eltpattern() { + return pass(pattern, maybeAssign) + } + function maybeAssign(_type, value) { + if (value == "=") return cont(expressionNoComma); + } + function vardefCont(type) { + if (type == ",") return cont(vardef); + } + function maybeelse(type, value) { + if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); + } + function forspec(type, value) { + if (value == "await") return cont(forspec); + if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex); + } + function forspec1(type) { + if (type == "var") return cont(vardef, expect(";"), forspec2); + if (type == ";") return cont(forspec2); + if (type == "variable") return cont(formaybeinof); + return pass(expression, expect(";"), forspec2); + } + function formaybeinof(_type, value) { + if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } + return cont(maybeoperatorComma, forspec2); + } + function forspec2(type, value) { + if (type == ";") return cont(forspec3); + if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } + return pass(expression, expect(";"), forspec3); + } + function forspec3(type) { + if (type != ")") cont(expression); + } + function functiondef(type, value) { + if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} + if (type == "variable") {register(value); return cont(functiondef);} + if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext); + if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef) + } + function funarg(type, value) { + if (value == "@") cont(expression, funarg) + if (type == "spread") return cont(funarg); + if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); } + return pass(pattern, maybetype, maybeAssign); + } + function classExpression(type, value) { + // Class expressions may have an optional name. + if (type == "variable") return className(type, value); + return classNameAfter(type, value); + } + function className(type, value) { + if (type == "variable") {register(value); return cont(classNameAfter);} + } + function classNameAfter(type, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter) + if (value == "extends" || value == "implements" || (isTS && type == ",")) { + if (value == "implements") cx.marked = "keyword"; + return cont(isTS ? typeexpr : expression, classNameAfter); + } + if (type == "{") return cont(pushlex("}"), classBody, poplex); + } + function classBody(type, value) { + if (type == "async" || + (type == "variable" && + (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) && + cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) { + cx.marked = "keyword"; + return cont(classBody); + } + if (type == "variable" || cx.style == "keyword") { + cx.marked = "property"; + return cont(isTS ? classfield : functiondef, classBody); + } + if (type == "[") + return cont(expression, maybetype, expect("]"), isTS ? classfield : functiondef, classBody) + if (value == "*") { + cx.marked = "keyword"; + return cont(classBody); + } + if (type == ";") return cont(classBody); + if (type == "}") return cont(); + if (value == "@") return cont(expression, classBody) + } + function classfield(type, value) { + if (value == "?") return cont(classfield) + if (type == ":") return cont(typeexpr, maybeAssign) + if (value == "=") return cont(expressionNoComma) + return pass(functiondef) + } + function afterExport(type, value) { + if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } + if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } + if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); + return pass(statement); + } + function exportField(type, value) { + if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); } + if (type == "variable") return pass(expressionNoComma, exportField); + } + function afterImport(type) { + if (type == "string") return cont(); + if (type == "(") return pass(expression); + return pass(importSpec, maybeMoreImports, maybeFrom); + } + function importSpec(type, value) { + if (type == "{") return contCommasep(importSpec, "}"); + if (type == "variable") register(value); + if (value == "*") cx.marked = "keyword"; + return cont(maybeAs); + } + function maybeMoreImports(type) { + if (type == ",") return cont(importSpec, maybeMoreImports) + } + function maybeAs(_type, value) { + if (value == "as") { cx.marked = "keyword"; return cont(importSpec); } + } + function maybeFrom(_type, value) { + if (value == "from") { cx.marked = "keyword"; return cont(expression); } + } + function arrayLiteral(type) { + if (type == "]") return cont(); + return pass(commasep(expressionNoComma, "]")); + } + function enumdef() { + return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex) + } + function enummember() { + return pass(pattern, maybeAssign); + } + + function isContinuedStatement(state, textAfter) { + return state.lastType == "operator" || state.lastType == "," || + isOperatorChar.test(textAfter.charAt(0)) || + /[,.]/.test(textAfter.charAt(0)); + } + + function expressionAllowed(stream, state, backUp) { + return state.tokenize == tokenBase && + /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || + (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0)))) + } + + // Interface + + return { + startState: function(basecolumn) { + var state = { + tokenize: tokenBase, + lastType: "sof", + cc: [], + lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), + localVars: parserConfig.localVars, + context: parserConfig.localVars && new Context(null, null, false), + indented: basecolumn || 0 + }; + if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") + state.globalVars = parserConfig.globalVars; + return state; + }, + + token: function(stream, state) { + if (stream.sol()) { + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = false; + state.indented = stream.indentation(); + findFatArrow(stream, state); + } + if (state.tokenize != tokenComment && stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (type == "comment") return style; + state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; + return parseJS(state, style, type, content, stream); + }, + + indent: function(state, textAfter) { + if (state.tokenize == tokenComment) return CodeMirror.Pass; + if (state.tokenize != tokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top + // Kludge to prevent 'maybelse' from blocking lexical scope pops + if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { + var c = state.cc[i]; + if (c == poplex) lexical = lexical.prev; + else if (c != maybeelse) break; + } + while ((lexical.type == "stat" || lexical.type == "form") && + (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) && + (top == maybeoperatorComma || top == maybeoperatorNoComma) && + !/^[,\.=+\-*:?[\(]/.test(textAfter)))) + lexical = lexical.prev; + if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") + lexical = lexical.prev; + var type = lexical.type, closing = firstChar == type; + + if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0); + else if (type == "form" && firstChar == "{") return lexical.indented; + else if (type == "form") return lexical.indented + indentUnit; + else if (type == "stat") + return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); + else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) + return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); + else if (lexical.align) return lexical.column + (closing ? 0 : 1); + else return lexical.indented + (closing ? 0 : indentUnit); + }, + + electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, + blockCommentStart: jsonMode ? null : "/*", + blockCommentEnd: jsonMode ? null : "*/", + blockCommentContinue: jsonMode ? null : " * ", + lineComment: jsonMode ? null : "//", + fold: "brace", + closeBrackets: "()[]{}''\"\"``", + + helperType: jsonMode ? "json" : "javascript", + jsonldMode: jsonldMode, + jsonMode: jsonMode, + + expressionAllowed: expressionAllowed, + + skipExpression: function(state) { + var top = state.cc[state.cc.length - 1] + if (top == expression || top == expressionNoComma) state.cc.pop() + } + }; +}); + +CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); + +CodeMirror.defineMIME("text/javascript", "javascript"); +CodeMirror.defineMIME("text/ecmascript", "javascript"); +CodeMirror.defineMIME("application/javascript", "javascript"); +CodeMirror.defineMIME("application/x-javascript", "javascript"); +CodeMirror.defineMIME("application/ecmascript", "javascript"); +CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); +CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); +CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); +CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); +CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); + +}); diff --git a/js/codemirror/5.40.2/material.css b/js/codemirror/5.40.2/material.css new file mode 100644 index 0000000..84962a2 --- /dev/null +++ b/js/codemirror/5.40.2/material.css @@ -0,0 +1,53 @@ +/* + + Name: material + Author: Michael Kaminsky (http://github.com/mkaminsky11) + + Original material color scheme by Mattia Astorino (https://github.com/equinusocio/material-theme) + +*/ + +.cm-s-material.CodeMirror { + background-color: #263238; + color: rgba(233, 237, 237, 1); +} +.cm-s-material .CodeMirror-gutters { + background: #263238; + color: rgb(83,127,126); + border: none; +} +.cm-s-material .CodeMirror-guttermarker, .cm-s-material .CodeMirror-guttermarker-subtle, .cm-s-material .CodeMirror-linenumber { color: rgb(83,127,126); } +.cm-s-material .CodeMirror-cursor { border-left: 1px solid #f8f8f0; } +.cm-s-material div.CodeMirror-selected { background: rgba(255, 255, 255, 0.15); } +.cm-s-material.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.10); } +.cm-s-material .CodeMirror-line::selection, .cm-s-material .CodeMirror-line > span::selection, .cm-s-material .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); } +.cm-s-material .CodeMirror-line::-moz-selection, .cm-s-material .CodeMirror-line > span::-moz-selection, .cm-s-material .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); } + +.cm-s-material .CodeMirror-activeline-background { background: rgba(0, 0, 0, 0); } +.cm-s-material .cm-keyword { color: rgba(199, 146, 234, 1); } +.cm-s-material .cm-operator { color: rgba(233, 237, 237, 1); } +.cm-s-material .cm-variable-2 { color: #80CBC4; } +.cm-s-material .cm-variable-3, .cm-s-material .cm-type { color: #82B1FF; } +.cm-s-material .cm-builtin { color: #DECB6B; } +.cm-s-material .cm-atom { color: #F77669; } +.cm-s-material .cm-number { color: #F77669; } +.cm-s-material .cm-def { color: rgba(233, 237, 237, 1); } +.cm-s-material .cm-string { color: #C3E88D; } +.cm-s-material .cm-string-2 { color: #80CBC4; } +.cm-s-material .cm-comment { color: #546E7A; } +.cm-s-material .cm-variable { color: #82B1FF; } +.cm-s-material .cm-tag { color: #80CBC4; } +.cm-s-material .cm-meta { color: #80CBC4; } +.cm-s-material .cm-attribute { color: #FFCB6B; } +.cm-s-material .cm-property { color: #80CBAE; } +.cm-s-material .cm-qualifier { color: #DECB6B; } +.cm-s-material .cm-variable-3, .cm-s-material .cm-type { color: #DECB6B; } +.cm-s-material .cm-tag { color: rgba(255, 83, 112, 1); } +.cm-s-material .cm-error { + color: rgba(255, 255, 255, 1.0); + background-color: #EC5F67; +} +.cm-s-material .CodeMirror-matchingbracket { + text-decoration: underline; + color: white !important; +} diff --git a/js/codemirror/5.40.2/monokai.css b/js/codemirror/5.40.2/monokai.css new file mode 100644 index 0000000..cd4cd55 --- /dev/null +++ b/js/codemirror/5.40.2/monokai.css @@ -0,0 +1,41 @@ +/* Based on Sublime Text's Monokai theme */ + +.cm-s-monokai.CodeMirror { background: #272822; color: #f8f8f2; } +.cm-s-monokai div.CodeMirror-selected { background: #49483E; } +.cm-s-monokai .CodeMirror-line::selection, .cm-s-monokai .CodeMirror-line > span::selection, .cm-s-monokai .CodeMirror-line > span > span::selection { background: rgba(73, 72, 62, .99); } +.cm-s-monokai .CodeMirror-line::-moz-selection, .cm-s-monokai .CodeMirror-line > span::-moz-selection, .cm-s-monokai .CodeMirror-line > span > span::-moz-selection { background: rgba(73, 72, 62, .99); } +.cm-s-monokai .CodeMirror-gutters { background: #272822; border-right: 0px; } +.cm-s-monokai .CodeMirror-guttermarker { color: white; } +.cm-s-monokai .CodeMirror-guttermarker-subtle { color: #d0d0d0; } +.cm-s-monokai .CodeMirror-linenumber { color: #d0d0d0; } +.cm-s-monokai .CodeMirror-cursor { border-left: 1px solid #f8f8f0; } + +.cm-s-monokai span.cm-comment { color: #75715e; } +.cm-s-monokai span.cm-atom { color: #ae81ff; } +.cm-s-monokai span.cm-number { color: #ae81ff; } + +.cm-s-monokai span.cm-comment.cm-attribute { color: #97b757; } +.cm-s-monokai span.cm-comment.cm-def { color: #bc9262; } +.cm-s-monokai span.cm-comment.cm-tag { color: #bc6283; } +.cm-s-monokai span.cm-comment.cm-type { color: #5998a6; } + +.cm-s-monokai span.cm-property, .cm-s-monokai span.cm-attribute { color: #a6e22e; } +.cm-s-monokai span.cm-keyword { color: #f92672; } +.cm-s-monokai span.cm-builtin { color: #66d9ef; } +.cm-s-monokai span.cm-string { color: #e6db74; } + +.cm-s-monokai span.cm-variable { color: #f8f8f2; } +.cm-s-monokai span.cm-variable-2 { color: #9effff; } +.cm-s-monokai span.cm-variable-3, .cm-s-monokai span.cm-type { color: #66d9ef; } +.cm-s-monokai span.cm-def { color: #fd971f; } +.cm-s-monokai span.cm-bracket { color: #f8f8f2; } +.cm-s-monokai span.cm-tag { color: #f92672; } +.cm-s-monokai span.cm-header { color: #ae81ff; } +.cm-s-monokai span.cm-link { color: #ae81ff; } +.cm-s-monokai span.cm-error { background: #f92672; color: #f8f8f0; } + +.cm-s-monokai .CodeMirror-activeline-background { background: #373831; } +.cm-s-monokai .CodeMirror-matchingbracket { + text-decoration: underline; + color: white !important; +} diff --git a/js/codemirror/5.40.2/python.js b/js/codemirror/5.40.2/python.js new file mode 100644 index 0000000..623c03f --- /dev/null +++ b/js/codemirror/5.40.2/python.js @@ -0,0 +1,409 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + function wordRegexp(words) { + return new RegExp("^((" + words.join(")|(") + "))\\b"); + } + + var wordOperators = wordRegexp(["and", "or", "not", "is"]); + var commonKeywords = ["as", "assert", "break", "class", "continue", + "def", "del", "elif", "else", "except", "finally", + "for", "from", "global", "if", "import", + "lambda", "pass", "raise", "return", + "try", "while", "with", "yield", "in"]; + var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr", + "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod", + "enumerate", "eval", "filter", "float", "format", "frozenset", + "getattr", "globals", "hasattr", "hash", "help", "hex", "id", + "input", "int", "isinstance", "issubclass", "iter", "len", + "list", "locals", "map", "max", "memoryview", "min", "next", + "object", "oct", "open", "ord", "pow", "property", "range", + "repr", "reversed", "round", "set", "setattr", "slice", + "sorted", "staticmethod", "str", "sum", "super", "tuple", + "type", "vars", "zip", "__import__", "NotImplemented", + "Ellipsis", "__debug__"]; + CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins)); + + function top(state) { + return state.scopes[state.scopes.length - 1]; + } + + CodeMirror.defineMode("python", function(conf, parserConf) { + var ERRORCLASS = "error"; + + var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.\\]/; + // (Backwards-compatiblity with old, cumbersome config system) + var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters, + parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@])/] + for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1) + + var hangingIndent = parserConf.hangingIndent || conf.indentUnit; + + var myKeywords = commonKeywords, myBuiltins = commonBuiltins; + if (parserConf.extra_keywords != undefined) + myKeywords = myKeywords.concat(parserConf.extra_keywords); + + if (parserConf.extra_builtins != undefined) + myBuiltins = myBuiltins.concat(parserConf.extra_builtins); + + var py3 = !(parserConf.version && Number(parserConf.version) < 3) + if (py3) { + // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator + var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/; + myKeywords = myKeywords.concat(["nonlocal", "False", "True", "None", "async", "await"]); + myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]); + var stringPrefixes = new RegExp("^(([rbuf]|(br)|(fr))?('{3}|\"{3}|['\"]))", "i"); + } else { + var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/; + myKeywords = myKeywords.concat(["exec", "print"]); + myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile", + "file", "intern", "long", "raw_input", "reduce", "reload", + "unichr", "unicode", "xrange", "False", "True", "None"]); + var stringPrefixes = new RegExp("^(([rubf]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i"); + } + var keywords = wordRegexp(myKeywords); + var builtins = wordRegexp(myBuiltins); + + // tokenizers + function tokenBase(stream, state) { + var sol = stream.sol() && state.lastToken != "\\" + if (sol) state.indent = stream.indentation() + // Handle scope changes + if (sol && top(state).type == "py") { + var scopeOffset = top(state).offset; + if (stream.eatSpace()) { + var lineOffset = stream.indentation(); + if (lineOffset > scopeOffset) + pushPyScope(state); + else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#") + state.errorToken = true; + return null; + } else { + var style = tokenBaseInner(stream, state); + if (scopeOffset > 0 && dedent(stream, state)) + style += " " + ERRORCLASS; + return style; + } + } + return tokenBaseInner(stream, state); + } + + function tokenBaseInner(stream, state) { + if (stream.eatSpace()) return null; + + // Handle Comments + if (stream.match(/^#.*/)) return "comment"; + + // Handle Number Literals + if (stream.match(/^[0-9\.]/, false)) { + var floatLiteral = false; + // Floats + if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; } + if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; } + if (stream.match(/^\.\d+/)) { floatLiteral = true; } + if (floatLiteral) { + // Float literals may be "imaginary" + stream.eat(/J/i); + return "number"; + } + // Integers + var intLiteral = false; + // Hex + if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true; + // Binary + if (stream.match(/^0b[01_]+/i)) intLiteral = true; + // Octal + if (stream.match(/^0o[0-7_]+/i)) intLiteral = true; + // Decimal + if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) { + // Decimal literals may be "imaginary" + stream.eat(/J/i); + // TODO - Can you have imaginary longs? + intLiteral = true; + } + // Zero by itself with no other piece of number. + if (stream.match(/^0(?![\dx])/i)) intLiteral = true; + if (intLiteral) { + // Integer literals may be "long" + stream.eat(/L/i); + return "number"; + } + } + + // Handle Strings + if (stream.match(stringPrefixes)) { + var isFmtString = stream.current().toLowerCase().indexOf('f') !== -1; + if (!isFmtString) { + state.tokenize = tokenStringFactory(stream.current()); + return state.tokenize(stream, state); + } else { + state.tokenize = formatStringFactory(stream.current(), state.tokenize); + return state.tokenize(stream, state); + } + } + + for (var i = 0; i < operators.length; i++) + if (stream.match(operators[i])) return "operator" + + if (stream.match(delimiters)) return "punctuation"; + + if (state.lastToken == "." && stream.match(identifiers)) + return "property"; + + if (stream.match(keywords) || stream.match(wordOperators)) + return "keyword"; + + if (stream.match(builtins)) + return "builtin"; + + if (stream.match(/^(self|cls)\b/)) + return "variable-2"; + + if (stream.match(identifiers)) { + if (state.lastToken == "def" || state.lastToken == "class") + return "def"; + return "variable"; + } + + // Handle non-detected items + stream.next(); + return ERRORCLASS; + } + + function formatStringFactory(delimiter, tokenOuter) { + while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0) + delimiter = delimiter.substr(1); + + var singleline = delimiter.length == 1; + var OUTCLASS = "string"; + + function tokenFString(stream, state) { + // inside f-str Expression + if (stream.match(delimiter)) { + // expression ends pre-maturally, but very common in editing + // Could show error to remind users to close brace here + state.tokenize = tokenString + return OUTCLASS; + } else if (stream.match('{')) { + // starting brace, if not eaten below + return "punctuation"; + } else if (stream.match('}')) { + // return to regular inside string state + state.tokenize = tokenString + return "punctuation"; + } else { + // use tokenBaseInner to parse the expression + return tokenBaseInner(stream, state); + } + } + + function tokenString(stream, state) { + while (!stream.eol()) { + stream.eatWhile(/[^'"\{\}\\]/); + if (stream.eat("\\")) { + stream.next(); + if (singleline && stream.eol()) + return OUTCLASS; + } else if (stream.match(delimiter)) { + state.tokenize = tokenOuter; + return OUTCLASS; + } else if (stream.match('{{')) { + // ignore {{ in f-str + return OUTCLASS; + } else if (stream.match('{', false)) { + // switch to nested mode + state.tokenize = tokenFString + if (stream.current()) { + return OUTCLASS; + } else { + // need to return something, so eat the starting { + stream.next(); + return "punctuation"; + } + } else if (stream.match('}}')) { + return OUTCLASS; + } else if (stream.match('}')) { + // single } in f-string is an error + return ERRORCLASS; + } else { + stream.eat(/['"]/); + } + } + if (singleline) { + if (parserConf.singleLineStringErrors) + return ERRORCLASS; + else + state.tokenize = tokenOuter; + } + return OUTCLASS; + } + tokenString.isString = true; + return tokenString; + } + + function tokenStringFactory(delimiter) { + while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0) + delimiter = delimiter.substr(1); + + var singleline = delimiter.length == 1; + var OUTCLASS = "string"; + + function tokenString(stream, state) { + while (!stream.eol()) { + stream.eatWhile(/[^'"\\]/); + if (stream.eat("\\")) { + stream.next(); + if (singleline && stream.eol()) + return OUTCLASS; + } else if (stream.match(delimiter)) { + state.tokenize = tokenBase; + return OUTCLASS; + } else { + stream.eat(/['"]/); + } + } + if (singleline) { + if (parserConf.singleLineStringErrors) + return ERRORCLASS; + else + state.tokenize = tokenBase; + } + return OUTCLASS; + } + tokenString.isString = true; + return tokenString; + } + + function pushPyScope(state) { + while (top(state).type != "py") state.scopes.pop() + state.scopes.push({offset: top(state).offset + conf.indentUnit, + type: "py", + align: null}) + } + + function pushBracketScope(stream, state, type) { + var align = stream.match(/^([\s\[\{\(]|#.*)*$/, false) ? null : stream.column() + 1 + state.scopes.push({offset: state.indent + hangingIndent, + type: type, + align: align}) + } + + function dedent(stream, state) { + var indented = stream.indentation(); + while (state.scopes.length > 1 && top(state).offset > indented) { + if (top(state).type != "py") return true; + state.scopes.pop(); + } + return top(state).offset != indented; + } + + function tokenLexer(stream, state) { + if (stream.sol()) state.beginningOfLine = true; + + var style = state.tokenize(stream, state); + var current = stream.current(); + + // Handle decorators + if (state.beginningOfLine && current == "@") + return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS; + + if (/\S/.test(current)) state.beginningOfLine = false; + + if ((style == "variable" || style == "builtin") + && state.lastToken == "meta") + style = "meta"; + + // Handle scope changes. + if (current == "pass" || current == "return") + state.dedent += 1; + + if (current == "lambda") state.lambda = true; + if (current == ":" && !state.lambda && top(state).type == "py") + pushPyScope(state); + + if (current.length == 1 && !/string|comment/.test(style)) { + var delimiter_index = "[({".indexOf(current); + if (delimiter_index != -1) + pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1)); + + delimiter_index = "])}".indexOf(current); + if (delimiter_index != -1) { + if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent + else return ERRORCLASS; + } + } + if (state.dedent > 0 && stream.eol() && top(state).type == "py") { + if (state.scopes.length > 1) state.scopes.pop(); + state.dedent -= 1; + } + + return style; + } + + var external = { + startState: function(basecolumn) { + return { + tokenize: tokenBase, + scopes: [{offset: basecolumn || 0, type: "py", align: null}], + indent: basecolumn || 0, + lastToken: null, + lambda: false, + dedent: 0 + }; + }, + + token: function(stream, state) { + var addErr = state.errorToken; + if (addErr) state.errorToken = false; + var style = tokenLexer(stream, state); + + if (style && style != "comment") + state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style; + if (style == "punctuation") style = null; + + if (stream.eol() && state.lambda) + state.lambda = false; + return addErr ? style + " " + ERRORCLASS : style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase) + return state.tokenize.isString ? CodeMirror.Pass : 0; + + var scope = top(state), closing = scope.type == textAfter.charAt(0) + if (scope.align != null) + return scope.align - (closing ? 1 : 0) + else + return scope.offset - (closing ? hangingIndent : 0) + }, + + electricInput: /^\s*[\}\]\)]$/, + closeBrackets: {triples: "'\""}, + lineComment: "#", + fold: "indent" + }; + return external; + }); + + CodeMirror.defineMIME("text/x-python", "python"); + + var words = function(str) { return str.split(" "); }; + + CodeMirror.defineMIME("text/x-cython", { + name: "python", + extra_keywords: words("by cdef cimport cpdef ctypedef enum except "+ + "extern gil include nogil property public "+ + "readonly struct union DEF IF ELIF ELSE") + }); + +}); diff --git a/js/codemirror/5.40.2/xml.js b/js/codemirror/5.40.2/xml.js new file mode 100644 index 0000000..b67bf85 --- /dev/null +++ b/js/codemirror/5.40.2/xml.js @@ -0,0 +1,402 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +var htmlConfig = { + autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true, + 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true, + 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, + 'track': true, 'wbr': true, 'menuitem': true}, + implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true, + 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true, + 'th': true, 'tr': true}, + contextGrabbers: { + 'dd': {'dd': true, 'dt': true}, + 'dt': {'dd': true, 'dt': true}, + 'li': {'li': true}, + 'option': {'option': true, 'optgroup': true}, + 'optgroup': {'optgroup': true}, + 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true, + 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true, + 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true, + 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true, + 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true}, + 'rp': {'rp': true, 'rt': true}, + 'rt': {'rp': true, 'rt': true}, + 'tbody': {'tbody': true, 'tfoot': true}, + 'td': {'td': true, 'th': true}, + 'tfoot': {'tbody': true}, + 'th': {'td': true, 'th': true}, + 'thead': {'tbody': true, 'tfoot': true}, + 'tr': {'tr': true} + }, + doNotIndent: {"pre": true}, + allowUnquoted: true, + allowMissing: true, + caseFold: true +} + +var xmlConfig = { + autoSelfClosers: {}, + implicitlyClosed: {}, + contextGrabbers: {}, + doNotIndent: {}, + allowUnquoted: false, + allowMissing: false, + allowMissingTagName: false, + caseFold: false +} + +CodeMirror.defineMode("xml", function(editorConf, config_) { + var indentUnit = editorConf.indentUnit + var config = {} + var defaults = config_.htmlMode ? htmlConfig : xmlConfig + for (var prop in defaults) config[prop] = defaults[prop] + for (var prop in config_) config[prop] = config_[prop] + + // Return variables for tokenizers + var type, setStyle; + + function inText(stream, state) { + function chain(parser) { + state.tokenize = parser; + return parser(stream, state); + } + + var ch = stream.next(); + if (ch == "<") { + if (stream.eat("!")) { + if (stream.eat("[")) { + if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>")); + else return null; + } else if (stream.match("--")) { + return chain(inBlock("comment", "-->")); + } else if (stream.match("DOCTYPE", true, true)) { + stream.eatWhile(/[\w\._\-]/); + return chain(doctype(1)); + } else { + return null; + } + } else if (stream.eat("?")) { + stream.eatWhile(/[\w\._\-]/); + state.tokenize = inBlock("meta", "?>"); + return "meta"; + } else { + type = stream.eat("/") ? "closeTag" : "openTag"; + state.tokenize = inTag; + return "tag bracket"; + } + } else if (ch == "&") { + var ok; + if (stream.eat("#")) { + if (stream.eat("x")) { + ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); + } else { + ok = stream.eatWhile(/[\d]/) && stream.eat(";"); + } + } else { + ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); + } + return ok ? "atom" : "error"; + } else { + stream.eatWhile(/[^&<]/); + return null; + } + } + inText.isInText = true; + + function inTag(stream, state) { + var ch = stream.next(); + if (ch == ">" || (ch == "/" && stream.eat(">"))) { + state.tokenize = inText; + type = ch == ">" ? "endTag" : "selfcloseTag"; + return "tag bracket"; + } else if (ch == "=") { + type = "equals"; + return null; + } else if (ch == "<") { + state.tokenize = inText; + state.state = baseState; + state.tagName = state.tagStart = null; + var next = state.tokenize(stream, state); + return next ? next + " tag error" : "tag error"; + } else if (/[\'\"]/.test(ch)) { + state.tokenize = inAttribute(ch); + state.stringStartCol = stream.column(); + return state.tokenize(stream, state); + } else { + stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/); + return "word"; + } + } + + function inAttribute(quote) { + var closure = function(stream, state) { + while (!stream.eol()) { + if (stream.next() == quote) { + state.tokenize = inTag; + break; + } + } + return "string"; + }; + closure.isInAttribute = true; + return closure; + } + + function inBlock(style, terminator) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.match(terminator)) { + state.tokenize = inText; + break; + } + stream.next(); + } + return style; + } + } + + function doctype(depth) { + return function(stream, state) { + var ch; + while ((ch = stream.next()) != null) { + if (ch == "<") { + state.tokenize = doctype(depth + 1); + return state.tokenize(stream, state); + } else if (ch == ">") { + if (depth == 1) { + state.tokenize = inText; + break; + } else { + state.tokenize = doctype(depth - 1); + return state.tokenize(stream, state); + } + } + } + return "meta"; + }; + } + + function Context(state, tagName, startOfLine) { + this.prev = state.context; + this.tagName = tagName; + this.indent = state.indented; + this.startOfLine = startOfLine; + if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent)) + this.noIndent = true; + } + function popContext(state) { + if (state.context) state.context = state.context.prev; + } + function maybePopContext(state, nextTagName) { + var parentTagName; + while (true) { + if (!state.context) { + return; + } + parentTagName = state.context.tagName; + if (!config.contextGrabbers.hasOwnProperty(parentTagName) || + !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { + return; + } + popContext(state); + } + } + + function baseState(type, stream, state) { + if (type == "openTag") { + state.tagStart = stream.column(); + return tagNameState; + } else if (type == "closeTag") { + return closeTagNameState; + } else { + return baseState; + } + } + function tagNameState(type, stream, state) { + if (type == "word") { + state.tagName = stream.current(); + setStyle = "tag"; + return attrState; + } else if (config.allowMissingTagName && type == "endTag") { + setStyle = "tag bracket"; + return attrState(type, stream, state); + } else { + setStyle = "error"; + return tagNameState; + } + } + function closeTagNameState(type, stream, state) { + if (type == "word") { + var tagName = stream.current(); + if (state.context && state.context.tagName != tagName && + config.implicitlyClosed.hasOwnProperty(state.context.tagName)) + popContext(state); + if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) { + setStyle = "tag"; + return closeState; + } else { + setStyle = "tag error"; + return closeStateErr; + } + } else if (config.allowMissingTagName && type == "endTag") { + setStyle = "tag bracket"; + return closeState(type, stream, state); + } else { + setStyle = "error"; + return closeStateErr; + } + } + + function closeState(type, _stream, state) { + if (type != "endTag") { + setStyle = "error"; + return closeState; + } + popContext(state); + return baseState; + } + function closeStateErr(type, stream, state) { + setStyle = "error"; + return closeState(type, stream, state); + } + + function attrState(type, _stream, state) { + if (type == "word") { + setStyle = "attribute"; + return attrEqState; + } else if (type == "endTag" || type == "selfcloseTag") { + var tagName = state.tagName, tagStart = state.tagStart; + state.tagName = state.tagStart = null; + if (type == "selfcloseTag" || + config.autoSelfClosers.hasOwnProperty(tagName)) { + maybePopContext(state, tagName); + } else { + maybePopContext(state, tagName); + state.context = new Context(state, tagName, tagStart == state.indented); + } + return baseState; + } + setStyle = "error"; + return attrState; + } + function attrEqState(type, stream, state) { + if (type == "equals") return attrValueState; + if (!config.allowMissing) setStyle = "error"; + return attrState(type, stream, state); + } + function attrValueState(type, stream, state) { + if (type == "string") return attrContinuedState; + if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;} + setStyle = "error"; + return attrState(type, stream, state); + } + function attrContinuedState(type, stream, state) { + if (type == "string") return attrContinuedState; + return attrState(type, stream, state); + } + + return { + startState: function(baseIndent) { + var state = {tokenize: inText, + state: baseState, + indented: baseIndent || 0, + tagName: null, tagStart: null, + context: null} + if (baseIndent != null) state.baseIndent = baseIndent + return state + }, + + token: function(stream, state) { + if (!state.tagName && stream.sol()) + state.indented = stream.indentation(); + + if (stream.eatSpace()) return null; + type = null; + var style = state.tokenize(stream, state); + if ((style || type) && style != "comment") { + setStyle = null; + state.state = state.state(type || style, stream, state); + if (setStyle) + style = setStyle == "error" ? style + " error" : setStyle; + } + return style; + }, + + indent: function(state, textAfter, fullLine) { + var context = state.context; + // Indent multi-line strings (e.g. css). + if (state.tokenize.isInAttribute) { + if (state.tagStart == state.indented) + return state.stringStartCol + 1; + else + return state.indented + indentUnit; + } + if (context && context.noIndent) return CodeMirror.Pass; + if (state.tokenize != inTag && state.tokenize != inText) + return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; + // Indent the starts of attribute names. + if (state.tagName) { + if (config.multilineTagIndentPastTag !== false) + return state.tagStart + state.tagName.length + 2; + else + return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1); + } + if (config.alignCDATA && /$/, + blockCommentStart: "", + + configuration: config.htmlMode ? "html" : "xml", + helperType: config.htmlMode ? "html" : "xml", + + skipAttribute: function(state) { + if (state.state == attrValueState) + state.state = attrState + } + }; +}); + +CodeMirror.defineMIME("text/xml", "xml"); +CodeMirror.defineMIME("application/xml", "xml"); +if (!CodeMirror.mimeModes.hasOwnProperty("text/html")) + CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true}); + +}); diff --git a/js/codemirror/5.50.0/.DS_Store b/js/codemirror/5.50.0/.DS_Store new file mode 100644 index 0000000..be6f762 Binary files /dev/null and b/js/codemirror/5.50.0/.DS_Store differ diff --git a/js/codemirror/5.50.0/addons/javascript-lint.js b/js/codemirror/5.50.0/addons/javascript-lint.js new file mode 100644 index 0000000..cc132d7 --- /dev/null +++ b/js/codemirror/5.50.0/addons/javascript-lint.js @@ -0,0 +1,63 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + // declare global: JSHINT + + function validator(text, options) { + if (!window.JSHINT) { + if (window.console) { + window.console.error("Error: window.JSHINT not defined, CodeMirror JavaScript linting cannot run."); + } + return []; + } + if (!options.indent) // JSHint error.character actually is a column index, this fixes underlining on lines using tabs for indentation + options.indent = 1; // JSHint default value is 4 + JSHINT(text, options, options.globals); + var errors = JSHINT.data().errors, result = []; + if (errors) parseErrors(errors, result); + return result; + } + + CodeMirror.registerHelper("lint", "javascript", validator); + + function parseErrors(errors, output) { + for ( var i = 0; i < errors.length; i++) { + var error = errors[i]; + if (error) { + if (error.line <= 0) { + if (window.console) { + window.console.warn("Cannot display JSHint error (invalid line " + error.line + ")", error); + } + continue; + } + + var start = error.character - 1, end = start + 1; + if (error.evidence) { + var index = error.evidence.substring(start).search(/.\b/); + if (index > -1) { + end += index; + } + } + + // Convert to format expected by validation service + var hint = { + message: error.reason, + severity: error.code ? (error.code.startsWith('W') ? "warning" : "error") : "error", + from: CodeMirror.Pos(error.line - 1, start), + to: CodeMirror.Pos(error.line - 1, end) + }; + + output.push(hint); + } + } + } +}); diff --git a/js/codemirror/5.50.0/codemirror.css b/js/codemirror/5.50.0/codemirror.css new file mode 100644 index 0000000..bc910fb --- /dev/null +++ b/js/codemirror/5.50.0/codemirror.css @@ -0,0 +1,349 @@ +/* BASICS */ + +.CodeMirror { + /* Set height, width, borders, and global font properties here */ + font-family: monospace; + height: 300px; + color: black; + direction: ltr; +} + +/* PADDING */ + +.CodeMirror-lines { + padding: 4px 0; /* Vertical padding around content */ +} +.CodeMirror pre.CodeMirror-line, +.CodeMirror pre.CodeMirror-line-like { + padding: 0 4px; /* Horizontal padding of content */ +} + +.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + background-color: white; /* The little square between H and V scrollbars */ +} + +/* GUTTER */ + +.CodeMirror-gutters { + border-right: 1px solid #ddd; + background-color: #f7f7f7; + white-space: nowrap; +} +.CodeMirror-linenumbers {} +.CodeMirror-linenumber { + padding: 0 3px 0 5px; + min-width: 20px; + text-align: right; + color: #999; + white-space: nowrap; +} + +.CodeMirror-guttermarker { color: black; } +.CodeMirror-guttermarker-subtle { color: #999; } + +/* CURSOR */ + +.CodeMirror-cursor { + border-left: 1px solid black; + border-right: none; + width: 0; +} +/* Shown when moving in bi-directional text */ +.CodeMirror div.CodeMirror-secondarycursor { + border-left: 1px solid silver; +} +.cm-fat-cursor .CodeMirror-cursor { + width: auto; + border: 0 !important; + background: #7e7; +} +.cm-fat-cursor div.CodeMirror-cursors { + z-index: 1; +} +.cm-fat-cursor-mark { + background-color: rgba(20, 255, 20, 0.5); + -webkit-animation: blink 1.06s steps(1) infinite; + -moz-animation: blink 1.06s steps(1) infinite; + animation: blink 1.06s steps(1) infinite; +} +.cm-animate-fat-cursor { + width: auto; + border: 0; + -webkit-animation: blink 1.06s steps(1) infinite; + -moz-animation: blink 1.06s steps(1) infinite; + animation: blink 1.06s steps(1) infinite; + background-color: #7e7; +} +@-moz-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@-webkit-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} + +/* Can style cursor different in overwrite (non-insert) mode */ +.CodeMirror-overwrite .CodeMirror-cursor {} + +.cm-tab { display: inline-block; text-decoration: inherit; } + +.CodeMirror-rulers { + position: absolute; + left: 0; right: 0; top: -50px; bottom: 0; + overflow: hidden; +} +.CodeMirror-ruler { + border-left: 1px solid #ccc; + top: 0; bottom: 0; + position: absolute; +} + +/* DEFAULT THEME */ + +.cm-s-default .cm-header {color: blue;} +.cm-s-default .cm-quote {color: #090;} +.cm-negative {color: #d44;} +.cm-positive {color: #292;} +.cm-header, .cm-strong {font-weight: bold;} +.cm-em {font-style: italic;} +.cm-link {text-decoration: underline;} +.cm-strikethrough {text-decoration: line-through;} + +.cm-s-default .cm-keyword {color: #708;} +.cm-s-default .cm-atom {color: #219;} +.cm-s-default .cm-number {color: #164;} +.cm-s-default .cm-def {color: #00f;} +.cm-s-default .cm-variable, +.cm-s-default .cm-punctuation, +.cm-s-default .cm-property, +.cm-s-default .cm-operator {} +.cm-s-default .cm-variable-2 {color: #05a;} +.cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;} +.cm-s-default .cm-comment {color: #a50;} +.cm-s-default .cm-string {color: #a11;} +.cm-s-default .cm-string-2 {color: #f50;} +.cm-s-default .cm-meta {color: #555;} +.cm-s-default .cm-qualifier {color: #555;} +.cm-s-default .cm-builtin {color: #30a;} +.cm-s-default .cm-bracket {color: #997;} +.cm-s-default .cm-tag {color: #170;} +.cm-s-default .cm-attribute {color: #00c;} +.cm-s-default .cm-hr {color: #999;} +.cm-s-default .cm-link {color: #00c;} + +.cm-s-default .cm-error {color: #f00;} +.cm-invalidchar {color: #f00;} + +.CodeMirror-composing { border-bottom: 2px solid; } + +/* Default styles for common addons */ + +div.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;} +div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;} +.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } +.CodeMirror-activeline-background {background: #e8f2ff;} + +/* STOP */ + +/* The rest of this file contains styles related to the mechanics of + the editor. You probably shouldn't touch them. */ + +.CodeMirror { + position: relative; + overflow: hidden; + background: white; +} + +.CodeMirror-scroll { + overflow: scroll !important; /* Things will break if this is overridden */ + /* 30px is the magic margin used to hide the element's real scrollbars */ + /* See overflow: hidden in .CodeMirror */ + margin-bottom: -30px; margin-right: -30px; + padding-bottom: 30px; + height: 100%; + outline: none; /* Prevent dragging from highlighting the element */ + position: relative; +} +.CodeMirror-sizer { + position: relative; + border-right: 30px solid transparent; +} + +/* The fake, visible scrollbars. Used to force redraw during scrolling + before actual scrolling happens, thus preventing shaking and + flickering artifacts. */ +.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + position: absolute; + z-index: 6; + display: none; +} +.CodeMirror-vscrollbar { + right: 0; top: 0; + overflow-x: hidden; + overflow-y: scroll; +} +.CodeMirror-hscrollbar { + bottom: 0; left: 0; + overflow-y: hidden; + overflow-x: scroll; +} +.CodeMirror-scrollbar-filler { + right: 0; bottom: 0; +} +.CodeMirror-gutter-filler { + left: 0; bottom: 0; +} + +.CodeMirror-gutters { + position: absolute; left: 0; top: 0; + min-height: 100%; + z-index: 3; +} +.CodeMirror-gutter { + white-space: normal; + height: 100%; + display: inline-block; + vertical-align: top; + margin-bottom: -30px; +} +.CodeMirror-gutter-wrapper { + position: absolute; + z-index: 4; + background: none !important; + border: none !important; +} +.CodeMirror-gutter-background { + position: absolute; + top: 0; bottom: 0; + z-index: 4; +} +.CodeMirror-gutter-elt { + position: absolute; + cursor: default; + z-index: 4; +} +.CodeMirror-gutter-wrapper ::selection { background-color: transparent } +.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent } + +.CodeMirror-lines { + cursor: text; + min-height: 1px; /* prevents collapsing before first draw */ +} +.CodeMirror pre.CodeMirror-line, +.CodeMirror pre.CodeMirror-line-like { + /* Reset some styles that the rest of the page might have set */ + -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; + border-width: 0; + background: transparent; + font-family: inherit; + font-size: inherit; + margin: 0; + white-space: pre; + word-wrap: normal; + line-height: inherit; + color: inherit; + z-index: 2; + position: relative; + overflow: visible; + -webkit-tap-highlight-color: transparent; + -webkit-font-variant-ligatures: contextual; + font-variant-ligatures: contextual; +} +.CodeMirror-wrap pre.CodeMirror-line, +.CodeMirror-wrap pre.CodeMirror-line-like { + word-wrap: break-word; + white-space: pre-wrap; + word-break: normal; +} + +.CodeMirror-linebackground { + position: absolute; + left: 0; right: 0; top: 0; bottom: 0; + z-index: 0; +} + +.CodeMirror-linewidget { + position: relative; + z-index: 2; + padding: 0.1px; /* Force widget margins to stay inside of the container */ +} + +.CodeMirror-widget {} + +.CodeMirror-rtl pre { direction: rtl; } + +.CodeMirror-code { + outline: none; +} + +/* Force content-box sizing for the elements where we expect it */ +.CodeMirror-scroll, +.CodeMirror-sizer, +.CodeMirror-gutter, +.CodeMirror-gutters, +.CodeMirror-linenumber { + -moz-box-sizing: content-box; + box-sizing: content-box; +} + +.CodeMirror-measure { + position: absolute; + width: 100%; + height: 0; + overflow: hidden; + visibility: hidden; +} + +.CodeMirror-cursor { + position: absolute; + pointer-events: none; +} +.CodeMirror-measure pre { position: static; } + +div.CodeMirror-cursors { + visibility: hidden; + position: relative; + z-index: 3; +} +div.CodeMirror-dragcursors { + visibility: visible; +} + +.CodeMirror-focused div.CodeMirror-cursors { + visibility: visible; +} + +.CodeMirror-selected { background: #d9d9d9; } +.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } +.CodeMirror-crosshair { cursor: crosshair; } +.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; } +.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; } + +.cm-searching { + background-color: #ffa; + background-color: rgba(255, 255, 0, .4); +} + +/* Used to force a border model for a node */ +.cm-force-border { padding-right: .1px; } + +@media print { + /* Hide the cursor when printing */ + .CodeMirror div.CodeMirror-cursors { + visibility: hidden; + } +} + +/* See issue #2901 */ +.cm-tab-wrap-hack:after { content: ''; } + +/* Help users use markselection to safely style text background */ +span.CodeMirror-selectedtext { background: none; } diff --git a/js/codemirror/5.50.0/codemirror.js b/js/codemirror/5.50.0/codemirror.js new file mode 100644 index 0000000..22ac022 --- /dev/null +++ b/js/codemirror/5.50.0/codemirror.js @@ -0,0 +1,9785 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +// This is CodeMirror (https://codemirror.net), a code editor +// implemented in JavaScript on top of the browser's DOM. +// +// You can find some technical background for some of the code below +// at http://marijnhaverbeke.nl/blog/#cm-internals . + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.CodeMirror = factory()); +}(this, (function () { 'use strict'; + + // Kludges for bugs and behavior differences that can't be feature + // detected are enabled based on userAgent etc sniffing. + var userAgent = navigator.userAgent; + var platform = navigator.platform; + + var gecko = /gecko\/\d/i.test(userAgent); + var ie_upto10 = /MSIE \d/.test(userAgent); + var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); + var edge = /Edge\/(\d+)/.exec(userAgent); + var ie = ie_upto10 || ie_11up || edge; + var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]); + var webkit = !edge && /WebKit\//.test(userAgent); + var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); + var chrome = !edge && /Chrome\//.test(userAgent); + var presto = /Opera\//.test(userAgent); + var safari = /Apple Computer/.test(navigator.vendor); + var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); + var phantom = /PhantomJS/.test(userAgent); + + var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent); + var android = /Android/.test(userAgent); + // This is woefully incomplete. Suggestions for alternative methods welcome. + var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); + var mac = ios || /Mac/.test(platform); + var chromeOS = /\bCrOS\b/.test(userAgent); + var windows = /win/i.test(platform); + + var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); + if (presto_version) { presto_version = Number(presto_version[1]); } + if (presto_version && presto_version >= 15) { presto = false; webkit = true; } + // Some browsers use the wrong event properties to signal cmd/ctrl on OS X + var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); + var captureRightClick = gecko || (ie && ie_version >= 9); + + function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } + + var rmClass = function(node, cls) { + var current = node.className; + var match = classTest(cls).exec(current); + if (match) { + var after = current.slice(match.index + match[0].length); + node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); + } + }; + + function removeChildren(e) { + for (var count = e.childNodes.length; count > 0; --count) + { e.removeChild(e.firstChild); } + return e + } + + function removeChildrenAndAdd(parent, e) { + return removeChildren(parent).appendChild(e) + } + + function elt(tag, content, className, style) { + var e = document.createElement(tag); + if (className) { e.className = className; } + if (style) { e.style.cssText = style; } + if (typeof content == "string") { e.appendChild(document.createTextNode(content)); } + else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } } + return e + } + // wrapper for elt, which removes the elt from the accessibility tree + function eltP(tag, content, className, style) { + var e = elt(tag, content, className, style); + e.setAttribute("role", "presentation"); + return e + } + + var range; + if (document.createRange) { range = function(node, start, end, endNode) { + var r = document.createRange(); + r.setEnd(endNode || node, end); + r.setStart(node, start); + return r + }; } + else { range = function(node, start, end) { + var r = document.body.createTextRange(); + try { r.moveToElementText(node.parentNode); } + catch(e) { return r } + r.collapse(true); + r.moveEnd("character", end); + r.moveStart("character", start); + return r + }; } + + function contains(parent, child) { + if (child.nodeType == 3) // Android browser always returns false when child is a textnode + { child = child.parentNode; } + if (parent.contains) + { return parent.contains(child) } + do { + if (child.nodeType == 11) { child = child.host; } + if (child == parent) { return true } + } while (child = child.parentNode) + } + + function activeElt() { + // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. + // IE < 10 will throw when accessed while the page is loading or in an iframe. + // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. + var activeElement; + try { + activeElement = document.activeElement; + } catch(e) { + activeElement = document.body || null; + } + while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) + { activeElement = activeElement.shadowRoot.activeElement; } + return activeElement + } + + function addClass(node, cls) { + var current = node.className; + if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; } + } + function joinClasses(a, b) { + var as = a.split(" "); + for (var i = 0; i < as.length; i++) + { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } } + return b + } + + var selectInput = function(node) { node.select(); }; + if (ios) // Mobile Safari apparently has a bug where select() is broken. + { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; } + else if (ie) // Suppress mysterious IE10 errors + { selectInput = function(node) { try { node.select(); } catch(_e) {} }; } + + function bind(f) { + var args = Array.prototype.slice.call(arguments, 1); + return function(){return f.apply(null, args)} + } + + function copyObj(obj, target, overwrite) { + if (!target) { target = {}; } + for (var prop in obj) + { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) + { target[prop] = obj[prop]; } } + return target + } + + // Counts the column offset in a string, taking tabs into account. + // Used mostly to find indentation. + function countColumn(string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) { end = string.length; } + } + for (var i = startIndex || 0, n = startValue || 0;;) { + var nextTab = string.indexOf("\t", i); + if (nextTab < 0 || nextTab >= end) + { return n + (end - i) } + n += nextTab - i; + n += tabSize - (n % tabSize); + i = nextTab + 1; + } + } + + var Delayed = function() { + this.id = null; + this.f = null; + this.time = 0; + this.handler = bind(this.onTimeout, this); + }; + Delayed.prototype.onTimeout = function (self) { + self.id = 0; + if (self.time <= +new Date) { + self.f(); + } else { + setTimeout(self.handler, self.time - +new Date); + } + }; + Delayed.prototype.set = function (ms, f) { + this.f = f; + var time = +new Date + ms; + if (!this.id || time < this.time) { + clearTimeout(this.id); + this.id = setTimeout(this.handler, ms); + this.time = time; + } + }; + + function indexOf(array, elt) { + for (var i = 0; i < array.length; ++i) + { if (array[i] == elt) { return i } } + return -1 + } + + // Number of pixels added to scroller and sizer to hide scrollbar + var scrollerGap = 30; + + // Returned or thrown by various protocols to signal 'I'm not + // handling this'. + var Pass = {toString: function(){return "CodeMirror.Pass"}}; + + // Reused option objects for setSelection & friends + var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; + + // The inverse of countColumn -- find the offset that corresponds to + // a particular column. + function findColumn(string, goal, tabSize) { + for (var pos = 0, col = 0;;) { + var nextTab = string.indexOf("\t", pos); + if (nextTab == -1) { nextTab = string.length; } + var skipped = nextTab - pos; + if (nextTab == string.length || col + skipped >= goal) + { return pos + Math.min(skipped, goal - col) } + col += nextTab - pos; + col += tabSize - (col % tabSize); + pos = nextTab + 1; + if (col >= goal) { return pos } + } + } + + var spaceStrs = [""]; + function spaceStr(n) { + while (spaceStrs.length <= n) + { spaceStrs.push(lst(spaceStrs) + " "); } + return spaceStrs[n] + } + + function lst(arr) { return arr[arr.length-1] } + + function map(array, f) { + var out = []; + for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); } + return out + } + + function insertSorted(array, value, score) { + var pos = 0, priority = score(value); + while (pos < array.length && score(array[pos]) <= priority) { pos++; } + array.splice(pos, 0, value); + } + + function nothing() {} + + function createObj(base, props) { + var inst; + if (Object.create) { + inst = Object.create(base); + } else { + nothing.prototype = base; + inst = new nothing(); + } + if (props) { copyObj(props, inst); } + return inst + } + + var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + function isWordCharBasic(ch) { + return /\w/.test(ch) || ch > "\x80" && + (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)) + } + function isWordChar(ch, helper) { + if (!helper) { return isWordCharBasic(ch) } + if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true } + return helper.test(ch) + } + + function isEmpty(obj) { + for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } } + return true + } + + // Extending unicode characters. A series of a non-extending char + + // any number of extending chars is treated as a single unit as far + // as editing and measuring is concerned. This is not fully correct, + // since some scripts/fonts/browsers also treat other configurations + // of code points as a group. + var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; + function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) } + + // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range. + function skipExtendingChars(str, pos, dir) { + while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; } + return pos + } + + // Returns the value from the range [`from`; `to`] that satisfies + // `pred` and is closest to `from`. Assumes that at least `to` + // satisfies `pred`. Supports `from` being greater than `to`. + function findFirst(pred, from, to) { + // At any point we are certain `to` satisfies `pred`, don't know + // whether `from` does. + var dir = from > to ? -1 : 1; + for (;;) { + if (from == to) { return from } + var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF); + if (mid == from) { return pred(mid) ? from : to } + if (pred(mid)) { to = mid; } + else { from = mid + dir; } + } + } + + // BIDI HELPERS + + function iterateBidiSections(order, from, to, f) { + if (!order) { return f(from, to, "ltr", 0) } + var found = false; + for (var i = 0; i < order.length; ++i) { + var part = order[i]; + if (part.from < to && part.to > from || from == to && part.to == from) { + f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i); + found = true; + } + } + if (!found) { f(from, to, "ltr"); } + } + + var bidiOther = null; + function getBidiPartAt(order, ch, sticky) { + var found; + bidiOther = null; + for (var i = 0; i < order.length; ++i) { + var cur = order[i]; + if (cur.from < ch && cur.to > ch) { return i } + if (cur.to == ch) { + if (cur.from != cur.to && sticky == "before") { found = i; } + else { bidiOther = i; } + } + if (cur.from == ch) { + if (cur.from != cur.to && sticky != "before") { found = i; } + else { bidiOther = i; } + } + } + return found != null ? found : bidiOther + } + + // Bidirectional ordering algorithm + // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm + // that this (partially) implements. + + // One-char codes used for character types: + // L (L): Left-to-Right + // R (R): Right-to-Left + // r (AL): Right-to-Left Arabic + // 1 (EN): European Number + // + (ES): European Number Separator + // % (ET): European Number Terminator + // n (AN): Arabic Number + // , (CS): Common Number Separator + // m (NSM): Non-Spacing Mark + // b (BN): Boundary Neutral + // s (B): Paragraph Separator + // t (S): Segment Separator + // w (WS): Whitespace + // N (ON): Other Neutrals + + // Returns null if characters are ordered as they appear + // (left-to-right), or an array of sections ({from, to, level} + // objects) in the order in which they occur visually. + var bidiOrdering = (function() { + // Character types for codepoints 0 to 0xff + var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; + // Character types for codepoints 0x600 to 0x6f9 + var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; + function charType(code) { + if (code <= 0xf7) { return lowTypes.charAt(code) } + else if (0x590 <= code && code <= 0x5f4) { return "R" } + else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) } + else if (0x6ee <= code && code <= 0x8ac) { return "r" } + else if (0x2000 <= code && code <= 0x200b) { return "w" } + else if (code == 0x200c) { return "b" } + else { return "L" } + } + + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; + var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; + + function BidiSpan(level, from, to) { + this.level = level; + this.from = from; this.to = to; + } + + return function(str, direction) { + var outerType = direction == "ltr" ? "L" : "R"; + + if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false } + var len = str.length, types = []; + for (var i = 0; i < len; ++i) + { types.push(charType(str.charCodeAt(i))); } + + // W1. Examine each non-spacing mark (NSM) in the level run, and + // change the type of the NSM to the type of the previous + // character. If the NSM is at the start of the level run, it will + // get the type of sor. + for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) { + var type = types[i$1]; + if (type == "m") { types[i$1] = prev; } + else { prev = type; } + } + + // W2. Search backwards from each instance of a European number + // until the first strong type (R, L, AL, or sor) is found. If an + // AL is found, change the type of the European number to Arabic + // number. + // W3. Change all ALs to R. + for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) { + var type$1 = types[i$2]; + if (type$1 == "1" && cur == "r") { types[i$2] = "n"; } + else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } } + } + + // W4. A single European separator between two European numbers + // changes to a European number. A single common separator between + // two numbers of the same type changes to that type. + for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { + var type$2 = types[i$3]; + if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; } + else if (type$2 == "," && prev$1 == types[i$3+1] && + (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; } + prev$1 = type$2; + } + + // W5. A sequence of European terminators adjacent to European + // numbers changes to all European numbers. + // W6. Otherwise, separators and terminators change to Other + // Neutral. + for (var i$4 = 0; i$4 < len; ++i$4) { + var type$3 = types[i$4]; + if (type$3 == ",") { types[i$4] = "N"; } + else if (type$3 == "%") { + var end = (void 0); + for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} + var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; + for (var j = i$4; j < end; ++j) { types[j] = replace; } + i$4 = end - 1; + } + } + + // W7. Search backwards from each instance of a European number + // until the first strong type (R, L, or sor) is found. If an L is + // found, then change the type of the European number to L. + for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { + var type$4 = types[i$5]; + if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; } + else if (isStrong.test(type$4)) { cur$1 = type$4; } + } + + // N1. A sequence of neutrals takes the direction of the + // surrounding strong text if the text on both sides has the same + // direction. European and Arabic numbers act as if they were R in + // terms of their influence on neutrals. Start-of-level-run (sor) + // and end-of-level-run (eor) are used at level run boundaries. + // N2. Any remaining neutrals take the embedding direction. + for (var i$6 = 0; i$6 < len; ++i$6) { + if (isNeutral.test(types[i$6])) { + var end$1 = (void 0); + for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} + var before = (i$6 ? types[i$6-1] : outerType) == "L"; + var after = (end$1 < len ? types[end$1] : outerType) == "L"; + var replace$1 = before == after ? (before ? "L" : "R") : outerType; + for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; } + i$6 = end$1 - 1; + } + } + + // Here we depart from the documented algorithm, in order to avoid + // building up an actual levels array. Since there are only three + // levels (0, 1, 2) in an implementation that doesn't take + // explicit embedding into account, we can build up the order on + // the fly, without following the level-based algorithm. + var order = [], m; + for (var i$7 = 0; i$7 < len;) { + if (countsAsLeft.test(types[i$7])) { + var start = i$7; + for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} + order.push(new BidiSpan(0, start, i$7)); + } else { + var pos = i$7, at = order.length; + for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} + for (var j$2 = pos; j$2 < i$7;) { + if (countsAsNum.test(types[j$2])) { + if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); } + var nstart = j$2; + for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} + order.splice(at, 0, new BidiSpan(2, nstart, j$2)); + pos = j$2; + } else { ++j$2; } + } + if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); } + } + } + if (direction == "ltr") { + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length; + order.unshift(new BidiSpan(0, 0, m[0].length)); + } + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length; + order.push(new BidiSpan(0, len - m[0].length, len)); + } + } + + return direction == "rtl" ? order.reverse() : order + } + })(); + + // Get the bidi ordering for the given line (and cache it). Returns + // false for lines that are fully left-to-right, and an array of + // BidiSpan objects otherwise. + function getOrder(line, direction) { + var order = line.order; + if (order == null) { order = line.order = bidiOrdering(line.text, direction); } + return order + } + + // EVENT HANDLING + + // Lightweight event framework. on/off also work on DOM nodes, + // registering native DOM handlers. + + var noHandlers = []; + + var on = function(emitter, type, f) { + if (emitter.addEventListener) { + emitter.addEventListener(type, f, false); + } else if (emitter.attachEvent) { + emitter.attachEvent("on" + type, f); + } else { + var map$$1 = emitter._handlers || (emitter._handlers = {}); + map$$1[type] = (map$$1[type] || noHandlers).concat(f); + } + }; + + function getHandlers(emitter, type) { + return emitter._handlers && emitter._handlers[type] || noHandlers + } + + function off(emitter, type, f) { + if (emitter.removeEventListener) { + emitter.removeEventListener(type, f, false); + } else if (emitter.detachEvent) { + emitter.detachEvent("on" + type, f); + } else { + var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type]; + if (arr) { + var index = indexOf(arr, f); + if (index > -1) + { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); } + } + } + } + + function signal(emitter, type /*, values...*/) { + var handlers = getHandlers(emitter, type); + if (!handlers.length) { return } + var args = Array.prototype.slice.call(arguments, 2); + for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); } + } + + // The DOM events that CodeMirror handles can be overridden by + // registering a (non-DOM) handler on the editor for the event name, + // and preventDefault-ing the event in that handler. + function signalDOMEvent(cm, e, override) { + if (typeof e == "string") + { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; } + signal(cm, override || e.type, cm, e); + return e_defaultPrevented(e) || e.codemirrorIgnore + } + + function signalCursorActivity(cm) { + var arr = cm._handlers && cm._handlers.cursorActivity; + if (!arr) { return } + var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); + for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1) + { set.push(arr[i]); } } + } + + function hasHandler(emitter, type) { + return getHandlers(emitter, type).length > 0 + } + + // Add on and off methods to a constructor's prototype, to make + // registering events on such objects more convenient. + function eventMixin(ctor) { + ctor.prototype.on = function(type, f) {on(this, type, f);}; + ctor.prototype.off = function(type, f) {off(this, type, f);}; + } + + // Due to the fact that we still support jurassic IE versions, some + // compatibility wrappers are needed. + + function e_preventDefault(e) { + if (e.preventDefault) { e.preventDefault(); } + else { e.returnValue = false; } + } + function e_stopPropagation(e) { + if (e.stopPropagation) { e.stopPropagation(); } + else { e.cancelBubble = true; } + } + function e_defaultPrevented(e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false + } + function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} + + function e_target(e) {return e.target || e.srcElement} + function e_button(e) { + var b = e.which; + if (b == null) { + if (e.button & 1) { b = 1; } + else if (e.button & 2) { b = 3; } + else if (e.button & 4) { b = 2; } + } + if (mac && e.ctrlKey && b == 1) { b = 3; } + return b + } + + // Detect drag-and-drop + var dragAndDrop = function() { + // There is *some* kind of drag-and-drop support in IE6-8, but I + // couldn't get it to work yet. + if (ie && ie_version < 9) { return false } + var div = elt('div'); + return "draggable" in div || "dragDrop" in div + }(); + + var zwspSupported; + function zeroWidthElement(measure) { + if (zwspSupported == null) { + var test = elt("span", "\u200b"); + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); + if (measure.firstChild.offsetHeight != 0) + { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); } + } + var node = zwspSupported ? elt("span", "\u200b") : + elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); + node.setAttribute("cm-text", ""); + return node + } + + // Feature-detect IE's crummy client rect reporting for bidi text + var badBidiRects; + function hasBadBidiRects(measure) { + if (badBidiRects != null) { return badBidiRects } + var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); + var r0 = range(txt, 0, 1).getBoundingClientRect(); + var r1 = range(txt, 1, 2).getBoundingClientRect(); + removeChildren(measure); + if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780) + return badBidiRects = (r1.right - r0.right < 3) + } + + // See if "".split is the broken IE version, if so, provide an + // alternative way to split lines. + var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { + var pos = 0, result = [], l = string.length; + while (pos <= l) { + var nl = string.indexOf("\n", pos); + if (nl == -1) { nl = string.length; } + var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); + var rt = line.indexOf("\r"); + if (rt != -1) { + result.push(line.slice(0, rt)); + pos += rt + 1; + } else { + result.push(line); + pos = nl + 1; + } + } + return result + } : function (string) { return string.split(/\r\n?|\n/); }; + + var hasSelection = window.getSelection ? function (te) { + try { return te.selectionStart != te.selectionEnd } + catch(e) { return false } + } : function (te) { + var range$$1; + try {range$$1 = te.ownerDocument.selection.createRange();} + catch(e) {} + if (!range$$1 || range$$1.parentElement() != te) { return false } + return range$$1.compareEndPoints("StartToEnd", range$$1) != 0 + }; + + var hasCopyEvent = (function () { + var e = elt("div"); + if ("oncopy" in e) { return true } + e.setAttribute("oncopy", "return;"); + return typeof e.oncopy == "function" + })(); + + var badZoomedRects = null; + function hasBadZoomedRects(measure) { + if (badZoomedRects != null) { return badZoomedRects } + var node = removeChildrenAndAdd(measure, elt("span", "x")); + var normal = node.getBoundingClientRect(); + var fromRange = range(node, 0, 1).getBoundingClientRect(); + return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 + } + + // Known modes, by name and by MIME + var modes = {}, mimeModes = {}; + + // Extra arguments are stored as the mode's dependencies, which is + // used by (legacy) mechanisms like loadmode.js to automatically + // load a mode. (Preferred mechanism is the require/define calls.) + function defineMode(name, mode) { + if (arguments.length > 2) + { mode.dependencies = Array.prototype.slice.call(arguments, 2); } + modes[name] = mode; + } + + function defineMIME(mime, spec) { + mimeModes[mime] = spec; + } + + // Given a MIME type, a {name, ...options} config object, or a name + // string, return a mode config object. + function resolveMode(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec]; + } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { + var found = mimeModes[spec.name]; + if (typeof found == "string") { found = {name: found}; } + spec = createObj(found, spec); + spec.name = found.name; + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return resolveMode("application/xml") + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { + return resolveMode("application/json") + } + if (typeof spec == "string") { return {name: spec} } + else { return spec || {name: "null"} } + } + + // Given a mode spec (anything that resolveMode accepts), find and + // initialize an actual mode object. + function getMode(options, spec) { + spec = resolveMode(spec); + var mfactory = modes[spec.name]; + if (!mfactory) { return getMode(options, "text/plain") } + var modeObj = mfactory(options, spec); + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name]; + for (var prop in exts) { + if (!exts.hasOwnProperty(prop)) { continue } + if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; } + modeObj[prop] = exts[prop]; + } + } + modeObj.name = spec.name; + if (spec.helperType) { modeObj.helperType = spec.helperType; } + if (spec.modeProps) { for (var prop$1 in spec.modeProps) + { modeObj[prop$1] = spec.modeProps[prop$1]; } } + + return modeObj + } + + // This can be used to attach properties to mode objects from + // outside the actual mode definition. + var modeExtensions = {}; + function extendMode(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); + copyObj(properties, exts); + } + + function copyState(mode, state) { + if (state === true) { return state } + if (mode.copyState) { return mode.copyState(state) } + var nstate = {}; + for (var n in state) { + var val = state[n]; + if (val instanceof Array) { val = val.concat([]); } + nstate[n] = val; + } + return nstate + } + + // Given a mode and a state (for that mode), find the inner mode and + // state at the position that the state refers to. + function innerMode(mode, state) { + var info; + while (mode.innerMode) { + info = mode.innerMode(state); + if (!info || info.mode == mode) { break } + state = info.state; + mode = info.mode; + } + return info || {mode: mode, state: state} + } + + function startState(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true + } + + // STRING STREAM + + // Fed to the mode parsers, provides helper functions to make + // parsers more succinct. + + var StringStream = function(string, tabSize, lineOracle) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + this.lastColumnPos = this.lastColumnValue = 0; + this.lineStart = 0; + this.lineOracle = lineOracle; + }; + + StringStream.prototype.eol = function () {return this.pos >= this.string.length}; + StringStream.prototype.sol = function () {return this.pos == this.lineStart}; + StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined}; + StringStream.prototype.next = function () { + if (this.pos < this.string.length) + { return this.string.charAt(this.pos++) } + }; + StringStream.prototype.eat = function (match) { + var ch = this.string.charAt(this.pos); + var ok; + if (typeof match == "string") { ok = ch == match; } + else { ok = ch && (match.test ? match.test(ch) : match(ch)); } + if (ok) {++this.pos; return ch} + }; + StringStream.prototype.eatWhile = function (match) { + var start = this.pos; + while (this.eat(match)){} + return this.pos > start + }; + StringStream.prototype.eatSpace = function () { + var this$1 = this; + + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; } + return this.pos > start + }; + StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;}; + StringStream.prototype.skipTo = function (ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) {this.pos = found; return true} + }; + StringStream.prototype.backUp = function (n) {this.pos -= n;}; + StringStream.prototype.column = function () { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); + this.lastColumnPos = this.start; + } + return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) + }; + StringStream.prototype.indentation = function () { + return countColumn(this.string, null, this.tabSize) - + (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) + }; + StringStream.prototype.match = function (pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) { this.pos += pattern.length; } + return true + } + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) { return null } + if (match && consume !== false) { this.pos += match[0].length; } + return match + } + }; + StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)}; + StringStream.prototype.hideFirstChars = function (n, inner) { + this.lineStart += n; + try { return inner() } + finally { this.lineStart -= n; } + }; + StringStream.prototype.lookAhead = function (n) { + var oracle = this.lineOracle; + return oracle && oracle.lookAhead(n) + }; + StringStream.prototype.baseToken = function () { + var oracle = this.lineOracle; + return oracle && oracle.baseToken(this.pos) + }; + + // Find the line object corresponding to the given line number. + function getLine(doc, n) { + n -= doc.first; + if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") } + var chunk = doc; + while (!chunk.lines) { + for (var i = 0;; ++i) { + var child = chunk.children[i], sz = child.chunkSize(); + if (n < sz) { chunk = child; break } + n -= sz; + } + } + return chunk.lines[n] + } + + // Get the part of a document between two positions, as an array of + // strings. + function getBetween(doc, start, end) { + var out = [], n = start.line; + doc.iter(start.line, end.line + 1, function (line) { + var text = line.text; + if (n == end.line) { text = text.slice(0, end.ch); } + if (n == start.line) { text = text.slice(start.ch); } + out.push(text); + ++n; + }); + return out + } + // Get the lines between from and to, as array of strings. + function getLines(doc, from, to) { + var out = []; + doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value + return out + } + + // Update the height of a line, propagating the height change + // upwards to parent nodes. + function updateLineHeight(line, height) { + var diff = height - line.height; + if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } } + } + + // Given a line object, find its line number by walking up through + // its parent links. + function lineNo(line) { + if (line.parent == null) { return null } + var cur = line.parent, no = indexOf(cur.lines, line); + for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { + for (var i = 0;; ++i) { + if (chunk.children[i] == cur) { break } + no += chunk.children[i].chunkSize(); + } + } + return no + cur.first + } + + // Find the line at the given vertical position, using the height + // information in the document tree. + function lineAtHeight(chunk, h) { + var n = chunk.first; + outer: do { + for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) { + var child = chunk.children[i$1], ch = child.height; + if (h < ch) { chunk = child; continue outer } + h -= ch; + n += child.chunkSize(); + } + return n + } while (!chunk.lines) + var i = 0; + for (; i < chunk.lines.length; ++i) { + var line = chunk.lines[i], lh = line.height; + if (h < lh) { break } + h -= lh; + } + return n + i + } + + function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size} + + function lineNumberFor(options, i) { + return String(options.lineNumberFormatter(i + options.firstLineNumber)) + } + + // A Pos instance represents a position within the text. + function Pos(line, ch, sticky) { + if ( sticky === void 0 ) sticky = null; + + if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) } + this.line = line; + this.ch = ch; + this.sticky = sticky; + } + + // Compare two positions, return 0 if they are the same, a negative + // number when a is less, and a positive number otherwise. + function cmp(a, b) { return a.line - b.line || a.ch - b.ch } + + function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 } + + function copyPos(x) {return Pos(x.line, x.ch)} + function maxPos(a, b) { return cmp(a, b) < 0 ? b : a } + function minPos(a, b) { return cmp(a, b) < 0 ? a : b } + + // Most of the external API clips given positions to make sure they + // actually exist within the document. + function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))} + function clipPos(doc, pos) { + if (pos.line < doc.first) { return Pos(doc.first, 0) } + var last = doc.first + doc.size - 1; + if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) } + return clipToLen(pos, getLine(doc, pos.line).text.length) + } + function clipToLen(pos, linelen) { + var ch = pos.ch; + if (ch == null || ch > linelen) { return Pos(pos.line, linelen) } + else if (ch < 0) { return Pos(pos.line, 0) } + else { return pos } + } + function clipPosArray(doc, array) { + var out = []; + for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); } + return out + } + + var SavedContext = function(state, lookAhead) { + this.state = state; + this.lookAhead = lookAhead; + }; + + var Context = function(doc, state, line, lookAhead) { + this.state = state; + this.doc = doc; + this.line = line; + this.maxLookAhead = lookAhead || 0; + this.baseTokens = null; + this.baseTokenPos = 1; + }; + + Context.prototype.lookAhead = function (n) { + var line = this.doc.getLine(this.line + n); + if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; } + return line + }; + + Context.prototype.baseToken = function (n) { + var this$1 = this; + + if (!this.baseTokens) { return null } + while (this.baseTokens[this.baseTokenPos] <= n) + { this$1.baseTokenPos += 2; } + var type = this.baseTokens[this.baseTokenPos + 1]; + return {type: type && type.replace(/( |^)overlay .*/, ""), + size: this.baseTokens[this.baseTokenPos] - n} + }; + + Context.prototype.nextLine = function () { + this.line++; + if (this.maxLookAhead > 0) { this.maxLookAhead--; } + }; + + Context.fromSaved = function (doc, saved, line) { + if (saved instanceof SavedContext) + { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) } + else + { return new Context(doc, copyState(doc.mode, saved), line) } + }; + + Context.prototype.save = function (copy) { + var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; + return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state + }; + + + // Compute a style array (an array starting with a mode generation + // -- for invalidation -- followed by pairs of end positions and + // style strings), which is used to highlight the tokens on the + // line. + function highlightLine(cm, line, context, forceToEnd) { + // A styles array always starts with a number identifying the + // mode/overlays that it is based on (for easy invalidation). + var st = [cm.state.modeGen], lineClasses = {}; + // Compute the base array of styles + runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); }, + lineClasses, forceToEnd); + var state = context.state; + + // Run overlays, adjust style array. + var loop = function ( o ) { + context.baseTokens = st; + var overlay = cm.state.overlays[o], i = 1, at = 0; + context.state = true; + runMode(cm, line.text, overlay.mode, context, function (end, style) { + var start = i; + // Ensure there's a token end at the current position, and that i points at it + while (at < end) { + var i_end = st[i]; + if (i_end > end) + { st.splice(i, 1, end, st[i+1], i_end); } + i += 2; + at = Math.min(end, i_end); + } + if (!style) { return } + if (overlay.opaque) { + st.splice(start, i - start, end, "overlay " + style); + i = start + 2; + } else { + for (; start < i; start += 2) { + var cur = st[start+1]; + st[start+1] = (cur ? cur + " " : "") + "overlay " + style; + } + } + }, lineClasses); + context.state = state; + context.baseTokens = null; + context.baseTokenPos = 1; + }; + + for (var o = 0; o < cm.state.overlays.length; ++o) loop( o ); + + return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} + } + + function getLineStyles(cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + var context = getContextBefore(cm, lineNo(line)); + var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); + var result = highlightLine(cm, line, context); + if (resetState) { context.state = resetState; } + line.stateAfter = context.save(!resetState); + line.styles = result.styles; + if (result.classes) { line.styleClasses = result.classes; } + else if (line.styleClasses) { line.styleClasses = null; } + if (updateFrontier === cm.doc.highlightFrontier) + { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); } + } + return line.styles + } + + function getContextBefore(cm, n, precise) { + var doc = cm.doc, display = cm.display; + if (!doc.mode.startState) { return new Context(doc, true, n) } + var start = findStartLine(cm, n, precise); + var saved = start > doc.first && getLine(doc, start - 1).stateAfter; + var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start); + + doc.iter(start, n, function (line) { + processLine(cm, line.text, context); + var pos = context.line; + line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; + context.nextLine(); + }); + if (precise) { doc.modeFrontier = context.line; } + return context + } + + // Lightweight form of highlight -- proceed over this line and + // update state, but don't save a style array. Used for lines that + // aren't currently visible. + function processLine(cm, text, context, startAt) { + var mode = cm.doc.mode; + var stream = new StringStream(text, cm.options.tabSize, context); + stream.start = stream.pos = startAt || 0; + if (text == "") { callBlankLine(mode, context.state); } + while (!stream.eol()) { + readToken(mode, stream, context.state); + stream.start = stream.pos; + } + } + + function callBlankLine(mode, state) { + if (mode.blankLine) { return mode.blankLine(state) } + if (!mode.innerMode) { return } + var inner = innerMode(mode, state); + if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) } + } + + function readToken(mode, stream, state, inner) { + for (var i = 0; i < 10; i++) { + if (inner) { inner[0] = innerMode(mode, state).mode; } + var style = mode.token(stream, state); + if (stream.pos > stream.start) { return style } + } + throw new Error("Mode " + mode.name + " failed to advance stream.") + } + + var Token = function(stream, type, state) { + this.start = stream.start; this.end = stream.pos; + this.string = stream.current(); + this.type = type || null; + this.state = state; + }; + + // Utility for getTokenAt and getLineTokens + function takeToken(cm, pos, precise, asArray) { + var doc = cm.doc, mode = doc.mode, style; + pos = clipPos(doc, pos); + var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise); + var stream = new StringStream(line.text, cm.options.tabSize, context), tokens; + if (asArray) { tokens = []; } + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos; + style = readToken(mode, stream, context.state); + if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); } + } + return asArray ? tokens : new Token(stream, style, context.state) + } + + function extractLineClasses(type, output) { + if (type) { for (;;) { + var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); + if (!lineClass) { break } + type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); + var prop = lineClass[1] ? "bgClass" : "textClass"; + if (output[prop] == null) + { output[prop] = lineClass[2]; } + else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) + { output[prop] += " " + lineClass[2]; } + } } + return type + } + + // Run the given mode's parser over a line, calling f for each token. + function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { + var flattenSpans = mode.flattenSpans; + if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; } + var curStart = 0, curStyle = null; + var stream = new StringStream(text, cm.options.tabSize, context), style; + var inner = cm.options.addModeClass && [null]; + if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); } + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false; + if (forceToEnd) { processLine(cm, text, context, stream.pos); } + stream.pos = text.length; + style = null; + } else { + style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); + } + if (inner) { + var mName = inner[0].name; + if (mName) { style = "m-" + (style ? mName + " " + style : mName); } + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 5000); + f(curStart, curStyle); + } + curStyle = style; + } + stream.start = stream.pos; + } + while (curStart < stream.pos) { + // Webkit seems to refuse to render text nodes longer than 57444 + // characters, and returns inaccurate measurements in nodes + // starting around 5000 chars. + var pos = Math.min(stream.pos, curStart + 5000); + f(pos, curStyle); + curStart = pos; + } + } + + // Finds the line to start with when starting a parse. Tries to + // find a line with a stateAfter, so that it can start with a + // valid state. If that fails, it returns the line with the + // smallest indentation, which tends to need the least context to + // parse correctly. + function findStartLine(cm, n, precise) { + var minindent, minline, doc = cm.doc; + var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); + for (var search = n; search > lim; --search) { + if (search <= doc.first) { return doc.first } + var line = getLine(doc, search - 1), after = line.stateAfter; + if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) + { return search } + var indented = countColumn(line.text, null, cm.options.tabSize); + if (minline == null || minindent > indented) { + minline = search - 1; + minindent = indented; + } + } + return minline + } + + function retreatFrontier(doc, n) { + doc.modeFrontier = Math.min(doc.modeFrontier, n); + if (doc.highlightFrontier < n - 10) { return } + var start = doc.first; + for (var line = n - 1; line > start; line--) { + var saved = getLine(doc, line).stateAfter; + // change is on 3 + // state on line 1 looked ahead 2 -- so saw 3 + // test 1 + 2 < 3 should cover this + if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { + start = line + 1; + break + } + } + doc.highlightFrontier = Math.min(doc.highlightFrontier, start); + } + + // Optimize some code when these features are not used. + var sawReadOnlySpans = false, sawCollapsedSpans = false; + + function seeReadOnlySpans() { + sawReadOnlySpans = true; + } + + function seeCollapsedSpans() { + sawCollapsedSpans = true; + } + + // TEXTMARKER SPANS + + function MarkedSpan(marker, from, to) { + this.marker = marker; + this.from = from; this.to = to; + } + + // Search an array of spans for a span matching the given marker. + function getMarkedSpanFor(spans, marker) { + if (spans) { for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.marker == marker) { return span } + } } + } + // Remove a span from an array, returning undefined if no spans are + // left (we don't store arrays for lines without spans). + function removeMarkedSpan(spans, span) { + var r; + for (var i = 0; i < spans.length; ++i) + { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } } + return r + } + // Add a span to a line. + function addMarkedSpan(line, span) { + line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; + span.marker.attachLine(line); + } + + // Used for the algorithm that adjusts markers for a change in the + // document. These functions cut an array of spans at a given + // character position, returning an array of remaining chunks (or + // undefined if nothing remains). + function markedSpansBefore(old, startCh, isInsert) { + var nw; + if (old) { for (var i = 0; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); + if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh) + ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); + } + } } + return nw + } + function markedSpansAfter(old, endCh, isInsert) { + var nw; + if (old) { for (var i = 0; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); + if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh) + ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, + span.to == null ? null : span.to - endCh)); + } + } } + return nw + } + + // Given a change object, compute the new set of marker spans that + // cover the line in which the change took place. Removes spans + // entirely within the change, reconnects spans belonging to the + // same marker that appear on both sides of the change, and cuts off + // spans partially within the change. Returns an array of span + // arrays with one element for each line in (after) the change. + function stretchSpansOverChange(doc, change) { + if (change.full) { return null } + var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; + var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; + if (!oldFirst && !oldLast) { return null } + + var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; + // Get the spans that 'stick out' on both sides + var first = markedSpansBefore(oldFirst, startCh, isInsert); + var last = markedSpansAfter(oldLast, endCh, isInsert); + + // Next, merge those two ends + var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); + if (first) { + // Fix up .to properties of first + for (var i = 0; i < first.length; ++i) { + var span = first[i]; + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker); + if (!found) { span.to = startCh; } + else if (sameLine) { span.to = found.to == null ? null : found.to + offset; } + } + } + } + if (last) { + // Fix up .from in last (or move them into first in case of sameLine) + for (var i$1 = 0; i$1 < last.length; ++i$1) { + var span$1 = last[i$1]; + if (span$1.to != null) { span$1.to += offset; } + if (span$1.from == null) { + var found$1 = getMarkedSpanFor(first, span$1.marker); + if (!found$1) { + span$1.from = offset; + if (sameLine) { (first || (first = [])).push(span$1); } + } + } else { + span$1.from += offset; + if (sameLine) { (first || (first = [])).push(span$1); } + } + } + } + // Make sure we didn't create any zero-length spans + if (first) { first = clearEmptySpans(first); } + if (last && last != first) { last = clearEmptySpans(last); } + + var newMarkers = [first]; + if (!sameLine) { + // Fill gap with whole-line-spans + var gap = change.text.length - 2, gapMarkers; + if (gap > 0 && first) + { for (var i$2 = 0; i$2 < first.length; ++i$2) + { if (first[i$2].to == null) + { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } } + for (var i$3 = 0; i$3 < gap; ++i$3) + { newMarkers.push(gapMarkers); } + newMarkers.push(last); + } + return newMarkers + } + + // Remove spans that are empty and don't have a clearWhenEmpty + // option of false. + function clearEmptySpans(spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) + { spans.splice(i--, 1); } + } + if (!spans.length) { return null } + return spans + } + + // Used to 'clip' out readOnly ranges when making a change. + function removeReadOnlyRanges(doc, from, to) { + var markers = null; + doc.iter(from.line, to.line + 1, function (line) { + if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { + var mark = line.markedSpans[i].marker; + if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) + { (markers || (markers = [])).push(mark); } + } } + }); + if (!markers) { return null } + var parts = [{from: from, to: to}]; + for (var i = 0; i < markers.length; ++i) { + var mk = markers[i], m = mk.find(0); + for (var j = 0; j < parts.length; ++j) { + var p = parts[j]; + if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue } + var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); + if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) + { newParts.push({from: p.from, to: m.from}); } + if (dto > 0 || !mk.inclusiveRight && !dto) + { newParts.push({from: m.to, to: p.to}); } + parts.splice.apply(parts, newParts); + j += newParts.length - 3; + } + } + return parts + } + + // Connect or disconnect spans from a line. + function detachMarkedSpans(line) { + var spans = line.markedSpans; + if (!spans) { return } + for (var i = 0; i < spans.length; ++i) + { spans[i].marker.detachLine(line); } + line.markedSpans = null; + } + function attachMarkedSpans(line, spans) { + if (!spans) { return } + for (var i = 0; i < spans.length; ++i) + { spans[i].marker.attachLine(line); } + line.markedSpans = spans; + } + + // Helpers used when computing which overlapping collapsed span + // counts as the larger one. + function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 } + function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 } + + // Returns a number indicating which of two overlapping collapsed + // spans is larger (and thus includes the other). Falls back to + // comparing ids when the spans cover exactly the same range. + function compareCollapsedMarkers(a, b) { + var lenDiff = a.lines.length - b.lines.length; + if (lenDiff != 0) { return lenDiff } + var aPos = a.find(), bPos = b.find(); + var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); + if (fromCmp) { return -fromCmp } + var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); + if (toCmp) { return toCmp } + return b.id - a.id + } + + // Find out whether a line ends or starts in a collapsed span. If + // so, return the marker for that span. + function collapsedSpanAtSide(line, start) { + var sps = sawCollapsedSpans && line.markedSpans, found; + if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && + (!found || compareCollapsedMarkers(found, sp.marker) < 0)) + { found = sp.marker; } + } } + return found + } + function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) } + function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) } + + function collapsedSpanAround(line, ch) { + var sps = sawCollapsedSpans && line.markedSpans, found; + if (sps) { for (var i = 0; i < sps.length; ++i) { + var sp = sps[i]; + if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && + (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; } + } } + return found + } + + // Test whether there exists a collapsed span that partially + // overlaps (covers the start or end, but not both) of a new span. + // Such overlap is not allowed. + function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) { + var line = getLine(doc, lineNo$$1); + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { for (var i = 0; i < sps.length; ++i) { + var sp = sps[i]; + if (!sp.marker.collapsed) { continue } + var found = sp.marker.find(0); + var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); + var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); + if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue } + if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || + fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) + { return true } + } } + } + + // A visual line is a line as drawn on the screen. Folding, for + // example, can cause multiple logical lines to appear on the same + // visual line. This finds the start of the visual line that the + // given line is part of (usually that is the line itself). + function visualLine(line) { + var merged; + while (merged = collapsedSpanAtStart(line)) + { line = merged.find(-1, true).line; } + return line + } + + function visualLineEnd(line) { + var merged; + while (merged = collapsedSpanAtEnd(line)) + { line = merged.find(1, true).line; } + return line + } + + // Returns an array of logical lines that continue the visual line + // started by the argument, or undefined if there are no such lines. + function visualLineContinued(line) { + var merged, lines; + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line + ;(lines || (lines = [])).push(line); + } + return lines + } + + // Get the line number of the start of the visual line that the + // given line number is part of. + function visualLineNo(doc, lineN) { + var line = getLine(doc, lineN), vis = visualLine(line); + if (line == vis) { return lineN } + return lineNo(vis) + } + + // Get the line number of the start of the next visual line after + // the given line. + function visualLineEndNo(doc, lineN) { + if (lineN > doc.lastLine()) { return lineN } + var line = getLine(doc, lineN), merged; + if (!lineIsHidden(doc, line)) { return lineN } + while (merged = collapsedSpanAtEnd(line)) + { line = merged.find(1, true).line; } + return lineNo(line) + 1 + } + + // Compute whether a line is hidden. Lines count as hidden when they + // are part of a visual line that starts with another line, or when + // they are entirely covered by collapsed, non-widget span. + function lineIsHidden(doc, line) { + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (!sp.marker.collapsed) { continue } + if (sp.from == null) { return true } + if (sp.marker.widgetNode) { continue } + if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) + { return true } + } } + } + function lineIsHiddenInner(doc, line, span) { + if (span.to == null) { + var end = span.marker.find(1, true); + return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)) + } + if (span.marker.inclusiveRight && span.to == line.text.length) + { return true } + for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) { + sp = line.markedSpans[i]; + if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && + (sp.to == null || sp.to != span.from) && + (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && + lineIsHiddenInner(doc, line, sp)) { return true } + } + } + + // Find the height above the given line. + function heightAtLine(lineObj) { + lineObj = visualLine(lineObj); + + var h = 0, chunk = lineObj.parent; + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i]; + if (line == lineObj) { break } + else { h += line.height; } + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i$1 = 0; i$1 < p.children.length; ++i$1) { + var cur = p.children[i$1]; + if (cur == chunk) { break } + else { h += cur.height; } + } + } + return h + } + + // Compute the character length of a line, taking into account + // collapsed ranges (see markText) that might hide parts, and join + // other lines onto it. + function lineLength(line) { + if (line.height == 0) { return 0 } + var len = line.text.length, merged, cur = line; + while (merged = collapsedSpanAtStart(cur)) { + var found = merged.find(0, true); + cur = found.from.line; + len += found.from.ch - found.to.ch; + } + cur = line; + while (merged = collapsedSpanAtEnd(cur)) { + var found$1 = merged.find(0, true); + len -= cur.text.length - found$1.from.ch; + cur = found$1.to.line; + len += cur.text.length - found$1.to.ch; + } + return len + } + + // Find the longest line in the document. + function findMaxLine(cm) { + var d = cm.display, doc = cm.doc; + d.maxLine = getLine(doc, doc.first); + d.maxLineLength = lineLength(d.maxLine); + d.maxLineChanged = true; + doc.iter(function (line) { + var len = lineLength(line); + if (len > d.maxLineLength) { + d.maxLineLength = len; + d.maxLine = line; + } + }); + } + + // LINE DATA STRUCTURE + + // Line objects. These hold state related to a line, including + // highlighting info (the styles array). + var Line = function(text, markedSpans, estimateHeight) { + this.text = text; + attachMarkedSpans(this, markedSpans); + this.height = estimateHeight ? estimateHeight(this) : 1; + }; + + Line.prototype.lineNo = function () { return lineNo(this) }; + eventMixin(Line); + + // Change the content (text, markers) of a line. Automatically + // invalidates cached information and tries to re-estimate the + // line's height. + function updateLine(line, text, markedSpans, estimateHeight) { + line.text = text; + if (line.stateAfter) { line.stateAfter = null; } + if (line.styles) { line.styles = null; } + if (line.order != null) { line.order = null; } + detachMarkedSpans(line); + attachMarkedSpans(line, markedSpans); + var estHeight = estimateHeight ? estimateHeight(line) : 1; + if (estHeight != line.height) { updateLineHeight(line, estHeight); } + } + + // Detach a line from the document tree and its markers. + function cleanUpLine(line) { + line.parent = null; + detachMarkedSpans(line); + } + + // Convert a style as returned by a mode (either null, or a string + // containing one or more styles) to a CSS style. This is cached, + // and also looks for line-wide styles. + var styleToClassCache = {}, styleToClassCacheWithMode = {}; + function interpretTokenStyle(style, options) { + if (!style || /^\s*$/.test(style)) { return null } + var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; + return cache[style] || + (cache[style] = style.replace(/\S+/g, "cm-$&")) + } + + // Render the DOM representation of the text of a line. Also builds + // up a 'line map', which points at the DOM nodes that represent + // specific stretches of text, and is used by the measuring code. + // The returned object contains the DOM node, this map, and + // information about line-wide styles that were set by the mode. + function buildLineContent(cm, lineView) { + // The padding-right forces the element to have a 'border', which + // is needed on Webkit to be able to get line-level bounding + // rectangles for it (in measureChar). + var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); + var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content, + col: 0, pos: 0, cm: cm, + trailingSpace: false, + splitSpaces: cm.getOption("lineWrapping")}; + lineView.measure = {}; + + // Iterate over the logical lines that make up this visual line. + for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { + var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0); + builder.pos = 0; + builder.addToken = buildToken; + // Optionally wire in some hacks into the token-rendering + // algorithm, to deal with browser quirks. + if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) + { builder.addToken = buildTokenBadBidi(builder.addToken, order); } + builder.map = []; + var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); + insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); + if (line.styleClasses) { + if (line.styleClasses.bgClass) + { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); } + if (line.styleClasses.textClass) + { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); } + } + + // Ensure at least a single node is present, for measuring. + if (builder.map.length == 0) + { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); } + + // Store the map and a cache object for the current logical line + if (i == 0) { + lineView.measure.map = builder.map; + lineView.measure.cache = {}; + } else { + (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) + ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}); + } + } + + // See issue #2901 + if (webkit) { + var last = builder.content.lastChild; + if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) + { builder.content.className = "cm-tab-wrap-hack"; } + } + + signal(cm, "renderLine", cm, lineView.line, builder.pre); + if (builder.pre.className) + { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); } + + return builder + } + + function defaultSpecialCharPlaceholder(ch) { + var token = elt("span", "\u2022", "cm-invalidchar"); + token.title = "\\u" + ch.charCodeAt(0).toString(16); + token.setAttribute("aria-label", token.title); + return token + } + + // Build up the DOM representation for a single token, and add it to + // the line map. Takes care to render special characters separately. + function buildToken(builder, text, style, startStyle, endStyle, css, attributes) { + if (!text) { return } + var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; + var special = builder.cm.state.specialChars, mustWrap = false; + var content; + if (!special.test(text)) { + builder.col += text.length; + content = document.createTextNode(displayText); + builder.map.push(builder.pos, builder.pos + text.length, content); + if (ie && ie_version < 9) { mustWrap = true; } + builder.pos += text.length; + } else { + content = document.createDocumentFragment(); + var pos = 0; + while (true) { + special.lastIndex = pos; + var m = special.exec(text); + var skipped = m ? m.index - pos : text.length - pos; + if (skipped) { + var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); + if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); } + else { content.appendChild(txt); } + builder.map.push(builder.pos, builder.pos + skipped, txt); + builder.col += skipped; + builder.pos += skipped; + } + if (!m) { break } + pos += skipped + 1; + var txt$1 = (void 0); + if (m[0] == "\t") { + var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; + txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); + txt$1.setAttribute("role", "presentation"); + txt$1.setAttribute("cm-text", "\t"); + builder.col += tabWidth; + } else if (m[0] == "\r" || m[0] == "\n") { + txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); + txt$1.setAttribute("cm-text", m[0]); + builder.col += 1; + } else { + txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); + txt$1.setAttribute("cm-text", m[0]); + if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); } + else { content.appendChild(txt$1); } + builder.col += 1; + } + builder.map.push(builder.pos, builder.pos + 1, txt$1); + builder.pos++; + } + } + builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; + if (style || startStyle || endStyle || mustWrap || css) { + var fullStyle = style || ""; + if (startStyle) { fullStyle += startStyle; } + if (endStyle) { fullStyle += endStyle; } + var token = elt("span", [content], fullStyle, css); + if (attributes) { + for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") + { token.setAttribute(attr, attributes[attr]); } } + } + return builder.content.appendChild(token) + } + builder.content.appendChild(content); + } + + // Change some spaces to NBSP to prevent the browser from collapsing + // trailing spaces at the end of a line when rendering text (issue #1362). + function splitSpaces(text, trailingBefore) { + if (text.length > 1 && !/ /.test(text)) { return text } + var spaceBefore = trailingBefore, result = ""; + for (var i = 0; i < text.length; i++) { + var ch = text.charAt(i); + if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) + { ch = "\u00a0"; } + result += ch; + spaceBefore = ch == " "; + } + return result + } + + // Work around nonsense dimensions being reported for stretches of + // right-to-left text. + function buildTokenBadBidi(inner, order) { + return function (builder, text, style, startStyle, endStyle, css, attributes) { + style = style ? style + " cm-force-border" : "cm-force-border"; + var start = builder.pos, end = start + text.length; + for (;;) { + // Find the part that overlaps with the start of this text + var part = (void 0); + for (var i = 0; i < order.length; i++) { + part = order[i]; + if (part.to > start && part.from <= start) { break } + } + if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) } + inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes); + startStyle = null; + text = text.slice(part.to - start); + start = part.to; + } + } + } + + function buildCollapsedSpan(builder, size, marker, ignoreWidget) { + var widget = !ignoreWidget && marker.widgetNode; + if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); } + if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { + if (!widget) + { widget = builder.content.appendChild(document.createElement("span")); } + widget.setAttribute("cm-marker", marker.id); + } + if (widget) { + builder.cm.display.input.setUneditable(widget); + builder.content.appendChild(widget); + } + builder.pos += size; + builder.trailingSpace = false; + } + + // Outputs a number of spans to make up a line, taking highlighting + // and marked text into account. + function insertLineContent(line, builder, styles) { + var spans = line.markedSpans, allText = line.text, at = 0; + if (!spans) { + for (var i$1 = 1; i$1 < styles.length; i$1+=2) + { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); } + return + } + + var len = allText.length, pos = 0, i = 1, text = "", style, css; + var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes; + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = css = ""; + attributes = null; + collapsed = null; nextChange = Infinity; + var foundBookmarks = [], endStyles = (void 0); + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], m = sp.marker; + if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { + foundBookmarks.push(m); + } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { + if (sp.to != null && sp.to != pos && nextChange > sp.to) { + nextChange = sp.to; + spanEndStyle = ""; + } + if (m.className) { spanStyle += " " + m.className; } + if (m.css) { css = (css ? css + ";" : "") + m.css; } + if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; } + if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); } + // support for the old title property + // https://github.com/codemirror/CodeMirror/pull/5673 + if (m.title) { (attributes || (attributes = {})).title = m.title; } + if (m.attributes) { + for (var attr in m.attributes) + { (attributes || (attributes = {}))[attr] = m.attributes[attr]; } + } + if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) + { collapsed = sp; } + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from; + } + } + if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) + { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } } + + if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) + { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } } + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, + collapsed.marker, collapsed.from == null); + if (collapsed.to == null) { return } + if (collapsed.to == pos) { collapsed = false; } + } + } + if (pos >= len) { break } + + var upto = Math.min(len, nextChange); + while (true) { + if (text) { + var end = pos + text.length; + if (!collapsed) { + var tokenText = end > upto ? text.slice(0, upto - pos) : text; + builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, + spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes); + } + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break} + pos = end; + spanStartStyle = ""; + } + text = allText.slice(at, at = styles[i++]); + style = interpretTokenStyle(styles[i++], builder.cm.options); + } + } + } + + + // These objects are used to represent the visible (currently drawn) + // part of the document. A LineView may correspond to multiple + // logical lines, if those are connected by collapsed ranges. + function LineView(doc, line, lineN) { + // The starting line + this.line = line; + // Continuing lines, if any + this.rest = visualLineContinued(line); + // Number of logical lines in this visual line + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; + this.node = this.text = null; + this.hidden = lineIsHidden(doc, line); + } + + // Create a range of LineView objects for the given lines. + function buildViewArray(cm, from, to) { + var array = [], nextPos; + for (var pos = from; pos < to; pos = nextPos) { + var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); + nextPos = pos + view.size; + array.push(view); + } + return array + } + + var operationGroup = null; + + function pushOperation(op) { + if (operationGroup) { + operationGroup.ops.push(op); + } else { + op.ownsGroup = operationGroup = { + ops: [op], + delayedCallbacks: [] + }; + } + } + + function fireCallbacksForOps(group) { + // Calls delayed callbacks and cursorActivity handlers until no + // new ones appear + var callbacks = group.delayedCallbacks, i = 0; + do { + for (; i < callbacks.length; i++) + { callbacks[i].call(null); } + for (var j = 0; j < group.ops.length; j++) { + var op = group.ops[j]; + if (op.cursorActivityHandlers) + { while (op.cursorActivityCalled < op.cursorActivityHandlers.length) + { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } } + } + } while (i < callbacks.length) + } + + function finishOperation(op, endCb) { + var group = op.ownsGroup; + if (!group) { return } + + try { fireCallbacksForOps(group); } + finally { + operationGroup = null; + endCb(group); + } + } + + var orphanDelayedCallbacks = null; + + // Often, we want to signal events at a point where we are in the + // middle of some work, but don't want the handler to start calling + // other methods on the editor, which might be in an inconsistent + // state or simply not expect any other events to happen. + // signalLater looks whether there are any handlers, and schedules + // them to be executed when the last operation ends, or, if no + // operation is active, when a timeout fires. + function signalLater(emitter, type /*, values...*/) { + var arr = getHandlers(emitter, type); + if (!arr.length) { return } + var args = Array.prototype.slice.call(arguments, 2), list; + if (operationGroup) { + list = operationGroup.delayedCallbacks; + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks; + } else { + list = orphanDelayedCallbacks = []; + setTimeout(fireOrphanDelayed, 0); + } + var loop = function ( i ) { + list.push(function () { return arr[i].apply(null, args); }); + }; + + for (var i = 0; i < arr.length; ++i) + loop( i ); + } + + function fireOrphanDelayed() { + var delayed = orphanDelayedCallbacks; + orphanDelayedCallbacks = null; + for (var i = 0; i < delayed.length; ++i) { delayed[i](); } + } + + // When an aspect of a line changes, a string is added to + // lineView.changes. This updates the relevant part of the line's + // DOM structure. + function updateLineForChanges(cm, lineView, lineN, dims) { + for (var j = 0; j < lineView.changes.length; j++) { + var type = lineView.changes[j]; + if (type == "text") { updateLineText(cm, lineView); } + else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); } + else if (type == "class") { updateLineClasses(cm, lineView); } + else if (type == "widget") { updateLineWidgets(cm, lineView, dims); } + } + lineView.changes = null; + } + + // Lines with gutter elements, widgets or a background class need to + // be wrapped, and have the extra elements added to the wrapper div + function ensureLineWrapped(lineView) { + if (lineView.node == lineView.text) { + lineView.node = elt("div", null, null, "position: relative"); + if (lineView.text.parentNode) + { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); } + lineView.node.appendChild(lineView.text); + if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; } + } + return lineView.node + } + + function updateLineBackground(cm, lineView) { + var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; + if (cls) { cls += " CodeMirror-linebackground"; } + if (lineView.background) { + if (cls) { lineView.background.className = cls; } + else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } + } else if (cls) { + var wrap = ensureLineWrapped(lineView); + lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); + cm.display.input.setUneditable(lineView.background); + } + } + + // Wrapper around buildLineContent which will reuse the structure + // in display.externalMeasured when possible. + function getLineContent(cm, lineView) { + var ext = cm.display.externalMeasured; + if (ext && ext.line == lineView.line) { + cm.display.externalMeasured = null; + lineView.measure = ext.measure; + return ext.built + } + return buildLineContent(cm, lineView) + } + + // Redraw the line's text. Interacts with the background and text + // classes because the mode may output tokens that influence these + // classes. + function updateLineText(cm, lineView) { + var cls = lineView.text.className; + var built = getLineContent(cm, lineView); + if (lineView.text == lineView.node) { lineView.node = built.pre; } + lineView.text.parentNode.replaceChild(built.pre, lineView.text); + lineView.text = built.pre; + if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { + lineView.bgClass = built.bgClass; + lineView.textClass = built.textClass; + updateLineClasses(cm, lineView); + } else if (cls) { + lineView.text.className = cls; + } + } + + function updateLineClasses(cm, lineView) { + updateLineBackground(cm, lineView); + if (lineView.line.wrapClass) + { ensureLineWrapped(lineView).className = lineView.line.wrapClass; } + else if (lineView.node != lineView.text) + { lineView.node.className = ""; } + var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; + lineView.text.className = textClass || ""; + } + + function updateLineGutter(cm, lineView, lineN, dims) { + if (lineView.gutter) { + lineView.node.removeChild(lineView.gutter); + lineView.gutter = null; + } + if (lineView.gutterBackground) { + lineView.node.removeChild(lineView.gutterBackground); + lineView.gutterBackground = null; + } + if (lineView.line.gutterClass) { + var wrap = ensureLineWrapped(lineView); + lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, + ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px")); + cm.display.input.setUneditable(lineView.gutterBackground); + wrap.insertBefore(lineView.gutterBackground, lineView.text); + } + var markers = lineView.line.gutterMarkers; + if (cm.options.lineNumbers || markers) { + var wrap$1 = ensureLineWrapped(lineView); + var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px")); + cm.display.input.setUneditable(gutterWrap); + wrap$1.insertBefore(gutterWrap, lineView.text); + if (lineView.line.gutterClass) + { gutterWrap.className += " " + lineView.line.gutterClass; } + if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) + { lineView.lineNumber = gutterWrap.appendChild( + elt("div", lineNumberFor(cm.options, lineN), + "CodeMirror-linenumber CodeMirror-gutter-elt", + ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); } + if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) { + var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id]; + if (found) + { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", + ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); } + } } + } + } + + function updateLineWidgets(cm, lineView, dims) { + if (lineView.alignable) { lineView.alignable = null; } + var isWidget = classTest("CodeMirror-linewidget"); + for (var node = lineView.node.firstChild, next = (void 0); node; node = next) { + next = node.nextSibling; + if (isWidget.test(node)) { lineView.node.removeChild(node); } + } + insertLineWidgets(cm, lineView, dims); + } + + // Build a line's DOM representation from scratch + function buildLineElement(cm, lineView, lineN, dims) { + var built = getLineContent(cm, lineView); + lineView.text = lineView.node = built.pre; + if (built.bgClass) { lineView.bgClass = built.bgClass; } + if (built.textClass) { lineView.textClass = built.textClass; } + + updateLineClasses(cm, lineView); + updateLineGutter(cm, lineView, lineN, dims); + insertLineWidgets(cm, lineView, dims); + return lineView.node + } + + // A lineView may contain multiple logical lines (when merged by + // collapsed spans). The widgets for all of them need to be drawn. + function insertLineWidgets(cm, lineView, dims) { + insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); + if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) + { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } } + } + + function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { + if (!line.widgets) { return } + var wrap = ensureLineWrapped(lineView); + for (var i = 0, ws = line.widgets; i < ws.length; ++i) { + var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : "")); + if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); } + positionLineWidget(widget, node, lineView, dims); + cm.display.input.setUneditable(node); + if (allowAbove && widget.above) + { wrap.insertBefore(node, lineView.gutter || lineView.text); } + else + { wrap.appendChild(node); } + signalLater(widget, "redraw"); + } + } + + function positionLineWidget(widget, node, lineView, dims) { + if (widget.noHScroll) { + (lineView.alignable || (lineView.alignable = [])).push(node); + var width = dims.wrapperWidth; + node.style.left = dims.fixedPos + "px"; + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth; + node.style.paddingLeft = dims.gutterTotalWidth + "px"; + } + node.style.width = width + "px"; + } + if (widget.coverGutter) { + node.style.zIndex = 5; + node.style.position = "relative"; + if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; } + } + } + + function widgetHeight(widget) { + if (widget.height != null) { return widget.height } + var cm = widget.doc.cm; + if (!cm) { return 0 } + if (!contains(document.body, widget.node)) { + var parentStyle = "position: relative;"; + if (widget.coverGutter) + { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; } + if (widget.noHScroll) + { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; } + removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); + } + return widget.height = widget.node.parentNode.offsetHeight + } + + // Return true when the given mouse event happened in a widget + function eventInWidget(display, e) { + for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { + if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || + (n.parentNode == display.sizer && n != display.mover)) + { return true } + } + } + + // POSITION MEASUREMENT + + function paddingTop(display) {return display.lineSpace.offsetTop} + function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight} + function paddingH(display) { + if (display.cachedPaddingH) { return display.cachedPaddingH } + var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like")); + var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; + var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; + if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; } + return data + } + + function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth } + function displayWidth(cm) { + return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth + } + function displayHeight(cm) { + return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight + } + + // Ensure the lineView.wrapping.heights array is populated. This is + // an array of bottom offsets for the lines that make up a drawn + // line. When lineWrapping is on, there might be more than one + // height. + function ensureLineHeights(cm, lineView, rect) { + var wrapping = cm.options.lineWrapping; + var curWidth = wrapping && displayWidth(cm); + if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { + var heights = lineView.measure.heights = []; + if (wrapping) { + lineView.measure.width = curWidth; + var rects = lineView.text.firstChild.getClientRects(); + for (var i = 0; i < rects.length - 1; i++) { + var cur = rects[i], next = rects[i + 1]; + if (Math.abs(cur.bottom - next.bottom) > 2) + { heights.push((cur.bottom + next.top) / 2 - rect.top); } + } + } + heights.push(rect.bottom - rect.top); + } + } + + // Find a line map (mapping character offsets to text nodes) and a + // measurement cache for the given line number. (A line view might + // contain multiple lines when collapsed ranges are present.) + function mapFromLineView(lineView, line, lineN) { + if (lineView.line == line) + { return {map: lineView.measure.map, cache: lineView.measure.cache} } + for (var i = 0; i < lineView.rest.length; i++) + { if (lineView.rest[i] == line) + { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } } + for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) + { if (lineNo(lineView.rest[i$1]) > lineN) + { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } } + } + + // Render a line into the hidden node display.externalMeasured. Used + // when measurement is needed for a line that's not in the viewport. + function updateExternalMeasurement(cm, line) { + line = visualLine(line); + var lineN = lineNo(line); + var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); + view.lineN = lineN; + var built = view.built = buildLineContent(cm, view); + view.text = built.pre; + removeChildrenAndAdd(cm.display.lineMeasure, built.pre); + return view + } + + // Get a {top, bottom, left, right} box (in line-local coordinates) + // for a given character. + function measureChar(cm, line, ch, bias) { + return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias) + } + + // Find a line view that corresponds to the given line number. + function findViewForLine(cm, lineN) { + if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) + { return cm.display.view[findViewIndex(cm, lineN)] } + var ext = cm.display.externalMeasured; + if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) + { return ext } + } + + // Measurement can be split in two steps, the set-up work that + // applies to the whole line, and the measurement of the actual + // character. Functions like coordsChar, that need to do a lot of + // measurements in a row, can thus ensure that the set-up work is + // only done once. + function prepareMeasureForLine(cm, line) { + var lineN = lineNo(line); + var view = findViewForLine(cm, lineN); + if (view && !view.text) { + view = null; + } else if (view && view.changes) { + updateLineForChanges(cm, view, lineN, getDimensions(cm)); + cm.curOp.forceUpdate = true; + } + if (!view) + { view = updateExternalMeasurement(cm, line); } + + var info = mapFromLineView(view, line, lineN); + return { + line: line, view: view, rect: null, + map: info.map, cache: info.cache, before: info.before, + hasHeights: false + } + } + + // Given a prepared measurement object, measures the position of an + // actual character (or fetches it from the cache). + function measureCharPrepared(cm, prepared, ch, bias, varHeight) { + if (prepared.before) { ch = -1; } + var key = ch + (bias || ""), found; + if (prepared.cache.hasOwnProperty(key)) { + found = prepared.cache[key]; + } else { + if (!prepared.rect) + { prepared.rect = prepared.view.text.getBoundingClientRect(); } + if (!prepared.hasHeights) { + ensureLineHeights(cm, prepared.view, prepared.rect); + prepared.hasHeights = true; + } + found = measureCharInner(cm, prepared, ch, bias); + if (!found.bogus) { prepared.cache[key] = found; } + } + return {left: found.left, right: found.right, + top: varHeight ? found.rtop : found.top, + bottom: varHeight ? found.rbottom : found.bottom} + } + + var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; + + function nodeAndOffsetInLineMap(map$$1, ch, bias) { + var node, start, end, collapse, mStart, mEnd; + // First, search the line map for the text node corresponding to, + // or closest to, the target character. + for (var i = 0; i < map$$1.length; i += 3) { + mStart = map$$1[i]; + mEnd = map$$1[i + 1]; + if (ch < mStart) { + start = 0; end = 1; + collapse = "left"; + } else if (ch < mEnd) { + start = ch - mStart; + end = start + 1; + } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) { + end = mEnd - mStart; + start = end - 1; + if (ch >= mEnd) { collapse = "right"; } + } + if (start != null) { + node = map$$1[i + 2]; + if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) + { collapse = bias; } + if (bias == "left" && start == 0) + { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) { + node = map$$1[(i -= 3) + 2]; + collapse = "left"; + } } + if (bias == "right" && start == mEnd - mStart) + { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) { + node = map$$1[(i += 3) + 2]; + collapse = "right"; + } } + break + } + } + return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd} + } + + function getUsefulRect(rects, bias) { + var rect = nullRect; + if (bias == "left") { for (var i = 0; i < rects.length; i++) { + if ((rect = rects[i]).left != rect.right) { break } + } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) { + if ((rect = rects[i$1]).left != rect.right) { break } + } } + return rect + } + + function measureCharInner(cm, prepared, ch, bias) { + var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); + var node = place.node, start = place.start, end = place.end, collapse = place.collapse; + + var rect; + if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. + for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned + while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; } + while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; } + if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) + { rect = node.parentNode.getBoundingClientRect(); } + else + { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); } + if (rect.left || rect.right || start == 0) { break } + end = start; + start = start - 1; + collapse = "right"; + } + if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); } + } else { // If it is a widget, simply get the box for the whole widget. + if (start > 0) { collapse = bias = "right"; } + var rects; + if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) + { rect = rects[bias == "right" ? rects.length - 1 : 0]; } + else + { rect = node.getBoundingClientRect(); } + } + if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { + var rSpan = node.parentNode.getClientRects()[0]; + if (rSpan) + { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; } + else + { rect = nullRect; } + } + + var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; + var mid = (rtop + rbot) / 2; + var heights = prepared.view.measure.heights; + var i = 0; + for (; i < heights.length - 1; i++) + { if (mid < heights[i]) { break } } + var top = i ? heights[i - 1] : 0, bot = heights[i]; + var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, + right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, + top: top, bottom: bot}; + if (!rect.left && !rect.right) { result.bogus = true; } + if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } + + return result + } + + // Work around problem with bounding client rects on ranges being + // returned incorrectly when zoomed on IE10 and below. + function maybeUpdateRectForZooming(measure, rect) { + if (!window.screen || screen.logicalXDPI == null || + screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) + { return rect } + var scaleX = screen.logicalXDPI / screen.deviceXDPI; + var scaleY = screen.logicalYDPI / screen.deviceYDPI; + return {left: rect.left * scaleX, right: rect.right * scaleX, + top: rect.top * scaleY, bottom: rect.bottom * scaleY} + } + + function clearLineMeasurementCacheFor(lineView) { + if (lineView.measure) { + lineView.measure.cache = {}; + lineView.measure.heights = null; + if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) + { lineView.measure.caches[i] = {}; } } + } + } + + function clearLineMeasurementCache(cm) { + cm.display.externalMeasure = null; + removeChildren(cm.display.lineMeasure); + for (var i = 0; i < cm.display.view.length; i++) + { clearLineMeasurementCacheFor(cm.display.view[i]); } + } + + function clearCaches(cm) { + clearLineMeasurementCache(cm); + cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; + if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; } + cm.display.lineNumChars = null; + } + + function pageScrollX() { + // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206 + // which causes page_Offset and bounding client rects to use + // different reference viewports and invalidate our calculations. + if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) } + return window.pageXOffset || (document.documentElement || document.body).scrollLeft + } + function pageScrollY() { + if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) } + return window.pageYOffset || (document.documentElement || document.body).scrollTop + } + + function widgetTopHeight(lineObj) { + var height = 0; + if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) + { height += widgetHeight(lineObj.widgets[i]); } } } + return height + } + + // Converts a {top, bottom, left, right} box from line-local + // coordinates into another coordinate system. Context may be one of + // "line", "div" (display.lineDiv), "local"./null (editor), "window", + // or "page". + function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { + if (!includeWidgets) { + var height = widgetTopHeight(lineObj); + rect.top += height; rect.bottom += height; + } + if (context == "line") { return rect } + if (!context) { context = "local"; } + var yOff = heightAtLine(lineObj); + if (context == "local") { yOff += paddingTop(cm.display); } + else { yOff -= cm.display.viewOffset; } + if (context == "page" || context == "window") { + var lOff = cm.display.lineSpace.getBoundingClientRect(); + yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); + var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); + rect.left += xOff; rect.right += xOff; + } + rect.top += yOff; rect.bottom += yOff; + return rect + } + + // Coverts a box from "div" coords to another coordinate system. + // Context may be "window", "page", "div", or "local"./null. + function fromCoordSystem(cm, coords, context) { + if (context == "div") { return coords } + var left = coords.left, top = coords.top; + // First move into "page" coordinate system + if (context == "page") { + left -= pageScrollX(); + top -= pageScrollY(); + } else if (context == "local" || !context) { + var localBox = cm.display.sizer.getBoundingClientRect(); + left += localBox.left; + top += localBox.top; + } + + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); + return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} + } + + function charCoords(cm, pos, context, lineObj, bias) { + if (!lineObj) { lineObj = getLine(cm.doc, pos.line); } + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context) + } + + // Returns a box for a given cursor position, which may have an + // 'other' property containing the position of the secondary cursor + // on a bidi boundary. + // A cursor Pos(line, char, "before") is on the same visual line as `char - 1` + // and after `char - 1` in writing order of `char - 1` + // A cursor Pos(line, char, "after") is on the same visual line as `char` + // and before `char` in writing order of `char` + // Examples (upper-case letters are RTL, lower-case are LTR): + // Pos(0, 1, ...) + // before after + // ab a|b a|b + // aB a|B aB| + // Ab |Ab A|b + // AB B|A B|A + // Every position after the last character on a line is considered to stick + // to the last character on the line. + function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { + lineObj = lineObj || getLine(cm.doc, pos.line); + if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } + function get(ch, right) { + var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); + if (right) { m.left = m.right; } else { m.right = m.left; } + return intoCoordSystem(cm, lineObj, m, context) + } + var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky; + if (ch >= lineObj.text.length) { + ch = lineObj.text.length; + sticky = "before"; + } else if (ch <= 0) { + ch = 0; + sticky = "after"; + } + if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") } + + function getBidi(ch, partPos, invert) { + var part = order[partPos], right = part.level == 1; + return get(invert ? ch - 1 : ch, right != invert) + } + var partPos = getBidiPartAt(order, ch, sticky); + var other = bidiOther; + var val = getBidi(ch, partPos, sticky == "before"); + if (other != null) { val.other = getBidi(ch, other, sticky != "before"); } + return val + } + + // Used to cheaply estimate the coordinates for a position. Used for + // intermediate scroll updates. + function estimateCoords(cm, pos) { + var left = 0; + pos = clipPos(cm.doc, pos); + if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; } + var lineObj = getLine(cm.doc, pos.line); + var top = heightAtLine(lineObj) + paddingTop(cm.display); + return {left: left, right: left, top: top, bottom: top + lineObj.height} + } + + // Positions returned by coordsChar contain some extra information. + // xRel is the relative x position of the input coordinates compared + // to the found position (so xRel > 0 means the coordinates are to + // the right of the character position, for example). When outside + // is true, that means the coordinates lie outside the line's + // vertical range. + function PosWithInfo(line, ch, sticky, outside, xRel) { + var pos = Pos(line, ch, sticky); + pos.xRel = xRel; + if (outside) { pos.outside = outside; } + return pos + } + + // Compute the character position closest to the given coordinates. + // Input must be lineSpace-local ("div" coordinate system). + function coordsChar(cm, x, y) { + var doc = cm.doc; + y += cm.display.viewOffset; + if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) } + var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; + if (lineN > last) + { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) } + if (x < 0) { x = 0; } + + var lineObj = getLine(doc, lineN); + for (;;) { + var found = coordsCharInner(cm, lineObj, lineN, x, y); + var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0)); + if (!collapsed) { return found } + var rangeEnd = collapsed.find(1); + if (rangeEnd.line == lineN) { return rangeEnd } + lineObj = getLine(doc, lineN = rangeEnd.line); + } + } + + function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { + y -= widgetTopHeight(lineObj); + var end = lineObj.text.length; + var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0); + end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end); + return {begin: begin, end: end} + } + + function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { + if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } + var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; + return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop) + } + + // Returns true if the given side of a box is after the given + // coordinates, in top-to-bottom, left-to-right order. + function boxIsAfter(box, x, y, left) { + return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x + } + + function coordsCharInner(cm, lineObj, lineNo$$1, x, y) { + // Move y into line-local coordinate space + y -= heightAtLine(lineObj); + var preparedMeasure = prepareMeasureForLine(cm, lineObj); + // When directly calling `measureCharPrepared`, we have to adjust + // for the widgets at this line. + var widgetHeight$$1 = widgetTopHeight(lineObj); + var begin = 0, end = lineObj.text.length, ltr = true; + + var order = getOrder(lineObj, cm.doc.direction); + // If the line isn't plain left-to-right text, first figure out + // which bidi section the coordinates fall into. + if (order) { + var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart) + (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y); + ltr = part.level != 1; + // The awkward -1 offsets are needed because findFirst (called + // on these below) will treat its first bound as inclusive, + // second as exclusive, but we want to actually address the + // characters in the part's range + begin = ltr ? part.from : part.to - 1; + end = ltr ? part.to : part.from - 1; + } + + // A binary search to find the first character whose bounding box + // starts after the coordinates. If we run across any whose box wrap + // the coordinates, store that. + var chAround = null, boxAround = null; + var ch = findFirst(function (ch) { + var box = measureCharPrepared(cm, preparedMeasure, ch); + box.top += widgetHeight$$1; box.bottom += widgetHeight$$1; + if (!boxIsAfter(box, x, y, false)) { return false } + if (box.top <= y && box.left <= x) { + chAround = ch; + boxAround = box; + } + return true + }, begin, end); + + var baseX, sticky, outside = false; + // If a box around the coordinates was found, use that + if (boxAround) { + // Distinguish coordinates nearer to the left or right side of the box + var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr; + ch = chAround + (atStart ? 0 : 1); + sticky = atStart ? "after" : "before"; + baseX = atLeft ? boxAround.left : boxAround.right; + } else { + // (Adjust for extended bound, if necessary.) + if (!ltr && (ch == end || ch == begin)) { ch++; } + // To determine which side to associate with, get the box to the + // left of the character and compare it's vertical position to the + // coordinates + sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : + (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ? + "after" : "before"; + // Now get accurate coordinates for this place, in order to get a + // base X position + var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure); + baseX = coords.left; + outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0; + } + + ch = skipExtendingChars(lineObj.text, ch, 1); + return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX) + } + + function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) { + // Bidi parts are sorted left-to-right, and in a non-line-wrapping + // situation, we can take this ordering to correspond to the visual + // ordering. This finds the first part whose end is after the given + // coordinates. + var index = findFirst(function (i) { + var part = order[i], ltr = part.level != 1; + return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"), + "line", lineObj, preparedMeasure), x, y, true) + }, 0, order.length - 1); + var part = order[index]; + // If this isn't the first part, the part's start is also after + // the coordinates, and the coordinates aren't on the same line as + // that start, move one part back. + if (index > 0) { + var ltr = part.level != 1; + var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"), + "line", lineObj, preparedMeasure); + if (boxIsAfter(start, x, y, true) && start.top > y) + { part = order[index - 1]; } + } + return part + } + + function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { + // In a wrapped line, rtl text on wrapping boundaries can do things + // that don't correspond to the ordering in our `order` array at + // all, so a binary search doesn't work, and we want to return a + // part that only spans one line so that the binary search in + // coordsCharInner is safe. As such, we first find the extent of the + // wrapped line, and then do a flat search in which we discard any + // spans that aren't on the line. + var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); + var begin = ref.begin; + var end = ref.end; + if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; } + var part = null, closestDist = null; + for (var i = 0; i < order.length; i++) { + var p = order[i]; + if (p.from >= end || p.to <= begin) { continue } + var ltr = p.level != 1; + var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right; + // Weigh against spans ending before this, so that they are only + // picked if nothing ends after + var dist = endX < x ? x - endX + 1e9 : endX - x; + if (!part || closestDist > dist) { + part = p; + closestDist = dist; + } + } + if (!part) { part = order[order.length - 1]; } + // Clip the part to the wrapped line. + if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; } + if (part.to > end) { part = {from: part.from, to: end, level: part.level}; } + return part + } + + var measureText; + // Compute the default text height. + function textHeight(display) { + if (display.cachedTextHeight != null) { return display.cachedTextHeight } + if (measureText == null) { + measureText = elt("pre", null, "CodeMirror-line-like"); + // Measure a bunch of lines, for browsers that compute + // fractional heights. + for (var i = 0; i < 49; ++i) { + measureText.appendChild(document.createTextNode("x")); + measureText.appendChild(elt("br")); + } + measureText.appendChild(document.createTextNode("x")); + } + removeChildrenAndAdd(display.measure, measureText); + var height = measureText.offsetHeight / 50; + if (height > 3) { display.cachedTextHeight = height; } + removeChildren(display.measure); + return height || 1 + } + + // Compute the default character width. + function charWidth(display) { + if (display.cachedCharWidth != null) { return display.cachedCharWidth } + var anchor = elt("span", "xxxxxxxxxx"); + var pre = elt("pre", [anchor], "CodeMirror-line-like"); + removeChildrenAndAdd(display.measure, pre); + var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; + if (width > 2) { display.cachedCharWidth = width; } + return width || 10 + } + + // Do a bulk-read of the DOM positions and sizes needed to draw the + // view, so that we don't interleave reading and writing to the DOM. + function getDimensions(cm) { + var d = cm.display, left = {}, width = {}; + var gutterLeft = d.gutters.clientLeft; + for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { + var id = cm.display.gutterSpecs[i].className; + left[id] = n.offsetLeft + n.clientLeft + gutterLeft; + width[id] = n.clientWidth; + } + return {fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth} + } + + // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, + // but using getBoundingClientRect to get a sub-pixel-accurate + // result. + function compensateForHScroll(display) { + return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left + } + + // Returns a function that estimates the height of a line, to use as + // first approximation until the line becomes visible (and is thus + // properly measurable). + function estimateHeight(cm) { + var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; + var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); + return function (line) { + if (lineIsHidden(cm.doc, line)) { return 0 } + + var widgetsHeight = 0; + if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { + if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; } + } } + + if (wrapping) + { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th } + else + { return widgetsHeight + th } + } + } + + function estimateLineHeights(cm) { + var doc = cm.doc, est = estimateHeight(cm); + doc.iter(function (line) { + var estHeight = est(line); + if (estHeight != line.height) { updateLineHeight(line, estHeight); } + }); + } + + // Given a mouse event, find the corresponding position. If liberal + // is false, it checks whether a gutter or scrollbar was clicked, + // and returns null if it was. forRect is used by rectangular + // selections, and tries to estimate a character position even for + // coordinates beyond the right of the text. + function posFromMouse(cm, e, liberal, forRect) { + var display = cm.display; + if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null } + + var x, y, space = display.lineSpace.getBoundingClientRect(); + // Fails unpredictably on IE[67] when mouse is dragged around quickly. + try { x = e.clientX - space.left; y = e.clientY - space.top; } + catch (e) { return null } + var coords = coordsChar(cm, x, y), line; + if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { + var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; + coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); + } + return coords + } + + // Find the view element corresponding to a given line. Return null + // when the line isn't visible. + function findViewIndex(cm, n) { + if (n >= cm.display.viewTo) { return null } + n -= cm.display.viewFrom; + if (n < 0) { return null } + var view = cm.display.view; + for (var i = 0; i < view.length; i++) { + n -= view[i].size; + if (n < 0) { return i } + } + } + + // Updates the display.view data structure for a given change to the + // document. From and to are in pre-change coordinates. Lendiff is + // the amount of lines added or subtracted by the change. This is + // used for changes that span multiple lines, or change the way + // lines are divided into visual lines. regLineChange (below) + // registers single-line changes. + function regChange(cm, from, to, lendiff) { + if (from == null) { from = cm.doc.first; } + if (to == null) { to = cm.doc.first + cm.doc.size; } + if (!lendiff) { lendiff = 0; } + + var display = cm.display; + if (lendiff && to < display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers > from)) + { display.updateLineNumbers = from; } + + cm.curOp.viewChanged = true; + + if (from >= display.viewTo) { // Change after + if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) + { resetView(cm); } + } else if (to <= display.viewFrom) { // Change before + if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { + resetView(cm); + } else { + display.viewFrom += lendiff; + display.viewTo += lendiff; + } + } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap + resetView(cm); + } else if (from <= display.viewFrom) { // Top overlap + var cut = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cut) { + display.view = display.view.slice(cut.index); + display.viewFrom = cut.lineN; + display.viewTo += lendiff; + } else { + resetView(cm); + } + } else if (to >= display.viewTo) { // Bottom overlap + var cut$1 = viewCuttingPoint(cm, from, from, -1); + if (cut$1) { + display.view = display.view.slice(0, cut$1.index); + display.viewTo = cut$1.lineN; + } else { + resetView(cm); + } + } else { // Gap in the middle + var cutTop = viewCuttingPoint(cm, from, from, -1); + var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cutTop && cutBot) { + display.view = display.view.slice(0, cutTop.index) + .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) + .concat(display.view.slice(cutBot.index)); + display.viewTo += lendiff; + } else { + resetView(cm); + } + } + + var ext = display.externalMeasured; + if (ext) { + if (to < ext.lineN) + { ext.lineN += lendiff; } + else if (from < ext.lineN + ext.size) + { display.externalMeasured = null; } + } + } + + // Register a change to a single line. Type must be one of "text", + // "gutter", "class", "widget" + function regLineChange(cm, line, type) { + cm.curOp.viewChanged = true; + var display = cm.display, ext = cm.display.externalMeasured; + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) + { display.externalMeasured = null; } + + if (line < display.viewFrom || line >= display.viewTo) { return } + var lineView = display.view[findViewIndex(cm, line)]; + if (lineView.node == null) { return } + var arr = lineView.changes || (lineView.changes = []); + if (indexOf(arr, type) == -1) { arr.push(type); } + } + + // Clear the view. + function resetView(cm) { + cm.display.viewFrom = cm.display.viewTo = cm.doc.first; + cm.display.view = []; + cm.display.viewOffset = 0; + } + + function viewCuttingPoint(cm, oldN, newN, dir) { + var index = findViewIndex(cm, oldN), diff, view = cm.display.view; + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) + { return {index: index, lineN: newN} } + var n = cm.display.viewFrom; + for (var i = 0; i < index; i++) + { n += view[i].size; } + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) { return null } + diff = (n + view[index].size) - oldN; + index++; + } else { + diff = n - oldN; + } + oldN += diff; newN += diff; + } + while (visualLineNo(cm.doc, newN) != newN) { + if (index == (dir < 0 ? 0 : view.length - 1)) { return null } + newN += dir * view[index - (dir < 0 ? 1 : 0)].size; + index += dir; + } + return {index: index, lineN: newN} + } + + // Force the view to cover a given range, adding empty view element + // or clipping off existing ones as needed. + function adjustView(cm, from, to) { + var display = cm.display, view = display.view; + if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { + display.view = buildViewArray(cm, from, to); + display.viewFrom = from; + } else { + if (display.viewFrom > from) + { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); } + else if (display.viewFrom < from) + { display.view = display.view.slice(findViewIndex(cm, from)); } + display.viewFrom = from; + if (display.viewTo < to) + { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); } + else if (display.viewTo > to) + { display.view = display.view.slice(0, findViewIndex(cm, to)); } + } + display.viewTo = to; + } + + // Count the number of lines in the view whose DOM representation is + // out of date (or nonexistent). + function countDirtyView(cm) { + var view = cm.display.view, dirty = 0; + for (var i = 0; i < view.length; i++) { + var lineView = view[i]; + if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; } + } + return dirty + } + + function updateSelection(cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()); + } + + function prepareSelection(cm, primary) { + if ( primary === void 0 ) primary = true; + + var doc = cm.doc, result = {}; + var curFragment = result.cursors = document.createDocumentFragment(); + var selFragment = result.selection = document.createDocumentFragment(); + + for (var i = 0; i < doc.sel.ranges.length; i++) { + if (!primary && i == doc.sel.primIndex) { continue } + var range$$1 = doc.sel.ranges[i]; + if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue } + var collapsed = range$$1.empty(); + if (collapsed || cm.options.showCursorWhenSelecting) + { drawSelectionCursor(cm, range$$1.head, curFragment); } + if (!collapsed) + { drawSelectionRange(cm, range$$1, selFragment); } + } + return result + } + + // Draws a cursor for the given range + function drawSelectionCursor(cm, head, output) { + var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); + + var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); + cursor.style.left = pos.left + "px"; + cursor.style.top = pos.top + "px"; + cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; + + if (pos.other) { + // Secondary cursor, shown when on a 'jump' in bi-directional text + var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); + otherCursor.style.display = ""; + otherCursor.style.left = pos.other.left + "px"; + otherCursor.style.top = pos.other.top + "px"; + otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; + } + } + + function cmpCoords(a, b) { return a.top - b.top || a.left - b.left } + + // Draws the given range as a highlighted selection + function drawSelectionRange(cm, range$$1, output) { + var display = cm.display, doc = cm.doc; + var fragment = document.createDocumentFragment(); + var padding = paddingH(cm.display), leftSide = padding.left; + var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; + var docLTR = doc.direction == "ltr"; + + function add(left, top, width, bottom) { + if (top < 0) { top = 0; } + top = Math.round(top); + bottom = Math.round(bottom); + fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px"))); + } + + function drawForLine(line, fromArg, toArg) { + var lineObj = getLine(doc, line); + var lineLen = lineObj.text.length; + var start, end; + function coords(ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias) + } + + function wrapX(pos, dir, side) { + var extent = wrappedLineExtentChar(cm, lineObj, null, pos); + var prop = (dir == "ltr") == (side == "after") ? "left" : "right"; + var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1); + return coords(ch, prop)[prop] + } + + var order = getOrder(lineObj, doc.direction); + iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) { + var ltr = dir == "ltr"; + var fromPos = coords(from, ltr ? "left" : "right"); + var toPos = coords(to - 1, ltr ? "right" : "left"); + + var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen; + var first = i == 0, last = !order || i == order.length - 1; + if (toPos.top - fromPos.top <= 3) { // Single line + var openLeft = (docLTR ? openStart : openEnd) && first; + var openRight = (docLTR ? openEnd : openStart) && last; + var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left; + var right = openRight ? rightSide : (ltr ? toPos : fromPos).right; + add(left, fromPos.top, right - left, fromPos.bottom); + } else { // Multiple lines + var topLeft, topRight, botLeft, botRight; + if (ltr) { + topLeft = docLTR && openStart && first ? leftSide : fromPos.left; + topRight = docLTR ? rightSide : wrapX(from, dir, "before"); + botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); + botRight = docLTR && openEnd && last ? rightSide : toPos.right; + } else { + topLeft = !docLTR ? leftSide : wrapX(from, dir, "before"); + topRight = !docLTR && openStart && first ? rightSide : fromPos.right; + botLeft = !docLTR && openEnd && last ? leftSide : toPos.left; + botRight = !docLTR ? rightSide : wrapX(to, dir, "after"); + } + add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom); + if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); } + add(botLeft, toPos.top, botRight - botLeft, toPos.bottom); + } + + if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; } + if (cmpCoords(toPos, start) < 0) { start = toPos; } + if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; } + if (cmpCoords(toPos, end) < 0) { end = toPos; } + }); + return {start: start, end: end} + } + + var sFrom = range$$1.from(), sTo = range$$1.to(); + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch); + } else { + var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); + var singleVLine = visualLine(fromLine) == visualLine(toLine); + var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; + var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); + add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); + } + } + if (leftEnd.bottom < rightStart.top) + { add(leftSide, leftEnd.bottom, null, rightStart.top); } + } + + output.appendChild(fragment); + } + + // Cursor-blinking + function restartBlink(cm) { + if (!cm.state.focused) { return } + var display = cm.display; + clearInterval(display.blinker); + var on = true; + display.cursorDiv.style.visibility = ""; + if (cm.options.cursorBlinkRate > 0) + { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; }, + cm.options.cursorBlinkRate); } + else if (cm.options.cursorBlinkRate < 0) + { display.cursorDiv.style.visibility = "hidden"; } + } + + function ensureFocus(cm) { + if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } + } + + function delayBlurEvent(cm) { + cm.state.delayingBlurEvent = true; + setTimeout(function () { if (cm.state.delayingBlurEvent) { + cm.state.delayingBlurEvent = false; + onBlur(cm); + } }, 100); + } + + function onFocus(cm, e) { + if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; } + + if (cm.options.readOnly == "nocursor") { return } + if (!cm.state.focused) { + signal(cm, "focus", cm, e); + cm.state.focused = true; + addClass(cm.display.wrapper, "CodeMirror-focused"); + // This test prevents this from firing when a context + // menu is closed (since the input reset would kill the + // select-all detection hack) + if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { + cm.display.input.reset(); + if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730 + } + cm.display.input.receivedFocus(); + } + restartBlink(cm); + } + function onBlur(cm, e) { + if (cm.state.delayingBlurEvent) { return } + + if (cm.state.focused) { + signal(cm, "blur", cm, e); + cm.state.focused = false; + rmClass(cm.display.wrapper, "CodeMirror-focused"); + } + clearInterval(cm.display.blinker); + setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150); + } + + // Read the actual heights of the rendered lines, and update their + // stored heights to match. + function updateHeightsInViewport(cm) { + var display = cm.display; + var prevBottom = display.lineDiv.offsetTop; + for (var i = 0; i < display.view.length; i++) { + var cur = display.view[i], wrapping = cm.options.lineWrapping; + var height = (void 0), width = 0; + if (cur.hidden) { continue } + if (ie && ie_version < 8) { + var bot = cur.node.offsetTop + cur.node.offsetHeight; + height = bot - prevBottom; + prevBottom = bot; + } else { + var box = cur.node.getBoundingClientRect(); + height = box.bottom - box.top; + // Check that lines don't extend past the right of the current + // editor width + if (!wrapping && cur.text.firstChild) + { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; } + } + var diff = cur.line.height - height; + if (diff > .005 || diff < -.005) { + updateLineHeight(cur.line, height); + updateWidgetHeight(cur.line); + if (cur.rest) { for (var j = 0; j < cur.rest.length; j++) + { updateWidgetHeight(cur.rest[j]); } } + } + if (width > cm.display.sizerWidth) { + var chWidth = Math.ceil(width / charWidth(cm.display)); + if (chWidth > cm.display.maxLineLength) { + cm.display.maxLineLength = chWidth; + cm.display.maxLine = cur.line; + cm.display.maxLineChanged = true; + } + } + } + } + + // Read and store the height of line widgets associated with the + // given line. + function updateWidgetHeight(line) { + if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) { + var w = line.widgets[i], parent = w.node.parentNode; + if (parent) { w.height = parent.offsetHeight; } + } } + } + + // Compute the lines that are visible in a given viewport (defaults + // the the current scroll position). viewport may contain top, + // height, and ensure (see op.scrollToPos) properties. + function visibleLines(display, doc, viewport) { + var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; + top = Math.floor(top - paddingTop(display)); + var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; + + var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); + // Ensure is a {from: {line, ch}, to: {line, ch}} object, and + // forces those lines into the viewport (if possible). + if (viewport && viewport.ensure) { + var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; + if (ensureFrom < from) { + from = ensureFrom; + to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); + } else if (Math.min(ensureTo, doc.lastLine()) >= to) { + from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); + to = ensureTo; + } + } + return {from: from, to: Math.max(to, from + 1)} + } + + // SCROLLING THINGS INTO VIEW + + // If an editor sits on the top or bottom of the window, partially + // scrolled out of view, this ensures that the cursor is visible. + function maybeScrollWindow(cm, rect) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) { return } + + var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; + if (rect.top + box.top < 0) { doScroll = true; } + else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; } + if (doScroll != null && !phantom) { + var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;")); + cm.display.lineSpace.appendChild(scrollNode); + scrollNode.scrollIntoView(doScroll); + cm.display.lineSpace.removeChild(scrollNode); + } + } + + // Scroll a given position into view (immediately), verifying that + // it actually became visible (as line heights are accurately + // measured, the position of something may 'drift' during drawing). + function scrollPosIntoView(cm, pos, end, margin) { + if (margin == null) { margin = 0; } + var rect; + if (!cm.options.lineWrapping && pos == end) { + // Set pos and end to the cursor positions around the character pos sticks to + // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch + // If pos == Pos(_, 0, "before"), pos and end are unchanged + pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos; + end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos; + } + for (var limit = 0; limit < 5; limit++) { + var changed = false; + var coords = cursorCoords(cm, pos); + var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); + rect = {left: Math.min(coords.left, endCoords.left), + top: Math.min(coords.top, endCoords.top) - margin, + right: Math.max(coords.left, endCoords.left), + bottom: Math.max(coords.bottom, endCoords.bottom) + margin}; + var scrollPos = calculateScrollPos(cm, rect); + var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; + if (scrollPos.scrollTop != null) { + updateScrollTop(cm, scrollPos.scrollTop); + if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; } + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; } + } + if (!changed) { break } + } + return rect + } + + // Scroll a given set of coordinates into view (immediately). + function scrollIntoView(cm, rect) { + var scrollPos = calculateScrollPos(cm, rect); + if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); } + if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); } + } + + // Calculate a new scroll position needed to scroll the given + // rectangle into view. Returns an object with scrollTop and + // scrollLeft properties. When these are undefined, the + // vertical/horizontal position does not need to be adjusted. + function calculateScrollPos(cm, rect) { + var display = cm.display, snapMargin = textHeight(cm.display); + if (rect.top < 0) { rect.top = 0; } + var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; + var screen = displayHeight(cm), result = {}; + if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; } + var docBottom = cm.doc.height + paddingVert(display); + var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin; + if (rect.top < screentop) { + result.scrollTop = atTop ? 0 : rect.top; + } else if (rect.bottom > screentop + screen) { + var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen); + if (newTop != screentop) { result.scrollTop = newTop; } + } + + var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; + var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); + var tooWide = rect.right - rect.left > screenw; + if (tooWide) { rect.right = rect.left + screenw; } + if (rect.left < 10) + { result.scrollLeft = 0; } + else if (rect.left < screenleft) + { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); } + else if (rect.right > screenw + screenleft - 3) + { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; } + return result + } + + // Store a relative adjustment to the scroll position in the current + // operation (to be applied when the operation finishes). + function addToScrollTop(cm, top) { + if (top == null) { return } + resolveScrollToPos(cm); + cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; + } + + // Make sure that at the end of the operation the current cursor is + // shown. + function ensureCursorVisible(cm) { + resolveScrollToPos(cm); + var cur = cm.getCursor(); + cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin}; + } + + function scrollToCoords(cm, x, y) { + if (x != null || y != null) { resolveScrollToPos(cm); } + if (x != null) { cm.curOp.scrollLeft = x; } + if (y != null) { cm.curOp.scrollTop = y; } + } + + function scrollToRange(cm, range$$1) { + resolveScrollToPos(cm); + cm.curOp.scrollToPos = range$$1; + } + + // When an operation has its scrollToPos property set, and another + // scroll action is applied before the end of the operation, this + // 'simulates' scrolling that position into view in a cheap way, so + // that the effect of intermediate scroll commands is not ignored. + function resolveScrollToPos(cm) { + var range$$1 = cm.curOp.scrollToPos; + if (range$$1) { + cm.curOp.scrollToPos = null; + var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to); + scrollToCoordsRange(cm, from, to, range$$1.margin); + } + } + + function scrollToCoordsRange(cm, from, to, margin) { + var sPos = calculateScrollPos(cm, { + left: Math.min(from.left, to.left), + top: Math.min(from.top, to.top) - margin, + right: Math.max(from.right, to.right), + bottom: Math.max(from.bottom, to.bottom) + margin + }); + scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); + } + + // Sync the scrollable area and scrollbars, ensure the viewport + // covers the visible area. + function updateScrollTop(cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) { return } + if (!gecko) { updateDisplaySimple(cm, {top: val}); } + setScrollTop(cm, val, true); + if (gecko) { updateDisplaySimple(cm); } + startWorker(cm, 100); + } + + function setScrollTop(cm, val, forceScroll) { + val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val); + if (cm.display.scroller.scrollTop == val && !forceScroll) { return } + cm.doc.scrollTop = val; + cm.display.scrollbars.setScrollTop(val); + if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; } + } + + // Sync scroller and scrollbar, ensure the gutter elements are + // aligned. + function setScrollLeft(cm, val, isScroller, forceScroll) { + val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); + if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return } + cm.doc.scrollLeft = val; + alignHorizontally(cm); + if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; } + cm.display.scrollbars.setScrollLeft(val); + } + + // SCROLLBARS + + // Prepare DOM reads needed to update the scrollbars. Done in one + // shot to minimize update/measure roundtrips. + function measureForScrollbars(cm) { + var d = cm.display, gutterW = d.gutters.offsetWidth; + var docH = Math.round(cm.doc.height + paddingVert(cm.display)); + return { + clientHeight: d.scroller.clientHeight, + viewHeight: d.wrapper.clientHeight, + scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, + viewWidth: d.wrapper.clientWidth, + barLeft: cm.options.fixedGutter ? gutterW : 0, + docHeight: docH, + scrollHeight: docH + scrollGap(cm) + d.barHeight, + nativeBarWidth: d.nativeBarWidth, + gutterWidth: gutterW + } + } + + var NativeScrollbars = function(place, scroll, cm) { + this.cm = cm; + var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); + var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); + vert.tabIndex = horiz.tabIndex = -1; + place(vert); place(horiz); + + on(vert, "scroll", function () { + if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); } + }); + on(horiz, "scroll", function () { + if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); } + }); + + this.checkedZeroWidth = false; + // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). + if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; } + }; + + NativeScrollbars.prototype.update = function (measure) { + var needsH = measure.scrollWidth > measure.clientWidth + 1; + var needsV = measure.scrollHeight > measure.clientHeight + 1; + var sWidth = measure.nativeBarWidth; + + if (needsV) { + this.vert.style.display = "block"; + this.vert.style.bottom = needsH ? sWidth + "px" : "0"; + var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); + // A bug in IE8 can cause this value to be negative, so guard it. + this.vert.firstChild.style.height = + Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; + } else { + this.vert.style.display = ""; + this.vert.firstChild.style.height = "0"; + } + + if (needsH) { + this.horiz.style.display = "block"; + this.horiz.style.right = needsV ? sWidth + "px" : "0"; + this.horiz.style.left = measure.barLeft + "px"; + var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); + this.horiz.firstChild.style.width = + Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; + } else { + this.horiz.style.display = ""; + this.horiz.firstChild.style.width = "0"; + } + + if (!this.checkedZeroWidth && measure.clientHeight > 0) { + if (sWidth == 0) { this.zeroWidthHack(); } + this.checkedZeroWidth = true; + } + + return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} + }; + + NativeScrollbars.prototype.setScrollLeft = function (pos) { + if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; } + if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); } + }; + + NativeScrollbars.prototype.setScrollTop = function (pos) { + if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; } + if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); } + }; + + NativeScrollbars.prototype.zeroWidthHack = function () { + var w = mac && !mac_geMountainLion ? "12px" : "18px"; + this.horiz.style.height = this.vert.style.width = w; + this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; + this.disableHoriz = new Delayed; + this.disableVert = new Delayed; + }; + + NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { + bar.style.pointerEvents = "auto"; + function maybeDisable() { + // To find out whether the scrollbar is still visible, we + // check whether the element under the pixel in the bottom + // right corner of the scrollbar box is the scrollbar box + // itself (when the bar is still visible) or its filler child + // (when the bar is hidden). If it is still visible, we keep + // it enabled, if it's hidden, we disable pointer events. + var box = bar.getBoundingClientRect(); + var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) + : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); + if (elt$$1 != bar) { bar.style.pointerEvents = "none"; } + else { delay.set(1000, maybeDisable); } + } + delay.set(1000, maybeDisable); + }; + + NativeScrollbars.prototype.clear = function () { + var parent = this.horiz.parentNode; + parent.removeChild(this.horiz); + parent.removeChild(this.vert); + }; + + var NullScrollbars = function () {}; + + NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} }; + NullScrollbars.prototype.setScrollLeft = function () {}; + NullScrollbars.prototype.setScrollTop = function () {}; + NullScrollbars.prototype.clear = function () {}; + + function updateScrollbars(cm, measure) { + if (!measure) { measure = measureForScrollbars(cm); } + var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; + updateScrollbarsInner(cm, measure); + for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { + if (startWidth != cm.display.barWidth && cm.options.lineWrapping) + { updateHeightsInViewport(cm); } + updateScrollbarsInner(cm, measureForScrollbars(cm)); + startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; + } + } + + // Re-synchronize the fake scrollbars with the actual size of the + // content. + function updateScrollbarsInner(cm, measure) { + var d = cm.display; + var sizes = d.scrollbars.update(measure); + + d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; + d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; + d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; + + if (sizes.right && sizes.bottom) { + d.scrollbarFiller.style.display = "block"; + d.scrollbarFiller.style.height = sizes.bottom + "px"; + d.scrollbarFiller.style.width = sizes.right + "px"; + } else { d.scrollbarFiller.style.display = ""; } + if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { + d.gutterFiller.style.display = "block"; + d.gutterFiller.style.height = sizes.bottom + "px"; + d.gutterFiller.style.width = measure.gutterWidth + "px"; + } else { d.gutterFiller.style.display = ""; } + } + + var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; + + function initScrollbars(cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear(); + if (cm.display.scrollbars.addClass) + { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); } + } + + cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { + cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); + // Prevent clicks in the scrollbars from killing focus + on(node, "mousedown", function () { + if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); } + }); + node.setAttribute("cm-not-content", "true"); + }, function (pos, axis) { + if (axis == "horizontal") { setScrollLeft(cm, pos); } + else { updateScrollTop(cm, pos); } + }, cm); + if (cm.display.scrollbars.addClass) + { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); } + } + + // Operations are used to wrap a series of changes to the editor + // state in such a way that each change won't have to update the + // cursor and display (which would be awkward, slow, and + // error-prone). Instead, display updates are batched and then all + // combined and executed at once. + + var nextOpId = 0; + // Start a new operation. + function startOperation(cm) { + cm.curOp = { + cm: cm, + viewChanged: false, // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, // Used to detect need to update scrollbar + forceUpdate: false, // Used to force a redraw + updateInput: 0, // Whether to reset the input textarea + typing: false, // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, // Accumulated changes, for firing change events + cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already + selectionChanged: false, // Whether the selection needs to be redrawn + updateMaxLine: false, // Set when the widest line needs to be determined anew + scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, // Used to scroll to a specific position + focus: false, + id: ++nextOpId // Unique ID + }; + pushOperation(cm.curOp); + } + + // Finish an operation, updating the display and signalling delayed events + function endOperation(cm) { + var op = cm.curOp; + if (op) { finishOperation(op, function (group) { + for (var i = 0; i < group.ops.length; i++) + { group.ops[i].cm.curOp = null; } + endOperations(group); + }); } + } + + // The DOM updates done when an operation finishes are batched so + // that the minimum number of relayouts are required. + function endOperations(group) { + var ops = group.ops; + for (var i = 0; i < ops.length; i++) // Read DOM + { endOperation_R1(ops[i]); } + for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe) + { endOperation_W1(ops[i$1]); } + for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM + { endOperation_R2(ops[i$2]); } + for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe) + { endOperation_W2(ops[i$3]); } + for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM + { endOperation_finish(ops[i$4]); } + } + + function endOperation_R1(op) { + var cm = op.cm, display = cm.display; + maybeClipScrollbars(cm); + if (op.updateMaxLine) { findMaxLine(cm); } + + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || + op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || + op.scrollToPos.to.line >= display.viewTo) || + display.maxLineChanged && cm.options.lineWrapping; + op.update = op.mustUpdate && + new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); + } + + function endOperation_W1(op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); + } + + function endOperation_R2(op) { + var cm = op.cm, display = cm.display; + if (op.updatedDisplay) { updateHeightsInViewport(cm); } + + op.barMeasure = measureForScrollbars(cm); + + // If the max line changed since it was last measured, measure it, + // and ensure the document's width matches it. + // updateDisplay_W2 will use these properties to do the actual resizing + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; + cm.display.sizerWidth = op.adjustWidthTo; + op.barMeasure.scrollWidth = + Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); + op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); + } + + if (op.updatedDisplay || op.selectionChanged) + { op.preparedSelection = display.input.prepareSelection(); } + } + + function endOperation_W2(op) { + var cm = op.cm; + + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; + if (op.maxScrollLeft < cm.doc.scrollLeft) + { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); } + cm.display.maxLineChanged = false; + } + + var takeFocus = op.focus && op.focus == activeElt(); + if (op.preparedSelection) + { cm.display.input.showSelection(op.preparedSelection, takeFocus); } + if (op.updatedDisplay || op.startHeight != cm.doc.height) + { updateScrollbars(cm, op.barMeasure); } + if (op.updatedDisplay) + { setDocumentHeight(cm, op.barMeasure); } + + if (op.selectionChanged) { restartBlink(cm); } + + if (cm.state.focused && op.updateInput) + { cm.display.input.reset(op.typing); } + if (takeFocus) { ensureFocus(op.cm); } + } + + function endOperation_finish(op) { + var cm = op.cm, display = cm.display, doc = cm.doc; + + if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); } + + // Abort mouse wheel delta measurement, when scrolling explicitly + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) + { display.wheelStartX = display.wheelStartY = null; } + + // Propagate the scroll position to the actual DOM scroller + if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); } + + if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); } + // If we need to scroll a specific position into view, do so. + if (op.scrollToPos) { + var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), + clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); + maybeScrollWindow(cm, rect); + } + + // Fire events for markers that are hidden/unidden by editing or + // undoing + var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; + if (hidden) { for (var i = 0; i < hidden.length; ++i) + { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } } + if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1) + { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } } + + if (display.wrapper.offsetHeight) + { doc.scrollTop = cm.display.scroller.scrollTop; } + + // Fire change events, and delayed event handlers + if (op.changeObjs) + { signal(cm, "changes", cm, op.changeObjs); } + if (op.update) + { op.update.finish(); } + } + + // Run the given function in an operation + function runInOp(cm, f) { + if (cm.curOp) { return f() } + startOperation(cm); + try { return f() } + finally { endOperation(cm); } + } + // Wraps a function in an operation. Returns the wrapped function. + function operation(cm, f) { + return function() { + if (cm.curOp) { return f.apply(cm, arguments) } + startOperation(cm); + try { return f.apply(cm, arguments) } + finally { endOperation(cm); } + } + } + // Used to add methods to editor and doc instances, wrapping them in + // operations. + function methodOp(f) { + return function() { + if (this.curOp) { return f.apply(this, arguments) } + startOperation(this); + try { return f.apply(this, arguments) } + finally { endOperation(this); } + } + } + function docMethodOp(f) { + return function() { + var cm = this.cm; + if (!cm || cm.curOp) { return f.apply(this, arguments) } + startOperation(cm); + try { return f.apply(this, arguments) } + finally { endOperation(cm); } + } + } + + // HIGHLIGHT WORKER + + function startWorker(cm, time) { + if (cm.doc.highlightFrontier < cm.display.viewTo) + { cm.state.highlight.set(time, bind(highlightWorker, cm)); } + } + + function highlightWorker(cm) { + var doc = cm.doc; + if (doc.highlightFrontier >= cm.display.viewTo) { return } + var end = +new Date + cm.options.workTime; + var context = getContextBefore(cm, doc.highlightFrontier); + var changedLines = []; + + doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { + if (context.line >= cm.display.viewFrom) { // Visible + var oldStyles = line.styles; + var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null; + var highlighted = highlightLine(cm, line, context, true); + if (resetState) { context.state = resetState; } + line.styles = highlighted.styles; + var oldCls = line.styleClasses, newCls = highlighted.classes; + if (newCls) { line.styleClasses = newCls; } + else if (oldCls) { line.styleClasses = null; } + var ischange = !oldStyles || oldStyles.length != line.styles.length || + oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); + for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; } + if (ischange) { changedLines.push(context.line); } + line.stateAfter = context.save(); + context.nextLine(); + } else { + if (line.text.length <= cm.options.maxHighlightLength) + { processLine(cm, line.text, context); } + line.stateAfter = context.line % 5 == 0 ? context.save() : null; + context.nextLine(); + } + if (+new Date > end) { + startWorker(cm, cm.options.workDelay); + return true + } + }); + doc.highlightFrontier = context.line; + doc.modeFrontier = Math.max(doc.modeFrontier, context.line); + if (changedLines.length) { runInOp(cm, function () { + for (var i = 0; i < changedLines.length; i++) + { regLineChange(cm, changedLines[i], "text"); } + }); } + } + + // DISPLAY DRAWING + + var DisplayUpdate = function(cm, viewport, force) { + var display = cm.display; + + this.viewport = viewport; + // Store some values that we'll need later (but don't want to force a relayout for) + this.visible = visibleLines(display, cm.doc, viewport); + this.editorIsHidden = !display.wrapper.offsetWidth; + this.wrapperHeight = display.wrapper.clientHeight; + this.wrapperWidth = display.wrapper.clientWidth; + this.oldDisplayWidth = displayWidth(cm); + this.force = force; + this.dims = getDimensions(cm); + this.events = []; + }; + + DisplayUpdate.prototype.signal = function (emitter, type) { + if (hasHandler(emitter, type)) + { this.events.push(arguments); } + }; + DisplayUpdate.prototype.finish = function () { + var this$1 = this; + + for (var i = 0; i < this.events.length; i++) + { signal.apply(null, this$1.events[i]); } + }; + + function maybeClipScrollbars(cm) { + var display = cm.display; + if (!display.scrollbarsClipped && display.scroller.offsetWidth) { + display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; + display.heightForcer.style.height = scrollGap(cm) + "px"; + display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; + display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; + display.scrollbarsClipped = true; + } + } + + function selectionSnapshot(cm) { + if (cm.hasFocus()) { return null } + var active = activeElt(); + if (!active || !contains(cm.display.lineDiv, active)) { return null } + var result = {activeElt: active}; + if (window.getSelection) { + var sel = window.getSelection(); + if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { + result.anchorNode = sel.anchorNode; + result.anchorOffset = sel.anchorOffset; + result.focusNode = sel.focusNode; + result.focusOffset = sel.focusOffset; + } + } + return result + } + + function restoreSelection(snapshot) { + if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return } + snapshot.activeElt.focus(); + if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { + var sel = window.getSelection(), range$$1 = document.createRange(); + range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset); + range$$1.collapse(false); + sel.removeAllRanges(); + sel.addRange(range$$1); + sel.extend(snapshot.focusNode, snapshot.focusOffset); + } + } + + // Does the actual updating of the line display. Bails out + // (returning false) when there is nothing to be done and forced is + // false. + function updateDisplayIfNeeded(cm, update) { + var display = cm.display, doc = cm.doc; + + if (update.editorIsHidden) { + resetView(cm); + return false + } + + // Bail out if the visible area is already rendered and nothing changed. + if (!update.force && + update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && + display.renderedView == display.view && countDirtyView(cm) == 0) + { return false } + + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm); + update.dims = getDimensions(cm); + } + + // Compute a suitable new viewport (from & to) + var end = doc.first + doc.size; + var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); + var to = Math.min(end, update.visible.to + cm.options.viewportMargin); + if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); } + if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); } + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from); + to = visualLineEndNo(cm.doc, to); + } + + var different = from != display.viewFrom || to != display.viewTo || + display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; + adjustView(cm, from, to); + + display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); + // Position the mover div to align with the current scroll position + cm.display.mover.style.top = display.viewOffset + "px"; + + var toUpdate = countDirtyView(cm); + if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) + { return false } + + // For big changes, we hide the enclosing element during the + // update, since that speeds up the operations on most browsers. + var selSnapshot = selectionSnapshot(cm); + if (toUpdate > 4) { display.lineDiv.style.display = "none"; } + patchDisplay(cm, display.updateLineNumbers, update.dims); + if (toUpdate > 4) { display.lineDiv.style.display = ""; } + display.renderedView = display.view; + // There might have been a widget with a focused element that got + // hidden or updated, if so re-focus it. + restoreSelection(selSnapshot); + + // Prevent selection and cursors from interfering with the scroll + // width and height. + removeChildren(display.cursorDiv); + removeChildren(display.selectionDiv); + display.gutters.style.height = display.sizer.style.minHeight = 0; + + if (different) { + display.lastWrapHeight = update.wrapperHeight; + display.lastWrapWidth = update.wrapperWidth; + startWorker(cm, 400); + } + + display.updateLineNumbers = null; + + return true + } + + function postUpdateDisplay(cm, update) { + var viewport = update.viewport; + + for (var first = true;; first = false) { + if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { + // Clip forced viewport to actual scrollable area. + if (viewport && viewport.top != null) + { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; } + // Updated line heights might result in the drawn area not + // actually covering the viewport. Keep looping until it does. + update.visible = visibleLines(cm.display, cm.doc, viewport); + if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) + { break } + } + if (!updateDisplayIfNeeded(cm, update)) { break } + updateHeightsInViewport(cm); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + updateScrollbars(cm, barMeasure); + setDocumentHeight(cm, barMeasure); + update.force = false; + } + + update.signal(cm, "update", cm); + if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { + update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); + cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; + } + } + + function updateDisplaySimple(cm, viewport) { + var update = new DisplayUpdate(cm, viewport); + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm); + postUpdateDisplay(cm, update); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + updateScrollbars(cm, barMeasure); + setDocumentHeight(cm, barMeasure); + update.finish(); + } + } + + // Sync the actual display DOM structure with display.view, removing + // nodes for lines that are no longer in view, and creating the ones + // that are not there yet, and updating the ones that are out of + // date. + function patchDisplay(cm, updateNumbersFrom, dims) { + var display = cm.display, lineNumbers = cm.options.lineNumbers; + var container = display.lineDiv, cur = container.firstChild; + + function rm(node) { + var next = node.nextSibling; + // Works around a throw-scroll bug in OS X Webkit + if (webkit && mac && cm.display.currentWheelTarget == node) + { node.style.display = "none"; } + else + { node.parentNode.removeChild(node); } + return next + } + + var view = display.view, lineN = display.viewFrom; + // Loop over the elements in the view, syncing cur (the DOM nodes + // in display.lineDiv) with the view as we go. + for (var i = 0; i < view.length; i++) { + var lineView = view[i]; + if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet + var node = buildLineElement(cm, lineView, lineN, dims); + container.insertBefore(node, cur); + } else { // Already drawn + while (cur != lineView.node) { cur = rm(cur); } + var updateNumber = lineNumbers && updateNumbersFrom != null && + updateNumbersFrom <= lineN && lineView.lineNumber; + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; } + updateLineForChanges(cm, lineView, lineN, dims); + } + if (updateNumber) { + removeChildren(lineView.lineNumber); + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); + } + cur = lineView.node.nextSibling; + } + lineN += lineView.size; + } + while (cur) { cur = rm(cur); } + } + + function updateGutterSpace(display) { + var width = display.gutters.offsetWidth; + display.sizer.style.marginLeft = width + "px"; + } + + function setDocumentHeight(cm, measure) { + cm.display.sizer.style.minHeight = measure.docHeight + "px"; + cm.display.heightForcer.style.top = measure.docHeight + "px"; + cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"; + } + + // Re-align line numbers and gutter marks to compensate for + // horizontal scrolling. + function alignHorizontally(cm) { + var display = cm.display, view = display.view; + if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return } + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; + var gutterW = display.gutters.offsetWidth, left = comp + "px"; + for (var i = 0; i < view.length; i++) { if (!view[i].hidden) { + if (cm.options.fixedGutter) { + if (view[i].gutter) + { view[i].gutter.style.left = left; } + if (view[i].gutterBackground) + { view[i].gutterBackground.style.left = left; } + } + var align = view[i].alignable; + if (align) { for (var j = 0; j < align.length; j++) + { align[j].style.left = left; } } + } } + if (cm.options.fixedGutter) + { display.gutters.style.left = (comp + gutterW) + "px"; } + } + + // Used to ensure that the line number gutter is still the right + // size for the current document size. Returns true when an update + // is needed. + function maybeUpdateLineNumberWidth(cm) { + if (!cm.options.lineNumbers) { return false } + var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild(elt("div", [elt("div", last)], + "CodeMirror-linenumber CodeMirror-gutter-elt")); + var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; + display.lineGutter.style.width = ""; + display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; + display.lineNumWidth = display.lineNumInnerWidth + padding; + display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; + display.lineGutter.style.width = display.lineNumWidth + "px"; + updateGutterSpace(cm.display); + return true + } + return false + } + + function getGutters(gutters, lineNumbers) { + var result = [], sawLineNumbers = false; + for (var i = 0; i < gutters.length; i++) { + var name = gutters[i], style = null; + if (typeof name != "string") { style = name.style; name = name.className; } + if (name == "CodeMirror-linenumbers") { + if (!lineNumbers) { continue } + else { sawLineNumbers = true; } + } + result.push({className: name, style: style}); + } + if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); } + return result + } + + // Rebuild the gutter elements, ensure the margin to the left of the + // code matches their width. + function renderGutters(display) { + var gutters = display.gutters, specs = display.gutterSpecs; + removeChildren(gutters); + display.lineGutter = null; + for (var i = 0; i < specs.length; ++i) { + var ref = specs[i]; + var className = ref.className; + var style = ref.style; + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className)); + if (style) { gElt.style.cssText = style; } + if (className == "CodeMirror-linenumbers") { + display.lineGutter = gElt; + gElt.style.width = (display.lineNumWidth || 1) + "px"; + } + } + gutters.style.display = specs.length ? "" : "none"; + updateGutterSpace(display); + } + + function updateGutters(cm) { + renderGutters(cm.display); + regChange(cm); + alignHorizontally(cm); + } + + // The display handles the DOM integration, both for input reading + // and content drawing. It holds references to DOM nodes and + // display-related state. + + function Display(place, doc, input, options) { + var d = this; + this.input = input; + + // Covers bottom-right square when both scrollbars are present. + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); + d.scrollbarFiller.setAttribute("cm-not-content", "true"); + // Covers bottom of gutter when coverGutterNextToScrollbar is on + // and h scrollbar is present. + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); + d.gutterFiller.setAttribute("cm-not-content", "true"); + // Will contain the actual code, positioned to cover the viewport. + d.lineDiv = eltP("div", null, "CodeMirror-code"); + // Elements are added to these to represent selection and cursors. + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); + d.cursorDiv = elt("div", null, "CodeMirror-cursors"); + // A visibility: hidden element used to find the size of things. + d.measure = elt("div", null, "CodeMirror-measure"); + // When lines outside of the viewport are measured, they are drawn in this. + d.lineMeasure = elt("div", null, "CodeMirror-measure"); + // Wraps everything that needs to exist inside the vertically-padded coordinate system + d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], + null, "position: relative; outline: none"); + var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); + // Moved around its parent to cover visible view. + d.mover = elt("div", [lines], null, "position: relative"); + // Set to the height of the document, allowing scrolling. + d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); + d.sizerWidth = null; + // Behavior of elts with overflow: auto and padding is + // inconsistent across browsers. This is used to ensure the + // scrollable area is big enough. + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); + // Will contain the gutters, if any. + d.gutters = elt("div", null, "CodeMirror-gutters"); + d.lineGutter = null; + // Actual scrollable element. + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); + d.scroller.setAttribute("tabIndex", "-1"); + // The element in which the editor lives. + d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); + + // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) + if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } + if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; } + + if (place) { + if (place.appendChild) { place.appendChild(d.wrapper); } + else { place(d.wrapper); } + } + + // Current rendered range (may be bigger than the view window). + d.viewFrom = d.viewTo = doc.first; + d.reportedViewFrom = d.reportedViewTo = doc.first; + // Information about the rendered lines. + d.view = []; + d.renderedView = null; + // Holds info about a single rendered line when it was rendered + // for measurement, while not in view. + d.externalMeasured = null; + // Empty space (in pixels) above the view + d.viewOffset = 0; + d.lastWrapHeight = d.lastWrapWidth = 0; + d.updateLineNumbers = null; + + d.nativeBarWidth = d.barHeight = d.barWidth = 0; + d.scrollbarsClipped = false; + + // Used to only resize the line number gutter when necessary (when + // the amount of lines crosses a boundary that makes its width change) + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; + // Set to true when a non-horizontal-scrolling line widget is + // added. As an optimization, line widget aligning is skipped when + // this is false. + d.alignWidgets = false; + + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + + // Tracks the maximum line length so that the horizontal scrollbar + // can be kept static when scrolling. + d.maxLine = null; + d.maxLineLength = 0; + d.maxLineChanged = false; + + // Used for measuring wheel scrolling granularity + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; + + // True when shift is held down. + d.shift = false; + + // Used to track whether anything happened since the context menu + // was opened. + d.selForContextMenu = null; + + d.activeTouch = null; + + d.gutterSpecs = getGutters(options.gutters, options.lineNumbers); + renderGutters(d); + + input.init(d); + } + + // Since the delta values reported on mouse wheel events are + // unstandardized between browsers and even browser versions, and + // generally horribly unpredictable, this code starts by measuring + // the scroll effect that the first few mouse wheel events have, + // and, from that, detects the way it can convert deltas to pixel + // offsets afterwards. + // + // The reason we want to know the amount a wheel event will scroll + // is that it gives us a chance to update the display before the + // actual scrolling happens, reducing flickering. + + var wheelSamples = 0, wheelPixelsPerUnit = null; + // Fill in a browser-detected starting value on browsers where we + // know one. These don't have to be accurate -- the result of them + // being wrong would just be a slight flicker on the first wheel + // scroll (if it is large enough). + if (ie) { wheelPixelsPerUnit = -.53; } + else if (gecko) { wheelPixelsPerUnit = 15; } + else if (chrome) { wheelPixelsPerUnit = -.7; } + else if (safari) { wheelPixelsPerUnit = -1/3; } + + function wheelEventDelta(e) { + var dx = e.wheelDeltaX, dy = e.wheelDeltaY; + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; } + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; } + else if (dy == null) { dy = e.wheelDelta; } + return {x: dx, y: dy} + } + function wheelEventPixels(e) { + var delta = wheelEventDelta(e); + delta.x *= wheelPixelsPerUnit; + delta.y *= wheelPixelsPerUnit; + return delta + } + + function onScrollWheel(cm, e) { + var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; + + var display = cm.display, scroll = display.scroller; + // Quit if there's nothing to scroll here + var canScrollX = scroll.scrollWidth > scroll.clientWidth; + var canScrollY = scroll.scrollHeight > scroll.clientHeight; + if (!(dx && canScrollX || dy && canScrollY)) { return } + + // Webkit browsers on OS X abort momentum scrolls when the target + // of the scroll event is removed from the scrollable element. + // This hack (see related code in patchDisplay) makes sure the + // element is kept around. + if (dy && mac && webkit) { + outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + for (var i = 0; i < view.length; i++) { + if (view[i].node == cur) { + cm.display.currentWheelTarget = cur; + break outer + } + } + } + } + + // On some browsers, horizontal scrolling will cause redraws to + // happen before the gutter has been realigned, causing it to + // wriggle around in a most unseemly way. When we have an + // estimated pixels/delta value, we just handle horizontal + // scrolling entirely here. It'll be slightly off from native, but + // better than glitching out. + if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { + if (dy && canScrollY) + { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); } + setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit)); + // Only prevent default scrolling if vertical scrolling is + // actually possible. Otherwise, it causes vertical scroll + // jitter on OSX trackpads when deltaX is small and deltaY + // is large (issue #3579) + if (!dy || (dy && canScrollY)) + { e_preventDefault(e); } + display.wheelStartX = null; // Abort measurement, if in progress + return + } + + // 'Project' the visible viewport to cover the area that is being + // scrolled into view (if we know enough to estimate it). + if (dy && wheelPixelsPerUnit != null) { + var pixels = dy * wheelPixelsPerUnit; + var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; + if (pixels < 0) { top = Math.max(0, top + pixels - 50); } + else { bot = Math.min(cm.doc.height, bot + pixels + 50); } + updateDisplaySimple(cm, {top: top, bottom: bot}); + } + + if (wheelSamples < 20) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; + display.wheelDX = dx; display.wheelDY = dy; + setTimeout(function () { + if (display.wheelStartX == null) { return } + var movedX = scroll.scrollLeft - display.wheelStartX; + var movedY = scroll.scrollTop - display.wheelStartY; + var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || + (movedX && display.wheelDX && movedX / display.wheelDX); + display.wheelStartX = display.wheelStartY = null; + if (!sample) { return } + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); + ++wheelSamples; + }, 200); + } else { + display.wheelDX += dx; display.wheelDY += dy; + } + } + } + + // Selection objects are immutable. A new one is created every time + // the selection changes. A selection is one or more non-overlapping + // (and non-touching) ranges, sorted, and an integer that indicates + // which one is the primary selection (the one that's scrolled into + // view, that getCursor returns, etc). + var Selection = function(ranges, primIndex) { + this.ranges = ranges; + this.primIndex = primIndex; + }; + + Selection.prototype.primary = function () { return this.ranges[this.primIndex] }; + + Selection.prototype.equals = function (other) { + var this$1 = this; + + if (other == this) { return true } + if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false } + for (var i = 0; i < this.ranges.length; i++) { + var here = this$1.ranges[i], there = other.ranges[i]; + if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false } + } + return true + }; + + Selection.prototype.deepCopy = function () { + var this$1 = this; + + var out = []; + for (var i = 0; i < this.ranges.length; i++) + { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); } + return new Selection(out, this.primIndex) + }; + + Selection.prototype.somethingSelected = function () { + var this$1 = this; + + for (var i = 0; i < this.ranges.length; i++) + { if (!this$1.ranges[i].empty()) { return true } } + return false + }; + + Selection.prototype.contains = function (pos, end) { + var this$1 = this; + + if (!end) { end = pos; } + for (var i = 0; i < this.ranges.length; i++) { + var range = this$1.ranges[i]; + if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) + { return i } + } + return -1 + }; + + var Range = function(anchor, head) { + this.anchor = anchor; this.head = head; + }; + + Range.prototype.from = function () { return minPos(this.anchor, this.head) }; + Range.prototype.to = function () { return maxPos(this.anchor, this.head) }; + Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch }; + + // Take an unsorted, potentially overlapping set of ranges, and + // build a selection out of it. 'Consumes' ranges array (modifying + // it). + function normalizeSelection(cm, ranges, primIndex) { + var mayTouch = cm && cm.options.selectionsMayTouch; + var prim = ranges[primIndex]; + ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }); + primIndex = indexOf(ranges, prim); + for (var i = 1; i < ranges.length; i++) { + var cur = ranges[i], prev = ranges[i - 1]; + var diff = cmp(prev.to(), cur.from()); + if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) { + var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); + var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; + if (i <= primIndex) { --primIndex; } + ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); + } + } + return new Selection(ranges, primIndex) + } + + function simpleSelection(anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0) + } + + // Compute the position of the end of a change (its 'to' property + // refers to the pre-change end). + function changeEnd(change) { + if (!change.text) { return change.to } + return Pos(change.from.line + change.text.length - 1, + lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) + } + + // Adjust a position to refer to the post-change position of the + // same text, or the end of the change if the change covers it. + function adjustForChange(pos, change) { + if (cmp(pos, change.from) < 0) { return pos } + if (cmp(pos, change.to) <= 0) { return changeEnd(change) } + + var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; + if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; } + return Pos(line, ch) + } + + function computeSelAfterChange(doc, change) { + var out = []; + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i]; + out.push(new Range(adjustForChange(range.anchor, change), + adjustForChange(range.head, change))); + } + return normalizeSelection(doc.cm, out, doc.sel.primIndex) + } + + function offsetPos(pos, old, nw) { + if (pos.line == old.line) + { return Pos(nw.line, pos.ch - old.ch + nw.ch) } + else + { return Pos(nw.line + (pos.line - old.line), pos.ch) } + } + + // Used by replaceSelections to allow moving the selection to the + // start or around the replaced test. Hint may be "start" or "around". + function computeReplacedSel(doc, changes, hint) { + var out = []; + var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + var from = offsetPos(change.from, oldPrev, newPrev); + var to = offsetPos(changeEnd(change), oldPrev, newPrev); + oldPrev = change.to; + newPrev = to; + if (hint == "around") { + var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; + out[i] = new Range(inv ? to : from, inv ? from : to); + } else { + out[i] = new Range(from, from); + } + } + return new Selection(out, doc.sel.primIndex) + } + + // Used to get the editor into a consistent state again when options change. + + function loadMode(cm) { + cm.doc.mode = getMode(cm.options, cm.doc.modeOption); + resetModeState(cm); + } + + function resetModeState(cm) { + cm.doc.iter(function (line) { + if (line.stateAfter) { line.stateAfter = null; } + if (line.styles) { line.styles = null; } + }); + cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; + startWorker(cm, 100); + cm.state.modeGen++; + if (cm.curOp) { regChange(cm); } + } + + // DOCUMENT DATA STRUCTURE + + // By default, updates that start and end at the beginning of a line + // are treated specially, in order to make the association of line + // widgets and marker elements with the text behave more intuitive. + function isWholeLineUpdate(doc, change) { + return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && + (!doc.cm || doc.cm.options.wholeLineUpdateBefore) + } + + // Perform a change on the document data structure. + function updateDoc(doc, change, markedSpans, estimateHeight$$1) { + function spansFor(n) {return markedSpans ? markedSpans[n] : null} + function update(line, text, spans) { + updateLine(line, text, spans, estimateHeight$$1); + signalLater(line, "change", line, change); + } + function linesFor(start, end) { + var result = []; + for (var i = start; i < end; ++i) + { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); } + return result + } + + var from = change.from, to = change.to, text = change.text; + var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); + var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; + + // Adjust the line structure + if (change.full) { + doc.insert(0, linesFor(0, text.length)); + doc.remove(text.length, doc.size - text.length); + } else if (isWholeLineUpdate(doc, change)) { + // This is a whole-line replace. Treated specially to make + // sure line objects move the way they are supposed to. + var added = linesFor(0, text.length - 1); + update(lastLine, lastLine.text, lastSpans); + if (nlines) { doc.remove(from.line, nlines); } + if (added.length) { doc.insert(from.line, added); } + } else if (firstLine == lastLine) { + if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); + } else { + var added$1 = linesFor(1, text.length - 1); + added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1)); + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + doc.insert(from.line + 1, added$1); + } + } else if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); + doc.remove(from.line + 1, nlines); + } else { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); + var added$2 = linesFor(1, text.length - 1); + if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); } + doc.insert(from.line + 1, added$2); + } + + signalLater(doc, "change", doc, change); + } + + // Call f for all linked documents. + function linkedDocs(doc, f, sharedHistOnly) { + function propagate(doc, skip, sharedHist) { + if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) { + var rel = doc.linked[i]; + if (rel.doc == skip) { continue } + var shared = sharedHist && rel.sharedHist; + if (sharedHistOnly && !shared) { continue } + f(rel.doc, shared); + propagate(rel.doc, doc, shared); + } } + } + propagate(doc, null, true); + } + + // Attach a document to an editor. + function attachDoc(cm, doc) { + if (doc.cm) { throw new Error("This document is already in use.") } + cm.doc = doc; + doc.cm = cm; + estimateLineHeights(cm); + loadMode(cm); + setDirectionClass(cm); + if (!cm.options.lineWrapping) { findMaxLine(cm); } + cm.options.mode = doc.modeOption; + regChange(cm); + } + + function setDirectionClass(cm) { + (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); + } + + function directionChanged(cm) { + runInOp(cm, function () { + setDirectionClass(cm); + regChange(cm); + }); + } + + function History(startGen) { + // Arrays of change events and selections. Doing something adds an + // event to done and clears undo. Undoing moves events from done + // to undone, redoing moves them in the other direction. + this.done = []; this.undone = []; + this.undoDepth = Infinity; + // Used to track when changes can be merged into a single undo + // event + this.lastModTime = this.lastSelTime = 0; + this.lastOp = this.lastSelOp = null; + this.lastOrigin = this.lastSelOrigin = null; + // Used by the isClean() method + this.generation = this.maxGeneration = startGen || 1; + } + + // Create a history change event from an updateDoc-style change + // object. + function historyChangeFromChange(doc, change) { + var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; + attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); + linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true); + return histChange + } + + // Pop all selection events off the end of a history array. Stop at + // a change event. + function clearSelectionEvents(array) { + while (array.length) { + var last = lst(array); + if (last.ranges) { array.pop(); } + else { break } + } + } + + // Find the top change event in the history. Pop off selection + // events that are in the way. + function lastChangeEvent(hist, force) { + if (force) { + clearSelectionEvents(hist.done); + return lst(hist.done) + } else if (hist.done.length && !lst(hist.done).ranges) { + return lst(hist.done) + } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { + hist.done.pop(); + return lst(hist.done) + } + } + + // Register a change in the history. Merges changes that are within + // a single operation, or are close together with an origin that + // allows merging (starting with "+") into a single event. + function addChangeToHistory(doc, change, selAfter, opId) { + var hist = doc.history; + hist.undone.length = 0; + var time = +new Date, cur; + var last; + + if ((hist.lastOp == opId || + hist.lastOrigin == change.origin && change.origin && + ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) || + change.origin.charAt(0) == "*")) && + (cur = lastChangeEvent(hist, hist.lastOp == opId))) { + // Merge this change into the last event + last = lst(cur.changes); + if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { + // Optimized case for simple insertion -- don't want to add + // new changesets for every character typed + last.to = changeEnd(change); + } else { + // Add new sub-event + cur.changes.push(historyChangeFromChange(doc, change)); + } + } else { + // Can not be merged, start a new event. + var before = lst(hist.done); + if (!before || !before.ranges) + { pushSelectionToHistory(doc.sel, hist.done); } + cur = {changes: [historyChangeFromChange(doc, change)], + generation: hist.generation}; + hist.done.push(cur); + while (hist.done.length > hist.undoDepth) { + hist.done.shift(); + if (!hist.done[0].ranges) { hist.done.shift(); } + } + } + hist.done.push(selAfter); + hist.generation = ++hist.maxGeneration; + hist.lastModTime = hist.lastSelTime = time; + hist.lastOp = hist.lastSelOp = opId; + hist.lastOrigin = hist.lastSelOrigin = change.origin; + + if (!last) { signal(doc, "historyAdded"); } + } + + function selectionEventCanBeMerged(doc, origin, prev, sel) { + var ch = origin.charAt(0); + return ch == "*" || + ch == "+" && + prev.ranges.length == sel.ranges.length && + prev.somethingSelected() == sel.somethingSelected() && + new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500) + } + + // Called whenever the selection changes, sets the new selection as + // the pending selection in the history, and pushes the old pending + // selection into the 'done' array when it was significantly + // different (in number of selected ranges, emptiness, or time). + function addSelectionToHistory(doc, sel, opId, options) { + var hist = doc.history, origin = options && options.origin; + + // A new event is started when the previous origin does not match + // the current, or the origins don't allow matching. Origins + // starting with * are always merged, those starting with + are + // merged when similar and close together in time. + if (opId == hist.lastSelOp || + (origin && hist.lastSelOrigin == origin && + (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || + selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) + { hist.done[hist.done.length - 1] = sel; } + else + { pushSelectionToHistory(sel, hist.done); } + + hist.lastSelTime = +new Date; + hist.lastSelOrigin = origin; + hist.lastSelOp = opId; + if (options && options.clearRedo !== false) + { clearSelectionEvents(hist.undone); } + } + + function pushSelectionToHistory(sel, dest) { + var top = lst(dest); + if (!(top && top.ranges && top.equals(sel))) + { dest.push(sel); } + } + + // Used to store marked span information in the history. + function attachLocalSpans(doc, change, from, to) { + var existing = change["spans_" + doc.id], n = 0; + doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { + if (line.markedSpans) + { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; } + ++n; + }); + } + + // When un/re-doing restores text containing marked spans, those + // that have been explicitly cleared should not be restored. + function removeClearedSpans(spans) { + if (!spans) { return null } + var out; + for (var i = 0; i < spans.length; ++i) { + if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } } + else if (out) { out.push(spans[i]); } + } + return !out ? spans : out.length ? out : null + } + + // Retrieve and filter the old marked spans stored in a change event. + function getOldSpans(doc, change) { + var found = change["spans_" + doc.id]; + if (!found) { return null } + var nw = []; + for (var i = 0; i < change.text.length; ++i) + { nw.push(removeClearedSpans(found[i])); } + return nw + } + + // Used for un/re-doing changes from the history. Combines the + // result of computing the existing spans with the set of spans that + // existed in the history (so that deleting around a span and then + // undoing brings back the span). + function mergeOldSpans(doc, change) { + var old = getOldSpans(doc, change); + var stretched = stretchSpansOverChange(doc, change); + if (!old) { return stretched } + if (!stretched) { return old } + + for (var i = 0; i < old.length; ++i) { + var oldCur = old[i], stretchCur = stretched[i]; + if (oldCur && stretchCur) { + spans: for (var j = 0; j < stretchCur.length; ++j) { + var span = stretchCur[j]; + for (var k = 0; k < oldCur.length; ++k) + { if (oldCur[k].marker == span.marker) { continue spans } } + oldCur.push(span); + } + } else if (stretchCur) { + old[i] = stretchCur; + } + } + return old + } + + // Used both to provide a JSON-safe object in .getHistory, and, when + // detaching a document, to split the history in two + function copyHistoryArray(events, newGroup, instantiateSel) { + var copy = []; + for (var i = 0; i < events.length; ++i) { + var event = events[i]; + if (event.ranges) { + copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); + continue + } + var changes = event.changes, newChanges = []; + copy.push({changes: newChanges}); + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], m = (void 0); + newChanges.push({from: change.from, to: change.to, text: change.text}); + if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop] = change[prop]; + delete change[prop]; + } + } } } + } + } + return copy + } + + // The 'scroll' parameter given to many of these indicated whether + // the new cursor position should be scrolled into view after + // modifying the selection. + + // If shift is held or the extend flag is set, extends a range to + // include a given position (and optionally a second position). + // Otherwise, simply returns the range between the given positions. + // Used for cursor motion and such. + function extendRange(range, head, other, extend) { + if (extend) { + var anchor = range.anchor; + if (other) { + var posBefore = cmp(head, anchor) < 0; + if (posBefore != (cmp(other, anchor) < 0)) { + anchor = head; + head = other; + } else if (posBefore != (cmp(head, other) < 0)) { + head = other; + } + } + return new Range(anchor, head) + } else { + return new Range(other || head, head) + } + } + + // Extend the primary selection range, discard the rest. + function extendSelection(doc, head, other, options, extend) { + if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); } + setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options); + } + + // Extend all selections (pos is an array of selections with length + // equal the number of selections) + function extendSelections(doc, heads, options) { + var out = []; + var extend = doc.cm && (doc.cm.display.shift || doc.extend); + for (var i = 0; i < doc.sel.ranges.length; i++) + { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); } + var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex); + setSelection(doc, newSel, options); + } + + // Updates a single range in the selection. + function replaceOneSelection(doc, i, range, options) { + var ranges = doc.sel.ranges.slice(0); + ranges[i] = range; + setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options); + } + + // Reset the selection to a single range. + function setSimpleSelection(doc, anchor, head, options) { + setSelection(doc, simpleSelection(anchor, head), options); + } + + // Give beforeSelectionChange handlers a change to influence a + // selection update. + function filterSelectionChange(doc, sel, options) { + var obj = { + ranges: sel.ranges, + update: function(ranges) { + var this$1 = this; + + this.ranges = []; + for (var i = 0; i < ranges.length; i++) + { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), + clipPos(doc, ranges[i].head)); } + }, + origin: options && options.origin + }; + signal(doc, "beforeSelectionChange", doc, obj); + if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); } + if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) } + else { return sel } + } + + function setSelectionReplaceHistory(doc, sel, options) { + var done = doc.history.done, last = lst(done); + if (last && last.ranges) { + done[done.length - 1] = sel; + setSelectionNoUndo(doc, sel, options); + } else { + setSelection(doc, sel, options); + } + } + + // Set a new selection. + function setSelection(doc, sel, options) { + setSelectionNoUndo(doc, sel, options); + addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); + } + + function setSelectionNoUndo(doc, sel, options) { + if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) + { sel = filterSelectionChange(doc, sel, options); } + + var bias = options && options.bias || + (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); + setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); + + if (!(options && options.scroll === false) && doc.cm) + { ensureCursorVisible(doc.cm); } + } + + function setSelectionInner(doc, sel) { + if (sel.equals(doc.sel)) { return } + + doc.sel = sel; + + if (doc.cm) { + doc.cm.curOp.updateInput = 1; + doc.cm.curOp.selectionChanged = true; + signalCursorActivity(doc.cm); + } + signalLater(doc, "cursorActivity", doc); + } + + // Verify that the selection does not partially select any atomic + // marked ranges. + function reCheckSelection(doc) { + setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); + } + + // Return a selection that does not partially select any atomic + // ranges. + function skipAtomicInSelection(doc, sel, bias, mayClear) { + var out; + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i]; + var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]; + var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear); + var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear); + if (out || newAnchor != range.anchor || newHead != range.head) { + if (!out) { out = sel.ranges.slice(0, i); } + out[i] = new Range(newAnchor, newHead); + } + } + return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel + } + + function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { + var line = getLine(doc, pos.line); + if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { + var sp = line.markedSpans[i], m = sp.marker; + + // Determine if we should prevent the cursor being placed to the left/right of an atomic marker + // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it + // is with selectLeft/Right + var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft; + var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight; + + if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && + (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) { + if (mayClear) { + signal(m, "beforeCursorEnter"); + if (m.explicitlyCleared) { + if (!line.markedSpans) { break } + else {--i; continue} + } + } + if (!m.atomic) { continue } + + if (oldPos) { + var near = m.find(dir < 0 ? 1 : -1), diff = (void 0); + if (dir < 0 ? preventCursorRight : preventCursorLeft) + { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); } + if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) + { return skipAtomicInner(doc, near, pos, dir, mayClear) } + } + + var far = m.find(dir < 0 ? -1 : 1); + if (dir < 0 ? preventCursorLeft : preventCursorRight) + { far = movePos(doc, far, dir, far.line == pos.line ? line : null); } + return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null + } + } } + return pos + } + + // Ensure a given position is not inside an atomic range. + function skipAtomic(doc, pos, oldPos, bias, mayClear) { + var dir = bias || 1; + var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || + (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || + skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || + (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)); + if (!found) { + doc.cantEdit = true; + return Pos(doc.first, 0) + } + return found + } + + function movePos(doc, pos, dir, line) { + if (dir < 0 && pos.ch == 0) { + if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) } + else { return null } + } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { + if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) } + else { return null } + } else { + return new Pos(pos.line, pos.ch + dir) + } + } + + function selectAll(cm) { + cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); + } + + // UPDATING + + // Allow "beforeChange" event handlers to influence a change + function filterChange(doc, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function () { return obj.canceled = true; } + }; + if (update) { obj.update = function (from, to, text, origin) { + if (from) { obj.from = clipPos(doc, from); } + if (to) { obj.to = clipPos(doc, to); } + if (text) { obj.text = text; } + if (origin !== undefined) { obj.origin = origin; } + }; } + signal(doc, "beforeChange", doc, obj); + if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); } + + if (obj.canceled) { + if (doc.cm) { doc.cm.curOp.updateInput = 2; } + return null + } + return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} + } + + // Apply a change to a document, and add it to the document's + // history, and propagating it to all linked documents. + function makeChange(doc, change, ignoreReadOnly) { + if (doc.cm) { + if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) } + if (doc.cm.state.suppressEdits) { return } + } + + if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { + change = filterChange(doc, change, true); + if (!change) { return } + } + + // Possibly split or suppress the update based on the presence + // of read-only spans in its range. + var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); + if (split) { + for (var i = split.length - 1; i >= 0; --i) + { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); } + } else { + makeChangeInner(doc, change); + } + } + + function makeChangeInner(doc, change) { + if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return } + var selAfter = computeSelAfterChange(doc, change); + addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); + + makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); + var rebased = []; + + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); + }); + } + + // Revert a change stored in a document's history. + function makeChangeFromHistory(doc, type, allowSelectionOnly) { + var suppress = doc.cm && doc.cm.state.suppressEdits; + if (suppress && !allowSelectionOnly) { return } + + var hist = doc.history, event, selAfter = doc.sel; + var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; + + // Verify that there is a useable event (so that ctrl-z won't + // needlessly clear selection events) + var i = 0; + for (; i < source.length; i++) { + event = source[i]; + if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) + { break } + } + if (i == source.length) { return } + hist.lastOrigin = hist.lastSelOrigin = null; + + for (;;) { + event = source.pop(); + if (event.ranges) { + pushSelectionToHistory(event, dest); + if (allowSelectionOnly && !event.equals(doc.sel)) { + setSelection(doc, event, {clearRedo: false}); + return + } + selAfter = event; + } else if (suppress) { + source.push(event); + return + } else { break } + } + + // Build up a reverse change object to add to the opposite history + // stack (redo when undoing, and vice versa). + var antiChanges = []; + pushSelectionToHistory(selAfter, dest); + dest.push({changes: antiChanges, generation: hist.generation}); + hist.generation = event.generation || ++hist.maxGeneration; + + var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); + + var loop = function ( i ) { + var change = event.changes[i]; + change.origin = type; + if (filter && !filterChange(doc, change, false)) { + source.length = 0; + return {} + } + + antiChanges.push(historyChangeFromChange(doc, change)); + + var after = i ? computeSelAfterChange(doc, change) : lst(source); + makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); + if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); } + var rebased = []; + + // Propagate to the linked documents + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); + }); + }; + + for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { + var returned = loop( i$1 ); + + if ( returned ) return returned.v; + } + } + + // Sub-views need their line numbers shifted when text is added + // above or below them in the parent document. + function shiftDoc(doc, distance) { + if (distance == 0) { return } + doc.first += distance; + doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range( + Pos(range.anchor.line + distance, range.anchor.ch), + Pos(range.head.line + distance, range.head.ch) + ); }), doc.sel.primIndex); + if (doc.cm) { + regChange(doc.cm, doc.first, doc.first - distance, distance); + for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) + { regLineChange(doc.cm, l, "gutter"); } + } + } + + // More lower-level change function, handling only a single document + // (not linked ones). + function makeChangeSingleDoc(doc, change, selAfter, spans) { + if (doc.cm && !doc.cm.curOp) + { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) } + + if (change.to.line < doc.first) { + shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); + return + } + if (change.from.line > doc.lastLine()) { return } + + // Clip the change to the size of this doc + if (change.from.line < doc.first) { + var shift = change.text.length - 1 - (doc.first - change.from.line); + shiftDoc(doc, shift); + change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], origin: change.origin}; + } + var last = doc.lastLine(); + if (change.to.line > last) { + change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), + text: [change.text[0]], origin: change.origin}; + } + + change.removed = getBetween(doc, change.from, change.to); + + if (!selAfter) { selAfter = computeSelAfterChange(doc, change); } + if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); } + else { updateDoc(doc, change, spans); } + setSelectionNoUndo(doc, selAfter, sel_dontScroll); + + if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) + { doc.cantEdit = false; } + } + + // Handle the interaction of a change to a document with the editor + // that this document is part of. + function makeChangeSingleDocInEditor(cm, change, spans) { + var doc = cm.doc, display = cm.display, from = change.from, to = change.to; + + var recomputeMaxLength = false, checkWidthStart = from.line; + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); + doc.iter(checkWidthStart, to.line + 1, function (line) { + if (line == display.maxLine) { + recomputeMaxLength = true; + return true + } + }); + } + + if (doc.sel.contains(change.from, change.to) > -1) + { signalCursorActivity(cm); } + + updateDoc(doc, change, spans, estimateHeight(cm)); + + if (!cm.options.lineWrapping) { + doc.iter(checkWidthStart, from.line + change.text.length, function (line) { + var len = lineLength(line); + if (len > display.maxLineLength) { + display.maxLine = line; + display.maxLineLength = len; + display.maxLineChanged = true; + recomputeMaxLength = false; + } + }); + if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; } + } + + retreatFrontier(doc, from.line); + startWorker(cm, 400); + + var lendiff = change.text.length - (to.line - from.line) - 1; + // Remember that these lines changed, for updating the display + if (change.full) + { regChange(cm); } + else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) + { regLineChange(cm, from.line, "text"); } + else + { regChange(cm, from.line, to.line + 1, lendiff); } + + var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); + if (changeHandler || changesHandler) { + var obj = { + from: from, to: to, + text: change.text, + removed: change.removed, + origin: change.origin + }; + if (changeHandler) { signalLater(cm, "change", cm, obj); } + if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); } + } + cm.display.selForContextMenu = null; + } + + function replaceRange(doc, code, from, to, origin) { + var assign; + + if (!to) { to = from; } + if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); } + if (typeof code == "string") { code = doc.splitLines(code); } + makeChange(doc, {from: from, to: to, text: code, origin: origin}); + } + + // Rebasing/resetting history to deal with externally-sourced changes + + function rebaseHistSelSingle(pos, from, to, diff) { + if (to < pos.line) { + pos.line += diff; + } else if (from < pos.line) { + pos.line = from; + pos.ch = 0; + } + } + + // Tries to rebase an array of history events given a change in the + // document. If the change touches the same lines as the event, the + // event, and everything 'behind' it, is discarded. If the change is + // before the event, the event's positions are updated. Uses a + // copy-on-write scheme for the positions, to avoid having to + // reallocate them all on every rebase, but also avoid problems with + // shared position objects being unsafely updated. + function rebaseHistArray(array, from, to, diff) { + for (var i = 0; i < array.length; ++i) { + var sub = array[i], ok = true; + if (sub.ranges) { + if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } + for (var j = 0; j < sub.ranges.length; j++) { + rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); + rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); + } + continue + } + for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { + var cur = sub.changes[j$1]; + if (to < cur.from.line) { + cur.from = Pos(cur.from.line + diff, cur.from.ch); + cur.to = Pos(cur.to.line + diff, cur.to.ch); + } else if (from <= cur.to.line) { + ok = false; + break + } + } + if (!ok) { + array.splice(0, i + 1); + i = 0; + } + } + } + + function rebaseHist(hist, change) { + var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; + rebaseHistArray(hist.done, from, to, diff); + rebaseHistArray(hist.undone, from, to, diff); + } + + // Utility for applying a change to a line by handle or number, + // returning the number and optionally registering the line as + // changed. + function changeLine(doc, handle, changeType, op) { + var no = handle, line = handle; + if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); } + else { no = lineNo(handle); } + if (no == null) { return null } + if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); } + return line + } + + // The document is represented as a BTree consisting of leaves, with + // chunk of lines in them, and branches, with up to ten leaves or + // other branch nodes below them. The top node is always a branch + // node, and is the document object itself (meaning it has + // additional methods and properties). + // + // All nodes have parent links. The tree is used both to go from + // line numbers to line objects, and to go from objects to numbers. + // It also indexes by height, and is used to convert between height + // and line object, and to find the total height of the document. + // + // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html + + function LeafChunk(lines) { + var this$1 = this; + + this.lines = lines; + this.parent = null; + var height = 0; + for (var i = 0; i < lines.length; ++i) { + lines[i].parent = this$1; + height += lines[i].height; + } + this.height = height; + } + + LeafChunk.prototype = { + chunkSize: function() { return this.lines.length }, + + // Remove the n lines at offset 'at'. + removeInner: function(at, n) { + var this$1 = this; + + for (var i = at, e = at + n; i < e; ++i) { + var line = this$1.lines[i]; + this$1.height -= line.height; + cleanUpLine(line); + signalLater(line, "delete"); + } + this.lines.splice(at, n); + }, + + // Helper used to collapse a small branch into a single leaf. + collapse: function(lines) { + lines.push.apply(lines, this.lines); + }, + + // Insert the given array of lines at offset 'at', count them as + // having the given height. + insertInner: function(at, lines, height) { + var this$1 = this; + + this.height += height; + this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); + for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; } + }, + + // Used to iterate over a part of the tree. + iterN: function(at, n, op) { + var this$1 = this; + + for (var e = at + n; at < e; ++at) + { if (op(this$1.lines[at])) { return true } } + } + }; + + function BranchChunk(children) { + var this$1 = this; + + this.children = children; + var size = 0, height = 0; + for (var i = 0; i < children.length; ++i) { + var ch = children[i]; + size += ch.chunkSize(); height += ch.height; + ch.parent = this$1; + } + this.size = size; + this.height = height; + this.parent = null; + } + + BranchChunk.prototype = { + chunkSize: function() { return this.size }, + + removeInner: function(at, n) { + var this$1 = this; + + this.size -= n; + for (var i = 0; i < this.children.length; ++i) { + var child = this$1.children[i], sz = child.chunkSize(); + if (at < sz) { + var rm = Math.min(n, sz - at), oldHeight = child.height; + child.removeInner(at, rm); + this$1.height -= oldHeight - child.height; + if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; } + if ((n -= rm) == 0) { break } + at = 0; + } else { at -= sz; } + } + // If the result is smaller than 25 lines, ensure that it is a + // single leaf node. + if (this.size - n < 25 && + (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { + var lines = []; + this.collapse(lines); + this.children = [new LeafChunk(lines)]; + this.children[0].parent = this; + } + }, + + collapse: function(lines) { + var this$1 = this; + + for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); } + }, + + insertInner: function(at, lines, height) { + var this$1 = this; + + this.size += lines.length; + this.height += height; + for (var i = 0; i < this.children.length; ++i) { + var child = this$1.children[i], sz = child.chunkSize(); + if (at <= sz) { + child.insertInner(at, lines, height); + if (child.lines && child.lines.length > 50) { + // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. + // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. + var remaining = child.lines.length % 25 + 25; + for (var pos = remaining; pos < child.lines.length;) { + var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); + child.height -= leaf.height; + this$1.children.splice(++i, 0, leaf); + leaf.parent = this$1; + } + child.lines = child.lines.slice(0, remaining); + this$1.maybeSpill(); + } + break + } + at -= sz; + } + }, + + // When a node has grown, check whether it should be split. + maybeSpill: function() { + if (this.children.length <= 10) { return } + var me = this; + do { + var spilled = me.children.splice(me.children.length - 5, 5); + var sibling = new BranchChunk(spilled); + if (!me.parent) { // Become the parent node + var copy = new BranchChunk(me.children); + copy.parent = me; + me.children = [copy, sibling]; + me = copy; + } else { + me.size -= sibling.size; + me.height -= sibling.height; + var myIndex = indexOf(me.parent.children, me); + me.parent.children.splice(myIndex + 1, 0, sibling); + } + sibling.parent = me.parent; + } while (me.children.length > 10) + me.parent.maybeSpill(); + }, + + iterN: function(at, n, op) { + var this$1 = this; + + for (var i = 0; i < this.children.length; ++i) { + var child = this$1.children[i], sz = child.chunkSize(); + if (at < sz) { + var used = Math.min(n, sz - at); + if (child.iterN(at, used, op)) { return true } + if ((n -= used) == 0) { break } + at = 0; + } else { at -= sz; } + } + } + }; + + // Line widgets are block elements displayed above or below a line. + + var LineWidget = function(doc, node, options) { + var this$1 = this; + + if (options) { for (var opt in options) { if (options.hasOwnProperty(opt)) + { this$1[opt] = options[opt]; } } } + this.doc = doc; + this.node = node; + }; + + LineWidget.prototype.clear = function () { + var this$1 = this; + + var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); + if (no == null || !ws) { return } + for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } } + if (!ws.length) { line.widgets = null; } + var height = widgetHeight(this); + updateLineHeight(line, Math.max(0, line.height - height)); + if (cm) { + runInOp(cm, function () { + adjustScrollWhenAboveVisible(cm, line, -height); + regLineChange(cm, no, "widget"); + }); + signalLater(cm, "lineWidgetCleared", cm, this, no); + } + }; + + LineWidget.prototype.changed = function () { + var this$1 = this; + + var oldH = this.height, cm = this.doc.cm, line = this.line; + this.height = null; + var diff = widgetHeight(this) - oldH; + if (!diff) { return } + if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); } + if (cm) { + runInOp(cm, function () { + cm.curOp.forceUpdate = true; + adjustScrollWhenAboveVisible(cm, line, diff); + signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line)); + }); + } + }; + eventMixin(LineWidget); + + function adjustScrollWhenAboveVisible(cm, line, diff) { + if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) + { addToScrollTop(cm, diff); } + } + + function addLineWidget(doc, handle, node, options) { + var widget = new LineWidget(doc, node, options); + var cm = doc.cm; + if (cm && widget.noHScroll) { cm.display.alignWidgets = true; } + changeLine(doc, handle, "widget", function (line) { + var widgets = line.widgets || (line.widgets = []); + if (widget.insertAt == null) { widgets.push(widget); } + else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); } + widget.line = line; + if (cm && !lineIsHidden(doc, line)) { + var aboveVisible = heightAtLine(line) < doc.scrollTop; + updateLineHeight(line, line.height + widgetHeight(widget)); + if (aboveVisible) { addToScrollTop(cm, widget.height); } + cm.curOp.forceUpdate = true; + } + return true + }); + if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); } + return widget + } + + // TEXTMARKERS + + // Created with markText and setBookmark methods. A TextMarker is a + // handle that can be used to clear or find a marked position in the + // document. Line objects hold arrays (markedSpans) containing + // {from, to, marker} object pointing to such marker objects, and + // indicating that such a marker is present on that line. Multiple + // lines may point to the same marker when it spans across lines. + // The spans will have null for their from/to properties when the + // marker continues beyond the start/end of the line. Markers have + // links back to the lines they currently touch. + + // Collapsed markers have unique ids, in order to be able to order + // them, which is needed for uniquely determining an outer marker + // when they overlap (they may nest, but not partially overlap). + var nextMarkerId = 0; + + var TextMarker = function(doc, type) { + this.lines = []; + this.type = type; + this.doc = doc; + this.id = ++nextMarkerId; + }; + + // Clear the marker. + TextMarker.prototype.clear = function () { + var this$1 = this; + + if (this.explicitlyCleared) { return } + var cm = this.doc.cm, withOp = cm && !cm.curOp; + if (withOp) { startOperation(cm); } + if (hasHandler(this, "clear")) { + var found = this.find(); + if (found) { signalLater(this, "clear", found.from, found.to); } + } + var min = null, max = null; + for (var i = 0; i < this.lines.length; ++i) { + var line = this$1.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this$1); + if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); } + else if (cm) { + if (span.to != null) { max = lineNo(line); } + if (span.from != null) { min = lineNo(line); } + } + line.markedSpans = removeMarkedSpan(line.markedSpans, span); + if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm) + { updateLineHeight(line, textHeight(cm.display)); } + } + if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) { + var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual); + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual; + cm.display.maxLineLength = len; + cm.display.maxLineChanged = true; + } + } } + + if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); } + this.lines.length = 0; + this.explicitlyCleared = true; + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false; + if (cm) { reCheckSelection(cm.doc); } + } + if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); } + if (withOp) { endOperation(cm); } + if (this.parent) { this.parent.clear(); } + }; + + // Find the position of the marker in the document. Returns a {from, + // to} object by default. Side can be passed to get a specific side + // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the + // Pos objects returned contain a line object, rather than a line + // number (used to prevent looking up the same line twice). + TextMarker.prototype.find = function (side, lineObj) { + var this$1 = this; + + if (side == null && this.type == "bookmark") { side = 1; } + var from, to; + for (var i = 0; i < this.lines.length; ++i) { + var line = this$1.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this$1); + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from); + if (side == -1) { return from } + } + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to); + if (side == 1) { return to } + } + } + return from && {from: from, to: to} + }; + + // Signals that the marker's widget changed, and surrounding layout + // should be recomputed. + TextMarker.prototype.changed = function () { + var this$1 = this; + + var pos = this.find(-1, true), widget = this, cm = this.doc.cm; + if (!pos || !cm) { return } + runInOp(cm, function () { + var line = pos.line, lineN = lineNo(pos.line); + var view = findViewForLine(cm, lineN); + if (view) { + clearLineMeasurementCacheFor(view); + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; + } + cm.curOp.updateMaxLine = true; + if (!lineIsHidden(widget.doc, line) && widget.height != null) { + var oldHeight = widget.height; + widget.height = null; + var dHeight = widgetHeight(widget) - oldHeight; + if (dHeight) + { updateLineHeight(line, line.height + dHeight); } + } + signalLater(cm, "markerChanged", cm, this$1); + }); + }; + + TextMarker.prototype.attachLine = function (line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) + { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); } + } + this.lines.push(line); + }; + + TextMarker.prototype.detachLine = function (line) { + this.lines.splice(indexOf(this.lines, line), 1); + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp + ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); + } + }; + eventMixin(TextMarker); + + // Create a marker, wire it up to the right lines, and + function markText(doc, from, to, options, type) { + // Shared markers (across linked documents) are handled separately + // (markTextShared will call out to this again, once per + // document). + if (options && options.shared) { return markTextShared(doc, from, to, options, type) } + // Ensure we are in an operation. + if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) } + + var marker = new TextMarker(doc, type), diff = cmp(from, to); + if (options) { copyObj(options, marker, false); } + // Don't connect empty markers unless clearWhenEmpty is false + if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) + { return marker } + if (marker.replacedWith) { + // Showing up as a widget implies collapsed (widget replaces text) + marker.collapsed = true; + marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); + if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); } + if (options.insertLeft) { marker.widgetNode.insertLeft = true; } + } + if (marker.collapsed) { + if (conflictingCollapsedRange(doc, from.line, from, to, marker) || + from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) + { throw new Error("Inserting collapsed marker partially overlapping an existing one") } + seeCollapsedSpans(); + } + + if (marker.addToHistory) + { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); } + + var curLine = from.line, cm = doc.cm, updateMaxLine; + doc.iter(curLine, to.line + 1, function (line) { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) + { updateMaxLine = true; } + if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); } + addMarkedSpan(line, new MarkedSpan(marker, + curLine == from.line ? from.ch : null, + curLine == to.line ? to.ch : null)); + ++curLine; + }); + // lineIsHidden depends on the presence of the spans, so needs a second pass + if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) { + if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); } + }); } + + if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); } + + if (marker.readOnly) { + seeReadOnlySpans(); + if (doc.history.done.length || doc.history.undone.length) + { doc.clearHistory(); } + } + if (marker.collapsed) { + marker.id = ++nextMarkerId; + marker.atomic = true; + } + if (cm) { + // Sync editor state + if (updateMaxLine) { cm.curOp.updateMaxLine = true; } + if (marker.collapsed) + { regChange(cm, from.line, to.line + 1); } + else if (marker.className || marker.startStyle || marker.endStyle || marker.css || + marker.attributes || marker.title) + { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } } + if (marker.atomic) { reCheckSelection(cm.doc); } + signalLater(cm, "markerAdded", cm, marker); + } + return marker + } + + // SHARED TEXTMARKERS + + // A shared marker spans multiple linked documents. It is + // implemented as a meta-marker-object controlling multiple normal + // markers. + var SharedTextMarker = function(markers, primary) { + var this$1 = this; + + this.markers = markers; + this.primary = primary; + for (var i = 0; i < markers.length; ++i) + { markers[i].parent = this$1; } + }; + + SharedTextMarker.prototype.clear = function () { + var this$1 = this; + + if (this.explicitlyCleared) { return } + this.explicitlyCleared = true; + for (var i = 0; i < this.markers.length; ++i) + { this$1.markers[i].clear(); } + signalLater(this, "clear"); + }; + + SharedTextMarker.prototype.find = function (side, lineObj) { + return this.primary.find(side, lineObj) + }; + eventMixin(SharedTextMarker); + + function markTextShared(doc, from, to, options, type) { + options = copyObj(options); + options.shared = false; + var markers = [markText(doc, from, to, options, type)], primary = markers[0]; + var widget = options.widgetNode; + linkedDocs(doc, function (doc) { + if (widget) { options.widgetNode = widget.cloneNode(true); } + markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); + for (var i = 0; i < doc.linked.length; ++i) + { if (doc.linked[i].isParent) { return } } + primary = lst(markers); + }); + return new SharedTextMarker(markers, primary) + } + + function findSharedMarkers(doc) { + return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; }) + } + + function copySharedMarkers(doc, markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], pos = marker.find(); + var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); + if (cmp(mFrom, mTo)) { + var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); + marker.markers.push(subMark); + subMark.parent = marker; + } + } + } + + function detachSharedMarkers(markers) { + var loop = function ( i ) { + var marker = markers[i], linked = [marker.primary.doc]; + linkedDocs(marker.primary.doc, function (d) { return linked.push(d); }); + for (var j = 0; j < marker.markers.length; j++) { + var subMarker = marker.markers[j]; + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null; + marker.markers.splice(j--, 1); + } + } + }; + + for (var i = 0; i < markers.length; i++) loop( i ); + } + + var nextDocId = 0; + var Doc = function(text, mode, firstLine, lineSep, direction) { + if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) } + if (firstLine == null) { firstLine = 0; } + + BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); + this.first = firstLine; + this.scrollTop = this.scrollLeft = 0; + this.cantEdit = false; + this.cleanGeneration = 1; + this.modeFrontier = this.highlightFrontier = firstLine; + var start = Pos(firstLine, 0); + this.sel = simpleSelection(start); + this.history = new History(null); + this.id = ++nextDocId; + this.modeOption = mode; + this.lineSep = lineSep; + this.direction = (direction == "rtl") ? "rtl" : "ltr"; + this.extend = false; + + if (typeof text == "string") { text = this.splitLines(text); } + updateDoc(this, {from: start, to: start, text: text}); + setSelection(this, simpleSelection(start), sel_dontScroll); + }; + + Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + // Iterate over the document. Supports two forms -- with only one + // argument, it calls that for each line in the document. With + // three, it iterates over the range given by the first two (with + // the second being non-inclusive). + iter: function(from, to, op) { + if (op) { this.iterN(from - this.first, to - from, op); } + else { this.iterN(this.first, this.first + this.size, from); } + }, + + // Non-public interface for adding and removing lines. + insert: function(at, lines) { + var height = 0; + for (var i = 0; i < lines.length; ++i) { height += lines[i].height; } + this.insertInner(at - this.first, lines, height); + }, + remove: function(at, n) { this.removeInner(at - this.first, n); }, + + // From here, the methods are part of the public interface. Most + // are also available from CodeMirror (editor) instances. + + getValue: function(lineSep) { + var lines = getLines(this, this.first, this.first + this.size); + if (lineSep === false) { return lines } + return lines.join(lineSep || this.lineSeparator()) + }, + setValue: docMethodOp(function(code) { + var top = Pos(this.first, 0), last = this.first + this.size - 1; + makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), + text: this.splitLines(code), origin: "setValue", full: true}, true); + if (this.cm) { scrollToCoords(this.cm, 0, 0); } + setSelection(this, simpleSelection(top), sel_dontScroll); + }), + replaceRange: function(code, from, to, origin) { + from = clipPos(this, from); + to = to ? clipPos(this, to) : from; + replaceRange(this, code, from, to, origin); + }, + getRange: function(from, to, lineSep) { + var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); + if (lineSep === false) { return lines } + return lines.join(lineSep || this.lineSeparator()) + }, + + getLine: function(line) {var l = this.getLineHandle(line); return l && l.text}, + + getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }}, + getLineNumber: function(line) {return lineNo(line)}, + + getLineHandleVisualStart: function(line) { + if (typeof line == "number") { line = getLine(this, line); } + return visualLine(line) + }, + + lineCount: function() {return this.size}, + firstLine: function() {return this.first}, + lastLine: function() {return this.first + this.size - 1}, + + clipPos: function(pos) {return clipPos(this, pos)}, + + getCursor: function(start) { + var range$$1 = this.sel.primary(), pos; + if (start == null || start == "head") { pos = range$$1.head; } + else if (start == "anchor") { pos = range$$1.anchor; } + else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); } + else { pos = range$$1.from(); } + return pos + }, + listSelections: function() { return this.sel.ranges }, + somethingSelected: function() {return this.sel.somethingSelected()}, + + setCursor: docMethodOp(function(line, ch, options) { + setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); + }), + setSelection: docMethodOp(function(anchor, head, options) { + setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); + }), + extendSelection: docMethodOp(function(head, other, options) { + extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); + }), + extendSelections: docMethodOp(function(heads, options) { + extendSelections(this, clipPosArray(this, heads), options); + }), + extendSelectionsBy: docMethodOp(function(f, options) { + var heads = map(this.sel.ranges, f); + extendSelections(this, clipPosArray(this, heads), options); + }), + setSelections: docMethodOp(function(ranges, primary, options) { + var this$1 = this; + + if (!ranges.length) { return } + var out = []; + for (var i = 0; i < ranges.length; i++) + { out[i] = new Range(clipPos(this$1, ranges[i].anchor), + clipPos(this$1, ranges[i].head)); } + if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); } + setSelection(this, normalizeSelection(this.cm, out, primary), options); + }), + addSelection: docMethodOp(function(anchor, head, options) { + var ranges = this.sel.ranges.slice(0); + ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); + setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options); + }), + + getSelection: function(lineSep) { + var this$1 = this; + + var ranges = this.sel.ranges, lines; + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()); + lines = lines ? lines.concat(sel) : sel; + } + if (lineSep === false) { return lines } + else { return lines.join(lineSep || this.lineSeparator()) } + }, + getSelections: function(lineSep) { + var this$1 = this; + + var parts = [], ranges = this.sel.ranges; + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()); + if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); } + parts[i] = sel; + } + return parts + }, + replaceSelection: function(code, collapse, origin) { + var dup = []; + for (var i = 0; i < this.sel.ranges.length; i++) + { dup[i] = code; } + this.replaceSelections(dup, collapse, origin || "+input"); + }, + replaceSelections: docMethodOp(function(code, collapse, origin) { + var this$1 = this; + + var changes = [], sel = this.sel; + for (var i = 0; i < sel.ranges.length; i++) { + var range$$1 = sel.ranges[i]; + changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin}; + } + var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); + for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) + { makeChange(this$1, changes[i$1]); } + if (newSel) { setSelectionReplaceHistory(this, newSel); } + else if (this.cm) { ensureCursorVisible(this.cm); } + }), + undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), + redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), + undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), + redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), + + setExtending: function(val) {this.extend = val;}, + getExtending: function() {return this.extend}, + + historySize: function() { + var hist = this.history, done = 0, undone = 0; + for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } } + for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } } + return {undo: done, redo: undone} + }, + clearHistory: function() {this.history = new History(this.history.maxGeneration);}, + + markClean: function() { + this.cleanGeneration = this.changeGeneration(true); + }, + changeGeneration: function(forceSplit) { + if (forceSplit) + { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; } + return this.history.generation + }, + isClean: function (gen) { + return this.history.generation == (gen || this.cleanGeneration) + }, + + getHistory: function() { + return {done: copyHistoryArray(this.history.done), + undone: copyHistoryArray(this.history.undone)} + }, + setHistory: function(histData) { + var hist = this.history = new History(this.history.maxGeneration); + hist.done = copyHistoryArray(histData.done.slice(0), null, true); + hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); + }, + + setGutterMarker: docMethodOp(function(line, gutterID, value) { + return changeLine(this, line, "gutter", function (line) { + var markers = line.gutterMarkers || (line.gutterMarkers = {}); + markers[gutterID] = value; + if (!value && isEmpty(markers)) { line.gutterMarkers = null; } + return true + }) + }), + + clearGutter: docMethodOp(function(gutterID) { + var this$1 = this; + + this.iter(function (line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + changeLine(this$1, line, "gutter", function () { + line.gutterMarkers[gutterID] = null; + if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; } + return true + }); + } + }); + }), + + lineInfo: function(line) { + var n; + if (typeof line == "number") { + if (!isLine(this, line)) { return null } + n = line; + line = getLine(this, line); + if (!line) { return null } + } else { + n = lineNo(line); + if (n == null) { return null } + } + return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, + textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, + widgets: line.widgets} + }, + + addLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass"; + if (!line[prop]) { line[prop] = cls; } + else if (classTest(cls).test(line[prop])) { return false } + else { line[prop] += " " + cls; } + return true + }) + }), + removeLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass"; + var cur = line[prop]; + if (!cur) { return false } + else if (cls == null) { line[prop] = null; } + else { + var found = cur.match(classTest(cls)); + if (!found) { return false } + var end = found.index + found[0].length; + line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; + } + return true + }) + }), + + addLineWidget: docMethodOp(function(handle, node, options) { + return addLineWidget(this, handle, node, options) + }), + removeLineWidget: function(widget) { widget.clear(); }, + + markText: function(from, to, options) { + return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range") + }, + setBookmark: function(pos, options) { + var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft, + clearWhenEmpty: false, shared: options && options.shared, + handleMouseEvents: options && options.handleMouseEvents}; + pos = clipPos(this, pos); + return markText(this, pos, pos, realOpts, "bookmark") + }, + findMarksAt: function(pos) { + pos = clipPos(this, pos); + var markers = [], spans = getLine(this, pos.line).markedSpans; + if (spans) { for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if ((span.from == null || span.from <= pos.ch) && + (span.to == null || span.to >= pos.ch)) + { markers.push(span.marker.parent || span.marker); } + } } + return markers + }, + findMarks: function(from, to, filter) { + from = clipPos(this, from); to = clipPos(this, to); + var found = [], lineNo$$1 = from.line; + this.iter(from.line, to.line + 1, function (line) { + var spans = line.markedSpans; + if (spans) { for (var i = 0; i < spans.length; i++) { + var span = spans[i]; + if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to || + span.from == null && lineNo$$1 != from.line || + span.from != null && lineNo$$1 == to.line && span.from >= to.ch) && + (!filter || filter(span.marker))) + { found.push(span.marker.parent || span.marker); } + } } + ++lineNo$$1; + }); + return found + }, + getAllMarks: function() { + var markers = []; + this.iter(function (line) { + var sps = line.markedSpans; + if (sps) { for (var i = 0; i < sps.length; ++i) + { if (sps[i].from != null) { markers.push(sps[i].marker); } } } + }); + return markers + }, + + posFromIndex: function(off) { + var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length; + this.iter(function (line) { + var sz = line.text.length + sepSize; + if (sz > off) { ch = off; return true } + off -= sz; + ++lineNo$$1; + }); + return clipPos(this, Pos(lineNo$$1, ch)) + }, + indexFromPos: function (coords) { + coords = clipPos(this, coords); + var index = coords.ch; + if (coords.line < this.first || coords.ch < 0) { return 0 } + var sepSize = this.lineSeparator().length; + this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value + index += line.text.length + sepSize; + }); + return index + }, + + copy: function(copyHistory) { + var doc = new Doc(getLines(this, this.first, this.first + this.size), + this.modeOption, this.first, this.lineSep, this.direction); + doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; + doc.sel = this.sel; + doc.extend = false; + if (copyHistory) { + doc.history.undoDepth = this.history.undoDepth; + doc.setHistory(this.getHistory()); + } + return doc + }, + + linkedDoc: function(options) { + if (!options) { options = {}; } + var from = this.first, to = this.first + this.size; + if (options.from != null && options.from > from) { from = options.from; } + if (options.to != null && options.to < to) { to = options.to; } + var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); + if (options.sharedHist) { copy.history = this.history + ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); + copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; + copySharedMarkers(copy, findSharedMarkers(this)); + return copy + }, + unlinkDoc: function(other) { + var this$1 = this; + + if (other instanceof CodeMirror) { other = other.doc; } + if (this.linked) { for (var i = 0; i < this.linked.length; ++i) { + var link = this$1.linked[i]; + if (link.doc != other) { continue } + this$1.linked.splice(i, 1); + other.unlinkDoc(this$1); + detachSharedMarkers(findSharedMarkers(this$1)); + break + } } + // If the histories were shared, split them again + if (other.history == this.history) { + var splitIds = [other.id]; + linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true); + other.history = new History(null); + other.history.done = copyHistoryArray(this.history.done, splitIds); + other.history.undone = copyHistoryArray(this.history.undone, splitIds); + } + }, + iterLinkedDocs: function(f) {linkedDocs(this, f);}, + + getMode: function() {return this.mode}, + getEditor: function() {return this.cm}, + + splitLines: function(str) { + if (this.lineSep) { return str.split(this.lineSep) } + return splitLinesAuto(str) + }, + lineSeparator: function() { return this.lineSep || "\n" }, + + setDirection: docMethodOp(function (dir) { + if (dir != "rtl") { dir = "ltr"; } + if (dir == this.direction) { return } + this.direction = dir; + this.iter(function (line) { return line.order = null; }); + if (this.cm) { directionChanged(this.cm); } + }) + }); + + // Public alias. + Doc.prototype.eachLine = Doc.prototype.iter; + + // Kludge to work around strange IE behavior where it'll sometimes + // re-fire a series of drag-related events right after the drop (#1551) + var lastDrop = 0; + + function onDrop(e) { + var cm = this; + clearDragCursor(cm); + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) + { return } + e_preventDefault(e); + if (ie) { lastDrop = +new Date; } + var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; + if (!pos || cm.isReadOnly()) { return } + // Might be a file drop, in which case we simply extract the text + // and insert it. + if (files && files.length && window.FileReader && window.File) { + var n = files.length, text = Array(n), read = 0; + var loadFile = function (file, i) { + if (cm.options.allowDropFileTypes && + indexOf(cm.options.allowDropFileTypes, file.type) == -1) + { return } + + var reader = new FileReader; + reader.onload = operation(cm, function () { + var content = reader.result; + if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; } + text[i] = content; + if (++read == n) { + pos = clipPos(cm.doc, pos); + var change = {from: pos, to: pos, + text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), + origin: "paste"}; + makeChange(cm.doc, change); + setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); + } + }); + reader.readAsText(file); + }; + for (var i = 0; i < n; ++i) { loadFile(files[i], i); } + } else { // Normal drop + // Don't do a replace if the drop happened inside of the selected text. + if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { + cm.state.draggingText(e); + // Ensure the editor is re-focused + setTimeout(function () { return cm.display.input.focus(); }, 20); + return + } + try { + var text$1 = e.dataTransfer.getData("Text"); + if (text$1) { + var selected; + if (cm.state.draggingText && !cm.state.draggingText.copy) + { selected = cm.listSelections(); } + setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); + if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1) + { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } } + cm.replaceSelection(text$1, "around", "paste"); + cm.display.input.focus(); + } + } + catch(e){} + } + } + + function onDragStart(cm, e) { + if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return } + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } + + e.dataTransfer.setData("Text", cm.getSelection()); + e.dataTransfer.effectAllowed = "copyMove"; + + // Use dummy image instead of default browsers image. + // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. + if (e.dataTransfer.setDragImage && !safari) { + var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); + img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; + if (presto) { + img.width = img.height = 1; + cm.display.wrapper.appendChild(img); + // Force a relayout, or Opera won't use our image for some obscure reason + img._top = img.offsetTop; + } + e.dataTransfer.setDragImage(img, 0, 0); + if (presto) { img.parentNode.removeChild(img); } + } + } + + function onDragOver(cm, e) { + var pos = posFromMouse(cm, e); + if (!pos) { return } + var frag = document.createDocumentFragment(); + drawSelectionCursor(cm, pos, frag); + if (!cm.display.dragCursor) { + cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); + cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); + } + removeChildrenAndAdd(cm.display.dragCursor, frag); + } + + function clearDragCursor(cm) { + if (cm.display.dragCursor) { + cm.display.lineSpace.removeChild(cm.display.dragCursor); + cm.display.dragCursor = null; + } + } + + // These must be handled carefully, because naively registering a + // handler for each editor will cause the editors to never be + // garbage collected. + + function forEachCodeMirror(f) { + if (!document.getElementsByClassName) { return } + var byClass = document.getElementsByClassName("CodeMirror"), editors = []; + for (var i = 0; i < byClass.length; i++) { + var cm = byClass[i].CodeMirror; + if (cm) { editors.push(cm); } + } + if (editors.length) { editors[0].operation(function () { + for (var i = 0; i < editors.length; i++) { f(editors[i]); } + }); } + } + + var globalsRegistered = false; + function ensureGlobalHandlers() { + if (globalsRegistered) { return } + registerGlobalHandlers(); + globalsRegistered = true; + } + function registerGlobalHandlers() { + // When the window resizes, we need to refresh active editors. + var resizeTimer; + on(window, "resize", function () { + if (resizeTimer == null) { resizeTimer = setTimeout(function () { + resizeTimer = null; + forEachCodeMirror(onResize); + }, 100); } + }); + // When the window loses focus, we want to show the editor as blurred + on(window, "blur", function () { return forEachCodeMirror(onBlur); }); + } + // Called when the window resizes + function onResize(cm) { + var d = cm.display; + // Might be a text scaling operation, clear size caches. + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + d.scrollbarsClipped = false; + cm.setSize(); + } + + var keyNames = { + 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", + 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", + 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", + 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", + 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock", + 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", + 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", + 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" + }; + + // Number keys + for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); } + // Alphabetic keys + for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); } + // Function keys + for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; } + + var keyMap = {}; + + keyMap.basic = { + "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", + "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", + "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", + "Tab": "defaultTab", "Shift-Tab": "indentAuto", + "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", + "Esc": "singleSelection" + }; + // Note that the save and find-related commands aren't defined by + // default. User code or addons can define them. Unknown commands + // are simply ignored. + keyMap.pcDefault = { + "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", + "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", + "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", + "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", + "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", + "fallthrough": "basic" + }; + // Very basic readline/emacs-style bindings, which are standard on Mac. + keyMap.emacsy = { + "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", + "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", + "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", + "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", + "Ctrl-O": "openLine" + }; + keyMap.macDefault = { + "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", + "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", + "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", + "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", + "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", + "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", + "fallthrough": ["basic", "emacsy"] + }; + keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; + + // KEYMAP DISPATCH + + function normalizeKeyName(name) { + var parts = name.split(/-(?!$)/); + name = parts[parts.length - 1]; + var alt, ctrl, shift, cmd; + for (var i = 0; i < parts.length - 1; i++) { + var mod = parts[i]; + if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; } + else if (/^a(lt)?$/i.test(mod)) { alt = true; } + else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; } + else if (/^s(hift)?$/i.test(mod)) { shift = true; } + else { throw new Error("Unrecognized modifier name: " + mod) } + } + if (alt) { name = "Alt-" + name; } + if (ctrl) { name = "Ctrl-" + name; } + if (cmd) { name = "Cmd-" + name; } + if (shift) { name = "Shift-" + name; } + return name + } + + // This is a kludge to keep keymaps mostly working as raw objects + // (backwards compatibility) while at the same time support features + // like normalization and multi-stroke key bindings. It compiles a + // new normalized keymap, and then updates the old object to reflect + // this. + function normalizeKeyMap(keymap) { + var copy = {}; + for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) { + var value = keymap[keyname]; + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue } + if (value == "...") { delete keymap[keyname]; continue } + + var keys = map(keyname.split(" "), normalizeKeyName); + for (var i = 0; i < keys.length; i++) { + var val = (void 0), name = (void 0); + if (i == keys.length - 1) { + name = keys.join(" "); + val = value; + } else { + name = keys.slice(0, i + 1).join(" "); + val = "..."; + } + var prev = copy[name]; + if (!prev) { copy[name] = val; } + else if (prev != val) { throw new Error("Inconsistent bindings for " + name) } + } + delete keymap[keyname]; + } } + for (var prop in copy) { keymap[prop] = copy[prop]; } + return keymap + } + + function lookupKey(key, map$$1, handle, context) { + map$$1 = getKeyMap(map$$1); + var found = map$$1.call ? map$$1.call(key, context) : map$$1[key]; + if (found === false) { return "nothing" } + if (found === "...") { return "multi" } + if (found != null && handle(found)) { return "handled" } + + if (map$$1.fallthrough) { + if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]") + { return lookupKey(key, map$$1.fallthrough, handle, context) } + for (var i = 0; i < map$$1.fallthrough.length; i++) { + var result = lookupKey(key, map$$1.fallthrough[i], handle, context); + if (result) { return result } + } + } + } + + // Modifier key presses don't count as 'real' key presses for the + // purpose of keymap fallthrough. + function isModifierKey(value) { + var name = typeof value == "string" ? value : keyNames[value.keyCode]; + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" + } + + function addModifierNames(name, event, noShift) { + var base = name; + if (event.altKey && base != "Alt") { name = "Alt-" + name; } + if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; } + if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; } + if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; } + return name + } + + // Look up the name of a key as indicated by an event object. + function keyName(event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) { return false } + var name = keyNames[event.keyCode]; + if (name == null || event.altGraphKey) { return false } + // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause, + // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+) + if (event.keyCode == 3 && event.code) { name = event.code; } + return addModifierNames(name, event, noShift) + } + + function getKeyMap(val) { + return typeof val == "string" ? keyMap[val] : val + } + + // Helper for deleting text near the selection(s), used to implement + // backspace, delete, and similar functionality. + function deleteNearSelection(cm, compute) { + var ranges = cm.doc.sel.ranges, kill = []; + // Build up a set of ranges to kill first, merging overlapping + // ranges. + for (var i = 0; i < ranges.length; i++) { + var toKill = compute(ranges[i]); + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + var replaced = kill.pop(); + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from; + break + } + } + kill.push(toKill); + } + // Next, remove those actual ranges. + runInOp(cm, function () { + for (var i = kill.length - 1; i >= 0; i--) + { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); } + ensureCursorVisible(cm); + }); + } + + function moveCharLogically(line, ch, dir) { + var target = skipExtendingChars(line.text, ch + dir, dir); + return target < 0 || target > line.text.length ? null : target + } + + function moveLogically(line, start, dir) { + var ch = moveCharLogically(line, start.ch, dir); + return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before") + } + + function endOfLine(visually, cm, lineObj, lineNo, dir) { + if (visually) { + var order = getOrder(lineObj, cm.doc.direction); + if (order) { + var part = dir < 0 ? lst(order) : order[0]; + var moveInStorageOrder = (dir < 0) == (part.level == 1); + var sticky = moveInStorageOrder ? "after" : "before"; + var ch; + // With a wrapped rtl chunk (possibly spanning multiple bidi parts), + // it could be that the last bidi part is not on the last visual line, + // since visual lines contain content order-consecutive chunks. + // Thus, in rtl, we are looking for the first (content-order) character + // in the rtl chunk that is on the last line (that is, the same line + // as the last (content-order) character). + if (part.level > 0 || cm.doc.direction == "rtl") { + var prep = prepareMeasureForLine(cm, lineObj); + ch = dir < 0 ? lineObj.text.length - 1 : 0; + var targetTop = measureCharPrepared(cm, prep, ch).top; + ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch); + if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); } + } else { ch = dir < 0 ? part.to : part.from; } + return new Pos(lineNo, ch, sticky) + } + } + return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after") + } + + function moveVisually(cm, line, start, dir) { + var bidi = getOrder(line, cm.doc.direction); + if (!bidi) { return moveLogically(line, start, dir) } + if (start.ch >= line.text.length) { + start.ch = line.text.length; + start.sticky = "before"; + } else if (start.ch <= 0) { + start.ch = 0; + start.sticky = "after"; + } + var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]; + if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { + // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines, + // nothing interesting happens. + return moveLogically(line, start, dir) + } + + var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }; + var prep; + var getWrappedLineExtent = function (ch) { + if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} } + prep = prep || prepareMeasureForLine(cm, line); + return wrappedLineExtentChar(cm, line, prep, ch) + }; + var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); + + if (cm.doc.direction == "rtl" || part.level == 1) { + var moveInStorageOrder = (part.level == 1) == (dir < 0); + var ch = mv(start, moveInStorageOrder ? 1 : -1); + if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) { + // Case 2: We move within an rtl part or in an rtl editor on the same visual line + var sticky = moveInStorageOrder ? "before" : "after"; + return new Pos(start.line, ch, sticky) + } + } + + // Case 3: Could not move within this bidi part in this visual line, so leave + // the current bidi part + + var searchInVisualLine = function (partPos, dir, wrappedLineExtent) { + var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder + ? new Pos(start.line, mv(ch, 1), "before") + : new Pos(start.line, ch, "after"); }; + + for (; partPos >= 0 && partPos < bidi.length; partPos += dir) { + var part = bidi[partPos]; + var moveInStorageOrder = (dir > 0) == (part.level != 1); + var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1); + if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) } + ch = moveInStorageOrder ? part.from : mv(part.to, -1); + if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) } + } + }; + + // Case 3a: Look for other bidi parts on the same visual line + var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent); + if (res) { return res } + + // Case 3b: Look for other bidi parts on the next visual line + var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1); + if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { + res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); + if (res) { return res } + } + + // Case 4: Nowhere to move + return null + } + + // Commands are parameter-less actions that can be performed on an + // editor, mostly used for keybindings. + var commands = { + selectAll: selectAll, + singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); }, + killLine: function (cm) { return deleteNearSelection(cm, function (range) { + if (range.empty()) { + var len = getLine(cm.doc, range.head.line).text.length; + if (range.head.ch == len && range.head.line < cm.lastLine()) + { return {from: range.head, to: Pos(range.head.line + 1, 0)} } + else + { return {from: range.head, to: Pos(range.head.line, len)} } + } else { + return {from: range.from(), to: range.to()} + } + }); }, + deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({ + from: Pos(range.from().line, 0), + to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) + }); }); }, + delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({ + from: Pos(range.from().line, 0), to: range.from() + }); }); }, + delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + var leftPos = cm.coordsChar({left: 0, top: top}, "div"); + return {from: leftPos, to: range.from()} + }); }, + delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); + return {from: range.from(), to: rightPos } + }); }, + undo: function (cm) { return cm.undo(); }, + redo: function (cm) { return cm.redo(); }, + undoSelection: function (cm) { return cm.undoSelection(); }, + redoSelection: function (cm) { return cm.redoSelection(); }, + goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); }, + goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); }, + goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, + {origin: "+move", bias: 1} + ); }, + goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); }, + {origin: "+move", bias: 1} + ); }, + goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, + {origin: "+move", bias: -1} + ); }, + goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.cursorCoords(range.head, "div").top + 5; + return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") + }, sel_move); }, + goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.cursorCoords(range.head, "div").top + 5; + return cm.coordsChar({left: 0, top: top}, "div") + }, sel_move); }, + goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.cursorCoords(range.head, "div").top + 5; + var pos = cm.coordsChar({left: 0, top: top}, "div"); + if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) } + return pos + }, sel_move); }, + goLineUp: function (cm) { return cm.moveV(-1, "line"); }, + goLineDown: function (cm) { return cm.moveV(1, "line"); }, + goPageUp: function (cm) { return cm.moveV(-1, "page"); }, + goPageDown: function (cm) { return cm.moveV(1, "page"); }, + goCharLeft: function (cm) { return cm.moveH(-1, "char"); }, + goCharRight: function (cm) { return cm.moveH(1, "char"); }, + goColumnLeft: function (cm) { return cm.moveH(-1, "column"); }, + goColumnRight: function (cm) { return cm.moveH(1, "column"); }, + goWordLeft: function (cm) { return cm.moveH(-1, "word"); }, + goGroupRight: function (cm) { return cm.moveH(1, "group"); }, + goGroupLeft: function (cm) { return cm.moveH(-1, "group"); }, + goWordRight: function (cm) { return cm.moveH(1, "word"); }, + delCharBefore: function (cm) { return cm.deleteH(-1, "char"); }, + delCharAfter: function (cm) { return cm.deleteH(1, "char"); }, + delWordBefore: function (cm) { return cm.deleteH(-1, "word"); }, + delWordAfter: function (cm) { return cm.deleteH(1, "word"); }, + delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); }, + delGroupAfter: function (cm) { return cm.deleteH(1, "group"); }, + indentAuto: function (cm) { return cm.indentSelection("smart"); }, + indentMore: function (cm) { return cm.indentSelection("add"); }, + indentLess: function (cm) { return cm.indentSelection("subtract"); }, + insertTab: function (cm) { return cm.replaceSelection("\t"); }, + insertSoftTab: function (cm) { + var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; + for (var i = 0; i < ranges.length; i++) { + var pos = ranges[i].from(); + var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); + spaces.push(spaceStr(tabSize - col % tabSize)); + } + cm.replaceSelections(spaces); + }, + defaultTab: function (cm) { + if (cm.somethingSelected()) { cm.indentSelection("add"); } + else { cm.execCommand("insertTab"); } + }, + // Swap the two chars left and right of each selection's head. + // Move cursor behind the two swapped characters afterwards. + // + // Doesn't consider line feeds a character. + // Doesn't scan more than one line above to find a character. + // Doesn't do anything on an empty line. + // Doesn't do anything with non-empty selections. + transposeChars: function (cm) { return runInOp(cm, function () { + var ranges = cm.listSelections(), newSel = []; + for (var i = 0; i < ranges.length; i++) { + if (!ranges[i].empty()) { continue } + var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; + if (line) { + if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); } + if (cur.ch > 0) { + cur = new Pos(cur.line, cur.ch + 1); + cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), + Pos(cur.line, cur.ch - 2), cur, "+transpose"); + } else if (cur.line > cm.doc.first) { + var prev = getLine(cm.doc, cur.line - 1).text; + if (prev) { + cur = new Pos(cur.line, 1); + cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + + prev.charAt(prev.length - 1), + Pos(cur.line - 1, prev.length - 1), cur, "+transpose"); + } + } + } + newSel.push(new Range(cur, cur)); + } + cm.setSelections(newSel); + }); }, + newlineAndIndent: function (cm) { return runInOp(cm, function () { + var sels = cm.listSelections(); + for (var i = sels.length - 1; i >= 0; i--) + { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); } + sels = cm.listSelections(); + for (var i$1 = 0; i$1 < sels.length; i$1++) + { cm.indentLine(sels[i$1].from().line, null, true); } + ensureCursorVisible(cm); + }); }, + openLine: function (cm) { return cm.replaceSelection("\n", "start"); }, + toggleOverwrite: function (cm) { return cm.toggleOverwrite(); } + }; + + + function lineStart(cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLine(line); + if (visual != line) { lineN = lineNo(visual); } + return endOfLine(true, cm, visual, lineN, 1) + } + function lineEnd(cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLineEnd(line); + if (visual != line) { lineN = lineNo(visual); } + return endOfLine(true, cm, line, lineN, -1) + } + function lineStartSmart(cm, pos) { + var start = lineStart(cm, pos.line); + var line = getLine(cm.doc, start.line); + var order = getOrder(line, cm.doc.direction); + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(0, line.text.search(/\S/)); + var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; + return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky) + } + return start + } + + // Run a handler that was bound to a key. + function doHandleBinding(cm, bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound]; + if (!bound) { return false } + } + // Ensure previous input has been read, so that the handler sees a + // consistent view of the document + cm.display.input.ensurePolled(); + var prevShift = cm.display.shift, done = false; + try { + if (cm.isReadOnly()) { cm.state.suppressEdits = true; } + if (dropShift) { cm.display.shift = false; } + done = bound(cm) != Pass; + } finally { + cm.display.shift = prevShift; + cm.state.suppressEdits = false; + } + return done + } + + function lookupKeyForEditor(cm, name, handle) { + for (var i = 0; i < cm.state.keyMaps.length; i++) { + var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); + if (result) { return result } + } + return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) + || lookupKey(name, cm.options.keyMap, handle, cm) + } + + // Note that, despite the name, this function is also used to check + // for bound mouse clicks. + + var stopSeq = new Delayed; + + function dispatchKey(cm, name, e, handle) { + var seq = cm.state.keySeq; + if (seq) { + if (isModifierKey(name)) { return "handled" } + if (/\'$/.test(name)) + { cm.state.keySeq = null; } + else + { stopSeq.set(50, function () { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null; + cm.display.input.reset(); + } + }); } + if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true } + } + return dispatchKeyInner(cm, name, e, handle) + } + + function dispatchKeyInner(cm, name, e, handle) { + var result = lookupKeyForEditor(cm, name, handle); + + if (result == "multi") + { cm.state.keySeq = name; } + if (result == "handled") + { signalLater(cm, "keyHandled", cm, name, e); } + + if (result == "handled" || result == "multi") { + e_preventDefault(e); + restartBlink(cm); + } + + return !!result + } + + // Handle a key from the keydown event. + function handleKeyBinding(cm, e) { + var name = keyName(e, true); + if (!name) { return false } + + if (e.shiftKey && !cm.state.keySeq) { + // First try to resolve full name (including 'Shift-'). Failing + // that, see if there is a cursor-motion command (starting with + // 'go') bound to the keyname without 'Shift-'. + return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); }) + || dispatchKey(cm, name, e, function (b) { + if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) + { return doHandleBinding(cm, b) } + }) + } else { + return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }) + } + } + + // Handle a key from the keypress event + function handleCharBinding(cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); }) + } + + var lastStoppedKey = null; + function onKeyDown(e) { + var cm = this; + cm.curOp.focus = activeElt(); + if (signalDOMEvent(cm, e)) { return } + // IE does strange things with escape. + if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; } + var code = e.keyCode; + cm.display.shift = code == 16 || e.shiftKey; + var handled = handleKeyBinding(cm, e); + if (presto) { + lastStoppedKey = handled ? code : null; + // Opera has no cut event... we try to at least catch the key combo + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) + { cm.replaceSelection("", null, "cut"); } + } + if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) + { document.execCommand("cut"); } + + // Turn mouse into crosshair when Alt is held on Mac. + if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) + { showCrossHair(cm); } + } + + function showCrossHair(cm) { + var lineDiv = cm.display.lineDiv; + addClass(lineDiv, "CodeMirror-crosshair"); + + function up(e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair"); + off(document, "keyup", up); + off(document, "mouseover", up); + } + } + on(document, "keyup", up); + on(document, "mouseover", up); + } + + function onKeyUp(e) { + if (e.keyCode == 16) { this.doc.sel.shift = false; } + signalDOMEvent(this, e); + } + + function onKeyPress(e) { + var cm = this; + if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return } + var keyCode = e.keyCode, charCode = e.charCode; + if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} + if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return } + var ch = String.fromCharCode(charCode == null ? keyCode : charCode); + // Some browsers fire keypress events for backspace + if (ch == "\x08") { return } + if (handleCharBinding(cm, e, ch)) { return } + cm.display.input.onKeyPress(e); + } + + var DOUBLECLICK_DELAY = 400; + + var PastClick = function(time, pos, button) { + this.time = time; + this.pos = pos; + this.button = button; + }; + + PastClick.prototype.compare = function (time, pos, button) { + return this.time + DOUBLECLICK_DELAY > time && + cmp(pos, this.pos) == 0 && button == this.button + }; + + var lastClick, lastDoubleClick; + function clickRepeat(pos, button) { + var now = +new Date; + if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { + lastClick = lastDoubleClick = null; + return "triple" + } else if (lastClick && lastClick.compare(now, pos, button)) { + lastDoubleClick = new PastClick(now, pos, button); + lastClick = null; + return "double" + } else { + lastClick = new PastClick(now, pos, button); + lastDoubleClick = null; + return "single" + } + } + + // A mouse down can be a single click, double click, triple click, + // start of selection drag, start of text drag, new cursor + // (ctrl-click), rectangle drag (alt-drag), or xwin + // middle-click-paste. Or it might be a click on something we should + // not interfere with, such as a scrollbar or widget. + function onMouseDown(e) { + var cm = this, display = cm.display; + if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return } + display.input.ensurePolled(); + display.shift = e.shiftKey; + + if (eventInWidget(display, e)) { + if (!webkit) { + // Briefly turn off draggability, to allow widgets to do + // normal dragging things. + display.scroller.draggable = false; + setTimeout(function () { return display.scroller.draggable = true; }, 100); + } + return + } + if (clickInGutter(cm, e)) { return } + var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single"; + window.focus(); + + // #3261: make sure, that we're not starting a second selection + if (button == 1 && cm.state.selectingText) + { cm.state.selectingText(e); } + + if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return } + + if (button == 1) { + if (pos) { leftButtonDown(cm, pos, repeat, e); } + else if (e_target(e) == display.scroller) { e_preventDefault(e); } + } else if (button == 2) { + if (pos) { extendSelection(cm.doc, pos); } + setTimeout(function () { return display.input.focus(); }, 20); + } else if (button == 3) { + if (captureRightClick) { cm.display.input.onContextMenu(e); } + else { delayBlurEvent(cm); } + } + } + + function handleMappedButton(cm, button, pos, repeat, event) { + var name = "Click"; + if (repeat == "double") { name = "Double" + name; } + else if (repeat == "triple") { name = "Triple" + name; } + name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; + + return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { + if (typeof bound == "string") { bound = commands[bound]; } + if (!bound) { return false } + var done = false; + try { + if (cm.isReadOnly()) { cm.state.suppressEdits = true; } + done = bound(cm, pos) != Pass; + } finally { + cm.state.suppressEdits = false; + } + return done + }) + } + + function configureMouse(cm, repeat, event) { + var option = cm.getOption("configureMouse"); + var value = option ? option(cm, repeat, event) : {}; + if (value.unit == null) { + var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; + value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; + } + if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; } + if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; } + if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); } + return value + } + + function leftButtonDown(cm, pos, repeat, event) { + if (ie) { setTimeout(bind(ensureFocus, cm), 0); } + else { cm.curOp.focus = activeElt(); } + + var behavior = configureMouse(cm, repeat, event); + + var sel = cm.doc.sel, contained; + if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && + repeat == "single" && (contained = sel.contains(pos)) > -1 && + (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && + (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) + { leftButtonStartDrag(cm, event, pos, behavior); } + else + { leftButtonSelect(cm, event, pos, behavior); } + } + + // Start a text drag. When it ends, see if any dragging actually + // happen, and treat as a click if it didn't. + function leftButtonStartDrag(cm, event, pos, behavior) { + var display = cm.display, moved = false; + var dragEnd = operation(cm, function (e) { + if (webkit) { display.scroller.draggable = false; } + cm.state.draggingText = false; + off(display.wrapper.ownerDocument, "mouseup", dragEnd); + off(display.wrapper.ownerDocument, "mousemove", mouseMove); + off(display.scroller, "dragstart", dragStart); + off(display.scroller, "drop", dragEnd); + if (!moved) { + e_preventDefault(e); + if (!behavior.addNew) + { extendSelection(cm.doc, pos, null, null, behavior.extend); } + // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) + if (webkit || ie && ie_version == 9) + { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus();}, 20); } + else + { display.input.focus(); } + } + }); + var mouseMove = function(e2) { + moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; + }; + var dragStart = function () { return moved = true; }; + // Let the drag handler handle this. + if (webkit) { display.scroller.draggable = true; } + cm.state.draggingText = dragEnd; + dragEnd.copy = !behavior.moveOnDrag; + // IE's approach to draggable + if (display.scroller.dragDrop) { display.scroller.dragDrop(); } + on(display.wrapper.ownerDocument, "mouseup", dragEnd); + on(display.wrapper.ownerDocument, "mousemove", mouseMove); + on(display.scroller, "dragstart", dragStart); + on(display.scroller, "drop", dragEnd); + + delayBlurEvent(cm); + setTimeout(function () { return display.input.focus(); }, 20); + } + + function rangeForUnit(cm, pos, unit) { + if (unit == "char") { return new Range(pos, pos) } + if (unit == "word") { return cm.findWordAt(pos) } + if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) } + var result = unit(cm, pos); + return new Range(result.from, result.to) + } + + // Normal selection, as opposed to text dragging. + function leftButtonSelect(cm, event, start, behavior) { + var display = cm.display, doc = cm.doc; + e_preventDefault(event); + + var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; + if (behavior.addNew && !behavior.extend) { + ourIndex = doc.sel.contains(start); + if (ourIndex > -1) + { ourRange = ranges[ourIndex]; } + else + { ourRange = new Range(start, start); } + } else { + ourRange = doc.sel.primary(); + ourIndex = doc.sel.primIndex; + } + + if (behavior.unit == "rectangle") { + if (!behavior.addNew) { ourRange = new Range(start, start); } + start = posFromMouse(cm, event, true, true); + ourIndex = -1; + } else { + var range$$1 = rangeForUnit(cm, start, behavior.unit); + if (behavior.extend) + { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); } + else + { ourRange = range$$1; } + } + + if (!behavior.addNew) { + ourIndex = 0; + setSelection(doc, new Selection([ourRange], 0), sel_mouse); + startSel = doc.sel; + } else if (ourIndex == -1) { + ourIndex = ranges.length; + setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), + {scroll: false, origin: "*mouse"}); + } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { + setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), + {scroll: false, origin: "*mouse"}); + startSel = doc.sel; + } else { + replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); + } + + var lastPos = start; + function extendTo(pos) { + if (cmp(lastPos, pos) == 0) { return } + lastPos = pos; + + if (behavior.unit == "rectangle") { + var ranges = [], tabSize = cm.options.tabSize; + var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); + var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); + var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); + for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); + line <= end; line++) { + var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); + if (left == right) + { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); } + else if (text.length > leftPos) + { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); } + } + if (!ranges.length) { ranges.push(new Range(start, start)); } + setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), + {origin: "*mouse", scroll: false}); + cm.scrollIntoView(pos); + } else { + var oldRange = ourRange; + var range$$1 = rangeForUnit(cm, pos, behavior.unit); + var anchor = oldRange.anchor, head; + if (cmp(range$$1.anchor, anchor) > 0) { + head = range$$1.head; + anchor = minPos(oldRange.from(), range$$1.anchor); + } else { + head = range$$1.anchor; + anchor = maxPos(oldRange.to(), range$$1.head); + } + var ranges$1 = startSel.ranges.slice(0); + ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head)); + setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse); + } + } + + var editorSize = display.wrapper.getBoundingClientRect(); + // Used to ensure timeout re-tries don't fire when another extend + // happened in the meantime (clearTimeout isn't reliable -- at + // least on Chrome, the timeouts still happen even when cleared, + // if the clear happens after their scheduled firing time). + var counter = 0; + + function extend(e) { + var curCount = ++counter; + var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); + if (!cur) { return } + if (cmp(cur, lastPos) != 0) { + cm.curOp.focus = activeElt(); + extendTo(cur); + var visible = visibleLines(display, doc); + if (cur.line >= visible.to || cur.line < visible.from) + { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); } + } else { + var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; + if (outside) { setTimeout(operation(cm, function () { + if (counter != curCount) { return } + display.scroller.scrollTop += outside; + extend(e); + }), 50); } + } + } + + function done(e) { + cm.state.selectingText = false; + counter = Infinity; + // If e is null or undefined we interpret this as someone trying + // to explicitly cancel the selection rather than the user + // letting go of the mouse button. + if (e) { + e_preventDefault(e); + display.input.focus(); + } + off(display.wrapper.ownerDocument, "mousemove", move); + off(display.wrapper.ownerDocument, "mouseup", up); + doc.history.lastSelOrigin = null; + } + + var move = operation(cm, function (e) { + if (e.buttons === 0 || !e_button(e)) { done(e); } + else { extend(e); } + }); + var up = operation(cm, done); + cm.state.selectingText = up; + on(display.wrapper.ownerDocument, "mousemove", move); + on(display.wrapper.ownerDocument, "mouseup", up); + } + + // Used when mouse-selecting to adjust the anchor to the proper side + // of a bidi jump depending on the visual position of the head. + function bidiSimplify(cm, range$$1) { + var anchor = range$$1.anchor; + var head = range$$1.head; + var anchorLine = getLine(cm.doc, anchor.line); + if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 } + var order = getOrder(anchorLine); + if (!order) { return range$$1 } + var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index]; + if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 } + var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1); + if (boundary == 0 || boundary == order.length) { return range$$1 } + + // Compute the relative visual position of the head compared to the + // anchor (<0 is to the left, >0 to the right) + var leftSide; + if (head.line != anchor.line) { + leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0; + } else { + var headIndex = getBidiPartAt(order, head.ch, head.sticky); + var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1); + if (headIndex == boundary - 1 || headIndex == boundary) + { leftSide = dir < 0; } + else + { leftSide = dir > 0; } + } + + var usePart = order[boundary + (leftSide ? -1 : 0)]; + var from = leftSide == (usePart.level == 1); + var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before"; + return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head) + } + + + // Determines whether an event happened in the gutter, and fires the + // handlers for the corresponding event. + function gutterEvent(cm, e, type, prevent) { + var mX, mY; + if (e.touches) { + mX = e.touches[0].clientX; + mY = e.touches[0].clientY; + } else { + try { mX = e.clientX; mY = e.clientY; } + catch(e) { return false } + } + if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false } + if (prevent) { e_preventDefault(e); } + + var display = cm.display; + var lineBox = display.lineDiv.getBoundingClientRect(); + + if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) } + mY -= lineBox.top - display.viewOffset; + + for (var i = 0; i < cm.display.gutterSpecs.length; ++i) { + var g = display.gutters.childNodes[i]; + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY); + var gutter = cm.display.gutterSpecs[i]; + signal(cm, type, cm, line, gutter.className, e); + return e_defaultPrevented(e) + } + } + } + + function clickInGutter(cm, e) { + return gutterEvent(cm, e, "gutterClick", true) + } + + // CONTEXT MENU HANDLING + + // To make the context menu work, we need to briefly unhide the + // textarea (making it as unobtrusive as possible) to let the + // right-click take effect on it. + function onContextMenu(cm, e) { + if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return } + if (signalDOMEvent(cm, e, "contextmenu")) { return } + if (!captureRightClick) { cm.display.input.onContextMenu(e); } + } + + function contextMenuInGutter(cm, e) { + if (!hasHandler(cm, "gutterContextMenu")) { return false } + return gutterEvent(cm, e, "gutterContextMenu", false) + } + + function themeChanged(cm) { + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); + clearCaches(cm); + } + + var Init = {toString: function(){return "CodeMirror.Init"}}; + + var defaults = {}; + var optionHandlers = {}; + + function defineOptions(CodeMirror) { + var optionHandlers = CodeMirror.optionHandlers; + + function option(name, deflt, handle, notOnInit) { + CodeMirror.defaults[name] = deflt; + if (handle) { optionHandlers[name] = + notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; } + } + + CodeMirror.defineOption = option; + + // Passed to option handlers when there is no old value. + CodeMirror.Init = Init; + + // These two are, on init, called from the constructor because they + // have to be initialized before the editor can start at all. + option("value", "", function (cm, val) { return cm.setValue(val); }, true); + option("mode", null, function (cm, val) { + cm.doc.modeOption = val; + loadMode(cm); + }, true); + + option("indentUnit", 2, loadMode, true); + option("indentWithTabs", false); + option("smartIndent", true); + option("tabSize", 4, function (cm) { + resetModeState(cm); + clearCaches(cm); + regChange(cm); + }, true); + + option("lineSeparator", null, function (cm, val) { + cm.doc.lineSep = val; + if (!val) { return } + var newBreaks = [], lineNo = cm.doc.first; + cm.doc.iter(function (line) { + for (var pos = 0;;) { + var found = line.text.indexOf(val, pos); + if (found == -1) { break } + pos = found + val.length; + newBreaks.push(Pos(lineNo, found)); + } + lineNo++; + }); + for (var i = newBreaks.length - 1; i >= 0; i--) + { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); } + }); + option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) { + cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); + if (old != Init) { cm.refresh(); } + }); + option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true); + option("electricChars", true); + option("inputStyle", mobile ? "contenteditable" : "textarea", function () { + throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME + }, true); + option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true); + option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true); + option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true); + option("rtlMoveVisually", !windows); + option("wholeLineUpdateBefore", true); + + option("theme", "default", function (cm) { + themeChanged(cm); + updateGutters(cm); + }, true); + option("keyMap", "default", function (cm, val, old) { + var next = getKeyMap(val); + var prev = old != Init && getKeyMap(old); + if (prev && prev.detach) { prev.detach(cm, next); } + if (next.attach) { next.attach(cm, prev || null); } + }); + option("extraKeys", null); + option("configureMouse", null); + + option("lineWrapping", false, wrappingChanged, true); + option("gutters", [], function (cm, val) { + cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers); + updateGutters(cm); + }, true); + option("fixedGutter", true, function (cm, val) { + cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; + cm.refresh(); + }, true); + option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true); + option("scrollbarStyle", "native", function (cm) { + initScrollbars(cm); + updateScrollbars(cm); + cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); + cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); + }, true); + option("lineNumbers", false, function (cm, val) { + cm.display.gutterSpecs = getGutters(cm.options.gutters, val); + updateGutters(cm); + }, true); + option("firstLineNumber", 1, updateGutters, true); + option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true); + option("showCursorWhenSelecting", false, updateSelection, true); + + option("resetSelectionOnContextMenu", true); + option("lineWiseCopyCut", true); + option("pasteLinesPerSelection", true); + option("selectionsMayTouch", false); + + option("readOnly", false, function (cm, val) { + if (val == "nocursor") { + onBlur(cm); + cm.display.input.blur(); + } + cm.display.input.readOnlyChanged(val); + }); + option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true); + option("dragDrop", true, dragDropChanged); + option("allowDropFileTypes", null); + + option("cursorBlinkRate", 530); + option("cursorScrollMargin", 0); + option("cursorHeight", 1, updateSelection, true); + option("singleCursorHeightPerLine", true, updateSelection, true); + option("workTime", 100); + option("workDelay", 100); + option("flattenSpans", true, resetModeState, true); + option("addModeClass", false, resetModeState, true); + option("pollInterval", 100); + option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; }); + option("historyEventDelay", 1250); + option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true); + option("maxHighlightLength", 10000, resetModeState, true); + option("moveInputWithCursor", true, function (cm, val) { + if (!val) { cm.display.input.resetPosition(); } + }); + + option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; }); + option("autofocus", null); + option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true); + option("phrases", null); + } + + function dragDropChanged(cm, value, old) { + var wasOn = old && old != Init; + if (!value != !wasOn) { + var funcs = cm.display.dragFunctions; + var toggle = value ? on : off; + toggle(cm.display.scroller, "dragstart", funcs.start); + toggle(cm.display.scroller, "dragenter", funcs.enter); + toggle(cm.display.scroller, "dragover", funcs.over); + toggle(cm.display.scroller, "dragleave", funcs.leave); + toggle(cm.display.scroller, "drop", funcs.drop); + } + } + + function wrappingChanged(cm) { + if (cm.options.lineWrapping) { + addClass(cm.display.wrapper, "CodeMirror-wrap"); + cm.display.sizer.style.minWidth = ""; + cm.display.sizerWidth = null; + } else { + rmClass(cm.display.wrapper, "CodeMirror-wrap"); + findMaxLine(cm); + } + estimateLineHeights(cm); + regChange(cm); + clearCaches(cm); + setTimeout(function () { return updateScrollbars(cm); }, 100); + } + + // A CodeMirror instance represents an editor. This is the object + // that user code is usually dealing with. + + function CodeMirror(place, options) { + var this$1 = this; + + if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) } + + this.options = options = options ? copyObj(options) : {}; + // Determine effective options based on given values and defaults. + copyObj(defaults, options, false); + + var doc = options.value; + if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); } + else if (options.mode) { doc.modeOption = options.mode; } + this.doc = doc; + + var input = new CodeMirror.inputStyles[options.inputStyle](this); + var display = this.display = new Display(place, doc, input, options); + display.wrapper.CodeMirror = this; + themeChanged(this); + if (options.lineWrapping) + { this.display.wrapper.className += " CodeMirror-wrap"; } + initScrollbars(this); + + this.state = { + keyMaps: [], // stores maps added by addKeyMap + overlays: [], // highlighting overlays, as added by addOverlay + modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info + overwrite: false, + delayingBlurEvent: false, + focused: false, + suppressEdits: false, // used to disable editing during key handlers when in readOnly mode + pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll + selectingText: false, + draggingText: false, + highlight: new Delayed(), // stores highlight worker timeout + keySeq: null, // Unfinished key sequence + specialChars: null + }; + + if (options.autofocus && !mobile) { display.input.focus(); } + + // Override magic textarea content restore that IE sometimes does + // on our hidden textarea on reload + if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); } + + registerEventHandlers(this); + ensureGlobalHandlers(); + + startOperation(this); + this.curOp.forceUpdate = true; + attachDoc(this, doc); + + if ((options.autofocus && !mobile) || this.hasFocus()) + { setTimeout(bind(onFocus, this), 20); } + else + { onBlur(this); } + + for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt)) + { optionHandlers[opt](this$1, options[opt], Init); } } + maybeUpdateLineNumberWidth(this); + if (options.finishInit) { options.finishInit(this); } + for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); } + endOperation(this); + // Suppress optimizelegibility in Webkit, since it breaks text + // measuring on line wrapping boundaries. + if (webkit && options.lineWrapping && + getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") + { display.lineDiv.style.textRendering = "auto"; } + } + + // The default configuration options. + CodeMirror.defaults = defaults; + // Functions to run when options are changed. + CodeMirror.optionHandlers = optionHandlers; + + // Attach the necessary event handlers when initializing the editor + function registerEventHandlers(cm) { + var d = cm.display; + on(d.scroller, "mousedown", operation(cm, onMouseDown)); + // Older IE's will not fire a second mousedown for a double click + if (ie && ie_version < 11) + { on(d.scroller, "dblclick", operation(cm, function (e) { + if (signalDOMEvent(cm, e)) { return } + var pos = posFromMouse(cm, e); + if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return } + e_preventDefault(e); + var word = cm.findWordAt(pos); + extendSelection(cm.doc, word.anchor, word.head); + })); } + else + { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); } + // Some browsers fire contextmenu *after* opening the menu, at + // which point we can't mess with it anymore. Context menu is + // handled in onMouseDown for these browsers. + on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); + + // Used to suppress mouse event handling when a touch happens + var touchFinished, prevTouch = {end: 0}; + function finishTouch() { + if (d.activeTouch) { + touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000); + prevTouch = d.activeTouch; + prevTouch.end = +new Date; + } + } + function isMouseLikeTouchEvent(e) { + if (e.touches.length != 1) { return false } + var touch = e.touches[0]; + return touch.radiusX <= 1 && touch.radiusY <= 1 + } + function farAway(touch, other) { + if (other.left == null) { return true } + var dx = other.left - touch.left, dy = other.top - touch.top; + return dx * dx + dy * dy > 20 * 20 + } + on(d.scroller, "touchstart", function (e) { + if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { + d.input.ensurePolled(); + clearTimeout(touchFinished); + var now = +new Date; + d.activeTouch = {start: now, moved: false, + prev: now - prevTouch.end <= 300 ? prevTouch : null}; + if (e.touches.length == 1) { + d.activeTouch.left = e.touches[0].pageX; + d.activeTouch.top = e.touches[0].pageY; + } + } + }); + on(d.scroller, "touchmove", function () { + if (d.activeTouch) { d.activeTouch.moved = true; } + }); + on(d.scroller, "touchend", function (e) { + var touch = d.activeTouch; + if (touch && !eventInWidget(d, e) && touch.left != null && + !touch.moved && new Date - touch.start < 300) { + var pos = cm.coordsChar(d.activeTouch, "page"), range; + if (!touch.prev || farAway(touch, touch.prev)) // Single tap + { range = new Range(pos, pos); } + else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap + { range = cm.findWordAt(pos); } + else // Triple tap + { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); } + cm.setSelection(range.anchor, range.head); + cm.focus(); + e_preventDefault(e); + } + finishTouch(); + }); + on(d.scroller, "touchcancel", finishTouch); + + // Sync scrolling between fake scrollbars and real scrollable + // area, ensure viewport is updated when scrolling. + on(d.scroller, "scroll", function () { + if (d.scroller.clientHeight) { + updateScrollTop(cm, d.scroller.scrollTop); + setScrollLeft(cm, d.scroller.scrollLeft, true); + signal(cm, "scroll", cm); + } + }); + + // Listen to wheel events in order to try and update the viewport on time. + on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); }); + on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); }); + + // Prevent wrapper from ever scrolling + on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); + + d.dragFunctions = { + enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }}, + over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, + start: function (e) { return onDragStart(cm, e); }, + drop: operation(cm, onDrop), + leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }} + }; + + var inp = d.input.getField(); + on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); }); + on(inp, "keydown", operation(cm, onKeyDown)); + on(inp, "keypress", operation(cm, onKeyPress)); + on(inp, "focus", function (e) { return onFocus(cm, e); }); + on(inp, "blur", function (e) { return onBlur(cm, e); }); + } + + var initHooks = []; + CodeMirror.defineInitHook = function (f) { return initHooks.push(f); }; + + // Indent the given line. The how parameter can be "smart", + // "add"/null, "subtract", or "prev". When aggressive is false + // (typically set to true for forced single-line indents), empty + // lines are not indented, and places where the mode returns Pass + // are left alone. + function indentLine(cm, n, how, aggressive) { + var doc = cm.doc, state; + if (how == null) { how = "add"; } + if (how == "smart") { + // Fall back to "prev" when the mode doesn't have an indentation + // method. + if (!doc.mode.indent) { how = "prev"; } + else { state = getContextBefore(cm, n).state; } + } + + var tabSize = cm.options.tabSize; + var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); + if (line.stateAfter) { line.stateAfter = null; } + var curSpaceString = line.text.match(/^\s*/)[0], indentation; + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0; + how = "not"; + } else if (how == "smart") { + indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); + if (indentation == Pass || indentation > 150) { + if (!aggressive) { return } + how = "prev"; + } + } + if (how == "prev") { + if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); } + else { indentation = 0; } + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit; + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit; + } else if (typeof how == "number") { + indentation = curSpace + how; + } + indentation = Math.max(0, indentation); + + var indentString = "", pos = 0; + if (cm.options.indentWithTabs) + { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} } + if (pos < indentation) { indentString += spaceStr(indentation - pos); } + + if (indentString != curSpaceString) { + replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); + line.stateAfter = null; + return true + } else { + // Ensure that, if the cursor was in the whitespace at the start + // of the line, it is moved to the end of that space. + for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) { + var range = doc.sel.ranges[i$1]; + if (range.head.line == n && range.head.ch < curSpaceString.length) { + var pos$1 = Pos(n, curSpaceString.length); + replaceOneSelection(doc, i$1, new Range(pos$1, pos$1)); + break + } + } + } + } + + // This will be set to a {lineWise: bool, text: [string]} object, so + // that, when pasting, we know what kind of selections the copied + // text was made out of. + var lastCopied = null; + + function setLastCopied(newLastCopied) { + lastCopied = newLastCopied; + } + + function applyTextInput(cm, inserted, deleted, sel, origin) { + var doc = cm.doc; + cm.display.shift = false; + if (!sel) { sel = doc.sel; } + + var recent = +new Date - 200; + var paste = origin == "paste" || cm.state.pasteIncoming > recent; + var textLines = splitLinesAuto(inserted), multiPaste = null; + // When pasting N lines into N selections, insert one line per selection + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.text.join("\n") == inserted) { + if (sel.ranges.length % lastCopied.text.length == 0) { + multiPaste = []; + for (var i = 0; i < lastCopied.text.length; i++) + { multiPaste.push(doc.splitLines(lastCopied.text[i])); } + } + } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { + multiPaste = map(textLines, function (l) { return [l]; }); + } + } + + var updateInput = cm.curOp.updateInput; + // Normal behavior is to insert the new text into every selection + for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) { + var range$$1 = sel.ranges[i$1]; + var from = range$$1.from(), to = range$$1.to(); + if (range$$1.empty()) { + if (deleted && deleted > 0) // Handle deletion + { from = Pos(from.line, from.ch - deleted); } + else if (cm.state.overwrite && !paste) // Handle overwrite + { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); } + else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) + { from = to = Pos(from.line, 0); } + } + var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")}; + makeChange(cm.doc, changeEvent); + signalLater(cm, "inputRead", cm, changeEvent); + } + if (inserted && !paste) + { triggerElectric(cm, inserted); } + + ensureCursorVisible(cm); + if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; } + cm.curOp.typing = true; + cm.state.pasteIncoming = cm.state.cutIncoming = -1; + } + + function handlePaste(e, cm) { + var pasted = e.clipboardData && e.clipboardData.getData("Text"); + if (pasted) { + e.preventDefault(); + if (!cm.isReadOnly() && !cm.options.disableInput) + { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); } + return true + } + } + + function triggerElectric(cm, inserted) { + // When an 'electric' character is inserted, immediately trigger a reindent + if (!cm.options.electricChars || !cm.options.smartIndent) { return } + var sel = cm.doc.sel; + + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range$$1 = sel.ranges[i]; + if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue } + var mode = cm.getModeAt(range$$1.head); + var indented = false; + if (mode.electricChars) { + for (var j = 0; j < mode.electricChars.length; j++) + { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range$$1.head.line, "smart"); + break + } } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch))) + { indented = indentLine(cm, range$$1.head.line, "smart"); } + } + if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); } + } + } + + function copyableRanges(cm) { + var text = [], ranges = []; + for (var i = 0; i < cm.doc.sel.ranges.length; i++) { + var line = cm.doc.sel.ranges[i].head.line; + var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; + ranges.push(lineRange); + text.push(cm.getRange(lineRange.anchor, lineRange.head)); + } + return {text: text, ranges: ranges} + } + + function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) { + field.setAttribute("autocorrect", autocorrect ? "" : "off"); + field.setAttribute("autocapitalize", autocapitalize ? "" : "off"); + field.setAttribute("spellcheck", !!spellcheck); + } + + function hiddenTextarea() { + var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"); + var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); + // The textarea is kept positioned near the cursor to prevent the + // fact that it'll be scrolled into view on input from scrolling + // our fake cursor out of view. On webkit, when wrap=off, paste is + // very slow. So make the area wide instead. + if (webkit) { te.style.width = "1000px"; } + else { te.setAttribute("wrap", "off"); } + // If border: 0; -- iOS fails to open keyboard (issue #1287) + if (ios) { te.style.border = "1px solid black"; } + disableBrowserMagic(te); + return div + } + + // The publicly visible API. Note that methodOp(f) means + // 'wrap f in an operation, performed on its `this` parameter'. + + // This is not the complete set of editor methods. Most of the + // methods defined on the Doc type are also injected into + // CodeMirror.prototype, for backwards compatibility and + // convenience. + + function addEditorMethods(CodeMirror) { + var optionHandlers = CodeMirror.optionHandlers; + + var helpers = CodeMirror.helpers = {}; + + CodeMirror.prototype = { + constructor: CodeMirror, + focus: function(){window.focus(); this.display.input.focus();}, + + setOption: function(option, value) { + var options = this.options, old = options[option]; + if (options[option] == value && option != "mode") { return } + options[option] = value; + if (optionHandlers.hasOwnProperty(option)) + { operation(this, optionHandlers[option])(this, value, old); } + signal(this, "optionChange", this, option); + }, + + getOption: function(option) {return this.options[option]}, + getDoc: function() {return this.doc}, + + addKeyMap: function(map$$1, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1)); + }, + removeKeyMap: function(map$$1) { + var maps = this.state.keyMaps; + for (var i = 0; i < maps.length; ++i) + { if (maps[i] == map$$1 || maps[i].name == map$$1) { + maps.splice(i, 1); + return true + } } + }, + + addOverlay: methodOp(function(spec, options) { + var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); + if (mode.startState) { throw new Error("Overlays may not be stateful.") } + insertSorted(this.state.overlays, + {mode: mode, modeSpec: spec, opaque: options && options.opaque, + priority: (options && options.priority) || 0}, + function (overlay) { return overlay.priority; }); + this.state.modeGen++; + regChange(this); + }), + removeOverlay: methodOp(function(spec) { + var this$1 = this; + + var overlays = this.state.overlays; + for (var i = 0; i < overlays.length; ++i) { + var cur = overlays[i].modeSpec; + if (cur == spec || typeof spec == "string" && cur.name == spec) { + overlays.splice(i, 1); + this$1.state.modeGen++; + regChange(this$1); + return + } + } + }), + + indentLine: methodOp(function(n, dir, aggressive) { + if (typeof dir != "string" && typeof dir != "number") { + if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; } + else { dir = dir ? "add" : "subtract"; } + } + if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); } + }), + indentSelection: methodOp(function(how) { + var this$1 = this; + + var ranges = this.doc.sel.ranges, end = -1; + for (var i = 0; i < ranges.length; i++) { + var range$$1 = ranges[i]; + if (!range$$1.empty()) { + var from = range$$1.from(), to = range$$1.to(); + var start = Math.max(end, from.line); + end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; + for (var j = start; j < end; ++j) + { indentLine(this$1, j, how); } + var newRanges = this$1.doc.sel.ranges; + if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) + { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); } + } else if (range$$1.head.line > end) { + indentLine(this$1, range$$1.head.line, how, true); + end = range$$1.head.line; + if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); } + } + } + }), + + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function(pos, precise) { + return takeToken(this, pos, precise) + }, + + getLineTokens: function(line, precise) { + return takeToken(this, Pos(line), precise, true) + }, + + getTokenTypeAt: function(pos) { + pos = clipPos(this.doc, pos); + var styles = getLineStyles(this, getLine(this.doc, pos.line)); + var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; + var type; + if (ch == 0) { type = styles[2]; } + else { for (;;) { + var mid = (before + after) >> 1; + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; } + else if (styles[mid * 2 + 1] < ch) { before = mid + 1; } + else { type = styles[mid * 2 + 2]; break } + } } + var cut = type ? type.indexOf("overlay ") : -1; + return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1) + }, + + getModeAt: function(pos) { + var mode = this.doc.mode; + if (!mode.innerMode) { return mode } + return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode + }, + + getHelper: function(pos, type) { + return this.getHelpers(pos, type)[0] + }, + + getHelpers: function(pos, type) { + var this$1 = this; + + var found = []; + if (!helpers.hasOwnProperty(type)) { return found } + var help = helpers[type], mode = this.getModeAt(pos); + if (typeof mode[type] == "string") { + if (help[mode[type]]) { found.push(help[mode[type]]); } + } else if (mode[type]) { + for (var i = 0; i < mode[type].length; i++) { + var val = help[mode[type][i]]; + if (val) { found.push(val); } + } + } else if (mode.helperType && help[mode.helperType]) { + found.push(help[mode.helperType]); + } else if (help[mode.name]) { + found.push(help[mode.name]); + } + for (var i$1 = 0; i$1 < help._global.length; i$1++) { + var cur = help._global[i$1]; + if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1) + { found.push(cur.val); } + } + return found + }, + + getStateAfter: function(line, precise) { + var doc = this.doc; + line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); + return getContextBefore(this, line + 1, precise).state + }, + + cursorCoords: function(start, mode) { + var pos, range$$1 = this.doc.sel.primary(); + if (start == null) { pos = range$$1.head; } + else if (typeof start == "object") { pos = clipPos(this.doc, start); } + else { pos = start ? range$$1.from() : range$$1.to(); } + return cursorCoords(this, pos, mode || "page") + }, + + charCoords: function(pos, mode) { + return charCoords(this, clipPos(this.doc, pos), mode || "page") + }, + + coordsChar: function(coords, mode) { + coords = fromCoordSystem(this, coords, mode || "page"); + return coordsChar(this, coords.left, coords.top) + }, + + lineAtHeight: function(height, mode) { + height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; + return lineAtHeight(this.doc, height + this.display.viewOffset) + }, + heightAtLine: function(line, mode, includeWidgets) { + var end = false, lineObj; + if (typeof line == "number") { + var last = this.doc.first + this.doc.size - 1; + if (line < this.doc.first) { line = this.doc.first; } + else if (line > last) { line = last; end = true; } + lineObj = getLine(this.doc, line); + } else { + lineObj = line; + } + return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top + + (end ? this.doc.height - heightAtLine(lineObj) : 0) + }, + + defaultTextHeight: function() { return textHeight(this.display) }, + defaultCharWidth: function() { return charWidth(this.display) }, + + getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, + + addWidget: function(pos, node, scroll, vert, horiz) { + var display = this.display; + pos = cursorCoords(this, clipPos(this.doc, pos)); + var top = pos.bottom, left = pos.left; + node.style.position = "absolute"; + node.setAttribute("cm-ignore-events", "true"); + this.display.input.setUneditable(node); + display.sizer.appendChild(node); + if (vert == "over") { + top = pos.top; + } else if (vert == "above" || vert == "near") { + var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), + hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); + // Default to positioning above (if specified and possible); otherwise default to positioning below + if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) + { top = pos.top - node.offsetHeight; } + else if (pos.bottom + node.offsetHeight <= vspace) + { top = pos.bottom; } + if (left + node.offsetWidth > hspace) + { left = hspace - node.offsetWidth; } + } + node.style.top = top + "px"; + node.style.left = node.style.right = ""; + if (horiz == "right") { + left = display.sizer.clientWidth - node.offsetWidth; + node.style.right = "0px"; + } else { + if (horiz == "left") { left = 0; } + else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; } + node.style.left = left + "px"; + } + if (scroll) + { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); } + }, + + triggerOnKeyDown: methodOp(onKeyDown), + triggerOnKeyPress: methodOp(onKeyPress), + triggerOnKeyUp: onKeyUp, + triggerOnMouseDown: methodOp(onMouseDown), + + execCommand: function(cmd) { + if (commands.hasOwnProperty(cmd)) + { return commands[cmd].call(null, this) } + }, + + triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), + + findPosH: function(from, amount, unit, visually) { + var this$1 = this; + + var dir = 1; + if (amount < 0) { dir = -1; amount = -amount; } + var cur = clipPos(this.doc, from); + for (var i = 0; i < amount; ++i) { + cur = findPosH(this$1.doc, cur, dir, unit, visually); + if (cur.hitSide) { break } + } + return cur + }, + + moveH: methodOp(function(dir, unit) { + var this$1 = this; + + this.extendSelectionsBy(function (range$$1) { + if (this$1.display.shift || this$1.doc.extend || range$$1.empty()) + { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) } + else + { return dir < 0 ? range$$1.from() : range$$1.to() } + }, sel_move); + }), + + deleteH: methodOp(function(dir, unit) { + var sel = this.doc.sel, doc = this.doc; + if (sel.somethingSelected()) + { doc.replaceSelection("", null, "+delete"); } + else + { deleteNearSelection(this, function (range$$1) { + var other = findPosH(doc, range$$1.head, dir, unit, false); + return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other} + }); } + }), + + findPosV: function(from, amount, unit, goalColumn) { + var this$1 = this; + + var dir = 1, x = goalColumn; + if (amount < 0) { dir = -1; amount = -amount; } + var cur = clipPos(this.doc, from); + for (var i = 0; i < amount; ++i) { + var coords = cursorCoords(this$1, cur, "div"); + if (x == null) { x = coords.left; } + else { coords.left = x; } + cur = findPosV(this$1, coords, dir, unit); + if (cur.hitSide) { break } + } + return cur + }, + + moveV: methodOp(function(dir, unit) { + var this$1 = this; + + var doc = this.doc, goals = []; + var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected(); + doc.extendSelectionsBy(function (range$$1) { + if (collapse) + { return dir < 0 ? range$$1.from() : range$$1.to() } + var headPos = cursorCoords(this$1, range$$1.head, "div"); + if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; } + goals.push(headPos.left); + var pos = findPosV(this$1, headPos, dir, unit); + if (unit == "page" && range$$1 == doc.sel.primary()) + { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); } + return pos + }, sel_move); + if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++) + { doc.sel.ranges[i].goalColumn = goals[i]; } } + }), + + // Find the word at the given position (as returned by coordsChar). + findWordAt: function(pos) { + var doc = this.doc, line = getLine(doc, pos.line).text; + var start = pos.ch, end = pos.ch; + if (line) { + var helper = this.getHelper(pos, "wordChars"); + if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; } + var startChar = line.charAt(start); + var check = isWordChar(startChar, helper) + ? function (ch) { return isWordChar(ch, helper); } + : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); } + : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }; + while (start > 0 && check(line.charAt(start - 1))) { --start; } + while (end < line.length && check(line.charAt(end))) { ++end; } + } + return new Range(Pos(pos.line, start), Pos(pos.line, end)) + }, + + toggleOverwrite: function(value) { + if (value != null && value == this.state.overwrite) { return } + if (this.state.overwrite = !this.state.overwrite) + { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); } + else + { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); } + + signal(this, "overwriteToggle", this, this.state.overwrite); + }, + hasFocus: function() { return this.display.input.getField() == activeElt() }, + isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, + + scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }), + getScrollInfo: function() { + var scroller = this.display.scroller; + return {left: scroller.scrollLeft, top: scroller.scrollTop, + height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, + width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, + clientHeight: displayHeight(this), clientWidth: displayWidth(this)} + }, + + scrollIntoView: methodOp(function(range$$1, margin) { + if (range$$1 == null) { + range$$1 = {from: this.doc.sel.primary().head, to: null}; + if (margin == null) { margin = this.options.cursorScrollMargin; } + } else if (typeof range$$1 == "number") { + range$$1 = {from: Pos(range$$1, 0), to: null}; + } else if (range$$1.from == null) { + range$$1 = {from: range$$1, to: null}; + } + if (!range$$1.to) { range$$1.to = range$$1.from; } + range$$1.margin = margin || 0; + + if (range$$1.from.line != null) { + scrollToRange(this, range$$1); + } else { + scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin); + } + }), + + setSize: methodOp(function(width, height) { + var this$1 = this; + + var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }; + if (width != null) { this.display.wrapper.style.width = interpret(width); } + if (height != null) { this.display.wrapper.style.height = interpret(height); } + if (this.options.lineWrapping) { clearLineMeasurementCache(this); } + var lineNo$$1 = this.display.viewFrom; + this.doc.iter(lineNo$$1, this.display.viewTo, function (line) { + if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) + { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } } + ++lineNo$$1; + }); + this.curOp.forceUpdate = true; + signal(this, "refresh", this); + }), + + operation: function(f){return runInOp(this, f)}, + startOperation: function(){return startOperation(this)}, + endOperation: function(){return endOperation(this)}, + + refresh: methodOp(function() { + var oldHeight = this.display.cachedTextHeight; + regChange(this); + this.curOp.forceUpdate = true; + clearCaches(this); + scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); + updateGutterSpace(this.display); + if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) + { estimateLineHeights(this); } + signal(this, "refresh", this); + }), + + swapDoc: methodOp(function(doc) { + var old = this.doc; + old.cm = null; + // Cancel the current text selection if any (#5821) + if (this.state.selectingText) { this.state.selectingText(); } + attachDoc(this, doc); + clearCaches(this); + this.display.input.reset(); + scrollToCoords(this, doc.scrollLeft, doc.scrollTop); + this.curOp.forceScroll = true; + signalLater(this, "swapDoc", this, old); + return old + }), + + phrase: function(phraseText) { + var phrases = this.options.phrases; + return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText + }, + + getInputField: function(){return this.display.input.getField()}, + getWrapperElement: function(){return this.display.wrapper}, + getScrollerElement: function(){return this.display.scroller}, + getGutterElement: function(){return this.display.gutters} + }; + eventMixin(CodeMirror); + + CodeMirror.registerHelper = function(type, name, value) { + if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; } + helpers[type][name] = value; + }; + CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { + CodeMirror.registerHelper(type, name, value); + helpers[type]._global.push({pred: predicate, val: value}); + }; + } + + // Used for horizontal relative motion. Dir is -1 or 1 (left or + // right), unit can be "char", "column" (like char, but doesn't + // cross line boundaries), "word" (across next word), or "group" (to + // the start of next group of word or non-word-non-whitespace + // chars). The visually param controls whether, in right-to-left + // text, direction 1 means to move towards the next index in the + // string, or towards the character to the right of the current + // position. The resulting position will have a hitSide=true + // property if it reached the end of the document. + function findPosH(doc, pos, dir, unit, visually) { + var oldPos = pos; + var origDir = dir; + var lineObj = getLine(doc, pos.line); + function findNextLine() { + var l = pos.line + dir; + if (l < doc.first || l >= doc.first + doc.size) { return false } + pos = new Pos(l, pos.ch, pos.sticky); + return lineObj = getLine(doc, l) + } + function moveOnce(boundToLine) { + var next; + if (visually) { + next = moveVisually(doc.cm, lineObj, pos, dir); + } else { + next = moveLogically(lineObj, pos, dir); + } + if (next == null) { + if (!boundToLine && findNextLine()) + { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); } + else + { return false } + } else { + pos = next; + } + return true + } + + if (unit == "char") { + moveOnce(); + } else if (unit == "column") { + moveOnce(true); + } else if (unit == "word" || unit == "group") { + var sawType = null, group = unit == "group"; + var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); + for (var first = true;; first = false) { + if (dir < 0 && !moveOnce(!first)) { break } + var cur = lineObj.text.charAt(pos.ch) || "\n"; + var type = isWordChar(cur, helper) ? "w" + : group && cur == "\n" ? "n" + : !group || /\s/.test(cur) ? null + : "p"; + if (group && !first && !type) { type = "s"; } + if (sawType && sawType != type) { + if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";} + break + } + + if (type) { sawType = type; } + if (dir > 0 && !moveOnce(!first)) { break } + } + } + var result = skipAtomic(doc, pos, oldPos, origDir, true); + if (equalCursorPos(oldPos, result)) { result.hitSide = true; } + return result + } + + // For relative vertical movement. Dir may be -1 or 1. Unit can be + // "page" or "line". The resulting position will have a hitSide=true + // property if it reached the end of the document. + function findPosV(cm, pos, dir, unit) { + var doc = cm.doc, x = pos.left, y; + if (unit == "page") { + var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); + var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3); + y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; + + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3; + } + var target; + for (;;) { + target = coordsChar(cm, x, y); + if (!target.outside) { break } + if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break } + y += dir * 5; + } + return target + } + + // CONTENTEDITABLE INPUT STYLE + + var ContentEditableInput = function(cm) { + this.cm = cm; + this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; + this.polling = new Delayed(); + this.composing = null; + this.gracePeriod = false; + this.readDOMTimeout = null; + }; + + ContentEditableInput.prototype.init = function (display) { + var this$1 = this; + + var input = this, cm = input.cm; + var div = input.div = display.lineDiv; + disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize); + + on(div, "paste", function (e) { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } + // IE doesn't fire input events, so we schedule a read for the pasted content in this way + if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); } + }); + + on(div, "compositionstart", function (e) { + this$1.composing = {data: e.data, done: false}; + }); + on(div, "compositionupdate", function (e) { + if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; } + }); + on(div, "compositionend", function (e) { + if (this$1.composing) { + if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); } + this$1.composing.done = true; + } + }); + + on(div, "touchstart", function () { return input.forceCompositionEnd(); }); + + on(div, "input", function () { + if (!this$1.composing) { this$1.readFromDOMSoon(); } + }); + + function onCopyCut(e) { + if (signalDOMEvent(cm, e)) { return } + if (cm.somethingSelected()) { + setLastCopied({lineWise: false, text: cm.getSelections()}); + if (e.type == "cut") { cm.replaceSelection("", null, "cut"); } + } else if (!cm.options.lineWiseCopyCut) { + return + } else { + var ranges = copyableRanges(cm); + setLastCopied({lineWise: true, text: ranges.text}); + if (e.type == "cut") { + cm.operation(function () { + cm.setSelections(ranges.ranges, 0, sel_dontScroll); + cm.replaceSelection("", null, "cut"); + }); + } + } + if (e.clipboardData) { + e.clipboardData.clearData(); + var content = lastCopied.text.join("\n"); + // iOS exposes the clipboard API, but seems to discard content inserted into it + e.clipboardData.setData("Text", content); + if (e.clipboardData.getData("Text") == content) { + e.preventDefault(); + return + } + } + // Old-fashioned briefly-focus-a-textarea hack + var kludge = hiddenTextarea(), te = kludge.firstChild; + cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); + te.value = lastCopied.text.join("\n"); + var hadFocus = document.activeElement; + selectInput(te); + setTimeout(function () { + cm.display.lineSpace.removeChild(kludge); + hadFocus.focus(); + if (hadFocus == div) { input.showPrimarySelection(); } + }, 50); + } + on(div, "copy", onCopyCut); + on(div, "cut", onCopyCut); + }; + + ContentEditableInput.prototype.prepareSelection = function () { + var result = prepareSelection(this.cm, false); + result.focus = this.cm.state.focused; + return result + }; + + ContentEditableInput.prototype.showSelection = function (info, takeFocus) { + if (!info || !this.cm.display.view.length) { return } + if (info.focus || takeFocus) { this.showPrimarySelection(); } + this.showMultipleSelections(info); + }; + + ContentEditableInput.prototype.getSelection = function () { + return this.cm.display.wrapper.ownerDocument.getSelection() + }; + + ContentEditableInput.prototype.showPrimarySelection = function () { + var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary(); + var from = prim.from(), to = prim.to(); + + if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { + sel.removeAllRanges(); + return + } + + var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); + if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && + cmp(minPos(curAnchor, curFocus), from) == 0 && + cmp(maxPos(curAnchor, curFocus), to) == 0) + { return } + + var view = cm.display.view; + var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) || + {node: view[0].measure.map[2], offset: 0}; + var end = to.line < cm.display.viewTo && posToDOM(cm, to); + if (!end) { + var measure = view[view.length - 1].measure; + var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; + end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]}; + } + + if (!start || !end) { + sel.removeAllRanges(); + return + } + + var old = sel.rangeCount && sel.getRangeAt(0), rng; + try { rng = range(start.node, start.offset, end.offset, end.node); } + catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible + if (rng) { + if (!gecko && cm.state.focused) { + sel.collapse(start.node, start.offset); + if (!rng.collapsed) { + sel.removeAllRanges(); + sel.addRange(rng); + } + } else { + sel.removeAllRanges(); + sel.addRange(rng); + } + if (old && sel.anchorNode == null) { sel.addRange(old); } + else if (gecko) { this.startGracePeriod(); } + } + this.rememberSelection(); + }; + + ContentEditableInput.prototype.startGracePeriod = function () { + var this$1 = this; + + clearTimeout(this.gracePeriod); + this.gracePeriod = setTimeout(function () { + this$1.gracePeriod = false; + if (this$1.selectionChanged()) + { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); } + }, 20); + }; + + ContentEditableInput.prototype.showMultipleSelections = function (info) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); + }; + + ContentEditableInput.prototype.rememberSelection = function () { + var sel = this.getSelection(); + this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; + this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; + }; + + ContentEditableInput.prototype.selectionInEditor = function () { + var sel = this.getSelection(); + if (!sel.rangeCount) { return false } + var node = sel.getRangeAt(0).commonAncestorContainer; + return contains(this.div, node) + }; + + ContentEditableInput.prototype.focus = function () { + if (this.cm.options.readOnly != "nocursor") { + if (!this.selectionInEditor()) + { this.showSelection(this.prepareSelection(), true); } + this.div.focus(); + } + }; + ContentEditableInput.prototype.blur = function () { this.div.blur(); }; + ContentEditableInput.prototype.getField = function () { return this.div }; + + ContentEditableInput.prototype.supportsTouch = function () { return true }; + + ContentEditableInput.prototype.receivedFocus = function () { + var input = this; + if (this.selectionInEditor()) + { this.pollSelection(); } + else + { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); } + + function poll() { + if (input.cm.state.focused) { + input.pollSelection(); + input.polling.set(input.cm.options.pollInterval, poll); + } + } + this.polling.set(this.cm.options.pollInterval, poll); + }; + + ContentEditableInput.prototype.selectionChanged = function () { + var sel = this.getSelection(); + return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || + sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset + }; + + ContentEditableInput.prototype.pollSelection = function () { + if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return } + var sel = this.getSelection(), cm = this.cm; + // On Android Chrome (version 56, at least), backspacing into an + // uneditable block element will put the cursor in that element, + // and then, because it's not editable, hide the virtual keyboard. + // Because Android doesn't allow us to actually detect backspace + // presses in a sane way, this code checks for when that happens + // and simulates a backspace press in this case. + if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) { + this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs}); + this.blur(); + this.focus(); + return + } + if (this.composing) { return } + this.rememberSelection(); + var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var head = domToPos(cm, sel.focusNode, sel.focusOffset); + if (anchor && head) { runInOp(cm, function () { + setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); + if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; } + }); } + }; + + ContentEditableInput.prototype.pollContent = function () { + if (this.readDOMTimeout != null) { + clearTimeout(this.readDOMTimeout); + this.readDOMTimeout = null; + } + + var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); + var from = sel.from(), to = sel.to(); + if (from.ch == 0 && from.line > cm.firstLine()) + { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); } + if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) + { to = Pos(to.line + 1, 0); } + if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false } + + var fromIndex, fromLine, fromNode; + if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { + fromLine = lineNo(display.view[0].line); + fromNode = display.view[0].node; + } else { + fromLine = lineNo(display.view[fromIndex].line); + fromNode = display.view[fromIndex - 1].node.nextSibling; + } + var toIndex = findViewIndex(cm, to.line); + var toLine, toNode; + if (toIndex == display.view.length - 1) { + toLine = display.viewTo - 1; + toNode = display.lineDiv.lastChild; + } else { + toLine = lineNo(display.view[toIndex + 1].line) - 1; + toNode = display.view[toIndex + 1].node.previousSibling; + } + + if (!fromNode) { return false } + var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); + var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } + else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } + else { break } + } + + var cutFront = 0, cutEnd = 0; + var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); + while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) + { ++cutFront; } + var newBot = lst(newText), oldBot = lst(oldText); + var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), + oldBot.length - (oldText.length == 1 ? cutFront : 0)); + while (cutEnd < maxCutEnd && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) + { ++cutEnd; } + // Try to move start of change to start of selection if ambiguous + if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { + while (cutFront && cutFront > from.ch && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { + cutFront--; + cutEnd++; + } + } + + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); + newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); + + var chFrom = Pos(fromLine, cutFront); + var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input"); + return true + } + }; + + ContentEditableInput.prototype.ensurePolled = function () { + this.forceCompositionEnd(); + }; + ContentEditableInput.prototype.reset = function () { + this.forceCompositionEnd(); + }; + ContentEditableInput.prototype.forceCompositionEnd = function () { + if (!this.composing) { return } + clearTimeout(this.readDOMTimeout); + this.composing = null; + this.updateFromDOM(); + this.div.blur(); + this.div.focus(); + }; + ContentEditableInput.prototype.readFromDOMSoon = function () { + var this$1 = this; + + if (this.readDOMTimeout != null) { return } + this.readDOMTimeout = setTimeout(function () { + this$1.readDOMTimeout = null; + if (this$1.composing) { + if (this$1.composing.done) { this$1.composing = null; } + else { return } + } + this$1.updateFromDOM(); + }, 80); + }; + + ContentEditableInput.prototype.updateFromDOM = function () { + var this$1 = this; + + if (this.cm.isReadOnly() || !this.pollContent()) + { runInOp(this.cm, function () { return regChange(this$1.cm); }); } + }; + + ContentEditableInput.prototype.setUneditable = function (node) { + node.contentEditable = "false"; + }; + + ContentEditableInput.prototype.onKeyPress = function (e) { + if (e.charCode == 0 || this.composing) { return } + e.preventDefault(); + if (!this.cm.isReadOnly()) + { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); } + }; + + ContentEditableInput.prototype.readOnlyChanged = function (val) { + this.div.contentEditable = String(val != "nocursor"); + }; + + ContentEditableInput.prototype.onContextMenu = function () {}; + ContentEditableInput.prototype.resetPosition = function () {}; + + ContentEditableInput.prototype.needsContentAttribute = true; + + function posToDOM(cm, pos) { + var view = findViewForLine(cm, pos.line); + if (!view || view.hidden) { return null } + var line = getLine(cm.doc, pos.line); + var info = mapFromLineView(view, line, pos.line); + + var order = getOrder(line, cm.doc.direction), side = "left"; + if (order) { + var partPos = getBidiPartAt(order, pos.ch); + side = partPos % 2 ? "right" : "left"; + } + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); + result.offset = result.collapse == "right" ? result.end : result.start; + return result + } + + function isInGutter(node) { + for (var scan = node; scan; scan = scan.parentNode) + { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } } + return false + } + + function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos } + + function domTextBetween(cm, from, to, fromLine, toLine) { + var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false; + function recognizeMarker(id) { return function (marker) { return marker.id == id; } } + function close() { + if (closing) { + text += lineSep; + if (extraLinebreak) { text += lineSep; } + closing = extraLinebreak = false; + } + } + function addText(str) { + if (str) { + close(); + text += str; + } + } + function walk(node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text"); + if (cmText) { + addText(cmText); + return + } + var markerID = node.getAttribute("cm-marker"), range$$1; + if (markerID) { + var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); + if (found.length && (range$$1 = found[0].find(0))) + { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); } + return + } + if (node.getAttribute("contenteditable") == "false") { return } + var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName); + if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return } + + if (isBlock) { close(); } + for (var i = 0; i < node.childNodes.length; i++) + { walk(node.childNodes[i]); } + + if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; } + if (isBlock) { closing = true; } + } else if (node.nodeType == 3) { + addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " ")); + } + } + for (;;) { + walk(from); + if (from == to) { break } + from = from.nextSibling; + extraLinebreak = false; + } + return text + } + + function domToPos(cm, node, offset) { + var lineNode; + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset]; + if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) } + node = null; offset = 0; + } else { + for (lineNode = node;; lineNode = lineNode.parentNode) { + if (!lineNode || lineNode == cm.display.lineDiv) { return null } + if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break } + } + } + for (var i = 0; i < cm.display.view.length; i++) { + var lineView = cm.display.view[i]; + if (lineView.node == lineNode) + { return locateNodeInLineView(lineView, node, offset) } + } + } + + function locateNodeInLineView(lineView, node, offset) { + var wrapper = lineView.text.firstChild, bad = false; + if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) } + if (node == wrapper) { + bad = true; + node = wrapper.childNodes[offset]; + offset = 0; + if (!node) { + var line = lineView.rest ? lst(lineView.rest) : lineView.line; + return badPos(Pos(lineNo(line), line.text.length), bad) + } + } + + var textNode = node.nodeType == 3 ? node : null, topNode = node; + if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { + textNode = node.firstChild; + if (offset) { offset = textNode.nodeValue.length; } + } + while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; } + var measure = lineView.measure, maps = measure.maps; + + function find(textNode, topNode, offset) { + for (var i = -1; i < (maps ? maps.length : 0); i++) { + var map$$1 = i < 0 ? measure.map : maps[i]; + for (var j = 0; j < map$$1.length; j += 3) { + var curNode = map$$1[j + 2]; + if (curNode == textNode || curNode == topNode) { + var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); + var ch = map$$1[j] + offset; + if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; } + return Pos(line, ch) + } + } + } + } + var found = find(textNode, topNode, offset); + if (found) { return badPos(found, bad) } + + // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems + for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { + found = find(after, after.firstChild, 0); + if (found) + { return badPos(Pos(found.line, found.ch - dist), bad) } + else + { dist += after.textContent.length; } + } + for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { + found = find(before, before.firstChild, -1); + if (found) + { return badPos(Pos(found.line, found.ch + dist$1), bad) } + else + { dist$1 += before.textContent.length; } + } + } + + // TEXTAREA INPUT STYLE + + var TextareaInput = function(cm) { + this.cm = cm; + // See input.poll and input.reset + this.prevInput = ""; + + // Flag that indicates whether we expect input to appear real soon + // now (after some event like 'keypress' or 'input') and are + // polling intensively. + this.pollingFast = false; + // Self-resetting timeout for the poller + this.polling = new Delayed(); + // Used to work around IE issue with selection being forgotten when focus moves away from textarea + this.hasSelection = false; + this.composing = null; + }; + + TextareaInput.prototype.init = function (display) { + var this$1 = this; + + var input = this, cm = this.cm; + this.createField(display); + var te = this.textarea; + + display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild); + + // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) + if (ios) { te.style.width = "0px"; } + + on(te, "input", function () { + if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; } + input.poll(); + }); + + on(te, "paste", function (e) { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } + + cm.state.pasteIncoming = +new Date; + input.fastPoll(); + }); + + function prepareCopyCut(e) { + if (signalDOMEvent(cm, e)) { return } + if (cm.somethingSelected()) { + setLastCopied({lineWise: false, text: cm.getSelections()}); + } else if (!cm.options.lineWiseCopyCut) { + return + } else { + var ranges = copyableRanges(cm); + setLastCopied({lineWise: true, text: ranges.text}); + if (e.type == "cut") { + cm.setSelections(ranges.ranges, null, sel_dontScroll); + } else { + input.prevInput = ""; + te.value = ranges.text.join("\n"); + selectInput(te); + } + } + if (e.type == "cut") { cm.state.cutIncoming = +new Date; } + } + on(te, "cut", prepareCopyCut); + on(te, "copy", prepareCopyCut); + + on(display.scroller, "paste", function (e) { + if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return } + if (!te.dispatchEvent) { + cm.state.pasteIncoming = +new Date; + input.focus(); + return + } + + // Pass the `paste` event to the textarea so it's handled by its event listener. + var event = new Event("paste"); + event.clipboardData = e.clipboardData; + te.dispatchEvent(event); + }); + + // Prevent normal selection in the editor (we handle our own) + on(display.lineSpace, "selectstart", function (e) { + if (!eventInWidget(display, e)) { e_preventDefault(e); } + }); + + on(te, "compositionstart", function () { + var start = cm.getCursor("from"); + if (input.composing) { input.composing.range.clear(); } + input.composing = { + start: start, + range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) + }; + }); + on(te, "compositionend", function () { + if (input.composing) { + input.poll(); + input.composing.range.clear(); + input.composing = null; + } + }); + }; + + TextareaInput.prototype.createField = function (_display) { + // Wraps and hides input textarea + this.wrapper = hiddenTextarea(); + // The semihidden textarea that is focused when the editor is + // focused, and receives input. + this.textarea = this.wrapper.firstChild; + }; + + TextareaInput.prototype.prepareSelection = function () { + // Redraw the selection and/or cursor + var cm = this.cm, display = cm.display, doc = cm.doc; + var result = prepareSelection(cm); + + // Move the hidden textarea near the cursor to prevent scrolling artifacts + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); + var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); + result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, + headPos.top + lineOff.top - wrapOff.top)); + result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, + headPos.left + lineOff.left - wrapOff.left)); + } + + return result + }; + + TextareaInput.prototype.showSelection = function (drawn) { + var cm = this.cm, display = cm.display; + removeChildrenAndAdd(display.cursorDiv, drawn.cursors); + removeChildrenAndAdd(display.selectionDiv, drawn.selection); + if (drawn.teTop != null) { + this.wrapper.style.top = drawn.teTop + "px"; + this.wrapper.style.left = drawn.teLeft + "px"; + } + }; + + // Reset the input to correspond to the selection (or to be empty, + // when not typing and nothing is selected) + TextareaInput.prototype.reset = function (typing) { + if (this.contextMenuPending || this.composing) { return } + var cm = this.cm; + if (cm.somethingSelected()) { + this.prevInput = ""; + var content = cm.getSelection(); + this.textarea.value = content; + if (cm.state.focused) { selectInput(this.textarea); } + if (ie && ie_version >= 9) { this.hasSelection = content; } + } else if (!typing) { + this.prevInput = this.textarea.value = ""; + if (ie && ie_version >= 9) { this.hasSelection = null; } + } + }; + + TextareaInput.prototype.getField = function () { return this.textarea }; + + TextareaInput.prototype.supportsTouch = function () { return false }; + + TextareaInput.prototype.focus = function () { + if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { + try { this.textarea.focus(); } + catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM + } + }; + + TextareaInput.prototype.blur = function () { this.textarea.blur(); }; + + TextareaInput.prototype.resetPosition = function () { + this.wrapper.style.top = this.wrapper.style.left = 0; + }; + + TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); }; + + // Poll for input changes, using the normal rate of polling. This + // runs as long as the editor is focused. + TextareaInput.prototype.slowPoll = function () { + var this$1 = this; + + if (this.pollingFast) { return } + this.polling.set(this.cm.options.pollInterval, function () { + this$1.poll(); + if (this$1.cm.state.focused) { this$1.slowPoll(); } + }); + }; + + // When an event has just come in that is likely to add or change + // something in the input textarea, we poll faster, to ensure that + // the change appears on the screen quickly. + TextareaInput.prototype.fastPoll = function () { + var missed = false, input = this; + input.pollingFast = true; + function p() { + var changed = input.poll(); + if (!changed && !missed) {missed = true; input.polling.set(60, p);} + else {input.pollingFast = false; input.slowPoll();} + } + input.polling.set(20, p); + }; + + // Read input from the textarea, and update the document to match. + // When something is selected, it is present in the textarea, and + // selected (unless it is huge, in which case a placeholder is + // used). When nothing is selected, the cursor sits after previously + // seen text (can be empty), which is stored in prevInput (we must + // not reset the textarea when typing, because that breaks IME). + TextareaInput.prototype.poll = function () { + var this$1 = this; + + var cm = this.cm, input = this.textarea, prevInput = this.prevInput; + // Since this is called a *lot*, try to bail out as cheaply as + // possible when it is clear that nothing happened. hasSelection + // will be the case when there is a lot of text in the textarea, + // in which case reading its value would be expensive. + if (this.contextMenuPending || !cm.state.focused || + (hasSelection(input) && !prevInput && !this.composing) || + cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) + { return false } + + var text = input.value; + // If nothing changed, bail. + if (text == prevInput && !cm.somethingSelected()) { return false } + // Work around nonsensical selection resetting in IE9/10, and + // inexplicable appearance of private area unicode characters on + // some key combos in Mac (#2689). + if (ie && ie_version >= 9 && this.hasSelection === text || + mac && /[\uf700-\uf7ff]/.test(text)) { + cm.display.input.reset(); + return false + } + + if (cm.doc.sel == cm.display.selForContextMenu) { + var first = text.charCodeAt(0); + if (first == 0x200b && !prevInput) { prevInput = "\u200b"; } + if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") } + } + // Find the part of the input that is actually new + var same = 0, l = Math.min(prevInput.length, text.length); + while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; } + + runInOp(cm, function () { + applyTextInput(cm, text.slice(same), prevInput.length - same, + null, this$1.composing ? "*compose" : null); + + // Don't leave long text in the textarea, since it makes further polling slow + if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; } + else { this$1.prevInput = text; } + + if (this$1.composing) { + this$1.composing.range.clear(); + this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), + {className: "CodeMirror-composing"}); + } + }); + return true + }; + + TextareaInput.prototype.ensurePolled = function () { + if (this.pollingFast && this.poll()) { this.pollingFast = false; } + }; + + TextareaInput.prototype.onKeyPress = function () { + if (ie && ie_version >= 9) { this.hasSelection = null; } + this.fastPoll(); + }; + + TextareaInput.prototype.onContextMenu = function (e) { + var input = this, cm = input.cm, display = cm.display, te = input.textarea; + if (input.contextMenuPending) { input.contextMenuPending(); } + var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; + if (!pos || presto) { return } // Opera is difficult. + + // Reset the current text selection only if the click is done outside of the selection + // and 'resetSelectionOnContextMenu' option is true. + var reset = cm.options.resetSelectionOnContextMenu; + if (reset && cm.doc.sel.contains(pos) == -1) + { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); } + + var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText; + var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect(); + input.wrapper.style.cssText = "position: static"; + te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; + var oldScrollY; + if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712) + display.input.focus(); + if (webkit) { window.scrollTo(null, oldScrollY); } + display.input.reset(); + // Adds "Select all" to context menu in FF + if (!cm.somethingSelected()) { te.value = input.prevInput = " "; } + input.contextMenuPending = rehide; + display.selForContextMenu = cm.doc.sel; + clearTimeout(display.detectingSelectAll); + + // Select-all will be greyed out if there's nothing to select, so + // this adds a zero-width space so that we can later check whether + // it got selected. + function prepareSelectAllHack() { + if (te.selectionStart != null) { + var selected = cm.somethingSelected(); + var extval = "\u200b" + (selected ? te.value : ""); + te.value = "\u21da"; // Used to catch context-menu undo + te.value = extval; + input.prevInput = selected ? "" : "\u200b"; + te.selectionStart = 1; te.selectionEnd = extval.length; + // Re-set this, in case some other handler touched the + // selection in the meantime. + display.selForContextMenu = cm.doc.sel; + } + } + function rehide() { + if (input.contextMenuPending != rehide) { return } + input.contextMenuPending = false; + input.wrapper.style.cssText = oldWrapperCSS; + te.style.cssText = oldCSS; + if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); } + + // Try to detect the user choosing select-all + if (te.selectionStart != null) { + if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); } + var i = 0, poll = function () { + if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && + te.selectionEnd > 0 && input.prevInput == "\u200b") { + operation(cm, selectAll)(cm); + } else if (i++ < 10) { + display.detectingSelectAll = setTimeout(poll, 500); + } else { + display.selForContextMenu = null; + display.input.reset(); + } + }; + display.detectingSelectAll = setTimeout(poll, 200); + } + } + + if (ie && ie_version >= 9) { prepareSelectAllHack(); } + if (captureRightClick) { + e_stop(e); + var mouseup = function () { + off(window, "mouseup", mouseup); + setTimeout(rehide, 20); + }; + on(window, "mouseup", mouseup); + } else { + setTimeout(rehide, 50); + } + }; + + TextareaInput.prototype.readOnlyChanged = function (val) { + if (!val) { this.reset(); } + this.textarea.disabled = val == "nocursor"; + }; + + TextareaInput.prototype.setUneditable = function () {}; + + TextareaInput.prototype.needsContentAttribute = false; + + function fromTextArea(textarea, options) { + options = options ? copyObj(options) : {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabIndex) + { options.tabindex = textarea.tabIndex; } + if (!options.placeholder && textarea.placeholder) + { options.placeholder = textarea.placeholder; } + // Set autofocus to true if this textarea is focused, or if it has + // autofocus and no other element is focused. + if (options.autofocus == null) { + var hasFocus = activeElt(); + options.autofocus = hasFocus == textarea || + textarea.getAttribute("autofocus") != null && hasFocus == document.body; + } + + function save() {textarea.value = cm.getValue();} + + var realSubmit; + if (textarea.form) { + on(textarea.form, "submit", save); + // Deplorable hack to make the submit method do the right thing. + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form; + realSubmit = form.submit; + try { + var wrappedSubmit = form.submit = function () { + save(); + form.submit = realSubmit; + form.submit(); + form.submit = wrappedSubmit; + }; + } catch(e) {} + } + } + + options.finishInit = function (cm) { + cm.save = save; + cm.getTextArea = function () { return textarea; }; + cm.toTextArea = function () { + cm.toTextArea = isNaN; // Prevent this from being ran twice + save(); + textarea.parentNode.removeChild(cm.getWrapperElement()); + textarea.style.display = ""; + if (textarea.form) { + off(textarea.form, "submit", save); + if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") + { textarea.form.submit = realSubmit; } + } + }; + }; + + textarea.style.display = "none"; + var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); }, + options); + return cm + } + + function addLegacyProps(CodeMirror) { + CodeMirror.off = off; + CodeMirror.on = on; + CodeMirror.wheelEventPixels = wheelEventPixels; + CodeMirror.Doc = Doc; + CodeMirror.splitLines = splitLinesAuto; + CodeMirror.countColumn = countColumn; + CodeMirror.findColumn = findColumn; + CodeMirror.isWordChar = isWordCharBasic; + CodeMirror.Pass = Pass; + CodeMirror.signal = signal; + CodeMirror.Line = Line; + CodeMirror.changeEnd = changeEnd; + CodeMirror.scrollbarModel = scrollbarModel; + CodeMirror.Pos = Pos; + CodeMirror.cmpPos = cmp; + CodeMirror.modes = modes; + CodeMirror.mimeModes = mimeModes; + CodeMirror.resolveMode = resolveMode; + CodeMirror.getMode = getMode; + CodeMirror.modeExtensions = modeExtensions; + CodeMirror.extendMode = extendMode; + CodeMirror.copyState = copyState; + CodeMirror.startState = startState; + CodeMirror.innerMode = innerMode; + CodeMirror.commands = commands; + CodeMirror.keyMap = keyMap; + CodeMirror.keyName = keyName; + CodeMirror.isModifierKey = isModifierKey; + CodeMirror.lookupKey = lookupKey; + CodeMirror.normalizeKeyMap = normalizeKeyMap; + CodeMirror.StringStream = StringStream; + CodeMirror.SharedTextMarker = SharedTextMarker; + CodeMirror.TextMarker = TextMarker; + CodeMirror.LineWidget = LineWidget; + CodeMirror.e_preventDefault = e_preventDefault; + CodeMirror.e_stopPropagation = e_stopPropagation; + CodeMirror.e_stop = e_stop; + CodeMirror.addClass = addClass; + CodeMirror.contains = contains; + CodeMirror.rmClass = rmClass; + CodeMirror.keyNames = keyNames; + } + + // EDITOR CONSTRUCTOR + + defineOptions(CodeMirror); + + addEditorMethods(CodeMirror); + + // Set up methods on CodeMirror's prototype to redirect to the editor's document. + var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); + for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) + { CodeMirror.prototype[prop] = (function(method) { + return function() {return method.apply(this.doc, arguments)} + })(Doc.prototype[prop]); } } + + eventMixin(Doc); + CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; + + // Extra arguments are stored as the mode's dependencies, which is + // used by (legacy) mechanisms like loadmode.js to automatically + // load a mode. (Preferred mechanism is the require/define calls.) + CodeMirror.defineMode = function(name/*, mode, …*/) { + if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; } + defineMode.apply(this, arguments); + }; + + CodeMirror.defineMIME = defineMIME; + + // Minimal default mode. + CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }); + CodeMirror.defineMIME("text/plain", "null"); + + // EXTENSIONS + + CodeMirror.defineExtension = function (name, func) { + CodeMirror.prototype[name] = func; + }; + CodeMirror.defineDocExtension = function (name, func) { + Doc.prototype[name] = func; + }; + + CodeMirror.fromTextArea = fromTextArea; + + addLegacyProps(CodeMirror); + + CodeMirror.version = "5.50.0"; + + return CodeMirror; + +}))); diff --git a/js/codemirror/5.50.0/css.js b/js/codemirror/5.50.0/css.js new file mode 100644 index 0000000..05742c5 --- /dev/null +++ b/js/codemirror/5.50.0/css.js @@ -0,0 +1,831 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("css", function(config, parserConfig) { + var inline = parserConfig.inline + if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css"); + + var indentUnit = config.indentUnit, + tokenHooks = parserConfig.tokenHooks, + documentTypes = parserConfig.documentTypes || {}, + mediaTypes = parserConfig.mediaTypes || {}, + mediaFeatures = parserConfig.mediaFeatures || {}, + mediaValueKeywords = parserConfig.mediaValueKeywords || {}, + propertyKeywords = parserConfig.propertyKeywords || {}, + nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {}, + fontProperties = parserConfig.fontProperties || {}, + counterDescriptors = parserConfig.counterDescriptors || {}, + colorKeywords = parserConfig.colorKeywords || {}, + valueKeywords = parserConfig.valueKeywords || {}, + allowNested = parserConfig.allowNested, + lineComment = parserConfig.lineComment, + supportsAtComponent = parserConfig.supportsAtComponent === true; + + var type, override; + function ret(style, tp) { type = tp; return style; } + + // Tokenizers + + function tokenBase(stream, state) { + var ch = stream.next(); + if (tokenHooks[ch]) { + var result = tokenHooks[ch](stream, state); + if (result !== false) return result; + } + if (ch == "@") { + stream.eatWhile(/[\w\\\-]/); + return ret("def", stream.current()); + } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) { + return ret(null, "compare"); + } else if (ch == "\"" || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "#") { + stream.eatWhile(/[\w\\\-]/); + return ret("atom", "hash"); + } else if (ch == "!") { + stream.match(/^\s*\w*/); + return ret("keyword", "important"); + } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (ch === "-") { + if (/[\d.]/.test(stream.peek())) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (stream.match(/^-[\w\\\-]*/)) { + stream.eatWhile(/[\w\\\-]/); + if (stream.match(/^\s*:/, false)) + return ret("variable-2", "variable-definition"); + return ret("variable-2", "variable"); + } else if (stream.match(/^\w+-/)) { + return ret("meta", "meta"); + } + } else if (/[,+>*\/]/.test(ch)) { + return ret(null, "select-op"); + } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) { + return ret("qualifier", "qualifier"); + } else if (/[:;{}\[\]\(\)]/.test(ch)) { + return ret(null, ch); + } else if (stream.match(/[\w-.]+(?=\()/)) { + if (/^(url(-prefix)?|domain|regexp)$/.test(stream.current().toLowerCase())) { + state.tokenize = tokenParenthesized; + } + return ret("variable callee", "variable"); + } else if (/[\w\\\-]/.test(ch)) { + stream.eatWhile(/[\w\\\-]/); + return ret("property", "word"); + } else { + return ret(null, null); + } + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) { + if (quote == ")") stream.backUp(1); + break; + } + escaped = !escaped && ch == "\\"; + } + if (ch == quote || !escaped && quote != ")") state.tokenize = null; + return ret("string", "string"); + }; + } + + function tokenParenthesized(stream, state) { + stream.next(); // Must be '(' + if (!stream.match(/\s*[\"\')]/, false)) + state.tokenize = tokenString(")"); + else + state.tokenize = null; + return ret(null, "("); + } + + // Context management + + function Context(type, indent, prev) { + this.type = type; + this.indent = indent; + this.prev = prev; + } + + function pushContext(state, stream, type, indent) { + state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context); + return type; + } + + function popContext(state) { + if (state.context.prev) + state.context = state.context.prev; + return state.context.type; + } + + function pass(type, stream, state) { + return states[state.context.type](type, stream, state); + } + function popAndPass(type, stream, state, n) { + for (var i = n || 1; i > 0; i--) + state.context = state.context.prev; + return pass(type, stream, state); + } + + // Parser + + function wordAsValue(stream) { + var word = stream.current().toLowerCase(); + if (valueKeywords.hasOwnProperty(word)) + override = "atom"; + else if (colorKeywords.hasOwnProperty(word)) + override = "keyword"; + else + override = "variable"; + } + + var states = {}; + + states.top = function(type, stream, state) { + if (type == "{") { + return pushContext(state, stream, "block"); + } else if (type == "}" && state.context.prev) { + return popContext(state); + } else if (supportsAtComponent && /@component/i.test(type)) { + return pushContext(state, stream, "atComponentBlock"); + } else if (/^@(-moz-)?document$/i.test(type)) { + return pushContext(state, stream, "documentTypes"); + } else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) { + return pushContext(state, stream, "atBlock"); + } else if (/^@(font-face|counter-style)/i.test(type)) { + state.stateArg = type; + return "restricted_atBlock_before"; + } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) { + return "keyframes"; + } else if (type && type.charAt(0) == "@") { + return pushContext(state, stream, "at"); + } else if (type == "hash") { + override = "builtin"; + } else if (type == "word") { + override = "tag"; + } else if (type == "variable-definition") { + return "maybeprop"; + } else if (type == "interpolation") { + return pushContext(state, stream, "interpolation"); + } else if (type == ":") { + return "pseudo"; + } else if (allowNested && type == "(") { + return pushContext(state, stream, "parens"); + } + return state.context.type; + }; + + states.block = function(type, stream, state) { + if (type == "word") { + var word = stream.current().toLowerCase(); + if (propertyKeywords.hasOwnProperty(word)) { + override = "property"; + return "maybeprop"; + } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) { + override = "string-2"; + return "maybeprop"; + } else if (allowNested) { + override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag"; + return "block"; + } else { + override += " error"; + return "maybeprop"; + } + } else if (type == "meta") { + return "block"; + } else if (!allowNested && (type == "hash" || type == "qualifier")) { + override = "error"; + return "block"; + } else { + return states.top(type, stream, state); + } + }; + + states.maybeprop = function(type, stream, state) { + if (type == ":") return pushContext(state, stream, "prop"); + return pass(type, stream, state); + }; + + states.prop = function(type, stream, state) { + if (type == ";") return popContext(state); + if (type == "{" && allowNested) return pushContext(state, stream, "propBlock"); + if (type == "}" || type == "{") return popAndPass(type, stream, state); + if (type == "(") return pushContext(state, stream, "parens"); + + if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) { + override += " error"; + } else if (type == "word") { + wordAsValue(stream); + } else if (type == "interpolation") { + return pushContext(state, stream, "interpolation"); + } + return "prop"; + }; + + states.propBlock = function(type, _stream, state) { + if (type == "}") return popContext(state); + if (type == "word") { override = "property"; return "maybeprop"; } + return state.context.type; + }; + + states.parens = function(type, stream, state) { + if (type == "{" || type == "}") return popAndPass(type, stream, state); + if (type == ")") return popContext(state); + if (type == "(") return pushContext(state, stream, "parens"); + if (type == "interpolation") return pushContext(state, stream, "interpolation"); + if (type == "word") wordAsValue(stream); + return "parens"; + }; + + states.pseudo = function(type, stream, state) { + if (type == "meta") return "pseudo"; + + if (type == "word") { + override = "variable-3"; + return state.context.type; + } + return pass(type, stream, state); + }; + + states.documentTypes = function(type, stream, state) { + if (type == "word" && documentTypes.hasOwnProperty(stream.current())) { + override = "tag"; + return state.context.type; + } else { + return states.atBlock(type, stream, state); + } + }; + + states.atBlock = function(type, stream, state) { + if (type == "(") return pushContext(state, stream, "atBlock_parens"); + if (type == "}" || type == ";") return popAndPass(type, stream, state); + if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top"); + + if (type == "interpolation") return pushContext(state, stream, "interpolation"); + + if (type == "word") { + var word = stream.current().toLowerCase(); + if (word == "only" || word == "not" || word == "and" || word == "or") + override = "keyword"; + else if (mediaTypes.hasOwnProperty(word)) + override = "attribute"; + else if (mediaFeatures.hasOwnProperty(word)) + override = "property"; + else if (mediaValueKeywords.hasOwnProperty(word)) + override = "keyword"; + else if (propertyKeywords.hasOwnProperty(word)) + override = "property"; + else if (nonStandardPropertyKeywords.hasOwnProperty(word)) + override = "string-2"; + else if (valueKeywords.hasOwnProperty(word)) + override = "atom"; + else if (colorKeywords.hasOwnProperty(word)) + override = "keyword"; + else + override = "error"; + } + return state.context.type; + }; + + states.atComponentBlock = function(type, stream, state) { + if (type == "}") + return popAndPass(type, stream, state); + if (type == "{") + return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false); + if (type == "word") + override = "error"; + return state.context.type; + }; + + states.atBlock_parens = function(type, stream, state) { + if (type == ")") return popContext(state); + if (type == "{" || type == "}") return popAndPass(type, stream, state, 2); + return states.atBlock(type, stream, state); + }; + + states.restricted_atBlock_before = function(type, stream, state) { + if (type == "{") + return pushContext(state, stream, "restricted_atBlock"); + if (type == "word" && state.stateArg == "@counter-style") { + override = "variable"; + return "restricted_atBlock_before"; + } + return pass(type, stream, state); + }; + + states.restricted_atBlock = function(type, stream, state) { + if (type == "}") { + state.stateArg = null; + return popContext(state); + } + if (type == "word") { + if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) || + (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase()))) + override = "error"; + else + override = "property"; + return "maybeprop"; + } + return "restricted_atBlock"; + }; + + states.keyframes = function(type, stream, state) { + if (type == "word") { override = "variable"; return "keyframes"; } + if (type == "{") return pushContext(state, stream, "top"); + return pass(type, stream, state); + }; + + states.at = function(type, stream, state) { + if (type == ";") return popContext(state); + if (type == "{" || type == "}") return popAndPass(type, stream, state); + if (type == "word") override = "tag"; + else if (type == "hash") override = "builtin"; + return "at"; + }; + + states.interpolation = function(type, stream, state) { + if (type == "}") return popContext(state); + if (type == "{" || type == ";") return popAndPass(type, stream, state); + if (type == "word") override = "variable"; + else if (type != "variable" && type != "(" && type != ")") override = "error"; + return "interpolation"; + }; + + return { + startState: function(base) { + return {tokenize: null, + state: inline ? "block" : "top", + stateArg: null, + context: new Context(inline ? "block" : "top", base || 0, null)}; + }, + + token: function(stream, state) { + if (!state.tokenize && stream.eatSpace()) return null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style && typeof style == "object") { + type = style[1]; + style = style[0]; + } + override = style; + if (type != "comment") + state.state = states[state.state](type, stream, state); + return override; + }, + + indent: function(state, textAfter) { + var cx = state.context, ch = textAfter && textAfter.charAt(0); + var indent = cx.indent; + if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev; + if (cx.prev) { + if (ch == "}" && (cx.type == "block" || cx.type == "top" || + cx.type == "interpolation" || cx.type == "restricted_atBlock")) { + // Resume indentation from parent context. + cx = cx.prev; + indent = cx.indent; + } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") || + ch == "{" && (cx.type == "at" || cx.type == "atBlock")) { + // Dedent relative to current context. + indent = Math.max(0, cx.indent - indentUnit); + } + } + return indent; + }, + + electricChars: "}", + blockCommentStart: "/*", + blockCommentEnd: "*/", + blockCommentContinue: " * ", + lineComment: lineComment, + fold: "brace" + }; +}); + + function keySet(array) { + var keys = {}; + for (var i = 0; i < array.length; ++i) { + keys[array[i].toLowerCase()] = true; + } + return keys; + } + + var documentTypes_ = [ + "domain", "regexp", "url", "url-prefix" + ], documentTypes = keySet(documentTypes_); + + var mediaTypes_ = [ + "all", "aural", "braille", "handheld", "print", "projection", "screen", + "tty", "tv", "embossed" + ], mediaTypes = keySet(mediaTypes_); + + var mediaFeatures_ = [ + "width", "min-width", "max-width", "height", "min-height", "max-height", + "device-width", "min-device-width", "max-device-width", "device-height", + "min-device-height", "max-device-height", "aspect-ratio", + "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio", + "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color", + "max-color", "color-index", "min-color-index", "max-color-index", + "monochrome", "min-monochrome", "max-monochrome", "resolution", + "min-resolution", "max-resolution", "scan", "grid", "orientation", + "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio", + "pointer", "any-pointer", "hover", "any-hover" + ], mediaFeatures = keySet(mediaFeatures_); + + var mediaValueKeywords_ = [ + "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover", + "interlace", "progressive" + ], mediaValueKeywords = keySet(mediaValueKeywords_); + + var propertyKeywords_ = [ + "align-content", "align-items", "align-self", "alignment-adjust", + "alignment-baseline", "anchor-point", "animation", "animation-delay", + "animation-direction", "animation-duration", "animation-fill-mode", + "animation-iteration-count", "animation-name", "animation-play-state", + "animation-timing-function", "appearance", "azimuth", "backface-visibility", + "background", "background-attachment", "background-blend-mode", "background-clip", + "background-color", "background-image", "background-origin", "background-position", + "background-repeat", "background-size", "baseline-shift", "binding", + "bleed", "bookmark-label", "bookmark-level", "bookmark-state", + "bookmark-target", "border", "border-bottom", "border-bottom-color", + "border-bottom-left-radius", "border-bottom-right-radius", + "border-bottom-style", "border-bottom-width", "border-collapse", + "border-color", "border-image", "border-image-outset", + "border-image-repeat", "border-image-slice", "border-image-source", + "border-image-width", "border-left", "border-left-color", + "border-left-style", "border-left-width", "border-radius", "border-right", + "border-right-color", "border-right-style", "border-right-width", + "border-spacing", "border-style", "border-top", "border-top-color", + "border-top-left-radius", "border-top-right-radius", "border-top-style", + "border-top-width", "border-width", "bottom", "box-decoration-break", + "box-shadow", "box-sizing", "break-after", "break-before", "break-inside", + "caption-side", "caret-color", "clear", "clip", "color", "color-profile", "column-count", + "column-fill", "column-gap", "column-rule", "column-rule-color", + "column-rule-style", "column-rule-width", "column-span", "column-width", + "columns", "content", "counter-increment", "counter-reset", "crop", "cue", + "cue-after", "cue-before", "cursor", "direction", "display", + "dominant-baseline", "drop-initial-after-adjust", + "drop-initial-after-align", "drop-initial-before-adjust", + "drop-initial-before-align", "drop-initial-size", "drop-initial-value", + "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis", + "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap", + "float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings", + "font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust", + "font-stretch", "font-style", "font-synthesis", "font-variant", + "font-variant-alternates", "font-variant-caps", "font-variant-east-asian", + "font-variant-ligatures", "font-variant-numeric", "font-variant-position", + "font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow", + "grid-auto-rows", "grid-column", "grid-column-end", "grid-column-gap", + "grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap", + "grid-row-start", "grid-template", "grid-template-areas", "grid-template-columns", + "grid-template-rows", "hanging-punctuation", "height", "hyphens", + "icon", "image-orientation", "image-rendering", "image-resolution", + "inline-box-align", "justify-content", "justify-items", "justify-self", "left", "letter-spacing", + "line-break", "line-height", "line-stacking", "line-stacking-ruby", + "line-stacking-shift", "line-stacking-strategy", "list-style", + "list-style-image", "list-style-position", "list-style-type", "margin", + "margin-bottom", "margin-left", "margin-right", "margin-top", + "marks", "marquee-direction", "marquee-loop", + "marquee-play-count", "marquee-speed", "marquee-style", "max-height", + "max-width", "min-height", "min-width", "mix-blend-mode", "move-to", "nav-down", "nav-index", + "nav-left", "nav-right", "nav-up", "object-fit", "object-position", + "opacity", "order", "orphans", "outline", + "outline-color", "outline-offset", "outline-style", "outline-width", + "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y", + "padding", "padding-bottom", "padding-left", "padding-right", "padding-top", + "page", "page-break-after", "page-break-before", "page-break-inside", + "page-policy", "pause", "pause-after", "pause-before", "perspective", + "perspective-origin", "pitch", "pitch-range", "place-content", "place-items", "place-self", "play-during", "position", + "presentation-level", "punctuation-trim", "quotes", "region-break-after", + "region-break-before", "region-break-inside", "region-fragment", + "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness", + "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang", + "ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin", + "shape-outside", "size", "speak", "speak-as", "speak-header", + "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set", + "tab-size", "table-layout", "target", "target-name", "target-new", + "target-position", "text-align", "text-align-last", "text-decoration", + "text-decoration-color", "text-decoration-line", "text-decoration-skip", + "text-decoration-style", "text-emphasis", "text-emphasis-color", + "text-emphasis-position", "text-emphasis-style", "text-height", + "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow", + "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position", + "text-wrap", "top", "transform", "transform-origin", "transform-style", + "transition", "transition-delay", "transition-duration", + "transition-property", "transition-timing-function", "unicode-bidi", + "user-select", "vertical-align", "visibility", "voice-balance", "voice-duration", + "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress", + "voice-volume", "volume", "white-space", "widows", "width", "will-change", "word-break", + "word-spacing", "word-wrap", "z-index", + // SVG-specific + "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color", + "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events", + "color-interpolation", "color-interpolation-filters", + "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering", + "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke", + "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", + "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering", + "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal", + "glyph-orientation-vertical", "text-anchor", "writing-mode" + ], propertyKeywords = keySet(propertyKeywords_); + + var nonStandardPropertyKeywords_ = [ + "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color", + "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color", + "scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside", + "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", + "searchfield-results-decoration", "zoom" + ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_); + + var fontProperties_ = [ + "font-family", "src", "unicode-range", "font-variant", "font-feature-settings", + "font-stretch", "font-weight", "font-style" + ], fontProperties = keySet(fontProperties_); + + var counterDescriptors_ = [ + "additive-symbols", "fallback", "negative", "pad", "prefix", "range", + "speak-as", "suffix", "symbols", "system" + ], counterDescriptors = keySet(counterDescriptors_); + + var colorKeywords_ = [ + "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", + "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", + "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", + "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", + "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", + "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", + "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", + "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", + "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", + "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew", + "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", + "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", + "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink", + "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", + "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", + "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", + "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", + "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", + "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", + "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", + "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", + "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown", + "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", + "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", + "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", + "whitesmoke", "yellow", "yellowgreen" + ], colorKeywords = keySet(colorKeywords_); + + var valueKeywords_ = [ + "above", "absolute", "activeborder", "additive", "activecaption", "afar", + "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate", + "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", + "arabic-indic", "armenian", "asterisks", "attr", "auto", "auto-flow", "avoid", "avoid-column", "avoid-page", + "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary", + "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box", + "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel", + "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian", + "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", + "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch", + "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", + "col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse", + "compact", "condensed", "contain", "content", "contents", + "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop", + "cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal", + "decimal-leading-zero", "default", "default-button", "dense", "destination-atop", + "destination-in", "destination-out", "destination-over", "devanagari", "difference", + "disc", "discard", "disclosure-closed", "disclosure-open", "document", + "dot-dash", "dot-dot-dash", + "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", + "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", + "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er", + "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", + "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et", + "ethiopic-halehame-gez", "ethiopic-halehame-om-et", + "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et", + "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig", + "ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed", + "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes", + "forwards", "from", "geometricPrecision", "georgian", "graytext", "grid", "groove", + "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew", + "help", "hidden", "hide", "higher", "highlight", "highlighttext", + "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "icon", "ignore", + "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", + "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", + "inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert", + "italic", "japanese-formal", "japanese-informal", "justify", "kannada", + "katakana", "katakana-iroha", "keep-all", "khmer", + "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal", + "landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten", + "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem", + "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", + "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian", + "lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "match", "matrix", "matrix3d", + "media-controls-background", "media-current-time-display", + "media-fullscreen-button", "media-mute-button", "media-play-button", + "media-return-to-realtime-button", "media-rewind-button", + "media-seek-back-button", "media-seek-forward-button", "media-slider", + "media-sliderthumb", "media-time-remaining-display", "media-volume-slider", + "media-volume-slider-container", "media-volume-sliderthumb", "medium", + "menu", "menulist", "menulist-button", "menulist-text", + "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic", + "mix", "mongolian", "monospace", "move", "multiple", "multiply", "myanmar", "n-resize", + "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", + "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", + "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "opacity", "open-quote", + "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", + "outside", "outside-shape", "overlay", "overline", "padding", "padding-box", + "painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter", + "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", + "progress", "push-button", "radial-gradient", "radio", "read-only", + "read-write", "read-write-plaintext-only", "rectangle", "region", + "relative", "repeat", "repeating-linear-gradient", + "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse", + "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY", + "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running", + "s-resize", "sans-serif", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen", + "scroll", "scrollbar", "scroll-position", "se-resize", "searchfield", + "searchfield-cancel-button", "searchfield-decoration", + "searchfield-results-button", "searchfield-results-decoration", "self-start", "self-end", + "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama", + "simp-chinese-formal", "simp-chinese-informal", "single", + "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal", + "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", + "small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali", + "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "space-evenly", "spell-out", "square", + "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub", + "subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "system-ui", "table", + "table-caption", "table-cell", "table-column", "table-column-group", + "table-footer-group", "table-header-group", "table-row", "table-row-group", + "tamil", + "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai", + "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight", + "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er", + "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top", + "trad-chinese-formal", "trad-chinese-informal", "transform", + "translate", "translate3d", "translateX", "translateY", "translateZ", + "transparent", "ultra-condensed", "ultra-expanded", "underline", "unset", "up", + "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", + "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", + "var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted", + "visibleStroke", "visual", "w-resize", "wait", "wave", "wider", + "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor", + "xx-large", "xx-small" + ], valueKeywords = keySet(valueKeywords_); + + var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_) + .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_) + .concat(valueKeywords_); + CodeMirror.registerHelper("hintWords", "css", allWords); + + function tokenCComment(stream, state) { + var maybeEnd = false, ch; + while ((ch = stream.next()) != null) { + if (maybeEnd && ch == "/") { + state.tokenize = null; + break; + } + maybeEnd = (ch == "*"); + } + return ["comment", "comment"]; + } + + CodeMirror.defineMIME("text/css", { + documentTypes: documentTypes, + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + fontProperties: fontProperties, + counterDescriptors: counterDescriptors, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + tokenHooks: { + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + }, + name: "css" + }); + + CodeMirror.defineMIME("text/x-scss", { + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + fontProperties: fontProperties, + allowNested: true, + lineComment: "//", + tokenHooks: { + "/": function(stream, state) { + if (stream.eat("/")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } else if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else { + return ["operator", "operator"]; + } + }, + ":": function(stream) { + if (stream.match(/\s*\{/, false)) + return [null, null] + return false; + }, + "$": function(stream) { + stream.match(/^[\w-]+/); + if (stream.match(/^\s*:/, false)) + return ["variable-2", "variable-definition"]; + return ["variable-2", "variable"]; + }, + "#": function(stream) { + if (!stream.eat("{")) return false; + return [null, "interpolation"]; + } + }, + name: "css", + helperType: "scss" + }); + + CodeMirror.defineMIME("text/x-less", { + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + fontProperties: fontProperties, + allowNested: true, + lineComment: "//", + tokenHooks: { + "/": function(stream, state) { + if (stream.eat("/")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } else if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else { + return ["operator", "operator"]; + } + }, + "@": function(stream) { + if (stream.eat("{")) return [null, "interpolation"]; + if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i, false)) return false; + stream.eatWhile(/[\w\\\-]/); + if (stream.match(/^\s*:/, false)) + return ["variable-2", "variable-definition"]; + return ["variable-2", "variable"]; + }, + "&": function() { + return ["atom", "atom"]; + } + }, + name: "css", + helperType: "less" + }); + + CodeMirror.defineMIME("text/x-gss", { + documentTypes: documentTypes, + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + fontProperties: fontProperties, + counterDescriptors: counterDescriptors, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + supportsAtComponent: true, + tokenHooks: { + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + }, + name: "css", + helperType: "gss" + }); + +}); diff --git a/js/codemirror/5.50.0/htmlmixed.js b/js/codemirror/5.50.0/htmlmixed.js new file mode 100644 index 0000000..8341ac8 --- /dev/null +++ b/js/codemirror/5.50.0/htmlmixed.js @@ -0,0 +1,152 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("../xml/xml"), require("../javascript/javascript"), require("../css/css")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript", "../css/css"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var defaultTags = { + script: [ + ["lang", /(javascript|babel)/i, "javascript"], + ["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i, "javascript"], + ["type", /./, "text/plain"], + [null, null, "javascript"] + ], + style: [ + ["lang", /^css$/i, "css"], + ["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"], + ["type", /./, "text/plain"], + [null, null, "css"] + ] + }; + + function maybeBackup(stream, pat, style) { + var cur = stream.current(), close = cur.search(pat); + if (close > -1) { + stream.backUp(cur.length - close); + } else if (cur.match(/<\/?$/)) { + stream.backUp(cur.length); + if (!stream.match(pat, false)) stream.match(cur); + } + return style; + } + + var attrRegexpCache = {}; + function getAttrRegexp(attr) { + var regexp = attrRegexpCache[attr]; + if (regexp) return regexp; + return attrRegexpCache[attr] = new RegExp("\\s+" + attr + "\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*"); + } + + function getAttrValue(text, attr) { + var match = text.match(getAttrRegexp(attr)) + return match ? /^\s*(.*?)\s*$/.exec(match[2])[1] : "" + } + + function getTagRegexp(tagName, anchored) { + return new RegExp((anchored ? "^" : "") + "<\/\s*" + tagName + "\s*>", "i"); + } + + function addTags(from, to) { + for (var tag in from) { + var dest = to[tag] || (to[tag] = []); + var source = from[tag]; + for (var i = source.length - 1; i >= 0; i--) + dest.unshift(source[i]) + } + } + + function findMatchingMode(tagInfo, tagText) { + for (var i = 0; i < tagInfo.length; i++) { + var spec = tagInfo[i]; + if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2]; + } + } + + CodeMirror.defineMode("htmlmixed", function (config, parserConfig) { + var htmlMode = CodeMirror.getMode(config, { + name: "xml", + htmlMode: true, + multilineTagIndentFactor: parserConfig.multilineTagIndentFactor, + multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag + }); + + var tags = {}; + var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes; + addTags(defaultTags, tags); + if (configTags) addTags(configTags, tags); + if (configScript) for (var i = configScript.length - 1; i >= 0; i--) + tags.script.unshift(["type", configScript[i].matches, configScript[i].mode]) + + function html(stream, state) { + var style = htmlMode.token(stream, state.htmlState), tag = /\btag\b/.test(style), tagName + if (tag && !/[<>\s\/]/.test(stream.current()) && + (tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) && + tags.hasOwnProperty(tagName)) { + state.inTag = tagName + " " + } else if (state.inTag && tag && />$/.test(stream.current())) { + var inTag = /^([\S]+) (.*)/.exec(state.inTag) + state.inTag = null + var modeSpec = stream.current() == ">" && findMatchingMode(tags[inTag[1]], inTag[2]) + var mode = CodeMirror.getMode(config, modeSpec) + var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false); + state.token = function (stream, state) { + if (stream.match(endTagA, false)) { + state.token = html; + state.localState = state.localMode = null; + return null; + } + return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState)); + }; + state.localMode = mode; + state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, "", "")); + } else if (state.inTag) { + state.inTag += stream.current() + if (stream.eol()) state.inTag += " " + } + return style; + }; + + return { + startState: function () { + var state = CodeMirror.startState(htmlMode); + return {token: html, inTag: null, localMode: null, localState: null, htmlState: state}; + }, + + copyState: function (state) { + var local; + if (state.localState) { + local = CodeMirror.copyState(state.localMode, state.localState); + } + return {token: state.token, inTag: state.inTag, + localMode: state.localMode, localState: local, + htmlState: CodeMirror.copyState(htmlMode, state.htmlState)}; + }, + + token: function (stream, state) { + return state.token(stream, state); + }, + + indent: function (state, textAfter, line) { + if (!state.localMode || /^\s*<\//.test(textAfter)) + return htmlMode.indent(state.htmlState, textAfter, line); + else if (state.localMode.indent) + return state.localMode.indent(state.localState, textAfter, line); + else + return CodeMirror.Pass; + }, + + innerMode: function (state) { + return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode}; + } + }; + }, "xml", "javascript", "css"); + + CodeMirror.defineMIME("text/html", "htmlmixed"); +}); diff --git a/js/codemirror/5.50.0/javascript.js b/js/codemirror/5.50.0/javascript.js new file mode 100644 index 0000000..16943a9 --- /dev/null +++ b/js/codemirror/5.50.0/javascript.js @@ -0,0 +1,930 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("javascript", function(config, parserConfig) { + var indentUnit = config.indentUnit; + var statementIndent = parserConfig.statementIndent; + var jsonldMode = parserConfig.jsonld; + var jsonMode = parserConfig.json || jsonldMode; + var isTS = parserConfig.typescript; + var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; + + // Tokenizer + + var keywords = function(){ + function kw(type) {return {type: type, style: "keyword"};} + var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d"); + var operator = kw("operator"), atom = {type: "atom", style: "atom"}; + + return { + "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, + "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C, + "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"), + "function": kw("function"), "catch": kw("catch"), + "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), + "in": operator, "typeof": operator, "instanceof": operator, + "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, + "this": kw("this"), "class": kw("class"), "super": kw("atom"), + "yield": C, "export": kw("export"), "import": kw("import"), "extends": C, + "await": C + }; + }(); + + var isOperatorChar = /[+\-*&%=<>!?|~^@]/; + var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; + + function readRegexp(stream) { + var escaped = false, next, inSet = false; + while ((next = stream.next()) != null) { + if (!escaped) { + if (next == "/" && !inSet) return; + if (next == "[") inSet = true; + else if (inSet && next == "]") inSet = false; + } + escaped = !escaped && next == "\\"; + } + } + + // Used as scratch variables to communicate multiple values without + // consing up tons of objects. + var type, content; + function ret(tp, style, cont) { + type = tp; content = cont; + return style; + } + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) { + return ret("number", "number"); + } else if (ch == "." && stream.match("..")) { + return ret("spread", "meta"); + } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + return ret(ch); + } else if (ch == "=" && stream.eat(">")) { + return ret("=>", "operator"); + } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) { + return ret("number", "number"); + } else if (/\d/.test(ch)) { + stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/); + return ret("number", "number"); + } else if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } else if (stream.eat("/")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } else if (expressionAllowed(stream, state, 1)) { + readRegexp(stream); + stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); + return ret("regexp", "string-2"); + } else { + stream.eat("="); + return ret("operator", "operator", stream.current()); + } + } else if (ch == "`") { + state.tokenize = tokenQuasi; + return tokenQuasi(stream, state); + } else if (ch == "#") { + stream.skipToEnd(); + return ret("error", "error"); + } else if (ch == "<" && stream.match("!--") || ch == "-" && stream.match("->")) { + stream.skipToEnd() + return ret("comment", "comment") + } else if (isOperatorChar.test(ch)) { + if (ch != ">" || !state.lexical || state.lexical.type != ">") { + if (stream.eat("=")) { + if (ch == "!" || ch == "=") stream.eat("=") + } else if (/[<>*+\-]/.test(ch)) { + stream.eat(ch) + if (ch == ">") stream.eat(ch) + } + } + return ret("operator", "operator", stream.current()); + } else if (wordRE.test(ch)) { + stream.eatWhile(wordRE); + var word = stream.current() + if (state.lastType != ".") { + if (keywords.propertyIsEnumerable(word)) { + var kw = keywords[word] + return ret(kw.type, kw.style, word) + } + if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/, false)) + return ret("async", "keyword", word) + } + return ret("variable", "variable", word) + } + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next; + if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ + state.tokenize = tokenBase; + return ret("jsonld-keyword", "meta"); + } + while ((next = stream.next()) != null) { + if (next == quote && !escaped) break; + escaped = !escaped && next == "\\"; + } + if (!escaped) state.tokenize = tokenBase; + return ret("string", "string"); + }; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return ret("comment", "comment"); + } + + function tokenQuasi(stream, state) { + var escaped = false, next; + while ((next = stream.next()) != null) { + if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { + state.tokenize = tokenBase; + break; + } + escaped = !escaped && next == "\\"; + } + return ret("quasi", "string-2", stream.current()); + } + + var brackets = "([{}])"; + // This is a crude lookahead trick to try and notice that we're + // parsing the argument patterns for a fat-arrow function before we + // actually hit the arrow token. It only works if the arrow is on + // the same line as the arguments and there's no strange noise + // (comments) in between. Fallback is to only notice when we hit the + // arrow, and not declare the arguments as locals for the arrow + // body. + function findFatArrow(stream, state) { + if (state.fatArrowAt) state.fatArrowAt = null; + var arrow = stream.string.indexOf("=>", stream.start); + if (arrow < 0) return; + + if (isTS) { // Try to skip TypeScript return type declarations after the arguments + var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)) + if (m) arrow = m.index + } + + var depth = 0, sawSomething = false; + for (var pos = arrow - 1; pos >= 0; --pos) { + var ch = stream.string.charAt(pos); + var bracket = brackets.indexOf(ch); + if (bracket >= 0 && bracket < 3) { + if (!depth) { ++pos; break; } + if (--depth == 0) { if (ch == "(") sawSomething = true; break; } + } else if (bracket >= 3 && bracket < 6) { + ++depth; + } else if (wordRE.test(ch)) { + sawSomething = true; + } else if (/["'\/`]/.test(ch)) { + for (;; --pos) { + if (pos == 0) return + var next = stream.string.charAt(pos - 1) + if (next == ch && stream.string.charAt(pos - 2) != "\\") { pos--; break } + } + } else if (sawSomething && !depth) { + ++pos; + break; + } + } + if (sawSomething && !depth) state.fatArrowAt = pos; + } + + // Parser + + var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; + + function JSLexical(indented, column, type, align, prev, info) { + this.indented = indented; + this.column = column; + this.type = type; + this.prev = prev; + this.info = info; + if (align != null) this.align = align; + } + + function inScope(state, varname) { + for (var v = state.localVars; v; v = v.next) + if (v.name == varname) return true; + for (var cx = state.context; cx; cx = cx.prev) { + for (var v = cx.vars; v; v = v.next) + if (v.name == varname) return true; + } + } + + function parseJS(state, style, type, content, stream) { + var cc = state.cc; + // Communicate our context to the combinators. + // (Less wasteful than consing up a hundred closures on every call.) + cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; + + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = true; + + while(true) { + var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; + if (combinator(type, content)) { + while(cc.length && cc[cc.length - 1].lex) + cc.pop()(); + if (cx.marked) return cx.marked; + if (type == "variable" && inScope(state, content)) return "variable-2"; + return style; + } + } + } + + // Combinator utils + + var cx = {state: null, column: null, marked: null, cc: null}; + function pass() { + for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); + } + function cont() { + pass.apply(null, arguments); + return true; + } + function inList(name, list) { + for (var v = list; v; v = v.next) if (v.name == name) return true + return false; + } + function register(varname) { + var state = cx.state; + cx.marked = "def"; + if (state.context) { + if (state.lexical.info == "var" && state.context && state.context.block) { + // FIXME function decls are also not block scoped + var newContext = registerVarScoped(varname, state.context) + if (newContext != null) { + state.context = newContext + return + } + } else if (!inList(varname, state.localVars)) { + state.localVars = new Var(varname, state.localVars) + return + } + } + // Fall through means this is global + if (parserConfig.globalVars && !inList(varname, state.globalVars)) + state.globalVars = new Var(varname, state.globalVars) + } + function registerVarScoped(varname, context) { + if (!context) { + return null + } else if (context.block) { + var inner = registerVarScoped(varname, context.prev) + if (!inner) return null + if (inner == context.prev) return context + return new Context(inner, context.vars, true) + } else if (inList(varname, context.vars)) { + return context + } else { + return new Context(context.prev, new Var(varname, context.vars), false) + } + } + + function isModifier(name) { + return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly" + } + + // Combinators + + function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block } + function Var(name, next) { this.name = name; this.next = next } + + var defaultVars = new Var("this", new Var("arguments", null)) + function pushcontext() { + cx.state.context = new Context(cx.state.context, cx.state.localVars, false) + cx.state.localVars = defaultVars + } + function pushblockcontext() { + cx.state.context = new Context(cx.state.context, cx.state.localVars, true) + cx.state.localVars = null + } + function popcontext() { + cx.state.localVars = cx.state.context.vars + cx.state.context = cx.state.context.prev + } + popcontext.lex = true + function pushlex(type, info) { + var result = function() { + var state = cx.state, indent = state.indented; + if (state.lexical.type == "stat") indent = state.lexical.indented; + else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) + indent = outer.indented; + state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); + }; + result.lex = true; + return result; + } + function poplex() { + var state = cx.state; + if (state.lexical.prev) { + if (state.lexical.type == ")") + state.indented = state.lexical.indented; + state.lexical = state.lexical.prev; + } + } + poplex.lex = true; + + function expect(wanted) { + function exp(type) { + if (type == wanted) return cont(); + else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass(); + else return cont(exp); + }; + return exp; + } + + function statement(type, value) { + if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex); + if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); + if (type == "keyword b") return cont(pushlex("form"), statement, poplex); + if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); + if (type == "debugger") return cont(expect(";")); + if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext); + if (type == ";") return cont(); + if (type == "if") { + if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) + cx.state.cc.pop()(); + return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); + } + if (type == "function") return cont(functiondef); + if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); + if (type == "class" || (isTS && value == "interface")) { + cx.marked = "keyword" + return cont(pushlex("form", type == "class" ? type : value), className, poplex) + } + if (type == "variable") { + if (isTS && value == "declare") { + cx.marked = "keyword" + return cont(statement) + } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { + cx.marked = "keyword" + if (value == "enum") return cont(enumdef); + else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";")); + else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex) + } else if (isTS && value == "namespace") { + cx.marked = "keyword" + return cont(pushlex("form"), expression, statement, poplex) + } else if (isTS && value == "abstract") { + cx.marked = "keyword" + return cont(statement) + } else { + return cont(pushlex("stat"), maybelabel); + } + } + if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext, + block, poplex, poplex, popcontext); + if (type == "case") return cont(expression, expect(":")); + if (type == "default") return cont(expect(":")); + if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext); + if (type == "export") return cont(pushlex("stat"), afterExport, poplex); + if (type == "import") return cont(pushlex("stat"), afterImport, poplex); + if (type == "async") return cont(statement) + if (value == "@") return cont(expression, statement) + return pass(pushlex("stat"), expression, expect(";"), poplex); + } + function maybeCatchBinding(type) { + if (type == "(") return cont(funarg, expect(")")) + } + function expression(type, value) { + return expressionInner(type, value, false); + } + function expressionNoComma(type, value) { + return expressionInner(type, value, true); + } + function parenExpr(type) { + if (type != "(") return pass() + return cont(pushlex(")"), expression, expect(")"), poplex) + } + function expressionInner(type, value, noComma) { + if (cx.state.fatArrowAt == cx.stream.start) { + var body = noComma ? arrowBodyNoComma : arrowBody; + if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext); + else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); + } + + var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; + if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); + if (type == "function") return cont(functiondef, maybeop); + if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); } + if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression); + if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); + if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); + if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); + if (type == "{") return contCommasep(objprop, "}", null, maybeop); + if (type == "quasi") return pass(quasi, maybeop); + if (type == "new") return cont(maybeTarget(noComma)); + if (type == "import") return cont(expression); + return cont(); + } + function maybeexpression(type) { + if (type.match(/[;\}\)\],]/)) return pass(); + return pass(expression); + } + + function maybeoperatorComma(type, value) { + if (type == ",") return cont(expression); + return maybeoperatorNoComma(type, value, false); + } + function maybeoperatorNoComma(type, value, noComma) { + var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; + var expr = noComma == false ? expression : expressionNoComma; + if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); + if (type == "operator") { + if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me); + if (isTS && value == "<" && cx.stream.match(/^([^>]|<.*?>)*>\s*\(/, false)) + return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me); + if (value == "?") return cont(expression, expect(":"), expr); + return cont(expr); + } + if (type == "quasi") { return pass(quasi, me); } + if (type == ";") return; + if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); + if (type == ".") return cont(property, me); + if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); + if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) } + if (type == "regexp") { + cx.state.lastType = cx.marked = "operator" + cx.stream.backUp(cx.stream.pos - cx.stream.start - 1) + return cont(expr) + } + } + function quasi(type, value) { + if (type != "quasi") return pass(); + if (value.slice(value.length - 2) != "${") return cont(quasi); + return cont(expression, continueQuasi); + } + function continueQuasi(type) { + if (type == "}") { + cx.marked = "string-2"; + cx.state.tokenize = tokenQuasi; + return cont(quasi); + } + } + function arrowBody(type) { + findFatArrow(cx.stream, cx.state); + return pass(type == "{" ? statement : expression); + } + function arrowBodyNoComma(type) { + findFatArrow(cx.stream, cx.state); + return pass(type == "{" ? statement : expressionNoComma); + } + function maybeTarget(noComma) { + return function(type) { + if (type == ".") return cont(noComma ? targetNoComma : target); + else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma) + else return pass(noComma ? expressionNoComma : expression); + }; + } + function target(_, value) { + if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); } + } + function targetNoComma(_, value) { + if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); } + } + function maybelabel(type) { + if (type == ":") return cont(poplex, statement); + return pass(maybeoperatorComma, expect(";"), poplex); + } + function property(type) { + if (type == "variable") {cx.marked = "property"; return cont();} + } + function objprop(type, value) { + if (type == "async") { + cx.marked = "property"; + return cont(objprop); + } else if (type == "variable" || cx.style == "keyword") { + cx.marked = "property"; + if (value == "get" || value == "set") return cont(getterSetter); + var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params + if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) + cx.state.fatArrowAt = cx.stream.pos + m[0].length + return cont(afterprop); + } else if (type == "number" || type == "string") { + cx.marked = jsonldMode ? "property" : (cx.style + " property"); + return cont(afterprop); + } else if (type == "jsonld-keyword") { + return cont(afterprop); + } else if (isTS && isModifier(value)) { + cx.marked = "keyword" + return cont(objprop) + } else if (type == "[") { + return cont(expression, maybetype, expect("]"), afterprop); + } else if (type == "spread") { + return cont(expressionNoComma, afterprop); + } else if (value == "*") { + cx.marked = "keyword"; + return cont(objprop); + } else if (type == ":") { + return pass(afterprop) + } + } + function getterSetter(type) { + if (type != "variable") return pass(afterprop); + cx.marked = "property"; + return cont(functiondef); + } + function afterprop(type) { + if (type == ":") return cont(expressionNoComma); + if (type == "(") return pass(functiondef); + } + function commasep(what, end, sep) { + function proceed(type, value) { + if (sep ? sep.indexOf(type) > -1 : type == ",") { + var lex = cx.state.lexical; + if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; + return cont(function(type, value) { + if (type == end || value == end) return pass() + return pass(what) + }, proceed); + } + if (type == end || value == end) return cont(); + if (sep && sep.indexOf(";") > -1) return pass(what) + return cont(expect(end)); + } + return function(type, value) { + if (type == end || value == end) return cont(); + return pass(what, proceed); + }; + } + function contCommasep(what, end, info) { + for (var i = 3; i < arguments.length; i++) + cx.cc.push(arguments[i]); + return cont(pushlex(end, info), commasep(what, end), poplex); + } + function block(type) { + if (type == "}") return cont(); + return pass(statement, block); + } + function maybetype(type, value) { + if (isTS) { + if (type == ":") return cont(typeexpr); + if (value == "?") return cont(maybetype); + } + } + function maybetypeOrIn(type, value) { + if (isTS && (type == ":" || value == "in")) return cont(typeexpr) + } + function mayberettype(type) { + if (isTS && type == ":") { + if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr) + else return cont(typeexpr) + } + } + function isKW(_, value) { + if (value == "is") { + cx.marked = "keyword" + return cont() + } + } + function typeexpr(type, value) { + if (value == "keyof" || value == "typeof" || value == "infer") { + cx.marked = "keyword" + return cont(value == "typeof" ? expressionNoComma : typeexpr) + } + if (type == "variable" || value == "void") { + cx.marked = "type" + return cont(afterType) + } + if (value == "|" || value == "&") return cont(typeexpr) + if (type == "string" || type == "number" || type == "atom") return cont(afterType); + if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType) + if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType) + if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType) + if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr) + } + function maybeReturnType(type) { + if (type == "=>") return cont(typeexpr) + } + function typeprop(type, value) { + if (type == "variable" || cx.style == "keyword") { + cx.marked = "property" + return cont(typeprop) + } else if (value == "?" || type == "number" || type == "string") { + return cont(typeprop) + } else if (type == ":") { + return cont(typeexpr) + } else if (type == "[") { + return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop) + } else if (type == "(") { + return pass(functiondecl, typeprop) + } + } + function typearg(type, value) { + if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg) + if (type == ":") return cont(typeexpr) + if (type == "spread") return cont(typearg) + return pass(typeexpr) + } + function afterType(type, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) + if (value == "|" || type == "." || value == "&") return cont(typeexpr) + if (type == "[") return cont(typeexpr, expect("]"), afterType) + if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) } + if (value == "?") return cont(typeexpr, expect(":"), typeexpr) + } + function maybeTypeArgs(_, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) + } + function typeparam() { + return pass(typeexpr, maybeTypeDefault) + } + function maybeTypeDefault(_, value) { + if (value == "=") return cont(typeexpr) + } + function vardef(_, value) { + if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)} + return pass(pattern, maybetype, maybeAssign, vardefCont); + } + function pattern(type, value) { + if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) } + if (type == "variable") { register(value); return cont(); } + if (type == "spread") return cont(pattern); + if (type == "[") return contCommasep(eltpattern, "]"); + if (type == "{") return contCommasep(proppattern, "}"); + } + function proppattern(type, value) { + if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { + register(value); + return cont(maybeAssign); + } + if (type == "variable") cx.marked = "property"; + if (type == "spread") return cont(pattern); + if (type == "}") return pass(); + if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern); + return cont(expect(":"), pattern, maybeAssign); + } + function eltpattern() { + return pass(pattern, maybeAssign) + } + function maybeAssign(_type, value) { + if (value == "=") return cont(expressionNoComma); + } + function vardefCont(type) { + if (type == ",") return cont(vardef); + } + function maybeelse(type, value) { + if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); + } + function forspec(type, value) { + if (value == "await") return cont(forspec); + if (type == "(") return cont(pushlex(")"), forspec1, poplex); + } + function forspec1(type) { + if (type == "var") return cont(vardef, forspec2); + if (type == "variable") return cont(forspec2); + return pass(forspec2) + } + function forspec2(type, value) { + if (type == ")") return cont() + if (type == ";") return cont(forspec2) + if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression, forspec2) } + return pass(expression, forspec2) + } + function functiondef(type, value) { + if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} + if (type == "variable") {register(value); return cont(functiondef);} + if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext); + if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef) + } + function functiondecl(type, value) { + if (value == "*") {cx.marked = "keyword"; return cont(functiondecl);} + if (type == "variable") {register(value); return cont(functiondecl);} + if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext); + if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl) + } + function typename(type, value) { + if (type == "keyword" || type == "variable") { + cx.marked = "type" + return cont(typename) + } else if (value == "<") { + return cont(pushlex(">"), commasep(typeparam, ">"), poplex) + } + } + function funarg(type, value) { + if (value == "@") cont(expression, funarg) + if (type == "spread") return cont(funarg); + if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); } + if (isTS && type == "this") return cont(maybetype, maybeAssign) + return pass(pattern, maybetype, maybeAssign); + } + function classExpression(type, value) { + // Class expressions may have an optional name. + if (type == "variable") return className(type, value); + return classNameAfter(type, value); + } + function className(type, value) { + if (type == "variable") {register(value); return cont(classNameAfter);} + } + function classNameAfter(type, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter) + if (value == "extends" || value == "implements" || (isTS && type == ",")) { + if (value == "implements") cx.marked = "keyword"; + return cont(isTS ? typeexpr : expression, classNameAfter); + } + if (type == "{") return cont(pushlex("}"), classBody, poplex); + } + function classBody(type, value) { + if (type == "async" || + (type == "variable" && + (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) && + cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) { + cx.marked = "keyword"; + return cont(classBody); + } + if (type == "variable" || cx.style == "keyword") { + cx.marked = "property"; + return cont(isTS ? classfield : functiondef, classBody); + } + if (type == "number" || type == "string") return cont(isTS ? classfield : functiondef, classBody); + if (type == "[") + return cont(expression, maybetype, expect("]"), isTS ? classfield : functiondef, classBody) + if (value == "*") { + cx.marked = "keyword"; + return cont(classBody); + } + if (isTS && type == "(") return pass(functiondecl, classBody) + if (type == ";" || type == ",") return cont(classBody); + if (type == "}") return cont(); + if (value == "@") return cont(expression, classBody) + } + function classfield(type, value) { + if (value == "?") return cont(classfield) + if (type == ":") return cont(typeexpr, maybeAssign) + if (value == "=") return cont(expressionNoComma) + var context = cx.state.lexical.prev, isInterface = context && context.info == "interface" + return pass(isInterface ? functiondecl : functiondef) + } + function afterExport(type, value) { + if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } + if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } + if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); + return pass(statement); + } + function exportField(type, value) { + if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); } + if (type == "variable") return pass(expressionNoComma, exportField); + } + function afterImport(type) { + if (type == "string") return cont(); + if (type == "(") return pass(expression); + return pass(importSpec, maybeMoreImports, maybeFrom); + } + function importSpec(type, value) { + if (type == "{") return contCommasep(importSpec, "}"); + if (type == "variable") register(value); + if (value == "*") cx.marked = "keyword"; + return cont(maybeAs); + } + function maybeMoreImports(type) { + if (type == ",") return cont(importSpec, maybeMoreImports) + } + function maybeAs(_type, value) { + if (value == "as") { cx.marked = "keyword"; return cont(importSpec); } + } + function maybeFrom(_type, value) { + if (value == "from") { cx.marked = "keyword"; return cont(expression); } + } + function arrayLiteral(type) { + if (type == "]") return cont(); + return pass(commasep(expressionNoComma, "]")); + } + function enumdef() { + return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex) + } + function enummember() { + return pass(pattern, maybeAssign); + } + + function isContinuedStatement(state, textAfter) { + return state.lastType == "operator" || state.lastType == "," || + isOperatorChar.test(textAfter.charAt(0)) || + /[,.]/.test(textAfter.charAt(0)); + } + + function expressionAllowed(stream, state, backUp) { + return state.tokenize == tokenBase && + /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || + (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0)))) + } + + // Interface + + return { + startState: function(basecolumn) { + var state = { + tokenize: tokenBase, + lastType: "sof", + cc: [], + lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), + localVars: parserConfig.localVars, + context: parserConfig.localVars && new Context(null, null, false), + indented: basecolumn || 0 + }; + if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") + state.globalVars = parserConfig.globalVars; + return state; + }, + + token: function(stream, state) { + if (stream.sol()) { + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = false; + state.indented = stream.indentation(); + findFatArrow(stream, state); + } + if (state.tokenize != tokenComment && stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (type == "comment") return style; + state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; + return parseJS(state, style, type, content, stream); + }, + + indent: function(state, textAfter) { + if (state.tokenize == tokenComment) return CodeMirror.Pass; + if (state.tokenize != tokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top + // Kludge to prevent 'maybelse' from blocking lexical scope pops + if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { + var c = state.cc[i]; + if (c == poplex) lexical = lexical.prev; + else if (c != maybeelse) break; + } + while ((lexical.type == "stat" || lexical.type == "form") && + (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) && + (top == maybeoperatorComma || top == maybeoperatorNoComma) && + !/^[,\.=+\-*:?[\(]/.test(textAfter)))) + lexical = lexical.prev; + if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") + lexical = lexical.prev; + var type = lexical.type, closing = firstChar == type; + + if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0); + else if (type == "form" && firstChar == "{") return lexical.indented; + else if (type == "form") return lexical.indented + indentUnit; + else if (type == "stat") + return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); + else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) + return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); + else if (lexical.align) return lexical.column + (closing ? 0 : 1); + else return lexical.indented + (closing ? 0 : indentUnit); + }, + + electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, + blockCommentStart: jsonMode ? null : "/*", + blockCommentEnd: jsonMode ? null : "*/", + blockCommentContinue: jsonMode ? null : " * ", + lineComment: jsonMode ? null : "//", + fold: "brace", + closeBrackets: "()[]{}''\"\"``", + + helperType: jsonMode ? "json" : "javascript", + jsonldMode: jsonldMode, + jsonMode: jsonMode, + + expressionAllowed: expressionAllowed, + + skipExpression: function(state) { + var top = state.cc[state.cc.length - 1] + if (top == expression || top == expressionNoComma) state.cc.pop() + } + }; +}); + +CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); + +CodeMirror.defineMIME("text/javascript", "javascript"); +CodeMirror.defineMIME("text/ecmascript", "javascript"); +CodeMirror.defineMIME("application/javascript", "javascript"); +CodeMirror.defineMIME("application/x-javascript", "javascript"); +CodeMirror.defineMIME("application/ecmascript", "javascript"); +CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); +CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); +CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); +CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); +CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); + +}); diff --git a/js/codemirror/5.50.0/material.css b/js/codemirror/5.50.0/material.css new file mode 100644 index 0000000..9ac17a3 --- /dev/null +++ b/js/codemirror/5.50.0/material.css @@ -0,0 +1,135 @@ +/* + Name: material + Author: Mattia Astorino (http://github.com/equinusocio) + Website: https://material-theme.site/ +*/ + +.cm-s-material.CodeMirror { + background-color: #263238; + color: #EEFFFF; +} + +.cm-s-material .CodeMirror-gutters { + background: #263238; + color: #546E7A; + border: none; +} + +.cm-s-material .CodeMirror-guttermarker, +.cm-s-material .CodeMirror-guttermarker-subtle, +.cm-s-material .CodeMirror-linenumber { + color: #546E7A; +} + +.cm-s-material .CodeMirror-cursor { + border-left: 1px solid #FFCC00; +} + +.cm-s-material div.CodeMirror-selected { + background: rgba(128, 203, 196, 0.2); +} + +.cm-s-material.CodeMirror-focused div.CodeMirror-selected { + background: rgba(128, 203, 196, 0.2); +} + +.cm-s-material .CodeMirror-line::selection, +.cm-s-material .CodeMirror-line>span::selection, +.cm-s-material .CodeMirror-line>span>span::selection { + background: rgba(128, 203, 196, 0.2); +} + +.cm-s-material .CodeMirror-line::-moz-selection, +.cm-s-material .CodeMirror-line>span::-moz-selection, +.cm-s-material .CodeMirror-line>span>span::-moz-selection { + background: rgba(128, 203, 196, 0.2); +} + +.cm-s-material .CodeMirror-activeline-background { + background: rgba(0, 0, 0, 0.5); +} + +.cm-s-material .cm-keyword { + color: #C792EA; +} + +.cm-s-material .cm-operator { + color: #89DDFF; +} + +.cm-s-material .cm-variable-2 { + color: #EEFFFF; +} + +.cm-s-material .cm-variable-3, +.cm-s-material .cm-type { + color: #f07178; +} + +.cm-s-material .cm-builtin { + color: #FFCB6B; +} + +.cm-s-material .cm-atom { + color: #F78C6C; +} + +.cm-s-material .cm-number { + color: #FF5370; +} + +.cm-s-material .cm-def { + color: #82AAFF; +} + +.cm-s-material .cm-string { + color: #C3E88D; +} + +.cm-s-material .cm-string-2 { + color: #f07178; +} + +.cm-s-material .cm-comment { + color: #546E7A; +} + +.cm-s-material .cm-variable { + color: #f07178; +} + +.cm-s-material .cm-tag { + color: #FF5370; +} + +.cm-s-material .cm-meta { + color: #FFCB6B; +} + +.cm-s-material .cm-attribute { + color: #C792EA; +} + +.cm-s-material .cm-property { + color: #C792EA; +} + +.cm-s-material .cm-qualifier { + color: #DECB6B; +} + +.cm-s-material .cm-variable-3, +.cm-s-material .cm-type { + color: #DECB6B; +} + + +.cm-s-material .cm-error { + color: rgba(255, 255, 255, 1.0); + background-color: #FF5370; +} + +.cm-s-material .CodeMirror-matchingbracket { + text-decoration: underline; + color: white !important; +} \ No newline at end of file diff --git a/js/codemirror/5.50.0/monokai.css b/js/codemirror/5.50.0/monokai.css new file mode 100644 index 0000000..cd4cd55 --- /dev/null +++ b/js/codemirror/5.50.0/monokai.css @@ -0,0 +1,41 @@ +/* Based on Sublime Text's Monokai theme */ + +.cm-s-monokai.CodeMirror { background: #272822; color: #f8f8f2; } +.cm-s-monokai div.CodeMirror-selected { background: #49483E; } +.cm-s-monokai .CodeMirror-line::selection, .cm-s-monokai .CodeMirror-line > span::selection, .cm-s-monokai .CodeMirror-line > span > span::selection { background: rgba(73, 72, 62, .99); } +.cm-s-monokai .CodeMirror-line::-moz-selection, .cm-s-monokai .CodeMirror-line > span::-moz-selection, .cm-s-monokai .CodeMirror-line > span > span::-moz-selection { background: rgba(73, 72, 62, .99); } +.cm-s-monokai .CodeMirror-gutters { background: #272822; border-right: 0px; } +.cm-s-monokai .CodeMirror-guttermarker { color: white; } +.cm-s-monokai .CodeMirror-guttermarker-subtle { color: #d0d0d0; } +.cm-s-monokai .CodeMirror-linenumber { color: #d0d0d0; } +.cm-s-monokai .CodeMirror-cursor { border-left: 1px solid #f8f8f0; } + +.cm-s-monokai span.cm-comment { color: #75715e; } +.cm-s-monokai span.cm-atom { color: #ae81ff; } +.cm-s-monokai span.cm-number { color: #ae81ff; } + +.cm-s-monokai span.cm-comment.cm-attribute { color: #97b757; } +.cm-s-monokai span.cm-comment.cm-def { color: #bc9262; } +.cm-s-monokai span.cm-comment.cm-tag { color: #bc6283; } +.cm-s-monokai span.cm-comment.cm-type { color: #5998a6; } + +.cm-s-monokai span.cm-property, .cm-s-monokai span.cm-attribute { color: #a6e22e; } +.cm-s-monokai span.cm-keyword { color: #f92672; } +.cm-s-monokai span.cm-builtin { color: #66d9ef; } +.cm-s-monokai span.cm-string { color: #e6db74; } + +.cm-s-monokai span.cm-variable { color: #f8f8f2; } +.cm-s-monokai span.cm-variable-2 { color: #9effff; } +.cm-s-monokai span.cm-variable-3, .cm-s-monokai span.cm-type { color: #66d9ef; } +.cm-s-monokai span.cm-def { color: #fd971f; } +.cm-s-monokai span.cm-bracket { color: #f8f8f2; } +.cm-s-monokai span.cm-tag { color: #f92672; } +.cm-s-monokai span.cm-header { color: #ae81ff; } +.cm-s-monokai span.cm-link { color: #ae81ff; } +.cm-s-monokai span.cm-error { background: #f92672; color: #f8f8f0; } + +.cm-s-monokai .CodeMirror-activeline-background { background: #373831; } +.cm-s-monokai .CodeMirror-matchingbracket { + text-decoration: underline; + color: white !important; +} diff --git a/js/codemirror/5.50.0/python.js b/js/codemirror/5.50.0/python.js new file mode 100644 index 0000000..9745103 --- /dev/null +++ b/js/codemirror/5.50.0/python.js @@ -0,0 +1,399 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + function wordRegexp(words) { + return new RegExp("^((" + words.join(")|(") + "))\\b"); + } + + var wordOperators = wordRegexp(["and", "or", "not", "is"]); + var commonKeywords = ["as", "assert", "break", "class", "continue", + "def", "del", "elif", "else", "except", "finally", + "for", "from", "global", "if", "import", + "lambda", "pass", "raise", "return", + "try", "while", "with", "yield", "in"]; + var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr", + "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod", + "enumerate", "eval", "filter", "float", "format", "frozenset", + "getattr", "globals", "hasattr", "hash", "help", "hex", "id", + "input", "int", "isinstance", "issubclass", "iter", "len", + "list", "locals", "map", "max", "memoryview", "min", "next", + "object", "oct", "open", "ord", "pow", "property", "range", + "repr", "reversed", "round", "set", "setattr", "slice", + "sorted", "staticmethod", "str", "sum", "super", "tuple", + "type", "vars", "zip", "__import__", "NotImplemented", + "Ellipsis", "__debug__"]; + CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins)); + + function top(state) { + return state.scopes[state.scopes.length - 1]; + } + + CodeMirror.defineMode("python", function(conf, parserConf) { + var ERRORCLASS = "error"; + + var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.\\]/; + // (Backwards-compatiblity with old, cumbersome config system) + var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters, + parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@]|\.\.\.)/] + for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1) + + var hangingIndent = parserConf.hangingIndent || conf.indentUnit; + + var myKeywords = commonKeywords, myBuiltins = commonBuiltins; + if (parserConf.extra_keywords != undefined) + myKeywords = myKeywords.concat(parserConf.extra_keywords); + + if (parserConf.extra_builtins != undefined) + myBuiltins = myBuiltins.concat(parserConf.extra_builtins); + + var py3 = !(parserConf.version && Number(parserConf.version) < 3) + if (py3) { + // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator + var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/; + myKeywords = myKeywords.concat(["nonlocal", "False", "True", "None", "async", "await"]); + myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]); + var stringPrefixes = new RegExp("^(([rbuf]|(br)|(fr))?('{3}|\"{3}|['\"]))", "i"); + } else { + var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/; + myKeywords = myKeywords.concat(["exec", "print"]); + myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile", + "file", "intern", "long", "raw_input", "reduce", "reload", + "unichr", "unicode", "xrange", "False", "True", "None"]); + var stringPrefixes = new RegExp("^(([rubf]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i"); + } + var keywords = wordRegexp(myKeywords); + var builtins = wordRegexp(myBuiltins); + + // tokenizers + function tokenBase(stream, state) { + var sol = stream.sol() && state.lastToken != "\\" + if (sol) state.indent = stream.indentation() + // Handle scope changes + if (sol && top(state).type == "py") { + var scopeOffset = top(state).offset; + if (stream.eatSpace()) { + var lineOffset = stream.indentation(); + if (lineOffset > scopeOffset) + pushPyScope(state); + else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#") + state.errorToken = true; + return null; + } else { + var style = tokenBaseInner(stream, state); + if (scopeOffset > 0 && dedent(stream, state)) + style += " " + ERRORCLASS; + return style; + } + } + return tokenBaseInner(stream, state); + } + + function tokenBaseInner(stream, state) { + if (stream.eatSpace()) return null; + + // Handle Comments + if (stream.match(/^#.*/)) return "comment"; + + // Handle Number Literals + if (stream.match(/^[0-9\.]/, false)) { + var floatLiteral = false; + // Floats + if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; } + if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; } + if (stream.match(/^\.\d+/)) { floatLiteral = true; } + if (floatLiteral) { + // Float literals may be "imaginary" + stream.eat(/J/i); + return "number"; + } + // Integers + var intLiteral = false; + // Hex + if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true; + // Binary + if (stream.match(/^0b[01_]+/i)) intLiteral = true; + // Octal + if (stream.match(/^0o[0-7_]+/i)) intLiteral = true; + // Decimal + if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) { + // Decimal literals may be "imaginary" + stream.eat(/J/i); + // TODO - Can you have imaginary longs? + intLiteral = true; + } + // Zero by itself with no other piece of number. + if (stream.match(/^0(?![\dx])/i)) intLiteral = true; + if (intLiteral) { + // Integer literals may be "long" + stream.eat(/L/i); + return "number"; + } + } + + // Handle Strings + if (stream.match(stringPrefixes)) { + var isFmtString = stream.current().toLowerCase().indexOf('f') !== -1; + if (!isFmtString) { + state.tokenize = tokenStringFactory(stream.current(), state.tokenize); + return state.tokenize(stream, state); + } else { + state.tokenize = formatStringFactory(stream.current(), state.tokenize); + return state.tokenize(stream, state); + } + } + + for (var i = 0; i < operators.length; i++) + if (stream.match(operators[i])) return "operator" + + if (stream.match(delimiters)) return "punctuation"; + + if (state.lastToken == "." && stream.match(identifiers)) + return "property"; + + if (stream.match(keywords) || stream.match(wordOperators)) + return "keyword"; + + if (stream.match(builtins)) + return "builtin"; + + if (stream.match(/^(self|cls)\b/)) + return "variable-2"; + + if (stream.match(identifiers)) { + if (state.lastToken == "def" || state.lastToken == "class") + return "def"; + return "variable"; + } + + // Handle non-detected items + stream.next(); + return ERRORCLASS; + } + + function formatStringFactory(delimiter, tokenOuter) { + while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0) + delimiter = delimiter.substr(1); + + var singleline = delimiter.length == 1; + var OUTCLASS = "string"; + + function tokenNestedExpr(depth) { + return function(stream, state) { + var inner = tokenBaseInner(stream, state) + if (inner == "punctuation") { + if (stream.current() == "{") { + state.tokenize = tokenNestedExpr(depth + 1) + } else if (stream.current() == "}") { + if (depth > 1) state.tokenize = tokenNestedExpr(depth - 1) + else state.tokenize = tokenString + } + } + return inner + } + } + + function tokenString(stream, state) { + while (!stream.eol()) { + stream.eatWhile(/[^'"\{\}\\]/); + if (stream.eat("\\")) { + stream.next(); + if (singleline && stream.eol()) + return OUTCLASS; + } else if (stream.match(delimiter)) { + state.tokenize = tokenOuter; + return OUTCLASS; + } else if (stream.match('{{')) { + // ignore {{ in f-str + return OUTCLASS; + } else if (stream.match('{', false)) { + // switch to nested mode + state.tokenize = tokenNestedExpr(0) + if (stream.current()) return OUTCLASS; + else return state.tokenize(stream, state) + } else if (stream.match('}}')) { + return OUTCLASS; + } else if (stream.match('}')) { + // single } in f-string is an error + return ERRORCLASS; + } else { + stream.eat(/['"]/); + } + } + if (singleline) { + if (parserConf.singleLineStringErrors) + return ERRORCLASS; + else + state.tokenize = tokenOuter; + } + return OUTCLASS; + } + tokenString.isString = true; + return tokenString; + } + + function tokenStringFactory(delimiter, tokenOuter) { + while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0) + delimiter = delimiter.substr(1); + + var singleline = delimiter.length == 1; + var OUTCLASS = "string"; + + function tokenString(stream, state) { + while (!stream.eol()) { + stream.eatWhile(/[^'"\\]/); + if (stream.eat("\\")) { + stream.next(); + if (singleline && stream.eol()) + return OUTCLASS; + } else if (stream.match(delimiter)) { + state.tokenize = tokenOuter; + return OUTCLASS; + } else { + stream.eat(/['"]/); + } + } + if (singleline) { + if (parserConf.singleLineStringErrors) + return ERRORCLASS; + else + state.tokenize = tokenOuter; + } + return OUTCLASS; + } + tokenString.isString = true; + return tokenString; + } + + function pushPyScope(state) { + while (top(state).type != "py") state.scopes.pop() + state.scopes.push({offset: top(state).offset + conf.indentUnit, + type: "py", + align: null}) + } + + function pushBracketScope(stream, state, type) { + var align = stream.match(/^([\s\[\{\(]|#.*)*$/, false) ? null : stream.column() + 1 + state.scopes.push({offset: state.indent + hangingIndent, + type: type, + align: align}) + } + + function dedent(stream, state) { + var indented = stream.indentation(); + while (state.scopes.length > 1 && top(state).offset > indented) { + if (top(state).type != "py") return true; + state.scopes.pop(); + } + return top(state).offset != indented; + } + + function tokenLexer(stream, state) { + if (stream.sol()) state.beginningOfLine = true; + + var style = state.tokenize(stream, state); + var current = stream.current(); + + // Handle decorators + if (state.beginningOfLine && current == "@") + return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS; + + if (/\S/.test(current)) state.beginningOfLine = false; + + if ((style == "variable" || style == "builtin") + && state.lastToken == "meta") + style = "meta"; + + // Handle scope changes. + if (current == "pass" || current == "return") + state.dedent += 1; + + if (current == "lambda") state.lambda = true; + if (current == ":" && !state.lambda && top(state).type == "py") + pushPyScope(state); + + if (current.length == 1 && !/string|comment/.test(style)) { + var delimiter_index = "[({".indexOf(current); + if (delimiter_index != -1) + pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1)); + + delimiter_index = "])}".indexOf(current); + if (delimiter_index != -1) { + if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent + else return ERRORCLASS; + } + } + if (state.dedent > 0 && stream.eol() && top(state).type == "py") { + if (state.scopes.length > 1) state.scopes.pop(); + state.dedent -= 1; + } + + return style; + } + + var external = { + startState: function(basecolumn) { + return { + tokenize: tokenBase, + scopes: [{offset: basecolumn || 0, type: "py", align: null}], + indent: basecolumn || 0, + lastToken: null, + lambda: false, + dedent: 0 + }; + }, + + token: function(stream, state) { + var addErr = state.errorToken; + if (addErr) state.errorToken = false; + var style = tokenLexer(stream, state); + + if (style && style != "comment") + state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style; + if (style == "punctuation") style = null; + + if (stream.eol() && state.lambda) + state.lambda = false; + return addErr ? style + " " + ERRORCLASS : style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase) + return state.tokenize.isString ? CodeMirror.Pass : 0; + + var scope = top(state), closing = scope.type == textAfter.charAt(0) + if (scope.align != null) + return scope.align - (closing ? 1 : 0) + else + return scope.offset - (closing ? hangingIndent : 0) + }, + + electricInput: /^\s*[\}\]\)]$/, + closeBrackets: {triples: "'\""}, + lineComment: "#", + fold: "indent" + }; + return external; + }); + + CodeMirror.defineMIME("text/x-python", "python"); + + var words = function(str) { return str.split(" "); }; + + CodeMirror.defineMIME("text/x-cython", { + name: "python", + extra_keywords: words("by cdef cimport cpdef ctypedef enum except "+ + "extern gil include nogil property public "+ + "readonly struct union DEF IF ELIF ELSE") + }); + +}); diff --git a/js/codemirror/5.50.0/xml.js b/js/codemirror/5.50.0/xml.js new file mode 100644 index 0000000..73c6e0e --- /dev/null +++ b/js/codemirror/5.50.0/xml.js @@ -0,0 +1,413 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +var htmlConfig = { + autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true, + 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true, + 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, + 'track': true, 'wbr': true, 'menuitem': true}, + implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true, + 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true, + 'th': true, 'tr': true}, + contextGrabbers: { + 'dd': {'dd': true, 'dt': true}, + 'dt': {'dd': true, 'dt': true}, + 'li': {'li': true}, + 'option': {'option': true, 'optgroup': true}, + 'optgroup': {'optgroup': true}, + 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true, + 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true, + 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true, + 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true, + 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true}, + 'rp': {'rp': true, 'rt': true}, + 'rt': {'rp': true, 'rt': true}, + 'tbody': {'tbody': true, 'tfoot': true}, + 'td': {'td': true, 'th': true}, + 'tfoot': {'tbody': true}, + 'th': {'td': true, 'th': true}, + 'thead': {'tbody': true, 'tfoot': true}, + 'tr': {'tr': true} + }, + doNotIndent: {"pre": true}, + allowUnquoted: true, + allowMissing: true, + caseFold: true +} + +var xmlConfig = { + autoSelfClosers: {}, + implicitlyClosed: {}, + contextGrabbers: {}, + doNotIndent: {}, + allowUnquoted: false, + allowMissing: false, + allowMissingTagName: false, + caseFold: false +} + +CodeMirror.defineMode("xml", function(editorConf, config_) { + var indentUnit = editorConf.indentUnit + var config = {} + var defaults = config_.htmlMode ? htmlConfig : xmlConfig + for (var prop in defaults) config[prop] = defaults[prop] + for (var prop in config_) config[prop] = config_[prop] + + // Return variables for tokenizers + var type, setStyle; + + function inText(stream, state) { + function chain(parser) { + state.tokenize = parser; + return parser(stream, state); + } + + var ch = stream.next(); + if (ch == "<") { + if (stream.eat("!")) { + if (stream.eat("[")) { + if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>")); + else return null; + } else if (stream.match("--")) { + return chain(inBlock("comment", "-->")); + } else if (stream.match("DOCTYPE", true, true)) { + stream.eatWhile(/[\w\._\-]/); + return chain(doctype(1)); + } else { + return null; + } + } else if (stream.eat("?")) { + stream.eatWhile(/[\w\._\-]/); + state.tokenize = inBlock("meta", "?>"); + return "meta"; + } else { + type = stream.eat("/") ? "closeTag" : "openTag"; + state.tokenize = inTag; + return "tag bracket"; + } + } else if (ch == "&") { + var ok; + if (stream.eat("#")) { + if (stream.eat("x")) { + ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); + } else { + ok = stream.eatWhile(/[\d]/) && stream.eat(";"); + } + } else { + ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); + } + return ok ? "atom" : "error"; + } else { + stream.eatWhile(/[^&<]/); + return null; + } + } + inText.isInText = true; + + function inTag(stream, state) { + var ch = stream.next(); + if (ch == ">" || (ch == "/" && stream.eat(">"))) { + state.tokenize = inText; + type = ch == ">" ? "endTag" : "selfcloseTag"; + return "tag bracket"; + } else if (ch == "=") { + type = "equals"; + return null; + } else if (ch == "<") { + state.tokenize = inText; + state.state = baseState; + state.tagName = state.tagStart = null; + var next = state.tokenize(stream, state); + return next ? next + " tag error" : "tag error"; + } else if (/[\'\"]/.test(ch)) { + state.tokenize = inAttribute(ch); + state.stringStartCol = stream.column(); + return state.tokenize(stream, state); + } else { + stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/); + return "word"; + } + } + + function inAttribute(quote) { + var closure = function(stream, state) { + while (!stream.eol()) { + if (stream.next() == quote) { + state.tokenize = inTag; + break; + } + } + return "string"; + }; + closure.isInAttribute = true; + return closure; + } + + function inBlock(style, terminator) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.match(terminator)) { + state.tokenize = inText; + break; + } + stream.next(); + } + return style; + } + } + + function doctype(depth) { + return function(stream, state) { + var ch; + while ((ch = stream.next()) != null) { + if (ch == "<") { + state.tokenize = doctype(depth + 1); + return state.tokenize(stream, state); + } else if (ch == ">") { + if (depth == 1) { + state.tokenize = inText; + break; + } else { + state.tokenize = doctype(depth - 1); + return state.tokenize(stream, state); + } + } + } + return "meta"; + }; + } + + function Context(state, tagName, startOfLine) { + this.prev = state.context; + this.tagName = tagName; + this.indent = state.indented; + this.startOfLine = startOfLine; + if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent)) + this.noIndent = true; + } + function popContext(state) { + if (state.context) state.context = state.context.prev; + } + function maybePopContext(state, nextTagName) { + var parentTagName; + while (true) { + if (!state.context) { + return; + } + parentTagName = state.context.tagName; + if (!config.contextGrabbers.hasOwnProperty(parentTagName) || + !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { + return; + } + popContext(state); + } + } + + function baseState(type, stream, state) { + if (type == "openTag") { + state.tagStart = stream.column(); + return tagNameState; + } else if (type == "closeTag") { + return closeTagNameState; + } else { + return baseState; + } + } + function tagNameState(type, stream, state) { + if (type == "word") { + state.tagName = stream.current(); + setStyle = "tag"; + return attrState; + } else if (config.allowMissingTagName && type == "endTag") { + setStyle = "tag bracket"; + return attrState(type, stream, state); + } else { + setStyle = "error"; + return tagNameState; + } + } + function closeTagNameState(type, stream, state) { + if (type == "word") { + var tagName = stream.current(); + if (state.context && state.context.tagName != tagName && + config.implicitlyClosed.hasOwnProperty(state.context.tagName)) + popContext(state); + if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) { + setStyle = "tag"; + return closeState; + } else { + setStyle = "tag error"; + return closeStateErr; + } + } else if (config.allowMissingTagName && type == "endTag") { + setStyle = "tag bracket"; + return closeState(type, stream, state); + } else { + setStyle = "error"; + return closeStateErr; + } + } + + function closeState(type, _stream, state) { + if (type != "endTag") { + setStyle = "error"; + return closeState; + } + popContext(state); + return baseState; + } + function closeStateErr(type, stream, state) { + setStyle = "error"; + return closeState(type, stream, state); + } + + function attrState(type, _stream, state) { + if (type == "word") { + setStyle = "attribute"; + return attrEqState; + } else if (type == "endTag" || type == "selfcloseTag") { + var tagName = state.tagName, tagStart = state.tagStart; + state.tagName = state.tagStart = null; + if (type == "selfcloseTag" || + config.autoSelfClosers.hasOwnProperty(tagName)) { + maybePopContext(state, tagName); + } else { + maybePopContext(state, tagName); + state.context = new Context(state, tagName, tagStart == state.indented); + } + return baseState; + } + setStyle = "error"; + return attrState; + } + function attrEqState(type, stream, state) { + if (type == "equals") return attrValueState; + if (!config.allowMissing) setStyle = "error"; + return attrState(type, stream, state); + } + function attrValueState(type, stream, state) { + if (type == "string") return attrContinuedState; + if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;} + setStyle = "error"; + return attrState(type, stream, state); + } + function attrContinuedState(type, stream, state) { + if (type == "string") return attrContinuedState; + return attrState(type, stream, state); + } + + return { + startState: function(baseIndent) { + var state = {tokenize: inText, + state: baseState, + indented: baseIndent || 0, + tagName: null, tagStart: null, + context: null} + if (baseIndent != null) state.baseIndent = baseIndent + return state + }, + + token: function(stream, state) { + if (!state.tagName && stream.sol()) + state.indented = stream.indentation(); + + if (stream.eatSpace()) return null; + type = null; + var style = state.tokenize(stream, state); + if ((style || type) && style != "comment") { + setStyle = null; + state.state = state.state(type || style, stream, state); + if (setStyle) + style = setStyle == "error" ? style + " error" : setStyle; + } + return style; + }, + + indent: function(state, textAfter, fullLine) { + var context = state.context; + // Indent multi-line strings (e.g. css). + if (state.tokenize.isInAttribute) { + if (state.tagStart == state.indented) + return state.stringStartCol + 1; + else + return state.indented + indentUnit; + } + if (context && context.noIndent) return CodeMirror.Pass; + if (state.tokenize != inTag && state.tokenize != inText) + return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; + // Indent the starts of attribute names. + if (state.tagName) { + if (config.multilineTagIndentPastTag !== false) + return state.tagStart + state.tagName.length + 2; + else + return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1); + } + if (config.alignCDATA && /$/, + blockCommentStart: "", + + configuration: config.htmlMode ? "html" : "xml", + helperType: config.htmlMode ? "html" : "xml", + + skipAttribute: function(state) { + if (state.state == attrValueState) + state.state = attrState + }, + + xmlCurrentTag: function(state) { + return state.tagName ? {name: state.tagName, close: state.type == "closeTag"} : null + }, + + xmlCurrentContext: function(state) { + var context = [] + for (var cx = state.context; cx; cx = cx.prev) + if (cx.tagName) context.push(cx.tagName) + return context.reverse() + } + }; +}); + +CodeMirror.defineMIME("text/xml", "xml"); +CodeMirror.defineMIME("application/xml", "xml"); +if (!CodeMirror.mimeModes.hasOwnProperty("text/html")) + CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true}); + +}); diff --git a/js/codemirror/5.65.1/.DS_Store b/js/codemirror/5.65.1/.DS_Store new file mode 100644 index 0000000..e7bb3ca Binary files /dev/null and b/js/codemirror/5.65.1/.DS_Store differ diff --git a/js/codemirror/5.65.1/codemirror.css b/js/codemirror/5.65.1/codemirror.css new file mode 100644 index 0000000..f4d5718 --- /dev/null +++ b/js/codemirror/5.65.1/codemirror.css @@ -0,0 +1,344 @@ +/* BASICS */ + +.CodeMirror { + /* Set height, width, borders, and global font properties here */ + font-family: monospace; + height: 300px; + color: black; + direction: ltr; +} + +/* PADDING */ + +.CodeMirror-lines { + padding: 4px 0; /* Vertical padding around content */ +} +.CodeMirror pre.CodeMirror-line, +.CodeMirror pre.CodeMirror-line-like { + padding: 0 4px; /* Horizontal padding of content */ +} + +.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + background-color: white; /* The little square between H and V scrollbars */ +} + +/* GUTTER */ + +.CodeMirror-gutters { + border-right: 1px solid #ddd; + background-color: #f7f7f7; + white-space: nowrap; +} +.CodeMirror-linenumbers {} +.CodeMirror-linenumber { + padding: 0 3px 0 5px; + min-width: 20px; + text-align: right; + color: #999; + white-space: nowrap; +} + +.CodeMirror-guttermarker { color: black; } +.CodeMirror-guttermarker-subtle { color: #999; } + +/* CURSOR */ + +.CodeMirror-cursor { + border-left: 1px solid black; + border-right: none; + width: 0; +} +/* Shown when moving in bi-directional text */ +.CodeMirror div.CodeMirror-secondarycursor { + border-left: 1px solid silver; +} +.cm-fat-cursor .CodeMirror-cursor { + width: auto; + border: 0 !important; + background: #7e7; +} +.cm-fat-cursor div.CodeMirror-cursors { + z-index: 1; +} +.cm-fat-cursor .CodeMirror-line::selection, +.cm-fat-cursor .CodeMirror-line > span::selection, +.cm-fat-cursor .CodeMirror-line > span > span::selection { background: transparent; } +.cm-fat-cursor .CodeMirror-line::-moz-selection, +.cm-fat-cursor .CodeMirror-line > span::-moz-selection, +.cm-fat-cursor .CodeMirror-line > span > span::-moz-selection { background: transparent; } +.cm-fat-cursor { caret-color: transparent; } +@-moz-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@-webkit-keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} +@keyframes blink { + 0% {} + 50% { background-color: transparent; } + 100% {} +} + +/* Can style cursor different in overwrite (non-insert) mode */ +.CodeMirror-overwrite .CodeMirror-cursor {} + +.cm-tab { display: inline-block; text-decoration: inherit; } + +.CodeMirror-rulers { + position: absolute; + left: 0; right: 0; top: -50px; bottom: 0; + overflow: hidden; +} +.CodeMirror-ruler { + border-left: 1px solid #ccc; + top: 0; bottom: 0; + position: absolute; +} + +/* DEFAULT THEME */ + +.cm-s-default .cm-header {color: blue;} +.cm-s-default .cm-quote {color: #090;} +.cm-negative {color: #d44;} +.cm-positive {color: #292;} +.cm-header, .cm-strong {font-weight: bold;} +.cm-em {font-style: italic;} +.cm-link {text-decoration: underline;} +.cm-strikethrough {text-decoration: line-through;} + +.cm-s-default .cm-keyword {color: #708;} +.cm-s-default .cm-atom {color: #219;} +.cm-s-default .cm-number {color: #164;} +.cm-s-default .cm-def {color: #00f;} +.cm-s-default .cm-variable, +.cm-s-default .cm-punctuation, +.cm-s-default .cm-property, +.cm-s-default .cm-operator {} +.cm-s-default .cm-variable-2 {color: #05a;} +.cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;} +.cm-s-default .cm-comment {color: #a50;} +.cm-s-default .cm-string {color: #a11;} +.cm-s-default .cm-string-2 {color: #f50;} +.cm-s-default .cm-meta {color: #555;} +.cm-s-default .cm-qualifier {color: #555;} +.cm-s-default .cm-builtin {color: #30a;} +.cm-s-default .cm-bracket {color: #997;} +.cm-s-default .cm-tag {color: #170;} +.cm-s-default .cm-attribute {color: #00c;} +.cm-s-default .cm-hr {color: #999;} +.cm-s-default .cm-link {color: #00c;} + +.cm-s-default .cm-error {color: #f00;} +.cm-invalidchar {color: #f00;} + +.CodeMirror-composing { border-bottom: 2px solid; } + +/* Default styles for common addons */ + +div.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;} +div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;} +.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } +.CodeMirror-activeline-background {background: #e8f2ff;} + +/* STOP */ + +/* The rest of this file contains styles related to the mechanics of + the editor. You probably shouldn't touch them. */ + +.CodeMirror { + position: relative; + overflow: hidden; + background: white; +} + +.CodeMirror-scroll { + overflow: scroll !important; /* Things will break if this is overridden */ + /* 50px is the magic margin used to hide the element's real scrollbars */ + /* See overflow: hidden in .CodeMirror */ + margin-bottom: -50px; margin-right: -50px; + padding-bottom: 50px; + height: 100%; + outline: none; /* Prevent dragging from highlighting the element */ + position: relative; + z-index: 0; +} +.CodeMirror-sizer { + position: relative; + border-right: 50px solid transparent; +} + +/* The fake, visible scrollbars. Used to force redraw during scrolling + before actual scrolling happens, thus preventing shaking and + flickering artifacts. */ +.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + position: absolute; + z-index: 6; + display: none; + outline: none; +} +.CodeMirror-vscrollbar { + right: 0; top: 0; + overflow-x: hidden; + overflow-y: scroll; +} +.CodeMirror-hscrollbar { + bottom: 0; left: 0; + overflow-y: hidden; + overflow-x: scroll; +} +.CodeMirror-scrollbar-filler { + right: 0; bottom: 0; +} +.CodeMirror-gutter-filler { + left: 0; bottom: 0; +} + +.CodeMirror-gutters { + position: absolute; left: 0; top: 0; + min-height: 100%; + z-index: 3; +} +.CodeMirror-gutter { + white-space: normal; + height: 100%; + display: inline-block; + vertical-align: top; + margin-bottom: -50px; +} +.CodeMirror-gutter-wrapper { + position: absolute; + z-index: 4; + background: none !important; + border: none !important; +} +.CodeMirror-gutter-background { + position: absolute; + top: 0; bottom: 0; + z-index: 4; +} +.CodeMirror-gutter-elt { + position: absolute; + cursor: default; + z-index: 4; +} +.CodeMirror-gutter-wrapper ::selection { background-color: transparent } +.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent } + +.CodeMirror-lines { + cursor: text; + min-height: 1px; /* prevents collapsing before first draw */ +} +.CodeMirror pre.CodeMirror-line, +.CodeMirror pre.CodeMirror-line-like { + /* Reset some styles that the rest of the page might have set */ + -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; + border-width: 0; + background: transparent; + font-family: inherit; + font-size: inherit; + margin: 0; + white-space: pre; + word-wrap: normal; + line-height: inherit; + color: inherit; + z-index: 2; + position: relative; + overflow: visible; + -webkit-tap-highlight-color: transparent; + -webkit-font-variant-ligatures: contextual; + font-variant-ligatures: contextual; +} +.CodeMirror-wrap pre.CodeMirror-line, +.CodeMirror-wrap pre.CodeMirror-line-like { + word-wrap: break-word; + white-space: pre-wrap; + word-break: normal; +} + +.CodeMirror-linebackground { + position: absolute; + left: 0; right: 0; top: 0; bottom: 0; + z-index: 0; +} + +.CodeMirror-linewidget { + position: relative; + z-index: 2; + padding: 0.1px; /* Force widget margins to stay inside of the container */ +} + +.CodeMirror-widget {} + +.CodeMirror-rtl pre { direction: rtl; } + +.CodeMirror-code { + outline: none; +} + +/* Force content-box sizing for the elements where we expect it */ +.CodeMirror-scroll, +.CodeMirror-sizer, +.CodeMirror-gutter, +.CodeMirror-gutters, +.CodeMirror-linenumber { + -moz-box-sizing: content-box; + box-sizing: content-box; +} + +.CodeMirror-measure { + position: absolute; + width: 100%; + height: 0; + overflow: hidden; + visibility: hidden; +} + +.CodeMirror-cursor { + position: absolute; + pointer-events: none; +} +.CodeMirror-measure pre { position: static; } + +div.CodeMirror-cursors { + visibility: hidden; + position: relative; + z-index: 3; +} +div.CodeMirror-dragcursors { + visibility: visible; +} + +.CodeMirror-focused div.CodeMirror-cursors { + visibility: visible; +} + +.CodeMirror-selected { background: #d9d9d9; } +.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } +.CodeMirror-crosshair { cursor: crosshair; } +.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; } +.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; } + +.cm-searching { + background-color: #ffa; + background-color: rgba(255, 255, 0, .4); +} + +/* Used to force a border model for a node */ +.cm-force-border { padding-right: .1px; } + +@media print { + /* Hide the cursor when printing */ + .CodeMirror div.CodeMirror-cursors { + visibility: hidden; + } +} + +/* See issue #2901 */ +.cm-tab-wrap-hack:after { content: ''; } + +/* Help users use markselection to safely style text background */ +span.CodeMirror-selectedtext { background: none; } diff --git a/js/codemirror/5.65.1/codemirror.js b/js/codemirror/5.65.1/codemirror.js new file mode 100644 index 0000000..3ea5d23 --- /dev/null +++ b/js/codemirror/5.65.1/codemirror.js @@ -0,0 +1,9849 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +// This is CodeMirror (https://codemirror.net), a code editor +// implemented in JavaScript on top of the browser's DOM. +// +// You can find some technical background for some of the code below +// at http://marijnhaverbeke.nl/blog/#cm-internals . + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.CodeMirror = factory()); +}(this, (function () { 'use strict'; + + // Kludges for bugs and behavior differences that can't be feature + // detected are enabled based on userAgent etc sniffing. + var userAgent = navigator.userAgent; + var platform = navigator.platform; + + var gecko = /gecko\/\d/i.test(userAgent); + var ie_upto10 = /MSIE \d/.test(userAgent); + var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); + var edge = /Edge\/(\d+)/.exec(userAgent); + var ie = ie_upto10 || ie_11up || edge; + var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]); + var webkit = !edge && /WebKit\//.test(userAgent); + var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); + var chrome = !edge && /Chrome\//.test(userAgent); + var presto = /Opera\//.test(userAgent); + var safari = /Apple Computer/.test(navigator.vendor); + var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); + var phantom = /PhantomJS/.test(userAgent); + + var ios = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2); + var android = /Android/.test(userAgent); + // This is woefully incomplete. Suggestions for alternative methods welcome. + var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); + var mac = ios || /Mac/.test(platform); + var chromeOS = /\bCrOS\b/.test(userAgent); + var windows = /win/i.test(platform); + + var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); + if (presto_version) { presto_version = Number(presto_version[1]); } + if (presto_version && presto_version >= 15) { presto = false; webkit = true; } + // Some browsers use the wrong event properties to signal cmd/ctrl on OS X + var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); + var captureRightClick = gecko || (ie && ie_version >= 9); + + function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } + + var rmClass = function(node, cls) { + var current = node.className; + var match = classTest(cls).exec(current); + if (match) { + var after = current.slice(match.index + match[0].length); + node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); + } + }; + + function removeChildren(e) { + for (var count = e.childNodes.length; count > 0; --count) + { e.removeChild(e.firstChild); } + return e + } + + function removeChildrenAndAdd(parent, e) { + return removeChildren(parent).appendChild(e) + } + + function elt(tag, content, className, style) { + var e = document.createElement(tag); + if (className) { e.className = className; } + if (style) { e.style.cssText = style; } + if (typeof content == "string") { e.appendChild(document.createTextNode(content)); } + else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } } + return e + } + // wrapper for elt, which removes the elt from the accessibility tree + function eltP(tag, content, className, style) { + var e = elt(tag, content, className, style); + e.setAttribute("role", "presentation"); + return e + } + + var range; + if (document.createRange) { range = function(node, start, end, endNode) { + var r = document.createRange(); + r.setEnd(endNode || node, end); + r.setStart(node, start); + return r + }; } + else { range = function(node, start, end) { + var r = document.body.createTextRange(); + try { r.moveToElementText(node.parentNode); } + catch(e) { return r } + r.collapse(true); + r.moveEnd("character", end); + r.moveStart("character", start); + return r + }; } + + function contains(parent, child) { + if (child.nodeType == 3) // Android browser always returns false when child is a textnode + { child = child.parentNode; } + if (parent.contains) + { return parent.contains(child) } + do { + if (child.nodeType == 11) { child = child.host; } + if (child == parent) { return true } + } while (child = child.parentNode) + } + + function activeElt() { + // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. + // IE < 10 will throw when accessed while the page is loading or in an iframe. + // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. + var activeElement; + try { + activeElement = document.activeElement; + } catch(e) { + activeElement = document.body || null; + } + while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) + { activeElement = activeElement.shadowRoot.activeElement; } + return activeElement + } + + function addClass(node, cls) { + var current = node.className; + if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; } + } + function joinClasses(a, b) { + var as = a.split(" "); + for (var i = 0; i < as.length; i++) + { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } } + return b + } + + var selectInput = function(node) { node.select(); }; + if (ios) // Mobile Safari apparently has a bug where select() is broken. + { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; } + else if (ie) // Suppress mysterious IE10 errors + { selectInput = function(node) { try { node.select(); } catch(_e) {} }; } + + function bind(f) { + var args = Array.prototype.slice.call(arguments, 1); + return function(){return f.apply(null, args)} + } + + function copyObj(obj, target, overwrite) { + if (!target) { target = {}; } + for (var prop in obj) + { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) + { target[prop] = obj[prop]; } } + return target + } + + // Counts the column offset in a string, taking tabs into account. + // Used mostly to find indentation. + function countColumn(string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) { end = string.length; } + } + for (var i = startIndex || 0, n = startValue || 0;;) { + var nextTab = string.indexOf("\t", i); + if (nextTab < 0 || nextTab >= end) + { return n + (end - i) } + n += nextTab - i; + n += tabSize - (n % tabSize); + i = nextTab + 1; + } + } + + var Delayed = function() { + this.id = null; + this.f = null; + this.time = 0; + this.handler = bind(this.onTimeout, this); + }; + Delayed.prototype.onTimeout = function (self) { + self.id = 0; + if (self.time <= +new Date) { + self.f(); + } else { + setTimeout(self.handler, self.time - +new Date); + } + }; + Delayed.prototype.set = function (ms, f) { + this.f = f; + var time = +new Date + ms; + if (!this.id || time < this.time) { + clearTimeout(this.id); + this.id = setTimeout(this.handler, ms); + this.time = time; + } + }; + + function indexOf(array, elt) { + for (var i = 0; i < array.length; ++i) + { if (array[i] == elt) { return i } } + return -1 + } + + // Number of pixels added to scroller and sizer to hide scrollbar + var scrollerGap = 50; + + // Returned or thrown by various protocols to signal 'I'm not + // handling this'. + var Pass = {toString: function(){return "CodeMirror.Pass"}}; + + // Reused option objects for setSelection & friends + var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; + + // The inverse of countColumn -- find the offset that corresponds to + // a particular column. + function findColumn(string, goal, tabSize) { + for (var pos = 0, col = 0;;) { + var nextTab = string.indexOf("\t", pos); + if (nextTab == -1) { nextTab = string.length; } + var skipped = nextTab - pos; + if (nextTab == string.length || col + skipped >= goal) + { return pos + Math.min(skipped, goal - col) } + col += nextTab - pos; + col += tabSize - (col % tabSize); + pos = nextTab + 1; + if (col >= goal) { return pos } + } + } + + var spaceStrs = [""]; + function spaceStr(n) { + while (spaceStrs.length <= n) + { spaceStrs.push(lst(spaceStrs) + " "); } + return spaceStrs[n] + } + + function lst(arr) { return arr[arr.length-1] } + + function map(array, f) { + var out = []; + for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); } + return out + } + + function insertSorted(array, value, score) { + var pos = 0, priority = score(value); + while (pos < array.length && score(array[pos]) <= priority) { pos++; } + array.splice(pos, 0, value); + } + + function nothing() {} + + function createObj(base, props) { + var inst; + if (Object.create) { + inst = Object.create(base); + } else { + nothing.prototype = base; + inst = new nothing(); + } + if (props) { copyObj(props, inst); } + return inst + } + + var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + function isWordCharBasic(ch) { + return /\w/.test(ch) || ch > "\x80" && + (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)) + } + function isWordChar(ch, helper) { + if (!helper) { return isWordCharBasic(ch) } + if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true } + return helper.test(ch) + } + + function isEmpty(obj) { + for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } } + return true + } + + // Extending unicode characters. A series of a non-extending char + + // any number of extending chars is treated as a single unit as far + // as editing and measuring is concerned. This is not fully correct, + // since some scripts/fonts/browsers also treat other configurations + // of code points as a group. + var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; + function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) } + + // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range. + function skipExtendingChars(str, pos, dir) { + while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; } + return pos + } + + // Returns the value from the range [`from`; `to`] that satisfies + // `pred` and is closest to `from`. Assumes that at least `to` + // satisfies `pred`. Supports `from` being greater than `to`. + function findFirst(pred, from, to) { + // At any point we are certain `to` satisfies `pred`, don't know + // whether `from` does. + var dir = from > to ? -1 : 1; + for (;;) { + if (from == to) { return from } + var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF); + if (mid == from) { return pred(mid) ? from : to } + if (pred(mid)) { to = mid; } + else { from = mid + dir; } + } + } + + // BIDI HELPERS + + function iterateBidiSections(order, from, to, f) { + if (!order) { return f(from, to, "ltr", 0) } + var found = false; + for (var i = 0; i < order.length; ++i) { + var part = order[i]; + if (part.from < to && part.to > from || from == to && part.to == from) { + f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i); + found = true; + } + } + if (!found) { f(from, to, "ltr"); } + } + + var bidiOther = null; + function getBidiPartAt(order, ch, sticky) { + var found; + bidiOther = null; + for (var i = 0; i < order.length; ++i) { + var cur = order[i]; + if (cur.from < ch && cur.to > ch) { return i } + if (cur.to == ch) { + if (cur.from != cur.to && sticky == "before") { found = i; } + else { bidiOther = i; } + } + if (cur.from == ch) { + if (cur.from != cur.to && sticky != "before") { found = i; } + else { bidiOther = i; } + } + } + return found != null ? found : bidiOther + } + + // Bidirectional ordering algorithm + // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm + // that this (partially) implements. + + // One-char codes used for character types: + // L (L): Left-to-Right + // R (R): Right-to-Left + // r (AL): Right-to-Left Arabic + // 1 (EN): European Number + // + (ES): European Number Separator + // % (ET): European Number Terminator + // n (AN): Arabic Number + // , (CS): Common Number Separator + // m (NSM): Non-Spacing Mark + // b (BN): Boundary Neutral + // s (B): Paragraph Separator + // t (S): Segment Separator + // w (WS): Whitespace + // N (ON): Other Neutrals + + // Returns null if characters are ordered as they appear + // (left-to-right), or an array of sections ({from, to, level} + // objects) in the order in which they occur visually. + var bidiOrdering = (function() { + // Character types for codepoints 0 to 0xff + var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; + // Character types for codepoints 0x600 to 0x6f9 + var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; + function charType(code) { + if (code <= 0xf7) { return lowTypes.charAt(code) } + else if (0x590 <= code && code <= 0x5f4) { return "R" } + else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) } + else if (0x6ee <= code && code <= 0x8ac) { return "r" } + else if (0x2000 <= code && code <= 0x200b) { return "w" } + else if (code == 0x200c) { return "b" } + else { return "L" } + } + + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; + var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; + + function BidiSpan(level, from, to) { + this.level = level; + this.from = from; this.to = to; + } + + return function(str, direction) { + var outerType = direction == "ltr" ? "L" : "R"; + + if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false } + var len = str.length, types = []; + for (var i = 0; i < len; ++i) + { types.push(charType(str.charCodeAt(i))); } + + // W1. Examine each non-spacing mark (NSM) in the level run, and + // change the type of the NSM to the type of the previous + // character. If the NSM is at the start of the level run, it will + // get the type of sor. + for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) { + var type = types[i$1]; + if (type == "m") { types[i$1] = prev; } + else { prev = type; } + } + + // W2. Search backwards from each instance of a European number + // until the first strong type (R, L, AL, or sor) is found. If an + // AL is found, change the type of the European number to Arabic + // number. + // W3. Change all ALs to R. + for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) { + var type$1 = types[i$2]; + if (type$1 == "1" && cur == "r") { types[i$2] = "n"; } + else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } } + } + + // W4. A single European separator between two European numbers + // changes to a European number. A single common separator between + // two numbers of the same type changes to that type. + for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { + var type$2 = types[i$3]; + if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; } + else if (type$2 == "," && prev$1 == types[i$3+1] && + (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; } + prev$1 = type$2; + } + + // W5. A sequence of European terminators adjacent to European + // numbers changes to all European numbers. + // W6. Otherwise, separators and terminators change to Other + // Neutral. + for (var i$4 = 0; i$4 < len; ++i$4) { + var type$3 = types[i$4]; + if (type$3 == ",") { types[i$4] = "N"; } + else if (type$3 == "%") { + var end = (void 0); + for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} + var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; + for (var j = i$4; j < end; ++j) { types[j] = replace; } + i$4 = end - 1; + } + } + + // W7. Search backwards from each instance of a European number + // until the first strong type (R, L, or sor) is found. If an L is + // found, then change the type of the European number to L. + for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { + var type$4 = types[i$5]; + if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; } + else if (isStrong.test(type$4)) { cur$1 = type$4; } + } + + // N1. A sequence of neutrals takes the direction of the + // surrounding strong text if the text on both sides has the same + // direction. European and Arabic numbers act as if they were R in + // terms of their influence on neutrals. Start-of-level-run (sor) + // and end-of-level-run (eor) are used at level run boundaries. + // N2. Any remaining neutrals take the embedding direction. + for (var i$6 = 0; i$6 < len; ++i$6) { + if (isNeutral.test(types[i$6])) { + var end$1 = (void 0); + for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} + var before = (i$6 ? types[i$6-1] : outerType) == "L"; + var after = (end$1 < len ? types[end$1] : outerType) == "L"; + var replace$1 = before == after ? (before ? "L" : "R") : outerType; + for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; } + i$6 = end$1 - 1; + } + } + + // Here we depart from the documented algorithm, in order to avoid + // building up an actual levels array. Since there are only three + // levels (0, 1, 2) in an implementation that doesn't take + // explicit embedding into account, we can build up the order on + // the fly, without following the level-based algorithm. + var order = [], m; + for (var i$7 = 0; i$7 < len;) { + if (countsAsLeft.test(types[i$7])) { + var start = i$7; + for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} + order.push(new BidiSpan(0, start, i$7)); + } else { + var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0; + for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} + for (var j$2 = pos; j$2 < i$7;) { + if (countsAsNum.test(types[j$2])) { + if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; } + var nstart = j$2; + for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} + order.splice(at, 0, new BidiSpan(2, nstart, j$2)); + at += isRTL; + pos = j$2; + } else { ++j$2; } + } + if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); } + } + } + if (direction == "ltr") { + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length; + order.unshift(new BidiSpan(0, 0, m[0].length)); + } + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length; + order.push(new BidiSpan(0, len - m[0].length, len)); + } + } + + return direction == "rtl" ? order.reverse() : order + } + })(); + + // Get the bidi ordering for the given line (and cache it). Returns + // false for lines that are fully left-to-right, and an array of + // BidiSpan objects otherwise. + function getOrder(line, direction) { + var order = line.order; + if (order == null) { order = line.order = bidiOrdering(line.text, direction); } + return order + } + + // EVENT HANDLING + + // Lightweight event framework. on/off also work on DOM nodes, + // registering native DOM handlers. + + var noHandlers = []; + + var on = function(emitter, type, f) { + if (emitter.addEventListener) { + emitter.addEventListener(type, f, false); + } else if (emitter.attachEvent) { + emitter.attachEvent("on" + type, f); + } else { + var map = emitter._handlers || (emitter._handlers = {}); + map[type] = (map[type] || noHandlers).concat(f); + } + }; + + function getHandlers(emitter, type) { + return emitter._handlers && emitter._handlers[type] || noHandlers + } + + function off(emitter, type, f) { + if (emitter.removeEventListener) { + emitter.removeEventListener(type, f, false); + } else if (emitter.detachEvent) { + emitter.detachEvent("on" + type, f); + } else { + var map = emitter._handlers, arr = map && map[type]; + if (arr) { + var index = indexOf(arr, f); + if (index > -1) + { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); } + } + } + } + + function signal(emitter, type /*, values...*/) { + var handlers = getHandlers(emitter, type); + if (!handlers.length) { return } + var args = Array.prototype.slice.call(arguments, 2); + for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); } + } + + // The DOM events that CodeMirror handles can be overridden by + // registering a (non-DOM) handler on the editor for the event name, + // and preventDefault-ing the event in that handler. + function signalDOMEvent(cm, e, override) { + if (typeof e == "string") + { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; } + signal(cm, override || e.type, cm, e); + return e_defaultPrevented(e) || e.codemirrorIgnore + } + + function signalCursorActivity(cm) { + var arr = cm._handlers && cm._handlers.cursorActivity; + if (!arr) { return } + var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); + for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1) + { set.push(arr[i]); } } + } + + function hasHandler(emitter, type) { + return getHandlers(emitter, type).length > 0 + } + + // Add on and off methods to a constructor's prototype, to make + // registering events on such objects more convenient. + function eventMixin(ctor) { + ctor.prototype.on = function(type, f) {on(this, type, f);}; + ctor.prototype.off = function(type, f) {off(this, type, f);}; + } + + // Due to the fact that we still support jurassic IE versions, some + // compatibility wrappers are needed. + + function e_preventDefault(e) { + if (e.preventDefault) { e.preventDefault(); } + else { e.returnValue = false; } + } + function e_stopPropagation(e) { + if (e.stopPropagation) { e.stopPropagation(); } + else { e.cancelBubble = true; } + } + function e_defaultPrevented(e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false + } + function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} + + function e_target(e) {return e.target || e.srcElement} + function e_button(e) { + var b = e.which; + if (b == null) { + if (e.button & 1) { b = 1; } + else if (e.button & 2) { b = 3; } + else if (e.button & 4) { b = 2; } + } + if (mac && e.ctrlKey && b == 1) { b = 3; } + return b + } + + // Detect drag-and-drop + var dragAndDrop = function() { + // There is *some* kind of drag-and-drop support in IE6-8, but I + // couldn't get it to work yet. + if (ie && ie_version < 9) { return false } + var div = elt('div'); + return "draggable" in div || "dragDrop" in div + }(); + + var zwspSupported; + function zeroWidthElement(measure) { + if (zwspSupported == null) { + var test = elt("span", "\u200b"); + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); + if (measure.firstChild.offsetHeight != 0) + { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); } + } + var node = zwspSupported ? elt("span", "\u200b") : + elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); + node.setAttribute("cm-text", ""); + return node + } + + // Feature-detect IE's crummy client rect reporting for bidi text + var badBidiRects; + function hasBadBidiRects(measure) { + if (badBidiRects != null) { return badBidiRects } + var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); + var r0 = range(txt, 0, 1).getBoundingClientRect(); + var r1 = range(txt, 1, 2).getBoundingClientRect(); + removeChildren(measure); + if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780) + return badBidiRects = (r1.right - r0.right < 3) + } + + // See if "".split is the broken IE version, if so, provide an + // alternative way to split lines. + var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { + var pos = 0, result = [], l = string.length; + while (pos <= l) { + var nl = string.indexOf("\n", pos); + if (nl == -1) { nl = string.length; } + var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); + var rt = line.indexOf("\r"); + if (rt != -1) { + result.push(line.slice(0, rt)); + pos += rt + 1; + } else { + result.push(line); + pos = nl + 1; + } + } + return result + } : function (string) { return string.split(/\r\n?|\n/); }; + + var hasSelection = window.getSelection ? function (te) { + try { return te.selectionStart != te.selectionEnd } + catch(e) { return false } + } : function (te) { + var range; + try {range = te.ownerDocument.selection.createRange();} + catch(e) {} + if (!range || range.parentElement() != te) { return false } + return range.compareEndPoints("StartToEnd", range) != 0 + }; + + var hasCopyEvent = (function () { + var e = elt("div"); + if ("oncopy" in e) { return true } + e.setAttribute("oncopy", "return;"); + return typeof e.oncopy == "function" + })(); + + var badZoomedRects = null; + function hasBadZoomedRects(measure) { + if (badZoomedRects != null) { return badZoomedRects } + var node = removeChildrenAndAdd(measure, elt("span", "x")); + var normal = node.getBoundingClientRect(); + var fromRange = range(node, 0, 1).getBoundingClientRect(); + return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 + } + + // Known modes, by name and by MIME + var modes = {}, mimeModes = {}; + + // Extra arguments are stored as the mode's dependencies, which is + // used by (legacy) mechanisms like loadmode.js to automatically + // load a mode. (Preferred mechanism is the require/define calls.) + function defineMode(name, mode) { + if (arguments.length > 2) + { mode.dependencies = Array.prototype.slice.call(arguments, 2); } + modes[name] = mode; + } + + function defineMIME(mime, spec) { + mimeModes[mime] = spec; + } + + // Given a MIME type, a {name, ...options} config object, or a name + // string, return a mode config object. + function resolveMode(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec]; + } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { + var found = mimeModes[spec.name]; + if (typeof found == "string") { found = {name: found}; } + spec = createObj(found, spec); + spec.name = found.name; + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return resolveMode("application/xml") + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { + return resolveMode("application/json") + } + if (typeof spec == "string") { return {name: spec} } + else { return spec || {name: "null"} } + } + + // Given a mode spec (anything that resolveMode accepts), find and + // initialize an actual mode object. + function getMode(options, spec) { + spec = resolveMode(spec); + var mfactory = modes[spec.name]; + if (!mfactory) { return getMode(options, "text/plain") } + var modeObj = mfactory(options, spec); + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name]; + for (var prop in exts) { + if (!exts.hasOwnProperty(prop)) { continue } + if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; } + modeObj[prop] = exts[prop]; + } + } + modeObj.name = spec.name; + if (spec.helperType) { modeObj.helperType = spec.helperType; } + if (spec.modeProps) { for (var prop$1 in spec.modeProps) + { modeObj[prop$1] = spec.modeProps[prop$1]; } } + + return modeObj + } + + // This can be used to attach properties to mode objects from + // outside the actual mode definition. + var modeExtensions = {}; + function extendMode(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); + copyObj(properties, exts); + } + + function copyState(mode, state) { + if (state === true) { return state } + if (mode.copyState) { return mode.copyState(state) } + var nstate = {}; + for (var n in state) { + var val = state[n]; + if (val instanceof Array) { val = val.concat([]); } + nstate[n] = val; + } + return nstate + } + + // Given a mode and a state (for that mode), find the inner mode and + // state at the position that the state refers to. + function innerMode(mode, state) { + var info; + while (mode.innerMode) { + info = mode.innerMode(state); + if (!info || info.mode == mode) { break } + state = info.state; + mode = info.mode; + } + return info || {mode: mode, state: state} + } + + function startState(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true + } + + // STRING STREAM + + // Fed to the mode parsers, provides helper functions to make + // parsers more succinct. + + var StringStream = function(string, tabSize, lineOracle) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + this.lastColumnPos = this.lastColumnValue = 0; + this.lineStart = 0; + this.lineOracle = lineOracle; + }; + + StringStream.prototype.eol = function () {return this.pos >= this.string.length}; + StringStream.prototype.sol = function () {return this.pos == this.lineStart}; + StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined}; + StringStream.prototype.next = function () { + if (this.pos < this.string.length) + { return this.string.charAt(this.pos++) } + }; + StringStream.prototype.eat = function (match) { + var ch = this.string.charAt(this.pos); + var ok; + if (typeof match == "string") { ok = ch == match; } + else { ok = ch && (match.test ? match.test(ch) : match(ch)); } + if (ok) {++this.pos; return ch} + }; + StringStream.prototype.eatWhile = function (match) { + var start = this.pos; + while (this.eat(match)){} + return this.pos > start + }; + StringStream.prototype.eatSpace = function () { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; } + return this.pos > start + }; + StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;}; + StringStream.prototype.skipTo = function (ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) {this.pos = found; return true} + }; + StringStream.prototype.backUp = function (n) {this.pos -= n;}; + StringStream.prototype.column = function () { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); + this.lastColumnPos = this.start; + } + return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) + }; + StringStream.prototype.indentation = function () { + return countColumn(this.string, null, this.tabSize) - + (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) + }; + StringStream.prototype.match = function (pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) { this.pos += pattern.length; } + return true + } + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) { return null } + if (match && consume !== false) { this.pos += match[0].length; } + return match + } + }; + StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)}; + StringStream.prototype.hideFirstChars = function (n, inner) { + this.lineStart += n; + try { return inner() } + finally { this.lineStart -= n; } + }; + StringStream.prototype.lookAhead = function (n) { + var oracle = this.lineOracle; + return oracle && oracle.lookAhead(n) + }; + StringStream.prototype.baseToken = function () { + var oracle = this.lineOracle; + return oracle && oracle.baseToken(this.pos) + }; + + // Find the line object corresponding to the given line number. + function getLine(doc, n) { + n -= doc.first; + if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") } + var chunk = doc; + while (!chunk.lines) { + for (var i = 0;; ++i) { + var child = chunk.children[i], sz = child.chunkSize(); + if (n < sz) { chunk = child; break } + n -= sz; + } + } + return chunk.lines[n] + } + + // Get the part of a document between two positions, as an array of + // strings. + function getBetween(doc, start, end) { + var out = [], n = start.line; + doc.iter(start.line, end.line + 1, function (line) { + var text = line.text; + if (n == end.line) { text = text.slice(0, end.ch); } + if (n == start.line) { text = text.slice(start.ch); } + out.push(text); + ++n; + }); + return out + } + // Get the lines between from and to, as array of strings. + function getLines(doc, from, to) { + var out = []; + doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value + return out + } + + // Update the height of a line, propagating the height change + // upwards to parent nodes. + function updateLineHeight(line, height) { + var diff = height - line.height; + if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } } + } + + // Given a line object, find its line number by walking up through + // its parent links. + function lineNo(line) { + if (line.parent == null) { return null } + var cur = line.parent, no = indexOf(cur.lines, line); + for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { + for (var i = 0;; ++i) { + if (chunk.children[i] == cur) { break } + no += chunk.children[i].chunkSize(); + } + } + return no + cur.first + } + + // Find the line at the given vertical position, using the height + // information in the document tree. + function lineAtHeight(chunk, h) { + var n = chunk.first; + outer: do { + for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) { + var child = chunk.children[i$1], ch = child.height; + if (h < ch) { chunk = child; continue outer } + h -= ch; + n += child.chunkSize(); + } + return n + } while (!chunk.lines) + var i = 0; + for (; i < chunk.lines.length; ++i) { + var line = chunk.lines[i], lh = line.height; + if (h < lh) { break } + h -= lh; + } + return n + i + } + + function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size} + + function lineNumberFor(options, i) { + return String(options.lineNumberFormatter(i + options.firstLineNumber)) + } + + // A Pos instance represents a position within the text. + function Pos(line, ch, sticky) { + if ( sticky === void 0 ) sticky = null; + + if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) } + this.line = line; + this.ch = ch; + this.sticky = sticky; + } + + // Compare two positions, return 0 if they are the same, a negative + // number when a is less, and a positive number otherwise. + function cmp(a, b) { return a.line - b.line || a.ch - b.ch } + + function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 } + + function copyPos(x) {return Pos(x.line, x.ch)} + function maxPos(a, b) { return cmp(a, b) < 0 ? b : a } + function minPos(a, b) { return cmp(a, b) < 0 ? a : b } + + // Most of the external API clips given positions to make sure they + // actually exist within the document. + function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))} + function clipPos(doc, pos) { + if (pos.line < doc.first) { return Pos(doc.first, 0) } + var last = doc.first + doc.size - 1; + if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) } + return clipToLen(pos, getLine(doc, pos.line).text.length) + } + function clipToLen(pos, linelen) { + var ch = pos.ch; + if (ch == null || ch > linelen) { return Pos(pos.line, linelen) } + else if (ch < 0) { return Pos(pos.line, 0) } + else { return pos } + } + function clipPosArray(doc, array) { + var out = []; + for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); } + return out + } + + var SavedContext = function(state, lookAhead) { + this.state = state; + this.lookAhead = lookAhead; + }; + + var Context = function(doc, state, line, lookAhead) { + this.state = state; + this.doc = doc; + this.line = line; + this.maxLookAhead = lookAhead || 0; + this.baseTokens = null; + this.baseTokenPos = 1; + }; + + Context.prototype.lookAhead = function (n) { + var line = this.doc.getLine(this.line + n); + if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; } + return line + }; + + Context.prototype.baseToken = function (n) { + if (!this.baseTokens) { return null } + while (this.baseTokens[this.baseTokenPos] <= n) + { this.baseTokenPos += 2; } + var type = this.baseTokens[this.baseTokenPos + 1]; + return {type: type && type.replace(/( |^)overlay .*/, ""), + size: this.baseTokens[this.baseTokenPos] - n} + }; + + Context.prototype.nextLine = function () { + this.line++; + if (this.maxLookAhead > 0) { this.maxLookAhead--; } + }; + + Context.fromSaved = function (doc, saved, line) { + if (saved instanceof SavedContext) + { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) } + else + { return new Context(doc, copyState(doc.mode, saved), line) } + }; + + Context.prototype.save = function (copy) { + var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; + return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state + }; + + + // Compute a style array (an array starting with a mode generation + // -- for invalidation -- followed by pairs of end positions and + // style strings), which is used to highlight the tokens on the + // line. + function highlightLine(cm, line, context, forceToEnd) { + // A styles array always starts with a number identifying the + // mode/overlays that it is based on (for easy invalidation). + var st = [cm.state.modeGen], lineClasses = {}; + // Compute the base array of styles + runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); }, + lineClasses, forceToEnd); + var state = context.state; + + // Run overlays, adjust style array. + var loop = function ( o ) { + context.baseTokens = st; + var overlay = cm.state.overlays[o], i = 1, at = 0; + context.state = true; + runMode(cm, line.text, overlay.mode, context, function (end, style) { + var start = i; + // Ensure there's a token end at the current position, and that i points at it + while (at < end) { + var i_end = st[i]; + if (i_end > end) + { st.splice(i, 1, end, st[i+1], i_end); } + i += 2; + at = Math.min(end, i_end); + } + if (!style) { return } + if (overlay.opaque) { + st.splice(start, i - start, end, "overlay " + style); + i = start + 2; + } else { + for (; start < i; start += 2) { + var cur = st[start+1]; + st[start+1] = (cur ? cur + " " : "") + "overlay " + style; + } + } + }, lineClasses); + context.state = state; + context.baseTokens = null; + context.baseTokenPos = 1; + }; + + for (var o = 0; o < cm.state.overlays.length; ++o) loop( o ); + + return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} + } + + function getLineStyles(cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + var context = getContextBefore(cm, lineNo(line)); + var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); + var result = highlightLine(cm, line, context); + if (resetState) { context.state = resetState; } + line.stateAfter = context.save(!resetState); + line.styles = result.styles; + if (result.classes) { line.styleClasses = result.classes; } + else if (line.styleClasses) { line.styleClasses = null; } + if (updateFrontier === cm.doc.highlightFrontier) + { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); } + } + return line.styles + } + + function getContextBefore(cm, n, precise) { + var doc = cm.doc, display = cm.display; + if (!doc.mode.startState) { return new Context(doc, true, n) } + var start = findStartLine(cm, n, precise); + var saved = start > doc.first && getLine(doc, start - 1).stateAfter; + var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start); + + doc.iter(start, n, function (line) { + processLine(cm, line.text, context); + var pos = context.line; + line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; + context.nextLine(); + }); + if (precise) { doc.modeFrontier = context.line; } + return context + } + + // Lightweight form of highlight -- proceed over this line and + // update state, but don't save a style array. Used for lines that + // aren't currently visible. + function processLine(cm, text, context, startAt) { + var mode = cm.doc.mode; + var stream = new StringStream(text, cm.options.tabSize, context); + stream.start = stream.pos = startAt || 0; + if (text == "") { callBlankLine(mode, context.state); } + while (!stream.eol()) { + readToken(mode, stream, context.state); + stream.start = stream.pos; + } + } + + function callBlankLine(mode, state) { + if (mode.blankLine) { return mode.blankLine(state) } + if (!mode.innerMode) { return } + var inner = innerMode(mode, state); + if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) } + } + + function readToken(mode, stream, state, inner) { + for (var i = 0; i < 10; i++) { + if (inner) { inner[0] = innerMode(mode, state).mode; } + var style = mode.token(stream, state); + if (stream.pos > stream.start) { return style } + } + throw new Error("Mode " + mode.name + " failed to advance stream.") + } + + var Token = function(stream, type, state) { + this.start = stream.start; this.end = stream.pos; + this.string = stream.current(); + this.type = type || null; + this.state = state; + }; + + // Utility for getTokenAt and getLineTokens + function takeToken(cm, pos, precise, asArray) { + var doc = cm.doc, mode = doc.mode, style; + pos = clipPos(doc, pos); + var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise); + var stream = new StringStream(line.text, cm.options.tabSize, context), tokens; + if (asArray) { tokens = []; } + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos; + style = readToken(mode, stream, context.state); + if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); } + } + return asArray ? tokens : new Token(stream, style, context.state) + } + + function extractLineClasses(type, output) { + if (type) { for (;;) { + var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); + if (!lineClass) { break } + type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); + var prop = lineClass[1] ? "bgClass" : "textClass"; + if (output[prop] == null) + { output[prop] = lineClass[2]; } + else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop])) + { output[prop] += " " + lineClass[2]; } + } } + return type + } + + // Run the given mode's parser over a line, calling f for each token. + function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { + var flattenSpans = mode.flattenSpans; + if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; } + var curStart = 0, curStyle = null; + var stream = new StringStream(text, cm.options.tabSize, context), style; + var inner = cm.options.addModeClass && [null]; + if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); } + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false; + if (forceToEnd) { processLine(cm, text, context, stream.pos); } + stream.pos = text.length; + style = null; + } else { + style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); + } + if (inner) { + var mName = inner[0].name; + if (mName) { style = "m-" + (style ? mName + " " + style : mName); } + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 5000); + f(curStart, curStyle); + } + curStyle = style; + } + stream.start = stream.pos; + } + while (curStart < stream.pos) { + // Webkit seems to refuse to render text nodes longer than 57444 + // characters, and returns inaccurate measurements in nodes + // starting around 5000 chars. + var pos = Math.min(stream.pos, curStart + 5000); + f(pos, curStyle); + curStart = pos; + } + } + + // Finds the line to start with when starting a parse. Tries to + // find a line with a stateAfter, so that it can start with a + // valid state. If that fails, it returns the line with the + // smallest indentation, which tends to need the least context to + // parse correctly. + function findStartLine(cm, n, precise) { + var minindent, minline, doc = cm.doc; + var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); + for (var search = n; search > lim; --search) { + if (search <= doc.first) { return doc.first } + var line = getLine(doc, search - 1), after = line.stateAfter; + if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) + { return search } + var indented = countColumn(line.text, null, cm.options.tabSize); + if (minline == null || minindent > indented) { + minline = search - 1; + minindent = indented; + } + } + return minline + } + + function retreatFrontier(doc, n) { + doc.modeFrontier = Math.min(doc.modeFrontier, n); + if (doc.highlightFrontier < n - 10) { return } + var start = doc.first; + for (var line = n - 1; line > start; line--) { + var saved = getLine(doc, line).stateAfter; + // change is on 3 + // state on line 1 looked ahead 2 -- so saw 3 + // test 1 + 2 < 3 should cover this + if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { + start = line + 1; + break + } + } + doc.highlightFrontier = Math.min(doc.highlightFrontier, start); + } + + // Optimize some code when these features are not used. + var sawReadOnlySpans = false, sawCollapsedSpans = false; + + function seeReadOnlySpans() { + sawReadOnlySpans = true; + } + + function seeCollapsedSpans() { + sawCollapsedSpans = true; + } + + // TEXTMARKER SPANS + + function MarkedSpan(marker, from, to) { + this.marker = marker; + this.from = from; this.to = to; + } + + // Search an array of spans for a span matching the given marker. + function getMarkedSpanFor(spans, marker) { + if (spans) { for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.marker == marker) { return span } + } } + } + + // Remove a span from an array, returning undefined if no spans are + // left (we don't store arrays for lines without spans). + function removeMarkedSpan(spans, span) { + var r; + for (var i = 0; i < spans.length; ++i) + { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } } + return r + } + + // Add a span to a line. + function addMarkedSpan(line, span, op) { + var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet)); + if (inThisOp && inThisOp.has(line.markedSpans)) { + line.markedSpans.push(span); + } else { + line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; + if (inThisOp) { inThisOp.add(line.markedSpans); } + } + span.marker.attachLine(line); + } + + // Used for the algorithm that adjusts markers for a change in the + // document. These functions cut an array of spans at a given + // character position, returning an array of remaining chunks (or + // undefined if nothing remains). + function markedSpansBefore(old, startCh, isInsert) { + var nw; + if (old) { for (var i = 0; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); + if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh) + ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); + } + } } + return nw + } + function markedSpansAfter(old, endCh, isInsert) { + var nw; + if (old) { for (var i = 0; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); + if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh) + ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, + span.to == null ? null : span.to - endCh)); + } + } } + return nw + } + + // Given a change object, compute the new set of marker spans that + // cover the line in which the change took place. Removes spans + // entirely within the change, reconnects spans belonging to the + // same marker that appear on both sides of the change, and cuts off + // spans partially within the change. Returns an array of span + // arrays with one element for each line in (after) the change. + function stretchSpansOverChange(doc, change) { + if (change.full) { return null } + var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; + var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; + if (!oldFirst && !oldLast) { return null } + + var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; + // Get the spans that 'stick out' on both sides + var first = markedSpansBefore(oldFirst, startCh, isInsert); + var last = markedSpansAfter(oldLast, endCh, isInsert); + + // Next, merge those two ends + var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); + if (first) { + // Fix up .to properties of first + for (var i = 0; i < first.length; ++i) { + var span = first[i]; + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker); + if (!found) { span.to = startCh; } + else if (sameLine) { span.to = found.to == null ? null : found.to + offset; } + } + } + } + if (last) { + // Fix up .from in last (or move them into first in case of sameLine) + for (var i$1 = 0; i$1 < last.length; ++i$1) { + var span$1 = last[i$1]; + if (span$1.to != null) { span$1.to += offset; } + if (span$1.from == null) { + var found$1 = getMarkedSpanFor(first, span$1.marker); + if (!found$1) { + span$1.from = offset; + if (sameLine) { (first || (first = [])).push(span$1); } + } + } else { + span$1.from += offset; + if (sameLine) { (first || (first = [])).push(span$1); } + } + } + } + // Make sure we didn't create any zero-length spans + if (first) { first = clearEmptySpans(first); } + if (last && last != first) { last = clearEmptySpans(last); } + + var newMarkers = [first]; + if (!sameLine) { + // Fill gap with whole-line-spans + var gap = change.text.length - 2, gapMarkers; + if (gap > 0 && first) + { for (var i$2 = 0; i$2 < first.length; ++i$2) + { if (first[i$2].to == null) + { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } } + for (var i$3 = 0; i$3 < gap; ++i$3) + { newMarkers.push(gapMarkers); } + newMarkers.push(last); + } + return newMarkers + } + + // Remove spans that are empty and don't have a clearWhenEmpty + // option of false. + function clearEmptySpans(spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) + { spans.splice(i--, 1); } + } + if (!spans.length) { return null } + return spans + } + + // Used to 'clip' out readOnly ranges when making a change. + function removeReadOnlyRanges(doc, from, to) { + var markers = null; + doc.iter(from.line, to.line + 1, function (line) { + if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { + var mark = line.markedSpans[i].marker; + if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) + { (markers || (markers = [])).push(mark); } + } } + }); + if (!markers) { return null } + var parts = [{from: from, to: to}]; + for (var i = 0; i < markers.length; ++i) { + var mk = markers[i], m = mk.find(0); + for (var j = 0; j < parts.length; ++j) { + var p = parts[j]; + if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue } + var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); + if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) + { newParts.push({from: p.from, to: m.from}); } + if (dto > 0 || !mk.inclusiveRight && !dto) + { newParts.push({from: m.to, to: p.to}); } + parts.splice.apply(parts, newParts); + j += newParts.length - 3; + } + } + return parts + } + + // Connect or disconnect spans from a line. + function detachMarkedSpans(line) { + var spans = line.markedSpans; + if (!spans) { return } + for (var i = 0; i < spans.length; ++i) + { spans[i].marker.detachLine(line); } + line.markedSpans = null; + } + function attachMarkedSpans(line, spans) { + if (!spans) { return } + for (var i = 0; i < spans.length; ++i) + { spans[i].marker.attachLine(line); } + line.markedSpans = spans; + } + + // Helpers used when computing which overlapping collapsed span + // counts as the larger one. + function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 } + function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 } + + // Returns a number indicating which of two overlapping collapsed + // spans is larger (and thus includes the other). Falls back to + // comparing ids when the spans cover exactly the same range. + function compareCollapsedMarkers(a, b) { + var lenDiff = a.lines.length - b.lines.length; + if (lenDiff != 0) { return lenDiff } + var aPos = a.find(), bPos = b.find(); + var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); + if (fromCmp) { return -fromCmp } + var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); + if (toCmp) { return toCmp } + return b.id - a.id + } + + // Find out whether a line ends or starts in a collapsed span. If + // so, return the marker for that span. + function collapsedSpanAtSide(line, start) { + var sps = sawCollapsedSpans && line.markedSpans, found; + if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && + (!found || compareCollapsedMarkers(found, sp.marker) < 0)) + { found = sp.marker; } + } } + return found + } + function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) } + function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) } + + function collapsedSpanAround(line, ch) { + var sps = sawCollapsedSpans && line.markedSpans, found; + if (sps) { for (var i = 0; i < sps.length; ++i) { + var sp = sps[i]; + if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && + (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; } + } } + return found + } + + // Test whether there exists a collapsed span that partially + // overlaps (covers the start or end, but not both) of a new span. + // Such overlap is not allowed. + function conflictingCollapsedRange(doc, lineNo, from, to, marker) { + var line = getLine(doc, lineNo); + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { for (var i = 0; i < sps.length; ++i) { + var sp = sps[i]; + if (!sp.marker.collapsed) { continue } + var found = sp.marker.find(0); + var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); + var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); + if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue } + if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || + fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) + { return true } + } } + } + + // A visual line is a line as drawn on the screen. Folding, for + // example, can cause multiple logical lines to appear on the same + // visual line. This finds the start of the visual line that the + // given line is part of (usually that is the line itself). + function visualLine(line) { + var merged; + while (merged = collapsedSpanAtStart(line)) + { line = merged.find(-1, true).line; } + return line + } + + function visualLineEnd(line) { + var merged; + while (merged = collapsedSpanAtEnd(line)) + { line = merged.find(1, true).line; } + return line + } + + // Returns an array of logical lines that continue the visual line + // started by the argument, or undefined if there are no such lines. + function visualLineContinued(line) { + var merged, lines; + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line + ;(lines || (lines = [])).push(line); + } + return lines + } + + // Get the line number of the start of the visual line that the + // given line number is part of. + function visualLineNo(doc, lineN) { + var line = getLine(doc, lineN), vis = visualLine(line); + if (line == vis) { return lineN } + return lineNo(vis) + } + + // Get the line number of the start of the next visual line after + // the given line. + function visualLineEndNo(doc, lineN) { + if (lineN > doc.lastLine()) { return lineN } + var line = getLine(doc, lineN), merged; + if (!lineIsHidden(doc, line)) { return lineN } + while (merged = collapsedSpanAtEnd(line)) + { line = merged.find(1, true).line; } + return lineNo(line) + 1 + } + + // Compute whether a line is hidden. Lines count as hidden when they + // are part of a visual line that starts with another line, or when + // they are entirely covered by collapsed, non-widget span. + function lineIsHidden(doc, line) { + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (!sp.marker.collapsed) { continue } + if (sp.from == null) { return true } + if (sp.marker.widgetNode) { continue } + if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) + { return true } + } } + } + function lineIsHiddenInner(doc, line, span) { + if (span.to == null) { + var end = span.marker.find(1, true); + return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)) + } + if (span.marker.inclusiveRight && span.to == line.text.length) + { return true } + for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) { + sp = line.markedSpans[i]; + if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && + (sp.to == null || sp.to != span.from) && + (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && + lineIsHiddenInner(doc, line, sp)) { return true } + } + } + + // Find the height above the given line. + function heightAtLine(lineObj) { + lineObj = visualLine(lineObj); + + var h = 0, chunk = lineObj.parent; + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i]; + if (line == lineObj) { break } + else { h += line.height; } + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i$1 = 0; i$1 < p.children.length; ++i$1) { + var cur = p.children[i$1]; + if (cur == chunk) { break } + else { h += cur.height; } + } + } + return h + } + + // Compute the character length of a line, taking into account + // collapsed ranges (see markText) that might hide parts, and join + // other lines onto it. + function lineLength(line) { + if (line.height == 0) { return 0 } + var len = line.text.length, merged, cur = line; + while (merged = collapsedSpanAtStart(cur)) { + var found = merged.find(0, true); + cur = found.from.line; + len += found.from.ch - found.to.ch; + } + cur = line; + while (merged = collapsedSpanAtEnd(cur)) { + var found$1 = merged.find(0, true); + len -= cur.text.length - found$1.from.ch; + cur = found$1.to.line; + len += cur.text.length - found$1.to.ch; + } + return len + } + + // Find the longest line in the document. + function findMaxLine(cm) { + var d = cm.display, doc = cm.doc; + d.maxLine = getLine(doc, doc.first); + d.maxLineLength = lineLength(d.maxLine); + d.maxLineChanged = true; + doc.iter(function (line) { + var len = lineLength(line); + if (len > d.maxLineLength) { + d.maxLineLength = len; + d.maxLine = line; + } + }); + } + + // LINE DATA STRUCTURE + + // Line objects. These hold state related to a line, including + // highlighting info (the styles array). + var Line = function(text, markedSpans, estimateHeight) { + this.text = text; + attachMarkedSpans(this, markedSpans); + this.height = estimateHeight ? estimateHeight(this) : 1; + }; + + Line.prototype.lineNo = function () { return lineNo(this) }; + eventMixin(Line); + + // Change the content (text, markers) of a line. Automatically + // invalidates cached information and tries to re-estimate the + // line's height. + function updateLine(line, text, markedSpans, estimateHeight) { + line.text = text; + if (line.stateAfter) { line.stateAfter = null; } + if (line.styles) { line.styles = null; } + if (line.order != null) { line.order = null; } + detachMarkedSpans(line); + attachMarkedSpans(line, markedSpans); + var estHeight = estimateHeight ? estimateHeight(line) : 1; + if (estHeight != line.height) { updateLineHeight(line, estHeight); } + } + + // Detach a line from the document tree and its markers. + function cleanUpLine(line) { + line.parent = null; + detachMarkedSpans(line); + } + + // Convert a style as returned by a mode (either null, or a string + // containing one or more styles) to a CSS style. This is cached, + // and also looks for line-wide styles. + var styleToClassCache = {}, styleToClassCacheWithMode = {}; + function interpretTokenStyle(style, options) { + if (!style || /^\s*$/.test(style)) { return null } + var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; + return cache[style] || + (cache[style] = style.replace(/\S+/g, "cm-$&")) + } + + // Render the DOM representation of the text of a line. Also builds + // up a 'line map', which points at the DOM nodes that represent + // specific stretches of text, and is used by the measuring code. + // The returned object contains the DOM node, this map, and + // information about line-wide styles that were set by the mode. + function buildLineContent(cm, lineView) { + // The padding-right forces the element to have a 'border', which + // is needed on Webkit to be able to get line-level bounding + // rectangles for it (in measureChar). + var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); + var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content, + col: 0, pos: 0, cm: cm, + trailingSpace: false, + splitSpaces: cm.getOption("lineWrapping")}; + lineView.measure = {}; + + // Iterate over the logical lines that make up this visual line. + for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { + var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0); + builder.pos = 0; + builder.addToken = buildToken; + // Optionally wire in some hacks into the token-rendering + // algorithm, to deal with browser quirks. + if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) + { builder.addToken = buildTokenBadBidi(builder.addToken, order); } + builder.map = []; + var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); + insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); + if (line.styleClasses) { + if (line.styleClasses.bgClass) + { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); } + if (line.styleClasses.textClass) + { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); } + } + + // Ensure at least a single node is present, for measuring. + if (builder.map.length == 0) + { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); } + + // Store the map and a cache object for the current logical line + if (i == 0) { + lineView.measure.map = builder.map; + lineView.measure.cache = {}; + } else { + (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) + ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}); + } + } + + // See issue #2901 + if (webkit) { + var last = builder.content.lastChild; + if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) + { builder.content.className = "cm-tab-wrap-hack"; } + } + + signal(cm, "renderLine", cm, lineView.line, builder.pre); + if (builder.pre.className) + { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); } + + return builder + } + + function defaultSpecialCharPlaceholder(ch) { + var token = elt("span", "\u2022", "cm-invalidchar"); + token.title = "\\u" + ch.charCodeAt(0).toString(16); + token.setAttribute("aria-label", token.title); + return token + } + + // Build up the DOM representation for a single token, and add it to + // the line map. Takes care to render special characters separately. + function buildToken(builder, text, style, startStyle, endStyle, css, attributes) { + if (!text) { return } + var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; + var special = builder.cm.state.specialChars, mustWrap = false; + var content; + if (!special.test(text)) { + builder.col += text.length; + content = document.createTextNode(displayText); + builder.map.push(builder.pos, builder.pos + text.length, content); + if (ie && ie_version < 9) { mustWrap = true; } + builder.pos += text.length; + } else { + content = document.createDocumentFragment(); + var pos = 0; + while (true) { + special.lastIndex = pos; + var m = special.exec(text); + var skipped = m ? m.index - pos : text.length - pos; + if (skipped) { + var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); + if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); } + else { content.appendChild(txt); } + builder.map.push(builder.pos, builder.pos + skipped, txt); + builder.col += skipped; + builder.pos += skipped; + } + if (!m) { break } + pos += skipped + 1; + var txt$1 = (void 0); + if (m[0] == "\t") { + var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; + txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); + txt$1.setAttribute("role", "presentation"); + txt$1.setAttribute("cm-text", "\t"); + builder.col += tabWidth; + } else if (m[0] == "\r" || m[0] == "\n") { + txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); + txt$1.setAttribute("cm-text", m[0]); + builder.col += 1; + } else { + txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); + txt$1.setAttribute("cm-text", m[0]); + if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); } + else { content.appendChild(txt$1); } + builder.col += 1; + } + builder.map.push(builder.pos, builder.pos + 1, txt$1); + builder.pos++; + } + } + builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; + if (style || startStyle || endStyle || mustWrap || css || attributes) { + var fullStyle = style || ""; + if (startStyle) { fullStyle += startStyle; } + if (endStyle) { fullStyle += endStyle; } + var token = elt("span", [content], fullStyle, css); + if (attributes) { + for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") + { token.setAttribute(attr, attributes[attr]); } } + } + return builder.content.appendChild(token) + } + builder.content.appendChild(content); + } + + // Change some spaces to NBSP to prevent the browser from collapsing + // trailing spaces at the end of a line when rendering text (issue #1362). + function splitSpaces(text, trailingBefore) { + if (text.length > 1 && !/ /.test(text)) { return text } + var spaceBefore = trailingBefore, result = ""; + for (var i = 0; i < text.length; i++) { + var ch = text.charAt(i); + if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) + { ch = "\u00a0"; } + result += ch; + spaceBefore = ch == " "; + } + return result + } + + // Work around nonsense dimensions being reported for stretches of + // right-to-left text. + function buildTokenBadBidi(inner, order) { + return function (builder, text, style, startStyle, endStyle, css, attributes) { + style = style ? style + " cm-force-border" : "cm-force-border"; + var start = builder.pos, end = start + text.length; + for (;;) { + // Find the part that overlaps with the start of this text + var part = (void 0); + for (var i = 0; i < order.length; i++) { + part = order[i]; + if (part.to > start && part.from <= start) { break } + } + if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) } + inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes); + startStyle = null; + text = text.slice(part.to - start); + start = part.to; + } + } + } + + function buildCollapsedSpan(builder, size, marker, ignoreWidget) { + var widget = !ignoreWidget && marker.widgetNode; + if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); } + if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { + if (!widget) + { widget = builder.content.appendChild(document.createElement("span")); } + widget.setAttribute("cm-marker", marker.id); + } + if (widget) { + builder.cm.display.input.setUneditable(widget); + builder.content.appendChild(widget); + } + builder.pos += size; + builder.trailingSpace = false; + } + + // Outputs a number of spans to make up a line, taking highlighting + // and marked text into account. + function insertLineContent(line, builder, styles) { + var spans = line.markedSpans, allText = line.text, at = 0; + if (!spans) { + for (var i$1 = 1; i$1 < styles.length; i$1+=2) + { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); } + return + } + + var len = allText.length, pos = 0, i = 1, text = "", style, css; + var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes; + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = css = ""; + attributes = null; + collapsed = null; nextChange = Infinity; + var foundBookmarks = [], endStyles = (void 0); + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], m = sp.marker; + if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { + foundBookmarks.push(m); + } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { + if (sp.to != null && sp.to != pos && nextChange > sp.to) { + nextChange = sp.to; + spanEndStyle = ""; + } + if (m.className) { spanStyle += " " + m.className; } + if (m.css) { css = (css ? css + ";" : "") + m.css; } + if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; } + if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); } + // support for the old title property + // https://github.com/codemirror/CodeMirror/pull/5673 + if (m.title) { (attributes || (attributes = {})).title = m.title; } + if (m.attributes) { + for (var attr in m.attributes) + { (attributes || (attributes = {}))[attr] = m.attributes[attr]; } + } + if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) + { collapsed = sp; } + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from; + } + } + if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) + { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } } + + if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) + { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } } + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, + collapsed.marker, collapsed.from == null); + if (collapsed.to == null) { return } + if (collapsed.to == pos) { collapsed = false; } + } + } + if (pos >= len) { break } + + var upto = Math.min(len, nextChange); + while (true) { + if (text) { + var end = pos + text.length; + if (!collapsed) { + var tokenText = end > upto ? text.slice(0, upto - pos) : text; + builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, + spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes); + } + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break} + pos = end; + spanStartStyle = ""; + } + text = allText.slice(at, at = styles[i++]); + style = interpretTokenStyle(styles[i++], builder.cm.options); + } + } + } + + + // These objects are used to represent the visible (currently drawn) + // part of the document. A LineView may correspond to multiple + // logical lines, if those are connected by collapsed ranges. + function LineView(doc, line, lineN) { + // The starting line + this.line = line; + // Continuing lines, if any + this.rest = visualLineContinued(line); + // Number of logical lines in this visual line + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; + this.node = this.text = null; + this.hidden = lineIsHidden(doc, line); + } + + // Create a range of LineView objects for the given lines. + function buildViewArray(cm, from, to) { + var array = [], nextPos; + for (var pos = from; pos < to; pos = nextPos) { + var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); + nextPos = pos + view.size; + array.push(view); + } + return array + } + + var operationGroup = null; + + function pushOperation(op) { + if (operationGroup) { + operationGroup.ops.push(op); + } else { + op.ownsGroup = operationGroup = { + ops: [op], + delayedCallbacks: [] + }; + } + } + + function fireCallbacksForOps(group) { + // Calls delayed callbacks and cursorActivity handlers until no + // new ones appear + var callbacks = group.delayedCallbacks, i = 0; + do { + for (; i < callbacks.length; i++) + { callbacks[i].call(null); } + for (var j = 0; j < group.ops.length; j++) { + var op = group.ops[j]; + if (op.cursorActivityHandlers) + { while (op.cursorActivityCalled < op.cursorActivityHandlers.length) + { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } } + } + } while (i < callbacks.length) + } + + function finishOperation(op, endCb) { + var group = op.ownsGroup; + if (!group) { return } + + try { fireCallbacksForOps(group); } + finally { + operationGroup = null; + endCb(group); + } + } + + var orphanDelayedCallbacks = null; + + // Often, we want to signal events at a point where we are in the + // middle of some work, but don't want the handler to start calling + // other methods on the editor, which might be in an inconsistent + // state or simply not expect any other events to happen. + // signalLater looks whether there are any handlers, and schedules + // them to be executed when the last operation ends, or, if no + // operation is active, when a timeout fires. + function signalLater(emitter, type /*, values...*/) { + var arr = getHandlers(emitter, type); + if (!arr.length) { return } + var args = Array.prototype.slice.call(arguments, 2), list; + if (operationGroup) { + list = operationGroup.delayedCallbacks; + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks; + } else { + list = orphanDelayedCallbacks = []; + setTimeout(fireOrphanDelayed, 0); + } + var loop = function ( i ) { + list.push(function () { return arr[i].apply(null, args); }); + }; + + for (var i = 0; i < arr.length; ++i) + loop( i ); + } + + function fireOrphanDelayed() { + var delayed = orphanDelayedCallbacks; + orphanDelayedCallbacks = null; + for (var i = 0; i < delayed.length; ++i) { delayed[i](); } + } + + // When an aspect of a line changes, a string is added to + // lineView.changes. This updates the relevant part of the line's + // DOM structure. + function updateLineForChanges(cm, lineView, lineN, dims) { + for (var j = 0; j < lineView.changes.length; j++) { + var type = lineView.changes[j]; + if (type == "text") { updateLineText(cm, lineView); } + else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); } + else if (type == "class") { updateLineClasses(cm, lineView); } + else if (type == "widget") { updateLineWidgets(cm, lineView, dims); } + } + lineView.changes = null; + } + + // Lines with gutter elements, widgets or a background class need to + // be wrapped, and have the extra elements added to the wrapper div + function ensureLineWrapped(lineView) { + if (lineView.node == lineView.text) { + lineView.node = elt("div", null, null, "position: relative"); + if (lineView.text.parentNode) + { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); } + lineView.node.appendChild(lineView.text); + if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; } + } + return lineView.node + } + + function updateLineBackground(cm, lineView) { + var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; + if (cls) { cls += " CodeMirror-linebackground"; } + if (lineView.background) { + if (cls) { lineView.background.className = cls; } + else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } + } else if (cls) { + var wrap = ensureLineWrapped(lineView); + lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); + cm.display.input.setUneditable(lineView.background); + } + } + + // Wrapper around buildLineContent which will reuse the structure + // in display.externalMeasured when possible. + function getLineContent(cm, lineView) { + var ext = cm.display.externalMeasured; + if (ext && ext.line == lineView.line) { + cm.display.externalMeasured = null; + lineView.measure = ext.measure; + return ext.built + } + return buildLineContent(cm, lineView) + } + + // Redraw the line's text. Interacts with the background and text + // classes because the mode may output tokens that influence these + // classes. + function updateLineText(cm, lineView) { + var cls = lineView.text.className; + var built = getLineContent(cm, lineView); + if (lineView.text == lineView.node) { lineView.node = built.pre; } + lineView.text.parentNode.replaceChild(built.pre, lineView.text); + lineView.text = built.pre; + if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { + lineView.bgClass = built.bgClass; + lineView.textClass = built.textClass; + updateLineClasses(cm, lineView); + } else if (cls) { + lineView.text.className = cls; + } + } + + function updateLineClasses(cm, lineView) { + updateLineBackground(cm, lineView); + if (lineView.line.wrapClass) + { ensureLineWrapped(lineView).className = lineView.line.wrapClass; } + else if (lineView.node != lineView.text) + { lineView.node.className = ""; } + var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; + lineView.text.className = textClass || ""; + } + + function updateLineGutter(cm, lineView, lineN, dims) { + if (lineView.gutter) { + lineView.node.removeChild(lineView.gutter); + lineView.gutter = null; + } + if (lineView.gutterBackground) { + lineView.node.removeChild(lineView.gutterBackground); + lineView.gutterBackground = null; + } + if (lineView.line.gutterClass) { + var wrap = ensureLineWrapped(lineView); + lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, + ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px")); + cm.display.input.setUneditable(lineView.gutterBackground); + wrap.insertBefore(lineView.gutterBackground, lineView.text); + } + var markers = lineView.line.gutterMarkers; + if (cm.options.lineNumbers || markers) { + var wrap$1 = ensureLineWrapped(lineView); + var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px")); + gutterWrap.setAttribute("aria-hidden", "true"); + cm.display.input.setUneditable(gutterWrap); + wrap$1.insertBefore(gutterWrap, lineView.text); + if (lineView.line.gutterClass) + { gutterWrap.className += " " + lineView.line.gutterClass; } + if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) + { lineView.lineNumber = gutterWrap.appendChild( + elt("div", lineNumberFor(cm.options, lineN), + "CodeMirror-linenumber CodeMirror-gutter-elt", + ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); } + if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) { + var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id]; + if (found) + { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", + ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); } + } } + } + } + + function updateLineWidgets(cm, lineView, dims) { + if (lineView.alignable) { lineView.alignable = null; } + var isWidget = classTest("CodeMirror-linewidget"); + for (var node = lineView.node.firstChild, next = (void 0); node; node = next) { + next = node.nextSibling; + if (isWidget.test(node.className)) { lineView.node.removeChild(node); } + } + insertLineWidgets(cm, lineView, dims); + } + + // Build a line's DOM representation from scratch + function buildLineElement(cm, lineView, lineN, dims) { + var built = getLineContent(cm, lineView); + lineView.text = lineView.node = built.pre; + if (built.bgClass) { lineView.bgClass = built.bgClass; } + if (built.textClass) { lineView.textClass = built.textClass; } + + updateLineClasses(cm, lineView); + updateLineGutter(cm, lineView, lineN, dims); + insertLineWidgets(cm, lineView, dims); + return lineView.node + } + + // A lineView may contain multiple logical lines (when merged by + // collapsed spans). The widgets for all of them need to be drawn. + function insertLineWidgets(cm, lineView, dims) { + insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); + if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) + { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } } + } + + function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { + if (!line.widgets) { return } + var wrap = ensureLineWrapped(lineView); + for (var i = 0, ws = line.widgets; i < ws.length; ++i) { + var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : "")); + if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); } + positionLineWidget(widget, node, lineView, dims); + cm.display.input.setUneditable(node); + if (allowAbove && widget.above) + { wrap.insertBefore(node, lineView.gutter || lineView.text); } + else + { wrap.appendChild(node); } + signalLater(widget, "redraw"); + } + } + + function positionLineWidget(widget, node, lineView, dims) { + if (widget.noHScroll) { + (lineView.alignable || (lineView.alignable = [])).push(node); + var width = dims.wrapperWidth; + node.style.left = dims.fixedPos + "px"; + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth; + node.style.paddingLeft = dims.gutterTotalWidth + "px"; + } + node.style.width = width + "px"; + } + if (widget.coverGutter) { + node.style.zIndex = 5; + node.style.position = "relative"; + if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; } + } + } + + function widgetHeight(widget) { + if (widget.height != null) { return widget.height } + var cm = widget.doc.cm; + if (!cm) { return 0 } + if (!contains(document.body, widget.node)) { + var parentStyle = "position: relative;"; + if (widget.coverGutter) + { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; } + if (widget.noHScroll) + { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; } + removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); + } + return widget.height = widget.node.parentNode.offsetHeight + } + + // Return true when the given mouse event happened in a widget + function eventInWidget(display, e) { + for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { + if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || + (n.parentNode == display.sizer && n != display.mover)) + { return true } + } + } + + // POSITION MEASUREMENT + + function paddingTop(display) {return display.lineSpace.offsetTop} + function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight} + function paddingH(display) { + if (display.cachedPaddingH) { return display.cachedPaddingH } + var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like")); + var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; + var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; + if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; } + return data + } + + function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth } + function displayWidth(cm) { + return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth + } + function displayHeight(cm) { + return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight + } + + // Ensure the lineView.wrapping.heights array is populated. This is + // an array of bottom offsets for the lines that make up a drawn + // line. When lineWrapping is on, there might be more than one + // height. + function ensureLineHeights(cm, lineView, rect) { + var wrapping = cm.options.lineWrapping; + var curWidth = wrapping && displayWidth(cm); + if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { + var heights = lineView.measure.heights = []; + if (wrapping) { + lineView.measure.width = curWidth; + var rects = lineView.text.firstChild.getClientRects(); + for (var i = 0; i < rects.length - 1; i++) { + var cur = rects[i], next = rects[i + 1]; + if (Math.abs(cur.bottom - next.bottom) > 2) + { heights.push((cur.bottom + next.top) / 2 - rect.top); } + } + } + heights.push(rect.bottom - rect.top); + } + } + + // Find a line map (mapping character offsets to text nodes) and a + // measurement cache for the given line number. (A line view might + // contain multiple lines when collapsed ranges are present.) + function mapFromLineView(lineView, line, lineN) { + if (lineView.line == line) + { return {map: lineView.measure.map, cache: lineView.measure.cache} } + if (lineView.rest) { + for (var i = 0; i < lineView.rest.length; i++) + { if (lineView.rest[i] == line) + { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } } + for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) + { if (lineNo(lineView.rest[i$1]) > lineN) + { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } } + } + } + + // Render a line into the hidden node display.externalMeasured. Used + // when measurement is needed for a line that's not in the viewport. + function updateExternalMeasurement(cm, line) { + line = visualLine(line); + var lineN = lineNo(line); + var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); + view.lineN = lineN; + var built = view.built = buildLineContent(cm, view); + view.text = built.pre; + removeChildrenAndAdd(cm.display.lineMeasure, built.pre); + return view + } + + // Get a {top, bottom, left, right} box (in line-local coordinates) + // for a given character. + function measureChar(cm, line, ch, bias) { + return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias) + } + + // Find a line view that corresponds to the given line number. + function findViewForLine(cm, lineN) { + if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) + { return cm.display.view[findViewIndex(cm, lineN)] } + var ext = cm.display.externalMeasured; + if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) + { return ext } + } + + // Measurement can be split in two steps, the set-up work that + // applies to the whole line, and the measurement of the actual + // character. Functions like coordsChar, that need to do a lot of + // measurements in a row, can thus ensure that the set-up work is + // only done once. + function prepareMeasureForLine(cm, line) { + var lineN = lineNo(line); + var view = findViewForLine(cm, lineN); + if (view && !view.text) { + view = null; + } else if (view && view.changes) { + updateLineForChanges(cm, view, lineN, getDimensions(cm)); + cm.curOp.forceUpdate = true; + } + if (!view) + { view = updateExternalMeasurement(cm, line); } + + var info = mapFromLineView(view, line, lineN); + return { + line: line, view: view, rect: null, + map: info.map, cache: info.cache, before: info.before, + hasHeights: false + } + } + + // Given a prepared measurement object, measures the position of an + // actual character (or fetches it from the cache). + function measureCharPrepared(cm, prepared, ch, bias, varHeight) { + if (prepared.before) { ch = -1; } + var key = ch + (bias || ""), found; + if (prepared.cache.hasOwnProperty(key)) { + found = prepared.cache[key]; + } else { + if (!prepared.rect) + { prepared.rect = prepared.view.text.getBoundingClientRect(); } + if (!prepared.hasHeights) { + ensureLineHeights(cm, prepared.view, prepared.rect); + prepared.hasHeights = true; + } + found = measureCharInner(cm, prepared, ch, bias); + if (!found.bogus) { prepared.cache[key] = found; } + } + return {left: found.left, right: found.right, + top: varHeight ? found.rtop : found.top, + bottom: varHeight ? found.rbottom : found.bottom} + } + + var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; + + function nodeAndOffsetInLineMap(map, ch, bias) { + var node, start, end, collapse, mStart, mEnd; + // First, search the line map for the text node corresponding to, + // or closest to, the target character. + for (var i = 0; i < map.length; i += 3) { + mStart = map[i]; + mEnd = map[i + 1]; + if (ch < mStart) { + start = 0; end = 1; + collapse = "left"; + } else if (ch < mEnd) { + start = ch - mStart; + end = start + 1; + } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { + end = mEnd - mStart; + start = end - 1; + if (ch >= mEnd) { collapse = "right"; } + } + if (start != null) { + node = map[i + 2]; + if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) + { collapse = bias; } + if (bias == "left" && start == 0) + { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { + node = map[(i -= 3) + 2]; + collapse = "left"; + } } + if (bias == "right" && start == mEnd - mStart) + { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { + node = map[(i += 3) + 2]; + collapse = "right"; + } } + break + } + } + return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd} + } + + function getUsefulRect(rects, bias) { + var rect = nullRect; + if (bias == "left") { for (var i = 0; i < rects.length; i++) { + if ((rect = rects[i]).left != rect.right) { break } + } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) { + if ((rect = rects[i$1]).left != rect.right) { break } + } } + return rect + } + + function measureCharInner(cm, prepared, ch, bias) { + var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); + var node = place.node, start = place.start, end = place.end, collapse = place.collapse; + + var rect; + if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. + for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned + while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; } + while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; } + if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) + { rect = node.parentNode.getBoundingClientRect(); } + else + { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); } + if (rect.left || rect.right || start == 0) { break } + end = start; + start = start - 1; + collapse = "right"; + } + if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); } + } else { // If it is a widget, simply get the box for the whole widget. + if (start > 0) { collapse = bias = "right"; } + var rects; + if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) + { rect = rects[bias == "right" ? rects.length - 1 : 0]; } + else + { rect = node.getBoundingClientRect(); } + } + if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { + var rSpan = node.parentNode.getClientRects()[0]; + if (rSpan) + { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; } + else + { rect = nullRect; } + } + + var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; + var mid = (rtop + rbot) / 2; + var heights = prepared.view.measure.heights; + var i = 0; + for (; i < heights.length - 1; i++) + { if (mid < heights[i]) { break } } + var top = i ? heights[i - 1] : 0, bot = heights[i]; + var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, + right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, + top: top, bottom: bot}; + if (!rect.left && !rect.right) { result.bogus = true; } + if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } + + return result + } + + // Work around problem with bounding client rects on ranges being + // returned incorrectly when zoomed on IE10 and below. + function maybeUpdateRectForZooming(measure, rect) { + if (!window.screen || screen.logicalXDPI == null || + screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) + { return rect } + var scaleX = screen.logicalXDPI / screen.deviceXDPI; + var scaleY = screen.logicalYDPI / screen.deviceYDPI; + return {left: rect.left * scaleX, right: rect.right * scaleX, + top: rect.top * scaleY, bottom: rect.bottom * scaleY} + } + + function clearLineMeasurementCacheFor(lineView) { + if (lineView.measure) { + lineView.measure.cache = {}; + lineView.measure.heights = null; + if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) + { lineView.measure.caches[i] = {}; } } + } + } + + function clearLineMeasurementCache(cm) { + cm.display.externalMeasure = null; + removeChildren(cm.display.lineMeasure); + for (var i = 0; i < cm.display.view.length; i++) + { clearLineMeasurementCacheFor(cm.display.view[i]); } + } + + function clearCaches(cm) { + clearLineMeasurementCache(cm); + cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; + if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; } + cm.display.lineNumChars = null; + } + + function pageScrollX() { + // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206 + // which causes page_Offset and bounding client rects to use + // different reference viewports and invalidate our calculations. + if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) } + return window.pageXOffset || (document.documentElement || document.body).scrollLeft + } + function pageScrollY() { + if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) } + return window.pageYOffset || (document.documentElement || document.body).scrollTop + } + + function widgetTopHeight(lineObj) { + var ref = visualLine(lineObj); + var widgets = ref.widgets; + var height = 0; + if (widgets) { for (var i = 0; i < widgets.length; ++i) { if (widgets[i].above) + { height += widgetHeight(widgets[i]); } } } + return height + } + + // Converts a {top, bottom, left, right} box from line-local + // coordinates into another coordinate system. Context may be one of + // "line", "div" (display.lineDiv), "local"./null (editor), "window", + // or "page". + function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { + if (!includeWidgets) { + var height = widgetTopHeight(lineObj); + rect.top += height; rect.bottom += height; + } + if (context == "line") { return rect } + if (!context) { context = "local"; } + var yOff = heightAtLine(lineObj); + if (context == "local") { yOff += paddingTop(cm.display); } + else { yOff -= cm.display.viewOffset; } + if (context == "page" || context == "window") { + var lOff = cm.display.lineSpace.getBoundingClientRect(); + yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); + var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); + rect.left += xOff; rect.right += xOff; + } + rect.top += yOff; rect.bottom += yOff; + return rect + } + + // Coverts a box from "div" coords to another coordinate system. + // Context may be "window", "page", "div", or "local"./null. + function fromCoordSystem(cm, coords, context) { + if (context == "div") { return coords } + var left = coords.left, top = coords.top; + // First move into "page" coordinate system + if (context == "page") { + left -= pageScrollX(); + top -= pageScrollY(); + } else if (context == "local" || !context) { + var localBox = cm.display.sizer.getBoundingClientRect(); + left += localBox.left; + top += localBox.top; + } + + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); + return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} + } + + function charCoords(cm, pos, context, lineObj, bias) { + if (!lineObj) { lineObj = getLine(cm.doc, pos.line); } + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context) + } + + // Returns a box for a given cursor position, which may have an + // 'other' property containing the position of the secondary cursor + // on a bidi boundary. + // A cursor Pos(line, char, "before") is on the same visual line as `char - 1` + // and after `char - 1` in writing order of `char - 1` + // A cursor Pos(line, char, "after") is on the same visual line as `char` + // and before `char` in writing order of `char` + // Examples (upper-case letters are RTL, lower-case are LTR): + // Pos(0, 1, ...) + // before after + // ab a|b a|b + // aB a|B aB| + // Ab |Ab A|b + // AB B|A B|A + // Every position after the last character on a line is considered to stick + // to the last character on the line. + function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { + lineObj = lineObj || getLine(cm.doc, pos.line); + if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } + function get(ch, right) { + var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); + if (right) { m.left = m.right; } else { m.right = m.left; } + return intoCoordSystem(cm, lineObj, m, context) + } + var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky; + if (ch >= lineObj.text.length) { + ch = lineObj.text.length; + sticky = "before"; + } else if (ch <= 0) { + ch = 0; + sticky = "after"; + } + if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") } + + function getBidi(ch, partPos, invert) { + var part = order[partPos], right = part.level == 1; + return get(invert ? ch - 1 : ch, right != invert) + } + var partPos = getBidiPartAt(order, ch, sticky); + var other = bidiOther; + var val = getBidi(ch, partPos, sticky == "before"); + if (other != null) { val.other = getBidi(ch, other, sticky != "before"); } + return val + } + + // Used to cheaply estimate the coordinates for a position. Used for + // intermediate scroll updates. + function estimateCoords(cm, pos) { + var left = 0; + pos = clipPos(cm.doc, pos); + if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; } + var lineObj = getLine(cm.doc, pos.line); + var top = heightAtLine(lineObj) + paddingTop(cm.display); + return {left: left, right: left, top: top, bottom: top + lineObj.height} + } + + // Positions returned by coordsChar contain some extra information. + // xRel is the relative x position of the input coordinates compared + // to the found position (so xRel > 0 means the coordinates are to + // the right of the character position, for example). When outside + // is true, that means the coordinates lie outside the line's + // vertical range. + function PosWithInfo(line, ch, sticky, outside, xRel) { + var pos = Pos(line, ch, sticky); + pos.xRel = xRel; + if (outside) { pos.outside = outside; } + return pos + } + + // Compute the character position closest to the given coordinates. + // Input must be lineSpace-local ("div" coordinate system). + function coordsChar(cm, x, y) { + var doc = cm.doc; + y += cm.display.viewOffset; + if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) } + var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; + if (lineN > last) + { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) } + if (x < 0) { x = 0; } + + var lineObj = getLine(doc, lineN); + for (;;) { + var found = coordsCharInner(cm, lineObj, lineN, x, y); + var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0)); + if (!collapsed) { return found } + var rangeEnd = collapsed.find(1); + if (rangeEnd.line == lineN) { return rangeEnd } + lineObj = getLine(doc, lineN = rangeEnd.line); + } + } + + function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { + y -= widgetTopHeight(lineObj); + var end = lineObj.text.length; + var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0); + end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end); + return {begin: begin, end: end} + } + + function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { + if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } + var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; + return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop) + } + + // Returns true if the given side of a box is after the given + // coordinates, in top-to-bottom, left-to-right order. + function boxIsAfter(box, x, y, left) { + return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x + } + + function coordsCharInner(cm, lineObj, lineNo, x, y) { + // Move y into line-local coordinate space + y -= heightAtLine(lineObj); + var preparedMeasure = prepareMeasureForLine(cm, lineObj); + // When directly calling `measureCharPrepared`, we have to adjust + // for the widgets at this line. + var widgetHeight = widgetTopHeight(lineObj); + var begin = 0, end = lineObj.text.length, ltr = true; + + var order = getOrder(lineObj, cm.doc.direction); + // If the line isn't plain left-to-right text, first figure out + // which bidi section the coordinates fall into. + if (order) { + var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart) + (cm, lineObj, lineNo, preparedMeasure, order, x, y); + ltr = part.level != 1; + // The awkward -1 offsets are needed because findFirst (called + // on these below) will treat its first bound as inclusive, + // second as exclusive, but we want to actually address the + // characters in the part's range + begin = ltr ? part.from : part.to - 1; + end = ltr ? part.to : part.from - 1; + } + + // A binary search to find the first character whose bounding box + // starts after the coordinates. If we run across any whose box wrap + // the coordinates, store that. + var chAround = null, boxAround = null; + var ch = findFirst(function (ch) { + var box = measureCharPrepared(cm, preparedMeasure, ch); + box.top += widgetHeight; box.bottom += widgetHeight; + if (!boxIsAfter(box, x, y, false)) { return false } + if (box.top <= y && box.left <= x) { + chAround = ch; + boxAround = box; + } + return true + }, begin, end); + + var baseX, sticky, outside = false; + // If a box around the coordinates was found, use that + if (boxAround) { + // Distinguish coordinates nearer to the left or right side of the box + var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr; + ch = chAround + (atStart ? 0 : 1); + sticky = atStart ? "after" : "before"; + baseX = atLeft ? boxAround.left : boxAround.right; + } else { + // (Adjust for extended bound, if necessary.) + if (!ltr && (ch == end || ch == begin)) { ch++; } + // To determine which side to associate with, get the box to the + // left of the character and compare it's vertical position to the + // coordinates + sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : + (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ? + "after" : "before"; + // Now get accurate coordinates for this place, in order to get a + // base X position + var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure); + baseX = coords.left; + outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0; + } + + ch = skipExtendingChars(lineObj.text, ch, 1); + return PosWithInfo(lineNo, ch, sticky, outside, x - baseX) + } + + function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) { + // Bidi parts are sorted left-to-right, and in a non-line-wrapping + // situation, we can take this ordering to correspond to the visual + // ordering. This finds the first part whose end is after the given + // coordinates. + var index = findFirst(function (i) { + var part = order[i], ltr = part.level != 1; + return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"), + "line", lineObj, preparedMeasure), x, y, true) + }, 0, order.length - 1); + var part = order[index]; + // If this isn't the first part, the part's start is also after + // the coordinates, and the coordinates aren't on the same line as + // that start, move one part back. + if (index > 0) { + var ltr = part.level != 1; + var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"), + "line", lineObj, preparedMeasure); + if (boxIsAfter(start, x, y, true) && start.top > y) + { part = order[index - 1]; } + } + return part + } + + function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { + // In a wrapped line, rtl text on wrapping boundaries can do things + // that don't correspond to the ordering in our `order` array at + // all, so a binary search doesn't work, and we want to return a + // part that only spans one line so that the binary search in + // coordsCharInner is safe. As such, we first find the extent of the + // wrapped line, and then do a flat search in which we discard any + // spans that aren't on the line. + var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); + var begin = ref.begin; + var end = ref.end; + if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; } + var part = null, closestDist = null; + for (var i = 0; i < order.length; i++) { + var p = order[i]; + if (p.from >= end || p.to <= begin) { continue } + var ltr = p.level != 1; + var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right; + // Weigh against spans ending before this, so that they are only + // picked if nothing ends after + var dist = endX < x ? x - endX + 1e9 : endX - x; + if (!part || closestDist > dist) { + part = p; + closestDist = dist; + } + } + if (!part) { part = order[order.length - 1]; } + // Clip the part to the wrapped line. + if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; } + if (part.to > end) { part = {from: part.from, to: end, level: part.level}; } + return part + } + + var measureText; + // Compute the default text height. + function textHeight(display) { + if (display.cachedTextHeight != null) { return display.cachedTextHeight } + if (measureText == null) { + measureText = elt("pre", null, "CodeMirror-line-like"); + // Measure a bunch of lines, for browsers that compute + // fractional heights. + for (var i = 0; i < 49; ++i) { + measureText.appendChild(document.createTextNode("x")); + measureText.appendChild(elt("br")); + } + measureText.appendChild(document.createTextNode("x")); + } + removeChildrenAndAdd(display.measure, measureText); + var height = measureText.offsetHeight / 50; + if (height > 3) { display.cachedTextHeight = height; } + removeChildren(display.measure); + return height || 1 + } + + // Compute the default character width. + function charWidth(display) { + if (display.cachedCharWidth != null) { return display.cachedCharWidth } + var anchor = elt("span", "xxxxxxxxxx"); + var pre = elt("pre", [anchor], "CodeMirror-line-like"); + removeChildrenAndAdd(display.measure, pre); + var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; + if (width > 2) { display.cachedCharWidth = width; } + return width || 10 + } + + // Do a bulk-read of the DOM positions and sizes needed to draw the + // view, so that we don't interleave reading and writing to the DOM. + function getDimensions(cm) { + var d = cm.display, left = {}, width = {}; + var gutterLeft = d.gutters.clientLeft; + for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { + var id = cm.display.gutterSpecs[i].className; + left[id] = n.offsetLeft + n.clientLeft + gutterLeft; + width[id] = n.clientWidth; + } + return {fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth} + } + + // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, + // but using getBoundingClientRect to get a sub-pixel-accurate + // result. + function compensateForHScroll(display) { + return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left + } + + // Returns a function that estimates the height of a line, to use as + // first approximation until the line becomes visible (and is thus + // properly measurable). + function estimateHeight(cm) { + var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; + var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); + return function (line) { + if (lineIsHidden(cm.doc, line)) { return 0 } + + var widgetsHeight = 0; + if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { + if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; } + } } + + if (wrapping) + { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th } + else + { return widgetsHeight + th } + } + } + + function estimateLineHeights(cm) { + var doc = cm.doc, est = estimateHeight(cm); + doc.iter(function (line) { + var estHeight = est(line); + if (estHeight != line.height) { updateLineHeight(line, estHeight); } + }); + } + + // Given a mouse event, find the corresponding position. If liberal + // is false, it checks whether a gutter or scrollbar was clicked, + // and returns null if it was. forRect is used by rectangular + // selections, and tries to estimate a character position even for + // coordinates beyond the right of the text. + function posFromMouse(cm, e, liberal, forRect) { + var display = cm.display; + if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null } + + var x, y, space = display.lineSpace.getBoundingClientRect(); + // Fails unpredictably on IE[67] when mouse is dragged around quickly. + try { x = e.clientX - space.left; y = e.clientY - space.top; } + catch (e$1) { return null } + var coords = coordsChar(cm, x, y), line; + if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { + var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; + coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); + } + return coords + } + + // Find the view element corresponding to a given line. Return null + // when the line isn't visible. + function findViewIndex(cm, n) { + if (n >= cm.display.viewTo) { return null } + n -= cm.display.viewFrom; + if (n < 0) { return null } + var view = cm.display.view; + for (var i = 0; i < view.length; i++) { + n -= view[i].size; + if (n < 0) { return i } + } + } + + // Updates the display.view data structure for a given change to the + // document. From and to are in pre-change coordinates. Lendiff is + // the amount of lines added or subtracted by the change. This is + // used for changes that span multiple lines, or change the way + // lines are divided into visual lines. regLineChange (below) + // registers single-line changes. + function regChange(cm, from, to, lendiff) { + if (from == null) { from = cm.doc.first; } + if (to == null) { to = cm.doc.first + cm.doc.size; } + if (!lendiff) { lendiff = 0; } + + var display = cm.display; + if (lendiff && to < display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers > from)) + { display.updateLineNumbers = from; } + + cm.curOp.viewChanged = true; + + if (from >= display.viewTo) { // Change after + if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) + { resetView(cm); } + } else if (to <= display.viewFrom) { // Change before + if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { + resetView(cm); + } else { + display.viewFrom += lendiff; + display.viewTo += lendiff; + } + } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap + resetView(cm); + } else if (from <= display.viewFrom) { // Top overlap + var cut = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cut) { + display.view = display.view.slice(cut.index); + display.viewFrom = cut.lineN; + display.viewTo += lendiff; + } else { + resetView(cm); + } + } else if (to >= display.viewTo) { // Bottom overlap + var cut$1 = viewCuttingPoint(cm, from, from, -1); + if (cut$1) { + display.view = display.view.slice(0, cut$1.index); + display.viewTo = cut$1.lineN; + } else { + resetView(cm); + } + } else { // Gap in the middle + var cutTop = viewCuttingPoint(cm, from, from, -1); + var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cutTop && cutBot) { + display.view = display.view.slice(0, cutTop.index) + .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) + .concat(display.view.slice(cutBot.index)); + display.viewTo += lendiff; + } else { + resetView(cm); + } + } + + var ext = display.externalMeasured; + if (ext) { + if (to < ext.lineN) + { ext.lineN += lendiff; } + else if (from < ext.lineN + ext.size) + { display.externalMeasured = null; } + } + } + + // Register a change to a single line. Type must be one of "text", + // "gutter", "class", "widget" + function regLineChange(cm, line, type) { + cm.curOp.viewChanged = true; + var display = cm.display, ext = cm.display.externalMeasured; + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) + { display.externalMeasured = null; } + + if (line < display.viewFrom || line >= display.viewTo) { return } + var lineView = display.view[findViewIndex(cm, line)]; + if (lineView.node == null) { return } + var arr = lineView.changes || (lineView.changes = []); + if (indexOf(arr, type) == -1) { arr.push(type); } + } + + // Clear the view. + function resetView(cm) { + cm.display.viewFrom = cm.display.viewTo = cm.doc.first; + cm.display.view = []; + cm.display.viewOffset = 0; + } + + function viewCuttingPoint(cm, oldN, newN, dir) { + var index = findViewIndex(cm, oldN), diff, view = cm.display.view; + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) + { return {index: index, lineN: newN} } + var n = cm.display.viewFrom; + for (var i = 0; i < index; i++) + { n += view[i].size; } + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) { return null } + diff = (n + view[index].size) - oldN; + index++; + } else { + diff = n - oldN; + } + oldN += diff; newN += diff; + } + while (visualLineNo(cm.doc, newN) != newN) { + if (index == (dir < 0 ? 0 : view.length - 1)) { return null } + newN += dir * view[index - (dir < 0 ? 1 : 0)].size; + index += dir; + } + return {index: index, lineN: newN} + } + + // Force the view to cover a given range, adding empty view element + // or clipping off existing ones as needed. + function adjustView(cm, from, to) { + var display = cm.display, view = display.view; + if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { + display.view = buildViewArray(cm, from, to); + display.viewFrom = from; + } else { + if (display.viewFrom > from) + { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); } + else if (display.viewFrom < from) + { display.view = display.view.slice(findViewIndex(cm, from)); } + display.viewFrom = from; + if (display.viewTo < to) + { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); } + else if (display.viewTo > to) + { display.view = display.view.slice(0, findViewIndex(cm, to)); } + } + display.viewTo = to; + } + + // Count the number of lines in the view whose DOM representation is + // out of date (or nonexistent). + function countDirtyView(cm) { + var view = cm.display.view, dirty = 0; + for (var i = 0; i < view.length; i++) { + var lineView = view[i]; + if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; } + } + return dirty + } + + function updateSelection(cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()); + } + + function prepareSelection(cm, primary) { + if ( primary === void 0 ) primary = true; + + var doc = cm.doc, result = {}; + var curFragment = result.cursors = document.createDocumentFragment(); + var selFragment = result.selection = document.createDocumentFragment(); + + var customCursor = cm.options.$customCursor; + if (customCursor) { primary = true; } + for (var i = 0; i < doc.sel.ranges.length; i++) { + if (!primary && i == doc.sel.primIndex) { continue } + var range = doc.sel.ranges[i]; + if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue } + var collapsed = range.empty(); + if (customCursor) { + var head = customCursor(cm, range); + if (head) { drawSelectionCursor(cm, head, curFragment); } + } else if (collapsed || cm.options.showCursorWhenSelecting) { + drawSelectionCursor(cm, range.head, curFragment); + } + if (!collapsed) + { drawSelectionRange(cm, range, selFragment); } + } + return result + } + + // Draws a cursor for the given range + function drawSelectionCursor(cm, head, output) { + var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); + + var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); + cursor.style.left = pos.left + "px"; + cursor.style.top = (pos.top+5) + "px"; + cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; + + if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) { + var charPos = charCoords(cm, head, "div", null, null); + var width = charPos.right - charPos.left; + cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px"; + } + + if (pos.other) { + // Secondary cursor, shown when on a 'jump' in bi-directional text + var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); + otherCursor.style.display = ""; + otherCursor.style.left = pos.other.left + "px"; + otherCursor.style.top = pos.other.top + "px"; + otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; + } + } + + function cmpCoords(a, b) { return a.top - b.top || a.left - b.left } + + // Draws the given range as a highlighted selection + function drawSelectionRange(cm, range, output) { + var display = cm.display, doc = cm.doc; + var fragment = document.createDocumentFragment(); + var padding = paddingH(cm.display), leftSide = padding.left; + var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; + var docLTR = doc.direction == "ltr"; + + function add(left, top, width, bottom) { + if (top < 0) { top = 0; } + top = Math.round(top); + bottom = Math.round(bottom); + fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px"))); + } + + function drawForLine(line, fromArg, toArg) { + var lineObj = getLine(doc, line); + var lineLen = lineObj.text.length; + var start, end; + function coords(ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias) + } + + function wrapX(pos, dir, side) { + var extent = wrappedLineExtentChar(cm, lineObj, null, pos); + var prop = (dir == "ltr") == (side == "after") ? "left" : "right"; + var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1); + return coords(ch, prop)[prop] + } + + var order = getOrder(lineObj, doc.direction); + iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) { + var ltr = dir == "ltr"; + var fromPos = coords(from, ltr ? "left" : "right"); + var toPos = coords(to - 1, ltr ? "right" : "left"); + + var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen; + var first = i == 0, last = !order || i == order.length - 1; + if (toPos.top - fromPos.top <= 3) { // Single line + var openLeft = (docLTR ? openStart : openEnd) && first; + var openRight = (docLTR ? openEnd : openStart) && last; + var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left; + var right = openRight ? rightSide : (ltr ? toPos : fromPos).right; + add(left, fromPos.top, right - left, fromPos.bottom); + } else { // Multiple lines + var topLeft, topRight, botLeft, botRight; + if (ltr) { + topLeft = docLTR && openStart && first ? leftSide : fromPos.left; + topRight = docLTR ? rightSide : wrapX(from, dir, "before"); + botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); + botRight = docLTR && openEnd && last ? rightSide : toPos.right; + } else { + topLeft = !docLTR ? leftSide : wrapX(from, dir, "before"); + topRight = !docLTR && openStart && first ? rightSide : fromPos.right; + botLeft = !docLTR && openEnd && last ? leftSide : toPos.left; + botRight = !docLTR ? rightSide : wrapX(to, dir, "after"); + } + add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom); + if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); } + add(botLeft, toPos.top, botRight - botLeft, toPos.bottom); + } + + if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; } + if (cmpCoords(toPos, start) < 0) { start = toPos; } + if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; } + if (cmpCoords(toPos, end) < 0) { end = toPos; } + }); + return {start: start, end: end} + } + + var sFrom = range.from(), sTo = range.to(); + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch); + } else { + var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); + var singleVLine = visualLine(fromLine) == visualLine(toLine); + var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; + var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); + add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); + } + } + if (leftEnd.bottom < rightStart.top) + { add(leftSide, leftEnd.bottom, null, rightStart.top); } + } + + output.appendChild(fragment); + } + + // Cursor-blinking + function restartBlink(cm) { + if (!cm.state.focused) { return } + var display = cm.display; + clearInterval(display.blinker); + var on = true; + display.cursorDiv.style.visibility = ""; + if (cm.options.cursorBlinkRate > 0) + { display.blinker = setInterval(function () { + if (!cm.hasFocus()) { onBlur(cm); } + display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; + }, cm.options.cursorBlinkRate); } + else if (cm.options.cursorBlinkRate < 0) + { display.cursorDiv.style.visibility = "hidden"; } + } + + function ensureFocus(cm) { + if (!cm.hasFocus()) { + cm.display.input.focus(); + if (!cm.state.focused) { onFocus(cm); } + } + } + + function delayBlurEvent(cm) { + cm.state.delayingBlurEvent = true; + setTimeout(function () { if (cm.state.delayingBlurEvent) { + cm.state.delayingBlurEvent = false; + if (cm.state.focused) { onBlur(cm); } + } }, 100); + } + + function onFocus(cm, e) { + if (cm.state.delayingBlurEvent && !cm.state.draggingText) { cm.state.delayingBlurEvent = false; } + + if (cm.options.readOnly == "nocursor") { return } + if (!cm.state.focused) { + signal(cm, "focus", cm, e); + cm.state.focused = true; + addClass(cm.display.wrapper, "CodeMirror-focused"); + // This test prevents this from firing when a context + // menu is closed (since the input reset would kill the + // select-all detection hack) + if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { + cm.display.input.reset(); + if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730 + } + cm.display.input.receivedFocus(); + } + restartBlink(cm); + } + function onBlur(cm, e) { + if (cm.state.delayingBlurEvent) { return } + + if (cm.state.focused) { + signal(cm, "blur", cm, e); + cm.state.focused = false; + rmClass(cm.display.wrapper, "CodeMirror-focused"); + } + clearInterval(cm.display.blinker); + setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150); + } + + // Read the actual heights of the rendered lines, and update their + // stored heights to match. + function updateHeightsInViewport(cm) { + var display = cm.display; + var prevBottom = display.lineDiv.offsetTop; + var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top); + var oldHeight = display.lineDiv.getBoundingClientRect().top; + var mustScroll = 0; + for (var i = 0; i < display.view.length; i++) { + var cur = display.view[i], wrapping = cm.options.lineWrapping; + var height = (void 0), width = 0; + if (cur.hidden) { continue } + oldHeight += cur.line.height; + if (ie && ie_version < 8) { + var bot = cur.node.offsetTop + cur.node.offsetHeight; + height = bot - prevBottom; + prevBottom = bot; + } else { + var box = cur.node.getBoundingClientRect(); + height = box.bottom - box.top; + // Check that lines don't extend past the right of the current + // editor width + if (!wrapping && cur.text.firstChild) + { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; } + } + var diff = cur.line.height - height; + if (diff > .005 || diff < -.005) { + if (oldHeight < viewTop) { mustScroll -= diff; } + updateLineHeight(cur.line, height); + updateWidgetHeight(cur.line); + if (cur.rest) { for (var j = 0; j < cur.rest.length; j++) + { updateWidgetHeight(cur.rest[j]); } } + } + if (width > cm.display.sizerWidth) { + var chWidth = Math.ceil(width / charWidth(cm.display)); + if (chWidth > cm.display.maxLineLength) { + cm.display.maxLineLength = chWidth; + cm.display.maxLine = cur.line; + cm.display.maxLineChanged = true; + } + } + } + if (Math.abs(mustScroll) > 2) { display.scroller.scrollTop += mustScroll; } + } + + // Read and store the height of line widgets associated with the + // given line. + function updateWidgetHeight(line) { + if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) { + var w = line.widgets[i], parent = w.node.parentNode; + if (parent) { w.height = parent.offsetHeight; } + } } + } + + // Compute the lines that are visible in a given viewport (defaults + // the the current scroll position). viewport may contain top, + // height, and ensure (see op.scrollToPos) properties. + function visibleLines(display, doc, viewport) { + var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; + top = Math.floor(top - paddingTop(display)); + var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; + + var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); + // Ensure is a {from: {line, ch}, to: {line, ch}} object, and + // forces those lines into the viewport (if possible). + if (viewport && viewport.ensure) { + var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; + if (ensureFrom < from) { + from = ensureFrom; + to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); + } else if (Math.min(ensureTo, doc.lastLine()) >= to) { + from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); + to = ensureTo; + } + } + return {from: from, to: Math.max(to, from + 1)} + } + + // SCROLLING THINGS INTO VIEW + + // If an editor sits on the top or bottom of the window, partially + // scrolled out of view, this ensures that the cursor is visible. + function maybeScrollWindow(cm, rect) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) { return } + + var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; + if (rect.top + box.top < 0) { doScroll = true; } + else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; } + if (doScroll != null && !phantom) { + var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;")); + cm.display.lineSpace.appendChild(scrollNode); + scrollNode.scrollIntoView(doScroll); + cm.display.lineSpace.removeChild(scrollNode); + } + } + + // Scroll a given position into view (immediately), verifying that + // it actually became visible (as line heights are accurately + // measured, the position of something may 'drift' during drawing). + function scrollPosIntoView(cm, pos, end, margin) { + if (margin == null) { margin = 0; } + var rect; + if (!cm.options.lineWrapping && pos == end) { + // Set pos and end to the cursor positions around the character pos sticks to + // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch + // If pos == Pos(_, 0, "before"), pos and end are unchanged + end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos; + pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos; + } + for (var limit = 0; limit < 5; limit++) { + var changed = false; + var coords = cursorCoords(cm, pos); + var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); + rect = {left: Math.min(coords.left, endCoords.left), + top: Math.min(coords.top, endCoords.top) - margin, + right: Math.max(coords.left, endCoords.left), + bottom: Math.max(coords.bottom, endCoords.bottom) + margin}; + var scrollPos = calculateScrollPos(cm, rect); + var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; + if (scrollPos.scrollTop != null) { + updateScrollTop(cm, scrollPos.scrollTop); + if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; } + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; } + } + if (!changed) { break } + } + return rect + } + + // Scroll a given set of coordinates into view (immediately). + function scrollIntoView(cm, rect) { + var scrollPos = calculateScrollPos(cm, rect); + if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); } + if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); } + } + + // Calculate a new scroll position needed to scroll the given + // rectangle into view. Returns an object with scrollTop and + // scrollLeft properties. When these are undefined, the + // vertical/horizontal position does not need to be adjusted. + function calculateScrollPos(cm, rect) { + var display = cm.display, snapMargin = textHeight(cm.display); + if (rect.top < 0) { rect.top = 0; } + var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; + var screen = displayHeight(cm), result = {}; + if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; } + var docBottom = cm.doc.height + paddingVert(display); + var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin; + if (rect.top < screentop) { + result.scrollTop = atTop ? 0 : rect.top; + } else if (rect.bottom > screentop + screen) { + var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen); + if (newTop != screentop) { result.scrollTop = newTop; } + } + + var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth; + var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace; + var screenw = displayWidth(cm) - display.gutters.offsetWidth; + var tooWide = rect.right - rect.left > screenw; + if (tooWide) { rect.right = rect.left + screenw; } + if (rect.left < 10) + { result.scrollLeft = 0; } + else if (rect.left < screenleft) + { result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); } + else if (rect.right > screenw + screenleft - 3) + { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; } + return result + } + + // Store a relative adjustment to the scroll position in the current + // operation (to be applied when the operation finishes). + function addToScrollTop(cm, top) { + if (top == null) { return } + resolveScrollToPos(cm); + cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; + } + + // Make sure that at the end of the operation the current cursor is + // shown. + function ensureCursorVisible(cm) { + resolveScrollToPos(cm); + var cur = cm.getCursor(); + cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin}; + } + + function scrollToCoords(cm, x, y) { + if (x != null || y != null) { resolveScrollToPos(cm); } + if (x != null) { cm.curOp.scrollLeft = x; } + if (y != null) { cm.curOp.scrollTop = y; } + } + + function scrollToRange(cm, range) { + resolveScrollToPos(cm); + cm.curOp.scrollToPos = range; + } + + // When an operation has its scrollToPos property set, and another + // scroll action is applied before the end of the operation, this + // 'simulates' scrolling that position into view in a cheap way, so + // that the effect of intermediate scroll commands is not ignored. + function resolveScrollToPos(cm) { + var range = cm.curOp.scrollToPos; + if (range) { + cm.curOp.scrollToPos = null; + var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); + scrollToCoordsRange(cm, from, to, range.margin); + } + } + + function scrollToCoordsRange(cm, from, to, margin) { + var sPos = calculateScrollPos(cm, { + left: Math.min(from.left, to.left), + top: Math.min(from.top, to.top) - margin, + right: Math.max(from.right, to.right), + bottom: Math.max(from.bottom, to.bottom) + margin + }); + scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); + } + + // Sync the scrollable area and scrollbars, ensure the viewport + // covers the visible area. + function updateScrollTop(cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) { return } + if (!gecko) { updateDisplaySimple(cm, {top: val}); } + setScrollTop(cm, val, true); + if (gecko) { updateDisplaySimple(cm); } + startWorker(cm, 100); + } + + function setScrollTop(cm, val, forceScroll) { + val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)); + if (cm.display.scroller.scrollTop == val && !forceScroll) { return } + cm.doc.scrollTop = val; + cm.display.scrollbars.setScrollTop(val); + if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; } + } + + // Sync scroller and scrollbar, ensure the gutter elements are + // aligned. + function setScrollLeft(cm, val, isScroller, forceScroll) { + val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)); + if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return } + cm.doc.scrollLeft = val; + alignHorizontally(cm); + if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; } + cm.display.scrollbars.setScrollLeft(val); + } + + // SCROLLBARS + + // Prepare DOM reads needed to update the scrollbars. Done in one + // shot to minimize update/measure roundtrips. + function measureForScrollbars(cm) { + var d = cm.display, gutterW = d.gutters.offsetWidth; + var docH = Math.round(cm.doc.height + paddingVert(cm.display)); + return { + clientHeight: d.scroller.clientHeight, + viewHeight: d.wrapper.clientHeight, + scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, + viewWidth: d.wrapper.clientWidth, + barLeft: cm.options.fixedGutter ? gutterW : 0, + docHeight: docH, + scrollHeight: docH + scrollGap(cm) + d.barHeight, + nativeBarWidth: d.nativeBarWidth, + gutterWidth: gutterW + } + } + + var NativeScrollbars = function(place, scroll, cm) { + this.cm = cm; + var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); + var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); + vert.tabIndex = horiz.tabIndex = -1; + place(vert); place(horiz); + + on(vert, "scroll", function () { + if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); } + }); + on(horiz, "scroll", function () { + if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); } + }); + + this.checkedZeroWidth = false; + // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). + if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; } + }; + + NativeScrollbars.prototype.update = function (measure) { + var needsH = measure.scrollWidth > measure.clientWidth + 1; + var needsV = measure.scrollHeight > measure.clientHeight + 1; + var sWidth = measure.nativeBarWidth; + + if (needsV) { + this.vert.style.display = "block"; + this.vert.style.bottom = needsH ? sWidth + "px" : "0"; + var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); + // A bug in IE8 can cause this value to be negative, so guard it. + this.vert.firstChild.style.height = + Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; + } else { + this.vert.scrollTop = 0; + this.vert.style.display = ""; + this.vert.firstChild.style.height = "0"; + } + + if (needsH) { + this.horiz.style.display = "block"; + this.horiz.style.right = needsV ? sWidth + "px" : "0"; + this.horiz.style.left = measure.barLeft + "px"; + var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); + this.horiz.firstChild.style.width = + Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; + } else { + this.horiz.style.display = ""; + this.horiz.firstChild.style.width = "0"; + } + + if (!this.checkedZeroWidth && measure.clientHeight > 0) { + if (sWidth == 0) { this.zeroWidthHack(); } + this.checkedZeroWidth = true; + } + + return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} + }; + + NativeScrollbars.prototype.setScrollLeft = function (pos) { + if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; } + if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); } + }; + + NativeScrollbars.prototype.setScrollTop = function (pos) { + if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; } + if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); } + }; + + NativeScrollbars.prototype.zeroWidthHack = function () { + var w = mac && !mac_geMountainLion ? "12px" : "18px"; + this.horiz.style.height = this.vert.style.width = w; + this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; + this.disableHoriz = new Delayed; + this.disableVert = new Delayed; + }; + + NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { + bar.style.pointerEvents = "auto"; + function maybeDisable() { + // To find out whether the scrollbar is still visible, we + // check whether the element under the pixel in the bottom + // right corner of the scrollbar box is the scrollbar box + // itself (when the bar is still visible) or its filler child + // (when the bar is hidden). If it is still visible, we keep + // it enabled, if it's hidden, we disable pointer events. + var box = bar.getBoundingClientRect(); + var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) + : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); + if (elt != bar) { bar.style.pointerEvents = "none"; } + else { delay.set(1000, maybeDisable); } + } + delay.set(1000, maybeDisable); + }; + + NativeScrollbars.prototype.clear = function () { + var parent = this.horiz.parentNode; + parent.removeChild(this.horiz); + parent.removeChild(this.vert); + }; + + var NullScrollbars = function () {}; + + NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} }; + NullScrollbars.prototype.setScrollLeft = function () {}; + NullScrollbars.prototype.setScrollTop = function () {}; + NullScrollbars.prototype.clear = function () {}; + + function updateScrollbars(cm, measure) { + if (!measure) { measure = measureForScrollbars(cm); } + var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; + updateScrollbarsInner(cm, measure); + for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { + if (startWidth != cm.display.barWidth && cm.options.lineWrapping) + { updateHeightsInViewport(cm); } + updateScrollbarsInner(cm, measureForScrollbars(cm)); + startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; + } + } + + // Re-synchronize the fake scrollbars with the actual size of the + // content. + function updateScrollbarsInner(cm, measure) { + var d = cm.display; + var sizes = d.scrollbars.update(measure); + + d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; + d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; + d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; + + if (sizes.right && sizes.bottom) { + d.scrollbarFiller.style.display = "block"; + d.scrollbarFiller.style.height = sizes.bottom + "px"; + d.scrollbarFiller.style.width = sizes.right + "px"; + } else { d.scrollbarFiller.style.display = ""; } + if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { + d.gutterFiller.style.display = "block"; + d.gutterFiller.style.height = sizes.bottom + "px"; + d.gutterFiller.style.width = measure.gutterWidth + "px"; + } else { d.gutterFiller.style.display = ""; } + } + + var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; + + function initScrollbars(cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear(); + if (cm.display.scrollbars.addClass) + { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); } + } + + cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { + cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); + // Prevent clicks in the scrollbars from killing focus + on(node, "mousedown", function () { + if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); } + }); + node.setAttribute("cm-not-content", "true"); + }, function (pos, axis) { + if (axis == "horizontal") { setScrollLeft(cm, pos); } + else { updateScrollTop(cm, pos); } + }, cm); + if (cm.display.scrollbars.addClass) + { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); } + } + + // Operations are used to wrap a series of changes to the editor + // state in such a way that each change won't have to update the + // cursor and display (which would be awkward, slow, and + // error-prone). Instead, display updates are batched and then all + // combined and executed at once. + + var nextOpId = 0; + // Start a new operation. + function startOperation(cm) { + cm.curOp = { + cm: cm, + viewChanged: false, // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, // Used to detect need to update scrollbar + forceUpdate: false, // Used to force a redraw + updateInput: 0, // Whether to reset the input textarea + typing: false, // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, // Accumulated changes, for firing change events + cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already + selectionChanged: false, // Whether the selection needs to be redrawn + updateMaxLine: false, // Set when the widest line needs to be determined anew + scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, // Used to scroll to a specific position + focus: false, + id: ++nextOpId, // Unique ID + markArrays: null // Used by addMarkedSpan + }; + pushOperation(cm.curOp); + } + + // Finish an operation, updating the display and signalling delayed events + function endOperation(cm) { + var op = cm.curOp; + if (op) { finishOperation(op, function (group) { + for (var i = 0; i < group.ops.length; i++) + { group.ops[i].cm.curOp = null; } + endOperations(group); + }); } + } + + // The DOM updates done when an operation finishes are batched so + // that the minimum number of relayouts are required. + function endOperations(group) { + var ops = group.ops; + for (var i = 0; i < ops.length; i++) // Read DOM + { endOperation_R1(ops[i]); } + for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe) + { endOperation_W1(ops[i$1]); } + for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM + { endOperation_R2(ops[i$2]); } + for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe) + { endOperation_W2(ops[i$3]); } + for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM + { endOperation_finish(ops[i$4]); } + } + + function endOperation_R1(op) { + var cm = op.cm, display = cm.display; + maybeClipScrollbars(cm); + if (op.updateMaxLine) { findMaxLine(cm); } + + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || + op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || + op.scrollToPos.to.line >= display.viewTo) || + display.maxLineChanged && cm.options.lineWrapping; + op.update = op.mustUpdate && + new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); + } + + function endOperation_W1(op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); + } + + function endOperation_R2(op) { + var cm = op.cm, display = cm.display; + if (op.updatedDisplay) { updateHeightsInViewport(cm); } + + op.barMeasure = measureForScrollbars(cm); + + // If the max line changed since it was last measured, measure it, + // and ensure the document's width matches it. + // updateDisplay_W2 will use these properties to do the actual resizing + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; + cm.display.sizerWidth = op.adjustWidthTo; + op.barMeasure.scrollWidth = + Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); + op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); + } + + if (op.updatedDisplay || op.selectionChanged) + { op.preparedSelection = display.input.prepareSelection(); } + } + + function endOperation_W2(op) { + var cm = op.cm; + + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; + if (op.maxScrollLeft < cm.doc.scrollLeft) + { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); } + cm.display.maxLineChanged = false; + } + + var takeFocus = op.focus && op.focus == activeElt(); + if (op.preparedSelection) + { cm.display.input.showSelection(op.preparedSelection, takeFocus); } + if (op.updatedDisplay || op.startHeight != cm.doc.height) + { updateScrollbars(cm, op.barMeasure); } + if (op.updatedDisplay) + { setDocumentHeight(cm, op.barMeasure); } + + if (op.selectionChanged) { restartBlink(cm); } + + if (cm.state.focused && op.updateInput) + { cm.display.input.reset(op.typing); } + if (takeFocus) { ensureFocus(op.cm); } + } + + function endOperation_finish(op) { + var cm = op.cm, display = cm.display, doc = cm.doc; + + if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); } + + // Abort mouse wheel delta measurement, when scrolling explicitly + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) + { display.wheelStartX = display.wheelStartY = null; } + + // Propagate the scroll position to the actual DOM scroller + if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); } + + if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); } + // If we need to scroll a specific position into view, do so. + if (op.scrollToPos) { + var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), + clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); + maybeScrollWindow(cm, rect); + } + + // Fire events for markers that are hidden/unidden by editing or + // undoing + var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; + if (hidden) { for (var i = 0; i < hidden.length; ++i) + { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } } + if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1) + { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } } + + if (display.wrapper.offsetHeight) + { doc.scrollTop = cm.display.scroller.scrollTop; } + + // Fire change events, and delayed event handlers + if (op.changeObjs) + { signal(cm, "changes", cm, op.changeObjs); } + if (op.update) + { op.update.finish(); } + } + + // Run the given function in an operation + function runInOp(cm, f) { + if (cm.curOp) { return f() } + startOperation(cm); + try { return f() } + finally { endOperation(cm); } + } + // Wraps a function in an operation. Returns the wrapped function. + function operation(cm, f) { + return function() { + if (cm.curOp) { return f.apply(cm, arguments) } + startOperation(cm); + try { return f.apply(cm, arguments) } + finally { endOperation(cm); } + } + } + // Used to add methods to editor and doc instances, wrapping them in + // operations. + function methodOp(f) { + return function() { + if (this.curOp) { return f.apply(this, arguments) } + startOperation(this); + try { return f.apply(this, arguments) } + finally { endOperation(this); } + } + } + function docMethodOp(f) { + return function() { + var cm = this.cm; + if (!cm || cm.curOp) { return f.apply(this, arguments) } + startOperation(cm); + try { return f.apply(this, arguments) } + finally { endOperation(cm); } + } + } + + // HIGHLIGHT WORKER + + function startWorker(cm, time) { + if (cm.doc.highlightFrontier < cm.display.viewTo) + { cm.state.highlight.set(time, bind(highlightWorker, cm)); } + } + + function highlightWorker(cm) { + var doc = cm.doc; + if (doc.highlightFrontier >= cm.display.viewTo) { return } + var end = +new Date + cm.options.workTime; + var context = getContextBefore(cm, doc.highlightFrontier); + var changedLines = []; + + doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { + if (context.line >= cm.display.viewFrom) { // Visible + var oldStyles = line.styles; + var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null; + var highlighted = highlightLine(cm, line, context, true); + if (resetState) { context.state = resetState; } + line.styles = highlighted.styles; + var oldCls = line.styleClasses, newCls = highlighted.classes; + if (newCls) { line.styleClasses = newCls; } + else if (oldCls) { line.styleClasses = null; } + var ischange = !oldStyles || oldStyles.length != line.styles.length || + oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); + for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; } + if (ischange) { changedLines.push(context.line); } + line.stateAfter = context.save(); + context.nextLine(); + } else { + if (line.text.length <= cm.options.maxHighlightLength) + { processLine(cm, line.text, context); } + line.stateAfter = context.line % 5 == 0 ? context.save() : null; + context.nextLine(); + } + if (+new Date > end) { + startWorker(cm, cm.options.workDelay); + return true + } + }); + doc.highlightFrontier = context.line; + doc.modeFrontier = Math.max(doc.modeFrontier, context.line); + if (changedLines.length) { runInOp(cm, function () { + for (var i = 0; i < changedLines.length; i++) + { regLineChange(cm, changedLines[i], "text"); } + }); } + } + + // DISPLAY DRAWING + + var DisplayUpdate = function(cm, viewport, force) { + var display = cm.display; + + this.viewport = viewport; + // Store some values that we'll need later (but don't want to force a relayout for) + this.visible = visibleLines(display, cm.doc, viewport); + this.editorIsHidden = !display.wrapper.offsetWidth; + this.wrapperHeight = display.wrapper.clientHeight; + this.wrapperWidth = display.wrapper.clientWidth; + this.oldDisplayWidth = displayWidth(cm); + this.force = force; + this.dims = getDimensions(cm); + this.events = []; + }; + + DisplayUpdate.prototype.signal = function (emitter, type) { + if (hasHandler(emitter, type)) + { this.events.push(arguments); } + }; + DisplayUpdate.prototype.finish = function () { + for (var i = 0; i < this.events.length; i++) + { signal.apply(null, this.events[i]); } + }; + + function maybeClipScrollbars(cm) { + var display = cm.display; + if (!display.scrollbarsClipped && display.scroller.offsetWidth) { + display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; + display.heightForcer.style.height = scrollGap(cm) + "px"; + display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; + display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; + display.scrollbarsClipped = true; + } + } + + function selectionSnapshot(cm) { + if (cm.hasFocus()) { return null } + var active = activeElt(); + if (!active || !contains(cm.display.lineDiv, active)) { return null } + var result = {activeElt: active}; + if (window.getSelection) { + var sel = window.getSelection(); + if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { + result.anchorNode = sel.anchorNode; + result.anchorOffset = sel.anchorOffset; + result.focusNode = sel.focusNode; + result.focusOffset = sel.focusOffset; + } + } + return result + } + + function restoreSelection(snapshot) { + if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return } + snapshot.activeElt.focus(); + if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) && + snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { + var sel = window.getSelection(), range = document.createRange(); + range.setEnd(snapshot.anchorNode, snapshot.anchorOffset); + range.collapse(false); + sel.removeAllRanges(); + sel.addRange(range); + sel.extend(snapshot.focusNode, snapshot.focusOffset); + } + } + + // Does the actual updating of the line display. Bails out + // (returning false) when there is nothing to be done and forced is + // false. + function updateDisplayIfNeeded(cm, update) { + var display = cm.display, doc = cm.doc; + + if (update.editorIsHidden) { + resetView(cm); + return false + } + + // Bail out if the visible area is already rendered and nothing changed. + if (!update.force && + update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && + display.renderedView == display.view && countDirtyView(cm) == 0) + { return false } + + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm); + update.dims = getDimensions(cm); + } + + // Compute a suitable new viewport (from & to) + var end = doc.first + doc.size; + var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); + var to = Math.min(end, update.visible.to + cm.options.viewportMargin); + if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); } + if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); } + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from); + to = visualLineEndNo(cm.doc, to); + } + + var different = from != display.viewFrom || to != display.viewTo || + display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; + adjustView(cm, from, to); + + display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); + // Position the mover div to align with the current scroll position + cm.display.mover.style.top = display.viewOffset + "px"; + + var toUpdate = countDirtyView(cm); + if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) + { return false } + + // For big changes, we hide the enclosing element during the + // update, since that speeds up the operations on most browsers. + var selSnapshot = selectionSnapshot(cm); + if (toUpdate > 4) { display.lineDiv.style.display = "none"; } + patchDisplay(cm, display.updateLineNumbers, update.dims); + if (toUpdate > 4) { display.lineDiv.style.display = ""; } + display.renderedView = display.view; + // There might have been a widget with a focused element that got + // hidden or updated, if so re-focus it. + restoreSelection(selSnapshot); + + // Prevent selection and cursors from interfering with the scroll + // width and height. + removeChildren(display.cursorDiv); + removeChildren(display.selectionDiv); + display.gutters.style.height = display.sizer.style.minHeight = 0; + + if (different) { + display.lastWrapHeight = update.wrapperHeight; + display.lastWrapWidth = update.wrapperWidth; + startWorker(cm, 400); + } + + display.updateLineNumbers = null; + + return true + } + + function postUpdateDisplay(cm, update) { + var viewport = update.viewport; + + for (var first = true;; first = false) { + if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { + // Clip forced viewport to actual scrollable area. + if (viewport && viewport.top != null) + { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; } + // Updated line heights might result in the drawn area not + // actually covering the viewport. Keep looping until it does. + update.visible = visibleLines(cm.display, cm.doc, viewport); + if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) + { break } + } else if (first) { + update.visible = visibleLines(cm.display, cm.doc, viewport); + } + if (!updateDisplayIfNeeded(cm, update)) { break } + updateHeightsInViewport(cm); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + updateScrollbars(cm, barMeasure); + setDocumentHeight(cm, barMeasure); + update.force = false; + } + + update.signal(cm, "update", cm); + if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { + update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); + cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; + } + } + + function updateDisplaySimple(cm, viewport) { + var update = new DisplayUpdate(cm, viewport); + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm); + postUpdateDisplay(cm, update); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + updateScrollbars(cm, barMeasure); + setDocumentHeight(cm, barMeasure); + update.finish(); + } + } + + // Sync the actual display DOM structure with display.view, removing + // nodes for lines that are no longer in view, and creating the ones + // that are not there yet, and updating the ones that are out of + // date. + function patchDisplay(cm, updateNumbersFrom, dims) { + var display = cm.display, lineNumbers = cm.options.lineNumbers; + var container = display.lineDiv, cur = container.firstChild; + + function rm(node) { + var next = node.nextSibling; + // Works around a throw-scroll bug in OS X Webkit + if (webkit && mac && cm.display.currentWheelTarget == node) + { node.style.display = "none"; } + else + { node.parentNode.removeChild(node); } + return next + } + + var view = display.view, lineN = display.viewFrom; + // Loop over the elements in the view, syncing cur (the DOM nodes + // in display.lineDiv) with the view as we go. + for (var i = 0; i < view.length; i++) { + var lineView = view[i]; + if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet + var node = buildLineElement(cm, lineView, lineN, dims); + container.insertBefore(node, cur); + } else { // Already drawn + while (cur != lineView.node) { cur = rm(cur); } + var updateNumber = lineNumbers && updateNumbersFrom != null && + updateNumbersFrom <= lineN && lineView.lineNumber; + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; } + updateLineForChanges(cm, lineView, lineN, dims); + } + if (updateNumber) { + removeChildren(lineView.lineNumber); + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); + } + cur = lineView.node.nextSibling; + } + lineN += lineView.size; + } + while (cur) { cur = rm(cur); } + } + + function updateGutterSpace(display) { + var width = display.gutters.offsetWidth; + display.sizer.style.marginLeft = width + "px"; + // Send an event to consumers responding to changes in gutter width. + signalLater(display, "gutterChanged", display); + } + + function setDocumentHeight(cm, measure) { + cm.display.sizer.style.minHeight = measure.docHeight + "px"; + cm.display.heightForcer.style.top = measure.docHeight + "px"; + cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"; + } + + // Re-align line numbers and gutter marks to compensate for + // horizontal scrolling. + function alignHorizontally(cm) { + var display = cm.display, view = display.view; + if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return } + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; + var gutterW = display.gutters.offsetWidth, left = comp + "px"; + for (var i = 0; i < view.length; i++) { if (!view[i].hidden) { + if (cm.options.fixedGutter) { + if (view[i].gutter) + { view[i].gutter.style.left = left; } + if (view[i].gutterBackground) + { view[i].gutterBackground.style.left = left; } + } + var align = view[i].alignable; + if (align) { for (var j = 0; j < align.length; j++) + { align[j].style.left = left; } } + } } + if (cm.options.fixedGutter) + { display.gutters.style.left = (comp + gutterW) + "px"; } + } + + // Used to ensure that the line number gutter is still the right + // size for the current document size. Returns true when an update + // is needed. + function maybeUpdateLineNumberWidth(cm) { + if (!cm.options.lineNumbers) { return false } + var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild(elt("div", [elt("div", last)], + "CodeMirror-linenumber CodeMirror-gutter-elt")); + var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; + display.lineGutter.style.width = ""; + display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; + display.lineNumWidth = display.lineNumInnerWidth + padding; + display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; + display.lineGutter.style.width = display.lineNumWidth + "px"; + updateGutterSpace(cm.display); + return true + } + return false + } + + function getGutters(gutters, lineNumbers) { + var result = [], sawLineNumbers = false; + for (var i = 0; i < gutters.length; i++) { + var name = gutters[i], style = null; + if (typeof name != "string") { style = name.style; name = name.className; } + if (name == "CodeMirror-linenumbers") { + if (!lineNumbers) { continue } + else { sawLineNumbers = true; } + } + result.push({className: name, style: style}); + } + if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); } + return result + } + + // Rebuild the gutter elements, ensure the margin to the left of the + // code matches their width. + function renderGutters(display) { + var gutters = display.gutters, specs = display.gutterSpecs; + removeChildren(gutters); + display.lineGutter = null; + for (var i = 0; i < specs.length; ++i) { + var ref = specs[i]; + var className = ref.className; + var style = ref.style; + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className)); + if (style) { gElt.style.cssText = style; } + if (className == "CodeMirror-linenumbers") { + display.lineGutter = gElt; + gElt.style.width = (display.lineNumWidth || 1) + "px"; + } + } + gutters.style.display = specs.length ? "" : "none"; + updateGutterSpace(display); + } + + function updateGutters(cm) { + renderGutters(cm.display); + regChange(cm); + alignHorizontally(cm); + } + + // The display handles the DOM integration, both for input reading + // and content drawing. It holds references to DOM nodes and + // display-related state. + + function Display(place, doc, input, options) { + var d = this; + this.input = input; + + // Covers bottom-right square when both scrollbars are present. + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); + d.scrollbarFiller.setAttribute("cm-not-content", "true"); + // Covers bottom of gutter when coverGutterNextToScrollbar is on + // and h scrollbar is present. + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); + d.gutterFiller.setAttribute("cm-not-content", "true"); + // Will contain the actual code, positioned to cover the viewport. + d.lineDiv = eltP("div", null, "CodeMirror-code"); + // Elements are added to these to represent selection and cursors. + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); + d.cursorDiv = elt("div", null, "CodeMirror-cursors"); + // A visibility: hidden element used to find the size of things. + d.measure = elt("div", null, "CodeMirror-measure"); + // When lines outside of the viewport are measured, they are drawn in this. + d.lineMeasure = elt("div", null, "CodeMirror-measure"); + // Wraps everything that needs to exist inside the vertically-padded coordinate system + d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], + null, "position: relative; outline: none"); + var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); + // Moved around its parent to cover visible view. + d.mover = elt("div", [lines], null, "position: relative"); + // Set to the height of the document, allowing scrolling. + d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); + d.sizerWidth = null; + // Behavior of elts with overflow: auto and padding is + // inconsistent across browsers. This is used to ensure the + // scrollable area is big enough. + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); + // Will contain the gutters, if any. + d.gutters = elt("div", null, "CodeMirror-gutters"); + d.lineGutter = null; + // Actual scrollable element. + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); + d.scroller.setAttribute("tabIndex", "-1"); + // The element in which the editor lives. + d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); + + // This attribute is respected by automatic translation systems such as Google Translate, + // and may also be respected by tools used by human translators. + d.wrapper.setAttribute('translate', 'no'); + + // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) + if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } + if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; } + + if (place) { + if (place.appendChild) { place.appendChild(d.wrapper); } + else { place(d.wrapper); } + } + + // Current rendered range (may be bigger than the view window). + d.viewFrom = d.viewTo = doc.first; + d.reportedViewFrom = d.reportedViewTo = doc.first; + // Information about the rendered lines. + d.view = []; + d.renderedView = null; + // Holds info about a single rendered line when it was rendered + // for measurement, while not in view. + d.externalMeasured = null; + // Empty space (in pixels) above the view + d.viewOffset = 0; + d.lastWrapHeight = d.lastWrapWidth = 0; + d.updateLineNumbers = null; + + d.nativeBarWidth = d.barHeight = d.barWidth = 0; + d.scrollbarsClipped = false; + + // Used to only resize the line number gutter when necessary (when + // the amount of lines crosses a boundary that makes its width change) + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; + // Set to true when a non-horizontal-scrolling line widget is + // added. As an optimization, line widget aligning is skipped when + // this is false. + d.alignWidgets = false; + + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + + // Tracks the maximum line length so that the horizontal scrollbar + // can be kept static when scrolling. + d.maxLine = null; + d.maxLineLength = 0; + d.maxLineChanged = false; + + // Used for measuring wheel scrolling granularity + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; + + // True when shift is held down. + d.shift = false; + + // Used to track whether anything happened since the context menu + // was opened. + d.selForContextMenu = null; + + d.activeTouch = null; + + d.gutterSpecs = getGutters(options.gutters, options.lineNumbers); + renderGutters(d); + + input.init(d); + } + + // Since the delta values reported on mouse wheel events are + // unstandardized between browsers and even browser versions, and + // generally horribly unpredictable, this code starts by measuring + // the scroll effect that the first few mouse wheel events have, + // and, from that, detects the way it can convert deltas to pixel + // offsets afterwards. + // + // The reason we want to know the amount a wheel event will scroll + // is that it gives us a chance to update the display before the + // actual scrolling happens, reducing flickering. + + var wheelSamples = 0, wheelPixelsPerUnit = null; + // Fill in a browser-detected starting value on browsers where we + // know one. These don't have to be accurate -- the result of them + // being wrong would just be a slight flicker on the first wheel + // scroll (if it is large enough). + if (ie) { wheelPixelsPerUnit = -.53; } + else if (gecko) { wheelPixelsPerUnit = 15; } + else if (chrome) { wheelPixelsPerUnit = -.7; } + else if (safari) { wheelPixelsPerUnit = -1/3; } + + function wheelEventDelta(e) { + var dx = e.wheelDeltaX, dy = e.wheelDeltaY; + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; } + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; } + else if (dy == null) { dy = e.wheelDelta; } + return {x: dx, y: dy} + } + function wheelEventPixels(e) { + var delta = wheelEventDelta(e); + delta.x *= wheelPixelsPerUnit; + delta.y *= wheelPixelsPerUnit; + return delta + } + + function onScrollWheel(cm, e) { + var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; + var pixelsPerUnit = wheelPixelsPerUnit; + if (e.deltaMode === 0) { + dx = e.deltaX; + dy = e.deltaY; + pixelsPerUnit = 1; + } + + var display = cm.display, scroll = display.scroller; + // Quit if there's nothing to scroll here + var canScrollX = scroll.scrollWidth > scroll.clientWidth; + var canScrollY = scroll.scrollHeight > scroll.clientHeight; + if (!(dx && canScrollX || dy && canScrollY)) { return } + + // Webkit browsers on OS X abort momentum scrolls when the target + // of the scroll event is removed from the scrollable element. + // This hack (see related code in patchDisplay) makes sure the + // element is kept around. + if (dy && mac && webkit) { + outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + for (var i = 0; i < view.length; i++) { + if (view[i].node == cur) { + cm.display.currentWheelTarget = cur; + break outer + } + } + } + } + + // On some browsers, horizontal scrolling will cause redraws to + // happen before the gutter has been realigned, causing it to + // wriggle around in a most unseemly way. When we have an + // estimated pixels/delta value, we just handle horizontal + // scrolling entirely here. It'll be slightly off from native, but + // better than glitching out. + if (dx && !gecko && !presto && pixelsPerUnit != null) { + if (dy && canScrollY) + { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); } + setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit)); + // Only prevent default scrolling if vertical scrolling is + // actually possible. Otherwise, it causes vertical scroll + // jitter on OSX trackpads when deltaX is small and deltaY + // is large (issue #3579) + if (!dy || (dy && canScrollY)) + { e_preventDefault(e); } + display.wheelStartX = null; // Abort measurement, if in progress + return + } + + // 'Project' the visible viewport to cover the area that is being + // scrolled into view (if we know enough to estimate it). + if (dy && pixelsPerUnit != null) { + var pixels = dy * pixelsPerUnit; + var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; + if (pixels < 0) { top = Math.max(0, top + pixels - 50); } + else { bot = Math.min(cm.doc.height, bot + pixels + 50); } + updateDisplaySimple(cm, {top: top, bottom: bot}); + } + + if (wheelSamples < 20 && e.deltaMode !== 0) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; + display.wheelDX = dx; display.wheelDY = dy; + setTimeout(function () { + if (display.wheelStartX == null) { return } + var movedX = scroll.scrollLeft - display.wheelStartX; + var movedY = scroll.scrollTop - display.wheelStartY; + var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || + (movedX && display.wheelDX && movedX / display.wheelDX); + display.wheelStartX = display.wheelStartY = null; + if (!sample) { return } + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); + ++wheelSamples; + }, 200); + } else { + display.wheelDX += dx; display.wheelDY += dy; + } + } + } + + // Selection objects are immutable. A new one is created every time + // the selection changes. A selection is one or more non-overlapping + // (and non-touching) ranges, sorted, and an integer that indicates + // which one is the primary selection (the one that's scrolled into + // view, that getCursor returns, etc). + var Selection = function(ranges, primIndex) { + this.ranges = ranges; + this.primIndex = primIndex; + }; + + Selection.prototype.primary = function () { return this.ranges[this.primIndex] }; + + Selection.prototype.equals = function (other) { + if (other == this) { return true } + if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false } + for (var i = 0; i < this.ranges.length; i++) { + var here = this.ranges[i], there = other.ranges[i]; + if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false } + } + return true + }; + + Selection.prototype.deepCopy = function () { + var out = []; + for (var i = 0; i < this.ranges.length; i++) + { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); } + return new Selection(out, this.primIndex) + }; + + Selection.prototype.somethingSelected = function () { + for (var i = 0; i < this.ranges.length; i++) + { if (!this.ranges[i].empty()) { return true } } + return false + }; + + Selection.prototype.contains = function (pos, end) { + if (!end) { end = pos; } + for (var i = 0; i < this.ranges.length; i++) { + var range = this.ranges[i]; + if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) + { return i } + } + return -1 + }; + + var Range = function(anchor, head) { + this.anchor = anchor; this.head = head; + }; + + Range.prototype.from = function () { return minPos(this.anchor, this.head) }; + Range.prototype.to = function () { return maxPos(this.anchor, this.head) }; + Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch }; + + // Take an unsorted, potentially overlapping set of ranges, and + // build a selection out of it. 'Consumes' ranges array (modifying + // it). + function normalizeSelection(cm, ranges, primIndex) { + var mayTouch = cm && cm.options.selectionsMayTouch; + var prim = ranges[primIndex]; + ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }); + primIndex = indexOf(ranges, prim); + for (var i = 1; i < ranges.length; i++) { + var cur = ranges[i], prev = ranges[i - 1]; + var diff = cmp(prev.to(), cur.from()); + if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) { + var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); + var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; + if (i <= primIndex) { --primIndex; } + ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); + } + } + return new Selection(ranges, primIndex) + } + + function simpleSelection(anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0) + } + + // Compute the position of the end of a change (its 'to' property + // refers to the pre-change end). + function changeEnd(change) { + if (!change.text) { return change.to } + return Pos(change.from.line + change.text.length - 1, + lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) + } + + // Adjust a position to refer to the post-change position of the + // same text, or the end of the change if the change covers it. + function adjustForChange(pos, change) { + if (cmp(pos, change.from) < 0) { return pos } + if (cmp(pos, change.to) <= 0) { return changeEnd(change) } + + var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; + if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; } + return Pos(line, ch) + } + + function computeSelAfterChange(doc, change) { + var out = []; + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i]; + out.push(new Range(adjustForChange(range.anchor, change), + adjustForChange(range.head, change))); + } + return normalizeSelection(doc.cm, out, doc.sel.primIndex) + } + + function offsetPos(pos, old, nw) { + if (pos.line == old.line) + { return Pos(nw.line, pos.ch - old.ch + nw.ch) } + else + { return Pos(nw.line + (pos.line - old.line), pos.ch) } + } + + // Used by replaceSelections to allow moving the selection to the + // start or around the replaced test. Hint may be "start" or "around". + function computeReplacedSel(doc, changes, hint) { + var out = []; + var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + var from = offsetPos(change.from, oldPrev, newPrev); + var to = offsetPos(changeEnd(change), oldPrev, newPrev); + oldPrev = change.to; + newPrev = to; + if (hint == "around") { + var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; + out[i] = new Range(inv ? to : from, inv ? from : to); + } else { + out[i] = new Range(from, from); + } + } + return new Selection(out, doc.sel.primIndex) + } + + // Used to get the editor into a consistent state again when options change. + + function loadMode(cm) { + cm.doc.mode = getMode(cm.options, cm.doc.modeOption); + resetModeState(cm); + } + + function resetModeState(cm) { + cm.doc.iter(function (line) { + if (line.stateAfter) { line.stateAfter = null; } + if (line.styles) { line.styles = null; } + }); + cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; + startWorker(cm, 100); + cm.state.modeGen++; + if (cm.curOp) { regChange(cm); } + } + + // DOCUMENT DATA STRUCTURE + + // By default, updates that start and end at the beginning of a line + // are treated specially, in order to make the association of line + // widgets and marker elements with the text behave more intuitive. + function isWholeLineUpdate(doc, change) { + return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && + (!doc.cm || doc.cm.options.wholeLineUpdateBefore) + } + + // Perform a change on the document data structure. + function updateDoc(doc, change, markedSpans, estimateHeight) { + function spansFor(n) {return markedSpans ? markedSpans[n] : null} + function update(line, text, spans) { + updateLine(line, text, spans, estimateHeight); + signalLater(line, "change", line, change); + } + function linesFor(start, end) { + var result = []; + for (var i = start; i < end; ++i) + { result.push(new Line(text[i], spansFor(i), estimateHeight)); } + return result + } + + var from = change.from, to = change.to, text = change.text; + var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); + var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; + + // Adjust the line structure + if (change.full) { + doc.insert(0, linesFor(0, text.length)); + doc.remove(text.length, doc.size - text.length); + } else if (isWholeLineUpdate(doc, change)) { + // This is a whole-line replace. Treated specially to make + // sure line objects move the way they are supposed to. + var added = linesFor(0, text.length - 1); + update(lastLine, lastLine.text, lastSpans); + if (nlines) { doc.remove(from.line, nlines); } + if (added.length) { doc.insert(from.line, added); } + } else if (firstLine == lastLine) { + if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); + } else { + var added$1 = linesFor(1, text.length - 1); + added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + doc.insert(from.line + 1, added$1); + } + } else if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); + doc.remove(from.line + 1, nlines); + } else { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); + var added$2 = linesFor(1, text.length - 1); + if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); } + doc.insert(from.line + 1, added$2); + } + + signalLater(doc, "change", doc, change); + } + + // Call f for all linked documents. + function linkedDocs(doc, f, sharedHistOnly) { + function propagate(doc, skip, sharedHist) { + if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) { + var rel = doc.linked[i]; + if (rel.doc == skip) { continue } + var shared = sharedHist && rel.sharedHist; + if (sharedHistOnly && !shared) { continue } + f(rel.doc, shared); + propagate(rel.doc, doc, shared); + } } + } + propagate(doc, null, true); + } + + // Attach a document to an editor. + function attachDoc(cm, doc) { + if (doc.cm) { throw new Error("This document is already in use.") } + cm.doc = doc; + doc.cm = cm; + estimateLineHeights(cm); + loadMode(cm); + setDirectionClass(cm); + cm.options.direction = doc.direction; + if (!cm.options.lineWrapping) { findMaxLine(cm); } + cm.options.mode = doc.modeOption; + regChange(cm); + } + + function setDirectionClass(cm) { + (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); + } + + function directionChanged(cm) { + runInOp(cm, function () { + setDirectionClass(cm); + regChange(cm); + }); + } + + function History(prev) { + // Arrays of change events and selections. Doing something adds an + // event to done and clears undo. Undoing moves events from done + // to undone, redoing moves them in the other direction. + this.done = []; this.undone = []; + this.undoDepth = prev ? prev.undoDepth : Infinity; + // Used to track when changes can be merged into a single undo + // event + this.lastModTime = this.lastSelTime = 0; + this.lastOp = this.lastSelOp = null; + this.lastOrigin = this.lastSelOrigin = null; + // Used by the isClean() method + this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1; + } + + // Create a history change event from an updateDoc-style change + // object. + function historyChangeFromChange(doc, change) { + var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; + attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); + linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true); + return histChange + } + + // Pop all selection events off the end of a history array. Stop at + // a change event. + function clearSelectionEvents(array) { + while (array.length) { + var last = lst(array); + if (last.ranges) { array.pop(); } + else { break } + } + } + + // Find the top change event in the history. Pop off selection + // events that are in the way. + function lastChangeEvent(hist, force) { + if (force) { + clearSelectionEvents(hist.done); + return lst(hist.done) + } else if (hist.done.length && !lst(hist.done).ranges) { + return lst(hist.done) + } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { + hist.done.pop(); + return lst(hist.done) + } + } + + // Register a change in the history. Merges changes that are within + // a single operation, or are close together with an origin that + // allows merging (starting with "+") into a single event. + function addChangeToHistory(doc, change, selAfter, opId) { + var hist = doc.history; + hist.undone.length = 0; + var time = +new Date, cur; + var last; + + if ((hist.lastOp == opId || + hist.lastOrigin == change.origin && change.origin && + ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) || + change.origin.charAt(0) == "*")) && + (cur = lastChangeEvent(hist, hist.lastOp == opId))) { + // Merge this change into the last event + last = lst(cur.changes); + if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { + // Optimized case for simple insertion -- don't want to add + // new changesets for every character typed + last.to = changeEnd(change); + } else { + // Add new sub-event + cur.changes.push(historyChangeFromChange(doc, change)); + } + } else { + // Can not be merged, start a new event. + var before = lst(hist.done); + if (!before || !before.ranges) + { pushSelectionToHistory(doc.sel, hist.done); } + cur = {changes: [historyChangeFromChange(doc, change)], + generation: hist.generation}; + hist.done.push(cur); + while (hist.done.length > hist.undoDepth) { + hist.done.shift(); + if (!hist.done[0].ranges) { hist.done.shift(); } + } + } + hist.done.push(selAfter); + hist.generation = ++hist.maxGeneration; + hist.lastModTime = hist.lastSelTime = time; + hist.lastOp = hist.lastSelOp = opId; + hist.lastOrigin = hist.lastSelOrigin = change.origin; + + if (!last) { signal(doc, "historyAdded"); } + } + + function selectionEventCanBeMerged(doc, origin, prev, sel) { + var ch = origin.charAt(0); + return ch == "*" || + ch == "+" && + prev.ranges.length == sel.ranges.length && + prev.somethingSelected() == sel.somethingSelected() && + new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500) + } + + // Called whenever the selection changes, sets the new selection as + // the pending selection in the history, and pushes the old pending + // selection into the 'done' array when it was significantly + // different (in number of selected ranges, emptiness, or time). + function addSelectionToHistory(doc, sel, opId, options) { + var hist = doc.history, origin = options && options.origin; + + // A new event is started when the previous origin does not match + // the current, or the origins don't allow matching. Origins + // starting with * are always merged, those starting with + are + // merged when similar and close together in time. + if (opId == hist.lastSelOp || + (origin && hist.lastSelOrigin == origin && + (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || + selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) + { hist.done[hist.done.length - 1] = sel; } + else + { pushSelectionToHistory(sel, hist.done); } + + hist.lastSelTime = +new Date; + hist.lastSelOrigin = origin; + hist.lastSelOp = opId; + if (options && options.clearRedo !== false) + { clearSelectionEvents(hist.undone); } + } + + function pushSelectionToHistory(sel, dest) { + var top = lst(dest); + if (!(top && top.ranges && top.equals(sel))) + { dest.push(sel); } + } + + // Used to store marked span information in the history. + function attachLocalSpans(doc, change, from, to) { + var existing = change["spans_" + doc.id], n = 0; + doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { + if (line.markedSpans) + { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; } + ++n; + }); + } + + // When un/re-doing restores text containing marked spans, those + // that have been explicitly cleared should not be restored. + function removeClearedSpans(spans) { + if (!spans) { return null } + var out; + for (var i = 0; i < spans.length; ++i) { + if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } } + else if (out) { out.push(spans[i]); } + } + return !out ? spans : out.length ? out : null + } + + // Retrieve and filter the old marked spans stored in a change event. + function getOldSpans(doc, change) { + var found = change["spans_" + doc.id]; + if (!found) { return null } + var nw = []; + for (var i = 0; i < change.text.length; ++i) + { nw.push(removeClearedSpans(found[i])); } + return nw + } + + // Used for un/re-doing changes from the history. Combines the + // result of computing the existing spans with the set of spans that + // existed in the history (so that deleting around a span and then + // undoing brings back the span). + function mergeOldSpans(doc, change) { + var old = getOldSpans(doc, change); + var stretched = stretchSpansOverChange(doc, change); + if (!old) { return stretched } + if (!stretched) { return old } + + for (var i = 0; i < old.length; ++i) { + var oldCur = old[i], stretchCur = stretched[i]; + if (oldCur && stretchCur) { + spans: for (var j = 0; j < stretchCur.length; ++j) { + var span = stretchCur[j]; + for (var k = 0; k < oldCur.length; ++k) + { if (oldCur[k].marker == span.marker) { continue spans } } + oldCur.push(span); + } + } else if (stretchCur) { + old[i] = stretchCur; + } + } + return old + } + + // Used both to provide a JSON-safe object in .getHistory, and, when + // detaching a document, to split the history in two + function copyHistoryArray(events, newGroup, instantiateSel) { + var copy = []; + for (var i = 0; i < events.length; ++i) { + var event = events[i]; + if (event.ranges) { + copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); + continue + } + var changes = event.changes, newChanges = []; + copy.push({changes: newChanges}); + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], m = (void 0); + newChanges.push({from: change.from, to: change.to, text: change.text}); + if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop] = change[prop]; + delete change[prop]; + } + } } } + } + } + return copy + } + + // The 'scroll' parameter given to many of these indicated whether + // the new cursor position should be scrolled into view after + // modifying the selection. + + // If shift is held or the extend flag is set, extends a range to + // include a given position (and optionally a second position). + // Otherwise, simply returns the range between the given positions. + // Used for cursor motion and such. + function extendRange(range, head, other, extend) { + if (extend) { + var anchor = range.anchor; + if (other) { + var posBefore = cmp(head, anchor) < 0; + if (posBefore != (cmp(other, anchor) < 0)) { + anchor = head; + head = other; + } else if (posBefore != (cmp(head, other) < 0)) { + head = other; + } + } + return new Range(anchor, head) + } else { + return new Range(other || head, head) + } + } + + // Extend the primary selection range, discard the rest. + function extendSelection(doc, head, other, options, extend) { + if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); } + setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options); + } + + // Extend all selections (pos is an array of selections with length + // equal the number of selections) + function extendSelections(doc, heads, options) { + var out = []; + var extend = doc.cm && (doc.cm.display.shift || doc.extend); + for (var i = 0; i < doc.sel.ranges.length; i++) + { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); } + var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex); + setSelection(doc, newSel, options); + } + + // Updates a single range in the selection. + function replaceOneSelection(doc, i, range, options) { + var ranges = doc.sel.ranges.slice(0); + ranges[i] = range; + setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options); + } + + // Reset the selection to a single range. + function setSimpleSelection(doc, anchor, head, options) { + setSelection(doc, simpleSelection(anchor, head), options); + } + + // Give beforeSelectionChange handlers a change to influence a + // selection update. + function filterSelectionChange(doc, sel, options) { + var obj = { + ranges: sel.ranges, + update: function(ranges) { + this.ranges = []; + for (var i = 0; i < ranges.length; i++) + { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), + clipPos(doc, ranges[i].head)); } + }, + origin: options && options.origin + }; + signal(doc, "beforeSelectionChange", doc, obj); + if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); } + if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) } + else { return sel } + } + + function setSelectionReplaceHistory(doc, sel, options) { + var done = doc.history.done, last = lst(done); + if (last && last.ranges) { + done[done.length - 1] = sel; + setSelectionNoUndo(doc, sel, options); + } else { + setSelection(doc, sel, options); + } + } + + // Set a new selection. + function setSelection(doc, sel, options) { + setSelectionNoUndo(doc, sel, options); + addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); + } + + function setSelectionNoUndo(doc, sel, options) { + if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) + { sel = filterSelectionChange(doc, sel, options); } + + var bias = options && options.bias || + (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); + setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); + + if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor") + { ensureCursorVisible(doc.cm); } + } + + function setSelectionInner(doc, sel) { + if (sel.equals(doc.sel)) { return } + + doc.sel = sel; + + if (doc.cm) { + doc.cm.curOp.updateInput = 1; + doc.cm.curOp.selectionChanged = true; + signalCursorActivity(doc.cm); + } + signalLater(doc, "cursorActivity", doc); + } + + // Verify that the selection does not partially select any atomic + // marked ranges. + function reCheckSelection(doc) { + setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); + } + + // Return a selection that does not partially select any atomic + // ranges. + function skipAtomicInSelection(doc, sel, bias, mayClear) { + var out; + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i]; + var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]; + var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear); + var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear); + if (out || newAnchor != range.anchor || newHead != range.head) { + if (!out) { out = sel.ranges.slice(0, i); } + out[i] = new Range(newAnchor, newHead); + } + } + return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel + } + + function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { + var line = getLine(doc, pos.line); + if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { + var sp = line.markedSpans[i], m = sp.marker; + + // Determine if we should prevent the cursor being placed to the left/right of an atomic marker + // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it + // is with selectLeft/Right + var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft; + var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight; + + if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && + (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) { + if (mayClear) { + signal(m, "beforeCursorEnter"); + if (m.explicitlyCleared) { + if (!line.markedSpans) { break } + else {--i; continue} + } + } + if (!m.atomic) { continue } + + if (oldPos) { + var near = m.find(dir < 0 ? 1 : -1), diff = (void 0); + if (dir < 0 ? preventCursorRight : preventCursorLeft) + { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); } + if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) + { return skipAtomicInner(doc, near, pos, dir, mayClear) } + } + + var far = m.find(dir < 0 ? -1 : 1); + if (dir < 0 ? preventCursorLeft : preventCursorRight) + { far = movePos(doc, far, dir, far.line == pos.line ? line : null); } + return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null + } + } } + return pos + } + + // Ensure a given position is not inside an atomic range. + function skipAtomic(doc, pos, oldPos, bias, mayClear) { + var dir = bias || 1; + var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || + (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || + skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || + (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)); + if (!found) { + doc.cantEdit = true; + return Pos(doc.first, 0) + } + return found + } + + function movePos(doc, pos, dir, line) { + if (dir < 0 && pos.ch == 0) { + if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) } + else { return null } + } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { + if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) } + else { return null } + } else { + return new Pos(pos.line, pos.ch + dir) + } + } + + function selectAll(cm) { + cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); + } + + // UPDATING + + // Allow "beforeChange" event handlers to influence a change + function filterChange(doc, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function () { return obj.canceled = true; } + }; + if (update) { obj.update = function (from, to, text, origin) { + if (from) { obj.from = clipPos(doc, from); } + if (to) { obj.to = clipPos(doc, to); } + if (text) { obj.text = text; } + if (origin !== undefined) { obj.origin = origin; } + }; } + signal(doc, "beforeChange", doc, obj); + if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); } + + if (obj.canceled) { + if (doc.cm) { doc.cm.curOp.updateInput = 2; } + return null + } + return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} + } + + // Apply a change to a document, and add it to the document's + // history, and propagating it to all linked documents. + function makeChange(doc, change, ignoreReadOnly) { + if (doc.cm) { + if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) } + if (doc.cm.state.suppressEdits) { return } + } + + if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { + change = filterChange(doc, change, true); + if (!change) { return } + } + + // Possibly split or suppress the update based on the presence + // of read-only spans in its range. + var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); + if (split) { + for (var i = split.length - 1; i >= 0; --i) + { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); } + } else { + makeChangeInner(doc, change); + } + } + + function makeChangeInner(doc, change) { + if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return } + var selAfter = computeSelAfterChange(doc, change); + addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); + + makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); + var rebased = []; + + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); + }); + } + + // Revert a change stored in a document's history. + function makeChangeFromHistory(doc, type, allowSelectionOnly) { + var suppress = doc.cm && doc.cm.state.suppressEdits; + if (suppress && !allowSelectionOnly) { return } + + var hist = doc.history, event, selAfter = doc.sel; + var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; + + // Verify that there is a useable event (so that ctrl-z won't + // needlessly clear selection events) + var i = 0; + for (; i < source.length; i++) { + event = source[i]; + if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) + { break } + } + if (i == source.length) { return } + hist.lastOrigin = hist.lastSelOrigin = null; + + for (;;) { + event = source.pop(); + if (event.ranges) { + pushSelectionToHistory(event, dest); + if (allowSelectionOnly && !event.equals(doc.sel)) { + setSelection(doc, event, {clearRedo: false}); + return + } + selAfter = event; + } else if (suppress) { + source.push(event); + return + } else { break } + } + + // Build up a reverse change object to add to the opposite history + // stack (redo when undoing, and vice versa). + var antiChanges = []; + pushSelectionToHistory(selAfter, dest); + dest.push({changes: antiChanges, generation: hist.generation}); + hist.generation = event.generation || ++hist.maxGeneration; + + var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); + + var loop = function ( i ) { + var change = event.changes[i]; + change.origin = type; + if (filter && !filterChange(doc, change, false)) { + source.length = 0; + return {} + } + + antiChanges.push(historyChangeFromChange(doc, change)); + + var after = i ? computeSelAfterChange(doc, change) : lst(source); + makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); + if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); } + var rebased = []; + + // Propagate to the linked documents + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); + }); + }; + + for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { + var returned = loop( i$1 ); + + if ( returned ) return returned.v; + } + } + + // Sub-views need their line numbers shifted when text is added + // above or below them in the parent document. + function shiftDoc(doc, distance) { + if (distance == 0) { return } + doc.first += distance; + doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range( + Pos(range.anchor.line + distance, range.anchor.ch), + Pos(range.head.line + distance, range.head.ch) + ); }), doc.sel.primIndex); + if (doc.cm) { + regChange(doc.cm, doc.first, doc.first - distance, distance); + for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) + { regLineChange(doc.cm, l, "gutter"); } + } + } + + // More lower-level change function, handling only a single document + // (not linked ones). + function makeChangeSingleDoc(doc, change, selAfter, spans) { + if (doc.cm && !doc.cm.curOp) + { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) } + + if (change.to.line < doc.first) { + shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); + return + } + if (change.from.line > doc.lastLine()) { return } + + // Clip the change to the size of this doc + if (change.from.line < doc.first) { + var shift = change.text.length - 1 - (doc.first - change.from.line); + shiftDoc(doc, shift); + change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], origin: change.origin}; + } + var last = doc.lastLine(); + if (change.to.line > last) { + change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), + text: [change.text[0]], origin: change.origin}; + } + + change.removed = getBetween(doc, change.from, change.to); + + if (!selAfter) { selAfter = computeSelAfterChange(doc, change); } + if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); } + else { updateDoc(doc, change, spans); } + setSelectionNoUndo(doc, selAfter, sel_dontScroll); + + if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) + { doc.cantEdit = false; } + } + + // Handle the interaction of a change to a document with the editor + // that this document is part of. + function makeChangeSingleDocInEditor(cm, change, spans) { + var doc = cm.doc, display = cm.display, from = change.from, to = change.to; + + var recomputeMaxLength = false, checkWidthStart = from.line; + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); + doc.iter(checkWidthStart, to.line + 1, function (line) { + if (line == display.maxLine) { + recomputeMaxLength = true; + return true + } + }); + } + + if (doc.sel.contains(change.from, change.to) > -1) + { signalCursorActivity(cm); } + + updateDoc(doc, change, spans, estimateHeight(cm)); + + if (!cm.options.lineWrapping) { + doc.iter(checkWidthStart, from.line + change.text.length, function (line) { + var len = lineLength(line); + if (len > display.maxLineLength) { + display.maxLine = line; + display.maxLineLength = len; + display.maxLineChanged = true; + recomputeMaxLength = false; + } + }); + if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; } + } + + retreatFrontier(doc, from.line); + startWorker(cm, 400); + + var lendiff = change.text.length - (to.line - from.line) - 1; + // Remember that these lines changed, for updating the display + if (change.full) + { regChange(cm); } + else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) + { regLineChange(cm, from.line, "text"); } + else + { regChange(cm, from.line, to.line + 1, lendiff); } + + var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); + if (changeHandler || changesHandler) { + var obj = { + from: from, to: to, + text: change.text, + removed: change.removed, + origin: change.origin + }; + if (changeHandler) { signalLater(cm, "change", cm, obj); } + if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); } + } + cm.display.selForContextMenu = null; + } + + function replaceRange(doc, code, from, to, origin) { + var assign; + + if (!to) { to = from; } + if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); } + if (typeof code == "string") { code = doc.splitLines(code); } + makeChange(doc, {from: from, to: to, text: code, origin: origin}); + } + + // Rebasing/resetting history to deal with externally-sourced changes + + function rebaseHistSelSingle(pos, from, to, diff) { + if (to < pos.line) { + pos.line += diff; + } else if (from < pos.line) { + pos.line = from; + pos.ch = 0; + } + } + + // Tries to rebase an array of history events given a change in the + // document. If the change touches the same lines as the event, the + // event, and everything 'behind' it, is discarded. If the change is + // before the event, the event's positions are updated. Uses a + // copy-on-write scheme for the positions, to avoid having to + // reallocate them all on every rebase, but also avoid problems with + // shared position objects being unsafely updated. + function rebaseHistArray(array, from, to, diff) { + for (var i = 0; i < array.length; ++i) { + var sub = array[i], ok = true; + if (sub.ranges) { + if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } + for (var j = 0; j < sub.ranges.length; j++) { + rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); + rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); + } + continue + } + for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { + var cur = sub.changes[j$1]; + if (to < cur.from.line) { + cur.from = Pos(cur.from.line + diff, cur.from.ch); + cur.to = Pos(cur.to.line + diff, cur.to.ch); + } else if (from <= cur.to.line) { + ok = false; + break + } + } + if (!ok) { + array.splice(0, i + 1); + i = 0; + } + } + } + + function rebaseHist(hist, change) { + var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; + rebaseHistArray(hist.done, from, to, diff); + rebaseHistArray(hist.undone, from, to, diff); + } + + // Utility for applying a change to a line by handle or number, + // returning the number and optionally registering the line as + // changed. + function changeLine(doc, handle, changeType, op) { + var no = handle, line = handle; + if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); } + else { no = lineNo(handle); } + if (no == null) { return null } + if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); } + return line + } + + // The document is represented as a BTree consisting of leaves, with + // chunk of lines in them, and branches, with up to ten leaves or + // other branch nodes below them. The top node is always a branch + // node, and is the document object itself (meaning it has + // additional methods and properties). + // + // All nodes have parent links. The tree is used both to go from + // line numbers to line objects, and to go from objects to numbers. + // It also indexes by height, and is used to convert between height + // and line object, and to find the total height of the document. + // + // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html + + function LeafChunk(lines) { + this.lines = lines; + this.parent = null; + var height = 0; + for (var i = 0; i < lines.length; ++i) { + lines[i].parent = this; + height += lines[i].height; + } + this.height = height; + } + + LeafChunk.prototype = { + chunkSize: function() { return this.lines.length }, + + // Remove the n lines at offset 'at'. + removeInner: function(at, n) { + for (var i = at, e = at + n; i < e; ++i) { + var line = this.lines[i]; + this.height -= line.height; + cleanUpLine(line); + signalLater(line, "delete"); + } + this.lines.splice(at, n); + }, + + // Helper used to collapse a small branch into a single leaf. + collapse: function(lines) { + lines.push.apply(lines, this.lines); + }, + + // Insert the given array of lines at offset 'at', count them as + // having the given height. + insertInner: function(at, lines, height) { + this.height += height; + this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); + for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; } + }, + + // Used to iterate over a part of the tree. + iterN: function(at, n, op) { + for (var e = at + n; at < e; ++at) + { if (op(this.lines[at])) { return true } } + } + }; + + function BranchChunk(children) { + this.children = children; + var size = 0, height = 0; + for (var i = 0; i < children.length; ++i) { + var ch = children[i]; + size += ch.chunkSize(); height += ch.height; + ch.parent = this; + } + this.size = size; + this.height = height; + this.parent = null; + } + + BranchChunk.prototype = { + chunkSize: function() { return this.size }, + + removeInner: function(at, n) { + this.size -= n; + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var rm = Math.min(n, sz - at), oldHeight = child.height; + child.removeInner(at, rm); + this.height -= oldHeight - child.height; + if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } + if ((n -= rm) == 0) { break } + at = 0; + } else { at -= sz; } + } + // If the result is smaller than 25 lines, ensure that it is a + // single leaf node. + if (this.size - n < 25 && + (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { + var lines = []; + this.collapse(lines); + this.children = [new LeafChunk(lines)]; + this.children[0].parent = this; + } + }, + + collapse: function(lines) { + for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); } + }, + + insertInner: function(at, lines, height) { + this.size += lines.length; + this.height += height; + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at <= sz) { + child.insertInner(at, lines, height); + if (child.lines && child.lines.length > 50) { + // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. + // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. + var remaining = child.lines.length % 25 + 25; + for (var pos = remaining; pos < child.lines.length;) { + var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); + child.height -= leaf.height; + this.children.splice(++i, 0, leaf); + leaf.parent = this; + } + child.lines = child.lines.slice(0, remaining); + this.maybeSpill(); + } + break + } + at -= sz; + } + }, + + // When a node has grown, check whether it should be split. + maybeSpill: function() { + if (this.children.length <= 10) { return } + var me = this; + do { + var spilled = me.children.splice(me.children.length - 5, 5); + var sibling = new BranchChunk(spilled); + if (!me.parent) { // Become the parent node + var copy = new BranchChunk(me.children); + copy.parent = me; + me.children = [copy, sibling]; + me = copy; + } else { + me.size -= sibling.size; + me.height -= sibling.height; + var myIndex = indexOf(me.parent.children, me); + me.parent.children.splice(myIndex + 1, 0, sibling); + } + sibling.parent = me.parent; + } while (me.children.length > 10) + me.parent.maybeSpill(); + }, + + iterN: function(at, n, op) { + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var used = Math.min(n, sz - at); + if (child.iterN(at, used, op)) { return true } + if ((n -= used) == 0) { break } + at = 0; + } else { at -= sz; } + } + } + }; + + // Line widgets are block elements displayed above or below a line. + + var LineWidget = function(doc, node, options) { + if (options) { for (var opt in options) { if (options.hasOwnProperty(opt)) + { this[opt] = options[opt]; } } } + this.doc = doc; + this.node = node; + }; + + LineWidget.prototype.clear = function () { + var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); + if (no == null || !ws) { return } + for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } } + if (!ws.length) { line.widgets = null; } + var height = widgetHeight(this); + updateLineHeight(line, Math.max(0, line.height - height)); + if (cm) { + runInOp(cm, function () { + adjustScrollWhenAboveVisible(cm, line, -height); + regLineChange(cm, no, "widget"); + }); + signalLater(cm, "lineWidgetCleared", cm, this, no); + } + }; + + LineWidget.prototype.changed = function () { + var this$1 = this; + + var oldH = this.height, cm = this.doc.cm, line = this.line; + this.height = null; + var diff = widgetHeight(this) - oldH; + if (!diff) { return } + if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); } + if (cm) { + runInOp(cm, function () { + cm.curOp.forceUpdate = true; + adjustScrollWhenAboveVisible(cm, line, diff); + signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line)); + }); + } + }; + eventMixin(LineWidget); + + function adjustScrollWhenAboveVisible(cm, line, diff) { + if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) + { addToScrollTop(cm, diff); } + } + + function addLineWidget(doc, handle, node, options) { + var widget = new LineWidget(doc, node, options); + var cm = doc.cm; + if (cm && widget.noHScroll) { cm.display.alignWidgets = true; } + changeLine(doc, handle, "widget", function (line) { + var widgets = line.widgets || (line.widgets = []); + if (widget.insertAt == null) { widgets.push(widget); } + else { widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); } + widget.line = line; + if (cm && !lineIsHidden(doc, line)) { + var aboveVisible = heightAtLine(line) < doc.scrollTop; + updateLineHeight(line, line.height + widgetHeight(widget)); + if (aboveVisible) { addToScrollTop(cm, widget.height); } + cm.curOp.forceUpdate = true; + } + return true + }); + if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); } + return widget + } + + // TEXTMARKERS + + // Created with markText and setBookmark methods. A TextMarker is a + // handle that can be used to clear or find a marked position in the + // document. Line objects hold arrays (markedSpans) containing + // {from, to, marker} object pointing to such marker objects, and + // indicating that such a marker is present on that line. Multiple + // lines may point to the same marker when it spans across lines. + // The spans will have null for their from/to properties when the + // marker continues beyond the start/end of the line. Markers have + // links back to the lines they currently touch. + + // Collapsed markers have unique ids, in order to be able to order + // them, which is needed for uniquely determining an outer marker + // when they overlap (they may nest, but not partially overlap). + var nextMarkerId = 0; + + var TextMarker = function(doc, type) { + this.lines = []; + this.type = type; + this.doc = doc; + this.id = ++nextMarkerId; + }; + + // Clear the marker. + TextMarker.prototype.clear = function () { + if (this.explicitlyCleared) { return } + var cm = this.doc.cm, withOp = cm && !cm.curOp; + if (withOp) { startOperation(cm); } + if (hasHandler(this, "clear")) { + var found = this.find(); + if (found) { signalLater(this, "clear", found.from, found.to); } + } + var min = null, max = null; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); } + else if (cm) { + if (span.to != null) { max = lineNo(line); } + if (span.from != null) { min = lineNo(line); } + } + line.markedSpans = removeMarkedSpan(line.markedSpans, span); + if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) + { updateLineHeight(line, textHeight(cm.display)); } + } + if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) { + var visual = visualLine(this.lines[i$1]), len = lineLength(visual); + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual; + cm.display.maxLineLength = len; + cm.display.maxLineChanged = true; + } + } } + + if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); } + this.lines.length = 0; + this.explicitlyCleared = true; + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false; + if (cm) { reCheckSelection(cm.doc); } + } + if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); } + if (withOp) { endOperation(cm); } + if (this.parent) { this.parent.clear(); } + }; + + // Find the position of the marker in the document. Returns a {from, + // to} object by default. Side can be passed to get a specific side + // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the + // Pos objects returned contain a line object, rather than a line + // number (used to prevent looking up the same line twice). + TextMarker.prototype.find = function (side, lineObj) { + if (side == null && this.type == "bookmark") { side = 1; } + var from, to; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from); + if (side == -1) { return from } + } + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to); + if (side == 1) { return to } + } + } + return from && {from: from, to: to} + }; + + // Signals that the marker's widget changed, and surrounding layout + // should be recomputed. + TextMarker.prototype.changed = function () { + var this$1 = this; + + var pos = this.find(-1, true), widget = this, cm = this.doc.cm; + if (!pos || !cm) { return } + runInOp(cm, function () { + var line = pos.line, lineN = lineNo(pos.line); + var view = findViewForLine(cm, lineN); + if (view) { + clearLineMeasurementCacheFor(view); + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; + } + cm.curOp.updateMaxLine = true; + if (!lineIsHidden(widget.doc, line) && widget.height != null) { + var oldHeight = widget.height; + widget.height = null; + var dHeight = widgetHeight(widget) - oldHeight; + if (dHeight) + { updateLineHeight(line, line.height + dHeight); } + } + signalLater(cm, "markerChanged", cm, this$1); + }); + }; + + TextMarker.prototype.attachLine = function (line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) + { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); } + } + this.lines.push(line); + }; + + TextMarker.prototype.detachLine = function (line) { + this.lines.splice(indexOf(this.lines, line), 1); + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp + ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); + } + }; + eventMixin(TextMarker); + + // Create a marker, wire it up to the right lines, and + function markText(doc, from, to, options, type) { + // Shared markers (across linked documents) are handled separately + // (markTextShared will call out to this again, once per + // document). + if (options && options.shared) { return markTextShared(doc, from, to, options, type) } + // Ensure we are in an operation. + if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) } + + var marker = new TextMarker(doc, type), diff = cmp(from, to); + if (options) { copyObj(options, marker, false); } + // Don't connect empty markers unless clearWhenEmpty is false + if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) + { return marker } + if (marker.replacedWith) { + // Showing up as a widget implies collapsed (widget replaces text) + marker.collapsed = true; + marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); + if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); } + if (options.insertLeft) { marker.widgetNode.insertLeft = true; } + } + if (marker.collapsed) { + if (conflictingCollapsedRange(doc, from.line, from, to, marker) || + from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) + { throw new Error("Inserting collapsed marker partially overlapping an existing one") } + seeCollapsedSpans(); + } + + if (marker.addToHistory) + { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); } + + var curLine = from.line, cm = doc.cm, updateMaxLine; + doc.iter(curLine, to.line + 1, function (line) { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) + { updateMaxLine = true; } + if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); } + addMarkedSpan(line, new MarkedSpan(marker, + curLine == from.line ? from.ch : null, + curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp); + ++curLine; + }); + // lineIsHidden depends on the presence of the spans, so needs a second pass + if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) { + if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); } + }); } + + if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); } + + if (marker.readOnly) { + seeReadOnlySpans(); + if (doc.history.done.length || doc.history.undone.length) + { doc.clearHistory(); } + } + if (marker.collapsed) { + marker.id = ++nextMarkerId; + marker.atomic = true; + } + if (cm) { + // Sync editor state + if (updateMaxLine) { cm.curOp.updateMaxLine = true; } + if (marker.collapsed) + { regChange(cm, from.line, to.line + 1); } + else if (marker.className || marker.startStyle || marker.endStyle || marker.css || + marker.attributes || marker.title) + { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } } + if (marker.atomic) { reCheckSelection(cm.doc); } + signalLater(cm, "markerAdded", cm, marker); + } + return marker + } + + // SHARED TEXTMARKERS + + // A shared marker spans multiple linked documents. It is + // implemented as a meta-marker-object controlling multiple normal + // markers. + var SharedTextMarker = function(markers, primary) { + this.markers = markers; + this.primary = primary; + for (var i = 0; i < markers.length; ++i) + { markers[i].parent = this; } + }; + + SharedTextMarker.prototype.clear = function () { + if (this.explicitlyCleared) { return } + this.explicitlyCleared = true; + for (var i = 0; i < this.markers.length; ++i) + { this.markers[i].clear(); } + signalLater(this, "clear"); + }; + + SharedTextMarker.prototype.find = function (side, lineObj) { + return this.primary.find(side, lineObj) + }; + eventMixin(SharedTextMarker); + + function markTextShared(doc, from, to, options, type) { + options = copyObj(options); + options.shared = false; + var markers = [markText(doc, from, to, options, type)], primary = markers[0]; + var widget = options.widgetNode; + linkedDocs(doc, function (doc) { + if (widget) { options.widgetNode = widget.cloneNode(true); } + markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); + for (var i = 0; i < doc.linked.length; ++i) + { if (doc.linked[i].isParent) { return } } + primary = lst(markers); + }); + return new SharedTextMarker(markers, primary) + } + + function findSharedMarkers(doc) { + return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; }) + } + + function copySharedMarkers(doc, markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], pos = marker.find(); + var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); + if (cmp(mFrom, mTo)) { + var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); + marker.markers.push(subMark); + subMark.parent = marker; + } + } + } + + function detachSharedMarkers(markers) { + var loop = function ( i ) { + var marker = markers[i], linked = [marker.primary.doc]; + linkedDocs(marker.primary.doc, function (d) { return linked.push(d); }); + for (var j = 0; j < marker.markers.length; j++) { + var subMarker = marker.markers[j]; + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null; + marker.markers.splice(j--, 1); + } + } + }; + + for (var i = 0; i < markers.length; i++) loop( i ); + } + + var nextDocId = 0; + var Doc = function(text, mode, firstLine, lineSep, direction) { + if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) } + if (firstLine == null) { firstLine = 0; } + + BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); + this.first = firstLine; + this.scrollTop = this.scrollLeft = 0; + this.cantEdit = false; + this.cleanGeneration = 1; + this.modeFrontier = this.highlightFrontier = firstLine; + var start = Pos(firstLine, 0); + this.sel = simpleSelection(start); + this.history = new History(null); + this.id = ++nextDocId; + this.modeOption = mode; + this.lineSep = lineSep; + this.direction = (direction == "rtl") ? "rtl" : "ltr"; + this.extend = false; + + if (typeof text == "string") { text = this.splitLines(text); } + updateDoc(this, {from: start, to: start, text: text}); + setSelection(this, simpleSelection(start), sel_dontScroll); + }; + + Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + // Iterate over the document. Supports two forms -- with only one + // argument, it calls that for each line in the document. With + // three, it iterates over the range given by the first two (with + // the second being non-inclusive). + iter: function(from, to, op) { + if (op) { this.iterN(from - this.first, to - from, op); } + else { this.iterN(this.first, this.first + this.size, from); } + }, + + // Non-public interface for adding and removing lines. + insert: function(at, lines) { + var height = 0; + for (var i = 0; i < lines.length; ++i) { height += lines[i].height; } + this.insertInner(at - this.first, lines, height); + }, + remove: function(at, n) { this.removeInner(at - this.first, n); }, + + // From here, the methods are part of the public interface. Most + // are also available from CodeMirror (editor) instances. + + getValue: function(lineSep) { + var lines = getLines(this, this.first, this.first + this.size); + if (lineSep === false) { return lines } + return lines.join(lineSep || this.lineSeparator()) + }, + setValue: docMethodOp(function(code) { + var top = Pos(this.first, 0), last = this.first + this.size - 1; + makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), + text: this.splitLines(code), origin: "setValue", full: true}, true); + if (this.cm) { scrollToCoords(this.cm, 0, 0); } + setSelection(this, simpleSelection(top), sel_dontScroll); + }), + replaceRange: function(code, from, to, origin) { + from = clipPos(this, from); + to = to ? clipPos(this, to) : from; + replaceRange(this, code, from, to, origin); + }, + getRange: function(from, to, lineSep) { + var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); + if (lineSep === false) { return lines } + if (lineSep === '') { return lines.join('') } + return lines.join(lineSep || this.lineSeparator()) + }, + + getLine: function(line) {var l = this.getLineHandle(line); return l && l.text}, + + getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }}, + getLineNumber: function(line) {return lineNo(line)}, + + getLineHandleVisualStart: function(line) { + if (typeof line == "number") { line = getLine(this, line); } + return visualLine(line) + }, + + lineCount: function() {return this.size}, + firstLine: function() {return this.first}, + lastLine: function() {return this.first + this.size - 1}, + + clipPos: function(pos) {return clipPos(this, pos)}, + + getCursor: function(start) { + var range = this.sel.primary(), pos; + if (start == null || start == "head") { pos = range.head; } + else if (start == "anchor") { pos = range.anchor; } + else if (start == "end" || start == "to" || start === false) { pos = range.to(); } + else { pos = range.from(); } + return pos + }, + listSelections: function() { return this.sel.ranges }, + somethingSelected: function() {return this.sel.somethingSelected()}, + + setCursor: docMethodOp(function(line, ch, options) { + setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); + }), + setSelection: docMethodOp(function(anchor, head, options) { + setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); + }), + extendSelection: docMethodOp(function(head, other, options) { + extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); + }), + extendSelections: docMethodOp(function(heads, options) { + extendSelections(this, clipPosArray(this, heads), options); + }), + extendSelectionsBy: docMethodOp(function(f, options) { + var heads = map(this.sel.ranges, f); + extendSelections(this, clipPosArray(this, heads), options); + }), + setSelections: docMethodOp(function(ranges, primary, options) { + if (!ranges.length) { return } + var out = []; + for (var i = 0; i < ranges.length; i++) + { out[i] = new Range(clipPos(this, ranges[i].anchor), + clipPos(this, ranges[i].head || ranges[i].anchor)); } + if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); } + setSelection(this, normalizeSelection(this.cm, out, primary), options); + }), + addSelection: docMethodOp(function(anchor, head, options) { + var ranges = this.sel.ranges.slice(0); + ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); + setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options); + }), + + getSelection: function(lineSep) { + var ranges = this.sel.ranges, lines; + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this, ranges[i].from(), ranges[i].to()); + lines = lines ? lines.concat(sel) : sel; + } + if (lineSep === false) { return lines } + else { return lines.join(lineSep || this.lineSeparator()) } + }, + getSelections: function(lineSep) { + var parts = [], ranges = this.sel.ranges; + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this, ranges[i].from(), ranges[i].to()); + if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); } + parts[i] = sel; + } + return parts + }, + replaceSelection: function(code, collapse, origin) { + var dup = []; + for (var i = 0; i < this.sel.ranges.length; i++) + { dup[i] = code; } + this.replaceSelections(dup, collapse, origin || "+input"); + }, + replaceSelections: docMethodOp(function(code, collapse, origin) { + var changes = [], sel = this.sel; + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i]; + changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin}; + } + var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); + for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) + { makeChange(this, changes[i$1]); } + if (newSel) { setSelectionReplaceHistory(this, newSel); } + else if (this.cm) { ensureCursorVisible(this.cm); } + }), + undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), + redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), + undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), + redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), + + setExtending: function(val) {this.extend = val;}, + getExtending: function() {return this.extend}, + + historySize: function() { + var hist = this.history, done = 0, undone = 0; + for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } } + for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } } + return {undo: done, redo: undone} + }, + clearHistory: function() { + var this$1 = this; + + this.history = new History(this.history); + linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true); + }, + + markClean: function() { + this.cleanGeneration = this.changeGeneration(true); + }, + changeGeneration: function(forceSplit) { + if (forceSplit) + { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; } + return this.history.generation + }, + isClean: function (gen) { + return this.history.generation == (gen || this.cleanGeneration) + }, + + getHistory: function() { + return {done: copyHistoryArray(this.history.done), + undone: copyHistoryArray(this.history.undone)} + }, + setHistory: function(histData) { + var hist = this.history = new History(this.history); + hist.done = copyHistoryArray(histData.done.slice(0), null, true); + hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); + }, + + setGutterMarker: docMethodOp(function(line, gutterID, value) { + return changeLine(this, line, "gutter", function (line) { + var markers = line.gutterMarkers || (line.gutterMarkers = {}); + markers[gutterID] = value; + if (!value && isEmpty(markers)) { line.gutterMarkers = null; } + return true + }) + }), + + clearGutter: docMethodOp(function(gutterID) { + var this$1 = this; + + this.iter(function (line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + changeLine(this$1, line, "gutter", function () { + line.gutterMarkers[gutterID] = null; + if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; } + return true + }); + } + }); + }), + + lineInfo: function(line) { + var n; + if (typeof line == "number") { + if (!isLine(this, line)) { return null } + n = line; + line = getLine(this, line); + if (!line) { return null } + } else { + n = lineNo(line); + if (n == null) { return null } + } + return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, + textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, + widgets: line.widgets} + }, + + addLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass"; + if (!line[prop]) { line[prop] = cls; } + else if (classTest(cls).test(line[prop])) { return false } + else { line[prop] += " " + cls; } + return true + }) + }), + removeLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass"; + var cur = line[prop]; + if (!cur) { return false } + else if (cls == null) { line[prop] = null; } + else { + var found = cur.match(classTest(cls)); + if (!found) { return false } + var end = found.index + found[0].length; + line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; + } + return true + }) + }), + + addLineWidget: docMethodOp(function(handle, node, options) { + return addLineWidget(this, handle, node, options) + }), + removeLineWidget: function(widget) { widget.clear(); }, + + markText: function(from, to, options) { + return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range") + }, + setBookmark: function(pos, options) { + var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft, + clearWhenEmpty: false, shared: options && options.shared, + handleMouseEvents: options && options.handleMouseEvents}; + pos = clipPos(this, pos); + return markText(this, pos, pos, realOpts, "bookmark") + }, + findMarksAt: function(pos) { + pos = clipPos(this, pos); + var markers = [], spans = getLine(this, pos.line).markedSpans; + if (spans) { for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if ((span.from == null || span.from <= pos.ch) && + (span.to == null || span.to >= pos.ch)) + { markers.push(span.marker.parent || span.marker); } + } } + return markers + }, + findMarks: function(from, to, filter) { + from = clipPos(this, from); to = clipPos(this, to); + var found = [], lineNo = from.line; + this.iter(from.line, to.line + 1, function (line) { + var spans = line.markedSpans; + if (spans) { for (var i = 0; i < spans.length; i++) { + var span = spans[i]; + if (!(span.to != null && lineNo == from.line && from.ch >= span.to || + span.from == null && lineNo != from.line || + span.from != null && lineNo == to.line && span.from >= to.ch) && + (!filter || filter(span.marker))) + { found.push(span.marker.parent || span.marker); } + } } + ++lineNo; + }); + return found + }, + getAllMarks: function() { + var markers = []; + this.iter(function (line) { + var sps = line.markedSpans; + if (sps) { for (var i = 0; i < sps.length; ++i) + { if (sps[i].from != null) { markers.push(sps[i].marker); } } } + }); + return markers + }, + + posFromIndex: function(off) { + var ch, lineNo = this.first, sepSize = this.lineSeparator().length; + this.iter(function (line) { + var sz = line.text.length + sepSize; + if (sz > off) { ch = off; return true } + off -= sz; + ++lineNo; + }); + return clipPos(this, Pos(lineNo, ch)) + }, + indexFromPos: function (coords) { + coords = clipPos(this, coords); + var index = coords.ch; + if (coords.line < this.first || coords.ch < 0) { return 0 } + var sepSize = this.lineSeparator().length; + this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value + index += line.text.length + sepSize; + }); + return index + }, + + copy: function(copyHistory) { + var doc = new Doc(getLines(this, this.first, this.first + this.size), + this.modeOption, this.first, this.lineSep, this.direction); + doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; + doc.sel = this.sel; + doc.extend = false; + if (copyHistory) { + doc.history.undoDepth = this.history.undoDepth; + doc.setHistory(this.getHistory()); + } + return doc + }, + + linkedDoc: function(options) { + if (!options) { options = {}; } + var from = this.first, to = this.first + this.size; + if (options.from != null && options.from > from) { from = options.from; } + if (options.to != null && options.to < to) { to = options.to; } + var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); + if (options.sharedHist) { copy.history = this.history + ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); + copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; + copySharedMarkers(copy, findSharedMarkers(this)); + return copy + }, + unlinkDoc: function(other) { + if (other instanceof CodeMirror) { other = other.doc; } + if (this.linked) { for (var i = 0; i < this.linked.length; ++i) { + var link = this.linked[i]; + if (link.doc != other) { continue } + this.linked.splice(i, 1); + other.unlinkDoc(this); + detachSharedMarkers(findSharedMarkers(this)); + break + } } + // If the histories were shared, split them again + if (other.history == this.history) { + var splitIds = [other.id]; + linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true); + other.history = new History(null); + other.history.done = copyHistoryArray(this.history.done, splitIds); + other.history.undone = copyHistoryArray(this.history.undone, splitIds); + } + }, + iterLinkedDocs: function(f) {linkedDocs(this, f);}, + + getMode: function() {return this.mode}, + getEditor: function() {return this.cm}, + + splitLines: function(str) { + if (this.lineSep) { return str.split(this.lineSep) } + return splitLinesAuto(str) + }, + lineSeparator: function() { return this.lineSep || "\n" }, + + setDirection: docMethodOp(function (dir) { + if (dir != "rtl") { dir = "ltr"; } + if (dir == this.direction) { return } + this.direction = dir; + this.iter(function (line) { return line.order = null; }); + if (this.cm) { directionChanged(this.cm); } + }) + }); + + // Public alias. + Doc.prototype.eachLine = Doc.prototype.iter; + + // Kludge to work around strange IE behavior where it'll sometimes + // re-fire a series of drag-related events right after the drop (#1551) + var lastDrop = 0; + + function onDrop(e) { + var cm = this; + clearDragCursor(cm); + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) + { return } + e_preventDefault(e); + if (ie) { lastDrop = +new Date; } + var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; + if (!pos || cm.isReadOnly()) { return } + // Might be a file drop, in which case we simply extract the text + // and insert it. + if (files && files.length && window.FileReader && window.File) { + var n = files.length, text = Array(n), read = 0; + var markAsReadAndPasteIfAllFilesAreRead = function () { + if (++read == n) { + operation(cm, function () { + pos = clipPos(cm.doc, pos); + var change = {from: pos, to: pos, + text: cm.doc.splitLines( + text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())), + origin: "paste"}; + makeChange(cm.doc, change); + setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change)))); + })(); + } + }; + var readTextFromFile = function (file, i) { + if (cm.options.allowDropFileTypes && + indexOf(cm.options.allowDropFileTypes, file.type) == -1) { + markAsReadAndPasteIfAllFilesAreRead(); + return + } + var reader = new FileReader; + reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); }; + reader.onload = function () { + var content = reader.result; + if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { + markAsReadAndPasteIfAllFilesAreRead(); + return + } + text[i] = content; + markAsReadAndPasteIfAllFilesAreRead(); + }; + reader.readAsText(file); + }; + for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); } + } else { // Normal drop + // Don't do a replace if the drop happened inside of the selected text. + if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { + cm.state.draggingText(e); + // Ensure the editor is re-focused + setTimeout(function () { return cm.display.input.focus(); }, 20); + return + } + try { + var text$1 = e.dataTransfer.getData("Text"); + if (text$1) { + var selected; + if (cm.state.draggingText && !cm.state.draggingText.copy) + { selected = cm.listSelections(); } + setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); + if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1) + { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } } + cm.replaceSelection(text$1, "around", "paste"); + cm.display.input.focus(); + } + } + catch(e$1){} + } + } + + function onDragStart(cm, e) { + if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return } + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } + + e.dataTransfer.setData("Text", cm.getSelection()); + e.dataTransfer.effectAllowed = "copyMove"; + + // Use dummy image instead of default browsers image. + // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. + if (e.dataTransfer.setDragImage && !safari) { + var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); + img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; + if (presto) { + img.width = img.height = 1; + cm.display.wrapper.appendChild(img); + // Force a relayout, or Opera won't use our image for some obscure reason + img._top = img.offsetTop; + } + e.dataTransfer.setDragImage(img, 0, 0); + if (presto) { img.parentNode.removeChild(img); } + } + } + + function onDragOver(cm, e) { + var pos = posFromMouse(cm, e); + if (!pos) { return } + var frag = document.createDocumentFragment(); + drawSelectionCursor(cm, pos, frag); + if (!cm.display.dragCursor) { + cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); + cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); + } + removeChildrenAndAdd(cm.display.dragCursor, frag); + } + + function clearDragCursor(cm) { + if (cm.display.dragCursor) { + cm.display.lineSpace.removeChild(cm.display.dragCursor); + cm.display.dragCursor = null; + } + } + + // These must be handled carefully, because naively registering a + // handler for each editor will cause the editors to never be + // garbage collected. + + function forEachCodeMirror(f) { + if (!document.getElementsByClassName) { return } + var byClass = document.getElementsByClassName("CodeMirror"), editors = []; + for (var i = 0; i < byClass.length; i++) { + var cm = byClass[i].CodeMirror; + if (cm) { editors.push(cm); } + } + if (editors.length) { editors[0].operation(function () { + for (var i = 0; i < editors.length; i++) { f(editors[i]); } + }); } + } + + var globalsRegistered = false; + function ensureGlobalHandlers() { + if (globalsRegistered) { return } + registerGlobalHandlers(); + globalsRegistered = true; + } + function registerGlobalHandlers() { + // When the window resizes, we need to refresh active editors. + var resizeTimer; + on(window, "resize", function () { + if (resizeTimer == null) { resizeTimer = setTimeout(function () { + resizeTimer = null; + forEachCodeMirror(onResize); + }, 100); } + }); + // When the window loses focus, we want to show the editor as blurred + on(window, "blur", function () { return forEachCodeMirror(onBlur); }); + } + // Called when the window resizes + function onResize(cm) { + var d = cm.display; + // Might be a text scaling operation, clear size caches. + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + d.scrollbarsClipped = false; + cm.setSize(); + } + + var keyNames = { + 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", + 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", + 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", + 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", + 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock", + 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", + 221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", + 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" + }; + + // Number keys + for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); } + // Alphabetic keys + for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); } + // Function keys + for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; } + + var keyMap = {}; + + keyMap.basic = { + "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", + "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", + "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", + "Tab": "defaultTab", "Shift-Tab": "indentAuto", + "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", + "Esc": "singleSelection" + }; + // Note that the save and find-related commands aren't defined by + // default. User code or addons can define them. Unknown commands + // are simply ignored. + keyMap.pcDefault = { + "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", + "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", + "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", + "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", + "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", + "fallthrough": "basic" + }; + // Very basic readline/emacs-style bindings, which are standard on Mac. + keyMap.emacsy = { + "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", + "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", + "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", + "Ctrl-T": "transposeChars", "Ctrl-O": "openLine" + }; + keyMap.macDefault = { + "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", + "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", + "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", + "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", + "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", + "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", + "fallthrough": ["basic", "emacsy"] + }; + keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; + + // KEYMAP DISPATCH + + function normalizeKeyName(name) { + var parts = name.split(/-(?!$)/); + name = parts[parts.length - 1]; + var alt, ctrl, shift, cmd; + for (var i = 0; i < parts.length - 1; i++) { + var mod = parts[i]; + if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; } + else if (/^a(lt)?$/i.test(mod)) { alt = true; } + else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; } + else if (/^s(hift)?$/i.test(mod)) { shift = true; } + else { throw new Error("Unrecognized modifier name: " + mod) } + } + if (alt) { name = "Alt-" + name; } + if (ctrl) { name = "Ctrl-" + name; } + if (cmd) { name = "Cmd-" + name; } + if (shift) { name = "Shift-" + name; } + return name + } + + // This is a kludge to keep keymaps mostly working as raw objects + // (backwards compatibility) while at the same time support features + // like normalization and multi-stroke key bindings. It compiles a + // new normalized keymap, and then updates the old object to reflect + // this. + function normalizeKeyMap(keymap) { + var copy = {}; + for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) { + var value = keymap[keyname]; + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue } + if (value == "...") { delete keymap[keyname]; continue } + + var keys = map(keyname.split(" "), normalizeKeyName); + for (var i = 0; i < keys.length; i++) { + var val = (void 0), name = (void 0); + if (i == keys.length - 1) { + name = keys.join(" "); + val = value; + } else { + name = keys.slice(0, i + 1).join(" "); + val = "..."; + } + var prev = copy[name]; + if (!prev) { copy[name] = val; } + else if (prev != val) { throw new Error("Inconsistent bindings for " + name) } + } + delete keymap[keyname]; + } } + for (var prop in copy) { keymap[prop] = copy[prop]; } + return keymap + } + + function lookupKey(key, map, handle, context) { + map = getKeyMap(map); + var found = map.call ? map.call(key, context) : map[key]; + if (found === false) { return "nothing" } + if (found === "...") { return "multi" } + if (found != null && handle(found)) { return "handled" } + + if (map.fallthrough) { + if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") + { return lookupKey(key, map.fallthrough, handle, context) } + for (var i = 0; i < map.fallthrough.length; i++) { + var result = lookupKey(key, map.fallthrough[i], handle, context); + if (result) { return result } + } + } + } + + // Modifier key presses don't count as 'real' key presses for the + // purpose of keymap fallthrough. + function isModifierKey(value) { + var name = typeof value == "string" ? value : keyNames[value.keyCode]; + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" + } + + function addModifierNames(name, event, noShift) { + var base = name; + if (event.altKey && base != "Alt") { name = "Alt-" + name; } + if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; } + if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; } + if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; } + return name + } + + // Look up the name of a key as indicated by an event object. + function keyName(event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) { return false } + var name = keyNames[event.keyCode]; + if (name == null || event.altGraphKey) { return false } + // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause, + // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+) + if (event.keyCode == 3 && event.code) { name = event.code; } + return addModifierNames(name, event, noShift) + } + + function getKeyMap(val) { + return typeof val == "string" ? keyMap[val] : val + } + + // Helper for deleting text near the selection(s), used to implement + // backspace, delete, and similar functionality. + function deleteNearSelection(cm, compute) { + var ranges = cm.doc.sel.ranges, kill = []; + // Build up a set of ranges to kill first, merging overlapping + // ranges. + for (var i = 0; i < ranges.length; i++) { + var toKill = compute(ranges[i]); + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + var replaced = kill.pop(); + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from; + break + } + } + kill.push(toKill); + } + // Next, remove those actual ranges. + runInOp(cm, function () { + for (var i = kill.length - 1; i >= 0; i--) + { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); } + ensureCursorVisible(cm); + }); + } + + function moveCharLogically(line, ch, dir) { + var target = skipExtendingChars(line.text, ch + dir, dir); + return target < 0 || target > line.text.length ? null : target + } + + function moveLogically(line, start, dir) { + var ch = moveCharLogically(line, start.ch, dir); + return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before") + } + + function endOfLine(visually, cm, lineObj, lineNo, dir) { + if (visually) { + if (cm.doc.direction == "rtl") { dir = -dir; } + var order = getOrder(lineObj, cm.doc.direction); + if (order) { + var part = dir < 0 ? lst(order) : order[0]; + var moveInStorageOrder = (dir < 0) == (part.level == 1); + var sticky = moveInStorageOrder ? "after" : "before"; + var ch; + // With a wrapped rtl chunk (possibly spanning multiple bidi parts), + // it could be that the last bidi part is not on the last visual line, + // since visual lines contain content order-consecutive chunks. + // Thus, in rtl, we are looking for the first (content-order) character + // in the rtl chunk that is on the last line (that is, the same line + // as the last (content-order) character). + if (part.level > 0 || cm.doc.direction == "rtl") { + var prep = prepareMeasureForLine(cm, lineObj); + ch = dir < 0 ? lineObj.text.length - 1 : 0; + var targetTop = measureCharPrepared(cm, prep, ch).top; + ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch); + if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); } + } else { ch = dir < 0 ? part.to : part.from; } + return new Pos(lineNo, ch, sticky) + } + } + return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after") + } + + function moveVisually(cm, line, start, dir) { + var bidi = getOrder(line, cm.doc.direction); + if (!bidi) { return moveLogically(line, start, dir) } + if (start.ch >= line.text.length) { + start.ch = line.text.length; + start.sticky = "before"; + } else if (start.ch <= 0) { + start.ch = 0; + start.sticky = "after"; + } + var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]; + if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { + // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines, + // nothing interesting happens. + return moveLogically(line, start, dir) + } + + var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }; + var prep; + var getWrappedLineExtent = function (ch) { + if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} } + prep = prep || prepareMeasureForLine(cm, line); + return wrappedLineExtentChar(cm, line, prep, ch) + }; + var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); + + if (cm.doc.direction == "rtl" || part.level == 1) { + var moveInStorageOrder = (part.level == 1) == (dir < 0); + var ch = mv(start, moveInStorageOrder ? 1 : -1); + if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) { + // Case 2: We move within an rtl part or in an rtl editor on the same visual line + var sticky = moveInStorageOrder ? "before" : "after"; + return new Pos(start.line, ch, sticky) + } + } + + // Case 3: Could not move within this bidi part in this visual line, so leave + // the current bidi part + + var searchInVisualLine = function (partPos, dir, wrappedLineExtent) { + var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder + ? new Pos(start.line, mv(ch, 1), "before") + : new Pos(start.line, ch, "after"); }; + + for (; partPos >= 0 && partPos < bidi.length; partPos += dir) { + var part = bidi[partPos]; + var moveInStorageOrder = (dir > 0) == (part.level != 1); + var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1); + if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) } + ch = moveInStorageOrder ? part.from : mv(part.to, -1); + if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) } + } + }; + + // Case 3a: Look for other bidi parts on the same visual line + var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent); + if (res) { return res } + + // Case 3b: Look for other bidi parts on the next visual line + var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1); + if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { + res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); + if (res) { return res } + } + + // Case 4: Nowhere to move + return null + } + + // Commands are parameter-less actions that can be performed on an + // editor, mostly used for keybindings. + var commands = { + selectAll: selectAll, + singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); }, + killLine: function (cm) { return deleteNearSelection(cm, function (range) { + if (range.empty()) { + var len = getLine(cm.doc, range.head.line).text.length; + if (range.head.ch == len && range.head.line < cm.lastLine()) + { return {from: range.head, to: Pos(range.head.line + 1, 0)} } + else + { return {from: range.head, to: Pos(range.head.line, len)} } + } else { + return {from: range.from(), to: range.to()} + } + }); }, + deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({ + from: Pos(range.from().line, 0), + to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) + }); }); }, + delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({ + from: Pos(range.from().line, 0), to: range.from() + }); }); }, + delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + var leftPos = cm.coordsChar({left: 0, top: top}, "div"); + return {from: leftPos, to: range.from()} + }); }, + delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); + return {from: range.from(), to: rightPos } + }); }, + undo: function (cm) { return cm.undo(); }, + redo: function (cm) { return cm.redo(); }, + undoSelection: function (cm) { return cm.undoSelection(); }, + redoSelection: function (cm) { return cm.redoSelection(); }, + goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); }, + goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); }, + goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, + {origin: "+move", bias: 1} + ); }, + goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); }, + {origin: "+move", bias: 1} + ); }, + goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, + {origin: "+move", bias: -1} + ); }, + goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.cursorCoords(range.head, "div").top + 5; + return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") + }, sel_move); }, + goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.cursorCoords(range.head, "div").top + 5; + return cm.coordsChar({left: 0, top: top}, "div") + }, sel_move); }, + goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.cursorCoords(range.head, "div").top + 5; + var pos = cm.coordsChar({left: 0, top: top}, "div"); + if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) } + return pos + }, sel_move); }, + goLineUp: function (cm) { return cm.moveV(-1, "line"); }, + goLineDown: function (cm) { return cm.moveV(1, "line"); }, + goPageUp: function (cm) { return cm.moveV(-1, "page"); }, + goPageDown: function (cm) { return cm.moveV(1, "page"); }, + goCharLeft: function (cm) { return cm.moveH(-1, "char"); }, + goCharRight: function (cm) { return cm.moveH(1, "char"); }, + goColumnLeft: function (cm) { return cm.moveH(-1, "column"); }, + goColumnRight: function (cm) { return cm.moveH(1, "column"); }, + goWordLeft: function (cm) { return cm.moveH(-1, "word"); }, + goGroupRight: function (cm) { return cm.moveH(1, "group"); }, + goGroupLeft: function (cm) { return cm.moveH(-1, "group"); }, + goWordRight: function (cm) { return cm.moveH(1, "word"); }, + delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); }, + delCharAfter: function (cm) { return cm.deleteH(1, "char"); }, + delWordBefore: function (cm) { return cm.deleteH(-1, "word"); }, + delWordAfter: function (cm) { return cm.deleteH(1, "word"); }, + delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); }, + delGroupAfter: function (cm) { return cm.deleteH(1, "group"); }, + indentAuto: function (cm) { return cm.indentSelection("smart"); }, + indentMore: function (cm) { return cm.indentSelection("add"); }, + indentLess: function (cm) { return cm.indentSelection("subtract"); }, + insertTab: function (cm) { return cm.replaceSelection("\t"); }, + insertSoftTab: function (cm) { + var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; + for (var i = 0; i < ranges.length; i++) { + var pos = ranges[i].from(); + var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); + spaces.push(spaceStr(tabSize - col % tabSize)); + } + cm.replaceSelections(spaces); + }, + defaultTab: function (cm) { + if (cm.somethingSelected()) { cm.indentSelection("add"); } + else { cm.execCommand("insertTab"); } + }, + // Swap the two chars left and right of each selection's head. + // Move cursor behind the two swapped characters afterwards. + // + // Doesn't consider line feeds a character. + // Doesn't scan more than one line above to find a character. + // Doesn't do anything on an empty line. + // Doesn't do anything with non-empty selections. + transposeChars: function (cm) { return runInOp(cm, function () { + var ranges = cm.listSelections(), newSel = []; + for (var i = 0; i < ranges.length; i++) { + if (!ranges[i].empty()) { continue } + var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; + if (line) { + if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); } + if (cur.ch > 0) { + cur = new Pos(cur.line, cur.ch + 1); + cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), + Pos(cur.line, cur.ch - 2), cur, "+transpose"); + } else if (cur.line > cm.doc.first) { + var prev = getLine(cm.doc, cur.line - 1).text; + if (prev) { + cur = new Pos(cur.line, 1); + cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + + prev.charAt(prev.length - 1), + Pos(cur.line - 1, prev.length - 1), cur, "+transpose"); + } + } + } + newSel.push(new Range(cur, cur)); + } + cm.setSelections(newSel); + }); }, + newlineAndIndent: function (cm) { return runInOp(cm, function () { + var sels = cm.listSelections(); + for (var i = sels.length - 1; i >= 0; i--) + { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); } + sels = cm.listSelections(); + for (var i$1 = 0; i$1 < sels.length; i$1++) + { cm.indentLine(sels[i$1].from().line, null, true); } + ensureCursorVisible(cm); + }); }, + openLine: function (cm) { return cm.replaceSelection("\n", "start"); }, + toggleOverwrite: function (cm) { return cm.toggleOverwrite(); } + }; + + + function lineStart(cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLine(line); + if (visual != line) { lineN = lineNo(visual); } + return endOfLine(true, cm, visual, lineN, 1) + } + function lineEnd(cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLineEnd(line); + if (visual != line) { lineN = lineNo(visual); } + return endOfLine(true, cm, line, lineN, -1) + } + function lineStartSmart(cm, pos) { + var start = lineStart(cm, pos.line); + var line = getLine(cm.doc, start.line); + var order = getOrder(line, cm.doc.direction); + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(start.ch, line.text.search(/\S/)); + var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; + return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky) + } + return start + } + + // Run a handler that was bound to a key. + function doHandleBinding(cm, bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound]; + if (!bound) { return false } + } + // Ensure previous input has been read, so that the handler sees a + // consistent view of the document + cm.display.input.ensurePolled(); + var prevShift = cm.display.shift, done = false; + try { + if (cm.isReadOnly()) { cm.state.suppressEdits = true; } + if (dropShift) { cm.display.shift = false; } + done = bound(cm) != Pass; + } finally { + cm.display.shift = prevShift; + cm.state.suppressEdits = false; + } + return done + } + + function lookupKeyForEditor(cm, name, handle) { + for (var i = 0; i < cm.state.keyMaps.length; i++) { + var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); + if (result) { return result } + } + return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) + || lookupKey(name, cm.options.keyMap, handle, cm) + } + + // Note that, despite the name, this function is also used to check + // for bound mouse clicks. + + var stopSeq = new Delayed; + + function dispatchKey(cm, name, e, handle) { + var seq = cm.state.keySeq; + if (seq) { + if (isModifierKey(name)) { return "handled" } + if (/\'$/.test(name)) + { cm.state.keySeq = null; } + else + { stopSeq.set(50, function () { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null; + cm.display.input.reset(); + } + }); } + if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true } + } + return dispatchKeyInner(cm, name, e, handle) + } + + function dispatchKeyInner(cm, name, e, handle) { + var result = lookupKeyForEditor(cm, name, handle); + + if (result == "multi") + { cm.state.keySeq = name; } + if (result == "handled") + { signalLater(cm, "keyHandled", cm, name, e); } + + if (result == "handled" || result == "multi") { + e_preventDefault(e); + restartBlink(cm); + } + + return !!result + } + + // Handle a key from the keydown event. + function handleKeyBinding(cm, e) { + var name = keyName(e, true); + if (!name) { return false } + + if (e.shiftKey && !cm.state.keySeq) { + // First try to resolve full name (including 'Shift-'). Failing + // that, see if there is a cursor-motion command (starting with + // 'go') bound to the keyname without 'Shift-'. + return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); }) + || dispatchKey(cm, name, e, function (b) { + if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) + { return doHandleBinding(cm, b) } + }) + } else { + return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }) + } + } + + // Handle a key from the keypress event + function handleCharBinding(cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); }) + } + + var lastStoppedKey = null; + function onKeyDown(e) { + var cm = this; + if (e.target && e.target != cm.display.input.getField()) { return } + cm.curOp.focus = activeElt(); + if (signalDOMEvent(cm, e)) { return } + // IE does strange things with escape. + if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; } + var code = e.keyCode; + cm.display.shift = code == 16 || e.shiftKey; + var handled = handleKeyBinding(cm, e); + if (presto) { + lastStoppedKey = handled ? code : null; + // Opera has no cut event... we try to at least catch the key combo + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) + { cm.replaceSelection("", null, "cut"); } + } + if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) + { document.execCommand("cut"); } + + // Turn mouse into crosshair when Alt is held on Mac. + if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) + { showCrossHair(cm); } + } + + function showCrossHair(cm) { + var lineDiv = cm.display.lineDiv; + addClass(lineDiv, "CodeMirror-crosshair"); + + function up(e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair"); + off(document, "keyup", up); + off(document, "mouseover", up); + } + } + on(document, "keyup", up); + on(document, "mouseover", up); + } + + function onKeyUp(e) { + if (e.keyCode == 16) { this.doc.sel.shift = false; } + signalDOMEvent(this, e); + } + + function onKeyPress(e) { + var cm = this; + if (e.target && e.target != cm.display.input.getField()) { return } + if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return } + var keyCode = e.keyCode, charCode = e.charCode; + if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} + if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return } + var ch = String.fromCharCode(charCode == null ? keyCode : charCode); + // Some browsers fire keypress events for backspace + if (ch == "\x08") { return } + if (handleCharBinding(cm, e, ch)) { return } + cm.display.input.onKeyPress(e); + } + + var DOUBLECLICK_DELAY = 400; + + var PastClick = function(time, pos, button) { + this.time = time; + this.pos = pos; + this.button = button; + }; + + PastClick.prototype.compare = function (time, pos, button) { + return this.time + DOUBLECLICK_DELAY > time && + cmp(pos, this.pos) == 0 && button == this.button + }; + + var lastClick, lastDoubleClick; + function clickRepeat(pos, button) { + var now = +new Date; + if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { + lastClick = lastDoubleClick = null; + return "triple" + } else if (lastClick && lastClick.compare(now, pos, button)) { + lastDoubleClick = new PastClick(now, pos, button); + lastClick = null; + return "double" + } else { + lastClick = new PastClick(now, pos, button); + lastDoubleClick = null; + return "single" + } + } + + // A mouse down can be a single click, double click, triple click, + // start of selection drag, start of text drag, new cursor + // (ctrl-click), rectangle drag (alt-drag), or xwin + // middle-click-paste. Or it might be a click on something we should + // not interfere with, such as a scrollbar or widget. + function onMouseDown(e) { + var cm = this, display = cm.display; + if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return } + display.input.ensurePolled(); + display.shift = e.shiftKey; + + if (eventInWidget(display, e)) { + if (!webkit) { + // Briefly turn off draggability, to allow widgets to do + // normal dragging things. + display.scroller.draggable = false; + setTimeout(function () { return display.scroller.draggable = true; }, 100); + } + return + } + if (clickInGutter(cm, e)) { return } + var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single"; + window.focus(); + + // #3261: make sure, that we're not starting a second selection + if (button == 1 && cm.state.selectingText) + { cm.state.selectingText(e); } + + if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return } + + if (button == 1) { + if (pos) { leftButtonDown(cm, pos, repeat, e); } + else if (e_target(e) == display.scroller) { e_preventDefault(e); } + } else if (button == 2) { + if (pos) { extendSelection(cm.doc, pos); } + setTimeout(function () { return display.input.focus(); }, 20); + } else if (button == 3) { + if (captureRightClick) { cm.display.input.onContextMenu(e); } + else { delayBlurEvent(cm); } + } + } + + function handleMappedButton(cm, button, pos, repeat, event) { + var name = "Click"; + if (repeat == "double") { name = "Double" + name; } + else if (repeat == "triple") { name = "Triple" + name; } + name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; + + return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { + if (typeof bound == "string") { bound = commands[bound]; } + if (!bound) { return false } + var done = false; + try { + if (cm.isReadOnly()) { cm.state.suppressEdits = true; } + done = bound(cm, pos) != Pass; + } finally { + cm.state.suppressEdits = false; + } + return done + }) + } + + function configureMouse(cm, repeat, event) { + var option = cm.getOption("configureMouse"); + var value = option ? option(cm, repeat, event) : {}; + if (value.unit == null) { + var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; + value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; + } + if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; } + if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; } + if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); } + return value + } + + function leftButtonDown(cm, pos, repeat, event) { + if (ie) { setTimeout(bind(ensureFocus, cm), 0); } + else { cm.curOp.focus = activeElt(); } + + var behavior = configureMouse(cm, repeat, event); + + var sel = cm.doc.sel, contained; + if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && + repeat == "single" && (contained = sel.contains(pos)) > -1 && + (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && + (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) + { leftButtonStartDrag(cm, event, pos, behavior); } + else + { leftButtonSelect(cm, event, pos, behavior); } + } + + // Start a text drag. When it ends, see if any dragging actually + // happen, and treat as a click if it didn't. + function leftButtonStartDrag(cm, event, pos, behavior) { + var display = cm.display, moved = false; + var dragEnd = operation(cm, function (e) { + if (webkit) { display.scroller.draggable = false; } + cm.state.draggingText = false; + if (cm.state.delayingBlurEvent) { + if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; } + else { delayBlurEvent(cm); } + } + off(display.wrapper.ownerDocument, "mouseup", dragEnd); + off(display.wrapper.ownerDocument, "mousemove", mouseMove); + off(display.scroller, "dragstart", dragStart); + off(display.scroller, "drop", dragEnd); + if (!moved) { + e_preventDefault(e); + if (!behavior.addNew) + { extendSelection(cm.doc, pos, null, null, behavior.extend); } + // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) + if ((webkit && !safari) || ie && ie_version == 9) + { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); } + else + { display.input.focus(); } + } + }); + var mouseMove = function(e2) { + moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; + }; + var dragStart = function () { return moved = true; }; + // Let the drag handler handle this. + if (webkit) { display.scroller.draggable = true; } + cm.state.draggingText = dragEnd; + dragEnd.copy = !behavior.moveOnDrag; + on(display.wrapper.ownerDocument, "mouseup", dragEnd); + on(display.wrapper.ownerDocument, "mousemove", mouseMove); + on(display.scroller, "dragstart", dragStart); + on(display.scroller, "drop", dragEnd); + + cm.state.delayingBlurEvent = true; + setTimeout(function () { return display.input.focus(); }, 20); + // IE's approach to draggable + if (display.scroller.dragDrop) { display.scroller.dragDrop(); } + } + + function rangeForUnit(cm, pos, unit) { + if (unit == "char") { return new Range(pos, pos) } + if (unit == "word") { return cm.findWordAt(pos) } + if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) } + var result = unit(cm, pos); + return new Range(result.from, result.to) + } + + // Normal selection, as opposed to text dragging. + function leftButtonSelect(cm, event, start, behavior) { + if (ie) { delayBlurEvent(cm); } + var display = cm.display, doc = cm.doc; + e_preventDefault(event); + + var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; + if (behavior.addNew && !behavior.extend) { + ourIndex = doc.sel.contains(start); + if (ourIndex > -1) + { ourRange = ranges[ourIndex]; } + else + { ourRange = new Range(start, start); } + } else { + ourRange = doc.sel.primary(); + ourIndex = doc.sel.primIndex; + } + + if (behavior.unit == "rectangle") { + if (!behavior.addNew) { ourRange = new Range(start, start); } + start = posFromMouse(cm, event, true, true); + ourIndex = -1; + } else { + var range = rangeForUnit(cm, start, behavior.unit); + if (behavior.extend) + { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); } + else + { ourRange = range; } + } + + if (!behavior.addNew) { + ourIndex = 0; + setSelection(doc, new Selection([ourRange], 0), sel_mouse); + startSel = doc.sel; + } else if (ourIndex == -1) { + ourIndex = ranges.length; + setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), + {scroll: false, origin: "*mouse"}); + } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { + setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), + {scroll: false, origin: "*mouse"}); + startSel = doc.sel; + } else { + replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); + } + + var lastPos = start; + function extendTo(pos) { + if (cmp(lastPos, pos) == 0) { return } + lastPos = pos; + + if (behavior.unit == "rectangle") { + var ranges = [], tabSize = cm.options.tabSize; + var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); + var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); + var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); + for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); + line <= end; line++) { + var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); + if (left == right) + { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); } + else if (text.length > leftPos) + { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); } + } + if (!ranges.length) { ranges.push(new Range(start, start)); } + setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), + {origin: "*mouse", scroll: false}); + cm.scrollIntoView(pos); + } else { + var oldRange = ourRange; + var range = rangeForUnit(cm, pos, behavior.unit); + var anchor = oldRange.anchor, head; + if (cmp(range.anchor, anchor) > 0) { + head = range.head; + anchor = minPos(oldRange.from(), range.anchor); + } else { + head = range.anchor; + anchor = maxPos(oldRange.to(), range.head); + } + var ranges$1 = startSel.ranges.slice(0); + ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head)); + setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse); + } + } + + var editorSize = display.wrapper.getBoundingClientRect(); + // Used to ensure timeout re-tries don't fire when another extend + // happened in the meantime (clearTimeout isn't reliable -- at + // least on Chrome, the timeouts still happen even when cleared, + // if the clear happens after their scheduled firing time). + var counter = 0; + + function extend(e) { + var curCount = ++counter; + var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); + if (!cur) { return } + if (cmp(cur, lastPos) != 0) { + cm.curOp.focus = activeElt(); + extendTo(cur); + var visible = visibleLines(display, doc); + if (cur.line >= visible.to || cur.line < visible.from) + { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); } + } else { + var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; + if (outside) { setTimeout(operation(cm, function () { + if (counter != curCount) { return } + display.scroller.scrollTop += outside; + extend(e); + }), 50); } + } + } + + function done(e) { + cm.state.selectingText = false; + counter = Infinity; + // If e is null or undefined we interpret this as someone trying + // to explicitly cancel the selection rather than the user + // letting go of the mouse button. + if (e) { + e_preventDefault(e); + display.input.focus(); + } + off(display.wrapper.ownerDocument, "mousemove", move); + off(display.wrapper.ownerDocument, "mouseup", up); + doc.history.lastSelOrigin = null; + } + + var move = operation(cm, function (e) { + if (e.buttons === 0 || !e_button(e)) { done(e); } + else { extend(e); } + }); + var up = operation(cm, done); + cm.state.selectingText = up; + on(display.wrapper.ownerDocument, "mousemove", move); + on(display.wrapper.ownerDocument, "mouseup", up); + } + + // Used when mouse-selecting to adjust the anchor to the proper side + // of a bidi jump depending on the visual position of the head. + function bidiSimplify(cm, range) { + var anchor = range.anchor; + var head = range.head; + var anchorLine = getLine(cm.doc, anchor.line); + if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range } + var order = getOrder(anchorLine); + if (!order) { return range } + var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index]; + if (part.from != anchor.ch && part.to != anchor.ch) { return range } + var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1); + if (boundary == 0 || boundary == order.length) { return range } + + // Compute the relative visual position of the head compared to the + // anchor (<0 is to the left, >0 to the right) + var leftSide; + if (head.line != anchor.line) { + leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0; + } else { + var headIndex = getBidiPartAt(order, head.ch, head.sticky); + var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1); + if (headIndex == boundary - 1 || headIndex == boundary) + { leftSide = dir < 0; } + else + { leftSide = dir > 0; } + } + + var usePart = order[boundary + (leftSide ? -1 : 0)]; + var from = leftSide == (usePart.level == 1); + var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before"; + return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head) + } + + + // Determines whether an event happened in the gutter, and fires the + // handlers for the corresponding event. + function gutterEvent(cm, e, type, prevent) { + var mX, mY; + if (e.touches) { + mX = e.touches[0].clientX; + mY = e.touches[0].clientY; + } else { + try { mX = e.clientX; mY = e.clientY; } + catch(e$1) { return false } + } + if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false } + if (prevent) { e_preventDefault(e); } + + var display = cm.display; + var lineBox = display.lineDiv.getBoundingClientRect(); + + if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) } + mY -= lineBox.top - display.viewOffset; + + for (var i = 0; i < cm.display.gutterSpecs.length; ++i) { + var g = display.gutters.childNodes[i]; + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY); + var gutter = cm.display.gutterSpecs[i]; + signal(cm, type, cm, line, gutter.className, e); + return e_defaultPrevented(e) + } + } + } + + function clickInGutter(cm, e) { + return gutterEvent(cm, e, "gutterClick", true) + } + + // CONTEXT MENU HANDLING + + // To make the context menu work, we need to briefly unhide the + // textarea (making it as unobtrusive as possible) to let the + // right-click take effect on it. + function onContextMenu(cm, e) { + if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return } + if (signalDOMEvent(cm, e, "contextmenu")) { return } + if (!captureRightClick) { cm.display.input.onContextMenu(e); } + } + + function contextMenuInGutter(cm, e) { + if (!hasHandler(cm, "gutterContextMenu")) { return false } + return gutterEvent(cm, e, "gutterContextMenu", false) + } + + function themeChanged(cm) { + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); + clearCaches(cm); + } + + var Init = {toString: function(){return "CodeMirror.Init"}}; + + var defaults = {}; + var optionHandlers = {}; + + function defineOptions(CodeMirror) { + var optionHandlers = CodeMirror.optionHandlers; + + function option(name, deflt, handle, notOnInit) { + CodeMirror.defaults[name] = deflt; + if (handle) { optionHandlers[name] = + notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; } + } + + CodeMirror.defineOption = option; + + // Passed to option handlers when there is no old value. + CodeMirror.Init = Init; + + // These two are, on init, called from the constructor because they + // have to be initialized before the editor can start at all. + option("value", "", function (cm, val) { return cm.setValue(val); }, true); + option("mode", null, function (cm, val) { + cm.doc.modeOption = val; + loadMode(cm); + }, true); + + option("indentUnit", 2, loadMode, true); + option("indentWithTabs", false); + option("smartIndent", true); + option("tabSize", 4, function (cm) { + resetModeState(cm); + clearCaches(cm); + regChange(cm); + }, true); + + option("lineSeparator", null, function (cm, val) { + cm.doc.lineSep = val; + if (!val) { return } + var newBreaks = [], lineNo = cm.doc.first; + cm.doc.iter(function (line) { + for (var pos = 0;;) { + var found = line.text.indexOf(val, pos); + if (found == -1) { break } + pos = found + val.length; + newBreaks.push(Pos(lineNo, found)); + } + lineNo++; + }); + for (var i = newBreaks.length - 1; i >= 0; i--) + { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); } + }); + option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) { + cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); + if (old != Init) { cm.refresh(); } + }); + option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true); + option("electricChars", true); + option("inputStyle", mobile ? "contenteditable" : "textarea", function () { + throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME + }, true); + option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true); + option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true); + option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true); + option("rtlMoveVisually", !windows); + option("wholeLineUpdateBefore", true); + + option("theme", "default", function (cm) { + themeChanged(cm); + updateGutters(cm); + }, true); + option("keyMap", "default", function (cm, val, old) { + var next = getKeyMap(val); + var prev = old != Init && getKeyMap(old); + if (prev && prev.detach) { prev.detach(cm, next); } + if (next.attach) { next.attach(cm, prev || null); } + }); + option("extraKeys", null); + option("configureMouse", null); + + option("lineWrapping", false, wrappingChanged, true); + option("gutters", [], function (cm, val) { + cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers); + updateGutters(cm); + }, true); + option("fixedGutter", true, function (cm, val) { + cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; + cm.refresh(); + }, true); + option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true); + option("scrollbarStyle", "native", function (cm) { + initScrollbars(cm); + updateScrollbars(cm); + cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); + cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); + }, true); + option("lineNumbers", false, function (cm, val) { + cm.display.gutterSpecs = getGutters(cm.options.gutters, val); + updateGutters(cm); + }, true); + option("firstLineNumber", 1, updateGutters, true); + option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true); + option("showCursorWhenSelecting", false, updateSelection, true); + + option("resetSelectionOnContextMenu", true); + option("lineWiseCopyCut", true); + option("pasteLinesPerSelection", true); + option("selectionsMayTouch", false); + + option("readOnly", false, function (cm, val) { + if (val == "nocursor") { + onBlur(cm); + cm.display.input.blur(); + } + cm.display.input.readOnlyChanged(val); + }); + + option("screenReaderLabel", null, function (cm, val) { + val = (val === '') ? null : val; + cm.display.input.screenReaderLabelChanged(val); + }); + + option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true); + option("dragDrop", true, dragDropChanged); + option("allowDropFileTypes", null); + + option("cursorBlinkRate", 530); + option("cursorScrollMargin", 0); + option("cursorHeight", 1, updateSelection, true); + option("singleCursorHeightPerLine", true, updateSelection, true); + option("workTime", 100); + option("workDelay", 100); + option("flattenSpans", true, resetModeState, true); + option("addModeClass", false, resetModeState, true); + option("pollInterval", 100); + option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; }); + option("historyEventDelay", 1250); + option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true); + option("maxHighlightLength", 10000, resetModeState, true); + option("moveInputWithCursor", true, function (cm, val) { + if (!val) { cm.display.input.resetPosition(); } + }); + + option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; }); + option("autofocus", null); + option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true); + option("phrases", null); + } + + function dragDropChanged(cm, value, old) { + var wasOn = old && old != Init; + if (!value != !wasOn) { + var funcs = cm.display.dragFunctions; + var toggle = value ? on : off; + toggle(cm.display.scroller, "dragstart", funcs.start); + toggle(cm.display.scroller, "dragenter", funcs.enter); + toggle(cm.display.scroller, "dragover", funcs.over); + toggle(cm.display.scroller, "dragleave", funcs.leave); + toggle(cm.display.scroller, "drop", funcs.drop); + } + } + + function wrappingChanged(cm) { + if (cm.options.lineWrapping) { + addClass(cm.display.wrapper, "CodeMirror-wrap"); + cm.display.sizer.style.minWidth = ""; + cm.display.sizerWidth = null; + } else { + rmClass(cm.display.wrapper, "CodeMirror-wrap"); + findMaxLine(cm); + } + estimateLineHeights(cm); + regChange(cm); + clearCaches(cm); + setTimeout(function () { return updateScrollbars(cm); }, 100); + } + + // A CodeMirror instance represents an editor. This is the object + // that user code is usually dealing with. + + function CodeMirror(place, options) { + var this$1 = this; + + if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) } + + this.options = options = options ? copyObj(options) : {}; + // Determine effective options based on given values and defaults. + copyObj(defaults, options, false); + + var doc = options.value; + if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); } + else if (options.mode) { doc.modeOption = options.mode; } + this.doc = doc; + + var input = new CodeMirror.inputStyles[options.inputStyle](this); + var display = this.display = new Display(place, doc, input, options); + display.wrapper.CodeMirror = this; + themeChanged(this); + if (options.lineWrapping) + { this.display.wrapper.className += " CodeMirror-wrap"; } + initScrollbars(this); + + this.state = { + keyMaps: [], // stores maps added by addKeyMap + overlays: [], // highlighting overlays, as added by addOverlay + modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info + overwrite: false, + delayingBlurEvent: false, + focused: false, + suppressEdits: false, // used to disable editing during key handlers when in readOnly mode + pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll + selectingText: false, + draggingText: false, + highlight: new Delayed(), // stores highlight worker timeout + keySeq: null, // Unfinished key sequence + specialChars: null + }; + + if (options.autofocus && !mobile) { display.input.focus(); } + + // Override magic textarea content restore that IE sometimes does + // on our hidden textarea on reload + if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); } + + registerEventHandlers(this); + ensureGlobalHandlers(); + + startOperation(this); + this.curOp.forceUpdate = true; + attachDoc(this, doc); + + if ((options.autofocus && !mobile) || this.hasFocus()) + { setTimeout(function () { + if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); } + }, 20); } + else + { onBlur(this); } + + for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt)) + { optionHandlers[opt](this, options[opt], Init); } } + maybeUpdateLineNumberWidth(this); + if (options.finishInit) { options.finishInit(this); } + for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); } + endOperation(this); + // Suppress optimizelegibility in Webkit, since it breaks text + // measuring on line wrapping boundaries. + if (webkit && options.lineWrapping && + getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") + { display.lineDiv.style.textRendering = "auto"; } + } + + // The default configuration options. + CodeMirror.defaults = defaults; + // Functions to run when options are changed. + CodeMirror.optionHandlers = optionHandlers; + + // Attach the necessary event handlers when initializing the editor + function registerEventHandlers(cm) { + var d = cm.display; + on(d.scroller, "mousedown", operation(cm, onMouseDown)); + // Older IE's will not fire a second mousedown for a double click + if (ie && ie_version < 11) + { on(d.scroller, "dblclick", operation(cm, function (e) { + if (signalDOMEvent(cm, e)) { return } + var pos = posFromMouse(cm, e); + if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return } + e_preventDefault(e); + var word = cm.findWordAt(pos); + extendSelection(cm.doc, word.anchor, word.head); + })); } + else + { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); } + // Some browsers fire contextmenu *after* opening the menu, at + // which point we can't mess with it anymore. Context menu is + // handled in onMouseDown for these browsers. + on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); + on(d.input.getField(), "contextmenu", function (e) { + if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); } + }); + + // Used to suppress mouse event handling when a touch happens + var touchFinished, prevTouch = {end: 0}; + function finishTouch() { + if (d.activeTouch) { + touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000); + prevTouch = d.activeTouch; + prevTouch.end = +new Date; + } + } + function isMouseLikeTouchEvent(e) { + if (e.touches.length != 1) { return false } + var touch = e.touches[0]; + return touch.radiusX <= 1 && touch.radiusY <= 1 + } + function farAway(touch, other) { + if (other.left == null) { return true } + var dx = other.left - touch.left, dy = other.top - touch.top; + return dx * dx + dy * dy > 20 * 20 + } + on(d.scroller, "touchstart", function (e) { + if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { + d.input.ensurePolled(); + clearTimeout(touchFinished); + var now = +new Date; + d.activeTouch = {start: now, moved: false, + prev: now - prevTouch.end <= 300 ? prevTouch : null}; + if (e.touches.length == 1) { + d.activeTouch.left = e.touches[0].pageX; + d.activeTouch.top = e.touches[0].pageY; + } + } + }); + on(d.scroller, "touchmove", function () { + if (d.activeTouch) { d.activeTouch.moved = true; } + }); + on(d.scroller, "touchend", function (e) { + var touch = d.activeTouch; + if (touch && !eventInWidget(d, e) && touch.left != null && + !touch.moved && new Date - touch.start < 300) { + var pos = cm.coordsChar(d.activeTouch, "page"), range; + if (!touch.prev || farAway(touch, touch.prev)) // Single tap + { range = new Range(pos, pos); } + else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap + { range = cm.findWordAt(pos); } + else // Triple tap + { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); } + cm.setSelection(range.anchor, range.head); + cm.focus(); + e_preventDefault(e); + } + finishTouch(); + }); + on(d.scroller, "touchcancel", finishTouch); + + // Sync scrolling between fake scrollbars and real scrollable + // area, ensure viewport is updated when scrolling. + on(d.scroller, "scroll", function () { + if (d.scroller.clientHeight) { + updateScrollTop(cm, d.scroller.scrollTop); + setScrollLeft(cm, d.scroller.scrollLeft, true); + signal(cm, "scroll", cm); + } + }); + + // Listen to wheel events in order to try and update the viewport on time. + on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); }); + on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); }); + + // Prevent wrapper from ever scrolling + on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); + + d.dragFunctions = { + enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }}, + over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, + start: function (e) { return onDragStart(cm, e); }, + drop: operation(cm, onDrop), + leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }} + }; + + var inp = d.input.getField(); + on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); }); + on(inp, "keydown", operation(cm, onKeyDown)); + on(inp, "keypress", operation(cm, onKeyPress)); + on(inp, "focus", function (e) { return onFocus(cm, e); }); + on(inp, "blur", function (e) { return onBlur(cm, e); }); + } + + var initHooks = []; + CodeMirror.defineInitHook = function (f) { return initHooks.push(f); }; + + // Indent the given line. The how parameter can be "smart", + // "add"/null, "subtract", or "prev". When aggressive is false + // (typically set to true for forced single-line indents), empty + // lines are not indented, and places where the mode returns Pass + // are left alone. + function indentLine(cm, n, how, aggressive) { + var doc = cm.doc, state; + if (how == null) { how = "add"; } + if (how == "smart") { + // Fall back to "prev" when the mode doesn't have an indentation + // method. + if (!doc.mode.indent) { how = "prev"; } + else { state = getContextBefore(cm, n).state; } + } + + var tabSize = cm.options.tabSize; + var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); + if (line.stateAfter) { line.stateAfter = null; } + var curSpaceString = line.text.match(/^\s*/)[0], indentation; + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0; + how = "not"; + } else if (how == "smart") { + indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); + if (indentation == Pass || indentation > 150) { + if (!aggressive) { return } + how = "prev"; + } + } + if (how == "prev") { + if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); } + else { indentation = 0; } + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit; + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit; + } else if (typeof how == "number") { + indentation = curSpace + how; + } + indentation = Math.max(0, indentation); + + var indentString = "", pos = 0; + if (cm.options.indentWithTabs) + { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} } + if (pos < indentation) { indentString += spaceStr(indentation - pos); } + + if (indentString != curSpaceString) { + replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); + line.stateAfter = null; + return true + } else { + // Ensure that, if the cursor was in the whitespace at the start + // of the line, it is moved to the end of that space. + for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) { + var range = doc.sel.ranges[i$1]; + if (range.head.line == n && range.head.ch < curSpaceString.length) { + var pos$1 = Pos(n, curSpaceString.length); + replaceOneSelection(doc, i$1, new Range(pos$1, pos$1)); + break + } + } + } + } + + // This will be set to a {lineWise: bool, text: [string]} object, so + // that, when pasting, we know what kind of selections the copied + // text was made out of. + var lastCopied = null; + + function setLastCopied(newLastCopied) { + lastCopied = newLastCopied; + } + + function applyTextInput(cm, inserted, deleted, sel, origin) { + var doc = cm.doc; + cm.display.shift = false; + if (!sel) { sel = doc.sel; } + + var recent = +new Date - 200; + var paste = origin == "paste" || cm.state.pasteIncoming > recent; + var textLines = splitLinesAuto(inserted), multiPaste = null; + // When pasting N lines into N selections, insert one line per selection + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.text.join("\n") == inserted) { + if (sel.ranges.length % lastCopied.text.length == 0) { + multiPaste = []; + for (var i = 0; i < lastCopied.text.length; i++) + { multiPaste.push(doc.splitLines(lastCopied.text[i])); } + } + } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { + multiPaste = map(textLines, function (l) { return [l]; }); + } + } + + var updateInput = cm.curOp.updateInput; + // Normal behavior is to insert the new text into every selection + for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) { + var range = sel.ranges[i$1]; + var from = range.from(), to = range.to(); + if (range.empty()) { + if (deleted && deleted > 0) // Handle deletion + { from = Pos(from.line, from.ch - deleted); } + else if (cm.state.overwrite && !paste) // Handle overwrite + { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); } + else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n")) + { from = to = Pos(from.line, 0); } + } + var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")}; + makeChange(cm.doc, changeEvent); + signalLater(cm, "inputRead", cm, changeEvent); + } + if (inserted && !paste) + { triggerElectric(cm, inserted); } + + ensureCursorVisible(cm); + if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; } + cm.curOp.typing = true; + cm.state.pasteIncoming = cm.state.cutIncoming = -1; + } + + function handlePaste(e, cm) { + var pasted = e.clipboardData && e.clipboardData.getData("Text"); + if (pasted) { + e.preventDefault(); + if (!cm.isReadOnly() && !cm.options.disableInput) + { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); } + return true + } + } + + function triggerElectric(cm, inserted) { + // When an 'electric' character is inserted, immediately trigger a reindent + if (!cm.options.electricChars || !cm.options.smartIndent) { return } + var sel = cm.doc.sel; + + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i]; + if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue } + var mode = cm.getModeAt(range.head); + var indented = false; + if (mode.electricChars) { + for (var j = 0; j < mode.electricChars.length; j++) + { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range.head.line, "smart"); + break + } } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) + { indented = indentLine(cm, range.head.line, "smart"); } + } + if (indented) { signalLater(cm, "electricInput", cm, range.head.line); } + } + } + + function copyableRanges(cm) { + var text = [], ranges = []; + for (var i = 0; i < cm.doc.sel.ranges.length; i++) { + var line = cm.doc.sel.ranges[i].head.line; + var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; + ranges.push(lineRange); + text.push(cm.getRange(lineRange.anchor, lineRange.head)); + } + return {text: text, ranges: ranges} + } + + function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) { + field.setAttribute("autocorrect", autocorrect ? "" : "off"); + field.setAttribute("autocapitalize", autocapitalize ? "" : "off"); + field.setAttribute("spellcheck", !!spellcheck); + } + + function hiddenTextarea() { + var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none"); + var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); + // The textarea is kept positioned near the cursor to prevent the + // fact that it'll be scrolled into view on input from scrolling + // our fake cursor out of view. On webkit, when wrap=off, paste is + // very slow. So make the area wide instead. + if (webkit) { te.style.width = "1000px"; } + else { te.setAttribute("wrap", "off"); } + // If border: 0; -- iOS fails to open keyboard (issue #1287) + if (ios) { te.style.border = "1px solid black"; } + disableBrowserMagic(te); + return div + } + + // The publicly visible API. Note that methodOp(f) means + // 'wrap f in an operation, performed on its `this` parameter'. + + // This is not the complete set of editor methods. Most of the + // methods defined on the Doc type are also injected into + // CodeMirror.prototype, for backwards compatibility and + // convenience. + + function addEditorMethods(CodeMirror) { + var optionHandlers = CodeMirror.optionHandlers; + + var helpers = CodeMirror.helpers = {}; + + CodeMirror.prototype = { + constructor: CodeMirror, + focus: function(){window.focus(); this.display.input.focus();}, + + setOption: function(option, value) { + var options = this.options, old = options[option]; + if (options[option] == value && option != "mode") { return } + options[option] = value; + if (optionHandlers.hasOwnProperty(option)) + { operation(this, optionHandlers[option])(this, value, old); } + signal(this, "optionChange", this, option); + }, + + getOption: function(option) {return this.options[option]}, + getDoc: function() {return this.doc}, + + addKeyMap: function(map, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)); + }, + removeKeyMap: function(map) { + var maps = this.state.keyMaps; + for (var i = 0; i < maps.length; ++i) + { if (maps[i] == map || maps[i].name == map) { + maps.splice(i, 1); + return true + } } + }, + + addOverlay: methodOp(function(spec, options) { + var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); + if (mode.startState) { throw new Error("Overlays may not be stateful.") } + insertSorted(this.state.overlays, + {mode: mode, modeSpec: spec, opaque: options && options.opaque, + priority: (options && options.priority) || 0}, + function (overlay) { return overlay.priority; }); + this.state.modeGen++; + regChange(this); + }), + removeOverlay: methodOp(function(spec) { + var overlays = this.state.overlays; + for (var i = 0; i < overlays.length; ++i) { + var cur = overlays[i].modeSpec; + if (cur == spec || typeof spec == "string" && cur.name == spec) { + overlays.splice(i, 1); + this.state.modeGen++; + regChange(this); + return + } + } + }), + + indentLine: methodOp(function(n, dir, aggressive) { + if (typeof dir != "string" && typeof dir != "number") { + if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; } + else { dir = dir ? "add" : "subtract"; } + } + if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); } + }), + indentSelection: methodOp(function(how) { + var ranges = this.doc.sel.ranges, end = -1; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (!range.empty()) { + var from = range.from(), to = range.to(); + var start = Math.max(end, from.line); + end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; + for (var j = start; j < end; ++j) + { indentLine(this, j, how); } + var newRanges = this.doc.sel.ranges; + if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) + { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); } + } else if (range.head.line > end) { + indentLine(this, range.head.line, how, true); + end = range.head.line; + if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); } + } + } + }), + + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function(pos, precise) { + return takeToken(this, pos, precise) + }, + + getLineTokens: function(line, precise) { + return takeToken(this, Pos(line), precise, true) + }, + + getTokenTypeAt: function(pos) { + pos = clipPos(this.doc, pos); + var styles = getLineStyles(this, getLine(this.doc, pos.line)); + var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; + var type; + if (ch == 0) { type = styles[2]; } + else { for (;;) { + var mid = (before + after) >> 1; + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; } + else if (styles[mid * 2 + 1] < ch) { before = mid + 1; } + else { type = styles[mid * 2 + 2]; break } + } } + var cut = type ? type.indexOf("overlay ") : -1; + return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1) + }, + + getModeAt: function(pos) { + var mode = this.doc.mode; + if (!mode.innerMode) { return mode } + return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode + }, + + getHelper: function(pos, type) { + return this.getHelpers(pos, type)[0] + }, + + getHelpers: function(pos, type) { + var found = []; + if (!helpers.hasOwnProperty(type)) { return found } + var help = helpers[type], mode = this.getModeAt(pos); + if (typeof mode[type] == "string") { + if (help[mode[type]]) { found.push(help[mode[type]]); } + } else if (mode[type]) { + for (var i = 0; i < mode[type].length; i++) { + var val = help[mode[type][i]]; + if (val) { found.push(val); } + } + } else if (mode.helperType && help[mode.helperType]) { + found.push(help[mode.helperType]); + } else if (help[mode.name]) { + found.push(help[mode.name]); + } + for (var i$1 = 0; i$1 < help._global.length; i$1++) { + var cur = help._global[i$1]; + if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) + { found.push(cur.val); } + } + return found + }, + + getStateAfter: function(line, precise) { + var doc = this.doc; + line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); + return getContextBefore(this, line + 1, precise).state + }, + + cursorCoords: function(start, mode) { + var pos, range = this.doc.sel.primary(); + if (start == null) { pos = range.head; } + else if (typeof start == "object") { pos = clipPos(this.doc, start); } + else { pos = start ? range.from() : range.to(); } + return cursorCoords(this, pos, mode || "page") + }, + + charCoords: function(pos, mode) { + return charCoords(this, clipPos(this.doc, pos), mode || "page") + }, + + coordsChar: function(coords, mode) { + coords = fromCoordSystem(this, coords, mode || "page"); + return coordsChar(this, coords.left, coords.top) + }, + + lineAtHeight: function(height, mode) { + height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; + return lineAtHeight(this.doc, height + this.display.viewOffset) + }, + heightAtLine: function(line, mode, includeWidgets) { + var end = false, lineObj; + if (typeof line == "number") { + var last = this.doc.first + this.doc.size - 1; + if (line < this.doc.first) { line = this.doc.first; } + else if (line > last) { line = last; end = true; } + lineObj = getLine(this.doc, line); + } else { + lineObj = line; + } + return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top + + (end ? this.doc.height - heightAtLine(lineObj) : 0) + }, + + defaultTextHeight: function() { return textHeight(this.display) }, + defaultCharWidth: function() { return charWidth(this.display) }, + + getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, + + addWidget: function(pos, node, scroll, vert, horiz) { + var display = this.display; + pos = cursorCoords(this, clipPos(this.doc, pos)); + var top = pos.bottom, left = pos.left; + node.style.position = "absolute"; + node.setAttribute("cm-ignore-events", "true"); + this.display.input.setUneditable(node); + display.sizer.appendChild(node); + if (vert == "over") { + top = pos.top; + } else if (vert == "above" || vert == "near") { + var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), + hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); + // Default to positioning above (if specified and possible); otherwise default to positioning below + if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) + { top = pos.top - node.offsetHeight; } + else if (pos.bottom + node.offsetHeight <= vspace) + { top = pos.bottom; } + if (left + node.offsetWidth > hspace) + { left = hspace - node.offsetWidth; } + } + node.style.top = top + "px"; + node.style.left = node.style.right = ""; + if (horiz == "right") { + left = display.sizer.clientWidth - node.offsetWidth; + node.style.right = "0px"; + } else { + if (horiz == "left") { left = 0; } + else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; } + node.style.left = left + "px"; + } + if (scroll) + { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); } + }, + + triggerOnKeyDown: methodOp(onKeyDown), + triggerOnKeyPress: methodOp(onKeyPress), + triggerOnKeyUp: onKeyUp, + triggerOnMouseDown: methodOp(onMouseDown), + + execCommand: function(cmd) { + if (commands.hasOwnProperty(cmd)) + { return commands[cmd].call(null, this) } + }, + + triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), + + findPosH: function(from, amount, unit, visually) { + var dir = 1; + if (amount < 0) { dir = -1; amount = -amount; } + var cur = clipPos(this.doc, from); + for (var i = 0; i < amount; ++i) { + cur = findPosH(this.doc, cur, dir, unit, visually); + if (cur.hitSide) { break } + } + return cur + }, + + moveH: methodOp(function(dir, unit) { + var this$1 = this; + + this.extendSelectionsBy(function (range) { + if (this$1.display.shift || this$1.doc.extend || range.empty()) + { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) } + else + { return dir < 0 ? range.from() : range.to() } + }, sel_move); + }), + + deleteH: methodOp(function(dir, unit) { + var sel = this.doc.sel, doc = this.doc; + if (sel.somethingSelected()) + { doc.replaceSelection("", null, "+delete"); } + else + { deleteNearSelection(this, function (range) { + var other = findPosH(doc, range.head, dir, unit, false); + return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other} + }); } + }), + + findPosV: function(from, amount, unit, goalColumn) { + var dir = 1, x = goalColumn; + if (amount < 0) { dir = -1; amount = -amount; } + var cur = clipPos(this.doc, from); + for (var i = 0; i < amount; ++i) { + var coords = cursorCoords(this, cur, "div"); + if (x == null) { x = coords.left; } + else { coords.left = x; } + cur = findPosV(this, coords, dir, unit); + if (cur.hitSide) { break } + } + return cur + }, + + moveV: methodOp(function(dir, unit) { + var this$1 = this; + + var doc = this.doc, goals = []; + var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected(); + doc.extendSelectionsBy(function (range) { + if (collapse) + { return dir < 0 ? range.from() : range.to() } + var headPos = cursorCoords(this$1, range.head, "div"); + if (range.goalColumn != null) { headPos.left = range.goalColumn; } + goals.push(headPos.left); + var pos = findPosV(this$1, headPos, dir, unit); + if (unit == "page" && range == doc.sel.primary()) + { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); } + return pos + }, sel_move); + if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++) + { doc.sel.ranges[i].goalColumn = goals[i]; } } + }), + + // Find the word at the given position (as returned by coordsChar). + findWordAt: function(pos) { + var doc = this.doc, line = getLine(doc, pos.line).text; + var start = pos.ch, end = pos.ch; + if (line) { + var helper = this.getHelper(pos, "wordChars"); + if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; } + var startChar = line.charAt(start); + var check = isWordChar(startChar, helper) + ? function (ch) { return isWordChar(ch, helper); } + : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); } + : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }; + while (start > 0 && check(line.charAt(start - 1))) { --start; } + while (end < line.length && check(line.charAt(end))) { ++end; } + } + return new Range(Pos(pos.line, start), Pos(pos.line, end)) + }, + + toggleOverwrite: function(value) { + if (value != null && value == this.state.overwrite) { return } + if (this.state.overwrite = !this.state.overwrite) + { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); } + else + { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); } + + signal(this, "overwriteToggle", this, this.state.overwrite); + }, + hasFocus: function() { return this.display.input.getField() == activeElt() }, + isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, + + scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }), + getScrollInfo: function() { + var scroller = this.display.scroller; + return {left: scroller.scrollLeft, top: scroller.scrollTop, + height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, + width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, + clientHeight: displayHeight(this), clientWidth: displayWidth(this)} + }, + + scrollIntoView: methodOp(function(range, margin) { + if (range == null) { + range = {from: this.doc.sel.primary().head, to: null}; + if (margin == null) { margin = this.options.cursorScrollMargin; } + } else if (typeof range == "number") { + range = {from: Pos(range, 0), to: null}; + } else if (range.from == null) { + range = {from: range, to: null}; + } + if (!range.to) { range.to = range.from; } + range.margin = margin || 0; + + if (range.from.line != null) { + scrollToRange(this, range); + } else { + scrollToCoordsRange(this, range.from, range.to, range.margin); + } + }), + + setSize: methodOp(function(width, height) { + var this$1 = this; + + var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }; + if (width != null) { this.display.wrapper.style.width = interpret(width); } + if (height != null) { this.display.wrapper.style.height = interpret(height); } + if (this.options.lineWrapping) { clearLineMeasurementCache(this); } + var lineNo = this.display.viewFrom; + this.doc.iter(lineNo, this.display.viewTo, function (line) { + if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) + { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } } + ++lineNo; + }); + this.curOp.forceUpdate = true; + signal(this, "refresh", this); + }), + + operation: function(f){return runInOp(this, f)}, + startOperation: function(){return startOperation(this)}, + endOperation: function(){return endOperation(this)}, + + refresh: methodOp(function() { + var oldHeight = this.display.cachedTextHeight; + regChange(this); + this.curOp.forceUpdate = true; + clearCaches(this); + scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); + updateGutterSpace(this.display); + if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping) + { estimateLineHeights(this); } + signal(this, "refresh", this); + }), + + swapDoc: methodOp(function(doc) { + var old = this.doc; + old.cm = null; + // Cancel the current text selection if any (#5821) + if (this.state.selectingText) { this.state.selectingText(); } + attachDoc(this, doc); + clearCaches(this); + this.display.input.reset(); + scrollToCoords(this, doc.scrollLeft, doc.scrollTop); + this.curOp.forceScroll = true; + signalLater(this, "swapDoc", this, old); + return old + }), + + phrase: function(phraseText) { + var phrases = this.options.phrases; + return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText + }, + + getInputField: function(){return this.display.input.getField()}, + getWrapperElement: function(){return this.display.wrapper}, + getScrollerElement: function(){return this.display.scroller}, + getGutterElement: function(){return this.display.gutters} + }; + eventMixin(CodeMirror); + + CodeMirror.registerHelper = function(type, name, value) { + if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; } + helpers[type][name] = value; + }; + CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { + CodeMirror.registerHelper(type, name, value); + helpers[type]._global.push({pred: predicate, val: value}); + }; + } + + // Used for horizontal relative motion. Dir is -1 or 1 (left or + // right), unit can be "codepoint", "char", "column" (like char, but + // doesn't cross line boundaries), "word" (across next word), or + // "group" (to the start of next group of word or + // non-word-non-whitespace chars). The visually param controls + // whether, in right-to-left text, direction 1 means to move towards + // the next index in the string, or towards the character to the right + // of the current position. The resulting position will have a + // hitSide=true property if it reached the end of the document. + function findPosH(doc, pos, dir, unit, visually) { + var oldPos = pos; + var origDir = dir; + var lineObj = getLine(doc, pos.line); + var lineDir = visually && doc.direction == "rtl" ? -dir : dir; + function findNextLine() { + var l = pos.line + lineDir; + if (l < doc.first || l >= doc.first + doc.size) { return false } + pos = new Pos(l, pos.ch, pos.sticky); + return lineObj = getLine(doc, l) + } + function moveOnce(boundToLine) { + var next; + if (unit == "codepoint") { + var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1)); + if (isNaN(ch)) { + next = null; + } else { + var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF; + next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir); + } + } else if (visually) { + next = moveVisually(doc.cm, lineObj, pos, dir); + } else { + next = moveLogically(lineObj, pos, dir); + } + if (next == null) { + if (!boundToLine && findNextLine()) + { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); } + else + { return false } + } else { + pos = next; + } + return true + } + + if (unit == "char" || unit == "codepoint") { + moveOnce(); + } else if (unit == "column") { + moveOnce(true); + } else if (unit == "word" || unit == "group") { + var sawType = null, group = unit == "group"; + var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); + for (var first = true;; first = false) { + if (dir < 0 && !moveOnce(!first)) { break } + var cur = lineObj.text.charAt(pos.ch) || "\n"; + var type = isWordChar(cur, helper) ? "w" + : group && cur == "\n" ? "n" + : !group || /\s/.test(cur) ? null + : "p"; + if (group && !first && !type) { type = "s"; } + if (sawType && sawType != type) { + if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";} + break + } + + if (type) { sawType = type; } + if (dir > 0 && !moveOnce(!first)) { break } + } + } + var result = skipAtomic(doc, pos, oldPos, origDir, true); + if (equalCursorPos(oldPos, result)) { result.hitSide = true; } + return result + } + + // For relative vertical movement. Dir may be -1 or 1. Unit can be + // "page" or "line". The resulting position will have a hitSide=true + // property if it reached the end of the document. + function findPosV(cm, pos, dir, unit) { + var doc = cm.doc, x = pos.left, y; + if (unit == "page") { + var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); + var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3); + y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; + + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3; + } + var target; + for (;;) { + target = coordsChar(cm, x, y); + if (!target.outside) { break } + if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break } + y += dir * 5; + } + return target + } + + // CONTENTEDITABLE INPUT STYLE + + var ContentEditableInput = function(cm) { + this.cm = cm; + this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; + this.polling = new Delayed(); + this.composing = null; + this.gracePeriod = false; + this.readDOMTimeout = null; + }; + + ContentEditableInput.prototype.init = function (display) { + var this$1 = this; + + var input = this, cm = input.cm; + var div = input.div = display.lineDiv; + div.contentEditable = true; + disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize); + + function belongsToInput(e) { + for (var t = e.target; t; t = t.parentNode) { + if (t == div) { return true } + if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break } + } + return false + } + + on(div, "paste", function (e) { + if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } + // IE doesn't fire input events, so we schedule a read for the pasted content in this way + if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); } + }); + + on(div, "compositionstart", function (e) { + this$1.composing = {data: e.data, done: false}; + }); + on(div, "compositionupdate", function (e) { + if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; } + }); + on(div, "compositionend", function (e) { + if (this$1.composing) { + if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); } + this$1.composing.done = true; + } + }); + + on(div, "touchstart", function () { return input.forceCompositionEnd(); }); + + on(div, "input", function () { + if (!this$1.composing) { this$1.readFromDOMSoon(); } + }); + + function onCopyCut(e) { + if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return } + if (cm.somethingSelected()) { + setLastCopied({lineWise: false, text: cm.getSelections()}); + if (e.type == "cut") { cm.replaceSelection("", null, "cut"); } + } else if (!cm.options.lineWiseCopyCut) { + return + } else { + var ranges = copyableRanges(cm); + setLastCopied({lineWise: true, text: ranges.text}); + if (e.type == "cut") { + cm.operation(function () { + cm.setSelections(ranges.ranges, 0, sel_dontScroll); + cm.replaceSelection("", null, "cut"); + }); + } + } + if (e.clipboardData) { + e.clipboardData.clearData(); + var content = lastCopied.text.join("\n"); + // iOS exposes the clipboard API, but seems to discard content inserted into it + e.clipboardData.setData("Text", content); + if (e.clipboardData.getData("Text") == content) { + e.preventDefault(); + return + } + } + // Old-fashioned briefly-focus-a-textarea hack + var kludge = hiddenTextarea(), te = kludge.firstChild; + cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); + te.value = lastCopied.text.join("\n"); + var hadFocus = activeElt(); + selectInput(te); + setTimeout(function () { + cm.display.lineSpace.removeChild(kludge); + hadFocus.focus(); + if (hadFocus == div) { input.showPrimarySelection(); } + }, 50); + } + on(div, "copy", onCopyCut); + on(div, "cut", onCopyCut); + }; + + ContentEditableInput.prototype.screenReaderLabelChanged = function (label) { + // Label for screenreaders, accessibility + if(label) { + this.div.setAttribute('aria-label', label); + } else { + this.div.removeAttribute('aria-label'); + } + }; + + ContentEditableInput.prototype.prepareSelection = function () { + var result = prepareSelection(this.cm, false); + result.focus = activeElt() == this.div; + return result + }; + + ContentEditableInput.prototype.showSelection = function (info, takeFocus) { + if (!info || !this.cm.display.view.length) { return } + if (info.focus || takeFocus) { this.showPrimarySelection(); } + this.showMultipleSelections(info); + }; + + ContentEditableInput.prototype.getSelection = function () { + return this.cm.display.wrapper.ownerDocument.getSelection() + }; + + ContentEditableInput.prototype.showPrimarySelection = function () { + var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary(); + var from = prim.from(), to = prim.to(); + + if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { + sel.removeAllRanges(); + return + } + + var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); + if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && + cmp(minPos(curAnchor, curFocus), from) == 0 && + cmp(maxPos(curAnchor, curFocus), to) == 0) + { return } + + var view = cm.display.view; + var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) || + {node: view[0].measure.map[2], offset: 0}; + var end = to.line < cm.display.viewTo && posToDOM(cm, to); + if (!end) { + var measure = view[view.length - 1].measure; + var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; + end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}; + } + + if (!start || !end) { + sel.removeAllRanges(); + return + } + + var old = sel.rangeCount && sel.getRangeAt(0), rng; + try { rng = range(start.node, start.offset, end.offset, end.node); } + catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible + if (rng) { + if (!gecko && cm.state.focused) { + sel.collapse(start.node, start.offset); + if (!rng.collapsed) { + sel.removeAllRanges(); + sel.addRange(rng); + } + } else { + sel.removeAllRanges(); + sel.addRange(rng); + } + if (old && sel.anchorNode == null) { sel.addRange(old); } + else if (gecko) { this.startGracePeriod(); } + } + this.rememberSelection(); + }; + + ContentEditableInput.prototype.startGracePeriod = function () { + var this$1 = this; + + clearTimeout(this.gracePeriod); + this.gracePeriod = setTimeout(function () { + this$1.gracePeriod = false; + if (this$1.selectionChanged()) + { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); } + }, 20); + }; + + ContentEditableInput.prototype.showMultipleSelections = function (info) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); + }; + + ContentEditableInput.prototype.rememberSelection = function () { + var sel = this.getSelection(); + this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; + this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; + }; + + ContentEditableInput.prototype.selectionInEditor = function () { + var sel = this.getSelection(); + if (!sel.rangeCount) { return false } + var node = sel.getRangeAt(0).commonAncestorContainer; + return contains(this.div, node) + }; + + ContentEditableInput.prototype.focus = function () { + if (this.cm.options.readOnly != "nocursor") { + if (!this.selectionInEditor() || activeElt() != this.div) + { this.showSelection(this.prepareSelection(), true); } + this.div.focus(); + } + }; + ContentEditableInput.prototype.blur = function () { this.div.blur(); }; + ContentEditableInput.prototype.getField = function () { return this.div }; + + ContentEditableInput.prototype.supportsTouch = function () { return true }; + + ContentEditableInput.prototype.receivedFocus = function () { + var this$1 = this; + + var input = this; + if (this.selectionInEditor()) + { setTimeout(function () { return this$1.pollSelection(); }, 20); } + else + { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); } + + function poll() { + if (input.cm.state.focused) { + input.pollSelection(); + input.polling.set(input.cm.options.pollInterval, poll); + } + } + this.polling.set(this.cm.options.pollInterval, poll); + }; + + ContentEditableInput.prototype.selectionChanged = function () { + var sel = this.getSelection(); + return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || + sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset + }; + + ContentEditableInput.prototype.pollSelection = function () { + if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return } + var sel = this.getSelection(), cm = this.cm; + // On Android Chrome (version 56, at least), backspacing into an + // uneditable block element will put the cursor in that element, + // and then, because it's not editable, hide the virtual keyboard. + // Because Android doesn't allow us to actually detect backspace + // presses in a sane way, this code checks for when that happens + // and simulates a backspace press in this case. + if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) { + this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs}); + this.blur(); + this.focus(); + return + } + if (this.composing) { return } + this.rememberSelection(); + var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var head = domToPos(cm, sel.focusNode, sel.focusOffset); + if (anchor && head) { runInOp(cm, function () { + setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); + if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; } + }); } + }; + + ContentEditableInput.prototype.pollContent = function () { + if (this.readDOMTimeout != null) { + clearTimeout(this.readDOMTimeout); + this.readDOMTimeout = null; + } + + var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); + var from = sel.from(), to = sel.to(); + if (from.ch == 0 && from.line > cm.firstLine()) + { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); } + if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) + { to = Pos(to.line + 1, 0); } + if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false } + + var fromIndex, fromLine, fromNode; + if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { + fromLine = lineNo(display.view[0].line); + fromNode = display.view[0].node; + } else { + fromLine = lineNo(display.view[fromIndex].line); + fromNode = display.view[fromIndex - 1].node.nextSibling; + } + var toIndex = findViewIndex(cm, to.line); + var toLine, toNode; + if (toIndex == display.view.length - 1) { + toLine = display.viewTo - 1; + toNode = display.lineDiv.lastChild; + } else { + toLine = lineNo(display.view[toIndex + 1].line) - 1; + toNode = display.view[toIndex + 1].node.previousSibling; + } + + if (!fromNode) { return false } + var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); + var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } + else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } + else { break } + } + + var cutFront = 0, cutEnd = 0; + var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); + while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) + { ++cutFront; } + var newBot = lst(newText), oldBot = lst(oldText); + var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), + oldBot.length - (oldText.length == 1 ? cutFront : 0)); + while (cutEnd < maxCutEnd && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) + { ++cutEnd; } + // Try to move start of change to start of selection if ambiguous + if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { + while (cutFront && cutFront > from.ch && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { + cutFront--; + cutEnd++; + } + } + + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); + newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); + + var chFrom = Pos(fromLine, cutFront); + var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input"); + return true + } + }; + + ContentEditableInput.prototype.ensurePolled = function () { + this.forceCompositionEnd(); + }; + ContentEditableInput.prototype.reset = function () { + this.forceCompositionEnd(); + }; + ContentEditableInput.prototype.forceCompositionEnd = function () { + if (!this.composing) { return } + clearTimeout(this.readDOMTimeout); + this.composing = null; + this.updateFromDOM(); + this.div.blur(); + this.div.focus(); + }; + ContentEditableInput.prototype.readFromDOMSoon = function () { + var this$1 = this; + + if (this.readDOMTimeout != null) { return } + this.readDOMTimeout = setTimeout(function () { + this$1.readDOMTimeout = null; + if (this$1.composing) { + if (this$1.composing.done) { this$1.composing = null; } + else { return } + } + this$1.updateFromDOM(); + }, 80); + }; + + ContentEditableInput.prototype.updateFromDOM = function () { + var this$1 = this; + + if (this.cm.isReadOnly() || !this.pollContent()) + { runInOp(this.cm, function () { return regChange(this$1.cm); }); } + }; + + ContentEditableInput.prototype.setUneditable = function (node) { + node.contentEditable = "false"; + }; + + ContentEditableInput.prototype.onKeyPress = function (e) { + if (e.charCode == 0 || this.composing) { return } + e.preventDefault(); + if (!this.cm.isReadOnly()) + { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); } + }; + + ContentEditableInput.prototype.readOnlyChanged = function (val) { + this.div.contentEditable = String(val != "nocursor"); + }; + + ContentEditableInput.prototype.onContextMenu = function () {}; + ContentEditableInput.prototype.resetPosition = function () {}; + + ContentEditableInput.prototype.needsContentAttribute = true; + + function posToDOM(cm, pos) { + var view = findViewForLine(cm, pos.line); + if (!view || view.hidden) { return null } + var line = getLine(cm.doc, pos.line); + var info = mapFromLineView(view, line, pos.line); + + var order = getOrder(line, cm.doc.direction), side = "left"; + if (order) { + var partPos = getBidiPartAt(order, pos.ch); + side = partPos % 2 ? "right" : "left"; + } + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); + result.offset = result.collapse == "right" ? result.end : result.start; + return result + } + + function isInGutter(node) { + for (var scan = node; scan; scan = scan.parentNode) + { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } } + return false + } + + function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos } + + function domTextBetween(cm, from, to, fromLine, toLine) { + var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false; + function recognizeMarker(id) { return function (marker) { return marker.id == id; } } + function close() { + if (closing) { + text += lineSep; + if (extraLinebreak) { text += lineSep; } + closing = extraLinebreak = false; + } + } + function addText(str) { + if (str) { + close(); + text += str; + } + } + function walk(node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text"); + if (cmText) { + addText(cmText); + return + } + var markerID = node.getAttribute("cm-marker"), range; + if (markerID) { + var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); + if (found.length && (range = found[0].find(0))) + { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); } + return + } + if (node.getAttribute("contenteditable") == "false") { return } + var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName); + if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return } + + if (isBlock) { close(); } + for (var i = 0; i < node.childNodes.length; i++) + { walk(node.childNodes[i]); } + + if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; } + if (isBlock) { closing = true; } + } else if (node.nodeType == 3) { + addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " ")); + } + } + for (;;) { + walk(from); + if (from == to) { break } + from = from.nextSibling; + extraLinebreak = false; + } + return text + } + + function domToPos(cm, node, offset) { + var lineNode; + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset]; + if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) } + node = null; offset = 0; + } else { + for (lineNode = node;; lineNode = lineNode.parentNode) { + if (!lineNode || lineNode == cm.display.lineDiv) { return null } + if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break } + } + } + for (var i = 0; i < cm.display.view.length; i++) { + var lineView = cm.display.view[i]; + if (lineView.node == lineNode) + { return locateNodeInLineView(lineView, node, offset) } + } + } + + function locateNodeInLineView(lineView, node, offset) { + var wrapper = lineView.text.firstChild, bad = false; + if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) } + if (node == wrapper) { + bad = true; + node = wrapper.childNodes[offset]; + offset = 0; + if (!node) { + var line = lineView.rest ? lst(lineView.rest) : lineView.line; + return badPos(Pos(lineNo(line), line.text.length), bad) + } + } + + var textNode = node.nodeType == 3 ? node : null, topNode = node; + if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { + textNode = node.firstChild; + if (offset) { offset = textNode.nodeValue.length; } + } + while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; } + var measure = lineView.measure, maps = measure.maps; + + function find(textNode, topNode, offset) { + for (var i = -1; i < (maps ? maps.length : 0); i++) { + var map = i < 0 ? measure.map : maps[i]; + for (var j = 0; j < map.length; j += 3) { + var curNode = map[j + 2]; + if (curNode == textNode || curNode == topNode) { + var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); + var ch = map[j] + offset; + if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; } + return Pos(line, ch) + } + } + } + } + var found = find(textNode, topNode, offset); + if (found) { return badPos(found, bad) } + + // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems + for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { + found = find(after, after.firstChild, 0); + if (found) + { return badPos(Pos(found.line, found.ch - dist), bad) } + else + { dist += after.textContent.length; } + } + for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { + found = find(before, before.firstChild, -1); + if (found) + { return badPos(Pos(found.line, found.ch + dist$1), bad) } + else + { dist$1 += before.textContent.length; } + } + } + + // TEXTAREA INPUT STYLE + + var TextareaInput = function(cm) { + this.cm = cm; + // See input.poll and input.reset + this.prevInput = ""; + + // Flag that indicates whether we expect input to appear real soon + // now (after some event like 'keypress' or 'input') and are + // polling intensively. + this.pollingFast = false; + // Self-resetting timeout for the poller + this.polling = new Delayed(); + // Used to work around IE issue with selection being forgotten when focus moves away from textarea + this.hasSelection = false; + this.composing = null; + }; + + TextareaInput.prototype.init = function (display) { + var this$1 = this; + + var input = this, cm = this.cm; + this.createField(display); + var te = this.textarea; + + display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild); + + // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) + if (ios) { te.style.width = "0px"; } + + on(te, "input", function () { + if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; } + input.poll(); + }); + + on(te, "paste", function (e) { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } + + cm.state.pasteIncoming = +new Date; + input.fastPoll(); + }); + + function prepareCopyCut(e) { + if (signalDOMEvent(cm, e)) { return } + if (cm.somethingSelected()) { + setLastCopied({lineWise: false, text: cm.getSelections()}); + } else if (!cm.options.lineWiseCopyCut) { + return + } else { + var ranges = copyableRanges(cm); + setLastCopied({lineWise: true, text: ranges.text}); + if (e.type == "cut") { + cm.setSelections(ranges.ranges, null, sel_dontScroll); + } else { + input.prevInput = ""; + te.value = ranges.text.join("\n"); + selectInput(te); + } + } + if (e.type == "cut") { cm.state.cutIncoming = +new Date; } + } + on(te, "cut", prepareCopyCut); + on(te, "copy", prepareCopyCut); + + on(display.scroller, "paste", function (e) { + if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return } + if (!te.dispatchEvent) { + cm.state.pasteIncoming = +new Date; + input.focus(); + return + } + + // Pass the `paste` event to the textarea so it's handled by its event listener. + var event = new Event("paste"); + event.clipboardData = e.clipboardData; + te.dispatchEvent(event); + }); + + // Prevent normal selection in the editor (we handle our own) + on(display.lineSpace, "selectstart", function (e) { + if (!eventInWidget(display, e)) { e_preventDefault(e); } + }); + + on(te, "compositionstart", function () { + var start = cm.getCursor("from"); + if (input.composing) { input.composing.range.clear(); } + input.composing = { + start: start, + range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) + }; + }); + on(te, "compositionend", function () { + if (input.composing) { + input.poll(); + input.composing.range.clear(); + input.composing = null; + } + }); + }; + + TextareaInput.prototype.createField = function (_display) { + // Wraps and hides input textarea + this.wrapper = hiddenTextarea(); + // The semihidden textarea that is focused when the editor is + // focused, and receives input. + this.textarea = this.wrapper.firstChild; + }; + + TextareaInput.prototype.screenReaderLabelChanged = function (label) { + // Label for screenreaders, accessibility + if(label) { + this.textarea.setAttribute('aria-label', label); + } else { + this.textarea.removeAttribute('aria-label'); + } + }; + + TextareaInput.prototype.prepareSelection = function () { + // Redraw the selection and/or cursor + var cm = this.cm, display = cm.display, doc = cm.doc; + var result = prepareSelection(cm); + + // Move the hidden textarea near the cursor to prevent scrolling artifacts + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); + var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); + result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, + headPos.top + lineOff.top - wrapOff.top)); + result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, + headPos.left + lineOff.left - wrapOff.left)); + } + + return result + }; + + TextareaInput.prototype.showSelection = function (drawn) { + var cm = this.cm, display = cm.display; + removeChildrenAndAdd(display.cursorDiv, drawn.cursors); + removeChildrenAndAdd(display.selectionDiv, drawn.selection); + if (drawn.teTop != null) { + this.wrapper.style.top = drawn.teTop + "px"; + this.wrapper.style.left = drawn.teLeft + "px"; + } + }; + + // Reset the input to correspond to the selection (or to be empty, + // when not typing and nothing is selected) + TextareaInput.prototype.reset = function (typing) { + if (this.contextMenuPending || this.composing) { return } + var cm = this.cm; + if (cm.somethingSelected()) { + this.prevInput = ""; + var content = cm.getSelection(); + this.textarea.value = content; + if (cm.state.focused) { selectInput(this.textarea); } + if (ie && ie_version >= 9) { this.hasSelection = content; } + } else if (!typing) { + this.prevInput = this.textarea.value = ""; + if (ie && ie_version >= 9) { this.hasSelection = null; } + } + }; + + TextareaInput.prototype.getField = function () { return this.textarea }; + + TextareaInput.prototype.supportsTouch = function () { return false }; + + TextareaInput.prototype.focus = function () { + if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { + try { this.textarea.focus(); } + catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM + } + }; + + TextareaInput.prototype.blur = function () { this.textarea.blur(); }; + + TextareaInput.prototype.resetPosition = function () { + this.wrapper.style.top = this.wrapper.style.left = 0; + }; + + TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); }; + + // Poll for input changes, using the normal rate of polling. This + // runs as long as the editor is focused. + TextareaInput.prototype.slowPoll = function () { + var this$1 = this; + + if (this.pollingFast) { return } + this.polling.set(this.cm.options.pollInterval, function () { + this$1.poll(); + if (this$1.cm.state.focused) { this$1.slowPoll(); } + }); + }; + + // When an event has just come in that is likely to add or change + // something in the input textarea, we poll faster, to ensure that + // the change appears on the screen quickly. + TextareaInput.prototype.fastPoll = function () { + var missed = false, input = this; + input.pollingFast = true; + function p() { + var changed = input.poll(); + if (!changed && !missed) {missed = true; input.polling.set(60, p);} + else {input.pollingFast = false; input.slowPoll();} + } + input.polling.set(20, p); + }; + + // Read input from the textarea, and update the document to match. + // When something is selected, it is present in the textarea, and + // selected (unless it is huge, in which case a placeholder is + // used). When nothing is selected, the cursor sits after previously + // seen text (can be empty), which is stored in prevInput (we must + // not reset the textarea when typing, because that breaks IME). + TextareaInput.prototype.poll = function () { + var this$1 = this; + + var cm = this.cm, input = this.textarea, prevInput = this.prevInput; + // Since this is called a *lot*, try to bail out as cheaply as + // possible when it is clear that nothing happened. hasSelection + // will be the case when there is a lot of text in the textarea, + // in which case reading its value would be expensive. + if (this.contextMenuPending || !cm.state.focused || + (hasSelection(input) && !prevInput && !this.composing) || + cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) + { return false } + + var text = input.value; + // If nothing changed, bail. + if (text == prevInput && !cm.somethingSelected()) { return false } + // Work around nonsensical selection resetting in IE9/10, and + // inexplicable appearance of private area unicode characters on + // some key combos in Mac (#2689). + if (ie && ie_version >= 9 && this.hasSelection === text || + mac && /[\uf700-\uf7ff]/.test(text)) { + cm.display.input.reset(); + return false + } + + if (cm.doc.sel == cm.display.selForContextMenu) { + var first = text.charCodeAt(0); + if (first == 0x200b && !prevInput) { prevInput = "\u200b"; } + if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") } + } + // Find the part of the input that is actually new + var same = 0, l = Math.min(prevInput.length, text.length); + while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; } + + runInOp(cm, function () { + applyTextInput(cm, text.slice(same), prevInput.length - same, + null, this$1.composing ? "*compose" : null); + + // Don't leave long text in the textarea, since it makes further polling slow + if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; } + else { this$1.prevInput = text; } + + if (this$1.composing) { + this$1.composing.range.clear(); + this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), + {className: "CodeMirror-composing"}); + } + }); + return true + }; + + TextareaInput.prototype.ensurePolled = function () { + if (this.pollingFast && this.poll()) { this.pollingFast = false; } + }; + + TextareaInput.prototype.onKeyPress = function () { + if (ie && ie_version >= 9) { this.hasSelection = null; } + this.fastPoll(); + }; + + TextareaInput.prototype.onContextMenu = function (e) { + var input = this, cm = input.cm, display = cm.display, te = input.textarea; + if (input.contextMenuPending) { input.contextMenuPending(); } + var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; + if (!pos || presto) { return } // Opera is difficult. + + // Reset the current text selection only if the click is done outside of the selection + // and 'resetSelectionOnContextMenu' option is true. + var reset = cm.options.resetSelectionOnContextMenu; + if (reset && cm.doc.sel.contains(pos) == -1) + { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); } + + var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText; + var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect(); + input.wrapper.style.cssText = "position: static"; + te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; + var oldScrollY; + if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712) + display.input.focus(); + if (webkit) { window.scrollTo(null, oldScrollY); } + display.input.reset(); + // Adds "Select all" to context menu in FF + if (!cm.somethingSelected()) { te.value = input.prevInput = " "; } + input.contextMenuPending = rehide; + display.selForContextMenu = cm.doc.sel; + clearTimeout(display.detectingSelectAll); + + // Select-all will be greyed out if there's nothing to select, so + // this adds a zero-width space so that we can later check whether + // it got selected. + function prepareSelectAllHack() { + if (te.selectionStart != null) { + var selected = cm.somethingSelected(); + var extval = "\u200b" + (selected ? te.value : ""); + te.value = "\u21da"; // Used to catch context-menu undo + te.value = extval; + input.prevInput = selected ? "" : "\u200b"; + te.selectionStart = 1; te.selectionEnd = extval.length; + // Re-set this, in case some other handler touched the + // selection in the meantime. + display.selForContextMenu = cm.doc.sel; + } + } + function rehide() { + if (input.contextMenuPending != rehide) { return } + input.contextMenuPending = false; + input.wrapper.style.cssText = oldWrapperCSS; + te.style.cssText = oldCSS; + if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); } + + // Try to detect the user choosing select-all + if (te.selectionStart != null) { + if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); } + var i = 0, poll = function () { + if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && + te.selectionEnd > 0 && input.prevInput == "\u200b") { + operation(cm, selectAll)(cm); + } else if (i++ < 10) { + display.detectingSelectAll = setTimeout(poll, 500); + } else { + display.selForContextMenu = null; + display.input.reset(); + } + }; + display.detectingSelectAll = setTimeout(poll, 200); + } + } + + if (ie && ie_version >= 9) { prepareSelectAllHack(); } + if (captureRightClick) { + e_stop(e); + var mouseup = function () { + off(window, "mouseup", mouseup); + setTimeout(rehide, 20); + }; + on(window, "mouseup", mouseup); + } else { + setTimeout(rehide, 50); + } + }; + + TextareaInput.prototype.readOnlyChanged = function (val) { + if (!val) { this.reset(); } + this.textarea.disabled = val == "nocursor"; + this.textarea.readOnly = !!val; + }; + + TextareaInput.prototype.setUneditable = function () {}; + + TextareaInput.prototype.needsContentAttribute = false; + + function fromTextArea(textarea, options) { + options = options ? copyObj(options) : {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabIndex) + { options.tabindex = textarea.tabIndex; } + if (!options.placeholder && textarea.placeholder) + { options.placeholder = textarea.placeholder; } + // Set autofocus to true if this textarea is focused, or if it has + // autofocus and no other element is focused. + if (options.autofocus == null) { + var hasFocus = activeElt(); + options.autofocus = hasFocus == textarea || + textarea.getAttribute("autofocus") != null && hasFocus == document.body; + } + + function save() {textarea.value = cm.getValue();} + + var realSubmit; + if (textarea.form) { + on(textarea.form, "submit", save); + // Deplorable hack to make the submit method do the right thing. + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form; + realSubmit = form.submit; + try { + var wrappedSubmit = form.submit = function () { + save(); + form.submit = realSubmit; + form.submit(); + form.submit = wrappedSubmit; + }; + } catch(e) {} + } + } + + options.finishInit = function (cm) { + cm.save = save; + cm.getTextArea = function () { return textarea; }; + cm.toTextArea = function () { + cm.toTextArea = isNaN; // Prevent this from being ran twice + save(); + textarea.parentNode.removeChild(cm.getWrapperElement()); + textarea.style.display = ""; + if (textarea.form) { + off(textarea.form, "submit", save); + if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") + { textarea.form.submit = realSubmit; } + } + }; + }; + + textarea.style.display = "none"; + var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); }, + options); + return cm + } + + function addLegacyProps(CodeMirror) { + CodeMirror.off = off; + CodeMirror.on = on; + CodeMirror.wheelEventPixels = wheelEventPixels; + CodeMirror.Doc = Doc; + CodeMirror.splitLines = splitLinesAuto; + CodeMirror.countColumn = countColumn; + CodeMirror.findColumn = findColumn; + CodeMirror.isWordChar = isWordCharBasic; + CodeMirror.Pass = Pass; + CodeMirror.signal = signal; + CodeMirror.Line = Line; + CodeMirror.changeEnd = changeEnd; + CodeMirror.scrollbarModel = scrollbarModel; + CodeMirror.Pos = Pos; + CodeMirror.cmpPos = cmp; + CodeMirror.modes = modes; + CodeMirror.mimeModes = mimeModes; + CodeMirror.resolveMode = resolveMode; + CodeMirror.getMode = getMode; + CodeMirror.modeExtensions = modeExtensions; + CodeMirror.extendMode = extendMode; + CodeMirror.copyState = copyState; + CodeMirror.startState = startState; + CodeMirror.innerMode = innerMode; + CodeMirror.commands = commands; + CodeMirror.keyMap = keyMap; + CodeMirror.keyName = keyName; + CodeMirror.isModifierKey = isModifierKey; + CodeMirror.lookupKey = lookupKey; + CodeMirror.normalizeKeyMap = normalizeKeyMap; + CodeMirror.StringStream = StringStream; + CodeMirror.SharedTextMarker = SharedTextMarker; + CodeMirror.TextMarker = TextMarker; + CodeMirror.LineWidget = LineWidget; + CodeMirror.e_preventDefault = e_preventDefault; + CodeMirror.e_stopPropagation = e_stopPropagation; + CodeMirror.e_stop = e_stop; + CodeMirror.addClass = addClass; + CodeMirror.contains = contains; + CodeMirror.rmClass = rmClass; + CodeMirror.keyNames = keyNames; + } + + // EDITOR CONSTRUCTOR + + defineOptions(CodeMirror); + + addEditorMethods(CodeMirror); + + // Set up methods on CodeMirror's prototype to redirect to the editor's document. + var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); + for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) + { CodeMirror.prototype[prop] = (function(method) { + return function() {return method.apply(this.doc, arguments)} + })(Doc.prototype[prop]); } } + + eventMixin(Doc); + CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; + + // Extra arguments are stored as the mode's dependencies, which is + // used by (legacy) mechanisms like loadmode.js to automatically + // load a mode. (Preferred mechanism is the require/define calls.) + CodeMirror.defineMode = function(name/*, mode, …*/) { + if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; } + defineMode.apply(this, arguments); + }; + + CodeMirror.defineMIME = defineMIME; + + // Minimal default mode. + CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }); + CodeMirror.defineMIME("text/plain", "null"); + + // EXTENSIONS + + CodeMirror.defineExtension = function (name, func) { + CodeMirror.prototype[name] = func; + }; + CodeMirror.defineDocExtension = function (name, func) { + Doc.prototype[name] = func; + }; + + CodeMirror.fromTextArea = fromTextArea; + + addLegacyProps(CodeMirror); + + CodeMirror.version = "5.65.1"; + + return CodeMirror; + +}))); diff --git a/js/codemirror/5.65.1/css.js b/js/codemirror/5.65.1/css.js new file mode 100644 index 0000000..503c48c --- /dev/null +++ b/js/codemirror/5.65.1/css.js @@ -0,0 +1,866 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("css", function(config, parserConfig) { + var inline = parserConfig.inline + if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css"); + + var indentUnit = config.indentUnit, + tokenHooks = parserConfig.tokenHooks, + documentTypes = parserConfig.documentTypes || {}, + mediaTypes = parserConfig.mediaTypes || {}, + mediaFeatures = parserConfig.mediaFeatures || {}, + mediaValueKeywords = parserConfig.mediaValueKeywords || {}, + propertyKeywords = parserConfig.propertyKeywords || {}, + nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {}, + fontProperties = parserConfig.fontProperties || {}, + counterDescriptors = parserConfig.counterDescriptors || {}, + colorKeywords = parserConfig.colorKeywords || {}, + valueKeywords = parserConfig.valueKeywords || {}, + allowNested = parserConfig.allowNested, + lineComment = parserConfig.lineComment, + supportsAtComponent = parserConfig.supportsAtComponent === true, + highlightNonStandardPropertyKeywords = config.highlightNonStandardPropertyKeywords !== false; + + var type, override; + function ret(style, tp) { type = tp; return style; } + + // Tokenizers + + function tokenBase(stream, state) { + var ch = stream.next(); + if (tokenHooks[ch]) { + var result = tokenHooks[ch](stream, state); + if (result !== false) return result; + } + if (ch == "@") { + stream.eatWhile(/[\w\\\-]/); + return ret("def", stream.current()); + } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) { + return ret(null, "compare"); + } else if (ch == "\"" || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "#") { + stream.eatWhile(/[\w\\\-]/); + return ret("atom", "hash"); + } else if (ch == "!") { + stream.match(/^\s*\w*/); + return ret("keyword", "important"); + } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (ch === "-") { + if (/[\d.]/.test(stream.peek())) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (stream.match(/^-[\w\\\-]*/)) { + stream.eatWhile(/[\w\\\-]/); + if (stream.match(/^\s*:/, false)) + return ret("variable-2", "variable-definition"); + return ret("variable-2", "variable"); + } else if (stream.match(/^\w+-/)) { + return ret("meta", "meta"); + } + } else if (/[,+>*\/]/.test(ch)) { + return ret(null, "select-op"); + } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) { + return ret("qualifier", "qualifier"); + } else if (/[:;{}\[\]\(\)]/.test(ch)) { + return ret(null, ch); + } else if (stream.match(/^[\w-.]+(?=\()/)) { + if (/^(url(-prefix)?|domain|regexp)$/i.test(stream.current())) { + state.tokenize = tokenParenthesized; + } + return ret("variable callee", "variable"); + } else if (/[\w\\\-]/.test(ch)) { + stream.eatWhile(/[\w\\\-]/); + return ret("property", "word"); + } else { + return ret(null, null); + } + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) { + if (quote == ")") stream.backUp(1); + break; + } + escaped = !escaped && ch == "\\"; + } + if (ch == quote || !escaped && quote != ")") state.tokenize = null; + return ret("string", "string"); + }; + } + + function tokenParenthesized(stream, state) { + stream.next(); // Must be '(' + if (!stream.match(/^\s*[\"\')]/, false)) + state.tokenize = tokenString(")"); + else + state.tokenize = null; + return ret(null, "("); + } + + // Context management + + function Context(type, indent, prev) { + this.type = type; + this.indent = indent; + this.prev = prev; + } + + function pushContext(state, stream, type, indent) { + state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context); + return type; + } + + function popContext(state) { + if (state.context.prev) + state.context = state.context.prev; + return state.context.type; + } + + function pass(type, stream, state) { + return states[state.context.type](type, stream, state); + } + function popAndPass(type, stream, state, n) { + for (var i = n || 1; i > 0; i--) + state.context = state.context.prev; + return pass(type, stream, state); + } + + // Parser + + function wordAsValue(stream) { + var word = stream.current().toLowerCase(); + if (valueKeywords.hasOwnProperty(word)) + override = "atom"; + else if (colorKeywords.hasOwnProperty(word)) + override = "keyword"; + else + override = "variable"; + } + + var states = {}; + + states.top = function(type, stream, state) { + if (type == "{") { + return pushContext(state, stream, "block"); + } else if (type == "}" && state.context.prev) { + return popContext(state); + } else if (supportsAtComponent && /@component/i.test(type)) { + return pushContext(state, stream, "atComponentBlock"); + } else if (/^@(-moz-)?document$/i.test(type)) { + return pushContext(state, stream, "documentTypes"); + } else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) { + return pushContext(state, stream, "atBlock"); + } else if (/^@(font-face|counter-style)/i.test(type)) { + state.stateArg = type; + return "restricted_atBlock_before"; + } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) { + return "keyframes"; + } else if (type && type.charAt(0) == "@") { + return pushContext(state, stream, "at"); + } else if (type == "hash") { + override = "builtin"; + } else if (type == "word") { + override = "tag"; + } else if (type == "variable-definition") { + return "maybeprop"; + } else if (type == "interpolation") { + return pushContext(state, stream, "interpolation"); + } else if (type == ":") { + return "pseudo"; + } else if (allowNested && type == "(") { + return pushContext(state, stream, "parens"); + } + return state.context.type; + }; + + states.block = function(type, stream, state) { + if (type == "word") { + var word = stream.current().toLowerCase(); + if (propertyKeywords.hasOwnProperty(word)) { + override = "property"; + return "maybeprop"; + } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) { + override = highlightNonStandardPropertyKeywords ? "string-2" : "property"; + return "maybeprop"; + } else if (allowNested) { + override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag"; + return "block"; + } else { + override += " error"; + return "maybeprop"; + } + } else if (type == "meta") { + return "block"; + } else if (!allowNested && (type == "hash" || type == "qualifier")) { + override = "error"; + return "block"; + } else { + return states.top(type, stream, state); + } + }; + + states.maybeprop = function(type, stream, state) { + if (type == ":") return pushContext(state, stream, "prop"); + return pass(type, stream, state); + }; + + states.prop = function(type, stream, state) { + if (type == ";") return popContext(state); + if (type == "{" && allowNested) return pushContext(state, stream, "propBlock"); + if (type == "}" || type == "{") return popAndPass(type, stream, state); + if (type == "(") return pushContext(state, stream, "parens"); + + if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) { + override += " error"; + } else if (type == "word") { + wordAsValue(stream); + } else if (type == "interpolation") { + return pushContext(state, stream, "interpolation"); + } + return "prop"; + }; + + states.propBlock = function(type, _stream, state) { + if (type == "}") return popContext(state); + if (type == "word") { override = "property"; return "maybeprop"; } + return state.context.type; + }; + + states.parens = function(type, stream, state) { + if (type == "{" || type == "}") return popAndPass(type, stream, state); + if (type == ")") return popContext(state); + if (type == "(") return pushContext(state, stream, "parens"); + if (type == "interpolation") return pushContext(state, stream, "interpolation"); + if (type == "word") wordAsValue(stream); + return "parens"; + }; + + states.pseudo = function(type, stream, state) { + if (type == "meta") return "pseudo"; + + if (type == "word") { + override = "variable-3"; + return state.context.type; + } + return pass(type, stream, state); + }; + + states.documentTypes = function(type, stream, state) { + if (type == "word" && documentTypes.hasOwnProperty(stream.current())) { + override = "tag"; + return state.context.type; + } else { + return states.atBlock(type, stream, state); + } + }; + + states.atBlock = function(type, stream, state) { + if (type == "(") return pushContext(state, stream, "atBlock_parens"); + if (type == "}" || type == ";") return popAndPass(type, stream, state); + if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top"); + + if (type == "interpolation") return pushContext(state, stream, "interpolation"); + + if (type == "word") { + var word = stream.current().toLowerCase(); + if (word == "only" || word == "not" || word == "and" || word == "or") + override = "keyword"; + else if (mediaTypes.hasOwnProperty(word)) + override = "attribute"; + else if (mediaFeatures.hasOwnProperty(word)) + override = "property"; + else if (mediaValueKeywords.hasOwnProperty(word)) + override = "keyword"; + else if (propertyKeywords.hasOwnProperty(word)) + override = "property"; + else if (nonStandardPropertyKeywords.hasOwnProperty(word)) + override = highlightNonStandardPropertyKeywords ? "string-2" : "property"; + else if (valueKeywords.hasOwnProperty(word)) + override = "atom"; + else if (colorKeywords.hasOwnProperty(word)) + override = "keyword"; + else + override = "error"; + } + return state.context.type; + }; + + states.atComponentBlock = function(type, stream, state) { + if (type == "}") + return popAndPass(type, stream, state); + if (type == "{") + return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false); + if (type == "word") + override = "error"; + return state.context.type; + }; + + states.atBlock_parens = function(type, stream, state) { + if (type == ")") return popContext(state); + if (type == "{" || type == "}") return popAndPass(type, stream, state, 2); + return states.atBlock(type, stream, state); + }; + + states.restricted_atBlock_before = function(type, stream, state) { + if (type == "{") + return pushContext(state, stream, "restricted_atBlock"); + if (type == "word" && state.stateArg == "@counter-style") { + override = "variable"; + return "restricted_atBlock_before"; + } + return pass(type, stream, state); + }; + + states.restricted_atBlock = function(type, stream, state) { + if (type == "}") { + state.stateArg = null; + return popContext(state); + } + if (type == "word") { + if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) || + (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase()))) + override = "error"; + else + override = "property"; + return "maybeprop"; + } + return "restricted_atBlock"; + }; + + states.keyframes = function(type, stream, state) { + if (type == "word") { override = "variable"; return "keyframes"; } + if (type == "{") return pushContext(state, stream, "top"); + return pass(type, stream, state); + }; + + states.at = function(type, stream, state) { + if (type == ";") return popContext(state); + if (type == "{" || type == "}") return popAndPass(type, stream, state); + if (type == "word") override = "tag"; + else if (type == "hash") override = "builtin"; + return "at"; + }; + + states.interpolation = function(type, stream, state) { + if (type == "}") return popContext(state); + if (type == "{" || type == ";") return popAndPass(type, stream, state); + if (type == "word") override = "variable"; + else if (type != "variable" && type != "(" && type != ")") override = "error"; + return "interpolation"; + }; + + return { + startState: function(base) { + return {tokenize: null, + state: inline ? "block" : "top", + stateArg: null, + context: new Context(inline ? "block" : "top", base || 0, null)}; + }, + + token: function(stream, state) { + if (!state.tokenize && stream.eatSpace()) return null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style && typeof style == "object") { + type = style[1]; + style = style[0]; + } + override = style; + if (type != "comment") + state.state = states[state.state](type, stream, state); + return override; + }, + + indent: function(state, textAfter) { + var cx = state.context, ch = textAfter && textAfter.charAt(0); + var indent = cx.indent; + if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev; + if (cx.prev) { + if (ch == "}" && (cx.type == "block" || cx.type == "top" || + cx.type == "interpolation" || cx.type == "restricted_atBlock")) { + // Resume indentation from parent context. + cx = cx.prev; + indent = cx.indent; + } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") || + ch == "{" && (cx.type == "at" || cx.type == "atBlock")) { + // Dedent relative to current context. + indent = Math.max(0, cx.indent - indentUnit); + } + } + return indent; + }, + + electricChars: "}", + blockCommentStart: "/*", + blockCommentEnd: "*/", + blockCommentContinue: " * ", + lineComment: lineComment, + fold: "brace" + }; +}); + + function keySet(array) { + var keys = {}; + for (var i = 0; i < array.length; ++i) { + keys[array[i].toLowerCase()] = true; + } + return keys; + } + + var documentTypes_ = [ + "domain", "regexp", "url", "url-prefix" + ], documentTypes = keySet(documentTypes_); + + var mediaTypes_ = [ + "all", "aural", "braille", "handheld", "print", "projection", "screen", + "tty", "tv", "embossed" + ], mediaTypes = keySet(mediaTypes_); + + var mediaFeatures_ = [ + "width", "min-width", "max-width", "height", "min-height", "max-height", + "device-width", "min-device-width", "max-device-width", "device-height", + "min-device-height", "max-device-height", "aspect-ratio", + "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio", + "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color", + "max-color", "color-index", "min-color-index", "max-color-index", + "monochrome", "min-monochrome", "max-monochrome", "resolution", + "min-resolution", "max-resolution", "scan", "grid", "orientation", + "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio", + "pointer", "any-pointer", "hover", "any-hover", "prefers-color-scheme", + "dynamic-range", "video-dynamic-range" + ], mediaFeatures = keySet(mediaFeatures_); + + var mediaValueKeywords_ = [ + "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover", + "interlace", "progressive", + "dark", "light", + "standard", "high" + ], mediaValueKeywords = keySet(mediaValueKeywords_); + + var propertyKeywords_ = [ + "align-content", "align-items", "align-self", "alignment-adjust", + "alignment-baseline", "all", "anchor-point", "animation", "animation-delay", + "animation-direction", "animation-duration", "animation-fill-mode", + "animation-iteration-count", "animation-name", "animation-play-state", + "animation-timing-function", "appearance", "azimuth", "backdrop-filter", + "backface-visibility", "background", "background-attachment", + "background-blend-mode", "background-clip", "background-color", + "background-image", "background-origin", "background-position", + "background-position-x", "background-position-y", "background-repeat", + "background-size", "baseline-shift", "binding", "bleed", "block-size", + "bookmark-label", "bookmark-level", "bookmark-state", "bookmark-target", + "border", "border-bottom", "border-bottom-color", "border-bottom-left-radius", + "border-bottom-right-radius", "border-bottom-style", "border-bottom-width", + "border-collapse", "border-color", "border-image", "border-image-outset", + "border-image-repeat", "border-image-slice", "border-image-source", + "border-image-width", "border-left", "border-left-color", "border-left-style", + "border-left-width", "border-radius", "border-right", "border-right-color", + "border-right-style", "border-right-width", "border-spacing", "border-style", + "border-top", "border-top-color", "border-top-left-radius", + "border-top-right-radius", "border-top-style", "border-top-width", + "border-width", "bottom", "box-decoration-break", "box-shadow", "box-sizing", + "break-after", "break-before", "break-inside", "caption-side", "caret-color", + "clear", "clip", "color", "color-profile", "column-count", "column-fill", + "column-gap", "column-rule", "column-rule-color", "column-rule-style", + "column-rule-width", "column-span", "column-width", "columns", "contain", + "content", "counter-increment", "counter-reset", "crop", "cue", "cue-after", + "cue-before", "cursor", "direction", "display", "dominant-baseline", + "drop-initial-after-adjust", "drop-initial-after-align", + "drop-initial-before-adjust", "drop-initial-before-align", "drop-initial-size", + "drop-initial-value", "elevation", "empty-cells", "fit", "fit-content", "fit-position", + "flex", "flex-basis", "flex-direction", "flex-flow", "flex-grow", + "flex-shrink", "flex-wrap", "float", "float-offset", "flow-from", "flow-into", + "font", "font-family", "font-feature-settings", "font-kerning", + "font-language-override", "font-optical-sizing", "font-size", + "font-size-adjust", "font-stretch", "font-style", "font-synthesis", + "font-variant", "font-variant-alternates", "font-variant-caps", + "font-variant-east-asian", "font-variant-ligatures", "font-variant-numeric", + "font-variant-position", "font-variation-settings", "font-weight", "gap", + "grid", "grid-area", "grid-auto-columns", "grid-auto-flow", "grid-auto-rows", + "grid-column", "grid-column-end", "grid-column-gap", "grid-column-start", + "grid-gap", "grid-row", "grid-row-end", "grid-row-gap", "grid-row-start", + "grid-template", "grid-template-areas", "grid-template-columns", + "grid-template-rows", "hanging-punctuation", "height", "hyphens", "icon", + "image-orientation", "image-rendering", "image-resolution", "inline-box-align", + "inset", "inset-block", "inset-block-end", "inset-block-start", "inset-inline", + "inset-inline-end", "inset-inline-start", "isolation", "justify-content", + "justify-items", "justify-self", "left", "letter-spacing", "line-break", + "line-height", "line-height-step", "line-stacking", "line-stacking-ruby", + "line-stacking-shift", "line-stacking-strategy", "list-style", + "list-style-image", "list-style-position", "list-style-type", "margin", + "margin-bottom", "margin-left", "margin-right", "margin-top", "marks", + "marquee-direction", "marquee-loop", "marquee-play-count", "marquee-speed", + "marquee-style", "mask-clip", "mask-composite", "mask-image", "mask-mode", + "mask-origin", "mask-position", "mask-repeat", "mask-size","mask-type", + "max-block-size", "max-height", "max-inline-size", + "max-width", "min-block-size", "min-height", "min-inline-size", "min-width", + "mix-blend-mode", "move-to", "nav-down", "nav-index", "nav-left", "nav-right", + "nav-up", "object-fit", "object-position", "offset", "offset-anchor", + "offset-distance", "offset-path", "offset-position", "offset-rotate", + "opacity", "order", "orphans", "outline", "outline-color", "outline-offset", + "outline-style", "outline-width", "overflow", "overflow-style", + "overflow-wrap", "overflow-x", "overflow-y", "padding", "padding-bottom", + "padding-left", "padding-right", "padding-top", "page", "page-break-after", + "page-break-before", "page-break-inside", "page-policy", "pause", + "pause-after", "pause-before", "perspective", "perspective-origin", "pitch", + "pitch-range", "place-content", "place-items", "place-self", "play-during", + "position", "presentation-level", "punctuation-trim", "quotes", + "region-break-after", "region-break-before", "region-break-inside", + "region-fragment", "rendering-intent", "resize", "rest", "rest-after", + "rest-before", "richness", "right", "rotate", "rotation", "rotation-point", + "row-gap", "ruby-align", "ruby-overhang", "ruby-position", "ruby-span", + "scale", "scroll-behavior", "scroll-margin", "scroll-margin-block", + "scroll-margin-block-end", "scroll-margin-block-start", "scroll-margin-bottom", + "scroll-margin-inline", "scroll-margin-inline-end", + "scroll-margin-inline-start", "scroll-margin-left", "scroll-margin-right", + "scroll-margin-top", "scroll-padding", "scroll-padding-block", + "scroll-padding-block-end", "scroll-padding-block-start", + "scroll-padding-bottom", "scroll-padding-inline", "scroll-padding-inline-end", + "scroll-padding-inline-start", "scroll-padding-left", "scroll-padding-right", + "scroll-padding-top", "scroll-snap-align", "scroll-snap-type", + "shape-image-threshold", "shape-inside", "shape-margin", "shape-outside", + "size", "speak", "speak-as", "speak-header", "speak-numeral", + "speak-punctuation", "speech-rate", "stress", "string-set", "tab-size", + "table-layout", "target", "target-name", "target-new", "target-position", + "text-align", "text-align-last", "text-combine-upright", "text-decoration", + "text-decoration-color", "text-decoration-line", "text-decoration-skip", + "text-decoration-skip-ink", "text-decoration-style", "text-emphasis", + "text-emphasis-color", "text-emphasis-position", "text-emphasis-style", + "text-height", "text-indent", "text-justify", "text-orientation", + "text-outline", "text-overflow", "text-rendering", "text-shadow", + "text-size-adjust", "text-space-collapse", "text-transform", + "text-underline-position", "text-wrap", "top", "touch-action", "transform", "transform-origin", + "transform-style", "transition", "transition-delay", "transition-duration", + "transition-property", "transition-timing-function", "translate", + "unicode-bidi", "user-select", "vertical-align", "visibility", "voice-balance", + "voice-duration", "voice-family", "voice-pitch", "voice-range", "voice-rate", + "voice-stress", "voice-volume", "volume", "white-space", "widows", "width", + "will-change", "word-break", "word-spacing", "word-wrap", "writing-mode", "z-index", + // SVG-specific + "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color", + "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events", + "color-interpolation", "color-interpolation-filters", + "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering", + "marker", "marker-end", "marker-mid", "marker-start", "paint-order", "shape-rendering", "stroke", + "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", + "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering", + "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal", + "glyph-orientation-vertical", "text-anchor", "writing-mode", + ], propertyKeywords = keySet(propertyKeywords_); + + var nonStandardPropertyKeywords_ = [ + "accent-color", "aspect-ratio", "border-block", "border-block-color", "border-block-end", + "border-block-end-color", "border-block-end-style", "border-block-end-width", + "border-block-start", "border-block-start-color", "border-block-start-style", + "border-block-start-width", "border-block-style", "border-block-width", + "border-inline", "border-inline-color", "border-inline-end", + "border-inline-end-color", "border-inline-end-style", + "border-inline-end-width", "border-inline-start", "border-inline-start-color", + "border-inline-start-style", "border-inline-start-width", + "border-inline-style", "border-inline-width", "content-visibility", "margin-block", + "margin-block-end", "margin-block-start", "margin-inline", "margin-inline-end", + "margin-inline-start", "overflow-anchor", "overscroll-behavior", "padding-block", "padding-block-end", + "padding-block-start", "padding-inline", "padding-inline-end", + "padding-inline-start", "scroll-snap-stop", "scrollbar-3d-light-color", + "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color", + "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color", + "scrollbar-track-color", "searchfield-cancel-button", "searchfield-decoration", + "searchfield-results-button", "searchfield-results-decoration", "shape-inside", "zoom" + ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_); + + var fontProperties_ = [ + "font-display", "font-family", "src", "unicode-range", "font-variant", + "font-feature-settings", "font-stretch", "font-weight", "font-style" + ], fontProperties = keySet(fontProperties_); + + var counterDescriptors_ = [ + "additive-symbols", "fallback", "negative", "pad", "prefix", "range", + "speak-as", "suffix", "symbols", "system" + ], counterDescriptors = keySet(counterDescriptors_); + + var colorKeywords_ = [ + "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", + "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", + "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", + "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", + "darkgray", "darkgreen", "darkgrey", "darkkhaki", "darkmagenta", "darkolivegreen", + "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", + "darkslateblue", "darkslategray", "darkslategrey", "darkturquoise", "darkviolet", + "deeppink", "deepskyblue", "dimgray", "dimgrey", "dodgerblue", "firebrick", + "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", + "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew", + "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", + "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", + "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightgrey", "lightpink", + "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightslategrey", + "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", + "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", + "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", + "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", + "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", + "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", + "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", + "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown", + "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", + "slateblue", "slategray", "slategrey", "snow", "springgreen", "steelblue", "tan", + "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", + "whitesmoke", "yellow", "yellowgreen" + ], colorKeywords = keySet(colorKeywords_); + + var valueKeywords_ = [ + "above", "absolute", "activeborder", "additive", "activecaption", "afar", + "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate", + "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", + "arabic-indic", "armenian", "asterisks", "attr", "auto", "auto-flow", "avoid", "avoid-column", "avoid-page", + "avoid-region", "axis-pan", "background", "backwards", "baseline", "below", "bidi-override", "binary", + "bengali", "blink", "block", "block-axis", "blur", "bold", "bolder", "border", "border-box", + "both", "bottom", "break", "break-all", "break-word", "brightness", "bullets", "button", "button-bevel", + "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian", + "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", + "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch", + "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", + "col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse", + "compact", "condensed", "conic-gradient", "contain", "content", "contents", + "content-box", "context-menu", "continuous", "contrast", "copy", "counter", "counters", "cover", "crop", + "cross", "crosshair", "cubic-bezier", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal", + "decimal-leading-zero", "default", "default-button", "dense", "destination-atop", + "destination-in", "destination-out", "destination-over", "devanagari", "difference", + "disc", "discard", "disclosure-closed", "disclosure-open", "document", + "dot-dash", "dot-dot-dash", + "dotted", "double", "down", "drop-shadow", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", + "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", + "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er", + "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", + "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et", + "ethiopic-halehame-gez", "ethiopic-halehame-om-et", + "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et", + "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig", + "ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed", + "extra-expanded", "fantasy", "fast", "fill", "fill-box", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes", + "forwards", "from", "geometricPrecision", "georgian", "grayscale", "graytext", "grid", "groove", + "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew", + "help", "hidden", "hide", "higher", "highlight", "highlighttext", + "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "hue-rotate", "icon", "ignore", + "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", + "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", + "inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert", + "italic", "japanese-formal", "japanese-informal", "justify", "kannada", + "katakana", "katakana-iroha", "keep-all", "khmer", + "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal", + "landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten", + "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem", + "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", + "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian", + "lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "manipulation", "match", "matrix", "matrix3d", + "media-controls-background", "media-current-time-display", + "media-fullscreen-button", "media-mute-button", "media-play-button", + "media-return-to-realtime-button", "media-rewind-button", + "media-seek-back-button", "media-seek-forward-button", "media-slider", + "media-sliderthumb", "media-time-remaining-display", "media-volume-slider", + "media-volume-slider-container", "media-volume-sliderthumb", "medium", + "menu", "menulist", "menulist-button", "menulist-text", + "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic", + "mix", "mongolian", "monospace", "move", "multiple", "multiple_mask_images", "multiply", "myanmar", "n-resize", + "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", + "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", + "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "opacity", "open-quote", + "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", + "outside", "outside-shape", "overlay", "overline", "padding", "padding-box", + "painted", "page", "paused", "persian", "perspective", "pinch-zoom", "plus-darker", "plus-lighter", + "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", + "progress", "push-button", "radial-gradient", "radio", "read-only", + "read-write", "read-write-plaintext-only", "rectangle", "region", + "relative", "repeat", "repeating-linear-gradient", "repeating-radial-gradient", + "repeating-conic-gradient", "repeat-x", "repeat-y", "reset", "reverse", + "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY", + "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running", + "s-resize", "sans-serif", "saturate", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen", + "scroll", "scrollbar", "scroll-position", "se-resize", "searchfield", + "searchfield-cancel-button", "searchfield-decoration", + "searchfield-results-button", "searchfield-results-decoration", "self-start", "self-end", + "semi-condensed", "semi-expanded", "separate", "sepia", "serif", "show", "sidama", + "simp-chinese-formal", "simp-chinese-informal", "single", + "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal", + "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", + "small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali", + "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "space-evenly", "spell-out", "square", + "square-button", "start", "static", "status-bar", "stretch", "stroke", "stroke-box", "sub", + "subpixel-antialiased", "svg_masks", "super", "sw-resize", "symbolic", "symbols", "system-ui", "table", + "table-caption", "table-cell", "table-column", "table-column-group", + "table-footer-group", "table-header-group", "table-row", "table-row-group", + "tamil", + "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai", + "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight", + "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er", + "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top", + "trad-chinese-formal", "trad-chinese-informal", "transform", + "translate", "translate3d", "translateX", "translateY", "translateZ", + "transparent", "ultra-condensed", "ultra-expanded", "underline", "unidirectional-pan", "unset", "up", + "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", + "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", + "var", "vertical", "vertical-text", "view-box", "visible", "visibleFill", "visiblePainted", + "visibleStroke", "visual", "w-resize", "wait", "wave", "wider", + "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor", + "xx-large", "xx-small" + ], valueKeywords = keySet(valueKeywords_); + + var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_) + .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_) + .concat(valueKeywords_); + CodeMirror.registerHelper("hintWords", "css", allWords); + + function tokenCComment(stream, state) { + var maybeEnd = false, ch; + while ((ch = stream.next()) != null) { + if (maybeEnd && ch == "/") { + state.tokenize = null; + break; + } + maybeEnd = (ch == "*"); + } + return ["comment", "comment"]; + } + + CodeMirror.defineMIME("text/css", { + documentTypes: documentTypes, + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + fontProperties: fontProperties, + counterDescriptors: counterDescriptors, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + tokenHooks: { + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + }, + name: "css" + }); + + CodeMirror.defineMIME("text/x-scss", { + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + fontProperties: fontProperties, + allowNested: true, + lineComment: "//", + tokenHooks: { + "/": function(stream, state) { + if (stream.eat("/")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } else if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else { + return ["operator", "operator"]; + } + }, + ":": function(stream) { + if (stream.match(/^\s*\{/, false)) + return [null, null] + return false; + }, + "$": function(stream) { + stream.match(/^[\w-]+/); + if (stream.match(/^\s*:/, false)) + return ["variable-2", "variable-definition"]; + return ["variable-2", "variable"]; + }, + "#": function(stream) { + if (!stream.eat("{")) return false; + return [null, "interpolation"]; + } + }, + name: "css", + helperType: "scss" + }); + + CodeMirror.defineMIME("text/x-less", { + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + mediaValueKeywords: mediaValueKeywords, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + fontProperties: fontProperties, + allowNested: true, + lineComment: "//", + tokenHooks: { + "/": function(stream, state) { + if (stream.eat("/")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } else if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else { + return ["operator", "operator"]; + } + }, + "@": function(stream) { + if (stream.eat("{")) return [null, "interpolation"]; + if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i, false)) return false; + stream.eatWhile(/[\w\\\-]/); + if (stream.match(/^\s*:/, false)) + return ["variable-2", "variable-definition"]; + return ["variable-2", "variable"]; + }, + "&": function() { + return ["atom", "atom"]; + } + }, + name: "css", + helperType: "less" + }); + + CodeMirror.defineMIME("text/x-gss", { + documentTypes: documentTypes, + mediaTypes: mediaTypes, + mediaFeatures: mediaFeatures, + propertyKeywords: propertyKeywords, + nonStandardPropertyKeywords: nonStandardPropertyKeywords, + fontProperties: fontProperties, + counterDescriptors: counterDescriptors, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + supportsAtComponent: true, + tokenHooks: { + "/": function(stream, state) { + if (!stream.eat("*")) return false; + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + }, + name: "css", + helperType: "gss" + }); + +}); diff --git a/js/codemirror/5.65.1/javascript.js b/js/codemirror/5.65.1/javascript.js new file mode 100644 index 0000000..7cfee31 --- /dev/null +++ b/js/codemirror/5.65.1/javascript.js @@ -0,0 +1,960 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("javascript", function(config, parserConfig) { + var indentUnit = config.indentUnit; + var statementIndent = parserConfig.statementIndent; + var jsonldMode = parserConfig.jsonld; + var jsonMode = parserConfig.json || jsonldMode; + var trackScope = parserConfig.trackScope !== false + var isTS = parserConfig.typescript; + var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; + + // Tokenizer + + var keywords = function(){ + function kw(type) {return {type: type, style: "keyword"};} + var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d"); + var operator = kw("operator"), atom = {type: "atom", style: "atom"}; + + return { + "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, + "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C, + "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"), + "function": kw("function"), "catch": kw("catch"), + "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), + "in": operator, "typeof": operator, "instanceof": operator, + "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, + "this": kw("this"), "class": kw("class"), "super": kw("atom"), + "yield": C, "export": kw("export"), "import": kw("import"), "extends": C, + "await": C + }; + }(); + + var isOperatorChar = /[+\-*&%=<>!?|~^@]/; + var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; + + function readRegexp(stream) { + var escaped = false, next, inSet = false; + while ((next = stream.next()) != null) { + if (!escaped) { + if (next == "/" && !inSet) return; + if (next == "[") inSet = true; + else if (inSet && next == "]") inSet = false; + } + escaped = !escaped && next == "\\"; + } + } + + // Used as scratch variables to communicate multiple values without + // consing up tons of objects. + var type, content; + function ret(tp, style, cont) { + type = tp; content = cont; + return style; + } + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) { + return ret("number", "number"); + } else if (ch == "." && stream.match("..")) { + return ret("spread", "meta"); + } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + return ret(ch); + } else if (ch == "=" && stream.eat(">")) { + return ret("=>", "operator"); + } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) { + return ret("number", "number"); + } else if (/\d/.test(ch)) { + stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/); + return ret("number", "number"); + } else if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } else if (stream.eat("/")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } else if (expressionAllowed(stream, state, 1)) { + readRegexp(stream); + stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); + return ret("regexp", "string-2"); + } else { + stream.eat("="); + return ret("operator", "operator", stream.current()); + } + } else if (ch == "`") { + state.tokenize = tokenQuasi; + return tokenQuasi(stream, state); + } else if (ch == "#" && stream.peek() == "!") { + stream.skipToEnd(); + return ret("meta", "meta"); + } else if (ch == "#" && stream.eatWhile(wordRE)) { + return ret("variable", "property") + } else if (ch == "<" && stream.match("!--") || + (ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start)))) { + stream.skipToEnd() + return ret("comment", "comment") + } else if (isOperatorChar.test(ch)) { + if (ch != ">" || !state.lexical || state.lexical.type != ">") { + if (stream.eat("=")) { + if (ch == "!" || ch == "=") stream.eat("=") + } else if (/[<>*+\-|&?]/.test(ch)) { + stream.eat(ch) + if (ch == ">") stream.eat(ch) + } + } + if (ch == "?" && stream.eat(".")) return ret(".") + return ret("operator", "operator", stream.current()); + } else if (wordRE.test(ch)) { + stream.eatWhile(wordRE); + var word = stream.current() + if (state.lastType != ".") { + if (keywords.propertyIsEnumerable(word)) { + var kw = keywords[word] + return ret(kw.type, kw.style, word) + } + if (word == "async" && stream.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, false)) + return ret("async", "keyword", word) + } + return ret("variable", "variable", word) + } + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next; + if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ + state.tokenize = tokenBase; + return ret("jsonld-keyword", "meta"); + } + while ((next = stream.next()) != null) { + if (next == quote && !escaped) break; + escaped = !escaped && next == "\\"; + } + if (!escaped) state.tokenize = tokenBase; + return ret("string", "string"); + }; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return ret("comment", "comment"); + } + + function tokenQuasi(stream, state) { + var escaped = false, next; + while ((next = stream.next()) != null) { + if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { + state.tokenize = tokenBase; + break; + } + escaped = !escaped && next == "\\"; + } + return ret("quasi", "string-2", stream.current()); + } + + var brackets = "([{}])"; + // This is a crude lookahead trick to try and notice that we're + // parsing the argument patterns for a fat-arrow function before we + // actually hit the arrow token. It only works if the arrow is on + // the same line as the arguments and there's no strange noise + // (comments) in between. Fallback is to only notice when we hit the + // arrow, and not declare the arguments as locals for the arrow + // body. + function findFatArrow(stream, state) { + if (state.fatArrowAt) state.fatArrowAt = null; + var arrow = stream.string.indexOf("=>", stream.start); + if (arrow < 0) return; + + if (isTS) { // Try to skip TypeScript return type declarations after the arguments + var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)) + if (m) arrow = m.index + } + + var depth = 0, sawSomething = false; + for (var pos = arrow - 1; pos >= 0; --pos) { + var ch = stream.string.charAt(pos); + var bracket = brackets.indexOf(ch); + if (bracket >= 0 && bracket < 3) { + if (!depth) { ++pos; break; } + if (--depth == 0) { if (ch == "(") sawSomething = true; break; } + } else if (bracket >= 3 && bracket < 6) { + ++depth; + } else if (wordRE.test(ch)) { + sawSomething = true; + } else if (/["'\/`]/.test(ch)) { + for (;; --pos) { + if (pos == 0) return + var next = stream.string.charAt(pos - 1) + if (next == ch && stream.string.charAt(pos - 2) != "\\") { pos--; break } + } + } else if (sawSomething && !depth) { + ++pos; + break; + } + } + if (sawSomething && !depth) state.fatArrowAt = pos; + } + + // Parser + + var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, + "regexp": true, "this": true, "import": true, "jsonld-keyword": true}; + + function JSLexical(indented, column, type, align, prev, info) { + this.indented = indented; + this.column = column; + this.type = type; + this.prev = prev; + this.info = info; + if (align != null) this.align = align; + } + + function inScope(state, varname) { + if (!trackScope) return false + for (var v = state.localVars; v; v = v.next) + if (v.name == varname) return true; + for (var cx = state.context; cx; cx = cx.prev) { + for (var v = cx.vars; v; v = v.next) + if (v.name == varname) return true; + } + } + + function parseJS(state, style, type, content, stream) { + var cc = state.cc; + // Communicate our context to the combinators. + // (Less wasteful than consing up a hundred closures on every call.) + cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; + + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = true; + + while(true) { + var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; + if (combinator(type, content)) { + while(cc.length && cc[cc.length - 1].lex) + cc.pop()(); + if (cx.marked) return cx.marked; + if (type == "variable" && inScope(state, content)) return "variable-2"; + return style; + } + } + } + + // Combinator utils + + var cx = {state: null, column: null, marked: null, cc: null}; + function pass() { + for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); + } + function cont() { + pass.apply(null, arguments); + return true; + } + function inList(name, list) { + for (var v = list; v; v = v.next) if (v.name == name) return true + return false; + } + function register(varname) { + var state = cx.state; + cx.marked = "def"; + if (!trackScope) return + if (state.context) { + if (state.lexical.info == "var" && state.context && state.context.block) { + // FIXME function decls are also not block scoped + var newContext = registerVarScoped(varname, state.context) + if (newContext != null) { + state.context = newContext + return + } + } else if (!inList(varname, state.localVars)) { + state.localVars = new Var(varname, state.localVars) + return + } + } + // Fall through means this is global + if (parserConfig.globalVars && !inList(varname, state.globalVars)) + state.globalVars = new Var(varname, state.globalVars) + } + function registerVarScoped(varname, context) { + if (!context) { + return null + } else if (context.block) { + var inner = registerVarScoped(varname, context.prev) + if (!inner) return null + if (inner == context.prev) return context + return new Context(inner, context.vars, true) + } else if (inList(varname, context.vars)) { + return context + } else { + return new Context(context.prev, new Var(varname, context.vars), false) + } + } + + function isModifier(name) { + return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly" + } + + // Combinators + + function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block } + function Var(name, next) { this.name = name; this.next = next } + + var defaultVars = new Var("this", new Var("arguments", null)) + function pushcontext() { + cx.state.context = new Context(cx.state.context, cx.state.localVars, false) + cx.state.localVars = defaultVars + } + function pushblockcontext() { + cx.state.context = new Context(cx.state.context, cx.state.localVars, true) + cx.state.localVars = null + } + pushcontext.lex = pushblockcontext.lex = true + function popcontext() { + cx.state.localVars = cx.state.context.vars + cx.state.context = cx.state.context.prev + } + popcontext.lex = true + function pushlex(type, info) { + var result = function() { + var state = cx.state, indent = state.indented; + if (state.lexical.type == "stat") indent = state.lexical.indented; + else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) + indent = outer.indented; + state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); + }; + result.lex = true; + return result; + } + function poplex() { + var state = cx.state; + if (state.lexical.prev) { + if (state.lexical.type == ")") + state.indented = state.lexical.indented; + state.lexical = state.lexical.prev; + } + } + poplex.lex = true; + + function expect(wanted) { + function exp(type) { + if (type == wanted) return cont(); + else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass(); + else return cont(exp); + }; + return exp; + } + + function statement(type, value) { + if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex); + if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); + if (type == "keyword b") return cont(pushlex("form"), statement, poplex); + if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); + if (type == "debugger") return cont(expect(";")); + if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext); + if (type == ";") return cont(); + if (type == "if") { + if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) + cx.state.cc.pop()(); + return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); + } + if (type == "function") return cont(functiondef); + if (type == "for") return cont(pushlex("form"), pushblockcontext, forspec, statement, popcontext, poplex); + if (type == "class" || (isTS && value == "interface")) { + cx.marked = "keyword" + return cont(pushlex("form", type == "class" ? type : value), className, poplex) + } + if (type == "variable") { + if (isTS && value == "declare") { + cx.marked = "keyword" + return cont(statement) + } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { + cx.marked = "keyword" + if (value == "enum") return cont(enumdef); + else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";")); + else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex) + } else if (isTS && value == "namespace") { + cx.marked = "keyword" + return cont(pushlex("form"), expression, statement, poplex) + } else if (isTS && value == "abstract") { + cx.marked = "keyword" + return cont(statement) + } else { + return cont(pushlex("stat"), maybelabel); + } + } + if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext, + block, poplex, poplex, popcontext); + if (type == "case") return cont(expression, expect(":")); + if (type == "default") return cont(expect(":")); + if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext); + if (type == "export") return cont(pushlex("stat"), afterExport, poplex); + if (type == "import") return cont(pushlex("stat"), afterImport, poplex); + if (type == "async") return cont(statement) + if (value == "@") return cont(expression, statement) + return pass(pushlex("stat"), expression, expect(";"), poplex); + } + function maybeCatchBinding(type) { + if (type == "(") return cont(funarg, expect(")")) + } + function expression(type, value) { + return expressionInner(type, value, false); + } + function expressionNoComma(type, value) { + return expressionInner(type, value, true); + } + function parenExpr(type) { + if (type != "(") return pass() + return cont(pushlex(")"), maybeexpression, expect(")"), poplex) + } + function expressionInner(type, value, noComma) { + if (cx.state.fatArrowAt == cx.stream.start) { + var body = noComma ? arrowBodyNoComma : arrowBody; + if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext); + else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); + } + + var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; + if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); + if (type == "function") return cont(functiondef, maybeop); + if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); } + if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression); + if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); + if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); + if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); + if (type == "{") return contCommasep(objprop, "}", null, maybeop); + if (type == "quasi") return pass(quasi, maybeop); + if (type == "new") return cont(maybeTarget(noComma)); + return cont(); + } + function maybeexpression(type) { + if (type.match(/[;\}\)\],]/)) return pass(); + return pass(expression); + } + + function maybeoperatorComma(type, value) { + if (type == ",") return cont(maybeexpression); + return maybeoperatorNoComma(type, value, false); + } + function maybeoperatorNoComma(type, value, noComma) { + var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; + var expr = noComma == false ? expression : expressionNoComma; + if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); + if (type == "operator") { + if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me); + if (isTS && value == "<" && cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false)) + return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me); + if (value == "?") return cont(expression, expect(":"), expr); + return cont(expr); + } + if (type == "quasi") { return pass(quasi, me); } + if (type == ";") return; + if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); + if (type == ".") return cont(property, me); + if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); + if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) } + if (type == "regexp") { + cx.state.lastType = cx.marked = "operator" + cx.stream.backUp(cx.stream.pos - cx.stream.start - 1) + return cont(expr) + } + } + function quasi(type, value) { + if (type != "quasi") return pass(); + if (value.slice(value.length - 2) != "${") return cont(quasi); + return cont(maybeexpression, continueQuasi); + } + function continueQuasi(type) { + if (type == "}") { + cx.marked = "string-2"; + cx.state.tokenize = tokenQuasi; + return cont(quasi); + } + } + function arrowBody(type) { + findFatArrow(cx.stream, cx.state); + return pass(type == "{" ? statement : expression); + } + function arrowBodyNoComma(type) { + findFatArrow(cx.stream, cx.state); + return pass(type == "{" ? statement : expressionNoComma); + } + function maybeTarget(noComma) { + return function(type) { + if (type == ".") return cont(noComma ? targetNoComma : target); + else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma) + else return pass(noComma ? expressionNoComma : expression); + }; + } + function target(_, value) { + if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); } + } + function targetNoComma(_, value) { + if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); } + } + function maybelabel(type) { + if (type == ":") return cont(poplex, statement); + return pass(maybeoperatorComma, expect(";"), poplex); + } + function property(type) { + if (type == "variable") {cx.marked = "property"; return cont();} + } + function objprop(type, value) { + if (type == "async") { + cx.marked = "property"; + return cont(objprop); + } else if (type == "variable" || cx.style == "keyword") { + cx.marked = "property"; + if (value == "get" || value == "set") return cont(getterSetter); + var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params + if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) + cx.state.fatArrowAt = cx.stream.pos + m[0].length + return cont(afterprop); + } else if (type == "number" || type == "string") { + cx.marked = jsonldMode ? "property" : (cx.style + " property"); + return cont(afterprop); + } else if (type == "jsonld-keyword") { + return cont(afterprop); + } else if (isTS && isModifier(value)) { + cx.marked = "keyword" + return cont(objprop) + } else if (type == "[") { + return cont(expression, maybetype, expect("]"), afterprop); + } else if (type == "spread") { + return cont(expressionNoComma, afterprop); + } else if (value == "*") { + cx.marked = "keyword"; + return cont(objprop); + } else if (type == ":") { + return pass(afterprop) + } + } + function getterSetter(type) { + if (type != "variable") return pass(afterprop); + cx.marked = "property"; + return cont(functiondef); + } + function afterprop(type) { + if (type == ":") return cont(expressionNoComma); + if (type == "(") return pass(functiondef); + } + function commasep(what, end, sep) { + function proceed(type, value) { + if (sep ? sep.indexOf(type) > -1 : type == ",") { + var lex = cx.state.lexical; + if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; + return cont(function(type, value) { + if (type == end || value == end) return pass() + return pass(what) + }, proceed); + } + if (type == end || value == end) return cont(); + if (sep && sep.indexOf(";") > -1) return pass(what) + return cont(expect(end)); + } + return function(type, value) { + if (type == end || value == end) return cont(); + return pass(what, proceed); + }; + } + function contCommasep(what, end, info) { + for (var i = 3; i < arguments.length; i++) + cx.cc.push(arguments[i]); + return cont(pushlex(end, info), commasep(what, end), poplex); + } + function block(type) { + if (type == "}") return cont(); + return pass(statement, block); + } + function maybetype(type, value) { + if (isTS) { + if (type == ":") return cont(typeexpr); + if (value == "?") return cont(maybetype); + } + } + function maybetypeOrIn(type, value) { + if (isTS && (type == ":" || value == "in")) return cont(typeexpr) + } + function mayberettype(type) { + if (isTS && type == ":") { + if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr) + else return cont(typeexpr) + } + } + function isKW(_, value) { + if (value == "is") { + cx.marked = "keyword" + return cont() + } + } + function typeexpr(type, value) { + if (value == "keyof" || value == "typeof" || value == "infer" || value == "readonly") { + cx.marked = "keyword" + return cont(value == "typeof" ? expressionNoComma : typeexpr) + } + if (type == "variable" || value == "void") { + cx.marked = "type" + return cont(afterType) + } + if (value == "|" || value == "&") return cont(typeexpr) + if (type == "string" || type == "number" || type == "atom") return cont(afterType); + if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType) + if (type == "{") return cont(pushlex("}"), typeprops, poplex, afterType) + if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType) + if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr) + if (type == "quasi") { return pass(quasiType, afterType); } + } + function maybeReturnType(type) { + if (type == "=>") return cont(typeexpr) + } + function typeprops(type) { + if (type.match(/[\}\)\]]/)) return cont() + if (type == "," || type == ";") return cont(typeprops) + return pass(typeprop, typeprops) + } + function typeprop(type, value) { + if (type == "variable" || cx.style == "keyword") { + cx.marked = "property" + return cont(typeprop) + } else if (value == "?" || type == "number" || type == "string") { + return cont(typeprop) + } else if (type == ":") { + return cont(typeexpr) + } else if (type == "[") { + return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop) + } else if (type == "(") { + return pass(functiondecl, typeprop) + } else if (!type.match(/[;\}\)\],]/)) { + return cont() + } + } + function quasiType(type, value) { + if (type != "quasi") return pass(); + if (value.slice(value.length - 2) != "${") return cont(quasiType); + return cont(typeexpr, continueQuasiType); + } + function continueQuasiType(type) { + if (type == "}") { + cx.marked = "string-2"; + cx.state.tokenize = tokenQuasi; + return cont(quasiType); + } + } + function typearg(type, value) { + if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg) + if (type == ":") return cont(typeexpr) + if (type == "spread") return cont(typearg) + return pass(typeexpr) + } + function afterType(type, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) + if (value == "|" || type == "." || value == "&") return cont(typeexpr) + if (type == "[") return cont(typeexpr, expect("]"), afterType) + if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) } + if (value == "?") return cont(typeexpr, expect(":"), typeexpr) + } + function maybeTypeArgs(_, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) + } + function typeparam() { + return pass(typeexpr, maybeTypeDefault) + } + function maybeTypeDefault(_, value) { + if (value == "=") return cont(typeexpr) + } + function vardef(_, value) { + if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)} + return pass(pattern, maybetype, maybeAssign, vardefCont); + } + function pattern(type, value) { + if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) } + if (type == "variable") { register(value); return cont(); } + if (type == "spread") return cont(pattern); + if (type == "[") return contCommasep(eltpattern, "]"); + if (type == "{") return contCommasep(proppattern, "}"); + } + function proppattern(type, value) { + if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { + register(value); + return cont(maybeAssign); + } + if (type == "variable") cx.marked = "property"; + if (type == "spread") return cont(pattern); + if (type == "}") return pass(); + if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern); + return cont(expect(":"), pattern, maybeAssign); + } + function eltpattern() { + return pass(pattern, maybeAssign) + } + function maybeAssign(_type, value) { + if (value == "=") return cont(expressionNoComma); + } + function vardefCont(type) { + if (type == ",") return cont(vardef); + } + function maybeelse(type, value) { + if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); + } + function forspec(type, value) { + if (value == "await") return cont(forspec); + if (type == "(") return cont(pushlex(")"), forspec1, poplex); + } + function forspec1(type) { + if (type == "var") return cont(vardef, forspec2); + if (type == "variable") return cont(forspec2); + return pass(forspec2) + } + function forspec2(type, value) { + if (type == ")") return cont() + if (type == ";") return cont(forspec2) + if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression, forspec2) } + return pass(expression, forspec2) + } + function functiondef(type, value) { + if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} + if (type == "variable") {register(value); return cont(functiondef);} + if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext); + if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef) + } + function functiondecl(type, value) { + if (value == "*") {cx.marked = "keyword"; return cont(functiondecl);} + if (type == "variable") {register(value); return cont(functiondecl);} + if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext); + if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl) + } + function typename(type, value) { + if (type == "keyword" || type == "variable") { + cx.marked = "type" + return cont(typename) + } else if (value == "<") { + return cont(pushlex(">"), commasep(typeparam, ">"), poplex) + } + } + function funarg(type, value) { + if (value == "@") cont(expression, funarg) + if (type == "spread") return cont(funarg); + if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); } + if (isTS && type == "this") return cont(maybetype, maybeAssign) + return pass(pattern, maybetype, maybeAssign); + } + function classExpression(type, value) { + // Class expressions may have an optional name. + if (type == "variable") return className(type, value); + return classNameAfter(type, value); + } + function className(type, value) { + if (type == "variable") {register(value); return cont(classNameAfter);} + } + function classNameAfter(type, value) { + if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter) + if (value == "extends" || value == "implements" || (isTS && type == ",")) { + if (value == "implements") cx.marked = "keyword"; + return cont(isTS ? typeexpr : expression, classNameAfter); + } + if (type == "{") return cont(pushlex("}"), classBody, poplex); + } + function classBody(type, value) { + if (type == "async" || + (type == "variable" && + (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) && + cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) { + cx.marked = "keyword"; + return cont(classBody); + } + if (type == "variable" || cx.style == "keyword") { + cx.marked = "property"; + return cont(classfield, classBody); + } + if (type == "number" || type == "string") return cont(classfield, classBody); + if (type == "[") + return cont(expression, maybetype, expect("]"), classfield, classBody) + if (value == "*") { + cx.marked = "keyword"; + return cont(classBody); + } + if (isTS && type == "(") return pass(functiondecl, classBody) + if (type == ";" || type == ",") return cont(classBody); + if (type == "}") return cont(); + if (value == "@") return cont(expression, classBody) + } + function classfield(type, value) { + if (value == "!") return cont(classfield) + if (value == "?") return cont(classfield) + if (type == ":") return cont(typeexpr, maybeAssign) + if (value == "=") return cont(expressionNoComma) + var context = cx.state.lexical.prev, isInterface = context && context.info == "interface" + return pass(isInterface ? functiondecl : functiondef) + } + function afterExport(type, value) { + if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } + if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } + if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); + return pass(statement); + } + function exportField(type, value) { + if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); } + if (type == "variable") return pass(expressionNoComma, exportField); + } + function afterImport(type) { + if (type == "string") return cont(); + if (type == "(") return pass(expression); + if (type == ".") return pass(maybeoperatorComma); + return pass(importSpec, maybeMoreImports, maybeFrom); + } + function importSpec(type, value) { + if (type == "{") return contCommasep(importSpec, "}"); + if (type == "variable") register(value); + if (value == "*") cx.marked = "keyword"; + return cont(maybeAs); + } + function maybeMoreImports(type) { + if (type == ",") return cont(importSpec, maybeMoreImports) + } + function maybeAs(_type, value) { + if (value == "as") { cx.marked = "keyword"; return cont(importSpec); } + } + function maybeFrom(_type, value) { + if (value == "from") { cx.marked = "keyword"; return cont(expression); } + } + function arrayLiteral(type) { + if (type == "]") return cont(); + return pass(commasep(expressionNoComma, "]")); + } + function enumdef() { + return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex) + } + function enummember() { + return pass(pattern, maybeAssign); + } + + function isContinuedStatement(state, textAfter) { + return state.lastType == "operator" || state.lastType == "," || + isOperatorChar.test(textAfter.charAt(0)) || + /[,.]/.test(textAfter.charAt(0)); + } + + function expressionAllowed(stream, state, backUp) { + return state.tokenize == tokenBase && + /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || + (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0)))) + } + + // Interface + + return { + startState: function(basecolumn) { + var state = { + tokenize: tokenBase, + lastType: "sof", + cc: [], + lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), + localVars: parserConfig.localVars, + context: parserConfig.localVars && new Context(null, null, false), + indented: basecolumn || 0 + }; + if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") + state.globalVars = parserConfig.globalVars; + return state; + }, + + token: function(stream, state) { + if (stream.sol()) { + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = false; + state.indented = stream.indentation(); + findFatArrow(stream, state); + } + if (state.tokenize != tokenComment && stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (type == "comment") return style; + state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; + return parseJS(state, style, type, content, stream); + }, + + indent: function(state, textAfter) { + if (state.tokenize == tokenComment || state.tokenize == tokenQuasi) return CodeMirror.Pass; + if (state.tokenize != tokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top + // Kludge to prevent 'maybelse' from blocking lexical scope pops + if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { + var c = state.cc[i]; + if (c == poplex) lexical = lexical.prev; + else if (c != maybeelse && c != popcontext) break; + } + while ((lexical.type == "stat" || lexical.type == "form") && + (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) && + (top == maybeoperatorComma || top == maybeoperatorNoComma) && + !/^[,\.=+\-*:?[\(]/.test(textAfter)))) + lexical = lexical.prev; + if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") + lexical = lexical.prev; + var type = lexical.type, closing = firstChar == type; + + if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0); + else if (type == "form" && firstChar == "{") return lexical.indented; + else if (type == "form") return lexical.indented + indentUnit; + else if (type == "stat") + return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); + else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) + return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); + else if (lexical.align) return lexical.column + (closing ? 0 : 1); + else return lexical.indented + (closing ? 0 : indentUnit); + }, + + electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, + blockCommentStart: jsonMode ? null : "/*", + blockCommentEnd: jsonMode ? null : "*/", + blockCommentContinue: jsonMode ? null : " * ", + lineComment: jsonMode ? null : "//", + fold: "brace", + closeBrackets: "()[]{}''\"\"``", + + helperType: jsonMode ? "json" : "javascript", + jsonldMode: jsonldMode, + jsonMode: jsonMode, + + expressionAllowed: expressionAllowed, + + skipExpression: function(state) { + parseJS(state, "atom", "atom", "true", new CodeMirror.StringStream("", 2, null)) + } + }; +}); + +CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); + +CodeMirror.defineMIME("text/javascript", "javascript"); +CodeMirror.defineMIME("text/ecmascript", "javascript"); +CodeMirror.defineMIME("application/javascript", "javascript"); +CodeMirror.defineMIME("application/x-javascript", "javascript"); +CodeMirror.defineMIME("application/ecmascript", "javascript"); +CodeMirror.defineMIME("application/json", { name: "javascript", json: true }); +CodeMirror.defineMIME("application/x-json", { name: "javascript", json: true }); +CodeMirror.defineMIME("application/manifest+json", { name: "javascript", json: true }) +CodeMirror.defineMIME("application/ld+json", { name: "javascript", jsonld: true }); +CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); +CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); + +}); diff --git a/js/codemirror/5.65.1/material.css b/js/codemirror/5.65.1/material.css new file mode 100644 index 0000000..a784849 --- /dev/null +++ b/js/codemirror/5.65.1/material.css @@ -0,0 +1,141 @@ +/* + Name: material + Author: Mattia Astorino (http://github.com/equinusocio) + Website: https://material-theme.site/ +*/ + +.cm-s-material.CodeMirror { + background-color: #263238; + color: #EEFFFF; +} + +.cm-s-material .CodeMirror-gutters { + background: #263238; + color: #546E7A; + border: none; +} + +.cm-s-material .CodeMirror-guttermarker, +.cm-s-material .CodeMirror-guttermarker-subtle, +.cm-s-material .CodeMirror-linenumber { + color: #546E7A; +} + +.cm-s-material .CodeMirror-cursor { + border-left: 1px solid #FFCC00; +} +.cm-s-material.cm-fat-cursor .CodeMirror-cursor { + background-color: #5d6d5c80 !important; +} +.cm-s-material .cm-animate-fat-cursor { + background-color: #5d6d5c80 !important; +} + +.cm-s-material div.CodeMirror-selected { + background: rgba(128, 203, 196, 0.2); +} + +.cm-s-material.CodeMirror-focused div.CodeMirror-selected { + background: rgba(128, 203, 196, 0.2); +} + +.cm-s-material .CodeMirror-line::selection, +.cm-s-material .CodeMirror-line>span::selection, +.cm-s-material .CodeMirror-line>span>span::selection { + background: rgba(128, 203, 196, 0.2); +} + +.cm-s-material .CodeMirror-line::-moz-selection, +.cm-s-material .CodeMirror-line>span::-moz-selection, +.cm-s-material .CodeMirror-line>span>span::-moz-selection { + background: rgba(128, 203, 196, 0.2); +} + +.cm-s-material .CodeMirror-activeline-background { + background: rgba(0, 0, 0, 0.5); +} + +.cm-s-material .cm-keyword { + color: #C792EA; +} + +.cm-s-material .cm-operator { + color: #89DDFF; +} + +.cm-s-material .cm-variable-2 { + color: #EEFFFF; +} + +.cm-s-material .cm-variable-3, +.cm-s-material .cm-type { + color: #f07178; +} + +.cm-s-material .cm-builtin { + color: #FFCB6B; +} + +.cm-s-material .cm-atom { + color: #F78C6C; +} + +.cm-s-material .cm-number { + color: #FF5370; +} + +.cm-s-material .cm-def { + color: #82AAFF; +} + +.cm-s-material .cm-string { + color: #C3E88D; +} + +.cm-s-material .cm-string-2 { + color: #f07178; +} + +.cm-s-material .cm-comment { + color: #546E7A; +} + +.cm-s-material .cm-variable { + color: #f07178; +} + +.cm-s-material .cm-tag { + color: #FF5370; +} + +.cm-s-material .cm-meta { + color: #FFCB6B; +} + +.cm-s-material .cm-attribute { + color: #C792EA; +} + +.cm-s-material .cm-property { + color: #C792EA; +} + +.cm-s-material .cm-qualifier { + color: #DECB6B; +} + +.cm-s-material .cm-variable-3, +.cm-s-material .cm-type { + color: #DECB6B; +} + + +.cm-s-material .cm-error { + color: rgba(255, 255, 255, 1.0); + background-color: #FF5370; +} + +.cm-s-material .CodeMirror-matchingbracket { + text-decoration: underline; + color: white !important; +} diff --git a/js/codemirror/5.65.1/python.js b/js/codemirror/5.65.1/python.js new file mode 100644 index 0000000..9e532ea --- /dev/null +++ b/js/codemirror/5.65.1/python.js @@ -0,0 +1,402 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + function wordRegexp(words) { + return new RegExp("^((" + words.join(")|(") + "))\\b"); + } + + var wordOperators = wordRegexp(["and", "or", "not", "is"]); + var commonKeywords = ["as", "assert", "break", "class", "continue", + "def", "del", "elif", "else", "except", "finally", + "for", "from", "global", "if", "import", + "lambda", "pass", "raise", "return", + "try", "while", "with", "yield", "in"]; + var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr", + "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod", + "enumerate", "eval", "filter", "float", "format", "frozenset", + "getattr", "globals", "hasattr", "hash", "help", "hex", "id", + "input", "int", "isinstance", "issubclass", "iter", "len", + "list", "locals", "map", "max", "memoryview", "min", "next", + "object", "oct", "open", "ord", "pow", "property", "range", + "repr", "reversed", "round", "set", "setattr", "slice", + "sorted", "staticmethod", "str", "sum", "super", "tuple", + "type", "vars", "zip", "__import__", "NotImplemented", + "Ellipsis", "__debug__"]; + CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins)); + + function top(state) { + return state.scopes[state.scopes.length - 1]; + } + + CodeMirror.defineMode("python", function(conf, parserConf) { + var ERRORCLASS = "error"; + + var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.\\]/; + // (Backwards-compatibility with old, cumbersome config system) + var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters, + parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@]|\.\.\.)/] + for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1) + + var hangingIndent = parserConf.hangingIndent || conf.indentUnit; + + var myKeywords = commonKeywords, myBuiltins = commonBuiltins; + if (parserConf.extra_keywords != undefined) + myKeywords = myKeywords.concat(parserConf.extra_keywords); + + if (parserConf.extra_builtins != undefined) + myBuiltins = myBuiltins.concat(parserConf.extra_builtins); + + var py3 = !(parserConf.version && Number(parserConf.version) < 3) + if (py3) { + // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator + var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/; + myKeywords = myKeywords.concat(["nonlocal", "False", "True", "None", "async", "await"]); + myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]); + var stringPrefixes = new RegExp("^(([rbuf]|(br)|(rb)|(fr)|(rf))?('{3}|\"{3}|['\"]))", "i"); + } else { + var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/; + myKeywords = myKeywords.concat(["exec", "print"]); + myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile", + "file", "intern", "long", "raw_input", "reduce", "reload", + "unichr", "unicode", "xrange", "False", "True", "None"]); + var stringPrefixes = new RegExp("^(([rubf]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i"); + } + var keywords = wordRegexp(myKeywords); + var builtins = wordRegexp(myBuiltins); + + // tokenizers + function tokenBase(stream, state) { + var sol = stream.sol() && state.lastToken != "\\" + if (sol) state.indent = stream.indentation() + // Handle scope changes + if (sol && top(state).type == "py") { + var scopeOffset = top(state).offset; + if (stream.eatSpace()) { + var lineOffset = stream.indentation(); + if (lineOffset > scopeOffset) + pushPyScope(state); + else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#") + state.errorToken = true; + return null; + } else { + var style = tokenBaseInner(stream, state); + if (scopeOffset > 0 && dedent(stream, state)) + style += " " + ERRORCLASS; + return style; + } + } + return tokenBaseInner(stream, state); + } + + function tokenBaseInner(stream, state, inFormat) { + if (stream.eatSpace()) return null; + + // Handle Comments + if (!inFormat && stream.match(/^#.*/)) return "comment"; + + // Handle Number Literals + if (stream.match(/^[0-9\.]/, false)) { + var floatLiteral = false; + // Floats + if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; } + if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; } + if (stream.match(/^\.\d+/)) { floatLiteral = true; } + if (floatLiteral) { + // Float literals may be "imaginary" + stream.eat(/J/i); + return "number"; + } + // Integers + var intLiteral = false; + // Hex + if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true; + // Binary + if (stream.match(/^0b[01_]+/i)) intLiteral = true; + // Octal + if (stream.match(/^0o[0-7_]+/i)) intLiteral = true; + // Decimal + if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) { + // Decimal literals may be "imaginary" + stream.eat(/J/i); + // TODO - Can you have imaginary longs? + intLiteral = true; + } + // Zero by itself with no other piece of number. + if (stream.match(/^0(?![\dx])/i)) intLiteral = true; + if (intLiteral) { + // Integer literals may be "long" + stream.eat(/L/i); + return "number"; + } + } + + // Handle Strings + if (stream.match(stringPrefixes)) { + var isFmtString = stream.current().toLowerCase().indexOf('f') !== -1; + if (!isFmtString) { + state.tokenize = tokenStringFactory(stream.current(), state.tokenize); + return state.tokenize(stream, state); + } else { + state.tokenize = formatStringFactory(stream.current(), state.tokenize); + return state.tokenize(stream, state); + } + } + + for (var i = 0; i < operators.length; i++) + if (stream.match(operators[i])) return "operator" + + if (stream.match(delimiters)) return "punctuation"; + + if (state.lastToken == "." && stream.match(identifiers)) + return "property"; + + if (stream.match(keywords) || stream.match(wordOperators)) + return "keyword"; + + if (stream.match(builtins)) + return "builtin"; + + if (stream.match(/^(self|cls)\b/)) + return "variable-2"; + + if (stream.match(identifiers)) { + if (state.lastToken == "def" || state.lastToken == "class") + return "def"; + return "variable"; + } + + // Handle non-detected items + stream.next(); + return inFormat ? null :ERRORCLASS; + } + + function formatStringFactory(delimiter, tokenOuter) { + while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0) + delimiter = delimiter.substr(1); + + var singleline = delimiter.length == 1; + var OUTCLASS = "string"; + + function tokenNestedExpr(depth) { + return function(stream, state) { + var inner = tokenBaseInner(stream, state, true) + if (inner == "punctuation") { + if (stream.current() == "{") { + state.tokenize = tokenNestedExpr(depth + 1) + } else if (stream.current() == "}") { + if (depth > 1) state.tokenize = tokenNestedExpr(depth - 1) + else state.tokenize = tokenString + } + } + return inner + } + } + + function tokenString(stream, state) { + while (!stream.eol()) { + stream.eatWhile(/[^'"\{\}\\]/); + if (stream.eat("\\")) { + stream.next(); + if (singleline && stream.eol()) + return OUTCLASS; + } else if (stream.match(delimiter)) { + state.tokenize = tokenOuter; + return OUTCLASS; + } else if (stream.match('{{')) { + // ignore {{ in f-str + return OUTCLASS; + } else if (stream.match('{', false)) { + // switch to nested mode + state.tokenize = tokenNestedExpr(0) + if (stream.current()) return OUTCLASS; + else return state.tokenize(stream, state) + } else if (stream.match('}}')) { + return OUTCLASS; + } else if (stream.match('}')) { + // single } in f-string is an error + return ERRORCLASS; + } else { + stream.eat(/['"]/); + } + } + if (singleline) { + if (parserConf.singleLineStringErrors) + return ERRORCLASS; + else + state.tokenize = tokenOuter; + } + return OUTCLASS; + } + tokenString.isString = true; + return tokenString; + } + + function tokenStringFactory(delimiter, tokenOuter) { + while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0) + delimiter = delimiter.substr(1); + + var singleline = delimiter.length == 1; + var OUTCLASS = "string"; + + function tokenString(stream, state) { + while (!stream.eol()) { + stream.eatWhile(/[^'"\\]/); + if (stream.eat("\\")) { + stream.next(); + if (singleline && stream.eol()) + return OUTCLASS; + } else if (stream.match(delimiter)) { + state.tokenize = tokenOuter; + return OUTCLASS; + } else { + stream.eat(/['"]/); + } + } + if (singleline) { + if (parserConf.singleLineStringErrors) + return ERRORCLASS; + else + state.tokenize = tokenOuter; + } + return OUTCLASS; + } + tokenString.isString = true; + return tokenString; + } + + function pushPyScope(state) { + while (top(state).type != "py") state.scopes.pop() + state.scopes.push({offset: top(state).offset + conf.indentUnit, + type: "py", + align: null}) + } + + function pushBracketScope(stream, state, type) { + var align = stream.match(/^[\s\[\{\(]*(?:#|$)/, false) ? null : stream.column() + 1 + state.scopes.push({offset: state.indent + hangingIndent, + type: type, + align: align}) + } + + function dedent(stream, state) { + var indented = stream.indentation(); + while (state.scopes.length > 1 && top(state).offset > indented) { + if (top(state).type != "py") return true; + state.scopes.pop(); + } + return top(state).offset != indented; + } + + function tokenLexer(stream, state) { + if (stream.sol()) { + state.beginningOfLine = true; + state.dedent = false; + } + + var style = state.tokenize(stream, state); + var current = stream.current(); + + // Handle decorators + if (state.beginningOfLine && current == "@") + return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS; + + if (/\S/.test(current)) state.beginningOfLine = false; + + if ((style == "variable" || style == "builtin") + && state.lastToken == "meta") + style = "meta"; + + // Handle scope changes. + if (current == "pass" || current == "return") + state.dedent = true; + + if (current == "lambda") state.lambda = true; + if (current == ":" && !state.lambda && top(state).type == "py" && stream.match(/^\s*(?:#|$)/, false)) + pushPyScope(state); + + if (current.length == 1 && !/string|comment/.test(style)) { + var delimiter_index = "[({".indexOf(current); + if (delimiter_index != -1) + pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1)); + + delimiter_index = "])}".indexOf(current); + if (delimiter_index != -1) { + if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent + else return ERRORCLASS; + } + } + if (state.dedent && stream.eol() && top(state).type == "py" && state.scopes.length > 1) + state.scopes.pop(); + + return style; + } + + var external = { + startState: function(basecolumn) { + return { + tokenize: tokenBase, + scopes: [{offset: basecolumn || 0, type: "py", align: null}], + indent: basecolumn || 0, + lastToken: null, + lambda: false, + dedent: 0 + }; + }, + + token: function(stream, state) { + var addErr = state.errorToken; + if (addErr) state.errorToken = false; + var style = tokenLexer(stream, state); + + if (style && style != "comment") + state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style; + if (style == "punctuation") style = null; + + if (stream.eol() && state.lambda) + state.lambda = false; + return addErr ? style + " " + ERRORCLASS : style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase) + return state.tokenize.isString ? CodeMirror.Pass : 0; + + var scope = top(state) + var closing = scope.type == textAfter.charAt(0) || + scope.type == "py" && !state.dedent && /^(else:|elif |except |finally:)/.test(textAfter) + if (scope.align != null) + return scope.align - (closing ? 1 : 0) + else + return scope.offset - (closing ? hangingIndent : 0) + }, + + electricInput: /^\s*([\}\]\)]|else:|elif |except |finally:)$/, + closeBrackets: {triples: "'\""}, + lineComment: "#", + fold: "indent" + }; + return external; + }); + + CodeMirror.defineMIME("text/x-python", "python"); + + var words = function(str) { return str.split(" "); }; + + CodeMirror.defineMIME("text/x-cython", { + name: "python", + extra_keywords: words("by cdef cimport cpdef ctypedef enum except "+ + "extern gil include nogil property public "+ + "readonly struct union DEF IF ELIF ELSE") + }); + +}); diff --git a/js/codemirror/5.65.1/xml.js b/js/codemirror/5.65.1/xml.js new file mode 100644 index 0000000..4e36106 --- /dev/null +++ b/js/codemirror/5.65.1/xml.js @@ -0,0 +1,417 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: https://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +var htmlConfig = { + autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true, + 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true, + 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, + 'track': true, 'wbr': true, 'menuitem': true}, + implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true, + 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true, + 'th': true, 'tr': true}, + contextGrabbers: { + 'dd': {'dd': true, 'dt': true}, + 'dt': {'dd': true, 'dt': true}, + 'li': {'li': true}, + 'option': {'option': true, 'optgroup': true}, + 'optgroup': {'optgroup': true}, + 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true, + 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true, + 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true, + 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true, + 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true}, + 'rp': {'rp': true, 'rt': true}, + 'rt': {'rp': true, 'rt': true}, + 'tbody': {'tbody': true, 'tfoot': true}, + 'td': {'td': true, 'th': true}, + 'tfoot': {'tbody': true}, + 'th': {'td': true, 'th': true}, + 'thead': {'tbody': true, 'tfoot': true}, + 'tr': {'tr': true} + }, + doNotIndent: {"pre": true}, + allowUnquoted: true, + allowMissing: true, + caseFold: true +} + +var xmlConfig = { + autoSelfClosers: {}, + implicitlyClosed: {}, + contextGrabbers: {}, + doNotIndent: {}, + allowUnquoted: false, + allowMissing: false, + allowMissingTagName: false, + caseFold: false +} + +CodeMirror.defineMode("xml", function(editorConf, config_) { + var indentUnit = editorConf.indentUnit + var config = {} + var defaults = config_.htmlMode ? htmlConfig : xmlConfig + for (var prop in defaults) config[prop] = defaults[prop] + for (var prop in config_) config[prop] = config_[prop] + + // Return variables for tokenizers + var type, setStyle; + + function inText(stream, state) { + function chain(parser) { + state.tokenize = parser; + return parser(stream, state); + } + + var ch = stream.next(); + if (ch == "<") { + if (stream.eat("!")) { + if (stream.eat("[")) { + if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>")); + else return null; + } else if (stream.match("--")) { + return chain(inBlock("comment", "-->")); + } else if (stream.match("DOCTYPE", true, true)) { + stream.eatWhile(/[\w\._\-]/); + return chain(doctype(1)); + } else { + return null; + } + } else if (stream.eat("?")) { + stream.eatWhile(/[\w\._\-]/); + state.tokenize = inBlock("meta", "?>"); + return "meta"; + } else { + type = stream.eat("/") ? "closeTag" : "openTag"; + state.tokenize = inTag; + return "tag bracket"; + } + } else if (ch == "&") { + var ok; + if (stream.eat("#")) { + if (stream.eat("x")) { + ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); + } else { + ok = stream.eatWhile(/[\d]/) && stream.eat(";"); + } + } else { + ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); + } + return ok ? "atom" : "error"; + } else { + stream.eatWhile(/[^&<]/); + return null; + } + } + inText.isInText = true; + + function inTag(stream, state) { + var ch = stream.next(); + if (ch == ">" || (ch == "/" && stream.eat(">"))) { + state.tokenize = inText; + type = ch == ">" ? "endTag" : "selfcloseTag"; + return "tag bracket"; + } else if (ch == "=") { + type = "equals"; + return null; + } else if (ch == "<") { + state.tokenize = inText; + state.state = baseState; + state.tagName = state.tagStart = null; + var next = state.tokenize(stream, state); + return next ? next + " tag error" : "tag error"; + } else if (/[\'\"]/.test(ch)) { + state.tokenize = inAttribute(ch); + state.stringStartCol = stream.column(); + return state.tokenize(stream, state); + } else { + stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/); + return "word"; + } + } + + function inAttribute(quote) { + var closure = function(stream, state) { + while (!stream.eol()) { + if (stream.next() == quote) { + state.tokenize = inTag; + break; + } + } + return "string"; + }; + closure.isInAttribute = true; + return closure; + } + + function inBlock(style, terminator) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.match(terminator)) { + state.tokenize = inText; + break; + } + stream.next(); + } + return style; + } + } + + function doctype(depth) { + return function(stream, state) { + var ch; + while ((ch = stream.next()) != null) { + if (ch == "<") { + state.tokenize = doctype(depth + 1); + return state.tokenize(stream, state); + } else if (ch == ">") { + if (depth == 1) { + state.tokenize = inText; + break; + } else { + state.tokenize = doctype(depth - 1); + return state.tokenize(stream, state); + } + } + } + return "meta"; + }; + } + + function lower(tagName) { + return tagName && tagName.toLowerCase(); + } + + function Context(state, tagName, startOfLine) { + this.prev = state.context; + this.tagName = tagName || ""; + this.indent = state.indented; + this.startOfLine = startOfLine; + if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent)) + this.noIndent = true; + } + function popContext(state) { + if (state.context) state.context = state.context.prev; + } + function maybePopContext(state, nextTagName) { + var parentTagName; + while (true) { + if (!state.context) { + return; + } + parentTagName = state.context.tagName; + if (!config.contextGrabbers.hasOwnProperty(lower(parentTagName)) || + !config.contextGrabbers[lower(parentTagName)].hasOwnProperty(lower(nextTagName))) { + return; + } + popContext(state); + } + } + + function baseState(type, stream, state) { + if (type == "openTag") { + state.tagStart = stream.column(); + return tagNameState; + } else if (type == "closeTag") { + return closeTagNameState; + } else { + return baseState; + } + } + function tagNameState(type, stream, state) { + if (type == "word") { + state.tagName = stream.current(); + setStyle = "tag"; + return attrState; + } else if (config.allowMissingTagName && type == "endTag") { + setStyle = "tag bracket"; + return attrState(type, stream, state); + } else { + setStyle = "error"; + return tagNameState; + } + } + function closeTagNameState(type, stream, state) { + if (type == "word") { + var tagName = stream.current(); + if (state.context && state.context.tagName != tagName && + config.implicitlyClosed.hasOwnProperty(lower(state.context.tagName))) + popContext(state); + if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) { + setStyle = "tag"; + return closeState; + } else { + setStyle = "tag error"; + return closeStateErr; + } + } else if (config.allowMissingTagName && type == "endTag") { + setStyle = "tag bracket"; + return closeState(type, stream, state); + } else { + setStyle = "error"; + return closeStateErr; + } + } + + function closeState(type, _stream, state) { + if (type != "endTag") { + setStyle = "error"; + return closeState; + } + popContext(state); + return baseState; + } + function closeStateErr(type, stream, state) { + setStyle = "error"; + return closeState(type, stream, state); + } + + function attrState(type, _stream, state) { + if (type == "word") { + setStyle = "attribute"; + return attrEqState; + } else if (type == "endTag" || type == "selfcloseTag") { + var tagName = state.tagName, tagStart = state.tagStart; + state.tagName = state.tagStart = null; + if (type == "selfcloseTag" || + config.autoSelfClosers.hasOwnProperty(lower(tagName))) { + maybePopContext(state, tagName); + } else { + maybePopContext(state, tagName); + state.context = new Context(state, tagName, tagStart == state.indented); + } + return baseState; + } + setStyle = "error"; + return attrState; + } + function attrEqState(type, stream, state) { + if (type == "equals") return attrValueState; + if (!config.allowMissing) setStyle = "error"; + return attrState(type, stream, state); + } + function attrValueState(type, stream, state) { + if (type == "string") return attrContinuedState; + if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;} + setStyle = "error"; + return attrState(type, stream, state); + } + function attrContinuedState(type, stream, state) { + if (type == "string") return attrContinuedState; + return attrState(type, stream, state); + } + + return { + startState: function(baseIndent) { + var state = {tokenize: inText, + state: baseState, + indented: baseIndent || 0, + tagName: null, tagStart: null, + context: null} + if (baseIndent != null) state.baseIndent = baseIndent + return state + }, + + token: function(stream, state) { + if (!state.tagName && stream.sol()) + state.indented = stream.indentation(); + + if (stream.eatSpace()) return null; + type = null; + var style = state.tokenize(stream, state); + if ((style || type) && style != "comment") { + setStyle = null; + state.state = state.state(type || style, stream, state); + if (setStyle) + style = setStyle == "error" ? style + " error" : setStyle; + } + return style; + }, + + indent: function(state, textAfter, fullLine) { + var context = state.context; + // Indent multi-line strings (e.g. css). + if (state.tokenize.isInAttribute) { + if (state.tagStart == state.indented) + return state.stringStartCol + 1; + else + return state.indented + indentUnit; + } + if (context && context.noIndent) return CodeMirror.Pass; + if (state.tokenize != inTag && state.tokenize != inText) + return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; + // Indent the starts of attribute names. + if (state.tagName) { + if (config.multilineTagIndentPastTag !== false) + return state.tagStart + state.tagName.length + 2; + else + return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1); + } + if (config.alignCDATA && /$/, + blockCommentStart: "", + + configuration: config.htmlMode ? "html" : "xml", + helperType: config.htmlMode ? "html" : "xml", + + skipAttribute: function(state) { + if (state.state == attrValueState) + state.state = attrState + }, + + xmlCurrentTag: function(state) { + return state.tagName ? {name: state.tagName, close: state.type == "closeTag"} : null + }, + + xmlCurrentContext: function(state) { + var context = [] + for (var cx = state.context; cx; cx = cx.prev) + context.push(cx.tagName) + return context.reverse() + } + }; +}); + +CodeMirror.defineMIME("text/xml", "xml"); +CodeMirror.defineMIME("application/xml", "xml"); +if (!CodeMirror.mimeModes.hasOwnProperty("text/html")) + CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true}); + +}); diff --git a/js/codemirror/custom.txt b/js/codemirror/custom.txt new file mode 100644 index 0000000..28e9534 --- /dev/null +++ b/js/codemirror/custom.txt @@ -0,0 +1 @@ +cursor.style.top = (pos.top+5) + "px"; //#CUSTOM \ No newline at end of file diff --git a/js/codemirror/fake/codemirror.js b/js/codemirror/fake/codemirror.js new file mode 100644 index 0000000..5cd4618 --- /dev/null +++ b/js/codemirror/fake/codemirror.js @@ -0,0 +1,13 @@ +CodeMirror=function(a,b){ + this.value=b.value; + this.on=function(){} + this.setValue=function(x){ + this.value=x; + }; + this.getValue=function(){ + return this.value; + } + this.focus=function(){}; + this.clearHistory=function(){}; + return this; +} \ No newline at end of file diff --git a/js/codemirror/pixel.css b/js/codemirror/pixel.css new file mode 100644 index 0000000..e48ec53 --- /dev/null +++ b/js/codemirror/pixel.css @@ -0,0 +1,48 @@ +.cm-s-pixel { + background-color: #000000; + color: rgba(233, 237, 237, 1); +} +.cm-s-pixel .CodeMirror-gutters { +background: black; + color: rgb(83,127,126); + border: none; +} +.lspacer{ + background: black; + padding-left: 7px; +} +.cm-s-pixel .CodeMirror-guttermarker, .cm-s-pixel .CodeMirror-guttermarker-subtle, .cm-s-pixel .CodeMirror-linenumber { color: #E0E0D9; background: #303030; } +.cm-s-pixel .CodeMirror-cursor { border-left: 2px solid #f8f8f0; } +.cm-s-pixel div.CodeMirror-selected { background: rgba(255, 255, 255, 0.30); } +.cm-s-pixel.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.25); } +.cm-s-pixel .CodeMirror-line::selection, .cm-s-pixel .CodeMirror-line > span::selection, .cm-s-pixel .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.25); } +.cm-s-pixel .CodeMirror-line::-moz-selection, .cm-s-pixel .CodeMirror-line > span::-moz-selection, .cm-s-pixel .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.25); } + +.cm-s-pixel .CodeMirror-activeline-background { background: rgba(0, 0, 0, 0); } +.cm-s-pixel .cm-keyword { color: #C792EA; } .cm-s-pixel .cm-keyword {color: #6c6b6d;} +.cm-s-pixel .cm-operator { color: #EDEDED; } +.cm-s-pixel .cm-variable-2 { color: #80CBC4; } +.cm-s-pixel .cm-variable-3 { color: #82B1FF; } +.cm-s-pixel .cm-builtin { color: #DECB6B; } +.cm-s-pixel .cm-atom { color: #F77669; } +.cm-s-pixel .cm-number { color: #F77669; } +.cm-s-pixel .cm-def { color: #EDEDED; } +.cm-s-pixel .cm-string { color: #C3E88D; } +.cm-s-pixel .cm-string-2 { color: #80CBC4; } +.cm-s-pixel .cm-comment { color: #546E7A; } +.cm-s-pixel .cm-variable { color: #82B1FF; } .cm-s-pixel .cm-variable { color: #7d7caf; } +.cm-s-pixel .cm-tag { color: #80CBC4; } +.cm-s-pixel .cm-meta { color: #80CBC4; } +.cm-s-pixel .cm-attribute { color: #FFCB6B; } +.cm-s-pixel .cm-property { color: #80CBAE; } .cm-s-pixel .cm-property { color: #F77669; } +.cm-s-pixel .cm-qualifier { color: #DECB6B; } +.cm-s-pixel .cm-variable-3 { color: #DECB6B; } +.cm-s-pixel .cm-tag { color: #FF5370; } +.cm-s-pixel .cm-error { + color: rgba(255, 255, 255, 1.0); + background-color: #EC5F67; +} +.cm-s-pixel .CodeMirror-matchingbracket { + text-decoration: underline; + color: white !important; +} \ No newline at end of file diff --git a/js/codes/.DS_Store b/js/codes/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/js/codes/.DS_Store differ diff --git a/js/codes/bin.js b/js/codes/bin.js new file mode 100644 index 0000000..909ca75 --- /dev/null +++ b/js/codes/bin.js @@ -0,0 +1,80 @@ +function drag_logic() +{ + return; + function dragMoveListener (event) { + var target = event.target, + // keep the dragged position in the data-x/data-y attributes + x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx, + y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy; + + // translate the element + target.style.webkitTransform = + target.style.transform = + 'translate(' + x + 'px, ' + y + 'px)'; + + // update the posiion attributes + target.setAttribute('data-x', x); + target.setAttribute('data-y', y); + } + + interact('.draggable').draggable({ + // inertia: true, + restrict: { + restriction: ".dcontain", + endOnly: true, + elementRect: { top: 0, left: 0, bottom: 1, right: 1 } + }, + //autoScroll: true, + onmove: dragMoveListener, + onend: function (event) { + var textEl = event.target.querySelector('p'); + + textEl && (textEl.textContent = + 'moved a distance of ' + + (Math.sqrt(event.dx * event.dx + + event.dy * event.dy)|0) + 'px'); + } + }).actionChecker(function (pointer, event, action) { + if (event.button !== 0) { // without this the right click isn't ideal [26/06/16] + return null; + } + return action; + }); + window.dragMoveListener = dragMoveListener; + + + interact('.itemslot').dropzone({ + // only accept elements matching this CSS selector + accept: '.draggable', + // Require a 75% element overlap for a drop to be possible + overlap: 0.75, + + ondropactivate: function (event) { + // add active dropzone feedback + event.target.classList.add('drop-active'); + }, + ondragenter: function (event) { + var draggableElement = event.relatedTarget, + dropzoneElement = event.target; + + // feedback the possibility of a drop + dropzoneElement.classList.add('drop-target'); + draggableElement.classList.add('can-drop'); + draggableElement.textContent = 'Dragged in'; + }, + ondragleave: function (event) { + // remove the drop feedback style + event.target.classList.remove('drop-target'); + event.relatedTarget.classList.remove('can-drop'); + event.relatedTarget.textContent = 'Dragged out'; + }, + ondrop: function (event) { + event.relatedTarget.textContent = 'Dropped'; + }, + ondropdeactivate: function (event) { + // remove active dropzone feedback + event.target.classList.remove('drop-active'); + event.target.classList.remove('drop-target'); + } + }); +} \ No newline at end of file diff --git a/js/codes/bot_server.js b/js/codes/bot_server.js new file mode 100644 index 0000000..b049c95 --- /dev/null +++ b/js/codes/bot_server.js @@ -0,0 +1,43 @@ +var server_password="adventureland"; +var account_email="hello@adventure.land"; +var account_password="gg123456"; +var server_port=9012; + +var url=require('url'); +var app=require('http').createServer(http_handler); +app.listen(server_port); + +function http_handler(request,response) +{ + var body = []; + request.on('error', function(err) { + console.log("http_err: "+err,1); + }).on('data', function(chunk) { + body.push(chunk); + }).on('end', function() { + body = Buffer.concat(body).toString(); + try{ + var url_parts=url.parse(request.url,true),args=url_parts.query,cookies={},output=""; + + (body||"").split("&").forEach(function(pv){ + var pvp=pv.split("="); + args[pvp[0]]=pvp[1]; + }); + + if(cookies.password!=server_password) + { + response.writeHead(200); + response.end(html_password()); + } + response.writeHead(200); + response.end(output); + }catch(e){ + console.log("chttp_err: "+e,1); + } + }); +} + +function html_password() +{ + return "What is the password?"; +} \ No newline at end of file diff --git a/js/codes/contributions/draivins_calculate_move.js b/js/codes/contributions/draivins_calculate_move.js new file mode 100644 index 0000000..6109e59 --- /dev/null +++ b/js/codes/contributions/draivins_calculate_move.js @@ -0,0 +1,75 @@ +function calculate_move(map, cur_x, cur_y, target_x, target_y) { + var going_down = cur_y < target_y; + var going_right = cur_x < target_x; + + var x_lines = map.x_lines || []; + var y_lines = map.y_lines || []; + + var min_x = min(cur_x, target_x); + var max_x = max(cur_x, target_x); + var min_y = min(cur_y, target_y); + var max_y = max(cur_y, target_y); + + var dx = target_x - cur_x; + var dy = target_y - cur_y; + + var dydx = dy / (dx + EPS); + var dxdy = 1 / dydx; + + for (var i = 0; i < x_lines.length; i++) { + var line = x_lines[i]; + var line_x = line[0]; + if (max_x < line_x || min_x > line_x || max_y < line[1] || min_y > line[2]) { + continue; + } + + var y_intersect = cur_y + (line_x - cur_x) * dydx; + + if (y_intersect < line[1] || y_intersect > line[2]) { + continue; + } + + if (going_down) { + target_y = min(target_y, y_intersect); + } else { + target_y = max(target_y, y_intersect); + } + + if (going_right) { + target_x = min(target_x, line_x - 3); + } else { + target_x = max(target_x, line_x + 3); + } + } + + for (var i = 0; i < y_lines.length; i++) { + var line = y_lines[i]; + var line_y = line[0]; + if (max_y < line_y || min_y > line_y || max_x < line[1] || min_x > line[2]) { + continue; + } + + var x_intersect = cur_x + (line_y - cur_y) * dxdy; + + if (x_intersect < line[1] || x_intersect > line[2]) { + continue; + } + + if (going_right) { + target_x = min(target_x, x_intersect); + } else { + target_x = max(target_x, x_intersect); + } + + if (going_down) { + target_y = min(target_y, line_y - 3); + } else { + target_y = max(target_y, line_y + 7); + } + } + + return { + x: target_x, + y: target_y + }; +} \ No newline at end of file diff --git a/js/codes/contributions/draivins_calculate_move2.js b/js/codes/contributions/draivins_calculate_move2.js new file mode 100644 index 0000000..bd5191c --- /dev/null +++ b/js/codes/contributions/draivins_calculate_move2.js @@ -0,0 +1,83 @@ +function calculate_move(map, cur_x, cur_y, target_x, target_y) { + var going_down = cur_y < target_y; + var going_right = cur_x < target_x; + + var x_lines = map.x_lines || []; + var y_lines = map.y_lines || []; + + var min_x = min(cur_x, target_x); + var max_x = max(cur_x, target_x); + var min_y = min(cur_y, target_y); + var max_y = max(cur_y, target_y); + + var dx = target_x - cur_x; + var dy = target_y - cur_y; + + var dydx = dy / (dx + EPS); + var dxdy = 1 / dydx; + + for (var i = 0; i < x_lines.length; i++) { + var line = x_lines[i]; + var line_x = line[0]; + if (max_x < line_x || min_x > line_x || max_y < line[1] || min_y > line[2]) { + continue; + } + + var y_intersect = cur_y + (line_x - cur_x) * dydx; + + if (y_intersect < line[1] || y_intersect > line[2]) { + continue; + } + + if (going_down) { + target_y = min(target_y, y_intersect); + max_y = target_y; + } else { + target_y = max(target_y, y_intersect); + min_y = target_y; + } + + if (going_right) { + target_x = min(target_x, line_x - 3); + max_x = target_x; + } else { + target_x = max(target_x, line_x + 3); + min_x = target_x; + } + } + + for (var i = 0; i < y_lines.length; i++) { + var line = y_lines[i]; + var line_y = line[0]; + if (max_y < line_y || min_y > line_y || max_x < line[1] || min_x > line[2]) { + continue; + } + + var x_intersect = cur_x + (line_y - cur_y) * dxdy; + + if (x_intersect < line[1] || x_intersect > line[2]) { + continue; + } + + if (going_right) { + target_x = min(target_x, x_intersect); + max_x = target_x; + } else { + target_x = max(target_x, x_intersect); + min_x = target_x; + } + + if (going_down) { + target_y = min(target_y, line_y - 3); + max_y = target_y; + } else { + target_y = max(target_y, line_y + 7); + min_y = target_y; + } + } + + return { + x: target_x, + y: target_y + }; +} \ No newline at end of file diff --git a/js/codes/contributions/draivins_can_move.js b/js/codes/contributions/draivins_can_move.js new file mode 100644 index 0000000..e90aac9 --- /dev/null +++ b/js/codes/contributions/draivins_can_move.js @@ -0,0 +1,49 @@ +function can_move(map, cur_x, cur_y, target_x, target_y) { + var x_lines = map.x_lines || []; + var y_lines = map.y_lines || []; + + var min_x = min(cur_x, target_x); + var max_x = max(cur_x, target_x); + var min_y = min(cur_y, target_y); + var max_y = max(cur_y, target_y); + + var dx = target_x - cur_x; + var dy = target_y - cur_y; + + var dydx = dy / (dx + EPS); + var dxdy = 1 / dydx; + + for (var i = 0; i < x_lines.length; i++) { + var line = x_lines[i]; + var line_x = line[0]; + if (max_x < line_x || min_x > line_x || max_y < line[1] || min_y > line[2]) { + continue; + } + + var y_intersect = cur_y + (line_x - cur_x) * dydx; + + if (y_intersect < line[1] || y_intersect > line[2]) { + continue; + } + + return false; + } + + for (var i = 0; i < y_lines.length; i++) { + var line = y_lines[i]; + var line_y = line[0]; + if (max_y < line_y || min_y > line_y || max_x < line[1] || min_x > line[2]) { + continue; + } + + var x_intersect = cur_x + (line_y - cur_y) * dxdy; + + if (x_intersect < line[1] || x_intersect > line[2]) { + continue; + } + + return false; + } + + return true; +} \ No newline at end of file diff --git a/js/codes/contributions/draivins_inside_checker.js b/js/codes/contributions/draivins_inside_checker.js new file mode 100644 index 0000000..1b5772e --- /dev/null +++ b/js/codes/contributions/draivins_inside_checker.js @@ -0,0 +1,241 @@ +const GRAPH_RESOLUTION = 8; + +class Box { + constructor(x1, y1, x2, y2) { + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; + } + + width() { + return this.x2 - this.x1; + } + + height() { + return this.y2 - this.y1; + } + + contains(x, y) { + return (this.x1 < x && x < this.x2 && + this.y1 < y && y < this.y2); + } + + intersects(box) { + return (this.x1 <= box.x2 && + box.x1 <= this.x2 && + this.y1 <= box.y2 && + box.y1 <= this.y2); + } + + static square(cx, cy, side) { + let half_side = side / 2; + return new Box(cx - half_side, cy - half_side, cx + half_side, cy + half_side); + } +} + + +class NodeTree { + constructor(region, obstacles, root, level) { + if (!level) { + this.level = Math.ceil(Math.log2(region.width() / GRAPH_RESOLUTION)); + } else { + this.level = level; + } + + if (root) { + this.root = root; + } else { + this.root = this; + } + + this.region = region; + + this.x = (region.x1 + region.x2) / 2; + this.y = (region.y1 + region.y2) / 2; + + this.obstacles = obstacles; + + this.crossable = true; + this.is_leaf = false; + + if (this.obstacles.length == 0) { + this.is_leaf = true; + } else if (this.level == 0) { + this.is_leaf = true; + this.crossable = false; + } + + this.quads = null; + this.neighbors = null; + + this.is_inside = false; + + if (!this.is_leaf) { + this.subdivide(); + } + } + + get_quad(x, y) { + if (x < this.x && y < this.y) return this.quads[0]; + else if (x >= this.x && y < this.y) return this.quads[1]; + else if (x < this.x && y >= this.y) return this.quads[2]; + return this.quads[3]; + } + + subdivide() { + this.quads = []; + + let l = this.region.x1; + let r = this.region.x2; + let t = this.region.y1; + let b = this.region.y2; + + let x = this.x; + let y = this.y; + + let subregions = [ + new Box(l, t, x, y), + new Box(x, t, r, y), + new Box(l, y, x, b), + new Box(x, y, r, b), + ]; + + let obstacles = this.obstacles; + for (let i = 0; i < subregions.length; i++) { + let subregion = subregions[i]; + let subregion_obstacles = []; + + for (let j = 0; j < obstacles.length; j++) { + let obstacle = obstacles[j]; + if (subregion.intersects(obstacle)) { + subregion_obstacles.push(obstacle); + } + } + + this.quads[i] = new NodeTree(subregion, subregion_obstacles, this.root, this.level - 1); + } + } + + get(x, y) { + if (!this.region.contains(x, y)) return null; + if (this.is_leaf) return this; + return this.get_quad(x, y).get(x, y); + } + + get_neighbors() { + if (!this.is_leaf) throw new Error('Tried getting neighbors of non-leaf node'); + if (this.neighbors) return this.neighbors; + + if (!this.crossable) { + this.neighbors = []; + return this.neighbors; + } + + let left = this.region.x1; + let right = this.region.x2; + let top = this.region.y1; + let bottom = this.region.y2; + + let min_size = this.region.width() * (2 ** -this.level); + let num_neighbors = 2 ** this.level; + + let neighbor_set = new Set(); + + // Top and bottom (and corners). + for (let x = -(num_neighbors + 1); x <= (num_neighbors + 1); x += 2) { + let real_x = this.x + min_size * (x / 2); + + let neighbor = this.root.get(real_x, top - min_size / 2); + if (neighbor) neighbor_set.add(neighbor); + + neighbor = this.root.get(real_x, bottom + min_size / 2); + if (neighbor) neighbor_set.add(neighbor); + } + + // Left and right. + for (let y = -(num_neighbors - 1); y <= (num_neighbors - 1); y += 2) { + let real_y = this.y + min_size * (y / 2); + + let neighbor = this.root.get(left - min_size / 2, real_y); + if (neighbor) neighbor_set.add(neighbor); + + neighbor = this.root.get(right + min_size / 2, real_y); + if (neighbor) neighbor_set.add(neighbor); + } + + this.neighbors = [...neighbor_set]; + + return this.neighbors; + } + + flood_fill() { + if (this.is_inside) return; + this.is_inside = true; + + for (let neighbor of this.get_neighbors()) { + neighbor.flood_fill(); + } + } + +} + +function calculate_size(actual_size) { + let cur_size = GRAPH_RESOLUTION; + + while (cur_size < actual_size) { + cur_size *= 2; + } + + return cur_size; +} + +function initialize_graph(map_name) { + let map_data = G.maps[map_name].data; + + let min_x = Infinity; + let max_x = -Infinity; + let min_y = Infinity; + let max_y = -Infinity; + + + let obstacles = []; + + for (let line of map_data.x_lines) { + min_x = Math.min(min_x, line[0]); + max_x = Math.max(max_x, line[0]); + obstacles.push(new Box( + line[0] - 3, + line[1] - 3, + line[0] + 3, + line[2] + 7 + )); + } + + for (let line of map_data.y_lines) { + min_y = Math.min(min_y, line[0]); + max_y = Math.max(max_y, line[0]); + obstacles.push(new Box( + line[1] - 3, + line[0] - 3, + line[2] + 3, + line[0] + 7 + )); + } + + let largest_side = Math.max(max_x - min_x, max_y - min_y); + let side = calculate_size(largest_side); + + let center_x = (max_x + min_x) / 2; + let center_y = (max_y + min_y) / 2; + let region = Box.square(center_x, center_y, side); + + let map_tree = new NodeTree(region, obstacles); + + let spawns = G.maps[map_name].spawns; + for (let [x, y] of spawns) { + map_tree.get(x, y).flood_fill(); + } + + return map_tree; +} diff --git a/js/codes/focus_code.js b/js/codes/focus_code.js new file mode 100644 index 0000000..03a68a4 --- /dev/null +++ b/js/codes/focus_code.js @@ -0,0 +1,18 @@ +function on_draw() +{ + clear_drawings(); + for(var id in parent.entities) + { + var player=parent.entities[id]; + if(!parent.is_player(player)) continue; + if(player.target) + { + var target=parent.entities[player.target]; + if(target) + { + // game_log(target.name); + draw_line(player.real_x,player.real_y,target.real_x,target.real_y); + } + } + } +} \ No newline at end of file diff --git a/js/codes/old_moves.js b/js/codes/old_moves.js new file mode 100644 index 0000000..6fb16cb --- /dev/null +++ b/js/codes/old_moves.js @@ -0,0 +1,400 @@ +// This is draivin's calculate_move - it's well thought, as he introduced going_down and going_right, realising that approach direction matters, this is what probably inpired me to introduce the new simplified system 1.5 years later, where lines are duplicated, so approach direction doesn't need to be introduced in the calculation logic, which complicates things too much [17/07/18] +// [17/07/18 17:25] Sad realization - line duplication can never work, even if lines are increased in length to intersect - there are orphan lines on fences etc. +// [18/07/18 14:22] Latest iteration of movement logic, calculate 4 corners, select the minimal move, simple, easy to calculate + + +function calculate_move(map,cur_x,cur_y,target_x,target_y) // v4, tries to move back, but, if you are moving at a very very high angle, moving 7px back from an x_line, doesn't really move you 7px back in the y-direction, it's more like 0.1px, trial and error ... :) +{ + var o=move_distance(cur_x,cur_y,target_x,target_y); + var f=move_further(cur_x,cur_y,target_x,target_y,7.1288); + var move=calculate_movex(map, cur_x, cur_y, f.x, f.y); // move 4px forward instead, so line logic triggers + var n=move_distance(cur_x,cur_y,move.x,move.y); + console.log((n-o)+" target_x,y: "+target_x+","+target_y+" move.x,y: "+move.x+","+move.y); + if(n-o>=7.1288-EPS) return calculate_move_v2(map, cur_x, cur_y, target_x, target_y); // didn't clash with a line, return normal move + else + { + console.log((o-n+7.1288)+" further"); + var fx=move_further(cur_x,cur_y,target_x,target_y,-(o-n+7.1288)); + var move=calculate_movex(map, cur_x, cur_y, fx.x, fx.y); + } + return move; +} + +function move_further(x0,y0,x1,y1,dt) // Some of the earlier ideas involved trying to move forward and backtracking, imperfect and complex [19/07/18] +{ + var distance=Math.sqrt((x1-x0)*(x1-x0)+(y1-y0)*(y1-y0)); + if(!dt || !distance) return {x:x1,y:y1}; + var a=(y1-y0)/distance,b=(x1-x0)/distance; + return {x:x0+b*(distance+dt),y:y0+a*(distance+dt)}; +} + +function move_exact(x0,y0,x1,y1,dt) +{ + var distance=Math.sqrt((x1-x0)*(x1-x0)+(y1-y0)*(y1-y0)); + if(!dt || !distance) return {x:x1,y:y1}; + var a=(y1-y0)/distance,b=(x1-x0)/distance; + return {x:x0+b*(dt),y:y0+a*(dt)}; +} + +function calculate_movex(map, cur_x, cur_y, target_x, target_y) { + if(target_x==Infinity) target_x=CINF; + if(target_y==Infinity) target_y=CINF; + //console.log(cur_x+" "+cur_y+" "+target_x+" "+target_y); + var going_down = cur_y < target_y; + var going_right = cur_x < target_x; + + var x_lines = map.x_lines || []; + var y_lines = map.y_lines || []; + + var min_x = min(cur_x, target_x); + var max_x = max(cur_x, target_x); + var min_y = min(cur_y, target_y); + var max_y = max(cur_y, target_y); + + var dx = target_x - cur_x; + var dy = target_y - cur_y; + + var dydx = dy / (dx + EPS); + //console.log(dydx); + var dxdy = 1 / dydx; + + var N_SPC=0; // Tested 2, doesn't work, jail with test_movement.js [16/07/18] + + for (var i = 0; i < x_lines.length; i++) { + var line = x_lines[i]; + var line_x = line[0]; + if (max_x < line_x-N_SPC || min_x > line_x+N_SPC || max_y < line[1]-N_SPC || min_y > line[2]+N_SPC) { + continue; + } + + var y_intersect = cur_y + (line_x - cur_x) * dydx; + + if (y_intersect < line[1]-N_SPC || y_intersect > line[2]+N_SPC) { + continue; + } + + if (going_down) { + target_y = min(target_y, y_intersect); + max_y = target_y; + } else { + target_y = max(target_y, y_intersect); + min_y = target_y; + } + + if (going_right) { + target_x = min(target_x, line_x - 3); + max_x = target_x; + } else { + target_x = max(target_x, line_x + 3); + min_x = target_x; + } + } + + for (var i = 0; i < y_lines.length; i++) { + var line = y_lines[i]; + var line_y = line[0]; + if (max_y < line_y-N_SPC || min_y > line_y+N_SPC || max_x < line[1]-N_SPC || min_x > line[2]+N_SPC) { + continue; + } + + var x_intersect = cur_x + (line_y - cur_y) * dxdy; + + if (x_intersect < line[1]-N_SPC || x_intersect > line[2]+N_SPC) { + continue; + } + + if (going_right) { + target_x = min(target_x, x_intersect); + max_x = target_x; + } else { + target_x = max(target_x, x_intersect); + min_x = target_x; + } + + if (going_down) { + target_y = min(target_y, line_y - 3); + max_y = target_y; + } else { + target_y = max(target_y, line_y + 7); + min_y = target_y; + } + } + + //console.log(target_x+" "+target_y); + return { + x: target_x, + y: target_y + }; +} + +// This was a bugged version of applying the "Smooth Movement" - if you hit a line, this routine lets you walk as if you slide over the line you hit +function calculate_movev1(map, cur_x, cur_y, target_x, target_y) // improved, v1 +{ + var move=calculate_movex(map, cur_x, cur_y, target_x, target_y); + if(move.x!=target_x && move.y!=target_y) + { + var move2=calculate_movex(map, move.x,move.y, target_x, move.y); + if(move2.x==move.x) + { + var move2=calculate_movex(map, move2.x,move2.y, move2.x, target_y); + } + return move2; + } + return move; +} + +// Pre-perfection versions, introduced binary search in [16/07/18] - and quickly re-wrote the entire system and simplified things +function bsearch_start(arr,value) +{ + var start=0,end=arr.length-1,current; + while(start=x1 && line[1]-0.2<=y1 && line[2]+0.2>=y1) return false; // 2 instead of 0.2 causes jailing issues + if(mx>line[0]) continue; // can be commented out with: while(start=y1 && line[1]-0.2<=x1 && line[2]+0.2>=x1) return false; + if(my>line[0]) continue; + if(y0+1=x1 && line[1]-0.2<=y1 && line[2]+0.2>=y1) return false; // 2 instead of 0.2 causes jailing issues + if(mx>line[0]) continue; // can be commented out with: while(start=y1 && line[1]-0.2<=x1 && line[2]+0.2>=x1) return false; + if(my>line[0]) continue; + if(y0+1=x1 && line[1]-7<=y1 && line[2]+3>=y1) return false; + if(mx>line[0]) continue; + if(x0+1=y1 && line[1]-7<=x1 && line[2]+3>=x1) return false; + if(my>line[0]) continue; + if(y0+1 line_x || max_y < line[1] || min_y > line[2]) { + continue; + } + + var y_intersect = cur_y + (line_x - cur_x) * dydx; + + if (y_intersect < line[1] || y_intersect > line[2]) { + continue; + } + + return false; + } + + for (var i = 0; i < y_lines.length; i++) { + var line = y_lines[i]; + var line_y = line[0]; + if (max_y < line_y || min_y > line_y || max_x < line[1] || min_x > line[2]) { + continue; + } + + var x_intersect = cur_x + (line_y - cur_y) * dxdy; + + if (x_intersect < line[1] || x_intersect > line[2]) { + continue; + } + + return false; + } + + return true; +} \ No newline at end of file diff --git a/js/comm.js b/js/comm.js new file mode 100644 index 0000000..b754469 --- /dev/null +++ b/js/comm.js @@ -0,0 +1,81 @@ +var last_focus=new Date(); +setInterval(function(){ + if($(":focus").length) last_focus=new Date(); +},120); + +function touch_startify() +{ + return; + $('[onclick]').each(function(){ + var $this=$(this); + $this.attr("ontouchstart",$this.attr("onclick")); + $this.removeAttr("onclick"); + }) +} + +function toggle_ui() +{ + if(socket && observing && $('.serversuic').is(":visible")) + { + $('.charactersui').hide(); + $('.serversui').hide(); + } + else if($('.charactersuic').is(":visible")) + { + $('.charactersui').hide(); $('.serversui').css('display','inline-block'); + } + else + { + $('.serversui').hide(); $('.charactersui').css('display','inline-block'); + } +} + +function hide_nav() +{ + $('.charactersui').hide(); $('.serversui').hide(); +} + +var rc_cache="-1"; +function render_characters() +{ + var html="",key=""; + X.characters.forEach(function(char){ + key+=char.name+" "+char.level+" "+char.server+" "+char.rip+" "+char.skin+" "+char.cx+"|"; + }); + if(key==rc_cache) return; + rc_cache=key; + X.characters.forEach(function(char){ + if(char.online) + { + html+="
"; + html+=""+sprite(char.skin,{cx:char.cx,rip:char.rip})+""; + html+=char.name.length<=8&&char.name||char.name.substr(0,8)+".."; + html+=" ["+char.server+"]"; + html+="
"; + html+="Lv."+char.level+" "+char.type.toTitleCase()+""; + html+="
"; + } + }); + if(!html) html+="
ALL OFFLINE
"; + $(".charactersuic").html(html); + touch_startify(); +} + +var sl_cache="-1"; +function render_servers() +{ + var html="",key=""; + X.servers.forEach(function(server){ + key+=server.name+" "+server.players+"|"; + }); + if(key==sl_cache) return; + sl_cache=key; + X.servers.forEach(function(server){ + html+="
"; + html+=server.region+" "+server.name+" ["+server.players+"]"; + html+="
"; + }); + if(!html) html+="
GAME OFFLINE
"; + $(".serversuic").html(html); + touch_startify(); +} \ No newline at end of file diff --git a/js/common_functions.js b/js/common_functions.js new file mode 100644 index 0000000..0582804 --- /dev/null +++ b/js/common_functions.js @@ -0,0 +1,2274 @@ +var c_version=2; +var EPS=0.00000001; // 144-Number.EPSILON was 144 at the time :| [17/07/18] +var ZEPS=0.00000001; //z-index EPS +var REPS=((Number&&Number.EPSILON)||EPS); +var CINF=999999999999999; +var really_old=new Date(); really_old.setYear(1970); +var colors={ + "range":"#93A6A2", + "armor":"#5C5D5E", + "resistance":"#6A5598", + "attack":"#DB2900", + "str":"#F07F2F", + "int":"#3E6EED", + "dex":"#44B75C", + "for":"#5F3085", + "speed":"#36B89E", + "cash":"#5DAC40", + "hp":"#FF2E46", + //"mp":"#365DC5", + "mp":"#3A62CE", + "stat_xp":"#4570B1", + "party_xp":"#AD73E0", + "xp":"#CBFFFF", + "luck":"#2A9A3D", + "gold":"gold", + "male":"#43A1C6", + "female":"#C06C9B", + "server_success":"#85C76B", + "server_failure":"#C7302C", + "poison":"#41834A", + "ability":"#ff9100", // nice-green #66ad0f - neon-orange #ff9100 + "xmas":"#C82F17", + "xmasgreen":"#33BF6D", + "code_blue":"#32A3B0", + "code_pink":"#E13758", + "code_error":"#E13758", + "A":"#39BB54", + "B":"#DB37A3", + "npc_white":"#EBECEE", + "white_positive":"#C3FFC0", + "white_negative":"#FFDBDC", + "positive_greeb":"#85C76B", + "serious_red":"#BC0004", + "serious_green":"#428727", + "heal":"#EE4D93", + "lifesteal":"#9A1D27", + "manasteal":"#353C9C", + "inspect":"#7F75CA", + "property":"#EF7A4D", + "string":"#D3637E", +} +var trade_slots=[],check_slots=["elixir"]; +for(var i=1;i<=48;i++) trade_slots.push("trade"+i),check_slots.push("trade"+i); +var bank_packs={ + "items0":["bank",0,0], + "items1":["bank",0,0], + "items2":["bank",75000000,600], + "items3":["bank",75000000,600], + "items4":["bank",100000000,800], + "items5":["bank",100000000,800], + "items6":["bank",112500000,900], + "items7":["bank",112500000,900], + "items8":["bank_b",0,0], + "items9":["bank_b",475000000,1000], + "items10":["bank_b",675000000,1150], + "items11":["bank_b",825000000,1150], + "items12":["bank_b",975000000,1200], + "items13":["bank_b",975000000,1200], + "items14":["bank_b",975000000,1200], + "items15":["bank_b",975000000,1200], + "items16":["bank_b",975000000,1200], + "items17":["bank_b",1075000000,1200], + "items18":["bank_b",1175000000,1200], + "items19":["bank_b",1275000000,1200], + "items20":["bank_b",1375000000,1200], + "items21":["bank_b",1475000000,1200], + "items22":["bank_b",1575000000,1200], + "items23":["bank_b",1675000000,1200], + "items24":["bank_u",0,0], + "items25":["bank_u",2075000000,1350], + "items26":["bank_u",2075000000,1350], + "items27":["bank_u",2075000000,1350], + "items28":["bank_u",2075000000,1350], + "items29":["bank_u",3075000000,1350], + "items30":["bank_u",3075000000,1350], + "items31":["bank_u",3075000000,1350], + "items32":["bank_u",3075000000,1350], + "items33":["bank_u",3075000000,1350], + "items34":["bank_u",3075000000,1350], + "items35":["bank_u",4075000000,1450], + "items36":["bank_u",5075000000,1450], + "items37":["bank_u",6075000000,1450], + "items38":["bank_u",7075000000,1450], + "items39":["bank_u",8075000000,1450], + "items40":["bank_u",9075000000,1650], + "items41":["bank_u",9075000000,1650], + "items42":["bank_u",9975000000,1650], + "items43":["bank_u",9975000000,1650], + "items44":["bank_u",9975000000,1650], + "items45":["bank_u",9975000000,1850], + "items46":["bank_u",9975000000,1850], + "items47":["bank_u",9995000000,1850], +}; +var character_slots=["ring1","ring2","earring1","earring2","belt","mainhand","offhand","helmet","chest","pants","shoes","gloves","amulet","orb","elixir","cape"]; +var attire_slots=["helmet","chest","pants","shoes","gloves","cape"]; +var riches_slots=["ring1","ring2","earring1","earring2","amulet"]; +var booster_items=["xpbooster","luckbooster","goldbooster"]; +var doublehand_types=["axe","basher","great_staff"]; +var offhand_types={ + "quiver":"Quiver", + "shield":"Shield", + "misc_offhand":"Misc Offhand", + "source":"Source" +}; +var weapon_types={ + "sword":"Sword", + "short_sword":"Short Sword", + "great_sword":"Great Sword", + "axe":"Axe", + "wblade":"Magical Sword", + "basher":"Basher", + "dartgun":"Dart Gun", + "bow":"Bow", + "crossbow":"Crossbow", + "rapier":"Rapier", + "spear":"Spear", + "fist":"Fist Weapon", + "dagger":"Dagger", + "stars":"Throwing Stars", + "mace":"Mace", + "pmace":"Priest Mace", + "staff":"Staff", + "wand":"Wand", +}; +var cxtype_to_slot={ + "armor":"skin", + "body":"skin", + "character":"skin", + "face":"face", + "makeup":"makeup", + "a_makeup":"makeup", + "beard":"chin", + "mask":"chin", + "tail":"tail", + "s_wings":"back", + "wings":"back", + "hat":"hat", + "a_hat":"hat", + "head":"head", + "hair":"hair", + "gravestone":"gravestone", +}; +var free_cx=["makeup105","makeup117","mmakeup00","fmakeup01","fmakeup02","fmakeup03"]; +var can_buy={}; +var T={}; // sprite-type + +function process_game_data() +{ + G.quests={}; + for(var name in G.monsters) + { + if(G.monsters[name].charge) continue; + if(G.monsters[name].speed>=60) G.monsters[name].charge=round(G.monsters[name].speed*1.20); + else if(G.monsters[name].speed>=50) G.monsters[name].charge=round(G.monsters[name].speed*1.30); + else if(G.monsters[name].speed>=32) G.monsters[name].charge=round(G.monsters[name].speed*1.4); + else if(G.monsters[name].speed>=20) G.monsters[name].charge=round(G.monsters[name].speed*1.6); + else if(G.monsters[name].speed>=10) G.monsters[name].charge=round(G.monsters[name].speed*1.7); + else G.monsters[name].charge=round(G.monsters[name].speed*2); + G.monsters[name].max_hp=G.monsters[name].hp; // So default value adoption logic is easier [16/04/18] + } + for(var c in G.classes) + { + if(!G.classes[c].xcx) G.classes[c].xcx=[]; + free_cx.forEach(function(cx){ if(!G.classes[c].xcx.includes(cx)) G.classes[c].xcx.push(cx); }); + G.classes[c].looks.forEach(function(l){ + if(!G.classes[c].xcx.includes(l[0])) G.classes[c].xcx.push(l[0]); + for(var slot in l[1]) + { + if(!G.classes[c].xcx.includes(l[1][slot])) G.classes[c].xcx.push(l[1][slot]); + } + }) + } + for(var s in G.sprites) + { + var current=G.sprites[s],matrix=current.matrix; + if(current.skip) continue; + for(var i=0;i b[0]) ? 1 : ((b[0] > a[0]) ? -1 : 0);}); + // map.data.y_lines.forEach(function(line){ + // G.geometry[name].y_lines.push([line[0]-LD,line[1]-LD,line[2]+LD]); + // G.geometry[name].y_lines.push([line[0]+LD,line[1]-LD,line[2]+LD]); // The extra 4px is roughly the size of character shoes + // }); + // G.geometry[name].y_lines.sort(function(a,b){return (a[0] > b[0]) ? 1 : ((b[0] > a[0]) ? -1 : 0);}); + map.items={}; + map.merchants=[]; + map.ref=map.ref||{}; + (map.npcs||[]).forEach(function(npc){ + if(!npc.position) return; + var coords={map:name,"in":name,x:npc.position[0],y:npc.position[1],id:npc.id},data=G.npcs[npc.id]; + if(data.items) + { + map.merchants.push(coords); + data.items.forEach(function(name){ + if(!name) return; + if(G.items[name].cash) + { + G.items[name].buy_with_cash=true; + if(!G.items[name].p2w) return; + } + map.items[name]=map.items[name]||[]; + map.items[name].push(coords); + can_buy[name]=true; + G.items[name].buy=true; + }); + } + map.ref[npc.id]=coords; + if(data.role=="newupgrade") map.upgrade=map.compound=coords; // Refactored the NPC's, but decided to leave these [26/06/18] + if(data.role=="exchange") map.exchange=coords; + if(data.quest) G.quests[data.quest]=coords; + + }); + } + for(var id in G.items) + G.items[id].id=id; +} + +function test_logic() +{ + for(var id in G.items) + { + G.items[id].cash=0; + G.items[id].g=G.items[id].g||1; // actual values now + } + for(var id in G.monsters) + { + G.monsters[id].xp=0; + } +} + +function map_cx(player) +{ + var cx={}; + for(var c in (player.p&&player.p.acx||player.acx||{})) + { + if(G.cosmetics.bundle[c]) + G.cosmetics.bundle[c].forEach(function(cc){ cx[cc]=c; }) + else if(G.cosmetics.map[c]) + cx[G.cosmetics.map[c]]=c; + else + cx[c]=c; + } + return cx; +} + +function all_cx(player,send) +{ + var cx={}; + for(var c in (player.p&&player.p.acx||player.acx||{})) + { + if(G.cosmetics.bundle[c]) + G.cosmetics.bundle[c].forEach(function(cc){ cx[cc]=(cx[cc]||0)+1; }) + else if(G.cosmetics.map[c]) + cx[G.cosmetics.map[c]]=(cx[G.cosmetics.map[c]]||0)+1; + else + cx[c]=(cx[c]||0)+1; + } + if(send) + { + for(var s in (player.cx||{})) + { + var c=player.cx[s]; + if(G.cosmetics.bundle[c]) + G.cosmetics.bundle[c].forEach(function(cc){ cx[cc]=(cx[cc]||0)-1; }) + else if(G.cosmetics.map[c]) + cx[G.cosmetics.map[c]]=(cx[G.cosmetics.map[c]]||0)-1; + else + cx[c]=(cx[c]||0)-1; + } + [player.skin].forEach(function(c){ + if(G.cosmetics.bundle[c]) + G.cosmetics.bundle[c].forEach(function(cc){ cx[cc]=(cx[cc]||0)-1; }) + else if(G.cosmetics.map[c]) + cx[G.cosmetics.map[c]]=(cx[G.cosmetics.map[c]]||0)-1; + else + cx[c]=(cx[c]||0)-1; + }); + } + (player.p&&player.p.xcx||player.xcx||[]).forEach(function(c){ + if(G.cosmetics.bundle[c]) + G.cosmetics.bundle[c].forEach(function(cc){ cx[cc]=(cx[cc]||0)+0.01; }) + else if(G.cosmetics.map[c]) + cx[G.cosmetics.map[c]]=(cx[G.cosmetics.map[c]]||0)+0.01; + else + cx[c]=(cx[c]||0)+0.01; + }); + (G.classes[player.ctype||player.type].xcx||[]).forEach(function(c){ + if(G.cosmetics.bundle[c]) + G.cosmetics.bundle[c].forEach(function(cc){ cx[cc]=(cx[cc]||0)+0.01; }) + else if(G.cosmetics.map[c]) + cx[G.cosmetics.map[c]]=(cx[G.cosmetics.map[c]]||0)+0.01; + else + cx[c]=(cx[c]||0)+0.01; + }); + return cx; +} + +function prune_cx(cx,skin) +{ + if(skin && cx.upper && cx.upper=="skin") delete cx.upper; + for(var sname in cx) + { + if(!cx[sname] || sname=="upper" && T[cx[sname]]!="body" && T[cx[sname]]!="armor" || sname!="upper" && cxtype_to_slot[T[cx[sname]]]!=sname) + { + delete cx[sname]; + continue; + } + } +} + +function hx(color) +{ + return eval("0x"+color.replace("#","")); +} + +function hardcore_logic() +{ + for(var id in G.items) + { + // if(G.items[id].tier==2) G.items[id].a=0; + } + G.npcs.premium.items[3]="computer"; + G.npcs.premium.items[4]="tracker"; + G.npcs.premium.items.forEach(function(item){ + if(item) + { + G.items[item].cash=0; + G.items[item].g=parseInt(G.items[item].g*2); + } + }); + for(var id in G.monsters) + { + if(G.monsters[id].respawn!=-1) + G.monsters[id].respawn=1; + } + for(var id in G.tokens) + { + for(var m in G.tokens[id]) + { + G.tokens[id][m]=1; + } + } + G.tokens.monstertoken.fieldgen0=20; + G.items.offering.g=parseInt(G.items.offering.g/2); + G.items.xptome.g=99999999; + G.items.computer.g=1; + G.items.tracker.g=1; + G.items.gemfragment.e=10; + G.items.leather.e=5; + G.maps.main.monsters.push({"type":"wabbit","boundary":[-282,702,218,872],"count":1}); + G.npcs.scrolls.items[9]="vitscroll"; + G.monsters.wabbit.evasion=96.0; + G.monsters.wabbit.reflection=96.0; + G.monsters.phoenix.respawn=1; + G.monsters.mvampire.respawn=1; + delete G.items.test_orb.upgrade; + G.items.test_orb.compound={}; + // G.items.gem0.a=0; + // G.items.gem1.a=0; + // G.items.armorbox.a=0; + // G.items.weaponbox.a=0; +} + +function can_stack(a,b,d,args) +{ + if(a && b && a.name && G.items[a.name].s && a.name==b.name && a.q+b.q+(d||0)<=(G.items[a.name].s===true&&9999||G.items[a.name].s)) + { + if((a.p || b.p) && a.p!=b.p) return false; // property + if(a.name=="cxjar" && a.data!=b.data) return false; + if(a.name=="emotionjar" && a.data!=b.data) return false; + if(!args || !args.ignore_pvp) if(a.v && !b.v || !a.v && b.v) return false; // pvp + if(a.l || b.l || a.b || b.b) return false; // blocked and locked + return true; + } + return false; +} + +function can_add_item(player,new_item,args) // long requested feature [18/10/18] +{ + if(!args) args={}; + if(!new_item.name) new_item=create_new_item(new_item,args.q||1); + if(is_array(player)) // for "bank"/"swap" + { + player={items:player}; + for(var i=0;i<42;i++) if(!player.items[i]) return true; + } + if(player.esize>0) return true; + if(G.items[new_item.name].s) + { + for(var i=0;i=needed || !needed) return true; + items.forEach(function(new_item){ + if(G.items[new_item.name].s) + { + for(var i=0;i=needed) return true; + return false; +} + +var RESOLVE_ALL=false; +var deferreds={},current_deferred=null; +function deferred() +{ + var self=this; + this.promise=new Promise(function(resolve,reject){ + self.reject = reject; + self.resolve = resolve; + }); +} + +function push_deferred(name) +{ + var current=new deferred(); + if(["attack","heal"].includes(name)) + current.start=new Date(); + if(!deferreds[name]) deferreds[name]=[]; + deferreds[name].push(current); + if(deferreds[name].length>3200) deferreds[name].shift(); // outbreak + return current.promise; +} + +function push_deferreds(name,count) +{ + var deferreds=[]; + for(var i=0;i= (b_x - b_w2) + && (a_y) >= (b_y - b_h) + && (a_y - a_h) <= (b_y) ) return 0 + + // TODO: If one is just a single point, we're computing 8 needless calculations. + // Compare the 4 corners to each other + let min = 99999999 + for(const a_c of [{ x: a_x + a_w2, y: a_y - a_h}, + { x: a_x + a_w2, y: a_y}, + { x: a_x - a_w2, y: a_y - a_h}, + { x: a_x - a_w2, y: a_y}]) { + for(const b_c of [{ x: b_x + b_w2, y: b_y - b_h}, + { x: b_x + b_w2, y: b_y}, + { x: b_x - b_w2, y: b_y - b_h}, + { x: b_x - b_w2, y: b_y}]) { + const d = Math.hypot(a_c.x - b_c.x, a_c.y - b_c.y) + if(d < min) min = d + } + } + return min +} + +function random_away(x,y,R) // https://stackoverflow.com/a/5838055/914546 +{ + var t=2*Math.PI*Math.random(); + var u=Math.random()*2; + var r=u>1&&(2-u)||u; + return [x+R*r*Math.cos(t),y+R*r*Math.sin(t)]; +} + +function can_transport(entity) +{ + return can_walk(entity); +} + +function can_walk(entity) +{ + if(entity.s && entity.s.dash) return false; + if(is_game && entity.me && transporting && ssince(transporting)<8 && !entity.c.town) return false; + if(is_code && entity.me && parent.transporting && ssince(parent.transporting)<8 && !entity.c.town) return false; + return !is_disabled(entity); +} + +function is_silenced(entity) +{ + if(!entity || is_disabled(entity) || (entity.s && entity.s.silenced)) return true; +} + +function is_disabled(entity) +{ + if(!entity || entity.rip || (entity.s && (entity.s.stunned || entity.s.fingered || entity.s.stoned || entity.s.deepfreezed || entity.s.sleeping))) return true; +} + +function calculate_item_grade(def,item) +{ + if(!(def.upgrade || def.compound)) return 0; + if((item&&item.level||0)>=(def.grades||[9,10,11,12])[3]) return 4; + if((item&&item.level||0)>=(def.grades||[9,10,11,12])[2]) return 3; + if((item&&item.level||0)>=(def.grades||[9,10,11,12])[1]) return 2; + if((item&&item.level||0)>=(def.grades||[9,10,11,12])[0]) return 1; + return 0; +} + +function calculate_item_value(item,m) +{ + if(!item) return 0; + if(item.gift) return 1; + var def=G.items[item.name]||G.items.placeholder_m,value=def.cash&&def.g||def.g*(m||0.6),divide=1; // previously 0.8 + if(def.markup) value/=def.markup; + if(def.compound && item.level) + { + var grade=0,grades=def.grades||[11,12],s_value=0; + for(var i=1;i<=item.level;i++) + { + if(i>grades[1]) grade=2; + else if(i>grades[0]) grade=1; + if(def.cash) value*=1.5; + else value*=3.2; + if(def.type!="booster") value+=G.items["cscroll"+grade].g/2.4; + else value*=0.75; + } + } + if(def.upgrade && item.level) + { + var grade=0,grades=def.grades||[11,12],s_value=0; + for(var i=1;i<=item.level;i++) + { + if(i>grades[1]) grade=2; + else if(i>grades[0]) grade=1; + s_value+=G.items["scroll"+grade].g/2; + if(i>=7) value*=3,s_value*=1.32; + else if(i==6) value*=2.4; + else if(i>=4) value*=2; + if(i==9) value*=2.64,value+=400000; + if(i==10) value*=5; + //if(i==11) value*=2; + if(i==12) value*=0.8; + } + value+=s_value; + } + if(item.expires) divide=8; + return round(value/divide)||0; +} + +var prop_cache={}; // reset at reload_server + +function damage_multiplier(defense) // [10/12/17] +{ + return min(1.32,max(0.05,1-(max(0,min(100,defense))*0.00100+ + max(0,min(100,defense-100))*0.00100+ + max(0,min(100,defense-200))*0.00095+ + max(0,min(100,defense-300))*0.00090+ + max(0,min(100,defense-400))*0.00082+ + max(0,min(100,defense-500))*0.00070+ + max(0,min(100,defense-600))*0.00060+ + max(0,min(100,defense-700))*0.00050+ + max(0,defense-800)*0.00040)+ + max(0,min(50,0-defense))*0.00100+ // Negative's / Armor Piercing + max(0,min(50,-50-defense))*0.00075+ + max(0,min(50,-100-defense))*0.00050+ + max(0,-150-defense)*0.00025 + )); +} + +function dps_multiplier(defense) // [10/12/17] +{ + return 1-(max(0,min(100,defense))*0.00100+ + max(0,min(100,defense-100))*0.00100+ + max(0,min(100,defense-200))*0.00095+ + max(0,min(100,defense-300))*0.00090+ + max(0,min(100,defense-400))*0.00082+ + max(0,min(100,defense-500))*0.00070+ + max(0,min(100,defense-600))*0.00060+ + max(0,min(100,defense-700))*0.00050+ + max(0,defense-800)*0.00040)+ + max(0,min(50,0-defense))*0.00100+ // Negative's / Armor Piercing + max(0,min(50,-50-defense))*0.00075+ + max(0,min(50,-100-defense))*0.00050+ + max(0,-150-defense)*0.00025 +} + +function adopt_extras(def,ex) +{ + for(var p in ex) + { + if(p=='upgrade' || p=='compound') + { + for(var pp in ex) + { + def[p][pp]=(def[p][pp]||0)+ex[p][pp]; + } + } + else + def[p]=(def[p]||0)+ex[p]; + } +} + +function calculate_item_properties(item,args) +{ + if(!args) args={}; + var def=args.def||G.items[item.name],cls="",map=""; + if(args['class'] && def[args['class']]) cls=args['class']; + if(args['map'] && def[args['map']]) map=args['map']; + var prop_key=def.name+item.name+(def.card||"")+"|"+item.level+"|"+item.stat_type+"|"+item.p+"|"+cls+"|"+map; + if(prop_cache[prop_key]) return prop_cache[prop_key]; + if(cls || map) def=clone(def); + if(cls) adopt_extras(def,def[cls]); + if(map) adopt_extras(def,def[map]); + //#NEWIDEA: An item cache here [15/11/16] + var prop={ + "gold":0, + "luck":0, + "xp":0, + "int":0, + "str":0, + "dex":0, + "vit":0, + "for":0, + "charisma":0, + "cuteness":0, + "awesomeness":0, + "bling":0, + "hp":0, + "mp":0, + "attack":0, + "range":0, + "armor":0, + "incdmgamp":0, + "resistance":0, + "pnresistance":0, + "firesistance":0, + "fzresistance":0, + "phresistance":0, + "stresistance":0, + "stun":0, + "blast":0, + "explosion":0, + "breaks":0, + "stat":0, + "speed":0, + "level":0, + "evasion":0, + "miss":0, + "reflection":0, + "lifesteal":0, + "manasteal":0, + "attr0":0, + "attr1":0, + "rpiercing":0, + "apiercing":0, + "crit":0, + "critdamage":0, + "dreturn":0, + "frequency":0, + "mp_cost":0, + "mp_reduction":0, + "output":0, + "courage":0, + "mcourage":0, + "pcourage":0, + "set":null, + "class":null, + }; + var mult={ + "gold":0.5, + "luck":1, + "xp":0.5, + "int":1, + "str":1, + "dex":1, + "vit":1, + "for":1, + "armor":2.25, + "resistance":2.25, + "speed":0.325, + "evasion":0.325, + "reflection":0.150, + "lifesteal":0.15, + "manasteal":0.040, + "rpiercing":2.25, + "apiercing":2.25, + "crit":0.125, + "dreturn":0.5, + "frequency":0.325, + "mp_cost":-0.6, + "output":0.175, + }; + if(item.p=="shiny") + { + if(def.attack) + { + prop.attack+=4; + if(doublehand_types.includes(G.items[item.name].wtype)) prop.attack+=3; + } + else if(def.stat) + { + prop.stat+=2; + } + else if(def.armor) + { + prop.armor+=12; + prop.resistance=(prop.resistance||0)+10; + } + else + { + prop.dex+=1; + prop['int']+=1; + prop.str+=1; + } + } + else if(item.p=="glitched") + { + var roll=Math.random(); + if(roll<0.33) + { + prop.dex+=1; + } + else if(roll<0.66) + { + prop['int']+=1; + } + else + { + prop.str+=1; + } + } + else if(item.p && G.titles[item.p]) + { + for(var p in G.titles[item.p]) + if(p in prop) + prop[p]+=G.titles[item.p][p]; + } + if(def.upgrade||def.compound) + { + var u_def=def.upgrade||def.compound; + level=item.level||0; + prop.level=level; + for(var i=1;i<=level;i++) + { + var multiplier=1; + if(def.upgrade) + { + if(i==7) multiplier=1.25; + if(i==8) multiplier=1.5; + if(i==9) multiplier=2; + if(i==10) multiplier=3; + if(i==11) multiplier=1.25; + if(i==12) multiplier=1.25; + } + else if(def.compound) + { + if(i==5) multiplier=1.25; + if(i==6) multiplier=1.5; + if(i==7) multiplier=2; + if(i>=8) multiplier=3; + } + for(p in u_def) + { + if(p=="stat") prop[p]+=round(u_def[p]*multiplier); + else prop[p]+=u_def[p]*multiplier; // for weapons with float improvements [04/08/16] + if(p=="stat" && i>=7) prop.stat++; + } + } + + } + if(item.level==10 && prop.stat && def.tier && def.tier>=3) prop.stat+=2; + for(p in def) + if(prop[p]===null) prop[p]=def[p]; + else if(prop[p]!=undefined) prop[p]+=def[p]; + if(item.p=="legacy" && def.legacy) + { + for(var name in def.legacy) + { + if(def.legacy[name]===null) delete prop[name]; + else prop[name]=(prop[name]||0)+def.legacy[name]; + } + } + for(p in prop) + if(!in_arr(p,["evasion","miss","reflection","dreturn","lifesteal","manasteal","attr0","attr1","crit","critdamage","set","class","breaks"])) prop[p]=round(prop[p]); + if(def.stat && item.stat_type) + { + prop[item.stat_type]+=prop.stat*mult[item.stat_type]; + prop.stat=0; + } + // for(p in prop) prop[p]=floor(prop[p]); - round probably came after this one, commenting out [13/09/16] + prop_cache[prop_key]=prop; + return prop; +} + +function random_one(arr) +{ + if(!is_array(arr)) return random_one(Object.values(arr)); + if(!arr.length) return null; + return arr[parseInt(arr.length*Math.random())]; +} + +function floor_f2(num) +{ + return parseInt(num*100)/100.0; +} + +function to_pretty_float(num) +{ + return (0 + Math.trunc((num||0) * 100) / 100).toLocaleString("en-US"); + if(!num) return "0"; + var hnum=floor_f2(num).toFixed(2),num=parseFloat(hnum); + if(parseFloat(hnum)==parseFloat(num.toFixed(1))) hnum=num.toFixed(1); + if(parseFloat(hnum)==parseFloat(parseInt(num))) hnum=parseInt(num); + return hnum; +} + +function to_pretty_num(num) +{ + return (Math.floor(num||0) + 0).toLocaleString("en-US"); + if(!num) return "0"; + num=round(num); + var pretty=""; + while(num) + { + var current=num%1000; + if(!current) current="000"; + else if(current<10 && current!=num) current="00"+current; + else if(current<100 && current!=num) current="0"+current; + if(!pretty) pretty=current; + else pretty=current+","+pretty; + num=(num-num%1000)/1000; + } + return ""+pretty; +} + +function smart_num(num,edge) +{ + if(!edge) edge=10000; + if(num>=edge) return to_pretty_num(num); + return num; +} + +function to_shrinked_num(num) +{ + if(!num) return "0"; + num=round(num); + if(num<1000) return ""+num; + var arr=[[1000,"K"],[1000000,"M"],[1000000000,"B"],[1000000000000,"T"]]; + for(var i=0;i=1000*current[0]) continue; + var whole=floor(num/current[0]); + var remainder=floor((num%current[0])/(current[0]/10)); + var pretty=whole+"."+remainder; + pretty=pretty.substr(0,3); + if(pretty.endsWith(".00")) pretty=pretty.replace(".00",""); + if(pretty.endsWith(".0")) pretty=pretty.replace(".0",""); + if(pretty.endsWith(".")) pretty=pretty.replace(".",""); + return pretty+current[1]; + } + return "LOTS"; +} + +var valid_file_chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz_-.+ "; +function to_filename(name) +{ + var c="",v=valid_file_chars.split(""); + (""+name).split("").forEach(function(ch){ + if(v.includes(ch)) c+=ch; + }) + return c; +} + +function e_array(num) +{ + var array=[]; + for(var i=0;i line_x || max_y < line[1] || min_y > line[2]) { + continue; + } + + var y_intersect = cur_y + (line_x - cur_x) * dydx; + + if(eps_equal(cur_x,target_x) && eps_equal(cur_x,line_x)) // allows you to move parallelly right into the lines + { + line_xE=line_x; + if (going_down) y_intersect=min(line[1],line[2])-XEPS, target_y=min(target_y, y_intersect), max_y = target_y; + else y_intersect=max(line[1],line[2])+XEPS, target_y=min(target_y, y_intersect), min_y = target_y; + continue; + } + + + if (y_intersect < line[1] || y_intersect > line[2]) { + continue; + } + + + if (going_down) { + target_y = min(target_y, y_intersect); + max_y = target_y; + } else { + target_y = max(target_y, y_intersect); + min_y = target_y; + } + + if (going_right) { + target_x = min(target_x, line_xE); // Can never be directly on the lines themselves + max_x = target_x; + } else { + target_x = max(target_x, line_xE); + min_x = target_x; + } + } + + for (var i = bsearch_start(y_lines,min_y); i < y_lines.length; i++) { + var line = y_lines[i]; + var line_y = line[0],line_yE=line_y+XEPS; + if(going_down) line_yE=line_y-XEPS; + + if(max_y < line_y) break; + if (max_y < line_y || min_y > line_y || max_x < line[1] || min_x > line[2]) { + continue; + } + + var x_intersect = cur_x + (line_y - cur_y) * dxdy; + + if(eps_equal(cur_y,target_y) && eps_equal(cur_y,line_y)) + { + line_yE=line_y; + if (going_right) x_intersect=min(line[1],line[2])-XEPS, target_x=min(target_x, x_intersect), max_x = target_x; + else x_intersect=max(line[1],line[2])+XEPS, target_x=min(target_x, x_intersect), min_x = target_x; + continue; + } + + if (x_intersect < line[1] || x_intersect > line[2]) { + continue; + } + + + if (going_right) { + target_x = min(target_x, x_intersect); + max_x = target_x; + } else { + target_x = max(target_x, x_intersect); + min_x = target_x; + } + + if (going_down) { + target_y = min(target_y, line_yE); + max_y = target_y; + } else { + target_y = max(target_y, line_yE); + min_y = target_y; + } + } + + // console.log(target_x+" "+target_y); + return { + x: target_x, + y: target_y + }; +} + +function set_base(entity) +{ + var type=entity.mtype||entity.type; + entity.base={h:8,v:7,vn:2}; + if(G.dimensions[type] && G.dimensions[type][3]) + { + entity.base.h=G.dimensions[type][3]; + entity.base.v=min(9.9,G.dimensions[type][4]); // v+vn has to be <12 + } + else + { + entity.base.h=min(12,(get_width(entity)||0)*0.80); + entity.base.v=min(9.9,(get_height(entity)||0)/4.0); + if(!entity.base.h) entity.base.h=8,entity.base.v=7; + } +} + +function calculate_move_v2(map, cur_x, cur_y, target_x, target_y) // improved, v2 - all movements should originate from cur_x and cur_y +{ + if(target_x==Infinity) target_x=CINF; + if(target_y==Infinity) target_y=CINF; + var move=calculate_movex(map, cur_x, cur_y, target_x, target_y); + if(move.x!=target_x && move.y!=target_y) // this is a smooth move logic - if a line hit occurs, keeps moving in the movable direction + { + var move2=calculate_movex(map, cur_x,cur_y, target_x, move.y); + if(move2.x==move.x) + { + var move2=calculate_movex(map, cur_x,cur_y, move2.x, target_y); + } + return move2; + } + // return move_further(cur_x,cur_y,move.x,move.y,100); + return move; +} + +var m_calculate=false,m_line_x=false,m_line_y=false,line_hit_x=null,line_hit_y=null,m_dx,m_dy; // flags so can_calculate and can_move work in synergy + +function calculate_move(entity,target_x,target_y) // v5, calculate 4 edges, choose the minimal move [18/07/18] +{ + // -8,+8 left/right 0,-7 down/up + m_calculate=true; + var map=entity.map,cur_x=get_x(entity),cur_y=get_y(entity); + var corners=[[0,0]]; + var moves=[[target_x,target_y]],x_moves=[]; + if(entity.base) corners=[[-entity.base.h,entity.base.vn],[entity.base.h,entity.base.vn],[-entity.base.h,-entity.base.v],[entity.base.h,-entity.base.v]]; + // Test the movement limits of all 4 corners of an entity, and record the [mmx,mmy] at the limit + corners.forEach(function(mxy){ + for(var i=0;i<3;i++) + { + var mx=mxy[0],my=mxy[1]; + var dx=target_x+mx,dy=target_y+my; + if(i==1) dx=cur_x+mx; + if(i==2) dy=cur_y+my; + var cmove=calculate_movex(G.geometry[map]||{},cur_x+mx,cur_y+my,dx,dy); + var cdist=point_distance(cur_x+mx,cur_y+my,cmove.x,cmove.y); + // add_log(cdist,"orange"); + + mx=cmove.x-mx; + my=cmove.y-my; + // add_log("mx/y: "+mx+","+my); + + if(!in_arrD2([mx,my],moves)) moves.push([mx,my]); + // New logic, just check all possibilities, original logic just checked the min cdist + // Sometimes the minimum move is just a stuck corner in another move angle, so all possibilities need to be checked + // if(Math.abs(mx-round(mx))<40*EPS && !in_arrD2([mx,cur_y],moves)) moves.push([mx,cur_y]); + // x- if(Math.abs(mx-round(mx))<40*EPS && !in_arrD2([mx,target_y],moves) || 1) moves.push([mx,target_y]); + // if(Math.abs(my-round(my))<40*EPS && !in_arrD2([cur_x,my],moves)) moves.push([cur_x,my]); + // x- if(Math.abs(my-round(my))<40*EPS && !in_arrD2([target_x,my],moves) || 1) moves.push([target_x,my]); + } + }); + // console.log(moves); + var max=-1,move={x:cur_x,y:cur_y},min=CINF; + // Test all boundary coordinates, if none of them work, don't move + function check_move(xy) + { // This is the smooth move logic, even if you hit a line, you might still move along that line + var x=xy[0],y=xy[1]; + if(can_move({map:map,x:cur_x,y:cur_y,going_x:x,going_y:y,base:entity.base})) + { + // var cdist=point_distance(cur_x,cur_y,x,y); + // if(cdist>max) + // { + // max=cdist; + // move={x:x,y:y}; + // } + var cdist=point_distance(target_x,target_y,x,y); + // #IDEA: If the angle difference between intended angle, and move angle is factored in too, the selected movement could be the most natural one [20/07/18] + if(cdistx0) px0=-monster.base.h,px1=monster.base.h,mcy=m_line_x=min; // going right + var py0=monster.base.vn,py1=-monster.base.v; m_line_y=max; // going up + if(y1>y0) py0=-monster.base.v,py1=monster.base.vn,m_line_y=min; // going down + + m_dx=-px1; m_dy=-py1; // Find the line hit, then convert to actual coordinates + if(!can || !can_move({map:monster.map,x:x1+px1,y:y1+py0,going_x:x1+px1,going_y:y1+py1},1)) can=false; + if(!can || !can_move({map:monster.map,x:x1+px0,y:y1+py1,going_x:x1+px1,going_y:y1+py1},1)) can=false; + m_line_x=m_line_y=false; + + } + return can; + } + function line_hit_logic(ax,ay,bx,by) + { + line_hit_x=m_line_x(ax,bx),line_hit_x=m_line_x(line_hit_x+6*EPS,line_hit_x-6*EPS)+m_dx; + line_hit_y=m_line_y(ay,by),line_hit_y=m_line_y(line_hit_y+6*EPS,line_hit_y-6*EPS)+m_dy; + } + for(var i=bsearch_start(GEO.x_lines||[],minx);i<(GEO.x_lines||[]).length;i++) + { + if(is_server) perfc.roam_ops+=1; + var line=GEO.x_lines[i]; // c++; + if(line[0]==x1 && (line[1]<=y1 && line[2]>=y1 || line[0]==x0 && y0<=line[1] && y1>line[1])) // can't move directly onto lines - or move over lines, parallel to them + { + if(m_line_y) line_hit_logic(line[0],line[1],line[0],line[2]); + return false; + } + if(minx>line[0]) continue; // can be commented out with: while(start=x1 || line[0]==y0 && x0<=line[1] && x1>line[1])) + { + if(m_line_x) line_hit_logic(line[1],line[0],line[2],line[0]); + return false; + } + if(miny>line[0]) continue; + if(maxy=monster.going_x) || (monster.from_x>=monster.going_x && x<=monster.going_x) || abs(x-monster.going_x)<0.3 || abs(y-monster.going_y)<0.3) + if(((monster.from_x<=monster.going_x && x>=monster.going_x-0.1) || (monster.from_x>=monster.going_x && x<=monster.going_x+0.1)) && + ((monster.from_y<=monster.going_y && y>=monster.going_y-0.1) || (monster.from_y>=monster.going_y && y<=monster.going_y+0.1))) + { + set_xy(monster,monster.going_x,monster.going_y); + + //monster.going_x=undefined; - setting these to undefined had bad side effects, where a character moves in the client side, stops in server, and going_x becoming undefined mid transit client side [18/06/18] + //monster.going_y=undefined; + + if(monster.loop) + { + monster.going_x=monster.positions[(monster.last_m+1)%monster.positions.length][0]; + monster.going_y=monster.positions[(++monster.last_m)%monster.positions.length][1]; + monster.u=true; + start_moving_element(monster); + return; + } + + monster.moving=monster.amoving||false; + monster.vx=monster.vy=0; // added these 2 lines, as the character can walk outside when setTimeout ticks at 1000ms's [26/07/16] + // if(monster.me) console.log(monster.real_x+","+monster.real_y); + if(monster.s && monster.s.dash) + { + delete monster.s.dash; + if(is_server) resend(monster,"u+cid"); + } + if(monster.name_tag) stop_name_tag(monster); + if(monster.me) + { + resolve_deferreds("move",{reason:"stopped"}); + showhide_quirks_logic(); + } + if(monster.is_monster && !monster.target && is_server && E.schedule.night && Math.random()<0.4) + { + monster.s.sleeping={"ms":3000+5000*Math.random()}; + monster.u=true; monster.cid++; + } + } +} + +function is_door_close(map,door,x,y) +{ + var def=G.maps[map],spawn=def.spawns[door[6]]; + if(point_distance(x,y,spawn[0],spawn[1])<40) + return true; + if(distance({x:x,y:y,width:26,height:35},{x:door[0],y:door[1],width:door[2],height:door[3]})<40) + return true; + return false; +} + +function can_use_door(map,door,x,y) // this one is costly, so only check when is_door_close [14/09/18] +{ + var def=G.maps[map],spawn=def.spawns[door[6]]; + if(point_distance(x,y,spawn[0],spawn[1])<40 && can_move({map:map,x:x,y:y,going_x:spawn[0],going_y:spawn[1]})) + { + //console.log("SPAWNACCESS"+spawn); + return true; + } + if(distance({x:x,y:y,width:26,height:35},{x:door[0],y:door[1],width:door[2],height:door[3]})<40) + { + var can=false; + [ + [0,0], + [-door[2]/2,0], + [door[2]/2,0], + [-door[2]/2,-door[3]], + [door[2]/2,-door[3]], + [0,-door[3]], + ].forEach(function(mxy){ + var mx=mxy[0],my=mxy[1]; + if(can_move({map:map,x:x,y:y,going_x:door[0]+mx,going_y:door[1]+my})) + { + //console.log("DOORLINEACCESS"+(door[0]+mx)+","+(door[1]+my)); + can=true; + } + }) + if(can) return true; + } + return false; +} + +function is_point_inside(p,polygon) +{ + var isInside = false; + var minX = polygon[0][0], maxX = polygon[0][0]; + var minY = polygon[0][1], maxY = polygon[0][1]; + for (var n = 1; n < polygon.length; n++) { + var q = polygon[n]; + minX = Math.min(q[0], minX); + maxX = Math.max(q[0], maxX); + minY = Math.min(q[1], minY); + maxY = Math.max(q[1], maxY); + } + + if (p[0] < minX || p[0] > maxX || p[1] < minY || p[1] > maxY) { + return false; + } + + var i = 0, j = polygon.length - 1; + for (i, j; i < polygon.length; j = i++) { + if ( (polygon[i][1] > p[1]) != (polygon[j][1] > p[1]) && + p[0] < (polygon[j][0] - polygon[i][0]) * (p[1] - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0] ) { + isInside = !isInside; + } + } + + return isInside; +} + +function random_point(polygon,base) +{ + var minX = polygon[0][0], maxX = polygon[0][0]; + var minY = polygon[0][1], maxY = polygon[0][1]; + var defX = polygon[0][0], defY = polygon[0][1] + for (var n = 1; n < polygon.length; n++) { + var q = polygon[n]; + if(q[0] < minX || q[0]==minX && q[1]>defY) + { + + } + maxX = Math.max(q[0], maxX); + minY = Math.min(q[1], minY); + maxY = Math.max(q[1], maxY); + } + for(var i=0;i<200;i++) + { + var rX=minX+Math.random()*(maxX-minX); + var rY=minY+Math.random()*(maxY-minY); + if(is_point_inside([rX,rY],polygon)) + { + var valid=true; + if(base) + base_points(rX,rY,base).forEach(function(xy){ + if(!is_point_inside([xy[0],xy[1]],polygon)) valid=false; + }) + if(valid) return [rX,rY]; + } + } + if(base) return [defX,defY]; + return [defX,defY]; +} + +function trigger(f) +{ + setTimeout(f,0); +} + +function to_number(num) +{ + try{ + num=round(parseInt(num)); + if(num<0) return 0; + if(!num) num=0; + }catch(e){num=0}; + return num; +} + +function is_nun(a) +{ + if(a===undefined || a===null) return true; + return false; +} + +function nunv(a,b) +{ + if(a===undefined || a===null) return b; + return a; +} + +function is_number(obj) +{ + try{ + if(!isNaN(obj) && 0+obj===obj) return true; + }catch(e){} + return false; +} + +function is_string(obj) +{ try{ + return Object.prototype.toString.call(obj) == '[object String]'; +} catch(e){} return false; } + +function is_array(a) +{ try{ + if (Array.isArray(a)) return true; +} catch(e){} return false; } + +function is_function(f) +{ try{ + var g = {}; + return f && g.toString.call(f) === '[object Function]'; +} catch(e){} return false; } + +function is_object(o) +{ try{ + return o!==null && typeof o==='object'; +} catch(e){} return false; } + +function clone(obj,args) { + // http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object + if(!args) args={}; + if(!args.seen && args.seen!==[]) args.seen=[]; // seen modification - manual [24/12/14] + if(null == obj) return obj; + if(args.simple_functions && is_function(obj)) return "[clone]:"+obj.toString().substring(0,40); + if ("object" != typeof obj) return obj; + if (obj instanceof Date) { + var copy = new Date(); + copy.setTime(obj.getTime()); + return copy; + } + if (obj instanceof Array) { + args.seen.push(obj); + var copy = []; + for (var i = 0; i < obj.length; i++) { + copy[i] = clone(obj[i],args); + } + return copy; + } + if (obj instanceof Object) { + args.seen.push(obj); + var copy = {}; + for (var attr in obj) { + if (obj.hasOwnProperty(attr)) + { + if(args.seen.indexOf(obj[attr])!==-1) { copy[attr]="circular_attribute[clone]"; continue; } + copy[attr] = clone(obj[attr],args); + } + } + return copy; + } + throw "type not supported"; +} + +function safe_stringify(obj,third) // doesn't work for Event's - clone also doesn't work [31/08/15] +{ + var seen = []; + try{ + if(obj===undefined) return "undefined"; + var result=JSON.stringify(obj, function(key, val) { + if (val != null && typeof val == "object") { + if (seen.indexOf(val) >= 0) { + return; + } + seen.push(val); + if("x" in val) // amplify - also in functions.js game_stringify + { + var new_val={}; + ["x","y","width","height"].forEach(function(p){ + if(p in val) new_val[p]=val[p]; + }); + for(var p in val) new_val[p]=val[p]; + val=new_val; + } + } + return val; + },third); + try{ + if("x" in obj) // amplify - also in functions.js game_stringify + { + result=JSON.parse(result); + result.x=obj.x; + result.y=obj.y; + result=JSON.stringify(result); + } + }catch(e){} + return result; + } + catch(e) + { + return "safe_stringify_exception"; + } +} + +function smart_eval(code,args) +{ + // window[cur.func] usages might execute the corresponding string and cause an exception - highly unlikely [22:32] + if(!code) return; + if(args && !is_array(args)) args=[args]; + if(is_function(code)) + { + if(args) code.apply(this,clone(args)); // if args are not cloned they persist and cause irregularities like mid persistence [02/08/14] + else code(); + } + else if(is_string(code)) eval(code); +} + +function is_substr(a,b) +{ + if(is_array(b)) + { + for(var i=0;i=0;i--) + array.splice(to_delete[i],1); +} + +function array_delete(array,entity) // keywords: remove, from +{ + var index=array.indexOf(entity); + if (index > -1) { + array.splice(index, 1); + } +} + +function in_arr(i,kal) +{ + if(is_array(i)) + { + for(var j=0;jlimit) arr.pop(); + +} + +String.prototype.toTitleCase = function () { + return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); +}; + +String.prototype.replace_all = function (find, replace) { + var str = this; + return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace); +}; + +function html_escape(html) +{ + var escaped = ""+html; + var findReplace = [[/&/g, "&"], [//g, ">"], [/"/g, """]]; + for(var item in findReplace) + escaped = escaped.replace(findReplace[item][0], findReplace[item][1]); + return escaped; +} +/*"*/ +function he(html){return html_escape(html);} + +function future_ms(ms) +{ + var c=new Date(); + c.setUTCMilliseconds(c.getUTCMilliseconds()+ms); + return c; +} +function future_s(s) +{ + var c=new Date(); + c.setUTCSeconds(c.getUTCSeconds()+s); + return c; +} +function future_m(m) +{ + return future_s(60*m); +} +function future_h(h) +{ + return future_m(60*h); +} + +function mssince(t,ref) +{ + if(!ref) ref=new Date(); + return ref.getTime() - t.getTime(); +} +function ssince(t,ref) { return mssince(t,ref)/1000.0; } +function msince(t,ref) { return mssince(t,ref)/60000.0; } +function hsince(t,ref) { return mssince(t,ref)/3600000.0; } + +function sleep(ms) +{ + return new Promise(resolve=>setTimeout(resolve,ms)); +} + +function log_trace(place,err) +{ + console.log('\n===================='); + if(typeof err==='object') + { + if(err.message) console.log('Exception['+place+']:\n'+err.message); + if (err.stack) + { + console.log('Stacktrace:'); + //console.log('===================='); + console.log(err.stack); + //console.log(Object.keys(err.stack)); + } + } + else console.log('log_trace: argument is not an object on :'+place); + console.log('====================\n'); +} + +var TYPE_MIN = 'min'; +var TYPE_MAX = 'max'; + +function Heap(array, type, compareFunction) { + // https://gist.github.com/fabianuribe/5eeeaf5370d03f66f739 + var x={ + buildHeap: function () { + var last = this.array.length - 1; + var middle = Math.floor(last/2); + var i; + for (i = middle; i >= 0; i -= 1) { + this._heapify(i); + } + }, + sort: function () { + var limit = this._getLastIdx(); + while (limit > 0) { + this._swap(0, limit); + limit -= 1; + if (limit) { + this._heapify(0, limit); + } + } + }, + insert: function (element) { + this.array.push(element); + this._bubbleUp(this._getLastIdx()); + }, + removeTop: function () { + var top = this.array[0]; + this._swap(0, this._getLastIdx()); + this.array.pop(); + this._heapify(0); + return top; + }, + defaultCompareFunction: function (a, b) { + if (a > b) { + return 1; + } + if (b > a) { + return -1; + } + return 0; + }, + _heapify: function (startIdx, limitIdx) { + limitIdx = limitIdx || this._getLastIdx(); + var topIdx = startIdx; + var top = this.array[topIdx]; + var leftIdx = this._getLeftChild(startIdx, limitIdx); + var rightIdx = this._getRightChild(startIdx, limitIdx); + var left = leftIdx && this.array[leftIdx]; + var right = rightIdx && this.array[rightIdx]; + + if (startIdx > limitIdx) { + return; + } + + if (left && + ((this.type === TYPE_MIN && this.compare(left, top) < 0) || + (this.type === TYPE_MAX && this.compare(left, top) > 0))) { + topIdx = leftIdx; + top = left; + } + + if (right && + ((this.type === TYPE_MIN && this.compare(right, top) < 0) || + (this.type === TYPE_MAX && this.compare(right, top) > 0))) { + topIdx = rightIdx; + top = right; + } + + if (startIdx !== topIdx) { + this._swap(startIdx, topIdx); + this._heapify(topIdx, limitIdx); + } + }, + _swap: function (a, b) { + var temp = this.array[a]; + this.array[a] = this.array[b]; + this.array[b] = temp; + }, + _bubbleUp: function(index) { + var parentIdx = this._getParent(index); + var parent = (parentIdx >= 0) ? this.array[parentIdx] : null; + var value = this.array[index]; + + if (parent === null) { + return; + } + if ((this.type === TYPE_MIN && this.compare(value, parent) < 0) || + (this.type === TYPE_MAX && this.compare(value, parent) > 0)) { + this._swap(index, parentIdx); + this._bubbleUp(parentIdx); + } + }, + _getLeftChild: function (parent, limit) { + limit = limit || this._getLastIdx(); + var childIndex = parent * 2 + 1; + return (childIndex <= limit) ? childIndex : null; + }, + _getRightChild: function (parent, limit) { + limit = limit || this._getLastIdx(); + var childIndex = parent * 2 + 2; + return (childIndex <= limit) ? childIndex : null; + }, + _getParent: function (index) { + if (index % 2) { + // Is left child + return (index - 1)/2; + } + // Is right child + return (index/2) - 1; + }, + _getLastIdx: function () { + var size = this.array.length; + return size > 1 ? size - 1 : 0; + } + }; + x.array = array || []; + x.type = type === TYPE_MIN ? TYPE_MIN : TYPE_MAX; + x.compare = (typeof compareFunction === 'function') ? compareFunction : this.defaultCompareFunction; + x.buildHeap(); + return x; +} + +function vHeap() +{ + return Heap([],'min',function (a, b) { + if (a.value > b.value) { + return 1; + } + if (b.value > a.value) { + return -1; + } + return 0; + }); +} + +// try{ +// asadasdasd=asdasdda; +// } +// catch(e){log_trace("test",e);} + +function rough_size( object ) { + //reference: http://stackoverflow.com/a/11900218/914546 + var objectList = []; + var stack = [ object ]; + var bytes = 0; + + while ( stack.length ) { + var value = stack.pop(); + + if ( typeof value === 'boolean' ) { + bytes += 4; + } + else if ( typeof value === 'string' ) { + bytes += value.length * 2; + } + else if ( typeof value === 'number' ) { + bytes += 8; + } + else if + ( + typeof value === 'object' + && objectList.indexOf( value ) === -1 + ) + { + objectList.push( value ); + + for( var i in value ) { + stack.push( value[ i ] ); + } + } + } + return bytes; +} \ No newline at end of file diff --git a/js/functions.js b/js/functions.js new file mode 100644 index 0000000..f06b212 --- /dev/null +++ b/js/functions.js @@ -0,0 +1,7009 @@ +var auto_api_methods=[],base_url=window.location.protocol+"//"+window.location.host; +var sounds={}; +var draw_timeouts=[],timers={},pingts={},pings=[],modal_count=0,last_ping=new Date(); +var DTM=1; // draw_timeout multiplier - floating point - ideally ~1, but if a 60fps calibrated animation is executed on 30fps, around ~2 [04/03/19] +var DMS=0; // ms after draw timeout trigger + +function is_hidden() +{ + return document.hidden; +} + +var last_id_sent='',last_xid_sent=''; +function send_target_logic() +{ + var change=false; + if(ctarget && last_id_sent!=(ctarget.id||"")) change=true; + if(!ctarget && last_id_sent) change=true; + if(xtarget && last_xid_sent!=(xtarget.id||"")) change=true; + if(!xtarget && last_xid_sent) change=true; + last_id_sent=ctarget&&ctarget.id||""; + last_xid_sent=xtarget&&xtarget.id||""; + if(change) + { + socket.emit("target",{id:last_id_sent,xid:last_xid_sent}); + return push_deferred("target"); + } + return resolving_promise({success:true,no_change:true}); +} + +function is_npc(entity) +{ + if(entity && (entity.npc || entity.type=="npc")) return true; +} + +function is_monster(entity) +{ + if(entity && entity.type=="monster") return true; +} + +function is_player(entity) +{ + if(entity && entity.type=="character" && !entity.npc) return true; +} +function is_character(e){return is_player(e);} + +function cfocus(selector) +{ + var $selector=$(selector); + if(!$(selector+":focus").length) $selector.focus(); + $selector.html($selector.html()); +} + +var last_typing=new Date(); +function send_typing() +{ + if(mssince(last_typing)<1100) return; + last_typing=new Date(); + socket.emit('property',{typing:true}); +} + +setInterval(function(){ + if(ssince(last_ping)>2.4) + if(window.socket) ping(true); +},3200); + +function push_ping(ping) +{ + last_ping=new Date(); + pings.push(ping); + if(pings.length>40) pings.shift(); + if(character) + { + character.ping=0; + pings.forEach(function(p){character.ping+=p/pings.length;}) + } +} + +function ping(silent) +{ + var data={id:randomStr(5)}; + pingts[data.id]=new Date(); + if(!silent) data.ui=true; + socket.emit("ping_trig",data); +} + +function reset_ms_check(element,name,ms) +{ + element["ms_"+name]=null; + //element["ms_"+name]=new Date(); + //element["ms_"+name].setMilliseconds(element["ms_"+name].getMilliseconds()-parseInt(ms/2)); +} + +function ms_check(element,name,ms) +{ + if(!element["ms_"+name]) {element["ms_"+name]=new Date(); return 0;} //new[13/03/17] + if(element["ms_"+name] && mssince(element["ms_"+name]) should not remove < the entity ... messes the entire game logic [29/06/18] + } + else + { + element.real_alpha-=0.05; + element.height-=(element.cscale||1); + element.width-=(element.cscale||1); + draw_timeout(fade_out_magiport(i+1,element),16,1); + } + } +} + +function fade_away_teleport(i,element) +{ + return function(){ + if(i==10 || is_hidden()) + { + if(element==character) return; + destroy_sprite(element,"children"); + } + else + { + element.real_alpha-=0.10; + update_sprite(element); + draw_timeout(fade_away_teleport(i+1,element),30,1); + } + } +} + +function fade_away(i,element) +{ + return function(){ + if(i==20 || is_hidden()) + { + // map.removeChild(element); - originally there was only this - it caused a major memory leak [19/08/16] + destroy_sprite(element,"children"); //#TODO: consider calling .destroy({children:true}) [20/08/16] + } + else + { + element.real_alpha-=0.05; + update_sprite(element); + draw_timeout(fade_away(i+1,element),30,1); + } + } +} + +function booster_modal_logic() +{ + $(".bitems").html(item_container({skin:G.items.cscroll1.skin},{name:"cscroll1"})); + $(".bitemo").html(item_container({skin:G.items.offering.skin},{name:"offering"})); + for(var i=1;i<=5;i++) + $(".bitem"+i).html(item_container({skin:G.items.goldbooster.skin_a},{level:i,name:"goldbooster",expires:future_s(999999999)})); +} + +var snip_wl_code="map_key(\"Q\",\"snippet\",\"smart_move('winterland')\");\n//Press Q in the Game to test this, after you EXECUTE!"; +var snip_esc_code="map_key(\"ESC\",{name:\"eval\",code:\"use_skill('stop'); esc_pressed();\",skin:G.skills.stop.skin});\n//Overrides ESC, adds stopping, overrides the 'eval' icon with the 'stop' icon"; +function keymap_modal_logic() +{ + [["1","charge"],["2","blink"],["3","supershot"],["4","invis"],["5","cleave"],["X","use_hp"],["Y","use_mp"]].forEach(function(ks){ + var k=ks[0],s=ks[1]; + $(".skb"+k).html(item_container({skid:k,skin:G.skills[s].skin,draggable:false},{"name":s})); + }); + var html=""; + object_sort(K).forEach(function(k){ + html+=""+k[1]+""; + }); + $(".skbkeys").html(html); +} + +function show_game_guide() +{ + if(gameplay=="hardcore") show_modal($('#hardcoreguide').html(),{styles:''}); // background: #E5E5E5; color: #010805; + else render_guide(); +} + +function show_shells_info() +{ + show_modal($('#shellsinfo').html(),{styles:'padding-left: 20px; padding-right: 20px; font-size: 24px;'}); +} + +function show_ttp() +{ + show_modal($('#ttp').html(),{wrap:false}); +} + +function show_credits() +{ + show_modal($('#credits').html(),{styles:'background: #E5E5E5; color: #010805; padding-left: 20px; padding-right: 20px; font-size: 24px; text-align: center',url:"/credits"}); +} + +function show_terms() +{ + show_modal($('#terms').html(),{styles:'background: #E5E5E5; color: #010805; padding-left: 20px; padding-right: 20px; font-size: 24px; text-align: center',url:"/terms"}); +} + +function show_privacy() +{ + show_modal($('#privacy').html(),{styles:'background: #E5E5E5; color: #010805; padding-left: 20px; padding-right: 20px; font-size: 24px; text-align: center',url:"/privacy"}); +} + +function show_opensource_info() +{ + show_modal($('#opensource').html(),{styles:'background: #E5E5E5; color: #010805; padding-left: 20px; padding-right: 20px; font-size: 24px; text-align: center'}); +} + +function hide_modal(force) +{ + var old_url=null,new_url=null; + if(window.is_comm && mssince(last_focus)<320){ + return; + } + if(!force && $('.modal:last input.mprotected[type="text"], .modal:last input.mprotected[type="email"], .modal:last input.mprotected[type="password"], .modal:last textarea.mprotected').filter(function(){return this.value.length>0;}).length) + { + return show_confirm("Are you sure you want to discard your entries?","Yes","No!",function(){hide_modal(); hide_modal(true);}); + } + old_url=modals[modal_count-1] && modals[modal_count-1].url; + if(modal_count>0) modal_count--; + new_url=modals[modal_count-1] && modals[modal_count-1].url; + if(window.page && (old_url||new_url)) window.history.replaceState({},page.title,new_url||page.url); + if($('.modal:last').find(".destroy").length) eval($('.modal:last').find(".destroy").attr("onclick")); + $('.modal:last').remove(); + if($('.modal:last').hasClass("hideinbackground")) + { + $('.modal:last').show(); + position_modals(); + } + if(!modal_count) + { + block_right_clicks=true; + if(0 && window.code) + { + $('#codeui').show(); + codemirror_render.refresh(); + } + $(".showwithmodals").hide(); $(".hidewithmodals").show(); + } +} + +function hide_modals() +{ + while(modal_count) + hide_modal(true); +} + +var modals=[]; +function show_modal(mhtml,args) +{ + if(window.is_bot) return; + if(!args) args={}; + if(!args.opacity && window.modal_opacity!==undefined) args.opacity=window.modal_opacity; + else if(!args.opacity) args.opacity=0.4; + if(!args.classes) args.classes=""; + if(args.hideinbackground) args.classes="hideinbackground"; + if(args.wrap===undefined) args.wrap=true; + var wrap_styles="",min_width=600; + min_width=min(600,$(window).width()-32); + if(args.wrap) wrap_styles="width: "+(args.wwidth||min_width)+"px; border: 5px solid gray; background: black;"; + modals[modal_count]=args; + modal_count++; + var html="",styles=""; + styles+="position: fixed; top: 0px; bottom: 0px; left: 0px; right: 0px; z-index: 9000; text-align: center; vertical-align: middle; overflow-y: scroll; "; + styles+="background: rgba(0,0,0,"+args.opacity+")"; + html+=""; + html+="
"; + if($('.modal:last').hasClass("hideinbackground")) $('.modal:last').hide(); + $("body").append(html); + var iheight=$('.imodal:last').height(); + if(height>iheight) $('.imodal:last').css("margin-bottom","0px").css("margin-top",max(0,round(height/2-iheight/2-5))); + if($('.modal:last').find(".oncreate").length) eval($('.modal:last').find(".oncreate").attr("onclick")); + block_right_clicks=false; + $(".showwithmodals").show(); $(".hidewithmodals").hide(); + if(0 && window.code && !args.keep_code) + { + $('#codeui').hide(); + if(last_hint) $('#codehint').remove(),last_hint=undefined; + } + if(window.page && args.url) window.history.replaceState({},page.title,args.url); +} + +function show_alert(x) +{ + show_modal("
"+x+"
"); +} + +function position_modals() +{ + $('.imodal').each(function(){ + var $this=$(this),iheight=$this.height(); + if(height>iheight) $this.css("margin-bottom","0px").css("margin-top",max(0,round(height/2-iheight/2-5))); + else $this.css("margin-bottom","40px").css("margin-top","100px"); + }); +} + +function set_status(html) +{ + current_status=html; // <- this is super important, otherwise the redraw's ruin the game, causing the cursor to flicker etc. [15/01/18] + // $("#status").html(html); + // Issue: when $("#status").html(html); is there, if you move your mouse into the character iframe, the mouse starts flickering + // Challenge: when $("#status").html(html); is there, try to contain the overflow, or the mouse interaction, isolate the iframe +} + +function show_json(json,args) +{ + // Originally safe_stringify(json,2); [15/02/19] + var html="",name="",xhtml=""; + if(!args) args={}; + if(args.character_ui) + { + if(character && args.name==character.name) name="Showing parent.character"; + else name="Showing parent.entities[\""+args.name+"\"]"; + html+="
Docs: Character Objects Explained
"; + } + else if(args.monster_ui) + { + name="Showing parent.entities["+args.name+"]"; + html+="
" + html+="
Docs: Monster Objects Explained
"; + html+="
"; + html+="
Guide: "+G.monsters[args.monster_ui].name+" Info
"; + html+="
"; + html+="
Drops: "+G.monsters[args.monster_ui].name+" Drops
"; + html+="
"; + } + else if(args.inventory_ui!==undefined) + { + args.name=args.inventory_ui; + name="Showing character.items["+args.name+"]"; + html+="
" + if(character.items[args.name]) html+="
Ref: Item Information
"; + html+="
"; + html+="
Show: All Inventory
"; + html+="
"; + } + else if(args.name) + { + name="Showing "+(args.prefix||"")+""+args.name+(args.postfix||"")+""; + } + if(args.info) + { + xhtml+="Info "+args.info+""; + } + if(!is_string(json)) json=safe_stringify(json,"\t"); + // IDEA: XHTML to reference the full object + show_modal(html+name+"
"+syntax_highlight(json)+"
"+xhtml,{url:args.url}); +} + +function json_to_html(json) +{ + if(!is_string(json)) json=safe_stringify(json,"\t"); + return "
"+syntax_highlight(json)+"
"; +} + +function add_magiport(name) +{ + add_chat("^",""+name+" wants to magiport you! \ + Accept",undefined,"mp"+name); +} + +function add_invite(name) +{ + add_chat("^",""+name+" wants to party. \ + Accept",undefined,"pin"+name); +} + +function add_challenge(name) +{ + add_chat("^",""+name+" challenged you to duel! \ + Accept",undefined,"chl"+name); +} + +function add_duel(challenger,vs,id) +{ + add_chat("^",""+vs+" accepted a duel from "+challenger+"! \ + Join",undefined,"duel"+vs); +} + +function add_request(name) +{ + add_chat("^",""+name+" wants to join your party. \ + Accept",undefined,"rq"+name); +} + +function add_frequest(name) +{ + add_chat("^",""+name+" wants to be your friend. \ + Accept",undefined,"frq"+name); +} + +function add_update_notes() +{ + update_notes.forEach(function(note){ + var color="gray"; + //if(note.indexOf("Happy New Year")!=-1) color="#C82F17"; + if(note.indexOf("Holiday")!=-1) color="#C82F17"; + if(note.indexOf("Duelland")!=-1) color="#3BB7CB"; + if(note.indexOf("Lunar")!=-1) color="#B02B16"; + if(note.indexOf("Valentine")!=-1) color="#C987B7"; // ,color="#85C76B" + if(note.indexOf("Halloween")!=-1) color="#DE6E37"; + if(note.indexOf("Egg Hunt Event")!=-1) color="#DE5CB8"; + add_log(note,color); + }); +} + +var game_logs=[],game_chats=[]; + +function clear_game_logs() +{ + game_logs=[]; + $("#gamelog").html(""); +} + +function add_log(message,color) +{ + // if(is_object(message)) throw "gg"; + if(is_object(message)) try{ message=JSON.stringify(message); }catch(e){ message="[Circular Object]"; } + if(no_html=="bot") game_logs.push([message,color]); + if(mode.dom_tests || inside=="payments" || no_html) return; + if(game_logs.length>480) // previously 1000/720 [27/07/18] + { + var html="
- Truncated -
"; + game_logs=game_logs.slice(-160); + game_logs.forEach(function(log){ + html+="
"+log[0]+"
" + }); + $("#gamelog").html(html); + } + game_logs.push([message,color]); + $("#gamelog").append("
"+message+"
"); + var entity=$("#gamelog")[0]; + $("#gamelog").scrollTop(entity&&entity.scrollHeight); +} + +function add_holiday_log() +{ + if(mode.dom_tests || inside=="payments" || no_html) return; + $("#gamelog").append("
Would you like to turn on the Holiday Tunes? Yes!
"); + var entity=$("#gamelog")[0]; + $("#gamelog").scrollTop(entity&&entity.scrollHeight); +} +function add_greenlight_log() +{ + if(mode.dom_tests || inside=="payments" || no_html) return; + $("#gamelog").append("
Adventure Land is on Steam Greenlight! Would really appreciate your help: Browser Open: Steam
"); + var entity=$("#gamelog")[0]; + $("#gamelog").scrollTop(entity&&entity.scrollHeight); +} + +var unread_chat=0,no_chat_notification=false; +function chat_inventory_logic() +{ + if(no_chat_notification) return; + if(inventory) + { + unread_chat+=1; + if(unread_chat==1) $(".newchatui").html("1 unread chat message!"); + else $(".newchatui").html(unread_chat+" unread chat messages!"); + $(".newchatui").css("display","inline-block"); + } +} + +function rebuild_chat() +{ + var selector=(!window.character&&"#gamelog"||"#chatlog"); + var html=""; + if(game_chats.length>250) + { + html="
- Truncated -
"; + var new_chats=[]; + for(var i=0;i "; + if(log[2]==colors.server_success || log[2]=="gold") rcolor="#E0E0E0"; + if(log[2]==colors.server_failure) rcolor="#626363"; + if(rrpt>1) rrpt=" ["+rrpt+"]"; else rrpt=""; + html+="
"+o_html+(log[0]=="^"&&log[1]||html_escape(log[1]))+rrpt+"
"; + }); + $(selector).html(html); +} + +function add_chat(owner,message,color,id) +{ + if(no_html=="bot") game_chats.push([owner,message,color,id]); + if(no_html || window.is_comm) return; + var selector=(!window.character&&"#gamelog"||"#chatlog"),owner_html='',rpt=1,deletion=false; + for(var i=0;i250 || deletion) // previously 240-180|150 - previously 360|180-270 [27/07/18] + rebuild_chat(); + + chat_inventory_logic(); + var rcolor="#999A4F"; + if(color==colors.server_success || color=="gold") rcolor="#E0E0E0"; + if(color==colors.server_failure) rcolor="#626363"; + game_chats.push([owner,message,color,id,rpt]); + if(owner && owner!="^") owner_html=""+owner+": "; + if(rpt>1) rpt=" ["+rpt+"]"; else rpt=""; + $(selector).append("
"+owner_html+(owner=="^"&&message||html_escape(message))+rpt+"
"); + $(selector).scrollTop($(selector)[0].scrollHeight); +} + +function remove_chat(id) +{ + var deletion=false; + for(var i=game_chats.length-1;i>=0;i--) + { + if(game_chats[i][3]==id) + { + game_chats.splice(i,1); + deletion=true; + } + } + if(deletion) rebuild_chat(); +} + +function cpm_window(name) +{ + if(no_html) return; + var cid="pm"+name; + last_say=cid; + if(!in_arr(cid,cwindows)) open_chat_window("pm",name,1); + else toggle_chat_window("pm",name); +} + +function add_pmchat(to,owner,message,xserver) +{ + if(no_html) return; + var cid="pm"+to,color=""; + if(!in_arr(cid,cwindows)) open_chat_window("pm",to,owner==character.name); + if(owner!=character.name && in_arr(cid,docked)) $("#chatt"+cid).addClass("newmessage"); + var owner_html=''; + xserver=xserver&&" [X]"||""; + owner_html=""+owner+": "; + $("#chatd"+cid).append("
"+owner_html+html_escape(message)+xserver+"
"); //class='chatentry' + $("#chatd"+cid).scrollTop($("#chatd"+cid)[0].scrollHeight); +} + +function add_partychat(owner,message) +{ + if(no_html) return; + var cid="party",color=""; + if(!in_arr(cid,cwindows)) open_chat_window("party","",owner==character.name); + if(owner!=character.name && in_arr(cid,docked)) $("#chatt"+cid).addClass("newmessage"); + var owner_html=''; + owner_html=""+owner+": "; + $("#chatd"+cid).append("
"+owner_html+html_escape(message)+"
"); //class='chatentry' + $("#chatd"+cid).scrollTop($("#chatd"+cid)[0].scrollHeight); +} + +function refresh_page() +{ + window.location=window.location; +} + +function item_position(name) +{ + for(var i=41;i>=0;i--) + { + if(character.items[i] && character.items[i].name==name) return i; + } + return undefined; +} + +function can_use(name) +{ + if(!next_skill[name] || (new Date())>next_skill[name]) return true; + return false; +} + +function send_code_message(to,data) +{ + if(!is_array(to)) to=[to]; + socket.emit("cm",{to:to,message:JSON.stringify(data)}); + return push_deferred("cm"); +} + +function get_nearby_hostiles(args) +{ + var hostiles=[]; + if(!args) args={}; + if(!args.range) args.range=character&&character.range||12000; + if(!args.limit) args.limit=12; + + for(id in entities) + { + var current=entities[id]; + if(current.rip || current.invincible || current.npc) continue; + if(character.team && current.team==character.team) continue; + if(!character.team && current.party && character.party==current.party) continue; + if(!character.team && current.guild && character.guild==current.guild) continue; + if(current.type=="character" && !(is_pvp || G.maps[character.map].pvp)) continue; + if(in_arr(current.owner,parent.friends)) continue; + var c_dist=parent.distance(character,current); + if(c_dist b.c_dist) ? 1 : ((b.c_dist > a.c_dist) ? -1 : 0);}); + return hostiles; +} + +var input_onclicks=[]; +function get_input(args) +{ + if(!args) return; + var html="
",ilast=0,focus=null; + if(is_array(args)) args={elements:args}; + else if(!args.elements) args={elements:[args]}; + args.elements.forEach(function(element){ + if(element.title) html+="
"+element.title+"
"; + if(element.input) + { + if(!focus) focus=element.input; + html+="
"; + } + if(element.textarea) + { + if(!focus) focus=element.textarea; + html+="
COMMAND
"; + show_modal(html); + var value=""; + if(window.codemirror_render3) + { + value=codemirror_render3.getValue(); + // codemirror_render3.destroy(); Automatically garbage collected + } + window.codemirror_render3=CodeMirror(function(current){$("#rendererx").replaceWith(current);},{ + value:fvalue||value, + mode:"javascript", + indentUnit:4, + indentWithTabs:true, + lineWrapping:true, + lineNumbers:true, + gutters:["CodeMirror-linenumbers","lspacer"], + theme:"pixel", + cursorHeight:0.75, + /*,lineNumbers:true*/ + }); + codemirror_render3.focus(); +} + +function show_snippet(fvalue) +{ + if($(".snippetbtn").length) return; + var html="
EXECUTE
"; + show_modal(html); + var value=""; + if(window.codemirror_render3) + { + value=codemirror_render3.getValue(); + // codemirror_render3.destroy(); Automatically garbage collected + } + window.codemirror_render3=CodeMirror(function(current){$("#rendererx").replaceWith(current);},{ + value:fvalue||value, + mode:"javascript", + indentUnit:4, + indentWithTabs:true, + lineWrapping:true, + lineNumbers:true, + gutters:["CodeMirror-linenumbers","lspacer"], + theme:"pixel", + cursorHeight:0.75, + /*,lineNumbers:true*/ + }); + codemirror_render3.focus(); +} + +function eval_character_snippet(name) +{ + name=name.toLowerCase(); + character_code_eval(name,window["codemirror_render"+name].getValue()); +} + +function show_character_snippet(name) +{ + var oname=name; + name=name.toLowerCase(); + var html="
EXECUTE
"; + show_modal(html); + var value="// "+oname+"\n"; + if(window["codemirror_render"+name]) + { + value=window["codemirror_render"+name].getValue(); + } + window["codemirror_render"+name]=CodeMirror(function(current){$("#renderer"+name).replaceWith(current);},{ + value:value, + mode:"javascript", + indentUnit:4, + indentWithTabs:true, + lineWrapping:true, + lineNumbers:true, + gutters:["CodeMirror-linenumbers","lspacer"], + theme:"pixel", + cursorHeight:0.75, + /*,lineNumbers:true*/ + }); + window["codemirror_render"+name].focus(); +} + +function get_active_characters() +{ + var characters={}; + if(!character) return characters; + characters[character.name]="self" + $("iframe").each(function(){ + var $this=$(this),name=$this.data("name"),new_name=null; + if(name) + { + var state="starting",lname=name.toLowerCase(),rid=$this.attr("id"); + // add_log(rid); + if(document.getElementById(rid) && document.getElementById(rid).contentWindow) + { + state="loading"; + if(document.getElementById(rid).contentWindow.character) + { + new_name=document.getElementById(rid).contentWindow.character.name; + state="active"; + if(document.getElementById(rid).contentWindow.code_active) + { + state="code"; + } + } + } + if(new_name && new_name!=name) + name=new_name,$this.attr("id","ichar"+name.toLowerCase()); // TEST server name correction [31/07/18] + characters[name]=state; + } + }); + return characters; +} + +function character_code_eval(name,snippet) +{ + var rid="ichar"+name.toLowerCase(); + var weval=document.getElementById(rid) && document.getElementById(rid).contentWindow && document.getElementById(rid).contentWindow.eval; + if(!weval) { add_log("Character not found! ","#993D42"); return undefined; } + if(document.getElementById(rid).contentWindow.code_active) + { + document.getElementById(rid).contentWindow.call_code_function("eval",snippet); + } + else if(document.getElementById(rid).contentWindow.code_run) add_log("CODE is warming up","#DC9E48") + else + { + document.getElementById(rid).contentWindow.start_runner(0,"\nset_message('Snippet');\n"+snippet); + } +} + +function character_window_eval(name,snippet) +{ + var rid="ichar"+name.toLowerCase(); + var weval=document.getElementById(rid) && document.getElementById(rid).contentWindow && document.getElementById(rid).contentWindow.eval; + if(!weval) { add_log("Character not found!","#993D42"); return undefined; } + var result=true; + try{ + weval(snippet); + } + catch(e) + { + result=false; + } + return result; +} + +function character_load_code() +{ + +} + +function code_eval(snippet) +{ + var f="eval"; + if(snippet.search("output=")!=-1 || snippet.search("json_output=")!=-1) f="eval_s"; + if(snippet.search("await")!=-1) snippet="(async () => {"+snippet+"})()"; + if(code_active) + { + call_code_function(f,snippet); + } + else if(code_run) add_log("CODE is warming up","#DC9E48") + else + { + start_runner(0,"\nset_message('Snippet');\n"+snippet); + } +} + + +function code_move(x,y) +{ + code_eval("smart_move({x:'"+x+"',y:'"+y+"'})") +} + +function code_travel(map) // putting html into strings, then onclick's, ''s, ""s, gets impossible after a certain level [29/06/18] +{ + code_eval("smart_move({map:'"+map+"'})") +} + +function direct_travel(to,s) +{ + socket.emit('transport',{to:to,s:s}); + return push_deferred("transport"); +} + +function start_character_runner(name,code_slot_or_name) +{ + var rid="ichar"+name.toLowerCase(); + if(gameplay=="test") rid+=randomStr(10); + $("#"+rid).remove(); + var url=(window.page&&page.url)||(window.location+""); + url=url.replace(character.name,name); + url=url.split(".land"); url=url[1]||url[0]; + url=url.split(".com"); url=url[1]||url[0]; + url=url.split("?"); url=url[0]; + if(!code_slot_or_name) code_slot_or_name=''; + $('#iframelist').append('
'); + $("#iframelist").css("display","inline-block"); + return push_deferred(name); +} + +function stop_character_runner(name) +{ + var rid="ichar"+name.toLowerCase(); + $("#"+rid).remove(); +} + +function start_runner(rid,code) +{ + tut("engage"); + //#MAINISSUE: Probably a Chrome bug, you press "ENGAGE", then ESC right after, iframe dies + // pointer-events: none; is a life-saver, otherwise if you move cursor in, you are doomed, every message update breaks the game cursor + if(!rid) rid="maincode"; + actual_code=false; + if(code===undefined) code=codemirror_render.getValue(),actual_code=true; + the_code=code; + $('.engagebutton').hide(); $('.dengagebutton').show(); + $('.iengagebutton').hide(); $('.idengagebutton').css("display","inline-block"); + $("#"+rid).remove(); + if(no_html) $('body').append(''); + else $('#iframelist').append('
'); + $("#iframelist").css("display","inline-block"); + code_run=true; + code_persistence_logic(); +} + +function stop_runner(rid) +{ + if(!rid) rid="maincode"; + call_code_function("on_destroy"); + code_run=code_active=false; + $('.engagebutton').show(); $('.dengagebutton').hide(); + $('.iengagebutton').css("display","inline-block"); $('.idengagebutton').hide(); + $("#"+rid).remove(); + socket.emit("code",{run:0}); + code_persistence_logic(); + if(sounds.empty) sounds.empty.stop(),sounds.empty.cplaying=false; +} + +function set_setting(owner,key,value) +{ + var data=storage_get("settings_cache"),the_code="",to_run=false; + data=data&&JSON.parse(data)||{}; + data[owner]=data[owner]||{}; + data[owner][key]=value; + storage_set("settings_cache",JSON.stringify(data)); +} + +function get_settings(owner) +{ + var data=storage_get("settings_cache"),the_code="",to_run=false; + data=data&&JSON.parse(data)||{}; + data[owner]=data[owner]||{}; + return data[owner]; +} + +function free_character(name) +{ + var character=null; + X.characters.forEach(function(c){ if(name==c.name) character=c;}) + if(character) + { + var data=storage_get("code_cache"),the_code="",to_run=false; + data=data&&JSON.parse(data)||{}; + try{ delete data["run_"+character.id]; } catch(e){} + // try{ delete data["code_"+character.id]; } catch(e){} + storage_set("code_cache",JSON.stringify(data)); + //var data=storage_get("settings_cache"),the_code="",to_run=false; + //data=data&&JSON.parse(data)||{}; + //try{ delete data[character.id]; } catch(e){} + //try{ delete data["global"]; } catch(e){} + //storage_set("settings_cache",JSON.stringify(data)); + smart_eval($('.onbackbutton').attr('onclick')); + add_log('Done!'); + } + else + { + add_log('Character not found!'); + } +} + +function get_code_slot() +{ + if(explicit_slot) return explicit_slot; + var data=storage_get("code_cache"),the_code="",to_run=false; + if(data) + { + data=JSON.parse(data); + return data["slot_"+real_id]||real_id; + } + return real_id; +} + + +function backup_code_cache_once() +{ + if(storage_get("code_cache") && !storage_get("code_cache_backup")) + storage_set("code_cache_backup",storage_get("code_cache")); +} + +function code_persistence_logic() +{ + if(explicit_slot) return; + try{ + var data=storage_get("code_cache"),the_code="",to_run=false,suffix=""; + // if(gameplay!="normal") suffix=gameplay; + data=data&&JSON.parse(data)||{}; + if(!code_slot) code_slot=real_id; + data["run_"+real_id+suffix]=actual_code&&code_run&&'1'||''; + if(data["code_"+real_id+suffix]) code_change=true; // first-save - code is no longer locally saved [30/05/20] + delete data["code_"+real_id+suffix]; + // if(gameplay=="hardcore") data["code_"+real_id+suffix]=codemirror_render.getValue(); + data["slot_"+real_id+suffix]=code_slot; + storage_set("code_cache",JSON.stringify(data)); + if(code_change) api_call("save_code",{code:codemirror_render.getValue(),slot:code_slot,auto:true}),code_change=false; + console.log("Code saved!"); + } + catch(e){console.log(e);} +} + +function toggle_runner() +{ + if(code_run) + { + stop_runner(); + } + else + { + start_runner(); + } +} + +var last_hint=undefined; +function code_logic() +{ + backup_code_cache_once(); + window.codemirror_render=CodeMirror(function(current){$("#code").replaceWith(current); current.classList.add("maincode");},{ + value:$('#dcode').val(), + mode:"javascript", + indentUnit:4, + indentWithTabs:true, + lineWrapping:true, + lineNumbers:true, + gutters:["CodeMirror-linenumbers","lspacer"], // "CodeMirror-lint-markers", + theme:"pixel", + cursorHeight:0.75, + // lint:true, + /*,lineNumbers:true*/ + }); + codemirror_render.on("change",function(){ + code_change=true; + }); + listen_for_hints(codemirror_render); +} + +function listen_for_hints(editor) +{ + editor.on('cursorActivity', function() { + if(!code) return; + var word=editor.findWordAt(editor.getCursor()); + var text=editor.getRange(word.anchor, word.head); + + + + if(text && !in_arr(text,["0"]) && (window[text] || in_arr(text,G.docs.functions))) + { + if(last_hint===undefined) + { + // $("body").append("
"); + $("#codelog").prepend("
"); + } + last_hint=text; + $('#codehint').html("[E] "+text+""); + $('#codehint').show(); + } + else if(last_hint) + $('#codehint').remove(),last_hint=undefined; + }); +} + +function load_code(num,log) +{ + api_call("load_code",{name:num,run:'',log:log}); +} + +function remove_code_fx() +{ + delete stage.cfilter_ascii; + delete stage.cfilter_bloom; + regather_filters(stage); +} + +function toggle_code() +{ + if(code) + { + $('.codeui').hide(); + code=false; + $(":focus").blur(); // for the -_ button usage [26/04/17] + remove_code_fx(); + $('#codehint').remove(); last_hint=undefined; + } + else + { + $('.codeui').show(); + code=true; + codemirror_render.refresh(); + if(character && !character.moving && options.code_fx) + { + stage.cfilter_ascii=new PIXI.filters.AsciiFilter(16); + stage.cfilter_bloom=new PIXI.filters.BloomFilter(); + regather_filters(stage); + } + } +} + +function start_timer(name) +{ + timers[name]=new Date(); +} + +function stop_timer(name,extra) +{ + if(extra) extra="["+extra+"]"; else extra=""; + ms=mssince(timers[name]); + if(name=="draw" && ms>10 || name=="remove_sprite") + { + if(log_flags.timers) console.log("timer["+name+"]"+extra+": "+mssince(timers[name])); + } + timers[name]=new Date(); +} + +function the_door() +{ + if(animatables.the_door) h_shake(); + draw_timeout(function(){ + if(animatables.the_door) set_texture(animatables.the_door,"1"); + },200); + draw_timeout(function(){ + if(animatables.the_door) set_texture(animatables.the_door,"2"); + },300); + draw_timeout(function(){ + if(animatables.the_door) set_texture(animatables.the_door,"3"); + },400); + draw_timeout(function(){ + if(animatables.the_door) set_texture(animatables.the_door,"4"); + },500); + draw_timeout(function(){ + if(animatables.the_door) set_texture(animatables.the_door,"5"); + },600); + draw_timeout(function(){ + if(animatables.the_door) h_shake(); + },2800); + draw_timeout(function(){ + if(animatables.the_door) set_texture(animatables.the_door,"4"); + },2900); + draw_timeout(function(){ + if(animatables.the_door) set_texture(animatables.the_door,"3"); + },3000); + draw_timeout(function(){ + if(animatables.the_door) set_texture(animatables.the_door,"2"); + },3100); + draw_timeout(function(){ + if(animatables.the_door) set_texture(animatables.the_door,"1"); + },3200); + draw_timeout(function(){ + if(animatables.the_door) set_texture(animatables.the_door,"0"); + },3300); +} + +function the_lever() +{ + socket.emit("interaction","the_lever"); + if(animatables.the_lever) h_minor(); + draw_timeout(function(){ + if(animatables.the_lever) set_texture(animatables.the_lever,"1"); + },100); + draw_timeout(function(){ + if(animatables.the_lever) set_texture(animatables.the_lever,"2"); + },200); +} + +function v_shake_minor() +{ + function displ(y) + { + return function(){ + stage.y+=y; + ch_disp_y-=y; + } + } + var i=0; + [-1,1].forEach(function(d){ + setTimeout(displ(d),i++*20); + }) +} + +function v_shake() +{ + function displ(y) + { + return function(){ + stage.y+=y; + ch_disp_y-=y; + } + } + var i=0; + [-1,1,-2,2,-2,2,-1,1].forEach(function(d){ + setTimeout(displ(d),i++*40); + }) +} + +function v_shake_i(e) +{ + function displ(e,y) + { + return function(){ + if(e==character) ch_disp_y-=y; + else e.real_y-=y; + } + } + var i=0; + [-1,1,-2,2,-2,2,-1,1].forEach(function(d){ + setTimeout(displ(e,d),i++*40); + }) +} + +function v_shake_i_minorX(e) +{ + function displ(e,y) + { + return function(){ + e.real_y-=y; + if(y===1) delete e.shaking; + } + } + var i=1; + e.shaking=true; + [-1,1].forEach(function(d){ + setTimeout(displ(e,d),i++*(round(400+Math.random()*300))); + }) +} + +function v_shake_i2(e) +{ + function displ(e,y) + { + return function(){ + if(e==character) ch_disp_y-=y; + else e.real_y-=y; + } + } + var i=0; + [-1,1,-1,1,-1,1,-1,1].forEach(function(d){ + setTimeout(displ(e,d),i++*20); + }) +} + +function rshake_i_major(e) +{ + function displ(e,d) + { + return function(){ + if(e==character) stage.y-=d[1],stage.x-=d[0]; + else e.real_y-=d[1],e.real_x-=d[0]; + } + } + var i=0; + [[-6,-4],[6,4],[6,4],[-6,-4]].forEach(function(d){ + setTimeout(displ(e,d),i++*10); + }) +} + + +function v_shake_i_minor(e) // display object only +{ + function displ(e,y) + { + return function(){ + e.y-=y; + } + } + var i=0; + [-1,1].forEach(function(d){ + setTimeout(displ(e,d),i++*20); + }) +} + +function v_dive() +{ + function displ(y) + { + return function(){ + stage.y+=y; + ch_disp_y-=y; + } + } + var i=0; + [-2,-1.5,-1.5,2,1,1,1].forEach(function(d){ + setTimeout(displ(d),i++*20); + }) +} + +function v_dive_i(e) +{ + function displ(e,y) + { + return function(){ + if(e==character) ch_disp_y-=y; + else e.real_y-=y; + } + } + var i=0; + [-2,-1.5,-1.5,2,1,1,1].forEach(function(d){ + setTimeout(displ(e,d),i++*20); + }) +} + +function no_no_no(times) +{ + function displ(y) + { + return function(){ + ch_disp_x-=y; + } + } + var i=0,arr=[-1,1,-1,1]; + if(times==2) arr=[-1,1,-1,1,-1,1,-1,1]; + arr.forEach(function(d){ + setTimeout(displ(d),i++*40); + }) +} + +function yes_yes_yes(times) +{ + function displ(y) + { + return function(){ + ch_disp_y-=y; + } + } + var i=0,arr=[-1,1,-1,1]; + if(times==2) arr=[-1,1,-1,1,-1,1,-1,1]; + arr.forEach(function(d){ + setTimeout(displ(d),i++*40); + }) +} + +function jump_up(times) +{ + function displ(y) + { + return function(){ + ch_disp_y-=y; + } + } + var i=0,arr=[-1,-2,2,1]; + arr.forEach(function(d){ + setTimeout(displ(d),i++*40); + }) +} + +function sway(e) // This is the latest method, uncluding ch_disp/real_x logic [22/06/18] +{ + function displ(x,y) + { + return function(){ + if(e==character) ch_disp_x-=x,ch_disp_y-=y; + else e.real_x-=x,e.real_y-=y; + } + } + var i=0; + [[-3,-3],[-3,-3],[-3,-3],[0,3],[0,3],[0,3],[3,0],[3,0],[3,0]].forEach(function(d){ + setTimeout(displ(d[0],d[1]),i++*16); + }) +} + +function mojo(e) +{ + function displ(x,y) + { + return function(){ + if(e==character) ch_disp_x-=x,ch_disp_y-=y; + else e.real_x-=x,e.real_y-=y; + } + } + var i=0; + [[-3,-3],[3,3],[-3,3],[3,-3],[3,3],[-3,-3],[-3,3],[3,-3]].forEach(function(d){ + setTimeout(displ(d[0],d[1]),i++*33); + }) +} + +function flurry(e) +{ + function displ(x,y) + { + return function(){ + if(e==character) ch_disp_x-=x,ch_disp_y-=y; + else e.real_x-=x,e.real_y-=y; + } + } + var i=0; + var arr=[[-2,-2],[-2,-2],[-2,-2],[6,6],[0,-2],[0,-4],[-4,0],[-2,0],[0,2],[0,2],[0,2],[2,0],[2,0],[2,0]]; + shuffle(arr); + arr.forEach(function(d){ + setTimeout(displ(d[0],d[1]),i++*16); + }) +} + +function h_minor() +{ + function displ(x) + { + return function(){ + stage.x+=x; + } + } + var i=0; + [-1,1,-1,1,-1,1,-1,1].forEach(function(d){ + setTimeout(displ(d),i++*30); + }) +} + +function h_shake() +{ + function displ(x) + { + return function(){ + stage.x+=x; + ch_disp_x-=x; + } + } + var i=0; + [-1,1,-2,2,-3,3,-3,3,-3,3,-2,2,-1,1].forEach(function(d){ + setTimeout(displ(d),i++*80); + }) +} + +function bump_up(entity,amount) +{ + function displ(y) + { + return function(){ + if(entity==character) ch_disp_y-=y; + else entity.real_y-=y; + } + } + var i=0; + [1,1,1,-0.5,-0.5,-0.5,-0.5,-0.5,-0.5].forEach(function(d){ + setTimeout(displ(d*amount),i++*17); + }) +} + +function animate_weapon(player,target) +{ + player.fx.attack=[new Date(),0]; +} + +function safe_y_move(sprite,y) +{ + if(sprite.me) ch_disp_y+=y; + else sprite.real_y+=y,sprite.y_disp+=y; +} + +function safe_x_move(sprite,x) +{ + if(sprite.me) ch_disp_x+=x; + else sprite.real_x+=x; +} + +function attack_animation_logic(sprite,source) +{ + var only_up=false,multiplier=1.5; + if(sprite.type=="character") multiplier=3.5; + if(in_arr(source,["partyheal"])) only_up=true; + if(sprite.fx.aaa || sprite.fx.aaa===0) return; + sprite.fx.aaa=sprite.a_direction; + if(1) + { + if(sprite.fx.aaa==0 || only_up) safe_y_move(sprite,multiplier*2); + else if(sprite.fx.aaa==3) safe_y_move(sprite,-multiplier*2); + else if(sprite.fx.aaa==1) safe_x_move(sprite,-multiplier*2); + else safe_x_move(sprite,multiplier*2); + setTimeout(function(){ + if(sprite.fx.aaa==0 || only_up) safe_y_move(sprite,-multiplier); + else if(sprite.fx.aaa==3) safe_y_move(sprite,multiplier); + else if(sprite.fx.aaa==1) safe_x_move(sprite,multiplier); + else safe_x_move(sprite,-multiplier); + },60); + setTimeout(function(){ + if(sprite.fx.aaa==0 || only_up) safe_y_move(sprite,-multiplier); + else if(sprite.fx.aaa==3) safe_y_move(sprite,multiplier); + else if(sprite.fx.aaa==1) safe_x_move(sprite,multiplier); + else safe_x_move(sprite,-multiplier); + sprite.fx.aaa=null; + },120); + if(sprite.moving) + setTimeout(function(){ + if(sprite.moving && sprite.fx.aaa===null) + { + calculate_vxy(sprite); + set_direction(sprite); + } + },240); + } +} + +function set_direction(sprite,mode) +{ + // console.log(sprite.name+" "+mode); + if(mode!="soft" && sprite.moving && sprite.name_tag) start_name_tag(sprite); + var edge=70,direction=0; + if(mode=="npc") edge=45; + if(abs(sprite.angle)character.gold) render_interaction("noshells"); + else + { + socket.emit("buy_shells",{gold:(amount*G.multipliers.shells_to_gold)}); + render_interaction("yesshells"); + } +} + +function buy(name,quantity) +{ + if(G.items[name] && G.items[name].cash && !G.items[name].p2w && G.items[name].cash<=character.cash) + return buy_with_shells(name,quantity); + return buy_with_gold(name,quantity); +} + +function buy_with_gold(name,quantity) +{ + if(name=="scroll0") tut("buyscrolls"); if(name=="cscroll0") tut("buycscroll0"); + if(mssince(last_npc_right_click)<100) return rejecting_promise({reason:"npc_misclickp"}); + socket.emit("buy",{name:name,quantity:quantity}); + $('.buynum').html($('.buynum').data('q')); + return push_deferred("buy"); +} + +function buy_with_shells(name,quantity) +{ + if(mssince(last_npc_right_click)<100) return; + socket.emit("buy_with_cash",{name:name,quantity:quantity}); + $('.buynum').html($('.buynum').data('q')); + return push_deferred("buy_with_cash"); +} + +function split(num,quantity) +{ + socket.emit("split",{num:num,quantity:quantity}); + return push_deferred("split"); +} + +function sell(num,quantity) +{ + if(!quantity) quantity=1; + socket.emit("sell",{num:num,quantity:quantity}); + try{ + $('.sellnum').html(max(0,character.items[num].q-quantity)); + } + catch(e){ + $('.sellnum').html(0); + } + return push_deferred("sell"); +} + +var last_ccfunc=null; +function call_code_function_f(name,a1,a2,a3) +{ + if(code_active) + { + try{ + return get_code_function(name)(a1,a2,a3); + } + catch(e) + { + add_log(name+" "+e,colors.code_error); + log_trace("call_code_function "+name,e); + } + } + else + { + last_ccfunc=[name,a1,a2,a3]; + start_runner(0,"\nset_message('Snippet');\neval(parent.last_ccfunc[0])(parent.last_ccfunc[1],parent.last_ccfunc[2],parent.last_ccfunc[3])"); + } +} + +function call_code_function(name,a1,a2,a3) +{ + try{ + return get_code_function(name)(a1,a2,a3); + } + catch(e) + { + add_log(name+" "+e,colors.code_error); + log_trace("call_code_function "+name,e); + } +} + +function code_eval_if_r(code) +{ + code_active && document.getElementById("maincode") && document.getElementById("maincode").contentWindow && document.getElementById("maincode").contentWindow.eval && document.getElementById("maincode").contentWindow.eval(code); +} + +function get_code_function(name) +{ + return code_active && document.getElementById("maincode") && document.getElementById("maincode").contentWindow && document.getElementById("maincode").contentWindow[name] || (function(){}); +} + +function private_say(name,message,code) +{ + socket.emit("say",{message:message,code:code,name:name}); + return push_deferred("say"); +} + +function party_say(message,code) +{ + socket.emit("say",{message:message,code:code,party:true}); + return push_deferred("say"); +} + +var last_say="normal"; + +function say(message,code) +{ + message=""+message; + if(!message || !message.length) return; + last_say="normal"; + if(message[0]=="/") + { + message=message.substr(1,2000); + var components=message.split(" "),command=components.shift(),rest=components.join(" "); + if(command=="help" || command=="list" || command=="") + { + add_chat("","/list"); + add_chat("","/uptime"); + add_chat("","/guide"); + add_chat("","/learn"); + add_chat("","/docs"); + add_chat("","/codes"); + add_chat("","/invite NAME"); + add_chat("","/request NAME"); + add_chat("","/kick NAME"); + add_chat("","/friend NAME"); + add_chat("","/leave"); + add_chat("","/challenge"); + add_chat("","/whisper NAME MESSAGE"); + add_chat("","/p MESSAGE"); + add_chat("","/ping"); + add_chat("","/pause"); + add_chat("","/eval CODE"); + add_chat("","/snippet"); + add_chat("","/start CHARACTERNAME CODE(OPT.)"); + add_chat("","/stop CHARACTERNAME"); + add_chat("","/stop"); + add_chat("","/stop invis"); + add_chat("","/stop teleport"); + add_chat("","/disconnect"); + add_chat("","/disconnect CHARACTERNAME"); + if(is_electron) add_chat("","/new_window") + // add_chat("","/savecode /loadcode /runcode"); + } + else if(is_electron && (command=="new_window" || command=="window" || command=="newwindow")) + { + window.open(base_url,"",{width:$(window).width(),height:$(window).height()}); + } + else if(command=="start") + { + var args=rest.split(" "),name=args.shift(),code=args.shift(); + if(name) start_character_runner(name,code); + } + else if(command=="codes") + { + if(!is_electron) show_alert("Only works in game clients"); + else electron_open_codes(); + } + else if(command=="leave") + { + socket.emit("party",{event:"leave"}); + push_deferred("party"); + } + else if(command=="uptime") + { + add_chat("",to_pretty_num(parseInt(msince(inception)))+" minutes "+parseInt(ssince(inception)%60)+" seconds","gray"); + } + else if(command=="duel" || command=="challenge") + { + var args=rest.split(" "),name=args.shift(); + var target=xtarget||ctarget; + if(!name && target && target.name) socket.emit("duel",{event:"challenge",name:target.name}); + else if(name) socket.emit("duel",{event:"challenge",name:name}); + else add_chat("","No one to duel"); + } + else if(command=="stop") + { + var args=rest.split(" "),name=args.shift(); + if(!name) + { + use_skill("stop"); + } + else if(name=="teleport" || name=="town") + { + socket.emit("stop",{action:"town"}); + push_deferred("stop"); + } + else if(name=="revival") + { + socket.emit("stop",{action:"revival"}); + push_deferred("stop"); + } + else if(name=="invis") + { + socket.emit("stop",{action:"invis"}); + push_deferred("stop"); + } + else + { + stop_character_runner(name); + } + } + else if(command=="disconnect") + { + var args=rest.split(" "),name=args.shift(); + if(!name) window.location=base_url; + else + { + api_call("disconnect_character",{name:name}); + } + } + else if(command=="p") + { + party_say(rest); + } + else if(command=="pause") + { + pause(); + } + else if(command=="snippet") + { + show_snippet(); + } + else if(command=="eval" || command=="execute") + { + code_eval(rest); + } + else if(command=="pure_eval") + { + eval(rest); + } + else if(command=="w" || command=="whisper" || command=="pm") + { + var args=rest.split(" "),name=args.shift(),rest=args.join(" "); + if(!name || !rest) + { + add_chat("","Format: /w NAME MESSAGE"); + } + else + { + private_say(name,rest); + } + } + else if(command=="savecode") + { + var args=rest.split(" "),slot=args.shift(),name=args.join(" "); + if(slot.length && !parseInt(slot)) + { + add_chat("","/savecode NUMBER NAME"); + add_chat("","NUMBER can be from 1 to 100"); + } + else + { + if(!slot) slot=1; + api_call("save_code",{code:codemirror_render.getValue(),slot:slot,name:name}); + } + } + else if(command=="loadcode" || command=="runcode") + { + var args=rest.split(" "),name=args.shift(); + if(!name) name=1; + api_call("load_code",{name:name,run:(command=="runcode" && "1" || "")}); + } + else if(command=="ping") + { + ping(); + } + else if(command=="whisper") + { + var target=xtarget||ctarget; + if(target && !target.me && !target.npc && target.type=="character") private_say(target.name,rest); + else add_chat("","Target someone to whisper"); + } + else if(command=="party" || command=="invite") + { + var args=rest.split(" "),name=args.shift(); + var target=xtarget||ctarget; + if(name && name.length) socket.emit('party',{event:'invite',name:name}),push_deferred("party"); + else if(target && !target.me && !target.npc && target.type=="character") socket.emit('party',{event:'invite',id:target.id}),push_deferred("party"); + else add_chat("","Target someone to invite"); + } + else if(command=="kick") + { + var args=rest.split(" "),name=args.shift(); + var target=xtarget||ctarget; + if(name && name.length) socket.emit('party',{event:'kick',name:name}); + else if(target && !target.me && !target.npc && target.type=="character") socket.emit('party',{event:'kick',id:target.id}); + else add_chat("","Target someone to kick"); + } + else if(command=="request") + { + var args=rest.split(" "),name=args.shift(); + var target=xtarget||ctarget; + if(name && name.length) socket.emit('party',{event:'request',name:name}); + else if(target && !target.me && !target.npc && target.type=="character") socket.emit('party',{event:'request',id:target.id}); + else add_chat("","Target someone to request party"); + } + else if(command=="friend") + { + var args=rest.split(" "),name=args.shift(); + var target=xtarget||ctarget; + if(name && name.length) socket.emit("friend",{event:"request",name:name}),push_deferred("friend"); + else if(target && !target.me && !target.npc && target.type=="character") socket.emit("friend",{event:"request",name:target.name}),push_deferred("friend"); + else add_chat("","Target someone to friend"); + } + else if(command=="guide") + { + show_game_guide(); + } + else if(command=="learn") + { + render_code_articles(); + } + else if(command=="docs") + { + render_code_docs(); + } + else if(code_active && document.getElementById("maincode") && document.getElementById("maincode").contentWindow && document.getElementById("maincode").contentWindow.handle_command) + { + if(document.getElementById("maincode").contentWindow.handle_command(command,rest)!=-1); + else add_chat("","Command not found. You can add a `handle_command` function to your CODE to capture commands.") + } + else if(screenshot_mode && command=="p1") + { + add_chat("Wizard","Adventure Land is a 2D Pixel MMORPG","#D3C7A2"); + } + else if(screenshot_mode && command=="p2") + { + add_chat("Amazon","20% off on all Elixirs","gray"); + add_chat("Healer","Economy is completely Merchant-to-Merchant, players leave their merchants in the town square to sell or buy items","#58BCA5"); + } + else if(recording_mode && command=="r1") + { + ui_log("Item upgrade succeeded","white"); + ui_log("Item upgrade succeeded","white"); + ui_log("Item upgrade succeeded","white"); + ui_log("Item upgrade succeeded","white"); + // add_chat("Wizard","Higher monster hp means more gold from selling the drops, as calculations don't account for the hp based increase in drops","gray"); + add_chat("NewKid","hi","gray") + add_chat("Wizard","hello :)","gray"); + add_chat("","SweetPea received a Mittens +9","#85C76B"); + add_chat("","Maela found a Mistletoe","#85C76B"); + add_chat("","Trexnamedted found a Candy Cane","#85C76B"); + // add_chat("Wizard","gz :)","gray"); + } + else + { + add_chat("","Command not found. Suggestion: /list"); + } + } + else + { + socket.emit("say",{message:message,code:code}); + return push_deferred("say"); + } + return resolving_promise({command:true}); +} + +function join(event) +{ + // event can be one of show_json(Object.keys(G.events)) + socket.emit('join',{name:event}); + return push_deferred('join'); +} + +function activate(num) +{ + if(character.items[num] && character.items[num]) + { + socket.emit("booster",{num:num,action:"activate"}); + return push_deferred("booster"); + } + else + return rejecting_promise({reason:"no_item"}); +} + +function shift(num,to) +{ + socket.emit("booster",{num:num,action:"shift",to:to}); + return push_deferred("booster"); +} + +function open_merchant(num) +{ + socket.emit("merchant",{num:num}); + return push_deferred("merchant"); +} + +function close_merchant() +{ + socket.emit("merchant",{close:1}); + return push_deferred("merchant"); +} + +function donate(gold) +{ + if(gold===undefined) + { + var gold=parseInt($(".dgold").html().replace_all(",","")); + if(!gold) gold=100000; gold=max(1,gold); + } + socket.emit("donate",{gold:gold}); +} + +function dice(direction,num,gold) +{ + if(direction==1) direction="up"; + if(direction==2) direction="down"; + socket.emit("bet",{type:"dice",dir:direction,num:num,gold:gold}); +} + +function quantity(name,level) +{ + var q=0; + for(var i=0;i=i[0]) + { + items.push([k++,j]); + break; + } + } + }); + socket.emit('craft',{items:items}); + return push_deferred("craft"); + } +} + +var suppress_calculations=false; + +function upgrade(item,scroll,offering,code,calculate) +{ + if(!code && calculate && suppress_calculations) return; + if(!code && (item==null || (scroll==null && offering==null))) d_text("INVALID",character); + else + { + socket.emit("upgrade",{item_num:item,scroll_num:scroll,offering_num:offering,clevel:(character.items[item]&&character.items[item].level||0),calculate:calculate}); + last_uping=new Date(); + return push_deferred("upgrade"); + } +} + +function compound(item0,item1,item2,scroll,offering,code,calculate) +{ + if(!code && calculate && suppress_calculations) return; + if(!code && (item0==null || item1==null || item2==null || scroll==null)) d_text("INVALID",character); + else + { + socket.emit("compound",{items:[item0,item1,item2],scroll_num:scroll,offering_num:offering,clevel:(character.items[item0].level||0),calculate:calculate}); + return push_deferred("compound"); + } +} + +function lock_item(num) +{ + if(num===undefined) num=l_item; + socket.emit("locksmith",{num:num,operation:"lock"}); + return push_deferred("locksmith"); +} + +function seal_item(num) +{ + if(num===undefined) num=l_item; + socket.emit("locksmith",{num:num,operation:"seal"}); + return push_deferred("locksmith"); +} + +function unlock_item(num) +{ + if(num===undefined) num=l_item; + socket.emit("locksmith",{num:num,operation:"unlock"}); + return push_deferred("locksmith"); +} + +function deposit(amount) +{ + if(!G.maps[current_map].mount) { add_log("Not in the bank.","gray"); return rejecting_promise({reason:"not_in_bank"}); } + tut("deposit"); + if(!amount) amount=$(".npcgold").html()||""; + amount=amount.replace_all(",","").replace_all(".",""); + socket.emit("bank",{operation:"deposit",amount:parseInt(amount)}); + return push_deferred("bank"); +} + +function withdraw(amount) +{ + if(!G.maps[current_map].mount) { add_log("Not in the bank.","gray"); return rejecting_promise({reason:"not_in_bank"}); } + if(!amount) amount=$(".npcgold").html()||""; + amount=amount.replace_all(",","").replace_all(".",""); + socket.emit("bank",{operation:"withdraw",amount:parseInt(amount)}); + return push_deferred("bank"); +} + +var last_excanim=new Date(),exclast=0; +//var exccolors=["#ee4035","#f37736","#fdf498","#7bc043","#0392cf","#7bc043","#fdf498","#f37736"]; +// var exccolors=["#ee4035","#f37736","#fdf498","#7bc043","#0392cf"]; +//http://www.color-hex.com/color-palette/807 + +var exccolors1=["#f1c40f","#f39c12","#e74c3c","#c0392b","#8e44ad","#9b59b6","#2980b9","#3498db","#1abc9c"]; +var exccolorsl=["#CD6F1A","#A95C15"]; +var exccolorsg=["#EFD541","#9495AC"]; +var exccolorsgray=["#7C7C7C","#5C5D5D","#3B3C3C"]; +var exccolorsc=["#C82F17","#EBECEE"]; +var exccolorscosmo=["#CE667E","#91D489","#26BEEA","#61F129","#8990EB","#EBD411"]; +var exccolorssea=["#24A7CB","#EBECEE"]; + +function exchange_animation_logic() +{ + var exccolors=exccolors1; + if(character.q.exchange.qs=="leather") exccolors=exccolorsl; + if(character.q.exchange.qs=="lostearring") exccolors=exccolorsg; + if(character.q.exchange.qs=="seashell") exccolors=exccolorssea; + if(character.q.exchange.qs=="poof") exccolors=exccolorsgray; + if(character.q.exchange.name && character.q.exchange.name.startsWith("cosmo")) exccolors=exccolorscosmo; + if(in_arr(exchange_type,["mistletoe","ornament","candycane"])) exccolors=exccolorsc; + if(mssince(last_excanim)>300) + { + last_excanim=new Date(); + $('#eitem').children().css("border-color",exccolors[exclast%exccolors.length]); + $('.ering3').css("border-color",exccolors[(exclast+1)%exccolors.length]); + $('.ering2').css("border-color",exccolors[(exclast+2)%exccolors.length]); + $('.ering1').css("border-color",exccolors[(exclast+3)%exccolors.length]); + exclast++; + } +} + +var u_valid=false,last_uchance=null,last_uchance_for="upgrade_or_compound"; +function set_uchance(dchance,html) +{ + last_uchance=dchance; last_uchance_for=rendered_target; // retains calculations during reopen's [17/06/19] + if(dchance=="?") + { + $(".uchance").css("color","#299C4C"); + $(".uchance").html("%??.??"); + return; + } + if(parseInt(dchance*10000000000)) u_valid=true; + var chance=min(9999,(parseInt(dchance*10000)||0)),first=""+parseInt(chance/100),last=""+parseInt(chance%100); + chance=chance/100; + if(first.length==1) first="0"+first; + if(last.length==1) last="0"+last; + if(chance>95) color="#31C760"; + else if(chance>80) color="#259248"; + else if(chance>75) color="#56923B"; + else if(chance>60) color="#76922C"; + else if(chance>50) color="#8F8A23"; + else if(chance>40) color="#8E682D"; + else if(chance>30) color="#8E5744"; + else if(chance>20) color="#8E456A"; + else if(chance>10) color="#8E6087"; + else color="#AA3248"; + if(html) return [color,"%"+first+"."+last] + $(".uchance").css("color",color); + $(".uchance").html("%"+first+"."+last); +} + +var uroll_colors=["#f1c40f","#f39c12","#e74c3c","#c0392b","#8e44ad","#9b59b6","#2980b9","#3498db","#1abc9c"]; +var uroll_colors=["#868590"]; +var uroll_characters=["|","/","-","\\"],last_uc=0; +function set_uroll(def,rhtml) +{ + var c=uroll_characters[last_uc++%uroll_characters.length],color=0; + var html=""; + if(def.success) c="$",color="#49C528"; + if(def.failure) c="^",color="#9F1020"; + html+=""+c+""; + for(var i=3;i>=0;i--) + { + if(def.nums[i]!==undefined) html+=""+def.nums[i]+""; + else html+=""+parseInt(Math.random()*10)+""; + if(i==2) html+="."; + } + if(rhtml) return html; + $(".uroll").html(html); +} + +var last_companim=new Date(); +function compound_animation_logic() +{ + if(topleft_npc=="compound" && character.q.compound && character.items[character.q.compound.num] && character.items[character.q.compound.num].name=="placeholder") + { + var def=character.items[character.q.compound.num].p; + if(mssince(last_companim)>120) + { + last_companim=new Date(); + set_uroll(def); + } + } + if(character.map=="main" && Math.random()<0.4) random_spark({map:"main",x:G.maps.main.ref.c_mid[0]+5-Math.random()*10,y:G.maps.main.ref.c_mid[1]-Math.random()*6+1,'in':"main"},{color:"spark"}); +} + +var last_upganim=new Date(),last_uping=new Date(); +function upgrade_animation_logic() +{ + if(topleft_npc=="upgrade" && character.q.upgrade && character.items[character.q.upgrade.num] && character.items[character.q.upgrade.num].name=="placeholder") + { + var def=character.items[character.q.upgrade.num].p; + if(mssince(last_upganim)>120) + { + last_upganim=new Date(); + set_uroll(def); + } + } + if(character.map=="main" && Math.random()<0.4) random_spark({map:"main",x:G.maps.main.ref.u_mid[0]+5-Math.random()*10,y:G.maps.main.ref.u_mid[1]-Math.random()*6+1,'in':"main"},{color:"spark"}); +} + +setInterval(function(){ + if(window.character && !character.q.upgrade && topleft_npc=="upgrade" && u_valid && u_item!==null && u_scroll!==null && mssince(last_uping)>1600) upgrade(u_item,u_scroll,u_offering,null,true),last_uping=new Date(); +},1600); + +function poof(is_code) +{ + var delay=2400; + exchange_type="poof"; + if(is_code || 1) + { + socket.emit("destroy",{num:p_item,q:1,statue:true}); + return push_deferred("destroy"); + } + function poof_trigger(p_item) + { + return function(){ + if(!exchange_animations) return; + socket.emit("destroy",{num:p_item,q:1,statue:true}); + } + } + if(p_item==null) d_text("INVALID",character); + else if(exchange_animations) d_text("WAIT FOR IT",character); + else + { + exchange_animations=true; + draw_timeout(poof_trigger(p_item),delay); + } +} + +function exchange(is_code) +{ + if(character.q.exchange) + { + d_text("WAIT",character); + return rejecting_promise({reason:"in_progress"}); + } + else if(!is_code && e_item==null) + { + d_text("INVALID",character); + return rejecting_promise({reason:"invalid"}); + } + else + { + socket.emit("exchange",{item_num:e_item,q:character.items[e_item].q}); + return push_deferred("exchange"); + } +} + +function exchange_buy(token,name) +{ + var num=item_position(token); + if(num==undefined) + { + d_text("NO TOKENS",character); + return rejecting_promise({reason:"no_tokens"}); + } + else + { + socket.emit("exchange_buy",{num:num,name:name,q:character.items[num].q}); + return push_deferred("exchange_buy"); + } +} + +function craft() +{ + var items=[],j=false; + for(var i=0;i<9;i++) + { + if(cr_items[i] || cr_items[i]===0) j=true,items.push([i,cr_items[i]]); + } + if(!j) + { + d_text("INVALID",character); + return rejecting_promise({reason:"invalid"}); + } + else + { + socket.emit("craft",{items:items}); + return push_deferred("craft"); + } +} + +function dismantle() +{ + socket.emit("dismantle",{num:ds_item}); + return push_deferred("dismantle"); +} + +var u_retain=false,u_retain_t=false; +function reopen() +{ + if(options.retain_upgrades && u_item) u_retain=[u_item,u_scroll,u_offering]; + // u_offering=u_scroll=c_scroll=e_item=p_item=l_item=null; // so even if the fps is super-low, the upgrade won't trigger again + verified [14/08/16] + + draw_trigger(function(){ + var originals=[]; + if(rendered_target=="upgrade") originals=render_upgrade_shrine(); + else if(rendered_target=="compound") originals=render_compound_shrine(); + else if(rendered_target=="exchange") originals=render_exchange_shrine(exchange_type); + else if(rendered_target=="gold") render_gold_npc(); + else if(rendered_target=="items") render_items_npc(); + else if(rendered_target=="craftsman") render_craftsman(); + else if(rendered_target=="dismantler") render_dismantler(); + else if(rendered_target=="none") render_none_shrine(); + else if(rendered_target=="locksmith") render_locksmith(); + // else if(rendered_target=="secondhands") render_secondhands(); // Manual resets + if(inventory) reset_inventory(); + + suppress_calculations=true; var ocheck=false; + for(var i=0;i0) hide_modal(); + else if(code) toggle_code(); + else if(topright_npc) + { + $("#rightcornerui").html(''); + topright_npc=false; + } + else if(topleft_npc && topleft_npc!="dice") topleft_npc=false; + else if(xtarget) xtarget=null; + else if(ctarget && ctarget.type=="character") ctarget=null; + else if(inventory) draw_trigger(render_inventory); + else if(skillsui) draw_trigger(render_skills); + else if(topleft_npc=="dice") topleft_npc=false; + $(":focus").blur(); +} + +function toggle_stats() +{ + if(topright_npc!="character") render_character_sheet(); + else + { + $("#rightcornerui").html(''); + topright_npc=false; + } +} + +function toggle_character() +{ + // if(xtarget && xtarget==character) xtarget=null; + // else if(ctarget) topleft_npc=false,xtarget=character; + // else if(ctarget==character && !topleft_npc) ctarget=null; + // else topleft_npc=false,ctarget=character; + if(xtarget && xtarget==character) xtarget=null; + else if(ctarget==character && !topleft_npc) ctarget=null; + else topleft_npc=false,xtarget=character; +} + +function reset_inventory(condition) +{ + if(inventory) + { + if(condition && !in_arr(rendered_target,["upgrade","compound","exchange","npc","merchant","craftsman","dismantler","none","locksmith"])) return; + render_inventory(true); + } +} + +function close_chests() +{ + for(var id in chests) + { + var chest=chests[id]; + if(chest.openning) + { + delete chest.openning; + chest.frame=0; + set_texture(chest,chest.frame); + } + } +} + +function open_chest(id) +{ + var chest=chests[id]; + if(chest) + { + if(chest.openning && ssince(chest.openning)<5) return resolving_promise({sucess:false,in_progress:true,reason:"openning"});; + draw_trigger(function(){ + var chest=chests[id]; + if(chest && !chest.openning) + { + chest.openning=new Date(); + set_texture(chest,++chest.frame); + } + }); + } + socket.emit("open_chest",{id:id}); + return push_deferred("open_chest"); +} + +function generate_textures(name,stype) +{ + // console.log("generate_textures "+name+" "+stype); + if(in_arr(stype,["full","wings","body","armor","skin","upper","tail","character"])) + { + var d=XYWH[name],width=d[2],height=d[3],dx=0,dy=0,prefix="",dyh=0,col_num=3; + if(stype=="upper") prefix="upper",dyh=8; + var a=G.dimensions[name]; + if(a) + { + width=a[0]; height=a[1]; + dx=round((d[2]-width)/2.0+(a[2]||0)); + dy=round(d[3]-height); // +(a[3]||0) height-disp was never used, removed to simplify [20/07/18] + } + textures[prefix+name]=[[null,null,null,null],[null,null,null,null],[null,null,null,null]]; + if(stype=="tail") col_num=4,textures[prefix+name].push([null,null,null,null]); + for(var i=0;i1) + { + var s1=new PIXI.Sprite(def[0]); + s1.textures=def; + return s1; + } + return new PIXI.Sprite(def[0]); +} + +function random_rotating_rectangle(entity,args) +{ + if(no_graphics) return; + if(!entity.cxc.bg) return; + if(!args) args={}; + var e=new PIXI.Graphics(); + var colors=[0x00F33E,0xF4212B,0xF8F837,0x517DF8,0xE14BF9,0x1EA4F9,0x6E1CF9,0xF7722D]; + if(args.color=="success") colors=[0x85C76B,0xADFF8B,0xEEFCEF]; + else if(args.color=="purple") colors=[0x9944C8,0x7C38A3,0xF4DAFF]; + var color=random_one(colors); + var size=random_one([3,5,7]),x_step=random_one([1,-1,2,-2]),y_step=random_one([-0.5,0,1,2,3]),r_step=random_one([-0.2,0.2,-0.4,0.4]); + e.lineStyle(3,color); + e.beginFill(color); + e.drawRect(-size/2,-size/2,size/2,size/2); + e.rotation=Math.random(); + var filter=new PIXI.filters.PixelateFilter(7,7); + e.filters=[filter]; + e.x=0; + e.y=-15; + entity.cxc.bg.addChild(e); + function animate(step,x_step,y_step,r_step) + { + return function(){ + if(step>=10.6) + { + destroy_sprite(e); + } + else + { + //console.log(DTM); + e.x-=x_step*DTM*2; + e.y-=y_step*DTM*2; + e.rotation-=r_step*DTM; + e.opacity-=0.07*DTM; + draw_timeout(animate(step+DTM,x_step,y_step,r_step),15); + } + } + } + draw_timeout(animate(0,x_step,y_step,r_step),15); +} + +function random_spark(coord,args) +{ + if(no_graphics) return; + if(!args) args={}; + var e=new PIXI.Graphics(); + var colors=[0x00F33E,0xF4212B,0xF8F837,0x517DF8,0xE14BF9,0x1EA4F9,0x6E1CF9,0xF7722D]; + if(args.color=="success") colors=[0x85C76B,0xADFF8B,0xEEFCEF]; + else if(args.color=="purple") colors=[0x9944C8,0x7C38A3,0xF4DAFF]; + else if(args.color=="spark") colors=[0xFAFCE5,0xFCFCF3,0xFBC993,0xC4FFE2]; + else if(args.color=="blue") colors=[hx("#477FDD"),hx("#86AEDD"),hx("#2F52DD")]; + var color=random_one(colors); + var size=0.2,x_step=random_one([0.25,0.5,0,-0.25,-0.5]),y_step=random_one([0.25,0.5,0.75]),a_map=current_map; + e.lineStyle(3,color); + e.beginFill(color); + e.drawRect(-size/2,-size/2,size/2,size/2); + //var filter=new PIXI.filters.PixelateFilter(7,7); + //e.filters=[filter]; + e.x=coord.x; + e.y=coord.y; + e.alpha=args.alpha||0.25; + if(use_layers) e.parentGroup=player_layer; + else e.displayGroup=player_layer; + map.addChild(e); + function animate(step,x_step,y_step) + { + return function(){ + if(step>=20.6 || a_map!=current_map) + { + destroy_sprite(e); + } + else + { + //console.log(DTM); + e.x-=x_step*DTM*2; + e.y-=y_step*DTM*2; + e.height+=0.01*DTM; + e.width+=0.01*DTM; + e.alpha-=0.01*DTM; + draw_timeout(animate(step+DTM,x_step,y_step),15); + } + } + } + draw_timeout(animate(0,x_step,y_step),15); +} + +function weather_animation(type,args) +{ + if(!args) args={}; + var entity=new_sprite(type,"animation"); + entity.real_x=entity.x=args.x||0; + entity.real_y=entity.y=args.y||0; + entity.stype="animation"; + entity.atype="wmap"; + entity.last=0; + entity.last_update=new Date(); + entity.interval=120; + entity.parentGroup=entity.displayGroup=weather_layer; + entity.id=randomStr(8); + entity.y_disp=0; + map.addChild(entity); + map_animations[entity.id]=entity; +} + +function small_success(entity,args) +{ + for(var j=0;j<4;j++) + for(var i=0;i<30;i++) + { + draw_timeout(function(){ random_rotating_rectangle(entity,args); },i*16); + } +} + +function assassin_smoke(x,y,type) +{ + if(!type) type="explode_p"; + var d_height=1,d_width=1,d_y=3,interval=40,steps=12,d_x=0,a_map=current_map; + if(type=="firecrackers") + { + type="crackle",d_height=1.5,d_width=1.5,interval=16,d_y=1,steps=6; + var rx=Math.random(); + if(rx<0.3) d_x=0.5; + if(rx>0.7) d_x=-0.5; + if(rx<0.25) draw_timeout(function(){sfx("crackle0")},rx*40); + else if(rx>0.75) draw_timeout(function(){sfx("crackle1")},rx*40); + } + var sprite=new_sprite(type,"animation"); + if(use_layers) sprite.parentGroup=player_layer; + else sprite.displayGroup=player_layer; + sprite.x=round(x); + sprite.y=round(y); + sprite.real_x=x; + sprite.real_y=y+1; + if(type=="explode_p") + { + sprite.width=16; + sprite.height=16; + } + sprite.anchor.set(0.5,1); + map.addChild(sprite); + function assassin_smoke(step) + { + return function(){ + if(step>=steps || a_map!=current_map) + { + destroy_sprite(sprite); + } + else + { + sprite.x-=d_x; + sprite.y-=d_y; + sprite.height+=d_height; + sprite.width+=d_width; + sprite.frame++; + set_texture(sprite,sprite.frame); + draw_timeout(assassin_smoke(step+1),interval); + } + } + } + draw_timeout(assassin_smoke(1),interval); +} + +function confetti_shower(entity,level) +{ + if(!entity) return; + var interval=200,count=1,times=25,a_map=current_map; + if(level==2) interval=150,count=2,times=60; + if(is_hidden()) times=2; + for(var i=0;i=steps || a_map!=current_map) + { + destroy_sprite(sprite); + } + else + { + //sprite.x-=d_x; + //sprite.y-=d_y; + sprite.height+=d_height; + sprite.width+=d_width; + sprite.frame++; + set_texture(sprite,sprite.frame); + draw_timeout(egg_s(step+1),interval); + } + } + } + draw_timeout(egg_s(1),interval); +} + +function start_emblem(sprite,name,args) +{ + if(!args) args={}; + if(sprite.emblems[name]) { sprite.emblems[name].frames=args.frames||225; return; } + var esprite=new_sprite(name,"emblem"); + if(args.no_dip) esprite.frame_list=[0.57,0.60,0.63,0.66,0.69,0.72,0.75,0.78,0.82,0.86,0.90,0.95,1]; + else esprite.frame_list=[0.2,0.33,0.66,0.77,0.88,0.95,1]; + for(var i=esprite.frame_list.length-1;i>=0;i--) esprite.frame_list.push(esprite.frame_list[i]); + esprite.frame_list + sprite.emblems[name]=esprite; + esprite.frames=args.frames||225; + esprite.x=-0.5; + esprite.y=-6; + esprite.anchor.set(0.5,0.5); + esprite.parentGroup=animation_layer; + esprite.alpha=0.33; + sprite.addChild(esprite); +} + +function stop_emblem(sprite,name) +{ + if(sprite.emblems[name]) sprite.emblems[name].frames=0; +} + +function start_animation(sprite,name,mode) +{ + if(no_graphics) return; + if(sprite.animations[name]) { sprite.animations[name].frame=0; return } + var asprite=new_sprite(name,"animation"),width=(sprite.hitArea && sprite.hitArea.width || sprite.texture.width),height=(sprite.hitArea && sprite.hitArea.height || sprite.texture.height); + var def=G.animations[name]; + sprite.animations[name]=asprite; + if(def.alpha) asprite.alpha=def.alpha; + else asprite.alpha=0.5; + if(mode=="stun") + { + asprite.continuous=true; + asprite.width=round(width*2/3.0); + asprite.height=round(height/3); + asprite.y=-height+8; + } + if(def.continuous) asprite.continuous=true; + if(def.exact); + else if(def.bubble) + { + def.y=27; + } + else if(def.continuous) + { + asprite.height=round(height*0.95); + } + else if(def.proportional) + { + if(1.0*asprite.height*width/asprite.width>height) + { + asprite.height=height; + asprite.width=ceil(1.0*asprite.width*height/asprite.height); + } + else + { + asprite.height=ceil(1.0*asprite.height*width/asprite.width); + asprite.width=sprite.width; + } + } + else if(def.size) + { + asprite.width=round(width*def.size); + asprite.height=round(height*def.size); + } + else + { + asprite.width=width; + asprite.height=height; + } + if(name=="revival") + { + asprite.height=sprite.texture.height; + asprite.width=sprite.texture.width; + } + if(def.speeding) asprite.speeding=true; + if(def.front) asprite.y_disp=-30; + if(def.y) asprite.y=-def.y; + asprite.zy=1200; + asprite.aspeed=def.aspeed; + asprite.aspeed=(asprite.aspeed=="fast"&&0.8)||(asprite.aspeed=="mild"&&1.4)||(asprite.aspeed=="slow"&&3)||2 + asprite.anchor.set(0.5,1); + sprite.addChild(asprite); +} + +function map_animation(name,args) +{ + if(no_graphics) return; + if(!args) args={}; + var asprite=null; + if(args.item) asprite=new_sprite(name,"item"); + else asprite=new_sprite(name,"animation"); + var width=asprite.width,height=asprite.height; + var def=G.animations[name]||{}; + asprite.atype="map"; + asprite.continuous=true; + asprite.speeding=true; + asprite.aspeed=def.aspeed; + asprite.aspeed=(asprite.aspeed=="fast"&&0.8)||(asprite.aspeed=="mild"&&1.4)||(asprite.aspeed=="slow"&&3)||2 + asprite.anchor.set(0.5,0.5); + if(def.front) asprite.y_disp=-30; + asprite.parentGroup=asprite.displayGroup=player_layer; + asprite.anchor.set(0.5,1); + asprite.x=args.x||0; + asprite.y=args.y||0; + asprite.m=args.m||0; + asprite.limit=args.limit||16; + asprite.framefps=def.framefps||15; + asprite.last_frame=new Date(); + asprite.last_update=new Date(); + asprite.id=args.id||randomStr(8); + if(def.directional) asprite.directional=true; + asprite.speed=args.speed||def.speed||10; + asprite.to_fade=(args.fade===true&&0.025)||args.fade; + if(args.filter) asprite.filters=[args.filter]; + if(args.scale||def.scale) asprite.scale.set(args.scale||def.scale,args.scale||def.scale); + if(args.target) + { + asprite.target=args.target; + asprite.going_x=get_x(args.target); + asprite.going_y=get_y(args.target)-get_height(args.target)/2; + if(point_distance(asprite.x,asprite.y,asprite.going_x,asprite.going_y)<100) asprite.speed*=0.75; + } + map_animations[asprite.id]=asprite; + map.addChild(asprite); +} + +function continuous_map_animation(name,origin,target) +{ + if(no_graphics) return; + var asprite=new_sprite(name,"animation"),width=asprite.width,height=asprite.height; + var def=G.animations[name]; + asprite.atype="cmap"; + asprite.anchor.set(0.5,0.5); + asprite.zy=12000; + asprite.parentGroup=asprite.displayGroup=player_layer; + asprite.id=randomStr(8); + if(def.directional) asprite.directional=true; + asprite.speed=def.speed; + asprite.x=(get_x(origin)+get_x(target))/2; + asprite.y=(get_y(origin)-get_height(origin)/2+get_y(target)-get_height(target)/2)/2; + asprite.height=distance(origin,target); + asprite.origin=origin; + asprite.target=target; + asprite.last_update=new Date(); + map_animations[asprite.id]=asprite; + map.addChild(asprite); +} + + +function stop_animation(sprite,name) +{ + var anim=sprite.animations[name]; + if(!anim) return; + var parent=anim.parent; + if(!parent) return; + destroy_sprite(anim); + delete parent.animations[name]; +} + +function set_base_rectangle(e) +{ + var rectangle=e.texture.frame; + e.base_rectangle=new PIXI.Rectangle(rectangle.x,rectangle.y,rectangle.width,rectangle.height); +} + +function dirty_fix(sprite) +{ + return; + // if(ssince(inception)<10) return; + var r=sprite.texture.frame; + sprite.texture=new PIXI.Rectangle(r.x,r.y+8,r.width,r.height); +} + +function restore_base(e) +{ + var base=e.base_rectangle; + e.texture.frame=new PIXI.Rectangle(base.x,base.y,base.width,base.height); +} + +function rotate(sprite,num) +{ + //reference: http://pixijs.github.io/examples/index.html?s=demos&f=texture-rotate.js&title=Texture%20Rotate&v=dev + var D8 = PIXI.GroupD8,texture=sprite.texture; + var h = D8.isSwapWidthHeight(num)?texture.frame.width:texture.frame.height; + var w = D8.isSwapWidthHeight(num)?texture.frame.height:texture.frame.width; + + var frame=texture.frame; + var crop=new PIXI.Rectangle(0,0, w, h); + var trim=crop; + if(num%2==0) + { + var rotatedTexture=new PIXI.Texture(texture.baseTexture, frame, crop, trim, num); + } + else + { + var rotatedTexture=new PIXI.Texture(texture.baseTexture, frame, crop, trim, num-1); + rotatedTexture.rotate++; + } + sprite.texture=rotatedTexture; +} + +function rotated_texture(base_texture,frame,num) +{ + if(!num) return new PIXI.Texture(base_texture, frame); + //reference: http://pixijs.github.io/examples/index.html?s=demos&f=texture-rotate.js&title=Texture%20Rotate&v=dev + var D8 = PIXI.GroupD8; + var h = D8.isSwapWidthHeight(num)?frame.width:frame.height; + var w = D8.isSwapWidthHeight(num)?frame.height:frame.width; + + var crop=new PIXI.Rectangle(0,0, w, h); + var trim=crop; + if(num%2==0) + { + var rotatedTexture=new PIXI.Texture(base_texture, frame, crop, trim, num); + } + else + { + var rotatedTexture=new PIXI.Texture(base_texture, frame, crop, trim, num-1); + rotatedTexture.rotate++; + } + return rotatedTexture; +} + +function drag_logic() +{ + +} + +function draw_timeouts_logic(mode) +{ + var start=new Date(),to_delete=[]; + for(var i=0;i=timeout[1]) + { + DTM=1; + DMS=start-timeout[3]; + if(timeout[4]) + try{ + DTM=(start-timeout[3])/timeout[4]; + }catch(e){} + to_delete.push(i); + try{ timeout[0](); } + catch(e){ console.log('draw_timeout_error: '+e); console.log('code: '+timeout[0]); console.log(e.stack);} + } + } + if(to_delete) delete_indices(draw_timeouts,to_delete); +} + +function draw_timeout(f,ms,important) +{ + draw_timeouts.push([f,future_ms(ms),important,new Date(),ms]); +} + +function draw_trigger(f) +{ + if(in_draw) + { + try{ f(); } + catch(e){ console.log('draw_trigger_error: '+e); console.log('code: '+f); console.log(e.stack);} + } + else draw_timeouts.push([f,new Date(),2,new Date(),0]); +} + +function tint_logic() +{ + var start=new Date(),to_delete=[]; + for(var i=0;itint.end) + { + $(tint.selector).parent().find("img").css("opacity",1); + to_delete.push(i); + $(tint.selector).css("height","0px").css("background-color","rgb("+r+","+g+","+b+")"); + } + else + { + if(!tint.added) + { + $(".skidloader"+tint.skid).parent().find("img").css("opacity",0.5); + tint.added=true; + $(tint.selector).css("height","1px"); + } + var since=mssince(tint.start),to=-mssince(tint.end); + var height=2*46*since/(since+to+1),ratio=since/(since+to+1); + $(tint.selector).css("background-color","rgb("+round(r+(rr-r)*ratio)+","+round(g+(gg-g)*ratio)+","+round(b+(bb-b)*ratio)+")"); + $(tint.selector).css({ + //"height":"1px", + "-webkit-transform":"scaleY("+height+")", + "-moz-transform":"scaleY("+height+")", + "-ms-transform":"scaleY("+height+")", + "-o-transform":"scaleY("+height+")", + "transform":"scaleY("+height+")", + }); + } + } + else if(tint.type=="progress") // copy-paste of "selector" [14/06/19] + { + if(tint.compound) r=50,g=163,b=204,rr=70,gg=183,bb=244; + else if(tint.upgrade) rr=41,gg=156,bb=76,r=254,g=183,b=42; + else if(tint.upgrade) r=254,g=183,b=42,rr=255,gg=209,bb=9; + else r=200,g=200,b=200,rr=250,gg=250,bb=250; + if(start>tint.end) + { + //$(tint.selector).parent().find("img").css("opacity",1); + to_delete.push(i); + $(tint.selector).css("height","0px").css("background-color","rgb("+r+","+g+","+b+")"); + } + else + { + if(!tint.added) + { + //$(tint.selector).parent().find("img").css("opacity",0.5); + tint.added=true; + $(tint.selector).css("height","1px"); + } + var since=mssince(tint.start),to=-mssince(tint.end); + var height=2*46*since/(since+to+1),ratio=since/(since+to+1); + $(tint.selector).css("background-color","rgb("+round(r+(rr-r)*ratio)+","+round(g+(gg-g)*ratio)+","+round(b+(bb-b)*ratio)+")"); + $(tint.selector).css({ + //"height":"1px", + "-webkit-transform":"scaleY("+height+")", + "-moz-transform":"scaleY("+height+")", + "-ms-transform":"scaleY("+height+")", + "-o-transform":"scaleY("+height+")", + "transform":"scaleY("+height+")", + }); + } + } + else if(tint.type=="dissipate") + { + if(start>tint.end) + { + $(tint.selector).parent().css("background","black"); + to_delete.push(i); + } + else + { + var r=tint.r,g=tint.g,b=tint.b,steps=20; + if(tint.itint.end) + { + if(tint_c[tint.key]==tint.cur || 1) + { + $(tint.selector).children(".thetint").remove(); + $(tint.selector).css("background",tint.reset_to); + } + to_delete.push(i); + } + else + { + if(tint_c[tint.key]!=tint.cur && 0) continue; + if(!tint.added) + { + tint.added=true; + $(tint.selector).children(".thetint").remove(); + $(tint.selector).append("
") + } + var since=mssince(tint.start),to=-mssince(tint.end); + //console.log(to); + var height=60.1*since/(since+to+1); + // height=max(0,min(60,height)); + // $(tint.selector).children(".thetint").css("height",height+"px"); + $(tint.selector).children(".thetint").css({ + "-webkit-transform":"scaleY("+height+")", + "-moz-transform":"scaleY("+height+")", + "-ms-transform":"scaleY("+height+")", + "-o-transform":"scaleY("+height+")", + "transform":"scaleY("+height+")", + }); + } + } + else if(tint.type=="fill") + { + if(start>tint.end) + { + //console.log("end"); + tint.type="glow"; // #GTODO: Glow once + $(tint.selector).css("background",tint.reset_to); + if(tint.on_end) tint.on_end(); + to_delete.push(i); + } + else + { + var since=mssince(tint.start),to=-mssince(tint.end); + //console.log(to); + var percentage=round(100.0*since/(since+to+1)); + if(tint.reverse) percentage=100-percentage; + percentage=max(1,percentage); + $(tint.selector).css("background","-webkit-gradient(linear, "+tint.start_d+", "+tint.end_d+", from("+tint.color+"), to("+tint.back_to+"), color-stop("+(percentage-1)+"%,"+tint.color+"),color-stop("+percentage+"%, "+tint.back_to+")"); + } + } + else if(tint.type=="glow") + { + + } + else if(tint.type=="half") + { + $(tint.selector).css("background","-webkit-gradient(linear, left top, right top, from(#f0f), to(#0f0), color-stop(49%,#f0f),color-stop(50%, #0f0)"); + } + } + if(to_delete) delete_indices(tints,to_delete); +} + +function get_tint(selector) +{ + for(var i=0;i=0;i--) + { + var current=character.items[i]; + if(!current) continue; + if(done) break; + var def=G.items[current.name]; + (def.gives||[]).forEach(function(p){ + if(p[0]==item && p[1]>0 && !done){ + socket.emit("equip",{num:i}); + done=push_deferred("equip"); + } + }); + } + if(!done) + { + socket.emit("use",{item:item}); + return push_deferred("use"); + } + return done; +} + +var tint_c={"a":0,"p":0,"t":0}; +var next_attack=new Date(),next_potion=new Date(); // backwards compatibility + +function attack_timeout_animation(ms) +{ + // if(ms<=0) return; // [09/09/22] 0's are valid now, for corrections + // #6E6E6E is the ~best gray shade + //var original=$(".atint").css("background"); + draw_trigger(function(){ + $(".atint").css("background","none"); + tint_c.a++; + add_tint(".atint",{ms:-mssince(next_skill.attack)-DMS,color:"#4C4C4C",reset_to:"#6A6A6A",type:"brute",key:"a",cur:tint_c.a}); //start_d:"left top",end_d:"left bottom", + }); +} + +function pot_timeout(ms) +{ + // if(ms<=0) return; // [09/09/22] 0's are valid now, for corrections + if(ms===undefined) ms=2000; + next_potion=future_ms(ms); + skill_timeout("use_hp",ms); + skill_timeout("use_mp",ms); + //add_tint(".hpui",{ms:ms,color:"#9A9A9A",reverse:1}); + //add_tint(".mpui",{ms:ms,color:"#9A9A9A",reverse:1}); + // add_tint(".ptint",{ms:ms,color:"#5F346E",reverse:1}); + //var original=$(".ptint").css("background"); + draw_trigger(function(){ + if(!get_tint(".ptint")) $(".ptint").css("background","none"); + tint_c.p++; + add_tint(".ptint",{ms:-mssince(next_skill.use_hp)-DMS,color:"#4C4C4C",reset_to:"#6A6A6A",type:"brute",key:"p",cur:tint_c.p}); + }); +} + +function pvp_timeout(ms,me) +{ + if(ms<=0) return; + skill_timeout("use_town",ms); + if(me) return; + draw_trigger(function(){ + $(".pvptint").parent().css("background","rgb(200,50,20)"); + for(var i=1;i<10;i++) + { + var r=200-i*15,g=50-i*3,b=20-i; + draw_timeout(function(r,g,b){ return function(){ $(".pvptint").parent().css("background","rgb("+r+","+g+","+b+")");} }(r,g,b),i*600); + } + 0 && draw_timeout(function(){ + $(".pvptint").parent().css("background","black"); + $(".pvptint").css("background","#907B81"); + tint_c.t++; + add_tint(".pvptint",{ms:-mssince(next_skill.use_town)-DMS,color:"black",reset_to:"none",type:"brute",key:"t",cur:tint_c.t,pos:"top"}); + },200); + }); +} + +function pvp_timeout(ms,event) +{ + if(ms<=0) return; + var r=200,g=50,b=20; + if(event=="sneak") r=45,g=111,b=45; // didn't work out well + skill_timeout("use_town",ms); + if(event==1) return; // 1=me + draw_trigger(function(){ + $(".pvptint").parent().css("background","rgb("+r+","+g+","+b+")"); + tint_c.t++; + add_tint(".pvptint",{ms:-mssince(next_skill.use_town)-DMS,r:r,g:g,b:b,type:"dissipate",key:"t",cur:tint_c.t,i:0}); + }); +} + +var next_skill={"attack":new Date(),use_hp:new Date(),use_mp:new Date(),use_town:new Date()}; +function skill_timeout_singular(name,ms) +{ + // console.log([name,ms]); + if(ms<=0) ms=0; + var skids=[]; + if(ms===undefined && (G.skills[name].cooldown||G.skills[name].reuse_cooldown)!==undefined) ms=G.skills[name].cooldown||G.skills[name].reuse_cooldown; + else if(ms===undefined && G.skills[name].share) ms=G.skills[G.skills[name].share].cooldown*(G.skills[name].cooldown_multiplier||1); + else if(name=="attack" && ms===undefined) ms=1000.0/character.frequency; + next_skill[name]=future_ms(ms||0); + if(name=="attack") next_attack=next_skill[name]; + //add_tint(".hpui",{ms:ms,color:"#9A9A9A",reverse:1}); + //add_tint(".mpui",{ms:ms,color:"#9A9A9A",reverse:1}); + // add_tint(".ptint",{ms:ms,color:"#5F346E",reverse:1}); + //var original=$(".ptint").css("background"); + for(var N in keymap) + if(keymap[N] && (keymap[N]==name || keymap[N].name==name)) skids.push(N); + draw_trigger(function(){ + if(name=="attack") attack_timeout_animation(-mssince(next_skill[name])-DMS); + skids.forEach(function(skid){ + add_tint(".skidloader"+skid,{ms:-mssince(next_skill[name])-DMS,type:"skill",skid:skid}); + }); + }); +} + +function restart_skill_tints() +{ + if(0) + { + var skids=[]; + for(var N in keymap) + if(keymap[N] && (keymap[N]==name || keymap[N].name==name)) skids.push(N); + for(var name in next_skill) + { + if(-mssince(next_skill[name])>0) + { + draw_trigger(function(){ + skids.forEach(function(skid){ + add_tint(".skidloader"+skid,{ms:-mssince(next_skill[name]),type:"skill",skid:skid}); + }); + }); + } + } + } + if(1) + tints.forEach(function(tint){ + if(tint.skid) + { + $(".skidloader"+tint.skid).parent().find("img").css("opacity",0.5); + $(tint.selector).css("height","1px"); + } + }); +} + +function skill_timeout(name,ms) +{ + if(G.skills[name].share) + { + skill_timeout_singular(G.skills[name].share,ms); + for(var s in G.skills) + if(G.skills[s].share==G.skills[name].share) + skill_timeout_singular(s,ms); + } + else if((G.skills[name].cooldown||G.skills[name].reuse_cooldown)!==undefined || name=="attack") + skill_timeout_singular(name,ms); +} + +function disappearing_circle(x,y,size,args) +{ + if(!args) args={}; + if(!args.color) args.color=0xFFFFFF; + var sprite=new PIXI.Graphics(); + sprite.beginFill(args.color); + sprite.drawCircle(x,y,size); + sprite.endFill(); + sprite.pivot=new PIXI.Point(0.5,0.5); + sprite.alpha=args.alpha||1; + map.addChild(sprite); + function d_circle(step) + { + return function(){ + if(step>=10) + { + destroy_sprite(sprite); + } + else + { + //sprite.x-=3; + //sprite.y-=3; + //sprite.width+=3; + //sprite.height+=3; + //sprite.scale.x+=0.2; + //sprite.scale.y+=0.2; + sprite.alpha-=0.03; + draw_timeout(d_circle(step+1),40); + } + } + } + draw_timeout(d_circle(1),40); +} + +function empty_rect(x,y,width,height,size,color) +{ + if(!color) color=0x886C37; + if(!size) size=1; + if(!width) width=1; + if(!height) height=1; + e=new PIXI.Graphics(); + e.lineStyle(size, color); + e.drawPolygon([x,y,x,y+height,x+width,y+height,x+width,y,x,y]); + return e; +} + +function draw_crosshair(x,y,size,color) +{ + if(!color) color=0xFF2335; + if(!size) size=1; + e=new PIXI.Graphics(); + e.lineStyle(1.5, color); + e.moveTo(x-size,y); + e.lineTo(x+size,y); + e.moveTo(x,y-size); + e.lineTo(x,y+size); + e.endFill(); + return e; +} + +function draw_xhair(x,y,size,color) +{ + if(!color) color=0xFF2335; + if(!size) size=1; + e=new PIXI.Graphics(); + e.lineStyle(1.5, color); + e.moveTo(x-size,y-size); + e.lineTo(x+size,y+size); + e.moveTo(x+size,y-size); + e.lineTo(x-size,y+size); + e.endFill(); + return e; +} + +function draw_line(x,y,x2,y2,size,color) +{ + if(!color) color=0xFF2335; + if(!size) size=1; + e=new PIXI.Graphics(); + e.lineStyle(size, color); + e.moveTo(x,y); + e.lineTo(x2,y2); + e.endFill(); + return e; +} + +function draw_circle(x,y,size,color) +{ + if(!color) color=0xFF2335; + if(!size) size=1; + e=new PIXI.Graphics(); + e.beginFill(color); + e.drawCircle(x,y,size); + e.endFill(); + return e; +} + +function add_border(element,width,height) +{ + if(!width) width=(element.texture.width),height=(element.texture.height); + var e=new PIXI.Graphics(); + e.lineStyle(1,0xFEB222); + e.drawRect(0,0,width,height); + if(element.anchor) + { + e.x=-element.anchor.x*width; + e.y=-element.anchor.y*height; + } + if(element.hitArea && (element.hitArea.width!=width || element.hitArea.height!=height)) + { + var b=new PIXI.Graphics(); + b.lineStyle(1,0x84D5FF); + b.drawRect(0,0,element.hitArea.width,element.hitArea.height); + if(element.anchor) + { + b.x=-element.anchor.x*element.hitArea.width + b.y=-element.anchor.y*element.hitArea.height; + } + element.bborder=b; + element.addChild(b); + } + if(element.base) + { + var c=new PIXI.Graphics(); + c.lineStyle(1,0x54AFFF); + c.drawRect(0,0,element.base.h*2,element.base.v+element.base.vn); + if(element.anchor) + { + c.x=-element.anchor.x*(element.base.h*2); + c.y=-element.anchor.y*(element.base.v+element.base.vn); + } + c.y+=element.base.vn; + element.cborder=c; + element.addChild(c); + } + element.aborder=e; + element.addChild(e); +} + +function border_logic(element) +{ + if(element.aborder) return; + if(element.aborder) + { + destroy_sprite(element.aborder); element.aborder=null; + } + if(element.bborder) + { + destroy_sprite(element.bborder); element.bborder=null; + } + if(element.cborder) + { + destroy_sprite(element.cborder); element.cborder=null; + } + add_border(element); +} + +function player_rclick_logic(element) +{ + if(!character || element.me) return; + var add=false; + if(element.npc) add=true; + else if(character.ctype=="priest" || character.slots.mainhand && character.slots.mainhand.name=="cupid") add=true; // maybe disable when the target is full hp + else + { + if(!pvp); + else if(pvp) add=true; //attack + } + + if(add && !element.on_rclick) + { + element.on_rclick=true; + element.on("rightdown",player_right_click); + } + else if(!add && element.on_rclick) + { + element.on_rclick=false; + element.removeListener("rightdown"); + } +} + +function regather_filters(entity) +{ + var filters=[]; + for(var p in entity) if(p.startsWith("cfilter_")) filters.push(entity[p]); + entity.filters=filters; +} + +function rip_logic() +{ + if(character.rip && !rip) + { + if(code_run) + { + call_code_function("trigger_event","death",{id:character.id}); + call_code_function("trigger_character_event","death",{}); + } + rip=true; character.i=1; character.j=0; + if(!no_graphics) + { + var filter=new PIXI.filters.ColorMatrixFilter(); + filter.desaturate(); + stage.cfilter_rip=filter; + regather_filters(stage); + } + character.moving=false; + $("#ripbutton").show(); + skill_timeout('use_town',12000); + reopen(); + $("#name").css("color","#5E5D5D"); + + } + if(!character.rip && rip) + { + rip=false; + delete stage.cfilter_rip; + regather_filters(stage); + $("#ripbutton").hide(); + $("#name").css("color","#1AC506"); + } +} + +function name_logic(element) +{ + if(no_graphics) return; + if(element.type!="character" && element.type!="npc") return; + if((!options.show_names && !(options.always_hpn || options.always_names) && (mtarget||xtarget||ctarget)!=element && character) && element.name_tag) //show_names + { + destroy_sprite(element.name_tag,"children"); element.name_tag=null; element.ntag_cache=null; + } + else if(options.show_names || !character || options.always_hpn || options.always_names || (mtarget||xtarget||ctarget)==element) // && !element.name_tag - added ntag_cache [06/12/16] + { + add_name_tag(element); + } +} + +// #TODO: Apply manually: https://github.com/pixijs/pixi.js/pull/4833/files [30/11/18] +// Next level: also round every name tag when the character itself is moving + +function start_name_tag(element) +{ + var value=false; + if(!element.moving || element.me) value=true; + if(element.name_tag && element.name_tag.roundPixels!=value) + { + element.name_tag.roundPixels=value; + if(element.name_tag.children) + element.name_tag.children.forEach(function(c){ + c.roundPixels=value; + }); + } +} + +function stop_name_tag(element) +{ + start_name_tag(element) +} + +function add_name_tag_old(element) +{ + var ntag_cache=element.name+"|"+element.level; + if(element.name_tag) + { + if(element.ntag_cache==ntag_cache) return; + destroy_sprite(element.name_tag,"children"); element.name_tag=null; element.ntag_cache=null; + } + var bordered_rectangle=new PIXI.Graphics(); + var name=("Lv."+element.level+" ")+element.name,border_color=0x716D6C,width=name.length*4+4,height=11; + if(element.npc && (element.type=="npc" || G.npcs[element.npc])) + { + name=element.name||"NPC"; + border_color=0x26A1CD; + if(element.citizen) border_color=0xD87F06; + width=name.length*4+8; + } + if(element.role=="gm") + border_color=0xE6A32F; + + var multiplier=1,offset=0; + if(!element.me) multiplier=4; + else multiplier=4; // Previously 8, "Business" was always rendering bad, so trying 2 [06/08/18] + + var fp={fontFamily:SZ.font,fontSize:8*multiplier,fill:"white",align:"center"}; //,dropShadow:true,dropShadowDistance:1 + var name=new PIXI.Text(name,fp); + // var name=new PIXI.BitmapText(name,{font:"16px m5x7",align:"center"}); // tint:0xFFFFFF} // worse pixel issues [29/11/18] + // name.x=0; name.y=-round(element.aheight)-2; + name.roundPixels=false; + name.anchor.set(0.5,0); + name.scale=new PIXI.Point(1/multiplier,1/multiplier); + + width=round(name.width+10); // this is new, no more guessing the width [06/08/18] + // if(round(name.width)!=name.width) offset=0.25; - with roundPixels - no need + if(!element.moving || element.me) name.roundPixels=true; // manually applied to the 4.8.2 pixi.js + // [17/02/19] Tested adding element.speed<20 like statements for merchants, makes things worse, current blurring is better + + name.x=(width/2)+offset; name.y=2.5; + + bordered_rectangle.beginFill(border_color); + bordered_rectangle.drawRect(0,0,width,height); + bordered_rectangle.endFill(); + + bordered_rectangle.beginFill(0x201F1F); + bordered_rectangle.drawRect(1,1,width-2,height-2); + bordered_rectangle.endFill(); + + // bordered_rectangle.position=new PIXI.Point(-(width/2),-height-(element.aheight||element.height)); + bordered_rectangle.position=new PIXI.Point(-round(width/2),2); + + bordered_rectangle.addChild(name); + // bordered_rectangle.displayGroup=text_layer; + + element.name_tag=bordered_rectangle; + element.ntag_cache=ntag_cache; + element.addChild(bordered_rectangle); + bordered_rectangle.parentGroup=entity_layer; +} + +function add_name_tag(element) +{ + var bar={hp:false,mp:false,color:"white",party:false,level:false,cl:false,focus:false,stand:false,online:false},hp_mwidth=32,mp_mwidth=24,hp_width,mp_width,bsc=""; + if(element.type=="character" && (xtarget||ctarget)==element) bar.hp=bar.mp=bar.level=bar.cl=true; + if(element.type=="character" && mtarget==element) bar.hp=bar.level=bar.cl=true; + if(!element.max_mp) bar.mp=false; + if(is_player(element) && !element.afk) bar.online=true; + if(is_player(element) && element.stand && (mtarget==element || (xtarget||xtarget)==element)) + { + var items=[]; + for(var i=1;i<32;i++) + if(items.length<4 && element.slots["trade"+i] && !element.slots["trade"+i].b && G.positions[G.items[element.slots["trade"+i].name].skin]) + items.push(element.slots["trade"+i]),bsc+=element.slots["trade"+i].name; + if(items.length || 1) bar.stand=items,bar.hp=false; + } + if(character && !element.me && (element.target==character.name || element.focus==character.name) && is_player(element)) bar.focus=true; + + if(element.npc); //bar.color="#E09400"; + // else if(element.type=="character" && !pvp && !is_pvp && (ctarget==element || xtarget==element)) bar.color="#368C2B"; + else if(element.team=="A") bar.color="#39BB54",bar.hp=true; + else if(element.team=="B") bar.color="#DB37A3",bar.hp=true; + else if(element.type=="character" && (pvp || is_pvp) && character && character.guild!=element.guild && character.party!=element.party && (element.target==character.name || element.focus==character.name)); //red + else if(character && character.party && character.party==element.party) bar.color="#6F3F87"; // purple + //else if(character && character.guild && character.guild==element.guild) bar.color="#3EB6C0"; // teal + else if(character && element.controller==character.name) bar.color="#899B92"; + + if(bar.hp) hp_width=round((hp_mwidth-2-2)*element.hp/element.max_hp); + if(bar.mp) mp_width=round((mp_mwidth-2-2)*element.mp/element.max_mp); + + var ntag_cache=element.name+"|"+element.color+"|"+(bar.level&&element.level)+"|"+(bar.hp&&hp_width)+"|"+(bar.mp&&mp_width)+"|"+(bar.cl&&element.ctype)+"|"+bar.focus+"|"+(bar.stand&&bsc)+"|"+bar.online; + if(element.name_tag) + { + if(element.ntag_cache==ntag_cache) return; + destroy_sprite(element.name_tag,"children"); element.name_tag=null; + } + element.ntag_cache=ntag_cache; + var bordered_rectangle=new PIXI.Graphics(),name=element.name,height=9,multiplier=1,roundPixels=false; + if(!element.moving || element.me) roundPixels=true; + bordered_rectangle.roundPixels=roundPixels; + // if(element.level) name="Lv."+element.level+" "+name; + if(element.me) multiplier=1; + var fp={fontFamily:SZ.font,fontSize:64*multiplier,fill:bar.color,align:"center"}; //,dropShadow:true,dropShadowDistance:1 + var name=new PIXI.Text(name,fp); + name.scale=new PIXI.Point(0.125/multiplier,0.125/multiplier); + name.anchor.set(0.5,0); + var fpl={fontFamily:SZ.font,fontSize:64,fill:"#A2AAB0",align:"center"},level; + if(bar.level) + { + level=new PIXI.Text(element.level>99&&"XX"||element.level,fpl); + level.scale=new PIXI.Point(0.125,0.125); + level.anchor.set(0.5,0); + } + var fp2={fontFamily:SZ.font,fontSize:64,fill:colors[element.ctype!="merchant"&&G.classes[element.ctype]&&G.classes[element.ctype].main_stat]||"#A29880",align:"center"},cl; + if(bar.cl) + { + cl=new PIXI.Text(element.ctype[0].toUpperCase(),fp2); + cl.scale=new PIXI.Point(0.125,0.125); + cl.anchor.set(0.5,0); + } + + // #IMPORTANT: ensure name.worldTransform.tx - is an integer + + var width=round(name.width+8),cl_width=7,level_width=8; + + bordered_rectangle.beginFill(0x716D6C); // all gray + bordered_rectangle.drawRect(-(bar.cl&&(cl_width+1)||0),0,width+(bar.cl&&(cl_width+1)||0)+(bar.level&&(level_width+1)||0),height); + bordered_rectangle.endFill(); + + if(bar.cl) + { + bordered_rectangle.beginFill(0x201F1F); // class rectangle + bordered_rectangle.drawRect(-cl_width,1,cl_width,height-2); + bordered_rectangle.endFill(); + } + + bordered_rectangle.beginFill(0x201F1F); // name rectangle + bordered_rectangle.drawRect(1,1,width-2,height-2); + bordered_rectangle.endFill(); + if(bar.focus) + { + bordered_rectangle.beginFill(0x3B8ED2); + bordered_rectangle.drawRect(1,0,width-2,1); + bordered_rectangle.endFill(); + } + if(bar.online) + { + bordered_rectangle.beginFill(0x6EC344); + bordered_rectangle.drawRect(1,1,1,height-2); + bordered_rectangle.endFill(); + bordered_rectangle.beginFill(0x6EC344); + bordered_rectangle.drawRect(width-2,1,1,height-2); + bordered_rectangle.endFill(); + } + + if(bar.level) + { + bordered_rectangle.beginFill(0x201F1F); // level rectangle + bordered_rectangle.drawRect(width,1,level_width,height-2); + bordered_rectangle.endFill(); + } + + if(bar.stand) + { + for(var i=0;i<4;i++) + { + bordered_rectangle.beginFill(0x716D6C); // gray + bordered_rectangle.drawRect(round(width/2)+12-i*14+i,-13,14,14); + bordered_rectangle.endFill(); + bordered_rectangle.beginFill(0x201F1F); // black + bordered_rectangle.drawRect(round(width/2)+12-i*14+1+i,-12,12,12); + bordered_rectangle.endFill(); + if(bar.stand[3-i]) + { + var item=new_sprite(bar.stand[3-i].name,"item"); + item.texture=textures["item"+bar.stand[3-i].name][1]; + item.width=10; item.height=10; item.anchor.set(0,0); + item.x=round(width/2)+12-i*14+i+2; + item.y=-11; + bordered_rectangle.addChild(item); + } + } + } + + bordered_rectangle.position=new PIXI.Point(-round(width/2),-height-(element.aheight||element.height)-(bar.mp&&4||0)); + + name.x=round(width/2); name.y=1.5; name.roundPixels=roundPixels; + bordered_rectangle.addChild(name); + + if(bar.level) + { + level.x=width+4.5; level.y=1.5; level.roundPixels=roundPixels; + bordered_rectangle.addChild(level); + } + + if(bar.cl) + { + cl.x=-3; cl.y=1.5; cl.roundPixels=roundPixels; + bordered_rectangle.addChild(cl); + } + + var hp_color=0xB12727; //red + var mp_color=0x3A62CE; + + if(bar.hp) + { + var top_d=-5,left_d=(width-hp_mwidth)/2; + + bordered_rectangle.beginFill(0x716D6C); + bordered_rectangle.drawRect(left_d,top_d,hp_mwidth,4+1+1); + bordered_rectangle.endFill(); + + bordered_rectangle.beginFill(0x201F1F); + bordered_rectangle.drawRect(1+left_d,1+top_d,hp_mwidth-1-1,4); + bordered_rectangle.endFill(); + + bordered_rectangle.beginFill(hp_color); + bordered_rectangle.drawRect(1+1+left_d,1+1+top_d,hp_width,2); + bordered_rectangle.endFill(); + } + + if(bar.mp) + { + var top_d=8,left_d=(width-mp_mwidth)/2; + + bordered_rectangle.beginFill(0x716D6C); + bordered_rectangle.drawRect(left_d,top_d,mp_mwidth,4+1+1); + bordered_rectangle.endFill(); + + bordered_rectangle.beginFill(0x201F1F); + bordered_rectangle.drawRect(1+left_d,1+top_d,mp_mwidth-1-1,4); + bordered_rectangle.endFill(); + + bordered_rectangle.beginFill(mp_color); + bordered_rectangle.drawRect(1+1+left_d,1+1+top_d,mp_width,2); + bordered_rectangle.endFill(); + } + + var container=new PIXI.Sprite(); + container.addChild(bordered_rectangle); + element.name_tag=container; + element.addChild(container); + //container.parentGroup=player_layer; +} + +function hp_bar_logic(element) +{ + if(no_graphics) return; + if(element.type!="monster") return; + if(element.dead && !element.hp_bar) return; + if((!hp_bars || element.me) && !options.always_hpn) return; + if(ctarget==element || xtarget==element || mtarget==element || (character && character.party && character.party==element.party) || (character && character.party && (element.target && in_arr(element.target,party_list) || element.focus && in_arr(element.focus,party_list))) + || (character && (element.target==character.name || element.focus==character.name)) || (character && character.team && !element.npc) || (character && element.controller==character.name) || options.always_hpn) + { + add_hp_bar(element); + } + else if(element.hp_bar) + { + destroy_sprite(element.hp_bar,"children"); element.hp_bar=null; element.hp_color=null; + } +} + +function add_hp_bar_old(element) +{ + var width=max(32,round(element.width*0.8)),bsize=1,bsize2=round(2*bsize); // bsize = 1.5 -> awesome [12/08/16] + var color=0xB12727; //red + + if(element.npc) color=0xE09400; + else if(element.type=="character" && !pvp && !is_pvp && (ctarget==element || xtarget==element)) color=0x368C2B; // green + else if(element.team=="A") color=0x39BB54; + else if(element.team=="B") color=0xDB37A3; + else if(element.type=="character" && (pvp || is_pvp) && character && character.guild!=element.guild && character.party!=element.party && (element.target==character.name || element.focus==character.name)); //red + else if(character && character.party && character.party==element.party) color=0x6F3F87; // purple + else if(character && character.guild && character.guild==element.guild) color=0x3EB6C0; // teal + else if(character && is_monster(element) && (ctarget==element || xtarget==element)); //red + else if(character && element.controller==character.name) color=0x899B92; + else if(character && (element.target==character.name || element.focus==character.name) && is_player(element)) color=0x3FA8D1; + else if(mtarget==element) color=0x55CFDA; + // color=0xB8542A; // ligher-dark-orange + // color=0xB14622; // dark-orange + + var hp_width=round((width-round(2*(bsize+1)))*element.hp/element.max_hp); + + if(element.hp_bar) + { + if(element.hp_width == hp_width && element.hp_color==color) return; //The Cache! :) [06/08/16] + destroy_sprite(element.hp_bar,"children"); element.hp_bar=null; + } + //console.log("HP BAR DRAW"); + + element.hp_width=hp_width; + + var hp_bar=new PIXI.Graphics(); + + hp_bar.beginFill(0x716D6C); + hp_bar.drawRect(0,0,width,6+bsize2); + hp_bar.endFill(); + + hp_bar.beginFill(0x201F1F); + hp_bar.drawRect(bsize,bsize,width-bsize2,6); + hp_bar.endFill(); + + hp_bar.beginFill(color); + hp_bar.drawRect(bsize+1,bsize+1,element.hp_width,4); + hp_bar.endFill(); + + var dy=12,dx=0; + if(element.type=="character" && character_names) dy+=8; + if(element.mscale==2) dy+=6,dx+=width/2; + // if(element.height<40) dy=12; + + hp_bar.position=new PIXI.Point(-(width/2)-dx,-dy-(element.aheight||element.height)+(element.mscale==2&&-4||0)); + if(element.mscale) hp_bar.scale=new PIXI.Point(element.mscale,element.mscale); + element.hp_bar=hp_bar; element.hp_color=color; + hp_bar.parentGroup=window.hp_layer; + element.addChild(hp_bar); +} + +function add_hp_bar(element) +{ + var width=max(32,round(element.width*0.8)),bsize=1,bsize2=round(2*bsize); // bsize = 1.5 -> awesome [12/08/16] + var color=0xB12727; //red + + if(character && is_monster(element) && (ctarget==element || xtarget==element)); //red + else if(mtarget==element) color=hx("#91987B"); + + var hp_width=round((width-round(2*(bsize+1)))*element.hp/element.max_hp); + + if(element.hp_bar) + { + if(element.hp_width == hp_width && element.hp_color==color && element.hp_level==element.level) return; //The Cache! :) [06/08/16] + destroy_sprite(element.hp_bar,"children"); element.hp_bar=null; + } + //console.log("HP BAR DRAW"); + + element.hp_width=hp_width; + element.hp_level=element.level; + + var hp_bar=new PIXI.Graphics(); + var level=element.level>1; + + hp_bar.beginFill(0x716D6C); + hp_bar.drawRect(0-(level&&9||0),0,width+(level&&9||0),6+bsize2); + hp_bar.endFill(); + + if(level) + { + var lcolor="#5EC063",diff=calculate_difficulty(element); + if(diff>=2) lcolor="#D52526"; + else if(diff) lcolor="#EF9232"; + + hp_bar.beginFill(hx(lcolor)); + hp_bar.drawRect(bsize-9,bsize,8,6); + hp_bar.endFill(); + + var fpl={fontFamily:SZ.font,fontSize:64,fill:"white",align:"center"},level=new PIXI.Text(element.level>99&&"XX"||element.level,fpl); + level.scale=new PIXI.Point(0.125,0.125); + level.anchor.set(0.5,0); + level.x=-4; level.y=0.5; + hp_bar.addChild(level); + } + + hp_bar.beginFill(0x201F1F); + hp_bar.drawRect(bsize,bsize,width-bsize2,6); + hp_bar.endFill(); + + hp_bar.beginFill(color); + hp_bar.drawRect(bsize+1,bsize+1,element.hp_width,4); + hp_bar.endFill(); + + var dy=12,dx=0; + var SCALE=false; + if(element.mscale==0.5) SCALE=2; + if(element.mscale>1) dy-=element.mscale*element.mscale*4; + if(SCALE && element.mscale==0.5) dy+=6,dx+=width/2; + + // if(element.height<40) dy=12; + + hp_bar.position=new PIXI.Point(-(width/2)-dx,-dy-(element.aheight||element.height)); // +(element.mscale==2&&-4||0) + if(SCALE) hp_bar.scale=new PIXI.Point(SCALE,SCALE); + element.hp_bar=hp_bar; element.hp_color=color; + hp_bar.parentGroup=window.hp_layer; + element.addChild(hp_bar); +} + +function calculate_difficulty(monster) +{ + var mdps=monster.attack*monster.frequency,dps=4000,hp=8000,mhp=monster.hp; + if(character) dps=character.attack*character.frequency,hp=character.hp; + for(var i=0;i<30;i++) + { + hp-=mdps*2; + mhp-=dps*2; + hp+=400; + if(hp<0 || mhp<0) break; + } + if(hp<0) return 2; + else if(character && character.hp-hp>character.max_hp*0.3 || !character && 6000-hp>8000*0.3) return 1; + else return 0; +} + +function test_bitmap(x,y,size) +{ + var text=new PIXI.BitmapText("YAY BITMAPS!",{font:size+"px m5x7",align:"center"}); + text.displayGroup=text_layer; + text.x=round(x); + text.y=round(y); + map.addChild(text); +} + +function d_line(start,end,args) +{ + if(!d_lines || no_graphics || paused) return; + if(!args) args={}; + var party=[0xf80c12,0xee1100,0xff3311,0xff4422,0xff6644,0xff9933,0xfeae2d,0xccbb33,0xd0c310,0xaacc22,0x69d025,0x22ccaa,0x12bdb9,0x11aabb,0x4444dd,0x3311bb,0x3b0cbd,0x442299]; + if(start.slots && (start.slots.helmet && start.slots.helmet.name=="partyhat" || start.slots.mainhand && start.slots.mainhand.name=="ornamentstaff") && args.color!="heal") + { + shuffle(party); + args.size=1; + args.color=party[0]; + d_line({x:get_x(start)-1,y:get_y(start)-1},{x:get_x(end)-1,y:get_y(end)-1},{color:party[1]}); + } + else if(!args.color || args.color=="attack") args.color=0x980B00 //0xE01100; + else if(args.color=="heal") args.color=0xE08593; + else if(args.color=="taunt") args.color=0x707070; + else if(args.color=="burst") args.color=0x428FAE,args.size=3; + else if(args.color=="supershot") args.color=0x9B172E,args.size=2; + else if(args.color=="reflect") args.color=0x8A4AA2,args.size=2; + else if(args.color=="curse") args.color=0x7D4DAA,args.size=2; + else if(args.color=="evade") args.color=0x808B94; + else if(args.color=="my_hit") args.color=0x2C8E25; //0x2A9A28 + else if(args.color=="gold") args.color=0xFFD700; + else if(args.color=="item") args.color=0x3EA2B3; + else if(args.color=="cx") args.color=hx("#DC8BD4"); + else if(args.color=="mana") args.color=eval(colors.mp.replace("#","0x")); + else if(args.color=="mluck") args.color=eval("#9BF984".replace("#","0x")); + else if(args.color=="warrior") args.color=0xE07523,args.size=3; + else if(args.color && args.color.startsWith && args.color.startsWith("#")) args.color=eval(args.color.replace("#","0x")); + + e=new PIXI.Graphics(); + e.lineStyle(args.size||1, args.color); + e.moveTo(get_x(start),get_y(start)-2); + e.lineTo(get_x(end),get_y(end)-2); + e.endFill(); + map.addChild(e); + function disappear_line(step,line) + { + return function(){ + line.alpha-=0.08; + if(step<10) draw_timeout(disappear_line(step+1,line),20); + else + { + remove_sprite(line); + try{ line.destroy(); }catch(e){} + } + } + } + draw_timeout(disappear_line(0,e),20); +} + +function step_d_texts(entity,add) +{ + var to_remove=[]; + for(var i=0;i0.25); + else + { + remove_sprite(text); + try{ text.destroy({texture:true,baseTexture:true}); }catch(e){console.log(e);} // dirty fix: [20/08/16] #PIXI + to_remove.push(i); + } + } + for(var i=to_remove.length-1;i>=0;i--) + { + entity.texts.splice(to_remove[i],1); + } +} + +function shift_d_texts(entity,add) +{ + for(var i=0;iSZ.normal) text.disp_m=(SZ.normal+1)/18.0; + text.anim_time=max(75,parseInt(100*18.0/size)); // Originally just 100 [03/12/17] + text.type='text'; + text.alpha=1; text.last_fade=new Date(); + text.anchor.set(0.5,1); + if(fx) start_filter(text,fx); + if(text_quality>1) text.scale=new PIXI.Point((entity.mscale||1)/text_quality,(entity.mscale||1)/text_quality); + + //twidth=text.width,offset=0; + //if(round(twidth)!=twidth) offset=0.5; + + text.x=round(x); + text.y=round(y)+offset; + if(args.y) text.y-=args.y; + + entity.addChild(text); + + entity.texts=entity.texts||[]; + if(entity.texts.length && text.y-entity.texts[0].y<10) + shift_d_texts(entity,10-(text.y-entity.texts[0].y)); + entity.texts.splice(0,0,text); + + if(args.s) sfx(args.s,text.x,text.y); +} + +function d_text(message,x,y,args) +{ + var sprite=null; + if(mode.dom_tests_pixi || no_graphics || paused) return; + if(is_object(x)) + { + if(x.type && mode.use_new_d_texts) return d_text_new(message,x,y); + sprite=x; args=y; + x=get_x(sprite); + y=get_y(sprite)-(sprite.aheight||sprite.height)-(sprite.hp_bar&&15||2); + if(sprite.mscale==2) y+=14; + } + if(!args) args={}; + var color=args.color||"#4C4C4C",fx=null; // "#383537" before text_quality = 2 as default [16/08/16] + if(color=="hp") color="green"; + else if(color=="mp") color="#317188"; // previously "#006AA9" + else if(color=="damage") color="#C80000"; // previously "red" + else if(color=="+gold") color="gold"; + else if(color=="stun") color="#FF9601"; + else if(color=="sugar") color="#D64770"; + else if(color=="freeze") color="#53C1FF"; + else if(color=="burn") color="#FD9644"; + else if(color=="crit") color="#D32D51"; + else if(color=="sneak") color="#2D9B41"; + else if(color=="mana") color=colors.mp; + else if(color=="elixir") color="#E06A63"; + else if(color=="evade") color="#808B94"; + else if(color=="reflect") color="#6D62A2"; + else if(color=="burst") color="#2A8A9A",size="large"; + else if(color=="poison") color=colors.poison,size="large"; + else if(color=="1mxp") color="#FFFFFF",fx="glow"; + else if(colors[color]) color=colors[color]; + var size=SZ[args.size]||args.size||SZ.normal; + // if(args.size=="huge" || args.size=="large") y=-10; + // console.log(size); + var parent=args.parent||window.map; + var animate=!args.dont_animate; + var offset=args.offset||0; + var delay=1000; + var text=new PIXI.Text(message,{fontFamily:SZ.font,fontSize:size*text_quality,fontWeight:"bold",fill:color,align:"center"}); //,fontWeight:"bold" + //,dropShadow:true,dropShadowColor:"#B0B0B0",dropShadowDistance:1,dropShadowAngle:-Math.PI/2 + if(use_layers) text.parentGroup=text_layer; + else text.displayGroup=text_layer; + + text.disp_m=SZ.normal/18.0; + if(size>SZ.normal) text.disp_m=(SZ.normal+1)/18.0; + text.anim_time=max(75,parseInt(100*18.0/size)); // Originally just 100 [03/12/17] + text.type='text'; + text.alpha=1; text.last_fade=new Date(); + text.anchor.set(0.5,1); + if(fx) start_filter(text,fx); + if(text_quality>1) text.scale=new PIXI.Point(1/text_quality,1/text_quality); + + //twidth=text.width,offset=0; + //if(round(twidth)!=twidth) offset=0.5; + + text.x=round(x); + text.y=round(y)+offset; + if(args.y) text.y-=args.y; + + parent.addChild(text); + function disappear_text(step,text) + { + return function(){ + var ms=mssince(text.last_fade),y=round(4*ms/text.anim_time); + // console.log(y); + if(20.25) draw_timeout(disappear_text(step+1,text),text.anim_time); + else + { + remove_sprite(text); + try{ text.destroy({texture:true,baseTexture:true}); }catch(e){console.log(e);} // dirty fix: [20/08/16] #PIXI + } + } + } + function old_disappear_text(step,text) + { + return function(){ + text.position.y-=4; + text.alpha-=0.08; + if(step<10) draw_timeout(disappear_text(step+1,text),text.anim_time); + else + { + remove_sprite(text); + try{ text.destroy({texture:true,baseTexture:true}); }catch(e){console.log(e);} // dirty fix: [20/08/16] #PIXI + } + } + } + draw_timeout(disappear_text(0,text),text.anim_time); + + if(args.s) sfx(args.s,text.x,text.y); +} + +function api_call(method,args,r_args) +{ + if(!args) args={}; if(!r_args) r_args={}; + var api_path="/api/"+method,disable=r_args.disable; + if(args.ui_loader) { r_args.r_id=randomStr(10); delete args.ui_loader; } + if(args.callback) { r_args.callback=args.callback; delete args.callback; } + if(disable) disable.addClass("disable"); + if(window.is_electron) args.epl=electron_data.platform; + data={ 'method':method, 'arguments':JSON.stringify(args) }; + function on_success(r_args,disable) { + return function(ct) { + if(r_args.r_id) hide_loader(r_args.r_id); + if(r_args.callback) r_args.callback.apply(this,[ct]); + else handle_information(ct); + if(r_args.success) smart_eval(r_args.success); + if(disable) disable.removeClass("disable"); + if(r_args.pid) resolve_deferred("api_call"+r_args.pid); + } + } + function on_error(r_args,disable) + { + return function(ct) { + if(r_args.r_id) hide_loader(r_args.r_id); + if(r_args.silent || in_arr(method,auto_api_methods)) return; + ui_error("An Unknown Error [HTTP]"); error_ct=ct; + if(method!="log_error" && ct.status+""!="0") + setTimeout(function(ct,api_path){ return function(){api_call("log_error",{type:"api_call_error",err:ct.status+" "+ct.statusText+" on "+api_path,info:ct.getAllResponseHeaders()}); }}(ct,api_path),40000); + if(disable) disable.removeClass("disable"); + if(r_args.pid) reject_deferred("api_call"+r_args.pid); + } + } + if(r_args.r_id) show_loader(r_args.r_id); + call_args={type:'POST',dataType:"json",url:window.location.origin+api_path,data:data,success:on_success(r_args,disable),error:on_error(r_args,disable)} + $.ajax(call_args); + if(r_args.promise) + { + r_args.pid=randomStr(20); + return push_deferred("api_call"+r_args.pid); + } +} + +function api_call_l(method,args,r_args) +{ + if(!args) args={}; + args.ui_loader=true; + return api_call(method,args,r_args); +} + +var last_llevel=-1; +function light_logic() +{ + if(!mode.ltbl || no_graphics) return; + + var c=new Date(),h=c.getUTCHours(),m=c.getUTCMinutes(); + if(S.schedule && S.schedule.time_offset) h=(24+S.schedule.time_offset+h)%24; + + var llevel=1,bonus=0; + var levels=[0,0,0,0,0,0.2,0.6,0.9,1,1,1,1,1,1,1,1,1,1,1,0.9,0.4,0,0,0,0]; + + llevel=(levels[h]*(60-m)+levels[h+1]*(m))/60; + bonus=llevel/5; + + if(!G.maps[current_map].outside && G.maps[current_map].lux) llevel=G.maps[current_map].lux+bonus; + if(G.maps[current_map].outside && G.maps[current_map].lux) llevel=min(llevel,G.maps[current_map].lux); + + llevel=max(0,min(llevel,1)); + + var alpha=1; + var levels=[1,1,1,1,1,1,1,1,1,1,1,0.8,0.7,0.8,0.9,1,1,1,1,1,1,1,1,1,1]; + if(G.maps[current_map].outside && !G.maps[current_map].lux) alpha=(levels[h]*(60-m)+levels[h+1]*(m))/60; + // if(llevel) alpha=0.5; + + if(llevel==last_llevel) return; + + lighting.clearColor = [0.55+llevel*0.45,0.55+llevel*0.45,0.55+llevel*0.45,alpha]; + + map_nights.forEach(function(l){ + l.alpha=min(1,max(0,0.8-llevel)) + }) + + map_lights.forEach(function(l){ + l.alpha=min(1,max(0,0.8-llevel)) + }) + + if(is_sdk) console.log(lighting.clearColor); + + last_llevel=llevel+" "+alpha; +} + +var warned={}; +function new_map_logic(place,data) +{ + future_entities={players:{},monsters:{}}; + I=data.info||{}; + //console.log(JSON.stringify(I)); + + if(current_map=="resort") add_log("Resort is a prototype with work in progress","#ADA9E4"); + if(current_map=="tavern") + { + if(I.dice=="roll") + map_machines.dice.shuffling=true,map_machines.dice.num=undefined,delete map_machines.dice.lock_start,map_machines.dice.locked=0; + if(I.dice=="lock") + map_machines.dice.shuffling=true,map_machines.dice.num=I.num,map_machines.dice.lock_start=future_ms(-1200),map_machines.dice.locked=0; + if(I.dice=="bets") + map_machines.dice.shuffling=false,map_machines.dice.num=I.num,map_machines.dice.seconds=I.seconds,map_machines.dice.count_start=future_s(-I.seconds); + add_log("Tavern is a prototype with work in progress","#63ABE4"); + } + else dice_bet.active=false,topleft_npc=false; + + if(is_pvp && (place=="start" || place=="welcome")) add_log("This is a PVP Server. Be careful!","#E1664C"); + if(place=="map" && !is_pvp && G.maps[current_map].safe_pvp && !warned[current_map]) warned[current_map]=1,add_log("This is a Safe PVP Zone. You can lose recently looted items if someone defeats you!","#E1664C"); + else if(place=="map" && !is_pvp && G.maps[current_map].pvp && !warned[current_map]) warned[current_map]=1,add_log("This is a PVP Zone. Be careful!","#E1664C"); + else if(place=="map" && is_pvp && G.maps[current_map].safe && !warned[current_map]) warned[current_map]=1,add_log("This is a Safe Zone. No one can hurt you here!","#9DE85E"); + light_logic(); + render_map(); +} + +function new_game_logic() +{ + if(gameplay=="hardcore") hardcore_logic(); + if(gameplay=="test") test_logic(); +} + +function ui_log(m,color) +{ + add_log(m,color); +} + +function ui_error(m) +{ + add_log(m,"red"); +} + +function ui_success(m) +{ + add_log(m,"green"); +} + +function load_code_s(num) +{ + if(num=="#") + { + show_alert("To delete a code slot, simply enter DELETE as the slot name and save the slot!"); + } + else + { + $(".csharp").val(""+num); + $(".codename").val(X.codes[num]&&X.codes[num][0]||"Empty"); + } +} + +function save_code_s() +{ + if(!$(".csharp").val()) return; + api_call("save_code",{code:codemirror_render.getValue(),slot:$(".csharp").val(),name:$(".codename").val(),log:1}); +} + +var last_servers_and_characters=new Date(); +setInterval(function(){ + if(!window.inside) return; + if(inside=="game" && ssince(last_servers_and_characters)>89 || inside=="game" && character && !character.afk && ssince(last_servers_and_characters)>4 || inside=="selection" && ssince(last_servers_and_characters)>4 || window.is_comm && ssince(last_servers_and_characters)>4) + { + api_call("servers_and_characters"); + last_servers_and_characters=new Date(); + } +},2000); + +function update_servers_and_characters() +{ + var keys={1:null,2:null,3:null,"merchant":null},order=1,c_count=0; + X.characters.forEach(function(character){ + if(character.online) $(".characterav"+character.name).html('[I]'); + else $(".characterav"+character.name).html('[A]'); + + if(!character.online) return; + + if(character.type=="merchant") keys.merchant=character; + else if(order<=3) keys[order]=character,order+=1; + }); + [1,2,3,"merchant"].forEach(function(key){ + if(!keys[key]) $(".characterr"+key).html("Offline"); + else $(".characterr"+key).html(""+keys[key].name+""),c_count+=1; + }); + $(".ccount").html(c_count); + if($(".cclist").length) load_character_list(); + if($(".sslist").length) load_servers_list(); + if(!X.unread) + $(".comcount").html(""); + else + $(".comcount").html(" ["+X.unread+"]"); + $(".mcount").html(X.unread); +} + +function load_base_code() +{ + if(character && X.codes[real_id]) + show_confirm("If you load the base code and engage, your default character slot will be overwritten by it, are you sure you want to load the default base code?",["#D06631","Yes"],"No!",function(){ load_code("0",1); hide_modal(true);}); + else + load_code("0",1); +} + +function handle_information(infs) +{ + for(var i=0;i[Documentation] Code Slots and Files
'; + html+="
[Default] Load Base Code
"; + if(character) + { + html+="
[Character Default] "+character.name+"
"; + } + for(var num in ui_list) + { + if(num==real_id) continue; + var sname=num,lnum=num; + if(parseInt(num)>100) color="#D46E33",sname="Character Default"; + else color=colors.code_blue; + if(!X.codes[num]) lnum=0; + html+="
["+sname+"] "+ui_list[num][0]+"
"; + one=true; + } + html+="
"; + html+="
You can also load codes into your code. For example, you can save your 'Functions' in one code slot, let's say 2, and inside another code slot, you can:
load_code(2) or load_code('Functions')
"; + // html+="
To delete a code slot, enter 'delete' in the name field.
"; + html+="
"; + html+="
"; + show_modal(html,{keep_code:true,wrap:false}); + } + else if(info.purpose=="save") + { + var html="
",one=false; + var c_slot=code_slot,c_name=""; + if(c_slot) + for(var num in info.list) + if(parseInt(num)==c_slot) c_name=info.list[num][0]; + html+="
"; + // The id's and name's etc. are all to prevent autocomplete [13/03/19] + // https://stackoverflow.com/a/38961567/914546 + html+=""; + html+=""; + html+="
SAVE
"; + html+="
"; + // info.list={}; + var ui_list=clone(info.list); + X.codes=info.list; + if(!Object.keys(ui_list).length) ui_list={"1":["Empty",0],"2":["Empty",0]}; + for(var i=1;i<=100;i++) + if(!ui_list[i]) + { + ui_list[i]=["Empty",0]; + c_slot=""+i; + c_name="Empty"; + break; + } + + if(character.ctype!="merchant") + for(var num in ui_list) + { + if(parseInt(num)>100) + delete ui_list[num]; + } + if(character && !ui_list[real_id]) ui_list[real_id]=[character.name,0]; + ui_list["#"]=["DELETE",0]; + html+='
[Documentation] Code Slots and Files
'; + for(var num in ui_list) + { + if(parseInt(num)>100) color="#975CAD"; + else if(num=="#") color="gray"; + else color=colors.code_pink; + html+="
["+(num==real_id&&"YOUR BASE CODE"||num)+"] "+ui_list[num][0]+"
"; + one=true; + } + html+="
"; + html+="
"; + html+="
"; + // if(!one) html+="
You don't have any saved Code's yet
"; + show_modal(html,{keep_code:true,wrap:false}); + if(c_slot) $('#alcodenumx').val(c_slot); + if(c_name) $('#alcodeinputx').val(c_name); + } + else show_json(info.list); + } + else if(info.type=="servers_and_characters") + { + X.servers=info.servers; + X.characters=info.characters; + X.tutorial=info.tutorial; + X.unread=info.mail; + if(window.character && info.code_list[code_slot] && (!X.codes[code_slot] || info.code_list[code_slot][1]>X.codes[code_slot][1])) + { + add_log("External code update detected!","#5BAC57"); + add_log("Syncing ...","#5BAC57"); + api_call("load_code",{name:code_slot,run:'',log:true}); + } + if(is_electron && electron_is_main()) + { + var delay=0; + for(var num in X.codes) + { + if(!info.code_list[num]) + file_op_queue[num]=["remove",num,X.codes[num][1]]; + } + for(var num in info.code_list) + { + if(!X.codes[num] || !code_ref[num] || X.codes[num][1]>code_ref[num].v) + file_op_queue[num]=["download",num,info.code_list[num][1]]; + } + } + X.codes=info.code_list; + update_servers_and_characters(); + if(window.is_comm) render_characters(),render_servers(); + } + else if(info.type=="unread") + { + X.unread=info.count; + update_servers_and_characters(); + } + else if(info.type=="reload") + { + var reload_time=future_s(10); + storage_set("reload"+server_region+server_identifier,JSON.stringify({time:reload_time,ip:info.ip,port:""+info.port})); + } + else if(info.type=="friends") + { + load_friends(info); + } + else if(info.type=="mail") + { + //show_json(info); + load_mail(info); + } + else if(info.type=="messages") + { + // show_json(info); + load_chat(info,info.mtype); + } + else if(info.type=="merchants") + { + // show_json(info); + merchants={}; + load_merchants(info); + } + else if(in_arr(info.type,["ui_log","message"])) + { + if(info.color) add_log(info.message,info.color); + else ui_log(info.message); + } + else if(info.type=="code_info") + { + if(info['delete']) + delete X.codes[info.num]; + else + X.codes[info.num]=[info.name,info.v]; + } + else if(info.type=="libraries") + { + var folder=ide_root+"/adventureland/libraries"; + fs.promises.writeFile(folder+"/default_code.js",info.default_code.toString(),"utf8"); + fs.promises.writeFile(folder+"/runner_functions.js",info.runner_functions.toString(),"utf8"); + fs.promises.writeFile(folder+"/runner_compat.js",info.runner_compat.toString(),"utf8"); + fs.promises.writeFile(folder+"/common_functions.js",info.common_functions.toString(),"utf8"); + storage_set("lib_version",VERSION+""+user_id); + } + else if(info.type=="code") + { + info.code=""+info.code; // apparently it's possible to store objects + if(info.slot>0 && info.v) X.codes[info.slot]=[info.name,info.v]; + if(info.save) + { + if(is_electron && electron_is_main()) + file_op_queue[info.slot]=["save",info.slot,info.code,info.v]; + } + else + { + codemirror_render.setValue(info.code); + code_change=false; + + new_code_slot=(!info.slot)&&real_id||info.slot; + + if(info.reset || new_code_slot!=code_slot) codemirror_render.clearHistory(); + + code_slot=new_code_slot; + + if(info.run) + { + if(code_run) toggle_runner(),toggle_runner(); + else toggle_runner(); + } + else if(info.code.indexOf("autorerun")!=-1) + { + if(code_run) toggle_runner(),toggle_runner(); + } + + if(parseInt(code_slot)<=100) + $(".codeslottype").html(""+code_slot); + else + $(".codeslottype").html("Character"); + + $(".codeslotname").html(""+(X.codes[code_slot]&&X.codes[code_slot][0]||"Default Code")); + } + } + else if(info.type=="gcode") + { + var html=""; + html+=""; + show_modal(html); + } + else if(info.type=="article") + { + if(info.tutorial) + { + render_tutorial(info.html,parseInt(info.tutorial),info.url||"/docs"); + } + else if(info.guide) + { + render_learn_article(info.html,{url:info.url||"/docs",prev:info.prev,next:info.next}); + } + else if(info.func) + { + render_function_html=info.html; + render_function_reference(info.func,undefined,undefined); + } + else + { + render_learn_article(info.html,{url:info.url||"/docs",prev:info.prev,next:info.next}); + } + } + else if(info.type=="tutorial_data") + { + delete info.type; + X.tutorial=info; + if(info.next) + { + small_success(character,{color:"purple"}); + delete info.next; + setTimeout(open_tutorial,1000); + } + else if(info.success) + { + small_success(character,{color:"success"}); + delete info.success; + } + update_tutorial_ui(); + } + else if(info.type=="chat_message") + { + add_chat("",info.message,info.color); + } + else if(in_arr(info.type,["ui_error","error"])) + { + if(inside=="message") $("#message").html(info.message); + else ui_error(info.message); + } + else if(in_arr(info.type,["success"])) + { + if(inside=="message") $("#message").html(info.message); + else ui_success(info.message); + } + else if(info.type=="content") + { + $("#content").html(info.html); + resize(); + } + else if(info.type=="eval") + { + smart_eval(info.code); + } + else if(info.type=="func") + { + smart_eval(window[info.func],info.args); + } + else if(info.type=="refresh") + { + refresh_page(); + } + else if(info.type=="pcs") pcs(info.sound); + } +} + +function add_alert(e) +{ + console.log("caught exception: "+e); + if(is_sdk) alert(e); +} + +function sfx(type,x,y) +{ try { + if(!window.sound_sfx || no_html) return; + var sound=null; + if(type=="hit" || type=="monster_hit") sound=sounds.hit_8bit; + if(type=="explosion") sound=sounds.fx_explosion; + if(type=="coins") sound=sounds.coin_collect; + if(type=="hp" || type=="mp") sound=sounds.use_8bit; + if(type=="chat") sound=sounds.chat; + if(type=="walk") sound=sounds.walk; + if(type=="npc") sound=sounds.drop; + if(!sound && sounds[type]) sound=sounds[type]; + if(sound) + { + if(x===undefined) sound.play(); + else + { + if(mode.directional_sfx) + { + sound.orientation(0,0,0); + sound.pos((-x+map.real_x)/120.0,(y-map.real_y)/120.0,0); + sound.play(); + } + else + { + var distance=point_distance(x,y,map.real_x,map.real_y),volume=1; + if(!sound.original_volume) sound.original_volume=sound.volume(); + if(distance>700) volume=0.05; + else if(distance>500) volume=0.075; + else if(distance>400) volume=0.10; + else if(distance>300) volume=0.15; + else if(distance>250) volume=0.175; + else if(distance>275) volume=0.2; + else if(distance>250) volume=0.25; + else if(distance>225) volume=0.3; + else if(distance>200) volume=0.4; + else if(distance>175) volume=0.45; + else if(distance>150) volume=0.5; + else if(distance>125) volume=0.6; + else if(distance>100) volume=0.7; + else if(distance>75) volume=0.8; + else if(distance>50) volume=0.9; + sound.volume(sound.original_volume*volume); + // console.log(distance+" "+sound.original_volume*volume); + sound.play(); + } + } + } +} catch(e) { add_alert(e); } } + +function tut(name) +{try{ + if(X && X.tutorial && X.tutorial.task==name) + { + api_call("tutorial",{task:name}); + } +} catch(e) { console.error("FATAL: tut() "+name); } } + +function pcs(type) +{ + if(!window.sound_sfx) return; + if(!type || type==0) + { + if(sounds.click) sounds.click.play(); + } + if(type=="success" && sounds.success) sounds.success.play(); +} + +function init_sounds() +{ + if(!window.Howl) {sound_music=false; sound_sfx=false; add_log("Sound issue (Howl). Turned sound off"); return;} + if(no_html) return; + sounds.click = new Howl({ + src: [url_factory("/sounds/effects/click_natural.wav")], + volume:0.32, + }); + if(sound_sfx) init_fx(); + if(sound_music) init_music(); +} + +function init_fx() +{ + if(!window.Howl) {sound_music=false; sound_sfx=false; add_log("Sound issue (Howl). Turned sound off"); return;} + if(window.fx_init) return; + window.fx_init=1; + sounds.fx_explosion = new Howl({ + src: [url_factory("/sounds/fx/EXPLOSION_Short_Kickback_Crackle_stereo.wav")], + volume:0.3, + }); + sounds.coin_collect = new Howl({ + src: [url_factory("/sounds/fx/pop_plink.wav")], + volume:0.2, // 0.1 for Coin's + }); + sounds.drop_egg = new Howl({ + src: [url_factory("/sounds/fx/ANIMAL_Duck_08_mono.wav")], + volume:0.2, // 0.1 for Coin's + }); + // sounds.hit_8bit = new Howl({ + // src: [url_factory("/sounds/fx/8BIT_RETRO_Hit_Bump_Noise_mono.wav")], + // volume:0.1, + // }); + sounds.hit_8bit = new Howl({ + src: [url_factory("/sounds/fx/zap_drum.wav")], + volume:0.2, // 0.1 for Coin's + }); + sounds.magic_8bit = new Howl({ + src: [url_factory("/sounds/fx/8BIT_RETRO_Fire_Blaster_Short_mono.wav")], + volume:0.4, + }); + // sounds.use_8bit = new Howl({ + // src: [url_factory("/sounds/fx/VideoGameSFX_blip_07.wav")], + // volume:0.10, + // }); + sounds.use_8bit = new Howl({ + src: [url_factory("/sounds/fx/pop_plink.wav")], + volume:0.16, + }); + sounds.chat = new Howl({ + src: [url_factory("/sounds/fx/UI_Beep_Double_Quick_Smooth_stereo.wav")], + volume:0.5, + }); + sounds.walk=new Howl({ + src:[url_factory("/sounds/fx/FOOTSTEP_Asphalt_Trainers_Walk_Slow_RR5_mono.wav")], + volume:0.6, + }); + sounds.drop=new Howl({ + src:[url_factory("/sounds/fx/DROP_Designed_mono.wav")], + volume:0.4, + }); + sounds.open=new Howl({ + src:[url_factory("/sounds/fx/CLASP_Plastic_Open_stereo.wav")], + volume:0.4, + }); + sounds.whoosh=new Howl({ + src:[url_factory("/sounds/fx/WHOOSH_Air_Fast_Wind_RR1_mono.wav")], + volume:0.2, + }); + sounds.reflect=new Howl({ + src:[url_factory("/sounds/fx/MAGIC_SPELL_Spawn_mono.wav")], + volume:0.15, + }); + sounds.crackle01=new Howl({ + src:[url_factory("/sounds/fx/Explosive01.wav")], + volume:0.15, + }); + sounds.crackle0=new Howl({ + src:[url_factory("/sounds/fx/Explosive02.wav")], + volume:0.15, + }); + sounds.level_up=new Howl({ + src:[url_factory("/sounds/fx/MUSIC_EFFECT_Bell_Voice_Positive_09_stereo.wav")], + volume:0.2, + }); +} + +function performance_trick() +{ + if(!window.Howl) return; + if(sounds.empty) return sounds.empty.play(); + sounds.empty = new Howl({ + src: [url_factory("/sounds/loops/empty_loop_for_js_performance.ogg"),url_factory("/sounds/loops/empty_loop_for_js_performance.wav")], + volume:0.5, + autoplay: true, loop: true, + }); + sounds.empty.cplaying=true; +} + +function init_music() +{ + if(!window.Howl) {sound_music=false; sound_sfx=false; add_log("Sound issue (Howl). Turned sound off"); return;} + if(window.music_init) return; + window.music_init=1; + sounds.christmas = new Howl({ + src: [url_factory("/sounds/loops/christmas.ogg")], + volume:0.2*music_level, + autoplay: false, loop: true, + }); + if(xmas_tunes) return; + sounds.horror01 = new Howl({ + src: [url_factory("/sounds/loops/horror_01_loop.ogg")], // ,url_factory("/sounds/loops/horror_01_loop.xwav") + volume:0.15*music_level, + autoplay: false, loop: true, + }); + sounds.horror02 = new Howl({ + src: [url_factory("/sounds/loops/horror_02_loop.ogg")], + volume:0.15*music_level, + autoplay: false, loop: true, + }); + sounds.casual05 = new Howl({ + src: [url_factory("/sounds/loops/casual_05_loop.ogg")], + volume:0.2*music_level, + autoplay: false, loop: true, + }); + sounds.casual02 = new Howl({ + src: [url_factory("/sounds/loops/casual_02_loop.ogg")], + volume:0.2*music_level, + autoplay: false, loop: true, + }); + sounds.rpg07 = new Howl({ + src: [url_factory("/sounds/loops/rpg_07_loop.ogg")], + volume:0.2*music_level, + autoplay: false, loop: true, + }); + sounds.rpg08 = new Howl({ + src: [url_factory("/sounds/loops/rpg_08_loop.ogg")], // ,,url_factory("/sounds/loops/rpg_08_loop.xwav") + volume:0.2*music_level, + autoplay: false, loop: true, + }); + sounds.rpg10 = new Howl({ + src: [url_factory("/sounds/loops/rpg_10_loop.ogg")], + volume:0.2*music_level, + autoplay: false, loop: true, + }); + sounds.rpg14 = new Howl({ + src: [url_factory("/sounds/loops/rpg_14_loop.ogg")], + volume:0.2*music_level, + autoplay: false, loop: true, + }); + sounds.rpg16 = new Howl({ + src: [url_factory("/sounds/loops/rpg_16_loop.ogg")], + volume:0.2*music_level, + autoplay: false, loop: true, + }); + // sounds.rpg20 = new Howl({ + // src: [url_factory("/sounds/loops/rpg_20_loop.xogg")], + // volume:0.4*music_level, + // autoplay: false, loop: true, + // }); +} + +var current_music=null; +function reflect_music() +{ + var the_music=sounds.rpg08; + if(!window.Howl) {sound_music=false; sound_sfx=false; add_log("Sound issue (Howl). Turned sound off"); return;} + if(!sound_music) + { + if(current_music) current_music.stop(); + current_music=null; + return; + } + if(current_map=="tavern") the_music=sounds.rpg10; + if(in_arr(current_map,["cave","halloween","spookytown"]) || current_map.startsWith("level")) the_music=sounds.rpg14; + if(current_map.startsWith("winter_inn")) the_music=sounds.rpg16; + if(current_map=="desertland") the_music=sounds.rpg07; + if(current_map=="winterland" || xmas_tunes) the_music=sounds.christmas; + if(current_map=="bank") the_music=sounds.casual05; + if(current_map=="goobrawl") the_music=sounds.casual02; + if(current_map=="crypt" || current_map=="winter_instance") the_music=sounds.horror02; + if(current_music!=the_music && the_music) + { + if(current_music) current_music.stop(); + current_music=the_music; + the_music.play(); + } +} + +function sound_on() +{ + if(is_electron) Cookies.set('music','on',{ expires:12*365}); + else if(character) set_setting(real_id,"music","on"); + sound_music='1'; init_music(); reflect_music(); + $('.musicoff').hide(); + $('.musicoffi').hide(); + $('.musicon').show(); + $('.musiconi').css("display","inline-block"); +} + +function sound_off(just_ui) +{ + if(!just_ui) + { + if(is_electron) Cookies.set('music','off',{ expires:12*365}); + else if(character) set_setting(real_id,"music","off"); + sound_music=''; reflect_music(); + } + $('.musicon').hide(); + $('.musiconi').hide(); + $('.musicoff').show(); + $('.musicoffi').css("display","inline-block"); +} + +function sfx_on() +{ + if(is_electron) Cookies.set('sfx','on',{ expires:12*365}); + else if(character) set_setting(real_id,"sfx","on"); + sound_sfx='1'; + init_fx(); + $('.sfxoff').hide(); + $('.sfxoffi').hide(); + $('.sfxon').show(); + $('.sfxoni').css("display","inline-block"); +} + +function sfx_off() +{ + if(is_electron) Cookies.set('sfx','off',{ expires:12*365}); + else if(character) set_setting(real_id,"sfx","off"); + sound_sfx=''; + $('.sfxon').hide(); + $('.sfxoni').hide(); + $('.sfxoff').show(); + $('.sfxoffi').css("display","inline-block"); +} + +function gprocess_game_data() +{ + if(no_graphics) + { + for(var name in G.geometry) + { + var GEO=G.geometry[name]; + if(!GEO.data) continue; + GEO.data.tiles=[]; + GEO.data.placements=[]; + GEO.data.groups=[]; + } + } + process_game_data(); +} + +var BACKUP={}; + +function reload_data() +{ + BACKUP.maps=G.maps; + prop_cache={}; + //$("head").append(""); + $.getScript("/data.js?reload=1×tamp="+(new Date().getTime())); +} + +function apply_backup() +{ + G.maps=BACKUP.maps; + gprocess_game_data(); + BACKUP={}; +} + +function bc(t,type) +{ + var $this=$(t); + if($this.hasClass('disabled')) return 1; + pcs(type); + return 0; +} + +function btc(event,type) +{ + stpr(event); + pcs(type); +} + +function show_loader(){} +function hide_loader(){} + +function ui_inspect(e) +{ + var args={}; + if(e.type=="character") args.character_ui=true,args.name=e.id; + if(e.type=="monster") args.monster_ui=e.mtype,args.name=e.id; + show_json(game_stringify(e,'\t'),args); +} + +function alert_json(j){alert(JSON.stringify(j));} + +// PIXI.Sprite.prototype.toJSON=function(){ +// // maybe make this work: https://stackoverflow.com/a/48961962 +// var l=["x","y","width","height"],json={}; +// for(var p in this) l.push(p); +// l.forEach(function(p){ +// json[p]=this[p]; +// }) +// return json; +// } + +var ignored_properties=["transform","parent","displayGroup","parentGroup","vertexData","animations","tiles","placements","default","children","tempDisplayObjectParent","cachedTint","vertexTrimmedData","hp_bar","blendMode","filterArea","worldAlpha","pluginName","roundPixels","updateOrder","displayOrder","shader","accessible","interactiveChildren","hitArea","cursor","zOrder","accessibleTitle","accessibleHint","parentLayer","layerableChildren","trackedPointers","interactive","tabIndex","zIndex","buttonMode","renderable","cxc"]; + +function game_stringify(obj,third) +{ + var seen = []; + try{ + //TODO: Replicate changes on game_stringify_simple + if(obj===undefined) return "undefined"; + var result=JSON.stringify(obj, function(key, val) { + if(in_arr(key,ignored_properties) || key.indexOf("filter_")!=-1 || key[0]=="_") return; + if(key=="data" && obj[key] && obj[key].x_lines) return; + if (val != null && typeof val == "object") { + if (seen.indexOf(val) >= 0) { + return; + } + seen.push(val); + if("x" in val) // amplify - also in common_functions.js safe_stringify + { + var new_val={}; + ["x","y","width","height"].forEach(function(p){ + if(p in val) new_val[p]=val[p]; + }); + for(var p in val) new_val[p]=val[p]; + val=new_val; + } + } + return val; + },third); + try{ + if("x" in obj) // amplify - also in common_functions.js safe_stringify + { + result=JSON.parse(result); + result.x=obj.x; + result.y=obj.y; + result=JSON.stringify(result,undefined,third); + } + }catch(e){} + return result; + } + catch(e) + { + console.log(e); + return "game_stringify_exception"; + } +} + +function game_stringify_simple(obj,third) +{ + try{ + if(obj===undefined) return "undefined"; + var result=JSON.stringify(obj, function(key, val) { + if(in_arr(key,ignored_properties) || key.indexOf("filter_")!=-1 || key[0]=="_") return; + if(key=="data" && obj[key] && obj[key].x_lines) return; + if (val != null && typeof val == "object") { + if("x" in val) // amplify - also in common_functions.js safe_stringify + { + var new_val={}; + ["x","y","width","height"].forEach(function(p){ + if(p in val) new_val[p]=val[p]; + }); + for(var p in val) new_val[p]=val[p]; + val=new_val; + } + } + return val; + },third); + try{ + if("x" in obj) // amplify - also in common_functions.js safe_stringify + { + result=JSON.parse(result); + result.x=obj.x; + result.y=obj.y; + result=JSON.stringify(result,undefined,third); + } + }catch(e){} + return result; + } + catch(e) + { + return "game_stringify_simple_exception"; + } +} + +function syntax_highlight(json) { + json = json.replace(/&/g,'&').replace(//g,'>'); + return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) { + var cls = 'shnumber'; + if (/^"/.test(match)) { + if (/:$/.test(match)) { + cls = 'shkey'; + } else { + cls = 'shstring'; + } + } else if (/true|false/.test(match)) { + cls = 'shboolean'; + } else if (/null/.test(match)) { + cls = 'shnull'; + } + return ''+match+''; + }); +} + +jQuery.fn.all_html = function() { + return jQuery('
').append(this.eq(0).clone()).html(); +}; + +jQuery.fn.shtml=function(r) { // simplified/processed html for editable div's [26/07/18] + var e=jQuery(this); + var val=e.html(); + val=(""+val).replace_all(",","").replace_all(".","").replace_all("\n","").replace_all(" ","").replace_all("
",""); + return val; +}; + +jQuery.fn.rval=function(r) { + var e=jQuery(this); + var val=e.val(); + if(r==undefined) r=''; + e.val(r); + return val; +}; + +jQuery.fn.cfocus=function() { // Focusing an empty contenteditable is unreliable at this time [27/08/18] + var html=jQuery(this).html(); + var def="1"; + if(!(html||"").replace_all(" ","").length) + { + if(jQuery(this).data('default')!==undefined) def=jQuery(this).data('default'); + jQuery(this).html(def); + } + var val=jQuery(this).focus(); + if(def=="\u00a0") document.execCommand('delete', false, null); + return val; +}; + +jQuery.fn.codemirror=function(args){ + if(!args) args={}; + return this.each(function(){ + var $this=jQuery(this); + var value=args.value||$this.html(); + value=value.replace_all("&","&").replace_all(">",">").replace_all("<","<") + if(args.trim || $this.hasClass("trimnl")) + { + while(value[0]=="\n") value=value.substr(1,value.length); + while(value[value.length-1]=="\n") value=value.substr(0,value.length-1); + } + var codemirror=CodeMirror(function(current){$this.replaceWith(current);},{ + value:value, + mode:"javascript", + indentUnit:4, + indentWithTabs:true, + lineWrapping:true, + lineNumbers:true, + gutters:["CodeMirror-linenumbers","lspacer"], + theme:"pixel", + cursorHeight:0.75, + /*,lineNumbers:true*/ + }); + var $cm=$(codemirror.getWrapperElement()); + if($this.hasClass("executeb")) + { + $cm.append("
Execute!
") + } + if(args.focus) codemirror.focus(); + if(args.hints) listen_for_hints(codemirror); + }); +}; + +jQuery.fn.rfval=function(r) { + var val=jQuery(this).rval(r); + $(":focus").blur(); + return val; +}; + +function stkp(event) +{ try { + if(event=="manual") return; + event.preventDefault(); + event.stopPropagation(); +} catch(e){ } } + +function stprlink(event) // to make modal click catchers let clicks pass, for electron logic [05/02/19] +{ + try{ + if(event.target.tagName.toLowerCase() === 'a') return true; + event.stopPropagation(); + } + catch(e){} + return false; +} + +function stpr(event) +{ try { + if(event=="manual") return; + // if(event.stopImmediatePropagation) event.stopImmediatePropagation(); + event.stopPropagation(); + // event.preventDefault(); - recently removed this, as, on the payments UI, when the link click propagates, it was cancelled by this [24/08/16] +} catch(e){ } } + +/* SCREENSHOTS */ + +function clear_ui() +{ + $("body").children().each(function(){ + if(this.tagName!="CANVAS") $(this).remove(); + $("iframe").remove(); + }); +} + +function clear_ui2() +{ + $("body").children().each(function(){ + if(this.tagName!="CANVAS" && this.id!="topleftcorner") $(this).remove(); + $("iframe").remove(); + }); +} + +function storage_get(name) +{ + if(is_electron) + { + if(!electron_store) + { + var Store=require('electron-store'); + electron_store=new Store(); + } + return electron_store.get(name); + } + else + { + return window.localStorage.getItem(name); + } +} + +function storage_set(name,value) +{ + if(is_electron) + { + if(!electron_store) + { + var Store=require('electron-store'); + electron_store=new Store(); + } + electron_store.set(name,value); + } + else + { + return window.localStorage.setItem(name,value); + } +} + +/* ELECTRON */ + +var manifest=null; +var electron=null,path=null,electron_store=null,fs=null,ide_root="/gg/"; +function url_factory(url) +{ + try{ + if(is_electron && !manifest) + { + if(!electron) electron=require('electron'); + if(!path) path=electron.remote.require('path'); // #ELECTRON 6 + manifest=require(path.resolve(electron.remote.app.getAppPath(), './manifest.js')); + } + else if(!manifest) manifest={}; + var bare=url.split("?v=")[0],version=url.split("?v=")[1]; + if(manifest[bare]) + { + if(!version || manifest[bare].v==version) + { + var lpath=path.resolve(electron.remote.app.getAppPath(),"./files"+bare) + // console.log("Loaded "+bare+" locally: "+lpath); + return "file://"+lpath; + } + } + } + catch(e) + { + console.log("url_factory: "+e); + } + return url; +} + +function filename_to_cdata(oname) +{ + if(oname.length<4) return null; + var name=oname.substr(0,oname.length-3); + var slot=name.split("."); + if(slot.length<2) return; + slot=parseInt(slot[slot.length-1]); + name=name.substr(0,name.length-(""+slot).length-1); + var valid=false; + if(1<=slot && slot<=100) valid=true; + X.characters.forEach(function(c){if(c.id==slot) valid=true;}); + // console.log((name+"."+slot+".js")+"|"+oname); + if((name+"."+slot+".js")!=oname) valid=false; + name.split("").forEach(function(c){ if(!valid_file_chars.includes(c)) valid=false; }); + if(!valid) return null; + return {name:name,slot:slot,file:oname}; +} + +function get_code_file(name) +{ + var filename=to_filename(name); + for(var slot in code_ref) + { + if(slot==name || code_ref[slot].name==filename) + { + var folder=ide_root+"/adventureland/characters"; + if(parseInt(slot)<=100) folder=ide_root+"/adventureland/codes"; + return fs.readFileSync(folder+"/"+code_ref[slot].file,"utf8"); + } + } + return null; +} + +async function save_code_file(num,data,v) // only "code" +{ + var folder=ide_root+"/adventureland/characters",filename=X.codes[num][0]+"."+num+".js"; + if(parseInt(num)<=100) folder=ide_root+"/adventureland/codes"; + if(code_ref[num]) await fs.promises.copyFile(folder+"/"+code_ref[num].file,ide_root+"/history/"+code_ref[num].slot+".js").catch(); + file_op[filename]=new Date(); await fs.promises.writeFile(folder+"/"+filename,data.toString(),"utf8"); file_op[filename]=new Date(); + var cdata=filename_to_cdata(filename); + code_ref[cdata.slot]=cdata; code_ref[cdata.slot].v=v; + await fs.promises.stat(folder+"/"+filename).then(async (stats)=>{ + code_ref[cdata.slot].m=stats&&stats.mtimeMs; + if(!ec_initial) await fs.promises.writeFile(ide_root+"/data.json",JSON.stringify(code_ref),"utf8"); + }); + add_log("Saved locally: "+X.codes[num][0]+"."+num+".js","#5BAC57"); +} + +async function remove_code_file(num) // only "servers_and_characters" +{ + var folder=ide_root+"/adventureland/characters"; + if(parseInt(num)<=100) folder=ide_root+"/adventureland/codes"; + if(code_ref[num] && (!flag_new_code[num] || ssince(flag_new_code[num])>6)) + { + var fname=code_ref[num].file; + file_op[fname]=new Date(); + add_log("Moved to /history: "+code_ref[num].file,"#8063A9"); + await fs.promises.copyFile(folder+"/"+code_ref[num].file,ide_root+"/history/"+code_ref[num].slot+".js").catch(); + await fs.promises.unlink(folder+"/"+code_ref[num].file); + delete code_ref[num]; + if(!ec_initial) await fs.promises.writeFile(ide_root+"/data.json",JSON.stringify(code_ref),"utf8"); + file_op[fname]=new Date(); + } +} + +async function download_code_file(num,dynamic) +{ + if(dynamic && code_ref[num]) + { + var folder=ide_root+"/adventureland/characters",filename=X.codes[num][0]+"."+num+".js"; + if(parseInt(num)<=100) folder=ide_root+"/adventureland/codes"; + await fs.promises.copyFile(folder+"/"+code_ref[num].file,ide_root+"/history/"+code_ref[num].slot+".js").catch(); + } + await api_call("load_code",{name:num,run:'',log:false,save:true},{promise:true}); + if(file_op_queue[num] && file_op_queue[num][0]=="save") + { + await save_code_file(file_op_queue[num][1],file_op_queue[num][2],file_op_queue[num][3]); + delete file_op_queue[num]; + } +} + +var file_op_queue={}; +async function one_file_op(){ + if(ec_initial) return setTimeout(async function(){ await one_file_op(); },1600); + var done=false; + if(!done) + for(var slot in file_op_queue) + { + var op=file_op_queue[slot]; + if(op[0]=="remove") + { + await remove_code_file(op[1]); + done=true; + delete file_op_queue[slot]; + break; + } + } + if(!done) + for(var slot in file_op_queue) + { + var op=file_op_queue[slot]; + if(op[0]=="save") + { + await save_code_file(op[1],op[2],op[3]); + done=true; + delete file_op_queue[slot]; + break; + } + } + if(!done) + for(var slot in file_op_queue) + { + var op=file_op_queue[slot]; + if(op[0]=="download") + { + await download_code_file(op[1],true); + done=true; + delete file_op_queue[slot]; + break; + } + } + setTimeout(async function(){ await one_file_op(); },1600); +} +setTimeout(async function(){ await one_file_op(); },1600); + +async function process_file(folder,cdata) +{ + var new_m=null,change=true,deleted=false; + await fs.promises.stat(folder+"/"+cdata.file).then((stats)=>{new_m=stats.mtimeMs;}).catch(()=>{ deleted=true; }); + if(deleted) // live update deletion + { + change=false; + setTimeout(function(num,fname){ + return function(){ + if(code_ref[num] && code_ref[num].file==fname) // make sure it's not renamed + show_confirm("Are you sure you want to delete "+cdata.file+"?",["#D06631","Yes"],"No!",function(slot){return function(){ api_call("save_code",{name:"DELETE",slot:slot,electron:true},{promise:true}); hide_modal(true);}}(num)); + } + }(cdata.slot,cdata.file),5000); + } + else if(!code_ref[cdata.slot] && !X.codes[cdata.slot]) // new file + { + add_log("Uploading new code: "+cdata.file,"#5BAC57"); + flag_new_code[cdata.slot]=new Date(); + await fs.promises.readFile(folder+"/"+cdata.file,"utf8").then(async (data)=>{ + if(character && cdata.slot==code_slot) handle_information([{type:"code",code:data.toString()}]); + if(data) await api_call("save_code",{code:data.toString(),slot:cdata.slot,name:cdata.name,auto:true,electron:true},{promise:true}); + }).catch(()=>{}); + code_ref[cdata.slot]=cdata; code_ref[cdata.slot].v=1; code_ref[cdata.slot].m=new_m; + flag_new_code[cdata.slot]=new Date(); + await sleep(1200); + } + else if(code_ref[cdata.slot] && !X.codes[cdata.slot]) // deleted file + { + add_log("Moved to /history: "+cdata.file,"#8063A9"); + await fs.promises.copyFile(folder+"/"+cdata.file,ide_root+"/history/"+cdata.slot+".js").catch(()=>{}); + file_op[cdata.file]=new Date(); await fs.promises.unlink(folder+"/"+cdata.file); file_op[cdata.file]=new Date(); + delete code_ref[cdata.slot]; + await sleep(1200); + } + else if(code_ref[cdata.slot] && (code_ref[cdata.slot].m!=new_m || cdata.name!=X.codes[cdata.slot][0] || X.codes[cdata.slot][1]!=code_ref[cdata.slot].v)) // file changed or name changed or external update + { + if(code_ref[cdata.slot] && X.codes[cdata.slot][1]>code_ref[cdata.slot].v && code_ref[cdata.slot].m!=new_m) // clash + { + add_log("Moved to /clash: "+cdata.file,"#8063A9"); + await fs.promises.access(ide_root+"/adventureland/clash").catch(async function(){ await fs.promises.mkdir(ide_root+"/adventureland/clash"); }); + await fs.promises.copyFile(folder+"/"+cdata.file,ide_root+"/adventureland/clash/"+cdata.file+".c"+randomStr(10)).catch(()=>{}); + file_op[cdata.file]=new Date(); await fs.promises.unlink(folder+"/"+cdata.file); file_op[cdata.file]=new Date(); + delete code_ref[cdata.slot]; + } + if(!code_ref[cdata.slot] || X.codes[cdata.slot][1]>code_ref[cdata.slot].v) + { + add_log("Remote update: "+cdata.file); + await download_code_file(cdata.slot); + if(cdata.file && cdata.name!=X.codes[cdata.slot][0]) + { + add_log("Old file deleted: "+cdata.file); // delete old file name + file_op[cdata.file]=new Date(); await fs.promises.unlink(folder+"/"+cdata.file).catch(); file_op[cdata.file]=new Date(); + } + } + else + { + // add_log("Uploading code: "+cdata.file); + await fs.promises.readFile(folder+"/"+cdata.file,"utf8").then(async (data)=>{ + if(character && cdata.slot==code_slot) handle_information([{type:"code",code:data.toString()}]); + if(data) await api_call("save_code",{code:data.toString(),slot:cdata.slot,name:cdata.name,auto:true,electron:true},{promise:true}); + }).catch(()=>{}); + code_ref[cdata.slot]=cdata; code_ref[cdata.slot].v=X.codes[cdata.slot][1]; code_ref[cdata.slot].m=new_m; + } + await sleep(1200); + } + else if(!code_ref[cdata.slot] && !ec_initial) // happens after rename + { + add_log("Uploading code: "+cdata.file,"#5BAC57"); + await fs.promises.readFile(folder+"/"+cdata.file,"utf8").then(async (data)=>{ + if(character && cdata.slot==code_slot) handle_information([{type:"code",code:data.toString()}]); + if(data) await api_call("save_code",{code:data.toString(),slot:cdata.slot,name:cdata.name,auto:true,electron:true},{promise:true}); + }).catch(()=>{}); + code_ref[cdata.slot]=cdata; code_ref[cdata.slot].v=1; code_ref[cdata.slot].m=new_m; + flag_new_code[cdata.slot]=new Date(); + await sleep(1200); + } + else change=false; + if(!ec_initial && change) await fs.promises.writeFile(ide_root+"/data.json",JSON.stringify(code_ref),"utf8"); +} + +var code_ref={},found={},flag_new_code={},ec_initial=true; +var file_op={}; // to prevent race conditions +async function electron_code_sync_logic() +{ + try{ + if(!electron) electron=require('electron'); + if(!path) path=require('path'); + if(!fs) try{ fs=require('fs-extra'); }catch(e){ console.error("fs-extra import issue"); fs=require('fs'); }; + ide_root=path.join(electron.remote.app.getPath('appData'), electron.remote.app.getName()); + await fs.promises.access(ide_root+"/autosync"+user_id).catch(async function(){ await fs.promises.mkdir(ide_root+"/autosync"+user_id); }); + ide_root=ide_root+"/autosync"+user_id; + await fs.promises.access(ide_root+"/adventureland").catch(async function(){ await fs.promises.mkdir(ide_root+"/adventureland"); }); + await fs.promises.access(ide_root+"/adventureland/characters").catch(async function(){ await fs.promises.mkdir(ide_root+"/adventureland/characters"); }); + await fs.promises.access(ide_root+"/adventureland/codes").catch(async function(){ await fs.promises.mkdir(ide_root+"/adventureland/codes"); }); + await fs.promises.access(ide_root+"/adventureland/libraries").catch(async function(){ await fs.promises.mkdir(ide_root+"/adventureland/libraries"); }); + await fs.promises.access(ide_root+"/history").catch(async function(){ await fs.promises.mkdir(ide_root+"/history"); }); + await fs.promises.readFile(ide_root+"/data.json","utf8").then((data)=>{code_ref=JSON.parse(data)||{};}).catch(()=>{code_ref={};}); + // console.log(code_ref); + await fs.promises.readdir(ide_root+"/adventureland/characters").then(async (files)=>{ + for(var i=0;i{ + add_log("/adventureland/codes: "+e,"red"); + }); + await fs.promises.readdir(ide_root+"/adventureland/codes").then(async (files)=>{ + for(var i=0;i{ + add_log("/adventureland/codes: "+e,"red"); + }); + for(var slot in code_ref) + if(!found[slot]) + { + delete code_ref[slot]; // best to just ignore offline deleted files + } + ec_initial=false; + await fs.promises.writeFile(ide_root+"/data.json",JSON.stringify(code_ref),"utf8"); + for(var slot in X.codes) + { + if(!code_ref[slot]) + { + // add_log("X.Codes Missing: "+slot); + file_op_queue[slot]=["download",slot,X.codes[slot][1]]; + } + } + if(storage_get("lib_version")!=VERSION+""+user_id) + { + api_call("load_libraries"); + } + electron_start_watching(); + } + catch(e) + { + console.log("electron_code_sync_logic: "+e); + } +} + +var watcher1=null,watcher2=null; +function electron_start_watching() +{ + if(watcher1) return; + watcher1=fs.watch(ide_root+"/adventureland/characters",function(event,fname){ + if(file_op[fname] && mssince(file_op[fname])<3600) return; + console.log("watcher1: "+fname); + var cdata=filename_to_cdata(fname); + if(cdata) process_file(ide_root+"/adventureland/characters",cdata); + else add_log("Invalid filename: "+fname,"#A88690"); + }); + watcher2=fs.watch(ide_root+"/adventureland/codes",function(event,fname){ + if(file_op[fname] && mssince(file_op[fname])<3600) return; + console.log("watcher2: "+fname); + var cdata=filename_to_cdata(fname); + if(cdata) process_file(ide_root+"/adventureland/codes",cdata); + else add_log("Invalid filename: "+fname,"#A88690"); + }); +} + +function electron_stop_watching() +{ + if(watcher1) watcher1.close(),watcher2.close(),watcher1=watcher2=null; +} + +function electron_open_codes() +{ + if(!electron) electron=require('electron'); + if(!path) path=require('path'); + var iroot=path.join(electron.remote.app.getPath('appData'), electron.remote.app.getName())+"/autosync"+user_id; + show_alert("Import the 'adventureland' folder to your IDE. 'history' folder keeps only one previous local version. If you overwrite a code slot by mistake, you can recover it immediately from the 'history' folder."); + const {shell} = require('electron'); + try{ + shell.openItem(iroot); + }catch(e){ + shell.openExternal('file://'+iroot); + } +} + +function electron_reset() +{ + if(!electron) electron=require('electron'); + if(!path) path=require('path'); + if(!fs) try{ fs=require('fs-extra'); }catch(e){ console.error("fs-extra import issue"); fs=require('fs'); }; + getAppPath = path.join(electron.remote.app.getPath('appData'), electron.remote.app.getName()); + fs.unlink(getAppPath, function(){ + alert("App data cleared"); + electron.relaunch(); + electron.exit(); + }); +} + +// /pure_eval electron_dev_tools() +function electron_dev_tools() +{ + if(!electron) electron=require('electron'); + var ewindow = electron.remote.getCurrentWindow(); + ewindow.openDevTools({mode:'detach'}); +} + +var fullscreen=false; +function electron_fullscreen(val) +{ + if(val==undefined) val=!fullscreen; + fullscreen=val; + if(!electron) electron=require('electron'); + var ewindow = electron.remote.getCurrentWindow(); + ewindow.setFullScreen(fullscreen); +} + +function electron_screenshot(opt,cb) +{ + cb = cb || function () {}; + if(!opt) opt={delay:0}; + if(!cb) cb=function(){ console.log('Screenshot taken!'); }; + if(!opt.filename) opt.filename="AL Screenshot "+(new Date())+".png"; + var remote; + try { + remote = require('' + 'electron').remote + } catch (e) { + remote = require('' + 'remote') + } + setTimeout(function () { + remote.getCurrentWindow().capturePage(function handleCapture (img) { + remote.require('fs').writeFile(opt.filename, img.toPNG(), cb) + }) + }, opt.delay) +} + +function electron_mas_receipt() +{ + try{ + if(!electron) electron=require('electron'); + var receipt=electron.remote.app.getPath('exe'); + receipt=receipt.split(".app/Contents/")[0]+".app/Contents/_MASReceipt/receipt"; + // console.log(receipt); + return electron.remote.require('fs').readFileSync(receipt).toString("base64"); + }catch(e) + { + console.log(e); + } + return ""; +} + +function electron_steam_ticket() +{ + try{ + return storage_get("ticket")||""; + } + catch(e){ + console.log(e); + } + return ""; +} + +function electron_get_data() +{ + try{ + if(!electron) electron=require('electron'); + return electron.remote.getCurrentWindow().cdata||{}; + }catch(e) + { + return {}; + } +} + +function electron_http_mode(val) +{ + if(val===undefined) val=true; + storage_set("http_mode",val); +} + +function electron_get_http_mode() +{ + try{ + return storage_get("http_mode"); + } + catch(e){ + console.log(e); + } + return false; +} + +function electron_is_main() +{ + try{ + if(!electron) electron=require('electron'); + if(electron.remote.getCurrentWindow().webContents.browserWindowOptions.sideWindow) return false; + } + catch(e){console.log(e);} + return parent==window; +} + +function electron_add_webview(url) +{ + if(!url) url="http://thegame.com/character/GG/in/EU/I/"; + $("body").append(""); +} \ No newline at end of file diff --git a/js/game.js b/js/game.js new file mode 100644 index 0000000..80e389a --- /dev/null +++ b/js/game.js @@ -0,0 +1,6181 @@ +var is_game=1,is_server=0,is_code=0,is_pvp=0,is_demo=0,gameplay="normal"; +var inception=new Date(); +/* performance flags */ +/* + Current performance hogs + - Map tiling + - Disappearing Texts / Garbage Collection + - Inventory / Player+Slots UI Refreshes / Event+Garbage Collection +*/ +var scale=parseInt(scale); +var round_xy=true,floor_xy=false; //map +// IMPORTANT: Test things on the Macbook screen, Dell screens simply suck [19/05/18] +var round_entities_xy=false; +var offset_walking=true; // entities, to fix overflowing sprites +var antialias=false,mode_nearest=true; // mode_nearest fixes the overflows in general +var gtest=false; // glitch test - cause: pixellated :( +var mode={ + "dom_tests":0, // huntin the dom leak [20/08/16] + "dom_tests_pixi":0, + "bitmapfonts":0, + "debug_moves":0, + "destroy_tiles":1, + "log_incoming":0, + "cosmetics":0, + "empty_borders_darker":1, + "ltbl":1, // let there be light [06/08/22] +}; +var paused=false; +var log_flags={ //over-written at base_script + "timers":1, + "map":0, + "entities":0, + "xy_corrections":0, +}; +var ptimers=true; +// var cached_map=location.search.indexOf("fast")!=-1; // RenderTexture +var mdraw_mode="redraw",mdraw_border=40; +var mdraw_tiling_sprites=false; // #GTODO: perfect+launch this at one point [20/08/16] - so slow [22/03/20] +var manual_stop=false; +var manual_centering=true; +var high_precision=false; +var retina_mode=false; // conditionally set at DOMContentLoaded +var text_quality=2; +/* modes */ +var bw_mode=false; // border_mode in base_script now +var character_names=false; +var hp_bars=true; +/* timers */ +var last_interaction=new Date(),afk_edge=60,mm_afk=false; // [AFK] +last_interaction.setYear(1970); +var last_drag_start=new Date(); +var last_npc_right_click=new Date(); // to patch the propagation bug +/* */ +var block_right_clicks=true; +var mouse_only=true; +var the_code="",code_slot=0,code_change=false,new_code_slot=undefined; +var server_region="EU",server_identifier="I",server_name="",ipass=""; +var real_id='',character=null,observing=null,map=null,resources_loaded=false,socket_ready=false,socket_welcomed=false,game_loaded=false,friends=[]; +var ch_disp_x=0,ch_disp_y=0; // For shaking the character without modifying coordinates manually [22/06/18] +var head_x=0,head_y=0; // For head gestures [25/09/18] +var tints=[]; +var entities={},future_entities={players:{},monsters:{}},pull_all_next=false,clean_house=false; +// Important: set pulling_all to true, so the same logic applies on first connect [12/10/18] +// Removed the pull_all logic, simplifying [26/01/20] +var text_layer,monster_layer,player_layer,chest_layer,map_layer,separate_layer,entity_layer; +var rip=false; +var heartbeat=new Date(),slow_heartbeats=0; +var ctarget=null,ctoggled=null; // character's target +var xtarget=null; // secondary target +var mtarget=null; // mouse target +var textures={},C={},FC={},SS={},SSU={}; // cache textures here +var M={},GEO={}; // M - old x_lines/y_lines, - GEO - new logic +/* start map entities */ +var total_map_tiles=0; +var tiles=null,dtile=null,wtile=null; // cached_map entities +var map_npcs=[],map_doors=[],map_nights=[],map_lights=[],map_animatables={}; +var map_tiles=[],map_entities=[],map_machines={},dtile_size=32,dtile_width=0,dtile_height=0,wtile_name=null,wtile_width=0,wtile_height=0; +var map_animations={}; +var quirks={}; +var water_tiles=[],last_water_frame=-1; +var drawings=[],code_buttons={}; // user drawings +var chests={},party_list=[],party={}; +var tracker={}; +var merchants={}; +var tile_sprites={},tile_textures={},sprite_last={}; +var first_coords=false,first_x=0,first_y=0; +var last_refxy=0,ref_x=0,ref_y=0; +var last_light=new Date(0); +var current_map="main",current_in="main",draw_map="main"; +var transporting=false; +/* */ +var current_status="",last_status=""; +/* ui flags */ +var topleft_npc=false,merchant_id=null,inventory=false,inventory_openef_for=null,code=false,pvp=false,skillsui=false,exchange_type=""; +var topright_npc=false; +var transports=false; +var purpose="buying"; +var next_minteraction=null; +var next_side_interaction=null; +/* event vars */ +var events={ + "abtesting":false, + "duel":false, +}; +/* */ +var code_run=false,code_active=false,actual_code=false,CC={}; // run from game, active from code [30/10/16] +var reload_state=false,reload_timer=null,first_entities=false; +var blink_pressed=false,last_blink_pressed=new Date(); +var arrow_up=false,arrow_right=false,arrow_down=false,arrow_left=false; +var force_draw_on=false; +var use_layers=false; +var draws=0,in_draw=false; +var keymap={},skillbar=[]; +var secondhands=[],s_page=0,lostandfound=[],l_page=0; +var page={title:"Adventure Land",url:"/"}; +var I={}; // instance data +var S={}; // server data +var ST=new Date(); // server time +var CLI_OUT=[]; // CLI outgoing messages +var CLI_IN=[]; // CLI incoming messages +var options={ + "move_with_arrows":true, + "code_fx":false, + "show_names":false, + "move_with_mouse":false, + "always_hpn":false, + "always_names":false, + "retain_upgrades":false, + "friendly_fire":false, + "bank_max":false, + "directional_sfx":false, +}; +var SZ={ + "font":"Pixel", + "normal":18, + "large":24, + "huge":36, + "chat":18, +}; + +setInterval(function(){ + if(reload_state) + { + try{ + var data=storage_get("reload"+server_region+server_identifier); + if(data) + { + data=JSON.parse(data); + data.time=new Date(data.time); + if(new Date()reload_timer) + { + api_call("can_reload",{region:server_region,pvp:is_pvp||'',name:server_identifier}); + add_log("Echo Sent","gray"); + reload_timer=future_s((window.rc_delay||0)+3+parseInt(Math.random()*2)); + } + if(reload_state=="synced" && new Date()>reload_timer) + { + reload_state=false; + if(is_cli) CLI_OUT.push({"type":"kill"}); + else window.location.href=page.url; // location.reload(); + } + } + if(!game_loaded) return; + var ms_since=mssince(heartbeat),now_date=new Date(); + if(ms_since>900) slow_heartbeats++; + else if(ms_since<600) slow_heartbeats=0; + if(is_hidden() && !is_demo) // slow_heartbeats>3 + { + // if(!code_run) pull_all=true; - this would trigger pull_all frequently with the manual draw logic in place [19/08/16] + // else pull_all_next=true; + pull_all_next=true; + } + if(!is_hidden() && pull_all_next && socket) // ms_since<220 + { + console.log("pull_all_next triggered"); + pull_all_next=false; + socket.emit("send_updates",{}); + } + if(window.last_draw) + { + if((code_run || sound_sfx) && mssince(last_draw)>250) draw(0,1); // previously 500 + else if(!(code_run || sound_sfx) && mssince(last_draw)>15000) draw(0,1); + } + if(force_draw_on && force_draw_onafk_edge/2); + if(character) + { + if(!character.afk && ssince(window.last_interaction)>afk_edge) + { + character.afk=true; + socket.emit("property",{afk:true}); + } + if(character.afk && ssince(window.last_interaction)<=afk_edge) + { + character.afk=false; + socket.emit("property",{afk:false}); + } + if(mode.debug_moves) socket.emit("mreport",{x:character.real_x,y:character.real_y}); + } + // console.log(mssince(heartbeat)); 900 because chrome reduces heartbeat to 1000ms + heartbeat=new Date(); +},100); + +setInterval(function(){ + arrow_movement_logic(); +},200); + +function code_button() +{ + add_log("Executed"); + add_tint(".mpui",{ms:3000}); +} + +function observe_character(name) +{ + for(var i=0;i<(X.characters||[]).length;i++) + { + var ch=X.characters[i]; + if(ch.name==name && ch.secret) + { + for(var j=0;j
"+message+"
"); + } + + if(character) $("title").html(title_m+" - "+character.name); +} + +function position_map() +{ + if(character) map.real_x=character.real_x,map.real_y=character.real_y; + var x=width/2.0-map.real_x*scale,y=height/2.0-map.real_y*scale,change=false; + x=c_round(x); y=c_round(y); + if(map.x!=x) map.x=x,change=true; + if(map.y!=y) map.y=y,change=true; + if(change && dtile_size && window.dtile) + { + dtile.x=round(map.real_x-width/(scale*2.0)); + dtile.y=round(map.real_y-height/(scale*2.0)); + dtile.x=ceil(dtile.x/(dtile_size/1.0))*(dtile_size/1.0)-(dtile_size/1.0); + dtile.y=ceil(dtile.y/(dtile_size/1.0))*(dtile_size/1.0)-(dtile_size/1.0); + } + if(change && window.wtile) + { + wtile.x=round(map.real_x-width/(scale*2.0)); + wtile.y=round(map.real_y-height/(scale*2.0)); + wtile.x=ceil(wtile.x/(textures[wtile_name][0].width/1.0))*(textures[wtile_name][0].width/1.0)-(textures[wtile_name][0].width/1.0); + wtile.y=ceil(wtile.y/(textures[wtile_name][0].height/1.0))*(textures[wtile_name][0].height/1.0)-(textures[wtile_name][0].height/1.0); + } + if(character) + { + if(manual_centering) character.x=c_round(width/2.0+ch_disp_x),character.y=c_round(height/2.0+ch_disp_y); + else character.x=c_round(character.real_x),character.y=c_round(character.real_y); + } + // if(change && character) console.log("character x,y: "+character.x+","+character.y+" map x,y: "+map.x+","+map.y+" total x,y: "+(character.x-map.x)+","+(character.y-map.y)); +} + +function ui_logic() +{ + if(character && character.ctype=="mage") + { + if(b_pressed && map.cursor!="crosshair") map.cursor="crosshair"; + else if(!b_pressed && map.cursor=="crosshair") map.cursor="default"; + } +} + +var rendered_target={},last_target_cid=null,last_xtarget_cid=null,dialogs_target=null; +function reset_topleft() +{ + if(no_html) return; + var name='NO TARGET'; + var otarget=ctarget; // original target + ctarget=xtarget||ctarget; + if(ctarget && ctarget.dead && (!ctarget.died || ssince(ctarget.died)>3)) ctarget=null; + if(ctarget!=rendered_target) { last_target_cid=null; reset_inventory(1); } + if(dialogs_target && dialogs_target!=ctarget) $("#topleftcornerdialog").html(""),dialogs_target=null; + if(ctarget && topleft_npc) + { + if(topleft_npc && inventory) render_inventory(); + topleft_npc=false; + reset_inventory(); + } + + if(ctarget && ctarget.type=='monster' && last_target_cid!=ctarget.cid) + { + render_monster(ctarget); + } + else if(ctarget && ctarget.npc) + { + render_npc(ctarget); + } + else if(ctarget && ctarget.type=='character' && last_target_cid!=ctarget.cid) + { + render_character(ctarget); + } + else if(!ctarget && rendered_target!=null) + { + $("#topleftcornerui").html('
NO TARGET
'); + } + rendered_target=ctarget; + last_target_cid=ctarget && ctarget.cid; + + ctarget=otarget; +} + +function handle_entities(data,args) +{ + window.last_entities_received=data; + // if(data.type!="all" && pulling_all) return console.log("discarded 'entities' - pulling_all"); + // Commented the above section out [26/01/20] + if(data.type=="all") + { + if(!(args && args.new_map)) clean_house=true; + if(!first_entities) + { + first_entities=true; + if(character_to_load) + { + set_status("LOADING "+character_to_load); + try{ log_in(user_id,character_to_load,user_auth); }catch(e){console.log(e);} + character_to_load=false; + } + } + } + if(data.type=="all" && log_flags.entities) console.log("all entities "+new Date()); + if(0 && erec%100==1 && window.pako) + { + window.lastentities=data; + var rs=rough_size(data),ms; + var cs=new Date(); + var enc=pako.deflate(msgpack.encode(data)); + ms=mssince(cs); + console.log("entities%100 rough_size: "+rs+" enc_length: "+enc.length+" enc_in: "+ms+"ms") + } + if(character) + { + if(data.xy) last_refxy=new Date(),ref_x=data.x,ref_y=data.y; + else last_refxy=0; + } + for(var i=0;i120) // previously 40 [07/10/16] + { + current.real_x=monster.x; + current.real_y=monster.y; + if(log_flags.xy_corrections) console.log("manual x,y correction for: "+(current.name||current.id)); + } + speedm=simple_distance({x:current.real_x,y:current.real_y},{x:monster.going_x,y:monster.going_y})/(simple_distance(monster,{x:monster.going_x,y:monster.going_y})+EPS); + if(speedm>1.25 && log_flags.timers && log_flags.xy) console.log(current.id+" speedm: "+speedm); + current.moving=true; current.abs=false; + current.engaged_move=current.move_num; + current.from_x=current.real_x; + current.from_y=current.real_y; + current.going_x=monster.going_x; + current.going_y=monster.going_y; + calculate_vxy(current,speedm); + } +} +function process_entities() +{ + for(var id in future_entities.monsters) + { + var monster=future_entities.monsters[id]; + var current=entities[monster.id]; + // console.log(monster.type+" "+monster.id); + if(!current) + { + if(monster.dead) continue; + if(gtest) return; + try{ + current=entities[monster.id]=add_monster(monster); // #GTODO #IMPORTANT: Inspect where the type=undefined monster comes from + // console.log("added: "+current.id); + current.drawn=false; current.resync=true; + } + catch(e) + { + console.log("EMAIL HELLO@ADVENTURE.LAND WITH THIS: "+JSON.stringify(monster)); + if(is_sdk) alert(e+" "+JSON.stringify(monster)); + } + } + if(monster.dead) {current.dead=true; continue;} + sync_entity(current,monster); + (monster.events||[]).forEach(function(event){ + + // This routine originally hosted custom "mhit" events that replicated "hit" events + // It was too complicated due to the duplication of each routine + // Currently it can just piggyback regular events if mode.instant_monster_attacks is true + original_onevent.apply(socket,[{"type":2,"nsp":"/","data":event}]); + + }); + if(ctarget && ctarget.id==current.id) ctarget=current; + if(xtarget && xtarget.id==current.id) xtarget=current; + } + for(var id in future_entities.players) + { + var player=future_entities.players[id]; + // show_json(player); + var current=entities[player.id],original_rip=true; + if(current) original_rip=current.rip; + if(character && character.id==player.id) continue; + if(!current) + { + //alert_json(player); + if(player.dead) continue; + player.external=true; + player.player=true; + current=entities[player.id]=add_character(player); + current.drawn=false; current.resync=true; + if(mssince(last_light)<500) start_animation(current,"light"); + } + if(player.dead) {current.dead=true; continue;} + // if(current.dead) {console.log("Add a re-add logic!")}; Improved 'disappear' to change the id + sync_entity(current,player); + if(!original_rip && current.rip) + call_code_function("trigger_event","death",{id:current.id}); + if(ctarget && ctarget.id==current.id) ctarget=current; + if(xtarget && xtarget.id==current.id) xtarget=current; + } +} + +function on_disappear(data) +{ + // console.log("disappear: "+data.id); + if(future_entities.players[data.id]) delete future_entities.players[data.id]; // moving these outside the `if(entities[data.id])` condition should fix the non-disappearing entities issues [03/02/17] + if(future_entities.monsters[data.id]) delete future_entities.monsters[data.id]; + + if(entities[data.id]) + { + if(data.invis) assassin_smoke(entities[data.id].real_x,entities[data.id].real_y); + if(data.effect===1) start_animation(entities[data.id],"transport"); + entities["DEAD"+data.id]=entities[data.id]; + entities[data.id].dead=data.reason||true; + if(data.teleport) entities[data.id].tpd=true; + call_code_function("on_disappear",entities[data.id],data); + // console.log("disappear delete: "+data.id); + delete entities[data.id]; + } + else if(character && character.id==data.id) + { + if(data.invis) assassin_smoke(character.real_x,character.real_y); + call_code_function("on_disappear",character,data); + // if(data.effect) start_animation(entities[data.id],"transport"); + } +} + +var asp_skip={}; +["x","y","vx","vy","moving","abs","going_x","going_y","from_x","from_y","width","height","type","events","angle","skin","events","reopen"].forEach(function(s){asp_skip[s]=true;}) + +function adopt_soft_properties(element,data) +{ + if(element.me) + { + element.stats={}; + ["str","dex","int","vit","for"].forEach(function(p){element.stats[p]=data[p];}); + if(element.moving && element.speed && data.speed && element.speed!=data.speed) + { + element.speed=data.speed; + calculate_vxy(element); + } + if(data.abs) //[04/10/16] + { + element.moving=false; + if(element.me) resolve_deferreds("move",{reason:"abs"}); + } + element.bank=null; + } + else + { + element["in"]=current_in; + element.map=current_map; + } + ["team"].forEach(function(p){ if(!data.p) delete element[p];}); + if(element.type=="monster" && G.monsters[element.mtype]) + { + var def=G.monsters[element.mtype]; + var mapping=[["hp","hp"],["max_hp","hp"],["mp","mp"],["max_mp","mp"]]; + ["speed","xp","attack","frequency","rage","aggro","armor","resistance","damage_type","respawn","range","name","abilities","evasion","avoidance","reflection","dreturn","immune","cooperative","spawns","special","1hp","lifesteal","drops"].forEach(function(attr){mapping.push([attr,attr])}); + mapping.forEach(function(attr){ //same array as server.js monster_to_client + if(def[attr[1]]!==undefined && (data[attr[0]]===undefined || element[attr[0]]===undefined)) + { + element[attr[0]]=def[attr[1]]; + } + }); + } + if(element.type=="character") + { + ["damage_type"].forEach(function(attr){ + if(data[attr]) element[attr]=data[attr]; + }) + } + if(element.type=="character" && element.skin && element.skin!=data.skin && !element.rip) + { + if(!XYWH[data.skin]) data.skin="naked"; + element.skin=data.skin; + new_sprite(element,"full","renew"); + restore_dimensions(element); + } + // if(data.cash) {data.shells=data.cash; delete data.shells;} + for(prop in data) + { + if(asp_skip[prop]) continue; + element[prop]=data[prop]; + } + if(element.slots) + { + element.pzazz=0; + for(var slot in element.slots) + { + if(attire_slots.includes(slot) && element.slots[slot]) + { + var gr=calculate_item_grade(G.items[element.slots[slot].name])+0.5; + if(element.slots[slot].level==12) element.pzazz+=gr*12; + else if(element.slots[slot].level>=11) element.pzazz+=gr*8; + else if(element.slots[slot].level==10) element.pzazz+=gr*6; + else if(element.slots[slot].level==9) element.pzazz+=gr*2; + else if(element.slots[slot].level==8) element.pzazz+=gr/2; + } + } + } + // ["stunned","cursed","poisoned","poisonous","frozen"].forEach(function(prop){ + // if(element[prop]) element[prop]=false; + // }); + // if(is_player(element)) + // { + // ["charging","invis","invincible","mute"].forEach(function(prop){ + // if(element[prop]) element[prop]=false; + // }); + // } + // for(prop in data.s||{}) + // { + // element[prop]=data.s[prop]; + // } + if(element.me) element.bank=element.user; + element.last_ms=new Date(); +} + +function reposition_ui() +{ + var w1=$("#topmid").outerWidth(),w2=$("#bottommid").outerWidth(); + if(character && !no_html && !cached('rpui',$("html").width(),w1,w2)); + { + // $("#skills").css("right",$("#gamelog").outerWidth()); + // $(".locui").css("bottom",$("#chatlog").outerHeight()-5); + // $("#xpsui").css("bottom",$("#gamelog").outerHeight()-5); + // $("#coordsui").css("bottom",$("#gamelog").outerHeight()+$("#xpsui").outerHeight()-10); + $("#topmid").css("right",round(($("html").width()-w1)/2)); + $("#bottommid").css("right",round(($("html").width()-w2)/2)); + } +} + +function update_tutorial_ui() +{ + var completion=X.tutorial.progress; + if(last_rendered_step>X.tutorial.step) + { + completion=0; + } + else + { + if(last_rendered_step1) $(".flasht").removeClass("flasht"); + $("#tutorialui").html("TUTORIAL "+(X.tutorial.step+1)+" / "+G.docs.tutorial.length); + $("#tutorialslider").css("width",((X.tutorial.step+1)*100/G.docs.tutorial.length)+"%"); + if(X.tutorial.finished || !tutorial_ui) $(".tutorialui").hide(); + else $(".tutorialui").show(); +} + +function update_overlays() +{ + if(character) send_target_logic(); + if(mode.dom_tests || no_html) return; + if(character) + { + if(!cached("att",character.attack)) $(".attackui").html((character.ctype=="priest"&&"HEAL "||"ATT ")+(character.ctype=="priest"&&character.heal||character.attack)); + if(!cached("inv",character.esize+"|"+character.isize)) $(".invui").html("INV "+(character.isize-character.esize)+"/"+character.isize); + if(!cached("hptop",character.hp,character.max_hp)) + { + //$(".hpui").html("HP: "+character.hp+"/"+character.max_hp); + $("#hptext").html(character.hp+"/"+character.max_hp); + $("#hpslider").css("width",(character.hp*100/character.max_hp)+"%"); + } + if(!cached("mptop",character.mp,character.max_mp)) + { + //$(".mpui").html("MP: "+character.mp+"/"+character.max_mp); + $("#mptext").html(character.mp+"/"+character.max_mp); + $("#mpslider").css("width",(character.mp*100/character.max_mp)+"%"); + } + var xp=floor(character.xp/character.max_xp*100); + if(!cached("xptop",character.level+"|"+xp)) + { + $("#xpui").html("LV"+character.level+" "+xp+"%"); + $("#xpslider").css("width",(character.xp*100/character.max_xp)+"%"); + } + if(!cached("tutorialtop",X.tutorial.step+"|"+X.tutorial.task)) + { + update_tutorial_ui(); + } + if(inventory && !cached("igold",character.gold)) $('.goldnum').html(to_pretty_num(character.gold+((new Date()).getDate()==101 && (new Date()).getMonth()==3?1014201800:0))); + if(inventory && !cached("icash",character.cash)) $('.cashnum').html(to_pretty_num(character.cash)); + if(!cached("coord",round(map.real_x)+"|"+round(map.real_y))) $('.coords').html(round(map.real_x)+","+round(map.real_y)); + if(!topleft_npc) reset_topleft(ctarget); + if(topright_npc=="character" && !cached("chcid",character.cid)) render_character_sheet(); + } + + + var c=new Date(),h=c.getUTCHours(),m=c.getUTCMinutes(); + if(S.schedule && S.schedule.time_offset) h=(24+S.schedule.time_offset+h)%24; + if(!cached("time",("0"+h).slice(-2)+":"+("0"+m).slice(-2))) + { + $(".timeui").html(("0"+h).slice(-2)+":"+("0"+m).slice(-2)); + light_logic(); + } + + if(S.abtesting && window.abtesting) + { + $(".scoreA").html(S.abtesting.A); + $(".scoreB").html(S.abtesting.B); + var seconds=-ssince(new Date(S.abtesting.end)),minutes=parseInt(seconds/60),seconds=parseInt(seconds)%60; + if(seconds==0) seconds="00"; else if(seconds<10) seconds="0"+seconds; + $(".abtime").html("0"+minutes+":"+seconds); + } + if(character && character.moving && options.code_fx && stage.cfilter_ascii) remove_code_fx(); + showhide_quirks_logic(); +} + +function showhide_quirks_logic() +{ + if(!character) return; + var initial=quirks; quirks={}; + // $(".quirks").hide(); + (G.maps[character.map].quirks||[]).forEach(function(q){ + if(q[4]=="info" && point_distance(character.real_x,character.real_y,q[0],q[1])<200) + { + quirks[q[5]]=true; + } + }); + (G.maps[character.map].zones||[]).forEach(function(zone){ + [[0,-48,3],[-48,0,1],[48,0,2],[0,48,0],[0,-24,3],[-24,0,1],[24,0,2],[0,24,0]].forEach(function(m){ + if(is_point_inside([character.real_x+m[0],character.real_y+m[1]],zone.polygon)) + { + quirks[zone.type]=true; + } + }); + }); + if(JSON.stringify(initial) !== JSON.stringify(quirks)) + render_server(); +} + +var last_loader={progress:0}; +function on_load_progress(loader,resource) // called at selection.html - as it gets loaded dynamically into the game [16/11/18] +{ + if(!loader) loader=last_loader; + else last_loader=loader; + $("#progressui").html(round(loader.progress) + "%"); + if($("#progressui").html()=="100%") $("#progressui").removeClass("loading"); +} + +function loader_click() +{ + if(!server_addr) show_modal("
No servers found, 3 possible scenarios:

(1) The game is being updated
(2) All existing servers overloaded
(3) Someone found a bug that brought down all the servers

Best to spend this time in our Discord to figure out what happened
"); + else if($("#progressui").html()!="100%") show_modal("
Game resources are loading

This may take some time

If the game got stuck at this stage, please email hello@adventure.land
"); + else show_modal("
All game resources have been loaded

If you can't sign in, please email hello@adventure.land
") +} + +function init_interface() +{try{ + $('.codesearch').val(""); + $('.codesearch').bind("propertychange change click keyup input paste", function(event){ csearch_logic("ui"); }); + csearch_logic("ui"); + }catch(e){ + console.error(e); +}} + +function the_game(demo) +{ + // if(!window.requestAnimationFrame) window.requestAnimationFrame=function(a){ setTimeout(a,16); }; // jsdom patch [18/04/19] + if(is_cli && window.ls_emulation) window._localStorage=window.ls_emulation; + width=$(window).width(); + height=$(window).height(); + if(bowser.mac && bowser.firefox && !engine_mode) renderer=new PIXI.CanvasRenderer(width,height,{antialias: antialias, transparent: false}); //, resolution:window.devicePixelRatio etc. doesn't work [15/11/16] + else if(retina_mode && !engine_mode) renderer=new PIXI.autoDetectRenderer(width,height,{antialias: antialias, transparent: false, resolution:window.devicePixelRatio, autoResize:true}); + else if(engine_mode=="webgl") renderer=new PIXI.WebGLRenderer(width,height,{antialias: antialias, transparent: false}); + else if(engine_mode=="canvas") renderer=new PIXI.CanvasRenderer(width,height,{antialias: antialias, transparent: false}); + else renderer=new PIXI.autoDetectRenderer(width,height,{antialias: antialias, transparent: false}); // , resolution:window.devicePixelRatio, autoResize:true + + if(high_precision) PIXI.PRECISION.DEFAULT = PIXI.PRECISION.HIGH; + + if(renderer.type == PIXI.RENDERER_TYPE.WEBGL) console.log('WebGL Mode'); + else console.log('Canvas Mode'); + + renderer.plugins.interaction.cursorStyles.help="help"; + renderer.plugins.interaction.cursorStyles.crosshair="crosshair"; + + // renderer.plugins.interaction.cursorStyles.pointer = function() { + // console.log('Should be a pointer'); + // }; + // renderer.plugins.interaction.cursorStyles.default= function() { + // console.log('Should be default cursor'); + // }; + + if(!no_graphics) document.body.appendChild(renderer.view); + $("canvas").css("position","fixed").css("top","0px").css("left","0px").css("z-index",1); + + if(PIXI.display && PIXI.display.Stage) stage = new PIXI.display.Stage(); + else stage = new PIXI.Container(); + /* start secondary level */ + //inner_stage=new PIXI.Container(); + + if(bw_mode) + { + var filter=new PIXI.filters.ColorMatrixFilter(); + filter.desaturate(); + stage.cfilter_bw=filter; + regather_filters(stage); + } + else + { + delete stage.cfilter_bw; + regather_filters(stage); + } + + //stage.addChild(inner_stage); + /* end secondary level */ + + if(PIXI.DisplayList && !no_graphics) + { + if(window.inner_stage) inner_stage.displayList = new PIXI.DisplayList(); + else stage.displayList = new PIXI.DisplayList(); + map_layer=new PIXI.DisplayGroup(0, true); + text_layer=new PIXI.DisplayGroup(3, true); + chest_layer=new PIXI.DisplayGroup(2, true); + separate_layer=new PIXI.DisplayGroup(0, true); + monster_layer=new PIXI.DisplayGroup(1, function (sprite) { + var disp=0; + if(sprite.stand) disp=-3; + if("real_y" in sprite) sprite.zOrder = -sprite.real_y+disp+(sprite.y_disp||0); + else sprite.zOrder = -sprite.position.y+disp+(sprite.y_disp||0); + }); + // var player_layer = new PIXI.DisplayGroup(0, true); + player_layer=monster_layer; + chest_layer=monster_layer; + } + else if(PIXI.display) + { + + PIXI.Container.prototype.renderWebGL = function (renderer) { + if (this._activeParentLayer && this._activeParentLayer != renderer._activeLayer) { + return; + } + if (!this.visible) { + this.displayOrder = 0; + return; + } + + this.displayOrder = renderer.incDisplayOrder(); + + if (this.worldAlpha <= 0 || !this.renderable) { + return; + } + + renderer._activeLayer = null; // < -- this is my temporary change + this.containerRenderWebGL(renderer); + renderer._activeLayer = this._activeParentLayer; // < -- and this one too + }; + + use_layers=true; + stage.group.enableSort = true; + // chest_layer=new PIXI.display.Group(3, true); + var monster_sort=function(sprite){ + var disp=0; + if(sprite.stand) disp=-3; + if("real_y" in sprite) sprite.zOrder = -sprite.real_y+disp+(sprite.y_disp||0); + else sprite.zOrder = -sprite.position.y+disp+(sprite.y_disp||0); + }; + var child_sort=function(sprite){ + var disp=0; + if(sprite.parent.stand) disp=-3; + if("real_y" in sprite.parent) sprite.zOrder = -sprite.parent.real_y+disp+(sprite.parent.y_disp||0); + else sprite.zOrder = -sprite.parent.position.y+disp+(sprite.parent.y_disp||0); + } + map_layer=new PIXI.display.Group(0, true); stage.addChild(new PIXI.display.Layer(map_layer)); + animation_layer=new PIXI.display.Group(1,true); stage.addChild(new PIXI.display.Layer(animation_layer)); + entity_layer=new PIXI.display.Group(2,child_sort); stage.addChild(new PIXI.display.Layer(entity_layer)); + // Name tags - previously 2 - now 6 so they render over everything [06/08/18] + below_layer=new PIXI.display.Group(2.99,monster_sort); stage.addChild(new PIXI.display.Layer(below_layer)); + monster_layer=new PIXI.display.Group(3,monster_sort); stage.addChild(new PIXI.display.Layer(monster_layer)); + above_layer=new PIXI.display.Group(3.01,monster_sort); stage.addChild(new PIXI.display.Layer(above_layer)); + hp_layer=new PIXI.display.Group(4,child_sort); stage.addChild(new PIXI.display.Layer(hp_layer)); + text_layer=new PIXI.display.Group(5, true); stage.addChild(new PIXI.display.Layer(text_layer)); + weather_layer=new PIXI.display.Group(6, true); stage.addChild(new PIXI.display.Layer(weather_layer)); + fog_layer=new PIXI.display.Group(7, true); stage.addChild(new PIXI.display.Layer(fog_layer)); + + // var player_layer = new PIXI.DisplayGroup(0, true); + player_layer=monster_layer; + player_layer.sortPriority=1; + player_layer.useDoubleBuffer=true; + chest_layer=monster_layer; + + + if(mode.ltbl && !no_graphics) + { + lighting=new PIXI.display.Layer(); + lighting.on('display', function(element) { + element.blendMode=PIXI.BLEND_MODES.ADD; + }); + lighting.useRenderTexture = true; + lighting.clearColor = [0.25, 0.25, 0.25, 1]; // ambient gray + + stage.addChild(lighting); + + var lightingSprite = new PIXI.Sprite(lighting.getRenderTexture()); + lightingSprite.blendMode = PIXI.BLEND_MODES.MULTIPLY; + lightingSprite.parentGroup=lightingSprite.displayGroup=fog_layer; + + stage.addChild(lightingSprite); + } + } + frame_ms=16; + C=PIXI.utils.BaseTextureCache; + FC={}; // file for name + FM={}; // [i,j] for portraits + XYWH={}; // dimensions - previously D, it was cool while it lasted, renamed to XYWH, so the server.D can be imported into window.D [12/07/18] + loader=PIXI.loader; + loader.on("progress",on_load_progress); + + //alert(JSON.stringify(M)); + for(var name in G.animations) + { + G.animations[name].file=url_factory(G.animations[name].file); + loader.add(G.animations[name].file); + } + for(var name in G.tilesets) + { + G.tilesets[name].file=url_factory(G.tilesets[name].file); + loader.add(G.tilesets[name].file); + } + for(var name in G.sprites) + { + var s_def=G.sprites[name]; + if(s_def.skip) continue; + s_def.file=url_factory(s_def.file); + loader.add(s_def.file); + } + for(var name in G.imagesets) + { + if(!G.imagesets[name].load) continue; + G.imagesets[name].file=url_factory(G.imagesets[name].file); + loader.add(G.imagesets[name].file); + } + + gprocess_game_data(); + + if(mode.bitmapfonts) loader.add("/css/fonts/m5x7.xml"); //,{xhrType:PIXI.loaders.Resource.XHR_RESPONSE_TYPE.DOCUMENT} + + set_status("75% ->Server"); + + if(!demo) + { + load_game(); + init_socket(); + } + else init_demo(); +} + +function demo_entity_logic(sprite) +{ + if(!sprite.demo) return; + if(sprite.moving) return; + if(sprite.pause && mssince(sprite.pause)<800) return; + if(Math.random()<0.1) sprite.pause=new Date(); + var moves=[[1,0],[0,1],[-1,0],[0,-1],[0.8,0.8],[-0.8,-0.8],[0.8,-0.8],[-0.8,0.8]],multiplier=12; + if(Math.random()<0.3) multiplier*=2; + else if(Math.random()<0.3) multiplier*=3; + shuffle(moves); + sprite.going_x=sprite.x+moves[0][0]*multiplier; + sprite.going_y=sprite.y+moves[0][1]*multiplier; + if(sprite.boundary && (sprite.going_xsprite.boundary[2] || sprite.going_ysprite.boundary[3])); + else if(can_move(sprite)) + { + sprite.u=true; sprite.moving=true; + sprite.from_x=sprite.x; + sprite.from_y=sprite.y; + calculate_vxy(sprite); + } + else + { + sprite.going_x=sprite.x; sprite.going_y=sprite.y; + } +} + +function init_demo() +{ + is_demo=1; + current_map=current_in="shellsisland"; + M=G.maps[current_map].data; + GEO=G.geometry[current_map]; + reflect_music(); + load_game(); + // map.real_y=-90; <- at load_game's callback + G.maps[current_map].monsters.forEach(function(pack){ + future_entities.monsters[pack.type]={ + type:pack.type, + speed:8, + id:pack.type, + x:pack.boundary[0]+(pack.boundary[2]-pack.boundary[0])*Math.random(), + y:pack.boundary[1]+(pack.boundary[3]-pack.boundary[1])*Math.random(), + boundary:pack.boundary, + s:{}, + 'in':current_map, + map:current_map, + moving:false, + demo:true, + } + }); +} + +var first_welcome=false; +function init_socket(args) +{ + if(!args) args={}; + if(!server_addr) { add_log("Welcome"); add_log("No live server found","red"); add_log("Please check again in 2-3 minutes"); add_log("Spend this time in our Discord chat room",colors.code_blue); add_update_notes(); return; } + if(window.socket) + { + if(!socket_welcomed) return add_log("Another server connection in progress. Please wait."); + window.socket.destroy(); + } + $(".disconnected").hide(); + if(is_sdk && (Cookies.get("windows") || Cookies.get("local_ip") || window.location.host=="advanture.land" || window.location.host=="x.thegame.com")) server_addr="192.168.1.125"; // Cookies.set('windows','1',{expires:12*365}); + else if(is_sdk) server_addr="0.0.0.0"; + var query=args.secret&&"desktop="+(!is_comm&&1||"")+"&secret="+args.secret||undefined; + if(location.protocol=="https:") window.socket=io('wss://'+server_addr+':'+server_port,{secure:true,transports:['websocket'],query:query}); + else window.socket=io(server_addr+':'+server_port,{transports:['websocket'],query:query}); + add_log("Connecting to the server."); + socket_ready=false; socket_welcomed=false; observing=null; $("#observeui").hide(); + original_onevent=socket.onevent; + original_emit=socket.emit; + socket.emit=function(packet){ + var is_transport=in_arr(arguments && arguments["0"],["transport","enter","leave"]); + // if(is_transport) alert("transport intercepted"); + if(mode.log_calls) console.log('CALL',JSON.stringify(arguments)+" "+new Date()); + if(!(transporting && is_transport && ssince(transporting)<8)) + { + original_emit.apply(socket,arguments); + if(is_transport) transporting=new Date(); + } + else + { + resolve_deferred(arguments["0"],{success:false,in_progress:true,place:"emit_override_in_gamejs"}); + } + }; + socket.onevent=function(packet){ + if(mode.log_incoming) console.log('INCOMING',JSON.stringify(arguments)+" "+new Date()); + original_onevent.apply(socket,arguments); + }; + socket.on('welcome',function(data){ + if(data && data.character) + { + observing=data.character; + $("#observeui").show(); + } + S=data.S; + socket_welcomed=true; + is_pvp=data.pvp; + gameplay=data.gameplay; + server_region=data.region; + server_identifier=data.name; + server_name=server_names[data.region]+" "+data.name; + clear_game_logs(); add_log("Welcome to "+server_names[data.region]+" "+data.name); + add_update_notes(); + if(!first_welcome) + { + first_welcome=true; + if(is_electron && electron_is_main() && user_id) setTimeout(electron_code_sync_logic,1); + } + current_map=data.map; current_in=data["in"]; first_coords=true; first_x=data.x; first_y=data.y; reflect_music(); + M=G.maps[current_map].data; + GEO=G.geometry[current_map]; + $(".servername").html(server_name); + $(".mapname").html(G.maps[current_map].name||"Unknown"); + if(!resources_loaded) socket_ready=true; + else + { + launch_game(); + //create_map(); + //socket.emit("loaded",{success:1,width:screen.width,height:screen.height,scale:scale}); + } + render_server(); + new_map_logic("welcome",data); + }); + socket.on('new_map',function(data){ + var create=false; + transporting=false; + if(current_map!=data.name) + { + create=true; + topleft_npc=false; + data.redraw=true; + } + current_map=data.name; current_in=data["in"]; reflect_music(); + // alert(current_map); + M=G.maps[current_map].data; + GEO=G.geometry[current_map]; + $(".mapname").html(G.maps[current_map].name||"Unknown"); + if(character) + { + character.real_x=data.x; + character.real_y=data.y; + character.m=data.m; + character.moving=false; + resolve_deferreds("move",{reason:"new_map"}); + var odir=character.direction; + character.direction=data.direction||0; + character.map=current_map; + character['in']=data['in']; + if(data.effect==="blink") + { + delete character.fading_out; + delete character.s.blink; + character.real_alpha=0.5; + //character.fading_in=true; //Decided to use the regular .tp logic [17/05/18] + restore_dimensions(character); + } + if(data.effect==="magiport") + { + delete character.fading_out; + delete character.s.magiport; + stop_filter(character,"bloom"); + character.real_alpha=0.5; + character.direction=odir; + restore_dimensions(character); + } + blink_pressed=false; last_blink_pressed=really_old; + if(data.effect) unstuck_logic(character); + character.tp=data.effect; + if(data.name=="bank") tut("bank"); + } + var cm_timer=new Date(); + if(create) create_map(); + if(!character) + { + map.real_x=data.x; + map.real_y=data.y; + } + // console.log("create_map: "+mssince(cm_timer)); + position_map(); + new_map_logic("map",data); + handle_entities(data.entities,{new_map:true}); + if(data.eval) eval(data.eval); + call_code_function("trigger_event","new_map",data); + call_code_function("trigger_character_event","new_map",data); + }); + socket.on('start',function(data){ + // alert(JSON.stringify(data)); + if(!no_html) + { + $("#progressui").remove(); + $("#content").html(""); + $("#topmid,#bottommid,#toprightcorner,#bottomleftcorner2,#bottomleftcorner").show(); + $(".xpsui").css("display","block"); + $(".tutorialui").css("display","block"); + $("body").append(''); + } + + if(gtest) + { + $("body").children().each(function(){ + if(this.tagName!="CANVAS") $(this).remove(); + }); + } + // $("#gameui").show(); + inside="game"; observing=null; $("#observeui").hide(); + // show_json(data); + S=data.s_info; + var code=data.code,code_version=data.code_version,scode_slot=data.code_slot; delete data.code; delete data.code_version; delete data.code_slot; + if(scode_slot) console.log("start: "+data.id+" code: "+scode_slot); + // console.log(code); console.log(code_version); console.log(scode_slot); + var m_info=data.info; delete data.info; delete data.s_info; + var d_entities=data.entities; delete data.entities; + G.base_gold=data.base_gold; delete data.base_gold; + character=add_character(data,1); + character.ping=min(320,mssince(window.auth_sent)); + pings=[character.ping]; + if(!data.vision) character.vision=[700,500]; + friends=data.friends; + character.home=data.home; + character.emx=data.emx; + character.acx=data.acx; + character.xcx=data.xcx; + G.classes[character.ctype].xcx.forEach(function(c){ if(!character.xcx.includes(c)) character.xcx.push(c) }); + if(character.level==1) + { + if(X && X.tutorial && !X.tutorial.finished && tutorial_ui) open_tutorial(); + else show_game_guide(); + } + if(character.ctype=="merchant" || recording_mode || 1) options.show_names=true; + clear_game_logs(); add_log("Connected!"); + // add_holiday_log(); + // add_greenlight_log(); + if(gameplay=="hardcore") + { + add_log("Pro Tips: You can transport to anywhere from the Beach Cave, Water Spirits drop stat belts, 3 monsters drop 3 new unique items, 3 monsters drop 50 times the gold they usually do!","#B2D5DF"); + $(".saferespawn").show(); + } + else add_log("Note: Game dynamics and drops aren't final, they are evolving with every update","gray"); + // add_log("Warning: A Chrome bug is causing memory leaks, very small but it adds up. They patched the bug, however, that patch didn't make it to our browsers yet","#E08583"); + $(".charactername").html(character.name); + page.title=character.name; + if(gameplay=="hardcore") page.title="Fierce "+character.name; + try{ + var get=""; + if(no_html) get+=(!get&&"?"||"&")+"no_html=true"; + if(is_bot) get+=(!get&&"?"||"&")+"is_bot=1"; + if(no_graphics) get+=(!get&&"?"||"&")+"no_graphics=true"; + if(border_mode) get+=(!get&&"?"||"&")+"borders=true"; + if(explicit_slot) get+=(!get&&"?"||"&")+"code="+explicit_slot; + // if(lowest) get+=(!get&&"?"||"&")+"lowest=true"; + page.url="/character/"+character.name+"/in/"+server_region+"/"+server_identifier+"/"+get; + window.history.replaceState({},page.title,page.url); + $("title").html(page.title); + } catch(e){ + console.log(e); + } + // draw_timeout(function(){ add_log("Welcome "+character.name) },650); + reposition_ui(); update_overlays(); + current_in=character["in"]; + if(character.map!=current_map) + { + current_map=character.map; reflect_music(); + M=G.maps[current_map].data; + GEO=G.geometry[current_map]; + $(".mapname").html(G.maps[current_map].name||"Unknown"); + create_map(); + } + if(!gtest) + { + if(manual_centering) + { + if(window.inner_stage) inner_stage.addChild(character); + else stage.addChild(character); + } + else map.addChild(character); + } + position_map(); + rip_logic(); + new_map_logic("start",{info:m_info}); + new_game_logic(); + // ipass=data.ipass; + // setInterval(function(){ if(game_loaded) $.getJSON(location.protocol+"//"+server_addr+":"+(parseInt(server_port)+40)+"/character?checkin=1&ipass="+ipass+"&id="+character.id+"&callback=?"); },30000); // + "?" = JSONP + + // api_call("load_gcode",{file:"/examples/hardcore.js",run:true}); + try{ + var data=storage_get("code_cache"),the_code="",to_run=false; + if(data) + { + data=JSON.parse(data); + the_code=(!scode_slot || data["slot_"+real_id]==scode_slot)&&data["code_"+real_id]||code||""; + to_run=explicit_slot&&'1'||data["run_"+real_id]; + code_slot=scode_slot||data["slot_"+real_id]||real_id; + if(the_code.length) + handle_information([{type:"code",code:the_code,run:to_run,slot:code_slot,reset:true}]); + } + else if(code) + { + code_slot=scode_slot; + handle_information([{type:"code",code:code,run:explicit_slot&&true||false,slot:code_slot,reset:true}]); + } + } + catch(e){console.log(e);} + var settings=get_settings(real_id); + if(settings.skillbar) skillbar=settings.skillbar; + if(settings.keymap) keymap=settings.keymap; + if(!is_electron) + { + if(settings.music=="on" || sound_music) sound_on(); + if(settings.sfx=="on" || sound_sfx) sfx_on(); + } + map_keys_and_skills(); + render_skillbar(); + if(!character.rip) $("#name").css("color","#1AC506"); set_status("Connected"); + render_server(); + // show_json(d_entities); + handle_entities(d_entities,{new_map:true}); + if(character.role=="cx" && !is_bot) insert_cx_tuners(); + }); + socket.on('correction',function(data){ + if(can_move({map:character.map,x:character.real_x,y:character.real_y,going_x:data.x,going_y:data.y,base:character.base})) + { + add_log("Location corrected","gray"); + console.log("Character correction"); + character.real_x=parseFloat(data.x); + character.real_y=parseFloat(data.y); + // character.moving=false; character.vx=character.vy=0; + recalculate_vxy(character); + // resolve_deferreds("move",{reason:"correction"}); + } + }); + socket.on("players",function(data){ load_server_list(data); }); + socket.on("pvp_list",function(data){ if(data.code) call_code_function("trigger_event","pvp_list",data.list); else load_pvp_list(data.list); }); + socket.on("ping_ack",function(data){ + if(!pingts[data.id]) return; + if(data.ui) add_log("Ping: "+mssince(pingts[data.id])+"ms","gray"); + push_ping(mssince(pingts[data.id])); + delete pingts[data.id]; + }); + socket.on("requesting_ack",function(){ + socket.emit("requested_ack",{}); + }); + socket.on("game_error",function(data){ draw_trigger(function(){ if(is_string(data)) ui_error(data); else ui_error(data.message)}); }); + socket.on("game_log",function(data){ + if((data.message||data)=="You killed a Goo") tut("killagoo"); + draw_trigger(function(){ + if(is_string(data)) ui_log(data,"gray"); + else + { + if(data.sound) sfx(data.sound); + ui_log(data.message,data.color); + } + if(data.confetti && get_player(data.confetti)) confetti_shower(get_player(data.confetti),1); + }); + }); + socket.on("game_chat",function(data){ // Just for GM stuff [04/07/18] + draw_trigger(function(){ + if(is_string(data)) add_chat("",data,"gray"); + else + { + if(data.sound) sfx(data.sound); + add_chat("",data.message,data.color); + } + }); + }); + socket.on("fx",function(data){ + draw_trigger(function(){ + if(data.name=="the_door") the_door(); + }); + }); + socket.on("online",function(data){ + draw_trigger(function(){ + no_chat_notification=true; + add_chat("",data.name+" is on "+data.server,"white","online|"+data.name); //#80ECA7 + no_chat_notification=false; + }); + }); + socket.on('light',function(data){ + draw_trigger(function(){ + if(data.affected) + { + // These were outside draw_trigger, but moved inside [03/07/18] + if(is_pvp) pvp_timeout(3600); + skill_timeout('invis'); + } + if(data.affected) start_animation(character,"light"); + last_light=new Date(); + var player=get_entity(data.name); if(!player) return; + d_text("LIGHT",player,{color:"white"}); + //disappearing_circle(player.real_x,player.real_y-9,20,{alpha:0.7}); + //disappearing_circle(player.real_x,player.real_y-8,10,{alpha:0.7,color:0xDED491}); + if(player.me) start_animation(player,"light"); + for(var id in entities) + { + var entity=entities[id]; + if(is_player(entity) && distance(entity,player)<300) start_animation(entity,"light"); + } + }); + }); + socket.on('game_event',function(data){ + if(!data.name) data={name:data}; + if(data.name=="pinkgoo") + { + add_chat("","The 'Love Goo' has respawned in "+G.maps[data.map].name+"!","#EDB0E0"); + } + if(data.name=="snowman") + { + // add_chat("","Snowman respawned in "+G.maps[data.map].name+"!","#B1DCEF"); + // add_chat("","Join the fight against Snowman!","#B1DCEF"); + } + if(data.name=="franky") + { + // add_chat("","Franky spawned in "+G.maps[data.map].name+"!","#9D99EF"); + // add_chat("","Join the fight against Franky!","#9D99EF"); + } + if(data.name=="wabbit") + { + add_chat("","Wabbit has respawned in "+G.maps[data.map].name+"!","#78CFEF"); + } + if(data.name=="goldenbat") + { + add_chat("","The Golden Bat has spawned in "+G.maps[data.map].name+"!","gold"); + } + if(data.name=="ab_score") + { + if(!events.abtesting) return; + // add_log(data.color+" A: "+data.A+" B: "+data.B); + events.abtesting.A=data.A; + events.abtesting.B=data.B; + } + call_code_function("on_game_event",data); + call_code_function("trigger_event","event",data); + }); + socket.on('achievement_progress',function(data){ + add_log("AP["+data.name+"]: "+to_pretty_num(data.count)+"/"+to_pretty_num(data.needed),"#6DCC9E"); + }); + socket.on('achievement_success',function(data){ + add_log("AP["+data.name+"]: Complete!","#58CF40"); + }); + socket.on('skill_timeout',function(data){ + skill_timeout(data.name,data.ms); + }); + socket.on('game_response',function(data){ + if(is_sdk) console.log(["game_response",data]); + var response=data.response||data; + try{ + var cevent=false,event=false; + if(data.cevent) cevent=data.cevent,delete data.cevent; if(cevent===true) cevent=response; + if(data.event) event=data.event,delete data.event; if(event===true) event=response; + + if(data.place && data.failed) + { + if(!data.reason) data.reason=data.response; + reject_deferred(data.place,data); + } + else if(data.place) + { + resolve_deferred(data.place,data); + } + if(cevent) call_code_function("trigger_character_event",cevent,data); + if(event) call_code_function("trigger_event",event,data); + + }catch(e){ + if(is_sdk) console.error(e); + } + if(response=="upgrade_success" || response=="upgrade_fail") u_retain_t=options.retain_upgrades; + draw_trigger(function(){ + if(response=="elixir"){ ui_log("Consumed the elixir","gray"); d_text("YUM",character,{color:"elixir"}); } + else if(response=="data"){} + else if(response=="invalid"){ + d_text("INVALID",character); + } + else if(response=="error") + { + ui_error("Server error!"); + } + else if(response=="storage_full") + { + ui_log("Storage is full","gray"); + reopen(); + } + else if(response=="safety_check"); + else if(response=="inventory_full") + { + d_text("NO SPACE",character); + ui_log("Inventory is full","gray"); + reopen(); + } + else if(response=="home_set") + { + render_interaction({auto:true,skin:"lionsuit",message:"Set your home to: "+data.home}); + character.home=data.home; + } + else if(response=="sh_time") + { + render_interaction({auto:true,skin:"lionsuit",message:"You can't change your home server for another "+to_pretty_float(data.hours)+" hours!"}); + } + else if(response=="invalid") ui_log("Invalid","gray"); + else if(response=="only_in_home") ui_log("You can only do this in your home server!","gray"); + else if(response=="cant_when_sick") + { + if(data.goblin) render_interaction({auto:true,skin:G.npcs.lostandfound.skin,message:"Ugh, you're sick! Come back when you are healed!"}); + ui_log("You can't do this when you are sick!","gray"); + } + else if(response=="party_full") ui_log("The party is full","gray"); + else if(response=="already_in_party") ui_log("Already in this party","gray"); + else if(response=="player_gone") ui_log(data.name+" is gone","gray"); + else if(response=="invitation_expired") ui_log("Invitation expired","gray"); + else if(response=="request_expired") ui_log("Request expired","gray"); + else if(response=="cant_kick") ui_log("You can't kick someone who's above you.","gray"); + else if(response=="compound_success") + { + tut("compound"); + ui_log("Item combination succeeded",data.up&&"#1ABEFF"||"white"); + if(!data.stale) resolve_deferred("compound",{success:true,level:data.level,num:data.num}); + } + else if(response=="compound_fail") + { + tut("compound"); + ui_error("Item combination failed"); + if(!data.stale) resolve_deferred("compound",{success:false,level:data.level,num:data.num}); + } + else if(response=="compound_in_progress") + { + ui_log("Another combination in progress","gray"); + } + else if(response=="compound_invalid_offering") + { + ui_log("Offering not accepted","gray"); + reject_deferred("compound",{reason:"offering"}); + } + else if(response=="compound_mismatch") + { + ui_log("Items are different","gray"); + reject_deferred("compound",{reason:"mismatch"}); + } + else if(response=="compound_cant") + { + ui_log("Can't be combined","gray"); + reject_deferred("compound",{reason:"not_combinable"}); + } + else if(response=="compound_incompatible_scroll") + { + set_uchance("?"); + ui_log("Incompatible scroll","gray"); + reject_deferred("compound",{reason:"scroll"}); + } + else if(response=="misc_fail") + { + ui_log(":)","#FF5D54"); + } + else if(response=="upgrade_success") + { + tut("upgrade"); + ui_log("Item upgrade succeeded","white"); + if(!data.stale) resolve_deferred("upgrade",{success:true,level:data.level,num:data.num}); + } + else if(response=="upgrade_fail") + { + tut("upgrade"); + ui_error("Item upgrade failed"); + if(!data.stale) resolve_deferred("upgrade",{failed:true,success:false,level:data.level,num:data.num}); + } + else if(response=="upgrade_success_stat") + { + tut("addstats"); + if(!data.stale) resolve_deferred("upgrade",{stat:true,stat_type:data.stat_type,num:data.num}); + } + else if(response=="upgrade_offering_success") + { + ui_log("Offering succeeded","white"); + if(!data.stale) resolve_deferred("upgrade",{success:true}); + } + else if(response=="upgrade_no_item") + { + reject_deferred("upgrade",{reason:"no_item"}); + } + else if(response=="upgrade_in_progress") + { + ui_log("Another upgrade in progress","gray"); + reject_deferred("upgrade",{reason:"in_progress"}); + } + else if(response=="mail_sending") + { + ui_log("Sending mail ...","gray"); + hide_modal(true); + } + else if(response=="mail_failed") + { + show_alert("Mail failed, reason: "+data.reason); + } + else if(response=="mail_sent") + { + ui_log("Mail sent to "+data.to+"!","#C06978"); + } + else if(response=="mail_sent") + { + ui_log("Mail sent to "+data.to+"!","#C06978"); + } + else if(response=="mail_take_item_failed") + { + ui_log("Can't retrieve the item, probably you took it already","#C06978"); + setTimeout(function(){ api_call('pull_mail'); },2000); + $('.takeitem').hide(); + } + else if(response=="mail_item_taken") + { + ui_log("Item retrieved!","#6DAD47"); + setTimeout(function(){ api_call('pull_mail'); },2000); + $('.takeitem').hide(); + } + else if(response=="upgrade_no_scroll") + { + reject_deferred("upgrade",{reason:"no_scroll"}); + } + else if(response=="upgrade_mismatch") + { + reject_deferred("upgrade",{reason:"mismatch"}); + } + else if(response=="upgrade_invalid_offering") + { + ui_log("Offering not accepted","gray"); + reject_deferred("upgrade",{reason:"offering"}); + } + else if(response=="upgrade_cant") + { + ui_log("Can't be upgraded","gray"); + reject_deferred("upgrade",{reason:"not_upgradeable"}); + } + else if(response=="upgrade_incompatible_scroll") + { + set_uchance("?"); + ui_log("Incompatible scroll","gray"); + reject_deferred("upgrade",{reason:"scroll"}); + } + else if(response=="upgrade_scroll_q") + { + ui_log("Need "+data.q+" scrolls","gray"); + reject_deferred("upgrade",{reason:"scroll_quantity",need:data.q,have:data.h}); + } + else if(response=="upgrade_chance" || response=="compound_chance") + { + set_uchance(data.chance); + } + else if(response=="max_level") + { + set_uchance("?"); + ui_log("Already +"+data.level,"white"); + } + else if(response=="exception") + { + ui_error("ERROR!"); + } + else if(response=="got_picked") ui_log("Felt a touch","#D8866C"); + else if(response=="picked") { yes_yes_yes(); ui_log("Got something!","#3AD585"); } + else if(response=="pick_failed") { no_no_no(); ui_log("Couldn't pick anything","gray"); } + else if(response=="nothing") ui_log("Nothing happens","gray"); + else if(response=="inviter_gone") ui_log("Inviter gone","gray"); + else if(response=="not_ready") d_text("NOT READY",character); + else if(response=="cant_equip") d_text("CAN'T EQUIP",character); + else if(response=="cant") d_text("CAN'T",character); + else if(response=="muted") d_text("MUTED",character); + else if(response=="cant_consume") d_text("CAN'T CONSUME",character); + else if(response=="giveaway") d_text("GIVEAWAY?!",character); + else if(response=="no_merchants") ui_log("No merchants!","gray"); + else if(response=="join_too_late") ui_log("Too late to join","gray"); + else if(response=="receiver_unavailable") ui_log("Receiver unavailable","gray"); + else if(response=="no_mp") + { + d_text("NO MP",character); + } + else if(response=="friendly") + { + var safe=false,phrase="FRIENDLY"; + if(G.maps[character.map].safe) safe=true,phrase="SAFE ZONE"; + if(get_entity(data.id)) d_text(phrase,get_entity(data.id)); + else d_text(phrase,character); + if(safe) ui_log("You can't attack in a safe zone","gray"); + } + else if(response=="cooldown") + { + if(data.id && get_entity(data.id)) d_text("WAIT",get_entity(data.id)); + else d_text("WAIT",character); + } + else if(response=="too_far") d_text("TOO FAR",data.id && get_entity(data.id) || character); + else if(response=="invalid_target") d_text("DOESN'T WORK",data.id && get_entity(data.id) || character); + else if(response=="miss") + { + if(get_entity(data.id)) d_text("MISS",get_entity(data.id)); + else d_text("MISS",character); + } + else if(response=="disabled") + { + d_text("DISABLED",character); + } + else if(response=="attack_failed") + { + if(get_entity(data.id)) d_text("FAILED",get_entity(data.id)); + else d_text("FAILED",character); + if(data.reason=="level") ui_log("Level gap higher than 10","gray"); + } + else if(response=="no_skill") ui_log("Skill doesn't exist","gray"); + else if(response=="target_alive") d_text("LOOKS LIVE?",character); + else if(response=="slot_occuppied") ui_log("Slot occuppied","gray"); + else if(response=="no_target") d_text(!ctarget && "NO TARGET" || "INVALID TARGET",character); + else if(response=="non_friendly_target") d_text("NON FRIENDLY",character); + else if(response=="cant_respawn") ui_log("Can't respawn yet.","gray"); + else if(response=="chat_slowdown") ui_log("You can't chat this fast.","gray"); + else if(response=="not_in_party") ui_log("You are not in a party.","gray"); + else if(response=="challenge_sent") add_chat("","Challenged "+data.name+" to duel","white"); + else if(response=="challenge_accepted") add_chat("",data.name+" accepted the challenge!","#DF231B"); + else if(response=="challenge_received") + { + add_challenge(data.name); + call_code_function("trigger_character_event","challenge",data.name); + } + else if(response=="duel_started") + { + add_duel(data.challenger,data.vs,data.id); + call_code_function("trigger_character_event","duel",{challenger:data.challenger,vs:data.vs,id:data.id}); + } + else if(response=="no_level") { d_text("LOW LEVEL",character); } + else if(response=="not_in_pvp") { d_text("NO",character); } + else if(response=="skill_cant_incapacitated") { d_text("CAN'T USE",character); } + else if(response=="skill_cant_use") { d_text("CAN'T USE",character); } + else if(response=="skill_cant_safe") { d_text("CAN'T USE",character); } + else if(response=="skill_cant_item") { d_text("OUT OF AMMO",character); } + else if(response=="skill_cant_charges") { d_text("NO CHARGE",character); } + else if(response=="skill_cant_pve") { d_text("CAN'T USE",character); } + else if(response=="skill_cant_wtype") { ui_log("Wrong weapon","gray"); d_text("NOPE",character); } + else if(response=="skill_cant_slot") { ui_log("Item not equipped","gray"); d_text("NOPE",character); } + else if(response=="skill_cant_requirements") { ui_log("Skill requirements not met","gray"); d_text("NOPE",character); } + else if(response=="cruise") ui_log("Cruise speed set at "+data.speed,"gray"); + else if(response=="exchange_existing") { d_text("WAIT",character); ui_log("Existing exchange in progress","gray"); reopen(); } + else if(response=="exchange_notenough") { d_text("NOT ENOUGH",character); ui_log("Need more","gray"); reopen(); } + else if(in_arr(response,["mistletoe_success","leather_success","candycane_success","ornament_success","seashell_success","gemfragment_success"])) { render_interaction(response); } + else if(in_arr(response,["donate_thx","donate_gum","donate_low"])) + { + var message; + if(response=="donate_thx") message="Thanks kind sir. Thanks for helping the reserve."; + else if(response=="donate_gum") message=to_pretty_num(data.gold)+"? "+to_pretty_num(data.gold)+"? "+to_pretty_num(data.gold)+"?! Here, take this!"; + else if(response=="donate_low") message="They say there's no small contribution.. BUT THEY ARE OBVIOUSLY WRONG. "+to_pretty_num(data.gold)+"??!!! GET LOST"; + ui_log("Donated "+to_pretty_num(data.gold)+" gold","gray"); + render_interaction({auto:true,skin:"goblin",message:message}); + } + else if(response=="lostandfound_info") + { + var message="Hey there! I'm in charge of taking care of our gold reserve and making sure unlooted chests are 'recycled'! ",xp=3.2; + if(data.gold<500000000) message+="Currently the gold reserves are low, so I'm taking a small something something out of every chest :] ",xp=4.8; + else if(data.gold<1000000000) message+="Currently the gold reserves are low, so I'm taking a small something out of every chest :] ",xp=4; + message+="Donations are always welcome, merchants get "+xp+" XP for every gold they donate!"; + render_interaction({auto:true,skin:"goblin",message:message,button:"WHAT HAVE YOU FOUND?",onclick:function(){socket.emit('lostandfound')},button2:"DONATE",onclick2:function(){render_donate()}}); + } + else if(response=="lostandfound_donate") + { + var message="Not feeling like showing my loots to cheapskates! Sorry not sorry.."; + render_interaction({auto:true,skin:"goblin",message:message}); + } + else if(response=="bet_xshot") + { + var message="Get lost critter! You can't gamble substanced here!"; + render_interaction({auto:true,skin:"bouncer",message:message}); + if(Math.random()<0.5) d_text("MOVE B****",get_npc('bouncer'),{color:"#F7A9C5"}); + else d_text("GET OUT THE WAY",get_npc('bouncer'),{color:"#F7A9C5"}); + } + else if(response=="cant_escape") + { + d_text("CAN'T ESCAPE",character); + transporting=false; + } + else if(response=="cant_enter") + { + ui_log("Can't enter","gray"); + transporting=false; + } + else if(response=="cant_in_bank") + { + ui_log("Operation unavailable in bank","gray"); + } + else if(response=="bank_unavailable") ui_log("Bank unavailable","gray"); + else if(response=="bank_withdraw") ui_log("Withdrew "+to_pretty_num(data.gold)+" gold","gray"); + else if(response=="bank_store") ui_log("Stored "+to_pretty_num(data.gold)+" gold","gray"); + else if(response=="bank_new_pack") + { + if(data.gold) ui_log("Opened an account for "+to_pretty_num(data.gold)+" gold","gray"); + else ui_log("Opened an account for "+to_pretty_num(data.shells)+" shells","gray"); + } + else if(response=="locked") ui_log("Locked","gray"); + else if(response=="seller_gone") ui_log("Seller gone","gray"); + else if(response=="buyer_gone") ui_log("Buyer gone","gray"); + else if(response=="item_gone") ui_log("Item gone","gray"); + else if(response=="hmm") ui_log("Hmm.","gray"); + else if(response=="sneaky") ui_log("Sneaky sneaky.","gray"); + else if(response=="need_auth") ui_log("To perform this action your account needs a game client authorization","gray"); + else if(response=="giveaway_join") ui_log(data.name+" joined your giveaway!","gray"); + else if(response=="bank_opi") + { + ui_log("Bank connection in progress","gray"); + transporting=false; + } + else if(response=="bank_opx") + { + if(data.name) ui_log(data.name+" is in the bank","gray"); + else if(data.reason=="locked") ui_log("The door is locked","gray"); + else ui_log("Bank is busy right now","gray"); + transporting=false; + } + else if(response=="only_in_bank") + { + ui_log("Only works inside the bank","gray"); + } + else if(response=="already_unlocked") + { + ui_log("Already unlocked","gray"); + } + else if(response=="door_unlocked") + { + v_shake(); + ui_log("Door unlocked!","#9D9CFF"); + } + else if(response=="bank_pack_unlocked") + { + v_shake(); + ui_log("Teller unlocked!","#9D9CFF"); + } + else if(response=="transport_failed") + { + transporting=false; + } + else if(response=="loot_failed") + { + close_chests(); + ui_log("Can't loot","gray"); + } + else if(response=="no_space") + { + d_text("NO SPACE",character); + } + else if(response=="loot_no_space") + { + close_chests(); + d_text("NO SPACE",character); + } + else if(response=="transport_cant_reach") + { + ui_log("Can't reach","gray"); + transporting=false; + } + else if(response=="transport_cant_item") + { + ui_log("Item not found","gray"); + transporting=false; + } + else if(response=="transport_cant_dampened") + { + ui_log("Can't transport inside a dampening field","#A772D0"); + transporting=false; + v_shake_i2(character); + } + else if(response=="transport_cant_protection") + { + ui_log("The door is protected!","#A7282E"); + transporting=false; + } + else if(response=="transport_cant_locked") + { + ui_log("The door is locked!","#A7282E"); + transporting=false; + } + else if(response=="not_in_this_server") + { + ui_log("Not possible in this server","#7D5B93"); + } + else if(response=="destroyed") + { + ui_log("Destroyed "+G.items[data.name].name,"gray"); + } + else if(response=="distance") ui_log("Get closer","gray"); + else if(response=="trade_bspace") + { + ui_log("No space on buyer","gray"); + } + else if(response=="bank_restrictions") + { + ui_log("You can't buy, trade or upgrade in the bank.","gray"); + } + else if(response=="tavern_too_late") ui_log("Too late to bet!","gray"); + else if(response=="tavern_not_yet") ui_log("Not taking bets yet!","gray"); + else if(response=="tavern_too_many_bets") ui_log("You have too many active bets","gray"); + else if(response=="tavern_dice_exist") ui_log("You already have a bet","gray"); + else if(response=="tavern_gold_not_enough") ui_log("Gold reserve insufficient to cover this bet","gray"); + else if(response=="condition") + { + var def=G.conditions[data.name],from=data.from; + if(def.debuff) + { + ui_log("Afflicted by "+def.name,"gray"); + } + else if(from) + { + ui_log(from+" buffed you with "+def.name,"gray"); + } + else + { + ui_log("Buffed with "+def.name,"gray"); + } + } + else if(response=="cx_sent") + { + ui_log("Cosmetics sent: "+data.cx,"#DB7AA9"); + character.acx=data.acx; + } + else if(response=="cx_received") + { + ui_log("Cosmetics received: "+data.cx,"#A888DD"); + character.acx=data.acx; + } + else if(response=="cx_new") + { + if($("#topleftcornerdialog").length) + { + var html=""; + html+="
"; + html+="
"+cx_sprite(data.name)+"
"; + html+="
OK
"; + html+="
"; + $("#topleftcornerdialog").html(html); + } + else ui_log("Cosmetics: "+data.name,"#DB7AA9"); + character.acx=data.acx; + } + else if(response=="emotion_new") + { + ui_log("Emotion: "+data.name,"#DB7AA9"); + character.emx=data.emx; + } + else if(response=="cx_not_found") + { + ui_log("Cosmetics not found","gray"); + } + else if(response=="ex_condition") + { + var def=G.conditions[data.name]; + // ui_log(def.name+" faded away ...","gray"); + } + else if(response=="buy_success") + { + ui_log("Spent "+to_pretty_num(data.cost)+" gold","gray"); + } + else if(response=="buy_cant_npc") + { + ui_log("Can't buy this from an NPC","gray"); + } + else if(response=="buy_cant_space" || response=="cant_space") + { + d_text("SPACE",character); + ui_log("No space","gray"); + } + else if(response=="buy_cost") + { + d_text("INSUFFICIENT",character); + ui_log("Not enough gold","gray"); + } + else if(response=="emotion_cant") + { + d_text("NO",character); + } + else if(response=="emotion_cooldown") + { + d_text("WAIT",character); + } + else if(response=="cant_reach") ui_log("Can't reach","gray"); + else if(response=="no_item") ui_log("No item provided","gray"); + else if(response=="not_enough") ui_log("Not enough","gray"); + else if(response=="buyer_gold") ui_log("Not enough gold on buyer","gray"); + else if(response=="dont_have_enough") ui_log("Don't have enough","gray"); + else if(response=="op_unavailable") add_chat("","Operation unavailable","gray"); + else if(response=="send_no_space") add_chat("","No space on receiver","gray"); + else if(response=="send_no_item") add_chat("","Nothing to send","gray"); + else if(response=="send_no_cx") add_chat("","Don't have or not enough","gray"); + else if(response=="send_diff_owner") add_chat("","This is not one of ours!","gray"); + else if(response=="insufficient_q") ui_log("There aren't that many available","gray"); + else if(response=="signed_up") ui_log("Signed Up!","#39BB54"); + else if(response=="item_placeholder") + { + ui_log("Slot is occupied","gray"); + } + else if(response=="item_locked") + { + ui_log("Item is locked","gray"); + } + else if(response=="item_blocked") + { + ui_log("Item is in use","gray"); + } + else if(response=="item_received" || response=="item_sent") + { + var additional=""; + if(data.q>1) additional="(x"+data.q+")"; + if(response=="item_received") + { + add_chat("","Received "+G.items[data.item].name+additional+" from "+data.name,"#6AB3FF"); + call_code_function("trigger_character_event","item_received",{name:data.item,q:data.q,num:data.num,'from':data.name}); + } + else + { + add_chat("","Sent "+G.items[data.item].name+additional+" to "+data.name,"#6AB3FF"); + call_code_function("trigger_character_event","item_sent",{name:data.item,q:data.q,num:data.num,'to':data.name}); + } + } + else if(response=="add_item") + { + var additional="",prefix="a "; + if(data.item.q>1) additional="(x"+data.item.q+")",prefix=""; + add_log("Received "+prefix+G.items[data.item.name].name+additional,"#3B9358"); + } + else if(response=="gold_not_enough") ui_log("Not enough gold","gray"); + else if(response=="gold_sent") + { + add_chat("","Sent "+to_pretty_num(data.gold)+" gold to "+data.name,colors.gold); + call_code_function("trigger_character_event","gold_sent",{amount:data.gold,'to':data.name}); + } + else if(response=="gold_received" && !data.name) add_log("Received "+to_pretty_num(data.gold)+" gold","gray"); + else if(response=="gold_received") + { + add_chat("","Received "+to_pretty_num(data.gold)+" gold from "+data.name,colors.gold); + call_code_function("trigger_character_event","gold_received",{amount:data.gold,'from':data.name}); + } + else if(response=="friend_already") add_chat("","You are already friends","gray"); + else if(response=="friend_rleft") add_chat("","Player left the server","gray"); + else if(response=="friend_rsent") add_chat("","Friend request sent","#409BDD"); + else if(response=="friend_expired") add_chat("","Request expired","#409BDD"); + else if(response=="friend_failed") add_chat("","Friendship failed, reason: "+data.reason,"#409BDD"); + else if(response=="unfriend_failed") add_chat("","Unfriend failed, reason: "+data.reason,"#409BDD"); + else if(response=="gold_use") ui_log("Used "+to_pretty_num(data.gold)+" gold","gray"); + else if(response=="slots_success") ui_log("Machine went crazy","#9733FF"); + else if(response=="slots_fail") ui_log("Machine got stuck","gray"); + else if(response=="craft") + { + var def=G.craft[data.name]; + if(def.cost) ui_log("Spent "+to_pretty_num(def.cost)+" gold","gray"); + ui_log("Received "+G.items[data.name].name,"white"); + } + else if(response=="dismantle") + { + var def=G.dismantle[data.name]; + if(data.level) ui_log("Spent "+to_pretty_num(data.cost||10000)+" gold","gray"); + else ui_log("Spent "+to_pretty_num(def.cost)+" gold","gray"); + ui_log("Dismantled "+G.items[data.name].name,"#CF5C65"); + } + else if(response=="defeated_by_a_monster") + { + ui_log("Defeated by "+G.monsters[data.monster].name,"#571F1B"); + ui_log("Lost "+to_pretty_num(data.xp)+" experience","gray"); + } + else if(response=="dismantle_cant") ui_log("Can't dismantle","gray"); + else if(response=="inv_size") ui_log("Need more empty space","gray"); + else if(response=="craft_cant") ui_log("Can't craft","gray"); + else if(response=="craft_cant_quantity") ui_log("Not enough materials","gray"); + else if(response=="craft_atleast2") ui_log("You need to provide at least 2 items","gray"); + else if(response=="target_lock") + { + ui_log("Target Acquired: "+G.monsters[data.monster].name,"#F00B22"); + } + else if(response=="charm_failed") + { + ui_log("Couldn't charm ...","gray"); + } + else if(response=="cooldown") + { + d_text("NOT READY",character); + } + else if(response=="blink_failed") + { + no_no_no(); + d_text("NO",character); + last_blink_pressed=inception; + } + else if(response=="dash_failed") + { + no_no_no(); + d_text("CANT",character); + } + else if(response=="magiport_sent") + { + ui_log("Magiportation request sent to "+data.id,"white"); + } + else if(response=="magiport_gone") + { + ui_log("Magiporter gone","gray"); + no_no_no(2); + } + else if(response=="magiport_failed") ui_log("Magiport failed","gray"),no_no_no(2); + else if(response=="revive_failed") ui_log("Revival failed","gray"),no_no_no(1); + else if(response=="locksmith_cant") + { + ui_log("Can't lock/unlock this item","gray") + } + else if(response=="locksmith_aunlocked") + { + ui_log("Already unlocked","gray") + } + else if(response=="locksmith_alocked") + { + ui_log("Already locked","gray") + } + else if(response=="locksmith_unsealed") + { + ui_log("Spent 250,000 gold","gray"); + ui_log("Unsealed the item","gray"); + ui_log("It can be unlocked in 2 days","gray") + } + else if(response=="locksmith_unsealing") + { + ui_log("It can be unlocked in "+parseInt(data.hours)+" hours","gray") + } + else if(response=="locksmith_unlocked") + { + ui_log("Spent 250,000 gold","gray"); + ui_log("Unlocked the item","gray"); + } + else if(response=="locksmith_unseal_complete") + { + ui_log("Unlocked the item","gray"); + } + else if(response=="locksmith_locked") + { + ui_log("Spent 250,000 gold","gray"); + ui_log("Locked the item","gray"); + } + else if(response=="locksmith_sealed") + { + ui_log("Spent 250,000 gold","gray"); + ui_log("Sealed the item","gray"); + } + else if(response=="monsterhunt_started" || response=="monsterhunt_already") + { + if(!character.s.monsterhunt) return; + if(character.s.monsterhunt.c==1) $("#merchant-item").html(render_interaction({auto:true,skin:"daisy",message:"Alrighty then! Now go defeat "+G.monsters[character.s.monsterhunt.id].name+" and come back here!"},"return_html")); + else $("#merchant-item").html(render_interaction({auto:true,skin:"daisy",message:"Alrighty then! Now go defeat "+character.s.monsterhunt.c+" "+G.monsters[character.s.monsterhunt.id].name+"'s and come back here!"},"return_html")); + } + else if(response=="monsterhunt_merchant") + { + $("#merchant-item").html(render_interaction({auto:true,skin:"daisy",message:"Huh? A merchant? On the hunt? Hahahahahahahaha ... Go sell cake or something ..."},"return_html")); + } + else + { + console.log("Missed game_response: "+response); + } + }); + }); + socket.on("gm",function(data){ + if(data.ids && data.action=="jump_list"){ + var buttons=[]; + hide_modal(); + data.ids.forEach(function(id){ + buttons.push({button:id,onclick:function(){socket.emit("gm",{action:"jump",id:id})}}); + }); + get_input({no_wrap:true,elements:buttons}); + } + else if(data.action=="server_info") + { + show_json(data.info); + } + }); + socket.on("secondhands",function(data){ + secondhands=data; + secondhands.reverse(); + if(topleft_npc!="secondhands") s_page=0; + render_secondhands(); + }); + socket.on("lostandfound",function(data){ + lostandfound=data; + lostandfound.reverse(); + if(topleft_npc!="lostandfound") l_page=0; + render_secondhands("lostandfound"); + }); + socket.on("game_chat_log",function(data){ + draw_trigger(function(){ + if(is_string(data)) add_chat("",data) + else add_chat("",data.message,data.color); // <- add_chat needs a different color logic + }); + }); + socket.on('chat_log',function(data){ // <- bad naming [22/10/16] + draw_trigger(function(){ + var entity=get_entity(data.id); + if(data.id=="mainframe") + { + d_text(data.message,{real_x:0,real_y:-100,height:24},{size:SZ.chat,color:"#C7EFFF"}); + sfx("chat",0,-100); + } + else if(entity) + { + d_text(data.message,entity,{size:SZ.chat}); + sfx("chat",entity.real_x,entity.real_y); + } + else sfx("chat"); + add_chat(data.owner,data.message,data.color,is_number(data.id)&&data.id||undefined); + call_code_function("trigger_event","chat",{from:data.owner,message:data.message}); + }); + }); + socket.on('emotion',function(data){ + draw_trigger(function(){ + var player=get_player(data.player); + var emotion=data.name; + if(emotion=="drop_egg") + { + if(player) map_animation(random_one(["egg0","egg1","egg2","egg3","egg4","egg5","egg6","egg7","egg8","goldenegg"]),{x:get_x(player),y:get_y(player)+1,target:{x:get_x(player),y:get_y(player)+5,height:0},item:true,fade:0.005,speed:0.01,limit:1,scale:0.5,filter:new PIXI.filters.OutlineFilter(0.5,hx("#ABA3BC"))}); + if(player) v_shake_i(player); + setTimeout(function(){ sfx("drop_egg"); },30); + } + else if(player) + { + start_animation(player,emotion); + } + }); + }); + socket.on('ui',function(data){ + if(data.event) call_code_function("trigger_event",data.event===true&&data.type||data.event,data); + if(data.cevent && data.name==character.name) call_code_function("trigger_character_event",data.cevent===true&&data.type||data.cevent,data); + // show_json(data); + draw_trigger(function(){ + if(in_arr(data.type,["+$","-$"])) + { + var npc=get_npc(data.npc),player=get_player(data.name); + if(topleft_npc=="merchant" && merchant_id) npc=get_npc(merchant_id)||npc; + if(data.type=="-$") + { + if(npc) d_text(data.type,npc,{color:colors.white_negative}); + if(player) d_text("+$",player,{color:colors.white_positive}); + } + else + { + if(npc) d_text(data.type,npc,{color:colors.white_positive}); + if(player) d_text("-$",player,{color:colors.white_negative}); + } + } + else if(data.type=="+$p") + { + var npc=get_npc("secondhands"),player=get_player(data.name); + if(npc) d_text("+$",npc,{color:"#7E65D3"}); //,start_animation(npc,"purple_success"); + if(player) d_text("-$",player,{color:"#7E65D3"}); + call_code_function("trigger_event","sbuy",{item:data.item,name:data.name}); + } + else if(data.type=="+M") + { + var player=get_player(data.name); + if(player) d_text("+M",player,{color:"#67D385"}); + } + else if(data.type=="restore_mp") + { + var player=get_player(data.id); + if(player) d_text("+"+data.amount+" MPX!",player,{color:"#6585D3",huge:true}); + } + else if(data.type=="+$f") + { + var npc=get_npc("lostandfound"),player=get_player(data.name); + if(npc) d_text("+$",npc,{color:"#7E65D3"}); //,start_animation(npc,"purple_success"); + if(player) d_text("-$",player,{color:"#7E65D3"}); + call_code_function("trigger_event","fbuy",{item:data.item,name:data.name}); + } + else if(data.type=="+$$") + { + var seller=get_player(data.seller),buyer=get_player(data.buyer); + if(seller) d_text(data.type,seller,{color:colors.white_positive}); + if(buyer) d_text("-$$",buyer,{color:colors.white_negative}); + call_code_function("trigger_event","trade",{seller:data.seller,buyer:data.buyer,item:data.item,num:data.num,slot:data.slot}); + if(seller.me) call_code_function("trigger_event","sale",{buyer:data.buyer,item:data.item,num:data.num,slot:data.slot}); + } + else if(data.type=="gold_sent") + { + var sender=get_player(data.sender),receiver=get_player(data.receiver); + if(sender && receiver) d_line(sender,receiver,{color:"gold"}); + } + else if(data.type=="item_sent") + { + var sender=get_player(data.sender),receiver=get_player(data.receiver); + if(sender && receiver) d_line(sender,receiver,{color:"item"}); + } + else if(data.type=="cx_sent") + { + var sender=get_player(data.sender),receiver=get_player(data.receiver); + if(sender && receiver) d_line(sender,receiver,{color:"cx"}); + } + else if(data.type=="magiport") + { + var player=get_player(data.name); + if(player) + { + d_text("M",player,{size:"huge",color:"#3E97AA"}); + jump_up(); + } + } + else if(data.type=="mlevel") + { + var m=get_entity(data.id); + if(m) d_text(data.mult==-1&&"-1"||"+1",m,{color:"#9C76D3",size:"huge"}); + } + else if(data.type=="disengage") + { + var m=get_entity(data.id); + if(m) d_text("FFT..",m,{color:"#84A1D1"}); + } + else if(data.type=="mheal") + { + var m=get_entity(data.id); + if(m) d_text(data.heal,m,{color:colors.heal,size:"large"}); + } + else if(data.type=="throw") + { + var sender=get_player(data.from),receiver=get_entity(data.to); + if(sender && receiver) d_line(sender,receiver,{color:"#323232"}); + } + else if(data.type=="energize") + { + var sender=get_player(data.from),receiver=get_player(data.to); + if(sender && receiver) d_line(sender,receiver,{color:"mana"}); + if(receiver) start_animation(receiver,"block"); + } + else if(data.type=="mluck") + { + var sender=get_player(data.from),receiver=get_player(data.to); + if(sender && receiver) d_line(sender,receiver,{color:"mluck"}); + if(receiver) start_animation(receiver,"mluck"); + } + else if(data.type=="rspeed") + { + var sender=get_player(data.from),receiver=get_player(data.to); + if(sender && receiver) d_line(sender,receiver,{color:"#D4C392"}); + if(receiver) start_animation(receiver,"rspeed"); + } + else if(data.type=="reflection") + { + var sender=get_player(data.from),receiver=get_player(data.to); + if(sender && receiver) d_line(sender,receiver,{color:"#9488BF"}); + } + else if(data.type=="alchemy") + { + var sender=get_player(data.name); + if(sender) + { + map_animation("gold",{x:get_x(sender),y:get_y(sender)-36,target:{x:get_x(sender),y:get_y(sender)-90,height:0,fade:true}}); + start_animation(sender,"gold_anim"); + v_shake_i(sender); + } + } + else if(data.type=="4fingers") + { + var sender=get_player(data.from),receiver=get_player(data.to); + if(sender && receiver) d_line(sender,receiver,{color:"#6F62AE"}); + if(sender) mojo(sender); + } + else if(data.type=="mcourage") + { + var sender=get_player(data.name); + if(sender) d_text("OMG!",sender,{size:"huge",color:"#B9A08C"}); + } + else if(data.type=="mfrenzy") + { + var sender=get_player(data.name); + if(sender) d_text("OMG!!",sender,{size:"huge",color:"#B9A08C"}); + } + else if(data.type=="fishing_fail") + { + var sender=get_player(data.name); + if(sender) v_shake_i2(sender); + if(sender.me) add_log("Failed to fish","gray"); + } + else if(data.type=="fishing_none") + { + add_log("Didn't catch anything","gray"); + } + else if(data.type=="fishing_start") + { + var sender=get_player(data.name); + if(sender) + { + v_shake_minor(sender); + sender.a_direction=sender.direction=data.direction; + } + } + else if(data.type=="mining_fail") + { + var sender=get_player(data.name); + if(sender) v_shake_i2(sender); + if(sender.me) add_log("Failed to mine","gray"); + } + else if(data.type=="mining_none") + { + add_log("Didn't mine anything","gray"); + } + else if(data.type=="mining_start") + { + var sender=get_player(data.name); + if(sender) + { + v_shake_minor(sender); + sender.a_direction=sender.direction=data.direction; + } + } + else if(data.type=="poison_resist") + { + var target=get_entity(data.id); + if(target) d_text("RESIST!",target,{color:"#68B84B"}); + } + else if(data.type=="freeze_resist") + { + var target=get_entity(data.id); + if(target) d_text("RESIST!",target,{color:"#66C1C8"}); + } + else if(data.type=="fire_resist") + { + var target=get_entity(data.id); + if(target) d_text("RESIST!",target,{color:"#B22F1A"}); + } + else if(data.type=="stun_resist") + { + var target=get_entity(data.id); + if(target) d_text("RESIST!",target,{color:"crit"}); + } + else if(data.type=="huntersmark") + { + var sender=get_player(data.name); + var target=get_entity(data.id); + if(sender && target) d_line(sender,target,{color:"#730E0B"}); + if(target) d_text("X",target,{size:"huge",color:"#730E0B"}); + } + else if(data.type=="agitate") + { + var attacker=get_entity(data.name); + data.ids.forEach(function(id){ + var entity=entities[id]; if(!entity) return; + start_emblem(entity,"rr1",{frames:20}); + }); + if(attacker) start_emblem(attacker,"rr1",{frames:10}); + } + else if(data.type=="stomp") + { + var attacker=get_entity(data.name); + data.ids.forEach(function(id){ + var entity=entities[id]; if(!entity) return; + start_emblem(entity,"br1",{frames:30}); + if(1 || attacker!=character) v_shake_i(entity); + }); + if(attacker) start_emblem(attacker,"br1",{frames:5}); + // if(character && get_entity(data.name) && distance(character,get_entity(data.name))<600) v_shake(); + if(attacker==character) v_dive(); + else if(attacker) v_dive_i(attacker); + } + else if(data.type=="scare") + { + var attacker=get_entity(data.name); + data.ids.forEach(function(id){ + var entity=entities[id]; if(!entity) return; + start_emblem(entity,"j1",{frames:5}); + v_shake_i2(entity); + }); + if(attacker) d_text("BE GONE!",attacker,{size:"huge",color:"#ff5817"}); + } + else if(data.type=="cleave") + { + var points=[],attacker=get_entity(data.name); + data.ids.forEach(function(id){ + var entity=entities[id]||entities["DEAD"+id]; if(!entity) return; + points.push({x:get_x(entity),y:get_y(entity)}); + if(attacker) disappearing_clone(attacker,{x:(get_x(entity)+get_x(attacker)*2)/3.0,y:(get_y(entity)+get_y(attacker)*2)/3.0,random:true}) + }); + if(attacker) points.push({x:get_x(attacker),y:get_y(attacker)}),flurry(attacker); + cpoints=convexhull.makeHull(points); + for(var i=0;i=100000000) confetti_shower(player,2); + else if(data.net>=10000000) confetti_shower(player,1); + } + if(player && player.me) + { + dice_bet.active=false; + on_dice_change(); + $(".diceb").css("border-color","green"); + } + } + if(data.event=="lost") + { + var player=get_entity(data.name); + if(player) + { + d_text("-B",player,{color:"red"}); + if(data.gold>=10000000) assassin_smoke(player.real_x,player.real_y); + } + if(player && player.me) + { + dice_bet.active=false; + on_dice_change(); + $(".diceb").css("border-color","red"); + } + } + }); + socket.on("dice",function(data){ + console.log(JSON.stringify(data)); + if(data.state=="roll") + map_machines.dice.shuffling=true,map_machines.dice.num=undefined,delete map_machines.dice.lock_start,map_machines.dice.locked=0; + if(data.state=="lock") + map_machines.dice.num=data.num,map_machines.dice.lock_start=new Date(); + if(data.state=="bets") + map_machines.dice.shuffling=false,map_machines.dice.seconds=0,map_machines.dice.count_start=new Date(),dice_bet.active=false,on_dice_change(); + }); + socket.on("upgrade",function(data){ + //show_json(data); + draw_trigger(function(){ + if(data.type=="upgrade") assassin_smoke(G.maps.main.ref.u_mid[0],G.maps.main.ref.u_mid[1],"explode_up"); + else if(data.type=="compound") assassin_smoke(G.maps.main.ref.c_mid[0],G.maps.main.ref.c_mid[1],"explode_up"); + else if(data.type=="poof") assassin_smoke(G.maps.spookytown.ref.poof.x,G.maps.spookytown.ref.poof.y,"explode_up"); + map_npcs.forEach(function(npc){ + if(data.type=="exchange" && npc.role==data.type) + { + start_animation(npc,"exchange"); + } + if(npc.role=="newupgrade" && (data.type=="upgrade" || data.type=="compound")) + { + if(data.success) start_animation(npc,"success"); + else start_animation(npc,"failure"); + } + if(npc.role=="funtokens" && data.type=="funtokens") + { + start_animation(npc,"exchange"); + } + if(npc.role=="pvptokens" && data.type=="pvptokens") + { + start_animation(npc,"exchange"); + } + if(npc.role=="friendtokens" && data.type=="friendtokens") + { + start_animation(npc,"exchange"); + } + if(npc.role=="monstertokens" && data.type=="monstertokens") + { + start_animation(npc,"exchange"); + } + }); + }); + }); + socket.on('map_info',function(data){ + I=data; + render_map(); + }); + socket.on('server_info',function(data){ + S=data; + render_server(); + }); + socket.on('hardcore_info',function(data){ + S=data.E; + if(data.achiever) + add_chat("mainframe",data.achiever+" ranked on the rewards list!","#60B879"); + render_server(); + }); + socket.on("server_message",function(data){ + // console.log(data.message); + draw_trigger(function(){ + add_chat("",data.message,data.color||"orange"); + if(data.log && character) add_log(data.message,data.color||"orange"); + if(data.type && data.item) call_code_function("trigger_event",data.type,{item:data.item,name:data.name}); + }); + }); + socket.on("notice",function(data){ + add_chat("SERVER",data.message,data.color||"orange"); + }); + socket.on("reloaded",function(data){ + add_chat("SERVER","Executed a live reload. (Optional) Refresh the game.","orange"); + if(data.change) add_chat("CHANGES",data.change,"#59CAFF"); + reload_data(); + }); + socket.on('chest_opened',function(data){ + tut("firstloot"); + call_code_function("trigger_character_event","loot",data); + if(data.opener==character.name || data.gone) resolve_deferred("open_chest",data); + draw_trigger(function(){ + if(chests[data.id]) + { + var chest=chests[data.id],x=chest.x,y=chest.y; + if(is_hidden()) + { + destroy_sprite(chest); + delete chests[data.id]; + } + else + { + if(!chest.openning) + { + chest.openning=new Date(); + set_texture(chest,++chest.frame); + } + chest.to_delete=true; + chest.alpha=0.8; + } + sfx("coins",x,y); + } + try{ + var chars=get_active_characters(); + for(var name in chars) + { + if(chars[name]=="code" || chars[name]=="active") + { + character_window_eval(name,"delete chests['"+data.id+"'];") + } + } + }catch(e){console.log(e);} + }); + }); + socket.on('cm',function(data){ + try{ + call_code_function("trigger_character_event","cm",{name:data.name,message:JSON.parse(data.message)}); + }catch(e){ + console.log(e); + } + }); + socket.on('pm',function(data){ + draw_trigger(function(){ + var entity=get_entity(data.id); + if(entity) + { + d_text(data.message,entity,{size:SZ.chat,color:"#BA6B88"}); + sfx("chat",entity.real_x,entity.real_y); + } + else + { + sfx("chat"); + } + var cid="pm"+(data.to||data.owner); + add_pmchat(data.to||data.owner,data.owner,data.message,data.xserver); + if(in_arr(cid,docked)) add_chat(data.owner,data.message,"#CD7879"); + call_code_function("trigger_character_event","pm",{from:data.owner,message:data.message}); + }); + }); + socket.on('partym',function(data){ + draw_trigger(function(){ + var entity=get_entity(data.id); + if(entity) + { + d_text(data.message,entity,{size:SZ.chat,color:"#5B8DB0"}); + sfx("chat",entity.real_x,entity.real_y); + } + else + { + sfx("chat"); + } + add_partychat(data.owner,data.message); + if(in_arr("party",docked)) add_chat(data.owner,data.message,"#46A0C6"); + call_code_function("trigger_character_event","partym",{from:data.owner,message:data.message}); + }); + }); + socket.on('drop',function(data){ + draw_trigger(function(){ chest=add_chest(data); }); + }); + socket.on("reopen",function(data){ + reopen(); + }) + socket.on('code_eval',function(data){ + if(no_eval) return; + var code=data.code||data||""; + code_eval(code); + }); + socket.on('simple_eval',function(data){ + if(no_eval) return; + eval(data.code||data||""); + }); + socket.on('eval',function(data){ + if(no_eval) return; + smart_eval(data.code||data||"",data.args); + }); + socket.on('player',function(data){ + // more draw_trigger's might be needed in the future [24/09/18] + var hitchhikers=data.hitchhikers; + delete data.hitchhikers; + if(character) adopt_soft_properties(character,data),rip_logic(); + if(hitchhikers) hitchhikers.forEach(function(tuple){ original_onevent.apply(socket,[{"type":2,"nsp":"/","data":tuple}]); }); + if(data.reopen) draw_trigger(function(){ reopen(); }); // draw_trigger is new [24/09/18] + }); + socket.on('q_data',function(data){character.q=data.q;character.items[data.num].p=data.p;}) + socket.on('end',function(data){}); + socket.on('disconnect',function(){ socket.destroy(); window.socket=null; disconnect(); }); + socket.on('disconnect_reason',function(reason){ window.disconnect_reason=reason; }); + socket.on('limitdcreport',function(data){ + window.rc_delay=16; + data.calls['!']="You've made "+data.climit+" callcosts in 4 seconds. That's tooooo much. This is most probably because you are calling a function like 'move' consecutively. Some calls are also more expensive than others. If you are experiencing issues please email hello@adventure.land or ask for help in Discord/#code_beginner. Ps. You made "+to_pretty_num(data.total)+" calls in total."; + show_json(data.calls); + }); + socket.on('ccreport',function(data){ + call_code_function("trigger_event","ccreport",data); + }); + socket.on('action',function(data){ + if(is_sdk) console.log(data); + var attacker=get_entity(data.attacker); + var target=get_entity(data.target),no_target=false; + if(!attacker) return; + if(!target) target={"x":data.x,"y":data.y,"map":attacker.map,"in":attacker["in"],height:0,width:0,m:data.m},no_target=true; + + direction_logic(attacker,target,"attack"); + attack_animation_logic(attacker,data.source); + animate_weapon(attacker,target); + + var event_data={actor:data.attacker}; + for(var name in data) + if(!in_arr(name,["attacker"])) + event_data[name]=data[name]; + if(data.heal) event_data.heal=data.heal; + else if(data.damage) event_data.damage=data.damage; + + call_code_function("trigger_event","action",event_data); + if(target.me) call_code_function("trigger_character_event","incoming",event_data); + + var color="red"; + if(new_attacks) + { + if(G.projectiles[data.projectile] && G.projectiles[data.projectile].animation) + map_animation(G.projectiles[data.projectile].animation,{x:get_x(attacker),y:get_y(attacker)-15,target:target,m:data.m,id:data.pid,filter:!G.projectiles[data.projectile].pure&&attacker&&attacker.filter_wglow}); + + if(G.projectiles[data.projectile] && G.projectiles[data.projectile].ray) + continuous_map_animation(G.projectiles[data.projectile].ray,attacker,target); + } + else + { + var owner=attacker,entity=target; + if(data.heal!==undefined) d_line(owner,entity,{color:"heal"}); + else if(data.anim=="supershot") d_line(owner,entity,{color:"supershot"}); + else if(owner && !data.no_lines) d_line(owner,entity); + } + + }); + socket.on('hit',function(data){ + var entity=get_entity(data.id); + var owner=get_entity(data.hid); + var color="red"; + + if(map_animations[data.pid]) map_animations[data.pid].to_delete=true; + + var attack_data=clone(data); delete attack_data.id; delete attack_data.hid; + attack_data.actor=data.hid; attack_data.target=data.id; + if(data.stacked && entity && entity.me) call_code_function("trigger_character_event","stacked",{method:"attack",ids:data.stacked}); + if(data.mobbing && entity && entity.me) call_code_function("trigger_character_event","mobbing",{intensity:data.mobbing}); + if(data.heal!==undefined) + { + attack_data.heal=abs(data.heal); + delete attack_data.damage; + } + if(owner && owner.me) call_code_function("trigger_character_event","target_hit",attack_data); + if(entity && entity.me) call_code_function("trigger_character_event","hit",attack_data); + call_code_function("trigger_event","hit",attack_data); + + draw_trigger(function(){ + var evade=false,offsets=0; + if(entity && data.evade) sfx("whoosh",entity.real_x,entity.real_y); + if(entity && data.reflect) sfx("reflect",entity.real_x,entity.real_y); + if(data.reflect) + { + t=true; + d_text("REFLECT!",entity,{color:"reflect",from:data.hid,size:"huge"}); + } + if(data.evade) + { + evade=true; + d_text("EVADE",entity,{color:"evade",size:"huge",from:data.hid}); + } + if(data.miss) + { + evade=true; + d_text("OOPS",entity,{color:"evade",size:"huge",from:data.hid}); + } + if(data.avoid) + { + var c={x:data.x,y:data.y,map:data.map,'in':data['in'],height:14}; + // console.log(c); + if(entity==character) c=character; + evade=true; + d_text("AVOID",c,{color:"evade",size:"huge",from:data.hid}); + } + if(entity && data.goldsteal) + { + if(data.goldsteal>0) + { + d_text("-"+data.goldsteal,entity,{color:"gold",from:data.hid,y:-8}); + if(entity==character) + add_log("You lost "+to_pretty_num(data.goldsteal)+" gold","#5D5246"); + } + else + { + d_text("+"+(-data.goldsteal),entity,{color:"gold",from:data.hid,y:-8}); + if(entity==character) + add_log("Received "+to_pretty_num(-data.goldsteal)+" gold, huh","#25B77D"); + } + } + if(entity && data.projectile && !evade && G.projectiles[data.projectile].hit_animation) + { + var anim=G.projectiles[data.projectile].hit_animation; + if(G.animations[anim]) + start_animation(entity,anim); + } + if(entity && !evade) + sfx("monster_hit",entity.real_x,entity.real_y); + if(entity && data.projectile && !evade && G.projectiles[data.projectile].hit_text) + { + d_text(G.projectiles[data.projectile].hit_text[0],entity, + {color:G.projectiles[data.projectile].hit_text[1],size:"huge",offset:-offsets*25-10}); + offsets+=1; + } + if(entity && data.projectile && !evade && G.projectiles[data.projectile].kill_text && (entity.dead || entity.hp<=0)) + { + d_text(G.projectiles[data.projectile].kill_text[0],entity, + {color:G.projectiles[data.projectile].kill_text[1],size:"huge",offset:-offsets*25-10}); + offsets+=1; + } + if(data.crit) + { + var disp="2X"; + if(data.crit>2.90) disp="3X"; + else if(data.crit>2.74) disp="2.75X"; + else if(data.crit>2.44) disp="2.5X"; + else if(data.crit>2.20) disp="2.25X"; + d_text(disp,entity,{color:"crit",size:"huge",from:data.hid,offset:-offsets*25-10}); + offsets+=1; + } + if(entity && owner && data.damage!==undefined && !evade) // added && owner [15/01/18] + { + if(data.dreturn) d_text("-"+data.dreturn,owner,{color:color}); + if(data.damage>0) d_text("-"+data.damage,entity,{color:color}); + } + if(entity && data.heal!==undefined && !evade) + { + var y=0; + if(data.source=="partyheal" || data.source=="selfheal") start_animation(entity,"party_heal"),y=16; + d_text("+"+data.heal,entity,{color:colors.heal,y:y}); + } + }); + }); + socket.on("disappearing_text",function(data){ + draw_trigger(function(){ + if(!data.args) data.args={}; + if(data.args.sz) data.args.size=data.args.sz; + if(data.args.c) data.args.color=data.args.c; + + var entity=(data.id && get_entity(data.id)); + + // if(data.message=="+50" && entity && entity.me) add_log("Regenerated 50 HP","gray"); + // if(data.message=="+100" && entity && entity.me) add_log("Regenerated 100 MP","gray"); + + if(entity) d_text(data.message,entity,data.args); + else d_text(data.message,data.x,data.y,data.args); + }); + }); + socket.on('death',function(data){ + // unused now + if(data.place) reject_deferred(data.place,{reason:data.reason||"not_found"}); + call_code_function("trigger_event","death",data); + data.death=true; + on_disappear(data); + }); + socket.on("disappear",function(data){ + if(data.place) reject_deferred(data.place,{reason:data.reason||"not_found"}); + on_disappear(data); + }); + socket.on('entities',function(data){ + if(data['in']!=current_in) return console.log("Disregarded stale 'entities' response"); + if(data['type']=="all") future_entities={players:{},monsters:{}}; // also on new_map_logic + // console.log("Entities: "+data['in']); + handle_entities(data); + }); + socket.on('poke',function(data){ + draw_trigger(function(){ + var entity=get_entity(data.name); + if(entity) + { + if(entity==character) add_log(data.who+" poked you","gray") + if(data.level>=2) add_chat("",data.who+" poked "+data.name,"gray"); + bump_up(entity,data.level*2); + } + }); + }); + socket.on('test',function(data){ console.log(data.date); }); + socket.on('invite',function(data){ + draw_trigger(function(){ add_invite(data.name); }); + setTimeout(function(){ call_code_function("on_party_invite",data.name); },200); + }); + socket.on('magiport',function(data){ + draw_trigger(function(){ add_magiport(data.name); }); + setTimeout(function(){ call_code_function("on_magiport",data.name); },200); + }); + socket.on('request',function(data){ + draw_trigger(function(){ add_request(data.name); }); + setTimeout(function(){ call_code_function("on_party_request",data.name); },200); + }); + socket.on('frequest',function(data){ + draw_trigger(function(){ add_frequest(data.name); }); + setTimeout(function(){ call_code_function("on_friend_request",data.name); },200); + }); + socket.on('friend',function(data){ + draw_trigger(function(){ + if(data.event=="new") + { + add_chat("","You are now friends with "+data.name,"#409BDD"); + friends=data.friends; + } + if(data.event=="lost") + { + add_chat("","Lost a friend","#DB5E59"); // : "+data.name + friends=data.friends; + } + if(data.event=="request") + { + add_frequest(data.name); + } + if(data.event=="update") + { + friends=data.friends; + } + }); + }); + socket.on('party_update',function(data){ + draw_trigger(function(){ + if(data.message) + { + if(data.leave) add_log(data.message,"#875045"); + else add_log(data.message,"#703987"); + } + if(party_list.length==0 && (data.list||[]).length && !in_arr("party",cwindows)) open_chat_window("party"); + party_list=data.list||[]; + party=data.party||{}; + render_party(); + }); + }); + socket.on('blocker',function(data){ + if(data.type=="pvp") + { + if(data.allow) + { + add_chat("Ace","Be careful in there!","#62C358"); + draw_trigger(function(){ + var npc=get_npc("pvpblocker"); + if(npc) + { + map_npcs.splice(map_npcs.indexOf(get_npc("pvpblocker")),1); + draw_timeout(fade_away(1,npc),30,1); + } + }); + } + else + { + add_chat("Ace","I will leave when there are 6 adventurers around.","#C36348"); + } + } + }); + socket.on('tracker',function(data){ + tracker=data; + render_tracker(); + }) + socket.on('trade_history',function(data){ + //h-> [event,name,item,price] + var html=""; + data.forEach(function(h){ + var item=G.items[h[2].name].name,prefix=""; + if(h[2].level) item+=" +"+h[2].level; + if(h[2].q) prefix+=""+h[2].q+"x "; + if(h[0]=="buy") + { + html+="
- Bought "+prefix+"'"+item+"' from "+h[1]+" for "+to_pretty_num(h[3])+" gold
"; + } + else if(h[0]=="giveaway") + { + html+="
- Gave away "+prefix+"'"+item+"' to "+h[1]+"
"; + } + else + { + html+="
- Sold "+prefix+"'"+item+"' to "+h[1]+" for "+to_pretty_num(h[3])+" gold
"; + } + }); + if(!data.length) add_log("No trade recorded yet.","gray"); + else show_modal(html); + }); + socket.on("track",function(list){ + if(!list.length) return add_log("No echoes","gray"); + if(list.length==1) { add_log("One echo","gray"); add_log(parseInt(list[0].dist)+" clicks away","gray"); return; } + var c=""; + add_log(list.length+" echoes","gray"); + list.forEach(function(e){ + if(!c) c=parseInt(e.dist); + else c=c+","+parseInt(e.dist); + }); + add_log(c+" clicks","gray"); + }); +} + +function npc_right_click(event){ + var npc=G.npcs[this.npc]; + sfx("npc",this.x,this.y); + if(this.type=="character") npc=G.npcs[this.npc]; + last_npc_right_click=new Date(); + $("#topleftcornerdialog").html(""); + next_side_interaction=npc.side_interaction; + if(!npc.color && current_map=="main") npc.color=colors.npc_white; + if(this.role!="shrine" && this.role!="compound") + { + var says=npc.says||"Yes"; + if(is_array(says)) says=says[seed1()%says.length]; + if(says=="rbin") says=random_binary(); + d_text(says,this,{color:npc.color}); + } + if(this.role=="secondhands") + { + socket.emit("secondhands"); + } + if(this.role=="lostandfound") + { + socket.emit("lostandfound","info"); + } + if(this.role=="blocker") + { + socket.emit("blocker",{type:"pvp"}); + } + if(this.role=="merchant") + { + render_merchant(this); + if(!inventory) render_inventory(); + } + if(this.role=="premium") + { + render_merchant(this,1); + if(!inventory) render_inventory(); + } + if(this.role=="gold") + { + render_gold_npc(); + if(!inventory) render_inventory(); + } + if(this.role=="items") + { + render_items_npc(this.pack); + } + if(this.role=="exchange") + { + render_exchange_shrine(1); + } + if(this.role=="events") + { + if(character.home!=server_region+server_identifier) + { + render_interaction({auto:true,skin:"lionsuit",message:"This is not your home server. You are a resident of "+character.home+". Would you like to set this server as your home?",button:"Yes!",onclick:function(){ socket.emit('set_home'); push_deferred('set_home'); }}); + } + else + { + render_interaction({auto:true,skin:"lionsuit",message:"This is your home server. Make sure to follow daily and nightly server events! Just click the time icon in the bottom left corner for the schedule!"}) + } + } + if(this.role=="mcollector") + { + render_recipes("mcollector"); + $("#recipe-item").html(render_interaction({auto:true,skin:"proft",message:"Always looking for new materials for a grand project of mine. Bring the materials you find to me, I will exchange them for items that are more useful to you."},"return_html")); + } + if(this.role=="witch") + { + render_recipes("witch"); + $("#recipe-item").html(render_interaction({auto:true,skin:"brewingwitch",message:"My child, bring me the materials I seek and I shall unlock unimaginable horrors for you!"},"return_html")); + } + if(this.role=="shrine") + { + render_upgrade_shrine(1); + } + if(this.role=="newupgrade") + { + render_interaction("newupgrade"); + } + if(this.role=="locksmith") + { + render_interaction({auto:true,dialog:"locksmith",skin:"asoldier"}); + } + if(this.role=="compound") + { + render_compound_shrine(1); + } + if(this.role=="transport") + { + render_transports_npc(); + if(0) show_transports(); + } + if(this.role=="lottery") + { + render_interaction("lottery"); + } + if(this.role=="jailer") + { + render_interaction("jailer"); + } + if(this.role=="guard") + { + render_interaction("guard"); + } + if(this.quest=="seashell") + { + render_interaction("seashells"); + } + if(this.quest=="mistletoe") + { + render_interaction("mistletoe"); + } + if(this.quest=="ornament") + { + render_interaction("ornaments"); + } + if(this.quest=="leather") + { + render_interaction("leathers"); + } + if(this.quest=="lostearring") + { + render_interaction("lostearring"); + } + if(this.role=="santa") + { + render_interaction("santa"); + } + if(this.role=="tavern") + { + render_interaction("tavern"); + } + if(this.quest=="gemfragment") + { + render_interaction("gemfragments"); + } + if(this.role=="standmerchant") + { + render_interaction("standmerchant"); + } + if(this.role=="craftsman") + { + render_interaction("crafting"); + } + if(this.role=="thesearch" && gameplay=="hardcore") + { + render_interaction("hardcoretp"); + } + if(this.role=="shells") + { + render_interaction("buyshells"); + } + if(this.role=="newyear_tree") + { + socket.emit("interaction",{type:"newyear_tree"}); + } + if(this.role=="pvptokens") + { + render_token_exchange("pvptoken"); + } + if(this.role=="friendtokens") + { + render_token_exchange("friendtoken"); + } + if(this.role=="funtokens") + { + render_token_exchange("funtoken"); + } + if(this.role=="cx") + { + render_exchange_shrine("cx"); + } + if(this.role=="petkeeper") + { + render_pet_shrine(); + } + if(this.role=="monstertokens") + { + render_token_exchange("monstertoken"); + if(!character.s.monsterhunt) + $("#merchant-item").html(render_interaction({auto:true,skin:"daisy",message:"Would you like to go on a hunt? However, I have to warn you. It's not for the faint-hearted!"+(gameplay=="hardcore"&&" [100 TOKENS!]"||""),button:"I CAN HANDLE IT!",onclick:function(){socket.emit('monsterhunt'); push_deferred("monsterhunt")}},"return_html")); + else if(character.s.monsterhunt.c) + $("#merchant-item").html(render_interaction({auto:true,skin:"daisy",message:"Go now, go! Come back after you completed your hunt ..."},"return_html")); + else + { + socket.emit('monsterhunt'); + push_deferred("monsterhunt") + $("#merchant-item").html(render_interaction({auto:true,skin:"daisy",message:"Well done, well done! A token for your service!"},"return_html")); + } + } + if(this.role=="announcer") + { + render_interaction({auto:true,skin:"lionsuit",message:"Daily Events? Yes. Soon. Hopefully ... Definitely one day."}); + } + if(npc.interaction) + { + var message=npc.interaction; + if(is_array(message)) message=message[seed0()%message.length]; + if(message=="rbin") message=random_binaries(); + render_interaction({auto:true,skin:this.skin,message:message}); + } + if(this.stype=="full") + { + direction_logic(this,character,"npc"); + this.last_mdirection=new Date(); + setTimeout(function(e){ + return function(){ + if(mssince(e.last_mdirection)>220 && e.moving) + { + calculate_vxy(e); + set_direction(e); + } + } + }(this),240); + } + try{if(event) event.stopPropagation();}catch(e){}; +} + +function player_click(event) +{ + if(is_npc(this) && this.role=="daily_events") render_interaction("subscribe",this.party); + if(is_npc(this) && this.npc=="pvp") player_right_click.apply(this,event); + else if(this.npc_onclick) npc_right_click.apply(this,event); + else + { + if(topleft_npc && inventory) render_inventory(); + topleft_npc=false; + xtarget=this; + } + // socket.emit('click',{'type':'player','id':this.id,'button':'left'}); + event.stopPropagation(); +} + +function player_attack(event,code) +{ + ctarget=this; if(!code) xtarget=null; + direction_logic(character,ctarget); + if(event) event.stopPropagation(); + if(distance(this,character)>character.range+5) + { + draw_trigger(function(){ d_text("TOO FAR",ctarget||character); }); + return rejecting_promise({reason:"too_far",distance:distance(this,character)}); + } + if(0 && !options.friendly_fire && (!character.team || character.team==ctarget.team) && (character.party && ctarget.party==character.party || character.guild && ctarget.guild==character.guild)) + { + // let server decide [05/06/19] + d_text("FRIENDLY",character); + return rejecting_promise({reason:"friendly"}); + } + socket.emit('attack',{id:ctarget.id}); + return push_deferred("attack"); +} + +function player_heal(event,code) +{ + if(this!=character) + { + ctarget=this; if(!code) xtarget=null; + } + if(this!=character) direction_logic(character,ctarget); + if(event) event.stopPropagation(); + if(distance(this,character)>character.range) + { + if(this!=character) draw_trigger(function(){ d_text("TOO FAR",ctarget||character); }); + else draw_trigger(function(){ d_text("TOO FAR",character); }); + return rejecting_promise({reason:"too_far",distance:distance(this,character)}); + } + socket.emit('heal',{id:this.id}); + return push_deferred("heal"); +} + +function monster_attack(event,code) +{ + ctarget=this; if(!code) xtarget=null; + direction_logic(character,ctarget); + if(event) event.stopPropagation(); + if(distance(this,character)>character.range+10) + { + draw_trigger(function(){ d_text("TOO FAR",ctarget||character); }); // Added +10 - otherwise seems unfair [17/06/18] + return rejecting_promise({reason:"too_far",distance:distance(this,character)}); + } + socket.emit('attack',{id:this.id}); + return push_deferred("attack"); +} + +function player_right_click(event) // always !me + set on player_rclick_logic +{ + //alert("here"); + if(this.npc && this.npc=="pvp") + { + if(this.allow) + { + var message="Be careful in there!"; + add_chat("Ace",message); + d_text(message,this,{size:SZ.chat}); + } + else + { + var message="I will guard this entrance until there are 6 adventurers around."; + add_chat("Ace",message); + d_text(message,this,{size:SZ.chat}); + } + } + else if(this.npc); + else if(character.slots.mainhand && character.slots.mainhand.name=="cupid") // just attack now + { + player_attack.call(this); + } + else if(character.ctype=="priest") + { + if(!pvp || character.party && this.party==character.party) player_heal.call(this); + else if(pvp) player_attack.call(this); + else return; + } + else + { + if(!pvp || character.party && this.party==character.party) return; + else if(pvp) player_attack.call(this); + else return; // these are important, as event.stopPropagation() shouldn't be called + } + if(event) event.stopPropagation(); +} + +function monster_click(event) +{ + if(ctarget==this) map_click(event); + ctarget=this; xtarget=null; + // socket.emit('click',{'type':'monster','id':this.id,'button':'left',"x":this.x,"y":this.y}); + last_monster_click=new Date(); + if(event) event.stopPropagation(); +} + +function mouseover(event) +{ + mtarget=this; +} + +function mouseout(event) +{ + mtarget=null; +} + +function map_click(event) +{ + if(!socket || !character) return; + var dx=0,dy=0; + if(event && event.data && event.data.global) + { + var x=event.data.global.x,y=event.data.global.y; + dx=x-width/2; dy=y-height/2; + if(manual_centering && character) dx=x-character.x,dy=y-character.y; + dx/=scale; dy/=scale; + // if(log_flags.xy) console.log("dx,dy: "+round(dx)+","+round(dy)); + if(call_code_function("on_map_click",character.real_x+dx,character.real_y+dy)) return; + if((blink_pressed || mssince(last_blink_pressed)<360) && character.ctype=="mage") + { + push_deferred("blink"); + socket.emit("skill",{name:"blink",x:character.real_x+dx,y:character.real_y+dy,direction:character.moving&&character.direction}); + return; + } + } + else if(event.x) // Not used any more + { + dx=event.x-character.real_x; + dy=event.y-character.real_y; + } + if(character && can_walk(character)) + { + var move=calculate_move(character,character.real_x+dx,character.real_y+dy); + character.from_x=character.real_x; + character.from_y=character.real_y; + character.going_x=move.x; + character.going_y=move.y; + character.moving=true; + calculate_vxy(character); + // if(log_flags.xy) add_log("going to x: "+map.going_x+" y: "+map.going_y+" speed vx: "+character.vx+" speed vy: "+character.vy); + var data={x:character.real_x,y:character.real_y,going_x:character.going_x,going_y:character.going_y,m:character.m}; + if(next_minteraction) data.key=next_minteraction,next_minteraction=null; + socket.emit("move",data); + } + if(!(topleft_npc=="dice" && current_map=="tavern")) + { + if(topleft_npc && inventory) render_inventory(); + topleft_npc=false; + } +} + +function ui_move(x,y) +{ + character.from_x=character.real_x; + character.from_y=character.real_y; + character.going_x=x; + character.going_y=y; + character.moving=true; + calculate_vxy(character); +} + +function old_move(x,y) +{ + map_click({x:x,y:y}); +} + +function map_click_release(){} + +function update_sprite(sprite) +{ + if(!sprite || !sprite.stype) return; + for(name in (sprite.animations||{})) update_sprite(sprite.animations[name]); + for(name in (sprite.emblems||{})) update_sprite(sprite.emblems[name]); + if(sprite.stype=="static") return; + + if(sprite.type=="monster" && sprite.charge_skin) + { + if(sprite.target && sprite.skin!=sprite.charge_skin) sprite.skin=sprite.charge_skin; + if(!sprite.target && sprite.skin!=sprite.normal_skin) sprite.skin=sprite.normal_skin; + } + + if(sprite.type=="character" || sprite.type=="monster" || sprite.type=="npc") + { + hp_bar_logic(sprite); + if(border_mode) border_logic(sprite); + } + if(sprite.type=="character" || sprite.type=="npc") + { + name_logic(sprite); + } + if(sprite.type=="character") + { + player_rclick_logic(sprite); + player_effects_logic(sprite); + } + if(sprite.type=="character" || sprite.type=="monster") effects_logic(sprite); + + if(is_demo) demo_entity_logic(sprite); + + if(sprite.stype=="full") // walk + { + + var aa=false,i=1,j=0; var original=sprite.i; + if(sprite.type=="monster" && G.monsters[sprite.mtype].aa) aa=true; + + if(sprite.npc && !sprite.moving && sprite.allow===true) sprite.direction=1; + if(sprite.npc && !sprite.moving && sprite.allow===false) sprite.direction=0; + if(sprite.orientation && !sprite.moving && !sprite.target) sprite.direction=sprite.orientation; + + if((sprite.moving || aa || sprite.fx && sprite.fx.aaa) && sprite.walking===null) + { + if(sprite.last_stop && msince(sprite.last_stop)<320) sprite.walking=sprite.last_walking; + else reset_ms_check(sprite,"walk",350),sprite.walking=1; + } + else if(!(sprite.moving || aa || sprite.fx && sprite.fx.aaa) && sprite.walking) + { + sprite.last_stop=new Date(); + sprite.last_walking=sprite.walking||sprite.last_walking||1; + sprite.walking=null; + } + + var sequence=[0,1,2,1],base_ms=350; + if(sprite.mtype=="wabbit") sequence=[0,1,2],base_ms=220; + + if(sprite.walking && ms_check(sprite,"walk",base_ms-((sprite.speed+(sprite.fx&&sprite.fx.aaa&&500||0))/2||0))) sprite.walking++; //sprite.updates%20==1 + // originally just 325, and [0,1,2] animation [13/03/17] + + // if(sprite.moving) set_direction(sprite); should be before stop_logic, for short moves - moved [17/11/16] + + if(sprite.direction!==undefined) j=sprite.direction; + + if(!aa && sprite.s && sprite.s.stunned) i=1; + else if(sprite.walking) i=sequence[sprite.walking%sequence.length]; + else if(sprite.last_stop && mssince(sprite.last_stop)<(sprite.s&&sprite.s.dash&&5||180)) i=sequence[sprite.last_walking%sequence.length]; + + if((sprite.type=="character" || sprite.humanoid) && (i===0 || i===2) && original!=i) sfx("walk",sprite.real_x,sprite.real_y); + + if(sprite.lock_i!==undefined) i=sprite.lock_i; + + if(sprite.stand && !sprite.standed) + { + var stand=new PIXI.Sprite(textures[sprite.stand+"_texture"]); + stand.y=3; // also a manual "disp" at monster_layer + stand.anchor.set(0.5,1); + stand.zy=100; + sprite.addChild(stand); + sprite.standed=stand; + sprite.speed=10; + } + else if(sprite.standed && !sprite.stand) + { + destroy_sprite(sprite.standed); + delete sprite.standed; + } + + if(sprite.rip && !sprite.rtexture) + { + sprite.cskin=null; + sprite.rtexture=true; + var gravestone="gravestone"; + if(sprite.rip!==true) gravestone=sprite.rip; + if(!textures[gravestone]) generate_textures(gravestone,"gravestone"); + sprite.texture=textures[gravestone]; + restore_dimensions(sprite); + } + else if(!sprite.rip && sprite.rtexture) + { + delete sprite.rtexture; + set_texture(sprite,i,j); + restore_dimensions(sprite); + } + + if(!sprite.rip) + { + //if(sprite.standed) i=1,j=0; + set_texture(sprite,i,j); + } + + if(sprite.s && (sprite.s.charging || sprite.s.dash) && ms_check(sprite,"clone",sprite.s.charging&&80||30)) + { + if(sprite.s.dash) rshake_i_major(sprite); + disappearing_clone(sprite); //!(sprite.updates%5) + } + + } + + if((sprite.stype=="animation" || sprite.stype=="item") && sprite.atype=="map") + { + var target_x=get_x(sprite.target),target_y=get_y(sprite.target)-get_height(sprite.target)/2; + if(sprite.m!=sprite.target.m) target_x=sprite.going_x,target_y=sprite.going_y; + var ms=mssince(sprite.last_update); + sprite.crotation=Math.atan2(target_y-sprite.y,target_x-sprite.x)+Math.PI/2; + if(sprite.first_rotation===undefined) + { + sprite.first_rotation=sprite.crotation; + if(sprite.directional) sprite.rotation=sprite.crotation; + } + if(sprite.directional && point_distance(target_x,target_y,sprite.x,sprite.y)>50) + { + sprite.rotation=sprite.crotation; + } + sprite.from_x=sprite.x; sprite.from_y=sprite.y; + sprite.going_x=target_x; sprite.going_y=target_y; + calculate_vxy(sprite); + sprite.x=sprite.x+sprite.vx*ms/1000.0; + sprite.y=sprite.y+sprite.vy*ms/1000.0; + if(mssince(sprite.last_frame)>=sprite.framefps) sprite.frame+=1,sprite.last_frame=new Date(); + if(sprite.to_fade) sprite.alpha-=((sprite.to_fade!==true&&sprite.to_fade)||0.025)*ms/16.6; + if(sprite.frame>=sprite.frames) sprite.frame=0; + set_texture(sprite,sprite.frame); + sprite.crotation=Math.atan2(target_y-sprite.y,target_x-sprite.x)+Math.PI/2; + if(sprite.to_delete || point_distance(target_x,target_y,sprite.x,sprite.y)<(sprite.limit||16) || abs(sprite.first_rotation-sprite.crotation)>Math.PI/2) + { + destroy_sprite(sprite,"children"); + delete map_animations[sprite.id]; + return; + } + sprite.last_update=new Date(); + } + else if(sprite.stype=="animation" && sprite.atype=="cmap") + { + var ms=mssince(sprite.last_update); + sprite.ax=get_x(sprite.origin); + sprite.ay=get_y(sprite.origin)-get_height(sprite.origin)/2; + sprite.bx=get_x(sprite.target); + sprite.by=get_y(sprite.target)-get_height(sprite.target)/2; + sprite.x=sprite.ax/2+sprite.bx/2; + sprite.y=sprite.ay/2+sprite.by/2; + sprite.alpha-=0.025*ms/16.6; + sprite.height=point_distance(sprite.ax,sprite.ay,sprite.bx,sprite.by); + sprite.rotation=Math.atan2(sprite.by-sprite.ay,sprite.bx-sprite.ax)+Math.PI/2; + if(sprite.alpha<=0) + { + destroy_sprite(sprite,"children"); + delete map_animations[sprite.id]; + return; + } + sprite.last_update=new Date(); + } + else if(sprite.stype=="animation" && sprite.atype=="wmap") // map weather animation + { + var ms=mssince(sprite.last_update); + sprite.y+=1; + sprite.x+=0.1; + if(ms>=sprite.interval) + { + sprite.texture=textures[sprite.skin][(++sprite.last)%textures[sprite.skin].length]; + sprite.last_update=new Date(); + } + if(sprite.last>=textures[sprite.skin].length) + { + destroy_sprite(sprite,"children"); + delete map_animations[sprite.id]; + return; + } + } + else if(sprite.stype=="animation" && sprite.atype=="xmap") // map high frame animation + { + var ms=mssince(sprite.last_update); + if(ms>=sprite.interval) + { + sprite.texture=sprite.textures[(++sprite.last)%sprite.textures.length]; + sprite.last_update=new Date(); + } + } + else if(sprite.stype=="light" && sprite.atype=="xmap") // map high frame animation + { + var ms=mssince(sprite.last_update); + if(ms>=sprite.interval) + { + sprite.texture=sprite.textures[(++sprite.last)%sprite.textures.length]; + sprite.last_update=new Date(); + } + } + else if(sprite.stype=="animation") + { + var steps=sprite.aspeed; // not used [15/08/16] + if(sprite.speeding) sprite.aspeed-=0.003; + if(ms_check(sprite,"anim"+sprite.skin,steps*16.5)) sprite.frame+=1; //sprite.updates%steps==1 + if(sprite.frame>=sprite.frames && sprite.continuous) sprite.frame=0 + else if(sprite.frame>=sprite.frames) + { + var parent=sprite.parent; + if(parent) + { + // parent.removeChild(sprite); -- second major memory leak [19/08/16] + destroy_sprite(sprite,"children"); + delete parent.animations[sprite.skin]; + } + return; + } + set_texture(sprite,sprite.frame); + } + + if(sprite.stype=="emblem") + { + if(!sprite.frames) + { + var parent=sprite.parent; + if(parent) + { + destroy_sprite(sprite,"children"); + delete parent.emblems[sprite.skin]; + } + return; + } + if(ms_check(sprite,"emblem"+sprite.skin,60)) sprite.frames-=1; + sprite.alpha=sprite.frame_list[sprite.frames%sprite.frame_list.length]; + } + + if(sprite.stype=="emote") + { + var steps=(sprite.aspeed=="slow"&&17)||(sprite.aspeed=="slower"&&40)||10; // not used [15/08/16] + if(sprite.atype=="flow") + { + if(ms_check(sprite,"anim",steps*16.5)) sprite.frame+=1; + set_texture(sprite,[0,1,2,1][sprite.frame%4]); + } + else + { + if(ms_check(sprite,"anim",steps*16.5) && sprite.atype!="once") sprite.frame=(sprite.frame+1)%3; //sprite.updates%steps==1 + set_texture(sprite,sprite.frame); + } + } + + if(sprite.mtype && !(no_graphics || paused)) + { + if(sprite.mtype=="dice") + { + if(sprite.shuffling) + { + var shake=false; + if(!sprite.locked) + { + if(sprite.line) remove_sprite(sprite.line),delete sprite.line; + sprite.line=draw_line(0,0,34,0,1,0x80E278); + sprite.line.x=-17; + sprite.line.y=-35.5; + sprite.addChild(sprite.line); + } + for(var j=sprite.locked;j<4;j++) + { + if((sprite.updates%(j+1))) continue; + i=3-j; + var num=parseInt(Math.random()*10); + if(sprite.lock_start && j==sprite.locked && mssince(sprite.lock_start)>(sprite.locked+1)*300) + { + if(i==0) num=sprite.num[0]; + else if(i==1) num=sprite.num[1]; + else if(i==2) num=sprite.num[3]; + else if(i==3) num=sprite.num[4]; + sprite.locked++; + shake=true; + sprite.cskin="2"; + sprite.texture=textures["dice"][sprite.cskin]; + if(sprite.line) remove_sprite(sprite.line),delete sprite.line; + sprite.seconds=(4-sprite.locked)*7; + sprite.line=draw_line(0,0,min(34,sprite.seconds*1.12),0,1,0x80E278); + sprite.line.x=-17; + sprite.line.y=-35.5; + sprite.addChild(sprite.line); + if(!sprite.seconds) + { + sprite.count_start=future_s(8); + sprite.snum=sprite.num; + sprite.shuffling=false; + } + sprite.cskin="5"; + sprite.texture=textures["dice"][sprite.cskin]; + } + sprite.digits[i].texture=textures["dicesub"][num]; + } + if(shake) v_shake_i_minor(sprite); // can't be used for entities + if(!sprite.locked && sprite.shuffling && !(sprite.updates%40) || sprite.cskin!="0" && sprite.cskin!="1") + { + sprite.cskin=""+(parseInt(sprite.cskin)+1)%2; + sprite.texture=textures["dice"][sprite.cskin]; + } + } + else if(sprite.num!=sprite.snum) + { + sprite.snum=sprite.num; + for(var i=0;i<4;i++) + { + var num=0; + if(i==0) num=sprite.num[0]; + else if(i==1) num=sprite.num[1]; + else if(i==2) num=sprite.num[3]; + else if(i==3) num=sprite.num[4]; + sprite.digits[i].texture=textures["dicesub"][parseInt(num)]; + } + } + else + { + sprite.seconds=min(30,max(0,mssince(sprite.count_start))/1000.0); + if(sprite.line) remove_sprite(sprite.line),delete sprite.line; + sprite.line=draw_line(0,0,sprite.seconds*1.14,0,1,0x80E278); + sprite.line.x=-17; + sprite.line.y=-35.5; // -10.5 + sprite.addChild(sprite.line); + if(sprite.cskin!="5") + { + sprite.cskin="5"; + sprite.texture=textures["dice"][sprite.cskin]; + } + if(0 && !(sprite.updates%20)) + { + if(sprite.cskin=="3") sprite.cskin="4"; + else if(sprite.cskin=="4") sprite.cskin="5"; + else sprite.cskin="3"; + sprite.texture=textures["dice"][sprite.cskin]; + } + } + } + + if(sprite.mtype=="slots" || sprite.mtype=="wheel") + { + if(sprite.spinning) + { + if(!(sprite.updates%2)) + { + sprite.cskin=""+(parseInt(sprite.cskin)+1)%3; + sprite.texture=textures[sprite.mtype][sprite.cskin]; + } + if(sprite.spinning30 && sprite.frame!=3) + { + sprite.openning=new Date(); + set_texture(sprite,++sprite.frame); + if(sprite.to_delete) sprite.alpha-=0.1; + } + else if(mssince(sprite.openning)>30 && sprite.to_delete && sprite.alpha>=0.5) + { + sprite.alpha-=0.1; + } + else if(sprite.alpha<0.5) + { + destroy_sprite(chests[sprite.id]); + delete chests[sprite.id]; + } + } + + if(sprite.type=="character" || sprite.slots || sprite.cx) + { + if(!sprite.cx) sprite.cx={}; + if(sprite.stype=="full") cosmetics_logic(sprite); + } + + if(sprite.last_ms && sprite.s) + { + var ms=mssince(sprite.last_ms); + ["s","c","q"].forEach(function(stub){ + if(!sprite[stub]) return; + for(var name in sprite[stub]) + { + if(sprite[stub][name].ms) + { + sprite[stub][name].ms-=ms; + if(sprite[stub][name].ms<=0) + { + delete sprite[stub][name]; + // if(stub=="q") reopen(); + } + } + } + }); + sprite.last_ms=new Date(); + } + + if(sprite.real_alpha!==undefined) alpha_logic(sprite); + + update_filters(sprite); + if(sprite.texts) step_d_texts(sprite); + + sprite.updates+=1; //round(frame_ms/15); +} + +function add_monster(data) +{ + // console.log("add_monster "+data.type); + var def=G.monsters[data.type],sprite=new_sprite(data.skin||def.skin||data.type,"full"); + sprite.type="monster"; + sprite.mtype=data.type; + + adopt_soft_properties(sprite,data); + + sprite.parentGroup=sprite.displayGroup=monster_layer; + + sprite.walking=null; + sprite.animations={}; sprite.fx={}; + sprite.emblems={}; + sprite.move_num=data.move_num; + sprite.c={}; // [09/03/17] + sprite.real_alpha=1; + sprite.x=sprite.real_x=round(data.x); + sprite.y=sprite.real_y=round(data.y); + sprite.vx=data.vx || 0; + sprite.vy=data.vy || 0; + if(def.slots) sprite.slots=def.slots; + sprite.level=1; + if(sprite.s.young) sprite.real_alpha=0.4; + if(def.charge_skin) + { + sprite.normal_skin=sprite.skin; + sprite.charge_skin=def.charge_skin; + if(!textures[sprite.charge_skin]) generate_textures(sprite.charge_skin,"full"); + } + sprite.last_ms=new Date(); + sprite.anchor.set(0.5,1); + // sprite.speed=data.speed; [16/04/18] + if(def.hit) sprite.hit=def.hit; + if(def.size) sprite.height*=def.size,sprite.width*=def.size,sprite.mscale=def.size,sprite.hpbar_wdisp=-5; + if(def.orientation) sprite.orientation=def.orientation; + sprite.interactive=true; + sprite.buttonMode=true; + set_base(sprite); + sprite.on('mousedown',monster_click).on('touchstart',monster_click).on('rightdown',monster_attack); + sprite.on('mouseover',mouseover); + sprite.on('mouseout',mouseout); + if(0 && G.dimensions[data.type]) + { + var actual=G.dimensions[data.type],anchor=sprite.anchor; + sprite.hitArea=new PIXI.Rectangle(-actual[0]*anchor.x-2,-actual[1]*anchor.y-2,actual[0]+4,actual[1]+4); + sprite.awidth=actual[0]; + sprite.aheight=actual[1]; + } + return sprite; +} + +function update_filters(sprite) +{ + if(no_graphics) return; + if(sprite.pglow) + { + if(sprite.updates%3) return; + + var steps=[0.9,1.2,1.05]; + if(sprite.pzazz>50) steps=[1.7,1.9,1.7]; + else if(sprite.pzazz>40) steps=[1.5,1.6,1.5]; + else if(sprite.pzazz>25) steps=[1.4,1.5,1.42]; + else if(sprite.pzazz>13) steps=[1.3,1.4,1.275]; + else if(sprite.pzazz>6) steps=[1.2,1.3,1.075] + + var filter=sprite.filter_pglow; + if(filter.b>steps[1]) filter.step=-abs(filter.step); + if(filter.b=1 || mssince(sprite.appearing)>900) // rogue logic + { + sprite.appearing=sprite.tp=false; + sprite.real_alpha=1; + if(sprite.s && sprite.s.invis) sprite.real_alpha=0.5; + stop_animation(sprite,"transport"); + } + } + if(sprite.disappearing) + { + if(sprite.real_alpha>0.5) sprite.real_alpha-=0.0025; + } +} + +function start_filter(sprite,ftype,args) +{ + if(no_graphics) return; + var filter=null; + if(ftype=="darkgray") + { + filter=new PIXI.filters.OutlineFilter(3,0x5E615E); + } + else if(ftype=="fingered") + { + filter=new PIXI.filters.OutlineFilter(3,0x934FB2); + } + else if(ftype=="stoned") + { + filter=new PIXI.filters.ColorMatrixFilter(); + filter.greyscale(0.2); + } + else if(ftype=="orange") + { + filter=new PIXI.filters.AdjustmentFilter({red:1.5,blue:0,green:0.2,brightness:4}); + } + else if(ftype=="blue") + { + filter=new PIXI.filters.AdjustmentFilter({red:0,blue:2,green:0.1,brightness:3,gamma:2}); + } + else if(ftype=="green") + { + filter=new PIXI.filters.AdjustmentFilter({red:0.2,blue:0.2,green:1.5,brightness:2}); + } + else if(ftype=="red") + { + filter=new PIXI.filters.AdjustmentFilter({red:2,blue:0,green:0,brightness:2}); + } + else if(ftype=="yellow") + { + filter=new PIXI.filters.AdjustmentFilter({red:2,blue:0,green:0.5,brightness:2,gamma:2}); + } + else if(ftype=="bloom") + { + filter=new PIXI.filters.BloomFilter(1,1,1); + } + else if(ftype=="cv") + { + filter=new PIXI.filters.ConvolutionFilter([0.3,0.02,0.1,0.1,0.1,0.02,0.02,0.2,0.02],30,40); + } + else if(ftype=="cv2") + { + // filter=new PIXI.filters.ConvolutionFilter([1,1,1,1,1,1,1,1,1],40,50); + filter=new PIXI.filters.ConvolutionFilter([0.1,0.1,0.1,0.1,0.0,0.1,0.1,0.1,0.1],30,40); + } + else if(ftype=="rblur") + { + filter=new PIXI.filters.RadialBlurFilter(random_one([-0.75,-0.5,0.5,0.75]),[5,10],11,-1); + } + else if(ftype=="glow") + { + filter=new PIXI.filters.GlowFilter(8,4,0,0x598BFF); + } + else if(ftype=="alphaf") + { + filter=new PIXI.filters.AlphaFilter(); + filter.alpha=args||1; + } + else if(ftype=="rcolor") + { + filter=new PIXI.filters.ColorMatrixFilter(); + + //filter.matrix=[Math.random(),Math.random(),Math.random(),Math.random(),Math.random(),Math.random(),Math.random(),Math.random(),Math.random()]; + // filter.colorTone(5,5,"#7B1297","#D7BA36"); + + // if(Math.random()<0.5) filter.brightness(Math.random(),true); + // if(Math.random()<0.5) filter.saturate(Math.random(),true); + // if(Math.random()<0.2) filter.desaturate(); + + //if(Math.random()<0.5) filter.hue(parseInt(Math.random()*180),true); + //else filter.hue(-parseInt(Math.random()*180),true); + + filter.desaturate(); + } + else + { + filter=new PIXI.filters.ColorMatrixFilter(); + filter.step=0.01; + filter.b=1; + } + + if(ftype=="curse") + { + if(sprite.s && sprite.s.deepfreezed) filter.hue(36); + else if(sprite.s && sprite.s.frozen) filter.hue(24); + else if(sprite.s && sprite.s.poisoned) filter.hue(-24); + else filter.hue(20); + } + else if(ftype=="xcolor") + { + filter.desaturate(2); + filter.sepia(0.01); + } + else if(ftype=="darken") + { + filter.night(); + } + else if(ftype=="bw") + { + filter.desaturate(); + } + + + if(!sprite.filter_list) sprite.filter_list=[filter]; + else sprite.filter_list.push(filter); + sprite.filters=sprite.filter_list; + //filter.desaturate(2); filter.sepia(0.01); filter.brightness(b); + sprite["filter_"+ftype]=filter; +} + +function stop_filter(sprite,ftype) +{ + if(no_graphics) return; + if(!sprite["filter_"+ftype]) return; + sprite.filter_list.splice(sprite.filter_list.indexOf(sprite["filter_"+ftype]),1); + // console.log(JSON.stringify(sprite.filter_list)); + if(!sprite.filter_list.length) sprite.filters=null; + else sprite.filters=sprite.filter_list; + // sprite["filter_"+ftype].destroy(); - no such method [30/03/18] + delete sprite["filter_"+ftype]; + delete sprite[ftype]; +} + +function alpha_logic(sprite) +{ + if((!sprite.cx || !sprite.cx.length) && (!sprite.cxc || !Object.keys(sprite.cxc).length)) + { + if(sprite.alpha!=sprite.real_alpha) sprite.alpha=sprite.real_alpha; + } + else + { + if(sprite.alpha!=1) sprite.alpha=1; // sometimes cosmetics logic doesn't execute beforehand, alpha gets set, then gets stuck at 0.5 - this fixes it [28/01/20] + if(sprite.filter_alphaf) + { + if(sprite.real_alpha==1) stop_filter(sprite,"alphaf"); + else if(sprite.filter_alphaf.alpha!=sprite.real_alpha) sprite.filter_alphaf.alpha=sprite.real_alpha; + } + else if(sprite.real_alpha!=1) + { + start_filter(sprite,"alphaf",sprite.real_alpha); + } + } +} + +function player_effects_logic(sprite) +{ + if(no_graphics || !sprite.s) return; + if(sprite.pzazz>=4 && !sprite.filter_pglow) start_filter(sprite,"pglow"); + else if(sprite.pzazz<4 && sprite.filter_pglow) stop_filter(sprite,"pglow"); + + if(sprite.s.invis && (!sprite.fx.invis || sprite.real_alpha!=0.5)) + { + sprite.fx.invis=true; + sprite.real_alpha=0.5; + } + else if(!sprite.s.invis && sprite.fx.invis) + { + delete sprite.fx.invis; + sprite.real_alpha=1; + } + + if(sprite.s.phasedout && !sprite.fx.phs) + { + sprite.fx.phs=true; + sprite.real_alpha=0.8; + start_filter(sprite,"xcolor"); + //start_emblem(sprite,"c1",{frames:1200,no_dip:true}); + //start_filter(sprite.emblems.c1,"darken"); + if(sprite.me && 0) + { + stage.cfilter_rblur=new PIXI.filters.RadialBlurFilter(random_one([-0.5,-0.25,0.25,0.5]),[width/2,height/2],3,-1); + regather_filters(stage); + } + } + else if(!sprite.s.phasedout && sprite.fx.phs) + { + sprite.real_alpha+=0.02; + if(sprite.real_alpha>=1) + { + delete sprite.fx.phs; + stop_filter(sprite,"xcolor"); + } + //stop_emblem(sprite,"c1"); + if(sprite.me && 0) + { + delete stage.cfilter_rblur; + regather_filters(stage); + } + } + + if(sprite.s.darkblessing && !sprite.fx.db) + { + sprite.fx.db=true; + start_emblem(sprite,"dp1",{frames:1200,no_dip:false}); + } + else if(!sprite.s.darkblessing && sprite.fx.db) + { + delete sprite.fx.db; + stop_emblem(sprite,"dp1"); + } + + if(sprite.s.warcry && !sprite.fx.wcry) + { + sprite.fx.wcry=true; + start_emblem(sprite,"r1",{frames:1200,no_dip:false}); + } + else if(!sprite.s.warcry && sprite.fx.wcry) + { + delete sprite.fx.wcry; + stop_emblem(sprite,"r1"); + } + + if(sprite.s.blink && !sprite.fading_out) + { + sprite.fading_out=new Date(); + sprite.real_alpha=1; + draw_timeout(fade_out_blink(0,sprite),0); + } + + if(sprite.c.revival && !sprite.fx.revival) + { + sprite.fx.revival=true; + start_animation(sprite,"revival"); + } + else if(!sprite.c.revival && sprite.fx.revival) + { + delete sprite.fx.revival; + stop_animation(sprite,"revival"); + start_animation(sprite,"heal"); + } + + if(sprite.s.typing && !sprite.fx.typing) + { + sprite.fx.typing=true; + start_animation(sprite,"typing"); + } + else if(!sprite.s.typing && sprite.fx.typing) + { + delete sprite.fx.typing; + stop_animation(sprite,"typing"); + } + + if(sprite.c.town && !sprite.disappearing) + { + sprite.disappearing=new Date(); + sprite.real_alpha=1; + start_animation(sprite,"transport"); + } + else if(!sprite.c.town && sprite.disappearing) + { + delete sprite.disappearing; + sprite.real_alpha=1; + stop_animation(sprite,"transport"); + } + + if(sprite.tp && !sprite.appearing) // sprite.tp===1 to limit to regular .tp + { + sprite.appearing=new Date(); + sprite.real_alpha=0.5; + start_animation(sprite,"transport"); + } + + if(sprite.me && sprite.fear && (!sprite.last_fear || sprite.last_fear3) add_log("You are petrified","#B03736"); + else if(character.fear>1) add_log("You are terrified","#B04157"); + else if(character.fear) add_log("You are getting scared","gray"); + } + if(sprite.me) sprite.last_fear=sprite.fear; +} + +function effects_logic(sprite) +{ + if(no_graphics || !sprite.s) return; + + if(sprite.s && sprite.s.sleeping && !sprite.shaking) + { + if(Math.random()<0.1) d_text("zZz",sprite,{color:"white"}); + v_shake_i_minorX(sprite); + } + + if((sprite.s.cursed || sprite.s.poisoned || sprite.s.frozen || sprite.s.deepfreezed) && !sprite.fx.cursed) + { + sprite.fx.cursed=true; + start_filter(sprite,"curse"); + // start_animation(sprite,"cursed") + } + else if(!(sprite.s.cursed || sprite.s.poisoned || sprite.s.frozen || sprite.s.deepfreezed) && sprite.fx.cursed) + { + delete sprite.fx.cursed; + stop_filter(sprite,"curse"); + // stop_animation(sprite,"cursed") + } + + if(sprite.s.filter && !sprite["filter_"+sprite.s.filter.name]) + { + if(sprite.s.filter.name!="scale") start_filter(sprite,sprite.s.filter.name); + if(sprite.s.filter.scale) sprite.scale=new PIXI.Point(sprite.s.filter.scale,sprite.s.filter.scale),sprite.mscale=sprite.s.filter.scale; + } + + if(sprite.s.fingered && !sprite.filter_fingered) + { + start_filter(sprite,"fingered"); + } + else if(!sprite.s.fingered && sprite.filter_fingered) + { + stop_filter(sprite,"fingered"); + } + + if(sprite.s.stoned && !sprite.filter_stoned) + { + start_filter(sprite,"stoned"); + } + else if(!sprite.s.stoned && sprite.filter_stoned) + { + stop_filter(sprite,"stoned"); + } + + if(sprite.s.stunned && !sprite.fx.stunned && !sprite.s.fingered) + { + sprite.fx.stunned=true; + start_animation(sprite,"stunned","stun") + } + else if(!sprite.s.stunned && sprite.fx.stunned && !sprite.s.fingered) + { + delete sprite.fx.stunned; + stop_animation(sprite,"stunned") + } + + if(sprite.s.tangled && !sprite.fx.tangled) + { + sprite.fx.tangled=true; + start_animation(sprite,"tangle") + } + else if(!sprite.s.tangled && sprite.fx.tangled) + { + delete sprite.fx.tangled; + stop_animation(sprite,"tangle") + } + + if(sprite.s.dampened && !sprite.fx.dampened) + { + sprite.fx.dampened=true; + start_animation(sprite,"dampened") + } + else if(!sprite.s.dampened && sprite.fx.dampened) + { + delete sprite.fx.dampened; + stop_animation(sprite,"dampened") + } + + if(sprite.s.invincible && !sprite.fx.invincible) + { + var aname=sprite.role=="gm"&&"gm"||"invincible"; + sprite.fx.invincible=true; + start_animation(sprite,aname); + sprite.real_alpha=0.9; + } + else if(!sprite.s.invincible && sprite.fx.invincible) + { + var aname=sprite.role=="gm"&&"gm"||"invincible"; + delete sprite.fx.invincible; + stop_animation(sprite,aname); + sprite.real_alpha=1; + } + + if(sprite.s.hardshell && !sprite.fx.hardshell) + { + sprite.fx.hardshell=true; + start_animation(sprite,"hardshell") + } + else if(!sprite.s.hardshell && sprite.fx.hardshell) + { + delete sprite.fx.hardshell; + stop_animation(sprite,"hardshell") + } + + if(sprite.s.reflection && !sprite.fx.reflection) + { + sprite.fx.reflection=true; + start_animation(sprite,"reflection") + } + else if(!sprite.s.reflection && sprite.fx.reflection) + { + delete sprite.fx.reflection; + stop_animation(sprite,"reflection") + } + + if(sprite.s.magiport && !sprite.fading_out) + { + sprite.fading_out=new Date(); + sprite.real_alpha=1; + draw_timeout(fade_out_magiport(0,sprite),0); + start_filter(sprite,"bloom"); + } + + if(sprite.type=="monster" && !Object.keys(sprite.fx).length && sprite.real_alpha<1 && !sprite.dead && !(sprite.appearing || sprite.disappearing || sprite.fading_out)) + { + sprite.real_alpha=min(1,sprite.real_alpha+0.05); + } + + if(sprite.c && sprite.c.pickpocket && !sprite.fx.attack) sprite.fx.attack=[new Date(),0]; + if(sprite.c && sprite.c.fishing && !sprite.fx.attack) sprite.fx.attack=[new Date(),0]; + if(sprite.c && sprite.c.mining && !sprite.fx.attack) sprite.fx.attack=[new Date(),0]; +} + +// .cx={head:"",hair:"",hat:"",body:"",face:"",upper:"", special:"",back:"",tail:"", stone:""} + +function cosmetics_logic(sprite) +{ + // head tilt 0 px on default, 2px for "wizard" + // improve "zy" logic with parent disp + if(!sprite.cxc) sprite.cxc={}; + if(no_graphics) return; + var needed=["bg"],body_type="full",cx_prop={},cxs=[sprite.skin]; + for(var n in sprite.cx) cxs.push(n); + + cxs.forEach(function(cid){ + if(G.cosmetics.prop[cid]) + G.cosmetics.prop[cid].forEach(function(p){ + cx_prop[p]=true; + }) + }); + + if(T[sprite.skin]=="armor") body_type="armor"; + else if(T[sprite.skin]=="body") body_type="body"; + else if(T[sprite.skin]=="character") body_type="character"; + + if(sprite.slots && sprite.slots.helmet && sprite.slots.helmet.name.startsWith("ghat")) + { + var found=false; + for(var slot in sprite.slots) if(sprite.slots[slot] && sprite.slots[slot].giveaway) found=true; + if(found) sprite.cx.hat=G.items[sprite.slots.helmet.name].hat; + } + + if(sprite.rip) + { + if(sprite.cx.hat) needed.push(sprite.cx.hat); + } + else + { + needed.push(sprite.skin+"copy"); + if(body_type!="full" && !sprite.cx.head) sprite.cx.head="makeup117"; + for(var place in sprite.cx) + { + var cid=sprite.cx[place]; + if(!cid || ["stone"].includes(place)) continue; + if(place=="hair" && cx_prop.no_hair) continue; + if(body_type=="full" && in_arr(place,["head","hair"])) continue; + if(body_type=="character" && in_arr(place,["head","hair"])) continue; + if(place=="upper" && (body_type=="full" || SSU[cid]!=SSU[sprite.skin])) continue; + if(body_type=="armor" && place=="head") + needed.push({ + "small":G.cosmetics.head[cid]&&G.cosmetics.head[cid][0]||"sskin1a", + "normal":G.cosmetics.head[cid]&&G.cosmetics.head[cid][1]||"mskin1a", + "tall":G.cosmetics.head[cid]&&G.cosmetics.head[cid][1]||"mskin1a", + "large":G.cosmetics.head[cid]&&G.cosmetics.head[cid][2]||"lskin1a"}[SS[sprite.skin]]); + needed.push(cid); + } + if(new_attacks && sprite.slots && sprite.slots.mainhand && G.items[sprite.slots.mainhand.name] && G.items[sprite.slots.mainhand.name].type=="weapon" && G.positions[G.items[sprite.slots.mainhand.name].skin_c||G.items[sprite.slots.mainhand.name].skin]) + { + needed.push("weapon"+sprite.slots.mainhand.name); + } + if(new_attacks && sprite.slots && sprite.slots.mainhand && G.items[sprite.slots.mainhand.name] && G.items[sprite.slots.mainhand.name].type=="tool" && G.positions[G.items[sprite.slots.mainhand.name].skin_c||G.items[sprite.slots.mainhand.name].skin]) + { + needed.push("weapon"+sprite.slots.mainhand.name); + } + if(new_attacks && sprite.slots && sprite.slots.offhand && G.items[sprite.slots.offhand.name] && (0||G.items[sprite.slots.offhand.name].type=="weapon") && G.positions[G.items[sprite.slots.offhand.name].skin_c||G.items[sprite.slots.offhand.name].skin]) + { + needed.push("weap2n"+sprite.slots.offhand.name); + } + } + + for(var cid in sprite.cxc) + if(!in_arr(cid,needed)) + { + destroy_sprite(sprite.cxc[cid]); + delete sprite.cxc[cid]; + } + + var x_disp=head_x; + var head_dy={"large":2,"tall":1,"normal":0,"small":-1,"xsmall":-3,"xxsmall":-4}[SS[sprite.skin]]; + var head_dh=G.cosmetics.head[sprite.cx.head]&&G.cosmetics.head[sprite.cx.head][3]||0; + var hair_dy=G.cosmetics.hair[sprite.cx.hair]&&G.cosmetics.hair[sprite.cx.hair][0]||0; hair_dy+=head_dh; + var hair_dh=G.cosmetics.hair[sprite.cx.hair]&&G.cosmetics.hair[sprite.cx.hair][1]||0; + var hat_dy=G.cosmetics.hat[sprite.cx.hat]||0; hat_dy+=head_dh; + if(!(sprite.texture.width%2)) // old sprites have 26px width instead of 27px, they are not centered [25/09/18] + { + if(sprite.standed) sprite.standed.x=0; + x_disp-=0.5; + } + else + { + if(sprite.standed) sprite.standed.x=0.5; + } + + if(sprite.rip) + { + var g_height=G.cosmetics.gravestone[sprite.cx.gravestone||"gravestone"]||19; + head_dy=g_height-23; + hair_dy=0; + } + + needed.forEach(function(cid){ + var c=sprite.cxc[cid]; + if(!sprite.cxc[cid]) + { + if(sprite.rip && T[cid]!="hat" && T[cid]!="a_hat") return; + if(cid==sprite.skin+"copy") + { + c=new PIXI.Sprite(sprite.texture); + c.anchor.set(0.5,1); + c.stype="copy"; + c.skin=sprite.skin; + sprite.addChild(c); + sprite.cxc[cid]=c; + //c.filters=[new PIXI.filters.ColorReplaceFilter(0xf0f5c2,0x8d8476,0.2)]; + } + else if(cid=="bg") + { + c=new PIXI.Sprite(); + c.anchor.set(0.5,1); + c.stype="bg"; + sprite.addChild(c); + sprite.cxc[cid]=c; + } + else if(["hat","hair","head","face","makeup","beard","a_makeup","a_hat"].includes(T[cid])) + { + c=new_sprite(cid,T[cid]); + c.anchor.set(0.5,1); + sprite.addChild(c); + sprite.cxc[cid]=c; + } + else if(T[cid]=="armor") // for "upper" + { + c=new_sprite(cid,"upper"); + c.anchor.set(0.5,1); + c.y=-8; // maybe 9 for "large" ones + sprite.addChild(c); + sprite.cxc[cid]=c; + } + else if(T[cid]=="skin") + { + c=new_sprite(cid,T[cid]); + c.anchor.set(0.5,1); + sprite.addChild(c); + sprite.cxc[cid]=c; + } + else if(T[cid]=="wings") + { + c=new_sprite(cid,"wings"); + c.anchor.set(0.5,1); + c.x=-5; + sprite.addChild(c); + sprite.cxc[cid]=c; + } + else if(T[cid]=="s_wings") + { + c=new_sprite(cid,"s_wings"); + c.anchor.set(0.5,1); + sprite.addChild(c); + sprite.cxc[cid]=c; + } + else if(T[cid]=="tail") + { + c=new_sprite(cid,"tail"); + c.anchor.set(0.5,1); + c.y=0; + sprite.addChild(c); + sprite.cxc[cid]=c; + } + else if(cid.startsWith("wea")) + { + var wname=cid.substr(6,99),wcx=G.items[wname].cx||{},item=sprite.slots.mainhand,main=true; + if(cid[4]=="2") item=sprite.slots.offhand,main=false; + var gr=calculate_item_grade(G.items[wname]); + c=new_sprite(wname,"item"); + c.anchor.set(0.5,1); + c.y=-4; + c.x=-5+x_disp; + if(cid[4]=="2") c.x=5+x_disp,c.scale.set(-1,1); + + var bcolor=0x444444,bsize=0; + if(wcx.lightborder) bcolor=0x666666,bsize=1; + if(wcx.border) bsize=wcx.border; + + var glow_distance=8+(min(item.level,13)+[1,1.5,2,2,2][gr]-10)*3; + var glow_strength=4+(min(item.level,13)+[1.5,1.75,2,2,2][gr]-10)*2; + + if(item.level+gr>=10) + { + var glow_filter=new PIXI.filters.GlowFilter(glow_distance,glow_strength,0,hx(wcx.accent||"#DBDBBF",0.05)) // "#DAC7CF" + c.filters=[glow_filter]; + // if(item.level+gr>=11) c.filterArea = new PIXI.Rectangle(-4000, -4000, 4000, 4000); + if(main) sprite.filter_wglow=glow_filter; + } + else if(wcx.scale==0.5) c.filters=[new PIXI.filters.OutlineFilter(bsize||2,bcolor)]; // ,new PIXI.filters.PixelateFilter(2,2) + else if(wcx.scale==0.75) c.filters=[new PIXI.filters.OutlineFilter(bsize||2,bcolor)]; + else c.filters=[new PIXI.filters.OutlineFilter(bsize||2,bcolor)]; + + // character.cxc.weaponoozingterror.filters=[new PIXI.filters.GlowFilter(10,12,0,hx("#312345",0.05))] #6A49DD #582A08 + + c.zy=100; + sprite.addChild(c); + sprite.cxc[cid]=c; + } + else if(T[cid]=="gravestone"){ + return; + } + else /*if(!T[cid])*/ + { + console.log("Invalid cosmetics: "+cid); + return; + } + } + if(c.stype=="copy") + { + //c.texture=sprite.texture; + if(sprite.j!==undefined) c.texture=textures[sprite.skin][sprite.i][sprite.j]; // for _clone + c.zy=0; + } + else if(c.stype=="bg") + { + c.zy=-100*ZEPS; + } + else if(c.stype=="head") + { + var covers=G.cosmetics.prop[sprite.skin]&&G.cosmetics.prop[sprite.skin].includes("covers"); + c.y_disp=-(G.cosmetics.default_head_place+head_dy)+head_y; + c.zy=ZEPS; + var tilt=0; + if(sprite.i==0) c.y=c.y_disp+1; + else if(sprite.i==1) c.y=c.y_disp; + else if(sprite.i==2) c.y=c.y_disp+1; + if(sprite.j==0) c.x=0+x_disp; + else if(sprite.j==1) c.x=-tilt+x_disp; //,c.zy=-2*ZEPS; // new + else if(sprite.j==2) c.x=+tilt+x_disp; //,c.zy=-2*ZEPS; // new + else if(sprite.j==3) c.x=0+x_disp,c.zy=-ZEPS; + if(sprite.j<3 && covers) c.zy=-2*ZEPS; + if(sprite.j!==undefined) set_texture(c,sprite.j); + c.moved=false; + + } + else if(c.stype=="hair") + { + c.y_disp=-(G.cosmetics.default_hair_place+head_dy+hair_dy)+head_y; + var tilt=0; + c.zy=2*ZEPS; + if(sprite.i==0) c.y=c.y_disp+1; + else if(sprite.i==1) c.y=c.y_disp; + else if(sprite.i==2) c.y=c.y_disp+1; + if(sprite.j==0) c.x=0+x_disp; + else if(sprite.j==1) c.x=-tilt+x_disp; //,c.zy=-1.95*ZEPS; + else if(sprite.j==2) c.x=+tilt+x_disp; //,c.zy=-1.95*ZEPS; + else if(sprite.j==3) c.x=0+x_disp; + if(sprite.j!==undefined) set_texture(c,sprite.j); + c.moved=false; + } + else if(c.stype=="hat" || c.stype=="a_hat") + { + c.y_disp=-(G.cosmetics.default_hat_place+head_dy+hair_dh+hat_dy)+head_y; + var tilt=0; + c.zy=3*ZEPS; + if(sprite.i==0) c.y=c.y_disp+1; + else if(sprite.i==1) c.y=c.y_disp; + else if(sprite.i==2) c.y=c.y_disp+1; + if(sprite.j==0) c.x=0+x_disp; + else if(sprite.j==1) c.x=-tilt+x_disp; + else if(sprite.j==2) c.x=+tilt+x_disp; + else if(sprite.j==3) c.x=0+x_disp; + if(sprite.j!==undefined) set_texture(c,sprite.j,sprite.i); + c.moved=false; + } + else if(c.stype=="face") + { + c.y_disp=-(G.cosmetics.default_head_place+head_dy+G.cosmetics.default_face_position)+head_y; + c.y=c.y_disp; + var tilt=0; + c.zy=2.5*ZEPS; + if(sprite.i==0) c.y=c.y_disp+1; + else if(sprite.i==1) c.y=c.y_disp; + else if(sprite.i==2) c.y=c.y_disp+1; + if(sprite.j==0) c.x=0+x_disp; + else if(sprite.j==1) c.x=-tilt+x_disp; + else if(sprite.j==2) c.x=+tilt+x_disp; + else if(sprite.j==3) c.x=0+x_disp; + if(sprite.j!==undefined) set_texture(c,sprite.j); + c.moved=false; + } + else if(c.stype=="beard" || c.stype=="makeup" || c.stype=="a_makeup") + { + c.y_disp=-(G.cosmetics.default_head_place+head_dy+G.cosmetics.default_beard_position)+head_y; + c.y=c.y_disp; + var tilt=0; + c.zy=3.5*ZEPS; + if(sprite.i==0) c.y=c.y_disp+1; + else if(sprite.i==1) c.y=c.y_disp; + else if(sprite.i==2) c.y=c.y_disp+1; + if(sprite.j==0) c.x=0+x_disp; + else if(sprite.j==1) { c.x=-tilt+x_disp; if(0 && sprite.i==2) c.zy=-1.9*ZEPS; } + else if(sprite.j==2) { c.x=+tilt+x_disp; if(0 && sprite.i==0) c.zy=-1.9*ZEPS; } + else if(sprite.j==3) c.x=0+x_disp; + // if(sprite.j==1 && sprite.i==2 || sprite.j==2 && sprite.i==0) + // { + // if(!c.texture.frame.oheight) c.texture.frame.oheight=c.texture.frame.height; + // c.texture.frame.height=c.texture.frame.oheight-6; + // c.texture._updateUvs(); + // c.y-=6; + // } + // else + // { + // if(!c.texture.frame.oheight) c.texture.frame.oheight=c.texture.frame.height; + // c.texture.frame.height=c.texture.frame.oheight; + // c.texture._updateUvs(); + // } + if(sprite.j!==undefined) set_texture(c,sprite.j,parseInt(sprite.updates/4)); + c.moved=false; + } + else if(c.stype=="skin") + { + if(sprite.j==0) c.zy=-ZEPS; + else if(sprite.j==1) c.zy=-ZEPS; + else if(sprite.j==2) c.zy=-ZEPS; + else if(sprite.j==3) c.zy=-ZEPS; + if(sprite.j!==undefined) set_texture(c,sprite.i,sprite.j); + } + else if(c.stype=="armor") // for old "upper" + { + if(!c.texture.frame.p) + { + c.texture.frame.p=true; + c.texture.frame.height-=8; + c.texture._updateUvs(); + c.y=-8; + } + if(sprite.j==0) c.zy=2*ZEPS; + else if(sprite.j==1) c.zy=2*ZEPS; + else if(sprite.j==2) c.zy=2*ZEPS; + else if(sprite.j==3) c.zy=2*ZEPS; + if(sprite.j!==undefined) set_texture(c,sprite.i,sprite.j); + } + else if(c.stype=="upper") + { + if(sprite.j==0) c.zy=2*ZEPS; + else if(sprite.j==1) c.zy=2*ZEPS; + else if(sprite.j==2) c.zy=2*ZEPS; + else if(sprite.j==3) c.zy=2*ZEPS; + if(sprite.j!==undefined) set_texture(c,sprite.i,sprite.j); + } + else if(c.stype=="wings") + { + if(sprite.j==0) c.zy=-6*ZEPS,c.x=-2.5+x_disp; + else if(sprite.j==1) c.zy=-6*ZEPS,c.x=5+x_disp; + else if(sprite.j==2) c.zy=-6*ZEPS,c.x=-9+x_disp; + else if(sprite.j==3) c.zy=6*ZEPS,c.x=-5+x_disp; + if(sprite.j!==undefined) set_texture(c,sprite.i,sprite.j); + } + else if(c.stype=="s_wings") + { + c.y_disp=0; + if(sprite.i==0) c.y=c.y_disp+1,c.x=x_disp-1; + else if(sprite.i==1) c.y=c.y_disp,c.x=x_disp; + else if(sprite.i==2) c.y=c.y_disp+1,c.x=x_disp+1; + + if(sprite.j==0) c.zy=-6*ZEPS; + else if(sprite.j==1) c.zy=-6*ZEPS,c.x+=3; + else if(sprite.j==2) c.zy=-6*ZEPS,c.x-=3; + else if(sprite.j==3) c.zy=6*ZEPS; + if(sprite.j!==undefined) set_texture(c,sprite.j); + c.moved=false; + } + else if(c.stype=="tail") + { + c.x=x_disp; c.y=0; + if(sprite.j==0) c.zy=-6*ZEPS; + else if(sprite.j==1) c.zy=-6*ZEPS; + else if(sprite.j==2) c.zy=-6*ZEPS; + else if(sprite.j==3) c.zy=6*ZEPS; + if(sprite.j!==undefined) set_texture(c,(sprite.walking||0)%4,sprite.j); + c.moved=false; + } + else if(cid.startsWith("wea")) + { + var wname=cid.substr(6,99),wcx=G.items[wname].cx||{},def=G.items[wname],scale=1,extension=false,blade=false,staff=false,rod=false,pickaxe=false,bow=false,mirror=false,rotation=0,crossbow=false; + if(in_arr(def.wtype,["wblade","staff"])) staff=true; + else if(in_arr(def.wtype,["rod"])) rod=true; + else if(in_arr(def.wtype,["pickaxe"])) pickaxe=true; + else if(in_arr(def.wtype,["bow"])) bow=true; + else if(in_arr(def.wtype,["crossbow"])) crossbow=true; + else blade=true; + if(wcx.extension) extension=true; + if(wcx.scale) scale=G.items[wname].cx.scale; + var mainh=(cid[4]=="o"&&1||-1),xx=0,yy=0; + if(sprite.i==0) xx=-0.5,yy=-0.5; + else if(sprite.i==1) xx=0,yy=0; + else if(sprite.i==2) xx=0.5,yy=0.5; + + if(sprite.j==0) + { + c.zy=-(1000+mainh)*ZEPS; + if(mainh==-1) mirror=true; + if(extension) + { + xx+=mainh*-3; + yy+=1; + rotation=mainh*0.5*Math.PI; + if(wcx.small) xx+=mainh*-5; + } + yy-=2; + if(wcx.small) yy-=5; + } + else if(sprite.j==1) + { + c.zy=-(1000+mainh)*ZEPS; + mirror=true; + xx*=1*mainh; + yy*=1*mainh; + if(extension) yy+=round(1/scale); + else yy-=2; + if(blade || crossbow) + { + if(extension) rotation=0.5*Math.PI; + else xx+=2; + } + else + { + rotation=-0.25*Math.PI; xx+=8; yy-=3; + } + if(wcx.large) xx+=2; + if(wcx.small) yy-=5; + } + else if(sprite.j==2) + { + c.zy=-(1000+mainh)*ZEPS; + mirror=false; + xx*=-1*mainh; + yy*=-1*mainh; // reverse the move + if(extension) yy+=round(1/scale); + else yy-=2; + if(blade || crossbow) + { + if(extension) rotation=-0.5*Math.PI; + else xx+=-2; + } + else + { + rotation=0.25*Math.PI; xx+=-8; yy-=3; + } + if(wcx.large) xx-=2; + if(wcx.small) yy-=5; + } + else if(sprite.j==3) + { + c.zy=(1000+mainh)*ZEPS; + if(mainh==1) mirror=true; + yy=0; + if(extension) + { + xx+=mainh*-3; + yy+=1; + rotation=mainh*0.5*Math.PI; + if(wcx.small) xx+=mainh*-5; + } + if(wcx.small) yy-=5; + } + if(sprite.fx && sprite.fx.attack) + { + var edge=15,divider=40.0; + c.zy*=-1; + if(blade) edge=10,divider=20.0; + else + { + var distx=8; + if(staff) distx=16,yy+=3; + if(rod || pickaxe || crossbow) + { + if(sprite.j==1 || sprite.j==2); + else yy+=-8,mirror=true; + } + yy+=5; + if([1,2].includes(sprite.j)) xx+=((xx>0)?-1:1)*distx; + if(sprite.j==1) rotation=0,mirror=false; + if(sprite.j==2) rotation=0,mirror=true; + } + if(mssince(sprite.fx.attack[0])>edge) + { + sprite.fx.attack[0]=new Date(),sprite.fx.attack[1]++; + } + if(rotation>0 || sprite.j==2) rotation+=sprite.fx.attack[1]*Math.PI/divider; + else rotation-=sprite.fx.attack[1]*Math.PI/divider; + // console.log(c.skin+sprite.fx.attack[1]); + if(textures["item"+c.skin][0]!=textures["item"+c.skin][1]) + { + if(sprite.fx.attack[1]>2 && sprite.fx.attack[1]<=8) c.texture=textures["item"+c.skin][1]; + else c.texture=textures["item"+c.skin][0]; + } + if(sprite.fx.attack[1]<5) + { + xx+=((xx>0)?-1:1)*[1,2,3,4,6][sprite.fx.attack[1]]; + yy-=[0.5,1,1.25,1.5,2][sprite.fx.attack[1]]; + } + else if(sprite.fx.attack[1]<10) + { + xx+=((xx>0)?-1:1)*[5,4,3,2,1][sprite.fx.attack[1]-5]; + yy-=[2,1.5,1.25,1,0.5][sprite.fx.attack[1]-5]; + } + else + sprite.fx.attack=null; + } + if(scale<=0.5) yy-=6; + else if(scale<=0.75) yy-=3; + c.rotation=rotation; + c.scale.set((mirror&&-1||1)*scale,scale); + c.x=xx+x_disp; + c.y=-4+yy; + if(pickaxe && sprite.fx && sprite.fx.attack && sprite.fx.attack[1]==8) assassin_smoke(get_x(sprite)+((sprite.j==1)&&-10||(sprite.j==2)&&10||0),get_y(sprite)-8); + } + if((last_cx_d[0]||last_cx_d[1]) && !c.moved && c.skin==last_cx_name) c.moved=true,c.x+=last_cx_d[0],c.y+=last_cx_d[1]; + }); + sprite.children.sort(function(a,b){ + if(a.zy===undefined) a.zy=-CINF; // undefined's break the sort order [27/09/18] + if(b.zy===undefined) b.zy=-CINF; + return a.zy-b.zy; + }); +} + +function add_npc(npc,position,npc_id) // not used anymore [07/09/22] +{ + var sprite; + if(npc.type=="static") sprite=new_sprite(npc.skin,"static"); + else if(npc.type=="fullstatic") sprite=new_sprite(npc.skin,"full"); + else sprite=new_sprite(npc.skin,"emote"); + sprite.npc=npc_id; + sprite.parentGroup=sprite.displayGroup=player_layer; + sprite.interactive=true; + sprite.buttonMode=true; + sprite.real_x=sprite.x=round(position[0]); + sprite.real_y=sprite.y=round(position[1]); + if(npc.type=="fullstatic" && position.length==3) npc.direction=position[2]; + if(npc.role=="citizen") sprite.citizen=true; + sprite.anchor.set(0.5,1); // this might be manually handled, but no need + sprite.type="npc"; + sprite.npc=true; + sprite.animations={}; sprite.fx={}; + sprite.emblems={}; + adopt_soft_properties(sprite,npc); + if(npc.stand) + { + var stand=new PIXI.Sprite(textures[npc.stand]); + stand.y=7; + stand.anchor.set(0.5,1); + sprite.addChild(stand); + } + if(sprite.stype=="emote") + { + var actual=[26,35],anchor=sprite.anchor; + if(sprite.role=="newyear_tree") actual=[32,60]; + sprite.hitArea=new PIXI.Rectangle(-actual[0]*anchor.x-2,-actual[1]*anchor.y-2,actual[0]+4,actual[1]+4); + sprite.awidth=actual[0]; + sprite.aheight=actual[1]; + if(npc.atype) + { + sprite.atype=npc.atype; + sprite.frame=sprite.stopframe||sprite.frame; + } + } + sprite.on('mousedown',npc_right_click).on('touchstart',npc_right_click).on('rightdown',npc_right_click); + //#GTODO: Maybe focus with a story / name + sprite.onrclick=npc_right_click; + return sprite; +} + +function add_character(data,me) +{ + // console.log("add_character "+data.skin); + // data.skin="dknight2"; + var npc=data.npc && G.npcs[data.npc],stype="full"; + if(npc && npc.type=="static") stype="static"; + else if(npc && npc.type!="fullstatic") stype="emote"; + if(log_flags.entities) console.log("add character "+data.id); + var cscale=(me && manual_centering && 2) || 1; + if(!XYWH[data.skin]) data.skin="naked"; + var sprite=new_sprite(data.skin,stype); + if(cscale!=1) sprite.scale=new PIXI.Point(cscale,cscale); + sprite.cscale=cscale; + + adopt_soft_properties(sprite,data); + if(stype=="full") cosmetics_logic(sprite); + + sprite.name=sprite.id; + + sprite.parentGroup=sprite.displayGroup=player_layer; + sprite.walking=null; + sprite.animations={}; sprite.fx={}; + sprite.emblems={}; + sprite.real_alpha=1; + sprite.x=round(data.x); sprite.real_x=parseFloat(data.x); + sprite.y=round(data.y); sprite.real_y=parseFloat(data.y); + sprite.last_ms=new Date(); + sprite.anchor.set(0.5,1); + sprite.type="character"; + sprite.me=me; + sprite.base={h:8,v:7,vn:2}; + if(npc) + { + sprite.type="npc"; + if(data.direction!==undefined) sprite.direction=data.direction; + // sprite.npc_onclick=true; + sprite.role=G.npcs[data.npc].role; + adopt_soft_properties(sprite,npc); + if(npc.role=="citizen" || npc.movable) sprite.citizen=true; + if(npc.stand) + { + var stand=new PIXI.Sprite(textures[npc.stand]); + stand.y=7; + stand.anchor.set(0.5,1); + sprite.addChild(stand); + } + } + sprite.awidth=sprite.width/cscale; sprite.aheight=sprite.height/cscale; + if(stype=="emote") + { + var actual=[26,35],anchor=sprite.anchor; + if(sprite.role=="newyear_tree") actual=[32,60]; + sprite.hitArea=new PIXI.Rectangle(-actual[0]*anchor.x-2,-actual[1]*anchor.y-2,actual[0]+4,actual[1]+4); + sprite.awidth=actual[0]; + sprite.aheight=actual[1]; + if(npc.atype) + { + sprite.atype=npc.atype; + sprite.frame=sprite.stopframe||sprite.frame; + } + } + if(npc) + { + sprite.interactive=true; + sprite.buttonMode=true; + sprite.on('mousedown',npc_right_click).on('touchstart',npc_right_click).on('rightdown',npc_right_click); + sprite.onrclick=npc_right_click; + } + else if(!(me && manual_centering)) + { + sprite.interactive=true; + sprite.on("mousedown",player_click).on("touchstart",player_click); + sprite.on('mouseover',mouseover); + sprite.on('mouseout',mouseout); + if(!me && pvp) + { + sprite.cursor="crosshair"; + } + // sprite.on('rightdown',player_right_click); - so simple, yet doesn't work since there is no propagation between siblings [07/09/16] + } + if(me) + { + sprite.explanation="Hey Adventurer! This is your very own character that is a PIXI.Sprite Object. Adventure Land uses PIXI to draw things. You can learn more about it: https://www.pixijs.com/ and draw your own stuff via CODE! (Technical) Since your character is a special object, it doesn't get drawn like other entities, therefore your real character object has static x and y values. The character object in Code is an Object that mimics and extends your actual character Object. It's kinda complicated, but the only difference is that your real character object has different x and y values."; + if(mode.ltbl && 0) + { + var lightbulb = new PIXI.Graphics(); + var rr = 100; + var rg = 100; + var rb = 100; + var rad = 70; + lightbulb.beginFill((rr << 16) + (rg << 8) + rb, 1.0); + lightbulb.drawCircle(0, 0, rad); + lightbulb.endFill(); + lightbulb.parentLayer = lighting; + + sprite.addChild(lightbulb); + } + } + if(manual_centering && 0) + { + var actual=[sprite.awidth,sprite.aheight],anchor=sprite.anchor; + sprite.hitArea=new PIXI.Rectangle(-actual[0]*anchor.x-2,-actual[1]*anchor.y-2,actual[0]+4,actual[1]+4); + } + return sprite; +} + +function add_chest(data) +{ + var chest=new_sprite(data.chest,"v_animation"); // previously a new texture was created each time [01/04/17] + chest.parentGroup=chest.displayGroup=chest_layer; + chest.x=round(data.x); + chest.y=round(data.y)-1; + chest.items=data.items; + chest.anchor.set(0.5,1); + chest.type="chest"; + chest.interactive=true; + chest.buttonMode=true; + chest.cursor="help"; + chest.map=data.map; + chest.id=data.id; + var chest_click=function(){ + // sfx("open",chest.x,chest.y); + open_chest(data.id); + }; + chest.on('mousedown',chest_click).on('touchstart',chest_click).on('rightdown',chest_click); + chests[data.id]=chest; + if(chest.map==current_map) map.addChild(chest); +} + +function get_npc(n_id) +{ + if(!n_id) return null; + if(entities[n_id]) return entities[n_id]; + for(var id in entities) + if(entities[id].npc==n_id) + return entities[id]; + return null; +} + +function add_machine(machine) +{ + var sprite=new_sprite(machine,"machine"); + sprite.parentGroup=sprite.displayGroup=player_layer; + sprite.interactive=true; + // sprite.cursor="pointer"; + sprite.buttonMode=true; + sprite.x=round(machine.x); + sprite.y=round(machine.y); + sprite.type="machine"; + sprite.mtype=machine.type; + sprite.updates=0; + sprite.anchor.set(0.5,1); + // sprite.shuffling=true; + + if(machine.type=="dice") + { + sprite.digits=e_array(4); + for(var i=0;i<4;i++) + { + sprite.digits[i]=new PIXI.Sprite(textures["dicesub"][8]); //parseInt(Math.random()*10) + sprite.digits[i].anchor.set(0.5,1); + sprite.digits[i].x=-11+i*7; + if(i>1) sprite.digits[i].x+=1; + sprite.digits[i].y=-17; + sprite.addChild(sprite.digits[i]); + } + sprite.dot=new PIXI.Sprite(textures["dicesub"][10]); + sprite.dot.anchor.set(0.5,1); + sprite.dot.x=0; + sprite.dot.y=-21; + sprite.addChild(sprite.dot); + sprite.seconds=0; + sprite.count_start=new Date(); + // sprite.shuffling=true; + sprite.shuffle_speed=100; + } + + function machine_click(event) + { + if(machine.type=="dice") render_dice(); // add_log("Curious device","gray");// + if(machine.type=="wheel") add_log("The hostess isn't around","gray"); + if(machine.type=="slots") render_interaction({auto:true,skin:character.skin,message:"Hmm. This machine seems broken. Still give it a try? [1,000,000 gold]",button:"YES!",onclick:function(){socket.emit("bet",{type:"slots"});}});; + try{if(event) event.stopPropagation();}catch(e){}; + } + sprite.on('mousedown',machine_click).on('touchstart',machine_click).on('rightdown',machine_click); + sprite.onrclick=machine_click; + return sprite; +} + +function add_door(door) +{ + var sprite=new PIXI.Sprite(); + sprite.parentGroup=sprite.displayGroup=player_layer; + sprite.interactive=true; + //sprite.cursor="pointer"; + sprite.buttonMode=true; + sprite.x=round(door[0]); + sprite.y=round(door[1]); + sprite.to=door[4]; + sprite.s=door[5]; + sprite.anchor.set(0.5,1); + //sprite.width=door[2]; sprite.height=door[3]; + //sprite.hitArea=new PIXI.Rectangle(0,0,round(door[2]),round(door[3])); + sprite.hitArea=new PIXI.Rectangle(-round(door[2]*0.5),-round(door[3]*1),round(door[2]),round(door[3])); + sprite.type="door"; + function door_right_click(event){ + if(event) event.stopPropagation(); + // if(distance(character,{x:door[0]+door[2]/2,y:door[1]+door[3]/2})>100) {add_log("Get closer","gray"); return;} + if(is_electron && electron_data.platform=="mas" && door[4]=="tavern") return show_alert("You can't enter the Tavern from Mac App Store :|"); + if(door[7]=="key") + { + if(character.party) + { + for(var p in party) + { + var c=party[p]; + if(c['map']==door[4]) + { + socket.emit('enter',{place:door[4],name:c["in"]}); + push_deferred("enter"); + return; + } + } + } + setTimeout(function(){ show_confirm("Enter "+G.maps[door[4]].name+"? [Consumes a key!]",["#D06631","Yes"],"No!",function(){ socket.emit('enter',{place:door[4]}); push_deferred("enter"); hide_modal(true); }); },10); + return; + } + if(!is_door_close(character.map,door,character.real_x,character.real_y) || !can_use_door(character.map,door,character.real_x,character.real_y)) {add_log("Get closer","gray"); return;} + socket.emit("transport",{to:door[4],s:door[5]}); + push_deferred("transport"); + } + if(is_mobile) sprite.on('mousedown',door_right_click).on('touchstart',door_right_click); + sprite.on('rightdown',door_right_click); + sprite.onrclick=door_right_click; + return sprite; +} + +function add_quirk(quirk) +{ + var sprite=new PIXI.Sprite(); + sprite.parentGroup=sprite.displayGroup=player_layer; + sprite.interactive=true; + sprite.buttonMode=true; + if(quirk[4]!="upgrade" && quirk[4]!="compound") sprite.cursor="help"; + sprite.x=round(quirk[0]); + sprite.y=round(quirk[1]); + sprite.anchor.set(0.5,1); + //sprite.hitArea=new PIXI.Rectangle(0,0,round(quirk[2]),round(quirk[3])); + sprite.hitArea=new PIXI.Rectangle(-round(quirk[2]*0.5),-round(quirk[3]*1),round(quirk[2]),round(quirk[3])); + sprite.type="quirk"; + function quirk_right_click(event){ + if(quirk[4]=="sign") add_log('Sign reads: "'+quirk[5]+'"',"gray"); + else if(quirk[4]=="note") add_log('Note reads: "'+quirk[5]+'"',"gray"); + else if(quirk[4]=="tavern_info") socket.emit("tavern",{event:"info"}); + else if(quirk[4]=="mainframe") render_mainframe(); + else if(quirk[4]=="the_lever") the_lever(); + else if(quirk[4]=="log") add_log(quirk[5],"gray"); + else if(quirk[4]=="upgrade") render_upgrade_shrine(1); + else if(quirk[4]=="compound") render_compound_shrine(1); + else if(quirk[4]=="list_pvp") socket.emit("list_pvp"); + else if(quirk[4]=="invisible_statue") render_none_shrine(),add_log('An invisible statue!',"gray"); + try{if(event) event.stopPropagation();}catch(e){}; + } + if(is_mobile || in_arr(quirk[4],["upgrade","compound","invisible_statue"])) sprite.on('mousedown',quirk_right_click).on('touchstart',quirk_right_click); + sprite.on('rightdown',quirk_right_click); + sprite.on('mousedown',quirk_right_click).on('touchstart',quirk_right_click); // Better to make them all-clickable [31/08/18] + return sprite; +} + +function add_animatable(name,data) +{ + var animatable=new_sprite(data.position,"animatable"); + animatable.x=data.x; + animatable.y=data.y; + animatable.anchor.set(0.5,1); + animatable.type="animatable"; + return animatable; +} + +function create_map() +{ + var start=new Date(); + pvp=G.maps[current_map].pvp || is_pvp; + if(paused) return; + drawn_map=current_map; + if(window.map) + { + if(window.inner_stage) inner_stage.removeChild(window.map); + else stage.removeChild(window.map); + for(var id in chests) + { + var chest=chests[id]; + if(chest.map==window.map.map_name) map.removeChild(chest); + } + // #IDEA: Destroy sprites too, otherwise they stack up + if(!cached_map && map_tiles.length && map.children) map.removeChildren(map.children.indexOf(map_tiles[0]),map.children.indexOf(map_tiles[map_tiles.length-1])); // [06/03/20] + free_children(map) // #PIXI: https://github.com/pixijs/pixi.js/pull/2995#issuecomment-248974419 + + map.destroy(); + for(var id in map_animations) destroy_sprite(map_animations[id],"children"); + map_entities.forEach(function(e){ e.destroy({children:true}); }); + if(wtile) wtile.destroy(),wtile=null; + if(dtile) dtile.destroy(),dtile=null; + if(tiles) tiles.destroy(),tiles=null; + (window.rtextures||[]).forEach(function(t){if(t) t.destroy(true); }); // Live and learn experience, .destroy() was a major memory leak: https://github.com/pixijs/pixi.js/issues/4163 [18/07/17] + (window.dtextures||[]).forEach(function(t){if(t) t.destroy(true); }); + // #GTODO: Maybe only destroy groups and NPC's that are not re-used + // map.destroy({children:true}); // added children:true - exception [20/08/16] #PIXI + } + map_npcs=[]; map_doors=[]; map_nights=[]; map_lights=[]; map_tiles=[]; map_entities=[]; map_animations={}; map_machines={}; water_tiles=[]; entities={}; + + dtile_size=GEO['default']&&GEO.tiles[GEO['default']][3]; + if(dtile_size && is_array(dtile_size)) dtile_size=dtile_size[0]; + + wtile_name=G.maps[current_map].weather; + + map=new PIXI.Container(); + map.map_name=current_map; + //var filter=new PIXI.filters.ColorMatrixFilter() + //filter.desaturate(0.2); + //map.filters=[filter]; + //filter.sepia(0.01); + //filter.brightness(1.04); + map.real_x=0; map.real_y=0; + if(first_coords) + { + first_coords=false; + map.real_x=first_x; + map.real_y=first_y; + } + map.speed=80; + map.hitArea=new PIXI.Rectangle(-20000,-20000,40000,40000); + if(scale) map.scale=new PIXI.Point(scale,scale); + + map.interactive=true; + map.on('mousedown',map_click).on('mouseup',map_click_release).on('mouseupoutside',map_click_release) + .on('touchstart',map_click).on('touchend',map_click_release).on('touchendoutside',map_click_release); + + if(window.inner_stage) inner_stage.addChild(map); + else stage.addChild(map); + + if(G.maps[current_map].filter=="halloween" && !no_graphics) + { + var filter=new PIXI.filters.ColorMatrixFilter() + filter.saturate(-0.1); + stage.cfilter_halloween=filter; + regather_filters(stage); + } + else + { + delete stage.cfilter_halloween; + regather_filters(stage); + } + + if(!tile_sprites[current_map]) tile_sprites[current_map]=[],tile_textures[current_map]=[],sprite_last[current_map]=[]; + + for(var i=0;i=tile_sprites[current_map][tile[0]].length) + tile_sprites[current_map][tile[0]][ sprite_last[current_map][tile[0]] ]=new_map_tile(tile_textures[current_map][tile[0]]); + var entity=tile_sprites[current_map][tile[0]][ sprite_last[current_map][tile[0]]++ ]; // Sprite to add to the stage individually + if(entity.textures) entity.texture=entity.textures[last_water_frame]; + entity.x=tile[1]-GEO.min_x; + entity.y=tile[2]-GEO.min_y; + tile_containers[last_water_frame].addChild(entity); + } + else + { + var def=GEO.tiles[tile[0]],w=def[3],h=def[4]; + if(abs(((tile[3]-tile[1])/w+1)*((tile[4]-tile[2])/h+1))>=20) // abs(((tile[3]-tile[1])/w+1)*((tile[4]-tile[2])/h+1))>4 + { + // PIXI.extras.TilingSprite is slow [22/03/20] + var texture=tile_textures[current_map][tile[0]][0]; + if(tile_textures[current_map][tile[0]].length>1) // new_map_tile logic + texture=tile_textures[current_map][tile[0]][last_water_frame%tile_textures[current_map][tile[0]].length]; + var entity=new PIXI.extras.TilingSprite(texture,tile[3]-tile[1]+w,tile[4]-tile[2]+h); + entity.x=tile[1]-GEO.min_x; + entity.y=tile[2]-GEO.min_y; + tile_containers[last_water_frame].addChild(entity); + a++; + } + else + { + b++; + for(var x=tile[1];x<=tile[3];x+=w) + { + for(var y=tile[2];y<=tile[4];y+=h) + { + if(sprite_last[current_map][tile[0]]>=tile_sprites[current_map][tile[0]].length) + tile_sprites[current_map][tile[0]][ sprite_last[current_map][tile[0]] ]=new_map_tile(tile_textures[current_map][tile[0]]); + var entity=tile_sprites[current_map][tile[0]][ sprite_last[current_map][tile[0]]++ ]; + if(entity.textures) entity.texture=entity.textures[last_water_frame]; + entity.x=x-GEO.min_x; + entity.y=y-GEO.min_y; + tile_containers[last_water_frame].addChild(entity); + } + } + } + } + } + tile_containers[last_water_frame].x=0; tile_containers[last_water_frame].y=0; + renderer.render(tile_containers[last_water_frame],rtextures[last_water_frame]); + if(!mode.destroy_tiles) tile_containers[last_water_frame].destroy(); + } + if(dtile_size) window.dtile=new PIXI.Sprite(dtextures[1]),dtile.x=-500,dtile.y=-500; + if(wtile_name) window.wtile=new PIXI.Sprite(wtextures[0]),wtile.x=-500,wtile.y=-500,wtile.parentGroup=sprite.displayGroup=weather_layer; + if(0) + { + window.ftile=new PIXI.Sprite(textures.fog[0]),ftile.x=0,ftile.y=0,ftile.parentGroup=sprite.displayGroup=fog_layer; + window.ftile2=new PIXI.Sprite(textures.fog[1]),ftile2.x=-500,ftile2.y=0,ftile2.parentGroup=sprite.displayGroup=fog_layer; + window.ftile3=new PIXI.Sprite(textures.fog[1]),ftile3.x=500,ftile3.y=0,ftile3.parentGroup=sprite.displayGroup=fog_layer; + ftile.anchor.set(0.5,0.5); ftile.height*=5; ftile.width*=5; + ftile2.anchor.set(0.5,0.5); ftile2.height*=5; ftile2.width*=5; + ftile3.anchor.set(0.5,0.5); ftile3.height*=5; ftile3.width*=5; + map.addChild(ftile); + map.addChild(ftile2); + map.addChild(ftile3); + } + window.tiles=new PIXI.Sprite(rtextures[0]); + tiles.x=GEO.min_x; + tiles.y=GEO.min_y; + if(dtile_size) map.addChild(dtile); + map.addChild(tiles); + if(wtile_name) map.addChild(wtile); + + /* clean up */ + if(mode.destroy_tiles) + { + for(var i=0;i<3;i++) + { + tile_containers[i].destroy(); //{children:true} + } + for(var i=0;imax_y) max_y=nunv(tile[4],tile[2])+def[4]; + } + for(var i=0;i=border || abs(map.last_max_x-max_x)>=border)) + { + if(last_water_frame!=water_frame()) + { + last_water_frame=water_frame(); + for(var i=0;imax_x || entity.y>max_y || entity.x+entity.width=tile_sprites[current_map][GEO['default']].length) + tile_sprites[current_map][GEO['default']][ sprite_last[current_map][GEO['default']] ]=new_map_tile(tile_textures[current_map][GEO['default']]),s++; + var entity=tile_sprites[current_map][GEO['default']][ sprite_last[current_map][GEO['default']]++ ]; + if(entity.textures) entity.texture=entity.textures[last_water_frame],water_tiles.push(entity); + entity.x=ex*def[3]; + entity.y=ey*def[4]; + if(mdraw_mode!="redraw") entity.parentGroup=entity.displayGroup=map_layer,entity.zOrder=0; + entity.tid=tid; + map.addChild(entity); + map_tiles.push(entity); + } + } + else if(GEO['default']) + { + var def=GEO.tiles[GEO['default']]; + if(!window.default_tiling) default_tiling=new PIXI.extras.TilingSprite(tile_textures[current_map][GEO['default']][0],floor((max_x-min_x)/32)*32+32,floor((max_y-min_y)/32)*32+32); + default_tiling.x=floor(min_x/def[3])*def[3]; + default_tiling.y=floor(min_y/def[4])*def[4]; + default_tiling.textures=tile_textures[current_map][GEO['default']]; + map.addChild(default_tiling); + map_tiles.push(default_tiling); + } + + + for(var i=0;imax_x || tile[2]>max_y || tile[1]+w=tile_sprites[current_map][tile[0]].length) + tile_sprites[current_map][tile[0]][ sprite_last[current_map][tile[0]] ]=new_map_tile(tile_textures[current_map][tile[0]]),s++; + var entity=tile_sprites[current_map][tile[0]][ sprite_last[current_map][tile[0]]++ ]; // Sprite to add to the stage individually + if(entity.textures) entity.texture=entity.textures[last_water_frame],water_tiles.push(entity); + entity.x=tile[1]; + entity.y=tile[2]; + if(mdraw_mode!="redraw") entity.parentGroup=entity.displayGroup=map_layer,entity.zOrder=-(i+1); + entity.tid='p'+i; + map.addChild(entity); + map_tiles.push(entity); + } + else // #GTODO: Improve this routine, a lot [07/07/16] + { + var def=GEO.tiles[tile[0]],w=def[3],h=def[4]; + if(!mdraw_tiling_sprites || mdraw_tiling_sprites && abs(((tile[3]-tile[1])/w+1)*((tile[4]-tile[2])/h+1))<8) + { + for(var x=tile[1];x<=tile[3];x+=w) + { + if(x>max_x || x+wmax_y || y+h=tile_sprites[current_map][tile[0]].length) + tile_sprites[current_map][tile[0]][ sprite_last[current_map][tile[0]] ]=new_map_tile(tile_textures[current_map][tile[0]]),s++; + var entity=tile_sprites[current_map][tile[0]][ sprite_last[current_map][tile[0]]++ ]; + if(entity.textures) entity.texture=entity.textures[last_water_frame],water_tiles.push(entity); + entity.x=x; + entity.y=y; + entity.tid='p'+i+'-'+x+'-'+y; + map.addChild(entity); + map_tiles.push(entity); + } + } + } + else + { + if(!window['defP'+current_map+i]) window['defP'+current_map+i]=new PIXI.extras.TilingSprite(tile_textures[current_map][tile[0]][0],tile[3]-tile[1]+w,tile[4]-tile[2]+h); + var entity=window['defP'+current_map+i]; + entity.x=tile[1]; + entity.y=tile[2]; + entity.tid='pt'+i; + map.addChild(entity); + map_tiles.push(entity); + } + } + } + + drawings.forEach(function(e){ //user-drawings + try{ + var parent=e&&e.parent; + if(parent){parent.removeChild(e); parent.addChild(e);} + }catch(ex){ + console.log("User drawing exception: "+ex); + } + }); + + console.log("retile_map ms: "+mssince(start)+" min_x: "+min_x+" max_x: "+max_x+" entities: "+map_tiles.length+" removed: "+r+" new: "+s); + +} + +var fps_counter=null,frames=0,last_count=null,last_frame,fps=0; +function calculate_fps() +{ + if(!fps_counter) return; + if(mode.dom_tests_pixi || inside=="payments") return; + frames+=1; + if(!last_count) last_count=new Date(),last_frame=frames,frequency=500; + if(mssince(last_count)>=frequency) last_count=new Date(),fps=(frames-last_frame)*(1000.0/frequency),last_frame=frames; + fps_counter.text=""+round(fps); + fps_counter.position.set(width-(inside=="com"&&5||335), height-(inside=="com"&&5||0)); +} + +function load_game(c) +{ + loader.load(function (loader, resources) { + + //PIXI.ticker.shared.autoStart = false; + //PIXI.ticker.shared.stop(); https://github.com/pixijs/pixi.js/issues/2843#issuecomment-241682589 no observable effect + + if(mode_nearest) + for(file in PIXI.utils.BaseTextureCache) + PIXI.utils.BaseTextureCache[file].scaleMode=PIXI.SCALE_MODES.NEAREST; // great find - prevents tile gaps and upper shadows / similar imperfections [17/06/16] + + // IID=null; + + for(name in G.sprites) + { + var s_def=G.sprites[name]; + // console.log(s_def.file); + if(s_def.skip) continue; + var row_num=4,col_num=3,s_type="full"; + // #TODO: ALWAYS REPLICATE TO html.js / precompute_image_positions + if(in_arr(s_def.type,["animation"])) row_num=1,s_type=s_def.type; + if(in_arr(s_def.type,["tail"])) col_num=4,s_type=s_def.type; + if(in_arr(s_def.type,["v_animation","head","hair","hat","s_wings","face","makeup","beard"])) col_num=1,s_type=s_def.type; + if(in_arr(s_def.type,["a_makeup","a_hat"])) col_num=3,s_type=s_def.type; + if(in_arr(s_def.type,["wings","body","armor","skin","character"])) s_type=s_def.type; + if(in_arr(s_def.type,["emblem","gravestone"])) row_num=1,col_num=1,s_type=s_def.type; + var matrix=s_def.matrix; + if(no_graphics) C[s_def.file]={width:20,height:20}; //#NOGTODO: pull these values from SDK + Insert into data.js for usage [03/01/18] + var width=C[s_def.file].width/(s_def.columns*col_num); + var height=C[s_def.file].height/(s_def.rows*row_num); + for(var i=0;iright_pressed) map.real_x-=speed; + if(up_presseddown_pressed) map.real_y-=speed; + + } + + var cframe_ms=frame_ms,mframe_ms=frame_ms; + if(clean_house) draw_entities(),mframe_ms=0; + process_entities(); + future_entities={players:{},monsters:{}}; + stop_timer("draw","entities"); + + if(gtest && character) map.real_x-=0.1,map.real_y-=0.001; + + + // cframe_ms=min(2000,cframe_ms); // so the game won't freeze after a lengthy sleep - no need [26/07/16] + //console.log(cframe_ms); console.log(map.x+" "+map.y); + if(cframe_ms>(is_sdk&&200||10000)) console.log("cframe_ms is "+cframe_ms); + while(cframe_ms>0) + { + if(character && character.moving) + { + moved=true; + if(character.vx) character.real_x+=character.vx*min(cframe_ms,50)/1000.0; + if(character.vy) character.real_y+=character.vy*min(cframe_ms,50)/1000.0; + set_direction(character); + stop_logic(character); + // if(!character.moving) console.log("STOPPED"); + } + cframe_ms-=50; + } + while(mframe_ms>0) + { + var moved=false; + for(var iii in entities) + { + entity=entities[iii]; + if(entity && !entity.dead && entity.moving) + { + moved=true; + entity.real_x+=entity.vx*min(mframe_ms,50)/1000.0; + entity.real_y+=entity.vy*min(mframe_ms,50)/1000.0; + set_direction(entity); + stop_logic(entity); + } + } + mframe_ms-=50; + if(!moved) break; + } + if(window.ftile && character) + { + ftile.x=character.real_x; + ftile2.y=ftile3.y=ftile.y=character.real_y; + ftile2.x=ftile.x-500; + ftile3.x=ftile.x+500; + } + stop_timer("draw","movements"); + + position_map(); + + ui_logic(); + + call_code_function("on_draw"); // before retile_the_map, as retile_the_map updates drawings + + retile_the_map(); stop_timer("draw","retile"); + + update_overlays(); + + if(character && character.q.exchange && topleft_npc=="exchange") exchange_animation_logic(); + if(character && character.q.compound) compound_animation_logic(); + if(character && character.q.upgrade) upgrade_animation_logic(); + + stop_timer("draw","uis"); + + tint_logic(); + draw_timeouts_logic(); stop_timer("draw","timeouts"); + + draw_entities(); // moved all the update_sprite routines to the absolute end - as they make the final visual changes to the sprites [03/10/18] + + stop_timer("draw","draw_entities"); + + if(character) update_sprite(character); + map_npcs.forEach(function(npc){ update_sprite(npc); }); + for(var id in chests) if(chests[id].openning) update_sprite(chests[id]); + for(var id in map_animations) update_sprite(map_animations[id]); + stop_timer("draw","sprites"); + + stop_timer("draw","before_render"); + + if(force_draw_on || !manual_draw && !is_hidden() && !paused) + { + renderer.render(stage); + force_draw_on=false; + } + + if(current_status!=last_status) $("#status").html(current_status),last_status=current_status; + + stop_timer("draw","after_render"); + var t; + if(!manual_draw && (!no_html || no_html=="bot")) // && !no_html [18/04/19] - let no_html call draw as usual too + { + + if(no_graphics) t=setTimeout(draw,16); // jsdom patch [18/04/19] + else requestAnimationFrame(draw); + try{ + var chars=get_active_characters(); + for(var name in chars) + { + if(chars[name]!="self" && chars[name]!="loading") character_window_eval(name,"draw()"); + } + } + catch(e){console.log(e);} + } + in_draw=false; +} \ No newline at end of file diff --git a/js/howler/.DS_Store b/js/howler/.DS_Store new file mode 100644 index 0000000..cf81b6b Binary files /dev/null and b/js/howler/.DS_Store differ diff --git a/js/howler/2.0.0-beta14/howler.min.js b/js/howler/2.0.0-beta14/howler.min.js new file mode 100644 index 0000000..77e3f80 --- /dev/null +++ b/js/howler/2.0.0-beta14/howler.min.js @@ -0,0 +1,4 @@ +/*! howler.js v2.0.0-beta14 | (c) 2013-2016, James Simpson of GoldFire Studios | MIT License | howlerjs.com */ +!function(){"use strict";var e=function(){this.init()};e.prototype={init:function(){var e=this||n;return e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.mobileAutoEnable=!0,e._setup(),e},volume:function(e){var o=this||n;if(e=parseFloat(e),o.ctx||_(),"undefined"!=typeof e&&e>=0&&1>=e){if(o._volume=e,o._muted)return o;o.usingWebAudio&&(o.masterGain.gain.value=e);for(var t=0;t=0;o--)e._howls[o].unload();return e.usingWebAudio&&"undefined"!=typeof e.ctx.close&&(e.ctx.close(),e.ctx=null,_()),e},codecs:function(e){return(this||n)._codecs[e]},_setup:function(){var e=this||n;return e.state=e.ctx?e.ctx.state||"running":"running",e._autoSuspend(),e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||n,o="undefined"!=typeof Audio?new Audio:null;if(!o||"function"!=typeof o.canPlayType)return e;var t=o.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator&&e._navigator.userAgent.match(/OPR\/([0-6].)/g),u=r&&parseInt(r[0].split("/")[1],10)<33;return e._codecs={mp3:!(u||!t&&!o.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!t,opus:!!o.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!o.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!o.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!o.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),aac:!!o.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!o.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(o.canPlayType("audio/x-m4a;")||o.canPlayType("audio/m4a;")||o.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(o.canPlayType("audio/x-mp4;")||o.canPlayType("audio/mp4;")||o.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!!o.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,""),webm:!!o.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,""),dolby:!!o.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,"")},e},_enableMobileAudio:function(){var e=this||n,o=/iPhone|iPad|iPod|Android|BlackBerry|BB10|Silk|Mobi/i.test(e._navigator&&e._navigator.userAgent),t=!!("ontouchend"in window||e._navigator&&e._navigator.maxTouchPoints>0||e._navigator&&e._navigator.msMaxTouchPoints>0);if(!e._mobileEnabled&&e.ctx&&(o||t)){e._mobileEnabled=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var r=function(){var n=e.ctx.createBufferSource();n.buffer=e._scratchBuffer,n.connect(e.ctx.destination),"undefined"==typeof n.start?n.noteOn(0):n.start(0),n.onended=function(){n.disconnect(0),e._mobileEnabled=!0,e.mobileAutoEnable=!1,document.removeEventListener("touchend",r,!0)}};return document.addEventListener("touchend",r,!0),e}},_autoSuspend:function(){var e=this;if(e.autoSuspend&&e.ctx&&"undefined"!=typeof e.ctx.suspend&&n.usingWebAudio){for(var o=0;o0?d._seek:o._sprite[e][0]/1e3,_=(o._sprite[e][0]+o._sprite[e][1])/1e3-i,s=1e3*_/Math.abs(d._rate);d._paused=!1,d._ended=!1,d._sprite=e,d._seek=i,d._start=o._sprite[e][0]/1e3,d._stop=(o._sprite[e][0]+o._sprite[e][1])/1e3,d._loop=!(!d._loop&&!o._sprite[e][2]);var l=d._node;if(o._webAudio){var f=function(){o._refreshBuffer(d);var e=d._muted||o._muted?0:d._volume*n.volume();l.gain.setValueAtTime(e,n.ctx.currentTime),d._playStart=n.ctx.currentTime,"undefined"==typeof l.bufferSource.start?d._loop?l.bufferSource.noteGrainOn(0,i,86400):l.bufferSource.noteGrainOn(0,i,_):d._loop?l.bufferSource.start(0,i,86400):l.bufferSource.start(0,i,_),s!==1/0&&(o._endTimers[d._id]=setTimeout(o._ended.bind(o,d),s)),t[1]||setTimeout(function(){o._emit("play",d._id)},0)};"loaded"===o._state?f():(o.once("load",f,d._id),o._clearTimer(d._id))}else{var c=function(){l.currentTime=i,l.muted=d._muted||o._muted||n._muted||l.muted,l.volume=d._volume*n.volume(),l.playbackRate=d._rate,setTimeout(function(){l.play(),s!==1/0&&(o._endTimers[d._id]=setTimeout(o._ended.bind(o,d),s)),t[1]||o._emit("play",d._id)},0)},p="loaded"===o._state&&(window&&window.ejecta||!l.readyState&&n._navigator.isCocoonJS);if(4===l.readyState||p)c();else{var m=function(){c(),l.removeEventListener(n._canPlayEvent,m,!1)};l.addEventListener(n._canPlayEvent,m,!1),o._clearTimer(d._id)}}return d._id},pause:function(e){var n=this;if("loaded"!==n._state)return n._queue.push({event:"pause",action:function(){n.pause(e)}}),n;for(var o=n._getSoundIds(e),t=0;t=0?o=parseInt(r[0],10):e=parseFloat(r[0])}else r.length>=2&&(e=parseFloat(r[0]),o=parseInt(r[1],10));var d;if(!("undefined"!=typeof e&&e>=0&&1>=e))return d=o?t._soundById(o):t._sounds[0],d?d._volume:0;if("loaded"!==t._state)return t._queue.push({event:"volume",action:function(){t.volume.apply(t,r)}}),t;"undefined"==typeof o&&(t._volume=e),o=t._getSoundIds(o);for(var i=0;io?"out":"in",i=a/.01,_=t/i;if("loaded"!==u._state)return u._queue.push({event:"fade",action:function(){u.fade(e,o,t,r)}}),u;u.volume(e,r);for(var s=u._getSoundIds(r),l=0;l=0?o=parseInt(r[0],10):e=parseFloat(r[0])}else 2===r.length&&(e=parseFloat(r[0]),o=parseInt(r[1],10));var d;if("number"!=typeof e)return d=t._soundById(o),d?d._rate:t._rate;if("loaded"!==t._state)return t._queue.push({event:"rate",action:function(){t.rate.apply(t,r)}}),t;"undefined"==typeof o&&(t._rate=e),o=t._getSoundIds(o);for(var i=0;i=0?o=parseInt(r[0],10):(o=t._sounds[0]._id,e=parseFloat(r[0]))}else 2===r.length&&(e=parseFloat(r[0]),o=parseInt(r[1],10));if("undefined"==typeof o)return t;if("loaded"!==t._state)return t._queue.push({event:"seek",action:function(){t.seek.apply(t,r)}}),t;var d=t._soundById(o);if(d){if(!("number"==typeof e&&e>=0)){if(t._webAudio){var i=t.playing(o)?n.ctx.currentTime-d._playStart:0,_=d._rateSeek?d._rateSeek-d._seek:0;return d._seek+(_+i*Math.abs(d._rate))}return d._node.currentTime}var s=t.playing(o);s&&t.pause(o,!0),d._seek=e,d._ended=!1,t._clearTimer(o),s&&t.play(o,!0),t._emit("seek",o)}return t},playing:function(e){var n=this;if("number"==typeof e){var o=n._soundById(e);return o?!o._paused:!1}for(var t=0;t=0&&n._howls.splice(u,1)}var a=!0;for(t=0;t=0;u--)r[u].id&&r[u].id!==n&&"load"!==e||(setTimeout(function(e){e.call(this,n,o)}.bind(t,r[u].fn),0),r[u].once&&t.off(e,r[u].fn,r[u].id));return t},_loadQueue:function(){var e=this;if(e._queue.length>0){var n=e._queue[0];e.once(n.event,function(){e._queue.shift(),e._loadQueue()}),n.action()}return e},_ended:function(e){var o=this,t=e._sprite,r=!(!e._loop&&!o._sprite[t][2]);if(o._emit("end",e._id),!o._webAudio&&r&&o.stop(e._id).play(e._id),o._webAudio&&r){o._emit("play",e._id),e._seek=e._start||0,e._rateSeek=0,e._playStart=n.ctx.currentTime;var u=1e3*(e._stop-e._start)/Math.abs(e._rate);o._endTimers[e._id]=setTimeout(o._ended.bind(o,e),u)}return o._webAudio&&!r&&(e._paused=!0,e._ended=!0,e._seek=e._start||0,e._rateSeek=0,o._clearTimer(e._id),o._cleanBuffer(e._node),n._autoSuspend()),o._webAudio||r||o.stop(e._id),o},_clearTimer:function(e){var n=this;return n._endTimers[e]&&(clearTimeout(n._endTimers[e]),delete n._endTimers[e]),n},_soundById:function(e){for(var n=this,o=0;o=0;t--){if(n>=o)return;e._sounds[t]._ended&&(e._webAudio&&e._sounds[t]._node&&e._sounds[t]._node.disconnect(0),e._sounds.splice(t,1),o--)}}},_getSoundIds:function(e){var n=this;if("undefined"==typeof e){for(var o=[],t=0;t0&&(r[o._src]=e,i(o,e))},function(){o._emit("loaderror",null,"Decoding audio data failed.")})},i=function(e,n){n&&!e._duration&&(e._duration=n.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue()),e._autoplay&&e.play()},_=function(){n.noAudio=!1;try{"undefined"!=typeof AudioContext?n.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?n.ctx=new webkitAudioContext:n.usingWebAudio=!1}catch(e){n.usingWebAudio=!1}if(!n.usingWebAudio)if("undefined"!=typeof Audio)try{var o=new Audio;"undefined"==typeof o.oncanplaythrough&&(n._canPlayEvent="canplay")}catch(e){n.noAudio=!0}else n.noAudio=!0;try{var o=new Audio;o.muted&&(n.noAudio=!0)}catch(e){}var t=/iP(hone|od|ad)/.test(n._navigator&&n._navigator.platform),r=n._navigator&&n._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),u=r?parseInt(r[1],10):null;if(t&&u&&9>u){var a=/safari/.test(n._navigator&&n._navigator.userAgent.toLowerCase());(n._navigator&&n._navigator.standalone&&!a||n._navigator&&!n._navigator.standalone&&!a)&&(n.usingWebAudio=!1)}n.usingWebAudio&&(n.masterGain="undefined"==typeof n.ctx.createGain?n.ctx.createGainNode():n.ctx.createGain(),n.masterGain.gain.value=1,n.masterGain.connect(n.ctx.destination)),n._setup()};"function"==typeof define&&define.amd&&define([],function(){return{Howler:n,Howl:o}}),"undefined"!=typeof exports&&(exports.Howler=n,exports.Howl=o),"undefined"!=typeof window?(window.HowlerGlobal=e,window.Howler=n,window.Howl=o,window.Sound=t):"undefined"!=typeof global&&(global.HowlerGlobal=e,global.Howler=n,global.Howl=o,global.Sound=t)}(); +/*! Effects Plugin */ +!function(){"use strict";HowlerGlobal.prototype._pos=[0,0,0],HowlerGlobal.prototype._orientation=[0,0,-1,0,1,0],HowlerGlobal.prototype.stereo=function(e){var n=this;if(!n.ctx||!n.ctx.listener)return n;for(var t=n._howls.length-1;t>=0;t--)n._howls[t].stereo(e);return n},HowlerGlobal.prototype.pos=function(e,n,t){var o=this;return o.ctx&&o.ctx.listener?(n="number"!=typeof n?o._pos[1]:n,t="number"!=typeof t?o._pos[2]:t,"number"!=typeof e?o._pos:(o._pos=[e,n,t],o.ctx.listener.setPosition(o._pos[0],o._pos[1],o._pos[2]),o)):o},HowlerGlobal.prototype.orientation=function(e,n,t,o,r,i){var a=this;if(!a.ctx||!a.ctx.listener)return a;var p=a._orientation;return n="number"!=typeof n?p[1]:n,t="number"!=typeof t?p[2]:t,o="number"!=typeof o?p[3]:o,r="number"!=typeof r?p[4]:r,i="number"!=typeof i?p[5]:i,"number"!=typeof e?p:(a._orientation=[e,n,t,o,r,i],a.ctx.listener.setOrientation(e,n,t,o,r,i),a)},Howl.prototype.init=function(e){return function(n){var t=this;return t._orientation=n.orientation||[1,0,0],t._stereo=n.stereo||null,t._pos=n.pos||null,t._pannerAttr={coneInnerAngle:"undefined"!=typeof n.coneInnerAngle?n.coneInnerAngle:360,coneOuterAngle:"undefined"!=typeof n.coneOuterAngle?n.coneOuterAngle:360,coneOuterGain:"undefined"!=typeof n.coneOuterGain?n.coneOuterGain:0,distanceModel:"undefined"!=typeof n.distanceModel?n.distanceModel:"inverse",maxDistance:"undefined"!=typeof n.maxDistance?n.maxDistance:1e4,panningModel:"undefined"!=typeof n.panningModel?n.panningModel:"HRTF",refDistance:"undefined"!=typeof n.refDistance?n.refDistance:1,rolloffFactor:"undefined"!=typeof n.rolloffFactor?n.rolloffFactor:1},t._onstereo=n.onstereo?[{fn:n.onstereo}]:[],t._onpos=n.onpos?[{fn:n.onpos}]:[],t._onorientation=n.onorientation?[{fn:n.onorientation}]:[],e.call(this,n)}}(Howl.prototype.init),Howl.prototype.stereo=function(n,t){var o=this;if(!o._webAudio)return o;if("loaded"!==o._state)return o._queue.push({event:"stereo",action:function(){o.stereo(n,t)}}),o;var r="undefined"==typeof Howler.ctx.createStereoPanner?"spatial":"stereo";if("undefined"==typeof t){if("number"!=typeof n)return o._stereo;o._stereo=n,o._pos=[n,0,0]}for(var i=o._getSoundIds(t),a=0;a= 0 && vol <= 1) { + self._volume = vol; + + // Don't update any of the nodes if we are muted. + if (self._muted) { + return self; + } + + // When using Web Audio, we just need to adjust the master gain. + if (self.usingWebAudio) { + self.masterGain.gain.value = vol; + } + + // Loop through and change volume for all HTML5 audio nodes. + for (var i=0; i=0; i--) { + self._howls[i].unload(); + } + + // Create a new AudioContext to make sure it is fully reset. + if (self.usingWebAudio && typeof self.ctx.close !== 'undefined') { + self.ctx.close(); + self.ctx = null; + setupAudioContext(); + } + + return self; + }, + + /** + * Check for codec support of specific extension. + * @param {String} ext Audio file extention. + * @return {Boolean} + */ + codecs: function(ext) { + return (this || Howler)._codecs[ext]; + }, + + /** + * Setup various state values for global tracking. + * @return {Howler} + */ + _setup: function() { + var self = this || Howler; + + // Keeps track of the suspend/resume state of the AudioContext. + self.state = self.ctx ? self.ctx.state || 'running' : 'running'; + + // Automatically begin the 30-second suspend process + self._autoSuspend(); + + // Check for supported codecs. + if (!self.noAudio) { + self._setupCodecs(); + } + + return self; + }, + + /** + * Check for browser support for various codecs and cache the results. + * @return {Howler} + */ + _setupCodecs: function() { + var self = this || Howler; + var audioTest = (typeof Audio !== 'undefined') ? new Audio() : null; + + if (!audioTest || typeof audioTest.canPlayType !== 'function') { + return self; + } + + var mpegTest = audioTest.canPlayType('audio/mpeg;').replace(/^no$/, ''); + + // Opera version <33 has mixed MP3 support, so we need to check for and block it. + var checkOpera = self._navigator && self._navigator.userAgent.match(/OPR\/([0-6].)/g); + var isOldOpera = (checkOpera && parseInt(checkOpera[0].split('/')[1], 10) < 33); + + self._codecs = { + mp3: !!(!isOldOpera && (mpegTest || audioTest.canPlayType('audio/mp3;').replace(/^no$/, ''))), + mpeg: !!mpegTest, + opus: !!audioTest.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, ''), + ogg: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''), + oga: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''), + wav: !!audioTest.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''), + aac: !!audioTest.canPlayType('audio/aac;').replace(/^no$/, ''), + caf: !!audioTest.canPlayType('audio/x-caf;').replace(/^no$/, ''), + m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''), + mp4: !!(audioTest.canPlayType('audio/x-mp4;') || audioTest.canPlayType('audio/mp4;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''), + weba: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''), + webm: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''), + dolby: !!audioTest.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/, '') + }; + + return self; + }, + + /** + * Mobile browsers will only allow audio to be played after a user interaction. + * Attempt to automatically unlock audio on the first user interaction. + * Concept from: http://paulbakaus.com/tutorials/html5/web-audio-on-ios/ + * @return {Howler} + */ + _enableMobileAudio: function() { + var self = this || Howler; + + // Only run this on mobile devices if audio isn't already eanbled. + var isMobile = /iPhone|iPad|iPod|Android|BlackBerry|BB10|Silk|Mobi/i.test(self._navigator && self._navigator.userAgent); + var isTouch = !!(('ontouchend' in window) || (self._navigator && self._navigator.maxTouchPoints > 0) || (self._navigator && self._navigator.msMaxTouchPoints > 0)); + if (self._mobileEnabled || !self.ctx || (!isMobile && !isTouch)) { + return; + } + + self._mobileEnabled = false; + + // Some mobile devices/platforms have distortion issues when opening/closing tabs and/or web views. + // Bugs in the browser (especially Mobile Safari) can cause the sampleRate to change from 44100 to 48000. + // By calling Howler.unload(), we create a new AudioContext with the correct sampleRate. + if (!self._mobileUnloaded && self.ctx.sampleRate !== 44100) { + self._mobileUnloaded = true; + self.unload(); + } + + // Scratch buffer for enabling iOS to dispose of web audio buffers correctly, as per: + // http://stackoverflow.com/questions/24119684 + self._scratchBuffer = self.ctx.createBuffer(1, 1, 22050); + + // Call this method on touch start to create and play a buffer, + // then check if the audio actually played to determine if + // audio has now been unlocked on iOS, Android, etc. + var unlock = function() { + // Create an empty buffer. + var source = self.ctx.createBufferSource(); + source.buffer = self._scratchBuffer; + source.connect(self.ctx.destination); + + // Play the empty buffer. + if (typeof source.start === 'undefined') { + source.noteOn(0); + } else { + source.start(0); + } + + // Setup a timeout to check that we are unlocked on the next event loop. + source.onended = function() { + source.disconnect(0); + + // Update the unlocked state and prevent this check from happening again. + self._mobileEnabled = true; + self.mobileAutoEnable = false; + + // Remove the touch start listener. + document.removeEventListener('touchend', unlock, true); + }; + }; + + // Setup a touch start listener to attempt an unlock in. + document.addEventListener('touchend', unlock, true); + + return self; + }, + + /** + * Automatically suspend the Web Audio AudioContext after no sound has played for 30 seconds. + * This saves processing/energy and fixes various browser-specific bugs with audio getting stuck. + * @return {Howler} + */ + _autoSuspend: function() { + var self = this; + + if (!self.autoSuspend || !self.ctx || typeof self.ctx.suspend === 'undefined' || !Howler.usingWebAudio) { + return; + } + + // Check if any sounds are playing. + for (var i=0; i 0 ? sound._seek : self._sprite[sprite][0] / 1000; + var duration = ((self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000) - seek; + var timeout = (duration * 1000) / Math.abs(sound._rate); + + // Update the parameters of the sound + sound._paused = false; + sound._ended = false; + sound._sprite = sprite; + sound._seek = seek; + sound._start = self._sprite[sprite][0] / 1000; + sound._stop = (self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000; + sound._loop = !!(sound._loop || self._sprite[sprite][2]); + + // Begin the actual playback. + var node = sound._node; + if (self._webAudio) { + // Fire this when the sound is ready to play to begin Web Audio playback. + var playWebAudio = function() { + self._refreshBuffer(sound); + + // Setup the playback params. + var vol = (sound._muted || self._muted) ? 0 : sound._volume; + node.gain.setValueAtTime(vol, Howler.ctx.currentTime); + sound._playStart = Howler.ctx.currentTime; + + // Play the sound using the supported method. + if (typeof node.bufferSource.start === 'undefined') { + sound._loop ? node.bufferSource.noteGrainOn(0, seek, 86400) : node.bufferSource.noteGrainOn(0, seek, duration); + } else { + sound._loop ? node.bufferSource.start(0, seek, 86400) : node.bufferSource.start(0, seek, duration); + } + + // Start a new timer if none is present. + if (timeout !== Infinity) { + self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); + } + + if (!internal) { + setTimeout(function() { + self._emit('play', sound._id); + }, 0); + } + }; + + if (self._state === 'loaded') { + playWebAudio(); + } else { + // Wait for the audio to load and then begin playback. + self.once('load', playWebAudio, sound._id); + + // Cancel the end timer. + self._clearTimer(sound._id); + } + } else { + // Fire this when the sound is ready to play to begin HTML5 Audio playback. + var playHtml5 = function() { + node.currentTime = seek; + node.muted = sound._muted || self._muted || Howler._muted || node.muted; + node.volume = sound._volume * Howler.volume(); + node.playbackRate = sound._rate; + + setTimeout(function() { + node.play(); + + // Setup the new end timer. + if (timeout !== Infinity) { + self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); + } + + if (!internal) { + self._emit('play', sound._id); + } + }, 0); + }; + + // Play immediately if ready, or wait for the 'canplaythrough'e vent. + var loadedNoReadyState = (self._state === 'loaded' && (window && window.ejecta || !node.readyState && Howler._navigator.isCocoonJS)); + if (node.readyState === 4 || loadedNoReadyState) { + playHtml5(); + } else { + var listener = function() { + // Begin playback. + playHtml5(); + + // Clear this listener. + node.removeEventListener(Howler._canPlayEvent, listener, false); + }; + node.addEventListener(Howler._canPlayEvent, listener, false); + + // Cancel the end timer. + self._clearTimer(sound._id); + } + } + + return sound._id; + }, + + /** + * Pause playback and save current position. + * @param {Number} id The sound ID (empty to pause all in group). + * @return {Howl} + */ + pause: function(id) { + var self = this; + + // If the sound hasn't loaded, add it to the load queue to pause when capable. + if (self._state !== 'loaded') { + self._queue.push({ + event: 'pause', + action: function() { + self.pause(id); + } + }); + + return self; + } + + // If no id is passed, get all ID's to be paused. + var ids = self._getSoundIds(id); + + for (var i=0; i Returns the group's volume value. + * volume(id) -> Returns the sound id's current volume. + * volume(vol) -> Sets the volume of all sounds in this Howl group. + * volume(vol, id) -> Sets the volume of passed sound id. + * @return {Howl/Number} Returns self or current volume. + */ + volume: function() { + var self = this; + var args = arguments; + var vol, id; + + // Determine the values based on arguments. + if (args.length === 0) { + // Return the value of the groups' volume. + return self._volume; + } else if (args.length === 1) { + // First check if this is an ID, and if not, assume it is a new volume. + var ids = self._getSoundIds(); + var index = ids.indexOf(args[0]); + if (index >= 0) { + id = parseInt(args[0], 10); + } else { + vol = parseFloat(args[0]); + } + } else if (args.length >= 2) { + vol = parseFloat(args[0]); + id = parseInt(args[1], 10); + } + + // Update the volume or return the current volume. + var sound; + if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) { + // If the sound hasn't loaded, add it to the load queue to change volume when capable. + if (self._state !== 'loaded') { + self._queue.push({ + event: 'volume', + action: function() { + self.volume.apply(self, args); + } + }); + + return self; + } + + // Set the group volume. + if (typeof id === 'undefined') { + self._volume = vol; + } + + // Update one or all volumes. + id = self._getSoundIds(id); + for (var i=0; i to ? 'out' : 'in'; + var steps = diff / 0.01; + var stepLen = len / steps; + + // If the sound hasn't loaded, add it to the load queue to fade when capable. + if (self._state !== 'loaded') { + self._queue.push({ + event: 'fade', + action: function() { + self.fade(from, to, len, id); + } + }); + + return self; + } + + // Set the volume to the start position. + self.volume(from, id); + + // Fade the volume of one or all sounds. + var ids = self._getSoundIds(id); + for (var i=0; i Returns the group's loop value. + * loop(id) -> Returns the sound id's loop value. + * loop(loop) -> Sets the loop value for all sounds in this Howl group. + * loop(loop, id) -> Sets the loop value of passed sound id. + * @return {Howl/Boolean} Returns self or current loop value. + */ + loop: function() { + var self = this; + var args = arguments; + var loop, id, sound; + + // Determine the values for loop and id. + if (args.length === 0) { + // Return the grou's loop value. + return self._loop; + } else if (args.length === 1) { + if (typeof args[0] === 'boolean') { + loop = args[0]; + self._loop = loop; + } else { + // Return this sound's loop value. + sound = self._soundById(parseInt(args[0], 10)); + return sound ? sound._loop : false; + } + } else if (args.length === 2) { + loop = args[0]; + id = parseInt(args[1], 10); + } + + // If no id is passed, get all ID's to be looped. + var ids = self._getSoundIds(id); + for (var i=0; i Returns the first sound node's current playback rate. + * rate(id) -> Returns the sound id's current playback rate. + * rate(rate) -> Sets the playback rate of all sounds in this Howl group. + * rate(rate, id) -> Sets the playback rate of passed sound id. + * @return {Howl/Number} Returns self or the current playback rate. + */ + rate: function() { + var self = this; + var args = arguments; + var rate, id; + + // Determine the values based on arguments. + if (args.length === 0) { + // We will simply return the current rate of the first node. + id = self._sounds[0]._id; + } else if (args.length === 1) { + // First check if this is an ID, and if not, assume it is a new rate value. + var ids = self._getSoundIds(); + var index = ids.indexOf(args[0]); + if (index >= 0) { + id = parseInt(args[0], 10); + } else { + rate = parseFloat(args[0]); + } + } else if (args.length === 2) { + rate = parseFloat(args[0]); + id = parseInt(args[1], 10); + } + + // Update the playback rate or return the current value. + var sound; + if (typeof rate === 'number') { + // If the sound hasn't loaded, add it to the load queue to change playback rate when capable. + if (self._state !== 'loaded') { + self._queue.push({ + event: 'rate', + action: function() { + self.rate.apply(self, args); + } + }); + + return self; + } + + // Set the group rate. + if (typeof id === 'undefined') { + self._rate = rate; + } + + // Update one or all volumes. + id = self._getSoundIds(id); + for (var i=0; i Returns the first sound node's current seek position. + * seek(id) -> Returns the sound id's current seek position. + * seek(seek) -> Sets the seek position of the first sound node. + * seek(seek, id) -> Sets the seek position of passed sound id. + * @return {Howl/Number} Returns self or the current seek position. + */ + seek: function() { + var self = this; + var args = arguments; + var seek, id; + + // Determine the values based on arguments. + if (args.length === 0) { + // We will simply return the current position of the first node. + id = self._sounds[0]._id; + } else if (args.length === 1) { + // First check if this is an ID, and if not, assume it is a new seek position. + var ids = self._getSoundIds(); + var index = ids.indexOf(args[0]); + if (index >= 0) { + id = parseInt(args[0], 10); + } else { + id = self._sounds[0]._id; + seek = parseFloat(args[0]); + } + } else if (args.length === 2) { + seek = parseFloat(args[0]); + id = parseInt(args[1], 10); + } + + // If there is no ID, bail out. + if (typeof id === 'undefined') { + return self; + } + + // If the sound hasn't loaded, add it to the load queue to seek when capable. + if (self._state !== 'loaded') { + self._queue.push({ + event: 'seek', + action: function() { + self.seek.apply(self, args); + } + }); + + return self; + } + + // Get the sound. + var sound = self._soundById(id); + + if (sound) { + if (typeof seek === 'number' && seek >= 0) { + // Pause the sound and update position for restarting playback. + var playing = self.playing(id); + if (playing) { + self.pause(id, true); + } + + // Move the position of the track and cancel timer. + sound._seek = seek; + sound._ended = false; + self._clearTimer(id); + + // Restart the playback if the sound was playing. + if (playing) { + self.play(id, true); + } + + // Update the seek position for HTML5 Audio. + if (!self._webAudio && sound._node) { + sound._node.currentTime = seek; + } + + self._emit('seek', id); + } else { + if (self._webAudio) { + var realTime = self.playing(id) ? Howler.ctx.currentTime - sound._playStart : 0; + var rateSeek = sound._rateSeek ? sound._rateSeek - sound._seek : 0; + return sound._seek + (rateSeek + realTime * Math.abs(sound._rate)); + } else { + return sound._node.currentTime; + } + } + } + + return self; + }, + + /** + * Check if a specific sound is currently playing or not (if id is provided), or check if at least one of the sounds in the group is playing or not. + * @param {Number} id The sound id to check. If none is passed, the whole sound group is checked. + * @return {Boolean} True if playing and false if not. + */ + playing: function(id) { + var self = this; + + // Check the passed sound ID (if any). + if (typeof id === 'number') { + var sound = self._soundById(id); + return sound ? !sound._paused : false; + } + + // Otherwise, loop through all sounds and check if any are playing. + for (var i=0; i= 0) { + Howler._howls.splice(index, 1); + } + } + + // Delete this sound from the cache (if no other Howl is using it). + var remCache = true; + for (i=0; i=0; i--) { + if (!events[i].id || events[i].id === id || event === 'load') { + setTimeout(function(fn) { + fn.call(this, id, msg); + }.bind(self, events[i].fn), 0); + + // If this event was setup with `once`, remove it. + if (events[i].once) { + self.off(event, events[i].fn, events[i].id); + } + } + } + + return self; + }, + + /** + * Queue of actions initiated before the sound has loaded. + * These will be called in sequence, with the next only firing + * after the previous has finished executing (even if async like play). + * @return {Howl} + */ + _loadQueue: function() { + var self = this; + + if (self._queue.length > 0) { + var task = self._queue[0]; + + // don't move onto the next task until this one is done + self.once(task.event, function() { + self._queue.shift(); + self._loadQueue(); + }); + + task.action(); + } + + return self; + }, + + /** + * Fired when playback ends at the end of the duration. + * @param {Sound} sound The sound object to work with. + * @return {Howl} + */ + _ended: function(sound) { + var self = this; + var sprite = sound._sprite; + + // Should this sound loop? + var loop = !!(sound._loop || self._sprite[sprite][2]); + + // Fire the ended event. + self._emit('end', sound._id); + + // Restart the playback for HTML5 Audio loop. + if (!self._webAudio && loop) { + self.stop(sound._id, true).play(sound._id); + } + + // Restart this timer if on a Web Audio loop. + if (self._webAudio && loop) { + self._emit('play', sound._id); + sound._seek = sound._start || 0; + sound._rateSeek = 0; + sound._playStart = Howler.ctx.currentTime; + + var timeout = ((sound._stop - sound._start) * 1000) / Math.abs(sound._rate); + self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); + } + + // Mark the node as paused. + if (self._webAudio && !loop) { + sound._paused = true; + sound._ended = true; + sound._seek = sound._start || 0; + sound._rateSeek = 0; + self._clearTimer(sound._id); + + // Clean up the buffer source. + self._cleanBuffer(sound._node); + + // Attempt to auto-suspend AudioContext if no sounds are still playing. + Howler._autoSuspend(); + } + + // When using a sprite, end the track. + if (!self._webAudio && !loop) { + self.stop(sound._id); + } + + return self; + }, + + /** + * Clear the end timer for a sound playback. + * @param {Number} id The sound ID. + * @return {Howl} + */ + _clearTimer: function(id) { + var self = this; + + if (self._endTimers[id]) { + clearTimeout(self._endTimers[id]); + delete self._endTimers[id]; + } + + return self; + }, + + /** + * Return the sound identified by this ID, or return null. + * @param {Number} id Sound ID + * @return {Object} Sound object or null. + */ + _soundById: function(id) { + var self = this; + + // Loop through all sounds and find the one with this ID. + for (var i=0; i=0; i--) { + if (cnt <= limit) { + return; + } + + if (self._sounds[i]._ended) { + // Disconnect the audio source when using Web Audio. + if (self._webAudio && self._sounds[i]._node) { + self._sounds[i]._node.disconnect(0); + } + + // Remove sounds until we have the pool size. + self._sounds.splice(i, 1); + cnt--; + } + } + }, + + /** + * Get all ID's from the sounds pool. + * @param {Number} id Only return one ID if one is passed. + * @return {Array} Array of IDs. + */ + _getSoundIds: function(id) { + var self = this; + + if (typeof id === 'undefined') { + var ids = []; + for (var i=0; i 0) { + cache[self._src] = buffer; + loadSound(self, buffer); + } + }, function() { + self._emit('loaderror', null, 'Decoding audio data failed.'); + }); + }; + + /** + * Sound is now loaded, so finish setting everything up and fire the loaded event. + * @param {Howl} self + * @param {Object} buffer The decoded buffer sound source. + */ + var loadSound = function(self, buffer) { + // Set the duration. + if (buffer && !self._duration) { + self._duration = buffer.duration; + } + + // Setup a sprite if none is defined. + if (Object.keys(self._sprite).length === 0) { + self._sprite = {__default: [0, self._duration * 1000]}; + } + + // Fire the loaded event. + if (self._state !== 'loaded') { + self._state = 'loaded'; + self._emit('load'); + self._loadQueue(); + } + + // Begin playback if specified. + if (self._autoplay) { + self.play(); + } + }; + + /** + * Setup the audio context when available, or switch to HTML5 Audio mode. + */ + var setupAudioContext = function() { + Howler.noAudio = false; + + // Check if we are using Web Audio and setup the AudioContext if we are. + try { + if (typeof AudioContext !== 'undefined') { + Howler.ctx = new AudioContext(); + } else if (typeof webkitAudioContext !== 'undefined') { + Howler.ctx = new webkitAudioContext(); + } else { + Howler.usingWebAudio = false; + } + } catch(e) { + Howler.usingWebAudio = false; + } + + if (!Howler.usingWebAudio) { + // No audio is available on this system if noAudio is set to true. + if (typeof Audio !== 'undefined') { + try { + var test = new Audio(); + + // Check if the canplaythrough event is available. + if (typeof test.oncanplaythrough === 'undefined') { + Howler._canPlayEvent = 'canplay'; + } + } catch(e) { + Howler.noAudio = true; + } + } else { + Howler.noAudio = true; + } + } + + // Test to make sure audio isn't disabled in Internet Explorer + try { + var test = new Audio(); + if (test.muted) { + Howler.noAudio = true; + } + } catch (e) {} + + // Check if a webview is being used on iOS8 or earlier (rather than the browser). + // If it is, disable Web Audio as it causes crashing. + var iOS = (/iP(hone|od|ad)/.test(Howler._navigator && Howler._navigator.platform)); + var appVersion = Howler._navigator && Howler._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/); + var version = appVersion ? parseInt(appVersion[1], 10) : null; + if (iOS && version && version < 9) { + var safari = /safari/.test(Howler._navigator && Howler._navigator.userAgent.toLowerCase()); + if (Howler._navigator && Howler._navigator.standalone && !safari || Howler._navigator && !Howler._navigator.standalone && !safari) { + Howler.usingWebAudio = false; + } + } + + // Create and expose the master GainNode when using Web Audio (useful for plugins or advanced usage). + if (Howler.usingWebAudio) { + Howler.masterGain = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain(); + Howler.masterGain.gain.value = 1; + Howler.masterGain.connect(Howler.ctx.destination); + } + + // Re-run the setup on Howler. + Howler._setup(); + }; + + // Add support for AMD (Asynchronous Module Definition) libraries such as require.js. + if (typeof define === 'function' && define.amd) { + define([], function() { + return { + Howler: Howler, + Howl: Howl + }; + }); + } + + // Add support for CommonJS libraries such as browserify. + if (typeof exports !== 'undefined') { + exports.Howler = Howler; + exports.Howl = Howl; + } + + // Define globally in case AMD is not available or unused. + if (typeof window !== 'undefined') { + window.HowlerGlobal = HowlerGlobal; + window.Howler = Howler; + window.Howl = Howl; + window.Sound = Sound; + } else if (typeof global !== 'undefined') { // Add to global in Node.js (for testing, etc). + global.HowlerGlobal = HowlerGlobal; + global.Howler = Howler; + global.Howl = Howl; + global.Sound = Sound; + } +})(); + + +/*! + * Spatial Plugin - Adds support for stereo and 3D audio where Web Audio is supported. + * + * howler.js v2.0.0 + * howlerjs.com + * + * (c) 2013-2016, James Simpson of GoldFire Studios + * goldfirestudios.com + * + * MIT License + */ + +(function() { + + 'use strict'; + + // Setup default properties. + HowlerGlobal.prototype._pos = [0, 0, 0]; + HowlerGlobal.prototype._orientation = [0, 0, -1, 0, 1, 0]; + + /** Global Methods **/ + /***************************************************************************/ + + /** + * Helper method to update the stereo panning position of all current Howls. + * Future Howls will not use this value unless explicitely set. + * @param {Number} pan A value of -1.0 is all the way left and 1.0 is all the way right. + * @return {Howler/Number} Self or current stereo panning value. + */ + HowlerGlobal.prototype.stereo = function(pan) { + var self = this; + + // Stop right here if not using Web Audio. + if (!self.ctx || !self.ctx.listener) { + return self; + } + + // Loop through all Howls and update their stereo panning. + for (var i=self._howls.length-1; i>=0; i--) { + self._howls[i].stereo(pan); + } + + return self; + }; + + /** + * Get/set the position of the listener in 3D cartesian space. Sounds using + * 3D position will be relative to the listener's position. + * @param {Number} x The x-position of the listener. + * @param {Number} y The y-position of the listener. + * @param {Number} z The z-position of the listener. + * @return {Howler/Array} Self or current listener position. + */ + HowlerGlobal.prototype.pos = function(x, y, z) { + var self = this; + + // Stop right here if not using Web Audio. + if (!self.ctx || !self.ctx.listener) { + return self; + } + + // Set the defaults for optional 'y' & 'z'. + y = (typeof y !== 'number') ? self._pos[1] : y; + z = (typeof z !== 'number') ? self._pos[2] : z; + + if (typeof x === 'number') { + self._pos = [x, y, z]; + self.ctx.listener.setPosition(self._pos[0], self._pos[1], self._pos[2]); + } else { + return self._pos; + } + + return self; + }; + + /** + * Get/set the direction the listener is pointing in the 3D cartesian space. + * A front and up vector must be provided. The front is the direction the + * face of the listener is pointing, and up is the direction the top of the + * listener is pointing. Thus, these values are expected to be at right angles + * from each other. + * @param {Number} x The x-orientation of the listener. + * @param {Number} y The y-orientation of the listener. + * @param {Number} z The z-orientation of the listener. + * @param {Number} xUp The x-orientation of the top of the listener. + * @param {Number} yUp The y-orientation of the top of the listener. + * @param {Number} zUp The z-orientation of the top of the listener. + * @return {Howler/Array} Returns self or the current orientation vectors. + */ + HowlerGlobal.prototype.orientation = function(x, y, z, xUp, yUp, zUp) { + var self = this; + + // Stop right here if not using Web Audio. + if (!self.ctx || !self.ctx.listener) { + return self; + } + + // Set the defaults for optional 'y' & 'z'. + var or = self._orientation; + y = (typeof y !== 'number') ? or[1] : y; + z = (typeof z !== 'number') ? or[2] : z; + xUp = (typeof xUp !== 'number') ? or[3] : xUp; + yUp = (typeof yUp !== 'number') ? or[4] : yUp; + zUp = (typeof zUp !== 'number') ? or[5] : zUp; + + if (typeof x === 'number') { + self._orientation = [x, y, z, xUp, yUp, zUp]; + self.ctx.listener.setOrientation(x, y, z, xUp, yUp, zUp); + } else { + return or; + } + + return self; + }; + + /** Group Methods **/ + /***************************************************************************/ + + /** + * Add new properties to the core init. + * @param {Function} _super Core init method. + * @return {Howl} + */ + Howl.prototype.init = (function(_super) { + return function(o) { + var self = this; + + // Setup user-defined default properties. + self._orientation = o.orientation || [1, 0, 0]; + self._stereo = o.stereo || null; + self._pos = o.pos || null; + self._pannerAttr = { + coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : 360, + coneOuterAngle: typeof o.coneOuterAngle !== 'undefined' ? o.coneOuterAngle : 360, + coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : 0, + distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : 'inverse', + maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : 10000, + panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : 'HRTF', + refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : 1, + rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : 1 + }; + + // Setup event listeners. + self._onstereo = o.onstereo ? [{fn: o.onstereo}] : []; + self._onpos = o.onpos ? [{fn: o.onpos}] : []; + self._onorientation = o.onorientation ? [{fn: o.onorientation}] : []; + + // Complete initilization with howler.js core's init function. + return _super.call(this, o); + }; + })(Howl.prototype.init); + + /** + * Get/set the stereo panning of the audio source for this sound or all in the group. + * @param {Number} pan A value of -1.0 is all the way left and 1.0 is all the way right. + * @param {Number} id (optional) The sound ID. If none is passed, all in group will be updated. + * @return {Howl/Number} Returns self or the current stereo panning value. + */ + Howl.prototype.stereo = function(pan, id) { + var self = this; + + // Stop right here if not using Web Audio. + if (!self._webAudio) { + return self; + } + + // If the sound hasn't loaded, add it to the load queue to change stereo pan when capable. + if (self._state !== 'loaded') { + self._queue.push({ + event: 'stereo', + action: function() { + self.stereo(pan, id); + } + }); + + return self; + } + + // Check for PannerStereoNode support and fallback to PannerNode if it doesn't exist. + var pannerType = (typeof Howler.ctx.createStereoPanner === 'undefined') ? 'spatial' : 'stereo'; + + // Setup the group's stereo panning if no ID is passed. + if (typeof id === 'undefined') { + // Return the group's stereo panning if no parameters are passed. + if (typeof pan === 'number') { + self._stereo = pan; + self._pos = [pan, 0, 0]; + } else { + return self._stereo; + } + } + + // Change the streo panning of one or all sounds in group. + var ids = self._getSoundIds(id); + for (var i=0; i Returns the group's values. + * pannerAttr(id) -> Returns the sound id's values. + * pannerAttr(o) -> Set's the values of all sounds in this Howl group. + * pannerAttr(o, id) -> Set's the values of passed sound id. + * + * Attributes: + * coneInnerAngle - (360 by default) There will be no volume reduction inside this angle. + * coneOuterAngle - (360 by default) The volume will be reduced to a constant value of + * `coneOuterGain` outside this angle. + * coneOuterGain - (0 by default) The amount of volume reduction outside of `coneOuterAngle`. + * distanceModel - ('inverse' by default) Determines algorithm to use to reduce volume as audio moves + * away from listener. Can be `linear`, `inverse` or `exponential`. + * maxDistance - (10000 by default) Volume won't reduce between source/listener beyond this distance. + * panningModel - ('HRTF' by default) Determines which spatialization algorithm is used to position audio. + * Can be `HRTF` or `equalpower`. + * refDistance - (1 by default) A reference distance for reducing volume as the source + * moves away from the listener. + * rolloffFactor - (1 by default) How quickly the volume reduces as source moves from listener. + * + * @return {Howl/Object} Returns self or current panner attributes. + */ + Howl.prototype.pannerAttr = function() { + var self = this; + var args = arguments; + var o, id, sound; + + // Stop right here if not using Web Audio. + if (!self._webAudio) { + return self; + } + + // Determine the values based on arguments. + if (args.length === 0) { + // Return the group's panner attribute values. + return self._pannerAttr; + } else if (args.length === 1) { + if (typeof args[0] === 'object') { + o = args[0]; + + // Set the grou's panner attribute values. + if (typeof id === 'undefined') { + self._pannerAttr = { + coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : self._coneInnerAngle, + coneOuterAngle: typeof o.coneOuterAngle !== 'undefined' ? o.coneOuterAngle : self._coneOuterAngle, + coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : self._coneOuterGain, + distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : self._distanceModel, + maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : self._maxDistance, + panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : self._panningModel, + refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : self._refDistance, + rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : self._rolloffFactor + }; + } + } else { + // Return this sound's panner attribute values. + sound = self._soundById(parseInt(args[0], 10)); + return sound ? sound._pannerAttr : self._pannerAttr; + } + } else if (args.length === 2) { + o = args[0]; + id = parseInt(args[1], 10); + } + + // Update the values of the specified sounds. + var ids = self._getSoundIds(id); + for (var i=0; i=0&&e<=1){if(o._volume=e,o._muted)return o;o.usingWebAudio&&(o.masterGain.gain.value=e);for(var t=0;t=0;o--)e._howls[o].unload();return e.usingWebAudio&&"undefined"!=typeof e.ctx.close&&(e.ctx.close(),e.ctx=null,_()),e},codecs:function(e){return(this||n)._codecs[e]},_setup:function(){var e=this||n;return e.state=e.ctx?e.ctx.state||"running":"running",e._autoSuspend(),e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||n,o="undefined"!=typeof Audio?new Audio:null;if(!o||"function"!=typeof o.canPlayType)return e;var t=o.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator&&e._navigator.userAgent.match(/OPR\/([0-6].)/g),u=r&&parseInt(r[0].split("/")[1],10)<33;return e._codecs={mp3:!(u||!t&&!o.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!t,opus:!!o.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!o.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!o.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!o.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),aac:!!o.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!o.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(o.canPlayType("audio/x-m4a;")||o.canPlayType("audio/m4a;")||o.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(o.canPlayType("audio/x-mp4;")||o.canPlayType("audio/mp4;")||o.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!!o.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,""),webm:!!o.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,""),dolby:!!o.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,"")},e},_enableMobileAudio:function(){var e=this||n,o=/iPhone|iPad|iPod|Android|BlackBerry|BB10|Silk|Mobi/i.test(e._navigator&&e._navigator.userAgent),t=!!("ontouchend"in window||e._navigator&&e._navigator.maxTouchPoints>0||e._navigator&&e._navigator.msMaxTouchPoints>0);if(!e._mobileEnabled&&e.ctx&&(o||t)){e._mobileEnabled=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var r=function(){var n=e.ctx.createBufferSource();n.buffer=e._scratchBuffer,n.connect(e.ctx.destination),"undefined"==typeof n.start?n.noteOn(0):n.start(0),n.onended=function(){n.disconnect(0),e._mobileEnabled=!0,e.mobileAutoEnable=!1,document.removeEventListener("touchend",r,!0)}};return document.addEventListener("touchend",r,!0),e}},_autoSuspend:function(){var e=this;if(e.autoSuspend&&e.ctx&&"undefined"!=typeof e.ctx.suspend&&n.usingWebAudio){for(var o=0;o0?d._seek:t._sprite[e][0]/1e3,_=(t._sprite[e][0]+t._sprite[e][1])/1e3-i,s=1e3*_/Math.abs(d._rate);d._paused=!1,d._ended=!1,d._sprite=e,d._seek=i,d._start=t._sprite[e][0]/1e3,d._stop=(t._sprite[e][0]+t._sprite[e][1])/1e3,d._loop=!(!d._loop&&!t._sprite[e][2]);var l=d._node;if(t._webAudio){var f=function(){t._refreshBuffer(d);var e=d._muted||t._muted?0:d._volume;l.gain.setValueAtTime(e,n.ctx.currentTime),d._playStart=n.ctx.currentTime,"undefined"==typeof l.bufferSource.start?d._loop?l.bufferSource.noteGrainOn(0,i,86400):l.bufferSource.noteGrainOn(0,i,_):d._loop?l.bufferSource.start(0,i,86400):l.bufferSource.start(0,i,_),s!==1/0&&(t._endTimers[d._id]=setTimeout(t._ended.bind(t,d),s)),o||setTimeout(function(){t._emit("play",d._id)},0)};"loaded"===t._state?f():(t.once("load",f,d._id),t._clearTimer(d._id))}else{var c=function(){l.currentTime=i,l.muted=d._muted||t._muted||n._muted||l.muted,l.volume=d._volume*n.volume(),l.playbackRate=d._rate,setTimeout(function(){l.play(),s!==1/0&&(t._endTimers[d._id]=setTimeout(t._ended.bind(t,d),s)),o||t._emit("play",d._id)},0)},p="loaded"===t._state&&(window&&window.ejecta||!l.readyState&&n._navigator.isCocoonJS);if(4===l.readyState||p)c();else{var m=function(){c(),l.removeEventListener(n._canPlayEvent,m,!1)};l.addEventListener(n._canPlayEvent,m,!1),t._clearTimer(d._id)}}return d._id},pause:function(e){var n=this;if("loaded"!==n._state)return n._queue.push({event:"pause",action:function(){n.pause(e)}}),n;for(var o=n._getSoundIds(e),t=0;t=0?o=parseInt(r[0],10):e=parseFloat(r[0])}else r.length>=2&&(e=parseFloat(r[0]),o=parseInt(r[1],10));var d;if(!("undefined"!=typeof e&&e>=0&&e<=1))return d=o?t._soundById(o):t._sounds[0],d?d._volume:0;if("loaded"!==t._state)return t._queue.push({event:"volume",action:function(){t.volume.apply(t,r)}}),t;"undefined"==typeof o&&(t._volume=e),o=t._getSoundIds(o);for(var i=0;io?"out":"in",i=a/.01,_=t/i;if("loaded"!==u._state)return u._queue.push({event:"fade",action:function(){u.fade(e,o,t,r)}}),u;u.volume(e,r);for(var s=u._getSoundIds(r),l=0;l=0?o=parseInt(r[0],10):e=parseFloat(r[0])}else 2===r.length&&(e=parseFloat(r[0]),o=parseInt(r[1],10));var d;if("number"!=typeof e)return d=t._soundById(o),d?d._rate:t._rate;if("loaded"!==t._state)return t._queue.push({event:"rate",action:function(){t.rate.apply(t,r)}}),t;"undefined"==typeof o&&(t._rate=e),o=t._getSoundIds(o);for(var i=0;i=0?o=parseInt(r[0],10):(o=t._sounds[0]._id,e=parseFloat(r[0]))}else 2===r.length&&(e=parseFloat(r[0]),o=parseInt(r[1],10));if("undefined"==typeof o)return t;if("loaded"!==t._state)return t._queue.push({event:"seek",action:function(){t.seek.apply(t,r)}}),t;var d=t._soundById(o);if(d){if(!("number"==typeof e&&e>=0)){if(t._webAudio){var i=t.playing(o)?n.ctx.currentTime-d._playStart:0,_=d._rateSeek?d._rateSeek-d._seek:0;return d._seek+(_+i*Math.abs(d._rate))}return d._node.currentTime}var s=t.playing(o);s&&t.pause(o,!0),d._seek=e,d._ended=!1,t._clearTimer(o),s&&t.play(o,!0),!t._webAudio&&d._node&&(d._node.currentTime=e),t._emit("seek",o)}return t},playing:function(e){var n=this;if("number"==typeof e){var o=n._soundById(e);return!!o&&!o._paused}for(var t=0;t=0&&n._howls.splice(u,1)}var a=!0;for(t=0;t=0;u--)r[u].id&&r[u].id!==n&&"load"!==e||(setTimeout(function(e){e.call(this,n,o)}.bind(t,r[u].fn),0),r[u].once&&t.off(e,r[u].fn,r[u].id));return t},_loadQueue:function(){var e=this;if(e._queue.length>0){var n=e._queue[0];e.once(n.event,function(){e._queue.shift(),e._loadQueue()}),n.action()}return e},_ended:function(e){var o=this,t=e._sprite,r=!(!e._loop&&!o._sprite[t][2]);if(o._emit("end",e._id),!o._webAudio&&r&&o.stop(e._id,!0).play(e._id),o._webAudio&&r){o._emit("play",e._id),e._seek=e._start||0,e._rateSeek=0,e._playStart=n.ctx.currentTime;var u=1e3*(e._stop-e._start)/Math.abs(e._rate);o._endTimers[e._id]=setTimeout(o._ended.bind(o,e),u)}return o._webAudio&&!r&&(e._paused=!0,e._ended=!0,e._seek=e._start||0,e._rateSeek=0,o._clearTimer(e._id),o._cleanBuffer(e._node),n._autoSuspend()),o._webAudio||r||o.stop(e._id),o},_clearTimer:function(e){var n=this;return n._endTimers[e]&&(clearTimeout(n._endTimers[e]),delete n._endTimers[e]),n},_soundById:function(e){for(var n=this,o=0;o=0;t--){if(o<=n)return;e._sounds[t]._ended&&(e._webAudio&&e._sounds[t]._node&&e._sounds[t]._node.disconnect(0),e._sounds.splice(t,1),o--)}}},_getSoundIds:function(e){var n=this;if("undefined"==typeof e){for(var o=[],t=0;t0&&(r[o._src]=e,i(o,e))},function(){o._emit("loaderror",null,"Decoding audio data failed.")})},i=function(e,n){n&&!e._duration&&(e._duration=n.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue()),e._autoplay&&e.play()},_=function(){n.noAudio=!1;try{"undefined"!=typeof AudioContext?n.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?n.ctx=new webkitAudioContext:n.usingWebAudio=!1}catch(e){n.usingWebAudio=!1}if(!n.usingWebAudio)if("undefined"!=typeof Audio)try{var e=new Audio;"undefined"==typeof e.oncanplaythrough&&(n._canPlayEvent="canplay")}catch(e){n.noAudio=!0}else n.noAudio=!0;try{var e=new Audio;e.muted&&(n.noAudio=!0)}catch(e){}var o=/iP(hone|od|ad)/.test(n._navigator&&n._navigator.platform),t=n._navigator&&n._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),r=t?parseInt(t[1],10):null;if(o&&r&&r<9){var u=/safari/.test(n._navigator&&n._navigator.userAgent.toLowerCase());(n._navigator&&n._navigator.standalone&&!u||n._navigator&&!n._navigator.standalone&&!u)&&(n.usingWebAudio=!1)}n.usingWebAudio&&(n.masterGain="undefined"==typeof n.ctx.createGain?n.ctx.createGainNode():n.ctx.createGain(),n.masterGain.gain.value=1,n.masterGain.connect(n.ctx.destination)),n._setup()};"function"==typeof define&&define.amd&&define([],function(){return{Howler:n,Howl:o}}),"undefined"!=typeof exports&&(exports.Howler=n,exports.Howl=o),"undefined"!=typeof window?(window.HowlerGlobal=e,window.Howler=n,window.Howl=o,window.Sound=t):"undefined"!=typeof global&&(global.HowlerGlobal=e,global.Howler=n,global.Howl=o,global.Sound=t)}(); +/*! Spatial Plugin */ +!function(){"use strict";HowlerGlobal.prototype._pos=[0,0,0],HowlerGlobal.prototype._orientation=[0,0,-1,0,1,0],HowlerGlobal.prototype.stereo=function(e){var n=this;if(!n.ctx||!n.ctx.listener)return n;for(var t=n._howls.length-1;t>=0;t--)n._howls[t].stereo(e);return n},HowlerGlobal.prototype.pos=function(e,n,t){var o=this;return o.ctx&&o.ctx.listener?(n="number"!=typeof n?o._pos[1]:n,t="number"!=typeof t?o._pos[2]:t,"number"!=typeof e?o._pos:(o._pos=[e,n,t],o.ctx.listener.setPosition(o._pos[0],o._pos[1],o._pos[2]),o)):o},HowlerGlobal.prototype.orientation=function(e,n,t,o,r,i){var a=this;if(!a.ctx||!a.ctx.listener)return a;var p=a._orientation;return n="number"!=typeof n?p[1]:n,t="number"!=typeof t?p[2]:t,o="number"!=typeof o?p[3]:o,r="number"!=typeof r?p[4]:r,i="number"!=typeof i?p[5]:i,"number"!=typeof e?p:(a._orientation=[e,n,t,o,r,i],a.ctx.listener.setOrientation(e,n,t,o,r,i),a)},Howl.prototype.init=function(e){return function(n){var t=this;return t._orientation=n.orientation||[1,0,0],t._stereo=n.stereo||null,t._pos=n.pos||null,t._pannerAttr={coneInnerAngle:"undefined"!=typeof n.coneInnerAngle?n.coneInnerAngle:360,coneOuterAngle:"undefined"!=typeof n.coneOuterAngle?n.coneOuterAngle:360,coneOuterGain:"undefined"!=typeof n.coneOuterGain?n.coneOuterGain:0,distanceModel:"undefined"!=typeof n.distanceModel?n.distanceModel:"inverse",maxDistance:"undefined"!=typeof n.maxDistance?n.maxDistance:1e4,panningModel:"undefined"!=typeof n.panningModel?n.panningModel:"HRTF",refDistance:"undefined"!=typeof n.refDistance?n.refDistance:1,rolloffFactor:"undefined"!=typeof n.rolloffFactor?n.rolloffFactor:1},t._onstereo=n.onstereo?[{fn:n.onstereo}]:[],t._onpos=n.onpos?[{fn:n.onpos}]:[],t._onorientation=n.onorientation?[{fn:n.onorientation}]:[],e.call(this,n)}}(Howl.prototype.init),Howl.prototype.stereo=function(n,t){var o=this;if(!o._webAudio)return o;if("loaded"!==o._state)return o._queue.push({event:"stereo",action:function(){o.stereo(n,t)}}),o;var r="undefined"==typeof Howler.ctx.createStereoPanner?"spatial":"stereo";if("undefined"==typeof t){if("number"!=typeof n)return o._stereo;o._stereo=n,o._pos=[n,0,0]}for(var i=o._getSoundIds(t),a=0;a=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,n.ctx.currentTime);for(var o=0;o=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,_()),e},codecs:function(e){return(this||n)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||n;if(e.state=e.ctx?e.ctx.state||"running":"running",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{var t=new Audio;void 0===t.oncanplaythrough&&(e._canPlayEvent="canplay")}catch(n){e.noAudio=!0}else e.noAudio=!0;try{var t=new Audio;t.muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||n,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(n){return e}if(!t||"function"!=typeof t.canPlayType)return e;var o=t.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator&&e._navigator.userAgent.match(/OPR\/([0-6].)/g),a=r&&parseInt(r[0].split("/")[1],10)<33;return e._codecs={mp3:!(a||!o&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!o,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!t.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,""),webm:!!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,""),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_enableMobileAudio:function(){var e=this||n,t=/iPhone|iPad|iPod|Android|BlackBerry|BB10|Silk|Mobi/i.test(e._navigator&&e._navigator.userAgent),o=!!("ontouchend"in window||e._navigator&&e._navigator.maxTouchPoints>0||e._navigator&&e._navigator.msMaxTouchPoints>0);if(!e._mobileEnabled&&e.ctx&&(t||o)){e._mobileEnabled=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var r=function(){n._autoResume();var t=e.ctx.createBufferSource();t.buffer=e._scratchBuffer,t.connect(e.ctx.destination),void 0===t.start?t.noteOn(0):t.start(0),"function"==typeof e.ctx.resume&&e.ctx.resume(),t.onended=function(){t.disconnect(0),e._mobileEnabled=!0,e.mobileAutoEnable=!1,document.removeEventListener("touchstart",r,!0),document.removeEventListener("touchend",r,!0)}};return document.addEventListener("touchstart",r,!0),document.addEventListener("touchend",r,!0),e}},_autoSuspend:function(){var e=this;if(e.autoSuspend&&e.ctx&&void 0!==e.ctx.suspend&&n.usingWebAudio){for(var t=0;t0?i._seek:o._sprite[e][0]/1e3),s=Math.max(0,(o._sprite[e][0]+o._sprite[e][1])/1e3-_),l=1e3*s/Math.abs(i._rate);i._paused=!1,i._ended=!1,i._sprite=e,i._seek=_,i._start=o._sprite[e][0]/1e3,i._stop=(o._sprite[e][0]+o._sprite[e][1])/1e3,i._loop=!(!i._loop&&!o._sprite[e][2]);var c=i._node;if(o._webAudio){var f=function(){o._refreshBuffer(i);var e=i._muted||o._muted?0:i._volume;c.gain.setValueAtTime(e,n.ctx.currentTime),i._playStart=n.ctx.currentTime,void 0===c.bufferSource.start?i._loop?c.bufferSource.noteGrainOn(0,_,86400):c.bufferSource.noteGrainOn(0,_,s):i._loop?c.bufferSource.start(0,_,86400):c.bufferSource.start(0,_,s),l!==1/0&&(o._endTimers[i._id]=setTimeout(o._ended.bind(o,i),l)),t||setTimeout(function(){o._emit("play",i._id)},0)};"running"===n.state?f():(o.once("resume",f),o._clearTimer(i._id))}else{var p=function(){c.currentTime=_,c.muted=i._muted||o._muted||n._muted||c.muted,c.volume=i._volume*n.volume(),c.playbackRate=i._rate;try{var r=c.play();if("undefined"!=typeof Promise&&r instanceof Promise){o._playLock=!0;var a=function(){o._playLock=!1,t||o._emit("play",i._id)};r.then(a,a)}else t||o._emit("play",i._id);if(c.playbackRate=i._rate,c.paused)return void o._emit("playerror",i._id,"Playback was unable to start. This is most commonly an issue on mobile devices where playback was not within a user interaction.");"__default"!==e||i._loop?o._endTimers[i._id]=setTimeout(o._ended.bind(o,i),l):(o._endTimers[i._id]=function(){o._ended(i),c.removeEventListener("ended",o._endTimers[i._id],!1)},c.addEventListener("ended",o._endTimers[i._id],!1))}catch(e){o._emit("playerror",i._id,e)}},m=window&&window.ejecta||!c.readyState&&n._navigator.isCocoonJS;if(c.readyState>=3||m)p();else{var v=function(){p(),c.removeEventListener(n._canPlayEvent,v,!1)};c.addEventListener(n._canPlayEvent,v,!1),o._clearTimer(i._id)}}return i._id},pause:function(e){var n=this;if("loaded"!==n._state||n._playLock)return n._queue.push({event:"pause",action:function(){n.pause(e)}}),n;for(var t=n._getSoundIds(e),o=0;o=0?t=parseInt(r[0],10):e=parseFloat(r[0])}else r.length>=2&&(e=parseFloat(r[0]),t=parseInt(r[1],10));var a;if(!(void 0!==e&&e>=0&&e<=1))return a=t?o._soundById(t):o._sounds[0],a?a._volume:0;if("loaded"!==o._state)return o._queue.push({event:"volume",action:function(){o.volume.apply(o,r)}}),o;void 0===t&&(o._volume=e),t=o._getSoundIds(t);for(var u=0;u0?o/_:o),l=Date.now();e._fadeTo=t,e._interval=setInterval(function(){var r=(Date.now()-l)/o;l=Date.now(),i+=d*r,i=Math.max(0,i),i=Math.min(1,i),i=Math.round(100*i)/100,u._webAudio?e._volume=i:u.volume(i,e._id,!0),a&&(u._volume=i),(tn&&i>=t)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,u.volume(t,e._id),u._emit("fade",e._id))},s)},_stopFade:function(e){var t=this,o=t._soundById(e);return o&&o._interval&&(t._webAudio&&o._node.gain.cancelScheduledValues(n.ctx.currentTime),clearInterval(o._interval),o._interval=null,t.volume(o._fadeTo,e),o._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,n,t,o=this,r=arguments;if(0===r.length)return o._loop;if(1===r.length){if("boolean"!=typeof r[0])return!!(t=o._soundById(parseInt(r[0],10)))&&t._loop;e=r[0],o._loop=e}else 2===r.length&&(e=r[0],n=parseInt(r[1],10));for(var a=o._getSoundIds(n),u=0;u=0?t=parseInt(r[0],10):e=parseFloat(r[0])}else 2===r.length&&(e=parseFloat(r[0]),t=parseInt(r[1],10));var i;if("number"!=typeof e)return i=o._soundById(t),i?i._rate:o._rate;if("loaded"!==o._state)return o._queue.push({event:"rate",action:function(){o.rate.apply(o,r)}}),o;void 0===t&&(o._rate=e),t=o._getSoundIds(t);for(var d=0;d=0?t=parseInt(r[0],10):o._sounds.length&&(t=o._sounds[0]._id,e=parseFloat(r[0]))}else 2===r.length&&(e=parseFloat(r[0]),t=parseInt(r[1],10));if(void 0===t)return o;if("loaded"!==o._state)return o._queue.push({event:"seek",action:function(){o.seek.apply(o,r)}}),o;var i=o._soundById(t);if(i){if(!("number"==typeof e&&e>=0)){if(o._webAudio){var d=o.playing(t)?n.ctx.currentTime-i._playStart:0,_=i._rateSeek?i._rateSeek-i._seek:0;return i._seek+(_+d*Math.abs(i._rate))}return i._node.currentTime}var s=o.playing(t);if(s&&o.pause(t,!0),i._seek=e,i._ended=!1,o._clearTimer(t),s&&o.play(t,!0),!o._webAudio&&i._node&&(i._node.currentTime=e),s&&!o._webAudio){var l=function(){o._playLock?setTimeout(l,0):o._emit("seek",t)};setTimeout(l,0)}else o._emit("seek",t)}return o},playing:function(e){var n=this;if("number"==typeof e){var t=n._soundById(e);return!!t&&!t._paused}for(var o=0;o=0&&n._howls.splice(a,1);var u=!0;for(o=0;o=0;a--)r[a].id&&r[a].id!==n&&"load"!==e||(setTimeout(function(e){e.call(this,n,t)}.bind(o,r[a].fn),0),r[a].once&&o.off(e,r[a].fn,r[a].id));return o._loadQueue(e),o},_loadQueue:function(e){var n=this;if(n._queue.length>0){var t=n._queue[0];t.event===e&&(n._queue.shift(),n._loadQueue()),e||t.action()}return n},_ended:function(e){var t=this,o=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;o--){if(t<=n)return;e._sounds[o]._ended&&(e._webAudio&&e._sounds[o]._node&&e._sounds[o]._node.disconnect(0),e._sounds.splice(o,1),t--)}}},_getSoundIds:function(e){var n=this;if(void 0===e){for(var t=[],o=0;o0&&(r[t._src]=e,d(t,e))},function(){t._emit("loaderror",null,"Decoding audio data failed.")})},d=function(e,n){n&&!e._duration&&(e._duration=n.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},_=function(){try{"undefined"!=typeof AudioContext?n.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?n.ctx=new webkitAudioContext:n.usingWebAudio=!1}catch(e){n.usingWebAudio=!1}var e=/iP(hone|od|ad)/.test(n._navigator&&n._navigator.platform),t=n._navigator&&n._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),o=t?parseInt(t[1],10):null;if(e&&o&&o<9){var r=/safari/.test(n._navigator&&n._navigator.userAgent.toLowerCase());(n._navigator&&n._navigator.standalone&&!r||n._navigator&&!n._navigator.standalone&&!r)&&(n.usingWebAudio=!1)}n.usingWebAudio&&(n.masterGain=void 0===n.ctx.createGain?n.ctx.createGainNode():n.ctx.createGain(),n.masterGain.gain.setValueAtTime(n._muted?0:1,n.ctx.currentTime),n.masterGain.connect(n.ctx.destination)),n._setup()};"function"==typeof define&&define.amd&&define([],function(){return{Howler:n,Howl:t}}),"undefined"!=typeof exports&&(exports.Howler=n,exports.Howl=t),"undefined"!=typeof window?(window.HowlerGlobal=e,window.Howler=n,window.Howl=t,window.Sound=o):"undefined"!=typeof global&&(global.HowlerGlobal=e,global.Howler=n,global.Howl=t,global.Sound=o)}(); \ No newline at end of file diff --git a/js/howler/2.0.13/howler.js b/js/howler/2.0.13/howler.js new file mode 100755 index 0000000..52075fd --- /dev/null +++ b/js/howler/2.0.13/howler.js @@ -0,0 +1,2964 @@ +/*! + * howler.js v2.0.13 + * howlerjs.com + * + * (c) 2013-2018, James Simpson of GoldFire Studios + * goldfirestudios.com + * + * MIT License + */ + +(function() { + + 'use strict'; + + /** Global Methods **/ + /***************************************************************************/ + + /** + * Create the global controller. All contained methods and properties apply + * to all sounds that are currently playing or will be in the future. + */ + var HowlerGlobal = function() { + this.init(); + }; + HowlerGlobal.prototype = { + /** + * Initialize the global Howler object. + * @return {Howler} + */ + init: function() { + var self = this || Howler; + + // Create a global ID counter. + self._counter = 1000; + + // Internal properties. + self._codecs = {}; + self._howls = []; + self._muted = false; + self._volume = 1; + self._canPlayEvent = 'canplaythrough'; + self._navigator = (typeof window !== 'undefined' && window.navigator) ? window.navigator : null; + + // Public properties. + self.masterGain = null; + self.noAudio = false; + self.usingWebAudio = true; + self.autoSuspend = true; + self.ctx = null; + + // Set to false to disable the auto iOS enabler. + self.mobileAutoEnable = true; + + // Setup the various state values for global tracking. + self._setup(); + + return self; + }, + + /** + * Get/set the global volume for all sounds. + * @param {Float} vol Volume from 0.0 to 1.0. + * @return {Howler/Float} Returns self or current volume. + */ + volume: function(vol) { + var self = this || Howler; + vol = parseFloat(vol); + + // If we don't have an AudioContext created yet, run the setup. + if (!self.ctx) { + setupAudioContext(); + } + + if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) { + self._volume = vol; + + // Don't update any of the nodes if we are muted. + if (self._muted) { + return self; + } + + // When using Web Audio, we just need to adjust the master gain. + if (self.usingWebAudio) { + self.masterGain.gain.setValueAtTime(vol, Howler.ctx.currentTime); + } + + // Loop through and change volume for all HTML5 audio nodes. + for (var i=0; i=0; i--) { + self._howls[i].unload(); + } + + // Create a new AudioContext to make sure it is fully reset. + if (self.usingWebAudio && self.ctx && typeof self.ctx.close !== 'undefined') { + self.ctx.close(); + self.ctx = null; + setupAudioContext(); + } + + return self; + }, + + /** + * Check for codec support of specific extension. + * @param {String} ext Audio file extention. + * @return {Boolean} + */ + codecs: function(ext) { + return (this || Howler)._codecs[ext.replace(/^x-/, '')]; + }, + + /** + * Setup various state values for global tracking. + * @return {Howler} + */ + _setup: function() { + var self = this || Howler; + + // Keeps track of the suspend/resume state of the AudioContext. + self.state = self.ctx ? self.ctx.state || 'running' : 'running'; + + // Automatically begin the 30-second suspend process + self._autoSuspend(); + + // Check if audio is available. + if (!self.usingWebAudio) { + // No audio is available on this system if noAudio is set to true. + if (typeof Audio !== 'undefined') { + try { + var test = new Audio(); + + // Check if the canplaythrough event is available. + if (typeof test.oncanplaythrough === 'undefined') { + self._canPlayEvent = 'canplay'; + } + } catch(e) { + self.noAudio = true; + } + } else { + self.noAudio = true; + } + } + + // Test to make sure audio isn't disabled in Internet Explorer. + try { + var test = new Audio(); + if (test.muted) { + self.noAudio = true; + } + } catch (e) {} + + // Check for supported codecs. + if (!self.noAudio) { + self._setupCodecs(); + } + + return self; + }, + + /** + * Check for browser support for various codecs and cache the results. + * @return {Howler} + */ + _setupCodecs: function() { + var self = this || Howler; + var audioTest = null; + + // Must wrap in a try/catch because IE11 in server mode throws an error. + try { + audioTest = (typeof Audio !== 'undefined') ? new Audio() : null; + } catch (err) { + return self; + } + + if (!audioTest || typeof audioTest.canPlayType !== 'function') { + return self; + } + + var mpegTest = audioTest.canPlayType('audio/mpeg;').replace(/^no$/, ''); + + // Opera version <33 has mixed MP3 support, so we need to check for and block it. + var checkOpera = self._navigator && self._navigator.userAgent.match(/OPR\/([0-6].)/g); + var isOldOpera = (checkOpera && parseInt(checkOpera[0].split('/')[1], 10) < 33); + + self._codecs = { + mp3: !!(!isOldOpera && (mpegTest || audioTest.canPlayType('audio/mp3;').replace(/^no$/, ''))), + mpeg: !!mpegTest, + opus: !!audioTest.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, ''), + ogg: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''), + oga: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''), + wav: !!audioTest.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''), + aac: !!audioTest.canPlayType('audio/aac;').replace(/^no$/, ''), + caf: !!audioTest.canPlayType('audio/x-caf;').replace(/^no$/, ''), + m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''), + mp4: !!(audioTest.canPlayType('audio/x-mp4;') || audioTest.canPlayType('audio/mp4;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''), + weba: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''), + webm: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''), + dolby: !!audioTest.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/, ''), + flac: !!(audioTest.canPlayType('audio/x-flac;') || audioTest.canPlayType('audio/flac;')).replace(/^no$/, '') + }; + + return self; + }, + + /** + * Mobile browsers will only allow audio to be played after a user interaction. + * Attempt to automatically unlock audio on the first user interaction. + * Concept from: http://paulbakaus.com/tutorials/html5/web-audio-on-ios/ + * @return {Howler} + */ + _enableMobileAudio: function() { + var self = this || Howler; + + // Only run this on mobile devices if audio isn't already eanbled. + var isMobile = /iPhone|iPad|iPod|Android|BlackBerry|BB10|Silk|Mobi/i.test(self._navigator && self._navigator.userAgent); + var isTouch = !!(('ontouchend' in window) || (self._navigator && self._navigator.maxTouchPoints > 0) || (self._navigator && self._navigator.msMaxTouchPoints > 0)); + if (self._mobileEnabled || !self.ctx || (!isMobile && !isTouch)) { + return; + } + + self._mobileEnabled = false; + + // Some mobile devices/platforms have distortion issues when opening/closing tabs and/or web views. + // Bugs in the browser (especially Mobile Safari) can cause the sampleRate to change from 44100 to 48000. + // By calling Howler.unload(), we create a new AudioContext with the correct sampleRate. + if (!self._mobileUnloaded && self.ctx.sampleRate !== 44100) { + self._mobileUnloaded = true; + self.unload(); + } + + // Scratch buffer for enabling iOS to dispose of web audio buffers correctly, as per: + // http://stackoverflow.com/questions/24119684 + self._scratchBuffer = self.ctx.createBuffer(1, 1, 22050); + + // Call this method on touch start to create and play a buffer, + // then check if the audio actually played to determine if + // audio has now been unlocked on iOS, Android, etc. + var unlock = function() { + // Fix Android can not play in suspend state. + Howler._autoResume(); + + // Create an empty buffer. + var source = self.ctx.createBufferSource(); + source.buffer = self._scratchBuffer; + source.connect(self.ctx.destination); + + // Play the empty buffer. + if (typeof source.start === 'undefined') { + source.noteOn(0); + } else { + source.start(0); + } + + // Calling resume() on a stack initiated by user gesture is what actually unlocks the audio on Android Chrome >= 55. + if (typeof self.ctx.resume === 'function') { + self.ctx.resume(); + } + + // Setup a timeout to check that we are unlocked on the next event loop. + source.onended = function() { + source.disconnect(0); + + // Update the unlocked state and prevent this check from happening again. + self._mobileEnabled = true; + self.mobileAutoEnable = false; + + // Remove the touch start listener. + document.removeEventListener('touchstart', unlock, true); + document.removeEventListener('touchend', unlock, true); + }; + }; + + // Setup a touch start listener to attempt an unlock in. + document.addEventListener('touchstart', unlock, true); + document.addEventListener('touchend', unlock, true); + + return self; + }, + + /** + * Automatically suspend the Web Audio AudioContext after no sound has played for 30 seconds. + * This saves processing/energy and fixes various browser-specific bugs with audio getting stuck. + * @return {Howler} + */ + _autoSuspend: function() { + var self = this; + + if (!self.autoSuspend || !self.ctx || typeof self.ctx.suspend === 'undefined' || !Howler.usingWebAudio) { + return; + } + + // Check if any sounds are playing. + for (var i=0; i 0 ? sound._seek : self._sprite[sprite][0] / 1000); + var duration = Math.max(0, ((self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000) - seek); + var timeout = (duration * 1000) / Math.abs(sound._rate); + + // Update the parameters of the sound + sound._paused = false; + sound._ended = false; + sound._sprite = sprite; + sound._seek = seek; + sound._start = self._sprite[sprite][0] / 1000; + sound._stop = (self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000; + sound._loop = !!(sound._loop || self._sprite[sprite][2]); + + // Begin the actual playback. + var node = sound._node; + if (self._webAudio) { + // Fire this when the sound is ready to play to begin Web Audio playback. + var playWebAudio = function() { + self._refreshBuffer(sound); + + // Setup the playback params. + var vol = (sound._muted || self._muted) ? 0 : sound._volume; + node.gain.setValueAtTime(vol, Howler.ctx.currentTime); + sound._playStart = Howler.ctx.currentTime; + + // Play the sound using the supported method. + if (typeof node.bufferSource.start === 'undefined') { + sound._loop ? node.bufferSource.noteGrainOn(0, seek, 86400) : node.bufferSource.noteGrainOn(0, seek, duration); + } else { + sound._loop ? node.bufferSource.start(0, seek, 86400) : node.bufferSource.start(0, seek, duration); + } + + // Start a new timer if none is present. + if (timeout !== Infinity) { + self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); + } + + if (!internal) { + setTimeout(function() { + self._emit('play', sound._id); + }, 0); + } + }; + + if (Howler.state === 'running') { + playWebAudio(); + } else { + self.once('resume', playWebAudio); + + // Cancel the end timer. + self._clearTimer(sound._id); + } + } else { + // Fire this when the sound is ready to play to begin HTML5 Audio playback. + var playHtml5 = function() { + node.currentTime = seek; + node.muted = sound._muted || self._muted || Howler._muted || node.muted; + node.volume = sound._volume * Howler.volume(); + node.playbackRate = sound._rate; + + // Mobile browsers will throw an error if this is called without user interaction. + try { + var play = node.play(); + + // Support older browsers that don't support promises, and thus don't have this issue. + if (typeof Promise !== 'undefined' && play instanceof Promise) { + // Implements a lock to prevent DOMException: The play() request was interrupted by a call to pause(). + self._playLock = true; + + // Releases the lock and executes queued actions. + var runLoadQueue = function() { + self._playLock = false; + if (!internal) { + self._emit('play', sound._id); + } + }; + play.then(runLoadQueue, runLoadQueue); + } else if (!internal) { + self._emit('play', sound._id); + } + + // Setting rate before playing won't work in IE, so we set it again here. + node.playbackRate = sound._rate; + + // If the node is still paused, then we can assume there was a playback issue. + if (node.paused) { + self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' + + 'on mobile devices where playback was not within a user interaction.'); + return; + } + + // Setup the end timer on sprites or listen for the ended event. + if (sprite !== '__default' || sound._loop) { + self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); + } else { + self._endTimers[sound._id] = function() { + // Fire ended on this audio node. + self._ended(sound); + + // Clear this listener. + node.removeEventListener('ended', self._endTimers[sound._id], false); + }; + node.addEventListener('ended', self._endTimers[sound._id], false); + } + } catch (err) { + self._emit('playerror', sound._id, err); + } + }; + + // Play immediately if ready, or wait for the 'canplaythrough'e vent. + var loadedNoReadyState = (window && window.ejecta) || (!node.readyState && Howler._navigator.isCocoonJS); + if (node.readyState >= 3 || loadedNoReadyState) { + playHtml5(); + } else { + var listener = function() { + // Begin playback. + playHtml5(); + + // Clear this listener. + node.removeEventListener(Howler._canPlayEvent, listener, false); + }; + node.addEventListener(Howler._canPlayEvent, listener, false); + + // Cancel the end timer. + self._clearTimer(sound._id); + } + } + + return sound._id; + }, + + /** + * Pause playback and save current position. + * @param {Number} id The sound ID (empty to pause all in group). + * @return {Howl} + */ + pause: function(id) { + var self = this; + + // If the sound hasn't loaded or a play() promise is pending, add it to the load queue to pause when capable. + if (self._state !== 'loaded' || self._playLock) { + self._queue.push({ + event: 'pause', + action: function() { + self.pause(id); + } + }); + + return self; + } + + // If no id is passed, get all ID's to be paused. + var ids = self._getSoundIds(id); + + for (var i=0; i Returns the group's volume value. + * volume(id) -> Returns the sound id's current volume. + * volume(vol) -> Sets the volume of all sounds in this Howl group. + * volume(vol, id) -> Sets the volume of passed sound id. + * @return {Howl/Number} Returns self or current volume. + */ + volume: function() { + var self = this; + var args = arguments; + var vol, id; + + // Determine the values based on arguments. + if (args.length === 0) { + // Return the value of the groups' volume. + return self._volume; + } else if (args.length === 1 || args.length === 2 && typeof args[1] === 'undefined') { + // First check if this is an ID, and if not, assume it is a new volume. + var ids = self._getSoundIds(); + var index = ids.indexOf(args[0]); + if (index >= 0) { + id = parseInt(args[0], 10); + } else { + vol = parseFloat(args[0]); + } + } else if (args.length >= 2) { + vol = parseFloat(args[0]); + id = parseInt(args[1], 10); + } + + // Update the volume or return the current volume. + var sound; + if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) { + // If the sound hasn't loaded, add it to the load queue to change volume when capable. + if (self._state !== 'loaded') { + self._queue.push({ + event: 'volume', + action: function() { + self.volume.apply(self, args); + } + }); + + return self; + } + + // Set the group volume. + if (typeof id === 'undefined') { + self._volume = vol; + } + + // Update one or all volumes. + id = self._getSoundIds(id); + for (var i=0; i 0) ? len / steps : len); + var lastTick = Date.now(); + + // Store the value being faded to. + sound._fadeTo = to; + + // Update the volume value on each interval tick. + sound._interval = setInterval(function() { + // Update the volume based on the time since the last tick. + var tick = (Date.now() - lastTick) / len; + lastTick = Date.now(); + vol += diff * tick; + + // Make sure the volume is in the right bounds. + vol = Math.max(0, vol); + vol = Math.min(1, vol); + + // Round to within 2 decimal points. + vol = Math.round(vol * 100) / 100; + + // Change the volume. + if (self._webAudio) { + sound._volume = vol; + } else { + self.volume(vol, sound._id, true); + } + + // Set the group's volume. + if (isGroup) { + self._volume = vol; + } + + // When the fade is complete, stop it and fire event. + if ((to < from && vol <= to) || (to > from && vol >= to)) { + clearInterval(sound._interval); + sound._interval = null; + sound._fadeTo = null; + self.volume(to, sound._id); + self._emit('fade', sound._id); + } + }, stepLen); + }, + + /** + * Internal method that stops the currently playing fade when + * a new fade starts, volume is changed or the sound is stopped. + * @param {Number} id The sound id. + * @return {Howl} + */ + _stopFade: function(id) { + var self = this; + var sound = self._soundById(id); + + if (sound && sound._interval) { + if (self._webAudio) { + sound._node.gain.cancelScheduledValues(Howler.ctx.currentTime); + } + + clearInterval(sound._interval); + sound._interval = null; + self.volume(sound._fadeTo, id); + sound._fadeTo = null; + self._emit('fade', id); + } + + return self; + }, + + /** + * Get/set the loop parameter on a sound. This method can optionally take 0, 1 or 2 arguments. + * loop() -> Returns the group's loop value. + * loop(id) -> Returns the sound id's loop value. + * loop(loop) -> Sets the loop value for all sounds in this Howl group. + * loop(loop, id) -> Sets the loop value of passed sound id. + * @return {Howl/Boolean} Returns self or current loop value. + */ + loop: function() { + var self = this; + var args = arguments; + var loop, id, sound; + + // Determine the values for loop and id. + if (args.length === 0) { + // Return the grou's loop value. + return self._loop; + } else if (args.length === 1) { + if (typeof args[0] === 'boolean') { + loop = args[0]; + self._loop = loop; + } else { + // Return this sound's loop value. + sound = self._soundById(parseInt(args[0], 10)); + return sound ? sound._loop : false; + } + } else if (args.length === 2) { + loop = args[0]; + id = parseInt(args[1], 10); + } + + // If no id is passed, get all ID's to be looped. + var ids = self._getSoundIds(id); + for (var i=0; i Returns the first sound node's current playback rate. + * rate(id) -> Returns the sound id's current playback rate. + * rate(rate) -> Sets the playback rate of all sounds in this Howl group. + * rate(rate, id) -> Sets the playback rate of passed sound id. + * @return {Howl/Number} Returns self or the current playback rate. + */ + rate: function() { + var self = this; + var args = arguments; + var rate, id; + + // Determine the values based on arguments. + if (args.length === 0) { + // We will simply return the current rate of the first node. + id = self._sounds[0]._id; + } else if (args.length === 1) { + // First check if this is an ID, and if not, assume it is a new rate value. + var ids = self._getSoundIds(); + var index = ids.indexOf(args[0]); + if (index >= 0) { + id = parseInt(args[0], 10); + } else { + rate = parseFloat(args[0]); + } + } else if (args.length === 2) { + rate = parseFloat(args[0]); + id = parseInt(args[1], 10); + } + + // Update the playback rate or return the current value. + var sound; + if (typeof rate === 'number') { + // If the sound hasn't loaded, add it to the load queue to change playback rate when capable. + if (self._state !== 'loaded') { + self._queue.push({ + event: 'rate', + action: function() { + self.rate.apply(self, args); + } + }); + + return self; + } + + // Set the group rate. + if (typeof id === 'undefined') { + self._rate = rate; + } + + // Update one or all volumes. + id = self._getSoundIds(id); + for (var i=0; i Returns the first sound node's current seek position. + * seek(id) -> Returns the sound id's current seek position. + * seek(seek) -> Sets the seek position of the first sound node. + * seek(seek, id) -> Sets the seek position of passed sound id. + * @return {Howl/Number} Returns self or the current seek position. + */ + seek: function() { + var self = this; + var args = arguments; + var seek, id; + + // Determine the values based on arguments. + if (args.length === 0) { + // We will simply return the current position of the first node. + id = self._sounds[0]._id; + } else if (args.length === 1) { + // First check if this is an ID, and if not, assume it is a new seek position. + var ids = self._getSoundIds(); + var index = ids.indexOf(args[0]); + if (index >= 0) { + id = parseInt(args[0], 10); + } else if (self._sounds.length) { + id = self._sounds[0]._id; + seek = parseFloat(args[0]); + } + } else if (args.length === 2) { + seek = parseFloat(args[0]); + id = parseInt(args[1], 10); + } + + // If there is no ID, bail out. + if (typeof id === 'undefined') { + return self; + } + + // If the sound hasn't loaded, add it to the load queue to seek when capable. + if (self._state !== 'loaded') { + self._queue.push({ + event: 'seek', + action: function() { + self.seek.apply(self, args); + } + }); + + return self; + } + + // Get the sound. + var sound = self._soundById(id); + + if (sound) { + if (typeof seek === 'number' && seek >= 0) { + // Pause the sound and update position for restarting playback. + var playing = self.playing(id); + if (playing) { + self.pause(id, true); + } + + // Move the position of the track and cancel timer. + sound._seek = seek; + sound._ended = false; + self._clearTimer(id); + + // Restart the playback if the sound was playing. + if (playing) { + self.play(id, true); + } + + // Update the seek position for HTML5 Audio. + if (!self._webAudio && sound._node) { + sound._node.currentTime = seek; + } + + // Wait for the play lock to be unset before emitting (HTML5 Audio). + if (playing && !self._webAudio) { + var emitSeek = function() { + if (!self._playLock) { + self._emit('seek', id); + } else { + setTimeout(emitSeek, 0); + } + }; + setTimeout(emitSeek, 0); + } else { + self._emit('seek', id); + } + } else { + if (self._webAudio) { + var realTime = self.playing(id) ? Howler.ctx.currentTime - sound._playStart : 0; + var rateSeek = sound._rateSeek ? sound._rateSeek - sound._seek : 0; + return sound._seek + (rateSeek + realTime * Math.abs(sound._rate)); + } else { + return sound._node.currentTime; + } + } + } + + return self; + }, + + /** + * Check if a specific sound is currently playing or not (if id is provided), or check if at least one of the sounds in the group is playing or not. + * @param {Number} id The sound id to check. If none is passed, the whole sound group is checked. + * @return {Boolean} True if playing and false if not. + */ + playing: function(id) { + var self = this; + + // Check the passed sound ID (if any). + if (typeof id === 'number') { + var sound = self._soundById(id); + return sound ? !sound._paused : false; + } + + // Otherwise, loop through all sounds and check if any are playing. + for (var i=0; i= 0) { + Howler._howls.splice(index, 1); + } + + // Delete this sound from the cache (if no other Howl is using it). + var remCache = true; + for (i=0; i=0; i--) { + // Only fire the listener if the correct ID is used. + if (!events[i].id || events[i].id === id || event === 'load') { + setTimeout(function(fn) { + fn.call(this, id, msg); + }.bind(self, events[i].fn), 0); + + // If this event was setup with `once`, remove it. + if (events[i].once) { + self.off(event, events[i].fn, events[i].id); + } + } + } + + // Pass the event type into load queue so that it can continue stepping. + self._loadQueue(event); + + return self; + }, + + /** + * Queue of actions initiated before the sound has loaded. + * These will be called in sequence, with the next only firing + * after the previous has finished executing (even if async like play). + * @return {Howl} + */ + _loadQueue: function(event) { + var self = this; + + if (self._queue.length > 0) { + var task = self._queue[0]; + + // Remove this task if a matching event was passed. + if (task.event === event) { + self._queue.shift(); + self._loadQueue(); + } + + // Run the task if no event type is passed. + if (!event) { + task.action(); + } + } + + return self; + }, + + /** + * Fired when playback ends at the end of the duration. + * @param {Sound} sound The sound object to work with. + * @return {Howl} + */ + _ended: function(sound) { + var self = this; + var sprite = sound._sprite; + + // If we are using IE and there was network latency we may be clipping + // audio before it completes playing. Lets check the node to make sure it + // believes it has completed, before ending the playback. + if (!self._webAudio && sound._node && !sound._node.paused && !sound._node.ended && sound._node.currentTime < sound._stop) { + setTimeout(self._ended.bind(self, sound), 100); + return self; + } + + // Should this sound loop? + var loop = !!(sound._loop || self._sprite[sprite][2]); + + // Fire the ended event. + self._emit('end', sound._id); + + // Restart the playback for HTML5 Audio loop. + if (!self._webAudio && loop) { + self.stop(sound._id, true).play(sound._id); + } + + // Restart this timer if on a Web Audio loop. + if (self._webAudio && loop) { + self._emit('play', sound._id); + sound._seek = sound._start || 0; + sound._rateSeek = 0; + sound._playStart = Howler.ctx.currentTime; + + var timeout = ((sound._stop - sound._start) * 1000) / Math.abs(sound._rate); + self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); + } + + // Mark the node as paused. + if (self._webAudio && !loop) { + sound._paused = true; + sound._ended = true; + sound._seek = sound._start || 0; + sound._rateSeek = 0; + self._clearTimer(sound._id); + + // Clean up the buffer source. + self._cleanBuffer(sound._node); + + // Attempt to auto-suspend AudioContext if no sounds are still playing. + Howler._autoSuspend(); + } + + // When using a sprite, end the track. + if (!self._webAudio && !loop) { + self.stop(sound._id, true); + } + + return self; + }, + + /** + * Clear the end timer for a sound playback. + * @param {Number} id The sound ID. + * @return {Howl} + */ + _clearTimer: function(id) { + var self = this; + + if (self._endTimers[id]) { + // Clear the timeout or remove the ended listener. + if (typeof self._endTimers[id] !== 'function') { + clearTimeout(self._endTimers[id]); + } else { + var sound = self._soundById(id); + if (sound && sound._node) { + sound._node.removeEventListener('ended', self._endTimers[id], false); + } + } + + delete self._endTimers[id]; + } + + return self; + }, + + /** + * Return the sound identified by this ID, or return null. + * @param {Number} id Sound ID + * @return {Object} Sound object or null. + */ + _soundById: function(id) { + var self = this; + + // Loop through all sounds and find the one with this ID. + for (var i=0; i=0; i--) { + if (cnt <= limit) { + return; + } + + if (self._sounds[i]._ended) { + // Disconnect the audio source when using Web Audio. + if (self._webAudio && self._sounds[i]._node) { + self._sounds[i]._node.disconnect(0); + } + + // Remove sounds until we have the pool size. + self._sounds.splice(i, 1); + cnt--; + } + } + }, + + /** + * Get all ID's from the sounds pool. + * @param {Number} id Only return one ID if one is passed. + * @return {Array} Array of IDs. + */ + _getSoundIds: function(id) { + var self = this; + + if (typeof id === 'undefined') { + var ids = []; + for (var i=0; i 0) { + cache[self._src] = buffer; + loadSound(self, buffer); + } + }, function() { + self._emit('loaderror', null, 'Decoding audio data failed.'); + }); + }; + + /** + * Sound is now loaded, so finish setting everything up and fire the loaded event. + * @param {Howl} self + * @param {Object} buffer The decoded buffer sound source. + */ + var loadSound = function(self, buffer) { + // Set the duration. + if (buffer && !self._duration) { + self._duration = buffer.duration; + } + + // Setup a sprite if none is defined. + if (Object.keys(self._sprite).length === 0) { + self._sprite = {__default: [0, self._duration * 1000]}; + } + + // Fire the loaded event. + if (self._state !== 'loaded') { + self._state = 'loaded'; + self._emit('load'); + self._loadQueue(); + } + }; + + /** + * Setup the audio context when available, or switch to HTML5 Audio mode. + */ + var setupAudioContext = function() { + // Check if we are using Web Audio and setup the AudioContext if we are. + try { + if (typeof AudioContext !== 'undefined') { + Howler.ctx = new AudioContext(); + } else if (typeof webkitAudioContext !== 'undefined') { + Howler.ctx = new webkitAudioContext(); + } else { + Howler.usingWebAudio = false; + } + } catch(e) { + Howler.usingWebAudio = false; + } + + // Check if a webview is being used on iOS8 or earlier (rather than the browser). + // If it is, disable Web Audio as it causes crashing. + var iOS = (/iP(hone|od|ad)/.test(Howler._navigator && Howler._navigator.platform)); + var appVersion = Howler._navigator && Howler._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/); + var version = appVersion ? parseInt(appVersion[1], 10) : null; + if (iOS && version && version < 9) { + var safari = /safari/.test(Howler._navigator && Howler._navigator.userAgent.toLowerCase()); + if (Howler._navigator && Howler._navigator.standalone && !safari || Howler._navigator && !Howler._navigator.standalone && !safari) { + Howler.usingWebAudio = false; + } + } + + // Create and expose the master GainNode when using Web Audio (useful for plugins or advanced usage). + if (Howler.usingWebAudio) { + Howler.masterGain = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain(); + Howler.masterGain.gain.setValueAtTime(Howler._muted ? 0 : 1, Howler.ctx.currentTime); + Howler.masterGain.connect(Howler.ctx.destination); + } + + // Re-run the setup on Howler. + Howler._setup(); + }; + + // Add support for AMD (Asynchronous Module Definition) libraries such as require.js. + if (typeof define === 'function' && define.amd) { + define([], function() { + return { + Howler: Howler, + Howl: Howl + }; + }); + } + + // Add support for CommonJS libraries such as browserify. + if (typeof exports !== 'undefined') { + exports.Howler = Howler; + exports.Howl = Howl; + } + + // Define globally in case AMD is not available or unused. + if (typeof window !== 'undefined') { + window.HowlerGlobal = HowlerGlobal; + window.Howler = Howler; + window.Howl = Howl; + window.Sound = Sound; + } else if (typeof global !== 'undefined') { // Add to global in Node.js (for testing, etc). + global.HowlerGlobal = HowlerGlobal; + global.Howler = Howler; + global.Howl = Howl; + global.Sound = Sound; + } +})(); + + +/*! + * Spatial Plugin - Adds support for stereo and 3D audio where Web Audio is supported. + * + * howler.js v2.0.13 + * howlerjs.com + * + * (c) 2013-2018, James Simpson of GoldFire Studios + * goldfirestudios.com + * + * MIT License + */ + +(function() { + + 'use strict'; + + // Setup default properties. + HowlerGlobal.prototype._pos = [0, 0, 0]; + HowlerGlobal.prototype._orientation = [0, 0, -1, 0, 1, 0]; + + /** Global Methods **/ + /***************************************************************************/ + + /** + * Helper method to update the stereo panning position of all current Howls. + * Future Howls will not use this value unless explicitly set. + * @param {Number} pan A value of -1.0 is all the way left and 1.0 is all the way right. + * @return {Howler/Number} Self or current stereo panning value. + */ + HowlerGlobal.prototype.stereo = function(pan) { + var self = this; + + // Stop right here if not using Web Audio. + if (!self.ctx || !self.ctx.listener) { + return self; + } + + // Loop through all Howls and update their stereo panning. + for (var i=self._howls.length-1; i>=0; i--) { + self._howls[i].stereo(pan); + } + + return self; + }; + + /** + * Get/set the position of the listener in 3D cartesian space. Sounds using + * 3D position will be relative to the listener's position. + * @param {Number} x The x-position of the listener. + * @param {Number} y The y-position of the listener. + * @param {Number} z The z-position of the listener. + * @return {Howler/Array} Self or current listener position. + */ + HowlerGlobal.prototype.pos = function(x, y, z) { + var self = this; + + // Stop right here if not using Web Audio. + if (!self.ctx || !self.ctx.listener) { + return self; + } + + // Set the defaults for optional 'y' & 'z'. + y = (typeof y !== 'number') ? self._pos[1] : y; + z = (typeof z !== 'number') ? self._pos[2] : z; + + if (typeof x === 'number') { + self._pos = [x, y, z]; + + if (typeof self.ctx.listener.positionX !== 'undefined') { + self.ctx.listener.positionX.setTargetAtTime(self._pos[0], Howler.ctx.currentTime, 0.1); + self.ctx.listener.positionY.setTargetAtTime(self._pos[1], Howler.ctx.currentTime, 0.1); + self.ctx.listener.positionZ.setTargetAtTime(self._pos[2], Howler.ctx.currentTime, 0.1); + } else { + self.ctx.listener.setPosition(self._pos[0], self._pos[1], self._pos[2]); + } + } else { + return self._pos; + } + + return self; + }; + + /** + * Get/set the direction the listener is pointing in the 3D cartesian space. + * A front and up vector must be provided. The front is the direction the + * face of the listener is pointing, and up is the direction the top of the + * listener is pointing. Thus, these values are expected to be at right angles + * from each other. + * @param {Number} x The x-orientation of the listener. + * @param {Number} y The y-orientation of the listener. + * @param {Number} z The z-orientation of the listener. + * @param {Number} xUp The x-orientation of the top of the listener. + * @param {Number} yUp The y-orientation of the top of the listener. + * @param {Number} zUp The z-orientation of the top of the listener. + * @return {Howler/Array} Returns self or the current orientation vectors. + */ + HowlerGlobal.prototype.orientation = function(x, y, z, xUp, yUp, zUp) { + var self = this; + + // Stop right here if not using Web Audio. + if (!self.ctx || !self.ctx.listener) { + return self; + } + + // Set the defaults for optional 'y' & 'z'. + var or = self._orientation; + y = (typeof y !== 'number') ? or[1] : y; + z = (typeof z !== 'number') ? or[2] : z; + xUp = (typeof xUp !== 'number') ? or[3] : xUp; + yUp = (typeof yUp !== 'number') ? or[4] : yUp; + zUp = (typeof zUp !== 'number') ? or[5] : zUp; + + if (typeof x === 'number') { + self._orientation = [x, y, z, xUp, yUp, zUp]; + + if (typeof self.ctx.listener.forwardX !== 'undefined') { + self.ctx.listener.forwardX.setTargetAtTime(x, Howler.ctx.currentTime, 0.1); + self.ctx.listener.forwardY.setTargetAtTime(y, Howler.ctx.currentTime, 0.1); + self.ctx.listener.forwardZ.setTargetAtTime(z, Howler.ctx.currentTime, 0.1); + self.ctx.listener.upX.setTargetAtTime(x, Howler.ctx.currentTime, 0.1); + self.ctx.listener.upY.setTargetAtTime(y, Howler.ctx.currentTime, 0.1); + self.ctx.listener.upZ.setTargetAtTime(z, Howler.ctx.currentTime, 0.1); + } else { + self.ctx.listener.setOrientation(x, y, z, xUp, yUp, zUp); + } + } else { + return or; + } + + return self; + }; + + /** Group Methods **/ + /***************************************************************************/ + + /** + * Add new properties to the core init. + * @param {Function} _super Core init method. + * @return {Howl} + */ + Howl.prototype.init = (function(_super) { + return function(o) { + var self = this; + + // Setup user-defined default properties. + self._orientation = o.orientation || [1, 0, 0]; + self._stereo = o.stereo || null; + self._pos = o.pos || null; + self._pannerAttr = { + coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : 360, + coneOuterAngle: typeof o.coneOuterAngle !== 'undefined' ? o.coneOuterAngle : 360, + coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : 0, + distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : 'inverse', + maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : 10000, + panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : 'HRTF', + refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : 1, + rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : 1 + }; + + // Setup event listeners. + self._onstereo = o.onstereo ? [{fn: o.onstereo}] : []; + self._onpos = o.onpos ? [{fn: o.onpos}] : []; + self._onorientation = o.onorientation ? [{fn: o.onorientation}] : []; + + // Complete initilization with howler.js core's init function. + return _super.call(this, o); + }; + })(Howl.prototype.init); + + /** + * Get/set the stereo panning of the audio source for this sound or all in the group. + * @param {Number} pan A value of -1.0 is all the way left and 1.0 is all the way right. + * @param {Number} id (optional) The sound ID. If none is passed, all in group will be updated. + * @return {Howl/Number} Returns self or the current stereo panning value. + */ + Howl.prototype.stereo = function(pan, id) { + var self = this; + + // Stop right here if not using Web Audio. + if (!self._webAudio) { + return self; + } + + // If the sound hasn't loaded, add it to the load queue to change stereo pan when capable. + if (self._state !== 'loaded') { + self._queue.push({ + event: 'stereo', + action: function() { + self.stereo(pan, id); + } + }); + + return self; + } + + // Check for PannerStereoNode support and fallback to PannerNode if it doesn't exist. + var pannerType = (typeof Howler.ctx.createStereoPanner === 'undefined') ? 'spatial' : 'stereo'; + + // Setup the group's stereo panning if no ID is passed. + if (typeof id === 'undefined') { + // Return the group's stereo panning if no parameters are passed. + if (typeof pan === 'number') { + self._stereo = pan; + self._pos = [pan, 0, 0]; + } else { + return self._stereo; + } + } + + // Change the streo panning of one or all sounds in group. + var ids = self._getSoundIds(id); + for (var i=0; i Returns the group's values. + * pannerAttr(id) -> Returns the sound id's values. + * pannerAttr(o) -> Set's the values of all sounds in this Howl group. + * pannerAttr(o, id) -> Set's the values of passed sound id. + * + * Attributes: + * coneInnerAngle - (360 by default) A parameter for directional audio sources, this is an angle, in degrees, + * inside of which there will be no volume reduction. + * coneOuterAngle - (360 by default) A parameter for directional audio sources, this is an angle, in degrees, + * outside of which the volume will be reduced to a constant value of `coneOuterGain`. + * coneOuterGain - (0 by default) A parameter for directional audio sources, this is the gain outside of the + * `coneOuterAngle`. It is a linear value in the range `[0, 1]`. + * distanceModel - ('inverse' by default) Determines algorithm used to reduce volume as audio moves away from + * listener. Can be `linear`, `inverse` or `exponential. + * maxDistance - (10000 by default) The maximum distance between source and listener, after which the volume + * will not be reduced any further. + * refDistance - (1 by default) A reference distance for reducing volume as source moves further from the listener. + * This is simply a variable of the distance model and has a different effect depending on which model + * is used and the scale of your coordinates. Generally, volume will be equal to 1 at this distance. + * rolloffFactor - (1 by default) How quickly the volume reduces as source moves from listener. This is simply a + * variable of the distance model and can be in the range of `[0, 1]` with `linear` and `[0, ∞]` + * with `inverse` and `exponential`. + * panningModel - ('HRTF' by default) Determines which spatialization algorithm is used to position audio. + * Can be `HRTF` or `equalpower`. + * + * @return {Howl/Object} Returns self or current panner attributes. + */ + Howl.prototype.pannerAttr = function() { + var self = this; + var args = arguments; + var o, id, sound; + + // Stop right here if not using Web Audio. + if (!self._webAudio) { + return self; + } + + // Determine the values based on arguments. + if (args.length === 0) { + // Return the group's panner attribute values. + return self._pannerAttr; + } else if (args.length === 1) { + if (typeof args[0] === 'object') { + o = args[0]; + + // Set the grou's panner attribute values. + if (typeof id === 'undefined') { + if (!o.pannerAttr) { + o.pannerAttr = { + coneInnerAngle: o.coneInnerAngle, + coneOuterAngle: o.coneOuterAngle, + coneOuterGain: o.coneOuterGain, + distanceModel: o.distanceModel, + maxDistance: o.maxDistance, + refDistance: o.refDistance, + rolloffFactor: o.rolloffFactor, + panningModel: o.panningModel + }; + } + + self._pannerAttr = { + coneInnerAngle: typeof o.pannerAttr.coneInnerAngle !== 'undefined' ? o.pannerAttr.coneInnerAngle : self._coneInnerAngle, + coneOuterAngle: typeof o.pannerAttr.coneOuterAngle !== 'undefined' ? o.pannerAttr.coneOuterAngle : self._coneOuterAngle, + coneOuterGain: typeof o.pannerAttr.coneOuterGain !== 'undefined' ? o.pannerAttr.coneOuterGain : self._coneOuterGain, + distanceModel: typeof o.pannerAttr.distanceModel !== 'undefined' ? o.pannerAttr.distanceModel : self._distanceModel, + maxDistance: typeof o.pannerAttr.maxDistance !== 'undefined' ? o.pannerAttr.maxDistance : self._maxDistance, + refDistance: typeof o.pannerAttr.refDistance !== 'undefined' ? o.pannerAttr.refDistance : self._refDistance, + rolloffFactor: typeof o.pannerAttr.rolloffFactor !== 'undefined' ? o.pannerAttr.rolloffFactor : self._rolloffFactor, + panningModel: typeof o.pannerAttr.panningModel !== 'undefined' ? o.pannerAttr.panningModel : self._panningModel + }; + } + } else { + // Return this sound's panner attribute values. + sound = self._soundById(parseInt(args[0], 10)); + return sound ? sound._pannerAttr : self._pannerAttr; + } + } else if (args.length === 2) { + o = args[0]; + id = parseInt(args[1], 10); + } + + // Update the values of the specified sounds. + var ids = self._getSoundIds(id); + for (var i=0; i=0&&e<=1){if(t._volume=e,t._muted)return t;t.usingWebAudio&&t.masterGain.gain.setValueAtTime(e,n.ctx.currentTime);for(var o=0;o=0;t--)e._howls[t].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,_()),e},codecs:function(e){return(this||n)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||n;if(e.state=e.ctx?e.ctx.state||"running":"running",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{var t=new Audio;void 0===t.oncanplaythrough&&(e._canPlayEvent="canplay")}catch(n){e.noAudio=!0}else e.noAudio=!0;try{var t=new Audio;t.muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||n,t=null;try{t="undefined"!=typeof Audio?new Audio:null}catch(n){return e}if(!t||"function"!=typeof t.canPlayType)return e;var o=t.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator&&e._navigator.userAgent.match(/OPR\/([0-6].)/g),a=r&&parseInt(r[0].split("/")[1],10)<33;return e._codecs={mp3:!(a||!o&&!t.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!o,opus:!!t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!t.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),aac:!!t.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!t.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/m4a;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(t.canPlayType("audio/x-mp4;")||t.canPlayType("audio/mp4;")||t.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,""),webm:!!t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,""),dolby:!!t.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(t.canPlayType("audio/x-flac;")||t.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_enableMobileAudio:function(){var e=this||n,t=/iPhone|iPad|iPod|Android|BlackBerry|BB10|Silk|Mobi/i.test(e._navigator&&e._navigator.userAgent),o=!!("ontouchend"in window||e._navigator&&e._navigator.maxTouchPoints>0||e._navigator&&e._navigator.msMaxTouchPoints>0);if(!e._mobileEnabled&&e.ctx&&(t||o)){e._mobileEnabled=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var r=function(){n._autoResume();var t=e.ctx.createBufferSource();t.buffer=e._scratchBuffer,t.connect(e.ctx.destination),void 0===t.start?t.noteOn(0):t.start(0),"function"==typeof e.ctx.resume&&e.ctx.resume(),t.onended=function(){t.disconnect(0),e._mobileEnabled=!0,e.mobileAutoEnable=!1,document.removeEventListener("touchstart",r,!0),document.removeEventListener("touchend",r,!0)}};return document.addEventListener("touchstart",r,!0),document.addEventListener("touchend",r,!0),e}},_autoSuspend:function(){var e=this;if(e.autoSuspend&&e.ctx&&void 0!==e.ctx.suspend&&n.usingWebAudio){for(var t=0;t0?i._seek:o._sprite[e][0]/1e3),s=Math.max(0,(o._sprite[e][0]+o._sprite[e][1])/1e3-_),l=1e3*s/Math.abs(i._rate);i._paused=!1,i._ended=!1,i._sprite=e,i._seek=_,i._start=o._sprite[e][0]/1e3,i._stop=(o._sprite[e][0]+o._sprite[e][1])/1e3,i._loop=!(!i._loop&&!o._sprite[e][2]);var c=i._node;if(o._webAudio){var f=function(){o._refreshBuffer(i);var e=i._muted||o._muted?0:i._volume;c.gain.setValueAtTime(e,n.ctx.currentTime),i._playStart=n.ctx.currentTime,void 0===c.bufferSource.start?i._loop?c.bufferSource.noteGrainOn(0,_,86400):c.bufferSource.noteGrainOn(0,_,s):i._loop?c.bufferSource.start(0,_,86400):c.bufferSource.start(0,_,s),l!==1/0&&(o._endTimers[i._id]=setTimeout(o._ended.bind(o,i),l)),t||setTimeout(function(){o._emit("play",i._id)},0)};"running"===n.state?f():(o.once("resume",f),o._clearTimer(i._id))}else{var p=function(){c.currentTime=_,c.muted=i._muted||o._muted||n._muted||c.muted,c.volume=i._volume*n.volume(),c.playbackRate=i._rate;try{var r=c.play();if("undefined"!=typeof Promise&&r instanceof Promise){o._playLock=!0;var a=function(){o._playLock=!1,t||o._emit("play",i._id)};r.then(a,a)}else t||o._emit("play",i._id);if(c.playbackRate=i._rate,c.paused)return void o._emit("playerror",i._id,"Playback was unable to start. This is most commonly an issue on mobile devices where playback was not within a user interaction.");"__default"!==e||i._loop?o._endTimers[i._id]=setTimeout(o._ended.bind(o,i),l):(o._endTimers[i._id]=function(){o._ended(i),c.removeEventListener("ended",o._endTimers[i._id],!1)},c.addEventListener("ended",o._endTimers[i._id],!1))}catch(e){o._emit("playerror",i._id,e)}},m=window&&window.ejecta||!c.readyState&&n._navigator.isCocoonJS;if(c.readyState>=3||m)p();else{var v=function(){p(),c.removeEventListener(n._canPlayEvent,v,!1)};c.addEventListener(n._canPlayEvent,v,!1),o._clearTimer(i._id)}}return i._id},pause:function(e){var n=this;if("loaded"!==n._state||n._playLock)return n._queue.push({event:"pause",action:function(){n.pause(e)}}),n;for(var t=n._getSoundIds(e),o=0;o=0?t=parseInt(r[0],10):e=parseFloat(r[0])}else r.length>=2&&(e=parseFloat(r[0]),t=parseInt(r[1],10));var a;if(!(void 0!==e&&e>=0&&e<=1))return a=t?o._soundById(t):o._sounds[0],a?a._volume:0;if("loaded"!==o._state)return o._queue.push({event:"volume",action:function(){o.volume.apply(o,r)}}),o;void 0===t&&(o._volume=e),t=o._getSoundIds(t);for(var u=0;u0?o/_:o),l=Date.now();e._fadeTo=t,e._interval=setInterval(function(){var r=(Date.now()-l)/o;l=Date.now(),i+=d*r,i=Math.max(0,i),i=Math.min(1,i),i=Math.round(100*i)/100,u._webAudio?e._volume=i:u.volume(i,e._id,!0),a&&(u._volume=i),(tn&&i>=t)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,u.volume(t,e._id),u._emit("fade",e._id))},s)},_stopFade:function(e){var t=this,o=t._soundById(e);return o&&o._interval&&(t._webAudio&&o._node.gain.cancelScheduledValues(n.ctx.currentTime),clearInterval(o._interval),o._interval=null,t.volume(o._fadeTo,e),o._fadeTo=null,t._emit("fade",e)),t},loop:function(){var e,n,t,o=this,r=arguments;if(0===r.length)return o._loop;if(1===r.length){if("boolean"!=typeof r[0])return!!(t=o._soundById(parseInt(r[0],10)))&&t._loop;e=r[0],o._loop=e}else 2===r.length&&(e=r[0],n=parseInt(r[1],10));for(var a=o._getSoundIds(n),u=0;u=0?t=parseInt(r[0],10):e=parseFloat(r[0])}else 2===r.length&&(e=parseFloat(r[0]),t=parseInt(r[1],10));var i;if("number"!=typeof e)return i=o._soundById(t),i?i._rate:o._rate;if("loaded"!==o._state)return o._queue.push({event:"rate",action:function(){o.rate.apply(o,r)}}),o;void 0===t&&(o._rate=e),t=o._getSoundIds(t);for(var d=0;d=0?t=parseInt(r[0],10):o._sounds.length&&(t=o._sounds[0]._id,e=parseFloat(r[0]))}else 2===r.length&&(e=parseFloat(r[0]),t=parseInt(r[1],10));if(void 0===t)return o;if("loaded"!==o._state)return o._queue.push({event:"seek",action:function(){o.seek.apply(o,r)}}),o;var i=o._soundById(t);if(i){if(!("number"==typeof e&&e>=0)){if(o._webAudio){var d=o.playing(t)?n.ctx.currentTime-i._playStart:0,_=i._rateSeek?i._rateSeek-i._seek:0;return i._seek+(_+d*Math.abs(i._rate))}return i._node.currentTime}var s=o.playing(t);if(s&&o.pause(t,!0),i._seek=e,i._ended=!1,o._clearTimer(t),s&&o.play(t,!0),!o._webAudio&&i._node&&(i._node.currentTime=e),s&&!o._webAudio){var l=function(){o._playLock?setTimeout(l,0):o._emit("seek",t)};setTimeout(l,0)}else o._emit("seek",t)}return o},playing:function(e){var n=this;if("number"==typeof e){var t=n._soundById(e);return!!t&&!t._paused}for(var o=0;o=0&&n._howls.splice(a,1);var u=!0;for(o=0;o=0;a--)r[a].id&&r[a].id!==n&&"load"!==e||(setTimeout(function(e){e.call(this,n,t)}.bind(o,r[a].fn),0),r[a].once&&o.off(e,r[a].fn,r[a].id));return o._loadQueue(e),o},_loadQueue:function(e){var n=this;if(n._queue.length>0){var t=n._queue[0];t.event===e&&(n._queue.shift(),n._loadQueue()),e||t.action()}return n},_ended:function(e){var t=this,o=e._sprite;if(!t._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;o--){if(t<=n)return;e._sounds[o]._ended&&(e._webAudio&&e._sounds[o]._node&&e._sounds[o]._node.disconnect(0),e._sounds.splice(o,1),t--)}}},_getSoundIds:function(e){var n=this;if(void 0===e){for(var t=[],o=0;o0&&(r[t._src]=e,d(t,e))},function(){t._emit("loaderror",null,"Decoding audio data failed.")})},d=function(e,n){n&&!e._duration&&(e._duration=n.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},_=function(){try{"undefined"!=typeof AudioContext?n.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?n.ctx=new webkitAudioContext:n.usingWebAudio=!1}catch(e){n.usingWebAudio=!1}var e=/iP(hone|od|ad)/.test(n._navigator&&n._navigator.platform),t=n._navigator&&n._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),o=t?parseInt(t[1],10):null;if(e&&o&&o<9){var r=/safari/.test(n._navigator&&n._navigator.userAgent.toLowerCase());(n._navigator&&n._navigator.standalone&&!r||n._navigator&&!n._navigator.standalone&&!r)&&(n.usingWebAudio=!1)}n.usingWebAudio&&(n.masterGain=void 0===n.ctx.createGain?n.ctx.createGainNode():n.ctx.createGain(),n.masterGain.gain.setValueAtTime(n._muted?0:1,n.ctx.currentTime),n.masterGain.connect(n.ctx.destination)),n._setup()};"function"==typeof define&&define.amd&&define([],function(){return{Howler:n,Howl:t}}),"undefined"!=typeof exports&&(exports.Howler=n,exports.Howl=t),"undefined"!=typeof window?(window.HowlerGlobal=e,window.Howler=n,window.Howl=t,window.Sound=o):"undefined"!=typeof global&&(global.HowlerGlobal=e,global.Howler=n,global.Howl=t,global.Sound=o)}(); +/*! Spatial Plugin */ +!function(){"use strict";HowlerGlobal.prototype._pos=[0,0,0],HowlerGlobal.prototype._orientation=[0,0,-1,0,1,0],HowlerGlobal.prototype.stereo=function(e){var n=this;if(!n.ctx||!n.ctx.listener)return n;for(var t=n._howls.length-1;t>=0;t--)n._howls[t].stereo(e);return n},HowlerGlobal.prototype.pos=function(e,n,t){var r=this;return r.ctx&&r.ctx.listener?(n="number"!=typeof n?r._pos[1]:n,t="number"!=typeof t?r._pos[2]:t,"number"!=typeof e?r._pos:(r._pos=[e,n,t],void 0!==r.ctx.listener.positionX?(r.ctx.listener.positionX.setTargetAtTime(r._pos[0],Howler.ctx.currentTime,.1),r.ctx.listener.positionY.setTargetAtTime(r._pos[1],Howler.ctx.currentTime,.1),r.ctx.listener.positionZ.setTargetAtTime(r._pos[2],Howler.ctx.currentTime,.1)):r.ctx.listener.setPosition(r._pos[0],r._pos[1],r._pos[2]),r)):r},HowlerGlobal.prototype.orientation=function(e,n,t,r,o,i){var a=this;if(!a.ctx||!a.ctx.listener)return a;var s=a._orientation;return n="number"!=typeof n?s[1]:n,t="number"!=typeof t?s[2]:t,r="number"!=typeof r?s[3]:r,o="number"!=typeof o?s[4]:o,i="number"!=typeof i?s[5]:i,"number"!=typeof e?s:(a._orientation=[e,n,t,r,o,i],void 0!==a.ctx.listener.forwardX?(a.ctx.listener.forwardX.setTargetAtTime(e,Howler.ctx.currentTime,.1),a.ctx.listener.forwardY.setTargetAtTime(n,Howler.ctx.currentTime,.1),a.ctx.listener.forwardZ.setTargetAtTime(t,Howler.ctx.currentTime,.1),a.ctx.listener.upX.setTargetAtTime(e,Howler.ctx.currentTime,.1),a.ctx.listener.upY.setTargetAtTime(n,Howler.ctx.currentTime,.1),a.ctx.listener.upZ.setTargetAtTime(t,Howler.ctx.currentTime,.1)):a.ctx.listener.setOrientation(e,n,t,r,o,i),a)},Howl.prototype.init=function(e){return function(n){var t=this;return t._orientation=n.orientation||[1,0,0],t._stereo=n.stereo||null,t._pos=n.pos||null,t._pannerAttr={coneInnerAngle:void 0!==n.coneInnerAngle?n.coneInnerAngle:360,coneOuterAngle:void 0!==n.coneOuterAngle?n.coneOuterAngle:360,coneOuterGain:void 0!==n.coneOuterGain?n.coneOuterGain:0,distanceModel:void 0!==n.distanceModel?n.distanceModel:"inverse",maxDistance:void 0!==n.maxDistance?n.maxDistance:1e4,panningModel:void 0!==n.panningModel?n.panningModel:"HRTF",refDistance:void 0!==n.refDistance?n.refDistance:1,rolloffFactor:void 0!==n.rolloffFactor?n.rolloffFactor:1},t._onstereo=n.onstereo?[{fn:n.onstereo}]:[],t._onpos=n.onpos?[{fn:n.onpos}]:[],t._onorientation=n.onorientation?[{fn:n.onorientation}]:[],e.call(this,n)}}(Howl.prototype.init),Howl.prototype.stereo=function(n,t){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(n,t)}}),r;var o=void 0===Howler.ctx.createStereoPanner?"spatial":"stereo";if(void 0===t){if("number"!=typeof n)return r._stereo;r._stereo=n,r._pos=[n,0,0]}for(var i=r._getSoundIds(t),a=0;a=0;t--)n._howls[t].stereo(e);return n},HowlerGlobal.prototype.pos=function(e,n,t){var r=this;return r.ctx&&r.ctx.listener?(n="number"!=typeof n?r._pos[1]:n,t="number"!=typeof t?r._pos[2]:t,"number"!=typeof e?r._pos:(r._pos=[e,n,t],void 0!==r.ctx.listener.positionX?(r.ctx.listener.positionX.setTargetAtTime(r._pos[0],Howler.ctx.currentTime,.1),r.ctx.listener.positionY.setTargetAtTime(r._pos[1],Howler.ctx.currentTime,.1),r.ctx.listener.positionZ.setTargetAtTime(r._pos[2],Howler.ctx.currentTime,.1)):r.ctx.listener.setPosition(r._pos[0],r._pos[1],r._pos[2]),r)):r},HowlerGlobal.prototype.orientation=function(e,n,t,r,o,i){var a=this;if(!a.ctx||!a.ctx.listener)return a;var s=a._orientation;return n="number"!=typeof n?s[1]:n,t="number"!=typeof t?s[2]:t,r="number"!=typeof r?s[3]:r,o="number"!=typeof o?s[4]:o,i="number"!=typeof i?s[5]:i,"number"!=typeof e?s:(a._orientation=[e,n,t,r,o,i],void 0!==a.ctx.listener.forwardX?(a.ctx.listener.forwardX.setTargetAtTime(e,Howler.ctx.currentTime,.1),a.ctx.listener.forwardY.setTargetAtTime(n,Howler.ctx.currentTime,.1),a.ctx.listener.forwardZ.setTargetAtTime(t,Howler.ctx.currentTime,.1),a.ctx.listener.upX.setTargetAtTime(e,Howler.ctx.currentTime,.1),a.ctx.listener.upY.setTargetAtTime(n,Howler.ctx.currentTime,.1),a.ctx.listener.upZ.setTargetAtTime(t,Howler.ctx.currentTime,.1)):a.ctx.listener.setOrientation(e,n,t,r,o,i),a)},Howl.prototype.init=function(e){return function(n){var t=this;return t._orientation=n.orientation||[1,0,0],t._stereo=n.stereo||null,t._pos=n.pos||null,t._pannerAttr={coneInnerAngle:void 0!==n.coneInnerAngle?n.coneInnerAngle:360,coneOuterAngle:void 0!==n.coneOuterAngle?n.coneOuterAngle:360,coneOuterGain:void 0!==n.coneOuterGain?n.coneOuterGain:0,distanceModel:void 0!==n.distanceModel?n.distanceModel:"inverse",maxDistance:void 0!==n.maxDistance?n.maxDistance:1e4,panningModel:void 0!==n.panningModel?n.panningModel:"HRTF",refDistance:void 0!==n.refDistance?n.refDistance:1,rolloffFactor:void 0!==n.rolloffFactor?n.rolloffFactor:1},t._onstereo=n.onstereo?[{fn:n.onstereo}]:[],t._onpos=n.onpos?[{fn:n.onpos}]:[],t._onorientation=n.onorientation?[{fn:n.onorientation}]:[],e.call(this,n)}}(Howl.prototype.init),Howl.prototype.stereo=function(n,t){var r=this;if(!r._webAudio)return r;if("loaded"!==r._state)return r._queue.push({event:"stereo",action:function(){r.stereo(n,t)}}),r;var o=void 0===Howler.ctx.createStereoPanner?"spatial":"stereo";if(void 0===t){if("number"!=typeof n)return r._stereo;r._stereo=n,r._pos=[n,0,0]}for(var i=r._getSoundIds(t),a=0;a=0&&e<=1){if(o._volume=e,o._muted)return o;o.usingWebAudio&&o.masterGain.gain.setValueAtTime(e,n.ctx.currentTime);for(var t=0;t=0;o--)e._howls[o].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,_()),e},codecs:function(e){return(this||n)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||n;if(e.state=e.ctx?e.ctx.state||"running":"running",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{var o=new Audio;void 0===o.oncanplaythrough&&(e._canPlayEvent="canplay")}catch(n){e.noAudio=!0}else e.noAudio=!0;try{var o=new Audio;o.muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||n,o=null;try{o="undefined"!=typeof Audio?new Audio:null}catch(n){return e}if(!o||"function"!=typeof o.canPlayType)return e;var t=o.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator&&e._navigator.userAgent.match(/OPR\/([0-6].)/g),a=r&&parseInt(r[0].split("/")[1],10)<33;return e._codecs={mp3:!(a||!t&&!o.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!t,opus:!!o.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!o.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!o.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!o.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),aac:!!o.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!o.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(o.canPlayType("audio/x-m4a;")||o.canPlayType("audio/m4a;")||o.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(o.canPlayType("audio/x-mp4;")||o.canPlayType("audio/mp4;")||o.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!!o.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,""),webm:!!o.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,""),dolby:!!o.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(o.canPlayType("audio/x-flac;")||o.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_enableMobileAudio:function(){var e=this||n,o=/iPhone|iPad|iPod|Android|BlackBerry|BB10|Silk|Mobi/i.test(e._navigator&&e._navigator.userAgent),t=!!("ontouchend"in window||e._navigator&&e._navigator.maxTouchPoints>0||e._navigator&&e._navigator.msMaxTouchPoints>0);if(!e._mobileEnabled&&e.ctx&&(o||t)){e._mobileEnabled=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var r=function(){n._autoResume();var o=e.ctx.createBufferSource();o.buffer=e._scratchBuffer,o.connect(e.ctx.destination),void 0===o.start?o.noteOn(0):o.start(0),"function"==typeof e.ctx.resume&&e.ctx.resume(),o.onended=function(){o.disconnect(0),e._mobileEnabled=!0,e.mobileAutoEnable=!1,document.removeEventListener("touchstart",r,!0),document.removeEventListener("touchend",r,!0)}};return document.addEventListener("touchstart",r,!0),document.addEventListener("touchend",r,!0),e}},_autoSuspend:function(){var e=this;if(e.autoSuspend&&e.ctx&&void 0!==e.ctx.suspend&&n.usingWebAudio){for(var o=0;o0?i._seek:t._sprite[e][0]/1e3),s=Math.max(0,(t._sprite[e][0]+t._sprite[e][1])/1e3-_),l=1e3*s/Math.abs(i._rate);i._paused=!1,i._ended=!1,i._sprite=e,i._seek=_,i._start=t._sprite[e][0]/1e3,i._stop=(t._sprite[e][0]+t._sprite[e][1])/1e3,i._loop=!(!i._loop&&!t._sprite[e][2]);var c=i._node;if(t._webAudio){var f=function(){t._refreshBuffer(i);var e=i._muted||t._muted?0:i._volume;c.gain.setValueAtTime(e,n.ctx.currentTime),i._playStart=n.ctx.currentTime,void 0===c.bufferSource.start?i._loop?c.bufferSource.noteGrainOn(0,_,86400):c.bufferSource.noteGrainOn(0,_,s):i._loop?c.bufferSource.start(0,_,86400):c.bufferSource.start(0,_,s),l!==1/0&&(t._endTimers[i._id]=setTimeout(t._ended.bind(t,i),l)),o||setTimeout(function(){t._emit("play",i._id)},0)};"running"===n.state?f():(t.once("resume",f),t._clearTimer(i._id))}else{var p=function(){c.currentTime=_,c.muted=i._muted||t._muted||n._muted||c.muted,c.volume=i._volume*n.volume(),c.playbackRate=i._rate;try{var e=c.play();if("undefined"!=typeof Promise&&e instanceof Promise&&(t._playLock=!0,e.then(function(){t._playLock=!1,t._loadQueue()})),c.paused)return void t._emit("playerror",i._id,"Playback was unable to start. This is most commonly an issue on mobile devices where playback was not within a user interaction.");l!==1/0&&(t._endTimers[i._id]=setTimeout(t._ended.bind(t,i),l)),o||t._emit("play",i._id)}catch(e){t._emit("playerror",i._id,e)}},m=window&&window.ejecta||!c.readyState&&n._navigator.isCocoonJS;if(4===c.readyState||m)p();else{var v=function(){p(),c.removeEventListener(n._canPlayEvent,v,!1)};c.addEventListener(n._canPlayEvent,v,!1),t._clearTimer(i._id)}}return i._id},pause:function(e){var n=this;if("loaded"!==n._state||n._playLock)return n._queue.push({event:"pause",action:function(){n.pause(e)}}),n;for(var o=n._getSoundIds(e),t=0;t=0?o=parseInt(r[0],10):e=parseFloat(r[0])}else r.length>=2&&(e=parseFloat(r[0]),o=parseInt(r[1],10));var a;if(!(void 0!==e&&e>=0&&e<=1))return a=o?t._soundById(o):t._sounds[0],a?a._volume:0;if("loaded"!==t._state)return t._queue.push({event:"volume",action:function(){t.volume.apply(t,r)}}),t;void 0===o&&(t._volume=e),o=t._getSoundIds(o);for(var u=0;uo?"out":"in",_=Math.abs(n-o),s=_/.01,l=s>0?t/s:t;l<4&&(s=Math.ceil(s/(4/l)),l=4),e._fadeTo=o,e._interval=setInterval(function(){s>0&&(i+="in"===d?.01:-.01),i=Math.max(0,i),i=Math.min(1,i),i=Math.round(100*i)/100,u._webAudio?e._volume=i:u.volume(i,e._id,!0),a&&(u._volume=i),(on&&i>=o)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,u.volume(o,e._id),u._emit("fade",e._id))},l)},_stopFade:function(e){var o=this,t=o._soundById(e);return t&&t._interval&&(o._webAudio&&t._node.gain.cancelScheduledValues(n.ctx.currentTime),clearInterval(t._interval),t._interval=null,o.volume(t._fadeTo,e),t._fadeTo=null,o._emit("fade",e)),o},loop:function(){var e,n,o,t=this,r=arguments;if(0===r.length)return t._loop;if(1===r.length){if("boolean"!=typeof r[0])return!!(o=t._soundById(parseInt(r[0],10)))&&o._loop;e=r[0],t._loop=e}else 2===r.length&&(e=r[0],n=parseInt(r[1],10));for(var a=t._getSoundIds(n),u=0;u=0?o=parseInt(r[0],10):e=parseFloat(r[0])}else 2===r.length&&(e=parseFloat(r[0]),o=parseInt(r[1],10));var i;if("number"!=typeof e)return i=t._soundById(o),i?i._rate:t._rate;if("loaded"!==t._state)return t._queue.push({event:"rate",action:function(){t.rate.apply(t,r)}}),t;void 0===o&&(t._rate=e),o=t._getSoundIds(o);for(var d=0;d=0?o=parseInt(r[0],10):t._sounds.length&&(o=t._sounds[0]._id,e=parseFloat(r[0]))}else 2===r.length&&(e=parseFloat(r[0]),o=parseInt(r[1],10));if(void 0===o)return t;if("loaded"!==t._state)return t._queue.push({event:"seek",action:function(){t.seek.apply(t,r)}}),t;var i=t._soundById(o);if(i){if(!("number"==typeof e&&e>=0)){if(t._webAudio){var d=t.playing(o)?n.ctx.currentTime-i._playStart:0,_=i._rateSeek?i._rateSeek-i._seek:0;return i._seek+(_+d*Math.abs(i._rate))}return i._node.currentTime}var s=t.playing(o);s&&t.pause(o,!0),i._seek=e,i._ended=!1,t._clearTimer(o),s&&t.play(o,!0),!t._webAudio&&i._node&&(i._node.currentTime=e),t._emit("seek",o)}return t},playing:function(e){var n=this;if("number"==typeof e){var o=n._soundById(e);return!!o&&!o._paused}for(var t=0;t=0&&n._howls.splice(a,1)}var u=!0;for(t=0;t=0;a--)r[a].id&&r[a].id!==n&&"load"!==e||(setTimeout(function(e){e.call(this,n,o)}.bind(t,r[a].fn),0),r[a].once&&t.off(e,r[a].fn,r[a].id));return t},_loadQueue:function(){var e=this;if(e._queue.length>0){var n=e._queue[0];e.once(n.event,function(){e._queue.shift(),e._loadQueue()}),n.action()}return e},_ended:function(e){var o=this,t=e._sprite;if(!o._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;t--){if(o<=n)return;e._sounds[t]._ended&&(e._webAudio&&e._sounds[t]._node&&e._sounds[t]._node.disconnect(0),e._sounds.splice(t,1),o--)}}},_getSoundIds:function(e){var n=this;if(void 0===e){for(var o=[],t=0;t0&&(r[o._src]=e,d(o,e))},function(){o._emit("loaderror",null,"Decoding audio data failed.")})},d=function(e,n){n&&!e._duration&&(e._duration=n.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},_=function(){try{"undefined"!=typeof AudioContext?n.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?n.ctx=new webkitAudioContext:n.usingWebAudio=!1}catch(e){n.usingWebAudio=!1}var e=/iP(hone|od|ad)/.test(n._navigator&&n._navigator.platform),o=n._navigator&&n._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),t=o?parseInt(o[1],10):null;if(e&&t&&t<9){var r=/safari/.test(n._navigator&&n._navigator.userAgent.toLowerCase());(n._navigator&&n._navigator.standalone&&!r||n._navigator&&!n._navigator.standalone&&!r)&&(n.usingWebAudio=!1)}n.usingWebAudio&&(n.masterGain=void 0===n.ctx.createGain?n.ctx.createGainNode():n.ctx.createGain(),n.masterGain.gain.setValueAtTime(n._muted?0:1,n.ctx.currentTime),n.masterGain.connect(n.ctx.destination)),n._setup()};"function"==typeof define&&define.amd&&define([],function(){return{Howler:n,Howl:o}}),"undefined"!=typeof exports&&(exports.Howler=n,exports.Howl=o),"undefined"!=typeof window?(window.HowlerGlobal=e,window.Howler=n,window.Howl=o,window.Sound=t):"undefined"!=typeof global&&(global.HowlerGlobal=e,global.Howler=n,global.Howl=o,global.Sound=t)}(); \ No newline at end of file diff --git a/js/howler/2.0.7/howler.js b/js/howler/2.0.7/howler.js new file mode 100755 index 0000000..3c31d1f --- /dev/null +++ b/js/howler/2.0.7/howler.js @@ -0,0 +1,2873 @@ +/*! + * howler.js v2.0.7 + * howlerjs.com + * + * (c) 2013-2017, James Simpson of GoldFire Studios + * goldfirestudios.com + * + * MIT License + */ + +(function() { + + 'use strict'; + + /** Global Methods **/ + /***************************************************************************/ + + /** + * Create the global controller. All contained methods and properties apply + * to all sounds that are currently playing or will be in the future. + */ + var HowlerGlobal = function() { + this.init(); + }; + HowlerGlobal.prototype = { + /** + * Initialize the global Howler object. + * @return {Howler} + */ + init: function() { + var self = this || Howler; + + // Create a global ID counter. + self._counter = 1000; + + // Internal properties. + self._codecs = {}; + self._howls = []; + self._muted = false; + self._volume = 1; + self._canPlayEvent = 'canplaythrough'; + self._navigator = (typeof window !== 'undefined' && window.navigator) ? window.navigator : null; + + // Public properties. + self.masterGain = null; + self.noAudio = false; + self.usingWebAudio = true; + self.autoSuspend = true; + self.ctx = null; + + // Set to false to disable the auto iOS enabler. + self.mobileAutoEnable = true; + + // Setup the various state values for global tracking. + self._setup(); + + return self; + }, + + /** + * Get/set the global volume for all sounds. + * @param {Float} vol Volume from 0.0 to 1.0. + * @return {Howler/Float} Returns self or current volume. + */ + volume: function(vol) { + var self = this || Howler; + vol = parseFloat(vol); + + // If we don't have an AudioContext created yet, run the setup. + if (!self.ctx) { + setupAudioContext(); + } + + if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) { + self._volume = vol; + + // Don't update any of the nodes if we are muted. + if (self._muted) { + return self; + } + + // When using Web Audio, we just need to adjust the master gain. + if (self.usingWebAudio) { + self.masterGain.gain.setValueAtTime(vol, Howler.ctx.currentTime); + } + + // Loop through and change volume for all HTML5 audio nodes. + for (var i=0; i=0; i--) { + self._howls[i].unload(); + } + + // Create a new AudioContext to make sure it is fully reset. + if (self.usingWebAudio && self.ctx && typeof self.ctx.close !== 'undefined') { + self.ctx.close(); + self.ctx = null; + setupAudioContext(); + } + + return self; + }, + + /** + * Check for codec support of specific extension. + * @param {String} ext Audio file extention. + * @return {Boolean} + */ + codecs: function(ext) { + return (this || Howler)._codecs[ext.replace(/^x-/, '')]; + }, + + /** + * Setup various state values for global tracking. + * @return {Howler} + */ + _setup: function() { + var self = this || Howler; + + // Keeps track of the suspend/resume state of the AudioContext. + self.state = self.ctx ? self.ctx.state || 'running' : 'running'; + + // Automatically begin the 30-second suspend process + self._autoSuspend(); + + // Check if audio is available. + if (!self.usingWebAudio) { + // No audio is available on this system if noAudio is set to true. + if (typeof Audio !== 'undefined') { + try { + var test = new Audio(); + + // Check if the canplaythrough event is available. + if (typeof test.oncanplaythrough === 'undefined') { + self._canPlayEvent = 'canplay'; + } + } catch(e) { + self.noAudio = true; + } + } else { + self.noAudio = true; + } + } + + // Test to make sure audio isn't disabled in Internet Explorer. + try { + var test = new Audio(); + if (test.muted) { + self.noAudio = true; + } + } catch (e) {} + + // Check for supported codecs. + if (!self.noAudio) { + self._setupCodecs(); + } + + return self; + }, + + /** + * Check for browser support for various codecs and cache the results. + * @return {Howler} + */ + _setupCodecs: function() { + var self = this || Howler; + var audioTest = null; + + // Must wrap in a try/catch because IE11 in server mode throws an error. + try { + audioTest = (typeof Audio !== 'undefined') ? new Audio() : null; + } catch (err) { + return self; + } + + if (!audioTest || typeof audioTest.canPlayType !== 'function') { + return self; + } + + var mpegTest = audioTest.canPlayType('audio/mpeg;').replace(/^no$/, ''); + + // Opera version <33 has mixed MP3 support, so we need to check for and block it. + var checkOpera = self._navigator && self._navigator.userAgent.match(/OPR\/([0-6].)/g); + var isOldOpera = (checkOpera && parseInt(checkOpera[0].split('/')[1], 10) < 33); + + self._codecs = { + mp3: !!(!isOldOpera && (mpegTest || audioTest.canPlayType('audio/mp3;').replace(/^no$/, ''))), + mpeg: !!mpegTest, + opus: !!audioTest.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, ''), + ogg: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''), + oga: !!audioTest.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''), + wav: !!audioTest.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''), + aac: !!audioTest.canPlayType('audio/aac;').replace(/^no$/, ''), + caf: !!audioTest.canPlayType('audio/x-caf;').replace(/^no$/, ''), + m4a: !!(audioTest.canPlayType('audio/x-m4a;') || audioTest.canPlayType('audio/m4a;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''), + mp4: !!(audioTest.canPlayType('audio/x-mp4;') || audioTest.canPlayType('audio/mp4;') || audioTest.canPlayType('audio/aac;')).replace(/^no$/, ''), + weba: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''), + webm: !!audioTest.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''), + dolby: !!audioTest.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/, ''), + flac: !!(audioTest.canPlayType('audio/x-flac;') || audioTest.canPlayType('audio/flac;')).replace(/^no$/, '') + }; + + return self; + }, + + /** + * Mobile browsers will only allow audio to be played after a user interaction. + * Attempt to automatically unlock audio on the first user interaction. + * Concept from: http://paulbakaus.com/tutorials/html5/web-audio-on-ios/ + * @return {Howler} + */ + _enableMobileAudio: function() { + var self = this || Howler; + + // Only run this on mobile devices if audio isn't already eanbled. + var isMobile = /iPhone|iPad|iPod|Android|BlackBerry|BB10|Silk|Mobi/i.test(self._navigator && self._navigator.userAgent); + var isTouch = !!(('ontouchend' in window) || (self._navigator && self._navigator.maxTouchPoints > 0) || (self._navigator && self._navigator.msMaxTouchPoints > 0)); + if (self._mobileEnabled || !self.ctx || (!isMobile && !isTouch)) { + return; + } + + self._mobileEnabled = false; + + // Some mobile devices/platforms have distortion issues when opening/closing tabs and/or web views. + // Bugs in the browser (especially Mobile Safari) can cause the sampleRate to change from 44100 to 48000. + // By calling Howler.unload(), we create a new AudioContext with the correct sampleRate. + if (!self._mobileUnloaded && self.ctx.sampleRate !== 44100) { + self._mobileUnloaded = true; + self.unload(); + } + + // Scratch buffer for enabling iOS to dispose of web audio buffers correctly, as per: + // http://stackoverflow.com/questions/24119684 + self._scratchBuffer = self.ctx.createBuffer(1, 1, 22050); + + // Call this method on touch start to create and play a buffer, + // then check if the audio actually played to determine if + // audio has now been unlocked on iOS, Android, etc. + var unlock = function() { + // Fix Android can not play in suspend state. + Howler._autoResume(); + + // Create an empty buffer. + var source = self.ctx.createBufferSource(); + source.buffer = self._scratchBuffer; + source.connect(self.ctx.destination); + + // Play the empty buffer. + if (typeof source.start === 'undefined') { + source.noteOn(0); + } else { + source.start(0); + } + + // Calling resume() on a stack initiated by user gesture is what actually unlocks the audio on Android Chrome >= 55. + if (typeof self.ctx.resume === 'function') { + self.ctx.resume(); + } + + // Setup a timeout to check that we are unlocked on the next event loop. + source.onended = function() { + source.disconnect(0); + + // Update the unlocked state and prevent this check from happening again. + self._mobileEnabled = true; + self.mobileAutoEnable = false; + + // Remove the touch start listener. + document.removeEventListener('touchstart', unlock, true); + document.removeEventListener('touchend', unlock, true); + }; + }; + + // Setup a touch start listener to attempt an unlock in. + document.addEventListener('touchstart', unlock, true); + document.addEventListener('touchend', unlock, true); + + return self; + }, + + /** + * Automatically suspend the Web Audio AudioContext after no sound has played for 30 seconds. + * This saves processing/energy and fixes various browser-specific bugs with audio getting stuck. + * @return {Howler} + */ + _autoSuspend: function() { + var self = this; + + if (!self.autoSuspend || !self.ctx || typeof self.ctx.suspend === 'undefined' || !Howler.usingWebAudio) { + return; + } + + // Check if any sounds are playing. + for (var i=0; i 0 ? sound._seek : self._sprite[sprite][0] / 1000); + var duration = Math.max(0, ((self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000) - seek); + var timeout = (duration * 1000) / Math.abs(sound._rate); + + // Update the parameters of the sound + sound._paused = false; + sound._ended = false; + sound._sprite = sprite; + sound._seek = seek; + sound._start = self._sprite[sprite][0] / 1000; + sound._stop = (self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000; + sound._loop = !!(sound._loop || self._sprite[sprite][2]); + + // Begin the actual playback. + var node = sound._node; + if (self._webAudio) { + // Fire this when the sound is ready to play to begin Web Audio playback. + var playWebAudio = function() { + self._refreshBuffer(sound); + + // Setup the playback params. + var vol = (sound._muted || self._muted) ? 0 : sound._volume; + node.gain.setValueAtTime(vol, Howler.ctx.currentTime); + sound._playStart = Howler.ctx.currentTime; + + // Play the sound using the supported method. + if (typeof node.bufferSource.start === 'undefined') { + sound._loop ? node.bufferSource.noteGrainOn(0, seek, 86400) : node.bufferSource.noteGrainOn(0, seek, duration); + } else { + sound._loop ? node.bufferSource.start(0, seek, 86400) : node.bufferSource.start(0, seek, duration); + } + + // Start a new timer if none is present. + if (timeout !== Infinity) { + self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); + } + + if (!internal) { + setTimeout(function() { + self._emit('play', sound._id); + }, 0); + } + }; + + if (Howler.state === 'running') { + playWebAudio(); + } else { + self.once('resume', playWebAudio); + + // Cancel the end timer. + self._clearTimer(sound._id); + } + } else { + // Fire this when the sound is ready to play to begin HTML5 Audio playback. + var playHtml5 = function() { + node.currentTime = seek; + node.muted = sound._muted || self._muted || Howler._muted || node.muted; + node.volume = sound._volume * Howler.volume(); + node.playbackRate = sound._rate; + + // Mobile browsers will throw an error if this is called without user interaction. + try { + var play = node.play(); + + // Support older browsers that don't support promises, and thus don't have this issue. + if (typeof Promise !== 'undefined' && play instanceof Promise) { + // Implements a lock to prevent DOMException: The play() request was interrupted by a call to pause(). + self._playLock = true; + + // Releases the lock and executes queued actions. + play.then(function () { + self._playLock = false; + self._loadQueue(); + }); + } + + // If the node is still paused, then we can assume there was a playback issue. + if (node.paused) { + self._emit('playerror', sound._id, 'Playback was unable to start. This is most commonly an issue ' + + 'on mobile devices where playback was not within a user interaction.'); + return; + } + + // Setup the new end timer. + if (timeout !== Infinity) { + self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); + } + + if (!internal) { + self._emit('play', sound._id); + } + } catch (err) { + self._emit('playerror', sound._id, err); + } + }; + + // Play immediately if ready, or wait for the 'canplaythrough'e vent. + var loadedNoReadyState = (window && window.ejecta) || (!node.readyState && Howler._navigator.isCocoonJS); + if (node.readyState === 4 || loadedNoReadyState) { + playHtml5(); + } else { + var listener = function() { + // Begin playback. + playHtml5(); + + // Clear this listener. + node.removeEventListener(Howler._canPlayEvent, listener, false); + }; + node.addEventListener(Howler._canPlayEvent, listener, false); + + // Cancel the end timer. + self._clearTimer(sound._id); + } + } + + return sound._id; + }, + + /** + * Pause playback and save current position. + * @param {Number} id The sound ID (empty to pause all in group). + * @return {Howl} + */ + pause: function(id) { + var self = this; + + // If the sound hasn't loaded or a play() promise is pending, add it to the load queue to pause when capable. + if (self._state !== 'loaded' || self._playLock) { + self._queue.push({ + event: 'pause', + action: function() { + self.pause(id); + } + }); + + return self; + } + + // If no id is passed, get all ID's to be paused. + var ids = self._getSoundIds(id); + + for (var i=0; i Returns the group's volume value. + * volume(id) -> Returns the sound id's current volume. + * volume(vol) -> Sets the volume of all sounds in this Howl group. + * volume(vol, id) -> Sets the volume of passed sound id. + * @return {Howl/Number} Returns self or current volume. + */ + volume: function() { + var self = this; + var args = arguments; + var vol, id; + + // Determine the values based on arguments. + if (args.length === 0) { + // Return the value of the groups' volume. + return self._volume; + } else if (args.length === 1 || args.length === 2 && typeof args[1] === 'undefined') { + // First check if this is an ID, and if not, assume it is a new volume. + var ids = self._getSoundIds(); + var index = ids.indexOf(args[0]); + if (index >= 0) { + id = parseInt(args[0], 10); + } else { + vol = parseFloat(args[0]); + } + } else if (args.length >= 2) { + vol = parseFloat(args[0]); + id = parseInt(args[1], 10); + } + + // Update the volume or return the current volume. + var sound; + if (typeof vol !== 'undefined' && vol >= 0 && vol <= 1) { + // If the sound hasn't loaded, add it to the load queue to change volume when capable. + if (self._state !== 'loaded') { + self._queue.push({ + event: 'volume', + action: function() { + self.volume.apply(self, args); + } + }); + + return self; + } + + // Set the group volume. + if (typeof id === 'undefined') { + self._volume = vol; + } + + // Update one or all volumes. + id = self._getSoundIds(id); + for (var i=0; i to ? 'out' : 'in'; + var diff = Math.abs(from - to); + var steps = diff / 0.01; + var stepLen = (steps > 0) ? len / steps : len; + + // Since browsers clamp timeouts to 4ms, we need to clamp our steps to that too. + if (stepLen < 4) { + steps = Math.ceil(steps / (4 / stepLen)); + stepLen = 4; + } + + // Store the value being faded to. + sound._fadeTo = to; + + // Update the volume value on each interval tick. + sound._interval = setInterval(function() { + // Update the volume amount, but only if the volume should change. + if (steps > 0) { + vol += (dir === 'in' ? 0.01 : -0.01); + } + + // Make sure the volume is in the right bounds. + vol = Math.max(0, vol); + vol = Math.min(1, vol); + + // Round to within 2 decimal points. + vol = Math.round(vol * 100) / 100; + + // Change the volume. + if (self._webAudio) { + sound._volume = vol; + } else { + self.volume(vol, sound._id, true); + } + + // Set the group's volume. + if (isGroup) { + self._volume = vol; + } + + // When the fade is complete, stop it and fire event. + if ((to < from && vol <= to) || (to > from && vol >= to)) { + clearInterval(sound._interval); + sound._interval = null; + sound._fadeTo = null; + self.volume(to, sound._id); + self._emit('fade', sound._id); + } + }, stepLen); + }, + + /** + * Internal method that stops the currently playing fade when + * a new fade starts, volume is changed or the sound is stopped. + * @param {Number} id The sound id. + * @return {Howl} + */ + _stopFade: function(id) { + var self = this; + var sound = self._soundById(id); + + if (sound && sound._interval) { + if (self._webAudio) { + sound._node.gain.cancelScheduledValues(Howler.ctx.currentTime); + } + + clearInterval(sound._interval); + sound._interval = null; + self.volume(sound._fadeTo, id); + sound._fadeTo = null; + self._emit('fade', id); + } + + return self; + }, + + /** + * Get/set the loop parameter on a sound. This method can optionally take 0, 1 or 2 arguments. + * loop() -> Returns the group's loop value. + * loop(id) -> Returns the sound id's loop value. + * loop(loop) -> Sets the loop value for all sounds in this Howl group. + * loop(loop, id) -> Sets the loop value of passed sound id. + * @return {Howl/Boolean} Returns self or current loop value. + */ + loop: function() { + var self = this; + var args = arguments; + var loop, id, sound; + + // Determine the values for loop and id. + if (args.length === 0) { + // Return the grou's loop value. + return self._loop; + } else if (args.length === 1) { + if (typeof args[0] === 'boolean') { + loop = args[0]; + self._loop = loop; + } else { + // Return this sound's loop value. + sound = self._soundById(parseInt(args[0], 10)); + return sound ? sound._loop : false; + } + } else if (args.length === 2) { + loop = args[0]; + id = parseInt(args[1], 10); + } + + // If no id is passed, get all ID's to be looped. + var ids = self._getSoundIds(id); + for (var i=0; i Returns the first sound node's current playback rate. + * rate(id) -> Returns the sound id's current playback rate. + * rate(rate) -> Sets the playback rate of all sounds in this Howl group. + * rate(rate, id) -> Sets the playback rate of passed sound id. + * @return {Howl/Number} Returns self or the current playback rate. + */ + rate: function() { + var self = this; + var args = arguments; + var rate, id; + + // Determine the values based on arguments. + if (args.length === 0) { + // We will simply return the current rate of the first node. + id = self._sounds[0]._id; + } else if (args.length === 1) { + // First check if this is an ID, and if not, assume it is a new rate value. + var ids = self._getSoundIds(); + var index = ids.indexOf(args[0]); + if (index >= 0) { + id = parseInt(args[0], 10); + } else { + rate = parseFloat(args[0]); + } + } else if (args.length === 2) { + rate = parseFloat(args[0]); + id = parseInt(args[1], 10); + } + + // Update the playback rate or return the current value. + var sound; + if (typeof rate === 'number') { + // If the sound hasn't loaded, add it to the load queue to change playback rate when capable. + if (self._state !== 'loaded') { + self._queue.push({ + event: 'rate', + action: function() { + self.rate.apply(self, args); + } + }); + + return self; + } + + // Set the group rate. + if (typeof id === 'undefined') { + self._rate = rate; + } + + // Update one or all volumes. + id = self._getSoundIds(id); + for (var i=0; i Returns the first sound node's current seek position. + * seek(id) -> Returns the sound id's current seek position. + * seek(seek) -> Sets the seek position of the first sound node. + * seek(seek, id) -> Sets the seek position of passed sound id. + * @return {Howl/Number} Returns self or the current seek position. + */ + seek: function() { + var self = this; + var args = arguments; + var seek, id; + + // Determine the values based on arguments. + if (args.length === 0) { + // We will simply return the current position of the first node. + id = self._sounds[0]._id; + } else if (args.length === 1) { + // First check if this is an ID, and if not, assume it is a new seek position. + var ids = self._getSoundIds(); + var index = ids.indexOf(args[0]); + if (index >= 0) { + id = parseInt(args[0], 10); + } else if (self._sounds.length) { + id = self._sounds[0]._id; + seek = parseFloat(args[0]); + } + } else if (args.length === 2) { + seek = parseFloat(args[0]); + id = parseInt(args[1], 10); + } + + // If there is no ID, bail out. + if (typeof id === 'undefined') { + return self; + } + + // If the sound hasn't loaded, add it to the load queue to seek when capable. + if (self._state !== 'loaded') { + self._queue.push({ + event: 'seek', + action: function() { + self.seek.apply(self, args); + } + }); + + return self; + } + + // Get the sound. + var sound = self._soundById(id); + + if (sound) { + if (typeof seek === 'number' && seek >= 0) { + // Pause the sound and update position for restarting playback. + var playing = self.playing(id); + if (playing) { + self.pause(id, true); + } + + // Move the position of the track and cancel timer. + sound._seek = seek; + sound._ended = false; + self._clearTimer(id); + + // Restart the playback if the sound was playing. + if (playing) { + self.play(id, true); + } + + // Update the seek position for HTML5 Audio. + if (!self._webAudio && sound._node) { + sound._node.currentTime = seek; + } + + self._emit('seek', id); + } else { + if (self._webAudio) { + var realTime = self.playing(id) ? Howler.ctx.currentTime - sound._playStart : 0; + var rateSeek = sound._rateSeek ? sound._rateSeek - sound._seek : 0; + return sound._seek + (rateSeek + realTime * Math.abs(sound._rate)); + } else { + return sound._node.currentTime; + } + } + } + + return self; + }, + + /** + * Check if a specific sound is currently playing or not (if id is provided), or check if at least one of the sounds in the group is playing or not. + * @param {Number} id The sound id to check. If none is passed, the whole sound group is checked. + * @return {Boolean} True if playing and false if not. + */ + playing: function(id) { + var self = this; + + // Check the passed sound ID (if any). + if (typeof id === 'number') { + var sound = self._soundById(id); + return sound ? !sound._paused : false; + } + + // Otherwise, loop through all sounds and check if any are playing. + for (var i=0; i= 0) { + Howler._howls.splice(index, 1); + } + } + + // Delete this sound from the cache (if no other Howl is using it). + var remCache = true; + for (i=0; i=0; i--) { + if (!events[i].id || events[i].id === id || event === 'load') { + setTimeout(function(fn) { + fn.call(this, id, msg); + }.bind(self, events[i].fn), 0); + + // If this event was setup with `once`, remove it. + if (events[i].once) { + self.off(event, events[i].fn, events[i].id); + } + } + } + + return self; + }, + + /** + * Queue of actions initiated before the sound has loaded. + * These will be called in sequence, with the next only firing + * after the previous has finished executing (even if async like play). + * @return {Howl} + */ + _loadQueue: function() { + var self = this; + + if (self._queue.length > 0) { + var task = self._queue[0]; + + // don't move onto the next task until this one is done + self.once(task.event, function() { + self._queue.shift(); + self._loadQueue(); + }); + + task.action(); + } + + return self; + }, + + /** + * Fired when playback ends at the end of the duration. + * @param {Sound} sound The sound object to work with. + * @return {Howl} + */ + _ended: function(sound) { + var self = this; + var sprite = sound._sprite; + + // If we are using IE and there was network latency we may be clipping + // audio before it completes playing. Lets check the node to make sure it + // believes it has completed, before ending the playback. + if (!self._webAudio && sound._node && !sound._node.paused && !sound._node.ended && sound._node.currentTime < sound._stop) { + setTimeout(self._ended.bind(self, sound), 100); + return self; + } + + // Should this sound loop? + var loop = !!(sound._loop || self._sprite[sprite][2]); + + // Fire the ended event. + self._emit('end', sound._id); + + // Restart the playback for HTML5 Audio loop. + if (!self._webAudio && loop) { + self.stop(sound._id, true).play(sound._id); + } + + // Restart this timer if on a Web Audio loop. + if (self._webAudio && loop) { + self._emit('play', sound._id); + sound._seek = sound._start || 0; + sound._rateSeek = 0; + sound._playStart = Howler.ctx.currentTime; + + var timeout = ((sound._stop - sound._start) * 1000) / Math.abs(sound._rate); + self._endTimers[sound._id] = setTimeout(self._ended.bind(self, sound), timeout); + } + + // Mark the node as paused. + if (self._webAudio && !loop) { + sound._paused = true; + sound._ended = true; + sound._seek = sound._start || 0; + sound._rateSeek = 0; + self._clearTimer(sound._id); + + // Clean up the buffer source. + self._cleanBuffer(sound._node); + + // Attempt to auto-suspend AudioContext if no sounds are still playing. + Howler._autoSuspend(); + } + + // When using a sprite, end the track. + if (!self._webAudio && !loop) { + self.stop(sound._id); + } + + return self; + }, + + /** + * Clear the end timer for a sound playback. + * @param {Number} id The sound ID. + * @return {Howl} + */ + _clearTimer: function(id) { + var self = this; + + if (self._endTimers[id]) { + clearTimeout(self._endTimers[id]); + delete self._endTimers[id]; + } + + return self; + }, + + /** + * Return the sound identified by this ID, or return null. + * @param {Number} id Sound ID + * @return {Object} Sound object or null. + */ + _soundById: function(id) { + var self = this; + + // Loop through all sounds and find the one with this ID. + for (var i=0; i=0; i--) { + if (cnt <= limit) { + return; + } + + if (self._sounds[i]._ended) { + // Disconnect the audio source when using Web Audio. + if (self._webAudio && self._sounds[i]._node) { + self._sounds[i]._node.disconnect(0); + } + + // Remove sounds until we have the pool size. + self._sounds.splice(i, 1); + cnt--; + } + } + }, + + /** + * Get all ID's from the sounds pool. + * @param {Number} id Only return one ID if one is passed. + * @return {Array} Array of IDs. + */ + _getSoundIds: function(id) { + var self = this; + + if (typeof id === 'undefined') { + var ids = []; + for (var i=0; i 0) { + cache[self._src] = buffer; + loadSound(self, buffer); + } + }, function() { + self._emit('loaderror', null, 'Decoding audio data failed.'); + }); + }; + + /** + * Sound is now loaded, so finish setting everything up and fire the loaded event. + * @param {Howl} self + * @param {Object} buffer The decoded buffer sound source. + */ + var loadSound = function(self, buffer) { + // Set the duration. + if (buffer && !self._duration) { + self._duration = buffer.duration; + } + + // Setup a sprite if none is defined. + if (Object.keys(self._sprite).length === 0) { + self._sprite = {__default: [0, self._duration * 1000]}; + } + + // Fire the loaded event. + if (self._state !== 'loaded') { + self._state = 'loaded'; + self._emit('load'); + self._loadQueue(); + } + }; + + /** + * Setup the audio context when available, or switch to HTML5 Audio mode. + */ + var setupAudioContext = function() { + // Check if we are using Web Audio and setup the AudioContext if we are. + try { + if (typeof AudioContext !== 'undefined') { + Howler.ctx = new AudioContext(); + } else if (typeof webkitAudioContext !== 'undefined') { + Howler.ctx = new webkitAudioContext(); + } else { + Howler.usingWebAudio = false; + } + } catch(e) { + Howler.usingWebAudio = false; + } + + // Check if a webview is being used on iOS8 or earlier (rather than the browser). + // If it is, disable Web Audio as it causes crashing. + var iOS = (/iP(hone|od|ad)/.test(Howler._navigator && Howler._navigator.platform)); + var appVersion = Howler._navigator && Howler._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/); + var version = appVersion ? parseInt(appVersion[1], 10) : null; + if (iOS && version && version < 9) { + var safari = /safari/.test(Howler._navigator && Howler._navigator.userAgent.toLowerCase()); + if (Howler._navigator && Howler._navigator.standalone && !safari || Howler._navigator && !Howler._navigator.standalone && !safari) { + Howler.usingWebAudio = false; + } + } + + // Create and expose the master GainNode when using Web Audio (useful for plugins or advanced usage). + if (Howler.usingWebAudio) { + Howler.masterGain = (typeof Howler.ctx.createGain === 'undefined') ? Howler.ctx.createGainNode() : Howler.ctx.createGain(); + Howler.masterGain.gain.setValueAtTime(Howler._muted ? 0 : 1, Howler.ctx.currentTime); + Howler.masterGain.connect(Howler.ctx.destination); + } + + // Re-run the setup on Howler. + Howler._setup(); + }; + + // Add support for AMD (Asynchronous Module Definition) libraries such as require.js. + if (typeof define === 'function' && define.amd) { + define([], function() { + return { + Howler: Howler, + Howl: Howl + }; + }); + } + + // Add support for CommonJS libraries such as browserify. + if (typeof exports !== 'undefined') { + exports.Howler = Howler; + exports.Howl = Howl; + } + + // Define globally in case AMD is not available or unused. + if (typeof window !== 'undefined') { + window.HowlerGlobal = HowlerGlobal; + window.Howler = Howler; + window.Howl = Howl; + window.Sound = Sound; + } else if (typeof global !== 'undefined') { // Add to global in Node.js (for testing, etc). + global.HowlerGlobal = HowlerGlobal; + global.Howler = Howler; + global.Howl = Howl; + global.Sound = Sound; + } +})(); + + +/*! + * Spatial Plugin - Adds support for stereo and 3D audio where Web Audio is supported. + * + * howler.js v2.0.7 + * howlerjs.com + * + * (c) 2013-2017, James Simpson of GoldFire Studios + * goldfirestudios.com + * + * MIT License + */ + +(function() { + + 'use strict'; + + // Setup default properties. + HowlerGlobal.prototype._pos = [0, 0, 0]; + HowlerGlobal.prototype._orientation = [0, 0, -1, 0, 1, 0]; + + /** Global Methods **/ + /***************************************************************************/ + + /** + * Helper method to update the stereo panning position of all current Howls. + * Future Howls will not use this value unless explicitly set. + * @param {Number} pan A value of -1.0 is all the way left and 1.0 is all the way right. + * @return {Howler/Number} Self or current stereo panning value. + */ + HowlerGlobal.prototype.stereo = function(pan) { + var self = this; + + // Stop right here if not using Web Audio. + if (!self.ctx || !self.ctx.listener) { + return self; + } + + // Loop through all Howls and update their stereo panning. + for (var i=self._howls.length-1; i>=0; i--) { + self._howls[i].stereo(pan); + } + + return self; + }; + + /** + * Get/set the position of the listener in 3D cartesian space. Sounds using + * 3D position will be relative to the listener's position. + * @param {Number} x The x-position of the listener. + * @param {Number} y The y-position of the listener. + * @param {Number} z The z-position of the listener. + * @return {Howler/Array} Self or current listener position. + */ + HowlerGlobal.prototype.pos = function(x, y, z) { + var self = this; + + // Stop right here if not using Web Audio. + if (!self.ctx || !self.ctx.listener) { + return self; + } + + // Set the defaults for optional 'y' & 'z'. + y = (typeof y !== 'number') ? self._pos[1] : y; + z = (typeof z !== 'number') ? self._pos[2] : z; + + if (typeof x === 'number') { + self._pos = [x, y, z]; + self.ctx.listener.setPosition(self._pos[0], self._pos[1], self._pos[2]); + } else { + return self._pos; + } + + return self; + }; + + /** + * Get/set the direction the listener is pointing in the 3D cartesian space. + * A front and up vector must be provided. The front is the direction the + * face of the listener is pointing, and up is the direction the top of the + * listener is pointing. Thus, these values are expected to be at right angles + * from each other. + * @param {Number} x The x-orientation of the listener. + * @param {Number} y The y-orientation of the listener. + * @param {Number} z The z-orientation of the listener. + * @param {Number} xUp The x-orientation of the top of the listener. + * @param {Number} yUp The y-orientation of the top of the listener. + * @param {Number} zUp The z-orientation of the top of the listener. + * @return {Howler/Array} Returns self or the current orientation vectors. + */ + HowlerGlobal.prototype.orientation = function(x, y, z, xUp, yUp, zUp) { + var self = this; + + // Stop right here if not using Web Audio. + if (!self.ctx || !self.ctx.listener) { + return self; + } + + // Set the defaults for optional 'y' & 'z'. + var or = self._orientation; + y = (typeof y !== 'number') ? or[1] : y; + z = (typeof z !== 'number') ? or[2] : z; + xUp = (typeof xUp !== 'number') ? or[3] : xUp; + yUp = (typeof yUp !== 'number') ? or[4] : yUp; + zUp = (typeof zUp !== 'number') ? or[5] : zUp; + + if (typeof x === 'number') { + self._orientation = [x, y, z, xUp, yUp, zUp]; + self.ctx.listener.setOrientation(x, y, z, xUp, yUp, zUp); + } else { + return or; + } + + return self; + }; + + /** Group Methods **/ + /***************************************************************************/ + + /** + * Add new properties to the core init. + * @param {Function} _super Core init method. + * @return {Howl} + */ + Howl.prototype.init = (function(_super) { + return function(o) { + var self = this; + + // Setup user-defined default properties. + self._orientation = o.orientation || [1, 0, 0]; + self._stereo = o.stereo || null; + self._pos = o.pos || null; + self._pannerAttr = { + coneInnerAngle: typeof o.coneInnerAngle !== 'undefined' ? o.coneInnerAngle : 360, + coneOuterAngle: typeof o.coneOuterAngle !== 'undefined' ? o.coneOuterAngle : 360, + coneOuterGain: typeof o.coneOuterGain !== 'undefined' ? o.coneOuterGain : 0, + distanceModel: typeof o.distanceModel !== 'undefined' ? o.distanceModel : 'inverse', + maxDistance: typeof o.maxDistance !== 'undefined' ? o.maxDistance : 10000, + panningModel: typeof o.panningModel !== 'undefined' ? o.panningModel : 'HRTF', + refDistance: typeof o.refDistance !== 'undefined' ? o.refDistance : 1, + rolloffFactor: typeof o.rolloffFactor !== 'undefined' ? o.rolloffFactor : 1 + }; + + // Setup event listeners. + self._onstereo = o.onstereo ? [{fn: o.onstereo}] : []; + self._onpos = o.onpos ? [{fn: o.onpos}] : []; + self._onorientation = o.onorientation ? [{fn: o.onorientation}] : []; + + // Complete initilization with howler.js core's init function. + return _super.call(this, o); + }; + })(Howl.prototype.init); + + /** + * Get/set the stereo panning of the audio source for this sound or all in the group. + * @param {Number} pan A value of -1.0 is all the way left and 1.0 is all the way right. + * @param {Number} id (optional) The sound ID. If none is passed, all in group will be updated. + * @return {Howl/Number} Returns self or the current stereo panning value. + */ + Howl.prototype.stereo = function(pan, id) { + var self = this; + + // Stop right here if not using Web Audio. + if (!self._webAudio) { + return self; + } + + // If the sound hasn't loaded, add it to the load queue to change stereo pan when capable. + if (self._state !== 'loaded') { + self._queue.push({ + event: 'stereo', + action: function() { + self.stereo(pan, id); + } + }); + + return self; + } + + // Check for PannerStereoNode support and fallback to PannerNode if it doesn't exist. + var pannerType = (typeof Howler.ctx.createStereoPanner === 'undefined') ? 'spatial' : 'stereo'; + + // Setup the group's stereo panning if no ID is passed. + if (typeof id === 'undefined') { + // Return the group's stereo panning if no parameters are passed. + if (typeof pan === 'number') { + self._stereo = pan; + self._pos = [pan, 0, 0]; + } else { + return self._stereo; + } + } + + // Change the streo panning of one or all sounds in group. + var ids = self._getSoundIds(id); + for (var i=0; i Returns the group's values. + * pannerAttr(id) -> Returns the sound id's values. + * pannerAttr(o) -> Set's the values of all sounds in this Howl group. + * pannerAttr(o, id) -> Set's the values of passed sound id. + * + * Attributes: + * coneInnerAngle - (360 by default) A parameter for directional audio sources, this is an angle, in degrees, + * inside of which there will be no volume reduction. + * coneOuterAngle - (360 by default) A parameter for directional audio sources, this is an angle, in degrees, + * outside of which the volume will be reduced to a constant value of `coneOuterGain`. + * coneOuterGain - (0 by default) A parameter for directional audio sources, this is the gain outside of the + * `coneOuterAngle`. It is a linear value in the range `[0, 1]`. + * distanceModel - ('inverse' by default) Determines algorithm used to reduce volume as audio moves away from + * listener. Can be `linear`, `inverse` or `exponential. + * maxDistance - (10000 by default) The maximum distance between source and listener, after which the volume + * will not be reduced any further. + * refDistance - (1 by default) A reference distance for reducing volume as source moves further from the listener. + * This is simply a variable of the distance model and has a different effect depending on which model + * is used and the scale of your coordinates. Generally, volume will be equal to 1 at this distance. + * rolloffFactor - (1 by default) How quickly the volume reduces as source moves from listener. This is simply a + * variable of the distance model and can be in the range of `[0, 1]` with `linear` and `[0, ∞]` + * with `inverse` and `exponential`. + * panningModel - ('HRTF' by default) Determines which spatialization algorithm is used to position audio. + * Can be `HRTF` or `equalpower`. + * + * @return {Howl/Object} Returns self or current panner attributes. + */ + Howl.prototype.pannerAttr = function() { + var self = this; + var args = arguments; + var o, id, sound; + + // Stop right here if not using Web Audio. + if (!self._webAudio) { + return self; + } + + // Determine the values based on arguments. + if (args.length === 0) { + // Return the group's panner attribute values. + return self._pannerAttr; + } else if (args.length === 1) { + if (typeof args[0] === 'object') { + o = args[0]; + + // Set the grou's panner attribute values. + if (typeof id === 'undefined') { + if (!o.pannerAttr) { + o.pannerAttr = { + coneInnerAngle: o.coneInnerAngle, + coneOuterAngle: o.coneOuterAngle, + coneOuterGain: o.coneOuterGain, + distanceModel: o.distanceModel, + maxDistance: o.maxDistance, + refDistance: o.refDistance, + rolloffFactor: o.rolloffFactor, + panningModel: o.panningModel + }; + } + + self._pannerAttr = { + coneInnerAngle: typeof o.pannerAttr.coneInnerAngle !== 'undefined' ? o.pannerAttr.coneInnerAngle : self._coneInnerAngle, + coneOuterAngle: typeof o.pannerAttr.coneOuterAngle !== 'undefined' ? o.pannerAttr.coneOuterAngle : self._coneOuterAngle, + coneOuterGain: typeof o.pannerAttr.coneOuterGain !== 'undefined' ? o.pannerAttr.coneOuterGain : self._coneOuterGain, + distanceModel: typeof o.pannerAttr.distanceModel !== 'undefined' ? o.pannerAttr.distanceModel : self._distanceModel, + maxDistance: typeof o.pannerAttr.maxDistance !== 'undefined' ? o.pannerAttr.maxDistance : self._maxDistance, + refDistance: typeof o.pannerAttr.refDistance !== 'undefined' ? o.pannerAttr.refDistance : self._refDistance, + rolloffFactor: typeof o.pannerAttr.rolloffFactor !== 'undefined' ? o.pannerAttr.rolloffFactor : self._rolloffFactor, + panningModel: typeof o.pannerAttr.panningModel !== 'undefined' ? o.pannerAttr.panningModel : self._panningModel + }; + } + } else { + // Return this sound's panner attribute values. + sound = self._soundById(parseInt(args[0], 10)); + return sound ? sound._pannerAttr : self._pannerAttr; + } + } else if (args.length === 2) { + o = args[0]; + id = parseInt(args[1], 10); + } + + // Update the values of the specified sounds. + var ids = self._getSoundIds(id); + for (var i=0; i=0&&e<=1){if(o._volume=e,o._muted)return o;o.usingWebAudio&&o.masterGain.gain.setValueAtTime(e,n.ctx.currentTime);for(var t=0;t=0;o--)e._howls[o].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,_()),e},codecs:function(e){return(this||n)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||n;if(e.state=e.ctx?e.ctx.state||"running":"running",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{var o=new Audio;void 0===o.oncanplaythrough&&(e._canPlayEvent="canplay")}catch(n){e.noAudio=!0}else e.noAudio=!0;try{var o=new Audio;o.muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||n,o=null;try{o="undefined"!=typeof Audio?new Audio:null}catch(n){return e}if(!o||"function"!=typeof o.canPlayType)return e;var t=o.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator&&e._navigator.userAgent.match(/OPR\/([0-6].)/g),a=r&&parseInt(r[0].split("/")[1],10)<33;return e._codecs={mp3:!(a||!t&&!o.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!t,opus:!!o.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!o.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!o.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!o.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),aac:!!o.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!o.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(o.canPlayType("audio/x-m4a;")||o.canPlayType("audio/m4a;")||o.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(o.canPlayType("audio/x-mp4;")||o.canPlayType("audio/mp4;")||o.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!!o.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,""),webm:!!o.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,""),dolby:!!o.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(o.canPlayType("audio/x-flac;")||o.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_enableMobileAudio:function(){var e=this||n,o=/iPhone|iPad|iPod|Android|BlackBerry|BB10|Silk|Mobi/i.test(e._navigator&&e._navigator.userAgent),t=!!("ontouchend"in window||e._navigator&&e._navigator.maxTouchPoints>0||e._navigator&&e._navigator.msMaxTouchPoints>0);if(!e._mobileEnabled&&e.ctx&&(o||t)){e._mobileEnabled=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var r=function(){n._autoResume();var o=e.ctx.createBufferSource();o.buffer=e._scratchBuffer,o.connect(e.ctx.destination),void 0===o.start?o.noteOn(0):o.start(0),"function"==typeof e.ctx.resume&&e.ctx.resume(),o.onended=function(){o.disconnect(0),e._mobileEnabled=!0,e.mobileAutoEnable=!1,document.removeEventListener("touchstart",r,!0),document.removeEventListener("touchend",r,!0)}};return document.addEventListener("touchstart",r,!0),document.addEventListener("touchend",r,!0),e}},_autoSuspend:function(){var e=this;if(e.autoSuspend&&e.ctx&&void 0!==e.ctx.suspend&&n.usingWebAudio){for(var o=0;o0?i._seek:t._sprite[e][0]/1e3),s=Math.max(0,(t._sprite[e][0]+t._sprite[e][1])/1e3-_),l=1e3*s/Math.abs(i._rate);i._paused=!1,i._ended=!1,i._sprite=e,i._seek=_,i._start=t._sprite[e][0]/1e3,i._stop=(t._sprite[e][0]+t._sprite[e][1])/1e3,i._loop=!(!i._loop&&!t._sprite[e][2]);var c=i._node;if(t._webAudio){var f=function(){t._refreshBuffer(i);var e=i._muted||t._muted?0:i._volume;c.gain.setValueAtTime(e,n.ctx.currentTime),i._playStart=n.ctx.currentTime,void 0===c.bufferSource.start?i._loop?c.bufferSource.noteGrainOn(0,_,86400):c.bufferSource.noteGrainOn(0,_,s):i._loop?c.bufferSource.start(0,_,86400):c.bufferSource.start(0,_,s),l!==1/0&&(t._endTimers[i._id]=setTimeout(t._ended.bind(t,i),l)),o||setTimeout(function(){t._emit("play",i._id)},0)};"running"===n.state?f():(t.once("resume",f),t._clearTimer(i._id))}else{var p=function(){c.currentTime=_,c.muted=i._muted||t._muted||n._muted||c.muted,c.volume=i._volume*n.volume(),c.playbackRate=i._rate;try{var e=c.play();if("undefined"!=typeof Promise&&e instanceof Promise&&(t._playLock=!0,e.then(function(){t._playLock=!1,t._loadQueue()})),c.paused)return void t._emit("playerror",i._id,"Playback was unable to start. This is most commonly an issue on mobile devices where playback was not within a user interaction.");l!==1/0&&(t._endTimers[i._id]=setTimeout(t._ended.bind(t,i),l)),o||t._emit("play",i._id)}catch(e){t._emit("playerror",i._id,e)}},m=window&&window.ejecta||!c.readyState&&n._navigator.isCocoonJS;if(4===c.readyState||m)p();else{var v=function(){p(),c.removeEventListener(n._canPlayEvent,v,!1)};c.addEventListener(n._canPlayEvent,v,!1),t._clearTimer(i._id)}}return i._id},pause:function(e){var n=this;if("loaded"!==n._state||n._playLock)return n._queue.push({event:"pause",action:function(){n.pause(e)}}),n;for(var o=n._getSoundIds(e),t=0;t=0?o=parseInt(r[0],10):e=parseFloat(r[0])}else r.length>=2&&(e=parseFloat(r[0]),o=parseInt(r[1],10));var a;if(!(void 0!==e&&e>=0&&e<=1))return a=o?t._soundById(o):t._sounds[0],a?a._volume:0;if("loaded"!==t._state)return t._queue.push({event:"volume",action:function(){t.volume.apply(t,r)}}),t;void 0===o&&(t._volume=e),o=t._getSoundIds(o);for(var u=0;uo?"out":"in",_=Math.abs(n-o),s=_/.01,l=s>0?t/s:t;l<4&&(s=Math.ceil(s/(4/l)),l=4),e._fadeTo=o,e._interval=setInterval(function(){s>0&&(i+="in"===d?.01:-.01),i=Math.max(0,i),i=Math.min(1,i),i=Math.round(100*i)/100,u._webAudio?e._volume=i:u.volume(i,e._id,!0),a&&(u._volume=i),(on&&i>=o)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,u.volume(o,e._id),u._emit("fade",e._id))},l)},_stopFade:function(e){var o=this,t=o._soundById(e);return t&&t._interval&&(o._webAudio&&t._node.gain.cancelScheduledValues(n.ctx.currentTime),clearInterval(t._interval),t._interval=null,o.volume(t._fadeTo,e),t._fadeTo=null,o._emit("fade",e)),o},loop:function(){var e,n,o,t=this,r=arguments;if(0===r.length)return t._loop;if(1===r.length){if("boolean"!=typeof r[0])return!!(o=t._soundById(parseInt(r[0],10)))&&o._loop;e=r[0],t._loop=e}else 2===r.length&&(e=r[0],n=parseInt(r[1],10));for(var a=t._getSoundIds(n),u=0;u=0?o=parseInt(r[0],10):e=parseFloat(r[0])}else 2===r.length&&(e=parseFloat(r[0]),o=parseInt(r[1],10));var i;if("number"!=typeof e)return i=t._soundById(o),i?i._rate:t._rate;if("loaded"!==t._state)return t._queue.push({event:"rate",action:function(){t.rate.apply(t,r)}}),t;void 0===o&&(t._rate=e),o=t._getSoundIds(o);for(var d=0;d=0?o=parseInt(r[0],10):t._sounds.length&&(o=t._sounds[0]._id,e=parseFloat(r[0]))}else 2===r.length&&(e=parseFloat(r[0]),o=parseInt(r[1],10));if(void 0===o)return t;if("loaded"!==t._state)return t._queue.push({event:"seek",action:function(){t.seek.apply(t,r)}}),t;var i=t._soundById(o);if(i){if(!("number"==typeof e&&e>=0)){if(t._webAudio){var d=t.playing(o)?n.ctx.currentTime-i._playStart:0,_=i._rateSeek?i._rateSeek-i._seek:0;return i._seek+(_+d*Math.abs(i._rate))}return i._node.currentTime}var s=t.playing(o);s&&t.pause(o,!0),i._seek=e,i._ended=!1,t._clearTimer(o),s&&t.play(o,!0),!t._webAudio&&i._node&&(i._node.currentTime=e),t._emit("seek",o)}return t},playing:function(e){var n=this;if("number"==typeof e){var o=n._soundById(e);return!!o&&!o._paused}for(var t=0;t=0&&n._howls.splice(a,1)}var u=!0;for(t=0;t=0;a--)r[a].id&&r[a].id!==n&&"load"!==e||(setTimeout(function(e){e.call(this,n,o)}.bind(t,r[a].fn),0),r[a].once&&t.off(e,r[a].fn,r[a].id));return t},_loadQueue:function(){var e=this;if(e._queue.length>0){var n=e._queue[0];e.once(n.event,function(){e._queue.shift(),e._loadQueue()}),n.action()}return e},_ended:function(e){var o=this,t=e._sprite;if(!o._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime=0;t--){if(o<=n)return;e._sounds[t]._ended&&(e._webAudio&&e._sounds[t]._node&&e._sounds[t]._node.disconnect(0),e._sounds.splice(t,1),o--)}}},_getSoundIds:function(e){var n=this;if(void 0===e){for(var o=[],t=0;t0&&(r[o._src]=e,d(o,e))},function(){o._emit("loaderror",null,"Decoding audio data failed.")})},d=function(e,n){n&&!e._duration&&(e._duration=n.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},_=function(){try{"undefined"!=typeof AudioContext?n.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?n.ctx=new webkitAudioContext:n.usingWebAudio=!1}catch(e){n.usingWebAudio=!1}var e=/iP(hone|od|ad)/.test(n._navigator&&n._navigator.platform),o=n._navigator&&n._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),t=o?parseInt(o[1],10):null;if(e&&t&&t<9){var r=/safari/.test(n._navigator&&n._navigator.userAgent.toLowerCase());(n._navigator&&n._navigator.standalone&&!r||n._navigator&&!n._navigator.standalone&&!r)&&(n.usingWebAudio=!1)}n.usingWebAudio&&(n.masterGain=void 0===n.ctx.createGain?n.ctx.createGainNode():n.ctx.createGain(),n.masterGain.gain.setValueAtTime(n._muted?0:1,n.ctx.currentTime),n.masterGain.connect(n.ctx.destination)),n._setup()};"function"==typeof define&&define.amd&&define([],function(){return{Howler:n,Howl:o}}),"undefined"!=typeof exports&&(exports.Howler=n,exports.Howl=o),"undefined"!=typeof window?(window.HowlerGlobal=e,window.Howler=n,window.Howl=o,window.Sound=t):"undefined"!=typeof global&&(global.HowlerGlobal=e,global.Howler=n,global.Howl=o,global.Sound=t)}(); +/*! Spatial Plugin */ +!function(){"use strict";HowlerGlobal.prototype._pos=[0,0,0],HowlerGlobal.prototype._orientation=[0,0,-1,0,1,0],HowlerGlobal.prototype.stereo=function(n){var e=this;if(!e.ctx||!e.ctx.listener)return e;for(var t=e._howls.length-1;t>=0;t--)e._howls[t].stereo(n);return e},HowlerGlobal.prototype.pos=function(n,e,t){var o=this;return o.ctx&&o.ctx.listener?(e="number"!=typeof e?o._pos[1]:e,t="number"!=typeof t?o._pos[2]:t,"number"!=typeof n?o._pos:(o._pos=[n,e,t],o.ctx.listener.setPosition(o._pos[0],o._pos[1],o._pos[2]),o)):o},HowlerGlobal.prototype.orientation=function(n,e,t,o,r,a){var i=this;if(!i.ctx||!i.ctx.listener)return i;var p=i._orientation;return e="number"!=typeof e?p[1]:e,t="number"!=typeof t?p[2]:t,o="number"!=typeof o?p[3]:o,r="number"!=typeof r?p[4]:r,a="number"!=typeof a?p[5]:a,"number"!=typeof n?p:(i._orientation=[n,e,t,o,r,a],i.ctx.listener.setOrientation(n,e,t,o,r,a),i)},Howl.prototype.init=function(n){return function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],n.call(this,e)}}(Howl.prototype.init),Howl.prototype.stereo=function(e,t){var o=this;if(!o._webAudio)return o;if("loaded"!==o._state)return o._queue.push({event:"stereo",action:function(){o.stereo(e,t)}}),o;var r=void 0===Howler.ctx.createStereoPanner?"spatial":"stereo";if(void 0===t){if("number"!=typeof e)return o._stereo;o._stereo=e,o._pos=[e,0,0]}for(var a=o._getSoundIds(t),i=0;i=0;t--)e._howls[t].stereo(n);return e},HowlerGlobal.prototype.pos=function(n,e,t){var o=this;return o.ctx&&o.ctx.listener?(e="number"!=typeof e?o._pos[1]:e,t="number"!=typeof t?o._pos[2]:t,"number"!=typeof n?o._pos:(o._pos=[n,e,t],o.ctx.listener.setPosition(o._pos[0],o._pos[1],o._pos[2]),o)):o},HowlerGlobal.prototype.orientation=function(n,e,t,o,r,a){var i=this;if(!i.ctx||!i.ctx.listener)return i;var p=i._orientation;return e="number"!=typeof e?p[1]:e,t="number"!=typeof t?p[2]:t,o="number"!=typeof o?p[3]:o,r="number"!=typeof r?p[4]:r,a="number"!=typeof a?p[5]:a,"number"!=typeof n?p:(i._orientation=[n,e,t,o,r,a],i.ctx.listener.setOrientation(n,e,t,o,r,a),i)},Howl.prototype.init=function(n){return function(e){var t=this;return t._orientation=e.orientation||[1,0,0],t._stereo=e.stereo||null,t._pos=e.pos||null,t._pannerAttr={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:360,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:360,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:0,distanceModel:void 0!==e.distanceModel?e.distanceModel:"inverse",maxDistance:void 0!==e.maxDistance?e.maxDistance:1e4,panningModel:void 0!==e.panningModel?e.panningModel:"HRTF",refDistance:void 0!==e.refDistance?e.refDistance:1,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:1},t._onstereo=e.onstereo?[{fn:e.onstereo}]:[],t._onpos=e.onpos?[{fn:e.onpos}]:[],t._onorientation=e.onorientation?[{fn:e.onorientation}]:[],n.call(this,e)}}(Howl.prototype.init),Howl.prototype.stereo=function(e,t){var o=this;if(!o._webAudio)return o;if("loaded"!==o._state)return o._queue.push({event:"stereo",action:function(){o.stereo(e,t)}}),o;var r=void 0===Howler.ctx.createStereoPanner?"spatial":"stereo";if(void 0===t){if("number"!=typeof e)return o._stereo;o._stereo=e,o._pos=[e,0,0]}for(var a=o._getSoundIds(t),i=0;i"; + html+="
+ "+name+" x
"; + html+="
"; + html+="
"; + html+=""; + $("body").append(html); + docked.push(cid); + cwindows.push(cid); + if(open) toggle_chat_window(type,id); + redock(); +} + +function hide_settings() +{ + $("#content").html(""); + settings_shown=0; +} + +function prop_line(prop,value,args) +{ + var color="",bold=""; + if(!args) args={}; + if(args.bold) bold="font-weight: bold;"; + if(is_string(args)) color=args,args={}; + if(!color) color=args.color||"grey"; + return "
"+prop+": "+value+"
" +} + +function prop_remains(remains) +{ + if(remains<=1/60.0) return bold_prop_line("Seconds",to_pretty_float(remains*3600),"gray"); + else if(remains<1) return bold_prop_line("Minutes",to_pretty_float(remains*60),"gray"); + else return bold_prop_line("Hours",to_pretty_float(remains),"gray"); +} + +function bold_prop_line(prop,value,args) +{ + if(!args) args={}; + if(is_string(args)) args={color:args}; + if(window.is_bold) args.bold=true; + return prop_line(prop,value,args); +} + +function render_party_old(list) +{ + var html="
"; + if(list) + { + html+="
PARTY
"; + list.forEach(function(name){ + html+="
"+name+"
"; + }); + html+="
LEAVE
"; + } + html+="
"; + $("#partylist").html(html); + if(!list.length) $("#partylist").hide(); + else $("#partylist").css("display","inline-block"); +} + +function render_party() +{ + var html=""; + for(var name in party) + { + var member=party[name]; + html+="
"; + html+=sprite(member.skin,{cx:member.cx||[],rip:member.rip,scale:2,height:50,overflow:true}); + if(member.rip) html+="
RIP
"; + else html+="
"+name.substr(0,3).toUpperCase()+"
"; + html+="
"; + } + $("#newparty").html(html); + if(!party_list.length) $("#newparty").hide(); + else $("#newparty").show(); +} + +function duel_click(name) +{ + var sm_target=null; + I.A.forEach(function(member){ if(member.name==name) sm_target=member; }); + I.B.forEach(function(member){ if(member.name==name) sm_target=member; }); + if(sm_target) call_code_function_f("smart_move",sm_target); +} + +function render_member(member,space) +{ + var html=""; + if(space) html+="
"; + html+="
"; + html+=sprite(member.skin,{cx:member.cx||{},rip:member.rip}); + if(member.rip || !member.active) + { + html+="
RIP
"; + html+="
"; + } + else + { + html+="
"+member.name.substr(0,3).toUpperCase()+"
"; + var percent=member.hp/member.max_hp*99; + html+="
"; + } + html+="
"; + return html; +} + +function render_map() +{ + // Note: new_map_logic() - includes the initial messages + if(current_map=="abtesting" && S.abtesting && !window.abtesting) + { + $("#topmid").append("
A "+S.abtesting.A+"
5:00
B 0
"); reposition_ui(); + window.abtesting=true; + } + else if(current_map!="abtesting" && window.abtesting) + { + $("#abtesting").remove(); + window.abtesting=false; + } + + if(events.duel && (!I || !I.id || I.id!=events.duel)) + { + events.duel=false; + $("#duelui").remove(); + $(".badplaceforaui").html(""); + } + if(current_map=="duelland" && !events.duel) + { + events.duel=I.id; + $("#topmid").append("
0:60
"); + reposition_ui(); + } + if(events.duel) + { + if(I.seconds) $(".dueltime").html("0:"+("00"+I.seconds).slice(-2)); + else $(".dueltime").remove(); + + var html=""; + m_first=true; I.A.forEach(function(member){ html+=render_member(member,!m_first); m_first=false; }); + html+="
vs
"; + m_first=true; I.B.forEach(function(member){ html+=render_member(member,!m_first); m_first=false; }); + $(".badplaceforaui").html(html); + + } + +} + +function wabbit_click() +{ + if(!S.wabbit.live) + add_log("Wabbit spawns in "+parseInt(round(-msince(new Date(S.wabbit.spawn))))+" minutes"); + else + add_log("Engage Wabbit? Go","gray"); +} + +function emonster_click(id) +{ + if(!S[id] || !S[id].live && !S[id].spawn) + add_log(G.monsters[id].name+" hasn't spawned yet!"); + else if(!S[id].live) + add_log(G.monsters[id].name+" spawns in "+parseInt(round(-msince(new Date(S[id].spawn))))+" minutes"); + else + add_log("Engage "+G.monsters[id].name+"? Go","gray"); +} + +function render_rewards() +{ + show_json(S.rewards); +} + +function render_server() +{ + var html="",content=false; + if(quirks.crypt) + { + html+="
"; + html+="
"+item_container({skin:G.items.cryptkey.skin,bcolor:"black"})+"
"; + html+="
INFO
"; + html+="
"; + content=true; + } + if(quirks.darkmage) + { + html+="
"; + html+="
"+item_container({skin:G.items.frozenkey.skin,bcolor:"black"})+"
"; + html+="
INFO
"; + html+="
"; + content=true; + } + if(quirks.fishing) + { + html+="
"; + html+="
"+item_container({skin:G.items.rod.skin,bcolor:"black"})+"
"; + html+="
INFO
"; + html+="
"; + content=true; + } + if(quirks.mining) + { + html+="
"; + html+="
"+item_container({skin:G.items.pickaxe.skin,bcolor:"black"})+"
"; + html+="
INFO
"; + html+="
"; + content=true; + } + if(gameplay=="hardcore") + { + $(".rewardsbutton").css("display","inline-block"); + $(".minutesui").css("display","inline-block"); + var hours="0"+parseInt(S.minutes/60); + var minutes=S.minutes%60; if(!minutes) minutes="00"; else if(minutes<10) minutes="0"+minutes; + $(".minutesui").html(hours+":"+minutes); + } + ["crabxx","goobrawl","abtesting","franky","icegolem"].forEach(function(type){ + if(S[type]) + { + var scolor="#ECECEC",lcolor="#ECECEC",lphrase="EVENT!",s=type; + if(type=="goobrawl") lcolor="#FF5D34",s="rgoo"; + if(type=="abtesting") lcolor="#E10029",s="thehelmet"; + else if(G.monsters[type] && G.monsters[type].announce) lcolor=G.monsters[type].announce; + html+="
"; + html+=sprite(s,{overflow:true}); + html+="
"+lphrase+"
"; + html+="
"; + content=true; + } + }); + ["wabbit","mrpumpkin","mrgreen","snowman","dragold","grinch","pinkgoo","slenderman","tiger"].forEach(function(type){ + if(S[type]) + { + var scolor="#ECECEC",lcolor="#ECECEC",lphrase="LIVE"; + if(type=="snowman") lcolor=colors.xmasgreen,scolor=colors.xmas; + if(type=="grinch") scolor=colors.xmasgreen,lcolor=colors.xmas,lphrase="BEWARE"; + html+="
"; + html+=sprite(type,{overflow:true}); + if(!S[type].live) + html+="
"+parseInt(round(-msince(new Date(S[type].spawn))))+"M
"; + else if(S[type].target) + html+="
JOIN
"; + else + html+="
"+lphrase+"
"; + html+="
"; + content=true; + } + }); + if(S.halloween) + { + html+="
"; + html+="
"+item_container({skin:"candy0",bcolor:"black"})+"
"; + html+="
INFO
"; + html+="
"; + content=true; + } + if(S.holidayseason) + { + html+="
"; + html+="
"+item_container({skin:"candycane",bcolor:"black"})+"
"; + html+="
INFO
"; + html+="
"; + content=true; + } + if(S.lunarnewyear) + { + html+="
"; + html+="
"+item_container({skin:"greenenvelope",bcolor:"black"})+"
"; + html+="
INFO
"; + html+="
"; + content=true; + } + if(S.egghunt) + { + html+="
"; + html+="
"+item_container({skin:"basketofeggs",bcolor:"black"})+"
"; + html+="
INFO
"; + html+="
"; + content=true; + } + if(S.valentines) + { + html+="
"; + html+="
"+item_container({skin:"cupid",bcolor:"black"})+"
"; + html+="
INFO
"; + html+="
"; + content=true; + } + $("#serverinfo").html(html); + if(!content) $("#serverinfo").hide(); + else $("#serverinfo").show(); +} + +function render_character_sheet() +{ + var html="
"; + html+="
Class: "+to_title(character.ctype)+"
"; + html+="
Level: "+character.level+"
"; + html+="
XP: "+to_pretty_num(character.xp)+" / "+to_pretty_num(character.max_xp)+"
"; + var divider=1,disclaimer=""; + if(pvp && !(!is_pvp && G.maps[character.map].safe_pvp)) divider=10,disclaimer="(PVP)"; + var lost_xp=floor(min(max(character.max_xp*0.01/divider,character.xp*0.02/divider),character.xp)); + if(character.ctype!="merchant") html+="
Max XP Loss: "+to_pretty_num(lost_xp)+" "+disclaimer+"
"; + if(character.party && party && party[character.name]) html+="
Party: "+round(party[character.name].share*100)+"% (Your Share)
"; + if(character.ctype=="merchant") html+="
Tax: "+(character.tax*100)+"%
"; + if(character.ctype=="priest") + { + html+="
Heal: "+character.attack+"
"; + html+="
Attack: "+round(character.attack*0.4)+"
"; + } + else html+="
Attack: "+character.attack+"
"; + html+="
Attack Speed: "+round(character.frequency*100)+"
"; + html+="
Strength: "+character.str+"
"; + html+="
Intelligence: "+character['int']+"
"; + html+="
Dexterity: "+character.dex+"
"; + html+="
Vitality: "+character.vit+"
"; + html+="
Fortitude: "+character['for']+" ("+parseInt((1-damage_multiplier(character['for']*5))*10000.0)/100.0+"%)
"; + html+="
Armor: "+character.armor+" ("+parseInt((1-damage_multiplier(character.armor))*10000.0)/100.0+"%)
"; + html+="
Resistance: "+character.resistance+" ("+parseInt((1-damage_multiplier(character.resistance))*10000.0)/100.0+"%)
"; + html+="
Courage: "+character.courage+" | "+character.mcourage+" | "+character.pcourage+"
"; + html+="
Speed: "+character.speed+"
"; + html+="
MP Cost: "+character.mp_cost+"
"; + if(character.lifesteal) html+="
Lifesteal: "+to_pretty_float(character.lifesteal)+"%
"; + if(character.manasteal) html+="
Manasteal: "+to_pretty_float(character.manasteal)+"%
"; + if(character.dreturn) html+="
Damage Return: "+to_pretty_float(character.dreturn)+"%
"; + if(character.reflection) html+="
Reflection: "+to_pretty_float(character.reflection)+"%
"; + if(character.evasion) html+="
Evasion: "+to_pretty_float(character.evasion)+"%
"; + if(character.miss) html+="
Miss: "+to_pretty_float(character.miss)+"%
"; + if(character.crit) html+="
Crit: "+to_pretty_float(character.crit)+"%
"; + if(character.critdamage) html+="
Critical Damage: "+to_pretty_float(200+character.critdamage)+"%
"; + if(character.apiercing) html+="
Armor Piercing: "+character.apiercing+"
"; + if(character.rpiercing) html+="
Resistance Piercing: "+character.rpiercing+"
"; + if(character.goldm!=1) + { + if(character.party && party && party[character.name] && party[character.name].gold) + html+="
Gold: "+round(character.goldm*100-party[character.name].gold)+"% +"+party[character.name].gold+"%
"; + else html+="
Gold: "+round(character.goldm*100)+"%
"; + } + if(character.xpm!=1) + { + if(character.party && party && party[character.name] && party[character.name].xp) + html+="
Experience: "+round(character.xpm*100-party[character.name].xp)+"% +"+party[character.name].xp+"%
"; + else html+="
Experience: "+round(character.xpm*100)+"%
"; + } + if(character.luckm!=1) + { + if(character.party && party && party[character.name] && party[character.name].luck) + html+="
Luck: "+round(character.luckm*100-party[character.name].luck)+"% +"+party[character.name].luck+"%
"; + else html+="
Luck: "+round(character.luckm*100)+"%
"; + } + html+="
"; + $("#rightcornerui").html(html); + topright_npc="character"; +} + +function render_conditions(player) +{ + var html="
",current=0,rids=[]; + for(var condition in player.s) + { + if(G.skills[condition] && G.skills[condition].ui) + { + console.log("here"); + var def=G.skills[condition],rid=randomStr(30); + html+=item_container({skin:def.skin,loader:"cplc"+rid}); + rids.push([rid,24000,player.s[condition].ms]); + current+=1; + continue; + } + var prop=G.conditions[condition],actual=player.s[condition]; + if(!actual.skin && (!prop || (!prop.ui && (!actual.s || actual.s<20)))) continue; + if(player.type=="monster" && condition=="poisonous") continue; + if(current>0 && !(current%2)) html+="
"; + current+=1; + html+=item_container({skin:actual.skin||prop.skin,onclick:"condition_click('"+condition+"')"},actual); + } + for(var event in (player.q||{})) + { + if(event=="exchange") + { + var level=0; + var name=player.q.exchange.name; + var q=undefined; + // if(player.q.exchange.s) level=player.q.exchange.s; + // if(player.q.exchange.q>1) q=player.q.exchange.q; + current+=1; + html+=item_container({skin:G.items[name].skin,bcolor:"#E9973A"},{name:name,level:level,q:q}); + } + } + html+="
"; + if(current) + { + if($('.rconditions').length) $('.rconditions').replaceWith(html); + else $(".renderedinfo").append(html); + if(rids.length) + { + for(var i=0;i").appendTo("body").click(function(event){ + event.stopPropagation(); + event.preventDefault(); + var elements=document.elementsFromPoint(event.pageX,event.pageY); + for(var i=0;i"; + if(monster.dead) name+=" X",monster.hp=0; + if(monster.level>1) name+=" Lv."+monster.level; + var hp=monster.hp,max_hp=monster.max_hp,xp=monster.xp; + if(max_hp>=1000000) hp=to_pretty_num(hp),max_hp=to_pretty_num(max_hp); + if(xp>=1000000) xp=to_pretty_num(xp); + html+=info_line({line:name,color:"gray",onclick:"render_monster_info('"+monster.mtype+"')"}); + html+=info_line({name:"HP",color:colors.hp,value:hp+"/"+max_hp,cursed:monster.s.cursed,stunned:!monster.attack&&monster.s.stunned,poisoned:!monster.attack&&monster.s.poisoned}); + html+=info_line({name:"XP",color:"green",value:xp}); + if(monster.attack) html+=info_line({name:"ATT",color:"#316EE6",value:smart_num(monster.attack,10000),stunned:monster.s.stunned,poisoned:monster.s.poisoned}); + if(def.avoidance) html+=info_line({name:"AVOIDANCE",color:"gray",value:def.avoidance+"%"}); + if(def.evasion) html+=info_line({name:"EVASION",color:"gray",value:def.evasion+"%"}); + if(def.reflection) html+=info_line({name:"REFLECT.",color:"gray",value:def.reflection+"%"}); + if(def.dreturn) html+=info_line({name:"D.RETURN",color:"gray",value:def.dreturn+"%"}); + if(monster.armor) html+=info_line({name:"ARMOR",color:"gray",value:monster.armor}); + if(monster.resistance) html+=info_line({name:"RESIST.",color:"gray",value:monster.resistance}); + if(def.rpiercing) html+=info_line({name:"PIERCE.",color:"gray",value:def.rpiercing}); + if(def.apiercing) html+=info_line({name:"PIERCE.",color:"gray",value:def.apiercing}); + if(def.explosion) html+=info_line({name:"EXPL.",color:"gray",value:def.explosion}); + if(monster.lifesteal) html+=info_line({name:"LIFESTEAL",color:colors.lifesteal,value:monster.lifesteal+"%"}); + if(monster["1hp"]) html+=info_line({line:"1HP HITS",color:"#AEAEAE"}); + if(monster.cooperative) html+=info_line({line:"COOPERATIVE",color:"#AEAEAE"}); + if(def.immune) html+=info_line({line:"IMMUNE",color:"#AEAEAE"}); + if(def.peaceful) html+=info_line({line:"PEACEFUL",color:"#54B25F"}); + if(def.supporter) html+=info_line({line:"SUPPORTER",color:"#CA5931"}); + if(def.spawns) html+=info_line({line:"SPAWNS",color:"#AEAEAE"}); + if(def.abilities) + { + for(var id in def.abilities) + { + if(!G.skills[id]) continue; + html+=info_line({name:def.abilities[id].aura&&"AURA"||"ABILITY",color:"#FC5F39",value:G.skills[id].name.toUpperCase(),onclick:"dialogs_target=xtarget||ctarget; render_skill('#topleftcornerdialog','"+id+"')"}); + } + } + if(def.spawns) + { + def.spawns.forEach(function(s){ + html+=info_line({name:"SPAWNS",color:"#237B2A",value:G.monsters[s[1]].name.toUpperCase(),onclick:"render_monster_info('"+s[1]+"')"}); + }) + } + if(monster.target) html+=info_line({name:"TRG",color:"orange",value:monster.target}); + if(monster.pet) + { + html+=info_line({name:"NAME",value:monster.name,color:"#5CBD97"}); + html+=info_line({name:"PAL",value:monster.owner,color:"#CF539B"}); + } + if(monster.heal) + { + html+=info_line({line:"SELF HEALING",color:"#9E6367"}); + } + if(character) + { + var diff=calculate_difficulty(monster); + if(diff>=2) html+=info_line({name:"DIFF.",color:"gray",value:"Hard",vcolor:"#ED4047"}); + else if(diff) html+=info_line({name:"DIFF.",color:"gray",value:"Challenging",vcolor:"#EF9232"}); + else html+=info_line({name:"DIFF.",color:"gray",value:"Easy",vcolor:"#8BF54D"}); + } + if(def.poisonous) + { + html+=info_line({line:"POISONOUS",color:colors.poison}); + } + if(def.explanation) + { + html+=info_line({line:def.explanation,color:"gray"}); + } + html+=button_line({name:"{}: INSPECT",onclick:"ui_inspect(xtarget||ctarget)",color:colors.inspect}); + html+=""; + $("#topleftcornerui").html(html); + render_conditions(monster); +} + +var cache_bid=-1; +function render_character(player) +{ + var html="
",cccx=$('.cccx').length,ihtml="",bhtml="",xhtml="",already=false; + if($('.renderedinfo').length && $('.renderedinfo').data('id')==player.id) already=true; + html+=info_line({name:player.role&&player.role.toUpperCase()||"NAME",color:player.role&&"#E14F8B"||"gray",value:player.name,onclick:"render_cosmetics(xtarget||ctarget,{toggle:true})"}); + html+="
"; + ihtml+=info_line({name:"LEVEL",color:"orange",value:player.level,afk:player.afk}); + ihtml+=info_line({name:"HP",color:colors.hp,value:player.hp+"/"+player.max_hp}); + ihtml+=info_line({name:"MP",color:"#365DC5",value:player.mp+"/"+player.max_mp}); + if(player.heal) ihtml+=info_line({name:"HEAL",color:"#CB83AC",value:round(player.heal)}); + ihtml+=info_line({name:"ATT",color:"green",value:round(player.attack),cursed:player.s.cursed}); + ihtml+=info_line({name:"ATTSPD",color:"gray",value:round(player.frequency*100),poisoned:player.s.poisoned}); + ihtml+=info_line({name:"RANGE",color:"gray",value:player.range}); + ihtml+=info_line({name:"RUNSPD",color:"gray",value:round(player.speed)}); + ihtml+=info_line({name:"ARMOR",color:"gray",value:player.armor||0}); + ihtml+=info_line({name:"RESIST.",color:"gray",value:player.resistance||0}); + + if(player.code) ihtml+=info_line({name:"CODE",color:"gold",value:"Active"}); + if(player.party) ihtml+=info_line({name:"PARTY",color:"#FF4C73",value:player.party}); + html+=ihtml; + html+="
"; + html+="
"; + xhtml+=button_line({name:"{}: INSPECT",onclick:"ui_inspect(xtarget||ctarget)",color:colors.inspect}); + html+=xhtml; + html+="
"; + var bid=player.party+"|"+player.stand+"|"+(character.slots.trade1!==undefined); + html+="
"; + if(!player.party && character && !player.me && !player.stand) + bhtml+=button_line({name:"PARTY",onclick:"socket.emit('party',{event:'invite',id:'"+player.id+"'}); push_deferred('party')",color:"#6F3F87",pm_onclick:"cpm_window('"+(player.controller||player.name)+"')"}); + if(character && !player.me && (character.party && player.party==character.party && party_list.indexOf(character.name)"+info.value+""; + if(info.afk && info.afk=="bot") addition=" [BOT]"; + else if(info.afk && info.afk=="code") addition=" [CODE]"; + else if(info.afk) addition=" [AFK]"; + if(info.cursed) addition=" [C]"; + if(info.poisoned) addition=" [P]"; + if(info.stunned) addition=" [STUN]"; + if(info.line) + { + if(info.onclick) info.line=""+info.line+""; + html+=""+info.line+""+addition+"
"; + } + else if(info.vcolor) html+=""+info.name+": "+info.value+addition+"
"; + else html+=""+info.name+": "+info.value+addition+"
"; + return html; +} + +function button_line(button,no_newline) +{ + var html="",color=button.color||"white"; + html+=""+button.name+" "; + if(button.pm_onclick) html+=" PM "; + if(!no_newline) html+="
"; + return html; +} + +var cache_slots={},cache_sid=-1; +function render_slots(player,args) +{ + if(!args) args={}; + function render_slot(slot,shade,op) + { + var ecolor=undefined,chtml="",cached=cache_slots&&cache_slots[slot],cid='slot'+slot; // empty border color + if(!window.mode || mode.empty_borders_darker) ecolor="#222424",ecolor="#292929"; //,ecolor="black"; + if(!op) op=0.4; + if(player.slots[slot]) + { + var current=player.slots[slot]; + var id='item'+randomStr(10),item=G.items[current.name]; + if(!item) item=G.items.placeholder_m; + var skin=current.skin||item.skin; + if(current.expires) skin=item.skin_a; + if((current.name=="tristone" || current.name=="darktristone") && (player.skin.startsWith("mm_") || player.skin.startsWith("mf_") || player.skin.startsWith("tm_") || player.skin.startsWith("tf_"))) skin=item.skin_a; + chtml+=item_container({skin:skin, + onclick:args.merchant&&"mslot_click('"+player.name+"','"+slot+"')"||args.gallery&&window['slots'+player.name]&&"pslot_click('"+player.name+"','"+slot+"')"||args.gallery&&"render_item_info('"+current.name+"',"+current.level+")"||"slot_click('"+slot+"')", + def:item,id:id,cid:cid,draggable:player.me, + sname:player.me&&slot,shade:shade,s_op:op,slot:slot},current); // num:slot is new [06/08/16] + } + else if(in_arr(slot,trade_slots) && player.me) chtml+=item_container({size:40,draggable:player.me,shade:shade,s_op:op,slot:slot,cid:cid,onclick:"wishlist_click('"+slot+"')",bcolor:ecolor}); + else chtml+=item_container({size:40,draggable:player.me,shade:shade,s_op:op,slot:slot,cid:cid,bcolor:ecolor}); + html+=chtml; + if(already && !ui_items_same(cached,current)) + $('#slot'+slot).replaceWith(chtml); + } + var my_slots=(player.me && player.slots.trade1!==undefined || (player.slots.trade1||player.slots.trade2||player.slots.trade3||player.slots.trade4)) && !player.stand; + var draggable=player.me,already=false,sid=player.stand+"|"+my_slots; + if(!args.pure && $('.slots').length && $('.slots').data('id')==player.id && sid==cache_sid) already=true; else cache_slots={}; + var html="
"; + if(args.pure) html=""; + if(player.stand) + { + var row=4,col=4,found=false; + for(var t=30;t>=25;t--) + if(("trade"+t) in player.slots) row=5,col=6,found=true; + for(var t=24;t>=17;t--) + if(!found && ("trade"+t) in player.slots) row=4,col=6,found=true; + html+="
" + for(var i=0;i{}
" + if(args.cx && 0) html+="
COSMETICS
" + if(!args.pure) html+="
"; + if(!args.pure && !already) + { + if($('.slots').length) $('.slots').replaceWith(html); + else $("#topleftcornerui").append(html); + } + cache_slots=Object.assign({},player.slots); cache_sid=sid; + return html; // for character.html [19/11/18] + // console.log(JSON.stringify(collection)); +} + +function render_transports_npc() +{ + reset_inventory(1); + topleft_npc="transports"; rendered_target=topleft_npc; + e_item=null; + var html="
"; + html+="
> Mainland
"; + html+="
> Winterland
"; // XMAS!! + // html+="
> New Town [Very Soon!]
"; + // html+="
> Underworld
"; // [Soon!] + html+="
> Desertland
"; // [Soon!] + // html+="
> Spooky Forest
"; // [Halloween!] + if(S.duels) + { + for(var name in S.duels) + { + var duel=S.duels[name]; + html+="
> Duelland "+duel.challenger+" vs "+duel.vs+"
"; + } + } + html+="
"; + $("#topleftcornerui").html(html); +} + +function send_mainframe_command() +{ + var command=$(".maincommand").html(); + command=command.replace(" ",""); + //show_json(command); + socket.emit("eval",{command:command}); + $(".maincommand").html(""); + setTimeout(function() { + $(".maincommand").cfocus(); + },0); +} + +function render_mainframe() +{ + reset_inventory(1); + topleft_npc="mainframe"; rendered_target=topleft_npc; + var html="
"; + html+="
mainframe> connected
"; + html+="
mainframe>
"; + html+="
logout
"; + html+="
"; + $("#topleftcornerui").html(html); + $(".maincommand").keydown(function(e){ + if(e.keyCode===13) + { + send_mainframe_command(); + return false; + } + }); + setTimeout(function() { + $(".maincommand").cfocus(); + },0); +} + + +function render_gold_npc() +{ + reset_inventory(1); + topleft_npc="gold"; rendered_target=topleft_npc; + e_item=null; + var html="
"; + html+="
GOLD: "+(character.user&&to_pretty_num(character.user.gold)||"Unavailable")+"
"; + html+="
Amount:
0
"; + html+="
"; + if(options.bank_max) html+="
MAX
"; + html+="
DEPOSIT
WITHDRAW
"; + html+="
"; + $("#topleftcornerui").html(html); + cfocus('.npcgold'); +} + +var last_rendered_items="items0"; +function render_items_npc(pack) +{ + if(!character.user) return; + if(!pack) pack=last_rendered_items; + if(pack && !character.user[pack]) + { + render_interaction("unlock_"+pack,undefined,{pack:pack}); + topleft_npc="items"; rendered_target=topleft_npc; last_rendered_items=pack; // needs to be after render_interaction + return; + } + last_rendered_items=pack; + reset_inventory(1); + topleft_npc="items"; rendered_target=topleft_npc; + var collection=[],last=0,items=character.user[pack]||[]; + var html="
"; + html+="
"; + $("#topleftcornerui").html(html); + if(!inventory) render_inventory(),inventory_opened_for=topleft_npc; +} + +function render_dismantler() +{ + var shade="fclaw",button="DISMANTLE"; + reset_inventory(1); + topleft_npc="dismantler"; rendered_target=topleft_npc; + ds_item=null; + var html="
"; + /*html+="
"; + html+="
"; + html+="
"; + //html+="
";*/ + html+="
"; + html+=item_container({shade:shade,cid:'dsitem',s_op:0.36,draggable:false,droppable:true}); + html+="
"; + //html+="
"; + /*html+="
"; + html+="
"; + html+="
";*/ + html+="
"+button+"
"; + html+="
"; + $("#topleftcornerui").html(html); + if(!inventory) render_inventory(),inventory_opened_for=topleft_npc; +} + +var last_lmode="lock"; +function render_locksmith(mode) +{ + if(!mode) mode=last_lmode; last_lmode=mode; + var button="LOCK",f="lock_item",shade="shade_seal"; + if(mode=="unlock") button="UNLOCK",f="unlock_item",shade="shade_unlock"; + if(mode=="seal") button="SEAL",f="seal_item",shade="shade_lock"; + reset_inventory(1); + topleft_npc="locksmith"; rendered_target=topleft_npc; + l_item=null; + var html="
"; + /*html+="
"; + html+="
"; + html+="
"; + //html+="
";*/ + html+="
"; + html+=item_container({shade:shade,cid:'litem',s_op:0.4,draggable:false,droppable:true}); + html+="
"; + //html+="
"; + /*html+="
"; + html+="
"; + html+="
";*/ + html+="
"+button+"
"; + html+="
"; + $("#topleftcornerui").html(html); + if(!inventory) render_inventory(),inventory_opened_for=topleft_npc; +} + +function render_recipe(element,type,name) +{ + last_selector="#recipe-item"; + var html; + if(type!="dismantle") + { + html=render_item("html",{item:G.items[name],name:name,craft:true}); + } + else + { + html=render_item("html",{item:G.items[name],name:name,dismantle:true}); + } + if(element) + $("#recipe-item").html(html); + else + show_modal(html,{wrap:false,hideinbackground:true}); +} + +var r_page={}; +function render_recipes(type) +{ + if(!type) type=""; + reset_inventory(1); + topleft_npc="recipes"; rendered_target=topleft_npc; + var last=0,items=[]; + var html="
"; + if(type=="dismantle") + { + object_sort(G.dismantle,"gold_value").forEach(function(e){ + items.push(e[0]); + }); + } + else + { + object_sort(G.craft,"gold_value").forEach(function(e){ + if((e[1].quest||"")!=type) return; + items.push(e[0]); + }); + } + r_page[type]=r_page[type]||0; + if(r_page[type]>=1) last+=19+(r_page[type]-1)*18; + for(var i=0;i<4;i++) + { + html+="
" + for(var j=0;j<5;j++) + { + if(i==3 && j==0 && r_page[type]!=0) html+=item_container({skin:"left",onclick:"r_page['"+type+"']="+(r_page[type]-1)+"; render_recipes('"+type+"');"},{q:r_page[type],left:true}); + else if(i==3 && j==4 && last"; + next_side_interaction=null; + $("#topleftcornerui").html(html); +} + +function render_recipes_old(quest) +{ + topleft_npc="recipes"; rendered_target=topleft_npc; i=0; + var html="
"; + html+="
CRAFT
"; + object_sort(G.craft).forEach(function(io){ + if(io[1].quest!=quest) return; + var name=io[0]; + html+=item_container({skin:G.items[name].skin,onclick:"render_recipe(null,'craft','"+name+"')"},{name:name}); + i+=1; + if(!(i%6)) html+="
"; + }); + html+="
DISMANTLE
"; i=0; + object_sort(G.dismantle).forEach(function(io){ + if(io[1].quest!=quest) return; + var name=io[0]; + html+=item_container({skin:G.items[name].skin,onclick:"render_recipe(null,'dismantle','"+name+"')"},{name:name}); + i+=1; + if(!(i%6)) html+="
"; + }); + html+="
"; + $("#topleftcornerui").html(html); +} + +function render_exchange_shrine(type) +{ + var shade="shade_exchange",button="EXCHANGE"; + var originals=[e_item]; + reset_inventory(1); + topleft_npc="exchange"; rendered_target=topleft_npc; exchange_type=type; + if(type=="leather") shade="leather",button="GIVE"; + if(type=="lostearring") shade="lostearring",button="PROVIDE"; + if(type=="mistletoe") shade="mistletoe",button="GIVE IT"; + if(type=="candycane") shade="candycane",button="FEED"; + if(type=="ornament") shade="ornament",button="GIVE"; + if(type=="seashell") shade="seashell",button="GIVE"; + if(type=="gemfragment") shade="gemfragment",button="PROVIDE"; + if(type=="cx") shade="cosmo0",button="SHAZAM"; + e_item=null; + var html="
"; + html+="
"; + html+="
"; + html+="
"; + //html+="
"; + if(character.q.exchange) + { + var level=character.q.exchange.s||0; + var name=character.q.exchange.name; + var q=undefined; + if(character.q.exchange.q>1) q=character.q.exchange.q; + html+=item_container({cid:'eitem',draggable:false,droppable:false,skin:G.items[name].skin},{name:name,level:level,q:q}); + } + else html+=item_container({shade:shade,cid:'eitem',s_op:0.5,draggable:false,droppable:true}); + //html+="
"; + html+="
"; + html+="
"; + html+="
"; + html+="
"+button+"
"; + html+="
"; + html+="
"+"
"; + $("#topleftcornerui").html(html); + if(!inventory) render_inventory(),inventory_opened_for=topleft_npc; + return !character.q.exchange&&originals||[]; +} + +function render_pet_shrine() +{ + var button="RELEASE"; + var originals=[e_item]; + reset_inventory(1); + e_item=null; + var html="
"; + html+="
"; + html+="
"; + html+="
"; + //html+="
"; + if(character.q.exchange) + { + var level=character.q.exchange.s||0; + var name=character.q.exchange.name; + var q=undefined; + if(character.q.exchange.q>1) q=character.q.exchange.q; + html+=item_container({cid:'eitem',draggable:false,droppable:false,skin:G.items[name].skin},{name:name,level:level,q:q}); + } + else + { + html+=item_container({shade:"pball",cid:'eitem',s_op:0.5,draggable:false,droppable:true}); + html+=item_container({shade:"chry",cid:'eitem',s_op:0.5,draggable:false,droppable:true}); + } + //html+="
"; + html+="
"; + html+="
"; + html+="
"; + html+="
RELEASE
"; + html+="
"; + $("#topleftcornerui").html(html); + if(!inventory) render_inventory(),inventory_opened_for=topleft_npc; + return !character.q.exchange&&originals||[]; +} + +function render_none_shrine(type) +{ + var shade="cape0",button="POOF"; + reset_inventory(1); + topleft_npc="none"; rendered_target=topleft_npc; + p_item=null; + var html="
"; + html+="
"; + html+="
"; + html+="
"; + //html+="
"; + html+=item_container({shade:shade,cid:'pitem',s_op:0.5,draggable:false,droppable:true}); + //html+="
"; + html+="
"; + html+="
"; + html+="
"; + html+="
"+button+"
"; + html+="
"; + $("#topleftcornerui").html(html); + if(!inventory) render_inventory(),inventory_opened_for=topleft_npc; +} + +function render_shells_buyer() +{ + topleft_npc="buyshells"; rendered_target=topleft_npc; + var html="
",prefix=""; + html+="
10 Shells = 1,500,000 BUY
"; + html+="
100 Shells = 15,000,000 BUY
"; + html+="
500 Shells = 75,000,000 BUY
"; + html+="
1,000 Shells = 150,000,000 BUY
"; + if(!is_electron) prefix="Buy With $ | " + html+="
"+prefix+"Nope
"; + html+="
"; + $("#topleftcornerui").html(html); + if(!inventory) render_inventory(),inventory_opened_for=topleft_npc; +} + +function render_upgrade_shrine(explicit) +{ + reset_inventory(1); + var originals=[u_item,u_scroll,u_offering],already=(topleft_npc=="upgrade"); + topleft_npc="upgrade"; rendered_target=topleft_npc; + u_item=null,u_scroll=null,u_offering=null; + var html="
",rid=randomStr(6),core=""; + html+="
"; + if(character.q.upgrade && character.items[character.q.upgrade.num] && character.items[character.q.upgrade.num].name=="placeholder") + { + var def=character.items[character.q.upgrade.num].p; + core+="
"; + core+=item_container({skin:G.items[def.name].skin,pui:def},{name:def.name,level:def.level}); + core+="
"; + core+="
"; + if(def.offering) core+=item_container({skin:G.items[def.offering].skin,loader:!def.scroll&&"theuitem"+rid},{name:def.offering}); + else core+=item_container({shade:"shade_offering",s_op:0.36}); + if(def.scroll) core+=item_container({skin:G.items[def.scroll].skin,loader:"theuitem"+rid},{name:def.scroll}); + else core+=item_container({draggable:false,droppable:true,shade:"shade_scroll",cid:'uscroll',s_op:0.36}); + core+="
"; + } + else + { + core+="
"; + core+=item_container({draggable:false,droppable:true,shade:"shade_uweapon",cid:'uweapon',s_op:0.36,pui:true}); + core+="
"; + core+="
"; + core+=item_container({draggable:false,droppable:true,shade:"shade_offering",cid:'uoffering',s_op:0.36}); // previously 0.24 + core+=item_container({draggable:false,droppable:true,shade:"shade_scroll",cid:'uscroll',s_op:0.36}); + core+="
"; + } + html+=core; + html+="
"; + html+="
RESET
"; + html+="
UPGRADE
"; + html+="
"; + if(already) $("#core").html(core); + else $("#topleftcornerui").html(html); + if(character.q.upgrade) + { + $(".loadertheuitem"+rid).css("opacity",0.8); + add_tint(".loadertheuitem"+rid,{ms:character.q.upgrade.ms,start:future_ms(character.q.upgrade.ms-character.q.upgrade.len),type:"progress",upgrade:true}); + } + if(!inventory && explicit) render_inventory(),inventory_opened_for=topleft_npc; + return !character.q.upgrade&&originals||[]; +} + +function render_compound_shrine(explicit) +{ + reset_inventory(1); + var originals=[c_items[0],c_items[1],c_items[2],c_scroll,c_offering],already=(topleft_npc=="compound"); + topleft_npc="compound"; rendered_target=topleft_npc; + c_items=e_array(3),c_scroll=null,c_offering=null; c_last=0; + var html="
",rid=randomStr(6),core=""; + html+="
"; + html+="
"; // for pui:true [13/06/19] + if(character.q.compound && character.items[character.q.compound.num] && character.items[character.q.compound.num].name=="placeholder") + { + var def=character.items[character.q.compound.num].p; + core+="
"; + core+=item_container({skin:G.items[def.name].skin},{name:def.name,level:def.level}); + core+=item_container({skin:G.items[def.name].skin},{name:def.name,level:def.level}); + core+=item_container({skin:G.items[def.name].skin},{name:def.name,level:def.level}); + core+="
"; + core+="
"; + if(def.offering) core+=item_container({skin:G.items[def.offering].skin},{name:def.offering}); + else core+=item_container({shade:"shade_offering",s_op:0.36}); + core+=item_container({skin:G.items[def.scroll].skin,pui:def,loader:"theuitem"+rid},{name:def.scroll}); + core+="
"; + } + else + { + core+="
"; + core+=item_container({draggable:false,droppable:true,shade:"shade_cring",cid:'compound0',s_op:0.36}); + core+=item_container({draggable:false,droppable:true,shade:"shade_cring",cid:'compound1',s_op:0.36}); + core+=item_container({draggable:false,droppable:true,shade:"shade_cring",cid:'compound2',s_op:0.36}); + core+="
"; + core+="
"; + core+=item_container({draggable:false,droppable:true,shade:"shade_offering",cid:'coffering',s_op:0.36}); + core+=item_container({draggable:false,droppable:true,shade:"shade_cscroll",cid:'cscroll',s_op:0.36,pui:true}); + core+="
"; + } + html+=core; + html+="
"; + html+="
"; + html+="
RESET
"; + html+="
COMBINE
"; + html+="
"; + if(already) $("#core").html(core); + else $("#topleftcornerui").html(html); + if(character.q.compound) + { + $(".loadertheuitem"+rid).css("opacity",0.8); + add_tint(".loadertheuitem"+rid,{ms:character.q.compound.ms,start:future_ms(character.q.compound.ms-character.q.compound.len),type:"progress",compound:true}); + } + if(!inventory && explicit) render_inventory(),inventory_opened_for=topleft_npc; + return !character.q.compound&&originals||[]; +} + +var dice_bet={active:false,dir:1}; +function on_dice_change() +{ + if(topleft_npc!="dice") return; + var num=min(99.99,max(0,parseFloat($(".dicenum").html()))),mult; + var gold=parseInt($(".dicegold").html().replace_all(",","")); + if(!gold) gold=100000; gold=max(10000,gold); + $(".dicegold").html(to_pretty_num(gold)); dice_bet.gold=gold; + var hnum=num.toFixed(2); + if(hnum.length!=5) hnum="0"+hnum; + $(".dicenum").html(hnum); dice_bet.num=hnum; num=parseFloat(hnum); + if(dice_bet.dir==1) + { + mult=100.0/(100.0-num); + $(".diceup").css("border-color","#A7C16D"); $(".dicedown").css("border-color","gray"); + } + else + { + mult=100.0/num; + $(".diceup").css("border-color","gray"); $(".dicedown").css("border-color","#A7C16D"); + } + mult=min(mult,10000); + $(".dicexx").html("FOR "+to_pretty_float(mult)+"X"); + if(dice_bet.active) $(".diceb").css("border-color","gold"); + else $(".diceb").css("border-color","gray"); +} + +function on_dice_bet() +{ + var num=min(99.99,max(0,parseFloat($(".dicenum").html()))); + var gold=parseInt($(".dicegold").html().replace_all(",","")); + dice(dice_bet.dir,num,gold); +} + +function render_dice() +{ + var num=dice_bet.num||"50.00"; + var gold=dice_bet.gold||100000; + reset_inventory(1); + topleft_npc="dice"; rendered_target=topleft_npc + var html="
"; + html+="
"; + html+="
NUMBER:
"+num+"
"; + html+="
"; + html+="
"; + html+="
GOLD:
"+to_pretty_num(gold)+"
"; + html+="
"; + html+="
"; + html+="
UP
"; + html+="
DOWN
"; + html+="
"; + html+="
"; + html+="
BET FOR 2X
"; + html+="
"; + html+="
"; + $("#topleftcornerui").html(html); + if(!inventory) render_inventory(),inventory_opened_for=topleft_npc; + on_dice_change(); +} + +function render_tavern_info(data) +{ + topleft_npc="info"; rendered_target=topleft_npc + var html="
"; + html+="
"; + html+="
House Edge
"; + html+="
"; + html+="
"; + html+="
"+data.edge.toFixed(2)+"%
"; + html+="
"; + html+="
"; + html+="
Max. Net Win
"; + html+="
"; + html+="
"; + html+="
"+to_pretty_num(data.max)+"
"; + html+="
"; + html+="
"; + $("#topleftcornerui").html(html); + if(!inventory) render_inventory(),inventory_opened_for=topleft_npc; +} + +function on_donate_change() +{ + if(topleft_npc!="donate") return; + var gold=parseInt($(".dgold").html().replace_all(",","")); + if(!gold) gold=100000; gold=max(1,gold); + $(".dgold").html(to_pretty_num(gold)); dice_bet.gold=gold; +} + +function render_donate() +{ + var gold=10000000; + reset_inventory(1); + topleft_npc="donate"; rendered_target=topleft_npc + var html="
"; + html+="
"; + html+="
GOLD:
"+to_pretty_num(gold)+"
"; + html+="
"; + html+="
"; + html+="
DONATE
"; + html+="
"; + html+="
"; + $("#topleftcornerui").html(html); + if(!inventory) render_inventory(),inventory_opened_for=topleft_npc; + on_donate_change(); +} + +function render_merchant(npc,premium) +{ + reset_inventory(1); + topleft_npc="merchant"; rendered_target=topleft_npc; merchant_id=npc.id; + var last=0,collection=[]; + var html="
",f="buy_with_gold"; + if(premium) f="buy_with_shells"; + for(var i=0;i<4;i++) + { + html+="
" + for(var j=0;j<5;j++) + { + if(last"; + next_side_interaction=null; + $("#topleftcornerui").html(html); + for(var i=0;i=1) last+=19+(t_page[token]-1)*18; + for(var i=0;i<4;i++) + { + html+="
" + for(var j=0;j<5;j++) + { + if(i==3 && j==0 && t_page[token]!=0) html+=item_container({skin:"left",onclick:"t_page['"+token+"']="+(t_page[token]-1)+"; render_token_exchange('"+token+"');"},{q:t_page[token],left:true}); + else if(i==3 && j==4 && last"; + next_side_interaction=null; + $("#topleftcornerui").html(html); + for(var i=0;i"; + skin="shells"; + } + else if(def[1]=="gold") + { + html+="
"+to_shrinked_num(def[2])+"
"; + skin="gold"; + } + if(def[1]=="cx") html+=cx_sprite(def[2],{mright:4}); + else if(def[1]=="cxbundle") + { + G.cosmetics.bundle[def[2]].forEach(function(cid){ + html+=cx_sprite(cid,{mright:4}); + }); + } + else html+=""+item_container({skin:skin},actual)+""; + if(def[0]*mult>=1) html+="
"+to_pretty_float(def[0]*mult)+" / 1
"; + else if(1/(def[0]*mult)>=1.1 && 1/(def[0]*mult)<10 && parseInt(1/(def[0]*mult))*10!=parseInt(10/(def[0]*mult))) html+="
10 / "+to_pretty_num(round(10/(def[0]*mult)))+"
"; + else html+="
1 / "+(((1/(def[0]*mult))>=2)&&to_pretty_num(round(1/(def[0]*mult)))||to_pretty_float(1/(def[0]*mult)))+"
"; + html+="
"; + return html; +} + +function smart_smart_move(type,id) +{ + if(type=="npc") + { + var npc=G.npcs[id]; + show_confirm("Smart move to "+npc.name+"?","Yes","Cancel",function(){ hide_modals(); call_code_function_f("smart_move",id); }); + } + else if(type=="monster") + { + var m=G.monsters[id]; + show_confirm("Smart move to "+m.name+"'s?","Yes","Cancel",function(){ hide_modals(); call_code_function_f("smart_move",id); }); + } + else if(type=="map") + { + var m=G.maps[id]; + show_confirm("Smart move to "+m.name+"?","Yes","Cancel",function(){ hide_modals(); call_code_function_f("smart_move",id); }); + } +} + +function render_equip_info(name) +{ + var def=G.items[name],html=""; + html+="
"; + html+="
"+(weapon_types[def.wtype]||offhand_types[def.type]||def.wtype||def.type).toTitleCase()+"
"; + ["ranger","rogue","warrior","mage","priest","paladin","merchant"].forEach(function(ctype) + { + var color="#DDDDDD"; + if(window.character && character.ctype==ctype) color="#36813A"; + else if(window.character) color="#666870"; + if(G.classes[ctype].mainhand[def.wtype||def.type]) + { + html+="
"; + html+="
["+ctype.toTitleCase()+"] Mainhand
"; + var s=render_item("html",{item:{},prop:G.classes[ctype].mainhand[def.wtype||def.type],pure:true}); + if(!s) html+="
No Modifier
"; + else html+=s; + html+="
"; + } + if(G.classes[ctype].doublehand[def.wtype||def.type]) + { + html+="
"; + html+="
["+ctype.toTitleCase()+"] Doublehand
"; + var s=render_item("html",{item:{},prop:G.classes[ctype].doublehand[def.wtype||def.type],pure:true}); + if(!s) html+="
No Modifier
"; + else html+=s; + html+="
"; + html+="
"; + } + if(G.classes[ctype].offhand[def.wtype||def.type]) + { + html+="
"; + html+="
["+ctype.toTitleCase()+"] Offhand
"; + var s=render_item("html",{item:{},prop:G.classes[ctype].offhand[def.wtype||def.type],pure:true}); + if(!s) html+="
No Modifier
"; + else html+=s; + html+="
"; + html+="
"; + } + }); + html+="
"; + show_modal(html,{wrap:false,hideinbackground:true}); +} + +function render_item_help(container,name,level,pure) +{ + var html="",names=[name]; + html+="
"; + for(var depth=0;depth<3;depth++) + { + for(var dname in G.drops) + { + if(in_arr(dname,names) || dname=="glitch" || dname=="lglitch") continue; + var table=G.drops[dname]; + for(var i=0;i
"+sprite(npc.skin,{width:50,height:50})+"
"+npc.name+"
"; + }); + } + if(G.items[name].type=="token") + { + html+="
Spend At:
"; + var npc={},npc_id=null; + for(var nname in G.npcs) + if(G.npcs[nname].token==name) + npc=G.npcs[nname],npc_id=nname; + html+="
"; + html+="
"+sprite(npc.skin,{width:50,height:50})+"
"+npc.name+"
"; + html+="
"; + } + if(tokens.length) + { + html+="
Acquirable From:
"; + tokens.forEach(function(token){ + var npc={},npc_id=null; + for(var nname in G.npcs) + if(G.npcs[nname].token==token) + npc=G.npcs[nname],npc_id=nname; + html+="
"; + html+="
"+sprite(npc.skin,{width:50,height:50})+"
"+npc.name+"
"; + html+="
with
"; + html+=item_container({skin:G.items[token].skin,onclick:"stpr(event); render_item_popup('"+token+"')"},{name:token}); + html+="
"; + }); + } + if(G.items[name].e) + { + var npc=G.npcs.exchange,phrase="Exchange From",id="exchange"; + for(var nname in G.npcs) + if(G.items[name].quest && G.npcs[nname].quest==G.items[name].quest) npc=G.npcs[nname],phrase="Bring To",id=nname; + html+="
"+phrase+":
"; + html+="
"+sprite(npc.skin,{width:50,height:50})+"
"+npc.name+"
"; + html+="
Drop Table:
"; + html+=item_container({skin:G.items[name].skin,onclick:"stpr(event); render_exchange_info('"+(name+((G.items[name].upgrade||G.items[name].compound)&&(level||"0")||""))+"')"},{name:name,level:(G.items[name].upgrade||G.items[name].compound)&&level}); + } + if(G.items[name].upgrade || G.items[name].compound) + { + var npc=G.npcs.newupgrade,phrase="Upgrade At",id="newupgrade"; + if(G.items[name].compound) phrase="Combine 3 At"; + html+="
"+phrase+":
"; + html+="
"+sprite(npc.skin,{width:50,height:50})+"
"+npc.name+"
"; + var phrase="Buy Scrolls From",npc=G.npcs.scrolls,id="scrolls"; + html+="
"+phrase+":
"; + html+="
"+sprite(npc.skin,{width:50,height:50})+"
"+npc.name+"
"; + } + if(crafting.length) + { + html+="
Used For Crafting:
"; + crafting.forEach(function(i){ + html+=item_container({skin:G.items[i].skin,onclick:"stpr(event); render_recipe(null,'','"+i+"')"},{name:i}); + }); + } + if(collecting.length) + { + html+="
Collectable For:
"; + collecting.forEach(function(i){ + html+=item_container({skin:G.items[i].skin,onclick:"stpr(event); render_recipe(null,'mcollector','"+i+"')"},{name:i}); + }); + } + if(G.craft[name]) + { + var phrase="Craftable At",npc=G.npcs.craftsman,id="craftsman",rphrase="Recipe"; + if(G.craft[name].quest=="mcollector") phrase="Obtainable From",npc=G.npcs.mcollector,id="mcollector",rphrase="Materials"; + if(G.craft[name].quest=="witch") phrase="Concoctiable At",npc=G.npcs.witch,id="witch",rphrase="Materials"; + html+="
"+phrase+":
"; + html+="
"+sprite(npc.skin,{width:50,height:50})+"
"+npc.name+"
"; + html+=""+bold_prop_line("Show",rphrase,"#6F75DC")+""; + } + if(G.dismantle[name]) + { + html+="
Dismantle At:
"; + var npc=G.npcs.craftsman,id="craftsman"; + html+="
"+sprite(npc.skin,{width:50,height:50})+"
"+npc.name+"
"; + } + if(monsters.length) + { + html+="
Drops From:
"; + monsters.forEach(function(mo){ + var m=mo[0]; + html+="
"; + html+="
"; + html+=sprite(m,{scale:1.5}); + html+="
"; + if(mo[1]) html+="
"+to_pretty_fraction(mo[1])+"
"; + // html+="
"+G.monsters[m].name+"
"; + html+="
"; + }); + } + if(maps.length) + { + html+="
Global Drop At:
"; + maps.forEach(function(map){ + if(map=="global") + html+="
Everywhere
"; + else + html+="
"+G.maps[map].name+"
"; + }); + } + if(items.length) + { + html+="
Obtainable From:
"; + items.forEach(function(i){ + html+=item_container({skin:G.items[i[0]].skin,onclick:"stpr(event); render_item_popup('"+i[0]+"',"+i[1]+")"},{name:i[0],level:i[1]}); + }); + } + html+=""+bold_prop_line("Show","G.items."+name+"",colors.inspect)+""; + html+="
"; + // $(container).parent().replaceWith(html); + if(pure) return html; + show_modal(html,{wrap:false,hideinbackground:true}); +} + +function render_item_popup(name,level) +{ + var html=""; + html+=render_item("html",{item:G.items[name],actual:{name:name,level:level},name:name}); + show_modal(html,{wrap:false,hideinbackground:true}); +} + +function render_item_info(name,level,data) +{ + var html="
"; + if(name=="empty") + { + html+=render_item("html",{item:{name:"Empty",explanation:"Nothing, nada, zilch."},prop:{}}); + } + else if(name=="shells") + { + html+=render_item("html",{item:{name:"Shells",explanation:"Premium currency, can be used to buy cosmetics, extra bank storage, or for account operations like transferring a character."},prop:{}}); + } + else if(name=="gold") + { + html+=render_item("html",{item:{name:"Gold",explanation:"Just gold"},prop:{}}); + } + else if(level!==undefined) + { + html+=render_item("html",{item:G.items[name],actual:{level:level,name:name,data:data},guide:true}); + } + else if(G.items[name].compound) + { + for(var i=0;i<=15;i++) + { + html+="
"+render_item("html",{item:G.items[name],actual:{level:i,name:name},guide:true})+"
"; + if(calculate_item_grade(G.items[name],{level:i})==4) break; + } + } + else if(G.items[name].upgrade) + { + for(var i=0;i<=15;i++) + { + html+="
"+render_item("html",{item:G.items[name],actual:{level:i,name:name},guide:true})+"
"; + if(calculate_item_grade(G.items[name],{level:i})==4) break; + } + } + else + { + html+=render_item("html",{item:G.items[name],name:name,actual:{name:name},guide:true}); + } + html+="
"+render_item_help(null,name,level,true)+"
"; + html+="
"; + show_modal(html,{wrap:false,hideinbackground:true,url:"/docs/guide/all/items/"+name}); +} + +function render_monster_info(name) +{ + var html="
",parsed={},count=0,mcount=0,diff=0,mowner=""; + html+="
"+sprite(name,{full:true,scale:3})+"
"; + var RF=Object.keys(tracker).length&&tracker||G&&G.drops||{monsters:{},maps:{}},MR=Object.keys(tracker).length&&tracker&&tracker.drops||RF.monsters; + if(tracker && tracker.monsters) + { + count=tracker.monsters[name]||0; + diff=tracker.monsters_diff[name]||0; + if(tracker.max.monsters[name]) mcount=tracker.max.monsters[name][0],mowner=tracker.max.monsters[name][1]; + } + html+=render_item("html",{pure:true,item:G.monsters[name],prop:G.monsters[name],monster:name,count:count,mcount:mcount,score:count+diff,mowner:mowner}); + if(MR && MR[name] && MR[name].length) + { + html+="
Drops:
"; + MR[name].forEach(function(drop){ + html+=render_drop(drop,1,"#858B8E"); + }); + } + object_sort(G.maps).forEach(function(io){ + var map=io[1],mname=io[0]; + if(map.ignore || !(RF.maps&&RF.maps[mname]||[]).length) return; + (map.monsters||[]).forEach(function(pack){ + if(parsed[mname]) return; + if(pack.type==name) + { + parsed[mname]=true; + html+="
"+map.name+":
"; + RF.maps[mname].forEach(function(drop){ + html+=render_drop(drop,G.monsters[name].hp/1000.0,"#858B8E"); + }); + } + }); + }); + if(RF.maps && RF.maps.global_static && RF.maps.global_static.length || RF.maps && RF.maps.global && RF.maps.global.length) + { + var mult=1; + if(G.monsters[name]["1hp"]) mult=1000; + html+="
Global:
"; + RF.maps.global_static.forEach(function(drop){ + html+=render_drop(drop,1*mult,"#858B8E"); + }); + RF.maps.global.forEach(function(drop){ + html+=render_drop(drop,G.monsters[name].hp*mult/1000.0,"#858B8E"); + }); + } + html+="
"; + show_modal(html,{wwidth:240,hideinbackground:true,url:"/docs/guide/all/monsters/"+name}); +} + +function render_exchange_info(name,count) +{ + var html="
"; + html+=render_drop([1,"open",name],1,"#858B8E"); + html+="
"; + show_modal(html,{wwidth:240,styles:'max-width: 460px',hideinbackground:true}); +} + +function render_tracker() +{ + var html=""; + html+="
"; + html+="
Monsters
"; + html+="
Exchanges and Quests
"; + html+="
"; + html+="
"; + object_sort(G.monsters,"hpsort").forEach(function(e){ + if((e[1].stationary || e[1].cute) && !e[1].achievements || e[1].unlist) return; + var count=(tracker.monsters[e[0]]||0)+(tracker.monsters_diff[e[0]]||0),color="#50ADDD"; + if(tracker.max.monsters[e[0]] && tracker.max.monsters[e[0]][0]>count) + { + count=tracker.max.monsters[e[0]][0]; + color="#DCC343"; + } + html+="
"; + html+=sprite(e[0],{scale:1.5}); + if(!count) + { + //html+="
?
"; + } + else + { + html+="
"+to_shrinked_num(count)+"
"; + } + if(tracker.drops && tracker.drops[e[0]] && tracker.drops[e[0]].length) + html+="
"; + html+="
"; + }); + html+="
"; + html+=""; + show_modal(html,{wwidth:578,hideinbackground:true}); +} + +function render_computer($element) +{ + var html=""; + html+="
CONNECTED.
"; + html+="
> UPGRADE
"; // style='color: #C3C3C3' style='color: #D6D6D6' + html+="
> COMPOUND
"; + html+="
> EXCHANGE
"; + html+="
> LOCKSMITH
"; + html+="
> CRAFTING
"; + html+="
> POTIONS
"; + html+="
> SCROLLS
"; + html+="
> BASICS
"; + + html+="
> PREMIUM
"; + + $element.html(html); +} + +function render_skill(selector,skill_name,args) +{ + if(!args) args={}; + var actual=args.actual||{},html=""; + var skill=G.skills[skill_name]; + html+="
" + if(!skill) html+=skill_name; + else + { + html+="
"+skill.name+"
"; + if(skill.explanation) + { + html+="
"+skill.explanation+"
"; + if(skill.mp) html+=bold_prop_line("MP",skill.mp,colors.mp); + if(skill.duration) html+=bold_prop_line("Duration",(skill.duration/1000.0)+" seconds","gray"); + if(skill.cooldown && (skill.cooldown/1000.0)) html+=bold_prop_line("Cooldown",(skill.cooldown/1000.0)+" seconds","gray"); + if(skill.reuse_cooldown && (skill.reuse_cooldown/1000.0)) html+=bold_prop_line("R.Use Cooldown",(skill.reuse_cooldown/1000.0)+" seconds","gray"); + if(skill.share) html+=bold_prop_line("Cooldown",to_pretty_float(skill.cooldown_multiplier||1)+"X of "+G.skills[skill.share].name,"gray"); + if(skill.range) html+=bold_prop_line("Range",skill.range,"gray"); + if(skill.use_range) html+=bold_prop_line("Range","Character Range","gray"); + if(skill.range_multiplier && skill.range_bonus) html+=bold_prop_line("Range",to_pretty_float(skill.range_multiplier||1)+"X + "+skill.range_bonus,"gray"); + else if(skill.range_multiplier) html+=bold_prop_line("Range",to_pretty_float(skill.range_multiplier||1)+"X of Character Range","gray"); + if(skill.level) html+=bold_prop_line("Level Requirement",skill.level,"gray"); + if(skill.max) html+=bold_prop_line("Max",skill.max,"gray"); + if(skill.type=="passive") html+="
Passive
"; + if(skill.damage_type) + { + if(skill.damage_type=="pure") html+=bold_prop_line("Damage Type","Pure","#AA9B55"); + else if(skill.damage_type=="magical") html+=bold_prop_line("Damage Type","Magical","#8998AA"); + else if(skill.damage_type=="physical") html+=bold_prop_line("Damage Type","Physical","#93AB98"); + } + if(skill.condition && G.conditions[skill.condition]) + { + html+=info_line({name:"Condition",color:"#A59FFF",value:G.conditions[skill.condition].name,onclick:"dialogs_target=xtarget||ctarget; show_json(G.conditions."+skill.condition+",{name:'G.conditions."+skill.condition+"'})"}); + } + (skill.levels||[]).forEach(function(lv){ + var level=lv[0],value=lv[1]; + html+=bold_prop_line("Output",value+(level>0&&(" (Lv. "+level+")")),"gray"); + }); + for(var requirement in (skill.requirements||{})) + { + var amount=skill.requirements[requirement]; + html+=bold_prop_line("Required "+requirement.toTitleCase(),amount,"gray"); + } + if(skill.consume) + { + html+="
"+item_container({skin:G.items[skill.consume].skin,def:G.items[skill.consume]});+"
" + } + html+="
Show: G.skills."+skill_name+"
"; + } + } + html+="
"; + if(modal_count) show_modal(html,{wrap:false}); + else $(selector).html(html); +} + +function render_computer_network(selector) +{ + var html="
"; + $(selector).html(html); + render_computer($(".computernx")); +} + +function render_secondhands(type) +{ + reset_inventory(1); + topleft_npc="secondhands"; + if(type) topleft_npc=type; + rendered_target=topleft_npc; // merchant_id=npc.id; + var last=0,collection=[],f="sh_click"; + var html="
"; + var items=secondhands; + if(type) + { + items=lostandfound; + if(l_page>=1) last+=19+(l_page-1)*18; + f="lf_click"; + } + else + { + if(s_page>=1) last+=19+(s_page-1)*18; + } + for(var i=0;i<4;i++) + { + html+="
" + for(var j=0;j<5;j++) + { + if(!type && i==3 && j==0 && s_page!=0) html+=item_container({skin:"left",onclick:"s_page="+(s_page-1)+"; render_secondhands();"},{q:s_page,left:true}); + else if(!type && i==3 && j==4 && last"; + next_side_interaction=null; + $("#topleftcornerui").html(html); +} + +function old_render_gallery() +{ + var html=""; + G.codes.forEach(function(section){ + html+="
"+(section.name||section.key)+"
"; + }); + html+="
"; + G.codes[0].list.forEach(function(def){ + html+="
"+def[1]+"
"; + }); + html+="
"; + show_modal(html); +} + +function old_render_stepv1(args) +{ + if(!args) args={}; + args.title="[1/24] Move"; + args.main="Welcome to the first step of the tutorial. In this step, we are going to move! Now move your character near the green goo's by clicking on the map and walking below the town!"; + args.code="Using the CODE feature. You can use the `move` function, or, the more costly `smart_move` function."; + var html=""; + if(args.title) html+="
"+args.title+"
"; + if(args.main) html+="
"+args.main+"
"; + if(args.code) html+="
"+args.code+"
"; + show_modal(html); + +} + +function load_documentation(name) +{ + if(in_arr(name,G.docs.documented)) api_call("load_article",{name:name,func:true}); + else if(name=="character") show_json(game_stringify(character,'\t')); + else if(in_arr(name,G.docs.functions)) render_function_reference(name); + else + { + $(".codesearch").val(name); + csearch_logic("ui"); + } +} + +function open_article(name,url) +{ + api_call("load_article",{name:name,url:url}); +} + +function open_guide(name,url) +{ + api_call("load_article",{name:name,guide:true,url:url}); +} + +function open_tutorial() +{ + api_call("load_article",{name:G.docs.tutorial[X.tutorial.step].key,tutorial:""+X.tutorial.step}); +} + +var last_rendered_step=0; +function render_tutorial(article,step,url) +{ + hide_modals(); last_rendered_step=step; + var tutorial=G.docs.tutorial[step],cphrase="CONTINUE"; + if(step==G.docs.tutorial.length-1) cphrase="COMPLETE"; + + var html="
"; + html+="
"+tutorial.title+"
["+(step+1)+"/"+G.docs.tutorial.length+"]
"; + html+="
"; + html+=article; + html+="
"; + html+="
Completion: "+0+"%
INCOMPLETE
"+cphrase+"
"; + html+="
"; + + show_modal(html,{wrap:false,url:url}); + update_tutorial_ui(); + $(".code").codemirror({trim:true}); + position_modals(); +} + +function render_learn_article(article,args) +{ + var html="
"; + html+=article; + html+="
"; + if(args.prev) html+="
< Previous
"; + if(args.next) html+="
Next >
"; + html+="
"; + show_modal(html,{wrap:false,url:args&&args.url}); + $(".code").codemirror({trim:true}); + position_modals(); +} + +var render_function_html=""; +function render_function_reference(n,f,c) +{ + // hide_modal(); + if(n=="character") return show_json(game_stringify(character,'\t')); + if(!c) + { + code_eval("parent.render_function_reference(\""+n+"\",window['"+n+"'],1);"); + return; + } + if(!f && !window[n]) + { + render_function_html=""; + return add_log('Reference not found','gray'); + } + else if(!f) f=window[n]; + var html="",rid=randomStr(10); + if(render_function_html) + { + render_learn_article(render_function_html+"",{url:"/docs/code/functions/"+n}); + $(".codemirror"+rid).codemirror({value:"//Source code of: "+n+"\n"+f.toString(),hints:true}); + render_function_html=""; + } + else + { + html+=""; + show_modal(html,{wwidth:min($(window).width()-60,1200),url:"/docs/code/functions/"+n}); + $(".codemirror"+rid).codemirror({value:"//Source code of: "+n+"\n"+f.toString(),hints:true}); + position_modals(); + } +} + +function render_functions_directory() +{ + // hide_modal(); + var html="
"; + G.docs.functions.forEach(function(n){ + if(in_arr(n,G.docs.documented)) + html+="
"+n+"
"; + else + html+="
"+n+"
"; + }); + html+="
"; + show_modal(html,{wrap:false,hideinbackground:true,url:"/docs/code/functions"}); +} + +function render_all_recipes() +{ + var html="
"; + // html+="
Work in Progress
"; + var xprev=false; + object_sort(G.craft,"gold_value").forEach(function(r) + { + if(xprev) html+="
"; + var prev=false,name=r[0],recipe=r[1]; + html+="
"; + html+=item_container({skin:G.items[name].skin,onclick:"render_item_info('"+name+"')"},{name:name}); + html+=" <= "; + recipe.items.forEach(function(i){ + if(prev) html+=" + "; + html+=item_container({skin:G.items[i[1]].skin,onclick:"render_item_info('"+i[1]+"')"},{name:i[1],q:i[0],level:i[2]}); + prev=true; + }); + if(recipe.cost) html+=" + "+to_pretty_num(recipe.cost)+""; + html+="
"; + xprev=true; + }); + object_sort(G.dismantle,"gold_value").forEach(function(r) + { + if(xprev) html+="
"; + var prev=false,name=r[0],recipe=r[1]; + html+="
"; + html+=item_container({skin:G.items[name].skin,onclick:"render_item_info('"+name+"')"},{name:name}); + html+=" => "; + recipe.items.forEach(function(i){ + if(prev) html+=" + "; + html+=item_container({skin:G.items[i[1]].skin,onclick:"render_item_info('"+i[1]+"')"},{name:i[1],q:i[0],level:i[2]}); + prev=true; + }); + if(recipe.cost) html+=" - "+to_pretty_num(recipe.cost)+""; + html+="
"; + xprev=true; + }); + html+="
" + show_modal(html,{wrap:false,hideinbackground:true,url:"/docs/guide/all/recipes"}); +} + +function show_recipe(name) +{ + var html="
"; + var prev=false,recipe=G.craft[name]; + html+="
"; + html+=item_container({skin:G.items[name].skin,onclick:"render_item_info('"+name+"')"},{name:name}); + html+=" <= "; + recipe.items.forEach(function(i){ + if(prev) html+=" + "; + html+=item_container({skin:G.items[i[1]].skin,onclick:"render_item_info('"+i[1]+"')"},{name:i[1],q:i[0],level:i[2]}); + prev=true; + }); + if(recipe.cost) html+=" + "+to_pretty_num(recipe.cost)+""; + html+="
"; + html+="
"; + show_modal(html,{hideinbackground:true}); +} + +function render_cx_info(name) +{ + var html="
"; + html+="
"+cx_sprite(name,{mleft:4})+"
"; + html+=" ID: "+name+"
Type: "+T[name]+"
Slot: "+cxtype_to_slot[T[name]]; + html+="
"; + show_modal(html,{wrap:false,hideinbackground:true,url:"/docs/guide/all/cosmetics"}); +} + +function render_all_cosmetics() +{ + precompute_image_positions(); + var types=[ + ["hair","Hairs",[]], + ["hat","Hats",[]], + ["chin","Chins",[]], + ["face","Accents",[]], + ["head","Skins",[]], + ["armor","Armors",[]], + ["body","Bodies",[]], + ["character","Characters",[]], + ["back","Back",[]], + ["gravestone","Gravestones",[]], + ["","Others",[]], + ]; + var visited={},html="
"; + object_sort(T).forEach(function(ti){ + var val=ti[1],cid=ti[0]; + for(var i=0;i"; + html+="
"; + type[2].forEach(function(cid){ + html+=""+cx_sprite(cid,{mright:4,labels:true})+""; + }); + html+="
"; + }); + html+="
" + show_modal(html,{wrap:false,hideinbackground:true,url:"/docs/guide/all/cosmetics"}); +} + +function render_all_items() +{ + var types=[ + ["helmet","Helmets",[]], + ["chest","Armors",[]], + ["pants","Underarmors",[]], + ["gloves","Gloves",[]], + ["shoes","Shoes",[]], + ["cape","Capes",[]], + ["ring","Rings",[]], + ["earring","Earrings",[]], + ["amulet","Amulets",[]], + ["belt","Belts",[]], + ["orb","Orbs",[]], + ["weapon","Weapons",[]], + ["shield","Shields",[]], + ["offhand","Offhands",[]], + ["elixir","Elixirs",[]], + ["pot","Potions",[]], + ["scroll","Scrolls",[]], + ["material","Crafting and Collecting",[]], + ["exchange","Exchangeables",[]], + ["key","Keys",[]], + ["","Others",[]], + ]; + var visited={},html="
"; + object_sort(G.items,"gold_value").forEach(function(item){ + if(item[1].ignore) return; + for(var i=0;i"; + html+="
"; + type[2].forEach(function(item){ + html+=item_container({skin:G.items[item[0]].skin,onclick:"render_item_info('"+item[0]+"')"},{name:item[0]}); + }); + html+="
"; + }); + html+="
" + show_modal(html,{wrap:false,hideinbackground:true,url:"/docs/guide/all/items"}); +} + +function render_all_monsters() +{ + var html=""; + html+="
"; + object_sort(G.monsters,"hpsort").forEach(function(e){ + if((e[1].stationary || e[1].cute) && !e[1].achievements || e[1].hide) return; + html+="
"; + html+=sprite(e[0],{scale:1.5}); + if(G.drops && G.drops.monsters && G.drops.monsters[e[0]] && G.drops.monsters[e[0]].length) + html+="
"; + html+="
"; + }); + html+="
"; + show_modal(html,{wrap:false,hideinbackground:true,url:"/docs/guide/all/monsters"}); +} + +function render_all_events() +{ + function event_html(e,key) + { + var ehtml=""; + ehtml+="
"; + ehtml+=sprite(e.sprite,{overflow:true}); + ehtml+="
"+e.name+"
"; + ehtml+="
"; + return ehtml; + } + var html=""; + html+="
"; + html+="
Daily Events
"; + object_sort(G.events).forEach(function(e){ + if(e[1].type=="daily") + html+=event_html(e[1],e[0]); + }); + html+="
Nightly Events
"; + object_sort(G.events).forEach(function(e){ + if(e[1].type=="nightly") + html+=event_html(e[1],e[0]); + }); + // html+="
Random Events
"; + // object_sort(G.events).forEach(function(e){ + // if(e[1].type=="random") + // html+=event_html(e[1],e[0]); + // }); + html+="
Seasonal Events
"; + object_sort(G.events).forEach(function(e){ + if(e[1].type=="seasonal") + html+=event_html(e[1],e[0]); + }); + html+="
"; + show_modal(html,{wrap:false,hideinbackground:true,url:"/docs/guide/all/events"}); +} + +function render_guide(path,title,color) +{ + var more=false,ref=false,suffix=""; + docs=G.docs.guide; + if(!path || is_string(path)) + { + path=[],more=true,ref=true; + } + else + { + path.forEach(function(step){ + for(var i=0;i["+title[0]+"] "+title+"
"; + } + docs.forEach(function(n){ + if(n[4]) + { + path.push(n[0]); + html+="
["+n[1][0]+"] "+n[1]+" ["+n[4].length+"]
"; + path.pop(); + } + else + html+="
["+n[1][0]+"] "+n[1]+"
"; + index++; + }); + if(ref && inside!="docs") + { + // html+="
[C] Code Guide
"; + html+="
[X] Code Docs
"; + } + if(more) html+="
Guide is a Work in Progress!
"; + html+="
"; + show_modal(html,{wrap:false,hideinbackground:true,url:"/docs/guide"+suffix}); +} + +function render_code_articles(path,title,color) +{ + var more=false,suffix=""; + docs=G.docs.articles; + if(!path) path=[],more=true; + else + { + path.forEach(function(step){ + for(var i=0;i["+title[0]+"] "+title+"
"; + } + docs.forEach(function(n){ + if(n[3]) + { + path.push(n[0]); + html+="
["+n[1][0]+"] "+n[1]+" ["+n[3].length+"]
"; + path.pop(); + } + else + html+="
["+n[1][0]+"] "+n[1]+"
"; + index++; + }); + if(more) html+="
More Articles Coming Soon!
"; + html+="
"; + show_modal(html,{wrap:false,hideinbackground:true,url:"/docs/code/learn"+suffix}); +} + +function render_objects_reference(docs) +{ + // hide_modal(); + var html="
"; + var index=0; + G.docs.objects.forEach(function(n){ + html+="
"+n[1]+"
"; + index++; + }); + html+="
Work in Progress
"; + html+="
"; + show_modal(html,{wrap:false,hideinbackground:true}); +} + +function render_useful_links() +{ + // hide_modal(); + var html="
"; + html+="JSConsole.com"; + html+='
A very practical website to play with Javascript in a Console.
'; + html+="Code Academy: Javascript"; + html+='
Code Academy\'s Javascript course - If you want to learn Javascript properly first, Code Academy\'s refined course will hopefully be more helpful :]
'; + html+="Adventure Land's Github"; + html+='
#TODO: Create a gallery of player\'s Github repos
'; + html+="#code_beginner on Discord"; + + html+="
"; + show_modal(html,{wrap:false,url:"/docs/code/links"}); +} + +function render_data_reference(path,id) +{ + // if(!id) hide_modal(); + if(!id) path=[]; + else path.push(id); + var data=G,str="G",suffix=""; + path.forEach(function(p){ + data=data[p]; + str=str+"."+p; + if(!suffix) suffix+="/"+p; + }); + if(is_object(data) && path.length<2 && !in_arr(id,["levels"])) + { + // var html="
"; + var html="
"; + object_sort(data).forEach(function(nd){ + var n=nd[0]; + // html+="
"+str+"."+n+"
"; + html+="
"+str+"."+n+"
"; + }); + html+="
"; + show_modal(html,{wrap:false,hideinbackground:true,url:"/docs/code/data"+suffix}); + } + else + { + show_json(game_stringify_simple(data,'\t')); + } +} + +var csearch_value=undefined,codesearch_value=undefined; +function csearch_logic(place) +{ + var value="",one=false; + if(place=="ui") + { + value=$('.codesearch').val(); + if(value==codesearch_value) return; + codesearch_value=value; + } + else + { + value=$('.csearchi').val() + if(value==csearch_value) return; + csearch_value=value; + } + if(value.length || place=="ui") + { + var html=""; + if(place=="ui") + { + + } + else + { + $('.cdocsbuttons').hide(); + $('.cdocssearch').show(); + } + G.docs.references.forEach(function(ref){ + if(ref[2].search(value)!==-1 || place=="ui" && !value) + { + one=true; + if(!place) html+="
[REFERENCE] "+ref[1]+"
"; + else html+="
[R] "+ref[1]+"
"; + } + }); + var articles=[]; + function parse_articles(article) + { + if(is_array(article[0])) + { + article.forEach(function(a){ + parse_articles(a); + }); + } + else + { + if(!article[4]) articles.push(article); + else parse_articles(article[4]); + } + } + parse_articles(G.docs.guide); + // console.log(articles); + articles.forEach(function(article){ + if(!article[2]) return; + if(article[2].search(value)!==-1 || place=="ui" && !value) + { + one=true; + if(!place) html+="
[ARTICLE] "+article[1]+"
"; + else html+="
[A] "+article[1]+"
"; + } + }); + G.docs.javascript.forEach(function(ref){ + if(ref[1].search(value)!==-1 || place=="ui" && !value) + { + one=true; + if(!place) html+=""; + else html+=""; + } + }); + for(var name in G) + { + if(name.search(value)!==-1 || value=="[G]" || place=="ui" && !value) + { + one=true; + if(!place) html+="
[GAMEDATA] G."+name+"
"; + else html+="
[G] G."+name+"
"; + } + } + G.docs.functions.forEach(function(n){ + if(n.search(value)==-1 && value!="[F]" && !(place=="ui" && !value)) return; + if(in_arr(n,G.docs.documented)) + { + if(!place) html+="
[FUNCTION] "+n+"
"; + else html+="
[F] "+n+"
"; + } + else + { + if(!place) html+="
[FUNCTION] "+n+"
"; + else html+="
[F] "+n+"
"; + } + one=true; + }); + if(!one && !place) + html+="
[NONE FOUND]
"; + else if(!one) + html+="
[NONE FOUND]
"; + if(place=="ui") + { + last_hint=undefined; + $('#codehint').remove() + $('#codelog').html(html); + } + else $('.cdocssearch').html(html); + } + else + { + $('.cdocsbuttons').show(); + $('.cdocssearch').hide(); + position_modals(); + } +} + +function render_code_docs() +{ + csearch_value=undefined; + var html="
"; + //html+="
Learn [Basic to Advanced]
"; + html+="
[SEARCH]
"; + html+=""; + html+="
" + html+="
[F] Available Functions
"; + html+="
[G] Game Data
"; + // html+="
Objects Reference [WIP]
"; + html+="
[C] Character Reference
"; + html+="
[M] Monster Reference
"; + //html+="
Javascript Events [Soon]
"; + html+="
[E] Game Events
"; + html+="
[C] Character Events
"; + html+="
[U] Useful Links
"; + html+='
Note: CODE Documentation is a work in progress. You can use Discord/#feedback for ideas/requests.
'; + html+="
" + html+="
"; + show_modal(html,{wrap:false,hideinbackground:true,url:"/docs/code"}); + $('.csearchi').bind("propertychange change click keyup input paste", function(event){ csearch_logic(); }); +} + +function render_others() +{ + var html="
"; + //html+="
Learn [Basic to Advanced]
"; + html+="
" + html+="
[S] Skillbar and Keymapping
"; + html+="
[B] Using Boosters
"; + html+="
[$] About Shells
"; + html+="
" + html+="
"; + show_modal(html,{wrap:false,hideinbackground:true,url:"/docs/ref"}); +} + +function render_wishlist(num,page) +{ + var html="
"; + html+="
Wishlist
"; + var items=[],last=0; + for(var name in G.items) + if(!G.items[name].ignore) items.push([name,G.items[name],G.items[name].g||0]); + items.sort(function(a,b){return b[2]-a[2];}); + if(page>=1) last+=19+(page-1)*18; + for(var i=0;i<4;i++) + { + html+="
" + for(var j=0;j<5;j++) + { + if(i==3 && j==0 && page!=0) html+=item_container({skin:"left",onclick:"render_wishlist("+num+","+(page-1)+");"},{q:page,left:true}); + else if(i==3 && j==4 && last"; + if(!item) html+="ITEM"; + else + { + if(item.type=="tarot" && item.minor) html+=""; + else if(item.type=="tarot") html+=""; + color="#E4E4E4"; // previously gray [16/08/16] + if(item.grade=="mid") color="blue"; // lol - must be old [13/04/20] + if(actual && actual.p && G.titles[actual.p]) item_name=G.titles[actual.p].title+" "+item_name; + else if(actual && actual.p) item_name=actual.p.toTitleCase()+" "+item_name; + if(prop.level) + { + if(item.upgrade && prop.level==12) item_name+=" +Z"; + else if(item.upgrade && prop.level==11) item_name+=" +Y"; + else if(item.upgrade && prop.level==10) item_name+=" +X"; + else if(item.compound && prop.level==7) item_name+=" +R"; + else if(item.compound && prop.level==6) item_name+=" +S"; + else if(item.compound && prop.level==5) item_name+=" +V"; + else item_name+=" +"+prop.level; + } + if(args.thumbnail) + { + html+="
"+item_container({skin:item.skin,def:item})+"
"; + } + if(item.card) + { + html+="
"; + html+="
"+item_name+"
"; + html+="
"+item.card+"
"; + html+="
"; + } + else if(!args.pure) + { + html+="
"+item_name+"
"; + } + if(prop.miss && item.type=="elixir") html+=bold_prop_line("Alcohol",prop.miss+"%","#7CAAF6"); + (item.gives||[]).forEach(function(prop){ + if(prop[0]=="hp" && prop[1]<0) html+=bold_prop_line("HP",to_pretty_num(prop[1]),colors.hp); + else if(prop[0]=="hp") html+=bold_prop_line("HP","+"+to_pretty_num(prop[1]),colors.hp); + if(prop[0]=="mp") html+=bold_prop_line("MP","+"+to_pretty_num(prop[1]),colors.mp); + }); + if(item.debuff) html+=bold_prop_line("Effect","Debuff","#343792"); + if(args.monster) + { + html+=bold_prop_line("Name",item.name); + html+=""+bold_prop_line("Show","G.monsters."+args.monster+"",colors.inspect)+""; + html+=""+bold_prop_line("Find","\""+args.monster+"\"","#7AD963")+""; + } + if(prop.gold) html+=bold_prop_line("Gold",(prop.gold>0&&"+"||"")+prop.gold+"%","gold"); + if(prop.luck) html+=bold_prop_line("Luck",(prop.luck>0&&"+"||"")+prop.luck+"%","#5DE376"); + if(prop.xp) html+=bold_prop_line("XP",(!args.monster&&prop.xp>0&&"+"||"")+prop.xp+(!args.monster&&"%"||""),"#1E73DE"); + if(prop.lifesteal) html+=bold_prop_line("Lifesteal",to_pretty_float(prop.lifesteal)+"%",colors.lifesteal); + if(prop.manasteal) html+=bold_prop_line("Manasteal",to_pretty_float(prop.manasteal)+"%",colors.manasteal); + if(item.goldsteal) html+=bold_prop_line("Goldsteal","Dynamic","gold"); + if(prop.evasion) html+=bold_prop_line("Evasion",to_pretty_float(prop.evasion)+"%","#7AC0F5"); + if(prop.avoidance) html+=bold_prop_line("Avoidance",to_pretty_float(prop.avoidance)+"%","#7AC0F5"); + if(prop.miss && item.type!="elixir") html+=bold_prop_line("Miss",prop.miss+"%","#F36C6E"); + if(prop.reflection) html+=bold_prop_line("Reflection",to_pretty_float(prop.reflection)+"%","#B484E5"); + if(prop.dreturn) html+=bold_prop_line("D.Return",to_pretty_float(prop.dreturn)+"%","#E94959"); + if(prop.crit) html+=bold_prop_line("Crit",to_pretty_float(prop.crit)+"%","#E52967"); + if(prop.critdamage) html+=bold_prop_line("Crit Damage","+"+to_pretty_float(prop.critdamage)+"%","#A8214E"); + if(prop.attack) html+=bold_prop_line("Damage",prop.attack,colors.attack); + if(item.damage_type) + { + if(item.damage_type=="pure") html+=bold_prop_line("Type","Pure","#AA9B55"); + else if(item.damage_type=="magical") html+=bold_prop_line("Type","Magical","#8998AA"); + else if(item.damage_type=="physical") html+=bold_prop_line("Type","Physical","#93AB98"); + } + if(prop.range) html+=bold_prop_line("Range",(!args.monster&&"+"||"")+prop.range,colors.range); + if(prop.hp) html+=bold_prop_line("HP",prop.hp,colors.hp); + if(prop.str) html+=bold_prop_line("Strength",prop.str,colors.str); + if(prop['int']) html+=bold_prop_line("Intelligence",prop['int'],colors['int']); + if(prop.dex) html+=bold_prop_line("Dexterity",prop.dex,colors.dex); + if(prop.vit) html+=bold_prop_line("Vitality",prop.vit,colors.hp); + if(prop['for']) html+=bold_prop_line("Fortitude",prop['for'],colors['for']); + if(prop.mp) html+=bold_prop_line("MP",prop.mp,colors.mp); + if(prop.mp_cost>0) html+=bold_prop_line("Attack MP Cost","+"+prop.mp_cost,colors.mp); + else if(prop.mp_cost) html+=bold_prop_line("Attack MP Cost",prop.mp_cost,colors.mp); + if(prop.mp_reduction>0) html+=bold_prop_line("Skill MP Reduction","%"+prop.mp_reduction,colors.mp); + else if(prop.mp_reduction) html+=bold_prop_line("Skill MP Increase","%"+(-prop.mp_reduction),colors.mp); + if(prop.stat) html+=bold_prop_line("Stat",prop.stat); + if(prop.armor) html+=bold_prop_line("Armor",prop.armor,colors.armor); + if(prop.apiercing) html+=bold_prop_line("A.Piercing",prop.apiercing,colors.armor); + if(prop.rpiercing) html+=bold_prop_line("R.Piercing",prop.rpiercing,colors.resistance); + if(prop.resistance) html+=bold_prop_line("Resistance",prop.resistance,colors.resistance); + if(prop.pnresistance) html+=bold_prop_line("Poison Res.",prop.pnresistance,"#68B84B"); + if(prop.firesistance) html+=bold_prop_line("Fire Res.",prop.firesistance,"#B42B22"); + if(prop.fzresistance) html+=bold_prop_line("Freeze Res.",prop.fzresistance,"#69B1B6"); + if(prop.phresistance) html+=bold_prop_line("Impact Res.",prop.phresistance,"#69B1B6"); + if(prop.stresistance) html+=bold_prop_line("Status Res.",prop.stresistance,"#9FA7B6"); + if(item.wspeed) html+=bold_prop_line("Speed",item.wspeed.toTitleCase(),"gray"); + if(prop.speed) html+=bold_prop_line(item.wtype&&"Run Speed"||"Speed",(!args.monster&&(prop.speed>0)&&"+"||"")+prop.speed,colors.speed); + if(prop.frequency || args.monster) html+=bold_prop_line("A.Speed",(prop.frequency||1)*(args.monster&&100||1),"#3BE681"); + if(prop.output) html+=bold_prop_line("Damage Output",(prop.output>0&&"+"||"")+prop.output+"%","#D93319"); + if(prop.incdmgamp) html+=bold_prop_line("Incoming Damage",prop.incdmgamp+"%","#D93319"); + if(prop.stun) html+=bold_prop_line("Stun",prop.stun+"%","#784224"); + if(prop.explosion) html+=bold_prop_line("Explosion",prop.explosion+"%","#782D33"); + if(prop.blast) html+=bold_prop_line("Blast",prop.blast+"%","#685079"); + if(prop.breaks && prop.breaks>0) html+=bold_prop_line("Breaks",to_pretty_float(prop.breaks)+"%","#782D33"); + if(prop.charisma) html+=bold_prop_line("Charisma",prop.charisma,"#4DB174"); + if(prop.awesomeness) html+=bold_prop_line("Awesomeness",prop.awesomeness,"#FFDE2F"); + if(prop.bling) html+=bold_prop_line("Bling",prop.bling,"#A4E6FF"); + if(prop.cuteness) html+=bold_prop_line("Cuteness",prop.cuteness,"#FD82F0"); + if(prop.intensity) html+=bold_prop_line("Intensity",prop.intensity,"#786D6A"); + if(prop.courage) html+=bold_prop_line("Courage",prop.courage,"#9E1813"); + if(prop.mcourage) html+=bold_prop_line("M.Courage",prop.mcourage,"#4628A0"); + if(prop.pcourage) html+=bold_prop_line("P.Courage",prop.pcourage,"#D19D32"); + if(grade==1 && item.type!="booster") html+=bold_prop_line("Grade","High","#696354"); + if(grade==2 && item.type!="booster") html+=bold_prop_line("Grade","Rare","#6668AC"); + if(grade==3 && item.type!="booster") html+=bold_prop_line("Grade","Legendary","#39A868"); + if(grade==4 && item.type!="booster") html+=bold_prop_line("Grade","Exalted","#2875F9"); // gold: "#E5A818" purple: #8B3EE6" dark-pink: #e84664 + if(prop.poisonous) html+="
Poisonous
"; + if(prop.cooperative) html+="
Cooperative
"; + if(prop.peaceful) html+="
Peaceful
"; + if(prop.supporter) html+="
Supporter
"; + if(prop.abilities) + { + for(var id in prop.abilities) + { + if(!G.skills[id]) continue; + html+=info_line({name:prop.abilities[id].aura&&"Aura"||"Ability",color:"#FC5F39",value:G.skills[id].name,onclick:"dialogs_target=xtarget||ctarget; render_skill('#topleftcornerdialog','"+id+"')"}); + } + } + if(prop.spawns) + { + prop.spawns.forEach(function(s){ + html+=info_line({name:"Spawns",color:"#237B2A",value:G.monsters[s[1]].name,onclick:"render_monster_info('"+s[1]+"')"}); + }) + } + for(var mname in G.maps) + if(item[mname]) + { + html+="
Bonus: "+G.maps[mname].name+" [Only]"+"
"; + } + for(var cname in G.classes) + if(item[cname]) + { + html+="
Bonus: "+cname.toTitleCase()+" [Only]"+"
"; + } + if(args.count) html+=bold_prop_line("Kills",to_pretty_num(args.count),"#7D0C15"); + if(args.score) html+=bold_prop_line("Score",to_pretty_num(args.score),"#C38737"); + if(args.mcount) html+=bold_prop_line("Max Score",to_pretty_num(args.mcount)+" ["+args.mowner+"]","#DCC343"); + if(args.monster && G.base_gold) + { + for(mname in G.base_gold[args.monster]) + { + if(!G.maps[mname] || G.maps[mname].ignore) continue; + html+=bold_prop_line("Base Gold",G.base_gold[args.monster][mname]+" ("+G.maps[mname].name+")","gold"); + } + } + if(prop['class']) html+=bold_prop_line("Class",function(a){ var s=""; a.forEach(function(x){if(s.length) s+=", "; s+=x.toTitleCase()}); return(s) }(prop['class']),"gray"); + if(actual && item.type=="elixir" && args.slot=="elixir") + { + var remains=-msince(new Date(actual.expires))/60.0; + // html+="
"+remains+" hours
"; + html+=prop_remains(remains); + } + else if(item.type=="elixir") + { + html+=prop_remains(item.duration); + } + if(item.achievements) //args.monster + { + html+="
Achievements:
"; + item.achievements.forEach(function(a){ + var acolor="white"; + if(max(args.score,args.mcount)>=a[0]) acolor="#2EA436"; + var an=a[2]; + if(an=="frequency") an="a.speed"; + html+="
["+to_pretty_num(a[0])+"] "+an.toUpperCase()+" "+a[3]+"
"; + }); + if(args.count<100 && 0) + { + html+="
Insight: [LOCKED]
"; + html+="
100 kills are needed to discover the monster specific droprates.
"; + } + } + if(item.ability) + { + if(item.ability=="bash") + { + html+=bold_prop_line("Ability","Bash",colors.ability); + html+="
"+"Stuns the opponent for "+prop.attr1+" seconds with "+prop.attr0+"% chance.
"; + } + else if(item.ability=="freeze") + { + html+=bold_prop_line("Ability","Freeze","#2EBCE2"); + html+="
"+"Freezes the opponent with a "+prop.attr0+"% chance.
"; + } + else if(item.ability=="burn") + { + html+=bold_prop_line("Ability","Burn","#E03D31"); + html+="
"+"Burns the opponent with a "+prop.attr0+"% chance. Deals damage over time.
"; + } + else if(item.ability=="weave") + { + html+=bold_prop_line("Ability","Weave","#AAA9D2"); + html+="
Each hit slows the opponent more and more.
"; + } + else if(item.ability=="secondchance") + { + html+=bold_prop_line("Ability","Second Chance",colors.ability); + html+="
"+"Avoid death with a "+prop.attr0+"% chance.
"; + } + else if(item.ability=="sugarrush") + { + html+=bold_prop_line("Ability","Sugar Rush","#D64770"); + html+="
"+"Trigger a Sugar Rush on attack with 0.25% chance. Gain 240 Attack Speed for 10 seconds!
"; + } + else if(item.ability=="restore_mp") + { + html+=bold_prop_line("Ability","Restore MP","#5D9ED9"); + html+="
"+"Instead of using MP, skills restore 2X the amount with "+prop.attr0+"% chance.
"; + } + else if(G.skills[item.ability]) + { + html+=bold_prop_line("Ability",G.skills[item.ability].name,"#E1924D"); + if(prop.attr0) html+=bold_prop_line("Chance","%"+prop.attr0); + html+="
"+"Activate the ability from the 'SKILLS' system.
"; + } + } + if(item.aura) + { + if(G.conditions[item.aura]) + { + html+=bold_prop_line("Aura",G.conditions[item.aura].name,"#E1924D"); + if(prop.attr0) html+=bold_prop_line("Amount","%"+prop.attr0); + } + } + if(actual && item.charge && !actual.b) + { + html+=bold_prop_line("Charge",to_pretty_float((actual.charges||0)/item.charge*100)+"%","#7433A7"); + } + if(item.explanation) + { + html+="
"+item.explanation+"
"; + } + else if(item.type=="material") + { + html+="
An unknown material, as in, you have no idea what to do with it!
"; + } + if(item.multiplier && item.multiplier!=1) html+=bold_prop_line("Multiplier",item.multiplier,"gray"); + if(prop.set) + { + html+="
Set: "+G.sets[prop.set].name+"
"; + } + if(args.minutes!==undefined) + { + html+=prop_remains(args.minutes/60.0); + } + + if(actual && actual.l) + { + if(actual.l=="s") html+="
Sealed
"; + else if(actual.l=="u") html+="
Unsealing
"; + else html+="
Locked
"; + } + + if(actual && actual.acl) + { + html+="
Account Bound [X]
"; + } + + if(!(args && args.prop)) + { + var phrase="Information"; + if(item.e) phrase="Exchangeable"; + else if(item.upgrade && (!actual || actual.level<10)) phrase="Upgradeable"; + else if(item.compound) phrase="Compoundable"; + else + { + var done=false; + for(var iname in G.craft) + { + if(G.craft[iname].quest!="mcollector") continue; + G.craft[iname].items.forEach(function(i){ + if(i[1]==iname) done=true,phrase="Collectable"; + }); + } + if(!done) + { + for(var iname in G.craft) + { + if(G.craft[iname].quest=="mcollector") continue; + G.craft[iname].items.forEach(function(i){ + if(i[1]==iname) done=true,phrase="Useable"; + }); + } + } + } + if(item.type=="weapon" || offhand_types[item.type]) + { + + var t="",color="#CC3837"; + if(0 && parseInt(item.tier)Type: "+t+"
"; + } + html+="
[i]: "+phrase+"
"; + } + if(args.inventory_ui!==undefined) + { + html+=button_line({name:"{}: Inspect",onclick:"show_json(character.items["+args.inventory_ui+"],{inventory_ui:"+args.inventory_ui+"})",color:colors.inspect}); + } + + + if(args.trade && actual && character.slots.helmet && character.slots.helmet.name.startsWith("ghat")) + { + var svalue=2*calculate_item_value(actual); + html+="
"; + if((actual.q||1)>1) + { + html+="
Q:
"+actual.q+"
" + } + html+="
MINUTES:
20
"; + html+="
GIVEAWAY!
"; // style='color:#A99A5B' + html+="
"; + } + else if(args.trade && actual) + { + var svalue=2*calculate_item_value(actual); + html+="
"; + if((actual.q||1)>1) + { + html+="
Q:
"+actual.q+"
" + } + html+="
GOLD"+(((actual.q||1)>1)&&" [EACH]"||"")+":
"+to_pretty_num(svalue)+"
"; + html+="
PUT UP FOR SALE
"; // style='color:#A99A5B' + html+="
"; + } + if(actual && actual.name=="cxjar") + { + precompute_image_positions(); + if(!actual.data) + { + html+="
Empty / Anomaly
"; + } + else if(!T[actual.data]) + { + html+="
Invalid / "+actual.data+"
"; + } + else + { + html+="
"+cx_sprite(actual.data)+"
"; + } + } + if(actual && actual.name=="emotionjar") + { + if(!G.emotions[actual.data]) + { + html+="
Invalid / "+actual.data+"
"; + } + else + html+="
"+bold_prop_line("Includes","G.emotions."+actual.data+"",colors.inspect)+"
"; + } + if(in_arr(args.slot,trade_slots) && actual && actual.price && args.from_player && !actual.b && !actual.giveaway) + { + trade_item=true; + if((actual.q||1)>1) + { + html+="
Q:
1
"; + } + html+="
"+to_pretty_num(actual.price)+" GOLD"+((actual.q||1)>1&&" [EACH]"||"")+"
"; + html+="
BUY
"; + } + if(in_arr(args.slot,trade_slots) && actual && args.from_player && actual.giveaway) + { + trade_item=true; + if(actual.list.length) + { + html+="
PARTICIPANTS: "+actual.list.join(", ")+"
"; + } + html+="
MINUTES: "+actual.giveaway+"
"; + html+="
JOIN!
"; + } + if(in_arr(args.slot,trade_slots) && actual && actual.price && args.from_player && actual.b) + { + var q=false; if((actual.q||1)>1 && item.s) q=true; + trade_item=true; + if(q) + { + html+="
Q:
1
"; + } + html+="
"+to_pretty_num(actual.price)+" GOLD"+(q&&" [EACH]"||"")+"
"; + html+="
SELL
"; + } + if(args.secondhand) + { + var mult=2; + if(item.cash) mult=3; + trade_item=true; + html+="
"+to_pretty_num(calculate_item_value(actual)*mult*(actual.q||1))+" GOLD
"; + html+="
BUY
"; + } + if(args.lostandfound) + { + trade_item=true; + html+="
"+to_pretty_num(calculate_item_value(actual)*4*(actual.q||1))+" GOLD
"; + html+="
BUY
"; + } + if(value) + { + var f="buy_with_gold"; + if(item.days) html+="
Lasts 30 days
"; + + if(cash) html+="
"+to_pretty_num(item.cash)+" SHELLS
",f="buy_with_shells"; + else html+="
"+to_pretty_num(value)+" GOLD
"; + if(cash && character && item.cash>=character.cash) + { + if(is_electron) + { + html+="
"; + html+="
You can find SHELLS from gems, monsters. In future, from achievements.
"; + } + else + { + html+="
"; + html+="
You can find SHELLS from gems, monsters. In future, from achievements. For the time being, to receive SHELLS and support our game:
"; + html+="BUY or EARN SHELLS "; // onclick='shells_click(); $(this).parent().remove()' + // #EB8D3F nice orange - #33BBD6 meh blue - #54C8C1 ok teal + } + } + else + { + if(item.s) + { + var q=1; + if(item.gives) q=100; + html+="
"; + html+="Q:
"+q+"
| " + html+="BUY "; + html+="
"; + } + else + html+="
BUY
"; + } + } + else if(args.guide && actual) + { + html+="
"+to_pretty_num(calculate_item_value(actual,1))+" GOLD
"; + } + + if(args.token && args.key && args.key!=args.token) + { + var color="#B6A786",phrase="TOKENS"; + var text="#D3D5E0"; + if(args.token=="funtoken") color="#AA6AB3"; + else if(args.token=="pvptoken") text="#CCAE08"; + else if(args.token=="monstertoken") text="#6C531B"; + else if(args.token=="friendtoken") text="#AA6AB3"; + if(G.tokens[args.token][args.key]==1) phrase="TOKEN"; + if(G.tokens[args.token][args.key]<1) html+="
EXCHANGE "+(1/G.tokens[args.token][args.key])+" [1 TOKEN]
"; + else html+="
EXCHANGE ["+G.tokens[args.token][args.key]+" "+phrase+"]
"; + } + + if(args.sell && actual) + { + var value=calculate_item_value(actual); + html+="
"+to_pretty_num(value)+" GOLD
"; + if(item.s && actual.q) + { + var q=actual.q; + html+="
"; + html+="Q:
"+q+"
| " + html+="SELL "; + html+="
"; + } + else + html+="
SELL
"; + } + if(args.cancel) + { + html+="
CLOSE
" + } + if(in_arr(name,booster_items)) + { + if(actual && actual.expires) + { + var remains=round((-msince(new Date(actual.expires)))/(6*24))/10.0; + html+="
"+remains+" days
"; + } + if(!args.sell) html+="
HOW TO USE
"; + } + if(!value && !args.sell && actual && !trade_item && !args.trade && !args.npc) + { + if(item.action) + { + var id=args&&args.slot||args&&args.num; + html+='
'+item.action+'
'; + } + if(item.type=="computer") + { + html+="
NETWORK
"; + } + if(item.type=="stand") + { + html+="
TRADE HISTORY
"; + } + if(0 && item.type=="computer" && (actual.charges===undefined || actual.charges) && gameplay=="normal") + { + html+="
UNLOCK
"; + } + if(item.type=="computer") + { + html+="
NETWORK
"; + } + if(item.type=="stand" && !character.stand) + { + html+="
OPEN
"; + } + if(item.type=="stand" && character.stand) + { + html+="
CLOSE
"; + } + if(item.type=="elixir" && !args.from_player) + { + var phrase="DRINK"; + if(item.eat) phrase="EAT"; + html+="
"+phrase+"
"; + } + if((item.type=="licence" || item.type=="spawner") && !args.from_player) + { + html+="
USE
"; + } + if(in_arr(actual.name,["stoneofxp","stoneofgold","stoneofluck"])) + { + html+="
CONVERT TO SHELLS
"; + } + if(in_arr(actual.name,booster_items)) + { + if(actual.expires) + html+="
SHIFT
"; + else + html+="
ACTIVATE
"; + } + } + if(args.craft) + { + var i=0,phrase="Recipe",action="CRAFT",ecolor="#419FBE"; + if(G.craft[name].quest) phrase="Collect",action="EXCHANGE",ecolor="#4DC353"; + html+="
"; + html+="
"+phrase+"
"; + html+="
"; + G.craft[name].items.forEach(function(item){ + var q=undefined; + if(item[0]!=1) q=item[0]; + html+=item_container({skin:G.items[item[1]].skin,onclick:"render_item_by_name('"+item[1]+"')"},{name:item[1],q:q,level:item[2]}); + i+=1; + if(!(i%4)) html+="
"; + }); + if(G.craft[name].cost) html+=bold_prop_line("Cost",to_pretty_num(G.craft[name].cost),"gold"); + html+="
"+action+"
"; + } + if(args.dismantle) + { + var i=0; + html+="
"; + html+="
Dismantles-to
"; + html+="
"; + G.dismantle[name].items.forEach(function(item){ + var q=undefined; + if(item[0]!=1) q=item[0]; + html+=item_container({skin:G.items[item[1]].skin,onclick:"render_item_by_name('"+item[1]+"')"},{name:item[1],q:q}); + i+=1; + if(!(i%4)) html+="
"; + }); + if(G.dismantle[name].cost) html+=bold_prop_line("Cost",to_pretty_num(G.dismantle[name].cost),"gold"); + } + if(args.condition && args.condition.sn) html+=bold_prop_line("Server",args.condition.sn,"#BED4DE"); + if(args.condition && args.condition.f) html+=bold_prop_line("From",args.condition.f,"#BED4DE"); + if(args.condition && args.condition.c) html+=bold_prop_line("Count",args.condition.c+" left","#891C13"); + if(args.condition && args.condition.sn && args.condition.id) + { + html+="
"+sprite(args.condition.id)+"
"; + } + } + // html+=JSON.stringify(actual); + if(!args.pure) html+="
"; + if(selector=="html") return html; + else if(modal_count) show_modal(html,{wrap:false}); + else $(selector).html(html); +} + +function render_item_by_name(name) +{ + render_item_popup(name); + // render_item(null,{skin:G.items[name].skin,item:G.items[name],name:name}); +} + +function wishlist_form(num,name) +{ + wishlist(num,name,$('.wprice').shtml(),$('.wnumq').shtml(),$('.wlevel').shtml()); +} + +function render_wishlist_item(name,num) +{ + var def=G.items[name],html=""; + html+="
"; + html+="
"+item_container({skin:def.skin,def:def})+"
"; + html+="
" + html+="
Wishlist
"; + html+="
"; + html+="
"+def.name+"
"; + html+="
"; + + html+="
Q:
1
"; + html+="
GOLD"+(def.s&&" [EACH]"||"")+":
"+(calculate_item_value({name:name})+1)+"
"; + if(def.compound||def.upgrade) + html+="
LEVEL:
0
"; + html+="
WISHLIST
"; + + html+="
"; + $("#topleftcornerdialog").html(html); + dialogs_target=character; +} + +function render_set(name) +{ + var set=G.sets[name],selector=last_selector; + var html="
"; + html+="
"+set.name+"
"; + html+="
" + set.items.forEach(function(i){ + html+=item_container({skin:G.items[i].skin}); + }); + html+="
"; + [1,2,3,4,5,6,7,8].forEach(function(num){ + var rep=num; + if(num!=set.items.length) rep=num+"+"; + if(set[num] && Object.keys(set[num]).length) html+="
["+rep+" Equipped] "+render_item("html",{pure:true,item:set[num],prop:set[num]})+"
"; + }); + if(set.explanation) + { + html+="
"+set.explanation+"
"; + } + html+="
"; + if(modal_count) show_modal(html,{wrap:false,hideinbackground:true}); + else $(selector).html(html); +} + +function render_condition(selector,name) +{ + var def=G.conditions[name],minutes=0,condition=undefined,target=xtarget||ctarget; + if(target && target.s[name] && target.s[name].ms) minutes=target.s[name].ms/6000.0/10.0; + if(target && target.s[name]) + { + def=!def&&{}||clone(def); + condition=target.s[name]; + for(var p in target.s[name]) + { + def[p]=target.s[name][p]; + } + } + render_item(selector,{skin:condition&&condition.skin||def&&def.skin,item:def,prop:def,minutes:minutes,condition:condition}); +} + +function render_item_selector(selector,args) +{ + if(args && !args.purpose) purpose="buying"; + var items=[],row=0,html="
"; + for(var id in G.items) + if(!G.items[id].ignore) items.push(G.items[id]); + items.sort(function(a,b){return b.g-a.g;}); + for(var i=0;i8 || def.compound && actual.level>4)) bcolor=xbcolor; + if(bcolor=="gray" && (def.special || calculate_item_grade(actual)==2 || calculate_item_value(actual)>5000000)) + { + bcolor=xbcolor; + pompous=true; + } + } + if(def && actual && def.type=="booster" && actual.level) bcolor=xbcolor; + + if(item.draggable || !("draggable" in item)) + { + item_prop+=" draggable='true' ondragstart='on_drag_start(event)'"; + container_prop+="ondrop='on_drop(event)' ondragover='allow_drop(event)'"; + } + if(item.droppable) + { + item.trigrc=true; + container_prop+="ondrop='on_drop(event)' ondragover='allow_drop(event)'"; + } + if(item.onclick) + { + if(item.draggable) + { + container_prop+=' onclick="'+item.onclick+'" class="clickable" '; + if(item.onmousedown) container_prop+=' onmousedown="'+item.onmousedown+'"'; // to handle middle clicks + } + else container_prop+=' onmousedown="'+item.onclick+'" ontouchstart="'+item.onclick+'" class="clickable" '; + } + + // cls="rotate12"; + if(item.cnum!=undefined) cnum="data-cnum='"+item.cnum+"' "; + if(item.trigrc!=undefined) cnum="data-trigrc='1'"; // on_drop, just trigger on_rclick + if(item.strnum!=undefined) cnum="data-strnum='"+item.strnum+"' "; // render_items_npc - slot + if(item.slot!=undefined) cnum="data-slot='"+item.slot+"' "; + if(item.skid!=undefined) cnum="data-skid='"+item.skid+"' "; + if(item.cid) container_prop+=" id='"+item.cid+"' "; + + if(!item.skin && item.loader) xstyles="overflow: hidden;" + + html+="
"; + + if(item.pui) + { + var chance="%??.??",ccolor="#299C4C",roll="#00.00"; + if(item.pui.chance) + { + var res=set_uchance(item.pui.chance,true); + ccolor=res[0]; chance=res[1]; + roll=set_uroll(item.pui,true); + } + //html+="
"+chance+"
"; + //html+="
"+roll+"
"; + html+="
"+chance+"
"; + html+="
"+roll+"
"; + } + + if(item.skid && !item.skin) html+="
"+item.skid+"
"; // Skill ID + + if(item.shade) + { + if(!G.positions[item.shade]) item.shade="placeholder"; + var spack=G.imagesets[G.positions[item.shade][0]||"pack_20"],sscale=size/spack.size; + var sx=G.positions[item.shade][1],sy=G.positions[item.shade][2]; + html+="
"; + html+="
"; + // Previous default s_op was 0.2 [12/07/18] + html+=""; + html+="
"; + html+="
"; + } + + if(item.skin) + { + if(!G.positions[item.skin]) item.skin="placeholder"; + var pack=G.imagesets[G.positions[item.skin][0]||"pack_20"],x=G.positions[item.skin][1],y=G.positions[item.skin][2]; + var scale=size/pack.size + if(actual && actual.level && actual.level>7) classes+=" glow"+min(item.level,10); + if(item.num!=undefined) rclick="class='rclick"+classes+"' data-inum='"+item.num+"'"; + if(item.snum!=undefined) rclick="class='rclick"+classes+"' data-snum='"+item.snum+"'";// render_items_npc - item + if(item.sname!=undefined) rclick="class='rclick"+classes+"' data-sname='"+item.sname+"'"; + if(item.skname!=undefined) rclick="class='rclick"+classes+"' data-skname='"+item.skname+"'"; + if(item.on_rclick) rclick="class='rclick"+classes+"' data-onrclick=\""+item.on_rclick+'"'; + html+="
"; // overflow:hidden for .skidloader + // the "rid" / random id seems to be needed, on_drop gets elements by id - couldn't work around it without a deep re-analysis [22/06/18] + html+="
"; + html+=""; + html+="
"; + if(actual && actual.name=="monsterbox") + { + var xx=G.positions["egg2"][1],yy=G.positions["egg2"][2] + html+="
"; + html+=""; + html+="
"; + } + if(actual) + { + var prefix="u"; + if(def && def.compound) prefix="c"; + if(actual.c) + { + html+="
"+actual.c+"
"; + } + else if(actual.q && actual.left) + { + html+="
"+actual.q+"
"; + } + else if(actual.q && actual.q!=1) + { + if(actual.b) html+="
"+actual.q+"
"; + else if(def && def.debuff) html+="
"+actual.q+"
"; + else if(def && def.gives && def.gives[0] && def.gives[0][0]=="hp") html+="
"+actual.q+"
"; + else if(def && def.gives && def.gives[0] && def.gives[0][0]=="mp") html+="
"+actual.q+"
"; + else html+="
"+actual.q+"
"; + } + if(actual.level) + { + var level=actual.level,clevel=level; + if(def.type=="booster") clevel=level=(actual.level==1&&"A"||actual.level==2&&"B"||actual.level==3&&"C"||actual.level==4&&"D"||actual.level==5&&"E"||actual.level>5&&"W"); + if(pompous && def.compound && clevel==3) clevel=4; + if(pompous && def.upgrade && clevel==7) clevel=8; + html+="
"+(level==10&&"X"||level==11&&"Y"||level==12&&"Z"||level==5&&prefix=="c"&&"V"||level==6&&prefix=="c"&&"S"||level==7&&prefix=="c"&&"R"||level)+"
"; + } + if(actual.s) html+="
"+actual.s+"
"; + } + if(item.slot && in_arr(item.slot,trade_slots) || item.trade_for_ui) + { + if(actual && actual.giveaway) html+="
@
"; + else if(actual && actual.b) html+="
?
"; + else html+="
$
";//€ + } + else if(actual && actual.l && !item.slot) + { + if(actual.l=="s") html+="
S
"; + else if(actual.l=="u") html+="
U
"; + else html+="
X
"; + } + if(actual && actual.v) html+="

^
"; + else if(actual && actual.m) html+="
M
"; + if(item.loader) + { + html+="
" + } + if(item.skid) // Skill ID + { + html+="
" + html+="
"+item.skid+"
"; + if(actual && actual.name=="throw") + { + html+="
["+(actual.num||0)+"]
"; + } + } + html+="
"; + } + + if(!item.skin && item.loader) + { + html+="
" + } + + + if(!item.skin && item.level) + { + var level=item.level,clevel=level,def=G.items[item.iname],prefix="u"; + if(def && def.compound) prefix="c"; + if(def.type=="booster") clevel=level=(level==1&&"A"||level==2&&"B"||level==3&&"C"||level==4&&"D"||level==5&&"E"||level>5&&"W"); + if(pompous && def.compound && clevel==3) clevel=4; + if(pompous && def.upgrade && clevel==7) clevel=8; + html+="
"+(level==10&&"X"||level==11&&"Y"||level==12&&"Z"||level==5&&prefix=="c"&&"V"||level)+"
"; + } + + html+="
"; + return html; +} + +function render_skillbar(empty) +{ + if(empty){ $("#skillbar").html("").hide(); return; } + // $("#topmid").html(""); + var html="
",i=0; + skillbar.forEach(function(id){ + var current=keymap[id],skin=current; + if(current) + { + if(current && current.skin) skin=current.skin; + else if(current.type=="item" && G.items[current.name]) skin=G.items[current.name].skin; + else if(G.skills[current.name||current]) skin=G.skills[current.name||current].skin; + html+=item_container({skid:id,skin:skin||"",draggable:false,droppable:true,onclick:"on_skill('"+id+"')"},current); + } + else html+=item_container({skid:id,draggable:false,droppable:true}); + if(!(skillbar.length>=8 && !(skillbar.length%2) && !(i%2))) html+="
"; + i++; + }); + html+="
" + $("#skillbar").html(html).css("display","inline-block"); + restart_skill_tints(); + // $("#topmid").show().html(html); +} + +function skill_click(slot) +{ + if(skillsui && keymap[slot]) render_skill("#skills-item",keymap[slot].name||keymap[slot],keymap[slot]); + if(G.skills[slot]) render_skill("#skills-item",slot); +} + +var skills_page="I"; +function render_skills() +{ + if(skillsui) + { + $(".skillsui").hide(); + $("#theskills").remove(); + skillsui=false; + render_skillbar(); + return; + } + var last=0,right_style='text-align: right'; + var html="
" + html+="
"; + html+="
MAPPING 1 2 U
"; + var km1=["1","2","3","4","5","6","7"],km2=["Q","W","E","R","X","T","B"]; + if(skills_page=="II") km1=["8","9","0","G","H","J","K"],km2=["SHIFT","Z","V","M","P","D","BACK"]; + if(skills_page=="U") km1=["ESC","A","C","F","I","TAB","ENTER"],km2=["UP","LEFT","DOWN","RIGHT",",","S","U"]; + html+="
"; + km1.forEach(function(N){ + var current=keymap[N],skin=current; + if(current && current.skin) skin=current.skin; + else if(current && current.type=="item" && G.items[current.name]) skin=G.items[current.name].skin; + else if(current && G.skills[current.name||current]) skin=G.skills[current.name||current].skin; + html+=item_container({skid:N,skin:skin||"",onclick:"on_skill('"+N+"')"},current); + }); + html+="
"; + html+="
"; + km2.forEach(function(N){ + var current=keymap[N],skin=current; + if(current && current.skin) skin=current.skin; + else if(current && current.type=="item" && G.items[current.name]) skin=G.items[current.name].skin; + else if(current && G.skills[current.name||current]) skin=G.skills[current.name||current].skin; + html+=item_container({skid:N,skin:skin||"",onclick:"on_skill('"+N+"')"},current); + }); + html+="
"; + html+="
SKILLS
"; + var s=[],slast=0,a=[],alast=0; + object_sort(G.skills).forEach(function(io){ + var name=io[0],skill=io[1]; + if(skill.slot) + { + var found=false; + skill.slot.forEach(function(p){ + if(character.slots[p[0]] && character.slots[p[0]].name==p[1]) found=true; + }); + if(!found) return; + } + if(skill.inventory) + { + var found=false; + skill.inventory.forEach(function(p){ + for(var i=0;i<42;i++) + { + if(character && character.items[i] && character.items[i].name==p) + found=true; + } + }); + if(!found) return; + } + if(skill.type=="skill" && (!skill['class'] || in_arr(character.ctype,skill['class']) || character.role=="gm")) + s.push({name:name}); + if(skill.type=="passive" && (!skill['class'] || in_arr(character.ctype,skill['class']) || character.role=="gm")) + s.push({name:name}); + if(skill.type=="ability" && (!skill['class'] || in_arr(character.ctype,skill['class']) || character.role=="gm")) + a.push({name:name}); + if(skill.type=="utility" && skill.ui!==false && (!skill['class'] || in_arr(character.ctype,skill['class']))) + a.push({name:name}); + }); + if(character.role=="gm") a.push({name:"gm"}); + // html+="
"; + for(var i=0;i<10;i++) + { + html+="
" + for(var j=0;j<7;j++) + { + if(slast=s.length) break; // i && + } + html+="
ABILITIES
"; + // html+="
"; + for(var i=0;i<10;i++) + { + html+="
" + for(var j=0;j<7;j++) + { + if(alast=a.length) break; + } + html+="
"; + skillsui=true; + render_skillbar(1); + $("body").append("
"); + $(".skillsui").show(); + $("#theskills").html(html); + restart_skill_tints(); +} + +function show_condition(name) +{ + var def=G.conditions[name]; + show_modal(render_item("html",{skin:def.skin,item:def,prop:def}),{wrap:false}); +} + +function render_all_skills_and_conditions() +{ + var last=0,right_style='text-align: right'; + var html=""; + html+="
"; + // html+="
Work in Progress
"; + ["ranger","rogue","warrior","mage","priest","paladin","merchant"].forEach(function(ctype){ + html+="
"+ctype.toTitleCase()+"
"; + object_sort(G.skills).forEach(function(s){ + var name=s[0],skill=s[1]; + if(skill['class'] && skill['class'].includes(ctype)) + { + html+=item_container({skin:skill.skin,onclick:"render_skill('','"+s[0]+"')"}); + } + }); + }); + html+="
Item Skills
"; + object_sort(G.skills).forEach(function(s){ + var name=s[0],skill=s[1]; + if(skill.slot) + { + html+=item_container({skin:skill.skin,onclick:"render_skill('','"+s[0]+"')"}); + } + }); + html+="
Abilities and Utilities
"; + object_sort(G.skills).forEach(function(s){ + var name=s[0],skill=s[1]; + if(skill.type=="ability" || skill.type=="utility") + { + html+=item_container({skin:skill.skin,onclick:"render_skill('','"+s[0]+"')"}); + } + }); + function render_cnd(name,condition) + { + html+="
"+item_container({skin:condition.skin,onclick:"show_condition('"+name+"')"})+"
"+condition.name+"
\""+name+"\"
"; + } + html+="
Buffs
"; + object_sort(G.conditions).forEach(function(c){ + var name=c[0],condition=c[1]; + if(condition.buff) + render_cnd(name,condition); + }); + html+="
Debuffs
"; + object_sort(G.conditions).forEach(function(c){ + var name=c[0],condition=c[1]; + if(condition.debuff) + render_cnd(name,condition); + }); + html+="
Conditions
"; + object_sort(G.conditions).forEach(function(c){ + var name=c[0],condition=c[1]; + if(!condition.debuff && !condition.buff && !condition.technical) + render_cnd(name,condition); + }); + html+="
Technical
"; + object_sort(G.conditions).forEach(function(c){ + var name=c[0],condition=c[1]; + if(condition.technical) + render_cnd(name,condition); + }); + html+="
"; + show_modal(html,{wrap:false,hideinbackground:true,url:"/docs/guide/all/skills_and_conditions"}); +} + +function render_teleporter() +{ + var html="
"; + for(var id in G.maps) + { + if(!G.maps[id].ignore && !G.maps[id].instance) + { + html+="
"+G.maps[id].name+"
"; + } + } + html+="
"; + if(!$('.cxmodalteleporter').length) show_modal(html,{wrap:false}); +} + +function render_travel(the_map) +{ + var html="
"; + var one=false,places=false; + if(!the_map) the_map=character['map'],places=true; + (G.maps[the_map].npcs||[]).forEach(function(def){ + var npc=G.npcs[def.id]; + if(!in_arr(npc.role,["citizen","guard","pvp_announcer"])) + { + if(!one) + { + one=true; + html+="
NPCs in "+G.maps[the_map].name+"
"; + } + var position=def.position||def.positions[0]; + html+="
"+sprite(npc.skin,{width:50,height:50,cx:npc.cx})+"
"+npc.name+"
"; + } + }); + var parsed={},packs={}; + object_sort(G.maps,"random").forEach(function(e){ + var name=e[0],map=e[1]; + if(map.ignore) return; + cshuffle(map.monsters||[]).forEach(function(pack){ + if(name!=the_map && !pack.boundaries || parsed[pack.type]) return; + if(pack.boundaries) + { + cshuffle(pack.boundaries).forEach(function(b){ + if(b[0]!=the_map || parsed[pack.type]) return; + parsed[pack.type]=true; + packs[pack.type]={type:pack.type,x:b[1],y:b[2],hp:G.monsters[pack.type].hp} + }); + } + else + { + parsed[pack.type]=true; + packs[pack.type]={type:pack.type,x:pack.boundary[0],y:pack.boundary[1],hp:G.monsters[pack.type].hp}; + } + }); + }); + if(Object.keys(packs).length) + { + html+="
Monsters in "+G.maps[the_map].name+"
"; + html+="
"; + object_sort(packs,"hpsort").forEach(function(e){ + if((G.monsters[e[0]].cute || G.monsters[e[0]].stationary) && !G.monsters[e[0]].achievements) return; + html+="
"; + html+="
"; + html+=sprite(e[0],{scale:1.5}); + html+="
"; + html+="
"+G.monsters[e[0]].name+"
"; + html+="
"; + }); + html+="
"; + } + if(places) + { + html+="
Places
"; + object_sort(G.maps).forEach(function(io){ + var id=io[0]; + if(!G.maps[id].ignore && !G.maps[id].unlist && !G.maps[id].instance && !G.maps[id].irregular && (G.maps[id].world||"")==(window.world||"") && (!G.maps[id].event || (G.maps[id].event||"")==(window.current_event||""))) + { + html+="
"+G.maps[id].name+"
"; + } + }); + } + html+="
"; + if(!$('.cxmodalteleporter').length) show_modal(html,{wrap:false}); //true,styles:"background-color:#ABACB6",wwidth:420}); +} + +function render_gtravel() // gm monster travel +{ + var html="
",f="render_spawns"; + object_sort(G.maps).forEach(function(io){ + var id=io[0]; + if(!G.maps[id].ignore && !G.maps[id].instance) + { + html+="
"+G.maps[id].name+"
"; + } + }); + html+="
"; + if(!$('.cxmodalteleporter').length) show_modal(html,{wrap:false}); +} + +function render_gmonsters(t) +{ + var html="
"; + object_sort(G.monsters).forEach(function(io){ + var id=io[0]; + html+="
"+G.monsters[id].name+"
"; + }); + html+="
"; + show_modal(html,{wrap:false}); +} + +function render_spawns(id) +{ + var html="
",i=0; + G.maps[id].spawns.forEach(function(io){ + html+="
"+id+"["+i+"]
"; + i++; + }); + html+="
"; + show_modal(html,{wrap:false}); +} + + +function render_interaction(type,sub_type,args) +{ + if(!args) args={}; + if(sub_type!="return_html") + { + topleft_npc="interaction"; rendered_target=topleft_npc; rendered_interaction=type; + } + var left=0,top=0,file="/images/tiles/characters/npc1.png",img_type="normal",pass=false; + var html="
"; + + //face + if(type.auto) // likely, this will be the future method [25/07/17] + { + file=FC[type.skin]; + left=FM[type.skin][1]; + top=FM[type.skin][0]; + img_type=T[type.skin]; + if(type.dialog) type=type.dialog; + } + else if(in_arr(type,["wizard","hardcoretp"])) + { + left=2; top=0; file="/images/tiles/characters/chara8.png"; + } + else if(in_arr(type,["santa","candycane_success"])) + { + left=0; top=0; file="/images/tiles/characters/animationc.png"; img_type="animation"; + } + else if(in_arr(type,["leathers","leather_success"])) + { + left=1; top=0; file="/images/tiles/characters/npc5.png"; + } + else if(in_arr(type,["lostearring","lostearring_success"])) + { + left=3; top=0; file="/images/tiles/characters/chara8.png"; + } + else if(in_arr(type,["mistletoe","mistletoe_success"])) + { + left=0; top=0; file="/images/tiles/characters/chara8.png"; + } + else if(in_arr(type,["crafting"])) + { + left=0; top=0; file="/images/tiles/characters/npc5.png"; + } + else if(in_arr(type,["ornaments","ornament_success"])) + { + left=1; top=0; file="/images/tiles/characters/chara8.png"; + } + else if(in_arr(type,["jailer","guard","blocker","test"])) + { + left=3; top=0; file="/images/tiles/characters/chara5.png"; + } + else if(in_arr(type,["seashells","seashell_success"])) + { + left=0; top=1; file="/images/tiles/characters/npc1.png"; + } + else if(in_arr(type,["lottery"])) + { + left=3; top=0; file="/images/tiles/characters/npc6.png"; + } + else if(in_arr(type,["newupgrade"])) + { + left=3; top=1; file="/images/tiles/characters/chara8.png"; + } + else if(type=="tavern") + { + left=0; top=1; file="/images/tiles/characters/custom1.png"; + } + else if(type=="standmerchant") + { + left=3; top=0; file="/images/tiles/characters/npc5.png"; + } + else if(type=="subscribe") + { + left=3; top=1; file="/images/tiles/characters/chara7.png"; + } + else if(in_arr(type,["gemfragments","gemfragment_success"])) + { + left=2; top=1; file="/images/tiles/characters/npc1.png"; + } + else if(in_arr(type,["buyshells","noshells","yesshells"])) + { + left=0; top=1; file="/images/tiles/characters/dwarf2.png"; + } + else if(in_arr(type,["unlock_items2","unlock_items3","unlock_items4","unlock_items5","unlock_items6","unlock_items7"])) + { + left=3; top=1; file="/images/tiles/characters/npc4.png"; + if(type=="unlock_items2") top=1,left=0; + if(type=="unlock_items3") top=1,left=0; + if(type=="unlock_items4") top=1,left=2; + if(type=="unlock_items5") top=1,left=2; + if(type=="unlock_items6") top=0,left=1; + if(type=="unlock_items7") top=0,left=1; + } + else if(type.startsWith("unlock_")) pass=true; + else return; + + if(pass); + else if(img_type=="normal" || img_type=="full") html+="
"; + else html+="
"; + + + if(type.auto) + { + html+=type.message; + if(type.button) interaction_onclick=type.onclick,html+="
"+type.button+"
"; + if(type.button2) interaction_onclick2=type.onclick2,html+="
"+type.button2+"
"; + } + else if(type=="seashells") + { + html+="Ah, I love the sea, so calming. As a kid, I loved spending time on the beach. Collecting seashells. If you happen to find some, I would love to add them to my collection."; + html+="
I HAVE 20!
"; + } + else if(type=="buyshells") + { + html+="Yo dawg, I can hook you up with some shells If you want. I get these directly from Wizard in bulk so they are legit."; + html+="
HMM, SURE...
"; + } + else if(type=="noshells") + { + html+="Ugh, maybe go farm more gold. It's not like they grow on trees. Just kill some puny monsters, you'll have plenty!"; + } + else if(type=="yesshells") + { + html+="Please doing business with you! You'll have your shells in a couple of milliseconds!"; + } + else if(type=="hardcoretp") + { + html+="Aww, are you stuck here? I can take you places. If you want!"; + html+="
TELEPORT
"; + } + else if(type=="seashell_success") + { + if(Math.random()<0.001) html+="Awww. Ty. Ty. Ty. Xoxo."; + else html+="How kind of you! Please accept this small gift in return."; + d_text("+1",get_npc("fisherman"),{color:"#DFE9D9"}); + } + else if(type=="subscribe") + { + html+="It's that time of the day! Are you in?!"; + html+="
SIGN ME UP!
"; + } + else if(type=="tavern") + { + html+="Tavern. A place for adventurers to relax, drink, unwind, play games, wager, challenge each other in friendly games. Currently under construction."; + } + else if(type=="test") + { + html+="Greetings! Looking for a good deal on weapons and armor? Then you came to the right place! No one sells better gear than me!"; + } + else if(type=="newupgrade") + { + html+="Adventurer! I can upgrade your weapons or armors. Combine 3 accessories to make a stronger one! Tho, beware, the process isn't perfect. Sometimes the items are ... lost."; + html+="
UPGRADE
COMBINE
"; + } + else if(type=="locksmith") + { + html+="Lock - Prevents anything that can destroy an item, selling, upgrading, you name it! Seal - Locks the item in a way that unlocking it takes two days. Unlock - Frees it. Got it? Good. Cost? 250 big ones."; + html+="
LOCK
SEAL
UNLOCK
"; + } + else if(type=="crafting") + { + html+="I can craft or dismantle items for you. Price differs from item to item. Check out my recipes if you are interested!"; + html+="
RECIPES
RECYCLING
CRAFT
DISMANTLE
"; + } + else if(type=="wizard") + { + html+="Well, Hello there! I'm Wizard, I made this game. Hope you enjoy it. If you have any issues, suggestions, feel free to email me at hello@adventure.land!"; + } + else if(type=="santa") + { + html+="Happy holidays! Please excuse my companion, he is a bit grumpy. If you happen to find any candy canes, that might cheer him up!"; + html+="
I HAVE ONE!
"; + } + else if(type=="standmerchant") + { + html+="Anyone can become a merchant and start trading. You only need a merchant stand to display your items on!"; + html+="
LET ME BUY ONE!
"; + } + else if(type=="candycane_success") + { + html+="Ah! Thanks for cheering him up. Here's something for you in return!"; + } + else if(type=="lostearring") + { + html+="Ewww. Ewww. Ewww. These wretched things ate my earrings. Kill them, kill them all. Bring my earrings back!"; + html+="
AS YOU WISH
"; + } + else if(type=="lostearring_success") + { + html+="You did well. Here's something left from one of my old husbands..."; + } + else if(type=="mistletoe") + { + html+="You know, It gets boring in here sometimes ... I'm looking for some excitement. Uhm, Do you have a Mistletoe?"; + html+="
OH MY, I DO!
"; + } + else if(type=="mistletoe_success") + { + html+="Haha! You thought I was going to give you a kiss?! You wish... Take this instead!"; + } + else if(type=="ornaments") + { + html+="Hmm. We should decorate these trees. I need some Ornaments tho. If you happen to collect "+G.items.ornament.e+" of them, let me know!"; + html+="
YOU GOT IT!
"; + } + else if(type=="ornament_success") + { + html+="Thank you! Here's something in return."; //Great idea! + } + else if(type=="gemfragment_success") + { + html+="Bwahahahahah *cough* Ehem.. Thanks! You got a good deal. Keep bringing these fragments to me, don't give them to anyone else."; + d_text("+1",get_npc("gemmerchant"),{color:"#E78295"}); + } + else if(type=="gemfragments") + { + html+="Back in the day we had miners, then came the moles, they work for free yet retrieving the gems is a challenge. Bring me "+G.items.gemfragment.e+" gem fragments and I can give you something exciting in return, no questions asked."; + html+="
I GOT "+G.items.gemfragment.e+"!
"; + } + else if(type=="leathers") + { + html+="Hey, hey, hey! What brings you to this cold land? I personally love it here, ideal for my work. If you can bring me "+G.items.leather.e+" Leathers, I can give you one of my products in return."; + html+="
I HAVE "+G.items.leather.e+"!
"; + } + else if(type=="leather_success") + { + html+="Here you go! Enjoy! Keep bringing leathers to me, I have a lot to offer!"; + d_text("+1",get_npc("leathermerchant"),{color:"#DFE9D9"}); + } + else if(type=="jailer") + { + html+="Tu-tu-tu. Have you been a bad "+(Math.random()<0.5&&"boy"||"girl")+"? No worries. The lawmakers must see the potential in you, so instead of getting rid of you, they sent you here. You are free to leave whenever you want. But please don't repeat your mistake."; + html+="
LEAVE
"; + } + else if(type=="blocker" || type=="guard") + { + var roll=Math.random(); + if(roll<0.5) html+="Hmm. hmm. hmm. Can't let you pass. Check again later tho!"; + else html+="There's some work going on inside. Maybe check back later!"; + } + else if(type=="lottery") + { + html+="Hi Dear! The lottery tickets for this week haven't arrived yet. Apologies :)"; + } + else if(type.startsWith("unlock_")) + { + var pack=args.pack,gold=bank_packs[pack][1],shells=bank_packs[pack][2]; + if(is_electron) + { + html+="Hello! You don't seem to have an account open with me. Would you like to open one? It costs "+to_pretty_num(gold)+" Gold. We hold onto your items forever."; + html+="
PAY "+to_pretty_num(gold)+" GOLD
"; + } + else + { + html+="Hello! You don't seem to have an account open with me. Would you like to open one? It costs "+to_pretty_num(gold)+" Gold or "+to_pretty_num(shells)+" Shells. We hold onto your items forever."; + html+="
USE GOLD
USE SHELLS
"; + } + } + else return; + + html+="
"; + if(sub_type=="return_html") return html; + $("#topleftcornerui").html(html); +} + +function load_nearby(fallback) +{ + friends_inside="nearby"; + var html="",someone=false; + html+=render_com_buttons(); + for(var id in entities) + { + var player=entities[id]; if(!is_player(player)) continue; + someone=true; + } + if(someone) + { + html+=""; + html+=""; + var l=Object.values(entities); + l.sort(function(a,b){ if(!a.afk && b.afk) return -1; if(a.afk && !b.afk) return 1; if(a.ageb.age) return 1; if(a.name+FRIEND"; + if(!actions) actions="None"; + html+=""; + }); + html+="
NameLevelClassAgeStatusActions
"+player.name+""+player.level+""+player.ctype.toUpperCase()+""+player.age+""+afk+""+actions+"
"; + } + else + { + if(fallback) return load_server_list(); + html+="
There is no one nearby.
"; + } + $(".friendslist").html(html); + $(".friendslist").parent().find(".active2").removeClass("active2"); + $(".fnearby").addClass("active2"); + $(".fnearbyx").addClass("active3"); +} + +function load_friends(info) +{ + if(info) + { + if(friends_inside!="friends") return; + var html=""; + html+=render_com_buttons(); + if(!info.chars.length && !friends.length) html+="
You don't have any friends but it's ok. Hang in there! Be kind to other players, get to know them, then friend them from the 'Nearby' tab. Afterwards, you can see when they are online and where they are.
"; + else if(!info.chars.length) html+="
No one online.
"; + else + { + html+=""; + html+=""; + info.chars.sort(function(a,b){ if(!a.afk && b.afk) return -1; if(a.afk && !b.afk) return 1; if(a.ageb.age) return 1; if(a.name"; + }); + html+="
NameLevelClassStatusServer
"+player.level+""+player.type.toUpperCase()+""+afk+""+player.server+"
"; + } + $(".friendslist").html(html); + } + else + { + friends_inside="friends"; + api_call("pull_friends"); + //$(".friendslist").html("
Loading ...
"); + $(".friendslist").html(html); + } + $(".friendslist").parent().find(".active2").removeClass("active2"); + $(".ffriends").addClass("active2"); + $(".ffriendsx").addClass("active3"); +} + +function load_server_list(info) +{ + if(info) + { + if(friends_inside!="server") return; + var html=""; + html+=render_com_buttons(); + if(!info.length) html+="
No one discoverable.
"; + else + { + html+=""; + html+=""; + if(is_pvp) html+=""; + html+=""; + info.sort(function(a,b){ if(!a.afk && b.afk) return -1; if(a.afk && !b.afk) return 1; if(a.ageb.age) return 1; if(a.nameInvite"; + else if(player.name=="Hidden") party="None"; + else if(!player.party) party="You"; + else party=""+player.party+""; + if(player.name!=character.name && player.name!="Hidden") party+=" PM"; + if(name=="Hidden") name="Hidden"; + html+=""; + if(is_pvp) html+=""; + html+=""; + }); + html+="
NameLevelClassAgeStatusPartyKills
"+name+""+player.level+""+player.type.toUpperCase()+""+player.age+""+afk+""+party+""+to_pretty_num(player.kills)+"
"; + } + $(".friendslist").html(html); + } + else + { + friends_inside="server"; + socket.emit("players"); + //$(".friendslist").html("
Loading ...
"); + $(".friendslist").html(html); + } + $(".friendslist").parent().find(".active2").removeClass("active2"); + $(".fserver").addClass("active2"); + $(".fserverx").addClass("active3"); +} + +function load_merchants(info) +{ + if(info) + { + if(friends_inside!="servers") return; + var html=""; + if(!info.chars.length) html="
No merchants with a stand online.
"; + else + { + html+="
"; + info.chars.sort(function(a,b){ if(!a.afk && b.afk) return -1; if(a.afk && !b.afk) return 1; if(a.ageb.age) return 1; if(a.name"; + html+="
"+G.maps[player.map].name+": "+parseInt(player.x)+","+parseInt(player.y)+"
"; + html+="
"+player.server+"
"; + html+="
"; + html+="
"; + }); + html+="
" + } + $(".friendslist").html(html); + } + else + { + friends_inside="servers"; + api_call("pull_merchants"); + $(".friendslist").html(""); + $(".friendslist").parent().find(".active2").removeClass("active2"); + $(".fservers").addClass("active2"); + } +} + +function load_servers_list(info) +{ + friends_inside="servers"; + var html="
"; + html+=""; + html+=""; + html+=""; + html+=""; + X.servers.forEach(function(server){ + var action="Here"; + if(!(server_region==server.region && server.name==server_identifier)) action="Switch"; + html+=""; + }); + html+="
Name#Action
All MerchantsNShow
"+server_regions[server.region]+" "+server.name+""+server.players+""+action+"
"; + $(".friendslist").html(html); + $(".friendslist").parent().find(".active2").removeClass("active2"); + $(".fservers").addClass("active2"); +} + +function load_character_list() +{ + friends_inside="characters"; + var html=""; + html+=""; + html+=""; + html+=""; + X.characters.forEach(function(player){ + var afk="AFK",party=player.party,name=player.name,online=false; + if(player.online) afk="ONLINE",link="Deployed"; + else afk="OFFLINE",link="Deploy"; + if(player.name!=character.name && player.name!="Hidden") party+=" PM"; + if(name=="Hidden") name="Hidden"; + html+=""; + html+=""; + html+=""; + }); + html+="
NameLevelClassStatusDeploy
"+name+""+player.level+""+player.type.toUpperCase()+""+afk+""+link+"
"; + $(".friendslist").html(html); + $(".friendslist").parent().find(".active2").removeClass("active2"); + $(".fcharacters").addClass("active2"); +} + +function show_delete_mail(id) +{ + show_confirm("Delete the mail?","Yes","Cancel",function(){ api_call('delete_mail',{mid:id}); hide_modal(); setTimeout(function(){ hide_modal(); },20); setTimeout(function(){ load_mail() },1600); }); +} + +function render_mail(id) +{ + var mail=window.mail[id]; + var html="
"; + html+="
Delete
"; + html+="
From: "+mail.fro+"
"; + html+="
To: "+mail.to+"
"; + html+="
Subject: "+html_escape(mail.subject)+"
"; + html+="
"+html_escape(mail.message).replace_all("\r\n","
").replace_all("\n","
").replace_all("\t","  ")+"
"; + if(mail.item) + { + var item=JSON.parse(mail.item); + var take=""; + if(!mail.taken) take=" TAKE "; + html+="
Item: "+item_container({skin:G.items[item.name].skin,def:G.items[item.name],draggable:false},item)+take+"
"; + } + html+="
"; + show_modal(html); + api_call("read_mail",{mail:id},{silent:true}); +} + +function load_mail(info) +{ + var html=""; + html+="
Send Mail Cost: 48,000
"; + if(info) + { + if(friends_inside!="mail") return; + if(info.cursored) html+="
(Previous emails not shown)
"; + if(!info.mail.length && info.cursored) html+="
End of mail.
"; + else if(!info.mail.length) html+="
No mail yet.
"; + else + { + html+="
"; + window.mail={}; + info.mail.forEach(function(mail){ + var item_html=""; + window.mail[mail.id]=mail; + if(mail.item && !mail.taken) + { + var item=JSON.parse(mail.item); + item_html+=" ITEM! "; + } + html+="
From: "+mail.fro+" To: "+mail.to+" Subject: "+html_escape(mail.subject)+item_html+"
"; + }); + html+="
" + if(!(info.cursor && info.more)) html+="
End of mail.
"; + else html+="
Load More
"; + } + $(".friendslist").html(html); + } + else + { + friends_inside="mail"; + api_call("pull_mail"); + $(".friendslist").html(html); + $(".friendslist").parent().find(".active2").removeClass("active2"); + $(".fmail").addClass("active2"); + } +} + +function load_chat(info,type) +{ + var html=""; + if(!type) type="all"; + html+="
Global
"; + html+="
Party
"; + html+="
Private
"; + html+="
All Incoming
"; + X.servers.forEach(function(server){ + html+="
"+server.region+" "+server.name+"
"; + }); + // html+="
Pull
"; + if(info) + { + if(friends_inside!="chat") return; + if(info.cursored) html+="
(Previous messages not shown)
"; + if(!info.messages.length && info.cursored) html+="
End of chat.
"; + else if(!info.messages.length) html+="
No messages yet.
"; + else + { + html+="
"; + window.messages={}; + info.messages.forEach(function(message){ + var item_html="",server=""; + window.messages[message.id]=message; + var color="gray"; + if(message.type=="private") color="#CD7879",server=" ["+message.to[0]+"]"; + if(message.type=="party") color="#5B8DB0"; + if(message.type=="ambient" || type=="global") server=" ["+message.server+"]"; + html+="
"+html_escape(message.fro)+":"+" "+html_escape(message.message)+server+"
"; + }); + html+="
" + if(!(info.cursor && info.more)) html+="
End of messages.
"; + else html+="
Load More
"; + } + $(".friendslist").html(html); + } + else + { + friends_inside="chat"; + api_call("pull_messages",{type:type}); + $(".friendslist").html(html); + $(".friendslist").parent().find(".active2").removeClass("active2"); + $(".fchat").addClass("active2"); + } +} + +function load_pvp_list(list) +{ + console.log(list); + var html="
",pwn=false; + list.forEach(function(a_t){ + html+="
"+a_t[0]+" pwned "+a_t[1]+"
"; pwn=true; + }); + if(!pwn) html+="
Noone pwned Anyone
"; + html+="
"; + show_modal(html,{wwidth:400}); +} + +function load_coming_soon(num) +{ + var message="Coming Sooner!"; + $(".friendslist").parent().find(".active2").removeClass("active2"); + if(num==1) $(".fserver").addClass("active2"); + else if(num==2) $(".fguild").addClass("active2"),message="Coming Soon!"; + else if(num==3) $(".fleaders").addClass("active2"),message="Planned, along with achievements, character statistics, weekly, monthly leaderboards"; + else if(num==4) $(".fmail").addClass("active2"),message="Coming Soon!"; + $(".friendslist").html("
"+message+"
"); +} + +var friends_inside="nearby"; +function render_com() +{ + var html=""; + var c_count=0; + api_call("servers_and_characters"); + X.characters.forEach(function(c){if(c.online) c_count+=1;}); + html+="
"; + //html+="
Friends
"; + //html+="
Nearby
"; + //html+="
Server
"; + html+="
Comrades
"; + html+="
Realm
"; + html+="
Characters ["+c_count+"/4]
"; + html+="
Chat
"; + html+="
Mail ["+(window.X && X.unread || 0)+"]
"; + // html+="
Guild
Mail
Leaderboards
"; + html+="
"; + html+="
NOTE: The Communicator is an evolving protoype
"; + // html+="
Refresh
"; + html+="
"; + show_modal(html,{}); //styles:"background: #CACACA; border-color: #4C4C4C" + load_nearby(1); +} + +function render_com_buttons() +{ + var html="
"; + html+="
Friends
"; + html+="
Nearby
"; + html+="
Server
"; + html+="
" + return html; +} + +var IID=null; + +function precompute_image_positions() +{ + // G.images is new [25/09/18] + if(IID) return; + if(!window.SS) window.SS={},window.SSU={}; + if(!Object.keys(T).length) process_game_data(); + IID={}; // IID is reset after game loads, so actual dimensions are live + for(var name in G.sprites) + { + var s_def=G.sprites[name]; + if(s_def.skip) continue; + var row_num=4,col_num=3,s_type="full"; + if(in_arr(s_def.type,["animation"])) row_num=1,s_type=s_def.type; + if(in_arr(s_def.type,["tail"])) col_num=4,s_type=s_def.type; + if(in_arr(s_def.type,["v_animation","head","hair","hat","s_wings","face","makeup","beard"])) col_num=1,s_type=s_def.type; + if(in_arr(s_def.type,["a_makeup","a_hat"])) col_num=3,s_type=s_def.type; + if(in_arr(s_def.type,["wings","body","armor","skin","character"])) s_type=s_def.type; + if(in_arr(s_def.type,["emblem","gravestone"])) row_num=1,col_num=1,s_type=s_def.type; + var matrix=s_def.matrix; + var width=G.images[s_def.file.split("?")[0]]&&G.images[s_def.file.split("?")[0]].width||s_def.width||window.C&&C[s_def.file]&&C[s_def.file].width||312; + var height=G.images[s_def.file.split("?")[0]]&&G.images[s_def.file.split("?")[0]].height||s_def.height||window.C&&C[s_def.file]&&C[s_def.file].height||288; + // if(s_def.columns!=4 || s_def.rows!=2) continue; + for(var i=0;i\ +
"; + // Math.ceil((IID[name][4]-width)/2) + } + catch(e){ + console.log(e); + } + return ""; +} + +function sprite(name,args) +{ + try{ + if(!args) args={}; + if(is_string(args)) args={cx:args}; + if(is_string(args.cx)) args.cx=args.cx.split(","); + if(!args.cx) args.cx={}; + if(!args.scale) args.scale=1.5; + if(G.monsters[name] && G.monsters[name].size) args.scale-=1-G.monsters[name].size; + precompute_image_positions(); + if(!IID[name] && G.items[name]) return item_container({skin:name,bcolor:"black"}); + if(G.monsters[name] && G.monsters[name].skin) name=G.monsters[name].skin; + prune_cx(args.cx,name); + if(!args.width) args.width=40; + if(!args.height) args.height=50; + if(!args.rx_disp) args.rx_disp=0; + if(args.full) + { + if(G.dimensions[name]) args.width=(G.dimensions[name][0]+4)*args.scale,args.height=(G.dimensions[name][1]+5)*args.scale; + else args.width=IID[name][4]*args.scale,args.height=IID[name][5]*args.scale; + } + if(G.dimensions[name] && G.dimensions[name][3]) args.rx_disp=-G.dimensions[name][3]*args.scale; + var html="
"; + var head_y=G.cosmetics.default_head_place; + var hair_y=G.cosmetics.default_hair_place; + var hat_y=G.cosmetics.default_hat_place; + var skin=null,rip=false,cxs=[name],cx_prop={}; + for(var n in args.cx) cxs.push(n); + cxs.forEach(function(cid){ + if(G.cosmetics.prop[cid]) + G.cosmetics.prop[cid].forEach(function(p){ + cx_prop[p]=true; + }) + }); + var body_type="full"; + if(T[name]=="armor") body_type="armor"; + else if(T[name]=="body") body_type="body"; + else if(T[name]=="character") body_type="character"; + if(args.rip) + { + // originally opacity=0.4 + html+=sprite_image(args.cx.gravestone||"gravestone",{cwidth:args.width,scale:args.scale})+"
"; + return html; + } + var opacity=1,j=args.j||0; + if(body_type!="full" && !args.cx.head) args.cx.head="makeup117"; + if(body_type!="character" && !args.cx.head) args.cx.head="makeup117"; + // console.log(!(IID[name][4]%2)+" "+args.x_disp); + var head_dy={"large":2,"tall":1,"normal":0,"small":-1,"xsmall":-3,"xxsmall":-4}[SS[name]]; head_y+=head_dy; + var head_dh=G.cosmetics.head[args.cx.head]&&G.cosmetics.head[args.cx.head][3]||0; + var hair_dy=G.cosmetics.hair[args.cx.hair]&&G.cosmetics.hair[args.cx.hair][0]||0; hair_dy+=head_dh+head_dy; hair_y+=hair_dy; + var hair_dh=G.cosmetics.hair[args.cx.hair]&&G.cosmetics.hair[args.cx.hair][1]||0; hat_y+=hair_dh+head_dy; + var hat_dy=G.cosmetics.hat[args.cx.hat]||0; hat_dy+=head_dh; hat_y+=hat_dy; + var hidden_head=j==3||G.cosmetics.prop[name]&&G.cosmetics.prop[name].includes("covers"); + var cx={}; + for(var place in args.cx) + { + var cid=args.cx[place]; + if(!cid || !cid.length || !IID[cid]) continue; + if(place=="head") + { + if(body_type!="full" && body_type!="character") cx.head=cid; + } + else if(place=="hair") + { + if(body_type!="full" && body_type!="character" && !cx_prop.no_hair) cx.hair=cid; + } + else if(place=="upper") + { + if(body_type!="full" && T[cid]=="armor" && SSU[cid]==SSU[name]) cx.upper=cid; + } + else + cx[place]=cid; + } + if(cx.head && !skin) + { + skin={ + "small":G.cosmetics.head[cx.head]&&G.cosmetics.head[cx.head][0]||"sskin1a", + "normal":G.cosmetics.head[cx.head]&&G.cosmetics.head[cx.head][1]||"mskin1a", + "tall":G.cosmetics.head[cx.head]&&G.cosmetics.head[cx.head][1]||"mskin1a", + "large":G.cosmetics.head[cx.head]&&G.cosmetics.head[cx.head][2]||"lskin1a"}[SS[name]]; + } + if(cx.head && hidden_head) html+=sprite_image(cx.head,{p:head_y,cwidth:args.width,scale:args.scale,opacity:opacity,j:j}); + if(cx.back && j!=3) html+=sprite_image(cx.back,{cwidth:args.width,scale:args.scale,opacity:opacity,j:j}); + if(skin) html+=sprite_image(skin,{cwidth:args.width,scale:args.scale,opacity:opacity,j:j,x_disp:args.x_disp}); + if(!(IID[name][4]%2)) html+=sprite_image(name,{cwidth:args.width,scale:args.scale,opacity:opacity,j:j,x_disp:args.rx_disp+-0.5});// old 26px width frame + else html+=sprite_image(name,{cwidth:args.width,scale:args.scale,opacity:opacity,j:j,x_disp:args.rx_disp}); + if(cx.upper) html+=sprite_image(cx.upper,{cwidth:args.width,scale:args.scale,opacity:opacity,j:j,rheight:8}); + if(cx.head && !hidden_head) html+=sprite_image(cx.head,{p:head_y,cwidth:args.width,scale:args.scale,opacity:opacity,j:j}); + if(j!=3 && cx.makeup) html+=sprite_image(cx.makeup,{p:head_y+G.cosmetics.default_makeup_position,cwidth:args.width,scale:args.scale,opacity:opacity,j:j}); + if(cx.hair) html+=sprite_image(cx.hair,{p:hair_y,cwidth:args.width,scale:args.scale,opacity:opacity,j:j}); + if(j!=3 && cx.face) html+=sprite_image(cx.face,{p:head_y+G.cosmetics.default_face_position,cwidth:args.width,scale:args.scale,opacity:opacity,j:j}); + if(j!=3 && cx.chin) html+=sprite_image(cx.chin,{p:head_y+G.cosmetics.default_beard_position,cwidth:args.width,scale:args.scale,opacity:opacity,j:j}); + if(cx.tail) html+=sprite_image(cx.tail,{p:0,cwidth:args.width,scale:args.scale,opacity:opacity,j:j}); + if(cx.hat) html+=sprite_image(cx.hat,{p:hat_y,cwidth:args.width,scale:args.scale,opacity:opacity,j:j}); + if(cx.back && j==3) html+=sprite_image(cx.back,{cwidth:args.width,scale:args.scale,opacity:opacity,j:j}); + if(rip) html+=sprite_image(rip,{cwidth:args.width,scale:args.scale,j:j}); + html+="
"; + return html; + }catch(e){ + console.log(e) + } + return ""; +} + +function cx_sprite(name,args) +{ + if(!args) args={}; + function render_cosmetic(slot,rargs) + { + if(!rargs) rargs={}; + if(!rargs.color && (cx[slot] || slot=="skin")) rargs.color="#17B8E3"; + else if(!rargs.color) rargs.color="#5DBA50"; + rargs.bg="#D5D5D5"; + rargs.bg="#504254"; + var width=rargs.width||49,height=48,labels=""; + if(rargs.rip) height=48; + rargs.scale=rargs.scale||2; + rargs.j=rargs.j||0; + if(args.labels) + { + var drop=false,mdrop=false,ccx=false,icx=false; + for(var dname in G.drops) + { + if(!(G.items[dname] && G.items[dname].e)) continue; + G.drops[dname].forEach(function(t){ + if(t[1]=="cx" && t[2]==name) + drop=true; + }) + } + for(var mname in G.monsters) + { + if(!(G.drops && G.drops.monsters && G.drops.monsters[mname])) continue; + G.drops.monsters[mname].forEach(function(t){ + if(t[1]=="cxjar" && t[3]==name) + mdrop=true; + }) + } + for(var cname in G.classes) + { + if((G.classes[cname].xcx||[]).includes(name)) ccx=true; + } + for(var iname in G.items) + { + if((G.items[iname].xcx||[]).includes(name)) icx=true; + } + if(drop) labels+="E"; + if(mdrop) labels+="M"; + if(ccx) labels+="C"; + if(icx) labels+="I"; + if(!labels) labels+="X"; + } + html+="
"; + html+="
"; + if(args.labels) html+="
"+labels+"
"; + html+="
"+sprite(rargs.skin,{cx:rargs.cx,scale:rargs.scale,height:rargs.height*rargs.scale+20*rargs.scale,j:rargs.j,width:width,rip:rargs.rip})+"
"; + html+="
"+(rargs.text||slot).toUpperCase()+"
"; + html+="
" + html+="
"; + } + var html=""; + precompute_image_positions(); + if(["hair","face","head","makeup","a_makeup"].includes(T[name])) + { + var cx={head:T[name]=="head"&&name||"bwhead"}; + cx[cxtype_to_slot[T[name]]]=name; + render_cosmetic(T[name],{skin:T[name]=="head"&&"nothing"||"mabw",top:50+(T[name]=="head"&&-6||0),scale:3,cx:cx,height:16,aheight:4}); + return html; + } + else if(["hat","a_hat"].includes(T[name])) + { + var cx={head:"bwhead"}; + cx[cxtype_to_slot[T[name]]]=name; + render_cosmetic(T[name],{skin:"mabw",top:50,scale:3,cx:cx,height:16,aheight:4}); + return html; + } + else if(["beard","mask"].includes(T[name])) + { + var cx={head:"bwhead"}; + cx[cxtype_to_slot[T[name]]]=name; + render_cosmetic(T[name],{skin:"mabw",top:30,scale:3,cx:cx,height:16}); + return html; + } + else if(["armor","body","character"].includes(T[name])) + { + var cx={head:"bwhead"}; + cx[cxtype_to_slot[T[name]]]=name; + render_cosmetic(T[name]=="character"&&"char"||T[name],{skin:name,top:-7,scale:2,cx:cx,height:36,aheight:16}); + return html; + } + else if(["gravestone"].includes(T[name])) + { + var cx={head:"bwhead"}; + cx[cxtype_to_slot[T[name]]]=name; + render_cosmetic("stone",{skin:"mabw",top:-7,scale:2,cx:cx,height:36,aheight:16,rip:true}); + return html; + } + else if(["s_wings","tail"].includes(T[name])) + { + var cx={head:"bwhead"}; + cx[cxtype_to_slot[T[name]]]=name; + render_cosmetic(T[name],{skin:"mabw",j:3,top:-7,width:59,scale:2,cx:cx,height:36,aheight:16}); + return html; + } + else + { + return sprite(name,{cx:{head:"bwhead"}}); + } +} + +function cx_move(x,y) +{ + last_cx_d[0]+=x; + last_cx_d[1]+=y; + var skin=character.skin,cx=character.cx; + if(!textures.naked) generate_textures("naked","full"); + character.skin="naked"; character.cx={}; + cosmetics_logic(character); + character.skin=skin; character.cx=cx; + cosmetics_logic(character); + for(var n in character.cxc) + { + if(character.cxc[n].skin==last_cx_name) + { + character.cxc[n].x+=last_cx_d[0]; + character.cxc[n].y+=last_cx_d[1]; + character.cxc[n].moved=true; + } + } + var log=last_cx_name+":"; + if(!last_cx_d[0] && !last_cx_d[1]) log+=" default position"; + if(last_cx_d[0]<0) log+=" [move left "+(-last_cx_d[0])+"px]"; + if(last_cx_d[0]>0) log+=" [move right "+(last_cx_d[0])+"px]"; + if(last_cx_d[1]<0) log+=" [move up "+(-last_cx_d[1])+"px]"; + if(last_cx_d[1]>0) log+=" [move down "+(last_cx_d[1])+"px]"; + add_log(log,"#BD6BB6"); +} + +function insert_cx_tuners() +{ + var html="
"; + html+="
UP
"; + html+="
DOWN
"; + html+="
LEFT
"; + html+="
RIGHT
"; + html+="
" + $("body").append(html); +} + +var last_cx_slot="",last_cx_name="",last_cx_d=[0,0]; +function render_cgallery(skin,cx,slot) +{ + cx=clone(cx); + var html="",types=[],a=[],b=[],n=null,s,old=null,j=0,cx_count=all_cx(character,1),cx_map=map_cx(character),me=false; + if((xtarget||target).me) me=true; + var bg="#504254"; + function render_cosmetic(reset) + { + var width=47,height=64,html=""; + var aheight=32; + if(cx.hat || reset && slot=="hat") height+=12,aheight+=6; + if(slot=="gravestone") height=48; + var scale=2,found=false,onclick="onclick='if(!(xtarget||target).me) socket.emit(\"send\",{name:(xtarget||target).name,cx:\""+s[0]+"\"}),push_deferred(\"send\"); else socket.emit(\"cx\",{slot:\""+slot+"\",name:\""+s[0]+"\"}),last_cx_slot=\""+slot+"\",last_cx_name=\""+s[0]+"\",last_cx_d=[0,0],push_deferred(\"cx\"); hide_modal();' class='clickable'"; + if(!me && cx_map[s[0]] && cx_count[cx_map[s[0]]]>0 || me && cx_count[s[0]]!==undefined || me && character.role==="cx" || reset) found=true; + else onclick=""; + html+="
"; + if(mode.cosmetics) html+="
"+s[0]+"
"; + html+="
"; + html+="
"+sprite(skin,{cx:cx,scale:scale,height:aheight*scale+20*scale,j:j,width:width,rip:(slot=="gravestone")})+"
"; + html+="
" + html+="
"; + if(reset) n=html; + else if(found) a.push(html); + else b.push(html); + } + for(var cxt in cxtype_to_slot) + { + if(cxtype_to_slot[cxt]==slot) types.push(cxt); + } + + if(slot=="upper") types=["body","armor"]; + if(slot=="back") types.push("tail"); // synced with server.js/'cx' + if(slot=="face") types.push("makeup"),types.push("a_makeup"); + + if(slot=="tail" || slot=="back") j=3; + object_sort(T).forEach(function(x){ + s=x; + if(in_arr(s[1],types)) + { + if(T[skin]=="full" && slot=="head") return; + if(slot=="upper" && (T[skin]=="full" || SSU[s[0]]!=SSU[skin] || skin==s[0] || T[s[0]]!="armor")) return; + if(cxtype_to_slot[s[1]]=="skin") skin=s[0]; + else if(slot=="upper") cx.upper=s[0]; + else + { + types.forEach(function(t){ delete cx[cxtype_to_slot[t]]; }) + cx[cxtype_to_slot[s[1]]]=s[0]; + } + render_cosmetic(); + } + }); + if((a.length || b.length) && slot!="skin") + { + s=[""]; + types.forEach(function(t){ delete cx[cxtype_to_slot[t]]; }) + render_cosmetic(1); + } + if(a.length || b.length) + { + a.forEach(function(h){html+=h;}); + if(n) html+=n; + b.forEach(function(h){html+=h;}); + show_modal(html,{wrap:false,styles:"max-width:400px"}); + } + else show_modal("
No Alternatives
",{wrap:false,styles:"max-width:400px"}); +} + +var last_cx={},last_skin=""; +function render_cosmetics(player,args) +{ + if(!args) args={}; last_cx=player.cx; last_skin=player.skin; + if(args.toggle && $('.cccx').html()) return $("#topleftcornerdialog").html(""); + function render_cosmetic(slot,rargs) + { + if(!rargs) rargs={}; + if(!rargs.color && (player.cx[slot] || slot=="skin")) rargs.color="#17B8E3"; + else if(!rargs.color) rargs.color="#5DBA50"; + rargs.bg="#D5D5D5"; + rargs.bg="#504254"; + var width=39,height=48; + if(rargs.size=="big") + { + rargs.scale=3; + width=91,height=118; + rargs.top=12; + } + if(rargs.rip) height=48; + rargs.scale=rargs.scale||2; + rargs.j=rargs.j||0; + html+="
"; + html+="
"+(rargs.text||slot).toUpperCase()+"
"; + html+="
"; + else html+=">"; + html+="
"; + html+="
"+sprite(player.skin,{cx:rargs.cx,scale:rargs.scale,height:player.aheight*rargs.scale+20*rargs.scale,j:rargs.j,width:width,rip:rargs.rip})+"
"; + html+="
" + html+="
"; + } + var html="
"; + var color=""; + html+="
"; + html+="
"; + if(IID[player.skin][8]=="full") color="#BB2242"; + render_cosmetic("head",{text:"skin",top:-9,scale:3,color:color,cx:{head:player.cx.head}}); + render_cosmetic("hair",{top:6,scale:3,mleft:8,color:color,cx:{head:player.cx.head,hair:player.cx.hair||"bwhair"}}); + color=""; + render_cosmetic("hat",{top:12,scale:3,mleft:8,color:color,cx:{head:player.cx.head,hair:player.cx.hair,hat:player.cx.hat||"bwhat"}}); + html+="
"; + html+="
"; + render_cosmetic("face",{top:-9,scale:3,cx:{head:player.cx.head,hair:player.cx.hair,face:player.cx.face||"bwglasses"}}); + var cx=clone(player.cx); delete cx.upper; delete cx.back; + render_cosmetic("skin",{text:"ATTIRE",top:-12,scale:2,mleft:8,cx:cx}); + if(IID[player.skin][8]=="full") color="#BB2242"; + var cx=clone(player.cx); delete cx.back; + render_cosmetic("upper",{top:-5,scale:2,mleft:8,color:color,cx:cx}); + color=""; + html+="
"; + html+="
"; + render_cosmetic("chin",{top:-20,scale:3,cx:{head:player.cx.head,hair:player.cx.hair,chin:player.cx.chin||"beard112"}}); + render_cosmetic("special",{top:10,text:"sp. fx",cx:player.cx,scale:1,mleft:8,bg:"#E3B245"}); + var cx=clone(player.cx); delete cx.tail; + render_cosmetic("back",{top:-2,j:3,scale:1.5,mleft:8,cx:cx}); + //var cx=clone(player.cx); delete cx.back; + //render_cosmetic("tail",{top:-20,j:3,scale:2,mleft:8,cx:cx}); + html+="
"; + html+="
"; + html+="
"; + html+="
"; + render_cosmetic("skin",{text:"looks",cx:player.cx,size:"big",mleft:8}); + html+="
"; + html+="
"; + render_cosmetic("gravestone",{text:"RIP",top:-16,scale:1.75,mleft:8,cx:cx,rip:true,bg:"#8cb0bb"}); + render_cosmetic("EMOTES",{top:10,j:3,scale:1,mleft:8,cx:cx,bg:"#8756ff"}); + html+="
"; + html+="
"; + html+="
"; + dialogs_target=xtarget||ctarget; + $("#topleftcornerdialog").html(html); +} + +function load_class_info(name,look) +{ + var html=""; + name=name||window.chartype||"warrior"; + if(!G.classes[name]) return; + look=nunv(look,nunv(window.thelooks,0)); + if(!G.classes[name].looks[look]) look=0; + + //html+="
"; + html+="
"+sprite(G.classes[name].looks[look][0],{cx:G.classes[name].looks[look][1],scale:2,height:72,width:52})+"
"; + html+="
Class: "+name.toTitleCase()+"
"; + html+="
Primary Attribute: "+G.classes[name].main_stat.toTitleCase()+"
"; + if(G.classes[name].side_stat) html+="
Secondary Attribute: "+G.classes[name].side_stat.toTitleCase()+"
"; + html+="
Description: "+G.classes[name].description+"
"; + + $("#features").css("height",208).html(html); + // $(".salesui").css("bottom",208+36); +} + +function to_pretty_fraction(num) +{ + var html="IMPL"; + [[1000000000,"1B","#B30000"],[100000000,"100M","#825CD5"],[10000000,"10M","#825CD5"],[1000000,"1M","#825CD5"],[100000,"100K","#5090D3"],[10000,"10K","#5090D3"],[1000,"1K","#5090D3"],[100,"100","#909090"],[10,"10","#909090"],[1,"1","#64C287"]].forEach(function(l){ + if(num*l[0]>1) + html=to_pretty_float(num*l[0])+"/"+l[1]+""; + }); + return html; +} + + + diff --git a/js/interact/1.2.6/interact.js b/js/interact/1.2.6/interact.js new file mode 100644 index 0000000..ffbd05d --- /dev/null +++ b/js/interact/1.2.6/interact.js @@ -0,0 +1,5976 @@ +/** + * interact.js v1.2.6 + * + * Copyright (c) 2012-2015 Taye Adeyemi + * Open source under the MIT License. + * https://raw.github.com/taye/interact.js/master/LICENSE + */ +(function (realWindow) { + 'use strict'; + + // return early if there's no window to work with (eg. Node.js) + if (!realWindow) { return; } + + var // get wrapped window if using Shadow DOM polyfill + window = (function () { + // create a TextNode + var el = realWindow.document.createTextNode(''); + + // check if it's wrapped by a polyfill + if (el.ownerDocument !== realWindow.document + && typeof realWindow.wrap === 'function' + && realWindow.wrap(el) === el) { + // return wrapped window + return realWindow.wrap(realWindow); + } + + // no Shadow DOM polyfil or native implementation + return realWindow; + }()), + + document = window.document, + DocumentFragment = window.DocumentFragment || blank, + SVGElement = window.SVGElement || blank, + SVGSVGElement = window.SVGSVGElement || blank, + SVGElementInstance = window.SVGElementInstance || blank, + HTMLElement = window.HTMLElement || window.Element, + + PointerEvent = (window.PointerEvent || window.MSPointerEvent), + pEventTypes, + + hypot = Math.hypot || function (x, y) { return Math.sqrt(x * x + y * y); }, + + tmpXY = {}, // reduce object creation in getXY() + + documents = [], // all documents being listened to + + interactables = [], // all set interactables + interactions = [], // all interactions + + dynamicDrop = false, + + // { + // type: { + // selectors: ['selector', ...], + // contexts : [document, ...], + // listeners: [[listener, useCapture], ...] + // } + // } + delegatedEvents = {}, + + defaultOptions = { + base: { + accept : null, + actionChecker : null, + styleCursor : true, + preventDefault: 'auto', + origin : { x: 0, y: 0 }, + deltaSource : 'page', + allowFrom : null, + ignoreFrom : null, + _context : document, + dropChecker : null + }, + + drag: { + enabled: false, + manualStart: true, + max: Infinity, + maxPerElement: 1, + + snap: null, + restrict: null, + inertia: null, + autoScroll: null, + + axis: 'xy' + }, + + drop: { + enabled: false, + accept: null, + overlap: 'pointer' + }, + + resize: { + enabled: false, + manualStart: false, + max: Infinity, + maxPerElement: 1, + + snap: null, + restrict: null, + inertia: null, + autoScroll: null, + + square: false, + preserveAspectRatio: false, + axis: 'xy', + + // use default margin + margin: NaN, + + // object with props left, right, top, bottom which are + // true/false values to resize when the pointer is over that edge, + // CSS selectors to match the handles for each direction + // or the Elements for each handle + edges: null, + + // a value of 'none' will limit the resize rect to a minimum of 0x0 + // 'negate' will alow the rect to have negative width/height + // 'reposition' will keep the width/height positive by swapping + // the top and bottom edges and/or swapping the left and right edges + invert: 'none' + }, + + gesture: { + manualStart: false, + enabled: false, + max: Infinity, + maxPerElement: 1, + + restrict: null + }, + + perAction: { + manualStart: false, + max: Infinity, + maxPerElement: 1, + + snap: { + enabled : false, + endOnly : false, + range : Infinity, + targets : null, + offsets : null, + + relativePoints: null + }, + + restrict: { + enabled: false, + endOnly: false + }, + + autoScroll: { + enabled : false, + container : null, // the item that is scrolled (Window or HTMLElement) + margin : 60, + speed : 300 // the scroll speed in pixels per second + }, + + inertia: { + enabled : false, + resistance : 10, // the lambda in exponential decay + minSpeed : 100, // target speed must be above this for inertia to start + endSpeed : 10, // the speed at which inertia is slow enough to stop + allowResume : true, // allow resuming an action in inertia phase + zeroResumeDelta : true, // if an action is resumed after launch, set dx/dy to 0 + smoothEndDuration: 300 // animate to snap/restrict endOnly if there's no inertia + } + }, + + _holdDuration: 600 + }, + + // Things related to autoScroll + autoScroll = { + interaction: null, + i: null, // the handle returned by window.setInterval + x: 0, y: 0, // Direction each pulse is to scroll in + + // scroll the window by the values in scroll.x/y + scroll: function () { + var options = autoScroll.interaction.target.options[autoScroll.interaction.prepared.name].autoScroll, + container = options.container || getWindow(autoScroll.interaction.element), + now = new Date().getTime(), + // change in time in seconds + dtx = (now - autoScroll.prevTimeX) / 1000, + dty = (now - autoScroll.prevTimeY) / 1000, + vx, vy, sx, sy; + + // displacement + if (options.velocity) { + vx = options.velocity.x; + vy = options.velocity.y; + } + else { + vx = vy = options.speed + } + + sx = vx * dtx; + sy = vy * dty; + + if (sx >= 1 || sy >= 1) { + if (isWindow(container)) { + container.scrollBy(autoScroll.x * sx, autoScroll.y * sy); + } + else if (container) { + container.scrollLeft += autoScroll.x * sx; + container.scrollTop += autoScroll.y * sy; + } + + if (sx >=1) autoScroll.prevTimeX = now; + if (sy >= 1) autoScroll.prevTimeY = now; + } + + if (autoScroll.isScrolling) { + cancelFrame(autoScroll.i); + autoScroll.i = reqFrame(autoScroll.scroll); + } + }, + + isScrolling: false, + prevTimeX: 0, + prevTimeY: 0, + + start: function (interaction) { + autoScroll.isScrolling = true; + cancelFrame(autoScroll.i); + + autoScroll.interaction = interaction; + autoScroll.prevTimeX = new Date().getTime(); + autoScroll.prevTimeY = new Date().getTime(); + autoScroll.i = reqFrame(autoScroll.scroll); + }, + + stop: function () { + autoScroll.isScrolling = false; + cancelFrame(autoScroll.i); + } + }, + + // Does the browser support touch input? + supportsTouch = (('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch), + + // Does the browser support PointerEvents + supportsPointerEvent = !!PointerEvent, + + // Less Precision with touch input + margin = supportsTouch || supportsPointerEvent? 20: 10, + + pointerMoveTolerance = 1, + + // for ignoring browser's simulated mouse events + prevTouchTime = 0, + + // Allow this many interactions to happen simultaneously + maxInteractions = Infinity, + + // Check if is IE9 or older + actionCursors = (document.all && !window.atob) ? { + drag : 'move', + resizex : 'e-resize', + resizey : 's-resize', + resizexy: 'se-resize', + + resizetop : 'n-resize', + resizeleft : 'w-resize', + resizebottom : 's-resize', + resizeright : 'e-resize', + resizetopleft : 'se-resize', + resizebottomright: 'se-resize', + resizetopright : 'ne-resize', + resizebottomleft : 'ne-resize', + + gesture : '' + } : { + drag : 'move', + resizex : 'ew-resize', + resizey : 'ns-resize', + resizexy: 'nwse-resize', + + resizetop : 'ns-resize', + resizeleft : 'ew-resize', + resizebottom : 'ns-resize', + resizeright : 'ew-resize', + resizetopleft : 'nwse-resize', + resizebottomright: 'nwse-resize', + resizetopright : 'nesw-resize', + resizebottomleft : 'nesw-resize', + + gesture : '' + }, + + actionIsEnabled = { + drag : true, + resize : true, + gesture: true + }, + + // because Webkit and Opera still use 'mousewheel' event type + wheelEvent = 'onmousewheel' in document? 'mousewheel': 'wheel', + + eventTypes = [ + 'dragstart', + 'dragmove', + 'draginertiastart', + 'dragend', + 'dragenter', + 'dragleave', + 'dropactivate', + 'dropdeactivate', + 'dropmove', + 'drop', + 'resizestart', + 'resizemove', + 'resizeinertiastart', + 'resizeend', + 'gesturestart', + 'gesturemove', + 'gestureinertiastart', + 'gestureend', + + 'down', + 'move', + 'up', + 'cancel', + 'tap', + 'doubletap', + 'hold' + ], + + globalEvents = {}, + + // Opera Mobile must be handled differently + isOperaMobile = navigator.appName == 'Opera' && + supportsTouch && + navigator.userAgent.match('Presto'), + + // scrolling doesn't change the result of getClientRects on iOS 7 + isIOS7 = (/iP(hone|od|ad)/.test(navigator.platform) + && /OS 7[^\d]/.test(navigator.appVersion)), + + // prefix matchesSelector + prefixedMatchesSelector = 'matches' in Element.prototype? + 'matches': 'webkitMatchesSelector' in Element.prototype? + 'webkitMatchesSelector': 'mozMatchesSelector' in Element.prototype? + 'mozMatchesSelector': 'oMatchesSelector' in Element.prototype? + 'oMatchesSelector': 'msMatchesSelector', + + // will be polyfill function if browser is IE8 + ie8MatchesSelector, + + // native requestAnimationFrame or polyfill + reqFrame = realWindow.requestAnimationFrame, + cancelFrame = realWindow.cancelAnimationFrame, + + // Events wrapper + events = (function () { + var useAttachEvent = ('attachEvent' in window) && !('addEventListener' in window), + addEvent = useAttachEvent? 'attachEvent': 'addEventListener', + removeEvent = useAttachEvent? 'detachEvent': 'removeEventListener', + on = useAttachEvent? 'on': '', + + elements = [], + targets = [], + attachedListeners = []; + + function add (element, type, listener, useCapture) { + var elementIndex = indexOf(elements, element), + target = targets[elementIndex]; + + if (!target) { + target = { + events: {}, + typeCount: 0 + }; + + elementIndex = elements.push(element) - 1; + targets.push(target); + + attachedListeners.push((useAttachEvent ? { + supplied: [], + wrapped : [], + useCount: [] + } : null)); + } + + if (!target.events[type]) { + target.events[type] = []; + target.typeCount++; + } + + if (!contains(target.events[type], listener)) { + var ret; + + if (useAttachEvent) { + var listeners = attachedListeners[elementIndex], + listenerIndex = indexOf(listeners.supplied, listener); + + var wrapped = listeners.wrapped[listenerIndex] || function (event) { + if (!event.immediatePropagationStopped) { + event.target = event.srcElement; + event.currentTarget = element; + + event.preventDefault = event.preventDefault || preventDef; + event.stopPropagation = event.stopPropagation || stopProp; + event.stopImmediatePropagation = event.stopImmediatePropagation || stopImmProp; + + if (/mouse|click/.test(event.type)) { + event.pageX = event.clientX + getWindow(element).document.documentElement.scrollLeft; + event.pageY = event.clientY + getWindow(element).document.documentElement.scrollTop; + } + + listener(event); + } + }; + + ret = element[addEvent](on + type, wrapped, Boolean(useCapture)); + + if (listenerIndex === -1) { + listeners.supplied.push(listener); + listeners.wrapped.push(wrapped); + listeners.useCount.push(1); + } + else { + listeners.useCount[listenerIndex]++; + } + } + else { + ret = element[addEvent](type, listener, useCapture || false); + } + target.events[type].push(listener); + + return ret; + } + } + + function remove (element, type, listener, useCapture) { + var i, + elementIndex = indexOf(elements, element), + target = targets[elementIndex], + listeners, + listenerIndex, + wrapped = listener; + + if (!target || !target.events) { + return; + } + + if (useAttachEvent) { + listeners = attachedListeners[elementIndex]; + listenerIndex = indexOf(listeners.supplied, listener); + wrapped = listeners.wrapped[listenerIndex]; + } + + if (type === 'all') { + for (type in target.events) { + if (target.events.hasOwnProperty(type)) { + remove(element, type, 'all'); + } + } + return; + } + + if (target.events[type]) { + var len = target.events[type].length; + + if (listener === 'all') { + for (i = 0; i < len; i++) { + remove(element, type, target.events[type][i], Boolean(useCapture)); + } + return; + } else { + for (i = 0; i < len; i++) { + if (target.events[type][i] === listener) { + element[removeEvent](on + type, wrapped, useCapture || false); + target.events[type].splice(i, 1); + + if (useAttachEvent && listeners) { + listeners.useCount[listenerIndex]--; + if (listeners.useCount[listenerIndex] === 0) { + listeners.supplied.splice(listenerIndex, 1); + listeners.wrapped.splice(listenerIndex, 1); + listeners.useCount.splice(listenerIndex, 1); + } + } + + break; + } + } + } + + if (target.events[type] && target.events[type].length === 0) { + target.events[type] = null; + target.typeCount--; + } + } + + if (!target.typeCount) { + targets.splice(elementIndex, 1); + elements.splice(elementIndex, 1); + attachedListeners.splice(elementIndex, 1); + } + } + + function preventDef () { + this.returnValue = false; + } + + function stopProp () { + this.cancelBubble = true; + } + + function stopImmProp () { + this.cancelBubble = true; + this.immediatePropagationStopped = true; + } + + return { + add: add, + remove: remove, + useAttachEvent: useAttachEvent, + + _elements: elements, + _targets: targets, + _attachedListeners: attachedListeners + }; + }()); + + function blank () {} + + function isElement (o) { + if (!o || (typeof o !== 'object')) { return false; } + + var _window = getWindow(o) || window; + + return (/object|function/.test(typeof _window.Element) + ? o instanceof _window.Element //DOM2 + : o.nodeType === 1 && typeof o.nodeName === "string"); + } + function isWindow (thing) { return thing === window || !!(thing && thing.Window) && (thing instanceof thing.Window); } + function isDocFrag (thing) { return !!thing && thing instanceof DocumentFragment; } + function isArray (thing) { + return isObject(thing) + && (typeof thing.length !== undefined) + && isFunction(thing.splice); + } + function isObject (thing) { return !!thing && (typeof thing === 'object'); } + function isFunction (thing) { return typeof thing === 'function'; } + function isNumber (thing) { return typeof thing === 'number' ; } + function isBool (thing) { return typeof thing === 'boolean' ; } + function isString (thing) { return typeof thing === 'string' ; } + + function trySelector (value) { + if (!isString(value)) { return false; } + + // an exception will be raised if it is invalid + document.querySelector(value); + return true; + } + + function extend (dest, source) { + for (var prop in source) { + dest[prop] = source[prop]; + } + return dest; + } + + var prefixedPropREs = { + webkit: /(Movement[XY]|Radius[XY]|RotationAngle|Force)$/ + }; + + function pointerExtend (dest, source) { + for (var prop in source) { + var deprecated = false; + + // skip deprecated prefixed properties + for (var vendor in prefixedPropREs) { + if (prop.indexOf(vendor) === 0 && prefixedPropREs[vendor].test(prop)) { + deprecated = true; + break; + } + } + + if (!deprecated) { + dest[prop] = source[prop]; + } + } + return dest; + } + + function copyCoords (dest, src) { + dest.page = dest.page || {}; + dest.page.x = src.page.x; + dest.page.y = src.page.y; + + dest.client = dest.client || {}; + dest.client.x = src.client.x; + dest.client.y = src.client.y; + + dest.timeStamp = src.timeStamp; + } + + function setEventXY (targetObj, pointers, interaction) { + var pointer = (pointers.length > 1 + ? pointerAverage(pointers) + : pointers[0]); + + getPageXY(pointer, tmpXY, interaction); + targetObj.page.x = tmpXY.x; + targetObj.page.y = tmpXY.y; + + getClientXY(pointer, tmpXY, interaction); + targetObj.client.x = tmpXY.x; + targetObj.client.y = tmpXY.y; + + targetObj.timeStamp = new Date().getTime(); + } + + function setEventDeltas (targetObj, prev, cur) { + targetObj.page.x = cur.page.x - prev.page.x; + targetObj.page.y = cur.page.y - prev.page.y; + targetObj.client.x = cur.client.x - prev.client.x; + targetObj.client.y = cur.client.y - prev.client.y; + targetObj.timeStamp = new Date().getTime() - prev.timeStamp; + + // set pointer velocity + var dt = Math.max(targetObj.timeStamp / 1000, 0.001); + targetObj.page.speed = hypot(targetObj.page.x, targetObj.page.y) / dt; + targetObj.page.vx = targetObj.page.x / dt; + targetObj.page.vy = targetObj.page.y / dt; + + targetObj.client.speed = hypot(targetObj.client.x, targetObj.page.y) / dt; + targetObj.client.vx = targetObj.client.x / dt; + targetObj.client.vy = targetObj.client.y / dt; + } + + function isNativePointer (pointer) { + return (pointer instanceof window.Event + || (supportsTouch && window.Touch && pointer instanceof window.Touch)); + } + + // Get specified X/Y coords for mouse or event.touches[0] + function getXY (type, pointer, xy) { + xy = xy || {}; + type = type || 'page'; + + xy.x = pointer[type + 'X']; + xy.y = pointer[type + 'Y']; + + return xy; + } + + function getPageXY (pointer, page) { + page = page || {}; + + // Opera Mobile handles the viewport and scrolling oddly + if (isOperaMobile && isNativePointer(pointer)) { + getXY('screen', pointer, page); + + page.x += window.scrollX; + page.y += window.scrollY; + } + else { + getXY('page', pointer, page); + } + + return page; + } + + function getClientXY (pointer, client) { + client = client || {}; + + if (isOperaMobile && isNativePointer(pointer)) { + // Opera Mobile handles the viewport and scrolling oddly + getXY('screen', pointer, client); + } + else { + getXY('client', pointer, client); + } + + return client; + } + + function getScrollXY (win) { + win = win || window; + return { + x: win.scrollX || win.document.documentElement.scrollLeft, + y: win.scrollY || win.document.documentElement.scrollTop + }; + } + + function getPointerId (pointer) { + return isNumber(pointer.pointerId)? pointer.pointerId : pointer.identifier; + } + + function getActualElement (element) { + return (element instanceof SVGElementInstance + ? element.correspondingUseElement + : element); + } + + function getWindow (node) { + if (isWindow(node)) { + return node; + } + + var rootNode = (node.ownerDocument || node); + + return rootNode.defaultView || rootNode.parentWindow || window; + } + + function getElementClientRect (element) { + var clientRect = (element instanceof SVGElement + ? element.getBoundingClientRect() + : element.getClientRects()[0]); + + return clientRect && { + left : clientRect.left, + right : clientRect.right, + top : clientRect.top, + bottom: clientRect.bottom, + width : clientRect.width || clientRect.right - clientRect.left, + height: clientRect.height || clientRect.bottom - clientRect.top + }; + } + + function getElementRect (element) { + var clientRect = getElementClientRect(element); + + if (!isIOS7 && clientRect) { + var scroll = getScrollXY(getWindow(element)); + + clientRect.left += scroll.x; + clientRect.right += scroll.x; + clientRect.top += scroll.y; + clientRect.bottom += scroll.y; + } + + return clientRect; + } + + function getTouchPair (event) { + var touches = []; + + // array of touches is supplied + if (isArray(event)) { + touches[0] = event[0]; + touches[1] = event[1]; + } + // an event + else { + if (event.type === 'touchend') { + if (event.touches.length === 1) { + touches[0] = event.touches[0]; + touches[1] = event.changedTouches[0]; + } + else if (event.touches.length === 0) { + touches[0] = event.changedTouches[0]; + touches[1] = event.changedTouches[1]; + } + } + else { + touches[0] = event.touches[0]; + touches[1] = event.touches[1]; + } + } + + return touches; + } + + function pointerAverage (pointers) { + var average = { + pageX : 0, + pageY : 0, + clientX: 0, + clientY: 0, + screenX: 0, + screenY: 0 + }; + var prop; + + for (var i = 0; i < pointers.length; i++) { + for (prop in average) { + average[prop] += pointers[i][prop]; + } + } + for (prop in average) { + average[prop] /= pointers.length; + } + + return average; + } + + function touchBBox (event) { + if (!event.length && !(event.touches && event.touches.length > 1)) { + return; + } + + var touches = getTouchPair(event), + minX = Math.min(touches[0].pageX, touches[1].pageX), + minY = Math.min(touches[0].pageY, touches[1].pageY), + maxX = Math.max(touches[0].pageX, touches[1].pageX), + maxY = Math.max(touches[0].pageY, touches[1].pageY); + + return { + x: minX, + y: minY, + left: minX, + top: minY, + width: maxX - minX, + height: maxY - minY + }; + } + + function touchDistance (event, deltaSource) { + deltaSource = deltaSource || defaultOptions.deltaSource; + + var sourceX = deltaSource + 'X', + sourceY = deltaSource + 'Y', + touches = getTouchPair(event); + + + var dx = touches[0][sourceX] - touches[1][sourceX], + dy = touches[0][sourceY] - touches[1][sourceY]; + + return hypot(dx, dy); + } + + function touchAngle (event, prevAngle, deltaSource) { + deltaSource = deltaSource || defaultOptions.deltaSource; + + var sourceX = deltaSource + 'X', + sourceY = deltaSource + 'Y', + touches = getTouchPair(event), + dx = touches[0][sourceX] - touches[1][sourceX], + dy = touches[0][sourceY] - touches[1][sourceY], + angle = 180 * Math.atan(dy / dx) / Math.PI; + + if (isNumber(prevAngle)) { + var dr = angle - prevAngle, + drClamped = dr % 360; + + if (drClamped > 315) { + angle -= 360 + (angle / 360)|0 * 360; + } + else if (drClamped > 135) { + angle -= 180 + (angle / 360)|0 * 360; + } + else if (drClamped < -315) { + angle += 360 + (angle / 360)|0 * 360; + } + else if (drClamped < -135) { + angle += 180 + (angle / 360)|0 * 360; + } + } + + return angle; + } + + function getOriginXY (interactable, element) { + var origin = interactable + ? interactable.options.origin + : defaultOptions.origin; + + if (origin === 'parent') { + origin = parentElement(element); + } + else if (origin === 'self') { + origin = interactable.getRect(element); + } + else if (trySelector(origin)) { + origin = closest(element, origin) || { x: 0, y: 0 }; + } + + if (isFunction(origin)) { + origin = origin(interactable && element); + } + + if (isElement(origin)) { + origin = getElementRect(origin); + } + + origin.x = ('x' in origin)? origin.x : origin.left; + origin.y = ('y' in origin)? origin.y : origin.top; + + return origin; + } + + // http://stackoverflow.com/a/5634528/2280888 + function _getQBezierValue(t, p1, p2, p3) { + var iT = 1 - t; + return iT * iT * p1 + 2 * iT * t * p2 + t * t * p3; + } + + function getQuadraticCurvePoint(startX, startY, cpX, cpY, endX, endY, position) { + return { + x: _getQBezierValue(position, startX, cpX, endX), + y: _getQBezierValue(position, startY, cpY, endY) + }; + } + + // http://gizma.com/easing/ + function easeOutQuad (t, b, c, d) { + t /= d; + return -c * t*(t-2) + b; + } + + function nodeContains (parent, child) { + while (child) { + if (child === parent) { + return true; + } + + child = child.parentNode; + } + + return false; + } + + function closest (child, selector) { + var parent = parentElement(child); + + while (isElement(parent)) { + if (matchesSelector(parent, selector)) { return parent; } + + parent = parentElement(parent); + } + + return null; + } + + function parentElement (node) { + var parent = node.parentNode; + + if (isDocFrag(parent)) { + // skip past #shado-root fragments + while ((parent = parent.host) && isDocFrag(parent)) {} + + return parent; + } + + return parent; + } + + function inContext (interactable, element) { + return interactable._context === element.ownerDocument + || nodeContains(interactable._context, element); + } + + function testIgnore (interactable, interactableElement, element) { + var ignoreFrom = interactable.options.ignoreFrom; + + if (!ignoreFrom || !isElement(element)) { return false; } + + if (isString(ignoreFrom)) { + return matchesUpTo(element, ignoreFrom, interactableElement); + } + else if (isElement(ignoreFrom)) { + return nodeContains(ignoreFrom, element); + } + + return false; + } + + function testAllow (interactable, interactableElement, element) { + var allowFrom = interactable.options.allowFrom; + + if (!allowFrom) { return true; } + + if (!isElement(element)) { return false; } + + if (isString(allowFrom)) { + return matchesUpTo(element, allowFrom, interactableElement); + } + else if (isElement(allowFrom)) { + return nodeContains(allowFrom, element); + } + + return false; + } + + function checkAxis (axis, interactable) { + if (!interactable) { return false; } + + var thisAxis = interactable.options.drag.axis; + + return (axis === 'xy' || thisAxis === 'xy' || thisAxis === axis); + } + + function checkSnap (interactable, action) { + var options = interactable.options; + + if (/^resize/.test(action)) { + action = 'resize'; + } + + return options[action].snap && options[action].snap.enabled; + } + + function checkRestrict (interactable, action) { + var options = interactable.options; + + if (/^resize/.test(action)) { + action = 'resize'; + } + + return options[action].restrict && options[action].restrict.enabled; + } + + function checkAutoScroll (interactable, action) { + var options = interactable.options; + + if (/^resize/.test(action)) { + action = 'resize'; + } + + return options[action].autoScroll && options[action].autoScroll.enabled; + } + + function withinInteractionLimit (interactable, element, action) { + var options = interactable.options, + maxActions = options[action.name].max, + maxPerElement = options[action.name].maxPerElement, + activeInteractions = 0, + targetCount = 0, + targetElementCount = 0; + + for (var i = 0, len = interactions.length; i < len; i++) { + var interaction = interactions[i], + otherAction = interaction.prepared.name, + active = interaction.interacting(); + + if (!active) { continue; } + + activeInteractions++; + + if (activeInteractions >= maxInteractions) { + return false; + } + + if (interaction.target !== interactable) { continue; } + + targetCount += (otherAction === action.name)|0; + + if (targetCount >= maxActions) { + return false; + } + + if (interaction.element === element) { + targetElementCount++; + + if (otherAction !== action.name || targetElementCount >= maxPerElement) { + return false; + } + } + } + + return maxInteractions > 0; + } + + // Test for the element that's "above" all other qualifiers + function indexOfDeepestElement (elements) { + var dropzone, + deepestZone = elements[0], + index = deepestZone? 0: -1, + parent, + deepestZoneParents = [], + dropzoneParents = [], + child, + i, + n; + + for (i = 1; i < elements.length; i++) { + dropzone = elements[i]; + + // an element might belong to multiple selector dropzones + if (!dropzone || dropzone === deepestZone) { + continue; + } + + if (!deepestZone) { + deepestZone = dropzone; + index = i; + continue; + } + + // check if the deepest or current are document.documentElement or document.rootElement + // - if the current dropzone is, do nothing and continue + if (dropzone.parentNode === dropzone.ownerDocument) { + continue; + } + // - if deepest is, update with the current dropzone and continue to next + else if (deepestZone.parentNode === dropzone.ownerDocument) { + deepestZone = dropzone; + index = i; + continue; + } + + if (!deepestZoneParents.length) { + parent = deepestZone; + while (parent.parentNode && parent.parentNode !== parent.ownerDocument) { + deepestZoneParents.unshift(parent); + parent = parent.parentNode; + } + } + + // if this element is an svg element and the current deepest is + // an HTMLElement + if (deepestZone instanceof HTMLElement + && dropzone instanceof SVGElement + && !(dropzone instanceof SVGSVGElement)) { + + if (dropzone === deepestZone.parentNode) { + continue; + } + + parent = dropzone.ownerSVGElement; + } + else { + parent = dropzone; + } + + dropzoneParents = []; + + while (parent.parentNode !== parent.ownerDocument) { + dropzoneParents.unshift(parent); + parent = parent.parentNode; + } + + n = 0; + + // get (position of last common ancestor) + 1 + while (dropzoneParents[n] && dropzoneParents[n] === deepestZoneParents[n]) { + n++; + } + + var parents = [ + dropzoneParents[n - 1], + dropzoneParents[n], + deepestZoneParents[n] + ]; + + child = parents[0].lastChild; + + while (child) { + if (child === parents[1]) { + deepestZone = dropzone; + index = i; + deepestZoneParents = []; + + break; + } + else if (child === parents[2]) { + break; + } + + child = child.previousSibling; + } + } + + return index; + } + + function Interaction () { + this.target = null; // current interactable being interacted with + this.element = null; // the target element of the interactable + this.dropTarget = null; // the dropzone a drag target might be dropped into + this.dropElement = null; // the element at the time of checking + this.prevDropTarget = null; // the dropzone that was recently dragged away from + this.prevDropElement = null; // the element at the time of checking + + this.prepared = { // action that's ready to be fired on next move event + name : null, + axis : null, + edges: null + }; + + this.matches = []; // all selectors that are matched by target element + this.matchElements = []; // corresponding elements + + this.inertiaStatus = { + active : false, + smoothEnd : false, + ending : false, + + startEvent: null, + upCoords: {}, + + xe: 0, ye: 0, + sx: 0, sy: 0, + + t0: 0, + vx0: 0, vys: 0, + duration: 0, + + resumeDx: 0, + resumeDy: 0, + + lambda_v0: 0, + one_ve_v0: 0, + i : null + }; + + if (isFunction(Function.prototype.bind)) { + this.boundInertiaFrame = this.inertiaFrame.bind(this); + this.boundSmoothEndFrame = this.smoothEndFrame.bind(this); + } + else { + var that = this; + + this.boundInertiaFrame = function () { return that.inertiaFrame(); }; + this.boundSmoothEndFrame = function () { return that.smoothEndFrame(); }; + } + + this.activeDrops = { + dropzones: [], // the dropzones that are mentioned below + elements : [], // elements of dropzones that accept the target draggable + rects : [] // the rects of the elements mentioned above + }; + + // keep track of added pointers + this.pointers = []; + this.pointerIds = []; + this.downTargets = []; + this.downTimes = []; + this.holdTimers = []; + + // Previous native pointer move event coordinates + this.prevCoords = { + page : { x: 0, y: 0 }, + client : { x: 0, y: 0 }, + timeStamp: 0 + }; + // current native pointer move event coordinates + this.curCoords = { + page : { x: 0, y: 0 }, + client : { x: 0, y: 0 }, + timeStamp: 0 + }; + + // Starting InteractEvent pointer coordinates + this.startCoords = { + page : { x: 0, y: 0 }, + client : { x: 0, y: 0 }, + timeStamp: 0 + }; + + // Change in coordinates and time of the pointer + this.pointerDelta = { + page : { x: 0, y: 0, vx: 0, vy: 0, speed: 0 }, + client : { x: 0, y: 0, vx: 0, vy: 0, speed: 0 }, + timeStamp: 0 + }; + + this.downEvent = null; // pointerdown/mousedown/touchstart event + this.downPointer = {}; + + this._eventTarget = null; + this._curEventTarget = null; + + this.prevEvent = null; // previous action event + this.tapTime = 0; // time of the most recent tap event + this.prevTap = null; + + this.startOffset = { left: 0, right: 0, top: 0, bottom: 0 }; + this.restrictOffset = { left: 0, right: 0, top: 0, bottom: 0 }; + this.snapOffsets = []; + + this.gesture = { + start: { x: 0, y: 0 }, + + startDistance: 0, // distance between two touches of touchStart + prevDistance : 0, + distance : 0, + + scale: 1, // gesture.distance / gesture.startDistance + + startAngle: 0, // angle of line joining two touches + prevAngle : 0 // angle of the previous gesture event + }; + + this.snapStatus = { + x : 0, y : 0, + dx : 0, dy : 0, + realX : 0, realY : 0, + snappedX: 0, snappedY: 0, + targets : [], + locked : false, + changed : false + }; + + this.restrictStatus = { + dx : 0, dy : 0, + restrictedX: 0, restrictedY: 0, + snap : null, + restricted : false, + changed : false + }; + + this.restrictStatus.snap = this.snapStatus; + + this.pointerIsDown = false; + this.pointerWasMoved = false; + this.gesturing = false; + this.dragging = false; + this.resizing = false; + this.resizeAxes = 'xy'; + + this.mouse = false; + + interactions.push(this); + } + + Interaction.prototype = { + getPageXY : function (pointer, xy) { return getPageXY(pointer, xy, this); }, + getClientXY: function (pointer, xy) { return getClientXY(pointer, xy, this); }, + setEventXY : function (target, ptr) { return setEventXY(target, ptr, this); }, + + pointerOver: function (pointer, event, eventTarget) { + if (this.prepared.name || !this.mouse) { return; } + + var curMatches = [], + curMatchElements = [], + prevTargetElement = this.element; + + this.addPointer(pointer); + + if (this.target + && (testIgnore(this.target, this.element, eventTarget) + || !testAllow(this.target, this.element, eventTarget))) { + // if the eventTarget should be ignored or shouldn't be allowed + // clear the previous target + this.target = null; + this.element = null; + this.matches = []; + this.matchElements = []; + } + + var elementInteractable = interactables.get(eventTarget), + elementAction = (elementInteractable + && !testIgnore(elementInteractable, eventTarget, eventTarget) + && testAllow(elementInteractable, eventTarget, eventTarget) + && validateAction( + elementInteractable.getAction(pointer, event, this, eventTarget), + elementInteractable)); + + if (elementAction && !withinInteractionLimit(elementInteractable, eventTarget, elementAction)) { + elementAction = null; + } + + function pushCurMatches (interactable, selector) { + if (interactable + && inContext(interactable, eventTarget) + && !testIgnore(interactable, eventTarget, eventTarget) + && testAllow(interactable, eventTarget, eventTarget) + && matchesSelector(eventTarget, selector)) { + + curMatches.push(interactable); + curMatchElements.push(eventTarget); + } + } + + if (elementAction) { + this.target = elementInteractable; + this.element = eventTarget; + this.matches = []; + this.matchElements = []; + } + else { + interactables.forEachSelector(pushCurMatches); + + if (this.validateSelector(pointer, event, curMatches, curMatchElements)) { + this.matches = curMatches; + this.matchElements = curMatchElements; + + this.pointerHover(pointer, event, this.matches, this.matchElements); + events.add(eventTarget, + PointerEvent? pEventTypes.move : 'mousemove', + listeners.pointerHover); + } + else if (this.target) { + if (nodeContains(prevTargetElement, eventTarget)) { + this.pointerHover(pointer, event, this.matches, this.matchElements); + events.add(this.element, + PointerEvent? pEventTypes.move : 'mousemove', + listeners.pointerHover); + } + else { + this.target = null; + this.element = null; + this.matches = []; + this.matchElements = []; + } + } + } + }, + + // Check what action would be performed on pointerMove target if a mouse + // button were pressed and change the cursor accordingly + pointerHover: function (pointer, event, eventTarget, curEventTarget, matches, matchElements) { + var target = this.target; + + if (!this.prepared.name && this.mouse) { + + var action; + + // update pointer coords for defaultActionChecker to use + this.setEventXY(this.curCoords, [pointer]); + + if (matches) { + action = this.validateSelector(pointer, event, matches, matchElements); + } + else if (target) { + action = validateAction(target.getAction(this.pointers[0], event, this, this.element), this.target); + } + + if (target && target.options.styleCursor) { + if (action) { + target._doc.documentElement.style.cursor = getActionCursor(action); + } + else { + target._doc.documentElement.style.cursor = ''; + } + } + } + else if (this.prepared.name) { + this.checkAndPreventDefault(event, target, this.element); + } + }, + + pointerOut: function (pointer, event, eventTarget) { + if (this.prepared.name) { return; } + + // Remove temporary event listeners for selector Interactables + if (!interactables.get(eventTarget)) { + events.remove(eventTarget, + PointerEvent? pEventTypes.move : 'mousemove', + listeners.pointerHover); + } + + if (this.target && this.target.options.styleCursor && !this.interacting()) { + this.target._doc.documentElement.style.cursor = ''; + } + }, + + selectorDown: function (pointer, event, eventTarget, curEventTarget) { + var that = this, + // copy event to be used in timeout for IE8 + eventCopy = events.useAttachEvent? extend({}, event) : event, + element = eventTarget, + pointerIndex = this.addPointer(pointer), + action; + + this.holdTimers[pointerIndex] = setTimeout(function () { + that.pointerHold(events.useAttachEvent? eventCopy : pointer, eventCopy, eventTarget, curEventTarget); + }, defaultOptions._holdDuration); + + this.pointerIsDown = true; + + // Check if the down event hits the current inertia target + if (this.inertiaStatus.active && this.target.selector) { + // climb up the DOM tree from the event target + while (isElement(element)) { + + // if this element is the current inertia target element + if (element === this.element + // and the prospective action is the same as the ongoing one + && validateAction(this.target.getAction(pointer, event, this, this.element), this.target).name === this.prepared.name) { + + // stop inertia so that the next move will be a normal one + cancelFrame(this.inertiaStatus.i); + this.inertiaStatus.active = false; + + this.collectEventTargets(pointer, event, eventTarget, 'down'); + return; + } + element = parentElement(element); + } + } + + // do nothing if interacting + if (this.interacting()) { + this.collectEventTargets(pointer, event, eventTarget, 'down'); + return; + } + + function pushMatches (interactable, selector, context) { + var elements = ie8MatchesSelector + ? context.querySelectorAll(selector) + : undefined; + + if (inContext(interactable, element) + && !testIgnore(interactable, element, eventTarget) + && testAllow(interactable, element, eventTarget) + && matchesSelector(element, selector, elements)) { + + that.matches.push(interactable); + that.matchElements.push(element); + } + } + + // update pointer coords for defaultActionChecker to use + this.setEventXY(this.curCoords, [pointer]); + this.downEvent = event; + + while (isElement(element) && !action) { + this.matches = []; + this.matchElements = []; + + interactables.forEachSelector(pushMatches); + + action = this.validateSelector(pointer, event, this.matches, this.matchElements); + element = parentElement(element); + } + + if (action) { + this.prepared.name = action.name; + this.prepared.axis = action.axis; + this.prepared.edges = action.edges; + + this.collectEventTargets(pointer, event, eventTarget, 'down'); + + return this.pointerDown(pointer, event, eventTarget, curEventTarget, action); + } + else { + // do these now since pointerDown isn't being called from here + this.downTimes[pointerIndex] = new Date().getTime(); + this.downTargets[pointerIndex] = eventTarget; + pointerExtend(this.downPointer, pointer); + + copyCoords(this.prevCoords, this.curCoords); + this.pointerWasMoved = false; + } + + this.collectEventTargets(pointer, event, eventTarget, 'down'); + }, + + // Determine action to be performed on next pointerMove and add appropriate + // style and event Listeners + pointerDown: function (pointer, event, eventTarget, curEventTarget, forceAction) { + if (!forceAction && !this.inertiaStatus.active && this.pointerWasMoved && this.prepared.name) { + this.checkAndPreventDefault(event, this.target, this.element); + + return; + } + + this.pointerIsDown = true; + this.downEvent = event; + + var pointerIndex = this.addPointer(pointer), + action; + + // If it is the second touch of a multi-touch gesture, keep the + // target the same and get a new action if a target was set by the + // first touch + if (this.pointerIds.length > 1 && this.target._element === this.element) { + var newAction = validateAction(forceAction || this.target.getAction(pointer, event, this, this.element), this.target); + + if (withinInteractionLimit(this.target, this.element, newAction)) { + action = newAction; + } + + this.prepared.name = null; + } + // Otherwise, set the target if there is no action prepared + else if (!this.prepared.name) { + var interactable = interactables.get(curEventTarget); + + if (interactable + && !testIgnore(interactable, curEventTarget, eventTarget) + && testAllow(interactable, curEventTarget, eventTarget) + && (action = validateAction(forceAction || interactable.getAction(pointer, event, this, curEventTarget), interactable, eventTarget)) + && withinInteractionLimit(interactable, curEventTarget, action)) { + this.target = interactable; + this.element = curEventTarget; + } + } + + var target = this.target, + options = target && target.options; + + if (target && (forceAction || !this.prepared.name)) { + action = action || validateAction(forceAction || target.getAction(pointer, event, this, curEventTarget), target, this.element); + + this.setEventXY(this.startCoords, this.pointers); + + if (!action) { return; } + + if (options.styleCursor) { + target._doc.documentElement.style.cursor = getActionCursor(action); + } + + this.resizeAxes = action.name === 'resize'? action.axis : null; + + if (action === 'gesture' && this.pointerIds.length < 2) { + action = null; + } + + this.prepared.name = action.name; + this.prepared.axis = action.axis; + this.prepared.edges = action.edges; + + this.snapStatus.snappedX = this.snapStatus.snappedY = + this.restrictStatus.restrictedX = this.restrictStatus.restrictedY = NaN; + + this.downTimes[pointerIndex] = new Date().getTime(); + this.downTargets[pointerIndex] = eventTarget; + pointerExtend(this.downPointer, pointer); + + copyCoords(this.prevCoords, this.startCoords); + this.pointerWasMoved = false; + + this.checkAndPreventDefault(event, target, this.element); + } + // if inertia is active try to resume action + else if (this.inertiaStatus.active + && curEventTarget === this.element + && validateAction(target.getAction(pointer, event, this, this.element), target).name === this.prepared.name) { + + cancelFrame(this.inertiaStatus.i); + this.inertiaStatus.active = false; + + this.checkAndPreventDefault(event, target, this.element); + } + }, + + setModifications: function (coords, preEnd) { + var target = this.target, + shouldMove = true, + shouldSnap = checkSnap(target, this.prepared.name) && (!target.options[this.prepared.name].snap.endOnly || preEnd), + shouldRestrict = checkRestrict(target, this.prepared.name) && (!target.options[this.prepared.name].restrict.endOnly || preEnd); + + if (shouldSnap ) { this.setSnapping (coords); } else { this.snapStatus .locked = false; } + if (shouldRestrict) { this.setRestriction(coords); } else { this.restrictStatus.restricted = false; } + + if (shouldSnap && this.snapStatus.locked && !this.snapStatus.changed) { + shouldMove = shouldRestrict && this.restrictStatus.restricted && this.restrictStatus.changed; + } + else if (shouldRestrict && this.restrictStatus.restricted && !this.restrictStatus.changed) { + shouldMove = false; + } + + return shouldMove; + }, + + setStartOffsets: function (action, interactable, element) { + var rect = interactable.getRect(element), + origin = getOriginXY(interactable, element), + snap = interactable.options[this.prepared.name].snap, + restrict = interactable.options[this.prepared.name].restrict, + width, height; + + if (rect) { + this.startOffset.left = this.startCoords.page.x - rect.left; + this.startOffset.top = this.startCoords.page.y - rect.top; + + this.startOffset.right = rect.right - this.startCoords.page.x; + this.startOffset.bottom = rect.bottom - this.startCoords.page.y; + + if ('width' in rect) { width = rect.width; } + else { width = rect.right - rect.left; } + if ('height' in rect) { height = rect.height; } + else { height = rect.bottom - rect.top; } + } + else { + this.startOffset.left = this.startOffset.top = this.startOffset.right = this.startOffset.bottom = 0; + } + + this.snapOffsets.splice(0); + + var snapOffset = snap && snap.offset === 'startCoords' + ? { + x: this.startCoords.page.x - origin.x, + y: this.startCoords.page.y - origin.y + } + : snap && snap.offset || { x: 0, y: 0 }; + + if (rect && snap && snap.relativePoints && snap.relativePoints.length) { + for (var i = 0; i < snap.relativePoints.length; i++) { + this.snapOffsets.push({ + x: this.startOffset.left - (width * snap.relativePoints[i].x) + snapOffset.x, + y: this.startOffset.top - (height * snap.relativePoints[i].y) + snapOffset.y + }); + } + } + else { + this.snapOffsets.push(snapOffset); + } + + if (rect && restrict.elementRect) { + this.restrictOffset.left = this.startOffset.left - (width * restrict.elementRect.left); + this.restrictOffset.top = this.startOffset.top - (height * restrict.elementRect.top); + + this.restrictOffset.right = this.startOffset.right - (width * (1 - restrict.elementRect.right)); + this.restrictOffset.bottom = this.startOffset.bottom - (height * (1 - restrict.elementRect.bottom)); + } + else { + this.restrictOffset.left = this.restrictOffset.top = this.restrictOffset.right = this.restrictOffset.bottom = 0; + } + }, + + /*\ + * Interaction.start + [ method ] + * + * Start an action with the given Interactable and Element as tartgets. The + * action must be enabled for the target Interactable and an appropriate number + * of pointers must be held down – 1 for drag/resize, 2 for gesture. + * + * Use it with `interactable.able({ manualStart: false })` to always + * [start actions manually](https://github.com/taye/interact.js/issues/114) + * + - action (object) The action to be performed - drag, resize, etc. + - interactable (Interactable) The Interactable to target + - element (Element) The DOM Element to target + = (object) interact + ** + | interact(target) + | .draggable({ + | // disable the default drag start by down->move + | manualStart: true + | }) + | // start dragging after the user holds the pointer down + | .on('hold', function (event) { + | var interaction = event.interaction; + | + | if (!interaction.interacting()) { + | interaction.start({ name: 'drag' }, + | event.interactable, + | event.currentTarget); + | } + | }); + \*/ + start: function (action, interactable, element) { + if (this.interacting() + || !this.pointerIsDown + || this.pointerIds.length < (action.name === 'gesture'? 2 : 1)) { + return; + } + + // if this interaction had been removed after stopping + // add it back + if (indexOf(interactions, this) === -1) { + interactions.push(this); + } + + // set the startCoords if there was no prepared action + if (!this.prepared.name) { + this.setEventXY(this.startCoords); + } + + this.prepared.name = action.name; + this.prepared.axis = action.axis; + this.prepared.edges = action.edges; + this.target = interactable; + this.element = element; + + this.setStartOffsets(action.name, interactable, element); + this.setModifications(this.startCoords.page); + + this.prevEvent = this[this.prepared.name + 'Start'](this.downEvent); + }, + + pointerMove: function (pointer, event, eventTarget, curEventTarget, preEnd) { + if (this.inertiaStatus.active) { + var pageUp = this.inertiaStatus.upCoords.page; + var clientUp = this.inertiaStatus.upCoords.client; + + var inertiaPosition = { + pageX : pageUp.x + this.inertiaStatus.sx, + pageY : pageUp.y + this.inertiaStatus.sy, + clientX: clientUp.x + this.inertiaStatus.sx, + clientY: clientUp.y + this.inertiaStatus.sy + }; + + this.setEventXY(this.curCoords, [inertiaPosition]); + } + else { + this.recordPointer(pointer); + this.setEventXY(this.curCoords, this.pointers); + } + + var duplicateMove = (this.curCoords.page.x === this.prevCoords.page.x + && this.curCoords.page.y === this.prevCoords.page.y + && this.curCoords.client.x === this.prevCoords.client.x + && this.curCoords.client.y === this.prevCoords.client.y); + + var dx, dy, + pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer)); + + // register movement greater than pointerMoveTolerance + if (this.pointerIsDown && !this.pointerWasMoved) { + dx = this.curCoords.client.x - this.startCoords.client.x; + dy = this.curCoords.client.y - this.startCoords.client.y; + + this.pointerWasMoved = hypot(dx, dy) > pointerMoveTolerance; + } + + if (!duplicateMove && (!this.pointerIsDown || this.pointerWasMoved)) { + if (this.pointerIsDown) { + clearTimeout(this.holdTimers[pointerIndex]); + } + + this.collectEventTargets(pointer, event, eventTarget, 'move'); + } + + if (!this.pointerIsDown) { return; } + + if (duplicateMove && this.pointerWasMoved && !preEnd) { + this.checkAndPreventDefault(event, this.target, this.element); + return; + } + + // set pointer coordinate, time changes and speeds + setEventDeltas(this.pointerDelta, this.prevCoords, this.curCoords); + + if (!this.prepared.name) { return; } + + if (this.pointerWasMoved + // ignore movement while inertia is active + && (!this.inertiaStatus.active || (pointer instanceof InteractEvent && /inertiastart/.test(pointer.type)))) { + + // if just starting an action, calculate the pointer speed now + if (!this.interacting()) { + setEventDeltas(this.pointerDelta, this.prevCoords, this.curCoords); + + // check if a drag is in the correct axis + if (this.prepared.name === 'drag') { + var absX = Math.abs(dx), + absY = Math.abs(dy), + targetAxis = this.target.options.drag.axis, + axis = (absX > absY ? 'x' : absX < absY ? 'y' : 'xy'); + + // if the movement isn't in the axis of the interactable + if (axis !== 'xy' && targetAxis !== 'xy' && targetAxis !== axis) { + // cancel the prepared action + this.prepared.name = null; + + // then try to get a drag from another ineractable + + var element = eventTarget; + + // check element interactables + while (isElement(element)) { + var elementInteractable = interactables.get(element); + + if (elementInteractable + && elementInteractable !== this.target + && !elementInteractable.options.drag.manualStart + && elementInteractable.getAction(this.downPointer, this.downEvent, this, element).name === 'drag' + && checkAxis(axis, elementInteractable)) { + + this.prepared.name = 'drag'; + this.target = elementInteractable; + this.element = element; + break; + } + + element = parentElement(element); + } + + // if there's no drag from element interactables, + // check the selector interactables + if (!this.prepared.name) { + var thisInteraction = this; + + var getDraggable = function (interactable, selector, context) { + var elements = ie8MatchesSelector + ? context.querySelectorAll(selector) + : undefined; + + if (interactable === thisInteraction.target) { return; } + + if (inContext(interactable, eventTarget) + && !interactable.options.drag.manualStart + && !testIgnore(interactable, element, eventTarget) + && testAllow(interactable, element, eventTarget) + && matchesSelector(element, selector, elements) + && interactable.getAction(thisInteraction.downPointer, thisInteraction.downEvent, thisInteraction, element).name === 'drag' + && checkAxis(axis, interactable) + && withinInteractionLimit(interactable, element, 'drag')) { + + return interactable; + } + }; + + element = eventTarget; + + while (isElement(element)) { + var selectorInteractable = interactables.forEachSelector(getDraggable); + + if (selectorInteractable) { + this.prepared.name = 'drag'; + this.target = selectorInteractable; + this.element = element; + break; + } + + element = parentElement(element); + } + } + } + } + } + + var starting = !!this.prepared.name && !this.interacting(); + + if (starting + && (this.target.options[this.prepared.name].manualStart + || !withinInteractionLimit(this.target, this.element, this.prepared))) { + this.stop(event); + return; + } + + if (this.prepared.name && this.target) { + if (starting) { + this.start(this.prepared, this.target, this.element); + } + + var shouldMove = this.setModifications(this.curCoords.page, preEnd); + + // move if snapping or restriction doesn't prevent it + if (shouldMove || starting) { + this.prevEvent = this[this.prepared.name + 'Move'](event); + } + + this.checkAndPreventDefault(event, this.target, this.element); + } + } + + copyCoords(this.prevCoords, this.curCoords); + + if (this.dragging || this.resizing) { + this.autoScrollMove(pointer); + } + }, + + dragStart: function (event) { + var dragEvent = new InteractEvent(this, event, 'drag', 'start', this.element); + + this.dragging = true; + this.target.fire(dragEvent); + + // reset active dropzones + this.activeDrops.dropzones = []; + this.activeDrops.elements = []; + this.activeDrops.rects = []; + + if (!this.dynamicDrop) { + this.setActiveDrops(this.element); + } + + var dropEvents = this.getDropEvents(event, dragEvent); + + if (dropEvents.activate) { + this.fireActiveDrops(dropEvents.activate); + } + + return dragEvent; + }, + + dragMove: function (event) { + var target = this.target, + dragEvent = new InteractEvent(this, event, 'drag', 'move', this.element), + draggableElement = this.element, + drop = this.getDrop(dragEvent, event, draggableElement); + + this.dropTarget = drop.dropzone; + this.dropElement = drop.element; + + var dropEvents = this.getDropEvents(event, dragEvent); + + target.fire(dragEvent); + + if (dropEvents.leave) { this.prevDropTarget.fire(dropEvents.leave); } + if (dropEvents.enter) { this.dropTarget.fire(dropEvents.enter); } + if (dropEvents.move ) { this.dropTarget.fire(dropEvents.move ); } + + this.prevDropTarget = this.dropTarget; + this.prevDropElement = this.dropElement; + + return dragEvent; + }, + + resizeStart: function (event) { + var resizeEvent = new InteractEvent(this, event, 'resize', 'start', this.element); + + if (this.prepared.edges) { + var startRect = this.target.getRect(this.element); + + /* + * When using the `resizable.square` or `resizable.preserveAspectRatio` options, resizing from one edge + * will affect another. E.g. with `resizable.square`, resizing to make the right edge larger will make + * the bottom edge larger by the same amount. We call these 'linked' edges. Any linked edges will depend + * on the active edges and the edge being interacted with. + */ + if (this.target.options.resize.square || this.target.options.resize.preserveAspectRatio) { + var linkedEdges = extend({}, this.prepared.edges); + + linkedEdges.top = linkedEdges.top || (linkedEdges.left && !linkedEdges.bottom); + linkedEdges.left = linkedEdges.left || (linkedEdges.top && !linkedEdges.right ); + linkedEdges.bottom = linkedEdges.bottom || (linkedEdges.right && !linkedEdges.top ); + linkedEdges.right = linkedEdges.right || (linkedEdges.bottom && !linkedEdges.left ); + + this.prepared._linkedEdges = linkedEdges; + } + else { + this.prepared._linkedEdges = null; + } + + // if using `resizable.preserveAspectRatio` option, record aspect ratio at the start of the resize + if (this.target.options.resize.preserveAspectRatio) { + this.resizeStartAspectRatio = startRect.width / startRect.height; + } + + this.resizeRects = { + start : startRect, + current : extend({}, startRect), + restricted: extend({}, startRect), + previous : extend({}, startRect), + delta : { + left: 0, right : 0, width : 0, + top : 0, bottom: 0, height: 0 + } + }; + + resizeEvent.rect = this.resizeRects.restricted; + resizeEvent.deltaRect = this.resizeRects.delta; + } + + this.target.fire(resizeEvent); + + this.resizing = true; + + return resizeEvent; + }, + + resizeMove: function (event) { + var resizeEvent = new InteractEvent(this, event, 'resize', 'move', this.element); + + var edges = this.prepared.edges, + invert = this.target.options.resize.invert, + invertible = invert === 'reposition' || invert === 'negate'; + + if (edges) { + var dx = resizeEvent.dx, + dy = resizeEvent.dy, + + start = this.resizeRects.start, + current = this.resizeRects.current, + restricted = this.resizeRects.restricted, + delta = this.resizeRects.delta, + previous = extend(this.resizeRects.previous, restricted), + + originalEdges = edges; + + // `resize.preserveAspectRatio` takes precedence over `resize.square` + if (this.target.options.resize.preserveAspectRatio) { + var resizeStartAspectRatio = this.resizeStartAspectRatio; + + edges = this.prepared._linkedEdges; + + if ((originalEdges.left && originalEdges.bottom) + || (originalEdges.right && originalEdges.top)) { + dy = -dx / resizeStartAspectRatio; + } + else if (originalEdges.left || originalEdges.right) { dy = dx / resizeStartAspectRatio; } + else if (originalEdges.top || originalEdges.bottom) { dx = dy * resizeStartAspectRatio; } + } + else if (this.target.options.resize.square) { + edges = this.prepared._linkedEdges; + + if ((originalEdges.left && originalEdges.bottom) + || (originalEdges.right && originalEdges.top)) { + dy = -dx; + } + else if (originalEdges.left || originalEdges.right) { dy = dx; } + else if (originalEdges.top || originalEdges.bottom) { dx = dy; } + } + + // update the 'current' rect without modifications + if (edges.top ) { current.top += dy; } + if (edges.bottom) { current.bottom += dy; } + if (edges.left ) { current.left += dx; } + if (edges.right ) { current.right += dx; } + + if (invertible) { + // if invertible, copy the current rect + extend(restricted, current); + + if (invert === 'reposition') { + // swap edge values if necessary to keep width/height positive + var swap; + + if (restricted.top > restricted.bottom) { + swap = restricted.top; + + restricted.top = restricted.bottom; + restricted.bottom = swap; + } + if (restricted.left > restricted.right) { + swap = restricted.left; + + restricted.left = restricted.right; + restricted.right = swap; + } + } + } + else { + // if not invertible, restrict to minimum of 0x0 rect + restricted.top = Math.min(current.top, start.bottom); + restricted.bottom = Math.max(current.bottom, start.top); + restricted.left = Math.min(current.left, start.right); + restricted.right = Math.max(current.right, start.left); + } + + restricted.width = restricted.right - restricted.left; + restricted.height = restricted.bottom - restricted.top ; + + for (var edge in restricted) { + delta[edge] = restricted[edge] - previous[edge]; + } + + resizeEvent.edges = this.prepared.edges; + resizeEvent.rect = restricted; + resizeEvent.deltaRect = delta; + } + + this.target.fire(resizeEvent); + + return resizeEvent; + }, + + gestureStart: function (event) { + var gestureEvent = new InteractEvent(this, event, 'gesture', 'start', this.element); + + gestureEvent.ds = 0; + + this.gesture.startDistance = this.gesture.prevDistance = gestureEvent.distance; + this.gesture.startAngle = this.gesture.prevAngle = gestureEvent.angle; + this.gesture.scale = 1; + + this.gesturing = true; + + this.target.fire(gestureEvent); + + return gestureEvent; + }, + + gestureMove: function (event) { + if (!this.pointerIds.length) { + return this.prevEvent; + } + + var gestureEvent; + + gestureEvent = new InteractEvent(this, event, 'gesture', 'move', this.element); + gestureEvent.ds = gestureEvent.scale - this.gesture.scale; + + this.target.fire(gestureEvent); + + this.gesture.prevAngle = gestureEvent.angle; + this.gesture.prevDistance = gestureEvent.distance; + + if (gestureEvent.scale !== Infinity && + gestureEvent.scale !== null && + gestureEvent.scale !== undefined && + !isNaN(gestureEvent.scale)) { + + this.gesture.scale = gestureEvent.scale; + } + + return gestureEvent; + }, + + pointerHold: function (pointer, event, eventTarget) { + this.collectEventTargets(pointer, event, eventTarget, 'hold'); + }, + + pointerUp: function (pointer, event, eventTarget, curEventTarget) { + var pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer)); + + clearTimeout(this.holdTimers[pointerIndex]); + + this.collectEventTargets(pointer, event, eventTarget, 'up' ); + this.collectEventTargets(pointer, event, eventTarget, 'tap'); + + this.pointerEnd(pointer, event, eventTarget, curEventTarget); + + this.removePointer(pointer); + }, + + pointerCancel: function (pointer, event, eventTarget, curEventTarget) { + var pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer)); + + clearTimeout(this.holdTimers[pointerIndex]); + + this.collectEventTargets(pointer, event, eventTarget, 'cancel'); + this.pointerEnd(pointer, event, eventTarget, curEventTarget); + + this.removePointer(pointer); + }, + + // http://www.quirksmode.org/dom/events/click.html + // >Events leading to dblclick + // + // IE8 doesn't fire down event before dblclick. + // This workaround tries to fire a tap and doubletap after dblclick + ie8Dblclick: function (pointer, event, eventTarget) { + if (this.prevTap + && event.clientX === this.prevTap.clientX + && event.clientY === this.prevTap.clientY + && eventTarget === this.prevTap.target) { + + this.downTargets[0] = eventTarget; + this.downTimes[0] = new Date().getTime(); + this.collectEventTargets(pointer, event, eventTarget, 'tap'); + } + }, + + // End interact move events and stop auto-scroll unless inertia is enabled + pointerEnd: function (pointer, event, eventTarget, curEventTarget) { + var endEvent, + target = this.target, + options = target && target.options, + inertiaOptions = options && this.prepared.name && options[this.prepared.name].inertia, + inertiaStatus = this.inertiaStatus; + + if (this.interacting()) { + + if (inertiaStatus.active && !inertiaStatus.ending) { return; } + + var pointerSpeed, + now = new Date().getTime(), + inertiaPossible = false, + inertia = false, + smoothEnd = false, + endSnap = checkSnap(target, this.prepared.name) && options[this.prepared.name].snap.endOnly, + endRestrict = checkRestrict(target, this.prepared.name) && options[this.prepared.name].restrict.endOnly, + dx = 0, + dy = 0, + startEvent; + + if (this.dragging) { + if (options.drag.axis === 'x' ) { pointerSpeed = Math.abs(this.pointerDelta.client.vx); } + else if (options.drag.axis === 'y' ) { pointerSpeed = Math.abs(this.pointerDelta.client.vy); } + else /*options.drag.axis === 'xy'*/{ pointerSpeed = this.pointerDelta.client.speed; } + } + else { + pointerSpeed = this.pointerDelta.client.speed; + } + + // check if inertia should be started + inertiaPossible = (inertiaOptions && inertiaOptions.enabled + && this.prepared.name !== 'gesture' + && event !== inertiaStatus.startEvent); + + inertia = (inertiaPossible + && (now - this.curCoords.timeStamp) < 50 + && pointerSpeed > inertiaOptions.minSpeed + && pointerSpeed > inertiaOptions.endSpeed); + + if (inertiaPossible && !inertia && (endSnap || endRestrict)) { + + var snapRestrict = {}; + + snapRestrict.snap = snapRestrict.restrict = snapRestrict; + + if (endSnap) { + this.setSnapping(this.curCoords.page, snapRestrict); + if (snapRestrict.locked) { + dx += snapRestrict.dx; + dy += snapRestrict.dy; + } + } + + if (endRestrict) { + this.setRestriction(this.curCoords.page, snapRestrict); + if (snapRestrict.restricted) { + dx += snapRestrict.dx; + dy += snapRestrict.dy; + } + } + + if (dx || dy) { + smoothEnd = true; + } + } + + if (inertia || smoothEnd) { + copyCoords(inertiaStatus.upCoords, this.curCoords); + + this.pointers[0] = inertiaStatus.startEvent = startEvent = + new InteractEvent(this, event, this.prepared.name, 'inertiastart', this.element); + + inertiaStatus.t0 = now; + + target.fire(inertiaStatus.startEvent); + + if (inertia) { + inertiaStatus.vx0 = this.pointerDelta.client.vx; + inertiaStatus.vy0 = this.pointerDelta.client.vy; + inertiaStatus.v0 = pointerSpeed; + + this.calcInertia(inertiaStatus); + + var page = extend({}, this.curCoords.page), + origin = getOriginXY(target, this.element), + statusObject; + + page.x = page.x + inertiaStatus.xe - origin.x; + page.y = page.y + inertiaStatus.ye - origin.y; + + statusObject = { + useStatusXY: true, + x: page.x, + y: page.y, + dx: 0, + dy: 0, + snap: null + }; + + statusObject.snap = statusObject; + + dx = dy = 0; + + if (endSnap) { + var snap = this.setSnapping(this.curCoords.page, statusObject); + + if (snap.locked) { + dx += snap.dx; + dy += snap.dy; + } + } + + if (endRestrict) { + var restrict = this.setRestriction(this.curCoords.page, statusObject); + + if (restrict.restricted) { + dx += restrict.dx; + dy += restrict.dy; + } + } + + inertiaStatus.modifiedXe += dx; + inertiaStatus.modifiedYe += dy; + + inertiaStatus.i = reqFrame(this.boundInertiaFrame); + } + else { + inertiaStatus.smoothEnd = true; + inertiaStatus.xe = dx; + inertiaStatus.ye = dy; + + inertiaStatus.sx = inertiaStatus.sy = 0; + + inertiaStatus.i = reqFrame(this.boundSmoothEndFrame); + } + + inertiaStatus.active = true; + return; + } + + if (endSnap || endRestrict) { + // fire a move event at the snapped coordinates + this.pointerMove(pointer, event, eventTarget, curEventTarget, true); + } + } + + if (this.dragging) { + endEvent = new InteractEvent(this, event, 'drag', 'end', this.element); + + var draggableElement = this.element, + drop = this.getDrop(endEvent, event, draggableElement); + + this.dropTarget = drop.dropzone; + this.dropElement = drop.element; + + var dropEvents = this.getDropEvents(event, endEvent); + + if (dropEvents.leave) { this.prevDropTarget.fire(dropEvents.leave); } + if (dropEvents.enter) { this.dropTarget.fire(dropEvents.enter); } + if (dropEvents.drop ) { this.dropTarget.fire(dropEvents.drop ); } + if (dropEvents.deactivate) { + this.fireActiveDrops(dropEvents.deactivate); + } + + target.fire(endEvent); + } + else if (this.resizing) { + endEvent = new InteractEvent(this, event, 'resize', 'end', this.element); + target.fire(endEvent); + } + else if (this.gesturing) { + endEvent = new InteractEvent(this, event, 'gesture', 'end', this.element); + target.fire(endEvent); + } + + this.stop(event); + }, + + collectDrops: function (element) { + var drops = [], + elements = [], + i; + + element = element || this.element; + + // collect all dropzones and their elements which qualify for a drop + for (i = 0; i < interactables.length; i++) { + if (!interactables[i].options.drop.enabled) { continue; } + + var current = interactables[i], + accept = current.options.drop.accept; + + // test the draggable element against the dropzone's accept setting + if ((isElement(accept) && accept !== element) + || (isString(accept) + && !matchesSelector(element, accept))) { + + continue; + } + + // query for new elements if necessary + var dropElements = current.selector? current._context.querySelectorAll(current.selector) : [current._element]; + + for (var j = 0, len = dropElements.length; j < len; j++) { + var currentElement = dropElements[j]; + + if (currentElement === element) { + continue; + } + + drops.push(current); + elements.push(currentElement); + } + } + + return { + dropzones: drops, + elements: elements + }; + }, + + fireActiveDrops: function (event) { + var i, + current, + currentElement, + prevElement; + + // loop through all active dropzones and trigger event + for (i = 0; i < this.activeDrops.dropzones.length; i++) { + current = this.activeDrops.dropzones[i]; + currentElement = this.activeDrops.elements [i]; + + // prevent trigger of duplicate events on same element + if (currentElement !== prevElement) { + // set current element as event target + event.target = currentElement; + current.fire(event); + } + prevElement = currentElement; + } + }, + + // Collect a new set of possible drops and save them in activeDrops. + // setActiveDrops should always be called when a drag has just started or a + // drag event happens while dynamicDrop is true + setActiveDrops: function (dragElement) { + // get dropzones and their elements that could receive the draggable + var possibleDrops = this.collectDrops(dragElement, true); + + this.activeDrops.dropzones = possibleDrops.dropzones; + this.activeDrops.elements = possibleDrops.elements; + this.activeDrops.rects = []; + + for (var i = 0; i < this.activeDrops.dropzones.length; i++) { + this.activeDrops.rects[i] = this.activeDrops.dropzones[i].getRect(this.activeDrops.elements[i]); + } + }, + + getDrop: function (dragEvent, event, dragElement) { + var validDrops = []; + + if (dynamicDrop) { + this.setActiveDrops(dragElement); + } + + // collect all dropzones and their elements which qualify for a drop + for (var j = 0; j < this.activeDrops.dropzones.length; j++) { + var current = this.activeDrops.dropzones[j], + currentElement = this.activeDrops.elements [j], + rect = this.activeDrops.rects [j]; + + validDrops.push(current.dropCheck(dragEvent, event, this.target, dragElement, currentElement, rect) + ? currentElement + : null); + } + + // get the most appropriate dropzone based on DOM depth and order + var dropIndex = indexOfDeepestElement(validDrops), + dropzone = this.activeDrops.dropzones[dropIndex] || null, + element = this.activeDrops.elements [dropIndex] || null; + + return { + dropzone: dropzone, + element: element + }; + }, + + getDropEvents: function (pointerEvent, dragEvent) { + var dropEvents = { + enter : null, + leave : null, + activate : null, + deactivate: null, + move : null, + drop : null + }; + + if (this.dropElement !== this.prevDropElement) { + // if there was a prevDropTarget, create a dragleave event + if (this.prevDropTarget) { + dropEvents.leave = { + target : this.prevDropElement, + dropzone : this.prevDropTarget, + relatedTarget: dragEvent.target, + draggable : dragEvent.interactable, + dragEvent : dragEvent, + interaction : this, + timeStamp : dragEvent.timeStamp, + type : 'dragleave' + }; + + dragEvent.dragLeave = this.prevDropElement; + dragEvent.prevDropzone = this.prevDropTarget; + } + // if the dropTarget is not null, create a dragenter event + if (this.dropTarget) { + dropEvents.enter = { + target : this.dropElement, + dropzone : this.dropTarget, + relatedTarget: dragEvent.target, + draggable : dragEvent.interactable, + dragEvent : dragEvent, + interaction : this, + timeStamp : dragEvent.timeStamp, + type : 'dragenter' + }; + + dragEvent.dragEnter = this.dropElement; + dragEvent.dropzone = this.dropTarget; + } + } + + if (dragEvent.type === 'dragend' && this.dropTarget) { + dropEvents.drop = { + target : this.dropElement, + dropzone : this.dropTarget, + relatedTarget: dragEvent.target, + draggable : dragEvent.interactable, + dragEvent : dragEvent, + interaction : this, + timeStamp : dragEvent.timeStamp, + type : 'drop' + }; + + dragEvent.dropzone = this.dropTarget; + } + if (dragEvent.type === 'dragstart') { + dropEvents.activate = { + target : null, + dropzone : null, + relatedTarget: dragEvent.target, + draggable : dragEvent.interactable, + dragEvent : dragEvent, + interaction : this, + timeStamp : dragEvent.timeStamp, + type : 'dropactivate' + }; + } + if (dragEvent.type === 'dragend') { + dropEvents.deactivate = { + target : null, + dropzone : null, + relatedTarget: dragEvent.target, + draggable : dragEvent.interactable, + dragEvent : dragEvent, + interaction : this, + timeStamp : dragEvent.timeStamp, + type : 'dropdeactivate' + }; + } + if (dragEvent.type === 'dragmove' && this.dropTarget) { + dropEvents.move = { + target : this.dropElement, + dropzone : this.dropTarget, + relatedTarget: dragEvent.target, + draggable : dragEvent.interactable, + dragEvent : dragEvent, + interaction : this, + dragmove : dragEvent, + timeStamp : dragEvent.timeStamp, + type : 'dropmove' + }; + dragEvent.dropzone = this.dropTarget; + } + + return dropEvents; + }, + + currentAction: function () { + return (this.dragging && 'drag') || (this.resizing && 'resize') || (this.gesturing && 'gesture') || null; + }, + + interacting: function () { + return this.dragging || this.resizing || this.gesturing; + }, + + clearTargets: function () { + this.target = this.element = null; + + this.dropTarget = this.dropElement = this.prevDropTarget = this.prevDropElement = null; + }, + + stop: function (event) { + if (this.interacting()) { + autoScroll.stop(); + this.matches = []; + this.matchElements = []; + + var target = this.target; + + if (target.options.styleCursor) { + target._doc.documentElement.style.cursor = ''; + } + + // prevent Default only if were previously interacting + if (event && isFunction(event.preventDefault)) { + this.checkAndPreventDefault(event, target, this.element); + } + + if (this.dragging) { + this.activeDrops.dropzones = this.activeDrops.elements = this.activeDrops.rects = null; + } + } + + this.clearTargets(); + + this.pointerIsDown = this.snapStatus.locked = this.dragging = this.resizing = this.gesturing = false; + this.prepared.name = this.prevEvent = null; + this.inertiaStatus.resumeDx = this.inertiaStatus.resumeDy = 0; + + // remove pointers if their ID isn't in this.pointerIds + for (var i = 0; i < this.pointers.length; i++) { + if (indexOf(this.pointerIds, getPointerId(this.pointers[i])) === -1) { + this.pointers.splice(i, 1); + } + } + }, + + inertiaFrame: function () { + var inertiaStatus = this.inertiaStatus, + options = this.target.options[this.prepared.name].inertia, + lambda = options.resistance, + t = new Date().getTime() / 1000 - inertiaStatus.t0; + + if (t < inertiaStatus.te) { + + var progress = 1 - (Math.exp(-lambda * t) - inertiaStatus.lambda_v0) / inertiaStatus.one_ve_v0; + + if (inertiaStatus.modifiedXe === inertiaStatus.xe && inertiaStatus.modifiedYe === inertiaStatus.ye) { + inertiaStatus.sx = inertiaStatus.xe * progress; + inertiaStatus.sy = inertiaStatus.ye * progress; + } + else { + var quadPoint = getQuadraticCurvePoint( + 0, 0, + inertiaStatus.xe, inertiaStatus.ye, + inertiaStatus.modifiedXe, inertiaStatus.modifiedYe, + progress); + + inertiaStatus.sx = quadPoint.x; + inertiaStatus.sy = quadPoint.y; + } + + this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent); + + inertiaStatus.i = reqFrame(this.boundInertiaFrame); + } + else { + inertiaStatus.ending = true; + + inertiaStatus.sx = inertiaStatus.modifiedXe; + inertiaStatus.sy = inertiaStatus.modifiedYe; + + this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent); + this.pointerEnd(inertiaStatus.startEvent, inertiaStatus.startEvent); + + inertiaStatus.active = inertiaStatus.ending = false; + } + }, + + smoothEndFrame: function () { + var inertiaStatus = this.inertiaStatus, + t = new Date().getTime() - inertiaStatus.t0, + duration = this.target.options[this.prepared.name].inertia.smoothEndDuration; + + if (t < duration) { + inertiaStatus.sx = easeOutQuad(t, 0, inertiaStatus.xe, duration); + inertiaStatus.sy = easeOutQuad(t, 0, inertiaStatus.ye, duration); + + this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent); + + inertiaStatus.i = reqFrame(this.boundSmoothEndFrame); + } + else { + inertiaStatus.ending = true; + + inertiaStatus.sx = inertiaStatus.xe; + inertiaStatus.sy = inertiaStatus.ye; + + this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent); + this.pointerEnd(inertiaStatus.startEvent, inertiaStatus.startEvent); + + inertiaStatus.smoothEnd = + inertiaStatus.active = inertiaStatus.ending = false; + } + }, + + addPointer: function (pointer) { + var id = getPointerId(pointer), + index = this.mouse? 0 : indexOf(this.pointerIds, id); + + if (index === -1) { + index = this.pointerIds.length; + } + + this.pointerIds[index] = id; + this.pointers[index] = pointer; + + return index; + }, + + removePointer: function (pointer) { + var id = getPointerId(pointer), + index = this.mouse? 0 : indexOf(this.pointerIds, id); + + if (index === -1) { return; } + + this.pointers .splice(index, 1); + this.pointerIds .splice(index, 1); + this.downTargets.splice(index, 1); + this.downTimes .splice(index, 1); + this.holdTimers .splice(index, 1); + }, + + recordPointer: function (pointer) { + var index = this.mouse? 0: indexOf(this.pointerIds, getPointerId(pointer)); + + if (index === -1) { return; } + + this.pointers[index] = pointer; + }, + + collectEventTargets: function (pointer, event, eventTarget, eventType) { + var pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer)); + + // do not fire a tap event if the pointer was moved before being lifted + if (eventType === 'tap' && (this.pointerWasMoved + // or if the pointerup target is different to the pointerdown target + || !(this.downTargets[pointerIndex] && this.downTargets[pointerIndex] === eventTarget))) { + return; + } + + var targets = [], + elements = [], + element = eventTarget; + + function collectSelectors (interactable, selector, context) { + var els = ie8MatchesSelector + ? context.querySelectorAll(selector) + : undefined; + + if (interactable._iEvents[eventType] + && isElement(element) + && inContext(interactable, element) + && !testIgnore(interactable, element, eventTarget) + && testAllow(interactable, element, eventTarget) + && matchesSelector(element, selector, els)) { + + targets.push(interactable); + elements.push(element); + } + } + + while (element) { + if (interact.isSet(element) && interact(element)._iEvents[eventType]) { + targets.push(interact(element)); + elements.push(element); + } + + interactables.forEachSelector(collectSelectors); + + element = parentElement(element); + } + + // create the tap event even if there are no listeners so that + // doubletap can still be created and fired + if (targets.length || eventType === 'tap') { + this.firePointers(pointer, event, eventTarget, targets, elements, eventType); + } + }, + + firePointers: function (pointer, event, eventTarget, targets, elements, eventType) { + var pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer)), + pointerEvent = {}, + i, + // for tap events + interval, createNewDoubleTap; + + // if it's a doubletap then the event properties would have been + // copied from the tap event and provided as the pointer argument + if (eventType === 'doubletap') { + pointerEvent = pointer; + } + else { + pointerExtend(pointerEvent, event); + if (event !== pointer) { + pointerExtend(pointerEvent, pointer); + } + + pointerEvent.preventDefault = preventOriginalDefault; + pointerEvent.stopPropagation = InteractEvent.prototype.stopPropagation; + pointerEvent.stopImmediatePropagation = InteractEvent.prototype.stopImmediatePropagation; + pointerEvent.interaction = this; + + pointerEvent.timeStamp = new Date().getTime(); + pointerEvent.originalEvent = event; + pointerEvent.originalPointer = pointer; + pointerEvent.type = eventType; + pointerEvent.pointerId = getPointerId(pointer); + pointerEvent.pointerType = this.mouse? 'mouse' : !supportsPointerEvent? 'touch' + : isString(pointer.pointerType) + ? pointer.pointerType + : [,,'touch', 'pen', 'mouse'][pointer.pointerType]; + } + + if (eventType === 'tap') { + pointerEvent.dt = pointerEvent.timeStamp - this.downTimes[pointerIndex]; + + interval = pointerEvent.timeStamp - this.tapTime; + createNewDoubleTap = !!(this.prevTap && this.prevTap.type !== 'doubletap' + && this.prevTap.target === pointerEvent.target + && interval < 500); + + pointerEvent.double = createNewDoubleTap; + + this.tapTime = pointerEvent.timeStamp; + } + + for (i = 0; i < targets.length; i++) { + pointerEvent.currentTarget = elements[i]; + pointerEvent.interactable = targets[i]; + targets[i].fire(pointerEvent); + + if (pointerEvent.immediatePropagationStopped + ||(pointerEvent.propagationStopped && elements[i + 1] !== pointerEvent.currentTarget)) { + break; + } + } + + if (createNewDoubleTap) { + var doubleTap = {}; + + extend(doubleTap, pointerEvent); + + doubleTap.dt = interval; + doubleTap.type = 'doubletap'; + + this.collectEventTargets(doubleTap, event, eventTarget, 'doubletap'); + + this.prevTap = doubleTap; + } + else if (eventType === 'tap') { + this.prevTap = pointerEvent; + } + }, + + validateSelector: function (pointer, event, matches, matchElements) { + for (var i = 0, len = matches.length; i < len; i++) { + var match = matches[i], + matchElement = matchElements[i], + action = validateAction(match.getAction(pointer, event, this, matchElement), match); + + if (action && withinInteractionLimit(match, matchElement, action)) { + this.target = match; + this.element = matchElement; + + return action; + } + } + }, + + setSnapping: function (pageCoords, status) { + var snap = this.target.options[this.prepared.name].snap, + targets = [], + target, + page, + i; + + status = status || this.snapStatus; + + if (status.useStatusXY) { + page = { x: status.x, y: status.y }; + } + else { + var origin = getOriginXY(this.target, this.element); + + page = extend({}, pageCoords); + + page.x -= origin.x; + page.y -= origin.y; + } + + status.realX = page.x; + status.realY = page.y; + + page.x = page.x - this.inertiaStatus.resumeDx; + page.y = page.y - this.inertiaStatus.resumeDy; + + var len = snap.targets? snap.targets.length : 0; + + for (var relIndex = 0; relIndex < this.snapOffsets.length; relIndex++) { + var relative = { + x: page.x - this.snapOffsets[relIndex].x, + y: page.y - this.snapOffsets[relIndex].y + }; + + for (i = 0; i < len; i++) { + if (isFunction(snap.targets[i])) { + target = snap.targets[i](relative.x, relative.y, this); + } + else { + target = snap.targets[i]; + } + + if (!target) { continue; } + + targets.push({ + x: isNumber(target.x) ? (target.x + this.snapOffsets[relIndex].x) : relative.x, + y: isNumber(target.y) ? (target.y + this.snapOffsets[relIndex].y) : relative.y, + + range: isNumber(target.range)? target.range: snap.range + }); + } + } + + var closest = { + target: null, + inRange: false, + distance: 0, + range: 0, + dx: 0, + dy: 0 + }; + + for (i = 0, len = targets.length; i < len; i++) { + target = targets[i]; + + var range = target.range, + dx = target.x - page.x, + dy = target.y - page.y, + distance = hypot(dx, dy), + inRange = distance <= range; + + // Infinite targets count as being out of range + // compared to non infinite ones that are in range + if (range === Infinity && closest.inRange && closest.range !== Infinity) { + inRange = false; + } + + if (!closest.target || (inRange + // is the closest target in range? + ? (closest.inRange && range !== Infinity + // the pointer is relatively deeper in this target + ? distance / range < closest.distance / closest.range + // this target has Infinite range and the closest doesn't + : (range === Infinity && closest.range !== Infinity) + // OR this target is closer that the previous closest + || distance < closest.distance) + // The other is not in range and the pointer is closer to this target + : (!closest.inRange && distance < closest.distance))) { + + if (range === Infinity) { + inRange = true; + } + + closest.target = target; + closest.distance = distance; + closest.range = range; + closest.inRange = inRange; + closest.dx = dx; + closest.dy = dy; + + status.range = range; + } + } + + var snapChanged; + + if (closest.target) { + snapChanged = (status.snappedX !== closest.target.x || status.snappedY !== closest.target.y); + + status.snappedX = closest.target.x; + status.snappedY = closest.target.y; + } + else { + snapChanged = true; + + status.snappedX = NaN; + status.snappedY = NaN; + } + + status.dx = closest.dx; + status.dy = closest.dy; + + status.changed = (snapChanged || (closest.inRange && !status.locked)); + status.locked = closest.inRange; + + return status; + }, + + setRestriction: function (pageCoords, status) { + var target = this.target, + restrict = target && target.options[this.prepared.name].restrict, + restriction = restrict && restrict.restriction, + page; + + if (!restriction) { + return status; + } + + status = status || this.restrictStatus; + + page = status.useStatusXY + ? page = { x: status.x, y: status.y } + : page = extend({}, pageCoords); + + if (status.snap && status.snap.locked) { + page.x += status.snap.dx || 0; + page.y += status.snap.dy || 0; + } + + page.x -= this.inertiaStatus.resumeDx; + page.y -= this.inertiaStatus.resumeDy; + + status.dx = 0; + status.dy = 0; + status.restricted = false; + + var rect, restrictedX, restrictedY; + + if (isString(restriction)) { + if (restriction === 'parent') { + restriction = parentElement(this.element); + } + else if (restriction === 'self') { + restriction = target.getRect(this.element); + } + else { + restriction = closest(this.element, restriction); + } + + if (!restriction) { return status; } + } + + if (isFunction(restriction)) { + restriction = restriction(page.x, page.y, this.element); + } + + if (isElement(restriction)) { + restriction = getElementRect(restriction); + } + + rect = restriction; + + if (!restriction) { + restrictedX = page.x; + restrictedY = page.y; + } + // object is assumed to have + // x, y, width, height or + // left, top, right, bottom + else if ('x' in restriction && 'y' in restriction) { + restrictedX = Math.max(Math.min(rect.x + rect.width - this.restrictOffset.right , page.x), rect.x + this.restrictOffset.left); + restrictedY = Math.max(Math.min(rect.y + rect.height - this.restrictOffset.bottom, page.y), rect.y + this.restrictOffset.top ); + } + else { + restrictedX = Math.max(Math.min(rect.right - this.restrictOffset.right , page.x), rect.left + this.restrictOffset.left); + restrictedY = Math.max(Math.min(rect.bottom - this.restrictOffset.bottom, page.y), rect.top + this.restrictOffset.top ); + } + + status.dx = restrictedX - page.x; + status.dy = restrictedY - page.y; + + status.changed = status.restrictedX !== restrictedX || status.restrictedY !== restrictedY; + status.restricted = !!(status.dx || status.dy); + + status.restrictedX = restrictedX; + status.restrictedY = restrictedY; + + return status; + }, + + checkAndPreventDefault: function (event, interactable, element) { + if (!(interactable = interactable || this.target)) { return; } + + var options = interactable.options, + prevent = options.preventDefault; + + if (prevent === 'auto' && element && !/^(input|select|textarea)$/i.test(event.target.nodeName)) { + // do not preventDefault on pointerdown if the prepared action is a drag + // and dragging can only start from a certain direction - this allows + // a touch to pan the viewport if a drag isn't in the right direction + if (/down|start/i.test(event.type) + && this.prepared.name === 'drag' && options.drag.axis !== 'xy') { + + return; + } + + // with manualStart, only preventDefault while interacting + if (options[this.prepared.name] && options[this.prepared.name].manualStart + && !this.interacting()) { + return; + } + + event.preventDefault(); + return; + } + + if (prevent === 'always') { + event.preventDefault(); + return; + } + }, + + calcInertia: function (status) { + var inertiaOptions = this.target.options[this.prepared.name].inertia, + lambda = inertiaOptions.resistance, + inertiaDur = -Math.log(inertiaOptions.endSpeed / status.v0) / lambda; + + status.x0 = this.prevEvent.pageX; + status.y0 = this.prevEvent.pageY; + status.t0 = status.startEvent.timeStamp / 1000; + status.sx = status.sy = 0; + + status.modifiedXe = status.xe = (status.vx0 - inertiaDur) / lambda; + status.modifiedYe = status.ye = (status.vy0 - inertiaDur) / lambda; + status.te = inertiaDur; + + status.lambda_v0 = lambda / status.v0; + status.one_ve_v0 = 1 - inertiaOptions.endSpeed / status.v0; + }, + + autoScrollMove: function (pointer) { + if (!(this.interacting() + && checkAutoScroll(this.target, this.prepared.name))) { + return; + } + + if (this.inertiaStatus.active) { + autoScroll.x = autoScroll.y = 0; + return; + } + + var top, + right, + bottom, + left, + options = this.target.options[this.prepared.name].autoScroll, + container = options.container || getWindow(this.element); + + if (isWindow(container)) { + left = pointer.clientX < autoScroll.margin; + top = pointer.clientY < autoScroll.margin; + right = pointer.clientX > container.innerWidth - autoScroll.margin; + bottom = pointer.clientY > container.innerHeight - autoScroll.margin; + } + else { + var rect = getElementClientRect(container); + + left = pointer.clientX < rect.left + autoScroll.margin; + top = pointer.clientY < rect.top + autoScroll.margin; + right = pointer.clientX > rect.right - autoScroll.margin; + bottom = pointer.clientY > rect.bottom - autoScroll.margin; + } + + autoScroll.x = (right ? 1: left? -1: 0); + autoScroll.y = (bottom? 1: top? -1: 0); + + if (!autoScroll.isScrolling) { + // set the autoScroll properties to those of the target + autoScroll.margin = options.margin; + autoScroll.speed = options.speed; + + autoScroll.start(this); + } + }, + + _updateEventTargets: function (target, currentTarget) { + this._eventTarget = target; + this._curEventTarget = currentTarget; + } + + }; + + function getInteractionFromPointer (pointer, eventType, eventTarget) { + var i = 0, len = interactions.length, + mouseEvent = (/mouse/i.test(pointer.pointerType || eventType) + // MSPointerEvent.MSPOINTER_TYPE_MOUSE + || pointer.pointerType === 4), + interaction; + + var id = getPointerId(pointer); + + // try to resume inertia with a new pointer + if (/down|start/i.test(eventType)) { + for (i = 0; i < len; i++) { + interaction = interactions[i]; + + var element = eventTarget; + + if (interaction.inertiaStatus.active && interaction.target.options[interaction.prepared.name].inertia.allowResume + && (interaction.mouse === mouseEvent)) { + while (element) { + // if the element is the interaction element + if (element === interaction.element) { + return interaction; + } + element = parentElement(element); + } + } + } + } + + // if it's a mouse interaction + if (mouseEvent || !(supportsTouch || supportsPointerEvent)) { + + // find a mouse interaction that's not in inertia phase + for (i = 0; i < len; i++) { + if (interactions[i].mouse && !interactions[i].inertiaStatus.active) { + return interactions[i]; + } + } + + // find any interaction specifically for mouse. + // if the eventType is a mousedown, and inertia is active + // ignore the interaction + for (i = 0; i < len; i++) { + if (interactions[i].mouse && !(/down/.test(eventType) && interactions[i].inertiaStatus.active)) { + return interaction; + } + } + + // create a new interaction for mouse + interaction = new Interaction(); + interaction.mouse = true; + + return interaction; + } + + // get interaction that has this pointer + for (i = 0; i < len; i++) { + if (contains(interactions[i].pointerIds, id)) { + return interactions[i]; + } + } + + // at this stage, a pointerUp should not return an interaction + if (/up|end|out/i.test(eventType)) { + return null; + } + + // get first idle interaction + for (i = 0; i < len; i++) { + interaction = interactions[i]; + + if ((!interaction.prepared.name || (interaction.target.options.gesture.enabled)) + && !interaction.interacting() + && !(!mouseEvent && interaction.mouse)) { + + return interaction; + } + } + + return new Interaction(); + } + + function doOnInteractions (method) { + return (function (event) { + var interaction, + eventTarget = getActualElement(event.path + ? event.path[0] + : event.target), + curEventTarget = getActualElement(event.currentTarget), + i; + + if (supportsTouch && /touch/.test(event.type)) { + prevTouchTime = new Date().getTime(); + + for (i = 0; i < event.changedTouches.length; i++) { + var pointer = event.changedTouches[i]; + + interaction = getInteractionFromPointer(pointer, event.type, eventTarget); + + if (!interaction) { continue; } + + interaction._updateEventTargets(eventTarget, curEventTarget); + + interaction[method](pointer, event, eventTarget, curEventTarget); + } + } + else { + if (!supportsPointerEvent && /mouse/.test(event.type)) { + // ignore mouse events while touch interactions are active + for (i = 0; i < interactions.length; i++) { + if (!interactions[i].mouse && interactions[i].pointerIsDown) { + return; + } + } + + // try to ignore mouse events that are simulated by the browser + // after a touch event + if (new Date().getTime() - prevTouchTime < 500) { + return; + } + } + + interaction = getInteractionFromPointer(event, event.type, eventTarget); + + if (!interaction) { return; } + + interaction._updateEventTargets(eventTarget, curEventTarget); + + interaction[method](event, event, eventTarget, curEventTarget); + } + }); + } + + function InteractEvent (interaction, event, action, phase, element, related) { + var client, + page, + target = interaction.target, + snapStatus = interaction.snapStatus, + restrictStatus = interaction.restrictStatus, + pointers = interaction.pointers, + deltaSource = (target && target.options || defaultOptions).deltaSource, + sourceX = deltaSource + 'X', + sourceY = deltaSource + 'Y', + options = target? target.options: defaultOptions, + origin = getOriginXY(target, element), + starting = phase === 'start', + ending = phase === 'end', + coords = starting? interaction.startCoords : interaction.curCoords; + + element = element || interaction.element; + + page = extend({}, coords.page); + client = extend({}, coords.client); + + page.x -= origin.x; + page.y -= origin.y; + + client.x -= origin.x; + client.y -= origin.y; + + var relativePoints = options[action].snap && options[action].snap.relativePoints ; + + if (checkSnap(target, action) && !(starting && relativePoints && relativePoints.length)) { + this.snap = { + range : snapStatus.range, + locked : snapStatus.locked, + x : snapStatus.snappedX, + y : snapStatus.snappedY, + realX : snapStatus.realX, + realY : snapStatus.realY, + dx : snapStatus.dx, + dy : snapStatus.dy + }; + + if (snapStatus.locked) { + page.x += snapStatus.dx; + page.y += snapStatus.dy; + client.x += snapStatus.dx; + client.y += snapStatus.dy; + } + } + + if (checkRestrict(target, action) && !(starting && options[action].restrict.elementRect) && restrictStatus.restricted) { + page.x += restrictStatus.dx; + page.y += restrictStatus.dy; + client.x += restrictStatus.dx; + client.y += restrictStatus.dy; + + this.restrict = { + dx: restrictStatus.dx, + dy: restrictStatus.dy + }; + } + + this.pageX = page.x; + this.pageY = page.y; + this.clientX = client.x; + this.clientY = client.y; + + this.x0 = interaction.startCoords.page.x - origin.x; + this.y0 = interaction.startCoords.page.y - origin.y; + this.clientX0 = interaction.startCoords.client.x - origin.x; + this.clientY0 = interaction.startCoords.client.y - origin.y; + this.ctrlKey = event.ctrlKey; + this.altKey = event.altKey; + this.shiftKey = event.shiftKey; + this.metaKey = event.metaKey; + this.button = event.button; + this.buttons = event.buttons; + this.target = element; + this.t0 = interaction.downTimes[0]; + this.type = action + (phase || ''); + + this.interaction = interaction; + this.interactable = target; + + var inertiaStatus = interaction.inertiaStatus; + + if (inertiaStatus.active) { + this.detail = 'inertia'; + } + + if (related) { + this.relatedTarget = related; + } + + // end event dx, dy is difference between start and end points + if (ending) { + if (deltaSource === 'client') { + this.dx = client.x - interaction.startCoords.client.x; + this.dy = client.y - interaction.startCoords.client.y; + } + else { + this.dx = page.x - interaction.startCoords.page.x; + this.dy = page.y - interaction.startCoords.page.y; + } + } + else if (starting) { + this.dx = 0; + this.dy = 0; + } + // copy properties from previousmove if starting inertia + else if (phase === 'inertiastart') { + this.dx = interaction.prevEvent.dx; + this.dy = interaction.prevEvent.dy; + } + else { + if (deltaSource === 'client') { + this.dx = client.x - interaction.prevEvent.clientX; + this.dy = client.y - interaction.prevEvent.clientY; + } + else { + this.dx = page.x - interaction.prevEvent.pageX; + this.dy = page.y - interaction.prevEvent.pageY; + } + } + if (interaction.prevEvent && interaction.prevEvent.detail === 'inertia' + && !inertiaStatus.active + && options[action].inertia && options[action].inertia.zeroResumeDelta) { + + inertiaStatus.resumeDx += this.dx; + inertiaStatus.resumeDy += this.dy; + + this.dx = this.dy = 0; + } + + if (action === 'resize' && interaction.resizeAxes) { + if (options.resize.square) { + if (interaction.resizeAxes === 'y') { + this.dx = this.dy; + } + else { + this.dy = this.dx; + } + this.axes = 'xy'; + } + else { + this.axes = interaction.resizeAxes; + + if (interaction.resizeAxes === 'x') { + this.dy = 0; + } + else if (interaction.resizeAxes === 'y') { + this.dx = 0; + } + } + } + else if (action === 'gesture') { + this.touches = [pointers[0], pointers[1]]; + + if (starting) { + this.distance = touchDistance(pointers, deltaSource); + this.box = touchBBox(pointers); + this.scale = 1; + this.ds = 0; + this.angle = touchAngle(pointers, undefined, deltaSource); + this.da = 0; + } + else if (ending || event instanceof InteractEvent) { + this.distance = interaction.prevEvent.distance; + this.box = interaction.prevEvent.box; + this.scale = interaction.prevEvent.scale; + this.ds = this.scale - 1; + this.angle = interaction.prevEvent.angle; + this.da = this.angle - interaction.gesture.startAngle; + } + else { + this.distance = touchDistance(pointers, deltaSource); + this.box = touchBBox(pointers); + this.scale = this.distance / interaction.gesture.startDistance; + this.angle = touchAngle(pointers, interaction.gesture.prevAngle, deltaSource); + + this.ds = this.scale - interaction.gesture.prevScale; + this.da = this.angle - interaction.gesture.prevAngle; + } + } + + if (starting) { + this.timeStamp = interaction.downTimes[0]; + this.dt = 0; + this.duration = 0; + this.speed = 0; + this.velocityX = 0; + this.velocityY = 0; + } + else if (phase === 'inertiastart') { + this.timeStamp = interaction.prevEvent.timeStamp; + this.dt = interaction.prevEvent.dt; + this.duration = interaction.prevEvent.duration; + this.speed = interaction.prevEvent.speed; + this.velocityX = interaction.prevEvent.velocityX; + this.velocityY = interaction.prevEvent.velocityY; + } + else { + this.timeStamp = new Date().getTime(); + this.dt = this.timeStamp - interaction.prevEvent.timeStamp; + this.duration = this.timeStamp - interaction.downTimes[0]; + + if (event instanceof InteractEvent) { + var dx = this[sourceX] - interaction.prevEvent[sourceX], + dy = this[sourceY] - interaction.prevEvent[sourceY], + dt = this.dt / 1000; + + this.speed = hypot(dx, dy) / dt; + this.velocityX = dx / dt; + this.velocityY = dy / dt; + } + // if normal move or end event, use previous user event coords + else { + // speed and velocity in pixels per second + this.speed = interaction.pointerDelta[deltaSource].speed; + this.velocityX = interaction.pointerDelta[deltaSource].vx; + this.velocityY = interaction.pointerDelta[deltaSource].vy; + } + } + + if ((ending || phase === 'inertiastart') + && interaction.prevEvent.speed > 600 && this.timeStamp - interaction.prevEvent.timeStamp < 150) { + + var angle = 180 * Math.atan2(interaction.prevEvent.velocityY, interaction.prevEvent.velocityX) / Math.PI, + overlap = 22.5; + + if (angle < 0) { + angle += 360; + } + + var left = 135 - overlap <= angle && angle < 225 + overlap, + up = 225 - overlap <= angle && angle < 315 + overlap, + + right = !left && (315 - overlap <= angle || angle < 45 + overlap), + down = !up && 45 - overlap <= angle && angle < 135 + overlap; + + this.swipe = { + up : up, + down : down, + left : left, + right: right, + angle: angle, + speed: interaction.prevEvent.speed, + velocity: { + x: interaction.prevEvent.velocityX, + y: interaction.prevEvent.velocityY + } + }; + } + } + + InteractEvent.prototype = { + preventDefault: blank, + stopImmediatePropagation: function () { + this.immediatePropagationStopped = this.propagationStopped = true; + }, + stopPropagation: function () { + this.propagationStopped = true; + } + }; + + function preventOriginalDefault () { + this.originalEvent.preventDefault(); + } + + function getActionCursor (action) { + var cursor = ''; + + if (action.name === 'drag') { + cursor = actionCursors.drag; + } + if (action.name === 'resize') { + if (action.axis) { + cursor = actionCursors[action.name + action.axis]; + } + else if (action.edges) { + var cursorKey = 'resize', + edgeNames = ['top', 'bottom', 'left', 'right']; + + for (var i = 0; i < 4; i++) { + if (action.edges[edgeNames[i]]) { + cursorKey += edgeNames[i]; + } + } + + cursor = actionCursors[cursorKey]; + } + } + + return cursor; + } + + function checkResizeEdge (name, value, page, element, interactableElement, rect, margin) { + // false, '', undefined, null + if (!value) { return false; } + + // true value, use pointer coords and element rect + if (value === true) { + // if dimensions are negative, "switch" edges + var width = isNumber(rect.width)? rect.width : rect.right - rect.left, + height = isNumber(rect.height)? rect.height : rect.bottom - rect.top; + + if (width < 0) { + if (name === 'left' ) { name = 'right'; } + else if (name === 'right') { name = 'left' ; } + } + if (height < 0) { + if (name === 'top' ) { name = 'bottom'; } + else if (name === 'bottom') { name = 'top' ; } + } + + if (name === 'left' ) { return page.x < ((width >= 0? rect.left: rect.right ) + margin); } + if (name === 'top' ) { return page.y < ((height >= 0? rect.top : rect.bottom) + margin); } + + if (name === 'right' ) { return page.x > ((width >= 0? rect.right : rect.left) - margin); } + if (name === 'bottom') { return page.y > ((height >= 0? rect.bottom: rect.top ) - margin); } + } + + // the remaining checks require an element + if (!isElement(element)) { return false; } + + return isElement(value) + // the value is an element to use as a resize handle + ? value === element + // otherwise check if element matches value as selector + : matchesUpTo(element, value, interactableElement); + } + + function defaultActionChecker (pointer, interaction, element) { + var rect = this.getRect(element), + shouldResize = false, + action = null, + resizeAxes = null, + resizeEdges, + page = extend({}, interaction.curCoords.page), + options = this.options; + + if (!rect) { return null; } + + if (actionIsEnabled.resize && options.resize.enabled) { + var resizeOptions = options.resize; + + resizeEdges = { + left: false, right: false, top: false, bottom: false + }; + + // if using resize.edges + if (isObject(resizeOptions.edges)) { + for (var edge in resizeEdges) { + resizeEdges[edge] = checkResizeEdge(edge, + resizeOptions.edges[edge], + page, + interaction._eventTarget, + element, + rect, + resizeOptions.margin || margin); + } + + resizeEdges.left = resizeEdges.left && !resizeEdges.right; + resizeEdges.top = resizeEdges.top && !resizeEdges.bottom; + + shouldResize = resizeEdges.left || resizeEdges.right || resizeEdges.top || resizeEdges.bottom; + } + else { + var right = options.resize.axis !== 'y' && page.x > (rect.right - margin), + bottom = options.resize.axis !== 'x' && page.y > (rect.bottom - margin); + + shouldResize = right || bottom; + resizeAxes = (right? 'x' : '') + (bottom? 'y' : ''); + } + } + + action = shouldResize + ? 'resize' + : actionIsEnabled.drag && options.drag.enabled + ? 'drag' + : null; + + if (actionIsEnabled.gesture + && interaction.pointerIds.length >=2 + && !(interaction.dragging || interaction.resizing)) { + action = 'gesture'; + } + + if (action) { + return { + name: action, + axis: resizeAxes, + edges: resizeEdges + }; + } + + return null; + } + + // Check if action is enabled globally and the current target supports it + // If so, return the validated action. Otherwise, return null + function validateAction (action, interactable) { + if (!isObject(action)) { return null; } + + var actionName = action.name, + options = interactable.options; + + if (( (actionName === 'resize' && options.resize.enabled ) + || (actionName === 'drag' && options.drag.enabled ) + || (actionName === 'gesture' && options.gesture.enabled)) + && actionIsEnabled[actionName]) { + + if (actionName === 'resize' || actionName === 'resizeyx') { + actionName = 'resizexy'; + } + + return action; + } + return null; + } + + var listeners = {}, + interactionListeners = [ + 'dragStart', 'dragMove', 'resizeStart', 'resizeMove', 'gestureStart', 'gestureMove', + 'pointerOver', 'pointerOut', 'pointerHover', 'selectorDown', + 'pointerDown', 'pointerMove', 'pointerUp', 'pointerCancel', 'pointerEnd', + 'addPointer', 'removePointer', 'recordPointer', 'autoScrollMove' + ]; + + for (var i = 0, len = interactionListeners.length; i < len; i++) { + var name = interactionListeners[i]; + + listeners[name] = doOnInteractions(name); + } + + // bound to the interactable context when a DOM event + // listener is added to a selector interactable + function delegateListener (event, useCapture) { + var fakeEvent = {}, + delegated = delegatedEvents[event.type], + eventTarget = getActualElement(event.path + ? event.path[0] + : event.target), + element = eventTarget; + + useCapture = useCapture? true: false; + + // duplicate the event so that currentTarget can be changed + for (var prop in event) { + fakeEvent[prop] = event[prop]; + } + + fakeEvent.originalEvent = event; + fakeEvent.preventDefault = preventOriginalDefault; + + // climb up document tree looking for selector matches + while (isElement(element)) { + for (var i = 0; i < delegated.selectors.length; i++) { + var selector = delegated.selectors[i], + context = delegated.contexts[i]; + + if (matchesSelector(element, selector) + && nodeContains(context, eventTarget) + && nodeContains(context, element)) { + + var listeners = delegated.listeners[i]; + + fakeEvent.currentTarget = element; + + for (var j = 0; j < listeners.length; j++) { + if (listeners[j][1] === useCapture) { + listeners[j][0](fakeEvent); + } + } + } + } + + element = parentElement(element); + } + } + + function delegateUseCapture (event) { + return delegateListener.call(this, event, true); + } + + interactables.indexOfElement = function indexOfElement (element, context) { + context = context || document; + + for (var i = 0; i < this.length; i++) { + var interactable = this[i]; + + if ((interactable.selector === element + && (interactable._context === context)) + || (!interactable.selector && interactable._element === element)) { + + return i; + } + } + return -1; + }; + + interactables.get = function interactableGet (element, options) { + return this[this.indexOfElement(element, options && options.context)]; + }; + + interactables.forEachSelector = function (callback) { + for (var i = 0; i < this.length; i++) { + var interactable = this[i]; + + if (!interactable.selector) { + continue; + } + + var ret = callback(interactable, interactable.selector, interactable._context, i, this); + + if (ret !== undefined) { + return ret; + } + } + }; + + /*\ + * interact + [ method ] + * + * The methods of this variable can be used to set elements as + * interactables and also to change various default settings. + * + * Calling it as a function and passing an element or a valid CSS selector + * string returns an Interactable object which has various methods to + * configure it. + * + - element (Element | string) The HTML or SVG Element to interact with or CSS selector + = (object) An @Interactable + * + > Usage + | interact(document.getElementById('draggable')).draggable(true); + | + | var rectables = interact('rect'); + | rectables + | .gesturable(true) + | .on('gesturemove', function (event) { + | // something cool... + | }) + | .autoScroll(true); + \*/ + function interact (element, options) { + return interactables.get(element, options) || new Interactable(element, options); + } + + /*\ + * Interactable + [ property ] + ** + * Object type returned by @interact + \*/ + function Interactable (element, options) { + this._element = element; + this._iEvents = this._iEvents || {}; + + var _window; + + if (trySelector(element)) { + this.selector = element; + + var context = options && options.context; + + _window = context? getWindow(context) : window; + + if (context && (_window.Node + ? context instanceof _window.Node + : (isElement(context) || context === _window.document))) { + + this._context = context; + } + } + else { + _window = getWindow(element); + + if (isElement(element, _window)) { + + if (PointerEvent) { + events.add(this._element, pEventTypes.down, listeners.pointerDown ); + events.add(this._element, pEventTypes.move, listeners.pointerHover); + } + else { + events.add(this._element, 'mousedown' , listeners.pointerDown ); + events.add(this._element, 'mousemove' , listeners.pointerHover); + events.add(this._element, 'touchstart', listeners.pointerDown ); + events.add(this._element, 'touchmove' , listeners.pointerHover); + } + } + } + + this._doc = _window.document; + + if (!contains(documents, this._doc)) { + listenToDocument(this._doc); + } + + interactables.push(this); + + this.set(options); + } + + Interactable.prototype = { + setOnEvents: function (action, phases) { + if (action === 'drop') { + if (isFunction(phases.ondrop) ) { this.ondrop = phases.ondrop ; } + if (isFunction(phases.ondropactivate) ) { this.ondropactivate = phases.ondropactivate ; } + if (isFunction(phases.ondropdeactivate)) { this.ondropdeactivate = phases.ondropdeactivate; } + if (isFunction(phases.ondragenter) ) { this.ondragenter = phases.ondragenter ; } + if (isFunction(phases.ondragleave) ) { this.ondragleave = phases.ondragleave ; } + if (isFunction(phases.ondropmove) ) { this.ondropmove = phases.ondropmove ; } + } + else { + action = 'on' + action; + + if (isFunction(phases.onstart) ) { this[action + 'start' ] = phases.onstart ; } + if (isFunction(phases.onmove) ) { this[action + 'move' ] = phases.onmove ; } + if (isFunction(phases.onend) ) { this[action + 'end' ] = phases.onend ; } + if (isFunction(phases.oninertiastart)) { this[action + 'inertiastart' ] = phases.oninertiastart ; } + } + + return this; + }, + + /*\ + * Interactable.draggable + [ method ] + * + * Gets or sets whether drag actions can be performed on the + * Interactable + * + = (boolean) Indicates if this can be the target of drag events + | var isDraggable = interact('ul li').draggable(); + * or + - options (boolean | object) #optional true/false or An object with event listeners to be fired on drag events (object makes the Interactable draggable) + = (object) This Interactable + | interact(element).draggable({ + | onstart: function (event) {}, + | onmove : function (event) {}, + | onend : function (event) {}, + | + | // the axis in which the first movement must be + | // for the drag sequence to start + | // 'xy' by default - any direction + | axis: 'x' || 'y' || 'xy', + | + | // max number of drags that can happen concurrently + | // with elements of this Interactable. Infinity by default + | max: Infinity, + | + | // max number of drags that can target the same element+Interactable + | // 1 by default + | maxPerElement: 2 + | }); + \*/ + draggable: function (options) { + if (isObject(options)) { + this.options.drag.enabled = options.enabled === false? false: true; + this.setPerAction('drag', options); + this.setOnEvents('drag', options); + + if (/^x$|^y$|^xy$/.test(options.axis)) { + this.options.drag.axis = options.axis; + } + else if (options.axis === null) { + delete this.options.drag.axis; + } + + return this; + } + + if (isBool(options)) { + this.options.drag.enabled = options; + + return this; + } + + return this.options.drag; + }, + + setPerAction: function (action, options) { + // for all the default per-action options + for (var option in options) { + // if this option exists for this action + if (option in defaultOptions[action]) { + // if the option in the options arg is an object value + if (isObject(options[option])) { + // duplicate the object + this.options[action][option] = extend(this.options[action][option] || {}, options[option]); + + if (isObject(defaultOptions.perAction[option]) && 'enabled' in defaultOptions.perAction[option]) { + this.options[action][option].enabled = options[option].enabled === false? false : true; + } + } + else if (isBool(options[option]) && isObject(defaultOptions.perAction[option])) { + this.options[action][option].enabled = options[option]; + } + else if (options[option] !== undefined) { + // or if it's not undefined, do a plain assignment + this.options[action][option] = options[option]; + } + } + } + }, + + /*\ + * Interactable.dropzone + [ method ] + * + * Returns or sets whether elements can be dropped onto this + * Interactable to trigger drop events + * + * Dropzones can receive the following events: + * - `dropactivate` and `dropdeactivate` when an acceptable drag starts and ends + * - `dragenter` and `dragleave` when a draggable enters and leaves the dropzone + * - `dragmove` when a draggable that has entered the dropzone is moved + * - `drop` when a draggable is dropped into this dropzone + * + * Use the `accept` option to allow only elements that match the given CSS selector or element. + * + * Use the `overlap` option to set how drops are checked for. The allowed values are: + * - `'pointer'`, the pointer must be over the dropzone (default) + * - `'center'`, the draggable element's center must be over the dropzone + * - a number from 0-1 which is the `(intersection area) / (draggable area)`. + * e.g. `0.5` for drop to happen when half of the area of the + * draggable is over the dropzone + * + - options (boolean | object | null) #optional The new value to be set. + | interact('.drop').dropzone({ + | accept: '.can-drop' || document.getElementById('single-drop'), + | overlap: 'pointer' || 'center' || zeroToOne + | } + = (boolean | object) The current setting or this Interactable + \*/ + dropzone: function (options) { + if (isObject(options)) { + this.options.drop.enabled = options.enabled === false? false: true; + this.setOnEvents('drop', options); + + if (/^(pointer|center)$/.test(options.overlap)) { + this.options.drop.overlap = options.overlap; + } + else if (isNumber(options.overlap)) { + this.options.drop.overlap = Math.max(Math.min(1, options.overlap), 0); + } + if ('accept' in options) { + this.options.drop.accept = options.accept; + } + if ('checker' in options) { + this.options.drop.checker = options.checker; + } + + return this; + } + + if (isBool(options)) { + this.options.drop.enabled = options; + + return this; + } + + return this.options.drop; + }, + + dropCheck: function (dragEvent, event, draggable, draggableElement, dropElement, rect) { + var dropped = false; + + // if the dropzone has no rect (eg. display: none) + // call the custom dropChecker or just return false + if (!(rect = rect || this.getRect(dropElement))) { + return (this.options.drop.checker + ? this.options.drop.checker(dragEvent, event, dropped, this, dropElement, draggable, draggableElement) + : false); + } + + var dropOverlap = this.options.drop.overlap; + + if (dropOverlap === 'pointer') { + var page = getPageXY(dragEvent), + origin = getOriginXY(draggable, draggableElement), + horizontal, + vertical; + + page.x += origin.x; + page.y += origin.y; + + horizontal = (page.x > rect.left) && (page.x < rect.right); + vertical = (page.y > rect.top ) && (page.y < rect.bottom); + + dropped = horizontal && vertical; + } + + var dragRect = draggable.getRect(draggableElement); + + if (dropOverlap === 'center') { + var cx = dragRect.left + dragRect.width / 2, + cy = dragRect.top + dragRect.height / 2; + + dropped = cx >= rect.left && cx <= rect.right && cy >= rect.top && cy <= rect.bottom; + } + + if (isNumber(dropOverlap)) { + var overlapArea = (Math.max(0, Math.min(rect.right , dragRect.right ) - Math.max(rect.left, dragRect.left)) + * Math.max(0, Math.min(rect.bottom, dragRect.bottom) - Math.max(rect.top , dragRect.top ))), + overlapRatio = overlapArea / (dragRect.width * dragRect.height); + + dropped = overlapRatio >= dropOverlap; + } + + if (this.options.drop.checker) { + dropped = this.options.drop.checker(dragEvent, event, dropped, this, dropElement, draggable, draggableElement); + } + + return dropped; + }, + + /*\ + * Interactable.dropChecker + [ method ] + * + * DEPRECATED. Use interactable.dropzone({ checker: function... }) instead. + * + * Gets or sets the function used to check if a dragged element is + * over this Interactable. + * + - checker (function) #optional The function that will be called when checking for a drop + = (Function | Interactable) The checker function or this Interactable + * + * The checker function takes the following arguments: + * + - dragEvent (InteractEvent) The related dragmove or dragend event + - event (TouchEvent | PointerEvent | MouseEvent) The user move/up/end Event related to the dragEvent + - dropped (boolean) The value from the default drop checker + - dropzone (Interactable) The dropzone interactable + - dropElement (Element) The dropzone element + - draggable (Interactable) The Interactable being dragged + - draggableElement (Element) The actual element that's being dragged + * + > Usage: + | interact(target) + | .dropChecker(function(dragEvent, // related dragmove or dragend event + | event, // TouchEvent/PointerEvent/MouseEvent + | dropped, // bool result of the default checker + | dropzone, // dropzone Interactable + | dropElement, // dropzone elemnt + | draggable, // draggable Interactable + | draggableElement) {// draggable element + | + | return dropped && event.target.hasAttribute('allow-drop'); + | } + \*/ + dropChecker: function (checker) { + if (isFunction(checker)) { + this.options.drop.checker = checker; + + return this; + } + if (checker === null) { + delete this.options.getRect; + + return this; + } + + return this.options.drop.checker; + }, + + /*\ + * Interactable.accept + [ method ] + * + * Deprecated. add an `accept` property to the options object passed to + * @Interactable.dropzone instead. + * + * Gets or sets the Element or CSS selector match that this + * Interactable accepts if it is a dropzone. + * + - newValue (Element | string | null) #optional + * If it is an Element, then only that element can be dropped into this dropzone. + * If it is a string, the element being dragged must match it as a selector. + * If it is null, the accept options is cleared - it accepts any element. + * + = (string | Element | null | Interactable) The current accept option if given `undefined` or this Interactable + \*/ + accept: function (newValue) { + if (isElement(newValue)) { + this.options.drop.accept = newValue; + + return this; + } + + // test if it is a valid CSS selector + if (trySelector(newValue)) { + this.options.drop.accept = newValue; + + return this; + } + + if (newValue === null) { + delete this.options.drop.accept; + + return this; + } + + return this.options.drop.accept; + }, + + /*\ + * Interactable.resizable + [ method ] + * + * Gets or sets whether resize actions can be performed on the + * Interactable + * + = (boolean) Indicates if this can be the target of resize elements + | var isResizeable = interact('input[type=text]').resizable(); + * or + - options (boolean | object) #optional true/false or An object with event listeners to be fired on resize events (object makes the Interactable resizable) + = (object) This Interactable + | interact(element).resizable({ + | onstart: function (event) {}, + | onmove : function (event) {}, + | onend : function (event) {}, + | + | edges: { + | top : true, // Use pointer coords to check for resize. + | left : false, // Disable resizing from left edge. + | bottom: '.resize-s',// Resize if pointer target matches selector + | right : handleEl // Resize if pointer target is the given Element + | }, + | + | // Width and height can be adjusted independently. When `true`, width and + | // height are adjusted at a 1:1 ratio. + | square: false, + | + | // Width and height can be adjusted independently. When `true`, width and + | // height maintain the aspect ratio they had when resizing started. + | preserveAspectRatio: false, + | + | // a value of 'none' will limit the resize rect to a minimum of 0x0 + | // 'negate' will allow the rect to have negative width/height + | // 'reposition' will keep the width/height positive by swapping + | // the top and bottom edges and/or swapping the left and right edges + | invert: 'none' || 'negate' || 'reposition' + | + | // limit multiple resizes. + | // See the explanation in the @Interactable.draggable example + | max: Infinity, + | maxPerElement: 1, + | }); + \*/ + resizable: function (options) { + if (isObject(options)) { + this.options.resize.enabled = options.enabled === false? false: true; + this.setPerAction('resize', options); + this.setOnEvents('resize', options); + + if (/^x$|^y$|^xy$/.test(options.axis)) { + this.options.resize.axis = options.axis; + } + else if (options.axis === null) { + this.options.resize.axis = defaultOptions.resize.axis; + } + + if (isBool(options.preserveAspectRatio)) { + this.options.resize.preserveAspectRatio = options.preserveAspectRatio; + } + else if (isBool(options.square)) { + this.options.resize.square = options.square; + } + + return this; + } + if (isBool(options)) { + this.options.resize.enabled = options; + + return this; + } + return this.options.resize; + }, + + /*\ + * Interactable.squareResize + [ method ] + * + * Deprecated. Add a `square: true || false` property to @Interactable.resizable instead + * + * Gets or sets whether resizing is forced 1:1 aspect + * + = (boolean) Current setting + * + * or + * + - newValue (boolean) #optional + = (object) this Interactable + \*/ + squareResize: function (newValue) { + if (isBool(newValue)) { + this.options.resize.square = newValue; + + return this; + } + + if (newValue === null) { + delete this.options.resize.square; + + return this; + } + + return this.options.resize.square; + }, + + /*\ + * Interactable.gesturable + [ method ] + * + * Gets or sets whether multitouch gestures can be performed on the + * Interactable's element + * + = (boolean) Indicates if this can be the target of gesture events + | var isGestureable = interact(element).gesturable(); + * or + - options (boolean | object) #optional true/false or An object with event listeners to be fired on gesture events (makes the Interactable gesturable) + = (object) this Interactable + | interact(element).gesturable({ + | onstart: function (event) {}, + | onmove : function (event) {}, + | onend : function (event) {}, + | + | // limit multiple gestures. + | // See the explanation in @Interactable.draggable example + | max: Infinity, + | maxPerElement: 1, + | }); + \*/ + gesturable: function (options) { + if (isObject(options)) { + this.options.gesture.enabled = options.enabled === false? false: true; + this.setPerAction('gesture', options); + this.setOnEvents('gesture', options); + + return this; + } + + if (isBool(options)) { + this.options.gesture.enabled = options; + + return this; + } + + return this.options.gesture; + }, + + /*\ + * Interactable.autoScroll + [ method ] + ** + * Deprecated. Add an `autoscroll` property to the options object + * passed to @Interactable.draggable or @Interactable.resizable instead. + * + * Returns or sets whether dragging and resizing near the edges of the + * window/container trigger autoScroll for this Interactable + * + = (object) Object with autoScroll properties + * + * or + * + - options (object | boolean) #optional + * options can be: + * - an object with margin, distance and interval properties, + * - true or false to enable or disable autoScroll or + = (Interactable) this Interactable + \*/ + autoScroll: function (options) { + if (isObject(options)) { + options = extend({ actions: ['drag', 'resize']}, options); + } + else if (isBool(options)) { + options = { actions: ['drag', 'resize'], enabled: options }; + } + + return this.setOptions('autoScroll', options); + }, + + /*\ + * Interactable.snap + [ method ] + ** + * Deprecated. Add a `snap` property to the options object passed + * to @Interactable.draggable or @Interactable.resizable instead. + * + * Returns or sets if and how action coordinates are snapped. By + * default, snapping is relative to the pointer coordinates. You can + * change this by setting the + * [`elementOrigin`](https://github.com/taye/interact.js/pull/72). + ** + = (boolean | object) `false` if snap is disabled; object with snap properties if snap is enabled + ** + * or + ** + - options (object | boolean | null) #optional + = (Interactable) this Interactable + > Usage + | interact(document.querySelector('#thing')).snap({ + | targets: [ + | // snap to this specific point + | { + | x: 100, + | y: 100, + | range: 25 + | }, + | // give this function the x and y page coords and snap to the object returned + | function (x, y) { + | return { + | x: x, + | y: (75 + 50 * Math.sin(x * 0.04)), + | range: 40 + | }; + | }, + | // create a function that snaps to a grid + | interact.createSnapGrid({ + | x: 50, + | y: 50, + | range: 10, // optional + | offset: { x: 5, y: 10 } // optional + | }) + | ], + | // do not snap during normal movement. + | // Instead, trigger only one snapped move event + | // immediately before the end event. + | endOnly: true, + | + | relativePoints: [ + | { x: 0, y: 0 }, // snap relative to the top left of the element + | { x: 1, y: 1 }, // and also to the bottom right + | ], + | + | // offset the snap target coordinates + | // can be an object with x/y or 'startCoords' + | offset: { x: 50, y: 50 } + | } + | }); + \*/ + snap: function (options) { + var ret = this.setOptions('snap', options); + + if (ret === this) { return this; } + + return ret.drag; + }, + + setOptions: function (option, options) { + var actions = options && isArray(options.actions) + ? options.actions + : ['drag']; + + var i; + + if (isObject(options) || isBool(options)) { + for (i = 0; i < actions.length; i++) { + var action = /resize/.test(actions[i])? 'resize' : actions[i]; + + if (!isObject(this.options[action])) { continue; } + + var thisOption = this.options[action][option]; + + if (isObject(options)) { + extend(thisOption, options); + thisOption.enabled = options.enabled === false? false: true; + + if (option === 'snap') { + if (thisOption.mode === 'grid') { + thisOption.targets = [ + interact.createSnapGrid(extend({ + offset: thisOption.gridOffset || { x: 0, y: 0 } + }, thisOption.grid || {})) + ]; + } + else if (thisOption.mode === 'anchor') { + thisOption.targets = thisOption.anchors; + } + else if (thisOption.mode === 'path') { + thisOption.targets = thisOption.paths; + } + + if ('elementOrigin' in options) { + thisOption.relativePoints = [options.elementOrigin]; + } + } + } + else if (isBool(options)) { + thisOption.enabled = options; + } + } + + return this; + } + + var ret = {}, + allActions = ['drag', 'resize', 'gesture']; + + for (i = 0; i < allActions.length; i++) { + if (option in defaultOptions[allActions[i]]) { + ret[allActions[i]] = this.options[allActions[i]][option]; + } + } + + return ret; + }, + + + /*\ + * Interactable.inertia + [ method ] + ** + * Deprecated. Add an `inertia` property to the options object passed + * to @Interactable.draggable or @Interactable.resizable instead. + * + * Returns or sets if and how events continue to run after the pointer is released + ** + = (boolean | object) `false` if inertia is disabled; `object` with inertia properties if inertia is enabled + ** + * or + ** + - options (object | boolean | null) #optional + = (Interactable) this Interactable + > Usage + | // enable and use default settings + | interact(element).inertia(true); + | + | // enable and use custom settings + | interact(element).inertia({ + | // value greater than 0 + | // high values slow the object down more quickly + | resistance : 16, + | + | // the minimum launch speed (pixels per second) that results in inertia start + | minSpeed : 200, + | + | // inertia will stop when the object slows down to this speed + | endSpeed : 20, + | + | // boolean; should actions be resumed when the pointer goes down during inertia + | allowResume : true, + | + | // boolean; should the jump when resuming from inertia be ignored in event.dx/dy + | zeroResumeDelta: false, + | + | // if snap/restrict are set to be endOnly and inertia is enabled, releasing + | // the pointer without triggering inertia will animate from the release + | // point to the snaped/restricted point in the given amount of time (ms) + | smoothEndDuration: 300, + | + | // an array of action types that can have inertia (no gesture) + | actions : ['drag', 'resize'] + | }); + | + | // reset custom settings and use all defaults + | interact(element).inertia(null); + \*/ + inertia: function (options) { + var ret = this.setOptions('inertia', options); + + if (ret === this) { return this; } + + return ret.drag; + }, + + getAction: function (pointer, event, interaction, element) { + var action = this.defaultActionChecker(pointer, interaction, element); + + if (this.options.actionChecker) { + return this.options.actionChecker(pointer, event, action, this, element, interaction); + } + + return action; + }, + + defaultActionChecker: defaultActionChecker, + + /*\ + * Interactable.actionChecker + [ method ] + * + * Gets or sets the function used to check action to be performed on + * pointerDown + * + - checker (function | null) #optional A function which takes a pointer event, defaultAction string, interactable, element and interaction as parameters and returns an object with name property 'drag' 'resize' or 'gesture' and optionally an `edges` object with boolean 'top', 'left', 'bottom' and right props. + = (Function | Interactable) The checker function or this Interactable + * + | interact('.resize-drag') + | .resizable(true) + | .draggable(true) + | .actionChecker(function (pointer, event, action, interactable, element, interaction) { + | + | if (interact.matchesSelector(event.target, '.drag-handle') { + | // force drag with handle target + | action.name = drag; + | } + | else { + | // resize from the top and right edges + | action.name = 'resize'; + | action.edges = { top: true, right: true }; + | } + | + | return action; + | }); + \*/ + actionChecker: function (checker) { + if (isFunction(checker)) { + this.options.actionChecker = checker; + + return this; + } + + if (checker === null) { + delete this.options.actionChecker; + + return this; + } + + return this.options.actionChecker; + }, + + /*\ + * Interactable.getRect + [ method ] + * + * The default function to get an Interactables bounding rect. Can be + * overridden using @Interactable.rectChecker. + * + - element (Element) #optional The element to measure. + = (object) The object's bounding rectangle. + o { + o top : 0, + o left : 0, + o bottom: 0, + o right : 0, + o width : 0, + o height: 0 + o } + \*/ + getRect: function rectCheck (element) { + element = element || this._element; + + if (this.selector && !(isElement(element))) { + element = this._context.querySelector(this.selector); + } + + return getElementRect(element); + }, + + /*\ + * Interactable.rectChecker + [ method ] + * + * Returns or sets the function used to calculate the interactable's + * element's rectangle + * + - checker (function) #optional A function which returns this Interactable's bounding rectangle. See @Interactable.getRect + = (function | object) The checker function or this Interactable + \*/ + rectChecker: function (checker) { + if (isFunction(checker)) { + this.getRect = checker; + + return this; + } + + if (checker === null) { + delete this.options.getRect; + + return this; + } + + return this.getRect; + }, + + /*\ + * Interactable.styleCursor + [ method ] + * + * Returns or sets whether the action that would be performed when the + * mouse on the element are checked on `mousemove` so that the cursor + * may be styled appropriately + * + - newValue (boolean) #optional + = (boolean | Interactable) The current setting or this Interactable + \*/ + styleCursor: function (newValue) { + if (isBool(newValue)) { + this.options.styleCursor = newValue; + + return this; + } + + if (newValue === null) { + delete this.options.styleCursor; + + return this; + } + + return this.options.styleCursor; + }, + + /*\ + * Interactable.preventDefault + [ method ] + * + * Returns or sets whether to prevent the browser's default behaviour + * in response to pointer events. Can be set to: + * - `'always'` to always prevent + * - `'never'` to never prevent + * - `'auto'` to let interact.js try to determine what would be best + * + - newValue (string) #optional `true`, `false` or `'auto'` + = (string | Interactable) The current setting or this Interactable + \*/ + preventDefault: function (newValue) { + if (/^(always|never|auto)$/.test(newValue)) { + this.options.preventDefault = newValue; + return this; + } + + if (isBool(newValue)) { + this.options.preventDefault = newValue? 'always' : 'never'; + return this; + } + + return this.options.preventDefault; + }, + + /*\ + * Interactable.origin + [ method ] + * + * Gets or sets the origin of the Interactable's element. The x and y + * of the origin will be subtracted from action event coordinates. + * + - origin (object | string) #optional An object eg. { x: 0, y: 0 } or string 'parent', 'self' or any CSS selector + * OR + - origin (Element) #optional An HTML or SVG Element whose rect will be used + ** + = (object) The current origin or this Interactable + \*/ + origin: function (newValue) { + if (trySelector(newValue)) { + this.options.origin = newValue; + return this; + } + else if (isObject(newValue)) { + this.options.origin = newValue; + return this; + } + + return this.options.origin; + }, + + /*\ + * Interactable.deltaSource + [ method ] + * + * Returns or sets the mouse coordinate types used to calculate the + * movement of the pointer. + * + - newValue (string) #optional Use 'client' if you will be scrolling while interacting; Use 'page' if you want autoScroll to work + = (string | object) The current deltaSource or this Interactable + \*/ + deltaSource: function (newValue) { + if (newValue === 'page' || newValue === 'client') { + this.options.deltaSource = newValue; + + return this; + } + + return this.options.deltaSource; + }, + + /*\ + * Interactable.restrict + [ method ] + ** + * Deprecated. Add a `restrict` property to the options object passed to + * @Interactable.draggable, @Interactable.resizable or @Interactable.gesturable instead. + * + * Returns or sets the rectangles within which actions on this + * interactable (after snap calculations) are restricted. By default, + * restricting is relative to the pointer coordinates. You can change + * this by setting the + * [`elementRect`](https://github.com/taye/interact.js/pull/72). + ** + - options (object) #optional an object with keys drag, resize, and/or gesture whose values are rects, Elements, CSS selectors, or 'parent' or 'self' + = (object) The current restrictions object or this Interactable + ** + | interact(element).restrict({ + | // the rect will be `interact.getElementRect(element.parentNode)` + | drag: element.parentNode, + | + | // x and y are relative to the the interactable's origin + | resize: { x: 100, y: 100, width: 200, height: 200 } + | }) + | + | interact('.draggable').restrict({ + | // the rect will be the selected element's parent + | drag: 'parent', + | + | // do not restrict during normal movement. + | // Instead, trigger only one restricted move event + | // immediately before the end event. + | endOnly: true, + | + | // https://github.com/taye/interact.js/pull/72#issue-41813493 + | elementRect: { top: 0, left: 0, bottom: 1, right: 1 } + | }); + \*/ + restrict: function (options) { + if (!isObject(options)) { + return this.setOptions('restrict', options); + } + + var actions = ['drag', 'resize', 'gesture'], + ret; + + for (var i = 0; i < actions.length; i++) { + var action = actions[i]; + + if (action in options) { + var perAction = extend({ + actions: [action], + restriction: options[action] + }, options); + + ret = this.setOptions('restrict', perAction); + } + } + + return ret; + }, + + /*\ + * Interactable.context + [ method ] + * + * Gets the selector context Node of the Interactable. The default is `window.document`. + * + = (Node) The context Node of this Interactable + ** + \*/ + context: function () { + return this._context; + }, + + _context: document, + + /*\ + * Interactable.ignoreFrom + [ method ] + * + * If the target of the `mousedown`, `pointerdown` or `touchstart` + * event or any of it's parents match the given CSS selector or + * Element, no drag/resize/gesture is started. + * + - newValue (string | Element | null) #optional a CSS selector string, an Element or `null` to not ignore any elements + = (string | Element | object) The current ignoreFrom value or this Interactable + ** + | interact(element, { ignoreFrom: document.getElementById('no-action') }); + | // or + | interact(element).ignoreFrom('input, textarea, a'); + \*/ + ignoreFrom: function (newValue) { + if (trySelector(newValue)) { // CSS selector to match event.target + this.options.ignoreFrom = newValue; + return this; + } + + if (isElement(newValue)) { // specific element + this.options.ignoreFrom = newValue; + return this; + } + + return this.options.ignoreFrom; + }, + + /*\ + * Interactable.allowFrom + [ method ] + * + * A drag/resize/gesture is started only If the target of the + * `mousedown`, `pointerdown` or `touchstart` event or any of it's + * parents match the given CSS selector or Element. + * + - newValue (string | Element | null) #optional a CSS selector string, an Element or `null` to allow from any element + = (string | Element | object) The current allowFrom value or this Interactable + ** + | interact(element, { allowFrom: document.getElementById('drag-handle') }); + | // or + | interact(element).allowFrom('.handle'); + \*/ + allowFrom: function (newValue) { + if (trySelector(newValue)) { // CSS selector to match event.target + this.options.allowFrom = newValue; + return this; + } + + if (isElement(newValue)) { // specific element + this.options.allowFrom = newValue; + return this; + } + + return this.options.allowFrom; + }, + + /*\ + * Interactable.element + [ method ] + * + * If this is not a selector Interactable, it returns the element this + * interactable represents + * + = (Element) HTML / SVG Element + \*/ + element: function () { + return this._element; + }, + + /*\ + * Interactable.fire + [ method ] + * + * Calls listeners for the given InteractEvent type bound globally + * and directly to this Interactable + * + - iEvent (InteractEvent) The InteractEvent object to be fired on this Interactable + = (Interactable) this Interactable + \*/ + fire: function (iEvent) { + if (!(iEvent && iEvent.type) || !contains(eventTypes, iEvent.type)) { + return this; + } + + var listeners, + i, + len, + onEvent = 'on' + iEvent.type, + funcName = ''; + + // Interactable#on() listeners + if (iEvent.type in this._iEvents) { + listeners = this._iEvents[iEvent.type]; + + for (i = 0, len = listeners.length; i < len && !iEvent.immediatePropagationStopped; i++) { + funcName = listeners[i].name; + listeners[i](iEvent); + } + } + + // interactable.onevent listener + if (isFunction(this[onEvent])) { + funcName = this[onEvent].name; + this[onEvent](iEvent); + } + + // interact.on() listeners + if (iEvent.type in globalEvents && (listeners = globalEvents[iEvent.type])) { + + for (i = 0, len = listeners.length; i < len && !iEvent.immediatePropagationStopped; i++) { + funcName = listeners[i].name; + listeners[i](iEvent); + } + } + + return this; + }, + + /*\ + * Interactable.on + [ method ] + * + * Binds a listener for an InteractEvent or DOM event. + * + - eventType (string | array | object) The types of events to listen for + - listener (function) The function to be called on the given event(s) + - useCapture (boolean) #optional useCapture flag for addEventListener + = (object) This Interactable + \*/ + on: function (eventType, listener, useCapture) { + var i; + + if (isString(eventType) && eventType.search(' ') !== -1) { + eventType = eventType.trim().split(/ +/); + } + + if (isArray(eventType)) { + for (i = 0; i < eventType.length; i++) { + this.on(eventType[i], listener, useCapture); + } + + return this; + } + + if (isObject(eventType)) { + for (var prop in eventType) { + this.on(prop, eventType[prop], listener); + } + + return this; + } + + if (eventType === 'wheel') { + eventType = wheelEvent; + } + + // convert to boolean + useCapture = useCapture? true: false; + + if (contains(eventTypes, eventType)) { + // if this type of event was never bound to this Interactable + if (!(eventType in this._iEvents)) { + this._iEvents[eventType] = [listener]; + } + else { + this._iEvents[eventType].push(listener); + } + } + // delegated event for selector + else if (this.selector) { + if (!delegatedEvents[eventType]) { + delegatedEvents[eventType] = { + selectors: [], + contexts : [], + listeners: [] + }; + + // add delegate listener functions + for (i = 0; i < documents.length; i++) { + events.add(documents[i], eventType, delegateListener); + events.add(documents[i], eventType, delegateUseCapture, true); + } + } + + var delegated = delegatedEvents[eventType], + index; + + for (index = delegated.selectors.length - 1; index >= 0; index--) { + if (delegated.selectors[index] === this.selector + && delegated.contexts[index] === this._context) { + break; + } + } + + if (index === -1) { + index = delegated.selectors.length; + + delegated.selectors.push(this.selector); + delegated.contexts .push(this._context); + delegated.listeners.push([]); + } + + // keep listener and useCapture flag + delegated.listeners[index].push([listener, useCapture]); + } + else { + events.add(this._element, eventType, listener, useCapture); + } + + return this; + }, + + /*\ + * Interactable.off + [ method ] + * + * Removes an InteractEvent or DOM event listener + * + - eventType (string | array | object) The types of events that were listened for + - listener (function) The listener function to be removed + - useCapture (boolean) #optional useCapture flag for removeEventListener + = (object) This Interactable + \*/ + off: function (eventType, listener, useCapture) { + var i; + + if (isString(eventType) && eventType.search(' ') !== -1) { + eventType = eventType.trim().split(/ +/); + } + + if (isArray(eventType)) { + for (i = 0; i < eventType.length; i++) { + this.off(eventType[i], listener, useCapture); + } + + return this; + } + + if (isObject(eventType)) { + for (var prop in eventType) { + this.off(prop, eventType[prop], listener); + } + + return this; + } + + var eventList, + index = -1; + + // convert to boolean + useCapture = useCapture? true: false; + + if (eventType === 'wheel') { + eventType = wheelEvent; + } + + // if it is an action event type + if (contains(eventTypes, eventType)) { + eventList = this._iEvents[eventType]; + + if (eventList && (index = indexOf(eventList, listener)) !== -1) { + this._iEvents[eventType].splice(index, 1); + } + } + // delegated event + else if (this.selector) { + var delegated = delegatedEvents[eventType], + matchFound = false; + + if (!delegated) { return this; } + + // count from last index of delegated to 0 + for (index = delegated.selectors.length - 1; index >= 0; index--) { + // look for matching selector and context Node + if (delegated.selectors[index] === this.selector + && delegated.contexts[index] === this._context) { + + var listeners = delegated.listeners[index]; + + // each item of the listeners array is an array: [function, useCaptureFlag] + for (i = listeners.length - 1; i >= 0; i--) { + var fn = listeners[i][0], + useCap = listeners[i][1]; + + // check if the listener functions and useCapture flags match + if (fn === listener && useCap === useCapture) { + // remove the listener from the array of listeners + listeners.splice(i, 1); + + // if all listeners for this interactable have been removed + // remove the interactable from the delegated arrays + if (!listeners.length) { + delegated.selectors.splice(index, 1); + delegated.contexts .splice(index, 1); + delegated.listeners.splice(index, 1); + + // remove delegate function from context + events.remove(this._context, eventType, delegateListener); + events.remove(this._context, eventType, delegateUseCapture, true); + + // remove the arrays if they are empty + if (!delegated.selectors.length) { + delegatedEvents[eventType] = null; + } + } + + // only remove one listener + matchFound = true; + break; + } + } + + if (matchFound) { break; } + } + } + } + // remove listener from this Interatable's element + else { + events.remove(this._element, eventType, listener, useCapture); + } + + return this; + }, + + /*\ + * Interactable.set + [ method ] + * + * Reset the options of this Interactable + - options (object) The new settings to apply + = (object) This Interactable + \*/ + set: function (options) { + if (!isObject(options)) { + options = {}; + } + + this.options = extend({}, defaultOptions.base); + + var i, + actions = ['drag', 'drop', 'resize', 'gesture'], + methods = ['draggable', 'dropzone', 'resizable', 'gesturable'], + perActions = extend(extend({}, defaultOptions.perAction), options[action] || {}); + + for (i = 0; i < actions.length; i++) { + var action = actions[i]; + + this.options[action] = extend({}, defaultOptions[action]); + + this.setPerAction(action, perActions); + + this[methods[i]](options[action]); + } + + var settings = [ + 'accept', 'actionChecker', 'allowFrom', 'deltaSource', + 'dropChecker', 'ignoreFrom', 'origin', 'preventDefault', + 'rectChecker', 'styleCursor' + ]; + + for (i = 0, len = settings.length; i < len; i++) { + var setting = settings[i]; + + this.options[setting] = defaultOptions.base[setting]; + + if (setting in options) { + this[setting](options[setting]); + } + } + + return this; + }, + + /*\ + * Interactable.unset + [ method ] + * + * Remove this interactable from the list of interactables and remove + * it's drag, drop, resize and gesture capabilities + * + = (object) @interact + \*/ + unset: function () { + events.remove(this._element, 'all'); + + if (!isString(this.selector)) { + events.remove(this, 'all'); + if (this.options.styleCursor) { + this._element.style.cursor = ''; + } + } + else { + // remove delegated events + for (var type in delegatedEvents) { + var delegated = delegatedEvents[type]; + + for (var i = 0; i < delegated.selectors.length; i++) { + if (delegated.selectors[i] === this.selector + && delegated.contexts[i] === this._context) { + + delegated.selectors.splice(i, 1); + delegated.contexts .splice(i, 1); + delegated.listeners.splice(i, 1); + + // remove the arrays if they are empty + if (!delegated.selectors.length) { + delegatedEvents[type] = null; + } + } + + events.remove(this._context, type, delegateListener); + events.remove(this._context, type, delegateUseCapture, true); + + break; + } + } + } + + this.dropzone(false); + + interactables.splice(indexOf(interactables, this), 1); + + return interact; + } + }; + + function warnOnce (method, message) { + var warned = false; + + return function () { + if (!warned) { + window.console.warn(message); + warned = true; + } + + return method.apply(this, arguments); + }; + } + + Interactable.prototype.snap = warnOnce(Interactable.prototype.snap, + 'Interactable#snap is deprecated. See the new documentation for snapping at http://interactjs.io/docs/snapping'); + Interactable.prototype.restrict = warnOnce(Interactable.prototype.restrict, + 'Interactable#restrict is deprecated. See the new documentation for resticting at http://interactjs.io/docs/restriction'); + Interactable.prototype.inertia = warnOnce(Interactable.prototype.inertia, + 'Interactable#inertia is deprecated. See the new documentation for inertia at http://interactjs.io/docs/inertia'); + Interactable.prototype.autoScroll = warnOnce(Interactable.prototype.autoScroll, + 'Interactable#autoScroll is deprecated. See the new documentation for autoScroll at http://interactjs.io/docs/#autoscroll'); + Interactable.prototype.squareResize = warnOnce(Interactable.prototype.squareResize, + 'Interactable#squareResize is deprecated. See http://interactjs.io/docs/#resize-square'); + + Interactable.prototype.accept = warnOnce(Interactable.prototype.accept, + 'Interactable#accept is deprecated. use Interactable#dropzone({ accept: target }) instead'); + Interactable.prototype.dropChecker = warnOnce(Interactable.prototype.dropChecker, + 'Interactable#dropChecker is deprecated. use Interactable#dropzone({ dropChecker: checkerFunction }) instead'); + Interactable.prototype.context = warnOnce(Interactable.prototype.context, + 'Interactable#context as a method is deprecated. It will soon be a DOM Node instead'); + + /*\ + * interact.isSet + [ method ] + * + * Check if an element has been set + - element (Element) The Element being searched for + = (boolean) Indicates if the element or CSS selector was previously passed to interact + \*/ + interact.isSet = function(element, options) { + return interactables.indexOfElement(element, options && options.context) !== -1; + }; + + /*\ + * interact.on + [ method ] + * + * Adds a global listener for an InteractEvent or adds a DOM event to + * `document` + * + - type (string | array | object) The types of events to listen for + - listener (function) The function to be called on the given event(s) + - useCapture (boolean) #optional useCapture flag for addEventListener + = (object) interact + \*/ + interact.on = function (type, listener, useCapture) { + if (isString(type) && type.search(' ') !== -1) { + type = type.trim().split(/ +/); + } + + if (isArray(type)) { + for (var i = 0; i < type.length; i++) { + interact.on(type[i], listener, useCapture); + } + + return interact; + } + + if (isObject(type)) { + for (var prop in type) { + interact.on(prop, type[prop], listener); + } + + return interact; + } + + // if it is an InteractEvent type, add listener to globalEvents + if (contains(eventTypes, type)) { + // if this type of event was never bound + if (!globalEvents[type]) { + globalEvents[type] = [listener]; + } + else { + globalEvents[type].push(listener); + } + } + // If non InteractEvent type, addEventListener to document + else { + events.add(document, type, listener, useCapture); + } + + return interact; + }; + + /*\ + * interact.off + [ method ] + * + * Removes a global InteractEvent listener or DOM event from `document` + * + - type (string | array | object) The types of events that were listened for + - listener (function) The listener function to be removed + - useCapture (boolean) #optional useCapture flag for removeEventListener + = (object) interact + \*/ + interact.off = function (type, listener, useCapture) { + if (isString(type) && type.search(' ') !== -1) { + type = type.trim().split(/ +/); + } + + if (isArray(type)) { + for (var i = 0; i < type.length; i++) { + interact.off(type[i], listener, useCapture); + } + + return interact; + } + + if (isObject(type)) { + for (var prop in type) { + interact.off(prop, type[prop], listener); + } + + return interact; + } + + if (!contains(eventTypes, type)) { + events.remove(document, type, listener, useCapture); + } + else { + var index; + + if (type in globalEvents + && (index = indexOf(globalEvents[type], listener)) !== -1) { + globalEvents[type].splice(index, 1); + } + } + + return interact; + }; + + /*\ + * interact.enableDragging + [ method ] + * + * Deprecated. + * + * Returns or sets whether dragging is enabled for any Interactables + * + - newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables + = (boolean | object) The current setting or interact + \*/ + interact.enableDragging = warnOnce(function (newValue) { + if (newValue !== null && newValue !== undefined) { + actionIsEnabled.drag = newValue; + + return interact; + } + return actionIsEnabled.drag; + }, 'interact.enableDragging is deprecated and will soon be removed.'); + + /*\ + * interact.enableResizing + [ method ] + * + * Deprecated. + * + * Returns or sets whether resizing is enabled for any Interactables + * + - newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables + = (boolean | object) The current setting or interact + \*/ + interact.enableResizing = warnOnce(function (newValue) { + if (newValue !== null && newValue !== undefined) { + actionIsEnabled.resize = newValue; + + return interact; + } + return actionIsEnabled.resize; + }, 'interact.enableResizing is deprecated and will soon be removed.'); + + /*\ + * interact.enableGesturing + [ method ] + * + * Deprecated. + * + * Returns or sets whether gesturing is enabled for any Interactables + * + - newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables + = (boolean | object) The current setting or interact + \*/ + interact.enableGesturing = warnOnce(function (newValue) { + if (newValue !== null && newValue !== undefined) { + actionIsEnabled.gesture = newValue; + + return interact; + } + return actionIsEnabled.gesture; + }, 'interact.enableGesturing is deprecated and will soon be removed.'); + + interact.eventTypes = eventTypes; + + /*\ + * interact.debug + [ method ] + * + * Returns debugging data + = (object) An object with properties that outline the current state and expose internal functions and variables + \*/ + interact.debug = function () { + var interaction = interactions[0] || new Interaction(); + + return { + interactions : interactions, + target : interaction.target, + dragging : interaction.dragging, + resizing : interaction.resizing, + gesturing : interaction.gesturing, + prepared : interaction.prepared, + matches : interaction.matches, + matchElements : interaction.matchElements, + + prevCoords : interaction.prevCoords, + startCoords : interaction.startCoords, + + pointerIds : interaction.pointerIds, + pointers : interaction.pointers, + addPointer : listeners.addPointer, + removePointer : listeners.removePointer, + recordPointer : listeners.recordPointer, + + snap : interaction.snapStatus, + restrict : interaction.restrictStatus, + inertia : interaction.inertiaStatus, + + downTime : interaction.downTimes[0], + downEvent : interaction.downEvent, + downPointer : interaction.downPointer, + prevEvent : interaction.prevEvent, + + Interactable : Interactable, + interactables : interactables, + pointerIsDown : interaction.pointerIsDown, + defaultOptions : defaultOptions, + defaultActionChecker : defaultActionChecker, + + actionCursors : actionCursors, + dragMove : listeners.dragMove, + resizeMove : listeners.resizeMove, + gestureMove : listeners.gestureMove, + pointerUp : listeners.pointerUp, + pointerDown : listeners.pointerDown, + pointerMove : listeners.pointerMove, + pointerHover : listeners.pointerHover, + + eventTypes : eventTypes, + + events : events, + globalEvents : globalEvents, + delegatedEvents : delegatedEvents, + + prefixedPropREs : prefixedPropREs + }; + }; + + // expose the functions used to calculate multi-touch properties + interact.getPointerAverage = pointerAverage; + interact.getTouchBBox = touchBBox; + interact.getTouchDistance = touchDistance; + interact.getTouchAngle = touchAngle; + + interact.getElementRect = getElementRect; + interact.getElementClientRect = getElementClientRect; + interact.matchesSelector = matchesSelector; + interact.closest = closest; + + /*\ + * interact.margin + [ method ] + * + * Deprecated. Use `interact(target).resizable({ margin: number });` instead. + * Returns or sets the margin for autocheck resizing used in + * @Interactable.getAction. That is the distance from the bottom and right + * edges of an element clicking in which will start resizing + * + - newValue (number) #optional + = (number | interact) The current margin value or interact + \*/ + interact.margin = warnOnce(function (newvalue) { + if (isNumber(newvalue)) { + margin = newvalue; + + return interact; + } + return margin; + }, + 'interact.margin is deprecated. Use interact(target).resizable({ margin: number }); instead.') ; + + /*\ + * interact.supportsTouch + [ method ] + * + = (boolean) Whether or not the browser supports touch input + \*/ + interact.supportsTouch = function () { + return supportsTouch; + }; + + /*\ + * interact.supportsPointerEvent + [ method ] + * + = (boolean) Whether or not the browser supports PointerEvents + \*/ + interact.supportsPointerEvent = function () { + return supportsPointerEvent; + }; + + /*\ + * interact.stop + [ method ] + * + * Cancels all interactions (end events are not fired) + * + - event (Event) An event on which to call preventDefault() + = (object) interact + \*/ + interact.stop = function (event) { + for (var i = interactions.length - 1; i >= 0; i--) { + interactions[i].stop(event); + } + + return interact; + }; + + /*\ + * interact.dynamicDrop + [ method ] + * + * Returns or sets whether the dimensions of dropzone elements are + * calculated on every dragmove or only on dragstart for the default + * dropChecker + * + - newValue (boolean) #optional True to check on each move. False to check only before start + = (boolean | interact) The current setting or interact + \*/ + interact.dynamicDrop = function (newValue) { + if (isBool(newValue)) { + //if (dragging && dynamicDrop !== newValue && !newValue) { + //calcRects(dropzones); + //} + + dynamicDrop = newValue; + + return interact; + } + return dynamicDrop; + }; + + /*\ + * interact.pointerMoveTolerance + [ method ] + * Returns or sets the distance the pointer must be moved before an action + * sequence occurs. This also affects tolerance for tap events. + * + - newValue (number) #optional The movement from the start position must be greater than this value + = (number | Interactable) The current setting or interact + \*/ + interact.pointerMoveTolerance = function (newValue) { + if (isNumber(newValue)) { + pointerMoveTolerance = newValue; + + return this; + } + + return pointerMoveTolerance; + }; + + /*\ + * interact.maxInteractions + [ method ] + ** + * Returns or sets the maximum number of concurrent interactions allowed. + * By default only 1 interaction is allowed at a time (for backwards + * compatibility). To allow multiple interactions on the same Interactables + * and elements, you need to enable it in the draggable, resizable and + * gesturable `'max'` and `'maxPerElement'` options. + ** + - newValue (number) #optional Any number. newValue <= 0 means no interactions. + \*/ + interact.maxInteractions = function (newValue) { + if (isNumber(newValue)) { + maxInteractions = newValue; + + return this; + } + + return maxInteractions; + }; + + interact.createSnapGrid = function (grid) { + return function (x, y) { + var offsetX = 0, + offsetY = 0; + + if (isObject(grid.offset)) { + offsetX = grid.offset.x; + offsetY = grid.offset.y; + } + + var gridx = Math.round((x - offsetX) / grid.x), + gridy = Math.round((y - offsetY) / grid.y), + + newX = gridx * grid.x + offsetX, + newY = gridy * grid.y + offsetY; + + return { + x: newX, + y: newY, + range: grid.range + }; + }; + }; + + function endAllInteractions (event) { + for (var i = 0; i < interactions.length; i++) { + interactions[i].pointerEnd(event, event); + } + } + + function listenToDocument (doc) { + if (contains(documents, doc)) { return; } + + var win = doc.defaultView || doc.parentWindow; + + // add delegate event listener + for (var eventType in delegatedEvents) { + events.add(doc, eventType, delegateListener); + events.add(doc, eventType, delegateUseCapture, true); + } + + if (PointerEvent) { + if (PointerEvent === win.MSPointerEvent) { + pEventTypes = { + up: 'MSPointerUp', down: 'MSPointerDown', over: 'mouseover', + out: 'mouseout', move: 'MSPointerMove', cancel: 'MSPointerCancel' }; + } + else { + pEventTypes = { + up: 'pointerup', down: 'pointerdown', over: 'pointerover', + out: 'pointerout', move: 'pointermove', cancel: 'pointercancel' }; + } + + events.add(doc, pEventTypes.down , listeners.selectorDown ); + events.add(doc, pEventTypes.move , listeners.pointerMove ); + events.add(doc, pEventTypes.over , listeners.pointerOver ); + events.add(doc, pEventTypes.out , listeners.pointerOut ); + events.add(doc, pEventTypes.up , listeners.pointerUp ); + events.add(doc, pEventTypes.cancel, listeners.pointerCancel); + + // autoscroll + events.add(doc, pEventTypes.move, listeners.autoScrollMove); + } + else { + events.add(doc, 'mousedown', listeners.selectorDown); + events.add(doc, 'mousemove', listeners.pointerMove ); + events.add(doc, 'mouseup' , listeners.pointerUp ); + events.add(doc, 'mouseover', listeners.pointerOver ); + events.add(doc, 'mouseout' , listeners.pointerOut ); + + events.add(doc, 'touchstart' , listeners.selectorDown ); + events.add(doc, 'touchmove' , listeners.pointerMove ); + events.add(doc, 'touchend' , listeners.pointerUp ); + events.add(doc, 'touchcancel', listeners.pointerCancel); + + // autoscroll + events.add(doc, 'mousemove', listeners.autoScrollMove); + events.add(doc, 'touchmove', listeners.autoScrollMove); + } + + events.add(win, 'blur', endAllInteractions); + + try { + if (win.frameElement) { + var parentDoc = win.frameElement.ownerDocument, + parentWindow = parentDoc.defaultView; + + events.add(parentDoc , 'mouseup' , listeners.pointerEnd); + events.add(parentDoc , 'touchend' , listeners.pointerEnd); + events.add(parentDoc , 'touchcancel' , listeners.pointerEnd); + events.add(parentDoc , 'pointerup' , listeners.pointerEnd); + events.add(parentDoc , 'MSPointerUp' , listeners.pointerEnd); + events.add(parentWindow, 'blur' , endAllInteractions ); + } + } + catch (error) { + interact.windowParentError = error; + } + + // prevent native HTML5 drag on interact.js target elements + events.add(doc, 'dragstart', function (event) { + for (var i = 0; i < interactions.length; i++) { + var interaction = interactions[i]; + + if (interaction.element + && (interaction.element === event.target + || nodeContains(interaction.element, event.target))) { + + interaction.checkAndPreventDefault(event, interaction.target, interaction.element); + return; + } + } + }); + + if (events.useAttachEvent) { + // For IE's lack of Event#preventDefault + events.add(doc, 'selectstart', function (event) { + var interaction = interactions[0]; + + if (interaction.currentAction()) { + interaction.checkAndPreventDefault(event); + } + }); + + // For IE's bad dblclick event sequence + events.add(doc, 'dblclick', doOnInteractions('ie8Dblclick')); + } + + documents.push(doc); + } + + listenToDocument(document); + + function indexOf (array, target) { + for (var i = 0, len = array.length; i < len; i++) { + if (array[i] === target) { + return i; + } + } + + return -1; + } + + function contains (array, target) { + return indexOf(array, target) !== -1; + } + + function matchesSelector (element, selector, nodeList) { + if (ie8MatchesSelector) { + return ie8MatchesSelector(element, selector, nodeList); + } + + // remove /deep/ from selectors if shadowDOM polyfill is used + if (window !== realWindow) { + selector = selector.replace(/\/deep\//g, ' '); + } + + return element[prefixedMatchesSelector](selector); + } + + function matchesUpTo (element, selector, limit) { + while (isElement(element)) { + if (matchesSelector(element, selector)) { + return true; + } + + element = parentElement(element); + + if (element === limit) { + return matchesSelector(element, selector); + } + } + + return false; + } + + // For IE8's lack of an Element#matchesSelector + // taken from http://tanalin.com/en/blog/2012/12/matches-selector-ie8/ and modified + if (!(prefixedMatchesSelector in Element.prototype) || !isFunction(Element.prototype[prefixedMatchesSelector])) { + ie8MatchesSelector = function (element, selector, elems) { + elems = elems || element.parentNode.querySelectorAll(selector); + + for (var i = 0, len = elems.length; i < len; i++) { + if (elems[i] === element) { + return true; + } + } + + return false; + }; + } + + // requestAnimationFrame polyfill + (function() { + var lastTime = 0, + vendors = ['ms', 'moz', 'webkit', 'o']; + + for(var x = 0; x < vendors.length && !realWindow.requestAnimationFrame; ++x) { + reqFrame = realWindow[vendors[x]+'RequestAnimationFrame']; + cancelFrame = realWindow[vendors[x]+'CancelAnimationFrame'] || realWindow[vendors[x]+'CancelRequestAnimationFrame']; + } + + if (!reqFrame) { + reqFrame = function(callback) { + var currTime = new Date().getTime(), + timeToCall = Math.max(0, 16 - (currTime - lastTime)), + id = setTimeout(function() { callback(currTime + timeToCall); }, + timeToCall); + lastTime = currTime + timeToCall; + return id; + }; + } + + if (!cancelFrame) { + cancelFrame = function(id) { + clearTimeout(id); + }; + } + }()); + + /* global exports: true, module, define */ + + // http://documentcloud.github.io/underscore/docs/underscore.html#section-11 + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = interact; + } + exports.interact = interact; + } + // AMD + else if (typeof define === 'function' && define.amd) { + define('interact', function() { + return interact; + }); + } + else { + realWindow.interact = interact; + } + +} (typeof window === 'undefined'? undefined : window)); diff --git a/js/interact/1.2.6/interact.min.js b/js/interact/1.2.6/interact.min.js new file mode 100644 index 0000000..a3dcff6 --- /dev/null +++ b/js/interact/1.2.6/interact.min.js @@ -0,0 +1,124 @@ +/* interact.js v1.2.6 | https://raw.github.com/taye/interact.js/master/LICENSE */ (function(F){function ma(){}function t(a){if(!a||"object"!==typeof a)return!1;var b=V(a)||q;return/object|function/.test(typeof b.Element)?a instanceof b.Element:1===a.nodeType&&"string"===typeof a.nodeName}function Ba(a){return a===q||!(!a||!a.Window)&&a instanceof a.Window}function da(a){return z(a)&&void 0!==typeof a.length&&A(a.splice)}function z(a){return!!a&&"object"===typeof a}function A(a){return"function"===typeof a}function K(a){return"number"===typeof a}function H(a){return"boolean"=== +typeof a}function N(a){return"string"===typeof a}function ea(a){if(!N(a))return!1;Q.querySelector(a);return!0}function x(a,b){for(var c in b)a[c]=b[c];return a}function ra(a,b){for(var c in b){var d=!1,e;for(e in Ca)if(0===c.indexOf(e)&&Ca[e].test(c)){d=!0;break}d||(a[c]=b[c])}return a}function sa(a,b){a.page=a.page||{};a.page.x=b.page.x;a.page.y=b.page.y;a.client=a.client||{};a.client.x=b.client.x;a.client.y=b.client.y;a.timeStamp=b.timeStamp}function Ta(a,b,c){a.page.x=c.page.x-b.page.x;a.page.y= +c.page.y-b.page.y;a.client.x=c.client.x-b.client.x;a.client.y=c.client.y-b.client.y;a.timeStamp=(new Date).getTime()-b.timeStamp;b=Math.max(a.timeStamp/1E3,.001);a.page.speed=fa(a.page.x,a.page.y)/b;a.page.vx=a.page.x/b;a.page.vy=a.page.y/b;a.client.speed=fa(a.client.x,a.page.y)/b;a.client.vx=a.client.x/b;a.client.vy=a.client.y/b}function Ua(a){return a instanceof q.Event||ga&&q.Touch&&a instanceof q.Touch}function ta(a,b,c){c=c||{};a=a||"page";c.x=b[a+"X"];c.y=b[a+"Y"];return c}function Da(a,b){b= +b||{};Va&&Ua(a)?(ta("screen",a,b),b.x+=q.scrollX,b.y+=q.scrollY):ta("page",a,b);return b}function Wa(a,b){b=b||{};Va&&Ua(a)?ta("screen",a,b):ta("client",a,b);return b}function O(a){return K(a.pointerId)?a.pointerId:a.identifier}function Ea(a){return a instanceof nb?a.correspondingUseElement:a}function V(a){if(Ba(a))return a;a=a.ownerDocument||a;return a.defaultView||a.parentWindow||q}function Fa(a){return(a=a instanceof Xa?a.getBoundingClientRect():a.getClientRects()[0])&&{left:a.left,right:a.right, +top:a.top,bottom:a.bottom,width:a.width||a.right-a.left,height:a.height||a.bottom-a.top}}function ua(a){var b,c=Fa(a);!ob&&c&&(b=(b=V(a))||q,a=b.scrollX||b.document.documentElement.scrollLeft,b=b.scrollY||b.document.documentElement.scrollTop,c.left+=a,c.right+=a,c.top+=b,c.bottom+=b);return c}function Ga(a){var b=[];da(a)?(b[0]=a[0],b[1]=a[1]):"touchend"===a.type?1===a.touches.length?(b[0]=a.touches[0],b[1]=a.changedTouches[0]):0===a.touches.length&&(b[0]=a.changedTouches[0],b[1]=a.changedTouches[1]): +(b[0]=a.touches[0],b[1]=a.touches[1]);return b}function Ya(a){for(var b={pageX:0,pageY:0,clientX:0,clientY:0,screenX:0,screenY:0},c,d=0;db?d+=360+d/360|0:-135>b&&(d+=180+d/360|0));return d}function na(a,b){var c=a?a.options.origin:D.origin;"parent"===c?c=L(b):"self"===c?c=a.getRect(b):ea(c)&&(c=Ka(b,c)||{x:0,y:0});A(c)&&(c=c(a&&b));t(c)&&(c=ua(c));c.x="x"in c?c.x:c.left;c.y="y"in +c?c.y:c.top;return c}function Za(a,b,c,d){var e=1-a;return e*e*b+2*e*a*c+a*a*d}function Y(a,b){for(;b;){if(b===a)return!0;b=b.parentNode}return!1}function Ka(a,b){for(var c=L(a);t(c);){if(R(c,b))return c;c=L(c)}return null}function L(a){if((a=a.parentNode)&&a instanceof $a)for(;(a=a.host)&&a&&a instanceof $a;);return a}function va(a,b){return a._context===b.ownerDocument||Y(a._context,b)}function Z(a,b,c){return(a=a.options.ignoreFrom)&&t(c)?N(a)?La(c,a,b):t(a)?Y(a,c):!1:!1}function aa(a,b,c){return(a= +a.options.allowFrom)?t(c)?N(a)?La(c,a,b):t(a)?Y(a,c):!1:!1:!0}function ab(a,b){if(!b)return!1;var c=b.options.drag.axis;return"xy"===a||"xy"===c||c===a}function Ma(a,b){var c=a.options;/^resize/.test(b)&&(b="resize");return c[b].snap&&c[b].snap.enabled}function Na(a,b){var c=a.options;/^resize/.test(b)&&(b="resize");return c[b].restrict&&c[b].restrict.enabled}function ha(a,b,c){for(var d=a.options,e=d[c.name].max,d=d[c.name].maxPerElement,h=0,f=0,g=0,k=0,y=r.length;k=wa||n.target===a&&(f+=u===c.name|0,f>=e||n.element===b&&(g++,u!==c.name||g>=d))))return!1}return 0(new Date).getTime()-db)return}if(c=bb(b,b.type,d))c._updateEventTargets(d,e),c[a](b,b,d,e)}}}function G(a,b,c,d,e,h){var f,g,k=a.target,y=a.snapStatus,n=a.restrictStatus,u=a.pointers,E=(k&&k.options||D).deltaSource,eb=E+"X",l=E+"Y",ia=k?k.options:D,w=na(k,e),m="start"===d,p="end"===d;f=m?a.startCoords:a.curCoords;e=e||a.element;g=x({},f.page);f=x({},f.client);g.x-=w.x;g.y-=w.y;f.x-=w.x;f.y-=w.y;var I=ia[c].snap&&ia[c].snap.relativePoints;!Ma(k,c)||m&&I&&I.length||(this.snap={range:y.range, +locked:y.locked,x:y.snappedX,y:y.snappedY,realX:y.realX,realY:y.realY,dx:y.dx,dy:y.dy},y.locked&&(g.x+=y.dx,g.y+=y.dy,f.x+=y.dx,f.y+=y.dy));!Na(k,c)||m&&ia[c].restrict.elementRect||!n.restricted||(g.x+=n.dx,g.y+=n.dy,f.x+=n.dx,f.y+=n.dy,this.restrict={dx:n.dx,dy:n.dy});this.pageX=g.x;this.pageY=g.y;this.clientX=f.x;this.clientY=f.y;this.x0=a.startCoords.page.x-w.x;this.y0=a.startCoords.page.y-w.y;this.clientX0=a.startCoords.client.x-w.x;this.clientY0=a.startCoords.client.y-w.y;this.ctrlKey=b.ctrlKey; +this.altKey=b.altKey;this.shiftKey=b.shiftKey;this.metaKey=b.metaKey;this.button=b.button;this.buttons=b.buttons;this.target=e;this.t0=a.downTimes[0];this.type=c+(d||"");this.interaction=a;this.interactable=k;e=a.inertiaStatus;e.active&&(this.detail="inertia");h&&(this.relatedTarget=h);p?"client"===E?(this.dx=f.x-a.startCoords.client.x,this.dy=f.y-a.startCoords.client.y):(this.dx=g.x-a.startCoords.page.x,this.dy=g.y-a.startCoords.page.y):m?this.dy=this.dx=0:"inertiastart"===d?(this.dx=a.prevEvent.dx, +this.dy=a.prevEvent.dy):"client"===E?(this.dx=f.x-a.prevEvent.clientX,this.dy=f.y-a.prevEvent.clientY):(this.dx=g.x-a.prevEvent.pageX,this.dy=g.y-a.prevEvent.pageY);a.prevEvent&&"inertia"===a.prevEvent.detail&&!e.active&&ia[c].inertia&&ia[c].inertia.zeroResumeDelta&&(e.resumeDx+=this.dx,e.resumeDy+=this.dy,this.dx=this.dy=0);"resize"===c&&a.resizeAxes?ia.resize.square?("y"===a.resizeAxes?this.dx=this.dy:this.dy=this.dx,this.axes="xy"):(this.axes=a.resizeAxes,"x"===a.resizeAxes?this.dy=0:"y"===a.resizeAxes&& +(this.dx=0)):"gesture"===c&&(this.touches=[u[0],u[1]],m?(this.distance=Ia(u,E),this.box=Ha(u),this.scale=1,this.ds=0,this.angle=Ja(u,void 0,E),this.da=0):p||b instanceof G?(this.distance=a.prevEvent.distance,this.box=a.prevEvent.box,this.scale=a.prevEvent.scale,this.ds=this.scale-1,this.angle=a.prevEvent.angle,this.da=this.angle-a.gesture.startAngle):(this.distance=Ia(u,E),this.box=Ha(u),this.scale=this.distance/a.gesture.startDistance,this.angle=Ja(u,a.gesture.prevAngle,E),this.ds=this.scale-a.gesture.prevScale, +this.da=this.angle-a.gesture.prevAngle));m?(this.timeStamp=a.downTimes[0],this.velocityY=this.velocityX=this.speed=this.duration=this.dt=0):"inertiastart"===d?(this.timeStamp=a.prevEvent.timeStamp,this.dt=a.prevEvent.dt,this.duration=a.prevEvent.duration,this.speed=a.prevEvent.speed,this.velocityX=a.prevEvent.velocityX,this.velocityY=a.prevEvent.velocityY):(this.timeStamp=(new Date).getTime(),this.dt=this.timeStamp-a.prevEvent.timeStamp,this.duration=this.timeStamp-a.downTimes[0],b instanceof G?(b= +this[eb]-a.prevEvent[eb],l=this[l]-a.prevEvent[l],c=this.dt/1E3,this.speed=fa(b,l)/c,this.velocityX=b/c,this.velocityY=l/c):(this.speed=a.pointerDelta[E].speed,this.velocityX=a.pointerDelta[E].vx,this.velocityY=a.pointerDelta[E].vy));(p||"inertiastart"===d)&&600this.timeStamp-a.prevEvent.timeStamp&&(d=180*Math.atan2(a.prevEvent.velocityY,a.prevEvent.velocityX)/Math.PI,0>d&&(d+=360),p=112.5<=d&&247.5>d,l=202.5<=d&&337.5>d,this.swipe={up:l,down:!l&&22.5<=d&&157.5>d,left:p,right:!p&& +(292.5<=d||67.5>d),angle:d,speed:a.prevEvent.speed,velocity:{x:a.prevEvent.velocityX,y:a.prevEvent.velocityY}})}function fb(){this.originalEvent.preventDefault()}function gb(a){var b="";"drag"===a.name&&(b=za.drag);if("resize"===a.name)if(a.axis)b=za[a.name+a.axis];else if(a.edges){for(var b="resize",c=["top","bottom","left","right"],d=0;4>d;d++)a.edges[c[d]]&&(b+=c[d]);b=za[b]}return b}function hb(a,b,c){a=this.getRect(c);var d=!1,e=null,h=null,f,g=x({},b.curCoords.page),e=this.options;if(!a)return null; +if(S.resize&&e.resize.enabled)if(d=e.resize,f={left:!1,right:!1,top:!1,bottom:!1},z(d.edges)){for(var k in f){var y=f,n=k,u;a:{u=k;var E=d.edges[k],l=g,m=b._eventTarget,p=c,w=a,ya=d.margin||pa;if(E){if(!0===E){var q=K(w.width)?w.width:w.right-w.left,I=K(w.height)?w.height:w.bottom-w.top;0>q&&("left"===u?u="right":"right"===u&&(u="left"));0>I&&("top"===u?u="bottom":"bottom"===u&&(u="top"));if("left"===u){u=l.x<(0<=q?w.left:w.right)+ya;break a}if("top"===u){u=l.y<(0<=I?w.top:w.bottom)+ya;break a}if("right"=== +u){u=l.x>(0<=q?w.right:w.left)-ya;break a}if("bottom"===u){u=l.y>(0<=I?w.bottom:w.top)-ya;break a}}u=t(m)?t(E)?E===m:La(m,E,p):!1}else u=!1}y[n]=u}f.left=f.left&&!f.right;f.top=f.top&&!f.bottom;d=f.left||f.right||f.top||f.bottom}else c="y"!==e.resize.axis&&g.x>a.right-pa,a="x"!==e.resize.axis&&g.y>a.bottom-pa,d=c||a,h=(c?"x":"")+(a?"y":"");e=d?"resize":S.drag&&e.drag.enabled?"drag":null;S.gesture&&2<=b.pointerIds.length&&!b.dragging&&!b.resizing&&(e="gesture");return e?{name:e,axis:h,edges:f}:null} +function W(a,b){if(!z(a))return null;var c=a.name,d=b.options;return("resize"===c&&d.resize.enabled||"drag"===c&&d.drag.enabled||"gesture"===c&&d.gesture.enabled)&&S[c]?a:null}function qa(a,b){var c={},d=P[a.type],e=Ea(a.path?a.path[0]:a.target),h=e;b=b?!0:!1;for(var f in a)c[f]=a[f];c.originalEvent=a;for(c.preventDefault=fb;t(h);){for(f=0;fthis.pointerIds.length&&(f=null),this.prepared.name=f.name,this.prepared.axis=f.axis,this.prepared.edges=f.edges,this.snapStatus.snappedX=this.snapStatus.snappedY=this.restrictStatus.restrictedX=this.restrictStatus.restrictedY=NaN,this.downTimes[h]=(new Date).getTime(),this.downTargets[h]=c,ra(this.downPointer,a),sa(this.prevCoords,this.startCoords),this.pointerWasMoved=!1,this.checkAndPreventDefault(b,g,this.element)))}},setModifications:function(a, +b){var c=this.target,d=!0,e=Ma(c,this.prepared.name)&&(!c.options[this.prepared.name].snap.endOnly||b),c=Na(c,this.prepared.name)&&(!c.options[this.prepared.name].restrict.endOnly||b);e?this.setSnapping(a):this.snapStatus.locked=!1;c?this.setRestriction(a):this.restrictStatus.restricted=!1;e&&this.snapStatus.locked&&!this.snapStatus.changed?d=c&&this.restrictStatus.restricted&&this.restrictStatus.changed:c&&this.restrictStatus.restricted&&!this.restrictStatus.changed&&(d=!1);return d},setStartOffsets:function(a, +b,c){a=b.getRect(c);var d=na(b,c);c=b.options[this.prepared.name].snap;b=b.options[this.prepared.name].restrict;var e,h;a?(this.startOffset.left=this.startCoords.page.x-a.left,this.startOffset.top=this.startCoords.page.y-a.top,this.startOffset.right=a.right-this.startCoords.page.x,this.startOffset.bottom=a.bottom-this.startCoords.page.y,e="width"in a?a.width:a.right-a.left,h="height"in a?a.height:a.bottom-a.top):this.startOffset.left=this.startOffset.top=this.startOffset.right=this.startOffset.bottom= +0;this.snapOffsets.splice(0);d=c&&"startCoords"===c.offset?{x:this.startCoords.page.x-d.x,y:this.startCoords.page.y-d.y}:c&&c.offset||{x:0,y:0};if(a&&c&&c.relativePoints&&c.relativePoints.length)for(var f=0;fQa);d||this.pointerIsDown&&!this.pointerWasMoved||(this.pointerIsDown&&clearTimeout(this.holdTimers[h]),this.collectEventTargets(a,b,c,"move"));if(this.pointerIsDown)if(d&&this.pointerWasMoved&&!e)this.checkAndPreventDefault(b,this.target,this.element);else if(Ta(this.pointerDelta,this.prevCoords,this.curCoords),this.prepared.name){if(this.pointerWasMoved&&(!this.inertiaStatus.active||a instanceof G&&/inertiastart/.test(a.type))){if(!this.interacting()&&(Ta(this.pointerDelta, +this.prevCoords,this.curCoords),"drag"===this.prepared.name)){f=Math.abs(f);g=Math.abs(g);d=this.target.options.drag.axis;var k=f>g?"x":fk.bottom&&(b=k.top,k.top=k.bottom,k.bottom=b),k.left>k.right&&(b=k.left,k.left=k.right,k.right=b))):(k.top=Math.min(g.top,f.bottom),k.bottom=Math.max(g.bottom,f.top),k.left=Math.min(g.left,f.right),k.right=Math.max(g.right,f.left));k.width=k.right-k.left;k.height=k.bottom-k.top;for(var q in k)l[q]=k[q]-n[q];a.edges=this.prepared.edges;a.rect=k;a.deltaRect=l}this.target.fire(a); +return a},gestureStart:function(a){a=new G(this,a,"gesture","start",this.element);a.ds=0;this.gesture.startDistance=this.gesture.prevDistance=a.distance;this.gesture.startAngle=this.gesture.prevAngle=a.angle;this.gesture.scale=1;this.gesturing=!0;this.target.fire(a);return a},gestureMove:function(a){if(!this.pointerIds.length)return this.prevEvent;a=new G(this,a,"gesture","move",this.element);a.ds=a.scale-this.gesture.scale;this.target.fire(a);this.gesture.prevAngle=a.angle;this.gesture.prevDistance= +a.distance;Infinity===a.scale||null===a.scale||void 0===a.scale||isNaN(a.scale)||(this.gesture.scale=a.scale);return a},pointerHold:function(a,b,c){this.collectEventTargets(a,b,c,"hold")},pointerUp:function(a,b,c,d){var e=this.mouse?0:v(this.pointerIds,O(a));clearTimeout(this.holdTimers[e]);this.collectEventTargets(a,b,c,"up");this.collectEventTargets(a,b,c,"tap");this.pointerEnd(a,b,c,d);this.removePointer(a)},pointerCancel:function(a,b,c,d){var e=this.mouse?0:v(this.pointerIds,O(a));clearTimeout(this.holdTimers[e]); +this.collectEventTargets(a,b,c,"cancel");this.pointerEnd(a,b,c,d);this.removePointer(a)},ie8Dblclick:function(a,b,c){this.prevTap&&b.clientX===this.prevTap.clientX&&b.clientY===this.prevTap.clientY&&c===this.prevTap.target&&(this.downTargets[0]=c,this.downTimes[0]=(new Date).getTime(),this.collectEventTargets(a,b,c,"tap"))},pointerEnd:function(a,b,c,d){var e,h=this.target,f=h&&h.options,g=f&&this.prepared.name&&f[this.prepared.name].inertia;e=this.inertiaStatus;if(this.interacting()){if(e.active&& +!e.ending)return;var k=(new Date).getTime(),l=!1,m=!1,n=!1,p=Ma(h,this.prepared.name)&&f[this.prepared.name].snap.endOnly,q=Na(h,this.prepared.name)&&f[this.prepared.name].restrict.endOnly,r=0,t=0,f=this.dragging?"x"===f.drag.axis?Math.abs(this.pointerDelta.client.vx):"y"===f.drag.axis?Math.abs(this.pointerDelta.client.vy):this.pointerDelta.client.speed:this.pointerDelta.client.speed,m=(l=g&&g.enabled&&"gesture"!==this.prepared.name&&b!==e.startEvent)&&50>k-this.curCoords.timeStamp&&f>g.minSpeed&& +f>g.endSpeed;l&&!m&&(p||q)&&(g={},g.snap=g.restrict=g,p&&(this.setSnapping(this.curCoords.page,g),g.locked&&(r+=g.dx,t+=g.dy)),q&&(this.setRestriction(this.curCoords.page,g),g.restricted&&(r+=g.dx,t+=g.dy)),r||t)&&(n=!0);if(m||n){sa(e.upCoords,this.curCoords);this.pointers[0]=e.startEvent=new G(this,b,this.prepared.name,"inertiastart",this.element);e.t0=k;h.fire(e.startEvent);m?(e.vx0=this.pointerDelta.client.vx,e.vy0=this.pointerDelta.client.vy,e.v0=f,this.calcInertia(e),b=x({},this.curCoords.page), +h=na(h,this.element),b.x=b.x+e.xe-h.x,b.y=b.y+e.ye-h.y,h={useStatusXY:!0,x:b.x,y:b.y,dx:0,dy:0,snap:null},h.snap=h,r=t=0,p&&(b=this.setSnapping(this.curCoords.page,h),b.locked&&(r+=b.dx,t+=b.dy)),q&&(h=this.setRestriction(this.curCoords.page,h),h.restricted&&(r+=h.dx,t+=h.dy)),e.modifiedXe+=r,e.modifiedYe+=t,e.i=T(this.boundInertiaFrame)):(e.smoothEnd=!0,e.xe=r,e.ye=t,e.sx=e.sy=0,e.i=T(this.boundSmoothEndFrame));e.active=!0;return}(p||q)&&this.pointerMove(a,b,c,d,!0)}this.dragging?(e=new G(this,b, +"drag","end",this.element),q=this.getDrop(e,b,this.element),this.dropTarget=q.dropzone,this.dropElement=q.element,q=this.getDropEvents(b,e),q.leave&&this.prevDropTarget.fire(q.leave),q.enter&&this.dropTarget.fire(q.enter),q.drop&&this.dropTarget.fire(q.drop),q.deactivate&&this.fireActiveDrops(q.deactivate),h.fire(e)):this.resizing?(e=new G(this,b,"resize","end",this.element),h.fire(e)):this.gesturing&&(e=new G(this,b,"gesture","end",this.element),h.fire(e));this.stop(b)},collectDrops:function(a){var b= +[],c=[],d;a=a||this.element;for(d=0;dk),g["double"]=l,this.tapTime=g.timeStamp);for(a=0;ah.innerWidth-p.margin, +a=a.clientY>h.innerHeight-p.margin):(h=Fa(h),d=a.clientXh.right-p.margin,a=a.clientY>h.bottom-p.margin);p.x=c?1:d?-1:0;p.y=a?1:b?-1:0;p.isScrolling||(p.margin=e.margin,p.speed=e.speed,p.start(this))}},_updateEventTargets:function(a,b){this._eventTarget=a;this._curEventTarget=b}};G.prototype={preventDefault:ma,stopImmediatePropagation:function(){this.immediatePropagationStopped=this.propagationStopped=!0},stopPropagation:function(){this.propagationStopped= +!0}};for(var m={},lb="dragStart dragMove resizeStart resizeMove gestureStart gestureMove pointerOver pointerOut pointerHover selectorDown pointerDown pointerMove pointerUp pointerCancel pointerEnd addPointer removePointer recordPointer autoScrollMove".split(" "),Ra=0,Sa=lb.length;Rah.left&&k.xh.top&&k.y=h.left&&f<=h.right&&l>=h.top&&l<=h.bottom;K(g)&&(f=Math.max(0,Math.min(h.right,k.right)-Math.max(h.left,k.left))*Math.max(0,Math.min(h.bottom,k.bottom)-Math.max(h.top,k.top))/(k.width*k.height)>=g);this.options.drop.checker&&(f=this.options.drop.checker(a,b,f,this,e,c,d));return f},dropChecker:function(a){return A(a)?(this.options.drop.checker=a,this): +null===a?(delete this.options.getRect,this):this.options.drop.checker},accept:function(a){return t(a)||ea(a)?(this.options.drop.accept=a,this):null===a?(delete this.options.drop.accept,this):this.options.drop.accept},resizable:function(a){return z(a)?(this.options.resize.enabled=!1===a.enabled?!1:!0,this.setPerAction("resize",a),this.setOnEvents("resize",a),/^x$|^y$|^xy$/.test(a.axis)?this.options.resize.axis=a.axis:null===a.axis&&(this.options.resize.axis=D.resize.axis),H(a.preserveAspectRatio)? +this.options.resize.preserveAspectRatio=a.preserveAspectRatio:H(a.square)&&(this.options.resize.square=a.square),this):H(a)?(this.options.resize.enabled=a,this):this.options.resize},squareResize:function(a){return H(a)?(this.options.resize.square=a,this):null===a?(delete this.options.resize.square,this):this.options.resize.square},gesturable:function(a){return z(a)?(this.options.gesture.enabled=!1===a.enabled?!1:!0,this.setPerAction("gesture",a),this.setOnEvents("gesture",a),this):H(a)?(this.options.gesture.enabled= +a,this):this.options.gesture},autoScroll:function(a){z(a)?a=x({actions:["drag","resize"]},a):H(a)&&(a={actions:["drag","resize"],enabled:a});return this.setOptions("autoScroll",a)},snap:function(a){a=this.setOptions("snap",a);return a===this?this:a.drag},setOptions:function(a,b){var c=b&&da(b.actions)?b.actions:["drag"],d;if(z(b)||H(b)){for(d=0;da?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isPlainObject:function(a){var b;if("object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype||{},"isPrototypeOf"))return!1;for(b in a);return void 0===b||k.call(a,b)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=d.createElement("script"),b.text=a,d.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:h.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;d>g;g++)e=b(a[g],g,c),null!=e&&h.push(e);else for(g in a)e=b(a[g],g,c),null!=e&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(d=e.call(arguments,2),f=function(){return a.apply(b||this,d.concat(e.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M+"|[*])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,aa=/'|\\/g,ba=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(ea){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fa(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+qa(r[h]);s=r.join(","),w=_.test(a)&&oa(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function ga(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ha(a){return a[u]=!0,a}function ia(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ka(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function la(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function na(a){return ha(function(b){return b=+b,ha(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function oa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=fa.support={},f=fa.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fa.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ia(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ia(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ia(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ia(function(a){o.appendChild(a).innerHTML="
",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ia(function(a){var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ia(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ka(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ka(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},fa.matches=function(a,b){return fa(a,null,null,b)},fa.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fa(b,n,null,[a]).length>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fa.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fa.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fa.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fa.selectors={cacheLength:50,createPseudo:ha,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fa.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fa.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ba,ca).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fa.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(P," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fa.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ha(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ha(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ha(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ha(function(a){return function(b){return fa(a,b).length>0}}),contains:ha(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ha(function(a){return V.test(a||"")||fa.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:na(function(){return[0]}),last:na(function(a,b){return[b-1]}),eq:na(function(a,b,c){return[0>c?c+b:c]}),even:na(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:na(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:na(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:na(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function ra(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function sa(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ta(a,b,c){for(var d=0,e=b.length;e>d;d++)fa(a,b[d],c);return c}function ua(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function va(a,b,c,d,e,f){return d&&!d[u]&&(d=va(d)),e&&!e[u]&&(e=va(e,f)),ha(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ta(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ua(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ua(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ua(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ra(function(a){return a===b},h,!0),l=ra(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[ra(sa(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return va(i>1&&sa(m),i>1&&qa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(Q,"$1"),c,e>i&&wa(a.slice(i,e)),f>e&&wa(a=a.slice(e)),f>e&&qa(a))}m.push(c)}return sa(m)}function xa(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(i));u=ua(u)}H.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&fa.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ha(f):f}return h=fa.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xa(e,d)),f.selector=a}return f},i=fa.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ba,ca),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=W.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ba,ca),_.test(j[0].type)&&oa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qa(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||_.test(a)&&oa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ia(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ia(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||ja("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ia(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ja("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ia(function(a){return null==a.getAttribute("disabled")})||ja(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fa}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.uniqueSort=n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},v=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},w=n.expr.match.needsContext,x=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,y=/^.[^:#\[\.,]*$/;function z(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(y.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return h.call(b,a)>-1!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(z(this,a||[],!1))},not:function(a){return this.pushStack(z(this,a||[],!0))},is:function(a){return!!z(this,"string"==typeof a&&w.test(a)?n(a):a||[],!1).length}});var A,B=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=n.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||A,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:B.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),x.test(e[1])&&n.isPlainObject(b))for(e in b)n.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&f.parentNode&&(this.length=1,this[0]=f),this.context=d,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?void 0!==c.ready?c.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};C.prototype=n.fn,A=n(d);var D=/^(?:parents|prev(?:Until|All))/,E={children:!0,contents:!0,next:!0,prev:!0};n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=w.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?h.call(n(a),this[0]):h.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.uniqueSort(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function F(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return u(a,"parentNode")},parentsUntil:function(a,b,c){return u(a,"parentNode",c)},next:function(a){return F(a,"nextSibling")},prev:function(a){return F(a,"previousSibling")},nextAll:function(a){return u(a,"nextSibling")},prevAll:function(a){return u(a,"previousSibling")},nextUntil:function(a,b,c){return u(a,"nextSibling",c)},prevUntil:function(a,b,c){return u(a,"previousSibling",c)},siblings:function(a){return v((a.parentNode||{}).firstChild,a)},children:function(a){return v(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(E[a]||n.uniqueSort(e),D.test(a)&&e.reverse()),this.pushStack(e)}});var G=/\S+/g;function H(a){var b={};return n.each(a.match(G)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?H(a):n.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h-1)f.splice(c,1),h>=c&&h--}),this},has:function(a){return a?n.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().progress(c.notify).done(c.resolve).fail(c.reject):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=e.call(arguments),d=c.length,f=1!==d||a&&n.isFunction(a.promise)?d:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?e.call(arguments):d,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(d>1)for(i=new Array(d),j=new Array(d),k=new Array(d);d>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().progress(h(b,j,i)).done(h(b,k,c)).fail(g.reject):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(d,[n]),n.fn.triggerHandler&&(n(d).triggerHandler("ready"),n(d).off("ready"))))}});function J(){d.removeEventListener("DOMContentLoaded",J),a.removeEventListener("load",J),n.ready()}n.ready.promise=function(b){return I||(I=n.Deferred(),"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(n.ready):(d.addEventListener("DOMContentLoaded",J),a.addEventListener("load",J))),I.promise(b)},n.ready.promise();var K=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)K(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},L=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function M(){this.expando=n.expando+M.uid++}M.uid=1,M.prototype={register:function(a,b){var c=b||{};return a.nodeType?a[this.expando]=c:Object.defineProperty(a,this.expando,{value:c,writable:!0,configurable:!0}),a[this.expando]},cache:function(a){if(!L(a))return{};var b=a[this.expando];return b||(b={},L(a)&&(a.nodeType?a[this.expando]=b:Object.defineProperty(a,this.expando,{value:b,configurable:!0}))),b},set:function(a,b,c){var d,e=this.cache(a);if("string"==typeof b)e[b]=c;else for(d in b)e[d]=b[d];return e},get:function(a,b){return void 0===b?this.cache(a):a[this.expando]&&a[this.expando][b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=a[this.expando];if(void 0!==f){if(void 0===b)this.register(a);else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in f?d=[b,e]:(d=e,d=d in f?[d]:d.match(G)||[])),c=d.length;while(c--)delete f[d[c]]}(void 0===b||n.isEmptyObject(f))&&(a.nodeType?a[this.expando]=void 0:delete a[this.expando])}},hasData:function(a){var b=a[this.expando];return void 0!==b&&!n.isEmptyObject(b)}};var N=new M,O=new M,P=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Q=/[A-Z]/g;function R(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(Q,"-$&").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:P.test(c)?n.parseJSON(c):c; +}catch(e){}O.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return O.hasData(a)||N.hasData(a)},data:function(a,b,c){return O.access(a,b,c)},removeData:function(a,b){O.remove(a,b)},_data:function(a,b,c){return N.access(a,b,c)},_removeData:function(a,b){N.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=O.get(f),1===f.nodeType&&!N.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),R(f,d,e[d])));N.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){O.set(this,a)}):K(this,function(b){var c,d;if(f&&void 0===b){if(c=O.get(f,a)||O.get(f,a.replace(Q,"-$&").toLowerCase()),void 0!==c)return c;if(d=n.camelCase(a),c=O.get(f,d),void 0!==c)return c;if(c=R(f,d,void 0),void 0!==c)return c}else d=n.camelCase(a),this.each(function(){var c=O.get(this,d);O.set(this,d,b),a.indexOf("-")>-1&&void 0!==c&&O.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){O.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=N.get(a,b),c&&(!d||n.isArray(c)?d=N.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return N.get(a,c)||N.access(a,c,{empty:n.Callbacks("once memory").add(function(){N.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length",""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};$.optgroup=$.option,$.tbody=$.tfoot=$.colgroup=$.caption=$.thead,$.th=$.td;function _(a,b){var c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function aa(a,b){for(var c=0,d=a.length;d>c;c++)N.set(a[c],"globalEval",!b||N.get(b[c],"globalEval"))}var ba=/<|&#?\w+;/;function ca(a,b,c,d,e){for(var f,g,h,i,j,k,l=b.createDocumentFragment(),m=[],o=0,p=a.length;p>o;o++)if(f=a[o],f||0===f)if("object"===n.type(f))n.merge(m,f.nodeType?[f]:f);else if(ba.test(f)){g=g||l.appendChild(b.createElement("div")),h=(Y.exec(f)||["",""])[1].toLowerCase(),i=$[h]||$._default,g.innerHTML=i[1]+n.htmlPrefilter(f)+i[2],k=i[0];while(k--)g=g.lastChild;n.merge(m,g.childNodes),g=l.firstChild,g.textContent=""}else m.push(b.createTextNode(f));l.textContent="",o=0;while(f=m[o++])if(d&&n.inArray(f,d)>-1)e&&e.push(f);else if(j=n.contains(f.ownerDocument,f),g=_(l.appendChild(f),"script"),j&&aa(g),c){k=0;while(f=g[k++])Z.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var da=/^key/,ea=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,fa=/^([^.]*)(?:\.(.+)|)/;function ga(){return!0}function ha(){return!1}function ia(){try{return d.activeElement}catch(a){}}function ja(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)ja(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=ha;else if(!e)return a;return 1===f&&(g=e,e=function(a){return n().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=n.guid++)),a.each(function(){n.event.add(this,b,e,d,c)})}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=N.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return"undefined"!=typeof n&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(G)||[""],j=b.length;while(j--)h=fa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=N.hasData(a)&&N.get(a);if(r&&(i=r.events)){b=(b||"").match(G)||[""],j=b.length;while(j--)if(h=fa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&N.remove(a,"handle events")}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(N.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())a.rnamespace&&!a.rnamespace.test(g.namespace)||(a.handleObj=g,a.data=g.data,d=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!==this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>-1:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]*)\/>/gi,la=/\s*$/g;function pa(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function qa(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function ra(a){var b=na.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function sa(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(N.hasData(a)&&(f=N.access(a),g=N.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}O.hasData(a)&&(h=O.access(a),i=n.extend({},h),O.set(b,i))}}function ta(a,b){var c=b.nodeName.toLowerCase();"input"===c&&X.test(a.type)?b.checked=a.checked:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}function ua(a,b,c,d){b=f.apply([],b);var e,g,h,i,j,k,m=0,o=a.length,p=o-1,q=b[0],r=n.isFunction(q);if(r||o>1&&"string"==typeof q&&!l.checkClone&&ma.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),ua(f,b,c,d)});if(o&&(e=ca(b,a[0].ownerDocument,!1,a,d),g=e.firstChild,1===e.childNodes.length&&(e=g),g||d)){for(h=n.map(_(e,"script"),qa),i=h.length;o>m;m++)j=e,m!==p&&(j=n.clone(j,!0,!0),i&&n.merge(h,_(j,"script"))),c.call(a[m],j,m);if(i)for(k=h[h.length-1].ownerDocument,n.map(h,ra),m=0;i>m;m++)j=h[m],Z.test(j.type||"")&&!N.access(j,"globalEval")&&n.contains(k,j)&&(j.src?n._evalUrl&&n._evalUrl(j.src):n.globalEval(j.textContent.replace(oa,"")))}return a}function va(a,b,c){for(var d,e=b?n.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||n.cleanData(_(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&aa(_(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(ka,"<$1>")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=_(h),f=_(a),d=0,e=f.length;e>d;d++)ta(f[d],g[d]);if(b)if(c)for(f=f||_(a),g=g||_(h),d=0,e=f.length;e>d;d++)sa(f[d],g[d]);else sa(a,h);return g=_(h,"script"),g.length>0&&aa(g,!i&&_(a,"script")),h},cleanData:function(a){for(var b,c,d,e=n.event.special,f=0;void 0!==(c=a[f]);f++)if(L(c)){if(b=c[N.expando]){if(b.events)for(d in b.events)e[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);c[N.expando]=void 0}c[O.expando]&&(c[O.expando]=void 0)}}}),n.fn.extend({domManip:ua,detach:function(a){return va(this,a,!0)},remove:function(a){return va(this,a)},text:function(a){return K(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return ua(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=pa(this,a);b.appendChild(a)}})},prepend:function(){return ua(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=pa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return ua(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return ua(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(_(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return K(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!la.test(a)&&!$[(Y.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(_(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return ua(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData(_(this)),c&&c.replaceChild(b,this))},a)}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),f=e.length-1,h=0;f>=h;h++)c=h===f?this:this.clone(!0),n(e[h])[b](c),g.apply(d,c.get());return this.pushStack(d)}});var wa,xa={HTML:"block",BODY:"block"};function ya(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function za(a){var b=d,c=xa[a];return c||(c=ya(a,b),"none"!==c&&c||(wa=(wa||n("'; + html+="
"; + + html+="
Back >
"; + + html+="
"; + $('body').append(html); +} + +function show_poffers() +{ + var html=""; + html+="
"; + + html+="
"; + html+=''; + html+="
"; + + html+="
BACK >
"; + + html+="
"; + $('body').append(html); +} + diff --git a/js/pixi-display/.DS_Store b/js/pixi-display/.DS_Store new file mode 100644 index 0000000..bb9cc81 Binary files /dev/null and b/js/pixi-display/.DS_Store differ diff --git a/js/pixi-display/v1/pixi-display.js b/js/pixi-display/v1/pixi-display.js new file mode 100644 index 0000000..b016b97 --- /dev/null +++ b/js/pixi-display/v1/pixi-display.js @@ -0,0 +1,734 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o b.zOrder) { + return -1; + } + return a.updateOrder - b.updateOrder; +}; + +/** + * clears temporary variables + */ +DisplayGroup.prototype.clear = function () { + var list = this.computedChildren; + for (var i = 0; i < list.length; i++) { + var children = list[i].displayChildren; + if (children && children.length > 0) { + for (var j = 0; j < children.length; j++) { + children[j].displayParent = null; + } + children.length = 0; + } + list[i].displayParent = null; + } + list.length = 0; + this.currentDisplayList = null; + this.currentIndex = 0; +}; + +/** + * used only by displayList before sorting takes place + * @param container {PIXI.DisplayObject} + */ +DisplayGroup.prototype.add = function (displayObject) { + displayObject.displayOrder = this.computedChildren.length; + this.emit('add', displayObject); + this.computedChildren.push(displayObject); +}; + +/** + * Called after all childrens are computed + */ +DisplayGroup.prototype.update = function () { + this.emit('update'); + if (this.enableSort && this.computedChildren.length > 1) { + this.computedChildren.sort(DisplayGroup.compareZOrder); + } +}; + +},{}],5:[function(require,module,exports){ +var EventEmitter = PIXI.utils.EventEmitter, + Const = require('./Const'), + DisplayGroup = require('./DisplayGroup'); +/** + * A component for container, sorts all children inside according to their displayGroups + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +function DisplayList() { + EventEmitter.call(this); + /** + * Children that were rendered in last run + * @type {Array} + */ + this.displayGroups = []; + + this.container = null; + + /** + * how many elements were rendered by display list last time + * also it is used to generate updateOrder for them + * @type {number} + */ + this.totalElements = 0; + + this.defaultDisplayGroup = new DisplayGroup(0, false); +} + +DisplayList.prototype = Object.create(EventEmitter.prototype); +DisplayList.prototype.constructor = DisplayList; +module.exports = DisplayList; + +/** + * clears all display lists that were used in last rendering session + * please clear it when you stop using this displayList, otherwise you may have problems with GC in some cases + */ +DisplayList.prototype.clear = function () { + var list = this.displayGroups; + for (var i = 0; i < list.length; i++) { + list[i].clear(); + } + list.length = 0; + this.totalElements = 0; + this.container = null; +}; + +/** + * alias for clear() + * please call it if you stop using this displayList + */ +DisplayList.prototype.destroy = function () { + this.clear(); +}; + +DisplayList.compareZIndex = function (a, b) { + if (a.zIndex !== b.zIndex) { + return a.zIndex - b.zIndex; + } + return a.currentIndex - b.currentIndex; +}; + +/** + * + * @param displayObject {PIXI.DisplayObject} container that we are adding to displaylist + * @param parent {PIXI.Container} it is not direct parent, but some of ancestors + * @private + */ +DisplayList.prototype._addRecursive = function (container, parent) { + if (!container.visible || !container.renderable) { + return; + } + var groups = this.displayGroups; + var group = parent.displayGroup; + + container.updateOrder = this.totalElements++; + if (container.displayGroup) { + group = container.displayGroup; + if (!group.currentDisplayList) { + group.currentDisplayList = this; + group.currentIndex = groups.length; + groups.push(group); + } + group.add(container); + + container.displayParent = this; + } else { + container.displayParent = parent; + if (!parent.displayChildren) { + parent.displayChildren = []; + } + parent.displayChildren.push(container); + } + + if (container.displayFlag !== Const.DISPLAY_FLAG.MANUAL_CONTAINER) { + var children = container.children; + if (children && children.length > 0) { + if (container._mask || container._filters && container._filters.length || container.displayList) { + container.displayFlag = Const.DISPLAY_FLAG.AUTO_CONTAINER; + } else { + container.displayFlag = Const.DISPLAY_FLAG.AUTO_CHILDREN; + for (var i = 0; i < children.length; i++) { + this._addRecursive(children[i], container.displayParent); + } + } + } else { + container.displayFlag = Const.DISPLAY_FLAG.AUTO_OBJECT; + } + } +}; + +/** + * Called from container that owns this display list + * @param parentContainer + */ +DisplayList.prototype.update = function (parentContainer) { + this.clear(); + var tempGroup = parentContainer.displayGroup; + this.displayGroups.push(this.defaultDisplayGroup); + this.defaultDisplayGroup.add(parentContainer); + + this.container = parentContainer; + var children = parentContainer.children; + var i; + for (i = 0; i < children.length; i++) { + this._addRecursive(children[i], parentContainer); + } + var groups = this.displayGroups; + groups.sort(DisplayList.compareZIndex); + for (i = 0; i < groups.length; i++) { + groups[i].currentIndex = i; + groups[i].update(); + } + this.emit('afterUpdate'); +}; + +/** + * renders container with webgl context + * @param parentContainer + * @param renderer + */ +DisplayList.prototype.renderWebGL = function (parentContainer, renderer) { + var groups = this.displayGroups; + for (var i = 0; i < groups.length; i++) { + var group = groups[i]; + var list = group.computedChildren; + for (var j = 0; j < list.length; j++) { + var container = list[j]; + if (container.displayFlag) { + container.renderWebGL(renderer); + } else { + container.displayOrder = renderer.incDisplayOrder(); + container._renderWebGL(renderer); + var children = container.displayChildren; + if (children && children.length) { + for (var k = 0; k < children.length; k++) { + var child = children[k]; + child.displayOrder = renderer.incDisplayOrder(); + if (child.displayFlag) { + child.renderWebGL(renderer); + } else { + child._renderWebGL(renderer); + } + } + } + } + } + } +}; + +/** + * renders container with canvas2d context + * @param parentContainer + * @param renderer + */ +DisplayList.prototype.renderCanvas = function (parentContainer, renderer) { + var groups = this.displayGroups; + for (var i = 0; i < groups.length; i++) { + var group = groups[i]; + var list = group.computedChildren; + for (var j = 0; j < list.length; j++) { + var container = list[j]; + if (container.displayFlag) { + container.renderCanvas(renderer); + } else { + container.displayOrder = renderer.incDisplayOrder(); + container._renderCanvas(renderer); + var children = container.displayChildren; + if (children && children.length) { + for (var k = 0; k < children.length; k++) { + var child = children[k]; + child.displayOrder = renderer.incDisplayOrder(); + if (child.displayFlag) { + child.renderCanvas(renderer); + } else { + child._renderCanvas(renderer); + } + } + } + } + } + } +}; + +},{"./Const":2,"./DisplayGroup":4}],6:[function(require,module,exports){ +var Const = require('./Const'); + +/** + * @mixin + */ +var DisplayObjectMixin = { + /** + * please specify it to handle zOrder and zIndex + * @type {PIXI.DisplayGroup} + */ + displayGroup: null, + + /** + * calculated inside displayList. Can be set to manual mode + * @type {number} + */ + displayFlag: Const.DISPLAY_FLAG.AUTO_CHILDREN, + + /** + * calculated inside displayList. Cleared on displayList.clear() + * Equal to 'this' if displayGroup is specified + * @type {PIXI.Container} + */ + displayParent: null, + + /** + * zOrder is distance between screen and object. Objects with largest zOrder will appear first in their DisplayGroup + * @type {number} + */ + zOrder: 0, + + /** + * updateOrder is calculated by DisplayList, it is required for sorting inside DisplayGroup + * @type {number} + */ + updateOrder: 0 +}; + +module.exports = DisplayObjectMixin; + +},{"./Const":2}],7:[function(require,module,exports){ +//TODO: add maxDisplayOrder for displayObjects and use it to speed up the interaction here + +var gameofbombs = !!PIXI.Camera2d; + +/** + * @mixin + */ +var InteractionManagerMixin = { + /** + * This is private recursive copy of processInteractive + */ + _processInteractive: function (point, displayObject, hitTestOrder, interactive) { + if (!displayObject || !displayObject.visible) { + return false; + } + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + var hit = 0, + interactiveParent = interactive = displayObject.interactive || interactive; + + + // if the displayobject has a hitArea, then it does not need to hitTest children. + if (displayObject.hitArea) { + interactiveParent = false; + } + + // it has a mask! Then lets hit test that before continuing.. + if (hitTestOrder < Infinity && displayObject._mask) { + if (!displayObject._mask.containsPoint(point)) { + hitTestOrder = Infinity; + } + } + + // it has a filterArea! Same as mask but easier, its a rectangle + if (hitTestOrder < Infinity && displayObject.filterArea) { + if (!displayObject.filterArea.contains(point.x, point.y)) { + hitTestOrder = Infinity; + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow pixi to completly ignore and bypass checking the displayObjects children. + if (displayObject.interactiveChildren) { + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + + var child = children[i]; + + var hitChild = this._processInteractive(point, child, hitTestOrder, interactiveParent); + // time to get recursive.. if this function will return if something is hit.. + if (hitChild) { + hit = hitChild; + hitTestOrder = hitChild; + } + } + } + + + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children has already been hit! + if (hitTestOrder < displayObject.displayOrder) { + if (gameofbombs) { + //gameofbombs version + if (displayObject.hitArea && displayObject.isRaycastPossible) { + if (displayObject.containsPoint(point)) { + hit = displayObject.displayOrder; + } + } + } else { + //pixi v4 + if (displayObject.hitArea) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hit = displayObject.displayOrder; + } + } + else if (displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = displayObject.displayOrder; + } + } + } + } + + if (displayObject.interactive) { + this._queueAdd(displayObject, hit); + } + } + + return hit; + + }, + + /** + * This function is provides a neat way of crawling through the scene graph and running a specified function on all interactive objects it finds. + * It will also take care of hit testing the interactive objects and passes the hit across in the function. + * + * @param {PIXI.Point} point the point that is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject the displayObject that will be hit test (recursively crawls its children) + * @param {boolean} hitTest this indicates if the objects inside should be hit test against the point + * @param {Function} func the function that will be called on each interactive object. The displayObject and hit will be passed to the function + * @private + * @return {boolean} returns true if the displayObject hit the point + */ + processInteractive: function (point, displayObject, func, hitTest) { + this._startInteractionProcess(); + this._processInteractive(point, displayObject, hitTest ? 0 : Infinity, false); + this._finishInteractionProcess(func); + }, + + _startInteractionProcess: function () { + //move it to constructor + this._eventDisplayOrder = 1; + if (!this._queue) { + //move it to constructor + this._queue = [[], []]; + } + this._queue[0].length = 0; + this._queue[1].length = 0; + }, + + _queueAdd: function (displayObject, order) { + var queue = this._queue; + if (order < this._eventDisplayOrder) { + queue[0].push(displayObject); + } else { + if (order > this._eventDisplayOrder) { + this._eventDisplayOrder = order; + var q = queue[1]; + for (var i = 0; i < q.length; i++) { + queue[0].push(q[i]); + } + queue[1].length = 0; + } + queue[1].push(displayObject); + } + }, + + /** + * + * @param {Function} func the function that will be called on each interactive object. The displayObject and hit will be passed to the function + */ + _finishInteractionProcess: function (func) { + var queue = this._queue; + var q = queue[0]; + var i; + for (i = 0; i < q.length; i++) { + func(q[i], false); + } + q = queue[1]; + for (i = 0; i < q.length; i++) { + func(q[i], true); + } + } +}; + +module.exports = InteractionManagerMixin; + +},{}],8:[function(require,module,exports){ +/** + * @mixin + */ +var SystemRendererMixin = { + /** + * @private + * @type {number} + */ + _lastDisplayOrder: 0, + + /** + * gets new display order for container/displayobject + */ + incDisplayOrder: function() { + return ++this._lastDisplayOrder; + } +}; + +module.exports = SystemRendererMixin; + +},{}],9:[function(require,module,exports){ +/** + * @mixin + */ +var WebGLRendererMixin = { + _oldRender: PIXI.WebGLRenderer.prototype.render, + render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!renderTexture) { + this._lastDisplayOrder = 0; + } + this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform); + } +}; + +module.exports = WebGLRendererMixin; + +},{}],10:[function(require,module,exports){ +var plugin = { + DisplayGroup: require('./DisplayGroup'), + DisplayList: require('./DisplayList'), + Const: require('./Const'), + DisplayObjectMixin: require('./DisplayObjectMixin'), + ContainerMixin: require('./ContainerMixin'), + SystemRendererMixin: require('./SystemRendererMixin'), + WebGLRendererMixin: require('./WebGLRendererMixin'), + CanvasRendererMixin: require('./CanvasRendererMixin'), + InteractionManagerMixin: require('./InteractionManagerMixin') +}; + +var pluginMixin = { + DisplayGroup: plugin.DisplayGroup, + DisplayList: plugin.DisplayList +}; + +Object.assign(pluginMixin, plugin.Const); + +Object.assign(PIXI.DisplayObject.prototype, plugin.DisplayObjectMixin); + +Object.assign(PIXI.Container.prototype, plugin.ContainerMixin); + +Object.assign(PIXI.WebGLRenderer.prototype, plugin.SystemRendererMixin, plugin.WebGLRendererMixin); + +Object.assign(PIXI.CanvasRenderer.prototype, plugin.SystemRendererMixin, plugin.CanvasRendererMixin); + +Object.assign(PIXI.interaction.InteractionManager.prototype, plugin.InteractionManagerMixin); + +Object.assign(PIXI, pluginMixin); + +module.exports = plugin; + +},{"./CanvasRendererMixin":1,"./Const":2,"./ContainerMixin":3,"./DisplayGroup":4,"./DisplayList":5,"./DisplayObjectMixin":6,"./InteractionManagerMixin":7,"./SystemRendererMixin":8,"./WebGLRendererMixin":9}]},{},[10]) + + +//# sourceMappingURL=pixi-display.js.map diff --git a/js/pixi-display/v2/pixi-display.js b/js/pixi-display/v2/pixi-display.js new file mode 100644 index 0000000..683dde7 --- /dev/null +++ b/js/pixi-display/v2/pixi-display.js @@ -0,0 +1,734 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o b.zOrder) { + return -1; + } + return a.updateOrder - b.updateOrder; +}; + +/** + * clears temporary variables + */ +DisplayGroup.prototype.clear = function () { + var list = this.computedChildren; + for (var i = 0; i < list.length; i++) { + var children = list[i].displayChildren; + if (children && children.length > 0) { + for (var j = 0; j < children.length; j++) { + children[j].displayParent = null; + } + children.length = 0; + } + list[i].displayParent = null; + } + list.length = 0; + this.currentDisplayList = null; + this.currentIndex = 0; +}; + +/** + * used only by displayList before sorting takes place + * @param container {PIXI.DisplayObject} + */ +DisplayGroup.prototype.add = function (displayObject) { + displayObject.displayOrder = this.computedChildren.length; + this.emit('add', displayObject); + this.computedChildren.push(displayObject); +}; + +/** + * Called after all childrens are computed + */ +DisplayGroup.prototype.update = function () { + this.emit('update'); + if (this.enableSort && this.computedChildren.length > 1) { + this.computedChildren.sort(DisplayGroup.compareZOrder); + } +}; + +},{}],5:[function(require,module,exports){ +var EventEmitter = PIXI.utils.EventEmitter, + Const = require('./Const'), + DisplayGroup = require('./DisplayGroup'); +/** + * A component for container, sorts all children inside according to their displayGroups + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +function DisplayList() { + EventEmitter.call(this); + /** + * Children that were rendered in last run + * @type {Array} + */ + this.displayGroups = []; + + this.container = null; + + /** + * how many elements were rendered by display list last time + * also it is used to generate updateOrder for them + * @type {number} + */ + this.totalElements = 0; + + this.defaultDisplayGroup = new DisplayGroup(0, false); +} + +DisplayList.prototype = Object.create(EventEmitter.prototype); +DisplayList.prototype.constructor = DisplayList; +module.exports = DisplayList; + +/** + * clears all display lists that were used in last rendering session + * please clear it when you stop using this displayList, otherwise you may have problems with GC in some cases + */ +DisplayList.prototype.clear = function () { + var list = this.displayGroups; + for (var i = 0; i < list.length; i++) { + list[i].clear(); + } + list.length = 0; + this.totalElements = 0; + this.container = null; +}; + +/** + * alias for clear() + * please call it if you stop using this displayList + */ +DisplayList.prototype.destroy = function () { + this.clear(); +}; + +DisplayList.compareZIndex = function (a, b) { + if (a.zIndex !== b.zIndex) { + return a.zIndex - b.zIndex; + } + return a.currentIndex - b.currentIndex; +}; + +/** + * + * @param displayObject {PIXI.DisplayObject} container that we are adding to displaylist + * @param parent {PIXI.Container} it is not direct parent, but some of ancestors + * @private + */ +DisplayList.prototype._addRecursive = function (container, parent) { + if (!container.visible || !container.renderable) { + return; + } + var groups = this.displayGroups; + var group = parent.displayGroup; + + container.updateOrder = this.totalElements++; + if (container.displayGroup) { + group = container.displayGroup; + if (!group.currentDisplayList) { + group.currentDisplayList = this; + group.currentIndex = groups.length; + groups.push(group); + } + group.add(container); + + container.displayParent = container; + } else { + container.displayParent = parent; + if (!parent.displayChildren) { + parent.displayChildren = []; + } + parent.displayChildren.push(container); + } + + if (container.displayFlag !== Const.DISPLAY_FLAG.MANUAL_CONTAINER) { + var children = container.children; + if (children && children.length > 0) { + if (container._mask || container._filters && container._filters.length || container.displayList) { + container.displayFlag = Const.DISPLAY_FLAG.AUTO_CONTAINER; + } else { + container.displayFlag = Const.DISPLAY_FLAG.AUTO_CHILDREN; + for (var i = 0; i < children.length; i++) { + this._addRecursive(children[i], container.displayParent); + } + } + } else { + container.displayFlag = Const.DISPLAY_FLAG.AUTO_OBJECT; + } + } +}; + +/** + * Called from container that owns this display list + * @param parentContainer + */ +DisplayList.prototype.update = function (parentContainer) { + this.clear(); + var tempGroup = parentContainer.displayGroup; + this.displayGroups.push(this.defaultDisplayGroup); + this.defaultDisplayGroup.add(parentContainer); + + this.container = parentContainer; + var children = parentContainer.children; + var i; + for (i = 0; i < children.length; i++) { + this._addRecursive(children[i], parentContainer); + } + var groups = this.displayGroups; + groups.sort(DisplayList.compareZIndex); + for (i = 0; i < groups.length; i++) { + groups[i].currentIndex = i; + groups[i].update(); + } + this.emit('afterUpdate'); +}; + +/** + * renders container with webgl context + * @param parentContainer + * @param renderer + */ +DisplayList.prototype.renderWebGL = function (parentContainer, renderer) { + var groups = this.displayGroups; + for (var i = 0; i < groups.length; i++) { + var group = groups[i]; + var list = group.computedChildren; + for (var j = 0; j < list.length; j++) { + var container = list[j]; + if (container.displayFlag) { + container.renderWebGL(renderer); + } else { + container.displayOrder = renderer.incDisplayOrder(); + container._renderWebGL(renderer); + var children = container.displayChildren; + if (children && children.length) { + for (var k = 0; k < children.length; k++) { + var child = children[k]; + child.displayOrder = renderer.incDisplayOrder(); + if (child.displayFlag) { + child.renderWebGL(renderer); + } else { + child._renderWebGL(renderer); + } + } + } + } + } + } +}; + +/** + * renders container with canvas2d context + * @param parentContainer + * @param renderer + */ +DisplayList.prototype.renderCanvas = function (parentContainer, renderer) { + var groups = this.displayGroups; + for (var i = 0; i < groups.length; i++) { + var group = groups[i]; + var list = group.computedChildren; + for (var j = 0; j < list.length; j++) { + var container = list[j]; + if (container.displayFlag) { + container.renderCanvas(renderer); + } else { + container.displayOrder = renderer.incDisplayOrder(); + container._renderCanvas(renderer); + var children = container.displayChildren; + if (children && children.length) { + for (var k = 0; k < children.length; k++) { + var child = children[k]; + child.displayOrder = renderer.incDisplayOrder(); + if (child.displayFlag) { + child.renderCanvas(renderer); + } else { + child._renderCanvas(renderer); + } + } + } + } + } + } +}; + +},{"./Const":2,"./DisplayGroup":4}],6:[function(require,module,exports){ +var Const = require('./Const'); + +/** + * @mixin + */ +var DisplayObjectMixin = { + /** + * please specify it to handle zOrder and zIndex + * @type {PIXI.DisplayGroup} + */ + displayGroup: null, + + /** + * calculated inside displayList. Can be set to manual mode + * @type {number} + */ + displayFlag: Const.DISPLAY_FLAG.AUTO_CHILDREN, + + /** + * calculated inside displayList. Cleared on displayList.clear() + * Equal to 'this' if displayGroup is specified + * @type {PIXI.Container} + */ + displayParent: null, + + /** + * zOrder is distance between screen and object. Objects with largest zOrder will appear first in their DisplayGroup + * @type {number} + */ + zOrder: 0, + + /** + * updateOrder is calculated by DisplayList, it is required for sorting inside DisplayGroup + * @type {number} + */ + updateOrder: 0 +}; + +module.exports = DisplayObjectMixin; + +},{"./Const":2}],7:[function(require,module,exports){ +//TODO: add maxDisplayOrder for displayObjects and use it to speed up the interaction here + +var gameofbombs = !!PIXI.Camera2d; + +/** + * @mixin + */ +var InteractionManagerMixin = { + /** + * This is private recursive copy of processInteractive + */ + _processInteractive: function (point, displayObject, hitTestOrder, interactive) { + if (!displayObject || !displayObject.visible) { + return false; + } + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + var hit = 0, + interactiveParent = interactive = displayObject.interactive || interactive; + + + // if the displayobject has a hitArea, then it does not need to hitTest children. + if (displayObject.hitArea) { + interactiveParent = false; + } + + // it has a mask! Then lets hit test that before continuing.. + if (hitTestOrder < Infinity && displayObject._mask) { + if (!displayObject._mask.containsPoint(point)) { + hitTestOrder = Infinity; + } + } + + // it has a filterArea! Same as mask but easier, its a rectangle + if (hitTestOrder < Infinity && displayObject.filterArea) { + if (!displayObject.filterArea.contains(point.x, point.y)) { + hitTestOrder = Infinity; + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow pixi to completly ignore and bypass checking the displayObjects children. + if (displayObject.interactiveChildren) { + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + + var child = children[i]; + + var hitChild = this._processInteractive(point, child, hitTestOrder, interactiveParent); + // time to get recursive.. if this function will return if something is hit.. + if (hitChild) { + hit = hitChild; + hitTestOrder = hitChild; + } + } + } + + + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children has already been hit! + if (hitTestOrder < displayObject.displayOrder) { + if (gameofbombs) { + //gameofbombs version + if (displayObject.hitArea && displayObject.isRaycastPossible) { + if (displayObject.containsPoint(point)) { + hit = displayObject.displayOrder; + } + } + } else { + //pixi v4 + if (displayObject.hitArea) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hit = displayObject.displayOrder; + } + } + else if (displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = displayObject.displayOrder; + } + } + } + } + + if (displayObject.interactive) { + this._queueAdd(displayObject, hit); + } + } + + return hit; + + }, + + /** + * This function is provides a neat way of crawling through the scene graph and running a specified function on all interactive objects it finds. + * It will also take care of hit testing the interactive objects and passes the hit across in the function. + * + * @param {PIXI.Point} point the point that is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject the displayObject that will be hit test (recursively crawls its children) + * @param {boolean} hitTest this indicates if the objects inside should be hit test against the point + * @param {Function} func the function that will be called on each interactive object. The displayObject and hit will be passed to the function + * @private + * @return {boolean} returns true if the displayObject hit the point + */ + processInteractive: function (point, displayObject, func, hitTest) { + this._startInteractionProcess(); + this._processInteractive(point, displayObject, hitTest ? 0 : Infinity, false); + this._finishInteractionProcess(func); + }, + + _startInteractionProcess: function () { + //move it to constructor + this._eventDisplayOrder = 1; + if (!this._queue) { + //move it to constructor + this._queue = [[], []]; + } + this._queue[0].length = 0; + this._queue[1].length = 0; + }, + + _queueAdd: function (displayObject, order) { + var queue = this._queue; + if (order < this._eventDisplayOrder) { + queue[0].push(displayObject); + } else { + if (order > this._eventDisplayOrder) { + this._eventDisplayOrder = order; + var q = queue[1]; + for (var i = 0; i < q.length; i++) { + queue[0].push(q[i]); + } + queue[1].length = 0; + } + queue[1].push(displayObject); + } + }, + + /** + * + * @param {Function} func the function that will be called on each interactive object. The displayObject and hit will be passed to the function + */ + _finishInteractionProcess: function (func) { + var queue = this._queue; + var q = queue[0]; + var i; + for (i = 0; i < q.length; i++) { + func(q[i], false); + } + q = queue[1]; + for (i = 0; i < q.length; i++) { + func(q[i], true); + } + } +}; + +module.exports = InteractionManagerMixin; + +},{}],8:[function(require,module,exports){ +/** + * @mixin + */ +var SystemRendererMixin = { + /** + * @private + * @type {number} + */ + _lastDisplayOrder: 0, + + /** + * gets new display order for container/displayobject + */ + incDisplayOrder: function() { + return ++this._lastDisplayOrder; + } +}; + +module.exports = SystemRendererMixin; + +},{}],9:[function(require,module,exports){ +/** + * @mixin + */ +var WebGLRendererMixin = { + _oldRender: PIXI.WebGLRenderer.prototype.render, + render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!renderTexture) { + this._lastDisplayOrder = 0; + } + this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform); + } +}; + +module.exports = WebGLRendererMixin; + +},{}],10:[function(require,module,exports){ +var plugin = { + DisplayGroup: require('./DisplayGroup'), + DisplayList: require('./DisplayList'), + Const: require('./Const'), + DisplayObjectMixin: require('./DisplayObjectMixin'), + ContainerMixin: require('./ContainerMixin'), + SystemRendererMixin: require('./SystemRendererMixin'), + WebGLRendererMixin: require('./WebGLRendererMixin'), + CanvasRendererMixin: require('./CanvasRendererMixin'), + InteractionManagerMixin: require('./InteractionManagerMixin') +}; + +var pluginMixin = { + DisplayGroup: plugin.DisplayGroup, + DisplayList: plugin.DisplayList +}; + +Object.assign(pluginMixin, plugin.Const); + +Object.assign(PIXI.DisplayObject.prototype, plugin.DisplayObjectMixin); + +Object.assign(PIXI.Container.prototype, plugin.ContainerMixin); + +Object.assign(PIXI.WebGLRenderer.prototype, plugin.SystemRendererMixin, plugin.WebGLRendererMixin); + +Object.assign(PIXI.CanvasRenderer.prototype, plugin.SystemRendererMixin, plugin.CanvasRendererMixin); + +Object.assign(PIXI.interaction.InteractionManager.prototype, plugin.InteractionManagerMixin); + +Object.assign(PIXI, pluginMixin); + +module.exports = plugin; + +},{"./CanvasRendererMixin":1,"./Const":2,"./ContainerMixin":3,"./DisplayGroup":4,"./DisplayList":5,"./DisplayObjectMixin":6,"./InteractionManagerMixin":7,"./SystemRendererMixin":8,"./WebGLRendererMixin":9}]},{},[10]) + + +//# sourceMappingURL=pixi-display.js.map diff --git a/js/pixi-display/v3/pixi-display.js b/js/pixi-display/v3/pixi-display.js new file mode 100644 index 0000000..683dde7 --- /dev/null +++ b/js/pixi-display/v3/pixi-display.js @@ -0,0 +1,734 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o b.zOrder) { + return -1; + } + return a.updateOrder - b.updateOrder; +}; + +/** + * clears temporary variables + */ +DisplayGroup.prototype.clear = function () { + var list = this.computedChildren; + for (var i = 0; i < list.length; i++) { + var children = list[i].displayChildren; + if (children && children.length > 0) { + for (var j = 0; j < children.length; j++) { + children[j].displayParent = null; + } + children.length = 0; + } + list[i].displayParent = null; + } + list.length = 0; + this.currentDisplayList = null; + this.currentIndex = 0; +}; + +/** + * used only by displayList before sorting takes place + * @param container {PIXI.DisplayObject} + */ +DisplayGroup.prototype.add = function (displayObject) { + displayObject.displayOrder = this.computedChildren.length; + this.emit('add', displayObject); + this.computedChildren.push(displayObject); +}; + +/** + * Called after all childrens are computed + */ +DisplayGroup.prototype.update = function () { + this.emit('update'); + if (this.enableSort && this.computedChildren.length > 1) { + this.computedChildren.sort(DisplayGroup.compareZOrder); + } +}; + +},{}],5:[function(require,module,exports){ +var EventEmitter = PIXI.utils.EventEmitter, + Const = require('./Const'), + DisplayGroup = require('./DisplayGroup'); +/** + * A component for container, sorts all children inside according to their displayGroups + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +function DisplayList() { + EventEmitter.call(this); + /** + * Children that were rendered in last run + * @type {Array} + */ + this.displayGroups = []; + + this.container = null; + + /** + * how many elements were rendered by display list last time + * also it is used to generate updateOrder for them + * @type {number} + */ + this.totalElements = 0; + + this.defaultDisplayGroup = new DisplayGroup(0, false); +} + +DisplayList.prototype = Object.create(EventEmitter.prototype); +DisplayList.prototype.constructor = DisplayList; +module.exports = DisplayList; + +/** + * clears all display lists that were used in last rendering session + * please clear it when you stop using this displayList, otherwise you may have problems with GC in some cases + */ +DisplayList.prototype.clear = function () { + var list = this.displayGroups; + for (var i = 0; i < list.length; i++) { + list[i].clear(); + } + list.length = 0; + this.totalElements = 0; + this.container = null; +}; + +/** + * alias for clear() + * please call it if you stop using this displayList + */ +DisplayList.prototype.destroy = function () { + this.clear(); +}; + +DisplayList.compareZIndex = function (a, b) { + if (a.zIndex !== b.zIndex) { + return a.zIndex - b.zIndex; + } + return a.currentIndex - b.currentIndex; +}; + +/** + * + * @param displayObject {PIXI.DisplayObject} container that we are adding to displaylist + * @param parent {PIXI.Container} it is not direct parent, but some of ancestors + * @private + */ +DisplayList.prototype._addRecursive = function (container, parent) { + if (!container.visible || !container.renderable) { + return; + } + var groups = this.displayGroups; + var group = parent.displayGroup; + + container.updateOrder = this.totalElements++; + if (container.displayGroup) { + group = container.displayGroup; + if (!group.currentDisplayList) { + group.currentDisplayList = this; + group.currentIndex = groups.length; + groups.push(group); + } + group.add(container); + + container.displayParent = container; + } else { + container.displayParent = parent; + if (!parent.displayChildren) { + parent.displayChildren = []; + } + parent.displayChildren.push(container); + } + + if (container.displayFlag !== Const.DISPLAY_FLAG.MANUAL_CONTAINER) { + var children = container.children; + if (children && children.length > 0) { + if (container._mask || container._filters && container._filters.length || container.displayList) { + container.displayFlag = Const.DISPLAY_FLAG.AUTO_CONTAINER; + } else { + container.displayFlag = Const.DISPLAY_FLAG.AUTO_CHILDREN; + for (var i = 0; i < children.length; i++) { + this._addRecursive(children[i], container.displayParent); + } + } + } else { + container.displayFlag = Const.DISPLAY_FLAG.AUTO_OBJECT; + } + } +}; + +/** + * Called from container that owns this display list + * @param parentContainer + */ +DisplayList.prototype.update = function (parentContainer) { + this.clear(); + var tempGroup = parentContainer.displayGroup; + this.displayGroups.push(this.defaultDisplayGroup); + this.defaultDisplayGroup.add(parentContainer); + + this.container = parentContainer; + var children = parentContainer.children; + var i; + for (i = 0; i < children.length; i++) { + this._addRecursive(children[i], parentContainer); + } + var groups = this.displayGroups; + groups.sort(DisplayList.compareZIndex); + for (i = 0; i < groups.length; i++) { + groups[i].currentIndex = i; + groups[i].update(); + } + this.emit('afterUpdate'); +}; + +/** + * renders container with webgl context + * @param parentContainer + * @param renderer + */ +DisplayList.prototype.renderWebGL = function (parentContainer, renderer) { + var groups = this.displayGroups; + for (var i = 0; i < groups.length; i++) { + var group = groups[i]; + var list = group.computedChildren; + for (var j = 0; j < list.length; j++) { + var container = list[j]; + if (container.displayFlag) { + container.renderWebGL(renderer); + } else { + container.displayOrder = renderer.incDisplayOrder(); + container._renderWebGL(renderer); + var children = container.displayChildren; + if (children && children.length) { + for (var k = 0; k < children.length; k++) { + var child = children[k]; + child.displayOrder = renderer.incDisplayOrder(); + if (child.displayFlag) { + child.renderWebGL(renderer); + } else { + child._renderWebGL(renderer); + } + } + } + } + } + } +}; + +/** + * renders container with canvas2d context + * @param parentContainer + * @param renderer + */ +DisplayList.prototype.renderCanvas = function (parentContainer, renderer) { + var groups = this.displayGroups; + for (var i = 0; i < groups.length; i++) { + var group = groups[i]; + var list = group.computedChildren; + for (var j = 0; j < list.length; j++) { + var container = list[j]; + if (container.displayFlag) { + container.renderCanvas(renderer); + } else { + container.displayOrder = renderer.incDisplayOrder(); + container._renderCanvas(renderer); + var children = container.displayChildren; + if (children && children.length) { + for (var k = 0; k < children.length; k++) { + var child = children[k]; + child.displayOrder = renderer.incDisplayOrder(); + if (child.displayFlag) { + child.renderCanvas(renderer); + } else { + child._renderCanvas(renderer); + } + } + } + } + } + } +}; + +},{"./Const":2,"./DisplayGroup":4}],6:[function(require,module,exports){ +var Const = require('./Const'); + +/** + * @mixin + */ +var DisplayObjectMixin = { + /** + * please specify it to handle zOrder and zIndex + * @type {PIXI.DisplayGroup} + */ + displayGroup: null, + + /** + * calculated inside displayList. Can be set to manual mode + * @type {number} + */ + displayFlag: Const.DISPLAY_FLAG.AUTO_CHILDREN, + + /** + * calculated inside displayList. Cleared on displayList.clear() + * Equal to 'this' if displayGroup is specified + * @type {PIXI.Container} + */ + displayParent: null, + + /** + * zOrder is distance between screen and object. Objects with largest zOrder will appear first in their DisplayGroup + * @type {number} + */ + zOrder: 0, + + /** + * updateOrder is calculated by DisplayList, it is required for sorting inside DisplayGroup + * @type {number} + */ + updateOrder: 0 +}; + +module.exports = DisplayObjectMixin; + +},{"./Const":2}],7:[function(require,module,exports){ +//TODO: add maxDisplayOrder for displayObjects and use it to speed up the interaction here + +var gameofbombs = !!PIXI.Camera2d; + +/** + * @mixin + */ +var InteractionManagerMixin = { + /** + * This is private recursive copy of processInteractive + */ + _processInteractive: function (point, displayObject, hitTestOrder, interactive) { + if (!displayObject || !displayObject.visible) { + return false; + } + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + var hit = 0, + interactiveParent = interactive = displayObject.interactive || interactive; + + + // if the displayobject has a hitArea, then it does not need to hitTest children. + if (displayObject.hitArea) { + interactiveParent = false; + } + + // it has a mask! Then lets hit test that before continuing.. + if (hitTestOrder < Infinity && displayObject._mask) { + if (!displayObject._mask.containsPoint(point)) { + hitTestOrder = Infinity; + } + } + + // it has a filterArea! Same as mask but easier, its a rectangle + if (hitTestOrder < Infinity && displayObject.filterArea) { + if (!displayObject.filterArea.contains(point.x, point.y)) { + hitTestOrder = Infinity; + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow pixi to completly ignore and bypass checking the displayObjects children. + if (displayObject.interactiveChildren) { + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + + var child = children[i]; + + var hitChild = this._processInteractive(point, child, hitTestOrder, interactiveParent); + // time to get recursive.. if this function will return if something is hit.. + if (hitChild) { + hit = hitChild; + hitTestOrder = hitChild; + } + } + } + + + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children has already been hit! + if (hitTestOrder < displayObject.displayOrder) { + if (gameofbombs) { + //gameofbombs version + if (displayObject.hitArea && displayObject.isRaycastPossible) { + if (displayObject.containsPoint(point)) { + hit = displayObject.displayOrder; + } + } + } else { + //pixi v4 + if (displayObject.hitArea) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hit = displayObject.displayOrder; + } + } + else if (displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = displayObject.displayOrder; + } + } + } + } + + if (displayObject.interactive) { + this._queueAdd(displayObject, hit); + } + } + + return hit; + + }, + + /** + * This function is provides a neat way of crawling through the scene graph and running a specified function on all interactive objects it finds. + * It will also take care of hit testing the interactive objects and passes the hit across in the function. + * + * @param {PIXI.Point} point the point that is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject the displayObject that will be hit test (recursively crawls its children) + * @param {boolean} hitTest this indicates if the objects inside should be hit test against the point + * @param {Function} func the function that will be called on each interactive object. The displayObject and hit will be passed to the function + * @private + * @return {boolean} returns true if the displayObject hit the point + */ + processInteractive: function (point, displayObject, func, hitTest) { + this._startInteractionProcess(); + this._processInteractive(point, displayObject, hitTest ? 0 : Infinity, false); + this._finishInteractionProcess(func); + }, + + _startInteractionProcess: function () { + //move it to constructor + this._eventDisplayOrder = 1; + if (!this._queue) { + //move it to constructor + this._queue = [[], []]; + } + this._queue[0].length = 0; + this._queue[1].length = 0; + }, + + _queueAdd: function (displayObject, order) { + var queue = this._queue; + if (order < this._eventDisplayOrder) { + queue[0].push(displayObject); + } else { + if (order > this._eventDisplayOrder) { + this._eventDisplayOrder = order; + var q = queue[1]; + for (var i = 0; i < q.length; i++) { + queue[0].push(q[i]); + } + queue[1].length = 0; + } + queue[1].push(displayObject); + } + }, + + /** + * + * @param {Function} func the function that will be called on each interactive object. The displayObject and hit will be passed to the function + */ + _finishInteractionProcess: function (func) { + var queue = this._queue; + var q = queue[0]; + var i; + for (i = 0; i < q.length; i++) { + func(q[i], false); + } + q = queue[1]; + for (i = 0; i < q.length; i++) { + func(q[i], true); + } + } +}; + +module.exports = InteractionManagerMixin; + +},{}],8:[function(require,module,exports){ +/** + * @mixin + */ +var SystemRendererMixin = { + /** + * @private + * @type {number} + */ + _lastDisplayOrder: 0, + + /** + * gets new display order for container/displayobject + */ + incDisplayOrder: function() { + return ++this._lastDisplayOrder; + } +}; + +module.exports = SystemRendererMixin; + +},{}],9:[function(require,module,exports){ +/** + * @mixin + */ +var WebGLRendererMixin = { + _oldRender: PIXI.WebGLRenderer.prototype.render, + render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!renderTexture) { + this._lastDisplayOrder = 0; + } + this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform); + } +}; + +module.exports = WebGLRendererMixin; + +},{}],10:[function(require,module,exports){ +var plugin = { + DisplayGroup: require('./DisplayGroup'), + DisplayList: require('./DisplayList'), + Const: require('./Const'), + DisplayObjectMixin: require('./DisplayObjectMixin'), + ContainerMixin: require('./ContainerMixin'), + SystemRendererMixin: require('./SystemRendererMixin'), + WebGLRendererMixin: require('./WebGLRendererMixin'), + CanvasRendererMixin: require('./CanvasRendererMixin'), + InteractionManagerMixin: require('./InteractionManagerMixin') +}; + +var pluginMixin = { + DisplayGroup: plugin.DisplayGroup, + DisplayList: plugin.DisplayList +}; + +Object.assign(pluginMixin, plugin.Const); + +Object.assign(PIXI.DisplayObject.prototype, plugin.DisplayObjectMixin); + +Object.assign(PIXI.Container.prototype, plugin.ContainerMixin); + +Object.assign(PIXI.WebGLRenderer.prototype, plugin.SystemRendererMixin, plugin.WebGLRendererMixin); + +Object.assign(PIXI.CanvasRenderer.prototype, plugin.SystemRendererMixin, plugin.CanvasRendererMixin); + +Object.assign(PIXI.interaction.InteractionManager.prototype, plugin.InteractionManagerMixin); + +Object.assign(PIXI, pluginMixin); + +module.exports = plugin; + +},{"./CanvasRendererMixin":1,"./Const":2,"./ContainerMixin":3,"./DisplayGroup":4,"./DisplayList":5,"./DisplayObjectMixin":6,"./InteractionManagerMixin":7,"./SystemRendererMixin":8,"./WebGLRendererMixin":9}]},{},[10]) + + +//# sourceMappingURL=pixi-display.js.map diff --git a/js/pixi-display/v4/pixi-display.js b/js/pixi-display/v4/pixi-display.js new file mode 100644 index 0000000..86bf30e --- /dev/null +++ b/js/pixi-display/v4/pixi-display.js @@ -0,0 +1,459 @@ +PIXI.DISPLAY_FLAG = { + AUTO_CHILDREN: 0, + AUTO_CONTAINER: 1, + AUTO_OBJECT: 2, + MANUAL_CONTAINER: 3 +}; +var WebGLRenderer = PIXI.WebGLRenderer; +var CanvasRenderer = PIXI.CanvasRenderer; +Object.assign(PIXI.Container.prototype, { + displayList: null, + displayChildren: null, + displayParent: null, + updateTransform: function () { + if (!this.visible) { + return; + } + this.containerUpdateTransform(); + if (this.displayList) { + this.displayList.update(this); + } + }, + renderCanvas: function (renderer) { + if (!this.visible) { + this.displayOrder = 0; + return; + } + this.displayOrder = renderer.incDisplayOrder(); + if (this.worldAlpha <= 0 || !this.renderable) { + return; + } + if (this.displayList) { + this.displayList.renderCanvas(this, renderer); + return; + } + this.containerRenderCanvas(renderer); + }, + renderWebGL: function (renderer) { + if (!this.visible) { + this.displayOrder = 0; + return; + } + this.displayOrder = renderer.incDisplayOrder(); + if (this.worldAlpha <= 0 || !this.renderable) { + return; + } + if (this.displayList) { + this.displayList.renderWebGL(this, renderer); + return; + } + this.containerRenderWebGL(renderer); + }, + containerRenderWebGL: PIXI.Container.prototype.renderWebGL, + containerRenderCanvas: PIXI.Container.prototype.renderCanvas +}); +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var pixi_display; +(function (pixi_display) { + var utils = PIXI.utils; + var DisplayGroup = (function (_super) { + __extends(DisplayGroup, _super); + function DisplayGroup(zIndex, sorting) { + _super.call(this); + this.currentIndex = 0; + this.zIndex = 0; + this.enableSort = false; + this.computedChildren = []; + this.currentDisplayList = null; + this.currentIndex = 0; + this.zIndex = zIndex || 0; + this.enableSort = !!sorting; + if (typeof sorting === 'function') { + this.on('add', sorting); + } + } + DisplayGroup.compareZOrder = function (a, b) { + if (a.zOrder < b.zOrder) { + return 1; + } + if (a.zOrder > b.zOrder) { + return -1; + } + return a.updateOrder - b.updateOrder; + }; + ; + DisplayGroup.prototype.clear = function () { + var list = this.computedChildren; + for (var i = 0; i < list.length; i++) { + var children = list[i].displayChildren; + if (children && children.length > 0) { + for (var j = 0; j < children.length; j++) { + children[j].displayParent = null; + } + children.length = 0; + } + list[i].displayParent = null; + } + list.length = 0; + this.currentDisplayList = null; + this.currentIndex = 0; + }; + ; + DisplayGroup.prototype.add = function (displayObject) { + displayObject.displayOrder = this.computedChildren.length; + this.emit('add', displayObject); + this.computedChildren.push(displayObject); + }; + ; + DisplayGroup.prototype.update = function () { + this.emit('update'); + if (this.enableSort && this.computedChildren.length > 1) { + this.computedChildren.sort(DisplayGroup.compareZOrder); + } + }; + ; + DisplayGroup.prototype.renderWebGL = function (parentContainer, renderer) { + var list = this.computedChildren; + for (var j = 0; j < list.length; j++) { + var container = list[j]; + if (container.displayFlag) { + container.renderWebGL(renderer); + } + else { + container.displayOrder = renderer.incDisplayOrder(); + container._renderWebGL(renderer); + var children = container.displayChildren; + if (children && children.length) { + for (var k = 0; k < children.length; k++) { + var child = children[k]; + child.displayOrder = renderer.incDisplayOrder(); + if (child.displayFlag) { + child.renderWebGL(renderer); + } + else { + child._renderWebGL(renderer); + } + } + } + } + } + }; + ; + DisplayGroup.prototype.renderCanvas = function (parentContainer, renderer) { + var list = this.computedChildren; + for (var j = 0; j < list.length; j++) { + var container = list[j]; + if (container.displayFlag) { + container.renderCanvas(renderer); + } + else { + container.displayOrder = renderer.incDisplayOrder(); + container._renderCanvas(renderer); + var children = container.displayChildren; + if (children && children.length) { + for (var k = 0; k < children.length; k++) { + var child = children[k]; + child.displayOrder = renderer.incDisplayOrder(); + if (child.displayFlag) { + child.renderCanvas(renderer); + } + else { + child._renderCanvas(renderer); + } + } + } + } + } + }; + ; + return DisplayGroup; + }(utils.EventEmitter)); + pixi_display.DisplayGroup = DisplayGroup; +})(pixi_display || (pixi_display = {})); +var pixi_display; +(function (pixi_display) { + var utils = PIXI.utils; + var DisplayList = (function (_super) { + __extends(DisplayList, _super); + function DisplayList() { + _super.call(this); + this.container = null; + this.totalElements = 0; + this.displayGroups = []; + this.defaultDisplayGroup = new pixi_display.DisplayGroup(0, false); + } + DisplayList.prototype.clear = function () { + var list = this.displayGroups; + for (var i = 0; i < list.length; i++) { + list[i].clear(); + } + list.length = 0; + this.totalElements = 0; + this.container = null; + }; + ; + DisplayList.prototype.destroy = function () { + this.clear(); + }; + ; + DisplayList.compareZIndex = function (a, b) { + if (a.zIndex !== b.zIndex) { + return a.zIndex - b.zIndex; + } + return a.currentIndex - b.currentIndex; + }; + ; + DisplayList.prototype._addRecursive = function (displayObject, parent) { + var container = displayObject; + if (!container.visible || !container.renderable) { + return; + } + var groups = this.displayGroups; + var group = parent.displayGroup; + container.updateOrder = this.totalElements++; + if (container.displayGroup) { + group = container.displayGroup; + if (!group.currentDisplayList) { + group.currentDisplayList = this; + group.currentIndex = groups.length; + groups.push(group); + } + group.add(container); + container.displayParent = container; + } + else { + container.displayParent = parent; + if (!parent.displayChildren) { + parent.displayChildren = []; + } + parent.displayChildren.push(container); + } + if (container.displayFlag !== PIXI.DISPLAY_FLAG.MANUAL_CONTAINER) { + var children = container.children; + if (children && children.length > 0) { + if (container._mask || container._filters && container._filters.length || container.displayList) { + container.displayFlag = PIXI.DISPLAY_FLAG.AUTO_CONTAINER; + } + else { + container.displayFlag = PIXI.DISPLAY_FLAG.AUTO_CHILDREN; + for (var i = 0; i < children.length; i++) { + this._addRecursive(children[i], container.displayParent); + } + } + } + else { + container.displayFlag = PIXI.DISPLAY_FLAG.AUTO_OBJECT; + } + } + }; + ; + DisplayList.prototype.update = function (parentContainer) { + this.clear(); + var tempGroup = parentContainer.displayGroup; + this.displayGroups.push(this.defaultDisplayGroup); + this.defaultDisplayGroup.add(parentContainer); + this.container = parentContainer; + var children = parentContainer.children; + var i = 0; + for (i = 0; i < children.length; i++) { + this._addRecursive(children[i], parentContainer); + } + var groups = this.displayGroups; + groups.sort(DisplayList.compareZIndex); + for (i = 0; i < groups.length; i++) { + groups[i].currentIndex = i; + groups[i].update(); + } + this.emit('afterUpdate'); + }; + ; + DisplayList.prototype.renderWebGL = function (parentContainer, renderer) { + parentContainer.displayFlag = PIXI.DISPLAY_FLAG.AUTO_CHILDREN; + var groups = this.displayGroups; + for (var i = 0; i < groups.length; i++) { + var group = groups[i]; + group.renderWebGL(parentContainer, renderer); + } + }; + ; + DisplayList.prototype.renderCanvas = function (parentContainer, renderer) { + var groups = this.displayGroups; + for (var i = 0; i < groups.length; i++) { + var group = groups[i]; + group.renderCanvas(parentContainer, renderer); + } + }; + ; + return DisplayList; + }(utils.EventEmitter)); + pixi_display.DisplayList = DisplayList; +})(pixi_display || (pixi_display = {})); +Object.assign(PIXI.DisplayObject.prototype, { + displayGroup: null, + displayFlag: PIXI.DISPLAY_FLAG.AUTO_CHILDREN, + displayParent: null, + zOrder: 0, + updateOrder: 0, + displayOrder: 0 +}); +var pixi_display; +(function (pixi_display) { + var InteractionManager = PIXI.interaction.InteractionManager; + Object.assign(InteractionManager.prototype, { + _queue: [[], []], + _displayProcessInteractive: function (point, displayObject, hitTestOrder, interactive) { + if (!displayObject || !displayObject.visible) { + return 0; + } + var hit = 0, interactiveParent = interactive = displayObject.interactive || interactive; + if (displayObject.hitArea) { + interactiveParent = false; + } + var mask = displayObject._mask; + if (hitTestOrder < Infinity && mask) { + if (!mask.containsPoint(point)) { + hitTestOrder = Infinity; + } + } + if (hitTestOrder < Infinity && displayObject.filterArea) { + if (!displayObject.filterArea.contains(point.x, point.y)) { + hitTestOrder = Infinity; + } + } + var children = displayObject.children; + if (displayObject.interactiveChildren && children) { + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + var hitChild = this._displayProcessInteractive(point, child, hitTestOrder, interactiveParent); + if (hitChild) { + if (!child.parent) { + continue; + } + hit = hitChild; + hitTestOrder = hitChild; + } + } + } + if (interactive) { + if (hitTestOrder < displayObject.displayOrder) { + if (displayObject.hitArea) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hit = displayObject.displayOrder; + } + } + else if (displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = displayObject.displayOrder; + } + } + } + if (displayObject.interactive) { + this._queueAdd(displayObject, hit); + } + } + return hit; + }, + processInteractive: function (strangeStuff, displayObject, func, hitTest, interactive) { + var interactionEvent = null; + var point = null; + if (strangeStuff.data && + strangeStuff.data.global) { + interactionEvent = strangeStuff; + point = interactionEvent.data.global; + } + else { + point = strangeStuff; + } + this._startInteractionProcess(); + this._displayProcessInteractive(point, displayObject, hitTest ? 0 : Infinity, false); + this._finishInteractionProcess(interactionEvent, func); + }, + _startInteractionProcess: function () { + this._eventDisplayOrder = 1; + if (!this._queue) { + this._queue = [[], []]; + } + this._queue[0].length = 0; + this._queue[1].length = 0; + }, + _queueAdd: function (displayObject, order) { + var queue = this._queue; + if (order < this._eventDisplayOrder) { + queue[0].push(displayObject); + } + else { + if (order > this._eventDisplayOrder) { + this._eventDisplayOrder = order; + var q = queue[1]; + for (var i = 0; i < q.length; i++) { + queue[0].push(q[i]); + } + queue[1].length = 0; + } + queue[1].push(displayObject); + } + }, + _finishInteractionProcess: function (event, func) { + var queue = this._queue; + var q = queue[0]; + var i = 0; + for (; i < q.length; i++) { + if (event) { + func(event, q[i], false); + } + else { + func(q[i], false); + } + } + q = queue[1]; + for (i = 0; i < q.length; i++) { + if (event) { + if (!event.target) { + event.target = q[i]; + } + func(event, q[i], true); + } + else { + func(q[i], true); + } + } + } + }); +})(pixi_display || (pixi_display = {})); +Object.assign(WebGLRenderer.prototype, { + _lastDisplayOrder: 0, + incDisplayOrder: function () { + return ++this._lastDisplayOrder; + }, + _oldRender: WebGLRenderer.prototype.render, + render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!renderTexture) { + this._lastDisplayOrder = 0; + } + this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform); + } +}); +Object.assign(CanvasRenderer.prototype, { + _lastDisplayOrder: 0, + incDisplayOrder: function () { + return ++this._lastDisplayOrder; + }, + _oldRender: CanvasRenderer.prototype.render, + render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!renderTexture) { + this._lastDisplayOrder = 0; + } + this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform); + } +}); +Object.assign(PIXI, { + display: pixi_display, + DisplayGroup: pixi_display.DisplayGroup, + DisplayList: pixi_display.DisplayList +}); +//# sourceMappingURL=pixi-display.js.map \ No newline at end of file diff --git a/js/pixi-filters/.DS_Store b/js/pixi-filters/.DS_Store new file mode 100644 index 0000000..7804106 Binary files /dev/null and b/js/pixi-filters/.DS_Store differ diff --git a/js/pixi-filters/2.6.0c0/pixi-filters.js b/js/pixi-filters/2.6.0c0/pixi-filters.js new file mode 100644 index 0000000..37e64f7 --- /dev/null +++ b/js/pixi-filters/2.6.0c0/pixi-filters.js @@ -0,0 +1,9 @@ +/*! + * pixi-filters - v2.6.0 + * Compiled Thu, 29 Mar 2018 22:30:19 UTC + * + * pixi-filters is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +var __filters=function(e,t){"use strict";var n="attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}",r="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform float gamma;\nuniform float contrast;\nuniform float saturation;\nuniform float brightness;\nuniform float red;\nuniform float green;\nuniform float blue;\nuniform float alpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (c.a > 0.0) {\n c.rgb /= c.a;\n\n vec3 rgb = pow(c.rgb, vec3(1. / gamma));\n rgb = mix(vec3(.5), mix(vec3(dot(vec3(.2125, .7154, .0721), rgb)), rgb, saturation), contrast);\n rgb.r *= red;\n rgb.g *= green;\n rgb.b *= blue;\n c.rgb = rgb * brightness;\n\n c.rgb *= c.a;\n }\n\n gl_FragColor = c * alpha;\n}\n",o=function(e){function t(t){e.call(this,n,r),Object.assign(this,{gamma:1,saturation:1,contrast:1,brightness:1,red:1,green:1,blue:1,alpha:1},t)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.apply=function(e,t,n,r){this.uniforms.gamma=Math.max(this.gamma,1e-4),this.uniforms.saturation=this.saturation,this.uniforms.contrast=this.contrast,this.uniforms.brightness=this.brightness,this.uniforms.red=this.red,this.uniforms.green=this.green,this.uniforms.blue=this.blue,this.uniforms.alpha=this.alpha,e.applyFilter(this,t,n,r)},t}(t.Filter),i=n,l="\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 uOffset;\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n\n // Sample top left pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y + uOffset.y));\n\n // Sample top right pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y + uOffset.y));\n\n // Sample bottom right pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y - uOffset.y));\n\n // Sample bottom left pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y - uOffset.y));\n\n // Average\n color *= 0.25;\n\n gl_FragColor = color;\n}",s="\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 uOffset;\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n\n // Sample top left pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y + uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample top right pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y + uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample bottom right pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y - uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample bottom left pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y - uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Average\n color *= 0.25;\n\n gl_FragColor = color;\n}\n",a=function(e){function n(n,r,o){void 0===n&&(n=4),void 0===r&&(r=3),void 0===o&&(o=!1),e.call(this,i,o?s:l),this.uniforms.uOffset=new Float32Array(2),this._pixelSize=new t.Point,this.pixelSize=1,this._clamp=o,this._kernels=null,Array.isArray(n)?this.kernels=n:(this._blur=n,this.quality=r)}e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n;var r={kernels:{configurable:!0},clamp:{configurable:!0},pixelSize:{configurable:!0},quality:{configurable:!0},blur:{configurable:!0}};return n.prototype.apply=function(e,t,n,r){var o,i=this.pixelSize.x/t.size.width,l=this.pixelSize.y/t.size.height;if(1===this._quality||0===this._blur)o=this._kernels[0]+.5,this.uniforms.uOffset[0]=o*i,this.uniforms.uOffset[1]=o*l,e.applyFilter(this,t,n,r);else{for(var s,a=e.getRenderTarget(!0),u=t,c=a,f=this._quality-1,h=0;h0)for(var r=e,o=e/t,i=1;i0?(this._kernels=e,this._quality=e.length,this._blur=Math.max.apply(Math,e)):(this._kernels=[0],this._quality=1)},r.clamp.get=function(){return this._clamp},r.pixelSize.set=function(e){"number"==typeof e?(this._pixelSize.x=e,this._pixelSize.y=e):Array.isArray(e)?(this._pixelSize.x=e[0],this._pixelSize.y=e[1]):e instanceof t.Point?(this._pixelSize.x=e.x,this._pixelSize.y=e.y):(this._pixelSize.x=1,this._pixelSize.y=1)},r.pixelSize.get=function(){return this._pixelSize},r.quality.get=function(){return this._quality},r.quality.set=function(e){this._quality=Math.max(1,Math.round(e)),this._generateKernels()},r.blur.get=function(){return this._blur},r.blur.set=function(e){this._blur=e,this._generateKernels()},Object.defineProperties(n.prototype,r),n}(t.Filter),u=n,c="\nuniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform float threshold;\n\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n // A simple & fast algorithm for getting brightness.\n // It's inaccuracy , but good enought for this feature.\n float _max = max(max(color.r, color.g), color.b);\n float _min = min(min(color.r, color.g), color.b);\n float brightness = (_max + _min) * 0.5;\n\n if(brightness > threshold) {\n gl_FragColor = color;\n } else {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);\n }\n}\n",f=function(e){function t(t){void 0===t&&(t=.5),e.call(this,u,c),this.threshold=t}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={threshold:{configurable:!0}};return n.threshold.get=function(){return this.uniforms.threshold},n.threshold.set=function(e){this.uniforms.threshold=e},Object.defineProperties(t.prototype,n),t}(t.Filter),h="uniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D bloomTexture;\nuniform float bloomScale;\nuniform float brightness;\n\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord);\n color.rgb *= brightness;\n vec4 bloomColor = vec4(texture2D(bloomTexture, vTextureCoord).rgb, 0.0);\n bloomColor.rgb *= bloomScale;\n gl_FragColor = color + bloomColor;\n}\n",p=function(e){function n(n){e.call(this,u,h),"number"==typeof n&&(n={threshold:n}),n=Object.assign({threshold:.5,bloomScale:1,brightness:1,kernels:null,blur:8,quality:4,pixelSize:1,resolution:t.settings.RESOLUTION},n),this.bloomScale=n.bloomScale,this.brightness=n.brightness;var r=n.kernels,o=n.blur,i=n.quality,l=n.pixelSize,s=n.resolution;this._extractFilter=new f(n.threshold),this._extractFilter.resolution=s,this._blurFilter=r?new a(r):new a(o,i),this.pixelSize=l,this.resolution=s}e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n;var r={resolution:{configurable:!0},threshold:{configurable:!0},kernels:{configurable:!0},blur:{configurable:!0},quality:{configurable:!0},pixelSize:{configurable:!0}};return n.prototype.apply=function(e,t,n,r,o){var i=e.getRenderTarget(!0);this._extractFilter.apply(e,t,i,!0,o);var l=e.getRenderTarget(!0);this._blurFilter.apply(e,i,l,!0,o),this.uniforms.bloomScale=this.bloomScale,this.uniforms.brightness=this.brightness,this.uniforms.bloomTexture=l,e.applyFilter(this,t,n,r),e.returnRenderTarget(l),e.returnRenderTarget(i)},r.resolution.get=function(){return this._resolution},r.resolution.set=function(e){this._resolution=e,this._extractFilter&&(this._extractFilter.resolution=e),this._blurFilter&&(this._blurFilter.resolution=e)},r.threshold.get=function(){return this._extractFilter.threshold},r.threshold.set=function(e){this._extractFilter.threshold=e},r.kernels.get=function(){return this._blurFilter.kernels},r.kernels.set=function(e){this._blurFilter.kernels=e},r.blur.get=function(){return this._blurFilter.blur},r.blur.set=function(e){this._blurFilter.blur=e},r.quality.get=function(){return this._blurFilter.quality},r.quality.set=function(e){this._blurFilter.quality=e},r.pixelSize.get=function(){return this._blurFilter.pixelSize},r.pixelSize.set=function(e){this._blurFilter.pixelSize=e},Object.defineProperties(n.prototype,r),n}(t.Filter),d=n,m="varying vec2 vTextureCoord;\n\nuniform vec4 filterArea;\nuniform float pixelSize;\nuniform sampler2D uSampler;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 pixelate(vec2 coord, vec2 size)\n{\n return floor( coord / size ) * size;\n}\n\nvec2 getMod(vec2 coord, vec2 size)\n{\n return mod( coord , size) / size;\n}\n\nfloat character(float n, vec2 p)\n{\n p = floor(p*vec2(4.0, -4.0) + 2.5);\n if (clamp(p.x, 0.0, 4.0) == p.x && clamp(p.y, 0.0, 4.0) == p.y)\n {\n if (int(mod(n/exp2(p.x + 5.0*p.y), 2.0)) == 1) return 1.0;\n }\n return 0.0;\n}\n\nvoid main()\n{\n vec2 coord = mapCoord(vTextureCoord);\n\n // get the rounded color..\n vec2 pixCoord = pixelate(coord, vec2(pixelSize));\n pixCoord = unmapCoord(pixCoord);\n\n vec4 color = texture2D(uSampler, pixCoord);\n\n // determine the character to use\n float gray = (color.r + color.g + color.b) / 3.0;\n\n float n = 65536.0; // .\n if (gray > 0.2) n = 65600.0; // :\n if (gray > 0.3) n = 332772.0; // *\n if (gray > 0.4) n = 15255086.0; // o\n if (gray > 0.5) n = 23385164.0; // &\n if (gray > 0.6) n = 15252014.0; // 8\n if (gray > 0.7) n = 13199452.0; // @\n if (gray > 0.8) n = 11512810.0; // #\n\n // get the mod..\n vec2 modd = getMod(coord, vec2(pixelSize));\n\n gl_FragColor = color * character( n, vec2(-1.0) + modd * 2.0);\n\n}",g=function(e){function t(t){void 0===t&&(t=8),e.call(this,d,m),this.size=t}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={size:{configurable:!0}};return n.size.get=function(){return this.uniforms.pixelSize},n.size.set=function(e){this.uniforms.pixelSize=e},Object.defineProperties(t.prototype,n),t}(t.Filter),v=n,x="precision mediump float;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform float transformX;\nuniform float transformY;\nuniform vec3 lightColor;\nuniform float lightAlpha;\nuniform vec3 shadowColor;\nuniform float shadowAlpha;\n\nvoid main(void) {\n vec2 transform = vec2(1.0 / filterArea) * vec2(transformX, transformY);\n vec4 color = texture2D(uSampler, vTextureCoord);\n float light = texture2D(uSampler, vTextureCoord - transform).a;\n float shadow = texture2D(uSampler, vTextureCoord + transform).a;\n\n color.rgb = mix(color.rgb, lightColor, clamp((color.a - light) * lightAlpha, 0.0, 1.0));\n color.rgb = mix(color.rgb, shadowColor, clamp((color.a - shadow) * shadowAlpha, 0.0, 1.0));\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n",y=function(e){function n(t){void 0===t&&(t={}),e.call(this,v,x),this.uniforms.lightColor=new Float32Array(3),this.uniforms.shadowColor=new Float32Array(3),t=Object.assign({rotation:45,thickness:2,lightColor:16777215,lightAlpha:.7,shadowColor:0,shadowAlpha:.7},t),this.rotation=t.rotation,this.thickness=t.thickness,this.lightColor=t.lightColor,this.lightAlpha=t.lightAlpha,this.shadowColor=t.shadowColor,this.shadowAlpha=t.shadowAlpha}e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n;var r={rotation:{configurable:!0},thickness:{configurable:!0},lightColor:{configurable:!0},lightAlpha:{configurable:!0},shadowColor:{configurable:!0},shadowAlpha:{configurable:!0}};return n.prototype._updateTransform=function(){this.uniforms.transformX=this._thickness*Math.cos(this._angle),this.uniforms.transformY=this._thickness*Math.sin(this._angle)},r.rotation.get=function(){return this._angle/t.DEG_TO_RAD},r.rotation.set=function(e){this._angle=e*t.DEG_TO_RAD,this._updateTransform()},r.thickness.get=function(){return this._thickness},r.thickness.set=function(e){this._thickness=e,this._updateTransform()},r.lightColor.get=function(){return t.utils.rgb2hex(this.uniforms.lightColor)},r.lightColor.set=function(e){t.utils.hex2rgb(e,this.uniforms.lightColor)},r.lightAlpha.get=function(){return this.uniforms.lightAlpha},r.lightAlpha.set=function(e){this.uniforms.lightAlpha=e},r.shadowColor.get=function(){return t.utils.rgb2hex(this.uniforms.shadowColor)},r.shadowColor.set=function(e){t.utils.hex2rgb(e,this.uniforms.shadowColor)},r.shadowAlpha.get=function(){return this.uniforms.shadowAlpha},r.shadowAlpha.set=function(e){this.uniforms.shadowAlpha=e},Object.defineProperties(n.prototype,r),n}(t.Filter),_=t.filters,b=_.BlurXFilter,C=_.BlurYFilter,S=_.AlphaFilter,F=function(e){function n(n,r,o,i){var l,s;void 0===n&&(n=2),void 0===r&&(r=4),void 0===o&&(o=t.settings.RESOLUTION),void 0===i&&(i=5),e.call(this),"number"==typeof n?(l=n,s=n):n instanceof t.Point?(l=n.x,s=n.y):Array.isArray(n)&&(l=n[0],s=n[1]),this.blurXFilter=new b(l,r,o,i),this.blurYFilter=new C(s,r,o,i),this.blurYFilter.blendMode=t.BLEND_MODES.SCREEN,this.defaultFilter=new S}e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n;var r={blur:{configurable:!0},blurX:{configurable:!0},blurY:{configurable:!0}};return n.prototype.apply=function(e,t,n){var r=e.getRenderTarget(!0);this.defaultFilter.apply(e,t,n),this.blurXFilter.apply(e,t,r),this.blurYFilter.apply(e,r,n),e.returnRenderTarget(r)},r.blur.get=function(){return this.blurXFilter.blur},r.blur.set=function(e){this.blurXFilter.blur=this.blurYFilter.blur=e},r.blurX.get=function(){return this.blurXFilter.blur},r.blurX.set=function(e){this.blurXFilter.blur=e},r.blurY.get=function(){return this.blurYFilter.blur},r.blurY.set=function(e){this.blurYFilter.blur=e},Object.defineProperties(n.prototype,r),n}(t.Filter),z=n,A="uniform float radius;\nuniform float strength;\nuniform vec2 center;\nuniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\n\nvoid main()\n{\n vec2 coord = vTextureCoord * filterArea.xy;\n coord -= center * dimensions.xy;\n float distance = length(coord);\n if (distance < radius) {\n float percent = distance / radius;\n if (strength > 0.0) {\n coord *= mix(1.0, smoothstep(0.0, radius / distance, percent), strength * 0.75);\n } else {\n coord *= mix(1.0, pow(percent, 1.0 + strength * 0.75) * radius / distance, 1.0 - percent);\n }\n }\n coord += center * dimensions.xy;\n coord /= filterArea.xy;\n vec2 clampedCoord = clamp(coord, filterClamp.xy, filterClamp.zw);\n vec4 color = texture2D(uSampler, clampedCoord);\n if (coord != clampedCoord) {\n color *= max(0.0, 1.0 - length(coord - clampedCoord));\n }\n\n gl_FragColor = color;\n}\n",w=function(e){function t(t,n,r){e.call(this,z,A),this.uniforms.dimensions=new Float32Array(2),this.center=t||[.5,.5],this.radius=n||100,this.strength=r||1}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={radius:{configurable:!0},strength:{configurable:!0},center:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.dimensions[0]=t.sourceFrame.width,this.uniforms.dimensions[1]=t.sourceFrame.height,e.applyFilter(this,t,n,r)},n.radius.get=function(){return this.uniforms.radius},n.radius.set=function(e){this.uniforms.radius=e},n.strength.get=function(){return this.uniforms.strength},n.strength.set=function(e){this.uniforms.strength=e},n.center.get=function(){return this.uniforms.center},n.center.set=function(e){this.uniforms.center=e},Object.defineProperties(t.prototype,n),t}(t.Filter),T=n,D="\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform sampler2D colorMap;\n\nuniform float _mix;\nuniform float _size;\nuniform float _sliceSize;\nuniform float _slicePixelSize;\nuniform float _sliceInnerSize;\n\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord.xy);\n\n float sliceIndex = color.b * (_size - 1.0);\n float zSlice0 = floor(sliceIndex);\n float zSlice1 = ceil(sliceIndex);\n\n float xOffset = _slicePixelSize * 0.5 + color.r * _sliceInnerSize;\n float s0 = xOffset + zSlice0 * _sliceSize;\n float s1 = xOffset + zSlice1 * _sliceSize;\n vec4 slice0Color = texture2D(colorMap, vec2(s0, color.g));\n vec4 slice1Color = texture2D(colorMap, vec2(s1, color.g));\n vec4 adjusted = mix(slice0Color, slice1Color, fract(sliceIndex));\n\n gl_FragColor = mix(color, adjusted, _mix);\n}\n",O=function(e){function n(t,n,r){void 0===n&&(n=!1),void 0===r&&(r=1),e.call(this,T,D),this._size=0,this._sliceSize=0,this._slicePixelSize=0,this._sliceInnerSize=0,this._scaleMode=null,this._nearest=!1,this.nearest=n,this.mix=r,this.colorMap=t}e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n;var r={colorSize:{configurable:!0},colorMap:{configurable:!0},nearest:{configurable:!0}};return n.prototype.apply=function(e,t,n,r){this.uniforms._mix=this.mix,e.applyFilter(this,t,n,r)},r.colorSize.get=function(){return this._size},r.colorMap.get=function(){return this._colorMap},r.colorMap.set=function(e){e instanceof t.Texture||(e=t.Texture.from(e)),e&&e.baseTexture&&(e.baseTexture.scaleMode=this._scaleMode,e.baseTexture.mipmap=!1,this._size=e.height,this._sliceSize=1/this._size,this._slicePixelSize=this._sliceSize/this._size,this._sliceInnerSize=this._slicePixelSize*(this._size-1),this.uniforms._size=this._size,this.uniforms._sliceSize=this._sliceSize,this.uniforms._slicePixelSize=this._slicePixelSize,this.uniforms._sliceInnerSize=this._sliceInnerSize,this.uniforms.colorMap=e),this._colorMap=e},r.nearest.get=function(){return this._nearest},r.nearest.set=function(e){this._nearest=e,this._scaleMode=e?t.SCALE_MODES.NEAREST:t.SCALE_MODES.LINEAR;var n=this._colorMap;n&&n.baseTexture&&(n.baseTexture._glTextures={},n.baseTexture.scaleMode=this._scaleMode,n.baseTexture.mipmap=!1,n._updateID++,n.baseTexture.emit("update",n.baseTexture))},n.prototype.updateColorMap=function(){var e=this._colorMap;e&&e.baseTexture&&(e._updateID++,e.baseTexture.emit("update",e.baseTexture),this.colorMap=e)},n.prototype.destroy=function(t){this._colorMap&&this._colorMap.destroy(t),e.prototype.destroy.call(this)},Object.defineProperties(n.prototype,r),n}(t.Filter),P=n,M="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec3 originalColor;\nuniform vec3 newColor;\nuniform float epsilon;\nvoid main(void) {\n vec4 currentColor = texture2D(uSampler, vTextureCoord);\n vec3 colorDiff = originalColor - (currentColor.rgb / max(currentColor.a, 0.0000000001));\n float colorDistance = length(colorDiff);\n float doReplace = step(colorDistance, epsilon);\n gl_FragColor = vec4(mix(currentColor.rgb, (newColor + colorDiff) * currentColor.a, doReplace), currentColor.a);\n}\n",R=function(e){function n(t,n,r){void 0===t&&(t=16711680),void 0===n&&(n=0),void 0===r&&(r=.4),e.call(this,P,M),this.uniforms.originalColor=new Float32Array(3),this.uniforms.newColor=new Float32Array(3),this.originalColor=t,this.newColor=n,this.epsilon=r}e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n;var r={originalColor:{configurable:!0},newColor:{configurable:!0},epsilon:{configurable:!0}};return r.originalColor.set=function(e){var n=this.uniforms.originalColor;"number"==typeof e?(t.utils.hex2rgb(e,n),this._originalColor=e):(n[0]=e[0],n[1]=e[1],n[2]=e[2],this._originalColor=t.utils.rgb2hex(n))},r.originalColor.get=function(){return this._originalColor},r.newColor.set=function(e){var n=this.uniforms.newColor;"number"==typeof e?(t.utils.hex2rgb(e,n),this._newColor=e):(n[0]=e[0],n[1]=e[1],n[2]=e[2],this._newColor=t.utils.rgb2hex(n))},r.newColor.get=function(){return this._newColor},r.epsilon.set=function(e){this.uniforms.epsilon=e},r.epsilon.get=function(){return this.uniforms.epsilon},Object.defineProperties(n.prototype,r),n}(t.Filter),j=n,L="precision mediump float;\n\nvarying mediump vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec2 texelSize;\nuniform float matrix[9];\n\nvoid main(void)\n{\n vec4 c11 = texture2D(uSampler, vTextureCoord - texelSize); // top left\n vec4 c12 = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y - texelSize.y)); // top center\n vec4 c13 = texture2D(uSampler, vec2(vTextureCoord.x + texelSize.x, vTextureCoord.y - texelSize.y)); // top right\n\n vec4 c21 = texture2D(uSampler, vec2(vTextureCoord.x - texelSize.x, vTextureCoord.y)); // mid left\n vec4 c22 = texture2D(uSampler, vTextureCoord); // mid center\n vec4 c23 = texture2D(uSampler, vec2(vTextureCoord.x + texelSize.x, vTextureCoord.y)); // mid right\n\n vec4 c31 = texture2D(uSampler, vec2(vTextureCoord.x - texelSize.x, vTextureCoord.y + texelSize.y)); // bottom left\n vec4 c32 = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y + texelSize.y)); // bottom center\n vec4 c33 = texture2D(uSampler, vTextureCoord + texelSize); // bottom right\n\n gl_FragColor =\n c11 * matrix[0] + c12 * matrix[1] + c13 * matrix[2] +\n c21 * matrix[3] + c22 * matrix[4] + c23 * matrix[5] +\n c31 * matrix[6] + c32 * matrix[7] + c33 * matrix[8];\n\n gl_FragColor.a = c22.a;\n}\n",k=function(e){function t(t,n,r){e.call(this,j,L),this.uniforms.texelSize=new Float32Array(9),this.matrix=t,this.width=n,this.height=r}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={matrix:{configurable:!0},width:{configurable:!0},height:{configurable:!0}};return n.matrix.get=function(){return this.uniforms.matrix},n.matrix.set=function(e){this.uniforms.matrix=new Float32Array(e)},n.width.get=function(){return 1/this.uniforms.texelSize[0]},n.width.set=function(e){this.uniforms.texelSize[0]=1/e},n.height.get=function(){return 1/this.uniforms.texelSize[1]},n.height.set=function(e){this.uniforms.texelSize[1]=1/e},Object.defineProperties(t.prototype,n),t}(t.Filter),I=n,E="precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n float lum = length(texture2D(uSampler, vTextureCoord.xy).rgb);\n\n gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n\n if (lum < 1.00)\n {\n if (mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.75)\n {\n if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.50)\n {\n if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.3)\n {\n if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n}\n",B=function(e){function t(){e.call(this,I,E)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t}(t.Filter),X=n,q="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec2 dimensions;\n\nconst float SQRT_2 = 1.414213;\n\nconst float light = 1.0;\n\nuniform float curvature;\nuniform float lineWidth;\nuniform float lineContrast;\nuniform bool verticalLine;\nuniform float noise;\nuniform float noiseSize;\n\nuniform float vignetting;\nuniform float vignettingAlpha;\nuniform float vignettingBlur;\n\nuniform float seed;\nuniform float time;\n\nfloat rand(vec2 co) {\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main(void)\n{\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n vec2 coord = pixelCoord / dimensions;\n\n vec2 dir = vec2(coord - vec2(0.5, 0.5));\n\n float _c = curvature > 0. ? curvature : 1.;\n float k = curvature > 0. ?(length(dir * dir) * 0.25 * _c * _c + 0.935 * _c) : 1.;\n vec2 uv = dir * k;\n\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n vec3 rgb = gl_FragColor.rgb;\n\n\n if (noise > 0.0 && noiseSize > 0.0)\n {\n pixelCoord.x = floor(pixelCoord.x / noiseSize);\n pixelCoord.y = floor(pixelCoord.y / noiseSize);\n float _noise = rand(pixelCoord * noiseSize * seed) - 0.5;\n rgb += _noise * noise;\n }\n\n if (lineWidth > 0.0) {\n float v = (verticalLine ? uv.x * dimensions.x : uv.y * dimensions.y) * min(1.0, 2.0 / lineWidth ) / _c;\n float j = 1. + cos(v * 1.2 - time) * 0.5 * lineContrast;\n rgb *= j;\n float segment = verticalLine ? mod((dir.x + .5) * dimensions.x, 4.) : mod((dir.y + .5) * dimensions.y, 4.);\n rgb *= 0.99 + ceil(segment) * 0.015;\n }\n\n if (vignetting > 0.0)\n {\n float outter = SQRT_2 - vignetting * SQRT_2;\n float darker = clamp((outter - length(dir) * SQRT_2) / ( 0.00001 + vignettingBlur * SQRT_2), 0.0, 1.0);\n rgb *= darker + (1.0 - darker) * (1.0 - vignettingAlpha);\n }\n\n gl_FragColor.rgb = rgb;\n}\n",N=function(e){function t(t){e.call(this,X,q),this.uniforms.dimensions=new Float32Array(2),this.time=0,this.seed=0,Object.assign(this,{curvature:1,lineWidth:1,lineContrast:.25,verticalLine:!1,noise:0,noiseSize:1,seed:0,vignetting:.3,vignettingAlpha:1,vignettingBlur:.3,time:0},t)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={curvature:{configurable:!0},lineWidth:{configurable:!0},lineContrast:{configurable:!0},verticalLine:{configurable:!0},noise:{configurable:!0},noiseSize:{configurable:!0},vignetting:{configurable:!0},vignettingAlpha:{configurable:!0},vignettingBlur:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.dimensions[0]=t.sourceFrame.width,this.uniforms.dimensions[1]=t.sourceFrame.height,this.uniforms.seed=this.seed,this.uniforms.time=this.time,e.applyFilter(this,t,n,r)},n.curvature.set=function(e){this.uniforms.curvature=e},n.curvature.get=function(){return this.uniforms.curvature},n.lineWidth.set=function(e){this.uniforms.lineWidth=e},n.lineWidth.get=function(){return this.uniforms.lineWidth},n.lineContrast.set=function(e){this.uniforms.lineContrast=e},n.lineContrast.get=function(){return this.uniforms.lineContrast},n.verticalLine.set=function(e){this.uniforms.verticalLine=e},n.verticalLine.get=function(){return this.uniforms.verticalLine},n.noise.set=function(e){this.uniforms.noise=e},n.noise.get=function(){return this.uniforms.noise},n.noiseSize.set=function(e){this.uniforms.noiseSize=e},n.noiseSize.get=function(){return this.uniforms.noiseSize},n.vignetting.set=function(e){this.uniforms.vignetting=e},n.vignetting.get=function(){return this.uniforms.vignetting},n.vignettingAlpha.set=function(e){this.uniforms.vignettingAlpha=e},n.vignettingAlpha.get=function(){return this.uniforms.vignettingAlpha},n.vignettingBlur.set=function(e){this.uniforms.vignettingBlur=e},n.vignettingBlur.get=function(){return this.uniforms.vignettingBlur},Object.defineProperties(t.prototype,n),t}(t.Filter),G=n,K="precision mediump float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform vec4 filterArea;\nuniform sampler2D uSampler;\n\nuniform float angle;\nuniform float scale;\n\nfloat pattern()\n{\n float s = sin(angle), c = cos(angle);\n vec2 tex = vTextureCoord * filterArea.xy;\n vec2 point = vec2(\n c * tex.x - s * tex.y,\n s * tex.x + c * tex.y\n ) * scale;\n return (sin(point.x) * sin(point.y)) * 4.0;\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float average = (color.r + color.g + color.b) / 3.0;\n gl_FragColor = vec4(vec3(average * 10.0 - 5.0 + pattern()), color.a);\n}\n",Y=function(e){function t(t,n){void 0===t&&(t=1),void 0===n&&(n=5),e.call(this,G,K),this.scale=t,this.angle=n}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={scale:{configurable:!0},angle:{configurable:!0}};return n.scale.get=function(){return this.uniforms.scale},n.scale.set=function(e){this.uniforms.scale=e},n.angle.get=function(){return this.uniforms.angle},n.angle.set=function(e){this.uniforms.angle=e},Object.defineProperties(t.prototype,n),t}(t.Filter),W=n,Q="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform vec3 color;\nvoid main(void){\n vec4 sample = texture2D(uSampler, vTextureCoord);\n\n // Un-premultiply alpha before applying the color\n if (sample.a > 0.0) {\n sample.rgb /= sample.a;\n }\n\n // Premultiply alpha again\n sample.rgb = color.rgb * sample.a;\n\n // alpha user alpha\n sample *= alpha;\n\n gl_FragColor = sample;\n}",U=function(e){function n(n){n&&n.constructor!==Object&&(console.warn("DropShadowFilter now uses options instead of (rotation, distance, blur, color, alpha)"),n={rotation:n},void 0!==arguments[1]&&(n.distance=arguments[1]),void 0!==arguments[2]&&(n.blur=arguments[2]),void 0!==arguments[3]&&(n.color=arguments[3]),void 0!==arguments[4]&&(n.alpha=arguments[4])),n=Object.assign({rotation:45,distance:5,color:0,alpha:.5,shadowOnly:!1,kernels:null,blur:2,quality:3,pixelSize:1,resolution:t.settings.RESOLUTION},n),e.call(this);var r=n.kernels,o=n.blur,i=n.quality,l=n.pixelSize,s=n.resolution;this._tintFilter=new t.Filter(W,Q),this._tintFilter.uniforms.color=new Float32Array(4),this._tintFilter.resolution=s,this._blurFilter=r?new a(r):new a(o,i),this.pixelSize=l,this.resolution=s,this.targetTransform=new t.Matrix;var u=n.shadowOnly,c=n.rotation,f=n.distance,h=n.alpha,p=n.color;this.shadowOnly=u,this.rotation=c,this.distance=f,this.alpha=h,this.color=p,this._updatePadding()}e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n;var r={resolution:{configurable:!0},distance:{configurable:!0},rotation:{configurable:!0},alpha:{configurable:!0},color:{configurable:!0},kernels:{configurable:!0},blur:{configurable:!0},quality:{configurable:!0},pixelSize:{configurable:!0}};return n.prototype.apply=function(e,t,n,r){var o=e.getRenderTarget();o.transform=this.targetTransform,this._tintFilter.apply(e,t,o,!0),o.transform=null,this._blurFilter.apply(e,o,n),!0!==this.shadowOnly&&e.applyFilter(this,t,n,r),e.returnRenderTarget(o)},n.prototype._updatePadding=function(){this.padding=this.distance+2*this.blur},n.prototype._updateTargetTransform=function(){this.targetTransform.tx=this.distance*Math.cos(this.angle),this.targetTransform.ty=this.distance*Math.sin(this.angle)},r.resolution.get=function(){return this._resolution},r.resolution.set=function(e){this._resolution=e,this._tintFilter&&(this._tintFilter.resolution=e),this._blurFilter&&(this._blurFilter.resolution=e)},r.distance.get=function(){return this._distance},r.distance.set=function(e){this._distance=e,this._updatePadding(),this._updateTargetTransform()},r.rotation.get=function(){return this.angle/t.DEG_TO_RAD},r.rotation.set=function(e){this.angle=e*t.DEG_TO_RAD,this._updateTargetTransform()},r.alpha.get=function(){return this._tintFilter.uniforms.alpha},r.alpha.set=function(e){this._tintFilter.uniforms.alpha=e},r.color.get=function(){return t.utils.rgb2hex(this._tintFilter.uniforms.color)},r.color.set=function(e){t.utils.hex2rgb(e,this._tintFilter.uniforms.color)},r.kernels.get=function(){return this._blurFilter.kernels},r.kernels.set=function(e){this._blurFilter.kernels=e},r.blur.get=function(){return this._blurFilter.blur},r.blur.set=function(e){this._blurFilter.blur=e,this._updatePadding()},r.quality.get=function(){return this._blurFilter.quality},r.quality.set=function(e){this._blurFilter.quality=e},r.pixelSize.get=function(){return this._blurFilter.pixelSize},r.pixelSize.set=function(e){this._blurFilter.pixelSize=e},Object.defineProperties(n.prototype,r),n}(t.Filter),Z=n,V="precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float strength;\nuniform vec4 filterArea;\n\n\nvoid main(void)\n{\n\tvec2 onePixel = vec2(1.0 / filterArea);\n\n\tvec4 color;\n\n\tcolor.rgb = vec3(0.5);\n\n\tcolor -= texture2D(uSampler, vTextureCoord - onePixel) * strength;\n\tcolor += texture2D(uSampler, vTextureCoord + onePixel) * strength;\n\n\tcolor.rgb = vec3((color.r + color.g + color.b) / 3.0);\n\n\tfloat alpha = texture2D(uSampler, vTextureCoord).a;\n\n\tgl_FragColor = vec4(color.rgb * alpha, alpha);\n}\n",H=function(e){function t(t){void 0===t&&(t=5),e.call(this,Z,V),this.strength=t}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={strength:{configurable:!0}};return n.strength.get=function(){return this.uniforms.strength},n.strength.set=function(e){this.uniforms.strength=e},Object.defineProperties(t.prototype,n),t}(t.Filter),$=n,J="// precision highp float;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\nuniform float aspect;\n\nuniform sampler2D displacementMap;\nuniform float offset;\nuniform float sinDir;\nuniform float cosDir;\nuniform int fillMode;\n\nuniform float seed;\nuniform vec2 red;\nuniform vec2 green;\nuniform vec2 blue;\n\nconst int TRANSPARENT = 0;\nconst int ORIGINAL = 1;\nconst int LOOP = 2;\nconst int CLAMP = 3;\nconst int MIRROR = 4;\n\nvoid main(void)\n{\n vec2 coord = (vTextureCoord * filterArea.xy) / dimensions;\n\n if (coord.x > 1.0 || coord.y > 1.0) {\n return;\n }\n\n float cx = coord.x - 0.5;\n float cy = (coord.y - 0.5) * aspect;\n float ny = (-sinDir * cx + cosDir * cy) / aspect + 0.5;\n\n // displacementMap: repeat\n // ny = ny > 1.0 ? ny - 1.0 : (ny < 0.0 ? 1.0 + ny : ny);\n\n // displacementMap: mirror\n ny = ny > 1.0 ? 2.0 - ny : (ny < 0.0 ? -ny : ny);\n\n vec4 dc = texture2D(displacementMap, vec2(0.5, ny));\n\n float displacement = (dc.r - dc.g) * (offset / filterArea.x);\n\n coord = vTextureCoord + vec2(cosDir * displacement, sinDir * displacement * aspect);\n\n if (fillMode == CLAMP) {\n coord = clamp(coord, filterClamp.xy, filterClamp.zw);\n } else {\n if( coord.x > filterClamp.z ) {\n if (fillMode == ORIGINAL) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n } else if (fillMode == LOOP) {\n coord.x -= filterClamp.z;\n } else if (fillMode == MIRROR) {\n coord.x = filterClamp.z * 2.0 - coord.x;\n } else {\n gl_FragColor = vec4(0., 0., 0., 0.);\n return;\n }\n } else if( coord.x < filterClamp.x ) {\n if (fillMode == ORIGINAL) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n } else if (fillMode == LOOP) {\n coord.x += filterClamp.z;\n } else if (fillMode == MIRROR) {\n coord.x *= -filterClamp.z;\n } else {\n gl_FragColor = vec4(0., 0., 0., 0.);\n return;\n }\n }\n\n if( coord.y > filterClamp.w ) {\n if (fillMode == ORIGINAL) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n } else if (fillMode == LOOP) {\n coord.y -= filterClamp.w;\n } else if (fillMode == MIRROR) {\n coord.y = filterClamp.w * 2.0 - coord.y;\n } else {\n gl_FragColor = vec4(0., 0., 0., 0.);\n return;\n }\n } else if( coord.y < filterClamp.y ) {\n if (fillMode == ORIGINAL) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n } else if (fillMode == LOOP) {\n coord.y += filterClamp.w;\n } else if (fillMode == MIRROR) {\n coord.y *= -filterClamp.w;\n } else {\n gl_FragColor = vec4(0., 0., 0., 0.);\n return;\n }\n }\n }\n\n gl_FragColor.r = texture2D(uSampler, coord + red * (1.0 - seed * 0.4) / filterArea.xy).r;\n gl_FragColor.g = texture2D(uSampler, coord + green * (1.0 - seed * 0.3) / filterArea.xy).g;\n gl_FragColor.b = texture2D(uSampler, coord + blue * (1.0 - seed * 0.2) / filterArea.xy).b;\n gl_FragColor.a = texture2D(uSampler, coord).a;\n}\n",ee=function(e){function n(n){void 0===n&&(n={}),e.call(this,$,J),this.uniforms.dimensions=new Float32Array(2),n=Object.assign({slices:5,offset:100,direction:0,fillMode:0,average:!1,seed:0,red:[0,0],green:[0,0],blue:[0,0],minSize:8,sampleSize:512},n),this.direction=n.direction,this.red=n.red,this.green=n.green,this.blue=n.blue,this.offset=n.offset,this.fillMode=n.fillMode,this.average=n.average,this.seed=n.seed,this.minSize=n.minSize,this.sampleSize=n.sampleSize,this._canvas=document.createElement("canvas"),this._canvas.width=4,this._canvas.height=this.sampleSize,this.texture=t.Texture.fromCanvas(this._canvas,t.SCALE_MODES.NEAREST),this._slices=0,this.slices=n.slices}e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n;var r={sizes:{configurable:!0},offsets:{configurable:!0},slices:{configurable:!0},direction:{configurable:!0},red:{configurable:!0},green:{configurable:!0},blue:{configurable:!0}};return n.prototype.apply=function(e,t,n,r){var o=t.sourceFrame.width,i=t.sourceFrame.height;this.uniforms.dimensions[0]=o,this.uniforms.dimensions[1]=i,this.uniforms.aspect=i/o,this.uniforms.seed=this.seed,this.uniforms.offset=this.offset,this.uniforms.fillMode=this.fillMode,e.applyFilter(this,t,n,r)},n.prototype._randomizeSizes=function(){var e=this._sizes,t=this._slices-1,n=this.sampleSize,r=Math.min(this.minSize/n,.9/this._slices);if(this.average){for(var o=this._slices,i=1,l=0;l0;t--){var n=Math.random()*t>>0,r=e[t];e[t]=e[n],e[n]=r}},n.prototype._randomizeOffsets=function(){for(var e=0;e0?e:0,a=e<0?-e:0;r.fillStyle="rgba("+s+", "+a+", 0, 1)",r.fillRect(0,o>>0,t,l+1>>0),o+=l}n._updateID++,n.baseTexture.emit("update",n.baseTexture),this.uniforms.displacementMap=n},r.sizes.set=function(e){for(var t=Math.min(this._slices,e.length),n=0;nthis._maxColors)throw"Length of replacements ("+o+") exceeds the maximum colors length ("+this._maxColors+")";n[3*o]=-1;for(var i=0;i 0.5) then: 1 - 2 * (1 - dst) * (1 - src)\n return vec3((dst.x <= 0.5) ? (2.0 * src.x * dst.x) : (1.0 - 2.0 * (1.0 - dst.x) * (1.0 - src.x)),\n (dst.y <= 0.5) ? (2.0 * src.y * dst.y) : (1.0 - 2.0 * (1.0 - dst.y) * (1.0 - src.y)),\n (dst.z <= 0.5) ? (2.0 * src.z * dst.z) : (1.0 - 2.0 * (1.0 - dst.z) * (1.0 - src.z)));\n}\n\n\nvoid main()\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n vec3 color = gl_FragColor.rgb;\n\n if (sepia > 0.0)\n {\n float gray = (color.x + color.y + color.z) / 3.0;\n vec3 grayscale = vec3(gray);\n\n color = Overlay(SEPIA_RGB, grayscale);\n\n color = grayscale + sepia * (color - grayscale);\n }\n\n vec2 coord = vTextureCoord * filterArea.xy / dimensions.xy;\n\n if (vignetting > 0.0)\n {\n float outter = SQRT_2 - vignetting * SQRT_2;\n vec2 dir = vec2(vec2(0.5, 0.5) - coord);\n dir.y *= dimensions.y / dimensions.x;\n float darker = clamp((outter - length(dir) * SQRT_2) / ( 0.00001 + vignettingBlur * SQRT_2), 0.0, 1.0);\n color.rgb *= darker + (1.0 - darker) * (1.0 - vignettingAlpha);\n }\n\n if (scratchDensity > seed && scratch != 0.0)\n {\n float phase = seed * 256.0;\n float s = mod(floor(phase), 2.0);\n float dist = 1.0 / scratchDensity;\n float d = distance(coord, vec2(seed * dist, abs(s - seed * dist)));\n if (d < seed * 0.6 + 0.4)\n {\n highp float period = scratchDensity * 10.0;\n\n float xx = coord.x * period + phase;\n float aa = abs(mod(xx, 0.5) * 4.0);\n float bb = mod(floor(xx / 0.5), 2.0);\n float yy = (1.0 - bb) * aa + bb * (2.0 - aa);\n\n float kk = 2.0 * period;\n float dw = scratchWidth / dimensions.x * (0.75 + seed);\n float dh = dw * kk;\n\n float tine = (yy - (2.0 - dh));\n\n if (tine > 0.0) {\n float _sign = sign(scratch);\n\n tine = s * tine / period + scratch + 0.1;\n tine = clamp(tine + 1.0, 0.5 + _sign * 0.5, 1.5 + _sign * 0.5);\n\n color.rgb *= tine;\n }\n }\n }\n\n if (noise > 0.0 && noiseSize > 0.0)\n {\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n pixelCoord.x = floor(pixelCoord.x / noiseSize);\n pixelCoord.y = floor(pixelCoord.y / noiseSize);\n // vec2 d = pixelCoord * noiseSize * vec2(1024.0 + seed * 512.0, 1024.0 - seed * 512.0);\n // float _noise = snoise(d) * 0.5;\n float _noise = rand(pixelCoord * noiseSize * seed) - 0.5;\n color += _noise * noise;\n }\n\n gl_FragColor.rgb = color;\n}\n",ge=function(e){function t(t,n){void 0===n&&(n=0),e.call(this,de,me),this.uniforms.dimensions=new Float32Array(2),"number"==typeof t?(this.seed=t,t=null):this.seed=n,Object.assign(this,{sepia:.3,noise:.3,noiseSize:1,scratch:.5,scratchDensity:.3,scratchWidth:1,vignetting:.3,vignettingAlpha:1,vignettingBlur:.3},t)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={sepia:{configurable:!0},noise:{configurable:!0},noiseSize:{configurable:!0},scratch:{configurable:!0},scratchDensity:{configurable:!0},scratchWidth:{configurable:!0},vignetting:{configurable:!0},vignettingAlpha:{configurable:!0},vignettingBlur:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.dimensions[0]=t.sourceFrame.width,this.uniforms.dimensions[1]=t.sourceFrame.height,this.uniforms.seed=this.seed,e.applyFilter(this,t,n,r)},n.sepia.set=function(e){this.uniforms.sepia=e},n.sepia.get=function(){return this.uniforms.sepia},n.noise.set=function(e){this.uniforms.noise=e},n.noise.get=function(){return this.uniforms.noise},n.noiseSize.set=function(e){this.uniforms.noiseSize=e},n.noiseSize.get=function(){return this.uniforms.noiseSize},n.scratch.set=function(e){this.uniforms.scratch=e},n.scratch.get=function(){return this.uniforms.scratch},n.scratchDensity.set=function(e){this.uniforms.scratchDensity=e},n.scratchDensity.get=function(){return this.uniforms.scratchDensity},n.scratchWidth.set=function(e){this.uniforms.scratchWidth=e},n.scratchWidth.get=function(){return this.uniforms.scratchWidth},n.vignetting.set=function(e){this.uniforms.vignetting=e},n.vignetting.get=function(){return this.uniforms.vignetting},n.vignettingAlpha.set=function(e){this.uniforms.vignettingAlpha=e},n.vignettingAlpha.get=function(){return this.uniforms.vignettingAlpha},n.vignettingBlur.set=function(e){this.uniforms.vignettingBlur=e},n.vignettingBlur.get=function(){return this.uniforms.vignettingBlur},Object.defineProperties(t.prototype,n),t}(t.Filter),ve=n,xe="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 thickness;\nuniform vec4 outlineColor;\nuniform vec4 filterClamp;\n\nconst float DOUBLE_PI = 3.14159265358979323846264 * 2.;\n\nvoid main(void) {\n vec4 ownColor = texture2D(uSampler, vTextureCoord);\n vec4 curColor;\n float maxAlpha = 0.;\n vec2 displaced;\n for (float angle = 0.; angle <= DOUBLE_PI; angle += ${angleStep}) {\n displaced.x = vTextureCoord.x + thickness.x * cos(angle);\n displaced.y = vTextureCoord.y + thickness.y * sin(angle);\n curColor = texture2D(uSampler, clamp(displaced, filterClamp.xy, filterClamp.zw));\n maxAlpha = max(maxAlpha, curColor.a);\n }\n float resultAlpha = max(maxAlpha, ownColor.a);\n gl_FragColor = vec4((ownColor.rgb + outlineColor.rgb * (1. - ownColor.a)) * resultAlpha, resultAlpha);\n}\n",ye=function(e){function n(t,r,o){void 0===t&&(t=1),void 0===r&&(r=0),void 0===o&&(o=.1);var i=Math.max(o*n.MAX_SAMPLES,n.MIN_SAMPLES),l=(2*Math.PI/i).toFixed(7);e.call(this,ve,xe.replace(/\$\{angleStep\}/,l)),this.uniforms.thickness=new Float32Array([0,0]),this.thickness=t,this.uniforms.outlineColor=new Float32Array([0,0,0,1]),this.color=r,this.quality=o}e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n;var r={color:{configurable:!0}};return n.prototype.apply=function(e,t,n,r){this.uniforms.thickness[0]=this.thickness/t.size.width,this.uniforms.thickness[1]=this.thickness/t.size.height,e.applyFilter(this,t,n,r)},r.color.get=function(){return t.utils.rgb2hex(this.uniforms.outlineColor)},r.color.set=function(e){t.utils.hex2rgb(e,this.uniforms.outlineColor)},Object.defineProperties(n.prototype,r),n}(t.Filter);ye.MIN_SAMPLES=1,ye.MAX_SAMPLES=100;var _e=n,be="precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform vec2 size;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 pixelate(vec2 coord, vec2 size)\n{\n\treturn floor( coord / size ) * size;\n}\n\nvoid main(void)\n{\n vec2 coord = mapCoord(vTextureCoord);\n\n coord = pixelate(coord, size);\n\n coord = unmapCoord(coord);\n\n gl_FragColor = texture2D(uSampler, coord);\n}\n",Ce=function(e){function t(t){void 0===t&&(t=10),e.call(this,_e,be),this.size=t}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={size:{configurable:!0}};return n.size.get=function(){return this.uniforms.size},n.size.set=function(e){"number"==typeof e&&(e=[e,e]),this.uniforms.size=e},Object.defineProperties(t.prototype,n),t}(t.Filter),Se=n,Fe="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform float uRadian;\nuniform vec2 uCenter;\nuniform float uRadius;\nuniform int uKernelSize;\n\nconst int MAX_KERNEL_SIZE = 2048;\n\nvoid main(void)\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n if (uKernelSize == 0)\n {\n gl_FragColor = color;\n return;\n }\n\n float aspect = filterArea.y / filterArea.x;\n vec2 center = uCenter.xy / filterArea.xy;\n float gradient = uRadius / filterArea.x * 0.3;\n float radius = uRadius / filterArea.x - gradient * 0.5;\n int k = uKernelSize - 1;\n\n vec2 coord = vTextureCoord;\n vec2 dir = vec2(center - coord);\n float dist = length(vec2(dir.x, dir.y * aspect));\n\n float radianStep = uRadian;\n if (radius >= 0.0 && dist > radius) {\n float delta = dist - radius;\n float gap = gradient;\n float scale = 1.0 - abs(delta / gap);\n if (scale <= 0.0) {\n gl_FragColor = color;\n return;\n }\n radianStep *= scale;\n }\n radianStep /= float(k);\n\n float s = sin(radianStep);\n float c = cos(radianStep);\n mat2 rotationMatrix = mat2(vec2(c, -s), vec2(s, c));\n\n for(int i = 0; i < MAX_KERNEL_SIZE - 1; i++) {\n if (i == k) {\n break;\n }\n\n coord -= center;\n coord.y *= aspect;\n coord = rotationMatrix * coord;\n coord.y /= aspect;\n coord += center;\n\n vec4 sample = texture2D(uSampler, coord);\n\n // switch to pre-multiplied alpha to correctly blur transparent images\n // sample.rgb *= sample.a;\n\n color += sample;\n }\n\n gl_FragColor = color / float(uKernelSize);\n}\n",ze=function(e){function t(t,n,r,o){void 0===t&&(t=0),void 0===n&&(n=[0,0]),void 0===r&&(r=5),void 0===o&&(o=-1),e.call(this,Se,Fe),this._angle=0,this.angle=t,this.center=n,this.kernelSize=r,this.radius=o}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={angle:{configurable:!0},center:{configurable:!0},radius:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.uKernelSize=0!==this._angle?this.kernelSize:0,e.applyFilter(this,t,n,r)},n.angle.set=function(e){this._angle=e,this.uniforms.uRadian=e*Math.PI/180},n.angle.get=function(){return this._angle},n.center.get=function(){return this.uniforms.uCenter},n.center.set=function(e){this.uniforms.uCenter=e},n.radius.get=function(){return this.uniforms.uRadius},n.radius.set=function(e){(e<0||e===1/0)&&(e=-1),this.uniforms.uRadius=e},Object.defineProperties(t.prototype,n),t}(t.Filter),Ae=n,we="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\n\nuniform bool mirror;\nuniform float boundary;\nuniform vec2 amplitude;\nuniform vec2 waveLength;\nuniform vec2 alpha;\nuniform float time;\n\nfloat rand(vec2 co) {\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main(void)\n{\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n vec2 coord = pixelCoord / dimensions;\n\n if (coord.y < boundary) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n\n float k = (coord.y - boundary) / (1. - boundary + 0.0001);\n float areaY = boundary * dimensions.y / filterArea.y;\n float v = areaY + areaY - vTextureCoord.y;\n float y = mirror ? v : vTextureCoord.y;\n\n float _amplitude = ((amplitude.y - amplitude.x) * k + amplitude.x ) / filterArea.x;\n float _waveLength = ((waveLength.y - waveLength.x) * k + waveLength.x) / filterArea.y;\n float _alpha = (alpha.y - alpha.x) * k + alpha.x;\n\n float x = vTextureCoord.x + cos(v * 6.28 / _waveLength - time) * _amplitude;\n x = clamp(x, filterClamp.x, filterClamp.z);\n\n vec4 color = texture2D(uSampler, vec2(x, y));\n\n gl_FragColor = color * _alpha;\n}\n",Te=function(e){function t(t){e.call(this,Ae,we),this.uniforms.amplitude=new Float32Array(2),this.uniforms.waveLength=new Float32Array(2),this.uniforms.alpha=new Float32Array(2),this.uniforms.dimensions=new Float32Array(2),Object.assign(this,{mirror:!0,boundary:.5,amplitude:[0,20],waveLength:[30,100],alpha:[1,1],time:0},t)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={mirror:{configurable:!0},boundary:{configurable:!0},amplitude:{configurable:!0},waveLength:{configurable:!0},alpha:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.dimensions[0]=t.sourceFrame.width,this.uniforms.dimensions[1]=t.sourceFrame.height,this.uniforms.time=this.time,e.applyFilter(this,t,n,r)},n.mirror.set=function(e){this.uniforms.mirror=e},n.mirror.get=function(){return this.uniforms.mirror},n.boundary.set=function(e){this.uniforms.boundary=e},n.boundary.get=function(){return this.uniforms.boundary},n.amplitude.set=function(e){this.uniforms.amplitude[0]=e[0],this.uniforms.amplitude[1]=e[1]},n.amplitude.get=function(){return this.uniforms.amplitude},n.waveLength.set=function(e){this.uniforms.waveLength[0]=e[0],this.uniforms.waveLength[1]=e[1]},n.waveLength.get=function(){return this.uniforms.waveLength},n.alpha.set=function(e){this.uniforms.alpha[0]=e[0],this.uniforms.alpha[1]=e[1]},n.alpha.get=function(){return this.uniforms.alpha},Object.defineProperties(t.prototype,n),t}(t.Filter),De=n,Oe="precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\nuniform vec2 red;\nuniform vec2 green;\nuniform vec2 blue;\n\nvoid main(void)\n{\n gl_FragColor.r = texture2D(uSampler, vTextureCoord + red/filterArea.xy).r;\n gl_FragColor.g = texture2D(uSampler, vTextureCoord + green/filterArea.xy).g;\n gl_FragColor.b = texture2D(uSampler, vTextureCoord + blue/filterArea.xy).b;\n gl_FragColor.a = texture2D(uSampler, vTextureCoord).a;\n}\n",Pe=function(e){function t(t,n,r){void 0===t&&(t=[-10,0]),void 0===n&&(n=[0,10]),void 0===r&&(r=[0,0]),e.call(this,De,Oe),this.red=t,this.green=n,this.blue=r}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={red:{configurable:!0},green:{configurable:!0},blue:{configurable:!0}};return n.red.get=function(){return this.uniforms.red},n.red.set=function(e){this.uniforms.red=e},n.green.get=function(){return this.uniforms.green},n.green.set=function(e){this.uniforms.green=e},n.blue.get=function(){return this.uniforms.blue},n.blue.set=function(e){this.uniforms.blue=e},Object.defineProperties(t.prototype,n),t}(t.Filter),Me=n,Re="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\n\nuniform vec2 center;\n\nuniform float amplitude;\nuniform float wavelength;\n// uniform float power;\nuniform float brightness;\nuniform float speed;\nuniform float radius;\n\nuniform float time;\n\nconst float PI = 3.14159;\n\nvoid main()\n{\n float halfWavelength = wavelength * 0.5 / filterArea.x;\n float maxRadius = radius / filterArea.x;\n float currentRadius = time * speed / filterArea.x;\n\n float fade = 1.0;\n\n if (maxRadius > 0.0) {\n if (currentRadius > maxRadius) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n fade = 1.0 - pow(currentRadius / maxRadius, 2.0);\n }\n\n vec2 dir = vec2(vTextureCoord - center / filterArea.xy);\n dir.y *= filterArea.y / filterArea.x;\n float dist = length(dir);\n\n if (dist <= 0.0 || dist < currentRadius - halfWavelength || dist > currentRadius + halfWavelength) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n\n vec2 diffUV = normalize(dir);\n\n float diff = (dist - currentRadius) / halfWavelength;\n\n float p = 1.0 - pow(abs(diff), 2.0);\n\n // float powDiff = diff * pow(p, 2.0) * ( amplitude * fade );\n float powDiff = 1.25 * sin(diff * PI) * p * ( amplitude * fade );\n\n vec2 offset = diffUV * powDiff / filterArea.xy;\n\n // Do clamp :\n vec2 coord = vTextureCoord + offset;\n vec2 clampedCoord = clamp(coord, filterClamp.xy, filterClamp.zw);\n vec4 color = texture2D(uSampler, clampedCoord);\n if (coord != clampedCoord) {\n color *= max(0.0, 1.0 - length(coord - clampedCoord));\n }\n\n // No clamp :\n // gl_FragColor = texture2D(uSampler, vTextureCoord + offset);\n\n color.rgb *= 1.0 + (brightness - 1.0) * p * fade;\n\n gl_FragColor = color;\n}\n",je=function(e){function t(t,n,r){void 0===t&&(t=[0,0]),void 0===n&&(n={}),void 0===r&&(r=0),e.call(this,Me,Re),this.center=t,Array.isArray(n)&&(console.warn("Deprecated Warning: ShockwaveFilter params Array has been changed to options Object."),n={}),n=Object.assign({amplitude:30,wavelength:160,brightness:1,speed:500,radius:-1},n),this.amplitude=n.amplitude,this.wavelength=n.wavelength,this.brightness=n.brightness,this.speed=n.speed,this.radius=n.radius,this.time=r}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={center:{configurable:!0},amplitude:{configurable:!0},wavelength:{configurable:!0},brightness:{configurable:!0},speed:{configurable:!0},radius:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.time=this.time,e.applyFilter(this,t,n,r)},n.center.get=function(){return this.uniforms.center},n.center.set=function(e){this.uniforms.center=e},n.amplitude.get=function(){return this.uniforms.amplitude},n.amplitude.set=function(e){this.uniforms.amplitude=e},n.wavelength.get=function(){return this.uniforms.wavelength},n.wavelength.set=function(e){this.uniforms.wavelength=e},n.brightness.get=function(){return this.uniforms.brightness},n.brightness.set=function(e){this.uniforms.brightness=e},n.speed.get=function(){return this.uniforms.speed},n.speed.set=function(e){this.uniforms.speed=e},n.radius.get=function(){return this.uniforms.radius},n.radius.set=function(e){this.uniforms.radius=e},Object.defineProperties(t.prototype,n),t}(t.Filter),Le=n,ke="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform sampler2D uLightmap;\nuniform vec4 filterArea;\nuniform vec2 dimensions;\nuniform vec4 ambientColor;\nvoid main() {\n vec4 diffuseColor = texture2D(uSampler, vTextureCoord);\n vec2 lightCoord = (vTextureCoord * filterArea.xy) / dimensions;\n vec4 light = texture2D(uLightmap, lightCoord);\n vec3 ambient = ambientColor.rgb * ambientColor.a;\n vec3 intensity = ambient + light.rgb;\n vec3 finalColor = diffuseColor.rgb * intensity;\n gl_FragColor = vec4(finalColor, diffuseColor.a);\n}\n",Ie=function(e){function n(t,n,r){void 0===n&&(n=0),void 0===r&&(r=1),e.call(this,Le,ke),this.uniforms.dimensions=new Float32Array(2),this.uniforms.ambientColor=new Float32Array([0,0,0,r]),this.texture=t,this.color=n}e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n;var r={texture:{configurable:!0},color:{configurable:!0},alpha:{configurable:!0}};return n.prototype.apply=function(e,t,n,r){this.uniforms.dimensions[0]=t.sourceFrame.width,this.uniforms.dimensions[1]=t.sourceFrame.height,e.applyFilter(this,t,n,r)},r.texture.get=function(){return this.uniforms.uLightmap},r.texture.set=function(e){this.uniforms.uLightmap=e},r.color.set=function(e){var n=this.uniforms.ambientColor;"number"==typeof e?(t.utils.hex2rgb(e,n),this._color=e):(n[0]=e[0],n[1]=e[1],n[2]=e[2],n[3]=e[3],this._color=t.utils.rgb2hex(n))},r.color.get=function(){return this._color},r.alpha.get=function(){return this.uniforms.ambientColor[3]},r.alpha.set=function(e){this.uniforms.ambientColor[3]=e},Object.defineProperties(n.prototype,r),n}(t.Filter),Ee=n,Be="varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float blur;\nuniform float gradientBlur;\nuniform vec2 start;\nuniform vec2 end;\nuniform vec2 delta;\nuniform vec2 texSize;\n\nfloat random(vec3 scale, float seed)\n{\n return fract(sin(dot(gl_FragCoord.xyz + seed, scale)) * 43758.5453 + seed);\n}\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n float total = 0.0;\n\n float offset = random(vec3(12.9898, 78.233, 151.7182), 0.0);\n vec2 normal = normalize(vec2(start.y - end.y, end.x - start.x));\n float radius = smoothstep(0.0, 1.0, abs(dot(vTextureCoord * texSize - start, normal)) / gradientBlur) * blur;\n\n for (float t = -30.0; t <= 30.0; t++)\n {\n float percent = (t + offset - 0.5) / 30.0;\n float weight = 1.0 - abs(percent);\n vec4 sample = texture2D(uSampler, vTextureCoord + delta / texSize * percent * radius);\n sample.rgb *= sample.a;\n color += sample * weight;\n total += weight;\n }\n\n color /= total;\n color.rgb /= color.a + 0.00001;\n\n gl_FragColor = color;\n}\n",Xe=function(e){function n(n,r,o,i){void 0===n&&(n=100),void 0===r&&(r=600),void 0===o&&(o=null),void 0===i&&(i=null),e.call(this,Ee,Be),this.uniforms.blur=n,this.uniforms.gradientBlur=r,this.uniforms.start=o||new t.Point(0,window.innerHeight/2),this.uniforms.end=i||new t.Point(600,window.innerHeight/2),this.uniforms.delta=new t.Point(30,30),this.uniforms.texSize=new t.Point(window.innerWidth,window.innerHeight),this.updateDelta()}e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n;var r={blur:{configurable:!0},gradientBlur:{configurable:!0},start:{configurable:!0},end:{configurable:!0}};return n.prototype.updateDelta=function(){this.uniforms.delta.x=0,this.uniforms.delta.y=0},r.blur.get=function(){return this.uniforms.blur},r.blur.set=function(e){this.uniforms.blur=e},r.gradientBlur.get=function(){return this.uniforms.gradientBlur},r.gradientBlur.set=function(e){this.uniforms.gradientBlur=e},r.start.get=function(){return this.uniforms.start},r.start.set=function(e){this.uniforms.start=e,this.updateDelta()},r.end.get=function(){return this.uniforms.end},r.end.set=function(e){this.uniforms.end=e,this.updateDelta()},Object.defineProperties(n.prototype,r),n}(t.Filter),qe=function(e){function t(){e.apply(this,arguments)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.updateDelta=function(){var e=this.uniforms.end.x-this.uniforms.start.x,t=this.uniforms.end.y-this.uniforms.start.y,n=Math.sqrt(e*e+t*t);this.uniforms.delta.x=e/n,this.uniforms.delta.y=t/n},t}(Xe),Ne=function(e){function t(){e.apply(this,arguments)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.updateDelta=function(){var e=this.uniforms.end.x-this.uniforms.start.x,t=this.uniforms.end.y-this.uniforms.start.y,n=Math.sqrt(e*e+t*t);this.uniforms.delta.x=-t/n,this.uniforms.delta.y=e/n},t}(Xe),Ge=function(e){function t(t,n,r,o){void 0===t&&(t=100),void 0===n&&(n=600),void 0===r&&(r=null),void 0===o&&(o=null),e.call(this),this.tiltShiftXFilter=new qe(t,n,r,o),this.tiltShiftYFilter=new Ne(t,n,r,o)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={blur:{configurable:!0},gradientBlur:{configurable:!0},start:{configurable:!0},end:{configurable:!0}};return t.prototype.apply=function(e,t,n){var r=e.getRenderTarget(!0);this.tiltShiftXFilter.apply(e,t,r),this.tiltShiftYFilter.apply(e,r,n),e.returnRenderTarget(r)},n.blur.get=function(){return this.tiltShiftXFilter.blur},n.blur.set=function(e){this.tiltShiftXFilter.blur=this.tiltShiftYFilter.blur=e},n.gradientBlur.get=function(){return this.tiltShiftXFilter.gradientBlur},n.gradientBlur.set=function(e){this.tiltShiftXFilter.gradientBlur=this.tiltShiftYFilter.gradientBlur=e},n.start.get=function(){return this.tiltShiftXFilter.start},n.start.set=function(e){this.tiltShiftXFilter.start=this.tiltShiftYFilter.start=e},n.end.get=function(){return this.tiltShiftXFilter.end},n.end.set=function(e){this.tiltShiftXFilter.end=this.tiltShiftYFilter.end=e},Object.defineProperties(t.prototype,n),t}(t.Filter),Ke=n,Ye="varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float radius;\nuniform float angle;\nuniform vec2 offset;\nuniform vec4 filterArea;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 twist(vec2 coord)\n{\n coord -= offset;\n\n float dist = length(coord);\n\n if (dist < radius)\n {\n float ratioDist = (radius - dist) / radius;\n float angleMod = ratioDist * ratioDist * angle;\n float s = sin(angleMod);\n float c = cos(angleMod);\n coord = vec2(coord.x * c - coord.y * s, coord.x * s + coord.y * c);\n }\n\n coord += offset;\n\n return coord;\n}\n\nvoid main(void)\n{\n\n vec2 coord = mapCoord(vTextureCoord);\n\n coord = twist(coord);\n\n coord = unmapCoord(coord);\n\n gl_FragColor = texture2D(uSampler, coord );\n\n}\n",We=function(e){function t(t,n,r){void 0===t&&(t=200),void 0===n&&(n=4),void 0===r&&(r=20),e.call(this,Ke,Ye),this.radius=t,this.angle=n,this.padding=r}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={offset:{configurable:!0},radius:{configurable:!0},angle:{configurable:!0}};return n.offset.get=function(){return this.uniforms.offset},n.offset.set=function(e){this.uniforms.offset=e},n.radius.get=function(){return this.uniforms.radius},n.radius.set=function(e){this.uniforms.radius=e},n.angle.get=function(){return this.uniforms.angle},n.angle.set=function(e){this.uniforms.angle=e},Object.defineProperties(t.prototype,n),t}(t.Filter),Qe=n,Ue="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform vec2 uCenter;\nuniform float uStrength;\nuniform float uInnerRadius;\nuniform float uRadius;\n\nconst float MAX_KERNEL_SIZE = 32.0;\n\nfloat random(vec3 scale, float seed) {\n // use the fragment position for a different seed per-pixel\n return fract(sin(dot(gl_FragCoord.xyz + seed, scale)) * 43758.5453 + seed);\n}\n\nvoid main() {\n\n float minGradient = uInnerRadius * 0.3;\n float innerRadius = (uInnerRadius + minGradient * 0.5) / filterArea.x;\n\n float gradient = uRadius * 0.3;\n float radius = (uRadius - gradient * 0.5) / filterArea.x;\n\n float countLimit = MAX_KERNEL_SIZE;\n\n vec2 dir = vec2(uCenter.xy / filterArea.xy - vTextureCoord);\n float dist = length(vec2(dir.x, dir.y * filterArea.y / filterArea.x));\n\n float strength = uStrength;\n\n float delta = 0.0;\n float gap;\n if (dist < innerRadius) {\n delta = innerRadius - dist;\n gap = minGradient;\n } else if (radius >= 0.0 && dist > radius) { // radius < 0 means it's infinity\n delta = dist - radius;\n gap = gradient;\n }\n\n if (delta > 0.0) {\n float normalCount = gap / filterArea.x;\n delta = (normalCount - delta) / normalCount;\n countLimit *= delta;\n strength *= delta;\n if (countLimit < 1.0)\n {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n }\n\n // randomize the lookup values to hide the fixed number of samples\n float offset = random(vec3(12.9898, 78.233, 151.7182), 0.0);\n\n float total = 0.0;\n vec4 color = vec4(0.0);\n\n dir *= strength;\n\n for (float t = 0.0; t < MAX_KERNEL_SIZE; t++) {\n float percent = (t + offset) / MAX_KERNEL_SIZE;\n float weight = 4.0 * (percent - percent * percent);\n vec2 p = vTextureCoord + dir * percent;\n vec4 sample = texture2D(uSampler, p);\n\n // switch to pre-multiplied alpha to correctly blur transparent images\n // sample.rgb *= sample.a;\n\n color += sample * weight;\n total += weight;\n\n if (t > countLimit){\n break;\n }\n }\n\n color /= total;\n // switch back from pre-multiplied alpha\n color.rgb /= color.a + 0.00001;\n\n gl_FragColor = color;\n}\n",Ze=function(e){function t(t,n,r,o){void 0===t&&(t=.1),void 0===n&&(n=[0,0]),void 0===r&&(r=0),void 0===o&&(o=-1),e.call(this,Qe,Ue),this.center=n,this.strength=t,this.innerRadius=r,this.radius=o}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={center:{configurable:!0},strength:{configurable:!0},innerRadius:{configurable:!0},radius:{configurable:!0}};return n.center.get=function(){return this.uniforms.uCenter},n.center.set=function(e){this.uniforms.uCenter=e},n.strength.get=function(){return this.uniforms.uStrength},n.strength.set=function(e){this.uniforms.uStrength=e},n.innerRadius.get=function(){return this.uniforms.uInnerRadius},n.innerRadius.set=function(e){this.uniforms.uInnerRadius=e},n.radius.get=function(){return this.uniforms.uRadius},n.radius.set=function(e){(e<0||e===1/0)&&(e=-1),this.uniforms.uRadius=e},Object.defineProperties(t.prototype,n),t}(t.Filter);return e.AdjustmentFilter=o,e.AdvancedBloomFilter=p,e.AsciiFilter=g,e.BevelFilter=y,e.BloomFilter=F,e.BulgePinchFilter=w,e.ColorMapFilter=O,e.ColorReplaceFilter=R,e.ConvolutionFilter=k,e.CrossHatchFilter=B,e.CRTFilter=N,e.DotFilter=Y,e.DropShadowFilter=U,e.EmbossFilter=H,e.GlitchFilter=ee,e.GlowFilter=re,e.GodrayFilter=se,e.KawaseBlurFilter=a,e.MotionBlurFilter=ce,e.MultiColorReplaceFilter=pe,e.OldFilmFilter=ge,e.OutlineFilter=ye,e.PixelateFilter=Ce,e.RadialBlurFilter=ze,e.ReflectionFilter=Te,e.RGBSplitFilter=Pe,e.ShockwaveFilter=je,e.SimpleLightmapFilter=Ie,e.TiltShiftFilter=Ge,e.TiltShiftAxisFilter=Xe,e.TiltShiftXFilter=qe,e.TiltShiftYFilter=Ne,e.TwistFilter=We,e.ZoomBlurFilter=Ze,e}({},PIXI);Object.assign(PIXI.filters,this.__filters); +//# sourceMappingURL=pixi-filters.js.map diff --git a/js/pixi-filters/3.1.1/pixi-filters.js b/js/pixi-filters/3.1.1/pixi-filters.js new file mode 100644 index 0000000..ec99131 --- /dev/null +++ b/js/pixi-filters/3.1.1/pixi-filters.js @@ -0,0 +1,9 @@ +/*! + * pixi-filters - v3.1.1 + * Compiled Wed, 11 Mar 2020 20:40:29 UTC + * + * pixi-filters is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +var __filters=function(e,t,n,r,o,i,l,s){"use strict";var a="attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}",u="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform float gamma;\nuniform float contrast;\nuniform float saturation;\nuniform float brightness;\nuniform float red;\nuniform float green;\nuniform float blue;\nuniform float alpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (c.a > 0.0) {\n c.rgb /= c.a;\n\n vec3 rgb = pow(c.rgb, vec3(1. / gamma));\n rgb = mix(vec3(.5), mix(vec3(dot(vec3(.2125, .7154, .0721), rgb)), rgb, saturation), contrast);\n rgb.r *= red;\n rgb.g *= green;\n rgb.b *= blue;\n c.rgb = rgb * brightness;\n\n c.rgb *= c.a;\n }\n\n gl_FragColor = c * alpha;\n}\n",c=function(e){function t(t){e.call(this,a,u),Object.assign(this,{gamma:1,saturation:1,contrast:1,brightness:1,red:1,green:1,blue:1,alpha:1},t)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.apply=function(e,t,n,r){this.uniforms.gamma=Math.max(this.gamma,1e-4),this.uniforms.saturation=this.saturation,this.uniforms.contrast=this.contrast,this.uniforms.brightness=this.brightness,this.uniforms.red=this.red,this.uniforms.green=this.green,this.uniforms.blue=this.blue,this.uniforms.alpha=this.alpha,e.applyFilter(this,t,n,r)},t}(t.Filter),f=a,h="\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 uOffset;\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n\n // Sample top left pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y + uOffset.y));\n\n // Sample top right pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y + uOffset.y));\n\n // Sample bottom right pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y - uOffset.y));\n\n // Sample bottom left pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y - uOffset.y));\n\n // Average\n color *= 0.25;\n\n gl_FragColor = color;\n}",p="\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 uOffset;\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n\n // Sample top left pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y + uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample top right pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y + uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample bottom right pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y - uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample bottom left pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y - uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Average\n color *= 0.25;\n\n gl_FragColor = color;\n}\n",d=function(e){function t(t,r,o){void 0===t&&(t=4),void 0===r&&(r=3),void 0===o&&(o=!1),e.call(this,f,o?p:h),this.uniforms.uOffset=new Float32Array(2),this._pixelSize=new n.Point,this.pixelSize=1,this._clamp=o,this._kernels=null,Array.isArray(t)?this.kernels=t:(this._blur=t,this.quality=r)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var r={kernels:{configurable:!0},clamp:{configurable:!0},pixelSize:{configurable:!0},quality:{configurable:!0},blur:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){var o,i=this.pixelSize.x/t._frame.width,l=this.pixelSize.y/t._frame.height;if(1===this._quality||0===this._blur)o=this._kernels[0]+.5,this.uniforms.uOffset[0]=o*i,this.uniforms.uOffset[1]=o*l,e.applyFilter(this,t,n,r);else{for(var s,a=e.getFilterTexture(),u=t,c=a,f=this._quality-1,h=0;h0)for(var r=e,o=e/t,i=1;i0?(this._kernels=e,this._quality=e.length,this._blur=Math.max.apply(Math,e)):(this._kernels=[0],this._quality=1)},r.clamp.get=function(){return this._clamp},r.pixelSize.set=function(e){"number"==typeof e?(this._pixelSize.x=e,this._pixelSize.y=e):Array.isArray(e)?(this._pixelSize.x=e[0],this._pixelSize.y=e[1]):e instanceof n.Point?(this._pixelSize.x=e.x,this._pixelSize.y=e.y):(this._pixelSize.x=1,this._pixelSize.y=1)},r.pixelSize.get=function(){return this._pixelSize},r.quality.get=function(){return this._quality},r.quality.set=function(e){this._quality=Math.max(1,Math.round(e)),this._generateKernels()},r.blur.get=function(){return this._blur},r.blur.set=function(e){this._blur=e,this._generateKernels()},Object.defineProperties(t.prototype,r),t}(t.Filter),m=a,g="\nuniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform float threshold;\n\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n // A simple & fast algorithm for getting brightness.\n // It's inaccuracy , but good enought for this feature.\n float _max = max(max(color.r, color.g), color.b);\n float _min = min(min(color.r, color.g), color.b);\n float brightness = (_max + _min) * 0.5;\n\n if(brightness > threshold) {\n gl_FragColor = color;\n } else {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);\n }\n}\n",v=function(e){function t(t){void 0===t&&(t=.5),e.call(this,m,g),this.threshold=t}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={threshold:{configurable:!0}};return n.threshold.get=function(){return this.uniforms.threshold},n.threshold.set=function(e){this.uniforms.threshold=e},Object.defineProperties(t.prototype,n),t}(t.Filter),x="uniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D bloomTexture;\nuniform float bloomScale;\nuniform float brightness;\n\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord);\n color.rgb *= brightness;\n vec4 bloomColor = vec4(texture2D(bloomTexture, vTextureCoord).rgb, 0.0);\n bloomColor.rgb *= bloomScale;\n gl_FragColor = color + bloomColor;\n}\n",y=function(e){function t(t){e.call(this,m,x),"number"==typeof t&&(t={threshold:t}),t=Object.assign({threshold:.5,bloomScale:1,brightness:1,kernels:null,blur:8,quality:4,pixelSize:1,resolution:r.settings.RESOLUTION},t),this.bloomScale=t.bloomScale,this.brightness=t.brightness;var n=t.kernels,o=t.blur,i=t.quality,l=t.pixelSize,s=t.resolution;this._extractFilter=new v(t.threshold),this._extractFilter.resolution=s,this._blurFilter=n?new d(n):new d(o,i),this.pixelSize=l,this.resolution=s}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={resolution:{configurable:!0},threshold:{configurable:!0},kernels:{configurable:!0},blur:{configurable:!0},quality:{configurable:!0},pixelSize:{configurable:!0}};return t.prototype.apply=function(e,t,n,r,o){var i=e.getFilterTexture();this._extractFilter.apply(e,t,i,1,o);var l=e.getFilterTexture();this._blurFilter.apply(e,i,l,1,o),this.uniforms.bloomScale=this.bloomScale,this.uniforms.brightness=this.brightness,this.uniforms.bloomTexture=l,e.applyFilter(this,t,n,r),e.returnFilterTexture(l),e.returnFilterTexture(i)},n.resolution.get=function(){return this._resolution},n.resolution.set=function(e){this._resolution=e,this._extractFilter&&(this._extractFilter.resolution=e),this._blurFilter&&(this._blurFilter.resolution=e)},n.threshold.get=function(){return this._extractFilter.threshold},n.threshold.set=function(e){this._extractFilter.threshold=e},n.kernels.get=function(){return this._blurFilter.kernels},n.kernels.set=function(e){this._blurFilter.kernels=e},n.blur.get=function(){return this._blurFilter.blur},n.blur.set=function(e){this._blurFilter.blur=e},n.quality.get=function(){return this._blurFilter.quality},n.quality.set=function(e){this._blurFilter.quality=e},n.pixelSize.get=function(){return this._blurFilter.pixelSize},n.pixelSize.set=function(e){this._blurFilter.pixelSize=e},Object.defineProperties(t.prototype,n),t}(t.Filter),_=a,b="varying vec2 vTextureCoord;\n\nuniform vec4 filterArea;\nuniform float pixelSize;\nuniform sampler2D uSampler;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 pixelate(vec2 coord, vec2 size)\n{\n return floor( coord / size ) * size;\n}\n\nvec2 getMod(vec2 coord, vec2 size)\n{\n return mod( coord , size) / size;\n}\n\nfloat character(float n, vec2 p)\n{\n p = floor(p*vec2(4.0, -4.0) + 2.5);\n\n if (clamp(p.x, 0.0, 4.0) == p.x)\n {\n if (clamp(p.y, 0.0, 4.0) == p.y)\n {\n if (int(mod(n/exp2(p.x + 5.0*p.y), 2.0)) == 1) return 1.0;\n }\n }\n return 0.0;\n}\n\nvoid main()\n{\n vec2 coord = mapCoord(vTextureCoord);\n\n // get the rounded color..\n vec2 pixCoord = pixelate(coord, vec2(pixelSize));\n pixCoord = unmapCoord(pixCoord);\n\n vec4 color = texture2D(uSampler, pixCoord);\n\n // determine the character to use\n float gray = (color.r + color.g + color.b) / 3.0;\n\n float n = 65536.0; // .\n if (gray > 0.2) n = 65600.0; // :\n if (gray > 0.3) n = 332772.0; // *\n if (gray > 0.4) n = 15255086.0; // o\n if (gray > 0.5) n = 23385164.0; // &\n if (gray > 0.6) n = 15252014.0; // 8\n if (gray > 0.7) n = 13199452.0; // @\n if (gray > 0.8) n = 11512810.0; // #\n\n // get the mod..\n vec2 modd = getMod(coord, vec2(pixelSize));\n\n gl_FragColor = color * character( n, vec2(-1.0) + modd * 2.0);\n\n}\n",C=function(e){function t(t){void 0===t&&(t=8),e.call(this,_,b),this.size=t}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={size:{configurable:!0}};return n.size.get=function(){return this.uniforms.pixelSize},n.size.set=function(e){this.uniforms.pixelSize=e},Object.defineProperties(t.prototype,n),t}(t.Filter),S=a,F="precision mediump float;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform float transformX;\nuniform float transformY;\nuniform vec3 lightColor;\nuniform float lightAlpha;\nuniform vec3 shadowColor;\nuniform float shadowAlpha;\n\nvoid main(void) {\n vec2 transform = vec2(1.0 / filterArea) * vec2(transformX, transformY);\n vec4 color = texture2D(uSampler, vTextureCoord);\n float light = texture2D(uSampler, vTextureCoord - transform).a;\n float shadow = texture2D(uSampler, vTextureCoord + transform).a;\n\n color.rgb = mix(color.rgb, lightColor, clamp((color.a - light) * lightAlpha, 0.0, 1.0));\n color.rgb = mix(color.rgb, shadowColor, clamp((color.a - shadow) * shadowAlpha, 0.0, 1.0));\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n",z=function(e){function t(t){void 0===t&&(t={}),e.call(this,S,F),this.uniforms.lightColor=new Float32Array(3),this.uniforms.shadowColor=new Float32Array(3),t=Object.assign({rotation:45,thickness:2,lightColor:16777215,lightAlpha:.7,shadowColor:0,shadowAlpha:.7},t),this.rotation=t.rotation,this.thickness=t.thickness,this.lightColor=t.lightColor,this.lightAlpha=t.lightAlpha,this.shadowColor=t.shadowColor,this.shadowAlpha=t.shadowAlpha}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var r={rotation:{configurable:!0},thickness:{configurable:!0},lightColor:{configurable:!0},lightAlpha:{configurable:!0},shadowColor:{configurable:!0},shadowAlpha:{configurable:!0}};return t.prototype._updateTransform=function(){this.uniforms.transformX=this._thickness*Math.cos(this._angle),this.uniforms.transformY=this._thickness*Math.sin(this._angle)},r.rotation.get=function(){return this._angle/n.DEG_TO_RAD},r.rotation.set=function(e){this._angle=e*n.DEG_TO_RAD,this._updateTransform()},r.thickness.get=function(){return this._thickness},r.thickness.set=function(e){this._thickness=e,this._updateTransform()},r.lightColor.get=function(){return o.rgb2hex(this.uniforms.lightColor)},r.lightColor.set=function(e){o.hex2rgb(e,this.uniforms.lightColor)},r.lightAlpha.get=function(){return this.uniforms.lightAlpha},r.lightAlpha.set=function(e){this.uniforms.lightAlpha=e},r.shadowColor.get=function(){return o.rgb2hex(this.uniforms.shadowColor)},r.shadowColor.set=function(e){o.hex2rgb(e,this.uniforms.shadowColor)},r.shadowAlpha.get=function(){return this.uniforms.shadowAlpha},r.shadowAlpha.set=function(e){this.uniforms.shadowAlpha=e},Object.defineProperties(t.prototype,r),t}(t.Filter),A=function(e){function t(t,o,a,u){var c,f;void 0===t&&(t=2),void 0===o&&(o=4),void 0===a&&(a=r.settings.RESOLUTION),void 0===u&&(u=5),e.call(this),"number"==typeof t?(c=t,f=t):t instanceof n.Point?(c=t.x,f=t.y):Array.isArray(t)&&(c=t[0],f=t[1]),this.blurXFilter=new s.BlurFilterPass(!0,c,o,a,u),this.blurYFilter=new s.BlurFilterPass(!1,f,o,a,u),this.blurYFilter.blendMode=i.BLEND_MODES.SCREEN,this.defaultFilter=new l.AlphaFilter}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var o={blur:{configurable:!0},blurX:{configurable:!0},blurY:{configurable:!0}};return t.prototype.apply=function(e,t,n){var r=e.getFilterTexture(!0);this.defaultFilter.apply(e,t,n),this.blurXFilter.apply(e,t,r),this.blurYFilter.apply(e,r,n),e.returnFilterTexture(r)},o.blur.get=function(){return this.blurXFilter.blur},o.blur.set=function(e){this.blurXFilter.blur=this.blurYFilter.blur=e},o.blurX.get=function(){return this.blurXFilter.blur},o.blurX.set=function(e){this.blurXFilter.blur=e},o.blurY.get=function(){return this.blurYFilter.blur},o.blurY.set=function(e){this.blurYFilter.blur=e},Object.defineProperties(t.prototype,o),t}(t.Filter),w=a,T="uniform float radius;\nuniform float strength;\nuniform vec2 center;\nuniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\n\nvoid main()\n{\n vec2 coord = vTextureCoord * filterArea.xy;\n coord -= center * dimensions.xy;\n float distance = length(coord);\n if (distance < radius) {\n float percent = distance / radius;\n if (strength > 0.0) {\n coord *= mix(1.0, smoothstep(0.0, radius / distance, percent), strength * 0.75);\n } else {\n coord *= mix(1.0, pow(percent, 1.0 + strength * 0.75) * radius / distance, 1.0 - percent);\n }\n }\n coord += center * dimensions.xy;\n coord /= filterArea.xy;\n vec2 clampedCoord = clamp(coord, filterClamp.xy, filterClamp.zw);\n vec4 color = texture2D(uSampler, clampedCoord);\n if (coord != clampedCoord) {\n color *= max(0.0, 1.0 - length(coord - clampedCoord));\n }\n\n gl_FragColor = color;\n}\n",O=function(e){function t(t){if(e.call(this,w,T),"object"!=typeof t){var n=arguments[0],r=arguments[1],o=arguments[2];t={},void 0!==n&&(t.center=n),void 0!==r&&(t.radius=r),void 0!==o&&(t.strength=o)}this.uniforms.dimensions=new Float32Array(2),Object.assign(this,{center:[.5,.5],radius:100,strength:1},t)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={radius:{configurable:!0},strength:{configurable:!0},center:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.dimensions[0]=t.filterFrame.width,this.uniforms.dimensions[1]=t.filterFrame.height,e.applyFilter(this,t,n,r)},n.radius.get=function(){return this.uniforms.radius},n.radius.set=function(e){this.uniforms.radius=e},n.strength.get=function(){return this.uniforms.strength},n.strength.set=function(e){this.uniforms.strength=e},n.center.get=function(){return this.uniforms.center},n.center.set=function(e){this.uniforms.center=e},Object.defineProperties(t.prototype,n),t}(t.Filter),D=a,P="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform sampler2D colorMap;\nuniform float _mix;\nuniform float _size;\nuniform float _sliceSize;\nuniform float _slicePixelSize;\nuniform float _sliceInnerSize;\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord.xy);\n\n vec4 adjusted;\n if (color.a > 0.0) {\n color.rgb /= color.a;\n float innerWidth = _size - 1.0;\n float zSlice0 = min(floor(color.b * innerWidth), innerWidth);\n float zSlice1 = min(zSlice0 + 1.0, innerWidth);\n float xOffset = _slicePixelSize * 0.5 + color.r * _sliceInnerSize;\n float s0 = xOffset + (zSlice0 * _sliceSize);\n float s1 = xOffset + (zSlice1 * _sliceSize);\n float yOffset = _sliceSize * 0.5 + color.g * (1.0 - _sliceSize);\n vec4 slice0Color = texture2D(colorMap, vec2(s0,yOffset));\n vec4 slice1Color = texture2D(colorMap, vec2(s1,yOffset));\n float zOffset = fract(color.b * innerWidth);\n adjusted = mix(slice0Color, slice1Color, zOffset);\n\n color.rgb *= color.a;\n }\n gl_FragColor = vec4(mix(color, adjusted, _mix).rgb, color.a);\n\n}",M=function(e){function n(t,n,r){void 0===n&&(n=!1),void 0===r&&(r=1),e.call(this,D,P),this._size=0,this._sliceSize=0,this._slicePixelSize=0,this._sliceInnerSize=0,this._scaleMode=null,this._nearest=!1,this.nearest=n,this.mix=r,this.colorMap=t}e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n;var r={colorSize:{configurable:!0},colorMap:{configurable:!0},nearest:{configurable:!0}};return n.prototype.apply=function(e,t,n,r){this.uniforms._mix=this.mix,e.applyFilter(this,t,n,r)},r.colorSize.get=function(){return this._size},r.colorMap.get=function(){return this._colorMap},r.colorMap.set=function(e){e instanceof t.Texture||(e=t.Texture.from(e)),e&&e.baseTexture&&(e.baseTexture.scaleMode=this._scaleMode,e.baseTexture.mipmap=!1,this._size=e.height,this._sliceSize=1/this._size,this._slicePixelSize=this._sliceSize/this._size,this._sliceInnerSize=this._slicePixelSize*(this._size-1),this.uniforms._size=this._size,this.uniforms._sliceSize=this._sliceSize,this.uniforms._slicePixelSize=this._slicePixelSize,this.uniforms._sliceInnerSize=this._sliceInnerSize,this.uniforms.colorMap=e),this._colorMap=e},r.nearest.get=function(){return this._nearest},r.nearest.set=function(e){this._nearest=e,this._scaleMode=e?i.SCALE_MODES.NEAREST:i.SCALE_MODES.LINEAR;var t=this._colorMap;t&&t.baseTexture&&(t.baseTexture._glTextures={},t.baseTexture.scaleMode=this._scaleMode,t.baseTexture.mipmap=!1,t._updateID++,t.baseTexture.emit("update",t.baseTexture))},n.prototype.updateColorMap=function(){var e=this._colorMap;e&&e.baseTexture&&(e._updateID++,e.baseTexture.emit("update",e.baseTexture),this.colorMap=e)},n.prototype.destroy=function(t){this._colorMap&&this._colorMap.destroy(t),e.prototype.destroy.call(this)},Object.defineProperties(n.prototype,r),n}(t.Filter),R=a,k="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec3 color;\nvoid main(void) {\n vec4 currentColor = texture2D(uSampler, vTextureCoord);\n vec3 colorOverlay = color * currentColor.a;\n gl_FragColor = vec4(colorOverlay.r, colorOverlay.g, colorOverlay.b, currentColor.a);\n}\n",j=function(e){function t(t){void 0===t&&(t=0),e.call(this,R,k),this.uniforms.color=new Float32Array(3),this.color=t}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={color:{configurable:!0}};return n.color.set=function(e){var t=this.uniforms.color;"number"==typeof e?(o.hex2rgb(e,t),this._color=e):(t[0]=e[0],t[1]=e[1],t[2]=e[2],this._color=o.rgb2hex(t))},n.color.get=function(){return this._color},Object.defineProperties(t.prototype,n),t}(t.Filter),E=a,L="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec3 originalColor;\nuniform vec3 newColor;\nuniform float epsilon;\nvoid main(void) {\n vec4 currentColor = texture2D(uSampler, vTextureCoord);\n vec3 colorDiff = originalColor - (currentColor.rgb / max(currentColor.a, 0.0000000001));\n float colorDistance = length(colorDiff);\n float doReplace = step(colorDistance, epsilon);\n gl_FragColor = vec4(mix(currentColor.rgb, (newColor + colorDiff) * currentColor.a, doReplace), currentColor.a);\n}\n",I=function(e){function t(t,n,r){void 0===t&&(t=16711680),void 0===n&&(n=0),void 0===r&&(r=.4),e.call(this,E,L),this.uniforms.originalColor=new Float32Array(3),this.uniforms.newColor=new Float32Array(3),this.originalColor=t,this.newColor=n,this.epsilon=r}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={originalColor:{configurable:!0},newColor:{configurable:!0},epsilon:{configurable:!0}};return n.originalColor.set=function(e){var t=this.uniforms.originalColor;"number"==typeof e?(o.hex2rgb(e,t),this._originalColor=e):(t[0]=e[0],t[1]=e[1],t[2]=e[2],this._originalColor=o.rgb2hex(t))},n.originalColor.get=function(){return this._originalColor},n.newColor.set=function(e){var t=this.uniforms.newColor;"number"==typeof e?(o.hex2rgb(e,t),this._newColor=e):(t[0]=e[0],t[1]=e[1],t[2]=e[2],this._newColor=o.rgb2hex(t))},n.newColor.get=function(){return this._newColor},n.epsilon.set=function(e){this.uniforms.epsilon=e},n.epsilon.get=function(){return this.uniforms.epsilon},Object.defineProperties(t.prototype,n),t}(t.Filter),X=a,B="precision mediump float;\n\nvarying mediump vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec2 texelSize;\nuniform float matrix[9];\n\nvoid main(void)\n{\n vec4 c11 = texture2D(uSampler, vTextureCoord - texelSize); // top left\n vec4 c12 = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y - texelSize.y)); // top center\n vec4 c13 = texture2D(uSampler, vec2(vTextureCoord.x + texelSize.x, vTextureCoord.y - texelSize.y)); // top right\n\n vec4 c21 = texture2D(uSampler, vec2(vTextureCoord.x - texelSize.x, vTextureCoord.y)); // mid left\n vec4 c22 = texture2D(uSampler, vTextureCoord); // mid center\n vec4 c23 = texture2D(uSampler, vec2(vTextureCoord.x + texelSize.x, vTextureCoord.y)); // mid right\n\n vec4 c31 = texture2D(uSampler, vec2(vTextureCoord.x - texelSize.x, vTextureCoord.y + texelSize.y)); // bottom left\n vec4 c32 = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y + texelSize.y)); // bottom center\n vec4 c33 = texture2D(uSampler, vTextureCoord + texelSize); // bottom right\n\n gl_FragColor =\n c11 * matrix[0] + c12 * matrix[1] + c13 * matrix[2] +\n c21 * matrix[3] + c22 * matrix[4] + c23 * matrix[5] +\n c31 * matrix[6] + c32 * matrix[7] + c33 * matrix[8];\n\n gl_FragColor.a = c22.a;\n}\n",N=function(e){function t(t,n,r){void 0===n&&(n=200),void 0===r&&(r=200),e.call(this,X,B),this.uniforms.texelSize=new Float32Array(2),this.uniforms.matrix=new Float32Array(9),void 0!==t&&(this.matrix=t),this.width=n,this.height=r}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={matrix:{configurable:!0},width:{configurable:!0},height:{configurable:!0}};return n.matrix.get=function(){return this.uniforms.matrix},n.matrix.set=function(e){var t=this;e.forEach(function(e,n){return t.uniforms.matrix[n]=e})},n.width.get=function(){return 1/this.uniforms.texelSize[0]},n.width.set=function(e){this.uniforms.texelSize[0]=1/e},n.height.get=function(){return 1/this.uniforms.texelSize[1]},n.height.set=function(e){this.uniforms.texelSize[1]=1/e},Object.defineProperties(t.prototype,n),t}(t.Filter),G=a,q="precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n float lum = length(texture2D(uSampler, vTextureCoord.xy).rgb);\n\n gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n\n if (lum < 1.00)\n {\n if (mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.75)\n {\n if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.50)\n {\n if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.3)\n {\n if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n}\n",W=function(e){function t(){e.call(this,G,q)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t}(t.Filter),K=a,Y="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec2 dimensions;\n\nconst float SQRT_2 = 1.414213;\n\nconst float light = 1.0;\n\nuniform float curvature;\nuniform float lineWidth;\nuniform float lineContrast;\nuniform bool verticalLine;\nuniform float noise;\nuniform float noiseSize;\n\nuniform float vignetting;\nuniform float vignettingAlpha;\nuniform float vignettingBlur;\n\nuniform float seed;\nuniform float time;\n\nfloat rand(vec2 co) {\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main(void)\n{\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n vec2 coord = pixelCoord / dimensions;\n\n vec2 dir = vec2(coord - vec2(0.5, 0.5));\n\n float _c = curvature > 0. ? curvature : 1.;\n float k = curvature > 0. ?(length(dir * dir) * 0.25 * _c * _c + 0.935 * _c) : 1.;\n vec2 uv = dir * k;\n\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n vec3 rgb = gl_FragColor.rgb;\n\n\n if (noise > 0.0 && noiseSize > 0.0)\n {\n pixelCoord.x = floor(pixelCoord.x / noiseSize);\n pixelCoord.y = floor(pixelCoord.y / noiseSize);\n float _noise = rand(pixelCoord * noiseSize * seed) - 0.5;\n rgb += _noise * noise;\n }\n\n if (lineWidth > 0.0) {\n float v = (verticalLine ? uv.x * dimensions.x : uv.y * dimensions.y) * min(1.0, 2.0 / lineWidth ) / _c;\n float j = 1. + cos(v * 1.2 - time) * 0.5 * lineContrast;\n rgb *= j;\n float segment = verticalLine ? mod((dir.x + .5) * dimensions.x, 4.) : mod((dir.y + .5) * dimensions.y, 4.);\n rgb *= 0.99 + ceil(segment) * 0.015;\n }\n\n if (vignetting > 0.0)\n {\n float outter = SQRT_2 - vignetting * SQRT_2;\n float darker = clamp((outter - length(dir) * SQRT_2) / ( 0.00001 + vignettingBlur * SQRT_2), 0.0, 1.0);\n rgb *= darker + (1.0 - darker) * (1.0 - vignettingAlpha);\n }\n\n gl_FragColor.rgb = rgb;\n}\n",Z=function(e){function t(t){e.call(this,K,Y),this.uniforms.dimensions=new Float32Array(2),this.time=0,this.seed=0,Object.assign(this,{curvature:1,lineWidth:1,lineContrast:.25,verticalLine:!1,noise:0,noiseSize:1,seed:0,vignetting:.3,vignettingAlpha:1,vignettingBlur:.3,time:0},t)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={curvature:{configurable:!0},lineWidth:{configurable:!0},lineContrast:{configurable:!0},verticalLine:{configurable:!0},noise:{configurable:!0},noiseSize:{configurable:!0},vignetting:{configurable:!0},vignettingAlpha:{configurable:!0},vignettingBlur:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.dimensions[0]=t.filterFrame.width,this.uniforms.dimensions[1]=t.filterFrame.height,this.uniforms.seed=this.seed,this.uniforms.time=this.time,e.applyFilter(this,t,n,r)},n.curvature.set=function(e){this.uniforms.curvature=e},n.curvature.get=function(){return this.uniforms.curvature},n.lineWidth.set=function(e){this.uniforms.lineWidth=e},n.lineWidth.get=function(){return this.uniforms.lineWidth},n.lineContrast.set=function(e){this.uniforms.lineContrast=e},n.lineContrast.get=function(){return this.uniforms.lineContrast},n.verticalLine.set=function(e){this.uniforms.verticalLine=e},n.verticalLine.get=function(){return this.uniforms.verticalLine},n.noise.set=function(e){this.uniforms.noise=e},n.noise.get=function(){return this.uniforms.noise},n.noiseSize.set=function(e){this.uniforms.noiseSize=e},n.noiseSize.get=function(){return this.uniforms.noiseSize},n.vignetting.set=function(e){this.uniforms.vignetting=e},n.vignetting.get=function(){return this.uniforms.vignetting},n.vignettingAlpha.set=function(e){this.uniforms.vignettingAlpha=e},n.vignettingAlpha.get=function(){return this.uniforms.vignettingAlpha},n.vignettingBlur.set=function(e){this.uniforms.vignettingBlur=e},n.vignettingBlur.get=function(){return this.uniforms.vignettingBlur},Object.defineProperties(t.prototype,n),t}(t.Filter),Q=a,U="precision mediump float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform vec4 filterArea;\nuniform sampler2D uSampler;\n\nuniform float angle;\nuniform float scale;\n\nfloat pattern()\n{\n float s = sin(angle), c = cos(angle);\n vec2 tex = vTextureCoord * filterArea.xy;\n vec2 point = vec2(\n c * tex.x - s * tex.y,\n s * tex.x + c * tex.y\n ) * scale;\n return (sin(point.x) * sin(point.y)) * 4.0;\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float average = (color.r + color.g + color.b) / 3.0;\n gl_FragColor = vec4(vec3(average * 10.0 - 5.0 + pattern()), color.a);\n}\n",V=function(e){function t(t,n){void 0===t&&(t=1),void 0===n&&(n=5),e.call(this,Q,U),this.scale=t,this.angle=n}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={scale:{configurable:!0},angle:{configurable:!0}};return n.scale.get=function(){return this.uniforms.scale},n.scale.set=function(e){this.uniforms.scale=e},n.angle.get=function(){return this.uniforms.angle},n.angle.set=function(e){this.uniforms.angle=e},Object.defineProperties(t.prototype,n),t}(t.Filter),H=a,$="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform vec3 color;\n\nuniform vec2 shift;\nuniform vec4 inputSize;\n\nvoid main(void){\n vec4 sample = texture2D(uSampler, vTextureCoord - shift * inputSize.zw);\n\n // Premultiply alpha\n sample.rgb = color.rgb * sample.a;\n\n // alpha user alpha\n sample *= alpha;\n\n gl_FragColor = sample;\n}",J=function(e){function t(t){t&&t.constructor!==Object&&(console.warn("DropShadowFilter now uses options instead of (rotation, distance, blur, color, alpha)"),t={rotation:t},void 0!==arguments[1]&&(t.distance=arguments[1]),void 0!==arguments[2]&&(t.blur=arguments[2]),void 0!==arguments[3]&&(t.color=arguments[3]),void 0!==arguments[4]&&(t.alpha=arguments[4])),t=Object.assign({rotation:45,distance:5,color:0,alpha:.5,shadowOnly:!1,kernels:null,blur:2,quality:3,pixelSize:1,resolution:r.settings.RESOLUTION},t),e.call(this);var o=t.kernels,i=t.blur,l=t.quality,s=t.pixelSize,a=t.resolution;this._tintFilter=new e(H,$),this._tintFilter.uniforms.color=new Float32Array(4),this._tintFilter.uniforms.shift=new n.Point,this._tintFilter.resolution=a,this._blurFilter=o?new d(o):new d(i,l),this.pixelSize=s,this.resolution=a;var u=t.shadowOnly,c=t.rotation,f=t.distance,h=t.alpha,p=t.color;this.shadowOnly=u,this.rotation=c,this.distance=f,this.alpha=h,this.color=p,this._updatePadding()}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var i={resolution:{configurable:!0},distance:{configurable:!0},rotation:{configurable:!0},alpha:{configurable:!0},color:{configurable:!0},kernels:{configurable:!0},blur:{configurable:!0},quality:{configurable:!0},pixelSize:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){var o=e.getFilterTexture();this._tintFilter.apply(e,t,o,1),this._blurFilter.apply(e,o,n,r),!0!==this.shadowOnly&&e.applyFilter(this,t,n,0),e.returnFilterTexture(o)},t.prototype._updatePadding=function(){this.padding=this.distance+2*this.blur},t.prototype._updateShift=function(){this._tintFilter.uniforms.shift.set(this.distance*Math.cos(this.angle),this.distance*Math.sin(this.angle))},i.resolution.get=function(){return this._resolution},i.resolution.set=function(e){this._resolution=e,this._tintFilter&&(this._tintFilter.resolution=e),this._blurFilter&&(this._blurFilter.resolution=e)},i.distance.get=function(){return this._distance},i.distance.set=function(e){this._distance=e,this._updatePadding(),this._updateShift()},i.rotation.get=function(){return this.angle/n.DEG_TO_RAD},i.rotation.set=function(e){this.angle=e*n.DEG_TO_RAD,this._updateShift()},i.alpha.get=function(){return this._tintFilter.uniforms.alpha},i.alpha.set=function(e){this._tintFilter.uniforms.alpha=e},i.color.get=function(){return o.rgb2hex(this._tintFilter.uniforms.color)},i.color.set=function(e){o.hex2rgb(e,this._tintFilter.uniforms.color)},i.kernels.get=function(){return this._blurFilter.kernels},i.kernels.set=function(e){this._blurFilter.kernels=e},i.blur.get=function(){return this._blurFilter.blur},i.blur.set=function(e){this._blurFilter.blur=e,this._updatePadding()},i.quality.get=function(){return this._blurFilter.quality},i.quality.set=function(e){this._blurFilter.quality=e},i.pixelSize.get=function(){return this._blurFilter.pixelSize},i.pixelSize.set=function(e){this._blurFilter.pixelSize=e},Object.defineProperties(t.prototype,i),t}(t.Filter),ee=a,te="precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float strength;\nuniform vec4 filterArea;\n\n\nvoid main(void)\n{\n\tvec2 onePixel = vec2(1.0 / filterArea);\n\n\tvec4 color;\n\n\tcolor.rgb = vec3(0.5);\n\n\tcolor -= texture2D(uSampler, vTextureCoord - onePixel) * strength;\n\tcolor += texture2D(uSampler, vTextureCoord + onePixel) * strength;\n\n\tcolor.rgb = vec3((color.r + color.g + color.b) / 3.0);\n\n\tfloat alpha = texture2D(uSampler, vTextureCoord).a;\n\n\tgl_FragColor = vec4(color.rgb * alpha, alpha);\n}\n",ne=function(e){function t(t){void 0===t&&(t=5),e.call(this,ee,te),this.strength=t}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={strength:{configurable:!0}};return n.strength.get=function(){return this.uniforms.strength},n.strength.set=function(e){this.uniforms.strength=e},Object.defineProperties(t.prototype,n),t}(t.Filter),re=a,oe="// precision highp float;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\nuniform float aspect;\n\nuniform sampler2D displacementMap;\nuniform float offset;\nuniform float sinDir;\nuniform float cosDir;\nuniform int fillMode;\n\nuniform float seed;\nuniform vec2 red;\nuniform vec2 green;\nuniform vec2 blue;\n\nconst int TRANSPARENT = 0;\nconst int ORIGINAL = 1;\nconst int LOOP = 2;\nconst int CLAMP = 3;\nconst int MIRROR = 4;\n\nvoid main(void)\n{\n vec2 coord = (vTextureCoord * filterArea.xy) / dimensions;\n\n if (coord.x > 1.0 || coord.y > 1.0) {\n return;\n }\n\n float cx = coord.x - 0.5;\n float cy = (coord.y - 0.5) * aspect;\n float ny = (-sinDir * cx + cosDir * cy) / aspect + 0.5;\n\n // displacementMap: repeat\n // ny = ny > 1.0 ? ny - 1.0 : (ny < 0.0 ? 1.0 + ny : ny);\n\n // displacementMap: mirror\n ny = ny > 1.0 ? 2.0 - ny : (ny < 0.0 ? -ny : ny);\n\n vec4 dc = texture2D(displacementMap, vec2(0.5, ny));\n\n float displacement = (dc.r - dc.g) * (offset / filterArea.x);\n\n coord = vTextureCoord + vec2(cosDir * displacement, sinDir * displacement * aspect);\n\n if (fillMode == CLAMP) {\n coord = clamp(coord, filterClamp.xy, filterClamp.zw);\n } else {\n if( coord.x > filterClamp.z ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.x -= filterClamp.z;\n } else if (fillMode == MIRROR) {\n coord.x = filterClamp.z * 2.0 - coord.x;\n }\n } else if( coord.x < filterClamp.x ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.x += filterClamp.z;\n } else if (fillMode == MIRROR) {\n coord.x *= -filterClamp.z;\n }\n }\n\n if( coord.y > filterClamp.w ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.y -= filterClamp.w;\n } else if (fillMode == MIRROR) {\n coord.y = filterClamp.w * 2.0 - coord.y;\n }\n } else if( coord.y < filterClamp.y ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.y += filterClamp.w;\n } else if (fillMode == MIRROR) {\n coord.y *= -filterClamp.w;\n }\n }\n }\n\n gl_FragColor.r = texture2D(uSampler, coord + red * (1.0 - seed * 0.4) / filterArea.xy).r;\n gl_FragColor.g = texture2D(uSampler, coord + green * (1.0 - seed * 0.3) / filterArea.xy).g;\n gl_FragColor.b = texture2D(uSampler, coord + blue * (1.0 - seed * 0.2) / filterArea.xy).b;\n gl_FragColor.a = texture2D(uSampler, coord).a;\n}\n",ie=function(e){function r(n){void 0===n&&(n={}),e.call(this,re,oe),this.uniforms.dimensions=new Float32Array(2),n=Object.assign({slices:5,offset:100,direction:0,fillMode:0,average:!1,seed:0,red:[0,0],green:[0,0],blue:[0,0],minSize:8,sampleSize:512},n),this.direction=n.direction,this.red=n.red,this.green=n.green,this.blue=n.blue,this.offset=n.offset,this.fillMode=n.fillMode,this.average=n.average,this.seed=n.seed,this.minSize=n.minSize,this.sampleSize=n.sampleSize,this._canvas=document.createElement("canvas"),this._canvas.width=4,this._canvas.height=this.sampleSize,this.texture=t.Texture.from(this._canvas,{scaleMode:i.SCALE_MODES.NEAREST}),this._slices=0,this.slices=n.slices}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var o={sizes:{configurable:!0},offsets:{configurable:!0},slices:{configurable:!0},direction:{configurable:!0},red:{configurable:!0},green:{configurable:!0},blue:{configurable:!0}};return r.prototype.apply=function(e,t,n,r){var o=t.filterFrame.width,i=t.filterFrame.height;this.uniforms.dimensions[0]=o,this.uniforms.dimensions[1]=i,this.uniforms.aspect=i/o,this.uniforms.seed=this.seed,this.uniforms.offset=this.offset,this.uniforms.fillMode=this.fillMode,e.applyFilter(this,t,n,r)},r.prototype._randomizeSizes=function(){var e=this._sizes,t=this._slices-1,n=this.sampleSize,r=Math.min(this.minSize/n,.9/this._slices);if(this.average){for(var o=this._slices,i=1,l=0;l0;t--){var n=Math.random()*t>>0,r=e[t];e[t]=e[n],e[n]=r}},r.prototype._randomizeOffsets=function(){for(var e=0;e0?e:0,a=e<0?-e:0;r.fillStyle="rgba("+s+", "+a+", 0, 1)",r.fillRect(0,o>>0,t,l+1>>0),o+=l}n.baseTexture.update(),this.uniforms.displacementMap=n},o.sizes.set=function(e){for(var t=Math.min(this._slices,e.length),n=0;nthis._maxColors)throw"Length of replacements ("+r+") exceeds the maximum colors length ("+this._maxColors+")";t[3*r]=-1;for(var i=0;i 0.5) then: 1 - 2 * (1 - dst) * (1 - src)\n return vec3((dst.x <= 0.5) ? (2.0 * src.x * dst.x) : (1.0 - 2.0 * (1.0 - dst.x) * (1.0 - src.x)),\n (dst.y <= 0.5) ? (2.0 * src.y * dst.y) : (1.0 - 2.0 * (1.0 - dst.y) * (1.0 - src.y)),\n (dst.z <= 0.5) ? (2.0 * src.z * dst.z) : (1.0 - 2.0 * (1.0 - dst.z) * (1.0 - src.z)));\n}\n\n\nvoid main()\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n vec3 color = gl_FragColor.rgb;\n\n if (sepia > 0.0)\n {\n float gray = (color.x + color.y + color.z) / 3.0;\n vec3 grayscale = vec3(gray);\n\n color = Overlay(SEPIA_RGB, grayscale);\n\n color = grayscale + sepia * (color - grayscale);\n }\n\n vec2 coord = vTextureCoord * filterArea.xy / dimensions.xy;\n\n if (vignetting > 0.0)\n {\n float outter = SQRT_2 - vignetting * SQRT_2;\n vec2 dir = vec2(vec2(0.5, 0.5) - coord);\n dir.y *= dimensions.y / dimensions.x;\n float darker = clamp((outter - length(dir) * SQRT_2) / ( 0.00001 + vignettingBlur * SQRT_2), 0.0, 1.0);\n color.rgb *= darker + (1.0 - darker) * (1.0 - vignettingAlpha);\n }\n\n if (scratchDensity > seed && scratch != 0.0)\n {\n float phase = seed * 256.0;\n float s = mod(floor(phase), 2.0);\n float dist = 1.0 / scratchDensity;\n float d = distance(coord, vec2(seed * dist, abs(s - seed * dist)));\n if (d < seed * 0.6 + 0.4)\n {\n highp float period = scratchDensity * 10.0;\n\n float xx = coord.x * period + phase;\n float aa = abs(mod(xx, 0.5) * 4.0);\n float bb = mod(floor(xx / 0.5), 2.0);\n float yy = (1.0 - bb) * aa + bb * (2.0 - aa);\n\n float kk = 2.0 * period;\n float dw = scratchWidth / dimensions.x * (0.75 + seed);\n float dh = dw * kk;\n\n float tine = (yy - (2.0 - dh));\n\n if (tine > 0.0) {\n float _sign = sign(scratch);\n\n tine = s * tine / period + scratch + 0.1;\n tine = clamp(tine + 1.0, 0.5 + _sign * 0.5, 1.5 + _sign * 0.5);\n\n color.rgb *= tine;\n }\n }\n }\n\n if (noise > 0.0 && noiseSize > 0.0)\n {\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n pixelCoord.x = floor(pixelCoord.x / noiseSize);\n pixelCoord.y = floor(pixelCoord.y / noiseSize);\n // vec2 d = pixelCoord * noiseSize * vec2(1024.0 + seed * 512.0, 1024.0 - seed * 512.0);\n // float _noise = snoise(d) * 0.5;\n float _noise = rand(pixelCoord * noiseSize * seed) - 0.5;\n color += _noise * noise;\n }\n\n gl_FragColor.rgb = color;\n}\n",be=function(e){function t(t,n){void 0===n&&(n=0),e.call(this,ye,_e),this.uniforms.dimensions=new Float32Array(2),"number"==typeof t?(this.seed=t,t=null):this.seed=n,Object.assign(this,{sepia:.3,noise:.3,noiseSize:1,scratch:.5,scratchDensity:.3,scratchWidth:1,vignetting:.3,vignettingAlpha:1,vignettingBlur:.3},t)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={sepia:{configurable:!0},noise:{configurable:!0},noiseSize:{configurable:!0},scratch:{configurable:!0},scratchDensity:{configurable:!0},scratchWidth:{configurable:!0},vignetting:{configurable:!0},vignettingAlpha:{configurable:!0},vignettingBlur:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.dimensions[0]=t.filterFrame.width,this.uniforms.dimensions[1]=t.filterFrame.height,this.uniforms.seed=this.seed,e.applyFilter(this,t,n,r)},n.sepia.set=function(e){this.uniforms.sepia=e},n.sepia.get=function(){return this.uniforms.sepia},n.noise.set=function(e){this.uniforms.noise=e},n.noise.get=function(){return this.uniforms.noise},n.noiseSize.set=function(e){this.uniforms.noiseSize=e},n.noiseSize.get=function(){return this.uniforms.noiseSize},n.scratch.set=function(e){this.uniforms.scratch=e},n.scratch.get=function(){return this.uniforms.scratch},n.scratchDensity.set=function(e){this.uniforms.scratchDensity=e},n.scratchDensity.get=function(){return this.uniforms.scratchDensity},n.scratchWidth.set=function(e){this.uniforms.scratchWidth=e},n.scratchWidth.get=function(){return this.uniforms.scratchWidth},n.vignetting.set=function(e){this.uniforms.vignetting=e},n.vignetting.get=function(){return this.uniforms.vignetting},n.vignettingAlpha.set=function(e){this.uniforms.vignettingAlpha=e},n.vignettingAlpha.get=function(){return this.uniforms.vignettingAlpha},n.vignettingBlur.set=function(e){this.uniforms.vignettingBlur=e},n.vignettingBlur.get=function(){return this.uniforms.vignettingBlur},Object.defineProperties(t.prototype,n),t}(t.Filter),Ce=a,Se="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 thickness;\nuniform vec4 outlineColor;\nuniform vec4 filterClamp;\n\nconst float DOUBLE_PI = 3.14159265358979323846264 * 2.;\n\nvoid main(void) {\n vec4 ownColor = texture2D(uSampler, vTextureCoord);\n vec4 curColor;\n float maxAlpha = 0.;\n vec2 displaced;\n for (float angle = 0.; angle <= DOUBLE_PI; angle += ${angleStep}) {\n displaced.x = vTextureCoord.x + thickness.x * cos(angle);\n displaced.y = vTextureCoord.y + thickness.y * sin(angle);\n curColor = texture2D(uSampler, clamp(displaced, filterClamp.xy, filterClamp.zw));\n maxAlpha = max(maxAlpha, curColor.a);\n }\n float resultAlpha = max(maxAlpha, ownColor.a);\n gl_FragColor = vec4((ownColor.rgb + outlineColor.rgb * (1. - ownColor.a)) * resultAlpha, resultAlpha);\n}\n",Fe=function(e){function t(n,r,o){void 0===n&&(n=1),void 0===r&&(r=0),void 0===o&&(o=.1);var i=Math.max(o*t.MAX_SAMPLES,t.MIN_SAMPLES),l=(2*Math.PI/i).toFixed(7);e.call(this,Ce,Se.replace(/\$\{angleStep\}/,l)),this.uniforms.thickness=new Float32Array([0,0]),this.thickness=n,this.uniforms.outlineColor=new Float32Array([0,0,0,1]),this.color=r,this.quality=o}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={color:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.thickness[0]=this.thickness/t._frame.width,this.uniforms.thickness[1]=this.thickness/t._frame.height,e.applyFilter(this,t,n,r)},n.color.get=function(){return o.rgb2hex(this.uniforms.outlineColor)},n.color.set=function(e){o.hex2rgb(e,this.uniforms.outlineColor)},Object.defineProperties(t.prototype,n),t}(t.Filter);Fe.MIN_SAMPLES=1,Fe.MAX_SAMPLES=100;var ze=a,Ae="precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform vec2 size;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 pixelate(vec2 coord, vec2 size)\n{\n\treturn floor( coord / size ) * size;\n}\n\nvoid main(void)\n{\n vec2 coord = mapCoord(vTextureCoord);\n\n coord = pixelate(coord, size);\n\n coord = unmapCoord(coord);\n\n gl_FragColor = texture2D(uSampler, coord);\n}\n",we=function(e){function t(t){void 0===t&&(t=10),e.call(this,ze,Ae),this.size=t}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={size:{configurable:!0}};return n.size.get=function(){return this.uniforms.size},n.size.set=function(e){"number"==typeof e&&(e=[e,e]),this.uniforms.size=e},Object.defineProperties(t.prototype,n),t}(t.Filter),Te=a,Oe="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform float uRadian;\nuniform vec2 uCenter;\nuniform float uRadius;\nuniform int uKernelSize;\n\nconst int MAX_KERNEL_SIZE = 2048;\n\nvoid main(void)\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n if (uKernelSize == 0)\n {\n gl_FragColor = color;\n return;\n }\n\n float aspect = filterArea.y / filterArea.x;\n vec2 center = uCenter.xy / filterArea.xy;\n float gradient = uRadius / filterArea.x * 0.3;\n float radius = uRadius / filterArea.x - gradient * 0.5;\n int k = uKernelSize - 1;\n\n vec2 coord = vTextureCoord;\n vec2 dir = vec2(center - coord);\n float dist = length(vec2(dir.x, dir.y * aspect));\n\n float radianStep = uRadian;\n if (radius >= 0.0 && dist > radius) {\n float delta = dist - radius;\n float gap = gradient;\n float scale = 1.0 - abs(delta / gap);\n if (scale <= 0.0) {\n gl_FragColor = color;\n return;\n }\n radianStep *= scale;\n }\n radianStep /= float(k);\n\n float s = sin(radianStep);\n float c = cos(radianStep);\n mat2 rotationMatrix = mat2(vec2(c, -s), vec2(s, c));\n\n for(int i = 0; i < MAX_KERNEL_SIZE - 1; i++) {\n if (i == k) {\n break;\n }\n\n coord -= center;\n coord.y *= aspect;\n coord = rotationMatrix * coord;\n coord.y /= aspect;\n coord += center;\n\n vec4 sample = texture2D(uSampler, coord);\n\n // switch to pre-multiplied alpha to correctly blur transparent images\n // sample.rgb *= sample.a;\n\n color += sample;\n }\n\n gl_FragColor = color / float(uKernelSize);\n}\n",De=function(e){function t(t,n,r,o){void 0===t&&(t=0),void 0===n&&(n=[0,0]),void 0===r&&(r=5),void 0===o&&(o=-1),e.call(this,Te,Oe),this._angle=0,this.angle=t,this.center=n,this.kernelSize=r,this.radius=o}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={angle:{configurable:!0},center:{configurable:!0},radius:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.uKernelSize=0!==this._angle?this.kernelSize:0,e.applyFilter(this,t,n,r)},n.angle.set=function(e){this._angle=e,this.uniforms.uRadian=e*Math.PI/180},n.angle.get=function(){return this._angle},n.center.get=function(){return this.uniforms.uCenter},n.center.set=function(e){this.uniforms.uCenter=e},n.radius.get=function(){return this.uniforms.uRadius},n.radius.set=function(e){(e<0||e===1/0)&&(e=-1),this.uniforms.uRadius=e},Object.defineProperties(t.prototype,n),t}(t.Filter),Pe=a,Me="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\n\nuniform bool mirror;\nuniform float boundary;\nuniform vec2 amplitude;\nuniform vec2 waveLength;\nuniform vec2 alpha;\nuniform float time;\n\nfloat rand(vec2 co) {\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main(void)\n{\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n vec2 coord = pixelCoord / dimensions;\n\n if (coord.y < boundary) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n\n float k = (coord.y - boundary) / (1. - boundary + 0.0001);\n float areaY = boundary * dimensions.y / filterArea.y;\n float v = areaY + areaY - vTextureCoord.y;\n float y = mirror ? v : vTextureCoord.y;\n\n float _amplitude = ((amplitude.y - amplitude.x) * k + amplitude.x ) / filterArea.x;\n float _waveLength = ((waveLength.y - waveLength.x) * k + waveLength.x) / filterArea.y;\n float _alpha = (alpha.y - alpha.x) * k + alpha.x;\n\n float x = vTextureCoord.x + cos(v * 6.28 / _waveLength - time) * _amplitude;\n x = clamp(x, filterClamp.x, filterClamp.z);\n\n vec4 color = texture2D(uSampler, vec2(x, y));\n\n gl_FragColor = color * _alpha;\n}\n",Re=function(e){function t(t){e.call(this,Pe,Me),this.uniforms.amplitude=new Float32Array(2),this.uniforms.waveLength=new Float32Array(2),this.uniforms.alpha=new Float32Array(2),this.uniforms.dimensions=new Float32Array(2),Object.assign(this,{mirror:!0,boundary:.5,amplitude:[0,20],waveLength:[30,100],alpha:[1,1],time:0},t)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={mirror:{configurable:!0},boundary:{configurable:!0},amplitude:{configurable:!0},waveLength:{configurable:!0},alpha:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.dimensions[0]=t.filterFrame.width,this.uniforms.dimensions[1]=t.filterFrame.height,this.uniforms.time=this.time,e.applyFilter(this,t,n,r)},n.mirror.set=function(e){this.uniforms.mirror=e},n.mirror.get=function(){return this.uniforms.mirror},n.boundary.set=function(e){this.uniforms.boundary=e},n.boundary.get=function(){return this.uniforms.boundary},n.amplitude.set=function(e){this.uniforms.amplitude[0]=e[0],this.uniforms.amplitude[1]=e[1]},n.amplitude.get=function(){return this.uniforms.amplitude},n.waveLength.set=function(e){this.uniforms.waveLength[0]=e[0],this.uniforms.waveLength[1]=e[1]},n.waveLength.get=function(){return this.uniforms.waveLength},n.alpha.set=function(e){this.uniforms.alpha[0]=e[0],this.uniforms.alpha[1]=e[1]},n.alpha.get=function(){return this.uniforms.alpha},Object.defineProperties(t.prototype,n),t}(t.Filter),ke=a,je="precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\nuniform vec2 red;\nuniform vec2 green;\nuniform vec2 blue;\n\nvoid main(void)\n{\n gl_FragColor.r = texture2D(uSampler, vTextureCoord + red/filterArea.xy).r;\n gl_FragColor.g = texture2D(uSampler, vTextureCoord + green/filterArea.xy).g;\n gl_FragColor.b = texture2D(uSampler, vTextureCoord + blue/filterArea.xy).b;\n gl_FragColor.a = texture2D(uSampler, vTextureCoord).a;\n}\n",Ee=function(e){function t(t,n,r){void 0===t&&(t=[-10,0]),void 0===n&&(n=[0,10]),void 0===r&&(r=[0,0]),e.call(this,ke,je),this.red=t,this.green=n,this.blue=r}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={red:{configurable:!0},green:{configurable:!0},blue:{configurable:!0}};return n.red.get=function(){return this.uniforms.red},n.red.set=function(e){this.uniforms.red=e},n.green.get=function(){return this.uniforms.green},n.green.set=function(e){this.uniforms.green=e},n.blue.get=function(){return this.uniforms.blue},n.blue.set=function(e){this.uniforms.blue=e},Object.defineProperties(t.prototype,n),t}(t.Filter),Le=a,Ie="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\n\nuniform vec2 center;\n\nuniform float amplitude;\nuniform float wavelength;\n// uniform float power;\nuniform float brightness;\nuniform float speed;\nuniform float radius;\n\nuniform float time;\n\nconst float PI = 3.14159;\n\nvoid main()\n{\n float halfWavelength = wavelength * 0.5 / filterArea.x;\n float maxRadius = radius / filterArea.x;\n float currentRadius = time * speed / filterArea.x;\n\n float fade = 1.0;\n\n if (maxRadius > 0.0) {\n if (currentRadius > maxRadius) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n fade = 1.0 - pow(currentRadius / maxRadius, 2.0);\n }\n\n vec2 dir = vec2(vTextureCoord - center / filterArea.xy);\n dir.y *= filterArea.y / filterArea.x;\n float dist = length(dir);\n\n if (dist <= 0.0 || dist < currentRadius - halfWavelength || dist > currentRadius + halfWavelength) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n\n vec2 diffUV = normalize(dir);\n\n float diff = (dist - currentRadius) / halfWavelength;\n\n float p = 1.0 - pow(abs(diff), 2.0);\n\n // float powDiff = diff * pow(p, 2.0) * ( amplitude * fade );\n float powDiff = 1.25 * sin(diff * PI) * p * ( amplitude * fade );\n\n vec2 offset = diffUV * powDiff / filterArea.xy;\n\n // Do clamp :\n vec2 coord = vTextureCoord + offset;\n vec2 clampedCoord = clamp(coord, filterClamp.xy, filterClamp.zw);\n vec4 color = texture2D(uSampler, clampedCoord);\n if (coord != clampedCoord) {\n color *= max(0.0, 1.0 - length(coord - clampedCoord));\n }\n\n // No clamp :\n // gl_FragColor = texture2D(uSampler, vTextureCoord + offset);\n\n color.rgb *= 1.0 + (brightness - 1.0) * p * fade;\n\n gl_FragColor = color;\n}\n",Xe=function(e){function t(t,n,r){void 0===t&&(t=[0,0]),void 0===n&&(n={}),void 0===r&&(r=0),e.call(this,Le,Ie),this.center=t,Array.isArray(n)&&(console.warn("Deprecated Warning: ShockwaveFilter params Array has been changed to options Object."),n={}),n=Object.assign({amplitude:30,wavelength:160,brightness:1,speed:500,radius:-1},n),this.amplitude=n.amplitude,this.wavelength=n.wavelength,this.brightness=n.brightness,this.speed=n.speed,this.radius=n.radius,this.time=r}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={center:{configurable:!0},amplitude:{configurable:!0},wavelength:{configurable:!0},brightness:{configurable:!0},speed:{configurable:!0},radius:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.time=this.time,e.applyFilter(this,t,n,r)},n.center.get=function(){return this.uniforms.center},n.center.set=function(e){this.uniforms.center=e},n.amplitude.get=function(){return this.uniforms.amplitude},n.amplitude.set=function(e){this.uniforms.amplitude=e},n.wavelength.get=function(){return this.uniforms.wavelength},n.wavelength.set=function(e){this.uniforms.wavelength=e},n.brightness.get=function(){return this.uniforms.brightness},n.brightness.set=function(e){this.uniforms.brightness=e},n.speed.get=function(){return this.uniforms.speed},n.speed.set=function(e){this.uniforms.speed=e},n.radius.get=function(){return this.uniforms.radius},n.radius.set=function(e){this.uniforms.radius=e},Object.defineProperties(t.prototype,n),t}(t.Filter),Be=a,Ne="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform sampler2D uLightmap;\nuniform vec4 filterArea;\nuniform vec2 dimensions;\nuniform vec4 ambientColor;\nvoid main() {\n vec4 diffuseColor = texture2D(uSampler, vTextureCoord);\n vec2 lightCoord = (vTextureCoord * filterArea.xy) / dimensions;\n vec4 light = texture2D(uLightmap, lightCoord);\n vec3 ambient = ambientColor.rgb * ambientColor.a;\n vec3 intensity = ambient + light.rgb;\n vec3 finalColor = diffuseColor.rgb * intensity;\n gl_FragColor = vec4(finalColor, diffuseColor.a);\n}\n",Ge=function(e){function t(t,n,r){void 0===n&&(n=0),void 0===r&&(r=1),e.call(this,Be,Ne),this.uniforms.dimensions=new Float32Array(2),this.uniforms.ambientColor=new Float32Array([0,0,0,r]),this.texture=t,this.color=n}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={texture:{configurable:!0},color:{configurable:!0},alpha:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.dimensions[0]=t.filterFrame.width,this.uniforms.dimensions[1]=t.filterFrame.height,e.applyFilter(this,t,n,r)},n.texture.get=function(){return this.uniforms.uLightmap},n.texture.set=function(e){this.uniforms.uLightmap=e},n.color.set=function(e){var t=this.uniforms.ambientColor;"number"==typeof e?(o.hex2rgb(e,t),this._color=e):(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],this._color=o.rgb2hex(t))},n.color.get=function(){return this._color},n.alpha.get=function(){return this.uniforms.ambientColor[3]},n.alpha.set=function(e){this.uniforms.ambientColor[3]=e},Object.defineProperties(t.prototype,n),t}(t.Filter),qe=a,We="varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float blur;\nuniform float gradientBlur;\nuniform vec2 start;\nuniform vec2 end;\nuniform vec2 delta;\nuniform vec2 texSize;\n\nfloat random(vec3 scale, float seed)\n{\n return fract(sin(dot(gl_FragCoord.xyz + seed, scale)) * 43758.5453 + seed);\n}\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n float total = 0.0;\n\n float offset = random(vec3(12.9898, 78.233, 151.7182), 0.0);\n vec2 normal = normalize(vec2(start.y - end.y, end.x - start.x));\n float radius = smoothstep(0.0, 1.0, abs(dot(vTextureCoord * texSize - start, normal)) / gradientBlur) * blur;\n\n for (float t = -30.0; t <= 30.0; t++)\n {\n float percent = (t + offset - 0.5) / 30.0;\n float weight = 1.0 - abs(percent);\n vec4 sample = texture2D(uSampler, vTextureCoord + delta / texSize * percent * radius);\n sample.rgb *= sample.a;\n color += sample * weight;\n total += weight;\n }\n\n color /= total;\n color.rgb /= color.a + 0.00001;\n\n gl_FragColor = color;\n}\n",Ke=function(e){function t(t,r,o,i){void 0===t&&(t=100),void 0===r&&(r=600),void 0===o&&(o=null),void 0===i&&(i=null),e.call(this,qe,We),this.uniforms.blur=t,this.uniforms.gradientBlur=r,this.uniforms.start=o||new n.Point(0,window.innerHeight/2),this.uniforms.end=i||new n.Point(600,window.innerHeight/2),this.uniforms.delta=new n.Point(30,30),this.uniforms.texSize=new n.Point(window.innerWidth,window.innerHeight),this.updateDelta()}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var r={blur:{configurable:!0},gradientBlur:{configurable:!0},start:{configurable:!0},end:{configurable:!0}};return t.prototype.updateDelta=function(){this.uniforms.delta.x=0,this.uniforms.delta.y=0},r.blur.get=function(){return this.uniforms.blur},r.blur.set=function(e){this.uniforms.blur=e},r.gradientBlur.get=function(){return this.uniforms.gradientBlur},r.gradientBlur.set=function(e){this.uniforms.gradientBlur=e},r.start.get=function(){return this.uniforms.start},r.start.set=function(e){this.uniforms.start=e,this.updateDelta()},r.end.get=function(){return this.uniforms.end},r.end.set=function(e){this.uniforms.end=e,this.updateDelta()},Object.defineProperties(t.prototype,r),t}(t.Filter),Ye=function(e){function t(){e.apply(this,arguments)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.updateDelta=function(){var e=this.uniforms.end.x-this.uniforms.start.x,t=this.uniforms.end.y-this.uniforms.start.y,n=Math.sqrt(e*e+t*t);this.uniforms.delta.x=e/n,this.uniforms.delta.y=t/n},t}(Ke),Ze=function(e){function t(){e.apply(this,arguments)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.updateDelta=function(){var e=this.uniforms.end.x-this.uniforms.start.x,t=this.uniforms.end.y-this.uniforms.start.y,n=Math.sqrt(e*e+t*t);this.uniforms.delta.x=-t/n,this.uniforms.delta.y=e/n},t}(Ke),Qe=function(e){function t(t,n,r,o){void 0===t&&(t=100),void 0===n&&(n=600),void 0===r&&(r=null),void 0===o&&(o=null),e.call(this),this.tiltShiftXFilter=new Ye(t,n,r,o),this.tiltShiftYFilter=new Ze(t,n,r,o)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={blur:{configurable:!0},gradientBlur:{configurable:!0},start:{configurable:!0},end:{configurable:!0}};return t.prototype.apply=function(e,t,n){var r=e.getFilterTexture();this.tiltShiftXFilter.apply(e,t,r),this.tiltShiftYFilter.apply(e,r,n),e.returnFilterTexture(r)},n.blur.get=function(){return this.tiltShiftXFilter.blur},n.blur.set=function(e){this.tiltShiftXFilter.blur=this.tiltShiftYFilter.blur=e},n.gradientBlur.get=function(){return this.tiltShiftXFilter.gradientBlur},n.gradientBlur.set=function(e){this.tiltShiftXFilter.gradientBlur=this.tiltShiftYFilter.gradientBlur=e},n.start.get=function(){return this.tiltShiftXFilter.start},n.start.set=function(e){this.tiltShiftXFilter.start=this.tiltShiftYFilter.start=e},n.end.get=function(){return this.tiltShiftXFilter.end},n.end.set=function(e){this.tiltShiftXFilter.end=this.tiltShiftYFilter.end=e},Object.defineProperties(t.prototype,n),t}(t.Filter),Ue=a,Ve="varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float radius;\nuniform float angle;\nuniform vec2 offset;\nuniform vec4 filterArea;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 twist(vec2 coord)\n{\n coord -= offset;\n\n float dist = length(coord);\n\n if (dist < radius)\n {\n float ratioDist = (radius - dist) / radius;\n float angleMod = ratioDist * ratioDist * angle;\n float s = sin(angleMod);\n float c = cos(angleMod);\n coord = vec2(coord.x * c - coord.y * s, coord.x * s + coord.y * c);\n }\n\n coord += offset;\n\n return coord;\n}\n\nvoid main(void)\n{\n\n vec2 coord = mapCoord(vTextureCoord);\n\n coord = twist(coord);\n\n coord = unmapCoord(coord);\n\n gl_FragColor = texture2D(uSampler, coord );\n\n}\n",He=function(e){function t(t,n,r){void 0===t&&(t=200),void 0===n&&(n=4),void 0===r&&(r=20),e.call(this,Ue,Ve),this.radius=t,this.angle=n,this.padding=r}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={offset:{configurable:!0},radius:{configurable:!0},angle:{configurable:!0}};return n.offset.get=function(){return this.uniforms.offset},n.offset.set=function(e){this.uniforms.offset=e},n.radius.get=function(){return this.uniforms.radius},n.radius.set=function(e){this.uniforms.radius=e},n.angle.get=function(){return this.uniforms.angle},n.angle.set=function(e){this.uniforms.angle=e},Object.defineProperties(t.prototype,n),t}(t.Filter),$e=a,Je="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform vec2 uCenter;\nuniform float uStrength;\nuniform float uInnerRadius;\nuniform float uRadius;\n\nconst float MAX_KERNEL_SIZE = 32.0;\n\n// author: http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/\nhighp float rand(vec2 co, float seed) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot(co + seed, vec2(a, b)), sn = mod(dt, 3.14159);\n return fract(sin(sn) * c + seed);\n}\n\nvoid main() {\n\n float minGradient = uInnerRadius * 0.3;\n float innerRadius = (uInnerRadius + minGradient * 0.5) / filterArea.x;\n\n float gradient = uRadius * 0.3;\n float radius = (uRadius - gradient * 0.5) / filterArea.x;\n\n float countLimit = MAX_KERNEL_SIZE;\n\n vec2 dir = vec2(uCenter.xy / filterArea.xy - vTextureCoord);\n float dist = length(vec2(dir.x, dir.y * filterArea.y / filterArea.x));\n\n float strength = uStrength;\n\n float delta = 0.0;\n float gap;\n if (dist < innerRadius) {\n delta = innerRadius - dist;\n gap = minGradient;\n } else if (radius >= 0.0 && dist > radius) { // radius < 0 means it's infinity\n delta = dist - radius;\n gap = gradient;\n }\n\n if (delta > 0.0) {\n float normalCount = gap / filterArea.x;\n delta = (normalCount - delta) / normalCount;\n countLimit *= delta;\n strength *= delta;\n if (countLimit < 1.0)\n {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n }\n\n // randomize the lookup values to hide the fixed number of samples\n float offset = rand(vTextureCoord, 0.0);\n\n float total = 0.0;\n vec4 color = vec4(0.0);\n\n dir *= strength;\n\n for (float t = 0.0; t < MAX_KERNEL_SIZE; t++) {\n float percent = (t + offset) / MAX_KERNEL_SIZE;\n float weight = 4.0 * (percent - percent * percent);\n vec2 p = vTextureCoord + dir * percent;\n vec4 sample = texture2D(uSampler, p);\n\n // switch to pre-multiplied alpha to correctly blur transparent images\n // sample.rgb *= sample.a;\n\n color += sample * weight;\n total += weight;\n\n if (t > countLimit){\n break;\n }\n }\n\n color /= total;\n // switch back from pre-multiplied alpha\n // color.rgb /= color.a + 0.00001;\n\n gl_FragColor = color;\n}\n",et=function(e){function t(t){if(e.call(this,$e,Je),"object"!=typeof t){var n=arguments[0],r=arguments[1],o=arguments[2],i=arguments[3];t={},void 0!==n&&(t.strength=n),void 0!==r&&(t.center=r),void 0!==o&&(t.innerRadius=o),void 0!==i&&(t.radius=i)}Object.assign(this,{strength:.1,center:[0,0],innerRadius:0,radius:-1},t)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={center:{configurable:!0},strength:{configurable:!0},innerRadius:{configurable:!0},radius:{configurable:!0}};return n.center.get=function(){return this.uniforms.uCenter},n.center.set=function(e){this.uniforms.uCenter=e},n.strength.get=function(){return this.uniforms.uStrength},n.strength.set=function(e){this.uniforms.uStrength=e},n.innerRadius.get=function(){return this.uniforms.uInnerRadius},n.innerRadius.set=function(e){this.uniforms.uInnerRadius=e},n.radius.get=function(){return this.uniforms.uRadius},n.radius.set=function(e){(e<0||e===1/0)&&(e=-1),this.uniforms.uRadius=e},Object.defineProperties(t.prototype,n),t}(t.Filter);return e.AdjustmentFilter=c,e.AdvancedBloomFilter=y,e.AsciiFilter=C,e.BevelFilter=z,e.BloomFilter=A,e.BulgePinchFilter=O,e.CRTFilter=Z,e.ColorMapFilter=M,e.ColorOverlayFilter=j,e.ColorReplaceFilter=I,e.ConvolutionFilter=N,e.CrossHatchFilter=W,e.DotFilter=V,e.DropShadowFilter=J,e.EmbossFilter=ne,e.GlitchFilter=ie,e.GlowFilter=ae,e.GodrayFilter=he,e.KawaseBlurFilter=d,e.MotionBlurFilter=me,e.MultiColorReplaceFilter=xe,e.OldFilmFilter=be,e.OutlineFilter=Fe,e.PixelateFilter=we,e.RGBSplitFilter=Ee,e.RadialBlurFilter=De,e.ReflectionFilter=Re,e.ShockwaveFilter=Xe,e.SimpleLightmapFilter=Ge,e.TiltShiftAxisFilter=Ke,e.TiltShiftFilter=Qe,e.TiltShiftXFilter=Ye,e.TiltShiftYFilter=Ze,e.TwistFilter=He,e.ZoomBlurFilter=et,e}({},PIXI,PIXI,PIXI,PIXI.utils,PIXI,PIXI.filters,PIXI.filters);Object.assign(PIXI.filters,__filters); +//# sourceMappingURL=pixi-filters.js.map diff --git a/js/pixi-layers/.DS_Store b/js/pixi-layers/.DS_Store new file mode 100644 index 0000000..054a6f4 Binary files /dev/null and b/js/pixi-layers/.DS_Store differ diff --git a/js/pixi-layers/0.1.7.2/pixi-layers.js b/js/pixi-layers/0.1.7.2/pixi-layers.js new file mode 100644 index 0000000..e01f6d3 --- /dev/null +++ b/js/pixi-layers/0.1.7.2/pixi-layers.js @@ -0,0 +1,726 @@ +var pixi_display; +(function (pixi_display) { + Object.assign(PIXI.Container.prototype, { + renderWebGL: function (renderer) { + if (this._activeParentLayer && this._activeParentLayer != renderer._activeLayer) { + return; + } + if (!this.visible) { + this.displayOrder = 0; + return; + } + this.displayOrder = renderer.incDisplayOrder(); + if (this.worldAlpha <= 0 || !this.renderable) { + return; + } + this.containerRenderWebGL(renderer); + }, + renderCanvas: function (renderer) { + if (this._activeParentLayer && this._activeParentLayer != renderer._activeLayer) { + return; + } + if (!this.visible) { + this.displayOrder = 0; + return; + } + this.displayOrder = renderer.incDisplayOrder(); + if (this.worldAlpha <= 0 || !this.renderable) { + return; + } + this.containerRenderCanvas(renderer); + }, + containerRenderWebGL: PIXI.Container.prototype.renderWebGL, + containerRenderCanvas: PIXI.Container.prototype.renderCanvas + }); +})(pixi_display || (pixi_display = {})); +Object.assign(PIXI.DisplayObject.prototype, { + parentLayer: null, + _activeParentLayer: null, + parentGroup: null, + zOrder: 0, + zIndex: 0, + updateOrder: 0, + displayOrder: 0, + layerableChildren: true +}); +if (PIXI.particles && PIXI.particles.ParticleContainer) { + PIXI.particles.ParticleContainer.prototype.layerableChildren = false; +} +else if (PIXI.ParticleContainer) { + PIXI.ParticleContainer.prototype.layerableChildren = false; +} +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var pixi_display; +(function (pixi_display) { + var utils = PIXI.utils; + var Group = (function (_super) { + __extends(Group, _super); + function Group(zIndex, sorting) { + var _this = _super.call(this) || this; + _this._activeLayer = null; + _this._activeStage = null; + _this._activeChildren = []; + _this._lastUpdateId = -1; + _this.useRenderTexture = false; + _this.useDoubleBuffer = false; + _this.sortPriority = 0; + _this.clearColor = new Float32Array([0, 0, 0, 0]); + _this.canDrawWithoutLayer = false; + _this.canDrawInParentStage = true; + _this.zIndex = 0; + _this.enableSort = false; + _this._tempResult = []; + _this._tempZero = []; + _this.useZeroOptimization = false; + _this.zIndex = zIndex; + _this.enableSort = !!sorting; + if (typeof sorting === 'function') { + _this.on('sort', sorting); + } + return _this; + } + Group.prototype.doSort = function (layer, sorted) { + if (this.listeners('sort', true)) { + for (var i = 0; i < sorted.length; i++) { + this.emit('sort', sorted[i]); + } + } + if (this.useZeroOptimization) { + this.doSortWithZeroOptimization(layer, sorted); + } + else { + sorted.sort(Group.compareZIndex); + } + }; + Group.compareZIndex = function (a, b) { + if (a.zIndex !== b.zIndex) { + return a.zIndex - b.zIndex; + } + if (a.zOrder > b.zOrder) { + return -1; + } + if (a.zOrder < b.zOrder) { + return 1; + } + return a.updateOrder - b.updateOrder; + }; + Group.prototype.doSortWithZeroOptimization = function (layer, sorted) { + throw new Error("not implemented yet"); + }; + Group.prototype.clear = function () { + this._activeLayer = null; + this._activeStage = null; + this._activeChildren.length = 0; + }; + Group.prototype.addDisplayObject = function (stage, displayObject) { + this.check(stage); + displayObject._activeParentLayer = this._activeLayer; + if (this._activeLayer) { + this._activeLayer._activeChildren.push(displayObject); + } + else { + this._activeChildren.push(displayObject); + } + }; + Group.prototype.foundLayer = function (stage, layer) { + this.check(stage); + if (this._activeLayer != null) { + Group.conflict(); + } + this._activeLayer = layer; + this._activeStage = stage; + }; + Group.prototype.foundStage = function (stage) { + if (!this._activeLayer && !this.canDrawInParentStage) { + this.clear(); + } + }; + Group.prototype.check = function (stage) { + if (this._lastUpdateId < Group._layerUpdateId) { + this._lastUpdateId = Group._layerUpdateId; + this.clear(); + this._activeStage = stage; + } + else if (this.canDrawInParentStage) { + var current = this._activeStage; + while (current && current != stage) { + current = current._activeParentStage; + } + this._activeStage = current; + if (current == null) { + this.clear(); + return; + } + } + }; + Group.conflict = function () { + if (Group._lastLayerConflict + 5000 < Date.now()) { + Group._lastLayerConflict = Date.now(); + console.log("PIXI-display plugin found two layers with the same group in one stage - that's not healthy. Please place a breakpoint here and debug it"); + } + }; + Group._layerUpdateId = 0; + Group._lastLayerConflict = 0; + return Group; + }(utils.EventEmitter)); + pixi_display.Group = Group; +})(pixi_display || (pixi_display = {})); +var pixi_display; +(function (pixi_display) { + var InteractionManager = PIXI.interaction.InteractionManager; + Object.assign(InteractionManager.prototype, { + _queue: [[], []], + _displayProcessInteractive: function (point, displayObject, hitTestOrder, interactive, outOfMask) { + if (!displayObject || !displayObject.visible) { + return 0; + } + var hit = 0, interactiveParent = interactive = displayObject.interactive || interactive; + if (displayObject.hitArea) { + interactiveParent = false; + } + if (displayObject._activeParentLayer) { + outOfMask = false; + } + var mask = displayObject._mask; + if (hitTestOrder < Infinity && mask) { + if (!mask.containsPoint(point)) { + outOfMask = true; + } + } + if (hitTestOrder < Infinity && displayObject.filterArea) { + if (!displayObject.filterArea.contains(point.x, point.y)) { + outOfMask = true; + } + } + var children = displayObject.children; + if (displayObject.interactiveChildren && children) { + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + var hitChild = this._displayProcessInteractive(point, child, hitTestOrder, interactiveParent, outOfMask); + if (hitChild) { + if (!child.parent) { + continue; + } + hit = hitChild; + hitTestOrder = hitChild; + } + } + } + if (interactive) { + if (!outOfMask) { + if (hitTestOrder < displayObject.displayOrder) { + if (displayObject.hitArea) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hit = displayObject.displayOrder; + } + } + else if (displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = displayObject.displayOrder; + } + } + } + if (displayObject.interactive) { + this._queueAdd(displayObject, hit === Infinity ? 0 : hit); + } + } + else { + if (displayObject.interactive) { + this._queueAdd(displayObject, 0); + } + } + } + return hit; + }, + processInteractive: function (strangeStuff, displayObject, func, hitTest, interactive) { + var interactionEvent = null; + var point = null; + if (strangeStuff.data && + strangeStuff.data.global) { + interactionEvent = strangeStuff; + point = interactionEvent.data.global; + } + else { + point = strangeStuff; + } + this._startInteractionProcess(); + this._displayProcessInteractive(point, displayObject, hitTest ? 0 : Infinity, false); + this._finishInteractionProcess(interactionEvent, func); + }, + _startInteractionProcess: function () { + this._eventDisplayOrder = 1; + if (!this._queue) { + this._queue = [[], []]; + } + this._queue[0].length = 0; + this._queue[1].length = 0; + }, + _queueAdd: function (displayObject, order) { + var queue = this._queue; + if (order < this._eventDisplayOrder) { + queue[0].push(displayObject); + } + else { + if (order > this._eventDisplayOrder) { + this._eventDisplayOrder = order; + var q = queue[1]; + for (var i = 0; i < q.length; i++) { + queue[0].push(q[i]); + } + queue[1].length = 0; + } + queue[1].push(displayObject); + } + }, + _finishInteractionProcess: function (event, func) { + var queue = this._queue; + var q = queue[0]; + var i = 0; + for (; i < q.length; i++) { + if (event) { + if (func) { + func(event, q[i], false); + } + } + else { + func(q[i], false); + } + } + q = queue[1]; + for (i = 0; i < q.length; i++) { + if (event) { + if (!event.target) { + event.target = q[i]; + } + if (func) { + func(event, q[i], true); + } + } + else { + func(q[i], true); + } + } + } + }); +})(pixi_display || (pixi_display = {})); +var pixi_display; +(function (pixi_display) { + var LayerTextureCache = (function () { + function LayerTextureCache(layer) { + this.layer = layer; + this.renderTexture = null; + this.doubleBuffer = null; + this.currentBufferIndex = 0; + this._tempRenderTarget = null; + } + LayerTextureCache.prototype.initRenderTexture = function (renderer) { + var width = renderer ? renderer.screen.width : 100; + var height = renderer ? renderer.screen.height : 100; + var resolution = renderer ? renderer.resolution : PIXI.settings.RESOLUTION; + this.renderTexture = PIXI.RenderTexture.create(width, height, resolution); + if (this.layer.group.useDoubleBuffer) { + this.doubleBuffer = [ + PIXI.RenderTexture.create(width, height, resolution), + PIXI.RenderTexture.create(width, height, resolution) + ]; + } + }; + LayerTextureCache.prototype.getRenderTexture = function () { + if (!this.renderTexture) { + this.initRenderTexture(); + } + return this.renderTexture; + }; + LayerTextureCache.prototype.pushTexture = function (renderer) { + var screen = renderer.screen; + if (!this.renderTexture) { + this.initRenderTexture(renderer); + } + var rt = this.renderTexture; + var group = this.layer.group; + var db = this.doubleBuffer; + if (rt.width !== screen.width || + rt.height !== screen.height || + rt.baseTexture.resolution !== renderer.resolution) { + rt.baseTexture.resolution = renderer.resolution; + rt.resize(screen.width, screen.height); + if (db) { + db[0].baseTexture.resolution = renderer.resolution; + db[0].resize(screen.width, screen.height); + db[1].baseTexture.resolution = renderer.resolution; + db[1].resize(screen.width, screen.height); + } + } + this._tempRenderTarget = renderer._activeRenderTarget; + renderer.currentRenderer.flush(); + if (group.useDoubleBuffer) { + var buffer = db[this.currentBufferIndex]; + if (!buffer.baseTexture._glTextures[renderer.CONTEXT_UID]) { + renderer.bindRenderTexture(buffer, null); + if (group.clearColor) { + renderer.clear(group.clearColor); + } + } + renderer.unbindTexture(rt); + rt.baseTexture._glTextures = buffer.baseTexture._glTextures; + rt.baseTexture._glRenderTargets = buffer.baseTexture._glRenderTargets; + this.currentBufferIndex = 1 - this.currentBufferIndex; + buffer = db[this.currentBufferIndex]; + renderer.bindRenderTexture(buffer, null); + } + else { + renderer.bindRenderTexture(rt, undefined); + } + if (group.clearColor) { + renderer.clear(group.clearColor); + } + }; + LayerTextureCache.prototype.popTexture = function (renderer) { + renderer.currentRenderer.flush(); + renderer.bindRenderTarget(this._tempRenderTarget); + this._tempRenderTarget = null; + }; + LayerTextureCache.prototype.destroy = function () { + if (this.renderTexture) { + this.renderTexture.destroy(); + if (this.doubleBuffer) { + this.doubleBuffer[0].destroy(true); + this.doubleBuffer[1].destroy(true); + } + } + }; + return LayerTextureCache; + }()); + pixi_display.LayerTextureCache = LayerTextureCache; + var Layer = (function (_super) { + __extends(Layer, _super); + function Layer(group) { + if (group === void 0) { group = null; } + var _this = _super.call(this) || this; + _this.isLayer = true; + _this.group = null; + _this._activeChildren = []; + _this._tempChildren = null; + _this._activeStageParent = null; + _this._sortedChildren = []; + _this._tempLayerParent = null; + _this.insertChildrenBeforeActive = true; + _this.insertChildrenAfterActive = true; + if (group != null) { + _this.group = group; + _this.zIndex = group.zIndex; + } + else { + _this.group = new pixi_display.Group(0, false); + } + _this._tempChildren = _this.children; + return _this; + } + Layer.prototype.beginWork = function (stage) { + var active = this._activeChildren; + this._activeStageParent = stage; + this.group.foundLayer(stage, this); + var groupChildren = this.group._activeChildren; + active.length = 0; + for (var i = 0; i < groupChildren.length; i++) { + groupChildren[i]._activeParentLayer = this; + active.push(groupChildren[i]); + } + groupChildren.length = 0; + }; + Layer.prototype.endWork = function () { + var children = this.children; + var active = this._activeChildren; + var sorted = this._sortedChildren; + for (var i = 0; i < active.length; i++) { + this.emit("display", active[i]); + } + sorted.length = 0; + if (this.insertChildrenBeforeActive) { + for (var i = 0; i < children.length; i++) { + sorted.push(children[i]); + } + } + for (var i = 0; i < active.length; i++) { + sorted.push(active[i]); + } + if (!this.insertChildrenBeforeActive && + this.insertChildrenAfterActive) { + for (var i = 0; i < children.length; i++) { + sorted.push(children[i]); + } + } + if (this.group.enableSort) { + this.doSort(); + } + }; + Object.defineProperty(Layer.prototype, "useRenderTexture", { + get: function () { + return this.group.useRenderTexture; + }, + set: function (value) { + this.group.useRenderTexture = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Layer.prototype, "useDoubleBuffer", { + get: function () { + return this.group.useDoubleBuffer; + }, + set: function (value) { + this.group.useDoubleBuffer = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Layer.prototype, "clearColor", { + get: function () { + return this.group.clearColor; + }, + set: function (value) { + this.group.clearColor = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Layer.prototype, "sortPriority", { + get: function () { + return this.group.sortPriority; + }, + set: function (value) { + this.group.sortPriority = value; + }, + enumerable: true, + configurable: true + }); + Layer.prototype.getRenderTexture = function () { + if (!this.textureCache) { + this.textureCache = new LayerTextureCache(this); + } + return this.textureCache.getRenderTexture(); + }; + Layer.prototype.updateDisplayLayers = function () { + }; + Layer.prototype.doSort = function () { + this.group.doSort(this, this._sortedChildren); + }; + Layer.prototype._preRender = function (renderer) { + if (this._activeParentLayer && this._activeParentLayer != renderer._activeLayer) { + return false; + } + if (!this.visible) { + this.displayOrder = 0; + return false; + } + this.displayOrder = renderer.incDisplayOrder(); + if (this.worldAlpha <= 0 || !this.renderable) { + return false; + } + if (this.children !== this._sortedChildren && + this._tempChildren != this.children) { + this._tempChildren = this.children; + } + this._boundsID++; + this.children = this._sortedChildren; + this._tempLayerParent = renderer._activeLayer; + renderer._activeLayer = this; + return true; + }; + Layer.prototype._postRender = function (renderer) { + this.children = this._tempChildren; + renderer._activeLayer = this._tempLayerParent; + this._tempLayerParent = null; + }; + Layer.prototype.renderWebGL = function (renderer) { + if (!this._preRender(renderer)) { + return; + } + if (this.group.useRenderTexture) { + if (!this.textureCache) { + this.textureCache = new LayerTextureCache(this); + } + this.textureCache.pushTexture(renderer); + } + this.containerRenderWebGL(renderer); + this._postRender(renderer); + if (this.group.useRenderTexture) { + this.textureCache.popTexture(renderer); + } + }; + Layer.prototype.renderCanvas = function (renderer) { + if (this._preRender(renderer)) { + this.containerRenderCanvas(renderer); + this._postRender(renderer); + } + }; + Layer.prototype.destroy = function (options) { + if (this.textureCache) { + this.textureCache.destroy(); + this.textureCache = null; + } + _super.prototype.destroy.call(this, options); + }; + return Layer; + }(PIXI.Container)); + pixi_display.Layer = Layer; +})(pixi_display || (pixi_display = {})); +var pixi_display; +(function (pixi_display) { + var Stage = (function (_super) { + __extends(Stage, _super); + function Stage() { + var _this = _super.call(this) || this; + _this.isStage = true; + _this._tempGroups = []; + _this._activeLayers = []; + _this._activeParentStage = null; + return _this; + } + Stage.prototype.clear = function () { + this._activeLayers.length = 0; + this._tempGroups.length = 0; + }; + Stage.prototype.destroy = function (options) { + this.clear(); + _super.prototype.destroy.call(this, options); + }; + Stage.prototype._addRecursive = function (displayObject) { + if (!displayObject.visible) { + return; + } + if (displayObject.isLayer) { + var layer_1 = displayObject; + this._activeLayers.push(layer_1); + layer_1.beginWork(this); + } + if (displayObject != this && displayObject.isStage) { + var stage = displayObject; + stage.updateAsChildStage(this); + return; + } + var group = displayObject.parentGroup; + if (group !== null) { + group.addDisplayObject(this, displayObject); + } + var layer = displayObject.parentLayer; + if (layer !== null) { + group = layer.group; + group.addDisplayObject(this, displayObject); + } + displayObject.updateOrder = ++Stage._updateOrderCounter; + if (displayObject.alpha <= 0 || !displayObject.renderable + || !displayObject.layerableChildren + || group && group.sortPriority) { + return; + } + var children = displayObject.children; + if (children && children.length) { + for (var i = 0; i < children.length; i++) { + this._addRecursive(children[i]); + } + } + }; + Stage.prototype._addRecursiveChildren = function (displayObject) { + if (displayObject.alpha <= 0 || !displayObject.renderable + || !displayObject.layerableChildren) { + return; + } + var children = displayObject.children; + if (children && children.length) { + for (var i = 0; i < children.length; i++) { + this._addRecursive(children[i]); + } + } + }; + Stage.prototype._updateStageInner = function () { + this.clear(); + this._addRecursive(this); + var layers = this._activeLayers; + for (var i = 0; i < layers.length; i++) { + var layer = layers[i]; + if (layer.group.sortPriority) { + layer.endWork(); + var sorted = layer._sortedChildren; + for (var j = 0; j < sorted.length; j++) { + this._addRecursiveChildren(sorted[j]); + } + } + } + for (var i = 0; i < layers.length; i++) { + var layer = layers[i]; + if (!layer.group.sortPriority) { + layer.endWork(); + } + } + }; + Stage.prototype.updateAsChildStage = function (stage) { + this._activeParentStage = stage; + Stage._updateOrderCounter = 0; + this._updateStageInner(); + }; + Stage.prototype.updateStage = function () { + this._activeParentStage = null; + pixi_display.Group._layerUpdateId++; + this._updateStageInner(); + }; + ; + Stage._updateOrderCounter = 0; + return Stage; + }(pixi_display.Layer)); + pixi_display.Stage = Stage; +})(pixi_display || (pixi_display = {})); +var pixi_display; +(function (pixi_display) { + Object.assign(PIXI.WebGLRenderer.prototype, { + _lastDisplayOrder: 0, + _activeLayer: null, + incDisplayOrder: function () { + return ++this._lastDisplayOrder; + }, + _oldRender: PIXI.WebGLRenderer.prototype.render, + render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!renderTexture) { + this._lastDisplayOrder = 0; + } + this._activeLayer = null; + if (displayObject.isStage) { + displayObject.updateStage(); + } + this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform); + } + }); + Object.assign(PIXI.CanvasRenderer.prototype, { + _lastDisplayOrder: 0, + _activeLayer: null, + incDisplayOrder: function () { + return ++this._lastDisplayOrder; + }, + _oldRender: PIXI.CanvasRenderer.prototype.render, + render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!renderTexture) { + this._lastDisplayOrder = 0; + } + this._activeLayer = null; + if (displayObject.isStage) { + displayObject.updateStage(); + } + this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform); + } + }); +})(pixi_display || (pixi_display = {})); +var pixi_display; +(function (pixi_display) { + PIXI.display = pixi_display; +})(pixi_display || (pixi_display = {})); +//# sourceMappingURL=pixi-layers.js.map \ No newline at end of file diff --git a/js/pixi-layers/0.1.7/pixi-layers.js b/js/pixi-layers/0.1.7/pixi-layers.js new file mode 100644 index 0000000..c731f42 --- /dev/null +++ b/js/pixi-layers/0.1.7/pixi-layers.js @@ -0,0 +1,611 @@ +var pixi_display; +(function (pixi_display) { + Object.assign(PIXI.Container.prototype, { + renderWebGL: function (renderer) { + if (this._activeParentLayer && this._activeParentLayer != renderer._activeLayer) { + return; + } + if (!this.visible) { + this.displayOrder = 0; + return; + } + this.displayOrder = renderer.incDisplayOrder(); + if (this.worldAlpha <= 0 || !this.renderable) { + return; + } + this.containerRenderWebGL(renderer); + }, + renderCanvas: function (renderer) { + if (this._activeParentLayer && this._activeParentLayer != renderer._activeLayer) { + return; + } + if (!this.visible) { + this.displayOrder = 0; + return; + } + this.displayOrder = renderer.incDisplayOrder(); + if (this.worldAlpha <= 0 || !this.renderable) { + return; + } + this.containerRenderCanvas(renderer); + }, + containerRenderWebGL: PIXI.Container.prototype.renderWebGL, + containerRenderCanvas: PIXI.Container.prototype.renderCanvas + }); +})(pixi_display || (pixi_display = {})); +Object.assign(PIXI.DisplayObject.prototype, { + parentLayer: null, + _activeParentLayer: null, + parentGroup: null, + zOrder: 0, + zIndex: 0, + updateOrder: 0, + displayOrder: 0, + layerableChildren: true +}); +if (PIXI.particles && PIXI.particles.ParticleContainer) { + PIXI.particles.ParticleContainer.prototype.layerableChildren = false; +} +else if (PIXI.ParticleContainer) { + PIXI.ParticleContainer.prototype.layerableChildren = false; +} +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var pixi_display; +(function (pixi_display) { + var utils = PIXI.utils; + var Group = (function (_super) { + __extends(Group, _super); + function Group(zIndex, sorting) { + var _this = _super.call(this) || this; + _this._activeLayer = null; + _this._activeStage = null; + _this._activeChildren = []; + _this._lastUpdateId = -1; + _this.useRenderTexture = false; + _this.clearColor = new Float32Array([0, 0, 0, 0]); + _this.canDrawWithoutLayer = false; + _this.canDrawInParentStage = true; + _this.zIndex = 0; + _this.enableSort = false; + _this._tempResult = []; + _this._tempZero = []; + _this.useZeroOptimization = false; + _this.zIndex = zIndex; + _this.enableSort = !!sorting; + if (typeof sorting === 'function') { + _this.on('sort', sorting); + } + return _this; + } + Group.prototype.doSort = function (layer, sorted) { + if (this.listeners('sort', true)) { + for (var i = 0; i < sorted.length; i++) { + this.emit('sort', sorted[i]); + } + } + if (this.useZeroOptimization) { + this.doSortWithZeroOptimization(layer, sorted); + } + else { + sorted.sort(Group.compareZIndex); + } + }; + Group.compareZIndex = function (a, b) { + if (a.zIndex !== b.zIndex) { + return a.zIndex - b.zIndex; + } + if (a.zOrder > b.zOrder) { + return -1; + } + if (a.zOrder < b.zOrder) { + return 1; + } + return a.updateOrder - b.updateOrder; + }; + Group.prototype.doSortWithZeroOptimization = function (layer, sorted) { + throw new Error("not implemented yet"); + }; + Group.prototype.clear = function () { + this._activeLayer = null; + this._activeStage = null; + this._activeChildren.length = 0; + }; + Group.prototype.addDisplayObject = function (stage, displayObject) { + this.check(stage); + displayObject._activeParentLayer = this._activeLayer; + if (this._activeLayer) { + this._activeLayer._activeChildren.push(displayObject); + } + else { + this._activeChildren.push(displayObject); + } + }; + Group.prototype.foundLayer = function (stage, layer) { + this.check(stage); + if (this._activeLayer != null) { + Group.conflict(); + } + this._activeLayer = layer; + this._activeStage = stage; + }; + Group.prototype.foundStage = function (stage) { + if (!this._activeLayer && !this.canDrawInParentStage) { + this.clear(); + } + }; + Group.prototype.check = function (stage) { + if (this._lastUpdateId < Group._layerUpdateId) { + this._lastUpdateId = Group._layerUpdateId; + this.clear(); + this._activeStage = stage; + } + else if (this.canDrawInParentStage) { + var current = this._activeStage; + while (current && current != stage) { + current = current._activeParentStage; + } + this._activeStage = current; + if (current == null) { + this.clear(); + return; + } + } + }; + Group.conflict = function () { + if (Group._lastLayerConflict + 5000 < Date.now()) { + Group._lastLayerConflict = Date.now(); + console.log("PIXI-display plugin found two layers with the same group in one stage - that's not healthy. Please place a breakpoint here and debug it"); + } + }; + Group._layerUpdateId = 0; + Group._lastLayerConflict = 0; + return Group; + }(utils.EventEmitter)); + pixi_display.Group = Group; +})(pixi_display || (pixi_display = {})); +var pixi_display; +(function (pixi_display) { + var InteractionManager = PIXI.interaction.InteractionManager; + Object.assign(InteractionManager.prototype, { + _queue: [[], []], + _displayProcessInteractive: function (point, displayObject, hitTestOrder, interactive, outOfMask) { + if (!displayObject || !displayObject.visible) { + return 0; + } + var hit = 0, interactiveParent = interactive = displayObject.interactive || interactive; + if (displayObject.hitArea) { + interactiveParent = false; + } + if (displayObject._activeParentLayer) { + outOfMask = false; + } + var mask = displayObject._mask; + if (hitTestOrder < Infinity && mask) { + if (!mask.containsPoint(point)) { + outOfMask = true; + } + } + if (hitTestOrder < Infinity && displayObject.filterArea) { + if (!displayObject.filterArea.contains(point.x, point.y)) { + outOfMask = true; + } + } + var children = displayObject.children; + if (displayObject.interactiveChildren && children) { + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + var hitChild = this._displayProcessInteractive(point, child, hitTestOrder, interactiveParent, outOfMask); + if (hitChild) { + if (!child.parent) { + continue; + } + hit = hitChild; + hitTestOrder = hitChild; + } + } + } + if (interactive) { + if (!outOfMask) { + if (hitTestOrder < displayObject.displayOrder) { + if (displayObject.hitArea) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hit = displayObject.displayOrder; + } + } + else if (displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = displayObject.displayOrder; + } + } + } + if (displayObject.interactive) { + this._queueAdd(displayObject, hit === Infinity ? 0 : hit); + } + } + else { + if (displayObject.interactive) { + this._queueAdd(displayObject, 0); + } + } + } + return hit; + }, + processInteractive: function (strangeStuff, displayObject, func, hitTest, interactive) { + var interactionEvent = null; + var point = null; + if (strangeStuff.data && + strangeStuff.data.global) { + interactionEvent = strangeStuff; + point = interactionEvent.data.global; + } + else { + point = strangeStuff; + } + this._startInteractionProcess(); + this._displayProcessInteractive(point, displayObject, hitTest ? 0 : Infinity, false); + this._finishInteractionProcess(interactionEvent, func); + }, + _startInteractionProcess: function () { + this._eventDisplayOrder = 1; + if (!this._queue) { + this._queue = [[], []]; + } + this._queue[0].length = 0; + this._queue[1].length = 0; + }, + _queueAdd: function (displayObject, order) { + var queue = this._queue; + if (order < this._eventDisplayOrder) { + queue[0].push(displayObject); + } + else { + if (order > this._eventDisplayOrder) { + this._eventDisplayOrder = order; + var q = queue[1]; + for (var i = 0; i < q.length; i++) { + queue[0].push(q[i]); + } + queue[1].length = 0; + } + queue[1].push(displayObject); + } + }, + _finishInteractionProcess: function (event, func) { + var queue = this._queue; + var q = queue[0]; + var i = 0; + for (; i < q.length; i++) { + if (event) { + if (func) { + func(event, q[i], false); + } + } + else { + func(q[i], false); + } + } + q = queue[1]; + for (i = 0; i < q.length; i++) { + if (event) { + if (!event.target) { + event.target = q[i]; + } + if (func) { + func(event, q[i], true); + } + } + else { + func(q[i], true); + } + } + } + }); +})(pixi_display || (pixi_display = {})); +var pixi_display; +(function (pixi_display) { + var Layer = (function (_super) { + __extends(Layer, _super); + function Layer(group) { + if (group === void 0) { group = null; } + var _this = _super.call(this) || this; + _this.isLayer = true; + _this.group = null; + _this._activeChildren = []; + _this._tempChildren = null; + _this._activeStageParent = null; + _this._sortedChildren = []; + _this._tempLayerParent = null; + _this._thisRenderTexture = null; + _this._tempRenderTarget = null; + _this.insertChildrenBeforeActive = true; + _this.insertChildrenAfterActive = true; + if (group != null) { + _this.group = group; + _this.zIndex = group.zIndex; + } + else { + _this.group = new pixi_display.Group(0, false); + } + _this._tempChildren = _this.children; + return _this; + } + Layer.prototype.beginWork = function (stage) { + var active = this._activeChildren; + this._activeStageParent = stage; + this.group.foundLayer(stage, this); + var groupChildren = this.group._activeChildren; + active.length = 0; + for (var i = 0; i < groupChildren.length; i++) { + groupChildren[i]._activeParentLayer = this; + active.push(groupChildren[i]); + } + groupChildren.length = 0; + }; + Layer.prototype.endWork = function () { + var children = this.children; + var active = this._activeChildren; + var sorted = this._sortedChildren; + for (var i = 0; i < active.length; i++) { + this.emit("display", active[i]); + } + sorted.length = 0; + if (this.insertChildrenBeforeActive) { + for (var i = 0; i < children.length; i++) { + sorted.push(children[i]); + } + } + for (var i = 0; i < active.length; i++) { + sorted.push(active[i]); + } + if (!this.insertChildrenBeforeActive && + this.insertChildrenAfterActive) { + for (var i = 0; i < children.length; i++) { + sorted.push(children[i]); + } + } + if (this.group.enableSort) { + this.doSort(); + } + }; + Object.defineProperty(Layer.prototype, "useRenderTexture", { + get: function () { + return this.group.useRenderTexture; + }, + set: function (value) { + this.group.useRenderTexture = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Layer.prototype, "clearColor", { + get: function () { + return this.group.clearColor; + }, + set: function (value) { + this.group.clearColor = value; + }, + enumerable: true, + configurable: true + }); + Layer.prototype.getRenderTexture = function () { + if (!this._thisRenderTexture) { + this._thisRenderTexture = PIXI.RenderTexture.create(100, 100); + } + return this._thisRenderTexture; + }; + Layer.prototype.updateDisplayLayers = function () { + }; + Layer.prototype.doSort = function () { + this.group.doSort(this, this._sortedChildren); + }; + Layer.prototype._preRender = function (renderer) { + if (this._activeParentLayer && this._activeParentLayer != renderer._activeLayer) { + return false; + } + if (!this.visible) { + this.displayOrder = 0; + return false; + } + this.displayOrder = renderer.incDisplayOrder(); + if (this.worldAlpha <= 0 || !this.renderable) { + return false; + } + if (this.children !== this._sortedChildren && + this._tempChildren != this.children) { + this._tempChildren = this.children; + } + this._boundsID++; + this.children = this._sortedChildren; + this._tempLayerParent = renderer._activeLayer; + renderer._activeLayer = this; + return true; + }; + Layer.prototype._postRender = function (renderer) { + this.children = this._tempChildren; + renderer._activeLayer = this._tempLayerParent; + this._tempLayerParent = null; + }; + Layer.prototype._pushTexture = function (renderer) { + var screen = renderer.screen; + if (!this._thisRenderTexture) { + this._thisRenderTexture = PIXI.RenderTexture.create(screen.width, screen.height, null, renderer.resolution); + } + var rt = this._thisRenderTexture; + if (rt.width !== screen.width || + rt.height !== screen.height || + rt.baseTexture.resolution !== renderer.resolution) { + rt.baseTexture.resolution = renderer.resolution; + rt.resize(screen.width, screen.height); + } + this._tempRenderTarget = renderer._activeRenderTarget; + renderer.currentRenderer.flush(); + renderer.bindRenderTexture(rt, undefined); + if (this.group.clearColor) { + renderer.clear(this.group.clearColor); + } + }; + Layer.prototype._popTexture = function (renderer) { + renderer.currentRenderer.flush(); + renderer.bindRenderTarget(this._tempRenderTarget); + this._tempRenderTarget = null; + }; + Layer.prototype.renderWebGL = function (renderer) { + if (!this._preRender(renderer)) { + return; + } + if (this.group.useRenderTexture) { + this._pushTexture(renderer); + } + this.containerRenderWebGL(renderer); + this._postRender(renderer); + if (this.group.useRenderTexture) { + this._popTexture(renderer); + } + }; + Layer.prototype.renderCanvas = function (renderer) { + if (this._preRender(renderer)) { + this.containerRenderCanvas(renderer); + this._postRender(renderer); + } + }; + Layer.prototype.destroy = function (options) { + if (this._thisRenderTexture) { + this._thisRenderTexture.destroy(true); + } + _super.prototype.destroy.call(this, options); + }; + return Layer; + }(PIXI.Container)); + pixi_display.Layer = Layer; +})(pixi_display || (pixi_display = {})); +var pixi_display; +(function (pixi_display) { + Object.assign(PIXI.WebGLRenderer.prototype, { + _lastDisplayOrder: 0, + _activeLayer: null, + incDisplayOrder: function () { + return ++this._lastDisplayOrder; + }, + _oldRender: PIXI.WebGLRenderer.prototype.render, + render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!renderTexture) { + this._lastDisplayOrder = 0; + } + this._activeLayer = null; + if (displayObject.isStage) { + displayObject.updateStage(); + } + this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform); + } + }); + Object.assign(PIXI.CanvasRenderer.prototype, { + _lastDisplayOrder: 0, + _activeLayer: null, + incDisplayOrder: function () { + return ++this._lastDisplayOrder; + }, + _oldRender: PIXI.CanvasRenderer.prototype.render, + render: function (displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!renderTexture) { + this._lastDisplayOrder = 0; + } + this._activeLayer = null; + if (displayObject.isStage) { + displayObject.updateStage(); + } + this._oldRender(displayObject, renderTexture, clear, transform, skipUpdateTransform); + } + }); +})(pixi_display || (pixi_display = {})); +var pixi_display; +(function (pixi_display) { + var Stage = (function (_super) { + __extends(Stage, _super); + function Stage() { + var _this = _super.call(this) || this; + _this.isStage = true; + _this._tempGroups = []; + _this._activeLayers = []; + _this._activeParentStage = null; + return _this; + } + Stage.prototype.clear = function () { + this._activeLayers.length = 0; + this._tempGroups.length = 0; + }; + Stage.prototype.destroy = function (options) { + this.clear(); + _super.prototype.destroy.call(this, options); + }; + Stage.prototype._addRecursive = function (displayObject) { + if (!displayObject.visible) { + return; + } + if (displayObject.isLayer) { + var layer_1 = displayObject; + this._activeLayers.push(layer_1); + layer_1.beginWork(this); + } + if (displayObject != this && displayObject.isStage) { + var stage = displayObject; + stage.updateAsChildStage(this); + return; + } + var group = displayObject.parentGroup; + if (group != null) { + displayObject.parentGroup.addDisplayObject(this, displayObject); + } + var layer = displayObject.parentLayer; + if (layer != null) { + layer.group.addDisplayObject(this, displayObject); + } + displayObject.updateOrder = ++Stage._updateOrderCounter; + if (displayObject.alpha <= 0 || !displayObject.renderable || !displayObject.layerableChildren) { + return; + } + var children = displayObject.children; + if (children && children.length) { + for (var i = 0; i < children.length; i++) { + this._addRecursive(children[i]); + } + } + }; + Stage.prototype._updateStageInner = function () { + this.clear(); + this._addRecursive(this); + var layers = this._activeLayers; + for (var i = 0; i < layers.length; i++) { + layers[i].endWork(); + } + }; + Stage.prototype.updateAsChildStage = function (stage) { + this._activeParentStage = stage; + Stage._updateOrderCounter = 0; + this._updateStageInner(); + }; + Stage.prototype.updateStage = function () { + this._activeParentStage = null; + pixi_display.Group._layerUpdateId++; + this._updateStageInner(); + }; + ; + Stage._updateOrderCounter = 0; + return Stage; + }(pixi_display.Layer)); + pixi_display.Stage = Stage; +})(pixi_display || (pixi_display = {})); +var pixi_display; +(function (pixi_display) { + PIXI.display = pixi_display; +})(pixi_display || (pixi_display = {})); +//# sourceMappingURL=pixi-layers.js.map \ No newline at end of file diff --git a/js/pixi-lights/.DS_Store b/js/pixi-lights/.DS_Store new file mode 100644 index 0000000..ce5f471 Binary files /dev/null and b/js/pixi-lights/.DS_Store differ diff --git a/js/pixi-lights/2.0.3/pixi-lights.js b/js/pixi-lights/2.0.3/pixi-lights.js new file mode 100644 index 0000000..0157d7b --- /dev/null +++ b/js/pixi-lights/2.0.3/pixi-lights.js @@ -0,0 +1,9 @@ +/*! + * pixi-lights - v2.0.3 + * Compiled Fri, 05 Aug 2022 19:58:51 UTC + * + * pixi-lights is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t.PIXI=t.PIXI||{},t.PIXI.lights={}))}(this,function(t){"use strict";PIXI.Circle.prototype.getMesh=function(t,e,r){void 0===t&&(t=40),e=e||new Float32Array(2*(t+1)),r=r||new Uint16Array(t+1);var i=2*Math.PI/t,o=-1;r[++o]=o;for(var n=0;n<=t;++n){var a=2*n,s=i*n;e[a]=Math.cos(s)*this.radius,e[a+1]=Math.sin(s)*this.radius,r[++o]=o}return r[o]=1,{vertices:e,indices:r}};var e={},r=new PIXI.display.Group,i=new PIXI.display.Group,o=new PIXI.display.Group;function n(t,r){e[t]=r}r.useRenderTexture=!0,i.useRenderTexture=!0;var a=function(t){function e(e,r,i,n){t.call(this),this.vertices=i||new Float32Array(8),this.indices=n||new Uint16Array([0,1,2,0,2,3]),this.blendMode=PIXI.BLEND_MODES.ADD,this.drawMode=PIXI.DRAW_MODES.TRIANGLES,this.dirty=0,this.lightHeight=.075,this.falloff=[.75,3,20],this.shaderName=null,this.useViewportQuad=!0,this._color=5066073,this._colorRgba=[.3,.3,.35,.8],(e||0===e)&&(this.color=e),(r||0===r)&&(this.brightness=r),this.parentGroup=o,this._glDatas={},this.shaderName="lights"}t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e;var r={color:{configurable:!0},brightness:{configurable:!0}};return r.color.get=function(){return this._color},r.color.set=function(t){this._color=t,PIXI.utils.hex2rgb(t,this._colorRgba)},r.brightness.get=function(){return this._colorRgba[3]},r.brightness.set=function(t){this._colorRgba[3]=t},e.prototype.syncShader=function(t){t.uniforms.uUseViewportQuad=this.useViewportQuad;var e=t.uniforms.uLightColor;e&&(e[0]=this._colorRgba[0],e[1]=this._colorRgba[1],e[2]=this._colorRgba[2],e[3]=this._colorRgba[3],t.uniforms.uLightColor=e),t.uniforms.uLightHeight=this.lightHeight;var r=t.uniforms.uLightFalloff;r&&(r[0]=this.falloff[0],r[1]=this.falloff[1],r[2]=this.falloff[2],t.uniforms.uLightFalloff=r)},e.prototype._renderWebGL=function(t){t.setObjectRenderer(t.plugins.lights),t.plugins.lights.render(this)},Object.defineProperties(e.prototype,r),e}(PIXI.Container),s=function(t){function e(r,i,o,n,a){var s={translationMatrix:{type:"mat3",value:new Float32Array(9)},projectionMatrix:{type:"mat3",value:new Float32Array(9)},uSampler:{type:"sampler2D",value:null},uNormalSampler:{type:"sampler2D",value:null},uUseViewportQuad:{type:"bool",value:!0},uViewSize:{type:"2f",value:new Float32Array(2)},uViewPixels:{type:"2f",value:new Float32Array(2)},uLightColor:{type:"4f",value:new Float32Array([1,1,1,1])},uLightFalloff:{type:"3f",value:new Float32Array([0,0,0])},uLightHeight:{type:"1f",value:.075}};if(n)for(var l in n)s[l]=n[l];var u={aVertexPosition:0};if(a)for(var h in a)u[h]=a[h];t.call(this,r,i||e.defaultVertexSrc,o,u)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(PIXI.Shader);s.defaultVertexSrc="attribute vec2 aVertexPosition;\n\nuniform bool uUseViewportQuad;\nuniform mat3 translationMatrix;\nuniform mat3 projectionMatrix;\n\nvoid main(void) {\n if (uUseViewportQuad) {\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n }\n else\n {\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n }\n}\n";var l=function(t){function e(e,r){void 0===e&&(e=16777215),void 0===r&&(r=.5),t.call(this,e,r),this.shaderName="ambientLightShader"}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(a),u="uniform sampler2D uSampler;\nuniform sampler2D uNormalSampler;\n\nuniform mat3 translationMatrix;\n\nuniform vec2 uViewPixels; // size of the viewport, in pixels\nuniform vec2 uViewSize; // size of the viewport, in CSS\n\nuniform vec4 uLightColor; // light color, alpha channel used for intensity.\nuniform vec3 uLightFalloff; // light attenuation coefficients (constant, linear, quadratic)\nuniform float uLightHeight; // light height above the viewport\nuniform float uFlipY; // whether we use renderTexture, FBO is flipped\n",h="vec2 texCoord = gl_FragCoord.xy / uViewPixels;\ntexCoord.y = (1.0 - texCoord.y) * uFlipY + texCoord.y * (1.0 - uFlipY); // FBOs positions are flipped.\n",c="vec4 normalColor = texture2D(uNormalSampler, texCoord);\nnormalColor.g = 1.0 - normalColor.g; // Green layer is flipped Y coords.\n\n// bail out early when normal has no data\nif (normalColor.a == 0.0) discard;\n",f="precision highp float;\n\n"+u+"\n\nvoid main(void)\n{\n"+h+"\n"+c+"\n // simplified lambert shading that makes assumptions for ambient color\n vec3 diffuse = uLightColor.rgb * uLightColor.a;\n vec4 diffuseColor = texture2D(uSampler, texCoord);\n vec3 finalColor = diffuseColor.rgb * diffuse;\n \n gl_FragColor = vec4(finalColor, diffuseColor.a);\n}\n",d=function(t){function e(e){t.call(this,e,null,f)}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(s);n("ambientLightShader",d);var p=function(t){function e(e,r,i){if(void 0===e&&(e=16777215),void 0===r&&(r=1),void 0===i&&(i=1/0),i!==1/0){var o=new PIXI.Circle(0,0,i).getMesh(),n=o.vertices,a=o.indices;t.call(this,e,r,n,a),this.useViewportQuad=!1,this.drawMode=PIXI.DRAW_MODES.TRIANGLE_FAN}else t.call(this,e,r);this.radius=i,this.shaderName="pointLightShader"}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.syncShader=function(e){t.prototype.syncShader.call(this,e),e.uniforms.uLightRadius=this.radius},e}(a),g='// normalize vectors\nvec3 N = normalize(normalColor.xyz * 2.0 - 1.0);\nvec3 L = normalize(lightVector);\n\n// pre-multiply light color with intensity\n// then perform "N dot L" to determine our diffuse\nvec3 diffuse = (uLightColor.rgb * uLightColor.a) * max(dot(N, L), 0.0);\n',v="// calculate final intesity and color, then combine\nvec3 intensity = diffuse * attenuation;\nvec4 diffuseColor = texture2D(uSampler, texCoord);\nvec3 finalColor = diffuseColor.rgb * intensity;\n\ngl_FragColor = vec4(finalColor, diffuseColor.a);\n",y="precision highp float;\n\n// imports the common uniforms like samplers, and ambient color\n"+u+"\n\nuniform float uLightRadius;\n\nvoid main()\n{\n"+h+"\n"+c+"\n\n vec2 lightPosition = translationMatrix[2].xy / uViewSize;\n\n // the directional vector of the light\n vec3 lightVector = vec3(lightPosition - texCoord, uLightHeight);\n\n // correct for aspect ratio\n lightVector.x *= uViewSize.x / uViewSize.y;\n\n // compute Distance\n float D = length(lightVector);\n\n // bail out early when pixel outside of light sphere\n if (D > uLightRadius) discard;\n\n"+g+"\n\n // calculate attenuation\n float attenuation = 1.0 / (uLightFalloff.x + (uLightFalloff.y * D) + (uLightFalloff.z * D * D));\n\n"+v+"\n}\n",m=function(t){function e(e){t.call(this,e,null,y,{uLightRadius:{type:"1f",value:1}})}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(s);n("pointLightShader",m);var _=function(t){function e(e,r,i){void 0===e&&(e=16777215),void 0===r&&(r=1),t.call(this,e,r),this.target=i,this._directionVector=new PIXI.Point,this.shaderName="directionalLightShader"}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e.prototype.updateTransform=function(){this.containerUpdateTransform();var t=this._directionVector,e=this.worldTransform,r=this.target.worldTransform?this.target.worldTransform.tx:this.target.x,i=this.target.worldTransform?this.target.worldTransform.ty:this.target.y;t.x=e.tx-r,t.y=e.ty-i;var o=Math.sqrt(t.x*t.x+t.y*t.y);t.x/=o,t.y/=o},e.prototype.syncShader=function(e){t.prototype.syncShader.call(this,e);var r=e.uniforms.uLightDirection;r[0]=this._directionVector.x,r[1]=this._directionVector.y,e.uniforms.uLightDirection=r},e}(a),x="precision highp float;\n\n// imports the common uniforms like samplers, and ambient/light color\n"+u+"\n\nuniform vec2 uLightDirection;\n\nvoid main()\n{\n"+h+"\n"+c+"\n\n // the directional vector of the light\n vec3 lightVector = vec3(uLightDirection, uLightHeight);\n\n // compute Distance\n float D = length(lightVector);\n\n"+g+"\n\n // calculate attenuation\n float attenuation = 1.0;\n\n"+v+"\n}\n",b=function(t){function e(e){t.call(this,e,null,x,{uLightDirection:{type:"2f",value:new Float32Array(2)}})}return t&&(e.__proto__=t),e.prototype=Object.create(t&&t.prototype),e.prototype.constructor=e,e}(s);n("directionalLightShader",b);var w=function(t){function o(e){t.call(this,e);var r=6*o.MAX_LIGHTS;this.indices=new Uint16Array(r);for(var i=0,n=0;i= data.byteLength) + { + gl.bufferSubData(this.type, offset, data); + } + else + { + gl.bufferData(this.type, data, this.drawType); + } + + this.data = data; +}; +/** + * Binds the buffer + * + */ +Buffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindBuffer(this.type, this.buffer); +}; + +Buffer.createVertexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); +}; + +Buffer.createIndexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); +}; + +Buffer.create = function(gl, type, data, drawType) +{ + return new Buffer(gl, type, data, drawType); +}; + +/** + * Destroys the buffer + * + */ +Buffer.prototype.destroy = function(){ + this.gl.deleteBuffer(this.buffer); +}; + +module.exports = Buffer; + +},{}],2:[function(require,module,exports){ + +var Texture = require('./GLTexture'); + +/** + * Helper class to create a webGL Framebuffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + */ +var Framebuffer = function(gl, width, height) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The frame buffer + * + * @member {WebGLFramebuffer} + */ + this.framebuffer = gl.createFramebuffer(); + + /** + * The stencil buffer + * + * @member {WebGLRenderbuffer} + */ + this.stencil = null; + + /** + * The stencil buffer + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The width of the drawing area of the buffer + * + * @member {Number} + */ + this.width = width || 100; + /** + * The height of the drawing area of the buffer + * + * @member {Number} + */ + this.height = height || 100; +}; + +/** + * Adds a texture to the frame buffer + * @param texture {PIXI.glCore.GLTexture} + */ +Framebuffer.prototype.enableTexture = function(texture) +{ + var gl = this.gl; + + this.texture = texture || new Texture(gl); + + this.texture.bind(); + + //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + this.bind(); + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); +}; + +/** + * Initialises the stencil buffer + */ +Framebuffer.prototype.enableStencil = function() +{ + if(this.stencil)return; + + var gl = this.gl; + + this.stencil = gl.createRenderbuffer(); + + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + + // TODO.. this is depth AND stencil? + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width , this.height ); +}; + +/** + * Erases the drawing area and fills it with a colour + * @param r {Number} the red value of the clearing colour + * @param g {Number} the green value of the clearing colour + * @param b {Number} the blue value of the clearing colour + * @param a {Number} the alpha value of the clearing colour + */ +Framebuffer.prototype.clear = function( r, g, b, a ) +{ + this.bind(); + + var gl = this.gl; + + gl.clearColor(r, g, b, a); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Binds the frame buffer to the WebGL context + */ +Framebuffer.prototype.bind = function() +{ + var gl = this.gl; + + if(this.texture) + { + this.texture.unbind(); + } + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); +}; + +/** + * Unbinds the frame buffer to the WebGL context + */ +Framebuffer.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, null ); +}; +/** + * Resizes the drawing area of the buffer to the given width and height + * @param width {Number} the new width + * @param height {Number} the new height + */ +Framebuffer.prototype.resize = function(width, height) +{ + var gl = this.gl; + + this.width = width; + this.height = height; + + if ( this.texture ) + { + this.texture.uploadData(null, width, height); + } + + if ( this.stencil ) + { + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + } +}; + +/** + * Destroys this buffer + */ +Framebuffer.prototype.destroy = function() +{ + var gl = this.gl; + + //TODO + if(this.texture) + { + this.texture.destroy(); + } + + gl.deleteFramebuffer(this.framebuffer); + + this.gl = null; + + this.stencil = null; + this.texture = null; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createRGBA = function(gl, width, height, data) +{ + var texture = Texture.fromData(gl, null, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createFloat32 = function(gl, width, height, data) +{ + // create a new texture.. + var texture = new Texture.fromData(gl, data, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +module.exports = Framebuffer; + +},{"./GLTexture":4}],3:[function(require,module,exports){ + +var compileProgram = require('./shader/compileProgram'), + extractAttributes = require('./shader/extractAttributes'), + extractUniforms = require('./shader/extractUniforms'), + generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + +/** + * Helper class to create a webGL Shader + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + */ +var Shader = function(gl, vertexSrc, fragmentSrc, attributeLocations) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + + + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); + + for(var i in this.attributes) + { + console.log(i + " : " + this.attributes[i].location) + } + + console.log(">>>>>>>"); + + var uniformData = extractUniforms(gl, this.program); + + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject( gl, uniformData ); +}; +/** + * Uses this shader + */ +Shader.prototype.bind = function() +{ + this.gl.useProgram(this.program); +}; + +/** + * Destroys this shader + * TODO + */ +Shader.prototype.destroy = function() +{ + // var gl = this.gl; +}; + +module.exports = Shader; + +},{"./shader/compileProgram":9,"./shader/extractAttributes":11,"./shader/extractUniforms":12,"./shader/generateUniformAccessObject":13}],4:[function(require,module,exports){ + +/** + * Helper class to create a WebGL Texture + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL context + * @param width {number} the width of the texture + * @param height {number} the height of the texture + * @param format {number} the pixel format of the texture. defaults to gl.RGBA + * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE + */ +var Texture = function(gl, width, height, format, type) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); + + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; + + + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; + + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; + + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + + +}; + +/** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ +Texture.prototype.upload = function(source) +{ + this.bind(); + + var gl = this.gl; + + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + var newWidth = source.videoWidth || source.width; + var newHeight = source.videoHeight || source.height; + + if(newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } + + // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + +}; + +var FLOATING_POINT_AVAILABLE = false; + +/** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.prototype.uploadData = function(data, width, height) +{ + this.bind(); + + var gl = this.gl; + + + if(data instanceof Float32Array) + { + if(!FLOATING_POINT_AVAILABLE) + { + var ext = gl.getExtension("OES_texture_float"); + + if(ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } + + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = gl.UNSIGNED_BYTE; + } + + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + + if(width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } + + this.width = width; + this.height = height; + + +// texSubImage2D +}; + +/** + * Binds the texture + * @param location + */ +Texture.prototype.bind = function(location) +{ + var gl = this.gl; + + if(location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } + + gl.bindTexture(gl.TEXTURE_2D, this.texture); +}; + +/** + * Unbinds the texture + */ +Texture.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, null); +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.minFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + if(this.mipmap) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.magFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); +}; + +/** + * Enables mipmapping + */ +Texture.prototype.enableMipmap = function() +{ + var gl = this.gl; + + this.bind(); + + this.mipmap = true; + + gl.generateMipmap(gl.TEXTURE_2D); +}; + +/** + * Enables linear filtering + */ +Texture.prototype.enableLinearScaling = function() +{ + this.minFilter(true); + this.magFilter(true); +}; + +/** + * Enables nearest neighbour interpolation + */ +Texture.prototype.enableNearestScaling = function() +{ + this.minFilter(false); + this.magFilter(false); +}; + +/** + * Enables clamping on the texture so WebGL will not repeat it + */ +Texture.prototype.enableWrapClamp = function() +{ + var gl = this.gl; + + this.bind(); + + 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); +}; + +/** + * Enable tiling on the texture + */ +Texture.prototype.enableWrapRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); +}; + +Texture.prototype.enableWrapMirrorRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); +}; + + +/** + * Destroys this texture + */ +Texture.prototype.destroy = function() +{ + var gl = this.gl; + //TODO + gl.deleteTexture(this.texture); +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ +Texture.fromSource = function(gl, source, premultiplyAlpha) +{ + var texture = new Texture(gl); + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); + + return texture; +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.fromData = function(gl, data, width, height) +{ + //console.log(data, width, height); + var texture = new Texture(gl); + texture.uploadData(data, width, height); + + return texture; +}; + + +module.exports = Texture; + +},{}],5:[function(require,module,exports){ + +// state object// +var setVertexAttribArrays = require( './setVertexAttribArrays' ); + +/** + * Helper class to work with WebGL VertexArrayObjects (vaos) + * Only works if WebGL extensions are enabled (they usually are) + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function VertexArrayObject(gl, state) +{ + this.nativeVaoExtension = null; + + if(!VertexArrayObject.FORCE_NATIVE) + { + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + this.nativeState = state; + + if(this.nativeVaoExtension) + { + this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + + var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + // VAO - overwrite the state.. + this.nativeState = { + tempAttribState: new Array(maxAttribs), + attribState: new Array(maxAttribs) + }; + } + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of attributes + * + * @member {Array} + */ + this.attributes = []; + + /** + * @member {PIXI.glCore.GLBuffer} + */ + this.indexBuffer = null; + + /** + * A boolean flag + * + * @member {Boolean} + */ + this.dirty = false; +} + +VertexArrayObject.prototype.constructor = VertexArrayObject; +module.exports = VertexArrayObject; + +/** +* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) +* If you find on older devices that things have gone a bit weird then set this to true. +*/ +/** + * Lets the VAO know if you should use the WebGL extension or the native methods. + * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) + * If you find on older devices that things have gone a bit weird then set this to true. + * @static + * @property {Boolean} FORCE_NATIVE + */ +VertexArrayObject.FORCE_NATIVE = true; + +/** + * Binds the buffer + */ +VertexArrayObject.prototype.bind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + + if(this.dirty) + { + this.dirty = false; + this.activate(); + } + } + else + { + + this.activate(); + } + + return this; +}; + +/** + * Unbinds the buffer + */ +VertexArrayObject.prototype.unbind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + return this; +}; + +/** + * Uses this vao + */ +VertexArrayObject.prototype.activate = function() +{ + + var gl = this.gl; + var lastBuffer = null; + + for (var i = 0; i < this.attributes.length; i++) + { + var attrib = this.attributes[i]; + + if(lastBuffer !== attrib.buffer) + { + attrib.buffer.bind(); + lastBuffer = attrib.buffer; + } + + + //attrib.attribute.pointer(attrib.type, attrib.normalized, attrib.stride, attrib.start); + gl.vertexAttribPointer(attrib.attribute.location, + attrib.attribute.size, attrib.type || gl.FLOAT, + attrib.normalized || false, + attrib.stride || 0, + attrib.start || 0); + + + } + + setVertexAttribArrays(gl, this.attributes, this.nativeState); + + this.indexBuffer.bind(); + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + * @param attribute {*} + * @param type {String} + * @param normalized {Boolean} + * @param stride {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start) +{ + this.attributes.push({ + buffer: buffer, + attribute: attribute, + + location: attribute.location, + type: type || this.gl.FLOAT, + normalized: normalized || false, + stride: stride || 0, + start: start || 0 + }); + + this.dirty = true; + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + */ +VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) +{ + this.indexBuffer = buffer; + + this.dirty = true; + + return this; +}; + +/** + * Unbinds this vao and disables it + */ +VertexArrayObject.prototype.clear = function() +{ + // var gl = this.gl; + + // TODO - should this function unbind after clear? + // for now, no but lets see what happens in the real world! + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + } + + this.attributes.length = 0; + this.indexBuffer = null; + + return this; +}; + +/** + * @param type {Number} + * @param size {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.draw = function(type, size, start) +{ + var gl = this.gl; + gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, start || 0); + + return this; +}; + +/** + * Destroy this vao + */ +VertexArrayObject.prototype.destroy = function() +{ + // lose references + this.gl = null; + this.indexBuffer = null; + this.attributes = null; + this.nativeState = null; + + if(this.nativeVao) + { + this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); + } + + this.nativeVaoExtension = null; + this.nativeVao = null; +}; + +},{"./setVertexAttribArrays":8}],6:[function(require,module,exports){ + +/** + * Helper class to create a webGL Context + * + * @class + * @memberof PIXI.glCore + * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from + * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * @return {WebGLRenderingContext} the WebGL context + */ +var createContext = function(canvas, options) +{ + var gl = canvas.getContext('webgl', options) || + canvas.getContext('experimental-webgl', options); + + if (!gl) + { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + return gl; +}; + +module.exports = createContext; + +},{}],7:[function(require,module,exports){ +var gl = { + createContext: require('./createContext'), + setVertexAttribArrays: require('./setVertexAttribArrays'), + GLBuffer: require('./GLBuffer'), + GLFramebuffer: require('./GLFramebuffer'), + GLShader: require('./GLShader'), + GLTexture: require('./GLTexture'), + VertexArrayObject: require('./VertexArrayObject'), + shader: require('./shader') +}; + +// Export for Node-compatible environments +if (typeof module !== 'undefined' && module.exports) +{ + // Export the module + module.exports = gl; +} + +// Add to the browser window pixi.gl +if (typeof window !== 'undefined') +{ + // add the window object + window.PIXI = window.PIXI || {}; + window.PIXI.glCore = gl; +} + +},{"./GLBuffer":1,"./GLFramebuffer":2,"./GLShader":3,"./GLTexture":4,"./VertexArrayObject":5,"./createContext":6,"./setVertexAttribArrays":8,"./shader":14}],8:[function(require,module,exports){ +// var GL_MAP = {}; + +/** + * @param gl {WebGLRenderingContext} The current WebGL context + * @param attribs {*} + * @param state {*} + */ +var setVertexAttribArrays = function (gl, attribs, state) +{ + var i; + if(state) + { + var tempAttribState = state.tempAttribState, + attribState = state.attribState; + + for (i = 0; i < tempAttribState.length; i++) + { + tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + tempAttribState[attribs[i].attribute.location] = true; + } + + for (i = 0; i < attribState.length; i++) + { + if (attribState[i] !== tempAttribState[i]) + { + attribState[i] = tempAttribState[i]; + + if (state.attribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } + + } + else + { + for (i = 0; i < attribs.length; i++) + { + var attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); + } + } +}; + +module.exports = setVertexAttribArrays; + +},{}],9:[function(require,module,exports){ + +/** + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations + * @return {WebGLProgram} the shader program + */ +var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +{ + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + + var program = gl.createProgram(); + + gl.attachShader(program, glVertShader); + gl.attachShader(program, glFragShader); + + // optionally, set the attributes manually for the program rather than letting WebGL decide.. + if(attributeLocations) + { + for(var i in attributeLocations) + { + gl.bindAttribLocation(program, attributeLocations[i], i) + } + } + + + gl.linkProgram(program); + + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + console.error('Pixi.js Error: Could not initialize shader.'); + console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); + console.error('gl.getError()', gl.getError()); + + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') + { + console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + + gl.deleteProgram(program); + program = null; + } + + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + + return program; +}; + +/** + * @private + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @return {WebGLShader} the shader + */ +var compileShader = function (gl, type, src) +{ + var shader = gl.createShader(type); + + gl.shaderSource(shader, src); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + console.log(gl.getShaderInfoLog(shader)); + return null; + } + + return shader; +}; + +module.exports = compileProgram; + +},{}],10:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} Type of value + * @param size {Number} + */ +var defaultValue = function(type, size) +{ + switch (type) + { + case 'float': + return 0; + + case 'vec2': + return new Float32Array(2 * size); + + case 'vec3': + return new Float32Array(3 * size); + + case 'vec4': + return new Float32Array(4 * size); + + case 'int': + case 'sampler2D': + return 0; + + case 'ivec2': + return new Int32Array(2 * size); + + case 'ivec3': + return new Int32Array(3 * size); + + case 'ivec4': + return new Int32Array(4 * size); + + case 'bool': + return false; + + case 'bvec2': + + return booleanArray( 2 * size); + + case 'bvec3': + return booleanArray(3 * size); + + case 'bvec4': + return booleanArray(4 * size); + + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } +}; + +var booleanArray = function(size) +{ + var array = new Array(size); + + for (var i = 0; i < array.length; i++) + { + array[i] = false; + } + + return array; +}; + +module.exports = defaultValue; + +},{}],11:[function(require,module,exports){ + +var mapType = require('./mapType'); +var mapSize = require('./mapSize'); + +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the attributes from + * @return attributes {Object} + */ +var extractAttributes = function(gl, program) +{ + var attributes = {}; + + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + + for (var i = 0; i < totalAttributes; i++) + { + var attribData = gl.getActiveAttrib(program, i); + var type = mapType(gl, attribData.type); + + attributes[attribData.name] = { + type:type, + size:mapSize(type), + location:gl.getAttribLocation(program, attribData.name), + //TODO - make an attribute object + pointer: pointer + }; + } + + return attributes; +}; + +var pointer = function(type, normalized, stride, start){ + // console.log(this.location) + gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +}; + +module.exports = extractAttributes; + +},{"./mapSize":15,"./mapType":16}],12:[function(require,module,exports){ +var mapType = require('./mapType'); +var defaultValue = require('./defaultValue'); + +/** + * Extracts the uniforms + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the uniforms from + * @return uniforms {Object} + */ +var extractUniforms = function(gl, program) +{ + var uniforms = {}; + + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + + for (var i = 0; i < totalUniforms; i++) + { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]/, ""); + var type = mapType(gl, uniformData.type ); + + uniforms[name] = { + type:type, + size:uniformData.size, + location:gl.getUniformLocation(program, name), + value:defaultValue(type, uniformData.size) + }; + } + + return uniforms; +}; + +module.exports = extractUniforms; + +},{"./defaultValue":10,"./mapType":16}],13:[function(require,module,exports){ +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param uniforms {Array} @mat ? + * @return attributes {Object} + */ +var generateUniformAccessObject = function(gl, uniformData) +{ + // this is the object we will be sending back. + // an object hierachy will be created for structs + var uniforms = {data:{}}; + + uniforms.gl = gl; + + var uniformKeys= Object.keys(uniformData); + + for (var i = 0; i < uniformKeys.length; i++) + { + var fullName = uniformKeys[i]; + + var nameTokens = fullName.split('.'); + var name = nameTokens[nameTokens.length - 1]; + + var uniformGroup = getUniformGroup(nameTokens, uniforms); + + var uniform = uniformData[fullName]; + uniformGroup.data[name] = uniform; + + uniformGroup.gl = gl; + + Object.defineProperty(uniformGroup, name, { + get: generateGetter(name), + set: generateSetter(name, uniform) + }); + } + + return uniforms; +}; + +var generateGetter = function(name) +{ + var template = getterTemplate.replace('%%', name); + return new Function(template); // jshint ignore:line +}; + +var generateSetter = function(name, uniform) +{ + var template = setterTemplate.replace(/%%/g, name); + var setTemplate; + + if(uniform.size === 1) + { + setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; + } + else + { + setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; + } + + if(setTemplate) + { + template += "\nthis.gl." + setTemplate + ";"; + } + + return new Function('value', template); // jshint ignore:line +}; + +var getUniformGroup = function(nameTokens, uniform) +{ + var cur = uniform; + + for (var i = 0; i < nameTokens.length - 1; i++) + { + var o = cur[nameTokens[i]] || {data:{}}; + cur[nameTokens[i]] = o; + cur = o; + } + + return cur; +}; + +var getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +var setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;' +].join('\n'); + + +var GLSL_TO_SINGLE_SETTERS = { + + 'float': 'uniform1f(location, value)', + + 'vec2': 'uniform2f(location, value[0], value[1])', + 'vec3': 'uniform3f(location, value[0], value[1], value[2])', + 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', + + 'int': 'uniform1i(location, value)', + 'ivec2': 'uniform2i(location, value[0], value[1])', + 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', + 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'bool': 'uniform1i(location, value)', + 'bvec2': 'uniform2i(location, value[0], value[1])', + 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', + 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'mat2': 'uniformMatrix2fv(location, false, value)', + 'mat3': 'uniformMatrix3fv(location, false, value)', + 'mat4': 'uniformMatrix4fv(location, false, value)', + + 'sampler2D':'uniform1i(location, value)' +}; + +var GLSL_TO_ARRAY_SETTERS = { + + 'float': 'uniform1fv(location, value)', + + 'vec2': 'uniform2fv(location, value)', + 'vec3': 'uniform3fv(location, value)', + 'vec4': 'uniform4fv(location, value)', + + 'int': 'uniform1iv(location, value)', + 'ivec2': 'uniform2iv(location, value)', + 'ivec3': 'uniform3iv(location, value)', + 'ivec4': 'uniform4iv(location, value)', + + 'bool': 'uniform1iv(location, value)', + 'bvec2': 'uniform2iv(location, value)', + 'bvec3': 'uniform3iv(location, value)', + 'bvec4': 'uniform4iv(location, value)', + + 'sampler2D':'uniform1iv(location, value)' +}; + +module.exports = generateUniformAccessObject; + +},{}],14:[function(require,module,exports){ +module.exports = { + compileProgram: require('./compileProgram'), + defaultValue: require('./defaultValue'), + extractAttributes: require('./extractAttributes'), + extractUniforms: require('./extractUniforms'), + generateUniformAccessObject: require('./generateUniformAccessObject'), + mapSize: require('./mapSize'), + mapType: require('./mapType') +}; +},{"./compileProgram":9,"./defaultValue":10,"./extractAttributes":11,"./extractUniforms":12,"./generateUniformAccessObject":13,"./mapSize":15,"./mapType":16}],15:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} + * @return {Number} + */ +var mapSize = function(type) +{ + return GLSL_TO_SIZE[type]; +}; + + +var GLSL_TO_SIZE = { + 'float': 1, + 'vec2': 2, + 'vec3': 3, + 'vec4': 4, + + 'int': 1, + 'ivec2': 2, + 'ivec3': 3, + 'ivec4': 4, + + 'bool': 1, + 'bvec2': 2, + 'bvec3': 3, + 'bvec4': 4, + + 'mat2': 4, + 'mat3': 9, + 'mat4': 16, + + 'sampler2D': 1 +}; + +module.exports = mapSize; + +},{}],16:[function(require,module,exports){ + + +var mapSize = function(gl, type) +{ + if(!GL_TABLE) + { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + + GL_TABLE = {}; + + for(var i = 0; i < typeNames.length; ++i) + { + var tn = typeNames[i]; + GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + } + } + + return GL_TABLE[type]; +}; + +var GL_TABLE = null; + +var GL_TO_GLSL_TYPES = { + 'FLOAT': 'float', + 'FLOAT_VEC2': 'vec2', + 'FLOAT_VEC3': 'vec3', + 'FLOAT_VEC4': 'vec4', + + 'INT': 'int', + 'INT_VEC2': 'ivec2', + 'INT_VEC3': 'ivec3', + 'INT_VEC4': 'ivec4', + + 'BOOL': 'bool', + 'BOOL_VEC2': 'bvec2', + 'BOOL_VEC3': 'bvec3', + 'BOOL_VEC4': 'bvec4', + + 'FLOAT_MAT2': 'mat2', + 'FLOAT_MAT3': 'mat3', + 'FLOAT_MAT4': 'mat4', + + 'SAMPLER_2D': 'sampler2D' +}; + +module.exports = mapSize; + +},{}],17:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = eachLimit; + +var _eachOfLimit = require('./internal/eachOfLimit'); + +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); + +var _withoutIndex = require('./internal/withoutIndex'); + +var _withoutIndex2 = _interopRequireDefault(_withoutIndex); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|Object} coll - A colleciton to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A function to apply to each item in `coll`. The + * iteratee is passed a `callback(err)` which must be called once it has + * completed. If no error has occurred, the `callback` should be run without + * arguments or with an explicit `null` argument. The array index is not passed + * to the iteratee. Invoked with (item, callback). If you need the index, use + * `eachOfLimit`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ +function eachLimit(coll, limit, iteratee, callback) { + (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)(iteratee), callback); +} +module.exports = exports['default']; +},{"./internal/eachOfLimit":21,"./internal/withoutIndex":28}],18:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _eachLimit = require('./eachLimit'); + +var _eachLimit2 = _interopRequireDefault(_eachLimit); + +var _doLimit = require('./internal/doLimit'); + +var _doLimit2 = _interopRequireDefault(_doLimit); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A function to apply to each + * item in `coll`. The iteratee is passed a `callback(err)` which must be called + * once it has completed. If no error has occurred, the `callback` should be run + * without arguments or with an explicit `null` argument. The array index is + * not passed to the iteratee. Invoked with (item, callback). If you need the + * index, use `eachOfSeries`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + */ +exports.default = (0, _doLimit2.default)(_eachLimit2.default, 1); +module.exports = exports['default']; +},{"./eachLimit":17,"./internal/doLimit":20}],19:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = DLL; +// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation +// used for queues. This implementation assumes that the node provided by the user can be modified +// to adjust the next and last properties. We implement only the minimal functionality +// for queue support. +function DLL() { + this.head = this.tail = null; + this.length = 0; +} + +function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; +} + +DLL.prototype.removeLink = function (node) { + if (node.prev) node.prev.next = node.next;else this.head = node.next; + if (node.next) node.next.prev = node.prev;else this.tail = node.prev; + + node.prev = node.next = null; + this.length -= 1; + return node; +}; + +DLL.prototype.empty = DLL; + +DLL.prototype.insertAfter = function (node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode;else this.tail = newNode; + node.next = newNode; + this.length += 1; +}; + +DLL.prototype.insertBefore = function (node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode;else this.head = newNode; + node.prev = newNode; + this.length += 1; +}; + +DLL.prototype.unshift = function (node) { + if (this.head) this.insertBefore(this.head, node);else setInitial(this, node); +}; + +DLL.prototype.push = function (node) { + if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node); +}; + +DLL.prototype.shift = function () { + return this.head && this.removeLink(this.head); +}; + +DLL.prototype.pop = function () { + return this.tail && this.removeLink(this.tail); +}; +module.exports = exports['default']; +},{}],20:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = doLimit; +function doLimit(fn, limit) { + return function (iterable, iteratee, callback) { + return fn(iterable, limit, iteratee, callback); + }; +} +module.exports = exports['default']; +},{}],21:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _eachOfLimit; + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _once = require('./once'); + +var _once2 = _interopRequireDefault(_once); + +var _iterator = require('./iterator'); + +var _iterator2 = _interopRequireDefault(_iterator); + +var _onlyOnce = require('./onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _eachOfLimit(limit) { + return function (obj, iteratee, callback) { + callback = (0, _once2.default)(callback || _noop2.default); + if (limit <= 0 || !obj) { + return callback(null); + } + var nextElem = (0, _iterator2.default)(obj); + var done = false; + var running = 0; + + function iterateeCallback(err) { + running -= 1; + if (err) { + done = true; + callback(err); + } else if (done && running <= 0) { + return callback(null); + } else { + replenish(); + } + } + + function replenish() { + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback)); + } + } + + replenish(); + }; +} +module.exports = exports['default']; +},{"./iterator":23,"./once":24,"./onlyOnce":25,"lodash/noop":54}],22:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (coll) { + return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); +}; + +var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; + +module.exports = exports['default']; +},{}],23:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = iterator; + +var _isArrayLike = require('lodash/isArrayLike'); + +var _isArrayLike2 = _interopRequireDefault(_isArrayLike); + +var _getIterator = require('./getIterator'); + +var _getIterator2 = _interopRequireDefault(_getIterator); + +var _keys = require('lodash/keys'); + +var _keys2 = _interopRequireDefault(_keys); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? { value: coll[i], key: i } : null; + }; +} + +function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) return null; + i++; + return { value: item.value, key: i }; + }; +} + +function createObjectIterator(obj) { + var okeys = (0, _keys2.default)(obj); + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + return i < len ? { value: obj[key], key: key } : null; + }; +} + +function iterator(coll) { + if ((0, _isArrayLike2.default)(coll)) { + return createArrayIterator(coll); + } + + var iterator = (0, _getIterator2.default)(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); +} +module.exports = exports['default']; +},{"./getIterator":22,"lodash/isArrayLike":46,"lodash/keys":53}],24:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = once; +function once(fn) { + return function () { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, arguments); + }; +} +module.exports = exports['default']; +},{}],25:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = onlyOnce; +function onlyOnce(fn) { + return function () { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, arguments); + }; +} +module.exports = exports['default']; +},{}],26:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = queue; + +var _arrayEach = require('lodash/_arrayEach'); + +var _arrayEach2 = _interopRequireDefault(_arrayEach); + +var _isArray = require('lodash/isArray'); + +var _isArray2 = _interopRequireDefault(_isArray); + +var _noop = require('lodash/noop'); + +var _noop2 = _interopRequireDefault(_noop); + +var _rest = require('lodash/rest'); + +var _rest2 = _interopRequireDefault(_rest); + +var _onlyOnce = require('./onlyOnce'); + +var _onlyOnce2 = _interopRequireDefault(_onlyOnce); + +var _setImmediate = require('./setImmediate'); + +var _setImmediate2 = _interopRequireDefault(_setImmediate); + +var _DoublyLinkedList = require('./DoublyLinkedList'); + +var _DoublyLinkedList2 = _interopRequireDefault(_DoublyLinkedList); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function queue(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } else if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + + function _insert(data, insertAtFront, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; + if (!(0, _isArray2.default)(data)) { + data = [data]; + } + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + return (0, _setImmediate2.default)(function () { + q.drain(); + }); + } + (0, _arrayEach2.default)(data, function (task) { + var item = { + data: task, + callback: callback || _noop2.default + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + }); + (0, _setImmediate2.default)(q.process); + } + + function _next(tasks) { + return (0, _rest2.default)(function (args) { + workers -= 1; + + (0, _arrayEach2.default)(tasks, function (task) { + (0, _arrayEach2.default)(workersList, function (worker, index) { + if (worker === task) { + workersList.splice(index, 1); + return false; + } + }); + + task.callback.apply(task, args); + + if (args[0] != null) { + q.error(args[0], task.data); + } + }); + + if (workers <= q.concurrency - q.buffer) { + q.unsaturated(); + } + + if (q.idle()) { + q.drain(); + } + q.process(); + }); + } + + var workers = 0; + var workersList = []; + var q = { + _tasks: new _DoublyLinkedList2.default(), + concurrency: concurrency, + payload: payload, + saturated: _noop2.default, + unsaturated: _noop2.default, + buffer: concurrency / 4, + empty: _noop2.default, + drain: _noop2.default, + error: _noop2.default, + started: false, + paused: false, + push: function (data, callback) { + _insert(data, false, callback); + }, + kill: function () { + q.drain = _noop2.default; + q._tasks.empty(); + }, + unshift: function (data, callback) { + _insert(data, true, callback); + }, + process: function () { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var tasks = [], + data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + data.push(node.data); + } + + if (q._tasks.length === 0) { + q.empty(); + } + workers += 1; + workersList.push(tasks[0]); + + if (workers === q.concurrency) { + q.saturated(); + } + + var cb = (0, _onlyOnce2.default)(_next(tasks)); + worker(data, cb); + } + }, + length: function () { + return q._tasks.length; + }, + running: function () { + return workers; + }, + workersList: function () { + return workersList; + }, + idle: function () { + return q._tasks.length + workers === 0; + }, + pause: function () { + q.paused = true; + }, + resume: function () { + if (q.paused === false) { + return; + } + q.paused = false; + var resumeCount = Math.min(q.concurrency, q._tasks.length); + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= resumeCount; w++) { + (0, _setImmediate2.default)(q.process); + } + } + }; + return q; +} +module.exports = exports['default']; +},{"./DoublyLinkedList":19,"./onlyOnce":25,"./setImmediate":27,"lodash/_arrayEach":35,"lodash/isArray":45,"lodash/noop":54,"lodash/rest":55}],27:[function(require,module,exports){ +(function (process){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.hasNextTick = exports.hasSetImmediate = undefined; +exports.fallback = fallback; +exports.wrap = wrap; + +var _rest = require('lodash/rest'); + +var _rest2 = _interopRequireDefault(_rest); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var hasSetImmediate = exports.hasSetImmediate = typeof setImmediate === 'function' && setImmediate; +var hasNextTick = exports.hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; + +function fallback(fn) { + setTimeout(fn, 0); +} + +function wrap(defer) { + return (0, _rest2.default)(function (fn, args) { + defer(function () { + fn.apply(null, args); + }); + }); +} + +var _defer; + +if (hasSetImmediate) { + _defer = setImmediate; +} else if (hasNextTick) { + _defer = process.nextTick; +} else { + _defer = fallback; +} + +exports.default = wrap(_defer); +}).call(this,require('_process')) + +},{"_process":61,"lodash/rest":55}],28:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _withoutIndex; +function _withoutIndex(iteratee) { + return function (value, index, callback) { + return iteratee(value, callback); + }; +} +module.exports = exports['default']; +},{}],29:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +exports.default = function (worker, concurrency) { + return (0, _queue2.default)(function (items, cb) { + worker(items[0], cb); + }, concurrency, 1); +}; + +var _queue = require('./internal/queue'); + +var _queue2 = _interopRequireDefault(_queue); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports['default']; + +/** + * A queue of tasks for the worker function to complete. + * @typedef {Object} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {Function} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {Function} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {Function} saturated - a callback that is called when the number of + * running workers hits the `concurrency` limit, and further tasks will be + * queued. + * @property {Function} unsaturated - a callback that is called when the number + * of running workers is less than the `concurrency` & `buffer` limits, and + * further tasks will not be queued. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a callback that is called when the last item + * from the `queue` is given to a `worker`. + * @property {Function} drain - a callback that is called when the last item + * from the `queue` has returned from the `worker`. + * @property {Function} error - a callback that is called when a task errors. + * Has the signature `function(error, task)`. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. Invoke with `queue.kill()`. + */ + +/** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Function} worker - An asynchronous function for processing a queued + * task, which must call its `callback(err)` argument when finished, with an + * optional `error` as an argument. If you want to handle errors from an + * individual task, pass a callback to `q.push()`. Invoked with + * (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain = function() { + * console.log('all items have been processed'); + * }; + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * q.push({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ +},{"./internal/queue":26}],30:[function(require,module,exports){ +/** + * Bit twiddling hacks for JavaScript. + * + * Author: Mikola Lysenko + * + * Ported from Stanford bit twiddling hack library: + * http://graphics.stanford.edu/~seander/bithacks.html + */ + +"use strict"; "use restrict"; + +//Number of bits in an integer +var INT_BITS = 32; + +//Constants +exports.INT_BITS = INT_BITS; +exports.INT_MAX = 0x7fffffff; +exports.INT_MIN = -1<<(INT_BITS-1); + +//Returns -1, 0, +1 depending on sign of x +exports.sign = function(v) { + return (v > 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],31:[function(require,module,exports){ +'use strict'; + +module.exports = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, size), + maxZ = zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, size); + earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and size of the data bounding box +function zOrder(x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; + +},{}],32:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty; + +// +// We store our EE objects in a plain object whose properties are event names. +// If `Object.create(null)` is not supported we prefix the event names with a +// `~` to make sure that the built-in object properties are not overridden or +// used as an attack vector. +// We also assume that `Object.create(null)` is available when the event name +// is an ES6 Symbol. +// +var prefix = typeof Object.create !== 'function' ? '~' : false; + +/** + * Representation of a single EventEmitter function. + * + * @param {Function} fn Event handler to be called. + * @param {Mixed} context Context for function execution. + * @param {Boolean} [once=false] Only emit once + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal EventEmitter interface that is molded against the Node.js + * EventEmitter interface. + * + * @constructor + * @api public + */ +function EventEmitter() { /* Nothing to set */ } + +/** + * Hold the assigned EventEmitters by name. + * + * @type {Object} + * @private + */ +EventEmitter.prototype._events = undefined; + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @api public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var events = this._events + , names = [] + , name; + + if (!events) return names; + + for (name in events) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return a list of assigned event listeners. + * + * @param {String} event The events that should be listed. + * @param {Boolean} exists We only need to know if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events && this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Emit an event to all registered event listeners. + * + * @param {String} event The name of the event. + * @returns {Boolean} Indication if we've emitted an event. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events || !this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if ('function' === typeof listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Register a new EventListener for the given event. + * + * @param {String} event Name of the event. + * @param {Function} fn Callback function. + * @param {Mixed} [context=this] The context of the function. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events) this._events = prefix ? {} : Object.create(null); + if (!this._events[evt]) this._events[evt] = listener; + else { + if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [ + this._events[evt], listener + ]; + } + + return this; +}; + +/** + * Add an EventListener that's only called once. + * + * @param {String} event Name of the event. + * @param {Function} fn Callback function. + * @param {Mixed} [context=this] The context of the function. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events) this._events = prefix ? {} : Object.create(null); + if (!this._events[evt]) this._events[evt] = listener; + else { + if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [ + this._events[evt], listener + ]; + } + + return this; +}; + +/** + * Remove event listeners. + * + * @param {String} event The event we want to remove. + * @param {Function} fn The listener that we need to find. + * @param {Mixed} context Only remove listeners matching this context. + * @param {Boolean} once Only remove once listeners. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events || !this._events[evt]) return this; + + var listeners = this._events[evt] + , events = []; + + if (fn) { + if (listeners.fn) { + if ( + listeners.fn !== fn + || (once && !listeners.once) + || (context && listeners.context !== context) + ) { + events.push(listeners); + } + } else { + for (var i = 0, length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) { + this._events[evt] = events.length === 1 ? events[0] : events; + } else { + delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners or only the listeners for the specified event. + * + * @param {String} event The event want to remove all listeners for. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + if (!this._events) return this; + + if (event) delete this._events[prefix ? prefix + event : event]; + else this._events = prefix ? {} : Object.create(null); + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],33:[function(require,module,exports){ +/** + * isMobile.js v0.4.0 + * + * A simple library to detect Apple phones and tablets, + * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone), + * and any kind of seven inch device, via user agent sniffing. + * + * @author: Kai Mallea (kmallea@gmail.com) + * + * @license: http://creativecommons.org/publicdomain/zero/1.0/ + */ +(function (global) { + + var apple_phone = /iPhone/i, + apple_ipod = /iPod/i, + apple_tablet = /iPad/i, + android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i, // Match 'Android' AND 'Mobile' + android_tablet = /Android/i, + amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i, + amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i, + windows_phone = /IEMobile/i, + windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i, // Match 'Windows' AND 'ARM' + other_blackberry = /BlackBerry/i, + other_blackberry_10 = /BB10/i, + other_opera = /Opera Mini/i, + other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i, + other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i, // Match 'Firefox' AND 'Mobile' + seven_inch = new RegExp( + '(?:' + // Non-capturing group + + 'Nexus 7' + // Nexus 7 + + '|' + // OR + + 'BNTV250' + // B&N Nook Tablet 7 inch + + '|' + // OR + + 'Kindle Fire' + // Kindle Fire + + '|' + // OR + + 'Silk' + // Kindle Fire, Silk Accelerated + + '|' + // OR + + 'GT-P1000' + // Galaxy Tab 7 inch + + ')', // End non-capturing group + + 'i'); // Case-insensitive matching + + var match = function(regex, userAgent) { + return regex.test(userAgent); + }; + + var IsMobileClass = function(userAgent) { + var ua = userAgent || navigator.userAgent; + + // Facebook mobile app's integrated browser adds a bunch of strings that + // match everything. Strip it out if it exists. + var tmp = ua.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + // Twitter mobile app's integrated browser on iPad adds a "Twitter for + // iPhone" string. Same probable happens on other tablet platforms. + // This will confuse detection so strip it out if it exists. + tmp = ua.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + this.apple = { + phone: match(apple_phone, ua), + ipod: match(apple_ipod, ua), + tablet: !match(apple_phone, ua) && match(apple_tablet, ua), + device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua) + }; + this.amazon = { + phone: match(amazon_phone, ua), + tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) + }; + this.android = { + phone: match(amazon_phone, ua) || match(android_phone, ua), + tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua) + }; + this.windows = { + phone: match(windows_phone, ua), + tablet: match(windows_tablet, ua), + device: match(windows_phone, ua) || match(windows_tablet, ua) + }; + this.other = { + blackberry: match(other_blackberry, ua), + blackberry10: match(other_blackberry_10, ua), + opera: match(other_opera, ua), + firefox: match(other_firefox, ua), + chrome: match(other_chrome, ua), + device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua) + }; + this.seven_inch = match(seven_inch, ua); + this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch; + + // excludes 'other' devices and ipods, targeting touchscreen phones + this.phone = this.apple.phone || this.android.phone || this.windows.phone; + + // excludes 7 inch devices, classifying as phone or tablet is left to the user + this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet; + + if (typeof window === 'undefined') { + return this; + } + }; + + var instantiate = function() { + var IM = new IsMobileClass(); + IM.Class = IsMobileClass; + return IM; + }; + + if (typeof module !== 'undefined' && module.exports && typeof window === 'undefined') { + //node + module.exports = IsMobileClass; + } else if (typeof module !== 'undefined' && module.exports && typeof window !== 'undefined') { + //browserify + module.exports = instantiate(); + } else if (typeof define === 'function' && define.amd) { + //AMD + define('isMobile', [], global.isMobile = instantiate()); + } else { + global.isMobile = instantiate(); + } + +})(this); + +},{}],34:[function(require,module,exports){ +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} + +module.exports = apply; + +},{}],35:[function(require,module,exports){ +/** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ +function arrayEach(array, iteratee) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; +} + +module.exports = arrayEach; + +},{}],36:[function(require,module,exports){ +var baseTimes = require('./_baseTimes'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isIndex = require('./_isIndex'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; + + var length = result.length, + skipIndexes = !!length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); + } + } + return result; +} + +module.exports = arrayLikeKeys; + +},{"./_baseTimes":39,"./_isIndex":40,"./isArguments":44,"./isArray":45}],37:[function(require,module,exports){ +var isPrototype = require('./_isPrototype'), + nativeKeys = require('./_nativeKeys'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +module.exports = baseKeys; + +},{"./_isPrototype":41,"./_nativeKeys":42}],38:[function(require,module,exports){ +var apply = require('./_apply'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; +} + +module.exports = baseRest; + +},{"./_apply":34}],39:[function(require,module,exports){ +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +module.exports = baseTimes; + +},{}],40:[function(require,module,exports){ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} + +module.exports = isIndex; + +},{}],41:[function(require,module,exports){ +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +module.exports = isPrototype; + +},{}],42:[function(require,module,exports){ +var overArg = require('./_overArg'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object); + +module.exports = nativeKeys; + +},{"./_overArg":43}],43:[function(require,module,exports){ +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +module.exports = overArg; + +},{}],44:[function(require,module,exports){ +var isArrayLikeObject = require('./isArrayLikeObject'); + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} + +module.exports = isArguments; + +},{"./isArrayLikeObject":47}],45:[function(require,module,exports){ +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +module.exports = isArray; + +},{}],46:[function(require,module,exports){ +var isFunction = require('./isFunction'), + isLength = require('./isLength'); + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +module.exports = isArrayLike; + +},{"./isFunction":48,"./isLength":49}],47:[function(require,module,exports){ +var isArrayLike = require('./isArrayLike'), + isObjectLike = require('./isObjectLike'); + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +module.exports = isArrayLikeObject; + +},{"./isArrayLike":46,"./isObjectLike":51}],48:[function(require,module,exports){ +var isObject = require('./isObject'); + +/** `Object#toString` result references. */ +var funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} + +module.exports = isFunction; + +},{"./isObject":50}],49:[function(require,module,exports){ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +module.exports = isLength; + +},{}],50:[function(require,module,exports){ +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +module.exports = isObject; + +},{}],51:[function(require,module,exports){ +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +module.exports = isObjectLike; + +},{}],52:[function(require,module,exports){ +var isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +module.exports = isSymbol; + +},{"./isObjectLike":51}],53:[function(require,module,exports){ +var arrayLikeKeys = require('./_arrayLikeKeys'), + baseKeys = require('./_baseKeys'), + isArrayLike = require('./isArrayLike'); + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +module.exports = keys; + +},{"./_arrayLikeKeys":36,"./_baseKeys":37,"./isArrayLike":46}],54:[function(require,module,exports){ +/** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ +function noop() { + // No operation performed. +} + +module.exports = noop; + +},{}],55:[function(require,module,exports){ +var baseRest = require('./_baseRest'), + toInteger = require('./toInteger'); + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ +function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); +} + +module.exports = rest; + +},{"./_baseRest":38,"./toInteger":57}],56:[function(require,module,exports){ +var toNumber = require('./toNumber'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308; + +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} + +module.exports = toFinite; + +},{"./toNumber":58}],57:[function(require,module,exports){ +var toFinite = require('./toFinite'); + +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; +} + +module.exports = toInteger; + +},{"./toFinite":56}],58:[function(require,module,exports){ +var isObject = require('./isObject'), + isSymbol = require('./isSymbol'); + +/** Used as references for various `Number` constants. */ +var NAN = 0 / 0; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +module.exports = toNumber; + +},{"./isObject":50,"./isSymbol":52}],59:[function(require,module,exports){ +'use strict'; +/* eslint-disable no-unused-vars */ +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (e) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (Object.getOwnPropertySymbols) { + symbols = Object.getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],60:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) + +},{"_process":61}],61:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],62:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],63:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],64:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],65:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":63,"./encode":64}],66:[function(require,module,exports){ +'use strict'; + +var asyncQueue = require('async/queue'); +var asyncEachSeries = require('async/eachSeries'); +var urlParser = require('url'); +var Resource = require('./Resource'); +var EventEmitter = require('eventemitter3'); + +// some constants +var DEFAULT_CONCURRENCY = 10; +var MAX_PROGRESS = 100; + +/** + * Manages the state and loading of multiple resources to load. + * + * @class + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ +function Loader(baseUrl, concurrency) { + EventEmitter.call(this); + + concurrency = concurrency || DEFAULT_CONCURRENCY; + + /** + * The base url for all resources loaded by this loader. + * + * @member {string} + */ + this.baseUrl = baseUrl || ''; + + /** + * The progress percent of the loader going through the queue. + * + * @member {number} + */ + this.progress = 0; + + /** + * Loading state of the loader, true if it is currently loading resources. + * + * @member {boolean} + */ + this.loading = false; + + /** + * The percentage of total progress that a single resource represents. + * + * @member {number} + */ + this._progressChunk = 0; + + /** + * The middleware to run before loading each resource. + * + * @member {function[]} + */ + this._beforeMiddleware = []; + + /** + * The middleware to run after loading each resource. + * + * @member {function[]} + */ + this._afterMiddleware = []; + + /** + * The `_loadResource` function bound with this object context. + * + * @private + * @member {function} + */ + this._boundLoadResource = this._loadResource.bind(this); + + /** + * The resource buffer that fills until `load` is called to start loading resources. + * + * @private + * @member {Resource[]} + */ + this._buffer = []; + + /** + * Used to track load completion. + * + * @private + * @member {number} + */ + this._numToLoad = 0; + + /** + * The resources waiting to be loaded. + * + * @private + * @member {Resource[]} + */ + this._queue = asyncQueue(this._boundLoadResource, concurrency); + + /** + * All the resources for this loader keyed by name. + * + * @member {object} + */ + this.resources = {}; + + /** + * Emitted once per loaded or errored resource. + * + * @event progress + * @memberof Loader# + */ + + /** + * Emitted once per errored resource. + * + * @event error + * @memberof Loader# + */ + + /** + * Emitted once per loaded resource. + * + * @event load + * @memberof Loader# + */ + + /** + * Emitted when the loader begins to process the queue. + * + * @event start + * @memberof Loader# + */ + + /** + * Emitted when the queued resources all load. + * + * @event complete + * @memberof Loader# + */ +} + +Loader.prototype = Object.create(EventEmitter.prototype); +Loader.prototype.constructor = Loader; +module.exports = Loader; + +/** + * Adds a resource (or multiple resources) to the loader queue. + * + * This function can take a wide variety of different parameters. The only thing that is always + * required the url to load. All the following will work: + * + * ```js + * loader + * // normal param syntax + * .add('key', 'http://...', function () {}) + * .add('http://...', function () {}) + * .add('http://...') + * + * // object syntax + * .add({ + * name: 'key2', + * url: 'http://...' + * }, function () {}) + * .add({ + * url: 'http://...' + * }, function () {}) + * .add({ + * name: 'key3', + * url: 'http://...' + * onComplete: function () {} + * }) + * .add({ + * url: 'https://...', + * onComplete: function () {}, + * crossOrigin: true + * }) + * + * // you can also pass an array of objects or urls or both + * .add([ + * { name: 'key4', url: 'http://...', onComplete: function () {} }, + * { url: 'http://...', onComplete: function () {} }, + * 'http://...' + * ]) + * + * // and you can use both params and options + * .add('key', 'http://...', { crossOrigin: true }, function () {}) + * .add('http://...', { crossOrigin: true }, function () {}); + * ``` + * + * @alias enqueue + * @param {string} [name] - The name of the resource to load, if not passed the url is used. + * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @param {object} [options] - The options for the load. + * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.XHR_LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should the data being + * loaded be interpreted when using XHR? + * @param {function} [cb] - Function to call when this specific resource completes loading. + * @return {Loader} Returns itself. + */ +Loader.prototype.add = Loader.prototype.enqueue = function (name, url, options, cb) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + + return this; + } + + // if an object is passed instead of params + if (typeof name === 'object') { + cb = url || name.callback || name.onComplete; + options = name; + url = name.url; + name = name.name || name.key || name.url; + } + + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + cb = options; + options = url; + url = name; + } + + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + cb = options; + options = null; + } + + // check if resource already exists. + if (this.resources[name]) { + throw new Error('Resource with name "' + name + '" already exists.'); + } + + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + + // create the store the resource + this.resources[name] = new Resource(name, url, options); + + if (typeof cb === 'function') { + this.resources[name].once('afterMiddleware', cb); + } + + this._numToLoad++; + + // if already loading add it to the worker queue + if (this._queue.started) { + this._queue.push(this.resources[name]); + this._progressChunk = (MAX_PROGRESS - this.progress) / (this._queue.length() + this._queue.running()); + } + // otherwise buffer it to be added to the queue later + else { + this._buffer.push(this.resources[name]); + this._progressChunk = MAX_PROGRESS / this._buffer.length; + } + + return this; +}; + +/** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * + * @alias pre + * @method before + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ +Loader.prototype.before = Loader.prototype.pre = function (fn) { + this._beforeMiddleware.push(fn); + + return this; +}; + +/** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * + * @alias use + * @method after + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ +Loader.prototype.after = Loader.prototype.use = function (fn) { + this._afterMiddleware.push(fn); + + return this; +}; + +/** + * Resets the queue of the loader to prepare for a new load. + * + * @return {Loader} Returns itself. + */ +Loader.prototype.reset = function () { + // this.baseUrl = baseUrl || ''; + + this.progress = 0; + + this.loading = false; + + this._progressChunk = 0; + + // this._beforeMiddleware.length = 0; + // this._afterMiddleware.length = 0; + + this._buffer.length = 0; + + this._numToLoad = 0; + + this._queue.kill(); + this._queue.started = false; + + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + + res.off('complete', this._onLoad, this); + + if (res.isLoading) { + res.abort(); + } + } + + this.resources = {}; + + return this; +}; + +/** + * Starts loading the queued resources. + * + * @fires start + * @param {function} [cb] - Optional callback that will be bound to the `complete` event. + * @return {Loader} Returns itself. + */ +Loader.prototype.load = function (cb) { + // register complete callback if they pass one + if (typeof cb === 'function') { + this.once('complete', cb); + } + + // if the queue has already started we are done here + if (this._queue.started) { + return this; + } + + // notify of start + this.emit('start', this); + + // update loading state + this.loading = true; + + // start the internal queue + for (var i = 0; i < this._buffer.length; ++i) { + this._queue.push(this._buffer[i]); + } + + // empty the buffer + this._buffer.length = 0; + + return this; +}; + +/** + * Prepares a url for usage based on the configuration of this object + * + * @private + * @param {string} url - The url to prepare. + * @return {string} The prepared url. + */ +Loader.prototype._prepareUrl = function (url) { + var parsedUrl = urlParser.parse(url); + + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.pathname || parsedUrl.pathname.indexOf('//') === 0) { + return url; + } + + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + if (this.baseUrl.length + && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 + && url.charAt(0) !== '/' + ) { + return this.baseUrl + '/' + url; + } + + return this.baseUrl + url; +}; + +/** + * Loads a single resource. + * + * @private + * @param {Resource} resource - The resource to load. + * @param {function} dequeue - The function to call when we need to dequeue this item. + */ +Loader.prototype._loadResource = function (resource, dequeue) { + var self = this; + + resource._dequeue = dequeue; + + // run before middleware + asyncEachSeries( + this._beforeMiddleware, + function (fn, next) { + fn.call(self, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, + function () { + // resource.on('progress', self.emit.bind(self, 'progress')); + + if (resource.isComplete) { + self._onLoad(resource); + } + else { + resource.once('complete', self._onLoad, self); + resource.load(); + } + } + ); +}; + +/** + * Called once each resource has loaded. + * + * @fires complete + * @private + */ +Loader.prototype._onComplete = function () { + this.loading = false; + + this.emit('complete', this, this.resources); +}; + +/** + * Called each time a resources is loaded. + * + * @fires progress + * @fires error + * @fires load + * @private + * @param {Resource} resource - The resource that was loaded + */ +Loader.prototype._onLoad = function (resource) { + var self = this; + + // run middleware, this *must* happen before dequeue so sub-assets get added properly + asyncEachSeries( + this._afterMiddleware, + function (fn, next) { + fn.call(self, resource, next); + }, + function () { + resource.emit('afterMiddleware', resource); + + self._numToLoad--; + + self.progress += self._progressChunk; + self.emit('progress', self, resource); + + if (resource.error) { + self.emit('error', resource.error, self, resource); + } + else { + self.emit('load', self, resource); + } + + // do completion check + if (self._numToLoad === 0) { + self.progress = 100; + self._onComplete(); + } + } + ); + + // remove this resource from the async queue + resource._dequeue(); +}; + +Loader.LOAD_TYPE = Resource.LOAD_TYPE; +Loader.XHR_RESPONSE_TYPE = Resource.XHR_RESPONSE_TYPE; + +},{"./Resource":67,"async/eachSeries":18,"async/queue":29,"eventemitter3":32,"url":72}],67:[function(require,module,exports){ +'use strict'; + +var EventEmitter = require('eventemitter3'); +var _url = require('url'); + +// tests is CORS is supported in XHR, if not we need to use XDR +var useXdr = !!(window.XDomainRequest && !('withCredentials' in (new XMLHttpRequest()))); +var tempAnchor = null; + +// some status constants +var STATUS_NONE = 0; +var STATUS_OK = 200; +var STATUS_EMPTY = 204; + +/** + * Manages the state and loading of a single resource represented by + * a single URL. + * + * @class + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should the data being + * loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra info for middleware. + */ +function Resource(name, url, options) { + EventEmitter.call(this); + + options = options || {}; + + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + + /** + * The name of this resource. + * + * @member {string} + * @readonly + */ + this.name = name; + + /** + * The url used to load this resource. + * + * @member {string} + * @readonly + */ + this.url = url; + + /** + * Stores whether or not this url is a data url. + * + * @member {boolean} + * @readonly + */ + this.isDataUrl = this.url.indexOf('data:') === 0; + + /** + * The data that was loaded by the resource. + * + * @member {any} + */ + this.data = null; + + /** + * Is this request cross-origin? If unset, determined automatically. + * + * @member {string} + */ + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + + /** + * The method of loading to use for this resource. + * + * @member {Resource.LOAD_TYPE} + */ + this.loadType = options.loadType || this._determineLoadType(); + + /** + * The type used to load the resource via XHR. If unset, determined automatically. + * + * @member {string} + */ + this.xhrType = options.xhrType; + + /** + * Extra info for middleware, and controlling specifics about how the resource loads. + * + * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + * Meaning it will modify it as it sees fit. + * + * @member {object} + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources + * to. + */ + this.metadata = options.metadata || {}; + + /** + * The error that occurred while loading (if any). + * + * @member {Error} + * @readonly + */ + this.error = null; + + /** + * The XHR object that was used to load this resource. This is only set + * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * + * @member {XMLHttpRequest} + */ + this.xhr = null; + + /** + * Describes if this resource was loaded as json. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isJson = false; + + /** + * Describes if this resource was loaded as xml. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isXml = false; + + /** + * Describes if this resource was loaded as an image tag. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isImage = false; + + /** + * Describes if this resource was loaded as an audio tag. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isAudio = false; + + /** + * Describes if this resource was loaded as a video tag. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isVideo = false; + + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * + * @member {boolean} + */ + this.isComplete = false; + + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * + * @member {boolean} + */ + this.isLoading = false; + + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * + * @private + * @member {function} + */ + this._dequeue = null; + + /** + * The `complete` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundComplete = this.complete.bind(this); + + /** + * The `_onError` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnError = this._onError.bind(this); + + /** + * The `_onProgress` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnProgress = this._onProgress.bind(this); + + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + this._boundXdrOnTimeout = this._xdrOnTimeout.bind(this); + + /** + * Emitted when the resource beings to load. + * + * @event start + * @memberof Resource# + */ + + /** + * Emitted each time progress of this resource load updates. + * Not all resources types and loader systems can support this event + * so sometimes it may not be available. If the resource + * is being loaded on a modern browser, using XHR, and the remote server + * properly sets Content-Length headers, then this will be available. + * + * @event progress + * @memberof Resource# + */ + + /** + * Emitted once this resource has loaded, if there was an error it will + * be in the `error` property. + * + * @event complete + * @memberof Resource# + */ +} + +Resource.prototype = Object.create(EventEmitter.prototype); +Resource.prototype.constructor = Resource; +module.exports = Resource; + +/** + * Marks the resource as complete. + * + * @fires complete + */ +Resource.prototype.complete = function () { + // TODO: Clean this up in a wrapper or something...gross.... + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } + else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + + this.isComplete = true; + this.isLoading = false; + + this.emit('complete', this); +}; + +/** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ +Resource.prototype.abort = function (message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + + // store error + this.error = new Error(message); + + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } + else if (this.xdr) { + this.xdr.abort(); + } + else if (this.data) { + // single source + if (typeof this.data.src !== 'undefined') { + this.data.src = ''; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + + // done now. + this.complete(); +}; + +/** + * Kicks off loading of this resource. This method is asynchronous. + * + * @fires start + * @param {function} [cb] - Optional callback to call once the resource is loaded. + */ +Resource.prototype.load = function (cb) { + if (this.isLoading) { + return; + } + + if (this.isComplete) { + if (cb) { + var self = this; + + setTimeout(function () { + cb(self); + }, 1); + } + + return; + } + else if (cb) { + this.once('complete', cb); + } + + this.isLoading = true; + + this.emit('start', this); + + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + + switch (this.loadType) { + case Resource.LOAD_TYPE.IMAGE: + this._loadElement('image'); + break; + + case Resource.LOAD_TYPE.AUDIO: + this._loadSourceElement('audio'); + break; + + case Resource.LOAD_TYPE.VIDEO: + this._loadSourceElement('video'); + break; + + case Resource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } + else { + this._loadXhr(); + } + break; + } +}; + +/** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * + * @private + * @param {string} type - The type of element to use. + */ +Resource.prototype._loadElement = function (type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } + else if (type === 'image' && typeof window.Image !== 'undefined') { + this.data = new Image(); + } + else { + this.data = document.createElement(type); + } + + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + + var typeName = 'is' + type[0].toUpperCase() + type.substring(1); + + if (this[typeName] === false) { + this[typeName] = true; + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); +}; + +/** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * + * @private + * @param {string} type - The type of element to use. + */ +Resource.prototype._loadSourceElement = function (type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } + else if (type === 'audio' && typeof window.Audio !== 'undefined') { + this.data = new Audio(); + } + else { + this.data = document.createElement(type); + } + + if (this.data === null) { + this.abort('Unsupported element ' + type); + + return; + } + + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } + else if (Array.isArray(this.url)) { + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i])); + } + } + else { + this.data.appendChild(this._createSource(type, this.url)); + } + } + + this['is' + type[0].toUpperCase() + type.substring(1)] = true; + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + + this.data.load(); +}; + +/** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ +Resource.prototype._loadXhr = function () { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xhr = this.xhr = new XMLHttpRequest(); + + // set the request type and url + xhr.open('GET', this.url, true); + + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; + } + else { + xhr.responseType = this.xhrType; + } + + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + + xhr.send(); +}; + +/** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ +Resource.prototype._loadXdr = function () { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xdr = this.xhr = new XDomainRequest(); + + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = 5000; + + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXdrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + + xdr.open('GET', this.url, true); + + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { + xdr.send(); + }, 0); +}; + +/** + * Creates a source used in loading via an element. + * + * @private + * @param {string} type - The element type (video or audio). + * @param {string} url - The source URL to load from. + * @param {string} [mime] - The mime type of the video + * @return {HTMLSourceElement} The source element. + */ +Resource.prototype._createSource = function (type, url, mime) { + if (!mime) { + mime = type + '/' + url.substr(url.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = url; + source.type = mime; + + return source; +}; + +/** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ +Resource.prototype._onError = function (event) { + this.abort('Failed to load element using ' + event.target.nodeName); +}; + +/** + * Called if a load progress event fires for xhr/xdr. + * + * @fires progress + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ +Resource.prototype._onProgress = function (event) { + if (event && event.lengthComputable) { + this.emit('progress', this, event.loaded / event.total); + } +}; + +/** + * Called if an error event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestErrorEvent|Event} event - Error event. + */ +Resource.prototype._xhrOnError = function () { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"'); +}; + +/** + * Called if an abort event fires for xhr. + * + * @private + * @param {XMLHttpRequestAbortEvent} event - Abort Event + */ +Resource.prototype._xhrOnAbort = function () { + this.abort(reqType(this.xhr) + ' Request was aborted by the user.'); +}; + +/** + * Called if a timeout event fires for xdr. + * + * @private + * @param {Event} event - Timeout event. + */ +Resource.prototype._xdrOnTimeout = function () { + this.abort(reqType(this.xhr) + ' Request timed out.'); +}; + +/** + * Called when data successfully loads from an xhr/xdr request. + * + * @private + * @param {XMLHttpRequestLoadEvent|Event} event - Load event + */ +Resource.prototype._xhrOnLoad = function () { + var xhr = this.xhr; + var status = typeof xhr.status === 'undefined' ? xhr.status : STATUS_OK; // XDR has no `.status`, assume 200. + + // status can be 0 when using the file:// protocol, also check if a response was found + if (status === STATUS_OK || status === STATUS_EMPTY || (status === STATUS_NONE && xhr.responseText.length > 0)) { + // if text, just return it + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { + this.data = xhr.responseText; + } + // if json, parse into json object + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(xhr.responseText); + this.isJson = true; + } + catch (e) { + this.abort('Error trying to parse loaded json:', e); + + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (window.DOMParser) { + var domparser = new DOMParser(); + + this.data = domparser.parseFromString(xhr.responseText, 'text/xml'); + } + else { + var div = document.createElement('div'); + + div.innerHTML = xhr.responseText; + this.data = div; + } + this.isXml = true; + } + catch (e) { + this.abort('Error trying to parse loaded xml:', e); + + return; + } + } + // other types just return the response + else { + this.data = xhr.response || xhr.responseText; + } + } + else { + this.abort('[' + xhr.status + ']' + xhr.statusText + ':' + xhr.responseURL); + + return; + } + + this.complete(); +}; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * + * @private + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +Resource.prototype._determineCrossOrigin = function (url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url.parse(tempAnchor.href); + + var samePort = (!url.port && loc.port === '') || (url.port === loc.port); + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +}; + +/** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. + */ +Resource.prototype._determineXhrType = function () { + return Resource._xhrTypeMap[this._getExtension()] || Resource.XHR_RESPONSE_TYPE.TEXT; +}; + +Resource.prototype._determineLoadType = function () { + return Resource._loadTypeMap[this._getExtension()] || Resource.LOAD_TYPE.XHR; +}; + +Resource.prototype._getExtension = function () { + var url = this.url; + var ext = ''; + + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } + else { + var queryStart = url.indexOf('?'); + + if (queryStart !== -1) { + url = url.substring(0, queryStart); + } + + ext = url.substring(url.lastIndexOf('.') + 1); + } + + return ext.toLowerCase(); +}; + +/** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * + * @private + * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. + * @return {string} The mime type to use. + */ +Resource.prototype._getMimeFromXhrType = function (type) { + switch (type) { + case Resource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + + case Resource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + + case Resource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + + case Resource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + + case Resource.XHR_RESPONSE_TYPE.DEFAULT: + case Resource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + + } +}; + +/** + * Quick helper to get string xhr type. + * + * @ignore + * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. + * @return {string} The type. + */ +function reqType(xhr) { + return xhr.toString().replace('object ', ''); +} + +/** + * The types of loading a resource can use. + * + * @static + * @readonly + * @enum {number} + */ +Resource.LOAD_TYPE = { + /** Uses XMLHttpRequest to load the resource. */ + XHR: 1, + /** Uses an `Image` object to load the resource. */ + IMAGE: 2, + /** Uses an `Audio` object to load the resource. */ + AUDIO: 3, + /** Uses a `Video` object to load the resource. */ + VIDEO: 4 +}; + +/** + * The XHR ready states, used internally. + * + * @static + * @readonly + * @enum {string} + */ +Resource.XHR_RESPONSE_TYPE = { + /** defaults to text */ + DEFAULT: 'text', + /** ArrayBuffer */ + BUFFER: 'arraybuffer', + /** Blob */ + BLOB: 'blob', + /** Document */ + DOCUMENT: 'document', + /** Object */ + JSON: 'json', + /** String */ + TEXT: 'text' +}; + +Resource._loadTypeMap = { + gif: Resource.LOAD_TYPE.IMAGE, + png: Resource.LOAD_TYPE.IMAGE, + bmp: Resource.LOAD_TYPE.IMAGE, + jpg: Resource.LOAD_TYPE.IMAGE, + jpeg: Resource.LOAD_TYPE.IMAGE, + tif: Resource.LOAD_TYPE.IMAGE, + tiff: Resource.LOAD_TYPE.IMAGE, + webp: Resource.LOAD_TYPE.IMAGE, + tga: Resource.LOAD_TYPE.IMAGE, + 'svg+xml': Resource.LOAD_TYPE.IMAGE +}; + +Resource._xhrTypeMap = { + // xml + xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // images + gif: Resource.XHR_RESPONSE_TYPE.BLOB, + png: Resource.XHR_RESPONSE_TYPE.BLOB, + bmp: Resource.XHR_RESPONSE_TYPE.BLOB, + jpg: Resource.XHR_RESPONSE_TYPE.BLOB, + jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, + tif: Resource.XHR_RESPONSE_TYPE.BLOB, + tiff: Resource.XHR_RESPONSE_TYPE.BLOB, + webp: Resource.XHR_RESPONSE_TYPE.BLOB, + tga: Resource.XHR_RESPONSE_TYPE.BLOB, + + // json + json: Resource.XHR_RESPONSE_TYPE.JSON, + + // text + text: Resource.XHR_RESPONSE_TYPE.TEXT, + txt: Resource.XHR_RESPONSE_TYPE.TEXT +}; + +/** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. + */ +Resource.setExtensionLoadType = function (extname, loadType) { + setExtMap(Resource._loadTypeMap, extname, loadType); +}; + +/** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ +Resource.setExtensionXhrType = function (extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); +}; + +function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + + if (!extname) { + return; + } + + map[extname] = val; +} + +},{"eventemitter3":32,"url":72}],68:[function(require,module,exports){ +/* eslint no-magic-numbers: 0 */ +'use strict'; + +module.exports = { + // private property + _keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', + + encodeBinary: function (input) { + var output = ''; + var bytebuffer; + var encodedCharIndexes = new Array(4); + var inx = 0; + var jnx = 0; + var paddingBytes = 0; + + while (inx < input.length) { + // Fill byte buffer array + bytebuffer = new Array(3); + + for (jnx = 0; jnx < bytebuffer.length; jnx++) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } + else { + bytebuffer[jnx] = 0; + } + } + + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = ((bytebuffer[0] & 0x3) << 4) | (bytebuffer[1] >> 4); + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = ((bytebuffer[1] & 0x0f) << 2) | (bytebuffer[2] >> 6); + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + + // Determine whether padding happened, and adjust accordingly + paddingBytes = inx - (input.length - 1); + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + + default: + break; // No padding - proceed + } + + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (jnx = 0; jnx < encodedCharIndexes.length; jnx++) { + output += this._keyStr.charAt(encodedCharIndexes[jnx]); + } + } + + return output; + } +}; + +},{}],69:[function(require,module,exports){ +/* eslint global-require: 0 */ +'use strict'; + +module.exports = require('./Loader'); +module.exports.Resource = require('./Resource'); +module.exports.middleware = { + caching: { + memory: require('./middlewares/caching/memory') + }, + parsing: { + blob: require('./middlewares/parsing/blob') + } +}; + + +},{"./Loader":66,"./Resource":67,"./middlewares/caching/memory":70,"./middlewares/parsing/blob":71}],70:[function(require,module,exports){ +'use strict'; + +// a simple in-memory cache for resources +var cache = {}; + +module.exports = function () { + return function (resource, next) { + // if cached, then set data and complete the resource + if (cache[resource.url]) { + resource.data = cache[resource.url]; + resource.complete(); // marks resource load complete and stops processing before middlewares + } + // if not cached, wait for complete and store it in the cache. + else { + resource.once('complete', function () { + cache[this.url] = this.data; + }); + } + + next(); + }; +}; + +},{}],71:[function(require,module,exports){ +'use strict'; + +var Resource = require('../../Resource'); +var b64 = require('../../b64'); + +var Url = window.URL || window.webkitURL; + +// a middleware for transforming XHR loaded Blobs into more useful objects + +module.exports = function () { + return function (resource, next) { + if (!resource.data) { + next(); + + return; + } + + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === Resource.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!window.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = 'data:' + type + ';base64,' + b64.encodeBinary(resource.xhr.responseText); + + resource.isImage = true; + + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + + next(); + }; + + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var src = Url.createObjectURL(resource.data); + + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src; + + resource.isImage = true; + + // cleanup the no longer used blob after the image loads + resource.data.onload = function () { + Url.revokeObjectURL(src); + resource.data.onload = null; + + next(); + }; + + // next will be called on load. + return; + } + } + + next(); + }; +}; + +},{"../../Resource":67,"../../b64":68}],72:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":73,"punycode":62,"querystring":65}],73:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],74:[function(require,module,exports){ +var core = require('../core'); +var Device = require('ismobilejs'); + +// add some extra variables to the container.. +Object.assign( + core.DisplayObject.prototype, + require('./accessibleTarget') +); + + +/** + * The Accessibility manager reacreates the ability to tab and and have content read by screen readers. This is very important as it can possibly help people with disabilities access pixi content. + * Much like interaction any DisplayObject can be made accessible. This manager will map the events as if the mouse was being used, minimizing the efferot required to implement. + * + * @class + * @memberof PIXI + * @param renderer {PIXI.CanvasRenderer|PIXI.WebGLRenderer} A reference to the current renderer + */ +function AccessibilityManager(renderer) +{ + if((Device.tablet || Device.phone) && !navigator.isCocoonJS) + { + this.createTouchHook(); + } + + // first we create a div that will sit over the pixi element. This is where the div overlays will go. + var div = document.createElement('div'); + + div.style.width = 100 + 'px'; + div.style.height = 100 + 'px'; + div.style.position = 'absolute'; + div.style.top = 0; + div.style.left = 0; + // + div.style.zIndex = 2; + + /** + * This is the dom element that will sit over the pixi element. This is where the div overlays will go. + * + * @type {HTMLElement} + * @private + */ + this.div = div; + + /** + * A simple pool for storing divs. + * + * @type {*} + * @private + */ + this.pool = []; + + /** + * This is a tick used to check if an object is no longer being rendered. + * + * @type {Number} + * @private + */ + this.renderId = 0; + + /** + * Setting this to true will visually show the divs + * + * @type {boolean} + */ + this.debug = false; + + /** + * The renderer this accessibility manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * The array of currently active accessible items. + * + * @member {Array<*>} + * @private + */ + this.children = []; + + /** + * pre-bind the functions + * + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + + /** + * stores the state of the manager. If there are no accessible objects or the mouse is moving the will be false. + * + * @member {Array<*>} + * @private + */ + this.isActive = false; + this.isMobileAccessabillity = false; + + // let listen for tab.. once pressed we can fire up and show the accessibility layer + window.addEventListener('keydown', this._onKeyDown, false); +} + + +AccessibilityManager.prototype.constructor = AccessibilityManager; +module.exports = AccessibilityManager; + +AccessibilityManager.prototype.createTouchHook = function() +{ + var hookDiv = document.createElement('button'); + hookDiv.style.width = 1 + 'px'; + hookDiv.style.height = 1 + 'px'; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = -1000+'px'; + hookDiv.style.left = -1000+'px'; + hookDiv.style.zIndex = 2; + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'HOOK DIV'; + + hookDiv.addEventListener('focus', function(){ + + this.isMobileAccessabillity = true; + this.activate(); + document.body.removeChild(hookDiv); + + }.bind(this)); + + document.body.appendChild(hookDiv); + +}; + +/** + * Activating will cause the Accessibility layer to be shown. This is called when a user preses the tab key + * @private + */ +AccessibilityManager.prototype.activate = function() +{ + if(this.isActive ) + { + return; + } + + this.isActive = true; + + window.document.addEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown, false); + + this.renderer.on('postrender', this.update, this); + + if(this.renderer.view.parentNode) + { + this.renderer.view.parentNode.appendChild(this.div); + } +}; + +/** + * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves the mouse + * @private + */ +AccessibilityManager.prototype.deactivate = function() +{ + + if(!this.isActive || this.isMobileAccessabillity) + { + return; + } + + this.isActive = false; + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.addEventListener('keydown', this._onKeyDown, false); + + this.renderer.off('postrender', this.update); + + if(this.div.parentNode) + { + this.div.parentNode.removeChild(this.div); + } + +}; + +/** + * This recursive function will run throught he scene graph and add any new accessible objects to the DOM layer. + * @param displayObject {PIXI.Container} the DisplayObject to check. + * @private + */ +AccessibilityManager.prototype.updateAccessibleObjects = function(displayObject) +{ + if(!displayObject.visible) + { + return; + } + + if(displayObject.accessible && displayObject.interactive) + { + if(!displayObject._accessibleActive) + { + this.addChild(displayObject); + } + + displayObject.renderId = this.renderId; + } + + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + + this.updateAccessibleObjects(children[i]); + } +}; + + +/** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects + * @private + */ +AccessibilityManager.prototype.update = function() +{ + if(!this.renderer.renderingToScreen) { + return; + } + + // update children... + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + + var rect = this.renderer.view.getBoundingClientRect(); + var sx = rect.width / this.renderer.width; + var sy = rect.height / this.renderer.height; + + var div = this.div; + + div.style.left = rect.left + 'px'; + div.style.top = rect.top + 'px'; + div.style.width = this.renderer.width + 'px'; + div.style.height = this.renderer.height + 'px'; + + for (var i = 0; i < this.children.length; i++) + { + + var child = this.children[i]; + + if(child.renderId !== this.renderId) + { + child._accessibleActive = false; + + core.utils.removeItems(this.children, i, 1); + this.div.removeChild( child._accessibleDiv ); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + + i--; + + if(this.children.length === 0) + { + this.deactivate(); + } + } + else + { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + + if(child.hitArea) + { + div.style.left = ((wt.tx + (hitArea.x * wt.a)) * sx) + 'px'; + div.style.top = ((wt.ty + (hitArea.y * wt.d)) * sy) + 'px'; + + div.style.width = (hitArea.width * wt.a * sx) + 'px'; + div.style.height = (hitArea.height * wt.d * sy) + 'px'; + + } + else + { + hitArea = child.getBounds(); + + this.capHitArea(hitArea); + + div.style.left = (hitArea.x * sx) + 'px'; + div.style.top = (hitArea.y * sy) + 'px'; + + div.style.width = (hitArea.width * sx) + 'px'; + div.style.height = (hitArea.height * sy) + 'px'; + } + } + } + + // increment the render id.. + this.renderId++; +}; + +AccessibilityManager.prototype.capHitArea = function (hitArea) +{ + if (hitArea.x < 0) + { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + + if (hitArea.y < 0) + { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + + if ( hitArea.x + hitArea.width > this.renderer.width ) + { + hitArea.width = this.renderer.width - hitArea.x; + } + + if ( hitArea.y + hitArea.height > this.renderer.height ) + { + hitArea.height = this.renderer.height - hitArea.y; + } +}; + + +/** + * Adds a DisplayObject to the accessibility manager + * @private + */ +AccessibilityManager.prototype.addChild = function(displayObject) +{ +// this.activate(); + + var div = this.pool.pop(); + + if(!div) + { + div = document.createElement('button'); + + div.style.width = 100 + 'px'; + div.style.height = 100 + 'px'; + div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = 2; + div.style.borderStyle = 'none'; + + + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + + + if(displayObject.accessibleTitle) + { + div.title = displayObject.accessibleTitle; + } + else if (!displayObject.accessibleTitle && !displayObject.accessibleHint) + { + div.title = 'displayObject ' + this.tabIndex; + } + + if(displayObject.accessibleHint) + { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + + + // + + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + + + this.children.push(displayObject); + this.div.appendChild( displayObject._accessibleDiv ); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; +}; + + +/** + * Maps the div button press to pixi's InteractionManager (click) + * @private + */ +AccessibilityManager.prototype._onClick = function(e) +{ + var interactionManager = this.renderer.plugins.interaction; + interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); +}; + +/** + * Maps the div focus events to pixis InteractionManager (mouseover) + * @private + */ +AccessibilityManager.prototype._onFocus = function(e) +{ + var interactionManager = this.renderer.plugins.interaction; + interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); +}; + +/** + * Maps the div focus events to pixis InteractionManager (mouseout) + * @private + */ +AccessibilityManager.prototype._onFocusOut = function(e) +{ + var interactionManager = this.renderer.plugins.interaction; + interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); +}; + +/** + * Is called when a key is pressed + * + * @private + */ +AccessibilityManager.prototype._onKeyDown = function(e) +{ + if(e.keyCode !== 9) + { + return; + } + + this.activate(); +}; + +/** + * Is called when the mouse moves across the renderer element + * + * @private + */ +AccessibilityManager.prototype._onMouseMove = function() +{ + this.deactivate(); +}; + + +/** + * Destroys the accessibility manager + * + */ +AccessibilityManager.prototype.destroy = function () +{ + this.div = null; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].div = null; + } + + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.removeEventListener('keydown', this._onKeyDown); + + this.pool = null; + this.children = null; + this.renderer = null; + +}; + +core.WebGLRenderer.registerPlugin('accessibility', AccessibilityManager); +core.CanvasRenderer.registerPlugin('accessibility', AccessibilityManager); + +},{"../core":97,"./accessibleTarget":75,"ismobilejs":33}],75:[function(require,module,exports){ +/** + * Default property values of accessible objects + * used by {@link PIXI.accessibility.AccessibilityManager}. + * + * @mixin + * @memberof PIXI + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibility.accessibleTarget + * ); + */ +var accessibleTarget = { + + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * + * @member {boolean} + */ + accessible:false, + + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * + * @member {string} + */ + accessibleTitle:null, + + /** + * Sets the aria-label attribute of the shadow div + * + * @member {string} + */ + accessibleHint:null, + + /** + * @todo Needs docs. + */ + tabIndex:0, + + /** + * @todo Needs docs. + */ + _accessibleActive:false, + + /** + * @todo Needs docs. + */ + _accessibleDiv:false + +}; + +module.exports = accessibleTarget; + +},{}],76:[function(require,module,exports){ +/** + * @file Main export of the PIXI accessibility library + * @author Mat Groves + * @copyright 2013-2015 GoodBoyDigital + * @license {@link https://github.com/pixijs/pixi.js/blob/master/LICENSE|MIT License} + */ + +/** + * @namespace PIXI.AccessibilityManager + */ +module.exports = { + accessibleTarget: require('./accessibleTarget'), + AccessibilityManager: require('./AccessibilityManager') +}; + +},{"./AccessibilityManager":74,"./accessibleTarget":75}],77:[function(require,module,exports){ +var GLShader = require('pixi-gl-core').GLShader; +var Const = require('./const'); + +function checkPrecision(src) { + if (src instanceof Array) { + if (src[0].substring(0,9) !== 'precision') { + var copy = src.slice(0); + copy.unshift('precision ' + Const.PRECISION.DEFAULT + ' float;'); + return copy; + } + } else { + if (src.substring(0,9) !== 'precision') { + return 'precision ' + Const.PRECISION.DEFAULT + ' float;\n' + src; + } + } + return src; +} + +/** + * Wrapper class, webGL Shader for Pixi. + * Adds precision string if vertexSrc or fragmentSrc have no mention of it. + * + * @class + * @memberof PIXI + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations. + */ +var Shader = function(gl, vertexSrc, fragmentSrc, attributeLocations) { + GLShader.call(this, gl, checkPrecision(vertexSrc), checkPrecision(fragmentSrc), attributeLocations); +}; + +Shader.prototype = Object.create(GLShader.prototype); +Shader.prototype.constructor = Shader; +module.exports = Shader; + +},{"./const":78,"pixi-gl-core":7}],78:[function(require,module,exports){ + +/** + * Constant values used in pixi + * + * @lends PIXI + */ +var CONST = { + /** + * String of the current PIXI version. + * + * @static + * @constant + * @type {string} + */ + VERSION: '4.0.2', + + /** + * Two Pi. + * + * @static + * @constant + * @type {number} + */ + PI_2: Math.PI * 2, + + /** + * Conversion factor for converting radians to degrees. + * + * @static + * @constant + * @type {number} + */ + RAD_TO_DEG: 180 / Math.PI, + + /** + * Conversion factor for converting degrees to radians. + * + * @static + * @constant + * @type {number} + */ + DEG_TO_RAD: Math.PI / 180, + + /** + * Target frames per millisecond. + * + * @static + * @constant + * @type {number} + * @default 0.06 + */ + TARGET_FPMS: 0.06, + + /** + * Constant to identify the Renderer Type. + * + * @static + * @constant + * @type {object} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + RENDERER_TYPE: { + UNKNOWN: 0, + WEBGL: 1, + CANVAS: 2 + }, + + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * + * @static + * @constant + * @type {object} + * @property {number} NORMAL + * @property {number} ADD + * @property {number} MULTIPLY + * @property {number} SCREEN + * @property {number} OVERLAY + * @property {number} DARKEN + * @property {number} LIGHTEN + * @property {number} COLOR_DODGE + * @property {number} COLOR_BURN + * @property {number} HARD_LIGHT + * @property {number} SOFT_LIGHT + * @property {number} DIFFERENCE + * @property {number} EXCLUSION + * @property {number} HUE + * @property {number} SATURATION + * @property {number} COLOR + * @property {number} LUMINOSITY + */ + BLEND_MODES: { + NORMAL: 0, + ADD: 1, + MULTIPLY: 2, + SCREEN: 3, + OVERLAY: 4, + DARKEN: 5, + LIGHTEN: 6, + COLOR_DODGE: 7, + COLOR_BURN: 8, + HARD_LIGHT: 9, + SOFT_LIGHT: 10, + DIFFERENCE: 11, + EXCLUSION: 12, + HUE: 13, + SATURATION: 14, + COLOR: 15, + LUMINOSITY: 16 + }, + + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * + * @static + * @constant + * @type {object} + * @property {number} POINTS + * @property {number} LINES + * @property {number} LINE_LOOP + * @property {number} LINE_STRIP + * @property {number} TRIANGLES + * @property {number} TRIANGLE_STRIP + * @property {number} TRIANGLE_FAN + */ + DRAW_MODES: { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6 + }, + + /** + * The scale modes that are supported by pixi. + * + * The DEFAULT scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @static + * @constant + * @type {object} + * @property {number} DEFAULT=LINEAR + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + SCALE_MODES: { + DEFAULT: 0, + LINEAR: 0, + NEAREST: 1 + }, + + /** + * The wrap modes that are supported by pixi. + * + * The DEFAULT wrap mode affects the default wraping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as webGL can only use REPEAT if the texture is po2. + * This property only affects WebGL. + * + * @static + * @constant + * @type {object} + * @property {number} DEFAULT=CLAMP + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + WRAP_MODES: { + DEFAULT: 0, + CLAMP: 0, + REPEAT: 1, + MIRRORED_REPEAT:2 + }, + + /** + * The gc modes that are supported by pixi. + * + * The DEFAULT Garbage Collection mode for pixi textures is MANUAL + * If set to DEFAULT, the renderer will occasianally check textures usage. If they are not used for a specified period of time they will be removed from the GPU. + * They will of corse be uploaded again when they are required. This is a silent behind the scenes process that should ensure that the GPU does not get filled up. + * Handy for mobile devices! + * This property only affects WebGL. + * + * @static + * @constant + * @type {object} + * @property {number} DEFAULT=MANUAL + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + GC_MODES: { + DEFAULT: 0, + AUTO: 0, + MANUAL: 1, + }, + + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * + * @static + * @constant + * @type {boolean} + */ + MIPMAP_TEXTURES: true, + + /** + * The prefix that denotes a URL is for a retina asset. + * + * @static + * @constant + * @type {RegExp|string} + * @example `@2x` + */ + RETINA_PREFIX: /@(.+)x/, + + /** + * Default resolution / device pixel ratio of the renderer. + * + * @static + * @constant + * @type {number} + */ + RESOLUTION: 1, + + /** + * Default filter resolution. + * + * @static + * @constant + * @type {number} + */ + FILTER_RESOLUTION:1, + + /** + * The default render options if none are supplied to {@link PIXI.WebGLRenderer} + * or {@link PIXI.CanvasRenderer}. + * + * @static + * @constant + * @type {object} + * @property {HTMLCanvasElement} view=null + * @property {number} resolution=1 + * @property {boolean} antialias=false + * @property {boolean} forceFXAA=false + * @property {boolean} autoResize=false + * @property {boolean} transparent=false + * @property {number} backgroundColor=0x000000 + * @property {boolean} clearBeforeRender=true + * @property {boolean} preserveDrawingBuffer=false + * @property {boolean} roundPixels=false + */ + DEFAULT_RENDER_OPTIONS: { + view: null, + resolution: 1, + antialias: false, + forceFXAA: false, + autoResize: false, + transparent: false, + backgroundColor: 0x000000, + clearBeforeRender: true, + preserveDrawingBuffer: false, + roundPixels: false + }, + + /** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * + * @static + * @constant + * @type {object} + * @property {number} POLY + * @property {number} RECT + * @property {number} CIRC + * @property {number} ELIP + * @property {number} RREC + */ + SHAPES: { + POLY: 0, + RECT: 1, + CIRC: 2, + ELIP: 3, + RREC: 4 + }, + + /** + * Constants that specify float precision in shaders. + * + * @static + * @constant + * @type {object} + * @property {number} DEFAULT='mediump' + * @property {number} LOW='lowp' + * @property {number} MEDIUM='mediump' + * @property {number} HIGH='highp' + */ + PRECISION: { + DEFAULT: 'mediump', + LOW: 'lowp', + MEDIUM: 'mediump', + HIGH: 'highp' + }, + + /** + * Constants that specify the transform type. + * + * @static + * @constant + * @type {object} + * @property {number} DEFAULT=STATIC + * @property {number} STATIC + * @property {number} DYNAMIC + */ + TRANSFORM_MODE:{ + DEFAULT: 0, + STATIC: 0, + DYNAMIC: 1 + }, + + /** + * Constants that define the type of gradient on text. + * + * @static + * @constant + * @type {object} + * @property {number} LINEAR_VERTICAL + * @property {number} LINEAR_HORIZONTAL + */ + TEXT_GRADIENT: { + LINEAR_VERTICAL: 0, + LINEAR_HORIZONTAL: 1 + }, + + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * + * @static + * @constant + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + + /** + * The maximum textures that this device supports. + * + * @static + * @constant + * @type {number} + */ + SPRITE_MAX_TEXTURES: require('./utils/maxRecommendedTextures')(32) +}; + +module.exports = CONST; + +},{"./utils/maxRecommendedTextures":152}],79:[function(require,module,exports){ +var math = require('../math'), + Rectangle = math.Rectangle; + +/** + * 'Builder' pattern for bounds rectangles + * Axis-Aligned Bounding Box + * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems + * + * @class + * @memberof PIXI + */ +function Bounds() +{ + /** + * @member {number} + * @default 0 + */ + this.minX = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.minY = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxX = -Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxY = -Infinity; + + this.rect = null; +} + +Bounds.prototype.constructor = Bounds; +module.exports = Bounds; + +Bounds.prototype.isEmpty = function() +{ + return this.minX > this.maxX || this.minY > this.maxY; +}; + +Bounds.prototype.clear = function() +{ + this.updateID++; + + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; +}; + +/** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * @param tempRect {PIXI.Rectangle} temporary object will be used if AABB is not empty + * @returns {PIXI.Rectangle} + */ +Bounds.prototype.getRectangle = function(rect) +{ + if (this.minX > this.maxX || this.minY > this.maxY) { + return Rectangle.EMPTY; + } + + rect = rect || new Rectangle(0, 0, 1, 1); + + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + + return rect; +}; + +/** + * This function should be inlined when its possible + * @param point {PIXI.Point} + */ +Bounds.prototype.addPoint = function (point) +{ + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); +}; + +/** + * Adds a quad, not transformed + * @param vertices {Float32Array} + * @returns {PIXI.Bounds} + */ +Bounds.prototype.addQuad = function(vertices) +{ + var minX = this.minX, minY = this.minY, maxX = this.maxX, maxY = this.maxY; + + var x = vertices[0]; + var y = vertices[1]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; +}; + +/** + * Adds sprite frame, transformed + * @param transform {PIXI.TransformBase} + * @param x0 {number} + * @param y0 {number} + * @param x1 {number} + * @param y1 {number} + */ +Bounds.prototype.addFrame = function(transform, x0, y0, x1, y1) +{ + var matrix = transform.worldTransform; + var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d, tx = matrix.tx, ty = matrix.ty; + var minX = this.minX, minY = this.minY, maxX = this.maxX, maxY = this.maxY; + + var x = a * x0 + c * y0 + tx; + var y = b * x0 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y0 + tx; + y = b * x1 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x0 + c * y1 + tx; + y = b * x0 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y1 + tx; + y = b * x1 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; +}; + +/** + * add an array of vertices + * @param transform {PIXI.TransformBase} + * @param vertices {Float32Array} + * @param beginOffset {number} + * @param endOffset {number} + */ +Bounds.prototype.addVertices = function(transform, vertices, beginOffset, endOffset) +{ + var matrix = transform.worldTransform; + var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d, tx = matrix.tx, ty = matrix.ty; + var minX = this.minX, minY = this.minY, maxX = this.maxX, maxY = this.maxY; + + for (var i = beginOffset; i < endOffset; i += 2) + { + var rawX = vertices[i], rawY = vertices[i + 1]; + var x = (a * rawX) + (c * rawY) + tx; + var y = (d * rawY) + (b * rawX) + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; +}; + +Bounds.prototype.addBounds = function(bounds) +{ + var minX = this.minX, minY = this.minY, maxX = this.maxX, maxY = this.maxY; + + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; +}; + +},{"../math":102}],80:[function(require,module,exports){ +var utils = require('../utils'), + DisplayObject = require('./DisplayObject'); + +/** + * A Container represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + *```js + * var container = new PIXI.Container(); + * container.addChild(sprite); + * ``` + * @class + * @extends PIXI.DisplayObject + * @memberof PIXI + */ +function Container() +{ + DisplayObject.call(this); + + /** + * The array of children of this container. + * + * @member {PIXI.DisplayObject[]} + * @readonly + */ + this.children = []; +} + +// constructor +Container.prototype = Object.create(DisplayObject.prototype); +Container.prototype.constructor = Container; +module.exports = Container; + +Object.defineProperties(Container.prototype, { + /** + * The width of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Container# + */ + width: { + get: function () + { + return this.scale.x * this.getLocalBounds().width; + }, + set: function (value) + { + + var width = this.getLocalBounds().width; + + if (width !== 0) + { + this.scale.x = value / width; + } + else + { + this.scale.x = 1; + } + + + this._width = value; + } + }, + + /** + * The height of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Container# + */ + height: { + get: function () + { + return this.scale.y * this.getLocalBounds().height; + }, + set: function (value) + { + + var height = this.getLocalBounds().height; + + if (height !== 0) + { + this.scale.y = value / height ; + } + else + { + this.scale.y = 1; + } + + this._height = value; + } + } +}); + +/** + * Overridable method that can be used by Container subclasses whenever the children array is modified + * + * @private + */ +Container.prototype.onChildrenChange = function () {}; + +/** + * Adds a child or multiple children to the container. + * + * Multple items can be added like so: `myContainer.addChild(thinkOne, thingTwo, thingThree)` + * @param child {...PIXI.DisplayObject} The DisplayObject(s) to add to the container + * @return {PIXI.DisplayObject} The first child that was added. + */ +Container.prototype.addChild = function (child) +{ + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if(argumentsLength > 1) + { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) + { + this.addChild( arguments[i] ); + } + } + else + { + // if the child has a parent then lets remove it as Pixi objects can only exist in one place + if (child.parent) + { + child.parent.removeChild(child); + } + + child.parent = this; + + // ensure a transform will be recalculated.. + this.transform._parentID = -1; + + this.children.push(child); + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length-1); + child.emit('added', this); + } + + return child; +}; + +/** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @param child {PIXI.DisplayObject} The child to add + * @param index {number} The index to place the child in + * @return {PIXI.DisplayObject} The child that was added. + */ +Container.prototype.addChildAt = function (child, index) +{ + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { + child.parent.removeChild(child); + } + + child.parent = this; + + this.children.splice(index, 0, child); + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + + return child; + } + else + { + throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); + } +}; + +/** + * Swaps the position of 2 Display Objects within this container. + * + * @param child {PIXI.DisplayObject} First display object to swap + * @param child2 {PIXI.DisplayObject} Second display object to swap + */ +Container.prototype.swapChildren = function (child, child2) +{ + if (child === child2) + { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + + if (index1 < 0 || index2 < 0) + { + throw new Error('swapChildren: Both the supplied DisplayObjects must be children of the caller.'); + } + + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); +}; + +/** + * Returns the index position of a child DisplayObject instance + * + * @param child {PIXI.DisplayObject} The DisplayObject instance to identify + * @return {number} The index position of the child display object to identify + */ +Container.prototype.getChildIndex = function (child) +{ + var index = this.children.indexOf(child); + + if (index === -1) + { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; +}; + +/** + * Changes the position of an existing child in the display object container + * + * @param child {PIXI.DisplayObject} The child DisplayObject instance for which you want to change the index number + * @param index {number} The resulting index number for the child display object + */ +Container.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + utils.removeItems(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); //add at new position + this.onChildrenChange(index); +}; + +/** + * Returns the child at the specified index + * + * @param index {number} The index to get the child at + * @return {PIXI.DisplayObject} The child at the given index, if any. + */ +Container.prototype.getChildAt = function (index) +{ + if (index < 0 || index >= this.children.length) + { + throw new Error('getChildAt: Supplied index ' + index + ' does not exist in the child list, or the supplied DisplayObject is not a child of the caller'); + } + + return this.children[index]; +}; + +/** + * Removes a child from the container. + * + * @param child {PIXI.DisplayObject} The DisplayObject to remove + * @return {PIXI.DisplayObject} The child that was removed. + */ +Container.prototype.removeChild = function (child) +{ + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if(argumentsLength > 1) + { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) + { + this.removeChild( arguments[i] ); + } + } + else + { + if(!this.children) return; + var index = this.children.indexOf(child); + + if (index === -1) + { + return; + } + + child.parent = null; + utils.removeItems(this.children, index, 1); + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + } + + return child; +}; + +/** + * Removes a child from the specified index position. + * + * @param index {number} The index to get the child from + * @return {PIXI.DisplayObject} The child that was removed. + */ +Container.prototype.removeChildAt = function (index) +{ + var child = this.getChildAt(index); + + child.parent = null; + utils.removeItems(this.children, index, 1); + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + + return child; +}; + +/** + * Removes all children from this container that are within the begin and end indexes. + * + * @param [beginIndex=0] {number} The beginning position. + * @param [endIndex=this.children.length] {number} The ending position. Default value is size of the container. + */ +Container.prototype.removeChildren = function (beginIndex, endIndex) +{ + var begin = beginIndex || 0; + var end = typeof endIndex === 'number' ? endIndex : this.children.length; + var range = end - begin; + var removed, i; + + if (range > 0 && range <= end) + { + removed = this.children.splice(begin, range); + + for (i = 0; i < removed.length; ++i) + { + removed[i].parent = null; + } + + this.onChildrenChange(beginIndex); + + for (i = 0; i < removed.length; ++i) + { + removed[i].emit('removed', this); + } + + return removed; + } + else if (range === 0 && this.children.length === 0) + { + return []; + } + else + { + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + } +}; + +/* + * Updates the transform on all children of this container for rendering + * + * @private + */ +Container.prototype.updateTransform = function () +{ + this._boundsID++; + + if (!this.visible) + { + return; + } + + this.transform.updateTransform(this.parent.transform); + + //TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + for (var i = 0, j = this.children.length; i < j; ++i) + { + this.children[i].updateTransform(); + } +}; + +// performance increase to avoid using call.. (10x faster) +Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + + +Container.prototype.calculateBounds = function () +{ + this._bounds.clear(); + + if(!this.visible) + { + return; + } + + this._calculateBounds(); + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + child.calculateBounds(); + + this._bounds.addBounds(child._bounds); + } + + this._boundsID = this._lastBoundsID; +}; + +Container.prototype._calculateBounds = function () +{ + //FILL IN// +}; + +/** + * Renders the object using the WebGL renderer + * + * @param renderer {PIXI.WebGLRenderer} The renderer + */ +Container.prototype.renderWebGL = function (renderer) +{ + + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) + { + + return; + } + + + // do a quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) + { + this.renderAdvancedWebGL(renderer); + } + else + { + this._renderWebGL(renderer); + + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) + { + this.children[i].renderWebGL(renderer); + } + } +}; + +Container.prototype.renderAdvancedWebGL = function (renderer) +{ + renderer.currentRenderer.flush(); + + var filters = this._filters; + var mask = this._mask; + var i, j; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if ( filters ) + { + if(!this._enabledFilters) + { + this._enabledFilters = []; + } + + this._enabledFilters.length = 0; + + for (i = 0; i < filters.length; i++) + { + if(filters[i].enabled) + { + this._enabledFilters.push( filters[i] ); + } + } + + if( this._enabledFilters.length ) + { + renderer.filterManager.pushFilter(this, this._enabledFilters); + } + } + + if ( mask ) + { + renderer.maskManager.pushMask(this, this._mask); + } + + renderer.currentRenderer.start(); + + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); + + // now loop through the children and make sure they get rendered + for (i = 0, j = this.children.length; i < j; i++) + { + this.children[i].renderWebGL(renderer); + } + + renderer.currentRenderer.flush(); + + if ( mask ) + { + renderer.maskManager.popMask(this, this._mask); + } + + if ( filters && this._enabledFilters && this._enabledFilters.length ) + { + renderer.filterManager.popFilter(); + } + + renderer.currentRenderer.start(); +}; + +/** + * To be overridden by the subclass + * + * @param renderer {PIXI.WebGLRenderer} The renderer + * @private + */ +Container.prototype._renderWebGL = function (renderer) // jshint unused:false +{ + // this is where content itself gets rendered... +}; + +/** + * To be overridden by the subclass + * + * @param renderer {PIXI.CanvasRenderer} The renderer + * @private + */ +Container.prototype._renderCanvas = function (renderer) // jshint unused:false +{ + // this is where content itself gets rendered... +}; + + +/** + * Renders the object using the Canvas renderer + * + * @param renderer {PIXI.CanvasRenderer} The renderer + */ +Container.prototype.renderCanvas = function (renderer) +{ + // if not visible or the alpha is 0 then no need to render this + if (!this.visible || this.alpha <= 0 || !this.renderable) + { + return; + } + + if (this._mask) + { + renderer.maskManager.pushMask(this._mask); + } + + this._renderCanvas(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) + { + this.children[i].renderCanvas(renderer); + } + + if (this._mask) + { + renderer.maskManager.popMask(renderer); + } +}; + +/** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * @param [options] {object|boolean} Options parameter. A boolean will act as if all options have been set to that value + * @param [options.children=false] {boolean} if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + */ +Container.prototype.destroy = function (options) +{ + DisplayObject.prototype.destroy.call(this); + + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + + var oldChildren = this.children; + this.children = null; + + if (destroyChildren) + { + for (var i = oldChildren.length - 1; i >= 0; i--) + { + var child = oldChildren[i]; + child.parent = null; + child.destroy(options); + } + } +}; + +},{"../utils":151,"./DisplayObject":81}],81:[function(require,module,exports){ +var EventEmitter = require('eventemitter3'), + CONST = require('../const'), + TransformStatic = require('./TransformStatic'), + Transform = require('./Transform'), + Bounds = require('./Bounds'), + math = require('../math'), + _tempDisplayObjectParent = new DisplayObject(); + +/** + * The base class for all objects that are rendered on the screen. + * This is an abstract class and should not be used on its own rather it should be extended. + * + * @class + * @extends EventEmitter + * @mixes PIXI.interaction.interactiveTarget + * @memberof PIXI + */ +function DisplayObject() +{ + EventEmitter.call(this); + + var TransformClass = CONST.TRANSFORM_MODE.DEFAULT === CONST.TRANSFORM_MODE.STATIC ? TransformStatic : Transform; + + //TODO: need to create Transform from factory + /** + * World transform and local transform of this object. + * This will be reworked in v4.1, please do not use it yet unless you know what are you doing! + * + * @member {PIXI.TransformBase} + */ + this.transform = new TransformClass(); + + /** + * The opacity of the object. + * + * @member {number} + */ + this.alpha = 1; + + /** + * The visibility of the object. If false the object will not be drawn, and + * the updateTransform function will not be called. + * + * @member {boolean} + */ + this.visible = true; + + /** + * Can this object be rendered, if false the object will not be drawn but the updateTransform + * methods will still be called. + * + * @member {boolean} + */ + this.renderable = true; + + /** + * The display object container that contains this display object. + * + * @member {PIXI.Container} + * @readonly + */ + this.parent = null; + + /** + * The multiplied alpha of the displayObject + * + * @member {number} + * @readonly + */ + this.worldAlpha = 1; + + /** + * The area the filter is applied to. This is used as more of an optimisation + * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle + * + * Also works as an interaction mask + * + * @member {PIXI.Rectangle} + */ + this.filterArea = null; + + this._filters = null; + this._enabledFilters = null; + + /** + * The bounds object, this is used to calculate and store the bounds of the displayObject + * + * @member {PIXI.Rectangle} + * @private + */ + this._bounds = new Bounds(); + this._boundsID = 0; + this._lastBoundsID = -1; + this._boundsRect = null; + this._localBoundsRect = null; + + /** + * The original, cached mask of the object + * + * @member {PIXI.Rectangle} + * @private + */ + this._mask = null; + + +} + +// constructor +DisplayObject.prototype = Object.create(EventEmitter.prototype); +DisplayObject.prototype.constructor = DisplayObject; +module.exports = DisplayObject; + + +Object.defineProperties(DisplayObject.prototype, { + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + * + * @member {number} + * @memberof PIXI.DisplayObject# + */ + x: { + get: function () + { + return this.position.x; + }, + set: function (value) + { + this.transform.position.x = value; + } + }, + + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + * + * @member {number} + * @memberof PIXI.DisplayObject# + */ + y: { + get: function () + { + return this.position.y; + }, + set: function (value) + { + this.transform.position.y = value; + } + }, + + /** + * Current transform of the object based on world (parent) factors + * + * @member {PIXI.Matrix} + * @memberof PIXI.DisplayObject# + * @readonly + */ + worldTransform: { + get: function () + { + return this.transform.worldTransform; + } + }, + + /** + * Current transform of the object based on local factors: position, scale, other stuff + * + * @member {PIXI.Matrix} + * @memberof PIXI.DisplayObject# + * @readonly + */ + localTransform: { + get: function () + { + return this.transform.localTransform; + } + }, + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + position: { + get: function() + { + return this.transform.position; + }, + set: function(value) { + this.transform.position.copy(value); + } + }, + + /** + * The scale factor of the object. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + scale: { + get: function() { + return this.transform.scale; + }, + set: function(value) { + this.transform.scale.copy(value); + } + }, + + /** + * The pivot point of the displayObject that it rotates around + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + pivot: { + get: function() { + return this.transform.pivot; + }, + set: function(value) { + this.transform.pivot.copy(value); + } + }, + + /** + * The skew factor for the object in radians. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + skew: { + get: function() { + return this.transform.skew; + }, + set: function(value) { + this.transform.skew.copy(value); + } + }, + + /** + * The rotation of the object in radians. + * + * @member {number} + * @memberof PIXI.DisplayObject# + */ + rotation: { + get: function () + { + return this.transform.rotation; + }, + set: function (value) + { + this.transform.rotation = value; + } + }, + + /** + * Indicates if the sprite is globally visible. + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + * @readonly + */ + worldVisible: { + get: function () + { + var item = this; + + do { + if (!item.visible) + { + return false; + } + + item = item.parent; + } while (item); + + return true; + } + }, + + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an object to the shape of the mask applied to it. + * In PIXI a regular mask must be a PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it utilises shape clipping. + * To remove a mask, set this property to null. + * + * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + * + * @member {PIXI.Graphics|PIXI.Sprite} + * @memberof PIXI.DisplayObject# + */ + mask: { + get: function () + { + return this._mask; + }, + set: function (value) + { + if (this._mask) + { + this._mask.renderable = true; + } + + this._mask = value; + + if (this._mask) + { + this._mask.renderable = false; + } + } + }, + + /** + * Sets the filters for the displayObject. + * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * To remove filters simply set this property to 'null' + * + * @member {PIXI.AbstractFilter[]} + * @memberof PIXI.DisplayObject# + */ + filters: { + get: function () + { + return this._filters && this._filters.slice(); + }, + set: function (value) + { + this._filters = value && value.slice(); + } + } + +}); + +/* + * Updates the object transform for rendering + * + * TODO - Optimization pass! + */ +DisplayObject.prototype.updateTransform = function () +{ + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + this._bounds.updateID++; +}; + +// performance increase to avoid using call.. (10x faster) +DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + +/** + * recursively updates transform of all objects from the root to this one + * internal function for toLocal() + */ +DisplayObject.prototype._recursivePostUpdateTransform = function() +{ + if (this.parent) + { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } + else + { + this.transform.updateTransform(_tempDisplayObjectParent.transform); + } +}; + +/** + * + * + * Retrieves the bounds of the displayObject as a rectangle object. + * @param skipUpdate {boolean} setting to true will stop the transforms of the scene graph from being updated. This means the calculation returned MAY be out of date BUT will give you a nice performance boost + * @param rect {PIXI.Rectangle} Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ +DisplayObject.prototype.getBounds = function (skipUpdate, rect) +{ + if(!skipUpdate) + { + if(!this.parent) + { + this.parent = _tempDisplayObjectParent; + this.parent.transform._worldID++; + this.updateTransform(); + this.parent = null; + } + else + { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + + if(this._boundsID !== this._lastBoundsID) + { + this.calculateBounds(); + } + + if(!rect) + { + if(!this._boundsRect) + { + this._boundsRect = new math.Rectangle(); + } + + rect = this._boundsRect; + } + + return this._bounds.getRectangle(rect); +}; + +/** + * Retrieves the local bounds of the displayObject as a rectangle object + * @param rect {PIXI.Rectangle} Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ +DisplayObject.prototype.getLocalBounds = function (rect) +{ + var transformRef = this.transform; + var parentRef = this.parent; + + this.parent = null; + this.transform = _tempDisplayObjectParent.transform; + + if(!rect) + { + if(!this._localBoundsRect) + { + this._localBoundsRect = new math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + var bounds = this.getBounds(false, rect); + + this.parent = parentRef; + this.transform = transformRef; + + return bounds; +}; + +/** + * Calculates the global position of the display object + * + * @param position {PIXI.Point} The world origin to calculate from + * @return {PIXI.Point} A point object representing the position of this object + */ +DisplayObject.prototype.toGlobal = function (position, point, skipUpdate) +{ + if(!skipUpdate) + { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if(!this.parent) + { + this.parent = _tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } + else + { + this.displayObjectUpdateTransform(); + } + } + + // don't need to update the lot + return this.worldTransform.apply(position, point); +}; + +/** + * Calculates the local position of the display object relative to another point + * + * @param position {PIXI.Point} The world origin to calculate from + * @param [from] {PIXI.DisplayObject} The DisplayObject to calculate the global position from + * @param [point] {PIXI.Point} A Point object in which to store the value, optional (otherwise will create a new Point) + * @return {PIXI.Point} A point object representing the position of this object + */ +DisplayObject.prototype.toLocal = function (position, from, point, skipUpdate) +{ + if (from) + { + position = from.toGlobal(position, point, skipUpdate); + } + + if(! skipUpdate) + { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if(!this.parent) + { + this.parent = _tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } + else + { + this.displayObjectUpdateTransform(); + } + } + + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); +}; + +/** + * Renders the object using the WebGL renderer + * + * @param renderer {PIXI.WebGLRenderer} The renderer + */ +DisplayObject.prototype.renderWebGL = function (renderer) // jshint unused:false +{ + // OVERWRITE; +}; + +/** + * Renders the object using the Canvas renderer + * + * @param renderer {PIXI.CanvasRenderer} The renderer + */ +DisplayObject.prototype.renderCanvas = function (renderer) // jshint unused:false +{ + // OVERWRITE; +}; + +/** + * Set the parent Container of this DisplayObject + * + * @param container {PIXI.Container} The Container to add this DisplayObject to + * @return {PIXI.Container} The Container that this DisplayObject was added to + */ +DisplayObject.prototype.setParent = function (container) +{ + if (!container || !container.addChild) + { + throw new Error('setParent: Argument must be a Container'); + } + + container.addChild(this); + return container; +}; + +/** + * Convenience function to set the postion, scale, skew and pivot at once. + * + * @param [x=0] {number} The X position + * @param [y=0] {number} The Y position + * @param [scaleX=1] {number} The X scale value + * @param [scaleY=1] {number} The Y scale value + * @param [rotation=0] {number} The rotation + * @param [skewX=0] {number} The X skew value + * @param [skewY=0] {number} The Y skew value + * @param [pivotX=0] {number} The X pivot value + * @param [pivotY=0] {number} The Y pivot value + * @return {PIXI.DisplayObject} The DisplayObject instance + */ +DisplayObject.prototype.setTransform = function(x, y, scaleX, scaleY, rotation, skewX, skewY, pivotX, pivotY) //jshint ignore:line +{ + this.position.x = x || 0; + this.position.y = y || 0; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation || 0; + this.skew.x = skewX || 0; + this.skew.y = skewY || 0; + this.pivot.x = pivotX || 0; + this.pivot.y = pivotY || 0; + return this; +}; + +/** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy`. + */ +DisplayObject.prototype.destroy = function () +{ + this.removeAllListeners(); + if (this.parent) + { + this.parent.removeChild(this); + } + this.transform = null; + + this.parent = null; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this.filterArea = null; + + this.interactive = false; + this.interactiveChildren = false; +}; + +},{"../const":78,"../math":102,"./Bounds":79,"./Transform":82,"./TransformStatic":84,"eventemitter3":32}],82:[function(require,module,exports){ +var math = require('../math'), + TransformBase = require('./TransformBase'); + + +/** + * Generic class to deal with traditional 2D matrix transforms + * local transformation is calculated from position,scale,skew and rotation + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +function Transform() +{ + TransformBase.call(this); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.Point} + */ + this.position = new math.Point(0,0); + + /** + * The scale factor of the object. + * + * @member {PIXI.Point} + */ + this.scale = new math.Point(1,1); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + this.skew = new math.ObservablePoint(this.updateSkew, this, 0,0); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.Point} + */ + this.pivot = new math.Point(0,0); + + /** + * The rotation value of the object, in radians + * + * @member {Number} + * @private + */ + this._rotation = 0; + + this._sr = Math.sin(0); + this._cr = Math.cos(0); + this._cy = Math.cos(0);//skewY); + this._sy = Math.sin(0);//skewY); + this._nsx = Math.sin(0);//skewX); + this._cx = Math.cos(0);//skewX); +} + +Transform.prototype = Object.create(TransformBase.prototype); +Transform.prototype.constructor = Transform; + +Transform.prototype.updateSkew = function () +{ + this._cy = Math.cos(this.skew.y); + this._sy = Math.sin(this.skew.y); + this._nsx = Math.sin(this.skew.x); + this._cx = Math.cos(this.skew.x); +}; + +/** + * Updates only local matrix + */ +Transform.prototype.updateLocalTransform = function() { + var lt = this.localTransform; + var a, b, c, d; + + a = this._cr * this.scale.x; + b = this._sr * this.scale.x; + c = -this._sr * this.scale.y; + d = this._cr * this.scale.y; + + lt.a = this._cy * a + this._sy * c; + lt.b = this._cy * b + this._sy * d; + lt.c = this._nsx * a + this._cx * c; + lt.d = this._nsx * b + this._cx * d; +}; + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + */ +Transform.prototype.updateTransform = function (parentTransform) +{ + + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + var a, b, c, d; + + a = this._cr * this.scale.x; + b = this._sr * this.scale.x; + c = -this._sr * this.scale.y; + d = this._cr * this.scale.y; + + lt.a = this._cy * a + this._sy * c; + lt.b = this._cy * b + this._sy * d; + lt.c = this._nsx * a + this._cx * c; + lt.d = this._nsx * b + this._cx * d; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID ++; +}; + +/** + * Decomposes a matrix and sets the transforms properties based on it. + * @param {PIXI.Matrix} The matrix to decompose + */ +Transform.prototype.setFromMatrix = function (matrix) +{ + matrix.decompose(this); +}; + + +Object.defineProperties(Transform.prototype, { + /** + * The rotation of the object in radians. + * + * @member {number} + * @memberof PIXI.Transform# + */ + rotation: { + get: function () { + return this._rotation; + }, + set: function (value) { + this._rotation = value; + this._sr = Math.sin(value); + this._cr = Math.cos(value); + } + } +}); + +module.exports = Transform; + +},{"../math":102,"./TransformBase":83}],83:[function(require,module,exports){ +var math = require('../math'); + + +/** + * Generic class to deal with traditional 2D matrix transforms + * + * @class + * @memberof PIXI + */ +function TransformBase() +{ + /** + * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds() + * + * @member {PIXI.Matrix} + */ + this.worldTransform = new math.Matrix(); + /** + * The local matrix transform + * + * @member {PIXI.Matrix} + */ + this.localTransform = new math.Matrix(); + + this._worldID = 0; +} + +TransformBase.prototype.constructor = TransformBase; + +/** + * TransformBase does not have decomposition, so this function wont do anything + */ +TransformBase.prototype.updateLocalTransform = function() { // jshint unused:false + +}; + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.TransformBase} The transform of the parent of this object + * + */ +TransformBase.prototype.updateTransform = function (parentTransform) +{ + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID ++; +}; + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ +TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; + +TransformBase.IDENTITY = new TransformBase(); + +module.exports = TransformBase; + +},{"../math":102}],84:[function(require,module,exports){ +var math = require('../math'), + TransformBase = require('./TransformBase'); + +/** + * Transform that takes care about its versions + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +function TransformStatic() +{ + TransformBase.call(this); + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.ObservablePoint} + */ + this.position = new math.ObservablePoint(this.onChange, this,0,0); + + /** + * The scale factor of the object. + * + * @member {PIXI.ObservablePoint} + */ + this.scale = new math.ObservablePoint(this.onChange, this,1,1); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.ObservablePoint} + */ + this.pivot = new math.ObservablePoint(this.onChange, this,0, 0); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + this.skew = new math.ObservablePoint(this.updateSkew, this,0, 0); + + this._rotation = 0; + + this._sr = Math.sin(0); + this._cr = Math.cos(0); + this._cy = Math.cos(0);//skewY); + this._sy = Math.sin(0);//skewY); + this._nsx = Math.sin(0);//skewX); + this._cx = Math.cos(0);//skewX); + + this._localID = 0; + this._currentLocalID = 0; +} + +TransformStatic.prototype = Object.create(TransformBase.prototype); +TransformStatic.prototype.constructor = TransformStatic; + +TransformStatic.prototype.onChange = function () +{ + this._localID ++; +}; + +TransformStatic.prototype.updateSkew = function () +{ + this._cy = Math.cos(this.skew._y); + this._sy = Math.sin(this.skew._y); + this._nsx = Math.sin(this.skew._x); + this._cx = Math.cos(this.skew._x); + + this._localID ++; +}; + +/** + * Updates only local matrix + */ +TransformStatic.prototype.updateLocalTransform = function() { + var lt = this.localTransform; + if(this._localID !== this._currentLocalID) + { + // get the matrix values of the displayobject based on its transform properties.. + var a,b,c,d; + + a = this._cr * this.scale._x; + b = this._sr * this.scale._x; + c = -this._sr * this.scale._y; + d = this._cr * this.scale._y; + + lt.a = this._cy * a + this._sy * c; + lt.b = this._cy * b + this._sy * d; + lt.c = this._nsx * a + this._cx * c; + lt.d = this._nsx * b + this._cx * d; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } +}; + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ +TransformStatic.prototype.updateTransform = function (parentTransform) +{ + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + if(this._localID !== this._currentLocalID) + { + // get the matrix values of the displayobject based on its transform properties.. + var a,b,c,d; + + a = this._cr * this.scale._x; + b = this._sr * this.scale._x; + c = -this._sr * this.scale._y; + d = this._cr * this.scale._y; + + lt.a = this._cy * a + this._sy * c; + lt.b = this._cy * b + this._sy * d; + lt.c = this._nsx * a + this._cx * c; + lt.d = this._nsx * b + this._cx * d; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + + if(this._parentID !== parentTransform._worldID) + { + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._parentID = parentTransform._worldID; + + // update the id of the transform.. + this._worldID ++; + } +}; + +/** + * Decomposes a matrix and sets the transforms properties based on it. + * @param {PIXI.Matrix} The matrix to decompose + */ +TransformStatic.prototype.setFromMatrix = function (matrix) +{ + matrix.decompose(this); + this._localID ++; +}; + +Object.defineProperties(TransformStatic.prototype, { + /** + * The rotation of the object in radians. + * + * @member {number} + * @memberof PIXI.TransformStatic# + */ + rotation: { + get: function () { + return this._rotation; + }, + set: function (value) { + this._rotation = value; + this._sr = Math.sin(value); + this._cr = Math.cos(value); + this._localID ++; + } + } +}); + +module.exports = TransformStatic; + +},{"../math":102,"./TransformBase":83}],85:[function(require,module,exports){ +var Container = require('../display/Container'), + RenderTexture = require('../textures/RenderTexture'), + Texture = require('../textures/Texture'), + GraphicsData = require('./GraphicsData'), + Sprite = require('../sprites/Sprite'), + math = require('../math'), + CONST = require('../const'), + utils = require('../utils'), + Bounds = require('../display/Bounds'), + bezierCurveTo = require('./utils/bezierCurveTo'), + CanvasRenderer = require('../renderers/canvas/CanvasRenderer'), + canvasRenderer, + tempMatrix = new math.Matrix(), + tempPoint = new math.Point(), + tempColor1 = new Float32Array(4), + tempColor2 = new Float32Array(4); + +/** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ +function Graphics() +{ + Container.call(this); + + /** + * The alpha value used when filling the Graphics object. + * + * @member {number} + * @default 1 + */ + this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @member {number} + * @default 0 + */ + this.lineWidth = 0; + + /** + * The color of any lines drawn. + * + * @member {string} + * @default 0 + */ + this.lineColor = 0; + + /** + * Graphics data + * + * @member {PIXI.GraphicsData[]} + * @private + */ + this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to reset the tint. + * + * @member {number} + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The previous tint applied to the graphic shape. Used to compare to the current tint and check if theres change. + * + * @member {number} + * @private + * @default 0xFFFFFF + */ + this._prevTint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + this.blendMode = CONST.BLEND_MODES.NORMAL; + + /** + * Current path + * + * @member {PIXI.GraphicsData} + * @private + */ + this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @member {object} + * @private + */ + // TODO - _webgl should use a prototype object, not a random undocumented object... + this._webGL = {}; + + /** + * Whether this shape is being used as a mask. + * + * @member {boolean} + */ + this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @member {number} + */ + this.boundsPadding = 0; + + /** + * A cache of the local bounds to prevent recalculation. + * + * @member {PIXI.Rectangle} + * @private + */ + this._localBounds = new Bounds(); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics + * object will be recalculated. + * + * @member {boolean} + * @private + */ + this.dirty = 0; + + /** + * Used to detect if we need to do a fast rect check using the id compare method + * @type {Number} + */ + this.fastRectDirty = -1; + + /** + * Used to detect if we clear the graphics webGL data + * @type {Number} + */ + this.clearDirty = 0; + + /** + * Used to detect if we we need to recalculate local bounds + * @type {Number} + */ + this.boundsDirty = -1; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @member {boolean} + * @private + */ + this.cachedSpriteDirty = false; + + + this._spriteRect = null; + this._fastRect = false; + + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ +} + +Graphics._SPRITE_TEXTURE = null; + +// constructor +Graphics.prototype = Object.create(Container.prototype); +Graphics.prototype.constructor = Graphics; +module.exports = Graphics; + +/** + * Creates a new Graphics object with the same values as this one. + * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) + * + * @return {PIXI.Graphics} A clone of the graphics object + */ +Graphics.prototype.clone = function () +{ + var clone = new Graphics(); + + clone.renderable = this.renderable; + clone.fillAlpha = this.fillAlpha; + clone.lineWidth = this.lineWidth; + clone.lineColor = this.lineColor; + clone.tint = this.tint; + clone.blendMode = this.blendMode; + clone.isMask = this.isMask; + clone.boundsPadding = this.boundsPadding; + clone.dirty = 0; + clone.cachedSpriteDirty = this.cachedSpriteDirty; + + // copy graphics data + for (var i = 0; i < this.graphicsData.length; ++i) + { + clone.graphicsData.push(this.graphicsData[i].clone()); + } + + clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; + + clone.updateLocalBounds(); + + return clone; +}; + +/** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. + * + * @param lineWidth {number} width of the line to draw, will update the objects stored style + * @param color {number} color of the line to draw, will update the objects stored style + * @param alpha {number} alpha of the line to draw, will update the objects stored style + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ + this.lineWidth = lineWidth || 0; + this.lineColor = color || 0; + this.lineAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { + // halfway through a line? start a new one! + var shape = new math.Polygon(this.currentPath.shape.points.slice(-2)); + shape.closed = false; + this.drawShape(shape); + } + else + { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; +}; + +/** + * Moves the current drawing position to x, y. + * + * @param x {number} the X coordinate to move to + * @param y {number} the Y coordinate to move to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.moveTo = function (x, y) +{ + var shape = new math.Polygon([x,y]); + shape.closed = false; + this.drawShape(shape); + + return this; +}; + +/** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @param x {number} the X coordinate to draw to + * @param y {number} the Y coordinate to draw to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.lineTo = function (x, y) +{ + this.currentPath.shape.points.push(x, y); + this.dirty++; + + return this; +}; + +/** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @param cpX {number} Control point x + * @param cpY {number} Control point y + * @param toX {number} Destination point x + * @param toY {number} Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [0, 0]; + } + } + else + { + this.moveTo(0,0); + } + + + var xa, + ya, + n = 20, + points = this.currentPath.shape.points; + + if (points.length === 0) + { + this.moveTo(0, 0); + } + + var fromX = points[points.length-2]; + var fromY = points[points.length-1]; + + var j = 0; + for (var i = 1; i <= n; ++i) + { + j = i / n; + + xa = fromX + ( (cpX - fromX) * j ); + ya = fromY + ( (cpY - fromY) * j ); + + points.push( xa + ( ((cpX + ( (toX - cpX) * j )) - xa) * j ), + ya + ( ((cpY + ( (toY - cpY) * j )) - ya) * j ) ); + } + + this.dirty++; + + return this; +}; + +/** + * Calculate the points for a bezier curve and then draws it. + * + * @param cpX {number} Control point x + * @param cpY {number} Control point y + * @param cpX2 {number} Second Control point x + * @param cpY2 {number} Second Control point y + * @param toX {number} Destination point x + * @param toY {number} Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [0, 0]; + } + } + else + { + this.moveTo(0,0); + } + + var points = this.currentPath.shape.points; + + var fromX = points[points.length-2]; + var fromY = points[points.length-1]; + + points.length -= 2; + + bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, points); + + this.dirty++; + + return this; +}; + +/** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @param x1 {number} The x-coordinate of the beginning of the arc + * @param y1 {number} The y-coordinate of the beginning of the arc + * @param x2 {number} The x-coordinate of the end of the arc + * @param y2 {number} The y-coordinate of the end of the arc + * @param radius {number} The radius of the arc + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points.push(x1, y1); + } + } + else + { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points, + fromX = points[points.length-2], + fromY = points[points.length-1], + a1 = fromY - y1, + b1 = fromX - x1, + a2 = y2 - y1, + b2 = x2 - x1, + mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { + points.push(x1, y1); + } + } + else + { + var dd = a1 * a1 + b1 * b1, + cc = a2 * a2 + b2 * b2, + tt = a1 * a2 + b1 * b2, + k1 = radius * Math.sqrt(dd) / mm, + k2 = radius * Math.sqrt(cc) / mm, + j1 = k1 * tt / dd, + j2 = k2 * tt / cc, + cx = k1 * b2 + k2 * b1, + cy = k1 * a2 + k2 * a1, + px = b1 * (k2 + j1), + py = a1 * (k2 + j1), + qx = b2 * (k1 + j2), + qy = a2 * (k1 + j2), + startAngle = Math.atan2(py - cy, px - cx), + endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty++; + + return this; +}; + +/** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @param cx {number} The x-coordinate of the center of the circle + * @param cy {number} The y-coordinate of the center of the circle + * @param radius {number} The radius of the circle + * @param startAngle {number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle) + * @param endAngle {number} The ending angle, in radians + * @param [anticlockwise=false] {boolean} Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.arc = function(cx, cy, radius, startAngle, endAngle, anticlockwise) +{ + anticlockwise = anticlockwise || false; + + if (startAngle === endAngle) + { + return this; + } + + if( !anticlockwise && endAngle <= startAngle ) + { + endAngle += Math.PI * 2; + } + else if( anticlockwise && startAngle <= endAngle ) + { + startAngle += Math.PI * 2; + } + + var sweep = anticlockwise ? (startAngle - endAngle) * -1 : (endAngle - startAngle); + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * 40; + + if(sweep === 0) + { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + if (this.currentPath) + { + this.currentPath.shape.points.push(startX, startY); + } + else + { + this.moveTo(startX, startY); + } + + var points = this.currentPath.shape.points; + + var theta = sweep/(segs*2); + var theta2 = theta*2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = ( segMinus % 1 ) / segMinus; + + for(var i=0; i<=segMinus; i++) + { + var real = i + remainder * i; + + + var angle = ((theta) + startAngle + (theta2 * real)); + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push(( (cTheta * c) + (sTheta * s) ) * radius + cx, + ( (cTheta * -s) + (sTheta * c) ) * radius + cy); + } + + this.dirty++; + + return this; +}; + +/** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @param color {number} the color of the fill + * @param alpha {number} the alpha of the fill + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.beginFill = function (color, alpha) +{ + this.filling = true; + this.fillColor = color || 0; + this.fillAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + return this; +}; + +/** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.endFill = function () +{ + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; +}; + +/** + * + * @param x {number} The X coord of the top-left of the rectangle + * @param y {number} The Y coord of the top-left of the rectangle + * @param width {number} The width of the rectangle + * @param height {number} The height of the rectangle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ + this.drawShape(new math.Rectangle(x,y, width, height)); + + return this; +}; + +/** + * + * @param x {number} The X coord of the top-left of the rectangle + * @param y {number} The Y coord of the top-left of the rectangle + * @param width {number} The width of the rectangle + * @param height {number} The height of the rectangle + * @param radius {number} Radius of the rectangle corners + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ + this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); + + return this; +}; + +/** + * Draws a circle. + * + * @param x {number} The X coordinate of the center of the circle + * @param y {number} The Y coordinate of the center of the circle + * @param radius {number} The radius of the circle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.drawCircle = function (x, y, radius) +{ + this.drawShape(new math.Circle(x,y, radius)); + + return this; +}; + +/** + * Draws an ellipse. + * + * @param x {number} The X coordinate of the center of the ellipse + * @param y {number} The Y coordinate of the center of the ellipse + * @param width {number} The half width of the ellipse + * @param height {number} The half height of the ellipse + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ + this.drawShape(new math.Ellipse(x, y, width, height)); + + return this; +}; + +/** + * Draws a polygon using the given path. + * + * @param path {number[]|PIXI.Point[]} The path data used to construct the polygon. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.drawPolygon = function (path) +{ + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + var closed = true; + + if (points instanceof math.Polygon) + { + closed = points.closed; + points = points.points; + } + + if (!Array.isArray(points)) + { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) + { + points[i] = arguments[i]; + } + } + + var shape = new math.Polygon(points); + shape.closed = closed; + + this.drawShape(shape); + + return this; +}; + +/** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.clear = function () +{ + this.lineWidth = 0; + this.filling = false; + + this.dirty++; + this.clearDirty++; + this.graphicsData = []; + + return this; +}; + +/** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and masked with gl.scissor + * @returns {boolean} + */ +Graphics.prototype.isFastRect = function() { + return this.graphicsData.length === 1 && this.graphicsData[0].shape.type === CONST.SHAPES.RECT && !this.graphicsData[0].lineWidth; +}; + +/** + * Renders the object using the WebGL renderer + * + * @param renderer {PIXI.WebGLRenderer} + * @private + */ +Graphics.prototype._renderWebGL = function (renderer) +{ + // if the sprite is not visible or the alpha is 0 then no need to render this element + if(this.dirty !== this.fastRectDirty) + { + this.fastRectDirty = this.dirty; + this._fastRect = this.isFastRect(); + } + + //TODO this check can be moved to dirty? + if(this._fastRect) + { + this._renderSpriteRect(renderer); + } + else + { + renderer.setObjectRenderer(renderer.plugins.graphics); + renderer.plugins.graphics.render(this); + } + +}; + +Graphics.prototype._renderSpriteRect = function (renderer) +{ + var rect = this.graphicsData[0].shape; + if(!this._spriteRect) + { + if(!Graphics._SPRITE_TEXTURE) + { + var canvas = document.createElement('canvas'); + canvas.width = 10; + canvas.height = 10; + var context = canvas.getContext('2d'); + context.fillStyle = 'white'; + context.fillRect(0, 0, 10, 10); + Graphics._SPRITE_TEXTURE = Texture.fromCanvas(canvas); + } + + this._spriteRect = new Sprite(Graphics._SPRITE_TEXTURE); + } + if (this.tint === 0xffffff) { + this._spriteRect.tint = this.graphicsData[0].fillColor; + } else { + var t1 = tempColor1; + var t2 = tempColor2; + utils.hex2rgb(this.graphicsData[0].fillColor, t1); + utils.hex2rgb(this.tint, t2); + t1[0] *= t2[0]; + t1[1] *= t2[1]; + t1[2] *= t2[2]; + this._spriteRect.tint = utils.rgb2hex(t1); + } + this._spriteRect.alpha = this.graphicsData[0].fillAlpha; + this._spriteRect.worldAlpha = this.worldAlpha * this._spriteRect.alpha; + + Graphics._SPRITE_TEXTURE._frame.width = rect.width; + Graphics._SPRITE_TEXTURE._frame.height = rect.height; + + this._spriteRect.transform.worldTransform = this.transform.worldTransform; + + this._spriteRect.anchor.set(-rect.x / rect.width, -rect.y / rect.height); + this._spriteRect.onAnchorUpdate(); + + this._spriteRect._renderWebGL(renderer); +}; + +/** + * Renders the object using the Canvas renderer + * + * @param renderer {PIXI.CanvasRenderer} + * @private + */ +Graphics.prototype._renderCanvas = function (renderer) +{ + if (this.isMask === true) + { + return; + } + + renderer.plugins.graphics.render(this); +}; + +/** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @param [matrix] {PIXI.Matrix} The world transform matrix to use, defaults to this + * object's worldTransform. + * @return {PIXI.Rectangle} the rectangular bounding area + */ +Graphics.prototype._calculateBounds = function () +{ + if (!this.renderable) + { + return; + } + + if (this.boundsDirty !== this.dirty) + { + this.boundsDirty = this.dirty; + this.updateLocalBounds(); + + this.dirty++; + this.cachedSpriteDirty = true; + } + + var lb = this._localBounds; + this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); +}; + +/** +* Tests if a point is inside this graphics object +* +* @param point {PIXI.Point} the point to test +* @return {boolean} the result of the test +*/ +Graphics.prototype.containsPoint = function( point ) +{ + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; i++) + { + var data = graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // only deal with fills.. + if (data.shape) + { + if ( data.shape.contains( tempPoint.x, tempPoint.y ) ) + { + return true; + } + } + } + + return false; +}; + +/** + * Update the bounds of the object + * + */ +Graphics.prototype.updateLocalBounds = function () +{ + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) + { + var shape, points, x, y, w, h; + + for (var i = 0; i < this.graphicsData.length; i++) + { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + shape = data.shape; + + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { + x = shape.x - lineWidth/2; + y = shape.y - lineWidth/2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === CONST.SHAPES.CIRC) + { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth/2; + h = shape.radius + lineWidth/2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === CONST.SHAPES.ELIP) + { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth/2; + h = shape.height + lineWidth/2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else + { + // POLY + points = shape.points; + + for (var j = 0; j < points.length; j += 2) + { + x = points[j]; + y = points[j+1]; + + minX = x-lineWidth < minX ? x-lineWidth : minX; + maxX = x+lineWidth > maxX ? x+lineWidth : maxX; + + minY = y-lineWidth < minY ? y-lineWidth : minY; + maxY = y+lineWidth > maxY ? y+lineWidth : maxY; + } + } + } + } + else + { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.minX = minX - padding; + this._localBounds.maxX = maxX + padding * 2; + + this._localBounds.minY = minY - padding; + this._localBounds.maxY = maxY + padding * 2; +}; + + +/** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @param shape {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} The shape object to draw. + * @return {PIXI.GraphicsData} The generated GraphicsData object. + */ +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { + // check current path! + if (this.currentPath.shape.points.length <= 2) + { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + var data = new GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape); + + this.graphicsData.push(data); + + if (data.type === CONST.SHAPES.POLY) + { + data.shape.closed = data.shape.closed || this.filling; + this.currentPath = data; + } + + this.dirty++; + + return data; +}; + +Graphics.prototype.generateCanvasTexture = function(scaleMode, resolution) +{ + resolution = resolution || 1; + + var bounds = this.getLocalBounds(); + + var canvasBuffer = new RenderTexture.create(bounds.width * resolution, bounds.height * resolution); + + if(!canvasRenderer) + { + canvasRenderer = new CanvasRenderer(); + } + + tempMatrix.tx = -bounds.x; + tempMatrix.ty = -bounds.y; + + canvasRenderer.render(this, canvasBuffer, false, tempMatrix); + + var texture = Texture.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas, scaleMode); + texture.baseTexture.resolution = resolution; + + return texture; +}; + +Graphics.prototype.closePath = function () +{ + // ok so close path assumes next one is a hole! + var currentPath = this.currentPath; + if (currentPath && currentPath.shape) + { + currentPath.shape.close(); + } + return this; +}; + +Graphics.prototype.addHole = function() +{ + // this is a hole! + var hole = this.graphicsData.pop(); + + this.currentPath = this.graphicsData[this.graphicsData.length-1]; + + this.currentPath.addHole(hole.shape); + this.currentPath = null; + + return this; +}; + +/** + * Destroys the Graphics object. + */ +Graphics.prototype.destroy = function () +{ + Container.prototype.destroy.apply(this, arguments); + + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._webgl) { + for (var j = 0; j < this._webgl[id].data.length; ++j) { + this._webgl[id].data[j].destroy(); + } + } + + if(this._spriteRect) + { + this._spriteRect.destroy(); + } + this.graphicsData = null; + + this.currentPath = null; + this._webgl = null; + this._localBounds = null; +}; + +},{"../const":78,"../display/Bounds":79,"../display/Container":80,"../math":102,"../renderers/canvas/CanvasRenderer":109,"../sprites/Sprite":133,"../textures/RenderTexture":143,"../textures/Texture":144,"../utils":151,"./GraphicsData":86,"./utils/bezierCurveTo":88}],86:[function(require,module,exports){ +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + * @param lineWidth {number} the width of the line to draw + * @param lineColor {number} the color of the line to draw + * @param lineAlpha {number} the alpha of the line to draw + * @param fillColor {number} the color of the fill + * @param fillAlpha {number} the alpha of the fill + * @param fill {boolean} whether or not the shape is filled with a colour + * @param shape {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} The shape object to draw. + */ +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ + /* + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + + /* + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /* + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /* + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /* + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /* + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /* + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /* + * @member {boolean} whether or not the shape is filled with a colour + */ + this.fill = fill; + + this.holes = []; + + /* + * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} The shape object to draw. + */ + this.shape = shape; + + /* + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; +} + +GraphicsData.prototype.constructor = GraphicsData; +module.exports = GraphicsData; + +/** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {PIXI.GraphicsData} Cloned GraphicsData object + */ +GraphicsData.prototype.clone = function () +{ + return new GraphicsData( + this.lineWidth, + this.lineColor, + this.lineAlpha, + this.fillColor, + this.fillAlpha, + this.fill, + this.shape + ); +}; + +/** + * + * + */ +GraphicsData.prototype.addHole = function (shape) +{ + this.holes.push(shape); +}; + +/** + * Destroys the Graphics data. + */ +GraphicsData.prototype.destroy = function () { + this.shape = null; + this.holes = null; +}; + +},{}],87:[function(require,module,exports){ +var CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'), + CONST = require('../../const'); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasGraphicsRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasGraphicsRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching graphics objects. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + * @param renderer {PIXI.SystemRenderer} The current PIXI renderer. + */ +function CanvasGraphicsRenderer(renderer) +{ + this.renderer = renderer; +} + + +CanvasGraphicsRenderer.prototype.constructor = CanvasGraphicsRenderer; +module.exports = CanvasGraphicsRenderer; + +CanvasRenderer.registerPlugin('graphics', CanvasGraphicsRenderer); + +/* + * Renders a Graphics object to a canvas. + * + * @param graphics {PIXI.Graphics} the actual graphics object to render + * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas + */ +CanvasGraphicsRenderer.prototype.render = function (graphics) +{ + var renderer = this.renderer; + var context = renderer.context; + var worldAlpha = graphics.worldAlpha; + var transform = graphics.transform.worldTransform; + var resolution = renderer.resolution; + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) { + this.dirty = true; + } + + context.setTransform( + transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + transform.tx * resolution, + transform.ty * resolution + ); + + + if (graphics.dirty) + { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + renderer.setBlendMode(graphics.blendMode); + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === CONST.SHAPES.POLY) + { + context.beginPath(); + + this.renderPolygon(shape.points, shape.closed, context); + + for (var j = 0; j < data.holes.length; j++) + { + var hole = data.holes[j]; + this.renderPolygon(hole.points, true, context); + } + + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === CONST.SHAPES.RECT) + { + + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + + } + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } + else if (data.type === CONST.SHAPES.CIRC) + { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === CONST.SHAPES.ELIP) + { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + context.beginPath(); + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === CONST.SHAPES.RREC) + { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + + } + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } +}; + +/* + * Updates the tint of a graphics object + * + * @private + * @param graphics {PIXI.Graphics} the graphics that will have its tint updated + * + */ +CanvasGraphicsRenderer.prototype.updateGraphicsTint = function (graphics) +{ + graphics._prevTint = graphics.tint; + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF)/ 255; + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + // super inline cos im an optimization NAZI :) + data._fillTint = (((fillColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (fillColor & 0xFF) / 255 * tintB*255); + data._lineTint = (((lineColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (lineColor & 0xFF) / 255 * tintB*255); + } +}; + +CanvasGraphicsRenderer.prototype.renderPolygon = function (points, close, context) +{ + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (close) + { + context.closePath(); + } +}; + +/* + * destroy graphics object + * + */ +CanvasGraphicsRenderer.prototype.destroy = function () +{ + this.renderer = null; +}; + +},{"../../const":78,"../../renderers/canvas/CanvasRenderer":109}],88:[function(require,module,exports){ + +/** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @param fromX {number} Starting point x + * @param fromY {number} Starting point y + * @param cpX {number} Control point x + * @param cpY {number} Control point y + * @param cpX2 {number} Second Control point x + * @param cpY2 {number} Second Control point y + * @param toX {number} Destination point x + * @param toY {number} Destination point y + * @param [path=number[]] Path array to push points into + * @return {PIXI.Graphics} + */ +var bezierCurveTo = function (fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, path) // jshint ignore:line +{ + path = path || []; + + var n = 20, + dt, + dt2, + dt3, + t2, + t3; + + path.push(fromX, fromY); + + var j = 0; + + for (var i = 1; i <= n; ++i) + { + j = i / n; + + dt = (1 - j); + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + path.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, + dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + return path; +}; + +module.exports = bezierCurveTo; + +},{}],89:[function(require,module,exports){ +var utils = require('../../utils'), + CONST = require('../../const'), + ObjectRenderer = require('../../renderers/webgl/utils/ObjectRenderer'), + WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'), + WebGLGraphicsData = require('./WebGLGraphicsData'), + PrimitiveShader = require('./shaders/PrimitiveShader'), + + // some drawing functions.. + buildPoly = require('./utils/buildPoly'), + buildRectangle = require('./utils/buildRectangle'), + buildRoundedRectangle = require('./utils/buildRoundedRectangle'), + buildCircle = require('./utils/buildCircle'); + + + +/** + * Renders the graphics object. + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + * @param renderer {PIXI.WebGLRenderer} The renderer this object renderer works for. + */ +function GraphicsRenderer(renderer) +{ + ObjectRenderer.call(this, renderer); + + this.graphicsDataPool = []; + + this.primitiveShader = null; + + this.gl = renderer.gl; + + // easy access! + this.CONTEXT_UID = 0; +} + +GraphicsRenderer.prototype = Object.create(ObjectRenderer.prototype); +GraphicsRenderer.prototype.constructor = GraphicsRenderer; +module.exports = GraphicsRenderer; + +WebGLRenderer.registerPlugin('graphics', GraphicsRenderer); + +/** + * Called when there is a WebGL context change + * + * @private + * + */ +GraphicsRenderer.prototype.onContextChange = function() +{ + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.primitiveShader = new PrimitiveShader(this.gl); +}; + +/** + * Destroys this renderer. + * + */ +GraphicsRenderer.prototype.destroy = function () +{ + ObjectRenderer.prototype.destroy.call(this); + + for (var i = 0; i < this.graphicsDataPool.length; ++i) { + this.graphicsDataPool[i].destroy(); + } + + this.graphicsDataPool = null; +}; + +/** + * Renders a graphics object. + * + * @param graphics {PIXI.Graphics} The graphics object to render. + */ +GraphicsRenderer.prototype.render = function(graphics) +{ + var renderer = this.renderer; + var gl = renderer.gl; + + var webGLData; + + var webGL = graphics._webGL[this.CONTEXT_UID]; + + if (!webGL || graphics.dirty !== webGL.dirty ) + { + + this.updateGraphics(graphics); + + webGL = graphics._webGL[this.CONTEXT_UID]; + } + + + + // This could be speeded up for sure! + var shader = this.primitiveShader; + renderer.bindShader(shader); + renderer.state.setBlendMode( graphics.blendMode ); + + for (var i = 0, n = webGL.data.length; i < n; i++) + { + webGLData = webGL.data[i]; + var shaderTemp = webGLData.shader; + + renderer.bindShader(shaderTemp); + shaderTemp.uniforms.translationMatrix = graphics.transform.worldTransform.toArray(true); + shaderTemp.uniforms.tint = utils.hex2rgb(graphics.tint); + shaderTemp.uniforms.alpha = graphics.worldAlpha; + + webGLData.vao.bind() + .draw(gl.TRIANGLE_STRIP, webGLData.indices.length) + .unbind(); + } +}; + +/** + * Updates the graphics object + * + * @private + * @param graphics {PIXI.Graphics} The graphics object to update + */ +GraphicsRenderer.prototype.updateGraphics = function(graphics) +{ + var gl = this.renderer.gl; + + // get the contexts graphics object + var webGL = graphics._webGL[this.CONTEXT_UID]; + + // if the graphics object does not exist in the webGL context time to create it! + if (!webGL) + { + webGL = graphics._webGL[this.CONTEXT_UID] = {lastIndex:0, data:[], gl:gl, clearDirty:-1, dirty:-1}; + + } + + // flag the graphics as not dirty as we are about to update it... + webGL.dirty = graphics.dirty; + + var i; + + // if the user cleared the graphics object we will need to clear every object + if (graphics.clearDirty !== webGL.clearDirty) + { + webGL.clearDirty = graphics.clearDirty; + + // loop through and return all the webGLDatas to the object pool so than can be reused later on + for (i = 0; i < webGL.data.length; i++) + { + var graphicsData = webGL.data[i]; + this.graphicsDataPool.push( graphicsData ); + } + + // clear the array and reset the index.. + webGL.data = []; + webGL.lastIndex = 0; + } + + var webGLData; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + //TODO - this can be simplified + webGLData = this.getWebGLData(webGL, 0); + + if (data.type === CONST.SHAPES.POLY) + { + buildPoly(data, webGLData); + } + if (data.type === CONST.SHAPES.RECT) + { + buildRectangle(data, webGLData); + } + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { + buildCircle(data, webGLData); + } + else if (data.type === CONST.SHAPES.RREC) + { + buildRoundedRectangle(data, webGLData); + } + + webGL.lastIndex++; + } + + // upload all the dirty data... + for (i = 0; i < webGL.data.length; i++) + { + webGLData = webGL.data[i]; + + if (webGLData.dirty) + { + webGLData.upload(); + } + } +}; + +/** + * + * @private + * @param webGL {WebGLRenderingContext} the current WebGL drawing context + * @param type {number} TODO @Alvin + */ +GraphicsRenderer.prototype.getWebGLData = function (webGL, type) +{ + var webGLData = webGL.data[webGL.data.length-1]; + + if (!webGLData || webGLData.points.length > 320000) + { + webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData.reset(type); + webGL.data.push(webGLData); + } + + webGLData.dirty = true; + + return webGLData; +}; + +},{"../../const":78,"../../renderers/webgl/WebGLRenderer":116,"../../renderers/webgl/utils/ObjectRenderer":126,"../../utils":151,"./WebGLGraphicsData":90,"./shaders/PrimitiveShader":91,"./utils/buildCircle":92,"./utils/buildPoly":94,"./utils/buildRectangle":95,"./utils/buildRoundedRectangle":96}],90:[function(require,module,exports){ +var glCore = require('pixi-gl-core'); + + +/** + * An object containing WebGL specific properties to be used by the WebGL renderer + * + * @class + * @private + * @memberof PIXI + * @param gl {WebGLRenderingContext} The current WebGL drawing context + * @param shader {PIXI.Shader} The shader + * @param attribsState {object} The state for the VAO + */ +function WebGLGraphicsData(gl, shader, attribsState) +{ + + /** + * The current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + //TODO does this need to be split before uploding?? + /** + * An array of color components (r,g,b) + * @member {number[]} + */ + this.color = [0,0,0]; // color split! + + /** + * An array of points to draw + * @member {PIXI.Point[]} + */ + this.points = []; + + /** + * The indices of the vertices + * @member {number[]} + */ + this.indices = []; + /** + * The main buffer + * @member {WebGLBuffer} + */ + this.buffer = glCore.GLBuffer.createVertexBuffer(gl); + + /** + * The index buffer + * @member {WebGLBuffer} + */ + this.indexBuffer = glCore.GLBuffer.createIndexBuffer(gl); + + /** + * Whether this graphics is dirty or not + * @member {boolean} + */ + this.dirty = true; + + this.glPoints = null; + this.glIndices = null; + + /** + * + * @member {PIXI.Shader} + */ + this.shader = shader; + + this.vao = new glCore.VertexArrayObject(gl, attribsState) + .addIndex(this.indexBuffer) + .addAttribute(this.buffer, shader.attributes.aVertexPosition, gl.FLOAT, false, 4 * 6, 0) + .addAttribute(this.buffer, shader.attributes.aColor, gl.FLOAT, false, 4 * 6, 2 * 4); + + +} + +WebGLGraphicsData.prototype.constructor = WebGLGraphicsData; +module.exports = WebGLGraphicsData; + +/** + * Resets the vertices and the indices + */ +WebGLGraphicsData.prototype.reset = function () +{ + this.points.length = 0; + this.indices.length = 0; +}; + +/** + * Binds the buffers and uploads the data + */ +WebGLGraphicsData.prototype.upload = function () +{ + this.glPoints = new Float32Array(this.points); + this.buffer.upload( this.glPoints ); + + this.glIndices = new Uint16Array(this.indices); + this.indexBuffer.upload( this.glIndices ); + + this.dirty = false; +}; + + + +/** + * Empties all the data + */ +WebGLGraphicsData.prototype.destroy = function () +{ + this.color = null; + this.points = null; + this.indices = null; + + this.vao.destroy(); + this.buffer.destroy(); + this.indexBuffer.destroy(); + + this.gl = null; + + this.buffer = null; + this.indexBuffer = null; + + this.glPoints = null; + this.glIndices = null; +}; + +},{"pixi-gl-core":7}],91:[function(require,module,exports){ +var Shader = require('../../../Shader'); + +/** + * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. + * + * @class + * @memberof PIXI + * @extends PIXI.Shader + * @param gl {WebGLRenderingContext} The webgl shader manager this shader works for. + */ +function PrimitiveShader(gl) +{ + Shader.call(this, + gl, + // vertex shader + [ + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', + + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', + + 'uniform float alpha;', + 'uniform vec3 tint;', + + 'varying vec4 vColor;', + + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ].join('\n'), + // fragment shader + [ + 'varying vec4 vColor;', + + 'void main(void){', + ' gl_FragColor = vColor;', + '}' + ].join('\n') + ); +} + +PrimitiveShader.prototype = Object.create(Shader.prototype); +PrimitiveShader.prototype.constructor = PrimitiveShader; + +module.exports = PrimitiveShader; + +},{"../../../Shader":77}],92:[function(require,module,exports){ +var buildLine = require('./buildLine'), + CONST = require('../../../const'), + utils = require('../../../utils'); + +/** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param graphicsData {PIXI.WebGLGraphicsData} The graphics object to draw + * @param webGLData {object} an object containing all the webGL-specific information to create this shape + */ +var buildCircle = function (graphicsData, webGLData) +{ + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width; + var height; + + // TODO - bit hacky?? + if (graphicsData.type === CONST.SHAPES.CIRC) + { + width = circleData.radius; + height = circleData.radius; + } + else + { + width = circleData.width; + height = circleData.height; + } + + var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); + var seg = (Math.PI * 2) / totalSegs ; + + var i = 0; + + if (graphicsData.fill) + { + var color = utils.hex2rgb(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length/6; + + indices.push(vecPos); + + for (i = 0; i < totalSegs + 1 ; i++) + { + verts.push(x,y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height, + r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos-1); + } + + if (graphicsData.lineWidth) + { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (i = 0; i < totalSegs + 1; i++) + { + graphicsData.points.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height); + } + + buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + + +module.exports = buildCircle; + +},{"../../../const":78,"../../../utils":151,"./buildLine":93}],93:[function(require,module,exports){ +var math = require('../../../math'), + utils = require('../../../utils'); + +/** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param graphicsData {PIXI.WebGLGraphicsData} The graphics object containing all the necessary properties + * @param webGLData {object} an object containing all the webGL-specific information to create this shape + */ +var buildLine = function (graphicsData, webGLData) +{ + // TODO OPTIMISE! + var i = 0; + var points = graphicsData.points; + + if (points.length === 0) + { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + + // get first and last point.. figure out the middle! + var firstPoint = new math.Point(points[0], points[1]); + var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); + + // if the first point is the last point - gonna have issues :) + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length/6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = utils.hex2rgb(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var px, py, p1x, p1y, p2x, p2y, p3x, p3y; + var perpx, perpy, perp2x, perp2y, perp3x, perp3y; + var a1, b1, c1, a2, b2, c2; + var denom, pdist, dist; + + p1x = points[0]; + p1y = points[1]; + + p2x = points[2]; + p2y = points[3]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx , p1y - perpy, + r, g, b, alpha); + + verts.push(p1x + perpx , p1y + perpy, + r, g, b, alpha); + + for (i = 1; i < length-1; i++) + { + p1x = points[(i-1)*2]; + p1y = points[(i-1)*2 + 1]; + + p2x = points[(i)*2]; + p2y = points[(i)*2 + 1]; + + p3x = points[(i+1)*2]; + p3y = points[(i+1)*2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + a1 = (-perpy + p1y) - (-perpy + p2y); + b1 = (-perpx + p2x) - (-perpx + p1x); + c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + a2 = (-perp2y + p3y) - (-perp2y + p2y); + b2 = (-perp2x + p2x) - (-perp2x + p3x); + c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + denom = a1*b2 - a2*b1; + + if (Math.abs(denom) < 0.1 ) + { + + denom+=10.1; + verts.push(p2x - perpx , p2y - perpy, + r, g, b, alpha); + + verts.push(p2x + perpx , p2y + perpy, + r, g, b, alpha); + + continue; + } + + px = (b1*c2 - b2*c1)/denom; + py = (a2*c1 - a1*c2)/denom; + + + pdist = (px -p2x) * (px -p2x) + (py -p2y) * (py -p2y); + + + if (pdist > 140 * 140) + { + perp3x = perpx - perp2x; + perp3y = perpy - perp2y; + + dist = Math.sqrt(perp3x*perp3x + perp3y*perp3y); + perp3x /= dist; + perp3y /= dist; + perp3x *= width; + perp3y *= width; + + verts.push(p2x - perp3x, p2y -perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x + perp3x, p2y +perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x - perp3x, p2y -perp3y); + verts.push(r, g, b, alpha); + + indexCount++; + } + else + { + + verts.push(px , py); + verts.push(r, g, b, alpha); + + verts.push(p2x - (px-p2x), p2y - (py - p2y)); + verts.push(r, g, b, alpha); + } + } + + p1x = points[(length-2)*2]; + p1y = points[(length-2)*2 + 1]; + + p2x = points[(length-1)*2]; + p2y = points[(length-1)*2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + verts.push(p2x - perpx , p2y - perpy); + verts.push(r, g, b, alpha); + + verts.push(p2x + perpx , p2y + perpy); + verts.push(r, g, b, alpha); + + indices.push(indexStart); + + for (i = 0; i < indexCount; i++) + { + indices.push(indexStart++); + } + + indices.push(indexStart-1); +}; + +module.exports = buildLine; + +},{"../../../math":102,"../../../utils":151}],94:[function(require,module,exports){ +var buildLine = require('./buildLine'), + utils = require('../../../utils'), + earcut = require('earcut'); + +/** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param graphicsData {PIXI.WebGLGraphicsData} The graphics object containing all the necessary properties + * @param webGLData {object} an object containing all the webGL-specific information to create this shape + */ +var buildPoly = function (graphicsData, webGLData) +{ + graphicsData.points = graphicsData.shape.points.slice(); + + var points = graphicsData.points; + + if(graphicsData.fill && points.length >= 6) + { + var holeArray = []; + // Process holes.. + var holes = graphicsData.holes; + + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + + holeArray.push(points.length/2); + + points = points.concat(hole.points); + } + + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = utils.hex2rgb(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = earcut(points, holeArray, 2); + + if (!triangles) { + return; + } + + var vertPos = verts.length / 6; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vertPos); + indices.push(triangles[i] + vertPos); + indices.push(triangles[i+1] + vertPos); + indices.push(triangles[i+2] +vertPos); + indices.push(triangles[i+2] + vertPos); + } + + for (i = 0; i < length; i++) + { + verts.push(points[i * 2], points[i * 2 + 1], + r, g, b, alpha); + } + } + + if (graphicsData.lineWidth > 0) + { + buildLine(graphicsData, webGLData); + } +}; + + +module.exports = buildPoly; + +},{"../../../utils":151,"./buildLine":93,"earcut":31}],95:[function(require,module,exports){ +var buildLine = require('./buildLine'), + utils = require('../../../utils'); + +/** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param graphicsData {PIXI.WebGLGraphicsData} The graphics object containing all the necessary properties + * @param webGLData {object} an object containing all the webGL-specific information to create this shape + */ +var buildRectangle = function (graphicsData, webGLData) +{ + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if (graphicsData.fill) + { + var color = utils.hex2rgb(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vertPos = verts.length/6; + + // start + verts.push(x, y); + verts.push(r, g, b, alpha); + + verts.push(x + width, y); + verts.push(r, g, b, alpha); + + verts.push(x , y + height); + verts.push(r, g, b, alpha); + + verts.push(x + width, y + height); + verts.push(r, g, b, alpha); + + // insert 2 dead triangles.. + indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); + } + + if (graphicsData.lineWidth) + { + var tempPoints = graphicsData.points; + + graphicsData.points = [x, y, + x + width, y, + x + width, y + height, + x, y + height, + x, y]; + + + buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +module.exports = buildRectangle; + +},{"../../../utils":151,"./buildLine":93}],96:[function(require,module,exports){ +var earcut = require('earcut'), + buildLine = require('./buildLine'), + utils = require('../../../utils'); + +/** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param graphicsData {PIXI.WebGLGraphicsData} The graphics object containing all the necessary properties + * @param webGLData {object} an object containing all the webGL-specific information to create this shape + */ +var buildRoundedRectangle = function (graphicsData, webGLData) +{ + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + recPoints.push(x, y + radius); + quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height, recPoints); + quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius, recPoints); + quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y, recPoints); + quadraticBezierCurve(x + radius, y, x, y, x, y + radius + 0.0000000001, recPoints); + + // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. + // TODO - fix this properly, this is not very elegant.. but it works for now. + + if (graphicsData.fill) + { + var color = utils.hex2rgb(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length/6; + + var triangles = earcut(recPoints, null, 2); + + var i = 0; + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i+1] + vecPos); + indices.push(triangles[i+2] + vecPos); + indices.push(triangles[i+2] + vecPos); + } + + for (i = 0; i < recPoints.length; i++) + { + verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) + { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param fromX {number} Origin point x + * @param fromY {number} Origin point x + * @param cpX {number} Control point x + * @param cpY {number} Control point y + * @param toX {number} Destination point x + * @param toY {number} Destination point y + * @param [out] {number[]} The output array to add points into. If not passed, a new array is created. + * @return {number[]} an array of points + */ +var quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY, out)// jshint ignore:line +{ + var xa, + ya, + xb, + yb, + x, + y, + n = 20, + points = out || []; + + function getPt(n1 , n2, perc) { + var diff = n2 - n1; + + return n1 + ( diff * perc ); + } + + var j = 0; + for (var i = 0; i <= n; i++ ) { + j = i / n; + + // The Green Line + xa = getPt( fromX , cpX , j ); + ya = getPt( fromY , cpY , j ); + xb = getPt( cpX , toX , j ); + yb = getPt( cpY , toY , j ); + + // The Black Dot + x = getPt( xa , xb , j ); + y = getPt( ya , yb , j ); + + points.push(x, y); + } + + return points; +}; + + +module.exports = buildRoundedRectangle; + +},{"../../../utils":151,"./buildLine":93,"earcut":31}],97:[function(require,module,exports){ +/** + * @file Main export of the PIXI core library + * @author Mat Groves + * @copyright 2013-2015 GoodBoyDigital + * @license {@link https://github.com/pixijs/pixi.js/blob/master/LICENSE|MIT License} + */ + +/** + * @namespace PIXI + */ +// export core and const. We assign core to const so that the non-reference types in const remain in-tact +var core = module.exports = Object.assign(require('./const'), require('./math'), { + // utils + utils: require('./utils'), + ticker: require('./ticker'), + + // display + DisplayObject: require('./display/DisplayObject'), + Container: require('./display/Container'), + Transform: require('./display/Transform'), + TransformStatic: require('./display/TransformStatic'), + TransformBase: require('./display/TransformBase'), + + // sprites + Sprite: require('./sprites/Sprite'), + CanvasSpriteRenderer: require('./sprites/canvas/CanvasSpriteRenderer'), + CanvasTinter: require('./sprites/canvas/CanvasTinter'), + SpriteRenderer: require('./sprites/webgl/SpriteRenderer'), + + // text + Text: require('./text/Text'), + TextStyle: require('./text/TextStyle'), + // primitives + Graphics: require('./graphics/Graphics'), + GraphicsData: require('./graphics/GraphicsData'), + GraphicsRenderer: require('./graphics/webgl/GraphicsRenderer'), + CanvasGraphicsRenderer: require('./graphics/canvas/CanvasGraphicsRenderer'), + + // textures + Texture: require('./textures/Texture'), + BaseTexture: require('./textures/BaseTexture'), + RenderTexture: require('./textures/RenderTexture'), + BaseRenderTexture: require('./textures/BaseRenderTexture'), + VideoBaseTexture: require('./textures/VideoBaseTexture'), + TextureUvs: require('./textures/TextureUvs'), + + // renderers - canvas + CanvasRenderer: require('./renderers/canvas/CanvasRenderer'), + CanvasRenderTarget: require('./renderers/canvas/utils/CanvasRenderTarget'), + + // renderers - webgl + Shader: require('./Shader'), + WebGLRenderer: require('./renderers/webgl/WebGLRenderer'), + WebGLManager: require('./renderers/webgl/managers/WebGLManager'), + ObjectRenderer: require('./renderers/webgl/utils/ObjectRenderer'), + RenderTarget: require('./renderers/webgl/utils/RenderTarget'), + Quad: require('./renderers/webgl/utils/Quad'), + + // filters - webgl + SpriteMaskFilter: require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter'), + Filter: require('./renderers/webgl/filters/Filter'), + + glCore: require('pixi-gl-core'), + + /** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by + * the browser then this function will return a canvas renderer + * + * @memberof PIXI + * @param width=800 {number} the width of the renderers view + * @param height=600 {number} the height of the renderers view + * @param [options] {object} The optional renderer parameters + * @param [options.view] {HTMLCanvasElement} the canvas to use as a view, optional + * @param [options.transparent=false] {boolean} If the render view is transparent, default false + * @param [options.antialias=false] {boolean} sets antialias (only applicable in chrome at the moment) + * @param [options.preserveDrawingBuffer=false] {boolean} enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param [options.resolution=1] {number} The resolution / device pixel ratio of the renderer, retina would be 2 + * @param [noWebGL=false] {boolean} prevents selection of WebGL renderer, even if such is present + * + * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ + autoDetectRenderer: function (width, height, options, noWebGL) + { + width = width || 800; + height = height || 600; + + if (!noWebGL && core.utils.isWebGLSupported()) + { + return new core.WebGLRenderer(width, height, options); + } + + return new core.CanvasRenderer(width, height, options); + } +}); + +},{"./Shader":77,"./const":78,"./display/Container":80,"./display/DisplayObject":81,"./display/Transform":82,"./display/TransformBase":83,"./display/TransformStatic":84,"./graphics/Graphics":85,"./graphics/GraphicsData":86,"./graphics/canvas/CanvasGraphicsRenderer":87,"./graphics/webgl/GraphicsRenderer":89,"./math":102,"./renderers/canvas/CanvasRenderer":109,"./renderers/canvas/utils/CanvasRenderTarget":111,"./renderers/webgl/WebGLRenderer":116,"./renderers/webgl/filters/Filter":118,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":121,"./renderers/webgl/managers/WebGLManager":125,"./renderers/webgl/utils/ObjectRenderer":126,"./renderers/webgl/utils/Quad":127,"./renderers/webgl/utils/RenderTarget":128,"./sprites/Sprite":133,"./sprites/canvas/CanvasSpriteRenderer":134,"./sprites/canvas/CanvasTinter":135,"./sprites/webgl/SpriteRenderer":137,"./text/Text":139,"./text/TextStyle":140,"./textures/BaseRenderTexture":141,"./textures/BaseTexture":142,"./textures/RenderTexture":143,"./textures/Texture":144,"./textures/TextureUvs":145,"./textures/VideoBaseTexture":146,"./ticker":148,"./utils":151,"pixi-gl-core":7}],98:[function(require,module,exports){ +// Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16 + +var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; +var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; +var tempMatrices = []; +var Matrix = require('./Matrix'); + +var mul = []; + +function signum(x) { + if (x < 0) { + return -1; + } + if (x > 0) { + return 1; + } + return 0; +} + +function init() { + for (var i = 0; i < 16; i++) { + var row = []; + mul.push(row); + for (var j = 0; j < 16; j++) { + var _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); + var _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); + var _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); + var _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + + for (i=0;i<16;i++) { + var mat = new Matrix(); + mat.set(ux[i], uy[i], vx[i], vy[i], 0, 0); + tempMatrices.push(mat); + } +} + +init(); + +/** + * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, D8 is the same but with diagonals + * Used for texture rotations + * Vector xX(i), xY(i) is U-axis of sprite with rotation i + * Vector yY(i), yY(i) is V-axis of sprite with rotation i + * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) + * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) + * This is the small part of gameofbombs.com portal system. It works. + * @author Ivan @ivanpopelyshev + * + * @namespace PIXI.GroupD8 + */ +var GroupD8 = { + E: 0, + SE: 1, + S: 2, + SW: 3, + W: 4, + NW: 5, + N: 6, + NE: 7, + MIRROR_VERTICAL: 8, + MIRROR_HORIZONTAL: 12, + uX: function (ind) { + return ux[ind]; + }, + uY: function (ind) { + return uy[ind]; + }, + vX: function (ind) { + return vx[ind]; + }, + vY: function (ind) { + return vy[ind]; + }, + inv: function (rotation) { + if (rotation & 8) { + return rotation & 15; + } + return (-rotation) & 7; + }, + add: function (rotationSecond, rotationFirst) { + return mul[rotationSecond][rotationFirst]; + }, + sub: function (rotationSecond, rotationFirst) { + return mul[rotationSecond][GroupD8.inv(rotationFirst)]; + }, + /** + * Adds 180 degrees to rotation. Commutative operation + * @param rotation + * @returns {number} + */ + rotate180: function (rotation) { + return rotation ^ 4; + }, + /** + * I dont know why sometimes width and heights needs to be swapped. We'll fix it later. + * @param rotation + * @returns {boolean} + */ + isSwapWidthHeight: function(rotation) { + return (rotation & 3) === 2; + }, + byDirection: function (dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return GroupD8.S; + } + else { + return GroupD8.N; + } + } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return GroupD8.E; + } + else { + return GroupD8.W; + } + } else { + if (dy > 0) { + if (dx > 0) { + return GroupD8.SE; + } + else { + return GroupD8.SW; + } + } + else if (dx > 0) { + return GroupD8.NE; + } + else { + return GroupD8.NW; + } + } + }, + /** + * Helps sprite to compensate texture packer rotation. + * @param matrix {PIXI.Matrix} sprite world matrix + * @param rotation {number} + * @param tx {number|*} sprite anchoring + * @param ty {number|*} sprite anchoring + */ + matrixAppendRotationInv: function (matrix, rotation, tx, ty) { + //Packer used "rotation", we use "inv(rotation)" + var mat = tempMatrices[GroupD8.inv(rotation)]; + tx = tx || 0; + ty = ty || 0; + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + } +}; + +module.exports = GroupD8; + +},{"./Matrix":99}],99:[function(require,module,exports){ +// @todo - ignore the too many parameters warning for now +// should either fix it or change the jshint config +// jshint -W072 + +var Point = require('./Point'); + +/** + * The pixi Matrix class as an object, which makes it a lot faster, + * here is a representation of it : + * | a | b | tx| + * | c | d | ty| + * | 0 | 0 | 1 | + * + * @class + * @memberof PIXI + */ +function Matrix() +{ + /** + * @member {number} + * @default 1 + */ + this.a = 1; + + /** + * @member {number} + * @default 0 + */ + this.b = 0; + + /** + * @member {number} + * @default 0 + */ + this.c = 0; + + /** + * @member {number} + * @default 1 + */ + this.d = 1; + + /** + * @member {number} + * @default 0 + */ + this.tx = 0; + + /** + * @member {number} + * @default 0 + */ + this.ty = 0; + + this.array = null; +} + +Matrix.prototype.constructor = Matrix; +module.exports = Matrix; + +/** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @param array {number[]} The array that the matrix will be populated from. + */ +Matrix.prototype.fromArray = function (array) +{ + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; +}; + + +/** + * sets the matrix properties + * + * @param {number} a + * @param {number} b + * @param {number} c + * @param {number} d + * @param {number} tx + * @param {number} ty + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.set = function (a, b, c, d, tx, ty) +{ + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; +}; + + +/** + * Creates an array from the current Matrix object. + * + * @param transpose {boolean} Whether we need to transpose the matrix or not + * @param [out=new Float32Array(9)] {Float32Array} If provided the array will be assigned to out + * @return {number[]} the newly created array which contains the matrix + */ +Matrix.prototype.toArray = function (transpose, out) +{ + if (!this.array) + { + this.array = new Float32Array(9); + } + + var array = out || this.array; + + if (transpose) + { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } + else + { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; +}; + +/** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * + * @param pos {PIXI.Point} The origin + * @param [newPos] {PIXI.Point} The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, transformed through this matrix + */ +Matrix.prototype.apply = function (pos, newPos) +{ + newPos = newPos || new Point(); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; + + return newPos; +}; + +/** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * + * @param pos {PIXI.Point} The origin + * @param [newPos] {PIXI.Point} The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, inverse-transformed through this matrix + */ +Matrix.prototype.applyInverse = function (pos, newPos) +{ + newPos = newPos || new Point(); + + var id = 1 / (this.a * this.d + this.c * -this.b); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; +}; + +/** + * Translates the matrix on the x and y. + * + * @param {number} x How much to translate x by + * @param {number} y How much to translate y by + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.translate = function (x, y) +{ + this.tx += x; + this.ty += y; + + return this; +}; + +/** + * Applies a scale transformation to the matrix. + * + * @param {number} x The amount to scale horizontally + * @param {number} y The amount to scale vertically + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.scale = function (x, y) +{ + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; +}; + + +/** + * Applies a rotation transformation to the matrix. + * + * @param {number} angle - The angle in radians. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.rotate = function (angle) +{ + var cos = Math.cos( angle ); + var sin = Math.sin( angle ); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos-this.b * sin; + this.b = a1 * sin+this.b * cos; + this.c = c1 * cos-this.d * sin; + this.d = c1 * sin+this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; +}; + +/** + * Appends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.append = function (matrix) +{ + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; +}; + +/** + * Sets the matrix based on all the available properties + * + * @param {number} x Position on the x axis + * @param {number} y Position on the y axis + * @param {number} pivotX Pivot on the x axis + * @param {number} pivotY Pivot on the y axis + * @param {number} scaleX Scale on the x axis + * @param {number} scaleY Scale on the y axis + * @param {number} rotation Rotation in radians + * @param {number} skewX Skew on the x axis + * @param {number} skewY Skew on the y axis + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.setTransform = function (x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) +{ + var a, b, c, d, sr, cr, cy, sy, nsx, cx; + + sr = Math.sin(rotation); + cr = Math.cos(rotation); + cy = Math.cos(skewY); + sy = Math.sin(skewY); + nsx = -Math.sin(skewX); + cx = Math.cos(skewX); + + a = cr * scaleX; + b = sr * scaleX; + c = -sr * scaleY; + d = cr * scaleY; + + this.a = cy * a + sy * c; + this.b = cy * b + sy * d; + this.c = nsx * a + cx * c; + this.d = nsx * b + cx * d; + + this.tx = x + ( pivotX * a + pivotY * c ); + this.ty = y + ( pivotX * b + pivotY * d ); + + return this; +}; + +/** + * Prepends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.prepend = function(matrix) +{ + var tx1 = this.tx; + + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) + { + var a1 = this.a; + var c1 = this.c; + this.a = a1*matrix.a+this.b*matrix.c; + this.b = a1*matrix.b+this.b*matrix.d; + this.c = c1*matrix.a+this.d*matrix.c; + this.d = c1*matrix.b+this.d*matrix.d; + } + + this.tx = tx1*matrix.a+this.ty*matrix.c+matrix.tx; + this.ty = tx1*matrix.b+this.ty*matrix.d+matrix.ty; + + return this; +}; + +/** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * @param transform {PIXI.Transform|PIXI.TransformStatic} the transform to apply the properties to. + * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properies +*/ +Matrix.prototype.decompose = function(transform) +{ + // sort out rotation / skew.. + var a = this.a, + b = this.b, + c = this.c, + d = this.d; + + var skewX = Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + + var delta = Math.abs(1-skewX/skewY); + + if (delta < 0.00001) + { + transform.rotation = skewY; + + if (a < 0 && d >= 0) + { + transform.rotation += (transform.rotation <= 0) ? Math.PI : -Math.PI; + } + + transform.skew.x = transform.skew.y = 0; + + } + else + { + transform.skew.x = skewX; + transform.skew.y = skewY; + } + + // next set scale + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); + + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; + + return transform; +}; + + +/** + * Inverts this matrix + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.invert = function() +{ + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1*d1-b1*c1; + + this.a = d1/n; + this.b = -b1/n; + this.c = -c1/n; + this.d = a1/n; + this.tx = (c1*this.ty-d1*tx1)/n; + this.ty = -(a1*this.ty-b1*tx1)/n; + + return this; +}; + + +/** + * Resets this Matix to an identity (default) matrix. + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.identity = function () +{ + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + + return this; +}; + +/** + * Creates a new Matrix object with the same values as this one. + * + * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. + */ +Matrix.prototype.clone = function () +{ + var matrix = new Matrix(); + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; +}; + +/** + * Changes the values of the given matrix to be the same as the ones in this matrix + * + * @return {PIXI.Matrix} The matrix given in parameter with its values updated. + */ +Matrix.prototype.copy = function (matrix) +{ + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; +}; + +/** + * A default (identity) matrix + * + * @static + * @const + */ +Matrix.IDENTITY = new Matrix(); + +/** + * A temp matrix + * + * @static + * @const + */ +Matrix.TEMP_MATRIX = new Matrix(); + +},{"./Point":101}],100:[function(require,module,exports){ +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * An observable point is a point that triggers a callback when the point's position is changed. + * + * @class + * @memberof PIXI + * @param cb {Function} callback when changed + * @param scope {Object} owner of callback + * @param [x=0] {number} position of the point on the x axis + * @param [y=0] {number} position of the point on the y axis + */ +function ObservablePoint(cb, scope, x, y) +{ + this._x = x || 0; + this._y = y || 0; + + this.cb = cb; + this.scope = scope; +} + +ObservablePoint.prototype.constructor = ObservablePoint; +module.exports = ObservablePoint; + + + +Object.defineProperties(ObservablePoint.prototype, { + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + * @memberof PIXI.ObservablePoint# + */ + x: { + get: function () + { + return this._x; + }, + set: function (value) + { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + } + }, + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + * @memberof PIXI.ObservablePoint# + */ + y: { + get: function () + { + return this._y; + }, + set: function (value) + { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + } + } +}); + +/** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param [x=0] {number} position of the point on the x axis + * @param [y=0] {number} position of the point on the y axis + */ +ObservablePoint.prototype.set = function (x, y) +{ + var _x = x || 0; + var _y = y || ( (y !== 0) ? _x : 0 ); + if (this._x !== _x || this._y !== _y) + { + this._x = _x; + this._y = _y; + this.cb.call(this.scope); + } +}; + +/** + * Copies the data from another point + * + * @param point {PIXI.Point|PIXI.ObservablePoint} point to copy from + */ +ObservablePoint.prototype.copy = function (point) +{ + if (this._x !== point.x || this._y !== point.y) + { + this._x = point.x; + this._y = point.y; + this.cb.call(this.scope); + } +}; + +},{}],101:[function(require,module,exports){ +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * + * @class + * @memberof PIXI + * @param [x=0] {number} position of the point on the x axis + * @param [y=0] {number} position of the point on the y axis + */ +function Point(x, y) +{ + /** + * @member {number} + * @default 0 + */ + this.x = x || 0; + + /** + * @member {number} + * @default 0 + */ + this.y = y || 0; +} + +Point.prototype.constructor = Point; +module.exports = Point; + +/** + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point + */ +Point.prototype.clone = function () +{ + return new Point(this.x, this.y); +}; + +/** + * Copies x and y from the given point + * + * @param p {PIXI.Point} + */ +Point.prototype.copy = function (p) { + this.set(p.x, p.y); +}; + +/** + * Returns true if the given point is equal to this point + * + * @param p {PIXI.Point} + * @returns {boolean} Whether the given point equal to this point + */ +Point.prototype.equals = function (p) { + return (p.x === this.x) && (p.y === this.y); +}; + +/** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param [x=0] {number} position of the point on the x axis + * @param [y=0] {number} position of the point on the y axis + */ +Point.prototype.set = function (x, y) +{ + this.x = x || 0; + this.y = y || ( (y !== 0) ? this.x : 0 ) ; +}; + +},{}],102:[function(require,module,exports){ +/** + * Math classes and utilities mixed into PIXI namespace. + * + * @lends PIXI + */ +module.exports = { + // These will be mixed to be made publicly available, + // while this module is used internally in core + // to avoid circular dependencies and cut down on + // internal module requires. + + Point: require('./Point'), + ObservablePoint: require('./ObservablePoint'), + Matrix: require('./Matrix'), + GroupD8: require('./GroupD8'), + + Circle: require('./shapes/Circle'), + Ellipse: require('./shapes/Ellipse'), + Polygon: require('./shapes/Polygon'), + Rectangle: require('./shapes/Rectangle'), + RoundedRectangle: require('./shapes/RoundedRectangle') +}; + +},{"./GroupD8":98,"./Matrix":99,"./ObservablePoint":100,"./Point":101,"./shapes/Circle":103,"./shapes/Ellipse":104,"./shapes/Polygon":105,"./shapes/Rectangle":106,"./shapes/RoundedRectangle":107}],103:[function(require,module,exports){ +var Rectangle = require('./Rectangle'), + CONST = require('../../const'); + +/** + * The Circle object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + * @param x {number} The X coordinate of the center of this circle + * @param y {number} The Y coordinate of the center of this circle + * @param radius {number} The radius of the circle + */ +function Circle(x, y, radius) +{ + /** + * @member {number} + * @default 0 + */ + this.x = x || 0; + + /** + * @member {number} + * @default 0 + */ + this.y = y || 0; + + /** + * @member {number} + * @default 0 + */ + this.radius = radius || 0; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default CONST.SHAPES.CIRC + * @see PIXI.SHAPES + */ + this.type = CONST.SHAPES.CIRC; +} + +Circle.prototype.constructor = Circle; +module.exports = Circle; + +/** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ +Circle.prototype.clone = function () +{ + return new Circle(this.x, this.y, this.radius); +}; + +/** + * Checks whether the x and y coordinates given are contained within this circle + * + * @param x {number} The X coordinate of the point to test + * @param y {number} The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Circle + */ +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { + return false; + } + + var dx = (this.x - x), + dy = (this.y - y), + r2 = this.radius * this.radius; + + dx *= dx; + dy *= dy; + + return (dx + dy <= r2); +}; + +/** +* Returns the framing rectangle of the circle as a Rectangle object +* +* @return {PIXI.Rectangle} the framing rectangle +*/ +Circle.prototype.getBounds = function () +{ + return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); +}; + +},{"../../const":78,"./Rectangle":106}],104:[function(require,module,exports){ +var Rectangle = require('./Rectangle'), + CONST = require('../../const'); + +/** + * The Ellipse object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + * @param x {number} The X coordinate of the center of the ellipse + * @param y {number} The Y coordinate of the center of the ellipse + * @param width {number} The half width of this ellipse + * @param height {number} The half height of this ellipse + */ +function Ellipse(x, y, width, height) +{ + /** + * @member {number} + * @default 0 + */ + this.x = x || 0; + + /** + * @member {number} + * @default 0 + */ + this.y = y || 0; + + /** + * @member {number} + * @default 0 + */ + this.width = width || 0; + + /** + * @member {number} + * @default 0 + */ + this.height = height || 0; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default CONST.SHAPES.ELIP + * @see PIXI.SHAPES + */ + this.type = CONST.SHAPES.ELIP; +} + +Ellipse.prototype.constructor = Ellipse; +module.exports = Ellipse; + +/** + * Creates a clone of this Ellipse instance + * + * @return {PIXI.Ellipse} a copy of the ellipse + */ +Ellipse.prototype.clone = function () +{ + return new Ellipse(this.x, this.y, this.width, this.height); +}; + +/** + * Checks whether the x and y coordinates given are contained within this ellipse + * + * @param x {number} The X coordinate of the point to test + * @param y {number} The Y coordinate of the point to test + * @return {boolean} Whether the x/y coords are within this ellipse + */ +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { + return false; + } + + //normalize the coords to an ellipse with center 0,0 + var normx = ((x - this.x) / this.width), + normy = ((y - this.y) / this.height); + + normx *= normx; + normy *= normy; + + return (normx + normy <= 1); +}; + +/** + * Returns the framing rectangle of the ellipse as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ +Ellipse.prototype.getBounds = function () +{ + return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); +}; + +},{"../../const":78,"./Rectangle":106}],105:[function(require,module,exports){ +var Point = require('../Point'), + CONST = require('../../const'); + +/** + * @class + * @memberof PIXI + * @param points_ {PIXI.Point[]|number[]|...PIXI.Point|...number} This can be an array of Points that form the polygon, + * a flat array of numbers that will be interpreted as [x,y, x,y, ...], or the arguments passed can be + * all the points of the polygon e.g. `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the + * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are + * Numbers. + */ +function Polygon(points_) +{ + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = points_; + + //if points isn't an array, use arguments as the array + if (!Array.isArray(points)) + { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var a = 0; a < points.length; ++a) { + points[a] = arguments[a]; + } + } + + // if this is an array of points, convert it to a flat array of numbers + if (points[0] instanceof Point) + { + var p = []; + for (var i = 0, il = points.length; i < il; i++) + { + p.push(points[i].x, points[i].y); + } + + points = p; + } + + this.closed = true; + + /** + * An array of the points of this polygon + * + * @member {number[]} + */ + this.points = points; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default CONST.SHAPES.POLY + * @see PIXI.SHAPES + */ + this.type = CONST.SHAPES.POLY; +} + +Polygon.prototype.constructor = Polygon; +module.exports = Polygon; + +/** + * Creates a clone of this polygon + * + * @return {PIXI.Polygon} a copy of the polygon + */ +Polygon.prototype.clone = function () +{ + return new Polygon(this.points.slice()); +}; + + +Polygon.prototype.close = function () +{ + var points = this.points; + + // close the poly if the value is true! + if (points[0] !== points[points.length-2] || points[1] !== points[points.length-1]) + { + points.push(points[0], points[1]); + } +}; + +/** + * Checks whether the x and y coordinates passed to this function are contained within this polygon + * + * @param x {number} The X coordinate of the point to test + * @param y {number} The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this polygon + */ +Polygon.prototype.contains = function (x, y) +{ + var inside = false; + + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + + for (var i = 0, j = length - 1; i < length; j = i++) + { + var xi = this.points[i * 2], yi = this.points[i * 2 + 1], + xj = this.points[j * 2], yj = this.points[j * 2 + 1], + intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); + + if (intersect) + { + inside = !inside; + } + } + + return inside; +}; + +},{"../../const":78,"../Point":101}],106:[function(require,module,exports){ +var CONST = require('../../const'); + +/** + * the Rectangle object is an area defined by its position, as indicated by its top-left corner point (x, y) and by its width and its height. + * + * @class + * @memberof PIXI + * @param x {number} The X coordinate of the upper-left corner of the rectangle + * @param y {number} The Y coordinate of the upper-left corner of the rectangle + * @param width {number} The overall width of this rectangle + * @param height {number} The overall height of this rectangle + */ +function Rectangle(x, y, width, height) +{ + /** + * @member {number} + * @default 0 + */ + this.x = x || 0; + + /** + * @member {number} + * @default 0 + */ + this.y = y || 0; + + /** + * @member {number} + * @default 0 + */ + this.width = width || 0; + + /** + * @member {number} + * @default 0 + */ + this.height = height || 0; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default CONST.SHAPES.RECT + * @see PIXI.SHAPES + */ + this.type = CONST.SHAPES.RECT; +} + +Rectangle.prototype.constructor = Rectangle; +module.exports = Rectangle; + + +Object.defineProperties(Rectangle.prototype, { + /** + * returns the left edge of the rectangle + * + * @member {number} + * @memberof PIXI.Rectangle# + */ + left: { + get: function () + { + return this.x; + } + }, + + /** + * returns the right edge of the rectangle + * + * @member {number} + * @memberof PIXI.Rectangle + */ + right: { + get: function () + { + return this.x + this.width; + } + }, + + /** + * returns the top edge of the rectangle + * + * @member {number} + * @memberof PIXI.Rectangle + */ + top: { + get: function () + { + return this.y; + } + }, + + /** + * returns the bottom edge of the rectangle + * + * @member {number} + * @memberof PIXI.Rectangle + */ + bottom: { + get: function () + { + return this.y + this.height; + } + } + +}); + +/** + * A constant empty rectangle. + * + * @static + * @constant + */ +Rectangle.EMPTY = new Rectangle(0, 0, 0, 0); + + +/** + * Creates a clone of this Rectangle + * + * @return {PIXI.Rectangle} a copy of the rectangle + */ +Rectangle.prototype.clone = function () +{ + return new Rectangle(this.x, this.y, this.width, this.height); +}; + +Rectangle.prototype.copy = function (rectangle) +{ + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + + return this; +}; + +/** + * Checks whether the x and y coordinates given are contained within this Rectangle + * + * @param x {number} The X coordinate of the point to test + * @param y {number} The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rectangle + */ +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { + return false; + } + + if (x >= this.x && x < this.x + this.width) + { + if (y >= this.y && y < this.y + this.height) + { + return true; + } + } + + return false; +}; + +Rectangle.prototype.pad = function (paddingX, paddingY) +{ + paddingX = paddingX || 0; + paddingY = paddingY || ( (paddingY !== 0) ? paddingX : 0 ); + + this.x -= paddingX; + this.y -= paddingY; + + this.width += paddingX * 2; + this.height += paddingY * 2; +}; + +Rectangle.prototype.fit = function (rectangle) +{ + if (this.x < rectangle.x) + { + this.width += this.x; + if(this.width < 0) { + this.width = 0; + } + + this.x = rectangle.x; + } + + if (this.y < rectangle.y) + { + this.height += this.y; + if(this.height < 0) { + this.height = 0; + } + this.y = rectangle.y; + } + + if ( this.x + this.width > rectangle.x + rectangle.width ) + { + this.width = rectangle.width - this.x; + if(this.width < 0) { + this.width = 0; + } + } + + if ( this.y + this.height > rectangle.y + rectangle.height ) + { + this.height = rectangle.height - this.y; + if(this.height < 0) { + this.height = 0; + } + } +}; + +Rectangle.prototype.enlarge = function (rect) +{ + + if (rect === Rectangle.EMPTY) + { + return; + } + + var x1 = Math.min(this.x, rect.x); + var x2 = Math.max(this.x + this.width, rect.x + rect.width); + var y1 = Math.min(this.y, rect.y); + var y2 = Math.max(this.y + this.height, rect.y + rect.height); + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; +}; + +},{"../../const":78}],107:[function(require,module,exports){ +var CONST = require('../../const'); + +/** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its top-left corner point (x, y) and by its width and its height and its radius. + * + * @class + * @memberof PIXI + * @param x {number} The X coordinate of the upper-left corner of the rounded rectangle + * @param y {number} The Y coordinate of the upper-left corner of the rounded rectangle + * @param width {number} The overall width of this rounded rectangle + * @param height {number} The overall height of this rounded rectangle + * @param radius {number} Controls the radius of the rounded corners + */ +function RoundedRectangle(x, y, width, height, radius) +{ + /** + * @member {number} + * @default 0 + */ + this.x = x || 0; + + /** + * @member {number} + * @default 0 + */ + this.y = y || 0; + + /** + * @member {number} + * @default 0 + */ + this.width = width || 0; + + /** + * @member {number} + * @default 0 + */ + this.height = height || 0; + + /** + * @member {number} + * @default 20 + */ + this.radius = radius || 20; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readonly + * @default CONST.SHAPES.RREC + * @see PIXI.SHAPES + */ + this.type = CONST.SHAPES.RREC; +} + +RoundedRectangle.prototype.constructor = RoundedRectangle; +module.exports = RoundedRectangle; + +/** + * Creates a clone of this Rounded Rectangle + * + * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle + */ +RoundedRectangle.prototype.clone = function () +{ + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); +}; + +/** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * + * @param x {number} The X coordinate of the point to test + * @param y {number} The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + */ +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { + return false; + } + + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { + return true; + } + } + + return false; +}; + +},{"../../const":78}],108:[function(require,module,exports){ +var utils = require('../utils'), + math = require('../math'), + CONST = require('../const'), + Container = require('../display/Container'), + RenderTexture = require('../textures/RenderTexture'), + EventEmitter = require('eventemitter3'), + tempMatrix = new math.Matrix(); +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. + * Don't forget to add the CanvasRenderer.view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @param system {string} The name of the system this renderer is for. + * @param [width=800] {number} the width of the canvas view + * @param [height=600] {number} the height of the canvas view + * @param [options] {object} The optional renderer parameters + * @param [options.view] {HTMLCanvasElement} the canvas to use as a view, optional + * @param [options.transparent=false] {boolean} If the render view is transparent, default false + * @param [options.autoResize=false] {boolean} If the render view is automatically resized, default false + * @param [options.antialias=false] {boolean} sets antialias (only applicable in chrome at the moment) + * @param [options.resolution=1] {number} The resolution / device pixel ratio of the renderer. The resolution of the renderer retina would be 2. + * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. + * @param [options.backgroundColor=0x000000] {number} The background color of the rendered area (shown if not transparent). + * @param [options.roundPixels=false] {boolean} If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + */ +function SystemRenderer(system, width, height, options) +{ + EventEmitter.call(this); + + utils.sayHello(system); + + // prepare options + if (options) + { + for (var i in CONST.DEFAULT_RENDER_OPTIONS) + { + if (typeof options[i] === 'undefined') + { + options[i] = CONST.DEFAULT_RENDER_OPTIONS[i]; + } + } + } + else + { + options = CONST.DEFAULT_RENDER_OPTIONS; + } + + /** + * The type of the renderer. + * + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + this.type = CONST.RENDERER_TYPE.UNKNOWN; + + /** + * The width of the canvas view + * + * @member {number} + * @default 800 + */ + this.width = width || 800; + + /** + * The height of the canvas view + * + * @member {number} + * @default 600 + */ + this.height = height || 600; + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + this.view = options.view || document.createElement('canvas'); + + /** + * The resolution / device pixel ratio of the renderer + * + * @member {number} + * @default 1 + */ + this.resolution = options.resolution; + + /** + * Whether the render view is transparent + * + * @member {boolean} + */ + this.transparent = options.transparent; + + /** + * Whether the render view should be resized automatically + * + * @member {boolean} + */ + this.autoResize = options.autoResize || false; + + /** + * Tracks the blend modes useful for this renderer. + * + * @member {object} + */ + this.blendModes = null; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * + * @member {boolean} + */ + this.preserveDrawingBuffer = options.preserveDrawingBuffer; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent Pixi will use a canvas sized fillRect operation every frame to set the canvas background color. + * If the scene is transparent Pixi will use clearRect to clear the canvas every frame. + * Disable this by setting this to false. For example if your game has a canvas filling background image you often don't need this set. + * + * @member {boolean} + * @default + */ + this.clearBeforeRender = options.clearBeforeRender; + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + * + * @member {boolean} + */ + this.roundPixels = options.roundPixels; + + /** + * The background color as a number. + * + * @member {number} + * @private + */ + this._backgroundColor = 0x000000; + + /** + * The background color as an [R, G, B] array. + * + * @member {number[]} + * @private + */ + this._backgroundColorRgba = [0, 0, 0, 0]; + + /** + * The background color as a string. + * + * @member {string} + * @private + */ + this._backgroundColorString = '#000000'; + + this.backgroundColor = options.backgroundColor || this._backgroundColor; // run bg color setter + + /** + * This temporary display object used as the parent of the currently being rendered item + * + * @member {PIXI.DisplayObject} + * @private + */ + this._tempDisplayObjectParent = new Container(); + + /** + * The last root object that the renderer tried to render. + * + * @member {PIXI.DisplayObject} + * @private + */ + this._lastObjectRendered = this._tempDisplayObjectParent; +} + +// constructor +SystemRenderer.prototype = Object.create(EventEmitter.prototype); +SystemRenderer.prototype.constructor = SystemRenderer; +module.exports = SystemRenderer; + +Object.defineProperties(SystemRenderer.prototype, { + /** + * The background color to fill if not transparent + * + * @member {number} + * @memberof PIXI.SystemRenderer# + */ + backgroundColor: + { + get: function () + { + return this._backgroundColor; + }, + set: function (val) + { + this._backgroundColor = val; + this._backgroundColorString = utils.hex2string(val); + utils.hex2rgb(val, this._backgroundColorRgba); + } + } +}); + +/** + * Resizes the canvas view to the specified width and height + * + * @param width {number} the new width of the canvas view + * @param height {number} the new height of the canvas view + */ +SystemRenderer.prototype.resize = function (width, height) { + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) + { + this.view.style.width = this.width / this.resolution + 'px'; + this.view.style.height = this.height / this.resolution + 'px'; + } +}; + +/** + * Useful function that returns a texture of the display object that can then be used to create sprites + * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. + * + * @param displayObject {PIXI.DisplayObject} The displayObject the object will be generated from + * @param scaleMode {number} Should be one of the scaleMode consts + * @param resolution {number} The resolution / device pixel ratio of the texture being generated + * @return {PIXI.Texture} a texture of the graphics object + */ +SystemRenderer.prototype.generateTexture = function (displayObject, scaleMode, resolution) { + + var bounds = displayObject.getLocalBounds(); + + var renderTexture = RenderTexture.create(bounds.width | 0, bounds.height | 0, scaleMode, resolution); + + tempMatrix.tx = -bounds.x; + tempMatrix.ty = -bounds.y; + + this.render(displayObject, renderTexture, false, tempMatrix, true); + + return renderTexture; +}; + +/** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. + */ +SystemRenderer.prototype.destroy = function (removeView) { + if (removeView && this.view.parentNode) + { + this.view.parentNode.removeChild(this.view); + } + + this.type = CONST.RENDERER_TYPE.UNKNOWN; + + this.width = 0; + this.height = 0; + + this.view = null; + + this.resolution = 0; + + this.transparent = false; + + this.autoResize = false; + + this.blendModes = null; + + this.preserveDrawingBuffer = false; + this.clearBeforeRender = false; + + this.roundPixels = false; + + this._backgroundColor = 0; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + + this.backgroundColor = 0; + this._tempDisplayObjectParent = null; + this._lastObjectRendered = null; +}; + +},{"../const":78,"../display/Container":80,"../math":102,"../textures/RenderTexture":143,"../utils":151,"eventemitter3":32}],109:[function(require,module,exports){ +var SystemRenderer = require('../SystemRenderer'), + CanvasMaskManager = require('./utils/CanvasMaskManager'), + CanvasRenderTarget = require('./utils/CanvasRenderTarget'), + mapCanvasBlendModesToPixi = require('./utils/mapCanvasBlendModesToPixi'), + utils = require('../../utils'), + CONST = require('../../const'); + +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. + * Don't forget to add the CanvasRenderer.view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + * @param [width=800] {number} the width of the canvas view + * @param [height=600] {number} the height of the canvas view + * @param [options] {object} The optional renderer parameters + * @param [options.view] {HTMLCanvasElement} the canvas to use as a view, optional + * @param [options.transparent=false] {boolean} If the render view is transparent, default false + * @param [options.autoResize=false] {boolean} If the render view is automatically resized, default false + * @param [options.antialias=false] {boolean} sets antialias (only applicable in chrome at the moment) + * @param [options.resolution=1] {number} The resolution / device pixel ratio of the renderer. The resolution of the renderer retina would be 2. + * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. + * @param [options.roundPixels=false] {boolean} If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + */ +function CanvasRenderer(width, height, options) +{ + options = options || {}; + + SystemRenderer.call(this, 'Canvas', width, height, options); + + this.type = CONST.RENDERER_TYPE.CANVAS; + + /** + * The canvas 2d context that everything is drawn with. + * + * @member {CanvasRenderingContext2D} + */ + this.rootContext = this.view.getContext('2d', { alpha: this.transparent }); + this.rootResolution = this.resolution; + + /** + * Boolean flag controlling canvas refresh. + * + * @member {boolean} + */ + this.refresh = true; + + /** + * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. + * + * @member {PIXI.CanvasMaskManager} + */ + this.maskManager = new CanvasMaskManager(this); + + /** + * The canvas property used to set the canvas smoothing property. + * + * @member {string} + */ + this.smoothProperty = 'imageSmoothingEnabled'; + + if (!this.rootContext.imageSmoothingEnabled) + { + if (this.rootContext.webkitImageSmoothingEnabled) + { + this.smoothProperty = 'webkitImageSmoothingEnabled'; + } + else if (this.rootContext.mozImageSmoothingEnabled) + { + this.smoothProperty = 'mozImageSmoothingEnabled'; + } + else if (this.rootContext.oImageSmoothingEnabled) + { + this.smoothProperty = 'oImageSmoothingEnabled'; + } + else if (this.rootContext.msImageSmoothingEnabled) + { + this.smoothProperty = 'msImageSmoothingEnabled'; + } + } + + this.initPlugins(); + + this.blendModes = mapCanvasBlendModesToPixi(); + this._activeBlendMode = null; + + this.context = null; + this.renderingToScreen = false; + + this.resize(width, height); +} + +// constructor +CanvasRenderer.prototype = Object.create(SystemRenderer.prototype); +CanvasRenderer.prototype.constructor = CanvasRenderer; +module.exports = CanvasRenderer; +utils.pluginTarget.mixin(CanvasRenderer); + + +/** + * Renders the object to this canvas view + * + * @param displayObject {PIXI.DisplayObject} The object to be rendered + * @param [renderTexture] {PIXI.RenderTexture} A render texture to be rendered to. If unset, it will render to the root context. + * @param [clear=false] {boolean} Whether to clear the canvas before drawing + * @param [transform] {PIXI.Transform} A transformation to be applied + * @param [skipUpdateTransform=false] {boolean} Whether to skip the update transform + */ +CanvasRenderer.prototype.render = function (displayObject, renderTexture, clear, transform, skipUpdateTransform) +{ + + if (!this.view){ + return; + } + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + if(renderTexture) + { + renderTexture = renderTexture.baseTexture || renderTexture; + + if(!renderTexture._canvasRenderTarget) + { + + renderTexture._canvasRenderTarget = new CanvasRenderTarget(renderTexture.width, renderTexture.height, renderTexture.resolution); + renderTexture.source = renderTexture._canvasRenderTarget.canvas; + renderTexture.valid = true; + } + + this.context = renderTexture._canvasRenderTarget.context; + this.resolution = renderTexture._canvasRenderTarget.resolution; + } + else + { + + this.context = this.rootContext; + this.resolution = this.rootResolution; + } + + var context = this.context; + + if(!renderTexture) + { + this._lastObjectRendered = displayObject; + } + + + + + if(!skipUpdateTransform) + { + // update the scene graph + var cacheParent = displayObject.parent; + var tempWt = this._tempDisplayObjectParent.transform.worldTransform; + + if(transform) + { + transform.copy(tempWt); + } + else + { + tempWt.identity(); + } + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + + context.setTransform(1, 0, 0, 1, 0, 0); + context.globalAlpha = 1; + context.globalCompositeOperation = this.blendModes[CONST.BLEND_MODES.NORMAL]; + + if (navigator.isCocoonJS && this.view.screencanvas) + { + context.fillStyle = 'black'; + context.clear(); + } + + if(clear !== undefined ? clear : this.clearBeforeRender) + { + if (this.renderingToScreen) { + if (this.transparent) { + context.clearRect(0, 0, this.width, this.height); + } + else { + context.fillStyle = this._backgroundColorString; + context.fillRect(0, 0, this.width, this.height); + } + } //else { + //TODO: implement background for CanvasRenderTarget or RenderTexture? + //} + } + + // TODO RENDER TARGET STUFF HERE.. + var tempContext = this.context; + + this.context = context; + displayObject.renderCanvas(this); + this.context = tempContext; + + this.emit('postrender'); +}; + + +CanvasRenderer.prototype.setBlendMode = function (blendMode) +{ + if(this._activeBlendMode === blendMode) { + return; + } + + this.context.globalCompositeOperation = this.blendModes[blendMode]; +}; + +/** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. + */ +CanvasRenderer.prototype.destroy = function (removeView) +{ + this.destroyPlugins(); + + // call the base destroy + SystemRenderer.prototype.destroy.call(this, removeView); + + this.context = null; + + this.refresh = true; + + this.maskManager.destroy(); + this.maskManager = null; + + this.smoothProperty = null; +}; + +/** + * Resizes the canvas view to the specified width and height. + * + * @extends PIXI.SystemRenderer#resize + * + * @param width {number} The new width of the canvas view + * @param height {number} The new height of the canvas view + */ +CanvasRenderer.prototype.resize = function (width, height) +{ + SystemRenderer.prototype.resize.call(this, width, height); + + //reset the scale mode.. oddly this seems to be reset when the canvas is resized. + //surely a browser bug?? Let pixi fix that for you.. + if(this.smoothProperty) + { + this.rootContext[this.smoothProperty] = (CONST.SCALE_MODES.DEFAULT === CONST.SCALE_MODES.LINEAR); + } + +}; + +},{"../../const":78,"../../utils":151,"../SystemRenderer":108,"./utils/CanvasMaskManager":110,"./utils/CanvasRenderTarget":111,"./utils/mapCanvasBlendModesToPixi":113}],110:[function(require,module,exports){ +var CONST = require('../../../const'); +/** + * A set of functions used to handle masking. + * + * @class + * @memberof PIXI + */ +function CanvasMaskManager(renderer) +{ + this.renderer = renderer; +} + +CanvasMaskManager.prototype.constructor = CanvasMaskManager; +module.exports = CanvasMaskManager; + +/** + * This method adds it to the current stack of masks. + * + * @param maskData {object} the maskData that will be pushed + */ +CanvasMaskManager.prototype.pushMask = function (maskData) +{ + var renderer = this.renderer; + + renderer.context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.transform.worldTransform; + var resolution = renderer.resolution; + + renderer.context.setTransform( + transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + transform.tx * resolution, + transform.ty * resolution + ); + + //TODO suport sprite alpha masks?? + //lots of effort required. If demand is great enough.. + if(!maskData._texture) + { + this.renderGraphicsShape(maskData); + renderer.context.clip(); + } + + maskData.worldAlpha = cacheAlpha; +}; + +CanvasMaskManager.prototype.renderGraphicsShape = function (graphics) +{ + var context = this.renderer.context; + var len = graphics.graphicsData.length; + + if (len === 0) + { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === CONST.SHAPES.POLY) + { + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + } + else if (data.type === CONST.SHAPES.RECT) + { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } + else if (data.type === CONST.SHAPES.CIRC) + { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } + else if (data.type === CONST.SHAPES.ELIP) + { + + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } + else if (data.type === CONST.SHAPES.RREC) + { + + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } +}; + +/** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @param renderer {PIXI.WebGLRenderer|PIXI.CanvasRenderer} The renderer context to use. + */ +CanvasMaskManager.prototype.popMask = function (renderer) +{ + renderer.context.restore(); +}; + +CanvasMaskManager.prototype.destroy = function () {}; + +},{"../../../const":78}],111:[function(require,module,exports){ +var CONST = require('../../../const'); + +/** + * Creates a Canvas element of the given size. + * + * @class + * @memberof PIXI + * @param width {number} the width for the newly created canvas + * @param height {number} the height for the newly created canvas + * @param [resolution=1] The resolution / device pixel ratio of the canvas + */ +function CanvasRenderTarget(width, height, resolution) +{ + /** + * The Canvas object that belongs to this CanvasRenderTarget. + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @member {CanvasRenderingContext2D} + */ + this.context = this.canvas.getContext('2d'); + + this.resolution = resolution || CONST.RESOLUTION; + + this.resize(width, height); +} + +CanvasRenderTarget.prototype.constructor = CanvasRenderTarget; +module.exports = CanvasRenderTarget; + +Object.defineProperties(CanvasRenderTarget.prototype, { + /** + * The width of the canvas buffer in pixels. + * + * @member {number} + * @memberof PIXI.CanvasRenderTarget# + */ + width: { + get: function () + { + return this.canvas.width; + }, + set: function (val) + { + this.canvas.width = val; + } + }, + /** + * The height of the canvas buffer in pixels. + * + * @member {number} + * @memberof PIXI.CanvasRenderTarget# + */ + height: { + get: function () + { + return this.canvas.height; + }, + set: function (val) + { + this.canvas.height = val; + } + } +}); + +/** + * Clears the canvas that was created by the CanvasRenderTarget class. + * + * @private + */ +CanvasRenderTarget.prototype.clear = function () +{ + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0,0, this.canvas.width, this.canvas.height); +}; + +/** + * Resizes the canvas to the specified width and height. + * + * @param width {number} the new width of the canvas + * @param height {number} the new height of the canvas + */ +CanvasRenderTarget.prototype.resize = function (width, height) +{ + + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; +}; + +/** + * Destroys this canvas. + * + */ +CanvasRenderTarget.prototype.destroy = function () +{ + this.context = null; + this.canvas = null; +}; + +},{"../../../const":78}],112:[function(require,module,exports){ + + +/** + * Creates a little colored canvas + * @return {canvas} a small canvas element + */ +var createColoredCanvas = function(color) +{ + var canvas = document.createElement('canvas'); + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + context.fillStyle = color; + context.fillRect(0,0,6,1); + return canvas; +}; + + +/** + * Checks whether the Canvas BlendModes are supported by the current browser + * + * @return {boolean} whether they are supported + */ +var canUseNewCanvasBlendModes = function () +{ + if (typeof document === 'undefined') + { + return false; + } + + var magenta = createColoredCanvas('#ff00ff'); + var yellow = createColoredCanvas('#ffff00'); + + var canvas = document.createElement('canvas'); + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + context.globalCompositeOperation = 'multiply'; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + var imageData = context.getImageData(2,0,1,1); + + if (!imageData) + { + return false; + } + + var data = imageData.data; + + return (data[0] === 255 && data[1] === 0 && data[2] === 0); +}; + + +module.exports = canUseNewCanvasBlendModes; + +},{}],113:[function(require,module,exports){ +var CONST = require('../../../const'), +canUseNewCanvasBlendModes = require('./canUseNewCanvasBlendModes'); + +/** + * Maps blend combinations to Canvas + * @class + * @memberof PIXI + * @param array + */ +function mapCanvasBlendModesToPixi(array) +{ + array = array || []; + + if (canUseNewCanvasBlendModes()) + { + array[CONST.BLEND_MODES.NORMAL] = 'source-over'; + array[CONST.BLEND_MODES.ADD] = 'lighter'; //IS THIS OK??? + array[CONST.BLEND_MODES.MULTIPLY] = 'multiply'; + array[CONST.BLEND_MODES.SCREEN] = 'screen'; + array[CONST.BLEND_MODES.OVERLAY] = 'overlay'; + array[CONST.BLEND_MODES.DARKEN] = 'darken'; + array[CONST.BLEND_MODES.LIGHTEN] = 'lighten'; + array[CONST.BLEND_MODES.COLOR_DODGE] = 'color-dodge'; + array[CONST.BLEND_MODES.COLOR_BURN] = 'color-burn'; + array[CONST.BLEND_MODES.HARD_LIGHT] = 'hard-light'; + array[CONST.BLEND_MODES.SOFT_LIGHT] = 'soft-light'; + array[CONST.BLEND_MODES.DIFFERENCE] = 'difference'; + array[CONST.BLEND_MODES.EXCLUSION] = 'exclusion'; + array[CONST.BLEND_MODES.HUE] = 'hue'; + array[CONST.BLEND_MODES.SATURATION] = 'saturate'; + array[CONST.BLEND_MODES.COLOR] = 'color'; + array[CONST.BLEND_MODES.LUMINOSITY] = 'luminosity'; + } + else + { + // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' + array[CONST.BLEND_MODES.NORMAL] = 'source-over'; + array[CONST.BLEND_MODES.ADD] = 'lighter'; //IS THIS OK??? + array[CONST.BLEND_MODES.MULTIPLY] = 'source-over'; + array[CONST.BLEND_MODES.SCREEN] = 'source-over'; + array[CONST.BLEND_MODES.OVERLAY] = 'source-over'; + array[CONST.BLEND_MODES.DARKEN] = 'source-over'; + array[CONST.BLEND_MODES.LIGHTEN] = 'source-over'; + array[CONST.BLEND_MODES.COLOR_DODGE] = 'source-over'; + array[CONST.BLEND_MODES.COLOR_BURN] = 'source-over'; + array[CONST.BLEND_MODES.HARD_LIGHT] = 'source-over'; + array[CONST.BLEND_MODES.SOFT_LIGHT] = 'source-over'; + array[CONST.BLEND_MODES.DIFFERENCE] = 'source-over'; + array[CONST.BLEND_MODES.EXCLUSION] = 'source-over'; + array[CONST.BLEND_MODES.HUE] = 'source-over'; + array[CONST.BLEND_MODES.SATURATION] = 'source-over'; + array[CONST.BLEND_MODES.COLOR] = 'source-over'; + array[CONST.BLEND_MODES.LUMINOSITY] = 'source-over'; + } + + return array; +} + +module.exports = mapCanvasBlendModesToPixi; + +},{"../../../const":78,"./canUseNewCanvasBlendModes":112}],114:[function(require,module,exports){ + +var CONST = require('../../const'); + +/** + * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged up with textures that are no longer being used. + * + * @class + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} The renderer this manager works for. + */ +function TextureGarbageCollector(renderer) +{ + this.renderer = renderer; + + this.count = 0; + this.checkCount = 0; + this.maxIdle = 60 * 60; + this.checkCountMax = 60 * 10; + + this.mode = CONST.GC_MODES.DEFAULT; +} + +TextureGarbageCollector.prototype.constructor = TextureGarbageCollector; +module.exports = TextureGarbageCollector; + +/** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ +TextureGarbageCollector.prototype.update = function() +{ + this.count++; + + if(this.mode === CONST.GC_MODES.MANUAL) + { + return; + } + + this.checkCount++; + + + if(this.checkCount > this.checkCountMax) + { + this.checkCount = 0; + + this.run(); + } +}; + +/** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ +TextureGarbageCollector.prototype.run = function() +{ + var tm = this.renderer.textureManager; + var managedTextures = tm._managedTextures; + var wasRemoved = false; + var i,j; + + for (i = 0; i < managedTextures.length; i++) + { + var texture = managedTextures[i]; + + // only supports non generated textures at the moment! + if (!texture._glRenderTargets && this.count - texture.touched > this.maxIdle) + { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + + if (wasRemoved) + { + j = 0; + + for (i = 0; i < managedTextures.length; i++) + { + if (managedTextures[i] !== null) + { + managedTextures[j++] = managedTextures[i]; + } + } + + managedTextures.length = j; + } +}; + +/** + * Removes all the textures within the specified displayObject and its children from the GPU + * + * @param displayObject {PIXI.DisplayObject} the displayObject to remove the textures from. + */ +TextureGarbageCollector.prototype.unload = function( displayObject ) +{ + var tm = this.renderer.textureManager; + + if(displayObject._texture) + { + tm.destroyTexture(displayObject._texture, true); + } + + for (var i = displayObject.children.length - 1; i >= 0; i--) { + + this.unload(displayObject.children[i]); + + } +}; + +},{"../../const":78}],115:[function(require,module,exports){ +var GLTexture = require('pixi-gl-core').GLTexture, + CONST = require('../../const'), + RenderTarget = require('./utils/RenderTarget'), + utils = require('../../utils'); + +/** + * Helper class to create a webGL Texture + * + * @class + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} A reference to the current renderer + */ +var TextureManager = function(renderer) +{ + /** + * A reference to the current renderer + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = renderer.gl; + + /** + * Track textures in the renderer so we can no longer listen to them on destruction. + * + * @member {Array<*>} + * @private + */ + this._managedTextures = []; +}; + +TextureManager.prototype.bindTexture = function() +{ +}; + + +TextureManager.prototype.getTexture = function() +{ +}; + +/** + * Updates and/or Creates a WebGL texture for the renderer's context. + * + * @param texture {PIXI.BaseTexture|PIXI.Texture} the texture to update + */ +TextureManager.prototype.updateTexture = function(texture) +{ + texture = texture.baseTexture || texture; + + var isRenderTexture = !!texture._glRenderTargets; + + if (!texture.hasLoaded) + { + return; + } + + var glTexture = texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!glTexture) + { + if(isRenderTexture) + { + var renderTarget = new RenderTarget(this.gl, texture.width, texture.height, texture.scaleMode, texture.resolution); + renderTarget.resize(texture.width, texture.height); + texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget; + glTexture = renderTarget.texture; + } + else + { + glTexture = new GLTexture(this.gl); + glTexture.premultiplyAlpha = true; + glTexture.upload(texture.source); + } + + texture._glTextures[this.renderer.CONTEXT_UID] = glTexture; + + texture.on('update', this.updateTexture, this); + texture.on('dispose', this.destroyTexture, this); + + this._managedTextures.push(texture); + + if(texture.isPowerOfTwo) + { + if(texture.mipmap) + { + glTexture.enableMipmap(); + } + + if(texture.wrapMode === CONST.WRAP_MODES.CLAMP) + { + glTexture.enableWrapClamp(); + } + else if(texture.wrapMode === CONST.WRAP_MODES.REPEAT) + { + glTexture.enableWrapRepeat(); + } + else + { + glTexture.enableWrapMirrorRepeat(); + } + } + else + { + glTexture.enableWrapClamp(); + } + + if(texture.scaleMode === CONST.SCALE_MODES.NEAREST) + { + glTexture.enableNearestScaling(); + } + else + { + glTexture.enableLinearScaling(); + } + } + else + { + // the textur ealrady exists so we only need to update it.. + if(isRenderTexture) + { + texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height); + } + else + { + glTexture.upload(texture.source); + } + } + + return glTexture; +}; + +/** + * Deletes the texture from WebGL + * + * @param texture {PIXI.BaseTexture|PIXI.Texture} the texture to destroy + * @param [skipRemove=false] {boolean} Whether to skip removing the texture from the TextureManager. + */ +TextureManager.prototype.destroyTexture = function(texture, skipRemove) +{ + texture = texture.baseTexture || texture; + + if (!texture.hasLoaded) + { + return; + } + + if (texture._glTextures[this.renderer.CONTEXT_UID]) + { + texture._glTextures[this.renderer.CONTEXT_UID].destroy(); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + + + delete texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!skipRemove) + { + var i = this._managedTextures.indexOf(texture); + if (i !== -1) { + utils.removeItems(this._managedTextures, i, 1); + } + } + } +}; + +/** + * Deletes all the textures from WebGL + */ +TextureManager.prototype.removeAll = function() +{ + // empty all the old gl textures as they are useless now + for (var i = 0; i < this._managedTextures.length; ++i) + { + var texture = this._managedTextures[i]; + if (texture._glTextures[this.renderer.CONTEXT_UID]) + { + delete texture._glTextures[this.renderer.CONTEXT_UID]; + } + } +}; + +/** + * Destroys this manager and removes all its textures + */ +TextureManager.prototype.destroy = function() +{ + // destroy managed textures + for (var i = 0; i < this._managedTextures.length; ++i) + { + var texture = this._managedTextures[i]; + this.destroyTexture(texture, true); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + } + + this._managedTextures = null; +}; + +module.exports = TextureManager; + +},{"../../const":78,"../../utils":151,"./utils/RenderTarget":128,"pixi-gl-core":7}],116:[function(require,module,exports){ +var SystemRenderer = require('../SystemRenderer'), + MaskManager = require('./managers/MaskManager'), + StencilManager = require('./managers/StencilManager'), + FilterManager = require('./managers/FilterManager'), + RenderTarget = require('./utils/RenderTarget'), + ObjectRenderer = require('./utils/ObjectRenderer'), + TextureManager = require('./TextureManager'), + TextureGarbageCollector = require('./TextureGarbageCollector'), + WebGLState = require('./WebGLState'), + createContext = require('pixi-gl-core').createContext, + mapWebGLDrawModesToPixi = require('./utils/mapWebGLDrawModesToPixi'), + validateContext = require('./utils/validateContext'), + utils = require('../../utils'), + glCore = require('pixi-gl-core'), + CONST = require('../../const'); + +var CONTEXT_UID = 0; + +/** + * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + * @param [width=0] {number} the width of the canvas view + * @param [height=0] {number} the height of the canvas view + * @param [options] {object} The optional renderer parameters + * @param [options.view] {HTMLCanvasElement} the canvas to use as a view, optional + * @param [options.transparent=false] {boolean} If the render view is transparent, default false + * @param [options.autoResize=false] {boolean} If the render view is automatically resized, default false + * @param [options.antialias=false] {boolean} sets antialias. If not available natively then FXAA antialiasing is used + * @param [options.forceFXAA=false] {boolean} forces FXAA antialiasing to be used over native. FXAA is faster, but may not always look as great + * @param [options.resolution=1] {number} The resolution / device pixel ratio of the renderer. The resolution of the renderer retina would be 2. + * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. If you wish to set this to false, you *must* set preserveDrawingBuffer to `true`. + * @param [options.preserveDrawingBuffer=false] {boolean} enables drawing buffer preservation, enable this if + * you need to call toDataUrl on the webgl context. + * @param [options.roundPixels=false] {boolean} If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + */ +function WebGLRenderer(width, height, options) +{ + options = options || {}; + + SystemRenderer.call(this, 'WebGL', width, height, options); + /** + * The type of this renderer as a standardised const + * + * @member {number} + * @see PIXI.RENDERER_TYPE + */ + this.type = CONST.RENDERER_TYPE.WEBGL; + + this.handleContextLost = this.handleContextLost.bind(this); + this.handleContextRestored = this.handleContextRestored.bind(this); + + this.view.addEventListener('webglcontextlost', this.handleContextLost, false); + this.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); + + /** + * The options passed in to create a new webgl context. + * + * @member {object} + * @private + */ + this._contextOptions = { + alpha: this.transparent, + antialias: options.antialias, + premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: options.preserveDrawingBuffer + }; + + this._backgroundColorRgba[3] = this.transparent ? 0 : 1; + + /** + * Manages the masks using the stencil buffer. + * + * @member {PIXI.MaskManager} + */ + this.maskManager = new MaskManager(this); + + /** + * Manages the stencil buffer. + * + * @member {PIXI.StencilManager} + */ + this.stencilManager = new StencilManager(this); + + /** + * An empty renderer. + * + * @member {PIXI.ObjectRenderer} + */ + this.emptyRenderer = new ObjectRenderer(this); + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.ObjectRenderer} + */ + this.currentRenderer = this.emptyRenderer; + + this.initPlugins(); + + /** + * The current WebGL rendering context, it is created here + * + * @member {WebGLRenderingContext} + */ + // initialize the context so it is ready for the managers. + if(options.context) + { + // checks to see if a context is valid.. + validateContext(options.context); + } + + this.gl = options.context || createContext(this.view, this._contextOptions); + + this.CONTEXT_UID = CONTEXT_UID++; + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.WebGLState} + */ + this.state = new WebGLState(this.gl); + + this.renderingToScreen = true; + + + + this._initContext(); + + /** + * Manages the filters. + * + * @member {PIXI.FilterManager} + */ + this.filterManager = new FilterManager(this); + // map some webGL blend and drawmodes.. + this.drawModes = mapWebGLDrawModesToPixi(this.gl); + + + /** + * Holds the current shader + * + * @member {PIXI.Shader} + */ + this._activeShader = null; + + /** + * Holds the current render target + * + * @member {PIXI.RenderTarget} + */ + this._activeRenderTarget = null; + this._activeTextureLocation = 999; + this._activeTexture = null; + + this.setBlendMode(0); + + +} + +// constructor +WebGLRenderer.prototype = Object.create(SystemRenderer.prototype); +WebGLRenderer.prototype.constructor = WebGLRenderer; +module.exports = WebGLRenderer; +utils.pluginTarget.mixin(WebGLRenderer); + +/** + * Creates the WebGL context + * + * @private + */ +WebGLRenderer.prototype._initContext = function () +{ + var gl = this.gl; + + // create a texture manager... + this.textureManager = new TextureManager(this); + this.textureGC = new TextureGarbageCollector(this); + + this.state.resetToDefault(); + + this.rootRenderTarget = new RenderTarget(gl, this.width, this.height, null, this.resolution, true); + this.rootRenderTarget.clearColor = this._backgroundColorRgba; + + + this.bindRenderTarget(this.rootRenderTarget); + + this.emit('context', gl); + + // setup the width/height properties and gl viewport + this.resize(this.width, this.height); +}; + +/** + * Renders the object to its webGL view + * + * @param displayObject {PIXI.DisplayObject} the object to be rendered + * @param renderTexture {PIXI.RenderTexture} + * @param [clear] {boolean} Should the canvas be cleared before the new render + * @param [transform] {PIXI.Transform} + * @param [skipUpdateTransform] {boolean} + */ +WebGLRenderer.prototype.render = function (displayObject, renderTexture, clear, transform, skipUpdateTransform) +{ + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + + // no point rendering if our context has been blown up! + if (!this.gl || this.gl.isContextLost()) + { + return; + } + + if(!renderTexture) + { + this._lastObjectRendered = displayObject; + } + + if(!skipUpdateTransform) + { + // update the scene graph + var cacheParent = displayObject.parent; + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + this.bindRenderTexture(renderTexture, transform); + + this.currentRenderer.start(); + + if(clear !== undefined ? clear : this.clearBeforeRender) + { + this._activeRenderTarget.clear(); + } + + displayObject.renderWebGL(this); + + // apply transform.. + this.currentRenderer.flush(); + + //this.setObjectRenderer(this.emptyRenderer); + + this.textureGC.update(); + + this.emit('postrender'); +}; + +/** + * Changes the current renderer to the one given in parameter + * + * @param objectRenderer {PIXI.ObjectRenderer} The object renderer to use. + */ +WebGLRenderer.prototype.setObjectRenderer = function (objectRenderer) +{ + if (this.currentRenderer === objectRenderer) + { + return; + } + + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); +}; + +/** + * This shoudl be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + * + */ +WebGLRenderer.prototype.flush = function () +{ + this.setObjectRenderer(this.emptyRenderer); +}; + +/** + * Resizes the webGL view to the specified width and height. + * + * @param width {number} the new width of the webGL view + * @param height {number} the new height of the webGL view + */ +WebGLRenderer.prototype.resize = function (width, height) +{ + // if(width * this.resolution === this.width && height * this.resolution === this.height)return; + + SystemRenderer.prototype.resize.call(this, width, height); + + this.rootRenderTarget.resize(width, height); + + if(this._activeRenderTarget === this.rootRenderTarget) + { + this.rootRenderTarget.activate(); + + if(this._activeShader) + { + this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true); + } + } +}; + +/** + * Resizes the webGL view to the specified width and height. + * + * @param blendMode {number} the desired blend mode + */ +WebGLRenderer.prototype.setBlendMode = function (blendMode) +{ + this.state.setBlendMode(blendMode); +}; + +/** + * Erases the active render target and fills the drawing area with a colour + * + * @param [clearColor] {number} The colour + */ +WebGLRenderer.prototype.clear = function (clearColor) +{ + this._activeRenderTarget.clear(clearColor); +}; + +/** + * Sets the transform of the active render target to the given matrix + * + * @param matrix {PIXI.Matrix} The transformation matrix + */ +WebGLRenderer.prototype.setTransform = function (matrix) +{ + this._activeRenderTarget.transform = matrix; +}; + + +/** + * Binds a render texture for rendering + * + * @param renderTexture {PIXI.RenderTexture} The render texture to render + * @param transform {PIXI.Transform} The transform to be applied to the render texture + */ +WebGLRenderer.prototype.bindRenderTexture = function (renderTexture, transform) +{ + var renderTarget; + + if(renderTexture) + { + var baseTexture = renderTexture.baseTexture; + var gl = this.gl; + + if(!baseTexture._glRenderTargets[this.CONTEXT_UID]) + { + + this.textureManager.updateTexture(baseTexture); + gl.bindTexture(gl.TEXTURE_2D, null); + } + else + { + // the texture needs to be unbound if its being rendererd too.. + this._activeTextureLocation = baseTexture._id; + gl.activeTexture(gl.TEXTURE0 + baseTexture._id); + gl.bindTexture(gl.TEXTURE_2D, null); + } + + + renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + renderTarget.setFrame(renderTexture.frame); + } + else + { + renderTarget = this.rootRenderTarget; + } + + renderTarget.transform = transform; + this.bindRenderTarget(renderTarget); + + return this; +}; + +/** + * Changes the current render target to the one given in parameter + * + * @param renderTarget {PIXI.RenderTarget} the new render target + */ +WebGLRenderer.prototype.bindRenderTarget = function (renderTarget) +{ + if(renderTarget !== this._activeRenderTarget) + { + this._activeRenderTarget = renderTarget; + renderTarget.activate(); + + if(this._activeShader) + { + this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true); + } + + + this.stencilManager.setMaskStack( renderTarget.stencilMaskStack ); + } + + return this; +}; + +/** + * Changes the current shader to the one given in parameter + * + * @param shader {PIXI.Shader} the new shader + */ +WebGLRenderer.prototype.bindShader = function (shader) +{ + //TODO cache + if(this._activeShader !== shader) + { + this._activeShader = shader; + shader.bind(); + + // automatically set the projection matrix + shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(true); + } + + return this; +}; + +/** + * Binds the texture ... @mat + * + * @param texture {PIXI.Texture} the new texture + * @param location {number} the texture location + */ +WebGLRenderer.prototype.bindTexture = function (texture, location) +{ + texture = texture.baseTexture || texture; + + var gl = this.gl; + + //TODO test perf of cache? + location = location || 0; + + if(this._activeTextureLocation !== location)// + { + this._activeTextureLocation = location; + gl.activeTexture(gl.TEXTURE0 + location ); + } + + //TODO - can we cache this texture too? + this._activeTexture = texture; + + if (!texture._glTextures[this.CONTEXT_UID]) + { + // this will also bind the texture.. + this.textureManager.updateTexture(texture); + + } + else + { + texture.touched = this.textureGC.count; + // bind the current texture + texture._glTextures[this.CONTEXT_UID].bind(); + } + + return this; +}; + +WebGLRenderer.prototype.createVao = function () +{ + return new glCore.VertexArrayObject(this.gl, this.state.attribState); +}; + +/** + * Resets the WebGL state so you can render things however you fancy! + */ +WebGLRenderer.prototype.reset = function () +{ + this.setObjectRenderer(this.emptyRenderer); + + this._activeShader = null; + this._activeRenderTarget = this.rootRenderTarget; + this._activeTextureLocation = 999; + this._activeTexture = null; + + // bind the main frame buffer (the screen); + this.rootRenderTarget.activate(); + + this.state.resetToDefault(); + + return this; +}; + +/** + * Handles a lost webgl context + * + * @private + */ +WebGLRenderer.prototype.handleContextLost = function (event) +{ + event.preventDefault(); +}; + +/** + * Handles a restored webgl context + * + * @private + */ +WebGLRenderer.prototype.handleContextRestored = function () +{ + this._initContext(); + this.textureManager.removeAll(); +}; + +/** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. https://github.com/pixijs/pixi.js/issues/2233 + */ +WebGLRenderer.prototype.destroy = function (removeView) +{ + this.destroyPlugins(); + + // remove listeners + this.view.removeEventListener('webglcontextlost', this.handleContextLost); + this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); + + this.textureManager.destroy(); + + // call base destroy + SystemRenderer.prototype.destroy.call(this, removeView); + + this.uid = 0; + + // destroy the managers + this.maskManager.destroy(); + this.stencilManager.destroy(); + this.filterManager.destroy(); + + this.maskManager = null; + this.filterManager = null; + this.textureManager = null; + this.currentRenderer = null; + + this.handleContextLost = null; + this.handleContextRestored = null; + + this._contextOptions = null; + this.gl.useProgram(null); + + if(this.gl.getExtension('WEBGL_lose_context')) + { + this.gl.getExtension('WEBGL_lose_context').loseContext(); + } + + this.gl = null; + + // this = null; +}; + +},{"../../const":78,"../../utils":151,"../SystemRenderer":108,"./TextureGarbageCollector":114,"./TextureManager":115,"./WebGLState":117,"./managers/FilterManager":122,"./managers/MaskManager":123,"./managers/StencilManager":124,"./utils/ObjectRenderer":126,"./utils/RenderTarget":128,"./utils/mapWebGLDrawModesToPixi":131,"./utils/validateContext":132,"pixi-gl-core":7}],117:[function(require,module,exports){ +var mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); + +/** + * A WebGL state machines + * + * @memberof PIXI + * @class + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function WebGLState(gl) +{ + /** + * The current active state + * + * @member {Uint8Array} + */ + this.activeState = new Uint8Array(16); + + /** + * The default state + * + * @member {Uint8Array} + */ + this.defaultState = new Uint8Array(16); + + // default blend mode.. + this.defaultState[0] = 1; + + /** + * The current state index in the stack + * + * @member {number} + * @private + */ + this.stackIndex = 0; + + /** + * The stack holding all the different states + * + * @member {Array<*>} + * @private + */ + this.stack = []; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + this.attribState = {tempAttribState:new Array(this.maxAttribs), + attribState:new Array(this.maxAttribs)}; + + this.blendModes = mapWebGLBlendModesToPixi(gl); + + // check we have vao.. + this.nativeVaoExtension = ( + gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object') + ); +} + +/** + * Pushes a new active state + */ +WebGLState.prototype.push = function() +{ + // next state.. + var state = this.stack[++this.stackIndex]; + + if(!state) + { + state = this.stack[this.stackIndex] = new Uint8Array(16); + } + + // copy state.. + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) + { + this.activeState[i] = state[i]; + } +}; + +var BLEND = 0, + DEPTH_TEST = 1, + FRONT_FACE = 2, + CULL_FACE = 3, + BLEND_FUNC = 4; + +/** + * Pops a state out + */ +WebGLState.prototype.pop = function() +{ + var state = this.stack[--this.stackIndex]; + this.setState(state); +}; + +/** + * Sets the current state + * @param state {number} + */ +WebGLState.prototype.setState = function(state) +{ + this.setBlend(state[BLEND]); + this.setDepthTest(state[DEPTH_TEST]); + this.setFrontFace(state[FRONT_FACE]); + this.setCullFace(state[CULL_FACE]); + this.setBlendMode(state[BLEND_FUNC]); +}; + +/** + * Sets the blend mode ? @mat + * @param value {number} + */ +WebGLState.prototype.setBlend = function(value) +{ + if(this.activeState[BLEND] === value|0) { + return; + } + + this.activeState[BLEND] = value|0; + + var gl = this.gl; + + if(value) + { + gl.enable(gl.BLEND); + } + else + { + gl.disable(gl.BLEND); + } +}; + +/** + * Sets the blend mode ? @mat + * @param value {number} + */ +WebGLState.prototype.setBlendMode = function(value) +{ + if(value === this.activeState[BLEND_FUNC]) { + return; + } + + this.activeState[BLEND_FUNC] = value; + + this.gl.blendFunc(this.blendModes[value][0], this.blendModes[value][1]); +}; + +/** + * Sets the depth test @mat + * @param value {number} + */ +WebGLState.prototype.setDepthTest = function(value) +{ + if(this.activeState[DEPTH_TEST] === value|0) { + return; + } + + this.activeState[DEPTH_TEST] = value|0; + + var gl = this.gl; + + if(value) + { + gl.enable(gl.DEPTH_TEST); + } + else + { + gl.disable(gl.DEPTH_TEST); + } +}; + +/** + * Sets the depth test @mat + * @param value {number} + */ +WebGLState.prototype.setCullFace = function(value) +{ + if(this.activeState[CULL_FACE] === value|0) { + return; + } + + this.activeState[CULL_FACE] = value|0; + + var gl = this.gl; + + if(value) + { + gl.enable(gl.CULL_FACE); + } + else + { + gl.disable(gl.CULL_FACE); + } +}; + +/** + * Sets the depth test @mat + * @param value {number} + */ +WebGLState.prototype.setFrontFace = function(value) +{ + if(this.activeState[FRONT_FACE] === value|0) { + return; + } + + this.activeState[FRONT_FACE] = value|0; + + var gl = this.gl; + + if(value) + { + gl.frontFace(gl.CW); + } + else + { + gl.frontFace(gl.CCW); + } +}; + +/** + * Disables all the vaos in use + */ +WebGLState.prototype.resetAttributes = function() +{ + var i; + + for ( i = 0; i < this.attribState.tempAttribState.length; i++) { + this.attribState.tempAttribState[i] = 0; + } + + for ( i = 0; i < this.attribState.attribState.length; i++) { + this.attribState.attribState[i] = 0; + } + + var gl = this.gl; + + // im going to assume one is always active for performance reasons. + for (i = 1; i < this.maxAttribs; i++) + { + gl.disableVertexAttribArray(i); + } +}; + +//used +/** + * Resets all the logic and disables the vaos + */ +WebGLState.prototype.resetToDefault = function() +{ + + // unbind any VAO if they exist.. + if(this.nativeVaoExtension) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + + // reset all attributs.. + this.resetAttributes(); + + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) + { + this.activeState[i] = 32; + } + + var gl = this.gl; + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); + + + this.setState(this.defaultState); +}; + +module.exports = WebGLState; + +},{"./utils/mapWebGLBlendModesToPixi":130}],118:[function(require,module,exports){ +var extractUniformsFromSrc = require('./extractUniformsFromSrc'), + utils = require('../../../utils'), + CONST = require('../../../const'), + SOURCE_KEY_MAP = {}; + +// var math = require('../../../math'); +/** + * @class + * @memberof PIXI + * @extends PIXI.Shader + * @param [vertexSrc] {string} The source of the vertex shader. + * @param [uniforms] {object} Custom uniforms to use to augment the built-in ones. + * @param [fragmentSrc] {string} The source of the fragment shader. + */ +function Filter(vertexSrc, fragmentSrc, uniforms) +{ + + /** + * The vertex shader. + * + * @member {string} + */ + this.vertexSrc = vertexSrc || Filter.defaultVertexSrc; + + /** + * The fragment shader. + * + * @member {string} + */ + this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc; + + this.blendMode = CONST.BLEND_MODES.NORMAL; + + // pull out the vertex and shader uniforms if they are not specified.. + // currently this does not extract structs only default types + this.uniformData = uniforms || extractUniformsFromSrc( this.vertexSrc, this.fragmentSrc, 'projectionMatrix|uSampler'); + + this.uniforms = {}; + + for (var i in this.uniformData) + { + this.uniforms[i] = this.uniformData[i].value; + } + + // this is where we store shader references.. + // TODO we could cache this! + this.glShaders = []; + + // used for cacheing.. sure there is a better way! + if(!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) + { + SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = utils.uid(); + } + + this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]; + + /** + * The padding of the filter. Some filters require extra space to breath such as a blur. Increasing this will add extra width and height to the bounds of the object that the filter is applied to. + */ + this.padding = 4; + + /** + * The resolution of the filter. Setting this to be lower will lower the quality but increase the performance of the filter. + * @member {number} + */ + this.resolution = 1; + + /** + * If enabled is true the filter is applied, if false it will not. + * @member {boolean} + */ + this.enabled = true; +} + +// constructor +//Filter.prototype.constructor = Filter; +module.exports = Filter; + +// var tempMatrix = new math.Matrix(); + +Filter.prototype.apply = function(filterManager, input, output, clear) +{ + // --- // + // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); + + // do as you please! + + filterManager.applyFilter(this, input, output, clear); + + // or just do a regular render.. +}; + +/** + * The default vertex shader source + * + * @static + * @constant + */ +Filter.defaultVertexSrc = [ + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + + 'uniform mat3 projectionMatrix;', + 'uniform mat3 filterMatrix;', + + 'varying vec2 vTextureCoord;', + 'varying vec2 vFilterCoord;', + + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;', + ' vTextureCoord = aTextureCoord ;', + '}' +].join('\n'); + +/** + * The default fragment shader source + * + * @static + * @constant + */ +Filter.defaultFragmentSrc = [ + 'varying vec2 vTextureCoord;', + 'varying vec2 vFilterCoord;', + + 'uniform sampler2D uSampler;', + 'uniform sampler2D filterSampler;', + + 'void main(void){', + ' vec4 masky = texture2D(filterSampler, vFilterCoord);', + ' vec4 sample = texture2D(uSampler, vTextureCoord);', + ' vec4 color;', + ' if(mod(vFilterCoord.x, 1.0) > 0.5)', + ' {', + ' color = vec4(1.0, 0.0, 0.0, 1.0);', + ' }', + ' else', + ' {', + ' color = vec4(0.0, 1.0, 0.0, 1.0);', + ' }', + // ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', + ' gl_FragColor = mix(sample, masky, 0.5);', + ' gl_FragColor *= sample.a;', + '}' +].join('\n'); + +},{"../../../const":78,"../../../utils":151,"./extractUniformsFromSrc":119}],119:[function(require,module,exports){ +var defaultValue = require('pixi-gl-core').shader.defaultValue; + +function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) +{ + var vertUniforms = extractUniformsFromString(vertexSrc, mask); + var fragUniforms = extractUniformsFromString(fragmentSrc, mask); + + return Object.assign(vertUniforms, fragUniforms); +} + + +function extractUniformsFromString(string) +{ + var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea)$'); + + var uniforms = {}; + var nameSplit; + + + // clean the lines a little - remove extra spaces / teabs etc + // then split along ';' + var lines = string.replace(/\s+/g,' ') + .split(/\s*;\s*/); + + // loop through.. + for (var i = 0; i < lines.length; i++) + { + var line = lines[i].trim(); + + if(line.indexOf('uniform') > -1) + { + var splitLine = line.split(' '); + var type = splitLine[1]; + + var name = splitLine[2]; + var size = 1; + + if(name.indexOf('[') > -1) + { + // array! + nameSplit = name.split(/\[|\]/); + name = nameSplit[0]; + size *= Number(nameSplit[1]); + } + + if(!name.match(maskRegex)) + { + uniforms[name] = { + value:defaultValue(type, size), + name:name, + type:type + }; + } + } + } + + return uniforms; +} + +module.exports = extractUniformsFromSrc; + +},{"pixi-gl-core":7}],120:[function(require,module,exports){ +var math = require('../../../math'); + +/* + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// thia returns a matrix that will normalise map filter cords in the filter to screen space +var calculateScreenSpaceMatrix = function (outputMatrix, filterArea, textureSize) +{ + //var worldTransform = sprite.worldTransform.copy(math.Matrix.TEMP_MATRIX), + // var texture = {width:1136, height:700};//sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height ); + + mappedMatrix.scale( textureSize.width , textureSize.height ); + + return mappedMatrix; + +}; + +var calculateNormalizedScreenSpaceMatrix = function (outputMatrix, filterArea, textureSize) +{ + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height ); + + var translateScaleX = (textureSize.width / filterArea.width); + var translateScaleY = (textureSize.height / filterArea.height); + + mappedMatrix.scale( translateScaleX , translateScaleY ); + + return mappedMatrix; +}; + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +var calculateSpriteMatrix = function (outputMatrix, filterArea, textureSize, sprite) +{ + var worldTransform = sprite.worldTransform.copy(math.Matrix.TEMP_MATRIX), + texture = sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + // scale.. + var ratio = textureSize.height / textureSize.width; + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height ); + + mappedMatrix.scale(1 , ratio); + + var translateScaleX = (textureSize.width / texture.width); + var translateScaleY = (textureSize.height / texture.height); + + worldTransform.tx /= texture.width * translateScaleX; + + //this...? free beer for anyone who can explain why this makes sense! + worldTransform.ty /= texture.width * translateScaleX; + // worldTransform.ty /= texture.height * translateScaleY; + + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + + // apply inverse scale.. + mappedMatrix.scale(1 , 1/ratio); + + mappedMatrix.scale( translateScaleX , translateScaleY ); + + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; +}; + +module.exports = { + calculateScreenSpaceMatrix:calculateScreenSpaceMatrix, + calculateNormalizedScreenSpaceMatrix:calculateNormalizedScreenSpaceMatrix, + calculateSpriteMatrix:calculateSpriteMatrix +}; + +},{"../../../math":102}],121:[function(require,module,exports){ +var Filter = require('../Filter'), + math = require('../../../../math'); + +// @see https://github.com/substack/brfs/issues/25 + +/** + * The SpriteMaskFilter class + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + * @param sprite {PIXI.Sprite} the target sprite + */ +function SpriteMaskFilter(sprite) +{ + var maskMatrix = new math.Matrix(); + + Filter.call(this, + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n", + "#define GLSLIFY 1\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n original *= (masky.r * masky.a * alpha * clip);\n gl_FragColor = original;\n}\n" + ); + + sprite.renderable = false; + + this.maskSprite = sprite; + this.maskMatrix = maskMatrix; +} + +SpriteMaskFilter.prototype = Object.create(Filter.prototype); +SpriteMaskFilter.prototype.constructor = SpriteMaskFilter; +module.exports = SpriteMaskFilter; + +/** + * Applies the filter + * + * @param filterManager {PIXI.FilterManager} The renderer to retrieve the filter from + * @param input {PIXI.RenderTarget} + * @param output {PIXI.RenderTarget} + */ +SpriteMaskFilter.prototype.apply = function (filterManager, input, output) +{ + var maskSprite = this.maskSprite; + + this.uniforms.mask = maskSprite._texture; + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite ); + this.uniforms.alpha = maskSprite.worldAlpha; + + filterManager.applyFilter(this, input, output); +}; + +},{"../../../../math":102,"../Filter":118}],122:[function(require,module,exports){ + +var WebGLManager = require('./WebGLManager'), + RenderTarget = require('../utils/RenderTarget'), + Quad = require('../utils/Quad'), + math = require('../../../math'), + Shader = require('../../../Shader'), + filterTransforms = require('../filters/filterTransforms'), + bitTwiddle = require('bit-twiddle'); + +var FilterState = function() +{ + this.renderTarget = null; + this.sourceFrame = new math.Rectangle(); + this.destinationFrame = new math.Rectangle(); + this.filters = []; + this.target = null; + this.resolution = 1; +}; + + +/** + * @class + * @memberof PIXI + * @extends PIXI.WebGLManager + * @param renderer {PIXI.WebGLRenderer} The renderer this manager works for. + */ +function FilterManager(renderer) +{ + WebGLManager.call(this, renderer); + + this.gl = this.renderer.gl; + // know about sprites! + this.quad = new Quad(this.gl, renderer.state.attribState); + + this.shaderCache = {}; + // todo add default! + this.pool = {}; + + this.filterData = null; +} + +FilterManager.prototype = Object.create(WebGLManager.prototype); +FilterManager.prototype.constructor = FilterManager; +module.exports = FilterManager; + +FilterManager.prototype.pushFilter = function(target, filters) +{ + var renderer = this.renderer; + + var filterData = this.filterData; + + if(!filterData) + { + filterData = this.renderer._activeRenderTarget.filterStack; + + // add new stack + var filterState = new FilterState(); + filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; + filterState.renderTarget = renderer._activeRenderTarget; + + this.renderer._activeRenderTarget.filterData = filterData = { + index:0, + stack:[filterState] + }; + + this.filterData = filterData; + } + + // get the current filter state.. + var currentState = filterData.stack[++filterData.index]; + if(!currentState) + { + currentState = filterData.stack[filterData.index] = new FilterState(); + } + + // for now we go off the filter of the first resolution.. + var resolution = filters[0].resolution; + var padding = filters[0].padding; + var targetBounds = target.filterArea || target.getBounds(true); + var sourceFrame = currentState.sourceFrame; + var destinationFrame = currentState.destinationFrame; + + sourceFrame.x = ((targetBounds.x * resolution) | 0) / resolution; + sourceFrame.y = ((targetBounds.y * resolution) | 0) / resolution; + sourceFrame.width = ((targetBounds.width * resolution) | 0) / resolution; + sourceFrame.height = ((targetBounds.height * resolution) | 0) / resolution; + + if(filterData.stack[0].renderTarget.transform) + {//jshint ignore:line + + + } + else + { + sourceFrame.fit(filterData.stack[0].destinationFrame); + } + + // lets pplay the padding After we fit the element to the screen. + // this should stop the strange side effects that can occour when cropping to the edges + sourceFrame.pad(padding); + + + + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + + var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); + + currentState.target = target; + currentState.filters = filters; + currentState.resolution = resolution; + currentState.renderTarget = renderTarget; + + // bind the render taget to draw the shape in the top corner.. + + renderTarget.setFrame(destinationFrame, sourceFrame); + // bind the render target + renderer.bindRenderTarget(renderTarget); + + // clear the renderTarget + renderer.clear();//[0.5,0.5,0.5, 1.0]); +}; + +FilterManager.prototype.popFilter = function() +{ + var filterData = this.filterData; + + var lastState = filterData.stack[filterData.index-1]; + var currentState = filterData.stack[filterData.index]; + + this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); + + var filters = currentState.filters; + + if(filters.length === 1) + { + filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false); + this.freePotRenderTarget(currentState.renderTarget); + } + else + { + var flip = currentState.renderTarget; + var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, 1); + flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + for (var i = 0; i < filters.length-1; i++) + { + filters[i].apply(this, flip, flop, true); + + var t = flip; + flip = flop; + flop = t; + } + + filters[i].apply(this, flip, lastState.renderTarget, false); + + this.freePotRenderTarget(flip); + this.freePotRenderTarget(flop); + } + + filterData.index--; + + if(filterData.index === 0) + { + this.filterData = null; + } +}; + +FilterManager.prototype.applyFilter = function (filter, input, output, clear) +{ + var renderer = this.renderer; + var shader = filter.glShaders[renderer.CONTEXT_UID]; + + // cacheing.. + if(!shader) + { + if(filter.glShaderKey) + { + shader = this.shaderCache[filter.glShaderKey]; + + if(!shader) + { + shader = filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = new Shader(this.gl, filter.vertexSrc, filter.fragmentSrc); + } + } + else + { + shader = filter.glShaders[renderer.CONTEXT_UID] = new Shader(this.gl, filter.vertexSrc, filter.fragmentSrc); + } + + //TODO - this only needs to be done once? + this.quad.initVao(shader); + } + + renderer.bindRenderTarget(output); + + + + if(clear) + { + var gl = renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + renderer.clear();//[1, 1, 1, 1]); + gl.enable(gl.SCISSOR_TEST); + } + + // in case the render target is being masked using a scissor rect + if(output === renderer.maskManager.scissorRenderTarget) + { + renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); + } + + renderer.bindShader(shader); + + // this syncs the pixi filters uniforms with glsl uniforms + this.syncUniforms(shader, filter); + + // bind the input texture.. + input.texture.bind(0); + // when you manually bind a texture, please switch active texture location to it + renderer._activeTextureLocation = 0; + + renderer.state.setBlendMode( filter.blendMode ); + + this.quad.draw(); +}; + +// this returns a matrix that will normalise map filter cords in the filter to screen space +FilterManager.prototype.syncUniforms = function (shader, filter) +{ + var uniformData = filter.uniformData; + var uniforms = filter.uniforms; + + // 0 is reserverd for the pixi texture so we start at 1! + var textureCount = 1; + var currentState; + + if(shader.uniforms.data.filterArea) + { + currentState = this.filterData.stack[this.filterData.index]; + var filterArea = shader.uniforms.filterArea; + + filterArea[0] = currentState.renderTarget.size.width; + filterArea[1] = currentState.renderTarget.size.height; + filterArea[2] = currentState.sourceFrame.x; + filterArea[3] = currentState.sourceFrame.y; + + shader.uniforms.filterArea = filterArea; + } + + // use this to clamp displaced texture coords so they belong to filterArea + // see displacementFilter fragment shader for an example + if(shader.uniforms.data.filterClamp) + { + currentState = this.filterData.stack[this.filterData.index]; + var filterClamp = shader.uniforms.filterClamp; + + filterClamp[0] = 0.5 / currentState.renderTarget.size.width; + filterClamp[1] = 0.5 / currentState.renderTarget.size.height; + filterClamp[2] = (currentState.sourceFrame.width - 0.5) / currentState.renderTarget.size.width; + filterClamp[3] = (currentState.sourceFrame.height - 0.5) / currentState.renderTarget.size.height; + + shader.uniforms.filterClamp = filterClamp; + } + + var val; + //TODO Cacheing layer.. + for(var i in uniformData) + { + if(uniformData[i].type === 'sampler2D') + { + shader.uniforms[i] = textureCount; + + if(uniforms[i].baseTexture) + { + this.renderer.bindTexture(uniforms[i].baseTexture, textureCount); + } + else + { + // this is helpful as renderTargets can also be set. + // Although thinking about it, we could probably + // make the filter texture cache return a RenderTexture + // rather than a renderTarget + var gl = this.renderer.gl; + this.renderer._activeTextureLocation = gl.TEXTURE0 + textureCount; + gl.activeTexture(gl.TEXTURE0 + textureCount ); + uniforms[i].texture.bind(); + } + + textureCount++; + } + else if(uniformData[i].type === 'mat3') + { + // check if its pixi matrix.. + if(uniforms[i].a !== undefined) + { + shader.uniforms[i] = uniforms[i].toArray(true); + } + else + { + shader.uniforms[i] = uniforms[i]; + } + } + else if(uniformData[i].type === 'vec2') + { + //check if its a point.. + if(uniforms[i].x !== undefined) + { + val = shader.uniforms[i] || new Float32Array(2); + val[0] = uniforms[i].x; + val[1] = uniforms[i].y; + shader.uniforms[i] = val; + } + else + { + shader.uniforms[i] = uniforms[i]; + } + } + else if(uniformData[i].type === 'float') + { + if(shader.uniforms.data[i].value !== uniformData[i]) + { + shader.uniforms[i] = uniforms[i]; + } + } + else + { + shader.uniforms[i] = uniforms[i]; + } + } +}; + + +FilterManager.prototype.getRenderTarget = function(clear, resolution) +{ + var currentState = this.filterData.stack[this.filterData.index]; + var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution); + renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + return renderTarget; +}; + +FilterManager.prototype.returnRenderTarget = function(renderTarget) +{ + return this.freePotRenderTarget(renderTarget); +}; + +/* + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// thia returns a matrix that will normalise map filter cords in the filter to screen space +FilterManager.prototype.calculateScreenSpaceMatrix = function (outputMatrix) +{ + var currentState = this.filterData.stack[this.filterData.index]; + return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); +}; + +/** + * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea + * + * @param outputMatrix {PIXI.Matrix} + */ +FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function (outputMatrix) +{ + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); +}; + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +FilterManager.prototype.calculateSpriteMatrix = function (outputMatrix, sprite) +{ + var currentState = this.filterData.stack[this.filterData.index]; + return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); +}; + +FilterManager.prototype.destroy = function() +{ + this.shaderCache = []; + this.emptyPool(); +}; + + + +//TODO move to a seperate class could be on renderer? +//also - could cause issue with multiple contexts? +FilterManager.prototype.getPotRenderTarget = function(gl, minWidth, minHeight, resolution) +{ + //TODO you coud return a bigger texture if there is not one in the pool? + minWidth = bitTwiddle.nextPow2(minWidth * resolution); + minHeight = bitTwiddle.nextPow2(minHeight * resolution); + + var key = ((minWidth & 0xFFFF) << 16) | ( minHeight & 0xFFFF); + + if(!this.pool[key]) { + this.pool[key] = []; + } + + var renderTarget = this.pool[key].pop() || new RenderTarget(gl, minWidth, minHeight, null, 1); + + //manually tweak the resolution... + //this will not modify the size of the frame buffer, just its resolution. + renderTarget.resolution = resolution; + renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution; + renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution; + return renderTarget; +}; + +FilterManager.prototype.emptyPool = function() +{ + for (var i in this.pool) + { + var textures = this.pool[i]; + if(textures) + { + for (var j = 0; j < textures.length; j++) + { + textures[j].destroy(true); + } + } + } + + this.pool = {}; +}; + +FilterManager.prototype.freePotRenderTarget = function(renderTarget) +{ + var minWidth = renderTarget.size.width * renderTarget.resolution; + var minHeight = renderTarget.size.height * renderTarget.resolution; + + var key = ((minWidth & 0xFFFF) << 16) | (minHeight & 0xFFFF); + this.pool[key].push(renderTarget); +}; + +},{"../../../Shader":77,"../../../math":102,"../filters/filterTransforms":120,"../utils/Quad":127,"../utils/RenderTarget":128,"./WebGLManager":125,"bit-twiddle":30}],123:[function(require,module,exports){ +var WebGLManager = require('./WebGLManager'), + AlphaMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); + +/** + * @class + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} The renderer this manager works for. + */ +function MaskManager(renderer) +{ + WebGLManager.call(this, renderer); + + //TODO - we don't need both! + this.scissor = false; + this.scissorData = null; + this.scissorRenderTarget = null; + + this.enableScissor = true; + + this.alphaMaskPool = []; + this.alphaMaskIndex = 0; +} + +MaskManager.prototype = Object.create(WebGLManager.prototype); +MaskManager.prototype.constructor = MaskManager; +module.exports = MaskManager; + +/** + * Applies the Mask and adds it to the current filter stack. + * + * @param target {PIXI.DisplayObject} Display Object to push the mask to + * @param maskData {PIXI.Sprite|PIXI.Graphics} + */ +MaskManager.prototype.pushMask = function (target, maskData) +{ + if (maskData.texture) + { + this.pushSpriteMask(target, maskData); + } + else + { + if(this.enableScissor && !this.scissor && !this.renderer.stencilManager.stencilMaskStack.length && maskData.isFastRect()) + { + var matrix = maskData.worldTransform; + + var rot = Math.atan2(matrix.b, matrix.a); + + // use the nearest degree! + rot = Math.round(rot * (180/Math.PI)); + + if(rot % 90) + { + this.pushStencilMask(maskData); + } + else + { + this.pushScissorMask(target, maskData); + } + } + else + { + this.pushStencilMask(maskData); + } + } +}; + +/** + * Removes the last mask from the mask stack and doesn't return it. + * + * @param target {PIXI.DisplayObject} Display Object to pop the mask from + * @param maskData {Array<*>} + */ +MaskManager.prototype.popMask = function (target, maskData) +{ + if (maskData.texture) + { + this.popSpriteMask(target, maskData); + } + else + { + if(this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length) + { + this.popScissorMask(target, maskData); + } + else + { + this.popStencilMask(target, maskData); + } + + } +}; + +/** + * Applies the Mask and adds it to the current filter stack. + * + * @param target {PIXI.RenderTarget} Display Object to push the sprite mask to + * @param maskData {PIXI.Sprite} Sprite to be used as the mask + */ +MaskManager.prototype.pushSpriteMask = function (target, maskData) +{ + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + + if (!alphaMaskFilter) + { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new AlphaMaskFilter(maskData)]; + } + + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskData; + + //TODO - may cause issues! + target.filterArea = maskData.getBounds(true); + + this.renderer.filterManager.pushFilter(target, alphaMaskFilter); + + this.alphaMaskIndex++; +}; + +/** + * Removes the last filter from the filter stack and doesn't return it. + * + */ +MaskManager.prototype.popSpriteMask = function () +{ + this.renderer.filterManager.popFilter(); + this.alphaMaskIndex--; +}; + + +/** + * Applies the Mask and adds it to the current filter stack. + * + * @param maskData {Array<*>} + */ +MaskManager.prototype.pushStencilMask = function (maskData) +{ + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.pushStencil(maskData); +}; + +/** + * Removes the last filter from the filter stack and doesn't return it. + * + */ +MaskManager.prototype.popStencilMask = function () +{ + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.popStencil(); +}; + +/** + * + * @param target {PIXI.RenderTarget} Display Object to push the scissor mask to + * @param maskData + */ +MaskManager.prototype.pushScissorMask = function (target, maskData) +{ + maskData.renderable = true; + + var renderTarget = this.renderer._activeRenderTarget; + + var bounds = maskData.getBounds(); + + bounds.fit(renderTarget.size); + maskData.renderable = false; + + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + + var resolution = this.renderer.resolution; + this.renderer.gl.scissor(bounds.x * resolution, + (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution, + bounds.width * resolution, + bounds.height * resolution); + + this.scissorRenderTarget = renderTarget; + this.scissorData = maskData; + this.scissor = true; +}; + +/** + * + * + */ +MaskManager.prototype.popScissorMask = function () +{ + this.scissorRenderTarget = null; + this.scissorData = null; + this.scissor = false; + + // must be scissor! + var gl = this.renderer.gl; + gl.disable(gl.SCISSOR_TEST); +}; + +},{"../filters/spriteMask/SpriteMaskFilter":121,"./WebGLManager":125}],124:[function(require,module,exports){ +var WebGLManager = require('./WebGLManager'); + +/** + * @class + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} The renderer this manager works for. + */ +function StencilManager(renderer) +{ + WebGLManager.call(this, renderer); + this.stencilMaskStack = null; +} + +StencilManager.prototype = Object.create(WebGLManager.prototype); +StencilManager.prototype.constructor = StencilManager; +module.exports = StencilManager; + +/** + * Changes the mask stack that is used by this manager. + * + * @param stencilMaskStack {PIXI.Graphics[]} The mask stack + */ +StencilManager.prototype.setMaskStack = function ( stencilMaskStack ) +{ + this.stencilMaskStack = stencilMaskStack; + + var gl = this.renderer.gl; + + if (stencilMaskStack.length === 0) + { + gl.disable(gl.STENCIL_TEST); + } + else + { + gl.enable(gl.STENCIL_TEST); + } +}; + +/** + * Applies the Mask and adds it to the current filter stack. @alvin + * + * @param graphics {PIXI.Graphics} + */ +StencilManager.prototype.pushStencil = function (graphics) +{ + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + this.renderer._activeRenderTarget.attachStencilBuffer(); + + var gl = this.renderer.gl, + sms = this.stencilMaskStack; + + if (sms.length === 0) + { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.stencilFunc(gl.ALWAYS,1,1); + } + + sms.push(graphics); + + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL,0, sms.length); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); +}; + +/** + * TODO @alvin + */ +StencilManager.prototype.popStencil = function () +{ + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + var gl = this.renderer.gl, + sms = this.stencilMaskStack; + + var graphics = sms.pop(); + + if (sms.length === 0) + { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + } + else + { + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + } +}; + +/** + * Destroys the mask stack. + * + */ +StencilManager.prototype.destroy = function () +{ + WebGLManager.prototype.destroy.call(this); + + this.stencilMaskStack.stencilStack = null; +}; + +},{"./WebGLManager":125}],125:[function(require,module,exports){ +/** + * @class + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} The renderer this manager works for. + */ +function WebGLManager(renderer) +{ + /** + * The renderer this manager works for. + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + this.renderer.on('context', this.onContextChange, this); +} + +WebGLManager.prototype.constructor = WebGLManager; +module.exports = WebGLManager; + +/** + * Generic method called when there is a WebGL context change. + * + */ +WebGLManager.prototype.onContextChange = function () +{ + // do some codes init! +}; + +/** + * Generic destroy methods to be overridden by the subclass + * + */ +WebGLManager.prototype.destroy = function () +{ + this.renderer.off('context', this.onContextChange, this); + + this.renderer = null; +}; + +},{}],126:[function(require,module,exports){ +var WebGLManager = require('../managers/WebGLManager'); + +/** + * Base for a common object renderer that can be used as a system renderer plugin. + * + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} The renderer this object renderer works for. + */ +function ObjectRenderer(renderer) +{ + WebGLManager.call(this, renderer); +} + + +ObjectRenderer.prototype = Object.create(WebGLManager.prototype); +ObjectRenderer.prototype.constructor = ObjectRenderer; +module.exports = ObjectRenderer; + +/** + * Starts the renderer and sets the shader + * + */ +ObjectRenderer.prototype.start = function () +{ + // set the shader.. +}; + +/** + * Stops the renderer + * + */ +ObjectRenderer.prototype.stop = function () +{ + this.flush(); +}; + +/** + * Stub method for rendering content and emptying the current batch. + * + */ +ObjectRenderer.prototype.flush = function () +{ + // flush! +}; + +/** + * Renders an object + * + * @param object {PIXI.DisplayObject} The object to render. + */ +ObjectRenderer.prototype.render = function (object) // jshint unused:false +{ + // render the object +}; + +},{"../managers/WebGLManager":125}],127:[function(require,module,exports){ +var glCore = require('pixi-gl-core'), + createIndicesForQuads = require('../../../utils/createIndicesForQuads'); + +/** + * Helper class to create a quad + * + * @class + * @memberof PIXI + * @param gl {WebGLRenderingContext} The gl context for this quad to use. + * @param state {object} TODO: Description + */ +function Quad(gl, state) +{ + /* + * the current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = new Float32Array([ + -1,-1, + 1,-1, + 1,1, + -1,1 + ]); + + /** + * The Uvs of the quad + * + * @member {Float32Array} + */ + this.uvs = new Float32Array([ + 0,0, + 1,0, + 1,1, + 0,1 + ]); + + this.interleaved = new Float32Array(8 * 2); + + for (var i = 0; i < 4; i++) { + this.interleaved[i*4] = this.vertices[(i*2)]; + this.interleaved[(i*4)+1] = this.vertices[(i*2)+1]; + this.interleaved[(i*4)+2] = this.uvs[i*2]; + this.interleaved[(i*4)+3] = this.uvs[(i*2)+1]; + } + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + this.indices = createIndicesForQuads(1); + + /* + * @member {glCore.GLBuffer} The vertex buffer + */ + this.vertexBuffer = glCore.GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW); + + /* + * @member {glCore.GLBuffer} The index buffer + */ + this.indexBuffer = glCore.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + /* + * @member {glCore.VertexArrayObject} The index buffer + */ + this.vao = new glCore.VertexArrayObject(gl, state); + +} + +Quad.prototype.constructor = Quad; + +/** + * Initialises the vaos and uses the shader + * @param shader {PIXI.Shader} the shader to use + */ +Quad.prototype.initVao = function(shader) +{ + this.vao.clear() + .addIndex(this.indexBuffer) + .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) + .addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4); +}; + +/** + * Maps two Rectangle to the quad + * @param targetTextureFrame {PIXI.Rectangle} the first rectangle + * @param destinationFrame {PIXI.Rectangle} the second rectangle + */ +Quad.prototype.map = function(targetTextureFrame, destinationFrame) +{ + var x = 0; //destinationFrame.x / targetTextureFrame.width; + var y = 0; //destinationFrame.y / targetTextureFrame.height; + + this.uvs[0] = x; + this.uvs[1] = y; + + this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; + + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; + + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; + + /// ----- + x = destinationFrame.x; + y = destinationFrame.y; + + this.vertices[0] = x; + this.vertices[1] = y; + + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + + return this; +}; + +/** + * Draws the quad + */ +Quad.prototype.draw = function() +{ + this.vao.bind() + .draw(this.gl.TRIANGLES, 6, 0) + .unbind(); + + return this; +}; + +/** + * Binds the buffer and uploads the data + */ +Quad.prototype.upload = function() +{ + for (var i = 0; i < 4; i++) { + this.interleaved[i*4] = this.vertices[(i*2)]; + this.interleaved[(i*4)+1] = this.vertices[(i*2)+1]; + this.interleaved[(i*4)+2] = this.uvs[i*2]; + this.interleaved[(i*4)+3] = this.uvs[(i*2)+1]; + } + + this.vertexBuffer.upload(this.interleaved); + + return this; +}; + +/** + * Removes this quad from WebGL + */ +Quad.prototype.destroy = function() +{ + var gl = this.gl; + + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.indexBuffer); +}; + +module.exports = Quad; + +},{"../../../utils/createIndicesForQuads":149,"pixi-gl-core":7}],128:[function(require,module,exports){ +var math = require('../../../math'), + CONST = require('../../../const'), + GLFramebuffer = require('pixi-gl-core').GLFramebuffer; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @class + * @memberof PIXI + * @param gl {WebGLRenderingContext} the current WebGL drawing context + * @param [width=0] {number} the horizontal range of the filter + * @param [height=0] {number} the vertical range of the filter + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @param [resolution=1] {number} The current resolution / device pixel ratio + * @param [root=false] {boolean} Whether this object is the root element or not + */ +var RenderTarget = function(gl, width, height, scaleMode, resolution, root) +{ + //TODO Resolution could go here ( eg low res blurs ) + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // next time to create a frame buffer and texture + + /** + * A frame buffer + * + * @member {PIXI.glCore.GLFramebuffer} + */ + this.frameBuffer = null; + + /** + * The texture + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The background colour of this render target, as an array of [r,g,b,a] values + * + * @member {number[]} + */ + this.clearColor = [0, 0, 0, 0]; + + /** + * The size of the object as a rectangle + * + * @member {PIXI.Rectangle} + */ + this.size = new math.Rectangle(0, 0, 1, 1); + + /** + * The current resolution / device pixel ratio + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || CONST.RESOLUTION; + + /** + * The projection matrix + * + * @member {PIXI.Matrix} + */ + this.projectionMatrix = new math.Matrix(); + + /** + * The object's transform + * + * @member {PIXI.Matrix} + */ + this.transform = null; + + /** + * The frame. + * + * @member {PIXI.Rectangle} + */ + this.frame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.defaultFrame = new math.Rectangle(); + this.destinationFrame = null; + this.sourceFrame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.stencilBuffer = null; + + /** + * The data structure for the stencil masks + * + * @member {PIXI.Graphics[]} + */ + this.stencilMaskStack = []; + + /** + * Stores filter data for the render target + * + * @member {object[]} + */ + this.filterData = null; + + /** + * The scale mode. + * + * @member {number} + * @default PIXI.SCALE_MODES.DEFAULT + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode || CONST.SCALE_MODES.DEFAULT; + + /** + * Whether this object is the root element or not + * + * @member {boolean} + */ + this.root = root; + + + if (!this.root) + { + this.frameBuffer = GLFramebuffer.createRGBA(gl, 100, 100); + + if( this.scaleMode === CONST.SCALE_MODES.NEAREST) + { + this.frameBuffer.texture.enableNearestScaling(); + } + else + { + this.frameBuffer.texture.enableLinearScaling(); + + } + /* + A frame buffer needs a target to render to.. + create a texture and bind it attach it to the framebuffer.. + */ + + // this is used by the base texture + this.texture = this.frameBuffer.texture; + } + else + { + // make it a null framebuffer.. + this.frameBuffer = new GLFramebuffer(gl, 100, 100); + this.frameBuffer.framebuffer = null; + + } + + this.setFrame(); + + this.resize(width, height); +}; + +RenderTarget.prototype.constructor = RenderTarget; +module.exports = RenderTarget; + +/** + * Clears the filter texture. + * + * @param [clearColor=this.clearColor] {number[]} Array of [r,g,b,a] to clear the framebuffer + */ +RenderTarget.prototype.clear = function(clearColor) +{ + var cc = clearColor || this.clearColor; + this.frameBuffer.clear(cc[0],cc[1],cc[2],cc[3]);//r,g,b,a); +}; + +/** + * Binds the stencil buffer. + * + */ +RenderTarget.prototype.attachStencilBuffer = function() +{ + //TODO check if stencil is done? + /** + * The stencil buffer is used for masking in pixi + * lets create one and then add attach it to the framebuffer.. + */ + if (!this.root) + { + this.frameBuffer.enableStencil(); + } +}; + +RenderTarget.prototype.setFrame = function(destinationFrame, sourceFrame) +{ + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; +}; + +/** + * Binds the buffers and initialises the viewport. + * + */ +RenderTarget.prototype.activate = function() +{ + //TOOD refactor usage of frame.. + var gl = this.gl; + + // make surethe texture is unbound! + this.frameBuffer.bind(); + + this.calculateProjection( this.destinationFrame, this.sourceFrame ); + + if(this.transform) + { + this.projectionMatrix.append(this.transform); + } + + //TODO add a check as them may be the same! + if(this.destinationFrame !== this.sourceFrame) + { + + gl.enable(gl.SCISSOR_TEST); + gl.scissor(this.destinationFrame.x | 0,this.destinationFrame.y | 0, (this.destinationFrame.width * this.resolution) | 0, (this.destinationFrame.height* this.resolution) | 0); + } + else + { + gl.disable(gl.SCISSOR_TEST); + } + + + // TODO - does not need to be updated all the time?? + gl.viewport(this.destinationFrame.x | 0,this.destinationFrame.y | 0, (this.destinationFrame.width * this.resolution) | 0, (this.destinationFrame.height * this.resolution)|0); + + +}; + + +/** + * Updates the projection matrix based on a projection frame (which is a rectangle) + * + */ +RenderTarget.prototype.calculateProjection = function (destinationFrame, sourceFrame) +{ + var pm = this.projectionMatrix; + + sourceFrame = sourceFrame || destinationFrame; + + pm.identity(); + + // TODO: make dest scale source + if (!this.root) + { + pm.a = 1 / destinationFrame.width*2; + pm.d = 1 / destinationFrame.height*2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = -1 - sourceFrame.y * pm.d; + } + else + { + pm.a = 1 / destinationFrame.width*2; + pm.d = -1 / destinationFrame.height*2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = 1 - sourceFrame.y * pm.d; + } +}; + + +/** + * Resizes the texture to the specified width and height + * + * @param width {Number} the new width of the texture + * @param height {Number} the new height of the texture + */ +RenderTarget.prototype.resize = function (width, height) +{ + width = width | 0; + height = height | 0; + + if (this.size.width === width && this.size.height === height) + { + return; + } + + this.size.width = width; + this.size.height = height; + + this.defaultFrame.width = width; + this.defaultFrame.height = height; + + + this.frameBuffer.resize(width * this.resolution, height * this.resolution); + + var projectionFrame = this.frame || this.size; + + this.calculateProjection( projectionFrame ); +}; + +/** + * Destroys the render target. + * + */ +RenderTarget.prototype.destroy = function () +{ + this.frameBuffer.destroy(); + + this.frameBuffer = null; + this.texture = null; +}; + +},{"../../../const":78,"../../../math":102,"pixi-gl-core":7}],129:[function(require,module,exports){ +var glCore = require('pixi-gl-core'); + +var fragTemplate = [ + 'precision mediump float;', + 'void main(void){', + 'float test = 0.1;', + '%forloop%', + 'gl_FragColor = vec4(0.0);', + '}' +].join('\n'); + +var checkMaxIfStatmentsInShader = function(maxIfs, gl) +{ + var createTempContext = !gl; + + if(createTempContext) + { + var tinyCanvas = document.createElement('canvas'); + tinyCanvas.width = 1; + tinyCanvas.height = 1; + + gl = glCore.createContext(tinyCanvas); + } + + var shader = gl.createShader(gl.FRAGMENT_SHADER); + + while(true) + { + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + + if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + maxIfs = (maxIfs/2)|0; + } + else + { + // valid! + break; + } + } + + if(createTempContext) + { + // get rid of context + if(gl.getExtension('WEBGL_lose_context')) + { + gl.getExtension('WEBGL_lose_context').loseContext(); + } + } + + return maxIfs; +}; + + + +function generateIfTestSrc(maxIfs) +{ + var src = ''; + + for (var i = 0; i < maxIfs; i++) + { + if(i > 0) + { + src += '\nelse '; + } + + if(i < maxIfs-1) + { + src += 'if(test == ' + i + '.0){}'; + } + } + + return src; +} + +module.exports = checkMaxIfStatmentsInShader; + +},{"pixi-gl-core":7}],130:[function(require,module,exports){ +var CONST = require('../../../const'); + +/** + * Maps gl blend combinations to WebGL + * @class + * @memberof PIXI + * @param gl {WebGLRenderingContext} The current WebGL drawing context + * @param array + */ +function mapWebGLBlendModesToPixi(gl, array) +{ + array = array || []; + + //TODO - premultiply alpha would be different. + //add a boolean for that! + array[CONST.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.ADD] = [gl.ONE, gl.DST_ALPHA]; + array[CONST.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + array[CONST.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + return array; +} + +module.exports = mapWebGLBlendModesToPixi; + +},{"../../../const":78}],131:[function(require,module,exports){ +var CONST = require('../../../const'); + +/** + * Generic Mask Stack data structure + * @class + * @memberof PIXI + * @param gl {WebGLRenderingContext} The current WebGL drawing context + * @param object + */ +function mapWebGLDrawModesToPixi(gl, object) +{ + object= object || {}; + + object[CONST.DRAW_MODES.POINTS] = gl.POINTS; + object[CONST.DRAW_MODES.LINES] = gl.LINES; + object[CONST.DRAW_MODES.LINE_LOOP] = gl.LINE_LOOP; + object[CONST.DRAW_MODES.LINE_STRIP] = gl.LINE_STRIP; + object[CONST.DRAW_MODES.TRIANGLES] = gl.TRIANGLES; + object[CONST.DRAW_MODES.TRIANGLE_STRIP] = gl.TRIANGLE_STRIP; + object[CONST.DRAW_MODES.TRIANGLE_FAN] = gl.TRIANGLE_FAN; + +} + +module.exports = mapWebGLDrawModesToPixi; + +},{"../../../const":78}],132:[function(require,module,exports){ + + +function validateContext(gl) +{ + var attributes = gl.getContextAttributes(); + + // this is going to be fairly simple for now.. but at least we have rom to grow! + if(!attributes.stencil) + { + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); // jshint ignore:line + } +} + +module.exports = validateContext; + +},{}],133:[function(require,module,exports){ +var math = require('../math'), + Texture = require('../textures/Texture'), + Container = require('../display/Container'), + utils = require('../utils'), + CONST = require('../const'), + tempPoint = new math.Point(); + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * var sprite = new PIXI.Sprite.fromImage('assets/image.png'); + * ``` + * + * @class + * @extends PIXI.Container + * @memberof PIXI + * @param texture {PIXI.Texture} The texture for this sprite + */ +function Sprite(texture) +{ + Container.call(this); + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + */ + this.anchor = new math.ObservablePoint(this.onAnchorUpdate, this); + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + * @private + */ + this._texture = null; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @member {number} + * @private + */ + this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @member {number} + * @private + */ + this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + this._tint = null; + this._tintRGB = null; + this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + this.blendMode = CONST.BLEND_MODES.NORMAL; + + /** + * The shader that will be used to render the sprite. Set to null to remove a current shader. + * + * @member {PIXI.AbstractFilter|PIXI.Shader} + */ + this.shader = null; + + /** + * An internal cached value of the tint. + * + * @member {number} + * @default 0xFFFFFF + * @private + */ + this.cachedTint = 0xFFFFFF; + + // call texture setter + this.texture = texture || Texture.EMPTY; + + /** + * this is used to store the vertex data of the sprite (basically a quad) + * @type {Float32Array} + */ + this.vertexData = new Float32Array(8); + + /** + * this is used to calculate the bounds of the object IF it is a trimmed sprite + * @type {Float32Array} + */ + this.vertexTrimmedData = null; + + this._transformID = -1; + this._textureID = -1; +} + +// constructor +Sprite.prototype = Object.create(Container.prototype); +Sprite.prototype.constructor = Sprite; +module.exports = Sprite; + +Object.defineProperties(Sprite.prototype, { + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Sprite# + */ + width: { + get: function () + { + return Math.abs(this.scale.x) * this.texture.orig.width; + }, + set: function (value) + { + var sign = utils.sign(this.scale.x) || 1; + this.scale.x = sign * value / this.texture.orig.width; + this._width = value; + } + }, + + /** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Sprite# + */ + height: { + get: function () + { + return Math.abs(this.scale.y) * this.texture.orig.height; + }, + set: function (value) + { + var sign = utils.sign(this.scale.y) || 1; + this.scale.y = sign * value / this.texture.orig.height; + this._height = value; + } + }, + + tint: { + get: function () + { + return this._tint; + }, + set: function (value) + { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + } + }, + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + * @memberof PIXI.Sprite# + */ + texture: { + get: function () + { + return this._texture; + }, + set: function (value) + { + if (this._texture === value) + { + return; + } + + this._texture = value; + this.cachedTint = 0xFFFFFF; + + this._textureID = -1; + + if (value) + { + // wait for the texture to load + if (value.baseTexture.hasLoaded) + { + this._onTextureUpdate(); + } + else + { + value.once('update', this._onTextureUpdate, this); + } + } + } + } +}); + +/** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ +Sprite.prototype._onTextureUpdate = function () +{ + this._textureID = -1; + + // so if _width is 0 then width was not set.. + if (this._width) + { + this.scale.x = utils.sign(this.scale.x) * this._width / this.texture.orig.width; + } + + if (this._height) + { + this.scale.y = utils.sign(this.scale.y) * this._height / this.texture.orig.height; + } +}; + +Sprite.prototype.onAnchorUpdate = function() +{ + this._transformID = -1; +}; + +/** + * calculates worldTransform * vertices, store it in vertexData + */ +Sprite.prototype.calculateVertices = function () +{ + if(this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) + { + return; + } + + this._transformID = this.transform._worldID; + this._textureID = this._texture._updateID; + + // set the vertex data + + var texture = this._texture, + wt = this.transform.worldTransform, + a = wt.a, b = wt.b, c = wt.c, d = wt.d, tx = wt.tx, ty = wt.ty, + vertexData = this.vertexData, + w0, w1, h0, h1, + trim = texture.trim, + orig = texture.orig; + + if (trim) + { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra space before transforming the sprite coords.. + w1 = trim.x - this.anchor._x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - this.anchor._y * orig.height; + h0 = h1 + trim.height; + + } + else + { + w0 = orig.width * (1-this.anchor._x); + w1 = orig.width * -this.anchor._x; + + h0 = orig.height * (1-this.anchor._y); + h1 = orig.height * -this.anchor._y; + } + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; +}; + +/** + * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData + * This is used to ensure that the true width and height of a trimmed texture is respected + */ +Sprite.prototype.calculateTrimmedVertices = function () +{ + if(!this.vertexTrimmedData) + { + this.vertexTrimmedData = new Float32Array(8); + } + + // lets do some special trim code! + var texture = this._texture, + vertexData = this.vertexTrimmedData, + orig = texture.orig; + + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform, + a = wt.a, b = wt.b, c = wt.c, d = wt.d, tx = wt.tx, ty = wt.ty, + w0, w1, h0, h1; + + w0 = (orig.width ) * (1-this.anchor._x); + w1 = (orig.width ) * -this.anchor._x; + + h0 = orig.height * (1-this.anchor._y); + h1 = orig.height * -this.anchor._y; + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; +}; + +/** +* +* Renders the object using the WebGL renderer +* +* @param renderer {PIXI.WebGLRenderer} +* @private +*/ +Sprite.prototype._renderWebGL = function (renderer) +{ + this.calculateVertices(); + + renderer.setObjectRenderer(renderer.plugins.sprite); + renderer.plugins.sprite.render(this); +}; + +/** +* Renders the object using the Canvas renderer +* +* @param renderer {PIXI.CanvasRenderer} The renderer +* @private +*/ +Sprite.prototype._renderCanvas = function (renderer) +{ + renderer.plugins.sprite.render(this); +}; + + +Sprite.prototype._calculateBounds = function () +{ + + var trim = this._texture.trim, + orig = this._texture.orig; + + //First lets check to see if the current texture has a trim.. + if (!trim || trim.width === orig.width && trim.height === orig.height) { + + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } + else + { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } +}; + +/** + * Gets the local bounds of the sprite object. + * + */ + +Sprite.prototype.getLocalBounds = function (rect) +{ + // we can do a fast local bounds if the sprite has no children! + if(this.children.length === 0) + { + + this._bounds.minX = -this._texture.orig.width * this.anchor._x; + this._bounds.minY = -this._texture.orig.height * this.anchor._y; + this._bounds.maxX = this._texture.orig.width; + this._bounds.maxY = this._texture.orig.height; + + if(!rect) + { + if(!this._localBoundsRect) + { + this._localBoundsRect = new math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + else + { + return Container.prototype.getLocalBounds.call(this, rect); + } + +}; + +/** +* Tests if a point is inside this sprite +* +* @param point {PIXI.Point} the point to test +* @return {boolean} the result of the test +*/ +Sprite.prototype.containsPoint = function( point ) +{ + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1; + + if ( tempPoint.x > x1 && tempPoint.x < x1 + width ) + { + y1 = -height * this.anchor.y; + + if ( tempPoint.y > y1 && tempPoint.y < y1 + height ) + { + return true; + } + } + + return false; +}; + + +/** + * Destroys this sprite and optionally its texture and children + * + * @param [options] {object|boolean} Options parameter. A boolean will act as if all options have been set to that value + * @param [options.children=false] {boolean} if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param [options.texture=false] {boolean} Should it destroy the current texture of the sprite as well + * @param [options.baseTexture=false] {boolean} Should it destroy the base texture of the sprite as well + */ +Sprite.prototype.destroy = function (options) +{ + Container.prototype.destroy.call(this, options); + + this.anchor = null; + + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + if (destroyTexture) + { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + this._texture.destroy(!!destroyBaseTexture); + } + + this._texture = null; + this.shader = null; +}; + +// some helper functions.. + +/** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ +Sprite.from = function (source) +{ + return new Sprite(Texture.from(source)); +}; + +/** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param frameId {string} The frame Id of the texture in the cache + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId + */ +Sprite.fromFrame = function (frameId) +{ + var texture = utils.TextureCache[frameId]; + + if (!texture) + { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return new Sprite(texture); +}; + +/** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param imageId {string} The image url of the texture + * @param [crossorigin=(auto)] {boolean} if you want to specify the cross-origin parameter + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} if you want to specify the scale mode, see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id + */ +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ + return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); +}; + +},{"../const":78,"../display/Container":80,"../math":102,"../textures/Texture":144,"../utils":151}],134:[function(require,module,exports){ +var CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'), + CONST = require('../../const'), + math = require('../../math'), + canvasRenderWorldTransform = new math.Matrix(), + CanvasTinter = require('./CanvasTinter'); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasSpriteRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + * @param renderer {PIXI.WebGLRenderer} The renderer sprite this batch works for. + */ +function CanvasSpriteRenderer(renderer) +{ + this.renderer = renderer; +} + + +CanvasSpriteRenderer.prototype.constructor = CanvasSpriteRenderer; +module.exports = CanvasSpriteRenderer; + +CanvasRenderer.registerPlugin('sprite', CanvasSpriteRenderer); + +/** + * Renders the sprite object. + * + * @param sprite {PIXI.Sprite} the sprite to render when using this spritebatch + */ +CanvasSpriteRenderer.prototype.render = function (sprite) +{ + var texture = sprite._texture, + renderer = this.renderer, + wt = sprite.transform.worldTransform, + dx, + dy, + width = texture._frame.width, + height = texture._frame.height; + + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) + { + return; + } + + renderer.setBlendMode(sprite.blendMode); + + // Ignore null sources + if (texture.valid) + { + renderer.context.globalAlpha = sprite.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture + var smoothingEnabled = texture.baseTexture.scaleMode === CONST.SCALE_MODES.LINEAR; + if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) + { + renderer.context[renderer.smoothProperty] = smoothingEnabled; + } + + if (texture.trim) { + dx = texture.trim.width/2 + texture.trim.x - sprite.anchor.x * texture.orig.width; + dy = texture.trim.height/2 + texture.trim.y - sprite.anchor.y * texture.orig.height; + } else { + dx = (0.5 - sprite.anchor.x) * texture.orig.width; + dy = (0.5 - sprite.anchor.y) * texture.orig.height; + } + if(texture.rotate) { + wt.copy(canvasRenderWorldTransform); + wt = canvasRenderWorldTransform; + math.GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); + // the anchor has already been applied above, so lets set it to zero + dx = 0; + dy = 0; + } + dx -= width/2; + dy -= height/2; + // Allow for pixel rounding + if (renderer.roundPixels) + { + renderer.context.setTransform( + wt.a, + wt.b, + wt.c, + wt.d, + (wt.tx * renderer.resolution) | 0, + (wt.ty * renderer.resolution) | 0 + ); + + dx = dx | 0; + dy = dy | 0; + } + else + { + renderer.context.setTransform( + wt.a, + wt.b, + wt.c, + wt.d, + wt.tx * renderer.resolution, + wt.ty * renderer.resolution + ); + } + + var resolution = texture.baseTexture.resolution; + + if (sprite.tint !== 0xFFFFFF) + { + if (sprite.cachedTint !== sprite.tint) + { + sprite.cachedTint = sprite.tint; + + // TODO clean up caching - how to clean up the caches? + sprite.tintedTexture = CanvasTinter.getTintedTexture(sprite, sprite.tint); + } + + renderer.context.drawImage( + sprite.tintedTexture, + 0, + 0, + width * resolution, + height * resolution, + dx * renderer.resolution, + dy * renderer.resolution, + width * renderer.resolution, + height * renderer.resolution + ); + } + else + { + + renderer.context.drawImage( + texture.baseTexture.source, + texture._frame.x * resolution, + texture._frame.y * resolution, + width * resolution, + height * resolution, + dx * renderer.resolution, + dy * renderer.resolution, + width * renderer.resolution, + height * renderer.resolution + ); + } + } +}; + +/** + * destroy the sprite object. + * + */ +CanvasSpriteRenderer.prototype.destroy = function (){ + this.renderer = null; +}; + +},{"../../const":78,"../../math":102,"../../renderers/canvas/CanvasRenderer":109,"./CanvasTinter":135}],135:[function(require,module,exports){ +var utils = require('../../utils'), + canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); + +/** + * Utility methods for Sprite/Texture tinting. + * + * @namespace PIXI.CanvasTinter + */ +var CanvasTinter = module.exports = { + /** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @memberof PIXI.CanvasTinter + * @param sprite {PIXI.Sprite} the sprite to tint + * @param color {number} the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ + getTintedTexture: function (sprite, color) + { + var texture = sprite.texture; + + color = CanvasTinter.roundColor(color); + + var stringColor = '#' + ('00000' + ( color | 0).toString(16)).substr(-6); + + texture.tintCache = texture.tintCache || {}; + + if (texture.tintCache[stringColor]) + { + return texture.tintCache[stringColor]; + } + + // clone texture.. + var canvas = CanvasTinter.canvas || document.createElement('canvas'); + + //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); + CanvasTinter.tintMethod(texture, color, canvas); + + if (CanvasTinter.convertTintToImage) + { + // is this better? + var tintImage = new Image(); + tintImage.src = canvas.toDataURL(); + + texture.tintCache[stringColor] = tintImage; + } + else + { + texture.tintCache[stringColor] = canvas; + // if we are not converting the texture to an image then we need to lose the reference to the canvas + CanvasTinter.canvas = null; + } + + return canvas; + }, + + /** + * Tint a texture using the 'multiply' operation. + * + * @memberof PIXI.CanvasTinter + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + tintWithMultiply: function (texture, color, canvas) + { + var context = canvas.getContext( '2d' ); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = crop.width; + canvas.height = crop.height; + + context.fillStyle = '#' + ('00000' + ( color | 0).toString(16)).substr(-6); + + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage( + texture.baseTexture.source, + crop.x, + crop.y, + crop.width, + crop.height, + 0, + 0, + crop.width, + crop.height + ); + + context.globalCompositeOperation = 'destination-atop'; + + context.drawImage( + texture.baseTexture.source, + crop.x, + crop.y, + crop.width, + crop.height, + 0, + 0, + crop.width, + crop.height + ); + }, + + /** + * Tint a texture using the 'overlay' operation. + * + * @memberof PIXI.CanvasTinter + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + tintWithOverlay: function (texture, color, canvas) + { + var context = canvas.getContext( '2d' ); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = crop.width; + canvas.height = crop.height; + + context.globalCompositeOperation = 'copy'; + context.fillStyle = '#' + ('00000' + ( color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + context.drawImage( + texture.baseTexture.source, + crop.x, + crop.y, + crop.width, + crop.height, + 0, + 0, + crop.width, + crop.height + ); + + // context.globalCompositeOperation = 'copy'; + }, + + /** + * Tint a texture pixel per pixel. + * + * @memberof PIXI.CanvasTinter + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + tintWithPerPixel: function (texture, color, canvas) + { + var context = canvas.getContext( '2d' ); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = crop.width; + canvas.height = crop.height; + + context.globalCompositeOperation = 'copy'; + context.drawImage( + texture.baseTexture.source, + crop.x, + crop.y, + crop.width, + crop.height, + 0, + 0, + crop.width, + crop.height + ); + + var rgbValues = utils.hex2rgb(color); + var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, crop.width, crop.height); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) + { + pixels[i+0] *= r; + pixels[i+1] *= g; + pixels[i+2] *= b; + } + + context.putImageData(pixelData, 0, 0); + }, + + /** + * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel. + * + * @memberof PIXI.CanvasTinter + * @param color {number} the color to round, should be a hex color + */ + roundColor: function (color) + { + var step = CanvasTinter.cacheStepsPerColorChannel; + + var rgbValues = utils.hex2rgb(color); + + rgbValues[0] = Math.min(255, (rgbValues[0] / step) * step); + rgbValues[1] = Math.min(255, (rgbValues[1] / step) * step); + rgbValues[2] = Math.min(255, (rgbValues[2] / step) * step); + + return utils.rgb2hex(rgbValues); + }, + + /** + * Number of steps which will be used as a cap when rounding colors. + * + * @memberof PIXI.CanvasTinter + * @type {number} + */ + cacheStepsPerColorChannel: 8, + + /** + * Tint cache boolean flag. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + convertTintToImage: false, + + /** + * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + canUseMultiply: canUseNewCanvasBlendModes(), + + /** + * The tinting method that will be used. + * + * @memberof PIXI.CanvasTinter + * @type {tintMethodFunctionType} + */ + tintMethod: 0 +}; + +CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply : CanvasTinter.tintWithPerPixel; + +/** + * The tintMethod type. + * + * @memberof PIXI.CanvasTinter + * @callback tintMethodFunctionType + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + +},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":112,"../../utils":151}],136:[function(require,module,exports){ + + + var Buffer = function(size) + { + + this.vertices = new ArrayBuffer(size); + + /** + * View on the vertices as a Float32Array for positions + * + * @member {Float32Array} + */ + this.float32View = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array for uvs + * + * @member {Float32Array} + */ + this.uint32View = new Uint32Array(this.vertices); + }; + + module.exports = Buffer; + + Buffer.prototype.destroy = function(){ + this.vertices = null; + this.positions = null; + this.uvs = null; + this.colors = null; + }; +},{}],137:[function(require,module,exports){ +var ObjectRenderer = require('../../renderers/webgl/utils/ObjectRenderer'), + WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'), + createIndicesForQuads = require('../../utils/createIndicesForQuads'), + generateMultiTextureShader = require('./generateMultiTextureShader'), + checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'), + Buffer = require('./BatchBuffer'), + CONST = require('../../const'), + glCore = require('pixi-gl-core'), + bitTwiddle = require('bit-twiddle'); + + var TICK = 0; +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + * @param renderer {PIXI.WebGLRenderer} The renderer this sprite batch works for. + */ +function SpriteRenderer(renderer) +{ + ObjectRenderer.call(this, renderer); + + /** + * Number of values sent in the vertex buffer. + * positionX, positionY, colorR, colorG, colorB = 5 + * + * @member {number} + */ + this.vertSize = 5; + + /** + * The size of the vertex information in bytes. + * + * @member {number} + */ + this.vertByteSize = this.vertSize * 4; + + /** + * The number of images in the SpriteBatch before it flushes. + * + * @member {number} + */ + this.size = CONST.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + + // the total number of bytes in our batch + // var numVerts = this.size * 4 * this.vertByteSize; + + this.buffers = []; + for (var i = 1; i <= bitTwiddle.nextPow2(this.size); i*=2) { + var numVertsTemp = i * 4 * this.vertByteSize; + this.buffers.push(new Buffer(numVertsTemp)); + } + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = createIndicesForQuads(this.size); + + /** + * The default shaders that is used if a sprite doesn't have a more specific one. + * there is a shader for each number of textures that can be rendererd. + * These shaders will also be generated on the fly as required. + * @member {PIXI.Shader[]} + */ + this.shaders = null; + + this.currentIndex = 0; + TICK =0; + this.groups = []; + + for (var k = 0; k < this.size; k++) + { + this.groups[k] = {textures:[], textureCount:0, ids:[], size:0, start:0, blend:0}; + } + + this.sprites = []; + + this.vertexBuffers = []; + this.vaos = []; + + this.vaoMax = 2; + this.vertexCount = 0; + + this.renderer.on('prerender', this.onPrerender, this); +} + + +SpriteRenderer.prototype = Object.create(ObjectRenderer.prototype); +SpriteRenderer.prototype.constructor = SpriteRenderer; +module.exports = SpriteRenderer; + +WebGLRenderer.registerPlugin('sprite', SpriteRenderer); + +/** + * Sets up the renderer context and necessary buffers. + * + * @private + */ +SpriteRenderer.prototype.onContextChange = function () +{ + var gl = this.renderer.gl; + + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), CONST.SPRITE_MAX_TEXTURES); + + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = checkMaxIfStatmentsInShader( this.MAX_TEXTURES, gl ); + + this.shaders = new Array(this.MAX_TEXTURES); + this.shaders[0] = generateMultiTextureShader(gl, 1); + this.shaders[1] = generateMultiTextureShader(gl, 2); + + // create a couple of buffers + this.indexBuffer = glCore.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + // we use the second shader as the first one depending on your browser may omit aTextureId + // as it is not used by the shader so is optimized out. + var shader = this.shaders[1]; + + for (var i = 0; i < this.vaoMax; i++) { + this.vertexBuffers[i] = glCore.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + + // build the vao object that will render.. + this.vaos[i] = this.renderer.createVao() + .addIndex(this.indexBuffer) + .addAttribute(this.vertexBuffers[i], shader.attributes.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0) + .addAttribute(this.vertexBuffers[i], shader.attributes.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4) + .addAttribute(this.vertexBuffers[i], shader.attributes.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4) + .addAttribute(this.vertexBuffers[i], shader.attributes.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vao = this.vaos[0]; + this.currentBlendMode = 99999; +}; + +SpriteRenderer.prototype.onPrerender = function () +{ + this.vertexCount = 0; +}; + +/** + * Renders the sprite object. + * + * @param sprite {PIXI.Sprite} the sprite to render when using this spritebatch + */ +SpriteRenderer.prototype.render = function (sprite) +{ + //TODO set blend modes.. + // check texture.. + if (this.currentIndex >= this.size) + { + this.flush(); + } + + + // get the uvs for the texture + + + // if the uvs have not updated then no point rendering just yet! + if (!sprite.texture._uvs) + { + return; + } + + // push a texture. + // increment the batchsize + this.sprites[this.currentIndex++] = sprite; +}; + +/** + * Renders the content and empties the current batch. + * + */ +SpriteRenderer.prototype.flush = function () +{ + if (this.currentIndex === 0) { + return; + } + + var gl = this.renderer.gl; + + var np2 = bitTwiddle.nextPow2(this.currentIndex); + var log2 = bitTwiddle.log2(np2); + var buffer = this.buffers[log2]; + + var sprites = this.sprites; + var groups = this.groups; + + var float32View = buffer.float32View; + var uint32View = buffer.uint32View; + + var index = 0; + var nextTexture; + var currentTexture; + var groupCount = 1; + var textureCount = 0; + var currentGroup = groups[0]; + var vertexData; + var tint; + var uvs; + var textureId; + var blendMode = sprites[0].blendMode; + var shader; + + currentGroup.textureCount = 0; + currentGroup.start = 0; + currentGroup.blend = blendMode; + + TICK++; + + for (var i = 0; i < this.currentIndex; i++) + { + // upload the sprite elemetns... + // they have all ready been calculated so we just need to push them into the buffer. + var sprite = sprites[i]; + + nextTexture = sprite._texture.baseTexture; + + if(blendMode !== sprite.blendMode) + { + blendMode = sprite.blendMode; + + // force the batch to break! + currentTexture = null; + textureCount = this.MAX_TEXTURES; + TICK++; + } + + if(currentTexture !== nextTexture) + { + currentTexture = nextTexture; + + if(nextTexture._enabled !== TICK) + { + if(textureCount === this.MAX_TEXTURES) + { + TICK++; + + textureCount = 0; + + currentGroup.size = i - currentGroup.start; + + currentGroup = groups[groupCount++]; + currentGroup.textureCount = 0; + currentGroup.blend = blendMode; + currentGroup.start = i; + } + + nextTexture._enabled = TICK; + nextTexture._id = textureCount; + + currentGroup.textures[currentGroup.textureCount++] = nextTexture; + textureCount++; + } + + } + + vertexData = sprite.vertexData; + + //TODO this sum does not need to be set each frame.. + tint = sprite._tintRGB + (sprite.worldAlpha * 255 << 24); + uvs = sprite._texture._uvs.uvsUint32; + textureId = nextTexture._id; + + if (this.renderer.roundPixels) + { + var resolution = this.renderer.resolution; + + //xy + float32View[index] = ((vertexData[0] * resolution) | 0) / resolution; + float32View[index+1] = ((vertexData[1] * resolution) | 0) / resolution; + + // xy + float32View[index+5] = ((vertexData[2] * resolution) | 0) / resolution; + float32View[index+6] = ((vertexData[3] * resolution) | 0) / resolution; + + // xy + float32View[index+10] = ((vertexData[4] * resolution) | 0) / resolution; + float32View[index+11] = ((vertexData[5] * resolution) | 0) / resolution; + + // xy + float32View[index+15] = ((vertexData[6] * resolution) | 0) / resolution; + float32View[index+16] = ((vertexData[7] * resolution) | 0) / resolution; + + } + else + { + //xy + float32View[index] = vertexData[0]; + float32View[index+1] = vertexData[1]; + + // xy + float32View[index+5] = vertexData[2]; + float32View[index+6] = vertexData[3]; + + // xy + float32View[index+10] = vertexData[4]; + float32View[index+11] = vertexData[5]; + + // xy + float32View[index+15] = vertexData[6]; + float32View[index+16] = vertexData[7]; + } + + uint32View[index+2] = uvs[0]; + uint32View[index+7] = uvs[1]; + uint32View[index+12] = uvs[2]; + uint32View[index+17] = uvs[3]; + + uint32View[index+3] = uint32View[index+8] = uint32View[index+13] = uint32View[index+18] = tint; + float32View[index+4] = float32View[index+9] = float32View[index+14] = float32View[index+19] = textureId; + + index += 20; + } + + currentGroup.size = i - currentGroup.start; + + this.vertexCount++; + + if(this.vaoMax <= this.vertexCount) + { + this.vaoMax++; + shader = this.shaders[1]; + this.vertexBuffers[this.vertexCount] = glCore.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + // build the vao object that will render.. + this.vaos[this.vertexCount] = this.renderer.createVao() + .addIndex(this.indexBuffer) + .addAttribute(this.vertexBuffers[this.vertexCount], shader.attributes.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0) + .addAttribute(this.vertexBuffers[this.vertexCount], shader.attributes.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4) + .addAttribute(this.vertexBuffers[this.vertexCount], shader.attributes.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4) + .addAttribute(this.vertexBuffers[this.vertexCount], shader.attributes.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0); + this.vao = this.vaos[this.vertexCount].bind(); + + /// render the groups.. + for (i = 0; i < groupCount; i++) { + + var group = groups[i]; + var groupTextureCount = group.textureCount; + shader = this.shaders[groupTextureCount-1]; + + if(!shader) + { + shader = this.shaders[groupTextureCount-1] = generateMultiTextureShader(gl, groupTextureCount); + //console.log("SHADER generated for " + textureCount + " textures") + } + + this.renderer.bindShader(shader); + + for (var j = 0; j < groupTextureCount; j++) + { + this.renderer.bindTexture(group.textures[j], j); + } + + // set the blend mode.. + this.renderer.state.setBlendMode( group.blend ); + + gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); + } + + // reset elements for the next flush + this.currentIndex = 0; +}; + +/** + * Starts a new sprite batch. + * + */ +SpriteRenderer.prototype.start = function () +{ + //this.renderer.bindShader(this.shader); + //TICK %= 1000; +}; + +SpriteRenderer.prototype.stop = function () +{ + this.flush(); + this.vao.unbind(); +}; +/** + * Destroys the SpriteBatch. + * + */ +SpriteRenderer.prototype.destroy = function () +{ + for (var i = 0; i < this.vaoMax; i++) { + this.vertexBuffers[i].destroy(); + this.vaos[i].destroy(); + } + + this.indexBuffer.destroy(); + + this.renderer.off('prerender', this.onPrerender, this); + ObjectRenderer.prototype.destroy.call(this); + + for (i = 0; i < this.shaders.length; i++) { + + if(this.shaders[i]) + { + this.shaders[i].destroy(); + } + } + + this.vertexBuffers = null; + this.vaos = null; + this.indexBuffer = null; + this.indices = null; + + this.sprites = null; + + for (i = 0; i < this.buffers.length; i++) { + this.buffers[i].destroy(); + } + +}; + +},{"../../const":78,"../../renderers/webgl/WebGLRenderer":116,"../../renderers/webgl/utils/ObjectRenderer":126,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":129,"../../utils/createIndicesForQuads":149,"./BatchBuffer":136,"./generateMultiTextureShader":138,"bit-twiddle":30,"pixi-gl-core":7}],138:[function(require,module,exports){ +var Shader = require('../../Shader'); + + +var fragTemplate = [ + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureId;', + 'uniform sampler2D uSamplers[%count%];', + + 'void main(void){', + 'vec4 color;', + 'float textureId = floor(vTextureId+0.5);', + '%forloop%', + 'gl_FragColor = color * vColor;', + '}' +].join('\n'); + +function generateMultiTextureShader(gl, maxTextures) +{ + var vertexSrc = "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = vec4(aColor.rgb * aColor.a, aColor.a);\n}\n"; + var fragmentSrc = fragTemplate; + + fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); + + var shader = new Shader(gl, vertexSrc, fragmentSrc, {aVertexPosition:3, aColor:2, aTextureCoord:1, aTextureId:0}); + + var sampleValues = []; + for (var i = 0; i < maxTextures; i++) + { + sampleValues[i] = i; + } + + shader.bind(); + shader.uniforms.uSamplers = sampleValues; + + return shader; +} + +function generateSampleSrc(maxTextures) +{ + var src = ''; + + src += '\n'; + src += '\n'; + + for (var i = 0; i < maxTextures; i++) + { + if(i > 0) + { + src += '\nelse '; + } + + if(i < maxTextures-1) + { + src += 'if(textureId == ' + i + '.0)'; + } + + src += '\n{'; + src += '\n\tcolor = texture2D(uSamplers['+i+'], vTextureCoord);'; + src += '\n}'; + } + + src += '\n'; + src += '\n'; + + return src; +} + + + +module.exports = generateMultiTextureShader; + +},{"../../Shader":77}],139:[function(require,module,exports){ +var Sprite = require('../sprites/Sprite'), + Texture = require('../textures/Texture'), + math = require('../math'), + utils = require('../utils'), + CONST = require('../const'), + TextStyle = require('./TextStyle'); + + var defaultDestroyOptions = { + texture:true, + children:false, + baseTexture:true + }; +/** + * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string, + * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object. + * + * A Text can be created directly from a string and a style object + * + * ```js + * var text = new PIXI.Text('This is a pixi text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI + * @param text {string} The string that you would like the text to display + * @param [style] {object|PIXI.TextStyle} The style parameters + */ +function Text(text, style) +{ + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * The canvas 2d context that everything is drawn with + * @member {HTMLCanvasElement} + */ + this.context = this.canvas.getContext('2d'); + + /** + * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. + * @member {number} + * @default 1 + */ + this.resolution = CONST.RESOLUTION; + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + this._text = null; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + this._style = null; + /** + * Private listener to track style changes. + * + * @member {Function} + * @private + */ + this._styleListener = null; + + /** + * Private tracker for the current font. + * + * @member {string} + * @private + */ + this._font = ''; + + var texture = Texture.fromCanvas(this.canvas); + texture.orig = new math.Rectangle(); + texture.trim = new math.Rectangle(); + Sprite.call(this, texture); + + this.text = text; + this.style = style; + + this.localStyleID = -1; +} + +// constructor +Text.prototype = Object.create(Sprite.prototype); +Text.prototype.constructor = Text; +module.exports = Text; + +Text.fontPropertiesCache = {}; +Text.fontPropertiesCanvas = document.createElement('canvas'); +Text.fontPropertiesContext = Text.fontPropertiesCanvas.getContext('2d'); + +Object.defineProperties(Text.prototype, { + /** + * The width of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Text# + */ + width: { + get: function () + { + this.updateText(true); + + return Math.abs(this.scale.x) * this.texture.orig.width; + }, + set: function (value) + { + this.updateText(true); + + var sign = utils.sign(this.scale.x) || 1; + this.scale.x = sign * value / this.texture.orig.width; + this._width = value; + } + }, + + /** + * The height of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Text# + */ + height: { + get: function () + { + this.updateText(true); + + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function (value) + { + this.updateText(true); + + var sign = utils.sign(this.scale.y) || 1; + this.scale.y = sign * value / this.texture.orig.height; + this._height = value; + } + }, + + /** + * Set the style of the text. Set up an event listener to listen for changes on the style object and mark the text as dirty. + * + * @member {object|PIXI.TextStyle} + * @memberof PIXI.Text# + */ + style: { + get: function () + { + return this._style; + }, + set: function (style) + { + + style = style || {}; + if (style instanceof TextStyle) + { + this._style = style; + } + else + { + this._style = new TextStyle(style); + } + + this.localStyleID = -1; + this.dirty = true; + } + }, + + /** + * Set the copy for the text object. To split a line you can use '\n'. + * + * @member {string} + * @memberof PIXI.Text# + */ + text: { + get: function() + { + return this._text; + }, + set: function (text){ + + text = text || ' '; + text = text.toString(); + + if (this._text === text) + { + return; + } + this._text = text; + this.dirty = true; + } + } +}); + +/** + * Renders text and updates it when needed + * @param respectDirty {boolean} Whether to abort updating the text if the Text isn't dirty and the function is called. + * @private + */ +Text.prototype.updateText = function (respectDirty) +{ + var style = this._style; + + // check if style has changed.. + if(this.localStyleID !== style.styleID) + { + this.dirty = true; + this.localStyleID = style.styleID; + } + + if (!this.dirty && respectDirty) { + return; + } + + // build canvas api font setting from invididual components. Convert a numeric style.fontSize to px + var fontSizeString = (typeof style.fontSize === 'number') ? style.fontSize + 'px' : style.fontSize; + this._font = style.fontStyle + ' ' + style.fontVariant + ' ' + style.fontWeight + ' ' + fontSizeString + ' ' + style.fontFamily; + + this.context.font = this._font; + + // word wrap + // preserve original text + var outputText = style.wordWrap ? this.wordWrap(this._text) : this._text; + + // split text into lines + var lines = outputText.split(/(?:\r\n|\r|\n)/); + + // calculate text width + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + var fontProperties = this.determineFontProperties(this._font); + + var i; + for (i = 0; i < lines.length; i++) + { + var lineWidth = this.context.measureText(lines[i]).width + ((lines[i].length - 1) * style.letterSpacing); + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + + var width = maxLineWidth + style.strokeThickness; + if (style.dropShadow) + { + width += style.dropShadowDistance; + } + + width += style.padding * 2; + + this.canvas.width = Math.ceil( ( width + this.context.lineWidth ) * this.resolution ); + + // calculate text height + var lineHeight = this.style.lineHeight || fontProperties.fontSize + style.strokeThickness; + + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * lineHeight; + if (style.dropShadow) + { + height += style.dropShadowDistance; + } + + this.canvas.height = Math.ceil( ( height + this._style.padding * 2 ) * this.resolution ); + + this.context.scale( this.resolution, this.resolution); + + if (navigator.isCocoonJS) + { + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + + } + +// this.context.fillStyle="#FF0000"; +// this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); + + this.context.font = this._font; + this.context.strokeStyle = style.stroke; + this.context.lineWidth = style.strokeThickness; + this.context.textBaseline = style.textBaseline; + this.context.lineJoin = style.lineJoin; + this.context.miterLimit = style.miterLimit; + + var linePositionX; + var linePositionY; + + if (style.dropShadow) + { + if (style.dropShadowBlur > 0) { + this.context.shadowColor = style.dropShadowColor; + this.context.shadowBlur = style.dropShadowBlur; + } else { + this.context.fillStyle = style.dropShadowColor; + } + + var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + + for (i = 0; i < lines.length; i++) + { + linePositionX = style.strokeThickness / 2; + linePositionY = (style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent; + + if (style.align === 'right') + { + linePositionX += maxLineWidth - lineWidths[i]; + } + else if (style.align === 'center') + { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (style.fill) + { + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); + + if (style.stroke && style.strokeThickness) + { + this.context.strokeStyle = style.dropShadowColor; + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding, true); + this.context.strokeStyle = style.stroke; + } + } + } + } + + //set canvas text styles + this.context.fillStyle = this._generateFillStyle(style, lines); + + //draw lines line by line + for (i = 0; i < lines.length; i++) + { + linePositionX = style.strokeThickness / 2; + linePositionY = (style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent; + + if (style.align === 'right') + { + linePositionX += maxLineWidth - lineWidths[i]; + } + else if (style.align === 'center') + { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (style.stroke && style.strokeThickness) + { + this.drawLetterSpacing(lines[i], linePositionX + style.padding, linePositionY + style.padding, true); + } + + if (style.fill) + { + this.drawLetterSpacing(lines[i], linePositionX + style.padding, linePositionY + style.padding); + } + } + + this.updateTexture(); +}; + +/** + * Render the text with letter-spacing. + * @param {string} text - The text to draw + * @param {number} x - Horizontal position to draw the text + * @param {number} y - Vertical position to draw the text + * @param {boolean} isStroke - Is this drawing for the outside stroke of the text? If not, it's for the inside fill + * @private + */ +Text.prototype.drawLetterSpacing = function(text, x, y, isStroke) +{ + var style = this._style; + + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + + if (letterSpacing === 0) + { + if (isStroke) + { + this.context.strokeText(text, x, y); + } + else + { + this.context.fillText(text, x, y); + } + return; + } + + var characters = String.prototype.split.call(text, ''), + index = 0, + current, + currentPosition = x; + + while (index < text.length) + { + current = characters[index++]; + if (isStroke) + { + this.context.strokeText(current, currentPosition, y); + } + else + { + this.context.fillText(current, currentPosition, y); + } + currentPosition += this.context.measureText(current).width + letterSpacing; + } +}; + +/** + * Updates texture size based on canvas size + * + * @private + */ +Text.prototype.updateTexture = function () +{ + var texture = this._texture; + var style = this._style; + + texture.baseTexture.hasLoaded = true; + texture.baseTexture.resolution = this.resolution; + + texture.baseTexture.realWidth = this.canvas.width; + texture.baseTexture.realHeight = this.canvas.height; + texture.baseTexture.width = this.canvas.width / this.resolution; + texture.baseTexture.height = this.canvas.height / this.resolution; + texture.trim.width = texture._frame.width = this.canvas.width / this.resolution; + texture.trim.height = texture._frame.height = this.canvas.height / this.resolution; + + texture.trim.x = -style.padding; + texture.trim.y = -style.padding; + + texture.orig.width = texture._frame.width- style.padding*2; + texture.orig.height = texture._frame.height - style.padding*2; + + //call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + + texture.baseTexture.emit('update', texture.baseTexture); + + this.dirty = false; +}; + +/** + * Renders the object using the WebGL renderer + * + * @param renderer {PIXI.WebGLRenderer} The renderer + */ +Text.prototype.renderWebGL = function (renderer) +{ + if(this.resolution !== renderer.resolution) + { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + Sprite.prototype.renderWebGL.call(this, renderer); +}; + +/** + * Renders the object using the Canvas renderer + * + * @param renderer {PIXI.CanvasRenderer} The renderer + * @private + */ +Text.prototype._renderCanvas = function (renderer) +{ + if(this.resolution !== renderer.resolution) + { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + Sprite.prototype._renderCanvas.call(this, renderer); +}; + +/** + * Calculates the ascent, descent and fontSize of a given fontStyle + * + * @param fontStyle {string} String representing the style of the font + * @return {Object} Font properties object + * @private + */ +Text.prototype.determineFontProperties = function (fontStyle) +{ + var properties = Text.fontPropertiesCache[fontStyle]; + + if (!properties) + { + properties = {}; + + var canvas = Text.fontPropertiesCanvas; + var context = Text.fontPropertiesContext; + + context.font = fontStyle; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('M').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = fontStyle; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i, j; + + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; i++) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + if (!stop) + { + idx += line; + } + else + { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; i--) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + if (!stop) + { + idx -= line; + } + else + { + break; + } + } + + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + + Text.fontPropertiesCache[fontStyle] = properties; + } + + return properties; +}; + +/** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @param text {string} String to apply word wrapping to + * @return {string} New string with new lines applied where required + * @private + */ +Text.prototype.wordWrap = function (text) +{ + // Greedy wrapping algorithm that will wrap words as the line grows longer + // than its horizontal bounds. + var result = ''; + var lines = text.split('\n'); + var wordWrapWidth = this._style.wordWrapWidth; + for (var i = 0; i < lines.length; i++) + { + var spaceLeft = wordWrapWidth; + var words = lines[i].split(' '); + for (var j = 0; j < words.length; j++) + { + var wordWidth = this.context.measureText(words[j]).width; + if (this._style.breakWords && wordWidth > wordWrapWidth) + { + // Word should be split in the middle + var characters = words[j].split(''); + for (var c = 0; c < characters.length; c++) + { + var characterWidth = this.context.measureText(characters[c]).width; + if (characterWidth > spaceLeft) + { + result += '\n' + characters[c]; + spaceLeft = wordWrapWidth - characterWidth; + } + else + { + if (c === 0) + { + result += ' '; + } + result += characters[c]; + spaceLeft -= characterWidth; + } + } + } + else + { + var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; + if (j === 0 || wordWidthWithSpace > spaceLeft) + { + // Skip printing the newline if it's the first word of the line that is + // greater than the word wrap width. + if (j > 0) + { + result += '\n'; + } + result += words[j]; + spaceLeft = wordWrapWidth - wordWidth; + } + else + { + spaceLeft -= wordWidthWithSpace; + result += ' ' + words[j]; + } + } + } + + if (i < lines.length-1) + { + result += '\n'; + } + } + return result; +}; + +/** + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + */ +Text.prototype._calculateBounds = function () +{ + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); +}; + +/** + * Method to be called upon a TextStyle change. + * @private + */ +Text.prototype._onStyleChange = function () +{ + this.dirty = true; +}; + +/** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * @return string|Number|CanvasGradient + * @private + */ +Text.prototype._generateFillStyle = function (style, lines) +{ + if (!Array.isArray(style.fill)) + { + return style.fill; + } + else + { + // cocoon on canvas+ cannot generate textures, so use the first colour instead + if ( navigator.isCocoonJS ) { + return style.fill[0]; + } + + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var i; + var gradient; + var totalIterations; + var currentIteration; + var stop; + + var width = this.canvas.width / this.resolution; + var height = this.canvas.height / this.resolution; + + if (style.fillGradientType === CONST.TEXT_GRADIENT.LINEAR_VERTICAL) + { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); + + // we need to repeat the gradient so that each invididual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + totalIterations = ( style.fill.length + 1 ) * lines.length; + currentIteration = 0; + for (i = 0; i < lines.length; i++) + { + currentIteration += 1; + for (var j = 0; j < style.fill.length; j++) + { + stop = (currentIteration / totalIterations); + gradient.addColorStop(stop, style.fill[j]); + currentIteration++; + } + } + } + else + { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); + + // can just evenly space out the gradients in this case, as multiple lines makes no difference to an even left to right gradient + totalIterations = style.fill.length + 1; + currentIteration = 1; + + for (i = 0; i < style.fill.length; i++) + { + stop = currentIteration / totalIterations; + gradient.addColorStop(stop, style.fill[i]); + currentIteration++; + } + } + + return gradient; + } +}; + +/** + * Destroys this text object. + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majorety of the time the texture will not be shared with any other Sprites. + * + * @param [options] {object|boolean} Options parameter. A boolean will act as if all options have been set to that value + * @param [options.children=false] {boolean} if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param [options.texture=true] {boolean} Should it destroy the current texture of the sprite as well + * @param [options.baseTexture=true] {boolean} Should it destroy the base texture of the sprite as well + */ +Text.prototype.destroy = function (options) +{ + if (typeof options === 'boolean') { + options = { children: options }; + } + + options = Object.assign({}, defaultDestroyOptions, options); + + Sprite.prototype.destroy.call(this, options); + + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + + this._style = null; +}; + +},{"../const":78,"../math":102,"../sprites/Sprite":133,"../textures/Texture":144,"../utils":151,"./TextStyle":140}],140:[function(require,module,exports){ +var CONST = require('../const'), + utils = require('../utils'); + +/** + * A TextStyle Object decorates a Text Object. It can be shared between + * multiple Text objects. Changing the style will update all text objects using it. + * + * @class + * @memberof PIXI + * @param [style] {object} The style parameters + * @param [style.align='left'] {string} Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text + * @param [style.breakWords=false] {boolean} Indicates if lines can be wrapped within words, it needs wordWrap to be set to true + * @param [style.dropShadow=false] {boolean} Set a drop shadow for the text + * @param [style.dropShadowAngle=Math.PI/6] {number} Set a angle of the drop shadow + * @param [style.dropShadowBlur=0] {number} Set a shadow blur radius + * @param [style.dropShadowColor='#000000'] {string} A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param [style.dropShadowDistance=5] {number} Set a distance of the drop shadow + * @param [style.fill='black'] {string|string[]|number|number[]|CanvasGradient|CanvasPattern} A canvas fillstyle that will be used on the + * text e.g 'red', '#00FF00'. Can be an array to create a gradient eg ['#000000','#FFFFFF'] @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] {number} If fills styles are supplied, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} for possible values + * @param [style.fontFamily='Arial'] {string} The font family + * @param [style.fontSize=26] {number|string} The font size (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em') + * @param [style.fontStyle='normal'] {string} The font style ('normal', 'italic' or 'oblique') + * @param [style.fontVariant='normal'] {string} The font variant ('normal' or 'small-caps') + * @param [style.fontWeight='normal'] {string} The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900') + * @param [style.letterSpacing=0] {number} The amount of spacing between letters, default is 0 + * @param [style.lineHeight] {number} The line height, a number that represents the vertical space that a letter uses + * @param [style.lineJoin='miter'] {string} The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Default is 'miter' (creates a sharp corner). + * @param [style.miterLimit=10] {number} The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param [style.padding=0] {number} Occasionally some fonts are cropped on top or bottom. Adding some padding will + * prevent this from happening by adding padding to the top and bottom of text height. + * @param [style.stroke='black'] {string|number} A canvas fillstyle that will be used on the text stroke e.g 'blue', '#FCFF00' + * @param [style.strokeThickness=0] {number} A number that represents the thickness of the stroke. Default is 0 (no stroke) + * @param [style.textBaseline='alphabetic'] {string} The baseline of the text that is rendered. + * @param [style.wordWrap=false] {boolean} Indicates if word wrap should be used + * @param [style.wordWrapWidth=100] {number} The width at which text will wrap, it needs wordWrap to be set to true + */ +function TextStyle(style) +{ + this.styleID = 0; + Object.assign(this, this._defaults, style); +} + +TextStyle.prototype.constructor = TextStyle; +module.exports = TextStyle; + +// Default settings. Explained in the constructor. +TextStyle.prototype._defaults = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: '#000000', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: CONST.TEXT_GRADIENT.LINEAR_VERTICAL, + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + wordWrap: false, + wordWrapWidth: 100 +}; + +/** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return {PIXI.TextStyle} New cloned TextStyle object + */ +TextStyle.prototype.clone = function () +{ + var clonedProperties = {}; + for (var key in this._defaults) + { + clonedProperties[key] = this[key]; + } + return new TextStyle(clonedProperties); +}; + +/** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ +TextStyle.prototype.reset = function () +{ + Object.assign(this, this._defaults); +}; + +/** + * Create setters and getters for each of the style properties. Converts colors where necessary. + */ +Object.defineProperties(TextStyle.prototype, { + align: { + get: function () + { + return this._align; + }, + set: function (align) + { + if (this._align !== align) + { + this._align = align; + this.styleID++; + } + } + }, + + breakWords: { + get: function () + { + return this._breakWords; + }, + set: function (breakWords) + { + if (this._breakWords !== breakWords) + { + this._breakWords = breakWords; + this.styleID++; + } + } + }, + + dropShadow: { + get: function () + { + return this._dropShadow; + }, + set: function (dropShadow) + { + if (this._dropShadow !== dropShadow) + { + this._dropShadow = dropShadow; + this.styleID++; + } + } + }, + + dropShadowAngle: { + get: function () + { + return this._dropShadowAngle; + }, + set: function (dropShadowAngle) + { + if (this._dropShadowAngle !== dropShadowAngle) + { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + } + }, + + dropShadowBlur: { + get: function () + { + return this._dropShadowBlur; + }, + set: function (dropShadowBlur) + { + if (this._dropShadowBlur !== dropShadowBlur) + { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + } + }, + + dropShadowColor: { + get: function () + { + return this._dropShadowColor; + }, + set: function (dropShadowColor) + { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) + { + this._dropShadowColor = outputColor; + this.styleID++; + } + } + }, + + dropShadowDistance: { + get: function () + { + return this._dropShadowDistance; + }, + set: function (dropShadowDistance) + { + if (this._dropShadowDistance !== dropShadowDistance) + { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + } + }, + + fill: { + get: function () + { + return this._fill; + }, + set: function (fill) + { + var outputColor = getColor(fill); + if (this._fill !== outputColor) + { + this._fill = outputColor; + this.styleID++; + } + } + }, + + fillGradientType: { + get: function () + { + return this._fillGradientType; + }, + set: function (fillGradientType) + { + if (this._fillGradientType !== fillGradientType) + { + this._fillGradientType = fillGradientType; + this.styleID++; + } + } + }, + + fontFamily: { + get: function () + { + return this._fontFamily; + }, + set: function (fontFamily) + { + if (this.fontFamily !== fontFamily) + { + this._fontFamily = fontFamily; + this.styleID++; + } + } + }, + + fontSize: { + get: function () + { + return this._fontSize; + }, + set: function (fontSize) + { + if (this._fontSize !== fontSize) + { + this._fontSize = fontSize; + this.styleID++; + } + } + }, + + fontStyle: { + get: function () + { + return this._fontStyle; + }, + set: function (fontStyle) + { + if (this._fontStyle !== fontStyle) + { + this._fontStyle = fontStyle; + this.styleID++; + } + } + }, + + fontVariant: { + get: function () + { + return this._fontVariant; + }, + set: function (fontVariant) + { + if (this._fontVariant !== fontVariant) + { + this._fontVariant = fontVariant; + this.styleID++; + } + } + }, + + fontWeight: { + get: function () + { + return this._fontWeight; + }, + set: function (fontWeight) + { + if (this._fontWeight !== fontWeight) + { + this._fontWeight = fontWeight; + this.styleID++; + } + } + }, + + letterSpacing: { + get: function () + { + return this._letterSpacing; + }, + set: function (letterSpacing) + { + if (this._letterSpacing !== letterSpacing) + { + this._letterSpacing = letterSpacing; + this.styleID++; + } + } + }, + + lineHeight: { + get: function () + { + return this._lineHeight; + }, + set: function (lineHeight) + { + if (this._lineHeight !== lineHeight) + { + this._lineHeight = lineHeight; + this.styleID++; + } + } + }, + + lineJoin: { + get: function () + { + return this._lineJoin; + }, + set: function (lineJoin) + { + if (this._lineJoin !== lineJoin) + { + this._lineJoin = lineJoin; + this.styleID++; + } + } + }, + + miterLimit: { + get: function () + { + return this._miterLimit; + }, + set: function (miterLimit) + { + if (this._miterLimit !== miterLimit) + { + this._miterLimit = miterLimit; + this.styleID++; + } + } + }, + + padding: { + get: function () + { + return this._padding; + }, + set: function (padding) + { + if (this._padding !== padding) + { + this._padding = padding; + this.styleID++; + } + } + }, + + stroke: { + get: function () + { + return this._stroke; + }, + set: function (stroke) + { + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) + { + this._stroke = outputColor; + this.styleID++; + } + } + }, + + strokeThickness: { + get: function () + { + return this._strokeThickness; + }, + set: function (strokeThickness) + { + if (this._strokeThickness !== strokeThickness) + { + this._strokeThickness = strokeThickness; + this.styleID++; + } + } + }, + + textBaseline: { + get: function () + { + return this._textBaseline; + }, + set: function (textBaseline) + { + if (this._textBaseline !== textBaseline) + { + this._textBaseline = textBaseline; + this.styleID++; + } + } + }, + + wordWrap: { + get: function () + { + return this._wordWrap; + }, + set: function (wordWrap) + { + if (this._wordWrap !== wordWrap) + { + this._wordWrap = wordWrap; + this.styleID++; + } + } + }, + + wordWrapWidth: { + get: function () + { + return this._wordWrapWidth; + }, + set: function (wordWrapWidth) + { + if (this._wordWrapWidth !== wordWrapWidth) + { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + } + } +}); + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * + * @return {string} The color as a string. + */ +function getColor(color) +{ + if (typeof color === 'number') + { + return utils.hex2string(color); + } + else if (Array.isArray(color)) + { + for (var i = 0; i < color.length; ++i) + { + if (typeof color[i] === 'number') + { + color[i] = utils.hex2string(color[i]); + } + } + } + + return color; +} + +},{"../const":78,"../utils":151}],141:[function(require,module,exports){ +var BaseTexture = require('./BaseTexture'), + CONST = require('../const'); + +/** + * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * var renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * var BaserenderTexture = new PIXI.BaseRenderTexture(renderer, 800, 600); + * var sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * BaserenderTexture.render(sprite); + * ``` + * + * The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual + * position a Container should be used: + * + * ```js + * var doc = new PIXI.Container(); + * + * doc.addChild(sprite); + * + * var baseRenderTexture = new PIXI.BaserenderTexture(100, 100); + * var renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(doc, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + * @param [width=100] {number} The width of the base render texture + * @param [height=100] {number} The height of the base render texture + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @param [resolution=1] {number} The resolution / device pixel ratio of the texture being generated + */ +function BaseRenderTexture(width, height, scaleMode, resolution) +{ + BaseTexture.call(this, null, scaleMode); + + this.resolution = resolution || CONST.RESOLUTION; + + this.width = width || 100; + this.height = height || 100; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + this.scaleMode = scaleMode || CONST.SCALE_MODES.DEFAULT; + this.hasLoaded = true; + + /** + * A map of renderer IDs to webgl renderTargets + * + * @member {object} + * @private + */ + this._glRenderTargets = []; + + /** + * A reference to the canvas render target (we only need one as this can be shared accross renderers) + * + * @member {object} + * @private + */ + this._canvasRenderTarget = null; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + this.valid = false; +} + +BaseRenderTexture.prototype = Object.create(BaseTexture.prototype); +BaseRenderTexture.prototype.constructor = BaseRenderTexture; +module.exports = BaseRenderTexture; + +/** + * Resizes the BaseRenderTexture. + * + * @param width {number} The width to resize to. + * @param height {number} The height to resize to. + */ +BaseRenderTexture.prototype.resize = function (width, height) +{ + + if (width === this.width && height === this.height) + { + return; + } + + this.valid = (width > 0 && height > 0); + + this.width = width; + this.height = height; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + if (!this.valid) + { + return; + } + + this.emit('update', this); + +}; + +/** + * Destroys this texture + * + */ +BaseRenderTexture.prototype.destroy = function () +{ + BaseTexture.prototype.destroy.call(this, true); + this.renderer = null; +}; + + +},{"../const":78,"./BaseTexture":142}],142:[function(require,module,exports){ +var utils = require('../utils'), + CONST = require('../const'), + EventEmitter = require('eventemitter3'), + determineCrossOrigin = require('../utils/determineCrossOrigin'), + bitTwiddle = require('bit-twiddle'); + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class + * @memberof PIXI + * @param [source ]{HTMLImageElement|HTMLCanvasElement} the source object of the texture. + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @param [resolution=1] {number} The resolution / device pixel ratio of the texture + */ +function BaseTexture(source, scaleMode, resolution) +{ + EventEmitter.call(this); + + this.uid = utils.uid(); + + this.touched = 0; + + /** + * The resolution / device pixel ratio of the texture + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || CONST.RESOLUTION; + + /** + * The width of the base texture set when the image has loaded + * + * @member {number} + * @readonly + */ + this.width = 100; + + /** + * The height of the base texture set when the image has loaded + * + * @member {number} + * @readonly + */ + this.height = 100; + + // TODO docs + // used to store the actual dimensions of the source + /** + * Used to store the actual width of the source of this texture + * + * @member {number} + * @readonly + */ + this.realWidth = 100; + /** + * Used to store the actual height of the source of this texture + * + * @member {number} + * @readonly + */ + this.realHeight = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @member {number} + * @default PIXI.SCALE_MODES.DEFAULT + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode || CONST.SCALE_MODES.DEFAULT; + + /** + * Set to true once the base texture has successfully loaded. + * + * This is never true if the underlying source fails to load or has no texture data. + * + * @member {boolean} + * @readonly + */ + this.hasLoaded = false; + + /** + * Set to true if the source is currently loading. + * + * If an Image source is loading the 'loaded' or 'error' event will be + * dispatched when the operation ends. An underyling source that is + * immediately-available bypasses loading entirely. + * + * @member {boolean} + * @readonly + */ + this.isLoading = false; + + /** + * The image source that is used to create the texture. + * + * TODO: Make this a setter that calls loadSource(); + * + * @member {HTMLImageElement|HTMLCanvasElement} + * @readonly + */ + this.source = null; // set in loadSource, if at all + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * All blend modes, and shaders written for default value. Change it on your own risk. + * + * @member {boolean} + * @default true + */ + this.premultipliedAlpha = true; + + /** + * The image url of the texture + * + * @member {string} + */ + this.imageUrl = null; + + /** + * Wether or not the texture is a power of two, try to use power of two textures as much as you can + * @member {boolean} + * @private + */ + this.isPowerOfTwo = false; + + // used for webGL + + /** + * + * Set this to true if a mipmap of this texture needs to be generated. This value needs to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @member {boolean} + * @see PIXI.MIPMAP_TEXTURES + */ + this.mipmap = CONST.MIPMAP_TEXTURES; + + /** + * + * WebGL Texture wrap mode + * + * @member {number} + * @see PIXI.WRAP_MODES + */ + this.wrapMode = CONST.WRAP_MODES.DEFAULT; + + /** + * A map of renderer IDs to webgl textures + * + * @member {object} + * @private + */ + this._glTextures = []; + this._enabled = 0; + this._id = 0; + + // if no source passed don't try to load + if (source) + { + this.loadSource(source); + } + + /** + * Fired when a not-immediately-available source finishes loading. + * + * @event loaded + * @memberof PIXI.BaseTexture# + * @protected + */ + + /** + * Fired when a not-immediately-available source fails to load. + * + * @event error + * @memberof PIXI.BaseTexture# + * @protected + */ +} + +BaseTexture.prototype = Object.create(EventEmitter.prototype); +BaseTexture.prototype.constructor = BaseTexture; +module.exports = BaseTexture; + +/** + * Updates the texture on all the webgl renderers, this also assumes the src has changed. + * + * @fires update + */ +BaseTexture.prototype.update = function () +{ + this.realWidth = this.source.naturalWidth || this.source.videoWidth || this.source.width; + this.realHeight = this.source.naturalHeight || this.source.videoHeight || this.source.height; + + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); + + this.emit('update', this); +}; + +/** + * Load a source. + * + * If the source is not-immediately-available, such as an image that needs to be + * downloaded, then the 'loaded' or 'error' event will be dispatched in the future + * and `hasLoaded` will remain false after this call. + * + * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: + * + * if (texture.hasLoaded) { + * // texture ready for use + * } else if (texture.isLoading) { + * // listen to 'loaded' and/or 'error' events on texture + * } else { + * // not loading, not going to load UNLESS the source is reloaded + * // (it may still make sense to listen to the events) + * } + * + * @protected + * @param source {HTMLImageElement|HTMLCanvasElement} the source object of the texture. + */ +BaseTexture.prototype.loadSource = function (source) +{ + var wasLoading = this.isLoading; + this.hasLoaded = false; + this.isLoading = false; + + if (wasLoading && this.source) + { + this.source.onload = null; + this.source.onerror = null; + } + + this.source = source; + + // Apply source if loaded. Otherwise setup appropriate loading monitors. + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { + this._sourceLoaded(); + } + else if (!source.getContext) + { + + // Image fail / not ready + this.isLoading = true; + + var scope = this; + + source.onload = function () + { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) + { + return; + } + + scope.isLoading = false; + scope._sourceLoaded(); + + scope.emit('loaded', scope); + }; + + source.onerror = function () + { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) + { + return; + } + + scope.isLoading = false; + scope.emit('error', scope); + }; + + // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element + // "The value of `complete` can thus change while a script is executing." + // So complete needs to be re-checked after the callbacks have been added.. + // NOTE: complete will be true if the image has no src so best to check if the src is set. + if (source.complete && source.src) + { + this.isLoading = false; + + // ..and if we're complete now, no need for callbacks + source.onload = null; + source.onerror = null; + + if (source.width && source.height) + { + this._sourceLoaded(); + + // If any previous subscribers possible + if (wasLoading) + { + this.emit('loaded', this); + } + } + else + { + // If any previous subscribers possible + if (wasLoading) + { + this.emit('error', this); + } + } + } + } +}; + +/** + * Used internally to update the width, height, and some other tracking vars once + * a source has successfully loaded. + * + * @private + */ +BaseTexture.prototype._sourceLoaded = function () +{ + this.hasLoaded = true; + this.update(); +}; + +/** + * Destroys this base texture + * + */ +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { + delete utils.BaseTextureCache[this.imageUrl]; + delete utils.TextureCache[this.imageUrl]; + + this.imageUrl = null; + + if (!navigator.isCocoonJS) + { + this.source.src = ''; + } + } + else if (this.source && this.source._pixiId) + { + delete utils.BaseTextureCache[this.source._pixiId]; + } + + this.source = null; + + this.dispose(); +}; + +/** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + */ +BaseTexture.prototype.dispose = function () +{ + this.emit('dispose', this); + + // this should no longer be needed, the renderers should cleanup all the gl textures. + // this._glTextures = {}; +}; + +/** + * Changes the source image of the texture. + * The original source must be an Image element. + * + * @param newSrc {string} the path of the image + */ +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ + this.source.src = newSrc; + + this.loadSource(this.source); +}; + +/** + * Helper function that creates a base texture from the given image url. + * If the image is not in the base texture cache it will be created and loaded. + * + * @static + * @param imageUrl {string} The image url of the texture + * @param [crossorigin=(auto)] {boolean} Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @return PIXI.BaseTexture + */ +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ + var baseTexture = utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) + { + // new Image() breaks tex loading in some versions of Chrome. + // See https://code.google.com/p/chromium/issues/detail?id=238071 + var image = new Image();//document.createElement('img'); + + + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { + image.crossOrigin = determineCrossOrigin(imageUrl); + } + + baseTexture = new BaseTexture(image, scaleMode); + baseTexture.imageUrl = imageUrl; + + image.src = imageUrl; + + utils.BaseTextureCache[imageUrl] = baseTexture; + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = utils.getResolutionOfUrl(imageUrl); + } + + return baseTexture; +}; + +/** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @param canvas {HTMLCanvasElement} The canvas element source of the texture + * @param scaleMode {number} See {@link PIXI.SCALE_MODES} for possible values + * @return PIXI.BaseTexture + */ +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { + canvas._pixiId = 'canvas_' + utils.uid(); + } + + var baseTexture = utils.BaseTextureCache[canvas._pixiId]; + + if (!baseTexture) + { + baseTexture = new BaseTexture(canvas, scaleMode); + utils.BaseTextureCache[canvas._pixiId] = baseTexture; + } + + return baseTexture; +}; + +},{"../const":78,"../utils":151,"../utils/determineCrossOrigin":150,"bit-twiddle":30,"eventemitter3":32}],143:[function(require,module,exports){ +var BaseRenderTexture = require('./BaseRenderTexture'), + Texture = require('./Texture'); + +/** + * A RenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * var renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * var renderTexture = PIXI.RenderTexture.create(800, 600); + * var sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual + * position a Container should be used: + * + * ```js + * var doc = new PIXI.Container(); + * + * doc.addChild(sprite); + * + * renderer.render(doc, renderTexture); // Renders to center of renderTexture + * ``` + * + * @class + * @extends PIXI.Texture + * @memberof PIXI + * @param baseRenderTexture {PIXI.BaseRenderTexture} The renderer used for this RenderTexture + * @param [frame] {PIXI.Rectangle} The rectangle frame of the texture to show + */ +function RenderTexture(baseRenderTexture, frame) +{ + // suport for legacy.. + this.legacyRenderer = null; + + if( !(baseRenderTexture instanceof BaseRenderTexture) ) + { + var width = arguments[1]; + var height = arguments[2]; + var scaleMode = arguments[3] || 0; + var resolution = arguments[4] || 1; + + // we have an old render texture.. + console.warn('v4 RenderTexture now expects a new BaseRenderTexture. Please use RenderTexture.create('+width+', '+height+')'); // jshint ignore:line + this.legacyRenderer = arguments[0]; + + frame = null; + baseRenderTexture = new BaseRenderTexture(width, height, scaleMode, resolution); + } + + + /** + * The base texture object that this texture uses + * + * @member {BaseTexture} + */ + Texture.call(this, + baseRenderTexture, + frame + ); + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + this.valid = true; + + this._updateUvs(); +} + +RenderTexture.prototype = Object.create(Texture.prototype); +RenderTexture.prototype.constructor = RenderTexture; +module.exports = RenderTexture; + +/** + * Resizes the RenderTexture. + * + * @param width {number} The width to resize to. + * @param height {number} The height to resize to. + * @param doNotResizeBaseTexture {boolean} Should the baseTexture.width and height values be resized as well? + */ +RenderTexture.prototype.resize = function (width, height, doNotResizeBaseTexture) +{ + + //TODO - could be not required.. + this.valid = (width > 0 && height > 0); + + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + + if (!doNotResizeBaseTexture) + { + this.baseTexture.resize(width, height); + } + + this._updateUvs(); +}; + +/** + * A short hand way of creating a render texture.. + * @param [width=100] {number} The width of the render texture + * @param [height=100] {number} The height of the render texture + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @param [resolution=1] {number} The resolution / device pixel ratio of the texture being generated + */ +RenderTexture.create = function(width, height, scaleMode, resolution) +{ + return new RenderTexture(new BaseRenderTexture(width, height, scaleMode, resolution)); +}; + +},{"./BaseRenderTexture":141,"./Texture":144}],144:[function(require,module,exports){ +var BaseTexture = require('./BaseTexture'), + VideoBaseTexture = require('./VideoBaseTexture'), + TextureUvs = require('./TextureUvs'), + EventEmitter = require('eventemitter3'), + math = require('../math'), + utils = require('../utils'); + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * var texture = PIXI.Texture.fromImage('assets/image.png'); + * var sprite1 = new PIXI.Sprite(texture); + * var sprite2 = new PIXI.Sprite(texture); + * ``` + * + * @class + * @memberof PIXI + * @param baseTexture {PIXI.BaseTexture} The base texture source to create the texture from + * @param [frame] {PIXI.Rectangle} The rectangle frame of the texture to show + * @param [orig] {PIXI.Rectangle} The area of original texture + * @param [trim] {PIXI.Rectangle} Trimmed rectangle of original texture + * @param [rotate] {number} indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8} + */ +function Texture(baseTexture, frame, orig, trim, rotate) +{ + EventEmitter.call(this); + + /** + * Does this Texture have any frame data assigned to it? + * + * @member {boolean} + */ + this.noFrame = false; + + if (!frame) + { + this.noFrame = true; + frame = new math.Rectangle(0, 0, 1, 1); + } + + if (baseTexture instanceof Texture) + { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @member {PIXI.BaseTexture} + */ + this.baseTexture = baseTexture; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @member {PIXI.Rectangle} + */ + this._frame = frame; + + /** + * This is the trimmed area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + this.valid = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @member {boolean} + */ + this.requiresUpdate = false; + + /** + * The WebGL UV data cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + this._uvs = null; + + /** + * This is the area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + this.orig = orig || frame;//new math.Rectangle(0, 0, 1, 1); + + this._rotate = +(rotate || 0); + + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + this._rotate = 2; + } else { + if (this._rotate % 2 !== 0) { + throw 'attempt to use diamond-shaped UVs. If you are sure, set rotation manually'; + } + } + + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { + frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + + // if there is no frame we should monitor for any base texture changes.. + baseTexture.on('update', this.onBaseTextureUpdated, this); + } + this.frame = frame; + } + else + { + baseTexture.once('loaded', this.onBaseTextureLoaded, this); + } + + /** + * Fired when the texture is updated. This happens if the frame or the baseTexture is updated. + * + * @event update + * @memberof PIXI.Texture# + * @protected + */ + + + this._updateID = 0; +} + +Texture.prototype = Object.create(EventEmitter.prototype); +Texture.prototype.constructor = Texture; +module.exports = Texture; + +Object.defineProperties(Texture.prototype, { + /** + * The frame specifies the region of the base texture that this texture uses. + * + * @member {PIXI.Rectangle} + * @memberof PIXI.Texture# + */ + frame: { + get: function () + { + return this._frame; + }, + set: function (frame) + { + this._frame = frame; + + this.noFrame = false; + + if (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height) + { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); + } + + //this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + this.valid = frame && frame.width && frame.height && this.baseTexture.hasLoaded; + + if (!this.trim && !this.rotate) + { + this.orig = frame; + } + + if (this.valid) + { + this._updateUvs(); + } + } + }, + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.GroupD8} for explanation + * + * @member {number} + */ + rotate: { + get: function () + { + return this._rotate; + }, + set: function (rotate) + { + this._rotate = rotate; + if (this.valid) + { + this._updateUvs(); + } + } + }, + + /** + * The width of the Texture in pixels. + * + * @member {number} + */ + width: { + get: function() { + return this.orig ? this.orig.width : 0; + } + }, + + /** + * The height of the Texture in pixels. + * + * @member {number} + */ + height: { + get: function() { + return this.orig ? this.orig.height : 0; + } + } +}); + +/** + * Updates this texture on the gpu. + * + */ +Texture.prototype.update = function () +{ + this.baseTexture.update(); +}; + +/** + * Called when the base texture is loaded + * + * @private + */ +Texture.prototype.onBaseTextureLoaded = function (baseTexture) +{ + this._updateID++; + + // TODO this code looks confusing.. boo to abusing getters and setterss! + if (this.noFrame) + { + this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } + else + { + this.frame = this._frame; + } + + this.baseTexture.on('update', this.onBaseTextureUpdated, this); + this.emit('update', this); + +}; + +/** + * Called when the base texture is updated + * + * @private + */ +Texture.prototype.onBaseTextureUpdated = function (baseTexture) +{ + this._updateID++; + + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + + this.emit('update', this); +}; + +/** + * Destroys this texture + * + * @param [destroyBase=false] {boolean} Whether to destroy the base texture as well + */ +Texture.prototype.destroy = function (destroyBase) +{ + if (this.baseTexture) + { + + if (destroyBase) + { + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destoryed too.. + if(utils.TextureCache[this.baseTexture.imageUrl]) + { + delete utils.TextureCache[this.baseTexture.imageUrl]; + } + + this.baseTexture.destroy(); + } + + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); + + this.baseTexture = null; + } + + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + + this.valid = false; + + this.off('dispose', this.dispose, this); + this.off('update', this.update, this); +}; + +/** + * Creates a new texture object that acts the same as this one. + * + * @return {PIXI.Texture} + */ +Texture.prototype.clone = function () +{ + return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); +}; + +/** + * Updates the internal WebGL UV cache. + * + * @protected + */ +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { + this._uvs = new TextureUvs(); + } + + this._uvs.set(this._frame, this.baseTexture, this.rotate); + + this._updateID++; +}; + +/** + * Helper function that creates a Texture object from the given image url. + * If the image is not in the texture cache it will be created and loaded. + * + * @static + * @param imageUrl {string} The image url of the texture + * @param [crossorigin] {boolean} Whether requests should be treated as crossorigin + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ + var texture = utils.TextureCache[imageUrl]; + + if (!texture) + { + texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); + utils.TextureCache[imageUrl] = texture; + } + + return texture; +}; + +/** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param frameId {string} The frame Id of the texture in the cache + * @return {PIXI.Texture} The newly created texture + */ +Texture.fromFrame = function (frameId) +{ + var texture = utils.TextureCache[frameId]; + + if (!texture) + { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return texture; +}; + +/** + * Helper function that creates a new Texture based on the given canvas element. + * + * @static + * @param canvas {HTMLCanvasElement} The canvas element source of the texture + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ +Texture.fromCanvas = function (canvas, scaleMode) +{ + return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); +}; + +/** + * Helper function that creates a new Texture based on the given video element. + * + * @static + * @param video {HTMLVideoElement|string} The URL or actual element of the video + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ +Texture.fromVideo = function (video, scaleMode) +{ + if (typeof video === 'string') + { + return Texture.fromVideoUrl(video, scaleMode); + } + else + { + return new Texture(VideoBaseTexture.fromVideo(video, scaleMode)); + } +}; + +/** + * Helper function that creates a new Texture based on the video url. + * + * @static + * @param videoUrl {string} URL of the video + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ +Texture.fromVideoUrl = function (videoUrl, scaleMode) +{ + return new Texture(VideoBaseTexture.fromUrl(videoUrl, scaleMode)); +}; + +/** + * Helper function that creates a new Texture based on the source you provide. + * The soucre can be - frame id, image url, video url, canvae element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ +Texture.from = function (source) +{ + //TODO auto detect cross origin.. + //TODO pass in scale mode? + if(typeof source === 'string') + { + var texture = utils.TextureCache[source]; + + if (!texture) + { + // check if its a video.. + var isVideo = source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/) !== null; + if(isVideo) + { + return Texture.fromVideoUrl(source); + } + + return Texture.fromImage(source); + } + + return texture; + } + else if(source instanceof HTMLCanvasElement) + { + return Texture.fromCanvas(source); + } + else if(source instanceof HTMLVideoElement) + { + return Texture.fromVideo(source); + } + else if(source instanceof BaseTexture) + { + return new Texture(BaseTexture); + } + else + { + // lets assume its a texture! + return source; + } +}; + + +/** + * Adds a texture to the global utils.TextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param texture {PIXI.Texture} The Texture to add to the cache. + * @param id {string} The id that the texture will be stored against. + */ +Texture.addTextureToCache = function (texture, id) +{ + utils.TextureCache[id] = texture; +}; + +/** + * Remove a texture from the global utils.TextureCache. + * + * @static + * @param id {string} The id of the texture to be removed + * @return {PIXI.Texture} The texture that was removed + */ +Texture.removeTextureFromCache = function (id) +{ + var texture = utils.TextureCache[id]; + + delete utils.TextureCache[id]; + delete utils.BaseTextureCache[id]; + + return texture; +}; + +/** + * An empty texture, used often to not have to create multiple empty textures. + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.EMPTY = new Texture(new BaseTexture()); +Texture.EMPTY.destroy = function() {}; +Texture.EMPTY.on = function() {}; +Texture.EMPTY.once = function() {}; +Texture.EMPTY.emit = function() {}; + + +},{"../math":102,"../utils":151,"./BaseTexture":142,"./TextureUvs":145,"./VideoBaseTexture":146,"eventemitter3":32}],145:[function(require,module,exports){ + +/** + * A standard object to store the Uvs of a texture + * + * @class + * @private + * @memberof PIXI + */ +function TextureUvs() +{ + this.x0 = 0; + this.y0 = 0; + + this.x1 = 1; + this.y1 = 0; + + this.x2 = 1; + this.y2 = 1; + + this.x3 = 0; + this.y3 = 1; + + this.uvsUint32 = new Uint32Array(4); +} + +module.exports = TextureUvs; + +var GroupD8 = require('../math/GroupD8'); + +/** + * Sets the texture Uvs based on the given frame information + * @param frame {PIXI.Rectangle} + * @param baseFrame {PIXI.Rectangle} + * @param rotate {number} Rotation of frame, see {@link PIXI.GroupD8} + * @private + */ +TextureUvs.prototype.set = function (frame, baseFrame, rotate) +{ + var tw = baseFrame.width; + var th = baseFrame.height; + + if(rotate) + { + //width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + //coordinates of center + var cX = frame.x / tw + w2; + var cY = frame.y / th + h2; + rotate = GroupD8.add(rotate, GroupD8.NW); //NW is top-left corner + this.x0 = cX + w2 * GroupD8.uX(rotate); + this.y0 = cY + h2 * GroupD8.uY(rotate); + rotate = GroupD8.add(rotate, 2); //rotate 90 degrees clockwise + this.x1 = cX + w2 * GroupD8.uX(rotate); + this.y1 = cY + h2 * GroupD8.uY(rotate); + rotate = GroupD8.add(rotate, 2); + this.x2 = cX + w2 * GroupD8.uX(rotate); + this.y2 = cY + h2 * GroupD8.uY(rotate); + rotate = GroupD8.add(rotate, 2); + this.x3 = cX + w2 * GroupD8.uX(rotate); + this.y3 = cY + h2 * GroupD8.uY(rotate); + } + else + { + + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + + this.uvsUint32[0] = (((this.y0 * 65535) & 0xFFFF) << 16) | ((this.x0 * 65535) & 0xFFFF); + this.uvsUint32[1] = (((this.y1 * 65535) & 0xFFFF) << 16) | ((this.x1 * 65535) & 0xFFFF); + this.uvsUint32[2] = (((this.y2 * 65535) & 0xFFFF) << 16) | ((this.x2 * 65535) & 0xFFFF); + this.uvsUint32[3] = (((this.y3 * 65535) & 0xFFFF) << 16) | ((this.x3 * 65535) & 0xFFFF); +}; + +},{"../math/GroupD8":98}],146:[function(require,module,exports){ +var BaseTexture = require('./BaseTexture'), + utils = require('../utils'); + +/** + * A texture of a [playing] Video. + * + * Video base textures mimic Pixi BaseTexture.from.... method in their creation process. + * + * This can be used in several ways, such as: + * + * ```js + * var texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4'); + * + * var texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' }); + * + * var texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']); + * + * var texture = PIXI.VideoBaseTexture.fromUrls([ + * { src: '/video.webm', mime: 'video/webm' }, + * { src: '/video.mp4', mime: 'video/mp4' } + * ]); + * ``` + * + * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/). + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + * @param source {HTMLVideoElement} Video source + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + */ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { + throw new Error('No video source element specified.'); + } + + // hook in here to check if video is already available. + // BaseTexture looks for a source.complete boolean, plus width & height. + + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { + source.complete = true; + } + + BaseTexture.call(this, source, scaleMode); + + /** + * Should the base texture automatically update itself, set to true by default + * + * @member {boolean} + * @default true + */ + this.autoUpdate = false; + + this._onUpdate = this._onUpdate.bind(this); + this._onCanPlay = this._onCanPlay.bind(this); + + if (!source.complete) + { + source.addEventListener('canplay', this._onCanPlay); + source.addEventListener('canplaythrough', this._onCanPlay); + + // started playing.. + source.addEventListener('play', this._onPlayStart.bind(this)); + source.addEventListener('pause', this._onPlayStop.bind(this)); + } + + this.__loaded = false; +} + +VideoBaseTexture.prototype = Object.create(BaseTexture.prototype); +VideoBaseTexture.prototype.constructor = VideoBaseTexture; +module.exports = VideoBaseTexture; + +/** + * The internal update loop of the video base texture, only runs when autoUpdate is set to true + * + * @private + */ +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { + window.requestAnimationFrame(this._onUpdate); + this.update(); + } +}; + +/** + * Runs the update loop when the video is ready to play + * + * @private + */ +VideoBaseTexture.prototype._onPlayStart = function () +{ + // Just in case the video has not recieved its can play even yet.. + if(!this.hasLoaded) + { + this._onCanPlay(); + } + + if (!this.autoUpdate) + { + window.requestAnimationFrame(this._onUpdate); + this.autoUpdate = true; + } +}; + +/** + * Fired when a pause event is triggered, stops the update loop + * + * @private + */ +VideoBaseTexture.prototype._onPlayStop = function () +{ + this.autoUpdate = false; +}; + +/** + * Fired when the video is loaded and ready to play + * + * @private + */ +VideoBaseTexture.prototype._onCanPlay = function () +{ + this.hasLoaded = true; + + if (this.source) + { + this.source.removeEventListener('canplay', this._onCanPlay); + this.source.removeEventListener('canplaythrough', this._onCanPlay); + + this.width = this.source.videoWidth; + this.height = this.source.videoHeight; + + this.source.play(); + + // prevent multiple loaded dispatches.. + if (!this.__loaded) + { + this.__loaded = true; + this.emit('loaded', this); + } + } +}; + +/** + * Destroys this texture + * + */ +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { + delete utils.BaseTextureCache[ this.source._pixiId ]; + delete this.source._pixiId; + } + + BaseTexture.prototype.destroy.call(this); +}; + +/** + * Mimic Pixi BaseTexture.from.... method. + * + * @static + * @param video {HTMLVideoElement} Video to create texture from + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { + video._pixiId = 'video_' + utils.uid(); + } + + var baseTexture = utils.BaseTextureCache[video._pixiId]; + + if (!baseTexture) + { + baseTexture = new VideoBaseTexture(video, scaleMode); + utils.BaseTextureCache[ video._pixiId ] = baseTexture; + } + + return baseTexture; +}; + +/** + * Helper function that creates a new BaseTexture based on the given video element. + * This BaseTexture can then be used to create a texture + * + * @static + * @param videoSrc {string|object|string[]|object[]} The URL(s) for the video. + * @param [videoSrc.src] {string} One of the source urls for the video + * @param [videoSrc.mime] {string} The mimetype of the video (e.g. 'video/mp4'). If not specified + * the url's extension will be used as the second part of the mime type. + * @param scaleMode {number} See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ + var video = document.createElement('video'); + + // array of objects or strings + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { + video.appendChild(createSource(videoSrc[i].src || videoSrc[i], videoSrc[i].mime)); + } + } + // single object or string + else + { + video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); + } + + video.load(); + video.play(); + + return VideoBaseTexture.fromVideo(video, scaleMode); +}; + +VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; + +function createSource(path, type) +{ + if (!type) + { + type = 'video/' + path.substr(path.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = path; + source.type = type; + + return source; +} + +},{"../utils":151,"./BaseTexture":142}],147:[function(require,module,exports){ +var CONST = require('../const'), + EventEmitter = require('eventemitter3'), + // Internal event used by composed emitter + TICK = 'tick'; + +/** + * A Ticker class that runs an update loop that other objects listen to. + * This class is composed around an EventEmitter object to add listeners + * meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, + * e.g. When the ticker is started and the emitter has listeners. + * + * @class + * @memberof PIXI.ticker + */ +function Ticker() +{ + var _this = this; + + /** + * Internal tick method bound to ticker instance. + * This is because in early 2015, Function.bind + * is still 60% slower in high performance scenarios. + * Also separating frame requests from update method + * so listeners may be called at any time and with + * any animation API, just invoke ticker.update(time). + * + * @private + */ + this._tick = function _tick(time) { + + _this._requestId = null; + + if (_this.started) + { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._emitter.listeners(TICK, true)) + { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + + /** + * Internal emitter used to fire 'tick' event + * @private + */ + this._emitter = new EventEmitter(); + + /** + * Internal current frame request ID + * @private + */ + this._requestId = null; + + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + * @private + */ + this._maxElapsedMS = 100; + + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.ticker.Ticker#start} automatically + * when a listener is added. + * + * @member {boolean} + * @default false + */ + this.autoStart = false; + + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS} + * and is scaled with {@link PIXI.ticker.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * + * @member {number} + * @default 1 + */ + this.deltaTime = 1; + + /** + * Time elapsed in milliseconds from last frame to this frame. + * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime} + * is based, this value is neither capped nor scaled. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default 1 / TARGET_FPMS + */ + this.elapsedMS = 1 / CONST.TARGET_FPMS; // default to target frame time + + /** + * The last time {@link PIXI.ticker.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default 0 + */ + this.lastTime = 0; + + /** + * Factor of current {@link PIXI.ticker.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + * + * @member {number} + * @default 1 + */ + this.speed = 1; + + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.ticker.Ticker#start} has been called. + * `false` if {@link PIXI.ticker.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.ticker.Ticker#autoStart} being `true` + * and a listener is added. + * + * @member {boolean} + * @default false + */ + this.started = false; +} + +Object.defineProperties(Ticker.prototype, { + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.ticker.Ticker#speed}, which is specific + * to scaling {@link PIXI.ticker.Ticker#deltaTime}. + * + * @memberof PIXI.ticker.Ticker# + * @readonly + */ + FPS: { + get: function() + { + return 1000 / this.elapsedMS; + } + }, + + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.ticker.Ticker#update}. + * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.TARGET_FPMS * 1000`. + * + * @memberof PIXI.ticker.Ticker# + * @default 10 + */ + minFPS: { + get: function() + { + return 1000 / this._maxElapsedMS; + }, + set: function(fps) + { + // Clamp: 0 to TARGET_FPMS + var minFPMS = Math.min(Math.max(0, fps) / 1000, CONST.TARGET_FPMS); + this._maxElapsedMS = 1 / minFPMS; + } + } +}); + +/** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * + * @private + */ +Ticker.prototype._requestIfNeeded = function _requestIfNeeded() +{ + if (this._requestId === null && this._emitter.listeners(TICK, true)) + { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._requestId = requestAnimationFrame(this._tick); + } +}; + +/** + * Conditionally cancels a pending animation frame. + * + * @private + */ +Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() +{ + if (this._requestId !== null) + { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } +}; + +/** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * + * @private + */ +Ticker.prototype._startIfPossible = function _startIfPossible() +{ + if (this.started) + { + this._requestIfNeeded(); + } + else if (this.autoStart) + { + this.start(); + } +}; + +/** + * Calls {@link module:eventemitter3.EventEmitter#on} internally for the + * internal 'tick' event. It checks if the emitter has listeners, + * and if so it requests a new animation frame at this point. + * + * @param fn {Function} The listener function to be added for updates + * @param [context] {Function} The listener context + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ +Ticker.prototype.add = function add(fn, context) +{ + this._emitter.on(TICK, fn, context); + + this._startIfPossible(); + + return this; +}; + +/** + * Calls {@link module:eventemitter3.EventEmitter#once} internally for the + * internal 'tick' event. It checks if the emitter has listeners, + * and if so it requests a new animation frame at this point. + * + * @param fn {Function} The listener function to be added for one update + * @param [context] {Function} The listener context + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ +Ticker.prototype.addOnce = function addOnce(fn, context) +{ + this._emitter.once(TICK, fn, context); + + this._startIfPossible(); + + return this; +}; + +/** + * Calls {@link module:eventemitter3.EventEmitter#off} internally for 'tick' event. + * It checks if the emitter has listeners for 'tick' event. + * If it does, then it cancels the animation frame. + * + * @param [fn] {Function} The listener function to be removed + * @param [context] {Function} The listener context to be removed + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ +Ticker.prototype.remove = function remove(fn, context) +{ + this._emitter.off(TICK, fn, context); + + if (!this._emitter.listeners(TICK, true)) + { + this._cancelIfNeeded(); + } + + return this; +}; + +/** + * Starts the ticker. If the ticker has listeners + * a new animation frame is requested at this point. + */ +Ticker.prototype.start = function start() +{ + if (!this.started) + { + this.started = true; + this._requestIfNeeded(); + } +}; + +/** + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. + */ +Ticker.prototype.stop = function stop() +{ + if (this.started) + { + this.started = false; + this._cancelIfNeeded(); + } +}; + +/** + * Triggers an update. An update entails setting the + * current {@link PIXI.ticker.Ticker#elapsedMS}, + * the current {@link PIXI.ticker.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.ticker.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * + * @param [currentTime=performance.now()] {number} the current time of execution + */ +Ticker.prototype.update = function update(currentTime) +{ + var elapsedMS; + + // Allow calling update directly with default currentTime. + currentTime = currentTime || performance.now(); + + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + + if (currentTime > this.lastTime) + { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) + { + elapsedMS = this._maxElapsedMS; + } + + this.deltaTime = elapsedMS * CONST.TARGET_FPMS * this.speed; + + // Invoke listeners added to internal emitter + this._emitter.emit(TICK, this.deltaTime); + } + else + { + this.deltaTime = this.elapsedMS = 0; + } + + this.lastTime = currentTime; +}; + +module.exports = Ticker; + +},{"../const":78,"eventemitter3":32}],148:[function(require,module,exports){ +var Ticker = require('./Ticker'); + +/** + * The shared ticker instance used by {@link PIXI.extras.MovieClip}. + * and by {@link PIXI.interaction.InteractionManager}. + * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` + * for this instance. Please follow the examples for usage, including + * how to opt-out of auto-starting the shared ticker. + * + * @example + * var ticker = PIXI.ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * + * @example + * // You may use the shared ticker to render... + * var renderer = PIXI.autoDetectRenderer(800, 600); + * var stage = new PIXI.Container(); + * var interactionManager = PIXI.interaction.InteractionManager(renderer); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * + * @type {PIXI.ticker.Ticker} + * @memberof PIXI.ticker + */ +var shared = new Ticker(); +shared.autoStart = true; + +/** + * @namespace PIXI.ticker + */ +module.exports = { + shared: shared, + Ticker: Ticker +}; + +},{"./Ticker":147}],149:[function(require,module,exports){ +/** + * Generic Mask Stack data structure + * @class + * @memberof PIXI + * @param size {number} Number of quads + * @return {Uint16Array} indices + */ +var createIndicesForQuads = function (size) +{ + // the total number of indices in our array, there are 6 points per quad. + + var totalIndices = size * 6; + + var indices = new Uint16Array(totalIndices); + + // fill the indices with the quads to draw + for (var i=0, j=0; i < totalIndices; i += 6, j += 4) + { + indices[i + 0] = j + 0; + indices[i + 1] = j + 1; + indices[i + 2] = j + 2; + indices[i + 3] = j + 0; + indices[i + 4] = j + 2; + indices[i + 5] = j + 3; + } + + return indices; +}; + +module.exports = createIndicesForQuads; + +},{}],150:[function(require,module,exports){ +var tempAnchor; +var _url = require('url'); + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * @private + * @param url {string} The url to test. + * @param loc [location=window.location] {object} The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +var determineCrossOrigin = function (url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url.parse(tempAnchor.href); + + var samePort = (!url.port && loc.port === '') || (url.port === loc.port); + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +}; + +module.exports = determineCrossOrigin; + +},{"url":72}],151:[function(require,module,exports){ +var CONST = require('../const'); + +/** + * @namespace PIXI.utils + */ +var utils = module.exports = { + _uid: 0, + _saidHello: false, + + EventEmitter: require('eventemitter3'), + pluginTarget: require('./pluginTarget'), + + /** + * Gets the next unique identifier + * + * @memberof PIXI.utils + * @return {number} The next unique identifier to use. + */ + uid: function () + { + return ++utils._uid; + }, + + /** + * Converts a hex color number to an [R, G, B] array + * + * @memberof PIXI.utils + * @param hex {number} + * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one + * @return {number[]} An array representing the [R, G, B] of the color. + */ + hex2rgb: function (hex, out) + { + out = out || []; + + out[0] = (hex >> 16 & 0xFF) / 255; + out[1] = (hex >> 8 & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + + return out; + }, + + /** + * Converts a hex color number to a string. + * + * @memberof PIXI.utils + * @param hex {number} Number in hex + * @return {string} The string color. + */ + hex2string: function (hex) + { + hex = hex.toString(16); + hex = '000000'.substr(0, 6 - hex.length) + hex; + + return '#' + hex; + }, + + /** + * Converts a color as an [R, G, B] array to a hex number + * + * @memberof PIXI.utils + * @param rgb {number[]} rgb array + * @return {number} The color number + */ + rgb2hex: function (rgb) + { + return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); + }, + + + /** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * + * @memberof PIXI.utils + * @param url {string} the image path + * @return {number} resolution / device pixel ratio of an asset + */ + getResolutionOfUrl: function (url) + { + var resolution = CONST.RETINA_PREFIX.exec(url); + + if (resolution) + { + return parseFloat(resolution[1]); + } + + return 1; + }, + + /** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can set `PIXI.utils._saidHello = true;` + * so the library thinks it already said it. Keep in mind that doing that will forever + * makes you a jerk face. + * + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + * @constant + * @static + */ + sayHello: function (type) + { + if (utils._saidHello) + { + return; + } + + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { + var args = [ + '\n %c %c %c Pixi.js ' + CONST.VERSION + ' - ✰ ' + type + ' ✰ %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n', + 'background: #ff66a5; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'color: #ff66a5; background: #030307; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'background: #ffc3dc; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;' + ]; + + window.console.log.apply(console, args); //jshint ignore:line + } + else if (window.console) + { + window.console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line + } + + utils._saidHello = true; + }, + + /** + * Helper for checking for webgl support + * + * @memberof PIXI.utils + * @return {boolean} is webgl supported + */ + isWebGLSupported: function () + { + var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; + try + { + if (!window.WebGLRenderingContext) + { + return false; + } + + var canvas = document.createElement('canvas'), + gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); + + var success = !!(gl && gl.getContextAttributes().stencil); + if (gl) + { + var loseContext = gl.getExtension('WEBGL_lose_context'); + + if(loseContext) + { + loseContext.loseContext(); + } + } + gl = null; + + return success; + } + catch (e) + { + return false; + } + }, + + /** + * Returns sign of number + * + * @memberof PIXI.utils + * @param n {number} + * @returns {number} 0 if n is 0, -1 if n is negative, 1 if n i positive + */ + sign: function (n) + { + return n ? (n < 0 ? -1 : 1) : 0; + }, + + /** + * Remove a range of items from an array + * + * @memberof PIXI.utils + * @param {Array<*>} arr The target array + * @param {number} startIdx The index to begin removing from (inclusive) + * @param {number} removeCount How many items to remove + */ + removeItems: function (arr, startIdx, removeCount) + { + var length = arr.length; + + if (startIdx >= length || removeCount === 0) + { + return; + } + + removeCount = (startIdx+removeCount > length ? length-startIdx : removeCount); + for (var i = startIdx, len = length-removeCount; i < len; ++i) + { + arr[i] = arr[i + removeCount]; + } + + arr.length = len; + }, + + /** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ + TextureCache: {}, + + /** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ + BaseTextureCache: {} +}; + +},{"../const":78,"./pluginTarget":153,"eventemitter3":32}],152:[function(require,module,exports){ + + +var Device = require('ismobilejs'); + +var maxRecommendedTextures = function(max) +{ + + if(Device.tablet || Device.phone) + { + // check if the res is iphone 6 or higher.. + return 2; + } + else + { + // desktop should be ok + return max; + } +}; + +module.exports = maxRecommendedTextures; +},{"ismobilejs":33}],153:[function(require,module,exports){ +/** + * Mixins functionality to make an object have "plugins". + * + * @mixin + * @memberof PIXI.utils + * @param obj {object} The object to mix into. + * @example + * function MyObject() {} + * + * pluginTarget.mixin(MyObject); + */ +function pluginTarget(obj) +{ + obj.__plugins = {}; + + /** + * Adds a plugin to an object + * + * @param pluginName {string} The events that should be listed. + * @param ctor {Function} The constructor function for the plugin. + */ + obj.registerPlugin = function (pluginName, ctor) + { + obj.__plugins[pluginName] = ctor; + }; + + /** + * Instantiates all the plugins of this object + * + */ + obj.prototype.initPlugins = function () + { + this.plugins = this.plugins || {}; + + for (var o in obj.__plugins) + { + this.plugins[o] = new (obj.__plugins[o])(this); + } + }; + + /** + * Removes all the plugins of this object + * + */ + obj.prototype.destroyPlugins = function () + { + for (var o in this.plugins) + { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + + this.plugins = null; + }; +} + + +module.exports = { + /** + * Mixes in the properties of the pluginTarget into another object + * + * @param obj {object} The obj to mix into + */ + mixin: function mixin(obj) + { + pluginTarget(obj); + } +}; + +},{}],154:[function(require,module,exports){ +/*global console */ +var core = require('./core'), + mesh = require('./mesh'), + particles = require('./particles'), + extras = require('./extras'), + filters = require('./filters'); + +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code +function warn(msg) { + var stack = new Error().stack; + + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('Deprecation Warning: ', msg); + } + else { + // chop off the stack trace which includes pixi.js internal calls + stack = stack.split('\n').splice(3).join('\n'); + + if (console.groupCollapsed) { + console.groupCollapsed('%cDeprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', msg); + console.warn(stack); + console.groupEnd(); + } + else { + console.warn('Deprecation Warning: ', msg); + console.warn(stack); + } + } +} + +/** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ +core.SpriteBatch = function() +{ + throw new ReferenceError('SpriteBatch does not exist any more, please use the new ParticleContainer instead.'); +}; + +/** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ +core.AssetLoader = function() +{ + throw new ReferenceError('The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class.'); +}; + +Object.defineProperties(core, { + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + Stage: { + get: function() + { + warn('You do not need to use a PIXI Stage any more, you can simply render any container.'); + return core.Container; + } + }, + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + DisplayObjectContainer: { + get: function() + { + warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.'); + return core.Container; + } + }, + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + Strip: { + get: function() + { + warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.'); + return mesh.Mesh; + } + }, + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + Rope: { + get: function() + { + warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.'); + return mesh.Rope; + } + }, + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + ParticleContainer: { + get: function() { + warn('The ParticleContainer class has been moved to particles.ParticleContainer, please use particles.ParticleContainer from now on.'); + return particles.ParticleContainer; + } + }, + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + MovieClip: { + get: function() + { + warn('The MovieClip class has been moved to extras.MovieClip, please use extras.MovieClip from now on.'); + return extras.MovieClip; + } + }, + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + TilingSprite: { + get: function() + { + warn('The TilingSprite class has been moved to extras.TilingSprite, please use extras.TilingSprite from now on.'); + return extras.TilingSprite; + } + }, + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + BitmapText: { + get: function() + { + warn('The BitmapText class has been moved to extras.BitmapText, please use extras.BitmapText from now on.'); + return extras.BitmapText; + } + }, + + /** + * @class + * @private + * @name blendModes + * @memberof PIXI + * @see PIXI.BLEND_MODES + * @deprecated since version 3.0.0 + */ + blendModes: { + get: function() + { + warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.'); + return core.BLEND_MODES; + } + }, + + /** + * @class + * @private + * @name scaleModes + * @memberof PIXI + * @see PIXI.SCALE_MODES + * @deprecated since version 3.0.0 + */ + scaleModes: { + get: function() + { + warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.'); + return core.SCALE_MODES; + } + }, + + /** + * @class + * @private + * @name BaseTextureCache + * @memberof PIXI + * @see PIXI.utils.BaseTextureCache + * @deprecated since version 3.0.0 + */ + BaseTextureCache: { + get: function () + { + warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, please use utils.BaseTextureCache from now on.'); + return core.utils.BaseTextureCache; + } + }, + + /** + * @class + * @private + * @name TextureCache + * @memberof PIXI + * @see PIXI.utils.TextureCache + * @deprecated since version 3.0.0 + */ + TextureCache: { + get: function () + { + warn('The TextureCache class has been moved to utils.TextureCache, please use utils.TextureCache from now on.'); + return core.utils.TextureCache; + } + }, + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + math: { + get: function () + { + warn('The math namespace is deprecated, please access members already accessible on PIXI.'); + return core; + } + }, + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function() + { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + return core.Filter; + } + }, + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + TransformManual: { + get: function() + { + warn('TransformManual has been renamed to TransformBase, please update your pixi-spine'); + return core.TransformBase; + } + } +}); + +core.DisplayObject.prototype.generateTexture = function(renderer, scaleMode, resolution) +{ + warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); + return renderer.generateTexture(this, scaleMode, resolution); +}; + + +core.Graphics.prototype.generateTexture = function(scaleMode, resolution) +{ + warn('graphics generate texture has moved to the renderer. Or to render a graphics to a texture using canvas please use generateCanvasTexture'); + return this.generateCanvasTexture(scaleMode, resolution); +}; + +core.RenderTexture.prototype.render = function(displayObject, matrix, clear, updateTransform) +{ + this.legacyRenderer.render(displayObject, this, clear, matrix, !updateTransform); + warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)'); +}; + +core.RenderTexture.prototype.getImage = function(target) +{ + warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); + return this.legacyRenderer.extract.image(target); +}; + +core.RenderTexture.prototype.getBase64 = function(target) +{ + warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); + return this.legacyRenderer.extract.base64(target); +}; + +core.RenderTexture.prototype.getCanvas = function(target) +{ + warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); + return this.legacyRenderer.extract.canvas(target); +}; + +core.RenderTexture.prototype.getPixels = function(target) +{ + warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); + return this.legacyRenderer.pixels(target); +}; + + + +/** + * @method + * @private + * @name PIXI.Sprite#setTexture + * @see PIXI.Sprite#texture + * @deprecated since version 3.0.0 + */ +core.Sprite.prototype.setTexture = function(texture) +{ + this.texture = texture; + warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;'); +}; + + + +/** + * @method + * @name PIXI.extras.BitmapText#setText + * @see PIXI.extras.BitmapText#text + * @deprecated since version 3.0.0 + */ +extras.BitmapText.prototype.setText = function(text) +{ + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';'); +}; + +/** + * @method + * @name PIXI.Text#setText + * @see PIXI.Text#text + * @deprecated since version 3.0.0 + */ +core.Text.prototype.setText = function(text) +{ + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';'); +}; + +/** + * @method + * @name PIXI.Text#setStyle + * @see PIXI.Text#style + * @deprecated since version 3.0.0 + */ +core.Text.prototype.setStyle = function(style) +{ + this.style = style; + warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;'); +}; + +Object.defineProperties(core.TextStyle.prototype, { + /** + * Set all properties of a font as a single string + * + * @name PIXI.TextStyle#font + * @deprecated since version 4.0.0 + */ + font: { + get: function () + { + warn('text style property \'font\' is now deprecated, please use the \'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + var fontSizeString = (typeof this._fontSize === 'number') ? this._fontSize + 'px' : this._fontSize; + return this._fontStyle + ' ' + this._fontVariant + ' ' + this._fontWeight + ' ' + fontSizeString + ' ' + this._fontFamily; + }, + set: function (font) + { + warn('text style property \'font\' is now deprecated, please use the \'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + + // can work out fontStyle from search of whole string + if ( font.indexOf('italic') > 1 ) + { + this._fontStyle = 'italic'; + } + else if ( font.indexOf('oblique') > -1 ) + { + this._fontStyle = 'oblique'; + } + else + { + this._fontStyle = 'normal'; + } + + // can work out fontVariant from search of whole string + if ( font.indexOf('small-caps') > -1 ) + { + this._fontVariant = 'small-caps'; + } + else + { + this._fontVariant = 'normal'; + } + + // fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units + var splits = font.split(' '); + var i; + var fontSizeIndex = -1; + + this._fontSize = 26; + for ( i = 0; i < splits.length; ++i ) + { + if ( splits[i].match( /(px|pt|em|%)/ ) ) + { + fontSizeIndex = i; + this._fontSize = splits[i]; + break; + } + } + + // we can now search for fontWeight as we know it must occur before the fontSize + this._fontWeight = 'normal'; + for ( i = 0; i < fontSizeIndex; ++i ) + { + if ( splits[i].match( /(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/ ) ) + { + this._fontWeight = splits[i]; + break; + } + } + + // and finally join everything together after the fontSize in case the font family has multiple words + if ( fontSizeIndex > -1 && fontSizeIndex < splits.length-1 ) + { + this._fontFamily = ''; + for ( i = fontSizeIndex + 1; i < splits.length; ++i ) + { + this._fontFamily += splits[i] + ' '; + } + + this._fontFamily = this._fontFamily.slice(0, -1); + } + else + { + this._fontFamily = 'Arial'; + } + + this.styleID++; + } + } +} ); + +/** + * @method + * @name PIXI.Texture#setFrame + * @see PIXI.Texture#setFrame + * @deprecated since version 3.0.0 + */ +core.Texture.prototype.setFrame = function(frame) +{ + this.frame = frame; + warn('setFrame is now deprecated, please use the frame property, e.g : myTexture.frame = frame;'); +}; + +Object.defineProperties(filters, { + + /** + * @class + * @private + * @name PIXI.filters.AbstractFilter + * @see PIXI.AbstractFilter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function() + { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + return core.AbstractFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.SpriteMaskFilter + * @see PIXI.SpriteMaskFilter + * @deprecated since version 3.0.6 + */ + SpriteMaskFilter: { + get: function() + { + warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.'); + return core.SpriteMaskFilter; + } + } +}); + +/** + * @method + * @name PIXI.utils.uuid + * @see PIXI.utils.uid + * @deprecated since version 3.0.6 + */ +core.utils.uuid = function () +{ + warn('utils.uuid() is deprecated, please use utils.uid() from now on.'); + return core.utils.uid(); +}; + +/** + * @method + * @name PIXI.utils.canUseNewCanvasBlendModes + * @see PIXI.CanvasTinter + * @deprecated + */ +core.utils.canUseNewCanvasBlendModes = function() { + warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on'); + return core.CanvasTinter.canUseMultiply; +}; +},{"./core":97,"./extras":164,"./filters":175,"./mesh":191,"./particles":194}],155:[function(require,module,exports){ +var core = require('../../core'), + tempRect = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers + * @class + * @memberof PIXI + * @param renderer {PIXI.CanvasRenderer} A reference to the current renderer + */ +function CanvasExtract(renderer) +{ + this.renderer = renderer; + renderer.extract = this; +} + + +CanvasExtract.prototype.constructor = CanvasExtract; +module.exports = CanvasExtract; + +/** + * Will return a HTML Image of the target + * + * @param target {PIXI.DisplayObject|PIXI.RenderTexture} A displayObject or renderTexture to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ +CanvasExtract.prototype.image = function ( target ) +{ + var image = new Image(); + image.src = this.base64( target ); + return image; +}; + +/** + * Will return a a base64 encoded string of this target. It works by calling CanvasExtract.getCanvas and then running toDataURL on that. + * @param target {PIXI.DisplayObject|PIXI.RenderTexture} A displayObject or renderTexture to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ +CanvasExtract.prototype.base64 = function ( target ) +{ + return this.canvas( target ).toDataURL(); +}; + +/** + * Creates a Canvas element, renders this target to it and then returns it. + * @param target {PIXI.DisplayObject|PIXI.RenderTexture} A displayObject or renderTexture to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ +CanvasExtract.prototype.canvas = function ( target ) +{ + var renderer = this.renderer; + var context; + var resolution; + var frame; + var renderTexture; + + if(target) + { + if(target instanceof core.RenderTexture) + { + renderTexture = target; + } + else + { + renderTexture = renderer.generateTexture(target); + } + } + + if(renderTexture) + { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } + else + { + context = renderer.rootContext; + resolution = renderer.rootResolution; + + frame = tempRect; + frame.width = this.renderer.width; + frame.height = this.renderer.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); + canvasBuffer.context.putImageData(canvasData, 0, 0); + + + // send the canvas back.. + return canvasBuffer.canvas; +}; + +/** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA order, with integer values between 0 and 255 (included). + * @param target {PIXI.DisplayObject|PIXI.RenderTexture} A displayObject or renderTexture to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ +CanvasExtract.prototype.pixels = function ( target ) +{ + var renderer = this.renderer; + var context; + var resolution; + var frame; + var renderTexture; + + if(target) + { + if(target instanceof core.RenderTexture) + { + renderTexture = target; + } + else + { + renderTexture = renderer.generateTexture(target); + } + } + + if(renderTexture) + { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } + else + { + context = renderer.rootContext; + resolution = renderer.rootResolution; + + frame = tempRect; + frame.width = renderer.width; + frame.height = renderer.height; + } + + return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; +}; + +/** + * Destroys the extract + * + */ +CanvasExtract.prototype.destroy = function () +{ + this.renderer.extract = null; + this.renderer = null; +}; + +core.CanvasRenderer.registerPlugin('extract', CanvasExtract); + +},{"../../core":97}],156:[function(require,module,exports){ + +module.exports = { + webGL: require('./webgl/WebGLExtract'), + canvas: require('./canvas/CanvasExtract') +}; +},{"./canvas/CanvasExtract":155,"./webgl/WebGLExtract":157}],157:[function(require,module,exports){ +var core = require('../../core'), + tempRect = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers + * @class + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} A reference to the current renderer + */ +function WebGLExtract(renderer) +{ + this.renderer = renderer; + renderer.extract = this; +} + + +WebGLExtract.prototype.constructor = WebGLExtract; +module.exports = WebGLExtract; + +/** + * Will return a HTML Image of the target + * + * @param target {PIXI.DisplayObject|PIXI.RenderTexture} A displayObject or renderTexture to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ +WebGLExtract.prototype.image = function ( target ) +{ + var image = new Image(); + image.src = this.base64( target ); + return image; +}; + +/** + * Will return a a base64 encoded string of this target. It works by calling WebGLExtract.getCanvas and then running toDataURL on that. + * @param target {PIXI.DisplayObject|PIXI.RenderTexture} A displayObject or renderTexture to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ +WebGLExtract.prototype.base64 = function ( target ) +{ + return this.canvas( target ).toDataURL(); +}; + +/** + * Creates a Canvas element, renders this target to it and then returns it. + * @param target {PIXI.DisplayObject|PIXI.RenderTexture} A displayObject or renderTexture to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ +WebGLExtract.prototype.canvas = function ( target ) +{ + var renderer = this.renderer; + var textureBuffer; + var resolution; + var frame; + var flipY = false; + var renderTexture; + + if(target) + { + if(target instanceof core.RenderTexture) + { + renderTexture = target; + } + else + { + renderTexture = this.renderer.generateTexture(target); + + } + } + + if(renderTexture) + { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + flipY = false; + } + else + { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + flipY = true; + + frame = tempRect; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + + } + + + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + + if(textureBuffer) + { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + + // set up an array of pixels + var webGLPixels = new Uint8Array(4 * width * height); + + // read pixels to the array + var gl = renderer.gl; + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webGLPixels); + + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + canvasData.data.set(webGLPixels); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // pulling pixels + if(flipY) + { + canvasBuffer.context.scale(1, -1); + canvasBuffer.context.drawImage(canvasBuffer.canvas, 0,-height); + } + } + + // send the canvas back.. + return canvasBuffer.canvas; +}; + +/** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA order, with integer values between 0 and 255 (included). + * @param target {PIXI.DisplayObject|PIXI.RenderTexture} A displayObject or renderTexture to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ +WebGLExtract.prototype.pixels = function ( target ) +{ + var renderer = this.renderer; + var textureBuffer; + var resolution; + var frame; + var renderTexture; + + if(target) + { + if(target instanceof core.RenderTexture) + { + renderTexture = target; + } + else + { + renderTexture = this.renderer.generateTexture(target); + } + } + + if(renderTexture) + { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + + } + else + { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + + frame = tempRect; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var webGLPixels = new Uint8Array(4 * width * height); + + if(textureBuffer) + { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + // read pixels to the array + var gl = renderer.gl; + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webGLPixels); + } + + return webGLPixels; +}; + +/** + * Destroys the extract + * + */ +WebGLExtract.prototype.destroy = function () +{ + this.renderer.extract = null; + this.renderer = null; +}; + +core.WebGLRenderer.registerPlugin('extract', WebGLExtract); + +},{"../../core":97}],158:[function(require,module,exports){ +var core = require('../core'), + ObservablePoint = require('../core/math/ObservablePoint'); + +/** + * A BitmapText object will create a line or multiple lines of text using bitmap font. To + * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using: + * + * A BitmapText can only be created when the font is loaded + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * var bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); + * ``` + * + * http://www.angelcode.com/products/bmfont/ for windows or + * http://www.bmglyph.com/ for mac. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.extras + * @param text {string} The copy that you would like the text to display + * @param style {object} The style parameters + * @param style.font {string|object} The font descriptor for the object, can be passed as a string of form + * "24px FontName" or "FontName" or as an object with explicit name/size properties. + * @param [style.font.name] {string} The bitmap font id + * @param [style.font.size] {number} The size of the font in pixels, e.g. 24 + * @param [style.align='left'] {string} Alignment for multiline text ('left', 'center' or 'right'), does not affect + * single line text + * @param [style.tint=0xFFFFFF] {number} The tint color + */ +function BitmapText(text, style) +{ + core.Container.call(this); + + style = style || {}; + + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + this.textWidth = 0; + + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + this.textHeight = 0; + + /** + * Private tracker for the letter sprite pool. + * + * @member {PIXI.Sprite[]} + * @private + */ + this._glyphs = []; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + this._font = { + tint: style.tint !== undefined ? style.tint : 0xFFFFFF, + align: style.align || 'left', + name: null, + size: 0 + }; + + /** + * Private tracker for the current font. + * + * @member {object} + * @private + */ + this.font = style.font; // run font setter + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + this._text = text; + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + */ + this.maxWidth = 0; + + /** + * The max line height. This is useful when trying to use the total height of the Text, ie: when trying to vertically align. + * + * @member {number} + */ + this.maxLineHeight = 0; + + /** + * Text anchor. read-only + * + * @member {PIXI.ObservablePoint} + * @private + */ + this._anchor = new ObservablePoint(this.makeDirty, this, 0, 0); + + /** + * The dirty state of this object. + * + * @member {boolean} + */ + this.dirty = false; + + this.updateText(); +} + +// constructor +BitmapText.prototype = Object.create(core.Container.prototype); +BitmapText.prototype.constructor = BitmapText; +module.exports = BitmapText; + +Object.defineProperties(BitmapText.prototype, { + /** + * The tint of the BitmapText object + * + * @member {number} + * @memberof PIXI.extras.BitmapText# + */ + tint: { + get: function () + { + return this._font.tint; + }, + set: function (value) + { + this._font.tint = (typeof value === 'number' && value >= 0) ? value : 0xFFFFFF; + + this.dirty = true; + } + }, + + /** + * The alignment of the BitmapText object + * + * @member {string} + * @default 'left' + * @memberof PIXI.extras.BitmapText# + */ + align: { + get: function () + { + return this._font.align; + }, + set: function (value) + { + this._font.align = value || 'left'; + + this.dirty = true; + } + }, + + /** + * The anchor sets the origin point of the text. + * The default is 0,0 this means the text's origin is the top left + * Setting the anchor to 0.5,0.5 means the text's origin is centered + * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner + * + * @member {PIXI.Point | number} + * @memberof PIXI.extras.BitmapText# + */ + anchor: { + get : function() { + return this._anchor; + }, + set: function(value) { + if (typeof value === 'number'){ + this._anchor.set(value); + } + else { + this._anchor.copy(value); + } + } + }, + + /** + * The font descriptor of the BitmapText object + * + * @member {string|object} + * @memberof PIXI.extras.BitmapText# + */ + font: { + get: function () + { + return this._font; + }, + set: function (value) + { + if (!value) { + return; + } + + if (typeof value === 'string') { + value = value.split(' '); + + this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); + this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; + } + else { + this._font.name = value.name; + this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); + } + + this.dirty = true; + } + }, + + /** + * The text of the BitmapText object + * + * @member {string} + * @memberof PIXI.extras.BitmapText# + */ + text: { + get: function () + { + return this._text; + }, + set: function (value) + { + value = value.toString() || ' '; + if (this._text === value) + { + return; + } + this._text = value; + this.dirty = true; + } + } +}); + +/** + * Renders text and updates it when needed + * + * @private + */ +BitmapText.prototype.updateText = function () +{ + var data = BitmapText.fonts[this._font.name]; + var pos = new core.Point(); + var prevCharCode = null; + var chars = []; + var lastLineWidth = 0; + var maxLineWidth = 0; + var lineWidths = []; + var line = 0; + var scale = this._font.size / data.size; + var lastSpace = -1; + var lastSpaceWidth = 0; + var maxLineHeight = 0; + + for (var i = 0; i < this.text.length; i++) + { + var charCode = this.text.charCodeAt(i); + + if(/(\s)/.test(this.text.charAt(i))){ + lastSpace = i; + lastSpaceWidth = lastLineWidth; + } + + if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) + { + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + if (lastSpace !== -1 && this.maxWidth > 0 && pos.x * scale > this.maxWidth) + { + core.utils.removeItems(chars, lastSpace, i - lastSpace); + i = lastSpace; + lastSpace = -1; + + lineWidths.push(lastSpaceWidth); + maxLineWidth = Math.max(maxLineWidth, lastSpaceWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + var charData = data.chars[charCode]; + + if (!charData) + { + continue; + } + + if (prevCharCode && charData.kerning[prevCharCode]) + { + pos.x += charData.kerning[prevCharCode]; + } + + chars.push({texture:charData.texture, line: line, charCode: charCode, position: new core.Point(pos.x + charData.xOffset, pos.y + charData.yOffset)}); + lastLineWidth = pos.x + (charData.texture.width + charData.xOffset); + pos.x += charData.xAdvance; + maxLineHeight = Math.max(maxLineHeight, (charData.yOffset + charData.texture.height)); + prevCharCode = charCode; + } + + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + + var lineAlignOffsets = []; + + for (i = 0; i <= line; i++) + { + var alignOffset = 0; + + if (this._font.align === 'right') + { + alignOffset = maxLineWidth - lineWidths[i]; + } + else if (this._font.align === 'center') + { + alignOffset = (maxLineWidth - lineWidths[i]) / 2; + } + + lineAlignOffsets.push(alignOffset); + } + + var lenChars = chars.length; + var tint = this.tint; + + for (i = 0; i < lenChars; i++) + { + var c = this._glyphs[i]; // get the next glyph sprite + + if (c) + { + c.texture = chars[i].texture; + } + else + { + c = new core.Sprite(chars[i].texture); + this._glyphs.push(c); + } + + c.position.x = (chars[i].position.x + lineAlignOffsets[chars[i].line]) * scale; + c.position.y = chars[i].position.y * scale; + c.scale.x = c.scale.y = scale; + c.tint = tint; + + if (!c.parent) + { + this.addChild(c); + } + } + + // remove unnecessary children. + for (i = lenChars; i < this._glyphs.length; ++i) + { + this.removeChild(this._glyphs[i]); + } + + this.textWidth = maxLineWidth * scale; + this.textHeight = (pos.y + data.lineHeight) * scale; + + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) + { + for (i = 0; i < lenChars; i++) + { + this._glyphs[i].x -= this.textWidth * this.anchor.x; + this._glyphs[i].y -= this.textHeight * this.anchor.y; + } + } + this.maxLineHeight = maxLineHeight * scale; +}; + +/** + * Updates the transform of this object + * + * @private + */ +BitmapText.prototype.updateTransform = function () +{ + this.validate(); + this.containerUpdateTransform(); +}; + +/** + * Validates text before calling parent's getLocalBounds + * + * @return {PIXI.Rectangle} The rectangular bounding area + */ + +BitmapText.prototype.getLocalBounds = function() +{ + this.validate(); + return core.Container.prototype.getLocalBounds.call(this); +}; + +/** + * Updates text when needed + * + * @private + */ +BitmapText.prototype.validate = function() +{ + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } +}; + +BitmapText.prototype.makeDirty = function() { + this.dirty = true; +}; + +BitmapText.fonts = {}; + +},{"../core":97,"../core/math/ObservablePoint":100}],159:[function(require,module,exports){ +var core = require('../core'); + +/** + * @typedef FrameObject + * @type {object} + * @property texture {PIXI.Texture} The {@link PIXI.Texture} of the frame + * @property time {number} the duration of the frame in ms + */ + +/** + * A MovieClip is a simple way to display an animation depicted by a list of textures. + * + * ```js + * var alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * var textureArray = []; + * + * for (var i=0; i < 4; i++) + * { + * var texture = PIXI.Texture.fromImage(alienImages[i]); + * textureArray.push(texture); + * }; + * + * var mc = new PIXI.MovieClip(textureArray); + * ``` + * + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + * @param textures {PIXI.Texture[]|FrameObject[]} an array of {@link PIXI.Texture} or frame objects that make up the animation + */ +function MovieClip(textures) +{ + core.Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture); + + /** + * @private + */ + this._textures = null; + + /** + * @private + */ + this._durations = null; + + this.textures = textures; + + /** + * The speed that the MovieClip will play at. Higher is faster, lower is slower + * + * @member {number} + * @default 1 + */ + this.animationSpeed = 1; + + /** + * Whether or not the movie clip repeats after playing. + * + * @member {boolean} + * @default true + */ + this.loop = true; + + /** + * Function to call when a MovieClip finishes playing + * + * @method + * @memberof PIXI.extras.MovieClip# + */ + this.onComplete = null; + + /** + * Elapsed time since animation has been started, used internally to display current texture + * + * @member {number} + * @private + */ + this._currentTime = 0; + + /** + * Indicates if the MovieClip is currently playing + * + * @member {boolean} + * @readonly + */ + this.playing = false; +} + +// constructor +MovieClip.prototype = Object.create(core.Sprite.prototype); +MovieClip.prototype.constructor = MovieClip; +module.exports = MovieClip; + +Object.defineProperties(MovieClip.prototype, { + /** + * totalFrames is the total number of frames in the MovieClip. This is the same as number of textures + * assigned to the MovieClip. + * + * @member {number} + * @memberof PIXI.extras.MovieClip# + * @default 0 + * @readonly + */ + totalFrames: { + get: function() + { + return this._textures.length; + } + }, + + /** + * The array of textures used for this MovieClip + * + * @member {PIXI.Texture[]} + * @memberof PIXI.extras.MovieClip# + * + */ + textures: { + get: function () + { + return this._textures; + }, + set: function (value) + { + if(value[0] instanceof core.Texture) + { + this._textures = value; + this._durations = null; + } + else + { + this._textures = []; + this._durations = []; + for(var i = 0; i < value.length; i++) + { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + } + }, + + /** + * The MovieClips current frame index + * + * @member {number} + * @memberof PIXI.extras.MovieClip# + * @readonly + */ + currentFrame: { + get: function () + { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + if (currentFrame < 0) + { + currentFrame += this._textures.length; + } + return currentFrame; + } + } + +}); + +/** + * Stops the MovieClip + * + */ +MovieClip.prototype.stop = function () +{ + if(!this.playing) + { + return; + } + + this.playing = false; + core.ticker.shared.remove(this.update, this); +}; + +/** + * Plays the MovieClip + * + */ +MovieClip.prototype.play = function () +{ + if(this.playing) + { + return; + } + + this.playing = true; + core.ticker.shared.add(this.update, this); +}; + +/** + * Stops the MovieClip and goes to a specific frame + * + * @param frameNumber {number} frame index to stop at + */ +MovieClip.prototype.gotoAndStop = function (frameNumber) +{ + this.stop(); + + this._currentTime = frameNumber; + + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; +}; + +/** + * Goes to a specific frame and begins playing the MovieClip + * + * @param frameNumber {number} frame index to start at + */ +MovieClip.prototype.gotoAndPlay = function (frameNumber) +{ + this._currentTime = frameNumber; + + this.play(); +}; + +/* + * Updates the object transform for rendering + * @private + */ +MovieClip.prototype.update = function (deltaTime) +{ + var elapsed = this.animationSpeed * deltaTime; + + if (this._durations !== null) + { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + + lag += elapsed / 60 * 1000; + + while (lag < 0) + { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + + var sign = Math.sign(this.animationSpeed * deltaTime); + this._currentTime = Math.floor(this._currentTime); + + while (lag >= this._durations[this.currentFrame]) + { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + + this._currentTime += lag / this._durations[this.currentFrame]; + } + else + { + this._currentTime += elapsed; + } + + if (this._currentTime < 0 && !this.loop) + { + this.gotoAndStop(0); + + if (this.onComplete) + { + this.onComplete(); + } + } + else if (this._currentTime >= this._textures.length && !this.loop) + { + this.gotoAndStop(this._textures.length - 1); + + if (this.onComplete) + { + this.onComplete(); + } + } + else + { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + } + +}; + +/* + * Stops the MovieClip and destroys it + * + */ +MovieClip.prototype.destroy = function ( ) +{ + this.stop(); + core.Sprite.prototype.destroy.call(this); +}; + +/** + * A short hand way of creating a movieclip from an array of frame ids + * + * @static + * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames + */ +MovieClip.fromFrames = function (frames) +{ + var textures = []; + + for (var i = 0; i < frames.length; ++i) + { + textures.push(core.Texture.fromFrame(frames[i])); + } + + return new MovieClip(textures); +}; + +/** + * A short hand way of creating a movieclip from an array of image ids + * + * @static + * @param images {string[]} the array of image urls the movieclip will use as its texture frames + */ +MovieClip.fromImages = function (images) +{ + var textures = []; + + for (var i = 0; i < images.length; ++i) + { + textures.push(core.Texture.fromImage(images[i])); + } + + return new MovieClip(textures); +}; + +},{"../core":97}],160:[function(require,module,exports){ +var core = require('../core'), + tempPoint = new core.Point(), + Texture = require('../core/textures/Texture'), + CanvasTinter = require('../core/sprites/canvas/CanvasTinter'), + TilingShader = require('./webgl/TilingShader'), + tempArray = new Float32Array(4); +/** + * A tiling sprite is a fast way of rendering a tiling image + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + * @param texture {PIXI.Texture} the texture of the tiling sprite + * @param width {number} the width of the tiling sprite + * @param height {number} the height of the tiling sprite + */ +function TilingSprite(texture, width, height) +{ + core.Sprite.call(this, texture); + + /** + * The scaling of the image that is being tiled + * + * @member {PIXI.Point} + */ + this.tileScale = new core.Point(1,1); + + + /** + * The offset position of the image that is being tiled + * + * @member {PIXI.Point} + */ + this.tilePosition = new core.Point(0,0); + + ///// private + + /** + * The with of the tiling sprite + * + * @member {number} + * @private + */ + this._width = width || 100; + + /** + * The height of the tiling sprite + * + * @member {number} + * @private + */ + this._height = height || 100; + + /** + * An internal WebGL UV cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + this._uvs = new core.TextureUvs(); + + this._canvasPattern = null; + + this._glDatas = []; +} + +TilingSprite.prototype = Object.create(core.Sprite.prototype); +TilingSprite.prototype.constructor = TilingSprite; +module.exports = TilingSprite; + + +Object.defineProperties(TilingSprite.prototype, { + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.extras.TilingSprite# + */ + width: { + get: function () + { + return this._width; + }, + set: function (value) + { + this._width = value; + } + }, + + /** + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.extras.TilingSprite# + */ + height: { + get: function () + { + return this._height; + }, + set: function (value) + { + this._height = value; + } + } +}); + +TilingSprite.prototype._onTextureUpdate = function () +{ + return; +}; + + +/** + * Renders the object using the WebGL renderer + * + * @param renderer {PIXI.WebGLRenderer} The renderer + * @private + */ +TilingSprite.prototype._renderWebGL = function (renderer) +{ + + // tweak our texture temporarily.. + var texture = this._texture; + + if(!texture || !texture._uvs) + { + return; + } + + // get rid of any thing that may be batching. + renderer.flush(); + + var gl = renderer.gl; + var glData = this._glDatas[renderer.CONTEXT_UID]; + + if(!glData) + { + glData = { + shader:new TilingShader(gl), + quad:new core.Quad(gl) + }; + + this._glDatas[renderer.CONTEXT_UID] = glData; + + glData.quad.initVao(glData.shader); + } + + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra space before transforming the sprite coords.. + var vertices = glData.quad.vertices; + + vertices[0] = vertices[6] = ( this._width ) * -this.anchor.x; + vertices[1] = vertices[3] = this._height * -this.anchor.y; + + vertices[2] = vertices[4] = ( this._width ) * (1-this.anchor.x); + vertices[5] = vertices[7] = this._height * (1-this.anchor.y); + + glData.quad.upload(); + + renderer.bindShader(glData.shader); + + var textureUvs = texture._uvs, + textureWidth = texture._frame.width, + textureHeight = texture._frame.height, + textureBaseWidth = texture.baseTexture.width, + textureBaseHeight = texture.baseTexture.height; + + var uPixelSize = glData.shader.uniforms.uPixelSize; + uPixelSize[0] = 1.0/textureBaseWidth; + uPixelSize[1] = 1.0/textureBaseHeight; + glData.shader.uniforms.uPixelSize = uPixelSize; + + var uFrame = glData.shader.uniforms.uFrame; + uFrame[0] = textureUvs.x0; + uFrame[1] = textureUvs.y0; + uFrame[2] = textureUvs.x1 - textureUvs.x0; + uFrame[3] = textureUvs.y2 - textureUvs.y0; + glData.shader.uniforms.uFrame = uFrame; + + var uTransform = glData.shader.uniforms.uTransform; + uTransform[0] = (this.tilePosition.x % (textureWidth * this.tileScale.x)) / this._width; + uTransform[1] = (this.tilePosition.y % (textureHeight * this.tileScale.y)) / this._height; + uTransform[2] = ( textureBaseWidth / this._width ) * this.tileScale.x; + uTransform[3] = ( textureBaseHeight / this._height ) * this.tileScale.y; + glData.shader.uniforms.uTransform = uTransform; + + glData.shader.uniforms.translationMatrix = this.worldTransform.toArray(true); + + var color = tempArray; + + core.utils.hex2rgb(this.tint, color); + color[3] = this.worldAlpha; + + glData.shader.uniforms.uColor = color; + + renderer.bindTexture(this._texture, 0); + + renderer.state.setBlendMode( this.blendMode ); + glData.quad.draw(); +}; + +/** + * Renders the object using the Canvas renderer + * + * @param renderer {PIXI.CanvasRenderer} a reference to the canvas renderer + * @private + */ +TilingSprite.prototype._renderCanvas = function (renderer) +{ + var texture = this._texture; + + if (!texture.baseTexture.hasLoaded) + { + return; + } + + var context = renderer.context, + transform = this.worldTransform, + resolution = renderer.resolution, + baseTexture = texture.baseTexture, + modX = (this.tilePosition.x / this.tileScale.x) % texture._frame.width, + modY = (this.tilePosition.y / this.tileScale.y) % texture._frame.height; + + // create a nice shiny pattern! + // TODO this needs to be refreshed if texture changes.. + if(!this._canvasPattern) + { + // cut an object from a spritesheet.. + var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height); + + // Tint the tiling sprite + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { + this.cachedTint = this.tint; + + this.tintedTexture = CanvasTinter.getTintedTexture(this, this.tint); + } + tempCanvas.context.drawImage(this.tintedTexture, 0, 0); + } + else + { + tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x, -texture._frame.y); + } + this._canvasPattern = tempCanvas.context.createPattern( tempCanvas.canvas, 'repeat' ); + } + + // set context state.. + context.globalAlpha = this.worldAlpha; + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + transform.tx * resolution, + transform.ty * resolution); + + // TODO - this should be rolled into the setTransform above.. + context.scale(this.tileScale.x,this.tileScale.y); + + context.translate(modX + (this.anchor.x * -this._width ), + modY + (this.anchor.y * -this._height)); + + // check blend mode + var compositeOperation = renderer.blendModes[this.blendMode]; + if (compositeOperation !== renderer.context.globalCompositeOperation) + { + context.globalCompositeOperation = compositeOperation; + } + + // fill the pattern! + context.fillStyle = this._canvasPattern; + context.fillRect(-modX, + -modY, + this._width / this.tileScale.x, + this._height / this.tileScale.y); + + + //TODO - pretty sure this can be deleted... + //context.translate(-this.tilePosition.x + (this.anchor.x * this._width), -this.tilePosition.y + (this.anchor.y * this._height)); + //context.scale(1 / this.tileScale.x, 1 / this.tileScale.y); +}; + + +/** + * Returns the framing rectangle of the sprite as a Rectangle object +* + * @return {PIXI.Rectangle} the framing rectangle + */ +TilingSprite.prototype.getBounds = function () +{ + var width = this._width; + var height = this._height; + + var w0 = width * (1-this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1-this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var minX, + maxX, + minY, + maxY; + + minX = x1; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1; + maxX = x2 > maxX ? x2 : maxX; + maxX = x3 > maxX ? x3 : maxX; + maxX = x4 > maxX ? x4 : maxX; + + maxY = y1; + maxY = y2 > maxY ? y2 : maxY; + maxY = y3 > maxY ? y3 : maxY; + maxY = y4 > maxY ? y4 : maxY; + + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; +}; + +/** + * Checks if a point is inside this tiling sprite + * @param point {PIXI.Point} the point to check + */ +TilingSprite.prototype.containsPoint = function( point ) +{ + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor.x; + var y1; + + if ( tempPoint.x > x1 && tempPoint.x < x1 + width ) + { + y1 = -height * this.anchor.y; + + if ( tempPoint.y > y1 && tempPoint.y < y1 + height ) + { + return true; + } + } + + return false; +}; + +/** + * Destroys this tiling sprite + * + */ +TilingSprite.prototype.destroy = function () { + core.Sprite.prototype.destroy.call(this); + + this.tileScale = null; + this._tileScaleOffset = null; + this.tilePosition = null; + + this._uvs = null; +}; + +/** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from +* @param width {number} the width of the tiling sprite + * @param height {number} the height of the tiling sprite + * @return {PIXI.Texture} The newly created texture + */ +TilingSprite.from = function (source,width,height) +{ + return new TilingSprite(Texture.from(source),width,height); +}; + + + +/** + * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param frameId {string} The frame Id of the texture in the cache + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId + * @param width {number} the width of the tiling sprite + * @param height {number} the height of the tiling sprite + * @return {PIXI.extras.TilingSprite} A new TilingSprite + */ +TilingSprite.fromFrame = function (frameId,width,height) +{ + var texture = core.utils.TextureCache[frameId]; + + if (!texture) + { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this); + } + + return new TilingSprite(texture,width,height); +}; + +/** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param imageId {string} The image url of the texture + * @param width {number} the width of the tiling sprite + * @param height {number} the height of the tiling sprite + * @param [crossorigin=(auto)] {boolean} if you want to specify the cross-origin parameter + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} if you want to specify the scale mode, see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id + */ +TilingSprite.fromImage = function (imageId, width, height, crossorigin, scaleMode) +{ + return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode),width,height); +}; + +},{"../core":97,"../core/sprites/canvas/CanvasTinter":135,"../core/textures/Texture":144,"./webgl/TilingShader":165}],161:[function(require,module,exports){ +var core = require('../core'), + DisplayObject = core.DisplayObject, + _tempMatrix = new core.Matrix(); + +DisplayObject.prototype._cacheAsBitmap = false; +DisplayObject.prototype._cacheData = false; + +// figured theres no point adding ALL the extra variables to prototype. +// this model can hold the information needed. This can also be generated on demand as +// most objects are not cached as bitmaps. +var CacheData = function(){ + + this.originalRenderWebGL = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + + this.originalUpdateTransform = null; + this.originalHitTest = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.sprite = null; +}; + + +Object.defineProperties(DisplayObject.prototype, { + + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can provide a performance benefit for complex static displayObjects. + * To remove simply set this property to 'false' + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function () + { + return this._cacheAsBitmap; + }, + set: function (value) + { + if (this._cacheAsBitmap === value) + { + return; + } + + this._cacheAsBitmap = value; + + var data; + + if (value) + { + + if(!this._cacheData) + { + this._cacheData = new CacheData(); + } + + data = this._cacheData; + + data.originalRenderWebGL = this.renderWebGL; + data.originalRenderCanvas = this.renderCanvas; + + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this._calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + + data.originalDestroy = this.destroy; + + data.originalContainsPoint = this.containsPoint; + + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + + + + this.renderWebGL = this._renderCachedWebGL; + this.renderCanvas = this._renderCachedCanvas; + + this.destroy = this._cacheAsBitmapDestroy; + + } + else + { + data = this._cacheData; + + if (data.sprite) + { + this._destroyCachedDisplayObject(); + } + + + this.renderWebGL = data.originalRenderWebGL; + this.renderCanvas = data.originalRenderCanvas; + this._calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + + this.destroy = data.originalDestroy; + + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + } + } +}); +/** +* Renders a cached version of the sprite with WebGL +* +* @param renderer {PIXI.WebGLRenderer} the WebGL renderer +* @private +*/ +DisplayObject.prototype._renderCachedWebGL = function (renderer) +{ + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) + { + return; + } + + this._initCachedDisplayObject( renderer ); + + this._cacheData.sprite._transformID = -1; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderWebGL(renderer); +}; + +/** +* Prepares the WebGL renderer to cache the sprite +* +* @param renderer {PIXI.WebGLRenderer} the WebGL renderer +* @private +*/ +DisplayObject.prototype._initCachedDisplayObject = function (renderer) +{ + if(this._cacheData && this._cacheData.sprite) + { + return; + } + + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + this.alpha = 1; + + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.currentRenderer.flush(); + //this.filters= []; + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds().clone(); + + // add some padding! + if(this._filters) + { + var padding = this._filters[0].padding; + + bounds.pad(padding); + } + + // for now we cache the current renderTarget that the webGL renderer is currently using. + // this could be more elegent.. + var cachedRenderTarget = renderer._activeRenderTarget; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + var stack = renderer.filterManager.filterStack; + + // this renderTexture will be used to store the cached DisplayObject + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + // need to set // + var m = _tempMatrix; + m.tx = -bounds.x; + m.ty = -bounds.y; + + // reset + this.transform.worldTransform.identity(); + + // set all properties to there original so we can render to a texture + this.renderWebGL = this._cacheData.originalRenderWebGL; + + + renderer.render(this, renderTexture, true, m, true); + // now restore the state be setting the new properties + + renderer.bindRenderTarget(cachedRenderTarget); + + renderer.filterManager.filterStack = stack; + + this.renderWebGL = this._renderCachedWebGL; + this.updateTransform = this.displayObjectUpdateTransform; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -( bounds.x / bounds.width ); + cachedSprite.anchor.y = -( bounds.y / bounds.height ); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + + //easy bounds.. + this._calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + + this._cacheData.sprite = cachedSprite; + + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + this.updateTransform(); + + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** +* Renders a cached version of the sprite with canvas +* +* @param renderer {PIXI.CanvasRenderer} the Canvas renderer +* @private +*/ +DisplayObject.prototype._renderCachedCanvas = function (renderer) +{ + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) + { + return; + } + + this._initCachedDisplayObjectCanvas( renderer ); + + this._cacheData.sprite.worldAlpha = this.worldAlpha; + + this._cacheData.sprite.renderCanvas(renderer); +}; + +//TODO this can be the same as the webGL verison.. will need to do a little tweaking first though.. +/** +* Prepares the Canvas renderer to cache the sprite +* +* @param renderer {PIXI.CanvasRenderer} the Canvas renderer +* @private +*/ +DisplayObject.prototype._initCachedDisplayObjectCanvas = function (renderer) +{ + if(this._cacheData && this._cacheData.sprite) + { + return; + } + + //get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(); + + var cacheAlpha = this.alpha; + this.alpha = 1; + + var cachedRenderTarget = renderer.context; + + var renderTexture = new core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + // need to set // + var m = _tempMatrix; + this.transform.worldTransform.copy(m); + m.invert(); + + m.tx -= bounds.x; + m.ty -= bounds.y; + + //m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + + //renderTexture.render(this, m, true); + renderer.render(this, renderTexture, true, m, false); + + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + + this.renderCanvas = this._renderCachedCanvas; + this._calculateBounds = this._calculateCachedBounds; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -( bounds.x / bounds.width ); + cachedSprite.anchor.y = -( bounds.y / bounds.height ); + cachedSprite._bounds = this._bounds; + cachedSprite.alpha = cacheAlpha; + + this.updateTransform(); + this.updateTransform = this.displayObjectUpdateTransform; + + this._cacheData.sprite = cachedSprite; + + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); + + +}; + +/** +* Calculates the bounds of the cached sprite +* +* @private +*/ +DisplayObject.prototype._calculateCachedBounds = function () +{ + return this._cacheData.sprite._calculateBounds(); +}; + +DisplayObject.prototype._getCachedLocalBounds = function () +{ + return this._cacheData.sprite.getLocalBounds(); +}; + +/** +* Destroys the cached sprite. +* +* @private +*/ +DisplayObject.prototype._destroyCachedDisplayObject = function () +{ + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; +}; + +DisplayObject.prototype._cacheAsBitmapDestroy = function () +{ + this.cacheAsBitmap = false; + this.destroy(); +}; + +},{"../core":97}],162:[function(require,module,exports){ +var core = require('../core'); + +/** + * The instance name of the object. + * + * @memberof PIXI.DisplayObject# + * @member {string} + */ +core.DisplayObject.prototype.name = null; + +/** +* Returns the display object in the container +* +* @memberof PIXI.Container# +* @param name {string} instance name +* @return {PIXI.DisplayObject} +*/ +core.Container.prototype.getChildByName = function (name) +{ + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].name === name) + { + return this.children[i]; + } + } + return null; +}; + +},{"../core":97}],163:[function(require,module,exports){ +var core = require('../core'); + +/** +* Returns the global position of the displayObject +* +* @memberof PIXI.DisplayObject# +* @param point {Point} the point to write the global value to. If null a new point will be returned +* @return {Point} +*/ +core.DisplayObject.prototype.getGlobalPosition = function (point) +{ + point = point || new core.Point(); + + if(this.parent) + { + this.displayObjectUpdateTransform(); + + point.x = this.worldTransform.tx; + point.y = this.worldTransform.ty; + } + else + { + point.x = this.position.x; + point.y = this.position.y; + } + + return point; +}; + +},{"../core":97}],164:[function(require,module,exports){ +/** + * @file Main export of the PIXI extras library + * @author Mat Groves + * @copyright 2013-2015 GoodBoyDigital + * @license {@link https://github.com/pixijs/pixi.js/blob/master/LICENSE|MIT License} + */ + +require('./cacheAsBitmap'); +require('./getChildByName'); +require('./getGlobalPosition'); + +/** + * @namespace PIXI.extras + */ +module.exports = { + MovieClip: require('./MovieClip'), + TilingSprite: require('./TilingSprite'), + BitmapText: require('./BitmapText') +}; + +},{"./BitmapText":158,"./MovieClip":159,"./TilingSprite":160,"./cacheAsBitmap":161,"./getChildByName":162,"./getGlobalPosition":163}],165:[function(require,module,exports){ +var Shader = require('../../core/Shader'); + + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI.mesh + * @param gl {PIXI.Shader} The WebGL shader manager this shader works for. + */ +function TilingShader(gl) +{ + Shader.call(this, + gl, + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\n\nuniform vec4 uFrame;\nuniform vec4 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vec2 coord = aTextureCoord;\n coord -= uTransform.xy;\n coord /= uTransform.zw;\n vTextureCoord = coord;\n}\n", + "#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform vec4 uFrame;\nuniform vec2 uPixelSize;\n\nvoid main(void)\n{\n\n \tvec2 coord = mod(vTextureCoord, uFrame.zw);\n \tcoord = clamp(coord, uPixelSize, uFrame.zw - uPixelSize);\n \tcoord += uFrame.xy;\n\n \tvec4 sample = texture2D(uSampler, coord);\n \tvec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n \tgl_FragColor = sample * color ;\n}\n" + ); +} + +TilingShader.prototype = Object.create(Shader.prototype); +TilingShader.prototype.constructor = TilingShader; +module.exports = TilingShader; + + +},{"../../core/Shader":77}],166:[function(require,module,exports){ +var core = require('../../core'), + BlurXFilter = require('./BlurXFilter'), + BlurYFilter = require('./BlurYFilter'); + +/** + * The BlurFilter applies a Gaussian blur to an object. + * The strength of the blur can be set for x- and y-axis separately. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +function BlurFilter(strength, quality, resolution) +{ + core.Filter.call(this); + + this.blurXFilter = new BlurXFilter(); + this.blurYFilter = new BlurYFilter(); + this.resolution = 1; + + this.padding = 0; + this.resolution = resolution || 1; + this.quality = quality || 4; + this.blur = strength || 8; +} + +BlurFilter.prototype = Object.create(core.Filter.prototype); +BlurFilter.prototype.constructor = BlurFilter; +module.exports = BlurFilter; + +BlurFilter.prototype.apply = function (filterManager, input, output) +{ + + var renderTarget = filterManager.getRenderTarget(true); + + this.blurXFilter.apply(filterManager, input, renderTarget, true); + this.blurYFilter.apply(filterManager, renderTarget, output, false); + + filterManager.returnRenderTarget(renderTarget); +}; + +Object.defineProperties(BlurFilter.prototype, { + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * + * @member {number} + * @memberOf PIXI.filters.BlurFilter# + * @default 2 + */ + blur: { + get: function () + { + return this.blurXFilter.blur; + }, + set: function (value) + { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.padding = Math.max( Math.abs(this.blurYFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + }, + + /** + * Sets the number of passes for blur. More passes means higher quaility bluring. + * + * @member {number} + * @memberof PIXI.filters.BlurYFilter# + * @default 1 + */ + quality: { + get: function () + { + return this.blurXFilter.quality; + }, + set: function (value) + { + + this.blurXFilter.quality = this.blurYFilter.quality = value; + } + }, + + /** + * Sets the strength of the blurX property + * + * @member {number} + * @memberOf PIXI.filters.BlurFilter# + * @default 2 + */ + blurX: { + get: function () + { + return this.blurXFilter.blur; + }, + set: function (value) + { + this.blurXFilter.blur = value; + this.padding = Math.max( Math.abs(this.blurYFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + }, + + /** + * Sets the strength of the blurY property + * + * @member {number} + * @memberOf PIXI.filters.BlurFilter# + * @default 2 + */ + blurY: { + get: function () + { + return this.blurYFilter.blur; + }, + set: function (value) + { + this.blurYFilter.blur = value; + this.padding = Math.max( Math.abs(this.blurYFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + } +}); + +},{"../../core":97,"./BlurXFilter":167,"./BlurYFilter":168}],167:[function(require,module,exports){ +var core = require('../../core'); +var generateBlurVertSource = require('./generateBlurVertSource'); +var generateBlurFragSource = require('./generateBlurFragSource'); +var getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +/** + * The BlurXFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +function BlurXFilter(strength, quality, resolution) +{ + var vertSrc = generateBlurVertSource(5, true); + var fragSrc = generateBlurFragSource(5); + + core.Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc + ); + + this.resolution = resolution || 1; + + this._quality = 0; + + this.quality = quality || 4; + this.strength = strength || 8; + + this.firstRun = true; + +} + +BlurXFilter.prototype = Object.create(core.Filter.prototype); +BlurXFilter.prototype.constructor = BlurXFilter; +module.exports = BlurXFilter; + +BlurXFilter.prototype.apply = function (filterManager, input, output, clear) +{ + if(this.firstRun) + { + var gl = filterManager.renderer.gl; + var kernelSize = getMaxBlurKernelSize(gl); + + this.vertexSrc = generateBlurVertSource(kernelSize, true); + this.fragmentSrc = generateBlurFragSource(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = (1/output.size.width) * (output.size.width/input.size.width); /// // * 2 //4//this.strength / 4 / this.passes * (input.frame.width / input.size.width); + + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes;// / this.passes//Math.pow(1, this.passes); + + if(this.passes === 1) + { + filterManager.applyFilter(this, input, output, clear); + } + else + { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for(var i = 0; i < this.passes-1; i++) + { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } +}; + + +Object.defineProperties(BlurXFilter.prototype, { + /** + * Sets the strength of both the blur. + * + * @member {number} + * @memberof PIXI.filters.BlurXFilter# + * @default 16 + */ + blur: { + get: function () + { + return this.strength; + }, + set: function (value) + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + }, + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher quaility bluring but the lower the performance. + * + * @member {number} + * @memberof PIXI.filters.BlurXFilter# + * @default 4 + */ + quality: { + get: function () + { + return this._quality; + }, + set: function (value) + { + this._quality = value; + this.passes = value; + } + } +}); + +},{"../../core":97,"./generateBlurFragSource":169,"./generateBlurVertSource":170,"./getMaxBlurKernelSize":171}],168:[function(require,module,exports){ +var core = require('../../core'); +var generateBlurVertSource = require('./generateBlurVertSource'); +var generateBlurFragSource = require('./generateBlurFragSource'); +var getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +/** + * The BlurYFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +function BlurYFilter(strength, quality, resolution) +{ + var vertSrc = generateBlurVertSource(5, false); + var fragSrc = generateBlurFragSource(5); + + core.Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc + ); + + this.resolution = resolution || 1; + + this._quality = 0; + + this.quality = quality || 4; + this.strength = strength || 8; + + this.firstRun = true; +} + +BlurYFilter.prototype = Object.create(core.Filter.prototype); +BlurYFilter.prototype.constructor = BlurYFilter; +module.exports = BlurYFilter; + +BlurYFilter.prototype.apply = function (filterManager, input, output, clear) +{ + if(this.firstRun) + { + var gl = filterManager.renderer.gl; + var kernelSize = getMaxBlurKernelSize(gl); + + this.vertexSrc = generateBlurVertSource(kernelSize, false); + this.fragmentSrc = generateBlurFragSource(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = (1/output.size.height) * (output.size.height/input.size.height); /// // * 2 //4//this.strength / 4 / this.passes * (input.frame.width / input.size.width); + + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + + if(this.passes === 1) + { + filterManager.applyFilter(this, input, output, clear); + } + else + { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for(var i = 0; i < this.passes-1; i++) + { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } +}; + + +Object.defineProperties(BlurYFilter.prototype, { + /** + * Sets the strength of both the blur. + * + * @member {number} + * @memberof PIXI.filters.BlurYFilter# + * @default 2 + */ + blur: { + get: function () + { + return this.strength; + }, + set: function (value) + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + }, + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher quaility bluring but the lower the performance. + * + * @member {number} + * @memberof PIXI.filters.BlurXFilter# + * @default 4 + */ + quality: { + get: function () + { + return this._quality; + }, + set: function (value) + { + this._quality = value; + this.passes = value; + } + } +}); + +},{"../../core":97,"./generateBlurFragSource":169,"./generateBlurVertSource":170,"./getMaxBlurKernelSize":171}],169:[function(require,module,exports){ +var GAUSSIAN_VALUES = { + 5:[0.153388, 0.221461, 0.250301], + 7:[0.071303, 0.131514, 0.189879, 0.214607], + 9:[0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11:[0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13:[0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15:[0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] +}; + +var fragTemplate = [ + 'varying vec2 vBlurTexCoords[%size%];', + 'uniform sampler2D uSampler;', + + 'void main(void)', + '{', + ' gl_FragColor = vec4(0.0);', + ' %blur%', + '}' + +].join('\n'); + +var generateFragBlurSource = function(kernelSize) +{ + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + + var fragSource = fragTemplate; + + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value; + + for (var i = 0; i < kernelSize; i++) + { + var blur = template.replace('%index%', i); + + value = i; + + if(i >= halfLength) + { + value = kernelSize - i - 1; + } + + + blur = blur.replace('%value%', kernel[value]); + + blurLoop += blur; + blurLoop += '\n'; + } + + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize); + + + return fragSource; +}; + + + +module.exports = generateFragBlurSource; + +},{}],170:[function(require,module,exports){ + +var vertTemplate = [ + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + + 'uniform float strength;', + 'uniform mat3 projectionMatrix;', + + 'varying vec2 vBlurTexCoords[%size%];', + + 'void main(void)', + '{', + 'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);', + '%blur%', + '}' +].join('\n'); + +var generateVertBlurSource = function(kernelSize, x) +{ + var halfLength = Math.ceil(kernelSize/2); + + var vertSource = vertTemplate; + + var blurLoop = ''; + var template; + var value; + + if(x) + { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } + else + { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; + + } + + + for (var i = 0; i < kernelSize; i++) + { + var blur = template.replace('%index%', i); + + value = i; + + if(i >= halfLength) + { + value = kernelSize - i - 1; + } + + blur = blur.replace('%sampleIndex%', (i - (halfLength-1)) + '.0'); + + blurLoop += blur; + blurLoop += '\n'; + } + + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize); + + return vertSource; +}; + + + +module.exports = generateVertBlurSource; + +},{}],171:[function(require,module,exports){ + + +var getMaxKernelSize = function(gl) +{ + var maxVaryings = ( gl.getParameter(gl.MAX_VARYING_VECTORS) ); + var kernelSize = 15; + + while(kernelSize > maxVaryings) + { + kernelSize -= 2; + } + + return kernelSize; +}; + +module.exports = getMaxKernelSize; + +},{}],172:[function(require,module,exports){ +var core = require('../../core'); +// @see https://github.com/substack/brfs/issues/25 + + +/** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * var colorMatrix = new PIXI.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +function ColorMatrixFilter() +{ + core.Filter.call(this, + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}", + // fragment shader + "#define GLSLIFY 1\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\n\nvoid main(void)\n{\n\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n gl_FragColor.r = (m[0] * c.r);\n gl_FragColor.r += (m[1] * c.g);\n gl_FragColor.r += (m[2] * c.b);\n gl_FragColor.r += (m[3] * c.a);\n gl_FragColor.r += m[4] * c.a;\n\n gl_FragColor.g = (m[5] * c.r);\n gl_FragColor.g += (m[6] * c.g);\n gl_FragColor.g += (m[7] * c.b);\n gl_FragColor.g += (m[8] * c.a);\n gl_FragColor.g += m[9] * c.a;\n\n gl_FragColor.b = (m[10] * c.r);\n gl_FragColor.b += (m[11] * c.g);\n gl_FragColor.b += (m[12] * c.b);\n gl_FragColor.b += (m[13] * c.a);\n gl_FragColor.b += m[14] * c.a;\n\n gl_FragColor.a = (m[15] * c.r);\n gl_FragColor.a += (m[16] * c.g);\n gl_FragColor.a += (m[17] * c.b);\n gl_FragColor.a += (m[18] * c.a);\n gl_FragColor.a += m[19] * c.a;\n\n// gl_FragColor = vec4(m[0]);\n}\n" + ); + + this.uniforms.m = [ + 1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0]; + + +} + +ColorMatrixFilter.prototype = Object.create(core.Filter.prototype); +ColorMatrixFilter.prototype.constructor = ColorMatrixFilter; +module.exports = ColorMatrixFilter; + + +/** + * Transforms current matrix and set the new one + * + * @param matrix {number[]} (mat 5x4) + * @param multiply {boolean} if true, current matrix and matrix are multiplied. If false, just set the current matrix with @param matrix + */ +ColorMatrixFilter.prototype._loadMatrix = function (matrix, multiply) +{ + multiply = !!multiply; + + var newMatrix = matrix; + + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + + // set the new matrix + this.uniforms.m = newMatrix; +}; + +/** + * Multiplies two mat5's + * + * @param out {number[]} (mat 5x4) the receiving matrix + * @param a {number[]} (mat 5x4) the first operand + * @param b {number[]} (mat 5x4) the second operand + * @returns out {number[]} (mat 5x4) + */ +ColorMatrixFilter.prototype._multiply = function (out, a, b) +{ + + // Red Channel + out[0] = (a[0] * b[0]) + (a[1] * b[5]) + (a[2] * b[10]) + (a[3] * b[15]); + out[1] = (a[0] * b[1]) + (a[1] * b[6]) + (a[2] * b[11]) + (a[3] * b[16]); + out[2] = (a[0] * b[2]) + (a[1] * b[7]) + (a[2] * b[12]) + (a[3] * b[17]); + out[3] = (a[0] * b[3]) + (a[1] * b[8]) + (a[2] * b[13]) + (a[3] * b[18]); + out[4] = (a[0] * b[4]) + (a[1] * b[9]) + (a[2] * b[14]) + (a[3] * b[19]); + + // Green Channel + out[5] = (a[5] * b[0]) + (a[6] * b[5]) + (a[7] * b[10]) + (a[8] * b[15]); + out[6] = (a[5] * b[1]) + (a[6] * b[6]) + (a[7] * b[11]) + (a[8] * b[16]); + out[7] = (a[5] * b[2]) + (a[6] * b[7]) + (a[7] * b[12]) + (a[8] * b[17]); + out[8] = (a[5] * b[3]) + (a[6] * b[8]) + (a[7] * b[13]) + (a[8] * b[18]); + out[9] = (a[5] * b[4]) + (a[6] * b[9]) + (a[7] * b[14]) + (a[8] * b[19]); + + // Blue Channel + out[10] = (a[10] * b[0]) + (a[11] * b[5]) + (a[12] * b[10]) + (a[13] * b[15]); + out[11] = (a[10] * b[1]) + (a[11] * b[6]) + (a[12] * b[11]) + (a[13] * b[16]); + out[12] = (a[10] * b[2]) + (a[11] * b[7]) + (a[12] * b[12]) + (a[13] * b[17]); + out[13] = (a[10] * b[3]) + (a[11] * b[8]) + (a[12] * b[13]) + (a[13] * b[18]); + out[14] = (a[10] * b[4]) + (a[11] * b[9]) + (a[12] * b[14]) + (a[13] * b[19]); + + // Alpha Channel + out[15] = (a[15] * b[0]) + (a[16] * b[5]) + (a[17] * b[10]) + (a[18] * b[15]); + out[16] = (a[15] * b[1]) + (a[16] * b[6]) + (a[17] * b[11]) + (a[18] * b[16]); + out[17] = (a[15] * b[2]) + (a[16] * b[7]) + (a[17] * b[12]) + (a[18] * b[17]); + out[18] = (a[15] * b[3]) + (a[16] * b[8]) + (a[17] * b[13]) + (a[18] * b[18]); + out[19] = (a[15] * b[4]) + (a[16] * b[9]) + (a[17] * b[14]) + (a[18] * b[19]); + + return out; +}; + +/** + * Create a Float32 Array and normalize the offset component to 0-1 + * + * @param matrix {number[]} (mat 5x4) + * @return m {number[]} (mat 5x4) with all values between 0-1 + */ +ColorMatrixFilter.prototype._colorMatrix = function (matrix) +{ + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + + return m; +}; + +/** + * Adjusts brightness + * + * @param b {number} value of the brigthness (0 is black) + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.brightness = function (b, multiply) +{ + var matrix = [ + b, 0, 0, 0, 0, + 0, b, 0, 0, 0, + 0, 0, b, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Set the matrices in grey scales + * + * @param scale {number} value of the grey (0 is black) + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.greyscale = function (scale, multiply) +{ + var matrix = [ + scale, scale, scale, 0, 0, + scale, scale, scale, 0, 0, + scale, scale, scale, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; +//Americanized alias +ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + +/** + * Set the black and white matrice + * Multiply the current matrix + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.blackAndWhite = function (multiply) +{ + var matrix = [ + 0.3, 0.6, 0.1, 0, 0, + 0.3, 0.6, 0.1, 0, 0, + 0.3, 0.6, 0.1, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Set the hue property of the color + * + * @param rotation {number} in degrees + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.hue = function (rotation, multiply) +{ + rotation = (rotation || 0) / 180 * Math.PI; + + var cosR = Math.cos(rotation), + sinR = Math.sin(rotation), + sqrt = Math.sqrt; + + /*a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + + var w = 1/3, sqrW = sqrt(w);//weight is + + var a00 = cosR + (1.0 - cosR) * w; + var a01 = w * (1.0 - cosR) - sqrW * sinR; + var a02 = w * (1.0 - cosR) + sqrW * sinR; + + var a10 = w * (1.0 - cosR) + sqrW * sinR; + var a11 = cosR + w*(1.0 - cosR); + var a12 = w * (1.0 - cosR) - sqrW * sinR; + + var a20 = w * (1.0 - cosR) - sqrW * sinR; + var a21 = w * (1.0 - cosR) + sqrW * sinR; + var a22 = cosR + w * (1.0 - cosR); + + + var matrix = [ + a00, a01, a02, 0, 0, + a10, a11, a12, 0, 0, + a20, a21, a22, 0, 0, + 0, 0, 0, 1, 0, + ]; + + this._loadMatrix(matrix, multiply); +}; + + +/** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * + * @param amount {number} value of the contrast + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.contrast = function (amount, multiply) +{ + var v = (amount || 0) + 1; + var o = -128 * (v - 1); + + var matrix = [ + v, 0, 0, 0, o, + 0, v, 0, 0, o, + 0, 0, v, 0, o, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * + * @param [amount=0] {number} + * @param [multiply] {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.saturate = function (amount, multiply) +{ + var x = (amount || 0) * 2 / 3 + 1; + var y = ((x - 1) * -0.5); + + var matrix = [ + x, y, y, 0, 0, + y, x, y, 0, 0, + y, y, x, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Desaturate image (remove color) + * + * Call the saturate function + * + */ +ColorMatrixFilter.prototype.desaturate = function () // jshint unused:false +{ + this.saturate(-1); +}; + +/** + * Negative image (inverse of classic rgb matrix) + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.negative = function (multiply) +{ + var matrix = [ + 0, 1, 1, 0, 0, + 1, 0, 1, 0, 0, + 1, 1, 0, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Sepia image + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.sepia = function (multiply) +{ + var matrix = [ + 0.393, 0.7689999, 0.18899999, 0, 0, + 0.349, 0.6859999, 0.16799999, 0, 0, + 0.272, 0.5339999, 0.13099999, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.technicolor = function (multiply) +{ + var matrix = [ + 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, + -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, + -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Polaroid filter + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.polaroid = function (multiply) +{ + var matrix = [ + 1.438, -0.062, -0.062, 0, 0, + -0.122, 1.378, -0.122, 0, 0, + -0.016, -0.016, 1.483, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Filter who transforms : Red -> Blue and Blue -> Red + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.toBGR = function (multiply) +{ + var matrix = [ + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 1, 0, 0, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.kodachrome = function (multiply) +{ + var matrix = [ + 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, + -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, + -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Brown delicious browni filter (thanks Dominic Szablewski) + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.browni = function (multiply) +{ + var matrix = [ + 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, + -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, + 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/* + * Vintage filter (thanks Dominic Szablewski) + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.vintage = function (multiply) +{ + var matrix = [ + 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, + 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, + 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/* + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * + * @param desaturation {number} + * @param toned {number} + * @param lightColor {string} (example : "0xFFE580") + * @param darkColor {string} (example : "0xFFE580") + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.colorTone = function (desaturation, toned, lightColor, darkColor, multiply) +{ + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + + var lR = ((lightColor >> 16) & 0xFF) / 255; + var lG = ((lightColor >> 8) & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + + var dR = ((darkColor >> 16) & 0xFF) / 255; + var dG = ((darkColor >> 8) & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + + var matrix = [ + 0.3, 0.59, 0.11, 0, 0, + lR, lG, lB, desaturation, 0, + dR, dG, dB, toned, 0, + lR - dR, lG - dG, lB - dB, 0, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/* + * Night effect + * + * @param intensity {number} + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.night = function (intensity, multiply) +{ + intensity = intensity || 0.1; + var matrix = [ + intensity * ( -2.0), -intensity, 0, 0, 0, + -intensity, 0, intensity, 0, 0, + 0, intensity, intensity * 2.0, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + + +/* + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * + * @param amount {number} how much the predator feels his future victim + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.predator = function (amount, multiply) +{ + var matrix = [ + 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, + -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, + -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/* + * LSD effect + * + * Multiply the current matrix + * + * @param amount {number} How crazy is your effect + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.lsd = function (multiply) +{ + var matrix = [ + 2, -0.4, 0.5, 0, 0, + -0.5, 2, -0.4, 0, 0, + -0.4, -0.5, 3, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/* + * Erase the current matrix by setting the default one + * + */ +ColorMatrixFilter.prototype.reset = function () +{ + var matrix = [ + 1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, false); +}; + + +Object.defineProperties(ColorMatrixFilter.prototype, { + /** + * Sets the matrix of the color matrix filter + * + * @member {number[]} + * @memberof PIXI.filters.ColorMatrixFilter# + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + matrix: { + get: function () + { + return this.uniforms.m; + }, + set: function (value) + { + this.uniforms.m = value; + } + } +}); + +},{"../../core":97}],173:[function(require,module,exports){ +var core = require('../../core'); + + +/** + * The DisplacementFilter class uses the pixel values from the specified texture (called the displacement map) to perform a displacement of an object. + * You can use this filter to apply all manor of crazy warping effects + * Currently the r property of the texture is used to offset the x and the g property of the texture is used to offset the y. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + * @param sprite {PIXI.Sprite} The sprite used for the displacement map. (make sure its added to the scene!) + * @param scale {number} The scale of the displacement + */ +function DisplacementFilter(sprite, scale) +{ + var maskMatrix = new core.Matrix(); + sprite.renderable = false; + + core.Filter.call(this, + // vertex shader +// glslify('./displacement.vert'), + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}", + // fragment shader + "#define GLSLIFY 1\nvarying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n" + + ); + + this.maskSprite = sprite; + this.maskMatrix = maskMatrix; + + this.uniforms.mapSampler = sprite.texture; + this.uniforms.filterMatrix = maskMatrix.toArray(true); + this.uniforms.scale = { x: 1, y: 1 }; + + if (scale === null || scale === undefined) + { + scale = 20; + } + + this.scale = new core.Point(scale, scale); +} + +DisplacementFilter.prototype = Object.create(core.Filter.prototype); +DisplacementFilter.prototype.constructor = DisplacementFilter; +module.exports = DisplacementFilter; + +DisplacementFilter.prototype.apply = function (filterManager, input, output) +{ + var ratio = (1/output.destinationFrame.width) * (output.size.width/input.size.width); /// // * 2 //4//this.strength / 4 / this.passes * (input.frame.width / input.size.width); + + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x * ratio; + this.uniforms.scale.y = this.scale.y * ratio; + + // draw the filter... + filterManager.applyFilter(this, input, output); +}; + + +Object.defineProperties(DisplacementFilter.prototype, { + /** + * The texture used for the displacement map. Must be power of 2 sized texture. + * + * @member {PIXI.Texture} + * @memberof PIXI.filters.DisplacementFilter# + */ + map: { + get: function () + { + return this.uniforms.mapSampler; + }, + set: function (value) + { + this.uniforms.mapSampler = value; + + } + } +}); + +},{"../../core":97}],174:[function(require,module,exports){ +var core = require('../../core'); + + +/** + * + * Basic FXAA implementation based on the code on geeks3d.com with the + * modification that the texture2DLod stuff was removed since it's + * unsupported by WebGL. + * + * @see https://github.com/mitsuhiko/webgl-meincraft + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + * + */ +function FXAAFilter() +{ + //TODO - needs work + core.Filter.call(this, + + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}", + // fragment shader + "#define GLSLIFY 1\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it's\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n \tvec2 fragCoord = vTextureCoord * filterArea.xy;\n\n \tvec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n \tgl_FragColor = color;\n}\n" + ); + +} + +FXAAFilter.prototype = Object.create(core.Filter.prototype); +FXAAFilter.prototype.constructor = FXAAFilter; + +module.exports = FXAAFilter; + +},{"../../core":97}],175:[function(require,module,exports){ +/** + * @file Main export of the PIXI filters library + * @author Mat Groves + * @copyright 2013-2015 GoodBoyDigital + * @license {@link https://github.com/pixijs/pixi.js/blob/master/LICENSE|MIT License} + */ + +/** + * @namespace PIXI.filters + */ +module.exports = { + FXAAFilter: require('./fxaa/FXAAFilter'), + NoiseFilter: require('./noise/NoiseFilter'), + DisplacementFilter: require('./displacement/DisplacementFilter'), + BlurFilter: require('./blur/BlurFilter'), + BlurXFilter: require('./blur/BlurXFilter'), + BlurYFilter: require('./blur/BlurYFilter'), + ColorMatrixFilter: require('./colormatrix/ColorMatrixFilter'), + VoidFilter: require('./void/VoidFilter') +}; + +},{"./blur/BlurFilter":166,"./blur/BlurXFilter":167,"./blur/BlurYFilter":168,"./colormatrix/ColorMatrixFilter":172,"./displacement/DisplacementFilter":173,"./fxaa/FXAAFilter":174,"./noise/NoiseFilter":176,"./void/VoidFilter":177}],176:[function(require,module,exports){ +var core = require('../../core'); + + +/** + * @author Vico @vicocotea + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + */ + +/** + * A Noise effect filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +function NoiseFilter() +{ + core.Filter.call(this, + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}", + // fragment shader + "precision highp float;\n#define GLSLIFY 1\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float noise;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n float diff = (rand(gl_FragCoord.xy) - 0.5) * noise;\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n gl_FragColor = color;\n}\n" + ); + + this.noise = 0.5; +} + +NoiseFilter.prototype = Object.create(core.Filter.prototype); +NoiseFilter.prototype.constructor = NoiseFilter; +module.exports = NoiseFilter; + +Object.defineProperties(NoiseFilter.prototype, { + /** + * The amount of noise to apply. + * + * @member {number} + * @memberof PIXI.filters.NoiseFilter# + * @default 0.5 + */ + noise: { + get: function () + { + return this.uniforms.noise; + }, + set: function (value) + { + this.uniforms.noise = value; + } + } +}); + +},{"../../core":97}],177:[function(require,module,exports){ +var core = require('../../core'); +// @see https://github.com/substack/brfs/issues/25 + + +/** + * Does nothing. Very handy. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +function VoidFilter() +{ + core.Filter.call(this, + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}", + // fragment shader + "#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n" + ); + + this.glShaderKey = 'void'; +} + +VoidFilter.prototype = Object.create(core.Filter.prototype); +VoidFilter.prototype.constructor = VoidFilter; +module.exports = VoidFilter; + +},{"../../core":97}],178:[function(require,module,exports){ +var core = require('../core'); + +/** + * Holds all information related to an Interaction event + * + * @class + * @memberof PIXI.interaction + */ +function InteractionData() +{ + /** + * This point stores the global coords of where the touch/mouse event happened + * + * @member {PIXI.Point} + */ + this.global = new core.Point(); + + /** + * The target Sprite that was interacted with + * + * @member {PIXI.Sprite} + */ + this.target = null; + + /** + * When passed to an event handler, this will be the original DOM Event that was captured + * + * @member {Event} + */ + this.originalEvent = null; +} + +InteractionData.prototype.constructor = InteractionData; +module.exports = InteractionData; + +/** + * This will return the local coordinates of the specified displayObject for this InteractionData + * + * @param displayObject {PIXI.DisplayObject} The DisplayObject that you would like the local coords off + * @param [point] {PIXI.Point} A Point object in which to store the value, optional (otherwise will create a new point) + * @param [globalPos] {PIXI.Point} A Point object containing your custom global coords, optional (otherwise will use the current global coords) + * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative to the DisplayObject + */ +InteractionData.prototype.getLocalPosition = function (displayObject, point, globalPos) +{ + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); +}; + +},{"../core":97}],179:[function(require,module,exports){ +var core = require('../core'), + InteractionData = require('./InteractionData'), + EventEmitter = require('eventemitter3'); + +// Mix interactiveTarget into core.DisplayObject.prototype +Object.assign( + core.DisplayObject.prototype, + require('./interactiveTarget') +); + +/** + * The interaction manager deals with mouse and touch events. Any DisplayObject can be interactive + * if its interactive parameter is set to true + * This manager also supports multitouch. + * + * @class + * @extends EventEmitter + * @memberof PIXI.interaction + * @param renderer {PIXI.CanvasRenderer|PIXI.WebGLRenderer} A reference to the current renderer + * @param [options] {object} + * @param [options.autoPreventDefault=true] {boolean} Should the manager automatically prevent default browser actions. + * @param [options.interactionFrequency=10] {number} Frequency increases the interaction events will be checked. + */ +function InteractionManager(renderer, options) +{ + EventEmitter.call(this); + + options = options || {}; + + /** + * The renderer this interaction manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * Should default browser actions automatically be prevented. + * + * @member {boolean} + * @default true + */ + this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + + /** + * As this frequency increases the interaction events will be checked more often. + * + * @member {number} + * @default 10 + */ + this.interactionFrequency = options.interactionFrequency || 10; + + /** + * The mouse data + * + * @member {PIXI.interaction.InteractionData} + */ + this.mouse = new InteractionData(); + + // setting the pointer to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + this.mouse.global.set(-999999); + + /** + * An event data object to handle all the event tracking/dispatching + * + * @member {object} + */ + this.eventData = { + stopped: false, + target: null, + type: null, + data: this.mouse, + stopPropagation:function(){ + this.stopped = true; + } + }; + + /** + * Tiny little interactiveData pool ! + * + * @member {PIXI.interaction.InteractionData[]} + */ + this.interactiveDataPool = []; + + /** + * The DOM element to bind to. + * + * @member {HTMLElement} + * @private + */ + this.interactionDOMElement = null; + + /** + * This property determins if mousemove and touchmove events are fired only when the cursror is over the object + * Setting to true will make things work more in line with how the DOM verison works. + * Setting to false can make things easier for things like dragging + * It is currently set to false as this is how pixi used to work. This will be set to true in future versions of pixi. + * @member {boolean} + * @private + */ + this.moveWhenInside = false; + + /** + * Have events been attached to the dom element? + * + * @member {boolean} + * @private + */ + this.eventsAdded = false; + + //this will make it so that you don't have to call bind all the time + + /** + * @member {Function} + * @private + */ + this.onMouseUp = this.onMouseUp.bind(this); + this.processMouseUp = this.processMouseUp.bind( this ); + + + /** + * @member {Function} + * @private + */ + this.onMouseDown = this.onMouseDown.bind(this); + this.processMouseDown = this.processMouseDown.bind( this ); + + /** + * @member {Function} + * @private + */ + this.onMouseMove = this.onMouseMove.bind( this ); + this.processMouseMove = this.processMouseMove.bind( this ); + + /** + * @member {Function} + * @private + */ + this.onMouseOut = this.onMouseOut.bind(this); + this.processMouseOverOut = this.processMouseOverOut.bind( this ); + + /** + * @member {Function} + * @private + */ + this.onMouseOver = this.onMouseOver.bind(this); + + + /** + * @member {Function} + * @private + */ + this.onTouchStart = this.onTouchStart.bind(this); + this.processTouchStart = this.processTouchStart.bind(this); + + /** + * @member {Function} + * @private + */ + this.onTouchEnd = this.onTouchEnd.bind(this); + this.processTouchEnd = this.processTouchEnd.bind(this); + + /** + * @member {Function} + * @private + */ + this.onTouchMove = this.onTouchMove.bind(this); + this.processTouchMove = this.processTouchMove.bind(this); + + /** + * Every update cursor will be reset to this value, if some element wont override it in its hitTest + * @member {string} + * @default 'inherit' + */ + this.defaultCursorStyle = 'inherit'; + + /** + * The css style of the cursor that is being used + * @member {string} + */ + this.currentCursorStyle = 'inherit'; + + /** + * Internal cached var + * @member {PIXI.Point} + * @private + */ + this._tempPoint = new core.Point(); + + + /** + * The current resolution / device pixel ratio. + * @member {number} + * @default 1 + */ + this.resolution = 1; + + this.setTargetElement(this.renderer.view, this.renderer.resolution); + + /** + * Fired when a pointing device button (usually a mouse button) is pressed on the display object. + * + * @memberof PIXI.interaction.InteractionManager# + * @event mousedown + */ + + /** + * Fired when a pointing device secondary button (usually a mouse right-button) is pressed on the display object. + * + * @memberof PIXI.interaction.InteractionManager# + * @event rightdown + */ + + /** + * Fired when a pointing device button (usually a mouse button) is released over the display object. + * + * @memberof PIXI.interaction.InteractionManager# + * @event mouseup + */ + + /** + * Fired when a pointing device secondary button (usually a mouse right-button) is released over the display object. + * + * @memberof PIXI.interaction.InteractionManager# + * @event rightup + */ + + /** + * Fired when a pointing device button (usually a mouse button) is pressed and released on the display object. + * + * @event click + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointing device secondary button (usually a mouse right-button) is pressed and released on the display object. + * + * @event rightclick + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointing device button (usually a mouse button) is released outside the display object that initially registered a [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. + * + * @event mouseupoutside + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointing device secondary button (usually a mouse right-button) is released outside the display object that initially + * registered a [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. + * + * @event rightupoutside + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointing device (usually a mouse) is moved while over the display object + * + * @event mousemove + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointing device (usually a mouse) is moved onto the display object + * + * @event mouseover + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointing device (usually a mouse) is moved off the display object + * + * @event mouseout + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is placed on the display object. + * + * @event touchstart + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is removed from the display object. + * + * @event touchend + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * + * @event tap + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is removed outside of the display object that initially registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. + * + * @event touchendoutside + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is moved along the display object. + * + * @event touchmove + * @memberof PIXI.interaction.InteractionManager# + */ +} + +InteractionManager.prototype = Object.create(EventEmitter.prototype); +InteractionManager.prototype.constructor = InteractionManager; +module.exports = InteractionManager; + +/** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate + * another DOM element to receive those events. + * + * @param element {HTMLElement} the DOM element which will receive mouse and touch events. + * @param [resolution=1] {number} The resolution / device pixel ratio of the new element (relative to the canvas). + * @private + */ +InteractionManager.prototype.setTargetElement = function (element, resolution) +{ + this.removeEvents(); + + this.interactionDOMElement = element; + + this.resolution = resolution || 1; + + this.addEvents(); +}; + +/** + * Registers all the DOM events + * + * @private + */ +InteractionManager.prototype.addEvents = function () +{ + if (!this.interactionDOMElement) + { + return; + } + + core.ticker.shared.add(this.update, this); + + if (window.navigator.msPointerEnabled) + { + this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; + this.interactionDOMElement.style['-ms-touch-action'] = 'none'; + } + + window.document.addEventListener('mousemove', this.onMouseMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onMouseDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onMouseOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onMouseOver, true); + + this.interactionDOMElement.addEventListener('touchstart', this.onTouchStart, true); + this.interactionDOMElement.addEventListener('touchend', this.onTouchEnd, true); + this.interactionDOMElement.addEventListener('touchmove', this.onTouchMove, true); + + window.addEventListener('mouseup', this.onMouseUp, true); + + this.eventsAdded = true; +}; + +/** + * Removes all the DOM events that were previously registered + * + * @private + */ +InteractionManager.prototype.removeEvents = function () +{ + if (!this.interactionDOMElement) + { + return; + } + + core.ticker.shared.remove(this.update); + + if (window.navigator.msPointerEnabled) + { + this.interactionDOMElement.style['-ms-content-zooming'] = ''; + this.interactionDOMElement.style['-ms-touch-action'] = ''; + } + + window.document.removeEventListener('mousemove', this.onMouseMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onMouseDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onMouseOut, true); + this.interactionDOMElement.removeEventListener('mouseover', this.onMouseOver, true); + + this.interactionDOMElement.removeEventListener('touchstart', this.onTouchStart, true); + this.interactionDOMElement.removeEventListener('touchend', this.onTouchEnd, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onTouchMove, true); + + this.interactionDOMElement = null; + + window.removeEventListener('mouseup', this.onMouseUp, true); + + this.eventsAdded = false; +}; + +/** + * Updates the state of interactive objects. + * Invoked by a throttled ticker update from + * {@link PIXI.ticker.shared}. + * + * @param deltaTime {number} time delta since last tick + */ +InteractionManager.prototype.update = function (deltaTime) +{ + this._deltaTime += deltaTime; + + if (this._deltaTime < this.interactionFrequency) + { + return; + } + + this._deltaTime = 0; + + if (!this.interactionDOMElement) + { + return; + } + + // if the user move the mouse this check has already been dfone using the mouse move! + if(this.didMove) + { + this.didMove = false; + return; + } + + this.cursor = this.defaultCursorStyle; + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseOverOut, true ); + + if (this.currentCursorStyle !== this.cursor) + { + this.currentCursorStyle = this.cursor; + this.interactionDOMElement.style.cursor = this.cursor; + } + + //TODO +}; + +/** + * Dispatches an event on the display object that was interacted with + * + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} the display object in question + * @param eventString {string} the name of the event (e.g, mousedown) + * @param eventData {object} the event data object + * @private + */ +InteractionManager.prototype.dispatchEvent = function ( displayObject, eventString, eventData ) +{ + if(!eventData.stopped) + { + eventData.target = displayObject; + eventData.type = eventString; + + displayObject.emit( eventString, eventData ); + + if( displayObject[eventString] ) + { + displayObject[eventString]( eventData ); + } + } +}; + +/** + * Maps x and y coords from a DOM object and maps them correctly to the pixi view. The resulting value is stored in the point. + * This takes into account the fact that the DOM element could be scaled and positioned anywhere on the screen. + * + * @param {PIXI.Point} point the point that the result will be stored in + * @param {number} x the x coord of the position to map + * @param {number} y the y coord of the position to map + */ +InteractionManager.prototype.mapPositionToPoint = function ( point, x, y ) +{ + var rect; + // IE 11 fix + if(!this.interactionDOMElement.parentElement) + { + rect = { x: 0, y: 0, width: 0, height: 0 }; + } else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + + point.x = ( ( x - rect.left ) * (this.interactionDOMElement.width / rect.width ) ) / this.resolution; + point.y = ( ( y - rect.top ) * (this.interactionDOMElement.height / rect.height ) ) / this.resolution; +}; + +/** + * This function is provides a neat way of crawling through the scene graph and running a specified function on all interactive objects it finds. + * It will also take care of hit testing the interactive objects and passes the hit across in the function. + * + * @param point {PIXI.Point} the point that is tested for collision + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} the displayObject that will be hit test (recurcsivly crawls its children) + * @param [func] {Function} the function that will be called on each interactive object. The displayObject and hit will be passed to the function + * @param [hitTest] {boolean} this indicates if the objects inside should be hit test against the point + * @param [interactive] {boolean} Whether the displayObject is interactive + * @return {boolean} returns true if the displayObject hit the point + */ +InteractionManager.prototype.processInteractive = function (point, displayObject, func, hitTest, interactive) +{ + if(!displayObject || !displayObject.visible) + { + return false; + } + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + var hit = false, + interactiveParent = interactive = displayObject.interactive || interactive; + + + + + // if the displayobject has a hitArea, then it does not need to hitTest children. + if(displayObject.hitArea) + { + interactiveParent = false; + } + + // it has a mask! Then lets hit test that before continuing.. + if(hitTest && displayObject._mask) + { + if(!displayObject._mask.containsPoint(point)) + { + hitTest = false; + } + } + + // it has a filterArea! Same as mask but easier, its a rectangle + if(hitTest && displayObject.filterArea) + { + if(!displayObject.filterArea.contains(point.x, point.y)) + { + hitTest = false; + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow pixi to completly ignore and bypass checking the displayObjects children. + if(displayObject.interactiveChildren) + { + var children = displayObject.children; + + for (var i = children.length-1; i >= 0; i--) + { + var child = children[i]; + + // time to get recursive.. if this function will return if somthing is hit.. + if(this.processInteractive(point, child, func, hitTest, interactiveParent)) + { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if(!child.parent) + { + continue; + } + + hit = true; + + // we no longer need to hit test any more objects in this container as we we now know the parent has been hit + interactiveParent = false; + + // If the child is interactive , that means that the object hit was actually interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run through all objects, but we don't need to perform any hit tests. + + //{ + hitTest = false; + //} + + // we can break now as we have hit an object. + } + } + } + + + + // no point running this if the item is not interactive or does not have an interactive parent. + if(interactive) + { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children has already been hit! + if(hitTest && !hit) + { + + if(displayObject.hitArea) + { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + hit = displayObject.hitArea.contains( this._tempPoint.x, this._tempPoint.y ); + } + else if(displayObject.containsPoint) + { + hit = displayObject.containsPoint(point); + } + + + } + + if(displayObject.interactive) + { + func(displayObject, hit); + } + } + + return hit; + +}; + + +/** + * Is called when the mouse button is pressed down on the renderer element + * + * @param event {Event} The DOM event of a mouse button being pressed down + * @private + */ +InteractionManager.prototype.onMouseDown = function (event) +{ + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData.stopped = false; + + // Update internal mouse reference + this.mapPositionToPoint( this.mouse.global, event.clientX, event.clientY); + + if (this.autoPreventDefault) + { + this.mouse.originalEvent.preventDefault(); + } + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseDown, true ); + + var isRightButton = event.button === 2 || event.which === 3; + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); +}; + +/** + * Processes the result of the mouse down check and dispatches the event if need be + * + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} The display object that was tested + * @param hit {boolean} the result of the hit test on the dispay object + * @private + */ +InteractionManager.prototype.processMouseDown = function ( displayObject, hit ) +{ + var e = this.mouse.originalEvent; + + var isRightButton = e.button === 2 || e.which === 3; + + if(hit) + { + displayObject[ isRightButton ? '_isRightDown' : '_isLeftDown' ] = true; + this.dispatchEvent( displayObject, isRightButton ? 'rightdown' : 'mousedown', this.eventData ); + } +}; + +/** + * Is called when the mouse button is released on the renderer element + * + * @param event {Event} The DOM event of a mouse button being released + * @private + */ +InteractionManager.prototype.onMouseUp = function (event) +{ + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData.stopped = false; + + // Update internal mouse reference + this.mapPositionToPoint( this.mouse.global, event.clientX, event.clientY); + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseUp, true ); + + var isRightButton = event.button === 2 || event.which === 3; + this.emit(isRightButton ? 'rightup' : 'mouseup', this.eventData); +}; + +/** + * Processes the result of the mouse up check and dispatches the event if need be + * + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} The display object that was tested + * @param hit {boolean} the result of the hit test on the display object + * @private + */ +InteractionManager.prototype.processMouseUp = function ( displayObject, hit ) +{ + var e = this.mouse.originalEvent; + + var isRightButton = e.button === 2 || e.which === 3; + var isDown = isRightButton ? '_isRightDown' : '_isLeftDown'; + + if(hit) + { + this.dispatchEvent( displayObject, isRightButton ? 'rightup' : 'mouseup', this.eventData ); + + if( displayObject[ isDown ] ) + { + displayObject[ isDown ] = false; + this.dispatchEvent( displayObject, isRightButton ? 'rightclick' : 'click', this.eventData ); + } + } + else + { + if( displayObject[ isDown ] ) + { + displayObject[ isDown ] = false; + this.dispatchEvent( displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', this.eventData ); + } + } +}; + + +/** + * Is called when the mouse moves across the renderer element + * + * @param event {Event} The DOM event of the mouse moving + * @private + */ +InteractionManager.prototype.onMouseMove = function (event) +{ + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData.stopped = false; + + this.mapPositionToPoint( this.mouse.global, event.clientX, event.clientY); + + this.didMove = true; + + this.cursor = this.defaultCursorStyle; + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseMove, true ); + + this.emit('mousemove', this.eventData); + + if (this.currentCursorStyle !== this.cursor) + { + this.currentCursorStyle = this.cursor; + this.interactionDOMElement.style.cursor = this.cursor; + } + + //TODO BUG for parents ineractive object (border order issue) +}; + +/** + * Processes the result of the mouse move check and dispatches the event if need be + * + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} The display object that was tested + * @param hit {boolean} the result of the hit test on the display object + * @private + */ +InteractionManager.prototype.processMouseMove = function ( displayObject, hit ) +{ + this.processMouseOverOut(displayObject, hit); + + // only display on mouse over + if(!this.moveWhenInside || hit) + { + this.dispatchEvent( displayObject, 'mousemove', this.eventData); + } +}; + + +/** + * Is called when the mouse is moved out of the renderer element + * + * @param event {Event} The DOM event of a mouse being moved out + * @private + */ +InteractionManager.prototype.onMouseOut = function (event) +{ + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData.stopped = false; + + // Update internal mouse reference + this.mapPositionToPoint( this.mouse.global, event.clientX, event.clientY); + + this.interactionDOMElement.style.cursor = this.defaultCursorStyle; + + // TODO optimize by not check EVERY TIME! maybe half as often? // + this.mapPositionToPoint( this.mouse.global, event.clientX, event.clientY ); + + this.processInteractive( this.mouse.global, this.renderer._lastObjectRendered, this.processMouseOverOut, false ); + + this.emit('mouseout', this.eventData); +}; + +/** + * Processes the result of the mouse over/out check and dispatches the event if need be + * + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} The display object that was tested + * @param hit {boolean} the result of the hit test on the display object + * @private + */ +InteractionManager.prototype.processMouseOverOut = function ( displayObject, hit ) +{ + if(hit) + { + if(!displayObject._over) + { + displayObject._over = true; + this.dispatchEvent( displayObject, 'mouseover', this.eventData ); + } + + if (displayObject.buttonMode) + { + this.cursor = displayObject.defaultCursor; + } + } + else + { + if(displayObject._over) + { + displayObject._over = false; + this.dispatchEvent( displayObject, 'mouseout', this.eventData); + } + } +}; + +/** + * Is called when the mouse enters the renderer element area + * + * @param event {Event} The DOM event of the mouse moving into the renderer view + * @private + */ +InteractionManager.prototype.onMouseOver = function(event) +{ + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData.stopped = false; + + this.emit('mouseover', this.eventData); +}; + + +/** + * Is called when a touch is started on the renderer element + * + * @param event {Event} The DOM event of a touch starting on the renderer view + * @private + */ +InteractionManager.prototype.onTouchStart = function (event) +{ + if (this.autoPreventDefault) + { + event.preventDefault(); + } + + var changedTouches = event.changedTouches; + var cLength = changedTouches.length; + + for (var i=0; i < cLength; i++) + { + var touchEvent = changedTouches[i]; + //TODO POOL + var touchData = this.getTouchData( touchEvent ); + + touchData.originalEvent = event; + + this.eventData.data = touchData; + this.eventData.stopped = false; + + this.processInteractive( touchData.global, this.renderer._lastObjectRendered, this.processTouchStart, true ); + + this.emit('touchstart', this.eventData); + + this.returnTouchData( touchData ); + } +}; + +/** + * Processes the result of a touch check and dispatches the event if need be + * + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} The display object that was tested + * @param hit {boolean} the result of the hit test on the display object + * @private + */ +InteractionManager.prototype.processTouchStart = function ( displayObject, hit ) +{ + if(hit) + { + displayObject._touchDown = true; + this.dispatchEvent( displayObject, 'touchstart', this.eventData ); + } +}; + + +/** + * Is called when a touch ends on the renderer element + * + * @param event {Event} The DOM event of a touch ending on the renderer view + * @private + */ +InteractionManager.prototype.onTouchEnd = function (event) +{ + if (this.autoPreventDefault) + { + event.preventDefault(); + } + + var changedTouches = event.changedTouches; + var cLength = changedTouches.length; + + for (var i=0; i < cLength; i++) + { + var touchEvent = changedTouches[i]; + + var touchData = this.getTouchData( touchEvent ); + + touchData.originalEvent = event; + + //TODO this should be passed along.. no set + this.eventData.data = touchData; + this.eventData.stopped = false; + + + this.processInteractive( touchData.global, this.renderer._lastObjectRendered, this.processTouchEnd, true ); + + this.emit('touchend', this.eventData); + + this.returnTouchData( touchData ); + } +}; + +/** + * Processes the result of the end of a touch and dispatches the event if need be + * + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} The display object that was tested + * @param hit {boolean} the result of the hit test on the display object + * @private + */ +InteractionManager.prototype.processTouchEnd = function ( displayObject, hit ) +{ + if(hit) + { + this.dispatchEvent( displayObject, 'touchend', this.eventData ); + + if( displayObject._touchDown ) + { + displayObject._touchDown = false; + this.dispatchEvent( displayObject, 'tap', this.eventData ); + } + } + else + { + if( displayObject._touchDown ) + { + displayObject._touchDown = false; + this.dispatchEvent( displayObject, 'touchendoutside', this.eventData ); + } + } +}; + +/** + * Is called when a touch is moved across the renderer element + * + * @param event {Event} The DOM event of a touch moving across the renderer view + * @private + */ +InteractionManager.prototype.onTouchMove = function (event) +{ + if (this.autoPreventDefault) + { + event.preventDefault(); + } + + var changedTouches = event.changedTouches; + var cLength = changedTouches.length; + + for (var i=0; i < cLength; i++) + { + var touchEvent = changedTouches[i]; + + var touchData = this.getTouchData( touchEvent ); + + touchData.originalEvent = event; + + this.eventData.data = touchData; + this.eventData.stopped = false; + + this.processInteractive( touchData.global, this.renderer._lastObjectRendered, this.processTouchMove, this.moveWhenInside ); + + this.emit('touchmove', this.eventData); + + this.returnTouchData( touchData ); + } +}; + +/** + * Processes the result of a touch move check and dispatches the event if need be + * + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} The display object that was tested + * @param hit {boolean} the result of the hit test on the display object + * @private + */ +InteractionManager.prototype.processTouchMove = function ( displayObject, hit ) +{ + if(!this.moveWhenInside || hit) + { + this.dispatchEvent( displayObject, 'touchmove', this.eventData); + } +}; + +/** + * Grabs an interaction data object from the internal pool + * + * @param touchEvent {object} The touch event we need to pair with an interactionData object + * + * @private + */ +InteractionManager.prototype.getTouchData = function (touchEvent) +{ + var touchData = this.interactiveDataPool.pop(); + + if(!touchData) + { + touchData = new InteractionData(); + } + + touchData.identifier = touchEvent.identifier; + this.mapPositionToPoint( touchData.global, touchEvent.clientX, touchEvent.clientY ); + + if(navigator.isCocoonJS) + { + touchData.global.x = touchData.global.x / this.resolution; + touchData.global.y = touchData.global.y / this.resolution; + } + + touchEvent.globalX = touchData.global.x; + touchEvent.globalY = touchData.global.y; + + return touchData; +}; + +/** + * Returns an interaction data object to the internal pool + * + * @param touchData {PIXI.interaction.InteractionData} The touch data object we want to return to the pool + * + * @private + */ +InteractionManager.prototype.returnTouchData = function ( touchData ) +{ + this.interactiveDataPool.push( touchData ); +}; + +/** + * Destroys the interaction manager + * + */ +InteractionManager.prototype.destroy = function () { + this.removeEvents(); + + this.removeAllListeners(); + + this.renderer = null; + + this.mouse = null; + + this.eventData = null; + + this.interactiveDataPool = null; + + this.interactionDOMElement = null; + + this.onMouseUp = null; + this.processMouseUp = null; + + + this.onMouseDown = null; + this.processMouseDown = null; + + this.onMouseMove = null; + this.processMouseMove = null; + + this.onMouseOut = null; + this.processMouseOverOut = null; + + this.onMouseOver = null; + + this.onTouchStart = null; + this.processTouchStart = null; + + this.onTouchEnd = null; + this.processTouchEnd = null; + + this.onTouchMove = null; + this.processTouchMove = null; + + this._tempPoint = null; +}; + +core.WebGLRenderer.registerPlugin('interaction', InteractionManager); +core.CanvasRenderer.registerPlugin('interaction', InteractionManager); + +},{"../core":97,"./InteractionData":178,"./interactiveTarget":181,"eventemitter3":32}],180:[function(require,module,exports){ +/** + * @file Main export of the PIXI interactions library + * @author Mat Groves + * @copyright 2013-2015 GoodBoyDigital + * @license {@link https://github.com/pixijs/pixi.js/blob/master/LICENSE|MIT License} + */ + +/** + * @namespace PIXI.interaction + */ +module.exports = { + InteractionData: require('./InteractionData'), + InteractionManager: require('./InteractionManager'), + interactiveTarget: require('./interactiveTarget') +}; + +},{"./InteractionData":178,"./InteractionManager":179,"./interactiveTarget":181}],181:[function(require,module,exports){ +/** + * Default property values of interactive objects + * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties + * + * @mixin + * @memberof PIXI.interaction + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.interaction.interactiveTarget + * ); + */ +var interactiveTarget = { + /** + * Determines if the displayObject be clicked/touched + * + * @inner {boolean} + */ + interactive: false, + + /** + * Determines if the children to the displayObject can be clicked/touched + * Setting this to false allows pixi to bypass a recursive hitTest function + * + * @inner {boolean} + */ + interactiveChildren: true, + + /** + * Interaction shape. Children will be hit first, then this shape will be checked. + * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. + * + * @inner {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle} + */ + hitArea: null, + + /** + * If enabled, the mouse cursor will change when hovered over the displayObject if it is interactive + * + * @inner {boolean} + */ + buttonMode: false, + + /** + * If buttonMode is enabled, this defines what CSS cursor property is used when the mouse cursor is hovered over the displayObject + * https://developer.mozilla.org/en/docs/Web/CSS/cursor + * + * @inner {string} + */ + defaultCursor: 'pointer', + + // some internal checks.. + /** + * Internal check to detect if the mouse cursor is hovered over the displayObject + * + * @inner {boolean} + * @private + */ + _over: false, + + /** + * Internal check to detect if the left mouse button is pressed on the displayObject + * + * @inner {boolean} + * @private + */ + _isLeftDown: false, + + /** + * Internal check to detect if the right mouse button is pressed on the displayObject + * + * @inner {boolean} + * @private + */ + _isRightDown: false, + + /** + * Internal check to detect if a user has touched the displayObject + * + * @inner {boolean} + * @private + */ + _touchDown: false + }; + +module.exports = interactiveTarget; + +},{}],182:[function(require,module,exports){ +var Resource = require('resource-loader').Resource, + core = require('../core'), + extras = require('../extras'), + path = require('path'); + + +function parse(resource, texture) { + var data = {}; + var info = resource.data.getElementsByTagName('info')[0]; + var common = resource.data.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10); + data.chars = {}; + + //parse letters + var letters = resource.data.getElementsByTagName('char'); + + for (var i = 0; i < letters.length; i++) + { + var charCode = parseInt(letters[i].getAttribute('id'), 10); + + var textureRect = new core.Rectangle( + parseInt(letters[i].getAttribute('x'), 10) + texture.frame.x, + parseInt(letters[i].getAttribute('y'), 10) + texture.frame.y, + parseInt(letters[i].getAttribute('width'), 10), + parseInt(letters[i].getAttribute('height'), 10) + ); + + data.chars[charCode] = { + xOffset: parseInt(letters[i].getAttribute('xoffset'), 10), + yOffset: parseInt(letters[i].getAttribute('yoffset'), 10), + xAdvance: parseInt(letters[i].getAttribute('xadvance'), 10), + kerning: {}, + texture: new core.Texture(texture.baseTexture, textureRect) + + }; + } + + //parse kernings + var kernings = resource.data.getElementsByTagName('kerning'); + for (i = 0; i < kernings.length; i++) + { + var first = parseInt(kernings[i].getAttribute('first'), 10); + var second = parseInt(kernings[i].getAttribute('second'), 10); + var amount = parseInt(kernings[i].getAttribute('amount'), 10); + + if(data.chars[second]) + { + data.chars[second].kerning[first] = amount; + } + } + + resource.bitmapFont = data; + + // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 + // but it's very likely to change + extras.BitmapText.fonts[data.font] = data; +} + + +module.exports = function () +{ + return function (resource, next) + { + // skip if no data or not xml data + if (!resource.data || !resource.isXml) + { + return next(); + } + + // skip if not bitmap font data, using some silly duck-typing + if ( + resource.data.getElementsByTagName('page').length === 0 || + resource.data.getElementsByTagName('info').length === 0 || + resource.data.getElementsByTagName('info')[0].getAttribute('face') === null + ) + { + return next(); + } + + var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; + + if (resource.isDataUrl) { + if (xmlUrl === '.') { + xmlUrl = ''; + } + + if (this.baseUrl && xmlUrl) { + // if baseurl has a trailing slash then add one to xmlUrl so the replace works below + if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { + xmlUrl += '/'; + } + + // remove baseUrl from xmlUrl + xmlUrl = xmlUrl.replace(this.baseUrl, ''); + } + } + + // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { + xmlUrl += '/'; + } + + var textureUrl = xmlUrl + resource.data.getElementsByTagName('page')[0].getAttribute('file'); + if (core.utils.TextureCache[textureUrl]) { + //reuse existing texture + parse(resource, core.utils.TextureCache[textureUrl]); + next(); + } + else { + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata + }; + // load the texture for the font + this.add(resource.name + '_image', textureUrl, loadOptions, function (res) { + parse(resource, res.texture); + next(); + }); + } + }; +}; + +},{"../core":97,"../extras":164,"path":60,"resource-loader":69}],183:[function(require,module,exports){ +/** + * @file Main export of the PIXI loaders library + * @author Mat Groves + * @copyright 2013-2015 GoodBoyDigital + * @license {@link https://github.com/pixijs/pixi.js/blob/master/LICENSE|MIT License} + */ + +/** + * @namespace PIXI.loaders + */ +module.exports = { + Loader: require('./loader'), + + // parsers + bitmapFontParser: require('./bitmapFontParser'), + spritesheetParser: require('./spritesheetParser'), + textureParser: require('./textureParser'), + Resource: require('resource-loader').Resource +}; + +},{"./bitmapFontParser":182,"./loader":184,"./spritesheetParser":185,"./textureParser":186,"resource-loader":69}],184:[function(require,module,exports){ +var ResourceLoader = require('resource-loader'), + textureParser = require('./textureParser'), + spritesheetParser = require('./spritesheetParser'), + bitmapFontParser = require('./bitmapFontParser'); + +/** + * + * The new loader, extends Resource Loader by Chad Engler : https://github.com/englercj/resource-loader + * + * ```js + * var loader = PIXI.loader; // pixi exposes a premade instance for you to use. + * //or + * var loader = new PIXI.loaders.Loader(); // you can also create your own if you want + * + * loader.add('bunny',"data/bunny.png"); + * + * loader.once('complete',onAssetsLoaded); + * + * loader.load(); + * ``` + * + * @class + * @extends module:resource-loader.ResourceLoader + * @memberof PIXI.loaders + * @param [baseUrl=''] {string} The base url for all resources loaded by this loader. + * @param [concurrency=10] {number} The number of resources to load concurrently. + * @see https://github.com/englercj/resource-loader + */ +function Loader(baseUrl, concurrency) +{ + ResourceLoader.call(this, baseUrl, concurrency); + + for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { + this.use(Loader._pixiMiddleware[i]()); + } +} + +Loader.prototype = Object.create(ResourceLoader.prototype); +Loader.prototype.constructor = Loader; + +module.exports = Loader; + +Loader._pixiMiddleware = [ + // parse any blob into more usable objects (e.g. Image) + ResourceLoader.middleware.parsing.blob, + // parse any Image objects into textures + textureParser, + // parse any spritesheet data into multiple textures + spritesheetParser, + // parse any spritesheet data into multiple textures + bitmapFontParser +]; + +Loader.addPixiMiddleware = function (fn) { + Loader._pixiMiddleware.push(fn); +}; + +// Add custom extentions +var Resource = ResourceLoader.Resource; + +Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); + +},{"./bitmapFontParser":182,"./spritesheetParser":185,"./textureParser":186,"resource-loader":69}],185:[function(require,module,exports){ +var Resource = require('resource-loader').Resource, + path = require('path'), + core = require('../core'); + +var BATCH_SIZE = 1000; + +module.exports = function () +{ + return function (resource, next) + { + var resourcePath; + var imageResourceName = resource.name + '_image'; + + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data || !resource.isJson || !resource.data.frames || this.resources[imageResourceName]) + { + return next(); + } + + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata + }; + + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) + { + resourcePath = resource.data.meta.image; + } + else + { + resourcePath = path.dirname(resource.url.replace(this.baseUrl, '')) + '/' + resource.data.meta.image; + } + + // load the image for this sheet + this.add(imageResourceName, resourcePath, loadOptions, function (res) + { + resource.textures = {}; + + var frames = resource.data.frames; + var frameKeys = Object.keys(frames); + var resolution = core.utils.getResolutionOfUrl(resource.url); + var batchIndex = 0; + + function processFrames(initialFrameIndex, maxFrames) + { + var frameIndex = initialFrameIndex; + + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < frameKeys.length) + { + var i = frameKeys[frameIndex]; + var rect = frames[i].frame; + + if (rect) + { + + var frame = null; + var trim = null; + var orig = new core.Rectangle(0, 0, frames[i].sourceSize.w / resolution, frames[i].sourceSize.h / resolution); + + if (frames[i].rotated) { + frame = new core.Rectangle(rect.x / resolution, rect.y / resolution, rect.h / resolution, rect.w / resolution); + } + else { + frame = new core.Rectangle(rect.x / resolution, rect.y / resolution, rect.w / resolution, rect.h / resolution); + } + + // Check to see if the sprite is trimmed + if (frames[i].trimmed) + { + trim = new core.Rectangle( + frames[i].spriteSourceSize.x / resolution, + frames[i].spriteSourceSize.y / resolution, + frames[i].spriteSourceSize.w / resolution, + frames[i].spriteSourceSize.h / resolution + ); + } + + resource.textures[i] = new core.Texture(res.texture.baseTexture, frame, orig, trim, frames[i].rotated ? 2 : 0); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage functions + core.utils.TextureCache[i] = resource.textures[i]; + + } + + frameIndex++; + } + } + + function shouldProcessNextBatch() + { + return batchIndex * BATCH_SIZE < frameKeys.length; + } + + function processNextBatch(done) + { + processFrames(batchIndex * BATCH_SIZE, BATCH_SIZE); + batchIndex++; + setTimeout(done, 0); + } + + function iteration() { + processNextBatch(function() { + if (shouldProcessNextBatch()) { + iteration(); + } else { + next(); + } + }); + } + + if (frameKeys.length <= BATCH_SIZE) + { + processFrames(0, BATCH_SIZE); + next(); + } + else + { + iteration(); + } + }); + }; +}; + +},{"../core":97,"path":60,"resource-loader":69}],186:[function(require,module,exports){ +var core = require('../core'); + +module.exports = function () +{ + return function (resource, next) + { + // create a new texture if the data is an Image object + if (resource.data && resource.isImage) + { + var baseTexture = new core.BaseTexture(resource.data, null, core.utils.getResolutionOfUrl(resource.url)); + baseTexture.imageUrl = resource.url; + resource.texture = new core.Texture(baseTexture); + // lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions + core.utils.BaseTextureCache[resource.url] = baseTexture; + core.utils.TextureCache[resource.url] = resource.texture; + } + + next(); + }; +}; + +},{"../core":97}],187:[function(require,module,exports){ +var core = require('../core'), + glCore = require('pixi-gl-core'), + Shader = require('./webgl/MeshShader'), + tempPoint = new core.Point(), + tempPolygon = new core.Polygon(); + +/** + * Base mesh class + * @class + * @extends PIXI.Container + * @memberof PIXI.mesh + * @param texture {PIXI.Texture} The texture to use + * @param [vertices] {Float32Array} if you want to specify the vertices + * @param [uvs] {Float32Array} if you want to specify the uvs + * @param [indices] {Uint16Array} if you want to specify the indices + * @param [drawMode] {number} the drawMode, can be any of the Mesh.DRAW_MODES consts + */ +function Mesh(texture, vertices, uvs, indices, drawMode) +{ + core.Container.call(this); + + /** + * The texture of the Mesh + * + * @member {PIXI.Texture} + * @private + */ + this._texture = null; + + /** + * The Uvs of the Mesh + * + * @member {Float32Array} + */ + this.uvs = uvs || new Float32Array([0, 0, + 1, 0, + 1, 1, + 0, 1]); + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = vertices || new Float32Array([0, 0, + 100, 0, + 100, 100, + 0, 100]); + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + // TODO auto generate this based on draw mode! + this.indices = indices || new Uint16Array([0, 1, 3, 2]); + + /** + * Whether the Mesh is dirty or not + * + * @member {number} + */ + this.dirty = 0; + this.indexDirty = 0; + + /** + * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove any blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other. + * + * @member {number} + */ + this.canvasPadding = 0; + + /** + * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts + * + * @member {number} + * @see PIXI.mesh.Mesh.DRAW_MODES + */ + this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH; + + // run texture setter; + this.texture = texture; + + /** + * The default shader that is used if a mesh doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + this.shader = null; + + + /** + * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any tint effect. + * + * @member {number} + * @memberof PIXI.mesh.Mesh# + */ + this.tintRgb = new Float32Array([1, 1, 1]); + + this._glDatas = []; +} + +// constructor +Mesh.prototype = Object.create(core.Container.prototype); +Mesh.prototype.constructor = Mesh; +module.exports = Mesh; + +Object.defineProperties(Mesh.prototype, { + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + * @memberof PIXI.mesh.Mesh# + */ + texture: { + get: function () + { + return this._texture; + }, + set: function (value) + { + if (this._texture === value) + { + return; + } + + this._texture = value; + + if (value) + { + // wait for the texture to load + if (value.baseTexture.hasLoaded) + { + this._onTextureUpdate(); + } + else + { + value.once('update', this._onTextureUpdate, this); + } + } + } + }, + /** + * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @memberof PIXI.mesh.Mesh# + * @default 0xFFFFFF + */ + tint: { + get: function() { + return core.utils.rgb2hex(this.tintRgb); + }, + set: function(value) { + this.tintRgb = core.utils.hex2rgb(value, this.tintRgb); + } + } +}); + +/** + * Renders the object using the WebGL renderer + * + * @param renderer {PIXI.WebGLRenderer} a reference to the WebGL renderer + * @private + */ +Mesh.prototype._renderWebGL = function (renderer) +{ + // get rid of any thing that may be batching. + renderer.flush(); + + // renderer.plugins.mesh.render(this); + var gl = renderer.gl; + var glData = this._glDatas[renderer.CONTEXT_UID]; + + if(!glData) + { + glData = { + shader:new Shader(gl), + vertexBuffer:glCore.GLBuffer.createVertexBuffer(gl, this.vertices, gl.STREAM_DRAW), + uvBuffer:glCore.GLBuffer.createVertexBuffer(gl, this.uvs, gl.STREAM_DRAW), + indexBuffer:glCore.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW), + // build the vao object that will render.. + vao:new glCore.VertexArrayObject(gl), + dirty:this.dirty, + indexDirty:this.indexDirty + }; + + // build the vao object that will render.. + glData.vao = new glCore.VertexArrayObject(gl) + .addIndex(glData.indexBuffer) + .addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0) + .addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); + + this._glDatas[renderer.CONTEXT_UID] = glData; + + + } + + if(this.dirty !== glData.dirty) + { + glData.dirty = this.dirty; + glData.uvBuffer.upload(); + + } + + if(this.indexDirty !== glData.indexDirty) + { + glData.indexDirty = this.indexDirty; + glData.indexBuffer.upload(); + } + + glData.vertexBuffer.upload(); + + renderer.bindShader(glData.shader); + renderer.bindTexture(this._texture, 0); + renderer.state.setBlendMode(this.blendMode); + + glData.shader.uniforms.translationMatrix = this.worldTransform.toArray(true); + glData.shader.uniforms.alpha = this.worldAlpha; + glData.shader.uniforms.tint = this.tintRgb; + + var drawMode = this.drawMode === Mesh.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + glData.vao.bind() + .draw(drawMode, this.indices.length) + .unbind(); +}; + +/** + * Renders the object using the Canvas renderer + * + * @param renderer {PIXI.CanvasRenderer} + * @private + */ +Mesh.prototype._renderCanvas = function (renderer) +{ + var context = renderer.context; + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) + { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, (transform.tx * res) | 0, (transform.ty * res) | 0); + } + else + { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + if (this.drawMode === Mesh.DRAW_MODES.TRIANGLE_MESH) + { + this._renderCanvasTriangleMesh(context); + } + else + { + this._renderCanvasTriangles(context); + } +}; + +/** + * Draws the object in Triangle Mesh mode using canvas + * + * @param context {CanvasRenderingContext2D} the current drawing context + * @private + */ +Mesh.prototype._renderCanvasTriangleMesh = function (context) +{ + // draw triangles!! + var vertices = this.vertices; + var uvs = this.uvs; + + var length = vertices.length / 2; + // this.count++; + + for (var i = 0; i < length - 2; i++) + { + // draw some triangles! + var index = i * 2; + this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); + } +}; + +/** + * Draws the object in triangle mode using canvas + * + * @param context {CanvasRenderingContext2D} the current drawing context + * @private + */ +Mesh.prototype._renderCanvasTriangles = function (context) +{ + // draw triangles!! + var vertices = this.vertices; + var uvs = this.uvs; + var indices = this.indices; + + var length = indices.length; + // this.count++; + + for (var i = 0; i < length; i += 3) + { + // draw some triangles! + var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; + this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); + } +}; + +/** + * Draws one of the triangles that form this Mesh + * + * @param context {CanvasRenderingContext2D} the current drawing context + * @param vertices {Float32Array} a reference to the vertices of the Mesh + * @param uvs {Float32Array} a reference to the uvs of the Mesh + * @param index0 {number} the index of the first vertex + * @param index1 {number} the index of the second vertex + * @param index2 {number} the index of the third vertex + * @private + */ +Mesh.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ + var base = this._texture.baseTexture; + var textureSource = base.source; + var textureWidth = base.width; + var textureHeight = base.height; + + var x0 = vertices[index0], x1 = vertices[index1], x2 = vertices[index2]; + var y0 = vertices[index0 + 1], y1 = vertices[index1 + 1], y2 = vertices[index2 + 1]; + + var u0 = uvs[index0] * base.width, u1 = uvs[index1] * base.width, u2 = uvs[index2] * base.width; + var v0 = uvs[index0 + 1] * base.height, v1 = uvs[index1 + 1] * base.height, v2 = uvs[index2 + 1] * base.height; + + if (this.canvasPadding > 0) + { + var paddingX = this.canvasPadding / this.worldTransform.a; + var paddingY = this.canvasPadding / this.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt(normX * normX + normY * normY); + x0 = centerX + (normX / dist) * (dist + paddingX); + y0 = centerY + (normY / dist) * (dist + paddingY); + + // + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x1 = centerX + (normX / dist) * (dist + paddingX); + y1 = centerY + (normY / dist) * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x2 = centerX + (normX / dist) * (dist + paddingX); + y2 = centerY + (normY / dist) * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = (u0 * v1) + (v0 * u2) + (u1 * v2) - (v1 * u2) - (v0 * u1) - (u0 * v2); + var deltaA = (x0 * v1) + (v0 * x2) + (x1 * v2) - (v1 * x2) - (v0 * x1) - (x0 * v2); + var deltaB = (u0 * x1) + (x0 * u2) + (u1 * x2) - (x1 * u2) - (x0 * u1) - (u0 * x2); + var deltaC = (u0 * v1 * x2) + (v0 * x1 * u2) + (x0 * u1 * v2) - (x0 * v1 * u2) - (v0 * u1 * x2) - (u0 * x1 * v2); + var deltaD = (y0 * v1) + (v0 * y2) + (y1 * v2) - (v1 * y2) - (v0 * y1) - (y0 * v2); + var deltaE = (u0 * y1) + (y0 * u2) + (u1 * y2) - (y1 * u2) - (y0 * u1) - (u0 * y2); + var deltaF = (u0 * v1 * y2) + (v0 * y1 * u2) + (y0 * u1 * v2) - (y0 * v1 * u2) - (v0 * u1 * y2) - (u0 * y1 * v2); + + context.transform(deltaA / delta, deltaD / delta, + deltaB / delta, deltaE / delta, + deltaC / delta, deltaF / delta); + + context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + context.restore(); +}; + + + +/** + * Renders a flat Mesh + * + * @param Mesh {PIXI.mesh.Mesh} The Mesh to render + * @private + */ +Mesh.prototype.renderMeshFlat = function (Mesh) +{ + var context = this.context; + var vertices = Mesh.vertices; + + var length = vertices.length/2; + // this.count++; + + context.beginPath(); + for (var i=1; i < length-2; i++) + { + // draw some triangles! + var index = i*2; + + var x0 = vertices[index], x1 = vertices[index+2], x2 = vertices[index+4]; + var y0 = vertices[index+1], y1 = vertices[index+3], y2 = vertices[index+5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); +}; + +/** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ +Mesh.prototype._onTextureUpdate = function () +{ + +}; + +/** + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + * @param [matrix=this.worldTransform] {PIXI.Matrix} the transformation matrix of the sprite + * @return {PIXI.Rectangle} the framing rectangle + */ +Mesh.prototype._calculateBounds = function () +{ + //TODO - we can cache local bounds and use them if they are dirty (like graphics) + this._bounds.addVertices(this.transform, this.vertices, 0, this.vertices.length); +}; + +/** + * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH + * + * @param point {PIXI.Point} the point to test + * @return {boolean} the result of the test + */ +Mesh.prototype.containsPoint = function( point ) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + this.worldTransform.applyInverse(point, tempPoint); + + var vertices = this.vertices; + var points = tempPolygon.points; + + var indices = this.indices; + var len = this.indices.length; + var step = this.drawMode === Mesh.DRAW_MODES.TRIANGLES ? 3 : 1; + for (var i=0;i+2 + * A B + * +---+----------------------+---+ + * C | 1 | 2 | 3 | + * +---+----------------------+---+ + * | | | | + * | 4 | 5 | 6 | + * | | | | + * +---+----------------------+---+ + * D | 7 | 8 | 9 | + * +---+----------------------+---+ + + * When changing this objects width and/or height: + * areas 1 3 7 and 9 will remain unscaled. + * areas 2 and 8 will be stretched horizontally + * areas 4 and 6 will be stretched vertically + * area 5 will be stretched both horizontally and vertically + * + * + * @class + * @extends PIXI.mesh.Plane + * @memberof PIXI.mesh + * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. + * @param {int} [leftWidth=10] size of the left vertical bar (A) + * @param {int} [topHeight=10] size of the top horizontal bar (C) + * @param {int} [rightWidth=10] size of the right vertical bar (B) + * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) + * + */ +function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) +{ + Plane.call(this, texture, 4, 4); + + var uvs = this.uvs; + // right and bottom uv's are always 1 + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + + this._origWidth = texture.width; + this._origHeight = texture.height; + this._uvw = 1 / this._origWidth; + this._uvh = 1 / this._origHeight; + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + this.width = texture.width; + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + this.height = texture.height; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = this._uvw * leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - this._uvw * rightWidth; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = this._uvh * topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - this._uvh * bottomHeight; + + /** + * The width of the left column (a) + * + * @member {number} + */ + this.leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; + /** + * The width of the right column (b) + * + * @member {number} + */ + this.rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; + /** + * The height of the top row (c) + * + * @member {number} + */ + this.topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; + /** + * The height of the bottom row (d) + * + * @member {number} + */ + this.bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; +} + + +// constructor +NineSlicePlane.prototype = Object.create( Plane.prototype ); +NineSlicePlane.prototype.constructor = NineSlicePlane; +module.exports = NineSlicePlane; + +Object.defineProperties(NineSlicePlane.prototype, { + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + width: { + get: function () + { + return this._width; + }, + set: function (value) + { + this._width = value; + this.updateVerticalVertices(); + } + }, + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + height: { + get: function () + { + return this._height; + }, + set: function (value) + { + this._height = value; + this.updateHorizontalVertices(); + } + }, + + /** + * The width of the left column + * + * @member {number} + */ + leftWidth: { + get: function() + { + return this._leftWidth; + }, + set: function (value) + { + this._leftWidth = value; + var uvs = this.uvs; + var vertices = this.vertices; + uvs[2] = uvs[10] = uvs[18] = uvs[26] = this._uvw * value; + vertices[2] = vertices[10] = vertices[18] = vertices[26] = value; + this.dirty=true; + } + }, + /** + * The width of the right column + * + * @member {number} + */ + rightWidth: { + get: function() + { + return this._rightWidth; + }, + set: function (value) + { + this._rightWidth = value; + var uvs = this.uvs; + var vertices = this.vertices; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - this._uvw * value; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - value; + this.dirty=true; + } + }, + /** + * The height of the top row + * + * @member {number} + */ + topHeight: { + get: function() + { + return this._topHeight; + }, + set: function (value) + { + this._topHeight = value; + var uvs = this.uvs; + var vertices = this.vertices; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = this._uvh * value; + vertices[9] = vertices[11] = vertices[13] = vertices[15] = value; + this.dirty=true; + } + }, + /** + * The height of the bottom row + * + * @member {number} + */ + bottomHeight: { + get: function() + { + return this._bottomHeight; + }, + set: function (value) + { + this._bottomHeight = value; + var uvs = this.uvs; + var vertices = this.vertices; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - this._uvh * value; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - value; + this.dirty=true; + } + } +}); + +NineSlicePlane.prototype.updateHorizontalVertices = function() { + var vertices = this.vertices; + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight; + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; +}; + +NineSlicePlane.prototype.updateVerticalVertices = function() { + var vertices = this.vertices; + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth; + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width ; +}; + +/** + * Renders the object using the Canvas renderer + * + * @param renderer {PIXI.CanvasRenderer} + * @private + */ +NineSlicePlane.prototype._renderCanvas= function (renderer) +{ + var context = renderer.context; + context.globalAlpha = this.worldAlpha; + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) + { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, (transform.tx * res) | 0, (transform.ty * res) | 0); + } + else + { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + var base = this._texture.baseTexture; + var textureSource = base.source; + var w = base.width; + var h = base.height; + + this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11); + this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13); + this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15); + this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19); + this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21); + this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23); + this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27); + this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29); + this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31); +}; + +/** + * Renders one segment of the plane. + * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure + * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used. + * + * @param context + * @param textureSource + * @param w width of the texture + * @param h height of the texture + * @param x1 + * @param y1 + * @param x2 + * @param y2 + * @private + */ +NineSlicePlane.prototype.drawSegment= function (context, textureSource, w, h, x1, y1, x2, y2) +{ + // otherwise you get weird results when using slices of that are 0 wide or high. + var uvs = this.uvs; + var vertices = this.vertices; + + var sw = (uvs[x2]-uvs[x1]) * w; + var sh = (uvs[y2]-uvs[y1]) * h; + var dw = vertices[x2] - vertices[x1]; + var dh = vertices[y2] - vertices[y1]; + + // make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn. + if (sw<1) { + sw=1; + } + if (sh<1) { + sh=1; + } + // make sure destination is at least 1 pixel wide and high, otherwise you get lines when rendering close to original size. + if (dw<1) { + dw=1; + } + if (dh<1) { + dh=1; + } + context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh); +}; + +},{"./Plane":189}],189:[function(require,module,exports){ +var Mesh = require('./Mesh'); + +/** + * The Plane allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (var i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * var Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * @param {PIXI.Texture} texture - The texture to use on the Plane. + * @param {number} verticesX - The number of vertices in the x-axis + * @param {number} verticesY - The number of vertices in the y-axis + * + */ +function Plane(texture, verticesX, verticesY) +{ + Mesh.call(this, texture); + + /** + * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + this._ready = true; + + this.verticesX = verticesX || 10; + this.verticesY = verticesY || 10; + + this.drawMode = Mesh.DRAW_MODES.TRIANGLES; + this.refresh(); + +} + + +// constructor +Plane.prototype = Object.create( Mesh.prototype ); +Plane.prototype.constructor = Plane; +module.exports = Plane; + +/** + * Refreshes + * + */ +Plane.prototype.refresh = function() +{ + var total = this.verticesX * this.verticesY; + var verts = []; + var colors = []; + var uvs = []; + var indices = []; + var texture = this.texture; + + var segmentsX = this.verticesX - 1; + var segmentsY = this.verticesY - 1; + var i = 0; + + var sizeX = texture.width / segmentsX; + var sizeY = texture.height / segmentsY; + + for (i = 0; i < total; i++) { + + var x = (i % this.verticesX); + var y = ( (i / this.verticesX ) | 0 ); + + + verts.push((x * sizeX), + (y * sizeY)); + + // this works for rectangular textures. + uvs.push(texture._uvs.x0 + (texture._uvs.x1 - texture._uvs.x0) * (x / (this.verticesX-1)), texture._uvs.y0 + (texture._uvs.y3-texture._uvs.y0) * (y/ (this.verticesY-1))); + } + + // cons + + var totalSub = segmentsX * segmentsY; + + for (i = 0; i < totalSub; i++) { + + var xpos = i % segmentsX; + var ypos = (i / segmentsX ) | 0; + + + var value = (ypos * this.verticesX) + xpos; + var value2 = (ypos * this.verticesX) + xpos + 1; + var value3 = ((ypos+1) * this.verticesX) + xpos; + var value4 = ((ypos+1) * this.verticesX) + xpos + 1; + + indices.push(value, value2, value3); + indices.push(value2, value4, value3); + } + + + //console.log(indices) + this.vertices = new Float32Array(verts); + this.uvs = new Float32Array(uvs); + this.colors = new Float32Array(colors); + this.indices = new Uint16Array(indices); + + this.indexDirty = true; +}; + +/** + * Clear texture UVs when new texture is set + * + * @private + */ +Plane.prototype._onTextureUpdate = function () +{ + Mesh.prototype._onTextureUpdate.call(this); + + // wait for the Plane ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } +}; + +},{"./Mesh":187}],190:[function(require,module,exports){ +var Mesh = require('./Mesh'); +var core = require('../core'); + +/** + * The rope allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (var i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * var rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * @param {PIXI.Texture} texture - The texture to use on the rope. + * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. + * + */ +function Rope(texture, points) +{ + Mesh.call(this, texture); + + /* + * @member {PIXI.Point[]} An array of points that determine the rope + */ + this.points = points; + + /* + * @member {Float32Array} An array of vertices used to construct this rope. + */ + this.vertices = new Float32Array(points.length * 4); + + /* + * @member {Float32Array} The WebGL Uvs of the rope. + */ + this.uvs = new Float32Array(points.length * 4); + + /* + * @member {Float32Array} An array containing the color components + */ + this.colors = new Float32Array(points.length * 2); + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + this.indices = new Uint16Array(points.length * 2); + + /** + * Tracker for if the rope is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + this._ready = true; + + this.refresh(); +} + + +// constructor +Rope.prototype = Object.create(Mesh.prototype); +Rope.prototype.constructor = Rope; +module.exports = Rope; + +/** + * Refreshes + * + */ +Rope.prototype.refresh = function () +{ + var points = this.points; + + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1 || !this._texture._uvs) + { + return; + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + var textureUvs = this._texture._uvs; + var offset = new core.Point(textureUvs.x0, textureUvs.y0); + var factor = new core.Point(textureUvs.x2 - textureUvs.x0, textureUvs.y2 - textureUvs.y0); + + uvs[0] = 0 + offset.x; + uvs[1] = 0 + offset.y; + uvs[2] = 0 + offset.x; + uvs[3] = 1 * factor.y + offset.y; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length, + point, index, amount; + + for (var i = 1; i < total; i++) + { + point = points[i]; + index = i * 4; + // time to do some smart drawing! + amount = i / (total-1); + + uvs[index] = amount * factor.x + offset.x; + uvs[index+1] = 0 + offset.y; + + uvs[index+2] = amount * factor.x + offset.x; + uvs[index+3] = 1 * factor.y + offset.y; + + index = i * 2; + colors[index] = 1; + colors[index+1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + + this.dirty = true; + this.indexDirty = true; +}; + +/** + * Clear texture UVs when new texture is set + * + * @private + */ +Rope.prototype._onTextureUpdate = function () +{ + + Mesh.prototype._onTextureUpdate.call(this); + + // wait for the Rope ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } +}; + +/** + * Updates the object transform for rendering + * + * @private + */ +Rope.prototype.updateTransform = function () +{ + var points = this.points; + + if (points.length < 1) + { + return; + } + + var lastPoint = points[0]; + var nextPoint; + var perpX = 0; + var perpY = 0; + + // this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length, + point, index, ratio, perpLength, num; + + for (var i = 0; i < total; i++) + { + point = points[i]; + index = i * 4; + + if (i < points.length-1) + { + nextPoint = points[i+1]; + } + else + { + nextPoint = point; + } + + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + + ratio = (1 - (i / (total-1))) * 10; + + if (ratio > 1) + { + ratio = 1; + } + + perpLength = Math.sqrt(perpX * perpX + perpY * perpY); + num = this._texture.height / 2; //(20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; + perpX /= perpLength; + perpY /= perpLength; + + perpX *= num; + perpY *= num; + + vertices[index] = point.x + perpX; + vertices[index+1] = point.y + perpY; + vertices[index+2] = point.x - perpX; + vertices[index+3] = point.y - perpY; + + lastPoint = point; + } + + this.containerUpdateTransform(); +}; + +},{"../core":97,"./Mesh":187}],191:[function(require,module,exports){ +/** + * @file Main export of the PIXI extras library + * @author Mat Groves + * @copyright 2013-2015 GoodBoyDigital + * @license {@link https://github.com/pixijs/pixi.js/blob/master/LICENSE|MIT License} + */ + +/** + * @namespace PIXI.mesh + */ +module.exports = { + Mesh: require('./Mesh'), + Plane: require('./Plane'), + NineSlicePlane: require('./NineSlicePlane'), + Rope: require('./Rope'), + MeshShader: require('./webgl/MeshShader') +}; + +},{"./Mesh":187,"./NineSlicePlane":188,"./Plane":189,"./Rope":190,"./webgl/MeshShader":192}],192:[function(require,module,exports){ +var Shader = require('../../core/Shader'); + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI.mesh + * @param gl {PIXI.Shader} TODO: Find a good explanation for this. + */ +function MeshShader(gl) +{ + Shader.call(this, + gl, + // vertex shader + [ + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', + + 'varying vec2 vTextureCoord;', + + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vTextureCoord = aTextureCoord;', + '}' + ].join('\n'), + [ + 'varying vec2 vTextureCoord;', + 'uniform float alpha;', + 'uniform vec3 tint;', + + 'uniform sampler2D uSampler;', + + 'void main(void){', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vec4(tint * alpha, alpha);', + // ' gl_FragColor = vec4(1.0);', + '}' + ].join('\n') + ); +} + +MeshShader.prototype = Object.create(Shader.prototype); +MeshShader.prototype.constructor = MeshShader; +module.exports = MeshShader; + + +},{"../../core/Shader":77}],193:[function(require,module,exports){ +var core = require('../core'); + +/** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that advanced + * functionality will not work. ParticleContainer implements only the basic object transform (position, scale, rotation). + * Any other functionality like tinting, masking, etc will not work on sprites in this batch. + * + * It's extremely easy to use : + * + * ```js + * var container = new ParticleContainer(); + * + * for (var i = 0; i < 100; ++i) + * { + * var sprite = new PIXI.Sprite.fromImage("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be renderer at the speed of light. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.particles + * @param [maxSize=15000] {number} The maximum number of particles that can be renderer by the container. + * @param [properties] {object} The properties of children that should be uploaded to the gpu and applied. + * @param [properties.scale=false] {boolean} When true, scale be uploaded and applied. + * @param [properties.position=true] {boolean} When true, position be uploaded and applied. + * @param [properties.rotation=false] {boolean} When true, rotation be uploaded and applied. + * @param [properties.uvs=false] {boolean} When true, uvs be uploaded and applied. + * @param [properties.alpha=false] {boolean} When true, alpha be uploaded and applied. + * @param [batchSize=15000] {number} Number of particles per batch. + */ +function ParticleContainer(maxSize, properties, batchSize) +{ + core.Container.call(this); + + batchSize = batchSize || 15000; //CONST.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + maxSize = maxSize || 15000; + + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var maxBatchSize = 16384; + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + + if (batchSize > maxSize) { + batchSize = maxSize; + } + + /** + * Set properties to be dynamic (true) / static (false) + * + * @member {boolean[]} + * @private + */ + this._properties = [false, true, false, false, false]; + + /** + * @member {number} + * @private + */ + this._maxSize = maxSize; + + /** + * @member {number} + * @private + */ + this._batchSize = batchSize; + + /** + * @member {WebGLBuffer} + * @private + */ + this._glBuffers = []; + + /** + * @member {number} + * @private + */ + this._bufferToUpdate = 0; + + /** + * @member {boolean} + * + */ + this.interactiveChildren = false; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Used for canvas renderering. If true then the elements will be positioned at the nearest pixel. This provides a nice speed boost. + * + * @member {boolean} + * @default true; + */ + this.roundPixels = true; + + this.baseTexture = null; + + this.setProperties(properties); +} + +ParticleContainer.prototype = Object.create(core.Container.prototype); +ParticleContainer.prototype.constructor = ParticleContainer; +module.exports = ParticleContainer; + +/** + * Sets the private properties array to dynamic / static based on the passed properties object + * + * @param properties {object} The properties to be uploaded + */ +ParticleContainer.prototype.setProperties = function(properties) +{ + if ( properties ) { + this._properties[0] = 'scale' in properties ? !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'alpha' in properties ? !!properties.alpha : this._properties[4]; + } +}; + +/** + * Updates the object transform for rendering + * + * @private + */ +ParticleContainer.prototype.updateTransform = function () +{ + + // TODO don't need to! + this.displayObjectUpdateTransform(); + // PIXI.Container.prototype.updateTransform.call( this ); +}; + +/** + * Renders the container using the WebGL renderer + * + * @param renderer {PIXI.WebGLRenderer} The webgl renderer + * @private + */ +ParticleContainer.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) + { + return; + } + + + if(!this.baseTexture) + { + this.baseTexture = this.children[0]._texture.baseTexture; + if(!this.baseTexture.hasLoaded) + { + this.baseTexture.once('update', function(){ + this.onChildrenChange(0); + }, this); + } + } + + + renderer.setObjectRenderer( renderer.plugins.particle ); + renderer.plugins.particle.render( this ); +}; + +/** + * Set the flag that static data should be updated to true + * + * @private + */ +ParticleContainer.prototype.onChildrenChange = function (smallestChildIndex) +{ + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + if (bufferIndex < this._bufferToUpdate) { + this._bufferToUpdate = bufferIndex; + } +}; + +/** + * Renders the object using the Canvas renderer + * + * @param renderer {PIXI.CanvasRenderer} The canvas renderer + * @private + */ +ParticleContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) + { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var isRotated = true; + + var positionX = 0; + var positionY = 0; + + var finalWidth = 0; + var finalHeight = 0; + + var compositeOperation = renderer.blendModes[this.blendMode]; + if (compositeOperation !== context.globalCompositeOperation) + { + context.globalCompositeOperation = compositeOperation; + } + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + for (var i = 0; i < this.children.length; ++i) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + var frame = child.texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) + { + // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call + if (isRotated) + { + context.setTransform( + transform.a, + transform.b, + transform.c, + transform.d, + transform.tx * renderer.resolution, + transform.ty * renderer.resolution + ); + + isRotated = false; + } + + positionX = ((child.anchor.x) * (-frame.width * child.scale.x) + child.position.x + 0.5); + positionY = ((child.anchor.y) * (-frame.height * child.scale.y) + child.position.y + 0.5); + + finalWidth = frame.width * child.scale.x; + finalHeight = frame.height * child.scale.y; + + } + else + { + if (!isRotated) + { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + + if (renderer.roundPixels) + { + context.setTransform( + childTransform.a, + childTransform.b, + childTransform.c, + childTransform.d, + (childTransform.tx * renderer.resolution) | 0, + (childTransform.ty * renderer.resolution) | 0 + ); + } + else + { + context.setTransform( + childTransform.a, + childTransform.b, + childTransform.c, + childTransform.d, + childTransform.tx * renderer.resolution, + childTransform.ty * renderer.resolution + ); + } + + positionX = ((child.anchor.x) * (-frame.width) + 0.5); + positionY = ((child.anchor.y) * (-frame.height) + 0.5); + + finalWidth = frame.width; + finalHeight = frame.height; + } + + var resolution = child.texture.baseTexture.resolution; + + context.drawImage( + child.texture.baseTexture.source, + frame.x * resolution, + frame.y * resolution, + frame.width * resolution, + frame.height * resolution, + positionX * resolution, + positionY * resolution, + finalWidth * resolution, + finalHeight * resolution + ); + } +}; + +/** + * Destroys the container + * + */ +ParticleContainer.prototype.destroy = function () { + core.Container.prototype.destroy.apply(this, arguments); + + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + } + + this._properties = null; + this._buffers = null; +}; + +},{"../core":97}],194:[function(require,module,exports){ +/** + * @file Main export of the PIXI extras library + * @author Mat Groves + * @copyright 2013-2015 GoodBoyDigital + * @license {@link https://github.com/pixijs/pixi.js/blob/master/LICENSE|MIT License} + */ + +/** + * @namespace PIXI.particles + */ +module.exports = { + ParticleContainer: require('./ParticleContainer'), + ParticleRenderer: require('./webgl/ParticleRenderer') +}; + +},{"./ParticleContainer":193,"./webgl/ParticleRenderer":196}],195:[function(require,module,exports){ +var glCore = require('pixi-gl-core'), + createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + +/** + * The particle buffer manages the static and dynamic buffers for a particle container. + * + * @class + * @private + * @memberof PIXI + */ +function ParticleBuffer(gl, properties, dynamicPropertyFlags, size) +{ + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * Size of a single vertex. + * + * @member {number} + */ + this.vertSize = 2; + + /** + * Size of a single vertex in bytes. + * + * @member {number} + */ + this.vertByteSize = this.vertSize * 4; + + /** + * The number of particles the buffer can hold + * + * @member {number} + */ + this.size = size; + + /** + * A list of the properties that are dynamic. + * + * @member {object[]} + */ + this.dynamicProperties = []; + + /** + * A list of the properties that are static. + * + * @member {object[]} + */ + this.staticProperties = []; + + for (var i = 0; i < properties.length; i++) + { + var property = properties[i]; + + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = + { + attribute:property.attribute, + size:property.size, + uploadFunction:property.uploadFunction, + offset:property.offset + }; + + if(dynamicPropertyFlags[i]) + { + this.dynamicProperties.push(property); + } + else + { + this.staticProperties.push(property); + } + } + + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + + this.initBuffers(); + +} + +ParticleBuffer.prototype.constructor = ParticleBuffer; +module.exports = ParticleBuffer; + +/** + * Sets up the renderer context and necessary buffers. + * + * @private + */ +ParticleBuffer.prototype.initBuffers = function () +{ + var gl = this.gl; + var i; + var property; + + var dynamicOffset = 0; + + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = createIndicesForQuads(this.size); + this.indexBuffer = glCore.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + + this.dynamicStride = 0; + + for (i = 0; i < this.dynamicProperties.length; i++) + { + property = this.dynamicProperties[i]; + + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + + this.dynamicData = new Float32Array( this.size * this.dynamicStride * 4); + this.dynamicBuffer = glCore.GLBuffer.createVertexBuffer(gl, this.dynamicData, gl.STREAM_DRAW); + + // static // + var staticOffset = 0; + this.staticStride = 0; + + for (i = 0; i < this.staticProperties.length; i++) + { + property = this.staticProperties[i]; + + property.offset = staticOffset; + staticOffset += property.size; + this.staticStride += property.size; + + + } + + this.staticData = new Float32Array( this.size * this.staticStride * 4); + this.staticBuffer = glCore.GLBuffer.createVertexBuffer(gl, this.staticData, gl.STATIC_DRAW); + + + this.vao = new glCore.VertexArrayObject(gl) + .addIndex(this.indexBuffer); + + for (i = 0; i < this.dynamicProperties.length; i++) + { + property = this.dynamicProperties[i]; + this.vao.addAttribute(this.dynamicBuffer, property.attribute, gl.FLOAT, false, this.dynamicStride * 4, property.offset * 4); + } + + for (i = 0; i < this.staticProperties.length; i++) + { + property = this.staticProperties[i]; + this.vao.addAttribute(this.staticBuffer, property.attribute, gl.FLOAT, false, this.staticStride * 4, property.offset * 4); + } +}; + +/** + * Uploads the dynamic properties. + * + */ +ParticleBuffer.prototype.uploadDynamic = function(children, startIndex, amount) +{ + for (var i = 0; i < this.dynamicProperties.length; i++) + { + var property = this.dynamicProperties[i]; + property.uploadFunction(children, startIndex, amount, this.dynamicData, this.dynamicStride, property.offset); + } + + this.dynamicBuffer.upload(); +}; + +/** + * Uploads the static properties. + * + */ +ParticleBuffer.prototype.uploadStatic = function(children, startIndex, amount) +{ + for (var i = 0; i < this.staticProperties.length; i++) + { + var property = this.staticProperties[i]; + property.uploadFunction(children, startIndex, amount, this.staticData, this.staticStride, property.offset); + } + + this.staticBuffer.upload(); +}; + +/** + * Binds the buffers to the GPU + * + */ +ParticleBuffer.prototype.bind = function () +{ + this.vao.bind(); +}; + +/** + * Destroys the ParticleBuffer. + * + */ +ParticleBuffer.prototype.destroy = function () +{ + this.dynamicProperties = null; + this.dynamicData = null; + this.dynamicBuffer.destroy(); + + this.staticProperties = null; + this.staticData = null; + this.staticBuffer.destroy(); +}; + +},{"../../core/utils/createIndicesForQuads":149,"pixi-gl-core":7}],196:[function(require,module,exports){ +var core = require('../../core'), + ParticleShader = require('./ParticleShader'), + ParticleBuffer = require('./ParticleBuffer'); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + +/** + * + * @class + * @private + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} The renderer this sprite batch works for. + */ +function ParticleRenderer(renderer) +{ + core.ObjectRenderer.call(this, renderer); + + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // var numIndices = 98304; + + /** + * The default shader that is used if a sprite doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + this.shader = null; + + this.indexBuffer = null; + + this.properties = null; + + this.tempMatrix = new core.Matrix(); + + this.CONTEXT_UID = 0; +} + +ParticleRenderer.prototype = Object.create(core.ObjectRenderer.prototype); +ParticleRenderer.prototype.constructor = ParticleRenderer; +module.exports = ParticleRenderer; + +core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + +/** + * When there is a WebGL context change + * + * @private + */ +ParticleRenderer.prototype.onContextChange = function () +{ + var gl = this.renderer.gl; + + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + + // setup default shader + this.shader = new ParticleShader(gl); + + this.properties = [ + // verticesData + { + attribute:this.shader.attributes.aVertexPosition, + size:2, + uploadFunction:this.uploadVertices, + offset:0 + }, + // positionData + { + attribute:this.shader.attributes.aPositionCoord, + size:2, + uploadFunction:this.uploadPosition, + offset:0 + }, + // rotationData + { + attribute:this.shader.attributes.aRotation, + size:1, + uploadFunction:this.uploadRotation, + offset:0 + }, + // uvsData + { + attribute:this.shader.attributes.aTextureCoord, + size:2, + uploadFunction:this.uploadUvs, + offset:0 + }, + // alphaData + { + attribute:this.shader.attributes.aColor, + size:1, + uploadFunction:this.uploadAlpha, + offset:0 + } + ]; + +}; + +/** + * Starts a new particle batch. + * + */ +ParticleRenderer.prototype.start = function () +{ + this.renderer.bindShader(this.shader); +}; + + +/** + * Renders the particle container object. + * + * @param container {PIXI.ParticleContainer} The container to render using this ParticleRenderer + */ +ParticleRenderer.prototype.render = function (container) +{ + var children = container.children, + totalChildren = children.length, + maxSize = container._maxSize, + batchSize = container._batchSize; + + if(totalChildren === 0) + { + return; + } + else if(totalChildren > maxSize) + { + totalChildren = maxSize; + } + + var buffers = container._glBuffers[this.renderer.CONTEXT_UID]; + + if(!buffers) + { + buffers = container._glBuffers[this.renderer.CONTEXT_UID] = this.generateBuffers( container ); + } + + // if the uvs have not updated then no point rendering just yet! + this.renderer.setBlendMode(container.blendMode); + + var gl = this.renderer.gl; + + var m = container.worldTransform.copy( this.tempMatrix ); + m.prepend( this.renderer._activeRenderTarget.projectionMatrix ); + this.shader.uniforms.projectionMatrix = m.toArray(true); + this.shader.uniforms.uAlpha = container.worldAlpha; + + + // make sure the texture is bound.. + var baseTexture = children[0]._texture.baseTexture; + + this.renderer.bindTexture(baseTexture); + + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) + { + var amount = ( totalChildren - i); + if(amount > batchSize) + { + amount = batchSize; + } + + var buffer = buffers[j]; + + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + + // we only upload the static content when we have to! + if(container._bufferToUpdate === j) + { + buffer.uploadStatic(children, i, amount); + container._bufferToUpdate = j + 1; + } + + // bind the buffer + buffer.vao.bind() + .draw(gl.TRIANGLES, amount * 6) + .unbind(); + + // now draw those suckas! + // gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0); + // this.renderer.drawCount++; + } +}; + +/** + * Creates one particle buffer for each child in the container we want to render and updates internal properties + * + * @param container {PIXI.ParticleContainer} The container to render using this ParticleRenderer + */ +ParticleRenderer.prototype.generateBuffers = function (container) +{ + var gl = this.renderer.gl, + buffers = [], + size = container._maxSize, + batchSize = container._batchSize, + dynamicPropertyFlags = container._properties, + i; + + for (i = 0; i < size; i += batchSize) + { + buffers.push(new ParticleBuffer(gl, this.properties, dynamicPropertyFlags, batchSize)); + } + + return buffers; +}; + +/** + * Uploads the verticies. + * + * @param children {PIXI.DisplayObject[]} the array of display objects to render + * @param startIndex {number} the index to start from in the children array + * @param amount {number} the amount of children that will have their vertices uploaded + * @param array {number[]} + * @param stride {number} + * @param offset {number} + */ +ParticleRenderer.prototype.uploadVertices = function (children, startIndex, amount, array, stride, offset) +{ + var sprite, + texture, + trim, + orig, + sx, + sy, + w0, w1, h0, h1; + + for (var i = 0; i < amount; i++) { + + sprite = children[startIndex + i]; + texture = sprite._texture; + sx = sprite.scale.x; + sy = sprite.scale.y; + trim = texture.trim; + orig = texture.orig; + + if (trim) + { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra space before transforming the sprite coords.. + w1 = trim.x - sprite.anchor.x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - sprite.anchor.y * orig.height; + h0 = h1 + trim.height; + + } + else + { + w0 = (orig.width ) * (1-sprite.anchor.x); + w1 = (orig.width ) * -sprite.anchor.x; + + h0 = orig.height * (1-sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + + array[offset + stride * 2] = w0 * sx; + array[offset + stride * 2 + 1] = h0 * sy; + + array[offset + stride * 3] = w1 * sx; + array[offset + stride * 3 + 1] = h0 * sy; + + offset += stride * 4; + } + +}; + +/** + * + * @param children {PIXI.DisplayObject[]} the array of display objects to render + * @param startIndex {number} the index to start from in the children array + * @param amount {number} the amount of children that will have their positions uploaded + * @param array {number[]} + * @param stride {number} + * @param offset {number} + */ +ParticleRenderer.prototype.uploadPosition = function (children,startIndex, amount, array, stride, offset) +{ + for (var i = 0; i < amount; i++) + { + var spritePosition = children[startIndex + i].position; + + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + + array[offset + stride * 2] = spritePosition.x; + array[offset + stride * 2 + 1] = spritePosition.y; + + array[offset + stride * 3] = spritePosition.x; + array[offset + stride * 3 + 1] = spritePosition.y; + + offset += stride * 4; + } + +}; + +/** + * + * @param children {PIXI.DisplayObject[]} the array of display objects to render + * @param startIndex {number} the index to start from in the children array + * @param amount {number} the amount of children that will have their rotation uploaded + * @param array {number[]} + * @param stride {number} + * @param offset {number} + */ +ParticleRenderer.prototype.uploadRotation = function (children,startIndex, amount, array, stride, offset) +{ + for (var i = 0; i < amount; i++) + { + var spriteRotation = children[startIndex + i].rotation; + + + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + stride * 2] = spriteRotation; + array[offset + stride * 3] = spriteRotation; + + offset += stride * 4; + } +}; + +/** + * + * @param children {PIXI.DisplayObject[]} the array of display objects to render + * @param startIndex {number} the index to start from in the children array + * @param amount {number} the amount of children that will have their Uvs uploaded + * @param array {number[]} + * @param stride {number} + * @param offset {number} + */ +ParticleRenderer.prototype.uploadUvs = function (children,startIndex, amount, array, stride, offset) +{ + for (var i = 0; i < amount; i++) + { + var textureUvs = children[startIndex + i]._texture._uvs; + + if (textureUvs) + { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + + array[offset + stride * 2] = textureUvs.x2; + array[offset + stride * 2 + 1] = textureUvs.y2; + + array[offset + stride * 3] = textureUvs.x3; + array[offset + stride * 3 + 1] = textureUvs.y3; + + offset += stride * 4; + } + else + { + //TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + + array[offset + stride * 2] = 0; + array[offset + stride * 2 + 1] = 0; + + array[offset + stride * 3] = 0; + array[offset + stride * 3 + 1] = 0; + + offset += stride * 4; + } + } +}; + +/** + * + * @param children {PIXI.DisplayObject[]} the array of display objects to render + * @param startIndex {number} the index to start from in the children array + * @param amount {number} the amount of children that will have their alpha uploaded + * @param array {number[]} + * @param stride {number} + * @param offset {number} + */ +ParticleRenderer.prototype.uploadAlpha = function (children,startIndex, amount, array, stride, offset) +{ + for (var i = 0; i < amount; i++) + { + var spriteAlpha = children[startIndex + i].alpha; + + array[offset] = spriteAlpha; + array[offset + stride] = spriteAlpha; + array[offset + stride * 2] = spriteAlpha; + array[offset + stride * 3] = spriteAlpha; + + offset += stride * 4; + } +}; + + +/** + * Destroys the ParticleRenderer. + * + */ +ParticleRenderer.prototype.destroy = function () +{ + if (this.renderer.gl) { + this.renderer.gl.deleteBuffer(this.indexBuffer); + } + core.ObjectRenderer.prototype.destroy.apply(this, arguments); + + this.shader.destroy(); + + this.indices = null; + this.tempMatrix = null; +}; + +},{"../../core":97,"./ParticleBuffer":195,"./ParticleShader":197}],197:[function(require,module,exports){ +var Shader = require('../../core/Shader'); + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI + * @param gl {PIXI.Shader} The webgl shader manager this shader works for. + */ +function ParticleShader(gl) +{ + Shader.call(this, + gl, + // vertex shader + [ + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute float aColor;', + + 'attribute vec2 aPositionCoord;', + 'attribute vec2 aScale;', + 'attribute float aRotation;', + + 'uniform mat3 projectionMatrix;', + + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + + 'void main(void){', + ' vec2 v = aVertexPosition;', + + ' v.x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);', + ' v.y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);', + ' v = v + aPositionCoord;', + + ' gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);', + + ' vTextureCoord = aTextureCoord;', + ' vColor = aColor;', + '}' + ].join('\n'), + // hello + [ + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + + 'uniform sampler2D uSampler;', + 'uniform float uAlpha;', + + 'void main(void){', + ' vec4 color = texture2D(uSampler, vTextureCoord) * vColor * uAlpha;', + ' if (color.a == 0.0) discard;', + ' gl_FragColor = color;', + '}' + ].join('\n') + ); + + // TEMP HACK + +} + +ParticleShader.prototype = Object.create(Shader.prototype); +ParticleShader.prototype.constructor = ParticleShader; + +module.exports = ParticleShader; + +},{"../../core/Shader":77}],198:[function(require,module,exports){ +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + +if (!Math.sign) +{ + Math.sign = function (x) { + x = +x; + if (x === 0 || isNaN(x)) + { + return x; + } + return x > 0 ? 1 : -1; + }; +} + +},{}],199:[function(require,module,exports){ +// References: +// https://github.com/sindresorhus/object-assign +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + +if (!Object.assign) +{ + Object.assign = require('object-assign'); +} + +},{"object-assign":59}],200:[function(require,module,exports){ +require('./Object.assign'); +require('./requestAnimationFrame'); +require('./Math.sign'); + +if(!window.ArrayBuffer){ + window.ArrayBuffer = Array; +} +if(!window.Float32Array) { + window.Float32Array = Array; +} +if(!window.Uint32Array){ + window.Uint32Array = Array; +} +if(!window.Uint16Array){ + window.Uint16Array = Array; +} + +},{"./Math.sign":198,"./Object.assign":199,"./requestAnimationFrame":201}],201:[function(require,module,exports){ +(function (global){ +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + +// Expected to be used with Browserfiy +// Browserify automatically detects the use of `global` and passes the +// correct reference of `global`, `self`, and finally `window` + +// Date.now +if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; +} + +// performance.now +if (!(global.performance && global.performance.now)) { + var startTime = Date.now(); + if (!global.performance) { + global.performance = {}; + } + global.performance.now = function () { + return Date.now() - startTime; + }; +} + +// requestAnimationFrame +var lastTime = Date.now(); +var vendors = ['ms', 'moz', 'webkit', 'o']; + +for(var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { + global.requestAnimationFrame = global[vendors[x] + 'RequestAnimationFrame']; + global.cancelAnimationFrame = global[vendors[x] + 'CancelAnimationFrame'] || + global[vendors[x] + 'CancelRequestAnimationFrame']; +} + +if (!global.requestAnimationFrame) { + global.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + 'is not a function'); + } + + var currentTime = Date.now(), + delay = 16 + lastTime - currentTime; + + if (delay < 0) { + delay = 0; + } + + lastTime = currentTime; + + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} + +if (!global.cancelAnimationFrame) { + global.cancelAnimationFrame = function(id) { + clearTimeout(id); + }; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],202:[function(require,module,exports){ +var core = require('../../core'); + +/** + * Prepare uploads elements to the GPU. The CanvasRenderer version of prepare + * provides the same APIs as the WebGL version, but doesn't do anything. + * @class + * @memberof PIXI + * @param renderer {PIXI.CanvasRenderer} A reference to the current renderer + */ +function CanvasPrepare() +{ +} + +CanvasPrepare.prototype.constructor = CanvasPrepare; +module.exports = CanvasPrepare; + +/** + * Stub method for upload. + * @param {Function|PIXI.DisplayObject|PIXI.Container} item Either + * the container or display object to search for items to upload or + * the callback function, if items have been added using `prepare.add`. + * @param {Function} done When completed + */ +CanvasPrepare.prototype.upload = function(displayObject, done) +{ + if (typeof displayObject === 'function') + { + done = displayObject; + displayObject = null; + } + done(); +}; + +/** + * Stub method for registering hooks. + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ +CanvasPrepare.prototype.register = function() +{ + return this; +}; + +/** + * Stub method for adding items. + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ +CanvasPrepare.prototype.add = function() +{ + return this; +}; + +/** + * Stub method for destroying plugin. + */ +CanvasPrepare.prototype.destroy = function() +{ +}; + +core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); +},{"../../core":97}],203:[function(require,module,exports){ + +module.exports = { + webGL: require('./webgl/WebGLPrepare'), + canvas: require('./canvas/CanvasPrepare') +}; +},{"./canvas/CanvasPrepare":202,"./webgl/WebGLPrepare":204}],204:[function(require,module,exports){ +var core = require('../../core'), + SharedTicker = core.ticker.shared; + +/** + * The prepare manager provides functionality to upload content to the GPU + * @class + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} A reference to the current renderer + */ +function WebGLPrepare(renderer) +{ + /** + * Reference to the renderer. + * @type {PIXI.WebGLRenderer} + * @private + */ + this.renderer = renderer; + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + // Add textures and graphics to upload + this.register(findBaseTextures, uploadBaseTextures) + .register(findGraphics, uploadGraphics); +} + +/** + * The number of graphics or textures to upload to the GPU + * @property {number} UPLOADS_PER_FRAME + * @static + * @default 4 + */ +WebGLPrepare.UPLOADS_PER_FRAME = 4; + +WebGLPrepare.prototype.constructor = WebGLPrepare; +module.exports = WebGLPrepare; + +/** + * Upload all the textures and graphics to the GPU. + * @param {Function|PIXI.DisplayObject|PIXI.Container} item Either + * the container or display object to search for items to upload or + * the callback function, if items have been added using `prepare.add`. + * @param {Function} done When completed + */ +WebGLPrepare.prototype.upload = function(item, done) +{ + if (typeof item === 'function') + { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) + { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) + { + this.numLeft = WebGLPrepare.UPLOADS_PER_FRAME; + this.completes.push(done); + if (!this.ticking) + { + this.ticking = true; + SharedTicker.add(this.tick, this); + } + } + else + { + done(); + } +}; + +/** + * Handle tick update + * @private + */ +WebGLPrepare.prototype.tick = function() +{ + var i, len; + + // Upload the graphics + while(this.queue.length && this.numLeft > 0) + { + var item = this.queue[0]; + var uploaded = false; + for (i = 0, len = this.uploadHooks.length; i < len; i++) + { + if (this.uploadHooks[i](this.renderer, item)) + { + this.numLeft--; + this.queue.shift(); + uploaded = true; + break; + } + } + if (!uploaded) + { + this.queue.shift(); + } + } + + // We're finished + if (this.queue.length) + { + this.numLeft = WebGLPrepare.UPLOADS_PER_FRAME; + } + else + { + this.ticking = false; + SharedTicker.remove(this.tick, this); + var completes = this.completes.slice(0); + this.completes.length = 0; + for (i = 0, len = completes.length; i < len; i++) + { + completes[i](); + } + } +}; + +/** + * Adds hooks for finding and uploading items. + * @param {Function} [addHook] Function call that takes two parameters: `item:*, queue:Array` + function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] Function call that takes two parameters: `renderer:WebGLRenderer, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.WebGLPrepare} Instance of plugin for chaining. + */ +WebGLPrepare.prototype.register = function(addHook, uploadHook) +{ + if (addHook) + { + this.addHooks.push(addHook); + } + if (uploadHook) + { + this.uploadHooks.push(uploadHook); + } + return this; +}; + +/** + * Manually add an item to the uploading queue. + * @param {PIXI.DisplayObject|PIXI.Container|*} item Object to add to the queue + * @return {PIXI.WebGLPrepare} Instance of plugin for chaining. + */ +WebGLPrepare.prototype.add = function(item) +{ + var i, len; + + // Add additional hooks for finding elements on special + // types of objects that + for (i = 0, len = this.addHooks.length; i < len; i++) + { + if (this.addHooks[i](item, this.queue)) + { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) + { + for (i = item.children.length - 1; i >= 0; i--) + { + this.add(item.children[i]); + } + } + return this; +}; + +/** + * Destroys the plugin, don't use after this. + */ +WebGLPrepare.prototype.destroy = function() +{ + if (this.ticking) + { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; +}; + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU + * @private + * @param {*} item Item to check + * @return {boolean} If item was uploaded. + */ +function uploadBaseTextures(renderer, item) +{ + if (item instanceof core.BaseTexture) + { + renderer.textureManager.updateTexture(item); + return true; + } + return false; +} + +/** + * Built-in hook to upload PIXI.Graphics to the GPU + * @private + * @param {*} item Item to check + * @return {boolean} If item was uploaded. + */ +function uploadGraphics(renderer, item) +{ + if (item instanceof core.Graphics) + { + renderer.plugins.graphics.updateGraphics(item); + return true; + } + return false; +} + +/** + * Built-in hook to find textures from Sprites + * @private + * @param {PIXI.DisplayObject} item Display object to check + * @param {Array<*>} queue Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTextures(item, queue) +{ + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) + { + if (queue.indexOf(item) === -1) + { + queue.push(item); + } + return true; + } + else if (item._texture && item._texture instanceof core.Texture) + { + var texture = item._texture.baseTexture; + if (queue.indexOf(texture) === -1) + { + queue.push(texture); + } + return true; + } + return false; +} + +/** + * Built-in hook to find graphics + * @private + * @param {PIXI.DisplayObject} item Display object to check + * @param {Array<*>} queue Collection of items to upload + * @return {boolean} if a PIXI.Graphics object was found. + */ +function findGraphics(item, queue) +{ + if (item instanceof core.Graphics) + { + queue.push(item); + return true; + } + return false; +} + +core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); +},{"../../core":97}],205:[function(require,module,exports){ +(function (global){ +// run the polyfills +require('./polyfill'); + +var core = module.exports = require('./core'); + +// add core plugins. +core.extras = require('./extras'); +core.filters = require('./filters'); +core.interaction = require('./interaction'); +core.loaders = require('./loaders'); +core.mesh = require('./mesh'); +core.particles = require('./particles'); +core.accessibility = require('./accessibility'); +core.extract = require('./extract'); +core.prepare = require('./prepare'); + +// export a premade loader instance +/** + * A premade instance of the loader that can be used to loader resources. + * + * @name loader + * @memberof PIXI + * @property {PIXI.loaders.Loader} + */ +core.loader = new core.loaders.Loader(); + +// mixin the deprecation features. +Object.assign(core, require('./deprecation')); + +// Always export pixi globally. +global.PIXI = core; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"./accessibility":76,"./core":97,"./deprecation":154,"./extract":156,"./extras":164,"./filters":175,"./interaction":180,"./loaders":183,"./mesh":191,"./particles":194,"./polyfill":200,"./prepare":203}]},{},[205])(205) +}); + + +//# sourceMappingURL=pixi.js.map diff --git a/js/pixi/4.0.2/pixi.min.js b/js/pixi/4.0.2/pixi.min.js new file mode 100644 index 0000000..d792f90 --- /dev/null +++ b/js/pixi/4.0.2/pixi.min.js @@ -0,0 +1,18 @@ +/*! + * pixi.js - v4.0.2 + * Compiled Wed Sep 21 2016 13:19:41 GMT+0100 (BST) + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.PIXI=t()}}(function(){var t;return function t(e,r,i){function n(o,a){if(!r[o]){if(!e[o]){var h="function"==typeof require&&require;if(!a&&h)return h(o,!0);if(s)return s(o,!0);var u=new Error("Cannot find module '"+o+"'");throw u.code="MODULE_NOT_FOUND",u}var l=r[o]={exports:{}};e[o][0].call(l.exports,function(t){var r=e[o][1][t];return n(r?r:t)},l,l.exports,t,e,r,i)}return r[o].exports}for(var s="function"==typeof require&&require,o=0;o=t.byteLength?i.bufferSubData(this.type,e,t):i.bufferData(this.type,t,this.drawType),this.data=t},n.prototype.bind=function(){var t=this.gl;t.bindBuffer(this.type,this.buffer)},n.createVertexBuffer=function(t,e,r){return new n(t,t.ARRAY_BUFFER,e,r)},n.createIndexBuffer=function(t,e,r){return new n(t,t.ELEMENT_ARRAY_BUFFER,e,r)},n.create=function(t,e,r,i){return new n(t,e,r,i)},n.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer)},e.exports=n},{}],2:[function(t,e,r){var i=t("./GLTexture"),n=function(t,e,r){this.gl=t,this.framebuffer=t.createFramebuffer(),this.stencil=null,this.texture=null,this.width=e||100,this.height=r||100};n.prototype.enableTexture=function(t){var e=this.gl;this.texture=t||new i(e),this.texture.bind(),this.bind(),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0)},n.prototype.enableStencil=function(){if(!this.stencil){var t=this.gl;this.stencil=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.stencil),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.stencil),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,this.width,this.height)}},n.prototype.clear=function(t,e,r,i){this.bind();var n=this.gl;n.clearColor(t,e,r,i),n.clear(n.COLOR_BUFFER_BIT)},n.prototype.bind=function(){var t=this.gl;this.texture&&this.texture.unbind(),t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer)},n.prototype.unbind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)},n.prototype.resize=function(t,e){var r=this.gl;this.width=t,this.height=e,this.texture&&this.texture.uploadData(null,t,e),this.stencil&&(r.bindRenderbuffer(r.RENDERBUFFER,this.stencil),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e))},n.prototype.destroy=function(){var t=this.gl;this.texture&&this.texture.destroy(),t.deleteFramebuffer(this.framebuffer),this.gl=null,this.stencil=null,this.texture=null},n.createRGBA=function(t,e,r,s){var o=i.fromData(t,null,e,r);o.enableNearestScaling(),o.enableWrapClamp();var a=new n(t,e,r);return a.enableTexture(o),a.unbind(),a},n.createFloat32=function(t,e,r,s){var o=new i.fromData(t,s,e,r);o.enableNearestScaling(),o.enableWrapClamp();var a=new n(t,e,r);return a.enableTexture(o),a.unbind(),a},e.exports=n},{"./GLTexture":4}],3:[function(t,e,r){var i=t("./shader/compileProgram"),n=t("./shader/extractAttributes"),s=t("./shader/extractUniforms"),o=t("./shader/generateUniformAccessObject"),a=function(t,e,r,a){this.gl=t,this.program=i(t,e,r,a),this.attributes=n(t,this.program);for(var h in this.attributes)console.log(h+" : "+this.attributes[h].location);console.log(">>>>>>>");var u=s(t,this.program);this.uniforms=o(t,u)};a.prototype.bind=function(){this.gl.useProgram(this.program)},a.prototype.destroy=function(){},e.exports=a},{"./shader/compileProgram":9,"./shader/extractAttributes":11,"./shader/extractUniforms":12,"./shader/generateUniformAccessObject":13}],4:[function(t,e,r){var i=function(t,e,r,i,n){this.gl=t,this.texture=t.createTexture(),this.mipmap=!1,this.premultiplyAlpha=!1,this.width=e||-1,this.height=r||-1,this.format=i||t.RGBA,this.type=n||t.UNSIGNED_BYTE};i.prototype.upload=function(t){this.bind();var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var r=t.videoWidth||t.width,i=t.videoHeight||t.height;i!==this.height||r!==this.width?e.texImage2D(e.TEXTURE_2D,0,this.format,this.format,this.type,t):e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.format,this.type,t),this.width=r,this.height=i};var n=!1;i.prototype.uploadData=function(t,e,r){this.bind();var i=this.gl;if(t instanceof Float32Array){if(!n){var s=i.getExtension("OES_texture_float");if(!s)throw new Error("floating point textures not available");n=!0}this.type=i.FLOAT}else this.type=i.UNSIGNED_BYTE;i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),e!==this.width||r!==this.height?i.texImage2D(i.TEXTURE_2D,0,this.format,e,r,0,this.format,this.type,t||null):i.texSubImage2D(i.TEXTURE_2D,0,0,0,e,r,this.format,this.type,t||null),this.width=e,this.height=r},i.prototype.bind=function(t){var e=this.gl;void 0!==t&&e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,this.texture)},i.prototype.unbind=function(){var t=this.gl;t.bindTexture(t.TEXTURE_2D,null)},i.prototype.minFilter=function(t){var e=this.gl;this.bind(),this.mipmap?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR:e.NEAREST)},i.prototype.magFilter=function(t){var e=this.gl;this.bind(),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t?e.LINEAR:e.NEAREST)},i.prototype.enableMipmap=function(){var t=this.gl;this.bind(),this.mipmap=!0,t.generateMipmap(t.TEXTURE_2D)},i.prototype.enableLinearScaling=function(){this.minFilter(!0),this.magFilter(!0)},i.prototype.enableNearestScaling=function(){this.minFilter(!1),this.magFilter(!1)},i.prototype.enableWrapClamp=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)},i.prototype.enableWrapRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT)},i.prototype.enableWrapMirrorRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.MIRRORED_REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.MIRRORED_REPEAT)},i.prototype.destroy=function(){var t=this.gl;t.deleteTexture(this.texture)},i.fromSource=function(t,e,r){var n=new i(t);return n.premultiplyAlpha=r||!1,n.upload(e),n},i.fromData=function(t,e,r,n){var s=new i(t);return s.uploadData(e,r,n),s},e.exports=i},{}],5:[function(t,e,r){function i(t,e){if(this.nativeVaoExtension=null,i.FORCE_NATIVE||(this.nativeVaoExtension=t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object")),this.nativeState=e,this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var r=t.getParameter(t.MAX_VERTEX_ATTRIBS);this.nativeState={tempAttribState:new Array(r),attribState:new Array(r)}}this.gl=t,this.attributes=[],this.indexBuffer=null,this.dirty=!1}var n=t("./setVertexAttribArrays");i.prototype.constructor=i,e.exports=i,i.FORCE_NATIVE=!0,i.prototype.bind=function(){return this.nativeVao?(this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao),this.dirty&&(this.dirty=!1,this.activate())):this.activate(),this},i.prototype.unbind=function(){return this.nativeVao&&this.nativeVaoExtension.bindVertexArrayOES(null),this},i.prototype.activate=function(){for(var t=this.gl,e=null,r=0;r0)-(t<0)},r.abs=function(t){var e=t>>n-1;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,e|=r,e|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,t=(858993459&t)+(t>>>2&858993459),16843009*(t+(t>>>4)&252645135)>>>24},r.countTrailingZeros=i,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,t&=15,27030>>>t&1};var s=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,i=e,n=7;for(r>>>=1;r;r>>>=1)i<<=1,i|=1&r,--n;t[e]=i<>>8&255]<<16|s[t>>>16&255]<<8|s[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),t=65535&(t|t>>>16),t<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),t=1023&(t|t>>>16),t<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>i(t)+1}},{}],31:[function(t,e,r){"use strict";function i(t,e,r){r=r||2;var i=e&&e.length,s=i?e[0]*r:t.length,a=n(t,0,s,r,!0),h=[];if(!a)return h;var u,l,d,p,f,v,g;if(i&&(a=c(t,e,a,r)),t.length>80*r){u=d=t[0],l=p=t[1];for(var y=r;yd&&(d=f),v>p&&(p=v);g=Math.max(d-u,p-l)}return o(a,h,r,u,l,g),h}function n(t,e,r,i,n){var s,o;if(n===D(t,e,r,i)>0)for(s=e;s=e;s-=i)o=R(s,t[s],t[s+1],o);return o&&T(o,o.next)&&(A(o),o=o.next),o}function s(t,e){if(!t)return t;e||(e=t);var r,i=t;do if(r=!1,i.steiner||!T(i,i.next)&&0!==b(i.prev,i,i.next))i=i.next;else{if(A(i),i=e=i.prev,i===i.next)return null;r=!0}while(r||i!==e);return e}function o(t,e,r,i,n,c,d){if(t){!d&&c&&v(t,i,n,c);for(var p,f,g=t;t.prev!==t.next;)if(p=t.prev,f=t.next,c?h(t,i,n,c):a(t))e.push(p.i/r),e.push(t.i/r),e.push(f.i/r),A(t),t=f.next,g=f.next;else if(t=f,t===g){d?1===d?(t=u(t,e,r),o(t,e,r,i,n,c,2)):2===d&&l(t,e,r,i,n,c):o(s(t),e,r,i,n,c,1);break}}}function a(t){var e=t.prev,r=t,i=t.next;if(b(e,r,i)>=0)return!1;for(var n=t.next.next;n!==t.prev;){if(m(e.x,e.y,r.x,r.y,i.x,i.y,n.x,n.y)&&b(n.prev,n,n.next)>=0)return!1;n=n.next}return!0}function h(t,e,r,i){var n=t.prev,s=t,o=t.next;if(b(n,s,o)>=0)return!1;for(var a=n.xs.x?n.x>o.x?n.x:o.x:s.x>o.x?s.x:o.x,l=n.y>s.y?n.y>o.y?n.y:o.y:s.y>o.y?s.y:o.y,c=y(a,h,e,r,i),d=y(u,l,e,r,i),p=t.nextZ;p&&p.z<=d;){if(p!==t.prev&&p!==t.next&&m(n.x,n.y,s.x,s.y,o.x,o.y,p.x,p.y)&&b(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(p=t.prevZ;p&&p.z>=c;){if(p!==t.prev&&p!==t.next&&m(n.x,n.y,s.x,s.y,o.x,o.y,p.x,p.y)&&b(p.prev,p,p.next)>=0)return!1;p=p.prevZ}return!0}function u(t,e,r){var i=t;do{var n=i.prev,s=i.next.next;!T(n,s)&&E(n,i,i.next,s)&&S(n,s)&&S(s,n)&&(e.push(n.i/r),e.push(i.i/r),e.push(s.i/r),A(i),A(i.next),i=t=s),i=i.next}while(i!==t);return i}function l(t,e,r,i,n,a){var h=t;do{for(var u=h.next.next;u!==h.prev;){if(h.i!==u.i&&_(h,u)){var l=M(h,u);return h=s(h,h.next),l=s(l,l.next),o(h,e,r,i,n,a),void o(l,e,r,i,n,a)}u=u.next}h=h.next}while(h!==t)}function c(t,e,r,i){var o,a,h,u,l,c=[];for(o=0,a=e.length;o=i.next.y){var a=i.x+(s-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(a<=n&&a>o){if(o=a,a===n){if(s===i.y)return i;if(s===i.next.y)return i.next}r=i.x=i.x&&i.x>=l&&m(sr.x)&&S(i,t)&&(r=i,d=h)),i=i.next;return r}function v(t,e,r,i){var n=t;do null===n.z&&(n.z=y(n.x,n.y,e,r,i)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==t);n.prevZ.nextZ=null,n.prevZ=null,g(n)}function g(t){var e,r,i,n,s,o,a,h,u=1;do{for(r=t,t=null,s=null,o=0;r;){for(o++,i=r,a=0,e=0;e0||h>0&&i;)0===a?(n=i,i=i.nextZ,h--):0!==h&&i?r.z<=i.z?(n=r,r=r.nextZ,a--):(n=i,i=i.nextZ,h--):(n=r,r=r.nextZ,a--),s?s.nextZ=n:t=n,n.prevZ=s,s=n;r=i}s.nextZ=null,u*=2}while(o>1);return t}function y(t,e,r,i,n){return t=32767*(t-r)/n,e=32767*(e-i)/n,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1}function x(t){var e=t,r=t;do e.x=0&&(t-o)*(i-a)-(r-o)*(e-a)>=0&&(r-o)*(s-a)-(n-o)*(i-a)>=0}function _(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!w(t,e)&&S(t,e)&&S(e,t)&&C(t,e)}function b(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function T(t,e){return t.x===e.x&&t.y===e.y}function E(t,e,r,i){return!!(T(t,e)&&T(r,i)||T(t,i)&&T(r,e))||b(t,e,r)>0!=b(t,e,i)>0&&b(r,i,t)>0!=b(r,i,e)>0}function w(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&E(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}function S(t,e){return b(t.prev,t,t.next)<0?b(t,e,t.next)>=0&&b(t,t.prev,e)>=0:b(t,e,t.prev)<0||b(t,t.next,e)<0}function C(t,e){var r=t,i=!1,n=(t.x+e.x)/2,s=(t.y+e.y)/2;do r.y>s!=r.next.y>s&&n<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(i=!i),r=r.next;while(r!==t);return i}function M(t,e){var r=new O(t.i,t.x,t.y),i=new O(e.i,e.x,e.y),n=t.next,s=e.prev;return t.next=e,e.prev=t,r.next=n,n.prev=r,i.next=r,r.prev=i,s.next=i,i.prev=s,i}function R(t,e,r,i){var n=new O(t,e,r);return i?(n.next=i.next,n.prev=i,i.next.prev=n,i.next=n):(n.prev=n,n.next=n),n}function A(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function O(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function D(t,e,r,i){for(var n=0,s=e,o=r-i;s0&&(i+=t[n-1].length,r.holes.push(i))}return r}},{}],32:[function(t,e,r){"use strict";function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function n(){}var s=Object.prototype.hasOwnProperty,o="function"!=typeof Object.create&&"~";n.prototype._events=void 0,n.prototype.eventNames=function(){var t,e=this._events,r=[];if(!e)return r;for(t in e)s.call(e,t)&&r.push(o?t.slice(1):t);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},n.prototype.listeners=function(t,e){var r=o?o+t:t,i=this._events&&this._events[r];if(e)return!!i;if(!i)return[];if(i.fn)return[i.fn];for(var n=0,s=i.length,a=new Array(s);n-1&&t%1==0&&t-1&&t%1==0&&t<=n}var n=9007199254740991;e.exports=i},{}],50:[function(t,e,r){function i(t){var e=typeof t;return!!t&&("object"==e||"function"==e)}e.exports=i},{}],51:[function(t,e,r){function i(t){return!!t&&"object"==typeof t}e.exports=i},{}],52:[function(t,e,r){function i(t){return"symbol"==typeof t||n(t)&&a.call(t)==s}var n=t("./isObjectLike"),s="[object Symbol]",o=Object.prototype,a=o.toString;e.exports=i},{"./isObjectLike":51}],53:[function(t,e,r){function i(t){return o(t)?n(t):s(t)}var n=t("./_arrayLikeKeys"),s=t("./_baseKeys"),o=t("./isArrayLike");e.exports=i},{"./_arrayLikeKeys":36,"./_baseKeys":37,"./isArrayLike":46}],54:[function(t,e,r){function i(){}e.exports=i},{}],55:[function(t,e,r){function i(t,e){if("function"!=typeof t)throw new TypeError(o);return e=void 0===e?e:s(e),n(t,e)}var n=t("./_baseRest"),s=t("./toInteger"),o="Expected a function";e.exports=i},{"./_baseRest":38,"./toInteger":57}],56:[function(t,e,r){function i(t){if(!t)return 0===t?t:0;if(t=n(t),t===s||t===-s){var e=t<0?-1:1;return e*o}return t===t?t:0}var n=t("./toNumber"),s=1/0,o=1.7976931348623157e308;e.exports=i},{"./toNumber":58}],57:[function(t,e,r){function i(t){var e=n(t),r=e%1;return e===e?r?e-r:e:0}var n=t("./toFinite");e.exports=i},{"./toFinite":56}],58:[function(t,e,r){function i(t){if("number"==typeof t)return t;if(s(t))return o;if(n(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=n(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(a,"");var r=u.test(t);return r||l.test(t)?c(t.slice(2),r?2:8):h.test(t)?o:+t}var n=t("./isObject"),s=t("./isSymbol"),o=NaN,a=/^\s+|\s+$/g,h=/^[-+]0x[0-9a-f]+$/i,u=/^0b[01]+$/i,l=/^0o[0-7]+$/i,c=parseInt;e.exports=i},{"./isObject":50,"./isSymbol":52}],59:[function(t,e,r){"use strict";function i(t){if(null===t||void 0===t)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}function n(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de","5"===Object.getOwnPropertyNames(t)[0])return!1;for(var e={},r=0;r<10;r++)e["_"+String.fromCharCode(r)]=r;var i=Object.getOwnPropertyNames(e).map(function(t){return e[t]});if("0123456789"!==i.join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach(function(t){n[t]=t}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(t){return!1}}var s=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;e.exports=n()?Object.assign:function(t,e){for(var r,n,a=i(t),h=1;h=0;i--){var n=t[i];"."===n?t.splice(i,1):".."===n?(t.splice(i,1),r++):r&&(t.splice(i,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}function i(t,e){if(t.filter)return t.filter(e);for(var r=[],i=0;i=-1&&!n;s--){var o=s>=0?arguments[s]:t.cwd();if("string"!=typeof o)throw new TypeError("Arguments to path.resolve must be strings");o&&(r=o+"/"+r,n="/"===o.charAt(0))}return r=e(i(r.split("/"),function(t){return!!t}),!n).join("/"),(n?"/":"")+r||"."},r.normalize=function(t){var n=r.isAbsolute(t),s="/"===o(t,-1);return t=e(i(t.split("/"),function(t){return!!t}),!n).join("/"),t||n||(t="."),t&&s&&(t+="/"),(n?"/":"")+t},r.isAbsolute=function(t){return"/"===t.charAt(0)},r.join=function(){var t=Array.prototype.slice.call(arguments,0);return r.normalize(i(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},r.relative=function(t,e){function i(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=r.resolve(t).substr(1),e=r.resolve(e).substr(1);for(var n=i(t.split("/")),s=i(e.split("/")),o=Math.min(n.length,s.length),a=o,h=0;h1)for(var r=1;r1&&(i=r[0]+"@",t=r[1]),t=t.replace(I,".");var n=t.split("."),s=o(n,e).join(".");return i+s}function h(t){for(var e,r,i=[],n=0,s=t.length;n=55296&&e<=56319&&n65535&&(t-=65536,e+=N(t>>>10&1023|55296),t=56320|1023&t),e+=N(t)}).join("")}function l(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:E}function c(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function d(t,e,r){var i=0;for(t=r?B(t/M):t>>1,t+=B(t/e);t>F*S>>1;i+=E)t=B(t/F);return B(i+(F+1)*t/(t+C))}function p(t){var e,r,i,n,o,a,h,c,p,f,v=[],g=t.length,y=0,x=A,m=R;for(r=t.lastIndexOf(O),r<0&&(r=0),i=0;i=128&&s("not-basic"),v.push(t.charCodeAt(i));for(n=r>0?r+1:0;n=g&&s("invalid-input"),c=l(t.charCodeAt(n++)),(c>=E||c>B((T-y)/a))&&s("overflow"),y+=c*a,p=h<=m?w:h>=m+S?S:h-m,!(cB(T/f)&&s("overflow"),a*=f;e=v.length+1,m=d(y-o,e,0==o),B(y/e)>T-x&&s("overflow"),x+=B(y/e),y%=e,v.splice(y++,0,x)}return u(v)}function f(t){var e,r,i,n,o,a,u,l,p,f,v,g,y,x,m,_=[];for(t=h(t),g=t.length,e=A,r=0,o=R,a=0;a=e&&vB((T-r)/y)&&s("overflow"),r+=(u-e)*y,e=u,a=0;aT&&s("overflow"),v==e){for(l=r,p=E;f=p<=o?w:p>=o+S?S:p-o,!(l= 0x80 (not a basic code point)","invalid-input":"Invalid input"},F=E-w,B=Math.floor,N=String.fromCharCode;if(_={version:"1.4.1",ucs2:{decode:h,encode:u},decode:p,encode:f,toASCII:g,toUnicode:v},"function"==typeof t&&"object"==typeof t.amd&&t.amd)t("punycode",function(){return _});else if(y&&x)if(r.exports==y)x.exports=_;else for(b in _)_.hasOwnProperty(b)&&(y[b]=_[b]);else n.punycode=_}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],63:[function(t,e,r){"use strict";function i(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,r,s){e=e||"&",r=r||"=";var o={};if("string"!=typeof t||0===t.length)return o;var a=/\+/g;t=t.split(e);var h=1e3;s&&"number"==typeof s.maxKeys&&(h=s.maxKeys);var u=t.length;h>0&&u>h&&(u=h);for(var l=0;l=0?(c=v.substr(0,g),d=v.substr(g+1)):(c=v,d=""),p=decodeURIComponent(c),f=decodeURIComponent(d),i(o,p)?n(o[p])?o[p].push(f):o[p]=[o[p],f]:o[p]=f}return o};var n=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],64:[function(t,e,r){"use strict";function i(t,e){if(t.map)return t.map(e);for(var r=[],i=0;i0))return void this.abort("["+t.status+"]"+t.statusText+":"+t.responseURL);if(this.xhrType===i.XHR_RESPONSE_TYPE.TEXT)this.data=t.responseText;else if(this.xhrType===i.XHR_RESPONSE_TYPE.JSON)try{this.data=JSON.parse(t.responseText),this.isJson=!0}catch(t){return void this.abort("Error trying to parse loaded json:",t)}else if(this.xhrType===i.XHR_RESPONSE_TYPE.DOCUMENT)try{if(window.DOMParser){var r=new DOMParser;this.data=r.parseFromString(t.responseText,"text/xml")}else{var n=document.createElement("div");n.innerHTML=t.responseText,this.data=n}this.isXml=!0}catch(t){return void this.abort("Error trying to parse loaded xml:",t)}else this.data=t.response||t.responseText;this.complete()},i.prototype._determineCrossOrigin=function(t,e){if(0===t.indexOf("data:"))return"";e=e||window.location,u||(u=document.createElement("a")),u.href=t,t=a.parse(u.href);var r=!t.port&&""===e.port||t.port===e.port;return t.hostname===e.hostname&&r&&t.protocol===e.protocol?"":"anonymous"},i.prototype._determineXhrType=function(){return i._xhrTypeMap[this._getExtension()]||i.XHR_RESPONSE_TYPE.TEXT},i.prototype._determineLoadType=function(){return i._loadTypeMap[this._getExtension()]||i.LOAD_TYPE.XHR},i.prototype._getExtension=function(){var t=this.url,e="";if(this.isDataUrl){var r=t.indexOf("/");e=t.substring(r+1,t.indexOf(";",r))}else{var i=t.indexOf("?");i!==-1&&(t=t.substring(0,i)),e=t.substring(t.lastIndexOf(".")+1)}return e.toLowerCase()},i.prototype._getMimeFromXhrType=function(t){switch(t){case i.XHR_RESPONSE_TYPE.BUFFER:return"application/octet-binary";case i.XHR_RESPONSE_TYPE.BLOB:return"application/blob";case i.XHR_RESPONSE_TYPE.DOCUMENT:return"application/xml";case i.XHR_RESPONSE_TYPE.JSON:return"application/json";case i.XHR_RESPONSE_TYPE.DEFAULT:case i.XHR_RESPONSE_TYPE.TEXT:default:return"text/plain"}},i.LOAD_TYPE={XHR:1,IMAGE:2,AUDIO:3,VIDEO:4},i.XHR_RESPONSE_TYPE={DEFAULT:"text",BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"},i._loadTypeMap={gif:i.LOAD_TYPE.IMAGE,png:i.LOAD_TYPE.IMAGE,bmp:i.LOAD_TYPE.IMAGE,jpg:i.LOAD_TYPE.IMAGE,jpeg:i.LOAD_TYPE.IMAGE,tif:i.LOAD_TYPE.IMAGE,tiff:i.LOAD_TYPE.IMAGE,webp:i.LOAD_TYPE.IMAGE,tga:i.LOAD_TYPE.IMAGE,"svg+xml":i.LOAD_TYPE.IMAGE},i._xhrTypeMap={xhtml:i.XHR_RESPONSE_TYPE.DOCUMENT,html:i.XHR_RESPONSE_TYPE.DOCUMENT,htm:i.XHR_RESPONSE_TYPE.DOCUMENT,xml:i.XHR_RESPONSE_TYPE.DOCUMENT,tmx:i.XHR_RESPONSE_TYPE.DOCUMENT,tsx:i.XHR_RESPONSE_TYPE.DOCUMENT,svg:i.XHR_RESPONSE_TYPE.DOCUMENT,gif:i.XHR_RESPONSE_TYPE.BLOB,png:i.XHR_RESPONSE_TYPE.BLOB,bmp:i.XHR_RESPONSE_TYPE.BLOB,jpg:i.XHR_RESPONSE_TYPE.BLOB,jpeg:i.XHR_RESPONSE_TYPE.BLOB,tif:i.XHR_RESPONSE_TYPE.BLOB,tiff:i.XHR_RESPONSE_TYPE.BLOB,webp:i.XHR_RESPONSE_TYPE.BLOB,tga:i.XHR_RESPONSE_TYPE.BLOB,json:i.XHR_RESPONSE_TYPE.JSON,text:i.XHR_RESPONSE_TYPE.TEXT,txt:i.XHR_RESPONSE_TYPE.TEXT},i.setExtensionLoadType=function(t,e){s(i._loadTypeMap,t,e)},i.setExtensionXhrType=function(t,e){s(i._xhrTypeMap,t,e)}},{eventemitter3:32,url:72}],68:[function(t,e,r){"use strict";e.exports={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encodeBinary:function(t){for(var e,r="",i=new Array(4),n=0,s=0,o=0;n>2,i[1]=(3&e[0])<<4|e[1]>>4,i[2]=(15&e[1])<<2|e[2]>>6,i[3]=63&e[2],o=n-(t.length-1)){case 2:i[3]=64,i[2]=64;break;case 1:i[3]=64}for(s=0;s",'"',"`"," ","\r","\n","\t"],f=["{","}","|","\\","^","`"].concat(p),v=["'"].concat(f),g=["%","/","?",";","#"].concat(v),y=["/","?","#"],x=255,m=/^[+a-z0-9A-Z_-]{0,63}$/,_=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,b={javascript:!0,"javascript:":!0},T={javascript:!0,"javascript:":!0},E={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},w=t("querystring");i.prototype.parse=function(t,e,r){if(!u.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var i=t.indexOf("?"),n=i!==-1&&i127?"x":L[B];if(!F.match(m)){var k=P.slice(0,M),U=P.slice(M+1),j=L.match(_);j&&(k.push(j[1]),U.unshift(j[2])),U.length&&(a="/"+U.join(".")+a),this.hostname=k.join(".");break}}}this.hostname.length>x?this.hostname="":this.hostname=this.hostname.toLowerCase(),D||(this.hostname=h.toASCII(this.hostname));var W=this.port?":"+this.port:"",G=this.hostname||"";this.host=G+W,this.href+=this.host,D&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==a[0]&&(a="/"+a))}if(!b[f])for(var M=0,I=v.length;M0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return r.search=t.search,r.query=t.query,u.isNull(r.pathname)&&u.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!b.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var C=b.slice(-1)[0],M=(r.host||t.host||b.length>1)&&("."===C||".."===C)||""===C,R=0,A=b.length;A>=0;A--)C=b[A],"."===C?b.splice(A,1):".."===C?(b.splice(A,1),R++):R&&(b.splice(A,1),R--);if(!m&&!_)for(;R--;R)b.unshift("..");!m||""===b[0]||b[0]&&"/"===b[0].charAt(0)||b.unshift(""),M&&"/"!==b.join("/").substr(-1)&&b.push("");var O=""===b[0]||b[0]&&"/"===b[0].charAt(0);if(w){r.hostname=r.host=O?"":b.length?b.shift():"";var S=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return m=m||r.host&&b.length,m&&!O&&b.unshift(""),b.length?r.pathname=b.join("/"):(r.pathname=null,r.path=null),u.isNull(r.pathname)&&u.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},i.prototype.parseHost=function(){var t=this.host,e=c.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":73,punycode:62,querystring:65}],73:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],74:[function(t,e,r){function i(t){!s.tablet&&!s.phone||navigator.isCocoonJS||this.createTouchHook();var e=document.createElement("div");e.style.width="100px",e.style.height="100px",e.style.position="absolute",e.style.top=0,e.style.left=0,e.style.zIndex=2,this.div=e,this.pool=[],this.renderId=0,this.debug=!1,this.renderer=t,this.children=[],this._onKeyDown=this._onKeyDown.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this.isActive=!1,this.isMobileAccessabillity=!1,window.addEventListener("keydown",this._onKeyDown,!1)}var n=t("../core"),s=t("ismobilejs");Object.assign(n.DisplayObject.prototype,t("./accessibleTarget")),i.prototype.constructor=i,e.exports=i,i.prototype.createTouchHook=function(){var t=document.createElement("button");t.style.width="1px",t.style.height="1px",t.style.position="absolute",t.style.top="-1000px",t.style.left="-1000px",t.style.zIndex=2,t.style.backgroundColor="#FF0000",t.title="HOOK DIV",t.addEventListener("focus",function(){this.isMobileAccessabillity=!0,this.activate(),document.body.removeChild(t)}.bind(this)),document.body.appendChild(t)},i.prototype.activate=function(){this.isActive||(this.isActive=!0,window.document.addEventListener("mousemove",this._onMouseMove,!0),window.removeEventListener("keydown",this._onKeyDown,!1),this.renderer.on("postrender",this.update,this),this.renderer.view.parentNode&&this.renderer.view.parentNode.appendChild(this.div))},i.prototype.deactivate=function(){this.isActive&&!this.isMobileAccessabillity&&(this.isActive=!1,window.document.removeEventListener("mousemove",this._onMouseMove),window.addEventListener("keydown",this._onKeyDown,!1),this.renderer.off("postrender",this.update),this.div.parentNode&&this.div.parentNode.removeChild(this.div))},i.prototype.updateAccessibleObjects=function(t){if(t.visible){t.accessible&&t.interactive&&(t._accessibleActive||this.addChild(t),t.renderId=this.renderId);for(var e=t.children,r=e.length-1;r>=0;r--)this.updateAccessibleObjects(e[r])}},i.prototype.update=function(){if(this.renderer.renderingToScreen){this.updateAccessibleObjects(this.renderer._lastObjectRendered);var t=this.renderer.view.getBoundingClientRect(),e=t.width/this.renderer.width,r=t.height/this.renderer.height,i=this.div;i.style.left=t.left+"px",i.style.top=t.top+"px",i.style.width=this.renderer.width+"px",i.style.height=this.renderer.height+"px";for(var s=0;sthis.renderer.width&&(t.width=this.renderer.width-t.x),t.y+t.height>this.renderer.height&&(t.height=this.renderer.height-t.y)},i.prototype.addChild=function(t){var e=this.pool.pop();e||(e=document.createElement("button"),e.style.width="100px",e.style.height="100px",e.style.backgroundColor=this.debug?"rgba(255,0,0,0.5)":"transparent",e.style.position="absolute",e.style.zIndex=2,e.style.borderStyle="none",e.addEventListener("click",this._onClick.bind(this)),e.addEventListener("focus",this._onFocus.bind(this)),e.addEventListener("focusout",this._onFocusOut.bind(this))),t.accessibleTitle?e.title=t.accessibleTitle:t.accessibleTitle||t.accessibleHint||(e.title="displayObject "+this.tabIndex),t.accessibleHint&&e.setAttribute("aria-label",t.accessibleHint),t._accessibleActive=!0,t._accessibleDiv=e,e.displayObject=t,this.children.push(t),this.div.appendChild(t._accessibleDiv),t._accessibleDiv.tabIndex=t.tabIndex},i.prototype._onClick=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"click",e.eventData)},i.prototype._onFocus=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseover",e.eventData)},i.prototype._onFocusOut=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseout",e.eventData)},i.prototype._onKeyDown=function(t){9===t.keyCode&&this.activate()},i.prototype._onMouseMove=function(){this.deactivate()},i.prototype.destroy=function(){this.div=null;for(var t=0;tthis.maxX||this.minY>this.maxY},i.prototype.clear=function(){this.updateID++,this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0)},i.prototype.getRectangle=function(t){return this.minX>this.maxX||this.minY>this.maxY?s.EMPTY:(t=t||new s(0,0,1,1),t.x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)},i.prototype.addPoint=function(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)},i.prototype.addQuad=function(t){var e=this.minX,r=this.minY,i=this.maxX,n=this.maxY,s=t[0],o=t[1];e=si?s:i,n=o>n?o:n,s=t[2],o=t[3],e=si?s:i,n=o>n?o:n,s=t[4],o=t[5],e=si?s:i,n=o>n?o:n,s=t[6],o=t[7],e=si?s:i,n=o>n?o:n,this.minX=e,this.minY=r,this.maxX=i,this.maxY=n},i.prototype.addFrame=function(t,e,r,i,n){var s=t.worldTransform,o=s.a,a=s.b,h=s.c,u=s.d,l=s.tx,c=s.ty,d=this.minX,p=this.minY,f=this.maxX,v=this.maxY,g=o*e+h*r+l,y=a*e+u*r+c;d=gf?g:f,v=y>v?y:v,g=o*i+h*r+l,y=a*i+u*r+c,d=gf?g:f,v=y>v?y:v,g=o*e+h*n+l,y=a*e+u*n+c,d=gf?g:f,v=y>v?y:v,g=o*i+h*n+l,y=a*i+u*n+c,d=gf?g:f,v=y>v?y:v,this.minX=d,this.minY=p,this.maxX=f,this.maxY=v},i.prototype.addVertices=function(t,e,r,i){for(var n=t.worldTransform,s=n.a,o=n.b,a=n.c,h=n.d,u=n.tx,l=n.ty,c=this.minX,d=this.minY,p=this.maxX,f=this.maxY,v=r;vp?x:p,f=m>f?m:f}this.minX=c,this.minY=d,this.maxX=p,this.maxY=f},i.prototype.addBounds=function(t){var e=this.minX,r=this.minY,i=this.maxX,n=this.maxY;this.minX=t.minXi?t.maxX:i,this.maxY=t.maxY>n?t.maxY:n}},{"../math":102}],80:[function(t,e,r){function i(){s.call(this),this.children=[]}var n=t("../utils"),s=t("./DisplayObject");i.prototype=Object.create(s.prototype),i.prototype.constructor=i,e.exports=i,Object.defineProperties(i.prototype,{width:{get:function(){return this.scale.x*this.getLocalBounds().width},set:function(t){var e=this.getLocalBounds().width;0!==e?this.scale.x=t/e:this.scale.x=1,this._width=t}},height:{get:function(){return this.scale.y*this.getLocalBounds().height},set:function(t){var e=this.getLocalBounds().height;0!==e?this.scale.y=t/e:this.scale.y=1,this._height=t}}}),i.prototype.onChildrenChange=function(){},i.prototype.addChild=function(t){var e=arguments.length;if(e>1)for(var r=0;r=0&&e<=this.children.length)return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),this.onChildrenChange(e),t.emit("added",this),t;throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length)},i.prototype.swapChildren=function(t,e){if(t!==e){var r=this.getChildIndex(t),i=this.getChildIndex(e);if(r<0||i<0)throw new Error("swapChildren: Both the supplied DisplayObjects must be children of the caller.");this.children[r]=e,this.children[i]=t,this.onChildrenChange(r=this.children.length)throw new Error("The supplied index is out of bounds");var r=this.getChildIndex(t);n.removeItems(this.children,r,1),this.children.splice(e,0,t),this.onChildrenChange(e)},i.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Supplied index "+t+" does not exist in the child list, or the supplied DisplayObject is not a child of the caller");return this.children[t]},i.prototype.removeChild=function(t){var e=arguments.length;if(e>1)for(var r=0;r0&&o<=s){for(r=this.children.splice(n,o),i=0;i=0;i--){var n=r[i];n.parent=null,n.destroy(t)}}},{"../utils":151,"./DisplayObject":81}],81:[function(t,e,r){function i(){n.call(this);var t=s.TRANSFORM_MODE.DEFAULT===s.TRANSFORM_MODE.STATIC?o:a;this.transform=new t,this.alpha=1,this.visible=!0,this.renderable=!0,this.parent=null,this.worldAlpha=1,this.filterArea=null,this._filters=null,this._enabledFilters=null,this._bounds=new h,this._boundsID=0,this._lastBoundsID=-1,this._boundsRect=null,this._localBoundsRect=null,this._mask=null}var n=t("eventemitter3"),s=t("../const"),o=t("./TransformStatic"),a=t("./Transform"),h=t("./Bounds"),u=t("../math"),l=new i;i.prototype=Object.create(n.prototype),i.prototype.constructor=i,e.exports=i,Object.defineProperties(i.prototype,{x:{get:function(){return this.position.x},set:function(t){this.transform.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.transform.position.y=t}},worldTransform:{get:function(){return this.transform.worldTransform}},localTransform:{get:function(){return this.transform.localTransform}},position:{get:function(){return this.transform.position},set:function(t){this.transform.position.copy(t)}},scale:{get:function(){return this.transform.scale},set:function(t){this.transform.scale.copy(t)}},pivot:{get:function(){return this.transform.pivot},set:function(t){this.transform.pivot.copy(t)}},skew:{get:function(){return this.transform.skew},set:function(t){this.transform.skew.copy(t)}},rotation:{get:function(){return this.transform.rotation},set:function(t){this.transform.rotation=t}},worldVisible:{get:function(){var t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}},mask:{get:function(){return this._mask},set:function(t){this._mask&&(this._mask.renderable=!0),this._mask=t,this._mask&&(this._mask.renderable=!1)}},filters:{get:function(){return this._filters&&this._filters.slice()},set:function(t){this._filters=t&&t.slice()}}}),i.prototype.updateTransform=function(){this.transform.updateTransform(this.parent.transform),this.worldAlpha=this.alpha*this.parent.worldAlpha,this._bounds.updateID++},i.prototype.displayObjectUpdateTransform=i.prototype.updateTransform,i.prototype._recursivePostUpdateTransform=function(){this.parent?(this.parent._recursivePostUpdateTransform(),this.transform.updateTransform(this.parent.transform)):this.transform.updateTransform(l.transform)},i.prototype.getBounds=function(t,e){return t||(this.parent?(this._recursivePostUpdateTransform(),this.updateTransform()):(this.parent=l,this.parent.transform._worldID++,this.updateTransform(),this.parent=null)),this._boundsID!==this._lastBoundsID&&this.calculateBounds(),e||(this._boundsRect||(this._boundsRect=new u.Rectangle),e=this._boundsRect),this._bounds.getRectangle(e)},i.prototype.getLocalBounds=function(t){var e=this.transform,r=this.parent;this.parent=null,this.transform=l.transform,t||(this._localBoundsRect||(this._localBoundsRect=new u.Rectangle),t=this._localBoundsRect);var i=this.getBounds(!1,t);return this.parent=r,this.transform=e,i},i.prototype.toGlobal=function(t,e,r){return r||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=l,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)},i.prototype.toLocal=function(t,e,r,i){return e&&(t=e.toGlobal(t,r,i)),i||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=l,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,r)},i.prototype.renderWebGL=function(t){},i.prototype.renderCanvas=function(t){},i.prototype.setParent=function(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t},i.prototype.setTransform=function(t,e,r,i,n,s,o,a,h){return this.position.x=t||0,this.position.y=e||0,this.scale.x=r?r:1,this.scale.y=i?i:1,this.rotation=n||0,this.skew.x=s||0,this.skew.y=o||0,this.pivot.x=a||0,this.pivot.y=h||0,this},i.prototype.destroy=function(){this.removeAllListeners(),this.parent&&this.parent.removeChild(this),this.transform=null,this.parent=null,this._bounds=null,this._currentBounds=null,this._mask=null,this.filterArea=null,this.interactive=!1,this.interactiveChildren=!1}},{"../const":78,"../math":102,"./Bounds":79,"./Transform":82,"./TransformStatic":84,eventemitter3:32}],82:[function(t,e,r){function i(){s.call(this),this.position=new n.Point(0,0),this.scale=new n.Point(1,1),this.skew=new n.ObservablePoint(this.updateSkew,this,0,0),this.pivot=new n.Point(0,0),this._rotation=0,this._sr=Math.sin(0),this._cr=Math.cos(0),this._cy=Math.cos(0),this._sy=Math.sin(0),this._nsx=Math.sin(0),this._cx=Math.cos(0)}var n=t("../math"),s=t("./TransformBase");i.prototype=Object.create(s.prototype),i.prototype.constructor=i,i.prototype.updateSkew=function(){this._cy=Math.cos(this.skew.y),this._sy=Math.sin(this.skew.y),this._nsx=Math.sin(this.skew.x),this._cx=Math.cos(this.skew.x)},i.prototype.updateLocalTransform=function(){var t,e,r,i,n=this.localTransform;t=this._cr*this.scale.x,e=this._sr*this.scale.x,r=-this._sr*this.scale.y,i=this._cr*this.scale.y,n.a=this._cy*t+this._sy*r,n.b=this._cy*e+this._sy*i,n.c=this._nsx*t+this._cx*r,n.d=this._nsx*e+this._cx*i},i.prototype.updateTransform=function(t){var e,r,i,n,s=t.worldTransform,o=this.worldTransform,a=this.localTransform;e=this._cr*this.scale.x,r=this._sr*this.scale.x,i=-this._sr*this.scale.y,n=this._cr*this.scale.y,a.a=this._cy*e+this._sy*i,a.b=this._cy*r+this._sy*n,a.c=this._nsx*e+this._cx*i,a.d=this._nsx*r+this._cx*n,a.tx=this.position.x-(this.pivot.x*a.a+this.pivot.y*a.c),a.ty=this.position.y-(this.pivot.x*a.b+this.pivot.y*a.d),o.a=a.a*s.a+a.b*s.c,o.b=a.a*s.b+a.b*s.d,o.c=a.c*s.a+a.d*s.c,o.d=a.c*s.b+a.d*s.d,o.tx=a.tx*s.a+a.ty*s.c+s.tx,o.ty=a.tx*s.b+a.ty*s.d+s.ty,this._worldID++},i.prototype.setFromMatrix=function(t){t.decompose(this)},Object.defineProperties(i.prototype,{rotation:{get:function(){return this._rotation},set:function(t){this._rotation=t,this._sr=Math.sin(t),this._cr=Math.cos(t)}}}),e.exports=i},{"../math":102,"./TransformBase":83}],83:[function(t,e,r){function i(){this.worldTransform=new n.Matrix,this.localTransform=new n.Matrix,this._worldID=0}var n=t("../math");i.prototype.constructor=i,i.prototype.updateLocalTransform=function(){},i.prototype.updateTransform=function(t){var e=t.worldTransform,r=this.worldTransform,i=this.localTransform;r.a=i.a*e.a+i.b*e.c,r.b=i.a*e.b+i.b*e.d,r.c=i.c*e.a+i.d*e.c,r.d=i.c*e.b+i.d*e.d,r.tx=i.tx*e.a+i.ty*e.c+e.tx,r.ty=i.tx*e.b+i.ty*e.d+e.ty,this._worldID++},i.prototype.updateWorldTransform=i.prototype.updateTransform,i.IDENTITY=new i,e.exports=i},{"../math":102}],84:[function(t,e,r){function i(){s.call(this),this.position=new n.ObservablePoint(this.onChange,this,0,0),this.scale=new n.ObservablePoint(this.onChange,this,1,1),this.pivot=new n.ObservablePoint(this.onChange,this,0,0),this.skew=new n.ObservablePoint(this.updateSkew,this,0,0),this._rotation=0,this._sr=Math.sin(0),this._cr=Math.cos(0),this._cy=Math.cos(0),this._sy=Math.sin(0),this._nsx=Math.sin(0),this._cx=Math.cos(0),this._localID=0,this._currentLocalID=0}var n=t("../math"),s=t("./TransformBase");i.prototype=Object.create(s.prototype),i.prototype.constructor=i,i.prototype.onChange=function(){this._localID++},i.prototype.updateSkew=function(){this._cy=Math.cos(this.skew._y),this._sy=Math.sin(this.skew._y),this._nsx=Math.sin(this.skew._x),this._cx=Math.cos(this.skew._x),this._localID++},i.prototype.updateLocalTransform=function(){var t=this.localTransform;if(this._localID!==this._currentLocalID){var e,r,i,n;e=this._cr*this.scale._x,r=this._sr*this.scale._x,i=-this._sr*this.scale._y,n=this._cr*this.scale._y,t.a=this._cy*e+this._sy*i,t.b=this._cy*r+this._sy*n,t.c=this._nsx*e+this._cx*i,t.d=this._nsx*r+this._cx*n,t.tx=this.position._x-(this.pivot._x*t.a+this.pivot._y*t.c),t.ty=this.position._y-(this.pivot._x*t.b+this.pivot._y*t.d),this._currentLocalID=this._localID,this._parentID=-1}},i.prototype.updateTransform=function(t){var e=t.worldTransform,r=this.worldTransform,i=this.localTransform;if(this._localID!==this._currentLocalID){var n,s,o,a;n=this._cr*this.scale._x,s=this._sr*this.scale._x,o=-this._sr*this.scale._y,a=this._cr*this.scale._y,i.a=this._cy*n+this._sy*o,i.b=this._cy*s+this._sy*a,i.c=this._nsx*n+this._cx*o,i.d=this._nsx*s+this._cx*a,i.tx=this.position._x-(this.pivot._x*i.a+this.pivot._y*i.c),i.ty=this.position._y-(this.pivot._x*i.b+this.pivot._y*i.d),this._currentLocalID=this._localID,this._parentID=-1}this._parentID!==t._worldID&&(r.a=i.a*e.a+i.b*e.c,r.b=i.a*e.b+i.b*e.d,r.c=i.c*e.a+i.d*e.c,r.d=i.c*e.b+i.d*e.d,r.tx=i.tx*e.a+i.ty*e.c+e.tx,r.ty=i.tx*e.b+i.ty*e.d+e.ty,this._parentID=t._worldID,this._worldID++)},i.prototype.setFromMatrix=function(t){t.decompose(this),this._localID++},Object.defineProperties(i.prototype,{rotation:{get:function(){return this._rotation},set:function(t){this._rotation=t,this._sr=Math.sin(t),this._cr=Math.cos(t),this._localID++}}}),e.exports=i},{"../math":102,"./TransformBase":83}],85:[function(t,e,r){function i(){s.call(this),this.fillAlpha=1,this.lineWidth=0,this.lineColor=0,this.graphicsData=[],this.tint=16777215,this._prevTint=16777215,this.blendMode=c.BLEND_MODES.NORMAL,this.currentPath=null,this._webGL={},this.isMask=!1,this.boundsPadding=0,this._localBounds=new p,this.dirty=0,this.fastRectDirty=-1,this.clearDirty=0,this.boundsDirty=-1,this.cachedSpriteDirty=!1,this._spriteRect=null,this._fastRect=!1}var n,s=t("../display/Container"),o=t("../textures/RenderTexture"),a=t("../textures/Texture"),h=t("./GraphicsData"),u=t("../sprites/Sprite"),l=t("../math"),c=t("../const"),d=t("../utils"),p=t("../display/Bounds"),f=t("./utils/bezierCurveTo"),v=t("../renderers/canvas/CanvasRenderer"),g=new l.Matrix,y=new l.Point,x=new Float32Array(4),m=new Float32Array(4);i._SPRITE_TEXTURE=null,i.prototype=Object.create(s.prototype),i.prototype.constructor=i,e.exports=i,i.prototype.clone=function(){var t=new i;t.renderable=this.renderable,t.fillAlpha=this.fillAlpha,t.lineWidth=this.lineWidth,t.lineColor=this.lineColor,t.tint=this.tint,t.blendMode=this.blendMode,t.isMask=this.isMask,t.boundsPadding=this.boundsPadding,t.dirty=0,t.cachedSpriteDirty=this.cachedSpriteDirty;for(var e=0;ec*h)}return this.dirty++,this},i.prototype.arc=function(t,e,r,i,n,s){if(s=s||!1,i===n)return this;!s&&n<=i?n+=2*Math.PI:s&&i<=n&&(i+=2*Math.PI);var o=s?(i-n)*-1:n-i,a=40*Math.ceil(Math.abs(o)/(2*Math.PI));if(0===o)return this;var h=t+Math.cos(i)*r,u=e+Math.sin(i)*r;this.currentPath?this.currentPath.shape.points.push(h,u):this.moveTo(h,u);for(var l=this.currentPath.shape.points,c=o/(2*a),d=2*c,p=Math.cos(c),f=Math.sin(c),v=a-1,g=v%1/v,y=0;y<=v;y++){var x=y+g*y,m=c+i+d*x,_=Math.cos(m),b=-Math.sin(m);l.push((p*_+f*b)*r+t,(p*-b+f*_)*r+e)}return this.dirty++,this},i.prototype.beginFill=function(t,e){return this.filling=!0,this.fillColor=t||0,this.fillAlpha=void 0===e?1:e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},i.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},i.prototype.drawRect=function(t,e,r,i){return this.drawShape(new l.Rectangle(t,e,r,i)),this},i.prototype.drawRoundedRect=function(t,e,r,i,n){return this.drawShape(new l.RoundedRectangle(t,e,r,i,n)),this},i.prototype.drawCircle=function(t,e,r){return this.drawShape(new l.Circle(t,e,r)),this},i.prototype.drawEllipse=function(t,e,r,i){return this.drawShape(new l.Ellipse(t,e,r,i)),this},i.prototype.drawPolygon=function(t){var e=t,r=!0;if(e instanceof l.Polygon&&(r=e.closed,e=e.points),!Array.isArray(e)){e=new Array(arguments.length);for(var i=0;ie?o+h:e,r=ai?a+u:i;else if(p===c.SHAPES.CIRC)o=n.x,a=n.y,h=n.radius+f/2,u=n.radius+f/2,t=o-he?o+h:e,r=a-ui?a+u:i;else if(p===c.SHAPES.ELIP)o=n.x,a=n.y,h=n.width+f/2,u=n.height+f/2,t=o-he?o+h:e,r=a-ui?a+u:i;else{s=n.points;for(var v=0;ve?o+f:e,r=a-fi?a+f:i}}else t=0,e=0,r=0,i=0;var g=this.boundsPadding;this._localBounds.minX=t-g,this._localBounds.maxX=e+2*g,this._localBounds.minY=r-g,this._localBounds.maxY=i+2*g},i.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null;var e=new h(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===c.SHAPES.POLY&&(e.shape.closed=e.shape.closed||this.filling,this.currentPath=e),this.dirty++,e},i.prototype.generateCanvasTexture=function(t,e){e=e||1;var r=this.getLocalBounds(),i=new o.create(r.width*e,r.height*e);n||(n=new v),g.tx=-r.x,g.ty=-r.y,n.render(this,i,!1,g);var s=a.fromCanvas(i.baseTexture._canvasRenderTarget.canvas,t);return s.baseTexture.resolution=e,s},i.prototype.closePath=function(){var t=this.currentPath;return t&&t.shape&&t.shape.close(),this},i.prototype.addHole=function(){var t=this.graphicsData.pop();return this.currentPath=this.graphicsData[this.graphicsData.length-1],this.currentPath.addHole(t.shape),this.currentPath=null,this},i.prototype.destroy=function(){s.prototype.destroy.apply(this,arguments);for(var t=0;tO?O:A,r.beginPath(),r.moveTo(S,C+A),r.lineTo(S,C+R-A),r.quadraticCurveTo(S,C+R,S+A,C+R),r.lineTo(S+M-A,C+R),r.quadraticCurveTo(S+M,C+R,S+M,C+R-A),r.lineTo(S+M,C+A),r.quadraticCurveTo(S+M,C,S+M-A,C),r.lineTo(S+A,C),r.quadraticCurveTo(S,C,S,C+A),r.closePath(),(h.fillColor||0===h.fillColor)&&(r.globalAlpha=h.fillAlpha*i,r.fillStyle="#"+("00000"+(0|l).toString(16)).substr(-6),r.fill()),h.lineWidth&&(r.globalAlpha=h.lineAlpha*i,r.strokeStyle="#"+("00000"+(0|c).toString(16)).substr(-6),r.stroke())}}},i.prototype.updateGraphicsTint=function(t){t._prevTint=t.tint;for(var e=(t.tint>>16&255)/255,r=(t.tint>>8&255)/255,i=(255&t.tint)/255,n=0;n>16&255)/255*e*255<<16)+((o>>8&255)/255*r*255<<8)+(255&o)/255*i*255,s._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*r*255<<8)+(255&a)/255*i*255}},i.prototype.renderPolygon=function(t,e,r){r.moveTo(t[0],t[1]);for(var i=1;i32e4)&&(r=this.graphicsDataPool.pop()||new h(this.renderer.gl,this.primitiveShader,this.renderer.state.attribsState),r.reset(e),t.data.push(r)),r.dirty=!0,r}},{"../../const":78,"../../renderers/webgl/WebGLRenderer":116,"../../renderers/webgl/utils/ObjectRenderer":126,"../../utils":151,"./WebGLGraphicsData":90,"./shaders/PrimitiveShader":91,"./utils/buildCircle":92,"./utils/buildPoly":94,"./utils/buildRectangle":95,"./utils/buildRoundedRectangle":96}],90:[function(t,e,r){function i(t,e,r){this.gl=t,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=n.GLBuffer.createVertexBuffer(t),this.indexBuffer=n.GLBuffer.createIndexBuffer(t),this.dirty=!0,this.glPoints=null,this.glIndices=null,this.shader=e,this.vao=new n.VertexArrayObject(t,r).addIndex(this.indexBuffer).addAttribute(this.buffer,e.attributes.aVertexPosition,t.FLOAT,!1,24,0).addAttribute(this.buffer,e.attributes.aColor,t.FLOAT,!1,24,8)}var n=t("pixi-gl-core");i.prototype.constructor=i,e.exports=i,i.prototype.reset=function(){this.points.length=0,this.indices.length=0},i.prototype.upload=function(){this.glPoints=new Float32Array(this.points),this.buffer.upload(this.glPoints),this.glIndices=new Uint16Array(this.indices),this.indexBuffer.upload(this.glIndices),this.dirty=!1},i.prototype.destroy=function(){this.color=null,this.points=null,this.indices=null,this.vao.destroy(),this.buffer.destroy(),this.indexBuffer.destroy(),this.gl=null,this.buffer=null,this.indexBuffer=null,this.glPoints=null,this.glIndices=null}},{"pixi-gl-core":7}],91:[function(t,e,r){function i(t){n.call(this,t,["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","uniform float alpha;","uniform vec3 tint;","varying vec4 vColor;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"].join("\n"),["varying vec4 vColor;","void main(void){"," gl_FragColor = vColor;","}"].join("\n"))}var n=t("../../../Shader");i.prototype=Object.create(n.prototype),i.prototype.constructor=i,e.exports=i},{"../../../Shader":77}],92:[function(t,e,r){var i=t("./buildLine"),n=t("../../../const"),s=t("../../../utils"),o=function(t,e){var r,o,a=t.shape,h=a.x,u=a.y;t.type===n.SHAPES.CIRC?(r=a.radius,o=a.radius):(r=a.width,o=a.height);var l=Math.floor(30*Math.sqrt(a.radius))||Math.floor(15*Math.sqrt(a.width+a.height)),c=2*Math.PI/l,d=0;if(t.fill){var p=s.hex2rgb(t.fillColor),f=t.fillAlpha,v=p[0]*f,g=p[1]*f,y=p[2]*f,x=e.points,m=e.indices,_=x.length/6;for(m.push(_),d=0;d19600?(T=x-_,E=m-b,P=Math.sqrt(T*T+E*E),T/=P,E/=P,T*=k,E*=k,I.push(f-T,v-E),I.push(W,G,X,j),I.push(f+T,v+E),I.push(W,G,X,j),I.push(f-T,v-E),I.push(W,G,X,j),B++):(I.push(l,c),I.push(W,G,X,j),I.push(f-(l-f),v-(c-v)),I.push(W,G,X,j)));for(d=s[2*(F-2)],p=s[2*(F-2)+1],f=s[2*(F-1)],v=s[2*(F-1)+1],x=-(p-v),m=d-f,P=Math.sqrt(x*x+m*m),x/=P,m/=P,x*=k,m*=k,I.push(f-x,v-m),I.push(W,G,X,j),I.push(f+x,v+m),I.push(W,G,X,j),L.push(N),r=0;r=6){for(var o=[],a=t.holes,h=0;h0&&i(t,e)};e.exports=o},{"../../../utils":151,"./buildLine":93,earcut:31}],95:[function(t,e,r){var i=t("./buildLine"),n=t("../../../utils"),s=function(t,e){var r=t.shape,s=r.x,o=r.y,a=r.width,h=r.height;if(t.fill){var u=n.hex2rgb(t.fillColor),l=t.fillAlpha,c=u[0]*l,d=u[1]*l,p=u[2]*l,f=e.points,v=e.indices,g=f.length/6;f.push(s,o),f.push(c,d,p,l),f.push(s+a,o),f.push(c,d,p,l),f.push(s,o+h),f.push(c,d,p,l),f.push(s+a,o+h),f.push(c,d,p,l),v.push(g,g,g+1,g+2,g+3,g+3)}if(t.lineWidth){var y=t.points;t.points=[s,o,s+a,o,s+a,o+h,s,o+h,s,o],i(t,e),t.points=y}};e.exports=s},{"../../../utils":151,"./buildLine":93}],96:[function(t,e,r){var i=t("earcut"),n=t("./buildLine"),s=t("../../../utils"),o=function(t,e){var r=t.shape,o=r.x,h=r.y,u=r.width,l=r.height,c=r.radius,d=[];if(d.push(o,h+c),a(o,h+l-c,o,h+l,o+c,h+l,d),a(o+u-c,h+l,o+u,h+l,o+u,h+l-c,d),a(o+u,h+c,o+u,h,o+u-c,h,d),a(o+c,h,o,h,o,h+c+1e-10,d),t.fill){var p=s.hex2rgb(t.fillColor),f=t.fillAlpha,v=p[0]*f,g=p[1]*f,y=p[2]*f,x=e.points,m=e.indices,_=x.length/6,b=i(d,null,2),T=0;for(T=0;T0?1:0}function n(){for(var t=0;t<16;t++){var e=[];c.push(e);for(var r=0;r<16;r++)for(var n=i(s[t]*s[r]+a[t]*o[r]),d=i(o[t]*s[r]+h[t]*o[r]),p=i(s[t]*a[r]+a[t]*h[r]),f=i(o[t]*a[r]+h[t]*h[r]),v=0;v<16;v++)if(s[v]===n&&o[v]===d&&a[v]===p&&h[v]===f){e.push(v);break}}for(t=0;t<16;t++){var g=new l;g.set(s[t],o[t],a[t],h[t],0,0),u.push(g)}}var s=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],o=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],a=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],h=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],u=[],l=t("./Matrix"),c=[];n();var d={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MIRROR_HORIZONTAL:12,uX:function(t){return s[t]},uY:function(t){return o[t]},vX:function(t){return a[t]},vY:function(t){return h[t]},inv:function(t){return 8&t?15&t:7&-t},add:function(t,e){return c[t][e]},sub:function(t,e){return c[t][d.inv(e)]},rotate180:function(t){return 4^t},isSwapWidthHeight:function(t){return 2===(3&t)},byDirection:function(t,e){return 2*Math.abs(t)<=Math.abs(e)?e>=0?d.S:d.N:2*Math.abs(e)<=Math.abs(t)?t>0?d.E:d.W:e>0?t>0?d.SE:d.SW:t>0?d.NE:d.NW},matrixAppendRotationInv:function(t,e,r,i){var n=u[d.inv(e)];r=r||0,i=i||0,n.tx=r,n.ty=i,t.append(n)}};e.exports=d},{"./Matrix":99}],99:[function(t,e,r){function i(){this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this.array=null}var n=t("./Point");i.prototype.constructor=i,e.exports=i,i.prototype.fromArray=function(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]},i.prototype.set=function(t,e,r,i,n,s){return this.a=t,this.b=e,this.c=r,this.d=i,this.tx=n,this.ty=s,this},i.prototype.toArray=function(t,e){this.array||(this.array=new Float32Array(9));var r=e||this.array;return t?(r[0]=this.a,r[1]=this.b,r[2]=0,r[3]=this.c,r[4]=this.d,r[5]=0,r[6]=this.tx,r[7]=this.ty,r[8]=1):(r[0]=this.a,r[1]=this.c,r[2]=this.tx,r[3]=this.b,r[4]=this.d,r[5]=this.ty,r[6]=0,r[7]=0,r[8]=1),r},i.prototype.apply=function(t,e){e=e||new n;var r=t.x,i=t.y;return e.x=this.a*r+this.c*i+this.tx,e.y=this.b*r+this.d*i+this.ty,e},i.prototype.applyInverse=function(t,e){e=e||new n;var r=1/(this.a*this.d+this.c*-this.b),i=t.x,s=t.y;return e.x=this.d*r*i+-this.c*r*s+(this.ty*this.c-this.tx*this.d)*r,e.y=this.a*r*s+-this.b*r*i+(-this.ty*this.a+this.tx*this.b)*r,e},i.prototype.translate=function(t,e){return this.tx+=t,this.ty+=e,this},i.prototype.scale=function(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this},i.prototype.rotate=function(t){var e=Math.cos(t),r=Math.sin(t),i=this.a,n=this.c,s=this.tx;return this.a=i*e-this.b*r,this.b=i*r+this.b*e,this.c=n*e-this.d*r,this.d=n*r+this.d*e,this.tx=s*e-this.ty*r,this.ty=s*r+this.ty*e,this},i.prototype.append=function(t){var e=this.a,r=this.b,i=this.c,n=this.d;return this.a=t.a*e+t.b*i,this.b=t.a*r+t.b*n,this.c=t.c*e+t.d*i,this.d=t.c*r+t.d*n,this.tx=t.tx*e+t.ty*i+this.tx,this.ty=t.tx*r+t.ty*n+this.ty,this},i.prototype.setTransform=function(t,e,r,i,n,s,o,a,h){var u,l,c,d,p,f,v,g,y,x;return p=Math.sin(o),f=Math.cos(o),v=Math.cos(h),g=Math.sin(h),y=-Math.sin(a),x=Math.cos(a),u=f*n,l=p*n,c=-p*s,d=f*s,this.a=v*u+g*c,this.b=v*l+g*d,this.c=y*u+x*c,this.d=y*l+x*d,this.tx=t+(r*u+i*c),this.ty=e+(r*l+i*d),this},i.prototype.prepend=function(t){var e=this.tx;if(1!==t.a||0!==t.b||0!==t.c||1!==t.d){var r=this.a,i=this.c;this.a=r*t.a+this.b*t.c,this.b=r*t.b+this.b*t.d,this.c=i*t.a+this.d*t.c,this.d=i*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this},i.prototype.decompose=function(t){var e=this.a,r=this.b,i=this.c,n=this.d,s=Math.atan2(-i,n),o=Math.atan2(r,e),a=Math.abs(1-s/o);return a<1e-5?(t.rotation=o,e<0&&n>=0&&(t.rotation+=t.rotation<=0?Math.PI:-Math.PI),t.skew.x=t.skew.y=0):(t.skew.x=s,t.skew.y=o),t.scale.x=Math.sqrt(e*e+r*r),t.scale.y=Math.sqrt(i*i+n*n),t.position.x=this.tx,t.position.y=this.ty,t},i.prototype.invert=function(){var t=this.a,e=this.b,r=this.c,i=this.d,n=this.tx,s=t*i-e*r;return this.a=i/s,this.b=-e/s,this.c=-r/s,this.d=t/s,this.tx=(r*this.ty-i*n)/s,this.ty=-(t*this.ty-e*n)/s,this},i.prototype.identity=function(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this},i.prototype.clone=function(){var t=new i;return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t},i.prototype.copy=function(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t},i.IDENTITY=new i,i.TEMP_MATRIX=new i},{"./Point":101}],100:[function(t,e,r){function i(t,e,r,i){this._x=r||0,this._y=i||0,this.cb=t,this.scope=e}i.prototype.constructor=i,e.exports=i,Object.defineProperties(i.prototype,{x:{get:function(){return this._x},set:function(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}},y:{get:function(){return this._y},set:function(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}}),i.prototype.set=function(t,e){var r=t||0,i=e||(0!==e?r:0);this._x===r&&this._y===i||(this._x=r,this._y=i,this.cb.call(this.scope))},i.prototype.copy=function(t){this._x===t.x&&this._y===t.y||(this._x=t.x,this._y=t.y,this.cb.call(this.scope))}},{}],101:[function(t,e,r){function i(t,e){this.x=t||0,this.y=e||0}i.prototype.constructor=i,e.exports=i,i.prototype.clone=function(){return new i(this.x,this.y)},i.prototype.copy=function(t){this.set(t.x,t.y)},i.prototype.equals=function(t){return t.x===this.x&&t.y===this.y},i.prototype.set=function(t,e){this.x=t||0,this.y=e||(0!==e?this.x:0)}},{}],102:[function(t,e,r){e.exports={Point:t("./Point"),ObservablePoint:t("./ObservablePoint"),Matrix:t("./Matrix"),GroupD8:t("./GroupD8"),Circle:t("./shapes/Circle"),Ellipse:t("./shapes/Ellipse"),Polygon:t("./shapes/Polygon"),Rectangle:t("./shapes/Rectangle"),RoundedRectangle:t("./shapes/RoundedRectangle")}},{"./GroupD8":98,"./Matrix":99,"./ObservablePoint":100,"./Point":101,"./shapes/Circle":103,"./shapes/Ellipse":104,"./shapes/Polygon":105,"./shapes/Rectangle":106,"./shapes/RoundedRectangle":107}],103:[function(t,e,r){function i(t,e,r){this.x=t||0,this.y=e||0,this.radius=r||0,this.type=s.SHAPES.CIRC}var n=t("./Rectangle"),s=t("../../const");i.prototype.constructor=i,e.exports=i,i.prototype.clone=function(){return new i(this.x,this.y,this.radius)},i.prototype.contains=function(t,e){if(this.radius<=0)return!1;var r=this.x-t,i=this.y-e,n=this.radius*this.radius;return r*=r,i*=i,r+i<=n},i.prototype.getBounds=function(){return new n(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)}},{"../../const":78,"./Rectangle":106}],104:[function(t,e,r){function i(t,e,r,i){this.x=t||0,this.y=e||0,this.width=r||0,this.height=i||0,this.type=s.SHAPES.ELIP}var n=t("./Rectangle"),s=t("../../const");i.prototype.constructor=i,e.exports=i,i.prototype.clone=function(){return new i(this.x,this.y,this.width,this.height)},i.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;var r=(t-this.x)/this.width,i=(e-this.y)/this.height;return r*=r,i*=i,r+i<=1},i.prototype.getBounds=function(){return new n(this.x-this.width,this.y-this.height,this.width,this.height)}},{"../../const":78,"./Rectangle":106}],105:[function(t,e,r){function i(t){var e=t;if(!Array.isArray(e)){e=new Array(arguments.length);for(var r=0;re!=u>e&&t<(h-o)*(e-a)/(u-a)+o;l&&(r=!r)}return r}},{"../../const":78,"../Point":101}],106:[function(t,e,r){function i(t,e,r,i){this.x=t||0,this.y=e||0,this.width=r||0,this.height=i||0,this.type=n.SHAPES.RECT}var n=t("../../const");i.prototype.constructor=i,e.exports=i,Object.defineProperties(i.prototype,{left:{get:function(){return this.x}},right:{get:function(){return this.x+this.width}},top:{get:function(){return this.y}},bottom:{get:function(){return this.y+this.height}}}),i.EMPTY=new i(0,0,0,0),i.prototype.clone=function(){return new i(this.x,this.y,this.width,this.height)},i.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this},i.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t=this.y&&et.x+t.width&&(this.width=t.width-this.x,this.width<0&&(this.width=0)),this.y+this.height>t.y+t.height&&(this.height=t.height-this.y,this.height<0&&(this.height=0))},i.prototype.enlarge=function(t){if(t!==i.EMPTY){var e=Math.min(this.x,t.x),r=Math.max(this.x+this.width,t.x+t.width),n=Math.min(this.y,t.y),s=Math.max(this.y+this.height,t.y+t.height); +this.x=e,this.width=r-e,this.y=n,this.height=s-n}}},{"../../const":78}],107:[function(t,e,r){function i(t,e,r,i,s){this.x=t||0,this.y=e||0,this.width=r||0,this.height=i||0,this.radius=s||20,this.type=n.SHAPES.RREC}var n=t("../../const");i.prototype.constructor=i,e.exports=i,i.prototype.clone=function(){return new i(this.x,this.y,this.width,this.height,this.radius)},i.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height)}},{"../../const":78}],108:[function(t,e,r){function i(t,e,r,i){if(u.call(this),n.sayHello(t),i)for(var s in o.DEFAULT_RENDER_OPTIONS)"undefined"==typeof i[s]&&(i[s]=o.DEFAULT_RENDER_OPTIONS[s]);else i=o.DEFAULT_RENDER_OPTIONS;this.type=o.RENDERER_TYPE.UNKNOWN,this.width=e||800,this.height=r||600,this.view=i.view||document.createElement("canvas"),this.resolution=i.resolution,this.transparent=i.transparent,this.autoResize=i.autoResize||!1,this.blendModes=null,this.preserveDrawingBuffer=i.preserveDrawingBuffer,this.clearBeforeRender=i.clearBeforeRender,this.roundPixels=i.roundPixels,this._backgroundColor=0,this._backgroundColorRgba=[0,0,0,0],this._backgroundColorString="#000000",this.backgroundColor=i.backgroundColor||this._backgroundColor,this._tempDisplayObjectParent=new a,this._lastObjectRendered=this._tempDisplayObjectParent}var n=t("../utils"),s=t("../math"),o=t("../const"),a=t("../display/Container"),h=t("../textures/RenderTexture"),u=t("eventemitter3"),l=new s.Matrix;i.prototype=Object.create(u.prototype),i.prototype.constructor=i,e.exports=i,Object.defineProperties(i.prototype,{backgroundColor:{get:function(){return this._backgroundColor},set:function(t){this._backgroundColor=t,this._backgroundColorString=n.hex2string(t),n.hex2rgb(t,this._backgroundColorRgba)}}}),i.prototype.resize=function(t,e){this.width=t*this.resolution,this.height=e*this.resolution,this.view.width=this.width,this.view.height=this.height,this.autoResize&&(this.view.style.width=this.width/this.resolution+"px",this.view.style.height=this.height/this.resolution+"px")},i.prototype.generateTexture=function(t,e,r){var i=t.getLocalBounds(),n=h.create(0|i.width,0|i.height,e,r);return l.tx=-i.x,l.ty=-i.y,this.render(t,n,!1,l,!0),n},i.prototype.destroy=function(t){t&&this.view.parentNode&&this.view.parentNode.removeChild(this.view),this.type=o.RENDERER_TYPE.UNKNOWN,this.width=0,this.height=0,this.view=null,this.resolution=0,this.transparent=!1,this.autoResize=!1,this.blendModes=null,this.preserveDrawingBuffer=!1,this.clearBeforeRender=!1,this.roundPixels=!1,this._backgroundColor=0,this._backgroundColorRgba=null,this._backgroundColorString=null,this.backgroundColor=0,this._tempDisplayObjectParent=null,this._lastObjectRendered=null}},{"../const":78,"../display/Container":80,"../math":102,"../textures/RenderTexture":143,"../utils":151,eventemitter3:32}],109:[function(t,e,r){function i(t,e,r){r=r||{},n.call(this,"Canvas",t,e,r),this.type=u.RENDERER_TYPE.CANVAS,this.rootContext=this.view.getContext("2d",{alpha:this.transparent}),this.rootResolution=this.resolution,this.refresh=!0,this.maskManager=new s(this),this.smoothProperty="imageSmoothingEnabled",this.rootContext.imageSmoothingEnabled||(this.rootContext.webkitImageSmoothingEnabled?this.smoothProperty="webkitImageSmoothingEnabled":this.rootContext.mozImageSmoothingEnabled?this.smoothProperty="mozImageSmoothingEnabled":this.rootContext.oImageSmoothingEnabled?this.smoothProperty="oImageSmoothingEnabled":this.rootContext.msImageSmoothingEnabled&&(this.smoothProperty="msImageSmoothingEnabled")),this.initPlugins(),this.blendModes=a(),this._activeBlendMode=null,this.context=null,this.renderingToScreen=!1,this.resize(t,e)}var n=t("../SystemRenderer"),s=t("./utils/CanvasMaskManager"),o=t("./utils/CanvasRenderTarget"),a=t("./utils/mapCanvasBlendModesToPixi"),h=t("../../utils"),u=t("../../const");i.prototype=Object.create(n.prototype),i.prototype.constructor=i,e.exports=i,h.pluginTarget.mixin(i),i.prototype.render=function(t,e,r,i,n){if(this.view){this.renderingToScreen=!e,this.emit("prerender"),e?(e=e.baseTexture||e,e._canvasRenderTarget||(e._canvasRenderTarget=new o(e.width,e.height,e.resolution),e.source=e._canvasRenderTarget.canvas,e.valid=!0),this.context=e._canvasRenderTarget.context,this.resolution=e._canvasRenderTarget.resolution):(this.context=this.rootContext,this.resolution=this.rootResolution);var s=this.context;if(e||(this._lastObjectRendered=t),!n){var a=t.parent,h=this._tempDisplayObjectParent.transform.worldTransform;i?i.copy(h):h.identity(),t.parent=this._tempDisplayObjectParent,t.updateTransform(),t.parent=a}s.setTransform(1,0,0,1,0,0),s.globalAlpha=1,s.globalCompositeOperation=this.blendModes[u.BLEND_MODES.NORMAL],navigator.isCocoonJS&&this.view.screencanvas&&(s.fillStyle="black",s.clear()),(void 0!==r?r:this.clearBeforeRender)&&this.renderingToScreen&&(this.transparent?s.clearRect(0,0,this.width,this.height):(s.fillStyle=this._backgroundColorString,s.fillRect(0,0,this.width,this.height)));var l=this.context;this.context=s,t.renderCanvas(this),this.context=l,this.emit("postrender")}},i.prototype.setBlendMode=function(t){this._activeBlendMode!==t&&(this.context.globalCompositeOperation=this.blendModes[t])},i.prototype.destroy=function(t){this.destroyPlugins(),n.prototype.destroy.call(this,t),this.context=null,this.refresh=!0,this.maskManager.destroy(),this.maskManager=null,this.smoothProperty=null},i.prototype.resize=function(t,e){n.prototype.resize.call(this,t,e),this.smoothProperty&&(this.rootContext[this.smoothProperty]=u.SCALE_MODES.DEFAULT===u.SCALE_MODES.LINEAR)}},{"../../const":78,"../../utils":151,"../SystemRenderer":108,"./utils/CanvasMaskManager":110,"./utils/CanvasRenderTarget":111,"./utils/mapCanvasBlendModesToPixi":113}],110:[function(t,e,r){function i(t){this.renderer=t}var n=t("../../../const");i.prototype.constructor=i,e.exports=i,i.prototype.pushMask=function(t){var e=this.renderer;e.context.save();var r=t.alpha,i=t.transform.worldTransform,n=e.resolution;e.context.setTransform(i.a*n,i.b*n,i.c*n,i.d*n,i.tx*n,i.ty*n),t._texture||(this.renderGraphicsShape(t),e.context.clip()),t.worldAlpha=r},i.prototype.renderGraphicsShape=function(t){var e=this.renderer.context,r=t.graphicsData.length;if(0!==r){e.beginPath();for(var i=0;iS?S:w,e.moveTo(_,b+w),e.lineTo(_,b+E-w),e.quadraticCurveTo(_,b+E,_+w,b+E),e.lineTo(_+T-w,b+E),e.quadraticCurveTo(_+T,b+E,_+T,b+E-w),e.lineTo(_+T,b+w),e.quadraticCurveTo(_+T,b,_+T-w,b),e.lineTo(_+w,b),e.quadraticCurveTo(_,b,_,b+w),e.closePath()}}}},i.prototype.popMask=function(t){t.context.restore()},i.prototype.destroy=function(){}},{"../../../const":78}],111:[function(t,e,r){function i(t,e,r){this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d"),this.resolution=r||n.RESOLUTION,this.resize(t,e)}var n=t("../../../const");i.prototype.constructor=i,e.exports=i,Object.defineProperties(i.prototype,{width:{get:function(){return this.canvas.width},set:function(t){this.canvas.width=t}},height:{get:function(){return this.canvas.height},set:function(t){this.canvas.height=t}}}),i.prototype.clear=function(){this.context.setTransform(1,0,0,1,0,0),this.context.clearRect(0,0,this.canvas.width,this.canvas.height)},i.prototype.resize=function(t,e){this.canvas.width=t*this.resolution,this.canvas.height=e*this.resolution},i.prototype.destroy=function(){this.context=null,this.canvas=null}},{"../../../const":78}],112:[function(t,e,r){var i=function(t){var e=document.createElement("canvas");e.width=6,e.height=1;var r=e.getContext("2d");return r.fillStyle=t,r.fillRect(0,0,6,1),e},n=function(){if("undefined"==typeof document)return!1;var t=i("#ff00ff"),e=i("#ffff00"),r=document.createElement("canvas");r.width=6,r.height=1;var n=r.getContext("2d");n.globalCompositeOperation="multiply",n.drawImage(t,0,0),n.drawImage(e,2,0);var s=n.getImageData(2,0,1,1);if(!s)return!1;var o=s.data;return 255===o[0]&&0===o[1]&&0===o[2]};e.exports=n},{}],113:[function(t,e,r){function i(t){return t=t||[],s()?(t[n.BLEND_MODES.NORMAL]="source-over",t[n.BLEND_MODES.ADD]="lighter",t[n.BLEND_MODES.MULTIPLY]="multiply",t[n.BLEND_MODES.SCREEN]="screen",t[n.BLEND_MODES.OVERLAY]="overlay",t[n.BLEND_MODES.DARKEN]="darken",t[n.BLEND_MODES.LIGHTEN]="lighten",t[n.BLEND_MODES.COLOR_DODGE]="color-dodge",t[n.BLEND_MODES.COLOR_BURN]="color-burn",t[n.BLEND_MODES.HARD_LIGHT]="hard-light",t[n.BLEND_MODES.SOFT_LIGHT]="soft-light",t[n.BLEND_MODES.DIFFERENCE]="difference",t[n.BLEND_MODES.EXCLUSION]="exclusion",t[n.BLEND_MODES.HUE]="hue",t[n.BLEND_MODES.SATURATION]="saturate",t[n.BLEND_MODES.COLOR]="color",t[n.BLEND_MODES.LUMINOSITY]="luminosity"):(t[n.BLEND_MODES.NORMAL]="source-over",t[n.BLEND_MODES.ADD]="lighter",t[n.BLEND_MODES.MULTIPLY]="source-over",t[n.BLEND_MODES.SCREEN]="source-over",t[n.BLEND_MODES.OVERLAY]="source-over",t[n.BLEND_MODES.DARKEN]="source-over",t[n.BLEND_MODES.LIGHTEN]="source-over",t[n.BLEND_MODES.COLOR_DODGE]="source-over",t[n.BLEND_MODES.COLOR_BURN]="source-over",t[n.BLEND_MODES.HARD_LIGHT]="source-over",t[n.BLEND_MODES.SOFT_LIGHT]="source-over",t[n.BLEND_MODES.DIFFERENCE]="source-over",t[n.BLEND_MODES.EXCLUSION]="source-over",t[n.BLEND_MODES.HUE]="source-over",t[n.BLEND_MODES.SATURATION]="source-over",t[n.BLEND_MODES.COLOR]="source-over",t[n.BLEND_MODES.LUMINOSITY]="source-over"),t}var n=t("../../../const"),s=t("./canUseNewCanvasBlendModes");e.exports=i},{"../../../const":78,"./canUseNewCanvasBlendModes":112}],114:[function(t,e,r){function i(t){this.renderer=t,this.count=0,this.checkCount=0,this.maxIdle=3600,this.checkCountMax=600,this.mode=n.GC_MODES.DEFAULT}var n=t("../../const");i.prototype.constructor=i,e.exports=i,i.prototype.update=function(){this.count++,this.mode!==n.GC_MODES.MANUAL&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run()))},i.prototype.run=function(){var t,e,r=this.renderer.textureManager,i=r._managedTextures,n=!1;for(t=0;tthis.maxIdle&&(r.destroyTexture(s,!0),i[t]=null,n=!0)}if(n){for(e=0,t=0;t=0;r--)this.unload(t.children[r])}},{"../../const":78}],115:[function(t,e,r){var i=t("pixi-gl-core").GLTexture,n=t("../../const"),s=t("./utils/RenderTarget"),o=t("../../utils"),a=function(t){this.renderer=t,this.gl=t.gl,this._managedTextures=[]};a.prototype.bindTexture=function(){},a.prototype.getTexture=function(){},a.prototype.updateTexture=function(t){t=t.baseTexture||t;var e=!!t._glRenderTargets;if(t.hasLoaded){var r=t._glTextures[this.renderer.CONTEXT_UID];if(r)e?t._glRenderTargets[this.renderer.CONTEXT_UID].resize(t.width,t.height):r.upload(t.source);else{if(e){var o=new s(this.gl,t.width,t.height,t.scaleMode,t.resolution);o.resize(t.width,t.height),t._glRenderTargets[this.renderer.CONTEXT_UID]=o,r=o.texture}else r=new i(this.gl),r.premultiplyAlpha=!0,r.upload(t.source);t._glTextures[this.renderer.CONTEXT_UID]=r,t.on("update",this.updateTexture,this),t.on("dispose",this.destroyTexture,this),this._managedTextures.push(t),t.isPowerOfTwo?(t.mipmap&&r.enableMipmap(),t.wrapMode===n.WRAP_MODES.CLAMP?r.enableWrapClamp():t.wrapMode===n.WRAP_MODES.REPEAT?r.enableWrapRepeat():r.enableWrapMirrorRepeat()):r.enableWrapClamp(),t.scaleMode===n.SCALE_MODES.NEAREST?r.enableNearestScaling():r.enableLinearScaling()}return r}},a.prototype.destroyTexture=function(t,e){if(t=t.baseTexture||t,t.hasLoaded&&t._glTextures[this.renderer.CONTEXT_UID]&&(t._glTextures[this.renderer.CONTEXT_UID].destroy(),t.off("update",this.updateTexture,this),t.off("dispose",this.destroyTexture,this),delete t._glTextures[this.renderer.CONTEXT_UID],!e)){var r=this._managedTextures.indexOf(t);r!==-1&&o.removeItems(this._managedTextures,r,1)}},a.prototype.removeAll=function(){for(var t=0;t 0.5)"," {"," color = vec4(1.0, 0.0, 0.0, 1.0);"," }"," else"," {"," color = vec4(0.0, 1.0, 0.0, 1.0);"," }"," gl_FragColor = mix(sample, masky, 0.5);"," gl_FragColor *= sample.a;","}"].join("\n")},{"../../../const":78,"../../../utils":151,"./extractUniformsFromSrc":119}],119:[function(t,e,r){function i(t,e,r){var i=n(t,r),s=n(e,r);return Object.assign(i,s)}function n(t){for(var e,r=new RegExp("^(projectionMatrix|uSampler|filterArea)$"),i={},n=t.replace(/\s+/g," ").split(/\s*;\s*/),o=0;o-1){var h=a.split(" "),u=h[1],l=h[2],c=1;l.indexOf("[")>-1&&(e=l.split(/\[|\]/),l=e[0],c*=Number(e[1])),l.match(r)||(i[l]={value:s(u,c),name:l,type:u})}}return i}var s=t("pixi-gl-core").shader.defaultValue;e.exports=i},{"pixi-gl-core":7}],120:[function(t,e,r){var i=t("../../../math"),n=function(t,e,r){var i=t.identity();return i.translate(e.x/r.width,e.y/r.height),i.scale(r.width,r.height),i},s=function(t,e,r){var i=t.identity();i.translate(e.x/r.width,e.y/r.height);var n=r.width/e.width,s=r.height/e.height;return i.scale(n,s),i},o=function(t,e,r,n){var s=n.worldTransform.copy(i.Matrix.TEMP_MATRIX),o=n._texture.baseTexture,a=t.identity(),h=r.height/r.width;a.translate(e.x/r.width,e.y/r.height),a.scale(1,h);var u=r.width/o.width,l=r.height/o.height;return s.tx/=o.width*u,s.ty/=o.width*u,s.invert(),a.prepend(s),a.scale(1,1/h),a.scale(u,l),a.translate(n.anchor.x,n.anchor.y),a};e.exports={calculateScreenSpaceMatrix:n,calculateNormalizedScreenSpaceMatrix:s,calculateSpriteMatrix:o}},{"../../../math":102}],121:[function(t,e,r){function i(t){var e=new s.Matrix;n.call(this,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n","#define GLSLIFY 1\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n original *= (masky.r * masky.a * alpha * clip);\n gl_FragColor = original;\n}\n"),t.renderable=!1,this.maskSprite=t,this.maskMatrix=e}var n=t("../Filter"),s=t("../../../../math");i.prototype=Object.create(n.prototype),i.prototype.constructor=i,e.exports=i,i.prototype.apply=function(t,e,r){var i=this.maskSprite;this.uniforms.mask=i._texture,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,i),this.uniforms.alpha=i.worldAlpha,t.applyFilter(this,e,r)}},{"../../../../math":102,"../Filter":118}],122:[function(t,e,r){function i(t){n.call(this,t),this.gl=this.renderer.gl,this.quad=new o(this.gl,t.state.attribState),this.shaderCache={},this.pool={},this.filterData=null}var n=t("./WebGLManager"),s=t("../utils/RenderTarget"),o=t("../utils/Quad"),a=t("../../../math"),h=t("../../../Shader"),u=t("../filters/filterTransforms"),l=t("bit-twiddle"),c=function(){this.renderTarget=null,this.sourceFrame=new a.Rectangle,this.destinationFrame=new a.Rectangle,this.filters=[],this.target=null,this.resolution=1};i.prototype=Object.create(n.prototype),i.prototype.constructor=i,e.exports=i,i.prototype.pushFilter=function(t,e){var r=this.renderer,i=this.filterData;if(!i){i=this.renderer._activeRenderTarget.filterStack;var n=new c;n.sourceFrame=n.destinationFrame=this.renderer._activeRenderTarget.size,n.renderTarget=r._activeRenderTarget,this.renderer._activeRenderTarget.filterData=i={index:0,stack:[n]},this.filterData=i}var s=i.stack[++i.index];s||(s=i.stack[i.index]=new c);var o=e[0].resolution,a=e[0].padding,h=t.filterArea||t.getBounds(!0),u=s.sourceFrame,l=s.destinationFrame;u.x=(h.x*o|0)/o,u.y=(h.y*o|0)/o,u.width=(h.width*o|0)/o,u.height=(h.height*o|0)/o,i.stack[0].renderTarget.transform||u.fit(i.stack[0].destinationFrame),u.pad(a),l.width=u.width,l.height=u.height;var d=this.getPotRenderTarget(r.gl,u.width,u.height,o);s.target=t,s.filters=e,s.resolution=o,s.renderTarget=d,d.setFrame(l,u),r.bindRenderTarget(d),r.clear()},i.prototype.popFilter=function(){var t=this.filterData,e=t.stack[t.index-1],r=t.stack[t.index];this.quad.map(r.renderTarget.size,r.sourceFrame).upload();var i=r.filters;if(1===i.length)i[0].apply(this,r.renderTarget,e.renderTarget,!1),this.freePotRenderTarget(r.renderTarget);else{var n=r.renderTarget,s=this.getPotRenderTarget(this.renderer.gl,r.sourceFrame.width,r.sourceFrame.height,1);s.setFrame(r.destinationFrame,r.sourceFrame);for(var o=0;o0&&(e+="\nelse "),r>16)+(65280&t)+((255&t)<<16)}},texture:{get:function(){return this._texture},set:function(t){this._texture!==t&&(this._texture=t,this.cachedTint=16777215,this._textureID=-1,t&&(t.baseTexture.hasLoaded?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}}),i.prototype._onTextureUpdate=function(){this._textureID=-1,this._width&&(this.scale.x=a.sign(this.scale.x)*this._width/this.texture.orig.width),this._height&&(this.scale.y=a.sign(this.scale.y)*this._height/this.texture.orig.height)},i.prototype.onAnchorUpdate=function(){this._transformID=-1},i.prototype.calculateVertices=function(){if(this._transformID!==this.transform._worldID||this._textureID!==this._texture._updateID){this._transformID=this.transform._worldID,this._textureID=this._texture._updateID;var t,e,r,i,n=this._texture,s=this.transform.worldTransform,o=s.a,a=s.b,h=s.c,u=s.d,l=s.tx,c=s.ty,d=this.vertexData,p=n.trim,f=n.orig;p?(e=p.x-this.anchor._x*f.width,t=e+p.width,i=p.y-this.anchor._y*f.height,r=i+p.height):(t=f.width*(1-this.anchor._x),e=f.width*-this.anchor._x,r=f.height*(1-this.anchor._y),i=f.height*-this.anchor._y),d[0]=o*e+h*i+l,d[1]=u*i+a*e+c,d[2]=o*t+h*i+l,d[3]=u*i+a*t+c,d[4]=o*t+h*r+l,d[5]=u*r+a*t+c,d[6]=o*e+h*r+l,d[7]=u*r+a*e+c}},i.prototype.calculateTrimmedVertices=function(){this.vertexTrimmedData||(this.vertexTrimmedData=new Float32Array(8));var t,e,r,i,n=this._texture,s=this.vertexTrimmedData,o=n.orig,a=this.transform.worldTransform,h=a.a,u=a.b,l=a.c,c=a.d,d=a.tx,p=a.ty;t=o.width*(1-this.anchor._x),e=o.width*-this.anchor._x,r=o.height*(1-this.anchor._y),i=o.height*-this.anchor._y,s[0]=h*e+l*i+d,s[1]=c*i+u*e+p,s[2]=h*t+l*i+d,s[3]=c*i+u*t+p,s[4]=h*t+l*r+d,s[5]=c*r+u*t+p,s[6]=h*e+l*r+d,s[7]=c*r+u*e+p},i.prototype._renderWebGL=function(t){this.calculateVertices(),t.setObjectRenderer(t.plugins.sprite),t.plugins.sprite.render(this)},i.prototype._renderCanvas=function(t){t.plugins.sprite.render(this)},i.prototype._calculateBounds=function(){var t=this._texture.trim,e=this._texture.orig;!t||t.width===e.width&&t.height===e.height?(this.calculateVertices(),this._bounds.addQuad(this.vertexData)):(this.calculateTrimmedVertices(),this._bounds.addQuad(this.vertexTrimmedData))},i.prototype.getLocalBounds=function(t){return 0===this.children.length?(this._bounds.minX=-this._texture.orig.width*this.anchor._x,this._bounds.minY=-this._texture.orig.height*this.anchor._y,this._bounds.maxX=this._texture.orig.width,this._bounds.maxY=this._texture.orig.height,t||(this._localBoundsRect||(this._localBoundsRect=new n.Rectangle),t=this._localBoundsRect),this._bounds.getRectangle(t)):o.prototype.getLocalBounds.call(this,t)},i.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,u);var e,r=this._texture.orig.width,i=this._texture.orig.height,n=-r*this.anchor.x;return u.x>n&&u.xe&&u.y=this.size&&this.flush(),t.texture._uvs&&(this.sprites[this.currentIndex++]=t)},i.prototype.flush=function(){if(0!==this.currentIndex){var t,e,r,i,n,s,o,h=this.renderer.gl,u=d.nextPow2(this.currentIndex),l=d.log2(u),f=this.buffers[l],v=this.sprites,g=this.groups,y=f.float32View,x=f.uint32View,m=0,_=1,b=0,T=g[0],E=v[0].blendMode;T.textureCount=0,T.start=0,T.blend=E,p++;for(var w=0;w0&&(e+="\nelse "),r0?(this.context.shadowColor=e.dropShadowColor,this.context.shadowBlur=e.dropShadowBlur):this.context.fillStyle=e.dropShadowColor;var v=Math.cos(e.dropShadowAngle)*e.dropShadowDistance,g=Math.sin(e.dropShadowAngle)*e.dropShadowDistance;for(i=0;io;h--){for(u=0;ui)for(var u=o[a].split(""),l=0;ls?(e+="\n"+u[l],s=i-c):(0===l&&(e+=" "),e+=u[l],s-=c)}else{var d=h+this.context.measureText(" ").width;0===a||d>s?(a>0&&(e+="\n"),e+=o[a],s=i-h):(s-=d,e+=" "+o[a])}}n0&&e>0,this.width=t,this.height=e,this.realWidth=this.width*this.resolution,this.realHeight=this.height*this.resolution,this.valid&&this.emit("update",this))},i.prototype.destroy=function(){n.prototype.destroy.call(this,!0),this.renderer=null}},{"../const":78,"./BaseTexture":142}],142:[function(t,e,r){function i(t,e,r){o.call(this),this.uid=n.uid(),this.touched=0,this.resolution=r||s.RESOLUTION,this.width=100,this.height=100,this.realWidth=100,this.realHeight=100,this.scaleMode=e||s.SCALE_MODES.DEFAULT,this.hasLoaded=!1,this.isLoading=!1,this.source=null,this.premultipliedAlpha=!0,this.imageUrl=null,this.isPowerOfTwo=!1,this.mipmap=s.MIPMAP_TEXTURES,this.wrapMode=s.WRAP_MODES.DEFAULT,this._glTextures=[],this._enabled=0,this._id=0,t&&this.loadSource(t)}var n=t("../utils"),s=t("../const"),o=t("eventemitter3"),a=t("../utils/determineCrossOrigin"),h=t("bit-twiddle");i.prototype=Object.create(o.prototype),i.prototype.constructor=i,e.exports=i,i.prototype.update=function(){this.realWidth=this.source.naturalWidth||this.source.videoWidth||this.source.width,this.realHeight=this.source.naturalHeight||this.source.videoHeight||this.source.height,this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=h.isPow2(this.realWidth)&&h.isPow2(this.realHeight),this.emit("update",this)},i.prototype.loadSource=function(t){var e=this.isLoading;if(this.hasLoaded=!1,this.isLoading=!1,e&&this.source&&(this.source.onload=null,this.source.onerror=null),this.source=t,(this.source.complete||this.source.getContext)&&this.source.width&&this.source.height)this._sourceLoaded();else if(!t.getContext){this.isLoading=!0;var r=this;t.onload=function(){t.onload=null,t.onerror=null,r.isLoading&&(r.isLoading=!1,r._sourceLoaded(),r.emit("loaded",r))},t.onerror=function(){t.onload=null,t.onerror=null,r.isLoading&&(r.isLoading=!1,r.emit("error",r))},t.complete&&t.src&&(this.isLoading=!1,t.onload=null,t.onerror=null,t.width&&t.height?(this._sourceLoaded(),e&&this.emit("loaded",this)):e&&this.emit("error",this))}},i.prototype._sourceLoaded=function(){this.hasLoaded=!0,this.update()},i.prototype.destroy=function(){this.imageUrl?(delete n.BaseTextureCache[this.imageUrl],delete n.TextureCache[this.imageUrl],this.imageUrl=null,navigator.isCocoonJS||(this.source.src="")):this.source&&this.source._pixiId&&delete n.BaseTextureCache[this.source._pixiId],this.source=null,this.dispose()},i.prototype.dispose=function(){this.emit("dispose",this)},i.prototype.updateSourceImage=function(t){this.source.src=t,this.loadSource(this.source)},i.fromImage=function(t,e,r){var s=n.BaseTextureCache[t];if(!s){var o=new Image;void 0===e&&0!==t.indexOf("data:")&&(o.crossOrigin=a(t)),s=new i(o,r),s.imageUrl=t,o.src=t,n.BaseTextureCache[t]=s,s.resolution=n.getResolutionOfUrl(t)}return s},i.fromCanvas=function(t,e){t._pixiId||(t._pixiId="canvas_"+n.uid());var r=n.BaseTextureCache[t._pixiId];return r||(r=new i(t,e),n.BaseTextureCache[t._pixiId]=r),r}},{"../const":78,"../utils":151,"../utils/determineCrossOrigin":150,"bit-twiddle":30,eventemitter3:32}],143:[function(t,e,r){function i(t,e){if(this.legacyRenderer=null,!(t instanceof n)){var r=arguments[1],i=arguments[2],o=arguments[3]||0,a=arguments[4]||1;console.warn("v4 RenderTexture now expects a new BaseRenderTexture. Please use RenderTexture.create("+r+", "+i+")"),this.legacyRenderer=arguments[0],e=null,t=new n(r,i,o,a)}s.call(this,t,e),this.valid=!0,this._updateUvs()}var n=t("./BaseRenderTexture"),s=t("./Texture");i.prototype=Object.create(s.prototype),i.prototype.constructor=i,e.exports=i,i.prototype.resize=function(t,e,r){this.valid=t>0&&e>0,this._frame.width=this.orig.width=t,this._frame.height=this.orig.height=e,r||this.baseTexture.resize(t,e),this._updateUvs()},i.create=function(t,e,r,s){return new i(new n(t,e,r,s))}},{"./BaseRenderTexture":141,"./Texture":144}],144:[function(t,e,r){function i(t,e,r,n,s){if(a.call(this),this.noFrame=!1,e||(this.noFrame=!0,e=new h.Rectangle(0,0,1,1)),t instanceof i&&(t=t.baseTexture),this.baseTexture=t,this._frame=e,this.trim=n,this.valid=!1,this.requiresUpdate=!1,this._uvs=null,this.orig=r||e,this._rotate=+(s||0),s===!0)this._rotate=2;else if(this._rotate%2!==0)throw"attempt to use diamond-shaped UVs. If you are sure, set rotation manually";t.hasLoaded?(this.noFrame&&(e=new h.Rectangle(0,0,t.width,t.height),t.on("update",this.onBaseTextureUpdated,this)),this.frame=e):t.once("loaded",this.onBaseTextureLoaded,this),this._updateID=0}var n=t("./BaseTexture"),s=t("./VideoBaseTexture"),o=t("./TextureUvs"),a=t("eventemitter3"),h=t("../math"),u=t("../utils");i.prototype=Object.create(a.prototype),i.prototype.constructor=i,e.exports=i,Object.defineProperties(i.prototype,{frame:{get:function(){return this._frame},set:function(t){if(this._frame=t,this.noFrame=!1,t.x+t.width>this.baseTexture.width||t.y+t.height>this.baseTexture.height)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);this.valid=t&&t.width&&t.height&&this.baseTexture.hasLoaded,this.trim||this.rotate||(this.orig=t),this.valid&&this._updateUvs()}},rotate:{get:function(){return this._rotate},set:function(t){this._rotate=t,this.valid&&this._updateUvs()}},width:{get:function(){return this.orig?this.orig.width:0}},height:{get:function(){return this.orig?this.orig.height:0}}}),i.prototype.update=function(){this.baseTexture.update()},i.prototype.onBaseTextureLoaded=function(t){this._updateID++,this.noFrame?this.frame=new h.Rectangle(0,0,t.width,t.height):this.frame=this._frame,this.baseTexture.on("update",this.onBaseTextureUpdated,this),this.emit("update",this)},i.prototype.onBaseTextureUpdated=function(t){this._updateID++,this._frame.width=t.width,this._frame.height=t.height,this.emit("update",this)},i.prototype.destroy=function(t){this.baseTexture&&(t&&(u.TextureCache[this.baseTexture.imageUrl]&&delete u.TextureCache[this.baseTexture.imageUrl],this.baseTexture.destroy()),this.baseTexture.off("update",this.onBaseTextureUpdated,this),this.baseTexture.off("loaded",this.onBaseTextureLoaded,this),this.baseTexture=null),this._frame=null,this._uvs=null,this.trim=null,this.orig=null,this.valid=!1,this.off("dispose",this.dispose,this),this.off("update",this.update,this)},i.prototype.clone=function(){return new i(this.baseTexture,this.frame,this.orig,this.trim,this.rotate)},i.prototype._updateUvs=function(){this._uvs||(this._uvs=new o),this._uvs.set(this._frame,this.baseTexture,this.rotate),this._updateID++},i.fromImage=function(t,e,r){var s=u.TextureCache[t];return s||(s=new i(n.fromImage(t,e,r)),u.TextureCache[t]=s),s},i.fromFrame=function(t){var e=u.TextureCache[t];if(!e)throw new Error('The frameId "'+t+'" does not exist in the texture cache');return e},i.fromCanvas=function(t,e){return new i(n.fromCanvas(t,e))},i.fromVideo=function(t,e){return"string"==typeof t?i.fromVideoUrl(t,e):new i(s.fromVideo(t,e))},i.fromVideoUrl=function(t,e){return new i(s.fromUrl(t,e))},i.from=function(t){if("string"==typeof t){var e=u.TextureCache[t];if(!e){var r=null!==t.match(/\.(mp4|webm|ogg|h264|avi|mov)$/);return r?i.fromVideoUrl(t):i.fromImage(t)}return e}return t instanceof HTMLCanvasElement?i.fromCanvas(t):t instanceof HTMLVideoElement?i.fromVideo(t):t instanceof n?new i(n):t},i.addTextureToCache=function(t,e){u.TextureCache[e]=t},i.removeTextureFromCache=function(t){var e=u.TextureCache[t];return delete u.TextureCache[t],delete u.BaseTextureCache[t],e},i.EMPTY=new i(new n),i.EMPTY.destroy=function(){},i.EMPTY.on=function(){},i.EMPTY.once=function(){},i.EMPTY.emit=function(){}},{"../math":102,"../utils":151,"./BaseTexture":142,"./TextureUvs":145,"./VideoBaseTexture":146,eventemitter3:32}],145:[function(t,e,r){function i(){this.x0=0,this.y0=0,this.x1=1,this.y1=0,this.x2=1,this.y2=1,this.x3=0,this.y3=1,this.uvsUint32=new Uint32Array(4)}e.exports=i;var n=t("../math/GroupD8");i.prototype.set=function(t,e,r){var i=e.width,s=e.height;if(r){var o=t.width/2/i,a=t.height/2/s,h=t.x/i+o,u=t.y/s+a;r=n.add(r,n.NW),this.x0=h+o*n.uX(r),this.y0=u+a*n.uY(r),r=n.add(r,2),this.x1=h+o*n.uX(r),this.y1=u+a*n.uY(r),r=n.add(r,2),this.x2=h+o*n.uX(r),this.y2=u+a*n.uY(r),r=n.add(r,2),this.x3=h+o*n.uX(r),this.y3=u+a*n.uY(r)}else this.x0=t.x/i,this.y0=t.y/s,this.x1=(t.x+t.width)/i,this.y1=t.y/s,this.x2=(t.x+t.width)/i,this.y2=(t.y+t.height)/s,this.x3=t.x/i,this.y3=(t.y+t.height)/s;this.uvsUint32[0]=(65535*this.y0&65535)<<16|65535*this.x0&65535,this.uvsUint32[1]=(65535*this.y1&65535)<<16|65535*this.x1&65535,this.uvsUint32[2]=(65535*this.y2&65535)<<16|65535*this.x2&65535,this.uvsUint32[3]=(65535*this.y3&65535)<<16|65535*this.x3&65535}},{"../math/GroupD8":98}],146:[function(t,e,r){function i(t,e){if(!t)throw new Error("No video source element specified.");(t.readyState===t.HAVE_ENOUGH_DATA||t.readyState===t.HAVE_FUTURE_DATA)&&t.width&&t.height&&(t.complete=!0),s.call(this,t,e),this.autoUpdate=!1,this._onUpdate=this._onUpdate.bind(this),this._onCanPlay=this._onCanPlay.bind(this),t.complete||(t.addEventListener("canplay",this._onCanPlay),t.addEventListener("canplaythrough",this._onCanPlay),t.addEventListener("play",this._onPlayStart.bind(this)),t.addEventListener("pause",this._onPlayStop.bind(this))),this.__loaded=!1}function n(t,e){e||(e="video/"+t.substr(t.lastIndexOf(".")+1));var r=document.createElement("source");return r.src=t,r.type=e,r}var s=t("./BaseTexture"),o=t("../utils");i.prototype=Object.create(s.prototype),i.prototype.constructor=i,e.exports=i,i.prototype._onUpdate=function(){this.autoUpdate&&(window.requestAnimationFrame(this._onUpdate),this.update())},i.prototype._onPlayStart=function(){this.hasLoaded||this._onCanPlay(),this.autoUpdate||(window.requestAnimationFrame(this._onUpdate),this.autoUpdate=!0)},i.prototype._onPlayStop=function(){this.autoUpdate=!1},i.prototype._onCanPlay=function(){this.hasLoaded=!0,this.source&&(this.source.removeEventListener("canplay",this._onCanPlay),this.source.removeEventListener("canplaythrough",this._onCanPlay),this.width=this.source.videoWidth,this.height=this.source.videoHeight,this.source.play(),this.__loaded||(this.__loaded=!0,this.emit("loaded",this)))},i.prototype.destroy=function(){this.source&&this.source._pixiId&&(delete o.BaseTextureCache[this.source._pixiId],delete this.source._pixiId),s.prototype.destroy.call(this)},i.fromVideo=function(t,e){t._pixiId||(t._pixiId="video_"+o.uid());var r=o.BaseTextureCache[t._pixiId];return r||(r=new i(t,e),o.BaseTextureCache[t._pixiId]=r),r},i.fromUrl=function(t,e){var r=document.createElement("video");if(Array.isArray(t))for(var s=0;sthis.lastTime?(e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),this.deltaTime=e*n.TARGET_FPMS*this.speed,this._emitter.emit(o,this.deltaTime)):this.deltaTime=this.elapsedMS=0,this.lastTime=t},e.exports=i},{"../const":78,eventemitter3:32}],148:[function(t,e,r){var i=t("./Ticker"),n=new i;n.autoStart=!0,e.exports={shared:n,Ticker:i}},{"./Ticker":147}],149:[function(t,e,r){var i=function(t){for(var e=6*t,r=new Uint16Array(e),i=0,n=0;i>16&255)/255,e[1]=(t>>8&255)/255,e[2]=(255&t)/255,e},hex2string:function(t){return t=t.toString(16),t="000000".substr(0,6-t.length)+t,"#"+t},rgb2hex:function(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]},getResolutionOfUrl:function(t){var e=i.RETINA_PREFIX.exec(t);return e?parseFloat(e[1]):1},sayHello:function(t){if(!n._saidHello){if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var e=["\n %c %c %c Pixi.js "+i.VERSION+" - ✰ "+t+" ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n","background: #ff66a5; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff66a5; background: #030307; padding:5px 0;","background: #ff66a5; padding:5px 0;","background: #ffc3dc; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;"];window.console.log.apply(console,e)}else window.console&&window.console.log("Pixi.js "+i.VERSION+" - "+t+" - http://www.pixijs.com/");n._saidHello=!0}},isWebGLSupported:function(){var t={stencil:!0,failIfMajorPerformanceCaveat:!0};try{if(!window.WebGLRenderingContext)return!1;var e=document.createElement("canvas"),r=e.getContext("webgl",t)||e.getContext("experimental-webgl",t),i=!(!r||!r.getContextAttributes().stencil);if(r){var n=r.getExtension("WEBGL_lose_context");n&&n.loseContext()}return r=null,i}catch(t){return!1}},sign:function(t){return t?t<0?-1:1:0},removeItems:function(t,e,r){var i=t.length;if(!(e>=i||0===r)){r=e+r>i?i-e:r;for(var n=e,s=i-r;n1?this._fontStyle="italic":t.indexOf("oblique")>-1?this._fontStyle="oblique":this._fontStyle="normal",t.indexOf("small-caps")>-1?this._fontVariant="small-caps":this._fontVariant="normal";var e,r=t.split(" "),i=-1;for(this._fontSize=26,e=0;e-1&&i=0?t:16777215,this.dirty=!0}},align:{get:function(){return this._font.align},set:function(t){this._font.align=t||"left",this.dirty=!0}},anchor:{get:function(){return this._anchor},set:function(t){"number"==typeof t?this._anchor.set(t):this._anchor.copy(t)}},font:{get:function(){return this._font},set:function(t){t&&("string"==typeof t?(t=t.split(" "),this._font.name=1===t.length?t[0]:t.slice(1).join(" "),this._font.size=t.length>=2?parseInt(t[0],10):i.fonts[this._font.name].size):(this._font.name=t.name,this._font.size="number"==typeof t.size?t.size:parseInt(t.size,10)),this.dirty=!0)}},text:{get:function(){return this._text},set:function(t){t=t.toString()||" ",this._text!==t&&(this._text=t,this.dirty=!0)}}}),i.prototype.updateText=function(){for(var t=i.fonts[this._font.name],e=new n.Point,r=null,s=[],o=0,a=0,h=[],u=0,l=this._font.size/t.size,c=-1,d=0,p=0,f=0;f0&&e.x*l>this.maxWidth)n.utils.removeItems(s,c,f-c),f=c,c=-1,h.push(d),a=Math.max(a,d),u++,e.x=0,e.y+=t.lineHeight,r=null;else{var g=t.chars[v];g&&(r&&g.kerning[r]&&(e.x+=g.kerning[r]),s.push({texture:g.texture,line:u,charCode:v,position:new n.Point(e.x+g.xOffset,e.y+g.yOffset)}),o=e.x+(g.texture.width+g.xOffset),e.x+=g.xAdvance,p=Math.max(p,g.yOffset+g.texture.height),r=v)}}h.push(o),a=Math.max(a,o);var y=[];for(f=0;f<=u;f++){var x=0;"right"===this._font.align?x=a-h[f]:"center"===this._font.align&&(x=(a-h[f])/2),y.push(x)}var m=s.length,_=this.tint;for(f=0;f=this._durations[this.currentFrame];)r-=this._durations[this.currentFrame]*i,this._currentTime+=i;this._currentTime+=r/this._durations[this.currentFrame]}else this._currentTime+=e;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):(this._texture=this._textures[this.currentFrame],this._textureID=-1)},i.prototype.destroy=function(){this.stop(),n.Sprite.prototype.destroy.call(this)},i.fromFrames=function(t){for(var e=[],r=0;re?m:e,e=b>e?b:e,e=E>e?E:e,i=x,i=_>i?_:i,i=T>i?T:i,i=w>i?w:i;var S=this._bounds;return S.x=t,S.width=e-t,S.y=r,S.height=i-r,this._currentBounds=S,S},i.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,s);var e,r=this._width,i=this._height,n=-r*this.anchor.x;return s.x>n&&s.xe&&s.y=s&&(e=t-u-1),l=l.replace("%value%",r[e]),a+=l,a+="\n"}return o=o.replace("%blur%",a),o=o.replace("%size%",t)};e.exports=s},{}],170:[function(t,e,r){var i=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","uniform float strength;","uniform mat3 projectionMatrix;","varying vec2 vBlurTexCoords[%size%];","void main(void)","{","gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);","%blur%","}"].join("\n"),n=function(t,e){var r,n,s=Math.ceil(t/2),o=i,a="";r=e?"vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);":"vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);";for(var h=0;h=s&&(n=t-h-1),u=u.replace("%sampleIndex%",h-(s-1)+".0"),a+=u,a+="\n"}return o=o.replace("%blur%",a),o=o.replace("%size%",t)};e.exports=n},{}],171:[function(t,e,r){var i=function(t){for(var e=t.getParameter(t.MAX_VARYING_VECTORS),r=15;r>e;)r-=2;return r};e.exports=i},{}],172:[function(t,e,r){function i(){n.Filter.call(this,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","#define GLSLIFY 1\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\n\nvoid main(void)\n{\n\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n gl_FragColor.r = (m[0] * c.r);\n gl_FragColor.r += (m[1] * c.g);\n gl_FragColor.r += (m[2] * c.b);\n gl_FragColor.r += (m[3] * c.a);\n gl_FragColor.r += m[4] * c.a;\n\n gl_FragColor.g = (m[5] * c.r);\n gl_FragColor.g += (m[6] * c.g);\n gl_FragColor.g += (m[7] * c.b);\n gl_FragColor.g += (m[8] * c.a);\n gl_FragColor.g += m[9] * c.a;\n\n gl_FragColor.b = (m[10] * c.r);\n gl_FragColor.b += (m[11] * c.g);\n gl_FragColor.b += (m[12] * c.b);\n gl_FragColor.b += (m[13] * c.a);\n gl_FragColor.b += m[14] * c.a;\n\n gl_FragColor.a = (m[15] * c.r);\n gl_FragColor.a += (m[16] * c.g);\n gl_FragColor.a += (m[17] * c.b);\n gl_FragColor.a += (m[18] * c.a);\n gl_FragColor.a += m[19] * c.a;\n\n// gl_FragColor = vec4(m[0]);\n}\n"),this.uniforms.m=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0]}var n=t("../../core");i.prototype=Object.create(n.Filter.prototype),i.prototype.constructor=i,e.exports=i,i.prototype._loadMatrix=function(t,e){e=!!e;var r=t;e&&(this._multiply(r,this.uniforms.m,t),r=this._colorMatrix(r)),this.uniforms.m=r},i.prototype._multiply=function(t,e,r){return t[0]=e[0]*r[0]+e[1]*r[5]+e[2]*r[10]+e[3]*r[15],t[1]=e[0]*r[1]+e[1]*r[6]+e[2]*r[11]+e[3]*r[16],t[2]=e[0]*r[2]+e[1]*r[7]+e[2]*r[12]+e[3]*r[17],t[3]=e[0]*r[3]+e[1]*r[8]+e[2]*r[13]+e[3]*r[18],t[4]=e[0]*r[4]+e[1]*r[9]+e[2]*r[14]+e[3]*r[19],t[5]=e[5]*r[0]+e[6]*r[5]+e[7]*r[10]+e[8]*r[15],t[6]=e[5]*r[1]+e[6]*r[6]+e[7]*r[11]+e[8]*r[16],t[7]=e[5]*r[2]+e[6]*r[7]+e[7]*r[12]+e[8]*r[17],t[8]=e[5]*r[3]+e[6]*r[8]+e[7]*r[13]+e[8]*r[18],t[9]=e[5]*r[4]+e[6]*r[9]+e[7]*r[14]+e[8]*r[19],t[10]=e[10]*r[0]+e[11]*r[5]+e[12]*r[10]+e[13]*r[15],t[11]=e[10]*r[1]+e[11]*r[6]+e[12]*r[11]+e[13]*r[16],t[12]=e[10]*r[2]+e[11]*r[7]+e[12]*r[12]+e[13]*r[17],t[13]=e[10]*r[3]+e[11]*r[8]+e[12]*r[13]+e[13]*r[18],t[14]=e[10]*r[4]+e[11]*r[9]+e[12]*r[14]+e[13]*r[19],t[15]=e[15]*r[0]+e[16]*r[5]+e[17]*r[10]+e[18]*r[15],t[16]=e[15]*r[1]+e[16]*r[6]+e[17]*r[11]+e[18]*r[16],t[17]=e[15]*r[2]+e[16]*r[7]+e[17]*r[12]+e[18]*r[17],t[18]=e[15]*r[3]+e[16]*r[8]+e[17]*r[13]+e[18]*r[18],t[19]=e[15]*r[4]+e[16]*r[9]+e[17]*r[14]+e[18]*r[19],t},i.prototype._colorMatrix=function(t){var e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e},i.prototype.brightness=function(t,e){var r=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},i.prototype.greyscale=function(t,e){var r=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},i.prototype.grayscale=i.prototype.greyscale,i.prototype.blackAndWhite=function(t){var e=[.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.hue=function(t,e){t=(t||0)/180*Math.PI;var r=Math.cos(t),i=Math.sin(t),n=Math.sqrt,s=1/3,o=n(s),a=r+(1-r)*s,h=s*(1-r)-o*i,u=s*(1-r)+o*i,l=s*(1-r)+o*i,c=r+s*(1-r),d=s*(1-r)-o*i,p=s*(1-r)-o*i,f=s*(1-r)+o*i,v=r+s*(1-r),g=[a,h,u,0,0,l,c,d,0,0,p,f,v,0,0,0,0,0,1,0];this._loadMatrix(g,e)},i.prototype.contrast=function(t,e){var r=(t||0)+1,i=-128*(r-1),n=[r,0,0,0,i,0,r,0,0,i,0,0,r,0,i,0,0,0,1,0];this._loadMatrix(n,e)},i.prototype.saturate=function(t,e){var r=2*(t||0)/3+1,i=(r-1)*-.5,n=[r,i,i,0,0,i,r,i,0,0,i,i,r,0,0,0,0,0,1,0];this._loadMatrix(n,e)},i.prototype.desaturate=function(){this.saturate(-1)},i.prototype.negative=function(t){var e=[0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.sepia=function(t){var e=[.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.technicolor=function(t){var e=[1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.polaroid=function(t){var e=[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.toBGR=function(t){var e=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.kodachrome=function(t){var e=[1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.browni=function(t){var e=[.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.vintage=function(t){var e=[.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.colorTone=function(t,e,r,i,n){t=t||.2,e=e||.15,r=r||16770432,i=i||3375104;var s=(r>>16&255)/255,o=(r>>8&255)/255,a=(255&r)/255,h=(i>>16&255)/255,u=(i>>8&255)/255,l=(255&i)/255,c=[.3,.59,.11,0,0,s,o,a,t,0,h,u,l,e,0,s-h,o-u,a-l,0,0];this._loadMatrix(c,n)},i.prototype.night=function(t,e){t=t||.1;var r=[t*-2,-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},i.prototype.predator=function(t,e){var r=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(r,e)},i.prototype.lsd=function(t){var e=[2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.reset=function(){var t=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(t,!1)},Object.defineProperties(i.prototype,{matrix:{get:function(){return this.uniforms.m},set:function(t){this.uniforms.m=t}}})},{"../../core":97}],173:[function(t,e,r){function i(t,e){var r=new n.Matrix;t.renderable=!1,n.Filter.call(this,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}","#define GLSLIFY 1\nvarying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n"),this.maskSprite=t,this.maskMatrix=r,this.uniforms.mapSampler=t.texture,this.uniforms.filterMatrix=r.toArray(!0),this.uniforms.scale={x:1,y:1},null!==e&&void 0!==e||(e=20),this.scale=new n.Point(e,e)}var n=t("../../core");i.prototype=Object.create(n.Filter.prototype),i.prototype.constructor=i,e.exports=i,i.prototype.apply=function(t,e,r){var i=1/r.destinationFrame.width*(r.size.width/e.size.width);this.uniforms.filterMatrix=t.calculateSpriteMatrix(this.maskMatrix,this.maskSprite),this.uniforms.scale.x=this.scale.x*i,this.uniforms.scale.y=this.scale.y*i,t.applyFilter(this,e,r)},Object.defineProperties(i.prototype,{map:{get:function(){return this.uniforms.mapSampler},set:function(t){this.uniforms.mapSampler=t}}})},{"../../core":97}],174:[function(t,e,r){function i(){n.Filter.call(this,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}",'#define GLSLIFY 1\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n \tvec2 fragCoord = vTextureCoord * filterArea.xy;\n\n \tvec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n \tgl_FragColor = color;\n}\n'); +}var n=t("../../core");i.prototype=Object.create(n.Filter.prototype),i.prototype.constructor=i,e.exports=i},{"../../core":97}],175:[function(t,e,r){e.exports={FXAAFilter:t("./fxaa/FXAAFilter"),NoiseFilter:t("./noise/NoiseFilter"),DisplacementFilter:t("./displacement/DisplacementFilter"),BlurFilter:t("./blur/BlurFilter"),BlurXFilter:t("./blur/BlurXFilter"),BlurYFilter:t("./blur/BlurYFilter"),ColorMatrixFilter:t("./colormatrix/ColorMatrixFilter"),VoidFilter:t("./void/VoidFilter")}},{"./blur/BlurFilter":166,"./blur/BlurXFilter":167,"./blur/BlurYFilter":168,"./colormatrix/ColorMatrixFilter":172,"./displacement/DisplacementFilter":173,"./fxaa/FXAAFilter":174,"./noise/NoiseFilter":176,"./void/VoidFilter":177}],176:[function(t,e,r){function i(){n.Filter.call(this,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","precision highp float;\n#define GLSLIFY 1\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float noise;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n float diff = (rand(gl_FragCoord.xy) - 0.5) * noise;\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n gl_FragColor = color;\n}\n"),this.noise=.5}var n=t("../../core");i.prototype=Object.create(n.Filter.prototype),i.prototype.constructor=i,e.exports=i,Object.defineProperties(i.prototype,{noise:{get:function(){return this.uniforms.noise},set:function(t){this.uniforms.noise=t}}})},{"../../core":97}],177:[function(t,e,r){function i(){n.Filter.call(this,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"),this.glShaderKey="void"}var n=t("../../core");i.prototype=Object.create(n.Filter.prototype),i.prototype.constructor=i,e.exports=i},{"../../core":97}],178:[function(t,e,r){function i(){this.global=new n.Point,this.target=null,this.originalEvent=null}var n=t("../core");i.prototype.constructor=i,e.exports=i,i.prototype.getLocalPosition=function(t,e,r){return t.worldTransform.applyInverse(r||this.global,e)}},{"../core":97}],179:[function(t,e,r){function i(t,e){o.call(this),e=e||{},this.renderer=t,this.autoPreventDefault=void 0===e.autoPreventDefault||e.autoPreventDefault,this.interactionFrequency=e.interactionFrequency||10,this.mouse=new s,this.mouse.global.set(-999999),this.eventData={stopped:!1,target:null,type:null,data:this.mouse,stopPropagation:function(){this.stopped=!0}},this.interactiveDataPool=[],this.interactionDOMElement=null,this.moveWhenInside=!1,this.eventsAdded=!1,this.onMouseUp=this.onMouseUp.bind(this),this.processMouseUp=this.processMouseUp.bind(this),this.onMouseDown=this.onMouseDown.bind(this),this.processMouseDown=this.processMouseDown.bind(this),this.onMouseMove=this.onMouseMove.bind(this),this.processMouseMove=this.processMouseMove.bind(this),this.onMouseOut=this.onMouseOut.bind(this),this.processMouseOverOut=this.processMouseOverOut.bind(this),this.onMouseOver=this.onMouseOver.bind(this),this.onTouchStart=this.onTouchStart.bind(this),this.processTouchStart=this.processTouchStart.bind(this),this.onTouchEnd=this.onTouchEnd.bind(this),this.processTouchEnd=this.processTouchEnd.bind(this),this.onTouchMove=this.onTouchMove.bind(this),this.processTouchMove=this.processTouchMove.bind(this),this.defaultCursorStyle="inherit",this.currentCursorStyle="inherit",this._tempPoint=new n.Point,this.resolution=1,this.setTargetElement(this.renderer.view,this.renderer.resolution)}var n=t("../core"),s=t("./InteractionData"),o=t("eventemitter3");Object.assign(n.DisplayObject.prototype,t("./interactiveTarget")),i.prototype=Object.create(o.prototype),i.prototype.constructor=i,e.exports=i,i.prototype.setTargetElement=function(t,e){this.removeEvents(),this.interactionDOMElement=t,this.resolution=e||1,this.addEvents()},i.prototype.addEvents=function(){this.interactionDOMElement&&(n.ticker.shared.add(this.update,this),window.navigator.msPointerEnabled&&(this.interactionDOMElement.style["-ms-content-zooming"]="none",this.interactionDOMElement.style["-ms-touch-action"]="none"),window.document.addEventListener("mousemove",this.onMouseMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onMouseDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onMouseOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onMouseOver,!0),this.interactionDOMElement.addEventListener("touchstart",this.onTouchStart,!0),this.interactionDOMElement.addEventListener("touchend",this.onTouchEnd,!0),this.interactionDOMElement.addEventListener("touchmove",this.onTouchMove,!0),window.addEventListener("mouseup",this.onMouseUp,!0),this.eventsAdded=!0)},i.prototype.removeEvents=function(){this.interactionDOMElement&&(n.ticker.shared.remove(this.update),window.navigator.msPointerEnabled&&(this.interactionDOMElement.style["-ms-content-zooming"]="",this.interactionDOMElement.style["-ms-touch-action"]=""),window.document.removeEventListener("mousemove",this.onMouseMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onMouseDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onMouseOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onMouseOver,!0),this.interactionDOMElement.removeEventListener("touchstart",this.onTouchStart,!0),this.interactionDOMElement.removeEventListener("touchend",this.onTouchEnd,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onTouchMove,!0),this.interactionDOMElement=null,window.removeEventListener("mouseup",this.onMouseUp,!0),this.eventsAdded=!1)},i.prototype.update=function(t){if(this._deltaTime+=t,!(this._deltaTime=0;h--){var u=a[h];if(this.processInteractive(t,u,r,i,o)){if(!u.parent)continue;s=!0,o=!1,i=!1}}return n&&(i&&!s&&(e.hitArea?(e.worldTransform.applyInverse(t,this._tempPoint),s=e.hitArea.contains(this._tempPoint.x,this._tempPoint.y)):e.containsPoint&&(s=e.containsPoint(t))),e.interactive&&r(e,s)),s},i.prototype.onMouseDown=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData.stopped=!1,this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.autoPreventDefault&&this.mouse.originalEvent.preventDefault(),this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseDown,!0);var e=2===t.button||3===t.which;this.emit(e?"rightdown":"mousedown",this.eventData)},i.prototype.processMouseDown=function(t,e){var r=this.mouse.originalEvent,i=2===r.button||3===r.which;e&&(t[i?"_isRightDown":"_isLeftDown"]=!0,this.dispatchEvent(t,i?"rightdown":"mousedown",this.eventData))},i.prototype.onMouseUp=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData.stopped=!1,this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseUp,!0);var e=2===t.button||3===t.which;this.emit(e?"rightup":"mouseup",this.eventData)},i.prototype.processMouseUp=function(t,e){var r=this.mouse.originalEvent,i=2===r.button||3===r.which,n=i?"_isRightDown":"_isLeftDown";e?(this.dispatchEvent(t,i?"rightup":"mouseup",this.eventData),t[n]&&(t[n]=!1,this.dispatchEvent(t,i?"rightclick":"click",this.eventData))):t[n]&&(t[n]=!1,this.dispatchEvent(t,i?"rightupoutside":"mouseupoutside",this.eventData))},i.prototype.onMouseMove=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData.stopped=!1,this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.didMove=!0,this.cursor=this.defaultCursorStyle,this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseMove,!0),this.emit("mousemove",this.eventData),this.currentCursorStyle!==this.cursor&&(this.currentCursorStyle=this.cursor,this.interactionDOMElement.style.cursor=this.cursor)},i.prototype.processMouseMove=function(t,e){this.processMouseOverOut(t,e),this.moveWhenInside&&!e||this.dispatchEvent(t,"mousemove",this.eventData)},i.prototype.onMouseOut=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData.stopped=!1,this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.interactionDOMElement.style.cursor=this.defaultCursorStyle,this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseOverOut,!1),this.emit("mouseout",this.eventData)},i.prototype.processMouseOverOut=function(t,e){e?(t._over||(t._over=!0,this.dispatchEvent(t,"mouseover",this.eventData)),t.buttonMode&&(this.cursor=t.defaultCursor)):t._over&&(t._over=!1,this.dispatchEvent(t,"mouseout",this.eventData))},i.prototype.onMouseOver=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData.stopped=!1,this.emit("mouseover",this.eventData)},i.prototype.onTouchStart=function(t){this.autoPreventDefault&&t.preventDefault();for(var e=t.changedTouches,r=e.length,i=0;i0){var T=this.canvasPadding/this.worldTransform.a,E=this.canvasPadding/this.worldTransform.d,w=(l+c+d)/3,S=(p+f+v)/3,C=l-w,M=p-S,R=Math.sqrt(C*C+M*M);l=w+C/R*(R+T),p=S+M/R*(R+E),C=c-w,M=f-S,R=Math.sqrt(C*C+M*M),c=w+C/R*(R+T),f=S+M/R*(R+E),C=d-w,M=v-S,R=Math.sqrt(C*C+M*M),d=w+C/R*(R+T),v=S+M/R*(R+E)}t.save(),t.beginPath(),t.moveTo(l,p),t.lineTo(c,f),t.lineTo(d,v),t.closePath(),t.clip();var A=g*_+m*x+y*b-_*x-m*y-g*b,O=l*_+m*d+c*b-_*d-m*c-l*b,D=g*c+l*x+y*d-c*x-l*y-g*d,P=g*_*d+m*c*x+l*y*b-l*_*x-m*y*d-g*c*b,I=p*_+m*v+f*b-_*v-m*f-p*b,L=g*f+p*x+y*v-f*x-p*y-g*v,F=g*_*v+m*f*x+p*y*b-p*_*x-m*y*v-g*f*b;t.transform(O/A,I/A,D/A,L/A,P/A,F/A),t.drawImage(a,0,0,h*o.resolution,u*o.resolution,0,0,h,u),t.restore()},i.prototype.renderMeshFlat=function(t){var e=this.context,r=t.vertices,i=r.length/2;e.beginPath();for(var n=1;n1&&(n=1),s=Math.sqrt(h*h+u*u),o=this._texture.height/2,h/=s,u/=s,h*=o,u*=o,l[i]=r.x+h,l[i+1]=r.y+u,l[i+2]=r.x-h,l[i+3]=r.y-u,a=r;this.containerUpdateTransform()}}},{"../core":97,"./Mesh":187}],191:[function(t,e,r){e.exports={Mesh:t("./Mesh"),Plane:t("./Plane"),NineSlicePlane:t("./NineSlicePlane"),Rope:t("./Rope"),MeshShader:t("./webgl/MeshShader")}},{"./Mesh":187,"./NineSlicePlane":188,"./Plane":189,"./Rope":190,"./webgl/MeshShader":192}],192:[function(t,e,r){function i(t){n.call(this,t,["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","varying vec2 vTextureCoord;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vTextureCoord = aTextureCoord;","}"].join("\n"),["varying vec2 vTextureCoord;","uniform float alpha;","uniform vec3 tint;","uniform sampler2D uSampler;","void main(void){"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vec4(tint * alpha, alpha);","}"].join("\n"))}var n=t("../../core/Shader");i.prototype=Object.create(n.prototype),i.prototype.constructor=i,e.exports=i},{"../../core/Shader":77}],193:[function(t,e,r){function i(t,e,r){n.Container.call(this),r=r||15e3,t=t||15e3;var i=16384;r>i&&(r=i),r>t&&(r=t),this._properties=[!1,!0,!1,!1,!1],this._maxSize=t,this._batchSize=r,this._glBuffers=[],this._bufferToUpdate=0,this.interactiveChildren=!1,this.blendMode=n.BLEND_MODES.NORMAL,this.roundPixels=!0,this.baseTexture=null,this.setProperties(e)}var n=t("../core");i.prototype=Object.create(n.Container.prototype),i.prototype.constructor=i,e.exports=i,i.prototype.setProperties=function(t){t&&(this._properties[0]="scale"in t?!!t.scale:this._properties[0],this._properties[1]="position"in t?!!t.position:this._properties[1],this._properties[2]="rotation"in t?!!t.rotation:this._properties[2],this._properties[3]="uvs"in t?!!t.uvs:this._properties[3],this._properties[4]="alpha"in t?!!t.alpha:this._properties[4])},i.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},i.prototype.renderWebGL=function(t){this.visible&&!(this.worldAlpha<=0)&&this.children.length&&this.renderable&&(this.baseTexture||(this.baseTexture=this.children[0]._texture.baseTexture,this.baseTexture.hasLoaded||this.baseTexture.once("update",function(){this.onChildrenChange(0)},this)),t.setObjectRenderer(t.plugins.particle),t.plugins.particle.render(this))},i.prototype.onChildrenChange=function(t){var e=Math.floor(t/this._batchSize);ei&&(r=i);var s=t._glBuffers[this.renderer.CONTEXT_UID];s||(s=t._glBuffers[this.renderer.CONTEXT_UID]=this.generateBuffers(t)),this.renderer.setBlendMode(t.blendMode);var o=this.renderer.gl,a=t.worldTransform.copy(this.tempMatrix);a.prepend(this.renderer._activeRenderTarget.projectionMatrix),this.shader.uniforms.projectionMatrix=a.toArray(!0),this.shader.uniforms.uAlpha=t.worldAlpha;var h=e[0]._texture.baseTexture;this.renderer.bindTexture(h);for(var u=0,l=0;un&&(c=n);var d=s[l];d.uploadDynamic(e,u,c),t._bufferToUpdate===l&&(d.uploadStatic(e,u,c),t._bufferToUpdate=l+1),d.vao.bind().draw(o.TRIANGLES,6*c).unbind()}}},i.prototype.generateBuffers=function(t){var e,r=this.renderer.gl,i=[],n=t._maxSize,s=t._batchSize,a=t._properties;for(e=0;e0?1:-1})},{}],199:[function(t,e,r){Object.assign||(Object.assign=t("object-assign"))},{"object-assign":59}],200:[function(t,e,r){t("./Object.assign"),t("./requestAnimationFrame"),t("./Math.sign"),window.ArrayBuffer||(window.ArrayBuffer=Array),window.Float32Array||(window.Float32Array=Array),window.Uint32Array||(window.Uint32Array=Array),window.Uint16Array||(window.Uint16Array=Array)},{"./Math.sign":198,"./Object.assign":199,"./requestAnimationFrame":201}],201:[function(t,e,r){(function(t){if(Date.now&&Date.prototype.getTime||(Date.now=function(){return(new Date).getTime()}),!t.performance||!t.performance.now){var e=Date.now();t.performance||(t.performance={}),t.performance.now=function(){return Date.now()-e}}for(var r=Date.now(),i=["ms","moz","webkit","o"],n=0;n0;){var r=this.queue[0],n=!1;for(t=0,e=this.uploadHooks.length;t=0;e--)this.add(t.children[e]);return this},i.prototype.destroy=function(){this.ticking&&u.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null},h.WebGLRenderer.registerPlugin("prepare",i)},{"../../core":97}],205:[function(t,e,r){(function(r){t("./polyfill");var i=e.exports=t("./core");i.extras=t("./extras"),i.filters=t("./filters"),i.interaction=t("./interaction"),i.loaders=t("./loaders"),i.mesh=t("./mesh"),i.particles=t("./particles"),i.accessibility=t("./accessibility"),i.extract=t("./extract"),i.prepare=t("./prepare"),i.loader=new i.loaders.Loader,Object.assign(i,t("./deprecation")),r.PIXI=i}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./accessibility":76,"./core":97,"./deprecation":154,"./extract":156,"./extras":164,"./filters":175,"./interaction":180,"./loaders":183,"./mesh":191,"./particles":194,"./polyfill":200,"./prepare":203}]},{},[205])(205)}); +//# sourceMappingURL=pixi.min.js.map diff --git a/js/pixi/4.0.3-tiling/pixi.js b/js/pixi/4.0.3-tiling/pixi.js new file mode 100644 index 0000000..ca96246 --- /dev/null +++ b/js/pixi/4.0.3-tiling/pixi.js @@ -0,0 +1,36400 @@ +/*! + * pixi.js - v4.0.3 + * Compiled Mon Oct 03 2016 02:32:45 GMT+0300 (RTZ 2 (зима)) + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.PIXI = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],15:[function(require,module,exports){ +'use strict'; + +module.exports = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, size), + maxZ = zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, size); + earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and size of the data bounding box +function zOrder(x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; + +},{}],16:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty; + +// +// We store our EE objects in a plain object whose properties are event names. +// If `Object.create(null)` is not supported we prefix the event names with a +// `~` to make sure that the built-in object properties are not overridden or +// used as an attack vector. +// We also assume that `Object.create(null)` is available when the event name +// is an ES6 Symbol. +// +var prefix = typeof Object.create !== 'function' ? '~' : false; + +/** + * Representation of a single EventEmitter function. + * + * @param {Function} fn Event handler to be called. + * @param {Mixed} context Context for function execution. + * @param {Boolean} [once=false] Only emit once + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal EventEmitter interface that is molded against the Node.js + * EventEmitter interface. + * + * @constructor + * @api public + */ +function EventEmitter() { /* Nothing to set */ } + +/** + * Hold the assigned EventEmitters by name. + * + * @type {Object} + * @private + */ +EventEmitter.prototype._events = undefined; + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @api public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var events = this._events + , names = [] + , name; + + if (!events) return names; + + for (name in events) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return a list of assigned event listeners. + * + * @param {String} event The events that should be listed. + * @param {Boolean} exists We only need to know if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events && this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Emit an event to all registered event listeners. + * + * @param {String} event The name of the event. + * @returns {Boolean} Indication if we've emitted an event. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events || !this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if ('function' === typeof listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Register a new EventListener for the given event. + * + * @param {String} event Name of the event. + * @param {Function} fn Callback function. + * @param {Mixed} [context=this] The context of the function. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events) this._events = prefix ? {} : Object.create(null); + if (!this._events[evt]) this._events[evt] = listener; + else { + if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [ + this._events[evt], listener + ]; + } + + return this; +}; + +/** + * Add an EventListener that's only called once. + * + * @param {String} event Name of the event. + * @param {Function} fn Callback function. + * @param {Mixed} [context=this] The context of the function. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events) this._events = prefix ? {} : Object.create(null); + if (!this._events[evt]) this._events[evt] = listener; + else { + if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [ + this._events[evt], listener + ]; + } + + return this; +}; + +/** + * Remove event listeners. + * + * @param {String} event The event we want to remove. + * @param {Function} fn The listener that we need to find. + * @param {Mixed} context Only remove listeners matching this context. + * @param {Boolean} once Only remove once listeners. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events || !this._events[evt]) return this; + + var listeners = this._events[evt] + , events = []; + + if (fn) { + if (listeners.fn) { + if ( + listeners.fn !== fn + || (once && !listeners.once) + || (context && listeners.context !== context) + ) { + events.push(listeners); + } + } else { + for (var i = 0, length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) { + this._events[evt] = events.length === 1 ? events[0] : events; + } else { + delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners or only the listeners for the specified event. + * + * @param {String} event The event want to remove all listeners for. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + if (!this._events) return this; + + if (event) delete this._events[prefix ? prefix + event : event]; + else this._events = prefix ? {} : Object.create(null); + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],17:[function(require,module,exports){ +/** + * isMobile.js v0.4.0 + * + * A simple library to detect Apple phones and tablets, + * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone), + * and any kind of seven inch device, via user agent sniffing. + * + * @author: Kai Mallea (kmallea@gmail.com) + * + * @license: http://creativecommons.org/publicdomain/zero/1.0/ + */ +(function (global) { + + var apple_phone = /iPhone/i, + apple_ipod = /iPod/i, + apple_tablet = /iPad/i, + android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i, // Match 'Android' AND 'Mobile' + android_tablet = /Android/i, + amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i, + amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i, + windows_phone = /IEMobile/i, + windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i, // Match 'Windows' AND 'ARM' + other_blackberry = /BlackBerry/i, + other_blackberry_10 = /BB10/i, + other_opera = /Opera Mini/i, + other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i, + other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i, // Match 'Firefox' AND 'Mobile' + seven_inch = new RegExp( + '(?:' + // Non-capturing group + + 'Nexus 7' + // Nexus 7 + + '|' + // OR + + 'BNTV250' + // B&N Nook Tablet 7 inch + + '|' + // OR + + 'Kindle Fire' + // Kindle Fire + + '|' + // OR + + 'Silk' + // Kindle Fire, Silk Accelerated + + '|' + // OR + + 'GT-P1000' + // Galaxy Tab 7 inch + + ')', // End non-capturing group + + 'i'); // Case-insensitive matching + + var match = function(regex, userAgent) { + return regex.test(userAgent); + }; + + var IsMobileClass = function(userAgent) { + var ua = userAgent || navigator.userAgent; + + // Facebook mobile app's integrated browser adds a bunch of strings that + // match everything. Strip it out if it exists. + var tmp = ua.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + // Twitter mobile app's integrated browser on iPad adds a "Twitter for + // iPhone" string. Same probable happens on other tablet platforms. + // This will confuse detection so strip it out if it exists. + tmp = ua.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + this.apple = { + phone: match(apple_phone, ua), + ipod: match(apple_ipod, ua), + tablet: !match(apple_phone, ua) && match(apple_tablet, ua), + device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua) + }; + this.amazon = { + phone: match(amazon_phone, ua), + tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) + }; + this.android = { + phone: match(amazon_phone, ua) || match(android_phone, ua), + tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua) + }; + this.windows = { + phone: match(windows_phone, ua), + tablet: match(windows_tablet, ua), + device: match(windows_phone, ua) || match(windows_tablet, ua) + }; + this.other = { + blackberry: match(other_blackberry, ua), + blackberry10: match(other_blackberry_10, ua), + opera: match(other_opera, ua), + firefox: match(other_firefox, ua), + chrome: match(other_chrome, ua), + device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua) + }; + this.seven_inch = match(seven_inch, ua); + this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch; + + // excludes 'other' devices and ipods, targeting touchscreen phones + this.phone = this.apple.phone || this.android.phone || this.windows.phone; + + // excludes 7 inch devices, classifying as phone or tablet is left to the user + this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet; + + if (typeof window === 'undefined') { + return this; + } + }; + + var instantiate = function() { + var IM = new IsMobileClass(); + IM.Class = IsMobileClass; + return IM; + }; + + if (typeof module !== 'undefined' && module.exports && typeof window === 'undefined') { + //node + module.exports = IsMobileClass; + } else if (typeof module !== 'undefined' && module.exports && typeof window !== 'undefined') { + //browserify + module.exports = instantiate(); + } else if (typeof define === 'function' && define.amd) { + //AMD + define('isMobile', [], global.isMobile = instantiate()); + } else { + global.isMobile = instantiate(); + } + +})(this); + +},{}],18:[function(require,module,exports){ +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} + +module.exports = apply; + +},{}],19:[function(require,module,exports){ +/** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ +function arrayEach(array, iteratee) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; +} + +module.exports = arrayEach; + +},{}],20:[function(require,module,exports){ +var baseTimes = require('./_baseTimes'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isIndex = require('./_isIndex'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; + + var length = result.length, + skipIndexes = !!length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); + } + } + return result; +} + +module.exports = arrayLikeKeys; + +},{"./_baseTimes":23,"./_isIndex":24,"./isArguments":28,"./isArray":29}],21:[function(require,module,exports){ +var isPrototype = require('./_isPrototype'), + nativeKeys = require('./_nativeKeys'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +module.exports = baseKeys; + +},{"./_isPrototype":25,"./_nativeKeys":26}],22:[function(require,module,exports){ +var apply = require('./_apply'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; +} + +module.exports = baseRest; + +},{"./_apply":18}],23:[function(require,module,exports){ +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +module.exports = baseTimes; + +},{}],24:[function(require,module,exports){ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} + +module.exports = isIndex; + +},{}],25:[function(require,module,exports){ +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +module.exports = isPrototype; + +},{}],26:[function(require,module,exports){ +var overArg = require('./_overArg'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object); + +module.exports = nativeKeys; + +},{"./_overArg":27}],27:[function(require,module,exports){ +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +module.exports = overArg; + +},{}],28:[function(require,module,exports){ +var isArrayLikeObject = require('./isArrayLikeObject'); + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} + +module.exports = isArguments; + +},{"./isArrayLikeObject":31}],29:[function(require,module,exports){ +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +module.exports = isArray; + +},{}],30:[function(require,module,exports){ +var isFunction = require('./isFunction'), + isLength = require('./isLength'); + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +module.exports = isArrayLike; + +},{"./isFunction":32,"./isLength":33}],31:[function(require,module,exports){ +var isArrayLike = require('./isArrayLike'), + isObjectLike = require('./isObjectLike'); + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +module.exports = isArrayLikeObject; + +},{"./isArrayLike":30,"./isObjectLike":35}],32:[function(require,module,exports){ +var isObject = require('./isObject'); + +/** `Object#toString` result references. */ +var funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} + +module.exports = isFunction; + +},{"./isObject":34}],33:[function(require,module,exports){ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +module.exports = isLength; + +},{}],34:[function(require,module,exports){ +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +module.exports = isObject; + +},{}],35:[function(require,module,exports){ +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +module.exports = isObjectLike; + +},{}],36:[function(require,module,exports){ +var isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +module.exports = isSymbol; + +},{"./isObjectLike":35}],37:[function(require,module,exports){ +var arrayLikeKeys = require('./_arrayLikeKeys'), + baseKeys = require('./_baseKeys'), + isArrayLike = require('./isArrayLike'); + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +module.exports = keys; + +},{"./_arrayLikeKeys":20,"./_baseKeys":21,"./isArrayLike":30}],38:[function(require,module,exports){ +/** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ +function noop() { + // No operation performed. +} + +module.exports = noop; + +},{}],39:[function(require,module,exports){ +var baseRest = require('./_baseRest'), + toInteger = require('./toInteger'); + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ +function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); +} + +module.exports = rest; + +},{"./_baseRest":22,"./toInteger":41}],40:[function(require,module,exports){ +var toNumber = require('./toNumber'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308; + +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} + +module.exports = toFinite; + +},{"./toNumber":42}],41:[function(require,module,exports){ +var toFinite = require('./toFinite'); + +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; +} + +module.exports = toInteger; + +},{"./toFinite":40}],42:[function(require,module,exports){ +var isObject = require('./isObject'), + isSymbol = require('./isSymbol'); + +/** Used as references for various `Number` constants. */ +var NAN = 0 / 0; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +module.exports = toNumber; + +},{"./isObject":34,"./isSymbol":36}],43:[function(require,module,exports){ +'use strict'; +/* eslint-disable no-unused-vars */ +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (e) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (Object.getOwnPropertySymbols) { + symbols = Object.getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],44:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) + +},{"_process":61}],45:[function(require,module,exports){ +var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); + +/** + * Helper class to create a webGL buffer + * + * @class + * @memberof pixi.gl + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ +var Buffer = function(gl, type, data, drawType) +{ + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The WebGL buffer, created upon instantiation + * + * @member {WebGLBuffer} + */ + this.buffer = gl.createBuffer(); + + /** + * The type of the buffer + * + * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} + */ + this.type = type || gl.ARRAY_BUFFER; + + /** + * The draw type of the buffer + * + * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ + this.drawType = drawType || gl.STATIC_DRAW; + + /** + * The data in the buffer, as a typed array + * + * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} + */ + this.data = EMPTY_ARRAY_BUFFER; + + if(data) + { + this.upload(data); + } +}; + +/** + * Uploads the buffer to the GPU + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload + * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract + * @param dontBind {Boolean} whether to bind the buffer before uploading it + */ +Buffer.prototype.upload = function(data, offset, dontBind) +{ + // todo - needed? + if(!dontBind) this.bind(); + + var gl = this.gl; + + data = data || this.data; + offset = offset || 0; + + if(this.data.byteLength >= data.byteLength) + { + gl.bufferSubData(this.type, offset, data); + } + else + { + gl.bufferData(this.type, data, this.drawType); + } + + this.data = data; +}; +/** + * Binds the buffer + * + */ +Buffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindBuffer(this.type, this.buffer); +}; + +Buffer.createVertexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); +}; + +Buffer.createIndexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); +}; + +Buffer.create = function(gl, type, data, drawType) +{ + return new Buffer(gl, type, drawType); +}; + +/** + * Destroys the buffer + * + */ +Buffer.prototype.destroy = function(){ + this.gl.deleteBuffer(this.buffer); +}; + +module.exports = Buffer; + +},{}],46:[function(require,module,exports){ + +var Texture = require('./GLTexture'); + +/** + * Helper class to create a webGL Framebuffer + * + * @class + * @memberof pixi.gl + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + */ +var Framebuffer = function(gl, width, height) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The frame buffer + * + * @member {WebGLFramebuffer} + */ + this.framebuffer = gl.createFramebuffer(); + + /** + * The stencil buffer + * + * @member {WebGLRenderbuffer} + */ + this.stencil = null; + + /** + * The stencil buffer + * + * @member {GLTexture} + */ + this.texture = null; + + /** + * The width of the drawing area of the buffer + * + * @member {Number} + */ + this.width = width || 100; + /** + * The height of the drawing area of the buffer + * + * @member {Number} + */ + this.height = height || 100; +}; + +/** + * Adds a texture to the frame buffer + * @param texture {GLTexture} + */ +Framebuffer.prototype.enableTexture = function(texture) +{ + var gl = this.gl; + + this.texture = texture || new Texture(gl); + + this.texture.bind(); + + //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + this.bind(); + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); +}; + +/** + * Initialises the stencil buffer + */ +Framebuffer.prototype.enableStencil = function() +{ + if(this.stencil)return; + + var gl = this.gl; + + this.stencil = gl.createRenderbuffer(); + + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + + // TODO.. this is depth AND stencil? + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width , this.height ); +}; + +/** + * Erases the drawing area and fills it with a colour + * @param r {Number} the red value of the clearing colour + * @param g {Number} the green value of the clearing colour + * @param b {Number} the blue value of the clearing colour + * @param a {Number} the alpha value of the clearing colour + */ +Framebuffer.prototype.clear = function( r, g, b, a ) +{ + this.bind(); + + var gl = this.gl; + + gl.clearColor(r, g, b, a); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Binds the frame buffer to the WebGL context + */ +Framebuffer.prototype.bind = function() +{ + var gl = this.gl; + + if(this.texture) + { + this.texture.unbind(); + } + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); +}; + +/** + * Unbinds the frame buffer to the WebGL context + */ +Framebuffer.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, null ); +}; +/** + * Resizes the drawing area of the buffer to the given width and height + * @param width {Number} the new width + * @param height {Number} the new height + */ +Framebuffer.prototype.resize = function(width, height) +{ + var gl = this.gl; + + this.width = width; + this.height = height; + + if ( this.texture ) + { + this.texture.uploadData(null, width, height); + } + + if ( this.stencil ) + { + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + } +}; + +/** + * Destroys this buffer + */ +Framebuffer.prototype.destroy = function() +{ + var gl = this.gl; + + //TODO + if(this.texture) + { + this.texture.destroy(); + } + + gl.deleteFramebuffer(this.framebuffer); + + this.gl = null; + + this.stencil = null; + this.texture = null; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createRGBA = function(gl, width, height/*, data*/) +{ + var texture = Texture.fromData(gl, null, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createFloat32 = function(gl, width, height, data) +{ + // create a new texture.. + var texture = new Texture.fromData(gl, data, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +module.exports = Framebuffer; + +},{"./GLTexture":48}],47:[function(require,module,exports){ + +var compileProgram = require('./shader/compileProgram'), + extractAttributes = require('./shader/extractAttributes'), + extractUniforms = require('./shader/extractUniforms'), + generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + +/** + * Helper class to create a webGL Shader + * + * @class + * @memberof pixi.gl + * @param gl {WebGLRenderingContext} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + */ +var Shader = function(gl, vertexSrc, fragmentSrc) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc); + + + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); + + var uniformData = extractUniforms(gl, this.program); + + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject( gl, uniformData ); +}; +/** + * Uses this shader + */ +Shader.prototype.bind = function() +{ + this.gl.useProgram(this.program); +}; + +/** + * Destroys this shader + * TODO + */ +Shader.prototype.destroy = function() +{ + // var gl = this.gl; +}; + +module.exports = Shader; + +},{"./shader/compileProgram":53,"./shader/extractAttributes":55,"./shader/extractUniforms":56,"./shader/generateUniformAccessObject":57}],48:[function(require,module,exports){ + +/** + * Helper class to create a WebGL Texture + * + * @class + * @memberof pixi.gl + * @param gl {WebGLRenderingContext} The current WebGL context + * @param width {number} the width of the texture + * @param height {number} the height of the texture + * @param format {number} the pixel format of the texture. defaults to gl.RGBA + * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE + */ +var Texture = function(gl, width, height, format, type) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); + + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; + + + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || 0; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || 0; + + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; + + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + + +}; + +/** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ +Texture.prototype.upload = function(source) +{ + this.bind(); + + var gl = this.gl; + + // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. + this.width = source.videoWidth || source.width; + this.height = source.videoHeight || source.height; + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); +}; + +var FLOATING_POINT_AVAILABLE = false; + +/** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.prototype.uploadData = function(data, width, height) +{ + this.bind(); + + var gl = this.gl; + + this.width = width || this.width; + this.height = height || this.height; + + if(data instanceof Float32Array) + { + if(!FLOATING_POINT_AVAILABLE) + { + var ext = gl.getExtension("OES_texture_float"); + + if(ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } + + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = gl.UNSIGNED_BYTE; + } + + + + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.width, this.height, 0, this.format, this.type, data || null); + +}; + +/** + * Binds the texture + * @param location + */ +Texture.prototype.bind = function(location) +{ + var gl = this.gl; + + if(location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } + + gl.bindTexture(gl.TEXTURE_2D, this.texture); +}; + +/** + * Unbinds the texture + */ +Texture.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, null); +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.minFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + if(this.mipmap) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.magFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); +}; + +/** + * Enables mipmapping + */ +Texture.prototype.enableMipmap = function() +{ + var gl = this.gl; + + this.bind(); + + this.mipmap = true; + + gl.generateMipmap(gl.TEXTURE_2D); +}; + +/** + * Enables linear filtering + */ +Texture.prototype.enableLinearScaling = function() +{ + this.minFilter(true); + this.magFilter(true); +}; + +/** + * Enables nearest neighbour interpolation + */ +Texture.prototype.enableNearestScaling = function() +{ + this.minFilter(false); + this.magFilter(false); +}; + +/** + * Enables clamping on the texture so WebGL will not repeat it + */ +Texture.prototype.enableWrapClamp = function() +{ + var gl = this.gl; + + this.bind(); + + 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); +}; + +/** + * Enable tiling on the texture + */ +Texture.prototype.enableWrapRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); +}; + +Texture.prototype.enableWrapMirrorRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); +}; + + +/** + * Destroys this texture + */ +Texture.prototype.destroy = function() +{ + var gl = this.gl; + //TODO + gl.deleteTexture(this.texture); +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ +Texture.fromSource = function(gl, source, premultiplyAlpha) +{ + var texture = new Texture(gl); + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); + + return texture; +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.fromData = function(gl, data, width, height) +{ + //console.log(data, width, height); + var texture = new Texture(gl); + texture.uploadData(data, width, height); + + return texture; +}; + + +module.exports = Texture; + +},{}],49:[function(require,module,exports){ + +// state object// +var setVertexAttribArrays = require( './setVertexAttribArrays' ); + +/** + * Helper class to work with WebGL VertexArrayObjects (vaos) + * Only works if WebGL extensions are enabled (they usually are) + * + * @class + * @memberof pixi.gl + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function VertexArrayObject(gl, state) +{ + this.nativeVaoExtension = null; + + if(!VertexArrayObject.FORCE_NATIVE) + { + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + this.nativeState = state; + + if(this.nativeVaoExtension) + { + this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + + var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + // VAO - overwrite the state.. + this.nativeState = { + tempAttribState: new Array(maxAttribs), + attribState: new Array(maxAttribs) + }; + } + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of attributes + * + * @member {Array} + */ + this.attributes = []; + + /** + * @member {Array} + */ + this.indexBuffer = null; + + /** + * A boolean flag + * + * @member {Boolean} + */ + this.dirty = false; +} + +VertexArrayObject.prototype.constructor = VertexArrayObject; +module.exports = VertexArrayObject; + +/** +* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) +* If you find on older devices that things have gone a bit weird then set this to true. +*/ +/** + * Lets the VAO know if you should use the WebGL extension or the native methods. + * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) + * If you find on older devices that things have gone a bit weird then set this to true. + * @static + * @property {Boolean} FORCE_NATIVE + */ +VertexArrayObject.FORCE_NATIVE = false; + +/** + * Binds the buffer + */ +VertexArrayObject.prototype.bind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + + if(this.dirty) + { + this.dirty = false; + this.activate(); + } + } + else + { + + this.activate(); + } + + return this; +}; + +/** + * Unbinds the buffer + */ +VertexArrayObject.prototype.unbind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + return this; +}; + +/** + * Uses this vao + */ +VertexArrayObject.prototype.activate = function() +{ + + var gl = this.gl; + var lastBuffer = null; + + for (var i = 0; i < this.attributes.length; i++) + { + var attrib = this.attributes[i]; + + if(lastBuffer !== attrib.buffer) + { + attrib.buffer.bind(); + lastBuffer = attrib.buffer; + } + + //attrib.attribute.pointer(attrib.type, attrib.normalized, attrib.stride, attrib.start); + gl.vertexAttribPointer(attrib.attribute.location, + attrib.attribute.size, attrib.type || gl.FLOAT, + attrib.normalized || false, + attrib.stride || 0, + attrib.start || 0); + + + } + + setVertexAttribArrays(gl, this.attributes, this.nativeState); + + this.indexBuffer.bind(); + + return this; +}; + +/** + * + * @param buffer {WebGLBuffer} + * @param attribute {*} + * @param type {String} + * @param normalized {Boolean} + * @param stride {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start) +{ + this.attributes.push({ + buffer: buffer, + attribute: attribute, + + location: attribute.location, + type: type || this.gl.FLOAT, + normalized: normalized || false, + stride: stride || 0, + start: start || 0 + }); + + this.dirty = true; + + return this; +}; + +/** + * + * @param buffer {WebGLBuffer} + * @param options {Object} + */ +VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) +{ + this.indexBuffer = buffer; + + this.dirty = true; + + return this; +}; + +/** + * Unbinds this vao and disables it + */ +VertexArrayObject.prototype.clear = function() +{ + // var gl = this.gl; + + // TODO - should this function unbind after clear? + // for now, no but lets see what happens in the real world! + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + } + + this.attributes.length = 0; + this.indexBuffer = null; + + return this; +}; + +/** + * @param type {Number} + * @param size {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.draw = function(type, size, start) +{ + var gl = this.gl; + gl.drawElements(type, size, gl.UNSIGNED_SHORT, start || 0); + + return this; +}; + +/** + * Destroy this vao + */ +VertexArrayObject.prototype.destroy = function() +{ + // lose references + this.gl = null; + this.indexBuffer = null; + this.attributes = null; + this.nativeState = null; + + if(this.nativeVao) + { + this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); + } + + this.nativeVaoExtension = null; + this.nativeVao = null; +}; + +},{"./setVertexAttribArrays":52}],50:[function(require,module,exports){ + +/** + * Helper class to create a webGL Context + * + * @class + * @memberof pixi.gl + * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from + * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * @return {WebGLRenderingContext} the WebGL context + */ +var createContext = function(canvas, options) +{ + var gl = canvas.getContext('webgl', options) || + canvas.getContext('experimental-webgl', options); + + if (!gl) + { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + return gl; +}; + +module.exports = createContext; + +},{}],51:[function(require,module,exports){ +var gl = { + createContext: require('./createContext'), + setVertexAttribArrays: require('./setVertexAttribArrays'), + GLBuffer: require('./GLBuffer'), + GLFramebuffer: require('./GLFramebuffer'), + GLShader: require('./GLShader'), + GLTexture: require('./GLTexture'), + VertexArrayObject: require('./VertexArrayObject'), + shader: require('./shader') +}; + +// Export for Node-compatible environments +if (typeof module !== 'undefined' && module.exports) +{ + // Export the module + module.exports = gl; +} + +// Add to the browser window pixi.gl +if (typeof window !== 'undefined') +{ + // add the window object + window.pixi = { gl: gl }; +} +},{"./GLBuffer":45,"./GLFramebuffer":46,"./GLShader":47,"./GLTexture":48,"./VertexArrayObject":49,"./createContext":50,"./setVertexAttribArrays":52,"./shader":58}],52:[function(require,module,exports){ +// var GL_MAP = {}; + +/** + * @param gl {WebGLRenderingContext} The current WebGL context + * @param attribs {*} + * @param state {*} + */ +var setVertexAttribArrays = function (gl, attribs, state) +{ + var i; + if(state) + { + var tempAttribState = state.tempAttribState, + attribState = state.attribState; + + for (i = 0; i < tempAttribState.length; i++) + { + tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + tempAttribState[attribs[i].attribute.location] = true; + } + + for (i = 0; i < attribState.length; i++) + { + if (attribState[i] !== tempAttribState[i]) + { + attribState[i] = tempAttribState[i]; + + if (state.attribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } + + } + else + { + for (i = 0; i < attribs.length; i++) + { + var attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); + } + } +}; + +module.exports = setVertexAttribArrays; + +},{}],53:[function(require,module,exports){ + +/** + * @class + * @memberof pixi.gl.shader + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @return {WebGLProgram} the shader program + */ +var compileProgram = function(gl, vertexSrc, fragmentSrc) +{ + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + + var program = gl.createProgram(); + + gl.attachShader(program, glVertShader); + gl.attachShader(program, glFragShader); + gl.linkProgram(program); + + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + console.error('Pixi.js Error: Could not initialize shader.'); + console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); + console.error('gl.getError()', gl.getError()); + + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') + { + console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + + gl.deleteProgram(program); + program = null; + } + + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + + return program; +}; + +/** + * @private + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @return {WebGLShader} the shader + */ +var compileShader = function (gl, type, src) +{ + var shader = gl.createShader(type); + + gl.shaderSource(shader, src); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + console.log(gl.getShaderInfoLog(shader)); + return null; + } + + return shader; +}; + +module.exports = compileProgram; + +},{}],54:[function(require,module,exports){ +/** + * @class + * @memberof pixi.gl.shader + * @param type {String} Type of value + * @param size {Number} + */ +var defaultValue = function(type, size) +{ + switch (type) + { + case 'float': + return 0; + + case 'vec2': + return new Float32Array(2 * size); + + case 'vec3': + return new Float32Array(3 * size); + + case 'vec4': + return new Float32Array(4 * size); + + case 'int': + case 'sampler2D': + return 0; + + case 'ivec2': + return new Int32Array(2 * size); + + case 'ivec3': + return new Int32Array(3 * size); + + case 'ivec4': + return new Int32Array(4 * size); + + case 'bool': + return false; + + case 'bvec2': + + return booleanArray( 2 * size); + + case 'bvec3': + return booleanArray(3 * size); + + case 'bvec4': + return booleanArray(4 * size); + + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } +}; + +var booleanArray = function(size) +{ + var array = new Array(size); + + for (var i = 0; i < array.length; i++) + { + array[i] = false; + } + + return array; +}; + +module.exports = defaultValue; + +},{}],55:[function(require,module,exports){ + +var mapType = require('./mapType'); +var mapSize = require('./mapSize'); + +/** + * Extracts the attributes + * @class + * @memberof pixi.gl.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the attributes from + * @return attributes {Object} + */ +var extractAttributes = function(gl, program) +{ + var attributes = {}; + + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + + for (var i = 0; i < totalAttributes; i++) + { + var attribData = gl.getActiveAttrib(program, i); + var type = mapType(gl, attribData.type); + + attributes[attribData.name] = { + type:type, + size:mapSize(type), + location:gl.getAttribLocation(program, attribData.name), + //TODO - make an attribute object + pointer: pointer + }; + } + + return attributes; +}; + +var pointer = function(type, normalized, stride, start){ + // console.log(this.location) + gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +}; + +module.exports = extractAttributes; + +},{"./mapSize":59,"./mapType":60}],56:[function(require,module,exports){ +var mapType = require('./mapType'); +var defaultValue = require('./defaultValue'); + +/** + * Extracts the uniforms + * @class + * @memberof pixi.gl.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the uniforms from + * @return uniforms {Object} + */ +var extractUniforms = function(gl, program) +{ + var uniforms = {}; + + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + + for (var i = 0; i < totalUniforms; i++) + { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]/, ""); + var type = mapType(gl, uniformData.type ); + + uniforms[name] = { + type:type, + size:uniformData.size, + location:gl.getUniformLocation(program, name), + value:defaultValue(type, uniformData.size) + }; + } + + return uniforms; +}; + +module.exports = extractUniforms; + +},{"./defaultValue":54,"./mapType":60}],57:[function(require,module,exports){ +/** + * Extracts the attributes + * @class + * @memberof pixi.gl.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param uniforms {Array} @mat ? + * @return attributes {Object} + */ +var generateUniformAccessObject = function(gl, uniformData) +{ + // this is the object we will be sending back. + // an object hierachy will be created for structs + var uniforms = {data:{}}; + + uniforms.gl = gl; + + var uniformKeys= Object.keys(uniformData); + + for (var i = 0; i < uniformKeys.length; i++) + { + var fullName = uniformKeys[i]; + + var nameTokens = fullName.split('.'); + var name = nameTokens[nameTokens.length - 1]; + + var uniformGroup = getUniformGroup(nameTokens, uniforms); + + var uniform = uniformData[fullName]; + uniformGroup.data[name] = uniform; + + uniformGroup.gl = gl; + + Object.defineProperty(uniformGroup, name, { + get: generateGetter(name), + set: generateSetter(name, uniform) + }); + } + + return uniforms; +}; + +var generateGetter = function(name) +{ + var template = getterTemplate.replace('%%', name); + return new Function(template); // jshint ignore:line +}; + +var generateSetter = function(name, uniform) +{ + var template = setterTemplate.replace(/%%/g, name); + var setTemplate; + + if(uniform.size === 1) + { + setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; + } + else + { + setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; + } + + if(setTemplate) + { + template += "\nthis.gl." + setTemplate + ";"; + } + + return new Function('value', template); // jshint ignore:line +}; + +var getUniformGroup = function(nameTokens, uniform) +{ + var cur = uniform; + + for (var i = 0; i < nameTokens.length - 1; i++) + { + var o = cur[nameTokens[i]] || {data:{}}; + cur[nameTokens[i]] = o; + cur = o; + } + + return cur; +}; + +var getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +var setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;' +].join('\n'); + + +var GLSL_TO_SINGLE_SETTERS = { + + 'float': 'uniform1f(location, value)', + + 'vec2': 'uniform2f(location, value[0], value[1])', + 'vec3': 'uniform3f(location, value[0], value[1], value[2])', + 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', + + 'int': 'uniform1i(location, value)', + 'ivec2': 'uniform2i(location, value[0], value[1])', + 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', + 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'bool': 'uniform1i(location, value)', + 'bvec2': 'uniform2i(location, value[0], value[1])', + 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', + 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'mat2': 'uniformMatrix2fv(location, false, value)', + 'mat3': 'uniformMatrix3fv(location, false, value)', + 'mat4': 'uniformMatrix4fv(location, false, value)', + + 'sampler2D':'uniform1i(location, value)' +}; + +var GLSL_TO_ARRAY_SETTERS = { + + 'float': 'uniform1fv(location, value)', + + 'vec2': 'uniform2fv(location, value)', + 'vec3': 'uniform3fv(location, value)', + 'vec4': 'uniform4fv(location, value)', + + 'int': 'uniform1iv(location, value)', + 'ivec2': 'uniform2iv(location, value)', + 'ivec3': 'uniform3iv(location, value)', + 'ivec4': 'uniform4iv(location, value)', + + 'bool': 'uniform1iv(location, value)', + 'bvec2': 'uniform2iv(location, value)', + 'bvec3': 'uniform3iv(location, value)', + 'bvec4': 'uniform4iv(location, value)', + + 'sampler2D':'uniform1iv(location, value)' +}; + +module.exports = generateUniformAccessObject; + +},{}],58:[function(require,module,exports){ +module.exports = { + compileProgram: require('./compileProgram'), + defaultValue: require('./defaultValue'), + extractAttributes: require('./extractAttributes'), + extractUniforms: require('./extractUniforms'), + generateUniformAccessObject: require('./generateUniformAccessObject'), + mapSize: require('./mapSize'), + mapType: require('./mapType') +}; +},{"./compileProgram":53,"./defaultValue":54,"./extractAttributes":55,"./extractUniforms":56,"./generateUniformAccessObject":57,"./mapSize":59,"./mapType":60}],59:[function(require,module,exports){ +/** + * @class + * @memberof pixi.gl.shader + * @param type {String} + * @return {Number} + */ +var mapSize = function(type) +{ + return GLSL_TO_SIZE[type]; +}; + + +var GLSL_TO_SIZE = { + 'float': 1, + 'vec2': 2, + 'vec3': 3, + 'vec4': 4, + + 'int': 1, + 'ivec2': 2, + 'ivec3': 3, + 'ivec4': 4, + + 'bool': 1, + 'bvec2': 2, + 'bvec3': 3, + 'bvec4': 4, + + 'mat2': 4, + 'mat3': 9, + 'mat4': 16, + + 'sampler2D': 1 +}; + +module.exports = mapSize; + +},{}],60:[function(require,module,exports){ + + +var mapSize = function(gl, type) +{ + if(!GL_TABLE) + { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + + GL_TABLE = {}; + + for(var i = 0; i < typeNames.length; ++i) + { + var tn = typeNames[i]; + GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + } + } + + return GL_TABLE[type]; +}; + +var GL_TABLE = null; + +var GL_TO_GLSL_TYPES = { + 'FLOAT': 'float', + 'FLOAT_VEC2': 'vec2', + 'FLOAT_VEC3': 'vec3', + 'FLOAT_VEC4': 'vec4', + + 'INT': 'int', + 'INT_VEC2': 'ivec2', + 'INT_VEC3': 'ivec3', + 'INT_VEC4': 'ivec4', + + 'BOOL': 'bool', + 'BOOL_VEC2': 'bvec2', + 'BOOL_VEC3': 'bvec3', + 'BOOL_VEC4': 'bvec4', + + 'FLOAT_MAT2': 'mat2', + 'FLOAT_MAT3': 'mat3', + 'FLOAT_MAT4': 'mat4', + + 'SAMPLER_2D': 'sampler2D' +}; + +module.exports = mapSize; + +},{}],61:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +(function () { + try { + cachedSetTimeout = setTimeout; + } catch (e) { + cachedSetTimeout = function () { + throw new Error('setTimeout is not defined'); + } + } + try { + cachedClearTimeout = clearTimeout; + } catch (e) { + cachedClearTimeout = function () { + throw new Error('clearTimeout is not defined'); + } + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],62:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],63:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],64:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],65:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":63,"./encode":64}],66:[function(require,module,exports){ +'use strict'; + +var asyncQueue = require('async/queue'); +var asyncEachSeries = require('async/eachSeries'); +var urlParser = require('url'); +var Resource = require('./Resource'); +var EventEmitter = require('eventemitter3'); + +// some constants +var DEFAULT_CONCURRENCY = 10; +var MAX_PROGRESS = 100; + +/** + * Manages the state and loading of multiple resources to load. + * + * @class + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ +function Loader(baseUrl, concurrency) { + EventEmitter.call(this); + + concurrency = concurrency || DEFAULT_CONCURRENCY; + + /** + * The base url for all resources loaded by this loader. + * + * @member {string} + */ + this.baseUrl = baseUrl || ''; + + /** + * The progress percent of the loader going through the queue. + * + * @member {number} + */ + this.progress = 0; + + /** + * Loading state of the loader, true if it is currently loading resources. + * + * @member {boolean} + */ + this.loading = false; + + /** + * The percentage of total progress that a single resource represents. + * + * @member {number} + */ + this._progressChunk = 0; + + /** + * The middleware to run before loading each resource. + * + * @member {function[]} + */ + this._beforeMiddleware = []; + + /** + * The middleware to run after loading each resource. + * + * @member {function[]} + */ + this._afterMiddleware = []; + + /** + * The `_loadResource` function bound with this object context. + * + * @private + * @member {function} + */ + this._boundLoadResource = this._loadResource.bind(this); + + /** + * The resource buffer that fills until `load` is called to start loading resources. + * + * @private + * @member {Resource[]} + */ + this._buffer = []; + + /** + * Used to track load completion. + * + * @private + * @member {number} + */ + this._numToLoad = 0; + + /** + * The resources waiting to be loaded. + * + * @private + * @member {Resource[]} + */ + this._queue = asyncQueue(this._boundLoadResource, concurrency); + + /** + * All the resources for this loader keyed by name. + * + * @member {object} + */ + this.resources = {}; + + /** + * Emitted once per loaded or errored resource. + * + * @event progress + * @memberof Loader# + */ + + /** + * Emitted once per errored resource. + * + * @event error + * @memberof Loader# + */ + + /** + * Emitted once per loaded resource. + * + * @event load + * @memberof Loader# + */ + + /** + * Emitted when the loader begins to process the queue. + * + * @event start + * @memberof Loader# + */ + + /** + * Emitted when the queued resources all load. + * + * @event complete + * @memberof Loader# + */ +} + +Loader.prototype = Object.create(EventEmitter.prototype); +Loader.prototype.constructor = Loader; +module.exports = Loader; + +/** + * Adds a resource (or multiple resources) to the loader queue. + * + * This function can take a wide variety of different parameters. The only thing that is always + * required the url to load. All the following will work: + * + * ```js + * loader + * // normal param syntax + * .add('key', 'http://...', function () {}) + * .add('http://...', function () {}) + * .add('http://...') + * + * // object syntax + * .add({ + * name: 'key2', + * url: 'http://...' + * }, function () {}) + * .add({ + * url: 'http://...' + * }, function () {}) + * .add({ + * name: 'key3', + * url: 'http://...' + * onComplete: function () {} + * }) + * .add({ + * url: 'https://...', + * onComplete: function () {}, + * crossOrigin: true + * }) + * + * // you can also pass an array of objects or urls or both + * .add([ + * { name: 'key4', url: 'http://...', onComplete: function () {} }, + * { url: 'http://...', onComplete: function () {} }, + * 'http://...' + * ]) + * + * // and you can use both params and options + * .add('key', 'http://...', { crossOrigin: true }, function () {}) + * .add('http://...', { crossOrigin: true }, function () {}); + * ``` + * + * @alias enqueue + * @param {string} [name] - The name of the resource to load, if not passed the url is used. + * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @param {object} [options] - The options for the load. + * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.XHR_LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should the data being + * loaded be interpreted when using XHR? + * @param {function} [cb] - Function to call when this specific resource completes loading. + * @return {Loader} Returns itself. + */ +Loader.prototype.add = Loader.prototype.enqueue = function (name, url, options, cb) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + + return this; + } + + // if an object is passed instead of params + if (typeof name === 'object') { + cb = url || name.callback || name.onComplete; + options = name; + url = name.url; + name = name.name || name.key || name.url; + } + + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + cb = options; + options = url; + url = name; + } + + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + cb = options; + options = null; + } + + // check if resource already exists. + if (this.resources[name]) { + throw new Error('Resource with name "' + name + '" already exists.'); + } + + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + + // create the store the resource + this.resources[name] = new Resource(name, url, options); + + if (typeof cb === 'function') { + this.resources[name].once('afterMiddleware', cb); + } + + this._numToLoad++; + + // if already loading add it to the worker queue + if (this._queue.started) { + this._queue.push(this.resources[name]); + this._progressChunk = (MAX_PROGRESS - this.progress) / (this._queue.length() + this._queue.running()); + } + // otherwise buffer it to be added to the queue later + else { + this._buffer.push(this.resources[name]); + this._progressChunk = MAX_PROGRESS / this._buffer.length; + } + + return this; +}; + +/** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * + * @alias pre + * @method before + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ +Loader.prototype.before = Loader.prototype.pre = function (fn) { + this._beforeMiddleware.push(fn); + + return this; +}; + +/** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * + * @alias use + * @method after + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ +Loader.prototype.after = Loader.prototype.use = function (fn) { + this._afterMiddleware.push(fn); + + return this; +}; + +/** + * Resets the queue of the loader to prepare for a new load. + * + * @return {Loader} Returns itself. + */ +Loader.prototype.reset = function () { + // this.baseUrl = baseUrl || ''; + + this.progress = 0; + + this.loading = false; + + this._progressChunk = 0; + + // this._beforeMiddleware.length = 0; + // this._afterMiddleware.length = 0; + + this._buffer.length = 0; + + this._numToLoad = 0; + + this._queue.kill(); + this._queue.started = false; + + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + + res.off('complete', this._onLoad, this); + + if (res.isLoading) { + res.abort(); + } + } + + this.resources = {}; + + return this; +}; + +/** + * Starts loading the queued resources. + * + * @fires start + * @param {function} [cb] - Optional callback that will be bound to the `complete` event. + * @return {Loader} Returns itself. + */ +Loader.prototype.load = function (cb) { + // register complete callback if they pass one + if (typeof cb === 'function') { + this.once('complete', cb); + } + + // if the queue has already started we are done here + if (this._queue.started) { + return this; + } + + // notify of start + this.emit('start', this); + + // update loading state + this.loading = true; + + // start the internal queue + for (var i = 0; i < this._buffer.length; ++i) { + this._queue.push(this._buffer[i]); + } + + // empty the buffer + this._buffer.length = 0; + + return this; +}; + +/** + * Prepares a url for usage based on the configuration of this object + * + * @private + * @param {string} url - The url to prepare. + * @return {string} The prepared url. + */ +Loader.prototype._prepareUrl = function (url) { + var parsedUrl = urlParser.parse(url); + + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.pathname || parsedUrl.pathname.indexOf('//') === 0) { + return url; + } + + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + if (this.baseUrl.length + && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 + && url.charAt(0) !== '/' + ) { + return this.baseUrl + '/' + url; + } + + return this.baseUrl + url; +}; + +/** + * Loads a single resource. + * + * @private + * @param {Resource} resource - The resource to load. + * @param {function} dequeue - The function to call when we need to dequeue this item. + */ +Loader.prototype._loadResource = function (resource, dequeue) { + var self = this; + + resource._dequeue = dequeue; + + // run before middleware + asyncEachSeries( + this._beforeMiddleware, + function (fn, next) { + fn.call(self, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, + function () { + // resource.on('progress', self.emit.bind(self, 'progress')); + + if (resource.isComplete) { + self._onLoad(resource); + } + else { + resource.once('complete', self._onLoad, self); + resource.load(); + } + } + ); +}; + +/** + * Called once each resource has loaded. + * + * @fires complete + * @private + */ +Loader.prototype._onComplete = function () { + this.loading = false; + + this.emit('complete', this, this.resources); +}; + +/** + * Called each time a resources is loaded. + * + * @fires progress + * @fires error + * @fires load + * @private + * @param {Resource} resource - The resource that was loaded + */ +Loader.prototype._onLoad = function (resource) { + var self = this; + + // run middleware, this *must* happen before dequeue so sub-assets get added properly + asyncEachSeries( + this._afterMiddleware, + function (fn, next) { + fn.call(self, resource, next); + }, + function () { + resource.emit('afterMiddleware', resource); + + self._numToLoad--; + + self.progress += self._progressChunk; + self.emit('progress', self, resource); + + if (resource.error) { + self.emit('error', resource.error, self, resource); + } + else { + self.emit('load', self, resource); + } + + // do completion check + if (self._numToLoad === 0) { + self.progress = 100; + self._onComplete(); + } + } + ); + + // remove this resource from the async queue + resource._dequeue(); +}; + +Loader.LOAD_TYPE = Resource.LOAD_TYPE; +Loader.XHR_RESPONSE_TYPE = Resource.XHR_RESPONSE_TYPE; + +},{"./Resource":67,"async/eachSeries":2,"async/queue":13,"eventemitter3":16,"url":72}],67:[function(require,module,exports){ +'use strict'; + +var EventEmitter = require('eventemitter3'); +var _url = require('url'); + +// tests is CORS is supported in XHR, if not we need to use XDR +var useXdr = !!(window.XDomainRequest && !('withCredentials' in (new XMLHttpRequest()))); +var tempAnchor = null; + +// some status constants +var STATUS_NONE = 0; +var STATUS_OK = 200; +var STATUS_EMPTY = 204; + +/** + * Manages the state and loading of a single resource represented by + * a single URL. + * + * @class + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should the data being + * loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra info for middleware. + */ +function Resource(name, url, options) { + EventEmitter.call(this); + + options = options || {}; + + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + + /** + * The name of this resource. + * + * @member {string} + * @readonly + */ + this.name = name; + + /** + * The url used to load this resource. + * + * @member {string} + * @readonly + */ + this.url = url; + + /** + * Stores whether or not this url is a data url. + * + * @member {boolean} + * @readonly + */ + this.isDataUrl = this.url.indexOf('data:') === 0; + + /** + * The data that was loaded by the resource. + * + * @member {any} + */ + this.data = null; + + /** + * Is this request cross-origin? If unset, determined automatically. + * + * @member {string} + */ + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + + /** + * The method of loading to use for this resource. + * + * @member {Resource.LOAD_TYPE} + */ + this.loadType = options.loadType || this._determineLoadType(); + + /** + * The type used to load the resource via XHR. If unset, determined automatically. + * + * @member {string} + */ + this.xhrType = options.xhrType; + + /** + * Extra info for middleware, and controlling specifics about how the resource loads. + * + * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + * Meaning it will modify it as it sees fit. + * + * @member {object} + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources + * to. + */ + this.metadata = options.metadata || {}; + + /** + * The error that occurred while loading (if any). + * + * @member {Error} + * @readonly + */ + this.error = null; + + /** + * The XHR object that was used to load this resource. This is only set + * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * + * @member {XMLHttpRequest} + */ + this.xhr = null; + + /** + * Describes if this resource was loaded as json. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isJson = false; + + /** + * Describes if this resource was loaded as xml. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isXml = false; + + /** + * Describes if this resource was loaded as an image tag. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isImage = false; + + /** + * Describes if this resource was loaded as an audio tag. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isAudio = false; + + /** + * Describes if this resource was loaded as a video tag. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isVideo = false; + + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * + * @member {boolean} + */ + this.isComplete = false; + + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * + * @member {boolean} + */ + this.isLoading = false; + + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * + * @private + * @member {function} + */ + this._dequeue = null; + + /** + * The `complete` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundComplete = this.complete.bind(this); + + /** + * The `_onError` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnError = this._onError.bind(this); + + /** + * The `_onProgress` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnProgress = this._onProgress.bind(this); + + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + this._boundXdrOnTimeout = this._xdrOnTimeout.bind(this); + + /** + * Emitted when the resource beings to load. + * + * @event start + * @memberof Resource# + */ + + /** + * Emitted each time progress of this resource load updates. + * Not all resources types and loader systems can support this event + * so sometimes it may not be available. If the resource + * is being loaded on a modern browser, using XHR, and the remote server + * properly sets Content-Length headers, then this will be available. + * + * @event progress + * @memberof Resource# + */ + + /** + * Emitted once this resource has loaded, if there was an error it will + * be in the `error` property. + * + * @event complete + * @memberof Resource# + */ +} + +Resource.prototype = Object.create(EventEmitter.prototype); +Resource.prototype.constructor = Resource; +module.exports = Resource; + +/** + * Marks the resource as complete. + * + * @fires complete + */ +Resource.prototype.complete = function () { + // TODO: Clean this up in a wrapper or something...gross.... + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } + else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + + this.isComplete = true; + this.isLoading = false; + + this.emit('complete', this); +}; + +/** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ +Resource.prototype.abort = function (message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + + // store error + this.error = new Error(message); + + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } + else if (this.xdr) { + this.xdr.abort(); + } + else if (this.data) { + // single source + if (typeof this.data.src !== 'undefined') { + this.data.src = ''; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + + // done now. + this.complete(); +}; + +/** + * Kicks off loading of this resource. This method is asynchronous. + * + * @fires start + * @param {function} [cb] - Optional callback to call once the resource is loaded. + */ +Resource.prototype.load = function (cb) { + if (this.isLoading) { + return; + } + + if (this.isComplete) { + if (cb) { + var self = this; + + setTimeout(function () { + cb(self); + }, 1); + } + + return; + } + else if (cb) { + this.once('complete', cb); + } + + this.isLoading = true; + + this.emit('start', this); + + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + + switch (this.loadType) { + case Resource.LOAD_TYPE.IMAGE: + this._loadElement('image'); + break; + + case Resource.LOAD_TYPE.AUDIO: + this._loadSourceElement('audio'); + break; + + case Resource.LOAD_TYPE.VIDEO: + this._loadSourceElement('video'); + break; + + case Resource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } + else { + this._loadXhr(); + } + break; + } +}; + +/** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * + * @private + * @param {string} type - The type of element to use. + */ +Resource.prototype._loadElement = function (type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } + else if (type === 'image' && typeof window.Image !== 'undefined') { + this.data = new Image(); + } + else { + this.data = document.createElement(type); + } + + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + + var typeName = 'is' + type[0].toUpperCase() + type.substring(1); + + if (this[typeName] === false) { + this[typeName] = true; + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); +}; + +/** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * + * @private + * @param {string} type - The type of element to use. + */ +Resource.prototype._loadSourceElement = function (type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } + else if (type === 'audio' && typeof window.Audio !== 'undefined') { + this.data = new Audio(); + } + else { + this.data = document.createElement(type); + } + + if (this.data === null) { + this.abort('Unsupported element ' + type); + + return; + } + + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } + else if (Array.isArray(this.url)) { + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i])); + } + } + else { + this.data.appendChild(this._createSource(type, this.url)); + } + } + + this['is' + type[0].toUpperCase() + type.substring(1)] = true; + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + + this.data.load(); +}; + +/** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ +Resource.prototype._loadXhr = function () { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xhr = this.xhr = new XMLHttpRequest(); + + // set the request type and url + xhr.open('GET', this.url, true); + + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; + } + else { + xhr.responseType = this.xhrType; + } + + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + + xhr.send(); +}; + +/** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ +Resource.prototype._loadXdr = function () { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xdr = this.xhr = new XDomainRequest(); + + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = 5000; + + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXdrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + + xdr.open('GET', this.url, true); + + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { + xdr.send(); + }, 0); +}; + +/** + * Creates a source used in loading via an element. + * + * @private + * @param {string} type - The element type (video or audio). + * @param {string} url - The source URL to load from. + * @param {string} [mime] - The mime type of the video + * @return {HTMLSourceElement} The source element. + */ +Resource.prototype._createSource = function (type, url, mime) { + if (!mime) { + mime = type + '/' + url.substr(url.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = url; + source.type = mime; + + return source; +}; + +/** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ +Resource.prototype._onError = function (event) { + this.abort('Failed to load element using ' + event.target.nodeName); +}; + +/** + * Called if a load progress event fires for xhr/xdr. + * + * @fires progress + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ +Resource.prototype._onProgress = function (event) { + if (event && event.lengthComputable) { + this.emit('progress', this, event.loaded / event.total); + } +}; + +/** + * Called if an error event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestErrorEvent|Event} event - Error event. + */ +Resource.prototype._xhrOnError = function () { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"'); +}; + +/** + * Called if an abort event fires for xhr. + * + * @private + * @param {XMLHttpRequestAbortEvent} event - Abort Event + */ +Resource.prototype._xhrOnAbort = function () { + this.abort(reqType(this.xhr) + ' Request was aborted by the user.'); +}; + +/** + * Called if a timeout event fires for xdr. + * + * @private + * @param {Event} event - Timeout event. + */ +Resource.prototype._xdrOnTimeout = function () { + this.abort(reqType(this.xhr) + ' Request timed out.'); +}; + +/** + * Called when data successfully loads from an xhr/xdr request. + * + * @private + * @param {XMLHttpRequestLoadEvent|Event} event - Load event + */ +Resource.prototype._xhrOnLoad = function () { + var xhr = this.xhr; + var status = typeof xhr.status === 'undefined' ? xhr.status : STATUS_OK; // XDR has no `.status`, assume 200. + + // status can be 0 when using the file:// protocol, also check if a response was found + if (status === STATUS_OK || status === STATUS_EMPTY || (status === STATUS_NONE && xhr.responseText.length > 0)) { + // if text, just return it + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { + this.data = xhr.responseText; + } + // if json, parse into json object + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(xhr.responseText); + this.isJson = true; + } + catch (e) { + this.abort('Error trying to parse loaded json:', e); + + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (window.DOMParser) { + var domparser = new DOMParser(); + + this.data = domparser.parseFromString(xhr.responseText, 'text/xml'); + } + else { + var div = document.createElement('div'); + + div.innerHTML = xhr.responseText; + this.data = div; + } + this.isXml = true; + } + catch (e) { + this.abort('Error trying to parse loaded xml:', e); + + return; + } + } + // other types just return the response + else { + this.data = xhr.response || xhr.responseText; + } + } + else { + this.abort('[' + xhr.status + ']' + xhr.statusText + ':' + xhr.responseURL); + + return; + } + + this.complete(); +}; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * + * @private + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +Resource.prototype._determineCrossOrigin = function (url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url.parse(tempAnchor.href); + + var samePort = (!url.port && loc.port === '') || (url.port === loc.port); + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +}; + +/** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. + */ +Resource.prototype._determineXhrType = function () { + return Resource._xhrTypeMap[this._getExtension()] || Resource.XHR_RESPONSE_TYPE.TEXT; +}; + +Resource.prototype._determineLoadType = function () { + return Resource._loadTypeMap[this._getExtension()] || Resource.LOAD_TYPE.XHR; +}; + +Resource.prototype._getExtension = function () { + var url = this.url; + var ext = ''; + + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } + else { + var queryStart = url.indexOf('?'); + + if (queryStart !== -1) { + url = url.substring(0, queryStart); + } + + ext = url.substring(url.lastIndexOf('.') + 1); + } + + return ext.toLowerCase(); +}; + +/** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * + * @private + * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. + * @return {string} The mime type to use. + */ +Resource.prototype._getMimeFromXhrType = function (type) { + switch (type) { + case Resource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + + case Resource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + + case Resource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + + case Resource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + + case Resource.XHR_RESPONSE_TYPE.DEFAULT: + case Resource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + + } +}; + +/** + * Quick helper to get string xhr type. + * + * @ignore + * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. + * @return {string} The type. + */ +function reqType(xhr) { + return xhr.toString().replace('object ', ''); +} + +/** + * The types of loading a resource can use. + * + * @static + * @readonly + * @enum {number} + */ +Resource.LOAD_TYPE = { + /** Uses XMLHttpRequest to load the resource. */ + XHR: 1, + /** Uses an `Image` object to load the resource. */ + IMAGE: 2, + /** Uses an `Audio` object to load the resource. */ + AUDIO: 3, + /** Uses a `Video` object to load the resource. */ + VIDEO: 4 +}; + +/** + * The XHR ready states, used internally. + * + * @static + * @readonly + * @enum {string} + */ +Resource.XHR_RESPONSE_TYPE = { + /** defaults to text */ + DEFAULT: 'text', + /** ArrayBuffer */ + BUFFER: 'arraybuffer', + /** Blob */ + BLOB: 'blob', + /** Document */ + DOCUMENT: 'document', + /** Object */ + JSON: 'json', + /** String */ + TEXT: 'text' +}; + +Resource._loadTypeMap = { + gif: Resource.LOAD_TYPE.IMAGE, + png: Resource.LOAD_TYPE.IMAGE, + bmp: Resource.LOAD_TYPE.IMAGE, + jpg: Resource.LOAD_TYPE.IMAGE, + jpeg: Resource.LOAD_TYPE.IMAGE, + tif: Resource.LOAD_TYPE.IMAGE, + tiff: Resource.LOAD_TYPE.IMAGE, + webp: Resource.LOAD_TYPE.IMAGE, + tga: Resource.LOAD_TYPE.IMAGE, + 'svg+xml': Resource.LOAD_TYPE.IMAGE +}; + +Resource._xhrTypeMap = { + // xml + xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // images + gif: Resource.XHR_RESPONSE_TYPE.BLOB, + png: Resource.XHR_RESPONSE_TYPE.BLOB, + bmp: Resource.XHR_RESPONSE_TYPE.BLOB, + jpg: Resource.XHR_RESPONSE_TYPE.BLOB, + jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, + tif: Resource.XHR_RESPONSE_TYPE.BLOB, + tiff: Resource.XHR_RESPONSE_TYPE.BLOB, + webp: Resource.XHR_RESPONSE_TYPE.BLOB, + tga: Resource.XHR_RESPONSE_TYPE.BLOB, + + // json + json: Resource.XHR_RESPONSE_TYPE.JSON, + + // text + text: Resource.XHR_RESPONSE_TYPE.TEXT, + txt: Resource.XHR_RESPONSE_TYPE.TEXT +}; + +/** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. + */ +Resource.setExtensionLoadType = function (extname, loadType) { + setExtMap(Resource._loadTypeMap, extname, loadType); +}; + +/** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ +Resource.setExtensionXhrType = function (extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); +}; + +function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + + if (!extname) { + return; + } + + map[extname] = val; +} + +},{"eventemitter3":16,"url":72}],68:[function(require,module,exports){ +/* eslint no-magic-numbers: 0 */ +'use strict'; + +module.exports = { + // private property + _keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', + + encodeBinary: function (input) { + var output = ''; + var bytebuffer; + var encodedCharIndexes = new Array(4); + var inx = 0; + var jnx = 0; + var paddingBytes = 0; + + while (inx < input.length) { + // Fill byte buffer array + bytebuffer = new Array(3); + + for (jnx = 0; jnx < bytebuffer.length; jnx++) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } + else { + bytebuffer[jnx] = 0; + } + } + + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = ((bytebuffer[0] & 0x3) << 4) | (bytebuffer[1] >> 4); + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = ((bytebuffer[1] & 0x0f) << 2) | (bytebuffer[2] >> 6); + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + + // Determine whether padding happened, and adjust accordingly + paddingBytes = inx - (input.length - 1); + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + + default: + break; // No padding - proceed + } + + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (jnx = 0; jnx < encodedCharIndexes.length; jnx++) { + output += this._keyStr.charAt(encodedCharIndexes[jnx]); + } + } + + return output; + } +}; + +},{}],69:[function(require,module,exports){ +/* eslint global-require: 0 */ +'use strict'; + +module.exports = require('./Loader'); +module.exports.Resource = require('./Resource'); +module.exports.middleware = { + caching: { + memory: require('./middlewares/caching/memory') + }, + parsing: { + blob: require('./middlewares/parsing/blob') + } +}; + + +},{"./Loader":66,"./Resource":67,"./middlewares/caching/memory":70,"./middlewares/parsing/blob":71}],70:[function(require,module,exports){ +'use strict'; + +// a simple in-memory cache for resources +var cache = {}; + +module.exports = function () { + return function (resource, next) { + // if cached, then set data and complete the resource + if (cache[resource.url]) { + resource.data = cache[resource.url]; + resource.complete(); // marks resource load complete and stops processing before middlewares + } + // if not cached, wait for complete and store it in the cache. + else { + resource.once('complete', function () { + cache[this.url] = this.data; + }); + } + + next(); + }; +}; + +},{}],71:[function(require,module,exports){ +'use strict'; + +var Resource = require('../../Resource'); +var b64 = require('../../b64'); + +var Url = window.URL || window.webkitURL; + +// a middleware for transforming XHR loaded Blobs into more useful objects + +module.exports = function () { + return function (resource, next) { + if (!resource.data) { + next(); + + return; + } + + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === Resource.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!window.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = 'data:' + type + ';base64,' + b64.encodeBinary(resource.xhr.responseText); + + resource.isImage = true; + + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + + next(); + }; + + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var src = Url.createObjectURL(resource.data); + + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src; + + resource.isImage = true; + + // cleanup the no longer used blob after the image loads + resource.data.onload = function () { + Url.revokeObjectURL(src); + resource.data.onload = null; + + next(); + }; + + // next will be called on load. + return; + } + } + + next(); + }; +}; + +},{"../../Resource":67,"../../b64":68}],72:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":73,"punycode":62,"querystring":65}],73:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],74:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +var _accessibleTarget = require('./accessibleTarget'); + +var _accessibleTarget2 = _interopRequireDefault(_accessibleTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// add some extra variables to the container.. +Object.assign(core.DisplayObject.prototype, _accessibleTarget2.default); + +var KEY_CODE_TAB = 9; + +var DIV_TOUCH_SIZE = 100; +var DIV_TOUCH_POS_X = 0; +var DIV_TOUCH_POS_Y = 0; +var DIV_TOUCH_ZINDEX = 2; + +var DIV_HOOK_SIZE = 1; +var DIV_HOOK_POS_X = -1000; +var DIV_HOOK_POS_Y = -1000; +var DIV_HOOK_ZINDEX = 2; + +/** + * The Accessibility manager reacreates the ability to tab and and have content read by screen + * readers. This is very important as it can possibly help people with disabilities access pixi + * content. + * + * Much like interaction any DisplayObject can be made accessible. This manager will map the + * events as if the mouse was being used, minimizing the efferot required to implement. + * + * @class + * @memberof PIXI + */ + +var AccessibilityManager = function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + _classCallCheck(this, AccessibilityManager); + + if ((_ismobilejs2.default.tablet || _ismobilejs2.default.phone) && !navigator.isCocoonJS) { + this.createTouchHook(); + } + + // first we create a div that will sit over the pixi element. This is where the div overlays will go. + var div = document.createElement('div'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + 'px'; + div.style.left = DIV_TOUCH_POS_Y + 'px'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + + /** + * This is the dom element that will sit over the pixi element. This is where the div overlays will go. + * + * @type {HTMLElement} + * @private + */ + this.div = div; + + /** + * A simple pool for storing divs. + * + * @type {*} + * @private + */ + this.pool = []; + + /** + * This is a tick used to check if an object is no longer being rendered. + * + * @type {Number} + * @private + */ + this.renderId = 0; + + /** + * Setting this to true will visually show the divs + * + * @type {boolean} + */ + this.debug = false; + + /** + * The renderer this accessibility manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * The array of currently active accessible items. + * + * @member {Array<*>} + * @private + */ + this.children = []; + + /** + * pre-bind the functions + * + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + + /** + * stores the state of the manager. If there are no accessible objects or the mouse is moving the will be false. + * + * @member {Array<*>} + * @private + */ + this.isActive = false; + this.isMobileAccessabillity = false; + + // let listen for tab.. once pressed we can fire up and show the accessibility layer + window.addEventListener('keydown', this._onKeyDown, false); + } + + /** + * Creates the touch hooks. + * + */ + + + AccessibilityManager.prototype.createTouchHook = function createTouchHook() { + var _this = this; + + var hookDiv = document.createElement('button'); + + hookDiv.style.width = DIV_HOOK_SIZE + 'px'; + hookDiv.style.height = DIV_HOOK_SIZE + 'px'; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + 'px'; + hookDiv.style.left = DIV_HOOK_POS_Y + 'px'; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX; + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'HOOK DIV'; + + hookDiv.addEventListener('focus', function () { + _this.isMobileAccessabillity = true; + _this.activate(); + document.body.removeChild(hookDiv); + }); + + document.body.appendChild(hookDiv); + }; + + /** + * Activating will cause the Accessibility layer to be shown. This is called when a user + * preses the tab key + * + * @private + */ + + + AccessibilityManager.prototype.activate = function activate() { + if (this.isActive) { + return; + } + + this.isActive = true; + + window.document.addEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown, false); + + this.renderer.on('postrender', this.update, this); + + if (this.renderer.view.parentNode) { + this.renderer.view.parentNode.appendChild(this.div); + } + }; + + /** + * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves + * the mouse + * + * @private + */ + + + AccessibilityManager.prototype.deactivate = function deactivate() { + if (!this.isActive || this.isMobileAccessabillity) { + return; + } + + this.isActive = false; + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.addEventListener('keydown', this._onKeyDown, false); + + this.renderer.off('postrender', this.update); + + if (this.div.parentNode) { + this.div.parentNode.removeChild(this.div); + } + }; + + /** + * This recursive function will run throught he scene graph and add any new accessible objects to the DOM layer. + * + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + + + AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects(displayObject) { + if (!displayObject.visible) { + return; + } + + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + + displayObject.renderId = this.renderId; + } + + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + this.updateAccessibleObjects(children[i]); + } + }; + + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * + * @private + */ + + + AccessibilityManager.prototype.update = function update() { + if (!this.renderer.renderingToScreen) { + return; + } + + // update children... + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + + var rect = this.renderer.view.getBoundingClientRect(); + var sx = rect.width / this.renderer.width; + var sy = rect.height / this.renderer.height; + + var div = this.div; + + div.style.left = rect.left + 'px'; + div.style.top = rect.top + 'px'; + div.style.width = this.renderer.width + 'px'; + div.style.height = this.renderer.height + 'px'; + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + + core.utils.removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + + i--; + + if (this.children.length === 0) { + this.deactivate(); + } + } else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + + if (child.hitArea) { + div.style.left = (wt.tx + hitArea.x * wt.a) * sx + 'px'; + div.style.top = (wt.ty + hitArea.y * wt.d) * sy + 'px'; + + div.style.width = hitArea.width * wt.a * sx + 'px'; + div.style.height = hitArea.height * wt.d * sy + 'px'; + } else { + hitArea = child.getBounds(); + + this.capHitArea(hitArea); + + div.style.left = hitArea.x * sx + 'px'; + div.style.top = hitArea.y * sy + 'px'; + + div.style.width = hitArea.width * sx + 'px'; + div.style.height = hitArea.height * sy + 'px'; + } + } + } + + // increment the render id.. + this.renderId++; + }; + + /** + * TODO: docs. + * + * @param {Rectangle} hitArea - TODO docs + */ + + + AccessibilityManager.prototype.capHitArea = function capHitArea(hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + + if (hitArea.x + hitArea.width > this.renderer.width) { + hitArea.width = this.renderer.width - hitArea.x; + } + + if (hitArea.y + hitArea.height > this.renderer.height) { + hitArea.height = this.renderer.height - hitArea.y; + } + }; + + /** + * Adds a DisplayObject to the accessibility manager + * + * @private + * @param {DisplayObject} displayObject - The child to make accessible. + */ + + + AccessibilityManager.prototype.addChild = function addChild(displayObject) { + // this.activate(); + + var div = this.pool.pop(); + + if (!div) { + div = document.createElement('button'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + div.style.borderStyle = 'none'; + + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + + if (displayObject.accessibleTitle) { + div.title = displayObject.accessibleTitle; + } else if (!displayObject.accessibleTitle && !displayObject.accessibleHint) { + div.title = 'displayObject ' + this.tabIndex; + } + + if (displayObject.accessibleHint) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + + // + + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + + /** + * Maps the div button press to pixi's InteractionManager (click) + * + * @private + * @param {MouseEvent} e - The click event. + */ + + + AccessibilityManager.prototype._onClick = function _onClick(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixis InteractionManager (mouseover) + * + * @private + * @param {FocusEvent} e - The focus event. + */ + + + AccessibilityManager.prototype._onFocus = function _onFocus(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixis InteractionManager (mouseout) + * + * @private + * @param {FocusEvent} e - The focusout event. + */ + + + AccessibilityManager.prototype._onFocusOut = function _onFocusOut(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); + }; + + /** + * Is called when a key is pressed + * + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + + + AccessibilityManager.prototype._onKeyDown = function _onKeyDown(e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + + this.activate(); + }; + + /** + * Is called when the mouse moves across the renderer element + * + * @private + */ + + + AccessibilityManager.prototype._onMouseMove = function _onMouseMove() { + this.deactivate(); + }; + + /** + * Destroys the accessibility manager + * + */ + + + AccessibilityManager.prototype.destroy = function destroy() { + this.div = null; + + for (var i = 0; i < this.children.length; i++) { + this.children[i].div = null; + } + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.removeEventListener('keydown', this._onKeyDown); + + this.pool = null; + this.children = null; + this.renderer = null; + }; + + return AccessibilityManager; +}(); + +exports.default = AccessibilityManager; + + +core.WebGLRenderer.registerPlugin('accessibility', AccessibilityManager); +core.CanvasRenderer.registerPlugin('accessibility', AccessibilityManager); + +},{"../core":97,"./accessibleTarget":75,"ismobilejs":17}],75:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Default property values of accessible objects + * used by {@link PIXI.accessibility.AccessibilityManager}. + * + * @mixin + * @name accessibleTarget + * @memberof PIXI + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibility.accessibleTarget + * ); + */ +exports.default = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * + * @member {boolean} + */ + accessible: false, + + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * + * @member {string} + */ + accessibleTitle: null, + + /** + * Sets the aria-label attribute of the shadow div + * + * @member {string} + */ + accessibleHint: null, + + /** + * @todo Needs docs. + */ + tabIndex: 0, + + /** + * @todo Needs docs. + */ + _accessibleActive: false, + + /** + * @todo Needs docs. + */ + _accessibleDiv: false +}; + +},{}],76:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _accessibleTarget = require('./accessibleTarget'); + +Object.defineProperty(exports, 'accessibleTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_accessibleTarget).default; + } +}); + +var _AccessibilityManager = require('./AccessibilityManager'); + +Object.defineProperty(exports, 'AccessibilityManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AccessibilityManager).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./AccessibilityManager":74,"./accessibleTarget":75}],77:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _const = require('./const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function checkPrecision(src) { + if (src instanceof Array) { + if (src[0].substring(0, 9) !== 'precision') { + var copy = src.slice(0); + + copy.unshift('precision ' + _const.PRECISION.DEFAULT + ' float;'); + + return copy; + } + } else if (src.substring(0, 9) !== 'precision') { + return 'precision ' + _const.PRECISION.DEFAULT + ' float;\n' + src; + } + + return src; +} + +/** + * Wrapper class, webGL Shader for Pixi. + * Adds precision string if vertexSrc or fragmentSrc have no mention of it. + * + * @class + * @extends GLShader + * @memberof PIXI + */ + +var Shader = function (_GLShader) { + _inherits(Shader, _GLShader); + + /** + * + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + * @param {string|string[]} vertexSrc - The vertex shader source as an array of strings. + * @param {string|string[]} fragmentSrc - The fragment shader source as an array of strings. + */ + function Shader(gl, vertexSrc, fragmentSrc) { + _classCallCheck(this, Shader); + + return _possibleConstructorReturn(this, _GLShader.call(this, gl, checkPrecision(vertexSrc), checkPrecision(fragmentSrc))); + } + + return Shader; +}(_pixiGlCore.GLShader); + +exports.default = Shader; + +},{"./const":78,"pixi-gl-core":51}],78:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.SPRITE_MAX_TEXTURES = exports.SPRITE_BATCH_SIZE = exports.TEXT_GRADIENT = exports.TRANSFORM_MODE = exports.PRECISION = exports.SHAPES = exports.SVG_SIZE = exports.DATA_URI = exports.IMAGE_TYPE = exports.DEFAULT_RENDER_OPTIONS = exports.FILTER_RESOLUTION = exports.RESOLUTION = exports.RETINA_PREFIX = exports.MIPMAP_TEXTURES = exports.GC_MODES = exports.WRAP_MODES = exports.SCALE_MODES = exports.DRAW_MODES = exports.BLEND_MODES = exports.RENDERER_TYPE = exports.TARGET_FPMS = exports.DEG_TO_RAD = exports.RAD_TO_DEG = exports.PI_2 = exports.VERSION = undefined; + +var _maxRecommendedTextures = require('./utils/maxRecommendedTextures'); + +var _maxRecommendedTextures2 = _interopRequireDefault(_maxRecommendedTextures); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * String of the current PIXI version. + * + * @static + * @constant + * @memberof PIXI + * @type {string} + */ +var VERSION = exports.VERSION = '4.0.3'; + +/** + * Two Pi. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var PI_2 = exports.PI_2 = Math.PI * 2; + +/** + * Conversion factor for converting radians to degrees. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var RAD_TO_DEG = exports.RAD_TO_DEG = 180 / Math.PI; + +/** + * Conversion factor for converting degrees to radians. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var DEG_TO_RAD = exports.DEG_TO_RAD = Math.PI / 180; + +/** + * Target frames per millisecond. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + * @default 0.06 + */ +var TARGET_FPMS = exports.TARGET_FPMS = 0.06; + +/** + * Constant to identify the Renderer Type. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ +var RENDERER_TYPE = exports.RENDERER_TYPE = { + UNKNOWN: 0, + WEBGL: 1, + CANVAS: 2 +}; + +/** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} NORMAL + * @property {number} ADD + * @property {number} MULTIPLY + * @property {number} SCREEN + * @property {number} OVERLAY + * @property {number} DARKEN + * @property {number} LIGHTEN + * @property {number} COLOR_DODGE + * @property {number} COLOR_BURN + * @property {number} HARD_LIGHT + * @property {number} SOFT_LIGHT + * @property {number} DIFFERENCE + * @property {number} EXCLUSION + * @property {number} HUE + * @property {number} SATURATION + * @property {number} COLOR + * @property {number} LUMINOSITY + */ +var BLEND_MODES = exports.BLEND_MODES = { + NORMAL: 0, + ADD: 1, + MULTIPLY: 2, + SCREEN: 3, + OVERLAY: 4, + DARKEN: 5, + LIGHTEN: 6, + COLOR_DODGE: 7, + COLOR_BURN: 8, + HARD_LIGHT: 9, + SOFT_LIGHT: 10, + DIFFERENCE: 11, + EXCLUSION: 12, + HUE: 13, + SATURATION: 14, + COLOR: 15, + LUMINOSITY: 16 +}; + +/** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} POINTS + * @property {number} LINES + * @property {number} LINE_LOOP + * @property {number} LINE_STRIP + * @property {number} TRIANGLES + * @property {number} TRIANGLE_STRIP + * @property {number} TRIANGLE_FAN + */ +var DRAW_MODES = exports.DRAW_MODES = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6 +}; + +/** + * The scale modes that are supported by pixi. + * + * The DEFAULT scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} DEFAULT=LINEAR + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ +var SCALE_MODES = exports.SCALE_MODES = { + DEFAULT: 0, + LINEAR: 0, + NEAREST: 1 +}; + +/** + * The wrap modes that are supported by pixi. + * + * The DEFAULT wrap mode affects the default wraping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as webGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} DEFAULT=CLAMP + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ +var WRAP_MODES = exports.WRAP_MODES = { + DEFAULT: 0, + CLAMP: 0, + REPEAT: 1, + MIRRORED_REPEAT: 2 +}; + +/** + * The gc modes that are supported by pixi. + * + * The DEFAULT Garbage Collection mode for pixi textures is MANUAL + * If set to DEFAULT, the renderer will occasianally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} DEFAULT=MANUAL + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ +var GC_MODES = exports.GC_MODES = { + DEFAULT: 0, + AUTO: 0, + MANUAL: 1 +}; + +/** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * + * @static + * @constant + * @memberof PIXI + * @type {boolean} + */ +var MIPMAP_TEXTURES = exports.MIPMAP_TEXTURES = true; + +/** + * The prefix that denotes a URL is for a retina asset. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `@2x` + */ +var RETINA_PREFIX = exports.RETINA_PREFIX = /@(.+)x/; + +/** + * Default resolution / device pixel ratio of the renderer. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var RESOLUTION = exports.RESOLUTION = 1; + +/** + * Default filter resolution. + * + * @static + * @constant + * @type {number} + */ +var FILTER_RESOLUTION = exports.FILTER_RESOLUTION = 1; + +/** + * The default render options if none are supplied to {@link PIXI.WebGLRenderer} + * or {@link PIXI.CanvasRenderer}. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {HTMLCanvasElement} view=null + * @property {number} resolution=1 + * @property {boolean} antialias=false + * @property {boolean} forceFXAA=false + * @property {boolean} autoResize=false + * @property {boolean} transparent=false + * @property {number} backgroundColor=0x000000 + * @property {boolean} clearBeforeRender=true + * @property {boolean} preserveDrawingBuffer=false + * @property {boolean} roundPixels=false + */ +var DEFAULT_RENDER_OPTIONS = exports.DEFAULT_RENDER_OPTIONS = { + view: null, + resolution: 1, + antialias: false, + forceFXAA: false, + autoResize: false, + transparent: false, + backgroundColor: 0x000000, + clearBeforeRender: true, + preserveDrawingBuffer: false, + roundPixels: false +}; + +/** + * Regexp for image type by extension. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `image.png` + */ +var IMAGE_TYPE = exports.IMAGE_TYPE = /\.(gif|jpe?g|tiff|png|svg)$/i; + +/** + * Regexp for data URI. + * Based on: https://github.com/ragingwind/data-uri-regex + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `data:image/png;base64` + */ +var DATA_URI = exports.DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;(charset=[\w-]+|base64))?,(.*)/i; + +/** + * Regexp for SVG size. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `` + */ +var SVG_SIZE = exports.SVG_SIZE = /]*(?:\s(width|height)="(\d*(?:\.\d+)?)(?:px)?")[^>]*(?:\s(width|height)="(\d*(?:\.\d+)?)(?:px)?")[^>]*>/i; // eslint-disable-line max-len + +/** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} POLY + * @property {number} RECT + * @property {number} CIRC + * @property {number} ELIP + * @property {number} RREC + */ +var SHAPES = exports.SHAPES = { + POLY: 0, + RECT: 1, + CIRC: 2, + ELIP: 3, + RREC: 4 +}; + +/** + * Constants that specify float precision in shaders. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} DEFAULT='mediump' + * @property {number} LOW='lowp' + * @property {number} MEDIUM='mediump' + * @property {number} HIGH='highp' + */ +var PRECISION = exports.PRECISION = { + DEFAULT: 'mediump', + LOW: 'lowp', + MEDIUM: 'mediump', + HIGH: 'highp' +}; + +/** + * Constants that specify the transform type. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} DEFAULT=STATIC + * @property {number} STATIC + * @property {number} DYNAMIC + */ +var TRANSFORM_MODE = exports.TRANSFORM_MODE = { + DEFAULT: 0, + STATIC: 0, + DYNAMIC: 1 +}; + +/** + * Constants that define the type of gradient on text. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL + * @property {number} LINEAR_HORIZONTAL + */ +var TEXT_GRADIENT = exports.TEXT_GRADIENT = { + LINEAR_VERTICAL: 0, + LINEAR_HORIZONTAL: 1 +}; + +// TODO: maybe change to SPRITE.BATCH_SIZE: 2000 +// TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + +/** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + * @default 4096 + */ +var SPRITE_BATCH_SIZE = exports.SPRITE_BATCH_SIZE = 4096; + +/** + * The maximum textures that this device supports. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var SPRITE_MAX_TEXTURES = exports.SPRITE_MAX_TEXTURES = (0, _maxRecommendedTextures2.default)(32); + +},{"./utils/maxRecommendedTextures":153}],79:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * 'Builder' pattern for bounds rectangles + * Axis-Aligned Bounding Box + * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems + * + * @class + * @memberof PIXI + */ +var Bounds = function () { + /** + * + */ + function Bounds() { + _classCallCheck(this, Bounds); + + /** + * @member {number} + * @default 0 + */ + this.minX = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.minY = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxX = -Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxY = -Infinity; + + this.rect = null; + } + + /** + * Checks if bounds are empty. + * + * @return {boolean} True if empty. + */ + + + Bounds.prototype.isEmpty = function isEmpty() { + return this.minX > this.maxX || this.minY > this.maxY; + }; + + /** + * Clears the bounds and resets. + * + */ + + + Bounds.prototype.clear = function clear() { + this.updateID++; + + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * + * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty + * @returns {PIXI.Rectangle} A rectangle of the bounds + */ + + + Bounds.prototype.getRectangle = function getRectangle(rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return _math.Rectangle.EMPTY; + } + + rect = rect || new _math.Rectangle(0, 0, 1, 1); + + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + + return rect; + }; + + /** + * This function should be inlined when its possible. + * + * @param {PIXI.Point} point - The point to add. + */ + + + Bounds.prototype.addPoint = function addPoint(point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + }; + + /** + * Adds a quad, not transformed + * + * @param {Float32Array} vertices - The verts to add. + */ + + + Bounds.prototype.addQuad = function addQuad(vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = vertices[0]; + var y = vertices[1]; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds sprite frame, transformed. + * + * @param {PIXI.TransformBase} transform - TODO + * @param {number} x0 - TODO + * @param {number} y0 - TODO + * @param {number} x1 - TODO + * @param {number} y1 - TODO + */ + + + Bounds.prototype.addFrame = function addFrame(transform, x0, y0, x1, y1) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = a * x0 + c * y0 + tx; + var y = b * x0 + d * y0 + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y0 + tx; + y = b * x1 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x0 + c * y1 + tx; + y = b * x0 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y1 + tx; + y = b * x1 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Add an array of vertices + * + * @param {PIXI.TransformBase} transform - TODO + * @param {Float32Array} vertices - TODO + * @param {number} beginOffset - TODO + * @param {number} endOffset - TODO + */ + + + Bounds.prototype.addVertices = function addVertices(transform, vertices, beginOffset, endOffset) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = a * rawX + c * rawY + tx; + var y = d * rawY + b * rawX + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds other Bounds + * + * @param {PIXI.Bounds} bounds - TODO + */ + + + Bounds.prototype.addBounds = function addBounds(bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + }; + + /** + * Adds other Bounds, masked with Bounds + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Bounds} mask - TODO + */ + + + Bounds.prototype.addBoundsMask = function addBoundsMask(bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + /** + * Adds other Bounds, masked with Rectangle + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Rectangle} area - TODO + */ + + + Bounds.prototype.addBoundsArea = function addBoundsArea(bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : area.x + area.width; + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : area.y + area.height; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + return Bounds; +}(); + +exports.default = Bounds; + +},{"../math":102}],80:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _DisplayObject2 = require('./DisplayObject'); + +var _DisplayObject3 = _interopRequireDefault(_DisplayObject2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A Container represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + *```js + * let container = new PIXI.Container(); + * container.addChild(sprite); + * ``` + * + * @class + * @extends PIXI.DisplayObject + * @memberof PIXI + */ +var Container = function (_DisplayObject) { + _inherits(Container, _DisplayObject); + + /** + * + */ + function Container() { + _classCallCheck(this, Container); + + /** + * The array of children of this container. + * + * @member {PIXI.DisplayObject[]} + * @readonly + */ + var _this = _possibleConstructorReturn(this, _DisplayObject.call(this)); + + _this.children = []; + return _this; + } + + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified + * + * @private + */ + + + Container.prototype.onChildrenChange = function onChildrenChange() {} + /* empty */ + + + /** + * Adds a child or multiple children to the container. + * + * Multple items can be added like so: `myContainer.addChild(thinkOne, thingTwo, thingThree)` + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container + * @return {PIXI.DisplayObject} The first child that was added. + */ + ; + + Container.prototype.addChild = function addChild() { + for (var _len = arguments.length, childs = Array(_len), _key = 0; _key < _len; _key++) { + childs[_key] = arguments[_key]; + } + + for (var i = 0; i < childs.length; ++i) { + var child = childs[i]; + + // if the child has a parent then lets remove it as Pixi objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + + // ensure a transform will be recalculated.. + this.transform._parentID = -1; + this._boundsID++; + + this.children.push(child); + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + child.emit('added', this); + } + + return childs[0]; + }; + + /** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @return {PIXI.DisplayObject} The child that was added. + */ + + + Container.prototype.addChildAt = function addChildAt(child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error(child + 'addChildAt: The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + + this.children.splice(index, 0, child); + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + + return child; + }; + + /** + * Swaps the position of 2 Display Objects within this container. + * + * @param {PIXI.DisplayObject} child - First display object to swap + * @param {PIXI.DisplayObject} child2 - Second display object to swap + */ + + + Container.prototype.swapChildren = function swapChildren(child, child2) { + if (child === child2) { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + + if (index1 < 0 || index2 < 0) { + throw new Error('swapChildren: Both the supplied DisplayObjects must be children of the caller.'); + } + + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; + + /** + * Returns the index position of a child DisplayObject instance + * + * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify + * @return {number} The index position of the child display object to identify + */ + + + Container.prototype.getChildIndex = function getChildIndex(child) { + var index = this.children.indexOf(child); + + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + }; + + /** + * Changes the position of an existing child in the display object container + * + * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number + * @param {number} index - The resulting index number for the child display object + */ + + + Container.prototype.setChildIndex = function setChildIndex(child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + (0, _utils.removeItems)(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + this.onChildrenChange(index); + }; + + /** + * Returns the child at the specified index + * + * @param {number} index - The index to get the child at + * @return {PIXI.DisplayObject} The child at the given index, if any. + */ + + + Container.prototype.getChildAt = function getChildAt(index) { + if (index < 0 || index >= this.children.length) { + throw new Error('getChildAt: Index (' + index + ') does not exist.'); + } + + return this.children[index]; + }; + + /** + * Removes a child from the container. + * + * @param {...PIXI.DisplayObject} childs - The DisplayObject(s) to remove + * @return {PIXI.DisplayObject} The first child that was removed. + */ + + + Container.prototype.removeChild = function removeChild() { + for (var _len2 = arguments.length, childs = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + childs[_key2] = arguments[_key2]; + } + + for (var i = 0; i < childs.length; ++i) { + var child = childs[i]; + var index = this.children.indexOf(child); + + if (index === -1) continue; + + child.parent = null; + (0, _utils.removeItems)(this.children, index, 1); + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + } + + return childs[0]; + }; + + /** + * Removes a child from the specified index position. + * + * @param {number} index - The index to get the child from + * @return {PIXI.DisplayObject} The child that was removed. + */ + + + Container.prototype.removeChildAt = function removeChildAt(index) { + var child = this.getChildAt(index); + + child.parent = null; + (0, _utils.removeItems)(this.children, index, 1); + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + + return child; + }; + + /** + * Removes all children from this container that are within the begin and end indexes. + * + * @param {number} [beginIndex=0] - The beginning position. + * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. + * @returns {DisplayObject[]} List of removed children + */ + + + Container.prototype.removeChildren = function removeChildren() { + var beginIndex = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var endIndex = arguments[1]; + + var begin = beginIndex; + var end = typeof endIndex === 'number' ? endIndex : this.children.length; + var range = end - begin; + var removed = void 0; + + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + } + + this.onChildrenChange(beginIndex); + + for (var _i = 0; _i < removed.length; ++_i) { + removed[_i].emit('removed', this); + } + + return removed; + } else if (range === 0 && this.children.length === 0) { + return []; + } + + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + }; + + /** + * Updates the transform on all children of this container for rendering + * + * @private + */ + + + Container.prototype.updateTransform = function updateTransform() { + this._boundsID++; + + this.transform.updateTransform(this.parent.transform); + + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + + if (child.visible) { + child.updateTransform(); + } + } + }; + + /** + * Recalculates the bounds of the container. + * + */ + + + Container.prototype.calculateBounds = function calculateBounds() { + this._bounds.clear(); + + this._calculateBounds(); + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (!child.visible || !child.renderable) { + continue; + } + + child.calculateBounds(); + + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + child._mask.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, child._mask._bounds); + } else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } else { + this._bounds.addBounds(child._bounds); + } + } + + this._lastBoundsID = this._boundsID; + }; + + /** + * Recalculates the bounds of the object. Override this to + * calculate the bounds of the specific object (not including children). + * + */ + + + Container.prototype._calculateBounds = function _calculateBounds() {} + // FILL IN// + + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderWebGL = function renderWebGL(renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + // do a quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) { + this.renderAdvancedWebGL(renderer); + } else { + this._renderWebGL(renderer); + + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderWebGL(renderer); + } + } + }; + + /** + * Render the object using the WebGL renderer and advanced features. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { + renderer.currentRenderer.flush(); + + var filters = this._filters; + var mask = this._mask; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + + this._enabledFilters.length = 0; + + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + + if (this._enabledFilters.length) { + renderer.filterManager.pushFilter(this, this._enabledFilters); + } + } + + if (mask) { + renderer.maskManager.pushMask(this, this._mask); + } + + renderer.currentRenderer.start(); + + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); + + // now loop through the children and make sure they get rendered + for (var _i2 = 0, j = this.children.length; _i2 < j; _i2++) { + this.children[_i2].renderWebGL(renderer); + } + + renderer.currentRenderer.flush(); + + if (mask) { + renderer.maskManager.popMask(this, this._mask); + } + + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filterManager.popFilter(); + } + + renderer.currentRenderer.start(); + }; + + /** + * To be overridden by the subclasses. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype._renderWebGL = function _renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * To be overridden by the subclass + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype._renderCanvas = function _renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderCanvas = function renderCanvas(renderer) { + // if not visible or the alpha is 0 then no need to render this + if (!this.visible || this.alpha <= 0 || !this.renderable) { + return; + } + + if (this._mask) { + renderer.maskManager.pushMask(this._mask); + } + + this._renderCanvas(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderCanvas(renderer); + } + + if (this._mask) { + renderer.maskManager.popMask(renderer); + } + }; + + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + */ + + + Container.prototype.destroy = function destroy(options) { + _DisplayObject.prototype.destroy.call(this); + + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + + var oldChildren = this.removeChildren(0, this.children.length); + + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + }; + + /** + * The width of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Container# + */ + + + _createClass(Container, [{ + key: 'width', + get: function get() { + return this.scale.x * this.getLocalBounds().width; + } + + /** + * Sets the width of the container by modifying the scale. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + var width = this.getLocalBounds().width; + + if (width !== 0) { + this.scale.x = value / width; + } else { + this.scale.x = 1; + } + + this._width = value; + } + + /** + * The height of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Container# + */ + + }, { + key: 'height', + get: function get() { + return this.scale.y * this.getLocalBounds().height; + } + + /** + * Sets the height of the container by modifying the scale. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + var height = this.getLocalBounds().height; + + if (height !== 0) { + this.scale.y = value / height; + } else { + this.scale.y = 1; + } + + this._height = value; + } + }]); + + return Container; +}(_DisplayObject3.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = Container; +Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + +},{"../utils":152,"./DisplayObject":81}],81:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _const = require('../const'); + +var _TransformStatic = require('./TransformStatic'); + +var _TransformStatic2 = _interopRequireDefault(_TransformStatic); + +var _Transform = require('./Transform'); + +var _Transform2 = _interopRequireDefault(_Transform); + +var _Bounds = require('./Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _math = require('../math'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// _tempDisplayObjectParent = new DisplayObject(); + +/** + * The base class for all objects that are rendered on the screen. + * This is an abstract class and should not be used on its own rather it should be extended. + * + * @class + * @extends EventEmitter + * @mixes PIXI.interaction.interactiveTarget + * @memberof PIXI + */ +var DisplayObject = function (_EventEmitter) { + _inherits(DisplayObject, _EventEmitter); + + /** + * + */ + function DisplayObject() { + _classCallCheck(this, DisplayObject); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + var TransformClass = _const.TRANSFORM_MODE.DEFAULT === _const.TRANSFORM_MODE.STATIC ? _TransformStatic2.default : _Transform2.default; + + _this.tempDisplayObjectParent = null; + + // TODO: need to create Transform from factory + /** + * World transform and local transform of this object. + * This will become read-only later, please do not assign anything there unless you know what are you doing + * + * @member {PIXI.TransformBase} + */ + _this.transform = new TransformClass(); + + /** + * The opacity of the object. + * + * @member {number} + */ + _this.alpha = 1; + + /** + * The visibility of the object. If false the object will not be drawn, and + * the updateTransform function will not be called. + * + * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually + * + * @member {boolean} + */ + _this.visible = true; + + /** + * Can this object be rendered, if false the object will not be drawn but the updateTransform + * methods will still be called. + * + * Only affects recursive calls from parent. You can ask for bounds manually + * + * @member {boolean} + */ + _this.renderable = true; + + /** + * The display object container that contains this display object. + * + * @member {PIXI.Container} + * @readonly + */ + _this.parent = null; + + /** + * The multiplied alpha of the displayObject + * + * @member {number} + * @readonly + */ + _this.worldAlpha = 1; + + /** + * The area the filter is applied to. This is used as more of an optimisation + * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle + * + * Also works as an interaction mask + * + * @member {PIXI.Rectangle} + */ + _this.filterArea = null; + + _this._filters = null; + _this._enabledFilters = null; + + /** + * The bounds object, this is used to calculate and store the bounds of the displayObject + * + * @member {PIXI.Rectangle} + * @private + */ + _this._bounds = new _Bounds2.default(); + _this._boundsID = 0; + _this._lastBoundsID = -1; + _this._boundsRect = null; + _this._localBoundsRect = null; + + /** + * The original, cached mask of the object + * + * @member {PIXI.Rectangle} + * @private + */ + _this._mask = null; + return _this; + } + + /** + * @private + * @member {PIXI.DisplayObject} + */ + + + /** + * Updates the object transform for rendering + * + * TODO - Optimization pass! + */ + DisplayObject.prototype.updateTransform = function updateTransform() { + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + this._bounds.updateID++; + }; + + /** + * recursively updates transform of all objects from the root to this one + * internal function for toLocal() + */ + + + DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform() { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + }; + + /** + * Retrieves the bounds of the displayObject as a rectangle object. + * + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @param {PIXI.Rectangle} rect - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getBounds = function getBounds(skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + + if (this._boundsID !== this._lastBoundsID) { + this.calculateBounds(); + } + + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new _math.Rectangle(); + } + + rect = this._boundsRect; + } + + return this._bounds.getRectangle(rect); + }; + + /** + * Retrieves the local bounds of the displayObject as a rectangle object + * + * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getLocalBounds = function getLocalBounds(rect) { + var transformRef = this.transform; + var parentRef = this.parent; + + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + var bounds = this.getBounds(false, rect); + + this.parent = parentRef; + this.transform = transformRef; + + return bounds; + }; + + /** + * Calculates the global position of the display object + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform. + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toGlobal = function toGlobal(position, point) { + var skipUpdate = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; + + /** + * Calculates the local position of the display object relative to another point + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toLocal = function toLocal(position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + DisplayObject.prototype.renderCanvas = function renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Set the parent Container of this DisplayObject + * + * @param {PIXI.Container} container - The Container to add this DisplayObject to + * @return {PIXI.Container} The Container that this DisplayObject was added to + */ + ; + + DisplayObject.prototype.setParent = function setParent(container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); + } + + container.addChild(this); + + return container; + }; + + /** + * Convenience function to set the postion, scale, skew and pivot at once. + * + * @param {number} [x=0] - The X position + * @param {number} [y=0] - The Y position + * @param {number} [scaleX=1] - The X scale value + * @param {number} [scaleY=1] - The Y scale value + * @param {number} [rotation=0] - The rotation + * @param {number} [skewX=0] - The X skew value + * @param {number} [skewY=0] - The Y skew value + * @param {number} [pivotX=0] - The X pivot value + * @param {number} [pivotY=0] - The Y pivot value + * @return {PIXI.DisplayObject} The DisplayObject instance + */ + + + DisplayObject.prototype.setTransform = function setTransform() { + var x = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var y = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + var scaleX = arguments.length <= 2 || arguments[2] === undefined ? 1 : arguments[2]; + var scaleY = arguments.length <= 3 || arguments[3] === undefined ? 1 : arguments[3]; + var rotation = arguments.length <= 4 || arguments[4] === undefined ? 0 : arguments[4]; + var skewX = arguments.length <= 5 || arguments[5] === undefined ? 0 : arguments[5]; + var skewY = arguments.length <= 6 || arguments[6] === undefined ? 0 : arguments[6]; + var pivotX = arguments.length <= 7 || arguments[7] === undefined ? 0 : arguments[7]; + var pivotY = arguments.length <= 8 || arguments[8] === undefined ? 0 : arguments[8]; + + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + + return this; + }; + + /** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy`. + * + */ + + + DisplayObject.prototype.destroy = function destroy() { + this.removeAllListeners(); + if (this.parent) { + this.parent.removeChild(this); + } + this.transform = null; + + this.parent = null; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this.filterArea = null; + + this.interactive = false; + this.interactiveChildren = false; + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + * + * @member {number} + * @memberof PIXI.DisplayObject# + */ + + + _createClass(DisplayObject, [{ + key: '_tempDisplayObjectParent', + get: function get() { + if (this.tempDisplayObjectParent === null) { + this.tempDisplayObjectParent = new DisplayObject(); + } + + return this.tempDisplayObjectParent; + } + }, { + key: 'x', + get: function get() { + return this.position.x; + } + + /** + * Sets the X position of the object. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this.transform.position.x = value; + } + + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + * + * @member {number} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'y', + get: function get() { + return this.position.y; + } + + /** + * Sets the Y position of the object. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this.transform.position.y = value; + } + + /** + * Current transform of the object based on world (parent) factors + * + * @member {PIXI.Matrix} + * @memberof PIXI.DisplayObject# + * @readonly + */ + + }, { + key: 'worldTransform', + get: function get() { + return this.transform.worldTransform; + } + + /** + * Current transform of the object based on local factors: position, scale, other stuff + * + * @member {PIXI.Matrix} + * @memberof PIXI.DisplayObject# + * @readonly + */ + + }, { + key: 'localTransform', + get: function get() { + return this.transform.localTransform; + } + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'position', + get: function get() { + return this.transform.position; + } + + /** + * Copies the point to the position of the object. + * + * @param {PIXI.Point} value - The value to set to. + */ + , + set: function set(value) { + this.transform.position.copy(value); + } + + /** + * The scale factor of the object. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'scale', + get: function get() { + return this.transform.scale; + } + + /** + * Copies the point to the scale of the object. + * + * @param {PIXI.Point} value - The value to set to. + */ + , + set: function set(value) { + this.transform.scale.copy(value); + } + + /** + * The pivot point of the displayObject that it rotates around + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'pivot', + get: function get() { + return this.transform.pivot; + } + + /** + * Copies the point to the pivot of the object. + * + * @param {PIXI.Point} value - The value to set to. + */ + , + set: function set(value) { + this.transform.pivot.copy(value); + } + + /** + * The skew factor for the object in radians. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'skew', + get: function get() { + return this.transform.skew; + } + + /** + * Copies the point to the skew of the object. + * + * @param {PIXI.Point} value - The value to set to. + */ + , + set: function set(value) { + this.transform.skew.copy(value); + } + + /** + * The rotation of the object in radians. + * + * @member {number} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'rotation', + get: function get() { + return this.transform.rotation; + } + + /** + * Sets the rotation of the object. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this.transform.rotation = value; + } + + /** + * Indicates if the sprite is globally visible. + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + * @readonly + */ + + }, { + key: 'worldVisible', + get: function get() { + var item = this; + + do { + if (!item.visible) { + return false; + } + + item = item.parent; + } while (item); + + return true; + } + + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PIXI a regular mask must be a + * PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it + * utilises shape clipping. To remove a mask, set this property to null. + * + * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + * + * @member {PIXI.Graphics|PIXI.Sprite} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'mask', + get: function get() { + return this._mask; + } + + /** + * Sets the mask. + * + * @param {PIXI.Graphics|PIXI.Sprite} value - The value to set to. + */ + , + set: function set(value) { + if (this._mask) { + this._mask.renderable = true; + } + + this._mask = value; + + if (this._mask) { + this._mask.renderable = false; + } + } + + /** + * Sets the filters for the displayObject. + * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * To remove filters simply set this property to 'null' + * + * @member {PIXI.AbstractFilter[]} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'filters', + get: function get() { + return this._filters && this._filters.slice(); + } + + /** + * Shallow copies the array to the filters of the object. + * + * @param {PIXI.Filter[]} value - The filters to set. + */ + , + set: function set(value) { + this._filters = value && value.slice(); + } + }]); + + return DisplayObject; +}(_eventemitter2.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = DisplayObject; +DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + +},{"../const":78,"../math":102,"./Bounds":79,"./Transform":82,"./TransformStatic":84,"eventemitter3":16}],82:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Generic class to deal with traditional 2D matrix transforms + * local transformation is calculated from position,scale,skew and rotation + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var Transform = function (_TransformBase) { + _inherits(Transform, _TransformBase); + + /** + * + */ + function Transform() { + _classCallCheck(this, Transform); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.Point} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.Point(0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.Point} + */ + _this.scale = new _math.Point(1, 1); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.Point} + */ + _this.pivot = new _math.Point(0, 0); + + /** + * The rotation value of the object, in radians + * + * @member {Number} + * @private + */ + _this._rotation = 0; + + _this._sr = Math.sin(0); + _this._cr = Math.cos(0); + _this._cy = Math.cos(0); // skewY); + _this._sy = Math.sin(0); // skewY); + _this._nsx = Math.sin(0); // skewX); + _this._cx = Math.cos(0); // skewX); + return _this; + } + + /** + * Updates the skew values when the skew changes. + * + * @private + */ + + + Transform.prototype.updateSkew = function updateSkew() { + this._cy = Math.cos(this.skew.y); + this._sy = Math.sin(this.skew.y); + this._nsx = Math.sin(this.skew.x); + this._cx = Math.cos(this.skew.x); + }; + + /** + * Updates only local matrix + */ + + + Transform.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + var a = this._cr * this.scale.x; + var b = this._sr * this.scale.x; + var c = -this._sr * this.scale.y; + var d = this._cr * this.scale.y; + + lt.a = this._cy * a + this._sy * c; + lt.b = this._cy * b + this._sy * d; + lt.c = this._nsx * a + this._cx * c; + lt.d = this._nsx * b + this._cx * d; + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + Transform.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + var a = this._cr * this.scale.x; + var b = this._sr * this.scale.x; + var c = -this._sr * this.scale.y; + var d = this._cr * this.scale.y; + + lt.a = this._cy * a + this._sy * c; + lt.b = this._cy * b + this._sy * d; + lt.c = this._nsx * a + this._cx * c; + lt.d = this._nsx * b + this._cx * d; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + Transform.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + * @memberof PIXI.Transform# + */ + + + _createClass(Transform, [{ + key: 'rotation', + get: function get() { + return this._rotation; + } + + /** + * Set the rotation of the transform. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this._rotation = value; + this._sr = Math.sin(value); + this._cr = Math.cos(value); + } + }]); + + return Transform; +}(_TransformBase3.default); + +exports.default = Transform; + +},{"../math":102,"./TransformBase":83}],83:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Generic class to deal with traditional 2D matrix transforms + * + * @class + * @memberof PIXI + */ +var TransformBase = function () { + /** + * + */ + function TransformBase() { + _classCallCheck(this, TransformBase); + + /** + * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds() + * + * @member {PIXI.Matrix} + */ + this.worldTransform = new _math.Matrix(); + + /** + * The local matrix transform + * + * @member {PIXI.Matrix} + */ + this.localTransform = new _math.Matrix(); + + this._worldID = 0; + this._parentID = 0; + } + + /** + * TransformBase does not have decomposition, so this function wont do anything + */ + + + TransformBase.prototype.updateLocalTransform = function updateLocalTransform() {} + // empty + + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.TransformBase} parentTransform - The transform of the parent of this object + */ + ; + + TransformBase.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + return TransformBase; +}(); + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ + + +exports.default = TransformBase; +TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; + +TransformBase.IDENTITY = new TransformBase(); + +},{"../math":102}],84:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Transform that takes care about its versions + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var TransformStatic = function (_TransformBase) { + _inherits(TransformStatic, _TransformBase); + + /** + * + */ + function TransformStatic() { + _classCallCheck(this, TransformStatic); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.ObservablePoint} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.ObservablePoint} + */ + _this.scale = new _math.ObservablePoint(_this.onChange, _this, 1, 1); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.ObservablePoint} + */ + _this.pivot = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + _this._rotation = 0; + + _this._sr = Math.sin(0); + _this._cr = Math.cos(0); + _this._cy = Math.cos(0); // skewY); + _this._sy = Math.sin(0); // skewY); + _this._nsx = Math.sin(0); // skewX); + _this._cx = Math.cos(0); // skewX); + + _this._localID = 0; + _this._currentLocalID = 0; + return _this; + } + + /** + * Called when a value changes. + * + * @private + */ + + + TransformStatic.prototype.onChange = function onChange() { + this._localID++; + }; + + /** + * Called when skew changes + * + * @private + */ + + + TransformStatic.prototype.updateSkew = function updateSkew() { + this._cy = Math.cos(this.skew._y); + this._sy = Math.sin(this.skew._y); + this._nsx = Math.sin(this.skew._x); + this._cx = Math.cos(this.skew._x); + + this._localID++; + }; + + /** + * Updates only local matrix + */ + + + TransformStatic.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + var a = this._cr * this.scale._x; + var b = this._sr * this.scale._x; + var c = -this._sr * this.scale._y; + var d = this._cr * this.scale._y; + + lt.a = this._cy * a + this._sy * c; + lt.b = this._cy * b + this._sy * d; + lt.c = this._nsx * a + this._cx * c; + lt.d = this._nsx * b + this._cx * d; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + TransformStatic.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + var a = this._cr * this.scale._x; + var b = this._sr * this.scale._x; + var c = -this._sr * this.scale._y; + var d = this._cr * this.scale._y; + + lt.a = this._cy * a + this._sy * c; + lt.b = this._cy * b + this._sy * d; + lt.c = this._nsx * a + this._cx * c; + lt.d = this._nsx * b + this._cx * d; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._parentID = parentTransform._worldID; + + // update the id of the transform.. + this._worldID++; + } + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + TransformStatic.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + this._localID++; + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + * @memberof PIXI.TransformStatic# + */ + + + _createClass(TransformStatic, [{ + key: 'rotation', + get: function get() { + return this._rotation; + } + + /** + * Sets the rotation of the transform. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this._rotation = value; + this._sr = Math.sin(value); + this._cr = Math.cos(value); + this._localID++; + } + }]); + + return TransformStatic; +}(_TransformBase3.default); + +exports.default = TransformStatic; + +},{"../math":102,"./TransformBase":83}],85:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _GraphicsData = require('./GraphicsData'); + +var _GraphicsData2 = _interopRequireDefault(_GraphicsData); + +var _Sprite = require('../sprites/Sprite'); + +var _Sprite2 = _interopRequireDefault(_Sprite); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Bounds = require('../display/Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _bezierCurveTo2 = require('./utils/bezierCurveTo'); + +var _bezierCurveTo3 = _interopRequireDefault(_bezierCurveTo2); + +var _CanvasRenderer = require('../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var canvasRenderer = void 0; +var tempMatrix = new _math.Matrix(); +var tempPoint = new _math.Point(); +var tempColor1 = new Float32Array(4); +var tempColor2 = new Float32Array(4); + +/** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Graphics = function (_Container) { + _inherits(Graphics, _Container); + + /** + * + */ + function Graphics() { + _classCallCheck(this, Graphics); + + /** + * The alpha value used when filling the Graphics object. + * + * @member {number} + * @default 1 + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @member {number} + * @default 0 + */ + _this.lineWidth = 0; + + /** + * The color of any lines drawn. + * + * @member {string} + * @default 0 + */ + _this.lineColor = 0; + + /** + * Graphics data + * + * @member {PIXI.GraphicsData[]} + * @private + */ + _this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to + * reset the tint. + * + * @member {number} + * @default 0xFFFFFF + */ + _this.tint = 0xFFFFFF; + + /** + * The previous tint applied to the graphic shape. Used to compare to the current tint and + * check if theres change. + * + * @member {number} + * @private + * @default 0xFFFFFF + */ + _this._prevTint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * Current path + * + * @member {PIXI.GraphicsData} + * @private + */ + _this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @member {object} + * @private + */ + // TODO - _webgl should use a prototype object, not a random undocumented object... + _this._webGL = {}; + + /** + * Whether this shape is being used as a mask. + * + * @member {boolean} + */ + _this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @member {number} + */ + _this.boundsPadding = 0; + + /** + * A cache of the local bounds to prevent recalculation. + * + * @member {PIXI.Rectangle} + * @private + */ + _this._localBounds = new _Bounds2.default(); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics + * object will be recalculated. + * + * @member {boolean} + * @private + */ + _this.dirty = 0; + + /** + * Used to detect if we need to do a fast rect check using the id compare method + * @type {Number} + */ + _this.fastRectDirty = -1; + + /** + * Used to detect if we clear the graphics webGL data + * @type {Number} + */ + _this.clearDirty = 0; + + /** + * Used to detect if we we need to recalculate local bounds + * @type {Number} + */ + _this.boundsDirty = -1; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @member {boolean} + * @private + */ + _this.cachedSpriteDirty = false; + + _this._spriteRect = null; + _this._fastRect = false; + + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ + return _this; + } + + /** + * Creates a new Graphics object with the same values as this one. + * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) + * + * @return {PIXI.Graphics} A clone of the graphics object + */ + + + Graphics.prototype.clone = function clone() { + var clone = new Graphics(); + + clone.renderable = this.renderable; + clone.fillAlpha = this.fillAlpha; + clone.lineWidth = this.lineWidth; + clone.lineColor = this.lineColor; + clone.tint = this.tint; + clone.blendMode = this.blendMode; + clone.isMask = this.isMask; + clone.boundsPadding = this.boundsPadding; + clone.dirty = 0; + clone.cachedSpriteDirty = this.cachedSpriteDirty; + + // copy graphics data + for (var i = 0; i < this.graphicsData.length; ++i) { + clone.graphicsData.push(this.graphicsData[i].clone()); + } + + clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; + + clone.updateLocalBounds(); + + return clone; + }; + + /** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() + * method or the drawCircle() method. + * + * @param {number} [lineWidth=0] - width of the line to draw, will update the objects stored style + * @param {number} [color=0] - color of the line to draw, will update the objects stored style + * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineStyle = function lineStyle() { + var lineWidth = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var color = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + var alpha = arguments.length <= 2 || arguments[2] === undefined ? 1 : arguments[2]; + + this.lineWidth = lineWidth; + this.lineColor = color; + this.lineAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length) { + // halfway through a line? start a new one! + var shape = new _math.Polygon(this.currentPath.shape.points.slice(-2)); + + shape.closed = false; + + this.drawShape(shape); + } else { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + }; + + /** + * Moves the current drawing position to x, y. + * + * @param {number} x - the X coordinate to move to + * @param {number} y - the Y coordinate to move to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.moveTo = function moveTo(x, y) { + var shape = new _math.Polygon([x, y]); + + shape.closed = false; + this.drawShape(shape); + + return this; + }; + + /** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @param {number} x - the X coordinate to draw to + * @param {number} y - the Y coordinate to draw to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineTo = function lineTo(x, y) { + this.currentPath.shape.points.push(x, y); + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.quadraticCurveTo = function quadraticCurveTo(cpX, cpY, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var n = 20; + var points = this.currentPath.shape.points; + var xa = 0; + var ya = 0; + + if (points.length === 0) { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + for (var i = 1; i <= n; ++i) { + var j = i / n; + + xa = fromX + (cpX - fromX) * j; + ya = fromY + (cpY - fromY) * j; + + points.push(xa + (cpX + (toX - cpX) * j - xa) * j, ya + (cpY + (toY - cpY) * j - ya) * j); + } + + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a bezier curve and then draws it. + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.bezierCurveTo = function bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + points.length -= 2; + + (0, _bezierCurveTo3.default)(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, points); + + this.dirty++; + + return this; + }; + + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @param {number} x1 - The x-coordinate of the beginning of the arc + * @param {number} y1 - The y-coordinate of the beginning of the arc + * @param {number} x2 - The x-coordinate of the end of the arc + * @param {number} y2 - The y-coordinate of the end of the arc + * @param {number} radius - The radius of the arc + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arcTo = function arcTo(x1, y1, x2, y2, radius) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points.push(x1, y1); + } + } else { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + } else { + var dd = a1 * a1 + b1 * b1; + var cc = a2 * a2 + b2 * b2; + var tt = a1 * a2 + b1 * b2; + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = k1 * b2 + k2 * b1; + var cy = k1 * a2 + k2 * a1; + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty++; + + return this; + }; + + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @param {number} cx - The x-coordinate of the center of the circle + * @param {number} cy - The y-coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param {number} endAngle - The ending angle, in radians + * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arc = function arc(cx, cy, radius, startAngle, endAngle) { + var anticlockwise = arguments.length <= 5 || arguments[5] === undefined ? false : arguments[5]; + + if (startAngle === endAngle) { + return this; + } + + if (!anticlockwise && endAngle <= startAngle) { + endAngle += Math.PI * 2; + } else if (anticlockwise && startAngle <= endAngle) { + startAngle += Math.PI * 2; + } + + var sweep = anticlockwise ? (startAngle - endAngle) * -1 : endAngle - startAngle; + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * 40; + + if (sweep === 0) { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + if (this.currentPath) { + this.currentPath.shape.points.push(startX, startY); + } else { + this.moveTo(startX, startY); + } + + var points = this.currentPath.shape.points; + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = segMinus % 1 / segMinus; + + for (var i = 0; i <= segMinus; ++i) { + var real = i + remainder * i; + + var angle = theta + startAngle + theta2 * real; + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push((cTheta * c + sTheta * s) * radius + cx, (cTheta * -s + sTheta * c) * radius + cy); + } + + this.dirty++; + + return this; + }; + + /** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @param {number} [color=0] - the color of the fill + * @param {number} [alpha=1] - the alpha of the fill + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.beginFill = function beginFill() { + var color = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var alpha = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1]; + + this.filling = true; + this.fillColor = color; + this.fillAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length <= 2) { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + }; + + /** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.endFill = function endFill() { + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRect = function drawRect(x, y, width, height) { + this.drawShape(new _math.Rectangle(x, y, width, height)); + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @param {number} radius - Radius of the rectangle corners + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRoundedRect = function drawRoundedRect(x, y, width, height, radius) { + this.drawShape(new _math.RoundedRectangle(x, y, width, height, radius)); + + return this; + }; + + /** + * Draws a circle. + * + * @param {number} x - The X coordinate of the center of the circle + * @param {number} y - The Y coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawCircle = function drawCircle(x, y, radius) { + this.drawShape(new _math.Circle(x, y, radius)); + + return this; + }; + + /** + * Draws an ellipse. + * + * @param {number} x - The X coordinate of the center of the ellipse + * @param {number} y - The Y coordinate of the center of the ellipse + * @param {number} width - The half width of the ellipse + * @param {number} height - The half height of the ellipse + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawEllipse = function drawEllipse(x, y, width, height) { + this.drawShape(new _math.Ellipse(x, y, width, height)); + + return this; + }; + + /** + * Draws a polygon using the given path. + * + * @param {number[]|PIXI.Point[]} path - The path data used to construct the polygon. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawPolygon = function drawPolygon(path) { + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + var closed = true; + + if (points instanceof _math.Polygon) { + closed = points.closed; + points = points.points; + } + + if (!Array.isArray(points)) { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) { + points[i] = arguments[i]; // eslint-disable-line prefer-rest-params + } + } + + var shape = new _math.Polygon(points); + + shape.closed = closed; + + this.drawShape(shape); + + return this; + }; + + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.clear = function clear() { + if (this.lineWidth || this.filling || this.graphicsData.length > 0) { + this.lineWidth = 0; + this.filling = false; + + this.dirty++; + this.clearDirty++; + this.graphicsData.length = 0; + } + + return this; + }; + + /** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. + * + * @returns {boolean} True if only 1 rect. + */ + + + Graphics.prototype.isFastRect = function isFastRect() { + return this.graphicsData.length === 1 && this.graphicsData[0].shape.type === _const.SHAPES.RECT && !this.graphicsData[0].lineWidth; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderWebGL = function _renderWebGL(renderer) { + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.dirty !== this.fastRectDirty) { + this.fastRectDirty = this.dirty; + this._fastRect = this.isFastRect(); + } + + // TODO this check can be moved to dirty? + if (this._fastRect) { + this._renderSpriteRect(renderer); + } else { + renderer.setObjectRenderer(renderer.plugins.graphics); + renderer.plugins.graphics.render(this); + } + }; + + /** + * Renders a sprite rectangle. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderSpriteRect = function _renderSpriteRect(renderer) { + var rect = this.graphicsData[0].shape; + + if (!this._spriteRect) { + if (!Graphics._SPRITE_TEXTURE) { + Graphics._SPRITE_TEXTURE = _RenderTexture2.default.create(10, 10); + + var canvas = document.createElement('canvas'); + + canvas.width = 10; + canvas.height = 10; + + var context = canvas.getContext('2d'); + + context.fillStyle = 'white'; + context.fillRect(0, 0, 10, 10); + + Graphics._SPRITE_TEXTURE = _Texture2.default.fromCanvas(canvas); + } + + this._spriteRect = new _Sprite2.default(Graphics._SPRITE_TEXTURE); + } + if (this.tint === 0xffffff) { + this._spriteRect.tint = this.graphicsData[0].fillColor; + } else { + var t1 = tempColor1; + var t2 = tempColor2; + + (0, _utils.hex2rgb)(this.graphicsData[0].fillColor, t1); + (0, _utils.hex2rgb)(this.tint, t2); + + t1[0] *= t2[0]; + t1[1] *= t2[1]; + t1[2] *= t2[2]; + + this._spriteRect.tint = (0, _utils.rgb2hex)(t1); + } + this._spriteRect.alpha = this.graphicsData[0].fillAlpha; + this._spriteRect.worldAlpha = this.worldAlpha * this._spriteRect.alpha; + + Graphics._SPRITE_TEXTURE._frame.width = rect.width; + Graphics._SPRITE_TEXTURE._frame.height = rect.height; + + this._spriteRect.transform.worldTransform = this.transform.worldTransform; + + this._spriteRect.anchor.set(-rect.x / rect.width, -rect.y / rect.height); + this._spriteRect._onAnchorUpdate(); + + this._spriteRect._renderWebGL(renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.isMask === true) { + return; + } + + renderer.plugins.graphics.render(this); + }; + + /** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @private + */ + + + Graphics.prototype._calculateBounds = function _calculateBounds() { + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.updateLocalBounds(); + + this.dirty++; + this.cachedSpriteDirty = true; + } + + var lb = this._localBounds; + + this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); + }; + + /** + * Tests if a point is inside this graphics object + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Graphics.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + + if (!data.fill) { + continue; + } + + // only deal with fills.. + if (data.shape) { + if (data.shape.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + } + + return false; + }; + + /** + * Update the bounds of the object + * + */ + + + Graphics.prototype.updateLocalBounds = function updateLocalBounds() { + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) { + var shape = 0; + var x = 0; + var y = 0; + var w = 0; + var h = 0; + + for (var i = 0; i < this.graphicsData.length; i++) { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + + shape = data.shape; + + if (type === _const.SHAPES.RECT || type === _const.SHAPES.RREC) { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.CIRC) { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.ELIP) { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else { + // POLY + var points = shape.points; + + for (var j = 0; j < points.length; j += 2) { + x = points[j]; + y = points[j + 1]; + + minX = x - lineWidth < minX ? x - lineWidth : minX; + maxX = x + lineWidth > maxX ? x + lineWidth : maxX; + + minY = y - lineWidth < minY ? y - lineWidth : minY; + maxY = y + lineWidth > maxY ? y + lineWidth : maxY; + } + } + } + } else { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.minX = minX - padding; + this._localBounds.maxX = maxX + padding * 2; + + this._localBounds.minY = minY - padding; + this._localBounds.maxY = maxY + padding * 2; + }; + + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @return {PIXI.GraphicsData} The generated GraphicsData object. + */ + + + Graphics.prototype.drawShape = function drawShape(shape) { + if (this.currentPath) { + // check current path! + if (this.currentPath.shape.points.length <= 2) { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + var data = new _GraphicsData2.default(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape); + + this.graphicsData.push(data); + + if (data.type === _const.SHAPES.POLY) { + data.shape.closed = data.shape.closed || this.filling; + this.currentPath = data; + } + + this.dirty++; + + return data; + }; + + /** + * Generates a canvas texture. + * + * @param {number} scaleMode - The scale mode of the texture. + * @param {number} resolution - The resolution of the texture. + * @return {PIXI.Texture} The new texture. + */ + + + Graphics.prototype.generateCanvasTexture = function generateCanvasTexture(scaleMode) { + var resolution = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1]; + + var bounds = this.getLocalBounds(); + + var canvasBuffer = _RenderTexture2.default.create(bounds.width, bounds.height, scaleMode, resolution); + + if (!canvasRenderer) { + canvasRenderer = new _CanvasRenderer2.default(); + } + + tempMatrix.tx = -bounds.x; + tempMatrix.ty = -bounds.y; + + canvasRenderer.render(this, canvasBuffer, false, tempMatrix); + + var texture = _Texture2.default.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas, scaleMode); + + texture.baseTexture.resolution = resolution; + texture.baseTexture.update(); + + return texture; + }; + + /** + * Closes the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.closePath = function closePath() { + // ok so close path assumes next one is a hole! + var currentPath = this.currentPath; + + if (currentPath && currentPath.shape) { + currentPath.shape.close(); + } + + return this; + }; + + /** + * Adds a hole in the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.addHole = function addHole() { + // this is a hole! + var hole = this.graphicsData.pop(); + + this.currentPath = this.graphicsData[this.graphicsData.length - 1]; + + this.currentPath.addHole(hole.shape); + this.currentPath = null; + + return this; + }; + + /** + * Destroys the Graphics object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + */ + + + Graphics.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._webgl) { + for (var j = 0; j < this._webgl[id].data.length; ++j) { + this._webgl[id].data[j].destroy(); + } + } + + if (this._spriteRect) { + this._spriteRect.destroy(); + } + + this.graphicsData = null; + + this.currentPath = null; + this._webgl = null; + this._localBounds = null; + }; + + return Graphics; +}(_Container3.default); + +exports.default = Graphics; + + +Graphics._SPRITE_TEXTURE = null; + +},{"../const":78,"../display/Bounds":79,"../display/Container":80,"../math":102,"../renderers/canvas/CanvasRenderer":109,"../sprites/Sprite":133,"../textures/RenderTexture":143,"../textures/Texture":144,"../utils":152,"./GraphicsData":86,"./utils/bezierCurveTo":88}],86:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + */ +var GraphicsData = function () { + /** + * + * @param {number} lineWidth - the width of the line to draw + * @param {number} lineColor - the color of the line to draw + * @param {number} lineAlpha - the alpha of the line to draw + * @param {number} fillColor - the color of the fill + * @param {number} fillAlpha - the alpha of the fill + * @param {boolean} fill - whether or not the shape is filled with a colour + * @param {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} shape - The shape object to draw. + */ + function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { + _classCallCheck(this, GraphicsData); + + /** + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + + /** + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /** + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /** + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /** + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /** + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /** + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /** + * @member {boolean} whether or not the shape is filled with a colour + */ + this.fill = fill; + + this.holes = []; + + /** + * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} The shape object to draw. + */ + this.shape = shape; + + /** + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + } + + /** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {PIXI.GraphicsData} Cloned GraphicsData object + */ + + + GraphicsData.prototype.clone = function clone() { + return new GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.fill, this.shape); + }; + + /** + * Adds a hole to the shape. + * + * @param {PIXI.Rectangle|PIXI.Circle} shape - The shape of the hole. + */ + + + GraphicsData.prototype.addHole = function addHole(shape) { + this.holes.push(shape); + }; + + /** + * Destroys the Graphics data. + */ + + + GraphicsData.prototype.destroy = function destroy() { + this.shape = null; + this.holes = null; + }; + + return GraphicsData; +}(); + +exports.default = GraphicsData; + +},{}],87:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they + * now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasGraphicsRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasGraphicsRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching graphics objects. + * + * @class + * @private + * @memberof PIXI + */ +var CanvasGraphicsRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The current PIXI renderer. + */ + function CanvasGraphicsRenderer(renderer) { + _classCallCheck(this, CanvasGraphicsRenderer); + + this.renderer = renderer; + } + + /** + * Renders a Graphics object to a canvas. + * + * @param {PIXI.Graphics} graphics - the actual graphics object to render + */ + + + CanvasGraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var context = renderer.context; + var worldAlpha = graphics.worldAlpha; + var transform = graphics.transform.worldTransform; + var resolution = renderer.resolution; + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) { + this.dirty = true; + } + + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + if (graphics.dirty) { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + renderer.setBlendMode(graphics.blendMode); + + for (var i = 0; i < graphics.graphicsData.length; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === _const.SHAPES.POLY) { + context.beginPath(); + + this.renderPolygon(shape.points, shape.closed, context); + + for (var j = 0; j < data.holes.length; j++) { + this.renderPolygon(data.holes[j].points, true, context); + } + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RECT) { + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + context.beginPath(); + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + }; + + /** + * Updates the tint of a graphics object + * + * @private + * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated + */ + + + CanvasGraphicsRenderer.prototype.updateGraphicsTint = function updateGraphicsTint(graphics) { + graphics._prevTint = graphics.tint; + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF) / 255; + + for (var i = 0; i < graphics.graphicsData.length; ++i) { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + // super inline cos im an optimization NAZI :) + data._fillTint = ((fillColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (fillColor & 0xFF) / 255 * tintB * 255; + + data._lineTint = ((lineColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (lineColor & 0xFF) / 255 * tintB * 255; + } + }; + + /** + * Renders a polygon. + * + * @param {PIXI.Point[]} points - The points to render + * @param {boolean} close - Should the polygon be closed + * @param {CanvasRenderingContext2D} context - The rendering context to use + */ + + + CanvasGraphicsRenderer.prototype.renderPolygon = function renderPolygon(points, close, context) { + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; ++j) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (close) { + context.closePath(); + } + }; + + /** + * destroy graphics object + * + */ + + + CanvasGraphicsRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasGraphicsRenderer; +}(); + +exports.default = CanvasGraphicsRenderer; + + +_CanvasRenderer2.default.registerPlugin('graphics', CanvasGraphicsRenderer); + +},{"../../const":78,"../../renderers/canvas/CanvasRenderer":109}],88:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = bezierCurveTo; +/** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [path=[]] - Path array to push points into + * @return {number[]} Array of points of the curve + */ +function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var path = arguments.length <= 8 || arguments[8] === undefined ? [] : arguments[8]; + + var n = 20; + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + + path.push(fromX, fromY); + + for (var i = 1, j = 0; i <= n; ++i) { + j = i / n; + + dt = 1 - j; + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + path.push(dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + return path; +} + +},{}],89:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _WebGLGraphicsData = require('./WebGLGraphicsData'); + +var _WebGLGraphicsData2 = _interopRequireDefault(_WebGLGraphicsData); + +var _PrimitiveShader = require('./shaders/PrimitiveShader'); + +var _PrimitiveShader2 = _interopRequireDefault(_PrimitiveShader); + +var _buildPoly = require('./utils/buildPoly'); + +var _buildPoly2 = _interopRequireDefault(_buildPoly); + +var _buildRectangle = require('./utils/buildRectangle'); + +var _buildRectangle2 = _interopRequireDefault(_buildRectangle); + +var _buildRoundedRectangle = require('./utils/buildRoundedRectangle'); + +var _buildRoundedRectangle2 = _interopRequireDefault(_buildRoundedRectangle); + +var _buildCircle = require('./utils/buildCircle'); + +var _buildCircle2 = _interopRequireDefault(_buildCircle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Renders the graphics object. + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var GraphicsRenderer = function (_ObjectRenderer) { + _inherits(GraphicsRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this object renderer works for. + */ + function GraphicsRenderer(renderer) { + _classCallCheck(this, GraphicsRenderer); + + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.graphicsDataPool = []; + + _this.primitiveShader = null; + + _this.gl = renderer.gl; + + // easy access! + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * Called when there is a WebGL context change + * + * @private + * + */ + + + GraphicsRenderer.prototype.onContextChange = function onContextChange() { + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.primitiveShader = new _PrimitiveShader2.default(this.gl); + }; + + /** + * Destroys this renderer. + * + */ + + + GraphicsRenderer.prototype.destroy = function destroy() { + _ObjectRenderer3.default.prototype.destroy.call(this); + + for (var i = 0; i < this.graphicsDataPool.length; ++i) { + this.graphicsDataPool[i].destroy(); + } + + this.graphicsDataPool = null; + }; + + /** + * Renders a graphics object. + * + * @param {PIXI.Graphics} graphics - The graphics object to render. + */ + + + GraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var gl = renderer.gl; + + var webGLData = void 0; + var webGL = graphics._webGL[this.CONTEXT_UID]; + + if (!webGL || graphics.dirty !== webGL.dirty) { + this.updateGraphics(graphics); + + webGL = graphics._webGL[this.CONTEXT_UID]; + } + + // This could be speeded up for sure! + var shader = this.primitiveShader; + + renderer.bindShader(shader); + renderer.state.setBlendMode(graphics.blendMode); + + for (var i = 0, n = webGL.data.length; i < n; i++) { + webGLData = webGL.data[i]; + var shaderTemp = webGLData.shader; + + renderer.bindShader(shaderTemp); + shaderTemp.uniforms.translationMatrix = graphics.transform.worldTransform.toArray(true); + shaderTemp.uniforms.tint = (0, _utils.hex2rgb)(graphics.tint); + shaderTemp.uniforms.alpha = graphics.worldAlpha; + + webGLData.vao.bind().draw(gl.TRIANGLE_STRIP, webGLData.indices.length).unbind(); + } + }; + + /** + * Updates the graphics object + * + * @private + * @param {PIXI.Graphics} graphics - The graphics object to update + */ + + + GraphicsRenderer.prototype.updateGraphics = function updateGraphics(graphics) { + var gl = this.renderer.gl; + + // get the contexts graphics object + var webGL = graphics._webGL[this.CONTEXT_UID]; + + // if the graphics object does not exist in the webGL context time to create it! + if (!webGL) { + webGL = graphics._webGL[this.CONTEXT_UID] = { lastIndex: 0, data: [], gl: gl, clearDirty: -1, dirty: -1 }; + } + + // flag the graphics as not dirty as we are about to update it... + webGL.dirty = graphics.dirty; + + // if the user cleared the graphics object we will need to clear every object + if (graphics.clearDirty !== webGL.clearDirty) { + webGL.clearDirty = graphics.clearDirty; + + // loop through and return all the webGLDatas to the object pool so than can be reused later on + for (var i = 0; i < webGL.data.length; i++) { + this.graphicsDataPool.push(webGL.data[i]); + } + + // clear the array and reset the index.. + webGL.data.length = 0; + webGL.lastIndex = 0; + } + + var webGLData = void 0; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (var _i = webGL.lastIndex; _i < graphics.graphicsData.length; _i++) { + var data = graphics.graphicsData[_i]; + + // TODO - this can be simplified + webGLData = this.getWebGLData(webGL, 0); + + if (data.type === _const.SHAPES.POLY) { + (0, _buildPoly2.default)(data, webGLData); + } + if (data.type === _const.SHAPES.RECT) { + (0, _buildRectangle2.default)(data, webGLData); + } else if (data.type === _const.SHAPES.CIRC || data.type === _const.SHAPES.ELIP) { + (0, _buildCircle2.default)(data, webGLData); + } else if (data.type === _const.SHAPES.RREC) { + (0, _buildRoundedRectangle2.default)(data, webGLData); + } + + webGL.lastIndex++; + } + + // upload all the dirty data... + for (var _i2 = 0; _i2 < webGL.data.length; _i2++) { + webGLData = webGL.data[_i2]; + + if (webGLData.dirty) { + webGLData.upload(); + } + } + }; + + /** + * + * @private + * @param {WebGLRenderingContext} gl - the current WebGL drawing context + * @param {number} type - TODO @Alvin + * @return {*} TODO + */ + + + GraphicsRenderer.prototype.getWebGLData = function getWebGLData(gl, type) { + var webGLData = gl.data[gl.data.length - 1]; + + if (!webGLData || webGLData.points.length > 320000) { + webGLData = this.graphicsDataPool.pop() || new _WebGLGraphicsData2.default(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + + webGLData.reset(type); + gl.data.push(webGLData); + } + + webGLData.dirty = true; + + return webGLData; + }; + + return GraphicsRenderer; +}(_ObjectRenderer3.default); + +exports.default = GraphicsRenderer; + + +_WebGLRenderer2.default.registerPlugin('graphics', GraphicsRenderer); + +},{"../../const":78,"../../renderers/webgl/WebGLRenderer":116,"../../renderers/webgl/utils/ObjectRenderer":126,"../../utils":152,"./WebGLGraphicsData":90,"./shaders/PrimitiveShader":91,"./utils/buildCircle":92,"./utils/buildPoly":94,"./utils/buildRectangle":95,"./utils/buildRoundedRectangle":96}],90:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * An object containing WebGL specific properties to be used by the WebGL renderer + * + * @class + * @private + * @memberof PIXI + */ +var WebGLGraphicsData = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {PIXI.Shader} shader - The shader + * @param {object} attribsState - The state for the VAO + */ + function WebGLGraphicsData(gl, shader, attribsState) { + _classCallCheck(this, WebGLGraphicsData); + + /** + * The current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // TODO does this need to be split before uploding?? + /** + * An array of color components (r,g,b) + * @member {number[]} + */ + this.color = [0, 0, 0]; // color split! + + /** + * An array of points to draw + * @member {PIXI.Point[]} + */ + this.points = []; + + /** + * The indices of the vertices + * @member {number[]} + */ + this.indices = []; + /** + * The main buffer + * @member {WebGLBuffer} + */ + this.buffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl); + + /** + * The index buffer + * @member {WebGLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl); + + /** + * Whether this graphics is dirty or not + * @member {boolean} + */ + this.dirty = true; + + this.glPoints = null; + this.glIndices = null; + + /** + * + * @member {PIXI.Shader} + */ + this.shader = shader; + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, attribsState).addIndex(this.indexBuffer).addAttribute(this.buffer, shader.attributes.aVertexPosition, gl.FLOAT, false, 4 * 6, 0).addAttribute(this.buffer, shader.attributes.aColor, gl.FLOAT, false, 4 * 6, 2 * 4); + } + + /** + * Resets the vertices and the indices + */ + + + WebGLGraphicsData.prototype.reset = function reset() { + this.points.length = 0; + this.indices.length = 0; + }; + + /** + * Binds the buffers and uploads the data + */ + + + WebGLGraphicsData.prototype.upload = function upload() { + this.glPoints = new Float32Array(this.points); + this.buffer.upload(this.glPoints); + + this.glIndices = new Uint16Array(this.indices); + this.indexBuffer.upload(this.glIndices); + + this.dirty = false; + }; + + /** + * Empties all the data + */ + + + WebGLGraphicsData.prototype.destroy = function destroy() { + this.color = null; + this.points = null; + this.indices = null; + + this.vao.destroy(); + this.buffer.destroy(); + this.indexBuffer.destroy(); + + this.gl = null; + + this.buffer = null; + this.indexBuffer = null; + + this.glPoints = null; + this.glIndices = null; + }; + + return WebGLGraphicsData; +}(); + +exports.default = WebGLGraphicsData; + +},{"pixi-gl-core":51}],91:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../../Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. + * + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ +var PrimitiveShader = function (_Shader) { + _inherits(PrimitiveShader, _Shader); + + /** + * @param {WebGLRenderingContext} gl - The webgl shader manager this shader works for. + */ + function PrimitiveShader(gl) { + _classCallCheck(this, PrimitiveShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec4 aColor;', 'uniform mat3 translationMatrix;', 'uniform mat3 projectionMatrix;', 'uniform float alpha;', 'uniform vec3 tint;', 'varying vec4 vColor;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vColor = aColor * vec4(tint * alpha, alpha);', '}'].join('\n'), + // fragment shader + ['varying vec4 vColor;', 'void main(void){', ' gl_FragColor = vColor;', '}'].join('\n'))); + } + + return PrimitiveShader; +}(_Shader3.default); + +exports.default = PrimitiveShader; + +},{"../../../Shader":77}],92:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildCircle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _const = require('../../../const'); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildCircle(graphicsData, webGLData) { + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width = void 0; + var height = void 0; + + // TODO - bit hacky?? + if (graphicsData.type === _const.SHAPES.CIRC) { + width = circleData.radius; + height = circleData.radius; + } else { + width = circleData.width; + height = circleData.height; + } + + var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); + + var seg = Math.PI * 2 / totalSegs; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + indices.push(vecPos); + + for (var i = 0; i < totalSegs + 1; i++) { + verts.push(x, y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos - 1); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (var _i = 0; _i < totalSegs + 1; _i++) { + graphicsData.points.push(x + Math.sin(seg * _i) * width, y + Math.cos(seg * _i) * height); + } + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +},{"../../../const":78,"../../../utils":152,"./buildLine":93}],93:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildLine; + +var _math = require('../../../math'); + +var _utils = require('../../../utils'); + +/** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildLine(graphicsData, webGLData) { + // TODO OPTIMISE! + var points = graphicsData.points; + + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + + // get first and last point.. figure out the middle! + var firstPoint = new _math.Point(points[0], points[1]); + var lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + // if the first point is the last point - gonna have issues :) + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var p1x = points[0]; + var p1y = points[1]; + var p2x = points[2]; + var p2y = points[3]; + var p3x = 0; + var p3y = 0; + + var perpx = -(p1y - p2y); + var perpy = p1x - p2x; + var perp2x = 0; + var perp2y = 0; + var perp3x = 0; + var perp3y = 0; + + var dist = Math.sqrt(perpx * perpx + perpy * perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx, p1y - perpy, r, g, b, alpha); + + verts.push(p1x + perpx, p1y + perpy, r, g, b, alpha); + + for (var i = 1; i < length - 1; ++i) { + p1x = points[(i - 1) * 2]; + p1y = points[(i - 1) * 2 + 1]; + + p2x = points[i * 2]; + p2y = points[i * 2 + 1]; + + p3x = points[(i + 1) * 2]; + p3y = points[(i + 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + var a1 = -perpy + p1y - (-perpy + p2y); + var b1 = -perpx + p2x - (-perpx + p1x); + var c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + var a2 = -perp2y + p3y - (-perp2y + p2y); + var b2 = -perp2x + p2x - (-perp2x + p3x); + var c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + var denom = a1 * b2 - a2 * b1; + + if (Math.abs(denom) < 0.1) { + denom += 10.1; + verts.push(p2x - perpx, p2y - perpy, r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy, r, g, b, alpha); + + continue; + } + + var px = (b1 * c2 - b2 * c1) / denom; + var py = (a2 * c1 - a1 * c2) / denom; + var pdist = (px - p2x) * (px - p2x) + (py - p2y) * (py - p2y); + + if (pdist > 196 * width * width) { + perp3x = perpx - perp2x; + perp3y = perpy - perp2y; + + dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y); + perp3x /= dist; + perp3y /= dist; + perp3x *= width; + perp3y *= width; + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x + perp3x, p2y + perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + indexCount++; + } else { + verts.push(px, py); + verts.push(r, g, b, alpha); + + verts.push(p2x - (px - p2x), p2y - (py - p2y)); + verts.push(r, g, b, alpha); + } + } + + p1x = points[(length - 2) * 2]; + p1y = points[(length - 2) * 2 + 1]; + + p2x = points[(length - 1) * 2]; + p2y = points[(length - 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + verts.push(p2x - perpx, p2y - perpy); + verts.push(r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy); + verts.push(r, g, b, alpha); + + indices.push(indexStart); + + for (var _i = 0; _i < indexCount; ++_i) { + indices.push(indexStart++); + } + + indices.push(indexStart - 1); +} + +},{"../../../math":102,"../../../utils":152}],94:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildPoly; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildPoly(graphicsData, webGLData) { + graphicsData.points = graphicsData.shape.points.slice(); + + var points = graphicsData.points; + + if (graphicsData.fill && points.length >= 6) { + var holeArray = []; + // Process holes.. + var holes = graphicsData.holes; + + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + + holeArray.push(points.length / 2); + + points = points.concat(hole.points); + } + + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = (0, _earcut2.default)(points, holeArray, 2); + + if (!triangles) { + return; + } + + var vertPos = verts.length / 6; + + for (var _i = 0; _i < triangles.length; _i += 3) { + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i + 1] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + } + + for (var _i2 = 0; _i2 < length; _i2++) { + verts.push(points[_i2 * 2], points[_i2 * 2 + 1], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth > 0) { + (0, _buildLine2.default)(graphicsData, webGLData); + } +} + +},{"../../../utils":152,"./buildLine":93,"earcut":15}],95:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRectangle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildRectangle(graphicsData, webGLData) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vertPos = verts.length / 6; + + // start + verts.push(x, y); + verts.push(r, g, b, alpha); + + verts.push(x + width, y); + verts.push(r, g, b, alpha); + + verts.push(x, y + height); + verts.push(r, g, b, alpha); + + verts.push(x + width, y + height); + verts.push(r, g, b, alpha); + + // insert 2 dead triangles.. + indices.push(vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y]; + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +},{"../../../utils":152,"./buildLine":93}],96:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRoundedRectangle; + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildRoundedRectangle(graphicsData, webGLData) { + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + + recPoints.push(x, y + radius); + quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height, recPoints); + quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius, recPoints); + quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y, recPoints); + quadraticBezierCurve(x + radius, y, x, y, x, y + radius + 0.0000000001, recPoints); + + // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. + // TODO - fix this properly, this is not very elegant.. but it works for now. + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + var triangles = (0, _earcut2.default)(recPoints, null, 2); + + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + + for (var _i = 0, _j = recPoints.length; _i < _j; _i++) { + verts.push(recPoints[_i], recPoints[++_i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @return {number[]} an array of points + */ +function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY) { + var out = arguments.length <= 6 || arguments[6] === undefined ? [] : arguments[6]; + + var n = 20; + var points = out; + + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + + function getPt(n1, n2, perc) { + var diff = n2 - n1; + + return n1 + diff * perc; + } + + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + + points.push(x, y); + } + + return points; +} + +},{"../../../utils":152,"./buildLine":93,"earcut":15}],97:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Filter = exports.SpriteMaskFilter = exports.Quad = exports.RenderTarget = exports.ObjectRenderer = exports.WebGLManager = exports.Shader = exports.CanvasRenderTarget = exports.TextureUvs = exports.VideoBaseTexture = exports.BaseRenderTexture = exports.RenderTexture = exports.BaseTexture = exports.TextureTransform = exports.Texture = exports.CanvasGraphicsRenderer = exports.GraphicsRenderer = exports.GraphicsData = exports.Graphics = exports.TextStyle = exports.Text = exports.SpriteRenderer = exports.CanvasTinter = exports.CanvasSpriteRenderer = exports.Sprite = exports.TransformBase = exports.TransformStatic = exports.Transform = exports.Container = exports.DisplayObject = exports.glCore = exports.WebGLRenderer = exports.CanvasRenderer = exports.ticker = exports.utils = undefined; + +var _const = require('./const'); + +Object.keys(_const).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _const[key]; + } + }); +}); + +var _math = require('./math'); + +Object.keys(_math).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _math[key]; + } + }); +}); + +var _pixiGlCore = require('pixi-gl-core'); + +Object.defineProperty(exports, 'glCore', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_pixiGlCore).default; + } +}); + +var _DisplayObject = require('./display/DisplayObject'); + +Object.defineProperty(exports, 'DisplayObject', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplayObject).default; + } +}); + +var _Container = require('./display/Container'); + +Object.defineProperty(exports, 'Container', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Container).default; + } +}); + +var _Transform = require('./display/Transform'); + +Object.defineProperty(exports, 'Transform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Transform).default; + } +}); + +var _TransformStatic = require('./display/TransformStatic'); + +Object.defineProperty(exports, 'TransformStatic', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformStatic).default; + } +}); + +var _TransformBase = require('./display/TransformBase'); + +Object.defineProperty(exports, 'TransformBase', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformBase).default; + } +}); + +var _Sprite = require('./sprites/Sprite'); + +Object.defineProperty(exports, 'Sprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Sprite).default; + } +}); + +var _CanvasSpriteRenderer = require('./sprites/canvas/CanvasSpriteRenderer'); + +Object.defineProperty(exports, 'CanvasSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasSpriteRenderer).default; + } +}); + +var _CanvasTinter = require('./sprites/canvas/CanvasTinter'); + +Object.defineProperty(exports, 'CanvasTinter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasTinter).default; + } +}); + +var _SpriteRenderer = require('./sprites/webgl/SpriteRenderer'); + +Object.defineProperty(exports, 'SpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteRenderer).default; + } +}); + +var _Text = require('./text/Text'); + +Object.defineProperty(exports, 'Text', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Text).default; + } +}); + +var _TextStyle = require('./text/TextStyle'); + +Object.defineProperty(exports, 'TextStyle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextStyle).default; + } +}); + +var _Graphics = require('./graphics/Graphics'); + +Object.defineProperty(exports, 'Graphics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Graphics).default; + } +}); + +var _GraphicsData = require('./graphics/GraphicsData'); + +Object.defineProperty(exports, 'GraphicsData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsData).default; + } +}); + +var _GraphicsRenderer = require('./graphics/webgl/GraphicsRenderer'); + +Object.defineProperty(exports, 'GraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsRenderer).default; + } +}); + +var _CanvasGraphicsRenderer = require('./graphics/canvas/CanvasGraphicsRenderer'); + +Object.defineProperty(exports, 'CanvasGraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasGraphicsRenderer).default; + } +}); + +var _Texture = require('./textures/Texture'); + +Object.defineProperty(exports, 'Texture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Texture).default; + } +}); + +var _TextureTransform = require('./textures/TextureTransform'); + +Object.defineProperty(exports, 'TextureTransform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureTransform).default; + } +}); + +var _BaseTexture = require('./textures/BaseTexture'); + +Object.defineProperty(exports, 'BaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseTexture).default; + } +}); + +var _RenderTexture = require('./textures/RenderTexture'); + +Object.defineProperty(exports, 'RenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTexture).default; + } +}); + +var _BaseRenderTexture = require('./textures/BaseRenderTexture'); + +Object.defineProperty(exports, 'BaseRenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseRenderTexture).default; + } +}); + +var _VideoBaseTexture = require('./textures/VideoBaseTexture'); + +Object.defineProperty(exports, 'VideoBaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VideoBaseTexture).default; + } +}); + +var _TextureUvs = require('./textures/TextureUvs'); + +Object.defineProperty(exports, 'TextureUvs', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureUvs).default; + } +}); + +var _CanvasRenderTarget = require('./renderers/canvas/utils/CanvasRenderTarget'); + +Object.defineProperty(exports, 'CanvasRenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasRenderTarget).default; + } +}); + +var _Shader = require('./Shader'); + +Object.defineProperty(exports, 'Shader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Shader).default; + } +}); + +var _WebGLManager = require('./renderers/webgl/managers/WebGLManager'); + +Object.defineProperty(exports, 'WebGLManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLManager).default; + } +}); + +var _ObjectRenderer = require('./renderers/webgl/utils/ObjectRenderer'); + +Object.defineProperty(exports, 'ObjectRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObjectRenderer).default; + } +}); + +var _RenderTarget = require('./renderers/webgl/utils/RenderTarget'); + +Object.defineProperty(exports, 'RenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTarget).default; + } +}); + +var _Quad = require('./renderers/webgl/utils/Quad'); + +Object.defineProperty(exports, 'Quad', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Quad).default; + } +}); + +var _SpriteMaskFilter = require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter'); + +Object.defineProperty(exports, 'SpriteMaskFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteMaskFilter).default; + } +}); + +var _Filter = require('./renderers/webgl/filters/Filter'); + +Object.defineProperty(exports, 'Filter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Filter).default; + } +}); +exports.autoDetectRenderer = autoDetectRenderer; + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _ticker = require('./ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @namespace PIXI + */ +exports.utils = utils; +exports.ticker = ticker; +exports.CanvasRenderer = _CanvasRenderer2.default; +exports.WebGLRenderer = _WebGLRenderer2.default; + + +/** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by + * the browser then this function will return a canvas renderer + * + * @memberof PIXI + * @param {number} [width=800] - the width of the renderers view + * @param {number} [height=600] - the height of the renderers view + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [noWebGL=false] - prevents selection of WebGL renderer, even if such is present + * @return {PIXI.WebGLRenderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ +function autoDetectRenderer() { + var width = arguments.length <= 0 || arguments[0] === undefined ? 800 : arguments[0]; + var height = arguments.length <= 1 || arguments[1] === undefined ? 600 : arguments[1]; + var options = arguments[2]; + var noWebGL = arguments[3]; + + if (!noWebGL && utils.isWebGLSupported()) { + return new _WebGLRenderer2.default(width, height, options); + } + + return new _CanvasRenderer2.default(width, height, options); +} + +},{"./Shader":77,"./const":78,"./display/Container":80,"./display/DisplayObject":81,"./display/Transform":82,"./display/TransformBase":83,"./display/TransformStatic":84,"./graphics/Graphics":85,"./graphics/GraphicsData":86,"./graphics/canvas/CanvasGraphicsRenderer":87,"./graphics/webgl/GraphicsRenderer":89,"./math":102,"./renderers/canvas/CanvasRenderer":109,"./renderers/canvas/utils/CanvasRenderTarget":111,"./renderers/webgl/WebGLRenderer":116,"./renderers/webgl/filters/Filter":118,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":121,"./renderers/webgl/managers/WebGLManager":125,"./renderers/webgl/utils/ObjectRenderer":126,"./renderers/webgl/utils/Quad":127,"./renderers/webgl/utils/RenderTarget":128,"./sprites/Sprite":133,"./sprites/canvas/CanvasSpriteRenderer":134,"./sprites/canvas/CanvasTinter":135,"./sprites/webgl/SpriteRenderer":137,"./text/Text":139,"./text/TextStyle":140,"./textures/BaseRenderTexture":141,"./textures/BaseTexture":142,"./textures/RenderTexture":143,"./textures/Texture":144,"./textures/TextureTransform":145,"./textures/TextureUvs":146,"./textures/VideoBaseTexture":147,"./ticker":149,"./utils":152,"pixi-gl-core":51}],98:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Matrix = require('./Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16 + +var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; +var tempMatrices = []; + +var mul = []; + +function signum(x) { + if (x < 0) { + return -1; + } + if (x > 0) { + return 1; + } + + return 0; +} + +function init() { + for (var i = 0; i < 16; i++) { + var row = []; + + mul.push(row); + + for (var j = 0; j < 16; j++) { + var _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); + var _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); + var _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); + var _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); + + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + + for (var _i = 0; _i < 16; _i++) { + var mat = new _Matrix2.default(); + + mat.set(ux[_i], uy[_i], vx[_i], vy[_i], 0, 0); + tempMatrices.push(mat); + } +} + +init(); + +/** + * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, + * D8 is the same but with diagonals. Used for texture rotations. + * + * Vector xX(i), xY(i) is U-axis of sprite with rotation i + * Vector yY(i), yY(i) is V-axis of sprite with rotation i + * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) + * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) + * This is the small part of gameofbombs.com portal system. It works. + * + * @author Ivan @ivanpopelyshev + * + * @namespace PIXI.GroupD8 + */ +var GroupD8 = { + E: 0, + SE: 1, + S: 2, + SW: 3, + W: 4, + NW: 5, + N: 6, + NE: 7, + MIRROR_VERTICAL: 8, + MIRROR_HORIZONTAL: 12, + uX: function uX(ind) { + return ux[ind]; + }, + uY: function uY(ind) { + return uy[ind]; + }, + vX: function vX(ind) { + return vx[ind]; + }, + vY: function vY(ind) { + return vy[ind]; + }, + inv: function inv(rotation) { + if (rotation & 8) { + return rotation & 15; + } + + return -rotation & 7; + }, + add: function add(rotationSecond, rotationFirst) { + return mul[rotationSecond][rotationFirst]; + }, + sub: function sub(rotationSecond, rotationFirst) { + return mul[rotationSecond][GroupD8.inv(rotationFirst)]; + }, + + /** + * Adds 180 degrees to rotation. Commutative operation. + * + * @method + * @param {number} rotation - The number to rotate. + * @returns {number} rotated number + */ + rotate180: function rotate180(rotation) { + return rotation ^ 4; + }, + + /** + * I dont know why sometimes width and heights needs to be swapped. We'll fix it later. + * + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the width/height should be swapped. + */ + isSwapWidthHeight: function isSwapWidthHeight(rotation) { + return (rotation & 3) === 2; + }, + + /** + * @param {number} dx - TODO + * @param {number} dy - TODO + * + * @return {number} TODO + */ + byDirection: function byDirection(dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return GroupD8.S; + } + + return GroupD8.N; + } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return GroupD8.E; + } + + return GroupD8.W; + } else if (dy > 0) { + if (dx > 0) { + return GroupD8.SE; + } + + return GroupD8.SW; + } else if (dx > 0) { + return GroupD8.NE; + } + + return GroupD8.NW; + }, + + /** + * Helps sprite to compensate texture packer rotation. + * + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {number} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function matrixAppendRotationInv(matrix, rotation) { + var tx = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2]; + var ty = arguments.length <= 3 || arguments[3] === undefined ? 0 : arguments[3]; + + // Packer used "rotation", we use "inv(rotation)" + var mat = tempMatrices[GroupD8.inv(rotation)]; + + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + } +}; + +exports.default = GroupD8; + +},{"./Matrix":99}],99:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Point = require('./Point'); + +var _Point2 = _interopRequireDefault(_Point); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The pixi Matrix class as an object, which makes it a lot faster, + * here is a representation of it : + * | a | b | tx| + * | c | d | ty| + * | 0 | 0 | 1 | + * + * @class + * @memberof PIXI + */ +var Matrix = function () { + /** + * + */ + function Matrix() { + _classCallCheck(this, Matrix); + + /** + * @member {number} + * @default 1 + */ + this.a = 1; + + /** + * @member {number} + * @default 0 + */ + this.b = 0; + + /** + * @member {number} + * @default 0 + */ + this.c = 0; + + /** + * @member {number} + * @default 1 + */ + this.d = 1; + + /** + * @member {number} + * @default 0 + */ + this.tx = 0; + + /** + * @member {number} + * @default 0 + */ + this.ty = 0; + + this.array = null; + } + + /** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @param {number[]} array - The array that the matrix will be populated from. + */ + + + Matrix.prototype.fromArray = function fromArray(array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + }; + + /** + * sets the matrix properties + * + * @param {number} a - Matrix component + * @param {number} b - Matrix component + * @param {number} c - Matrix component + * @param {number} d - Matrix component + * @param {number} tx - Matrix component + * @param {number} ty - Matrix component + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.set = function set(a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + }; + + /** + * Creates an array from the current Matrix object. + * + * @param {boolean} transpose - Whether we need to transpose the matrix or not + * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out + * @return {number[]} the newly created array which contains the matrix + */ + + + Matrix.prototype.toArray = function toArray(transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + + var array = out || this.array; + + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + }; + + /** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, transformed through this matrix + */ + + + Matrix.prototype.apply = function apply(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; + + return newPos; + }; + + /** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, inverse-transformed through this matrix + */ + + + Matrix.prototype.applyInverse = function applyInverse(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var id = 1 / (this.a * this.d + this.c * -this.b); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + }; + + /** + * Translates the matrix on the x and y. + * + * @param {number} x How much to translate x by + * @param {number} y How much to translate y by + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.translate = function translate(x, y) { + this.tx += x; + this.ty += y; + + return this; + }; + + /** + * Applies a scale transformation to the matrix. + * + * @param {number} x The amount to scale horizontally + * @param {number} y The amount to scale vertically + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.scale = function scale(x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + }; + + /** + * Applies a rotation transformation to the matrix. + * + * @param {number} angle - The angle in radians. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.rotate = function rotate(angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos - this.b * sin; + this.b = a1 * sin + this.b * cos; + this.c = c1 * cos - this.d * sin; + this.d = c1 * sin + this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + }; + + /** + * Appends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to append. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.append = function append(matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + }; + + /** + * Sets the matrix based on all the available properties + * + * @param {number} x - Position on the x axis + * @param {number} y - Position on the y axis + * @param {number} pivotX - Pivot on the x axis + * @param {number} pivotY - Pivot on the y axis + * @param {number} scaleX - Scale on the x axis + * @param {number} scaleY - Scale on the y axis + * @param {number} rotation - Rotation in radians + * @param {number} skewX - Skew on the x axis + * @param {number} skewY - Skew on the y axis + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.setTransform = function setTransform(x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + var sr = Math.sin(rotation); + var cr = Math.cos(rotation); + var cy = Math.cos(skewY); + var sy = Math.sin(skewY); + var nsx = -Math.sin(skewX); + var cx = Math.cos(skewX); + + var a = cr * scaleX; + var b = sr * scaleX; + var c = -sr * scaleY; + var d = cr * scaleY; + + this.a = cy * a + sy * c; + this.b = cy * b + sy * d; + this.c = nsx * a + cx * c; + this.d = nsx * b + cx * d; + + this.tx = x + (pivotX * a + pivotY * c); + this.ty = y + (pivotX * b + pivotY * d); + + return this; + }; + + /** + * Prepends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to prepend + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.prepend = function prepend(matrix) { + var tx1 = this.tx; + + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + + this.a = a1 * matrix.a + this.b * matrix.c; + this.b = a1 * matrix.b + this.b * matrix.d; + this.c = c1 * matrix.a + this.d * matrix.c; + this.d = c1 * matrix.b + this.d * matrix.d; + } + + this.tx = tx1 * matrix.a + this.ty * matrix.c + matrix.tx; + this.ty = tx1 * matrix.b + this.ty * matrix.d + matrix.ty; + + return this; + }; + + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * + * @param {PIXI.Transform|PIXI.TransformStatic} transform - The transform to apply the properties to. + * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properies + */ + + + Matrix.prototype.decompose = function decompose(transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + + var skewX = Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + + var delta = Math.abs(1 - skewX / skewY); + + if (delta < 0.00001) { + transform.rotation = skewY; + + if (a < 0 && d >= 0) { + transform.rotation += transform.rotation <= 0 ? Math.PI : -Math.PI; + } + + transform.skew.x = transform.skew.y = 0; + } else { + transform.skew.x = skewX; + transform.skew.y = skewY; + } + + // next set scale + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); + + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; + + return transform; + }; + + /** + * Inverts this matrix + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.invert = function invert() { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1 * d1 - b1 * c1; + + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = (c1 * this.ty - d1 * tx1) / n; + this.ty = -(a1 * this.ty - b1 * tx1) / n; + + return this; + }; + + /** + * Resets this Matix to an identity (default) matrix. + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.identity = function identity() { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + + return this; + }; + + /** + * Creates a new Matrix object with the same values as this one. + * + * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. + */ + + + Matrix.prototype.clone = function clone() { + var matrix = new Matrix(); + + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * Changes the values of the given matrix to be the same as the ones in this matrix + * + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @return {PIXI.Matrix} The matrix given in parameter with its values updated. + */ + + + Matrix.prototype.copy = function copy(matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * A default (identity) matrix + * + * @static + * @const + */ + + + _createClass(Matrix, null, [{ + key: 'IDENTITY', + get: function get() { + return new Matrix(); + } + + /** + * A temp matrix + * + * @static + * @const + */ + + }, { + key: 'TEMP_MATRIX', + get: function get() { + return new Matrix(); + } + }]); + + return Matrix; +}(); + +exports.default = Matrix; + +},{"./Point":101}],100:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * An observable point is a point that triggers a callback when the point's position is changed. + * + * @class + * @memberof PIXI + */ +var ObservablePoint = function () { + /** + * @param {Function} cb - callback when changed + * @param {object} scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope) { + var x = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2]; + var y = arguments.length <= 3 || arguments[3] === undefined ? 0 : arguments[3]; + + _classCallCheck(this, ObservablePoint); + + this._x = x; + this._y = y; + + this.cb = cb; + this.scope = scope; + } + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + ObservablePoint.prototype.set = function set(x, y) { + var _x = x || 0; + var _y = y || (y !== 0 ? _x : 0); + + if (this._x !== _x || this._y !== _y) { + this._x = _x; + this._y = _y; + this.cb.call(this.scope); + } + }; + + /** + * Copies the data from another point + * + * @param {PIXI.Point|PIXI.ObservablePoint} point - point to copy from + */ + + + ObservablePoint.prototype.copy = function copy(point) { + if (this._x !== point.x || this._y !== point.y) { + this._x = point.x; + this._y = point.y; + this.cb.call(this.scope); + } + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + * @memberof PIXI.ObservablePoint# + */ + + + _createClass(ObservablePoint, [{ + key: "x", + get: function get() { + return this._x; + } + + /** + * Sets the X component. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + } + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + * @memberof PIXI.ObservablePoint# + */ + + }, { + key: "y", + get: function get() { + return this._y; + } + + /** + * Sets the Y component. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + } + }]); + + return ObservablePoint; +}(); + +exports.default = ObservablePoint; + +},{}],101:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * + * @class + * @memberof PIXI + */ +var Point = function () { + /** + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function Point() { + var x = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var y = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + + _classCallCheck(this, Point); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + } + + /** + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point + */ + + + Point.prototype.clone = function clone() { + return new Point(this.x, this.y); + }; + + /** + * Copies x and y from the given point + * + * @param {PIXI.Point} p - The point to copy. + */ + + + Point.prototype.copy = function copy(p) { + this.set(p.x, p.y); + }; + + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.Point} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + + + Point.prototype.equals = function equals(p) { + return p.x === this.x && p.y === this.y; + }; + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + Point.prototype.set = function set(x, y) { + this.x = x || 0; + this.y = y || (y !== 0 ? this.x : 0); + }; + + return Point; +}(); + +exports.default = Point; + +},{}],102:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('./Point'); + +Object.defineProperty(exports, 'Point', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Point).default; + } +}); + +var _ObservablePoint = require('./ObservablePoint'); + +Object.defineProperty(exports, 'ObservablePoint', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObservablePoint).default; + } +}); + +var _Matrix = require('./Matrix'); + +Object.defineProperty(exports, 'Matrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Matrix).default; + } +}); + +var _GroupD = require('./GroupD8'); + +Object.defineProperty(exports, 'GroupD8', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GroupD).default; + } +}); + +var _Circle = require('./shapes/Circle'); + +Object.defineProperty(exports, 'Circle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Circle).default; + } +}); + +var _Ellipse = require('./shapes/Ellipse'); + +Object.defineProperty(exports, 'Ellipse', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Ellipse).default; + } +}); + +var _Polygon = require('./shapes/Polygon'); + +Object.defineProperty(exports, 'Polygon', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Polygon).default; + } +}); + +var _Rectangle = require('./shapes/Rectangle'); + +Object.defineProperty(exports, 'Rectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rectangle).default; + } +}); + +var _RoundedRectangle = require('./shapes/RoundedRectangle'); + +Object.defineProperty(exports, 'RoundedRectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RoundedRectangle).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./GroupD8":98,"./Matrix":99,"./ObservablePoint":100,"./Point":101,"./shapes/Circle":103,"./shapes/Ellipse":104,"./shapes/Polygon":105,"./shapes/Rectangle":106,"./shapes/RoundedRectangle":107}],103:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Circle object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Circle = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [radius=0] - The radius of the circle + */ + function Circle() { + var x = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var y = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + var radius = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2]; + + _classCallCheck(this, Circle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.CIRC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.CIRC; + } + + /** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ + + + Circle.prototype.clone = function clone() { + return new Circle(this.x, this.y, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this circle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Circle + */ + + + Circle.prototype.contains = function contains(x, y) { + if (this.radius <= 0) { + return false; + } + + var r2 = this.radius * this.radius; + var dx = this.x - x; + var dy = this.y - y; + + dx *= dx; + dy *= dy; + + return dx + dy <= r2; + }; + + /** + * Returns the framing rectangle of the circle as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Circle.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + + return Circle; +}(); + +exports.default = Circle; + +},{"../../const":78,"./Rectangle":106}],104:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Ellipse object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Ellipse = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [width=0] - The half width of this ellipse + * @param {number} [height=0] - The half height of this ellipse + */ + function Ellipse() { + var x = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var y = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + var width = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2]; + var height = arguments.length <= 3 || arguments[3] === undefined ? 0 : arguments[3]; + + _classCallCheck(this, Ellipse); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.ELIP + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.ELIP; + } + + /** + * Creates a clone of this Ellipse instance + * + * @return {PIXI.Ellipse} a copy of the ellipse + */ + + + Ellipse.prototype.clone = function clone() { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coords are within this ellipse + */ + + + Ellipse.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + // normalize the coords to an ellipse with center 0,0 + var normx = (x - this.x) / this.width; + var normy = (y - this.y) / this.height; + + normx *= normx; + normy *= normy; + + return normx + normy <= 1; + }; + + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Ellipse.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.width, this.y - this.height, this.width, this.height); + }; + + return Ellipse; +}(); + +exports.default = Ellipse; + +},{"../../const":78,"./Rectangle":106}],105:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('../Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Polygon = function () { + /** + * @param {PIXI.Point[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + for (var _len = arguments.length, points = Array(_len), _key = 0; _key < _len; _key++) { + points[_key] = arguments[_key]; + } + + _classCallCheck(this, Polygon); + + if (Array.isArray(points[0])) { + points = points[0]; + } + + // if this is an array of points, convert it to a flat array of numbers + if (points[0] instanceof _Point2.default) { + var p = []; + + for (var i = 0, il = points.length; i < il; i++) { + p.push(points[i].x, points[i].y); + } + + points = p; + } + + this.closed = true; + + /** + * An array of the points of this polygon + * + * @member {number[]} + */ + this.points = points; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.POLY + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.POLY; + } + + /** + * Creates a clone of this polygon + * + * @return {PIXI.Polygon} a copy of the polygon + */ + + + Polygon.prototype.clone = function clone() { + return new Polygon(this.points.slice()); + }; + + /** + * Closes the polygon, adding points if necessary. + * + */ + + + Polygon.prototype.close = function close() { + var points = this.points; + + // close the poly if the value is true! + if (points[0] !== points[points.length - 2] || points[1] !== points[points.length - 1]) { + points.push(points[0], points[1]); + } + }; + + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this polygon + */ + + + Polygon.prototype.contains = function contains(x, y) { + var inside = false; + + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + + for (var i = 0, j = length - 1; i < length; j = ++i) { + var xi = this.points[i * 2]; + var yi = this.points[i * 2 + 1]; + var xj = this.points[j * 2]; + var yj = this.points[j * 2 + 1]; + var intersect = yi > y !== yj > y && x < (xj - xi) * ((y - yi) / (yj - yi)) + xi; + + if (intersect) { + inside = !inside; + } + } + + return inside; + }; + + return Polygon; +}(); + +exports.default = Polygon; + +},{"../../const":78,"../Point":101}],106:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * + * @class + * @memberof PIXI + */ +var Rectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle + * @param {number} [width=0] - The overall width of this rectangle + * @param {number} [height=0] - The overall height of this rectangle + */ + function Rectangle() { + var x = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var y = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + var width = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2]; + var height = arguments.length <= 3 || arguments[3] === undefined ? 0 : arguments[3]; + + _classCallCheck(this, Rectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.RECT + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RECT; + } + + /** + * returns the left edge of the rectangle + * + * @member {number} + * @memberof PIXI.Rectangle# + */ + + + /** + * Creates a clone of this Rectangle + * + * @return {PIXI.Rectangle} a copy of the rectangle + */ + Rectangle.prototype.clone = function clone() { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + + /** + * Copies another rectangle to this one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to copy. + * @return {PIXI.Rectanle} Returns itself. + */ + + + Rectangle.prototype.copy = function copy(rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + + return this; + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rectangle + */ + + + Rectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + + return false; + }; + + /** + * Pads the rectangle making it grow in all directions. + * + * @param {number} paddingX - The horizontal padding amount. + * @param {number} paddingY - The vertical padding amount. + */ + + + Rectangle.prototype.pad = function pad(paddingX, paddingY) { + paddingX = paddingX || 0; + paddingY = paddingY || (paddingY !== 0 ? paddingX : 0); + + this.x -= paddingX; + this.y -= paddingY; + + this.width += paddingX * 2; + this.height += paddingY * 2; + }; + + /** + * Fits this rectangle around the passed one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to fit. + */ + + + Rectangle.prototype.fit = function fit(rectangle) { + if (this.x < rectangle.x) { + this.width += this.x; + if (this.width < 0) { + this.width = 0; + } + + this.x = rectangle.x; + } + + if (this.y < rectangle.y) { + this.height += this.y; + if (this.height < 0) { + this.height = 0; + } + this.y = rectangle.y; + } + + if (this.x + this.width > rectangle.x + rectangle.width) { + this.width = rectangle.width - this.x; + if (this.width < 0) { + this.width = 0; + } + } + + if (this.y + this.height > rectangle.y + rectangle.height) { + this.height = rectangle.height - this.y; + if (this.height < 0) { + this.height = 0; + } + } + }; + + /** + * Enlarges this rectangle to include the passed rectangle. + * + * @param {PIXI.Rectangle} rect - The rectangle to include. + */ + + + Rectangle.prototype.enlarge = function enlarge(rect) { + if (rect === Rectangle.EMPTY) { + return; + } + + var x1 = Math.min(this.x, rect.x); + var x2 = Math.max(this.x + this.width, rect.x + rect.width); + var y1 = Math.min(this.y, rect.y); + var y2 = Math.max(this.y + this.height, rect.y + rect.height); + + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + }; + + _createClass(Rectangle, [{ + key: 'left', + get: function get() { + return this.x; + } + + /** + * returns the right edge of the rectangle + * + * @member {number} + * @memberof PIXI.Rectangle + */ + + }, { + key: 'right', + get: function get() { + return this.x + this.width; + } + + /** + * returns the top edge of the rectangle + * + * @member {number} + * @memberof PIXI.Rectangle + */ + + }, { + key: 'top', + get: function get() { + return this.y; + } + + /** + * returns the bottom edge of the rectangle + * + * @member {number} + * @memberof PIXI.Rectangle + */ + + }, { + key: 'bottom', + get: function get() { + return this.y + this.height; + } + + /** + * A constant empty rectangle. + * + * @static + * @constant + */ + + }], [{ + key: 'EMPTY', + get: function get() { + return new Rectangle(0, 0, 0, 0); + } + }]); + + return Rectangle; +}(); + +exports.default = Rectangle; + +},{"../../const":78}],107:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. + * + * @class + * @memberof PIXI + */ +var RoundedRectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle + * @param {number} [width=0] - The overall width of this rounded rectangle + * @param {number} [height=0] - The overall height of this rounded rectangle + * @param {number} [radius=20] - Controls the radius of the rounded corners + */ + function RoundedRectangle() { + var x = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var y = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + var width = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2]; + var height = arguments.length <= 3 || arguments[3] === undefined ? 0 : arguments[3]; + var radius = arguments.length <= 4 || arguments[4] === undefined ? 20 : arguments[4]; + + _classCallCheck(this, RoundedRectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * @member {number} + * @default 20 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readonly + * @default PIXI.SHAPES.RREC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RREC; + } + + /** + * Creates a clone of this Rounded Rectangle + * + * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle + */ + + + RoundedRectangle.prototype.clone = function clone() { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + */ + + + RoundedRectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + return true; + } + } + + return false; + }; + + return RoundedRectangle; +}(); + +exports.default = RoundedRectangle; + +},{"../../const":78}],108:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _math = require('../math'); + +var _const = require('../const'); + +var _Container = require('../display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMatrix = new _math.Matrix(); + +/** + * The SystemRenderer is the base for a Pixi Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.WebGLRenderer} which can be used for rendering a Pixi scene. + * + * @abstract + * @class + * @extends EventEmitter + * @memberof PIXI + */ + +var SystemRenderer = function (_EventEmitter) { + _inherits(SystemRenderer, _EventEmitter); + + /** + * @param {string} system - The name of the system this renderer is for. + * @param {number} [width=800] - the width of the canvas view + * @param {number} [height=600] - the height of the canvas view + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function SystemRenderer(system, width, height, options) { + _classCallCheck(this, SystemRenderer); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + (0, _utils.sayHello)(system); + + // prepare options + if (options) { + for (var i in _const.DEFAULT_RENDER_OPTIONS) { + if (typeof options[i] === 'undefined') { + options[i] = _const.DEFAULT_RENDER_OPTIONS[i]; + } + } + } else { + options = _const.DEFAULT_RENDER_OPTIONS; + } + + /** + * The type of the renderer. + * + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.UNKNOWN; + + /** + * The width of the canvas view + * + * @member {number} + * @default 800 + */ + _this.width = width || 800; + + /** + * The height of the canvas view + * + * @member {number} + * @default 600 + */ + _this.height = height || 600; + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.view = options.view || document.createElement('canvas'); + + /** + * The resolution / device pixel ratio of the renderer + * + * @member {number} + * @default 1 + */ + _this.resolution = options.resolution; + + /** + * Whether the render view is transparent + * + * @member {boolean} + */ + _this.transparent = options.transparent; + + /** + * Whether the render view should be resized automatically + * + * @member {boolean} + */ + _this.autoResize = options.autoResize || false; + + /** + * Tracks the blend modes useful for this renderer. + * + * @member {object} + */ + _this.blendModes = null; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent Pixi will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent Pixi will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example if + * your game has a canvas filling background image you often don't need this set. + * + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + * + * @member {boolean} + */ + _this.roundPixels = options.roundPixels; + + /** + * The background color as a number. + * + * @member {number} + * @private + */ + _this._backgroundColor = 0x000000; + + /** + * The background color as an [R, G, B] array. + * + * @member {number[]} + * @private + */ + _this._backgroundColorRgba = [0, 0, 0, 0]; + + /** + * The background color as a string. + * + * @member {string} + * @private + */ + _this._backgroundColorString = '#000000'; + + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + + /** + * This temporary display object used as the parent of the currently being rendered item + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._tempDisplayObjectParent = new _Container2.default(); + + /** + * The last root object that the renderer tried to render. + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._lastObjectRendered = _this._tempDisplayObjectParent; + return _this; + } + + /** + * Resizes the canvas view to the specified width and height + * + * @param {number} width - the new width of the canvas view + * @param {number} height - the new height of the canvas view + */ + + + SystemRenderer.prototype.resize = function resize(width, height) { + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) { + this.view.style.width = this.width / this.resolution + 'px'; + this.view.style.height = this.height / this.resolution + 'px'; + } + }; + + /** + * Useful function that returns a texture of the display object that can then be used to create sprites + * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. + * + * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from + * @param {number} scaleMode - Should be one of the scaleMode consts + * @param {number} resolution - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.Texture} a texture of the graphics object + */ + + + SystemRenderer.prototype.generateTexture = function generateTexture(displayObject, scaleMode, resolution) { + var bounds = displayObject.getLocalBounds(); + + var renderTexture = _RenderTexture2.default.create(bounds.width | 0, bounds.height | 0, scaleMode, resolution); + + tempMatrix.tx = -bounds.x; + tempMatrix.ty = -bounds.y; + + this.render(displayObject, renderTexture, false, tempMatrix, true); + + return renderTexture; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + SystemRenderer.prototype.destroy = function destroy(removeView) { + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } + + this.type = _const.RENDERER_TYPE.UNKNOWN; + + this.width = 0; + this.height = 0; + + this.view = null; + + this.resolution = 0; + + this.transparent = false; + + this.autoResize = false; + + this.blendModes = null; + + this.preserveDrawingBuffer = false; + this.clearBeforeRender = false; + + this.roundPixels = false; + + this._backgroundColor = 0; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + + this.backgroundColor = 0; + this._tempDisplayObjectParent = null; + this._lastObjectRendered = null; + }; + + /** + * The background color to fill if not transparent + * + * @member {number} + * @memberof PIXI.SystemRenderer# + */ + + + _createClass(SystemRenderer, [{ + key: 'backgroundColor', + get: function get() { + return this._backgroundColor; + } + + /** + * Sets the background color. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this._backgroundColor = value; + this._backgroundColorString = (0, _utils.hex2string)(value); + (0, _utils.hex2rgb)(value, this._backgroundColorRgba); + } + }]); + + return SystemRenderer; +}(_eventemitter2.default); + +exports.default = SystemRenderer; + +},{"../const":78,"../display/Container":80,"../math":102,"../textures/RenderTexture":143,"../utils":152,"eventemitter3":16}],109:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _CanvasMaskManager = require('./utils/CanvasMaskManager'); + +var _CanvasMaskManager2 = _interopRequireDefault(_CanvasMaskManager); + +var _CanvasRenderTarget = require('./utils/CanvasRenderTarget'); + +var _CanvasRenderTarget2 = _interopRequireDefault(_CanvasRenderTarget); + +var _mapCanvasBlendModesToPixi = require('./utils/mapCanvasBlendModesToPixi'); + +var _mapCanvasBlendModesToPixi2 = _interopRequireDefault(_mapCanvasBlendModesToPixi); + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should + * be used for browsers that do not support WebGL. Don't forget to add the CanvasRenderer.view to + * your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ +var CanvasRenderer = function (_SystemRenderer) { + _inherits(CanvasRenderer, _SystemRenderer); + + /** + * @param {number} [width=800] - the width of the canvas view + * @param {number} [height=600] - the height of the canvas view + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function CanvasRenderer(width, height) { + var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + + _classCallCheck(this, CanvasRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'Canvas', width, height, options)); + + _this.type = _const.RENDERER_TYPE.CANVAS; + + /** + * The canvas 2d context that everything is drawn with. + * + * @member {CanvasRenderingContext2D} + */ + _this.rootContext = _this.view.getContext('2d', { alpha: _this.transparent }); + + /** + * Boolean flag controlling canvas refresh. + * + * @member {boolean} + */ + _this.refresh = true; + + /** + * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. + * + * @member {PIXI.CanvasMaskManager} + */ + _this.maskManager = new _CanvasMaskManager2.default(_this); + + /** + * The canvas property used to set the canvas smoothing property. + * + * @member {string} + */ + _this.smoothProperty = 'imageSmoothingEnabled'; + + if (!_this.rootContext.imageSmoothingEnabled) { + if (_this.rootContext.webkitImageSmoothingEnabled) { + _this.smoothProperty = 'webkitImageSmoothingEnabled'; + } else if (_this.rootContext.mozImageSmoothingEnabled) { + _this.smoothProperty = 'mozImageSmoothingEnabled'; + } else if (_this.rootContext.oImageSmoothingEnabled) { + _this.smoothProperty = 'oImageSmoothingEnabled'; + } else if (_this.rootContext.msImageSmoothingEnabled) { + _this.smoothProperty = 'msImageSmoothingEnabled'; + } + } + + _this.initPlugins(); + + _this.blendModes = (0, _mapCanvasBlendModesToPixi2.default)(); + _this._activeBlendMode = null; + + _this.context = null; + _this.renderingToScreen = false; + + _this.resize(width, height); + return _this; + } + + /** + * Renders the object to this canvas view + * + * @param {PIXI.DisplayObject} displayObject - The object to be rendered + * @param {PIXI.RenderTexture} [renderTexture] - A render texture to be rendered to. + * If unset, it will render to the root context. + * @param {boolean} [clear=false] - Whether to clear the canvas before drawing + * @param {PIXI.Transform} [transform] - A transformation to be applied + * @param {boolean} [skipUpdateTransform=false] - Whether to skip the update transform + */ + + + CanvasRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!this.view) { + return; + } + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + if (renderTexture) { + renderTexture = renderTexture.baseTexture || renderTexture; + + if (!renderTexture._canvasRenderTarget) { + renderTexture._canvasRenderTarget = new _CanvasRenderTarget2.default(renderTexture.width, renderTexture.height, renderTexture.resolution); + renderTexture.source = renderTexture._canvasRenderTarget.canvas; + renderTexture.valid = true; + } + + this.context = renderTexture._canvasRenderTarget.context; + this.resolution = renderTexture._canvasRenderTarget.resolution; + } else { + this.context = this.rootContext; + } + + var context = this.context; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + var tempWt = this._tempDisplayObjectParent.transform.worldTransform; + + if (transform) { + transform.copy(tempWt); + } else { + tempWt.identity(); + } + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + context.setTransform(1, 0, 0, 1, 0, 0); + context.globalAlpha = 1; + context.globalCompositeOperation = this.blendModes[_const.BLEND_MODES.NORMAL]; + + if (navigator.isCocoonJS && this.view.screencanvas) { + context.fillStyle = 'black'; + context.clear(); + } + + if (clear !== undefined ? clear : this.clearBeforeRender) { + if (this.renderingToScreen) { + if (this.transparent) { + context.clearRect(0, 0, this.width, this.height); + } else { + context.fillStyle = this._backgroundColorString; + context.fillRect(0, 0, this.width, this.height); + } + } // else { + // TODO: implement background for CanvasRenderTarget or RenderTexture? + // } + } + + // TODO RENDER TARGET STUFF HERE.. + var tempContext = this.context; + + this.context = context; + displayObject.renderCanvas(this); + this.context = tempContext; + + this.emit('postrender'); + }; + + /** + * Sets the blend mode of the renderer. + * + * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values. + */ + + + CanvasRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + if (this._activeBlendMode === blendMode) { + return; + } + + this.context.globalCompositeOperation = this.blendModes[blendMode]; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + CanvasRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // call the base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.context = null; + + this.refresh = true; + + this.maskManager.destroy(); + this.maskManager = null; + + this.smoothProperty = null; + }; + + /** + * Resizes the canvas view to the specified width and height. + * + * @extends PIXI.SystemRenderer#resize + * + * @param {number} width - The new width of the canvas view + * @param {number} height - The new height of the canvas view + */ + + + CanvasRenderer.prototype.resize = function resize(width, height) { + _SystemRenderer.prototype.resize.call(this, width, height); + + // reset the scale mode.. oddly this seems to be reset when the canvas is resized. + // surely a browser bug?? Let pixi fix that for you.. + if (this.smoothProperty) { + this.rootContext[this.smoothProperty] = _const.SCALE_MODES.DEFAULT === _const.SCALE_MODES.LINEAR; + } + }; + + return CanvasRenderer; +}(_SystemRenderer3.default); + +exports.default = CanvasRenderer; + + +_utils.pluginTarget.mixin(CanvasRenderer); + +},{"../../const":78,"../../utils":152,"../SystemRenderer":108,"./utils/CanvasMaskManager":110,"./utils/CanvasRenderTarget":111,"./utils/mapCanvasBlendModesToPixi":113}],110:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A set of functions used to handle masking. + * + * @class + * @memberof PIXI + */ +var CanvasMaskManager = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + function CanvasMaskManager(renderer) { + _classCallCheck(this, CanvasMaskManager); + + this.renderer = renderer; + } + + /** + * This method adds it to the current stack of masks. + * + * @param {object} maskData - the maskData that will be pushed + */ + + + CanvasMaskManager.prototype.pushMask = function pushMask(maskData) { + var renderer = this.renderer; + + renderer.context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.transform.worldTransform; + var resolution = renderer.resolution; + + renderer.context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // TODO suport sprite alpha masks?? + // lots of effort required. If demand is great enough.. + if (!maskData._texture) { + this.renderGraphicsShape(maskData); + renderer.context.clip(); + } + + maskData.worldAlpha = cacheAlpha; + }; + + /** + * Renders a PIXI.Graphics shape. + * + * @param {PIXI.Graphics} graphics - The object to render. + */ + + + CanvasMaskManager.prototype.renderGraphicsShape = function renderGraphicsShape(graphics) { + var context = this.renderer.context; + var len = graphics.graphicsData.length; + + if (len === 0) { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === _const.SHAPES.POLY) { + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; j++) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) { + context.closePath(); + } + } else if (data.type === _const.SHAPES.RECT) { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } + }; + + /** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @param {PIXI.CanvasRenderer} renderer - The renderer context to use. + */ + + + CanvasMaskManager.prototype.popMask = function popMask(renderer) { + renderer.context.restore(); + }; + + /** + * Destroys this canvas mask manager. + * + */ + + + CanvasMaskManager.prototype.destroy = function destroy() { + /* empty */ + }; + + return CanvasMaskManager; +}(); + +exports.default = CanvasMaskManager; + +},{"../../../const":78}],111:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Creates a Canvas element of the given size. + * + * @class + * @memberof PIXI + */ +var CanvasRenderTarget = function () { + /** + * @param {number} width - the width for the newly created canvas + * @param {number} height - the height for the newly created canvas + * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + _classCallCheck(this, CanvasRenderTarget); + + /** + * The Canvas object that belongs to this CanvasRenderTarget. + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @member {CanvasRenderingContext2D} + */ + this.context = this.canvas.getContext('2d'); + + this.resolution = resolution || _const.RESOLUTION; + + this.resize(width, height); + } + + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * + * @private + */ + + + CanvasRenderTarget.prototype.clear = function clear() { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + + /** + * Resizes the canvas to the specified width and height. + * + * @param {number} width - the new width of the canvas + * @param {number} height - the new height of the canvas + */ + + + CanvasRenderTarget.prototype.resize = function resize(width, height) { + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; + }; + + /** + * Destroys this canvas. + * + */ + + + CanvasRenderTarget.prototype.destroy = function destroy() { + this.context = null; + this.canvas = null; + }; + + /** + * The width of the canvas buffer in pixels. + * + * @member {number} + * @memberof PIXI.CanvasRenderTarget# + */ + + + _createClass(CanvasRenderTarget, [{ + key: 'width', + get: function get() { + return this.canvas.width; + } + + /** + * Sets the width. + * + * @param {number} val - The value to set. + */ + , + set: function set(val) { + this.canvas.width = val; + } + + /** + * The height of the canvas buffer in pixels. + * + * @member {number} + * @memberof PIXI.CanvasRenderTarget# + */ + + }, { + key: 'height', + get: function get() { + return this.canvas.height; + } + + /** + * Sets the height. + * + * @param {number} val - The value to set. + */ + , + set: function set(val) { + this.canvas.height = val; + } + }]); + + return CanvasRenderTarget; +}(); + +exports.default = CanvasRenderTarget; + +},{"../../../const":78}],112:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = canUseNewCanvasBlendModes; +/** + * Creates a little colored canvas + * + * @ignore + * @param {number} color - The color to make the canvas + * @return {canvas} a small canvas element + */ +function createColoredCanvas(color) { + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.fillStyle = color; + context.fillRect(0, 0, 6, 1); + + return canvas; +} + +/** + * Checks whether the Canvas BlendModes are supported by the current browser + * + * @return {boolean} whether they are supported + */ +function canUseNewCanvasBlendModes() { + if (typeof document === 'undefined') { + return false; + } + + var magenta = createColoredCanvas('#ff00ff'); + var yellow = createColoredCanvas('#ffff00'); + + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.globalCompositeOperation = 'multiply'; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + var imageData = context.getImageData(2, 0, 1, 1); + + if (!imageData) { + return false; + } + + var data = imageData.data; + + return data[0] === 255 && data[1] === 0 && data[2] === 0; +} + +},{}],113:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapCanvasBlendModesToPixi; + +var _const = require('../../../const'); + +var _canUseNewCanvasBlendModes = require('./canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Maps blend combinations to Canvas. + * + * @memberof PIXI + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapCanvasBlendModesToPixi() { + var array = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; + + if ((0, _canUseNewCanvasBlendModes2.default)()) { + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'multiply'; + array[_const.BLEND_MODES.SCREEN] = 'screen'; + array[_const.BLEND_MODES.OVERLAY] = 'overlay'; + array[_const.BLEND_MODES.DARKEN] = 'darken'; + array[_const.BLEND_MODES.LIGHTEN] = 'lighten'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'color-dodge'; + array[_const.BLEND_MODES.COLOR_BURN] = 'color-burn'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'hard-light'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'soft-light'; + array[_const.BLEND_MODES.DIFFERENCE] = 'difference'; + array[_const.BLEND_MODES.EXCLUSION] = 'exclusion'; + array[_const.BLEND_MODES.HUE] = 'hue'; + array[_const.BLEND_MODES.SATURATION] = 'saturate'; + array[_const.BLEND_MODES.COLOR] = 'color'; + array[_const.BLEND_MODES.LUMINOSITY] = 'luminosity'; + } else { + // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'source-over'; + array[_const.BLEND_MODES.SCREEN] = 'source-over'; + array[_const.BLEND_MODES.OVERLAY] = 'source-over'; + array[_const.BLEND_MODES.DARKEN] = 'source-over'; + array[_const.BLEND_MODES.LIGHTEN] = 'source-over'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'source-over'; + array[_const.BLEND_MODES.COLOR_BURN] = 'source-over'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.DIFFERENCE] = 'source-over'; + array[_const.BLEND_MODES.EXCLUSION] = 'source-over'; + array[_const.BLEND_MODES.HUE] = 'source-over'; + array[_const.BLEND_MODES.SATURATION] = 'source-over'; + array[_const.BLEND_MODES.COLOR] = 'source-over'; + array[_const.BLEND_MODES.LUMINOSITY] = 'source-over'; + } + + return array; +} + +},{"../../../const":78,"./canUseNewCanvasBlendModes":112}],114:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged + * up with textures that are no longer being used. + * + * @class + * @memberof PIXI + */ +var TextureGarbageCollector = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function TextureGarbageCollector(renderer) { + _classCallCheck(this, TextureGarbageCollector); + + this.renderer = renderer; + + this.count = 0; + this.checkCount = 0; + this.maxIdle = 60 * 60; + this.checkCountMax = 60 * 10; + + this.mode = _const.GC_MODES.DEFAULT; + } + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.update = function update() { + this.count++; + + if (this.mode === _const.GC_MODES.MANUAL) { + return; + } + + this.checkCount++; + + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + + this.run(); + } + }; + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.run = function run() { + var tm = this.renderer.textureManager; + var managedTextures = tm._managedTextures; + var wasRemoved = false; + + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + + // only supports non generated textures at the moment! + if (!texture._glRenderTargets && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + + if (wasRemoved) { + var j = 0; + + for (var _i = 0; _i < managedTextures.length; _i++) { + if (managedTextures[_i] !== null) { + managedTextures[j++] = managedTextures[_i]; + } + } + + managedTextures.length = j; + } + }; + + /** + * Removes all the textures within the specified displayObject and its children from the GPU + * + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + */ + + + TextureGarbageCollector.prototype.unload = function unload(displayObject) { + var tm = this.renderer.textureManager; + + if (displayObject._texture) { + tm.destroyTexture(displayObject._texture, true); + } + + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + + return TextureGarbageCollector; +}(); + +exports.default = TextureGarbageCollector; + +},{"../../const":78}],115:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _const = require('../../const'); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _utils = require('../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a webGL Texture + * + * @class + * @memberof PIXI + */ +var TextureManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function TextureManager(renderer) { + _classCallCheck(this, TextureManager); + + /** + * A reference to the current renderer + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = renderer.gl; + + /** + * Track textures in the renderer so we can no longer listen to them on destruction. + * + * @member {Array<*>} + * @private + */ + this._managedTextures = []; + } + + /** + * Binds a texture. + * + */ + + + TextureManager.prototype.bindTexture = function bindTexture() {} + // empty + + + /** + * Gets a texture. + * + */ + ; + + TextureManager.prototype.getTexture = function getTexture() {} + // empty + + + /** + * Updates and/or Creates a WebGL texture for the renderer's context. + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update + * @return {GLTexture} The gl texture. + */ + ; + + TextureManager.prototype.updateTexture = function updateTexture(texture) { + texture = texture.baseTexture || texture; + + var isRenderTexture = !!texture._glRenderTargets; + + if (!texture.hasLoaded) { + return null; + } + + var glTexture = texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!glTexture) { + if (isRenderTexture) { + var renderTarget = new _RenderTarget2.default(this.gl, texture.width, texture.height, texture.scaleMode, texture.resolution); + + renderTarget.resize(texture.width, texture.height); + texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget; + glTexture = renderTarget.texture; + } else { + glTexture = new _pixiGlCore.GLTexture(this.gl); + glTexture.premultiplyAlpha = true; + glTexture.upload(texture.source); + } + + texture._glTextures[this.renderer.CONTEXT_UID] = glTexture; + + texture.on('update', this.updateTexture, this); + texture.on('dispose', this.destroyTexture, this); + + this._managedTextures.push(texture); + + if (texture.isPowerOfTwo) { + if (texture.mipmap) { + glTexture.enableMipmap(); + } + + if (texture.wrapMode === _const.WRAP_MODES.CLAMP) { + glTexture.enableWrapClamp(); + } else if (texture.wrapMode === _const.WRAP_MODES.REPEAT) { + glTexture.enableWrapRepeat(); + } else { + glTexture.enableWrapMirrorRepeat(); + } + } else { + glTexture.enableWrapClamp(); + } + + if (texture.scaleMode === _const.SCALE_MODES.NEAREST) { + glTexture.enableNearestScaling(); + } else { + glTexture.enableLinearScaling(); + } + } + // the textur ealrady exists so we only need to update it.. + else if (isRenderTexture) { + texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height); + } else { + glTexture.upload(texture.source); + } + + return glTexture; + }; + + /** + * Deletes the texture from WebGL + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy + * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. + */ + + + TextureManager.prototype.destroyTexture = function destroyTexture(texture, skipRemove) { + texture = texture.baseTexture || texture; + + if (!texture.hasLoaded) { + return; + } + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + texture._glTextures[this.renderer.CONTEXT_UID].destroy(); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + + delete texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!skipRemove) { + var i = this._managedTextures.indexOf(texture); + + if (i !== -1) { + (0, _utils.removeItems)(this._managedTextures, i, 1); + } + } + } + }; + + /** + * Deletes all the textures from WebGL + */ + + + TextureManager.prototype.removeAll = function removeAll() { + // empty all the old gl textures as they are useless now + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + delete texture._glTextures[this.renderer.CONTEXT_UID]; + } + } + }; + + /** + * Destroys this manager and removes all its textures + */ + + + TextureManager.prototype.destroy = function destroy() { + // destroy managed textures + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + this.destroyTexture(texture, true); + + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + } + + this._managedTextures = null; + }; + + return TextureManager; +}(); + +exports.default = TextureManager; + +},{"../../const":78,"../../utils":152,"./utils/RenderTarget":128,"pixi-gl-core":51}],116:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _MaskManager = require('./managers/MaskManager'); + +var _MaskManager2 = _interopRequireDefault(_MaskManager); + +var _StencilManager = require('./managers/StencilManager'); + +var _StencilManager2 = _interopRequireDefault(_StencilManager); + +var _FilterManager = require('./managers/FilterManager'); + +var _FilterManager2 = _interopRequireDefault(_FilterManager); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _ObjectRenderer = require('./utils/ObjectRenderer'); + +var _ObjectRenderer2 = _interopRequireDefault(_ObjectRenderer); + +var _TextureManager = require('./TextureManager'); + +var _TextureManager2 = _interopRequireDefault(_TextureManager); + +var _TextureGarbageCollector = require('./TextureGarbageCollector'); + +var _TextureGarbageCollector2 = _interopRequireDefault(_TextureGarbageCollector); + +var _WebGLState = require('./WebGLState'); + +var _WebGLState2 = _interopRequireDefault(_WebGLState); + +var _mapWebGLDrawModesToPixi = require('./utils/mapWebGLDrawModesToPixi'); + +var _mapWebGLDrawModesToPixi2 = _interopRequireDefault(_mapWebGLDrawModesToPixi); + +var _validateContext = require('./utils/validateContext'); + +var _validateContext2 = _interopRequireDefault(_validateContext); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CONTEXT_UID = 0; + +/** + * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ + +var WebGLRenderer = function (_SystemRenderer) { + _inherits(WebGLRenderer, _SystemRenderer); + + /** + * + * @param {number} [width=0] - the width of the canvas view + * @param {number} [height=0] - the height of the canvas view + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias. If not available natively then FXAA + * antialiasing is used + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. + * The resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear + * the canvas or not before the new render pass. If you wish to set this to false, you *must* set + * preserveDrawingBuffer to `true`. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when + * rendering, stopping pixel interpolation. + */ + function WebGLRenderer(width, height) { + var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + + _classCallCheck(this, WebGLRenderer); + + /** + * The type of this renderer as a standardised const + * + * @member {number} + * @see PIXI.RENDERER_TYPE + */ + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'WebGL', width, height, options)); + + _this.type = _const.RENDERER_TYPE.WEBGL; + + _this.handleContextLost = _this.handleContextLost.bind(_this); + _this.handleContextRestored = _this.handleContextRestored.bind(_this); + + _this.view.addEventListener('webglcontextlost', _this.handleContextLost, false); + _this.view.addEventListener('webglcontextrestored', _this.handleContextRestored, false); + + /** + * The options passed in to create a new webgl context. + * + * @member {object} + * @private + */ + _this._contextOptions = { + alpha: _this.transparent, + antialias: options.antialias, + premultipliedAlpha: _this.transparent && _this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: options.preserveDrawingBuffer + }; + + _this._backgroundColorRgba[3] = _this.transparent ? 0 : 1; + + /** + * Manages the masks using the stencil buffer. + * + * @member {PIXI.MaskManager} + */ + _this.maskManager = new _MaskManager2.default(_this); + + /** + * Manages the stencil buffer. + * + * @member {PIXI.StencilManager} + */ + _this.stencilManager = new _StencilManager2.default(_this); + + /** + * An empty renderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.emptyRenderer = new _ObjectRenderer2.default(_this); + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.currentRenderer = _this.emptyRenderer; + + _this.initPlugins(); + + /** + * The current WebGL rendering context, it is created here + * + * @member {WebGLRenderingContext} + */ + // initialize the context so it is ready for the managers. + if (options.context) { + // checks to see if a context is valid.. + (0, _validateContext2.default)(options.context); + } + + _this.gl = options.context || _pixiGlCore2.default.createContext(_this.view, _this._contextOptions); + + _this.CONTEXT_UID = CONTEXT_UID++; + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.WebGLState} + */ + _this.state = new _WebGLState2.default(_this.gl); + + _this.renderingToScreen = true; + + _this._initContext(); + + /** + * Manages the filters. + * + * @member {PIXI.FilterManager} + */ + _this.filterManager = new _FilterManager2.default(_this); + // map some webGL blend and drawmodes.. + _this.drawModes = (0, _mapWebGLDrawModesToPixi2.default)(_this.gl); + + /** + * Holds the current shader + * + * @member {PIXI.Shader} + */ + _this._activeShader = null; + + /** + * Holds the current render target + * + * @member {PIXI.RenderTarget} + */ + _this._activeRenderTarget = null; + _this._activeTextureLocation = 999; + _this._activeTexture = null; + + _this.setBlendMode(0); + return _this; + } + + /** + * Creates the WebGL context + * + * @private + */ + + + WebGLRenderer.prototype._initContext = function _initContext() { + var gl = this.gl; + + // create a texture manager... + this.textureManager = new _TextureManager2.default(this); + this.textureGC = new _TextureGarbageCollector2.default(this); + + this.state.resetToDefault(); + + this.rootRenderTarget = new _RenderTarget2.default(gl, this.width, this.height, null, this.resolution, true); + this.rootRenderTarget.clearColor = this._backgroundColorRgba; + + this.bindRenderTarget(this.rootRenderTarget); + + this.emit('context', gl); + + // setup the width/height properties and gl viewport + this.resize(this.width, this.height); + }; + + /** + * Renders the object to its webGL view + * + * @param {PIXI.DisplayObject} displayObject - the object to be rendered + * @param {PIXI.RenderTexture} renderTexture - The render texture to render to. + * @param {boolean} [clear] - Should the canvas be cleared before the new render + * @param {PIXI.Transform} [transform] - A transform to apply to the render texture before rendering. + * @param {boolean} [skipUpdateTransform] - Should we skip the update transform pass? + */ + + + WebGLRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + // no point rendering if our context has been blown up! + if (!this.gl || this.gl.isContextLost()) { + return; + } + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + this.bindRenderTexture(renderTexture, transform); + + this.currentRenderer.start(); + + if (clear !== undefined ? clear : this.clearBeforeRender) { + this._activeRenderTarget.clear(); + } + + displayObject.renderWebGL(this); + + // apply transform.. + this.currentRenderer.flush(); + + // this.setObjectRenderer(this.emptyRenderer); + + this.textureGC.update(); + + this.emit('postrender'); + }; + + /** + * Changes the current renderer to the one given in parameter + * + * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. + */ + + + WebGLRenderer.prototype.setObjectRenderer = function setObjectRenderer(objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; + + /** + * This shoudl be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + * + */ + + + WebGLRenderer.prototype.flush = function flush() { + this.setObjectRenderer(this.emptyRenderer); + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} width - the new width of the webGL view + * @param {number} height - the new height of the webGL view + */ + + + WebGLRenderer.prototype.resize = function resize(width, height) { + // if(width * this.resolution === this.width && height * this.resolution === this.height)return; + + _SystemRenderer3.default.prototype.resize.call(this, width, height); + + this.rootRenderTarget.resize(width, height); + + if (this._activeRenderTarget === this.rootRenderTarget) { + this.rootRenderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true); + } + } + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} blendMode - the desired blend mode + */ + + + WebGLRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + this.state.setBlendMode(blendMode); + }; + + /** + * Erases the active render target and fills the drawing area with a colour + * + * @param {number} [clearColor] - The colour + */ + + + WebGLRenderer.prototype.clear = function clear(clearColor) { + this._activeRenderTarget.clear(clearColor); + }; + + /** + * Sets the transform of the active render target to the given matrix + * + * @param {PIXI.Matrix} matrix - The transformation matrix + */ + + + WebGLRenderer.prototype.setTransform = function setTransform(matrix) { + this._activeRenderTarget.transform = matrix; + }; + + /** + * Binds a render texture for rendering + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to render + * @param {PIXI.Transform} transform - The transform to be applied to the render texture + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTexture = function bindRenderTexture(renderTexture, transform) { + var renderTarget = void 0; + + if (renderTexture) { + var baseTexture = renderTexture.baseTexture; + var gl = this.gl; + + if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) { + this.textureManager.updateTexture(baseTexture); + gl.bindTexture(gl.TEXTURE_2D, null); + } else { + // the texture needs to be unbound if its being rendererd too.. + this._activeTextureLocation = baseTexture._id; + gl.activeTexture(gl.TEXTURE0 + baseTexture._id); + gl.bindTexture(gl.TEXTURE_2D, null); + } + + renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + renderTarget.setFrame(renderTexture.frame); + } else { + renderTarget = this.rootRenderTarget; + } + + renderTarget.transform = transform; + this.bindRenderTarget(renderTarget); + + return this; + }; + + /** + * Changes the current render target to the one given in parameter + * + * @param {PIXI.RenderTarget} renderTarget - the new render target + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTarget = function bindRenderTarget(renderTarget) { + if (renderTarget !== this._activeRenderTarget) { + this._activeRenderTarget = renderTarget; + renderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true); + } + + this.stencilManager.setMaskStack(renderTarget.stencilMaskStack); + } + + return this; + }; + + /** + * Changes the current shader to the one given in parameter + * + * @param {PIXI.Shader} shader - the new shader + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindShader = function bindShader(shader) { + // TODO cache + if (this._activeShader !== shader) { + this._activeShader = shader; + shader.bind(); + + // automatically set the projection matrix + shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(true); + } + + return this; + }; + + /** + * Binds the texture ... @mat + * + * @param {PIXI.Texture} texture - the new texture + * @param {number} location - the texture location + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindTexture = function bindTexture(texture) { + var location = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + + texture = texture.baseTexture || texture; + + var gl = this.gl; + + // TODO test perf of cache? + + if (this._activeTextureLocation !== location) // + { + this._activeTextureLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + + // TODO - can we cache this texture too? + this._activeTexture = texture; + + if (!texture._glTextures[this.CONTEXT_UID]) { + // this will also bind the texture.. + this.textureManager.updateTexture(texture); + } else { + texture.touched = this.textureGC.count; + // bind the current texture + texture._glTextures[this.CONTEXT_UID].bind(); + } + + return this; + }; + + /** + * Creates a new VAO from this renderer's context and state. + * + * @return {VertexArrayObject} The new VAO. + */ + + + WebGLRenderer.prototype.createVao = function createVao() { + return new _pixiGlCore2.default.VertexArrayObject(this.gl, this.state.attribState); + }; + + /** + * Resets the WebGL state so you can render things however you fancy! + * + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.reset = function reset() { + this.setObjectRenderer(this.emptyRenderer); + + this._activeShader = null; + this._activeRenderTarget = this.rootRenderTarget; + this._activeTextureLocation = 999; + this._activeTexture = null; + + // bind the main frame buffer (the screen); + this.rootRenderTarget.activate(); + + this.state.resetToDefault(); + + return this; + }; + + /** + * Handles a lost webgl context + * + * @private + * @param {WebGLContextEvent} event - The context lost event. + */ + + + WebGLRenderer.prototype.handleContextLost = function handleContextLost(event) { + event.preventDefault(); + }; + + /** + * Handles a restored webgl context + * + * @private + */ + + + WebGLRenderer.prototype.handleContextRestored = function handleContextRestored() { + this._initContext(); + this.textureManager.removeAll(); + }; + + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + + + WebGLRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // remove listeners + this.view.removeEventListener('webglcontextlost', this.handleContextLost); + this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); + + this.textureManager.destroy(); + + // call base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.uid = 0; + + // destroy the managers + this.maskManager.destroy(); + this.stencilManager.destroy(); + this.filterManager.destroy(); + + this.maskManager = null; + this.filterManager = null; + this.textureManager = null; + this.currentRenderer = null; + + this.handleContextLost = null; + this.handleContextRestored = null; + + this._contextOptions = null; + this.gl.useProgram(null); + + if (this.gl.getExtension('WEBGL_lose_context')) { + this.gl.getExtension('WEBGL_lose_context').loseContext(); + } + + this.gl = null; + + // this = null; + }; + + return WebGLRenderer; +}(_SystemRenderer3.default); + +exports.default = WebGLRenderer; + + +_utils.pluginTarget.mixin(WebGLRenderer); + +},{"../../const":78,"../../utils":152,"../SystemRenderer":108,"./TextureGarbageCollector":114,"./TextureManager":115,"./WebGLState":117,"./managers/FilterManager":122,"./managers/MaskManager":123,"./managers/StencilManager":124,"./utils/ObjectRenderer":126,"./utils/RenderTarget":128,"./utils/mapWebGLDrawModesToPixi":131,"./utils/validateContext":132,"pixi-gl-core":51}],117:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); + +var _mapWebGLBlendModesToPixi2 = _interopRequireDefault(_mapWebGLBlendModesToPixi); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var BLEND = 0; +var DEPTH_TEST = 1; +var FRONT_FACE = 2; +var CULL_FACE = 3; +var BLEND_FUNC = 4; + +/** + * A WebGL state machines + * + * @memberof PIXI + * @class + */ + +var WebGLState = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + */ + function WebGLState(gl) { + _classCallCheck(this, WebGLState); + + /** + * The current active state + * + * @member {Uint8Array} + */ + this.activeState = new Uint8Array(16); + + /** + * The default state + * + * @member {Uint8Array} + */ + this.defaultState = new Uint8Array(16); + + // default blend mode.. + this.defaultState[0] = 1; + + /** + * The current state index in the stack + * + * @member {number} + * @private + */ + this.stackIndex = 0; + + /** + * The stack holding all the different states + * + * @member {Array<*>} + * @private + */ + this.stack = []; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + this.attribState = { + tempAttribState: new Array(this.maxAttribs), + attribState: new Array(this.maxAttribs) + }; + + this.blendModes = (0, _mapWebGLBlendModesToPixi2.default)(gl); + + // check we have vao.. + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || gl.getExtension('MOZ_OES_vertex_array_object') || gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + /** + * Pushes a new active state + */ + + + WebGLState.prototype.push = function push() { + // next state.. + var state = this.stack[++this.stackIndex]; + + if (!state) { + state = this.stack[this.stackIndex] = new Uint8Array(16); + } + + // copy state.. + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) { + this.activeState[i] = state[i]; + } + }; + + /** + * Pops a state out + */ + + + WebGLState.prototype.pop = function pop() { + var state = this.stack[--this.stackIndex]; + + this.setState(state); + }; + + /** + * Sets the current state + * + * @param {*} state - The state to set. + */ + + + WebGLState.prototype.setState = function setState(state) { + this.setBlend(state[BLEND]); + this.setDepthTest(state[DEPTH_TEST]); + this.setFrontFace(state[FRONT_FACE]); + this.setCullFace(state[CULL_FACE]); + this.setBlendMode(state[BLEND_FUNC]); + }; + + /** + * Enables or disabled blending. + * + * @param {boolean} value - Turn on or off webgl blending. + */ + + + WebGLState.prototype.setBlend = function setBlend(value) { + value = value ? 1 : 0; + + if (this.activeState[BLEND] === value) { + return; + } + + this.activeState[BLEND] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + }; + + /** + * Sets the blend mode. + * + * @param {number} value - The blend mode to set to. + */ + + + WebGLState.prototype.setBlendMode = function setBlendMode(value) { + if (value === this.activeState[BLEND_FUNC]) { + return; + } + + this.activeState[BLEND_FUNC] = value; + + this.gl.blendFunc(this.blendModes[value][0], this.blendModes[value][1]); + }; + + /** + * Sets whether to enable or disable depth test. + * + * @param {boolean} value - Turn on or off webgl depth testing. + */ + + + WebGLState.prototype.setDepthTest = function setDepthTest(value) { + value = value ? 1 : 0; + + if (this.activeState[DEPTH_TEST] === value) { + return; + } + + this.activeState[DEPTH_TEST] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + }; + + /** + * Sets whether to enable or disable cull face. + * + * @param {boolean} value - Turn on or off webgl cull face. + */ + + + WebGLState.prototype.setCullFace = function setCullFace(value) { + value = value ? 1 : 0; + + if (this.activeState[CULL_FACE] === value) { + return; + } + + this.activeState[CULL_FACE] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + }; + + /** + * Sets the gl front face. + * + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ + + + WebGLState.prototype.setFrontFace = function setFrontFace(value) { + value = value ? 1 : 0; + + if (this.activeState[FRONT_FACE] === value) { + return; + } + + this.activeState[FRONT_FACE] = value; + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); + }; + + /** + * Disables all the vaos in use + * + */ + + + WebGLState.prototype.resetAttributes = function resetAttributes() { + for (var i = 0; i < this.attribState.tempAttribState.length; i++) { + this.attribState.tempAttribState[i] = 0; + } + + for (var _i = 0; _i < this.attribState.attribState.length; _i++) { + this.attribState.attribState[_i] = 0; + } + + // im going to assume one is always active for performance reasons. + for (var _i2 = 1; _i2 < this.maxAttribs; _i2++) { + this.gl.disableVertexAttribArray(_i2); + } + }; + + // used + /** + * Resets all the logic and disables the vaos + */ + + + WebGLState.prototype.resetToDefault = function resetToDefault() { + // unbind any VAO if they exist.. + if (this.nativeVaoExtension) { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + // reset all attributs.. + this.resetAttributes(); + + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; ++i) { + this.activeState[i] = 32; + } + + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + + this.setState(this.defaultState); + }; + + return WebGLState; +}(); + +exports.default = WebGLState; + +},{"./utils/mapWebGLBlendModesToPixi":130}],118:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _extractUniformsFromSrc = require('./extractUniformsFromSrc'); + +var _extractUniformsFromSrc2 = _interopRequireDefault(_extractUniformsFromSrc); + +var _utils = require('../../../utils'); + +var _const = require('../../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SOURCE_KEY_MAP = {}; + +// let math = require('../../../math'); +/** + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ + +var Filter = function () { + /** + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. + */ + function Filter(vertexSrc, fragmentSrc, uniforms) { + _classCallCheck(this, Filter); + + /** + * The vertex shader. + * + * @member {string} + */ + this.vertexSrc = vertexSrc || Filter.defaultVertexSrc; + + /** + * The fragment shader. + * + * @member {string} + */ + this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc; + + this.blendMode = _const.BLEND_MODES.NORMAL; + + // pull out the vertex and shader uniforms if they are not specified.. + // currently this does not extract structs only default types + this.uniformData = uniforms || (0, _extractUniformsFromSrc2.default)(this.vertexSrc, this.fragmentSrc, 'projectionMatrix|uSampler'); + + this.uniforms = {}; + + for (var i in this.uniformData) { + this.uniforms[i] = this.uniformData[i].value; + } + + // this is where we store shader references.. + // TODO we could cache this! + this.glShaders = []; + + // used for cacheing.. sure there is a better way! + if (!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) { + SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = (0, _utils.uid)(); + } + + this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]; + + /** + * The padding of the filter. Some filters require extra space to breath such as a blur. + * Increasing this will add extra width and height to the bounds of the object that the + * filter is applied to. + * + * @member {number} + */ + this.padding = 4; + + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + * + * @member {number} + */ + this.resolution = 1; + + /** + * If enabled is true the filter is applied, if false it will not. + * + * @member {boolean} + */ + this.enabled = true; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + Filter.prototype.apply = function apply(filterManager, input, output, clear) { + // --- // + // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); + + // do as you please! + + filterManager.applyFilter(this, input, output, clear); + + // or just do a regular render.. + }; + + /** + * The default vertex shader source + * + * @static + * @constant + */ + + + _createClass(Filter, null, [{ + key: 'defaultVertexSrc', + get: function get() { + return ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform mat3 projectionMatrix;', 'uniform mat3 filterMatrix;', 'varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;', ' vTextureCoord = aTextureCoord ;', '}'].join('\n'); + } + + /** + * The default fragment shader source + * + * @static + * @constant + */ + + }, { + key: 'defaultFragmentSrc', + get: function get() { + return ['varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'uniform sampler2D uSampler;', 'uniform sampler2D filterSampler;', 'void main(void){', ' vec4 masky = texture2D(filterSampler, vFilterCoord);', ' vec4 sample = texture2D(uSampler, vTextureCoord);', ' vec4 color;', ' if(mod(vFilterCoord.x, 1.0) > 0.5)', ' {', ' color = vec4(1.0, 0.0, 0.0, 1.0);', ' }', ' else', ' {', ' color = vec4(0.0, 1.0, 0.0, 1.0);', ' }', + // ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', + ' gl_FragColor = mix(sample, masky, 0.5);', ' gl_FragColor *= sample.a;', '}'].join('\n'); + } + }]); + + return Filter; +}(); + +exports.default = Filter; + +},{"../../../const":78,"../../../utils":152,"./extractUniformsFromSrc":119}],119:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = extractUniformsFromSrc; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var defaultValue = _pixiGlCore2.default.shader.defaultValue; + +function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) { + var vertUniforms = extractUniformsFromString(vertexSrc, mask); + var fragUniforms = extractUniformsFromString(fragmentSrc, mask); + + return Object.assign(vertUniforms, fragUniforms); +} + +function extractUniformsFromString(string) { + var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea)$'); + + var uniforms = {}; + var nameSplit = void 0; + + // clean the lines a little - remove extra spaces / teabs etc + // then split along ';' + var lines = string.replace(/\s+/g, ' ').split(/\s*;\s*/); + + // loop through.. + for (var i = 0; i < lines.length; i++) { + var line = lines[i].trim(); + + if (line.indexOf('uniform') > -1) { + var splitLine = line.split(' '); + var type = splitLine[1]; + + var name = splitLine[2]; + var size = 1; + + if (name.indexOf('[') > -1) { + // array! + nameSplit = name.split(/\[|\]/); + name = nameSplit[0]; + size *= Number(nameSplit[1]); + } + + if (!name.match(maskRegex)) { + uniforms[name] = { + value: defaultValue(type, size), + name: name, + type: type + }; + } + } + } + + return uniforms; +} + +},{"pixi-gl-core":51}],120:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.calculateScreenSpaceMatrix = calculateScreenSpaceMatrix; +exports.calculateNormalizedScreenSpaceMatrix = calculateNormalizedScreenSpaceMatrix; +exports.calculateSpriteMatrix = calculateSpriteMatrix; + +var _math = require('../../../math'); + +/* + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// thia returns a matrix that will normalise map filter cords in the filter to screen space +function calculateScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + // let worldTransform = sprite.worldTransform.copy(Matrix.TEMP_MATRIX), + // let texture = {width:1136, height:700};//sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(textureSize.width, textureSize.height); + + return mappedMatrix; +} + +function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + var translateScaleX = textureSize.width / filterArea.width; + var translateScaleY = textureSize.height / filterArea.height; + + mappedMatrix.scale(translateScaleX, translateScaleY); + + return mappedMatrix; +} + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +function calculateSpriteMatrix(outputMatrix, filterArea, textureSize, sprite) { + var worldTransform = sprite.worldTransform.copy(_math.Matrix.TEMP_MATRIX); + var texture = sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + // scale.. + var ratio = textureSize.height / textureSize.width; + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(1, ratio); + + var translateScaleX = textureSize.width / texture.width; + var translateScaleY = textureSize.height / texture.height; + + worldTransform.tx /= texture.width * translateScaleX; + + // this...? free beer for anyone who can explain why this makes sense! + worldTransform.ty /= texture.width * translateScaleX; + // worldTransform.ty /= texture.height * translateScaleY; + + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + + // apply inverse scale.. + mappedMatrix.scale(1, 1 / ratio); + + mappedMatrix.scale(translateScaleX, translateScaleY); + + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; +} + +},{"../../../math":102}],121:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Filter2 = require('../Filter'); + +var _Filter3 = _interopRequireDefault(_Filter2); + +var _math = require('../../../../math'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// @see https://github.com/substack/brfs/issues/25 + // eslint-disable-line no-undef + +/** + * The SpriteMaskFilter class + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + */ + +var SpriteMaskFilter = function (_Filter) { + _inherits(SpriteMaskFilter, _Filter); + + /** + * @param {PIXI.Sprite} sprite - the target sprite + */ + function SpriteMaskFilter(sprite) { + _classCallCheck(this, SpriteMaskFilter); + + var maskMatrix = new _math.Matrix(); + + var _this = _possibleConstructorReturn(this, _Filter.call(this, "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n", "#define GLSLIFY 1\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n")); + + sprite.renderable = false; + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + return _this; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + */ + + + SpriteMaskFilter.prototype.apply = function apply(filterManager, input, output) { + var maskSprite = this.maskSprite; + + this.uniforms.mask = maskSprite._texture; + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite); + this.uniforms.alpha = maskSprite.worldAlpha; + + filterManager.applyFilter(this, input, output); + }; + + return SpriteMaskFilter; +}(_Filter3.default); + +exports.default = SpriteMaskFilter; + +},{"../../../../math":102,"../Filter":118}],122:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _RenderTarget = require('../utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _Quad = require('../utils/Quad'); + +var _Quad2 = _interopRequireDefault(_Quad); + +var _math = require('../../../math'); + +var _Shader = require('../../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _filterTransforms = require('../filters/filterTransforms'); + +var filterTransforms = _interopRequireWildcard(_filterTransforms); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @ignore + * @class + */ +var FilterState = +/** + * + */ +function FilterState() { + _classCallCheck(this, FilterState); + + this.renderTarget = null; + this.sourceFrame = new _math.Rectangle(); + this.destinationFrame = new _math.Rectangle(); + this.filters = []; + this.target = null; + this.resolution = 1; +}; + +/** + * @class + * @memberof PIXI + * @extends PIXI.WebGLManager + */ + + +var FilterManager = function (_WebGLManager) { + _inherits(FilterManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function FilterManager(renderer) { + _classCallCheck(this, FilterManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.gl = _this.renderer.gl; + // know about sprites! + _this.quad = new _Quad2.default(_this.gl, renderer.state.attribState); + + _this.shaderCache = {}; + // todo add default! + _this.pool = {}; + + _this.filterData = null; + return _this; + } + + /** + * Adds a new filter to the manager. + * + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param {PIXI.Filter[]} filters - The filters to apply. + */ + + + FilterManager.prototype.pushFilter = function pushFilter(target, filters) { + var renderer = this.renderer; + + var filterData = this.filterData; + + if (!filterData) { + filterData = this.renderer._activeRenderTarget.filterStack; + + // add new stack + var filterState = new FilterState(); + + filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; + filterState.renderTarget = renderer._activeRenderTarget; + + this.renderer._activeRenderTarget.filterData = filterData = { + index: 0, + stack: [filterState] + }; + + this.filterData = filterData; + } + + // get the current filter state.. + var currentState = filterData.stack[++filterData.index]; + + if (!currentState) { + currentState = filterData.stack[filterData.index] = new FilterState(); + } + + // for now we go off the filter of the first resolution.. + var resolution = filters[0].resolution; + var padding = filters[0].padding | 0; + var targetBounds = target.filterArea || target.getBounds(true); + var sourceFrame = currentState.sourceFrame; + var destinationFrame = currentState.destinationFrame; + + sourceFrame.x = (targetBounds.x * resolution | 0) / resolution; + sourceFrame.y = (targetBounds.y * resolution | 0) / resolution; + sourceFrame.width = (targetBounds.width * resolution | 0) / resolution; + sourceFrame.height = (targetBounds.height * resolution | 0) / resolution; + + if (filterData.stack[0].renderTarget.transform) {// + + // TODO we should fit the rect around the transform.. + } else { + sourceFrame.fit(filterData.stack[0].destinationFrame); + } + + // lets pplay the padding After we fit the element to the screen. + // this should stop the strange side effects that can occour when cropping to the edges + sourceFrame.pad(padding); + + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + + // lets play the padding after we fit the element to the screen. + // this should stop the strange side effects that can occour when cropping to the edges + + var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); + + currentState.target = target; + currentState.filters = filters; + currentState.resolution = resolution; + currentState.renderTarget = renderTarget; + + // bind the render taget to draw the shape in the top corner.. + + renderTarget.setFrame(destinationFrame, sourceFrame); + // bind the render target + renderer.bindRenderTarget(renderTarget); + + // clear the renderTarget + renderer.clear(); // [0.5,0.5,0.5, 1.0]); + }; + + /** + * Pops off the filter and applies it. + * + */ + + + FilterManager.prototype.popFilter = function popFilter() { + var filterData = this.filterData; + + var lastState = filterData.stack[filterData.index - 1]; + var currentState = filterData.stack[filterData.index]; + + this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); + + var filters = currentState.filters; + + if (filters.length === 1) { + filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false); + this.freePotRenderTarget(currentState.renderTarget); + } else { + var flip = currentState.renderTarget; + var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, 1); + + flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + var i = 0; + + for (i = 0; i < filters.length - 1; ++i) { + filters[i].apply(this, flip, flop, true); + + var t = flip; + + flip = flop; + flop = t; + } + + filters[i].apply(this, flip, lastState.renderTarget, false); + + this.freePotRenderTarget(flip); + this.freePotRenderTarget(flop); + } + + filterData.index--; + + if (filterData.index === 0) { + this.filterData = null; + } + }; + + /** + * Draws a filter. + * + * @param {PIXI.Filter} filter - The filter to draw. + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + FilterManager.prototype.applyFilter = function applyFilter(filter, input, output, clear) { + var renderer = this.renderer; + var shader = filter.glShaders[renderer.CONTEXT_UID]; + + // cacheing.. + if (!shader) { + if (filter.glShaderKey) { + shader = this.shaderCache[filter.glShaderKey]; + + if (!shader) { + shader = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + + filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = shader; + } + } else { + shader = filter.glShaders[renderer.CONTEXT_UID] = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + } + + // TODO - this only needs to be done once? + this.quad.initVao(shader); + } + + renderer.bindRenderTarget(output); + + if (clear) { + var gl = renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + renderer.clear(); // [1, 1, 1, 1]); + gl.enable(gl.SCISSOR_TEST); + } + + // in case the render target is being masked using a scissor rect + if (output === renderer.maskManager.scissorRenderTarget) { + renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); + } + + renderer.bindShader(shader); + + // this syncs the pixi filters uniforms with glsl uniforms + this.syncUniforms(shader, filter); + + // bind the input texture.. + input.texture.bind(0); + // when you manually bind a texture, please switch active texture location to it + renderer._activeTextureLocation = 0; + + renderer.state.setBlendMode(filter.blendMode); + + this.quad.draw(); + }; + + /** + * Uploads the uniforms of the filter. + * + * @param {GLShader} shader - The underlying gl shader. + * @param {PIXI.Filter} filter - The filter we are synchronizing. + */ + + + FilterManager.prototype.syncUniforms = function syncUniforms(shader, filter) { + var uniformData = filter.uniformData; + var uniforms = filter.uniforms; + + // 0 is reserverd for the pixi texture so we start at 1! + var textureCount = 1; + var currentState = void 0; + + if (shader.uniforms.data.filterArea) { + currentState = this.filterData.stack[this.filterData.index]; + var filterArea = shader.uniforms.filterArea; + + filterArea[0] = currentState.renderTarget.size.width; + filterArea[1] = currentState.renderTarget.size.height; + filterArea[2] = currentState.sourceFrame.x; + filterArea[3] = currentState.sourceFrame.y; + + shader.uniforms.filterArea = filterArea; + } + + // use this to clamp displaced texture coords so they belong to filterArea + // see displacementFilter fragment shader for an example + if (shader.uniforms.data.filterClamp) { + currentState = this.filterData.stack[this.filterData.index]; + + var filterClamp = shader.uniforms.filterClamp; + + filterClamp[0] = 0; + filterClamp[1] = 0; + filterClamp[2] = (currentState.sourceFrame.width - 1) / currentState.renderTarget.size.width; + filterClamp[3] = (currentState.sourceFrame.height - 1) / currentState.renderTarget.size.height; + + shader.uniforms.filterClamp = filterClamp; + } + + // TODO Cacheing layer.. + for (var i in uniformData) { + if (uniformData[i].type === 'sampler2D') { + shader.uniforms[i] = textureCount; + + if (uniforms[i].baseTexture) { + this.renderer.bindTexture(uniforms[i].baseTexture, textureCount); + } else { + // this is helpful as renderTargets can also be set. + // Although thinking about it, we could probably + // make the filter texture cache return a RenderTexture + // rather than a renderTarget + var gl = this.renderer.gl; + + this.renderer._activeTextureLocation = gl.TEXTURE0 + textureCount; + + gl.activeTexture(gl.TEXTURE0 + textureCount); + uniforms[i].texture.bind(); + } + + textureCount++; + } else if (uniformData[i].type === 'mat3') { + // check if its pixi matrix.. + if (uniforms[i].a !== undefined) { + shader.uniforms[i] = uniforms[i].toArray(true); + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (uniformData[i].type === 'vec2') { + // check if its a point.. + if (uniforms[i].x !== undefined) { + var val = shader.uniforms[i] || new Float32Array(2); + + val[0] = uniforms[i].x; + val[1] = uniforms[i].y; + shader.uniforms[i] = val; + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (uniformData[i].type === 'float') { + if (shader.uniforms.data[i].value !== uniformData[i]) { + shader.uniforms[i] = uniforms[i]; + } + } else { + shader.uniforms[i] = uniforms[i]; + } + } + }; + + /** + * Gets a render target from the pool, or creates a new one. + * + * @param {boolean} clear - Should we clear the render texture when we get it? + * @param {number} resolution - The resolution of the target. + * @return {PIXI.RenderTarget} The new render target + */ + + + FilterManager.prototype.getRenderTarget = function getRenderTarget(clear, resolution) { + var currentState = this.filterData.stack[this.filterData.index]; + var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution); + + renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + return renderTarget; + }; + + /** + * Returns a render target to the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The render target to return. + */ + + + FilterManager.prototype.returnRenderTarget = function returnRenderTarget(renderTarget) { + this.freePotRenderTarget(renderTarget); + }; + + /** + * Calculates the mapped matrix. + * + * TODO playing around here.. this is temporary - (will end up in the shader) + * this returns a matrix that will normalise map filter cords in the filter to screen space + * + * @param {PIXI.Matrix} outputMatrix - the matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateScreenSpaceMatrix = function calculateScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); + }; + + /** + * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function calculateNormalizedScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); + }; + + /** + * This will map the filter coord so that a texture can be used based on the transform of a sprite + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateSpriteMatrix = function calculateSpriteMatrix(outputMatrix, sprite) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); + }; + + /** + * Destroys this Filter Manager. + * + */ + + + FilterManager.prototype.destroy = function destroy() { + this.shaderCache = []; + this.emptyPool(); + }; + + /** + * Gets a Power-of-Two render texture. + * + * TODO move to a seperate class could be on renderer? + * also - could cause issue with multiple contexts? + * + * @private + * @param {WebGLRenderingContext} gl - The webgl rendering context + * @param {number} minWidth - The minimum width of the render target. + * @param {number} minHeight - The minimum height of the render target. + * @param {number} resolution - The resolution of the render target. + * @return {PIXI.RenderTarget} The new render target. + */ + + + FilterManager.prototype.getPotRenderTarget = function getPotRenderTarget(gl, minWidth, minHeight, resolution) { + // TODO you coud return a bigger texture if there is not one in the pool? + minWidth = _bitTwiddle2.default.nextPow2(minWidth * resolution); + minHeight = _bitTwiddle2.default.nextPow2(minHeight * resolution); + + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + if (!this.pool[key]) { + this.pool[key] = []; + } + + var renderTarget = this.pool[key].pop() || new _RenderTarget2.default(gl, minWidth, minHeight, null, 1); + + // manually tweak the resolution... + // this will not modify the size of the frame buffer, just its resolution. + renderTarget.resolution = resolution; + renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution; + renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution; + + return renderTarget; + }; + + /** + * Empties the texture pool. + * + */ + + + FilterManager.prototype.emptyPool = function emptyPool() { + for (var i in this.pool) { + var textures = this.pool[i]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + + this.pool = {}; + }; + + /** + * Frees a render target back into the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free + */ + + + FilterManager.prototype.freePotRenderTarget = function freePotRenderTarget(renderTarget) { + var minWidth = renderTarget.size.width * renderTarget.resolution; + var minHeight = renderTarget.size.height * renderTarget.resolution; + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + this.pool[key].push(renderTarget); + }; + + return FilterManager; +}(_WebGLManager3.default); + +exports.default = FilterManager; + +},{"../../../Shader":77,"../../../math":102,"../filters/filterTransforms":120,"../utils/Quad":127,"../utils/RenderTarget":128,"./WebGLManager":125,"bit-twiddle":14}],123:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _SpriteMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); + +var _SpriteMaskFilter2 = _interopRequireDefault(_SpriteMaskFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var MaskManager = function (_WebGLManager) { + _inherits(MaskManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function MaskManager(renderer) { + _classCallCheck(this, MaskManager); + + // TODO - we don't need both! + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.scissor = false; + _this.scissorData = null; + _this.scissorRenderTarget = null; + + _this.enableScissor = true; + + _this.alphaMaskPool = []; + _this.alphaMaskIndex = 0; + return _this; + } + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushMask = function pushMask(target, maskData) { + if (maskData.texture) { + this.pushSpriteMask(target, maskData); + } else if (this.enableScissor && !this.scissor && !this.renderer.stencilManager.stencilMaskStack.length && maskData.isFastRect()) { + var matrix = maskData.worldTransform; + + var rot = Math.atan2(matrix.b, matrix.a); + + // use the nearest degree! + rot = Math.round(rot * (180 / Math.PI)); + + if (rot % 90) { + this.pushStencilMask(maskData); + } else { + this.pushScissorMask(target, maskData); + } + } else { + this.pushStencilMask(maskData); + } + }; + + /** + * Removes the last mask from the mask stack and doesn't return it. + * + * @param {PIXI.DisplayObject} target - Display Object to pop the mask from + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.popMask = function popMask(target, maskData) { + if (maskData.texture) { + this.popSpriteMask(target, maskData); + } else if (this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length) { + this.popScissorMask(target, maskData); + } else { + this.popStencilMask(target, maskData); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.RenderTarget} target - Display Object to push the sprite mask to + * @param {PIXI.Sprite} maskData - Sprite to be used as the mask + */ + + + MaskManager.prototype.pushSpriteMask = function pushSpriteMask(target, maskData) { + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new _SpriteMaskFilter2.default(maskData)]; + } + + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskData; + + // TODO - may cause issues! + target.filterArea = maskData.getBounds(true); + + this.renderer.filterManager.pushFilter(target, alphaMaskFilter); + + this.alphaMaskIndex++; + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popSpriteMask = function popSpriteMask() { + this.renderer.filterManager.popFilter(); + this.alphaMaskIndex--; + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushStencilMask = function pushStencilMask(maskData) { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.pushStencil(maskData); + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popStencilMask = function popStencilMask() { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.popStencil(); + }; + + /** + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushScissorMask = function pushScissorMask(target, maskData) { + maskData.renderable = true; + + var renderTarget = this.renderer._activeRenderTarget; + + var bounds = maskData.getBounds(); + + bounds.fit(renderTarget.size); + maskData.renderable = false; + + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + + var resolution = this.renderer.resolution; + + this.renderer.gl.scissor(bounds.x * resolution, (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution, bounds.width * resolution, bounds.height * resolution); + + this.scissorRenderTarget = renderTarget; + this.scissorData = maskData; + this.scissor = true; + }; + + /** + * + * + */ + + + MaskManager.prototype.popScissorMask = function popScissorMask() { + this.scissorRenderTarget = null; + this.scissorData = null; + this.scissor = false; + + // must be scissor! + var gl = this.renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + }; + + return MaskManager; +}(_WebGLManager3.default); + +exports.default = MaskManager; + +},{"../filters/spriteMask/SpriteMaskFilter":121,"./WebGLManager":125}],124:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var StencilManager = function (_WebGLManager) { + _inherits(StencilManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function StencilManager(renderer) { + _classCallCheck(this, StencilManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.stencilMaskStack = null; + return _this; + } + + /** + * Changes the mask stack that is used by this manager. + * + * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack + */ + + + StencilManager.prototype.setMaskStack = function setMaskStack(stencilMaskStack) { + this.stencilMaskStack = stencilMaskStack; + + var gl = this.renderer.gl; + + if (stencilMaskStack.length === 0) { + gl.disable(gl.STENCIL_TEST); + } else { + gl.enable(gl.STENCIL_TEST); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. @alvin + * + * @param {PIXI.Graphics} graphics - The mask + */ + + + StencilManager.prototype.pushStencil = function pushStencil(graphics) { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + this.renderer._activeRenderTarget.attachStencilBuffer(); + + var gl = this.renderer.gl; + var sms = this.stencilMaskStack; + + if (sms.length === 0) { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.stencilFunc(gl.ALWAYS, 1, 1); + } + + sms.push(graphics); + + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; + + /** + * TODO @alvin + */ + + + StencilManager.prototype.popStencil = function popStencil() { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + var gl = this.renderer.gl; + var sms = this.stencilMaskStack; + + var graphics = sms.pop(); + + if (sms.length === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + } else { + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + } + }; + + /** + * Destroys the mask stack. + * + */ + + + StencilManager.prototype.destroy = function destroy() { + _WebGLManager3.default.prototype.destroy.call(this); + + this.stencilMaskStack.stencilStack = null; + }; + + return StencilManager; +}(_WebGLManager3.default); + +exports.default = StencilManager; + +},{"./WebGLManager":125}],125:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var WebGLManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function WebGLManager(renderer) { + _classCallCheck(this, WebGLManager); + + /** + * The renderer this manager works for. + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + this.renderer.on('context', this.onContextChange, this); + } + + /** + * Generic method called when there is a WebGL context change. + * + */ + + + WebGLManager.prototype.onContextChange = function onContextChange() {} + // do some codes init! + + + /** + * Generic destroy methods to be overridden by the subclass + * + */ + ; + + WebGLManager.prototype.destroy = function destroy() { + this.renderer.off('context', this.onContextChange, this); + + this.renderer = null; + }; + + return WebGLManager; +}(); + +exports.default = WebGLManager; + +},{}],126:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('../managers/WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Base for a common object renderer that can be used as a system renderer plugin. + * + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var ObjectRenderer = function (_WebGLManager) { + _inherits(ObjectRenderer, _WebGLManager); + + function ObjectRenderer() { + _classCallCheck(this, ObjectRenderer); + + return _possibleConstructorReturn(this, _WebGLManager.apply(this, arguments)); + } + + /** + * Starts the renderer and sets the shader + * + */ + ObjectRenderer.prototype.start = function start() {} + // set the shader.. + + + /** + * Stops the renderer + * + */ + ; + + ObjectRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Stub method for rendering content and emptying the current batch. + * + */ + + + ObjectRenderer.prototype.flush = function flush() {} + // flush! + + + /** + * Renders an object + * + * @param {PIXI.DisplayObject} object - The object to render. + */ + ; + + ObjectRenderer.prototype.render = function render(object) // eslint-disable-line no-unused-vars + { + // render the object + }; + + return ObjectRenderer; +}(_WebGLManager3.default); + +exports.default = ObjectRenderer; + +},{"../managers/WebGLManager":125}],127:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a quad + * + * @class + * @memberof PIXI + */ +var Quad = function () { + /** + * @param {WebGLRenderingContext} gl - The gl context for this quad to use. + * @param {object} state - TODO: Description + */ + function Quad(gl, state) { + _classCallCheck(this, Quad); + + /* + * the current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]); + + /** + * The Uvs of the quad + * + * @member {Float32Array} + */ + this.uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + this.interleaved = new Float32Array(8 * 2); + + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + this.indices = (0, _createIndicesForQuads2.default)(1); + + /* + * @member {glCore.GLBuffer} The vertex buffer + */ + this.vertexBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW); + + /* + * @member {glCore.GLBuffer} The index buffer + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + /* + * @member {glCore.VertexArrayObject} The index buffer + */ + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, state); + } + + /** + * Initialises the vaos and uses the shader. + * + * @param {PIXI.Shader} shader - the shader to use + */ + + + Quad.prototype.initVao = function initVao(shader) { + this.vao.clear().addIndex(this.indexBuffer).addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0).addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4); + }; + + /** + * Maps two Rectangle to the quad. + * + * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle + * @param {PIXI.Rectangle} destinationFrame - the second rectangle + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.map = function map(targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + + this.uvs[0] = x; + this.uvs[1] = y; + + this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; + + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; + + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; + + x = destinationFrame.x; + y = destinationFrame.y; + + this.vertices[0] = x; + this.vertices[1] = y; + + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + + return this; + }; + + /** + * Draws the quad + * + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.draw = function draw() { + this.vao.bind().draw(this.gl.TRIANGLES, 6, 0).unbind(); + + return this; + }; + + /** + * Binds the buffer and uploads the data + * + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.upload = function upload() { + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + this.vertexBuffer.upload(this.interleaved); + + return this; + }; + + /** + * Removes this quad from WebGL + */ + + + Quad.prototype.destroy = function destroy() { + var gl = this.gl; + + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.indexBuffer); + }; + + return Quad; +}(); + +exports.default = Quad; + +},{"../../../utils/createIndicesForQuads":150,"pixi-gl-core":51}],128:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../../../math'); + +var _const = require('../../../const'); + +var _pixiGlCore = require('pixi-gl-core'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var RenderTarget = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {number} [width=0] - the horizontal range of the filter + * @param {number} [height=0] - the vertical range of the filter + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The current resolution / device pixel ratio + * @param {boolean} [root=false] - Whether this object is the root element or not + */ + function RenderTarget(gl, width, height, scaleMode, resolution, root) { + _classCallCheck(this, RenderTarget); + + // TODO Resolution could go here ( eg low res blurs ) + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // next time to create a frame buffer and texture + + /** + * A frame buffer + * + * @member {PIXI.glCore.GLFramebuffer} + */ + this.frameBuffer = null; + + /** + * The texture + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The background colour of this render target, as an array of [r,g,b,a] values + * + * @member {number[]} + */ + this.clearColor = [0, 0, 0, 0]; + + /** + * The size of the object as a rectangle + * + * @member {PIXI.Rectangle} + */ + this.size = new _math.Rectangle(0, 0, 1, 1); + + /** + * The current resolution / device pixel ratio + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || _const.RESOLUTION; + + /** + * The projection matrix + * + * @member {PIXI.Matrix} + */ + this.projectionMatrix = new _math.Matrix(); + + /** + * The object's transform + * + * @member {PIXI.Matrix} + */ + this.transform = null; + + /** + * The frame. + * + * @member {PIXI.Rectangle} + */ + this.frame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.defaultFrame = new _math.Rectangle(); + this.destinationFrame = null; + this.sourceFrame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.stencilBuffer = null; + + /** + * The data structure for the stencil masks + * + * @member {PIXI.Graphics[]} + */ + this.stencilMaskStack = []; + + /** + * Stores filter data for the render target + * + * @member {object[]} + */ + this.filterData = null; + + /** + * The scale mode. + * + * @member {number} + * @default PIXI.SCALE_MODES.DEFAULT + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode || _const.SCALE_MODES.DEFAULT; + + /** + * Whether this object is the root element or not + * + * @member {boolean} + */ + this.root = root; + + if (!this.root) { + this.frameBuffer = _pixiGlCore.GLFramebuffer.createRGBA(gl, 100, 100); + + if (this.scaleMode === _const.SCALE_MODES.NEAREST) { + this.frameBuffer.texture.enableNearestScaling(); + } else { + this.frameBuffer.texture.enableLinearScaling(); + } + /* + A frame buffer needs a target to render to.. + create a texture and bind it attach it to the framebuffer.. + */ + + // this is used by the base texture + this.texture = this.frameBuffer.texture; + } else { + // make it a null framebuffer.. + this.frameBuffer = new _pixiGlCore.GLFramebuffer(gl, 100, 100); + this.frameBuffer.framebuffer = null; + } + + this.setFrame(); + + this.resize(width, height); + } + + /** + * Clears the filter texture. + * + * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer + */ + + + RenderTarget.prototype.clear = function clear(clearColor) { + var cc = clearColor || this.clearColor; + + this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a); + }; + + /** + * Binds the stencil buffer. + * + */ + + + RenderTarget.prototype.attachStencilBuffer = function attachStencilBuffer() { + // TODO check if stencil is done? + /** + * The stencil buffer is used for masking in pixi + * lets create one and then add attach it to the framebuffer.. + */ + if (!this.root) { + this.frameBuffer.enableStencil(); + } + }; + + /** + * Sets the frame of the render target. + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.setFrame = function setFrame(destinationFrame, sourceFrame) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; + }; + + /** + * Binds the buffers and initialises the viewport. + * + */ + + + RenderTarget.prototype.activate = function activate() { + // TOOD refactor usage of frame.. + var gl = this.gl; + + // make surethe texture is unbound! + this.frameBuffer.bind(); + + this.calculateProjection(this.destinationFrame, this.sourceFrame); + + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + + // TODO add a check as them may be the same! + if (this.destinationFrame !== this.sourceFrame) { + gl.enable(gl.SCISSOR_TEST); + gl.scissor(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + } else { + gl.disable(gl.SCISSOR_TEST); + } + + // TODO - does not need to be updated all the time?? + gl.viewport(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + }; + + /** + * Updates the projection matrix based on a projection frame (which is a rectangle) + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.calculateProjection = function calculateProjection(destinationFrame, sourceFrame) { + var pm = this.projectionMatrix; + + sourceFrame = sourceFrame || destinationFrame; + + pm.identity(); + + // TODO: make dest scale source + if (!this.root) { + pm.a = 1 / destinationFrame.width * 2; + pm.d = 1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = -1 - sourceFrame.y * pm.d; + } else { + pm.a = 1 / destinationFrame.width * 2; + pm.d = -1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = 1 - sourceFrame.y * pm.d; + } + }; + + /** + * Resizes the texture to the specified width and height + * + * @param {number} width - the new width of the texture + * @param {number} height - the new height of the texture + */ + + + RenderTarget.prototype.resize = function resize(width, height) { + width = width | 0; + height = height | 0; + + if (this.size.width === width && this.size.height === height) { + return; + } + + this.size.width = width; + this.size.height = height; + + this.defaultFrame.width = width; + this.defaultFrame.height = height; + + this.frameBuffer.resize(width * this.resolution, height * this.resolution); + + var projectionFrame = this.frame || this.size; + + this.calculateProjection(projectionFrame); + }; + + /** + * Destroys the render target. + * + */ + + + RenderTarget.prototype.destroy = function destroy() { + this.frameBuffer.destroy(); + + this.frameBuffer = null; + this.texture = null; + }; + + return RenderTarget; +}(); + +exports.default = RenderTarget; + +},{"../../../const":78,"../../../math":102,"pixi-gl-core":51}],129:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = checkMaxIfStatmentsInShader; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['precision mediump float;', 'void main(void){', 'float test = 0.1;', '%forloop%', 'gl_FragColor = vec4(0.0);', '}'].join('\n'); + +function checkMaxIfStatmentsInShader(maxIfs, gl) { + var createTempContext = !gl; + + if (createTempContext) { + var tinyCanvas = document.createElement('canvas'); + + tinyCanvas.width = 1; + tinyCanvas.height = 1; + + gl = _pixiGlCore2.default.createContext(tinyCanvas); + } + + var shader = gl.createShader(gl.FRAGMENT_SHADER); + + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = maxIfs / 2 | 0; + } else { + // valid! + break; + } + } + + if (createTempContext) { + // get rid of context + if (gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').loseContext(); + } + } + + return maxIfs; +} + +function generateIfTestSrc(maxIfs) { + var src = ''; + + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxIfs - 1) { + src += 'if(test == ' + i + '.0){}'; + } + } + + return src; +} + +},{"pixi-gl-core":51}],130:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLBlendModesToPixi; + +var _const = require('../../../const'); + +/** + * Maps gl blend combinations to WebGL. + * + * @memberof PIXI + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapWebGLBlendModesToPixi(gl) { + var array = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1]; + + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[_const.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD] = [gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + array[_const.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + return array; +} + +},{"../../../const":78}],131:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLDrawModesToPixi; + +var _const = require('../../../const'); + +/** + * Generic Mask Stack data structure. + * + * @class + * @memberof PIXI + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {object} [object={}] - The object to map into + * @return {object} The mapped draw modes. + */ +function mapWebGLDrawModesToPixi(gl) { + var object = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + + object[_const.DRAW_MODES.POINTS] = gl.POINTS; + object[_const.DRAW_MODES.LINES] = gl.LINES; + object[_const.DRAW_MODES.LINE_LOOP] = gl.LINE_LOOP; + object[_const.DRAW_MODES.LINE_STRIP] = gl.LINE_STRIP; + object[_const.DRAW_MODES.TRIANGLES] = gl.TRIANGLES; + object[_const.DRAW_MODES.TRIANGLE_STRIP] = gl.TRIANGLE_STRIP; + object[_const.DRAW_MODES.TRIANGLE_FAN] = gl.TRIANGLE_FAN; + + return object; +} + +},{"../../../const":78}],132:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = validateContext; +function validateContext(gl) { + var attributes = gl.getContextAttributes(); + + // this is going to be fairly simple for now.. but at least we have rom to grow! + if (!attributes.stencil) { + /* eslint-disable no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable no-console */ + } +} + +},{}],133:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new _math.Point(); + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = new PIXI.Sprite.fromImage('assets/image.png'); + * ``` + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Sprite = function (_Container) { + _inherits(Sprite, _Container); + + /** + * @param {PIXI.Texture} texture - The texture for this sprite + */ + function Sprite(texture) { + _classCallCheck(this, Sprite); + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + * @private + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this._anchor = new _math.ObservablePoint(_this._onAnchorUpdate, _this); + + /** + * The texture that the sprite is using + * + * @private + * @member {PIXI.Texture} + */ + _this._texture = null; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = null; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * The shader that will be used to render the sprite. Set to null to remove a current shader. + * + * @member {PIXI.AbstractFilter|PIXI.Shader} + */ + _this.shader = null; + + /** + * An internal cached value of the tint. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this.cachedTint = 0xFFFFFF; + + // call texture setter + _this.texture = texture || _Texture2.default.EMPTY; + + /** + * this is used to store the vertex data of the sprite (basically a quad) + * + * @private + * @member {Float32Array} + */ + _this.vertexData = new Float32Array(8); + + /** + * This is used to calculate the bounds of the object IF it is a trimmed sprite + * + * @private + * @member {Float32Array} + */ + _this.vertexTrimmedData = null; + + _this._transformID = -1; + _this._textureID = -1; + return _this; + } + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Sprite.prototype._onTextureUpdate = function _onTextureUpdate() { + this._textureID = -1; + + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = (0, _utils.sign)(this.scale.x) * this._width / this.texture.orig.width; + } + + if (this._height) { + this.scale.y = (0, _utils.sign)(this.scale.y) * this._height / this.texture.orig.height; + } + }; + + /** + * Called when the anchor position updates. + * + * @private + */ + + + Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate() { + this._transformID = -1; + }; + + /** + * calculates worldTransform * vertices, store it in vertexData + */ + + + Sprite.prototype.calculateVertices = function calculateVertices() { + if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) { + return; + } + + this._transformID = this.transform._worldID; + this._textureID = this._texture._updateID; + + // set the vertex data + + var texture = this._texture; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - this.anchor._x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - this.anchor._y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - this.anchor._x); + w1 = orig.width * -this.anchor._x; + + h0 = orig.height * (1 - this.anchor._y); + h1 = orig.height * -this.anchor._y; + } + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData + * This is used to ensure that the true width and height of a trimmed texture is respected + */ + + + Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices() { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } + + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + + var w0 = orig.width * (1 - this.anchor._x); + var w1 = orig.width * -this.anchor._x; + + var h0 = orig.height * (1 - this.anchor._y); + var h1 = orig.height * -this.anchor._y; + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use. + */ + + + Sprite.prototype._renderWebGL = function _renderWebGL(renderer) { + this.calculateVertices(); + + renderer.setObjectRenderer(renderer.plugins.sprite); + renderer.plugins.sprite.render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Sprite.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins.sprite.render(this); + }; + + /** + * Updates the bounds of the sprite. + * + * @private + */ + + + Sprite.prototype._calculateBounds = function _calculateBounds() { + var trim = this._texture.trim; + var orig = this._texture.orig; + + // First lets check to see if the current texture has a trim.. + if (!trim || trim.width === orig.width && trim.height === orig.height) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {Rectangle} rect - The output rectangle. + * @return {Rectangle} The bounds. + */ + + + Sprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = -this._texture.orig.width * this.anchor._x; + this._bounds.minY = -this._texture.orig.height * this.anchor._y; + this._bounds.maxX = this._texture.orig.width; + this._bounds.maxY = this._texture.orig.height; + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _Container.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Tests if a point is inside this sprite + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Sprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + + if (tempPoint.x > x1 && tempPoint.x < x1 + width) { + y1 = -height * this.anchor.y; + + if (tempPoint.y > y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + Sprite.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + this._anchor = null; + + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + + this._texture.destroy(!!destroyBaseTexture); + } + + this._texture = null; + this.shader = null; + }; + + // some helper functions.. + + /** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ + + + Sprite.from = function from(source) { + return new Sprite(_Texture2.default.from(source)); + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId + */ + + + Sprite.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return new Sprite(texture); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id + */ + + + Sprite.fromImage = function fromImage(imageId, crossorigin, scaleMode) { + return new Sprite(_Texture2.default.fromImage(imageId, crossorigin, scaleMode)); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Sprite# + */ + + + _createClass(Sprite, [{ + key: 'width', + get: function get() { + return Math.abs(this.scale.x) * this.texture.orig.width; + } + + /** + * Sets the width of the sprite by modifying the scale. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this.texture.orig.width; + this._width = value; + } + + /** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Sprite# + */ + + }, { + key: 'height', + get: function get() { + return Math.abs(this.scale.y) * this.texture.orig.height; + } + + /** + * Sets the height of the sprite by modifying the scale. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this.texture.orig.height; + this._height = value; + } + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + * @memberof PIXI.Sprite# + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + } + + /** + * Copies the anchor to the sprite. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this._anchor.copy(value); + } + + /** + * The tint applied to the sprite. This is a hex value. A value of + * 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @memberof PIXI.Sprite# + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return this._tint; + } + + /** + * Sets the tint of the sprite. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + } + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + * @memberof PIXI.Sprite# + */ + + }, { + key: 'texture', + get: function get() { + return this._texture; + } + + /** + * Sets the texture of the sprite. + * + * @param {PIXI.Texture} value - The value to set to. + */ + , + set: function set(value) { + if (this._texture === value) { + return; + } + + this._texture = value; + this.cachedTint = 0xFFFFFF; + + this._textureID = -1; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + }]); + + return Sprite; +}(_Container3.default); + +exports.default = Sprite; + +},{"../const":78,"../display/Container":80,"../math":102,"../textures/Texture":144,"../utils":152}],134:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +var _math = require('../../math'); + +var _CanvasTinter = require('./CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var canvasRenderWorldTransform = new _math.Matrix(); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasSpriteRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + */ + +var CanvasSpriteRenderer = function () { + /** + * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for. + */ + function CanvasSpriteRenderer(renderer) { + _classCallCheck(this, CanvasSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + CanvasSpriteRenderer.prototype.render = function render(sprite) { + var texture = sprite._texture; + var renderer = this.renderer; + + var width = texture._frame.width; + var height = texture._frame.height; + + var wt = sprite.transform.worldTransform; + var dx = 0; + var dy = 0; + + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) { + return; + } + + renderer.setBlendMode(sprite.blendMode); + + // Ignore null sources + if (texture.valid) { + renderer.context.globalAlpha = sprite.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture + var smoothingEnabled = texture.baseTexture.scaleMode === _const.SCALE_MODES.LINEAR; + + if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) { + renderer.context[renderer.smoothProperty] = smoothingEnabled; + } + + if (texture.trim) { + dx = texture.trim.width / 2 + texture.trim.x - sprite.anchor.x * texture.orig.width; + dy = texture.trim.height / 2 + texture.trim.y - sprite.anchor.y * texture.orig.height; + } else { + dx = (0.5 - sprite.anchor.x) * texture.orig.width; + dy = (0.5 - sprite.anchor.y) * texture.orig.height; + } + + if (texture.rotate) { + wt.copy(canvasRenderWorldTransform); + wt = canvasRenderWorldTransform; + _math.GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); + // the anchor has already been applied above, so lets set it to zero + dx = 0; + dy = 0; + } + + dx -= width / 2; + dy -= height / 2; + + // Allow for pixel rounding + if (renderer.roundPixels) { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution | 0, wt.ty * renderer.resolution | 0); + + dx = dx | 0; + dy = dy | 0; + } else { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution, wt.ty * renderer.resolution); + } + + var resolution = texture.baseTexture.resolution; + + if (sprite.tint !== 0xFFFFFF) { + if (sprite.cachedTint !== sprite.tint) { + sprite.cachedTint = sprite.tint; + + // TODO clean up caching - how to clean up the caches? + sprite.tintedTexture = _CanvasTinter2.default.getTintedTexture(sprite, sprite.tint); + } + + renderer.context.drawImage(sprite.tintedTexture, 0, 0, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } else { + renderer.context.drawImage(texture.baseTexture.source, texture._frame.x * resolution, texture._frame.y * resolution, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } + } + }; + + /** + * destroy the sprite object. + * + */ + + + CanvasSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasSpriteRenderer; +}(); + +exports.default = CanvasSpriteRenderer; + + +_CanvasRenderer2.default.registerPlugin('sprite', CanvasSpriteRenderer); + +},{"../../const":78,"../../math":102,"../../renderers/canvas/CanvasRenderer":109,"./CanvasTinter":135}],135:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Utility methods for Sprite/Texture tinting. + * + * @namespace PIXI.CanvasTinter + */ +var CanvasTinter = { + /** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Sprite} sprite - the sprite to tint + * @param {number} color - the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ + getTintedTexture: function getTintedTexture(sprite, color) { + var texture = sprite.texture; + + color = CanvasTinter.roundColor(color); + + var stringColor = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + texture.tintCache = texture.tintCache || {}; + + if (texture.tintCache[stringColor]) { + return texture.tintCache[stringColor]; + } + + // clone texture.. + var canvas = CanvasTinter.canvas || document.createElement('canvas'); + + // CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); + CanvasTinter.tintMethod(texture, color, canvas); + + if (CanvasTinter.convertTintToImage) { + // is this better? + var tintImage = new Image(); + + tintImage.src = canvas.toDataURL(); + + texture.tintCache[stringColor] = tintImage; + } else { + texture.tintCache[stringColor] = canvas; + // if we are not converting the texture to an image then we need to lose the reference to the canvas + CanvasTinter.canvas = null; + } + + return canvas; + }, + + /** + * Tint a texture using the 'multiply' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithMultiply: function tintWithMultiply(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = crop.width; + canvas.height = crop.height; + + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + }, + + /** + * Tint a texture using the 'overlay' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithOverlay: function tintWithOverlay(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = crop.width; + canvas.height = crop.height; + + context.globalCompositeOperation = 'copy'; + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + // context.globalCompositeOperation = 'copy'; + }, + + + /** + * Tint a texture pixel per pixel. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithPerPixel: function tintWithPerPixel(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = crop.width; + canvas.height = crop.height; + + context.globalCompositeOperation = 'copy'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + var rgbValues = (0, _utils.hex2rgb)(color); + var r = rgbValues[0]; + var g = rgbValues[1]; + var b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, crop.width, crop.height); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + } + + context.putImageData(pixelData, 0, 0); + }, + + /** + * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel. + * + * @memberof PIXI.CanvasTinter + * @param {number} color - the color to round, should be a hex color + * @return {number} The rounded color. + */ + roundColor: function roundColor(color) { + var step = CanvasTinter.cacheStepsPerColorChannel; + + var rgbValues = (0, _utils.hex2rgb)(color); + + rgbValues[0] = Math.min(255, rgbValues[0] / step * step); + rgbValues[1] = Math.min(255, rgbValues[1] / step * step); + rgbValues[2] = Math.min(255, rgbValues[2] / step * step); + + return (0, _utils.rgb2hex)(rgbValues); + }, + + /** + * Number of steps which will be used as a cap when rounding colors. + * + * @memberof PIXI.CanvasTinter + * @type {number} + */ + cacheStepsPerColorChannel: 8, + + /** + * Tint cache boolean flag. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + convertTintToImage: false, + + /** + * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + canUseMultiply: (0, _canUseNewCanvasBlendModes2.default)(), + + /** + * The tinting method that will be used. + * + * @memberof PIXI.CanvasTinter + * @type {tintMethodFunctionType} + */ + tintMethod: 0 +}; + +CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply : CanvasTinter.tintWithPerPixel; + +/** + * The tintMethod type. + * + * @memberof PIXI.CanvasTinter + * @callback tintMethodFunctionType + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + +exports.default = CanvasTinter; + +},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":112,"../../utils":152}],136:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + */ +var Buffer = function () { + /** + * @param {number} size - The size of the buffer in bytes. + */ + function Buffer(size) { + _classCallCheck(this, Buffer); + + this.vertices = new ArrayBuffer(size); + + /** + * View on the vertices as a Float32Array for positions + * + * @member {Float32Array} + */ + this.float32View = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array for uvs + * + * @member {Float32Array} + */ + this.uint32View = new Uint32Array(this.vertices); + } + + /** + * Destroys the buffer. + * + */ + + + Buffer.prototype.destroy = function destroy() { + this.vertices = null; + this.positions = null; + this.uvs = null; + this.colors = null; + }; + + return Buffer; +}(); + +exports.default = Buffer; + +},{}],137:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _createIndicesForQuads = require('../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +var _generateMultiTextureShader = require('./generateMultiTextureShader'); + +var _generateMultiTextureShader2 = _interopRequireDefault(_generateMultiTextureShader); + +var _checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'); + +var _checkMaxIfStatmentsInShader2 = _interopRequireDefault(_checkMaxIfStatmentsInShader); + +var _BatchBuffer = require('./BatchBuffer'); + +var _BatchBuffer2 = _interopRequireDefault(_BatchBuffer); + +var _const = require('../../const'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var TICK = 0; + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var SpriteRenderer = function (_ObjectRenderer) { + _inherits(SpriteRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function SpriteRenderer(renderer) { + _classCallCheck(this, SpriteRenderer); + + /** + * Number of values sent in the vertex buffer. + * positionX, positionY, colorR, colorG, colorB = 5 + * + * @member {number} + */ + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.vertSize = 5; + + /** + * The size of the vertex information in bytes. + * + * @member {number} + */ + _this.vertByteSize = _this.vertSize * 4; + + /** + * The number of images in the SpriteBatch before it flushes. + * + * @member {number} + */ + _this.size = _const.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + + // the total number of bytes in our batch + // let numVerts = this.size * 4 * this.vertByteSize; + + _this.buffers = []; + for (var i = 1; i <= _bitTwiddle2.default.nextPow2(_this.size); i *= 2) { + _this.buffers.push(new _BatchBuffer2.default(i * 4 * _this.vertByteSize)); + } + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + _this.indices = (0, _createIndicesForQuads2.default)(_this.size); + + /** + * The default shaders that is used if a sprite doesn't have a more specific one. + * there is a shader for each number of textures that can be rendererd. + * These shaders will also be generated on the fly as required. + * @member {PIXI.Shader[]} + */ + _this.shaders = null; + + _this.currentIndex = 0; + TICK = 0; + _this.groups = []; + + for (var k = 0; k < _this.size; k++) { + _this.groups[k] = { textures: [], textureCount: 0, ids: [], size: 0, start: 0, blend: 0 }; + } + + _this.sprites = []; + + _this.vertexBuffers = []; + _this.vaos = []; + + _this.vaoMax = 2; + _this.vertexCount = 0; + + _this.renderer.on('prerender', _this.onPrerender, _this); + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + SpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), _const.SPRITE_MAX_TEXTURES); + + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = (0, _checkMaxIfStatmentsInShader2.default)(this.MAX_TEXTURES, gl); + + this.shaders = new Array(this.MAX_TEXTURES); + this.shaders[0] = (0, _generateMultiTextureShader2.default)(gl, 1); + this.shaders[1] = (0, _generateMultiTextureShader2.default)(gl, 2); + + // create a couple of buffers + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + // we use the second shader as the first one depending on your browser may omit aTextureId + // as it is not used by the shader so is optimized out. + var shader = this.shaders[1]; + + for (var i = 0; i < this.vaoMax; i++) { + this.vertexBuffers[i] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + + /* eslint-disable max-len */ + + // build the vao object that will render.. + this.vaos[i] = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(this.vertexBuffers[i], shader.attributes.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(this.vertexBuffers[i], shader.attributes.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(this.vertexBuffers[i], shader.attributes.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4).addAttribute(this.vertexBuffers[i], shader.attributes.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + + /* eslint-disable max-len */ + } + + this.vao = this.vaos[0]; + this.currentBlendMode = 99999; + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + SpriteRenderer.prototype.onPrerender = function onPrerender() { + this.vertexCount = 0; + }; + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + SpriteRenderer.prototype.render = function render(sprite) { + // TODO set blend modes.. + // check texture.. + if (this.currentIndex >= this.size) { + this.flush(); + } + + // get the uvs for the texture + + // if the uvs have not updated then no point rendering just yet! + if (!sprite.texture._uvs) { + return; + } + + // push a texture. + // increment the batchsize + this.sprites[this.currentIndex++] = sprite; + }; + + /** + * Renders the content and empties the current batch. + * + */ + + + SpriteRenderer.prototype.flush = function flush() { + if (this.currentIndex === 0) { + return; + } + + var gl = this.renderer.gl; + + var np2 = _bitTwiddle2.default.nextPow2(this.currentIndex); + var log2 = _bitTwiddle2.default.log2(np2); + var buffer = this.buffers[log2]; + + var sprites = this.sprites; + var groups = this.groups; + + var float32View = buffer.float32View; + var uint32View = buffer.uint32View; + + var index = 0; + var nextTexture = void 0; + var currentTexture = void 0; + var groupCount = 1; + var textureCount = 0; + var currentGroup = groups[0]; + var vertexData = void 0; + var tint = void 0; + var uvs = void 0; + var textureId = void 0; + var blendMode = sprites[0].blendMode; + var shader = void 0; + + currentGroup.textureCount = 0; + currentGroup.start = 0; + currentGroup.blend = blendMode; + + TICK++; + + var i = void 0; + + for (i = 0; i < this.currentIndex; i++) { + // upload the sprite elemetns... + // they have all ready been calculated so we just need to push them into the buffer. + var sprite = sprites[i]; + + nextTexture = sprite._texture.baseTexture; + + if (blendMode !== sprite.blendMode) { + blendMode = sprite.blendMode; + + // force the batch to break! + currentTexture = null; + textureCount = this.MAX_TEXTURES; + TICK++; + } + + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + + if (nextTexture._enabled !== TICK) { + if (textureCount === this.MAX_TEXTURES) { + TICK++; + + textureCount = 0; + + currentGroup.size = i - currentGroup.start; + + currentGroup = groups[groupCount++]; + currentGroup.textureCount = 0; + currentGroup.blend = blendMode; + currentGroup.start = i; + } + + nextTexture._enabled = TICK; + nextTexture._id = textureCount; + + currentGroup.textures[currentGroup.textureCount++] = nextTexture; + textureCount++; + } + } + + vertexData = sprite.vertexData; + + // TODO this sum does not need to be set each frame.. + tint = sprite._tintRGB + (sprite.worldAlpha * 255 << 24); + uvs = sprite._texture._uvs.uvsUint32; + textureId = nextTexture._id; + + if (this.renderer.roundPixels) { + var resolution = this.renderer.resolution; + + // xy + float32View[index] = (vertexData[0] * resolution | 0) / resolution; + float32View[index + 1] = (vertexData[1] * resolution | 0) / resolution; + + // xy + float32View[index + 5] = (vertexData[2] * resolution | 0) / resolution; + float32View[index + 6] = (vertexData[3] * resolution | 0) / resolution; + + // xy + float32View[index + 10] = (vertexData[4] * resolution | 0) / resolution; + float32View[index + 11] = (vertexData[5] * resolution | 0) / resolution; + + // xy + float32View[index + 15] = (vertexData[6] * resolution | 0) / resolution; + float32View[index + 16] = (vertexData[7] * resolution | 0) / resolution; + } else { + // xy + float32View[index] = vertexData[0]; + float32View[index + 1] = vertexData[1]; + + // xy + float32View[index + 5] = vertexData[2]; + float32View[index + 6] = vertexData[3]; + + // xy + float32View[index + 10] = vertexData[4]; + float32View[index + 11] = vertexData[5]; + + // xy + float32View[index + 15] = vertexData[6]; + float32View[index + 16] = vertexData[7]; + } + + uint32View[index + 2] = uvs[0]; + uint32View[index + 7] = uvs[1]; + uint32View[index + 12] = uvs[2]; + uint32View[index + 17] = uvs[3]; + + uint32View[index + 3] = uint32View[index + 8] = uint32View[index + 13] = uint32View[index + 18] = tint; + float32View[index + 4] = float32View[index + 9] = float32View[index + 14] = float32View[index + 19] = textureId; + + index += 20; + } + + currentGroup.size = i - currentGroup.start; + + this.vertexCount++; + + if (this.vaoMax <= this.vertexCount) { + this.vaoMax++; + shader = this.shaders[1]; + this.vertexBuffers[this.vertexCount] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + // build the vao object that will render.. + this.vaos[this.vertexCount] = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(this.vertexBuffers[this.vertexCount], shader.attributes.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(this.vertexBuffers[this.vertexCount], shader.attributes.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(this.vertexBuffers[this.vertexCount], shader.attributes.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4).addAttribute(this.vertexBuffers[this.vertexCount], shader.attributes.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0); + this.vao = this.vaos[this.vertexCount].bind(); + + // / render the groups.. + for (i = 0; i < groupCount; i++) { + var group = groups[i]; + var groupTextureCount = group.textureCount; + + shader = this.shaders[groupTextureCount - 1]; + + if (!shader) { + shader = this.shaders[groupTextureCount - 1] = (0, _generateMultiTextureShader2.default)(gl, groupTextureCount); + // console.log("SHADER generated for " + textureCount + " textures") + } + + this.renderer.bindShader(shader); + + for (var j = 0; j < groupTextureCount; j++) { + this.renderer.bindTexture(group.textures[j], j); + } + + // set the blend mode.. + this.renderer.state.setBlendMode(group.blend); + + gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); + } + + // reset elements for the next flush + this.currentIndex = 0; + }; + + /** + * Starts a new sprite batch. + * + */ + + + SpriteRenderer.prototype.start = function start() {} + // this.renderer.bindShader(this.shader); + // TICK %= 1000; + + + /** + * Stops and flushes the current batch. + * + */ + ; + + SpriteRenderer.prototype.stop = function stop() { + this.flush(); + this.vao.unbind(); + }; + + /** + * Destroys the SpriteBatch. + * + */ + + + SpriteRenderer.prototype.destroy = function destroy() { + for (var i = 0; i < this.vaoMax; i++) { + this.vertexBuffers[i].destroy(); + this.vaos[i].destroy(); + } + + this.indexBuffer.destroy(); + + this.renderer.off('prerender', this.onPrerender, this); + + _ObjectRenderer.prototype.destroy.call(this); + + for (var _i = 0; _i < this.shaders.length; _i++) { + if (this.shaders[_i]) { + this.shaders[_i].destroy(); + } + } + + this.vertexBuffers = null; + this.vaos = null; + this.indexBuffer = null; + this.indices = null; + + this.sprites = null; + + for (var _i2 = 0; _i2 < this.buffers.length; _i2++) { + this.buffers[_i2].destroy(); + } + }; + + return SpriteRenderer; +}(_ObjectRenderer3.default); + +exports.default = SpriteRenderer; + + +_WebGLRenderer2.default.registerPlugin('sprite', SpriteRenderer); + +},{"../../const":78,"../../renderers/webgl/WebGLRenderer":116,"../../renderers/webgl/utils/ObjectRenderer":126,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":129,"../../utils/createIndicesForQuads":150,"./BatchBuffer":136,"./generateMultiTextureShader":138,"bit-twiddle":14,"pixi-gl-core":51}],138:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateMultiTextureShader; + +var _Shader = require('../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + // eslint-disable-line no-undef + +var fragTemplate = ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'varying float vTextureId;', 'uniform sampler2D uSamplers[%count%];', 'void main(void){', 'vec4 color;', 'float textureId = floor(vTextureId+0.5);', '%forloop%', 'gl_FragColor = color * vColor;', '}'].join('\n'); + +function generateMultiTextureShader(gl, maxTextures) { + var vertexSrc = "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = vec4(aColor.rgb * aColor.a, aColor.a);\n}\n"; + var fragmentSrc = fragTemplate; + + fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); + + var shader = new _Shader2.default(gl, vertexSrc, fragmentSrc); + + var sampleValues = []; + + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + + shader.bind(); + shader.uniforms.uSamplers = sampleValues; + + return shader; +} + +function generateSampleSrc(maxTextures) { + var src = ''; + + src += '\n'; + src += '\n'; + + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxTextures - 1) { + src += 'if(textureId == ' + i + '.0)'; + } + + src += '\n{'; + src += '\n\tcolor = texture2D(uSamplers[' + i + '], vTextureCoord);'; + src += '\n}'; + } + + src += '\n'; + src += '\n'; + + return src; +} + +},{"../../Shader":77}],139:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Sprite2 = require('../sprites/Sprite'); + +var _Sprite3 = _interopRequireDefault(_Sprite2); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _TextStyle = require('./TextStyle'); + +var _TextStyle2 = _interopRequireDefault(_TextStyle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint max-depth: [2, 8] */ + + +var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true +}; + +/** + * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string, + * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object. + * + * A Text can be created directly from a string and a style object + * + * ```js + * let text = new PIXI.Text('This is a pixi text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI + */ + +var Text = function (_Sprite) { + _inherits(Text, _Sprite); + + /** + * @param {string} text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + */ + function Text(text, style) { + _classCallCheck(this, Text); + + var canvas = document.createElement('canvas'); + + canvas.width = 16; + canvas.height = 16; + + var texture = _Texture2.default.fromCanvas(canvas); + + texture.orig = new _math.Rectangle(); + texture.trim = new _math.Rectangle(); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + var _this = _possibleConstructorReturn(this, _Sprite.call(this, texture)); + + _this.canvas = canvas; + + /** + * The canvas 2d context that everything is drawn with + * @member {HTMLCanvasElement} + */ + _this.context = _this.canvas.getContext('2d'); + + /** + * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. + * @member {number} + * @default 1 + */ + _this.resolution = _const.RESOLUTION; + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = null; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._style = null; + /** + * Private listener to track style changes. + * + * @member {Function} + * @private + */ + _this._styleListener = null; + + /** + * Private tracker for the current font. + * + * @member {string} + * @private + */ + _this._font = ''; + + _this.text = text; + _this.style = style; + + _this.localStyleID = -1; + return _this; + } + + /** + * Renders text and updates it when needed. + * + * @private + * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. + */ + + + Text.prototype.updateText = function updateText(respectDirty) { + var style = this._style; + + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + + if (!this.dirty && respectDirty) { + return; + } + + // build canvas api font setting from invididual components. Convert a numeric style.fontSize to px + var fontSizeString = typeof style.fontSize === 'number' ? style.fontSize + 'px' : style.fontSize; + + this._font = style.fontStyle + ' ' + style.fontVariant + ' ' + style.fontWeight + ' ' + fontSizeString + ' ' + style.fontFamily; + + this.context.font = this._font; + + // word wrap + // preserve original text + var outputText = style.wordWrap ? this.wordWrap(this._text) : this._text; + + // split text into lines + var lines = outputText.split(/(?:\r\n|\r|\n)/); + + // calculate text width + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + var fontProperties = this.determineFontProperties(this._font); + + for (var i = 0; i < lines.length; i++) { + var lineWidth = this.context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing; + + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + + var width = maxLineWidth + style.strokeThickness; + + if (style.dropShadow) { + width += style.dropShadowDistance; + } + + width += style.padding * 2; + + this.canvas.width = Math.ceil((width + this.context.lineWidth) * this.resolution); + + // calculate text height + var lineHeight = this.style.lineHeight || fontProperties.fontSize + style.strokeThickness; + + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * lineHeight; + + if (style.dropShadow) { + height += style.dropShadowDistance; + } + + this.canvas.height = Math.ceil((height + this._style.padding * 2) * this.resolution); + + this.context.scale(this.resolution, this.resolution); + + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + + this.context.font = this._font; + this.context.strokeStyle = style.stroke; + this.context.lineWidth = style.strokeThickness; + this.context.textBaseline = style.textBaseline; + this.context.lineJoin = style.lineJoin; + this.context.miterLimit = style.miterLimit; + + var linePositionX = void 0; + var linePositionY = void 0; + + if (style.dropShadow) { + if (style.dropShadowBlur > 0) { + this.context.shadowColor = style.dropShadowColor; + this.context.shadowBlur = style.dropShadowBlur; + } else { + this.context.fillStyle = style.dropShadowColor; + } + + var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + + for (var _i = 0; _i < lines.length; _i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i]) / 2; + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); + + if (style.stroke && style.strokeThickness) { + this.context.strokeStyle = style.dropShadowColor; + this.drawLetterSpacing(lines[_i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding, true); + this.context.strokeStyle = style.stroke; + } + } + } + } + + // set canvas text styles + this.context.fillStyle = this._generateFillStyle(style, lines); + + // draw lines line by line + for (var _i2 = 0; _i2 < lines.length; _i2++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i2 * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i2]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i2]) / 2; + } + + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[_i2], linePositionX + style.padding, linePositionY + style.padding, true); + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i2], linePositionX + style.padding, linePositionY + style.padding); + } + } + + this.updateTexture(); + }; + + /** + * Render the text with letter-spacing. + * @param {string} text - The text to draw + * @param {number} x - Horizontal position to draw the text + * @param {number} y - Vertical position to draw the text + * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + * @private + */ + + + Text.prototype.drawLetterSpacing = function drawLetterSpacing(text, x, y) { + var isStroke = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3]; + + var style = this._style; + + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + + if (letterSpacing === 0) { + if (isStroke) { + this.context.strokeText(text, x, y); + } else { + this.context.fillText(text, x, y); + } + + return; + } + + var characters = String.prototype.split.call(text, ''); + var currentPosition = x; + var index = 0; + var current = ''; + + while (index < text.length) { + current = characters[index++]; + if (isStroke) { + this.context.strokeText(current, currentPosition, y); + } else { + this.context.fillText(current, currentPosition, y); + } + currentPosition += this.context.measureText(current).width + letterSpacing; + } + }; + + /** + * Updates texture size based on canvas size + * + * @private + */ + + + Text.prototype.updateTexture = function updateTexture() { + var texture = this._texture; + var style = this._style; + + texture.baseTexture.hasLoaded = true; + texture.baseTexture.resolution = this.resolution; + + texture.baseTexture.realWidth = this.canvas.width; + texture.baseTexture.realHeight = this.canvas.height; + texture.baseTexture.width = this.canvas.width / this.resolution; + texture.baseTexture.height = this.canvas.height / this.resolution; + texture.trim.width = texture._frame.width = this.canvas.width / this.resolution; + texture.trim.height = texture._frame.height = this.canvas.height / this.resolution; + + texture.trim.x = -style.padding; + texture.trim.y = -style.padding; + + texture.orig.width = texture._frame.width - style.padding * 2; + texture.orig.height = texture._frame.height - style.padding * 2; + + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + + texture.baseTexture.emit('update', texture.baseTexture); + + this.dirty = false; + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Text.prototype.renderWebGL = function renderWebGL(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype.renderWebGL.call(this, renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Text.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype._renderCanvas.call(this, renderer); + }; + + /** + * Calculates the ascent, descent and fontSize of a given fontStyle + * + * @private + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ + + + Text.prototype.determineFontProperties = function determineFontProperties(fontStyle) { + var properties = Text.fontPropertiesCache[fontStyle]; + + if (!properties) { + properties = {}; + + var canvas = Text.fontPropertiesCanvas; + var context = Text.fontPropertiesContext; + + context.font = fontStyle; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('M').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = fontStyle; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i = 0; + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } else { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var _j = 0; _j < line; _j += 4) { + if (imagedata[idx + _j] !== 255) { + stop = true; + break; + } + } + + if (!stop) { + idx -= line; + } else { + break; + } + } + + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + + Text.fontPropertiesCache[fontStyle] = properties; + } + + return properties; + }; + + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @private + * @param {string} text - String to apply word wrapping to + * @return {string} New string with new lines applied where required + */ + + + Text.prototype.wordWrap = function wordWrap(text) { + // Greedy wrapping algorithm that will wrap words as the line grows longer + // than its horizontal bounds. + var result = ''; + var lines = text.split('\n'); + var wordWrapWidth = this._style.wordWrapWidth; + + for (var i = 0; i < lines.length; i++) { + var spaceLeft = wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) { + var wordWidth = this.context.measureText(words[j]).width; + + if (this._style.breakWords && wordWidth > wordWrapWidth) { + // Word should be split in the middle + var characters = words[j].split(''); + + for (var c = 0; c < characters.length; c++) { + var characterWidth = this.context.measureText(characters[c]).width; + + if (characterWidth > spaceLeft) { + result += '\n' + characters[c]; + spaceLeft = wordWrapWidth - characterWidth; + } else { + if (c === 0) { + result += ' '; + } + + result += characters[c]; + spaceLeft -= characterWidth; + } + } + } else { + var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; + + if (j === 0 || wordWidthWithSpace > spaceLeft) { + // Skip printing the newline if it's the first word of the line that is + // greater than the word wrap width. + if (j > 0) { + result += '\n'; + } + result += words[j]; + spaceLeft = wordWrapWidth - wordWidth; + } else { + spaceLeft -= wordWidthWithSpace; + result += ' ' + words[j]; + } + } + } + + if (i < lines.length - 1) { + result += '\n'; + } + } + + return result; + }; + + /** + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + */ + + + Text.prototype._calculateBounds = function _calculateBounds() { + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; + + /** + * Method to be called upon a TextStyle change. + * @private + */ + + + Text.prototype._onStyleChange = function _onStyleChange() { + this.dirty = true; + }; + + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * + * @private + * @param {object} style - The style. + * @param {string} lines - The lines of text. + * @return {string|number|CanvasGradient} The fill style + */ + + + Text.prototype._generateFillStyle = function _generateFillStyle(style, lines) { + if (!Array.isArray(style.fill)) { + return style.fill; + } + + // cocoon on canvas+ cannot generate textures, so use the first colour instead + if (navigator.isCocoonJS) { + return style.fill[0]; + } + + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient = void 0; + var totalIterations = void 0; + var currentIteration = void 0; + var stop = void 0; + + var width = this.canvas.width / this.resolution; + var height = this.canvas.height / this.resolution; + + if (style.fillGradientType === _const.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); + + // we need to repeat the gradient so that each invididual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + totalIterations = (style.fill.length + 1) * lines.length; + currentIteration = 0; + for (var i = 0; i < lines.length; i++) { + currentIteration += 1; + for (var j = 0; j < style.fill.length; j++) { + stop = currentIteration / totalIterations; + gradient.addColorStop(stop, style.fill[j]); + currentIteration++; + } + } + } else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); + + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + totalIterations = style.fill.length + 1; + currentIteration = 1; + + for (var _i3 = 0; _i3 < style.fill.length; _i3++) { + stop = currentIteration / totalIterations; + gradient.addColorStop(stop, style.fill[_i3]); + currentIteration++; + } + } + + return gradient; + }; + + /** + * Destroys this text object. + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majorety of the time the texture will not be shared with any other Sprites. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well + */ + + + Text.prototype.destroy = function destroy(options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + + options = Object.assign({}, defaultDestroyOptions, options); + + _Sprite.prototype.destroy.call(this, options); + + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + + this._style = null; + }; + + /** + * The width of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Text# + */ + + + _createClass(Text, [{ + key: 'width', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.x) * this.texture.orig.width; + } + + /** + * Sets the width of the text. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this.texture.orig.width; + this._width = value; + } + + /** + * The height of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Text# + */ + + }, { + key: 'height', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.y) * this._texture.orig.height; + } + + /** + * Sets the height of the text. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this.texture.orig.height; + this._height = value; + } + + /** + * Set the style of the text. Set up an event listener to listen for changes on the style + * object and mark the text as dirty. + * + * @member {object|PIXI.TextStyle} + * @memberof PIXI.Text# + */ + + }, { + key: 'style', + get: function get() { + return this._style; + } + + /** + * Sets the style of the text. + * + * @param {object} style - The value to set to. + */ + , + set: function set(style) { + style = style || {}; + + if (style instanceof _TextStyle2.default) { + this._style = style; + } else { + this._style = new _TextStyle2.default(style); + } + + this.localStyleID = -1; + this.dirty = true; + } + + /** + * Set the copy for the text object. To split a line you can use '\n'. + * + * @member {string} + * @memberof PIXI.Text# + */ + + }, { + key: 'text', + get: function get() { + return this._text; + } + + /** + * Sets the text. + * + * @param {string} text - The value to set to. + */ + , + set: function set(text) { + text = text || ' '; + text = text.toString(); + + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + } + }]); + + return Text; +}(_Sprite3.default); + +exports.default = Text; + + +Text.fontPropertiesCache = {}; +Text.fontPropertiesCanvas = document.createElement('canvas'); +Text.fontPropertiesContext = Text.fontPropertiesCanvas.getContext('2d'); + +},{"../const":78,"../math":102,"../sprites/Sprite":133,"../textures/Texture":144,"../utils":152,"./TextStyle":140}],140:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // disabling eslint for now, going to rewrite this in v5 +/* eslint-disable */ + +var _const = require('../const'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: '#000000', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: _const.TEXT_GRADIENT.LINEAR_VERTICAL, + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + wordWrap: false, + wordWrapWidth: 100 +}; + +/** + * A TextStyle Object decorates a Text Object. It can be shared between + * multiple Text objects. Changing the style will update all text objects using it. + * + * @class + * @memberof PIXI + */ + +var TextStyle = function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string} [style.dropShadowColor='#000000'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fills styles are + * supplied, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} for possible values + * @param {string} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', 800' or '900') + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Default is 'miter' (creates a sharp corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + _classCallCheck(this, TextStyle); + + this.styleID = 0; + + Object.assign(this, defaultStyle, style); + } + + /** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return {PIXI.TextStyle} New cloned TextStyle object + */ + + + TextStyle.prototype.clone = function clone() { + var clonedProperties = {}; + + for (var key in this._defaults) { + clonedProperties[key] = this[key]; + } + + return new TextStyle(clonedProperties); + }; + + /** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ + + + TextStyle.prototype.reset = function reset() { + Object.assign(this, this._defaults); + }; + + _createClass(TextStyle, [{ + key: 'align', + get: function get() { + return this._align; + }, + set: function set(align) { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + } + }, { + key: 'breakWords', + get: function get() { + return this._breakWords; + }, + set: function set(breakWords) { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + } + }, { + key: 'dropShadow', + get: function get() { + return this._dropShadow; + }, + set: function set(dropShadow) { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + } + }, { + key: 'dropShadowAngle', + get: function get() { + return this._dropShadowAngle; + }, + set: function set(dropShadowAngle) { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + } + }, { + key: 'dropShadowBlur', + get: function get() { + return this._dropShadowBlur; + }, + set: function set(dropShadowBlur) { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + } + }, { + key: 'dropShadowColor', + get: function get() { + return this._dropShadowColor; + }, + set: function set(dropShadowColor) { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + } + }, { + key: 'dropShadowDistance', + get: function get() { + return this._dropShadowDistance; + }, + set: function set(dropShadowDistance) { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + } + }, { + key: 'fill', + get: function get() { + return this._fill; + }, + set: function set(fill) { + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + } + }, { + key: 'fillGradientType', + get: function get() { + return this._fillGradientType; + }, + set: function set(fillGradientType) { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + } + }, { + key: 'fontFamily', + get: function get() { + return this._fontFamily; + }, + set: function set(fontFamily) { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + } + }, { + key: 'fontSize', + get: function get() { + return this._fontSize; + }, + set: function set(fontSize) { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + } + }, { + key: 'fontStyle', + get: function get() { + return this._fontStyle; + }, + set: function set(fontStyle) { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + } + }, { + key: 'fontVariant', + get: function get() { + return this._fontVariant; + }, + set: function set(fontVariant) { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + } + }, { + key: 'fontWeight', + get: function get() { + return this._fontWeight; + }, + set: function set(fontWeight) { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + } + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(letterSpacing) { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + } + }, { + key: 'lineHeight', + get: function get() { + return this._lineHeight; + }, + set: function set(lineHeight) { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + } + }, { + key: 'lineJoin', + get: function get() { + return this._lineJoin; + }, + set: function set(lineJoin) { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + } + }, { + key: 'miterLimit', + get: function get() { + return this._miterLimit; + }, + set: function set(miterLimit) { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + } + }, { + key: 'padding', + get: function get() { + return this._padding; + }, + set: function set(padding) { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + } + }, { + key: 'stroke', + get: function get() { + return this._stroke; + }, + set: function set(stroke) { + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + } + }, { + key: 'strokeThickness', + get: function get() { + return this._strokeThickness; + }, + set: function set(strokeThickness) { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + } + }, { + key: 'textBaseline', + get: function get() { + return this._textBaseline; + }, + set: function set(textBaseline) { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + } + }, { + key: 'wordWrap', + get: function get() { + return this._wordWrap; + }, + set: function set(wordWrap) { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + } + }, { + key: 'wordWrapWidth', + get: function get() { + return this._wordWrapWidth; + }, + set: function set(wordWrapWidth) { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + } + }]); + + return TextStyle; +}(); + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * + * @param {number|number[]} color + * @return {string} The color as a string. + */ + + +exports.default = TextStyle; +function getColor(color) { + if (typeof color === 'number') { + return (0, _utils.hex2string)(color); + } else if (Array.isArray(color)) { + for (var i = 0; i < color.length; ++i) { + if (typeof color[i] === 'number') { + color[i] = (0, _utils.hex2string)(color[i]); + } + } + } + + return color; +} + +},{"../const":78,"../utils":152}],141:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _const = require('../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let baseRenderTexture = new PIXI.BaseRenderTexture(renderer, 800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * baseRenderTexture.render(sprite); + * ``` + * + * The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual + * position a Container should be used: + * + * ```js + * let doc = new PIXI.Container(); + * + * doc.addChild(sprite); + * + * let baseRenderTexture = new PIXI.BaseRenderTexture(100, 100); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(doc, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var BaseRenderTexture = function (_BaseTexture) { + _inherits(BaseRenderTexture, _BaseTexture); + + /** + * @param {number} [width=100] - The width of the base render texture + * @param {number} [height=100] - The height of the base render texture + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + */ + function BaseRenderTexture() { + var width = arguments.length <= 0 || arguments[0] === undefined ? 100 : arguments[0]; + var height = arguments.length <= 1 || arguments[1] === undefined ? 100 : arguments[1]; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + + _classCallCheck(this, BaseRenderTexture); + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, null, scaleMode)); + + _this.resolution = resolution || _const.RESOLUTION; + + _this.width = width; + _this.height = height; + + _this.realWidth = _this.width * _this.resolution; + _this.realHeight = _this.height * _this.resolution; + + _this.scaleMode = scaleMode || _const.SCALE_MODES.DEFAULT; + _this.hasLoaded = true; + + /** + * A map of renderer IDs to webgl renderTargets + * + * @member {object} + * @private + */ + _this._glRenderTargets = []; + + /** + * A reference to the canvas render target (we only need one as this can be shared accross renderers) + * + * @member {object} + * @private + */ + _this._canvasRenderTarget = null; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + return _this; + } + + /** + * Resizes the BaseRenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + */ + + + BaseRenderTexture.prototype.resize = function resize(width, height) { + if (width === this.width && height === this.height) { + return; + } + + this.valid = width > 0 && height > 0; + + this.width = width; + this.height = height; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + if (!this.valid) { + return; + } + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + */ + + + BaseRenderTexture.prototype.destroy = function destroy() { + _BaseTexture.prototype.destroy.call(this, true); + this.renderer = null; + }; + + return BaseRenderTexture; +}(_BaseTexture3.default); + +exports.default = BaseRenderTexture; + +},{"../const":78,"./BaseTexture":142}],142:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var BaseTexture = function (_EventEmitter) { + _inherits(BaseTexture, _EventEmitter); + + /** + * @param {HTMLImageElement|HTMLCanvasElement} [source] - the source object of the texture. + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture + */ + function BaseTexture(source, scaleMode, resolution) { + _classCallCheck(this, BaseTexture); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.uid = (0, _utils.uid)(); + + _this.touched = 0; + + /** + * The resolution / device pixel ratio of the texture + * + * @member {number} + * @default 1 + */ + _this.resolution = resolution || _const.RESOLUTION; + + /** + * The width of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.width = 100; + + /** + * The height of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.height = 100; + + // TODO docs + // used to store the actual dimensions of the source + /** + * Used to store the actual width of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realWidth = 100; + /** + * Used to store the actual height of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realHeight = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @member {number} + * @default PIXI.SCALE_MODES.DEFAULT + * @see PIXI.SCALE_MODES + */ + _this.scaleMode = scaleMode || _const.SCALE_MODES.DEFAULT; + + /** + * Set to true once the base texture has successfully loaded. + * + * This is never true if the underlying source fails to load or has no texture data. + * + * @readonly + * @member {boolean} + */ + _this.hasLoaded = false; + + /** + * Set to true if the source is currently loading. + * + * If an Image source is loading the 'loaded' or 'error' event will be + * dispatched when the operation ends. An underyling source that is + * immediately-available bypasses loading entirely. + * + * @readonly + * @member {boolean} + */ + _this.isLoading = false; + + /** + * The image source that is used to create the texture. + * + * TODO: Make this a setter that calls loadSource(); + * + * @readonly + * @member {HTMLImageElement|HTMLCanvasElement} + */ + _this.source = null; // set in loadSource, if at all + + /** + * The image source that is used to create the texture. This is used to + * store the original Svg source when it is replaced with a canvas element. + * + * TODO: Currently not in use but could be used when re-scaling svg. + * + * @readonly + * @member {Image} + */ + _this.origSource = null; // set in loadSvg, if at all + + /** + * Type of image defined in source, eg. `png` or `svg` + * + * @readonly + * @member {string} + */ + _this.imageType = null; // set in updateImageType + + /** + * Scale for source image. Used with Svg images to scale them before rasterization. + * + * @readonly + * @member {number} + */ + _this.sourceScale = 1.0; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * All blend modes, and shaders written for default value. Change it on your own risk. + * + * @member {boolean} + * @default true + */ + _this.premultipliedAlpha = true; + + /** + * The image url of the texture + * + * @member {string} + */ + _this.imageUrl = null; + + /** + * Wether or not the texture is a power of two, try to use power of two textures as much + * as you can + * + * @private + * @member {boolean} + */ + _this.isPowerOfTwo = false; + + // used for webGL + + /** + * + * Set this to true if a mipmap of this texture needs to be generated. This value needs + * to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @member {boolean} + * @see PIXI.MIPMAP_TEXTURES + */ + _this.mipmap = _const.MIPMAP_TEXTURES; + + /** + * + * WebGL Texture wrap mode + * + * @member {number} + * @see PIXI.WRAP_MODES + */ + _this.wrapMode = _const.WRAP_MODES.DEFAULT; + + /** + * A map of renderer IDs to webgl textures + * + * @private + * @member {object} + */ + _this._glTextures = []; + _this._enabled = 0; + _this._id = 0; + + // if no source passed don't try to load + if (source) { + _this.loadSource(source); + } + + /** + * Fired when a not-immediately-available source finishes loading. + * + * @protected + * @event loaded + * @memberof PIXI.BaseTexture# + */ + + /** + * Fired when a not-immediately-available source fails to load. + * + * @protected + * @event error + * @memberof PIXI.BaseTexture# + */ + return _this; + } + + /** + * Updates the texture on all the webgl renderers, this also assumes the src has changed. + * + * @fires update + */ + + + BaseTexture.prototype.update = function update() { + // Svg size is handled during load + if (this.imageType !== 'svg') { + this.realWidth = this.source.naturalWidth || this.source.videoWidth || this.source.width; + this.realHeight = this.source.naturalHeight || this.source.videoHeight || this.source.height; + + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + this.isPowerOfTwo = _bitTwiddle2.default.isPow2(this.realWidth) && _bitTwiddle2.default.isPow2(this.realHeight); + } + + this.emit('update', this); + }; + + /** + * Load a source. + * + * If the source is not-immediately-available, such as an image that needs to be + * downloaded, then the 'loaded' or 'error' event will be dispatched in the future + * and `hasLoaded` will remain false after this call. + * + * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: + * + * if (texture.hasLoaded) { + * // texture ready for use + * } else if (texture.isLoading) { + * // listen to 'loaded' and/or 'error' events on texture + * } else { + * // not loading, not going to load UNLESS the source is reloaded + * // (it may still make sense to listen to the events) + * } + * + * @protected + * @param {HTMLImageElement|HTMLCanvasElement} source - the source object of the texture. + */ + + + BaseTexture.prototype.loadSource = function loadSource(source) { + var _this2 = this; + + var wasLoading = this.isLoading; + + this.hasLoaded = false; + this.isLoading = false; + + if (wasLoading && this.source) { + this.source.onload = null; + this.source.onerror = null; + } + + var firstSourceLoaded = !this.source; + + this.source = source; + + // Apply source if loaded. Otherwise setup appropriate loading monitors. + if ((source.src && source.complete || source.getContext) && source.width && source.height) { + this._updateImageType(); + + if (this.imageType === 'svg') { + this._loadSvgSource(); + } else { + this._sourceLoaded(); + } + + if (firstSourceLoaded) { + // send loaded event if previous source was null and we have been passed a pre-loaded IMG element + this.emit('loaded', this); + } + } else if (!source.getContext) { + var _ret = function () { + // Image fail / not ready + _this2.isLoading = true; + + var scope = _this2; + + source.onload = function () { + scope._updateImageType(); + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope._sourceLoaded(); + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + scope.emit('loaded', scope); + }; + + source.onerror = function () { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope.emit('error', scope); + }; + + // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element + // "The value of `complete` can thus change while a script is executing." + // So complete needs to be re-checked after the callbacks have been added.. + // NOTE: complete will be true if the image has no src so best to check if the src is set. + if (source.complete && source.src) { + // ..and if we're complete now, no need for callbacks + source.onload = null; + source.onerror = null; + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return { + v: void 0 + }; + } + + _this2.isLoading = false; + + if (source.width && source.height) { + _this2._sourceLoaded(); + + // If any previous subscribers possible + if (wasLoading) { + _this2.emit('loaded', _this2); + } + } + // If any previous subscribers possible + else if (wasLoading) { + _this2.emit('error', _this2); + } + } + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + }; + + /** + * Updates type of the source image. + */ + + + BaseTexture.prototype._updateImageType = function _updateImageType() { + if (!this.imageUrl) { + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + var imageType = void 0; + + if (dataUri && dataUri.mediaType === 'image') { + // Check for subType validity + var firstSubType = dataUri.subType.split('+')[0]; + + imageType = (0, _utils.getImageTypeOfUrl)('.' + firstSubType); + + if (!imageType) { + throw new Error('Invalid image type in data URI.'); + } + } else { + imageType = (0, _utils.getImageTypeOfUrl)(this.imageUrl); + + if (!imageType) { + throw new Error('Invalid image type in URL.'); + } + } + + this.imageType = imageType; + }; + + /** + * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls + * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. + */ + + + BaseTexture.prototype._loadSvgSource = function _loadSvgSource() { + if (this.imageType !== 'svg') { + // Do nothing if source is not svg + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + + if (dataUri) { + this._loadSvgSourceUsingDataUri(dataUri); + } else { + // We got an URL, so we need to do an XHR to check the svg size + this._loadSvgSourceUsingXhr(); + } + }; + + /** + * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`. + * + * @param {string} dataUri - The data uri to load from. + */ + + + BaseTexture.prototype._loadSvgSourceUsingDataUri = function _loadSvgSourceUsingDataUri(dataUri) { + var svgString = void 0; + + if (dataUri.encoding === 'base64') { + if (!atob) { + throw new Error('Your browser doesn\'t support base64 conversions.'); + } + svgString = atob(dataUri.data); + } else { + svgString = dataUri.data; + } + + this._loadSvgSourceUsingString(svgString); + }; + + /** + * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. + */ + + + BaseTexture.prototype._loadSvgSourceUsingXhr = function _loadSvgSourceUsingXhr() { + var _this3 = this; + + var svgXhr = new XMLHttpRequest(); + + // This throws error on IE, so SVG Document can't be used + // svgXhr.responseType = 'document'; + + // This is not needed since we load the svg as string (breaks IE too) + // but overrideMimeType() can be used to force the response to be parsed as XML + // svgXhr.overrideMimeType('image/svg+xml'); + + svgXhr.onload = function () { + if (svgXhr.readyState !== svgXhr.DONE || svgXhr.status !== 200) { + throw new Error('Failed to load SVG using XHR.'); + } + + _this3._loadSvgSourceUsingString(svgXhr.response); + }; + + svgXhr.onerror = function () { + return _this3.emit('error', _this3); + }; + + svgXhr.open('GET', this.imageUrl, true); + svgXhr.send(); + }; + + /** + * Loads texture using an SVG string. The original SVG Image is stored as `origSource` and the + * created canvas is the new `source`. The SVG is scaled using `sourceScale`. Called by + * `_loadSvgSourceUsingXhr` or `_loadSvgSourceUsingDataUri`. + * + * @param {string} svgString SVG source as string + * + * @fires loaded + */ + + + BaseTexture.prototype._loadSvgSourceUsingString = function _loadSvgSourceUsingString(svgString) { + var svgSize = (0, _utils.getSvgSize)(svgString); + + var svgWidth = svgSize.width; + var svgHeight = svgSize.height; + + if (!svgWidth || !svgHeight) { + throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); + } + + // Scale realWidth and realHeight + this.realWidth = Math.round(svgWidth * this.sourceScale); + this.realHeight = Math.round(svgHeight * this.sourceScale); + + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + // Check pow2 after scale + this.isPowerOfTwo = _bitTwiddle2.default.isPow2(this.realWidth) && _bitTwiddle2.default.isPow2(this.realHeight); + + // Create a canvas element + var canvas = document.createElement('canvas'); + + canvas.width = this.realWidth; + canvas.height = this.realHeight; + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + + // Draw the Svg to the canvas + canvas.getContext('2d').drawImage(this.source, 0, 0, svgWidth, svgHeight, 0, 0, this.realWidth, this.realHeight); + + // Replace the original source image with the canvas + this.origSource = this.source; + this.source = canvas; + + // Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`) + _utils.BaseTextureCache[canvas._pixiId] = this; + + this.isLoading = false; + this._sourceLoaded(); + this.emit('loaded', this); + }; + + /** + * Used internally to update the width, height, and some other tracking vars once + * a source has successfully loaded. + * + * @private + */ + + + BaseTexture.prototype._sourceLoaded = function _sourceLoaded() { + this.hasLoaded = true; + this.update(); + }; + + /** + * Destroys this base texture + * + */ + + + BaseTexture.prototype.destroy = function destroy() { + if (this.imageUrl) { + delete _utils.BaseTextureCache[this.imageUrl]; + delete _utils.TextureCache[this.imageUrl]; + + this.imageUrl = null; + + if (!navigator.isCocoonJS) { + this.source.src = ''; + } + } + // An svg source has both `imageUrl` and `__pixiId`, so no `else if` here + if (this.source && this.source._pixiId) { + delete _utils.BaseTextureCache[this.source._pixiId]; + } + + this.source = null; + + this.dispose(); + }; + + /** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + */ + + + BaseTexture.prototype.dispose = function dispose() { + this.emit('dispose', this); + + // this should no longer be needed, the renderers should cleanup all the gl textures. + // this._glTextures = {}; + }; + + /** + * Changes the source image of the texture. + * The original source must be an Image element. + * + * @param {string} newSrc - the path of the image + */ + + + BaseTexture.prototype.updateSourceImage = function updateSourceImage(newSrc) { + this.source.src = newSrc; + + this.loadSource(this.source); + }; + + /** + * Helper function that creates a base texture from the given image url. + * If the image is not in the base texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + // new Image() breaks tex loading in some versions of Chrome. + // See https://code.google.com/p/chromium/issues/detail?id=238071 + var image = new Image(); // document.createElement('img'); + + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + image.crossOrigin = (0, _determineCrossOrigin2.default)(imageUrl); + } + + baseTexture = new BaseTexture(image, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + image.src = imageUrl; // Setting this triggers load + + _utils.BaseTextureCache[imageUrl] = baseTexture; + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode) { + if (!canvas._pixiId) { + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[canvas._pixiId]; + + if (!baseTexture) { + baseTexture = new BaseTexture(canvas, scaleMode); + _utils.BaseTextureCache[canvas._pixiId] = baseTexture; + } + + return baseTexture; + }; + + return BaseTexture; +}(_eventemitter2.default); + +exports.default = BaseTexture; + +},{"../const":78,"../utils":152,"../utils/determineCrossOrigin":151,"bit-twiddle":14,"eventemitter3":16}],143:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseRenderTexture = require('./BaseRenderTexture'); + +var _BaseRenderTexture2 = _interopRequireDefault(_BaseRenderTexture); + +var _Texture2 = require('./Texture'); + +var _Texture3 = _interopRequireDefault(_Texture2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A RenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let renderTexture = PIXI.RenderTexture.create(800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual + * position a Container should be used: + * + * ```js + * let doc = new PIXI.Container(); + * + * doc.addChild(sprite); + * + * renderer.render(doc, renderTexture); // Renders to center of renderTexture + * ``` + * + * @class + * @extends PIXI.Texture + * @memberof PIXI + */ +var RenderTexture = function (_Texture) { + _inherits(RenderTexture, _Texture); + + /** + * @param {PIXI.BaseRenderTexture} baseRenderTexture - The renderer used for this RenderTexture + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + */ + function RenderTexture(baseRenderTexture, frame) { + _classCallCheck(this, RenderTexture); + + // suport for legacy.. + var _legacyRenderer = null; + + if (!(baseRenderTexture instanceof _BaseRenderTexture2.default)) { + /* eslint-disable prefer-rest-params, no-console */ + var width = arguments[1]; + var height = arguments[2]; + var scaleMode = arguments[3] || 0; + var resolution = arguments[4] || 1; + + // we have an old render texture.. + console.warn('Please use RenderTexture.create(' + width + ', ' + height + ') instead of the ctor directly.'); + _legacyRenderer = arguments[0]; + /* eslint-enable prefer-rest-params, no-console */ + + frame = null; + baseRenderTexture = new _BaseRenderTexture2.default(width, height, scaleMode, resolution); + } + + /** + * The base texture object that this texture uses + * + * @member {BaseTexture} + */ + + var _this = _possibleConstructorReturn(this, _Texture.call(this, baseRenderTexture, frame)); + + _this.legacyRenderer = _legacyRenderer; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = true; + + _this._updateUvs(); + return _this; + } + + /** + * Resizes the RenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + * @param {boolean} doNotResizeBaseTexture - Should the baseTexture.width and height values be resized as well? + */ + + + RenderTexture.prototype.resize = function resize(width, height, doNotResizeBaseTexture) { + // TODO - could be not required.. + this.valid = width > 0 && height > 0; + + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + + if (!doNotResizeBaseTexture) { + this.baseTexture.resize(width, height); + } + + this._updateUvs(); + }; + + /** + * A short hand way of creating a render texture. + * + * @param {number} [width=100] - The width of the render texture + * @param {number} [height=100] - The height of the render texture + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.RenderTexture} The new render texture + */ + + + RenderTexture.create = function create(width, height, scaleMode, resolution) { + return new RenderTexture(new _BaseRenderTexture2.default(width, height, scaleMode, resolution)); + }; + + return RenderTexture; +}(_Texture3.default); + +exports.default = RenderTexture; + +},{"./BaseRenderTexture":141,"./Texture":144}],144:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture = require('./BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _VideoBaseTexture = require('./VideoBaseTexture'); + +var _VideoBaseTexture2 = _interopRequireDefault(_VideoBaseTexture); + +var _TextureUvs = require('./TextureUvs'); + +var _TextureUvs2 = _interopRequireDefault(_TextureUvs); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _math = require('../math'); + +var _utils = require('../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided + * then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * let texture = PIXI.Texture.fromImage('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var Texture = function (_EventEmitter) { + _inherits(Texture, _EventEmitter); + + /** + * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + * @param {PIXI.Rectangle} [orig] - The area of original texture + * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture + * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8} + */ + function Texture(baseTexture, frame, orig, trim, rotate) { + _classCallCheck(this, Texture); + + /** + * Does this Texture have any frame data assigned to it? + * + * @member {boolean} + */ + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.noFrame = false; + + if (!frame) { + _this.noFrame = true; + frame = new _math.Rectangle(0, 0, 1, 1); + } + + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @member {PIXI.BaseTexture} + */ + _this.baseTexture = baseTexture; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @member {PIXI.Rectangle} + */ + _this._frame = frame; + + /** + * This is the trimmed area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @member {boolean} + */ + _this.requiresUpdate = false; + + /** + * The WebGL UV data cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + _this._uvs = null; + + /** + * This is the area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + + _this._rotate = Number(rotate || 0); + + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); + } + + if (baseTexture.hasLoaded) { + if (_this.noFrame) { + frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + + // if there is no frame we should monitor for any base texture changes.. + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + _this.frame = frame; + } else { + baseTexture.once('loaded', _this.onBaseTextureLoaded, _this); + } + + /** + * Fired when the texture is updated. This happens if the frame or the baseTexture is updated. + * + * @event update + * @memberof PIXI.Texture# + * @protected + */ + + _this._updateID = 0; + + /** + * Experimental! + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to 1.5 if you tex ture has repeated right and bottom lines, that leads to smoother borders + * IN REAL PIXELS + * @default 0 + * @member {number} + */ + _this.clampOffset = 0; + + /** + * Experimental! + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to 0 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * IN REAL PIXELS + * @default 0.5 + * @member {number} + */ + _this.clampMargin = 0.5; + return _this; + } + + /** + * Updates this texture on the gpu. + * + */ + + + Texture.prototype.update = function update() { + this.baseTexture.update(); + }; + + /** + * Called when the base texture is loaded + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureLoaded = function onBaseTextureLoaded(baseTexture) { + this._updateID++; + + // TODO this code looks confusing.. boo to abusing getters and setterss! + if (this.noFrame) { + this.frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } else { + this.frame = this._frame; + } + + this.baseTexture.on('update', this.onBaseTextureUpdated, this); + this.emit('update', this); + }; + + /** + * Called when the base texture is updated + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated(baseTexture) { + this._updateID++; + + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Texture.prototype.destroy = function destroy(destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destoryed too.. + if (_utils.TextureCache[this.baseTexture.imageUrl]) { + delete _utils.TextureCache[this.baseTexture.imageUrl]; + } + + this.baseTexture.destroy(); + } + + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); + + this.baseTexture = null; + } + + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + + this.valid = false; + + this.off('dispose', this.dispose, this); + this.off('update', this.update, this); + }; + + /** + * Creates a new texture object that acts the same as this one. + * + * @return {PIXI.Texture} The new texture + */ + + + Texture.prototype.clone = function clone() { + return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); + }; + + /** + * Updates the internal WebGL UV cache. + * + * @protected + */ + + + Texture.prototype._updateUvs = function _updateUvs() { + if (!this._uvs) { + this._uvs = new _TextureUvs2.default(); + } + + this._uvs.set(this._frame, this.baseTexture, this.rotate); + + this._updateID++; + }; + + /** + * returns uvs + * @member PIXI.TextureUvs# + * @memberof PIXI.Texture# + */ + + + /** + * Updates uvs accordingly to the texture + */ + Texture.prototype.updateUvs = function updateUvs() { + this._updateUvs(); + }; + + /** + * Helper function that creates a Texture object from the given image url. + * If the image is not in the texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var texture = _utils.TextureCache[imageUrl]; + + if (!texture) { + texture = new Texture(_BaseTexture2.default.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); + _utils.TextureCache[imageUrl] = texture; + } + + return texture; + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return texture; + }; + + /** + * Helper function that creates a new Texture based on the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromCanvas = function fromCanvas(canvas, scaleMode) { + return new Texture(_BaseTexture2.default.fromCanvas(canvas, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the given video element. + * + * @static + * @param {HTMLVideoElement|string} video - The URL or actual element of the video + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideo = function fromVideo(video, scaleMode) { + if (typeof video === 'string') { + return Texture.fromVideoUrl(video, scaleMode); + } + + return new Texture(_VideoBaseTexture2.default.fromVideo(video, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the video url. + * + * @static + * @param {string} videoUrl - URL of the video + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideoUrl = function fromVideoUrl(videoUrl, scaleMode) { + return new Texture(_VideoBaseTexture2.default.fromUrl(videoUrl, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the source you provide. + * The soucre can be - frame id, image url, video url, canvae element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.from = function from(source) { + // TODO auto detect cross origin.. + // TODO pass in scale mode? + if (typeof source === 'string') { + var texture = _utils.TextureCache[source]; + + if (!texture) { + // check if its a video.. + var isVideo = source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/) !== null; + + if (isVideo) { + return Texture.fromVideoUrl(source); + } + + return Texture.fromImage(source); + } + + return texture; + } else if (source instanceof HTMLCanvasElement) { + return Texture.fromCanvas(source); + } else if (source instanceof HTMLVideoElement) { + return Texture.fromVideo(source); + } else if (source instanceof _BaseTexture2.default) { + return new Texture(_BaseTexture2.default); + } + + // lets assume its a texture! + return source; + }; + + /** + * Adds a texture to the global TextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the texture will be stored against. + */ + + + Texture.addTextureToCache = function addTextureToCache(texture, id) { + _utils.TextureCache[id] = texture; + }; + + /** + * Remove a texture from the global TextureCache. + * + * @static + * @param {string} id - The id of the texture to be removed + * @return {PIXI.Texture} The texture that was removed + */ + + + Texture.removeTextureFromCache = function removeTextureFromCache(id) { + var texture = _utils.TextureCache[id]; + + delete _utils.TextureCache[id]; + delete _utils.BaseTextureCache[id]; + + return texture; + }; + + /** + * The frame specifies the region of the base texture that this texture uses. + * + * @member {PIXI.Rectangle} + * @memberof PIXI.Texture# + */ + + + _createClass(Texture, [{ + key: 'uvs', + get: function get() { + return this._uvs; + } + }, { + key: 'frame', + get: function get() { + return this._frame; + } + + /** + * Set the frame. + * + * @param {Rectangle} frame - The new frame to set. + */ + , + set: function set(frame) { + this._frame = frame; + + this.noFrame = false; + + if (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height) { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); + } + + // this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + this.valid = frame && frame.width && frame.height && this.baseTexture.hasLoaded; + + if (!this.trim && !this.rotate) { + this.orig = frame; + } + + if (this.valid) { + this._updateUvs(); + } + } + + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.GroupD8} for explanation + * + * @member {number} + */ + + }, { + key: 'rotate', + get: function get() { + return this._rotate; + } + + /** + * Set the rotation + * + * @param {number} rotate - The new rotation to set. + */ + , + set: function set(rotate) { + this._rotate = rotate; + if (this.valid) { + this._updateUvs(); + } + } + + /** + * The width of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'width', + get: function get() { + return this.orig ? this.orig.width : 0; + } + + /** + * The height of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.orig ? this.orig.height : 0; + } + }]); + + return Texture; +}(_eventemitter2.default); + +/** + * An empty texture, used often to not have to create multiple empty textures. + * Can not be destroyed. + * + * @static + * @constant + */ + + +exports.default = Texture; +Texture.EMPTY = new Texture(new _BaseTexture2.default()); +Texture.EMPTY.destroy = function _emptyDestroy() {/* empty */}; +Texture.EMPTY.on = function _emptyOn() {/* empty */}; +Texture.EMPTY.once = function _emptyOnce() {/* empty */}; +Texture.EMPTY.emit = function _emptyEmit() {/* empty */}; + +},{"../math":102,"../utils":152,"./BaseTexture":142,"./TextureUvs":146,"./VideoBaseTexture":147,"eventemitter3":16}],145:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Matrix = require('../math/Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var tempMat = new _Matrix2.default(); + +/** + * class controls uv transform and frame clamp for texture + */ + +var TextureTransform = function () { + /** + * + * @param {PIXI.Texture} texture observed texture + * @constructor + */ + function TextureTransform(texture) { + _classCallCheck(this, TextureTransform); + + this._texture = texture; + + this.mapCoord = new _Matrix2.default(); + + this.clampFrame = new Float32Array(4); + + this.clampOffset = new Float32Array(2); + + this._lastTextureID = -1; + + this.update(); + } + + /** + * texture property + * @member {PIXI.Texture} + * @memberof PIXI.TextureTransform + */ + + + /** + * updates matrices if texture was changed + * @param {boolean} forceUpdate if true, matrices will be updated any case + */ + TextureTransform.prototype.update = function update(forceUpdate) { + var tex = this.texture; + + if (!tex || !tex.valid) { + return; + } + + if (!forceUpdate && this._lastTextureID === this.texture._updateID) { + return; + } + + this._lastTextureID = this.texture._updateID; + + var uvs = this.texture._uvs; + + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + + var orig = tex.orig; + var trim = tex.trim; + + if (trim) { + tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat); + } + + var texBase = tex.baseTexture; + var frame = this.clampFrame; + var margin = tex.clampMargin / texBase.resolution; + var offset = tex.clampOffset; + + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.clampOffset[0] = offset / texBase.realWidth; + this.clampOffset[1] = offset / texBase.realHeight; + }; + + _createClass(TextureTransform, [{ + key: 'texture', + get: function get() { + return this._texture; + } + + /** + * sets texture value + * @param {PIXI.Texture} value texture to be set + */ + , + set: function set(value) { + this._texture = value; + this._lastTextureID = -1; + } + }]); + + return TextureTransform; +}(); + +exports.default = TextureTransform; + +},{"../math/Matrix":99}],146:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _GroupD = require('../math/GroupD8'); + +var _GroupD2 = _interopRequireDefault(_GroupD); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A standard object to store the Uvs of a texture + * + * @class + * @private + * @memberof PIXI + */ +var TextureUvs = function () { + /** + * + */ + function TextureUvs() { + _classCallCheck(this, TextureUvs); + + this.x0 = 0; + this.y0 = 0; + + this.x1 = 1; + this.y1 = 0; + + this.x2 = 1; + this.y2 = 1; + + this.x3 = 0; + this.y3 = 1; + + this.uvsUint32 = new Uint32Array(4); + this.uvsMatrix = null; + } + + /** + * Sets the texture Uvs based on the given frame information. + * + * @private + * @param {PIXI.Rectangle} frame - The frame of the texture + * @param {PIXI.Rectangle} baseFrame - The base frame of the texture + * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8} + */ + + + TextureUvs.prototype.set = function set(frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + + // coordinates of center + var cX = frame.x / tw + w2; + var cY = frame.y / th + h2; + + rotate = _GroupD2.default.add(rotate, _GroupD2.default.NW); // NW is top-left corner + this.x0 = cX + w2 * _GroupD2.default.uX(rotate); + this.y0 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + w2 * _GroupD2.default.uX(rotate); + this.y1 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x2 = cX + w2 * _GroupD2.default.uX(rotate); + this.y2 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x3 = cX + w2 * _GroupD2.default.uX(rotate); + this.y3 = cY + h2 * _GroupD2.default.uY(rotate); + } else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + + this.uvsUint32[0] = (this.y0 * 65535 & 0xFFFF) << 16 | this.x0 * 65535 & 0xFFFF; + this.uvsUint32[1] = (this.y1 * 65535 & 0xFFFF) << 16 | this.x1 * 65535 & 0xFFFF; + this.uvsUint32[2] = (this.y2 * 65535 & 0xFFFF) << 16 | this.x2 * 65535 & 0xFFFF; + this.uvsUint32[3] = (this.y3 * 65535 & 0xFFFF) << 16 | this.x3 * 65535 & 0xFFFF; + }; + + return TextureUvs; +}(); + +exports.default = TextureUvs; + +},{"../math/GroupD8":98}],147:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _utils = require('../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture of a [playing] Video. + * + * Video base textures mimic Pixi BaseTexture.from.... method in their creation process. + * + * This can be used in several ways, such as: + * + * ```js + * let texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4'); + * + * let texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' }); + * + * let texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']); + * + * let texture = PIXI.VideoBaseTexture.fromUrls([ + * { src: '/video.webm', mime: 'video/webm' }, + * { src: '/video.mp4', mime: 'video/mp4' } + * ]); + * ``` + * + * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/). + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var VideoBaseTexture = function (_BaseTexture) { + _inherits(VideoBaseTexture, _BaseTexture); + + /** + * @param {HTMLVideoElement} source - Video source + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + */ + function VideoBaseTexture(source, scaleMode) { + _classCallCheck(this, VideoBaseTexture); + + if (!source) { + throw new Error('No video source element specified.'); + } + + // hook in here to check if video is already available. + // BaseTexture looks for a source.complete boolean, plus width & height. + + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + source.complete = true; + } + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, source, scaleMode)); + + _this.width = source.videoWidth; + _this.height = source.videoHeight; + + /** + * Should the base texture automatically update itself, set to true by default + * + * @member {boolean} + * @default true + */ + _this.autoUpdate = false; + + /** + * When set to true will automatically play videos used by this texture once + * they are loaded. If false, it will not modify the playing state. + * + * @member {boolean} + * @default true + */ + _this.autoPlay = true; + + _this._onUpdate = _this._onUpdate.bind(_this); + _this._onCanPlay = _this._onCanPlay.bind(_this); + + source.addEventListener('play', _this._onPlayStart.bind(_this)); + source.addEventListener('pause', _this._onPlayStop.bind(_this)); + _this.hasLoaded = false; + _this.__loaded = false; + + if (!_this._isSourceReady()) { + source.addEventListener('canplay', _this._onCanPlay); + source.addEventListener('canplaythrough', _this._onCanPlay); + } else { + _this._onCanPlay(); + } + return _this; + } + + /** + * Returns true if the underlying source is playing. + * + * @private + * @return {boolean} True if playing. + */ + + + VideoBaseTexture.prototype._isSourcePlaying = function _isSourcePlaying() { + var source = this.source; + + return source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2; + }; + + /** + * Returns true if the underlying source is ready for playing. + * + * @private + * @return {boolean} True if ready. + */ + + + VideoBaseTexture.prototype._isSourceReady = function _isSourceReady() { + return this.source.readyState === 3 || this.source.readyState === 4; + }; + + /** + * The internal update loop of the video base texture, only runs when autoUpdate is set to true + * + * @private + */ + + + VideoBaseTexture.prototype._onUpdate = function _onUpdate() { + if (this.autoUpdate) { + window.requestAnimationFrame(this._onUpdate); + this.update(); + } + }; + + /** + * Runs the update loop when the video is ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStart = function _onPlayStart() { + // Just in case the video has not recieved its can play even yet.. + if (!this.hasLoaded) { + this._onCanPlay(); + } + + if (!this.autoUpdate) { + window.requestAnimationFrame(this._onUpdate); + this.autoUpdate = true; + } + }; + + /** + * Fired when a pause event is triggered, stops the update loop + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStop = function _onPlayStop() { + this.autoUpdate = false; + }; + + /** + * Fired when the video is loaded and ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onCanPlay = function _onCanPlay() { + this.hasLoaded = true; + + if (this.source) { + this.source.removeEventListener('canplay', this._onCanPlay); + this.source.removeEventListener('canplaythrough', this._onCanPlay); + + this.width = this.source.videoWidth; + this.height = this.source.videoHeight; + + // prevent multiple loaded dispatches.. + if (!this.__loaded) { + this.__loaded = true; + this.emit('loaded', this); + } + + if (this._isSourcePlaying()) { + this._onPlayStart(); + } else if (this.autoPlay) { + this.source.play(); + } + } + }; + + /** + * Destroys this texture + * + */ + + + VideoBaseTexture.prototype.destroy = function destroy() { + if (this.source && this.source._pixiId) { + delete _utils.BaseTextureCache[this.source._pixiId]; + delete this.source._pixiId; + } + + _BaseTexture.prototype.destroy.call(this); + }; + + /** + * Mimic Pixi BaseTexture.from.... method. + * + * @static + * @param {HTMLVideoElement} video - Video to create texture from + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromVideo = function fromVideo(video, scaleMode) { + if (!video._pixiId) { + video._pixiId = 'video_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[video._pixiId]; + + if (!baseTexture) { + baseTexture = new VideoBaseTexture(video, scaleMode); + _utils.BaseTextureCache[video._pixiId] = baseTexture; + } + + return baseTexture; + }; + + /** + * Helper function that creates a new BaseTexture based on the given video element. + * This BaseTexture can then be used to create a texture + * + * @static + * @param {string|object|string[]|object[]} videoSrc - The URL(s) for the video. + * @param {string} [videoSrc.src] - One of the source urls for the video + * @param {string} [videoSrc.mime] - The mimetype of the video (e.g. 'video/mp4'). If not specified + * the url's extension will be used as the second part of the mime type. + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromUrl = function fromUrl(videoSrc, scaleMode) { + var video = document.createElement('video'); + + video.setAttribute('webkit-playsinline', ''); + video.setAttribute('playsinline', ''); + + // array of objects or strings + if (Array.isArray(videoSrc)) { + for (var i = 0; i < videoSrc.length; ++i) { + video.appendChild(createSource(videoSrc[i].src || videoSrc[i], videoSrc[i].mime)); + } + } + // single object or string + else { + video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); + } + + video.load(); + video.play(); + + return VideoBaseTexture.fromVideo(video, scaleMode); + }; + + return VideoBaseTexture; +}(_BaseTexture3.default); + +exports.default = VideoBaseTexture; + + +VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; + +function createSource(path, type) { + if (!type) { + type = 'video/' + path.substr(path.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = path; + source.type = type; + + return source; +} + +},{"../utils":152,"./BaseTexture":142}],148:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../const'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// Internal event used by composed emitter +var TICK = 'tick'; + +/** + * A Ticker class that runs an update loop that other objects listen to. + * This class is composed around an EventEmitter object to add listeners + * meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, + * e.g. When the ticker is started and the emitter has listeners. + * + * @class + * @memberof PIXI.ticker + */ + +var Ticker = function () { + /** + * + */ + function Ticker() { + var _this = this; + + _classCallCheck(this, Ticker); + + /** + * Internal emitter used to fire 'tick' event + * @private + */ + this._emitter = new _eventemitter2.default(); + + /** + * Internal current frame request ID + * @private + */ + this._requestId = null; + + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + * @private + */ + this._maxElapsedMS = 100; + + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.ticker.Ticker#start} automatically + * when a listener is added. + * + * @member {boolean} + * @default false + */ + this.autoStart = false; + + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS} + * and is scaled with {@link PIXI.ticker.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * + * @member {number} + * @default 1 + */ + this.deltaTime = 1; + + /** + * Time elapsed in milliseconds from last frame to this frame. + * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime} + * is based, this value is neither capped nor scaled. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default 1 / TARGET_FPMS + */ + this.elapsedMS = 1 / _const.TARGET_FPMS; // default to target frame time + + /** + * The last time {@link PIXI.ticker.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default 0 + */ + this.lastTime = 0; + + /** + * Factor of current {@link PIXI.ticker.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + * + * @member {number} + * @default 1 + */ + this.speed = 1; + + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.ticker.Ticker#start} has been called. + * `false` if {@link PIXI.ticker.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.ticker.Ticker#autoStart} being `true` + * and a listener is added. + * + * @member {boolean} + * @default false + */ + this.started = false; + + /** + * Internal tick method bound to ticker instance. + * This is because in early 2015, Function.bind + * is still 60% slower in high performance scenarios. + * Also separating frame requests from update method + * so listeners may be called at any time and with + * any animation API, just invoke ticker.update(time). + * + * @private + * @param {number} time - Time since last tick. + */ + this._tick = function (time) { + _this._requestId = null; + + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._emitter.listeners(TICK, true)) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * + * @private + */ + + + Ticker.prototype._requestIfNeeded = function _requestIfNeeded() { + if (this._requestId === null && this._emitter.listeners(TICK, true)) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._requestId = requestAnimationFrame(this._tick); + } + }; + + /** + * Conditionally cancels a pending animation frame. + * + * @private + */ + + + Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; + + /** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * + * @private + */ + + + Ticker.prototype._startIfPossible = function _startIfPossible() { + if (this.started) { + this._requestIfNeeded(); + } else if (this.autoStart) { + this.start(); + } + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#on} internally for the + * internal 'tick' event. It checks if the emitter has listeners, + * and if so it requests a new animation frame at this point. + * + * @param {Function} fn - The listener function to be added for updates + * @param {Function} [context] - The listener context + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.add = function add(fn, context) { + this._emitter.on(TICK, fn, context); + + this._startIfPossible(); + + return this; + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#once} internally for the + * internal 'tick' event. It checks if the emitter has listeners, + * and if so it requests a new animation frame at this point. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context] - The listener context + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.addOnce = function addOnce(fn, context) { + this._emitter.once(TICK, fn, context); + + this._startIfPossible(); + + return this; + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#off} internally for 'tick' event. + * It checks if the emitter has listeners for 'tick' event. + * If it does, then it cancels the animation frame. + * + * @param {Function} [fn] - The listener function to be removed + * @param {Function} [context] - The listener context to be removed + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.remove = function remove(fn, context) { + this._emitter.off(TICK, fn, context); + + if (!this._emitter.listeners(TICK, true)) { + this._cancelIfNeeded(); + } + + return this; + }; + + /** + * Starts the ticker. If the ticker has listeners + * a new animation frame is requested at this point. + */ + + + Ticker.prototype.start = function start() { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + }; + + /** + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. + */ + + + Ticker.prototype.stop = function stop() { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; + + /** + * Triggers an update. An update entails setting the + * current {@link PIXI.ticker.Ticker#elapsedMS}, + * the current {@link PIXI.ticker.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.ticker.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + + + Ticker.prototype.update = function update() { + var currentTime = arguments.length <= 0 || arguments[0] === undefined ? performance.now() : arguments[0]; + + var elapsedMS = void 0; + + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + + this.deltaTime = elapsedMS * _const.TARGET_FPMS * this.speed; + + // Invoke listeners added to internal emitter + this._emitter.emit(TICK, this.deltaTime); + } else { + this.deltaTime = this.elapsedMS = 0; + } + + this.lastTime = currentTime; + }; + + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.ticker.Ticker#speed}, which is specific + * to scaling {@link PIXI.ticker.Ticker#deltaTime}. + * + * @memberof PIXI.ticker.Ticker# + * @readonly + */ + + + _createClass(Ticker, [{ + key: 'FPS', + get: function get() { + return 1000 / this.elapsedMS; + } + + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.ticker.Ticker#update}. + * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.TARGET_FPMS * 1000`. + * + * @memberof PIXI.ticker.Ticker# + * @default 10 + */ + + }, { + key: 'minFPS', + get: function get() { + return 1000 / this._maxElapsedMS; + } + + /** + * Sets the min fps. + * + * @param {number} fps - value to set. + */ + , + set: function set(fps) { + // Clamp: 0 to TARGET_FPMS + var minFPMS = Math.min(Math.max(0, fps) / 1000, _const.TARGET_FPMS); + + this._maxElapsedMS = 1 / minFPMS; + } + }]); + + return Ticker; +}(); + +exports.default = Ticker; + +},{"../const":78,"eventemitter3":16}],149:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Ticker = exports.shared = undefined; + +var _Ticker = require('./Ticker'); + +var _Ticker2 = _interopRequireDefault(_Ticker); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The shared ticker instance used by {@link PIXI.extras.MovieClip}. + * and by {@link PIXI.interaction.InteractionManager}. + * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` + * for this instance. Please follow the examples for usage, including + * how to opt-out of auto-starting the shared ticker. + * + * @example + * let ticker = PIXI.ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(800, 600); + * let stage = new PIXI.Container(); + * let interactionManager = PIXI.interaction.InteractionManager(renderer); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * + * @type {PIXI.ticker.Ticker} + * @memberof PIXI.ticker + */ +var shared = new _Ticker2.default(); + +shared.autoStart = true; + +/** + * @namespace PIXI.ticker + */ +exports.shared = shared; +exports.Ticker = _Ticker2.default; + +},{"./Ticker":148}],150:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = createIndicesForQuads; +/** + * Generic Mask Stack data structure + * + * @class + * @memberof PIXI + * @param {number} size - Number of quads + * @return {Uint16Array} indices + */ +function createIndicesForQuads(size) { + // the total number of indices in our array, there are 6 points per quad. + + var totalIndices = size * 6; + + var indices = new Uint16Array(totalIndices); + + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + indices[i + 0] = j + 0; + indices[i + 1] = j + 1; + indices[i + 2] = j + 2; + indices[i + 3] = j + 0; + indices[i + 4] = j + 2; + indices[i + 5] = j + 3; + } + + return indices; +} + +},{}],151:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = determineCrossOrigin; + +var _url2 = require('url'); + +var _url3 = _interopRequireDefault(_url2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var tempAnchor = void 0; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +function determineCrossOrigin(url) { + var loc = arguments.length <= 1 || arguments[1] === undefined ? window.location : arguments[1]; + + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url3.default.parse(tempAnchor.href); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +} + +},{"url":72}],152:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BaseTextureCache = exports.TextureCache = exports.pluginTarget = exports.EventEmitter = undefined; +exports.uid = uid; +exports.hex2rgb = hex2rgb; +exports.hex2string = hex2string; +exports.rgb2hex = rgb2hex; +exports.getResolutionOfUrl = getResolutionOfUrl; +exports.decomposeDataUri = decomposeDataUri; +exports.getImageTypeOfUrl = getImageTypeOfUrl; +exports.getSvgSize = getSvgSize; +exports.skipHello = skipHello; +exports.sayHello = sayHello; +exports.isWebGLSupported = isWebGLSupported; +exports.sign = sign; +exports.removeItems = removeItems; + +var _const = require('../const'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _pluginTarget = require('./pluginTarget'); + +var _pluginTarget2 = _interopRequireDefault(_pluginTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var nextUid = 0; +var saidHello = false; + +/** + * @namespace PIXI.utils + */ +exports.EventEmitter = _eventemitter2.default; +exports.pluginTarget = _pluginTarget2.default; + +/** + * Gets the next unique identifier + * + * @memberof PIXI.utils + * @return {number} The next unique identifier to use. + */ + +function uid() { + return ++nextUid; +} + +/** + * Converts a hex color number to an [R, G, B] array + * + * @memberof PIXI.utils + * @param {number} hex - The number to convert + * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one + * @return {number[]} An array representing the [R, G, B] of the color. + */ +function hex2rgb(hex, out) { + out = out || []; + + out[0] = (hex >> 16 & 0xFF) / 255; + out[1] = (hex >> 8 & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + + return out; +} + +/** + * Converts a hex color number to a string. + * + * @memberof PIXI.utils + * @param {number} hex - Number in hex + * @return {string} The string color. + */ +function hex2string(hex) { + hex = hex.toString(16); + hex = '000000'.substr(0, 6 - hex.length) + hex; + + return '#' + hex; +} + +/** + * Converts a color as an [R, G, B] array to a hex number + * + * @memberof PIXI.utils + * @param {number[]} rgb - rgb array + * @return {number} The color number + */ +function rgb2hex(rgb) { + return (rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + rgb[2] * 255; +} + +/** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * + * @memberof PIXI.utils + * @param {string} url - the image path + * @return {number} resolution / device pixel ratio of an asset + */ +function getResolutionOfUrl(url) { + var resolution = _const.RETINA_PREFIX.exec(url); + + if (resolution) { + return parseFloat(resolution[1]); + } + + return 1; +} + +/** + * Typedef for decomposeDataUri return object. + * + * @typedef {object} DecomposedDataUri + * @property {mediaType} Media type, eg. `image` + * @property {subType} Sub type, eg. `png` + * @property {encoding} Data encoding, eg. `base64` + * @property {data} The actual data + */ + +/** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. + * + * @memberof PIXI.utils + * @param {string} dataUri - the data URI to check + * @return {DecomposedDataUri|undefined} The decomposed data uri or undefined + */ +function decomposeDataUri(dataUri) { + var dataUriMatch = _const.DATA_URI.exec(dataUri); + + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + encoding: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + data: dataUriMatch[4] + }; + } + + return undefined; +} + +/** + * Get type of the image by regexp for extension. Returns undefined for unknown extensions. + * + * @memberof PIXI.utils + * @param {string} url - the image path + * @return {string|undefined} image extension + */ +function getImageTypeOfUrl(url) { + var extension = _const.IMAGE_TYPE.exec(url); + + if (extension) { + return extension[1].toLowerCase(); + } + + return undefined; +} + +/** + * Typedef for Size object. + * + * @typedef {object} Size + * @property {width} Width component + * @property {height} Height component + */ + +/** + * Get size from an svg string using regexp. + * + * @memberof PIXI.utils + * @param {string} svgString - a serialized svg element + * @return {Size|undefined} image extension + */ +function getSvgSize(svgString) { + var sizeMatch = _const.SVG_SIZE.exec(svgString); + var size = {}; + + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[2])); + size[sizeMatch[3]] = Math.round(parseFloat(sizeMatch[4])); + } + + return size; +} + +/** + * Skips the hello message of renderers that are created after this is run. + * + */ +function skipHello() { + saidHello = true; +} + +/** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever makes you a jerk face. + * + * @static + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ +function sayHello(type) { + if (saidHello) { + return; + } + + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = ['\n %c %c %c Pixi.js ' + _const.VERSION + ' - ✰ ' + type + ' ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n', 'background: #ff66a5; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff66a5; background: #030307; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'background: #ffc3dc; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;']; + + window.console.log.apply(console, args); + } else if (window.console) { + window.console.log('Pixi.js ' + _const.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); + } + + saidHello = true; +} + +/** + * Helper for checking for webgl support + * + * @memberof PIXI.utils + * @return {boolean} is webgl supported + */ +function isWebGLSupported() { + var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; + + try { + if (!window.WebGLRenderingContext) { + return false; + } + + var canvas = document.createElement('canvas'); + var gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); + + var success = !!(gl && gl.getContextAttributes().stencil); + + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + + if (loseContext) { + loseContext.loseContext(); + } + } + + gl = null; + + return success; + } catch (e) { + return false; + } +} + +/** + * Returns sign of number + * + * @memberof PIXI.utils + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ +function sign(n) { + if (n === 0) return 0; + + return n < 0 ? -1 : 1; +} + +/** + * Remove a range of items from an array + * + * @memberof PIXI.utils + * @param {Array<*>} arr The target array + * @param {number} startIdx The index to begin removing from (inclusive) + * @param {number} removeCount How many items to remove + */ +function removeItems(arr, startIdx, removeCount) { + var length = arr.length; + + if (startIdx >= length || removeCount === 0) { + return; + } + + removeCount = startIdx + removeCount > length ? length - startIdx : removeCount; + + var len = length - removeCount; + + for (var i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount]; + } + + arr.length = len; +} + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var TextureCache = exports.TextureCache = {}; + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var BaseTextureCache = exports.BaseTextureCache = {}; + +},{"../const":78,"./pluginTarget":154,"eventemitter3":16}],153:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = maxRecommendedTextures; + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function maxRecommendedTextures(max) { + if (_ismobilejs2.default.tablet || _ismobilejs2.default.phone) { + // check if the res is iphone 6 or higher.. + return 2; + } + + // desktop should be ok + return max; +} + +},{"ismobilejs":17}],154:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Mixins functionality to make an object have "plugins". + * + * @example + * function MyObject() {} + * + * pluginTarget.mixin(MyObject); + * + * @mixin + * @memberof PIXI.utils + * @param {object} obj - The object to mix into. + */ +function pluginTarget(obj) { + obj.__plugins = {}; + + /** + * Adds a plugin to an object + * + * @param {string} pluginName - The events that should be listed. + * @param {Function} ctor - The constructor function for the plugin. + */ + obj.registerPlugin = function registerPlugin(pluginName, ctor) { + obj.__plugins[pluginName] = ctor; + }; + + /** + * Instantiates all the plugins of this object + * + */ + obj.prototype.initPlugins = function initPlugins() { + this.plugins = this.plugins || {}; + + for (var o in obj.__plugins) { + this.plugins[o] = new obj.__plugins[o](this); + } + }; + + /** + * Removes all the plugins of this object + * + */ + obj.prototype.destroyPlugins = function destroyPlugins() { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + + this.plugins = null; + }; +} + +exports.default = { + /** + * Mixes in the properties of the pluginTarget into another object + * + * @param {object} obj - The obj to mix into + */ + mixin: function mixin(obj) { + pluginTarget(obj); + } +}; + +},{}],155:[function(require,module,exports){ +'use strict'; + +var _core = require('./core'); + +var core = _interopRequireWildcard(_core); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code +function warn(msg) { + /* eslint-disable no-console */ + var stack = new Error().stack; + + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('Deprecation Warning: ', msg); + } else { + // chop off the stack trace which includes pixi.js internal calls + stack = stack.split('\n').splice(3).join('\n'); + + if (console.groupCollapsed) { + console.groupCollapsed('%cDeprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', msg); + console.warn(stack); + console.groupEnd(); + } else { + console.warn('Deprecation Warning: ', msg); + console.warn(stack); + } + } + /* eslint-enable no-console */ +} + +/** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ +core.SpriteBatch = function () { + throw new ReferenceError('SpriteBatch does not exist any more, please use the new ParticleContainer instead.'); +}; + +/** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ +core.AssetLoader = function () { + throw new ReferenceError('The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class.'); +}; + +Object.defineProperties(core, { + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + Stage: { + get: function get() { + warn('You do not need to use a PIXI Stage any more, you can simply render any container.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + DisplayObjectContainer: { + get: function get() { + warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + Strip: { + get: function get() { + warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.'); + + return mesh.Mesh; + } + }, + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + Rope: { + get: function get() { + warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.'); + + return mesh.Rope; + } + }, + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + ParticleContainer: { + get: function get() { + warn('The ParticleContainer class has been moved to particles.ParticleContainer, ' + 'please use particles.ParticleContainer from now on.'); + + return particles.ParticleContainer; + } + }, + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + MovieClip: { + get: function get() { + warn('The MovieClip class has been moved to extras.MovieClip, please use extras.MovieClip from now on.'); + + return extras.MovieClip; + } + }, + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + TilingSprite: { + get: function get() { + warn('The TilingSprite class has been moved to extras.TilingSprite, ' + 'please use extras.TilingSprite from now on.'); + + return extras.TilingSprite; + } + }, + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + BitmapText: { + get: function get() { + warn('The BitmapText class has been moved to extras.BitmapText, ' + 'please use extras.BitmapText from now on.'); + + return extras.BitmapText; + } + }, + + /** + * @class + * @private + * @name blendModes + * @memberof PIXI + * @see PIXI.BLEND_MODES + * @deprecated since version 3.0.0 + */ + blendModes: { + get: function get() { + warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.'); + + return core.BLEND_MODES; + } + }, + + /** + * @class + * @private + * @name scaleModes + * @memberof PIXI + * @see PIXI.SCALE_MODES + * @deprecated since version 3.0.0 + */ + scaleModes: { + get: function get() { + warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.'); + + return core.SCALE_MODES; + } + }, + + /** + * @class + * @private + * @name BaseTextureCache + * @memberof PIXI + * @see PIXI.utils.BaseTextureCache + * @deprecated since version 3.0.0 + */ + BaseTextureCache: { + get: function get() { + warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, ' + 'please use utils.BaseTextureCache from now on.'); + + return core.utils.BaseTextureCache; + } + }, + + /** + * @class + * @private + * @name TextureCache + * @memberof PIXI + * @see PIXI.utils.TextureCache + * @deprecated since version 3.0.0 + */ + TextureCache: { + get: function get() { + warn('The TextureCache class has been moved to utils.TextureCache, ' + 'please use utils.TextureCache from now on.'); + + return core.utils.TextureCache; + } + }, + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + math: { + get: function get() { + warn('The math namespace is deprecated, please access members already accessible on PIXI.'); + + return core; + } + }, + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.Filter; + } + }, + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + TransformManual: { + get: function get() { + warn('TransformManual has been renamed to TransformBase, please update your pixi-spine'); + + return core.TransformBase; + } + } +}); + +core.DisplayObject.prototype.generateTexture = function (renderer, scaleMode, resolution) { + warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); + + return renderer.generateTexture(undefined, scaleMode, resolution); +}; + +core.Graphics.prototype.generateTexture = function (scaleMode, resolution) { + warn('graphics generate texture has moved to the renderer. ' + 'Or to render a graphics to a texture using canvas please use generateCanvasTexture'); + + return undefined.generateCanvasTexture(scaleMode, resolution); +}; + +core.RenderTexture.prototype.render = function (displayObject, matrix, clear, updateTransform) { + undefined.legacyRenderer.render(displayObject, undefined, clear, matrix, !updateTransform); + warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)'); +}; + +core.RenderTexture.prototype.getImage = function (target) { + warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); + + return undefined.legacyRenderer.extract.image(target); +}; + +core.RenderTexture.prototype.getBase64 = function (target) { + warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); + + return undefined.legacyRenderer.extract.base64(target); +}; + +core.RenderTexture.prototype.getCanvas = function (target) { + warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); + + return undefined.legacyRenderer.extract.canvas(target); +}; + +core.RenderTexture.prototype.getPixels = function (target) { + warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); + + return undefined.legacyRenderer.pixels(target); +}; + +/** + * @method + * @private + * @name PIXI.Sprite#setTexture + * @see PIXI.Sprite#texture + * @deprecated since version 3.0.0 + * @param {PIXI.Texture} texture - The texture to set to. + */ +core.Sprite.prototype.setTexture = function (texture) { + undefined.texture = texture; + warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;'); +}; + +/** + * @method + * @name PIXI.extras.BitmapText#setText + * @see PIXI.extras.BitmapText#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ +extras.BitmapText.prototype.setText = function (text) { + undefined.text = text; + warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';'); +}; + +/** + * @method + * @name PIXI.Text#setText + * @see PIXI.Text#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ +core.Text.prototype.setText = function (text) { + undefined.text = text; + warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';'); +}; + +/** + * @method + * @name PIXI.Text#setStyle + * @see PIXI.Text#style + * @deprecated since version 3.0.0 + * @param {*} style - The style to set to. + */ +core.Text.prototype.setStyle = function (style) { + undefined.style = style; + warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;'); +}; + +Object.defineProperties(core.TextStyle.prototype, { + /** + * Set all properties of a font as a single string + * + * @name PIXI.TextStyle#font + * @deprecated since version 4.0.0 + */ + font: { + get: function get() { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\', \'fontSize\', \'fontStyle\', \'fontVariant\' and \'fontWeight\' properties from now on'); + + var fontSizeString = typeof this._fontSize === 'number' ? this._fontSize + 'px' : this._fontSize; + + return this._fontStyle + ' ' + this._fontVariant + ' ' + this._fontWeight + ' ' + fontSizeString + ' ' + this._fontFamily; + }, + set: function set(font) { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + + // can work out fontStyle from search of whole string + if (font.indexOf('italic') > 1) { + this._fontStyle = 'italic'; + } else if (font.indexOf('oblique') > -1) { + this._fontStyle = 'oblique'; + } else { + this._fontStyle = 'normal'; + } + + // can work out fontVariant from search of whole string + if (font.indexOf('small-caps') > -1) { + this._fontVariant = 'small-caps'; + } else { + this._fontVariant = 'normal'; + } + + // fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units + var splits = font.split(' '); + var fontSizeIndex = -1; + + this._fontSize = 26; + for (var i = 0; i < splits.length; ++i) { + if (splits[i].match(/(px|pt|em|%)/)) { + fontSizeIndex = i; + this._fontSize = splits[i]; + break; + } + } + + // we can now search for fontWeight as we know it must occur before the fontSize + this._fontWeight = 'normal'; + for (var _i = 0; _i < fontSizeIndex; ++_i) { + if (splits[_i].match(/(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/)) { + this._fontWeight = splits[_i]; + break; + } + } + + // and finally join everything together after the fontSize in case the font family has multiple words + if (fontSizeIndex > -1 && fontSizeIndex < splits.length - 1) { + this._fontFamily = ''; + for (var _i2 = fontSizeIndex + 1; _i2 < splits.length; ++_i2) { + this._fontFamily += splits[_i2] + ' '; + } + + this._fontFamily = this._fontFamily.slice(0, -1); + } else { + this._fontFamily = 'Arial'; + } + + this.styleID++; + } + } +}); + +/** + * @method + * @name PIXI.Texture#setFrame + * @see PIXI.Texture#setFrame + * @deprecated since version 3.0.0 + * @param {PIXI.Rectangle} frame - The frame to set. + */ +core.Texture.prototype.setFrame = function (frame) { + undefined.frame = frame; + warn('setFrame is now deprecated, please use the frame property, e.g: myTexture.frame = frame;'); +}; + +Object.defineProperties(filters, { + + /** + * @class + * @private + * @name PIXI.filters.AbstractFilter + * @see PIXI.AbstractFilter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.AbstractFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.SpriteMaskFilter + * @see PIXI.SpriteMaskFilter + * @deprecated since version 3.0.6 + */ + SpriteMaskFilter: { + get: function get() { + warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.'); + + return core.SpriteMaskFilter; + } + } +}); + +/** + * @method + * @name PIXI.utils.uuid + * @see PIXI.utils.uid + * @deprecated since version 3.0.6 + * @return {number} The uid + */ +core.utils.uuid = function () { + warn('utils.uuid() is deprecated, please use utils.uid() from now on.'); + + return core.utils.uid(); +}; + +/** + * @method + * @name PIXI.utils.canUseNewCanvasBlendModes + * @see PIXI.CanvasTinter + * @deprecated + * @return {boolean} Can use blend modes. + */ +core.utils.canUseNewCanvasBlendModes = function () { + warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on'); + + return core.CanvasTinter.canUseMultiply; +}; + +},{"./core":97,"./extras":165,"./filters":176,"./mesh":193,"./particles":196}],156:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers. + * + * @class + * @memberof PIXI + */ + +var CanvasExtract = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasExtract(renderer) { + _classCallCheck(this, CanvasExtract); + + this.renderer = renderer; + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + CanvasExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `CanvasExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + CanvasExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + CanvasExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = this.renderer.width; + frame.height = this.renderer.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + CanvasExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + + return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; + }; + + /** + * Destroys the extract + * + */ + + + CanvasExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return CanvasExtract; +}(); + +exports.default = CanvasExtract; + + +core.CanvasRenderer.registerPlugin('extract', CanvasExtract); + +},{"../../core":97}],157:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLExtract = require('./webgl/WebGLExtract'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLExtract).default; + } +}); + +var _CanvasExtract = require('./canvas/CanvasExtract'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasExtract).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./canvas/CanvasExtract":156,"./webgl/WebGLExtract":158}],158:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); +var BYTES_PER_PIXEL = 4; + +/** + * The extract manager provides functionality to export content from the renderers. + * + * @class + * @memberof PIXI + */ + +var WebGLExtract = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLExtract(renderer) { + _classCallCheck(this, WebGLExtract); + + this.renderer = renderer; + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + WebGLExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `WebGLExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + WebGLExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + WebGLExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var flipY = false; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + flipY = false; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + flipY = true; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + + // set up an array of pixels + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + + canvasData.data.set(webglPixels); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // pulling pixels + if (flipY) { + canvasBuffer.context.scale(1, -1); + canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); + } + } + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + WebGLExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + } + + return webglPixels; + }; + + /** + * Destroys the extract + * + */ + + + WebGLExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return WebGLExtract; +}(); + +exports.default = WebGLExtract; + + +core.WebGLRenderer.registerPlugin('extract', WebGLExtract); + +},{"../../core":97}],159:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ObservablePoint = require('../core/math/ObservablePoint'); + +var _ObservablePoint2 = _interopRequireDefault(_ObservablePoint); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BitmapText object will create a line or multiple lines of text using bitmap font. To + * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using: + * + * A BitmapText can only be created when the font is loaded + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); + * ``` + * + * http://www.angelcode.com/products/bmfont/ for windows or + * http://www.bmglyph.com/ for mac. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.extras + */ +var BitmapText = function (_core$Container) { + _inherits(BitmapText, _core$Container); + + /** + * @param {string} text - The copy that you would like the text to display + * @param {object} style - The style parameters + * @param {string|object} style.font - The font descriptor for the object, can be passed as a string of form + * "24px FontName" or "FontName" or as an object with explicit name/size properties. + * @param {string} [style.font.name] - The bitmap font id + * @param {number} [style.font.size] - The size of the font in pixels, e.g. 24 + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), does not affect + * single line text + * @param {number} [style.tint=0xFFFFFF] - The tint color + */ + function BitmapText(text) { + var style = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + + _classCallCheck(this, BitmapText); + + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this.textWidth = 0; + + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + _this.textHeight = 0; + + /** + * Private tracker for the letter sprite pool. + * + * @member {PIXI.Sprite[]} + * @private + */ + _this._glyphs = []; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._font = { + tint: style.tint !== undefined ? style.tint : 0xFFFFFF, + align: style.align || 'left', + name: null, + size: 0 + }; + + /** + * Private tracker for the current font. + * + * @member {object} + * @private + */ + _this.font = style.font; // run font setter + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = text; + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + */ + _this.maxWidth = 0; + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + */ + _this.maxLineHeight = 0; + + /** + * Text anchor. read-only + * + * @member {PIXI.ObservablePoint} + * @private + */ + _this._anchor = new _ObservablePoint2.default(function () { + _this.dirty = true; + }, _this, 0, 0); + + /** + * The dirty state of this object. + * + * @member {boolean} + */ + _this.dirty = false; + + _this.updateText(); + return _this; + } + + /** + * Renders text and updates it when needed + * + * @private + */ + + + BitmapText.prototype.updateText = function updateText() { + var data = BitmapText.fonts[this._font.name]; + var scale = this._font.size / data.size; + var pos = new core.Point(); + var chars = []; + var lineWidths = []; + + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastSpace = -1; + var lastSpaceWidth = 0; + var maxLineHeight = 0; + + for (var i = 0; i < this.text.length; i++) { + var charCode = this.text.charCodeAt(i); + + if (/(\s)/.test(this.text.charAt(i))) { + lastSpace = i; + lastSpaceWidth = lastLineWidth; + } + + if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) { + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + if (lastSpace !== -1 && this.maxWidth > 0 && pos.x * scale > this.maxWidth) { + core.utils.removeItems(chars, lastSpace, i - lastSpace); + i = lastSpace; + lastSpace = -1; + + lineWidths.push(lastSpaceWidth); + maxLineWidth = Math.max(maxLineWidth, lastSpaceWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + var charData = data.chars[charCode]; + + if (!charData) { + continue; + } + + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + + chars.push({ + texture: charData.texture, + line: line, + charCode: charCode, + position: new core.Point(pos.x + charData.xOffset, pos.y + charData.yOffset) + }); + lastLineWidth = pos.x + (charData.texture.width + charData.xOffset); + pos.x += charData.xAdvance; + maxLineHeight = Math.max(maxLineHeight, charData.yOffset + charData.texture.height); + prevCharCode = charCode; + } + + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + + var lineAlignOffsets = []; + + for (var _i = 0; _i <= line; _i++) { + var alignOffset = 0; + + if (this._font.align === 'right') { + alignOffset = maxLineWidth - lineWidths[_i]; + } else if (this._font.align === 'center') { + alignOffset = (maxLineWidth - lineWidths[_i]) / 2; + } + + lineAlignOffsets.push(alignOffset); + } + + var lenChars = chars.length; + var tint = this.tint; + + for (var _i2 = 0; _i2 < lenChars; _i2++) { + var c = this._glyphs[_i2]; // get the next glyph sprite + + if (c) { + c.texture = chars[_i2].texture; + } else { + c = new core.Sprite(chars[_i2].texture); + this._glyphs.push(c); + } + + c.position.x = (chars[_i2].position.x + lineAlignOffsets[chars[_i2].line]) * scale; + c.position.y = chars[_i2].position.y * scale; + c.scale.x = c.scale.y = scale; + c.tint = tint; + + if (!c.parent) { + this.addChild(c); + } + } + + // remove unnecessary children. + for (var _i3 = lenChars; _i3 < this._glyphs.length; ++_i3) { + this.removeChild(this._glyphs[_i3]); + } + + this.textWidth = maxLineWidth * scale; + this.textHeight = (pos.y + data.lineHeight) * scale; + + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + for (var _i4 = 0; _i4 < lenChars; _i4++) { + this._glyphs[_i4].x -= this.textWidth * this.anchor.x; + this._glyphs[_i4].y -= this.textHeight * this.anchor.y; + } + } + this.maxLineHeight = maxLineHeight * scale; + }; + + /** + * Updates the transform of this object + * + * @private + */ + + + BitmapText.prototype.updateTransform = function updateTransform() { + this.validate(); + this.containerUpdateTransform(); + }; + + /** + * Validates text before calling parent's getLocalBounds + * + * @return {PIXI.Rectangle} The rectangular bounding area + */ + + + BitmapText.prototype.getLocalBounds = function getLocalBounds() { + this.validate(); + + return _core$Container.prototype.getLocalBounds.call(this); + }; + + /** + * Updates text when needed + * + * @private + */ + + + BitmapText.prototype.validate = function validate() { + if (this.dirty) { + this.updateText(); + this.dirty = false; + } + }; + + /** + * The tint of the BitmapText object + * + * @member {number} + * @memberof PIXI.extras.BitmapText# + */ + + + _createClass(BitmapText, [{ + key: 'tint', + get: function get() { + return this._font.tint; + } + + /** + * Sets the tint. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this._font.tint = typeof value === 'number' && value >= 0 ? value : 0xFFFFFF; + + this.dirty = true; + } + + /** + * The alignment of the BitmapText object + * + * @member {string} + * @default 'left' + * @memberof PIXI.extras.BitmapText# + */ + + }, { + key: 'align', + get: function get() { + return this._font.align; + } + + /** + * Sets the alignment + * + * @param {string} value - The value to set to. + */ + , + set: function set(value) { + this._font.align = value || 'left'; + + this.dirty = true; + } + + /** + * The anchor sets the origin point of the text. + * The default is 0,0 this means the text's origin is the top left + * Setting the anchor to 0.5,0.5 means the text's origin is centered + * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner + * + * @member {PIXI.Point | number} + * @memberof PIXI.extras.BitmapText# + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + } + + /** + * Sets the anchor. + * + * @param {PIXI.Point|number} value - The value to set to. + */ + , + set: function set(value) { + if (typeof value === 'number') { + this._anchor.set(value); + } else { + this._anchor.copy(value); + } + } + + /** + * The font descriptor of the BitmapText object + * + * @member {string|object} + * @memberof PIXI.extras.BitmapText# + */ + + }, { + key: 'font', + get: function get() { + return this._font; + } + + /** + * Sets the font. + * + * @param {string|object} value - The value to set to. + */ + , + set: function set(value) { + if (!value) { + return; + } + + if (typeof value === 'string') { + value = value.split(' '); + + this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); + this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; + } else { + this._font.name = value.name; + this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); + } + + this.dirty = true; + } + + /** + * The text of the BitmapText object + * + * @member {string} + * @memberof PIXI.extras.BitmapText# + */ + + }, { + key: 'text', + get: function get() { + return this._text; + } + + /** + * Sets the text. + * + * @param {string} value - The value to set to. + */ + , + set: function set(value) { + value = value.toString() || ' '; + if (this._text === value) { + return; + } + this._text = value; + this.dirty = true; + } + }]); + + return BitmapText; +}(core.Container); + +exports.default = BitmapText; + + +BitmapText.fonts = {}; + +},{"../core":97,"../core/math/ObservablePoint":100}],160:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @typedef FrameObject + * @type {object} + * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame + * @property {number} time - the duration of the frame in ms + */ + +/** + * A MovieClip is a simple way to display an animation depicted by a list of textures. + * + * ```js + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; + * + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.fromImage(alienImages[i]); + * textureArray.push(texture); + * }; + * + * let mc = new PIXI.MovieClip(textureArray); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ +var MovieClip = function (_core$Sprite) { + _inherits(MovieClip, _core$Sprite); + + /** + * @param {PIXI.Texture[]|FrameObject[]} textures - an array of {@link PIXI.Texture} or frame + * objects that make up the animation + */ + function MovieClip(textures) { + _classCallCheck(this, MovieClip); + + /** + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture)); + + _this._textures = null; + + /** + * @private + */ + _this._durations = null; + + _this.textures = textures; + + /** + * The speed that the MovieClip will play at. Higher is faster, lower is slower + * + * @member {number} + * @default 1 + */ + _this.animationSpeed = 1; + + /** + * Whether or not the movie clip repeats after playing. + * + * @member {boolean} + * @default true + */ + _this.loop = true; + + /** + * Function to call when a MovieClip finishes playing + * + * @method + * @memberof PIXI.extras.MovieClip# + */ + _this.onComplete = null; + + /** + * Function to call when a MovieClip changes which texture is being rendered + * + * @method + * @memberof PIXI.extras.MovieClip# + */ + _this.onFrameChange = null; + + /** + * Elapsed time since animation has been started, used internally to display current texture + * + * @member {number} + * @private + */ + _this._currentTime = 0; + + /** + * Indicates if the MovieClip is currently playing + * + * @member {boolean} + * @readonly + */ + _this.playing = false; + return _this; + } + + /** + * Stops the MovieClip + * + */ + + + MovieClip.prototype.stop = function stop() { + if (!this.playing) { + return; + } + + this.playing = false; + core.ticker.shared.remove(this.update, this); + }; + + /** + * Plays the MovieClip + * + */ + + + MovieClip.prototype.play = function play() { + if (this.playing) { + return; + } + + this.playing = true; + core.ticker.shared.add(this.update, this); + }; + + /** + * Stops the MovieClip and goes to a specific frame + * + * @param {number} frameNumber - frame index to stop at + */ + + + MovieClip.prototype.gotoAndStop = function gotoAndStop(frameNumber) { + this.stop(); + + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + } + }; + + /** + * Goes to a specific frame and begins playing the MovieClip + * + * @param {number} frameNumber - frame index to start at + */ + + + MovieClip.prototype.gotoAndPlay = function gotoAndPlay(frameNumber) { + this._currentTime = frameNumber; + + this.play(); + }; + + /** + * Updates the object transform for rendering. + * + * @private + * @param {number} deltaTime - Time since last tick. + */ + + + MovieClip.prototype.update = function update(deltaTime) { + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + + lag += elapsed / 60 * 1000; + + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + + var sign = Math.sign(this.animationSpeed * deltaTime); + + this._currentTime = Math.floor(this._currentTime); + + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + + this._currentTime += lag / this._durations[this.currentFrame]; + } else { + this._currentTime += elapsed; + } + + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + + if (this.onComplete) { + this.onComplete(); + } + } else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + + if (this.onComplete) { + this.onComplete(); + } + } else if (previousFrame !== this.currentFrame) { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + } + }; + + /** + * Stops the MovieClip and destroys it + * + */ + + + MovieClip.prototype.destroy = function destroy() { + this.stop(); + _core$Sprite.prototype.destroy.call(this); + }; + + /** + * A short hand way of creating a movieclip from an array of frame ids + * + * @static + * @param {string[]} frames - The array of frames ids the movieclip will use as its texture frames + * @return {MovieClip} The new movie clip with the specified frames. + */ + + + MovieClip.fromFrames = function fromFrames(frames) { + var textures = []; + + for (var i = 0; i < frames.length; ++i) { + textures.push(core.Texture.fromFrame(frames[i])); + } + + return new MovieClip(textures); + }; + + /** + * A short hand way of creating a movieclip from an array of image ids + * + * @static + * @param {string[]} images - the array of image urls the movieclip will use as its texture frames + * @return {MovieClip} The new movie clip with the specified images as frames. + */ + + + MovieClip.fromImages = function fromImages(images) { + var textures = []; + + for (var i = 0; i < images.length; ++i) { + textures.push(core.Texture.fromImage(images[i])); + } + + return new MovieClip(textures); + }; + + /** + * totalFrames is the total number of frames in the MovieClip. This is the same as number of textures + * assigned to the MovieClip. + * + * @readonly + * @member {number} + * @memberof PIXI.extras.MovieClip# + * @default 0 + */ + + + _createClass(MovieClip, [{ + key: 'totalFrames', + get: function get() { + return this._textures.length; + } + + /** + * The array of textures used for this MovieClip + * + * @member {PIXI.Texture[]} + * @memberof PIXI.extras.MovieClip# + */ + + }, { + key: 'textures', + get: function get() { + return this._textures; + } + + /** + * Sets the textures. + * + * @param {PIXI.Texture[]} value - The texture to set. + */ + , + set: function set(value) { + if (value[0] instanceof core.Texture) { + this._textures = value; + this._durations = null; + } else { + this._textures = []; + this._durations = []; + + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + } + + /** + * The MovieClips current frame index + * + * @member {number} + * @memberof PIXI.extras.MovieClip# + * @readonly + */ + + }, { + key: 'currentFrame', + get: function get() { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + + return currentFrame; + } + }]); + + return MovieClip; +}(core.Sprite); + +exports.default = MovieClip; + +},{"../core":97}],161:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CanvasTinter = require('../core/sprites/canvas/CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); + +/** + * A tiling sprite is a fast way of rendering a tiling image + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ + +var TilingSprite = function (_core$Sprite) { + _inherits(TilingSprite, _core$Sprite); + + /** + * @param {PIXI.Texture} texture - the texture of the tiling sprite + * @param {number} [width=100] - the width of the tiling sprite + * @param {number} [height=100] - the height of the tiling sprite + */ + function TilingSprite(texture) { + var width = arguments.length <= 1 || arguments[1] === undefined ? 100 : arguments[1]; + var height = arguments.length <= 2 || arguments[2] === undefined ? 100 : arguments[2]; + + _classCallCheck(this, TilingSprite); + + /** + * Tile transform + * + * @member {PIXI.TransformStatic} + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, texture)); + + _this.tileTransform = new core.TransformStatic(); + + // /// private + + /** + * The with of the tiling sprite + * + * @member {number} + * @private + */ + _this._width = width; + + /** + * The height of the tiling sprite + * + * @member {number} + * @private + */ + _this._height = height; + + _this._canvasPattern = null; + + _this._glDatas = []; + + /** + * transform that is applied to UV to get the texture coords + * @member {PIXI.TextureTransform} + */ + _this.uvTransform = new core.TextureTransform(texture); + return _this; + } + + /** + * setter for clampEdge + * @param {number} value assigned value + */ + + + /** + * @private + */ + TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate() { + if (this.uvTransform) { + this.uvTransform.texture = this._texture; + } + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + TilingSprite.prototype._renderWebGL = function _renderWebGL(renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + + if (!texture || !texture.valid) { + return; + } + + this.tileTransform.updateLocalTransform(); + this.uvTransform.update(); + + renderer.setObjectRenderer(renderer.plugins.tiling); + renderer.plugins.tiling.render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer + */ + + + TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { + var texture = this._texture; + + if (!texture.baseTexture.hasLoaded) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var resolution = renderer.resolution; + var baseTexture = texture.baseTexture; + var modX = this.tilePosition.x / this.tileScale.x % texture._frame.width; + var modY = this.tilePosition.y / this.tileScale.y % texture._frame.height; + + // create a nice shiny pattern! + // TODO this needs to be refreshed if texture changes.. + if (!this._canvasPattern) { + // cut an object from a spritesheet.. + var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height); + + // Tint the tiling sprite + if (this.tint !== 0xFFFFFF) { + if (this.cachedTint !== this.tint) { + this.cachedTint = this.tint; + + this.tintedTexture = _CanvasTinter2.default.getTintedTexture(this, this.tint); + } + tempCanvas.context.drawImage(this.tintedTexture, 0, 0); + } else { + tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x, -texture._frame.y); + } + this._canvasPattern = tempCanvas.context.createPattern(tempCanvas.canvas, 'repeat'); + } + + // set context state.. + context.globalAlpha = this.worldAlpha; + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // TODO - this should be rolled into the setTransform above.. + context.scale(this.tileScale.x, this.tileScale.y); + + context.translate(modX + this.anchor.x * -this._width, modY + this.anchor.y * -this._height); + + // check blend mode + var compositeOperation = renderer.blendModes[this.blendMode]; + + if (compositeOperation !== renderer.context.globalCompositeOperation) { + context.globalCompositeOperation = compositeOperation; + } + + // fill the pattern! + context.fillStyle = this._canvasPattern; + context.fillRect(-modX, -modY, this._width / this.tileScale.x, this._height / this.tileScale.y); + }; + + /** + * Returns the framing rectangle of the sprite as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + TilingSprite.prototype.getBounds = function getBounds() { + var width = this._width; + var height = this._height; + + var w0 = width * (1 - this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1 - this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var minX = 0; + var maxX = 0; + var minY = 0; + var maxY = 0; + + minX = x1; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1; + maxX = x2 > maxX ? x2 : maxX; + maxX = x3 > maxX ? x3 : maxX; + maxX = x4 > maxX ? x4 : maxX; + + maxY = y1; + maxY = y2 > maxY ? y2 : maxY; + maxY = y3 > maxY ? y3 : maxY; + maxY = y4 > maxY ? y4 : maxY; + + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + }; + + /** + * Checks if a point is inside this tiling sprite. + * + * @param {PIXI.Point} point - the point to check + * @return {boolean} Whether or not the sprite contains the point. + */ + + + TilingSprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor.x; + + if (tempPoint.x > x1 && tempPoint.x < x1 + width) { + var y1 = -height * this.anchor.y; + + if (tempPoint.y > y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this tiling sprite + * + */ + + + TilingSprite.prototype.destroy = function destroy() { + _core$Sprite.prototype.destroy.call(this); + + this.tileScale = null; + this._tileScaleOffset = null; + this.tilePosition = null; + + this._uvs = null; + }; + + /** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.Texture} The newly created texture + */ + + + TilingSprite.from = function from(source, width, height) { + return new TilingSprite(core.Texture.from(source), width, height); + }; + + /** + * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId + */ + + + TilingSprite.fromFrame = function fromFrame(frameId, width, height) { + var texture = core.utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this); + } + + return new TilingSprite(texture, width, height); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @param {boolean} [crossorigin] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id + */ + + + TilingSprite.fromImage = function fromImage(imageId, width, height, crossorigin, scaleMode) { + return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode), width, height); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.extras.TilingSprite# + */ + + + _createClass(TilingSprite, [{ + key: 'clampEdge', + set: function set(value) { + this.uvTransform.clampEdge = value; + this.uvTransform.update(true); + } + + /** + * The scaling of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'tileScale', + get: function get() { + return this.tileTransform.scale; + } + + /** + * Copies the point to the scale of the tiled image. + * + * @param {PIXI.Point|PIXI.ObservablePoint} value - The value to set to. + */ + , + set: function set(value) { + this.tileTransform.scale.copy(value); + } + + /** + * The offset of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + * @memberof PIXI.TilingSprite# + */ + + }, { + key: 'tilePosition', + get: function get() { + return this.tileTransform.position; + } + + /** + * Copies the point to the position of the tiled image. + * + * @param {PIXI.Point|PIXI.ObservablePoint} value - The value to set to. + */ + , + set: function set(value) { + this.tileTransform.position.copy(value); + } + }, { + key: 'width', + get: function get() { + return this._width; + } + + /** + * Sets the width. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this._width = value; + } + + /** + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.extras.TilingSprite# + */ + + }, { + key: 'height', + get: function get() { + return this._height; + } + + /** + * Sets the width. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this._height = value; + } + }]); + + return TilingSprite; +}(core.Sprite); + +exports.default = TilingSprite; + +},{"../core":97,"../core/sprites/canvas/CanvasTinter":135}],162:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DisplayObject = core.DisplayObject; +var _tempMatrix = new core.Matrix(); + +DisplayObject.prototype._cacheAsBitmap = false; +DisplayObject.prototype._cacheData = false; + +// figured theres no point adding ALL the extra variables to prototype. +// this model can hold the information needed. This can also be generated on demand as +// most objects are not cached as bitmaps. +/** + * @class + * @ignore + */ + +var CacheData = +/** + * + */ +function CacheData() { + _classCallCheck(this, CacheData); + + this.originalRenderWebGL = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + + this.originalUpdateTransform = null; + this.originalHitTest = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.sprite = null; +}; + +Object.defineProperties(DisplayObject.prototype, { + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to 'false' + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function get() { + return this._cacheAsBitmap; + }, + set: function set(value) { + if (this._cacheAsBitmap === value) { + return; + } + + this._cacheAsBitmap = value; + + var data = void 0; + + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + + data = this._cacheData; + + data.originalRenderWebGL = this.renderWebGL; + data.originalRenderCanvas = this.renderCanvas; + + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this._calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + + data.originalDestroy = this.destroy; + + data.originalContainsPoint = this.containsPoint; + + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + + this.renderWebGL = this._renderCachedWebGL; + this.renderCanvas = this._renderCachedCanvas; + + this.destroy = this._cacheAsBitmapDestroy; + } else { + data = this._cacheData; + + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + + this.renderWebGL = data.originalRenderWebGL; + this.renderCanvas = data.originalRenderCanvas; + this._calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + + this.destroy = data.originalDestroy; + + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + } + } +}); + +/** + * Renders a cached version of the sprite with WebGL + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedWebGL = function _renderCachedWebGL(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObject(renderer); + + this._cacheData.sprite._transformID = -1; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderWebGL(renderer); +}; + +/** + * Prepares the WebGL renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + + this.alpha = 1; + + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.currentRenderer.flush(); + // this.filters= []; + + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds().clone(); + + // add some padding! + if (this._filters) { + var padding = this._filters[0].padding; + + bounds.pad(padding); + } + + // for now we cache the current renderTarget that the webGL renderer is currently using. + // this could be more elegent.. + var cachedRenderTarget = renderer._activeRenderTarget; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + var stack = renderer.filterManager.filterStack; + + // this renderTexture will be used to store the cached DisplayObject + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + // need to set // + var m = _tempMatrix; + + m.tx = -bounds.x; + m.ty = -bounds.y; + + // reset + this.transform.worldTransform.identity(); + + // set all properties to there original so we can render to a texture + this.renderWebGL = this._cacheData.originalRenderWebGL; + + renderer.render(this, renderTexture, true, m, true); + // now restore the state be setting the new properties + + renderer.bindRenderTarget(cachedRenderTarget); + + renderer.filterManager.filterStack = stack; + + this.renderWebGL = this._renderCachedWebGL; + this.updateTransform = this.displayObjectUpdateTransform; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + + // easy bounds.. + this._calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + + this._cacheData.sprite = cachedSprite; + + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + this.updateTransform(); + + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Renders a cached version of the sprite with canvas + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObjectCanvas(renderer); + + this._cacheData.sprite.worldAlpha = this.worldAlpha; + + this._cacheData.sprite.renderCanvas(renderer); +}; + +// TODO this can be the same as the webGL verison.. will need to do a little tweaking first though.. +/** + * Prepares the Canvas renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(); + + var cacheAlpha = this.alpha; + + this.alpha = 1; + + var cachedRenderTarget = renderer.context; + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + // need to set // + var m = _tempMatrix; + + this.transform.worldTransform.copy(m); + m.invert(); + + m.tx -= bounds.x; + m.ty -= bounds.y; + + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + + // renderTexture.render(this, m, true); + renderer.render(this, renderTexture, true, m, false); + + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + + this.renderCanvas = this._renderCachedCanvas; + this._calculateBounds = this._calculateCachedBounds; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite._bounds = this._bounds; + cachedSprite.alpha = cacheAlpha; + + this.updateTransform(); + this.updateTransform = this.displayObjectUpdateTransform; + + this._cacheData.sprite = cachedSprite; + + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Calculates the bounds of the cached sprite + * + * @private + */ +DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._cacheData.sprite._calculateBounds(); +}; + +/** + * Gets the bounds of the cached sprite. + * + * @private + * @return {Rectangle} The local bounds. + */ +DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(); +}; + +/** + * Destroys the cached sprite. + * + * @private + */ +DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; +}; + +/** + * Destroys the cached object. + * + * @private + */ +DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy() { + this.cacheAsBitmap = false; + this.destroy(); +}; + +},{"../core":97}],163:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * The instance name of the object. + * + * @memberof PIXI.DisplayObject# + * @member {string} + */ +core.DisplayObject.prototype.name = null; + +/** + * Returns the display object in the container + * + * @memberof PIXI.Container# + * @param {string} name - instance name + * @return {PIXI.DisplayObject} The child with the specified name. + */ +core.Container.prototype.getChildByName = function getChildByName(name) { + for (var i = 0; i < this.children.length; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + + return null; +}; + +},{"../core":97}],164:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Returns the global position of the displayObject + * + * @memberof PIXI.DisplayObject# + * @param {Point} point - the point to write the global value to. If null a new point will be returned + * @return {Point} The updated point + */ +core.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition() { + var point = arguments.length <= 0 || arguments[0] === undefined ? new core.Point() : arguments[0]; + + if (this.parent) { + this.displayObjectUpdateTransform(); + + point.x = this.worldTransform.tx; + point.y = this.worldTransform.ty; + } else { + point.x = this.position.x; + point.y = this.position.y; + } + + return point; +}; + +},{"../core":97}],165:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _MovieClip = require('./MovieClip'); + +Object.defineProperty(exports, 'MovieClip', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_MovieClip).default; + } +}); + +var _TilingSprite = require('./TilingSprite'); + +Object.defineProperty(exports, 'TilingSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSprite).default; + } +}); + +var _TilingRenderer = require('./webgl/TilingRenderer'); + +Object.defineProperty(exports, 'TilingRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingRenderer).default; + } +}); + +var _BitmapText = require('./BitmapText'); + +Object.defineProperty(exports, 'BitmapText', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BitmapText).default; + } +}); + +var _cacheAsBitmap = require('./cacheAsBitmap'); + +Object.defineProperty(exports, 'cacheAsBitmap', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_cacheAsBitmap).default; + } +}); + +var _getChildByName = require('./getChildByName'); + +Object.defineProperty(exports, 'getChildByName', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_getChildByName).default; + } +}); + +var _getGlobalPosition = require('./getGlobalPosition'); + +Object.defineProperty(exports, 'getGlobalPosition', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_getGlobalPosition).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./BitmapText":159,"./MovieClip":160,"./TilingSprite":161,"./cacheAsBitmap":162,"./getChildByName":163,"./getGlobalPosition":164,"./webgl/TilingRenderer":166}],166:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.TilingRenderer = undefined; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _const = require('../../core/const'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + + // eslint-disable-line no-undef + +var tempMat = new core.Matrix(); +var tempArray = new Float32Array(4); + +/** + * WebGL renderer plugin for tiling sprites + */ + +var TilingRenderer = exports.TilingRenderer = function (_core$ObjectRenderer) { + _inherits(TilingRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function TilingRenderer(renderer) { + _classCallCheck(this, TilingRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + _this.simpleShader = null; + _this.quad = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + TilingRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n", "#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n gl_FragColor = sample * color ;\n}\n"); + this.simpleShader = new core.Shader(gl, "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n", "#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n gl_FragColor = sample * color;\n}\n"); + + this.quad = new core.Quad(gl); + this.quad.initVao(this.shader); + }; + + /** + * + * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered + */ + + + TilingRenderer.prototype.render = function render(ts) { + var quad = this.quad; + var vertices = quad.vertices; + + vertices[0] = vertices[6] = ts._width * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + + vertices[2] = vertices[4] = ts._width * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + + vertices = quad.uvs; + + vertices[0] = vertices[6] = -ts.anchor.x; + vertices[1] = vertices[3] = -ts.anchor.y; + + vertices[2] = vertices[4] = 1.0 - ts.anchor.x; + vertices[5] = vertices[7] = 1.0 - ts.anchor.y; + + quad.upload(); + + var renderer = this.renderer; + var tex = ts._texture; + var baseTex = tex.baseTexture; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvTransform; + var isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === _const.WRAP_MODES.CLAMP) { + baseTex.wrapMode = _const.WRAP_MODES.REPEAT; + } + } else { + isSimple = baseTex.wrapMode !== _const.WRAP_MODES.CLAMP; + } + } + + var shader = isSimple ? this.simpleShader : this.shader; + + renderer.bindShader(shader); + + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + + tempMat.invert(); + if (isSimple) { + tempMat.append(uv.mapCoord); + } else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.clampFrame; + shader.uniforms.uClampOffset = uv.clampOffset; + } + shader.uniforms.uTransform = tempMat.toArray(true); + + var color = tempArray; + + core.utils.hex2rgb(ts.tint, color); + color[3] = ts.worldAlpha; + shader.uniforms.uColor = color; + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + + renderer.bindTexture(tex); + renderer.setBlendMode(ts.blendMode); + + quad.draw(); + }; + + return TilingRenderer; +}(core.ObjectRenderer); + +core.WebGLRenderer.registerPlugin('tiling', TilingRenderer); + +},{"../../core":97,"../../core/const":78}],167:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BlurXFilter = require('./BlurXFilter'); + +var _BlurXFilter2 = _interopRequireDefault(_BlurXFilter); + +var _BlurYFilter = require('./BlurYFilter'); + +var _BlurYFilter2 = _interopRequireDefault(_BlurYFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurFilter applies a Gaussian blur to an object. + * The strength of the blur can be set for x- and y-axis separately. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurFilter = function (_core$Filter) { + _inherits(BlurFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The reoslution of the blur filter. + */ + function BlurFilter(strength, quality, resolution) { + _classCallCheck(this, BlurFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this)); + + _this.blurXFilter = new _BlurXFilter2.default(); + _this.blurYFilter = new _BlurYFilter2.default(); + _this.resolution = 1; + + _this.padding = 0; + _this.resolution = resolution || 1; + _this.quality = quality || 4; + _this.blur = strength || 8; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + BlurFilter.prototype.apply = function apply(filterManager, input, output) { + var renderTarget = filterManager.getRenderTarget(true); + + this.blurXFilter.apply(filterManager, input, renderTarget, true); + this.blurYFilter.apply(filterManager, renderTarget, output, false); + + filterManager.returnRenderTarget(renderTarget); + }; + + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * + * @member {number} + * @memberOf PIXI.filters.BlurFilter# + * @default 2 + */ + + + _createClass(BlurFilter, [{ + key: 'blur', + get: function get() { + return this.blurXFilter.blur; + } + + /** + * Sets the strength of the blur. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurYFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the number of passes for blur. More passes means higher quaility bluring. + * + * @member {number} + * @memberof PIXI.filters.BlurYFilter# + * @default 1 + */ + + }, { + key: 'quality', + get: function get() { + return this.blurXFilter.quality; + } + + /** + * Sets the quality of the blur. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this.blurXFilter.quality = this.blurYFilter.quality = value; + } + + /** + * Sets the strength of the blurX property + * + * @member {number} + * @memberOf PIXI.filters.BlurFilter# + * @default 2 + */ + + }, { + key: 'blurX', + get: function get() { + return this.blurXFilter.blur; + } + + /** + * Sets the strength of the blurX. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this.blurXFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurYFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the strength of the blurY property + * + * @member {number} + * @memberOf PIXI.filters.BlurFilter# + * @default 2 + */ + + }, { + key: 'blurY', + get: function get() { + return this.blurYFilter.blur; + } + + /** + * Sets the strength of the blurY. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurYFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + }]); + + return BlurFilter; +}(core.Filter); + +exports.default = BlurFilter; + +},{"../../core":97,"./BlurXFilter":168,"./BlurYFilter":169}],168:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurXFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurXFilter = function (_core$Filter) { + _inherits(BlurXFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The reoslution of the blur filter. + */ + function BlurXFilter(strength, quality, resolution) { + _classCallCheck(this, BlurXFilter); + + var vertSrc = (0, _generateBlurVertSource2.default)(5, true); + var fragSrc = (0, _generateBlurFragSource2.default)(5); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || 1; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurXFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.width * (output.size.width / input.size.width); + + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; // / this.passes//Math.pow(1, this.passes); + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @memberof PIXI.filters.BlurXFilter# + * @default 16 + */ + + + _createClass(BlurXFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + } + + /** + * Sets the strength of the blur. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @memberof PIXI.filters.BlurXFilter# + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + } + + /** + * Sets the quality of the blur. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this._quality = value; + this.passes = value; + } + }]); + + return BlurXFilter; +}(core.Filter); + +exports.default = BlurXFilter; + +},{"../../core":97,"./generateBlurFragSource":170,"./generateBlurVertSource":171,"./getMaxBlurKernelSize":172}],169:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurYFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurYFilter = function (_core$Filter) { + _inherits(BlurYFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The reoslution of the blur filter. + */ + function BlurYFilter(strength, quality, resolution) { + _classCallCheck(this, BlurYFilter); + + var vertSrc = (0, _generateBlurVertSource2.default)(5, false); + var fragSrc = (0, _generateBlurFragSource2.default)(5); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || 1; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurYFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.height * (output.size.height / input.size.height); + + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @memberof PIXI.filters.BlurYFilter# + * @default 2 + */ + + + _createClass(BlurYFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + } + + /** + * Sets the strength of the blur. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @memberof PIXI.filters.BlurXFilter# + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + } + + /** + * Sets the quality of the blur. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this._quality = value; + this.passes = value; + } + }]); + + return BlurYFilter; +}(core.Filter); + +exports.default = BlurYFilter; + +},{"../../core":97,"./generateBlurFragSource":170,"./generateBlurVertSource":171,"./getMaxBlurKernelSize":172}],170:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateFragBlurSource; +var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] +}; + +var fragTemplate = ['varying vec2 vBlurTexCoords[%size%];', 'uniform sampler2D uSampler;', 'void main(void)', '{', ' gl_FragColor = vec4(0.0);', ' %blur%', '}'].join('\n'); + +function generateFragBlurSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + + var fragSource = fragTemplate; + + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value = void 0; + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + value = i; + + if (i >= halfLength) { + value = kernelSize - i - 1; + } + + blur = blur.replace('%value%', kernel[value]); + + blurLoop += blur; + blurLoop += '\n'; + } + + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize); + + return fragSource; +} + +},{}],171:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateVertBlurSource; +var vertTemplate = ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform float strength;', 'uniform mat3 projectionMatrix;', 'varying vec2 vBlurTexCoords[%size%];', 'void main(void)', '{', 'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);', '%blur%', '}'].join('\n'); + +function generateVertBlurSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + + var vertSource = vertTemplate; + + var blurLoop = ''; + var template = void 0; + // let value; + + if (x) { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } else { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + // value = i; + + // if(i >= halfLength) + // { + // value = kernelSize - i - 1; + // } + + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + '.0'); + + blurLoop += blur; + blurLoop += '\n'; + } + + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize); + + return vertSource; +} + +},{}],172:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = getMaxKernelSize; +function getMaxKernelSize(gl) { + var maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + var kernelSize = 15; + + while (kernelSize > maxVaryings) { + kernelSize -= 2; + } + + return kernelSize; +} + +},{}],173:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + + // eslint-disable-line no-undef + +/** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ + +var ColorMatrixFilter = function (_core$Filter) { + _inherits(ColorMatrixFilter, _core$Filter); + + /** + * + */ + function ColorMatrixFilter() { + _classCallCheck(this, ColorMatrixFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}", + // fragment shader + "#define GLSLIFY 1\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\n\nvoid main(void)\n{\n\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n gl_FragColor.r = (m[0] * c.r);\n gl_FragColor.r += (m[1] * c.g);\n gl_FragColor.r += (m[2] * c.b);\n gl_FragColor.r += (m[3] * c.a);\n gl_FragColor.r += m[4] * c.a;\n\n gl_FragColor.g = (m[5] * c.r);\n gl_FragColor.g += (m[6] * c.g);\n gl_FragColor.g += (m[7] * c.b);\n gl_FragColor.g += (m[8] * c.a);\n gl_FragColor.g += m[9] * c.a;\n\n gl_FragColor.b = (m[10] * c.r);\n gl_FragColor.b += (m[11] * c.g);\n gl_FragColor.b += (m[12] * c.b);\n gl_FragColor.b += (m[13] * c.a);\n gl_FragColor.b += m[14] * c.a;\n\n gl_FragColor.a = (m[15] * c.r);\n gl_FragColor.a += (m[16] * c.g);\n gl_FragColor.a += (m[17] * c.b);\n gl_FragColor.a += (m[18] * c.a);\n gl_FragColor.a += m[19] * c.a;\n\n// gl_FragColor = vec4(m[0]);\n}\n")); + + _this.uniforms.m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + return _this; + } + + /** + * Transforms current matrix and set the new one + * + * @param {number[]} matrix - 5x4 matrix + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix(matrix) { + var multiply = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + + var newMatrix = matrix; + + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + + // set the new matrix + this.uniforms.m = newMatrix; + }; + + /** + * Multiplies two mat5's + * + * @private + * @param {number[]} out - 5x4 matrix the receiving matrix + * @param {number[]} a - 5x4 matrix the first operand + * @param {number[]} b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix + */ + + + ColorMatrixFilter.prototype._multiply = function _multiply(out, a, b) { + // Red Channel + out[0] = a[0] * b[0] + a[1] * b[5] + a[2] * b[10] + a[3] * b[15]; + out[1] = a[0] * b[1] + a[1] * b[6] + a[2] * b[11] + a[3] * b[16]; + out[2] = a[0] * b[2] + a[1] * b[7] + a[2] * b[12] + a[3] * b[17]; + out[3] = a[0] * b[3] + a[1] * b[8] + a[2] * b[13] + a[3] * b[18]; + out[4] = a[0] * b[4] + a[1] * b[9] + a[2] * b[14] + a[3] * b[19]; + + // Green Channel + out[5] = a[5] * b[0] + a[6] * b[5] + a[7] * b[10] + a[8] * b[15]; + out[6] = a[5] * b[1] + a[6] * b[6] + a[7] * b[11] + a[8] * b[16]; + out[7] = a[5] * b[2] + a[6] * b[7] + a[7] * b[12] + a[8] * b[17]; + out[8] = a[5] * b[3] + a[6] * b[8] + a[7] * b[13] + a[8] * b[18]; + out[9] = a[5] * b[4] + a[6] * b[9] + a[7] * b[14] + a[8] * b[19]; + + // Blue Channel + out[10] = a[10] * b[0] + a[11] * b[5] + a[12] * b[10] + a[13] * b[15]; + out[11] = a[10] * b[1] + a[11] * b[6] + a[12] * b[11] + a[13] * b[16]; + out[12] = a[10] * b[2] + a[11] * b[7] + a[12] * b[12] + a[13] * b[17]; + out[13] = a[10] * b[3] + a[11] * b[8] + a[12] * b[13] + a[13] * b[18]; + out[14] = a[10] * b[4] + a[11] * b[9] + a[12] * b[14] + a[13] * b[19]; + + // Alpha Channel + out[15] = a[15] * b[0] + a[16] * b[5] + a[17] * b[10] + a[18] * b[15]; + out[16] = a[15] * b[1] + a[16] * b[6] + a[17] * b[11] + a[18] * b[16]; + out[17] = a[15] * b[2] + a[16] * b[7] + a[17] * b[12] + a[18] * b[17]; + out[18] = a[15] * b[3] + a[16] * b[8] + a[17] * b[13] + a[18] * b[18]; + out[19] = a[15] * b[4] + a[16] * b[9] + a[17] * b[14] + a[18] * b[19]; + + return out; + }; + + /** + * Create a Float32 Array and normalize the offset component to 0-1 + * + * @private + * @param {number[]} matrix - 5x4 matrix + * @return {number[]} 5x4 matrix with all values between 0-1 + */ + + + ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix(matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + + return m; + }; + + /** + * Adjusts brightness + * + * @param {number} b - value of the brigthness (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.brightness = function brightness(b, multiply) { + var matrix = [b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the matrices in grey scales + * + * @param {number} scale - value of the grey (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.greyscale = function greyscale(scale, multiply) { + var matrix = [scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the black and white matrice. + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite(multiply) { + var matrix = [0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the hue property of the color + * + * @param {number} rotation - in degrees + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.hue = function hue(rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + + var a00 = cosR + (1.0 - cosR) * w; + var a01 = w * (1.0 - cosR) - sqrW * sinR; + var a02 = w * (1.0 - cosR) + sqrW * sinR; + + var a10 = w * (1.0 - cosR) + sqrW * sinR; + var a11 = cosR + w * (1.0 - cosR); + var a12 = w * (1.0 - cosR) - sqrW * sinR; + + var a20 = w * (1.0 - cosR) - sqrW * sinR; + var a21 = w * (1.0 - cosR) + sqrW * sinR; + var a22 = cosR + w * (1.0 - cosR); + + var matrix = [a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * + * @param {number} amount - value of the contrast (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.contrast = function contrast(amount, multiply) { + var v = (amount || 0) + 1; + var o = -128 * (v - 1); + + var matrix = [v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * + * @param {number} amount - The saturation amount (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.saturate = function saturate() { + var amount = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var multiply = arguments[1]; + + var x = amount * 2 / 3 + 1; + var y = (x - 1) * -0.5; + + var matrix = [x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Desaturate image (remove color) + * + * Call the saturate function + * + */ + + + ColorMatrixFilter.prototype.desaturate = function desaturate() // eslint-disable-line no-unused-vars + { + this.saturate(-1); + }; + + /** + * Negative image (inverse of classic rgb matrix) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.negative = function negative(multiply) { + var matrix = [0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Sepia image + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.sepia = function sepia(multiply) { + var matrix = [0.393, 0.7689999, 0.18899999, 0, 0, 0.349, 0.6859999, 0.16799999, 0, 0, 0.272, 0.5339999, 0.13099999, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.technicolor = function technicolor(multiply) { + var matrix = [1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Polaroid filter + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.polaroid = function polaroid(multiply) { + var matrix = [1.438, -0.062, -0.062, 0, 0, -0.122, 1.378, -0.122, 0, 0, -0.016, -0.016, 1.483, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Filter who transforms : Red -> Blue and Blue -> Red + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.toBGR = function toBGR(multiply) { + var matrix = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.kodachrome = function kodachrome(multiply) { + var matrix = [1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Brown delicious browni filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.browni = function browni(multiply) { + var matrix = [0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Vintage filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.vintage = function vintage(multiply) { + var matrix = [0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * + * @param {number} desaturation - Tone values. + * @param {number} toned - Tone values. + * @param {string} lightColor - Tone values, example: `0xFFE580` + * @param {string} darkColor - Tone values, example: `0xFFE580` + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.colorTone = function colorTone(desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + + var lR = (lightColor >> 16 & 0xFF) / 255; + var lG = (lightColor >> 8 & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + + var dR = (darkColor >> 16 & 0xFF) / 255; + var dG = (darkColor >> 8 & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + + var matrix = [0.3, 0.59, 0.11, 0, 0, lR, lG, lB, desaturation, 0, dR, dG, dB, toned, 0, lR - dR, lG - dG, lB - dB, 0, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Night effect + * + * @param {number} intensity - The intensity of the night effect. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.night = function night(intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [intensity * -2.0, -intensity, 0, 0, 0, -intensity, 0, intensity, 0, 0, 0, intensity, intensity * 2.0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * + * @param {number} amount - how much the predator feels his future victim + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.predator = function predator(amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * LSD effect + * + * Multiply the current matrix + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.lsd = function lsd(multiply) { + var matrix = [2, -0.4, 0.5, 0, 0, -0.5, 2, -0.4, 0, 0, -0.4, -0.5, 3, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Erase the current matrix by setting the default one + * + */ + + + ColorMatrixFilter.prototype.reset = function reset() { + var matrix = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, false); + }; + + /** + * The matrix of the color matrix filter + * + * @member {number[]} + * @memberof PIXI.filters.ColorMatrixFilter# + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + + + _createClass(ColorMatrixFilter, [{ + key: 'matrix', + get: function get() { + return this.uniforms.m; + } + + /** + * Sets the matrix directly. + * + * @param {number[]} value - the value to set to. + */ + , + set: function set(value) { + this.uniforms.m = value; + } + }]); + + return ColorMatrixFilter; +}(core.Filter); + +// Americanized alias + + +exports.default = ColorMatrixFilter; +ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + +},{"../../core":97}],174:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + + // eslint-disable-line no-undef + +/** + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. You can + * use this filter to apply all manor of crazy warping effects. Currently the r + * property of the texture is used to offset the x and the g property of the texture + * is used to offset the y. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ + +var DisplacementFilter = function (_core$Filter) { + _inherits(DisplacementFilter, _core$Filter); + + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param {number} scale - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + _classCallCheck(this, DisplacementFilter); + + var maskMatrix = new core.Matrix(); + + sprite.renderable = false; + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}", + // fragment shader + "#define GLSLIFY 1\nvarying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n")); + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + + _this.uniforms.mapSampler = sprite.texture; + _this.uniforms.filterMatrix = maskMatrix.toArray(true); + _this.uniforms.scale = { x: 1, y: 1 }; + + if (scale === null || scale === undefined) { + scale = 20; + } + + _this.scale = new core.Point(scale, scale); + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + DisplacementFilter.prototype.apply = function apply(filterManager, input, output) { + var ratio = 1 / output.destinationFrame.width * (output.size.width / input.size.width); + + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x * ratio; + this.uniforms.scale.y = this.scale.y * ratio; + + // draw the filter... + filterManager.applyFilter(this, input, output); + }; + + /** + * The texture used for the displacement map. Must be power of 2 sized texture. + * + * @member {PIXI.Texture} + * @memberof PIXI.filters.DisplacementFilter# + */ + + + _createClass(DisplacementFilter, [{ + key: 'map', + get: function get() { + return this.uniforms.mapSampler; + } + + /** + * Sets the texture to use for the displacement. + * + * @param {PIXI.Texture} value - The texture to set to. + */ + , + set: function set(value) { + this.uniforms.mapSampler = value; + } + }]); + + return DisplacementFilter; +}(core.Filter); + +exports.default = DisplacementFilter; + +},{"../../core":97}],175:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + + // eslint-disable-line no-undef + +/** + * + * Basic FXAA implementation based on the code on geeks3d.com with the + * modification that the texture2DLod stuff was removed since it's + * unsupported by WebGL. + * + * @see https://github.com/mitsuhiko/webgl-meincraft + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + * + */ + +var FXAAFilter = function (_core$Filter) { + _inherits(FXAAFilter, _core$Filter); + + /** + * + */ + function FXAAFilter() { + _classCallCheck(this, FXAAFilter); + + // TODO - needs work + return _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}", + // fragment shader + "#define GLSLIFY 1\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it's\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n")); + } + + return FXAAFilter; +}(core.Filter); + +exports.default = FXAAFilter; + +},{"../../core":97}],176:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _FXAAFilter = require('./fxaa/FXAAFilter'); + +Object.defineProperty(exports, 'FXAAFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_FXAAFilter).default; + } +}); + +var _NoiseFilter = require('./noise/NoiseFilter'); + +Object.defineProperty(exports, 'NoiseFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NoiseFilter).default; + } +}); + +var _DisplacementFilter = require('./displacement/DisplacementFilter'); + +Object.defineProperty(exports, 'DisplacementFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplacementFilter).default; + } +}); + +var _BlurFilter = require('./blur/BlurFilter'); + +Object.defineProperty(exports, 'BlurFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurFilter).default; + } +}); + +var _BlurXFilter = require('./blur/BlurXFilter'); + +Object.defineProperty(exports, 'BlurXFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurXFilter).default; + } +}); + +var _BlurYFilter = require('./blur/BlurYFilter'); + +Object.defineProperty(exports, 'BlurYFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurYFilter).default; + } +}); + +var _ColorMatrixFilter = require('./colormatrix/ColorMatrixFilter'); + +Object.defineProperty(exports, 'ColorMatrixFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ColorMatrixFilter).default; + } +}); + +var _VoidFilter = require('./void/VoidFilter'); + +Object.defineProperty(exports, 'VoidFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VoidFilter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./blur/BlurFilter":167,"./blur/BlurXFilter":168,"./blur/BlurYFilter":169,"./colormatrix/ColorMatrixFilter":173,"./displacement/DisplacementFilter":174,"./fxaa/FXAAFilter":175,"./noise/NoiseFilter":177,"./void/VoidFilter":178}],177:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + + // eslint-disable-line no-undef + +/** + * @author Vico @vicocotea + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + */ + +/** + * A Noise effect filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ + +var NoiseFilter = function (_core$Filter) { + _inherits(NoiseFilter, _core$Filter); + + /** + * + */ + function NoiseFilter() { + _classCallCheck(this, NoiseFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}", + // fragment shader + "precision highp float;\n#define GLSLIFY 1\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float noise;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n float diff = (rand(gl_FragCoord.xy) - 0.5) * noise;\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n gl_FragColor = color;\n}\n")); + + _this.noise = 0.5; + return _this; + } + + /** + * The amount of noise to apply. + * + * @member {number} + * @memberof PIXI.filters.NoiseFilter# + * @default 0.5 + */ + + + _createClass(NoiseFilter, [{ + key: 'noise', + get: function get() { + return this.uniforms.noise; + } + + /** + * Sets the amount of noise to apply. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this.uniforms.noise = value; + } + }]); + + return NoiseFilter; +}(core.Filter); + +exports.default = NoiseFilter; + +},{"../../core":97}],178:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// @see https://github.com/substack/brfs/issues/25 + // eslint-disable-line no-undef + +/** + * Does nothing. Very handy. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ + +var VoidFilter = function (_core$Filter) { + _inherits(VoidFilter, _core$Filter); + + /** + * + */ + function VoidFilter() { + _classCallCheck(this, VoidFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}", + // fragment shader + "#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n")); + + _this.glShaderKey = 'void'; + return _this; + } + + return VoidFilter; +}(core.Filter); + +exports.default = VoidFilter; + +},{"../../core":97}],179:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Holds all information related to an Interaction event + * + * @class + * @memberof PIXI.interaction + */ +var InteractionData = function () { + /** + * + */ + function InteractionData() { + _classCallCheck(this, InteractionData); + + /** + * This point stores the global coords of where the touch/mouse event happened + * + * @member {PIXI.Point} + */ + this.global = new core.Point(); + + /** + * The target Sprite that was interacted with + * + * @member {PIXI.Sprite} + */ + this.target = null; + + /** + * When passed to an event handler, this will be the original DOM Event that was captured + * + * @member {Event} + */ + this.originalEvent = null; + } + + /** + * This will return the local coordinates of the specified displayObject for this InteractionData + * + * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local + * coords off + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative + * to the DisplayObject + */ + + + InteractionData.prototype.getLocalPosition = function getLocalPosition(displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + + return InteractionData; +}(); + +exports.default = InteractionData; + +},{"../core":97}],180:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Event class that mimics native DOM events. + * + * @class + * @memberof PIXI.interaction + */ +var InteractionEvent = function () { + /** + * + */ + function InteractionEvent() { + _classCallCheck(this, InteractionEvent); + + /** + * Which this event will continue propagating in the tree + * + * @member {boolean} + */ + this.stopped = false; + + /** + * The object to which event is dispatched. + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * The object whose event listener’s callback is currently being invoked. + * + * @member {PIXI.DisplayObject} + */ + this.currentTarget = null; + + /* + * Type of the event + * + * @member {string} + */ + this.type = null; + + /* + * InteractionData related to this event + * + * @member {PIXI.interaction.InteractionData} + */ + this.data = null; + } + + /** + * Prevents event from reaching any objects other than the current object. + * + */ + + + InteractionEvent.prototype.stopPropagation = function stopPropagation() { + this.stopped = true; + }; + + /** + * Prevents event from reaching any objects other than the current object. + * + * @private + */ + + + InteractionEvent.prototype._reset = function _reset() { + this.stopped = false; + this.currentTarget = null; + this.target = null; + }; + + return InteractionEvent; +}(); + +exports.default = InteractionEvent; + +},{}],181:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _InteractionData = require('./InteractionData'); + +var _InteractionData2 = _interopRequireDefault(_InteractionData); + +var _InteractionEvent = require('./InteractionEvent'); + +var _InteractionEvent2 = _interopRequireDefault(_InteractionEvent); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _interactiveTarget = require('./interactiveTarget'); + +var _interactiveTarget2 = _interopRequireDefault(_interactiveTarget); + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// Mix interactiveTarget into core.DisplayObject.prototype +Object.assign(core.DisplayObject.prototype, _interactiveTarget2.default); + +/** + * The interaction manager deals with mouse and touch events. Any DisplayObject can be interactive + * if its interactive parameter is set to true + * This manager also supports multitouch. + * + * @class + * @extends EventEmitter + * @memberof PIXI.interaction + */ + +var InteractionManager = function (_EventEmitter) { + _inherits(InteractionManager, _EventEmitter); + + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + * @param {object} [options] - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Frequency increases the interaction events will be checked. + */ + function InteractionManager(renderer, options) { + _classCallCheck(this, InteractionManager); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + options = options || {}; + + /** + * The renderer this interaction manager works for. + * + * @member {PIXI.SystemRenderer} + */ + _this.renderer = renderer; + + /** + * Should default browser actions automatically be prevented. + * + * @member {boolean} + * @default true + */ + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + + /** + * As this frequency increases the interaction events will be checked more often. + * + * @member {number} + * @default 10 + */ + _this.interactionFrequency = options.interactionFrequency || 10; + + /** + * The mouse data + * + * @member {PIXI.interaction.InteractionData} + */ + _this.mouse = new _InteractionData2.default(); + + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + + /** + * The pointer data + * + * @member {PIXI.interaction.InteractionData} + */ + _this.pointer = new _InteractionData2.default(); + + // setting the pointer to start off far off screen will mean that pointer over does + // not get called before we even move the pointer. + _this.pointer.global.set(-999999); + + /** + * An event data object to handle all the event tracking/dispatching + * + * @member {object} + */ + _this.eventData = new _InteractionEvent2.default(); + + /** + * Tiny little interactiveData pool ! + * + * @member {PIXI.interaction.InteractionData[]} + */ + _this.interactiveDataPool = []; + + /** + * The DOM element to bind to. + * + * @private + * @member {HTMLElement} + */ + _this.interactionDOMElement = null; + + /** + * This property determins if mousemove and touchmove events are fired only when the cursror + * is over the object. + * Setting to true will make things work more in line with how the DOM verison works. + * Setting to false can make things easier for things like dragging + * It is currently set to false as this is how pixi used to work. This will be set to true in + * future versions of pixi. + * + * @private + * @member {boolean} + */ + _this.moveWhenInside = false; + + /** + * Have events been attached to the dom element? + * + * @private + * @member {boolean} + */ + _this.eventsAdded = false; + + /** + * Is the mouse hovering over the renderer? + * + * @private + * @member {boolean} + */ + _this.mouseOverRenderer = false; + + /** + * Does the device support touch events + * https://www.w3.org/TR/touch-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsTouchEvents = 'ontouchstart' in window; + + /** + * Does the device support pointer events + * https://www.w3.org/Submission/pointer-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsPointerEvents = !!window.PointerEvent; + + /** + * Are touch events being 'normalized' and converted into pointer events if pointer events are not supported + * For example, on a touch screen mobile device, a touchstart would also be emitted as a pointerdown + * + * @private + * @readonly + * @member {boolean} + */ + _this.normalizingTouchEvents = !_this.supportsPointerEvents && _this.supportsTouchEvents; + + /** + * Are mouse events being 'normalized' and converted into pointer events if pointer events are not supported + * For example, on a desktop pc, a mousedown would also be emitted as a pointerdown + * + * @private + * @readonly + * @member {boolean} + */ + _this.normalizingMouseEvents = !_this.supportsPointerEvents && !_ismobilejs2.default.any; + + // this will make it so that you don't have to call bind all the time + + /** + * @private + * @member {Function} + */ + _this.onMouseUp = _this.onMouseUp.bind(_this); + _this.processMouseUp = _this.processMouseUp.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onMouseDown = _this.onMouseDown.bind(_this); + _this.processMouseDown = _this.processMouseDown.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onMouseMove = _this.onMouseMove.bind(_this); + _this.processMouseMove = _this.processMouseMove.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onMouseOut = _this.onMouseOut.bind(_this); + _this.processMouseOverOut = _this.processMouseOverOut.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onMouseOver = _this.onMouseOver.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOver = _this.onPointerOver.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onTouchStart = _this.onTouchStart.bind(_this); + _this.processTouchStart = _this.processTouchStart.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onTouchEnd = _this.onTouchEnd.bind(_this); + _this.processTouchEnd = _this.processTouchEnd.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onTouchMove = _this.onTouchMove.bind(_this); + _this.processTouchMove = _this.processTouchMove.bind(_this); + + /** + * Every update cursor will be reset to this value, if some element wont override it in + * its hitTest. + * + * @member {string} + * @default 'inherit' + */ + _this.defaultCursorStyle = 'inherit'; + + /** + * The css style of the cursor that is being used. + * + * @member {string} + */ + _this.currentCursorStyle = 'inherit'; + + /** + * Internal cached let. + * + * @private + * @member {PIXI.Point} + */ + _this._tempPoint = new core.Point(); + + /** + * The current resolution / device pixel ratio. + * + * @member {number} + * @default 1 + */ + _this.resolution = 1; + + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + + /** + * Fired when a pointer device button (usually a mouse button) is pressed on the display + * object. + * + * @event mousedown + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * + * @event rightdown + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is released over the display + * object. + * + * @event mouseup + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * + * @event rightup + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is pressed and released on + * the display object. + * + * @event click + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * + * @event rightclick + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. + * + * @event mouseupoutside + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. + * + * @event rightupoutside + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * + * @event mousemove + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * + * @event mouseover + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * + * @event mouseout + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * + * @event pointerdown + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is released over the display object. + * + * @event pointerup + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * + * @event pointertap + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}. + * + * @event pointerupoutside + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved while over the display object + * + * @event pointermove + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved onto the display object + * + * @event pointerover + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved off the display object + * + * @event pointerout + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is placed on the display object. + * + * @event touchstart + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is removed from the display object. + * + * @event touchend + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * + * @event tap + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. + * + * @event touchendoutside + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is moved along the display object. + * + * @event touchmove + * @memberof PIXI.interaction.InteractionManager# + */ + return _this; + } + + /** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate + * another DOM element to receive those events. + * + * @param {HTMLCanvasElement} element - the DOM element which will receive mouse and touch events. + * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). + * @private + */ + + + InteractionManager.prototype.setTargetElement = function setTargetElement(element) { + var resolution = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1]; + + this.removeEvents(); + + this.interactionDOMElement = element; + + this.resolution = resolution; + + this.addEvents(); + }; + + /** + * Registers all the DOM events + * + * @private + */ + + + InteractionManager.prototype.addEvents = function addEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.add(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; + this.interactionDOMElement.style['-ms-touch-action'] = 'none'; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = 'none'; + } + + window.document.addEventListener('mousemove', this.onMouseMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onMouseDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onMouseOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onMouseOver, true); + window.addEventListener('mouseup', this.onMouseUp, true); + + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onTouchStart, true); + this.interactionDOMElement.addEventListener('touchend', this.onTouchEnd, true); + this.interactionDOMElement.addEventListener('touchmove', this.onTouchMove, true); + } + + if (this.supportsPointerEvents) { + window.document.addEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('pointerout', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); + window.addEventListener('pointerup', this.onPointerUp, true); + } else { + /** + * If pointer events aren't available on a device, this will turn either the touch or + * mouse events into pointer events. This allows a developer to just listen for emitted + * pointer events on interactive sprites + */ + if (this.normalizingTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); + } + + if (this.normalizingMouseEvents) { + window.document.addEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); + window.addEventListener('mouseup', this.onPointerUp, true); + } + } + + this.eventsAdded = true; + }; + + /** + * Removes all the DOM events that were previously registered + * + * @private + */ + + + InteractionManager.prototype.removeEvents = function removeEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.remove(this.update); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = ''; + this.interactionDOMElement.style['-ms-touch-action'] = ''; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = ''; + } + + window.document.removeEventListener('mousemove', this.onMouseMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onMouseDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onMouseOut, true); + this.interactionDOMElement.removeEventListener('mouseover', this.onMouseOver, true); + window.removeEventListener('mouseup', this.onMouseUp, true); + + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onTouchStart, true); + this.interactionDOMElement.removeEventListener('touchend', this.onTouchEnd, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onTouchMove, true); + } + + if (this.supportsPointerEvents) { + window.document.removeEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('pointerout', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); + window.removeEventListener('pointerup', this.onPointerUp, true); + } else { + /** + * If pointer events aren't available on a device, this will turn either the touch or + * mouse events into pointer events. This allows a developer to just listen for emitted + * pointer events on interactive sprites + */ + if (this.normalizingTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); + } + + if (this.normalizingMouseEvents) { + window.document.removeEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); + window.removeEventListener('mouseup', this.onPointerUp, true); + } + } + + this.interactionDOMElement = null; + + this.eventsAdded = false; + }; + + /** + * Updates the state of interactive objects. + * Invoked by a throttled ticker update from {@link PIXI.ticker.shared}. + * + * @param {number} deltaTime - time delta since last tick + */ + + + InteractionManager.prototype.update = function update(deltaTime) { + this._deltaTime += deltaTime; + + if (this._deltaTime < this.interactionFrequency) { + return; + } + + this._deltaTime = 0; + + if (!this.interactionDOMElement) { + return; + } + + // if the user move the mouse this check has already been dfone using the mouse move! + if (this.didMove) { + this.didMove = false; + + return; + } + + this.cursor = this.defaultCursorStyle; + + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + this.eventData._reset(); + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseOverOut, true); + + if (this.currentCursorStyle !== this.cursor) { + this.currentCursorStyle = this.cursor; + this.interactionDOMElement.style.cursor = this.cursor; + } + + // TODO + }; + + /** + * Dispatches an event on the display object that was interacted with + * + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the display object in question + * @param {string} eventString - the name of the event (e.g, mousedown) + * @param {object} eventData - the event data object + * @private + */ + + + InteractionManager.prototype.dispatchEvent = function dispatchEvent(displayObject, eventString, eventData) { + if (!eventData.stopped) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + + displayObject.emit(eventString, eventData); + + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } + }; + + /** + * Maps x and y coords from a DOM object and maps them correctly to the pixi view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. + * + * @param {PIXI.Point} point - the point that the result will be stored in + * @param {number} x - the x coord of the position to map + * @param {number} y - the y coord of the position to map + */ + + + InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint(point, x, y) { + var rect = void 0; + + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { x: 0, y: 0, width: 0, height: 0 }; + } else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + + point.x = (x - rect.left) * (this.interactionDOMElement.width / rect.width) / this.resolution; + point.y = (y - rect.top) * (this.interactionDOMElement.height / rect.height) / this.resolution; + }; + + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * + * @param {PIXI.Point} point - the point that is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the displayObject + * that will be hit test (recurcsivly crawls its children) + * @param {Function} [func] - the function that will be called on each interactive object. The + * displayObject and hit will be passed to the function + * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point + * @param {boolean} [interactive] - Whether the displayObject is interactive + * @return {boolean} returns true if the displayObject hit the point + */ + + + InteractionManager.prototype.processInteractive = function processInteractive(point, displayObject, func, hitTest, interactive) { + if (!displayObject || !displayObject.visible) { + return false; + } + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + interactive = displayObject.interactive || interactive; + + var hit = false; + var interactiveParent = interactive; + + // if the displayobject has a hitArea, then it does not need to hitTest children. + if (displayObject.hitArea) { + interactiveParent = false; + } + + // it has a mask! Then lets hit test that before continuing.. + if (hitTest && displayObject._mask) { + if (!displayObject._mask.containsPoint(point)) { + hitTest = false; + } + } + + // it has a filterArea! Same as mask but easier, its a rectangle + if (hitTest && displayObject.filterArea) { + if (!displayObject.filterArea.contains(point.x, point.y)) { + hitTest = false; + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow pixi to completly ignore and bypass checking the displayObjects children. + if (displayObject.interactiveChildren) { + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + + // time to get recursive.. if this function will return if somthing is hit.. + if (this.processInteractive(point, child, func, hitTest, interactiveParent)) { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if (!child.parent) { + continue; + } + + hit = true; + + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + + // { + hitTest = false; + // } + + // we can break now as we have hit an object. + } + } + } + + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit! + if (hitTest && !hit) { + if (displayObject.hitArea) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + hit = displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y); + } else if (displayObject.containsPoint) { + hit = displayObject.containsPoint(point); + } + } + + if (displayObject.interactive) { + if (hit && !this.eventData.target) { + this.eventData.target = displayObject; + this.mouse.target = displayObject; + this.pointer.target = displayObject; + } + + func(displayObject, hit); + } + } + + return hit; + }; + + /** + * Is called when the mouse button is pressed down on the renderer element + * + * @private + * @param {MouseEvent} event - The DOM event of a mouse button being pressed down + */ + + + InteractionManager.prototype.onMouseDown = function onMouseDown(event) { + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData._reset(); + + // Update internal mouse reference + this.mapPositionToPoint(this.mouse.global, event.clientX, event.clientY); + + if (this.autoPreventDefault) { + this.mouse.originalEvent.preventDefault(); + } + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseDown, true); + + var isRightButton = event.button === 2 || event.which === 3; + + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + }; + + /** + * Processes the result of the mouse down check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processMouseDown = function processMouseDown(displayObject, hit) { + var e = this.mouse.originalEvent; + + var isRightButton = e.button === 2 || e.which === 3; + + if (hit) { + displayObject[isRightButton ? '_isRightDown' : '_isLeftDown'] = true; + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + }; + + /** + * Is called when the mouse button is released on the renderer element + * + * @private + * @param {MouseEvent} event - The DOM event of a mouse button being released + */ + + + InteractionManager.prototype.onMouseUp = function onMouseUp(event) { + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData._reset(); + + // Update internal mouse reference + this.mapPositionToPoint(this.mouse.global, event.clientX, event.clientY); + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseUp, true); + + var isRightButton = event.button === 2 || event.which === 3; + + this.emit(isRightButton ? 'rightup' : 'mouseup', this.eventData); + }; + + /** + * Processes the result of the mouse up check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processMouseUp = function processMouseUp(displayObject, hit) { + var e = this.mouse.originalEvent; + + var isRightButton = e.button === 2 || e.which === 3; + var isDown = isRightButton ? '_isRightDown' : '_isLeftDown'; + + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', this.eventData); + + if (displayObject[isDown]) { + displayObject[isDown] = false; + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', this.eventData); + } + } else if (displayObject[isDown]) { + displayObject[isDown] = false; + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', this.eventData); + } + }; + + /** + * Is called when the mouse moves across the renderer element + * + * @private + * @param {MouseEvent} event - The DOM event of the mouse moving + */ + + + InteractionManager.prototype.onMouseMove = function onMouseMove(event) { + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData._reset(); + + this.mapPositionToPoint(this.mouse.global, event.clientX, event.clientY); + + this.didMove = true; + + this.cursor = this.defaultCursorStyle; + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseMove, true); + + this.emit('mousemove', this.eventData); + + if (this.currentCursorStyle !== this.cursor) { + this.currentCursorStyle = this.cursor; + this.interactionDOMElement.style.cursor = this.cursor; + } + + // TODO BUG for parents ineractive object (border order issue) + }; + + /** + * Processes the result of the mouse move check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processMouseMove = function processMouseMove(displayObject, hit) { + this.processMouseOverOut(displayObject, hit); + + // only display on mouse over + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'mousemove', this.eventData); + } + }; + + /** + * Is called when the mouse is moved out of the renderer element + * + * @private + * @param {MouseEvent} event - The DOM event of the mouse being moved out + */ + + + InteractionManager.prototype.onMouseOut = function onMouseOut(event) { + this.mouseOverRenderer = false; + + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData._reset(); + + // Update internal mouse reference + this.mapPositionToPoint(this.mouse.global, event.clientX, event.clientY); + + this.interactionDOMElement.style.cursor = this.defaultCursorStyle; + + // TODO optimize by not check EVERY TIME! maybe half as often? // + this.mapPositionToPoint(this.mouse.global, event.clientX, event.clientY); + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseOverOut, false); + + this.emit('mouseout', this.eventData); + }; + + /** + * Processes the result of the mouse over/out check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processMouseOverOut = function processMouseOverOut(displayObject, hit) { + if (hit && this.mouseOverRenderer) { + if (!displayObject._mouseOver) { + displayObject._mouseOver = true; + this.dispatchEvent(displayObject, 'mouseover', this.eventData); + } + + if (displayObject.buttonMode) { + this.cursor = displayObject.defaultCursor; + } + } else if (displayObject._mouseOver) { + displayObject._mouseOver = false; + this.dispatchEvent(displayObject, 'mouseout', this.eventData); + } + }; + + /** + * Is called when the mouse enters the renderer element area + * + * @private + * @param {MouseEvent} event - The DOM event of the mouse moving into the renderer view + */ + + + InteractionManager.prototype.onMouseOver = function onMouseOver(event) { + this.mouseOverRenderer = true; + + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData._reset(); + + this.emit('mouseover', this.eventData); + }; + + /** + * Is called when the pointer button is pressed down on the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being pressed down + */ + + + InteractionManager.prototype.onPointerDown = function onPointerDown(event) { + this.normalizeToPointerData(event); + this.pointer.originalEvent = event; + this.eventData.data = this.pointer; + this.eventData._reset(); + + // Update internal pointer reference + this.mapPositionToPoint(this.pointer.global, event.clientX, event.clientY); + + if (this.autoPreventDefault) { + this.pointer.originalEvent.preventDefault(); + } + + this.processInteractive(this.pointer.global, this.renderer._lastObjectRendered, this.processPointerDown, true); + + this.emit('pointerdown', this.eventData); + }; + + /** + * Processes the result of the pointer down check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerDown = function processPointerDown(displayObject, hit) { + if (hit) { + displayObject._pointerDown = true; + this.dispatchEvent(displayObject, 'pointerdown', this.eventData); + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerUp = function onPointerUp(event) { + this.normalizeToPointerData(event); + this.pointer.originalEvent = event; + this.eventData.data = this.pointer; + this.eventData._reset(); + + // Update internal pointer reference + this.mapPositionToPoint(this.pointer.global, event.clientX, event.clientY); + + this.processInteractive(this.pointer.global, this.renderer._lastObjectRendered, this.processPointerUp, true); + + this.emit('pointerup', this.eventData); + }; + + /** + * Processes the result of the pointer up check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerUp = function processPointerUp(displayObject, hit) { + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', this.eventData); + + if (displayObject._pointerDown) { + displayObject._pointerDown = false; + this.dispatchEvent(displayObject, 'pointertap', this.eventData); + } + } else if (displayObject._pointerDown) { + displayObject._pointerDown = false; + this.dispatchEvent(displayObject, 'pointerupoutside', this.eventData); + } + }; + + /** + * Is called when the pointer moves across the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer moving + */ + + + InteractionManager.prototype.onPointerMove = function onPointerMove(event) { + this.normalizeToPointerData(event); + this.pointer.originalEvent = event; + this.eventData.data = this.pointer; + this.eventData._reset(); + + this.mapPositionToPoint(this.pointer.global, event.clientX, event.clientY); + + this.processInteractive(this.pointer.global, this.renderer._lastObjectRendered, this.processPointerMove, true); + + this.emit('pointermove', this.eventData); + }; + + /** + * Processes the result of the pointer move check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerMove = function processPointerMove(displayObject, hit) { + if (!this.pointer.originalEvent.changedTouches) { + this.processPointerOverOut(displayObject, hit); + } + + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', this.eventData); + } + }; + + /** + * Is called when the pointer is moved out of the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer being moved out + */ + + + InteractionManager.prototype.onPointerOut = function onPointerOut(event) { + this.normalizeToPointerData(event); + this.pointer.originalEvent = event; + this.eventData.data = this.pointer; + this.eventData._reset(); + + // Update internal pointer reference + this.mapPositionToPoint(this.pointer.global, event.clientX, event.clientY); + + this.processInteractive(this.pointer.global, this.renderer._lastObjectRendered, this.processPointerOverOut, false); + + this.emit('pointerout', this.eventData); + }; + + /** + * Processes the result of the pointer over/out check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerOverOut = function processPointerOverOut(displayObject, hit) { + if (hit && this.mouseOverRenderer) { + if (!displayObject._pointerOver) { + displayObject._pointerOver = true; + this.dispatchEvent(displayObject, 'pointerover', this.eventData); + } + } else if (displayObject._pointerOver) { + displayObject._pointerOver = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + } + }; + + /** + * Is called when the pointer is moved into the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being moved into the renderer view + */ + + + InteractionManager.prototype.onPointerOver = function onPointerOver(event) { + this.pointer.originalEvent = event; + this.eventData.data = this.pointer; + this.eventData._reset(); + + this.emit('pointerover', this.eventData); + }; + + /** + * Is called when a touch is started on the renderer element + * + * @private + * @param {TouchEvent} event - The DOM event of a touch starting on the renderer view + */ + + + InteractionManager.prototype.onTouchStart = function onTouchStart(event) { + if (this.autoPreventDefault) { + event.preventDefault(); + } + + var changedTouches = event.changedTouches; + var cLength = changedTouches.length; + + for (var i = 0; i < cLength; i++) { + var touch = changedTouches[i]; + var touchData = this.getTouchData(touch); + + touchData.originalEvent = event; + + this.eventData.data = touchData; + this.eventData._reset(); + + this.processInteractive(touchData.global, this.renderer._lastObjectRendered, this.processTouchStart, true); + + this.emit('touchstart', this.eventData); + + this.returnTouchData(touchData); + } + }; + + /** + * Processes the result of a touch check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processTouchStart = function processTouchStart(displayObject, hit) { + if (hit) { + displayObject._touchDown = true; + this.dispatchEvent(displayObject, 'touchstart', this.eventData); + } + }; + + /** + * Is called when a touch ends on the renderer element + * + * @private + * @param {TouchEvent} event - The DOM event of a touch ending on the renderer view + */ + + + InteractionManager.prototype.onTouchEnd = function onTouchEnd(event) { + if (this.autoPreventDefault) { + event.preventDefault(); + } + + var changedTouches = event.changedTouches; + var cLength = changedTouches.length; + + for (var i = 0; i < cLength; i++) { + var touchEvent = changedTouches[i]; + + var touchData = this.getTouchData(touchEvent); + + touchData.originalEvent = event; + + // TODO this should be passed along.. no set + this.eventData.data = touchData; + this.eventData._reset(); + + this.processInteractive(touchData.global, this.renderer._lastObjectRendered, this.processTouchEnd, true); + + this.emit('touchend', this.eventData); + + this.returnTouchData(touchData); + } + }; + + /** + * Processes the result of the end of a touch and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processTouchEnd = function processTouchEnd(displayObject, hit) { + if (hit) { + this.dispatchEvent(displayObject, 'touchend', this.eventData); + + if (displayObject._touchDown) { + displayObject._touchDown = false; + this.dispatchEvent(displayObject, 'tap', this.eventData); + } + } else if (displayObject._touchDown) { + displayObject._touchDown = false; + this.dispatchEvent(displayObject, 'touchendoutside', this.eventData); + } + }; + + /** + * Is called when a touch is moved across the renderer element + * + * @private + * @param {TouchEvent} event - The DOM event of a touch moving accross the renderer view + */ + + + InteractionManager.prototype.onTouchMove = function onTouchMove(event) { + if (this.autoPreventDefault) { + event.preventDefault(); + } + + var changedTouches = event.changedTouches; + var cLength = changedTouches.length; + + for (var i = 0; i < cLength; i++) { + var touchEvent = changedTouches[i]; + + var touchData = this.getTouchData(touchEvent); + + touchData.originalEvent = event; + + this.eventData.data = touchData; + this.eventData._reset(); + + this.processInteractive(touchData.global, this.renderer._lastObjectRendered, this.processTouchMove, this.moveWhenInside); + + this.emit('touchmove', this.eventData); + + this.returnTouchData(touchData); + } + }; + + /** + * Processes the result of a touch move check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processTouchMove = function processTouchMove(displayObject, hit) { + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'touchmove', this.eventData); + } + }; + + /** + * Grabs an interaction data object from the internal pool + * + * @private + * @param {Touch} touch - The touch data we need to pair with an interactionData object + * @return {PIXI.interaction.InteractionData} The built data object. + */ + + + InteractionManager.prototype.getTouchData = function getTouchData(touch) { + var touchData = this.interactiveDataPool.pop() || new _InteractionData2.default(); + + touchData.identifier = touch.identifier; + this.mapPositionToPoint(touchData.global, touch.clientX, touch.clientY); + + if (navigator.isCocoonJS) { + touchData.global.x = touchData.global.x / this.resolution; + touchData.global.y = touchData.global.y / this.resolution; + } + + touch.globalX = touchData.global.x; + touch.globalY = touchData.global.y; + + return touchData; + }; + + /** + * Returns an interaction data object to the internal pool + * + * @private + * @param {PIXI.interaction.InteractionData} touchData - The touch data object we want to return to the pool + */ + + + InteractionManager.prototype.returnTouchData = function returnTouchData(touchData) { + this.interactiveDataPool.push(touchData); + }; + + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * + * @private + * @param {TouchEvent|MouseEvent} event - The original event data from a touch or mouse event + */ + + + InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData(event) { + if (this.normalizingTouchEvents && event.changedTouches) { + event.button = event.touches.length ? 1 : 0; + event.buttons = event.touches.length ? 1 : 0; + event.isPrimary = event.touches.length === 1; + event.width = event.changedTouches[0].radiusX || 1; + event.height = event.changedTouches[0].radiusY || 1; + event.tiltX = 0; + event.tiltY = 0; + event.pointerType = 'touch'; + event.pointerId = event.changedTouches[0].identifier || 0; + event.pressure = event.changedTouches[0].force || 0.5; + event.rotation = event.changedTouches[0].rotationAngle || 0; + + event.clientX = event.changedTouches[0].clientX; + event.clientY = event.changedTouches[0].clientY; + event.pageX = event.changedTouches[0].pageX; + event.pageY = event.changedTouches[0].pageY; + event.screenX = event.changedTouches[0].screenX; + event.screenY = event.changedTouches[0].screenY; + event.layerX = event.offsetX = event.clientX; + event.layerY = event.offsetY = event.clientY; + } else if (this.normalizingMouseEvents) { + event.isPrimary = true; + event.width = 1; + event.height = 1; + event.tiltX = 0; + event.tiltY = 0; + event.pointerType = 'mouse'; + event.pointerId = 1; + event.pressure = 0.5; + event.rotation = 0; + } + }; + + /** + * Destroys the interaction manager + * + */ + + + InteractionManager.prototype.destroy = function destroy() { + this.removeEvents(); + + this.removeAllListeners(); + + this.renderer = null; + + this.mouse = null; + + this.eventData = null; + + this.interactiveDataPool = null; + + this.interactionDOMElement = null; + + this.onMouseDown = null; + this.processMouseDown = null; + + this.onMouseUp = null; + this.processMouseUp = null; + + this.onMouseMove = null; + this.processMouseMove = null; + + this.onMouseOut = null; + this.processMouseOverOut = null; + + this.onMouseOver = null; + + this.onPointerDown = null; + this.processPointerDown = null; + + this.onPointerUp = null; + this.processPointerUp = null; + + this.onPointerMove = null; + this.processPointerMove = null; + + this.onPointerOut = null; + this.processPointerOverOut = null; + + this.onPointerOver = null; + + this.onTouchStart = null; + this.processTouchStart = null; + + this.onTouchEnd = null; + this.processTouchEnd = null; + + this.onTouchMove = null; + this.processTouchMove = null; + + this._tempPoint = null; + }; + + return InteractionManager; +}(_eventemitter2.default); + +exports.default = InteractionManager; + + +core.WebGLRenderer.registerPlugin('interaction', InteractionManager); +core.CanvasRenderer.registerPlugin('interaction', InteractionManager); + +},{"../core":97,"./InteractionData":179,"./InteractionEvent":180,"./interactiveTarget":183,"eventemitter3":16,"ismobilejs":17}],182:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _InteractionData = require('./InteractionData'); + +Object.defineProperty(exports, 'InteractionData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionData).default; + } +}); + +var _InteractionManager = require('./InteractionManager'); + +Object.defineProperty(exports, 'InteractionManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionManager).default; + } +}); + +var _interactiveTarget = require('./interactiveTarget'); + +Object.defineProperty(exports, 'interactiveTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_interactiveTarget).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./InteractionData":179,"./InteractionManager":181,"./interactiveTarget":183}],183:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * Default property values of interactive objects + * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties + * + * @mixin + * @name interactiveTarget + * @memberof PIXI.interaction + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.interaction.interactiveTarget + * ); + */ +exports.default = { + /** + * Determines if the displayObject be clicked/touched + * + * @inner {boolean} + */ + interactive: false, + + /** + * Determines if the children to the displayObject can be clicked/touched + * Setting this to false allows pixi to bypass a recursive hitTest function + * + * @inner {boolean} + */ + interactiveChildren: true, + + /** + * Interaction shape. Children will be hit first, then this shape will be checked. + * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. + * + * @inner {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle} + */ + hitArea: null, + + /** + * If enabled, the mouse cursor will change when hovered over the displayObject if it is interactive + * + * @inner {boolean} + */ + buttonMode: false, + + /** + * If buttonMode is enabled, this defines what CSS cursor property is used when the mouse cursor + * is hovered over the displayObject + * + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * + * @inner {string} + */ + defaultCursor: 'pointer', + + // some internal checks.. + /** + * Internal check to detect if the mouse cursor is hovered over the displayObject + * + * @inner {boolean} + * @private + */ + _over: false, + + /** + * Internal check to detect if the left mouse button is pressed on the displayObject + * + * @inner {boolean} + * @private + */ + _isLeftDown: false, + + /** + * Internal check to detect if the right mouse button is pressed on the displayObject + * + * @inner {boolean} + * @private + */ + _isRightDown: false, + + /** + * Internal check to detect if the pointer cursor is hovered over the displayObject + * + * @inner {boolean} + * @private + */ + _pointerOver: false, + + /** + * Internal check to detect if the pointer is down on the displayObject + * + * @inner {boolean} + * @private + */ + _pointerDown: false, + + /** + * Internal check to detect if a user has touched the displayObject + * + * @inner {boolean} + * @private + */ + _touchDown: false +}; + +},{}],184:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.parse = parse; + +exports.default = function () { + return function bitmapFontParser(resource, next) { + // skip if no data or not xml data + if (!resource.data || !resource.isXml) { + next(); + + return; + } + + // skip if not bitmap font data, using some silly duck-typing + if (resource.data.getElementsByTagName('page').length === 0 || resource.data.getElementsByTagName('info').length === 0 || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null) { + next(); + + return; + } + + var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; + + if (resource.isDataUrl) { + if (xmlUrl === '.') { + xmlUrl = ''; + } + + if (this.baseUrl && xmlUrl) { + // if baseurl has a trailing slash then add one to xmlUrl so the replace works below + if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { + xmlUrl += '/'; + } + + // remove baseUrl from xmlUrl + xmlUrl = xmlUrl.replace(this.baseUrl, ''); + } + } + + // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { + xmlUrl += '/'; + } + + var textureUrl = xmlUrl + resource.data.getElementsByTagName('page')[0].getAttribute('file'); + + if (_core.utils.TextureCache[textureUrl]) { + // reuse existing texture + parse(resource, _core.utils.TextureCache[textureUrl]); + next(); + } else { + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata + }; + + // load the texture for the font + this.add(resource.name + '_image', textureUrl, loadOptions, function (res) { + parse(resource, res.texture); + next(); + }); + } + }; +}; + +var _path = require('path'); + +var path = _interopRequireWildcard(_path); + +var _core = require('../core'); + +var _resourceLoader = require('resource-loader'); + +var _extras = require('../extras'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function parse(resource, texture) { + var data = {}; + var info = resource.data.getElementsByTagName('info')[0]; + var common = resource.data.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10); + data.chars = {}; + + // parse letters + var letters = resource.data.getElementsByTagName('char'); + + for (var i = 0; i < letters.length; i++) { + var charCode = parseInt(letters[i].getAttribute('id'), 10); + + var textureRect = new _core.Rectangle(parseInt(letters[i].getAttribute('x'), 10) + texture.frame.x, parseInt(letters[i].getAttribute('y'), 10) + texture.frame.y, parseInt(letters[i].getAttribute('width'), 10), parseInt(letters[i].getAttribute('height'), 10)); + + data.chars[charCode] = { + xOffset: parseInt(letters[i].getAttribute('xoffset'), 10), + yOffset: parseInt(letters[i].getAttribute('yoffset'), 10), + xAdvance: parseInt(letters[i].getAttribute('xadvance'), 10), + kerning: {}, + texture: new _core.Texture(texture.baseTexture, textureRect) + + }; + } + + // parse kernings + var kernings = resource.data.getElementsByTagName('kerning'); + + for (var _i = 0; _i < kernings.length; _i++) { + var first = parseInt(kernings[_i].getAttribute('first'), 10); + var second = parseInt(kernings[_i].getAttribute('second'), 10); + var amount = parseInt(kernings[_i].getAttribute('amount'), 10); + + if (data.chars[second]) { + data.chars[second].kerning[first] = amount; + } + } + + resource.bitmapFont = data; + + // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 + // but it's very likely to change + _extras.BitmapText.fonts[data.font] = data; +} + +},{"../core":97,"../extras":165,"path":44,"resource-loader":69}],185:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _loader = require('./loader'); + +Object.defineProperty(exports, 'Loader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_loader).default; + } +}); + +var _bitmapFontParser = require('./bitmapFontParser'); + +Object.defineProperty(exports, 'bitmapFontParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_bitmapFontParser).default; + } +}); +Object.defineProperty(exports, 'parseBitmapFontData', { + enumerable: true, + get: function get() { + return _bitmapFontParser.parse; + } +}); + +var _spritesheetParser = require('./spritesheetParser'); + +Object.defineProperty(exports, 'spritesheetParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_spritesheetParser).default; + } +}); + +var _textureParser = require('./textureParser'); + +Object.defineProperty(exports, 'textureParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_textureParser).default; + } +}); + +var _resourceLoader = require('resource-loader'); + +Object.defineProperty(exports, 'Resource', { + enumerable: true, + get: function get() { + return _resourceLoader.Resource; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./bitmapFontParser":184,"./loader":186,"./spritesheetParser":187,"./textureParser":188,"resource-loader":69}],186:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _resourceLoader = require('resource-loader'); + +var _resourceLoader2 = _interopRequireDefault(_resourceLoader); + +var _textureParser = require('./textureParser'); + +var _textureParser2 = _interopRequireDefault(_textureParser); + +var _spritesheetParser = require('./spritesheetParser'); + +var _spritesheetParser2 = _interopRequireDefault(_spritesheetParser); + +var _bitmapFontParser = require('./bitmapFontParser'); + +var _bitmapFontParser2 = _interopRequireDefault(_bitmapFontParser); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * The new loader, extends Resource Loader by Chad Engler : https://github.com/englercj/resource-loader + * + * ```js + * let loader = PIXI.loader; // pixi exposes a premade instance for you to use. + * //or + * let loader = new PIXI.loaders.Loader(); // you can also create your own if you want + * + * loader.add('bunny',"data/bunny.png"); + * + * loader.once('complete',onAssetsLoaded); + * + * loader.load(); + * ``` + * + * @see https://github.com/englercj/resource-loader + * + * @class + * @extends module:resource-loader.ResourceLoader + * @memberof PIXI.loaders + */ +var Loader = function (_ResourceLoader) { + _inherits(Loader, _ResourceLoader); + + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + _classCallCheck(this, Loader); + + var _this = _possibleConstructorReturn(this, _ResourceLoader.call(this, baseUrl, concurrency)); + + for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { + _this.use(Loader._pixiMiddleware[i]()); + } + return _this; + } + + /** + * Adds a default middleware to the pixi loader. + * + * @static + * @param {Function} fn - The middleware to add. + */ + + + Loader.addPixiMiddleware = function addPixiMiddleware(fn) { + Loader._pixiMiddleware.push(fn); + }; + + return Loader; +}(_resourceLoader2.default); + +exports.default = Loader; + + +Loader._pixiMiddleware = [ +// parse any blob into more usable objects (e.g. Image) +_resourceLoader2.default.middleware.parsing.blob, +// parse any Image objects into textures +_textureParser2.default, +// parse any spritesheet data into multiple textures +_spritesheetParser2.default, +// parse bitmap font data into multiple textures +_bitmapFontParser2.default]; + +// Add custom extentions +var Resource = _resourceLoader2.default.Resource; + +Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); + +},{"./bitmapFontParser":184,"./spritesheetParser":187,"./textureParser":188,"resource-loader":69}],187:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function spritesheetParser(resource, next) { + var resourcePath = void 0; + var imageResourceName = resource.name + '_image'; + + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data || !resource.isJson || !resource.data.frames || this.resources[imageResourceName]) { + next(); + + return; + } + + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata + }; + + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + resourcePath = resource.data.meta.image; + } else { + resourcePath = _path2.default.dirname(resource.url.replace(this.baseUrl, '')) + '/' + resource.data.meta.image; + } + + // load the image for this sheet + this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + resource.textures = {}; + + var frames = resource.data.frames; + var frameKeys = Object.keys(frames); + var resolution = core.utils.getResolutionOfUrl(resource.url); + var batchIndex = 0; + + function processFrames(initialFrameIndex, maxFrames) { + var frameIndex = initialFrameIndex; + + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < frameKeys.length) { + var i = frameKeys[frameIndex]; + var rect = frames[i].frame; + + if (rect) { + var frame = null; + var trim = null; + var orig = new core.Rectangle(0, 0, frames[i].sourceSize.w / resolution, frames[i].sourceSize.h / resolution); + + if (frames[i].rotated) { + frame = new core.Rectangle(rect.x / resolution, rect.y / resolution, rect.h / resolution, rect.w / resolution); + } else { + frame = new core.Rectangle(rect.x / resolution, rect.y / resolution, rect.w / resolution, rect.h / resolution); + } + + // Check to see if the sprite is trimmed + if (frames[i].trimmed) { + trim = new core.Rectangle(frames[i].spriteSourceSize.x / resolution, frames[i].spriteSourceSize.y / resolution, frames[i].spriteSourceSize.w / resolution, frames[i].spriteSourceSize.h / resolution); + } + + resource.textures[i] = new core.Texture(res.texture.baseTexture, frame, orig, trim, frames[i].rotated ? 2 : 0); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage functions + core.utils.TextureCache[i] = resource.textures[i]; + } + + frameIndex++; + } + } + + function shouldProcessNextBatch() { + return batchIndex * BATCH_SIZE < frameKeys.length; + } + + function processNextBatch(done) { + processFrames(batchIndex * BATCH_SIZE, BATCH_SIZE); + batchIndex++; + setTimeout(done, 0); + } + + function iteration() { + processNextBatch(function () { + if (shouldProcessNextBatch()) { + iteration(); + } else { + next(); + } + }); + } + + if (frameKeys.length <= BATCH_SIZE) { + processFrames(0, BATCH_SIZE); + next(); + } else { + iteration(); + } + }); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _path = require('path'); + +var _path2 = _interopRequireDefault(_path); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var BATCH_SIZE = 1000; + +},{"../core":97,"path":44,"resource-loader":69}],188:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function textureParser(resource, next) { + // create a new texture if the data is an Image object + if (resource.data && resource.isImage) { + var baseTexture = new core.BaseTexture(resource.data, null, core.utils.getResolutionOfUrl(resource.url)); + + baseTexture.imageUrl = resource.url; + resource.texture = new core.Texture(baseTexture); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions + core.utils.BaseTextureCache[resource.url] = baseTexture; + core.utils.TextureCache[resource.url] = resource.texture; + } + + next(); + }; +}; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +},{"../core":97}],189:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _MeshShader = require('./webgl/MeshShader'); + +var _MeshShader2 = _interopRequireDefault(_MeshShader); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); +var tempPolygon = new core.Polygon(); + +/** + * Base mesh class + * @class + * @extends PIXI.Container + * @memberof PIXI.mesh + */ + +var Mesh = function (_core$Container) { + _inherits(Mesh, _core$Container); + + /** + * @param {PIXI.Texture} texture - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts + */ + function Mesh(texture, vertices, uvs, indices, drawMode) { + _classCallCheck(this, Mesh); + + /** + * The texture of the Mesh + * + * @member {PIXI.Texture} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._texture = null; + + /** + * The Uvs of the Mesh + * + * @member {Float32Array} + */ + _this.uvs = uvs || new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + /** + * An array of vertices + * + * @member {Float32Array} + */ + _this.vertices = vertices || new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]); + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + // TODO auto generate this based on draw mode! + _this.indices = indices || new Uint16Array([0, 1, 3, 2]); + + /** + * Whether the Mesh is dirty or not + * + * @member {number} + */ + _this.dirty = 0; + _this.indexDirty = 0; + + /** + * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove + * any blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles + * to overlap a bit with each other. + * + * @member {number} + */ + _this.canvasPadding = 0; + + /** + * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts + * + * @member {number} + * @see PIXI.mesh.Mesh.DRAW_MODES + */ + _this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH; + + // run texture setter; + _this.texture = texture; + + /** + * The default shader that is used if a mesh doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + _this.shader = null; + + /** + * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any + * tint effect. + * + * @member {number} + * @memberof PIXI.mesh.Mesh# + */ + _this.tintRgb = new Float32Array([1, 1, 1]); + + _this._glDatas = []; + return _this; + } + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - a reference to the WebGL renderer + */ + + + Mesh.prototype._renderWebGL = function _renderWebGL(renderer) { + // get rid of any thing that may be batching. + renderer.flush(); + + // renderer.plugins.mesh.render(this); + var gl = renderer.gl; + var glData = this._glDatas[renderer.CONTEXT_UID]; + + if (!glData) { + glData = { + shader: new _MeshShader2.default(gl), + vertexBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.vertices, gl.STREAM_DRAW), + uvBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.uvs, gl.STREAM_DRAW), + indexBuffer: _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW), + // build the vao object that will render.. + vao: new _pixiGlCore2.default.VertexArrayObject(gl), + dirty: this.dirty, + indexDirty: this.indexDirty + }; + + // build the vao object that will render.. + glData.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(glData.indexBuffer).addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0).addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); + + this._glDatas[renderer.CONTEXT_UID] = glData; + } + + if (this.dirty !== glData.dirty) { + glData.dirty = this.dirty; + glData.uvBuffer.upload(); + } + + if (this.indexDirty !== glData.indexDirty) { + glData.indexDirty = this.indexDirty; + glData.indexBuffer.upload(); + } + + glData.vertexBuffer.upload(); + + renderer.bindShader(glData.shader); + renderer.bindTexture(this._texture, 0); + renderer.state.setBlendMode(this.blendMode); + + glData.shader.uniforms.translationMatrix = this.worldTransform.toArray(true); + glData.shader.uniforms.alpha = this.worldAlpha; + glData.shader.uniforms.tint = this.tintRgb; + + var drawMode = this.drawMode === Mesh.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + glData.vao.bind().draw(drawMode, this.indices.length).unbind(); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + + + Mesh.prototype._renderCanvas = function _renderCanvas(renderer) { + var context = renderer.context; + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + if (this.drawMode === Mesh.DRAW_MODES.TRIANGLE_MESH) { + this._renderCanvasTriangleMesh(context); + } else { + this._renderCanvasTriangles(context); + } + }; + + /** + * Draws the object in Triangle Mesh mode using canvas + * + * @private + * @param {CanvasRenderingContext2D} context - The current drawing context + */ + + + Mesh.prototype._renderCanvasTriangleMesh = function _renderCanvasTriangleMesh(context) { + // draw triangles!! + var vertices = this.vertices; + var uvs = this.uvs; + var length = vertices.length / 2; + + // this.count++; + + for (var i = 0; i < length - 2; i++) { + // draw some triangles! + var index = i * 2; + + this._renderCanvasDrawTriangle(context, vertices, uvs, index, index + 2, index + 4); + } + }; + + /** + * Draws the object in triangle mode using canvas + * + * @private + * @param {CanvasRenderingContext2D} context - the current drawing context + */ + + + Mesh.prototype._renderCanvasTriangles = function _renderCanvasTriangles(context) { + // draw triangles!! + var vertices = this.vertices; + var uvs = this.uvs; + var indices = this.indices; + var length = indices.length; + // this.count++; + + for (var i = 0; i < length; i += 3) { + // draw some triangles! + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); + } + }; + + /** + * Draws one of the triangles that form this Mesh + * + * @private + * @param {CanvasRenderingContext2D} context - the current drawing context + * @param {Float32Array} vertices - a reference to the vertices of the Mesh + * @param {Float32Array} uvs - a reference to the uvs of the Mesh + * @param {number} index0 - the index of the first vertex + * @param {number} index1 - the index of the second vertex + * @param {number} index2 - the index of the third vertex + */ + + + Mesh.prototype._renderCanvasDrawTriangle = function _renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2) { + var base = this._texture.baseTexture; + var textureSource = base.source; + var textureWidth = base.width; + var textureHeight = base.height; + + var u0 = uvs[index0] * base.width; + var u1 = uvs[index1] * base.width; + var u2 = uvs[index2] * base.width; + var v0 = uvs[index0 + 1] * base.height; + var v1 = uvs[index1 + 1] * base.height; + var v2 = uvs[index2 + 1] * base.height; + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + if (this.canvasPadding > 0) { + var paddingX = this.canvasPadding / this.worldTransform.a; + var paddingY = this.canvasPadding / this.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt(normX * normX + normY * normY); + + x0 = centerX + normX / dist * (dist + paddingX); + y0 = centerY + normY / dist * (dist + paddingY); + + // + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x1 = centerX + normX / dist * (dist + paddingX); + y1 = centerY + normY / dist * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x2 = centerX + normX / dist * (dist + paddingX); + y2 = centerY + normY / dist * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2; + var deltaA = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2; + var deltaB = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2; + var deltaC = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2; + var deltaD = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2; + var deltaE = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2; + var deltaF = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2; + + context.transform(deltaA / delta, deltaD / delta, deltaB / delta, deltaE / delta, deltaC / delta, deltaF / delta); + + context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + + context.restore(); + }; + + /** + * Renders a flat Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - The Mesh to render + */ + + + Mesh.prototype.renderMeshFlat = function renderMeshFlat(mesh) { + var context = this.context; + var vertices = mesh.vertices; + var length = vertices.length / 2; + + // this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; ++i) { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var y0 = vertices[index + 1]; + + var x1 = vertices[index + 2]; + var y1 = vertices[index + 3]; + + var x2 = vertices[index + 4]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + }; + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Mesh.prototype._onTextureUpdate = function _onTextureUpdate() {} + /* empty */ + + + /** + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + */ + ; + + Mesh.prototype._calculateBounds = function _calculateBounds() { + // TODO - we can cache local bounds and use them if they are dirty (like graphics) + this._bounds.addVertices(this.transform, this.vertices, 0, this.vertices.length); + }; + + /** + * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Mesh.prototype.containsPoint = function containsPoint(point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + + this.worldTransform.applyInverse(point, tempPoint); + + var vertices = this.vertices; + var points = tempPolygon.points; + var indices = this.indices; + var len = this.indices.length; + var step = this.drawMode === Mesh.DRAW_MODES.TRIANGLES ? 3 : 1; + + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + + return false; + }; + + /** + * The texture that the mesh uses. + * + * @member {PIXI.Texture} + * @memberof PIXI.mesh.Mesh# + */ + + + _createClass(Mesh, [{ + key: 'texture', + get: function get() { + return this._texture; + } + + /** + * Sets the texture the mesh uses. + * + * @param {Texture} value - The value to set. + */ + , + set: function set(value) { + if (this._texture === value) { + return; + } + + this._texture = value; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + + /** + * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @memberof PIXI.mesh.Mesh# + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return core.utils.rgb2hex(this.tintRgb); + } + + /** + * Sets the tint the mesh uses. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this.tintRgb = core.utils.hex2rgb(value, this.tintRgb); + } + }]); + + return Mesh; +}(core.Container); + +/** + * Different drawing buffer modes supported + * + * @static + * @constant + * @type {object} + * @property {number} TRIANGLE_MESH + * @property {number} TRIANGLES + */ + + +exports.default = Mesh; +Mesh.DRAW_MODES = { + TRIANGLE_MESH: 0, + TRIANGLES: 1 +}; + +},{"../core":97,"./webgl/MeshShader":194,"pixi-gl-core":51}],190:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Plane2 = require('./Plane'); + +var _Plane3 = _interopRequireDefault(_Plane2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DEFAULT_BORDER_SIZE = 10; + +/** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.fromImage('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
+ *      A                          B
+ *    +---+----------------------+---+
+ *  C | 1 |          2           | 3 |
+ *    +---+----------------------+---+
+ *    |   |                      |   |
+ *    | 4 |          5           | 6 |
+ *    |   |                      |   |
+ *    +---+----------------------+---+
+ *  D | 7 |          8           | 9 |
+ *    +---+----------------------+---+
+
+ *  When changing this objects width and/or height:
+ *     areas 1 3 7 and 9 will remain unscaled.
+ *     areas 2 and 8 will be stretched horizontally
+ *     areas 4 and 6 will be stretched vertically
+ *     area 5 will be stretched both horizontally and vertically
+ * 
+ * + * @class + * @extends PIXI.mesh.Plane + * @memberof PIXI.mesh + * + */ + +var NineSlicePlane = function (_Plane) { + _inherits(NineSlicePlane, _Plane); + + /** + * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. + * @param {int} [leftWidth=10] size of the left vertical bar (A) + * @param {int} [topHeight=10] size of the top horizontal bar (C) + * @param {int} [rightWidth=10] size of the right vertical bar (B) + * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) + */ + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + _classCallCheck(this, NineSlicePlane); + + var _this = _possibleConstructorReturn(this, _Plane.call(this, texture, 4, 4)); + + var uvs = _this.uvs; + + // right and bottom uv's are always 1 + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + + _this._origWidth = texture.width; + _this._origHeight = texture.height; + _this._uvw = 1 / _this._origWidth; + _this._uvh = 1 / _this._origHeight; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.width = texture.width; + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.height = texture.height; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _this._uvw * leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - _this._uvw * rightWidth; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _this._uvh * topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - _this._uvh * bottomHeight; + + /** + * The width of the left column (a) + * + * @member {number} + */ + _this.leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; + + /** + * The width of the right column (b) + * + * @member {number} + */ + _this.rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; + + /** + * The height of the top row (c) + * + * @member {number} + */ + _this.topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; + + /** + * The height of the bottom row (d) + * + * @member {number} + */ + _this.bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; + return _this; + } + + /** + * Updates the horizontal vertices. + * + */ + + + NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices() { + var vertices = this.vertices; + + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight; + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + }; + + /** + * Updates the vertical vertices. + * + */ + + + NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices() { + var vertices = this.vertices; + + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth; + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with. + */ + + + NineSlicePlane.prototype._renderCanvas = function _renderCanvas(renderer) { + var context = renderer.context; + + context.globalAlpha = this.worldAlpha; + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + var base = this._texture.baseTexture; + var textureSource = base.source; + var w = base.width; + var h = base.height; + + this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11); + this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13); + this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15); + this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19); + this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21); + this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23); + this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27); + this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29); + this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31); + }; + + /** + * Renders one segment of the plane. + * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure + * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used. + * + * @private + * @param {CanvasRenderingContext2D} context - The context to draw with. + * @param {CanvasImageSource} textureSource - The source to draw. + * @param {number} w - width of the texture + * @param {number} h - height of the texture + * @param {number} x1 - x index 1 + * @param {number} y1 - y index 1 + * @param {number} x2 - x index 2 + * @param {number} y2 - y index 2 + */ + + + NineSlicePlane.prototype.drawSegment = function drawSegment(context, textureSource, w, h, x1, y1, x2, y2) { + // otherwise you get weird results when using slices of that are 0 wide or high. + var uvs = this.uvs; + var vertices = this.vertices; + + var sw = (uvs[x2] - uvs[x1]) * w; + var sh = (uvs[y2] - uvs[y1]) * h; + var dw = vertices[x2] - vertices[x1]; + var dh = vertices[y2] - vertices[y1]; + + // make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn. + if (sw < 1) { + sw = 1; + } + + if (sh < 1) { + sh = 1; + } + + // make sure destination is at least 1 pixel wide and high, otherwise you get + // lines when rendering close to original size. + if (dw < 1) { + dw = 1; + } + + if (dh < 1) { + dh = 1; + } + + context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh); + }; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + */ + + + _createClass(NineSlicePlane, [{ + key: 'width', + get: function get() { + return this._width; + } + + /** + * Sets the width. + * + * @param {number} value - the value to set to. + */ + , + set: function set(value) { + this._width = value; + this.updateVerticalVertices(); + } + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + */ + + }, { + key: 'height', + get: function get() { + return this._height; + } + + /** + * Sets the height. + * + * @param {number} value - the value to set to. + */ + , + set: function set(value) { + this._height = value; + this.updateHorizontalVertices(); + } + + /** + * The width of the left column + * + * @member {number} + */ + + }, { + key: 'leftWidth', + get: function get() { + return this._leftWidth; + } + + /** + * Sets the width of the left column. + * + * @param {number} value - the value to set to. + */ + , + set: function set(value) { + this._leftWidth = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = this._uvw * value; + vertices[2] = vertices[10] = vertices[18] = vertices[26] = value; + + this.dirty = true; + } + + /** + * The width of the right column + * + * @member {number} + */ + + }, { + key: 'rightWidth', + get: function get() { + return this._rightWidth; + } + + /** + * Sets the width of the right column. + * + * @param {number} value - the value to set to. + */ + , + set: function set(value) { + this._rightWidth = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - this._uvw * value; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - value; + + this.dirty = true; + } + + /** + * The height of the top row + * + * @member {number} + */ + + }, { + key: 'topHeight', + get: function get() { + return this._topHeight; + } + + /** + * Sets the height of the top row. + * + * @param {number} value - the value to set to. + */ + , + set: function set(value) { + this._topHeight = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[9] = uvs[11] = uvs[13] = uvs[15] = this._uvh * value; + vertices[9] = vertices[11] = vertices[13] = vertices[15] = value; + + this.dirty = true; + } + + /** + * The height of the bottom row + * + * @member {number} + */ + + }, { + key: 'bottomHeight', + get: function get() { + return this._bottomHeight; + } + + /** + * Sets the height of the bottom row. + * + * @param {number} value - the value to set to. + */ + , + set: function set(value) { + this._bottomHeight = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - this._uvh * value; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - value; + + this.dirty = true; + } + }]); + + return NineSlicePlane; +}(_Plane3.default); + +exports.default = NineSlicePlane; + +},{"./Plane":191}],191:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The Plane allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Plane = function (_Mesh) { + _inherits(Plane, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the Plane. + * @param {number} verticesX - The number of vertices in the x-axis + * @param {number} verticesY - The number of vertices in the y-axis + */ + function Plane(texture, verticesX, verticesY) { + _classCallCheck(this, Plane); + + /** + * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this._ready = true; + + _this.verticesX = verticesX || 10; + _this.verticesY = verticesY || 10; + + _this.drawMode = _Mesh3.default.DRAW_MODES.TRIANGLES; + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Plane.prototype.refresh = function refresh() { + var total = this.verticesX * this.verticesY; + var verts = []; + var colors = []; + var uvs = []; + var indices = []; + var texture = this.texture; + + var segmentsX = this.verticesX - 1; + var segmentsY = this.verticesY - 1; + + var sizeX = texture.width / segmentsX; + var sizeY = texture.height / segmentsY; + + for (var i = 0; i < total; i++) { + var x = i % this.verticesX; + var y = i / this.verticesX | 0; + + verts.push(x * sizeX, y * sizeY); + + // this works for rectangular textures. + uvs.push(texture._uvs.x0 + (texture._uvs.x1 - texture._uvs.x0) * (x / (this.verticesX - 1)), texture._uvs.y0 + (texture._uvs.y3 - texture._uvs.y0) * (y / (this.verticesY - 1))); + } + + // cons + + var totalSub = segmentsX * segmentsY; + + for (var _i = 0; _i < totalSub; _i++) { + var xpos = _i % segmentsX; + var ypos = _i / segmentsX | 0; + + var value = ypos * this.verticesX + xpos; + var value2 = ypos * this.verticesX + xpos + 1; + var value3 = (ypos + 1) * this.verticesX + xpos; + var value4 = (ypos + 1) * this.verticesX + xpos + 1; + + indices.push(value, value2, value3); + indices.push(value2, value4, value3); + } + + // console.log(indices) + this.vertices = new Float32Array(verts); + this.uvs = new Float32Array(uvs); + this.colors = new Float32Array(colors); + this.indices = new Uint16Array(indices); + + this.indexDirty = true; + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Plane.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh3.default.prototype._onTextureUpdate.call(this); + + // wait for the Plane ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + return Plane; +}(_Mesh3.default); + +exports.default = Plane; + +},{"./Mesh":189}],192:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The rope allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Rope = function (_Mesh) { + _inherits(Rope, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the rope. + * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. + */ + function Rope(texture, points) { + _classCallCheck(this, Rope); + + /* + * @member {PIXI.Point[]} An array of points that determine the rope + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this.points = points; + + /* + * @member {Float32Array} An array of vertices used to construct this rope. + */ + _this.vertices = new Float32Array(points.length * 4); + + /* + * @member {Float32Array} The WebGL Uvs of the rope. + */ + _this.uvs = new Float32Array(points.length * 4); + + /* + * @member {Float32Array} An array containing the color components + */ + _this.colors = new Float32Array(points.length * 2); + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + _this.indices = new Uint16Array(points.length * 2); + + /** + * Tracker for if the rope is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + _this._ready = true; + + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Rope.prototype.refresh = function refresh() { + var points = this.points; + + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1 || !this._texture._uvs) { + return; + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + var textureUvs = this._texture._uvs; + var offset = new core.Point(textureUvs.x0, textureUvs.y0); + var factor = new core.Point(textureUvs.x2 - textureUvs.x0, textureUvs.y2 - textureUvs.y0); + + uvs[0] = 0 + offset.x; + uvs[1] = 0 + offset.y; + uvs[2] = 0 + offset.x; + uvs[3] = Number(factor.y) + offset.y; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + + for (var i = 1; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + var amount = i / (total - 1); + + uvs[index] = amount * factor.x + offset.x; + uvs[index + 1] = 0 + offset.y; + + uvs[index + 2] = amount * factor.x + offset.x; + uvs[index + 3] = Number(factor.y) + offset.y; + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + + this.dirty = true; + this.indexDirty = true; + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Rope.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh.prototype._onTextureUpdate.call(this); + + // wait for the Rope ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + Rope.prototype.updateTransform = function updateTransform() { + var points = this.points; + + if (points.length < 1) { + return; + } + + var lastPoint = points[0]; + var nextPoint = void 0; + var perpX = 0; + var perpY = 0; + + // this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } else { + nextPoint = point; + } + + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + + var ratio = (1 - i / (total - 1)) * 10; + + if (ratio > 1) { + ratio = 1; + } + + var perpLength = Math.sqrt(perpX * perpX + perpY * perpY); + var num = this._texture.height / 2; // (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; + + perpX /= perpLength; + perpY /= perpLength; + + perpX *= num; + perpY *= num; + + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + + lastPoint = point; + } + + this.containerUpdateTransform(); + }; + + return Rope; +}(_Mesh3.default); + +exports.default = Rope; + +},{"../core":97,"./Mesh":189}],193:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh = require('./Mesh'); + +Object.defineProperty(exports, 'Mesh', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Mesh).default; + } +}); + +var _Plane = require('./Plane'); + +Object.defineProperty(exports, 'Plane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Plane).default; + } +}); + +var _NineSlicePlane = require('./NineSlicePlane'); + +Object.defineProperty(exports, 'NineSlicePlane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NineSlicePlane).default; + } +}); + +var _Rope = require('./Rope'); + +Object.defineProperty(exports, 'Rope', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rope).default; + } +}); + +var _MeshShader = require('./webgl/MeshShader'); + +Object.defineProperty(exports, 'MeshShader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_MeshShader).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./Mesh":189,"./NineSlicePlane":190,"./Plane":191,"./Rope":192,"./webgl/MeshShader":194}],194:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../core/Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI.mesh + */ +var MeshShader = function (_Shader) { + _inherits(MeshShader, _Shader); + + /** + * @param {WebGLRenderingContext} gl - The WebGLRenderingContext. + */ + function MeshShader(gl) { + _classCallCheck(this, MeshShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform mat3 translationMatrix;', 'uniform mat3 projectionMatrix;', 'varying vec2 vTextureCoord;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', // eslint-disable-line max-len + ' vTextureCoord = aTextureCoord;', '}'].join('\n'), ['varying vec2 vTextureCoord;', 'uniform float alpha;', 'uniform vec3 tint;', 'uniform sampler2D uSampler;', 'void main(void){', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vec4(tint * alpha, alpha);', + // ' gl_FragColor = vec4(1.0);', + '}'].join('\n'))); + } + + return MeshShader; +}(_Shader3.default); + +exports.default = MeshShader; + +},{"../../core/Shader":77}],195:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that advanced + * functionality will not work. ParticleContainer implements only the basic object transform (position, scale, rotation). + * Any other functionality like tinting, masking, etc will not work on sprites in this batch. + * + * It's extremely easy to use : + * + * ```js + * let container = new ParticleContainer(); + * + * for (let i = 0; i < 100; ++i) + * { + * let sprite = new PIXI.Sprite.fromImage("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be renderer at the speed of light. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.particles + */ +var ParticleContainer = function (_core$Container) { + _inherits(ParticleContainer, _core$Container); + + /** + * @param {number} [maxSize=15000] - The maximum number of particles that can be renderer by the container. + * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.scale=false] - When true, scale be uploaded and applied. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.alpha=false] - When true, alpha be uploaded and applied. + * @param {number} [batchSize=15000] - Number of particles per batch. + */ + function ParticleContainer() { + var maxSize = arguments.length <= 0 || arguments[0] === undefined ? 1500 : arguments[0]; + var properties = arguments[1]; + var batchSize = arguments.length <= 2 || arguments[2] === undefined ? 16384 : arguments[2]; + + _classCallCheck(this, ParticleContainer); + + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + var maxBatchSize = 16384; + + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + + if (batchSize > maxSize) { + batchSize = maxSize; + } + + /** + * Set properties to be dynamic (true) / static (false) + * + * @member {boolean[]} + * @private + */ + _this._properties = [false, true, false, false, false]; + + /** + * @member {number} + * @private + */ + _this._maxSize = maxSize; + + /** + * @member {number} + * @private + */ + _this._batchSize = batchSize; + + /** + * @member {WebGLBuffer} + * @private + */ + _this._glBuffers = []; + + /** + * @member {number} + * @private + */ + _this._bufferToUpdate = 0; + + /** + * @member {boolean} + * + */ + _this.interactiveChildren = false; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` + * to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Used for canvas renderering. If true then the elements will be positioned at the + * nearest pixel. This provides a nice speed boost. + * + * @member {boolean} + * @default true; + */ + _this.roundPixels = true; + + /** + * The texture used to render the children. + * + * @readonly + * @member {BaseTexture} + */ + _this.baseTexture = null; + + _this.setProperties(properties); + return _this; + } + + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * + * @param {object} properties - The properties to be uploaded + */ + + + ParticleContainer.prototype.setProperties = function setProperties(properties) { + if (properties) { + this._properties[0] = 'scale' in properties ? !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'alpha' in properties ? !!properties.alpha : this._properties[4]; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + ParticleContainer.prototype.updateTransform = function updateTransform() { + // TODO don't need to! + this.displayObjectUpdateTransform(); + // PIXI.Container.prototype.updateTransform.call( this ); + }; + + /** + * Renders the container using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer + */ + + + ParticleContainer.prototype.renderWebGL = function renderWebGL(renderer) { + var _this2 = this; + + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.hasLoaded) { + this.baseTexture.once('update', function () { + return _this2.onChildrenChange(0); + }); + } + } + + renderer.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + + /** + * Set the flag that static data should be updated to true + * + * @private + * @param {number} smallestChildIndex - The smallest child index + */ + + + ParticleContainer.prototype.onChildrenChange = function onChildrenChange(smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + + if (bufferIndex < this._bufferToUpdate) { + this._bufferToUpdate = bufferIndex; + } + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + + + ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var isRotated = true; + + var positionX = 0; + var positionY = 0; + + var finalWidth = 0; + var finalHeight = 0; + + var compositeOperation = renderer.blendModes[this.blendMode]; + + if (compositeOperation !== context.globalCompositeOperation) { + context.globalCompositeOperation = compositeOperation; + } + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i]; + + if (!child.visible) { + continue; + } + + var frame = child.texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) { + // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call + if (isRotated) { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx * renderer.resolution, transform.ty * renderer.resolution); + + isRotated = false; + } + + positionX = child.anchor.x * (-frame.width * child.scale.x) + child.position.x + 0.5; + positionY = child.anchor.y * (-frame.height * child.scale.y) + child.position.y + 0.5; + + finalWidth = frame.width * child.scale.x; + finalHeight = frame.height * child.scale.y; + } else { + if (!isRotated) { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + + if (renderer.roundPixels) { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution | 0, childTransform.ty * renderer.resolution | 0); + } else { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution, childTransform.ty * renderer.resolution); + } + + positionX = child.anchor.x * -frame.width + 0.5; + positionY = child.anchor.y * -frame.height + 0.5; + + finalWidth = frame.width; + finalHeight = frame.height; + } + + var resolution = child.texture.baseTexture.resolution; + + context.drawImage(child.texture.baseTexture.source, frame.x * resolution, frame.y * resolution, frame.width * resolution, frame.height * resolution, positionX * resolution, positionY * resolution, finalWidth * resolution, finalHeight * resolution); + } + }; + + /** + * Destroys the container + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + */ + + + ParticleContainer.prototype.destroy = function destroy(options) { + _core$Container.prototype.destroy.call(this, options); + + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + } + + this._properties = null; + this._buffers = null; + }; + + return ParticleContainer; +}(core.Container); + +exports.default = ParticleContainer; + +},{"../core":97}],196:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ParticleContainer = require('./ParticleContainer'); + +Object.defineProperty(exports, 'ParticleContainer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleContainer).default; + } +}); + +var _ParticleRenderer = require('./webgl/ParticleRenderer'); + +Object.defineProperty(exports, 'ParticleRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleRenderer).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./ParticleContainer":195,"./webgl/ParticleRenderer":198}],197:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + +/** + * The particle buffer manages the static and dynamic buffers for a particle container. + * + * @class + * @private + * @memberof PIXI + */ +var ParticleBuffer = function () { + /** + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(gl, properties, dynamicPropertyFlags, size) { + _classCallCheck(this, ParticleBuffer); + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * Size of a single vertex. + * + * @member {number} + */ + this.vertSize = 2; + + /** + * Size of a single vertex in bytes. + * + * @member {number} + */ + this.vertByteSize = this.vertSize * 4; + + /** + * The number of particles the buffer can hold + * + * @member {number} + */ + this.size = size; + + /** + * A list of the properties that are dynamic. + * + * @member {object[]} + */ + this.dynamicProperties = []; + + /** + * A list of the properties that are static. + * + * @member {object[]} + */ + this.staticProperties = []; + + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attribute: property.attribute, + size: property.size, + uploadFunction: property.uploadFunction, + offset: property.offset + }; + + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } else { + this.staticProperties.push(property); + } + } + + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + + this.initBuffers(); + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + ParticleBuffer.prototype.initBuffers = function initBuffers() { + var gl = this.gl; + var dynamicOffset = 0; + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(this.size); + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + this.dynamicStride = 0; + + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + + this.dynamicData = new Float32Array(this.size * this.dynamicStride * 4); + this.dynamicBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.dynamicData, gl.STREAM_DRAW); + + // static // + var staticOffset = 0; + + this.staticStride = 0; + + for (var _i = 0; _i < this.staticProperties.length; ++_i) { + var _property = this.staticProperties[_i]; + + _property.offset = staticOffset; + staticOffset += _property.size; + this.staticStride += _property.size; + } + + this.staticData = new Float32Array(this.size * this.staticStride * 4); + this.staticBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.staticData, gl.STATIC_DRAW); + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(this.indexBuffer); + + for (var _i2 = 0; _i2 < this.dynamicProperties.length; ++_i2) { + var _property2 = this.dynamicProperties[_i2]; + + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.FLOAT, false, this.dynamicStride * 4, _property2.offset * 4); + } + + for (var _i3 = 0; _i3 < this.staticProperties.length; ++_i3) { + var _property3 = this.staticProperties[_i3]; + + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.FLOAT, false, this.staticStride * 4, _property3.offset * 4); + } + }; + + /** + * Uploads the dynamic properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadDynamic = function uploadDynamic(children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + + property.uploadFunction(children, startIndex, amount, this.dynamicData, this.dynamicStride, property.offset); + } + + this.dynamicBuffer.upload(); + }; + + /** + * Uploads the static properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadStatic = function uploadStatic(children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + + property.uploadFunction(children, startIndex, amount, this.staticData, this.staticStride, property.offset); + } + + this.staticBuffer.upload(); + }; + + /** + * Binds the buffers to the GPU + * + */ + + + ParticleBuffer.prototype.bind = function bind() { + this.vao.bind(); + }; + + /** + * Destroys the ParticleBuffer. + * + */ + + + ParticleBuffer.prototype.destroy = function destroy() { + this.dynamicProperties = null; + this.dynamicData = null; + this.dynamicBuffer.destroy(); + + this.staticProperties = null; + this.staticData = null; + this.staticBuffer.destroy(); + }; + + return ParticleBuffer; +}(); + +exports.default = ParticleBuffer; + +},{"../../core/utils/createIndicesForQuads":150,"pixi-gl-core":51}],198:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _ParticleShader = require('./ParticleShader'); + +var _ParticleShader2 = _interopRequireDefault(_ParticleShader); + +var _ParticleBuffer = require('./ParticleBuffer'); + +var _ParticleBuffer2 = _interopRequireDefault(_ParticleBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + +/** + * + * @class + * @private + * @memberof PIXI + */ +var ParticleRenderer = function (_core$ObjectRenderer) { + _inherits(ParticleRenderer, _core$ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + _classCallCheck(this, ParticleRenderer); + + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; + + /** + * The default shader that is used if a sprite doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + + _this.indexBuffer = null; + + _this.properties = null; + + _this.tempMatrix = new core.Matrix(); + + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * When there is a WebGL context change + * + * @private + */ + + + ParticleRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + + // setup default shader + this.shader = new _ParticleShader2.default(gl); + + this.properties = [ + // verticesData + { + attribute: this.shader.attributes.aVertexPosition, + size: 2, + uploadFunction: this.uploadVertices, + offset: 0 + }, + // positionData + { + attribute: this.shader.attributes.aPositionCoord, + size: 2, + uploadFunction: this.uploadPosition, + offset: 0 + }, + // rotationData + { + attribute: this.shader.attributes.aRotation, + size: 1, + uploadFunction: this.uploadRotation, + offset: 0 + }, + // uvsData + { + attribute: this.shader.attributes.aTextureCoord, + size: 2, + uploadFunction: this.uploadUvs, + offset: 0 + }, + // alphaData + { + attribute: this.shader.attributes.aColor, + size: 1, + uploadFunction: this.uploadAlpha, + offset: 0 + }]; + }; + + /** + * Starts a new particle batch. + * + */ + + + ParticleRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + }; + + /** + * Renders the particle container object. + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + */ + + + ParticleRenderer.prototype.render = function render(container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var totalChildren = children.length; + + if (totalChildren === 0) { + return; + } else if (totalChildren > maxSize) { + totalChildren = maxSize; + } + + var buffers = container._glBuffers[this.renderer.CONTEXT_UID]; + + if (!buffers) { + buffers = container._glBuffers[this.renderer.CONTEXT_UID] = this.generateBuffers(container); + } + + // if the uvs have not updated then no point rendering just yet! + this.renderer.setBlendMode(container.blendMode); + + var gl = this.renderer.gl; + + var m = container.worldTransform.copy(this.tempMatrix); + + m.prepend(this.renderer._activeRenderTarget.projectionMatrix); + + this.shader.uniforms.projectionMatrix = m.toArray(true); + this.shader.uniforms.uAlpha = container.worldAlpha; + + // make sure the texture is bound.. + var baseTexture = children[0]._texture.baseTexture; + + this.renderer.bindTexture(baseTexture); + + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = totalChildren - i; + + if (amount > batchSize) { + amount = batchSize; + } + + var buffer = buffers[j]; + + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + + // we only upload the static content when we have to! + if (container._bufferToUpdate === j) { + buffer.uploadStatic(children, i, amount); + container._bufferToUpdate = j + 1; + } + + // bind the buffer + buffer.vao.bind().draw(gl.TRIANGLES, amount * 6).unbind(); + + // now draw those suckas! + // gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0); + // this.renderer.drawCount++; + } + }; + + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer[]} The buffers + */ + + + ParticleRenderer.prototype.generateBuffers = function generateBuffers(container) { + var gl = this.renderer.gl; + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + for (var i = 0; i < size; i += batchSize) { + buffers.push(new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize)); + } + + return buffers; + }; + + /** + * Uploads the verticies. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their vertices uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadVertices = function uploadVertices(children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - sprite.anchor.x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - sprite.anchor.y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - sprite.anchor.x); + w1 = orig.width * -sprite.anchor.x; + + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + + array[offset + stride * 2] = w0 * sx; + array[offset + stride * 2 + 1] = h0 * sy; + + array[offset + stride * 3] = w1 * sx; + array[offset + stride * 3 + 1] = h0 * sy; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their positions uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadPosition = function uploadPosition(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + + array[offset + stride * 2] = spritePosition.x; + array[offset + stride * 2 + 1] = spritePosition.y; + + array[offset + stride * 3] = spritePosition.x; + array[offset + stride * 3 + 1] = spritePosition.y; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadRotation = function uploadRotation(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + stride * 2] = spriteRotation; + array[offset + stride * 3] = spriteRotation; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadUvs = function uploadUvs(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + + array[offset + stride * 2] = textureUvs.x2; + array[offset + stride * 2 + 1] = textureUvs.y2; + + array[offset + stride * 3] = textureUvs.x3; + array[offset + stride * 3 + 1] = textureUvs.y3; + + offset += stride * 4; + } else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + + array[offset + stride * 2] = 0; + array[offset + stride * 2 + 1] = 0; + + array[offset + stride * 3] = 0; + array[offset + stride * 3 + 1] = 0; + + offset += stride * 4; + } + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadAlpha = function uploadAlpha(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteAlpha = children[startIndex + i].alpha; + + array[offset] = spriteAlpha; + array[offset + stride] = spriteAlpha; + array[offset + stride * 2] = spriteAlpha; + array[offset + stride * 3] = spriteAlpha; + + offset += stride * 4; + } + }; + + /** + * Destroys the ParticleRenderer. + * + */ + + + ParticleRenderer.prototype.destroy = function destroy() { + if (this.renderer.gl) { + this.renderer.gl.deleteBuffer(this.indexBuffer); + } + + _core$ObjectRenderer.prototype.destroy.call(this); + + this.shader.destroy(); + + this.indices = null; + this.tempMatrix = null; + }; + + return ParticleRenderer; +}(core.ObjectRenderer); + +exports.default = ParticleRenderer; + + +core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + +},{"../../core":97,"./ParticleBuffer":197,"./ParticleShader":199}],199:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../core/Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI + */ +var ParticleShader = function (_Shader) { + _inherits(ParticleShader, _Shader); + + /** + * @param {PIXI.Shader} gl - The webgl shader manager this shader works for. + */ + function ParticleShader(gl) { + _classCallCheck(this, ParticleShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'attribute float aColor;', 'attribute vec2 aPositionCoord;', 'attribute vec2 aScale;', 'attribute float aRotation;', 'uniform mat3 projectionMatrix;', 'varying vec2 vTextureCoord;', 'varying float vColor;', 'void main(void){', ' vec2 v = aVertexPosition;', ' v.x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);', ' v.y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);', ' v = v + aPositionCoord;', ' gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = aColor;', '}'].join('\n'), + // hello + ['varying vec2 vTextureCoord;', 'varying float vColor;', 'uniform sampler2D uSampler;', 'uniform float uAlpha;', 'void main(void){', ' vec4 color = texture2D(uSampler, vTextureCoord) * vColor * uAlpha;', ' if (color.a == 0.0) discard;', ' gl_FragColor = color;', '}'].join('\n'))); + } + + return ParticleShader; +}(_Shader3.default); + +exports.default = ParticleShader; + +},{"../../core/Shader":77}],200:[function(require,module,exports){ +"use strict"; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + +if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + + if (x === 0 || isNaN(x)) { + return x; + } + + return x > 0 ? 1 : -1; + }; +} + +},{}],201:[function(require,module,exports){ +'use strict'; + +var _objectAssign = require('object-assign'); + +var _objectAssign2 = _interopRequireDefault(_objectAssign); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +if (!Object.assign) { + Object.assign = _objectAssign2.default; +} // References: +// https://github.com/sindresorhus/object-assign +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + +},{"object-assign":43}],202:[function(require,module,exports){ +'use strict'; + +require('./Object.assign'); + +require('./requestAnimationFrame'); + +require('./Math.sign'); + +if (!window.ArrayBuffer) { + window.ArrayBuffer = Array; +} + +if (!window.Float32Array) { + window.Float32Array = Array; +} + +if (!window.Uint32Array) { + window.Uint32Array = Array; +} + +if (!window.Uint16Array) { + window.Uint16Array = Array; +} + +},{"./Math.sign":200,"./Object.assign":201,"./requestAnimationFrame":203}],203:[function(require,module,exports){ +(function (global){ +'use strict'; + +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + +// Expected to be used with Browserfiy +// Browserify automatically detects the use of `global` and passes the +// correct reference of `global`, `self`, and finally `window` + +var ONE_FRAME_TIME = 16; + +// Date.now +if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; +} + +// performance.now +if (!(global.performance && global.performance.now)) { + (function () { + var startTime = Date.now(); + + if (!global.performance) { + global.performance = {}; + } + + global.performance.now = function () { + return Date.now() - startTime; + }; + })(); +} + +// requestAnimationFrame +var lastTime = Date.now(); +var vendors = ['ms', 'moz', 'webkit', 'o']; + +for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { + var p = vendors[x]; + + global.requestAnimationFrame = global[p + 'RequestAnimationFrame']; + global.cancelAnimationFrame = global[p + 'CancelAnimationFrame'] || global[p + 'CancelRequestAnimationFrame']; +} + +if (!global.requestAnimationFrame) { + global.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + 'is not a function'); + } + + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + + if (delay < 0) { + delay = 0; + } + + lastTime = currentTime; + + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} + +if (!global.cancelAnimationFrame) { + global.cancelAnimationFrame = function (id) { + return clearTimeout(id); + }; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],204:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SharedTicker = core.ticker.shared; + +var CANVAS_START_SIZE = 16; +var DEFAULT_UPLOADS_PER_FRAME = 4; + +/** + * The prepare manager provides functionality to upload content to the GPU + * This cannot be done directly for Canvas like in WebGL, but the effect can be achieved by drawing + * textures to an offline canvas. + * This draw call will force the texture to be moved onto the GPU. + * + * @class + * @memberof PIXI + */ + +var CanvasPrepare = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasPrepare(renderer) { + _classCallCheck(this, CanvasPrepare); + + /** + * Reference to the renderer. + * @type {PIXI.CanvasRenderer} + * @private + */ + this.renderer = renderer; + + /** + * An offline canvas to render textures to + * @type {HTMLCanvasElement} + * @private + */ + this.canvas = document.createElement('canvas'); + this.canvas.width = CANVAS_START_SIZE; + this.canvas.height = CANVAS_START_SIZE; + + /** + * The context to the canvas + * @type {CanvasRenderingContext2D} + * @private + */ + this.ctx = this.canvas.getContext('2d'); + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + // Add textures to upload + this.register(findBaseTextures, uploadBaseTextures); + } + + /** + * Upload all the textures and graphics to the GPU. + * + * @param {Function|PIXI.DisplayObject|PIXI.Container} item - Either + * the container or display object to search for items to upload or + * the callback function, if items have been added using `prepare.add`. + * @param {Function} [done] - Optional callback when all queued uploads have completed + */ + + + CanvasPrepare.prototype.upload = function upload(item, done) { + if (typeof item === 'function') { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) { + this.numLeft = CanvasPrepare.UPLOADS_PER_FRAME; + + if (done) { + this.completes.push(done); + } + + if (!this.ticking) { + this.ticking = true; + SharedTicker.add(this.tick, this); + } + } else if (done) { + done(); + } + }; + + /** + * Handle tick update + * + * @private + */ + + + CanvasPrepare.prototype.tick = function tick() { + // Upload the graphics + while (this.queue.length && this.numLeft > 0) { + var item = this.queue[0]; + var uploaded = false; + + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this, item)) { + this.numLeft--; + this.queue.shift(); + uploaded = true; + break; + } + } + + if (!uploaded) { + this.queue.shift(); + } + } + + // We're finished + if (this.queue.length) { + this.numLeft = CanvasPrepare.UPLOADS_PER_FRAME; + } else { + this.ticking = false; + + SharedTicker.remove(this.tick, this); + + var completes = this.completes.slice(0); + + this.completes.length = 0; + + for (var _i = 0, _len = completes.length; _i < _len; _i++) { + completes[_i](); + } + } + }; + + /** + * Adds hooks for finding and uploading items. + * + * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array` + function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + CanvasPrepare.prototype.register = function register(addHook, uploadHook) { + if (addHook) { + this.addHooks.push(addHook); + } + + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + + return this; + }; + + /** + * Manually add an item to the uploading queue. + * + * @param {PIXI.DisplayObject|PIXI.Container|*} item - Object to add to the queue + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + CanvasPrepare.prototype.add = function add(item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) { + for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { + this.add(item.children[_i2]); + } + } + + return this; + }; + + /** + * Destroys the plugin, don't use after this. + * + */ + + + CanvasPrepare.prototype.destroy = function destroy() { + if (this.ticking) { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.ctx = null; + this.canvas = null; + }; + + return CanvasPrepare; +}(); + +/** + * The number of graphics or textures to upload to the GPU. + * + * @static + * @type {number} + * @default 4 + */ + + +exports.default = CanvasPrepare; +CanvasPrepare.UPLOADS_PER_FRAME = DEFAULT_UPLOADS_PER_FRAME; + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {*} prepare - Instance of CanvasPrepare + * @param {*} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadBaseTextures(prepare, item) { + if (item instanceof core.BaseTexture) { + var image = item.source; + + // Sometimes images (like atlas images) report a size of zero, causing errors on windows phone. + // So if the width or height is equal to zero then use the canvas size + // Otherwise use whatever is smaller, the image dimensions or the canvas dimensions. + var imageWidth = image.width === 0 ? prepare.canvas.width : Math.min(prepare.canvas.width, image.width); + var imageHeight = image.height === 0 ? prepare.canvas.height : Math.min(prepare.canvas.height, image.height); + + // Only a small subsections is required to be drawn to have the whole texture uploaded to the GPU + // A smaller draw can be faster. + prepare.ctx.drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, prepare.canvas.width, prepare.canvas.height); + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item -Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTextures(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } else if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); + +},{"../../core":97}],205:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLPrepare = require('./webgl/WebGLPrepare'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLPrepare).default; + } +}); + +var _CanvasPrepare = require('./canvas/CanvasPrepare'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasPrepare).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./canvas/CanvasPrepare":204,"./webgl/WebGLPrepare":206}],206:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SharedTicker = core.ticker.shared; +var DEFAULT_UPLOADS_PER_FRAME = 4; + +/** + * The prepare manager provides functionality to upload content to the GPU. + * + * @class + * @memberof PIXI + */ + +var WebGLPrepare = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLPrepare(renderer) { + _classCallCheck(this, WebGLPrepare); + + /** + * Reference to the renderer. + * @type {PIXI.WebGLRenderer} + * @private + */ + this.renderer = renderer; + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + // Add textures and graphics to upload + this.register(findBaseTextures, uploadBaseTextures).register(findGraphics, uploadGraphics); + } + + /** + * Upload all the textures and graphics to the GPU. + * + * @param {Function|PIXI.DisplayObject|PIXI.Container} item - Either + * the container or display object to search for items to upload or + * the callback function, if items have been added using `prepare.add`. + * @param {Function} [done] - Optional callback when all queued uploads have completed + */ + + + WebGLPrepare.prototype.upload = function upload(item, done) { + if (typeof item === 'function') { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) { + this.numLeft = WebGLPrepare.UPLOADS_PER_FRAME; + + if (done) { + this.completes.push(done); + } + + if (!this.ticking) { + this.ticking = true; + SharedTicker.add(this.tick, this); + } + } else if (done) { + done(); + } + }; + + /** + * Handle tick update. + * + * @private + */ + + + WebGLPrepare.prototype.tick = function tick() { + // Upload the graphics + while (this.queue.length && this.numLeft > 0) { + var item = this.queue[0]; + var uploaded = false; + + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.renderer, item)) { + this.numLeft--; + this.queue.shift(); + uploaded = true; + break; + } + } + + if (!uploaded) { + this.queue.shift(); + } + } + + // We're finished + if (this.queue.length) { + this.numLeft = WebGLPrepare.UPLOADS_PER_FRAME; + } else { + this.ticking = false; + + SharedTicker.remove(this.tick, this); + + var completes = this.completes.slice(0); + + this.completes.length = 0; + + for (var _i = 0, _len = completes.length; _i < _len; _i++) { + completes[_i](); + } + } + }; + + /** + * Adds hooks for finding and uploading items. + * + * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array` + function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] - Function call that takes two parameters: `renderer:WebGLRenderer, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.WebGLPrepare} Instance of plugin for chaining. + */ + + + WebGLPrepare.prototype.register = function register(addHook, uploadHook) { + if (addHook) { + this.addHooks.push(addHook); + } + + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + + return this; + }; + + /** + * Manually add an item to the uploading queue. + * + * @param {PIXI.DisplayObject|PIXI.Container|*} item - Object to add to the queue + * @return {PIXI.WebGLPrepare} Instance of plugin for chaining. + */ + + + WebGLPrepare.prototype.add = function add(item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) { + for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { + this.add(item.children[_i2]); + } + } + + return this; + }; + + /** + * Destroys the plugin, don't use after this. + * + */ + + + WebGLPrepare.prototype.destroy = function destroy() { + if (this.ticking) { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + }; + + return WebGLPrepare; +}(); + +/** + * The number of graphics or textures to upload to the GPU + * + * @static + * @type {number} + * @default 4 + */ + + +exports.default = WebGLPrepare; +WebGLPrepare.UPLOADS_PER_FRAME = DEFAULT_UPLOADS_PER_FRAME; + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadBaseTextures(renderer, item) { + if (item instanceof core.BaseTexture) { + renderer.textureManager.updateTexture(item); + + return true; + } + + return false; +} + +/** + * Built-in hook to upload PIXI.Graphics to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadGraphics(renderer, item) { + if (item instanceof core.Graphics) { + renderer.plugins.graphics.updateGraphics(item); + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTextures(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } else if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find graphics. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Graphics object was found. + */ +function findGraphics(item, queue) { + if (item instanceof core.Graphics) { + queue.push(item); + + return true; + } + + return false; +} + +core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); + +},{"../../core":97}],207:[function(require,module,exports){ +(function (global){ +'use strict'; + +exports.__esModule = true; +exports.loader = exports.prepare = exports.particles = exports.mesh = exports.loaders = exports.interaction = exports.filters = exports.extras = exports.extract = exports.accessibility = undefined; + +var _core = require('./core'); + +Object.keys(_core).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _core[key]; + } + }); +}); + +require('./polyfill'); + +var _accessibility = require('./accessibility'); + +var accessibility = _interopRequireWildcard(_accessibility); + +var _extract = require('./extract'); + +var extract = _interopRequireWildcard(_extract); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +require('./deprecation'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// export lib +exports.accessibility = accessibility; +exports.extract = extract; +exports.extras = extras; +exports.filters = filters; +exports.interaction = interaction; +exports.loaders = loaders; +exports.mesh = mesh; +exports.particles = particles; +exports.prepare = prepare; + +// Mixin the deprecations +// import polyfills first + +/** + * A premade instance of the loader that can be used to loader resources. + * + * @name loader + * @memberof PIXI + * @property {PIXI.loaders.Loader} + */ +var loader = new loaders.Loader(); + +exports.loader = loader; + +// Always export pixi globally. + +global.PIXI = exports; // eslint-disable-line + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"./accessibility":76,"./core":97,"./deprecation":155,"./extract":157,"./extras":165,"./filters":176,"./interaction":182,"./loaders":185,"./mesh":193,"./particles":196,"./polyfill":202,"./prepare":205}]},{},[207])(207) +}); + + +//# sourceMappingURL=pixi.js.map diff --git a/js/pixi/4.0.3-tiling/pixi.min.js b/js/pixi/4.0.3-tiling/pixi.min.js new file mode 100644 index 0000000..39221a2 --- /dev/null +++ b/js/pixi/4.0.3-tiling/pixi.min.js @@ -0,0 +1,36400 @@ +/*! + * pixi.js - v4.0.3 + * Compiled Mon Oct 03 2016 02:32:45 GMT+0300 (RTZ 2 (зима)) + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.PIXI = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],15:[function(require,module,exports){ +'use strict'; + +module.exports = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, size), + maxZ = zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, size); + earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and size of the data bounding box +function zOrder(x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; + +},{}],16:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty; + +// +// We store our EE objects in a plain object whose properties are event names. +// If `Object.create(null)` is not supported we prefix the event names with a +// `~` to make sure that the built-in object properties are not overridden or +// used as an attack vector. +// We also assume that `Object.create(null)` is available when the event name +// is an ES6 Symbol. +// +var prefix = typeof Object.create !== 'function' ? '~' : false; + +/** + * Representation of a single EventEmitter function. + * + * @param {Function} fn Event handler to be called. + * @param {Mixed} context Context for function execution. + * @param {Boolean} [once=false] Only emit once + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal EventEmitter interface that is molded against the Node.js + * EventEmitter interface. + * + * @constructor + * @api public + */ +function EventEmitter() { /* Nothing to set */ } + +/** + * Hold the assigned EventEmitters by name. + * + * @type {Object} + * @private + */ +EventEmitter.prototype._events = undefined; + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @api public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var events = this._events + , names = [] + , name; + + if (!events) return names; + + for (name in events) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return a list of assigned event listeners. + * + * @param {String} event The events that should be listed. + * @param {Boolean} exists We only need to know if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events && this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Emit an event to all registered event listeners. + * + * @param {String} event The name of the event. + * @returns {Boolean} Indication if we've emitted an event. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events || !this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if ('function' === typeof listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Register a new EventListener for the given event. + * + * @param {String} event Name of the event. + * @param {Function} fn Callback function. + * @param {Mixed} [context=this] The context of the function. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events) this._events = prefix ? {} : Object.create(null); + if (!this._events[evt]) this._events[evt] = listener; + else { + if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [ + this._events[evt], listener + ]; + } + + return this; +}; + +/** + * Add an EventListener that's only called once. + * + * @param {String} event Name of the event. + * @param {Function} fn Callback function. + * @param {Mixed} [context=this] The context of the function. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events) this._events = prefix ? {} : Object.create(null); + if (!this._events[evt]) this._events[evt] = listener; + else { + if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [ + this._events[evt], listener + ]; + } + + return this; +}; + +/** + * Remove event listeners. + * + * @param {String} event The event we want to remove. + * @param {Function} fn The listener that we need to find. + * @param {Mixed} context Only remove listeners matching this context. + * @param {Boolean} once Only remove once listeners. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events || !this._events[evt]) return this; + + var listeners = this._events[evt] + , events = []; + + if (fn) { + if (listeners.fn) { + if ( + listeners.fn !== fn + || (once && !listeners.once) + || (context && listeners.context !== context) + ) { + events.push(listeners); + } + } else { + for (var i = 0, length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) { + this._events[evt] = events.length === 1 ? events[0] : events; + } else { + delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners or only the listeners for the specified event. + * + * @param {String} event The event want to remove all listeners for. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + if (!this._events) return this; + + if (event) delete this._events[prefix ? prefix + event : event]; + else this._events = prefix ? {} : Object.create(null); + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],17:[function(require,module,exports){ +/** + * isMobile.js v0.4.0 + * + * A simple library to detect Apple phones and tablets, + * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone), + * and any kind of seven inch device, via user agent sniffing. + * + * @author: Kai Mallea (kmallea@gmail.com) + * + * @license: http://creativecommons.org/publicdomain/zero/1.0/ + */ +(function (global) { + + var apple_phone = /iPhone/i, + apple_ipod = /iPod/i, + apple_tablet = /iPad/i, + android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i, // Match 'Android' AND 'Mobile' + android_tablet = /Android/i, + amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i, + amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i, + windows_phone = /IEMobile/i, + windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i, // Match 'Windows' AND 'ARM' + other_blackberry = /BlackBerry/i, + other_blackberry_10 = /BB10/i, + other_opera = /Opera Mini/i, + other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i, + other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i, // Match 'Firefox' AND 'Mobile' + seven_inch = new RegExp( + '(?:' + // Non-capturing group + + 'Nexus 7' + // Nexus 7 + + '|' + // OR + + 'BNTV250' + // B&N Nook Tablet 7 inch + + '|' + // OR + + 'Kindle Fire' + // Kindle Fire + + '|' + // OR + + 'Silk' + // Kindle Fire, Silk Accelerated + + '|' + // OR + + 'GT-P1000' + // Galaxy Tab 7 inch + + ')', // End non-capturing group + + 'i'); // Case-insensitive matching + + var match = function(regex, userAgent) { + return regex.test(userAgent); + }; + + var IsMobileClass = function(userAgent) { + var ua = userAgent || navigator.userAgent; + + // Facebook mobile app's integrated browser adds a bunch of strings that + // match everything. Strip it out if it exists. + var tmp = ua.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + // Twitter mobile app's integrated browser on iPad adds a "Twitter for + // iPhone" string. Same probable happens on other tablet platforms. + // This will confuse detection so strip it out if it exists. + tmp = ua.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + this.apple = { + phone: match(apple_phone, ua), + ipod: match(apple_ipod, ua), + tablet: !match(apple_phone, ua) && match(apple_tablet, ua), + device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua) + }; + this.amazon = { + phone: match(amazon_phone, ua), + tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) + }; + this.android = { + phone: match(amazon_phone, ua) || match(android_phone, ua), + tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua) + }; + this.windows = { + phone: match(windows_phone, ua), + tablet: match(windows_tablet, ua), + device: match(windows_phone, ua) || match(windows_tablet, ua) + }; + this.other = { + blackberry: match(other_blackberry, ua), + blackberry10: match(other_blackberry_10, ua), + opera: match(other_opera, ua), + firefox: match(other_firefox, ua), + chrome: match(other_chrome, ua), + device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua) + }; + this.seven_inch = match(seven_inch, ua); + this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch; + + // excludes 'other' devices and ipods, targeting touchscreen phones + this.phone = this.apple.phone || this.android.phone || this.windows.phone; + + // excludes 7 inch devices, classifying as phone or tablet is left to the user + this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet; + + if (typeof window === 'undefined') { + return this; + } + }; + + var instantiate = function() { + var IM = new IsMobileClass(); + IM.Class = IsMobileClass; + return IM; + }; + + if (typeof module !== 'undefined' && module.exports && typeof window === 'undefined') { + //node + module.exports = IsMobileClass; + } else if (typeof module !== 'undefined' && module.exports && typeof window !== 'undefined') { + //browserify + module.exports = instantiate(); + } else if (typeof define === 'function' && define.amd) { + //AMD + define('isMobile', [], global.isMobile = instantiate()); + } else { + global.isMobile = instantiate(); + } + +})(this); + +},{}],18:[function(require,module,exports){ +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} + +module.exports = apply; + +},{}],19:[function(require,module,exports){ +/** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ +function arrayEach(array, iteratee) { + var index = -1, + length = array ? array.length : 0; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; +} + +module.exports = arrayEach; + +},{}],20:[function(require,module,exports){ +var baseTimes = require('./_baseTimes'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isIndex = require('./_isIndex'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; + + var length = result.length, + skipIndexes = !!length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); + } + } + return result; +} + +module.exports = arrayLikeKeys; + +},{"./_baseTimes":23,"./_isIndex":24,"./isArguments":28,"./isArray":29}],21:[function(require,module,exports){ +var isPrototype = require('./_isPrototype'), + nativeKeys = require('./_nativeKeys'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +module.exports = baseKeys; + +},{"./_isPrototype":25,"./_nativeKeys":26}],22:[function(require,module,exports){ +var apply = require('./_apply'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; +} + +module.exports = baseRest; + +},{"./_apply":18}],23:[function(require,module,exports){ +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +module.exports = baseTimes; + +},{}],24:[function(require,module,exports){ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} + +module.exports = isIndex; + +},{}],25:[function(require,module,exports){ +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; +} + +module.exports = isPrototype; + +},{}],26:[function(require,module,exports){ +var overArg = require('./_overArg'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object); + +module.exports = nativeKeys; + +},{"./_overArg":27}],27:[function(require,module,exports){ +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +module.exports = overArg; + +},{}],28:[function(require,module,exports){ +var isArrayLikeObject = require('./isArrayLikeObject'); + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} + +module.exports = isArguments; + +},{"./isArrayLikeObject":31}],29:[function(require,module,exports){ +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +module.exports = isArray; + +},{}],30:[function(require,module,exports){ +var isFunction = require('./isFunction'), + isLength = require('./isLength'); + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +module.exports = isArrayLike; + +},{"./isFunction":32,"./isLength":33}],31:[function(require,module,exports){ +var isArrayLike = require('./isArrayLike'), + isObjectLike = require('./isObjectLike'); + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +module.exports = isArrayLikeObject; + +},{"./isArrayLike":30,"./isObjectLike":35}],32:[function(require,module,exports){ +var isObject = require('./isObject'); + +/** `Object#toString` result references. */ +var funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} + +module.exports = isFunction; + +},{"./isObject":34}],33:[function(require,module,exports){ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +module.exports = isLength; + +},{}],34:[function(require,module,exports){ +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +module.exports = isObject; + +},{}],35:[function(require,module,exports){ +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +module.exports = isObjectLike; + +},{}],36:[function(require,module,exports){ +var isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +module.exports = isSymbol; + +},{"./isObjectLike":35}],37:[function(require,module,exports){ +var arrayLikeKeys = require('./_arrayLikeKeys'), + baseKeys = require('./_baseKeys'), + isArrayLike = require('./isArrayLike'); + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +module.exports = keys; + +},{"./_arrayLikeKeys":20,"./_baseKeys":21,"./isArrayLike":30}],38:[function(require,module,exports){ +/** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ +function noop() { + // No operation performed. +} + +module.exports = noop; + +},{}],39:[function(require,module,exports){ +var baseRest = require('./_baseRest'), + toInteger = require('./toInteger'); + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ +function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); +} + +module.exports = rest; + +},{"./_baseRest":22,"./toInteger":41}],40:[function(require,module,exports){ +var toNumber = require('./toNumber'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308; + +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} + +module.exports = toFinite; + +},{"./toNumber":42}],41:[function(require,module,exports){ +var toFinite = require('./toFinite'); + +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; +} + +module.exports = toInteger; + +},{"./toFinite":40}],42:[function(require,module,exports){ +var isObject = require('./isObject'), + isSymbol = require('./isSymbol'); + +/** Used as references for various `Number` constants. */ +var NAN = 0 / 0; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +module.exports = toNumber; + +},{"./isObject":34,"./isSymbol":36}],43:[function(require,module,exports){ +'use strict'; +/* eslint-disable no-unused-vars */ +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (e) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (Object.getOwnPropertySymbols) { + symbols = Object.getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],44:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) + +},{"_process":61}],45:[function(require,module,exports){ +var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); + +/** + * Helper class to create a webGL buffer + * + * @class + * @memberof pixi.gl + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ +var Buffer = function(gl, type, data, drawType) +{ + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The WebGL buffer, created upon instantiation + * + * @member {WebGLBuffer} + */ + this.buffer = gl.createBuffer(); + + /** + * The type of the buffer + * + * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} + */ + this.type = type || gl.ARRAY_BUFFER; + + /** + * The draw type of the buffer + * + * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ + this.drawType = drawType || gl.STATIC_DRAW; + + /** + * The data in the buffer, as a typed array + * + * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} + */ + this.data = EMPTY_ARRAY_BUFFER; + + if(data) + { + this.upload(data); + } +}; + +/** + * Uploads the buffer to the GPU + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload + * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract + * @param dontBind {Boolean} whether to bind the buffer before uploading it + */ +Buffer.prototype.upload = function(data, offset, dontBind) +{ + // todo - needed? + if(!dontBind) this.bind(); + + var gl = this.gl; + + data = data || this.data; + offset = offset || 0; + + if(this.data.byteLength >= data.byteLength) + { + gl.bufferSubData(this.type, offset, data); + } + else + { + gl.bufferData(this.type, data, this.drawType); + } + + this.data = data; +}; +/** + * Binds the buffer + * + */ +Buffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindBuffer(this.type, this.buffer); +}; + +Buffer.createVertexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); +}; + +Buffer.createIndexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); +}; + +Buffer.create = function(gl, type, data, drawType) +{ + return new Buffer(gl, type, drawType); +}; + +/** + * Destroys the buffer + * + */ +Buffer.prototype.destroy = function(){ + this.gl.deleteBuffer(this.buffer); +}; + +module.exports = Buffer; + +},{}],46:[function(require,module,exports){ + +var Texture = require('./GLTexture'); + +/** + * Helper class to create a webGL Framebuffer + * + * @class + * @memberof pixi.gl + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + */ +var Framebuffer = function(gl, width, height) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The frame buffer + * + * @member {WebGLFramebuffer} + */ + this.framebuffer = gl.createFramebuffer(); + + /** + * The stencil buffer + * + * @member {WebGLRenderbuffer} + */ + this.stencil = null; + + /** + * The stencil buffer + * + * @member {GLTexture} + */ + this.texture = null; + + /** + * The width of the drawing area of the buffer + * + * @member {Number} + */ + this.width = width || 100; + /** + * The height of the drawing area of the buffer + * + * @member {Number} + */ + this.height = height || 100; +}; + +/** + * Adds a texture to the frame buffer + * @param texture {GLTexture} + */ +Framebuffer.prototype.enableTexture = function(texture) +{ + var gl = this.gl; + + this.texture = texture || new Texture(gl); + + this.texture.bind(); + + //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + this.bind(); + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); +}; + +/** + * Initialises the stencil buffer + */ +Framebuffer.prototype.enableStencil = function() +{ + if(this.stencil)return; + + var gl = this.gl; + + this.stencil = gl.createRenderbuffer(); + + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + + // TODO.. this is depth AND stencil? + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width , this.height ); +}; + +/** + * Erases the drawing area and fills it with a colour + * @param r {Number} the red value of the clearing colour + * @param g {Number} the green value of the clearing colour + * @param b {Number} the blue value of the clearing colour + * @param a {Number} the alpha value of the clearing colour + */ +Framebuffer.prototype.clear = function( r, g, b, a ) +{ + this.bind(); + + var gl = this.gl; + + gl.clearColor(r, g, b, a); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Binds the frame buffer to the WebGL context + */ +Framebuffer.prototype.bind = function() +{ + var gl = this.gl; + + if(this.texture) + { + this.texture.unbind(); + } + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); +}; + +/** + * Unbinds the frame buffer to the WebGL context + */ +Framebuffer.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, null ); +}; +/** + * Resizes the drawing area of the buffer to the given width and height + * @param width {Number} the new width + * @param height {Number} the new height + */ +Framebuffer.prototype.resize = function(width, height) +{ + var gl = this.gl; + + this.width = width; + this.height = height; + + if ( this.texture ) + { + this.texture.uploadData(null, width, height); + } + + if ( this.stencil ) + { + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + } +}; + +/** + * Destroys this buffer + */ +Framebuffer.prototype.destroy = function() +{ + var gl = this.gl; + + //TODO + if(this.texture) + { + this.texture.destroy(); + } + + gl.deleteFramebuffer(this.framebuffer); + + this.gl = null; + + this.stencil = null; + this.texture = null; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createRGBA = function(gl, width, height/*, data*/) +{ + var texture = Texture.fromData(gl, null, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createFloat32 = function(gl, width, height, data) +{ + // create a new texture.. + var texture = new Texture.fromData(gl, data, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +module.exports = Framebuffer; + +},{"./GLTexture":48}],47:[function(require,module,exports){ + +var compileProgram = require('./shader/compileProgram'), + extractAttributes = require('./shader/extractAttributes'), + extractUniforms = require('./shader/extractUniforms'), + generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + +/** + * Helper class to create a webGL Shader + * + * @class + * @memberof pixi.gl + * @param gl {WebGLRenderingContext} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + */ +var Shader = function(gl, vertexSrc, fragmentSrc) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc); + + + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); + + var uniformData = extractUniforms(gl, this.program); + + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject( gl, uniformData ); +}; +/** + * Uses this shader + */ +Shader.prototype.bind = function() +{ + this.gl.useProgram(this.program); +}; + +/** + * Destroys this shader + * TODO + */ +Shader.prototype.destroy = function() +{ + // var gl = this.gl; +}; + +module.exports = Shader; + +},{"./shader/compileProgram":53,"./shader/extractAttributes":55,"./shader/extractUniforms":56,"./shader/generateUniformAccessObject":57}],48:[function(require,module,exports){ + +/** + * Helper class to create a WebGL Texture + * + * @class + * @memberof pixi.gl + * @param gl {WebGLRenderingContext} The current WebGL context + * @param width {number} the width of the texture + * @param height {number} the height of the texture + * @param format {number} the pixel format of the texture. defaults to gl.RGBA + * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE + */ +var Texture = function(gl, width, height, format, type) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); + + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; + + + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || 0; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || 0; + + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; + + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + + +}; + +/** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ +Texture.prototype.upload = function(source) +{ + this.bind(); + + var gl = this.gl; + + // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. + this.width = source.videoWidth || source.width; + this.height = source.videoHeight || source.height; + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); +}; + +var FLOATING_POINT_AVAILABLE = false; + +/** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.prototype.uploadData = function(data, width, height) +{ + this.bind(); + + var gl = this.gl; + + this.width = width || this.width; + this.height = height || this.height; + + if(data instanceof Float32Array) + { + if(!FLOATING_POINT_AVAILABLE) + { + var ext = gl.getExtension("OES_texture_float"); + + if(ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } + + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = gl.UNSIGNED_BYTE; + } + + + + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.width, this.height, 0, this.format, this.type, data || null); + +}; + +/** + * Binds the texture + * @param location + */ +Texture.prototype.bind = function(location) +{ + var gl = this.gl; + + if(location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } + + gl.bindTexture(gl.TEXTURE_2D, this.texture); +}; + +/** + * Unbinds the texture + */ +Texture.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, null); +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.minFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + if(this.mipmap) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.magFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); +}; + +/** + * Enables mipmapping + */ +Texture.prototype.enableMipmap = function() +{ + var gl = this.gl; + + this.bind(); + + this.mipmap = true; + + gl.generateMipmap(gl.TEXTURE_2D); +}; + +/** + * Enables linear filtering + */ +Texture.prototype.enableLinearScaling = function() +{ + this.minFilter(true); + this.magFilter(true); +}; + +/** + * Enables nearest neighbour interpolation + */ +Texture.prototype.enableNearestScaling = function() +{ + this.minFilter(false); + this.magFilter(false); +}; + +/** + * Enables clamping on the texture so WebGL will not repeat it + */ +Texture.prototype.enableWrapClamp = function() +{ + var gl = this.gl; + + this.bind(); + + 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); +}; + +/** + * Enable tiling on the texture + */ +Texture.prototype.enableWrapRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); +}; + +Texture.prototype.enableWrapMirrorRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); +}; + + +/** + * Destroys this texture + */ +Texture.prototype.destroy = function() +{ + var gl = this.gl; + //TODO + gl.deleteTexture(this.texture); +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ +Texture.fromSource = function(gl, source, premultiplyAlpha) +{ + var texture = new Texture(gl); + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); + + return texture; +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.fromData = function(gl, data, width, height) +{ + //console.log(data, width, height); + var texture = new Texture(gl); + texture.uploadData(data, width, height); + + return texture; +}; + + +module.exports = Texture; + +},{}],49:[function(require,module,exports){ + +// state object// +var setVertexAttribArrays = require( './setVertexAttribArrays' ); + +/** + * Helper class to work with WebGL VertexArrayObjects (vaos) + * Only works if WebGL extensions are enabled (they usually are) + * + * @class + * @memberof pixi.gl + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function VertexArrayObject(gl, state) +{ + this.nativeVaoExtension = null; + + if(!VertexArrayObject.FORCE_NATIVE) + { + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + this.nativeState = state; + + if(this.nativeVaoExtension) + { + this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + + var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + // VAO - overwrite the state.. + this.nativeState = { + tempAttribState: new Array(maxAttribs), + attribState: new Array(maxAttribs) + }; + } + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of attributes + * + * @member {Array} + */ + this.attributes = []; + + /** + * @member {Array} + */ + this.indexBuffer = null; + + /** + * A boolean flag + * + * @member {Boolean} + */ + this.dirty = false; +} + +VertexArrayObject.prototype.constructor = VertexArrayObject; +module.exports = VertexArrayObject; + +/** +* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) +* If you find on older devices that things have gone a bit weird then set this to true. +*/ +/** + * Lets the VAO know if you should use the WebGL extension or the native methods. + * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) + * If you find on older devices that things have gone a bit weird then set this to true. + * @static + * @property {Boolean} FORCE_NATIVE + */ +VertexArrayObject.FORCE_NATIVE = false; + +/** + * Binds the buffer + */ +VertexArrayObject.prototype.bind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + + if(this.dirty) + { + this.dirty = false; + this.activate(); + } + } + else + { + + this.activate(); + } + + return this; +}; + +/** + * Unbinds the buffer + */ +VertexArrayObject.prototype.unbind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + return this; +}; + +/** + * Uses this vao + */ +VertexArrayObject.prototype.activate = function() +{ + + var gl = this.gl; + var lastBuffer = null; + + for (var i = 0; i < this.attributes.length; i++) + { + var attrib = this.attributes[i]; + + if(lastBuffer !== attrib.buffer) + { + attrib.buffer.bind(); + lastBuffer = attrib.buffer; + } + + //attrib.attribute.pointer(attrib.type, attrib.normalized, attrib.stride, attrib.start); + gl.vertexAttribPointer(attrib.attribute.location, + attrib.attribute.size, attrib.type || gl.FLOAT, + attrib.normalized || false, + attrib.stride || 0, + attrib.start || 0); + + + } + + setVertexAttribArrays(gl, this.attributes, this.nativeState); + + this.indexBuffer.bind(); + + return this; +}; + +/** + * + * @param buffer {WebGLBuffer} + * @param attribute {*} + * @param type {String} + * @param normalized {Boolean} + * @param stride {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start) +{ + this.attributes.push({ + buffer: buffer, + attribute: attribute, + + location: attribute.location, + type: type || this.gl.FLOAT, + normalized: normalized || false, + stride: stride || 0, + start: start || 0 + }); + + this.dirty = true; + + return this; +}; + +/** + * + * @param buffer {WebGLBuffer} + * @param options {Object} + */ +VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) +{ + this.indexBuffer = buffer; + + this.dirty = true; + + return this; +}; + +/** + * Unbinds this vao and disables it + */ +VertexArrayObject.prototype.clear = function() +{ + // var gl = this.gl; + + // TODO - should this function unbind after clear? + // for now, no but lets see what happens in the real world! + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + } + + this.attributes.length = 0; + this.indexBuffer = null; + + return this; +}; + +/** + * @param type {Number} + * @param size {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.draw = function(type, size, start) +{ + var gl = this.gl; + gl.drawElements(type, size, gl.UNSIGNED_SHORT, start || 0); + + return this; +}; + +/** + * Destroy this vao + */ +VertexArrayObject.prototype.destroy = function() +{ + // lose references + this.gl = null; + this.indexBuffer = null; + this.attributes = null; + this.nativeState = null; + + if(this.nativeVao) + { + this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); + } + + this.nativeVaoExtension = null; + this.nativeVao = null; +}; + +},{"./setVertexAttribArrays":52}],50:[function(require,module,exports){ + +/** + * Helper class to create a webGL Context + * + * @class + * @memberof pixi.gl + * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from + * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * @return {WebGLRenderingContext} the WebGL context + */ +var createContext = function(canvas, options) +{ + var gl = canvas.getContext('webgl', options) || + canvas.getContext('experimental-webgl', options); + + if (!gl) + { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + return gl; +}; + +module.exports = createContext; + +},{}],51:[function(require,module,exports){ +var gl = { + createContext: require('./createContext'), + setVertexAttribArrays: require('./setVertexAttribArrays'), + GLBuffer: require('./GLBuffer'), + GLFramebuffer: require('./GLFramebuffer'), + GLShader: require('./GLShader'), + GLTexture: require('./GLTexture'), + VertexArrayObject: require('./VertexArrayObject'), + shader: require('./shader') +}; + +// Export for Node-compatible environments +if (typeof module !== 'undefined' && module.exports) +{ + // Export the module + module.exports = gl; +} + +// Add to the browser window pixi.gl +if (typeof window !== 'undefined') +{ + // add the window object + window.pixi = { gl: gl }; +} +},{"./GLBuffer":45,"./GLFramebuffer":46,"./GLShader":47,"./GLTexture":48,"./VertexArrayObject":49,"./createContext":50,"./setVertexAttribArrays":52,"./shader":58}],52:[function(require,module,exports){ +// var GL_MAP = {}; + +/** + * @param gl {WebGLRenderingContext} The current WebGL context + * @param attribs {*} + * @param state {*} + */ +var setVertexAttribArrays = function (gl, attribs, state) +{ + var i; + if(state) + { + var tempAttribState = state.tempAttribState, + attribState = state.attribState; + + for (i = 0; i < tempAttribState.length; i++) + { + tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + tempAttribState[attribs[i].attribute.location] = true; + } + + for (i = 0; i < attribState.length; i++) + { + if (attribState[i] !== tempAttribState[i]) + { + attribState[i] = tempAttribState[i]; + + if (state.attribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } + + } + else + { + for (i = 0; i < attribs.length; i++) + { + var attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); + } + } +}; + +module.exports = setVertexAttribArrays; + +},{}],53:[function(require,module,exports){ + +/** + * @class + * @memberof pixi.gl.shader + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @return {WebGLProgram} the shader program + */ +var compileProgram = function(gl, vertexSrc, fragmentSrc) +{ + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + + var program = gl.createProgram(); + + gl.attachShader(program, glVertShader); + gl.attachShader(program, glFragShader); + gl.linkProgram(program); + + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + console.error('Pixi.js Error: Could not initialize shader.'); + console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); + console.error('gl.getError()', gl.getError()); + + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') + { + console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + + gl.deleteProgram(program); + program = null; + } + + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + + return program; +}; + +/** + * @private + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @return {WebGLShader} the shader + */ +var compileShader = function (gl, type, src) +{ + var shader = gl.createShader(type); + + gl.shaderSource(shader, src); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + console.log(gl.getShaderInfoLog(shader)); + return null; + } + + return shader; +}; + +module.exports = compileProgram; + +},{}],54:[function(require,module,exports){ +/** + * @class + * @memberof pixi.gl.shader + * @param type {String} Type of value + * @param size {Number} + */ +var defaultValue = function(type, size) +{ + switch (type) + { + case 'float': + return 0; + + case 'vec2': + return new Float32Array(2 * size); + + case 'vec3': + return new Float32Array(3 * size); + + case 'vec4': + return new Float32Array(4 * size); + + case 'int': + case 'sampler2D': + return 0; + + case 'ivec2': + return new Int32Array(2 * size); + + case 'ivec3': + return new Int32Array(3 * size); + + case 'ivec4': + return new Int32Array(4 * size); + + case 'bool': + return false; + + case 'bvec2': + + return booleanArray( 2 * size); + + case 'bvec3': + return booleanArray(3 * size); + + case 'bvec4': + return booleanArray(4 * size); + + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } +}; + +var booleanArray = function(size) +{ + var array = new Array(size); + + for (var i = 0; i < array.length; i++) + { + array[i] = false; + } + + return array; +}; + +module.exports = defaultValue; + +},{}],55:[function(require,module,exports){ + +var mapType = require('./mapType'); +var mapSize = require('./mapSize'); + +/** + * Extracts the attributes + * @class + * @memberof pixi.gl.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the attributes from + * @return attributes {Object} + */ +var extractAttributes = function(gl, program) +{ + var attributes = {}; + + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + + for (var i = 0; i < totalAttributes; i++) + { + var attribData = gl.getActiveAttrib(program, i); + var type = mapType(gl, attribData.type); + + attributes[attribData.name] = { + type:type, + size:mapSize(type), + location:gl.getAttribLocation(program, attribData.name), + //TODO - make an attribute object + pointer: pointer + }; + } + + return attributes; +}; + +var pointer = function(type, normalized, stride, start){ + // console.log(this.location) + gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +}; + +module.exports = extractAttributes; + +},{"./mapSize":59,"./mapType":60}],56:[function(require,module,exports){ +var mapType = require('./mapType'); +var defaultValue = require('./defaultValue'); + +/** + * Extracts the uniforms + * @class + * @memberof pixi.gl.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the uniforms from + * @return uniforms {Object} + */ +var extractUniforms = function(gl, program) +{ + var uniforms = {}; + + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + + for (var i = 0; i < totalUniforms; i++) + { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]/, ""); + var type = mapType(gl, uniformData.type ); + + uniforms[name] = { + type:type, + size:uniformData.size, + location:gl.getUniformLocation(program, name), + value:defaultValue(type, uniformData.size) + }; + } + + return uniforms; +}; + +module.exports = extractUniforms; + +},{"./defaultValue":54,"./mapType":60}],57:[function(require,module,exports){ +/** + * Extracts the attributes + * @class + * @memberof pixi.gl.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param uniforms {Array} @mat ? + * @return attributes {Object} + */ +var generateUniformAccessObject = function(gl, uniformData) +{ + // this is the object we will be sending back. + // an object hierachy will be created for structs + var uniforms = {data:{}}; + + uniforms.gl = gl; + + var uniformKeys= Object.keys(uniformData); + + for (var i = 0; i < uniformKeys.length; i++) + { + var fullName = uniformKeys[i]; + + var nameTokens = fullName.split('.'); + var name = nameTokens[nameTokens.length - 1]; + + var uniformGroup = getUniformGroup(nameTokens, uniforms); + + var uniform = uniformData[fullName]; + uniformGroup.data[name] = uniform; + + uniformGroup.gl = gl; + + Object.defineProperty(uniformGroup, name, { + get: generateGetter(name), + set: generateSetter(name, uniform) + }); + } + + return uniforms; +}; + +var generateGetter = function(name) +{ + var template = getterTemplate.replace('%%', name); + return new Function(template); // jshint ignore:line +}; + +var generateSetter = function(name, uniform) +{ + var template = setterTemplate.replace(/%%/g, name); + var setTemplate; + + if(uniform.size === 1) + { + setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; + } + else + { + setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; + } + + if(setTemplate) + { + template += "\nthis.gl." + setTemplate + ";"; + } + + return new Function('value', template); // jshint ignore:line +}; + +var getUniformGroup = function(nameTokens, uniform) +{ + var cur = uniform; + + for (var i = 0; i < nameTokens.length - 1; i++) + { + var o = cur[nameTokens[i]] || {data:{}}; + cur[nameTokens[i]] = o; + cur = o; + } + + return cur; +}; + +var getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +var setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;' +].join('\n'); + + +var GLSL_TO_SINGLE_SETTERS = { + + 'float': 'uniform1f(location, value)', + + 'vec2': 'uniform2f(location, value[0], value[1])', + 'vec3': 'uniform3f(location, value[0], value[1], value[2])', + 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', + + 'int': 'uniform1i(location, value)', + 'ivec2': 'uniform2i(location, value[0], value[1])', + 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', + 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'bool': 'uniform1i(location, value)', + 'bvec2': 'uniform2i(location, value[0], value[1])', + 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', + 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'mat2': 'uniformMatrix2fv(location, false, value)', + 'mat3': 'uniformMatrix3fv(location, false, value)', + 'mat4': 'uniformMatrix4fv(location, false, value)', + + 'sampler2D':'uniform1i(location, value)' +}; + +var GLSL_TO_ARRAY_SETTERS = { + + 'float': 'uniform1fv(location, value)', + + 'vec2': 'uniform2fv(location, value)', + 'vec3': 'uniform3fv(location, value)', + 'vec4': 'uniform4fv(location, value)', + + 'int': 'uniform1iv(location, value)', + 'ivec2': 'uniform2iv(location, value)', + 'ivec3': 'uniform3iv(location, value)', + 'ivec4': 'uniform4iv(location, value)', + + 'bool': 'uniform1iv(location, value)', + 'bvec2': 'uniform2iv(location, value)', + 'bvec3': 'uniform3iv(location, value)', + 'bvec4': 'uniform4iv(location, value)', + + 'sampler2D':'uniform1iv(location, value)' +}; + +module.exports = generateUniformAccessObject; + +},{}],58:[function(require,module,exports){ +module.exports = { + compileProgram: require('./compileProgram'), + defaultValue: require('./defaultValue'), + extractAttributes: require('./extractAttributes'), + extractUniforms: require('./extractUniforms'), + generateUniformAccessObject: require('./generateUniformAccessObject'), + mapSize: require('./mapSize'), + mapType: require('./mapType') +}; +},{"./compileProgram":53,"./defaultValue":54,"./extractAttributes":55,"./extractUniforms":56,"./generateUniformAccessObject":57,"./mapSize":59,"./mapType":60}],59:[function(require,module,exports){ +/** + * @class + * @memberof pixi.gl.shader + * @param type {String} + * @return {Number} + */ +var mapSize = function(type) +{ + return GLSL_TO_SIZE[type]; +}; + + +var GLSL_TO_SIZE = { + 'float': 1, + 'vec2': 2, + 'vec3': 3, + 'vec4': 4, + + 'int': 1, + 'ivec2': 2, + 'ivec3': 3, + 'ivec4': 4, + + 'bool': 1, + 'bvec2': 2, + 'bvec3': 3, + 'bvec4': 4, + + 'mat2': 4, + 'mat3': 9, + 'mat4': 16, + + 'sampler2D': 1 +}; + +module.exports = mapSize; + +},{}],60:[function(require,module,exports){ + + +var mapSize = function(gl, type) +{ + if(!GL_TABLE) + { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + + GL_TABLE = {}; + + for(var i = 0; i < typeNames.length; ++i) + { + var tn = typeNames[i]; + GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + } + } + + return GL_TABLE[type]; +}; + +var GL_TABLE = null; + +var GL_TO_GLSL_TYPES = { + 'FLOAT': 'float', + 'FLOAT_VEC2': 'vec2', + 'FLOAT_VEC3': 'vec3', + 'FLOAT_VEC4': 'vec4', + + 'INT': 'int', + 'INT_VEC2': 'ivec2', + 'INT_VEC3': 'ivec3', + 'INT_VEC4': 'ivec4', + + 'BOOL': 'bool', + 'BOOL_VEC2': 'bvec2', + 'BOOL_VEC3': 'bvec3', + 'BOOL_VEC4': 'bvec4', + + 'FLOAT_MAT2': 'mat2', + 'FLOAT_MAT3': 'mat3', + 'FLOAT_MAT4': 'mat4', + + 'SAMPLER_2D': 'sampler2D' +}; + +module.exports = mapSize; + +},{}],61:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +(function () { + try { + cachedSetTimeout = setTimeout; + } catch (e) { + cachedSetTimeout = function () { + throw new Error('setTimeout is not defined'); + } + } + try { + cachedClearTimeout = clearTimeout; + } catch (e) { + cachedClearTimeout = function () { + throw new Error('clearTimeout is not defined'); + } + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],62:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],63:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],64:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],65:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":63,"./encode":64}],66:[function(require,module,exports){ +'use strict'; + +var asyncQueue = require('async/queue'); +var asyncEachSeries = require('async/eachSeries'); +var urlParser = require('url'); +var Resource = require('./Resource'); +var EventEmitter = require('eventemitter3'); + +// some constants +var DEFAULT_CONCURRENCY = 10; +var MAX_PROGRESS = 100; + +/** + * Manages the state and loading of multiple resources to load. + * + * @class + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ +function Loader(baseUrl, concurrency) { + EventEmitter.call(this); + + concurrency = concurrency || DEFAULT_CONCURRENCY; + + /** + * The base url for all resources loaded by this loader. + * + * @member {string} + */ + this.baseUrl = baseUrl || ''; + + /** + * The progress percent of the loader going through the queue. + * + * @member {number} + */ + this.progress = 0; + + /** + * Loading state of the loader, true if it is currently loading resources. + * + * @member {boolean} + */ + this.loading = false; + + /** + * The percentage of total progress that a single resource represents. + * + * @member {number} + */ + this._progressChunk = 0; + + /** + * The middleware to run before loading each resource. + * + * @member {function[]} + */ + this._beforeMiddleware = []; + + /** + * The middleware to run after loading each resource. + * + * @member {function[]} + */ + this._afterMiddleware = []; + + /** + * The `_loadResource` function bound with this object context. + * + * @private + * @member {function} + */ + this._boundLoadResource = this._loadResource.bind(this); + + /** + * The resource buffer that fills until `load` is called to start loading resources. + * + * @private + * @member {Resource[]} + */ + this._buffer = []; + + /** + * Used to track load completion. + * + * @private + * @member {number} + */ + this._numToLoad = 0; + + /** + * The resources waiting to be loaded. + * + * @private + * @member {Resource[]} + */ + this._queue = asyncQueue(this._boundLoadResource, concurrency); + + /** + * All the resources for this loader keyed by name. + * + * @member {object} + */ + this.resources = {}; + + /** + * Emitted once per loaded or errored resource. + * + * @event progress + * @memberof Loader# + */ + + /** + * Emitted once per errored resource. + * + * @event error + * @memberof Loader# + */ + + /** + * Emitted once per loaded resource. + * + * @event load + * @memberof Loader# + */ + + /** + * Emitted when the loader begins to process the queue. + * + * @event start + * @memberof Loader# + */ + + /** + * Emitted when the queued resources all load. + * + * @event complete + * @memberof Loader# + */ +} + +Loader.prototype = Object.create(EventEmitter.prototype); +Loader.prototype.constructor = Loader; +module.exports = Loader; + +/** + * Adds a resource (or multiple resources) to the loader queue. + * + * This function can take a wide variety of different parameters. The only thing that is always + * required the url to load. All the following will work: + * + * ```js + * loader + * // normal param syntax + * .add('key', 'http://...', function () {}) + * .add('http://...', function () {}) + * .add('http://...') + * + * // object syntax + * .add({ + * name: 'key2', + * url: 'http://...' + * }, function () {}) + * .add({ + * url: 'http://...' + * }, function () {}) + * .add({ + * name: 'key3', + * url: 'http://...' + * onComplete: function () {} + * }) + * .add({ + * url: 'https://...', + * onComplete: function () {}, + * crossOrigin: true + * }) + * + * // you can also pass an array of objects or urls or both + * .add([ + * { name: 'key4', url: 'http://...', onComplete: function () {} }, + * { url: 'http://...', onComplete: function () {} }, + * 'http://...' + * ]) + * + * // and you can use both params and options + * .add('key', 'http://...', { crossOrigin: true }, function () {}) + * .add('http://...', { crossOrigin: true }, function () {}); + * ``` + * + * @alias enqueue + * @param {string} [name] - The name of the resource to load, if not passed the url is used. + * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @param {object} [options] - The options for the load. + * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.XHR_LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should the data being + * loaded be interpreted when using XHR? + * @param {function} [cb] - Function to call when this specific resource completes loading. + * @return {Loader} Returns itself. + */ +Loader.prototype.add = Loader.prototype.enqueue = function (name, url, options, cb) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + + return this; + } + + // if an object is passed instead of params + if (typeof name === 'object') { + cb = url || name.callback || name.onComplete; + options = name; + url = name.url; + name = name.name || name.key || name.url; + } + + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + cb = options; + options = url; + url = name; + } + + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + cb = options; + options = null; + } + + // check if resource already exists. + if (this.resources[name]) { + throw new Error('Resource with name "' + name + '" already exists.'); + } + + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + + // create the store the resource + this.resources[name] = new Resource(name, url, options); + + if (typeof cb === 'function') { + this.resources[name].once('afterMiddleware', cb); + } + + this._numToLoad++; + + // if already loading add it to the worker queue + if (this._queue.started) { + this._queue.push(this.resources[name]); + this._progressChunk = (MAX_PROGRESS - this.progress) / (this._queue.length() + this._queue.running()); + } + // otherwise buffer it to be added to the queue later + else { + this._buffer.push(this.resources[name]); + this._progressChunk = MAX_PROGRESS / this._buffer.length; + } + + return this; +}; + +/** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * + * @alias pre + * @method before + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ +Loader.prototype.before = Loader.prototype.pre = function (fn) { + this._beforeMiddleware.push(fn); + + return this; +}; + +/** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * + * @alias use + * @method after + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ +Loader.prototype.after = Loader.prototype.use = function (fn) { + this._afterMiddleware.push(fn); + + return this; +}; + +/** + * Resets the queue of the loader to prepare for a new load. + * + * @return {Loader} Returns itself. + */ +Loader.prototype.reset = function () { + // this.baseUrl = baseUrl || ''; + + this.progress = 0; + + this.loading = false; + + this._progressChunk = 0; + + // this._beforeMiddleware.length = 0; + // this._afterMiddleware.length = 0; + + this._buffer.length = 0; + + this._numToLoad = 0; + + this._queue.kill(); + this._queue.started = false; + + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + + res.off('complete', this._onLoad, this); + + if (res.isLoading) { + res.abort(); + } + } + + this.resources = {}; + + return this; +}; + +/** + * Starts loading the queued resources. + * + * @fires start + * @param {function} [cb] - Optional callback that will be bound to the `complete` event. + * @return {Loader} Returns itself. + */ +Loader.prototype.load = function (cb) { + // register complete callback if they pass one + if (typeof cb === 'function') { + this.once('complete', cb); + } + + // if the queue has already started we are done here + if (this._queue.started) { + return this; + } + + // notify of start + this.emit('start', this); + + // update loading state + this.loading = true; + + // start the internal queue + for (var i = 0; i < this._buffer.length; ++i) { + this._queue.push(this._buffer[i]); + } + + // empty the buffer + this._buffer.length = 0; + + return this; +}; + +/** + * Prepares a url for usage based on the configuration of this object + * + * @private + * @param {string} url - The url to prepare. + * @return {string} The prepared url. + */ +Loader.prototype._prepareUrl = function (url) { + var parsedUrl = urlParser.parse(url); + + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.pathname || parsedUrl.pathname.indexOf('//') === 0) { + return url; + } + + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + if (this.baseUrl.length + && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 + && url.charAt(0) !== '/' + ) { + return this.baseUrl + '/' + url; + } + + return this.baseUrl + url; +}; + +/** + * Loads a single resource. + * + * @private + * @param {Resource} resource - The resource to load. + * @param {function} dequeue - The function to call when we need to dequeue this item. + */ +Loader.prototype._loadResource = function (resource, dequeue) { + var self = this; + + resource._dequeue = dequeue; + + // run before middleware + asyncEachSeries( + this._beforeMiddleware, + function (fn, next) { + fn.call(self, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, + function () { + // resource.on('progress', self.emit.bind(self, 'progress')); + + if (resource.isComplete) { + self._onLoad(resource); + } + else { + resource.once('complete', self._onLoad, self); + resource.load(); + } + } + ); +}; + +/** + * Called once each resource has loaded. + * + * @fires complete + * @private + */ +Loader.prototype._onComplete = function () { + this.loading = false; + + this.emit('complete', this, this.resources); +}; + +/** + * Called each time a resources is loaded. + * + * @fires progress + * @fires error + * @fires load + * @private + * @param {Resource} resource - The resource that was loaded + */ +Loader.prototype._onLoad = function (resource) { + var self = this; + + // run middleware, this *must* happen before dequeue so sub-assets get added properly + asyncEachSeries( + this._afterMiddleware, + function (fn, next) { + fn.call(self, resource, next); + }, + function () { + resource.emit('afterMiddleware', resource); + + self._numToLoad--; + + self.progress += self._progressChunk; + self.emit('progress', self, resource); + + if (resource.error) { + self.emit('error', resource.error, self, resource); + } + else { + self.emit('load', self, resource); + } + + // do completion check + if (self._numToLoad === 0) { + self.progress = 100; + self._onComplete(); + } + } + ); + + // remove this resource from the async queue + resource._dequeue(); +}; + +Loader.LOAD_TYPE = Resource.LOAD_TYPE; +Loader.XHR_RESPONSE_TYPE = Resource.XHR_RESPONSE_TYPE; + +},{"./Resource":67,"async/eachSeries":2,"async/queue":13,"eventemitter3":16,"url":72}],67:[function(require,module,exports){ +'use strict'; + +var EventEmitter = require('eventemitter3'); +var _url = require('url'); + +// tests is CORS is supported in XHR, if not we need to use XDR +var useXdr = !!(window.XDomainRequest && !('withCredentials' in (new XMLHttpRequest()))); +var tempAnchor = null; + +// some status constants +var STATUS_NONE = 0; +var STATUS_OK = 200; +var STATUS_EMPTY = 204; + +/** + * Manages the state and loading of a single resource represented by + * a single URL. + * + * @class + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should the data being + * loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra info for middleware. + */ +function Resource(name, url, options) { + EventEmitter.call(this); + + options = options || {}; + + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + + /** + * The name of this resource. + * + * @member {string} + * @readonly + */ + this.name = name; + + /** + * The url used to load this resource. + * + * @member {string} + * @readonly + */ + this.url = url; + + /** + * Stores whether or not this url is a data url. + * + * @member {boolean} + * @readonly + */ + this.isDataUrl = this.url.indexOf('data:') === 0; + + /** + * The data that was loaded by the resource. + * + * @member {any} + */ + this.data = null; + + /** + * Is this request cross-origin? If unset, determined automatically. + * + * @member {string} + */ + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + + /** + * The method of loading to use for this resource. + * + * @member {Resource.LOAD_TYPE} + */ + this.loadType = options.loadType || this._determineLoadType(); + + /** + * The type used to load the resource via XHR. If unset, determined automatically. + * + * @member {string} + */ + this.xhrType = options.xhrType; + + /** + * Extra info for middleware, and controlling specifics about how the resource loads. + * + * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + * Meaning it will modify it as it sees fit. + * + * @member {object} + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources + * to. + */ + this.metadata = options.metadata || {}; + + /** + * The error that occurred while loading (if any). + * + * @member {Error} + * @readonly + */ + this.error = null; + + /** + * The XHR object that was used to load this resource. This is only set + * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * + * @member {XMLHttpRequest} + */ + this.xhr = null; + + /** + * Describes if this resource was loaded as json. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isJson = false; + + /** + * Describes if this resource was loaded as xml. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isXml = false; + + /** + * Describes if this resource was loaded as an image tag. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isImage = false; + + /** + * Describes if this resource was loaded as an audio tag. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isAudio = false; + + /** + * Describes if this resource was loaded as a video tag. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isVideo = false; + + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * + * @member {boolean} + */ + this.isComplete = false; + + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * + * @member {boolean} + */ + this.isLoading = false; + + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * + * @private + * @member {function} + */ + this._dequeue = null; + + /** + * The `complete` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundComplete = this.complete.bind(this); + + /** + * The `_onError` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnError = this._onError.bind(this); + + /** + * The `_onProgress` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnProgress = this._onProgress.bind(this); + + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + this._boundXdrOnTimeout = this._xdrOnTimeout.bind(this); + + /** + * Emitted when the resource beings to load. + * + * @event start + * @memberof Resource# + */ + + /** + * Emitted each time progress of this resource load updates. + * Not all resources types and loader systems can support this event + * so sometimes it may not be available. If the resource + * is being loaded on a modern browser, using XHR, and the remote server + * properly sets Content-Length headers, then this will be available. + * + * @event progress + * @memberof Resource# + */ + + /** + * Emitted once this resource has loaded, if there was an error it will + * be in the `error` property. + * + * @event complete + * @memberof Resource# + */ +} + +Resource.prototype = Object.create(EventEmitter.prototype); +Resource.prototype.constructor = Resource; +module.exports = Resource; + +/** + * Marks the resource as complete. + * + * @fires complete + */ +Resource.prototype.complete = function () { + // TODO: Clean this up in a wrapper or something...gross.... + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } + else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + + this.isComplete = true; + this.isLoading = false; + + this.emit('complete', this); +}; + +/** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ +Resource.prototype.abort = function (message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + + // store error + this.error = new Error(message); + + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } + else if (this.xdr) { + this.xdr.abort(); + } + else if (this.data) { + // single source + if (typeof this.data.src !== 'undefined') { + this.data.src = ''; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + + // done now. + this.complete(); +}; + +/** + * Kicks off loading of this resource. This method is asynchronous. + * + * @fires start + * @param {function} [cb] - Optional callback to call once the resource is loaded. + */ +Resource.prototype.load = function (cb) { + if (this.isLoading) { + return; + } + + if (this.isComplete) { + if (cb) { + var self = this; + + setTimeout(function () { + cb(self); + }, 1); + } + + return; + } + else if (cb) { + this.once('complete', cb); + } + + this.isLoading = true; + + this.emit('start', this); + + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + + switch (this.loadType) { + case Resource.LOAD_TYPE.IMAGE: + this._loadElement('image'); + break; + + case Resource.LOAD_TYPE.AUDIO: + this._loadSourceElement('audio'); + break; + + case Resource.LOAD_TYPE.VIDEO: + this._loadSourceElement('video'); + break; + + case Resource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } + else { + this._loadXhr(); + } + break; + } +}; + +/** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * + * @private + * @param {string} type - The type of element to use. + */ +Resource.prototype._loadElement = function (type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } + else if (type === 'image' && typeof window.Image !== 'undefined') { + this.data = new Image(); + } + else { + this.data = document.createElement(type); + } + + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + + var typeName = 'is' + type[0].toUpperCase() + type.substring(1); + + if (this[typeName] === false) { + this[typeName] = true; + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); +}; + +/** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * + * @private + * @param {string} type - The type of element to use. + */ +Resource.prototype._loadSourceElement = function (type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } + else if (type === 'audio' && typeof window.Audio !== 'undefined') { + this.data = new Audio(); + } + else { + this.data = document.createElement(type); + } + + if (this.data === null) { + this.abort('Unsupported element ' + type); + + return; + } + + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } + else if (Array.isArray(this.url)) { + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i])); + } + } + else { + this.data.appendChild(this._createSource(type, this.url)); + } + } + + this['is' + type[0].toUpperCase() + type.substring(1)] = true; + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + + this.data.load(); +}; + +/** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ +Resource.prototype._loadXhr = function () { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xhr = this.xhr = new XMLHttpRequest(); + + // set the request type and url + xhr.open('GET', this.url, true); + + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; + } + else { + xhr.responseType = this.xhrType; + } + + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + + xhr.send(); +}; + +/** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ +Resource.prototype._loadXdr = function () { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xdr = this.xhr = new XDomainRequest(); + + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = 5000; + + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXdrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + + xdr.open('GET', this.url, true); + + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { + xdr.send(); + }, 0); +}; + +/** + * Creates a source used in loading via an element. + * + * @private + * @param {string} type - The element type (video or audio). + * @param {string} url - The source URL to load from. + * @param {string} [mime] - The mime type of the video + * @return {HTMLSourceElement} The source element. + */ +Resource.prototype._createSource = function (type, url, mime) { + if (!mime) { + mime = type + '/' + url.substr(url.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = url; + source.type = mime; + + return source; +}; + +/** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ +Resource.prototype._onError = function (event) { + this.abort('Failed to load element using ' + event.target.nodeName); +}; + +/** + * Called if a load progress event fires for xhr/xdr. + * + * @fires progress + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ +Resource.prototype._onProgress = function (event) { + if (event && event.lengthComputable) { + this.emit('progress', this, event.loaded / event.total); + } +}; + +/** + * Called if an error event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestErrorEvent|Event} event - Error event. + */ +Resource.prototype._xhrOnError = function () { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"'); +}; + +/** + * Called if an abort event fires for xhr. + * + * @private + * @param {XMLHttpRequestAbortEvent} event - Abort Event + */ +Resource.prototype._xhrOnAbort = function () { + this.abort(reqType(this.xhr) + ' Request was aborted by the user.'); +}; + +/** + * Called if a timeout event fires for xdr. + * + * @private + * @param {Event} event - Timeout event. + */ +Resource.prototype._xdrOnTimeout = function () { + this.abort(reqType(this.xhr) + ' Request timed out.'); +}; + +/** + * Called when data successfully loads from an xhr/xdr request. + * + * @private + * @param {XMLHttpRequestLoadEvent|Event} event - Load event + */ +Resource.prototype._xhrOnLoad = function () { + var xhr = this.xhr; + var status = typeof xhr.status === 'undefined' ? xhr.status : STATUS_OK; // XDR has no `.status`, assume 200. + + // status can be 0 when using the file:// protocol, also check if a response was found + if (status === STATUS_OK || status === STATUS_EMPTY || (status === STATUS_NONE && xhr.responseText.length > 0)) { + // if text, just return it + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { + this.data = xhr.responseText; + } + // if json, parse into json object + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(xhr.responseText); + this.isJson = true; + } + catch (e) { + this.abort('Error trying to parse loaded json:', e); + + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (window.DOMParser) { + var domparser = new DOMParser(); + + this.data = domparser.parseFromString(xhr.responseText, 'text/xml'); + } + else { + var div = document.createElement('div'); + + div.innerHTML = xhr.responseText; + this.data = div; + } + this.isXml = true; + } + catch (e) { + this.abort('Error trying to parse loaded xml:', e); + + return; + } + } + // other types just return the response + else { + this.data = xhr.response || xhr.responseText; + } + } + else { + this.abort('[' + xhr.status + ']' + xhr.statusText + ':' + xhr.responseURL); + + return; + } + + this.complete(); +}; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * + * @private + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +Resource.prototype._determineCrossOrigin = function (url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url.parse(tempAnchor.href); + + var samePort = (!url.port && loc.port === '') || (url.port === loc.port); + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +}; + +/** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. + */ +Resource.prototype._determineXhrType = function () { + return Resource._xhrTypeMap[this._getExtension()] || Resource.XHR_RESPONSE_TYPE.TEXT; +}; + +Resource.prototype._determineLoadType = function () { + return Resource._loadTypeMap[this._getExtension()] || Resource.LOAD_TYPE.XHR; +}; + +Resource.prototype._getExtension = function () { + var url = this.url; + var ext = ''; + + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } + else { + var queryStart = url.indexOf('?'); + + if (queryStart !== -1) { + url = url.substring(0, queryStart); + } + + ext = url.substring(url.lastIndexOf('.') + 1); + } + + return ext.toLowerCase(); +}; + +/** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * + * @private + * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. + * @return {string} The mime type to use. + */ +Resource.prototype._getMimeFromXhrType = function (type) { + switch (type) { + case Resource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + + case Resource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + + case Resource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + + case Resource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + + case Resource.XHR_RESPONSE_TYPE.DEFAULT: + case Resource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + + } +}; + +/** + * Quick helper to get string xhr type. + * + * @ignore + * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. + * @return {string} The type. + */ +function reqType(xhr) { + return xhr.toString().replace('object ', ''); +} + +/** + * The types of loading a resource can use. + * + * @static + * @readonly + * @enum {number} + */ +Resource.LOAD_TYPE = { + /** Uses XMLHttpRequest to load the resource. */ + XHR: 1, + /** Uses an `Image` object to load the resource. */ + IMAGE: 2, + /** Uses an `Audio` object to load the resource. */ + AUDIO: 3, + /** Uses a `Video` object to load the resource. */ + VIDEO: 4 +}; + +/** + * The XHR ready states, used internally. + * + * @static + * @readonly + * @enum {string} + */ +Resource.XHR_RESPONSE_TYPE = { + /** defaults to text */ + DEFAULT: 'text', + /** ArrayBuffer */ + BUFFER: 'arraybuffer', + /** Blob */ + BLOB: 'blob', + /** Document */ + DOCUMENT: 'document', + /** Object */ + JSON: 'json', + /** String */ + TEXT: 'text' +}; + +Resource._loadTypeMap = { + gif: Resource.LOAD_TYPE.IMAGE, + png: Resource.LOAD_TYPE.IMAGE, + bmp: Resource.LOAD_TYPE.IMAGE, + jpg: Resource.LOAD_TYPE.IMAGE, + jpeg: Resource.LOAD_TYPE.IMAGE, + tif: Resource.LOAD_TYPE.IMAGE, + tiff: Resource.LOAD_TYPE.IMAGE, + webp: Resource.LOAD_TYPE.IMAGE, + tga: Resource.LOAD_TYPE.IMAGE, + 'svg+xml': Resource.LOAD_TYPE.IMAGE +}; + +Resource._xhrTypeMap = { + // xml + xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // images + gif: Resource.XHR_RESPONSE_TYPE.BLOB, + png: Resource.XHR_RESPONSE_TYPE.BLOB, + bmp: Resource.XHR_RESPONSE_TYPE.BLOB, + jpg: Resource.XHR_RESPONSE_TYPE.BLOB, + jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, + tif: Resource.XHR_RESPONSE_TYPE.BLOB, + tiff: Resource.XHR_RESPONSE_TYPE.BLOB, + webp: Resource.XHR_RESPONSE_TYPE.BLOB, + tga: Resource.XHR_RESPONSE_TYPE.BLOB, + + // json + json: Resource.XHR_RESPONSE_TYPE.JSON, + + // text + text: Resource.XHR_RESPONSE_TYPE.TEXT, + txt: Resource.XHR_RESPONSE_TYPE.TEXT +}; + +/** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. + */ +Resource.setExtensionLoadType = function (extname, loadType) { + setExtMap(Resource._loadTypeMap, extname, loadType); +}; + +/** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ +Resource.setExtensionXhrType = function (extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); +}; + +function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + + if (!extname) { + return; + } + + map[extname] = val; +} + +},{"eventemitter3":16,"url":72}],68:[function(require,module,exports){ +/* eslint no-magic-numbers: 0 */ +'use strict'; + +module.exports = { + // private property + _keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', + + encodeBinary: function (input) { + var output = ''; + var bytebuffer; + var encodedCharIndexes = new Array(4); + var inx = 0; + var jnx = 0; + var paddingBytes = 0; + + while (inx < input.length) { + // Fill byte buffer array + bytebuffer = new Array(3); + + for (jnx = 0; jnx < bytebuffer.length; jnx++) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } + else { + bytebuffer[jnx] = 0; + } + } + + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = ((bytebuffer[0] & 0x3) << 4) | (bytebuffer[1] >> 4); + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = ((bytebuffer[1] & 0x0f) << 2) | (bytebuffer[2] >> 6); + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + + // Determine whether padding happened, and adjust accordingly + paddingBytes = inx - (input.length - 1); + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + + default: + break; // No padding - proceed + } + + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (jnx = 0; jnx < encodedCharIndexes.length; jnx++) { + output += this._keyStr.charAt(encodedCharIndexes[jnx]); + } + } + + return output; + } +}; + +},{}],69:[function(require,module,exports){ +/* eslint global-require: 0 */ +'use strict'; + +module.exports = require('./Loader'); +module.exports.Resource = require('./Resource'); +module.exports.middleware = { + caching: { + memory: require('./middlewares/caching/memory') + }, + parsing: { + blob: require('./middlewares/parsing/blob') + } +}; + + +},{"./Loader":66,"./Resource":67,"./middlewares/caching/memory":70,"./middlewares/parsing/blob":71}],70:[function(require,module,exports){ +'use strict'; + +// a simple in-memory cache for resources +var cache = {}; + +module.exports = function () { + return function (resource, next) { + // if cached, then set data and complete the resource + if (cache[resource.url]) { + resource.data = cache[resource.url]; + resource.complete(); // marks resource load complete and stops processing before middlewares + } + // if not cached, wait for complete and store it in the cache. + else { + resource.once('complete', function () { + cache[this.url] = this.data; + }); + } + + next(); + }; +}; + +},{}],71:[function(require,module,exports){ +'use strict'; + +var Resource = require('../../Resource'); +var b64 = require('../../b64'); + +var Url = window.URL || window.webkitURL; + +// a middleware for transforming XHR loaded Blobs into more useful objects + +module.exports = function () { + return function (resource, next) { + if (!resource.data) { + next(); + + return; + } + + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === Resource.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!window.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = 'data:' + type + ';base64,' + b64.encodeBinary(resource.xhr.responseText); + + resource.isImage = true; + + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + + next(); + }; + + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var src = Url.createObjectURL(resource.data); + + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src; + + resource.isImage = true; + + // cleanup the no longer used blob after the image loads + resource.data.onload = function () { + Url.revokeObjectURL(src); + resource.data.onload = null; + + next(); + }; + + // next will be called on load. + return; + } + } + + next(); + }; +}; + +},{"../../Resource":67,"../../b64":68}],72:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":73,"punycode":62,"querystring":65}],73:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],74:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +var _accessibleTarget = require('./accessibleTarget'); + +var _accessibleTarget2 = _interopRequireDefault(_accessibleTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// add some extra variables to the container.. +Object.assign(core.DisplayObject.prototype, _accessibleTarget2.default); + +var KEY_CODE_TAB = 9; + +var DIV_TOUCH_SIZE = 100; +var DIV_TOUCH_POS_X = 0; +var DIV_TOUCH_POS_Y = 0; +var DIV_TOUCH_ZINDEX = 2; + +var DIV_HOOK_SIZE = 1; +var DIV_HOOK_POS_X = -1000; +var DIV_HOOK_POS_Y = -1000; +var DIV_HOOK_ZINDEX = 2; + +/** + * The Accessibility manager reacreates the ability to tab and and have content read by screen + * readers. This is very important as it can possibly help people with disabilities access pixi + * content. + * + * Much like interaction any DisplayObject can be made accessible. This manager will map the + * events as if the mouse was being used, minimizing the efferot required to implement. + * + * @class + * @memberof PIXI + */ + +var AccessibilityManager = function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + _classCallCheck(this, AccessibilityManager); + + if ((_ismobilejs2.default.tablet || _ismobilejs2.default.phone) && !navigator.isCocoonJS) { + this.createTouchHook(); + } + + // first we create a div that will sit over the pixi element. This is where the div overlays will go. + var div = document.createElement('div'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + 'px'; + div.style.left = DIV_TOUCH_POS_Y + 'px'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + + /** + * This is the dom element that will sit over the pixi element. This is where the div overlays will go. + * + * @type {HTMLElement} + * @private + */ + this.div = div; + + /** + * A simple pool for storing divs. + * + * @type {*} + * @private + */ + this.pool = []; + + /** + * This is a tick used to check if an object is no longer being rendered. + * + * @type {Number} + * @private + */ + this.renderId = 0; + + /** + * Setting this to true will visually show the divs + * + * @type {boolean} + */ + this.debug = false; + + /** + * The renderer this accessibility manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * The array of currently active accessible items. + * + * @member {Array<*>} + * @private + */ + this.children = []; + + /** + * pre-bind the functions + * + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + + /** + * stores the state of the manager. If there are no accessible objects or the mouse is moving the will be false. + * + * @member {Array<*>} + * @private + */ + this.isActive = false; + this.isMobileAccessabillity = false; + + // let listen for tab.. once pressed we can fire up and show the accessibility layer + window.addEventListener('keydown', this._onKeyDown, false); + } + + /** + * Creates the touch hooks. + * + */ + + + AccessibilityManager.prototype.createTouchHook = function createTouchHook() { + var _this = this; + + var hookDiv = document.createElement('button'); + + hookDiv.style.width = DIV_HOOK_SIZE + 'px'; + hookDiv.style.height = DIV_HOOK_SIZE + 'px'; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + 'px'; + hookDiv.style.left = DIV_HOOK_POS_Y + 'px'; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX; + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'HOOK DIV'; + + hookDiv.addEventListener('focus', function () { + _this.isMobileAccessabillity = true; + _this.activate(); + document.body.removeChild(hookDiv); + }); + + document.body.appendChild(hookDiv); + }; + + /** + * Activating will cause the Accessibility layer to be shown. This is called when a user + * preses the tab key + * + * @private + */ + + + AccessibilityManager.prototype.activate = function activate() { + if (this.isActive) { + return; + } + + this.isActive = true; + + window.document.addEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown, false); + + this.renderer.on('postrender', this.update, this); + + if (this.renderer.view.parentNode) { + this.renderer.view.parentNode.appendChild(this.div); + } + }; + + /** + * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves + * the mouse + * + * @private + */ + + + AccessibilityManager.prototype.deactivate = function deactivate() { + if (!this.isActive || this.isMobileAccessabillity) { + return; + } + + this.isActive = false; + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.addEventListener('keydown', this._onKeyDown, false); + + this.renderer.off('postrender', this.update); + + if (this.div.parentNode) { + this.div.parentNode.removeChild(this.div); + } + }; + + /** + * This recursive function will run throught he scene graph and add any new accessible objects to the DOM layer. + * + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + + + AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects(displayObject) { + if (!displayObject.visible) { + return; + } + + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + + displayObject.renderId = this.renderId; + } + + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + this.updateAccessibleObjects(children[i]); + } + }; + + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * + * @private + */ + + + AccessibilityManager.prototype.update = function update() { + if (!this.renderer.renderingToScreen) { + return; + } + + // update children... + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + + var rect = this.renderer.view.getBoundingClientRect(); + var sx = rect.width / this.renderer.width; + var sy = rect.height / this.renderer.height; + + var div = this.div; + + div.style.left = rect.left + 'px'; + div.style.top = rect.top + 'px'; + div.style.width = this.renderer.width + 'px'; + div.style.height = this.renderer.height + 'px'; + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + + core.utils.removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + + i--; + + if (this.children.length === 0) { + this.deactivate(); + } + } else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + + if (child.hitArea) { + div.style.left = (wt.tx + hitArea.x * wt.a) * sx + 'px'; + div.style.top = (wt.ty + hitArea.y * wt.d) * sy + 'px'; + + div.style.width = hitArea.width * wt.a * sx + 'px'; + div.style.height = hitArea.height * wt.d * sy + 'px'; + } else { + hitArea = child.getBounds(); + + this.capHitArea(hitArea); + + div.style.left = hitArea.x * sx + 'px'; + div.style.top = hitArea.y * sy + 'px'; + + div.style.width = hitArea.width * sx + 'px'; + div.style.height = hitArea.height * sy + 'px'; + } + } + } + + // increment the render id.. + this.renderId++; + }; + + /** + * TODO: docs. + * + * @param {Rectangle} hitArea - TODO docs + */ + + + AccessibilityManager.prototype.capHitArea = function capHitArea(hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + + if (hitArea.x + hitArea.width > this.renderer.width) { + hitArea.width = this.renderer.width - hitArea.x; + } + + if (hitArea.y + hitArea.height > this.renderer.height) { + hitArea.height = this.renderer.height - hitArea.y; + } + }; + + /** + * Adds a DisplayObject to the accessibility manager + * + * @private + * @param {DisplayObject} displayObject - The child to make accessible. + */ + + + AccessibilityManager.prototype.addChild = function addChild(displayObject) { + // this.activate(); + + var div = this.pool.pop(); + + if (!div) { + div = document.createElement('button'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + div.style.borderStyle = 'none'; + + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + + if (displayObject.accessibleTitle) { + div.title = displayObject.accessibleTitle; + } else if (!displayObject.accessibleTitle && !displayObject.accessibleHint) { + div.title = 'displayObject ' + this.tabIndex; + } + + if (displayObject.accessibleHint) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + + // + + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + + /** + * Maps the div button press to pixi's InteractionManager (click) + * + * @private + * @param {MouseEvent} e - The click event. + */ + + + AccessibilityManager.prototype._onClick = function _onClick(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixis InteractionManager (mouseover) + * + * @private + * @param {FocusEvent} e - The focus event. + */ + + + AccessibilityManager.prototype._onFocus = function _onFocus(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixis InteractionManager (mouseout) + * + * @private + * @param {FocusEvent} e - The focusout event. + */ + + + AccessibilityManager.prototype._onFocusOut = function _onFocusOut(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); + }; + + /** + * Is called when a key is pressed + * + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + + + AccessibilityManager.prototype._onKeyDown = function _onKeyDown(e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + + this.activate(); + }; + + /** + * Is called when the mouse moves across the renderer element + * + * @private + */ + + + AccessibilityManager.prototype._onMouseMove = function _onMouseMove() { + this.deactivate(); + }; + + /** + * Destroys the accessibility manager + * + */ + + + AccessibilityManager.prototype.destroy = function destroy() { + this.div = null; + + for (var i = 0; i < this.children.length; i++) { + this.children[i].div = null; + } + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.removeEventListener('keydown', this._onKeyDown); + + this.pool = null; + this.children = null; + this.renderer = null; + }; + + return AccessibilityManager; +}(); + +exports.default = AccessibilityManager; + + +core.WebGLRenderer.registerPlugin('accessibility', AccessibilityManager); +core.CanvasRenderer.registerPlugin('accessibility', AccessibilityManager); + +},{"../core":97,"./accessibleTarget":75,"ismobilejs":17}],75:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Default property values of accessible objects + * used by {@link PIXI.accessibility.AccessibilityManager}. + * + * @mixin + * @name accessibleTarget + * @memberof PIXI + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibility.accessibleTarget + * ); + */ +exports.default = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * + * @member {boolean} + */ + accessible: false, + + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * + * @member {string} + */ + accessibleTitle: null, + + /** + * Sets the aria-label attribute of the shadow div + * + * @member {string} + */ + accessibleHint: null, + + /** + * @todo Needs docs. + */ + tabIndex: 0, + + /** + * @todo Needs docs. + */ + _accessibleActive: false, + + /** + * @todo Needs docs. + */ + _accessibleDiv: false +}; + +},{}],76:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _accessibleTarget = require('./accessibleTarget'); + +Object.defineProperty(exports, 'accessibleTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_accessibleTarget).default; + } +}); + +var _AccessibilityManager = require('./AccessibilityManager'); + +Object.defineProperty(exports, 'AccessibilityManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AccessibilityManager).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./AccessibilityManager":74,"./accessibleTarget":75}],77:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _const = require('./const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function checkPrecision(src) { + if (src instanceof Array) { + if (src[0].substring(0, 9) !== 'precision') { + var copy = src.slice(0); + + copy.unshift('precision ' + _const.PRECISION.DEFAULT + ' float;'); + + return copy; + } + } else if (src.substring(0, 9) !== 'precision') { + return 'precision ' + _const.PRECISION.DEFAULT + ' float;\n' + src; + } + + return src; +} + +/** + * Wrapper class, webGL Shader for Pixi. + * Adds precision string if vertexSrc or fragmentSrc have no mention of it. + * + * @class + * @extends GLShader + * @memberof PIXI + */ + +var Shader = function (_GLShader) { + _inherits(Shader, _GLShader); + + /** + * + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + * @param {string|string[]} vertexSrc - The vertex shader source as an array of strings. + * @param {string|string[]} fragmentSrc - The fragment shader source as an array of strings. + */ + function Shader(gl, vertexSrc, fragmentSrc) { + _classCallCheck(this, Shader); + + return _possibleConstructorReturn(this, _GLShader.call(this, gl, checkPrecision(vertexSrc), checkPrecision(fragmentSrc))); + } + + return Shader; +}(_pixiGlCore.GLShader); + +exports.default = Shader; + +},{"./const":78,"pixi-gl-core":51}],78:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.SPRITE_MAX_TEXTURES = exports.SPRITE_BATCH_SIZE = exports.TEXT_GRADIENT = exports.TRANSFORM_MODE = exports.PRECISION = exports.SHAPES = exports.SVG_SIZE = exports.DATA_URI = exports.IMAGE_TYPE = exports.DEFAULT_RENDER_OPTIONS = exports.FILTER_RESOLUTION = exports.RESOLUTION = exports.RETINA_PREFIX = exports.MIPMAP_TEXTURES = exports.GC_MODES = exports.WRAP_MODES = exports.SCALE_MODES = exports.DRAW_MODES = exports.BLEND_MODES = exports.RENDERER_TYPE = exports.TARGET_FPMS = exports.DEG_TO_RAD = exports.RAD_TO_DEG = exports.PI_2 = exports.VERSION = undefined; + +var _maxRecommendedTextures = require('./utils/maxRecommendedTextures'); + +var _maxRecommendedTextures2 = _interopRequireDefault(_maxRecommendedTextures); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * String of the current PIXI version. + * + * @static + * @constant + * @memberof PIXI + * @type {string} + */ +var VERSION = exports.VERSION = '4.0.3'; + +/** + * Two Pi. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var PI_2 = exports.PI_2 = Math.PI * 2; + +/** + * Conversion factor for converting radians to degrees. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var RAD_TO_DEG = exports.RAD_TO_DEG = 180 / Math.PI; + +/** + * Conversion factor for converting degrees to radians. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var DEG_TO_RAD = exports.DEG_TO_RAD = Math.PI / 180; + +/** + * Target frames per millisecond. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + * @default 0.06 + */ +var TARGET_FPMS = exports.TARGET_FPMS = 0.06; + +/** + * Constant to identify the Renderer Type. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ +var RENDERER_TYPE = exports.RENDERER_TYPE = { + UNKNOWN: 0, + WEBGL: 1, + CANVAS: 2 +}; + +/** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} NORMAL + * @property {number} ADD + * @property {number} MULTIPLY + * @property {number} SCREEN + * @property {number} OVERLAY + * @property {number} DARKEN + * @property {number} LIGHTEN + * @property {number} COLOR_DODGE + * @property {number} COLOR_BURN + * @property {number} HARD_LIGHT + * @property {number} SOFT_LIGHT + * @property {number} DIFFERENCE + * @property {number} EXCLUSION + * @property {number} HUE + * @property {number} SATURATION + * @property {number} COLOR + * @property {number} LUMINOSITY + */ +var BLEND_MODES = exports.BLEND_MODES = { + NORMAL: 0, + ADD: 1, + MULTIPLY: 2, + SCREEN: 3, + OVERLAY: 4, + DARKEN: 5, + LIGHTEN: 6, + COLOR_DODGE: 7, + COLOR_BURN: 8, + HARD_LIGHT: 9, + SOFT_LIGHT: 10, + DIFFERENCE: 11, + EXCLUSION: 12, + HUE: 13, + SATURATION: 14, + COLOR: 15, + LUMINOSITY: 16 +}; + +/** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} POINTS + * @property {number} LINES + * @property {number} LINE_LOOP + * @property {number} LINE_STRIP + * @property {number} TRIANGLES + * @property {number} TRIANGLE_STRIP + * @property {number} TRIANGLE_FAN + */ +var DRAW_MODES = exports.DRAW_MODES = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6 +}; + +/** + * The scale modes that are supported by pixi. + * + * The DEFAULT scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} DEFAULT=LINEAR + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ +var SCALE_MODES = exports.SCALE_MODES = { + DEFAULT: 0, + LINEAR: 0, + NEAREST: 1 +}; + +/** + * The wrap modes that are supported by pixi. + * + * The DEFAULT wrap mode affects the default wraping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as webGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} DEFAULT=CLAMP + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ +var WRAP_MODES = exports.WRAP_MODES = { + DEFAULT: 0, + CLAMP: 0, + REPEAT: 1, + MIRRORED_REPEAT: 2 +}; + +/** + * The gc modes that are supported by pixi. + * + * The DEFAULT Garbage Collection mode for pixi textures is MANUAL + * If set to DEFAULT, the renderer will occasianally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} DEFAULT=MANUAL + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ +var GC_MODES = exports.GC_MODES = { + DEFAULT: 0, + AUTO: 0, + MANUAL: 1 +}; + +/** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * + * @static + * @constant + * @memberof PIXI + * @type {boolean} + */ +var MIPMAP_TEXTURES = exports.MIPMAP_TEXTURES = true; + +/** + * The prefix that denotes a URL is for a retina asset. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `@2x` + */ +var RETINA_PREFIX = exports.RETINA_PREFIX = /@(.+)x/; + +/** + * Default resolution / device pixel ratio of the renderer. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var RESOLUTION = exports.RESOLUTION = 1; + +/** + * Default filter resolution. + * + * @static + * @constant + * @type {number} + */ +var FILTER_RESOLUTION = exports.FILTER_RESOLUTION = 1; + +/** + * The default render options if none are supplied to {@link PIXI.WebGLRenderer} + * or {@link PIXI.CanvasRenderer}. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {HTMLCanvasElement} view=null + * @property {number} resolution=1 + * @property {boolean} antialias=false + * @property {boolean} forceFXAA=false + * @property {boolean} autoResize=false + * @property {boolean} transparent=false + * @property {number} backgroundColor=0x000000 + * @property {boolean} clearBeforeRender=true + * @property {boolean} preserveDrawingBuffer=false + * @property {boolean} roundPixels=false + */ +var DEFAULT_RENDER_OPTIONS = exports.DEFAULT_RENDER_OPTIONS = { + view: null, + resolution: 1, + antialias: false, + forceFXAA: false, + autoResize: false, + transparent: false, + backgroundColor: 0x000000, + clearBeforeRender: true, + preserveDrawingBuffer: false, + roundPixels: false +}; + +/** + * Regexp for image type by extension. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `image.png` + */ +var IMAGE_TYPE = exports.IMAGE_TYPE = /\.(gif|jpe?g|tiff|png|svg)$/i; + +/** + * Regexp for data URI. + * Based on: https://github.com/ragingwind/data-uri-regex + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `data:image/png;base64` + */ +var DATA_URI = exports.DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;(charset=[\w-]+|base64))?,(.*)/i; + +/** + * Regexp for SVG size. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `` + */ +var SVG_SIZE = exports.SVG_SIZE = /]*(?:\s(width|height)="(\d*(?:\.\d+)?)(?:px)?")[^>]*(?:\s(width|height)="(\d*(?:\.\d+)?)(?:px)?")[^>]*>/i; // eslint-disable-line max-len + +/** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} POLY + * @property {number} RECT + * @property {number} CIRC + * @property {number} ELIP + * @property {number} RREC + */ +var SHAPES = exports.SHAPES = { + POLY: 0, + RECT: 1, + CIRC: 2, + ELIP: 3, + RREC: 4 +}; + +/** + * Constants that specify float precision in shaders. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} DEFAULT='mediump' + * @property {number} LOW='lowp' + * @property {number} MEDIUM='mediump' + * @property {number} HIGH='highp' + */ +var PRECISION = exports.PRECISION = { + DEFAULT: 'mediump', + LOW: 'lowp', + MEDIUM: 'mediump', + HIGH: 'highp' +}; + +/** + * Constants that specify the transform type. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} DEFAULT=STATIC + * @property {number} STATIC + * @property {number} DYNAMIC + */ +var TRANSFORM_MODE = exports.TRANSFORM_MODE = { + DEFAULT: 0, + STATIC: 0, + DYNAMIC: 1 +}; + +/** + * Constants that define the type of gradient on text. + * + * @static + * @constant + * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL + * @property {number} LINEAR_HORIZONTAL + */ +var TEXT_GRADIENT = exports.TEXT_GRADIENT = { + LINEAR_VERTICAL: 0, + LINEAR_HORIZONTAL: 1 +}; + +// TODO: maybe change to SPRITE.BATCH_SIZE: 2000 +// TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + +/** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + * @default 4096 + */ +var SPRITE_BATCH_SIZE = exports.SPRITE_BATCH_SIZE = 4096; + +/** + * The maximum textures that this device supports. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var SPRITE_MAX_TEXTURES = exports.SPRITE_MAX_TEXTURES = (0, _maxRecommendedTextures2.default)(32); + +},{"./utils/maxRecommendedTextures":153}],79:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * 'Builder' pattern for bounds rectangles + * Axis-Aligned Bounding Box + * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems + * + * @class + * @memberof PIXI + */ +var Bounds = function () { + /** + * + */ + function Bounds() { + _classCallCheck(this, Bounds); + + /** + * @member {number} + * @default 0 + */ + this.minX = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.minY = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxX = -Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxY = -Infinity; + + this.rect = null; + } + + /** + * Checks if bounds are empty. + * + * @return {boolean} True if empty. + */ + + + Bounds.prototype.isEmpty = function isEmpty() { + return this.minX > this.maxX || this.minY > this.maxY; + }; + + /** + * Clears the bounds and resets. + * + */ + + + Bounds.prototype.clear = function clear() { + this.updateID++; + + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * + * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty + * @returns {PIXI.Rectangle} A rectangle of the bounds + */ + + + Bounds.prototype.getRectangle = function getRectangle(rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return _math.Rectangle.EMPTY; + } + + rect = rect || new _math.Rectangle(0, 0, 1, 1); + + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + + return rect; + }; + + /** + * This function should be inlined when its possible. + * + * @param {PIXI.Point} point - The point to add. + */ + + + Bounds.prototype.addPoint = function addPoint(point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + }; + + /** + * Adds a quad, not transformed + * + * @param {Float32Array} vertices - The verts to add. + */ + + + Bounds.prototype.addQuad = function addQuad(vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = vertices[0]; + var y = vertices[1]; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds sprite frame, transformed. + * + * @param {PIXI.TransformBase} transform - TODO + * @param {number} x0 - TODO + * @param {number} y0 - TODO + * @param {number} x1 - TODO + * @param {number} y1 - TODO + */ + + + Bounds.prototype.addFrame = function addFrame(transform, x0, y0, x1, y1) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = a * x0 + c * y0 + tx; + var y = b * x0 + d * y0 + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y0 + tx; + y = b * x1 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x0 + c * y1 + tx; + y = b * x0 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y1 + tx; + y = b * x1 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Add an array of vertices + * + * @param {PIXI.TransformBase} transform - TODO + * @param {Float32Array} vertices - TODO + * @param {number} beginOffset - TODO + * @param {number} endOffset - TODO + */ + + + Bounds.prototype.addVertices = function addVertices(transform, vertices, beginOffset, endOffset) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = a * rawX + c * rawY + tx; + var y = d * rawY + b * rawX + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds other Bounds + * + * @param {PIXI.Bounds} bounds - TODO + */ + + + Bounds.prototype.addBounds = function addBounds(bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + }; + + /** + * Adds other Bounds, masked with Bounds + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Bounds} mask - TODO + */ + + + Bounds.prototype.addBoundsMask = function addBoundsMask(bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + /** + * Adds other Bounds, masked with Rectangle + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Rectangle} area - TODO + */ + + + Bounds.prototype.addBoundsArea = function addBoundsArea(bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : area.x + area.width; + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : area.y + area.height; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + return Bounds; +}(); + +exports.default = Bounds; + +},{"../math":102}],80:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _DisplayObject2 = require('./DisplayObject'); + +var _DisplayObject3 = _interopRequireDefault(_DisplayObject2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A Container represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + *```js + * let container = new PIXI.Container(); + * container.addChild(sprite); + * ``` + * + * @class + * @extends PIXI.DisplayObject + * @memberof PIXI + */ +var Container = function (_DisplayObject) { + _inherits(Container, _DisplayObject); + + /** + * + */ + function Container() { + _classCallCheck(this, Container); + + /** + * The array of children of this container. + * + * @member {PIXI.DisplayObject[]} + * @readonly + */ + var _this = _possibleConstructorReturn(this, _DisplayObject.call(this)); + + _this.children = []; + return _this; + } + + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified + * + * @private + */ + + + Container.prototype.onChildrenChange = function onChildrenChange() {} + /* empty */ + + + /** + * Adds a child or multiple children to the container. + * + * Multple items can be added like so: `myContainer.addChild(thinkOne, thingTwo, thingThree)` + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container + * @return {PIXI.DisplayObject} The first child that was added. + */ + ; + + Container.prototype.addChild = function addChild() { + for (var _len = arguments.length, childs = Array(_len), _key = 0; _key < _len; _key++) { + childs[_key] = arguments[_key]; + } + + for (var i = 0; i < childs.length; ++i) { + var child = childs[i]; + + // if the child has a parent then lets remove it as Pixi objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + + // ensure a transform will be recalculated.. + this.transform._parentID = -1; + this._boundsID++; + + this.children.push(child); + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + child.emit('added', this); + } + + return childs[0]; + }; + + /** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @return {PIXI.DisplayObject} The child that was added. + */ + + + Container.prototype.addChildAt = function addChildAt(child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error(child + 'addChildAt: The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + + this.children.splice(index, 0, child); + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + + return child; + }; + + /** + * Swaps the position of 2 Display Objects within this container. + * + * @param {PIXI.DisplayObject} child - First display object to swap + * @param {PIXI.DisplayObject} child2 - Second display object to swap + */ + + + Container.prototype.swapChildren = function swapChildren(child, child2) { + if (child === child2) { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + + if (index1 < 0 || index2 < 0) { + throw new Error('swapChildren: Both the supplied DisplayObjects must be children of the caller.'); + } + + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; + + /** + * Returns the index position of a child DisplayObject instance + * + * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify + * @return {number} The index position of the child display object to identify + */ + + + Container.prototype.getChildIndex = function getChildIndex(child) { + var index = this.children.indexOf(child); + + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + }; + + /** + * Changes the position of an existing child in the display object container + * + * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number + * @param {number} index - The resulting index number for the child display object + */ + + + Container.prototype.setChildIndex = function setChildIndex(child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + (0, _utils.removeItems)(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + this.onChildrenChange(index); + }; + + /** + * Returns the child at the specified index + * + * @param {number} index - The index to get the child at + * @return {PIXI.DisplayObject} The child at the given index, if any. + */ + + + Container.prototype.getChildAt = function getChildAt(index) { + if (index < 0 || index >= this.children.length) { + throw new Error('getChildAt: Index (' + index + ') does not exist.'); + } + + return this.children[index]; + }; + + /** + * Removes a child from the container. + * + * @param {...PIXI.DisplayObject} childs - The DisplayObject(s) to remove + * @return {PIXI.DisplayObject} The first child that was removed. + */ + + + Container.prototype.removeChild = function removeChild() { + for (var _len2 = arguments.length, childs = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + childs[_key2] = arguments[_key2]; + } + + for (var i = 0; i < childs.length; ++i) { + var child = childs[i]; + var index = this.children.indexOf(child); + + if (index === -1) continue; + + child.parent = null; + (0, _utils.removeItems)(this.children, index, 1); + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + } + + return childs[0]; + }; + + /** + * Removes a child from the specified index position. + * + * @param {number} index - The index to get the child from + * @return {PIXI.DisplayObject} The child that was removed. + */ + + + Container.prototype.removeChildAt = function removeChildAt(index) { + var child = this.getChildAt(index); + + child.parent = null; + (0, _utils.removeItems)(this.children, index, 1); + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + + return child; + }; + + /** + * Removes all children from this container that are within the begin and end indexes. + * + * @param {number} [beginIndex=0] - The beginning position. + * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. + * @returns {DisplayObject[]} List of removed children + */ + + + Container.prototype.removeChildren = function removeChildren() { + var beginIndex = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var endIndex = arguments[1]; + + var begin = beginIndex; + var end = typeof endIndex === 'number' ? endIndex : this.children.length; + var range = end - begin; + var removed = void 0; + + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + } + + this.onChildrenChange(beginIndex); + + for (var _i = 0; _i < removed.length; ++_i) { + removed[_i].emit('removed', this); + } + + return removed; + } else if (range === 0 && this.children.length === 0) { + return []; + } + + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + }; + + /** + * Updates the transform on all children of this container for rendering + * + * @private + */ + + + Container.prototype.updateTransform = function updateTransform() { + this._boundsID++; + + this.transform.updateTransform(this.parent.transform); + + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + + if (child.visible) { + child.updateTransform(); + } + } + }; + + /** + * Recalculates the bounds of the container. + * + */ + + + Container.prototype.calculateBounds = function calculateBounds() { + this._bounds.clear(); + + this._calculateBounds(); + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (!child.visible || !child.renderable) { + continue; + } + + child.calculateBounds(); + + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + child._mask.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, child._mask._bounds); + } else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } else { + this._bounds.addBounds(child._bounds); + } + } + + this._lastBoundsID = this._boundsID; + }; + + /** + * Recalculates the bounds of the object. Override this to + * calculate the bounds of the specific object (not including children). + * + */ + + + Container.prototype._calculateBounds = function _calculateBounds() {} + // FILL IN// + + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderWebGL = function renderWebGL(renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + // do a quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) { + this.renderAdvancedWebGL(renderer); + } else { + this._renderWebGL(renderer); + + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderWebGL(renderer); + } + } + }; + + /** + * Render the object using the WebGL renderer and advanced features. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { + renderer.currentRenderer.flush(); + + var filters = this._filters; + var mask = this._mask; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + + this._enabledFilters.length = 0; + + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + + if (this._enabledFilters.length) { + renderer.filterManager.pushFilter(this, this._enabledFilters); + } + } + + if (mask) { + renderer.maskManager.pushMask(this, this._mask); + } + + renderer.currentRenderer.start(); + + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); + + // now loop through the children and make sure they get rendered + for (var _i2 = 0, j = this.children.length; _i2 < j; _i2++) { + this.children[_i2].renderWebGL(renderer); + } + + renderer.currentRenderer.flush(); + + if (mask) { + renderer.maskManager.popMask(this, this._mask); + } + + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filterManager.popFilter(); + } + + renderer.currentRenderer.start(); + }; + + /** + * To be overridden by the subclasses. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype._renderWebGL = function _renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * To be overridden by the subclass + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype._renderCanvas = function _renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderCanvas = function renderCanvas(renderer) { + // if not visible or the alpha is 0 then no need to render this + if (!this.visible || this.alpha <= 0 || !this.renderable) { + return; + } + + if (this._mask) { + renderer.maskManager.pushMask(this._mask); + } + + this._renderCanvas(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderCanvas(renderer); + } + + if (this._mask) { + renderer.maskManager.popMask(renderer); + } + }; + + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + */ + + + Container.prototype.destroy = function destroy(options) { + _DisplayObject.prototype.destroy.call(this); + + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + + var oldChildren = this.removeChildren(0, this.children.length); + + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + }; + + /** + * The width of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Container# + */ + + + _createClass(Container, [{ + key: 'width', + get: function get() { + return this.scale.x * this.getLocalBounds().width; + } + + /** + * Sets the width of the container by modifying the scale. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + var width = this.getLocalBounds().width; + + if (width !== 0) { + this.scale.x = value / width; + } else { + this.scale.x = 1; + } + + this._width = value; + } + + /** + * The height of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Container# + */ + + }, { + key: 'height', + get: function get() { + return this.scale.y * this.getLocalBounds().height; + } + + /** + * Sets the height of the container by modifying the scale. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + var height = this.getLocalBounds().height; + + if (height !== 0) { + this.scale.y = value / height; + } else { + this.scale.y = 1; + } + + this._height = value; + } + }]); + + return Container; +}(_DisplayObject3.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = Container; +Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + +},{"../utils":152,"./DisplayObject":81}],81:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _const = require('../const'); + +var _TransformStatic = require('./TransformStatic'); + +var _TransformStatic2 = _interopRequireDefault(_TransformStatic); + +var _Transform = require('./Transform'); + +var _Transform2 = _interopRequireDefault(_Transform); + +var _Bounds = require('./Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _math = require('../math'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// _tempDisplayObjectParent = new DisplayObject(); + +/** + * The base class for all objects that are rendered on the screen. + * This is an abstract class and should not be used on its own rather it should be extended. + * + * @class + * @extends EventEmitter + * @mixes PIXI.interaction.interactiveTarget + * @memberof PIXI + */ +var DisplayObject = function (_EventEmitter) { + _inherits(DisplayObject, _EventEmitter); + + /** + * + */ + function DisplayObject() { + _classCallCheck(this, DisplayObject); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + var TransformClass = _const.TRANSFORM_MODE.DEFAULT === _const.TRANSFORM_MODE.STATIC ? _TransformStatic2.default : _Transform2.default; + + _this.tempDisplayObjectParent = null; + + // TODO: need to create Transform from factory + /** + * World transform and local transform of this object. + * This will become read-only later, please do not assign anything there unless you know what are you doing + * + * @member {PIXI.TransformBase} + */ + _this.transform = new TransformClass(); + + /** + * The opacity of the object. + * + * @member {number} + */ + _this.alpha = 1; + + /** + * The visibility of the object. If false the object will not be drawn, and + * the updateTransform function will not be called. + * + * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually + * + * @member {boolean} + */ + _this.visible = true; + + /** + * Can this object be rendered, if false the object will not be drawn but the updateTransform + * methods will still be called. + * + * Only affects recursive calls from parent. You can ask for bounds manually + * + * @member {boolean} + */ + _this.renderable = true; + + /** + * The display object container that contains this display object. + * + * @member {PIXI.Container} + * @readonly + */ + _this.parent = null; + + /** + * The multiplied alpha of the displayObject + * + * @member {number} + * @readonly + */ + _this.worldAlpha = 1; + + /** + * The area the filter is applied to. This is used as more of an optimisation + * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle + * + * Also works as an interaction mask + * + * @member {PIXI.Rectangle} + */ + _this.filterArea = null; + + _this._filters = null; + _this._enabledFilters = null; + + /** + * The bounds object, this is used to calculate and store the bounds of the displayObject + * + * @member {PIXI.Rectangle} + * @private + */ + _this._bounds = new _Bounds2.default(); + _this._boundsID = 0; + _this._lastBoundsID = -1; + _this._boundsRect = null; + _this._localBoundsRect = null; + + /** + * The original, cached mask of the object + * + * @member {PIXI.Rectangle} + * @private + */ + _this._mask = null; + return _this; + } + + /** + * @private + * @member {PIXI.DisplayObject} + */ + + + /** + * Updates the object transform for rendering + * + * TODO - Optimization pass! + */ + DisplayObject.prototype.updateTransform = function updateTransform() { + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + this._bounds.updateID++; + }; + + /** + * recursively updates transform of all objects from the root to this one + * internal function for toLocal() + */ + + + DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform() { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + }; + + /** + * Retrieves the bounds of the displayObject as a rectangle object. + * + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @param {PIXI.Rectangle} rect - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getBounds = function getBounds(skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + + if (this._boundsID !== this._lastBoundsID) { + this.calculateBounds(); + } + + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new _math.Rectangle(); + } + + rect = this._boundsRect; + } + + return this._bounds.getRectangle(rect); + }; + + /** + * Retrieves the local bounds of the displayObject as a rectangle object + * + * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getLocalBounds = function getLocalBounds(rect) { + var transformRef = this.transform; + var parentRef = this.parent; + + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + var bounds = this.getBounds(false, rect); + + this.parent = parentRef; + this.transform = transformRef; + + return bounds; + }; + + /** + * Calculates the global position of the display object + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform. + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toGlobal = function toGlobal(position, point) { + var skipUpdate = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2]; + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; + + /** + * Calculates the local position of the display object relative to another point + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toLocal = function toLocal(position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + DisplayObject.prototype.renderCanvas = function renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Set the parent Container of this DisplayObject + * + * @param {PIXI.Container} container - The Container to add this DisplayObject to + * @return {PIXI.Container} The Container that this DisplayObject was added to + */ + ; + + DisplayObject.prototype.setParent = function setParent(container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); + } + + container.addChild(this); + + return container; + }; + + /** + * Convenience function to set the postion, scale, skew and pivot at once. + * + * @param {number} [x=0] - The X position + * @param {number} [y=0] - The Y position + * @param {number} [scaleX=1] - The X scale value + * @param {number} [scaleY=1] - The Y scale value + * @param {number} [rotation=0] - The rotation + * @param {number} [skewX=0] - The X skew value + * @param {number} [skewY=0] - The Y skew value + * @param {number} [pivotX=0] - The X pivot value + * @param {number} [pivotY=0] - The Y pivot value + * @return {PIXI.DisplayObject} The DisplayObject instance + */ + + + DisplayObject.prototype.setTransform = function setTransform() { + var x = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var y = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + var scaleX = arguments.length <= 2 || arguments[2] === undefined ? 1 : arguments[2]; + var scaleY = arguments.length <= 3 || arguments[3] === undefined ? 1 : arguments[3]; + var rotation = arguments.length <= 4 || arguments[4] === undefined ? 0 : arguments[4]; + var skewX = arguments.length <= 5 || arguments[5] === undefined ? 0 : arguments[5]; + var skewY = arguments.length <= 6 || arguments[6] === undefined ? 0 : arguments[6]; + var pivotX = arguments.length <= 7 || arguments[7] === undefined ? 0 : arguments[7]; + var pivotY = arguments.length <= 8 || arguments[8] === undefined ? 0 : arguments[8]; + + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + + return this; + }; + + /** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy`. + * + */ + + + DisplayObject.prototype.destroy = function destroy() { + this.removeAllListeners(); + if (this.parent) { + this.parent.removeChild(this); + } + this.transform = null; + + this.parent = null; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this.filterArea = null; + + this.interactive = false; + this.interactiveChildren = false; + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + * + * @member {number} + * @memberof PIXI.DisplayObject# + */ + + + _createClass(DisplayObject, [{ + key: '_tempDisplayObjectParent', + get: function get() { + if (this.tempDisplayObjectParent === null) { + this.tempDisplayObjectParent = new DisplayObject(); + } + + return this.tempDisplayObjectParent; + } + }, { + key: 'x', + get: function get() { + return this.position.x; + } + + /** + * Sets the X position of the object. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this.transform.position.x = value; + } + + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + * + * @member {number} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'y', + get: function get() { + return this.position.y; + } + + /** + * Sets the Y position of the object. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this.transform.position.y = value; + } + + /** + * Current transform of the object based on world (parent) factors + * + * @member {PIXI.Matrix} + * @memberof PIXI.DisplayObject# + * @readonly + */ + + }, { + key: 'worldTransform', + get: function get() { + return this.transform.worldTransform; + } + + /** + * Current transform of the object based on local factors: position, scale, other stuff + * + * @member {PIXI.Matrix} + * @memberof PIXI.DisplayObject# + * @readonly + */ + + }, { + key: 'localTransform', + get: function get() { + return this.transform.localTransform; + } + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'position', + get: function get() { + return this.transform.position; + } + + /** + * Copies the point to the position of the object. + * + * @param {PIXI.Point} value - The value to set to. + */ + , + set: function set(value) { + this.transform.position.copy(value); + } + + /** + * The scale factor of the object. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'scale', + get: function get() { + return this.transform.scale; + } + + /** + * Copies the point to the scale of the object. + * + * @param {PIXI.Point} value - The value to set to. + */ + , + set: function set(value) { + this.transform.scale.copy(value); + } + + /** + * The pivot point of the displayObject that it rotates around + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'pivot', + get: function get() { + return this.transform.pivot; + } + + /** + * Copies the point to the pivot of the object. + * + * @param {PIXI.Point} value - The value to set to. + */ + , + set: function set(value) { + this.transform.pivot.copy(value); + } + + /** + * The skew factor for the object in radians. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'skew', + get: function get() { + return this.transform.skew; + } + + /** + * Copies the point to the skew of the object. + * + * @param {PIXI.Point} value - The value to set to. + */ + , + set: function set(value) { + this.transform.skew.copy(value); + } + + /** + * The rotation of the object in radians. + * + * @member {number} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'rotation', + get: function get() { + return this.transform.rotation; + } + + /** + * Sets the rotation of the object. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this.transform.rotation = value; + } + + /** + * Indicates if the sprite is globally visible. + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + * @readonly + */ + + }, { + key: 'worldVisible', + get: function get() { + var item = this; + + do { + if (!item.visible) { + return false; + } + + item = item.parent; + } while (item); + + return true; + } + + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PIXI a regular mask must be a + * PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it + * utilises shape clipping. To remove a mask, set this property to null. + * + * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + * + * @member {PIXI.Graphics|PIXI.Sprite} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'mask', + get: function get() { + return this._mask; + } + + /** + * Sets the mask. + * + * @param {PIXI.Graphics|PIXI.Sprite} value - The value to set to. + */ + , + set: function set(value) { + if (this._mask) { + this._mask.renderable = true; + } + + this._mask = value; + + if (this._mask) { + this._mask.renderable = false; + } + } + + /** + * Sets the filters for the displayObject. + * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * To remove filters simply set this property to 'null' + * + * @member {PIXI.AbstractFilter[]} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'filters', + get: function get() { + return this._filters && this._filters.slice(); + } + + /** + * Shallow copies the array to the filters of the object. + * + * @param {PIXI.Filter[]} value - The filters to set. + */ + , + set: function set(value) { + this._filters = value && value.slice(); + } + }]); + + return DisplayObject; +}(_eventemitter2.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = DisplayObject; +DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + +},{"../const":78,"../math":102,"./Bounds":79,"./Transform":82,"./TransformStatic":84,"eventemitter3":16}],82:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Generic class to deal with traditional 2D matrix transforms + * local transformation is calculated from position,scale,skew and rotation + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var Transform = function (_TransformBase) { + _inherits(Transform, _TransformBase); + + /** + * + */ + function Transform() { + _classCallCheck(this, Transform); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.Point} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.Point(0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.Point} + */ + _this.scale = new _math.Point(1, 1); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.Point} + */ + _this.pivot = new _math.Point(0, 0); + + /** + * The rotation value of the object, in radians + * + * @member {Number} + * @private + */ + _this._rotation = 0; + + _this._sr = Math.sin(0); + _this._cr = Math.cos(0); + _this._cy = Math.cos(0); // skewY); + _this._sy = Math.sin(0); // skewY); + _this._nsx = Math.sin(0); // skewX); + _this._cx = Math.cos(0); // skewX); + return _this; + } + + /** + * Updates the skew values when the skew changes. + * + * @private + */ + + + Transform.prototype.updateSkew = function updateSkew() { + this._cy = Math.cos(this.skew.y); + this._sy = Math.sin(this.skew.y); + this._nsx = Math.sin(this.skew.x); + this._cx = Math.cos(this.skew.x); + }; + + /** + * Updates only local matrix + */ + + + Transform.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + var a = this._cr * this.scale.x; + var b = this._sr * this.scale.x; + var c = -this._sr * this.scale.y; + var d = this._cr * this.scale.y; + + lt.a = this._cy * a + this._sy * c; + lt.b = this._cy * b + this._sy * d; + lt.c = this._nsx * a + this._cx * c; + lt.d = this._nsx * b + this._cx * d; + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + Transform.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + var a = this._cr * this.scale.x; + var b = this._sr * this.scale.x; + var c = -this._sr * this.scale.y; + var d = this._cr * this.scale.y; + + lt.a = this._cy * a + this._sy * c; + lt.b = this._cy * b + this._sy * d; + lt.c = this._nsx * a + this._cx * c; + lt.d = this._nsx * b + this._cx * d; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + Transform.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + * @memberof PIXI.Transform# + */ + + + _createClass(Transform, [{ + key: 'rotation', + get: function get() { + return this._rotation; + } + + /** + * Set the rotation of the transform. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this._rotation = value; + this._sr = Math.sin(value); + this._cr = Math.cos(value); + } + }]); + + return Transform; +}(_TransformBase3.default); + +exports.default = Transform; + +},{"../math":102,"./TransformBase":83}],83:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Generic class to deal with traditional 2D matrix transforms + * + * @class + * @memberof PIXI + */ +var TransformBase = function () { + /** + * + */ + function TransformBase() { + _classCallCheck(this, TransformBase); + + /** + * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds() + * + * @member {PIXI.Matrix} + */ + this.worldTransform = new _math.Matrix(); + + /** + * The local matrix transform + * + * @member {PIXI.Matrix} + */ + this.localTransform = new _math.Matrix(); + + this._worldID = 0; + this._parentID = 0; + } + + /** + * TransformBase does not have decomposition, so this function wont do anything + */ + + + TransformBase.prototype.updateLocalTransform = function updateLocalTransform() {} + // empty + + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.TransformBase} parentTransform - The transform of the parent of this object + */ + ; + + TransformBase.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + return TransformBase; +}(); + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ + + +exports.default = TransformBase; +TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; + +TransformBase.IDENTITY = new TransformBase(); + +},{"../math":102}],84:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Transform that takes care about its versions + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var TransformStatic = function (_TransformBase) { + _inherits(TransformStatic, _TransformBase); + + /** + * + */ + function TransformStatic() { + _classCallCheck(this, TransformStatic); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.ObservablePoint} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.ObservablePoint} + */ + _this.scale = new _math.ObservablePoint(_this.onChange, _this, 1, 1); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.ObservablePoint} + */ + _this.pivot = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + _this._rotation = 0; + + _this._sr = Math.sin(0); + _this._cr = Math.cos(0); + _this._cy = Math.cos(0); // skewY); + _this._sy = Math.sin(0); // skewY); + _this._nsx = Math.sin(0); // skewX); + _this._cx = Math.cos(0); // skewX); + + _this._localID = 0; + _this._currentLocalID = 0; + return _this; + } + + /** + * Called when a value changes. + * + * @private + */ + + + TransformStatic.prototype.onChange = function onChange() { + this._localID++; + }; + + /** + * Called when skew changes + * + * @private + */ + + + TransformStatic.prototype.updateSkew = function updateSkew() { + this._cy = Math.cos(this.skew._y); + this._sy = Math.sin(this.skew._y); + this._nsx = Math.sin(this.skew._x); + this._cx = Math.cos(this.skew._x); + + this._localID++; + }; + + /** + * Updates only local matrix + */ + + + TransformStatic.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + var a = this._cr * this.scale._x; + var b = this._sr * this.scale._x; + var c = -this._sr * this.scale._y; + var d = this._cr * this.scale._y; + + lt.a = this._cy * a + this._sy * c; + lt.b = this._cy * b + this._sy * d; + lt.c = this._nsx * a + this._cx * c; + lt.d = this._nsx * b + this._cx * d; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + TransformStatic.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + var a = this._cr * this.scale._x; + var b = this._sr * this.scale._x; + var c = -this._sr * this.scale._y; + var d = this._cr * this.scale._y; + + lt.a = this._cy * a + this._sy * c; + lt.b = this._cy * b + this._sy * d; + lt.c = this._nsx * a + this._cx * c; + lt.d = this._nsx * b + this._cx * d; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._parentID = parentTransform._worldID; + + // update the id of the transform.. + this._worldID++; + } + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + TransformStatic.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + this._localID++; + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + * @memberof PIXI.TransformStatic# + */ + + + _createClass(TransformStatic, [{ + key: 'rotation', + get: function get() { + return this._rotation; + } + + /** + * Sets the rotation of the transform. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this._rotation = value; + this._sr = Math.sin(value); + this._cr = Math.cos(value); + this._localID++; + } + }]); + + return TransformStatic; +}(_TransformBase3.default); + +exports.default = TransformStatic; + +},{"../math":102,"./TransformBase":83}],85:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _GraphicsData = require('./GraphicsData'); + +var _GraphicsData2 = _interopRequireDefault(_GraphicsData); + +var _Sprite = require('../sprites/Sprite'); + +var _Sprite2 = _interopRequireDefault(_Sprite); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Bounds = require('../display/Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _bezierCurveTo2 = require('./utils/bezierCurveTo'); + +var _bezierCurveTo3 = _interopRequireDefault(_bezierCurveTo2); + +var _CanvasRenderer = require('../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var canvasRenderer = void 0; +var tempMatrix = new _math.Matrix(); +var tempPoint = new _math.Point(); +var tempColor1 = new Float32Array(4); +var tempColor2 = new Float32Array(4); + +/** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Graphics = function (_Container) { + _inherits(Graphics, _Container); + + /** + * + */ + function Graphics() { + _classCallCheck(this, Graphics); + + /** + * The alpha value used when filling the Graphics object. + * + * @member {number} + * @default 1 + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @member {number} + * @default 0 + */ + _this.lineWidth = 0; + + /** + * The color of any lines drawn. + * + * @member {string} + * @default 0 + */ + _this.lineColor = 0; + + /** + * Graphics data + * + * @member {PIXI.GraphicsData[]} + * @private + */ + _this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to + * reset the tint. + * + * @member {number} + * @default 0xFFFFFF + */ + _this.tint = 0xFFFFFF; + + /** + * The previous tint applied to the graphic shape. Used to compare to the current tint and + * check if theres change. + * + * @member {number} + * @private + * @default 0xFFFFFF + */ + _this._prevTint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * Current path + * + * @member {PIXI.GraphicsData} + * @private + */ + _this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @member {object} + * @private + */ + // TODO - _webgl should use a prototype object, not a random undocumented object... + _this._webGL = {}; + + /** + * Whether this shape is being used as a mask. + * + * @member {boolean} + */ + _this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @member {number} + */ + _this.boundsPadding = 0; + + /** + * A cache of the local bounds to prevent recalculation. + * + * @member {PIXI.Rectangle} + * @private + */ + _this._localBounds = new _Bounds2.default(); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics + * object will be recalculated. + * + * @member {boolean} + * @private + */ + _this.dirty = 0; + + /** + * Used to detect if we need to do a fast rect check using the id compare method + * @type {Number} + */ + _this.fastRectDirty = -1; + + /** + * Used to detect if we clear the graphics webGL data + * @type {Number} + */ + _this.clearDirty = 0; + + /** + * Used to detect if we we need to recalculate local bounds + * @type {Number} + */ + _this.boundsDirty = -1; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @member {boolean} + * @private + */ + _this.cachedSpriteDirty = false; + + _this._spriteRect = null; + _this._fastRect = false; + + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ + return _this; + } + + /** + * Creates a new Graphics object with the same values as this one. + * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) + * + * @return {PIXI.Graphics} A clone of the graphics object + */ + + + Graphics.prototype.clone = function clone() { + var clone = new Graphics(); + + clone.renderable = this.renderable; + clone.fillAlpha = this.fillAlpha; + clone.lineWidth = this.lineWidth; + clone.lineColor = this.lineColor; + clone.tint = this.tint; + clone.blendMode = this.blendMode; + clone.isMask = this.isMask; + clone.boundsPadding = this.boundsPadding; + clone.dirty = 0; + clone.cachedSpriteDirty = this.cachedSpriteDirty; + + // copy graphics data + for (var i = 0; i < this.graphicsData.length; ++i) { + clone.graphicsData.push(this.graphicsData[i].clone()); + } + + clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; + + clone.updateLocalBounds(); + + return clone; + }; + + /** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() + * method or the drawCircle() method. + * + * @param {number} [lineWidth=0] - width of the line to draw, will update the objects stored style + * @param {number} [color=0] - color of the line to draw, will update the objects stored style + * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineStyle = function lineStyle() { + var lineWidth = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var color = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + var alpha = arguments.length <= 2 || arguments[2] === undefined ? 1 : arguments[2]; + + this.lineWidth = lineWidth; + this.lineColor = color; + this.lineAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length) { + // halfway through a line? start a new one! + var shape = new _math.Polygon(this.currentPath.shape.points.slice(-2)); + + shape.closed = false; + + this.drawShape(shape); + } else { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + }; + + /** + * Moves the current drawing position to x, y. + * + * @param {number} x - the X coordinate to move to + * @param {number} y - the Y coordinate to move to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.moveTo = function moveTo(x, y) { + var shape = new _math.Polygon([x, y]); + + shape.closed = false; + this.drawShape(shape); + + return this; + }; + + /** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @param {number} x - the X coordinate to draw to + * @param {number} y - the Y coordinate to draw to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineTo = function lineTo(x, y) { + this.currentPath.shape.points.push(x, y); + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.quadraticCurveTo = function quadraticCurveTo(cpX, cpY, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var n = 20; + var points = this.currentPath.shape.points; + var xa = 0; + var ya = 0; + + if (points.length === 0) { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + for (var i = 1; i <= n; ++i) { + var j = i / n; + + xa = fromX + (cpX - fromX) * j; + ya = fromY + (cpY - fromY) * j; + + points.push(xa + (cpX + (toX - cpX) * j - xa) * j, ya + (cpY + (toY - cpY) * j - ya) * j); + } + + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a bezier curve and then draws it. + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.bezierCurveTo = function bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + points.length -= 2; + + (0, _bezierCurveTo3.default)(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, points); + + this.dirty++; + + return this; + }; + + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @param {number} x1 - The x-coordinate of the beginning of the arc + * @param {number} y1 - The y-coordinate of the beginning of the arc + * @param {number} x2 - The x-coordinate of the end of the arc + * @param {number} y2 - The y-coordinate of the end of the arc + * @param {number} radius - The radius of the arc + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arcTo = function arcTo(x1, y1, x2, y2, radius) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points.push(x1, y1); + } + } else { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + } else { + var dd = a1 * a1 + b1 * b1; + var cc = a2 * a2 + b2 * b2; + var tt = a1 * a2 + b1 * b2; + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = k1 * b2 + k2 * b1; + var cy = k1 * a2 + k2 * a1; + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty++; + + return this; + }; + + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @param {number} cx - The x-coordinate of the center of the circle + * @param {number} cy - The y-coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param {number} endAngle - The ending angle, in radians + * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arc = function arc(cx, cy, radius, startAngle, endAngle) { + var anticlockwise = arguments.length <= 5 || arguments[5] === undefined ? false : arguments[5]; + + if (startAngle === endAngle) { + return this; + } + + if (!anticlockwise && endAngle <= startAngle) { + endAngle += Math.PI * 2; + } else if (anticlockwise && startAngle <= endAngle) { + startAngle += Math.PI * 2; + } + + var sweep = anticlockwise ? (startAngle - endAngle) * -1 : endAngle - startAngle; + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * 40; + + if (sweep === 0) { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + if (this.currentPath) { + this.currentPath.shape.points.push(startX, startY); + } else { + this.moveTo(startX, startY); + } + + var points = this.currentPath.shape.points; + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = segMinus % 1 / segMinus; + + for (var i = 0; i <= segMinus; ++i) { + var real = i + remainder * i; + + var angle = theta + startAngle + theta2 * real; + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push((cTheta * c + sTheta * s) * radius + cx, (cTheta * -s + sTheta * c) * radius + cy); + } + + this.dirty++; + + return this; + }; + + /** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @param {number} [color=0] - the color of the fill + * @param {number} [alpha=1] - the alpha of the fill + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.beginFill = function beginFill() { + var color = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var alpha = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1]; + + this.filling = true; + this.fillColor = color; + this.fillAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length <= 2) { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + }; + + /** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.endFill = function endFill() { + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRect = function drawRect(x, y, width, height) { + this.drawShape(new _math.Rectangle(x, y, width, height)); + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @param {number} radius - Radius of the rectangle corners + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRoundedRect = function drawRoundedRect(x, y, width, height, radius) { + this.drawShape(new _math.RoundedRectangle(x, y, width, height, radius)); + + return this; + }; + + /** + * Draws a circle. + * + * @param {number} x - The X coordinate of the center of the circle + * @param {number} y - The Y coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawCircle = function drawCircle(x, y, radius) { + this.drawShape(new _math.Circle(x, y, radius)); + + return this; + }; + + /** + * Draws an ellipse. + * + * @param {number} x - The X coordinate of the center of the ellipse + * @param {number} y - The Y coordinate of the center of the ellipse + * @param {number} width - The half width of the ellipse + * @param {number} height - The half height of the ellipse + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawEllipse = function drawEllipse(x, y, width, height) { + this.drawShape(new _math.Ellipse(x, y, width, height)); + + return this; + }; + + /** + * Draws a polygon using the given path. + * + * @param {number[]|PIXI.Point[]} path - The path data used to construct the polygon. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawPolygon = function drawPolygon(path) { + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + var closed = true; + + if (points instanceof _math.Polygon) { + closed = points.closed; + points = points.points; + } + + if (!Array.isArray(points)) { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) { + points[i] = arguments[i]; // eslint-disable-line prefer-rest-params + } + } + + var shape = new _math.Polygon(points); + + shape.closed = closed; + + this.drawShape(shape); + + return this; + }; + + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.clear = function clear() { + if (this.lineWidth || this.filling || this.graphicsData.length > 0) { + this.lineWidth = 0; + this.filling = false; + + this.dirty++; + this.clearDirty++; + this.graphicsData.length = 0; + } + + return this; + }; + + /** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. + * + * @returns {boolean} True if only 1 rect. + */ + + + Graphics.prototype.isFastRect = function isFastRect() { + return this.graphicsData.length === 1 && this.graphicsData[0].shape.type === _const.SHAPES.RECT && !this.graphicsData[0].lineWidth; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderWebGL = function _renderWebGL(renderer) { + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.dirty !== this.fastRectDirty) { + this.fastRectDirty = this.dirty; + this._fastRect = this.isFastRect(); + } + + // TODO this check can be moved to dirty? + if (this._fastRect) { + this._renderSpriteRect(renderer); + } else { + renderer.setObjectRenderer(renderer.plugins.graphics); + renderer.plugins.graphics.render(this); + } + }; + + /** + * Renders a sprite rectangle. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderSpriteRect = function _renderSpriteRect(renderer) { + var rect = this.graphicsData[0].shape; + + if (!this._spriteRect) { + if (!Graphics._SPRITE_TEXTURE) { + Graphics._SPRITE_TEXTURE = _RenderTexture2.default.create(10, 10); + + var canvas = document.createElement('canvas'); + + canvas.width = 10; + canvas.height = 10; + + var context = canvas.getContext('2d'); + + context.fillStyle = 'white'; + context.fillRect(0, 0, 10, 10); + + Graphics._SPRITE_TEXTURE = _Texture2.default.fromCanvas(canvas); + } + + this._spriteRect = new _Sprite2.default(Graphics._SPRITE_TEXTURE); + } + if (this.tint === 0xffffff) { + this._spriteRect.tint = this.graphicsData[0].fillColor; + } else { + var t1 = tempColor1; + var t2 = tempColor2; + + (0, _utils.hex2rgb)(this.graphicsData[0].fillColor, t1); + (0, _utils.hex2rgb)(this.tint, t2); + + t1[0] *= t2[0]; + t1[1] *= t2[1]; + t1[2] *= t2[2]; + + this._spriteRect.tint = (0, _utils.rgb2hex)(t1); + } + this._spriteRect.alpha = this.graphicsData[0].fillAlpha; + this._spriteRect.worldAlpha = this.worldAlpha * this._spriteRect.alpha; + + Graphics._SPRITE_TEXTURE._frame.width = rect.width; + Graphics._SPRITE_TEXTURE._frame.height = rect.height; + + this._spriteRect.transform.worldTransform = this.transform.worldTransform; + + this._spriteRect.anchor.set(-rect.x / rect.width, -rect.y / rect.height); + this._spriteRect._onAnchorUpdate(); + + this._spriteRect._renderWebGL(renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.isMask === true) { + return; + } + + renderer.plugins.graphics.render(this); + }; + + /** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @private + */ + + + Graphics.prototype._calculateBounds = function _calculateBounds() { + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.updateLocalBounds(); + + this.dirty++; + this.cachedSpriteDirty = true; + } + + var lb = this._localBounds; + + this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); + }; + + /** + * Tests if a point is inside this graphics object + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Graphics.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + + if (!data.fill) { + continue; + } + + // only deal with fills.. + if (data.shape) { + if (data.shape.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + } + + return false; + }; + + /** + * Update the bounds of the object + * + */ + + + Graphics.prototype.updateLocalBounds = function updateLocalBounds() { + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) { + var shape = 0; + var x = 0; + var y = 0; + var w = 0; + var h = 0; + + for (var i = 0; i < this.graphicsData.length; i++) { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + + shape = data.shape; + + if (type === _const.SHAPES.RECT || type === _const.SHAPES.RREC) { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.CIRC) { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.ELIP) { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else { + // POLY + var points = shape.points; + + for (var j = 0; j < points.length; j += 2) { + x = points[j]; + y = points[j + 1]; + + minX = x - lineWidth < minX ? x - lineWidth : minX; + maxX = x + lineWidth > maxX ? x + lineWidth : maxX; + + minY = y - lineWidth < minY ? y - lineWidth : minY; + maxY = y + lineWidth > maxY ? y + lineWidth : maxY; + } + } + } + } else { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.minX = minX - padding; + this._localBounds.maxX = maxX + padding * 2; + + this._localBounds.minY = minY - padding; + this._localBounds.maxY = maxY + padding * 2; + }; + + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @return {PIXI.GraphicsData} The generated GraphicsData object. + */ + + + Graphics.prototype.drawShape = function drawShape(shape) { + if (this.currentPath) { + // check current path! + if (this.currentPath.shape.points.length <= 2) { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + var data = new _GraphicsData2.default(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape); + + this.graphicsData.push(data); + + if (data.type === _const.SHAPES.POLY) { + data.shape.closed = data.shape.closed || this.filling; + this.currentPath = data; + } + + this.dirty++; + + return data; + }; + + /** + * Generates a canvas texture. + * + * @param {number} scaleMode - The scale mode of the texture. + * @param {number} resolution - The resolution of the texture. + * @return {PIXI.Texture} The new texture. + */ + + + Graphics.prototype.generateCanvasTexture = function generateCanvasTexture(scaleMode) { + var resolution = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1]; + + var bounds = this.getLocalBounds(); + + var canvasBuffer = _RenderTexture2.default.create(bounds.width, bounds.height, scaleMode, resolution); + + if (!canvasRenderer) { + canvasRenderer = new _CanvasRenderer2.default(); + } + + tempMatrix.tx = -bounds.x; + tempMatrix.ty = -bounds.y; + + canvasRenderer.render(this, canvasBuffer, false, tempMatrix); + + var texture = _Texture2.default.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas, scaleMode); + + texture.baseTexture.resolution = resolution; + texture.baseTexture.update(); + + return texture; + }; + + /** + * Closes the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.closePath = function closePath() { + // ok so close path assumes next one is a hole! + var currentPath = this.currentPath; + + if (currentPath && currentPath.shape) { + currentPath.shape.close(); + } + + return this; + }; + + /** + * Adds a hole in the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.addHole = function addHole() { + // this is a hole! + var hole = this.graphicsData.pop(); + + this.currentPath = this.graphicsData[this.graphicsData.length - 1]; + + this.currentPath.addHole(hole.shape); + this.currentPath = null; + + return this; + }; + + /** + * Destroys the Graphics object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + */ + + + Graphics.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._webgl) { + for (var j = 0; j < this._webgl[id].data.length; ++j) { + this._webgl[id].data[j].destroy(); + } + } + + if (this._spriteRect) { + this._spriteRect.destroy(); + } + + this.graphicsData = null; + + this.currentPath = null; + this._webgl = null; + this._localBounds = null; + }; + + return Graphics; +}(_Container3.default); + +exports.default = Graphics; + + +Graphics._SPRITE_TEXTURE = null; + +},{"../const":78,"../display/Bounds":79,"../display/Container":80,"../math":102,"../renderers/canvas/CanvasRenderer":109,"../sprites/Sprite":133,"../textures/RenderTexture":143,"../textures/Texture":144,"../utils":152,"./GraphicsData":86,"./utils/bezierCurveTo":88}],86:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + */ +var GraphicsData = function () { + /** + * + * @param {number} lineWidth - the width of the line to draw + * @param {number} lineColor - the color of the line to draw + * @param {number} lineAlpha - the alpha of the line to draw + * @param {number} fillColor - the color of the fill + * @param {number} fillAlpha - the alpha of the fill + * @param {boolean} fill - whether or not the shape is filled with a colour + * @param {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} shape - The shape object to draw. + */ + function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) { + _classCallCheck(this, GraphicsData); + + /** + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + + /** + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /** + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /** + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /** + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /** + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /** + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /** + * @member {boolean} whether or not the shape is filled with a colour + */ + this.fill = fill; + + this.holes = []; + + /** + * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} The shape object to draw. + */ + this.shape = shape; + + /** + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + } + + /** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {PIXI.GraphicsData} Cloned GraphicsData object + */ + + + GraphicsData.prototype.clone = function clone() { + return new GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.fill, this.shape); + }; + + /** + * Adds a hole to the shape. + * + * @param {PIXI.Rectangle|PIXI.Circle} shape - The shape of the hole. + */ + + + GraphicsData.prototype.addHole = function addHole(shape) { + this.holes.push(shape); + }; + + /** + * Destroys the Graphics data. + */ + + + GraphicsData.prototype.destroy = function destroy() { + this.shape = null; + this.holes = null; + }; + + return GraphicsData; +}(); + +exports.default = GraphicsData; + +},{}],87:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they + * now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasGraphicsRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasGraphicsRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching graphics objects. + * + * @class + * @private + * @memberof PIXI + */ +var CanvasGraphicsRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The current PIXI renderer. + */ + function CanvasGraphicsRenderer(renderer) { + _classCallCheck(this, CanvasGraphicsRenderer); + + this.renderer = renderer; + } + + /** + * Renders a Graphics object to a canvas. + * + * @param {PIXI.Graphics} graphics - the actual graphics object to render + */ + + + CanvasGraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var context = renderer.context; + var worldAlpha = graphics.worldAlpha; + var transform = graphics.transform.worldTransform; + var resolution = renderer.resolution; + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) { + this.dirty = true; + } + + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + if (graphics.dirty) { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + renderer.setBlendMode(graphics.blendMode); + + for (var i = 0; i < graphics.graphicsData.length; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === _const.SHAPES.POLY) { + context.beginPath(); + + this.renderPolygon(shape.points, shape.closed, context); + + for (var j = 0; j < data.holes.length; j++) { + this.renderPolygon(data.holes[j].points, true, context); + } + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RECT) { + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + context.beginPath(); + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + }; + + /** + * Updates the tint of a graphics object + * + * @private + * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated + */ + + + CanvasGraphicsRenderer.prototype.updateGraphicsTint = function updateGraphicsTint(graphics) { + graphics._prevTint = graphics.tint; + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF) / 255; + + for (var i = 0; i < graphics.graphicsData.length; ++i) { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + // super inline cos im an optimization NAZI :) + data._fillTint = ((fillColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (fillColor & 0xFF) / 255 * tintB * 255; + + data._lineTint = ((lineColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (lineColor & 0xFF) / 255 * tintB * 255; + } + }; + + /** + * Renders a polygon. + * + * @param {PIXI.Point[]} points - The points to render + * @param {boolean} close - Should the polygon be closed + * @param {CanvasRenderingContext2D} context - The rendering context to use + */ + + + CanvasGraphicsRenderer.prototype.renderPolygon = function renderPolygon(points, close, context) { + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; ++j) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (close) { + context.closePath(); + } + }; + + /** + * destroy graphics object + * + */ + + + CanvasGraphicsRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasGraphicsRenderer; +}(); + +exports.default = CanvasGraphicsRenderer; + + +_CanvasRenderer2.default.registerPlugin('graphics', CanvasGraphicsRenderer); + +},{"../../const":78,"../../renderers/canvas/CanvasRenderer":109}],88:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = bezierCurveTo; +/** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [path=[]] - Path array to push points into + * @return {number[]} Array of points of the curve + */ +function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var path = arguments.length <= 8 || arguments[8] === undefined ? [] : arguments[8]; + + var n = 20; + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + + path.push(fromX, fromY); + + for (var i = 1, j = 0; i <= n; ++i) { + j = i / n; + + dt = 1 - j; + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + path.push(dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + return path; +} + +},{}],89:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _WebGLGraphicsData = require('./WebGLGraphicsData'); + +var _WebGLGraphicsData2 = _interopRequireDefault(_WebGLGraphicsData); + +var _PrimitiveShader = require('./shaders/PrimitiveShader'); + +var _PrimitiveShader2 = _interopRequireDefault(_PrimitiveShader); + +var _buildPoly = require('./utils/buildPoly'); + +var _buildPoly2 = _interopRequireDefault(_buildPoly); + +var _buildRectangle = require('./utils/buildRectangle'); + +var _buildRectangle2 = _interopRequireDefault(_buildRectangle); + +var _buildRoundedRectangle = require('./utils/buildRoundedRectangle'); + +var _buildRoundedRectangle2 = _interopRequireDefault(_buildRoundedRectangle); + +var _buildCircle = require('./utils/buildCircle'); + +var _buildCircle2 = _interopRequireDefault(_buildCircle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Renders the graphics object. + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var GraphicsRenderer = function (_ObjectRenderer) { + _inherits(GraphicsRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this object renderer works for. + */ + function GraphicsRenderer(renderer) { + _classCallCheck(this, GraphicsRenderer); + + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.graphicsDataPool = []; + + _this.primitiveShader = null; + + _this.gl = renderer.gl; + + // easy access! + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * Called when there is a WebGL context change + * + * @private + * + */ + + + GraphicsRenderer.prototype.onContextChange = function onContextChange() { + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.primitiveShader = new _PrimitiveShader2.default(this.gl); + }; + + /** + * Destroys this renderer. + * + */ + + + GraphicsRenderer.prototype.destroy = function destroy() { + _ObjectRenderer3.default.prototype.destroy.call(this); + + for (var i = 0; i < this.graphicsDataPool.length; ++i) { + this.graphicsDataPool[i].destroy(); + } + + this.graphicsDataPool = null; + }; + + /** + * Renders a graphics object. + * + * @param {PIXI.Graphics} graphics - The graphics object to render. + */ + + + GraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var gl = renderer.gl; + + var webGLData = void 0; + var webGL = graphics._webGL[this.CONTEXT_UID]; + + if (!webGL || graphics.dirty !== webGL.dirty) { + this.updateGraphics(graphics); + + webGL = graphics._webGL[this.CONTEXT_UID]; + } + + // This could be speeded up for sure! + var shader = this.primitiveShader; + + renderer.bindShader(shader); + renderer.state.setBlendMode(graphics.blendMode); + + for (var i = 0, n = webGL.data.length; i < n; i++) { + webGLData = webGL.data[i]; + var shaderTemp = webGLData.shader; + + renderer.bindShader(shaderTemp); + shaderTemp.uniforms.translationMatrix = graphics.transform.worldTransform.toArray(true); + shaderTemp.uniforms.tint = (0, _utils.hex2rgb)(graphics.tint); + shaderTemp.uniforms.alpha = graphics.worldAlpha; + + webGLData.vao.bind().draw(gl.TRIANGLE_STRIP, webGLData.indices.length).unbind(); + } + }; + + /** + * Updates the graphics object + * + * @private + * @param {PIXI.Graphics} graphics - The graphics object to update + */ + + + GraphicsRenderer.prototype.updateGraphics = function updateGraphics(graphics) { + var gl = this.renderer.gl; + + // get the contexts graphics object + var webGL = graphics._webGL[this.CONTEXT_UID]; + + // if the graphics object does not exist in the webGL context time to create it! + if (!webGL) { + webGL = graphics._webGL[this.CONTEXT_UID] = { lastIndex: 0, data: [], gl: gl, clearDirty: -1, dirty: -1 }; + } + + // flag the graphics as not dirty as we are about to update it... + webGL.dirty = graphics.dirty; + + // if the user cleared the graphics object we will need to clear every object + if (graphics.clearDirty !== webGL.clearDirty) { + webGL.clearDirty = graphics.clearDirty; + + // loop through and return all the webGLDatas to the object pool so than can be reused later on + for (var i = 0; i < webGL.data.length; i++) { + this.graphicsDataPool.push(webGL.data[i]); + } + + // clear the array and reset the index.. + webGL.data.length = 0; + webGL.lastIndex = 0; + } + + var webGLData = void 0; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (var _i = webGL.lastIndex; _i < graphics.graphicsData.length; _i++) { + var data = graphics.graphicsData[_i]; + + // TODO - this can be simplified + webGLData = this.getWebGLData(webGL, 0); + + if (data.type === _const.SHAPES.POLY) { + (0, _buildPoly2.default)(data, webGLData); + } + if (data.type === _const.SHAPES.RECT) { + (0, _buildRectangle2.default)(data, webGLData); + } else if (data.type === _const.SHAPES.CIRC || data.type === _const.SHAPES.ELIP) { + (0, _buildCircle2.default)(data, webGLData); + } else if (data.type === _const.SHAPES.RREC) { + (0, _buildRoundedRectangle2.default)(data, webGLData); + } + + webGL.lastIndex++; + } + + // upload all the dirty data... + for (var _i2 = 0; _i2 < webGL.data.length; _i2++) { + webGLData = webGL.data[_i2]; + + if (webGLData.dirty) { + webGLData.upload(); + } + } + }; + + /** + * + * @private + * @param {WebGLRenderingContext} gl - the current WebGL drawing context + * @param {number} type - TODO @Alvin + * @return {*} TODO + */ + + + GraphicsRenderer.prototype.getWebGLData = function getWebGLData(gl, type) { + var webGLData = gl.data[gl.data.length - 1]; + + if (!webGLData || webGLData.points.length > 320000) { + webGLData = this.graphicsDataPool.pop() || new _WebGLGraphicsData2.default(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + + webGLData.reset(type); + gl.data.push(webGLData); + } + + webGLData.dirty = true; + + return webGLData; + }; + + return GraphicsRenderer; +}(_ObjectRenderer3.default); + +exports.default = GraphicsRenderer; + + +_WebGLRenderer2.default.registerPlugin('graphics', GraphicsRenderer); + +},{"../../const":78,"../../renderers/webgl/WebGLRenderer":116,"../../renderers/webgl/utils/ObjectRenderer":126,"../../utils":152,"./WebGLGraphicsData":90,"./shaders/PrimitiveShader":91,"./utils/buildCircle":92,"./utils/buildPoly":94,"./utils/buildRectangle":95,"./utils/buildRoundedRectangle":96}],90:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * An object containing WebGL specific properties to be used by the WebGL renderer + * + * @class + * @private + * @memberof PIXI + */ +var WebGLGraphicsData = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {PIXI.Shader} shader - The shader + * @param {object} attribsState - The state for the VAO + */ + function WebGLGraphicsData(gl, shader, attribsState) { + _classCallCheck(this, WebGLGraphicsData); + + /** + * The current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // TODO does this need to be split before uploding?? + /** + * An array of color components (r,g,b) + * @member {number[]} + */ + this.color = [0, 0, 0]; // color split! + + /** + * An array of points to draw + * @member {PIXI.Point[]} + */ + this.points = []; + + /** + * The indices of the vertices + * @member {number[]} + */ + this.indices = []; + /** + * The main buffer + * @member {WebGLBuffer} + */ + this.buffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl); + + /** + * The index buffer + * @member {WebGLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl); + + /** + * Whether this graphics is dirty or not + * @member {boolean} + */ + this.dirty = true; + + this.glPoints = null; + this.glIndices = null; + + /** + * + * @member {PIXI.Shader} + */ + this.shader = shader; + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, attribsState).addIndex(this.indexBuffer).addAttribute(this.buffer, shader.attributes.aVertexPosition, gl.FLOAT, false, 4 * 6, 0).addAttribute(this.buffer, shader.attributes.aColor, gl.FLOAT, false, 4 * 6, 2 * 4); + } + + /** + * Resets the vertices and the indices + */ + + + WebGLGraphicsData.prototype.reset = function reset() { + this.points.length = 0; + this.indices.length = 0; + }; + + /** + * Binds the buffers and uploads the data + */ + + + WebGLGraphicsData.prototype.upload = function upload() { + this.glPoints = new Float32Array(this.points); + this.buffer.upload(this.glPoints); + + this.glIndices = new Uint16Array(this.indices); + this.indexBuffer.upload(this.glIndices); + + this.dirty = false; + }; + + /** + * Empties all the data + */ + + + WebGLGraphicsData.prototype.destroy = function destroy() { + this.color = null; + this.points = null; + this.indices = null; + + this.vao.destroy(); + this.buffer.destroy(); + this.indexBuffer.destroy(); + + this.gl = null; + + this.buffer = null; + this.indexBuffer = null; + + this.glPoints = null; + this.glIndices = null; + }; + + return WebGLGraphicsData; +}(); + +exports.default = WebGLGraphicsData; + +},{"pixi-gl-core":51}],91:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../../Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. + * + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ +var PrimitiveShader = function (_Shader) { + _inherits(PrimitiveShader, _Shader); + + /** + * @param {WebGLRenderingContext} gl - The webgl shader manager this shader works for. + */ + function PrimitiveShader(gl) { + _classCallCheck(this, PrimitiveShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec4 aColor;', 'uniform mat3 translationMatrix;', 'uniform mat3 projectionMatrix;', 'uniform float alpha;', 'uniform vec3 tint;', 'varying vec4 vColor;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vColor = aColor * vec4(tint * alpha, alpha);', '}'].join('\n'), + // fragment shader + ['varying vec4 vColor;', 'void main(void){', ' gl_FragColor = vColor;', '}'].join('\n'))); + } + + return PrimitiveShader; +}(_Shader3.default); + +exports.default = PrimitiveShader; + +},{"../../../Shader":77}],92:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildCircle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _const = require('../../../const'); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildCircle(graphicsData, webGLData) { + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width = void 0; + var height = void 0; + + // TODO - bit hacky?? + if (graphicsData.type === _const.SHAPES.CIRC) { + width = circleData.radius; + height = circleData.radius; + } else { + width = circleData.width; + height = circleData.height; + } + + var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); + + var seg = Math.PI * 2 / totalSegs; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + indices.push(vecPos); + + for (var i = 0; i < totalSegs + 1; i++) { + verts.push(x, y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos - 1); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (var _i = 0; _i < totalSegs + 1; _i++) { + graphicsData.points.push(x + Math.sin(seg * _i) * width, y + Math.cos(seg * _i) * height); + } + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +},{"../../../const":78,"../../../utils":152,"./buildLine":93}],93:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildLine; + +var _math = require('../../../math'); + +var _utils = require('../../../utils'); + +/** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildLine(graphicsData, webGLData) { + // TODO OPTIMISE! + var points = graphicsData.points; + + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + + // get first and last point.. figure out the middle! + var firstPoint = new _math.Point(points[0], points[1]); + var lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + // if the first point is the last point - gonna have issues :) + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var p1x = points[0]; + var p1y = points[1]; + var p2x = points[2]; + var p2y = points[3]; + var p3x = 0; + var p3y = 0; + + var perpx = -(p1y - p2y); + var perpy = p1x - p2x; + var perp2x = 0; + var perp2y = 0; + var perp3x = 0; + var perp3y = 0; + + var dist = Math.sqrt(perpx * perpx + perpy * perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx, p1y - perpy, r, g, b, alpha); + + verts.push(p1x + perpx, p1y + perpy, r, g, b, alpha); + + for (var i = 1; i < length - 1; ++i) { + p1x = points[(i - 1) * 2]; + p1y = points[(i - 1) * 2 + 1]; + + p2x = points[i * 2]; + p2y = points[i * 2 + 1]; + + p3x = points[(i + 1) * 2]; + p3y = points[(i + 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + var a1 = -perpy + p1y - (-perpy + p2y); + var b1 = -perpx + p2x - (-perpx + p1x); + var c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + var a2 = -perp2y + p3y - (-perp2y + p2y); + var b2 = -perp2x + p2x - (-perp2x + p3x); + var c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + var denom = a1 * b2 - a2 * b1; + + if (Math.abs(denom) < 0.1) { + denom += 10.1; + verts.push(p2x - perpx, p2y - perpy, r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy, r, g, b, alpha); + + continue; + } + + var px = (b1 * c2 - b2 * c1) / denom; + var py = (a2 * c1 - a1 * c2) / denom; + var pdist = (px - p2x) * (px - p2x) + (py - p2y) * (py - p2y); + + if (pdist > 196 * width * width) { + perp3x = perpx - perp2x; + perp3y = perpy - perp2y; + + dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y); + perp3x /= dist; + perp3y /= dist; + perp3x *= width; + perp3y *= width; + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x + perp3x, p2y + perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + indexCount++; + } else { + verts.push(px, py); + verts.push(r, g, b, alpha); + + verts.push(p2x - (px - p2x), p2y - (py - p2y)); + verts.push(r, g, b, alpha); + } + } + + p1x = points[(length - 2) * 2]; + p1y = points[(length - 2) * 2 + 1]; + + p2x = points[(length - 1) * 2]; + p2y = points[(length - 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + verts.push(p2x - perpx, p2y - perpy); + verts.push(r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy); + verts.push(r, g, b, alpha); + + indices.push(indexStart); + + for (var _i = 0; _i < indexCount; ++_i) { + indices.push(indexStart++); + } + + indices.push(indexStart - 1); +} + +},{"../../../math":102,"../../../utils":152}],94:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildPoly; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildPoly(graphicsData, webGLData) { + graphicsData.points = graphicsData.shape.points.slice(); + + var points = graphicsData.points; + + if (graphicsData.fill && points.length >= 6) { + var holeArray = []; + // Process holes.. + var holes = graphicsData.holes; + + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + + holeArray.push(points.length / 2); + + points = points.concat(hole.points); + } + + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = (0, _earcut2.default)(points, holeArray, 2); + + if (!triangles) { + return; + } + + var vertPos = verts.length / 6; + + for (var _i = 0; _i < triangles.length; _i += 3) { + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i + 1] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + } + + for (var _i2 = 0; _i2 < length; _i2++) { + verts.push(points[_i2 * 2], points[_i2 * 2 + 1], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth > 0) { + (0, _buildLine2.default)(graphicsData, webGLData); + } +} + +},{"../../../utils":152,"./buildLine":93,"earcut":15}],95:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRectangle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildRectangle(graphicsData, webGLData) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vertPos = verts.length / 6; + + // start + verts.push(x, y); + verts.push(r, g, b, alpha); + + verts.push(x + width, y); + verts.push(r, g, b, alpha); + + verts.push(x, y + height); + verts.push(r, g, b, alpha); + + verts.push(x + width, y + height); + verts.push(r, g, b, alpha); + + // insert 2 dead triangles.. + indices.push(vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y]; + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +},{"../../../utils":152,"./buildLine":93}],96:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRoundedRectangle; + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildRoundedRectangle(graphicsData, webGLData) { + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + + recPoints.push(x, y + radius); + quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height, recPoints); + quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius, recPoints); + quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y, recPoints); + quadraticBezierCurve(x + radius, y, x, y, x, y + radius + 0.0000000001, recPoints); + + // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. + // TODO - fix this properly, this is not very elegant.. but it works for now. + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + var triangles = (0, _earcut2.default)(recPoints, null, 2); + + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + + for (var _i = 0, _j = recPoints.length; _i < _j; _i++) { + verts.push(recPoints[_i], recPoints[++_i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @return {number[]} an array of points + */ +function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY) { + var out = arguments.length <= 6 || arguments[6] === undefined ? [] : arguments[6]; + + var n = 20; + var points = out; + + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + + function getPt(n1, n2, perc) { + var diff = n2 - n1; + + return n1 + diff * perc; + } + + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + + points.push(x, y); + } + + return points; +} + +},{"../../../utils":152,"./buildLine":93,"earcut":15}],97:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Filter = exports.SpriteMaskFilter = exports.Quad = exports.RenderTarget = exports.ObjectRenderer = exports.WebGLManager = exports.Shader = exports.CanvasRenderTarget = exports.TextureUvs = exports.VideoBaseTexture = exports.BaseRenderTexture = exports.RenderTexture = exports.BaseTexture = exports.TextureTransform = exports.Texture = exports.CanvasGraphicsRenderer = exports.GraphicsRenderer = exports.GraphicsData = exports.Graphics = exports.TextStyle = exports.Text = exports.SpriteRenderer = exports.CanvasTinter = exports.CanvasSpriteRenderer = exports.Sprite = exports.TransformBase = exports.TransformStatic = exports.Transform = exports.Container = exports.DisplayObject = exports.glCore = exports.WebGLRenderer = exports.CanvasRenderer = exports.ticker = exports.utils = undefined; + +var _const = require('./const'); + +Object.keys(_const).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _const[key]; + } + }); +}); + +var _math = require('./math'); + +Object.keys(_math).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _math[key]; + } + }); +}); + +var _pixiGlCore = require('pixi-gl-core'); + +Object.defineProperty(exports, 'glCore', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_pixiGlCore).default; + } +}); + +var _DisplayObject = require('./display/DisplayObject'); + +Object.defineProperty(exports, 'DisplayObject', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplayObject).default; + } +}); + +var _Container = require('./display/Container'); + +Object.defineProperty(exports, 'Container', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Container).default; + } +}); + +var _Transform = require('./display/Transform'); + +Object.defineProperty(exports, 'Transform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Transform).default; + } +}); + +var _TransformStatic = require('./display/TransformStatic'); + +Object.defineProperty(exports, 'TransformStatic', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformStatic).default; + } +}); + +var _TransformBase = require('./display/TransformBase'); + +Object.defineProperty(exports, 'TransformBase', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformBase).default; + } +}); + +var _Sprite = require('./sprites/Sprite'); + +Object.defineProperty(exports, 'Sprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Sprite).default; + } +}); + +var _CanvasSpriteRenderer = require('./sprites/canvas/CanvasSpriteRenderer'); + +Object.defineProperty(exports, 'CanvasSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasSpriteRenderer).default; + } +}); + +var _CanvasTinter = require('./sprites/canvas/CanvasTinter'); + +Object.defineProperty(exports, 'CanvasTinter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasTinter).default; + } +}); + +var _SpriteRenderer = require('./sprites/webgl/SpriteRenderer'); + +Object.defineProperty(exports, 'SpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteRenderer).default; + } +}); + +var _Text = require('./text/Text'); + +Object.defineProperty(exports, 'Text', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Text).default; + } +}); + +var _TextStyle = require('./text/TextStyle'); + +Object.defineProperty(exports, 'TextStyle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextStyle).default; + } +}); + +var _Graphics = require('./graphics/Graphics'); + +Object.defineProperty(exports, 'Graphics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Graphics).default; + } +}); + +var _GraphicsData = require('./graphics/GraphicsData'); + +Object.defineProperty(exports, 'GraphicsData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsData).default; + } +}); + +var _GraphicsRenderer = require('./graphics/webgl/GraphicsRenderer'); + +Object.defineProperty(exports, 'GraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsRenderer).default; + } +}); + +var _CanvasGraphicsRenderer = require('./graphics/canvas/CanvasGraphicsRenderer'); + +Object.defineProperty(exports, 'CanvasGraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasGraphicsRenderer).default; + } +}); + +var _Texture = require('./textures/Texture'); + +Object.defineProperty(exports, 'Texture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Texture).default; + } +}); + +var _TextureTransform = require('./textures/TextureTransform'); + +Object.defineProperty(exports, 'TextureTransform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureTransform).default; + } +}); + +var _BaseTexture = require('./textures/BaseTexture'); + +Object.defineProperty(exports, 'BaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseTexture).default; + } +}); + +var _RenderTexture = require('./textures/RenderTexture'); + +Object.defineProperty(exports, 'RenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTexture).default; + } +}); + +var _BaseRenderTexture = require('./textures/BaseRenderTexture'); + +Object.defineProperty(exports, 'BaseRenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseRenderTexture).default; + } +}); + +var _VideoBaseTexture = require('./textures/VideoBaseTexture'); + +Object.defineProperty(exports, 'VideoBaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VideoBaseTexture).default; + } +}); + +var _TextureUvs = require('./textures/TextureUvs'); + +Object.defineProperty(exports, 'TextureUvs', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureUvs).default; + } +}); + +var _CanvasRenderTarget = require('./renderers/canvas/utils/CanvasRenderTarget'); + +Object.defineProperty(exports, 'CanvasRenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasRenderTarget).default; + } +}); + +var _Shader = require('./Shader'); + +Object.defineProperty(exports, 'Shader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Shader).default; + } +}); + +var _WebGLManager = require('./renderers/webgl/managers/WebGLManager'); + +Object.defineProperty(exports, 'WebGLManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLManager).default; + } +}); + +var _ObjectRenderer = require('./renderers/webgl/utils/ObjectRenderer'); + +Object.defineProperty(exports, 'ObjectRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObjectRenderer).default; + } +}); + +var _RenderTarget = require('./renderers/webgl/utils/RenderTarget'); + +Object.defineProperty(exports, 'RenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTarget).default; + } +}); + +var _Quad = require('./renderers/webgl/utils/Quad'); + +Object.defineProperty(exports, 'Quad', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Quad).default; + } +}); + +var _SpriteMaskFilter = require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter'); + +Object.defineProperty(exports, 'SpriteMaskFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteMaskFilter).default; + } +}); + +var _Filter = require('./renderers/webgl/filters/Filter'); + +Object.defineProperty(exports, 'Filter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Filter).default; + } +}); +exports.autoDetectRenderer = autoDetectRenderer; + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _ticker = require('./ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @namespace PIXI + */ +exports.utils = utils; +exports.ticker = ticker; +exports.CanvasRenderer = _CanvasRenderer2.default; +exports.WebGLRenderer = _WebGLRenderer2.default; + + +/** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by + * the browser then this function will return a canvas renderer + * + * @memberof PIXI + * @param {number} [width=800] - the width of the renderers view + * @param {number} [height=600] - the height of the renderers view + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [noWebGL=false] - prevents selection of WebGL renderer, even if such is present + * @return {PIXI.WebGLRenderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ +function autoDetectRenderer() { + var width = arguments.length <= 0 || arguments[0] === undefined ? 800 : arguments[0]; + var height = arguments.length <= 1 || arguments[1] === undefined ? 600 : arguments[1]; + var options = arguments[2]; + var noWebGL = arguments[3]; + + if (!noWebGL && utils.isWebGLSupported()) { + return new _WebGLRenderer2.default(width, height, options); + } + + return new _CanvasRenderer2.default(width, height, options); +} + +},{"./Shader":77,"./const":78,"./display/Container":80,"./display/DisplayObject":81,"./display/Transform":82,"./display/TransformBase":83,"./display/TransformStatic":84,"./graphics/Graphics":85,"./graphics/GraphicsData":86,"./graphics/canvas/CanvasGraphicsRenderer":87,"./graphics/webgl/GraphicsRenderer":89,"./math":102,"./renderers/canvas/CanvasRenderer":109,"./renderers/canvas/utils/CanvasRenderTarget":111,"./renderers/webgl/WebGLRenderer":116,"./renderers/webgl/filters/Filter":118,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":121,"./renderers/webgl/managers/WebGLManager":125,"./renderers/webgl/utils/ObjectRenderer":126,"./renderers/webgl/utils/Quad":127,"./renderers/webgl/utils/RenderTarget":128,"./sprites/Sprite":133,"./sprites/canvas/CanvasSpriteRenderer":134,"./sprites/canvas/CanvasTinter":135,"./sprites/webgl/SpriteRenderer":137,"./text/Text":139,"./text/TextStyle":140,"./textures/BaseRenderTexture":141,"./textures/BaseTexture":142,"./textures/RenderTexture":143,"./textures/Texture":144,"./textures/TextureTransform":145,"./textures/TextureUvs":146,"./textures/VideoBaseTexture":147,"./ticker":149,"./utils":152,"pixi-gl-core":51}],98:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Matrix = require('./Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16 + +var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; +var tempMatrices = []; + +var mul = []; + +function signum(x) { + if (x < 0) { + return -1; + } + if (x > 0) { + return 1; + } + + return 0; +} + +function init() { + for (var i = 0; i < 16; i++) { + var row = []; + + mul.push(row); + + for (var j = 0; j < 16; j++) { + var _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); + var _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); + var _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); + var _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); + + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + + for (var _i = 0; _i < 16; _i++) { + var mat = new _Matrix2.default(); + + mat.set(ux[_i], uy[_i], vx[_i], vy[_i], 0, 0); + tempMatrices.push(mat); + } +} + +init(); + +/** + * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, + * D8 is the same but with diagonals. Used for texture rotations. + * + * Vector xX(i), xY(i) is U-axis of sprite with rotation i + * Vector yY(i), yY(i) is V-axis of sprite with rotation i + * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) + * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) + * This is the small part of gameofbombs.com portal system. It works. + * + * @author Ivan @ivanpopelyshev + * + * @namespace PIXI.GroupD8 + */ +var GroupD8 = { + E: 0, + SE: 1, + S: 2, + SW: 3, + W: 4, + NW: 5, + N: 6, + NE: 7, + MIRROR_VERTICAL: 8, + MIRROR_HORIZONTAL: 12, + uX: function uX(ind) { + return ux[ind]; + }, + uY: function uY(ind) { + return uy[ind]; + }, + vX: function vX(ind) { + return vx[ind]; + }, + vY: function vY(ind) { + return vy[ind]; + }, + inv: function inv(rotation) { + if (rotation & 8) { + return rotation & 15; + } + + return -rotation & 7; + }, + add: function add(rotationSecond, rotationFirst) { + return mul[rotationSecond][rotationFirst]; + }, + sub: function sub(rotationSecond, rotationFirst) { + return mul[rotationSecond][GroupD8.inv(rotationFirst)]; + }, + + /** + * Adds 180 degrees to rotation. Commutative operation. + * + * @method + * @param {number} rotation - The number to rotate. + * @returns {number} rotated number + */ + rotate180: function rotate180(rotation) { + return rotation ^ 4; + }, + + /** + * I dont know why sometimes width and heights needs to be swapped. We'll fix it later. + * + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the width/height should be swapped. + */ + isSwapWidthHeight: function isSwapWidthHeight(rotation) { + return (rotation & 3) === 2; + }, + + /** + * @param {number} dx - TODO + * @param {number} dy - TODO + * + * @return {number} TODO + */ + byDirection: function byDirection(dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return GroupD8.S; + } + + return GroupD8.N; + } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return GroupD8.E; + } + + return GroupD8.W; + } else if (dy > 0) { + if (dx > 0) { + return GroupD8.SE; + } + + return GroupD8.SW; + } else if (dx > 0) { + return GroupD8.NE; + } + + return GroupD8.NW; + }, + + /** + * Helps sprite to compensate texture packer rotation. + * + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {number} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function matrixAppendRotationInv(matrix, rotation) { + var tx = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2]; + var ty = arguments.length <= 3 || arguments[3] === undefined ? 0 : arguments[3]; + + // Packer used "rotation", we use "inv(rotation)" + var mat = tempMatrices[GroupD8.inv(rotation)]; + + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + } +}; + +exports.default = GroupD8; + +},{"./Matrix":99}],99:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Point = require('./Point'); + +var _Point2 = _interopRequireDefault(_Point); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The pixi Matrix class as an object, which makes it a lot faster, + * here is a representation of it : + * | a | b | tx| + * | c | d | ty| + * | 0 | 0 | 1 | + * + * @class + * @memberof PIXI + */ +var Matrix = function () { + /** + * + */ + function Matrix() { + _classCallCheck(this, Matrix); + + /** + * @member {number} + * @default 1 + */ + this.a = 1; + + /** + * @member {number} + * @default 0 + */ + this.b = 0; + + /** + * @member {number} + * @default 0 + */ + this.c = 0; + + /** + * @member {number} + * @default 1 + */ + this.d = 1; + + /** + * @member {number} + * @default 0 + */ + this.tx = 0; + + /** + * @member {number} + * @default 0 + */ + this.ty = 0; + + this.array = null; + } + + /** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @param {number[]} array - The array that the matrix will be populated from. + */ + + + Matrix.prototype.fromArray = function fromArray(array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + }; + + /** + * sets the matrix properties + * + * @param {number} a - Matrix component + * @param {number} b - Matrix component + * @param {number} c - Matrix component + * @param {number} d - Matrix component + * @param {number} tx - Matrix component + * @param {number} ty - Matrix component + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.set = function set(a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + }; + + /** + * Creates an array from the current Matrix object. + * + * @param {boolean} transpose - Whether we need to transpose the matrix or not + * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out + * @return {number[]} the newly created array which contains the matrix + */ + + + Matrix.prototype.toArray = function toArray(transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + + var array = out || this.array; + + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + }; + + /** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, transformed through this matrix + */ + + + Matrix.prototype.apply = function apply(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; + + return newPos; + }; + + /** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, inverse-transformed through this matrix + */ + + + Matrix.prototype.applyInverse = function applyInverse(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var id = 1 / (this.a * this.d + this.c * -this.b); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + }; + + /** + * Translates the matrix on the x and y. + * + * @param {number} x How much to translate x by + * @param {number} y How much to translate y by + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.translate = function translate(x, y) { + this.tx += x; + this.ty += y; + + return this; + }; + + /** + * Applies a scale transformation to the matrix. + * + * @param {number} x The amount to scale horizontally + * @param {number} y The amount to scale vertically + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.scale = function scale(x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + }; + + /** + * Applies a rotation transformation to the matrix. + * + * @param {number} angle - The angle in radians. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.rotate = function rotate(angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos - this.b * sin; + this.b = a1 * sin + this.b * cos; + this.c = c1 * cos - this.d * sin; + this.d = c1 * sin + this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + }; + + /** + * Appends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to append. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.append = function append(matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + }; + + /** + * Sets the matrix based on all the available properties + * + * @param {number} x - Position on the x axis + * @param {number} y - Position on the y axis + * @param {number} pivotX - Pivot on the x axis + * @param {number} pivotY - Pivot on the y axis + * @param {number} scaleX - Scale on the x axis + * @param {number} scaleY - Scale on the y axis + * @param {number} rotation - Rotation in radians + * @param {number} skewX - Skew on the x axis + * @param {number} skewY - Skew on the y axis + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.setTransform = function setTransform(x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + var sr = Math.sin(rotation); + var cr = Math.cos(rotation); + var cy = Math.cos(skewY); + var sy = Math.sin(skewY); + var nsx = -Math.sin(skewX); + var cx = Math.cos(skewX); + + var a = cr * scaleX; + var b = sr * scaleX; + var c = -sr * scaleY; + var d = cr * scaleY; + + this.a = cy * a + sy * c; + this.b = cy * b + sy * d; + this.c = nsx * a + cx * c; + this.d = nsx * b + cx * d; + + this.tx = x + (pivotX * a + pivotY * c); + this.ty = y + (pivotX * b + pivotY * d); + + return this; + }; + + /** + * Prepends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to prepend + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.prepend = function prepend(matrix) { + var tx1 = this.tx; + + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + + this.a = a1 * matrix.a + this.b * matrix.c; + this.b = a1 * matrix.b + this.b * matrix.d; + this.c = c1 * matrix.a + this.d * matrix.c; + this.d = c1 * matrix.b + this.d * matrix.d; + } + + this.tx = tx1 * matrix.a + this.ty * matrix.c + matrix.tx; + this.ty = tx1 * matrix.b + this.ty * matrix.d + matrix.ty; + + return this; + }; + + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * + * @param {PIXI.Transform|PIXI.TransformStatic} transform - The transform to apply the properties to. + * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properies + */ + + + Matrix.prototype.decompose = function decompose(transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + + var skewX = Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + + var delta = Math.abs(1 - skewX / skewY); + + if (delta < 0.00001) { + transform.rotation = skewY; + + if (a < 0 && d >= 0) { + transform.rotation += transform.rotation <= 0 ? Math.PI : -Math.PI; + } + + transform.skew.x = transform.skew.y = 0; + } else { + transform.skew.x = skewX; + transform.skew.y = skewY; + } + + // next set scale + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); + + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; + + return transform; + }; + + /** + * Inverts this matrix + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.invert = function invert() { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1 * d1 - b1 * c1; + + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = (c1 * this.ty - d1 * tx1) / n; + this.ty = -(a1 * this.ty - b1 * tx1) / n; + + return this; + }; + + /** + * Resets this Matix to an identity (default) matrix. + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.identity = function identity() { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + + return this; + }; + + /** + * Creates a new Matrix object with the same values as this one. + * + * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. + */ + + + Matrix.prototype.clone = function clone() { + var matrix = new Matrix(); + + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * Changes the values of the given matrix to be the same as the ones in this matrix + * + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @return {PIXI.Matrix} The matrix given in parameter with its values updated. + */ + + + Matrix.prototype.copy = function copy(matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * A default (identity) matrix + * + * @static + * @const + */ + + + _createClass(Matrix, null, [{ + key: 'IDENTITY', + get: function get() { + return new Matrix(); + } + + /** + * A temp matrix + * + * @static + * @const + */ + + }, { + key: 'TEMP_MATRIX', + get: function get() { + return new Matrix(); + } + }]); + + return Matrix; +}(); + +exports.default = Matrix; + +},{"./Point":101}],100:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * An observable point is a point that triggers a callback when the point's position is changed. + * + * @class + * @memberof PIXI + */ +var ObservablePoint = function () { + /** + * @param {Function} cb - callback when changed + * @param {object} scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope) { + var x = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2]; + var y = arguments.length <= 3 || arguments[3] === undefined ? 0 : arguments[3]; + + _classCallCheck(this, ObservablePoint); + + this._x = x; + this._y = y; + + this.cb = cb; + this.scope = scope; + } + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + ObservablePoint.prototype.set = function set(x, y) { + var _x = x || 0; + var _y = y || (y !== 0 ? _x : 0); + + if (this._x !== _x || this._y !== _y) { + this._x = _x; + this._y = _y; + this.cb.call(this.scope); + } + }; + + /** + * Copies the data from another point + * + * @param {PIXI.Point|PIXI.ObservablePoint} point - point to copy from + */ + + + ObservablePoint.prototype.copy = function copy(point) { + if (this._x !== point.x || this._y !== point.y) { + this._x = point.x; + this._y = point.y; + this.cb.call(this.scope); + } + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + * @memberof PIXI.ObservablePoint# + */ + + + _createClass(ObservablePoint, [{ + key: "x", + get: function get() { + return this._x; + } + + /** + * Sets the X component. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + } + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + * @memberof PIXI.ObservablePoint# + */ + + }, { + key: "y", + get: function get() { + return this._y; + } + + /** + * Sets the Y component. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + } + }]); + + return ObservablePoint; +}(); + +exports.default = ObservablePoint; + +},{}],101:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * + * @class + * @memberof PIXI + */ +var Point = function () { + /** + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function Point() { + var x = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var y = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + + _classCallCheck(this, Point); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + } + + /** + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point + */ + + + Point.prototype.clone = function clone() { + return new Point(this.x, this.y); + }; + + /** + * Copies x and y from the given point + * + * @param {PIXI.Point} p - The point to copy. + */ + + + Point.prototype.copy = function copy(p) { + this.set(p.x, p.y); + }; + + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.Point} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + + + Point.prototype.equals = function equals(p) { + return p.x === this.x && p.y === this.y; + }; + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + Point.prototype.set = function set(x, y) { + this.x = x || 0; + this.y = y || (y !== 0 ? this.x : 0); + }; + + return Point; +}(); + +exports.default = Point; + +},{}],102:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('./Point'); + +Object.defineProperty(exports, 'Point', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Point).default; + } +}); + +var _ObservablePoint = require('./ObservablePoint'); + +Object.defineProperty(exports, 'ObservablePoint', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObservablePoint).default; + } +}); + +var _Matrix = require('./Matrix'); + +Object.defineProperty(exports, 'Matrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Matrix).default; + } +}); + +var _GroupD = require('./GroupD8'); + +Object.defineProperty(exports, 'GroupD8', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GroupD).default; + } +}); + +var _Circle = require('./shapes/Circle'); + +Object.defineProperty(exports, 'Circle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Circle).default; + } +}); + +var _Ellipse = require('./shapes/Ellipse'); + +Object.defineProperty(exports, 'Ellipse', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Ellipse).default; + } +}); + +var _Polygon = require('./shapes/Polygon'); + +Object.defineProperty(exports, 'Polygon', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Polygon).default; + } +}); + +var _Rectangle = require('./shapes/Rectangle'); + +Object.defineProperty(exports, 'Rectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rectangle).default; + } +}); + +var _RoundedRectangle = require('./shapes/RoundedRectangle'); + +Object.defineProperty(exports, 'RoundedRectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RoundedRectangle).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./GroupD8":98,"./Matrix":99,"./ObservablePoint":100,"./Point":101,"./shapes/Circle":103,"./shapes/Ellipse":104,"./shapes/Polygon":105,"./shapes/Rectangle":106,"./shapes/RoundedRectangle":107}],103:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Circle object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Circle = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [radius=0] - The radius of the circle + */ + function Circle() { + var x = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var y = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + var radius = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2]; + + _classCallCheck(this, Circle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.CIRC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.CIRC; + } + + /** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ + + + Circle.prototype.clone = function clone() { + return new Circle(this.x, this.y, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this circle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Circle + */ + + + Circle.prototype.contains = function contains(x, y) { + if (this.radius <= 0) { + return false; + } + + var r2 = this.radius * this.radius; + var dx = this.x - x; + var dy = this.y - y; + + dx *= dx; + dy *= dy; + + return dx + dy <= r2; + }; + + /** + * Returns the framing rectangle of the circle as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Circle.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + + return Circle; +}(); + +exports.default = Circle; + +},{"../../const":78,"./Rectangle":106}],104:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Ellipse object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Ellipse = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [width=0] - The half width of this ellipse + * @param {number} [height=0] - The half height of this ellipse + */ + function Ellipse() { + var x = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var y = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + var width = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2]; + var height = arguments.length <= 3 || arguments[3] === undefined ? 0 : arguments[3]; + + _classCallCheck(this, Ellipse); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.ELIP + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.ELIP; + } + + /** + * Creates a clone of this Ellipse instance + * + * @return {PIXI.Ellipse} a copy of the ellipse + */ + + + Ellipse.prototype.clone = function clone() { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coords are within this ellipse + */ + + + Ellipse.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + // normalize the coords to an ellipse with center 0,0 + var normx = (x - this.x) / this.width; + var normy = (y - this.y) / this.height; + + normx *= normx; + normy *= normy; + + return normx + normy <= 1; + }; + + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Ellipse.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.width, this.y - this.height, this.width, this.height); + }; + + return Ellipse; +}(); + +exports.default = Ellipse; + +},{"../../const":78,"./Rectangle":106}],105:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('../Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Polygon = function () { + /** + * @param {PIXI.Point[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + for (var _len = arguments.length, points = Array(_len), _key = 0; _key < _len; _key++) { + points[_key] = arguments[_key]; + } + + _classCallCheck(this, Polygon); + + if (Array.isArray(points[0])) { + points = points[0]; + } + + // if this is an array of points, convert it to a flat array of numbers + if (points[0] instanceof _Point2.default) { + var p = []; + + for (var i = 0, il = points.length; i < il; i++) { + p.push(points[i].x, points[i].y); + } + + points = p; + } + + this.closed = true; + + /** + * An array of the points of this polygon + * + * @member {number[]} + */ + this.points = points; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.POLY + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.POLY; + } + + /** + * Creates a clone of this polygon + * + * @return {PIXI.Polygon} a copy of the polygon + */ + + + Polygon.prototype.clone = function clone() { + return new Polygon(this.points.slice()); + }; + + /** + * Closes the polygon, adding points if necessary. + * + */ + + + Polygon.prototype.close = function close() { + var points = this.points; + + // close the poly if the value is true! + if (points[0] !== points[points.length - 2] || points[1] !== points[points.length - 1]) { + points.push(points[0], points[1]); + } + }; + + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this polygon + */ + + + Polygon.prototype.contains = function contains(x, y) { + var inside = false; + + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + + for (var i = 0, j = length - 1; i < length; j = ++i) { + var xi = this.points[i * 2]; + var yi = this.points[i * 2 + 1]; + var xj = this.points[j * 2]; + var yj = this.points[j * 2 + 1]; + var intersect = yi > y !== yj > y && x < (xj - xi) * ((y - yi) / (yj - yi)) + xi; + + if (intersect) { + inside = !inside; + } + } + + return inside; + }; + + return Polygon; +}(); + +exports.default = Polygon; + +},{"../../const":78,"../Point":101}],106:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * + * @class + * @memberof PIXI + */ +var Rectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle + * @param {number} [width=0] - The overall width of this rectangle + * @param {number} [height=0] - The overall height of this rectangle + */ + function Rectangle() { + var x = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var y = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + var width = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2]; + var height = arguments.length <= 3 || arguments[3] === undefined ? 0 : arguments[3]; + + _classCallCheck(this, Rectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.RECT + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RECT; + } + + /** + * returns the left edge of the rectangle + * + * @member {number} + * @memberof PIXI.Rectangle# + */ + + + /** + * Creates a clone of this Rectangle + * + * @return {PIXI.Rectangle} a copy of the rectangle + */ + Rectangle.prototype.clone = function clone() { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + + /** + * Copies another rectangle to this one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to copy. + * @return {PIXI.Rectanle} Returns itself. + */ + + + Rectangle.prototype.copy = function copy(rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + + return this; + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rectangle + */ + + + Rectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + + return false; + }; + + /** + * Pads the rectangle making it grow in all directions. + * + * @param {number} paddingX - The horizontal padding amount. + * @param {number} paddingY - The vertical padding amount. + */ + + + Rectangle.prototype.pad = function pad(paddingX, paddingY) { + paddingX = paddingX || 0; + paddingY = paddingY || (paddingY !== 0 ? paddingX : 0); + + this.x -= paddingX; + this.y -= paddingY; + + this.width += paddingX * 2; + this.height += paddingY * 2; + }; + + /** + * Fits this rectangle around the passed one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to fit. + */ + + + Rectangle.prototype.fit = function fit(rectangle) { + if (this.x < rectangle.x) { + this.width += this.x; + if (this.width < 0) { + this.width = 0; + } + + this.x = rectangle.x; + } + + if (this.y < rectangle.y) { + this.height += this.y; + if (this.height < 0) { + this.height = 0; + } + this.y = rectangle.y; + } + + if (this.x + this.width > rectangle.x + rectangle.width) { + this.width = rectangle.width - this.x; + if (this.width < 0) { + this.width = 0; + } + } + + if (this.y + this.height > rectangle.y + rectangle.height) { + this.height = rectangle.height - this.y; + if (this.height < 0) { + this.height = 0; + } + } + }; + + /** + * Enlarges this rectangle to include the passed rectangle. + * + * @param {PIXI.Rectangle} rect - The rectangle to include. + */ + + + Rectangle.prototype.enlarge = function enlarge(rect) { + if (rect === Rectangle.EMPTY) { + return; + } + + var x1 = Math.min(this.x, rect.x); + var x2 = Math.max(this.x + this.width, rect.x + rect.width); + var y1 = Math.min(this.y, rect.y); + var y2 = Math.max(this.y + this.height, rect.y + rect.height); + + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + }; + + _createClass(Rectangle, [{ + key: 'left', + get: function get() { + return this.x; + } + + /** + * returns the right edge of the rectangle + * + * @member {number} + * @memberof PIXI.Rectangle + */ + + }, { + key: 'right', + get: function get() { + return this.x + this.width; + } + + /** + * returns the top edge of the rectangle + * + * @member {number} + * @memberof PIXI.Rectangle + */ + + }, { + key: 'top', + get: function get() { + return this.y; + } + + /** + * returns the bottom edge of the rectangle + * + * @member {number} + * @memberof PIXI.Rectangle + */ + + }, { + key: 'bottom', + get: function get() { + return this.y + this.height; + } + + /** + * A constant empty rectangle. + * + * @static + * @constant + */ + + }], [{ + key: 'EMPTY', + get: function get() { + return new Rectangle(0, 0, 0, 0); + } + }]); + + return Rectangle; +}(); + +exports.default = Rectangle; + +},{"../../const":78}],107:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. + * + * @class + * @memberof PIXI + */ +var RoundedRectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle + * @param {number} [width=0] - The overall width of this rounded rectangle + * @param {number} [height=0] - The overall height of this rounded rectangle + * @param {number} [radius=20] - Controls the radius of the rounded corners + */ + function RoundedRectangle() { + var x = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var y = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + var width = arguments.length <= 2 || arguments[2] === undefined ? 0 : arguments[2]; + var height = arguments.length <= 3 || arguments[3] === undefined ? 0 : arguments[3]; + var radius = arguments.length <= 4 || arguments[4] === undefined ? 20 : arguments[4]; + + _classCallCheck(this, RoundedRectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * @member {number} + * @default 20 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readonly + * @default PIXI.SHAPES.RREC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RREC; + } + + /** + * Creates a clone of this Rounded Rectangle + * + * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle + */ + + + RoundedRectangle.prototype.clone = function clone() { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + */ + + + RoundedRectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + return true; + } + } + + return false; + }; + + return RoundedRectangle; +}(); + +exports.default = RoundedRectangle; + +},{"../../const":78}],108:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _math = require('../math'); + +var _const = require('../const'); + +var _Container = require('../display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMatrix = new _math.Matrix(); + +/** + * The SystemRenderer is the base for a Pixi Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.WebGLRenderer} which can be used for rendering a Pixi scene. + * + * @abstract + * @class + * @extends EventEmitter + * @memberof PIXI + */ + +var SystemRenderer = function (_EventEmitter) { + _inherits(SystemRenderer, _EventEmitter); + + /** + * @param {string} system - The name of the system this renderer is for. + * @param {number} [width=800] - the width of the canvas view + * @param {number} [height=600] - the height of the canvas view + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function SystemRenderer(system, width, height, options) { + _classCallCheck(this, SystemRenderer); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + (0, _utils.sayHello)(system); + + // prepare options + if (options) { + for (var i in _const.DEFAULT_RENDER_OPTIONS) { + if (typeof options[i] === 'undefined') { + options[i] = _const.DEFAULT_RENDER_OPTIONS[i]; + } + } + } else { + options = _const.DEFAULT_RENDER_OPTIONS; + } + + /** + * The type of the renderer. + * + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.UNKNOWN; + + /** + * The width of the canvas view + * + * @member {number} + * @default 800 + */ + _this.width = width || 800; + + /** + * The height of the canvas view + * + * @member {number} + * @default 600 + */ + _this.height = height || 600; + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.view = options.view || document.createElement('canvas'); + + /** + * The resolution / device pixel ratio of the renderer + * + * @member {number} + * @default 1 + */ + _this.resolution = options.resolution; + + /** + * Whether the render view is transparent + * + * @member {boolean} + */ + _this.transparent = options.transparent; + + /** + * Whether the render view should be resized automatically + * + * @member {boolean} + */ + _this.autoResize = options.autoResize || false; + + /** + * Tracks the blend modes useful for this renderer. + * + * @member {object} + */ + _this.blendModes = null; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent Pixi will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent Pixi will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example if + * your game has a canvas filling background image you often don't need this set. + * + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + * + * @member {boolean} + */ + _this.roundPixels = options.roundPixels; + + /** + * The background color as a number. + * + * @member {number} + * @private + */ + _this._backgroundColor = 0x000000; + + /** + * The background color as an [R, G, B] array. + * + * @member {number[]} + * @private + */ + _this._backgroundColorRgba = [0, 0, 0, 0]; + + /** + * The background color as a string. + * + * @member {string} + * @private + */ + _this._backgroundColorString = '#000000'; + + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + + /** + * This temporary display object used as the parent of the currently being rendered item + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._tempDisplayObjectParent = new _Container2.default(); + + /** + * The last root object that the renderer tried to render. + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._lastObjectRendered = _this._tempDisplayObjectParent; + return _this; + } + + /** + * Resizes the canvas view to the specified width and height + * + * @param {number} width - the new width of the canvas view + * @param {number} height - the new height of the canvas view + */ + + + SystemRenderer.prototype.resize = function resize(width, height) { + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) { + this.view.style.width = this.width / this.resolution + 'px'; + this.view.style.height = this.height / this.resolution + 'px'; + } + }; + + /** + * Useful function that returns a texture of the display object that can then be used to create sprites + * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. + * + * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from + * @param {number} scaleMode - Should be one of the scaleMode consts + * @param {number} resolution - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.Texture} a texture of the graphics object + */ + + + SystemRenderer.prototype.generateTexture = function generateTexture(displayObject, scaleMode, resolution) { + var bounds = displayObject.getLocalBounds(); + + var renderTexture = _RenderTexture2.default.create(bounds.width | 0, bounds.height | 0, scaleMode, resolution); + + tempMatrix.tx = -bounds.x; + tempMatrix.ty = -bounds.y; + + this.render(displayObject, renderTexture, false, tempMatrix, true); + + return renderTexture; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + SystemRenderer.prototype.destroy = function destroy(removeView) { + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } + + this.type = _const.RENDERER_TYPE.UNKNOWN; + + this.width = 0; + this.height = 0; + + this.view = null; + + this.resolution = 0; + + this.transparent = false; + + this.autoResize = false; + + this.blendModes = null; + + this.preserveDrawingBuffer = false; + this.clearBeforeRender = false; + + this.roundPixels = false; + + this._backgroundColor = 0; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + + this.backgroundColor = 0; + this._tempDisplayObjectParent = null; + this._lastObjectRendered = null; + }; + + /** + * The background color to fill if not transparent + * + * @member {number} + * @memberof PIXI.SystemRenderer# + */ + + + _createClass(SystemRenderer, [{ + key: 'backgroundColor', + get: function get() { + return this._backgroundColor; + } + + /** + * Sets the background color. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this._backgroundColor = value; + this._backgroundColorString = (0, _utils.hex2string)(value); + (0, _utils.hex2rgb)(value, this._backgroundColorRgba); + } + }]); + + return SystemRenderer; +}(_eventemitter2.default); + +exports.default = SystemRenderer; + +},{"../const":78,"../display/Container":80,"../math":102,"../textures/RenderTexture":143,"../utils":152,"eventemitter3":16}],109:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _CanvasMaskManager = require('./utils/CanvasMaskManager'); + +var _CanvasMaskManager2 = _interopRequireDefault(_CanvasMaskManager); + +var _CanvasRenderTarget = require('./utils/CanvasRenderTarget'); + +var _CanvasRenderTarget2 = _interopRequireDefault(_CanvasRenderTarget); + +var _mapCanvasBlendModesToPixi = require('./utils/mapCanvasBlendModesToPixi'); + +var _mapCanvasBlendModesToPixi2 = _interopRequireDefault(_mapCanvasBlendModesToPixi); + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should + * be used for browsers that do not support WebGL. Don't forget to add the CanvasRenderer.view to + * your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ +var CanvasRenderer = function (_SystemRenderer) { + _inherits(CanvasRenderer, _SystemRenderer); + + /** + * @param {number} [width=800] - the width of the canvas view + * @param {number} [height=600] - the height of the canvas view + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function CanvasRenderer(width, height) { + var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + + _classCallCheck(this, CanvasRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'Canvas', width, height, options)); + + _this.type = _const.RENDERER_TYPE.CANVAS; + + /** + * The canvas 2d context that everything is drawn with. + * + * @member {CanvasRenderingContext2D} + */ + _this.rootContext = _this.view.getContext('2d', { alpha: _this.transparent }); + + /** + * Boolean flag controlling canvas refresh. + * + * @member {boolean} + */ + _this.refresh = true; + + /** + * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. + * + * @member {PIXI.CanvasMaskManager} + */ + _this.maskManager = new _CanvasMaskManager2.default(_this); + + /** + * The canvas property used to set the canvas smoothing property. + * + * @member {string} + */ + _this.smoothProperty = 'imageSmoothingEnabled'; + + if (!_this.rootContext.imageSmoothingEnabled) { + if (_this.rootContext.webkitImageSmoothingEnabled) { + _this.smoothProperty = 'webkitImageSmoothingEnabled'; + } else if (_this.rootContext.mozImageSmoothingEnabled) { + _this.smoothProperty = 'mozImageSmoothingEnabled'; + } else if (_this.rootContext.oImageSmoothingEnabled) { + _this.smoothProperty = 'oImageSmoothingEnabled'; + } else if (_this.rootContext.msImageSmoothingEnabled) { + _this.smoothProperty = 'msImageSmoothingEnabled'; + } + } + + _this.initPlugins(); + + _this.blendModes = (0, _mapCanvasBlendModesToPixi2.default)(); + _this._activeBlendMode = null; + + _this.context = null; + _this.renderingToScreen = false; + + _this.resize(width, height); + return _this; + } + + /** + * Renders the object to this canvas view + * + * @param {PIXI.DisplayObject} displayObject - The object to be rendered + * @param {PIXI.RenderTexture} [renderTexture] - A render texture to be rendered to. + * If unset, it will render to the root context. + * @param {boolean} [clear=false] - Whether to clear the canvas before drawing + * @param {PIXI.Transform} [transform] - A transformation to be applied + * @param {boolean} [skipUpdateTransform=false] - Whether to skip the update transform + */ + + + CanvasRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!this.view) { + return; + } + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + if (renderTexture) { + renderTexture = renderTexture.baseTexture || renderTexture; + + if (!renderTexture._canvasRenderTarget) { + renderTexture._canvasRenderTarget = new _CanvasRenderTarget2.default(renderTexture.width, renderTexture.height, renderTexture.resolution); + renderTexture.source = renderTexture._canvasRenderTarget.canvas; + renderTexture.valid = true; + } + + this.context = renderTexture._canvasRenderTarget.context; + this.resolution = renderTexture._canvasRenderTarget.resolution; + } else { + this.context = this.rootContext; + } + + var context = this.context; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + var tempWt = this._tempDisplayObjectParent.transform.worldTransform; + + if (transform) { + transform.copy(tempWt); + } else { + tempWt.identity(); + } + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + context.setTransform(1, 0, 0, 1, 0, 0); + context.globalAlpha = 1; + context.globalCompositeOperation = this.blendModes[_const.BLEND_MODES.NORMAL]; + + if (navigator.isCocoonJS && this.view.screencanvas) { + context.fillStyle = 'black'; + context.clear(); + } + + if (clear !== undefined ? clear : this.clearBeforeRender) { + if (this.renderingToScreen) { + if (this.transparent) { + context.clearRect(0, 0, this.width, this.height); + } else { + context.fillStyle = this._backgroundColorString; + context.fillRect(0, 0, this.width, this.height); + } + } // else { + // TODO: implement background for CanvasRenderTarget or RenderTexture? + // } + } + + // TODO RENDER TARGET STUFF HERE.. + var tempContext = this.context; + + this.context = context; + displayObject.renderCanvas(this); + this.context = tempContext; + + this.emit('postrender'); + }; + + /** + * Sets the blend mode of the renderer. + * + * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values. + */ + + + CanvasRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + if (this._activeBlendMode === blendMode) { + return; + } + + this.context.globalCompositeOperation = this.blendModes[blendMode]; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + CanvasRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // call the base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.context = null; + + this.refresh = true; + + this.maskManager.destroy(); + this.maskManager = null; + + this.smoothProperty = null; + }; + + /** + * Resizes the canvas view to the specified width and height. + * + * @extends PIXI.SystemRenderer#resize + * + * @param {number} width - The new width of the canvas view + * @param {number} height - The new height of the canvas view + */ + + + CanvasRenderer.prototype.resize = function resize(width, height) { + _SystemRenderer.prototype.resize.call(this, width, height); + + // reset the scale mode.. oddly this seems to be reset when the canvas is resized. + // surely a browser bug?? Let pixi fix that for you.. + if (this.smoothProperty) { + this.rootContext[this.smoothProperty] = _const.SCALE_MODES.DEFAULT === _const.SCALE_MODES.LINEAR; + } + }; + + return CanvasRenderer; +}(_SystemRenderer3.default); + +exports.default = CanvasRenderer; + + +_utils.pluginTarget.mixin(CanvasRenderer); + +},{"../../const":78,"../../utils":152,"../SystemRenderer":108,"./utils/CanvasMaskManager":110,"./utils/CanvasRenderTarget":111,"./utils/mapCanvasBlendModesToPixi":113}],110:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A set of functions used to handle masking. + * + * @class + * @memberof PIXI + */ +var CanvasMaskManager = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + function CanvasMaskManager(renderer) { + _classCallCheck(this, CanvasMaskManager); + + this.renderer = renderer; + } + + /** + * This method adds it to the current stack of masks. + * + * @param {object} maskData - the maskData that will be pushed + */ + + + CanvasMaskManager.prototype.pushMask = function pushMask(maskData) { + var renderer = this.renderer; + + renderer.context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.transform.worldTransform; + var resolution = renderer.resolution; + + renderer.context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // TODO suport sprite alpha masks?? + // lots of effort required. If demand is great enough.. + if (!maskData._texture) { + this.renderGraphicsShape(maskData); + renderer.context.clip(); + } + + maskData.worldAlpha = cacheAlpha; + }; + + /** + * Renders a PIXI.Graphics shape. + * + * @param {PIXI.Graphics} graphics - The object to render. + */ + + + CanvasMaskManager.prototype.renderGraphicsShape = function renderGraphicsShape(graphics) { + var context = this.renderer.context; + var len = graphics.graphicsData.length; + + if (len === 0) { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === _const.SHAPES.POLY) { + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; j++) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) { + context.closePath(); + } + } else if (data.type === _const.SHAPES.RECT) { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } + }; + + /** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @param {PIXI.CanvasRenderer} renderer - The renderer context to use. + */ + + + CanvasMaskManager.prototype.popMask = function popMask(renderer) { + renderer.context.restore(); + }; + + /** + * Destroys this canvas mask manager. + * + */ + + + CanvasMaskManager.prototype.destroy = function destroy() { + /* empty */ + }; + + return CanvasMaskManager; +}(); + +exports.default = CanvasMaskManager; + +},{"../../../const":78}],111:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Creates a Canvas element of the given size. + * + * @class + * @memberof PIXI + */ +var CanvasRenderTarget = function () { + /** + * @param {number} width - the width for the newly created canvas + * @param {number} height - the height for the newly created canvas + * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + _classCallCheck(this, CanvasRenderTarget); + + /** + * The Canvas object that belongs to this CanvasRenderTarget. + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @member {CanvasRenderingContext2D} + */ + this.context = this.canvas.getContext('2d'); + + this.resolution = resolution || _const.RESOLUTION; + + this.resize(width, height); + } + + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * + * @private + */ + + + CanvasRenderTarget.prototype.clear = function clear() { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + + /** + * Resizes the canvas to the specified width and height. + * + * @param {number} width - the new width of the canvas + * @param {number} height - the new height of the canvas + */ + + + CanvasRenderTarget.prototype.resize = function resize(width, height) { + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; + }; + + /** + * Destroys this canvas. + * + */ + + + CanvasRenderTarget.prototype.destroy = function destroy() { + this.context = null; + this.canvas = null; + }; + + /** + * The width of the canvas buffer in pixels. + * + * @member {number} + * @memberof PIXI.CanvasRenderTarget# + */ + + + _createClass(CanvasRenderTarget, [{ + key: 'width', + get: function get() { + return this.canvas.width; + } + + /** + * Sets the width. + * + * @param {number} val - The value to set. + */ + , + set: function set(val) { + this.canvas.width = val; + } + + /** + * The height of the canvas buffer in pixels. + * + * @member {number} + * @memberof PIXI.CanvasRenderTarget# + */ + + }, { + key: 'height', + get: function get() { + return this.canvas.height; + } + + /** + * Sets the height. + * + * @param {number} val - The value to set. + */ + , + set: function set(val) { + this.canvas.height = val; + } + }]); + + return CanvasRenderTarget; +}(); + +exports.default = CanvasRenderTarget; + +},{"../../../const":78}],112:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = canUseNewCanvasBlendModes; +/** + * Creates a little colored canvas + * + * @ignore + * @param {number} color - The color to make the canvas + * @return {canvas} a small canvas element + */ +function createColoredCanvas(color) { + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.fillStyle = color; + context.fillRect(0, 0, 6, 1); + + return canvas; +} + +/** + * Checks whether the Canvas BlendModes are supported by the current browser + * + * @return {boolean} whether they are supported + */ +function canUseNewCanvasBlendModes() { + if (typeof document === 'undefined') { + return false; + } + + var magenta = createColoredCanvas('#ff00ff'); + var yellow = createColoredCanvas('#ffff00'); + + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.globalCompositeOperation = 'multiply'; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + var imageData = context.getImageData(2, 0, 1, 1); + + if (!imageData) { + return false; + } + + var data = imageData.data; + + return data[0] === 255 && data[1] === 0 && data[2] === 0; +} + +},{}],113:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapCanvasBlendModesToPixi; + +var _const = require('../../../const'); + +var _canUseNewCanvasBlendModes = require('./canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Maps blend combinations to Canvas. + * + * @memberof PIXI + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapCanvasBlendModesToPixi() { + var array = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; + + if ((0, _canUseNewCanvasBlendModes2.default)()) { + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'multiply'; + array[_const.BLEND_MODES.SCREEN] = 'screen'; + array[_const.BLEND_MODES.OVERLAY] = 'overlay'; + array[_const.BLEND_MODES.DARKEN] = 'darken'; + array[_const.BLEND_MODES.LIGHTEN] = 'lighten'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'color-dodge'; + array[_const.BLEND_MODES.COLOR_BURN] = 'color-burn'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'hard-light'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'soft-light'; + array[_const.BLEND_MODES.DIFFERENCE] = 'difference'; + array[_const.BLEND_MODES.EXCLUSION] = 'exclusion'; + array[_const.BLEND_MODES.HUE] = 'hue'; + array[_const.BLEND_MODES.SATURATION] = 'saturate'; + array[_const.BLEND_MODES.COLOR] = 'color'; + array[_const.BLEND_MODES.LUMINOSITY] = 'luminosity'; + } else { + // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'source-over'; + array[_const.BLEND_MODES.SCREEN] = 'source-over'; + array[_const.BLEND_MODES.OVERLAY] = 'source-over'; + array[_const.BLEND_MODES.DARKEN] = 'source-over'; + array[_const.BLEND_MODES.LIGHTEN] = 'source-over'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'source-over'; + array[_const.BLEND_MODES.COLOR_BURN] = 'source-over'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.DIFFERENCE] = 'source-over'; + array[_const.BLEND_MODES.EXCLUSION] = 'source-over'; + array[_const.BLEND_MODES.HUE] = 'source-over'; + array[_const.BLEND_MODES.SATURATION] = 'source-over'; + array[_const.BLEND_MODES.COLOR] = 'source-over'; + array[_const.BLEND_MODES.LUMINOSITY] = 'source-over'; + } + + return array; +} + +},{"../../../const":78,"./canUseNewCanvasBlendModes":112}],114:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged + * up with textures that are no longer being used. + * + * @class + * @memberof PIXI + */ +var TextureGarbageCollector = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function TextureGarbageCollector(renderer) { + _classCallCheck(this, TextureGarbageCollector); + + this.renderer = renderer; + + this.count = 0; + this.checkCount = 0; + this.maxIdle = 60 * 60; + this.checkCountMax = 60 * 10; + + this.mode = _const.GC_MODES.DEFAULT; + } + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.update = function update() { + this.count++; + + if (this.mode === _const.GC_MODES.MANUAL) { + return; + } + + this.checkCount++; + + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + + this.run(); + } + }; + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.run = function run() { + var tm = this.renderer.textureManager; + var managedTextures = tm._managedTextures; + var wasRemoved = false; + + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + + // only supports non generated textures at the moment! + if (!texture._glRenderTargets && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + + if (wasRemoved) { + var j = 0; + + for (var _i = 0; _i < managedTextures.length; _i++) { + if (managedTextures[_i] !== null) { + managedTextures[j++] = managedTextures[_i]; + } + } + + managedTextures.length = j; + } + }; + + /** + * Removes all the textures within the specified displayObject and its children from the GPU + * + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + */ + + + TextureGarbageCollector.prototype.unload = function unload(displayObject) { + var tm = this.renderer.textureManager; + + if (displayObject._texture) { + tm.destroyTexture(displayObject._texture, true); + } + + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + + return TextureGarbageCollector; +}(); + +exports.default = TextureGarbageCollector; + +},{"../../const":78}],115:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _const = require('../../const'); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _utils = require('../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a webGL Texture + * + * @class + * @memberof PIXI + */ +var TextureManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function TextureManager(renderer) { + _classCallCheck(this, TextureManager); + + /** + * A reference to the current renderer + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = renderer.gl; + + /** + * Track textures in the renderer so we can no longer listen to them on destruction. + * + * @member {Array<*>} + * @private + */ + this._managedTextures = []; + } + + /** + * Binds a texture. + * + */ + + + TextureManager.prototype.bindTexture = function bindTexture() {} + // empty + + + /** + * Gets a texture. + * + */ + ; + + TextureManager.prototype.getTexture = function getTexture() {} + // empty + + + /** + * Updates and/or Creates a WebGL texture for the renderer's context. + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update + * @return {GLTexture} The gl texture. + */ + ; + + TextureManager.prototype.updateTexture = function updateTexture(texture) { + texture = texture.baseTexture || texture; + + var isRenderTexture = !!texture._glRenderTargets; + + if (!texture.hasLoaded) { + return null; + } + + var glTexture = texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!glTexture) { + if (isRenderTexture) { + var renderTarget = new _RenderTarget2.default(this.gl, texture.width, texture.height, texture.scaleMode, texture.resolution); + + renderTarget.resize(texture.width, texture.height); + texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget; + glTexture = renderTarget.texture; + } else { + glTexture = new _pixiGlCore.GLTexture(this.gl); + glTexture.premultiplyAlpha = true; + glTexture.upload(texture.source); + } + + texture._glTextures[this.renderer.CONTEXT_UID] = glTexture; + + texture.on('update', this.updateTexture, this); + texture.on('dispose', this.destroyTexture, this); + + this._managedTextures.push(texture); + + if (texture.isPowerOfTwo) { + if (texture.mipmap) { + glTexture.enableMipmap(); + } + + if (texture.wrapMode === _const.WRAP_MODES.CLAMP) { + glTexture.enableWrapClamp(); + } else if (texture.wrapMode === _const.WRAP_MODES.REPEAT) { + glTexture.enableWrapRepeat(); + } else { + glTexture.enableWrapMirrorRepeat(); + } + } else { + glTexture.enableWrapClamp(); + } + + if (texture.scaleMode === _const.SCALE_MODES.NEAREST) { + glTexture.enableNearestScaling(); + } else { + glTexture.enableLinearScaling(); + } + } + // the textur ealrady exists so we only need to update it.. + else if (isRenderTexture) { + texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height); + } else { + glTexture.upload(texture.source); + } + + return glTexture; + }; + + /** + * Deletes the texture from WebGL + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy + * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. + */ + + + TextureManager.prototype.destroyTexture = function destroyTexture(texture, skipRemove) { + texture = texture.baseTexture || texture; + + if (!texture.hasLoaded) { + return; + } + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + texture._glTextures[this.renderer.CONTEXT_UID].destroy(); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + + delete texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!skipRemove) { + var i = this._managedTextures.indexOf(texture); + + if (i !== -1) { + (0, _utils.removeItems)(this._managedTextures, i, 1); + } + } + } + }; + + /** + * Deletes all the textures from WebGL + */ + + + TextureManager.prototype.removeAll = function removeAll() { + // empty all the old gl textures as they are useless now + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + delete texture._glTextures[this.renderer.CONTEXT_UID]; + } + } + }; + + /** + * Destroys this manager and removes all its textures + */ + + + TextureManager.prototype.destroy = function destroy() { + // destroy managed textures + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + this.destroyTexture(texture, true); + + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + } + + this._managedTextures = null; + }; + + return TextureManager; +}(); + +exports.default = TextureManager; + +},{"../../const":78,"../../utils":152,"./utils/RenderTarget":128,"pixi-gl-core":51}],116:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _MaskManager = require('./managers/MaskManager'); + +var _MaskManager2 = _interopRequireDefault(_MaskManager); + +var _StencilManager = require('./managers/StencilManager'); + +var _StencilManager2 = _interopRequireDefault(_StencilManager); + +var _FilterManager = require('./managers/FilterManager'); + +var _FilterManager2 = _interopRequireDefault(_FilterManager); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _ObjectRenderer = require('./utils/ObjectRenderer'); + +var _ObjectRenderer2 = _interopRequireDefault(_ObjectRenderer); + +var _TextureManager = require('./TextureManager'); + +var _TextureManager2 = _interopRequireDefault(_TextureManager); + +var _TextureGarbageCollector = require('./TextureGarbageCollector'); + +var _TextureGarbageCollector2 = _interopRequireDefault(_TextureGarbageCollector); + +var _WebGLState = require('./WebGLState'); + +var _WebGLState2 = _interopRequireDefault(_WebGLState); + +var _mapWebGLDrawModesToPixi = require('./utils/mapWebGLDrawModesToPixi'); + +var _mapWebGLDrawModesToPixi2 = _interopRequireDefault(_mapWebGLDrawModesToPixi); + +var _validateContext = require('./utils/validateContext'); + +var _validateContext2 = _interopRequireDefault(_validateContext); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CONTEXT_UID = 0; + +/** + * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ + +var WebGLRenderer = function (_SystemRenderer) { + _inherits(WebGLRenderer, _SystemRenderer); + + /** + * + * @param {number} [width=0] - the width of the canvas view + * @param {number} [height=0] - the height of the canvas view + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias. If not available natively then FXAA + * antialiasing is used + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. + * The resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear + * the canvas or not before the new render pass. If you wish to set this to false, you *must* set + * preserveDrawingBuffer to `true`. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when + * rendering, stopping pixel interpolation. + */ + function WebGLRenderer(width, height) { + var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + + _classCallCheck(this, WebGLRenderer); + + /** + * The type of this renderer as a standardised const + * + * @member {number} + * @see PIXI.RENDERER_TYPE + */ + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'WebGL', width, height, options)); + + _this.type = _const.RENDERER_TYPE.WEBGL; + + _this.handleContextLost = _this.handleContextLost.bind(_this); + _this.handleContextRestored = _this.handleContextRestored.bind(_this); + + _this.view.addEventListener('webglcontextlost', _this.handleContextLost, false); + _this.view.addEventListener('webglcontextrestored', _this.handleContextRestored, false); + + /** + * The options passed in to create a new webgl context. + * + * @member {object} + * @private + */ + _this._contextOptions = { + alpha: _this.transparent, + antialias: options.antialias, + premultipliedAlpha: _this.transparent && _this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: options.preserveDrawingBuffer + }; + + _this._backgroundColorRgba[3] = _this.transparent ? 0 : 1; + + /** + * Manages the masks using the stencil buffer. + * + * @member {PIXI.MaskManager} + */ + _this.maskManager = new _MaskManager2.default(_this); + + /** + * Manages the stencil buffer. + * + * @member {PIXI.StencilManager} + */ + _this.stencilManager = new _StencilManager2.default(_this); + + /** + * An empty renderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.emptyRenderer = new _ObjectRenderer2.default(_this); + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.currentRenderer = _this.emptyRenderer; + + _this.initPlugins(); + + /** + * The current WebGL rendering context, it is created here + * + * @member {WebGLRenderingContext} + */ + // initialize the context so it is ready for the managers. + if (options.context) { + // checks to see if a context is valid.. + (0, _validateContext2.default)(options.context); + } + + _this.gl = options.context || _pixiGlCore2.default.createContext(_this.view, _this._contextOptions); + + _this.CONTEXT_UID = CONTEXT_UID++; + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.WebGLState} + */ + _this.state = new _WebGLState2.default(_this.gl); + + _this.renderingToScreen = true; + + _this._initContext(); + + /** + * Manages the filters. + * + * @member {PIXI.FilterManager} + */ + _this.filterManager = new _FilterManager2.default(_this); + // map some webGL blend and drawmodes.. + _this.drawModes = (0, _mapWebGLDrawModesToPixi2.default)(_this.gl); + + /** + * Holds the current shader + * + * @member {PIXI.Shader} + */ + _this._activeShader = null; + + /** + * Holds the current render target + * + * @member {PIXI.RenderTarget} + */ + _this._activeRenderTarget = null; + _this._activeTextureLocation = 999; + _this._activeTexture = null; + + _this.setBlendMode(0); + return _this; + } + + /** + * Creates the WebGL context + * + * @private + */ + + + WebGLRenderer.prototype._initContext = function _initContext() { + var gl = this.gl; + + // create a texture manager... + this.textureManager = new _TextureManager2.default(this); + this.textureGC = new _TextureGarbageCollector2.default(this); + + this.state.resetToDefault(); + + this.rootRenderTarget = new _RenderTarget2.default(gl, this.width, this.height, null, this.resolution, true); + this.rootRenderTarget.clearColor = this._backgroundColorRgba; + + this.bindRenderTarget(this.rootRenderTarget); + + this.emit('context', gl); + + // setup the width/height properties and gl viewport + this.resize(this.width, this.height); + }; + + /** + * Renders the object to its webGL view + * + * @param {PIXI.DisplayObject} displayObject - the object to be rendered + * @param {PIXI.RenderTexture} renderTexture - The render texture to render to. + * @param {boolean} [clear] - Should the canvas be cleared before the new render + * @param {PIXI.Transform} [transform] - A transform to apply to the render texture before rendering. + * @param {boolean} [skipUpdateTransform] - Should we skip the update transform pass? + */ + + + WebGLRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + // no point rendering if our context has been blown up! + if (!this.gl || this.gl.isContextLost()) { + return; + } + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + this.bindRenderTexture(renderTexture, transform); + + this.currentRenderer.start(); + + if (clear !== undefined ? clear : this.clearBeforeRender) { + this._activeRenderTarget.clear(); + } + + displayObject.renderWebGL(this); + + // apply transform.. + this.currentRenderer.flush(); + + // this.setObjectRenderer(this.emptyRenderer); + + this.textureGC.update(); + + this.emit('postrender'); + }; + + /** + * Changes the current renderer to the one given in parameter + * + * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. + */ + + + WebGLRenderer.prototype.setObjectRenderer = function setObjectRenderer(objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; + + /** + * This shoudl be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + * + */ + + + WebGLRenderer.prototype.flush = function flush() { + this.setObjectRenderer(this.emptyRenderer); + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} width - the new width of the webGL view + * @param {number} height - the new height of the webGL view + */ + + + WebGLRenderer.prototype.resize = function resize(width, height) { + // if(width * this.resolution === this.width && height * this.resolution === this.height)return; + + _SystemRenderer3.default.prototype.resize.call(this, width, height); + + this.rootRenderTarget.resize(width, height); + + if (this._activeRenderTarget === this.rootRenderTarget) { + this.rootRenderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true); + } + } + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} blendMode - the desired blend mode + */ + + + WebGLRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + this.state.setBlendMode(blendMode); + }; + + /** + * Erases the active render target and fills the drawing area with a colour + * + * @param {number} [clearColor] - The colour + */ + + + WebGLRenderer.prototype.clear = function clear(clearColor) { + this._activeRenderTarget.clear(clearColor); + }; + + /** + * Sets the transform of the active render target to the given matrix + * + * @param {PIXI.Matrix} matrix - The transformation matrix + */ + + + WebGLRenderer.prototype.setTransform = function setTransform(matrix) { + this._activeRenderTarget.transform = matrix; + }; + + /** + * Binds a render texture for rendering + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to render + * @param {PIXI.Transform} transform - The transform to be applied to the render texture + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTexture = function bindRenderTexture(renderTexture, transform) { + var renderTarget = void 0; + + if (renderTexture) { + var baseTexture = renderTexture.baseTexture; + var gl = this.gl; + + if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) { + this.textureManager.updateTexture(baseTexture); + gl.bindTexture(gl.TEXTURE_2D, null); + } else { + // the texture needs to be unbound if its being rendererd too.. + this._activeTextureLocation = baseTexture._id; + gl.activeTexture(gl.TEXTURE0 + baseTexture._id); + gl.bindTexture(gl.TEXTURE_2D, null); + } + + renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + renderTarget.setFrame(renderTexture.frame); + } else { + renderTarget = this.rootRenderTarget; + } + + renderTarget.transform = transform; + this.bindRenderTarget(renderTarget); + + return this; + }; + + /** + * Changes the current render target to the one given in parameter + * + * @param {PIXI.RenderTarget} renderTarget - the new render target + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTarget = function bindRenderTarget(renderTarget) { + if (renderTarget !== this._activeRenderTarget) { + this._activeRenderTarget = renderTarget; + renderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true); + } + + this.stencilManager.setMaskStack(renderTarget.stencilMaskStack); + } + + return this; + }; + + /** + * Changes the current shader to the one given in parameter + * + * @param {PIXI.Shader} shader - the new shader + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindShader = function bindShader(shader) { + // TODO cache + if (this._activeShader !== shader) { + this._activeShader = shader; + shader.bind(); + + // automatically set the projection matrix + shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(true); + } + + return this; + }; + + /** + * Binds the texture ... @mat + * + * @param {PIXI.Texture} texture - the new texture + * @param {number} location - the texture location + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindTexture = function bindTexture(texture) { + var location = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1]; + + texture = texture.baseTexture || texture; + + var gl = this.gl; + + // TODO test perf of cache? + + if (this._activeTextureLocation !== location) // + { + this._activeTextureLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + + // TODO - can we cache this texture too? + this._activeTexture = texture; + + if (!texture._glTextures[this.CONTEXT_UID]) { + // this will also bind the texture.. + this.textureManager.updateTexture(texture); + } else { + texture.touched = this.textureGC.count; + // bind the current texture + texture._glTextures[this.CONTEXT_UID].bind(); + } + + return this; + }; + + /** + * Creates a new VAO from this renderer's context and state. + * + * @return {VertexArrayObject} The new VAO. + */ + + + WebGLRenderer.prototype.createVao = function createVao() { + return new _pixiGlCore2.default.VertexArrayObject(this.gl, this.state.attribState); + }; + + /** + * Resets the WebGL state so you can render things however you fancy! + * + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.reset = function reset() { + this.setObjectRenderer(this.emptyRenderer); + + this._activeShader = null; + this._activeRenderTarget = this.rootRenderTarget; + this._activeTextureLocation = 999; + this._activeTexture = null; + + // bind the main frame buffer (the screen); + this.rootRenderTarget.activate(); + + this.state.resetToDefault(); + + return this; + }; + + /** + * Handles a lost webgl context + * + * @private + * @param {WebGLContextEvent} event - The context lost event. + */ + + + WebGLRenderer.prototype.handleContextLost = function handleContextLost(event) { + event.preventDefault(); + }; + + /** + * Handles a restored webgl context + * + * @private + */ + + + WebGLRenderer.prototype.handleContextRestored = function handleContextRestored() { + this._initContext(); + this.textureManager.removeAll(); + }; + + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + + + WebGLRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // remove listeners + this.view.removeEventListener('webglcontextlost', this.handleContextLost); + this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); + + this.textureManager.destroy(); + + // call base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.uid = 0; + + // destroy the managers + this.maskManager.destroy(); + this.stencilManager.destroy(); + this.filterManager.destroy(); + + this.maskManager = null; + this.filterManager = null; + this.textureManager = null; + this.currentRenderer = null; + + this.handleContextLost = null; + this.handleContextRestored = null; + + this._contextOptions = null; + this.gl.useProgram(null); + + if (this.gl.getExtension('WEBGL_lose_context')) { + this.gl.getExtension('WEBGL_lose_context').loseContext(); + } + + this.gl = null; + + // this = null; + }; + + return WebGLRenderer; +}(_SystemRenderer3.default); + +exports.default = WebGLRenderer; + + +_utils.pluginTarget.mixin(WebGLRenderer); + +},{"../../const":78,"../../utils":152,"../SystemRenderer":108,"./TextureGarbageCollector":114,"./TextureManager":115,"./WebGLState":117,"./managers/FilterManager":122,"./managers/MaskManager":123,"./managers/StencilManager":124,"./utils/ObjectRenderer":126,"./utils/RenderTarget":128,"./utils/mapWebGLDrawModesToPixi":131,"./utils/validateContext":132,"pixi-gl-core":51}],117:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); + +var _mapWebGLBlendModesToPixi2 = _interopRequireDefault(_mapWebGLBlendModesToPixi); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var BLEND = 0; +var DEPTH_TEST = 1; +var FRONT_FACE = 2; +var CULL_FACE = 3; +var BLEND_FUNC = 4; + +/** + * A WebGL state machines + * + * @memberof PIXI + * @class + */ + +var WebGLState = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + */ + function WebGLState(gl) { + _classCallCheck(this, WebGLState); + + /** + * The current active state + * + * @member {Uint8Array} + */ + this.activeState = new Uint8Array(16); + + /** + * The default state + * + * @member {Uint8Array} + */ + this.defaultState = new Uint8Array(16); + + // default blend mode.. + this.defaultState[0] = 1; + + /** + * The current state index in the stack + * + * @member {number} + * @private + */ + this.stackIndex = 0; + + /** + * The stack holding all the different states + * + * @member {Array<*>} + * @private + */ + this.stack = []; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + this.attribState = { + tempAttribState: new Array(this.maxAttribs), + attribState: new Array(this.maxAttribs) + }; + + this.blendModes = (0, _mapWebGLBlendModesToPixi2.default)(gl); + + // check we have vao.. + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || gl.getExtension('MOZ_OES_vertex_array_object') || gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + /** + * Pushes a new active state + */ + + + WebGLState.prototype.push = function push() { + // next state.. + var state = this.stack[++this.stackIndex]; + + if (!state) { + state = this.stack[this.stackIndex] = new Uint8Array(16); + } + + // copy state.. + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) { + this.activeState[i] = state[i]; + } + }; + + /** + * Pops a state out + */ + + + WebGLState.prototype.pop = function pop() { + var state = this.stack[--this.stackIndex]; + + this.setState(state); + }; + + /** + * Sets the current state + * + * @param {*} state - The state to set. + */ + + + WebGLState.prototype.setState = function setState(state) { + this.setBlend(state[BLEND]); + this.setDepthTest(state[DEPTH_TEST]); + this.setFrontFace(state[FRONT_FACE]); + this.setCullFace(state[CULL_FACE]); + this.setBlendMode(state[BLEND_FUNC]); + }; + + /** + * Enables or disabled blending. + * + * @param {boolean} value - Turn on or off webgl blending. + */ + + + WebGLState.prototype.setBlend = function setBlend(value) { + value = value ? 1 : 0; + + if (this.activeState[BLEND] === value) { + return; + } + + this.activeState[BLEND] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + }; + + /** + * Sets the blend mode. + * + * @param {number} value - The blend mode to set to. + */ + + + WebGLState.prototype.setBlendMode = function setBlendMode(value) { + if (value === this.activeState[BLEND_FUNC]) { + return; + } + + this.activeState[BLEND_FUNC] = value; + + this.gl.blendFunc(this.blendModes[value][0], this.blendModes[value][1]); + }; + + /** + * Sets whether to enable or disable depth test. + * + * @param {boolean} value - Turn on or off webgl depth testing. + */ + + + WebGLState.prototype.setDepthTest = function setDepthTest(value) { + value = value ? 1 : 0; + + if (this.activeState[DEPTH_TEST] === value) { + return; + } + + this.activeState[DEPTH_TEST] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + }; + + /** + * Sets whether to enable or disable cull face. + * + * @param {boolean} value - Turn on or off webgl cull face. + */ + + + WebGLState.prototype.setCullFace = function setCullFace(value) { + value = value ? 1 : 0; + + if (this.activeState[CULL_FACE] === value) { + return; + } + + this.activeState[CULL_FACE] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + }; + + /** + * Sets the gl front face. + * + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ + + + WebGLState.prototype.setFrontFace = function setFrontFace(value) { + value = value ? 1 : 0; + + if (this.activeState[FRONT_FACE] === value) { + return; + } + + this.activeState[FRONT_FACE] = value; + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); + }; + + /** + * Disables all the vaos in use + * + */ + + + WebGLState.prototype.resetAttributes = function resetAttributes() { + for (var i = 0; i < this.attribState.tempAttribState.length; i++) { + this.attribState.tempAttribState[i] = 0; + } + + for (var _i = 0; _i < this.attribState.attribState.length; _i++) { + this.attribState.attribState[_i] = 0; + } + + // im going to assume one is always active for performance reasons. + for (var _i2 = 1; _i2 < this.maxAttribs; _i2++) { + this.gl.disableVertexAttribArray(_i2); + } + }; + + // used + /** + * Resets all the logic and disables the vaos + */ + + + WebGLState.prototype.resetToDefault = function resetToDefault() { + // unbind any VAO if they exist.. + if (this.nativeVaoExtension) { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + // reset all attributs.. + this.resetAttributes(); + + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; ++i) { + this.activeState[i] = 32; + } + + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + + this.setState(this.defaultState); + }; + + return WebGLState; +}(); + +exports.default = WebGLState; + +},{"./utils/mapWebGLBlendModesToPixi":130}],118:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _extractUniformsFromSrc = require('./extractUniformsFromSrc'); + +var _extractUniformsFromSrc2 = _interopRequireDefault(_extractUniformsFromSrc); + +var _utils = require('../../../utils'); + +var _const = require('../../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SOURCE_KEY_MAP = {}; + +// let math = require('../../../math'); +/** + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ + +var Filter = function () { + /** + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. + */ + function Filter(vertexSrc, fragmentSrc, uniforms) { + _classCallCheck(this, Filter); + + /** + * The vertex shader. + * + * @member {string} + */ + this.vertexSrc = vertexSrc || Filter.defaultVertexSrc; + + /** + * The fragment shader. + * + * @member {string} + */ + this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc; + + this.blendMode = _const.BLEND_MODES.NORMAL; + + // pull out the vertex and shader uniforms if they are not specified.. + // currently this does not extract structs only default types + this.uniformData = uniforms || (0, _extractUniformsFromSrc2.default)(this.vertexSrc, this.fragmentSrc, 'projectionMatrix|uSampler'); + + this.uniforms = {}; + + for (var i in this.uniformData) { + this.uniforms[i] = this.uniformData[i].value; + } + + // this is where we store shader references.. + // TODO we could cache this! + this.glShaders = []; + + // used for cacheing.. sure there is a better way! + if (!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) { + SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = (0, _utils.uid)(); + } + + this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]; + + /** + * The padding of the filter. Some filters require extra space to breath such as a blur. + * Increasing this will add extra width and height to the bounds of the object that the + * filter is applied to. + * + * @member {number} + */ + this.padding = 4; + + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + * + * @member {number} + */ + this.resolution = 1; + + /** + * If enabled is true the filter is applied, if false it will not. + * + * @member {boolean} + */ + this.enabled = true; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + Filter.prototype.apply = function apply(filterManager, input, output, clear) { + // --- // + // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); + + // do as you please! + + filterManager.applyFilter(this, input, output, clear); + + // or just do a regular render.. + }; + + /** + * The default vertex shader source + * + * @static + * @constant + */ + + + _createClass(Filter, null, [{ + key: 'defaultVertexSrc', + get: function get() { + return ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform mat3 projectionMatrix;', 'uniform mat3 filterMatrix;', 'varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;', ' vTextureCoord = aTextureCoord ;', '}'].join('\n'); + } + + /** + * The default fragment shader source + * + * @static + * @constant + */ + + }, { + key: 'defaultFragmentSrc', + get: function get() { + return ['varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'uniform sampler2D uSampler;', 'uniform sampler2D filterSampler;', 'void main(void){', ' vec4 masky = texture2D(filterSampler, vFilterCoord);', ' vec4 sample = texture2D(uSampler, vTextureCoord);', ' vec4 color;', ' if(mod(vFilterCoord.x, 1.0) > 0.5)', ' {', ' color = vec4(1.0, 0.0, 0.0, 1.0);', ' }', ' else', ' {', ' color = vec4(0.0, 1.0, 0.0, 1.0);', ' }', + // ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', + ' gl_FragColor = mix(sample, masky, 0.5);', ' gl_FragColor *= sample.a;', '}'].join('\n'); + } + }]); + + return Filter; +}(); + +exports.default = Filter; + +},{"../../../const":78,"../../../utils":152,"./extractUniformsFromSrc":119}],119:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = extractUniformsFromSrc; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var defaultValue = _pixiGlCore2.default.shader.defaultValue; + +function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) { + var vertUniforms = extractUniformsFromString(vertexSrc, mask); + var fragUniforms = extractUniformsFromString(fragmentSrc, mask); + + return Object.assign(vertUniforms, fragUniforms); +} + +function extractUniformsFromString(string) { + var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea)$'); + + var uniforms = {}; + var nameSplit = void 0; + + // clean the lines a little - remove extra spaces / teabs etc + // then split along ';' + var lines = string.replace(/\s+/g, ' ').split(/\s*;\s*/); + + // loop through.. + for (var i = 0; i < lines.length; i++) { + var line = lines[i].trim(); + + if (line.indexOf('uniform') > -1) { + var splitLine = line.split(' '); + var type = splitLine[1]; + + var name = splitLine[2]; + var size = 1; + + if (name.indexOf('[') > -1) { + // array! + nameSplit = name.split(/\[|\]/); + name = nameSplit[0]; + size *= Number(nameSplit[1]); + } + + if (!name.match(maskRegex)) { + uniforms[name] = { + value: defaultValue(type, size), + name: name, + type: type + }; + } + } + } + + return uniforms; +} + +},{"pixi-gl-core":51}],120:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.calculateScreenSpaceMatrix = calculateScreenSpaceMatrix; +exports.calculateNormalizedScreenSpaceMatrix = calculateNormalizedScreenSpaceMatrix; +exports.calculateSpriteMatrix = calculateSpriteMatrix; + +var _math = require('../../../math'); + +/* + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// thia returns a matrix that will normalise map filter cords in the filter to screen space +function calculateScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + // let worldTransform = sprite.worldTransform.copy(Matrix.TEMP_MATRIX), + // let texture = {width:1136, height:700};//sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(textureSize.width, textureSize.height); + + return mappedMatrix; +} + +function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + var translateScaleX = textureSize.width / filterArea.width; + var translateScaleY = textureSize.height / filterArea.height; + + mappedMatrix.scale(translateScaleX, translateScaleY); + + return mappedMatrix; +} + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +function calculateSpriteMatrix(outputMatrix, filterArea, textureSize, sprite) { + var worldTransform = sprite.worldTransform.copy(_math.Matrix.TEMP_MATRIX); + var texture = sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + // scale.. + var ratio = textureSize.height / textureSize.width; + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(1, ratio); + + var translateScaleX = textureSize.width / texture.width; + var translateScaleY = textureSize.height / texture.height; + + worldTransform.tx /= texture.width * translateScaleX; + + // this...? free beer for anyone who can explain why this makes sense! + worldTransform.ty /= texture.width * translateScaleX; + // worldTransform.ty /= texture.height * translateScaleY; + + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + + // apply inverse scale.. + mappedMatrix.scale(1, 1 / ratio); + + mappedMatrix.scale(translateScaleX, translateScaleY); + + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; +} + +},{"../../../math":102}],121:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Filter2 = require('../Filter'); + +var _Filter3 = _interopRequireDefault(_Filter2); + +var _math = require('../../../../math'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// @see https://github.com/substack/brfs/issues/25 + // eslint-disable-line no-undef + +/** + * The SpriteMaskFilter class + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + */ + +var SpriteMaskFilter = function (_Filter) { + _inherits(SpriteMaskFilter, _Filter); + + /** + * @param {PIXI.Sprite} sprite - the target sprite + */ + function SpriteMaskFilter(sprite) { + _classCallCheck(this, SpriteMaskFilter); + + var maskMatrix = new _math.Matrix(); + + var _this = _possibleConstructorReturn(this, _Filter.call(this, "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n", "#define GLSLIFY 1\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n")); + + sprite.renderable = false; + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + return _this; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + */ + + + SpriteMaskFilter.prototype.apply = function apply(filterManager, input, output) { + var maskSprite = this.maskSprite; + + this.uniforms.mask = maskSprite._texture; + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite); + this.uniforms.alpha = maskSprite.worldAlpha; + + filterManager.applyFilter(this, input, output); + }; + + return SpriteMaskFilter; +}(_Filter3.default); + +exports.default = SpriteMaskFilter; + +},{"../../../../math":102,"../Filter":118}],122:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _RenderTarget = require('../utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _Quad = require('../utils/Quad'); + +var _Quad2 = _interopRequireDefault(_Quad); + +var _math = require('../../../math'); + +var _Shader = require('../../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _filterTransforms = require('../filters/filterTransforms'); + +var filterTransforms = _interopRequireWildcard(_filterTransforms); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @ignore + * @class + */ +var FilterState = +/** + * + */ +function FilterState() { + _classCallCheck(this, FilterState); + + this.renderTarget = null; + this.sourceFrame = new _math.Rectangle(); + this.destinationFrame = new _math.Rectangle(); + this.filters = []; + this.target = null; + this.resolution = 1; +}; + +/** + * @class + * @memberof PIXI + * @extends PIXI.WebGLManager + */ + + +var FilterManager = function (_WebGLManager) { + _inherits(FilterManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function FilterManager(renderer) { + _classCallCheck(this, FilterManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.gl = _this.renderer.gl; + // know about sprites! + _this.quad = new _Quad2.default(_this.gl, renderer.state.attribState); + + _this.shaderCache = {}; + // todo add default! + _this.pool = {}; + + _this.filterData = null; + return _this; + } + + /** + * Adds a new filter to the manager. + * + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param {PIXI.Filter[]} filters - The filters to apply. + */ + + + FilterManager.prototype.pushFilter = function pushFilter(target, filters) { + var renderer = this.renderer; + + var filterData = this.filterData; + + if (!filterData) { + filterData = this.renderer._activeRenderTarget.filterStack; + + // add new stack + var filterState = new FilterState(); + + filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; + filterState.renderTarget = renderer._activeRenderTarget; + + this.renderer._activeRenderTarget.filterData = filterData = { + index: 0, + stack: [filterState] + }; + + this.filterData = filterData; + } + + // get the current filter state.. + var currentState = filterData.stack[++filterData.index]; + + if (!currentState) { + currentState = filterData.stack[filterData.index] = new FilterState(); + } + + // for now we go off the filter of the first resolution.. + var resolution = filters[0].resolution; + var padding = filters[0].padding | 0; + var targetBounds = target.filterArea || target.getBounds(true); + var sourceFrame = currentState.sourceFrame; + var destinationFrame = currentState.destinationFrame; + + sourceFrame.x = (targetBounds.x * resolution | 0) / resolution; + sourceFrame.y = (targetBounds.y * resolution | 0) / resolution; + sourceFrame.width = (targetBounds.width * resolution | 0) / resolution; + sourceFrame.height = (targetBounds.height * resolution | 0) / resolution; + + if (filterData.stack[0].renderTarget.transform) {// + + // TODO we should fit the rect around the transform.. + } else { + sourceFrame.fit(filterData.stack[0].destinationFrame); + } + + // lets pplay the padding After we fit the element to the screen. + // this should stop the strange side effects that can occour when cropping to the edges + sourceFrame.pad(padding); + + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + + // lets play the padding after we fit the element to the screen. + // this should stop the strange side effects that can occour when cropping to the edges + + var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); + + currentState.target = target; + currentState.filters = filters; + currentState.resolution = resolution; + currentState.renderTarget = renderTarget; + + // bind the render taget to draw the shape in the top corner.. + + renderTarget.setFrame(destinationFrame, sourceFrame); + // bind the render target + renderer.bindRenderTarget(renderTarget); + + // clear the renderTarget + renderer.clear(); // [0.5,0.5,0.5, 1.0]); + }; + + /** + * Pops off the filter and applies it. + * + */ + + + FilterManager.prototype.popFilter = function popFilter() { + var filterData = this.filterData; + + var lastState = filterData.stack[filterData.index - 1]; + var currentState = filterData.stack[filterData.index]; + + this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); + + var filters = currentState.filters; + + if (filters.length === 1) { + filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false); + this.freePotRenderTarget(currentState.renderTarget); + } else { + var flip = currentState.renderTarget; + var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, 1); + + flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + var i = 0; + + for (i = 0; i < filters.length - 1; ++i) { + filters[i].apply(this, flip, flop, true); + + var t = flip; + + flip = flop; + flop = t; + } + + filters[i].apply(this, flip, lastState.renderTarget, false); + + this.freePotRenderTarget(flip); + this.freePotRenderTarget(flop); + } + + filterData.index--; + + if (filterData.index === 0) { + this.filterData = null; + } + }; + + /** + * Draws a filter. + * + * @param {PIXI.Filter} filter - The filter to draw. + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + FilterManager.prototype.applyFilter = function applyFilter(filter, input, output, clear) { + var renderer = this.renderer; + var shader = filter.glShaders[renderer.CONTEXT_UID]; + + // cacheing.. + if (!shader) { + if (filter.glShaderKey) { + shader = this.shaderCache[filter.glShaderKey]; + + if (!shader) { + shader = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + + filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = shader; + } + } else { + shader = filter.glShaders[renderer.CONTEXT_UID] = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + } + + // TODO - this only needs to be done once? + this.quad.initVao(shader); + } + + renderer.bindRenderTarget(output); + + if (clear) { + var gl = renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + renderer.clear(); // [1, 1, 1, 1]); + gl.enable(gl.SCISSOR_TEST); + } + + // in case the render target is being masked using a scissor rect + if (output === renderer.maskManager.scissorRenderTarget) { + renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); + } + + renderer.bindShader(shader); + + // this syncs the pixi filters uniforms with glsl uniforms + this.syncUniforms(shader, filter); + + // bind the input texture.. + input.texture.bind(0); + // when you manually bind a texture, please switch active texture location to it + renderer._activeTextureLocation = 0; + + renderer.state.setBlendMode(filter.blendMode); + + this.quad.draw(); + }; + + /** + * Uploads the uniforms of the filter. + * + * @param {GLShader} shader - The underlying gl shader. + * @param {PIXI.Filter} filter - The filter we are synchronizing. + */ + + + FilterManager.prototype.syncUniforms = function syncUniforms(shader, filter) { + var uniformData = filter.uniformData; + var uniforms = filter.uniforms; + + // 0 is reserverd for the pixi texture so we start at 1! + var textureCount = 1; + var currentState = void 0; + + if (shader.uniforms.data.filterArea) { + currentState = this.filterData.stack[this.filterData.index]; + var filterArea = shader.uniforms.filterArea; + + filterArea[0] = currentState.renderTarget.size.width; + filterArea[1] = currentState.renderTarget.size.height; + filterArea[2] = currentState.sourceFrame.x; + filterArea[3] = currentState.sourceFrame.y; + + shader.uniforms.filterArea = filterArea; + } + + // use this to clamp displaced texture coords so they belong to filterArea + // see displacementFilter fragment shader for an example + if (shader.uniforms.data.filterClamp) { + currentState = this.filterData.stack[this.filterData.index]; + + var filterClamp = shader.uniforms.filterClamp; + + filterClamp[0] = 0; + filterClamp[1] = 0; + filterClamp[2] = (currentState.sourceFrame.width - 1) / currentState.renderTarget.size.width; + filterClamp[3] = (currentState.sourceFrame.height - 1) / currentState.renderTarget.size.height; + + shader.uniforms.filterClamp = filterClamp; + } + + // TODO Cacheing layer.. + for (var i in uniformData) { + if (uniformData[i].type === 'sampler2D') { + shader.uniforms[i] = textureCount; + + if (uniforms[i].baseTexture) { + this.renderer.bindTexture(uniforms[i].baseTexture, textureCount); + } else { + // this is helpful as renderTargets can also be set. + // Although thinking about it, we could probably + // make the filter texture cache return a RenderTexture + // rather than a renderTarget + var gl = this.renderer.gl; + + this.renderer._activeTextureLocation = gl.TEXTURE0 + textureCount; + + gl.activeTexture(gl.TEXTURE0 + textureCount); + uniforms[i].texture.bind(); + } + + textureCount++; + } else if (uniformData[i].type === 'mat3') { + // check if its pixi matrix.. + if (uniforms[i].a !== undefined) { + shader.uniforms[i] = uniforms[i].toArray(true); + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (uniformData[i].type === 'vec2') { + // check if its a point.. + if (uniforms[i].x !== undefined) { + var val = shader.uniforms[i] || new Float32Array(2); + + val[0] = uniforms[i].x; + val[1] = uniforms[i].y; + shader.uniforms[i] = val; + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (uniformData[i].type === 'float') { + if (shader.uniforms.data[i].value !== uniformData[i]) { + shader.uniforms[i] = uniforms[i]; + } + } else { + shader.uniforms[i] = uniforms[i]; + } + } + }; + + /** + * Gets a render target from the pool, or creates a new one. + * + * @param {boolean} clear - Should we clear the render texture when we get it? + * @param {number} resolution - The resolution of the target. + * @return {PIXI.RenderTarget} The new render target + */ + + + FilterManager.prototype.getRenderTarget = function getRenderTarget(clear, resolution) { + var currentState = this.filterData.stack[this.filterData.index]; + var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution); + + renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + return renderTarget; + }; + + /** + * Returns a render target to the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The render target to return. + */ + + + FilterManager.prototype.returnRenderTarget = function returnRenderTarget(renderTarget) { + this.freePotRenderTarget(renderTarget); + }; + + /** + * Calculates the mapped matrix. + * + * TODO playing around here.. this is temporary - (will end up in the shader) + * this returns a matrix that will normalise map filter cords in the filter to screen space + * + * @param {PIXI.Matrix} outputMatrix - the matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateScreenSpaceMatrix = function calculateScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); + }; + + /** + * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function calculateNormalizedScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); + }; + + /** + * This will map the filter coord so that a texture can be used based on the transform of a sprite + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateSpriteMatrix = function calculateSpriteMatrix(outputMatrix, sprite) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); + }; + + /** + * Destroys this Filter Manager. + * + */ + + + FilterManager.prototype.destroy = function destroy() { + this.shaderCache = []; + this.emptyPool(); + }; + + /** + * Gets a Power-of-Two render texture. + * + * TODO move to a seperate class could be on renderer? + * also - could cause issue with multiple contexts? + * + * @private + * @param {WebGLRenderingContext} gl - The webgl rendering context + * @param {number} minWidth - The minimum width of the render target. + * @param {number} minHeight - The minimum height of the render target. + * @param {number} resolution - The resolution of the render target. + * @return {PIXI.RenderTarget} The new render target. + */ + + + FilterManager.prototype.getPotRenderTarget = function getPotRenderTarget(gl, minWidth, minHeight, resolution) { + // TODO you coud return a bigger texture if there is not one in the pool? + minWidth = _bitTwiddle2.default.nextPow2(minWidth * resolution); + minHeight = _bitTwiddle2.default.nextPow2(minHeight * resolution); + + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + if (!this.pool[key]) { + this.pool[key] = []; + } + + var renderTarget = this.pool[key].pop() || new _RenderTarget2.default(gl, minWidth, minHeight, null, 1); + + // manually tweak the resolution... + // this will not modify the size of the frame buffer, just its resolution. + renderTarget.resolution = resolution; + renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution; + renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution; + + return renderTarget; + }; + + /** + * Empties the texture pool. + * + */ + + + FilterManager.prototype.emptyPool = function emptyPool() { + for (var i in this.pool) { + var textures = this.pool[i]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + + this.pool = {}; + }; + + /** + * Frees a render target back into the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free + */ + + + FilterManager.prototype.freePotRenderTarget = function freePotRenderTarget(renderTarget) { + var minWidth = renderTarget.size.width * renderTarget.resolution; + var minHeight = renderTarget.size.height * renderTarget.resolution; + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + this.pool[key].push(renderTarget); + }; + + return FilterManager; +}(_WebGLManager3.default); + +exports.default = FilterManager; + +},{"../../../Shader":77,"../../../math":102,"../filters/filterTransforms":120,"../utils/Quad":127,"../utils/RenderTarget":128,"./WebGLManager":125,"bit-twiddle":14}],123:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _SpriteMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); + +var _SpriteMaskFilter2 = _interopRequireDefault(_SpriteMaskFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var MaskManager = function (_WebGLManager) { + _inherits(MaskManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function MaskManager(renderer) { + _classCallCheck(this, MaskManager); + + // TODO - we don't need both! + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.scissor = false; + _this.scissorData = null; + _this.scissorRenderTarget = null; + + _this.enableScissor = true; + + _this.alphaMaskPool = []; + _this.alphaMaskIndex = 0; + return _this; + } + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushMask = function pushMask(target, maskData) { + if (maskData.texture) { + this.pushSpriteMask(target, maskData); + } else if (this.enableScissor && !this.scissor && !this.renderer.stencilManager.stencilMaskStack.length && maskData.isFastRect()) { + var matrix = maskData.worldTransform; + + var rot = Math.atan2(matrix.b, matrix.a); + + // use the nearest degree! + rot = Math.round(rot * (180 / Math.PI)); + + if (rot % 90) { + this.pushStencilMask(maskData); + } else { + this.pushScissorMask(target, maskData); + } + } else { + this.pushStencilMask(maskData); + } + }; + + /** + * Removes the last mask from the mask stack and doesn't return it. + * + * @param {PIXI.DisplayObject} target - Display Object to pop the mask from + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.popMask = function popMask(target, maskData) { + if (maskData.texture) { + this.popSpriteMask(target, maskData); + } else if (this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length) { + this.popScissorMask(target, maskData); + } else { + this.popStencilMask(target, maskData); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.RenderTarget} target - Display Object to push the sprite mask to + * @param {PIXI.Sprite} maskData - Sprite to be used as the mask + */ + + + MaskManager.prototype.pushSpriteMask = function pushSpriteMask(target, maskData) { + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new _SpriteMaskFilter2.default(maskData)]; + } + + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskData; + + // TODO - may cause issues! + target.filterArea = maskData.getBounds(true); + + this.renderer.filterManager.pushFilter(target, alphaMaskFilter); + + this.alphaMaskIndex++; + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popSpriteMask = function popSpriteMask() { + this.renderer.filterManager.popFilter(); + this.alphaMaskIndex--; + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushStencilMask = function pushStencilMask(maskData) { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.pushStencil(maskData); + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popStencilMask = function popStencilMask() { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.popStencil(); + }; + + /** + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushScissorMask = function pushScissorMask(target, maskData) { + maskData.renderable = true; + + var renderTarget = this.renderer._activeRenderTarget; + + var bounds = maskData.getBounds(); + + bounds.fit(renderTarget.size); + maskData.renderable = false; + + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + + var resolution = this.renderer.resolution; + + this.renderer.gl.scissor(bounds.x * resolution, (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution, bounds.width * resolution, bounds.height * resolution); + + this.scissorRenderTarget = renderTarget; + this.scissorData = maskData; + this.scissor = true; + }; + + /** + * + * + */ + + + MaskManager.prototype.popScissorMask = function popScissorMask() { + this.scissorRenderTarget = null; + this.scissorData = null; + this.scissor = false; + + // must be scissor! + var gl = this.renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + }; + + return MaskManager; +}(_WebGLManager3.default); + +exports.default = MaskManager; + +},{"../filters/spriteMask/SpriteMaskFilter":121,"./WebGLManager":125}],124:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var StencilManager = function (_WebGLManager) { + _inherits(StencilManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function StencilManager(renderer) { + _classCallCheck(this, StencilManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.stencilMaskStack = null; + return _this; + } + + /** + * Changes the mask stack that is used by this manager. + * + * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack + */ + + + StencilManager.prototype.setMaskStack = function setMaskStack(stencilMaskStack) { + this.stencilMaskStack = stencilMaskStack; + + var gl = this.renderer.gl; + + if (stencilMaskStack.length === 0) { + gl.disable(gl.STENCIL_TEST); + } else { + gl.enable(gl.STENCIL_TEST); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. @alvin + * + * @param {PIXI.Graphics} graphics - The mask + */ + + + StencilManager.prototype.pushStencil = function pushStencil(graphics) { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + this.renderer._activeRenderTarget.attachStencilBuffer(); + + var gl = this.renderer.gl; + var sms = this.stencilMaskStack; + + if (sms.length === 0) { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.stencilFunc(gl.ALWAYS, 1, 1); + } + + sms.push(graphics); + + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; + + /** + * TODO @alvin + */ + + + StencilManager.prototype.popStencil = function popStencil() { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + var gl = this.renderer.gl; + var sms = this.stencilMaskStack; + + var graphics = sms.pop(); + + if (sms.length === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + } else { + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + } + }; + + /** + * Destroys the mask stack. + * + */ + + + StencilManager.prototype.destroy = function destroy() { + _WebGLManager3.default.prototype.destroy.call(this); + + this.stencilMaskStack.stencilStack = null; + }; + + return StencilManager; +}(_WebGLManager3.default); + +exports.default = StencilManager; + +},{"./WebGLManager":125}],125:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var WebGLManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function WebGLManager(renderer) { + _classCallCheck(this, WebGLManager); + + /** + * The renderer this manager works for. + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + this.renderer.on('context', this.onContextChange, this); + } + + /** + * Generic method called when there is a WebGL context change. + * + */ + + + WebGLManager.prototype.onContextChange = function onContextChange() {} + // do some codes init! + + + /** + * Generic destroy methods to be overridden by the subclass + * + */ + ; + + WebGLManager.prototype.destroy = function destroy() { + this.renderer.off('context', this.onContextChange, this); + + this.renderer = null; + }; + + return WebGLManager; +}(); + +exports.default = WebGLManager; + +},{}],126:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('../managers/WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Base for a common object renderer that can be used as a system renderer plugin. + * + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var ObjectRenderer = function (_WebGLManager) { + _inherits(ObjectRenderer, _WebGLManager); + + function ObjectRenderer() { + _classCallCheck(this, ObjectRenderer); + + return _possibleConstructorReturn(this, _WebGLManager.apply(this, arguments)); + } + + /** + * Starts the renderer and sets the shader + * + */ + ObjectRenderer.prototype.start = function start() {} + // set the shader.. + + + /** + * Stops the renderer + * + */ + ; + + ObjectRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Stub method for rendering content and emptying the current batch. + * + */ + + + ObjectRenderer.prototype.flush = function flush() {} + // flush! + + + /** + * Renders an object + * + * @param {PIXI.DisplayObject} object - The object to render. + */ + ; + + ObjectRenderer.prototype.render = function render(object) // eslint-disable-line no-unused-vars + { + // render the object + }; + + return ObjectRenderer; +}(_WebGLManager3.default); + +exports.default = ObjectRenderer; + +},{"../managers/WebGLManager":125}],127:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a quad + * + * @class + * @memberof PIXI + */ +var Quad = function () { + /** + * @param {WebGLRenderingContext} gl - The gl context for this quad to use. + * @param {object} state - TODO: Description + */ + function Quad(gl, state) { + _classCallCheck(this, Quad); + + /* + * the current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]); + + /** + * The Uvs of the quad + * + * @member {Float32Array} + */ + this.uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + this.interleaved = new Float32Array(8 * 2); + + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + this.indices = (0, _createIndicesForQuads2.default)(1); + + /* + * @member {glCore.GLBuffer} The vertex buffer + */ + this.vertexBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW); + + /* + * @member {glCore.GLBuffer} The index buffer + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + /* + * @member {glCore.VertexArrayObject} The index buffer + */ + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, state); + } + + /** + * Initialises the vaos and uses the shader. + * + * @param {PIXI.Shader} shader - the shader to use + */ + + + Quad.prototype.initVao = function initVao(shader) { + this.vao.clear().addIndex(this.indexBuffer).addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0).addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4); + }; + + /** + * Maps two Rectangle to the quad. + * + * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle + * @param {PIXI.Rectangle} destinationFrame - the second rectangle + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.map = function map(targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + + this.uvs[0] = x; + this.uvs[1] = y; + + this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; + + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; + + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; + + x = destinationFrame.x; + y = destinationFrame.y; + + this.vertices[0] = x; + this.vertices[1] = y; + + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + + return this; + }; + + /** + * Draws the quad + * + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.draw = function draw() { + this.vao.bind().draw(this.gl.TRIANGLES, 6, 0).unbind(); + + return this; + }; + + /** + * Binds the buffer and uploads the data + * + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.upload = function upload() { + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + this.vertexBuffer.upload(this.interleaved); + + return this; + }; + + /** + * Removes this quad from WebGL + */ + + + Quad.prototype.destroy = function destroy() { + var gl = this.gl; + + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.indexBuffer); + }; + + return Quad; +}(); + +exports.default = Quad; + +},{"../../../utils/createIndicesForQuads":150,"pixi-gl-core":51}],128:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../../../math'); + +var _const = require('../../../const'); + +var _pixiGlCore = require('pixi-gl-core'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var RenderTarget = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {number} [width=0] - the horizontal range of the filter + * @param {number} [height=0] - the vertical range of the filter + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The current resolution / device pixel ratio + * @param {boolean} [root=false] - Whether this object is the root element or not + */ + function RenderTarget(gl, width, height, scaleMode, resolution, root) { + _classCallCheck(this, RenderTarget); + + // TODO Resolution could go here ( eg low res blurs ) + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // next time to create a frame buffer and texture + + /** + * A frame buffer + * + * @member {PIXI.glCore.GLFramebuffer} + */ + this.frameBuffer = null; + + /** + * The texture + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The background colour of this render target, as an array of [r,g,b,a] values + * + * @member {number[]} + */ + this.clearColor = [0, 0, 0, 0]; + + /** + * The size of the object as a rectangle + * + * @member {PIXI.Rectangle} + */ + this.size = new _math.Rectangle(0, 0, 1, 1); + + /** + * The current resolution / device pixel ratio + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || _const.RESOLUTION; + + /** + * The projection matrix + * + * @member {PIXI.Matrix} + */ + this.projectionMatrix = new _math.Matrix(); + + /** + * The object's transform + * + * @member {PIXI.Matrix} + */ + this.transform = null; + + /** + * The frame. + * + * @member {PIXI.Rectangle} + */ + this.frame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.defaultFrame = new _math.Rectangle(); + this.destinationFrame = null; + this.sourceFrame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.stencilBuffer = null; + + /** + * The data structure for the stencil masks + * + * @member {PIXI.Graphics[]} + */ + this.stencilMaskStack = []; + + /** + * Stores filter data for the render target + * + * @member {object[]} + */ + this.filterData = null; + + /** + * The scale mode. + * + * @member {number} + * @default PIXI.SCALE_MODES.DEFAULT + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode || _const.SCALE_MODES.DEFAULT; + + /** + * Whether this object is the root element or not + * + * @member {boolean} + */ + this.root = root; + + if (!this.root) { + this.frameBuffer = _pixiGlCore.GLFramebuffer.createRGBA(gl, 100, 100); + + if (this.scaleMode === _const.SCALE_MODES.NEAREST) { + this.frameBuffer.texture.enableNearestScaling(); + } else { + this.frameBuffer.texture.enableLinearScaling(); + } + /* + A frame buffer needs a target to render to.. + create a texture and bind it attach it to the framebuffer.. + */ + + // this is used by the base texture + this.texture = this.frameBuffer.texture; + } else { + // make it a null framebuffer.. + this.frameBuffer = new _pixiGlCore.GLFramebuffer(gl, 100, 100); + this.frameBuffer.framebuffer = null; + } + + this.setFrame(); + + this.resize(width, height); + } + + /** + * Clears the filter texture. + * + * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer + */ + + + RenderTarget.prototype.clear = function clear(clearColor) { + var cc = clearColor || this.clearColor; + + this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a); + }; + + /** + * Binds the stencil buffer. + * + */ + + + RenderTarget.prototype.attachStencilBuffer = function attachStencilBuffer() { + // TODO check if stencil is done? + /** + * The stencil buffer is used for masking in pixi + * lets create one and then add attach it to the framebuffer.. + */ + if (!this.root) { + this.frameBuffer.enableStencil(); + } + }; + + /** + * Sets the frame of the render target. + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.setFrame = function setFrame(destinationFrame, sourceFrame) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; + }; + + /** + * Binds the buffers and initialises the viewport. + * + */ + + + RenderTarget.prototype.activate = function activate() { + // TOOD refactor usage of frame.. + var gl = this.gl; + + // make surethe texture is unbound! + this.frameBuffer.bind(); + + this.calculateProjection(this.destinationFrame, this.sourceFrame); + + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + + // TODO add a check as them may be the same! + if (this.destinationFrame !== this.sourceFrame) { + gl.enable(gl.SCISSOR_TEST); + gl.scissor(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + } else { + gl.disable(gl.SCISSOR_TEST); + } + + // TODO - does not need to be updated all the time?? + gl.viewport(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + }; + + /** + * Updates the projection matrix based on a projection frame (which is a rectangle) + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.calculateProjection = function calculateProjection(destinationFrame, sourceFrame) { + var pm = this.projectionMatrix; + + sourceFrame = sourceFrame || destinationFrame; + + pm.identity(); + + // TODO: make dest scale source + if (!this.root) { + pm.a = 1 / destinationFrame.width * 2; + pm.d = 1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = -1 - sourceFrame.y * pm.d; + } else { + pm.a = 1 / destinationFrame.width * 2; + pm.d = -1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = 1 - sourceFrame.y * pm.d; + } + }; + + /** + * Resizes the texture to the specified width and height + * + * @param {number} width - the new width of the texture + * @param {number} height - the new height of the texture + */ + + + RenderTarget.prototype.resize = function resize(width, height) { + width = width | 0; + height = height | 0; + + if (this.size.width === width && this.size.height === height) { + return; + } + + this.size.width = width; + this.size.height = height; + + this.defaultFrame.width = width; + this.defaultFrame.height = height; + + this.frameBuffer.resize(width * this.resolution, height * this.resolution); + + var projectionFrame = this.frame || this.size; + + this.calculateProjection(projectionFrame); + }; + + /** + * Destroys the render target. + * + */ + + + RenderTarget.prototype.destroy = function destroy() { + this.frameBuffer.destroy(); + + this.frameBuffer = null; + this.texture = null; + }; + + return RenderTarget; +}(); + +exports.default = RenderTarget; + +},{"../../../const":78,"../../../math":102,"pixi-gl-core":51}],129:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = checkMaxIfStatmentsInShader; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['precision mediump float;', 'void main(void){', 'float test = 0.1;', '%forloop%', 'gl_FragColor = vec4(0.0);', '}'].join('\n'); + +function checkMaxIfStatmentsInShader(maxIfs, gl) { + var createTempContext = !gl; + + if (createTempContext) { + var tinyCanvas = document.createElement('canvas'); + + tinyCanvas.width = 1; + tinyCanvas.height = 1; + + gl = _pixiGlCore2.default.createContext(tinyCanvas); + } + + var shader = gl.createShader(gl.FRAGMENT_SHADER); + + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = maxIfs / 2 | 0; + } else { + // valid! + break; + } + } + + if (createTempContext) { + // get rid of context + if (gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').loseContext(); + } + } + + return maxIfs; +} + +function generateIfTestSrc(maxIfs) { + var src = ''; + + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxIfs - 1) { + src += 'if(test == ' + i + '.0){}'; + } + } + + return src; +} + +},{"pixi-gl-core":51}],130:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLBlendModesToPixi; + +var _const = require('../../../const'); + +/** + * Maps gl blend combinations to WebGL. + * + * @memberof PIXI + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapWebGLBlendModesToPixi(gl) { + var array = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1]; + + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[_const.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD] = [gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + array[_const.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + return array; +} + +},{"../../../const":78}],131:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLDrawModesToPixi; + +var _const = require('../../../const'); + +/** + * Generic Mask Stack data structure. + * + * @class + * @memberof PIXI + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {object} [object={}] - The object to map into + * @return {object} The mapped draw modes. + */ +function mapWebGLDrawModesToPixi(gl) { + var object = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + + object[_const.DRAW_MODES.POINTS] = gl.POINTS; + object[_const.DRAW_MODES.LINES] = gl.LINES; + object[_const.DRAW_MODES.LINE_LOOP] = gl.LINE_LOOP; + object[_const.DRAW_MODES.LINE_STRIP] = gl.LINE_STRIP; + object[_const.DRAW_MODES.TRIANGLES] = gl.TRIANGLES; + object[_const.DRAW_MODES.TRIANGLE_STRIP] = gl.TRIANGLE_STRIP; + object[_const.DRAW_MODES.TRIANGLE_FAN] = gl.TRIANGLE_FAN; + + return object; +} + +},{"../../../const":78}],132:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = validateContext; +function validateContext(gl) { + var attributes = gl.getContextAttributes(); + + // this is going to be fairly simple for now.. but at least we have rom to grow! + if (!attributes.stencil) { + /* eslint-disable no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable no-console */ + } +} + +},{}],133:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new _math.Point(); + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = new PIXI.Sprite.fromImage('assets/image.png'); + * ``` + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Sprite = function (_Container) { + _inherits(Sprite, _Container); + + /** + * @param {PIXI.Texture} texture - The texture for this sprite + */ + function Sprite(texture) { + _classCallCheck(this, Sprite); + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + * @private + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this._anchor = new _math.ObservablePoint(_this._onAnchorUpdate, _this); + + /** + * The texture that the sprite is using + * + * @private + * @member {PIXI.Texture} + */ + _this._texture = null; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = null; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * The shader that will be used to render the sprite. Set to null to remove a current shader. + * + * @member {PIXI.AbstractFilter|PIXI.Shader} + */ + _this.shader = null; + + /** + * An internal cached value of the tint. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this.cachedTint = 0xFFFFFF; + + // call texture setter + _this.texture = texture || _Texture2.default.EMPTY; + + /** + * this is used to store the vertex data of the sprite (basically a quad) + * + * @private + * @member {Float32Array} + */ + _this.vertexData = new Float32Array(8); + + /** + * This is used to calculate the bounds of the object IF it is a trimmed sprite + * + * @private + * @member {Float32Array} + */ + _this.vertexTrimmedData = null; + + _this._transformID = -1; + _this._textureID = -1; + return _this; + } + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Sprite.prototype._onTextureUpdate = function _onTextureUpdate() { + this._textureID = -1; + + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = (0, _utils.sign)(this.scale.x) * this._width / this.texture.orig.width; + } + + if (this._height) { + this.scale.y = (0, _utils.sign)(this.scale.y) * this._height / this.texture.orig.height; + } + }; + + /** + * Called when the anchor position updates. + * + * @private + */ + + + Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate() { + this._transformID = -1; + }; + + /** + * calculates worldTransform * vertices, store it in vertexData + */ + + + Sprite.prototype.calculateVertices = function calculateVertices() { + if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) { + return; + } + + this._transformID = this.transform._worldID; + this._textureID = this._texture._updateID; + + // set the vertex data + + var texture = this._texture; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - this.anchor._x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - this.anchor._y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - this.anchor._x); + w1 = orig.width * -this.anchor._x; + + h0 = orig.height * (1 - this.anchor._y); + h1 = orig.height * -this.anchor._y; + } + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData + * This is used to ensure that the true width and height of a trimmed texture is respected + */ + + + Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices() { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } + + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + + var w0 = orig.width * (1 - this.anchor._x); + var w1 = orig.width * -this.anchor._x; + + var h0 = orig.height * (1 - this.anchor._y); + var h1 = orig.height * -this.anchor._y; + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use. + */ + + + Sprite.prototype._renderWebGL = function _renderWebGL(renderer) { + this.calculateVertices(); + + renderer.setObjectRenderer(renderer.plugins.sprite); + renderer.plugins.sprite.render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Sprite.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins.sprite.render(this); + }; + + /** + * Updates the bounds of the sprite. + * + * @private + */ + + + Sprite.prototype._calculateBounds = function _calculateBounds() { + var trim = this._texture.trim; + var orig = this._texture.orig; + + // First lets check to see if the current texture has a trim.. + if (!trim || trim.width === orig.width && trim.height === orig.height) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {Rectangle} rect - The output rectangle. + * @return {Rectangle} The bounds. + */ + + + Sprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = -this._texture.orig.width * this.anchor._x; + this._bounds.minY = -this._texture.orig.height * this.anchor._y; + this._bounds.maxX = this._texture.orig.width; + this._bounds.maxY = this._texture.orig.height; + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _Container.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Tests if a point is inside this sprite + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Sprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + + if (tempPoint.x > x1 && tempPoint.x < x1 + width) { + y1 = -height * this.anchor.y; + + if (tempPoint.y > y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + Sprite.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + this._anchor = null; + + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + + this._texture.destroy(!!destroyBaseTexture); + } + + this._texture = null; + this.shader = null; + }; + + // some helper functions.. + + /** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ + + + Sprite.from = function from(source) { + return new Sprite(_Texture2.default.from(source)); + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId + */ + + + Sprite.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return new Sprite(texture); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id + */ + + + Sprite.fromImage = function fromImage(imageId, crossorigin, scaleMode) { + return new Sprite(_Texture2.default.fromImage(imageId, crossorigin, scaleMode)); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Sprite# + */ + + + _createClass(Sprite, [{ + key: 'width', + get: function get() { + return Math.abs(this.scale.x) * this.texture.orig.width; + } + + /** + * Sets the width of the sprite by modifying the scale. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this.texture.orig.width; + this._width = value; + } + + /** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Sprite# + */ + + }, { + key: 'height', + get: function get() { + return Math.abs(this.scale.y) * this.texture.orig.height; + } + + /** + * Sets the height of the sprite by modifying the scale. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this.texture.orig.height; + this._height = value; + } + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + * @memberof PIXI.Sprite# + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + } + + /** + * Copies the anchor to the sprite. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this._anchor.copy(value); + } + + /** + * The tint applied to the sprite. This is a hex value. A value of + * 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @memberof PIXI.Sprite# + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return this._tint; + } + + /** + * Sets the tint of the sprite. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + } + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + * @memberof PIXI.Sprite# + */ + + }, { + key: 'texture', + get: function get() { + return this._texture; + } + + /** + * Sets the texture of the sprite. + * + * @param {PIXI.Texture} value - The value to set to. + */ + , + set: function set(value) { + if (this._texture === value) { + return; + } + + this._texture = value; + this.cachedTint = 0xFFFFFF; + + this._textureID = -1; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + }]); + + return Sprite; +}(_Container3.default); + +exports.default = Sprite; + +},{"../const":78,"../display/Container":80,"../math":102,"../textures/Texture":144,"../utils":152}],134:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +var _math = require('../../math'); + +var _CanvasTinter = require('./CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var canvasRenderWorldTransform = new _math.Matrix(); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasSpriteRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + */ + +var CanvasSpriteRenderer = function () { + /** + * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for. + */ + function CanvasSpriteRenderer(renderer) { + _classCallCheck(this, CanvasSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + CanvasSpriteRenderer.prototype.render = function render(sprite) { + var texture = sprite._texture; + var renderer = this.renderer; + + var width = texture._frame.width; + var height = texture._frame.height; + + var wt = sprite.transform.worldTransform; + var dx = 0; + var dy = 0; + + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) { + return; + } + + renderer.setBlendMode(sprite.blendMode); + + // Ignore null sources + if (texture.valid) { + renderer.context.globalAlpha = sprite.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture + var smoothingEnabled = texture.baseTexture.scaleMode === _const.SCALE_MODES.LINEAR; + + if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) { + renderer.context[renderer.smoothProperty] = smoothingEnabled; + } + + if (texture.trim) { + dx = texture.trim.width / 2 + texture.trim.x - sprite.anchor.x * texture.orig.width; + dy = texture.trim.height / 2 + texture.trim.y - sprite.anchor.y * texture.orig.height; + } else { + dx = (0.5 - sprite.anchor.x) * texture.orig.width; + dy = (0.5 - sprite.anchor.y) * texture.orig.height; + } + + if (texture.rotate) { + wt.copy(canvasRenderWorldTransform); + wt = canvasRenderWorldTransform; + _math.GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); + // the anchor has already been applied above, so lets set it to zero + dx = 0; + dy = 0; + } + + dx -= width / 2; + dy -= height / 2; + + // Allow for pixel rounding + if (renderer.roundPixels) { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution | 0, wt.ty * renderer.resolution | 0); + + dx = dx | 0; + dy = dy | 0; + } else { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution, wt.ty * renderer.resolution); + } + + var resolution = texture.baseTexture.resolution; + + if (sprite.tint !== 0xFFFFFF) { + if (sprite.cachedTint !== sprite.tint) { + sprite.cachedTint = sprite.tint; + + // TODO clean up caching - how to clean up the caches? + sprite.tintedTexture = _CanvasTinter2.default.getTintedTexture(sprite, sprite.tint); + } + + renderer.context.drawImage(sprite.tintedTexture, 0, 0, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } else { + renderer.context.drawImage(texture.baseTexture.source, texture._frame.x * resolution, texture._frame.y * resolution, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } + } + }; + + /** + * destroy the sprite object. + * + */ + + + CanvasSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasSpriteRenderer; +}(); + +exports.default = CanvasSpriteRenderer; + + +_CanvasRenderer2.default.registerPlugin('sprite', CanvasSpriteRenderer); + +},{"../../const":78,"../../math":102,"../../renderers/canvas/CanvasRenderer":109,"./CanvasTinter":135}],135:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Utility methods for Sprite/Texture tinting. + * + * @namespace PIXI.CanvasTinter + */ +var CanvasTinter = { + /** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Sprite} sprite - the sprite to tint + * @param {number} color - the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ + getTintedTexture: function getTintedTexture(sprite, color) { + var texture = sprite.texture; + + color = CanvasTinter.roundColor(color); + + var stringColor = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + texture.tintCache = texture.tintCache || {}; + + if (texture.tintCache[stringColor]) { + return texture.tintCache[stringColor]; + } + + // clone texture.. + var canvas = CanvasTinter.canvas || document.createElement('canvas'); + + // CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); + CanvasTinter.tintMethod(texture, color, canvas); + + if (CanvasTinter.convertTintToImage) { + // is this better? + var tintImage = new Image(); + + tintImage.src = canvas.toDataURL(); + + texture.tintCache[stringColor] = tintImage; + } else { + texture.tintCache[stringColor] = canvas; + // if we are not converting the texture to an image then we need to lose the reference to the canvas + CanvasTinter.canvas = null; + } + + return canvas; + }, + + /** + * Tint a texture using the 'multiply' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithMultiply: function tintWithMultiply(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = crop.width; + canvas.height = crop.height; + + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + }, + + /** + * Tint a texture using the 'overlay' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithOverlay: function tintWithOverlay(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = crop.width; + canvas.height = crop.height; + + context.globalCompositeOperation = 'copy'; + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + // context.globalCompositeOperation = 'copy'; + }, + + + /** + * Tint a texture pixel per pixel. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithPerPixel: function tintWithPerPixel(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = crop.width; + canvas.height = crop.height; + + context.globalCompositeOperation = 'copy'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + var rgbValues = (0, _utils.hex2rgb)(color); + var r = rgbValues[0]; + var g = rgbValues[1]; + var b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, crop.width, crop.height); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + } + + context.putImageData(pixelData, 0, 0); + }, + + /** + * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel. + * + * @memberof PIXI.CanvasTinter + * @param {number} color - the color to round, should be a hex color + * @return {number} The rounded color. + */ + roundColor: function roundColor(color) { + var step = CanvasTinter.cacheStepsPerColorChannel; + + var rgbValues = (0, _utils.hex2rgb)(color); + + rgbValues[0] = Math.min(255, rgbValues[0] / step * step); + rgbValues[1] = Math.min(255, rgbValues[1] / step * step); + rgbValues[2] = Math.min(255, rgbValues[2] / step * step); + + return (0, _utils.rgb2hex)(rgbValues); + }, + + /** + * Number of steps which will be used as a cap when rounding colors. + * + * @memberof PIXI.CanvasTinter + * @type {number} + */ + cacheStepsPerColorChannel: 8, + + /** + * Tint cache boolean flag. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + convertTintToImage: false, + + /** + * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + canUseMultiply: (0, _canUseNewCanvasBlendModes2.default)(), + + /** + * The tinting method that will be used. + * + * @memberof PIXI.CanvasTinter + * @type {tintMethodFunctionType} + */ + tintMethod: 0 +}; + +CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply : CanvasTinter.tintWithPerPixel; + +/** + * The tintMethod type. + * + * @memberof PIXI.CanvasTinter + * @callback tintMethodFunctionType + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + +exports.default = CanvasTinter; + +},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":112,"../../utils":152}],136:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + */ +var Buffer = function () { + /** + * @param {number} size - The size of the buffer in bytes. + */ + function Buffer(size) { + _classCallCheck(this, Buffer); + + this.vertices = new ArrayBuffer(size); + + /** + * View on the vertices as a Float32Array for positions + * + * @member {Float32Array} + */ + this.float32View = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array for uvs + * + * @member {Float32Array} + */ + this.uint32View = new Uint32Array(this.vertices); + } + + /** + * Destroys the buffer. + * + */ + + + Buffer.prototype.destroy = function destroy() { + this.vertices = null; + this.positions = null; + this.uvs = null; + this.colors = null; + }; + + return Buffer; +}(); + +exports.default = Buffer; + +},{}],137:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _createIndicesForQuads = require('../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +var _generateMultiTextureShader = require('./generateMultiTextureShader'); + +var _generateMultiTextureShader2 = _interopRequireDefault(_generateMultiTextureShader); + +var _checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'); + +var _checkMaxIfStatmentsInShader2 = _interopRequireDefault(_checkMaxIfStatmentsInShader); + +var _BatchBuffer = require('./BatchBuffer'); + +var _BatchBuffer2 = _interopRequireDefault(_BatchBuffer); + +var _const = require('../../const'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var TICK = 0; + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var SpriteRenderer = function (_ObjectRenderer) { + _inherits(SpriteRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function SpriteRenderer(renderer) { + _classCallCheck(this, SpriteRenderer); + + /** + * Number of values sent in the vertex buffer. + * positionX, positionY, colorR, colorG, colorB = 5 + * + * @member {number} + */ + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.vertSize = 5; + + /** + * The size of the vertex information in bytes. + * + * @member {number} + */ + _this.vertByteSize = _this.vertSize * 4; + + /** + * The number of images in the SpriteBatch before it flushes. + * + * @member {number} + */ + _this.size = _const.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + + // the total number of bytes in our batch + // let numVerts = this.size * 4 * this.vertByteSize; + + _this.buffers = []; + for (var i = 1; i <= _bitTwiddle2.default.nextPow2(_this.size); i *= 2) { + _this.buffers.push(new _BatchBuffer2.default(i * 4 * _this.vertByteSize)); + } + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + _this.indices = (0, _createIndicesForQuads2.default)(_this.size); + + /** + * The default shaders that is used if a sprite doesn't have a more specific one. + * there is a shader for each number of textures that can be rendererd. + * These shaders will also be generated on the fly as required. + * @member {PIXI.Shader[]} + */ + _this.shaders = null; + + _this.currentIndex = 0; + TICK = 0; + _this.groups = []; + + for (var k = 0; k < _this.size; k++) { + _this.groups[k] = { textures: [], textureCount: 0, ids: [], size: 0, start: 0, blend: 0 }; + } + + _this.sprites = []; + + _this.vertexBuffers = []; + _this.vaos = []; + + _this.vaoMax = 2; + _this.vertexCount = 0; + + _this.renderer.on('prerender', _this.onPrerender, _this); + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + SpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), _const.SPRITE_MAX_TEXTURES); + + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = (0, _checkMaxIfStatmentsInShader2.default)(this.MAX_TEXTURES, gl); + + this.shaders = new Array(this.MAX_TEXTURES); + this.shaders[0] = (0, _generateMultiTextureShader2.default)(gl, 1); + this.shaders[1] = (0, _generateMultiTextureShader2.default)(gl, 2); + + // create a couple of buffers + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + // we use the second shader as the first one depending on your browser may omit aTextureId + // as it is not used by the shader so is optimized out. + var shader = this.shaders[1]; + + for (var i = 0; i < this.vaoMax; i++) { + this.vertexBuffers[i] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + + /* eslint-disable max-len */ + + // build the vao object that will render.. + this.vaos[i] = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(this.vertexBuffers[i], shader.attributes.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(this.vertexBuffers[i], shader.attributes.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(this.vertexBuffers[i], shader.attributes.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4).addAttribute(this.vertexBuffers[i], shader.attributes.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + + /* eslint-disable max-len */ + } + + this.vao = this.vaos[0]; + this.currentBlendMode = 99999; + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + SpriteRenderer.prototype.onPrerender = function onPrerender() { + this.vertexCount = 0; + }; + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + SpriteRenderer.prototype.render = function render(sprite) { + // TODO set blend modes.. + // check texture.. + if (this.currentIndex >= this.size) { + this.flush(); + } + + // get the uvs for the texture + + // if the uvs have not updated then no point rendering just yet! + if (!sprite.texture._uvs) { + return; + } + + // push a texture. + // increment the batchsize + this.sprites[this.currentIndex++] = sprite; + }; + + /** + * Renders the content and empties the current batch. + * + */ + + + SpriteRenderer.prototype.flush = function flush() { + if (this.currentIndex === 0) { + return; + } + + var gl = this.renderer.gl; + + var np2 = _bitTwiddle2.default.nextPow2(this.currentIndex); + var log2 = _bitTwiddle2.default.log2(np2); + var buffer = this.buffers[log2]; + + var sprites = this.sprites; + var groups = this.groups; + + var float32View = buffer.float32View; + var uint32View = buffer.uint32View; + + var index = 0; + var nextTexture = void 0; + var currentTexture = void 0; + var groupCount = 1; + var textureCount = 0; + var currentGroup = groups[0]; + var vertexData = void 0; + var tint = void 0; + var uvs = void 0; + var textureId = void 0; + var blendMode = sprites[0].blendMode; + var shader = void 0; + + currentGroup.textureCount = 0; + currentGroup.start = 0; + currentGroup.blend = blendMode; + + TICK++; + + var i = void 0; + + for (i = 0; i < this.currentIndex; i++) { + // upload the sprite elemetns... + // they have all ready been calculated so we just need to push them into the buffer. + var sprite = sprites[i]; + + nextTexture = sprite._texture.baseTexture; + + if (blendMode !== sprite.blendMode) { + blendMode = sprite.blendMode; + + // force the batch to break! + currentTexture = null; + textureCount = this.MAX_TEXTURES; + TICK++; + } + + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + + if (nextTexture._enabled !== TICK) { + if (textureCount === this.MAX_TEXTURES) { + TICK++; + + textureCount = 0; + + currentGroup.size = i - currentGroup.start; + + currentGroup = groups[groupCount++]; + currentGroup.textureCount = 0; + currentGroup.blend = blendMode; + currentGroup.start = i; + } + + nextTexture._enabled = TICK; + nextTexture._id = textureCount; + + currentGroup.textures[currentGroup.textureCount++] = nextTexture; + textureCount++; + } + } + + vertexData = sprite.vertexData; + + // TODO this sum does not need to be set each frame.. + tint = sprite._tintRGB + (sprite.worldAlpha * 255 << 24); + uvs = sprite._texture._uvs.uvsUint32; + textureId = nextTexture._id; + + if (this.renderer.roundPixels) { + var resolution = this.renderer.resolution; + + // xy + float32View[index] = (vertexData[0] * resolution | 0) / resolution; + float32View[index + 1] = (vertexData[1] * resolution | 0) / resolution; + + // xy + float32View[index + 5] = (vertexData[2] * resolution | 0) / resolution; + float32View[index + 6] = (vertexData[3] * resolution | 0) / resolution; + + // xy + float32View[index + 10] = (vertexData[4] * resolution | 0) / resolution; + float32View[index + 11] = (vertexData[5] * resolution | 0) / resolution; + + // xy + float32View[index + 15] = (vertexData[6] * resolution | 0) / resolution; + float32View[index + 16] = (vertexData[7] * resolution | 0) / resolution; + } else { + // xy + float32View[index] = vertexData[0]; + float32View[index + 1] = vertexData[1]; + + // xy + float32View[index + 5] = vertexData[2]; + float32View[index + 6] = vertexData[3]; + + // xy + float32View[index + 10] = vertexData[4]; + float32View[index + 11] = vertexData[5]; + + // xy + float32View[index + 15] = vertexData[6]; + float32View[index + 16] = vertexData[7]; + } + + uint32View[index + 2] = uvs[0]; + uint32View[index + 7] = uvs[1]; + uint32View[index + 12] = uvs[2]; + uint32View[index + 17] = uvs[3]; + + uint32View[index + 3] = uint32View[index + 8] = uint32View[index + 13] = uint32View[index + 18] = tint; + float32View[index + 4] = float32View[index + 9] = float32View[index + 14] = float32View[index + 19] = textureId; + + index += 20; + } + + currentGroup.size = i - currentGroup.start; + + this.vertexCount++; + + if (this.vaoMax <= this.vertexCount) { + this.vaoMax++; + shader = this.shaders[1]; + this.vertexBuffers[this.vertexCount] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + // build the vao object that will render.. + this.vaos[this.vertexCount] = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(this.vertexBuffers[this.vertexCount], shader.attributes.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(this.vertexBuffers[this.vertexCount], shader.attributes.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(this.vertexBuffers[this.vertexCount], shader.attributes.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4).addAttribute(this.vertexBuffers[this.vertexCount], shader.attributes.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0); + this.vao = this.vaos[this.vertexCount].bind(); + + // / render the groups.. + for (i = 0; i < groupCount; i++) { + var group = groups[i]; + var groupTextureCount = group.textureCount; + + shader = this.shaders[groupTextureCount - 1]; + + if (!shader) { + shader = this.shaders[groupTextureCount - 1] = (0, _generateMultiTextureShader2.default)(gl, groupTextureCount); + // console.log("SHADER generated for " + textureCount + " textures") + } + + this.renderer.bindShader(shader); + + for (var j = 0; j < groupTextureCount; j++) { + this.renderer.bindTexture(group.textures[j], j); + } + + // set the blend mode.. + this.renderer.state.setBlendMode(group.blend); + + gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); + } + + // reset elements for the next flush + this.currentIndex = 0; + }; + + /** + * Starts a new sprite batch. + * + */ + + + SpriteRenderer.prototype.start = function start() {} + // this.renderer.bindShader(this.shader); + // TICK %= 1000; + + + /** + * Stops and flushes the current batch. + * + */ + ; + + SpriteRenderer.prototype.stop = function stop() { + this.flush(); + this.vao.unbind(); + }; + + /** + * Destroys the SpriteBatch. + * + */ + + + SpriteRenderer.prototype.destroy = function destroy() { + for (var i = 0; i < this.vaoMax; i++) { + this.vertexBuffers[i].destroy(); + this.vaos[i].destroy(); + } + + this.indexBuffer.destroy(); + + this.renderer.off('prerender', this.onPrerender, this); + + _ObjectRenderer.prototype.destroy.call(this); + + for (var _i = 0; _i < this.shaders.length; _i++) { + if (this.shaders[_i]) { + this.shaders[_i].destroy(); + } + } + + this.vertexBuffers = null; + this.vaos = null; + this.indexBuffer = null; + this.indices = null; + + this.sprites = null; + + for (var _i2 = 0; _i2 < this.buffers.length; _i2++) { + this.buffers[_i2].destroy(); + } + }; + + return SpriteRenderer; +}(_ObjectRenderer3.default); + +exports.default = SpriteRenderer; + + +_WebGLRenderer2.default.registerPlugin('sprite', SpriteRenderer); + +},{"../../const":78,"../../renderers/webgl/WebGLRenderer":116,"../../renderers/webgl/utils/ObjectRenderer":126,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":129,"../../utils/createIndicesForQuads":150,"./BatchBuffer":136,"./generateMultiTextureShader":138,"bit-twiddle":14,"pixi-gl-core":51}],138:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateMultiTextureShader; + +var _Shader = require('../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + + // eslint-disable-line no-undef + +var fragTemplate = ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'varying float vTextureId;', 'uniform sampler2D uSamplers[%count%];', 'void main(void){', 'vec4 color;', 'float textureId = floor(vTextureId+0.5);', '%forloop%', 'gl_FragColor = color * vColor;', '}'].join('\n'); + +function generateMultiTextureShader(gl, maxTextures) { + var vertexSrc = "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = vec4(aColor.rgb * aColor.a, aColor.a);\n}\n"; + var fragmentSrc = fragTemplate; + + fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); + + var shader = new _Shader2.default(gl, vertexSrc, fragmentSrc); + + var sampleValues = []; + + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + + shader.bind(); + shader.uniforms.uSamplers = sampleValues; + + return shader; +} + +function generateSampleSrc(maxTextures) { + var src = ''; + + src += '\n'; + src += '\n'; + + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxTextures - 1) { + src += 'if(textureId == ' + i + '.0)'; + } + + src += '\n{'; + src += '\n\tcolor = texture2D(uSamplers[' + i + '], vTextureCoord);'; + src += '\n}'; + } + + src += '\n'; + src += '\n'; + + return src; +} + +},{"../../Shader":77}],139:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Sprite2 = require('../sprites/Sprite'); + +var _Sprite3 = _interopRequireDefault(_Sprite2); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _TextStyle = require('./TextStyle'); + +var _TextStyle2 = _interopRequireDefault(_TextStyle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint max-depth: [2, 8] */ + + +var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true +}; + +/** + * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string, + * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object. + * + * A Text can be created directly from a string and a style object + * + * ```js + * let text = new PIXI.Text('This is a pixi text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI + */ + +var Text = function (_Sprite) { + _inherits(Text, _Sprite); + + /** + * @param {string} text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + */ + function Text(text, style) { + _classCallCheck(this, Text); + + var canvas = document.createElement('canvas'); + + canvas.width = 9; + canvas.height = 10; + + var texture = _Texture2.default.fromCanvas(canvas); + + texture.orig = new _math.Rectangle(); + texture.trim = new _math.Rectangle(); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + var _this = _possibleConstructorReturn(this, _Sprite.call(this, texture)); + + _this.canvas = canvas; + + /** + * The canvas 2d context that everything is drawn with + * @member {HTMLCanvasElement} + */ + _this.context = _this.canvas.getContext('2d'); + + /** + * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. + * @member {number} + * @default 1 + */ + _this.resolution = _const.RESOLUTION; + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = null; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._style = null; + /** + * Private listener to track style changes. + * + * @member {Function} + * @private + */ + _this._styleListener = null; + + /** + * Private tracker for the current font. + * + * @member {string} + * @private + */ + _this._font = ''; + + _this.text = text; + _this.style = style; + + _this.localStyleID = -1; + return _this; + } + + /** + * Renders text and updates it when needed. + * + * @private + * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. + */ + + + Text.prototype.updateText = function updateText(respectDirty) { + var style = this._style; + + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + + if (!this.dirty && respectDirty) { + return; + } + + // build canvas api font setting from invididual components. Convert a numeric style.fontSize to px + var fontSizeString = typeof style.fontSize === 'number' ? style.fontSize + 'px' : style.fontSize; + + this._font = style.fontStyle + ' ' + style.fontVariant + ' ' + style.fontWeight + ' ' + fontSizeString + ' ' + style.fontFamily; + + this.context.font = this._font; + + // word wrap + // preserve original text + var outputText = style.wordWrap ? this.wordWrap(this._text) : this._text; + + // split text into lines + var lines = outputText.split(/(?:\r\n|\r|\n)/); + + // calculate text width + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + var fontProperties = this.determineFontProperties(this._font); + + for (var i = 0; i < lines.length; i++) { + var lineWidth = this.context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing; + + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + + var width = maxLineWidth + style.strokeThickness; + + if (style.dropShadow) { + width += style.dropShadowDistance; + } + + width += style.padding * 2; + + this.canvas.width = Math.ceil((width + this.context.lineWidth) * this.resolution); + + // calculate text height + var lineHeight = this.style.lineHeight || fontProperties.fontSize + style.strokeThickness; + + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * lineHeight; + + if (style.dropShadow) { + height += style.dropShadowDistance; + } + + this.canvas.height = Math.ceil((height + this._style.padding * 2) * this.resolution); + + this.context.scale(this.resolution, this.resolution); + + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + + this.context.font = this._font; + this.context.strokeStyle = style.stroke; + this.context.lineWidth = style.strokeThickness; + this.context.textBaseline = style.textBaseline; + this.context.lineJoin = style.lineJoin; + this.context.miterLimit = style.miterLimit; + + var linePositionX = void 0; + var linePositionY = void 0; + + if (style.dropShadow) { + if (style.dropShadowBlur > 0) { + this.context.shadowColor = style.dropShadowColor; + this.context.shadowBlur = style.dropShadowBlur; + } else { + this.context.fillStyle = style.dropShadowColor; + } + + var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + + for (var _i = 0; _i < lines.length; _i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i]) / 2; + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); + + if (style.stroke && style.strokeThickness) { + this.context.strokeStyle = style.dropShadowColor; + this.drawLetterSpacing(lines[_i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding, true); + this.context.strokeStyle = style.stroke; + } + } + } + } + + // set canvas text styles + this.context.fillStyle = this._generateFillStyle(style, lines); + + // draw lines line by line + for (var _i2 = 0; _i2 < lines.length; _i2++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i2 * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i2]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i2]) / 2; + } + + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[_i2], linePositionX + style.padding, linePositionY + style.padding, true); + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i2], linePositionX + style.padding, linePositionY + style.padding); + } + } + + this.updateTexture(); + }; + + /** + * Render the text with letter-spacing. + * @param {string} text - The text to draw + * @param {number} x - Horizontal position to draw the text + * @param {number} y - Vertical position to draw the text + * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + * @private + */ + + + Text.prototype.drawLetterSpacing = function drawLetterSpacing(text, x, y) { + var isStroke = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3]; + + var style = this._style; + + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + + if (letterSpacing === 0) { + if (isStroke) { + this.context.strokeText(text, x, y); + } else { + this.context.fillText(text, x, y); + } + + return; + } + + var characters = String.prototype.split.call(text, ''); + var currentPosition = x; + var index = 0; + var current = ''; + + while (index < text.length) { + current = characters[index++]; + if (isStroke) { + this.context.strokeText(current, currentPosition, y); + } else { + this.context.fillText(current, currentPosition, y); + } + currentPosition += this.context.measureText(current).width + letterSpacing; + } + }; + + /** + * Updates texture size based on canvas size + * + * @private + */ + + + Text.prototype.updateTexture = function updateTexture() { + var texture = this._texture; + var style = this._style; + + texture.baseTexture.hasLoaded = true; + texture.baseTexture.resolution = this.resolution; + + texture.baseTexture.realWidth = this.canvas.width; + texture.baseTexture.realHeight = this.canvas.height; + texture.baseTexture.width = this.canvas.width / this.resolution; + texture.baseTexture.height = this.canvas.height / this.resolution; + texture.trim.width = texture._frame.width = this.canvas.width / this.resolution; + texture.trim.height = texture._frame.height = this.canvas.height / this.resolution; + + texture.trim.x = -style.padding; + texture.trim.y = -style.padding; + + texture.orig.width = texture._frame.width - style.padding * 2; + texture.orig.height = texture._frame.height - style.padding * 2; + + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + + texture.baseTexture.emit('update', texture.baseTexture); + + this.dirty = false; + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Text.prototype.renderWebGL = function renderWebGL(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype.renderWebGL.call(this, renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Text.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype._renderCanvas.call(this, renderer); + }; + + /** + * Calculates the ascent, descent and fontSize of a given fontStyle + * + * @private + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ + + + Text.prototype.determineFontProperties = function determineFontProperties(fontStyle) { + var properties = Text.fontPropertiesCache[fontStyle]; + + if (!properties) { + properties = {}; + + var canvas = Text.fontPropertiesCanvas; + var context = Text.fontPropertiesContext; + + context.font = fontStyle; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('M').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = fontStyle; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i = 0; + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } else { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var _j = 0; _j < line; _j += 4) { + if (imagedata[idx + _j] !== 255) { + stop = true; + break; + } + } + + if (!stop) { + idx -= line; + } else { + break; + } + } + + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + + Text.fontPropertiesCache[fontStyle] = properties; + } + + return properties; + }; + + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @private + * @param {string} text - String to apply word wrapping to + * @return {string} New string with new lines applied where required + */ + + + Text.prototype.wordWrap = function wordWrap(text) { + // Greedy wrapping algorithm that will wrap words as the line grows longer + // than its horizontal bounds. + var result = ''; + var lines = text.split('\n'); + var wordWrapWidth = this._style.wordWrapWidth; + + for (var i = 0; i < lines.length; i++) { + var spaceLeft = wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) { + var wordWidth = this.context.measureText(words[j]).width; + + if (this._style.breakWords && wordWidth > wordWrapWidth) { + // Word should be split in the middle + var characters = words[j].split(''); + + for (var c = 0; c < characters.length; c++) { + var characterWidth = this.context.measureText(characters[c]).width; + + if (characterWidth > spaceLeft) { + result += '\n' + characters[c]; + spaceLeft = wordWrapWidth - characterWidth; + } else { + if (c === 0) { + result += ' '; + } + + result += characters[c]; + spaceLeft -= characterWidth; + } + } + } else { + var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; + + if (j === 0 || wordWidthWithSpace > spaceLeft) { + // Skip printing the newline if it's the first word of the line that is + // greater than the word wrap width. + if (j > 0) { + result += '\n'; + } + result += words[j]; + spaceLeft = wordWrapWidth - wordWidth; + } else { + spaceLeft -= wordWidthWithSpace; + result += ' ' + words[j]; + } + } + } + + if (i < lines.length - 1) { + result += '\n'; + } + } + + return result; + }; + + /** + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + */ + + + Text.prototype._calculateBounds = function _calculateBounds() { + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; + + /** + * Method to be called upon a TextStyle change. + * @private + */ + + + Text.prototype._onStyleChange = function _onStyleChange() { + this.dirty = true; + }; + + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * + * @private + * @param {object} style - The style. + * @param {string} lines - The lines of text. + * @return {string|number|CanvasGradient} The fill style + */ + + + Text.prototype._generateFillStyle = function _generateFillStyle(style, lines) { + if (!Array.isArray(style.fill)) { + return style.fill; + } + + // cocoon on canvas+ cannot generate textures, so use the first colour instead + if (navigator.isCocoonJS) { + return style.fill[0]; + } + + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient = void 0; + var totalIterations = void 0; + var currentIteration = void 0; + var stop = void 0; + + var width = this.canvas.width / this.resolution; + var height = this.canvas.height / this.resolution; + + if (style.fillGradientType === _const.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); + + // we need to repeat the gradient so that each invididual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + totalIterations = (style.fill.length + 1) * lines.length; + currentIteration = 0; + for (var i = 0; i < lines.length; i++) { + currentIteration += 1; + for (var j = 0; j < style.fill.length; j++) { + stop = currentIteration / totalIterations; + gradient.addColorStop(stop, style.fill[j]); + currentIteration++; + } + } + } else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); + + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + totalIterations = style.fill.length + 1; + currentIteration = 1; + + for (var _i3 = 0; _i3 < style.fill.length; _i3++) { + stop = currentIteration / totalIterations; + gradient.addColorStop(stop, style.fill[_i3]); + currentIteration++; + } + } + + return gradient; + }; + + /** + * Destroys this text object. + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majorety of the time the texture will not be shared with any other Sprites. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well + */ + + + Text.prototype.destroy = function destroy(options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + + options = Object.assign({}, defaultDestroyOptions, options); + + _Sprite.prototype.destroy.call(this, options); + + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + + this._style = null; + }; + + /** + * The width of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Text# + */ + + + _createClass(Text, [{ + key: 'width', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.x) * this.texture.orig.width; + } + + /** + * Sets the width of the text. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this.texture.orig.width; + this._width = value; + } + + /** + * The height of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Text# + */ + + }, { + key: 'height', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.y) * this._texture.orig.height; + } + + /** + * Sets the height of the text. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this.texture.orig.height; + this._height = value; + } + + /** + * Set the style of the text. Set up an event listener to listen for changes on the style + * object and mark the text as dirty. + * + * @member {object|PIXI.TextStyle} + * @memberof PIXI.Text# + */ + + }, { + key: 'style', + get: function get() { + return this._style; + } + + /** + * Sets the style of the text. + * + * @param {object} style - The value to set to. + */ + , + set: function set(style) { + style = style || {}; + + if (style instanceof _TextStyle2.default) { + this._style = style; + } else { + this._style = new _TextStyle2.default(style); + } + + this.localStyleID = -1; + this.dirty = true; + } + + /** + * Set the copy for the text object. To split a line you can use '\n'. + * + * @member {string} + * @memberof PIXI.Text# + */ + + }, { + key: 'text', + get: function get() { + return this._text; + } + + /** + * Sets the text. + * + * @param {string} text - The value to set to. + */ + , + set: function set(text) { + text = text || ' '; + text = text.toString(); + + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + } + }]); + + return Text; +}(_Sprite3.default); + +exports.default = Text; + + +Text.fontPropertiesCache = {}; +Text.fontPropertiesCanvas = document.createElement('canvas'); +Text.fontPropertiesContext = Text.fontPropertiesCanvas.getContext('2d'); + +},{"../const":78,"../math":102,"../sprites/Sprite":133,"../textures/Texture":144,"../utils":152,"./TextStyle":140}],140:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // disabling eslint for now, going to rewrite this in v5 +/* eslint-disable */ + +var _const = require('../const'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: '#000000', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: _const.TEXT_GRADIENT.LINEAR_VERTICAL, + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + wordWrap: false, + wordWrapWidth: 100 +}; + +/** + * A TextStyle Object decorates a Text Object. It can be shared between + * multiple Text objects. Changing the style will update all text objects using it. + * + * @class + * @memberof PIXI + */ + +var TextStyle = function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string} [style.dropShadowColor='#000000'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fills styles are + * supplied, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} for possible values + * @param {string} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', 800' or '900') + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Default is 'miter' (creates a sharp corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + _classCallCheck(this, TextStyle); + + this.styleID = 0; + + Object.assign(this, defaultStyle, style); + } + + /** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return {PIXI.TextStyle} New cloned TextStyle object + */ + + + TextStyle.prototype.clone = function clone() { + var clonedProperties = {}; + + for (var key in this._defaults) { + clonedProperties[key] = this[key]; + } + + return new TextStyle(clonedProperties); + }; + + /** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ + + + TextStyle.prototype.reset = function reset() { + Object.assign(this, this._defaults); + }; + + _createClass(TextStyle, [{ + key: 'align', + get: function get() { + return this._align; + }, + set: function set(align) { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + } + }, { + key: 'breakWords', + get: function get() { + return this._breakWords; + }, + set: function set(breakWords) { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + } + }, { + key: 'dropShadow', + get: function get() { + return this._dropShadow; + }, + set: function set(dropShadow) { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + } + }, { + key: 'dropShadowAngle', + get: function get() { + return this._dropShadowAngle; + }, + set: function set(dropShadowAngle) { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + } + }, { + key: 'dropShadowBlur', + get: function get() { + return this._dropShadowBlur; + }, + set: function set(dropShadowBlur) { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + } + }, { + key: 'dropShadowColor', + get: function get() { + return this._dropShadowColor; + }, + set: function set(dropShadowColor) { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + } + }, { + key: 'dropShadowDistance', + get: function get() { + return this._dropShadowDistance; + }, + set: function set(dropShadowDistance) { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + } + }, { + key: 'fill', + get: function get() { + return this._fill; + }, + set: function set(fill) { + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + } + }, { + key: 'fillGradientType', + get: function get() { + return this._fillGradientType; + }, + set: function set(fillGradientType) { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + } + }, { + key: 'fontFamily', + get: function get() { + return this._fontFamily; + }, + set: function set(fontFamily) { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + } + }, { + key: 'fontSize', + get: function get() { + return this._fontSize; + }, + set: function set(fontSize) { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + } + }, { + key: 'fontStyle', + get: function get() { + return this._fontStyle; + }, + set: function set(fontStyle) { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + } + }, { + key: 'fontVariant', + get: function get() { + return this._fontVariant; + }, + set: function set(fontVariant) { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + } + }, { + key: 'fontWeight', + get: function get() { + return this._fontWeight; + }, + set: function set(fontWeight) { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + } + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(letterSpacing) { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + } + }, { + key: 'lineHeight', + get: function get() { + return this._lineHeight; + }, + set: function set(lineHeight) { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + } + }, { + key: 'lineJoin', + get: function get() { + return this._lineJoin; + }, + set: function set(lineJoin) { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + } + }, { + key: 'miterLimit', + get: function get() { + return this._miterLimit; + }, + set: function set(miterLimit) { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + } + }, { + key: 'padding', + get: function get() { + return this._padding; + }, + set: function set(padding) { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + } + }, { + key: 'stroke', + get: function get() { + return this._stroke; + }, + set: function set(stroke) { + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + } + }, { + key: 'strokeThickness', + get: function get() { + return this._strokeThickness; + }, + set: function set(strokeThickness) { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + } + }, { + key: 'textBaseline', + get: function get() { + return this._textBaseline; + }, + set: function set(textBaseline) { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + } + }, { + key: 'wordWrap', + get: function get() { + return this._wordWrap; + }, + set: function set(wordWrap) { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + } + }, { + key: 'wordWrapWidth', + get: function get() { + return this._wordWrapWidth; + }, + set: function set(wordWrapWidth) { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + } + }]); + + return TextStyle; +}(); + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * + * @param {number|number[]} color + * @return {string} The color as a string. + */ + + +exports.default = TextStyle; +function getColor(color) { + if (typeof color === 'number') { + return (0, _utils.hex2string)(color); + } else if (Array.isArray(color)) { + for (var i = 0; i < color.length; ++i) { + if (typeof color[i] === 'number') { + color[i] = (0, _utils.hex2string)(color[i]); + } + } + } + + return color; +} + +},{"../const":78,"../utils":152}],141:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _const = require('../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let baseRenderTexture = new PIXI.BaseRenderTexture(renderer, 800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * baseRenderTexture.render(sprite); + * ``` + * + * The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual + * position a Container should be used: + * + * ```js + * let doc = new PIXI.Container(); + * + * doc.addChild(sprite); + * + * let baseRenderTexture = new PIXI.BaseRenderTexture(100, 100); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(doc, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var BaseRenderTexture = function (_BaseTexture) { + _inherits(BaseRenderTexture, _BaseTexture); + + /** + * @param {number} [width=100] - The width of the base render texture + * @param {number} [height=100] - The height of the base render texture + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + */ + function BaseRenderTexture() { + var width = arguments.length <= 0 || arguments[0] === undefined ? 100 : arguments[0]; + var height = arguments.length <= 1 || arguments[1] === undefined ? 100 : arguments[1]; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + + _classCallCheck(this, BaseRenderTexture); + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, null, scaleMode)); + + _this.resolution = resolution || _const.RESOLUTION; + + _this.width = width; + _this.height = height; + + _this.realWidth = _this.width * _this.resolution; + _this.realHeight = _this.height * _this.resolution; + + _this.scaleMode = scaleMode || _const.SCALE_MODES.DEFAULT; + _this.hasLoaded = true; + + /** + * A map of renderer IDs to webgl renderTargets + * + * @member {object} + * @private + */ + _this._glRenderTargets = []; + + /** + * A reference to the canvas render target (we only need one as this can be shared accross renderers) + * + * @member {object} + * @private + */ + _this._canvasRenderTarget = null; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + return _this; + } + + /** + * Resizes the BaseRenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + */ + + + BaseRenderTexture.prototype.resize = function resize(width, height) { + if (width === this.width && height === this.height) { + return; + } + + this.valid = width > 0 && height > 0; + + this.width = width; + this.height = height; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + if (!this.valid) { + return; + } + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + */ + + + BaseRenderTexture.prototype.destroy = function destroy() { + _BaseTexture.prototype.destroy.call(this, true); + this.renderer = null; + }; + + return BaseRenderTexture; +}(_BaseTexture3.default); + +exports.default = BaseRenderTexture; + +},{"../const":78,"./BaseTexture":142}],142:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var BaseTexture = function (_EventEmitter) { + _inherits(BaseTexture, _EventEmitter); + + /** + * @param {HTMLImageElement|HTMLCanvasElement} [source] - the source object of the texture. + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture + */ + function BaseTexture(source, scaleMode, resolution) { + _classCallCheck(this, BaseTexture); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.uid = (0, _utils.uid)(); + + _this.touched = 0; + + /** + * The resolution / device pixel ratio of the texture + * + * @member {number} + * @default 1 + */ + _this.resolution = resolution || _const.RESOLUTION; + + /** + * The width of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.width = 100; + + /** + * The height of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.height = 100; + + // TODO docs + // used to store the actual dimensions of the source + /** + * Used to store the actual width of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realWidth = 100; + /** + * Used to store the actual height of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realHeight = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @member {number} + * @default PIXI.SCALE_MODES.DEFAULT + * @see PIXI.SCALE_MODES + */ + _this.scaleMode = scaleMode || _const.SCALE_MODES.DEFAULT; + + /** + * Set to true once the base texture has successfully loaded. + * + * This is never true if the underlying source fails to load or has no texture data. + * + * @readonly + * @member {boolean} + */ + _this.hasLoaded = false; + + /** + * Set to true if the source is currently loading. + * + * If an Image source is loading the 'loaded' or 'error' event will be + * dispatched when the operation ends. An underyling source that is + * immediately-available bypasses loading entirely. + * + * @readonly + * @member {boolean} + */ + _this.isLoading = false; + + /** + * The image source that is used to create the texture. + * + * TODO: Make this a setter that calls loadSource(); + * + * @readonly + * @member {HTMLImageElement|HTMLCanvasElement} + */ + _this.source = null; // set in loadSource, if at all + + /** + * The image source that is used to create the texture. This is used to + * store the original Svg source when it is replaced with a canvas element. + * + * TODO: Currently not in use but could be used when re-scaling svg. + * + * @readonly + * @member {Image} + */ + _this.origSource = null; // set in loadSvg, if at all + + /** + * Type of image defined in source, eg. `png` or `svg` + * + * @readonly + * @member {string} + */ + _this.imageType = null; // set in updateImageType + + /** + * Scale for source image. Used with Svg images to scale them before rasterization. + * + * @readonly + * @member {number} + */ + _this.sourceScale = 1.0; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * All blend modes, and shaders written for default value. Change it on your own risk. + * + * @member {boolean} + * @default true + */ + _this.premultipliedAlpha = true; + + /** + * The image url of the texture + * + * @member {string} + */ + _this.imageUrl = null; + + /** + * Wether or not the texture is a power of two, try to use power of two textures as much + * as you can + * + * @private + * @member {boolean} + */ + _this.isPowerOfTwo = false; + + // used for webGL + + /** + * + * Set this to true if a mipmap of this texture needs to be generated. This value needs + * to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @member {boolean} + * @see PIXI.MIPMAP_TEXTURES + */ + _this.mipmap = _const.MIPMAP_TEXTURES; + + /** + * + * WebGL Texture wrap mode + * + * @member {number} + * @see PIXI.WRAP_MODES + */ + _this.wrapMode = _const.WRAP_MODES.DEFAULT; + + /** + * A map of renderer IDs to webgl textures + * + * @private + * @member {object} + */ + _this._glTextures = []; + _this._enabled = 0; + _this._id = 0; + + // if no source passed don't try to load + if (source) { + _this.loadSource(source); + } + + /** + * Fired when a not-immediately-available source finishes loading. + * + * @protected + * @event loaded + * @memberof PIXI.BaseTexture# + */ + + /** + * Fired when a not-immediately-available source fails to load. + * + * @protected + * @event error + * @memberof PIXI.BaseTexture# + */ + return _this; + } + + /** + * Updates the texture on all the webgl renderers, this also assumes the src has changed. + * + * @fires update + */ + + + BaseTexture.prototype.update = function update() { + // Svg size is handled during load + if (this.imageType !== 'svg') { + this.realWidth = this.source.naturalWidth || this.source.videoWidth || this.source.width; + this.realHeight = this.source.naturalHeight || this.source.videoHeight || this.source.height; + + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + this.isPowerOfTwo = _bitTwiddle2.default.isPow2(this.realWidth) && _bitTwiddle2.default.isPow2(this.realHeight); + } + + this.emit('update', this); + }; + + /** + * Load a source. + * + * If the source is not-immediately-available, such as an image that needs to be + * downloaded, then the 'loaded' or 'error' event will be dispatched in the future + * and `hasLoaded` will remain false after this call. + * + * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: + * + * if (texture.hasLoaded) { + * // texture ready for use + * } else if (texture.isLoading) { + * // listen to 'loaded' and/or 'error' events on texture + * } else { + * // not loading, not going to load UNLESS the source is reloaded + * // (it may still make sense to listen to the events) + * } + * + * @protected + * @param {HTMLImageElement|HTMLCanvasElement} source - the source object of the texture. + */ + + + BaseTexture.prototype.loadSource = function loadSource(source) { + var _this2 = this; + + var wasLoading = this.isLoading; + + this.hasLoaded = false; + this.isLoading = false; + + if (wasLoading && this.source) { + this.source.onload = null; + this.source.onerror = null; + } + + var firstSourceLoaded = !this.source; + + this.source = source; + + // Apply source if loaded. Otherwise setup appropriate loading monitors. + if ((source.src && source.complete || source.getContext) && source.width && source.height) { + this._updateImageType(); + + if (this.imageType === 'svg') { + this._loadSvgSource(); + } else { + this._sourceLoaded(); + } + + if (firstSourceLoaded) { + // send loaded event if previous source was null and we have been passed a pre-loaded IMG element + this.emit('loaded', this); + } + } else if (!source.getContext) { + var _ret = function () { + // Image fail / not ready + _this2.isLoading = true; + + var scope = _this2; + + source.onload = function () { + scope._updateImageType(); + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope._sourceLoaded(); + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + scope.emit('loaded', scope); + }; + + source.onerror = function () { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope.emit('error', scope); + }; + + // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element + // "The value of `complete` can thus change while a script is executing." + // So complete needs to be re-checked after the callbacks have been added.. + // NOTE: complete will be true if the image has no src so best to check if the src is set. + if (source.complete && source.src) { + // ..and if we're complete now, no need for callbacks + source.onload = null; + source.onerror = null; + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return { + v: void 0 + }; + } + + _this2.isLoading = false; + + if (source.width && source.height) { + _this2._sourceLoaded(); + + // If any previous subscribers possible + if (wasLoading) { + _this2.emit('loaded', _this2); + } + } + // If any previous subscribers possible + else if (wasLoading) { + _this2.emit('error', _this2); + } + } + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + }; + + /** + * Updates type of the source image. + */ + + + BaseTexture.prototype._updateImageType = function _updateImageType() { + if (!this.imageUrl) { + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + var imageType = void 0; + + if (dataUri && dataUri.mediaType === 'image') { + // Check for subType validity + var firstSubType = dataUri.subType.split('+')[0]; + + imageType = (0, _utils.getImageTypeOfUrl)('.' + firstSubType); + + if (!imageType) { + throw new Error('Invalid image type in data URI.'); + } + } else { + imageType = (0, _utils.getImageTypeOfUrl)(this.imageUrl); + + if (!imageType) { + throw new Error('Invalid image type in URL.'); + } + } + + this.imageType = imageType; + }; + + /** + * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls + * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. + */ + + + BaseTexture.prototype._loadSvgSource = function _loadSvgSource() { + if (this.imageType !== 'svg') { + // Do nothing if source is not svg + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + + if (dataUri) { + this._loadSvgSourceUsingDataUri(dataUri); + } else { + // We got an URL, so we need to do an XHR to check the svg size + this._loadSvgSourceUsingXhr(); + } + }; + + /** + * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`. + * + * @param {string} dataUri - The data uri to load from. + */ + + + BaseTexture.prototype._loadSvgSourceUsingDataUri = function _loadSvgSourceUsingDataUri(dataUri) { + var svgString = void 0; + + if (dataUri.encoding === 'base64') { + if (!atob) { + throw new Error('Your browser doesn\'t support base64 conversions.'); + } + svgString = atob(dataUri.data); + } else { + svgString = dataUri.data; + } + + this._loadSvgSourceUsingString(svgString); + }; + + /** + * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. + */ + + + BaseTexture.prototype._loadSvgSourceUsingXhr = function _loadSvgSourceUsingXhr() { + var _this3 = this; + + var svgXhr = new XMLHttpRequest(); + + // This throws error on IE, so SVG Document can't be used + // svgXhr.responseType = 'document'; + + // This is not needed since we load the svg as string (breaks IE too) + // but overrideMimeType() can be used to force the response to be parsed as XML + // svgXhr.overrideMimeType('image/svg+xml'); + + svgXhr.onload = function () { + if (svgXhr.readyState !== svgXhr.DONE || svgXhr.status !== 200) { + throw new Error('Failed to load SVG using XHR.'); + } + + _this3._loadSvgSourceUsingString(svgXhr.response); + }; + + svgXhr.onerror = function () { + return _this3.emit('error', _this3); + }; + + svgXhr.open('GET', this.imageUrl, true); + svgXhr.send(); + }; + + /** + * Loads texture using an SVG string. The original SVG Image is stored as `origSource` and the + * created canvas is the new `source`. The SVG is scaled using `sourceScale`. Called by + * `_loadSvgSourceUsingXhr` or `_loadSvgSourceUsingDataUri`. + * + * @param {string} svgString SVG source as string + * + * @fires loaded + */ + + + BaseTexture.prototype._loadSvgSourceUsingString = function _loadSvgSourceUsingString(svgString) { + var svgSize = (0, _utils.getSvgSize)(svgString); + + var svgWidth = svgSize.width; + var svgHeight = svgSize.height; + + if (!svgWidth || !svgHeight) { + throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); + } + + // Scale realWidth and realHeight + this.realWidth = Math.round(svgWidth * this.sourceScale); + this.realHeight = Math.round(svgHeight * this.sourceScale); + + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + // Check pow2 after scale + this.isPowerOfTwo = _bitTwiddle2.default.isPow2(this.realWidth) && _bitTwiddle2.default.isPow2(this.realHeight); + + // Create a canvas element + var canvas = document.createElement('canvas'); + + canvas.width = this.realWidth; + canvas.height = this.realHeight; + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + + // Draw the Svg to the canvas + canvas.getContext('2d').drawImage(this.source, 0, 0, svgWidth, svgHeight, 0, 0, this.realWidth, this.realHeight); + + // Replace the original source image with the canvas + this.origSource = this.source; + this.source = canvas; + + // Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`) + _utils.BaseTextureCache[canvas._pixiId] = this; + + this.isLoading = false; + this._sourceLoaded(); + this.emit('loaded', this); + }; + + /** + * Used internally to update the width, height, and some other tracking vars once + * a source has successfully loaded. + * + * @private + */ + + + BaseTexture.prototype._sourceLoaded = function _sourceLoaded() { + this.hasLoaded = true; + this.update(); + }; + + /** + * Destroys this base texture + * + */ + + + BaseTexture.prototype.destroy = function destroy() { + if (this.imageUrl) { + delete _utils.BaseTextureCache[this.imageUrl]; + delete _utils.TextureCache[this.imageUrl]; + + this.imageUrl = null; + + if (!navigator.isCocoonJS) { + this.source.src = ''; + } + } + // An svg source has both `imageUrl` and `__pixiId`, so no `else if` here + if (this.source && this.source._pixiId) { + delete _utils.BaseTextureCache[this.source._pixiId]; + } + + this.source = null; + + this.dispose(); + }; + + /** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + */ + + + BaseTexture.prototype.dispose = function dispose() { + this.emit('dispose', this); + + // this should no longer be needed, the renderers should cleanup all the gl textures. + // this._glTextures = {}; + }; + + /** + * Changes the source image of the texture. + * The original source must be an Image element. + * + * @param {string} newSrc - the path of the image + */ + + + BaseTexture.prototype.updateSourceImage = function updateSourceImage(newSrc) { + this.source.src = newSrc; + + this.loadSource(this.source); + }; + + /** + * Helper function that creates a base texture from the given image url. + * If the image is not in the base texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + // new Image() breaks tex loading in some versions of Chrome. + // See https://code.google.com/p/chromium/issues/detail?id=238071 + var image = new Image(); // document.createElement('img'); + + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + image.crossOrigin = (0, _determineCrossOrigin2.default)(imageUrl); + } + + baseTexture = new BaseTexture(image, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + image.src = imageUrl; // Setting this triggers load + + _utils.BaseTextureCache[imageUrl] = baseTexture; + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode) { + if (!canvas._pixiId) { + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[canvas._pixiId]; + + if (!baseTexture) { + baseTexture = new BaseTexture(canvas, scaleMode); + _utils.BaseTextureCache[canvas._pixiId] = baseTexture; + } + + return baseTexture; + }; + + return BaseTexture; +}(_eventemitter2.default); + +exports.default = BaseTexture; + +},{"../const":78,"../utils":152,"../utils/determineCrossOrigin":151,"bit-twiddle":14,"eventemitter3":16}],143:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseRenderTexture = require('./BaseRenderTexture'); + +var _BaseRenderTexture2 = _interopRequireDefault(_BaseRenderTexture); + +var _Texture2 = require('./Texture'); + +var _Texture3 = _interopRequireDefault(_Texture2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A RenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let renderTexture = PIXI.RenderTexture.create(800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual + * position a Container should be used: + * + * ```js + * let doc = new PIXI.Container(); + * + * doc.addChild(sprite); + * + * renderer.render(doc, renderTexture); // Renders to center of renderTexture + * ``` + * + * @class + * @extends PIXI.Texture + * @memberof PIXI + */ +var RenderTexture = function (_Texture) { + _inherits(RenderTexture, _Texture); + + /** + * @param {PIXI.BaseRenderTexture} baseRenderTexture - The renderer used for this RenderTexture + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + */ + function RenderTexture(baseRenderTexture, frame) { + _classCallCheck(this, RenderTexture); + + // suport for legacy.. + var _legacyRenderer = null; + + if (!(baseRenderTexture instanceof _BaseRenderTexture2.default)) { + /* eslint-disable prefer-rest-params, no-console */ + var width = arguments[1]; + var height = arguments[2]; + var scaleMode = arguments[3] || 0; + var resolution = arguments[4] || 1; + + // we have an old render texture.. + console.warn('Please use RenderTexture.create(' + width + ', ' + height + ') instead of the ctor directly.'); + _legacyRenderer = arguments[0]; + /* eslint-enable prefer-rest-params, no-console */ + + frame = null; + baseRenderTexture = new _BaseRenderTexture2.default(width, height, scaleMode, resolution); + } + + /** + * The base texture object that this texture uses + * + * @member {BaseTexture} + */ + + var _this = _possibleConstructorReturn(this, _Texture.call(this, baseRenderTexture, frame)); + + _this.legacyRenderer = _legacyRenderer; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = true; + + _this._updateUvs(); + return _this; + } + + /** + * Resizes the RenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + * @param {boolean} doNotResizeBaseTexture - Should the baseTexture.width and height values be resized as well? + */ + + + RenderTexture.prototype.resize = function resize(width, height, doNotResizeBaseTexture) { + // TODO - could be not required.. + this.valid = width > 0 && height > 0; + + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + + if (!doNotResizeBaseTexture) { + this.baseTexture.resize(width, height); + } + + this._updateUvs(); + }; + + /** + * A short hand way of creating a render texture. + * + * @param {number} [width=100] - The width of the render texture + * @param {number} [height=100] - The height of the render texture + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.RenderTexture} The new render texture + */ + + + RenderTexture.create = function create(width, height, scaleMode, resolution) { + return new RenderTexture(new _BaseRenderTexture2.default(width, height, scaleMode, resolution)); + }; + + return RenderTexture; +}(_Texture3.default); + +exports.default = RenderTexture; + +},{"./BaseRenderTexture":141,"./Texture":144}],144:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture = require('./BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _VideoBaseTexture = require('./VideoBaseTexture'); + +var _VideoBaseTexture2 = _interopRequireDefault(_VideoBaseTexture); + +var _TextureUvs = require('./TextureUvs'); + +var _TextureUvs2 = _interopRequireDefault(_TextureUvs); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _math = require('../math'); + +var _utils = require('../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided + * then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * let texture = PIXI.Texture.fromImage('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var Texture = function (_EventEmitter) { + _inherits(Texture, _EventEmitter); + + /** + * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + * @param {PIXI.Rectangle} [orig] - The area of original texture + * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture + * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8} + */ + function Texture(baseTexture, frame, orig, trim, rotate) { + _classCallCheck(this, Texture); + + /** + * Does this Texture have any frame data assigned to it? + * + * @member {boolean} + */ + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.noFrame = false; + + if (!frame) { + _this.noFrame = true; + frame = new _math.Rectangle(0, 0, 1, 1); + } + + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @member {PIXI.BaseTexture} + */ + _this.baseTexture = baseTexture; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @member {PIXI.Rectangle} + */ + _this._frame = frame; + + /** + * This is the trimmed area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @member {boolean} + */ + _this.requiresUpdate = false; + + /** + * The WebGL UV data cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + _this._uvs = null; + + /** + * This is the area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + + _this._rotate = Number(rotate || 0); + + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); + } + + if (baseTexture.hasLoaded) { + if (_this.noFrame) { + frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + + // if there is no frame we should monitor for any base texture changes.. + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + _this.frame = frame; + } else { + baseTexture.once('loaded', _this.onBaseTextureLoaded, _this); + } + + /** + * Fired when the texture is updated. This happens if the frame or the baseTexture is updated. + * + * @event update + * @memberof PIXI.Texture# + * @protected + */ + + _this._updateID = 0; + + /** + * Experimental! + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to 1.5 if you tex ture has repeated right and bottom lines, that leads to smoother borders + * IN REAL PIXELS + * @default 0 + * @member {number} + */ + _this.clampOffset = 0; + + /** + * Experimental! + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to 0 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * IN REAL PIXELS + * @default 0.5 + * @member {number} + */ + _this.clampMargin = 0.5; + return _this; + } + + /** + * Updates this texture on the gpu. + * + */ + + + Texture.prototype.update = function update() { + this.baseTexture.update(); + }; + + /** + * Called when the base texture is loaded + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureLoaded = function onBaseTextureLoaded(baseTexture) { + this._updateID++; + + // TODO this code looks confusing.. boo to abusing getters and setterss! + if (this.noFrame) { + this.frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } else { + this.frame = this._frame; + } + + this.baseTexture.on('update', this.onBaseTextureUpdated, this); + this.emit('update', this); + }; + + /** + * Called when the base texture is updated + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated(baseTexture) { + this._updateID++; + + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Texture.prototype.destroy = function destroy(destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destoryed too.. + if (_utils.TextureCache[this.baseTexture.imageUrl]) { + delete _utils.TextureCache[this.baseTexture.imageUrl]; + } + + this.baseTexture.destroy(); + } + + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); + + this.baseTexture = null; + } + + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + + this.valid = false; + + this.off('dispose', this.dispose, this); + this.off('update', this.update, this); + }; + + /** + * Creates a new texture object that acts the same as this one. + * + * @return {PIXI.Texture} The new texture + */ + + + Texture.prototype.clone = function clone() { + return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); + }; + + /** + * Updates the internal WebGL UV cache. + * + * @protected + */ + + + Texture.prototype._updateUvs = function _updateUvs() { + if (!this._uvs) { + this._uvs = new _TextureUvs2.default(); + } + + this._uvs.set(this._frame, this.baseTexture, this.rotate); + + this._updateID++; + }; + + /** + * returns uvs + * @member PIXI.TextureUvs# + * @memberof PIXI.Texture# + */ + + + /** + * Updates uvs accordingly to the texture + */ + Texture.prototype.updateUvs = function updateUvs() { + this._updateUvs(); + }; + + /** + * Helper function that creates a Texture object from the given image url. + * If the image is not in the texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var texture = _utils.TextureCache[imageUrl]; + + if (!texture) { + texture = new Texture(_BaseTexture2.default.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); + _utils.TextureCache[imageUrl] = texture; + } + + return texture; + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return texture; + }; + + /** + * Helper function that creates a new Texture based on the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromCanvas = function fromCanvas(canvas, scaleMode) { + return new Texture(_BaseTexture2.default.fromCanvas(canvas, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the given video element. + * + * @static + * @param {HTMLVideoElement|string} video - The URL or actual element of the video + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideo = function fromVideo(video, scaleMode) { + if (typeof video === 'string') { + return Texture.fromVideoUrl(video, scaleMode); + } + + return new Texture(_VideoBaseTexture2.default.fromVideo(video, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the video url. + * + * @static + * @param {string} videoUrl - URL of the video + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideoUrl = function fromVideoUrl(videoUrl, scaleMode) { + return new Texture(_VideoBaseTexture2.default.fromUrl(videoUrl, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the source you provide. + * The soucre can be - frame id, image url, video url, canvae element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.from = function from(source) { + // TODO auto detect cross origin.. + // TODO pass in scale mode? + if (typeof source === 'string') { + var texture = _utils.TextureCache[source]; + + if (!texture) { + // check if its a video.. + var isVideo = source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/) !== null; + + if (isVideo) { + return Texture.fromVideoUrl(source); + } + + return Texture.fromImage(source); + } + + return texture; + } else if (source instanceof HTMLCanvasElement) { + return Texture.fromCanvas(source); + } else if (source instanceof HTMLVideoElement) { + return Texture.fromVideo(source); + } else if (source instanceof _BaseTexture2.default) { + return new Texture(_BaseTexture2.default); + } + + // lets assume its a texture! + return source; + }; + + /** + * Adds a texture to the global TextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the texture will be stored against. + */ + + + Texture.addTextureToCache = function addTextureToCache(texture, id) { + _utils.TextureCache[id] = texture; + }; + + /** + * Remove a texture from the global TextureCache. + * + * @static + * @param {string} id - The id of the texture to be removed + * @return {PIXI.Texture} The texture that was removed + */ + + + Texture.removeTextureFromCache = function removeTextureFromCache(id) { + var texture = _utils.TextureCache[id]; + + delete _utils.TextureCache[id]; + delete _utils.BaseTextureCache[id]; + + return texture; + }; + + /** + * The frame specifies the region of the base texture that this texture uses. + * + * @member {PIXI.Rectangle} + * @memberof PIXI.Texture# + */ + + + _createClass(Texture, [{ + key: 'uvs', + get: function get() { + return this._uvs; + } + }, { + key: 'frame', + get: function get() { + return this._frame; + } + + /** + * Set the frame. + * + * @param {Rectangle} frame - The new frame to set. + */ + , + set: function set(frame) { + this._frame = frame; + + this.noFrame = false; + + if (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height) { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); + } + + // this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + this.valid = frame && frame.width && frame.height && this.baseTexture.hasLoaded; + + if (!this.trim && !this.rotate) { + this.orig = frame; + } + + if (this.valid) { + this._updateUvs(); + } + } + + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.GroupD8} for explanation + * + * @member {number} + */ + + }, { + key: 'rotate', + get: function get() { + return this._rotate; + } + + /** + * Set the rotation + * + * @param {number} rotate - The new rotation to set. + */ + , + set: function set(rotate) { + this._rotate = rotate; + if (this.valid) { + this._updateUvs(); + } + } + + /** + * The width of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'width', + get: function get() { + return this.orig ? this.orig.width : 0; + } + + /** + * The height of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.orig ? this.orig.height : 0; + } + }]); + + return Texture; +}(_eventemitter2.default); + +/** + * An empty texture, used often to not have to create multiple empty textures. + * Can not be destroyed. + * + * @static + * @constant + */ + + +exports.default = Texture; +Texture.EMPTY = new Texture(new _BaseTexture2.default()); +Texture.EMPTY.destroy = function _emptyDestroy() {/* empty */}; +Texture.EMPTY.on = function _emptyOn() {/* empty */}; +Texture.EMPTY.once = function _emptyOnce() {/* empty */}; +Texture.EMPTY.emit = function _emptyEmit() {/* empty */}; + +},{"../math":102,"../utils":152,"./BaseTexture":142,"./TextureUvs":146,"./VideoBaseTexture":147,"eventemitter3":16}],145:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Matrix = require('../math/Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var tempMat = new _Matrix2.default(); + +/** + * class controls uv transform and frame clamp for texture + */ + +var TextureTransform = function () { + /** + * + * @param {PIXI.Texture} texture observed texture + * @constructor + */ + function TextureTransform(texture) { + _classCallCheck(this, TextureTransform); + + this._texture = texture; + + this.mapCoord = new _Matrix2.default(); + + this.clampFrame = new Float32Array(4); + + this.clampOffset = new Float32Array(2); + + this._lastTextureID = -1; + + this.update(); + } + + /** + * texture property + * @member {PIXI.Texture} + * @memberof PIXI.TextureTransform + */ + + + /** + * updates matrices if texture was changed + * @param {boolean} forceUpdate if true, matrices will be updated any case + */ + TextureTransform.prototype.update = function update(forceUpdate) { + var tex = this.texture; + + if (!tex || !tex.valid) { + return; + } + + if (!forceUpdate && this._lastTextureID === this.texture._updateID) { + return; + } + + this._lastTextureID = this.texture._updateID; + + var uvs = this.texture._uvs; + + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + + var orig = tex.orig; + var trim = tex.trim; + + if (trim) { + tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat); + } + + var texBase = tex.baseTexture; + var frame = this.clampFrame; + var margin = tex.clampMargin / texBase.resolution; + var offset = tex.clampOffset; + + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.clampOffset[0] = offset / texBase.realWidth; + this.clampOffset[1] = offset / texBase.realHeight; + }; + + _createClass(TextureTransform, [{ + key: 'texture', + get: function get() { + return this._texture; + } + + /** + * sets texture value + * @param {PIXI.Texture} value texture to be set + */ + , + set: function set(value) { + this._texture = value; + this._lastTextureID = -1; + } + }]); + + return TextureTransform; +}(); + +exports.default = TextureTransform; + +},{"../math/Matrix":99}],146:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _GroupD = require('../math/GroupD8'); + +var _GroupD2 = _interopRequireDefault(_GroupD); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A standard object to store the Uvs of a texture + * + * @class + * @private + * @memberof PIXI + */ +var TextureUvs = function () { + /** + * + */ + function TextureUvs() { + _classCallCheck(this, TextureUvs); + + this.x0 = 0; + this.y0 = 0; + + this.x1 = 1; + this.y1 = 0; + + this.x2 = 1; + this.y2 = 1; + + this.x3 = 0; + this.y3 = 1; + + this.uvsUint32 = new Uint32Array(4); + this.uvsMatrix = null; + } + + /** + * Sets the texture Uvs based on the given frame information. + * + * @private + * @param {PIXI.Rectangle} frame - The frame of the texture + * @param {PIXI.Rectangle} baseFrame - The base frame of the texture + * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8} + */ + + + TextureUvs.prototype.set = function set(frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + + // coordinates of center + var cX = frame.x / tw + w2; + var cY = frame.y / th + h2; + + rotate = _GroupD2.default.add(rotate, _GroupD2.default.NW); // NW is top-left corner + this.x0 = cX + w2 * _GroupD2.default.uX(rotate); + this.y0 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + w2 * _GroupD2.default.uX(rotate); + this.y1 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x2 = cX + w2 * _GroupD2.default.uX(rotate); + this.y2 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x3 = cX + w2 * _GroupD2.default.uX(rotate); + this.y3 = cY + h2 * _GroupD2.default.uY(rotate); + } else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + + this.uvsUint32[0] = (this.y0 * 65535 & 0xFFFF) << 16 | this.x0 * 65535 & 0xFFFF; + this.uvsUint32[1] = (this.y1 * 65535 & 0xFFFF) << 16 | this.x1 * 65535 & 0xFFFF; + this.uvsUint32[2] = (this.y2 * 65535 & 0xFFFF) << 16 | this.x2 * 65535 & 0xFFFF; + this.uvsUint32[3] = (this.y3 * 65535 & 0xFFFF) << 16 | this.x3 * 65535 & 0xFFFF; + }; + + return TextureUvs; +}(); + +exports.default = TextureUvs; + +},{"../math/GroupD8":98}],147:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _utils = require('../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture of a [playing] Video. + * + * Video base textures mimic Pixi BaseTexture.from.... method in their creation process. + * + * This can be used in several ways, such as: + * + * ```js + * let texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4'); + * + * let texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' }); + * + * let texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']); + * + * let texture = PIXI.VideoBaseTexture.fromUrls([ + * { src: '/video.webm', mime: 'video/webm' }, + * { src: '/video.mp4', mime: 'video/mp4' } + * ]); + * ``` + * + * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/). + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var VideoBaseTexture = function (_BaseTexture) { + _inherits(VideoBaseTexture, _BaseTexture); + + /** + * @param {HTMLVideoElement} source - Video source + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + */ + function VideoBaseTexture(source, scaleMode) { + _classCallCheck(this, VideoBaseTexture); + + if (!source) { + throw new Error('No video source element specified.'); + } + + // hook in here to check if video is already available. + // BaseTexture looks for a source.complete boolean, plus width & height. + + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + source.complete = true; + } + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, source, scaleMode)); + + _this.width = source.videoWidth; + _this.height = source.videoHeight; + + /** + * Should the base texture automatically update itself, set to true by default + * + * @member {boolean} + * @default true + */ + _this.autoUpdate = false; + + /** + * When set to true will automatically play videos used by this texture once + * they are loaded. If false, it will not modify the playing state. + * + * @member {boolean} + * @default true + */ + _this.autoPlay = true; + + _this._onUpdate = _this._onUpdate.bind(_this); + _this._onCanPlay = _this._onCanPlay.bind(_this); + + source.addEventListener('play', _this._onPlayStart.bind(_this)); + source.addEventListener('pause', _this._onPlayStop.bind(_this)); + _this.hasLoaded = false; + _this.__loaded = false; + + if (!_this._isSourceReady()) { + source.addEventListener('canplay', _this._onCanPlay); + source.addEventListener('canplaythrough', _this._onCanPlay); + } else { + _this._onCanPlay(); + } + return _this; + } + + /** + * Returns true if the underlying source is playing. + * + * @private + * @return {boolean} True if playing. + */ + + + VideoBaseTexture.prototype._isSourcePlaying = function _isSourcePlaying() { + var source = this.source; + + return source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2; + }; + + /** + * Returns true if the underlying source is ready for playing. + * + * @private + * @return {boolean} True if ready. + */ + + + VideoBaseTexture.prototype._isSourceReady = function _isSourceReady() { + return this.source.readyState === 3 || this.source.readyState === 4; + }; + + /** + * The internal update loop of the video base texture, only runs when autoUpdate is set to true + * + * @private + */ + + + VideoBaseTexture.prototype._onUpdate = function _onUpdate() { + if (this.autoUpdate) { + window.requestAnimationFrame(this._onUpdate); + this.update(); + } + }; + + /** + * Runs the update loop when the video is ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStart = function _onPlayStart() { + // Just in case the video has not recieved its can play even yet.. + if (!this.hasLoaded) { + this._onCanPlay(); + } + + if (!this.autoUpdate) { + window.requestAnimationFrame(this._onUpdate); + this.autoUpdate = true; + } + }; + + /** + * Fired when a pause event is triggered, stops the update loop + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStop = function _onPlayStop() { + this.autoUpdate = false; + }; + + /** + * Fired when the video is loaded and ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onCanPlay = function _onCanPlay() { + this.hasLoaded = true; + + if (this.source) { + this.source.removeEventListener('canplay', this._onCanPlay); + this.source.removeEventListener('canplaythrough', this._onCanPlay); + + this.width = this.source.videoWidth; + this.height = this.source.videoHeight; + + // prevent multiple loaded dispatches.. + if (!this.__loaded) { + this.__loaded = true; + this.emit('loaded', this); + } + + if (this._isSourcePlaying()) { + this._onPlayStart(); + } else if (this.autoPlay) { + this.source.play(); + } + } + }; + + /** + * Destroys this texture + * + */ + + + VideoBaseTexture.prototype.destroy = function destroy() { + if (this.source && this.source._pixiId) { + delete _utils.BaseTextureCache[this.source._pixiId]; + delete this.source._pixiId; + } + + _BaseTexture.prototype.destroy.call(this); + }; + + /** + * Mimic Pixi BaseTexture.from.... method. + * + * @static + * @param {HTMLVideoElement} video - Video to create texture from + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromVideo = function fromVideo(video, scaleMode) { + if (!video._pixiId) { + video._pixiId = 'video_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[video._pixiId]; + + if (!baseTexture) { + baseTexture = new VideoBaseTexture(video, scaleMode); + _utils.BaseTextureCache[video._pixiId] = baseTexture; + } + + return baseTexture; + }; + + /** + * Helper function that creates a new BaseTexture based on the given video element. + * This BaseTexture can then be used to create a texture + * + * @static + * @param {string|object|string[]|object[]} videoSrc - The URL(s) for the video. + * @param {string} [videoSrc.src] - One of the source urls for the video + * @param {string} [videoSrc.mime] - The mimetype of the video (e.g. 'video/mp4'). If not specified + * the url's extension will be used as the second part of the mime type. + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromUrl = function fromUrl(videoSrc, scaleMode) { + var video = document.createElement('video'); + + video.setAttribute('webkit-playsinline', ''); + video.setAttribute('playsinline', ''); + + // array of objects or strings + if (Array.isArray(videoSrc)) { + for (var i = 0; i < videoSrc.length; ++i) { + video.appendChild(createSource(videoSrc[i].src || videoSrc[i], videoSrc[i].mime)); + } + } + // single object or string + else { + video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); + } + + video.load(); + video.play(); + + return VideoBaseTexture.fromVideo(video, scaleMode); + }; + + return VideoBaseTexture; +}(_BaseTexture3.default); + +exports.default = VideoBaseTexture; + + +VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; + +function createSource(path, type) { + if (!type) { + type = 'video/' + path.substr(path.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = path; + source.type = type; + + return source; +} + +},{"../utils":152,"./BaseTexture":142}],148:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../const'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// Internal event used by composed emitter +var TICK = 'tick'; + +/** + * A Ticker class that runs an update loop that other objects listen to. + * This class is composed around an EventEmitter object to add listeners + * meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, + * e.g. When the ticker is started and the emitter has listeners. + * + * @class + * @memberof PIXI.ticker + */ + +var Ticker = function () { + /** + * + */ + function Ticker() { + var _this = this; + + _classCallCheck(this, Ticker); + + /** + * Internal emitter used to fire 'tick' event + * @private + */ + this._emitter = new _eventemitter2.default(); + + /** + * Internal current frame request ID + * @private + */ + this._requestId = null; + + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + * @private + */ + this._maxElapsedMS = 100; + + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.ticker.Ticker#start} automatically + * when a listener is added. + * + * @member {boolean} + * @default false + */ + this.autoStart = false; + + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS} + * and is scaled with {@link PIXI.ticker.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * + * @member {number} + * @default 1 + */ + this.deltaTime = 1; + + /** + * Time elapsed in milliseconds from last frame to this frame. + * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime} + * is based, this value is neither capped nor scaled. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default 1 / TARGET_FPMS + */ + this.elapsedMS = 1 / _const.TARGET_FPMS; // default to target frame time + + /** + * The last time {@link PIXI.ticker.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default 0 + */ + this.lastTime = 0; + + /** + * Factor of current {@link PIXI.ticker.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + * + * @member {number} + * @default 1 + */ + this.speed = 1; + + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.ticker.Ticker#start} has been called. + * `false` if {@link PIXI.ticker.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.ticker.Ticker#autoStart} being `true` + * and a listener is added. + * + * @member {boolean} + * @default false + */ + this.started = false; + + /** + * Internal tick method bound to ticker instance. + * This is because in early 2015, Function.bind + * is still 60% slower in high performance scenarios. + * Also separating frame requests from update method + * so listeners may be called at any time and with + * any animation API, just invoke ticker.update(time). + * + * @private + * @param {number} time - Time since last tick. + */ + this._tick = function (time) { + _this._requestId = null; + + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._emitter.listeners(TICK, true)) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * + * @private + */ + + + Ticker.prototype._requestIfNeeded = function _requestIfNeeded() { + if (this._requestId === null && this._emitter.listeners(TICK, true)) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._requestId = requestAnimationFrame(this._tick); + } + }; + + /** + * Conditionally cancels a pending animation frame. + * + * @private + */ + + + Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; + + /** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * + * @private + */ + + + Ticker.prototype._startIfPossible = function _startIfPossible() { + if (this.started) { + this._requestIfNeeded(); + } else if (this.autoStart) { + this.start(); + } + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#on} internally for the + * internal 'tick' event. It checks if the emitter has listeners, + * and if so it requests a new animation frame at this point. + * + * @param {Function} fn - The listener function to be added for updates + * @param {Function} [context] - The listener context + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.add = function add(fn, context) { + this._emitter.on(TICK, fn, context); + + this._startIfPossible(); + + return this; + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#once} internally for the + * internal 'tick' event. It checks if the emitter has listeners, + * and if so it requests a new animation frame at this point. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context] - The listener context + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.addOnce = function addOnce(fn, context) { + this._emitter.once(TICK, fn, context); + + this._startIfPossible(); + + return this; + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#off} internally for 'tick' event. + * It checks if the emitter has listeners for 'tick' event. + * If it does, then it cancels the animation frame. + * + * @param {Function} [fn] - The listener function to be removed + * @param {Function} [context] - The listener context to be removed + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.remove = function remove(fn, context) { + this._emitter.off(TICK, fn, context); + + if (!this._emitter.listeners(TICK, true)) { + this._cancelIfNeeded(); + } + + return this; + }; + + /** + * Starts the ticker. If the ticker has listeners + * a new animation frame is requested at this point. + */ + + + Ticker.prototype.start = function start() { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + }; + + /** + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. + */ + + + Ticker.prototype.stop = function stop() { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; + + /** + * Triggers an update. An update entails setting the + * current {@link PIXI.ticker.Ticker#elapsedMS}, + * the current {@link PIXI.ticker.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.ticker.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + + + Ticker.prototype.update = function update() { + var currentTime = arguments.length <= 0 || arguments[0] === undefined ? performance.now() : arguments[0]; + + var elapsedMS = void 0; + + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + + this.deltaTime = elapsedMS * _const.TARGET_FPMS * this.speed; + + // Invoke listeners added to internal emitter + this._emitter.emit(TICK, this.deltaTime); + } else { + this.deltaTime = this.elapsedMS = 0; + } + + this.lastTime = currentTime; + }; + + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.ticker.Ticker#speed}, which is specific + * to scaling {@link PIXI.ticker.Ticker#deltaTime}. + * + * @memberof PIXI.ticker.Ticker# + * @readonly + */ + + + _createClass(Ticker, [{ + key: 'FPS', + get: function get() { + return 1000 / this.elapsedMS; + } + + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.ticker.Ticker#update}. + * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.TARGET_FPMS * 1000`. + * + * @memberof PIXI.ticker.Ticker# + * @default 10 + */ + + }, { + key: 'minFPS', + get: function get() { + return 1000 / this._maxElapsedMS; + } + + /** + * Sets the min fps. + * + * @param {number} fps - value to set. + */ + , + set: function set(fps) { + // Clamp: 0 to TARGET_FPMS + var minFPMS = Math.min(Math.max(0, fps) / 1000, _const.TARGET_FPMS); + + this._maxElapsedMS = 1 / minFPMS; + } + }]); + + return Ticker; +}(); + +exports.default = Ticker; + +},{"../const":78,"eventemitter3":16}],149:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Ticker = exports.shared = undefined; + +var _Ticker = require('./Ticker'); + +var _Ticker2 = _interopRequireDefault(_Ticker); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The shared ticker instance used by {@link PIXI.extras.MovieClip}. + * and by {@link PIXI.interaction.InteractionManager}. + * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` + * for this instance. Please follow the examples for usage, including + * how to opt-out of auto-starting the shared ticker. + * + * @example + * let ticker = PIXI.ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(800, 600); + * let stage = new PIXI.Container(); + * let interactionManager = PIXI.interaction.InteractionManager(renderer); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * + * @type {PIXI.ticker.Ticker} + * @memberof PIXI.ticker + */ +var shared = new _Ticker2.default(); + +shared.autoStart = true; + +/** + * @namespace PIXI.ticker + */ +exports.shared = shared; +exports.Ticker = _Ticker2.default; + +},{"./Ticker":148}],150:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = createIndicesForQuads; +/** + * Generic Mask Stack data structure + * + * @class + * @memberof PIXI + * @param {number} size - Number of quads + * @return {Uint16Array} indices + */ +function createIndicesForQuads(size) { + // the total number of indices in our array, there are 6 points per quad. + + var totalIndices = size * 6; + + var indices = new Uint16Array(totalIndices); + + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + indices[i + 0] = j + 0; + indices[i + 1] = j + 1; + indices[i + 2] = j + 2; + indices[i + 3] = j + 0; + indices[i + 4] = j + 2; + indices[i + 5] = j + 3; + } + + return indices; +} + +},{}],151:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = determineCrossOrigin; + +var _url2 = require('url'); + +var _url3 = _interopRequireDefault(_url2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var tempAnchor = void 0; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +function determineCrossOrigin(url) { + var loc = arguments.length <= 1 || arguments[1] === undefined ? window.location : arguments[1]; + + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url3.default.parse(tempAnchor.href); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +} + +},{"url":72}],152:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BaseTextureCache = exports.TextureCache = exports.pluginTarget = exports.EventEmitter = undefined; +exports.uid = uid; +exports.hex2rgb = hex2rgb; +exports.hex2string = hex2string; +exports.rgb2hex = rgb2hex; +exports.getResolutionOfUrl = getResolutionOfUrl; +exports.decomposeDataUri = decomposeDataUri; +exports.getImageTypeOfUrl = getImageTypeOfUrl; +exports.getSvgSize = getSvgSize; +exports.skipHello = skipHello; +exports.sayHello = sayHello; +exports.isWebGLSupported = isWebGLSupported; +exports.sign = sign; +exports.removeItems = removeItems; + +var _const = require('../const'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _pluginTarget = require('./pluginTarget'); + +var _pluginTarget2 = _interopRequireDefault(_pluginTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var nextUid = 0; +var saidHello = false; + +/** + * @namespace PIXI.utils + */ +exports.EventEmitter = _eventemitter2.default; +exports.pluginTarget = _pluginTarget2.default; + +/** + * Gets the next unique identifier + * + * @memberof PIXI.utils + * @return {number} The next unique identifier to use. + */ + +function uid() { + return ++nextUid; +} + +/** + * Converts a hex color number to an [R, G, B] array + * + * @memberof PIXI.utils + * @param {number} hex - The number to convert + * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one + * @return {number[]} An array representing the [R, G, B] of the color. + */ +function hex2rgb(hex, out) { + out = out || []; + + out[0] = (hex >> 16 & 0xFF) / 255; + out[1] = (hex >> 8 & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + + return out; +} + +/** + * Converts a hex color number to a string. + * + * @memberof PIXI.utils + * @param {number} hex - Number in hex + * @return {string} The string color. + */ +function hex2string(hex) { + hex = hex.toString(16); + hex = '000000'.substr(0, 6 - hex.length) + hex; + + return '#' + hex; +} + +/** + * Converts a color as an [R, G, B] array to a hex number + * + * @memberof PIXI.utils + * @param {number[]} rgb - rgb array + * @return {number} The color number + */ +function rgb2hex(rgb) { + return (rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + rgb[2] * 255; +} + +/** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * + * @memberof PIXI.utils + * @param {string} url - the image path + * @return {number} resolution / device pixel ratio of an asset + */ +function getResolutionOfUrl(url) { + var resolution = _const.RETINA_PREFIX.exec(url); + + if (resolution) { + return parseFloat(resolution[1]); + } + + return 1; +} + +/** + * Typedef for decomposeDataUri return object. + * + * @typedef {object} DecomposedDataUri + * @property {mediaType} Media type, eg. `image` + * @property {subType} Sub type, eg. `png` + * @property {encoding} Data encoding, eg. `base64` + * @property {data} The actual data + */ + +/** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. + * + * @memberof PIXI.utils + * @param {string} dataUri - the data URI to check + * @return {DecomposedDataUri|undefined} The decomposed data uri or undefined + */ +function decomposeDataUri(dataUri) { + var dataUriMatch = _const.DATA_URI.exec(dataUri); + + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + encoding: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + data: dataUriMatch[4] + }; + } + + return undefined; +} + +/** + * Get type of the image by regexp for extension. Returns undefined for unknown extensions. + * + * @memberof PIXI.utils + * @param {string} url - the image path + * @return {string|undefined} image extension + */ +function getImageTypeOfUrl(url) { + var extension = _const.IMAGE_TYPE.exec(url); + + if (extension) { + return extension[1].toLowerCase(); + } + + return undefined; +} + +/** + * Typedef for Size object. + * + * @typedef {object} Size + * @property {width} Width component + * @property {height} Height component + */ + +/** + * Get size from an svg string using regexp. + * + * @memberof PIXI.utils + * @param {string} svgString - a serialized svg element + * @return {Size|undefined} image extension + */ +function getSvgSize(svgString) { + var sizeMatch = _const.SVG_SIZE.exec(svgString); + var size = {}; + + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[2])); + size[sizeMatch[3]] = Math.round(parseFloat(sizeMatch[4])); + } + + return size; +} + +/** + * Skips the hello message of renderers that are created after this is run. + * + */ +function skipHello() { + saidHello = true; +} + +/** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever makes you a jerk face. + * + * @static + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ +function sayHello(type) { + if (saidHello) { + return; + } + + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = ['\n %c %c %c Pixi.js ' + _const.VERSION + ' - ✰ ' + type + ' ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n', 'background: #ff66a5; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff66a5; background: #030307; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'background: #ffc3dc; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;']; + + window.console.log.apply(console, args); + } else if (window.console) { + window.console.log('Pixi.js ' + _const.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); + } + + saidHello = true; +} + +/** + * Helper for checking for webgl support + * + * @memberof PIXI.utils + * @return {boolean} is webgl supported + */ +function isWebGLSupported() { + var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; + + try { + if (!window.WebGLRenderingContext) { + return false; + } + + var canvas = document.createElement('canvas'); + var gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); + + var success = !!(gl && gl.getContextAttributes().stencil); + + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + + if (loseContext) { + loseContext.loseContext(); + } + } + + gl = null; + + return success; + } catch (e) { + return false; + } +} + +/** + * Returns sign of number + * + * @memberof PIXI.utils + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ +function sign(n) { + if (n === 0) return 0; + + return n < 0 ? -1 : 1; +} + +/** + * Remove a range of items from an array + * + * @memberof PIXI.utils + * @param {Array<*>} arr The target array + * @param {number} startIdx The index to begin removing from (inclusive) + * @param {number} removeCount How many items to remove + */ +function removeItems(arr, startIdx, removeCount) { + var length = arr.length; + + if (startIdx >= length || removeCount === 0) { + return; + } + + removeCount = startIdx + removeCount > length ? length - startIdx : removeCount; + + var len = length - removeCount; + + for (var i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount]; + } + + arr.length = len; +} + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var TextureCache = exports.TextureCache = {}; + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var BaseTextureCache = exports.BaseTextureCache = {}; + +},{"../const":78,"./pluginTarget":154,"eventemitter3":16}],153:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = maxRecommendedTextures; + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function maxRecommendedTextures(max) { + if (_ismobilejs2.default.tablet || _ismobilejs2.default.phone) { + // check if the res is iphone 6 or higher.. + return 2; + } + + // desktop should be ok + return max; +} + +},{"ismobilejs":17}],154:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Mixins functionality to make an object have "plugins". + * + * @example + * function MyObject() {} + * + * pluginTarget.mixin(MyObject); + * + * @mixin + * @memberof PIXI.utils + * @param {object} obj - The object to mix into. + */ +function pluginTarget(obj) { + obj.__plugins = {}; + + /** + * Adds a plugin to an object + * + * @param {string} pluginName - The events that should be listed. + * @param {Function} ctor - The constructor function for the plugin. + */ + obj.registerPlugin = function registerPlugin(pluginName, ctor) { + obj.__plugins[pluginName] = ctor; + }; + + /** + * Instantiates all the plugins of this object + * + */ + obj.prototype.initPlugins = function initPlugins() { + this.plugins = this.plugins || {}; + + for (var o in obj.__plugins) { + this.plugins[o] = new obj.__plugins[o](this); + } + }; + + /** + * Removes all the plugins of this object + * + */ + obj.prototype.destroyPlugins = function destroyPlugins() { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + + this.plugins = null; + }; +} + +exports.default = { + /** + * Mixes in the properties of the pluginTarget into another object + * + * @param {object} obj - The obj to mix into + */ + mixin: function mixin(obj) { + pluginTarget(obj); + } +}; + +},{}],155:[function(require,module,exports){ +'use strict'; + +var _core = require('./core'); + +var core = _interopRequireWildcard(_core); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code +function warn(msg) { + /* eslint-disable no-console */ + var stack = new Error().stack; + + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('Deprecation Warning: ', msg); + } else { + // chop off the stack trace which includes pixi.js internal calls + stack = stack.split('\n').splice(3).join('\n'); + + if (console.groupCollapsed) { + console.groupCollapsed('%cDeprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', msg); + console.warn(stack); + console.groupEnd(); + } else { + console.warn('Deprecation Warning: ', msg); + console.warn(stack); + } + } + /* eslint-enable no-console */ +} + +/** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ +core.SpriteBatch = function () { + throw new ReferenceError('SpriteBatch does not exist any more, please use the new ParticleContainer instead.'); +}; + +/** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ +core.AssetLoader = function () { + throw new ReferenceError('The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class.'); +}; + +Object.defineProperties(core, { + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + Stage: { + get: function get() { + warn('You do not need to use a PIXI Stage any more, you can simply render any container.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + DisplayObjectContainer: { + get: function get() { + warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + Strip: { + get: function get() { + warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.'); + + return mesh.Mesh; + } + }, + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + Rope: { + get: function get() { + warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.'); + + return mesh.Rope; + } + }, + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + ParticleContainer: { + get: function get() { + warn('The ParticleContainer class has been moved to particles.ParticleContainer, ' + 'please use particles.ParticleContainer from now on.'); + + return particles.ParticleContainer; + } + }, + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + MovieClip: { + get: function get() { + warn('The MovieClip class has been moved to extras.MovieClip, please use extras.MovieClip from now on.'); + + return extras.MovieClip; + } + }, + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + TilingSprite: { + get: function get() { + warn('The TilingSprite class has been moved to extras.TilingSprite, ' + 'please use extras.TilingSprite from now on.'); + + return extras.TilingSprite; + } + }, + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + BitmapText: { + get: function get() { + warn('The BitmapText class has been moved to extras.BitmapText, ' + 'please use extras.BitmapText from now on.'); + + return extras.BitmapText; + } + }, + + /** + * @class + * @private + * @name blendModes + * @memberof PIXI + * @see PIXI.BLEND_MODES + * @deprecated since version 3.0.0 + */ + blendModes: { + get: function get() { + warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.'); + + return core.BLEND_MODES; + } + }, + + /** + * @class + * @private + * @name scaleModes + * @memberof PIXI + * @see PIXI.SCALE_MODES + * @deprecated since version 3.0.0 + */ + scaleModes: { + get: function get() { + warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.'); + + return core.SCALE_MODES; + } + }, + + /** + * @class + * @private + * @name BaseTextureCache + * @memberof PIXI + * @see PIXI.utils.BaseTextureCache + * @deprecated since version 3.0.0 + */ + BaseTextureCache: { + get: function get() { + warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, ' + 'please use utils.BaseTextureCache from now on.'); + + return core.utils.BaseTextureCache; + } + }, + + /** + * @class + * @private + * @name TextureCache + * @memberof PIXI + * @see PIXI.utils.TextureCache + * @deprecated since version 3.0.0 + */ + TextureCache: { + get: function get() { + warn('The TextureCache class has been moved to utils.TextureCache, ' + 'please use utils.TextureCache from now on.'); + + return core.utils.TextureCache; + } + }, + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + math: { + get: function get() { + warn('The math namespace is deprecated, please access members already accessible on PIXI.'); + + return core; + } + }, + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.Filter; + } + }, + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + TransformManual: { + get: function get() { + warn('TransformManual has been renamed to TransformBase, please update your pixi-spine'); + + return core.TransformBase; + } + } +}); + +core.DisplayObject.prototype.generateTexture = function (renderer, scaleMode, resolution) { + warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); + + return renderer.generateTexture(undefined, scaleMode, resolution); +}; + +core.Graphics.prototype.generateTexture = function (scaleMode, resolution) { + warn('graphics generate texture has moved to the renderer. ' + 'Or to render a graphics to a texture using canvas please use generateCanvasTexture'); + + return undefined.generateCanvasTexture(scaleMode, resolution); +}; + +core.RenderTexture.prototype.render = function (displayObject, matrix, clear, updateTransform) { + undefined.legacyRenderer.render(displayObject, undefined, clear, matrix, !updateTransform); + warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)'); +}; + +core.RenderTexture.prototype.getImage = function (target) { + warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); + + return undefined.legacyRenderer.extract.image(target); +}; + +core.RenderTexture.prototype.getBase64 = function (target) { + warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); + + return undefined.legacyRenderer.extract.base64(target); +}; + +core.RenderTexture.prototype.getCanvas = function (target) { + warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); + + return undefined.legacyRenderer.extract.canvas(target); +}; + +core.RenderTexture.prototype.getPixels = function (target) { + warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); + + return undefined.legacyRenderer.pixels(target); +}; + +/** + * @method + * @private + * @name PIXI.Sprite#setTexture + * @see PIXI.Sprite#texture + * @deprecated since version 3.0.0 + * @param {PIXI.Texture} texture - The texture to set to. + */ +core.Sprite.prototype.setTexture = function (texture) { + undefined.texture = texture; + warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;'); +}; + +/** + * @method + * @name PIXI.extras.BitmapText#setText + * @see PIXI.extras.BitmapText#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ +extras.BitmapText.prototype.setText = function (text) { + undefined.text = text; + warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';'); +}; + +/** + * @method + * @name PIXI.Text#setText + * @see PIXI.Text#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ +core.Text.prototype.setText = function (text) { + undefined.text = text; + warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';'); +}; + +/** + * @method + * @name PIXI.Text#setStyle + * @see PIXI.Text#style + * @deprecated since version 3.0.0 + * @param {*} style - The style to set to. + */ +core.Text.prototype.setStyle = function (style) { + undefined.style = style; + warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;'); +}; + +Object.defineProperties(core.TextStyle.prototype, { + /** + * Set all properties of a font as a single string + * + * @name PIXI.TextStyle#font + * @deprecated since version 4.0.0 + */ + font: { + get: function get() { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\', \'fontSize\', \'fontStyle\', \'fontVariant\' and \'fontWeight\' properties from now on'); + + var fontSizeString = typeof this._fontSize === 'number' ? this._fontSize + 'px' : this._fontSize; + + return this._fontStyle + ' ' + this._fontVariant + ' ' + this._fontWeight + ' ' + fontSizeString + ' ' + this._fontFamily; + }, + set: function set(font) { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + + // can work out fontStyle from search of whole string + if (font.indexOf('italic') > 1) { + this._fontStyle = 'italic'; + } else if (font.indexOf('oblique') > -1) { + this._fontStyle = 'oblique'; + } else { + this._fontStyle = 'normal'; + } + + // can work out fontVariant from search of whole string + if (font.indexOf('small-caps') > -1) { + this._fontVariant = 'small-caps'; + } else { + this._fontVariant = 'normal'; + } + + // fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units + var splits = font.split(' '); + var fontSizeIndex = -1; + + this._fontSize = 26; + for (var i = 0; i < splits.length; ++i) { + if (splits[i].match(/(px|pt|em|%)/)) { + fontSizeIndex = i; + this._fontSize = splits[i]; + break; + } + } + + // we can now search for fontWeight as we know it must occur before the fontSize + this._fontWeight = 'normal'; + for (var _i = 0; _i < fontSizeIndex; ++_i) { + if (splits[_i].match(/(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/)) { + this._fontWeight = splits[_i]; + break; + } + } + + // and finally join everything together after the fontSize in case the font family has multiple words + if (fontSizeIndex > -1 && fontSizeIndex < splits.length - 1) { + this._fontFamily = ''; + for (var _i2 = fontSizeIndex + 1; _i2 < splits.length; ++_i2) { + this._fontFamily += splits[_i2] + ' '; + } + + this._fontFamily = this._fontFamily.slice(0, -1); + } else { + this._fontFamily = 'Arial'; + } + + this.styleID++; + } + } +}); + +/** + * @method + * @name PIXI.Texture#setFrame + * @see PIXI.Texture#setFrame + * @deprecated since version 3.0.0 + * @param {PIXI.Rectangle} frame - The frame to set. + */ +core.Texture.prototype.setFrame = function (frame) { + undefined.frame = frame; + warn('setFrame is now deprecated, please use the frame property, e.g: myTexture.frame = frame;'); +}; + +Object.defineProperties(filters, { + + /** + * @class + * @private + * @name PIXI.filters.AbstractFilter + * @see PIXI.AbstractFilter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.AbstractFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.SpriteMaskFilter + * @see PIXI.SpriteMaskFilter + * @deprecated since version 3.0.6 + */ + SpriteMaskFilter: { + get: function get() { + warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.'); + + return core.SpriteMaskFilter; + } + } +}); + +/** + * @method + * @name PIXI.utils.uuid + * @see PIXI.utils.uid + * @deprecated since version 3.0.6 + * @return {number} The uid + */ +core.utils.uuid = function () { + warn('utils.uuid() is deprecated, please use utils.uid() from now on.'); + + return core.utils.uid(); +}; + +/** + * @method + * @name PIXI.utils.canUseNewCanvasBlendModes + * @see PIXI.CanvasTinter + * @deprecated + * @return {boolean} Can use blend modes. + */ +core.utils.canUseNewCanvasBlendModes = function () { + warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on'); + + return core.CanvasTinter.canUseMultiply; +}; + +},{"./core":97,"./extras":165,"./filters":176,"./mesh":193,"./particles":196}],156:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers. + * + * @class + * @memberof PIXI + */ + +var CanvasExtract = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasExtract(renderer) { + _classCallCheck(this, CanvasExtract); + + this.renderer = renderer; + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + CanvasExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `CanvasExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + CanvasExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + CanvasExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = this.renderer.width; + frame.height = this.renderer.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + CanvasExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + + return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; + }; + + /** + * Destroys the extract + * + */ + + + CanvasExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return CanvasExtract; +}(); + +exports.default = CanvasExtract; + + +core.CanvasRenderer.registerPlugin('extract', CanvasExtract); + +},{"../../core":97}],157:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLExtract = require('./webgl/WebGLExtract'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLExtract).default; + } +}); + +var _CanvasExtract = require('./canvas/CanvasExtract'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasExtract).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./canvas/CanvasExtract":156,"./webgl/WebGLExtract":158}],158:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); +var BYTES_PER_PIXEL = 4; + +/** + * The extract manager provides functionality to export content from the renderers. + * + * @class + * @memberof PIXI + */ + +var WebGLExtract = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLExtract(renderer) { + _classCallCheck(this, WebGLExtract); + + this.renderer = renderer; + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + WebGLExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `WebGLExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + WebGLExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + WebGLExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var flipY = false; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + flipY = false; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + flipY = true; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + + // set up an array of pixels + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + + canvasData.data.set(webglPixels); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // pulling pixels + if (flipY) { + canvasBuffer.context.scale(1, -1); + canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); + } + } + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + WebGLExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + } + + return webglPixels; + }; + + /** + * Destroys the extract + * + */ + + + WebGLExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return WebGLExtract; +}(); + +exports.default = WebGLExtract; + + +core.WebGLRenderer.registerPlugin('extract', WebGLExtract); + +},{"../../core":97}],159:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ObservablePoint = require('../core/math/ObservablePoint'); + +var _ObservablePoint2 = _interopRequireDefault(_ObservablePoint); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BitmapText object will create a line or multiple lines of text using bitmap font. To + * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using: + * + * A BitmapText can only be created when the font is loaded + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); + * ``` + * + * http://www.angelcode.com/products/bmfont/ for windows or + * http://www.bmglyph.com/ for mac. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.extras + */ +var BitmapText = function (_core$Container) { + _inherits(BitmapText, _core$Container); + + /** + * @param {string} text - The copy that you would like the text to display + * @param {object} style - The style parameters + * @param {string|object} style.font - The font descriptor for the object, can be passed as a string of form + * "24px FontName" or "FontName" or as an object with explicit name/size properties. + * @param {string} [style.font.name] - The bitmap font id + * @param {number} [style.font.size] - The size of the font in pixels, e.g. 24 + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), does not affect + * single line text + * @param {number} [style.tint=0xFFFFFF] - The tint color + */ + function BitmapText(text) { + var style = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + + _classCallCheck(this, BitmapText); + + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this.textWidth = 0; + + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + _this.textHeight = 0; + + /** + * Private tracker for the letter sprite pool. + * + * @member {PIXI.Sprite[]} + * @private + */ + _this._glyphs = []; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._font = { + tint: style.tint !== undefined ? style.tint : 0xFFFFFF, + align: style.align || 'left', + name: null, + size: 0 + }; + + /** + * Private tracker for the current font. + * + * @member {object} + * @private + */ + _this.font = style.font; // run font setter + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = text; + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + */ + _this.maxWidth = 0; + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + */ + _this.maxLineHeight = 0; + + /** + * Text anchor. read-only + * + * @member {PIXI.ObservablePoint} + * @private + */ + _this._anchor = new _ObservablePoint2.default(function () { + _this.dirty = true; + }, _this, 0, 0); + + /** + * The dirty state of this object. + * + * @member {boolean} + */ + _this.dirty = false; + + _this.updateText(); + return _this; + } + + /** + * Renders text and updates it when needed + * + * @private + */ + + + BitmapText.prototype.updateText = function updateText() { + var data = BitmapText.fonts[this._font.name]; + var scale = this._font.size / data.size; + var pos = new core.Point(); + var chars = []; + var lineWidths = []; + + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastSpace = -1; + var lastSpaceWidth = 0; + var maxLineHeight = 0; + + for (var i = 0; i < this.text.length; i++) { + var charCode = this.text.charCodeAt(i); + + if (/(\s)/.test(this.text.charAt(i))) { + lastSpace = i; + lastSpaceWidth = lastLineWidth; + } + + if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) { + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + if (lastSpace !== -1 && this.maxWidth > 0 && pos.x * scale > this.maxWidth) { + core.utils.removeItems(chars, lastSpace, i - lastSpace); + i = lastSpace; + lastSpace = -1; + + lineWidths.push(lastSpaceWidth); + maxLineWidth = Math.max(maxLineWidth, lastSpaceWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + var charData = data.chars[charCode]; + + if (!charData) { + continue; + } + + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + + chars.push({ + texture: charData.texture, + line: line, + charCode: charCode, + position: new core.Point(pos.x + charData.xOffset, pos.y + charData.yOffset) + }); + lastLineWidth = pos.x + (charData.texture.width + charData.xOffset); + pos.x += charData.xAdvance; + maxLineHeight = Math.max(maxLineHeight, charData.yOffset + charData.texture.height); + prevCharCode = charCode; + } + + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + + var lineAlignOffsets = []; + + for (var _i = 0; _i <= line; _i++) { + var alignOffset = 0; + + if (this._font.align === 'right') { + alignOffset = maxLineWidth - lineWidths[_i]; + } else if (this._font.align === 'center') { + alignOffset = (maxLineWidth - lineWidths[_i]) / 2; + } + + lineAlignOffsets.push(alignOffset); + } + + var lenChars = chars.length; + var tint = this.tint; + + for (var _i2 = 0; _i2 < lenChars; _i2++) { + var c = this._glyphs[_i2]; // get the next glyph sprite + + if (c) { + c.texture = chars[_i2].texture; + } else { + c = new core.Sprite(chars[_i2].texture); + this._glyphs.push(c); + } + + c.position.x = (chars[_i2].position.x + lineAlignOffsets[chars[_i2].line]) * scale; + c.position.y = chars[_i2].position.y * scale; + c.scale.x = c.scale.y = scale; + c.tint = tint; + + if (!c.parent) { + this.addChild(c); + } + } + + // remove unnecessary children. + for (var _i3 = lenChars; _i3 < this._glyphs.length; ++_i3) { + this.removeChild(this._glyphs[_i3]); + } + + this.textWidth = maxLineWidth * scale; + this.textHeight = (pos.y + data.lineHeight) * scale; + + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + for (var _i4 = 0; _i4 < lenChars; _i4++) { + this._glyphs[_i4].x -= this.textWidth * this.anchor.x; + this._glyphs[_i4].y -= this.textHeight * this.anchor.y; + } + } + this.maxLineHeight = maxLineHeight * scale; + }; + + /** + * Updates the transform of this object + * + * @private + */ + + + BitmapText.prototype.updateTransform = function updateTransform() { + this.validate(); + this.containerUpdateTransform(); + }; + + /** + * Validates text before calling parent's getLocalBounds + * + * @return {PIXI.Rectangle} The rectangular bounding area + */ + + + BitmapText.prototype.getLocalBounds = function getLocalBounds() { + this.validate(); + + return _core$Container.prototype.getLocalBounds.call(this); + }; + + /** + * Updates text when needed + * + * @private + */ + + + BitmapText.prototype.validate = function validate() { + if (this.dirty) { + this.updateText(); + this.dirty = false; + } + }; + + /** + * The tint of the BitmapText object + * + * @member {number} + * @memberof PIXI.extras.BitmapText# + */ + + + _createClass(BitmapText, [{ + key: 'tint', + get: function get() { + return this._font.tint; + } + + /** + * Sets the tint. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this._font.tint = typeof value === 'number' && value >= 0 ? value : 0xFFFFFF; + + this.dirty = true; + } + + /** + * The alignment of the BitmapText object + * + * @member {string} + * @default 'left' + * @memberof PIXI.extras.BitmapText# + */ + + }, { + key: 'align', + get: function get() { + return this._font.align; + } + + /** + * Sets the alignment + * + * @param {string} value - The value to set to. + */ + , + set: function set(value) { + this._font.align = value || 'left'; + + this.dirty = true; + } + + /** + * The anchor sets the origin point of the text. + * The default is 0,0 this means the text's origin is the top left + * Setting the anchor to 0.5,0.5 means the text's origin is centered + * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner + * + * @member {PIXI.Point | number} + * @memberof PIXI.extras.BitmapText# + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + } + + /** + * Sets the anchor. + * + * @param {PIXI.Point|number} value - The value to set to. + */ + , + set: function set(value) { + if (typeof value === 'number') { + this._anchor.set(value); + } else { + this._anchor.copy(value); + } + } + + /** + * The font descriptor of the BitmapText object + * + * @member {string|object} + * @memberof PIXI.extras.BitmapText# + */ + + }, { + key: 'font', + get: function get() { + return this._font; + } + + /** + * Sets the font. + * + * @param {string|object} value - The value to set to. + */ + , + set: function set(value) { + if (!value) { + return; + } + + if (typeof value === 'string') { + value = value.split(' '); + + this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); + this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; + } else { + this._font.name = value.name; + this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); + } + + this.dirty = true; + } + + /** + * The text of the BitmapText object + * + * @member {string} + * @memberof PIXI.extras.BitmapText# + */ + + }, { + key: 'text', + get: function get() { + return this._text; + } + + /** + * Sets the text. + * + * @param {string} value - The value to set to. + */ + , + set: function set(value) { + value = value.toString() || ' '; + if (this._text === value) { + return; + } + this._text = value; + this.dirty = true; + } + }]); + + return BitmapText; +}(core.Container); + +exports.default = BitmapText; + + +BitmapText.fonts = {}; + +},{"../core":97,"../core/math/ObservablePoint":100}],160:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @typedef FrameObject + * @type {object} + * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame + * @property {number} time - the duration of the frame in ms + */ + +/** + * A MovieClip is a simple way to display an animation depicted by a list of textures. + * + * ```js + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; + * + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.fromImage(alienImages[i]); + * textureArray.push(texture); + * }; + * + * let mc = new PIXI.MovieClip(textureArray); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ +var MovieClip = function (_core$Sprite) { + _inherits(MovieClip, _core$Sprite); + + /** + * @param {PIXI.Texture[]|FrameObject[]} textures - an array of {@link PIXI.Texture} or frame + * objects that make up the animation + */ + function MovieClip(textures) { + _classCallCheck(this, MovieClip); + + /** + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture)); + + _this._textures = null; + + /** + * @private + */ + _this._durations = null; + + _this.textures = textures; + + /** + * The speed that the MovieClip will play at. Higher is faster, lower is slower + * + * @member {number} + * @default 1 + */ + _this.animationSpeed = 1; + + /** + * Whether or not the movie clip repeats after playing. + * + * @member {boolean} + * @default true + */ + _this.loop = true; + + /** + * Function to call when a MovieClip finishes playing + * + * @method + * @memberof PIXI.extras.MovieClip# + */ + _this.onComplete = null; + + /** + * Function to call when a MovieClip changes which texture is being rendered + * + * @method + * @memberof PIXI.extras.MovieClip# + */ + _this.onFrameChange = null; + + /** + * Elapsed time since animation has been started, used internally to display current texture + * + * @member {number} + * @private + */ + _this._currentTime = 0; + + /** + * Indicates if the MovieClip is currently playing + * + * @member {boolean} + * @readonly + */ + _this.playing = false; + return _this; + } + + /** + * Stops the MovieClip + * + */ + + + MovieClip.prototype.stop = function stop() { + if (!this.playing) { + return; + } + + this.playing = false; + core.ticker.shared.remove(this.update, this); + }; + + /** + * Plays the MovieClip + * + */ + + + MovieClip.prototype.play = function play() { + if (this.playing) { + return; + } + + this.playing = true; + core.ticker.shared.add(this.update, this); + }; + + /** + * Stops the MovieClip and goes to a specific frame + * + * @param {number} frameNumber - frame index to stop at + */ + + + MovieClip.prototype.gotoAndStop = function gotoAndStop(frameNumber) { + this.stop(); + + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + } + }; + + /** + * Goes to a specific frame and begins playing the MovieClip + * + * @param {number} frameNumber - frame index to start at + */ + + + MovieClip.prototype.gotoAndPlay = function gotoAndPlay(frameNumber) { + this._currentTime = frameNumber; + + this.play(); + }; + + /** + * Updates the object transform for rendering. + * + * @private + * @param {number} deltaTime - Time since last tick. + */ + + + MovieClip.prototype.update = function update(deltaTime) { + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + + lag += elapsed / 60 * 1000; + + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + + var sign = Math.sign(this.animationSpeed * deltaTime); + + this._currentTime = Math.floor(this._currentTime); + + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + + this._currentTime += lag / this._durations[this.currentFrame]; + } else { + this._currentTime += elapsed; + } + + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + + if (this.onComplete) { + this.onComplete(); + } + } else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + + if (this.onComplete) { + this.onComplete(); + } + } else if (previousFrame !== this.currentFrame) { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + } + }; + + /** + * Stops the MovieClip and destroys it + * + */ + + + MovieClip.prototype.destroy = function destroy() { + this.stop(); + _core$Sprite.prototype.destroy.call(this); + }; + + /** + * A short hand way of creating a movieclip from an array of frame ids + * + * @static + * @param {string[]} frames - The array of frames ids the movieclip will use as its texture frames + * @return {MovieClip} The new movie clip with the specified frames. + */ + + + MovieClip.fromFrames = function fromFrames(frames) { + var textures = []; + + for (var i = 0; i < frames.length; ++i) { + textures.push(core.Texture.fromFrame(frames[i])); + } + + return new MovieClip(textures); + }; + + /** + * A short hand way of creating a movieclip from an array of image ids + * + * @static + * @param {string[]} images - the array of image urls the movieclip will use as its texture frames + * @return {MovieClip} The new movie clip with the specified images as frames. + */ + + + MovieClip.fromImages = function fromImages(images) { + var textures = []; + + for (var i = 0; i < images.length; ++i) { + textures.push(core.Texture.fromImage(images[i])); + } + + return new MovieClip(textures); + }; + + /** + * totalFrames is the total number of frames in the MovieClip. This is the same as number of textures + * assigned to the MovieClip. + * + * @readonly + * @member {number} + * @memberof PIXI.extras.MovieClip# + * @default 0 + */ + + + _createClass(MovieClip, [{ + key: 'totalFrames', + get: function get() { + return this._textures.length; + } + + /** + * The array of textures used for this MovieClip + * + * @member {PIXI.Texture[]} + * @memberof PIXI.extras.MovieClip# + */ + + }, { + key: 'textures', + get: function get() { + return this._textures; + } + + /** + * Sets the textures. + * + * @param {PIXI.Texture[]} value - The texture to set. + */ + , + set: function set(value) { + if (value[0] instanceof core.Texture) { + this._textures = value; + this._durations = null; + } else { + this._textures = []; + this._durations = []; + + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + } + + /** + * The MovieClips current frame index + * + * @member {number} + * @memberof PIXI.extras.MovieClip# + * @readonly + */ + + }, { + key: 'currentFrame', + get: function get() { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + + return currentFrame; + } + }]); + + return MovieClip; +}(core.Sprite); + +exports.default = MovieClip; + +},{"../core":97}],161:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CanvasTinter = require('../core/sprites/canvas/CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); + +/** + * A tiling sprite is a fast way of rendering a tiling image + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ + +var TilingSprite = function (_core$Sprite) { + _inherits(TilingSprite, _core$Sprite); + + /** + * @param {PIXI.Texture} texture - the texture of the tiling sprite + * @param {number} [width=100] - the width of the tiling sprite + * @param {number} [height=100] - the height of the tiling sprite + */ + function TilingSprite(texture) { + var width = arguments.length <= 1 || arguments[1] === undefined ? 100 : arguments[1]; + var height = arguments.length <= 2 || arguments[2] === undefined ? 100 : arguments[2]; + + _classCallCheck(this, TilingSprite); + + /** + * Tile transform + * + * @member {PIXI.TransformStatic} + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, texture)); + + _this.tileTransform = new core.TransformStatic(); + + // /// private + + /** + * The with of the tiling sprite + * + * @member {number} + * @private + */ + _this._width = width; + + /** + * The height of the tiling sprite + * + * @member {number} + * @private + */ + _this._height = height; + + _this._canvasPattern = null; + + _this._glDatas = []; + + /** + * transform that is applied to UV to get the texture coords + * @member {PIXI.TextureTransform} + */ + _this.uvTransform = new core.TextureTransform(texture); + return _this; + } + + /** + * setter for clampEdge + * @param {number} value assigned value + */ + + + /** + * @private + */ + TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate() { + if (this.uvTransform) { + this.uvTransform.texture = this._texture; + } + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + TilingSprite.prototype._renderWebGL = function _renderWebGL(renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + + if (!texture || !texture.valid) { + return; + } + + this.tileTransform.updateLocalTransform(); + this.uvTransform.update(); + + renderer.setObjectRenderer(renderer.plugins.tiling); + renderer.plugins.tiling.render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer + */ + + + TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { + var texture = this._texture; + + if (!texture.baseTexture.hasLoaded) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var resolution = renderer.resolution; + var baseTexture = texture.baseTexture; + var modX = this.tilePosition.x / this.tileScale.x % texture._frame.width; + var modY = this.tilePosition.y / this.tileScale.y % texture._frame.height; + + // create a nice shiny pattern! + // TODO this needs to be refreshed if texture changes.. + if (!this._canvasPattern) { + // cut an object from a spritesheet.. + var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height); + + // Tint the tiling sprite + if (this.tint !== 0xFFFFFF) { + if (this.cachedTint !== this.tint) { + this.cachedTint = this.tint; + + this.tintedTexture = _CanvasTinter2.default.getTintedTexture(this, this.tint); + } + tempCanvas.context.drawImage(this.tintedTexture, 0, 0); + } else { + tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x, -texture._frame.y); + } + this._canvasPattern = tempCanvas.context.createPattern(tempCanvas.canvas, 'repeat'); + } + + // set context state.. + context.globalAlpha = this.worldAlpha; + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // TODO - this should be rolled into the setTransform above.. + context.scale(this.tileScale.x, this.tileScale.y); + + context.translate(modX + this.anchor.x * -this._width, modY + this.anchor.y * -this._height); + + // check blend mode + var compositeOperation = renderer.blendModes[this.blendMode]; + + if (compositeOperation !== renderer.context.globalCompositeOperation) { + context.globalCompositeOperation = compositeOperation; + } + + // fill the pattern! + context.fillStyle = this._canvasPattern; + context.fillRect(-modX, -modY, this._width / this.tileScale.x, this._height / this.tileScale.y); + }; + + /** + * Returns the framing rectangle of the sprite as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + TilingSprite.prototype.getBounds = function getBounds() { + var width = this._width; + var height = this._height; + + var w0 = width * (1 - this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1 - this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var minX = 0; + var maxX = 0; + var minY = 0; + var maxY = 0; + + minX = x1; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1; + maxX = x2 > maxX ? x2 : maxX; + maxX = x3 > maxX ? x3 : maxX; + maxX = x4 > maxX ? x4 : maxX; + + maxY = y1; + maxY = y2 > maxY ? y2 : maxY; + maxY = y3 > maxY ? y3 : maxY; + maxY = y4 > maxY ? y4 : maxY; + + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; + }; + + /** + * Checks if a point is inside this tiling sprite. + * + * @param {PIXI.Point} point - the point to check + * @return {boolean} Whether or not the sprite contains the point. + */ + + + TilingSprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor.x; + + if (tempPoint.x > x1 && tempPoint.x < x1 + width) { + var y1 = -height * this.anchor.y; + + if (tempPoint.y > y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this tiling sprite + * + */ + + + TilingSprite.prototype.destroy = function destroy() { + _core$Sprite.prototype.destroy.call(this); + + this.tileScale = null; + this._tileScaleOffset = null; + this.tilePosition = null; + + this._uvs = null; + }; + + /** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.Texture} The newly created texture + */ + + + TilingSprite.from = function from(source, width, height) { + return new TilingSprite(core.Texture.from(source), width, height); + }; + + /** + * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId + */ + + + TilingSprite.fromFrame = function fromFrame(frameId, width, height) { + var texture = core.utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this); + } + + return new TilingSprite(texture, width, height); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @param {boolean} [crossorigin] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.SCALE_MODES.DEFAULT] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id + */ + + + TilingSprite.fromImage = function fromImage(imageId, width, height, crossorigin, scaleMode) { + return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode), width, height); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.extras.TilingSprite# + */ + + + _createClass(TilingSprite, [{ + key: 'clampEdge', + set: function set(value) { + this.uvTransform.clampEdge = value; + this.uvTransform.update(true); + } + + /** + * The scaling of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + + }, { + key: 'tileScale', + get: function get() { + return this.tileTransform.scale; + } + + /** + * Copies the point to the scale of the tiled image. + * + * @param {PIXI.Point|PIXI.ObservablePoint} value - The value to set to. + */ + , + set: function set(value) { + this.tileTransform.scale.copy(value); + } + + /** + * The offset of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + * @memberof PIXI.TilingSprite# + */ + + }, { + key: 'tilePosition', + get: function get() { + return this.tileTransform.position; + } + + /** + * Copies the point to the position of the tiled image. + * + * @param {PIXI.Point|PIXI.ObservablePoint} value - The value to set to. + */ + , + set: function set(value) { + this.tileTransform.position.copy(value); + } + }, { + key: 'width', + get: function get() { + return this._width; + } + + /** + * Sets the width. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this._width = value; + } + + /** + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.extras.TilingSprite# + */ + + }, { + key: 'height', + get: function get() { + return this._height; + } + + /** + * Sets the width. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this._height = value; + } + }]); + + return TilingSprite; +}(core.Sprite); + +exports.default = TilingSprite; + +},{"../core":97,"../core/sprites/canvas/CanvasTinter":135}],162:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DisplayObject = core.DisplayObject; +var _tempMatrix = new core.Matrix(); + +DisplayObject.prototype._cacheAsBitmap = false; +DisplayObject.prototype._cacheData = false; + +// figured theres no point adding ALL the extra variables to prototype. +// this model can hold the information needed. This can also be generated on demand as +// most objects are not cached as bitmaps. +/** + * @class + * @ignore + */ + +var CacheData = +/** + * + */ +function CacheData() { + _classCallCheck(this, CacheData); + + this.originalRenderWebGL = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + + this.originalUpdateTransform = null; + this.originalHitTest = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.sprite = null; +}; + +Object.defineProperties(DisplayObject.prototype, { + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to 'false' + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function get() { + return this._cacheAsBitmap; + }, + set: function set(value) { + if (this._cacheAsBitmap === value) { + return; + } + + this._cacheAsBitmap = value; + + var data = void 0; + + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + + data = this._cacheData; + + data.originalRenderWebGL = this.renderWebGL; + data.originalRenderCanvas = this.renderCanvas; + + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this._calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + + data.originalDestroy = this.destroy; + + data.originalContainsPoint = this.containsPoint; + + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + + this.renderWebGL = this._renderCachedWebGL; + this.renderCanvas = this._renderCachedCanvas; + + this.destroy = this._cacheAsBitmapDestroy; + } else { + data = this._cacheData; + + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + + this.renderWebGL = data.originalRenderWebGL; + this.renderCanvas = data.originalRenderCanvas; + this._calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + + this.destroy = data.originalDestroy; + + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + } + } +}); + +/** + * Renders a cached version of the sprite with WebGL + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedWebGL = function _renderCachedWebGL(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObject(renderer); + + this._cacheData.sprite._transformID = -1; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderWebGL(renderer); +}; + +/** + * Prepares the WebGL renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + + this.alpha = 1; + + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.currentRenderer.flush(); + // this.filters= []; + + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds().clone(); + + // add some padding! + if (this._filters) { + var padding = this._filters[0].padding; + + bounds.pad(padding); + } + + // for now we cache the current renderTarget that the webGL renderer is currently using. + // this could be more elegent.. + var cachedRenderTarget = renderer._activeRenderTarget; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + var stack = renderer.filterManager.filterStack; + + // this renderTexture will be used to store the cached DisplayObject + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + // need to set // + var m = _tempMatrix; + + m.tx = -bounds.x; + m.ty = -bounds.y; + + // reset + this.transform.worldTransform.identity(); + + // set all properties to there original so we can render to a texture + this.renderWebGL = this._cacheData.originalRenderWebGL; + + renderer.render(this, renderTexture, true, m, true); + // now restore the state be setting the new properties + + renderer.bindRenderTarget(cachedRenderTarget); + + renderer.filterManager.filterStack = stack; + + this.renderWebGL = this._renderCachedWebGL; + this.updateTransform = this.displayObjectUpdateTransform; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + + // easy bounds.. + this._calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + + this._cacheData.sprite = cachedSprite; + + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + this.updateTransform(); + + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Renders a cached version of the sprite with canvas + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObjectCanvas(renderer); + + this._cacheData.sprite.worldAlpha = this.worldAlpha; + + this._cacheData.sprite.renderCanvas(renderer); +}; + +// TODO this can be the same as the webGL verison.. will need to do a little tweaking first though.. +/** + * Prepares the Canvas renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(); + + var cacheAlpha = this.alpha; + + this.alpha = 1; + + var cachedRenderTarget = renderer.context; + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + // need to set // + var m = _tempMatrix; + + this.transform.worldTransform.copy(m); + m.invert(); + + m.tx -= bounds.x; + m.ty -= bounds.y; + + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + + // renderTexture.render(this, m, true); + renderer.render(this, renderTexture, true, m, false); + + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + + this.renderCanvas = this._renderCachedCanvas; + this._calculateBounds = this._calculateCachedBounds; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite._bounds = this._bounds; + cachedSprite.alpha = cacheAlpha; + + this.updateTransform(); + this.updateTransform = this.displayObjectUpdateTransform; + + this._cacheData.sprite = cachedSprite; + + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Calculates the bounds of the cached sprite + * + * @private + */ +DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._cacheData.sprite._calculateBounds(); +}; + +/** + * Gets the bounds of the cached sprite. + * + * @private + * @return {Rectangle} The local bounds. + */ +DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(); +}; + +/** + * Destroys the cached sprite. + * + * @private + */ +DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; +}; + +/** + * Destroys the cached object. + * + * @private + */ +DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy() { + this.cacheAsBitmap = false; + this.destroy(); +}; + +},{"../core":97}],163:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * The instance name of the object. + * + * @memberof PIXI.DisplayObject# + * @member {string} + */ +core.DisplayObject.prototype.name = null; + +/** + * Returns the display object in the container + * + * @memberof PIXI.Container# + * @param {string} name - instance name + * @return {PIXI.DisplayObject} The child with the specified name. + */ +core.Container.prototype.getChildByName = function getChildByName(name) { + for (var i = 0; i < this.children.length; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + + return null; +}; + +},{"../core":97}],164:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Returns the global position of the displayObject + * + * @memberof PIXI.DisplayObject# + * @param {Point} point - the point to write the global value to. If null a new point will be returned + * @return {Point} The updated point + */ +core.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition() { + var point = arguments.length <= 0 || arguments[0] === undefined ? new core.Point() : arguments[0]; + + if (this.parent) { + this.displayObjectUpdateTransform(); + + point.x = this.worldTransform.tx; + point.y = this.worldTransform.ty; + } else { + point.x = this.position.x; + point.y = this.position.y; + } + + return point; +}; + +},{"../core":97}],165:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _MovieClip = require('./MovieClip'); + +Object.defineProperty(exports, 'MovieClip', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_MovieClip).default; + } +}); + +var _TilingSprite = require('./TilingSprite'); + +Object.defineProperty(exports, 'TilingSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSprite).default; + } +}); + +var _TilingRenderer = require('./webgl/TilingRenderer'); + +Object.defineProperty(exports, 'TilingRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingRenderer).default; + } +}); + +var _BitmapText = require('./BitmapText'); + +Object.defineProperty(exports, 'BitmapText', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BitmapText).default; + } +}); + +var _cacheAsBitmap = require('./cacheAsBitmap'); + +Object.defineProperty(exports, 'cacheAsBitmap', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_cacheAsBitmap).default; + } +}); + +var _getChildByName = require('./getChildByName'); + +Object.defineProperty(exports, 'getChildByName', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_getChildByName).default; + } +}); + +var _getGlobalPosition = require('./getGlobalPosition'); + +Object.defineProperty(exports, 'getGlobalPosition', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_getGlobalPosition).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./BitmapText":159,"./MovieClip":160,"./TilingSprite":161,"./cacheAsBitmap":162,"./getChildByName":163,"./getGlobalPosition":164,"./webgl/TilingRenderer":166}],166:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.TilingRenderer = undefined; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _const = require('../../core/const'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + + // eslint-disable-line no-undef + +var tempMat = new core.Matrix(); +var tempArray = new Float32Array(4); + +/** + * WebGL renderer plugin for tiling sprites + */ + +var TilingRenderer = exports.TilingRenderer = function (_core$ObjectRenderer) { + _inherits(TilingRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function TilingRenderer(renderer) { + _classCallCheck(this, TilingRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + _this.simpleShader = null; + _this.quad = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + TilingRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n", "#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n gl_FragColor = sample * color ;\n}\n"); + this.simpleShader = new core.Shader(gl, "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n", "#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n gl_FragColor = sample * color;\n}\n"); + + this.quad = new core.Quad(gl); + this.quad.initVao(this.shader); + }; + + /** + * + * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered + */ + + + TilingRenderer.prototype.render = function render(ts) { + var quad = this.quad; + var vertices = quad.vertices; + + vertices[0] = vertices[6] = ts._width * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + + vertices[2] = vertices[4] = ts._width * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + + vertices = quad.uvs; + + vertices[0] = vertices[6] = -ts.anchor.x; + vertices[1] = vertices[3] = -ts.anchor.y; + + vertices[2] = vertices[4] = 1.0 - ts.anchor.x; + vertices[5] = vertices[7] = 1.0 - ts.anchor.y; + + quad.upload(); + + var renderer = this.renderer; + var tex = ts._texture; + var baseTex = tex.baseTexture; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvTransform; + var isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === _const.WRAP_MODES.CLAMP) { + baseTex.wrapMode = _const.WRAP_MODES.REPEAT; + } + } else { + isSimple = baseTex.wrapMode !== _const.WRAP_MODES.CLAMP; + } + } + + var shader = isSimple ? this.simpleShader : this.shader; + + renderer.bindShader(shader); + + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + + tempMat.invert(); + if (isSimple) { + tempMat.append(uv.mapCoord); + } else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.clampFrame; + shader.uniforms.uClampOffset = uv.clampOffset; + } + shader.uniforms.uTransform = tempMat.toArray(true); + + var color = tempArray; + + core.utils.hex2rgb(ts.tint, color); + color[3] = ts.worldAlpha; + shader.uniforms.uColor = color; + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + + renderer.bindTexture(tex); + renderer.setBlendMode(ts.blendMode); + + quad.draw(); + }; + + return TilingRenderer; +}(core.ObjectRenderer); + +core.WebGLRenderer.registerPlugin('tiling', TilingRenderer); + +},{"../../core":97,"../../core/const":78}],167:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BlurXFilter = require('./BlurXFilter'); + +var _BlurXFilter2 = _interopRequireDefault(_BlurXFilter); + +var _BlurYFilter = require('./BlurYFilter'); + +var _BlurYFilter2 = _interopRequireDefault(_BlurYFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurFilter applies a Gaussian blur to an object. + * The strength of the blur can be set for x- and y-axis separately. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurFilter = function (_core$Filter) { + _inherits(BlurFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The reoslution of the blur filter. + */ + function BlurFilter(strength, quality, resolution) { + _classCallCheck(this, BlurFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this)); + + _this.blurXFilter = new _BlurXFilter2.default(); + _this.blurYFilter = new _BlurYFilter2.default(); + _this.resolution = 1; + + _this.padding = 0; + _this.resolution = resolution || 1; + _this.quality = quality || 4; + _this.blur = strength || 8; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + BlurFilter.prototype.apply = function apply(filterManager, input, output) { + var renderTarget = filterManager.getRenderTarget(true); + + this.blurXFilter.apply(filterManager, input, renderTarget, true); + this.blurYFilter.apply(filterManager, renderTarget, output, false); + + filterManager.returnRenderTarget(renderTarget); + }; + + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * + * @member {number} + * @memberOf PIXI.filters.BlurFilter# + * @default 2 + */ + + + _createClass(BlurFilter, [{ + key: 'blur', + get: function get() { + return this.blurXFilter.blur; + } + + /** + * Sets the strength of the blur. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurYFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the number of passes for blur. More passes means higher quaility bluring. + * + * @member {number} + * @memberof PIXI.filters.BlurYFilter# + * @default 1 + */ + + }, { + key: 'quality', + get: function get() { + return this.blurXFilter.quality; + } + + /** + * Sets the quality of the blur. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this.blurXFilter.quality = this.blurYFilter.quality = value; + } + + /** + * Sets the strength of the blurX property + * + * @member {number} + * @memberOf PIXI.filters.BlurFilter# + * @default 2 + */ + + }, { + key: 'blurX', + get: function get() { + return this.blurXFilter.blur; + } + + /** + * Sets the strength of the blurX. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this.blurXFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurYFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the strength of the blurY property + * + * @member {number} + * @memberOf PIXI.filters.BlurFilter# + * @default 2 + */ + + }, { + key: 'blurY', + get: function get() { + return this.blurYFilter.blur; + } + + /** + * Sets the strength of the blurY. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurYFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + }]); + + return BlurFilter; +}(core.Filter); + +exports.default = BlurFilter; + +},{"../../core":97,"./BlurXFilter":168,"./BlurYFilter":169}],168:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurXFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurXFilter = function (_core$Filter) { + _inherits(BlurXFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The reoslution of the blur filter. + */ + function BlurXFilter(strength, quality, resolution) { + _classCallCheck(this, BlurXFilter); + + var vertSrc = (0, _generateBlurVertSource2.default)(5, true); + var fragSrc = (0, _generateBlurFragSource2.default)(5); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || 1; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurXFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.width * (output.size.width / input.size.width); + + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; // / this.passes//Math.pow(1, this.passes); + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @memberof PIXI.filters.BlurXFilter# + * @default 16 + */ + + + _createClass(BlurXFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + } + + /** + * Sets the strength of the blur. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @memberof PIXI.filters.BlurXFilter# + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + } + + /** + * Sets the quality of the blur. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this._quality = value; + this.passes = value; + } + }]); + + return BlurXFilter; +}(core.Filter); + +exports.default = BlurXFilter; + +},{"../../core":97,"./generateBlurFragSource":170,"./generateBlurVertSource":171,"./getMaxBlurKernelSize":172}],169:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurYFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurYFilter = function (_core$Filter) { + _inherits(BlurYFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The reoslution of the blur filter. + */ + function BlurYFilter(strength, quality, resolution) { + _classCallCheck(this, BlurYFilter); + + var vertSrc = (0, _generateBlurVertSource2.default)(5, false); + var fragSrc = (0, _generateBlurFragSource2.default)(5); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || 1; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurYFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.height * (output.size.height / input.size.height); + + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @memberof PIXI.filters.BlurYFilter# + * @default 2 + */ + + + _createClass(BlurYFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + } + + /** + * Sets the strength of the blur. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @memberof PIXI.filters.BlurXFilter# + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + } + + /** + * Sets the quality of the blur. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this._quality = value; + this.passes = value; + } + }]); + + return BlurYFilter; +}(core.Filter); + +exports.default = BlurYFilter; + +},{"../../core":97,"./generateBlurFragSource":170,"./generateBlurVertSource":171,"./getMaxBlurKernelSize":172}],170:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateFragBlurSource; +var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] +}; + +var fragTemplate = ['varying vec2 vBlurTexCoords[%size%];', 'uniform sampler2D uSampler;', 'void main(void)', '{', ' gl_FragColor = vec4(0.0);', ' %blur%', '}'].join('\n'); + +function generateFragBlurSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + + var fragSource = fragTemplate; + + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value = void 0; + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + value = i; + + if (i >= halfLength) { + value = kernelSize - i - 1; + } + + blur = blur.replace('%value%', kernel[value]); + + blurLoop += blur; + blurLoop += '\n'; + } + + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize); + + return fragSource; +} + +},{}],171:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateVertBlurSource; +var vertTemplate = ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform float strength;', 'uniform mat3 projectionMatrix;', 'varying vec2 vBlurTexCoords[%size%];', 'void main(void)', '{', 'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);', '%blur%', '}'].join('\n'); + +function generateVertBlurSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + + var vertSource = vertTemplate; + + var blurLoop = ''; + var template = void 0; + // let value; + + if (x) { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } else { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + // value = i; + + // if(i >= halfLength) + // { + // value = kernelSize - i - 1; + // } + + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + '.0'); + + blurLoop += blur; + blurLoop += '\n'; + } + + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize); + + return vertSource; +} + +},{}],172:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = getMaxKernelSize; +function getMaxKernelSize(gl) { + var maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + var kernelSize = 15; + + while (kernelSize > maxVaryings) { + kernelSize -= 2; + } + + return kernelSize; +} + +},{}],173:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + + // eslint-disable-line no-undef + +/** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ + +var ColorMatrixFilter = function (_core$Filter) { + _inherits(ColorMatrixFilter, _core$Filter); + + /** + * + */ + function ColorMatrixFilter() { + _classCallCheck(this, ColorMatrixFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}", + // fragment shader + "#define GLSLIFY 1\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\n\nvoid main(void)\n{\n\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n gl_FragColor.r = (m[0] * c.r);\n gl_FragColor.r += (m[1] * c.g);\n gl_FragColor.r += (m[2] * c.b);\n gl_FragColor.r += (m[3] * c.a);\n gl_FragColor.r += m[4] * c.a;\n\n gl_FragColor.g = (m[5] * c.r);\n gl_FragColor.g += (m[6] * c.g);\n gl_FragColor.g += (m[7] * c.b);\n gl_FragColor.g += (m[8] * c.a);\n gl_FragColor.g += m[9] * c.a;\n\n gl_FragColor.b = (m[10] * c.r);\n gl_FragColor.b += (m[11] * c.g);\n gl_FragColor.b += (m[12] * c.b);\n gl_FragColor.b += (m[13] * c.a);\n gl_FragColor.b += m[14] * c.a;\n\n gl_FragColor.a = (m[15] * c.r);\n gl_FragColor.a += (m[16] * c.g);\n gl_FragColor.a += (m[17] * c.b);\n gl_FragColor.a += (m[18] * c.a);\n gl_FragColor.a += m[19] * c.a;\n\n// gl_FragColor = vec4(m[0]);\n}\n")); + + _this.uniforms.m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + return _this; + } + + /** + * Transforms current matrix and set the new one + * + * @param {number[]} matrix - 5x4 matrix + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix(matrix) { + var multiply = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + + var newMatrix = matrix; + + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + + // set the new matrix + this.uniforms.m = newMatrix; + }; + + /** + * Multiplies two mat5's + * + * @private + * @param {number[]} out - 5x4 matrix the receiving matrix + * @param {number[]} a - 5x4 matrix the first operand + * @param {number[]} b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix + */ + + + ColorMatrixFilter.prototype._multiply = function _multiply(out, a, b) { + // Red Channel + out[0] = a[0] * b[0] + a[1] * b[5] + a[2] * b[10] + a[3] * b[15]; + out[1] = a[0] * b[1] + a[1] * b[6] + a[2] * b[11] + a[3] * b[16]; + out[2] = a[0] * b[2] + a[1] * b[7] + a[2] * b[12] + a[3] * b[17]; + out[3] = a[0] * b[3] + a[1] * b[8] + a[2] * b[13] + a[3] * b[18]; + out[4] = a[0] * b[4] + a[1] * b[9] + a[2] * b[14] + a[3] * b[19]; + + // Green Channel + out[5] = a[5] * b[0] + a[6] * b[5] + a[7] * b[10] + a[8] * b[15]; + out[6] = a[5] * b[1] + a[6] * b[6] + a[7] * b[11] + a[8] * b[16]; + out[7] = a[5] * b[2] + a[6] * b[7] + a[7] * b[12] + a[8] * b[17]; + out[8] = a[5] * b[3] + a[6] * b[8] + a[7] * b[13] + a[8] * b[18]; + out[9] = a[5] * b[4] + a[6] * b[9] + a[7] * b[14] + a[8] * b[19]; + + // Blue Channel + out[10] = a[10] * b[0] + a[11] * b[5] + a[12] * b[10] + a[13] * b[15]; + out[11] = a[10] * b[1] + a[11] * b[6] + a[12] * b[11] + a[13] * b[16]; + out[12] = a[10] * b[2] + a[11] * b[7] + a[12] * b[12] + a[13] * b[17]; + out[13] = a[10] * b[3] + a[11] * b[8] + a[12] * b[13] + a[13] * b[18]; + out[14] = a[10] * b[4] + a[11] * b[9] + a[12] * b[14] + a[13] * b[19]; + + // Alpha Channel + out[15] = a[15] * b[0] + a[16] * b[5] + a[17] * b[10] + a[18] * b[15]; + out[16] = a[15] * b[1] + a[16] * b[6] + a[17] * b[11] + a[18] * b[16]; + out[17] = a[15] * b[2] + a[16] * b[7] + a[17] * b[12] + a[18] * b[17]; + out[18] = a[15] * b[3] + a[16] * b[8] + a[17] * b[13] + a[18] * b[18]; + out[19] = a[15] * b[4] + a[16] * b[9] + a[17] * b[14] + a[18] * b[19]; + + return out; + }; + + /** + * Create a Float32 Array and normalize the offset component to 0-1 + * + * @private + * @param {number[]} matrix - 5x4 matrix + * @return {number[]} 5x4 matrix with all values between 0-1 + */ + + + ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix(matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + + return m; + }; + + /** + * Adjusts brightness + * + * @param {number} b - value of the brigthness (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.brightness = function brightness(b, multiply) { + var matrix = [b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the matrices in grey scales + * + * @param {number} scale - value of the grey (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.greyscale = function greyscale(scale, multiply) { + var matrix = [scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the black and white matrice. + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite(multiply) { + var matrix = [0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the hue property of the color + * + * @param {number} rotation - in degrees + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.hue = function hue(rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + + var a00 = cosR + (1.0 - cosR) * w; + var a01 = w * (1.0 - cosR) - sqrW * sinR; + var a02 = w * (1.0 - cosR) + sqrW * sinR; + + var a10 = w * (1.0 - cosR) + sqrW * sinR; + var a11 = cosR + w * (1.0 - cosR); + var a12 = w * (1.0 - cosR) - sqrW * sinR; + + var a20 = w * (1.0 - cosR) - sqrW * sinR; + var a21 = w * (1.0 - cosR) + sqrW * sinR; + var a22 = cosR + w * (1.0 - cosR); + + var matrix = [a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * + * @param {number} amount - value of the contrast (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.contrast = function contrast(amount, multiply) { + var v = (amount || 0) + 1; + var o = -128 * (v - 1); + + var matrix = [v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * + * @param {number} amount - The saturation amount (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.saturate = function saturate() { + var amount = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; + var multiply = arguments[1]; + + var x = amount * 2 / 3 + 1; + var y = (x - 1) * -0.5; + + var matrix = [x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Desaturate image (remove color) + * + * Call the saturate function + * + */ + + + ColorMatrixFilter.prototype.desaturate = function desaturate() // eslint-disable-line no-unused-vars + { + this.saturate(-1); + }; + + /** + * Negative image (inverse of classic rgb matrix) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.negative = function negative(multiply) { + var matrix = [0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Sepia image + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.sepia = function sepia(multiply) { + var matrix = [0.393, 0.7689999, 0.18899999, 0, 0, 0.349, 0.6859999, 0.16799999, 0, 0, 0.272, 0.5339999, 0.13099999, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.technicolor = function technicolor(multiply) { + var matrix = [1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Polaroid filter + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.polaroid = function polaroid(multiply) { + var matrix = [1.438, -0.062, -0.062, 0, 0, -0.122, 1.378, -0.122, 0, 0, -0.016, -0.016, 1.483, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Filter who transforms : Red -> Blue and Blue -> Red + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.toBGR = function toBGR(multiply) { + var matrix = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.kodachrome = function kodachrome(multiply) { + var matrix = [1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Brown delicious browni filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.browni = function browni(multiply) { + var matrix = [0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Vintage filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.vintage = function vintage(multiply) { + var matrix = [0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * + * @param {number} desaturation - Tone values. + * @param {number} toned - Tone values. + * @param {string} lightColor - Tone values, example: `0xFFE580` + * @param {string} darkColor - Tone values, example: `0xFFE580` + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.colorTone = function colorTone(desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + + var lR = (lightColor >> 16 & 0xFF) / 255; + var lG = (lightColor >> 8 & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + + var dR = (darkColor >> 16 & 0xFF) / 255; + var dG = (darkColor >> 8 & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + + var matrix = [0.3, 0.59, 0.11, 0, 0, lR, lG, lB, desaturation, 0, dR, dG, dB, toned, 0, lR - dR, lG - dG, lB - dB, 0, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Night effect + * + * @param {number} intensity - The intensity of the night effect. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.night = function night(intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [intensity * -2.0, -intensity, 0, 0, 0, -intensity, 0, intensity, 0, 0, 0, intensity, intensity * 2.0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * + * @param {number} amount - how much the predator feels his future victim + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.predator = function predator(amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * LSD effect + * + * Multiply the current matrix + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.lsd = function lsd(multiply) { + var matrix = [2, -0.4, 0.5, 0, 0, -0.5, 2, -0.4, 0, 0, -0.4, -0.5, 3, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Erase the current matrix by setting the default one + * + */ + + + ColorMatrixFilter.prototype.reset = function reset() { + var matrix = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, false); + }; + + /** + * The matrix of the color matrix filter + * + * @member {number[]} + * @memberof PIXI.filters.ColorMatrixFilter# + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + + + _createClass(ColorMatrixFilter, [{ + key: 'matrix', + get: function get() { + return this.uniforms.m; + } + + /** + * Sets the matrix directly. + * + * @param {number[]} value - the value to set to. + */ + , + set: function set(value) { + this.uniforms.m = value; + } + }]); + + return ColorMatrixFilter; +}(core.Filter); + +// Americanized alias + + +exports.default = ColorMatrixFilter; +ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + +},{"../../core":97}],174:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + + // eslint-disable-line no-undef + +/** + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. You can + * use this filter to apply all manor of crazy warping effects. Currently the r + * property of the texture is used to offset the x and the g property of the texture + * is used to offset the y. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ + +var DisplacementFilter = function (_core$Filter) { + _inherits(DisplacementFilter, _core$Filter); + + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param {number} scale - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + _classCallCheck(this, DisplacementFilter); + + var maskMatrix = new core.Matrix(); + + sprite.renderable = false; + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}", + // fragment shader + "#define GLSLIFY 1\nvarying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n")); + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + + _this.uniforms.mapSampler = sprite.texture; + _this.uniforms.filterMatrix = maskMatrix.toArray(true); + _this.uniforms.scale = { x: 1, y: 1 }; + + if (scale === null || scale === undefined) { + scale = 20; + } + + _this.scale = new core.Point(scale, scale); + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + DisplacementFilter.prototype.apply = function apply(filterManager, input, output) { + var ratio = 1 / output.destinationFrame.width * (output.size.width / input.size.width); + + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x * ratio; + this.uniforms.scale.y = this.scale.y * ratio; + + // draw the filter... + filterManager.applyFilter(this, input, output); + }; + + /** + * The texture used for the displacement map. Must be power of 2 sized texture. + * + * @member {PIXI.Texture} + * @memberof PIXI.filters.DisplacementFilter# + */ + + + _createClass(DisplacementFilter, [{ + key: 'map', + get: function get() { + return this.uniforms.mapSampler; + } + + /** + * Sets the texture to use for the displacement. + * + * @param {PIXI.Texture} value - The texture to set to. + */ + , + set: function set(value) { + this.uniforms.mapSampler = value; + } + }]); + + return DisplacementFilter; +}(core.Filter); + +exports.default = DisplacementFilter; + +},{"../../core":97}],175:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + + // eslint-disable-line no-undef + +/** + * + * Basic FXAA implementation based on the code on geeks3d.com with the + * modification that the texture2DLod stuff was removed since it's + * unsupported by WebGL. + * + * @see https://github.com/mitsuhiko/webgl-meincraft + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + * + */ + +var FXAAFilter = function (_core$Filter) { + _inherits(FXAAFilter, _core$Filter); + + /** + * + */ + function FXAAFilter() { + _classCallCheck(this, FXAAFilter); + + // TODO - needs work + return _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}", + // fragment shader + "#define GLSLIFY 1\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it's\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n")); + } + + return FXAAFilter; +}(core.Filter); + +exports.default = FXAAFilter; + +},{"../../core":97}],176:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _FXAAFilter = require('./fxaa/FXAAFilter'); + +Object.defineProperty(exports, 'FXAAFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_FXAAFilter).default; + } +}); + +var _NoiseFilter = require('./noise/NoiseFilter'); + +Object.defineProperty(exports, 'NoiseFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NoiseFilter).default; + } +}); + +var _DisplacementFilter = require('./displacement/DisplacementFilter'); + +Object.defineProperty(exports, 'DisplacementFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplacementFilter).default; + } +}); + +var _BlurFilter = require('./blur/BlurFilter'); + +Object.defineProperty(exports, 'BlurFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurFilter).default; + } +}); + +var _BlurXFilter = require('./blur/BlurXFilter'); + +Object.defineProperty(exports, 'BlurXFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurXFilter).default; + } +}); + +var _BlurYFilter = require('./blur/BlurYFilter'); + +Object.defineProperty(exports, 'BlurYFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurYFilter).default; + } +}); + +var _ColorMatrixFilter = require('./colormatrix/ColorMatrixFilter'); + +Object.defineProperty(exports, 'ColorMatrixFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ColorMatrixFilter).default; + } +}); + +var _VoidFilter = require('./void/VoidFilter'); + +Object.defineProperty(exports, 'VoidFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VoidFilter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./blur/BlurFilter":167,"./blur/BlurXFilter":168,"./blur/BlurYFilter":169,"./colormatrix/ColorMatrixFilter":173,"./displacement/DisplacementFilter":174,"./fxaa/FXAAFilter":175,"./noise/NoiseFilter":177,"./void/VoidFilter":178}],177:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + + // eslint-disable-line no-undef + +/** + * @author Vico @vicocotea + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + */ + +/** + * A Noise effect filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ + +var NoiseFilter = function (_core$Filter) { + _inherits(NoiseFilter, _core$Filter); + + /** + * + */ + function NoiseFilter() { + _classCallCheck(this, NoiseFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}", + // fragment shader + "precision highp float;\n#define GLSLIFY 1\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float noise;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n float diff = (rand(gl_FragCoord.xy) - 0.5) * noise;\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n gl_FragColor = color;\n}\n")); + + _this.noise = 0.5; + return _this; + } + + /** + * The amount of noise to apply. + * + * @member {number} + * @memberof PIXI.filters.NoiseFilter# + * @default 0.5 + */ + + + _createClass(NoiseFilter, [{ + key: 'noise', + get: function get() { + return this.uniforms.noise; + } + + /** + * Sets the amount of noise to apply. + * + * @param {number} value - The value to set to. + */ + , + set: function set(value) { + this.uniforms.noise = value; + } + }]); + + return NoiseFilter; +}(core.Filter); + +exports.default = NoiseFilter; + +},{"../../core":97}],178:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// @see https://github.com/substack/brfs/issues/25 + // eslint-disable-line no-undef + +/** + * Does nothing. Very handy. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ + +var VoidFilter = function (_core$Filter) { + _inherits(VoidFilter, _core$Filter); + + /** + * + */ + function VoidFilter() { + _classCallCheck(this, VoidFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}", + // fragment shader + "#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n")); + + _this.glShaderKey = 'void'; + return _this; + } + + return VoidFilter; +}(core.Filter); + +exports.default = VoidFilter; + +},{"../../core":97}],179:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Holds all information related to an Interaction event + * + * @class + * @memberof PIXI.interaction + */ +var InteractionData = function () { + /** + * + */ + function InteractionData() { + _classCallCheck(this, InteractionData); + + /** + * This point stores the global coords of where the touch/mouse event happened + * + * @member {PIXI.Point} + */ + this.global = new core.Point(); + + /** + * The target Sprite that was interacted with + * + * @member {PIXI.Sprite} + */ + this.target = null; + + /** + * When passed to an event handler, this will be the original DOM Event that was captured + * + * @member {Event} + */ + this.originalEvent = null; + } + + /** + * This will return the local coordinates of the specified displayObject for this InteractionData + * + * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local + * coords off + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative + * to the DisplayObject + */ + + + InteractionData.prototype.getLocalPosition = function getLocalPosition(displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + + return InteractionData; +}(); + +exports.default = InteractionData; + +},{"../core":97}],180:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Event class that mimics native DOM events. + * + * @class + * @memberof PIXI.interaction + */ +var InteractionEvent = function () { + /** + * + */ + function InteractionEvent() { + _classCallCheck(this, InteractionEvent); + + /** + * Which this event will continue propagating in the tree + * + * @member {boolean} + */ + this.stopped = false; + + /** + * The object to which event is dispatched. + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * The object whose event listener’s callback is currently being invoked. + * + * @member {PIXI.DisplayObject} + */ + this.currentTarget = null; + + /* + * Type of the event + * + * @member {string} + */ + this.type = null; + + /* + * InteractionData related to this event + * + * @member {PIXI.interaction.InteractionData} + */ + this.data = null; + } + + /** + * Prevents event from reaching any objects other than the current object. + * + */ + + + InteractionEvent.prototype.stopPropagation = function stopPropagation() { + this.stopped = true; + }; + + /** + * Prevents event from reaching any objects other than the current object. + * + * @private + */ + + + InteractionEvent.prototype._reset = function _reset() { + this.stopped = false; + this.currentTarget = null; + this.target = null; + }; + + return InteractionEvent; +}(); + +exports.default = InteractionEvent; + +},{}],181:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _InteractionData = require('./InteractionData'); + +var _InteractionData2 = _interopRequireDefault(_InteractionData); + +var _InteractionEvent = require('./InteractionEvent'); + +var _InteractionEvent2 = _interopRequireDefault(_InteractionEvent); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _interactiveTarget = require('./interactiveTarget'); + +var _interactiveTarget2 = _interopRequireDefault(_interactiveTarget); + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// Mix interactiveTarget into core.DisplayObject.prototype +Object.assign(core.DisplayObject.prototype, _interactiveTarget2.default); + +/** + * The interaction manager deals with mouse and touch events. Any DisplayObject can be interactive + * if its interactive parameter is set to true + * This manager also supports multitouch. + * + * @class + * @extends EventEmitter + * @memberof PIXI.interaction + */ + +var InteractionManager = function (_EventEmitter) { + _inherits(InteractionManager, _EventEmitter); + + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + * @param {object} [options] - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Frequency increases the interaction events will be checked. + */ + function InteractionManager(renderer, options) { + _classCallCheck(this, InteractionManager); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + options = options || {}; + + /** + * The renderer this interaction manager works for. + * + * @member {PIXI.SystemRenderer} + */ + _this.renderer = renderer; + + /** + * Should default browser actions automatically be prevented. + * + * @member {boolean} + * @default true + */ + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + + /** + * As this frequency increases the interaction events will be checked more often. + * + * @member {number} + * @default 10 + */ + _this.interactionFrequency = options.interactionFrequency || 10; + + /** + * The mouse data + * + * @member {PIXI.interaction.InteractionData} + */ + _this.mouse = new _InteractionData2.default(); + + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + + /** + * The pointer data + * + * @member {PIXI.interaction.InteractionData} + */ + _this.pointer = new _InteractionData2.default(); + + // setting the pointer to start off far off screen will mean that pointer over does + // not get called before we even move the pointer. + _this.pointer.global.set(-999999); + + /** + * An event data object to handle all the event tracking/dispatching + * + * @member {object} + */ + _this.eventData = new _InteractionEvent2.default(); + + /** + * Tiny little interactiveData pool ! + * + * @member {PIXI.interaction.InteractionData[]} + */ + _this.interactiveDataPool = []; + + /** + * The DOM element to bind to. + * + * @private + * @member {HTMLElement} + */ + _this.interactionDOMElement = null; + + /** + * This property determins if mousemove and touchmove events are fired only when the cursror + * is over the object. + * Setting to true will make things work more in line with how the DOM verison works. + * Setting to false can make things easier for things like dragging + * It is currently set to false as this is how pixi used to work. This will be set to true in + * future versions of pixi. + * + * @private + * @member {boolean} + */ + _this.moveWhenInside = false; + + /** + * Have events been attached to the dom element? + * + * @private + * @member {boolean} + */ + _this.eventsAdded = false; + + /** + * Is the mouse hovering over the renderer? + * + * @private + * @member {boolean} + */ + _this.mouseOverRenderer = false; + + /** + * Does the device support touch events + * https://www.w3.org/TR/touch-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsTouchEvents = 'ontouchstart' in window; + + /** + * Does the device support pointer events + * https://www.w3.org/Submission/pointer-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsPointerEvents = !!window.PointerEvent; + + /** + * Are touch events being 'normalized' and converted into pointer events if pointer events are not supported + * For example, on a touch screen mobile device, a touchstart would also be emitted as a pointerdown + * + * @private + * @readonly + * @member {boolean} + */ + _this.normalizingTouchEvents = !_this.supportsPointerEvents && _this.supportsTouchEvents; + + /** + * Are mouse events being 'normalized' and converted into pointer events if pointer events are not supported + * For example, on a desktop pc, a mousedown would also be emitted as a pointerdown + * + * @private + * @readonly + * @member {boolean} + */ + _this.normalizingMouseEvents = !_this.supportsPointerEvents && !_ismobilejs2.default.any; + + // this will make it so that you don't have to call bind all the time + + /** + * @private + * @member {Function} + */ + _this.onMouseUp = _this.onMouseUp.bind(_this); + _this.processMouseUp = _this.processMouseUp.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onMouseDown = _this.onMouseDown.bind(_this); + _this.processMouseDown = _this.processMouseDown.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onMouseMove = _this.onMouseMove.bind(_this); + _this.processMouseMove = _this.processMouseMove.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onMouseOut = _this.onMouseOut.bind(_this); + _this.processMouseOverOut = _this.processMouseOverOut.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onMouseOver = _this.onMouseOver.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOver = _this.onPointerOver.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onTouchStart = _this.onTouchStart.bind(_this); + _this.processTouchStart = _this.processTouchStart.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onTouchEnd = _this.onTouchEnd.bind(_this); + _this.processTouchEnd = _this.processTouchEnd.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onTouchMove = _this.onTouchMove.bind(_this); + _this.processTouchMove = _this.processTouchMove.bind(_this); + + /** + * Every update cursor will be reset to this value, if some element wont override it in + * its hitTest. + * + * @member {string} + * @default 'inherit' + */ + _this.defaultCursorStyle = 'inherit'; + + /** + * The css style of the cursor that is being used. + * + * @member {string} + */ + _this.currentCursorStyle = 'inherit'; + + /** + * Internal cached let. + * + * @private + * @member {PIXI.Point} + */ + _this._tempPoint = new core.Point(); + + /** + * The current resolution / device pixel ratio. + * + * @member {number} + * @default 1 + */ + _this.resolution = 1; + + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + + /** + * Fired when a pointer device button (usually a mouse button) is pressed on the display + * object. + * + * @event mousedown + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * + * @event rightdown + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is released over the display + * object. + * + * @event mouseup + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * + * @event rightup + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is pressed and released on + * the display object. + * + * @event click + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * + * @event rightclick + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. + * + * @event mouseupoutside + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. + * + * @event rightupoutside + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * + * @event mousemove + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * + * @event mouseover + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * + * @event mouseout + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * + * @event pointerdown + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is released over the display object. + * + * @event pointerup + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * + * @event pointertap + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}. + * + * @event pointerupoutside + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved while over the display object + * + * @event pointermove + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved onto the display object + * + * @event pointerover + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved off the display object + * + * @event pointerout + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is placed on the display object. + * + * @event touchstart + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is removed from the display object. + * + * @event touchend + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * + * @event tap + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. + * + * @event touchendoutside + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is moved along the display object. + * + * @event touchmove + * @memberof PIXI.interaction.InteractionManager# + */ + return _this; + } + + /** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate + * another DOM element to receive those events. + * + * @param {HTMLCanvasElement} element - the DOM element which will receive mouse and touch events. + * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). + * @private + */ + + + InteractionManager.prototype.setTargetElement = function setTargetElement(element) { + var resolution = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1]; + + this.removeEvents(); + + this.interactionDOMElement = element; + + this.resolution = resolution; + + this.addEvents(); + }; + + /** + * Registers all the DOM events + * + * @private + */ + + + InteractionManager.prototype.addEvents = function addEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.add(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; + this.interactionDOMElement.style['-ms-touch-action'] = 'none'; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = 'none'; + } + + window.document.addEventListener('mousemove', this.onMouseMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onMouseDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onMouseOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onMouseOver, true); + window.addEventListener('mouseup', this.onMouseUp, true); + + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onTouchStart, true); + this.interactionDOMElement.addEventListener('touchend', this.onTouchEnd, true); + this.interactionDOMElement.addEventListener('touchmove', this.onTouchMove, true); + } + + if (this.supportsPointerEvents) { + window.document.addEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('pointerout', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); + window.addEventListener('pointerup', this.onPointerUp, true); + } else { + /** + * If pointer events aren't available on a device, this will turn either the touch or + * mouse events into pointer events. This allows a developer to just listen for emitted + * pointer events on interactive sprites + */ + if (this.normalizingTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); + } + + if (this.normalizingMouseEvents) { + window.document.addEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); + window.addEventListener('mouseup', this.onPointerUp, true); + } + } + + this.eventsAdded = true; + }; + + /** + * Removes all the DOM events that were previously registered + * + * @private + */ + + + InteractionManager.prototype.removeEvents = function removeEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.remove(this.update); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = ''; + this.interactionDOMElement.style['-ms-touch-action'] = ''; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = ''; + } + + window.document.removeEventListener('mousemove', this.onMouseMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onMouseDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onMouseOut, true); + this.interactionDOMElement.removeEventListener('mouseover', this.onMouseOver, true); + window.removeEventListener('mouseup', this.onMouseUp, true); + + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onTouchStart, true); + this.interactionDOMElement.removeEventListener('touchend', this.onTouchEnd, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onTouchMove, true); + } + + if (this.supportsPointerEvents) { + window.document.removeEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('pointerout', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); + window.removeEventListener('pointerup', this.onPointerUp, true); + } else { + /** + * If pointer events aren't available on a device, this will turn either the touch or + * mouse events into pointer events. This allows a developer to just listen for emitted + * pointer events on interactive sprites + */ + if (this.normalizingTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); + } + + if (this.normalizingMouseEvents) { + window.document.removeEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); + window.removeEventListener('mouseup', this.onPointerUp, true); + } + } + + this.interactionDOMElement = null; + + this.eventsAdded = false; + }; + + /** + * Updates the state of interactive objects. + * Invoked by a throttled ticker update from {@link PIXI.ticker.shared}. + * + * @param {number} deltaTime - time delta since last tick + */ + + + InteractionManager.prototype.update = function update(deltaTime) { + this._deltaTime += deltaTime; + + if (this._deltaTime < this.interactionFrequency) { + return; + } + + this._deltaTime = 0; + + if (!this.interactionDOMElement) { + return; + } + + // if the user move the mouse this check has already been dfone using the mouse move! + if (this.didMove) { + this.didMove = false; + + return; + } + + this.cursor = this.defaultCursorStyle; + + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + this.eventData._reset(); + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseOverOut, true); + + if (this.currentCursorStyle !== this.cursor) { + this.currentCursorStyle = this.cursor; + this.interactionDOMElement.style.cursor = this.cursor; + } + + // TODO + }; + + /** + * Dispatches an event on the display object that was interacted with + * + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the display object in question + * @param {string} eventString - the name of the event (e.g, mousedown) + * @param {object} eventData - the event data object + * @private + */ + + + InteractionManager.prototype.dispatchEvent = function dispatchEvent(displayObject, eventString, eventData) { + if (!eventData.stopped) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + + displayObject.emit(eventString, eventData); + + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } + }; + + /** + * Maps x and y coords from a DOM object and maps them correctly to the pixi view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. + * + * @param {PIXI.Point} point - the point that the result will be stored in + * @param {number} x - the x coord of the position to map + * @param {number} y - the y coord of the position to map + */ + + + InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint(point, x, y) { + var rect = void 0; + + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { x: 0, y: 0, width: 0, height: 0 }; + } else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + + point.x = (x - rect.left) * (this.interactionDOMElement.width / rect.width) / this.resolution; + point.y = (y - rect.top) * (this.interactionDOMElement.height / rect.height) / this.resolution; + }; + + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * + * @param {PIXI.Point} point - the point that is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the displayObject + * that will be hit test (recurcsivly crawls its children) + * @param {Function} [func] - the function that will be called on each interactive object. The + * displayObject and hit will be passed to the function + * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point + * @param {boolean} [interactive] - Whether the displayObject is interactive + * @return {boolean} returns true if the displayObject hit the point + */ + + + InteractionManager.prototype.processInteractive = function processInteractive(point, displayObject, func, hitTest, interactive) { + if (!displayObject || !displayObject.visible) { + return false; + } + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + interactive = displayObject.interactive || interactive; + + var hit = false; + var interactiveParent = interactive; + + // if the displayobject has a hitArea, then it does not need to hitTest children. + if (displayObject.hitArea) { + interactiveParent = false; + } + + // it has a mask! Then lets hit test that before continuing.. + if (hitTest && displayObject._mask) { + if (!displayObject._mask.containsPoint(point)) { + hitTest = false; + } + } + + // it has a filterArea! Same as mask but easier, its a rectangle + if (hitTest && displayObject.filterArea) { + if (!displayObject.filterArea.contains(point.x, point.y)) { + hitTest = false; + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow pixi to completly ignore and bypass checking the displayObjects children. + if (displayObject.interactiveChildren) { + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + + // time to get recursive.. if this function will return if somthing is hit.. + if (this.processInteractive(point, child, func, hitTest, interactiveParent)) { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if (!child.parent) { + continue; + } + + hit = true; + + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + + // { + hitTest = false; + // } + + // we can break now as we have hit an object. + } + } + } + + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit! + if (hitTest && !hit) { + if (displayObject.hitArea) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + hit = displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y); + } else if (displayObject.containsPoint) { + hit = displayObject.containsPoint(point); + } + } + + if (displayObject.interactive) { + if (hit && !this.eventData.target) { + this.eventData.target = displayObject; + this.mouse.target = displayObject; + this.pointer.target = displayObject; + } + + func(displayObject, hit); + } + } + + return hit; + }; + + /** + * Is called when the mouse button is pressed down on the renderer element + * + * @private + * @param {MouseEvent} event - The DOM event of a mouse button being pressed down + */ + + + InteractionManager.prototype.onMouseDown = function onMouseDown(event) { + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData._reset(); + + // Update internal mouse reference + this.mapPositionToPoint(this.mouse.global, event.clientX, event.clientY); + + if (this.autoPreventDefault) { + this.mouse.originalEvent.preventDefault(); + } + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseDown, true); + + var isRightButton = event.button === 2 || event.which === 3; + + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + }; + + /** + * Processes the result of the mouse down check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processMouseDown = function processMouseDown(displayObject, hit) { + var e = this.mouse.originalEvent; + + var isRightButton = e.button === 2 || e.which === 3; + + if (hit) { + displayObject[isRightButton ? '_isRightDown' : '_isLeftDown'] = true; + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + }; + + /** + * Is called when the mouse button is released on the renderer element + * + * @private + * @param {MouseEvent} event - The DOM event of a mouse button being released + */ + + + InteractionManager.prototype.onMouseUp = function onMouseUp(event) { + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData._reset(); + + // Update internal mouse reference + this.mapPositionToPoint(this.mouse.global, event.clientX, event.clientY); + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseUp, true); + + var isRightButton = event.button === 2 || event.which === 3; + + this.emit(isRightButton ? 'rightup' : 'mouseup', this.eventData); + }; + + /** + * Processes the result of the mouse up check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processMouseUp = function processMouseUp(displayObject, hit) { + var e = this.mouse.originalEvent; + + var isRightButton = e.button === 2 || e.which === 3; + var isDown = isRightButton ? '_isRightDown' : '_isLeftDown'; + + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', this.eventData); + + if (displayObject[isDown]) { + displayObject[isDown] = false; + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', this.eventData); + } + } else if (displayObject[isDown]) { + displayObject[isDown] = false; + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', this.eventData); + } + }; + + /** + * Is called when the mouse moves across the renderer element + * + * @private + * @param {MouseEvent} event - The DOM event of the mouse moving + */ + + + InteractionManager.prototype.onMouseMove = function onMouseMove(event) { + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData._reset(); + + this.mapPositionToPoint(this.mouse.global, event.clientX, event.clientY); + + this.didMove = true; + + this.cursor = this.defaultCursorStyle; + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseMove, true); + + this.emit('mousemove', this.eventData); + + if (this.currentCursorStyle !== this.cursor) { + this.currentCursorStyle = this.cursor; + this.interactionDOMElement.style.cursor = this.cursor; + } + + // TODO BUG for parents ineractive object (border order issue) + }; + + /** + * Processes the result of the mouse move check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processMouseMove = function processMouseMove(displayObject, hit) { + this.processMouseOverOut(displayObject, hit); + + // only display on mouse over + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'mousemove', this.eventData); + } + }; + + /** + * Is called when the mouse is moved out of the renderer element + * + * @private + * @param {MouseEvent} event - The DOM event of the mouse being moved out + */ + + + InteractionManager.prototype.onMouseOut = function onMouseOut(event) { + this.mouseOverRenderer = false; + + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData._reset(); + + // Update internal mouse reference + this.mapPositionToPoint(this.mouse.global, event.clientX, event.clientY); + + this.interactionDOMElement.style.cursor = this.defaultCursorStyle; + + // TODO optimize by not check EVERY TIME! maybe half as often? // + this.mapPositionToPoint(this.mouse.global, event.clientX, event.clientY); + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseOverOut, false); + + this.emit('mouseout', this.eventData); + }; + + /** + * Processes the result of the mouse over/out check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processMouseOverOut = function processMouseOverOut(displayObject, hit) { + if (hit && this.mouseOverRenderer) { + if (!displayObject._mouseOver) { + displayObject._mouseOver = true; + this.dispatchEvent(displayObject, 'mouseover', this.eventData); + } + + if (displayObject.buttonMode) { + this.cursor = displayObject.defaultCursor; + } + } else if (displayObject._mouseOver) { + displayObject._mouseOver = false; + this.dispatchEvent(displayObject, 'mouseout', this.eventData); + } + }; + + /** + * Is called when the mouse enters the renderer element area + * + * @private + * @param {MouseEvent} event - The DOM event of the mouse moving into the renderer view + */ + + + InteractionManager.prototype.onMouseOver = function onMouseOver(event) { + this.mouseOverRenderer = true; + + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData._reset(); + + this.emit('mouseover', this.eventData); + }; + + /** + * Is called when the pointer button is pressed down on the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being pressed down + */ + + + InteractionManager.prototype.onPointerDown = function onPointerDown(event) { + this.normalizeToPointerData(event); + this.pointer.originalEvent = event; + this.eventData.data = this.pointer; + this.eventData._reset(); + + // Update internal pointer reference + this.mapPositionToPoint(this.pointer.global, event.clientX, event.clientY); + + if (this.autoPreventDefault) { + this.pointer.originalEvent.preventDefault(); + } + + this.processInteractive(this.pointer.global, this.renderer._lastObjectRendered, this.processPointerDown, true); + + this.emit('pointerdown', this.eventData); + }; + + /** + * Processes the result of the pointer down check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerDown = function processPointerDown(displayObject, hit) { + if (hit) { + displayObject._pointerDown = true; + this.dispatchEvent(displayObject, 'pointerdown', this.eventData); + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerUp = function onPointerUp(event) { + this.normalizeToPointerData(event); + this.pointer.originalEvent = event; + this.eventData.data = this.pointer; + this.eventData._reset(); + + // Update internal pointer reference + this.mapPositionToPoint(this.pointer.global, event.clientX, event.clientY); + + this.processInteractive(this.pointer.global, this.renderer._lastObjectRendered, this.processPointerUp, true); + + this.emit('pointerup', this.eventData); + }; + + /** + * Processes the result of the pointer up check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerUp = function processPointerUp(displayObject, hit) { + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', this.eventData); + + if (displayObject._pointerDown) { + displayObject._pointerDown = false; + this.dispatchEvent(displayObject, 'pointertap', this.eventData); + } + } else if (displayObject._pointerDown) { + displayObject._pointerDown = false; + this.dispatchEvent(displayObject, 'pointerupoutside', this.eventData); + } + }; + + /** + * Is called when the pointer moves across the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer moving + */ + + + InteractionManager.prototype.onPointerMove = function onPointerMove(event) { + this.normalizeToPointerData(event); + this.pointer.originalEvent = event; + this.eventData.data = this.pointer; + this.eventData._reset(); + + this.mapPositionToPoint(this.pointer.global, event.clientX, event.clientY); + + this.processInteractive(this.pointer.global, this.renderer._lastObjectRendered, this.processPointerMove, true); + + this.emit('pointermove', this.eventData); + }; + + /** + * Processes the result of the pointer move check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerMove = function processPointerMove(displayObject, hit) { + if (!this.pointer.originalEvent.changedTouches) { + this.processPointerOverOut(displayObject, hit); + } + + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', this.eventData); + } + }; + + /** + * Is called when the pointer is moved out of the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer being moved out + */ + + + InteractionManager.prototype.onPointerOut = function onPointerOut(event) { + this.normalizeToPointerData(event); + this.pointer.originalEvent = event; + this.eventData.data = this.pointer; + this.eventData._reset(); + + // Update internal pointer reference + this.mapPositionToPoint(this.pointer.global, event.clientX, event.clientY); + + this.processInteractive(this.pointer.global, this.renderer._lastObjectRendered, this.processPointerOverOut, false); + + this.emit('pointerout', this.eventData); + }; + + /** + * Processes the result of the pointer over/out check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerOverOut = function processPointerOverOut(displayObject, hit) { + if (hit && this.mouseOverRenderer) { + if (!displayObject._pointerOver) { + displayObject._pointerOver = true; + this.dispatchEvent(displayObject, 'pointerover', this.eventData); + } + } else if (displayObject._pointerOver) { + displayObject._pointerOver = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + } + }; + + /** + * Is called when the pointer is moved into the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being moved into the renderer view + */ + + + InteractionManager.prototype.onPointerOver = function onPointerOver(event) { + this.pointer.originalEvent = event; + this.eventData.data = this.pointer; + this.eventData._reset(); + + this.emit('pointerover', this.eventData); + }; + + /** + * Is called when a touch is started on the renderer element + * + * @private + * @param {TouchEvent} event - The DOM event of a touch starting on the renderer view + */ + + + InteractionManager.prototype.onTouchStart = function onTouchStart(event) { + if (this.autoPreventDefault) { + event.preventDefault(); + } + + var changedTouches = event.changedTouches; + var cLength = changedTouches.length; + + for (var i = 0; i < cLength; i++) { + var touch = changedTouches[i]; + var touchData = this.getTouchData(touch); + + touchData.originalEvent = event; + + this.eventData.data = touchData; + this.eventData._reset(); + + this.processInteractive(touchData.global, this.renderer._lastObjectRendered, this.processTouchStart, true); + + this.emit('touchstart', this.eventData); + + this.returnTouchData(touchData); + } + }; + + /** + * Processes the result of a touch check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processTouchStart = function processTouchStart(displayObject, hit) { + if (hit) { + displayObject._touchDown = true; + this.dispatchEvent(displayObject, 'touchstart', this.eventData); + } + }; + + /** + * Is called when a touch ends on the renderer element + * + * @private + * @param {TouchEvent} event - The DOM event of a touch ending on the renderer view + */ + + + InteractionManager.prototype.onTouchEnd = function onTouchEnd(event) { + if (this.autoPreventDefault) { + event.preventDefault(); + } + + var changedTouches = event.changedTouches; + var cLength = changedTouches.length; + + for (var i = 0; i < cLength; i++) { + var touchEvent = changedTouches[i]; + + var touchData = this.getTouchData(touchEvent); + + touchData.originalEvent = event; + + // TODO this should be passed along.. no set + this.eventData.data = touchData; + this.eventData._reset(); + + this.processInteractive(touchData.global, this.renderer._lastObjectRendered, this.processTouchEnd, true); + + this.emit('touchend', this.eventData); + + this.returnTouchData(touchData); + } + }; + + /** + * Processes the result of the end of a touch and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processTouchEnd = function processTouchEnd(displayObject, hit) { + if (hit) { + this.dispatchEvent(displayObject, 'touchend', this.eventData); + + if (displayObject._touchDown) { + displayObject._touchDown = false; + this.dispatchEvent(displayObject, 'tap', this.eventData); + } + } else if (displayObject._touchDown) { + displayObject._touchDown = false; + this.dispatchEvent(displayObject, 'touchendoutside', this.eventData); + } + }; + + /** + * Is called when a touch is moved across the renderer element + * + * @private + * @param {TouchEvent} event - The DOM event of a touch moving accross the renderer view + */ + + + InteractionManager.prototype.onTouchMove = function onTouchMove(event) { + if (this.autoPreventDefault) { + event.preventDefault(); + } + + var changedTouches = event.changedTouches; + var cLength = changedTouches.length; + + for (var i = 0; i < cLength; i++) { + var touchEvent = changedTouches[i]; + + var touchData = this.getTouchData(touchEvent); + + touchData.originalEvent = event; + + this.eventData.data = touchData; + this.eventData._reset(); + + this.processInteractive(touchData.global, this.renderer._lastObjectRendered, this.processTouchMove, this.moveWhenInside); + + this.emit('touchmove', this.eventData); + + this.returnTouchData(touchData); + } + }; + + /** + * Processes the result of a touch move check and dispatches the event if need be + * + * @private + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processTouchMove = function processTouchMove(displayObject, hit) { + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'touchmove', this.eventData); + } + }; + + /** + * Grabs an interaction data object from the internal pool + * + * @private + * @param {Touch} touch - The touch data we need to pair with an interactionData object + * @return {PIXI.interaction.InteractionData} The built data object. + */ + + + InteractionManager.prototype.getTouchData = function getTouchData(touch) { + var touchData = this.interactiveDataPool.pop() || new _InteractionData2.default(); + + touchData.identifier = touch.identifier; + this.mapPositionToPoint(touchData.global, touch.clientX, touch.clientY); + + if (navigator.isCocoonJS) { + touchData.global.x = touchData.global.x / this.resolution; + touchData.global.y = touchData.global.y / this.resolution; + } + + touch.globalX = touchData.global.x; + touch.globalY = touchData.global.y; + + return touchData; + }; + + /** + * Returns an interaction data object to the internal pool + * + * @private + * @param {PIXI.interaction.InteractionData} touchData - The touch data object we want to return to the pool + */ + + + InteractionManager.prototype.returnTouchData = function returnTouchData(touchData) { + this.interactiveDataPool.push(touchData); + }; + + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * + * @private + * @param {TouchEvent|MouseEvent} event - The original event data from a touch or mouse event + */ + + + InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData(event) { + if (this.normalizingTouchEvents && event.changedTouches) { + event.button = event.touches.length ? 1 : 0; + event.buttons = event.touches.length ? 1 : 0; + event.isPrimary = event.touches.length === 1; + event.width = event.changedTouches[0].radiusX || 1; + event.height = event.changedTouches[0].radiusY || 1; + event.tiltX = 0; + event.tiltY = 0; + event.pointerType = 'touch'; + event.pointerId = event.changedTouches[0].identifier || 0; + event.pressure = event.changedTouches[0].force || 0.5; + event.rotation = event.changedTouches[0].rotationAngle || 0; + + event.clientX = event.changedTouches[0].clientX; + event.clientY = event.changedTouches[0].clientY; + event.pageX = event.changedTouches[0].pageX; + event.pageY = event.changedTouches[0].pageY; + event.screenX = event.changedTouches[0].screenX; + event.screenY = event.changedTouches[0].screenY; + event.layerX = event.offsetX = event.clientX; + event.layerY = event.offsetY = event.clientY; + } else if (this.normalizingMouseEvents) { + event.isPrimary = true; + event.width = 1; + event.height = 1; + event.tiltX = 0; + event.tiltY = 0; + event.pointerType = 'mouse'; + event.pointerId = 1; + event.pressure = 0.5; + event.rotation = 0; + } + }; + + /** + * Destroys the interaction manager + * + */ + + + InteractionManager.prototype.destroy = function destroy() { + this.removeEvents(); + + this.removeAllListeners(); + + this.renderer = null; + + this.mouse = null; + + this.eventData = null; + + this.interactiveDataPool = null; + + this.interactionDOMElement = null; + + this.onMouseDown = null; + this.processMouseDown = null; + + this.onMouseUp = null; + this.processMouseUp = null; + + this.onMouseMove = null; + this.processMouseMove = null; + + this.onMouseOut = null; + this.processMouseOverOut = null; + + this.onMouseOver = null; + + this.onPointerDown = null; + this.processPointerDown = null; + + this.onPointerUp = null; + this.processPointerUp = null; + + this.onPointerMove = null; + this.processPointerMove = null; + + this.onPointerOut = null; + this.processPointerOverOut = null; + + this.onPointerOver = null; + + this.onTouchStart = null; + this.processTouchStart = null; + + this.onTouchEnd = null; + this.processTouchEnd = null; + + this.onTouchMove = null; + this.processTouchMove = null; + + this._tempPoint = null; + }; + + return InteractionManager; +}(_eventemitter2.default); + +exports.default = InteractionManager; + + +core.WebGLRenderer.registerPlugin('interaction', InteractionManager); +core.CanvasRenderer.registerPlugin('interaction', InteractionManager); + +},{"../core":97,"./InteractionData":179,"./InteractionEvent":180,"./interactiveTarget":183,"eventemitter3":16,"ismobilejs":17}],182:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _InteractionData = require('./InteractionData'); + +Object.defineProperty(exports, 'InteractionData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionData).default; + } +}); + +var _InteractionManager = require('./InteractionManager'); + +Object.defineProperty(exports, 'InteractionManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionManager).default; + } +}); + +var _interactiveTarget = require('./interactiveTarget'); + +Object.defineProperty(exports, 'interactiveTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_interactiveTarget).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./InteractionData":179,"./InteractionManager":181,"./interactiveTarget":183}],183:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * Default property values of interactive objects + * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties + * + * @mixin + * @name interactiveTarget + * @memberof PIXI.interaction + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.interaction.interactiveTarget + * ); + */ +exports.default = { + /** + * Determines if the displayObject be clicked/touched + * + * @inner {boolean} + */ + interactive: false, + + /** + * Determines if the children to the displayObject can be clicked/touched + * Setting this to false allows pixi to bypass a recursive hitTest function + * + * @inner {boolean} + */ + interactiveChildren: true, + + /** + * Interaction shape. Children will be hit first, then this shape will be checked. + * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. + * + * @inner {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle} + */ + hitArea: null, + + /** + * If enabled, the mouse cursor will change when hovered over the displayObject if it is interactive + * + * @inner {boolean} + */ + buttonMode: false, + + /** + * If buttonMode is enabled, this defines what CSS cursor property is used when the mouse cursor + * is hovered over the displayObject + * + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * + * @inner {string} + */ + defaultCursor: 'pointer', + + // some internal checks.. + /** + * Internal check to detect if the mouse cursor is hovered over the displayObject + * + * @inner {boolean} + * @private + */ + _over: false, + + /** + * Internal check to detect if the left mouse button is pressed on the displayObject + * + * @inner {boolean} + * @private + */ + _isLeftDown: false, + + /** + * Internal check to detect if the right mouse button is pressed on the displayObject + * + * @inner {boolean} + * @private + */ + _isRightDown: false, + + /** + * Internal check to detect if the pointer cursor is hovered over the displayObject + * + * @inner {boolean} + * @private + */ + _pointerOver: false, + + /** + * Internal check to detect if the pointer is down on the displayObject + * + * @inner {boolean} + * @private + */ + _pointerDown: false, + + /** + * Internal check to detect if a user has touched the displayObject + * + * @inner {boolean} + * @private + */ + _touchDown: false +}; + +},{}],184:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.parse = parse; + +exports.default = function () { + return function bitmapFontParser(resource, next) { + // skip if no data or not xml data + if (!resource.data || !resource.isXml) { + next(); + + return; + } + + // skip if not bitmap font data, using some silly duck-typing + if (resource.data.getElementsByTagName('page').length === 0 || resource.data.getElementsByTagName('info').length === 0 || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null) { + next(); + + return; + } + + var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; + + if (resource.isDataUrl) { + if (xmlUrl === '.') { + xmlUrl = ''; + } + + if (this.baseUrl && xmlUrl) { + // if baseurl has a trailing slash then add one to xmlUrl so the replace works below + if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { + xmlUrl += '/'; + } + + // remove baseUrl from xmlUrl + xmlUrl = xmlUrl.replace(this.baseUrl, ''); + } + } + + // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { + xmlUrl += '/'; + } + + var textureUrl = xmlUrl + resource.data.getElementsByTagName('page')[0].getAttribute('file'); + + if (_core.utils.TextureCache[textureUrl]) { + // reuse existing texture + parse(resource, _core.utils.TextureCache[textureUrl]); + next(); + } else { + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata + }; + + // load the texture for the font + this.add(resource.name + '_image', textureUrl, loadOptions, function (res) { + parse(resource, res.texture); + next(); + }); + } + }; +}; + +var _path = require('path'); + +var path = _interopRequireWildcard(_path); + +var _core = require('../core'); + +var _resourceLoader = require('resource-loader'); + +var _extras = require('../extras'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function parse(resource, texture) { + var data = {}; + var info = resource.data.getElementsByTagName('info')[0]; + var common = resource.data.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10); + data.chars = {}; + + // parse letters + var letters = resource.data.getElementsByTagName('char'); + + for (var i = 0; i < letters.length; i++) { + var charCode = parseInt(letters[i].getAttribute('id'), 10); + + var textureRect = new _core.Rectangle(parseInt(letters[i].getAttribute('x'), 10) + texture.frame.x, parseInt(letters[i].getAttribute('y'), 10) + texture.frame.y, parseInt(letters[i].getAttribute('width'), 10), parseInt(letters[i].getAttribute('height'), 10)); + + data.chars[charCode] = { + xOffset: parseInt(letters[i].getAttribute('xoffset'), 10), + yOffset: parseInt(letters[i].getAttribute('yoffset'), 10), + xAdvance: parseInt(letters[i].getAttribute('xadvance'), 10), + kerning: {}, + texture: new _core.Texture(texture.baseTexture, textureRect) + + }; + } + + // parse kernings + var kernings = resource.data.getElementsByTagName('kerning'); + + for (var _i = 0; _i < kernings.length; _i++) { + var first = parseInt(kernings[_i].getAttribute('first'), 10); + var second = parseInt(kernings[_i].getAttribute('second'), 10); + var amount = parseInt(kernings[_i].getAttribute('amount'), 10); + + if (data.chars[second]) { + data.chars[second].kerning[first] = amount; + } + } + + resource.bitmapFont = data; + + // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 + // but it's very likely to change + _extras.BitmapText.fonts[data.font] = data; +} + +},{"../core":97,"../extras":165,"path":44,"resource-loader":69}],185:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _loader = require('./loader'); + +Object.defineProperty(exports, 'Loader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_loader).default; + } +}); + +var _bitmapFontParser = require('./bitmapFontParser'); + +Object.defineProperty(exports, 'bitmapFontParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_bitmapFontParser).default; + } +}); +Object.defineProperty(exports, 'parseBitmapFontData', { + enumerable: true, + get: function get() { + return _bitmapFontParser.parse; + } +}); + +var _spritesheetParser = require('./spritesheetParser'); + +Object.defineProperty(exports, 'spritesheetParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_spritesheetParser).default; + } +}); + +var _textureParser = require('./textureParser'); + +Object.defineProperty(exports, 'textureParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_textureParser).default; + } +}); + +var _resourceLoader = require('resource-loader'); + +Object.defineProperty(exports, 'Resource', { + enumerable: true, + get: function get() { + return _resourceLoader.Resource; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./bitmapFontParser":184,"./loader":186,"./spritesheetParser":187,"./textureParser":188,"resource-loader":69}],186:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _resourceLoader = require('resource-loader'); + +var _resourceLoader2 = _interopRequireDefault(_resourceLoader); + +var _textureParser = require('./textureParser'); + +var _textureParser2 = _interopRequireDefault(_textureParser); + +var _spritesheetParser = require('./spritesheetParser'); + +var _spritesheetParser2 = _interopRequireDefault(_spritesheetParser); + +var _bitmapFontParser = require('./bitmapFontParser'); + +var _bitmapFontParser2 = _interopRequireDefault(_bitmapFontParser); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * The new loader, extends Resource Loader by Chad Engler : https://github.com/englercj/resource-loader + * + * ```js + * let loader = PIXI.loader; // pixi exposes a premade instance for you to use. + * //or + * let loader = new PIXI.loaders.Loader(); // you can also create your own if you want + * + * loader.add('bunny',"data/bunny.png"); + * + * loader.once('complete',onAssetsLoaded); + * + * loader.load(); + * ``` + * + * @see https://github.com/englercj/resource-loader + * + * @class + * @extends module:resource-loader.ResourceLoader + * @memberof PIXI.loaders + */ +var Loader = function (_ResourceLoader) { + _inherits(Loader, _ResourceLoader); + + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + _classCallCheck(this, Loader); + + var _this = _possibleConstructorReturn(this, _ResourceLoader.call(this, baseUrl, concurrency)); + + for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { + _this.use(Loader._pixiMiddleware[i]()); + } + return _this; + } + + /** + * Adds a default middleware to the pixi loader. + * + * @static + * @param {Function} fn - The middleware to add. + */ + + + Loader.addPixiMiddleware = function addPixiMiddleware(fn) { + Loader._pixiMiddleware.push(fn); + }; + + return Loader; +}(_resourceLoader2.default); + +exports.default = Loader; + + +Loader._pixiMiddleware = [ +// parse any blob into more usable objects (e.g. Image) +_resourceLoader2.default.middleware.parsing.blob, +// parse any Image objects into textures +_textureParser2.default, +// parse any spritesheet data into multiple textures +_spritesheetParser2.default, +// parse bitmap font data into multiple textures +_bitmapFontParser2.default]; + +// Add custom extentions +var Resource = _resourceLoader2.default.Resource; + +Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); + +},{"./bitmapFontParser":184,"./spritesheetParser":187,"./textureParser":188,"resource-loader":69}],187:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function spritesheetParser(resource, next) { + var resourcePath = void 0; + var imageResourceName = resource.name + '_image'; + + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data || !resource.isJson || !resource.data.frames || this.resources[imageResourceName]) { + next(); + + return; + } + + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata + }; + + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + resourcePath = resource.data.meta.image; + } else { + resourcePath = _path2.default.dirname(resource.url.replace(this.baseUrl, '')) + '/' + resource.data.meta.image; + } + + // load the image for this sheet + this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + resource.textures = {}; + + var frames = resource.data.frames; + var frameKeys = Object.keys(frames); + var resolution = core.utils.getResolutionOfUrl(resource.url); + var batchIndex = 0; + + function processFrames(initialFrameIndex, maxFrames) { + var frameIndex = initialFrameIndex; + + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < frameKeys.length) { + var i = frameKeys[frameIndex]; + var rect = frames[i].frame; + + if (rect) { + var frame = null; + var trim = null; + var orig = new core.Rectangle(0, 0, frames[i].sourceSize.w / resolution, frames[i].sourceSize.h / resolution); + + if (frames[i].rotated) { + frame = new core.Rectangle(rect.x / resolution, rect.y / resolution, rect.h / resolution, rect.w / resolution); + } else { + frame = new core.Rectangle(rect.x / resolution, rect.y / resolution, rect.w / resolution, rect.h / resolution); + } + + // Check to see if the sprite is trimmed + if (frames[i].trimmed) { + trim = new core.Rectangle(frames[i].spriteSourceSize.x / resolution, frames[i].spriteSourceSize.y / resolution, frames[i].spriteSourceSize.w / resolution, frames[i].spriteSourceSize.h / resolution); + } + + resource.textures[i] = new core.Texture(res.texture.baseTexture, frame, orig, trim, frames[i].rotated ? 2 : 0); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage functions + core.utils.TextureCache[i] = resource.textures[i]; + } + + frameIndex++; + } + } + + function shouldProcessNextBatch() { + return batchIndex * BATCH_SIZE < frameKeys.length; + } + + function processNextBatch(done) { + processFrames(batchIndex * BATCH_SIZE, BATCH_SIZE); + batchIndex++; + setTimeout(done, 0); + } + + function iteration() { + processNextBatch(function () { + if (shouldProcessNextBatch()) { + iteration(); + } else { + next(); + } + }); + } + + if (frameKeys.length <= BATCH_SIZE) { + processFrames(0, BATCH_SIZE); + next(); + } else { + iteration(); + } + }); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _path = require('path'); + +var _path2 = _interopRequireDefault(_path); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var BATCH_SIZE = 1000; + +},{"../core":97,"path":44,"resource-loader":69}],188:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function textureParser(resource, next) { + // create a new texture if the data is an Image object + if (resource.data && resource.isImage) { + var baseTexture = new core.BaseTexture(resource.data, null, core.utils.getResolutionOfUrl(resource.url)); + + baseTexture.imageUrl = resource.url; + resource.texture = new core.Texture(baseTexture); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions + core.utils.BaseTextureCache[resource.url] = baseTexture; + core.utils.TextureCache[resource.url] = resource.texture; + } + + next(); + }; +}; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +},{"../core":97}],189:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _MeshShader = require('./webgl/MeshShader'); + +var _MeshShader2 = _interopRequireDefault(_MeshShader); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); +var tempPolygon = new core.Polygon(); + +/** + * Base mesh class + * @class + * @extends PIXI.Container + * @memberof PIXI.mesh + */ + +var Mesh = function (_core$Container) { + _inherits(Mesh, _core$Container); + + /** + * @param {PIXI.Texture} texture - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts + */ + function Mesh(texture, vertices, uvs, indices, drawMode) { + _classCallCheck(this, Mesh); + + /** + * The texture of the Mesh + * + * @member {PIXI.Texture} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._texture = null; + + /** + * The Uvs of the Mesh + * + * @member {Float32Array} + */ + _this.uvs = uvs || new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + /** + * An array of vertices + * + * @member {Float32Array} + */ + _this.vertices = vertices || new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]); + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + // TODO auto generate this based on draw mode! + _this.indices = indices || new Uint16Array([0, 1, 3, 2]); + + /** + * Whether the Mesh is dirty or not + * + * @member {number} + */ + _this.dirty = 0; + _this.indexDirty = 0; + + /** + * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove + * any blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles + * to overlap a bit with each other. + * + * @member {number} + */ + _this.canvasPadding = 0; + + /** + * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts + * + * @member {number} + * @see PIXI.mesh.Mesh.DRAW_MODES + */ + _this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH; + + // run texture setter; + _this.texture = texture; + + /** + * The default shader that is used if a mesh doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + _this.shader = null; + + /** + * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any + * tint effect. + * + * @member {number} + * @memberof PIXI.mesh.Mesh# + */ + _this.tintRgb = new Float32Array([1, 1, 1]); + + _this._glDatas = []; + return _this; + } + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - a reference to the WebGL renderer + */ + + + Mesh.prototype._renderWebGL = function _renderWebGL(renderer) { + // get rid of any thing that may be batching. + renderer.flush(); + + // renderer.plugins.mesh.render(this); + var gl = renderer.gl; + var glData = this._glDatas[renderer.CONTEXT_UID]; + + if (!glData) { + glData = { + shader: new _MeshShader2.default(gl), + vertexBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.vertices, gl.STREAM_DRAW), + uvBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.uvs, gl.STREAM_DRAW), + indexBuffer: _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW), + // build the vao object that will render.. + vao: new _pixiGlCore2.default.VertexArrayObject(gl), + dirty: this.dirty, + indexDirty: this.indexDirty + }; + + // build the vao object that will render.. + glData.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(glData.indexBuffer).addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0).addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); + + this._glDatas[renderer.CONTEXT_UID] = glData; + } + + if (this.dirty !== glData.dirty) { + glData.dirty = this.dirty; + glData.uvBuffer.upload(); + } + + if (this.indexDirty !== glData.indexDirty) { + glData.indexDirty = this.indexDirty; + glData.indexBuffer.upload(); + } + + glData.vertexBuffer.upload(); + + renderer.bindShader(glData.shader); + renderer.bindTexture(this._texture, 0); + renderer.state.setBlendMode(this.blendMode); + + glData.shader.uniforms.translationMatrix = this.worldTransform.toArray(true); + glData.shader.uniforms.alpha = this.worldAlpha; + glData.shader.uniforms.tint = this.tintRgb; + + var drawMode = this.drawMode === Mesh.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + glData.vao.bind().draw(drawMode, this.indices.length).unbind(); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + + + Mesh.prototype._renderCanvas = function _renderCanvas(renderer) { + var context = renderer.context; + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + if (this.drawMode === Mesh.DRAW_MODES.TRIANGLE_MESH) { + this._renderCanvasTriangleMesh(context); + } else { + this._renderCanvasTriangles(context); + } + }; + + /** + * Draws the object in Triangle Mesh mode using canvas + * + * @private + * @param {CanvasRenderingContext2D} context - The current drawing context + */ + + + Mesh.prototype._renderCanvasTriangleMesh = function _renderCanvasTriangleMesh(context) { + // draw triangles!! + var vertices = this.vertices; + var uvs = this.uvs; + var length = vertices.length / 2; + + // this.count++; + + for (var i = 0; i < length - 2; i++) { + // draw some triangles! + var index = i * 2; + + this._renderCanvasDrawTriangle(context, vertices, uvs, index, index + 2, index + 4); + } + }; + + /** + * Draws the object in triangle mode using canvas + * + * @private + * @param {CanvasRenderingContext2D} context - the current drawing context + */ + + + Mesh.prototype._renderCanvasTriangles = function _renderCanvasTriangles(context) { + // draw triangles!! + var vertices = this.vertices; + var uvs = this.uvs; + var indices = this.indices; + var length = indices.length; + // this.count++; + + for (var i = 0; i < length; i += 3) { + // draw some triangles! + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); + } + }; + + /** + * Draws one of the triangles that form this Mesh + * + * @private + * @param {CanvasRenderingContext2D} context - the current drawing context + * @param {Float32Array} vertices - a reference to the vertices of the Mesh + * @param {Float32Array} uvs - a reference to the uvs of the Mesh + * @param {number} index0 - the index of the first vertex + * @param {number} index1 - the index of the second vertex + * @param {number} index2 - the index of the third vertex + */ + + + Mesh.prototype._renderCanvasDrawTriangle = function _renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2) { + var base = this._texture.baseTexture; + var textureSource = base.source; + var textureWidth = base.width; + var textureHeight = base.height; + + var u0 = uvs[index0] * base.width; + var u1 = uvs[index1] * base.width; + var u2 = uvs[index2] * base.width; + var v0 = uvs[index0 + 1] * base.height; + var v1 = uvs[index1 + 1] * base.height; + var v2 = uvs[index2 + 1] * base.height; + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + if (this.canvasPadding > 0) { + var paddingX = this.canvasPadding / this.worldTransform.a; + var paddingY = this.canvasPadding / this.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt(normX * normX + normY * normY); + + x0 = centerX + normX / dist * (dist + paddingX); + y0 = centerY + normY / dist * (dist + paddingY); + + // + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x1 = centerX + normX / dist * (dist + paddingX); + y1 = centerY + normY / dist * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x2 = centerX + normX / dist * (dist + paddingX); + y2 = centerY + normY / dist * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2; + var deltaA = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2; + var deltaB = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2; + var deltaC = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2; + var deltaD = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2; + var deltaE = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2; + var deltaF = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2; + + context.transform(deltaA / delta, deltaD / delta, deltaB / delta, deltaE / delta, deltaC / delta, deltaF / delta); + + context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + + context.restore(); + }; + + /** + * Renders a flat Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - The Mesh to render + */ + + + Mesh.prototype.renderMeshFlat = function renderMeshFlat(mesh) { + var context = this.context; + var vertices = mesh.vertices; + var length = vertices.length / 2; + + // this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; ++i) { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var y0 = vertices[index + 1]; + + var x1 = vertices[index + 2]; + var y1 = vertices[index + 3]; + + var x2 = vertices[index + 4]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + }; + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Mesh.prototype._onTextureUpdate = function _onTextureUpdate() {} + /* empty */ + + + /** + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + */ + ; + + Mesh.prototype._calculateBounds = function _calculateBounds() { + // TODO - we can cache local bounds and use them if they are dirty (like graphics) + this._bounds.addVertices(this.transform, this.vertices, 0, this.vertices.length); + }; + + /** + * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Mesh.prototype.containsPoint = function containsPoint(point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + + this.worldTransform.applyInverse(point, tempPoint); + + var vertices = this.vertices; + var points = tempPolygon.points; + var indices = this.indices; + var len = this.indices.length; + var step = this.drawMode === Mesh.DRAW_MODES.TRIANGLES ? 3 : 1; + + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + + return false; + }; + + /** + * The texture that the mesh uses. + * + * @member {PIXI.Texture} + * @memberof PIXI.mesh.Mesh# + */ + + + _createClass(Mesh, [{ + key: 'texture', + get: function get() { + return this._texture; + } + + /** + * Sets the texture the mesh uses. + * + * @param {Texture} value - The value to set. + */ + , + set: function set(value) { + if (this._texture === value) { + return; + } + + this._texture = value; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + + /** + * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @memberof PIXI.mesh.Mesh# + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return core.utils.rgb2hex(this.tintRgb); + } + + /** + * Sets the tint the mesh uses. + * + * @param {number} value - The value to set. + */ + , + set: function set(value) { + this.tintRgb = core.utils.hex2rgb(value, this.tintRgb); + } + }]); + + return Mesh; +}(core.Container); + +/** + * Different drawing buffer modes supported + * + * @static + * @constant + * @type {object} + * @property {number} TRIANGLE_MESH + * @property {number} TRIANGLES + */ + + +exports.default = Mesh; +Mesh.DRAW_MODES = { + TRIANGLE_MESH: 0, + TRIANGLES: 1 +}; + +},{"../core":97,"./webgl/MeshShader":194,"pixi-gl-core":51}],190:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Plane2 = require('./Plane'); + +var _Plane3 = _interopRequireDefault(_Plane2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DEFAULT_BORDER_SIZE = 10; + +/** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.fromImage('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
+ *      A                          B
+ *    +---+----------------------+---+
+ *  C | 1 |          2           | 3 |
+ *    +---+----------------------+---+
+ *    |   |                      |   |
+ *    | 4 |          5           | 6 |
+ *    |   |                      |   |
+ *    +---+----------------------+---+
+ *  D | 7 |          8           | 9 |
+ *    +---+----------------------+---+
+
+ *  When changing this objects width and/or height:
+ *     areas 1 3 7 and 9 will remain unscaled.
+ *     areas 2 and 8 will be stretched horizontally
+ *     areas 4 and 6 will be stretched vertically
+ *     area 5 will be stretched both horizontally and vertically
+ * 
+ * + * @class + * @extends PIXI.mesh.Plane + * @memberof PIXI.mesh + * + */ + +var NineSlicePlane = function (_Plane) { + _inherits(NineSlicePlane, _Plane); + + /** + * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. + * @param {int} [leftWidth=10] size of the left vertical bar (A) + * @param {int} [topHeight=10] size of the top horizontal bar (C) + * @param {int} [rightWidth=10] size of the right vertical bar (B) + * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) + */ + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + _classCallCheck(this, NineSlicePlane); + + var _this = _possibleConstructorReturn(this, _Plane.call(this, texture, 4, 4)); + + var uvs = _this.uvs; + + // right and bottom uv's are always 1 + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + + _this._origWidth = texture.width; + _this._origHeight = texture.height; + _this._uvw = 1 / _this._origWidth; + _this._uvh = 1 / _this._origHeight; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.width = texture.width; + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.height = texture.height; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _this._uvw * leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - _this._uvw * rightWidth; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _this._uvh * topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - _this._uvh * bottomHeight; + + /** + * The width of the left column (a) + * + * @member {number} + */ + _this.leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; + + /** + * The width of the right column (b) + * + * @member {number} + */ + _this.rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; + + /** + * The height of the top row (c) + * + * @member {number} + */ + _this.topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; + + /** + * The height of the bottom row (d) + * + * @member {number} + */ + _this.bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; + return _this; + } + + /** + * Updates the horizontal vertices. + * + */ + + + NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices() { + var vertices = this.vertices; + + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight; + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + }; + + /** + * Updates the vertical vertices. + * + */ + + + NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices() { + var vertices = this.vertices; + + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth; + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with. + */ + + + NineSlicePlane.prototype._renderCanvas = function _renderCanvas(renderer) { + var context = renderer.context; + + context.globalAlpha = this.worldAlpha; + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + var base = this._texture.baseTexture; + var textureSource = base.source; + var w = base.width; + var h = base.height; + + this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11); + this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13); + this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15); + this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19); + this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21); + this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23); + this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27); + this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29); + this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31); + }; + + /** + * Renders one segment of the plane. + * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure + * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used. + * + * @private + * @param {CanvasRenderingContext2D} context - The context to draw with. + * @param {CanvasImageSource} textureSource - The source to draw. + * @param {number} w - width of the texture + * @param {number} h - height of the texture + * @param {number} x1 - x index 1 + * @param {number} y1 - y index 1 + * @param {number} x2 - x index 2 + * @param {number} y2 - y index 2 + */ + + + NineSlicePlane.prototype.drawSegment = function drawSegment(context, textureSource, w, h, x1, y1, x2, y2) { + // otherwise you get weird results when using slices of that are 0 wide or high. + var uvs = this.uvs; + var vertices = this.vertices; + + var sw = (uvs[x2] - uvs[x1]) * w; + var sh = (uvs[y2] - uvs[y1]) * h; + var dw = vertices[x2] - vertices[x1]; + var dh = vertices[y2] - vertices[y1]; + + // make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn. + if (sw < 1) { + sw = 1; + } + + if (sh < 1) { + sh = 1; + } + + // make sure destination is at least 1 pixel wide and high, otherwise you get + // lines when rendering close to original size. + if (dw < 1) { + dw = 1; + } + + if (dh < 1) { + dh = 1; + } + + context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh); + }; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + */ + + + _createClass(NineSlicePlane, [{ + key: 'width', + get: function get() { + return this._width; + } + + /** + * Sets the width. + * + * @param {number} value - the value to set to. + */ + , + set: function set(value) { + this._width = value; + this.updateVerticalVertices(); + } + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + */ + + }, { + key: 'height', + get: function get() { + return this._height; + } + + /** + * Sets the height. + * + * @param {number} value - the value to set to. + */ + , + set: function set(value) { + this._height = value; + this.updateHorizontalVertices(); + } + + /** + * The width of the left column + * + * @member {number} + */ + + }, { + key: 'leftWidth', + get: function get() { + return this._leftWidth; + } + + /** + * Sets the width of the left column. + * + * @param {number} value - the value to set to. + */ + , + set: function set(value) { + this._leftWidth = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = this._uvw * value; + vertices[2] = vertices[10] = vertices[18] = vertices[26] = value; + + this.dirty = true; + } + + /** + * The width of the right column + * + * @member {number} + */ + + }, { + key: 'rightWidth', + get: function get() { + return this._rightWidth; + } + + /** + * Sets the width of the right column. + * + * @param {number} value - the value to set to. + */ + , + set: function set(value) { + this._rightWidth = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - this._uvw * value; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - value; + + this.dirty = true; + } + + /** + * The height of the top row + * + * @member {number} + */ + + }, { + key: 'topHeight', + get: function get() { + return this._topHeight; + } + + /** + * Sets the height of the top row. + * + * @param {number} value - the value to set to. + */ + , + set: function set(value) { + this._topHeight = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[9] = uvs[11] = uvs[13] = uvs[15] = this._uvh * value; + vertices[9] = vertices[11] = vertices[13] = vertices[15] = value; + + this.dirty = true; + } + + /** + * The height of the bottom row + * + * @member {number} + */ + + }, { + key: 'bottomHeight', + get: function get() { + return this._bottomHeight; + } + + /** + * Sets the height of the bottom row. + * + * @param {number} value - the value to set to. + */ + , + set: function set(value) { + this._bottomHeight = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - this._uvh * value; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - value; + + this.dirty = true; + } + }]); + + return NineSlicePlane; +}(_Plane3.default); + +exports.default = NineSlicePlane; + +},{"./Plane":191}],191:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The Plane allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Plane = function (_Mesh) { + _inherits(Plane, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the Plane. + * @param {number} verticesX - The number of vertices in the x-axis + * @param {number} verticesY - The number of vertices in the y-axis + */ + function Plane(texture, verticesX, verticesY) { + _classCallCheck(this, Plane); + + /** + * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this._ready = true; + + _this.verticesX = verticesX || 10; + _this.verticesY = verticesY || 10; + + _this.drawMode = _Mesh3.default.DRAW_MODES.TRIANGLES; + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Plane.prototype.refresh = function refresh() { + var total = this.verticesX * this.verticesY; + var verts = []; + var colors = []; + var uvs = []; + var indices = []; + var texture = this.texture; + + var segmentsX = this.verticesX - 1; + var segmentsY = this.verticesY - 1; + + var sizeX = texture.width / segmentsX; + var sizeY = texture.height / segmentsY; + + for (var i = 0; i < total; i++) { + var x = i % this.verticesX; + var y = i / this.verticesX | 0; + + verts.push(x * sizeX, y * sizeY); + + // this works for rectangular textures. + uvs.push(texture._uvs.x0 + (texture._uvs.x1 - texture._uvs.x0) * (x / (this.verticesX - 1)), texture._uvs.y0 + (texture._uvs.y3 - texture._uvs.y0) * (y / (this.verticesY - 1))); + } + + // cons + + var totalSub = segmentsX * segmentsY; + + for (var _i = 0; _i < totalSub; _i++) { + var xpos = _i % segmentsX; + var ypos = _i / segmentsX | 0; + + var value = ypos * this.verticesX + xpos; + var value2 = ypos * this.verticesX + xpos + 1; + var value3 = (ypos + 1) * this.verticesX + xpos; + var value4 = (ypos + 1) * this.verticesX + xpos + 1; + + indices.push(value, value2, value3); + indices.push(value2, value4, value3); + } + + // console.log(indices) + this.vertices = new Float32Array(verts); + this.uvs = new Float32Array(uvs); + this.colors = new Float32Array(colors); + this.indices = new Uint16Array(indices); + + this.indexDirty = true; + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Plane.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh3.default.prototype._onTextureUpdate.call(this); + + // wait for the Plane ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + return Plane; +}(_Mesh3.default); + +exports.default = Plane; + +},{"./Mesh":189}],192:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The rope allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Rope = function (_Mesh) { + _inherits(Rope, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the rope. + * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. + */ + function Rope(texture, points) { + _classCallCheck(this, Rope); + + /* + * @member {PIXI.Point[]} An array of points that determine the rope + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this.points = points; + + /* + * @member {Float32Array} An array of vertices used to construct this rope. + */ + _this.vertices = new Float32Array(points.length * 4); + + /* + * @member {Float32Array} The WebGL Uvs of the rope. + */ + _this.uvs = new Float32Array(points.length * 4); + + /* + * @member {Float32Array} An array containing the color components + */ + _this.colors = new Float32Array(points.length * 2); + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + _this.indices = new Uint16Array(points.length * 2); + + /** + * Tracker for if the rope is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + _this._ready = true; + + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Rope.prototype.refresh = function refresh() { + var points = this.points; + + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1 || !this._texture._uvs) { + return; + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + var textureUvs = this._texture._uvs; + var offset = new core.Point(textureUvs.x0, textureUvs.y0); + var factor = new core.Point(textureUvs.x2 - textureUvs.x0, textureUvs.y2 - textureUvs.y0); + + uvs[0] = 0 + offset.x; + uvs[1] = 0 + offset.y; + uvs[2] = 0 + offset.x; + uvs[3] = Number(factor.y) + offset.y; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + + for (var i = 1; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + var amount = i / (total - 1); + + uvs[index] = amount * factor.x + offset.x; + uvs[index + 1] = 0 + offset.y; + + uvs[index + 2] = amount * factor.x + offset.x; + uvs[index + 3] = Number(factor.y) + offset.y; + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + + this.dirty = true; + this.indexDirty = true; + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Rope.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh.prototype._onTextureUpdate.call(this); + + // wait for the Rope ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + Rope.prototype.updateTransform = function updateTransform() { + var points = this.points; + + if (points.length < 1) { + return; + } + + var lastPoint = points[0]; + var nextPoint = void 0; + var perpX = 0; + var perpY = 0; + + // this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } else { + nextPoint = point; + } + + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + + var ratio = (1 - i / (total - 1)) * 10; + + if (ratio > 1) { + ratio = 1; + } + + var perpLength = Math.sqrt(perpX * perpX + perpY * perpY); + var num = this._texture.height / 2; // (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; + + perpX /= perpLength; + perpY /= perpLength; + + perpX *= num; + perpY *= num; + + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + + lastPoint = point; + } + + this.containerUpdateTransform(); + }; + + return Rope; +}(_Mesh3.default); + +exports.default = Rope; + +},{"../core":97,"./Mesh":189}],193:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh = require('./Mesh'); + +Object.defineProperty(exports, 'Mesh', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Mesh).default; + } +}); + +var _Plane = require('./Plane'); + +Object.defineProperty(exports, 'Plane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Plane).default; + } +}); + +var _NineSlicePlane = require('./NineSlicePlane'); + +Object.defineProperty(exports, 'NineSlicePlane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NineSlicePlane).default; + } +}); + +var _Rope = require('./Rope'); + +Object.defineProperty(exports, 'Rope', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rope).default; + } +}); + +var _MeshShader = require('./webgl/MeshShader'); + +Object.defineProperty(exports, 'MeshShader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_MeshShader).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./Mesh":189,"./NineSlicePlane":190,"./Plane":191,"./Rope":192,"./webgl/MeshShader":194}],194:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../core/Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI.mesh + */ +var MeshShader = function (_Shader) { + _inherits(MeshShader, _Shader); + + /** + * @param {WebGLRenderingContext} gl - The WebGLRenderingContext. + */ + function MeshShader(gl) { + _classCallCheck(this, MeshShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform mat3 translationMatrix;', 'uniform mat3 projectionMatrix;', 'varying vec2 vTextureCoord;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', // eslint-disable-line max-len + ' vTextureCoord = aTextureCoord;', '}'].join('\n'), ['varying vec2 vTextureCoord;', 'uniform float alpha;', 'uniform vec3 tint;', 'uniform sampler2D uSampler;', 'void main(void){', ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vec4(tint * alpha, alpha);', + // ' gl_FragColor = vec4(1.0);', + '}'].join('\n'))); + } + + return MeshShader; +}(_Shader3.default); + +exports.default = MeshShader; + +},{"../../core/Shader":77}],195:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that advanced + * functionality will not work. ParticleContainer implements only the basic object transform (position, scale, rotation). + * Any other functionality like tinting, masking, etc will not work on sprites in this batch. + * + * It's extremely easy to use : + * + * ```js + * let container = new ParticleContainer(); + * + * for (let i = 0; i < 100; ++i) + * { + * let sprite = new PIXI.Sprite.fromImage("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be renderer at the speed of light. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.particles + */ +var ParticleContainer = function (_core$Container) { + _inherits(ParticleContainer, _core$Container); + + /** + * @param {number} [maxSize=15000] - The maximum number of particles that can be renderer by the container. + * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.scale=false] - When true, scale be uploaded and applied. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.alpha=false] - When true, alpha be uploaded and applied. + * @param {number} [batchSize=15000] - Number of particles per batch. + */ + function ParticleContainer() { + var maxSize = arguments.length <= 0 || arguments[0] === undefined ? 1500 : arguments[0]; + var properties = arguments[1]; + var batchSize = arguments.length <= 2 || arguments[2] === undefined ? 16384 : arguments[2]; + + _classCallCheck(this, ParticleContainer); + + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + var maxBatchSize = 16384; + + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + + if (batchSize > maxSize) { + batchSize = maxSize; + } + + /** + * Set properties to be dynamic (true) / static (false) + * + * @member {boolean[]} + * @private + */ + _this._properties = [false, true, false, false, false]; + + /** + * @member {number} + * @private + */ + _this._maxSize = maxSize; + + /** + * @member {number} + * @private + */ + _this._batchSize = batchSize; + + /** + * @member {WebGLBuffer} + * @private + */ + _this._glBuffers = []; + + /** + * @member {number} + * @private + */ + _this._bufferToUpdate = 0; + + /** + * @member {boolean} + * + */ + _this.interactiveChildren = false; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` + * to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Used for canvas renderering. If true then the elements will be positioned at the + * nearest pixel. This provides a nice speed boost. + * + * @member {boolean} + * @default true; + */ + _this.roundPixels = true; + + /** + * The texture used to render the children. + * + * @readonly + * @member {BaseTexture} + */ + _this.baseTexture = null; + + _this.setProperties(properties); + return _this; + } + + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * + * @param {object} properties - The properties to be uploaded + */ + + + ParticleContainer.prototype.setProperties = function setProperties(properties) { + if (properties) { + this._properties[0] = 'scale' in properties ? !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'alpha' in properties ? !!properties.alpha : this._properties[4]; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + ParticleContainer.prototype.updateTransform = function updateTransform() { + // TODO don't need to! + this.displayObjectUpdateTransform(); + // PIXI.Container.prototype.updateTransform.call( this ); + }; + + /** + * Renders the container using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer + */ + + + ParticleContainer.prototype.renderWebGL = function renderWebGL(renderer) { + var _this2 = this; + + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.hasLoaded) { + this.baseTexture.once('update', function () { + return _this2.onChildrenChange(0); + }); + } + } + + renderer.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + + /** + * Set the flag that static data should be updated to true + * + * @private + * @param {number} smallestChildIndex - The smallest child index + */ + + + ParticleContainer.prototype.onChildrenChange = function onChildrenChange(smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + + if (bufferIndex < this._bufferToUpdate) { + this._bufferToUpdate = bufferIndex; + } + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + + + ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var isRotated = true; + + var positionX = 0; + var positionY = 0; + + var finalWidth = 0; + var finalHeight = 0; + + var compositeOperation = renderer.blendModes[this.blendMode]; + + if (compositeOperation !== context.globalCompositeOperation) { + context.globalCompositeOperation = compositeOperation; + } + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i]; + + if (!child.visible) { + continue; + } + + var frame = child.texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) { + // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call + if (isRotated) { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx * renderer.resolution, transform.ty * renderer.resolution); + + isRotated = false; + } + + positionX = child.anchor.x * (-frame.width * child.scale.x) + child.position.x + 0.5; + positionY = child.anchor.y * (-frame.height * child.scale.y) + child.position.y + 0.5; + + finalWidth = frame.width * child.scale.x; + finalHeight = frame.height * child.scale.y; + } else { + if (!isRotated) { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + + if (renderer.roundPixels) { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution | 0, childTransform.ty * renderer.resolution | 0); + } else { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution, childTransform.ty * renderer.resolution); + } + + positionX = child.anchor.x * -frame.width + 0.5; + positionY = child.anchor.y * -frame.height + 0.5; + + finalWidth = frame.width; + finalHeight = frame.height; + } + + var resolution = child.texture.baseTexture.resolution; + + context.drawImage(child.texture.baseTexture.source, frame.x * resolution, frame.y * resolution, frame.width * resolution, frame.height * resolution, positionX * resolution, positionY * resolution, finalWidth * resolution, finalHeight * resolution); + } + }; + + /** + * Destroys the container + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + */ + + + ParticleContainer.prototype.destroy = function destroy(options) { + _core$Container.prototype.destroy.call(this, options); + + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + } + + this._properties = null; + this._buffers = null; + }; + + return ParticleContainer; +}(core.Container); + +exports.default = ParticleContainer; + +},{"../core":97}],196:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ParticleContainer = require('./ParticleContainer'); + +Object.defineProperty(exports, 'ParticleContainer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleContainer).default; + } +}); + +var _ParticleRenderer = require('./webgl/ParticleRenderer'); + +Object.defineProperty(exports, 'ParticleRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleRenderer).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./ParticleContainer":195,"./webgl/ParticleRenderer":198}],197:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + +/** + * The particle buffer manages the static and dynamic buffers for a particle container. + * + * @class + * @private + * @memberof PIXI + */ +var ParticleBuffer = function () { + /** + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(gl, properties, dynamicPropertyFlags, size) { + _classCallCheck(this, ParticleBuffer); + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * Size of a single vertex. + * + * @member {number} + */ + this.vertSize = 2; + + /** + * Size of a single vertex in bytes. + * + * @member {number} + */ + this.vertByteSize = this.vertSize * 4; + + /** + * The number of particles the buffer can hold + * + * @member {number} + */ + this.size = size; + + /** + * A list of the properties that are dynamic. + * + * @member {object[]} + */ + this.dynamicProperties = []; + + /** + * A list of the properties that are static. + * + * @member {object[]} + */ + this.staticProperties = []; + + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attribute: property.attribute, + size: property.size, + uploadFunction: property.uploadFunction, + offset: property.offset + }; + + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } else { + this.staticProperties.push(property); + } + } + + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + + this.initBuffers(); + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + ParticleBuffer.prototype.initBuffers = function initBuffers() { + var gl = this.gl; + var dynamicOffset = 0; + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(this.size); + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + this.dynamicStride = 0; + + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + + this.dynamicData = new Float32Array(this.size * this.dynamicStride * 4); + this.dynamicBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.dynamicData, gl.STREAM_DRAW); + + // static // + var staticOffset = 0; + + this.staticStride = 0; + + for (var _i = 0; _i < this.staticProperties.length; ++_i) { + var _property = this.staticProperties[_i]; + + _property.offset = staticOffset; + staticOffset += _property.size; + this.staticStride += _property.size; + } + + this.staticData = new Float32Array(this.size * this.staticStride * 4); + this.staticBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.staticData, gl.STATIC_DRAW); + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(this.indexBuffer); + + for (var _i2 = 0; _i2 < this.dynamicProperties.length; ++_i2) { + var _property2 = this.dynamicProperties[_i2]; + + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.FLOAT, false, this.dynamicStride * 4, _property2.offset * 4); + } + + for (var _i3 = 0; _i3 < this.staticProperties.length; ++_i3) { + var _property3 = this.staticProperties[_i3]; + + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.FLOAT, false, this.staticStride * 4, _property3.offset * 4); + } + }; + + /** + * Uploads the dynamic properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadDynamic = function uploadDynamic(children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + + property.uploadFunction(children, startIndex, amount, this.dynamicData, this.dynamicStride, property.offset); + } + + this.dynamicBuffer.upload(); + }; + + /** + * Uploads the static properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadStatic = function uploadStatic(children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + + property.uploadFunction(children, startIndex, amount, this.staticData, this.staticStride, property.offset); + } + + this.staticBuffer.upload(); + }; + + /** + * Binds the buffers to the GPU + * + */ + + + ParticleBuffer.prototype.bind = function bind() { + this.vao.bind(); + }; + + /** + * Destroys the ParticleBuffer. + * + */ + + + ParticleBuffer.prototype.destroy = function destroy() { + this.dynamicProperties = null; + this.dynamicData = null; + this.dynamicBuffer.destroy(); + + this.staticProperties = null; + this.staticData = null; + this.staticBuffer.destroy(); + }; + + return ParticleBuffer; +}(); + +exports.default = ParticleBuffer; + +},{"../../core/utils/createIndicesForQuads":150,"pixi-gl-core":51}],198:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _ParticleShader = require('./ParticleShader'); + +var _ParticleShader2 = _interopRequireDefault(_ParticleShader); + +var _ParticleBuffer = require('./ParticleBuffer'); + +var _ParticleBuffer2 = _interopRequireDefault(_ParticleBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + +/** + * + * @class + * @private + * @memberof PIXI + */ +var ParticleRenderer = function (_core$ObjectRenderer) { + _inherits(ParticleRenderer, _core$ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + _classCallCheck(this, ParticleRenderer); + + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; + + /** + * The default shader that is used if a sprite doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + + _this.indexBuffer = null; + + _this.properties = null; + + _this.tempMatrix = new core.Matrix(); + + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * When there is a WebGL context change + * + * @private + */ + + + ParticleRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + + // setup default shader + this.shader = new _ParticleShader2.default(gl); + + this.properties = [ + // verticesData + { + attribute: this.shader.attributes.aVertexPosition, + size: 2, + uploadFunction: this.uploadVertices, + offset: 0 + }, + // positionData + { + attribute: this.shader.attributes.aPositionCoord, + size: 2, + uploadFunction: this.uploadPosition, + offset: 0 + }, + // rotationData + { + attribute: this.shader.attributes.aRotation, + size: 1, + uploadFunction: this.uploadRotation, + offset: 0 + }, + // uvsData + { + attribute: this.shader.attributes.aTextureCoord, + size: 2, + uploadFunction: this.uploadUvs, + offset: 0 + }, + // alphaData + { + attribute: this.shader.attributes.aColor, + size: 1, + uploadFunction: this.uploadAlpha, + offset: 0 + }]; + }; + + /** + * Starts a new particle batch. + * + */ + + + ParticleRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + }; + + /** + * Renders the particle container object. + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + */ + + + ParticleRenderer.prototype.render = function render(container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var totalChildren = children.length; + + if (totalChildren === 0) { + return; + } else if (totalChildren > maxSize) { + totalChildren = maxSize; + } + + var buffers = container._glBuffers[this.renderer.CONTEXT_UID]; + + if (!buffers) { + buffers = container._glBuffers[this.renderer.CONTEXT_UID] = this.generateBuffers(container); + } + + // if the uvs have not updated then no point rendering just yet! + this.renderer.setBlendMode(container.blendMode); + + var gl = this.renderer.gl; + + var m = container.worldTransform.copy(this.tempMatrix); + + m.prepend(this.renderer._activeRenderTarget.projectionMatrix); + + this.shader.uniforms.projectionMatrix = m.toArray(true); + this.shader.uniforms.uAlpha = container.worldAlpha; + + // make sure the texture is bound.. + var baseTexture = children[0]._texture.baseTexture; + + this.renderer.bindTexture(baseTexture); + + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = totalChildren - i; + + if (amount > batchSize) { + amount = batchSize; + } + + var buffer = buffers[j]; + + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + + // we only upload the static content when we have to! + if (container._bufferToUpdate === j) { + buffer.uploadStatic(children, i, amount); + container._bufferToUpdate = j + 1; + } + + // bind the buffer + buffer.vao.bind().draw(gl.TRIANGLES, amount * 6).unbind(); + + // now draw those suckas! + // gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0); + // this.renderer.drawCount++; + } + }; + + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer[]} The buffers + */ + + + ParticleRenderer.prototype.generateBuffers = function generateBuffers(container) { + var gl = this.renderer.gl; + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + for (var i = 0; i < size; i += batchSize) { + buffers.push(new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize)); + } + + return buffers; + }; + + /** + * Uploads the verticies. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their vertices uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadVertices = function uploadVertices(children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - sprite.anchor.x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - sprite.anchor.y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - sprite.anchor.x); + w1 = orig.width * -sprite.anchor.x; + + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + + array[offset + stride * 2] = w0 * sx; + array[offset + stride * 2 + 1] = h0 * sy; + + array[offset + stride * 3] = w1 * sx; + array[offset + stride * 3 + 1] = h0 * sy; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their positions uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadPosition = function uploadPosition(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + + array[offset + stride * 2] = spritePosition.x; + array[offset + stride * 2 + 1] = spritePosition.y; + + array[offset + stride * 3] = spritePosition.x; + array[offset + stride * 3 + 1] = spritePosition.y; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadRotation = function uploadRotation(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + stride * 2] = spriteRotation; + array[offset + stride * 3] = spriteRotation; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadUvs = function uploadUvs(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + + array[offset + stride * 2] = textureUvs.x2; + array[offset + stride * 2 + 1] = textureUvs.y2; + + array[offset + stride * 3] = textureUvs.x3; + array[offset + stride * 3 + 1] = textureUvs.y3; + + offset += stride * 4; + } else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + + array[offset + stride * 2] = 0; + array[offset + stride * 2 + 1] = 0; + + array[offset + stride * 3] = 0; + array[offset + stride * 3 + 1] = 0; + + offset += stride * 4; + } + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadAlpha = function uploadAlpha(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteAlpha = children[startIndex + i].alpha; + + array[offset] = spriteAlpha; + array[offset + stride] = spriteAlpha; + array[offset + stride * 2] = spriteAlpha; + array[offset + stride * 3] = spriteAlpha; + + offset += stride * 4; + } + }; + + /** + * Destroys the ParticleRenderer. + * + */ + + + ParticleRenderer.prototype.destroy = function destroy() { + if (this.renderer.gl) { + this.renderer.gl.deleteBuffer(this.indexBuffer); + } + + _core$ObjectRenderer.prototype.destroy.call(this); + + this.shader.destroy(); + + this.indices = null; + this.tempMatrix = null; + }; + + return ParticleRenderer; +}(core.ObjectRenderer); + +exports.default = ParticleRenderer; + + +core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + +},{"../../core":97,"./ParticleBuffer":197,"./ParticleShader":199}],199:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../core/Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI + */ +var ParticleShader = function (_Shader) { + _inherits(ParticleShader, _Shader); + + /** + * @param {PIXI.Shader} gl - The webgl shader manager this shader works for. + */ + function ParticleShader(gl) { + _classCallCheck(this, ParticleShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'attribute float aColor;', 'attribute vec2 aPositionCoord;', 'attribute vec2 aScale;', 'attribute float aRotation;', 'uniform mat3 projectionMatrix;', 'varying vec2 vTextureCoord;', 'varying float vColor;', 'void main(void){', ' vec2 v = aVertexPosition;', ' v.x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);', ' v.y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);', ' v = v + aPositionCoord;', ' gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = aColor;', '}'].join('\n'), + // hello + ['varying vec2 vTextureCoord;', 'varying float vColor;', 'uniform sampler2D uSampler;', 'uniform float uAlpha;', 'void main(void){', ' vec4 color = texture2D(uSampler, vTextureCoord) * vColor * uAlpha;', ' if (color.a == 0.0) discard;', ' gl_FragColor = color;', '}'].join('\n'))); + } + + return ParticleShader; +}(_Shader3.default); + +exports.default = ParticleShader; + +},{"../../core/Shader":77}],200:[function(require,module,exports){ +"use strict"; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + +if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + + if (x === 0 || isNaN(x)) { + return x; + } + + return x > 0 ? 1 : -1; + }; +} + +},{}],201:[function(require,module,exports){ +'use strict'; + +var _objectAssign = require('object-assign'); + +var _objectAssign2 = _interopRequireDefault(_objectAssign); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +if (!Object.assign) { + Object.assign = _objectAssign2.default; +} // References: +// https://github.com/sindresorhus/object-assign +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + +},{"object-assign":43}],202:[function(require,module,exports){ +'use strict'; + +require('./Object.assign'); + +require('./requestAnimationFrame'); + +require('./Math.sign'); + +if (!window.ArrayBuffer) { + window.ArrayBuffer = Array; +} + +if (!window.Float32Array) { + window.Float32Array = Array; +} + +if (!window.Uint32Array) { + window.Uint32Array = Array; +} + +if (!window.Uint16Array) { + window.Uint16Array = Array; +} + +},{"./Math.sign":200,"./Object.assign":201,"./requestAnimationFrame":203}],203:[function(require,module,exports){ +(function (global){ +'use strict'; + +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + +// Expected to be used with Browserfiy +// Browserify automatically detects the use of `global` and passes the +// correct reference of `global`, `self`, and finally `window` + +var ONE_FRAME_TIME = 16; + +// Date.now +if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; +} + +// performance.now +if (!(global.performance && global.performance.now)) { + (function () { + var startTime = Date.now(); + + if (!global.performance) { + global.performance = {}; + } + + global.performance.now = function () { + return Date.now() - startTime; + }; + })(); +} + +// requestAnimationFrame +var lastTime = Date.now(); +var vendors = ['ms', 'moz', 'webkit', 'o']; + +for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { + var p = vendors[x]; + + global.requestAnimationFrame = global[p + 'RequestAnimationFrame']; + global.cancelAnimationFrame = global[p + 'CancelAnimationFrame'] || global[p + 'CancelRequestAnimationFrame']; +} + +if (!global.requestAnimationFrame) { + global.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + 'is not a function'); + } + + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + + if (delay < 0) { + delay = 0; + } + + lastTime = currentTime; + + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} + +if (!global.cancelAnimationFrame) { + global.cancelAnimationFrame = function (id) { + return clearTimeout(id); + }; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],204:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SharedTicker = core.ticker.shared; + +var CANVAS_START_SIZE = 16; +var DEFAULT_UPLOADS_PER_FRAME = 4; + +/** + * The prepare manager provides functionality to upload content to the GPU + * This cannot be done directly for Canvas like in WebGL, but the effect can be achieved by drawing + * textures to an offline canvas. + * This draw call will force the texture to be moved onto the GPU. + * + * @class + * @memberof PIXI + */ + +var CanvasPrepare = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasPrepare(renderer) { + _classCallCheck(this, CanvasPrepare); + + /** + * Reference to the renderer. + * @type {PIXI.CanvasRenderer} + * @private + */ + this.renderer = renderer; + + /** + * An offline canvas to render textures to + * @type {HTMLCanvasElement} + * @private + */ + this.canvas = document.createElement('canvas'); + this.canvas.width = CANVAS_START_SIZE; + this.canvas.height = CANVAS_START_SIZE; + + /** + * The context to the canvas + * @type {CanvasRenderingContext2D} + * @private + */ + this.ctx = this.canvas.getContext('2d'); + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + // Add textures to upload + this.register(findBaseTextures, uploadBaseTextures); + } + + /** + * Upload all the textures and graphics to the GPU. + * + * @param {Function|PIXI.DisplayObject|PIXI.Container} item - Either + * the container or display object to search for items to upload or + * the callback function, if items have been added using `prepare.add`. + * @param {Function} [done] - Optional callback when all queued uploads have completed + */ + + + CanvasPrepare.prototype.upload = function upload(item, done) { + if (typeof item === 'function') { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) { + this.numLeft = CanvasPrepare.UPLOADS_PER_FRAME; + + if (done) { + this.completes.push(done); + } + + if (!this.ticking) { + this.ticking = true; + SharedTicker.add(this.tick, this); + } + } else if (done) { + done(); + } + }; + + /** + * Handle tick update + * + * @private + */ + + + CanvasPrepare.prototype.tick = function tick() { + // Upload the graphics + while (this.queue.length && this.numLeft > 0) { + var item = this.queue[0]; + var uploaded = false; + + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this, item)) { + this.numLeft--; + this.queue.shift(); + uploaded = true; + break; + } + } + + if (!uploaded) { + this.queue.shift(); + } + } + + // We're finished + if (this.queue.length) { + this.numLeft = CanvasPrepare.UPLOADS_PER_FRAME; + } else { + this.ticking = false; + + SharedTicker.remove(this.tick, this); + + var completes = this.completes.slice(0); + + this.completes.length = 0; + + for (var _i = 0, _len = completes.length; _i < _len; _i++) { + completes[_i](); + } + } + }; + + /** + * Adds hooks for finding and uploading items. + * + * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array` + function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + CanvasPrepare.prototype.register = function register(addHook, uploadHook) { + if (addHook) { + this.addHooks.push(addHook); + } + + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + + return this; + }; + + /** + * Manually add an item to the uploading queue. + * + * @param {PIXI.DisplayObject|PIXI.Container|*} item - Object to add to the queue + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + CanvasPrepare.prototype.add = function add(item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) { + for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { + this.add(item.children[_i2]); + } + } + + return this; + }; + + /** + * Destroys the plugin, don't use after this. + * + */ + + + CanvasPrepare.prototype.destroy = function destroy() { + if (this.ticking) { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.ctx = null; + this.canvas = null; + }; + + return CanvasPrepare; +}(); + +/** + * The number of graphics or textures to upload to the GPU. + * + * @static + * @type {number} + * @default 4 + */ + + +exports.default = CanvasPrepare; +CanvasPrepare.UPLOADS_PER_FRAME = DEFAULT_UPLOADS_PER_FRAME; + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {*} prepare - Instance of CanvasPrepare + * @param {*} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadBaseTextures(prepare, item) { + if (item instanceof core.BaseTexture) { + var image = item.source; + + // Sometimes images (like atlas images) report a size of zero, causing errors on windows phone. + // So if the width or height is equal to zero then use the canvas size + // Otherwise use whatever is smaller, the image dimensions or the canvas dimensions. + var imageWidth = image.width === 0 ? prepare.canvas.width : Math.min(prepare.canvas.width, image.width); + var imageHeight = image.height === 0 ? prepare.canvas.height : Math.min(prepare.canvas.height, image.height); + + // Only a small subsections is required to be drawn to have the whole texture uploaded to the GPU + // A smaller draw can be faster. + prepare.ctx.drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, prepare.canvas.width, prepare.canvas.height); + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item -Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTextures(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } else if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); + +},{"../../core":97}],205:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLPrepare = require('./webgl/WebGLPrepare'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLPrepare).default; + } +}); + +var _CanvasPrepare = require('./canvas/CanvasPrepare'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasPrepare).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./canvas/CanvasPrepare":204,"./webgl/WebGLPrepare":206}],206:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SharedTicker = core.ticker.shared; +var DEFAULT_UPLOADS_PER_FRAME = 4; + +/** + * The prepare manager provides functionality to upload content to the GPU. + * + * @class + * @memberof PIXI + */ + +var WebGLPrepare = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLPrepare(renderer) { + _classCallCheck(this, WebGLPrepare); + + /** + * Reference to the renderer. + * @type {PIXI.WebGLRenderer} + * @private + */ + this.renderer = renderer; + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + // Add textures and graphics to upload + this.register(findBaseTextures, uploadBaseTextures).register(findGraphics, uploadGraphics); + } + + /** + * Upload all the textures and graphics to the GPU. + * + * @param {Function|PIXI.DisplayObject|PIXI.Container} item - Either + * the container or display object to search for items to upload or + * the callback function, if items have been added using `prepare.add`. + * @param {Function} [done] - Optional callback when all queued uploads have completed + */ + + + WebGLPrepare.prototype.upload = function upload(item, done) { + if (typeof item === 'function') { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) { + this.numLeft = WebGLPrepare.UPLOADS_PER_FRAME; + + if (done) { + this.completes.push(done); + } + + if (!this.ticking) { + this.ticking = true; + SharedTicker.add(this.tick, this); + } + } else if (done) { + done(); + } + }; + + /** + * Handle tick update. + * + * @private + */ + + + WebGLPrepare.prototype.tick = function tick() { + // Upload the graphics + while (this.queue.length && this.numLeft > 0) { + var item = this.queue[0]; + var uploaded = false; + + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.renderer, item)) { + this.numLeft--; + this.queue.shift(); + uploaded = true; + break; + } + } + + if (!uploaded) { + this.queue.shift(); + } + } + + // We're finished + if (this.queue.length) { + this.numLeft = WebGLPrepare.UPLOADS_PER_FRAME; + } else { + this.ticking = false; + + SharedTicker.remove(this.tick, this); + + var completes = this.completes.slice(0); + + this.completes.length = 0; + + for (var _i = 0, _len = completes.length; _i < _len; _i++) { + completes[_i](); + } + } + }; + + /** + * Adds hooks for finding and uploading items. + * + * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array` + function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] - Function call that takes two parameters: `renderer:WebGLRenderer, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.WebGLPrepare} Instance of plugin for chaining. + */ + + + WebGLPrepare.prototype.register = function register(addHook, uploadHook) { + if (addHook) { + this.addHooks.push(addHook); + } + + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + + return this; + }; + + /** + * Manually add an item to the uploading queue. + * + * @param {PIXI.DisplayObject|PIXI.Container|*} item - Object to add to the queue + * @return {PIXI.WebGLPrepare} Instance of plugin for chaining. + */ + + + WebGLPrepare.prototype.add = function add(item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) { + for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { + this.add(item.children[_i2]); + } + } + + return this; + }; + + /** + * Destroys the plugin, don't use after this. + * + */ + + + WebGLPrepare.prototype.destroy = function destroy() { + if (this.ticking) { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + }; + + return WebGLPrepare; +}(); + +/** + * The number of graphics or textures to upload to the GPU + * + * @static + * @type {number} + * @default 4 + */ + + +exports.default = WebGLPrepare; +WebGLPrepare.UPLOADS_PER_FRAME = DEFAULT_UPLOADS_PER_FRAME; + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadBaseTextures(renderer, item) { + if (item instanceof core.BaseTexture) { + renderer.textureManager.updateTexture(item); + + return true; + } + + return false; +} + +/** + * Built-in hook to upload PIXI.Graphics to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadGraphics(renderer, item) { + if (item instanceof core.Graphics) { + renderer.plugins.graphics.updateGraphics(item); + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTextures(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } else if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find graphics. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Graphics object was found. + */ +function findGraphics(item, queue) { + if (item instanceof core.Graphics) { + queue.push(item); + + return true; + } + + return false; +} + +core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); + +},{"../../core":97}],207:[function(require,module,exports){ +(function (global){ +'use strict'; + +exports.__esModule = true; +exports.loader = exports.prepare = exports.particles = exports.mesh = exports.loaders = exports.interaction = exports.filters = exports.extras = exports.extract = exports.accessibility = undefined; + +var _core = require('./core'); + +Object.keys(_core).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _core[key]; + } + }); +}); + +require('./polyfill'); + +var _accessibility = require('./accessibility'); + +var accessibility = _interopRequireWildcard(_accessibility); + +var _extract = require('./extract'); + +var extract = _interopRequireWildcard(_extract); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +require('./deprecation'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// export lib +exports.accessibility = accessibility; +exports.extract = extract; +exports.extras = extras; +exports.filters = filters; +exports.interaction = interaction; +exports.loaders = loaders; +exports.mesh = mesh; +exports.particles = particles; +exports.prepare = prepare; + +// Mixin the deprecations +// import polyfills first + +/** + * A premade instance of the loader that can be used to loader resources. + * + * @name loader + * @memberof PIXI + * @property {PIXI.loaders.Loader} + */ +var loader = new loaders.Loader(); + +exports.loader = loader; + +// Always export pixi globally. + +global.PIXI = exports; // eslint-disable-line + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"./accessibility":76,"./core":97,"./deprecation":155,"./extract":157,"./extras":165,"./filters":176,"./interaction":182,"./loaders":185,"./mesh":193,"./particles":196,"./polyfill":202,"./prepare":205}]},{},[207])(207) +}); + + +//# sourceMappingURL=pixi.js.map diff --git a/js/pixi/4.0.3-tiling2-custom/pixi.min.js b/js/pixi/4.0.3-tiling2-custom/pixi.min.js new file mode 100644 index 0000000..526727c --- /dev/null +++ b/js/pixi/4.0.3-tiling2-custom/pixi.min.js @@ -0,0 +1,20 @@ +/*! + * pixi.js - v4.0.3 + * Compiled Thu Oct 06 2016 10:23:34 GMT+0300 (EEST) + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.PIXI=t()}}(function(){var t;return function t(e,r,i){function n(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var h=new Error("Cannot find module '"+s+"'");throw h.code="MODULE_NOT_FOUND",h}var l=r[s]={exports:{}};e[s][0].call(l.exports,function(t){var r=e[s][1][t];return n(r?r:t)},l,l.exports,t,e,r,i)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s0)-(t<0)},r.abs=function(t){var e=t>>n-1;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,e|=r,e|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,t=(858993459&t)+(t>>>2&858993459),16843009*(t+(t>>>4)&252645135)>>>24},r.countTrailingZeros=i,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,t&=15,27030>>>t&1};var o=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,i=e,n=7;for(r>>>=1;r;r>>>=1)i<<=1,i|=1&r,--n;t[e]=i<>>8&255]<<16|o[t>>>16&255]<<8|o[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),t=65535&(t|t>>>16),t<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),t=1023&(t|t>>>16),t<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>i(t)+1}},{}],2:[function(t,e,r){"use strict";function i(t,e,r){r=r||2;var i=e&&e.length,o=i?e[0]*r:t.length,a=n(t,0,o,r,!0),u=[];if(!a)return u;var h,l,f,d,p,v,y;if(i&&(a=c(t,e,a,r)),t.length>80*r){h=f=t[0],l=d=t[1];for(var g=r;gf&&(f=p),v>d&&(d=v);y=Math.max(f-h,d-l)}return s(a,u,r,h,l,y),u}function n(t,e,r,i,n){var o,s;if(n===D(t,e,r,i)>0)for(o=e;o=e;o-=i)s=P(o,t[o],t[o+1],s);return s&&T(s,s.next)&&(C(s),s=s.next),s}function o(t,e){if(!t)return t;e||(e=t);var r,i=t;do if(r=!1,i.steiner||!T(i,i.next)&&0!==x(i.prev,i,i.next))i=i.next;else{if(C(i),i=e=i.prev,i===i.next)return null;r=!0}while(r||i!==e);return e}function s(t,e,r,i,n,c,f){if(t){!f&&c&&v(t,i,n,c);for(var d,p,y=t;t.prev!==t.next;)if(d=t.prev,p=t.next,c?u(t,i,n,c):a(t))e.push(d.i/r),e.push(t.i/r),e.push(p.i/r),C(t),t=p.next,y=p.next;else if(t=p,t===y){f?1===f?(t=h(t,e,r),s(t,e,r,i,n,c,2)):2===f&&l(t,e,r,i,n,c):s(o(t),e,r,i,n,c,1);break}}}function a(t){var e=t.prev,r=t,i=t.next;if(x(e,r,i)>=0)return!1;for(var n=t.next.next;n!==t.prev;){if(_(e.x,e.y,r.x,r.y,i.x,i.y,n.x,n.y)&&x(n.prev,n,n.next)>=0)return!1;n=n.next}return!0}function u(t,e,r,i){var n=t.prev,o=t,s=t.next;if(x(n,o,s)>=0)return!1;for(var a=n.xo.x?n.x>s.x?n.x:s.x:o.x>s.x?o.x:s.x,l=n.y>o.y?n.y>s.y?n.y:s.y:o.y>s.y?o.y:s.y,c=g(a,u,e,r,i),f=g(h,l,e,r,i),d=t.nextZ;d&&d.z<=f;){if(d!==t.prev&&d!==t.next&&_(n.x,n.y,o.x,o.y,s.x,s.y,d.x,d.y)&&x(d.prev,d,d.next)>=0)return!1;d=d.nextZ}for(d=t.prevZ;d&&d.z>=c;){if(d!==t.prev&&d!==t.next&&_(n.x,n.y,o.x,o.y,s.x,s.y,d.x,d.y)&&x(d.prev,d,d.next)>=0)return!1;d=d.prevZ}return!0}function h(t,e,r){var i=t;do{var n=i.prev,o=i.next.next;!T(n,o)&&w(n,i,i.next,o)&&S(n,o)&&S(o,n)&&(e.push(n.i/r),e.push(i.i/r),e.push(o.i/r),C(i),C(i.next),i=t=o),i=i.next}while(i!==t);return i}function l(t,e,r,i,n,a){var u=t;do{for(var h=u.next.next;h!==u.prev;){if(u.i!==h.i&&b(u,h)){var l=M(u,h);return u=o(u,u.next),l=o(l,l.next),s(u,e,r,i,n,a),void s(l,e,r,i,n,a)}h=h.next}u=u.next}while(u!==t)}function c(t,e,r,i){var s,a,u,h,l,c=[];for(s=0,a=e.length;s=i.next.y){var a=i.x+(o-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(a<=n&&a>s){if(s=a,a===n){if(o===i.y)return i;if(o===i.next.y)return i.next}r=i.x=i.x&&i.x>=l&&_(or.x)&&S(i,t)&&(r=i,f=u)),i=i.next;return r}function v(t,e,r,i){var n=t;do null===n.z&&(n.z=g(n.x,n.y,e,r,i)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==t);n.prevZ.nextZ=null,n.prevZ=null,y(n)}function y(t){var e,r,i,n,o,s,a,u,h=1;do{for(r=t,t=null,o=null,s=0;r;){for(s++,i=r,a=0,e=0;e0||u>0&&i;)0===a?(n=i,i=i.nextZ,u--):0!==u&&i?r.z<=i.z?(n=r,r=r.nextZ,a--):(n=i,i=i.nextZ,u--):(n=r,r=r.nextZ,a--),o?o.nextZ=n:t=n,n.prevZ=o,o=n;r=i}o.nextZ=null,h*=2}while(s>1);return t}function g(t,e,r,i,n){return t=32767*(t-r)/n,e=32767*(e-i)/n,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1}function m(t){var e=t,r=t;do e.x=0&&(t-s)*(i-a)-(r-s)*(e-a)>=0&&(r-s)*(o-a)-(n-s)*(i-a)>=0}function b(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!E(t,e)&&S(t,e)&&S(e,t)&&O(t,e)}function x(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function T(t,e){return t.x===e.x&&t.y===e.y}function w(t,e,r,i){return!!(T(t,e)&&T(r,i)||T(t,i)&&T(r,e))||x(t,e,r)>0!=x(t,e,i)>0&&x(r,i,t)>0!=x(r,i,e)>0}function E(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&w(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}function S(t,e){return x(t.prev,t,t.next)<0?x(t,e,t.next)>=0&&x(t,t.prev,e)>=0:x(t,e,t.prev)<0||x(t,t.next,e)<0}function O(t,e){var r=t,i=!1,n=(t.x+e.x)/2,o=(t.y+e.y)/2;do r.y>o!=r.next.y>o&&n<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(i=!i),r=r.next;while(r!==t);return i}function M(t,e){var r=new R(t.i,t.x,t.y),i=new R(e.i,e.x,e.y),n=t.next,o=e.prev;return t.next=e,e.prev=t,r.next=n,n.prev=r,i.next=r,r.prev=i,o.next=i,i.prev=o,i}function P(t,e,r,i){var n=new R(t,e,r);return i?(n.next=i.next,n.prev=i,i.next.prev=n,i.next=n):(n.prev=n,n.next=n),n}function C(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function R(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function D(t,e,r,i){for(var n=0,o=e,s=r-i;o0&&(i+=t[n-1].length,r.holes.push(i))}return r}},{}],3:[function(t,e,r){"use strict";function i(){}function n(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function o(){this._events=new i,this._eventsCount=0}var s=Object.prototype.hasOwnProperty,a="~";Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(a=!1)),o.prototype.eventNames=function(){var t,e,r=[];if(0===this._eventsCount)return r;for(e in t=this._events)s.call(t,e)&&r.push(a?e.slice(1):e);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t,e){var r=a?a+t:t,i=this._events[r];if(e)return!!i;if(!i)return[];if(i.fn)return[i.fn];for(var n=0,o=i.length,s=new Array(o);n=0;i--){var n=t[i];"."===n?t.splice(i,1):".."===n?(t.splice(i,1),r++):r&&(t.splice(i,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}function i(t,e){if(t.filter)return t.filter(e);for(var r=[],i=0;i=-1&&!n;o--){var s=o>=0?arguments[o]:t.cwd();if("string"!=typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(r=s+"/"+r,n="/"===s.charAt(0))}return r=e(i(r.split("/"),function(t){return!!t}),!n).join("/"),(n?"/":"")+r||"."},r.normalize=function(t){var n=r.isAbsolute(t),o="/"===s(t,-1);return t=e(i(t.split("/"),function(t){return!!t}),!n).join("/"),t||n||(t="."),t&&o&&(t+="/"),(n?"/":"")+t},r.isAbsolute=function(t){return"/"===t.charAt(0)},r.join=function(){var t=Array.prototype.slice.call(arguments,0);return r.normalize(i(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},r.relative=function(t,e){function i(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=r.resolve(t).substr(1),e=r.resolve(e).substr(1);for(var n=i(t.split("/")),o=i(e.split("/")),s=Math.min(n.length,o.length),a=s,u=0;u=t.byteLength?i.bufferSubData(this.type,e,t):i.bufferData(this.type,t,this.drawType),this.data=t},n.prototype.bind=function(){var t=this.gl;t.bindBuffer(this.type,this.buffer)},n.createVertexBuffer=function(t,e,r){return new n(t,t.ARRAY_BUFFER,e,r)},n.createIndexBuffer=function(t,e,r){return new n(t,t.ELEMENT_ARRAY_BUFFER,e,r)},n.create=function(t,e,r,i){return new n(t,e,i)},n.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer)},e.exports=n},{}],9:[function(t,e,r){var i=t("./GLTexture"),n=function(t,e,r){this.gl=t,this.framebuffer=t.createFramebuffer(),this.stencil=null,this.texture=null,this.width=e||100,this.height=r||100};n.prototype.enableTexture=function(t){var e=this.gl;this.texture=t||new i(e),this.texture.bind(),this.bind(),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0)},n.prototype.enableStencil=function(){if(!this.stencil){var t=this.gl;this.stencil=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.stencil),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.stencil),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,this.width,this.height)}},n.prototype.clear=function(t,e,r,i){this.bind();var n=this.gl;n.clearColor(t,e,r,i),n.clear(n.COLOR_BUFFER_BIT)},n.prototype.bind=function(){var t=this.gl;this.texture&&this.texture.unbind(),t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer)},n.prototype.unbind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)},n.prototype.resize=function(t,e){var r=this.gl;this.width=t,this.height=e,this.texture&&this.texture.uploadData(null,t,e),this.stencil&&(r.bindRenderbuffer(r.RENDERBUFFER,this.stencil),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e))},n.prototype.destroy=function(){var t=this.gl;this.texture&&this.texture.destroy(),t.deleteFramebuffer(this.framebuffer),this.gl=null,this.stencil=null,this.texture=null},n.createRGBA=function(t,e,r){var o=i.fromData(t,null,e,r);o.enableNearestScaling(),o.enableWrapClamp();var s=new n(t,e,r);return s.enableTexture(o),s.unbind(),s},n.createFloat32=function(t,e,r,o){var s=new i.fromData(t,o,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new n(t,e,r);return a.enableTexture(s),a.unbind(),a},e.exports=n},{"./GLTexture":11}],10:[function(t,e,r){var i=t("./shader/compileProgram"),n=t("./shader/extractAttributes"),o=t("./shader/extractUniforms"),s=t("./shader/generateUniformAccessObject"),a=function(t,e,r){this.gl=t,this.program=i(t,e,r),this.attributes=n(t,this.program);var a=o(t,this.program);this.uniforms=s(t,a)};a.prototype.bind=function(){this.gl.useProgram(this.program)},a.prototype.destroy=function(){},e.exports=a},{"./shader/compileProgram":16,"./shader/extractAttributes":18,"./shader/extractUniforms":19,"./shader/generateUniformAccessObject":20}],11:[function(t,e,r){var i=function(t,e,r,i,n){this.gl=t,this.texture=t.createTexture(),this.mipmap=!1,this.premultiplyAlpha=!1,this.width=e||0,this.height=r||0,this.format=i||t.RGBA,this.type=n||t.UNSIGNED_BYTE};i.prototype.upload=function(t){this.bind();var e=this.gl;this.width=t.videoWidth||t.width,this.height=t.videoHeight||t.height,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),e.texImage2D(e.TEXTURE_2D,0,this.format,this.format,this.type,t)};var n=!1;i.prototype.uploadData=function(t,e,r){this.bind();var i=this.gl;if(this.width=e||this.width,this.height=r||this.height,t instanceof Float32Array){if(!n){var o=i.getExtension("OES_texture_float");if(!o)throw new Error("floating point textures not available");n=!0}this.type=i.FLOAT}else this.type=i.UNSIGNED_BYTE;i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.texImage2D(i.TEXTURE_2D,0,this.format,this.width,this.height,0,this.format,this.type,t||null)},i.prototype.bind=function(t){var e=this.gl;void 0!==t&&e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,this.texture)},i.prototype.unbind=function(){var t=this.gl;t.bindTexture(t.TEXTURE_2D,null)},i.prototype.minFilter=function(t){var e=this.gl;this.bind(),this.mipmap?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR:e.NEAREST)},i.prototype.magFilter=function(t){var e=this.gl;this.bind(),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t?e.LINEAR:e.NEAREST)},i.prototype.enableMipmap=function(){var t=this.gl;this.bind(),this.mipmap=!0,t.generateMipmap(t.TEXTURE_2D)},i.prototype.enableLinearScaling=function(){this.minFilter(!0),this.magFilter(!0)},i.prototype.enableNearestScaling=function(){this.minFilter(!1),this.magFilter(!1)},i.prototype.enableWrapClamp=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)},i.prototype.enableWrapRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT)},i.prototype.enableWrapMirrorRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.MIRRORED_REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.MIRRORED_REPEAT)},i.prototype.destroy=function(){var t=this.gl;t.deleteTexture(this.texture)},i.fromSource=function(t,e,r){var n=new i(t);return n.premultiplyAlpha=r||!1,n.upload(e),n},i.fromData=function(t,e,r,n){var o=new i(t);return o.uploadData(e,r,n),o},e.exports=i},{}],12:[function(t,e,r){function i(t,e){if(this.nativeVaoExtension=null,i.FORCE_NATIVE||(this.nativeVaoExtension=t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object")),this.nativeState=e,this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var r=t.getParameter(t.MAX_VERTEX_ATTRIBS);this.nativeState={tempAttribState:new Array(r),attribState:new Array(r)}}this.gl=t,this.attributes=[],this.indexBuffer=null,this.dirty=!1}var n=t("./setVertexAttribArrays");i.prototype.constructor=i,e.exports=i,i.FORCE_NATIVE=!1,i.prototype.bind=function(){return this.nativeVao?(this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao),this.dirty&&(this.dirty=!1,this.activate())):this.activate(),this},i.prototype.unbind=function(){return this.nativeVao&&this.nativeVaoExtension.bindVertexArrayOES(null),this},i.prototype.activate=function(){for(var t=this.gl,e=null,r=0;r1)for(var r=1;r1&&(i=r[0]+"@",t=r[1]),t=t.replace(I,".");var n=t.split("."),o=s(n,e).join(".");return i+o}function u(t){for(var e,r,i=[],n=0,o=t.length;n=55296&&e<=56319&&n65535&&(t-=65536,e+=B(t>>>10&1023|55296),t=56320|1023&t),e+=B(t)}).join("")}function l(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:w}function c(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function f(t,e,r){var i=0;for(t=r?F(t/M):t>>1,t+=F(t/e);t>j*S>>1;i+=w)t=F(t/j);return F(i+(j+1)*t/(t+O))}function d(t){var e,r,i,n,s,a,u,c,d,p,v=[],y=t.length,g=0,m=C,_=P;for(r=t.lastIndexOf(R),r<0&&(r=0),i=0;i=128&&o("not-basic"),v.push(t.charCodeAt(i));for(n=r>0?r+1:0;n=y&&o("invalid-input"),c=l(t.charCodeAt(n++)),(c>=w||c>F((T-g)/a))&&o("overflow"),g+=c*a,d=u<=_?E:u>=_+S?S:u-_,!(cF(T/p)&&o("overflow"),a*=p;e=v.length+1,_=f(g-s,e,0==s),F(g/e)>T-m&&o("overflow"),m+=F(g/e),g%=e,v.splice(g++,0,m)}return h(v)}function p(t){var e,r,i,n,s,a,h,l,d,p,v,y,g,m,_,b=[];for(t=u(t),y=t.length,e=C,r=0,s=P,a=0;a=e&&vF((T-r)/g)&&o("overflow"),r+=(h-e)*g,e=h,a=0;aT&&o("overflow"),v==e){for(l=r,d=w;p=d<=s?E:d>=s+S?S:d-s,!(l= 0x80 (not a basic code point)","invalid-input":"Invalid input"},j=w-E,F=Math.floor,B=String.fromCharCode;if(b={version:"1.4.1",ucs2:{decode:u,encode:h},decode:d,encode:p,toASCII:y,toUnicode:v},"function"==typeof t&&"object"==typeof t.amd&&t.amd)t("punycode",function(){return b});else if(g&&m)if(r.exports==g)m.exports=b;else for(x in b)b.hasOwnProperty(x)&&(g[x]=b[x]);else n.punycode=b}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],26:[function(t,e,r){"use strict";function i(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,r,o){e=e||"&",r=r||"=";var s={};if("string"!=typeof t||0===t.length)return s;var a=/\+/g;t=t.split(e);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var h=t.length;u>0&&h>u&&(h=u);for(var l=0;l=0?(c=v.substr(0,y),f=v.substr(y+1)):(c=v,f=""),d=decodeURIComponent(c),p=decodeURIComponent(f),i(s,d)?n(s[d])?s[d].push(p):s[d]=[s[d],p]:s[d]=p}return s};var n=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],27:[function(t,e,r){"use strict";function i(t,e){if(t.map)return t.map(e);for(var r=[],i=0;i0))return void this.abort("["+t.status+"]"+t.statusText+":"+t.responseURL);if(this.xhrType===i.XHR_RESPONSE_TYPE.TEXT)this.data=t.responseText;else if(this.xhrType===i.XHR_RESPONSE_TYPE.JSON)try{this.data=JSON.parse(t.responseText),this.isJson=!0}catch(t){return void this.abort("Error trying to parse loaded json:",t)}else if(this.xhrType===i.XHR_RESPONSE_TYPE.DOCUMENT)try{if(window.DOMParser){var r=new DOMParser;this.data=r.parseFromString(t.responseText,"text/xml")}else{var n=document.createElement("div");n.innerHTML=t.responseText,this.data=n}this.isXml=!0}catch(t){return void this.abort("Error trying to parse loaded xml:",t)}else this.data=t.response||t.responseText;this.complete()},i.prototype._determineCrossOrigin=function(t,e){if(0===t.indexOf("data:"))return"";e=e||window.location,h||(h=document.createElement("a")),h.href=t,t=a(h.href,{strictMode:!0});var r=!t.port&&""===e.port||t.port===e.port,i=t.protocol?t.protocol+":":"";return t.host===e.hostname&&r&&i===e.protocol?"":"anonymous"},i.prototype._determineXhrType=function(){return i._xhrTypeMap[this._getExtension()]||i.XHR_RESPONSE_TYPE.TEXT},i.prototype._determineLoadType=function(){return i._loadTypeMap[this._getExtension()]||i.LOAD_TYPE.XHR},i.prototype._getExtension=function(){var t=this.url,e="";if(this.isDataUrl){var r=t.indexOf("/");e=t.substring(r+1,t.indexOf(";",r))}else{var i=t.indexOf("?");i!==-1&&(t=t.substring(0,i)),e=t.substring(t.lastIndexOf(".")+1)}return e.toLowerCase()},i.prototype._getMimeFromXhrType=function(t){switch(t){case i.XHR_RESPONSE_TYPE.BUFFER:return"application/octet-binary";case i.XHR_RESPONSE_TYPE.BLOB:return"application/blob";case i.XHR_RESPONSE_TYPE.DOCUMENT:return"application/xml";case i.XHR_RESPONSE_TYPE.JSON:return"application/json";case i.XHR_RESPONSE_TYPE.DEFAULT:case i.XHR_RESPONSE_TYPE.TEXT:default:return"text/plain"}},i.LOAD_TYPE={XHR:1,IMAGE:2,AUDIO:3,VIDEO:4},i.XHR_RESPONSE_TYPE={DEFAULT:"text",BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"},i._loadTypeMap={gif:i.LOAD_TYPE.IMAGE,png:i.LOAD_TYPE.IMAGE,bmp:i.LOAD_TYPE.IMAGE,jpg:i.LOAD_TYPE.IMAGE,jpeg:i.LOAD_TYPE.IMAGE,tif:i.LOAD_TYPE.IMAGE,tiff:i.LOAD_TYPE.IMAGE,webp:i.LOAD_TYPE.IMAGE,tga:i.LOAD_TYPE.IMAGE,"svg+xml":i.LOAD_TYPE.IMAGE},i._xhrTypeMap={xhtml:i.XHR_RESPONSE_TYPE.DOCUMENT,html:i.XHR_RESPONSE_TYPE.DOCUMENT,htm:i.XHR_RESPONSE_TYPE.DOCUMENT,xml:i.XHR_RESPONSE_TYPE.DOCUMENT,tmx:i.XHR_RESPONSE_TYPE.DOCUMENT,tsx:i.XHR_RESPONSE_TYPE.DOCUMENT,svg:i.XHR_RESPONSE_TYPE.DOCUMENT,gif:i.XHR_RESPONSE_TYPE.BLOB,png:i.XHR_RESPONSE_TYPE.BLOB,bmp:i.XHR_RESPONSE_TYPE.BLOB,jpg:i.XHR_RESPONSE_TYPE.BLOB,jpeg:i.XHR_RESPONSE_TYPE.BLOB,tif:i.XHR_RESPONSE_TYPE.BLOB,tiff:i.XHR_RESPONSE_TYPE.BLOB,webp:i.XHR_RESPONSE_TYPE.BLOB,tga:i.XHR_RESPONSE_TYPE.BLOB,json:i.XHR_RESPONSE_TYPE.JSON,text:i.XHR_RESPONSE_TYPE.TEXT,txt:i.XHR_RESPONSE_TYPE.TEXT},i.setExtensionLoadType=function(t,e){o(i._loadTypeMap,t,e)},i.setExtensionXhrType=function(t,e){o(i._xhrTypeMap,t,e)}},{eventemitter3:3,"parse-uri":6}],31:[function(t,e,r){"use strict";function i(){}function n(t,e,r){var i=0,n=t.length;!function o(s){return s||i===n?void(r&&r(s)):void e(t[i++],o)}()}function o(t){return function(){if(null===t)throw new Error("Callback was already called.");var e=t;t=null,e.apply(this,arguments)}}function s(t,e){function r(t,e,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(a.started=!0,null==t&&a.idle())return void setTimeout(function(){a.drain()},1);var n={data:t,callback:"function"==typeof r?r:i};e?a._tasks.unshift(n):a._tasks.push(n),setTimeout(function(){a.process()},1)}function n(t){return function(){s-=1,t.callback.apply(t,arguments),null!=arguments[0]&&a.error(arguments[0],t.data),s<=a.concurrency-a.buffer&&a.unsaturated(),a.idle()&&a.drain(),a.process()}}if(null==e)e=1;else if(0===e)throw new Error("Concurrency must not be zero");var s=0,a={_tasks:[],concurrency:e,saturated:i,unsaturated:i,buffer:e/4,empty:i,drain:i,error:i,started:!1,paused:!1,push:function(t,e){r(t,!1,e)},kill:function(){a.drain=i,a._tasks=[]},unshift:function(t,e){r(t,!0,e)},process:function(){for(;!a.paused&&s>2,i[1]=(3&e[0])<<4|e[1]>>4,i[2]=(15&e[1])<<2|e[2]>>6,i[3]=63&e[2],s=n-(t.length-1)){case 2:i[3]=64,i[2]=64;break;case 1:i[3]=64}for(o=0;o",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(d),v=["'"].concat(p),y=["%","/","?",";","#"].concat(v),g=["/","?","#"],m=255,_=/^[+a-z0-9A-Z_-]{0,63}$/,b=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,x={javascript:!0,"javascript:":!0},T={javascript:!0,"javascript:":!0},w={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},E=t("querystring");i.prototype.parse=function(t,e,r){if(!h.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var i=t.indexOf("?"),n=i!==-1&&i127?"x":L[F];if(!j.match(_)){var k=A.slice(0,M),N=A.slice(M+1),U=L.match(b);U&&(k.push(U[1]),N.unshift(U[2])),N.length&&(a="/"+N.join(".")+a),this.hostname=k.join(".");break}}}this.hostname.length>m?this.hostname="":this.hostname=this.hostname.toLowerCase(),D||(this.hostname=u.toASCII(this.hostname));var X=this.port?":"+this.port:"",W=this.hostname||"";this.host=W+X,this.href+=this.host,D&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==a[0]&&(a="/"+a))}if(!x[p])for(var M=0,I=v.length;M0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return r.search=t.search,r.query=t.query,h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!x.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var O=x.slice(-1)[0],M=(r.host||t.host||x.length>1)&&("."===O||".."===O)||""===O,P=0,C=x.length;C>=0;C--)O=x[C],"."===O?x.splice(C,1):".."===O?(x.splice(C,1),P++):P&&(x.splice(C,1),P--);if(!_&&!b)for(;P--;P)x.unshift("..");!_||""===x[0]||x[0]&&"/"===x[0].charAt(0)||x.unshift(""),M&&"/"!==x.join("/").substr(-1)&&x.push("");var R=""===x[0]||x[0]&&"/"===x[0].charAt(0);if(E){r.hostname=r.host=R?"":x.length?x.shift():"";var S=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return _=_||r.host&&x.length,_&&!R&&x.unshift(""),x.length?r.pathname=x.join("/"):(r.pathname=null,r.path=null),h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},i.prototype.parseHost=function(){var t=this.host,e=c.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":37,punycode:25,querystring:28}],37:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],38:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var s=t("../core"),a=n(s),u=t("ismobilejs"),h=i(u),l=t("./accessibleTarget"),c=i(l);Object.assign(a.DisplayObject.prototype,c.default);var f=9,d=100,p=0,v=0,y=2,g=1,m=-1e3,_=-1e3,b=2,x=function(){function t(e){o(this,t),!h.default.tablet&&!h.default.phone||navigator.isCocoonJS||this.createTouchHook();var r=document.createElement("div");r.style.width=d+"px",r.style.height=d+"px",r.style.position="absolute",r.style.top=p+"px",r.style.left=v+"px",r.style.zIndex=y,this.div=r,this.pool=[],this.renderId=0,this.debug=!1,this.renderer=e,this.children=[],this._onKeyDown=this._onKeyDown.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this.isActive=!1,this.isMobileAccessabillity=!1,window.addEventListener("keydown",this._onKeyDown,!1)}return t.prototype.createTouchHook=function(){var t=this,e=document.createElement("button");e.style.width=g+"px",e.style.height=g+"px",e.style.position="absolute",e.style.top=m+"px",e.style.left=_+"px",e.style.zIndex=b,e.style.backgroundColor="#FF0000",e.title="HOOK DIV",e.addEventListener("focus",function(){t.isMobileAccessabillity=!0,t.activate(),document.body.removeChild(e)}),document.body.appendChild(e)},t.prototype.activate=function(){this.isActive||(this.isActive=!0,window.document.addEventListener("mousemove",this._onMouseMove,!0),window.removeEventListener("keydown",this._onKeyDown,!1),this.renderer.on("postrender",this.update,this),this.renderer.view.parentNode&&this.renderer.view.parentNode.appendChild(this.div))},t.prototype.deactivate=function(){this.isActive&&!this.isMobileAccessabillity&&(this.isActive=!1,window.document.removeEventListener("mousemove",this._onMouseMove),window.addEventListener("keydown",this._onKeyDown,!1),this.renderer.off("postrender",this.update),this.div.parentNode&&this.div.parentNode.removeChild(this.div))},t.prototype.updateAccessibleObjects=function(t){if(t.visible){t.accessible&&t.interactive&&(t._accessibleActive||this.addChild(t),t.renderId=this.renderId);for(var e=t.children,r=e.length-1;r>=0;r--)this.updateAccessibleObjects(e[r])}},t.prototype.update=function(){if(this.renderer.renderingToScreen){this.updateAccessibleObjects(this.renderer._lastObjectRendered);var t=this.renderer.view.getBoundingClientRect(),e=t.width/this.renderer.width,r=t.height/this.renderer.height,i=this.div;i.style.left=t.left+"px",i.style.top=t.top+"px",i.style.width=this.renderer.width+"px",i.style.height=this.renderer.height+"px";for(var n=0;nthis.renderer.width&&(t.width=this.renderer.width-t.x),t.y+t.height>this.renderer.height&&(t.height=this.renderer.height-t.y)},t.prototype.addChild=function(t){var e=this.pool.pop();e||(e=document.createElement("button"),e.style.width=d+"px",e.style.height=d+"px",e.style.backgroundColor=this.debug?"rgba(255,0,0,0.5)":"transparent",e.style.position="absolute",e.style.zIndex=y,e.style.borderStyle="none",e.addEventListener("click",this._onClick.bind(this)),e.addEventListener("focus",this._onFocus.bind(this)),e.addEventListener("focusout",this._onFocusOut.bind(this))),t.accessibleTitle?e.title=t.accessibleTitle:t.accessibleTitle||t.accessibleHint||(e.title="displayObject "+this.tabIndex),t.accessibleHint&&e.setAttribute("aria-label",t.accessibleHint),t._accessibleActive=!0,t._accessibleDiv=e,e.displayObject=t,this.children.push(t),this.div.appendChild(t._accessibleDiv),t._accessibleDiv.tabIndex=t.tabIndex},t.prototype._onClick=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"click",e.eventData)},t.prototype._onFocus=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseover",e.eventData)},t.prototype._onFocusOut=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseout",e.eventData)},t.prototype._onKeyDown=function(t){t.keyCode===f&&this.activate()},t.prototype._onMouseMove=function(){this.deactivate()},t.prototype.destroy=function(){this.div=null;for(var t=0;t]*(?:\s(width|height)="(\d*(?:\.\d+)?)(?:px)?")[^>]*(?:\s(width|height)="(\d*(?:\.\d+)?)(?:px)?")[^>]*>/i,r.SHAPES={POLY:0,RECT:1,CIRC:2,ELIP:3,RREC:4},r.PRECISION={DEFAULT:"mediump",LOW:"lowp",MEDIUM:"mediump",HIGH:"highp"},r.TRANSFORM_MODE={DEFAULT:0,STATIC:0,DYNAMIC:1},r.TEXT_GRADIENT={LINEAR_VERTICAL:0,LINEAR_HORIZONTAL:1},r.SPRITE_BATCH_SIZE=4096,r.SPRITE_MAX_TEXTURES=(0,o.default)(32)},{"./utils/maxRecommendedTextures":116}],43:[function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var n=t("../math"),o=function(){function t(){i(this,t),this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0),this.rect=null}return t.prototype.isEmpty=function(){return this.minX>this.maxX||this.minY>this.maxY},t.prototype.clear=function(){this.updateID++,this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0)},t.prototype.getRectangle=function(t){return this.minX>this.maxX||this.minY>this.maxY?n.Rectangle.EMPTY:(t=t||new n.Rectangle(0,0,1,1),t.x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)},t.prototype.addPoint=function(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)},t.prototype.addQuad=function(t){var e=this.minX,r=this.minY,i=this.maxX,n=this.maxY,o=t[0],s=t[1];e=oi?o:i,n=s>n?s:n,o=t[2],s=t[3],e=oi?o:i,n=s>n?s:n,o=t[4],s=t[5],e=oi?o:i,n=s>n?s:n,o=t[6],s=t[7],e=oi?o:i,n=s>n?s:n,this.minX=e,this.minY=r,this.maxX=i,this.maxY=n},t.prototype.addFrame=function(t,e,r,i,n){var o=t.worldTransform,s=o.a,a=o.b,u=o.c,h=o.d,l=o.tx,c=o.ty,f=this.minX,d=this.minY,p=this.maxX,v=this.maxY,y=s*e+u*r+l,g=a*e+h*r+c;f=yp?y:p,v=g>v?g:v,y=s*i+u*r+l,g=a*i+h*r+c,f=yp?y:p,v=g>v?g:v,y=s*e+u*n+l,g=a*e+h*n+c,f=yp?y:p,v=g>v?g:v,y=s*i+u*n+l,g=a*i+h*n+c,f=yp?y:p,v=g>v?g:v,this.minX=f,this.minY=d,this.maxX=p,this.maxY=v},t.prototype.addVertices=function(t,e,r,i){for(var n=t.worldTransform,o=n.a,s=n.b,a=n.c,u=n.d,h=n.tx,l=n.ty,c=this.minX,f=this.minY,d=this.maxX,p=this.maxY,v=r;vd?m:d,p=_>p?_:p}this.minX=c,this.minY=f,this.maxX=d,this.maxY=p},t.prototype.addBounds=function(t){var e=this.minX,r=this.minY,i=this.maxX,n=this.maxY;this.minX=t.minXi?t.maxX:i,this.maxY=t.maxY>n?t.maxY:n},t.prototype.addBoundsMask=function(t,e){var r=t.minX>e.minX?t.minX:e.minX,i=t.minY>e.minY?t.minY:e.minY,n=t.maxXu?n:u,this.maxY=o>h?o:h}},t.prototype.addBoundsArea=function(t,e){var r=t.minX>e.x?t.minX:e.x,i=t.minY>e.y?t.minY:e.y,n=t.maxXu?n:u,this.maxY=o>h?o:h}},t}();r.default=o},{"../math":66}],44:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rthis.children.length)throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length);return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),this.onChildrenChange(e),t.emit("added",this),t},e.prototype.swapChildren=function(t,e){if(t!==e){var r=this.getChildIndex(t),i=this.getChildIndex(e);if(r<0||i<0)throw new Error("swapChildren: Both the supplied DisplayObjects must be children of the caller.");this.children[r]=e,this.children[i]=t,this.onChildrenChange(r=this.children.length)throw new Error("The supplied index is out of bounds");var r=this.getChildIndex(t);(0,u.removeItems)(this.children,r,1),this.children.splice(e,0,t),this.onChildrenChange(e)},e.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Index ("+t+") does not exist.");return this.children[t]},e.prototype.removeChild=function(){for(var t=arguments.length,e=Array(t),r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=t,i="number"==typeof e?e:this.children.length,n=i-r,o=void 0;if(n>0&&n<=i){o=this.children.splice(r,n);for(var s=0;s2&&void 0!==arguments[2]&&arguments[2];return r||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)},e.prototype.toLocal=function(t,e,r,i){return e&&(t=e.toGlobal(t,r,i)),i||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,r)},e.prototype.renderWebGL=function(t){},e.prototype.renderCanvas=function(t){},e.prototype.setParent=function(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t},e.prototype.setTransform=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0,u=arguments.length>8&&void 0!==arguments[8]?arguments[8]:0;return this.position.x=t,this.position.y=e,this.scale.x=r?r:1,this.scale.y=i?i:1,this.rotation=n,this.skew.x=o,this.skew.y=s,this.pivot.x=a,this.pivot.y=u,this},e.prototype.destroy=function(){this.removeAllListeners(),this.parent&&this.parent.removeChild(this),this.transform=null,this.parent=null,this._bounds=null,this._currentBounds=null,this._mask=null,this.filterArea=null,this.interactive=!1,this.interactiveChildren=!1},a(e,[{key:"_tempDisplayObjectParent",get:function(){return null===this.tempDisplayObjectParent&&(this.tempDisplayObjectParent=new e),this.tempDisplayObjectParent}},{key:"x",get:function(){return this.position.x},set:function(t){this.transform.position.x=t}},{key:"y",get:function(){return this.position.y},set:function(t){this.transform.position.y=t}},{key:"worldTransform",get:function(){return this.transform.worldTransform}},{key:"localTransform",get:function(){return this.transform.localTransform}},{key:"position",get:function(){return this.transform.position},set:function(t){this.transform.position.copy(t)}},{key:"scale",get:function(){return this.transform.scale},set:function(t){this.transform.scale.copy(t)}},{key:"pivot",get:function(){return this.transform.pivot},set:function(t){this.transform.pivot.copy(t)}},{key:"skew",get:function(){return this.transform.skew},set:function(t){this.transform.skew.copy(t)}},{key:"rotation",get:function(){return this.transform.rotation},set:function(t){this.transform.rotation=t}},{key:"worldVisible",get:function(){var t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask&&(this._mask.renderable=!0),this._mask=t,this._mask&&(this._mask.renderable=!1)}},{key:"filters",get:function(){return this._filters&&this._filters.slice()},set:function(t){this._filters=t&&t.slice()}}]),e}(h.default);r.default=m,m.prototype.displayObjectUpdateTransform=m.prototype.updateTransform},{"../const":42,"../math":66,"./Bounds":43,"./Transform":46,"./TransformStatic":48,eventemitter3:3}],46:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;if(this.lineWidth=t,this.lineColor=e,this.lineAlpha=r,this.currentPath)if(this.currentPath.shape.points.length){var i=new g.Polygon(this.currentPath.shape.points.slice(-2));i.closed=!1,this.drawShape(i)}else this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha;return this},e.prototype.moveTo=function(t,e){var r=new g.Polygon([t,e]);return r.closed=!1,this.drawShape(r),this},e.prototype.lineTo=function(t,e){return this.currentPath.shape.points.push(t,e),this.dirty++,this},e.prototype.quadraticCurveTo=function(t,e,r,i){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var n=20,o=this.currentPath.shape.points,s=0,a=0;0===o.length&&this.moveTo(0,0);for(var u=o[o.length-2],h=o[o.length-1],l=1;l<=n;++l){var c=l/n;s=u+(t-u)*c,a=h+(e-h)*c,o.push(s+(t+(r-t)*c-s)*c,a+(e+(i-e)*c-a)*c)}return this.dirty++,this},e.prototype.bezierCurveTo=function(t,e,r,i,n,o){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var s=this.currentPath.shape.points,a=s[s.length-2],u=s[s.length-1];return s.length-=2,(0,w.default)(a,u,t,e,r,i,n,o,s),this.dirty++,this},e.prototype.arcTo=function(t,e,r,i,n){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(t,e):this.moveTo(t,e);var o=this.currentPath.shape.points,s=o[o.length-2],a=o[o.length-1],u=a-e,h=s-t,l=i-e,c=r-t,f=Math.abs(u*c-h*l);if(f<1e-8||0===n)o[o.length-2]===t&&o[o.length-1]===e||o.push(t,e);else{var d=u*u+h*h,p=l*l+c*c,v=u*l+h*c,y=n*Math.sqrt(d)/f,g=n*Math.sqrt(p)/f,m=y*v/d,_=g*v/p,b=y*c+g*h,x=y*l+g*u,T=h*(g+m),w=u*(g+m),E=c*(y+_),S=l*(y+_),O=Math.atan2(w-x,T-b),M=Math.atan2(S-x,E-b);this.arc(b+t,x+e,n,O,M,h*l>c*u)}return this.dirty++,this},e.prototype.arc=function(t,e,r,i,n){var o=arguments.length>5&&void 0!==arguments[5]&&arguments[5];if(i===n)return this;!o&&n<=i?n+=2*Math.PI:o&&i<=n&&(i+=2*Math.PI);var s=o?(i-n)*-1:n-i,a=40*Math.ceil(Math.abs(s)/(2*Math.PI));if(0===s)return this;var u=t+Math.cos(i)*r,h=e+Math.sin(i)*r; +this.currentPath?this.currentPath.shape.points.push(u,h):this.moveTo(u,h);for(var l=this.currentPath.shape.points,c=s/(2*a),f=2*c,d=Math.cos(c),p=Math.sin(c),v=a-1,y=v%1/v,g=0;g<=v;++g){var m=g+y*g,_=c+i+f*m,b=Math.cos(_),x=-Math.sin(_);l.push((d*b+p*x)*r+t,(d*-x+p*b)*r+e)}return this.dirty++,this},e.prototype.beginFill=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this.filling=!0,this.fillColor=t,this.fillAlpha=e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},e.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},e.prototype.drawRect=function(t,e,r,i){return this.drawShape(new g.Rectangle(t,e,r,i)),this},e.prototype.drawRoundedRect=function(t,e,r,i,n){return this.drawShape(new g.RoundedRectangle(t,e,r,i,n)),this},e.prototype.drawCircle=function(t,e,r){return this.drawShape(new g.Circle(t,e,r)),this},e.prototype.drawEllipse=function(t,e,r,i){return this.drawShape(new g.Ellipse(t,e,r,i)),this},e.prototype.drawPolygon=function(t){var e=t,r=!0;if(e instanceof g.Polygon&&(r=e.closed,e=e.points),!Array.isArray(e)){e=new Array(arguments.length);for(var i=0;i0)&&(this.lineWidth=0,this.filling=!1,this.dirty++,this.clearDirty++,this.graphicsData.length=0),this},e.prototype.isFastRect=function(){return 1===this.graphicsData.length&&this.graphicsData[0].shape.type===_.SHAPES.RECT&&!this.graphicsData[0].lineWidth},e.prototype._renderWebGL=function(t){this.dirty!==this.fastRectDirty&&(this.fastRectDirty=this.dirty,this._fastRect=this.isFastRect()),this._fastRect?this._renderSpriteRect(t):(t.setObjectRenderer(t.plugins.graphics),t.plugins.graphics.render(this))},e.prototype._renderSpriteRect=function(t){var r=this.graphicsData[0].shape;if(!this._spriteRect){if(!e._SPRITE_TEXTURE){e._SPRITE_TEXTURE=l.default.create(10,10);var i=document.createElement("canvas");i.width=10,i.height=10;var n=i.getContext("2d");n.fillStyle="white",n.fillRect(0,0,10,10),e._SPRITE_TEXTURE=f.default.fromCanvas(i)}this._spriteRect=new y.default(e._SPRITE_TEXTURE)}if(16777215===this.tint)this._spriteRect.tint=this.graphicsData[0].fillColor;else{var o=C,s=R;(0,m.hex2rgb)(this.graphicsData[0].fillColor,o),(0,m.hex2rgb)(this.tint,s),o[0]*=s[0],o[1]*=s[1],o[2]*=s[2],this._spriteRect.tint=(0,m.rgb2hex)(o)}this._spriteRect.alpha=this.graphicsData[0].fillAlpha,this._spriteRect.worldAlpha=this.worldAlpha*this._spriteRect.alpha,e._SPRITE_TEXTURE._frame.width=r.width,e._SPRITE_TEXTURE._frame.height=r.height,this._spriteRect.transform.worldTransform=this.transform.worldTransform,this._spriteRect.anchor.set(-r.x/r.width,-r.y/r.height),this._spriteRect._onAnchorUpdate(),this._spriteRect._renderWebGL(t)},e.prototype._renderCanvas=function(t){this.isMask!==!0&&t.plugins.graphics.render(this)},e.prototype._calculateBounds=function(){this.boundsDirty!==this.dirty&&(this.boundsDirty=this.dirty,this.updateLocalBounds(),this.dirty++,this.cachedSpriteDirty=!0);var t=this._localBounds;this._bounds.addFrame(this.transform,t.minX,t.minY,t.maxX,t.maxY)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,P);for(var e=this.graphicsData,r=0;re?o+a:e,r=si?s+u:i;else if(c===_.SHAPES.CIRC)o=n.x,s=n.y,a=n.radius+f/2,u=n.radius+f/2,t=o-ae?o+a:e,r=s-ui?s+u:i;else if(c===_.SHAPES.ELIP)o=n.x,s=n.y,a=n.width+f/2,u=n.height+f/2,t=o-ae?o+a:e,r=s-ui?s+u:i;else for(var d=n.points,p=0;pe?o+f:e,r=s-fi?s+f:i}else t=0,e=0,r=0,i=0;var v=this.boundsPadding;this._localBounds.minX=t-v,this._localBounds.maxX=e+2*v,this._localBounds.minY=r-v,this._localBounds.maxY=i+2*v},e.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null;var e=new p.default(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===_.SHAPES.POLY&&(e.shape.closed=e.shape.closed||this.filling,this.currentPath=e),this.dirty++,e},e.prototype.generateCanvasTexture=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=this.getLocalBounds(),i=l.default.create(r.width,r.height,t,e);O||(O=new S.default),M.tx=-r.x,M.ty=-r.y,O.render(this,i,!1,M);var n=f.default.fromCanvas(i.baseTexture._canvasRenderTarget.canvas,t);return n.baseTexture.resolution=e,n.baseTexture.update(),n},e.prototype.closePath=function(){var t=this.currentPath;return t&&t.shape&&t.shape.close(),this},e.prototype.addHole=function(){var t=this.graphicsData.pop();return this.currentPath=this.graphicsData[this.graphicsData.length-1],this.currentPath.addHole(t.shape),this.currentPath=null,this},e.prototype.destroy=function(e){t.prototype.destroy.call(this,e);for(var r=0;rC?C:P,r.beginPath(),r.moveTo(E,S+P),r.lineTo(E,S+M-P),r.quadraticCurveTo(E,S+M,E+P,S+M),r.lineTo(E+O-P,S+M),r.quadraticCurveTo(E+O,S+M,E+O,S+M-P),r.lineTo(E+O,S+P),r.quadraticCurveTo(E+O,S,E+O-P,S),r.lineTo(E+P,S),r.quadraticCurveTo(E,S,E,S+P),r.closePath(),(u.fillColor||0===u.fillColor)&&(r.globalAlpha=u.fillAlpha*i,r.fillStyle="#"+("00000"+(0|l).toString(16)).substr(-6),r.fill()),u.lineWidth&&(r.globalAlpha=u.lineAlpha*i,r.strokeStyle="#"+("00000"+(0|c).toString(16)).substr(-6),r.stroke())}}},t.prototype.updateGraphicsTint=function(t){t._prevTint=t.tint;for(var e=(t.tint>>16&255)/255,r=(t.tint>>8&255)/255,i=(255&t.tint)/255,n=0;n>16&255)/255*e*255<<16)+((s>>8&255)/255*r*255<<8)+(255&s)/255*i*255,o._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*r*255<<8)+(255&a)/255*i*255}},t.prototype.renderPolygon=function(t,e,r){r.moveTo(t[0],t[1]);for(var i=1;i8&&void 0!==arguments[8]?arguments[8]:[],h=20,l=0,c=0,f=0,d=0,p=0;u.push(t,e);for(var v=1,y=0;v<=h;++v)y=v/h,l=1-y,c=l*l,f=c*l,d=y*y,p=d*y,u.push(f*t+3*c*y*r+3*l*d*n+p*s,f*e+3*c*y*i+3*l*d*o+p*a);return u}r.__esModule=!0,r.default=i},{}],53:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../utils"),u=t("../../const"),h=t("../../renderers/webgl/utils/ObjectRenderer"),l=i(h),c=t("../../renderers/webgl/WebGLRenderer"),f=i(c),d=t("./WebGLGraphicsData"),p=i(d),v=t("./shaders/PrimitiveShader"),y=i(v),g=t("./utils/buildPoly"),m=i(g),_=t("./utils/buildRectangle"),b=i(_),x=t("./utils/buildRoundedRectangle"),T=i(x),w=t("./utils/buildCircle"),E=i(w),S=function(t){function e(r){n(this,e);var i=o(this,t.call(this,r));return i.graphicsDataPool=[],i.primitiveShader=null,i.gl=r.gl,i.CONTEXT_UID=0,i}return s(e,t),e.prototype.onContextChange=function(){this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.primitiveShader=new y.default(this.gl)},e.prototype.destroy=function(){l.default.prototype.destroy.call(this);for(var t=0;t32e4)&&(r=this.graphicsDataPool.pop()||new p.default(this.renderer.gl,this.primitiveShader,this.renderer.state.attribsState),r.reset(e),t.data.push(r)),r.dirty=!0,r},e}(l.default);r.default=S,f.default.registerPlugin("graphics",S)},{"../../const":42,"../../renderers/webgl/WebGLRenderer":80,"../../renderers/webgl/utils/ObjectRenderer":90,"../../utils":115,"./WebGLGraphicsData":54,"./shaders/PrimitiveShader":55,"./utils/buildCircle":56,"./utils/buildPoly":58,"./utils/buildRectangle":59,"./utils/buildRoundedRectangle":60}],54:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("pixi-gl-core"),s=i(o),a=function(){function t(e,r,i){n(this,t),this.gl=e,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=s.default.GLBuffer.createVertexBuffer(e),this.indexBuffer=s.default.GLBuffer.createIndexBuffer(e),this.dirty=!0,this.glPoints=null,this.glIndices=null,this.shader=r,this.vao=new s.default.VertexArrayObject(e,i).addIndex(this.indexBuffer).addAttribute(this.buffer,r.attributes.aVertexPosition,e.FLOAT,!1,24,0).addAttribute(this.buffer,r.attributes.aColor,e.FLOAT,!1,24,8)}return t.prototype.reset=function(){this.points.length=0,this.indices.length=0},t.prototype.upload=function(){this.glPoints=new Float32Array(this.points),this.buffer.upload(this.glPoints),this.glIndices=new Uint16Array(this.indices),this.indexBuffer.upload(this.glIndices),this.dirty=!1},t.prototype.destroy=function(){this.color=null,this.points=null,this.indices=null,this.vao.destroy(),this.buffer.destroy(),this.indexBuffer.destroy(),this.gl=null,this.buffer=null,this.indexBuffer=null,this.glPoints=null,this.glIndices=null},t}();r.default=a},{"pixi-gl-core":14}],55:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../../Shader"),u=i(a),h=function(t){function e(r){return n(this,e),o(this,t.call(this,r,["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","uniform float alpha;","uniform vec3 tint;","varying vec4 vColor;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"].join("\n"),["varying vec4 vColor;","void main(void){"," gl_FragColor = vColor;","}"].join("\n")))}return s(e,t),e}(u.default);r.default=h},{"../../../Shader":41}],56:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){var r=t.shape,i=r.x,n=r.y,o=void 0,h=void 0;t.type===a.SHAPES.CIRC?(o=r.radius,h=r.radius):(o=r.width,h=r.height);var l=Math.floor(30*Math.sqrt(r.radius))||Math.floor(15*Math.sqrt(r.width+r.height)),c=2*Math.PI/l;if(t.fill){var f=(0,u.hex2rgb)(t.fillColor),d=t.fillAlpha,p=f[0]*d,v=f[1]*d,y=f[2]*d,g=e.points,m=e.indices,_=g.length/6;m.push(_);for(var b=0;b196*p*p?(R=O-P,D=M-C,A=Math.sqrt(R*R+D*D),R/=A,D/=A,R*=p,D*=p,h.push(T-R,w-D),h.push(g,m,_,y),h.push(T+R,w+D),h.push(g,m,_,y),h.push(T-R,w-D),h.push(g,m,_,y),f++):(h.push(X,W),h.push(g,m,_,y),h.push(T-(X-T),w-(W-w)),h.push(g,m,_,y))}}b=r[2*(c-2)],x=r[2*(c-2)+1],T=r[2*(c-1)],w=r[2*(c-1)+1],O=-(x-w),M=b-T,A=Math.sqrt(O*O+M*M),O/=A,M/=A,O*=p,M*=p,h.push(T-O,w-M),h.push(g,m,_,y),h.push(T+O,w+M),h.push(g,m,_,y),l.push(d);for(var Y=0;Y=6){for(var i=[],n=t.holes,o=0;o0&&(0,s.default)(t,e)}r.__esModule=!0,r.default=n;var o=t("./buildLine"),s=i(o),a=t("../../../utils"),u=t("earcut"),h=i(u)},{"../../../utils":115,"./buildLine":57,earcut:2}],59:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){var r=t.shape,i=r.x,n=r.y,o=r.width,u=r.height;if(t.fill){var h=(0,a.hex2rgb)(t.fillColor),l=t.fillAlpha,c=h[0]*l,f=h[1]*l,d=h[2]*l,p=e.points,v=e.indices,y=p.length/6;p.push(i,n),p.push(c,f,d,l),p.push(i+o,n),p.push(c,f,d,l),p.push(i,n+u),p.push(c,f,d,l),p.push(i+o,n+u),p.push(c,f,d,l),v.push(y,y,y+1,y+2,y+3,y+3)}if(t.lineWidth){var g=t.points;t.points=[i,n,i+o,n,i+o,n+u,i,n+u,i,n],(0,s.default)(t,e),t.points=g}}r.__esModule=!0,r.default=n;var o=t("./buildLine"),s=i(o),a=t("../../../utils")},{"../../../utils":115,"./buildLine":57}],60:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){var r=t.shape,i=r.x,n=r.y,s=r.width,u=r.height,c=r.radius,f=[];if(f.push(i,n+c),o(i,n+u-c,i,n+u,i+c,n+u,f),o(i+s-c,n+u,i+s,n+u,i+s,n+u-c,f),o(i+s,n+c,i+s,n,i+s-c,n,f),o(i+c,n,i,n,i,n+c+1e-10,f),t.fill){for(var d=(0,l.hex2rgb)(t.fillColor),p=t.fillAlpha,v=d[0]*p,y=d[1]*p,g=d[2]*p,m=e.points,_=e.indices,b=m.length/6,x=(0,a.default)(f,null,2),T=0,w=x.length;T6&&void 0!==arguments[6]?arguments[6]:[],u=20,h=a,l=0,c=0,f=0,d=0,p=0,v=0,y=0,g=0;y<=u;++y)g=y/u,l=s(t,r,g),c=s(e,i,g),f=s(r,n,g),d=s(i,o,g),p=s(l,f,g),v=s(c,d,g),h.push(p,v);return h}r.__esModule=!0,r.default=n;var s=t("earcut"),a=i(s),u=t("./buildLine"),h=i(u),l=t("../../../utils")},{"../../../utils":115,"./buildLine":57,earcut:2}],61:[function(t,e,r){"use strict";function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function n(t){return t&&t.__esModule?t:{default:t}}function o(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:800,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:600,r=arguments[2],i=arguments[3];return!i&&N.isWebGLSupported()?new H.default(t,e,r):new G.default(t,e,r)}r.__esModule=!0,r.Filter=r.SpriteMaskFilter=r.Quad=r.RenderTarget=r.ObjectRenderer=r.WebGLManager=r.Shader=r.CanvasRenderTarget=r.TextureUvs=r.VideoBaseTexture=r.BaseRenderTexture=r.RenderTexture=r.BaseTexture=r.Texture=r.CanvasGraphicsRenderer=r.GraphicsRenderer=r.GraphicsData=r.Graphics=r.TextStyle=r.Text=r.SpriteRenderer=r.CanvasTinter=r.CanvasSpriteRenderer=r.Sprite=r.TransformBase=r.TransformStatic=r.Transform=r.Container=r.DisplayObject=r.glCore=r.WebGLRenderer=r.CanvasRenderer=r.ticker=r.utils=void 0;var s=t("./const");Object.keys(s).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return s[t]}})});var a=t("./math");Object.keys(a).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return a[t]}})});var u=t("pixi-gl-core");Object.defineProperty(r,"glCore",{enumerable:!0,get:function(){return n(u).default}});var h=t("./display/DisplayObject");Object.defineProperty(r,"DisplayObject",{enumerable:!0,get:function(){return n(h).default}});var l=t("./display/Container");Object.defineProperty(r,"Container",{enumerable:!0,get:function(){return n(l).default}});var c=t("./display/Transform");Object.defineProperty(r,"Transform",{enumerable:!0,get:function(){return n(c).default}});var f=t("./display/TransformStatic");Object.defineProperty(r,"TransformStatic",{enumerable:!0,get:function(){return n(f).default}});var d=t("./display/TransformBase");Object.defineProperty(r,"TransformBase",{enumerable:!0,get:function(){return n(d).default}});var p=t("./sprites/Sprite");Object.defineProperty(r,"Sprite",{enumerable:!0,get:function(){return n(p).default}});var v=t("./sprites/canvas/CanvasSpriteRenderer");Object.defineProperty(r,"CanvasSpriteRenderer",{enumerable:!0,get:function(){return n(v).default}});var y=t("./sprites/canvas/CanvasTinter");Object.defineProperty(r,"CanvasTinter",{enumerable:!0,get:function(){return n(y).default}});var g=t("./sprites/webgl/SpriteRenderer");Object.defineProperty(r,"SpriteRenderer",{enumerable:!0,get:function(){return n(g).default}});var m=t("./text/Text");Object.defineProperty(r,"Text",{enumerable:!0,get:function(){return n(m).default}});var _=t("./text/TextStyle");Object.defineProperty(r,"TextStyle",{enumerable:!0,get:function(){return n(_).default}});var b=t("./graphics/Graphics");Object.defineProperty(r,"Graphics",{enumerable:!0,get:function(){return n(b).default}});var x=t("./graphics/GraphicsData");Object.defineProperty(r,"GraphicsData",{enumerable:!0,get:function(){return n(x).default}});var T=t("./graphics/webgl/GraphicsRenderer");Object.defineProperty(r,"GraphicsRenderer",{enumerable:!0,get:function(){return n(T).default}});var w=t("./graphics/canvas/CanvasGraphicsRenderer");Object.defineProperty(r,"CanvasGraphicsRenderer",{enumerable:!0,get:function(){return n(w).default}});var E=t("./textures/Texture");Object.defineProperty(r,"Texture",{enumerable:!0,get:function(){return n(E).default}});var S=t("./textures/BaseTexture");Object.defineProperty(r,"BaseTexture",{enumerable:!0,get:function(){return n(S).default}});var O=t("./textures/RenderTexture");Object.defineProperty(r,"RenderTexture",{enumerable:!0,get:function(){return n(O).default}});var M=t("./textures/BaseRenderTexture");Object.defineProperty(r,"BaseRenderTexture",{enumerable:!0,get:function(){return n(M).default}});var P=t("./textures/VideoBaseTexture");Object.defineProperty(r,"VideoBaseTexture",{enumerable:!0,get:function(){return n(P).default}});var C=t("./textures/TextureUvs");Object.defineProperty(r,"TextureUvs",{enumerable:!0,get:function(){return n(C).default}});var R=t("./renderers/canvas/utils/CanvasRenderTarget");Object.defineProperty(r,"CanvasRenderTarget",{enumerable:!0,get:function(){return n(R).default}});var D=t("./Shader");Object.defineProperty(r,"Shader",{enumerable:!0,get:function(){return n(D).default}});var A=t("./renderers/webgl/managers/WebGLManager");Object.defineProperty(r,"WebGLManager",{enumerable:!0,get:function(){return n(A).default}});var I=t("./renderers/webgl/utils/ObjectRenderer");Object.defineProperty(r,"ObjectRenderer",{enumerable:!0,get:function(){return n(I).default}});var L=t("./renderers/webgl/utils/RenderTarget");Object.defineProperty(r,"RenderTarget",{enumerable:!0,get:function(){return n(L).default}});var j=t("./renderers/webgl/utils/Quad");Object.defineProperty(r,"Quad",{enumerable:!0,get:function(){return n(j).default}});var F=t("./renderers/webgl/filters/spriteMask/SpriteMaskFilter");Object.defineProperty(r,"SpriteMaskFilter",{enumerable:!0,get:function(){return n(F).default}});var B=t("./renderers/webgl/filters/Filter");Object.defineProperty(r,"Filter",{enumerable:!0,get:function(){return n(B).default}}),r.autoDetectRenderer=o;var k=t("./utils"),N=i(k),U=t("./ticker"),X=i(U),W=t("./renderers/canvas/CanvasRenderer"),G=n(W),Y=t("./renderers/webgl/WebGLRenderer"),H=n(Y);r.utils=N,r.ticker=X,r.CanvasRenderer=G.default,r.WebGLRenderer=H.default},{"./Shader":41,"./const":42,"./display/Container":44,"./display/DisplayObject":45,"./display/Transform":46,"./display/TransformBase":47,"./display/TransformStatic":48,"./graphics/Graphics":49,"./graphics/GraphicsData":50,"./graphics/canvas/CanvasGraphicsRenderer":51,"./graphics/webgl/GraphicsRenderer":53,"./math":66,"./renderers/canvas/CanvasRenderer":73,"./renderers/canvas/utils/CanvasRenderTarget":75,"./renderers/webgl/WebGLRenderer":80,"./renderers/webgl/filters/Filter":82,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":85,"./renderers/webgl/managers/WebGLManager":89,"./renderers/webgl/utils/ObjectRenderer":90,"./renderers/webgl/utils/Quad":91,"./renderers/webgl/utils/RenderTarget":92,"./sprites/Sprite":97,"./sprites/canvas/CanvasSpriteRenderer":98,"./sprites/canvas/CanvasTinter":99,"./sprites/webgl/SpriteRenderer":101,"./text/Text":103,"./text/TextStyle":104,"./textures/BaseRenderTexture":105,"./textures/BaseTexture":106,"./textures/RenderTexture":107,"./textures/Texture":108,"./textures/TextureUvs":109,"./textures/VideoBaseTexture":110,"./ticker":112,"./utils":115,"pixi-gl-core":14}],62:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t){return t<0?-1:t>0?1:0}function o(){for(var t=0;t<16;t++){var e=[];d.push(e);for(var r=0;r<16;r++)for(var i=n(u[t]*u[r]+l[t]*h[r]),o=n(h[t]*u[r]+c[t]*h[r]),s=n(u[t]*l[r]+l[t]*c[r]),p=n(h[t]*l[r]+c[t]*c[r]),v=0;v<16;v++)if(u[v]===i&&h[v]===o&&l[v]===s&&c[v]===p){e.push(v);break}}for(var y=0;y<16;y++){var g=new a.default;g.set(u[y],h[y],l[y],c[y],0,0),f.push(g)}}r.__esModule=!0;var s=t("./Matrix"),a=i(s),u=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],h=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],l=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],c=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],f=[],d=[];o();var p={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MIRROR_HORIZONTAL:12,uX:function(t){return u[t]},uY:function(t){return h[t]},vX:function(t){return l[t]},vY:function(t){return c[t]},inv:function(t){return 8&t?15&t:7&-t},add:function(t,e){return d[t][e]},sub:function(t,e){return d[t][p.inv(e)]},rotate180:function(t){return 4^t},isSwapWidthHeight:function(t){return 2===(3&t)},byDirection:function(t,e){return 2*Math.abs(t)<=Math.abs(e)?e>=0?p.S:p.N:2*Math.abs(e)<=Math.abs(t)?t>0?p.E:p.W:e>0?t>0?p.SE:p.SW:t>0?p.NE:p.NW},matrixAppendRotationInv:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,n=f[p.inv(e)];n.tx=r,n.ty=i,t.append(n)}};r.default=p},{"./Matrix":63}],63:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r=0&&(t.rotation+=t.rotation<=0?Math.PI:-Math.PI),t.skew.x=t.skew.y=0):(t.skew.x=o,t.skew.y=s),t.scale.x=Math.sqrt(e*e+r*r),t.scale.y=Math.sqrt(i*i+n*n),t.position.x=this.tx,t.position.y=this.ty,t},t.prototype.invert=function(){var t=this.a,e=this.b,r=this.c,i=this.d,n=this.tx,o=t*i-e*r;return this.a=i/o,this.b=-e/o,this.c=-r/o,this.d=t/o,this.tx=(r*this.ty-i*n)/o,this.ty=-(t*this.ty-e*n)/o,this},t.prototype.identity=function(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this},t.prototype.clone=function(){var e=new t;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e},t.prototype.copy=function(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t},o(t,null,[{key:"IDENTITY",get:function(){return new t}},{key:"TEMP_MATRIX",get:function(){return new t}}]),t}();r.default=u},{"./Point":65}],64:[function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var n=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;i(this,t),this._x=n,this._y=o,this.cb=e,this.scope=r}return t.prototype.set=function(t,e){var r=t||0,i=e||(0!==e?r:0);this._x===r&&this._y===i||(this._x=r,this._y=i,this.cb.call(this.scope))},t.prototype.copy=function(t){this._x===t.x&&this._y===t.y||(this._x=t.x,this._y=t.y,this.cb.call(this.scope))},n(t,[{key:"x",get:function(){return this._x},set:function(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}},{key:"y",get:function(){return this._y},set:function(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}]),t}();r.default=o},{}],65:[function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var n=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;i(this,t),this.x=e,this.y=r}return t.prototype.clone=function(){return new t(this.x,this.y)},t.prototype.copy=function(t){this.set(t.x,t.y)},t.prototype.equals=function(t){return t.x===this.x&&t.y===this.y},t.prototype.set=function(t,e){this.x=t||0,this.y=e||(0!==e?this.x:0)},t}();r.default=n},{}],66:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var n=t("./Point");Object.defineProperty(r,"Point",{enumerable:!0,get:function(){return i(n).default}});var o=t("./ObservablePoint");Object.defineProperty(r,"ObservablePoint",{enumerable:!0,get:function(){return i(o).default}});var s=t("./Matrix");Object.defineProperty(r,"Matrix",{enumerable:!0,get:function(){return i(s).default}});var a=t("./GroupD8");Object.defineProperty(r,"GroupD8",{enumerable:!0,get:function(){return i(a).default}});var u=t("./shapes/Circle");Object.defineProperty(r,"Circle",{enumerable:!0,get:function(){return i(u).default}});var h=t("./shapes/Ellipse");Object.defineProperty(r,"Ellipse",{enumerable:!0,get:function(){return i(h).default}});var l=t("./shapes/Polygon");Object.defineProperty(r,"Polygon",{enumerable:!0,get:function(){return i(l).default}});var c=t("./shapes/Rectangle");Object.defineProperty(r,"Rectangle",{enumerable:!0,get:function(){return i(c).default}});var f=t("./shapes/RoundedRectangle");Object.defineProperty(r,"RoundedRectangle",{enumerable:!0,get:function(){return i(f).default}})},{"./GroupD8":62,"./Matrix":63,"./ObservablePoint":64,"./Point":65,"./shapes/Circle":67,"./shapes/Ellipse":68,"./shapes/Polygon":69,"./shapes/Rectangle":70,"./shapes/RoundedRectangle":71}],67:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./Rectangle"),s=i(o),a=t("../../const"),u=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;n(this,t),this.x=e,this.y=r,this.radius=i,this.type=a.SHAPES.CIRC}return t.prototype.clone=function(){return new t(this.x,this.y,this.radius)},t.prototype.contains=function(t,e){if(this.radius<=0)return!1;var r=this.radius*this.radius,i=this.x-t,n=this.y-e;return i*=i,n*=n,i+n<=r},t.prototype.getBounds=function(){return new s.default(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)},t}();r.default=u},{"../../const":42,"./Rectangle":70}],68:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./Rectangle"),s=i(o),a=t("../../const"),u=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this.x=e,this.y=r,this.width=i,this.height=o,this.type=a.SHAPES.ELIP}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;var r=(t-this.x)/this.width,i=(e-this.y)/this.height;return r*=r,i*=i,r+i<=1},t.prototype.getBounds=function(){return new s.default(this.x-this.width,this.y-this.height,this.width,this.height)},t}();r.default=u},{"../../const":42,"./Rectangle":70}],69:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../Point"),s=i(o),a=t("../../const"),u=function(){function t(){for(var e=arguments.length,r=Array(e),i=0;ie!=h>e&&t<(u-s)*((e-a)/(h-a))+s;l&&(r=!r)}return r},t}();r.default=u},{"../../const":42,"../Point":65}],70:[function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var n=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;i(this,t),this.x=e,this.y=r,this.width=n,this.height=s,this.type=o.SHAPES.RECT}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this},t.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t=this.y&&et.x+t.width&&(this.width=t.width-this.x,this.width<0&&(this.width=0)),this.y+this.height>t.y+t.height&&(this.height=t.height-this.y,this.height<0&&(this.height=0))},t.prototype.enlarge=function(e){if(e!==t.EMPTY){var r=Math.min(this.x,e.x),i=Math.max(this.x+this.width,e.x+e.width),n=Math.min(this.y,e.y),o=Math.max(this.y+this.height,e.y+e.height);this.x=r,this.width=i-r,this.y=n,this.height=o-n}},n(t,[{key:"left",get:function(){return this.x}},{key:"right",get:function(){return this.x+this.width}},{key:"top",get:function(){return this.y}},{key:"bottom",get:function(){return this.y+this.height}}],[{key:"EMPTY",get:function(){return new t(0,0,0,0)}}]),t}();r.default=s},{"../../const":42}],71:[function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var n=t("../../const"),o=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:20;i(this,t),this.x=e,this.y=r,this.width=o,this.height=s,this.radius=a,this.type=n.SHAPES.RREC}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height,this.radius)},t.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height)},t}();r.default=o},{"../../const":42}],72:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:{};n(this,e);var a=o(this,t.call(this,"Canvas",r,i,s));return a.type=y.RENDERER_TYPE.CANVAS,a.rootContext=a.view.getContext("2d",{alpha:a.transparent}),a.refresh=!0,a.maskManager=new l.default(a),a.smoothProperty="imageSmoothingEnabled",a.rootContext.imageSmoothingEnabled||(a.rootContext.webkitImageSmoothingEnabled?a.smoothProperty="webkitImageSmoothingEnabled":a.rootContext.mozImageSmoothingEnabled?a.smoothProperty="mozImageSmoothingEnabled":a.rootContext.oImageSmoothingEnabled?a.smoothProperty="oImageSmoothingEnabled":a.rootContext.msImageSmoothingEnabled&&(a.smoothProperty="msImageSmoothingEnabled")),a.initPlugins(),a.blendModes=(0,p.default)(),a._activeBlendMode=null,a.context=null,a.renderingToScreen=!1,a.resize(r,i),a}return s(e,t),e.prototype.render=function(t,e,r,i,n){if(this.view){this.renderingToScreen=!e,this.emit("prerender"),e?(e=e.baseTexture||e,e._canvasRenderTarget||(e._canvasRenderTarget=new f.default(e.width,e.height,e.resolution),e.source=e._canvasRenderTarget.canvas,e.valid=!0),this.context=e._canvasRenderTarget.context,this.resolution=e._canvasRenderTarget.resolution):this.context=this.rootContext;var o=this.context;if(e||(this._lastObjectRendered=t),!n){var s=t.parent,a=this._tempDisplayObjectParent.transform.worldTransform;i?i.copy(a):a.identity(),t.parent=this._tempDisplayObjectParent,t.updateTransform(),t.parent=s}o.setTransform(1,0,0,1,0,0),o.globalAlpha=1,o.globalCompositeOperation=this.blendModes[y.BLEND_MODES.NORMAL],navigator.isCocoonJS&&this.view.screencanvas&&(o.fillStyle="black",o.clear()),(void 0!==r?r:this.clearBeforeRender)&&this.renderingToScreen&&(this.transparent?o.clearRect(0,0,this.width,this.height):(o.fillStyle=this._backgroundColorString,o.fillRect(0,0,this.width,this.height)));var u=this.context;this.context=o,t.renderCanvas(this),this.context=u,this.emit("postrender")}},e.prototype.setBlendMode=function(t){this._activeBlendMode!==t&&(this.context.globalCompositeOperation=this.blendModes[t])},e.prototype.destroy=function(e){this.destroyPlugins(),t.prototype.destroy.call(this,e),this.context=null,this.refresh=!0,this.maskManager.destroy(),this.maskManager=null,this.smoothProperty=null},e.prototype.resize=function(e,r){t.prototype.resize.call(this,e,r),this.smoothProperty&&(this.rootContext[this.smoothProperty]=y.SCALE_MODES.DEFAULT===y.SCALE_MODES.LINEAR)},e}(u.default);r.default=g,v.pluginTarget.mixin(g)},{"../../const":42,"../../utils":115,"../SystemRenderer":72,"./utils/CanvasMaskManager":74,"./utils/CanvasRenderTarget":75,"./utils/mapCanvasBlendModesToPixi":77}],74:[function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var n=t("../../../const"),o=function(){function t(e){i(this,t),this.renderer=e}return t.prototype.pushMask=function(t){var e=this.renderer;e.context.save();var r=t.alpha,i=t.transform.worldTransform,n=e.resolution;e.context.setTransform(i.a*n,i.b*n,i.c*n,i.d*n,i.tx*n,i.ty*n),t._texture||(this.renderGraphicsShape(t),e.context.clip()),t.worldAlpha=r},t.prototype.renderGraphicsShape=function(t){var e=this.renderer.context,r=t.graphicsData.length;if(0!==r){e.beginPath();for(var i=0;iS?S:E,e.moveTo(b,x+E),e.lineTo(b,x+w-E),e.quadraticCurveTo(b,x+w,b+E,x+w),e.lineTo(b+T-E,x+w),e.quadraticCurveTo(b+T,x+w,b+T,x+w-E),e.lineTo(b+T,x+E),e.quadraticCurveTo(b+T,x,b+T-E,x),e.lineTo(b+E,x),e.quadraticCurveTo(b,x,b,x+E),e.closePath()}}}},t.prototype.popMask=function(t){t.context.restore()},t.prototype.destroy=function(){},t}();r.default=o},{"../../../const":42}],75:[function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var n=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:[];return(0,a.default)()?(t[o.BLEND_MODES.NORMAL]="source-over",t[o.BLEND_MODES.ADD]="lighter",t[o.BLEND_MODES.MULTIPLY]="multiply",t[o.BLEND_MODES.SCREEN]="screen",t[o.BLEND_MODES.OVERLAY]="overlay",t[o.BLEND_MODES.DARKEN]="darken",t[o.BLEND_MODES.LIGHTEN]="lighten",t[o.BLEND_MODES.COLOR_DODGE]="color-dodge",t[o.BLEND_MODES.COLOR_BURN]="color-burn",t[o.BLEND_MODES.HARD_LIGHT]="hard-light",t[o.BLEND_MODES.SOFT_LIGHT]="soft-light",t[o.BLEND_MODES.DIFFERENCE]="difference",t[o.BLEND_MODES.EXCLUSION]="exclusion",t[o.BLEND_MODES.HUE]="hue",t[o.BLEND_MODES.SATURATION]="saturate",t[o.BLEND_MODES.COLOR]="color",t[o.BLEND_MODES.LUMINOSITY]="luminosity"):(t[o.BLEND_MODES.NORMAL]="source-over",t[o.BLEND_MODES.ADD]="lighter",t[o.BLEND_MODES.MULTIPLY]="source-over",t[o.BLEND_MODES.SCREEN]="source-over",t[o.BLEND_MODES.OVERLAY]="source-over",t[o.BLEND_MODES.DARKEN]="source-over",t[o.BLEND_MODES.LIGHTEN]="source-over",t[o.BLEND_MODES.COLOR_DODGE]="source-over",t[o.BLEND_MODES.COLOR_BURN]="source-over",t[o.BLEND_MODES.HARD_LIGHT]="source-over",t[o.BLEND_MODES.SOFT_LIGHT]="source-over",t[o.BLEND_MODES.DIFFERENCE]="source-over",t[o.BLEND_MODES.EXCLUSION]="source-over",t[o.BLEND_MODES.HUE]="source-over",t[o.BLEND_MODES.SATURATION]="source-over",t[o.BLEND_MODES.COLOR]="source-over",t[o.BLEND_MODES.LUMINOSITY]="source-over"),t}r.__esModule=!0,r.default=n;var o=t("../../../const"),s=t("./canUseNewCanvasBlendModes"),a=i(s)},{"../../../const":42,"./canUseNewCanvasBlendModes":76}],78:[function(t,e,r){"use strict";function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var n=t("../../const"),o=function(){function t(e){i(this,t),this.renderer=e,this.count=0,this.checkCount=0,this.maxIdle=3600,this.checkCountMax=600,this.mode=n.GC_MODES.DEFAULT}return t.prototype.update=function(){this.count++,this.mode!==n.GC_MODES.MANUAL&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run()))},t.prototype.run=function(){for(var t=this.renderer.textureManager,e=t._managedTextures,r=!1,i=0;ithis.maxIdle&&(t.destroyTexture(n,!0),e[i]=null,r=!0)}if(r){for(var o=0,s=0;s=0;r--)this.unload(t.children[r])},t}();r.default=o},{"../../const":42}],79:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("pixi-gl-core"),s=t("../../const"),a=t("./utils/RenderTarget"),u=i(a),h=t("../../utils"),l=function(){function t(e){n(this,t),this.renderer=e,this.gl=e.gl,this._managedTextures=[]}return t.prototype.bindTexture=function(){},t.prototype.getTexture=function(){},t.prototype.updateTexture=function(t){t=t.baseTexture||t;var e=!!t._glRenderTargets;if(!t.hasLoaded)return null;var r=t._glTextures[this.renderer.CONTEXT_UID];if(r)e?t._glRenderTargets[this.renderer.CONTEXT_UID].resize(t.width,t.height):r.upload(t.source);else{if(e){var i=new u.default(this.gl,t.width,t.height,t.scaleMode,t.resolution);i.resize(t.width,t.height),t._glRenderTargets[this.renderer.CONTEXT_UID]=i,r=i.texture}else r=new o.GLTexture(this.gl),r.premultiplyAlpha=!0,r.upload(t.source);t._glTextures[this.renderer.CONTEXT_UID]=r,t.on("update",this.updateTexture,this),t.on("dispose",this.destroyTexture,this),this._managedTextures.push(t),t.isPowerOfTwo?(t.mipmap&&r.enableMipmap(),t.wrapMode===s.WRAP_MODES.CLAMP?r.enableWrapClamp():t.wrapMode===s.WRAP_MODES.REPEAT?r.enableWrapRepeat():r.enableWrapMirrorRepeat()):r.enableWrapClamp(),t.scaleMode===s.SCALE_MODES.NEAREST?r.enableNearestScaling():r.enableLinearScaling()}return r},t.prototype.destroyTexture=function(t,e){if(t=t.baseTexture||t,t.hasLoaded&&t._glTextures[this.renderer.CONTEXT_UID]&&(t._glTextures[this.renderer.CONTEXT_UID].destroy(),t.off("update",this.updateTexture,this),t.off("dispose",this.destroyTexture,this),delete t._glTextures[this.renderer.CONTEXT_UID],!e)){var r=this._managedTextures.indexOf(t);r!==-1&&(0,h.removeItems)(this._managedTextures,r,1)}},t.prototype.removeAll=function(){for(var t=0;t2&&void 0!==arguments[2]?arguments[2]:{};n(this,e);var a=o(this,t.call(this,"WebGL",r,i,s));return a.type=A.RENDERER_TYPE.WEBGL,a.handleContextLost=a.handleContextLost.bind(a),a.handleContextRestored=a.handleContextRestored.bind(a),a.view.addEventListener("webglcontextlost",a.handleContextLost,!1),a.view.addEventListener("webglcontextrestored",a.handleContextRestored,!1),a._contextOptions={alpha:a.transparent,antialias:s.antialias,premultipliedAlpha:a.transparent&&"notMultiplied"!==a.transparent,stencil:!0,preserveDrawingBuffer:s.preserveDrawingBuffer},a._backgroundColorRgba[3]=a.transparent?0:1,a.maskManager=new l.default(a),a.stencilManager=new f.default(a),a.emptyRenderer=new m.default(a),a.currentRenderer=a.emptyRenderer,a.initPlugins(),s.context&&(0,P.default)(s.context),a.gl=s.context||D.default.createContext(a.view,a._contextOptions),a.CONTEXT_UID=I++,a.state=new E.default(a.gl),a.renderingToScreen=!0,a._initContext(),a.filterManager=new p.default(a),a.drawModes=(0,O.default)(a.gl),a._activeShader=null,a._activeRenderTarget=null,a._activeTextureLocation=999,a._activeTexture=null,a.setBlendMode(0),a}return s(e,t),e.prototype._initContext=function(){var t=this.gl;t.isContextLost()&&t.getExtension("WEBGL_lose_context")&&t.getExtension("WEBGL_lose_context").restoreContext(),this.textureManager=new b.default(this),this.textureGC=new T.default(this),this.state.resetToDefault(),this.rootRenderTarget=new y.default(t,this.width,this.height,null,this.resolution,(!0)),this.rootRenderTarget.clearColor=this._backgroundColorRgba,this.bindRenderTarget(this.rootRenderTarget),this.emit("context",t),this.resize(this.width,this.height)},e.prototype.render=function(t,e,r,i,n){if(this.renderingToScreen=!e,this.emit("prerender"),this.gl&&!this.gl.isContextLost()){if(e||(this._lastObjectRendered=t),!n){var o=t.parent;t.parent=this._tempDisplayObjectParent,t.updateTransform(),t.parent=o}this.bindRenderTexture(e,i),this.currentRenderer.start(),(void 0!==r?r:this.clearBeforeRender)&&this._activeRenderTarget.clear(),t.renderWebGL(this),this.currentRenderer.flush(),this.textureGC.update(),this.emit("postrender")}},e.prototype.setObjectRenderer=function(t){this.currentRenderer!==t&&(this.currentRenderer.stop(),this.currentRenderer=t,this.currentRenderer.start())},e.prototype.flush=function(){this.setObjectRenderer(this.emptyRenderer)},e.prototype.resize=function(t,e){u.default.prototype.resize.call(this,t,e),this.rootRenderTarget.resize(t,e),this._activeRenderTarget===this.rootRenderTarget&&(this.rootRenderTarget.activate(),this._activeShader&&(this._activeShader.uniforms.projectionMatrix=this.rootRenderTarget.projectionMatrix.toArray(!0)))},e.prototype.setBlendMode=function(t){this.state.setBlendMode(t)},e.prototype.clear=function(t){this._activeRenderTarget.clear(t)},e.prototype.setTransform=function(t){this._activeRenderTarget.transform=t},e.prototype.bindRenderTexture=function(t,e){var r=void 0;if(t){var i=t.baseTexture,n=this.gl;i._glRenderTargets[this.CONTEXT_UID]?(this._activeTextureLocation=i._id,n.activeTexture(n.TEXTURE0+i._id),n.bindTexture(n.TEXTURE_2D,null)):(this.textureManager.updateTexture(i),n.bindTexture(n.TEXTURE_2D,null)),r=i._glRenderTargets[this.CONTEXT_UID],r.setFrame(t.frame)}else r=this.rootRenderTarget;return r.transform=e,this.bindRenderTarget(r),this},e.prototype.bindRenderTarget=function(t){return t!==this._activeRenderTarget&&(this._activeRenderTarget=t,t.activate(),this._activeShader&&(this._activeShader.uniforms.projectionMatrix=t.projectionMatrix.toArray(!0)),this.stencilManager.setMaskStack(t.stencilMaskStack)),this},e.prototype.bindShader=function(t){return this._activeShader!==t&&(this._activeShader=t,t.bind(),t.uniforms.projectionMatrix=this._activeRenderTarget.projectionMatrix.toArray(!0)),this},e.prototype.bindTexture=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;t=t.baseTexture||t;var r=this.gl;return this._activeTextureLocation!==e&&(this._activeTextureLocation=e,r.activeTexture(r.TEXTURE0+e)),this._activeTexture=t,t._glTextures[this.CONTEXT_UID]?(t.touched=this.textureGC.count,t._glTextures[this.CONTEXT_UID].bind()):this.textureManager.updateTexture(t),this},e.prototype.createVao=function(){return new D.default.VertexArrayObject(this.gl,this.state.attribState)},e.prototype.reset=function(){return this.setObjectRenderer(this.emptyRenderer),this._activeShader=null,this._activeRenderTarget=this.rootRenderTarget,this._activeTextureLocation=999,this._activeTexture=null,this.rootRenderTarget.activate(),this.state.resetToDefault(),this},e.prototype.handleContextLost=function(t){t.preventDefault()},e.prototype.handleContextRestored=function(){this._initContext(),this.textureManager.removeAll()},e.prototype.destroy=function(e){this.destroyPlugins(),this.view.removeEventListener("webglcontextlost",this.handleContextLost),this.view.removeEventListener("webglcontextrestored",this.handleContextRestored),this.textureManager.destroy(),t.prototype.destroy.call(this,e),this.uid=0,this.maskManager.destroy(),this.stencilManager.destroy(),this.filterManager.destroy(),this.maskManager=null,this.filterManager=null,this.textureManager=null, +this.currentRenderer=null,this.handleContextLost=null,this.handleContextRestored=null,this._contextOptions=null,this.gl.useProgram(null),this.gl.getExtension("WEBGL_lose_context")&&this.gl.getExtension("WEBGL_lose_context").loseContext(),this.gl=null},e}(u.default);r.default=L,C.pluginTarget.mixin(L)},{"../../const":42,"../../utils":115,"../SystemRenderer":72,"./TextureGarbageCollector":78,"./TextureManager":79,"./WebGLState":81,"./managers/FilterManager":86,"./managers/MaskManager":87,"./managers/StencilManager":88,"./utils/ObjectRenderer":90,"./utils/RenderTarget":92,"./utils/mapWebGLDrawModesToPixi":95,"./utils/validateContext":96,"pixi-gl-core":14}],81:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./utils/mapWebGLBlendModesToPixi"),s=i(o),a=0,u=1,h=2,l=3,c=4,f=function(){function t(e){n(this,t),this.activeState=new Uint8Array(16),this.defaultState=new Uint8Array(16),this.defaultState[0]=1,this.stackIndex=0,this.stack=[],this.gl=e,this.maxAttribs=e.getParameter(e.MAX_VERTEX_ATTRIBS),this.attribState={tempAttribState:new Array(this.maxAttribs),attribState:new Array(this.maxAttribs)},this.blendModes=(0,s.default)(e),this.nativeVaoExtension=e.getExtension("OES_vertex_array_object")||e.getExtension("MOZ_OES_vertex_array_object")||e.getExtension("WEBKIT_OES_vertex_array_object")}return t.prototype.push=function(){var t=this.stack[++this.stackIndex];t||(t=this.stack[this.stackIndex]=new Uint8Array(16));for(var e=0;e 0.5)"," {"," color = vec4(1.0, 0.0, 0.0, 1.0);"," }"," else"," {"," color = vec4(0.0, 1.0, 0.0, 1.0);"," }"," gl_FragColor = mix(sample, masky, 0.5);"," gl_FragColor *= sample.a;","}"].join("\n")}}]),t}();r.default=c},{"../../../const":42,"../../../utils":115,"./extractUniformsFromSrc":83}],83:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e,r){var i=o(t,r),n=o(e,r);return Object.assign(i,n)}function o(t){for(var e=new RegExp("^(projectionMatrix|uSampler|filterArea)$"),r={},i=void 0,n=t.replace(/\s+/g," ").split(/\s*;\s*/),o=0;o-1){var a=s.split(" "),h=a[1],l=a[2],c=1;l.indexOf("[")>-1&&(i=l.split(/\[|\]/),l=i[0],c*=Number(i[1])),l.match(e)||(r[l]={value:u(h,c),name:l,type:h})}}return r}r.__esModule=!0,r.default=n;var s=t("pixi-gl-core"),a=i(s),u=a.default.shader.defaultValue},{"pixi-gl-core":14}],84:[function(t,e,r){"use strict";function i(t,e,r){var i=t.identity();return i.translate(e.x/r.width,e.y/r.height),i.scale(r.width,r.height),i}function n(t,e,r){var i=t.identity();i.translate(e.x/r.width,e.y/r.height);var n=r.width/e.width,o=r.height/e.height;return i.scale(n,o),i}function o(t,e,r,i){var n=i.worldTransform.copy(s.Matrix.TEMP_MATRIX),o=i._texture.baseTexture,a=t.identity(),u=r.height/r.width;a.translate(e.x/r.width,e.y/r.height),a.scale(1,u);var h=r.width/o.width,l=r.height/o.height;return n.tx/=o.width*h,n.ty/=o.width*h,n.invert(),a.prepend(n),a.scale(1,1/u),a.scale(h,l),a.translate(i.anchor.x,i.anchor.y),a}r.__esModule=!0,r.calculateScreenSpaceMatrix=i,r.calculateNormalizedScreenSpaceMatrix=n,r.calculateSpriteMatrix=o;var s=t("../../../math")},{"../../../math":66}],85:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../Filter"),u=i(a),h=t("../../../../math"),l=function(t){function e(r){n(this,e);var i=new h.Matrix,s=o(this,t.call(this,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n","#define GLSLIFY 1\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n"));return r.renderable=!1,s.maskSprite=r,s.maskMatrix=i,s}return s(e,t),e.prototype.apply=function(t,e,r){var i=this.maskSprite;this.uniforms.mask=i._texture,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,i),this.uniforms.alpha=i.worldAlpha,t.applyFilter(this,e,r)},e}(u.default);r.default=l},{"../../../../math":66,"../Filter":82}],86:[function(t,e,r){"use strict";function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function n(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var u=t("./WebGLManager"),h=n(u),l=t("../utils/RenderTarget"),c=n(l),f=t("../utils/Quad"),d=n(f),p=t("../../../math"),v=t("../../../Shader"),y=n(v),g=t("../filters/filterTransforms"),m=i(g),_=t("bit-twiddle"),b=n(_),x=function t(){a(this,t),this.renderTarget=null,this.sourceFrame=new p.Rectangle,this.destinationFrame=new p.Rectangle,this.filters=[],this.target=null,this.resolution=1},T=function(t){function e(r){a(this,e);var i=o(this,t.call(this,r));return i.gl=i.renderer.gl,i.quad=new d.default(i.gl,r.state.attribState),i.shaderCache={},i.pool={},i.filterData=null,i}return s(e,t),e.prototype.pushFilter=function(t,e){var r=this.renderer,i=this.filterData;if(!i){i=this.renderer._activeRenderTarget.filterStack;var n=new x;n.sourceFrame=n.destinationFrame=this.renderer._activeRenderTarget.size,n.renderTarget=r._activeRenderTarget,this.renderer._activeRenderTarget.filterData=i={index:0,stack:[n]},this.filterData=i}var o=i.stack[++i.index];o||(o=i.stack[i.index]=new x);var s=e[0].resolution,a=0|e[0].padding,u=t.filterArea||t.getBounds(!0),h=o.sourceFrame,l=o.destinationFrame;h.x=(u.x*s|0)/s,h.y=(u.y*s|0)/s,h.width=(u.width*s|0)/s,h.height=(u.height*s|0)/s,i.stack[0].renderTarget.transform||h.fit(i.stack[0].destinationFrame),h.pad(a),l.width=h.width,l.height=h.height;var c=this.getPotRenderTarget(r.gl,h.width,h.height,s);o.target=t,o.filters=e,o.resolution=s,o.renderTarget=c,c.setFrame(l,h),r.bindRenderTarget(c),r.clear()},e.prototype.popFilter=function(){var t=this.filterData,e=t.stack[t.index-1],r=t.stack[t.index];this.quad.map(r.renderTarget.size,r.sourceFrame).upload();var i=r.filters;if(1===i.length)i[0].apply(this,r.renderTarget,e.renderTarget,!1),this.freePotRenderTarget(r.renderTarget);else{var n=r.renderTarget,o=this.getPotRenderTarget(this.renderer.gl,r.sourceFrame.width,r.sourceFrame.height,r.resolution);o.setFrame(r.destinationFrame,r.sourceFrame);var s=0;for(s=0;s0&&(e+="\nelse "),r1&&void 0!==arguments[1]?arguments[1]:[];return e[n.BLEND_MODES.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[n.BLEND_MODES.ADD]=[t.ONE,t.DST_ALPHA],e[n.BLEND_MODES.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA],e[n.BLEND_MODES.SCREEN]=[t.ONE,t.ONE_MINUS_SRC_COLOR],e[n.BLEND_MODES.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[n.BLEND_MODES.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[n.BLEND_MODES.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[n.BLEND_MODES.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[n.BLEND_MODES.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[n.BLEND_MODES.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[n.BLEND_MODES.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[n.BLEND_MODES.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[n.BLEND_MODES.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[n.BLEND_MODES.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[n.BLEND_MODES.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[n.BLEND_MODES.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[n.BLEND_MODES.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e}r.__esModule=!0,r.default=i;var n=t("../../../const")},{"../../../const":42}],95:[function(t,e,r){"use strict";function i(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e[n.DRAW_MODES.POINTS]=t.POINTS,e[n.DRAW_MODES.LINES]=t.LINES,e[n.DRAW_MODES.LINE_LOOP]=t.LINE_LOOP,e[n.DRAW_MODES.LINE_STRIP]=t.LINE_STRIP,e[n.DRAW_MODES.TRIANGLES]=t.TRIANGLES,e[n.DRAW_MODES.TRIANGLE_STRIP]=t.TRIANGLE_STRIP,e[n.DRAW_MODES.TRIANGLE_FAN]=t.TRIANGLE_FAN,e}r.__esModule=!0,r.default=i;var n=t("../../../const")},{"../../../const":42}],96:[function(t,e,r){"use strict";function i(t){var e=t.getContextAttributes();e.stencil||console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly")}r.__esModule=!0,r.default=i},{}],97:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;ri&&v.xn&&v.y>16)+(65280&t)+((255&t)<<16)}},{key:"texture",get:function(){return this._texture},set:function(t){this._texture!==t&&(this._texture=t,this.cachedTint=16777215,this._textureID=-1,t&&(t.baseTexture.hasLoaded?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}]),e}(p.default);r.default=y},{"../const":42,"../display/Container":44,"../math":66,"../textures/Texture":108,"../utils":115}],98:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../renderers/canvas/CanvasRenderer"),s=i(o),a=t("../../const"),u=t("../../math"),h=t("./CanvasTinter"),l=i(h),c=new u.Matrix,f=function(){function t(e){n(this,t),this.renderer=e}return t.prototype.render=function(t){var e=t._texture,r=this.renderer,i=e._frame.width,n=e._frame.height,o=t.transform.worldTransform,s=0,h=0;if(!(e.orig.width<=0||e.orig.height<=0)&&e.baseTexture.source&&(r.setBlendMode(t.blendMode),e.valid)){r.context.globalAlpha=t.worldAlpha;var f=e.baseTexture.scaleMode===a.SCALE_MODES.LINEAR;r.smoothProperty&&r.context[r.smoothProperty]!==f&&(r.context[r.smoothProperty]=f),e.trim?(s=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,h=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(s=(.5-t.anchor.x)*e.orig.width,h=(.5-t.anchor.y)*e.orig.height),e.rotate&&(o.copy(c),o=c,u.GroupD8.matrixAppendRotationInv(o,e.rotate,s,h),s=0,h=0),s-=i/2,h-=n/2,r.roundPixels?(r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution|0,o.ty*r.resolution|0),s=0|s,h=0|h):r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution,o.ty*r.resolution);var d=e.baseTexture.resolution;16777215!==t.tint?(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=l.default.getTintedTexture(t,t.tint)),r.context.drawImage(t.tintedTexture,0,0,i*d,n*d,s*r.resolution,h*r.resolution,i*r.resolution,n*r.resolution)):r.context.drawImage(e.baseTexture.source,e._frame.x*d,e._frame.y*d,i*d,n*d,s*r.resolution,h*r.resolution,i*r.resolution,n*r.resolution)}},t.prototype.destroy=function(){this.renderer=null},t}();r.default=f,s.default.registerPlugin("sprite",f)},{"../../const":42,"../../math":66,"../../renderers/canvas/CanvasRenderer":73,"./CanvasTinter":99}],99:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var n=t("../../utils"),o=t("../../renderers/canvas/utils/canUseNewCanvasBlendModes"),s=i(o),a={getTintedTexture:function(t,e){var r=t.texture;e=a.roundColor(e);var i="#"+("00000"+(0|e).toString(16)).substr(-6);if(r.tintCache=r.tintCache||{},r.tintCache[i])return r.tintCache[i];var n=a.canvas||document.createElement("canvas");if(a.tintMethod(r,e,n),a.convertTintToImage){var o=new Image;o.src=n.toDataURL(),r.tintCache[i]=o}else r.tintCache[i]=n,a.canvas=null;return n},tintWithMultiply:function(t,e,r){var i=r.getContext("2d"),n=t._frame.clone(),o=t.baseTexture.resolution;n.x*=o,n.y*=o,n.width*=o,n.height*=o,r.width=n.width,r.height=n.height,i.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),i.fillRect(0,0,n.width,n.height),i.globalCompositeOperation="multiply",i.drawImage(t.baseTexture.source,n.x,n.y,n.width,n.height,0,0,n.width,n.height),i.globalCompositeOperation="destination-atop",i.drawImage(t.baseTexture.source,n.x,n.y,n.width,n.height,0,0,n.width,n.height)},tintWithOverlay:function(t,e,r){var i=r.getContext("2d"),n=t._frame.clone(),o=t.baseTexture.resolution;n.x*=o,n.y*=o,n.width*=o,n.height*=o,r.width=n.width,r.height=n.height,i.globalCompositeOperation="copy",i.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),i.fillRect(0,0,n.width,n.height),i.globalCompositeOperation="destination-atop",i.drawImage(t.baseTexture.source,n.x,n.y,n.width,n.height,0,0,n.width,n.height)},tintWithPerPixel:function(t,e,r){var i=r.getContext("2d"),o=t._frame.clone(),s=t.baseTexture.resolution;o.x*=s,o.y*=s,o.width*=s,o.height*=s,r.width=o.width,r.height=o.height,i.globalCompositeOperation="copy",i.drawImage(t.baseTexture.source,o.x,o.y,o.width,o.height,0,0,o.width,o.height);for(var a=(0,n.hex2rgb)(e),u=a[0],h=a[1],l=a[2],c=i.getImageData(0,0,o.width,o.height),f=c.data,d=0;d=this.size&&this.flush(),t.texture._uvs&&(this.sprites[this.currentIndex++]=t)},e.prototype.flush=function(){if(0!==this.currentIndex){var t=this.renderer.gl,e=w.default.nextPow2(this.currentIndex),r=w.default.log2(e),i=this.buffers[r],n=this.sprites,o=this.groups,s=i.float32View,a=i.uint32View,u=0,h=void 0,l=void 0,c=1,f=0,d=o[0],v=void 0,y=void 0,g=void 0,m=void 0,_=n[0].blendMode,b=void 0;d.textureCount=0,d.start=0,d.blend=_,E++;var T=void 0;for(T=0;T0&&(e+="\nelse "),r0?(this.context.shadowColor=e.dropShadowColor,this.context.shadowBlur=e.dropShadowBlur):this.context.fillStyle=e.dropShadowColor;for(var v=Math.cos(e.dropShadowAngle)*e.dropShadowDistance,y=Math.sin(e.dropShadowAngle)*e.dropShadowDistance,g=0;g3&&void 0!==arguments[3]&&arguments[3],n=this._style,o=n.letterSpacing;if(0===o)return void(i?this.context.strokeText(t,e,r):this.context.fillText(t,e,r));for(var s=String.prototype.split.call(t,""),a=e,u=0,h="";us;--c){for(var v=0;vi)for(var h=s[a].split(""),l=0;lo?(e+="\n"+h[l],o=i-c):(0===l&&(e+=" "),e+=h[l],o-=c)}else{var f=u+this.context.measureText(" ").width;0===a||f>o?(a>0&&(e+="\n"),e+=s[a],o=i-u):(o-=f,e+=" "+s[a])}}n0&&void 0!==arguments[0]?arguments[0]:100,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,s=arguments[2],a=arguments[3];n(this,e);var u=o(this,t.call(this,null,s));return u.resolution=a||h.RESOLUTION,u.width=r,u.height=i,u.realWidth=u.width*u.resolution,u.realHeight=u.height*u.resolution,u.scaleMode=s||h.SCALE_MODES.DEFAULT,u.hasLoaded=!0,u._glRenderTargets=[],u._canvasRenderTarget=null,u.valid=!1,u}return s(e,t),e.prototype.resize=function(t,e){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.realWidth=this.width*this.resolution,this.realHeight=this.height*this.resolution,this.valid&&this.emit("update",this))},e.prototype.destroy=function(){t.prototype.destroy.call(this,!0),this.renderer=null},e}(u.default);r.default=l},{"../const":42,"./BaseTexture":106}],106:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u=t("../utils"),h=t("../const"),l=t("eventemitter3"),c=i(l),f=t("../utils/determineCrossOrigin"),d=i(f),p=t("bit-twiddle"),v=i(p),y=function(t){function e(r,i,s){n(this,e);var a=o(this,t.call(this));return a.uid=(0,u.uid)(),a.touched=0,a.resolution=s||h.RESOLUTION,a.width=100,a.height=100,a.realWidth=100,a.realHeight=100,a.scaleMode=i||h.SCALE_MODES.DEFAULT,a.hasLoaded=!1,a.isLoading=!1,a.source=null,a.origSource=null,a.imageType=null,a.sourceScale=1,a.premultipliedAlpha=!0,a.imageUrl=null,a.isPowerOfTwo=!1,a.mipmap=h.MIPMAP_TEXTURES,a.wrapMode=h.WRAP_MODES.DEFAULT,a._glTextures=[],a._enabled=0,a._id=0,r&&a.loadSource(r),a}return s(e,t),e.prototype.update=function(){"svg"!==this.imageType&&(this.realWidth=this.source.naturalWidth||this.source.videoWidth||this.source.width,this.realHeight=this.source.naturalHeight||this.source.videoHeight||this.source.height,this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=v.default.isPow2(this.realWidth)&&v.default.isPow2(this.realHeight)),this.emit("update",this)},e.prototype.loadSource=function(t){var e=this,r=this.isLoading;this.hasLoaded=!1,this.isLoading=!1,r&&this.source&&(this.source.onload=null,this.source.onerror=null);var i=!this.source;if(this.source=t,(t.src&&t.complete||t.getContext)&&t.width&&t.height)this._updateImageType(),"svg"===this.imageType?this._loadSvgSource():this._sourceLoaded(),i&&this.emit("loaded",this);else if(!t.getContext){ +var n=function(){e.isLoading=!0;var i=e;if(t.onload=function(){if(i._updateImageType(),t.onload=null,t.onerror=null,i.isLoading)return i.isLoading=!1,i._sourceLoaded(),"svg"===i.imageType?void i._loadSvgSource():void i.emit("loaded",i)},t.onerror=function(){t.onload=null,t.onerror=null,i.isLoading&&(i.isLoading=!1,i.emit("error",i))},t.complete&&t.src){if(t.onload=null,t.onerror=null,"svg"===i.imageType)return i._loadSvgSource(),{v:void 0};e.isLoading=!1,t.width&&t.height?(e._sourceLoaded(),r&&e.emit("loaded",e)):r&&e.emit("error",e)}}();if("object"===("undefined"==typeof n?"undefined":a(n)))return n.v}},e.prototype._updateImageType=function(){if(this.imageUrl){var t=(0,u.decomposeDataUri)(this.imageUrl),e=void 0;if(t&&"image"===t.mediaType){var r=t.subType.split("+")[0];if(e=(0,u.getUrlFileExtension)("."+r),!e)throw new Error("Invalid image type in data URI.")}else if(e=(0,u.getUrlFileExtension)(this.imageUrl),!e)throw new Error("Invalid image type in URL.");this.imageType=e}},e.prototype._loadSvgSource=function(){if("svg"===this.imageType){var t=(0,u.decomposeDataUri)(this.imageUrl);t?this._loadSvgSourceUsingDataUri(t):this._loadSvgSourceUsingXhr()}},e.prototype._loadSvgSourceUsingDataUri=function(t){var e=void 0;if("base64"===t.encoding){if(!atob)throw new Error("Your browser doesn't support base64 conversions.");e=atob(t.data)}else e=t.data;this._loadSvgSourceUsingString(e)},e.prototype._loadSvgSourceUsingXhr=function(){var t=this,e=new XMLHttpRequest;e.onload=function(){if(e.readyState!==e.DONE||200!==e.status)throw new Error("Failed to load SVG using XHR.");t._loadSvgSourceUsingString(e.response)},e.onerror=function(){return t.emit("error",t)},e.open("GET",this.imageUrl,!0),e.send()},e.prototype._loadSvgSourceUsingString=function(t){var e=(0,u.getSvgSize)(t),r=e.width,i=e.height;if(!r||!i)throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them.");this.realWidth=Math.round(r*this.sourceScale),this.realHeight=Math.round(i*this.sourceScale),this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=v.default.isPow2(this.realWidth)&&v.default.isPow2(this.realHeight);var n=document.createElement("canvas");n.width=this.realWidth,n.height=this.realHeight,n._pixiId="canvas_"+(0,u.uid)(),n.getContext("2d").drawImage(this.source,0,0,r,i,0,0,this.realWidth,this.realHeight),this.origSource=this.source,this.source=n,u.BaseTextureCache[n._pixiId]=this,this.isLoading=!1,this._sourceLoaded(),this.emit("loaded",this)},e.prototype._sourceLoaded=function(){this.hasLoaded=!0,this.update()},e.prototype.destroy=function(){this.imageUrl&&(delete u.BaseTextureCache[this.imageUrl],delete u.TextureCache[this.imageUrl],this.imageUrl=null,navigator.isCocoonJS||(this.source.src="")),this.source&&this.source._pixiId&&delete u.BaseTextureCache[this.source._pixiId],this.source=null,this.dispose()},e.prototype.dispose=function(){this.emit("dispose",this)},e.prototype.updateSourceImage=function(t){this.source.src=t,this.loadSource(this.source)},e.fromImage=function(t,r,i,n){var o=u.BaseTextureCache[t];if(!o){var s=new Image;void 0===r&&0!==t.indexOf("data:")&&(s.crossOrigin=(0,d.default)(t)),o=new e(s,i),o.imageUrl=t,n&&(o.sourceScale=n),o.resolution=(0,u.getResolutionOfUrl)(t),s.src=t,u.BaseTextureCache[t]=o}return o},e.fromCanvas=function(t,r){t._pixiId||(t._pixiId="canvas_"+(0,u.uid)());var i=u.BaseTextureCache[t._pixiId];return i||(i=new e(t,r),u.BaseTextureCache[t._pixiId]=i),i},e}(c.default);r.default=y},{"../const":42,"../utils":115,"../utils/determineCrossOrigin":114,"bit-twiddle":1,eventemitter3:3}],107:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("./BaseRenderTexture"),u=i(a),h=t("./Texture"),l=i(h),c=function(t){function e(r,i){n(this,e);var s=null;if(!(r instanceof u.default)){var a=arguments[1],h=arguments[2],l=arguments[3]||0,c=arguments[4]||1;console.warn("Please use RenderTexture.create("+a+", "+h+") instead of the ctor directly."),s=arguments[0],i=null,r=new u.default(a,h,l,c)}var f=o(this,t.call(this,r,i));return f.legacyRenderer=s,f.valid=!0,f._updateUvs(),f}return s(e,t),e.prototype.resize=function(t,e,r){this.valid=t>0&&e>0,this._frame.width=this.orig.width=t,this._frame.height=this.orig.height=e,r||this.baseTexture.resize(t,e),this._updateUvs()},e.create=function(t,r,i,n){return new e(new u.default(t,r,i,n))},e}(l.default);r.default=c},{"./BaseRenderTexture":105,"./Texture":108}],108:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rthis.baseTexture.width||t.y+t.height>this.baseTexture.height)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);this.valid=t&&t.width&&t.height&&this.baseTexture.hasLoaded,this.trim||this.rotate||(this.orig=t),this.valid&&this._updateUvs()}},{key:"rotate",get:function(){return this._rotate},set:function(t){this._rotate=t,this.valid&&this._updateUvs()}},{key:"width",get:function(){return this.orig?this.orig.width:0}},{key:"height",get:function(){return this.orig?this.orig.height:0}}]),e}(v.default);r.default=m,m.EMPTY=new m(new h.default),m.EMPTY.destroy=function(){},m.EMPTY.on=function(){},m.EMPTY.once=function(){},m.EMPTY.emit=function(){}},{"../math":66,"../utils":115,"./BaseTexture":106,"./TextureUvs":109,"./VideoBaseTexture":110,eventemitter3:3}],109:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../math/GroupD8"),s=i(o),a=function(){function t(){n(this,t),this.x0=0,this.y0=0,this.x1=1,this.y1=0,this.x2=1,this.y2=1,this.x3=0,this.y3=1,this.uvsUint32=new Uint32Array(4)}return t.prototype.set=function(t,e,r){var i=e.width,n=e.height;if(r){var o=t.width/2/i,a=t.height/2/n,u=t.x/i+o,h=t.y/n+a;r=s.default.add(r,s.default.NW),this.x0=u+o*s.default.uX(r),this.y0=h+a*s.default.uY(r),r=s.default.add(r,2),this.x1=u+o*s.default.uX(r),this.y1=h+a*s.default.uY(r),r=s.default.add(r,2),this.x2=u+o*s.default.uX(r),this.y2=h+a*s.default.uY(r),r=s.default.add(r,2),this.x3=u+o*s.default.uX(r),this.y3=h+a*s.default.uY(r)}else this.x0=t.x/i,this.y0=t.y/n,this.x1=(t.x+t.width)/i,this.y1=t.y/n,this.x2=(t.x+t.width)/i,this.y2=(t.y+t.height)/n,this.x3=t.x/i,this.y3=(t.y+t.height)/n;this.uvsUint32[0]=(65535*this.y0&65535)<<16|65535*this.x0&65535,this.uvsUint32[1]=(65535*this.y1&65535)<<16|65535*this.x1&65535,this.uvsUint32[2]=(65535*this.y2&65535)<<16|65535*this.x2&65535,this.uvsUint32[3]=(65535*this.y3&65535)<<16|65535*this.x3&65535},t}();r.default=a},{"../math/GroupD8":62}],110:[function(t,e,r){"use strict";function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function n(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function u(t,e){e||(e="video/"+t.substr(t.lastIndexOf(".")+1));var r=document.createElement("source");return r.src=t,r.type=e,r}r.__esModule=!0;var h=function(){function t(t,e){for(var r=0;r0&&t.paused===!1&&t.ended===!1&&t.readyState>2},e.prototype._isSourceReady=function(){return 3===this.source.readyState||4===this.source.readyState},e.prototype._onPlayStart=function(){this.hasLoaded||this._onCanPlay(),!this._isAutoUpdating&&this.autoUpdate&&(p.shared.add(this.update,this),this._isAutoUpdating=!0)},e.prototype._onPlayStop=function(){this._isAutoUpdating&&(p.shared.remove(this.update,this),this._isAutoUpdating=!1)},e.prototype._onCanPlay=function(){this.hasLoaded=!0,this.source&&(this.source.removeEventListener("canplay",this._onCanPlay),this.source.removeEventListener("canplaythrough",this._onCanPlay),this.width=this.source.videoWidth,this.height=this.source.videoHeight,this.__loaded||(this.__loaded=!0,this.emit("loaded",this)),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.source.play())},e.prototype.destroy=function(){this._isAutoUpdating&&p.shared.remove(this.update,this),this.source&&this.source._pixiId&&(delete f.BaseTextureCache[this.source._pixiId],delete this.source._pixiId),t.prototype.destroy.call(this)},e.fromVideo=function(t,r){t._pixiId||(t._pixiId="video_"+(0,f.uid)());var i=f.BaseTextureCache[t._pixiId];return i||(i=new e(t,r),f.BaseTextureCache[t._pixiId]=i),i},e.fromUrl=function(t,r){var i=document.createElement("video");if(i.setAttribute("webkit-playsinline",""),i.setAttribute("playsinline",""),Array.isArray(t))for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:performance.now(),e=void 0;t>this.lastTime?(e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),this.deltaTime=e*s.TARGET_FPMS*this.speed,this._emitter.emit(h,this.deltaTime)):this.deltaTime=this.elapsedMS=0,this.lastTime=t},o(t,[{key:"FPS",get:function(){return 1e3/this.elapsedMS}},{key:"minFPS",get:function(){return 1e3/this._maxElapsedMS},set:function(t){var e=Math.min(Math.max(0,t)/1e3,s.TARGET_FPMS);this._maxElapsedMS=1/e}}]),t}();r.default=l},{"../const":42,eventemitter3:3}],112:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.Ticker=r.shared=void 0;var n=t("./Ticker"),o=i(n),s=new o.default;s.autoStart=!0,r.shared=s,r.Ticker=o.default},{"./Ticker":111}],113:[function(t,e,r){"use strict";function i(t){for(var e=6*t,r=new Uint16Array(e),i=0,n=0;i1&&void 0!==arguments[1]?arguments[1]:window.location;if(0===t.indexOf("data:"))return"";e=e||window.location,a||(a=document.createElement("a")),a.href=t,t=s.default.parse(a.href);var r=!t.port&&""===e.port||t.port===e.port;return t.hostname===e.hostname&&r&&t.protocol===e.protocol?"":"anonymous"}r.__esModule=!0,r.default=n;var o=t("url"),s=i(o),a=void 0},{url:36}],115:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(){return++T}function o(t,e){return e=e||[],e[0]=(t>>16&255)/255,e[1]=(t>>8&255)/255,e[2]=(255&t)/255,e}function s(t){return t=t.toString(16),t="000000".substr(0,6-t.length)+t,"#"+t}function a(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]}function u(t){var e=g.RETINA_PREFIX.exec(t);return e?parseFloat(e[1]):1}function h(t){var e=g.DATA_URI.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,encoding:e[3]?e[3].toLowerCase():void 0,data:e[4]}}function l(t){var e=g.URL_FILE_EXTENSION.exec(t);if(e)return e[1].toLowerCase()}function c(t){var e=g.SVG_SIZE.exec(t),r={};return e&&(r[e[1]]=Math.round(parseFloat(e[2])),r[e[3]]=Math.round(parseFloat(e[4]))),r}function f(){w=!0}function d(t){if(!w){if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var e=["\n %c %c %c Pixi.js "+g.VERSION+" - ✰ "+t+" ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n","background: #ff66a5; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff66a5; background: #030307; padding:5px 0;","background: #ff66a5; padding:5px 0;","background: #ffc3dc; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;"];window.console.log.apply(console,e)}else window.console&&window.console.log("Pixi.js "+g.VERSION+" - "+t+" - http://www.pixijs.com/");w=!0}}function p(){var t={stencil:!0,failIfMajorPerformanceCaveat:!0};try{if(!window.WebGLRenderingContext)return!1;var e=document.createElement("canvas"),r=e.getContext("webgl",t)||e.getContext("experimental-webgl",t),i=!(!r||!r.getContextAttributes().stencil);if(r){var n=r.getExtension("WEBGL_lose_context");n&&n.loseContext()}return r=null,i}catch(t){return!1}}function v(t){return 0===t?0:t<0?-1:1}function y(t,e,r){var i=t.length;if(!(e>=i||0===r)){r=e+r>i?i-e:r;for(var n=i-r,o=e;o1?this._fontStyle="italic":t.indexOf("oblique")>-1?this._fontStyle="oblique":this._fontStyle="normal",t.indexOf("small-caps")>-1?this._fontVariant="small-caps":this._fontVariant="normal";var e=t.split(" "),r=-1;this._fontSize=26;for(var i=0;i-1&&r1&&void 0!==arguments[1]?arguments[1]:{};o(this,e);var n=s(this,t.call(this));return n.textWidth=0,n.textHeight=0,n._glyphs=[],n._font={tint:void 0!==i.tint?i.tint:16777215,align:i.align||"left",name:null,size:0},n.font=i.font,n._text=r,n.maxWidth=0,n.maxLineHeight=0,n._anchor=new f.default(function(){n.dirty=!0},n,0,0),n.dirty=!1,n.updateText(),n}return a(e,t),e.prototype.updateText=function(){for(var t=e.fonts[this._font.name],r=this._font.size/t.size,i=new l.Point,n=[],o=[],s=null,a=0,u=0,h=0,c=-1,f=0,d=0,p=0;p0&&i.x*r>this.maxWidth)l.utils.removeItems(n,c,p-c),p=c,c=-1,o.push(f),u=Math.max(u,f),h++,i.x=0,i.y+=t.lineHeight,s=null;else{var y=t.chars[v];y&&(s&&y.kerning[s]&&(i.x+=y.kerning[s]),n.push({texture:y.texture,line:h,charCode:v,position:new l.Point(i.x+y.xOffset,i.y+y.yOffset)}),a=i.x+(y.texture.width+y.xOffset),i.x+=y.xAdvance,d=Math.max(d,y.yOffset+y.texture.height),s=v)}}o.push(a),u=Math.max(u,a);for(var g=[],m=0;m<=h;m++){var _=0;"right"===this._font.align?_=u-o[m]:"center"===this._font.align&&(_=(u-o[m])/2),g.push(_)}for(var b=n.length,x=this.tint,T=0;T=0?t:16777215,this.dirty=!0}},{key:"align",get:function(){return this._font.align},set:function(t){this._font.align=t||"left",this.dirty=!0}},{key:"anchor",get:function(){return this._anchor},set:function(t){"number"==typeof t?this._anchor.set(t):this._anchor.copy(t)}},{key:"font",get:function(){return this._font},set:function(t){t&&("string"==typeof t?(t=t.split(" "),this._font.name=1===t.length?t[0]:t.slice(1).join(" "),this._font.size=t.length>=2?parseInt(t[0],10):e.fonts[this._font.name].size):(this._font.name=t.name,this._font.size="number"==typeof t.size?t.size:parseInt(t.size,10)),this.dirty=!0)}},{key:"text",get:function(){return this._text},set:function(t){t=t.toString()||" ",this._text!==t&&(this._text=t,this.dirty=!0)}}]),e}(l.Container);r.default=d,d.fonts={}},{"../core":61,"../core/math/ObservablePoint":64}],123:[function(t,e,r){"use strict";function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r=this._durations[this.currentFrame];)i-=this._durations[this.currentFrame]*n,this._currentTime+=n;this._currentTime+=i/this._durations[this.currentFrame]}else this._currentTime+=e;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):r!==this.currentFrame&&(this._texture=this._textures[this.currentFrame],this._textureID=-1,this.onFrameChange&&this.onFrameChange(this.currentFrame))},e.prototype.destroy=function(){this.stop(),t.prototype.destroy.call(this)},e.fromFrames=function(t){for(var r=[],i=0;i1&&void 0!==arguments[1]?arguments[1]:100,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:100;o(this,e);var a=s(this,t.call(this,r));return a.tileTransform=new l.TransformStatic,a._width=i,a._height=n,a._canvasPattern=null,a.uvTransform=r.transform||new p.default(r),a}return a(e,t),e.prototype._onTextureUpdate=function(){this.uvTransform&&(this.uvTransform.texture=this._texture)},e.prototype._renderWebGL=function(t){var e=this._texture;e&&e.valid&&(this.tileTransform.updateLocalTransform(),this.uvTransform.update(),t.setObjectRenderer(t.plugins.tilingSprite),t.plugins.tilingSprite.render(this))},e.prototype._renderCanvas=function(t){var e=this._texture;if(e.baseTexture.hasLoaded){var r=t.context,i=this.worldTransform,n=t.resolution,o=e.baseTexture,s=this.tilePosition.x/this.tileScale.x%e._frame.width,a=this.tilePosition.y/this.tileScale.y%e._frame.height;if(!this._canvasPattern){var u=new l.CanvasRenderTarget(e._frame.width,e._frame.height);16777215!==this.tint?(this.cachedTint!==this.tint&&(this.cachedTint=this.tint,this.tintedTexture=f.default.getTintedTexture(this,this.tint)),u.context.drawImage(this.tintedTexture,0,0)):u.context.drawImage(o.source,-e._frame.x,-e._frame.y),this._canvasPattern=u.context.createPattern(u.canvas,"repeat")}r.globalAlpha=this.worldAlpha,r.setTransform(i.a*n,i.b*n,i.c*n,i.d*n,i.tx*n,i.ty*n),r.scale(this.tileScale.x,this.tileScale.y),r.translate(s+this.anchor.x*-this._width,a+this.anchor.y*-this._height);var h=t.blendModes[this.blendMode];h!==t.context.globalCompositeOperation&&(r.globalCompositeOperation=h),r.fillStyle=this._canvasPattern,r.fillRect(-s,-a,this._width/this.tileScale.x,this._height/this.tileScale.y)}},e.prototype.getLocalBounds=function(e){return 0===this.children.length?(this._bounds.minX=-this._width*this.anchor._x,this._bounds.minY=-this._height*this.anchor._y,this._bounds.maxX=this._width,this._bounds.maxY=this._height,e||(this._localBoundsRect||(this._localBoundsRect=new l.Rectangle),e=this._localBoundsRect),this._bounds.getRectangle(e)):t.prototype.getLocalBounds.call(this,e)},e.prototype.getBounds=function(){var t=this._width,e=this._height,r=t*(1-this.anchor.x),i=t*-this.anchor.x,n=e*(1-this.anchor.y),o=e*-this.anchor.y,s=this.worldTransform,a=s.a,u=s.b,h=s.c,l=s.d,c=s.tx,f=s.ty,d=a*i+h*o+c,p=l*o+u*i+f,v=a*r+h*o+c,y=l*o+u*r+f,g=a*r+h*n+c,m=l*n+u*r+f,_=a*i+h*n+c,b=l*n+u*i+f,x=0,T=0,w=0,E=0;x=d,x=vT?v:T,T=g>T?g:T,T=_>T?_:T,E=p,E=y>E?y:E,E=m>E?m:E,E=b>E?b:E;var S=this._bounds;return S.x=x,S.width=T-x,S.y=w,S.height=E-w,this._currentBounds=S,S},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,v);var e=this._width,r=this._height,i=-e*this.anchor.x;if(v.x>i&&v.xn&&v.y0&&void 0!==arguments[0]?arguments[0]:new o.Point;return this.parent?(this.displayObjectUpdateTransform(),t.x=this.worldTransform.tx,t.y=this.worldTransform.ty):(t.x=this.position.x,t.y=this.position.y),t}},{"../core":61}],129:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var n=t("./TextureTransform");Object.defineProperty(r,"TextureTransform",{enumerable:!0,get:function(){return i(n).default}});var o=t("./MovieClip");Object.defineProperty(r,"MovieClip",{enumerable:!0,get:function(){return i(o).default}});var s=t("./TilingSprite");Object.defineProperty(r,"TilingSprite",{enumerable:!0,get:function(){return i(s).default}});var a=t("./webgl/TilingSpriteRenderer");Object.defineProperty(r,"TilingSpriteRenderer",{enumerable:!0,get:function(){return i(a).default}});var u=t("./BitmapText");Object.defineProperty(r,"BitmapText",{enumerable:!0,get:function(){return i(u).default}});var h=t("./cacheAsBitmap");Object.defineProperty(r,"cacheAsBitmap",{enumerable:!0,get:function(){return i(h).default}});var l=t("./getChildByName");Object.defineProperty(r,"getChildByName",{enumerable:!0,get:function(){return i(l).default}});var c=t("./getGlobalPosition");Object.defineProperty(r,"getGlobalPosition",{enumerable:!0,get:function(){return i(c).default}})},{"./BitmapText":122,"./MovieClip":123,"./TextureTransform":124,"./TilingSprite":125,"./cacheAsBitmap":126,"./getChildByName":127,"./getGlobalPosition":128,"./webgl/TilingSpriteRenderer":130}],130:[function(t,e,r){"use strict";function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0,r.TilingSpriteRenderer=void 0;var a=t("../../core"),u=i(a),h=t("../../core/const"),l=new u.Matrix,c=new Float32Array(4),f=r.TilingSpriteRenderer=function(t){function e(r){n(this,e);var i=o(this,t.call(this,r));return i.shader=null,i.simpleShader=null,i.quad=null,i}return s(e,t),e.prototype.onContextChange=function(){var t=this.renderer.gl;this.shader=new u.Shader(t,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n gl_FragColor = sample * color ;\n}\n"),this.simpleShader=new u.Shader(t,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n gl_FragColor = sample * color;\n}\n"),this.quad=new u.Quad(t),this.quad.initVao(this.shader)},e.prototype.render=function(t){var e=this.quad,r=e.vertices;r[0]=r[6]=t._width*-t.anchor.x,r[1]=r[3]=t._height*-t.anchor.y,r[2]=r[4]=t._width*(1-t.anchor.x),r[5]=r[7]=t._height*(1-t.anchor.y),r=e.uvs,r[0]=r[6]=-t.anchor.x,r[1]=r[3]=-t.anchor.y,r[2]=r[4]=1-t.anchor.x,r[5]=r[7]=1-t.anchor.y,e.upload();var i=this.renderer,n=t._texture,o=n.baseTexture,s=t.tileTransform.localTransform,a=t.uvTransform,f=o.isPowerOfTwo&&n.frame.width===o.width&&n.frame.height===o.height;f&&(o._glTextures[i.CONTEXT_UID]?f=o.wrapMode!==h.WRAP_MODES.CLAMP:o.wrapMode===h.WRAP_MODES.CLAMP&&(o.wrapMode=h.WRAP_MODES.REPEAT));var d=f?this.simpleShader:this.shader;i.bindShader(d);var p=n.width,v=n.height,y=t._width,g=t._height;l.set(s.a*p/y,s.b*p/g,s.c*v/y,s.d*v/g,s.tx/y,s.ty/g),l.invert(),f?l.append(a.mapCoord):(d.uniforms.uMapCoord=a.mapCoord.toArray(!0),d.uniforms.uClampFrame=a.uClampFrame,d.uniforms.uClampOffset=a.uClampOffset),d.uniforms.uTransform=l.toArray(!0);var m=c;u.utils.hex2rgb(t.tint,m),m[3]=t.worldAlpha,d.uniforms.uColor=m,d.uniforms.translationMatrix=t.transform.worldTransform.toArray(!0),i.bindTexture(n),i.setBlendMode(t.blendMode),e.draw()},e}(u.ObjectRenderer);u.WebGLRenderer.registerPlugin("tilingSprite",f)},{"../../core":61,"../../core/const":42}],131:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var u=function(){function t(t,e){for(var r=0;r=r&&(u=t-h-1),l=l.replace("%value%",e[u]),s+=l,s+="\n"}return i=i.replace("%blur%",s),i=i.replace("%size%",t)}r.__esModule=!0,r.default=i;var n={5:[.153388,.221461,.250301],7:[.071303,.131514,.189879,.214607],9:[.028532,.067234,.124009,.179044,.20236],11:[.0093,.028002,.065984,.121703,.175713,.198596],13:[.002406,.009255,.027867,.065666,.121117,.174868,.197641],15:[489e-6,.002403,.009246,.02784,.065602,.120999,.174697,.197448]},o=["varying vec2 vBlurTexCoords[%size%];","uniform sampler2D uSampler;","void main(void)","{"," gl_FragColor = vec4(0.0);"," %blur%","}"].join("\n")},{}],135:[function(t,e,r){"use strict";function i(t,e){var r=Math.ceil(t/2),i=n,o="",s=void 0;s=e?"vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);":"vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);";for(var a=0;ae;)r-=2;return r}r.__esModule=!0,r.default=i},{}],137:[function(t,e,r){"use strict";function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]&&arguments[1],r=t;e&&(this._multiply(r,this.uniforms.m,t),r=this._colorMatrix(r)),this.uniforms.m=r},e.prototype._multiply=function(t,e,r){return t[0]=e[0]*r[0]+e[1]*r[5]+e[2]*r[10]+e[3]*r[15],t[1]=e[0]*r[1]+e[1]*r[6]+e[2]*r[11]+e[3]*r[16],t[2]=e[0]*r[2]+e[1]*r[7]+e[2]*r[12]+e[3]*r[17],t[3]=e[0]*r[3]+e[1]*r[8]+e[2]*r[13]+e[3]*r[18],t[4]=e[0]*r[4]+e[1]*r[9]+e[2]*r[14]+e[3]*r[19],t[5]=e[5]*r[0]+e[6]*r[5]+e[7]*r[10]+e[8]*r[15],t[6]=e[5]*r[1]+e[6]*r[6]+e[7]*r[11]+e[8]*r[16],t[7]=e[5]*r[2]+e[6]*r[7]+e[7]*r[12]+e[8]*r[17],t[8]=e[5]*r[3]+e[6]*r[8]+e[7]*r[13]+e[8]*r[18],t[9]=e[5]*r[4]+e[6]*r[9]+e[7]*r[14]+e[8]*r[19],t[10]=e[10]*r[0]+e[11]*r[5]+e[12]*r[10]+e[13]*r[15],t[11]=e[10]*r[1]+e[11]*r[6]+e[12]*r[11]+e[13]*r[16],t[12]=e[10]*r[2]+e[11]*r[7]+e[12]*r[12]+e[13]*r[17],t[13]=e[10]*r[3]+e[11]*r[8]+e[12]*r[13]+e[13]*r[18],t[14]=e[10]*r[4]+e[11]*r[9]+e[12]*r[14]+e[13]*r[19],t[15]=e[15]*r[0]+e[16]*r[5]+e[17]*r[10]+e[18]*r[15],t[16]=e[15]*r[1]+e[16]*r[6]+e[17]*r[11]+e[18]*r[16],t[17]=e[15]*r[2]+e[16]*r[7]+e[17]*r[12]+e[18]*r[17],t[18]=e[15]*r[3]+e[16]*r[8]+e[17]*r[13]+e[18]*r[18],t[19]=e[15]*r[4]+e[16]*r[9]+e[17]*r[14]+e[18]*r[19],t},e.prototype._colorMatrix=function(t){var e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e},e.prototype.brightness=function(t,e){var r=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.greyscale=function(t,e){var r=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.blackAndWhite=function(t){var e=[.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.hue=function(t,e){t=(t||0)/180*Math.PI;var r=Math.cos(t),i=Math.sin(t),n=Math.sqrt,o=1/3,s=n(o),a=r+(1-r)*o,u=o*(1-r)-s*i,h=o*(1-r)+s*i,l=o*(1-r)+s*i,c=r+o*(1-r),f=o*(1-r)-s*i,d=o*(1-r)-s*i,p=o*(1-r)+s*i,v=r+o*(1-r),y=[a,u,h,0,0,l,c,f,0,0,d,p,v,0,0,0,0,0,1,0];this._loadMatrix(y,e)},e.prototype.contrast=function(t,e){var r=(t||0)+1,i=-128*(r-1),n=[r,0,0,0,i,0,r,0,0,i,0,0,r,0,i,0,0,0,1,0];this._loadMatrix(n,e)},e.prototype.saturate=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=2*t/3+1,i=(r-1)*-.5,n=[r,i,i,0,0,i,r,i,0,0,i,i,r,0,0,0,0,0,1,0];this._loadMatrix(n,e)},e.prototype.desaturate=function(){this.saturate(-1)},e.prototype.negative=function(t){var e=[0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.sepia=function(t){var e=[.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.technicolor=function(t){var e=[1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.polaroid=function(t){var e=[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.toBGR=function(t){var e=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.kodachrome=function(t){var e=[1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.browni=function(t){var e=[.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.vintage=function(t){var e=[.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.colorTone=function(t,e,r,i,n){t=t||.2,e=e||.15,r=r||16770432,i=i||3375104;var o=(r>>16&255)/255,s=(r>>8&255)/255,a=(255&r)/255,u=(i>>16&255)/255,h=(i>>8&255)/255,l=(255&i)/255,c=[.3,.59,.11,0,0,o,s,a,t,0,u,h,l,e,0,o-u,s-h,a-l,0,0];this._loadMatrix(c,n)},e.prototype.night=function(t,e){t=t||.1;var r=[t*-2,-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.predator=function(t,e){var r=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.lsd=function(t){var e=[2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.reset=function(){var t=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(t,!1)},a(e,[{key:"matrix",get:function(){return this.uniforms.m},set:function(t){this.uniforms.m=t}}]),e}(h.Filter);r.default=l,l.prototype.grayscale=l.prototype.greyscale},{"../../core":61}],138:[function(t,e,r){"use strict";function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n'))}return s(e,t),e}(u.Filter);r.default=h},{"../../core":61}],140:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var n=t("./fxaa/FXAAFilter");Object.defineProperty(r,"FXAAFilter",{enumerable:!0,get:function(){return i(n).default}});var o=t("./noise/NoiseFilter");Object.defineProperty(r,"NoiseFilter",{enumerable:!0,get:function(){return i(o).default}});var s=t("./displacement/DisplacementFilter");Object.defineProperty(r,"DisplacementFilter",{enumerable:!0,get:function(){return i(s).default}});var a=t("./blur/BlurFilter");Object.defineProperty(r,"BlurFilter",{enumerable:!0,get:function(){return i(a).default}});var u=t("./blur/BlurXFilter");Object.defineProperty(r,"BlurXFilter",{enumerable:!0,get:function(){return i(u).default}});var h=t("./blur/BlurYFilter");Object.defineProperty(r,"BlurYFilter",{enumerable:!0,get:function(){return i(h).default}});var l=t("./colormatrix/ColorMatrixFilter");Object.defineProperty(r,"ColorMatrixFilter",{enumerable:!0,get:function(){return i(l).default}});var c=t("./void/VoidFilter");Object.defineProperty(r,"VoidFilter",{enumerable:!0,get:function(){return i(c).default}})},{"./blur/BlurFilter":131,"./blur/BlurXFilter":132,"./blur/BlurYFilter":133,"./colormatrix/ColorMatrixFilter":137,"./displacement/DisplacementFilter":138,"./fxaa/FXAAFilter":139,"./noise/NoiseFilter":141,"./void/VoidFilter":142}],141:[function(t,e,r){"use strict";function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:1;this.removeEvents(),this.interactionDOMElement=t,this.resolution=e,this.addEvents()},e.prototype.addEvents=function(){this.interactionDOMElement&&(h.ticker.shared.add(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="none",this.interactionDOMElement.style["-ms-touch-action"]="none"):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]="none"),window.document.addEventListener("mousemove",this.onMouseMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onMouseDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onMouseOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onMouseOver,!0),window.addEventListener("mouseup",this.onMouseUp,!0),this.supportsTouchEvents&&(this.interactionDOMElement.addEventListener("touchstart",this.onTouchStart,!0),this.interactionDOMElement.addEventListener("touchend",this.onTouchEnd,!0),this.interactionDOMElement.addEventListener("touchmove",this.onTouchMove,!0)),this.supportsPointerEvents?(window.document.addEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("pointerout",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("pointerover",this.onPointerOver,!0),window.addEventListener("pointerup",this.onPointerUp,!0)):(this.normalizeTouchEvents&&(this.interactionDOMElement.addEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.addEventListener("touchmove",this.onPointerMove,!0)),this.normalizeMouseEvents&&(window.document.addEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onPointerOver,!0),window.addEventListener("mouseup",this.onPointerUp,!0))),this.eventsAdded=!0)},e.prototype.removeEvents=function(){this.interactionDOMElement&&(h.ticker.shared.remove(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="",this.interactionDOMElement.style["-ms-touch-action"]=""):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]=""),window.document.removeEventListener("mousemove",this.onMouseMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onMouseDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onMouseOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onMouseOver,!0),window.removeEventListener("mouseup",this.onMouseUp,!0),this.supportsTouchEvents&&(this.interactionDOMElement.removeEventListener("touchstart",this.onTouchStart,!0),this.interactionDOMElement.removeEventListener("touchend",this.onTouchEnd,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onTouchMove,!0)),this.supportsPointerEvents?(window.document.removeEventListener("pointermove",this.onPointerMove,!0), +this.interactionDOMElement.removeEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("pointerout",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("pointerover",this.onPointerOver,!0),window.removeEventListener("pointerup",this.onPointerUp,!0)):(this.normalizeTouchEvents&&(this.interactionDOMElement.removeEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onPointerMove,!0)),this.normalizeMouseEvents&&(window.document.removeEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onPointerOver,!0),window.removeEventListener("mouseup",this.onPointerUp,!0))),this.interactionDOMElement=null,this.eventsAdded=!1)},e.prototype.update=function(t){if(this._deltaTime+=t,!(this._deltaTime=0;u--){var h=a[u];if(this.processInteractive(t,h,r,i,s)){if(!h.parent)continue;o=!0,s=!1,i=!1}}return n&&(i&&!o&&(e.hitArea?(e.worldTransform.applyInverse(t,this._tempPoint),o=e.hitArea.contains(this._tempPoint.x,this._tempPoint.y)):e.containsPoint&&(o=e.containsPoint(t))),e.interactive&&(o&&!this.eventData.target&&(this.eventData.target=e,this.mouse.target=e,this.pointer.target=e),r(e,o))),o},e.prototype.onMouseDown=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData._reset(),this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.autoPreventDefault&&this.mouse.originalEvent.preventDefault(),this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseDown,!0);var e=2===t.button||3===t.which;this.emit(e?"rightdown":"mousedown",this.eventData)},e.prototype.processMouseDown=function(t,e){var r=this.mouse.originalEvent,i=2===r.button||3===r.which;e&&(t[i?"_isRightDown":"_isLeftDown"]=!0,this.dispatchEvent(t,i?"rightdown":"mousedown",this.eventData))},e.prototype.onMouseUp=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData._reset(),this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseUp,!0);var e=2===t.button||3===t.which;this.emit(e?"rightup":"mouseup",this.eventData)},e.prototype.processMouseUp=function(t,e){var r=this.mouse.originalEvent,i=2===r.button||3===r.which,n=i?"_isRightDown":"_isLeftDown";e?(this.dispatchEvent(t,i?"rightup":"mouseup",this.eventData),t[n]&&(t[n]=!1,this.dispatchEvent(t,i?"rightclick":"click",this.eventData))):t[n]&&(t[n]=!1,this.dispatchEvent(t,i?"rightupoutside":"mouseupoutside",this.eventData))},e.prototype.onMouseMove=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData._reset(),this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.didMove=!0,this.cursor=this.defaultCursorStyle,this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseMove,!0),this.emit("mousemove",this.eventData),this.currentCursorStyle!==this.cursor&&(this.currentCursorStyle=this.cursor,this.interactionDOMElement.style.cursor=this.cursor)},e.prototype.processMouseMove=function(t,e){this.processMouseOverOut(t,e),this.moveWhenInside&&!e||this.dispatchEvent(t,"mousemove",this.eventData)},e.prototype.onMouseOut=function(t){this.mouseOverRenderer=!1,this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData._reset(),this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.interactionDOMElement.style.cursor=this.defaultCursorStyle,this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseOverOut,!1),this.emit("mouseout",this.eventData)},e.prototype.processMouseOverOut=function(t,e){e&&this.mouseOverRenderer?(t._mouseOver||(t._mouseOver=!0,this.dispatchEvent(t,"mouseover",this.eventData)),t.buttonMode&&(this.cursor=t.defaultCursor)):t._mouseOver&&(t._mouseOver=!1,this.dispatchEvent(t,"mouseout",this.eventData))},e.prototype.onMouseOver=function(t){this.mouseOverRenderer=!0,this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData._reset(),this.emit("mouseover",this.eventData)},e.prototype.onPointerDown=function(t){this.normalizeToPointerData(t),this.pointer.originalEvent=t,this.eventData.data=this.pointer,this.eventData._reset(),this.mapPositionToPoint(this.pointer.global,t.clientX,t.clientY),this.autoPreventDefault&&this.pointer.originalEvent.preventDefault(),this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerDown,!0),this.emit("pointerdown",this.eventData)},e.prototype.processPointerDown=function(t,e){e&&(t._pointerDown=!0,this.dispatchEvent(t,"pointerdown",this.eventData))},e.prototype.onPointerUp=function(t){this.normalizeToPointerData(t),this.pointer.originalEvent=t,this.eventData.data=this.pointer,this.eventData._reset(),this.mapPositionToPoint(this.pointer.global,t.clientX,t.clientY),this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerUp,!0),this.emit("pointerup",this.eventData)},e.prototype.processPointerUp=function(t,e){e?(this.dispatchEvent(t,"pointerup",this.eventData),t._pointerDown&&(t._pointerDown=!1,this.dispatchEvent(t,"pointertap",this.eventData))):t._pointerDown&&(t._pointerDown=!1,this.dispatchEvent(t,"pointerupoutside",this.eventData))},e.prototype.onPointerMove=function(t){this.normalizeToPointerData(t),this.pointer.originalEvent=t,this.eventData.data=this.pointer,this.eventData._reset(),this.mapPositionToPoint(this.pointer.global,t.clientX,t.clientY),this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerMove,!0),this.emit("pointermove",this.eventData)},e.prototype.processPointerMove=function(t,e){this.pointer.originalEvent.changedTouches||this.processPointerOverOut(t,e),this.moveWhenInside&&!e||this.dispatchEvent(t,"pointermove",this.eventData)},e.prototype.onPointerOut=function(t){this.normalizeToPointerData(t),this.pointer.originalEvent=t,this.eventData.data=this.pointer,this.eventData._reset(),this.mapPositionToPoint(this.pointer.global,t.clientX,t.clientY),this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerOverOut,!1),this.emit("pointerout",this.eventData)},e.prototype.processPointerOverOut=function(t,e){e&&this.mouseOverRenderer?t._pointerOver||(t._pointerOver=!0,this.dispatchEvent(t,"pointerover",this.eventData)):t._pointerOver&&(t._pointerOver=!1,this.dispatchEvent(t,"pointerout",this.eventData))},e.prototype.onPointerOver=function(t){this.pointer.originalEvent=t,this.eventData.data=this.pointer,this.eventData._reset(),this.emit("pointerover",this.eventData)},e.prototype.onTouchStart=function(t){this.autoPreventDefault&&t.preventDefault();for(var e=t.changedTouches,r=e.length,i=0;i0){var T=this.canvasPadding/this.worldTransform.a,w=this.canvasPadding/this.worldTransform.d,E=(y+g+m)/3,S=(_+b+x)/3,O=y-E,M=_-S,P=Math.sqrt(O*O+M*M);y=E+O/P*(P+T),_=S+M/P*(P+w),O=g-E,M=b-S,P=Math.sqrt(O*O+M*M),g=E+O/P*(P+T),b=S+M/P*(P+w),O=m-E,M=x-S,P=Math.sqrt(O*O+M*M),m=E+O/P*(P+T),x=S+M/P*(P+w)}t.save(),t.beginPath(),t.moveTo(y,_),t.lineTo(g,b),t.lineTo(m,x),t.closePath(),t.clip();var C=l*p+d*f+c*v-p*f-d*c-l*v,R=y*p+d*m+g*v-p*m-d*g-y*v,D=l*g+y*f+c*m-g*f-y*c-l*m,A=l*p*m+d*g*f+y*c*v-y*p*f-d*c*m-l*g*v,I=_*p+d*x+b*v-p*x-d*b-_*v,L=l*b+_*f+c*x-b*f-_*c-l*x,j=l*p*x+d*b*f+_*c*v-_*p*f-d*c*x-l*b*v;t.transform(R/C,I/C,D/C,L/C,A/C,j/C),t.drawImage(a,0,0,u*s.resolution,h*s.resolution,0,0,u,h),t.restore()},e.prototype.renderMeshFlat=function(t){var e=this.context,r=t.vertices,i=r.length/2;e.beginPath();for(var n=1;n1&&(l=1);var c=Math.sqrt(i*i+n*n),f=this._texture.height/2;i/=c,n/=c,i*=f,n*=f,o[h]=u.x+i,o[h+1]=u.y+n,o[h+2]=u.x-i,o[h+3]=u.y-n,e=u}this.containerUpdateTransform()}},e}(h.default);r.default=f},{"../core":61,"./Mesh":153}],157:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var n=t("./Mesh");Object.defineProperty(r,"Mesh",{enumerable:!0,get:function(){return i(n).default}});var o=t("./Plane");Object.defineProperty(r,"Plane",{enumerable:!0,get:function(){return i(o).default}});var s=t("./NineSlicePlane");Object.defineProperty(r,"NineSlicePlane",{enumerable:!0,get:function(){return i(s).default}});var a=t("./Rope");Object.defineProperty(r,"Rope",{enumerable:!0,get:function(){return i(a).default}});var u=t("./webgl/MeshShader");Object.defineProperty(r,"MeshShader",{enumerable:!0,get:function(){return i(u).default}})},{"./Mesh":153,"./NineSlicePlane":154,"./Plane":155,"./Rope":156,"./webgl/MeshShader":158}],158:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../core/Shader"),u=i(a),h=function(t){function e(r){return n(this,e),o(this,t.call(this,r,["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","varying vec2 vTextureCoord;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vTextureCoord = aTextureCoord;","}"].join("\n"),["varying vec2 vTextureCoord;","uniform float alpha;","uniform vec3 tint;","uniform sampler2D uSampler;","void main(void){"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vec4(tint * alpha, alpha);","}"].join("\n")))}return s(e,t),e}(u.default);r.default=h},{"../../core/Shader":41}],159:[function(t,e,r){"use strict";function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../core"),u=i(a),h=function(t){function e(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1500,i=arguments[1],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16384;n(this,e);var a=o(this,t.call(this)),h=16384;return s>h&&(s=h),s>r&&(s=r),a._properties=[!1,!0,!1,!1,!1],a._maxSize=r,a._batchSize=s,a._glBuffers=[],a._bufferToUpdate=0,a.interactiveChildren=!1,a.blendMode=u.BLEND_MODES.NORMAL,a.roundPixels=!0,a.baseTexture=null,a.setProperties(i),a}return s(e,t),e.prototype.setProperties=function(t){t&&(this._properties[0]="scale"in t?!!t.scale:this._properties[0],this._properties[1]="position"in t?!!t.position:this._properties[1],this._properties[2]="rotation"in t?!!t.rotation:this._properties[2],this._properties[3]="uvs"in t?!!t.uvs:this._properties[3],this._properties[4]="alpha"in t?!!t.alpha:this._properties[4])},e.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},e.prototype.renderWebGL=function(t){var e=this;this.visible&&!(this.worldAlpha<=0)&&this.children.length&&this.renderable&&(this.baseTexture||(this.baseTexture=this.children[0]._texture.baseTexture,this.baseTexture.hasLoaded||this.baseTexture.once("update",function(){return e.onChildrenChange(0)})),t.setObjectRenderer(t.plugins.particle),t.plugins.particle.render(this))},e.prototype.onChildrenChange=function(t){var e=Math.floor(t/this._batchSize);er&&(n=r);var o=t._glBuffers[this.renderer.CONTEXT_UID];o||(o=t._glBuffers[this.renderer.CONTEXT_UID]=this.generateBuffers(t)),this.renderer.setBlendMode(t.blendMode);var s=this.renderer.gl,a=t.worldTransform.copy(this.tempMatrix);a.prepend(this.renderer._activeRenderTarget.projectionMatrix),this.shader.uniforms.projectionMatrix=a.toArray(!0),this.shader.uniforms.uAlpha=t.worldAlpha;var u=e[0]._texture.baseTexture;this.renderer.bindTexture(u);for(var h=0,l=0;hi&&(c=i);var f=o[l];f.uploadDynamic(e,h,c),t._bufferToUpdate===l&&(f.uploadStatic(e,h,c),t._bufferToUpdate=l+1),f.vao.bind().draw(s.TRIANGLES,6*c).unbind()}}},e.prototype.generateBuffers=function(t){for(var e=this.renderer.gl,r=[],i=t._maxSize,n=t._batchSize,o=t._properties,s=0;s0?1:-1})},{}],165:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}var n=t("object-assign"),o=i(n);Object.assign||(Object.assign=o.default)},{"object-assign":5}],166:[function(t,e,r){"use strict";t("./Object.assign"),t("./requestAnimationFrame"),t("./Math.sign"),window.ArrayBuffer||(window.ArrayBuffer=Array),window.Float32Array||(window.Float32Array=Array),window.Uint32Array||(window.Uint32Array=Array),window.Uint16Array||(window.Uint16Array=Array)},{"./Math.sign":164,"./Object.assign":165,"./requestAnimationFrame":167}],167:[function(t,e,r){(function(t){"use strict";var e=16;Date.now&&Date.prototype.getTime||(Date.now=function(){return(new Date).getTime()}),t.performance&&t.performance.now||!function(){var e=Date.now();t.performance||(t.performance={}),t.performance.now=function(){return Date.now()-e}}();for(var r=Date.now(),i=["ms","moz","webkit","o"],n=0;n0;){for(var e=this.queue[0],r=!1,i=0,n=this.uploadHooks.length;i=0;i--)this.add(t.children[i]);return this},t.prototype.destroy=function(){this.ticking&&h.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null,this.ctx=null,this.canvas=null},t}();r.default=f,f.UPLOADS_PER_FRAME=c,u.CanvasRenderer.registerPlugin("prepare",f)},{"../../core":61}],169:[function(t,e,r){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var n=t("./webgl/WebGLPrepare");Object.defineProperty(r,"webgl",{enumerable:!0,get:function(){return i(n).default}});var o=t("./canvas/CanvasPrepare");Object.defineProperty(r,"canvas",{enumerable:!0,get:function(){return i(o).default}})},{"./canvas/CanvasPrepare":168,"./webgl/WebGLPrepare":170}],170:[function(t,e,r){"use strict";function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){return e instanceof l.BaseTexture&&(t.textureManager.updateTexture(e),!0)}function s(t,e){return e instanceof l.Graphics&&(t.plugins.graphics.updateGraphics(e),!0)}function a(t,e){if(t instanceof l.BaseTexture)return e.indexOf(t)===-1&&e.push(t),!0;if(t._texture&&t._texture instanceof l.Texture){var r=t._texture.baseTexture;return e.indexOf(r)===-1&&e.push(r),!0}return!1}function u(t,e){return t instanceof l.Graphics&&(e.push(t),!0)}r.__esModule=!0;var h=t("../../core"),l=i(h),c=l.ticker.shared,f=4,d=function(){function t(e){n(this,t),this.renderer=e,this.queue=[],this.addHooks=[],this.uploadHooks=[],this.completes=[],this.ticking=!1,this.register(a,o).register(u,s)}return t.prototype.upload=function(e,r){"function"==typeof e&&(r=e,e=null),e&&this.add(e),this.queue.length?(this.numLeft=t.UPLOADS_PER_FRAME,r&&this.completes.push(r),this.ticking||(this.ticking=!0,c.add(this.tick,this))):r&&r()},t.prototype.tick=function(){for(;this.queue.length&&this.numLeft>0;){for(var e=this.queue[0],r=!1,i=0,n=this.uploadHooks.length;i=0;i--)this.add(t.children[i]);return this},t.prototype.destroy=function(){this.ticking&&c.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null},t}();r.default=d,d.UPLOADS_PER_FRAME=f,l.WebGLRenderer.registerPlugin("prepare",d)},{"../../core":61}],171:[function(t,e,r){(function(e){"use strict";function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}r.__esModule=!0,r.loader=r.prepare=r.particles=r.mesh=r.loaders=r.interaction=r.filters=r.extras=r.extract=r.accessibility=void 0;var n=t("./deprecation");Object.keys(n).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return n[t]}})});var o=t("./core");Object.keys(o).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return o[t]}})}),t("./polyfill");var s=t("./accessibility"),a=i(s),u=t("./extract"),h=i(u),l=t("./extras"),c=i(l),f=t("./filters"),d=i(f),p=t("./interaction"),v=i(p),y=t("./loaders"),g=i(y),m=t("./mesh"),_=i(m),b=t("./particles"),x=i(b),T=t("./prepare"),w=i(T);r.accessibility=a,r.extract=h,r.extras=c,r.filters=d,r.interaction=v,r.loaders=g,r.mesh=_,r.particles=x,r.prepare=w;var E=new g.Loader;r.loader=E,e.PIXI=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./accessibility":40,"./core":61,"./deprecation":118,"./extract":120,"./extras":129,"./filters":140,"./interaction":146,"./loaders":149,"./mesh":157,"./particles":160,"./polyfill":166,"./prepare":169}]},{},[171])(171)}); +//# sourceMappingURL=pixi.min.js.map diff --git a/js/pixi/4.0.3/pixi.js b/js/pixi/4.0.3/pixi.js new file mode 100644 index 0000000..ed1d4cc --- /dev/null +++ b/js/pixi/4.0.3/pixi.js @@ -0,0 +1,31257 @@ +/*! + * pixi.js - v4.0.3 + * Compiled Thu Sep 29 2016 12:09:34 GMT-0400 (EDT) + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.PIXI = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],2:[function(require,module,exports){ +'use strict'; + +module.exports = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, size), + maxZ = zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, size); + earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and size of the data bounding box +function zOrder(x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; + +},{}],3:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty; + +// +// We store our EE objects in a plain object whose properties are event names. +// If `Object.create(null)` is not supported we prefix the event names with a +// `~` to make sure that the built-in object properties are not overridden or +// used as an attack vector. +// We also assume that `Object.create(null)` is available when the event name +// is an ES6 Symbol. +// +var prefix = typeof Object.create !== 'function' ? '~' : false; + +/** + * Representation of a single EventEmitter function. + * + * @param {Function} fn Event handler to be called. + * @param {Mixed} context Context for function execution. + * @param {Boolean} [once=false] Only emit once + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal EventEmitter interface that is molded against the Node.js + * EventEmitter interface. + * + * @constructor + * @api public + */ +function EventEmitter() { /* Nothing to set */ } + +/** + * Hold the assigned EventEmitters by name. + * + * @type {Object} + * @private + */ +EventEmitter.prototype._events = undefined; + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @api public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var events = this._events + , names = [] + , name; + + if (!events) return names; + + for (name in events) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return a list of assigned event listeners. + * + * @param {String} event The events that should be listed. + * @param {Boolean} exists We only need to know if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events && this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Emit an event to all registered event listeners. + * + * @param {String} event The name of the event. + * @returns {Boolean} Indication if we've emitted an event. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events || !this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if ('function' === typeof listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Register a new EventListener for the given event. + * + * @param {String} event Name of the event. + * @param {Function} fn Callback function. + * @param {Mixed} [context=this] The context of the function. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events) this._events = prefix ? {} : Object.create(null); + if (!this._events[evt]) this._events[evt] = listener; + else { + if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [ + this._events[evt], listener + ]; + } + + return this; +}; + +/** + * Add an EventListener that's only called once. + * + * @param {String} event Name of the event. + * @param {Function} fn Callback function. + * @param {Mixed} [context=this] The context of the function. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events) this._events = prefix ? {} : Object.create(null); + if (!this._events[evt]) this._events[evt] = listener; + else { + if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [ + this._events[evt], listener + ]; + } + + return this; +}; + +/** + * Remove event listeners. + * + * @param {String} event The event we want to remove. + * @param {Function} fn The listener that we need to find. + * @param {Mixed} context Only remove listeners matching this context. + * @param {Boolean} once Only remove once listeners. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events || !this._events[evt]) return this; + + var listeners = this._events[evt] + , events = []; + + if (fn) { + if (listeners.fn) { + if ( + listeners.fn !== fn + || (once && !listeners.once) + || (context && listeners.context !== context) + ) { + events.push(listeners); + } + } else { + for (var i = 0, length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) { + this._events[evt] = events.length === 1 ? events[0] : events; + } else { + delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners or only the listeners for the specified event. + * + * @param {String} event The event want to remove all listeners for. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + if (!this._events) return this; + + if (event) delete this._events[prefix ? prefix + event : event]; + else this._events = prefix ? {} : Object.create(null); + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],4:[function(require,module,exports){ +/** + * isMobile.js v0.4.0 + * + * A simple library to detect Apple phones and tablets, + * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone), + * and any kind of seven inch device, via user agent sniffing. + * + * @author: Kai Mallea (kmallea@gmail.com) + * + * @license: http://creativecommons.org/publicdomain/zero/1.0/ + */ +(function (global) { + + var apple_phone = /iPhone/i, + apple_ipod = /iPod/i, + apple_tablet = /iPad/i, + android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i, // Match 'Android' AND 'Mobile' + android_tablet = /Android/i, + amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i, + amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i, + windows_phone = /IEMobile/i, + windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i, // Match 'Windows' AND 'ARM' + other_blackberry = /BlackBerry/i, + other_blackberry_10 = /BB10/i, + other_opera = /Opera Mini/i, + other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i, + other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i, // Match 'Firefox' AND 'Mobile' + seven_inch = new RegExp( + '(?:' + // Non-capturing group + + 'Nexus 7' + // Nexus 7 + + '|' + // OR + + 'BNTV250' + // B&N Nook Tablet 7 inch + + '|' + // OR + + 'Kindle Fire' + // Kindle Fire + + '|' + // OR + + 'Silk' + // Kindle Fire, Silk Accelerated + + '|' + // OR + + 'GT-P1000' + // Galaxy Tab 7 inch + + ')', // End non-capturing group + + 'i'); // Case-insensitive matching + + var match = function(regex, userAgent) { + return regex.test(userAgent); + }; + + var IsMobileClass = function(userAgent) { + var ua = userAgent || navigator.userAgent; + + // Facebook mobile app's integrated browser adds a bunch of strings that + // match everything. Strip it out if it exists. + var tmp = ua.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + // Twitter mobile app's integrated browser on iPad adds a "Twitter for + // iPhone" string. Same probable happens on other tablet platforms. + // This will confuse detection so strip it out if it exists. + tmp = ua.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + this.apple = { + phone: match(apple_phone, ua), + ipod: match(apple_ipod, ua), + tablet: !match(apple_phone, ua) && match(apple_tablet, ua), + device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua) + }; + this.amazon = { + phone: match(amazon_phone, ua), + tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) + }; + this.android = { + phone: match(amazon_phone, ua) || match(android_phone, ua), + tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua) + }; + this.windows = { + phone: match(windows_phone, ua), + tablet: match(windows_tablet, ua), + device: match(windows_phone, ua) || match(windows_tablet, ua) + }; + this.other = { + blackberry: match(other_blackberry, ua), + blackberry10: match(other_blackberry_10, ua), + opera: match(other_opera, ua), + firefox: match(other_firefox, ua), + chrome: match(other_chrome, ua), + device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua) + }; + this.seven_inch = match(seven_inch, ua); + this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch; + + // excludes 'other' devices and ipods, targeting touchscreen phones + this.phone = this.apple.phone || this.android.phone || this.windows.phone; + + // excludes 7 inch devices, classifying as phone or tablet is left to the user + this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet; + + if (typeof window === 'undefined') { + return this; + } + }; + + var instantiate = function() { + var IM = new IsMobileClass(); + IM.Class = IsMobileClass; + return IM; + }; + + if (typeof module !== 'undefined' && module.exports && typeof window === 'undefined') { + //node + module.exports = IsMobileClass; + } else if (typeof module !== 'undefined' && module.exports && typeof window !== 'undefined') { + //browserify + module.exports = instantiate(); + } else if (typeof define === 'function' && define.amd) { + //AMD + define('isMobile', [], global.isMobile = instantiate()); + } else { + global.isMobile = instantiate(); + } + +})(this); + +},{}],5:[function(require,module,exports){ +'use strict'; +/* eslint-disable no-unused-vars */ +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (e) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (Object.getOwnPropertySymbols) { + symbols = Object.getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],6:[function(require,module,exports){ +var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); + +/** + * Helper class to create a webGL buffer + * + * @class + * @memberof pixi.gl + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ +var Buffer = function(gl, type, data, drawType) +{ + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The WebGL buffer, created upon instantiation + * + * @member {WebGLBuffer} + */ + this.buffer = gl.createBuffer(); + + /** + * The type of the buffer + * + * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} + */ + this.type = type || gl.ARRAY_BUFFER; + + /** + * The draw type of the buffer + * + * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ + this.drawType = drawType || gl.STATIC_DRAW; + + /** + * The data in the buffer, as a typed array + * + * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} + */ + this.data = EMPTY_ARRAY_BUFFER; + + if(data) + { + this.upload(data); + } +}; + +/** + * Uploads the buffer to the GPU + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload + * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract + * @param dontBind {Boolean} whether to bind the buffer before uploading it + */ +Buffer.prototype.upload = function(data, offset, dontBind) +{ + // todo - needed? + if(!dontBind) this.bind(); + + var gl = this.gl; + + data = data || this.data; + offset = offset || 0; + + if(this.data.byteLength >= data.byteLength) + { + gl.bufferSubData(this.type, offset, data); + } + else + { + gl.bufferData(this.type, data, this.drawType); + } + + this.data = data; +}; +/** + * Binds the buffer + * + */ +Buffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindBuffer(this.type, this.buffer); +}; + +Buffer.createVertexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); +}; + +Buffer.createIndexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); +}; + +Buffer.create = function(gl, type, data, drawType) +{ + return new Buffer(gl, type, drawType); +}; + +/** + * Destroys the buffer + * + */ +Buffer.prototype.destroy = function(){ + this.gl.deleteBuffer(this.buffer); +}; + +module.exports = Buffer; + +},{}],7:[function(require,module,exports){ + +var Texture = require('./GLTexture'); + +/** + * Helper class to create a webGL Framebuffer + * + * @class + * @memberof pixi.gl + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + */ +var Framebuffer = function(gl, width, height) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The frame buffer + * + * @member {WebGLFramebuffer} + */ + this.framebuffer = gl.createFramebuffer(); + + /** + * The stencil buffer + * + * @member {WebGLRenderbuffer} + */ + this.stencil = null; + + /** + * The stencil buffer + * + * @member {GLTexture} + */ + this.texture = null; + + /** + * The width of the drawing area of the buffer + * + * @member {Number} + */ + this.width = width || 100; + /** + * The height of the drawing area of the buffer + * + * @member {Number} + */ + this.height = height || 100; +}; + +/** + * Adds a texture to the frame buffer + * @param texture {GLTexture} + */ +Framebuffer.prototype.enableTexture = function(texture) +{ + var gl = this.gl; + + this.texture = texture || new Texture(gl); + + this.texture.bind(); + + //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + this.bind(); + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); +}; + +/** + * Initialises the stencil buffer + */ +Framebuffer.prototype.enableStencil = function() +{ + if(this.stencil)return; + + var gl = this.gl; + + this.stencil = gl.createRenderbuffer(); + + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + + // TODO.. this is depth AND stencil? + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width , this.height ); +}; + +/** + * Erases the drawing area and fills it with a colour + * @param r {Number} the red value of the clearing colour + * @param g {Number} the green value of the clearing colour + * @param b {Number} the blue value of the clearing colour + * @param a {Number} the alpha value of the clearing colour + */ +Framebuffer.prototype.clear = function( r, g, b, a ) +{ + this.bind(); + + var gl = this.gl; + + gl.clearColor(r, g, b, a); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Binds the frame buffer to the WebGL context + */ +Framebuffer.prototype.bind = function() +{ + var gl = this.gl; + + if(this.texture) + { + this.texture.unbind(); + } + + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); +}; + +/** + * Unbinds the frame buffer to the WebGL context + */ +Framebuffer.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, null ); +}; +/** + * Resizes the drawing area of the buffer to the given width and height + * @param width {Number} the new width + * @param height {Number} the new height + */ +Framebuffer.prototype.resize = function(width, height) +{ + var gl = this.gl; + + this.width = width; + this.height = height; + + if ( this.texture ) + { + this.texture.uploadData(null, width, height); + } + + if ( this.stencil ) + { + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + } +}; + +/** + * Destroys this buffer + */ +Framebuffer.prototype.destroy = function() +{ + var gl = this.gl; + + //TODO + if(this.texture) + { + this.texture.destroy(); + } + + gl.deleteFramebuffer(this.framebuffer); + + this.gl = null; + + this.stencil = null; + this.texture = null; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createRGBA = function(gl, width, height/*, data*/) +{ + var texture = Texture.fromData(gl, null, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createFloat32 = function(gl, width, height, data) +{ + // create a new texture.. + var texture = new Texture.fromData(gl, data, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +module.exports = Framebuffer; + +},{"./GLTexture":9}],8:[function(require,module,exports){ + +var compileProgram = require('./shader/compileProgram'), + extractAttributes = require('./shader/extractAttributes'), + extractUniforms = require('./shader/extractUniforms'), + generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + +/** + * Helper class to create a webGL Shader + * + * @class + * @memberof pixi.gl + * @param gl {WebGLRenderingContext} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + */ +var Shader = function(gl, vertexSrc, fragmentSrc) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc); + + + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); + + var uniformData = extractUniforms(gl, this.program); + + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject( gl, uniformData ); +}; +/** + * Uses this shader + */ +Shader.prototype.bind = function() +{ + this.gl.useProgram(this.program); +}; + +/** + * Destroys this shader + * TODO + */ +Shader.prototype.destroy = function() +{ + // var gl = this.gl; +}; + +module.exports = Shader; + +},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18}],9:[function(require,module,exports){ + +/** + * Helper class to create a WebGL Texture + * + * @class + * @memberof pixi.gl + * @param gl {WebGLRenderingContext} The current WebGL context + * @param width {number} the width of the texture + * @param height {number} the height of the texture + * @param format {number} the pixel format of the texture. defaults to gl.RGBA + * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE + */ +var Texture = function(gl, width, height, format, type) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); + + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; + + + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || 0; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || 0; + + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; + + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + + +}; + +/** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ +Texture.prototype.upload = function(source) +{ + this.bind(); + + var gl = this.gl; + + // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. + this.width = source.videoWidth || source.width; + this.height = source.videoHeight || source.height; + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); +}; + +var FLOATING_POINT_AVAILABLE = false; + +/** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.prototype.uploadData = function(data, width, height) +{ + this.bind(); + + var gl = this.gl; + + this.width = width || this.width; + this.height = height || this.height; + + if(data instanceof Float32Array) + { + if(!FLOATING_POINT_AVAILABLE) + { + var ext = gl.getExtension("OES_texture_float"); + + if(ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } + + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = gl.UNSIGNED_BYTE; + } + + + + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.width, this.height, 0, this.format, this.type, data || null); + +}; + +/** + * Binds the texture + * @param location + */ +Texture.prototype.bind = function(location) +{ + var gl = this.gl; + + if(location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } + + gl.bindTexture(gl.TEXTURE_2D, this.texture); +}; + +/** + * Unbinds the texture + */ +Texture.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, null); +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.minFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + if(this.mipmap) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.magFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); +}; + +/** + * Enables mipmapping + */ +Texture.prototype.enableMipmap = function() +{ + var gl = this.gl; + + this.bind(); + + this.mipmap = true; + + gl.generateMipmap(gl.TEXTURE_2D); +}; + +/** + * Enables linear filtering + */ +Texture.prototype.enableLinearScaling = function() +{ + this.minFilter(true); + this.magFilter(true); +}; + +/** + * Enables nearest neighbour interpolation + */ +Texture.prototype.enableNearestScaling = function() +{ + this.minFilter(false); + this.magFilter(false); +}; + +/** + * Enables clamping on the texture so WebGL will not repeat it + */ +Texture.prototype.enableWrapClamp = function() +{ + var gl = this.gl; + + this.bind(); + + 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); +}; + +/** + * Enable tiling on the texture + */ +Texture.prototype.enableWrapRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); +}; + +Texture.prototype.enableWrapMirrorRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); +}; + + +/** + * Destroys this texture + */ +Texture.prototype.destroy = function() +{ + var gl = this.gl; + //TODO + gl.deleteTexture(this.texture); +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ +Texture.fromSource = function(gl, source, premultiplyAlpha) +{ + var texture = new Texture(gl); + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); + + return texture; +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.fromData = function(gl, data, width, height) +{ + //console.log(data, width, height); + var texture = new Texture(gl); + texture.uploadData(data, width, height); + + return texture; +}; + + +module.exports = Texture; + +},{}],10:[function(require,module,exports){ + +// state object// +var setVertexAttribArrays = require( './setVertexAttribArrays' ); + +/** + * Helper class to work with WebGL VertexArrayObjects (vaos) + * Only works if WebGL extensions are enabled (they usually are) + * + * @class + * @memberof pixi.gl + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function VertexArrayObject(gl, state) +{ + this.nativeVaoExtension = null; + + if(!VertexArrayObject.FORCE_NATIVE) + { + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + this.nativeState = state; + + if(this.nativeVaoExtension) + { + this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + + var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + // VAO - overwrite the state.. + this.nativeState = { + tempAttribState: new Array(maxAttribs), + attribState: new Array(maxAttribs) + }; + } + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of attributes + * + * @member {Array} + */ + this.attributes = []; + + /** + * @member {Array} + */ + this.indexBuffer = null; + + /** + * A boolean flag + * + * @member {Boolean} + */ + this.dirty = false; +} + +VertexArrayObject.prototype.constructor = VertexArrayObject; +module.exports = VertexArrayObject; + +/** +* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) +* If you find on older devices that things have gone a bit weird then set this to true. +*/ +/** + * Lets the VAO know if you should use the WebGL extension or the native methods. + * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) + * If you find on older devices that things have gone a bit weird then set this to true. + * @static + * @property {Boolean} FORCE_NATIVE + */ +VertexArrayObject.FORCE_NATIVE = false; + +/** + * Binds the buffer + */ +VertexArrayObject.prototype.bind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + + if(this.dirty) + { + this.dirty = false; + this.activate(); + } + } + else + { + + this.activate(); + } + + return this; +}; + +/** + * Unbinds the buffer + */ +VertexArrayObject.prototype.unbind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + return this; +}; + +/** + * Uses this vao + */ +VertexArrayObject.prototype.activate = function() +{ + + var gl = this.gl; + var lastBuffer = null; + + for (var i = 0; i < this.attributes.length; i++) + { + var attrib = this.attributes[i]; + + if(lastBuffer !== attrib.buffer) + { + attrib.buffer.bind(); + lastBuffer = attrib.buffer; + } + + //attrib.attribute.pointer(attrib.type, attrib.normalized, attrib.stride, attrib.start); + gl.vertexAttribPointer(attrib.attribute.location, + attrib.attribute.size, attrib.type || gl.FLOAT, + attrib.normalized || false, + attrib.stride || 0, + attrib.start || 0); + + + } + + setVertexAttribArrays(gl, this.attributes, this.nativeState); + + this.indexBuffer.bind(); + + return this; +}; + +/** + * + * @param buffer {WebGLBuffer} + * @param attribute {*} + * @param type {String} + * @param normalized {Boolean} + * @param stride {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start) +{ + this.attributes.push({ + buffer: buffer, + attribute: attribute, + + location: attribute.location, + type: type || this.gl.FLOAT, + normalized: normalized || false, + stride: stride || 0, + start: start || 0 + }); + + this.dirty = true; + + return this; +}; + +/** + * + * @param buffer {WebGLBuffer} + * @param options {Object} + */ +VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) +{ + this.indexBuffer = buffer; + + this.dirty = true; + + return this; +}; + +/** + * Unbinds this vao and disables it + */ +VertexArrayObject.prototype.clear = function() +{ + // var gl = this.gl; + + // TODO - should this function unbind after clear? + // for now, no but lets see what happens in the real world! + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + } + + this.attributes.length = 0; + this.indexBuffer = null; + + return this; +}; + +/** + * @param type {Number} + * @param size {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.draw = function(type, size, start) +{ + var gl = this.gl; + gl.drawElements(type, size, gl.UNSIGNED_SHORT, start || 0); + + return this; +}; + +/** + * Destroy this vao + */ +VertexArrayObject.prototype.destroy = function() +{ + // lose references + this.gl = null; + this.indexBuffer = null; + this.attributes = null; + this.nativeState = null; + + if(this.nativeVao) + { + this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); + } + + this.nativeVaoExtension = null; + this.nativeVao = null; +}; + +},{"./setVertexAttribArrays":13}],11:[function(require,module,exports){ + +/** + * Helper class to create a webGL Context + * + * @class + * @memberof pixi.gl + * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from + * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * @return {WebGLRenderingContext} the WebGL context + */ +var createContext = function(canvas, options) +{ + var gl = canvas.getContext('webgl', options) || + canvas.getContext('experimental-webgl', options); + + if (!gl) + { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + return gl; +}; + +module.exports = createContext; + +},{}],12:[function(require,module,exports){ +var gl = { + createContext: require('./createContext'), + setVertexAttribArrays: require('./setVertexAttribArrays'), + GLBuffer: require('./GLBuffer'), + GLFramebuffer: require('./GLFramebuffer'), + GLShader: require('./GLShader'), + GLTexture: require('./GLTexture'), + VertexArrayObject: require('./VertexArrayObject'), + shader: require('./shader') +}; + +// Export for Node-compatible environments +if (typeof module !== 'undefined' && module.exports) +{ + // Export the module + module.exports = gl; +} + +// Add to the browser window pixi.gl +if (typeof window !== 'undefined') +{ + // add the window object + window.pixi = { gl: gl }; +} +},{"./GLBuffer":6,"./GLFramebuffer":7,"./GLShader":8,"./GLTexture":9,"./VertexArrayObject":10,"./createContext":11,"./setVertexAttribArrays":13,"./shader":19}],13:[function(require,module,exports){ +// var GL_MAP = {}; + +/** + * @param gl {WebGLRenderingContext} The current WebGL context + * @param attribs {*} + * @param state {*} + */ +var setVertexAttribArrays = function (gl, attribs, state) +{ + var i; + if(state) + { + var tempAttribState = state.tempAttribState, + attribState = state.attribState; + + for (i = 0; i < tempAttribState.length; i++) + { + tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + tempAttribState[attribs[i].attribute.location] = true; + } + + for (i = 0; i < attribState.length; i++) + { + if (attribState[i] !== tempAttribState[i]) + { + attribState[i] = tempAttribState[i]; + + if (state.attribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } + + } + else + { + for (i = 0; i < attribs.length; i++) + { + var attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); + } + } +}; + +module.exports = setVertexAttribArrays; + +},{}],14:[function(require,module,exports){ + +/** + * @class + * @memberof pixi.gl.shader + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @return {WebGLProgram} the shader program + */ +var compileProgram = function(gl, vertexSrc, fragmentSrc) +{ + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + + var program = gl.createProgram(); + + gl.attachShader(program, glVertShader); + gl.attachShader(program, glFragShader); + gl.linkProgram(program); + + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + console.error('Pixi.js Error: Could not initialize shader.'); + console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); + console.error('gl.getError()', gl.getError()); + + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') + { + console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + + gl.deleteProgram(program); + program = null; + } + + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + + return program; +}; + +/** + * @private + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @return {WebGLShader} the shader + */ +var compileShader = function (gl, type, src) +{ + var shader = gl.createShader(type); + + gl.shaderSource(shader, src); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + console.log(gl.getShaderInfoLog(shader)); + return null; + } + + return shader; +}; + +module.exports = compileProgram; + +},{}],15:[function(require,module,exports){ +/** + * @class + * @memberof pixi.gl.shader + * @param type {String} Type of value + * @param size {Number} + */ +var defaultValue = function(type, size) +{ + switch (type) + { + case 'float': + return 0; + + case 'vec2': + return new Float32Array(2 * size); + + case 'vec3': + return new Float32Array(3 * size); + + case 'vec4': + return new Float32Array(4 * size); + + case 'int': + case 'sampler2D': + return 0; + + case 'ivec2': + return new Int32Array(2 * size); + + case 'ivec3': + return new Int32Array(3 * size); + + case 'ivec4': + return new Int32Array(4 * size); + + case 'bool': + return false; + + case 'bvec2': + + return booleanArray( 2 * size); + + case 'bvec3': + return booleanArray(3 * size); + + case 'bvec4': + return booleanArray(4 * size); + + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } +}; + +var booleanArray = function(size) +{ + var array = new Array(size); + + for (var i = 0; i < array.length; i++) + { + array[i] = false; + } + + return array; +}; + +module.exports = defaultValue; + +},{}],16:[function(require,module,exports){ + +var mapType = require('./mapType'); +var mapSize = require('./mapSize'); + +/** + * Extracts the attributes + * @class + * @memberof pixi.gl.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the attributes from + * @return attributes {Object} + */ +var extractAttributes = function(gl, program) +{ + var attributes = {}; + + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + + for (var i = 0; i < totalAttributes; i++) + { + var attribData = gl.getActiveAttrib(program, i); + var type = mapType(gl, attribData.type); + + attributes[attribData.name] = { + type:type, + size:mapSize(type), + location:gl.getAttribLocation(program, attribData.name), + //TODO - make an attribute object + pointer: pointer + }; + } + + return attributes; +}; + +var pointer = function(type, normalized, stride, start){ + // console.log(this.location) + gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +}; + +module.exports = extractAttributes; + +},{"./mapSize":20,"./mapType":21}],17:[function(require,module,exports){ +var mapType = require('./mapType'); +var defaultValue = require('./defaultValue'); + +/** + * Extracts the uniforms + * @class + * @memberof pixi.gl.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the uniforms from + * @return uniforms {Object} + */ +var extractUniforms = function(gl, program) +{ + var uniforms = {}; + + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + + for (var i = 0; i < totalUniforms; i++) + { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]/, ""); + var type = mapType(gl, uniformData.type ); + + uniforms[name] = { + type:type, + size:uniformData.size, + location:gl.getUniformLocation(program, name), + value:defaultValue(type, uniformData.size) + }; + } + + return uniforms; +}; + +module.exports = extractUniforms; + +},{"./defaultValue":15,"./mapType":21}],18:[function(require,module,exports){ +/** + * Extracts the attributes + * @class + * @memberof pixi.gl.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param uniforms {Array} @mat ? + * @return attributes {Object} + */ +var generateUniformAccessObject = function(gl, uniformData) +{ + // this is the object we will be sending back. + // an object hierachy will be created for structs + var uniforms = {data:{}}; + + uniforms.gl = gl; + + var uniformKeys= Object.keys(uniformData); + + for (var i = 0; i < uniformKeys.length; i++) + { + var fullName = uniformKeys[i]; + + var nameTokens = fullName.split('.'); + var name = nameTokens[nameTokens.length - 1]; + + var uniformGroup = getUniformGroup(nameTokens, uniforms); + + var uniform = uniformData[fullName]; + uniformGroup.data[name] = uniform; + + uniformGroup.gl = gl; + + Object.defineProperty(uniformGroup, name, { + get: generateGetter(name), + set: generateSetter(name, uniform) + }); + } + + return uniforms; +}; + +var generateGetter = function(name) +{ + var template = getterTemplate.replace('%%', name); + return new Function(template); // jshint ignore:line +}; + +var generateSetter = function(name, uniform) +{ + var template = setterTemplate.replace(/%%/g, name); + var setTemplate; + + if(uniform.size === 1) + { + setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; + } + else + { + setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; + } + + if(setTemplate) + { + template += "\nthis.gl." + setTemplate + ";"; + } + + return new Function('value', template); // jshint ignore:line +}; + +var getUniformGroup = function(nameTokens, uniform) +{ + var cur = uniform; + + for (var i = 0; i < nameTokens.length - 1; i++) + { + var o = cur[nameTokens[i]] || {data:{}}; + cur[nameTokens[i]] = o; + cur = o; + } + + return cur; +}; + +var getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +var setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;' +].join('\n'); + + +var GLSL_TO_SINGLE_SETTERS = { + + 'float': 'uniform1f(location, value)', + + 'vec2': 'uniform2f(location, value[0], value[1])', + 'vec3': 'uniform3f(location, value[0], value[1], value[2])', + 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', + + 'int': 'uniform1i(location, value)', + 'ivec2': 'uniform2i(location, value[0], value[1])', + 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', + 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'bool': 'uniform1i(location, value)', + 'bvec2': 'uniform2i(location, value[0], value[1])', + 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', + 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'mat2': 'uniformMatrix2fv(location, false, value)', + 'mat3': 'uniformMatrix3fv(location, false, value)', + 'mat4': 'uniformMatrix4fv(location, false, value)', + + 'sampler2D':'uniform1i(location, value)' +}; + +var GLSL_TO_ARRAY_SETTERS = { + + 'float': 'uniform1fv(location, value)', + + 'vec2': 'uniform2fv(location, value)', + 'vec3': 'uniform3fv(location, value)', + 'vec4': 'uniform4fv(location, value)', + + 'int': 'uniform1iv(location, value)', + 'ivec2': 'uniform2iv(location, value)', + 'ivec3': 'uniform3iv(location, value)', + 'ivec4': 'uniform4iv(location, value)', + + 'bool': 'uniform1iv(location, value)', + 'bvec2': 'uniform2iv(location, value)', + 'bvec3': 'uniform3iv(location, value)', + 'bvec4': 'uniform4iv(location, value)', + + 'sampler2D':'uniform1iv(location, value)' +}; + +module.exports = generateUniformAccessObject; + +},{}],19:[function(require,module,exports){ +module.exports = { + compileProgram: require('./compileProgram'), + defaultValue: require('./defaultValue'), + extractAttributes: require('./extractAttributes'), + extractUniforms: require('./extractUniforms'), + generateUniformAccessObject: require('./generateUniformAccessObject'), + mapSize: require('./mapSize'), + mapType: require('./mapType') +}; +},{"./compileProgram":14,"./defaultValue":15,"./extractAttributes":16,"./extractUniforms":17,"./generateUniformAccessObject":18,"./mapSize":20,"./mapType":21}],20:[function(require,module,exports){ +/** + * @class + * @memberof pixi.gl.shader + * @param type {String} + * @return {Number} + */ +var mapSize = function(type) +{ + return GLSL_TO_SIZE[type]; +}; + + +var GLSL_TO_SIZE = { + 'float': 1, + 'vec2': 2, + 'vec3': 3, + 'vec4': 4, + + 'int': 1, + 'ivec2': 2, + 'ivec3': 3, + 'ivec4': 4, + + 'bool': 1, + 'bvec2': 2, + 'bvec3': 3, + 'bvec4': 4, + + 'mat2': 4, + 'mat3': 9, + 'mat4': 16, + + 'sampler2D': 1 +}; + +module.exports = mapSize; + +},{}],21:[function(require,module,exports){ + + +var mapSize = function(gl, type) +{ + if(!GL_TABLE) + { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + + GL_TABLE = {}; + + for(var i = 0; i < typeNames.length; ++i) + { + var tn = typeNames[i]; + GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + } + } + + return GL_TABLE[type]; +}; + +var GL_TABLE = null; + +var GL_TO_GLSL_TYPES = { + 'FLOAT': 'float', + 'FLOAT_VEC2': 'vec2', + 'FLOAT_VEC3': 'vec3', + 'FLOAT_VEC4': 'vec4', + + 'INT': 'int', + 'INT_VEC2': 'ivec2', + 'INT_VEC3': 'ivec3', + 'INT_VEC4': 'ivec4', + + 'BOOL': 'bool', + 'BOOL_VEC2': 'bvec2', + 'BOOL_VEC3': 'bvec3', + 'BOOL_VEC4': 'bvec4', + + 'FLOAT_MAT2': 'mat2', + 'FLOAT_MAT3': 'mat3', + 'FLOAT_MAT4': 'mat4', + + 'SAMPLER_2D': 'sampler2D' +}; + +module.exports = mapSize; + +},{}],22:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) + +},{"_process":23}],23:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],24:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],25:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],26:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],27:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":25,"./encode":26}],28:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":29,"punycode":24,"querystring":27}],29:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],30:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @api private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {Mixed} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @api public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @api public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Boolean} exists Only check if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Add a one-time listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Remove the listeners of a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {Mixed} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn + && (!once || listeners.once) + && (!context || listeners.context === context) + ) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {String|Symbol} [event] The event name. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],31:[function(require,module,exports){ +'use strict' + +module.exports = function parseURI (str, opts) { + opts = opts || {} + + var o = { + key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], + q: { + name: 'queryKey', + parser: /(?:^|&)([^&=]*)=?([^&]*)/g + }, + parser: { + strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, + loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ + } + } + + var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str) + var uri = {} + var i = 14 + + while (i--) uri[o.key[i]] = m[i] || '' + + uri[o.q.name] = {} + uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { + if ($1) uri[o.q.name][$1] = $2 + }) + + return uri +} + +},{}],32:[function(require,module,exports){ +'use strict'; + +var parseUri = require('parse-uri'); +var async = require('./async'); +var Resource = require('./Resource'); +var EventEmitter = require('eventemitter3'); + +// some constants +var DEFAULT_CONCURRENCY = 10; +var MAX_PROGRESS = 100; + +/** + * Manages the state and loading of multiple resources to load. + * + * @class + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ +function Loader(baseUrl, concurrency) { + EventEmitter.call(this); + + concurrency = concurrency || DEFAULT_CONCURRENCY; + + /** + * The base url for all resources loaded by this loader. + * + * @member {string} + */ + this.baseUrl = baseUrl || ''; + + /** + * The progress percent of the loader going through the queue. + * + * @member {number} + */ + this.progress = 0; + + /** + * Loading state of the loader, true if it is currently loading resources. + * + * @member {boolean} + */ + this.loading = false; + + /** + * The percentage of total progress that a single resource represents. + * + * @member {number} + */ + this._progressChunk = 0; + + /** + * The middleware to run before loading each resource. + * + * @member {function[]} + */ + this._beforeMiddleware = []; + + /** + * The middleware to run after loading each resource. + * + * @member {function[]} + */ + this._afterMiddleware = []; + + /** + * The `_loadResource` function bound with this object context. + * + * @private + * @member {function} + */ + this._boundLoadResource = this._loadResource.bind(this); + + /** + * The resource buffer that fills until `load` is called to start loading resources. + * + * @private + * @member {Resource[]} + */ + this._buffer = []; + + /** + * Used to track load completion. + * + * @private + * @member {number} + */ + this._numToLoad = 0; + + /** + * The resources waiting to be loaded. + * + * @private + * @member {Resource[]} + */ + this._queue = async.queue(this._boundLoadResource, concurrency); + + /** + * All the resources for this loader keyed by name. + * + * @member {object} + */ + this.resources = {}; + + /** + * Emitted once per loaded or errored resource. + * + * @event progress + * @memberof Loader# + */ + + /** + * Emitted once per errored resource. + * + * @event error + * @memberof Loader# + */ + + /** + * Emitted once per loaded resource. + * + * @event load + * @memberof Loader# + */ + + /** + * Emitted when the loader begins to process the queue. + * + * @event start + * @memberof Loader# + */ + + /** + * Emitted when the queued resources all load. + * + * @event complete + * @memberof Loader# + */ +} + +Loader.prototype = Object.create(EventEmitter.prototype); +Loader.prototype.constructor = Loader; +module.exports = Loader; + +/** + * Adds a resource (or multiple resources) to the loader queue. + * + * This function can take a wide variety of different parameters. The only thing that is always + * required the url to load. All the following will work: + * + * ```js + * loader + * // normal param syntax + * .add('key', 'http://...', function () {}) + * .add('http://...', function () {}) + * .add('http://...') + * + * // object syntax + * .add({ + * name: 'key2', + * url: 'http://...' + * }, function () {}) + * .add({ + * url: 'http://...' + * }, function () {}) + * .add({ + * name: 'key3', + * url: 'http://...' + * onComplete: function () {} + * }) + * .add({ + * url: 'https://...', + * onComplete: function () {}, + * crossOrigin: true + * }) + * + * // you can also pass an array of objects or urls or both + * .add([ + * { name: 'key4', url: 'http://...', onComplete: function () {} }, + * { url: 'http://...', onComplete: function () {} }, + * 'http://...' + * ]) + * + * // and you can use both params and options + * .add('key', 'http://...', { crossOrigin: true }, function () {}) + * .add('http://...', { crossOrigin: true }, function () {}); + * ``` + * + * @alias enqueue + * @param {string} [name] - The name of the resource to load, if not passed the url is used. + * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @param {object} [options] - The options for the load. + * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.XHR_LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should the data being + * loaded be interpreted when using XHR? + * @param {function} [cb] - Function to call when this specific resource completes loading. + * @return {Loader} Returns itself. + */ +Loader.prototype.add = Loader.prototype.enqueue = function (name, url, options, cb) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + + return this; + } + + // if an object is passed instead of params + if (typeof name === 'object') { + cb = url || name.callback || name.onComplete; + options = name; + url = name.url; + name = name.name || name.key || name.url; + } + + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + cb = options; + options = url; + url = name; + } + + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + cb = options; + options = null; + } + + // check if resource already exists. + if (this.resources[name]) { + throw new Error('Resource with name "' + name + '" already exists.'); + } + + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + + // create the store the resource + this.resources[name] = new Resource(name, url, options); + + if (typeof cb === 'function') { + this.resources[name].once('afterMiddleware', cb); + } + + this._numToLoad++; + + // if already loading add it to the worker queue + if (this._queue.started) { + this._queue.push(this.resources[name]); + this._progressChunk = (MAX_PROGRESS - this.progress) / (this._queue.length() + this._queue.running()); + } + // otherwise buffer it to be added to the queue later + else { + this._buffer.push(this.resources[name]); + this._progressChunk = MAX_PROGRESS / this._buffer.length; + } + + return this; +}; + +/** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * + * @alias pre + * @method before + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ +Loader.prototype.before = Loader.prototype.pre = function (fn) { + this._beforeMiddleware.push(fn); + + return this; +}; + +/** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * + * @alias use + * @method after + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ +Loader.prototype.after = Loader.prototype.use = function (fn) { + this._afterMiddleware.push(fn); + + return this; +}; + +/** + * Resets the queue of the loader to prepare for a new load. + * + * @return {Loader} Returns itself. + */ +Loader.prototype.reset = function () { + // this.baseUrl = baseUrl || ''; + + this.progress = 0; + + this.loading = false; + + this._progressChunk = 0; + + // this._beforeMiddleware.length = 0; + // this._afterMiddleware.length = 0; + + this._buffer.length = 0; + + this._numToLoad = 0; + + this._queue.kill(); + this._queue.started = false; + + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + + res.off('complete', this._onLoad, this); + + if (res.isLoading) { + res.abort(); + } + } + + this.resources = {}; + + return this; +}; + +/** + * Starts loading the queued resources. + * + * @fires start + * @param {function} [cb] - Optional callback that will be bound to the `complete` event. + * @return {Loader} Returns itself. + */ +Loader.prototype.load = function (cb) { + // register complete callback if they pass one + if (typeof cb === 'function') { + this.once('complete', cb); + } + + // if the queue has already started we are done here + if (this._queue.started) { + return this; + } + + // notify of start + this.emit('start', this); + + // update loading state + this.loading = true; + + // start the internal queue + for (var i = 0; i < this._buffer.length; ++i) { + this._queue.push(this._buffer[i]); + } + + // empty the buffer + this._buffer.length = 0; + + return this; +}; + +/** + * Prepares a url for usage based on the configuration of this object + * + * @private + * @param {string} url - The url to prepare. + * @return {string} The prepared url. + */ +Loader.prototype._prepareUrl = function (url) { + var parsedUrl = parseUri(url, { strictMode: true }); + + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.path || parsedUrl.path.indexOf('//') === 0) { + return url; + } + + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + if (this.baseUrl.length + && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 + && url.charAt(0) !== '/' + ) { + return this.baseUrl + '/' + url; + } + + return this.baseUrl + url; +}; + +/** + * Loads a single resource. + * + * @private + * @param {Resource} resource - The resource to load. + * @param {function} dequeue - The function to call when we need to dequeue this item. + */ +Loader.prototype._loadResource = function (resource, dequeue) { + var self = this; + + resource._dequeue = dequeue; + + // run before middleware + async.eachSeries( + this._beforeMiddleware, + function (fn, next) { + fn.call(self, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, + function () { + // resource.on('progress', self.emit.bind(self, 'progress')); + + if (resource.isComplete) { + self._onLoad(resource); + } + else { + resource.once('complete', self._onLoad, self); + resource.load(); + } + } + ); +}; + +/** + * Called once each resource has loaded. + * + * @fires complete + * @private + */ +Loader.prototype._onComplete = function () { + this.loading = false; + + this.emit('complete', this, this.resources); +}; + +/** + * Called each time a resources is loaded. + * + * @fires progress + * @fires error + * @fires load + * @private + * @param {Resource} resource - The resource that was loaded + */ +Loader.prototype._onLoad = function (resource) { + var self = this; + + // run middleware, this *must* happen before dequeue so sub-assets get added properly + async.eachSeries( + this._afterMiddleware, + function (fn, next) { + fn.call(self, resource, next); + }, + function () { + resource.emit('afterMiddleware', resource); + + self._numToLoad--; + + self.progress += self._progressChunk; + self.emit('progress', self, resource); + + if (resource.error) { + self.emit('error', resource.error, self, resource); + } + else { + self.emit('load', self, resource); + } + + // do completion check + if (self._numToLoad === 0) { + self.progress = 100; + self._onComplete(); + } + } + ); + + // remove this resource from the async queue + resource._dequeue(); +}; + +Loader.LOAD_TYPE = Resource.LOAD_TYPE; +Loader.XHR_RESPONSE_TYPE = Resource.XHR_RESPONSE_TYPE; + +},{"./Resource":33,"./async":34,"eventemitter3":30,"parse-uri":31}],33:[function(require,module,exports){ +'use strict'; + +var EventEmitter = require('eventemitter3'); +var parseUri = require('parse-uri'); + +// tests is CORS is supported in XHR, if not we need to use XDR +var useXdr = !!(window.XDomainRequest && !('withCredentials' in (new XMLHttpRequest()))); +var tempAnchor = null; + +// some status constants +var STATUS_NONE = 0; +var STATUS_OK = 200; +var STATUS_EMPTY = 204; + +/** + * Manages the state and loading of a single resource represented by + * a single URL. + * + * @class + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should the data being + * loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra info for middleware. + */ +function Resource(name, url, options) { + EventEmitter.call(this); + + options = options || {}; + + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + + /** + * The name of this resource. + * + * @member {string} + * @readonly + */ + this.name = name; + + /** + * The url used to load this resource. + * + * @member {string} + * @readonly + */ + this.url = url; + + /** + * Stores whether or not this url is a data url. + * + * @member {boolean} + * @readonly + */ + this.isDataUrl = this.url.indexOf('data:') === 0; + + /** + * The data that was loaded by the resource. + * + * @member {any} + */ + this.data = null; + + /** + * Is this request cross-origin? If unset, determined automatically. + * + * @member {string} + */ + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + + /** + * The method of loading to use for this resource. + * + * @member {Resource.LOAD_TYPE} + */ + this.loadType = options.loadType || this._determineLoadType(); + + /** + * The type used to load the resource via XHR. If unset, determined automatically. + * + * @member {string} + */ + this.xhrType = options.xhrType; + + /** + * Extra info for middleware, and controlling specifics about how the resource loads. + * + * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + * Meaning it will modify it as it sees fit. + * + * @member {object} + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources + * to. + */ + this.metadata = options.metadata || {}; + + /** + * The error that occurred while loading (if any). + * + * @member {Error} + * @readonly + */ + this.error = null; + + /** + * The XHR object that was used to load this resource. This is only set + * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * + * @member {XMLHttpRequest} + */ + this.xhr = null; + + /** + * Describes if this resource was loaded as json. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isJson = false; + + /** + * Describes if this resource was loaded as xml. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isXml = false; + + /** + * Describes if this resource was loaded as an image tag. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isImage = false; + + /** + * Describes if this resource was loaded as an audio tag. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isAudio = false; + + /** + * Describes if this resource was loaded as a video tag. Only valid after the resource + * has completely loaded. + * + * @member {boolean} + */ + this.isVideo = false; + + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * + * @member {boolean} + */ + this.isComplete = false; + + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * + * @member {boolean} + */ + this.isLoading = false; + + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * + * @private + * @member {function} + */ + this._dequeue = null; + + /** + * The `complete` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundComplete = this.complete.bind(this); + + /** + * The `_onError` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnError = this._onError.bind(this); + + /** + * The `_onProgress` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnProgress = this._onProgress.bind(this); + + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + this._boundXdrOnTimeout = this._xdrOnTimeout.bind(this); + + /** + * Emitted when the resource beings to load. + * + * @event start + * @memberof Resource# + */ + + /** + * Emitted each time progress of this resource load updates. + * Not all resources types and loader systems can support this event + * so sometimes it may not be available. If the resource + * is being loaded on a modern browser, using XHR, and the remote server + * properly sets Content-Length headers, then this will be available. + * + * @event progress + * @memberof Resource# + */ + + /** + * Emitted once this resource has loaded, if there was an error it will + * be in the `error` property. + * + * @event complete + * @memberof Resource# + */ +} + +Resource.prototype = Object.create(EventEmitter.prototype); +Resource.prototype.constructor = Resource; +module.exports = Resource; + +/** + * Marks the resource as complete. + * + * @fires complete + */ +Resource.prototype.complete = function () { + // TODO: Clean this up in a wrapper or something...gross.... + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } + else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + + this.isComplete = true; + this.isLoading = false; + + this.emit('complete', this); +}; + +/** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ +Resource.prototype.abort = function (message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + + // store error + this.error = new Error(message); + + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } + else if (this.xdr) { + this.xdr.abort(); + } + else if (this.data) { + // single source + if (typeof this.data.src !== 'undefined') { + this.data.src = ''; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + + // done now. + this.complete(); +}; + +/** + * Kicks off loading of this resource. This method is asynchronous. + * + * @fires start + * @param {function} [cb] - Optional callback to call once the resource is loaded. + */ +Resource.prototype.load = function (cb) { + if (this.isLoading) { + return; + } + + if (this.isComplete) { + if (cb) { + var self = this; + + setTimeout(function () { + cb(self); + }, 1); + } + + return; + } + else if (cb) { + this.once('complete', cb); + } + + this.isLoading = true; + + this.emit('start', this); + + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + + switch (this.loadType) { + case Resource.LOAD_TYPE.IMAGE: + this._loadElement('image'); + break; + + case Resource.LOAD_TYPE.AUDIO: + this._loadSourceElement('audio'); + break; + + case Resource.LOAD_TYPE.VIDEO: + this._loadSourceElement('video'); + break; + + case Resource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } + else { + this._loadXhr(); + } + break; + } +}; + +/** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * + * @private + * @param {string} type - The type of element to use. + */ +Resource.prototype._loadElement = function (type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } + else if (type === 'image' && typeof window.Image !== 'undefined') { + this.data = new Image(); + } + else { + this.data = document.createElement(type); + } + + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + + var typeName = 'is' + type[0].toUpperCase() + type.substring(1); + + if (this[typeName] === false) { + this[typeName] = true; + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); +}; + +/** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * + * @private + * @param {string} type - The type of element to use. + */ +Resource.prototype._loadSourceElement = function (type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } + else if (type === 'audio' && typeof window.Audio !== 'undefined') { + this.data = new Audio(); + } + else { + this.data = document.createElement(type); + } + + if (this.data === null) { + this.abort('Unsupported element ' + type); + + return; + } + + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } + else if (Array.isArray(this.url)) { + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i])); + } + } + else { + this.data.appendChild(this._createSource(type, this.url)); + } + } + + this['is' + type[0].toUpperCase() + type.substring(1)] = true; + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + + this.data.load(); +}; + +/** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ +Resource.prototype._loadXhr = function () { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xhr = this.xhr = new XMLHttpRequest(); + + // set the request type and url + xhr.open('GET', this.url, true); + + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; + } + else { + xhr.responseType = this.xhrType; + } + + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + + xhr.send(); +}; + +/** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ +Resource.prototype._loadXdr = function () { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xdr = this.xhr = new XDomainRequest(); + + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = 5000; + + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXdrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + + xdr.open('GET', this.url, true); + + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { + xdr.send(); + }, 0); +}; + +/** + * Creates a source used in loading via an element. + * + * @private + * @param {string} type - The element type (video or audio). + * @param {string} url - The source URL to load from. + * @param {string} [mime] - The mime type of the video + * @return {HTMLSourceElement} The source element. + */ +Resource.prototype._createSource = function (type, url, mime) { + if (!mime) { + mime = type + '/' + url.substr(url.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = url; + source.type = mime; + + return source; +}; + +/** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ +Resource.prototype._onError = function (event) { + this.abort('Failed to load element using ' + event.target.nodeName); +}; + +/** + * Called if a load progress event fires for xhr/xdr. + * + * @fires progress + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ +Resource.prototype._onProgress = function (event) { + if (event && event.lengthComputable) { + this.emit('progress', this, event.loaded / event.total); + } +}; + +/** + * Called if an error event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestErrorEvent|Event} event - Error event. + */ +Resource.prototype._xhrOnError = function () { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"'); +}; + +/** + * Called if an abort event fires for xhr. + * + * @private + * @param {XMLHttpRequestAbortEvent} event - Abort Event + */ +Resource.prototype._xhrOnAbort = function () { + this.abort(reqType(this.xhr) + ' Request was aborted by the user.'); +}; + +/** + * Called if a timeout event fires for xdr. + * + * @private + * @param {Event} event - Timeout event. + */ +Resource.prototype._xdrOnTimeout = function () { + this.abort(reqType(this.xhr) + ' Request timed out.'); +}; + +/** + * Called when data successfully loads from an xhr/xdr request. + * + * @private + * @param {XMLHttpRequestLoadEvent|Event} event - Load event + */ +Resource.prototype._xhrOnLoad = function () { + var xhr = this.xhr; + var status = typeof xhr.status === 'undefined' ? xhr.status : STATUS_OK; // XDR has no `.status`, assume 200. + + // status can be 0 when using the file:// protocol, also check if a response was found + if (status === STATUS_OK || status === STATUS_EMPTY || (status === STATUS_NONE && xhr.responseText.length > 0)) { + // if text, just return it + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { + this.data = xhr.responseText; + } + // if json, parse into json object + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(xhr.responseText); + this.isJson = true; + } + catch (e) { + this.abort('Error trying to parse loaded json:', e); + + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (window.DOMParser) { + var domparser = new DOMParser(); + + this.data = domparser.parseFromString(xhr.responseText, 'text/xml'); + } + else { + var div = document.createElement('div'); + + div.innerHTML = xhr.responseText; + this.data = div; + } + this.isXml = true; + } + catch (e) { + this.abort('Error trying to parse loaded xml:', e); + + return; + } + } + // other types just return the response + else { + this.data = xhr.response || xhr.responseText; + } + } + else { + this.abort('[' + xhr.status + ']' + xhr.statusText + ':' + xhr.responseURL); + + return; + } + + this.complete(); +}; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * + * @private + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +Resource.prototype._determineCrossOrigin = function (url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = parseUri(tempAnchor.href, { strictMode: true }); + + var samePort = (!url.port && loc.port === '') || (url.port === loc.port); + var protocol = url.protocol ? url.protocol + ':' : ''; + + // if cross origin + if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +}; + +/** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. + */ +Resource.prototype._determineXhrType = function () { + return Resource._xhrTypeMap[this._getExtension()] || Resource.XHR_RESPONSE_TYPE.TEXT; +}; + +Resource.prototype._determineLoadType = function () { + return Resource._loadTypeMap[this._getExtension()] || Resource.LOAD_TYPE.XHR; +}; + +Resource.prototype._getExtension = function () { + var url = this.url; + var ext = ''; + + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } + else { + var queryStart = url.indexOf('?'); + + if (queryStart !== -1) { + url = url.substring(0, queryStart); + } + + ext = url.substring(url.lastIndexOf('.') + 1); + } + + return ext.toLowerCase(); +}; + +/** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * + * @private + * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. + * @return {string} The mime type to use. + */ +Resource.prototype._getMimeFromXhrType = function (type) { + switch (type) { + case Resource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + + case Resource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + + case Resource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + + case Resource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + + case Resource.XHR_RESPONSE_TYPE.DEFAULT: + case Resource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + + } +}; + +/** + * Quick helper to get string xhr type. + * + * @ignore + * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. + * @return {string} The type. + */ +function reqType(xhr) { + return xhr.toString().replace('object ', ''); +} + +/** + * The types of loading a resource can use. + * + * @static + * @readonly + * @enum {number} + */ +Resource.LOAD_TYPE = { + /** Uses XMLHttpRequest to load the resource. */ + XHR: 1, + /** Uses an `Image` object to load the resource. */ + IMAGE: 2, + /** Uses an `Audio` object to load the resource. */ + AUDIO: 3, + /** Uses a `Video` object to load the resource. */ + VIDEO: 4 +}; + +/** + * The XHR ready states, used internally. + * + * @static + * @readonly + * @enum {string} + */ +Resource.XHR_RESPONSE_TYPE = { + /** defaults to text */ + DEFAULT: 'text', + /** ArrayBuffer */ + BUFFER: 'arraybuffer', + /** Blob */ + BLOB: 'blob', + /** Document */ + DOCUMENT: 'document', + /** Object */ + JSON: 'json', + /** String */ + TEXT: 'text' +}; + +Resource._loadTypeMap = { + gif: Resource.LOAD_TYPE.IMAGE, + png: Resource.LOAD_TYPE.IMAGE, + bmp: Resource.LOAD_TYPE.IMAGE, + jpg: Resource.LOAD_TYPE.IMAGE, + jpeg: Resource.LOAD_TYPE.IMAGE, + tif: Resource.LOAD_TYPE.IMAGE, + tiff: Resource.LOAD_TYPE.IMAGE, + webp: Resource.LOAD_TYPE.IMAGE, + tga: Resource.LOAD_TYPE.IMAGE, + 'svg+xml': Resource.LOAD_TYPE.IMAGE +}; + +Resource._xhrTypeMap = { + // xml + xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // images + gif: Resource.XHR_RESPONSE_TYPE.BLOB, + png: Resource.XHR_RESPONSE_TYPE.BLOB, + bmp: Resource.XHR_RESPONSE_TYPE.BLOB, + jpg: Resource.XHR_RESPONSE_TYPE.BLOB, + jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, + tif: Resource.XHR_RESPONSE_TYPE.BLOB, + tiff: Resource.XHR_RESPONSE_TYPE.BLOB, + webp: Resource.XHR_RESPONSE_TYPE.BLOB, + tga: Resource.XHR_RESPONSE_TYPE.BLOB, + + // json + json: Resource.XHR_RESPONSE_TYPE.JSON, + + // text + text: Resource.XHR_RESPONSE_TYPE.TEXT, + txt: Resource.XHR_RESPONSE_TYPE.TEXT +}; + +/** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. + */ +Resource.setExtensionLoadType = function (extname, loadType) { + setExtMap(Resource._loadTypeMap, extname, loadType); +}; + +/** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ +Resource.setExtensionXhrType = function (extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); +}; + +function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + + if (!extname) { + return; + } + + map[extname] = val; +} + +},{"eventemitter3":30,"parse-uri":31}],34:[function(require,module,exports){ +'use strict'; + +/** + * Smaller version of the async library constructs. + * + */ + +module.exports = { + eachSeries: asyncEachSeries, + queue: asyncQueue +}; + +function _noop() { /* empty */ } + +/** + * Iterates an array in series. + * + * @param {*[]} array - Array to iterate. + * @param {function} iterator - Function to call for each element. + * @param {function} callback - Function to call when done, or on error. + */ +function asyncEachSeries(array, iterator, callback) { + var i = 0; + var len = array.length; + + (function next(err) { + if (err || i === len) { + if (callback) { + callback(err); + } + + return; + } + + iterator(array[i++], next); + })(); +} + +/** + * Ensures a function is only called once. + * + * @param {function} fn - The function to wrap. + * @return {function} The wrapping function. + */ +function onlyOnce(fn) { + return function onceWrapper() { + if (fn === null) { + throw new Error('Callback was already called.'); + } + + var callFn = fn; + + fn = null; + callFn.apply(this, arguments); + }; +} + +/** + * Async queue implementation, + * + * @param {function} worker - The worker function to call for each task. + * @param {number} concurrency - How many workers to run in parrallel. + * @return {*} The async queue object. + */ +function asyncQueue(worker, concurrency) { + if (concurrency == null) { // eslint-disable-line no-eq-null,eqeqeq + concurrency = 1; + } + else if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + + var workers = 0; + var q = { + _tasks: [], + concurrency: concurrency, + saturated: _noop, + unsaturated: _noop, + buffer: concurrency / 4, + empty: _noop, + drain: _noop, + error: _noop, + started: false, + paused: false, + push: function (data, callback) { + _insert(data, false, callback); + }, + kill: function () { + q.drain = _noop; + q._tasks = []; + }, + unshift: function (data, callback) { + _insert(data, true, callback); + }, + process: function () { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var task = q._tasks.shift(); + + if (q._tasks.length === 0) { + q.empty(); + } + + workers += 1; + + if (workers === q.concurrency) { + q.saturated(); + } + + worker(task.data, onlyOnce(_next(task))); + } + }, + length: function () { + return q._tasks.length; + }, + running: function () { + return workers; + }, + idle: function () { + return q._tasks.length + workers === 0; + }, + pause: function () { + if (q.paused === true) { + return; + } + + q.paused = true; + }, + resume: function () { + if (q.paused === false) { + return; + } + + q.paused = false; + + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= q.concurrency; w++) { + q.process(); + } + } + }; + + function _insert(data, insertAtFront, callback) { + if (callback != null && typeof callback !== 'function') { // eslint-disable-line no-eq-null,eqeqeq + throw new Error('task callback must be a function'); + } + + q.started = true; + + if (data == null && q.idle()) { // eslint-disable-line no-eq-null,eqeqeq + // call drain immediately if there are no tasks + setTimeout(function () { + q.drain(); + }, 1); + + return; + } + + var item = { + data: data, + callback: typeof callback === 'function' ? callback : _noop + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } + else { + q._tasks.push(item); + } + + setTimeout(function () { + q.process(); + }, 1); + } + + function _next(task) { + return function () { + workers -= 1; + + task.callback.apply(task, arguments); + + if (arguments[0] != null) { // eslint-disable-line no-eq-null,eqeqeq + q.error(arguments[0], task.data); + } + + if (workers <= (q.concurrency - q.buffer)) { + q.unsaturated(); + } + + if (q.idle()) { + q.drain(); + } + + q.process(); + }; + } + + return q; +} + +},{}],35:[function(require,module,exports){ +/* eslint no-magic-numbers: 0 */ +'use strict'; + +module.exports = { + // private property + _keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', + + encodeBinary: function (input) { + var output = ''; + var bytebuffer; + var encodedCharIndexes = new Array(4); + var inx = 0; + var jnx = 0; + var paddingBytes = 0; + + while (inx < input.length) { + // Fill byte buffer array + bytebuffer = new Array(3); + + for (jnx = 0; jnx < bytebuffer.length; jnx++) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } + else { + bytebuffer[jnx] = 0; + } + } + + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = ((bytebuffer[0] & 0x3) << 4) | (bytebuffer[1] >> 4); + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = ((bytebuffer[1] & 0x0f) << 2) | (bytebuffer[2] >> 6); + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + + // Determine whether padding happened, and adjust accordingly + paddingBytes = inx - (input.length - 1); + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + + default: + break; // No padding - proceed + } + + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (jnx = 0; jnx < encodedCharIndexes.length; jnx++) { + output += this._keyStr.charAt(encodedCharIndexes[jnx]); + } + } + + return output; + } +}; + +},{}],36:[function(require,module,exports){ +/* eslint global-require: 0 */ +'use strict'; + +module.exports = require('./Loader'); +module.exports.Resource = require('./Resource'); +module.exports.middleware = { + caching: { + memory: require('./middlewares/caching/memory') + }, + parsing: { + blob: require('./middlewares/parsing/blob') + } +}; + +module.exports.async = require('./async'); + +},{"./Loader":32,"./Resource":33,"./async":34,"./middlewares/caching/memory":37,"./middlewares/parsing/blob":38}],37:[function(require,module,exports){ +'use strict'; + +// a simple in-memory cache for resources +var cache = {}; + +module.exports = function () { + return function (resource, next) { + // if cached, then set data and complete the resource + if (cache[resource.url]) { + resource.data = cache[resource.url]; + resource.complete(); // marks resource load complete and stops processing before middlewares + } + // if not cached, wait for complete and store it in the cache. + else { + resource.once('complete', function () { + cache[this.url] = this.data; + }); + } + + next(); + }; +}; + +},{}],38:[function(require,module,exports){ +'use strict'; + +var Resource = require('../../Resource'); +var b64 = require('../../b64'); + +var Url = window.URL || window.webkitURL; + +// a middleware for transforming XHR loaded Blobs into more useful objects + +module.exports = function () { + return function (resource, next) { + if (!resource.data) { + next(); + + return; + } + + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === Resource.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!window.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = 'data:' + type + ';base64,' + b64.encodeBinary(resource.xhr.responseText); + + resource.isImage = true; + + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + + next(); + }; + + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var src = Url.createObjectURL(resource.data); + + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src; + + resource.isImage = true; + + // cleanup the no longer used blob after the image loads + resource.data.onload = function () { + Url.revokeObjectURL(src); + resource.data.onload = null; + + next(); + }; + + // next will be called on load. + return; + } + } + + next(); + }; +}; + +},{"../../Resource":33,"../../b64":35}],39:[function(require,module,exports){ +var core = require('../core'); +var Device = require('ismobilejs'); + +// add some extra variables to the container.. +Object.assign( + core.DisplayObject.prototype, + require('./accessibleTarget') +); + + +/** + * The Accessibility manager reacreates the ability to tab and and have content read by screen readers. This is very important as it can possibly help people with disabilities access pixi content. + * Much like interaction any DisplayObject can be made accessible. This manager will map the events as if the mouse was being used, minimizing the efferot required to implement. + * + * @class + * @memberof PIXI + * @param renderer {PIXI.CanvasRenderer|PIXI.WebGLRenderer} A reference to the current renderer + */ +function AccessibilityManager(renderer) +{ + if((Device.tablet || Device.phone) && !navigator.isCocoonJS) + { + this.createTouchHook(); + } + + // first we create a div that will sit over the pixi element. This is where the div overlays will go. + var div = document.createElement('div'); + + div.style.width = 100 + 'px'; + div.style.height = 100 + 'px'; + div.style.position = 'absolute'; + div.style.top = 0; + div.style.left = 0; + // + div.style.zIndex = 2; + + /** + * This is the dom element that will sit over the pixi element. This is where the div overlays will go. + * + * @type {HTMLElement} + * @private + */ + this.div = div; + + /** + * A simple pool for storing divs. + * + * @type {*} + * @private + */ + this.pool = []; + + /** + * This is a tick used to check if an object is no longer being rendered. + * + * @type {Number} + * @private + */ + this.renderId = 0; + + /** + * Setting this to true will visually show the divs + * + * @type {boolean} + */ + this.debug = false; + + /** + * The renderer this accessibility manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * The array of currently active accessible items. + * + * @member {Array<*>} + * @private + */ + this.children = []; + + /** + * pre-bind the functions + * + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + + /** + * stores the state of the manager. If there are no accessible objects or the mouse is moving the will be false. + * + * @member {Array<*>} + * @private + */ + this.isActive = false; + this.isMobileAccessabillity = false; + + // let listen for tab.. once pressed we can fire up and show the accessibility layer + window.addEventListener('keydown', this._onKeyDown, false); +} + + +AccessibilityManager.prototype.constructor = AccessibilityManager; +module.exports = AccessibilityManager; + +AccessibilityManager.prototype.createTouchHook = function() +{ + var hookDiv = document.createElement('button'); + hookDiv.style.width = 1 + 'px'; + hookDiv.style.height = 1 + 'px'; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = -1000+'px'; + hookDiv.style.left = -1000+'px'; + hookDiv.style.zIndex = 2; + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'HOOK DIV'; + + hookDiv.addEventListener('focus', function(){ + + this.isMobileAccessabillity = true; + this.activate(); + document.body.removeChild(hookDiv); + + }.bind(this)); + + document.body.appendChild(hookDiv); + +}; + +/** + * Activating will cause the Accessibility layer to be shown. This is called when a user preses the tab key + * @private + */ +AccessibilityManager.prototype.activate = function() +{ + if(this.isActive ) + { + return; + } + + this.isActive = true; + + window.document.addEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown, false); + + this.renderer.on('postrender', this.update, this); + + if(this.renderer.view.parentNode) + { + this.renderer.view.parentNode.appendChild(this.div); + } +}; + +/** + * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves the mouse + * @private + */ +AccessibilityManager.prototype.deactivate = function() +{ + + if(!this.isActive || this.isMobileAccessabillity) + { + return; + } + + this.isActive = false; + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.addEventListener('keydown', this._onKeyDown, false); + + this.renderer.off('postrender', this.update); + + if(this.div.parentNode) + { + this.div.parentNode.removeChild(this.div); + } + +}; + +/** + * This recursive function will run throught he scene graph and add any new accessible objects to the DOM layer. + * @param displayObject {PIXI.Container} the DisplayObject to check. + * @private + */ +AccessibilityManager.prototype.updateAccessibleObjects = function(displayObject) +{ + if(!displayObject.visible) + { + return; + } + + if(displayObject.accessible && displayObject.interactive) + { + if(!displayObject._accessibleActive) + { + this.addChild(displayObject); + } + + displayObject.renderId = this.renderId; + } + + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + + this.updateAccessibleObjects(children[i]); + } +}; + + +/** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects + * @private + */ +AccessibilityManager.prototype.update = function() +{ + if(!this.renderer.renderingToScreen) { + return; + } + + // update children... + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + + var rect = this.renderer.view.getBoundingClientRect(); + var sx = rect.width / this.renderer.width; + var sy = rect.height / this.renderer.height; + + var div = this.div; + + div.style.left = rect.left + 'px'; + div.style.top = rect.top + 'px'; + div.style.width = this.renderer.width + 'px'; + div.style.height = this.renderer.height + 'px'; + + for (var i = 0; i < this.children.length; i++) + { + + var child = this.children[i]; + + if(child.renderId !== this.renderId) + { + child._accessibleActive = false; + + core.utils.removeItems(this.children, i, 1); + this.div.removeChild( child._accessibleDiv ); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + + i--; + + if(this.children.length === 0) + { + this.deactivate(); + } + } + else + { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + + if(child.hitArea) + { + div.style.left = ((wt.tx + (hitArea.x * wt.a)) * sx) + 'px'; + div.style.top = ((wt.ty + (hitArea.y * wt.d)) * sy) + 'px'; + + div.style.width = (hitArea.width * wt.a * sx) + 'px'; + div.style.height = (hitArea.height * wt.d * sy) + 'px'; + + } + else + { + hitArea = child.getBounds(); + + this.capHitArea(hitArea); + + div.style.left = (hitArea.x * sx) + 'px'; + div.style.top = (hitArea.y * sy) + 'px'; + + div.style.width = (hitArea.width * sx) + 'px'; + div.style.height = (hitArea.height * sy) + 'px'; + } + } + } + + // increment the render id.. + this.renderId++; +}; + +AccessibilityManager.prototype.capHitArea = function (hitArea) +{ + if (hitArea.x < 0) + { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + + if (hitArea.y < 0) + { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + + if ( hitArea.x + hitArea.width > this.renderer.width ) + { + hitArea.width = this.renderer.width - hitArea.x; + } + + if ( hitArea.y + hitArea.height > this.renderer.height ) + { + hitArea.height = this.renderer.height - hitArea.y; + } +}; + + +/** + * Adds a DisplayObject to the accessibility manager + * @private + */ +AccessibilityManager.prototype.addChild = function(displayObject) +{ +// this.activate(); + + var div = this.pool.pop(); + + if(!div) + { + div = document.createElement('button'); + + div.style.width = 100 + 'px'; + div.style.height = 100 + 'px'; + div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = 2; + div.style.borderStyle = 'none'; + + + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + + + if(displayObject.accessibleTitle) + { + div.title = displayObject.accessibleTitle; + } + else if (!displayObject.accessibleTitle && !displayObject.accessibleHint) + { + div.title = 'displayObject ' + this.tabIndex; + } + + if(displayObject.accessibleHint) + { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + + + // + + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + + + this.children.push(displayObject); + this.div.appendChild( displayObject._accessibleDiv ); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; +}; + + +/** + * Maps the div button press to pixi's InteractionManager (click) + * @private + */ +AccessibilityManager.prototype._onClick = function(e) +{ + var interactionManager = this.renderer.plugins.interaction; + interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); +}; + +/** + * Maps the div focus events to pixis InteractionManager (mouseover) + * @private + */ +AccessibilityManager.prototype._onFocus = function(e) +{ + var interactionManager = this.renderer.plugins.interaction; + interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); +}; + +/** + * Maps the div focus events to pixis InteractionManager (mouseout) + * @private + */ +AccessibilityManager.prototype._onFocusOut = function(e) +{ + var interactionManager = this.renderer.plugins.interaction; + interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); +}; + +/** + * Is called when a key is pressed + * + * @private + */ +AccessibilityManager.prototype._onKeyDown = function(e) +{ + if(e.keyCode !== 9) + { + return; + } + + this.activate(); +}; + +/** + * Is called when the mouse moves across the renderer element + * + * @private + */ +AccessibilityManager.prototype._onMouseMove = function() +{ + this.deactivate(); +}; + + +/** + * Destroys the accessibility manager + * + */ +AccessibilityManager.prototype.destroy = function () +{ + this.div = null; + + for (var i = 0; i < this.children.length; i++) + { + this.children[i].div = null; + } + + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.removeEventListener('keydown', this._onKeyDown); + + this.pool = null; + this.children = null; + this.renderer = null; + +}; + +core.WebGLRenderer.registerPlugin('accessibility', AccessibilityManager); +core.CanvasRenderer.registerPlugin('accessibility', AccessibilityManager); + +},{"../core":62,"./accessibleTarget":40,"ismobilejs":4}],40:[function(require,module,exports){ +/** + * Default property values of accessible objects + * used by {@link PIXI.accessibility.AccessibilityManager}. + * + * @mixin + * @memberof PIXI + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibility.accessibleTarget + * ); + */ +var accessibleTarget = { + + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * + * @member {boolean} + */ + accessible:false, + + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * + * @member {string} + */ + accessibleTitle:null, + + /** + * Sets the aria-label attribute of the shadow div + * + * @member {string} + */ + accessibleHint:null, + + /** + * @todo Needs docs. + */ + tabIndex:0, + + /** + * @todo Needs docs. + */ + _accessibleActive:false, + + /** + * @todo Needs docs. + */ + _accessibleDiv:false + +}; + +module.exports = accessibleTarget; + +},{}],41:[function(require,module,exports){ +/** + * @file Main export of the PIXI accessibility library + * @author Mat Groves + * @copyright 2013-2015 GoodBoyDigital + * @license {@link https://github.com/pixijs/pixi.js/blob/master/LICENSE|MIT License} + */ + +/** + * @namespace PIXI.AccessibilityManager + */ +module.exports = { + accessibleTarget: require('./accessibleTarget'), + AccessibilityManager: require('./AccessibilityManager') +}; + +},{"./AccessibilityManager":39,"./accessibleTarget":40}],42:[function(require,module,exports){ +var GLShader = require('pixi-gl-core').GLShader; +var Const = require('./const'); + +function checkPrecision(src) { + if (src instanceof Array) { + if (src[0].substring(0,9) !== 'precision') { + var copy = src.slice(0); + copy.unshift('precision ' + Const.PRECISION.DEFAULT + ' float;'); + return copy; + } + } else { + if (src.substring(0,9) !== 'precision') { + return 'precision ' + Const.PRECISION.DEFAULT + ' float;\n' + src; + } + } + return src; +} + +/** + * Wrapper class, webGL Shader for Pixi. + * Adds precision string if vertexSrc or fragmentSrc have no mention of it. + * + * @class + * @memberof PIXI + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations. + */ +var Shader = function(gl, vertexSrc, fragmentSrc, attributeLocations) { + GLShader.call(this, gl, checkPrecision(vertexSrc), checkPrecision(fragmentSrc), attributeLocations); +}; + +Shader.prototype = Object.create(GLShader.prototype); +Shader.prototype.constructor = Shader; +module.exports = Shader; + +},{"./const":43,"pixi-gl-core":12}],43:[function(require,module,exports){ + +/** + * Constant values used in pixi + * + * @lends PIXI + */ +var CONST = { + /** + * String of the current PIXI version. + * + * @static + * @constant + * @type {string} + */ + VERSION: '4.0.3', + + /** + * Two Pi. + * + * @static + * @constant + * @type {number} + */ + PI_2: Math.PI * 2, + + /** + * Conversion factor for converting radians to degrees. + * + * @static + * @constant + * @type {number} + */ + RAD_TO_DEG: 180 / Math.PI, + + /** + * Conversion factor for converting degrees to radians. + * + * @static + * @constant + * @type {number} + */ + DEG_TO_RAD: Math.PI / 180, + + /** + * Target frames per millisecond. + * + * @static + * @constant + * @type {number} + * @default 0.06 + */ + TARGET_FPMS: 0.06, + + /** + * Constant to identify the Renderer Type. + * + * @static + * @constant + * @type {object} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + RENDERER_TYPE: { + UNKNOWN: 0, + WEBGL: 1, + CANVAS: 2 + }, + + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * + * @static + * @constant + * @type {object} + * @property {number} NORMAL + * @property {number} ADD + * @property {number} MULTIPLY + * @property {number} SCREEN + * @property {number} OVERLAY + * @property {number} DARKEN + * @property {number} LIGHTEN + * @property {number} COLOR_DODGE + * @property {number} COLOR_BURN + * @property {number} HARD_LIGHT + * @property {number} SOFT_LIGHT + * @property {number} DIFFERENCE + * @property {number} EXCLUSION + * @property {number} HUE + * @property {number} SATURATION + * @property {number} COLOR + * @property {number} LUMINOSITY + */ + BLEND_MODES: { + NORMAL: 0, + ADD: 1, + MULTIPLY: 2, + SCREEN: 3, + OVERLAY: 4, + DARKEN: 5, + LIGHTEN: 6, + COLOR_DODGE: 7, + COLOR_BURN: 8, + HARD_LIGHT: 9, + SOFT_LIGHT: 10, + DIFFERENCE: 11, + EXCLUSION: 12, + HUE: 13, + SATURATION: 14, + COLOR: 15, + LUMINOSITY: 16 + }, + + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * + * @static + * @constant + * @type {object} + * @property {number} POINTS + * @property {number} LINES + * @property {number} LINE_LOOP + * @property {number} LINE_STRIP + * @property {number} TRIANGLES + * @property {number} TRIANGLE_STRIP + * @property {number} TRIANGLE_FAN + */ + DRAW_MODES: { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6 + }, + + /** + * The scale modes that are supported by pixi. + * + * The DEFAULT scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @static + * @constant + * @type {object} + * @property {number} DEFAULT=LINEAR + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + SCALE_MODES: { + DEFAULT: 0, + LINEAR: 0, + NEAREST: 1 + }, + + /** + * The wrap modes that are supported by pixi. + * + * The DEFAULT wrap mode affects the default wraping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as webGL can only use REPEAT if the texture is po2. + * This property only affects WebGL. + * + * @static + * @constant + * @type {object} + * @property {number} DEFAULT=CLAMP + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + WRAP_MODES: { + DEFAULT: 0, + CLAMP: 0, + REPEAT: 1, + MIRRORED_REPEAT:2 + }, + + /** + * The gc modes that are supported by pixi. + * + * The DEFAULT Garbage Collection mode for pixi textures is MANUAL + * If set to DEFAULT, the renderer will occasianally check textures usage. If they are not used for a specified period of time they will be removed from the GPU. + * They will of corse be uploaded again when they are required. This is a silent behind the scenes process that should ensure that the GPU does not get filled up. + * Handy for mobile devices! + * This property only affects WebGL. + * + * @static + * @constant + * @type {object} + * @property {number} DEFAULT=MANUAL + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + GC_MODES: { + DEFAULT: 0, + AUTO: 0, + MANUAL: 1, + }, + + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * + * @static + * @constant + * @type {boolean} + */ + MIPMAP_TEXTURES: true, + + /** + * The prefix that denotes a URL is for a retina asset. + * + * @static + * @constant + * @type {RegExp|string} + * @example `@2x` + */ + RETINA_PREFIX: /@(.+)x/, + + /** + * Default resolution / device pixel ratio of the renderer. + * + * @static + * @constant + * @type {number} + */ + RESOLUTION: 1, + + /** + * Default filter resolution. + * + * @static + * @constant + * @type {number} + */ + FILTER_RESOLUTION:1, + + /** + * The default render options if none are supplied to {@link PIXI.WebGLRenderer} + * or {@link PIXI.CanvasRenderer}. + * + * @static + * @constant + * @type {object} + * @property {HTMLCanvasElement} view=null + * @property {number} resolution=1 + * @property {boolean} antialias=false + * @property {boolean} forceFXAA=false + * @property {boolean} autoResize=false + * @property {boolean} transparent=false + * @property {number} backgroundColor=0x000000 + * @property {boolean} clearBeforeRender=true + * @property {boolean} preserveDrawingBuffer=false + * @property {boolean} roundPixels=false + */ + DEFAULT_RENDER_OPTIONS: { + view: null, + resolution: 1, + antialias: false, + forceFXAA: false, + autoResize: false, + transparent: false, + backgroundColor: 0x000000, + clearBeforeRender: true, + preserveDrawingBuffer: false, + roundPixels: false + }, + + /** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * + * @static + * @constant + * @type {object} + * @property {number} POLY + * @property {number} RECT + * @property {number} CIRC + * @property {number} ELIP + * @property {number} RREC + */ + SHAPES: { + POLY: 0, + RECT: 1, + CIRC: 2, + ELIP: 3, + RREC: 4 + }, + + /** + * Constants that specify float precision in shaders. + * + * @static + * @constant + * @type {object} + * @property {number} DEFAULT='mediump' + * @property {number} LOW='lowp' + * @property {number} MEDIUM='mediump' + * @property {number} HIGH='highp' + */ + PRECISION: { + DEFAULT: 'mediump', + LOW: 'lowp', + MEDIUM: 'mediump', + HIGH: 'highp' + }, + + /** + * Constants that specify the transform type. + * + * @static + * @constant + * @type {object} + * @property {number} DEFAULT=STATIC + * @property {number} STATIC + * @property {number} DYNAMIC + */ + TRANSFORM_MODE:{ + DEFAULT: 0, + STATIC: 0, + DYNAMIC: 1 + }, + + /** + * Constants that define the type of gradient on text. + * + * @static + * @constant + * @type {object} + * @property {number} LINEAR_VERTICAL + * @property {number} LINEAR_HORIZONTAL + */ + TEXT_GRADIENT: { + LINEAR_VERTICAL: 0, + LINEAR_HORIZONTAL: 1 + }, + + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * + * @static + * @constant + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + + /** + * The maximum textures that this device supports. + * + * @static + * @constant + * @type {number} + */ + SPRITE_MAX_TEXTURES: require('./utils/maxRecommendedTextures')(32) +}; + +module.exports = CONST; + +},{"./utils/maxRecommendedTextures":117}],44:[function(require,module,exports){ +var math = require('../math'), + Rectangle = math.Rectangle; + +/** + * 'Builder' pattern for bounds rectangles + * Axis-Aligned Bounding Box + * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems + * + * @class + * @memberof PIXI + */ +function Bounds() +{ + /** + * @member {number} + * @default 0 + */ + this.minX = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.minY = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxX = -Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxY = -Infinity; + + this.rect = null; +} + +Bounds.prototype.constructor = Bounds; +module.exports = Bounds; + +Bounds.prototype.isEmpty = function() +{ + return this.minX > this.maxX || this.minY > this.maxY; +}; + +Bounds.prototype.clear = function() +{ + this.updateID++; + + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; +}; + +/** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * @param tempRect {PIXI.Rectangle} temporary object will be used if AABB is not empty + * @returns {PIXI.Rectangle} + */ +Bounds.prototype.getRectangle = function(rect) +{ + if (this.minX > this.maxX || this.minY > this.maxY) { + return Rectangle.EMPTY; + } + + rect = rect || new Rectangle(0, 0, 1, 1); + + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + + return rect; +}; + +/** + * This function should be inlined when its possible + * @param point {PIXI.Point} + */ +Bounds.prototype.addPoint = function (point) +{ + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); +}; + +/** + * Adds a quad, not transformed + * @param vertices {Float32Array} + * @returns {PIXI.Bounds} + */ +Bounds.prototype.addQuad = function(vertices) +{ + var minX = this.minX, minY = this.minY, maxX = this.maxX, maxY = this.maxY; + + var x = vertices[0]; + var y = vertices[1]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; +}; + +/** + * Adds sprite frame, transformed + * @param transform {PIXI.TransformBase} + * @param x0 {number} + * @param y0 {number} + * @param x1 {number} + * @param y1 {number} + */ +Bounds.prototype.addFrame = function(transform, x0, y0, x1, y1) +{ + var matrix = transform.worldTransform; + var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d, tx = matrix.tx, ty = matrix.ty; + var minX = this.minX, minY = this.minY, maxX = this.maxX, maxY = this.maxY; + + var x = a * x0 + c * y0 + tx; + var y = b * x0 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y0 + tx; + y = b * x1 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x0 + c * y1 + tx; + y = b * x0 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y1 + tx; + y = b * x1 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; +}; + +/** + * add an array of vertices + * @param transform {PIXI.TransformBase} + * @param vertices {Float32Array} + * @param beginOffset {number} + * @param endOffset {number} + */ +Bounds.prototype.addVertices = function(transform, vertices, beginOffset, endOffset) +{ + var matrix = transform.worldTransform; + var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d, tx = matrix.tx, ty = matrix.ty; + var minX = this.minX, minY = this.minY, maxX = this.maxX, maxY = this.maxY; + + for (var i = beginOffset; i < endOffset; i += 2) + { + var rawX = vertices[i], rawY = vertices[i + 1]; + var x = (a * rawX) + (c * rawY) + tx; + var y = (d * rawY) + (b * rawX) + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; +}; + +Bounds.prototype.addBounds = function(bounds) +{ + var minX = this.minX, minY = this.minY, maxX = this.maxX, maxY = this.maxY; + + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; +}; + +},{"../math":67}],45:[function(require,module,exports){ +var utils = require('../utils'), + DisplayObject = require('./DisplayObject'); + +/** + * A Container represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + *```js + * var container = new PIXI.Container(); + * container.addChild(sprite); + * ``` + * @class + * @extends PIXI.DisplayObject + * @memberof PIXI + */ +function Container() +{ + DisplayObject.call(this); + + /** + * The array of children of this container. + * + * @member {PIXI.DisplayObject[]} + * @readonly + */ + this.children = []; +} + +// constructor +Container.prototype = Object.create(DisplayObject.prototype); +Container.prototype.constructor = Container; +module.exports = Container; + +Object.defineProperties(Container.prototype, { + /** + * The width of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Container# + */ + width: { + get: function () + { + return this.scale.x * this.getLocalBounds().width; + }, + set: function (value) + { + + var width = this.getLocalBounds().width; + + if (width !== 0) + { + this.scale.x = value / width; + } + else + { + this.scale.x = 1; + } + + + this._width = value; + } + }, + + /** + * The height of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Container# + */ + height: { + get: function () + { + return this.scale.y * this.getLocalBounds().height; + }, + set: function (value) + { + + var height = this.getLocalBounds().height; + + if (height !== 0) + { + this.scale.y = value / height ; + } + else + { + this.scale.y = 1; + } + + this._height = value; + } + } +}); + +/** + * Overridable method that can be used by Container subclasses whenever the children array is modified + * + * @private + */ +Container.prototype.onChildrenChange = function () {}; + +/** + * Adds a child or multiple children to the container. + * + * Multple items can be added like so: `myContainer.addChild(thinkOne, thingTwo, thingThree)` + * @param child {...PIXI.DisplayObject} The DisplayObject(s) to add to the container + * @return {PIXI.DisplayObject} The first child that was added. + */ +Container.prototype.addChild = function (child) +{ + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if(argumentsLength > 1) + { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) + { + this.addChild( arguments[i] ); + } + } + else + { + // if the child has a parent then lets remove it as Pixi objects can only exist in one place + if (child.parent) + { + child.parent.removeChild(child); + } + + child.parent = this; + + // ensure a transform will be recalculated.. + this.transform._parentID = -1; + + this.children.push(child); + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length-1); + child.emit('added', this); + } + + return child; +}; + +/** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @param child {PIXI.DisplayObject} The child to add + * @param index {number} The index to place the child in + * @return {PIXI.DisplayObject} The child that was added. + */ +Container.prototype.addChildAt = function (child, index) +{ + if (index >= 0 && index <= this.children.length) + { + if (child.parent) + { + child.parent.removeChild(child); + } + + child.parent = this; + + this.children.splice(index, 0, child); + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + + return child; + } + else + { + throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length); + } +}; + +/** + * Swaps the position of 2 Display Objects within this container. + * + * @param child {PIXI.DisplayObject} First display object to swap + * @param child2 {PIXI.DisplayObject} Second display object to swap + */ +Container.prototype.swapChildren = function (child, child2) +{ + if (child === child2) + { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + + if (index1 < 0 || index2 < 0) + { + throw new Error('swapChildren: Both the supplied DisplayObjects must be children of the caller.'); + } + + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); +}; + +/** + * Returns the index position of a child DisplayObject instance + * + * @param child {PIXI.DisplayObject} The DisplayObject instance to identify + * @return {number} The index position of the child display object to identify + */ +Container.prototype.getChildIndex = function (child) +{ + var index = this.children.indexOf(child); + + if (index === -1) + { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; +}; + +/** + * Changes the position of an existing child in the display object container + * + * @param child {PIXI.DisplayObject} The child DisplayObject instance for which you want to change the index number + * @param index {number} The resulting index number for the child display object + */ +Container.prototype.setChildIndex = function (child, index) +{ + if (index < 0 || index >= this.children.length) + { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + utils.removeItems(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); //add at new position + this.onChildrenChange(index); +}; + +/** + * Returns the child at the specified index + * + * @param index {number} The index to get the child at + * @return {PIXI.DisplayObject} The child at the given index, if any. + */ +Container.prototype.getChildAt = function (index) +{ + if (index < 0 || index >= this.children.length) + { + throw new Error('getChildAt: Supplied index ' + index + ' does not exist in the child list, or the supplied DisplayObject is not a child of the caller'); + } + + return this.children[index]; +}; + +/** + * Removes a child from the container. + * + * @param child {PIXI.DisplayObject} The DisplayObject to remove + * @return {PIXI.DisplayObject} The child that was removed. + */ +Container.prototype.removeChild = function (child) +{ + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if(argumentsLength > 1) + { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) + { + this.removeChild( arguments[i] ); + } + } + else + { + var index = this.children.indexOf(child); + + if (index === -1) + { + return; + } + + child.parent = null; + utils.removeItems(this.children, index, 1); + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + } + + return child; +}; + +/** + * Removes a child from the specified index position. + * + * @param index {number} The index to get the child from + * @return {PIXI.DisplayObject} The child that was removed. + */ +Container.prototype.removeChildAt = function (index) +{ + var child = this.getChildAt(index); + + child.parent = null; + utils.removeItems(this.children, index, 1); + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + + return child; +}; + +/** + * Removes all children from this container that are within the begin and end indexes. + * + * @param [beginIndex=0] {number} The beginning position. + * @param [endIndex=this.children.length] {number} The ending position. Default value is size of the container. + */ +Container.prototype.removeChildren = function (beginIndex, endIndex) +{ + var begin = beginIndex || 0; + var end = typeof endIndex === 'number' ? endIndex : this.children.length; + var range = end - begin; + var removed, i; + + if (range > 0 && range <= end) + { + removed = this.children.splice(begin, range); + + for (i = 0; i < removed.length; ++i) + { + removed[i].parent = null; + } + + this.onChildrenChange(beginIndex); + + for (i = 0; i < removed.length; ++i) + { + removed[i].emit('removed', this); + } + + return removed; + } + else if (range === 0 && this.children.length === 0) + { + return []; + } + else + { + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + } +}; + +/* + * Updates the transform on all children of this container for rendering + * + * @private + */ +Container.prototype.updateTransform = function () +{ + this._boundsID++; + + if (!this.visible) + { + return; + } + + this.transform.updateTransform(this.parent.transform); + + //TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + for (var i = 0, j = this.children.length; i < j; ++i) + { + this.children[i].updateTransform(); + } +}; + +// performance increase to avoid using call.. (10x faster) +Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + + +Container.prototype.calculateBounds = function () +{ + this._bounds.clear(); + + if(!this.visible) + { + return; + } + + this._calculateBounds(); + + for (var i = 0; i < this.children.length; i++) + { + var child = this.children[i]; + + child.calculateBounds(); + + this._bounds.addBounds(child._bounds); + } + + this._boundsID = this._lastBoundsID; +}; + +Container.prototype._calculateBounds = function () +{ + //FILL IN// +}; + +/** + * Renders the object using the WebGL renderer + * + * @param renderer {PIXI.WebGLRenderer} The renderer + */ +Container.prototype.renderWebGL = function (renderer) +{ + + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) + { + + return; + } + + + // do a quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) + { + this.renderAdvancedWebGL(renderer); + } + else + { + this._renderWebGL(renderer); + + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) + { + this.children[i].renderWebGL(renderer); + } + } +}; + +Container.prototype.renderAdvancedWebGL = function (renderer) +{ + renderer.currentRenderer.flush(); + + var filters = this._filters; + var mask = this._mask; + var i, j; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if ( filters ) + { + if(!this._enabledFilters) + { + this._enabledFilters = []; + } + + this._enabledFilters.length = 0; + + for (i = 0; i < filters.length; i++) + { + if(filters[i].enabled) + { + this._enabledFilters.push( filters[i] ); + } + } + + if( this._enabledFilters.length ) + { + renderer.filterManager.pushFilter(this, this._enabledFilters); + } + } + + if ( mask ) + { + renderer.maskManager.pushMask(this, this._mask); + } + + renderer.currentRenderer.start(); + + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); + + // now loop through the children and make sure they get rendered + for (i = 0, j = this.children.length; i < j; i++) + { + this.children[i].renderWebGL(renderer); + } + + renderer.currentRenderer.flush(); + + if ( mask ) + { + renderer.maskManager.popMask(this, this._mask); + } + + if ( filters && this._enabledFilters && this._enabledFilters.length ) + { + renderer.filterManager.popFilter(); + } + + renderer.currentRenderer.start(); +}; + +/** + * To be overridden by the subclass + * + * @param renderer {PIXI.WebGLRenderer} The renderer + * @private + */ +Container.prototype._renderWebGL = function (renderer) // jshint unused:false +{ + // this is where content itself gets rendered... +}; + +/** + * To be overridden by the subclass + * + * @param renderer {PIXI.CanvasRenderer} The renderer + * @private + */ +Container.prototype._renderCanvas = function (renderer) // jshint unused:false +{ + // this is where content itself gets rendered... +}; + + +/** + * Renders the object using the Canvas renderer + * + * @param renderer {PIXI.CanvasRenderer} The renderer + */ +Container.prototype.renderCanvas = function (renderer) +{ + // if not visible or the alpha is 0 then no need to render this + if (!this.visible || this.alpha <= 0 || !this.renderable) + { + return; + } + + if (this._mask) + { + renderer.maskManager.pushMask(this._mask); + } + + this._renderCanvas(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) + { + this.children[i].renderCanvas(renderer); + } + + if (this._mask) + { + renderer.maskManager.popMask(renderer); + } +}; + +/** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * @param [options] {object|boolean} Options parameter. A boolean will act as if all options have been set to that value + * @param [options.children=false] {boolean} if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + */ +Container.prototype.destroy = function (options) +{ + DisplayObject.prototype.destroy.call(this); + + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + + var oldChildren = this.children; + this.children = null; + + if (destroyChildren) + { + for (var i = oldChildren.length - 1; i >= 0; i--) + { + var child = oldChildren[i]; + child.parent = null; + child.destroy(options); + } + } +}; + +},{"../utils":116,"./DisplayObject":46}],46:[function(require,module,exports){ +var EventEmitter = require('eventemitter3'), + CONST = require('../const'), + TransformStatic = require('./TransformStatic'), + Transform = require('./Transform'), + Bounds = require('./Bounds'), + math = require('../math'), + _tempDisplayObjectParent = new DisplayObject(); + +/** + * The base class for all objects that are rendered on the screen. + * This is an abstract class and should not be used on its own rather it should be extended. + * + * @class + * @extends EventEmitter + * @mixes PIXI.interaction.interactiveTarget + * @memberof PIXI + */ +function DisplayObject() +{ + EventEmitter.call(this); + + var TransformClass = CONST.TRANSFORM_MODE.DEFAULT === CONST.TRANSFORM_MODE.STATIC ? TransformStatic : Transform; + + //TODO: need to create Transform from factory + /** + * World transform and local transform of this object. + * This will be reworked in v4.1, please do not use it yet unless you know what are you doing! + * + * @member {PIXI.TransformBase} + */ + this.transform = new TransformClass(); + + /** + * The opacity of the object. + * + * @member {number} + */ + this.alpha = 1; + + /** + * The visibility of the object. If false the object will not be drawn, and + * the updateTransform function will not be called. + * + * @member {boolean} + */ + this.visible = true; + + /** + * Can this object be rendered, if false the object will not be drawn but the updateTransform + * methods will still be called. + * + * @member {boolean} + */ + this.renderable = true; + + /** + * The display object container that contains this display object. + * + * @member {PIXI.Container} + * @readonly + */ + this.parent = null; + + /** + * The multiplied alpha of the displayObject + * + * @member {number} + * @readonly + */ + this.worldAlpha = 1; + + /** + * The area the filter is applied to. This is used as more of an optimisation + * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle + * + * Also works as an interaction mask + * + * @member {PIXI.Rectangle} + */ + this.filterArea = null; + + this._filters = null; + this._enabledFilters = null; + + /** + * The bounds object, this is used to calculate and store the bounds of the displayObject + * + * @member {PIXI.Rectangle} + * @private + */ + this._bounds = new Bounds(); + this._boundsID = 0; + this._lastBoundsID = -1; + this._boundsRect = null; + this._localBoundsRect = null; + + /** + * The original, cached mask of the object + * + * @member {PIXI.Rectangle} + * @private + */ + this._mask = null; + + +} + +// constructor +DisplayObject.prototype = Object.create(EventEmitter.prototype); +DisplayObject.prototype.constructor = DisplayObject; +module.exports = DisplayObject; + + +Object.defineProperties(DisplayObject.prototype, { + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + * + * @member {number} + * @memberof PIXI.DisplayObject# + */ + x: { + get: function () + { + return this.position.x; + }, + set: function (value) + { + this.transform.position.x = value; + } + }, + + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + * + * @member {number} + * @memberof PIXI.DisplayObject# + */ + y: { + get: function () + { + return this.position.y; + }, + set: function (value) + { + this.transform.position.y = value; + } + }, + + /** + * Current transform of the object based on world (parent) factors + * + * @member {PIXI.Matrix} + * @memberof PIXI.DisplayObject# + * @readonly + */ + worldTransform: { + get: function () + { + return this.transform.worldTransform; + } + }, + + /** + * Current transform of the object based on local factors: position, scale, other stuff + * + * @member {PIXI.Matrix} + * @memberof PIXI.DisplayObject# + * @readonly + */ + localTransform: { + get: function () + { + return this.transform.localTransform; + } + }, + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + position: { + get: function() + { + return this.transform.position; + }, + set: function(value) { + this.transform.position.copy(value); + } + }, + + /** + * The scale factor of the object. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + scale: { + get: function() { + return this.transform.scale; + }, + set: function(value) { + this.transform.scale.copy(value); + } + }, + + /** + * The pivot point of the displayObject that it rotates around + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + pivot: { + get: function() { + return this.transform.pivot; + }, + set: function(value) { + this.transform.pivot.copy(value); + } + }, + + /** + * The skew factor for the object in radians. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + * @memberof PIXI.DisplayObject# + */ + skew: { + get: function() { + return this.transform.skew; + }, + set: function(value) { + this.transform.skew.copy(value); + } + }, + + /** + * The rotation of the object in radians. + * + * @member {number} + * @memberof PIXI.DisplayObject# + */ + rotation: { + get: function () + { + return this.transform.rotation; + }, + set: function (value) + { + this.transform.rotation = value; + } + }, + + /** + * Indicates if the sprite is globally visible. + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + * @readonly + */ + worldVisible: { + get: function () + { + var item = this; + + do { + if (!item.visible) + { + return false; + } + + item = item.parent; + } while (item); + + return true; + } + }, + + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an object to the shape of the mask applied to it. + * In PIXI a regular mask must be a PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it utilises shape clipping. + * To remove a mask, set this property to null. + * + * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + * + * @member {PIXI.Graphics|PIXI.Sprite} + * @memberof PIXI.DisplayObject# + */ + mask: { + get: function () + { + return this._mask; + }, + set: function (value) + { + if (this._mask) + { + this._mask.renderable = true; + } + + this._mask = value; + + if (this._mask) + { + this._mask.renderable = false; + } + } + }, + + /** + * Sets the filters for the displayObject. + * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * To remove filters simply set this property to 'null' + * + * @member {PIXI.AbstractFilter[]} + * @memberof PIXI.DisplayObject# + */ + filters: { + get: function () + { + return this._filters && this._filters.slice(); + }, + set: function (value) + { + this._filters = value && value.slice(); + } + } + +}); + +/* + * Updates the object transform for rendering + * + * TODO - Optimization pass! + */ +DisplayObject.prototype.updateTransform = function () +{ + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + this._bounds.updateID++; +}; + +// performance increase to avoid using call.. (10x faster) +DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + +/** + * recursively updates transform of all objects from the root to this one + * internal function for toLocal() + */ +DisplayObject.prototype._recursivePostUpdateTransform = function() +{ + if (this.parent) + { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } + else + { + this.transform.updateTransform(_tempDisplayObjectParent.transform); + } +}; + +/** + * + * + * Retrieves the bounds of the displayObject as a rectangle object. + * @param skipUpdate {boolean} setting to true will stop the transforms of the scene graph from being updated. This means the calculation returned MAY be out of date BUT will give you a nice performance boost + * @param rect {PIXI.Rectangle} Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ +DisplayObject.prototype.getBounds = function (skipUpdate, rect) +{ + if(!skipUpdate) + { + if(!this.parent) + { + this.parent = _tempDisplayObjectParent; + this.parent.transform._worldID++; + this.updateTransform(); + this.parent = null; + } + else + { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + + if(this._boundsID !== this._lastBoundsID) + { + this.calculateBounds(); + } + + if(!rect) + { + if(!this._boundsRect) + { + this._boundsRect = new math.Rectangle(); + } + + rect = this._boundsRect; + } + + return this._bounds.getRectangle(rect); +}; + +/** + * Retrieves the local bounds of the displayObject as a rectangle object + * @param rect {PIXI.Rectangle} Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ +DisplayObject.prototype.getLocalBounds = function (rect) +{ + var transformRef = this.transform; + var parentRef = this.parent; + + this.parent = null; + this.transform = _tempDisplayObjectParent.transform; + + if(!rect) + { + if(!this._localBoundsRect) + { + this._localBoundsRect = new math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + var bounds = this.getBounds(false, rect); + + this.parent = parentRef; + this.transform = transformRef; + + return bounds; +}; + +/** + * Calculates the global position of the display object + * + * @param position {PIXI.Point} The world origin to calculate from + * @return {PIXI.Point} A point object representing the position of this object + */ +DisplayObject.prototype.toGlobal = function (position, point, skipUpdate) +{ + if(!skipUpdate) + { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if(!this.parent) + { + this.parent = _tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } + else + { + this.displayObjectUpdateTransform(); + } + } + + // don't need to update the lot + return this.worldTransform.apply(position, point); +}; + +/** + * Calculates the local position of the display object relative to another point + * + * @param position {PIXI.Point} The world origin to calculate from + * @param [from] {PIXI.DisplayObject} The DisplayObject to calculate the global position from + * @param [point] {PIXI.Point} A Point object in which to store the value, optional (otherwise will create a new Point) + * @return {PIXI.Point} A point object representing the position of this object + */ +DisplayObject.prototype.toLocal = function (position, from, point, skipUpdate) +{ + if (from) + { + position = from.toGlobal(position, point, skipUpdate); + } + + if(! skipUpdate) + { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if(!this.parent) + { + this.parent = _tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } + else + { + this.displayObjectUpdateTransform(); + } + } + + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); +}; + +/** + * Renders the object using the WebGL renderer + * + * @param renderer {PIXI.WebGLRenderer} The renderer + */ +DisplayObject.prototype.renderWebGL = function (renderer) // jshint unused:false +{ + // OVERWRITE; +}; + +/** + * Renders the object using the Canvas renderer + * + * @param renderer {PIXI.CanvasRenderer} The renderer + */ +DisplayObject.prototype.renderCanvas = function (renderer) // jshint unused:false +{ + // OVERWRITE; +}; + +/** + * Set the parent Container of this DisplayObject + * + * @param container {PIXI.Container} The Container to add this DisplayObject to + * @return {PIXI.Container} The Container that this DisplayObject was added to + */ +DisplayObject.prototype.setParent = function (container) +{ + if (!container || !container.addChild) + { + throw new Error('setParent: Argument must be a Container'); + } + + container.addChild(this); + return container; +}; + +/** + * Convenience function to set the postion, scale, skew and pivot at once. + * + * @param [x=0] {number} The X position + * @param [y=0] {number} The Y position + * @param [scaleX=1] {number} The X scale value + * @param [scaleY=1] {number} The Y scale value + * @param [rotation=0] {number} The rotation + * @param [skewX=0] {number} The X skew value + * @param [skewY=0] {number} The Y skew value + * @param [pivotX=0] {number} The X pivot value + * @param [pivotY=0] {number} The Y pivot value + * @return {PIXI.DisplayObject} The DisplayObject instance + */ +DisplayObject.prototype.setTransform = function(x, y, scaleX, scaleY, rotation, skewX, skewY, pivotX, pivotY) //jshint ignore:line +{ + this.position.x = x || 0; + this.position.y = y || 0; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation || 0; + this.skew.x = skewX || 0; + this.skew.y = skewY || 0; + this.pivot.x = pivotX || 0; + this.pivot.y = pivotY || 0; + return this; +}; + +/** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy`. + */ +DisplayObject.prototype.destroy = function () +{ + this.removeAllListeners(); + if (this.parent) + { + this.parent.removeChild(this); + } + this.transform = null; + + this.parent = null; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this.filterArea = null; + + this.interactive = false; + this.interactiveChildren = false; +}; + +},{"../const":43,"../math":67,"./Bounds":44,"./Transform":47,"./TransformStatic":49,"eventemitter3":3}],47:[function(require,module,exports){ +var math = require('../math'), + TransformBase = require('./TransformBase'); + + +/** + * Generic class to deal with traditional 2D matrix transforms + * local transformation is calculated from position,scale,skew and rotation + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +function Transform() +{ + TransformBase.call(this); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.Point} + */ + this.position = new math.Point(0,0); + + /** + * The scale factor of the object. + * + * @member {PIXI.Point} + */ + this.scale = new math.Point(1,1); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + this.skew = new math.ObservablePoint(this.updateSkew, this, 0,0); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.Point} + */ + this.pivot = new math.Point(0,0); + + /** + * The rotation value of the object, in radians + * + * @member {Number} + * @private + */ + this._rotation = 0; + + this._sr = Math.sin(0); + this._cr = Math.cos(0); + this._cy = Math.cos(0);//skewY); + this._sy = Math.sin(0);//skewY); + this._nsx = Math.sin(0);//skewX); + this._cx = Math.cos(0);//skewX); +} + +Transform.prototype = Object.create(TransformBase.prototype); +Transform.prototype.constructor = Transform; + +Transform.prototype.updateSkew = function () +{ + this._cy = Math.cos(this.skew.y); + this._sy = Math.sin(this.skew.y); + this._nsx = Math.sin(this.skew.x); + this._cx = Math.cos(this.skew.x); +}; + +/** + * Updates only local matrix + */ +Transform.prototype.updateLocalTransform = function() { + var lt = this.localTransform; + var a, b, c, d; + + a = this._cr * this.scale.x; + b = this._sr * this.scale.x; + c = -this._sr * this.scale.y; + d = this._cr * this.scale.y; + + lt.a = this._cy * a + this._sy * c; + lt.b = this._cy * b + this._sy * d; + lt.c = this._nsx * a + this._cx * c; + lt.d = this._nsx * b + this._cx * d; +}; + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + */ +Transform.prototype.updateTransform = function (parentTransform) +{ + + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + var a, b, c, d; + + a = this._cr * this.scale.x; + b = this._sr * this.scale.x; + c = -this._sr * this.scale.y; + d = this._cr * this.scale.y; + + lt.a = this._cy * a + this._sy * c; + lt.b = this._cy * b + this._sy * d; + lt.c = this._nsx * a + this._cx * c; + lt.d = this._nsx * b + this._cx * d; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID ++; +}; + +/** + * Decomposes a matrix and sets the transforms properties based on it. + * @param {PIXI.Matrix} The matrix to decompose + */ +Transform.prototype.setFromMatrix = function (matrix) +{ + matrix.decompose(this); +}; + + +Object.defineProperties(Transform.prototype, { + /** + * The rotation of the object in radians. + * + * @member {number} + * @memberof PIXI.Transform# + */ + rotation: { + get: function () { + return this._rotation; + }, + set: function (value) { + this._rotation = value; + this._sr = Math.sin(value); + this._cr = Math.cos(value); + } + } +}); + +module.exports = Transform; + +},{"../math":67,"./TransformBase":48}],48:[function(require,module,exports){ +var math = require('../math'); + + +/** + * Generic class to deal with traditional 2D matrix transforms + * + * @class + * @memberof PIXI + */ +function TransformBase() +{ + /** + * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds() + * + * @member {PIXI.Matrix} + */ + this.worldTransform = new math.Matrix(); + /** + * The local matrix transform + * + * @member {PIXI.Matrix} + */ + this.localTransform = new math.Matrix(); + + this._worldID = 0; +} + +TransformBase.prototype.constructor = TransformBase; + +/** + * TransformBase does not have decomposition, so this function wont do anything + */ +TransformBase.prototype.updateLocalTransform = function() { // jshint unused:false + +}; + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.TransformBase} The transform of the parent of this object + * + */ +TransformBase.prototype.updateTransform = function (parentTransform) +{ + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID ++; +}; + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ +TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; + +TransformBase.IDENTITY = new TransformBase(); + +module.exports = TransformBase; + +},{"../math":67}],49:[function(require,module,exports){ +var math = require('../math'), + TransformBase = require('./TransformBase'); + +/** + * Transform that takes care about its versions + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +function TransformStatic() +{ + TransformBase.call(this); + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.ObservablePoint} + */ + this.position = new math.ObservablePoint(this.onChange, this,0,0); + + /** + * The scale factor of the object. + * + * @member {PIXI.ObservablePoint} + */ + this.scale = new math.ObservablePoint(this.onChange, this,1,1); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.ObservablePoint} + */ + this.pivot = new math.ObservablePoint(this.onChange, this,0, 0); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + this.skew = new math.ObservablePoint(this.updateSkew, this,0, 0); + + this._rotation = 0; + + this._sr = Math.sin(0); + this._cr = Math.cos(0); + this._cy = Math.cos(0);//skewY); + this._sy = Math.sin(0);//skewY); + this._nsx = Math.sin(0);//skewX); + this._cx = Math.cos(0);//skewX); + + this._localID = 0; + this._currentLocalID = 0; +} + +TransformStatic.prototype = Object.create(TransformBase.prototype); +TransformStatic.prototype.constructor = TransformStatic; + +TransformStatic.prototype.onChange = function () +{ + this._localID ++; +}; + +TransformStatic.prototype.updateSkew = function () +{ + this._cy = Math.cos(this.skew._y); + this._sy = Math.sin(this.skew._y); + this._nsx = Math.sin(this.skew._x); + this._cx = Math.cos(this.skew._x); + + this._localID ++; +}; + +/** + * Updates only local matrix + */ +TransformStatic.prototype.updateLocalTransform = function() { + var lt = this.localTransform; + if(this._localID !== this._currentLocalID) + { + // get the matrix values of the displayobject based on its transform properties.. + var a,b,c,d; + + a = this._cr * this.scale._x; + b = this._sr * this.scale._x; + c = -this._sr * this.scale._y; + d = this._cr * this.scale._y; + + lt.a = this._cy * a + this._sy * c; + lt.b = this._cy * b + this._sy * d; + lt.c = this._nsx * a + this._cx * c; + lt.d = this._nsx * b + this._cx * d; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } +}; + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ +TransformStatic.prototype.updateTransform = function (parentTransform) +{ + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + if(this._localID !== this._currentLocalID) + { + // get the matrix values of the displayobject based on its transform properties.. + var a,b,c,d; + + a = this._cr * this.scale._x; + b = this._sr * this.scale._x; + c = -this._sr * this.scale._y; + d = this._cr * this.scale._y; + + lt.a = this._cy * a + this._sy * c; + lt.b = this._cy * b + this._sy * d; + lt.c = this._nsx * a + this._cx * c; + lt.d = this._nsx * b + this._cx * d; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + + if(this._parentID !== parentTransform._worldID) + { + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._parentID = parentTransform._worldID; + + // update the id of the transform.. + this._worldID ++; + } +}; + +/** + * Decomposes a matrix and sets the transforms properties based on it. + * @param {PIXI.Matrix} The matrix to decompose + */ +TransformStatic.prototype.setFromMatrix = function (matrix) +{ + matrix.decompose(this); + this._localID ++; +}; + +Object.defineProperties(TransformStatic.prototype, { + /** + * The rotation of the object in radians. + * + * @member {number} + * @memberof PIXI.TransformStatic# + */ + rotation: { + get: function () { + return this._rotation; + }, + set: function (value) { + this._rotation = value; + this._sr = Math.sin(value); + this._cr = Math.cos(value); + this._localID ++; + } + } +}); + +module.exports = TransformStatic; + +},{"../math":67,"./TransformBase":48}],50:[function(require,module,exports){ +var Container = require('../display/Container'), + RenderTexture = require('../textures/RenderTexture'), + Texture = require('../textures/Texture'), + GraphicsData = require('./GraphicsData'), + Sprite = require('../sprites/Sprite'), + math = require('../math'), + CONST = require('../const'), + utils = require('../utils'), + Bounds = require('../display/Bounds'), + bezierCurveTo = require('./utils/bezierCurveTo'), + CanvasRenderer = require('../renderers/canvas/CanvasRenderer'), + canvasRenderer, + tempMatrix = new math.Matrix(), + tempPoint = new math.Point(), + tempColor1 = new Float32Array(4), + tempColor2 = new Float32Array(4); + +/** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ +function Graphics() +{ + Container.call(this); + + /** + * The alpha value used when filling the Graphics object. + * + * @member {number} + * @default 1 + */ + this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @member {number} + * @default 0 + */ + this.lineWidth = 0; + + /** + * The color of any lines drawn. + * + * @member {string} + * @default 0 + */ + this.lineColor = 0; + + /** + * Graphics data + * + * @member {PIXI.GraphicsData[]} + * @private + */ + this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to reset the tint. + * + * @member {number} + * @default 0xFFFFFF + */ + this.tint = 0xFFFFFF; + + /** + * The previous tint applied to the graphic shape. Used to compare to the current tint and check if theres change. + * + * @member {number} + * @private + * @default 0xFFFFFF + */ + this._prevTint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + this.blendMode = CONST.BLEND_MODES.NORMAL; + + /** + * Current path + * + * @member {PIXI.GraphicsData} + * @private + */ + this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @member {object} + * @private + */ + // TODO - _webgl should use a prototype object, not a random undocumented object... + this._webGL = {}; + + /** + * Whether this shape is being used as a mask. + * + * @member {boolean} + */ + this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @member {number} + */ + this.boundsPadding = 0; + + /** + * A cache of the local bounds to prevent recalculation. + * + * @member {PIXI.Rectangle} + * @private + */ + this._localBounds = new Bounds(); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics + * object will be recalculated. + * + * @member {boolean} + * @private + */ + this.dirty = 0; + + /** + * Used to detect if we need to do a fast rect check using the id compare method + * @type {Number} + */ + this.fastRectDirty = -1; + + /** + * Used to detect if we clear the graphics webGL data + * @type {Number} + */ + this.clearDirty = 0; + + /** + * Used to detect if we we need to recalculate local bounds + * @type {Number} + */ + this.boundsDirty = -1; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @member {boolean} + * @private + */ + this.cachedSpriteDirty = false; + + + this._spriteRect = null; + this._fastRect = false; + + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ +} + +Graphics._SPRITE_TEXTURE = null; + +// constructor +Graphics.prototype = Object.create(Container.prototype); +Graphics.prototype.constructor = Graphics; +module.exports = Graphics; + +/** + * Creates a new Graphics object with the same values as this one. + * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) + * + * @return {PIXI.Graphics} A clone of the graphics object + */ +Graphics.prototype.clone = function () +{ + var clone = new Graphics(); + + clone.renderable = this.renderable; + clone.fillAlpha = this.fillAlpha; + clone.lineWidth = this.lineWidth; + clone.lineColor = this.lineColor; + clone.tint = this.tint; + clone.blendMode = this.blendMode; + clone.isMask = this.isMask; + clone.boundsPadding = this.boundsPadding; + clone.dirty = 0; + clone.cachedSpriteDirty = this.cachedSpriteDirty; + + // copy graphics data + for (var i = 0; i < this.graphicsData.length; ++i) + { + clone.graphicsData.push(this.graphicsData[i].clone()); + } + + clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; + + clone.updateLocalBounds(); + + return clone; +}; + +/** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. + * + * @param lineWidth {number} width of the line to draw, will update the objects stored style + * @param color {number} color of the line to draw, will update the objects stored style + * @param alpha {number} alpha of the line to draw, will update the objects stored style + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.lineStyle = function (lineWidth, color, alpha) +{ + this.lineWidth = lineWidth || 0; + this.lineColor = color || 0; + this.lineAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length) + { + // halfway through a line? start a new one! + var shape = new math.Polygon(this.currentPath.shape.points.slice(-2)); + shape.closed = false; + this.drawShape(shape); + } + else + { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; +}; + +/** + * Moves the current drawing position to x, y. + * + * @param x {number} the X coordinate to move to + * @param y {number} the Y coordinate to move to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.moveTo = function (x, y) +{ + var shape = new math.Polygon([x,y]); + shape.closed = false; + this.drawShape(shape); + + return this; +}; + +/** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @param x {number} the X coordinate to draw to + * @param y {number} the Y coordinate to draw to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.lineTo = function (x, y) +{ + this.currentPath.shape.points.push(x, y); + this.dirty++; + + return this; +}; + +/** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @param cpX {number} Control point x + * @param cpY {number} Control point y + * @param toX {number} Destination point x + * @param toY {number} Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [0, 0]; + } + } + else + { + this.moveTo(0,0); + } + + + var xa, + ya, + n = 20, + points = this.currentPath.shape.points; + + if (points.length === 0) + { + this.moveTo(0, 0); + } + + var fromX = points[points.length-2]; + var fromY = points[points.length-1]; + + var j = 0; + for (var i = 1; i <= n; ++i) + { + j = i / n; + + xa = fromX + ( (cpX - fromX) * j ); + ya = fromY + ( (cpY - fromY) * j ); + + points.push( xa + ( ((cpX + ( (toX - cpX) * j )) - xa) * j ), + ya + ( ((cpY + ( (toY - cpY) * j )) - ya) * j ) ); + } + + this.dirty++; + + return this; +}; + +/** + * Calculate the points for a bezier curve and then draws it. + * + * @param cpX {number} Control point x + * @param cpY {number} Control point y + * @param cpX2 {number} Second Control point x + * @param cpY2 {number} Second Control point y + * @param toX {number} Destination point x + * @param toY {number} Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points = [0, 0]; + } + } + else + { + this.moveTo(0,0); + } + + var points = this.currentPath.shape.points; + + var fromX = points[points.length-2]; + var fromY = points[points.length-1]; + + points.length -= 2; + + bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, points); + + this.dirty++; + + return this; +}; + +/** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @param x1 {number} The x-coordinate of the beginning of the arc + * @param y1 {number} The y-coordinate of the beginning of the arc + * @param x2 {number} The x-coordinate of the end of the arc + * @param y2 {number} The y-coordinate of the end of the arc + * @param radius {number} The radius of the arc + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) +{ + if (this.currentPath) + { + if (this.currentPath.shape.points.length === 0) + { + this.currentPath.shape.points.push(x1, y1); + } + } + else + { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points, + fromX = points[points.length-2], + fromY = points[points.length-1], + a1 = fromY - y1, + b1 = fromX - x1, + a2 = y2 - y1, + b2 = x2 - x1, + mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) + { + if (points[points.length-2] !== x1 || points[points.length-1] !== y1) + { + points.push(x1, y1); + } + } + else + { + var dd = a1 * a1 + b1 * b1, + cc = a2 * a2 + b2 * b2, + tt = a1 * a2 + b1 * b2, + k1 = radius * Math.sqrt(dd) / mm, + k2 = radius * Math.sqrt(cc) / mm, + j1 = k1 * tt / dd, + j2 = k2 * tt / cc, + cx = k1 * b2 + k2 * b1, + cy = k1 * a2 + k2 * a1, + px = b1 * (k2 + j1), + py = a1 * (k2 + j1), + qx = b2 * (k1 + j2), + qy = a2 * (k1 + j2), + startAngle = Math.atan2(py - cy, px - cx), + endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty++; + + return this; +}; + +/** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @param cx {number} The x-coordinate of the center of the circle + * @param cy {number} The y-coordinate of the center of the circle + * @param radius {number} The radius of the circle + * @param startAngle {number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle) + * @param endAngle {number} The ending angle, in radians + * @param [anticlockwise=false] {boolean} Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.arc = function(cx, cy, radius, startAngle, endAngle, anticlockwise) +{ + anticlockwise = anticlockwise || false; + + if (startAngle === endAngle) + { + return this; + } + + if( !anticlockwise && endAngle <= startAngle ) + { + endAngle += Math.PI * 2; + } + else if( anticlockwise && startAngle <= endAngle ) + { + startAngle += Math.PI * 2; + } + + var sweep = anticlockwise ? (startAngle - endAngle) * -1 : (endAngle - startAngle); + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * 40; + + if(sweep === 0) + { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + if (this.currentPath) + { + this.currentPath.shape.points.push(startX, startY); + } + else + { + this.moveTo(startX, startY); + } + + var points = this.currentPath.shape.points; + + var theta = sweep/(segs*2); + var theta2 = theta*2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = ( segMinus % 1 ) / segMinus; + + for(var i=0; i<=segMinus; i++) + { + var real = i + remainder * i; + + + var angle = ((theta) + startAngle + (theta2 * real)); + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push(( (cTheta * c) + (sTheta * s) ) * radius + cx, + ( (cTheta * -s) + (sTheta * c) ) * radius + cy); + } + + this.dirty++; + + return this; +}; + +/** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @param color {number} the color of the fill + * @param alpha {number} the alpha of the fill + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.beginFill = function (color, alpha) +{ + this.filling = true; + this.fillColor = color || 0; + this.fillAlpha = (alpha === undefined) ? 1 : alpha; + + if (this.currentPath) + { + if (this.currentPath.shape.points.length <= 2) + { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + return this; +}; + +/** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.endFill = function () +{ + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; +}; + +/** + * + * @param x {number} The X coord of the top-left of the rectangle + * @param y {number} The Y coord of the top-left of the rectangle + * @param width {number} The width of the rectangle + * @param height {number} The height of the rectangle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.drawRect = function ( x, y, width, height ) +{ + this.drawShape(new math.Rectangle(x,y, width, height)); + + return this; +}; + +/** + * + * @param x {number} The X coord of the top-left of the rectangle + * @param y {number} The Y coord of the top-left of the rectangle + * @param width {number} The width of the rectangle + * @param height {number} The height of the rectangle + * @param radius {number} Radius of the rectangle corners + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.drawRoundedRect = function ( x, y, width, height, radius ) +{ + this.drawShape(new math.RoundedRectangle(x, y, width, height, radius)); + + return this; +}; + +/** + * Draws a circle. + * + * @param x {number} The X coordinate of the center of the circle + * @param y {number} The Y coordinate of the center of the circle + * @param radius {number} The radius of the circle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.drawCircle = function (x, y, radius) +{ + this.drawShape(new math.Circle(x,y, radius)); + + return this; +}; + +/** + * Draws an ellipse. + * + * @param x {number} The X coordinate of the center of the ellipse + * @param y {number} The Y coordinate of the center of the ellipse + * @param width {number} The half width of the ellipse + * @param height {number} The half height of the ellipse + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.drawEllipse = function (x, y, width, height) +{ + this.drawShape(new math.Ellipse(x, y, width, height)); + + return this; +}; + +/** + * Draws a polygon using the given path. + * + * @param path {number[]|PIXI.Point[]} The path data used to construct the polygon. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.drawPolygon = function (path) +{ + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + var closed = true; + + if (points instanceof math.Polygon) + { + closed = points.closed; + points = points.points; + } + + if (!Array.isArray(points)) + { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) + { + points[i] = arguments[i]; + } + } + + var shape = new math.Polygon(points); + shape.closed = closed; + + this.drawShape(shape); + + return this; +}; + +/** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ +Graphics.prototype.clear = function () +{ + this.lineWidth = 0; + this.filling = false; + + this.dirty++; + this.clearDirty++; + this.graphicsData = []; + + return this; +}; + +/** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and masked with gl.scissor + * @returns {boolean} + */ +Graphics.prototype.isFastRect = function() { + return this.graphicsData.length === 1 && this.graphicsData[0].shape.type === CONST.SHAPES.RECT && !this.graphicsData[0].lineWidth; +}; + +/** + * Renders the object using the WebGL renderer + * + * @param renderer {PIXI.WebGLRenderer} + * @private + */ +Graphics.prototype._renderWebGL = function (renderer) +{ + // if the sprite is not visible or the alpha is 0 then no need to render this element + if(this.dirty !== this.fastRectDirty) + { + this.fastRectDirty = this.dirty; + this._fastRect = this.isFastRect(); + } + + //TODO this check can be moved to dirty? + if(this._fastRect) + { + this._renderSpriteRect(renderer); + } + else + { + renderer.setObjectRenderer(renderer.plugins.graphics); + renderer.plugins.graphics.render(this); + } + +}; + +Graphics.prototype._renderSpriteRect = function (renderer) +{ + var rect = this.graphicsData[0].shape; + if(!this._spriteRect) + { + if(!Graphics._SPRITE_TEXTURE) + { + var canvas = document.createElement('canvas'); + canvas.width = 10; + canvas.height = 10; + var context = canvas.getContext('2d'); + context.fillStyle = 'white'; + context.fillRect(0, 0, 10, 10); + Graphics._SPRITE_TEXTURE = Texture.fromCanvas(canvas); + } + + this._spriteRect = new Sprite(Graphics._SPRITE_TEXTURE); + } + if (this.tint === 0xffffff) { + this._spriteRect.tint = this.graphicsData[0].fillColor; + } else { + var t1 = tempColor1; + var t2 = tempColor2; + utils.hex2rgb(this.graphicsData[0].fillColor, t1); + utils.hex2rgb(this.tint, t2); + t1[0] *= t2[0]; + t1[1] *= t2[1]; + t1[2] *= t2[2]; + this._spriteRect.tint = utils.rgb2hex(t1); + } + this._spriteRect.alpha = this.graphicsData[0].fillAlpha; + this._spriteRect.worldAlpha = this.worldAlpha * this._spriteRect.alpha; + + Graphics._SPRITE_TEXTURE._frame.width = rect.width; + Graphics._SPRITE_TEXTURE._frame.height = rect.height; + + this._spriteRect.transform.worldTransform = this.transform.worldTransform; + + this._spriteRect.anchor.set(-rect.x / rect.width, -rect.y / rect.height); + this._spriteRect.onAnchorUpdate(); + + this._spriteRect._renderWebGL(renderer); +}; + +/** + * Renders the object using the Canvas renderer + * + * @param renderer {PIXI.CanvasRenderer} + * @private + */ +Graphics.prototype._renderCanvas = function (renderer) +{ + if (this.isMask === true) + { + return; + } + + renderer.plugins.graphics.render(this); +}; + +/** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @param [matrix] {PIXI.Matrix} The world transform matrix to use, defaults to this + * object's worldTransform. + * @return {PIXI.Rectangle} the rectangular bounding area + */ +Graphics.prototype._calculateBounds = function () +{ + if (!this.renderable) + { + return; + } + + if (this.boundsDirty !== this.dirty) + { + this.boundsDirty = this.dirty; + this.updateLocalBounds(); + + this.dirty++; + this.cachedSpriteDirty = true; + } + + var lb = this._localBounds; + this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); +}; + +/** +* Tests if a point is inside this graphics object +* +* @param point {PIXI.Point} the point to test +* @return {boolean} the result of the test +*/ +Graphics.prototype.containsPoint = function( point ) +{ + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; i++) + { + var data = graphicsData[i]; + + if (!data.fill) + { + continue; + } + + // only deal with fills.. + if (data.shape) + { + if ( data.shape.contains( tempPoint.x, tempPoint.y ) ) + { + return true; + } + } + } + + return false; +}; + +/** + * Update the bounds of the object + * + */ +Graphics.prototype.updateLocalBounds = function () +{ + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) + { + var shape, points, x, y, w, h; + + for (var i = 0; i < this.graphicsData.length; i++) + { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + shape = data.shape; + + if (type === CONST.SHAPES.RECT || type === CONST.SHAPES.RREC) + { + x = shape.x - lineWidth/2; + y = shape.y - lineWidth/2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === CONST.SHAPES.CIRC) + { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth/2; + h = shape.radius + lineWidth/2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else if (type === CONST.SHAPES.ELIP) + { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth/2; + h = shape.height + lineWidth/2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } + else + { + // POLY + points = shape.points; + + for (var j = 0; j < points.length; j += 2) + { + x = points[j]; + y = points[j+1]; + + minX = x-lineWidth < minX ? x-lineWidth : minX; + maxX = x+lineWidth > maxX ? x+lineWidth : maxX; + + minY = y-lineWidth < minY ? y-lineWidth : minY; + maxY = y+lineWidth > maxY ? y+lineWidth : maxY; + } + } + } + } + else + { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.minX = minX - padding; + this._localBounds.maxX = maxX + padding * 2; + + this._localBounds.minY = minY - padding; + this._localBounds.maxY = maxY + padding * 2; +}; + + +/** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @param shape {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} The shape object to draw. + * @return {PIXI.GraphicsData} The generated GraphicsData object. + */ +Graphics.prototype.drawShape = function (shape) +{ + if (this.currentPath) + { + // check current path! + if (this.currentPath.shape.points.length <= 2) + { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + var data = new GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape); + + this.graphicsData.push(data); + + if (data.type === CONST.SHAPES.POLY) + { + data.shape.closed = data.shape.closed || this.filling; + this.currentPath = data; + } + + this.dirty++; + + return data; +}; + +Graphics.prototype.generateCanvasTexture = function(scaleMode, resolution) +{ + resolution = resolution || 1; + + var bounds = this.getLocalBounds(); + + var canvasBuffer = new RenderTexture.create(bounds.width * resolution, bounds.height * resolution); + + if(!canvasRenderer) + { + canvasRenderer = new CanvasRenderer(); + } + + tempMatrix.tx = -bounds.x; + tempMatrix.ty = -bounds.y; + + canvasRenderer.render(this, canvasBuffer, false, tempMatrix); + + var texture = Texture.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas, scaleMode); + texture.baseTexture.resolution = resolution; + + return texture; +}; + +Graphics.prototype.closePath = function () +{ + // ok so close path assumes next one is a hole! + var currentPath = this.currentPath; + if (currentPath && currentPath.shape) + { + currentPath.shape.close(); + } + return this; +}; + +Graphics.prototype.addHole = function() +{ + // this is a hole! + var hole = this.graphicsData.pop(); + + this.currentPath = this.graphicsData[this.graphicsData.length-1]; + + this.currentPath.addHole(hole.shape); + this.currentPath = null; + + return this; +}; + +/** + * Destroys the Graphics object. + */ +Graphics.prototype.destroy = function () +{ + Container.prototype.destroy.apply(this, arguments); + + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._webgl) { + for (var j = 0; j < this._webgl[id].data.length; ++j) { + this._webgl[id].data[j].destroy(); + } + } + + if(this._spriteRect) + { + this._spriteRect.destroy(); + } + this.graphicsData = null; + + this.currentPath = null; + this._webgl = null; + this._localBounds = null; +}; + +},{"../const":43,"../display/Bounds":44,"../display/Container":45,"../math":67,"../renderers/canvas/CanvasRenderer":74,"../sprites/Sprite":98,"../textures/RenderTexture":108,"../textures/Texture":109,"../utils":116,"./GraphicsData":51,"./utils/bezierCurveTo":53}],51:[function(require,module,exports){ +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + * @param lineWidth {number} the width of the line to draw + * @param lineColor {number} the color of the line to draw + * @param lineAlpha {number} the alpha of the line to draw + * @param fillColor {number} the color of the fill + * @param fillAlpha {number} the alpha of the fill + * @param fill {boolean} whether or not the shape is filled with a colour + * @param shape {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} The shape object to draw. + */ +function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) +{ + /* + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + + /* + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /* + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /* + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /* + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /* + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /* + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /* + * @member {boolean} whether or not the shape is filled with a colour + */ + this.fill = fill; + + this.holes = []; + + /* + * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} The shape object to draw. + */ + this.shape = shape; + + /* + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; +} + +GraphicsData.prototype.constructor = GraphicsData; +module.exports = GraphicsData; + +/** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {PIXI.GraphicsData} Cloned GraphicsData object + */ +GraphicsData.prototype.clone = function () +{ + return new GraphicsData( + this.lineWidth, + this.lineColor, + this.lineAlpha, + this.fillColor, + this.fillAlpha, + this.fill, + this.shape + ); +}; + +/** + * + * + */ +GraphicsData.prototype.addHole = function (shape) +{ + this.holes.push(shape); +}; + +/** + * Destroys the Graphics data. + */ +GraphicsData.prototype.destroy = function () { + this.shape = null; + this.holes = null; +}; + +},{}],52:[function(require,module,exports){ +var CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'), + CONST = require('../../const'); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasGraphicsRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasGraphicsRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching graphics objects. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + * @param renderer {PIXI.SystemRenderer} The current PIXI renderer. + */ +function CanvasGraphicsRenderer(renderer) +{ + this.renderer = renderer; +} + + +CanvasGraphicsRenderer.prototype.constructor = CanvasGraphicsRenderer; +module.exports = CanvasGraphicsRenderer; + +CanvasRenderer.registerPlugin('graphics', CanvasGraphicsRenderer); + +/* + * Renders a Graphics object to a canvas. + * + * @param graphics {PIXI.Graphics} the actual graphics object to render + * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas + */ +CanvasGraphicsRenderer.prototype.render = function (graphics) +{ + var renderer = this.renderer; + var context = renderer.context; + var worldAlpha = graphics.worldAlpha; + var transform = graphics.transform.worldTransform; + var resolution = renderer.resolution; + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) { + this.dirty = true; + } + + context.setTransform( + transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + transform.tx * resolution, + transform.ty * resolution + ); + + + if (graphics.dirty) + { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + renderer.setBlendMode(graphics.blendMode); + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === CONST.SHAPES.POLY) + { + context.beginPath(); + + this.renderPolygon(shape.points, shape.closed, context); + + for (var j = 0; j < data.holes.length; j++) + { + var hole = data.holes[j]; + this.renderPolygon(hole.points, true, context); + } + + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === CONST.SHAPES.RECT) + { + + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + + } + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } + else if (data.type === CONST.SHAPES.CIRC) + { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI); + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === CONST.SHAPES.ELIP) + { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + context.beginPath(); + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + else if (data.type === CONST.SHAPES.RREC) + { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) + { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6); + context.fill(); + + } + if (data.lineWidth) + { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } +}; + +/* + * Updates the tint of a graphics object + * + * @private + * @param graphics {PIXI.Graphics} the graphics that will have its tint updated + * + */ +CanvasGraphicsRenderer.prototype.updateGraphicsTint = function (graphics) +{ + graphics._prevTint = graphics.tint; + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF)/ 255; + + for (var i = 0; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + // super inline cos im an optimization NAZI :) + data._fillTint = (((fillColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (fillColor & 0xFF) / 255 * tintB*255); + data._lineTint = (((lineColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (lineColor & 0xFF) / 255 * tintB*255); + } +}; + +CanvasGraphicsRenderer.prototype.renderPolygon = function (points, close, context) +{ + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (close) + { + context.closePath(); + } +}; + +/* + * destroy graphics object + * + */ +CanvasGraphicsRenderer.prototype.destroy = function () +{ + this.renderer = null; +}; + +},{"../../const":43,"../../renderers/canvas/CanvasRenderer":74}],53:[function(require,module,exports){ + +/** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @param fromX {number} Starting point x + * @param fromY {number} Starting point y + * @param cpX {number} Control point x + * @param cpY {number} Control point y + * @param cpX2 {number} Second Control point x + * @param cpY2 {number} Second Control point y + * @param toX {number} Destination point x + * @param toY {number} Destination point y + * @param [path=number[]] Path array to push points into + * @return {PIXI.Graphics} + */ +var bezierCurveTo = function (fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, path) // jshint ignore:line +{ + path = path || []; + + var n = 20, + dt, + dt2, + dt3, + t2, + t3; + + path.push(fromX, fromY); + + var j = 0; + + for (var i = 1; i <= n; ++i) + { + j = i / n; + + dt = (1 - j); + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + path.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, + dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + return path; +}; + +module.exports = bezierCurveTo; + +},{}],54:[function(require,module,exports){ +var utils = require('../../utils'), + CONST = require('../../const'), + ObjectRenderer = require('../../renderers/webgl/utils/ObjectRenderer'), + WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'), + WebGLGraphicsData = require('./WebGLGraphicsData'), + PrimitiveShader = require('./shaders/PrimitiveShader'), + + // some drawing functions.. + buildPoly = require('./utils/buildPoly'), + buildRectangle = require('./utils/buildRectangle'), + buildRoundedRectangle = require('./utils/buildRoundedRectangle'), + buildCircle = require('./utils/buildCircle'); + + + +/** + * Renders the graphics object. + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + * @param renderer {PIXI.WebGLRenderer} The renderer this object renderer works for. + */ +function GraphicsRenderer(renderer) +{ + ObjectRenderer.call(this, renderer); + + this.graphicsDataPool = []; + + this.primitiveShader = null; + + this.gl = renderer.gl; + + // easy access! + this.CONTEXT_UID = 0; +} + +GraphicsRenderer.prototype = Object.create(ObjectRenderer.prototype); +GraphicsRenderer.prototype.constructor = GraphicsRenderer; +module.exports = GraphicsRenderer; + +WebGLRenderer.registerPlugin('graphics', GraphicsRenderer); + +/** + * Called when there is a WebGL context change + * + * @private + * + */ +GraphicsRenderer.prototype.onContextChange = function() +{ + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.primitiveShader = new PrimitiveShader(this.gl); +}; + +/** + * Destroys this renderer. + * + */ +GraphicsRenderer.prototype.destroy = function () +{ + ObjectRenderer.prototype.destroy.call(this); + + for (var i = 0; i < this.graphicsDataPool.length; ++i) { + this.graphicsDataPool[i].destroy(); + } + + this.graphicsDataPool = null; +}; + +/** + * Renders a graphics object. + * + * @param graphics {PIXI.Graphics} The graphics object to render. + */ +GraphicsRenderer.prototype.render = function(graphics) +{ + var renderer = this.renderer; + var gl = renderer.gl; + + var webGLData; + + var webGL = graphics._webGL[this.CONTEXT_UID]; + + if (!webGL || graphics.dirty !== webGL.dirty ) + { + + this.updateGraphics(graphics); + + webGL = graphics._webGL[this.CONTEXT_UID]; + } + + + + // This could be speeded up for sure! + var shader = this.primitiveShader; + renderer.bindShader(shader); + renderer.state.setBlendMode( graphics.blendMode ); + + for (var i = 0, n = webGL.data.length; i < n; i++) + { + webGLData = webGL.data[i]; + var shaderTemp = webGLData.shader; + + renderer.bindShader(shaderTemp); + shaderTemp.uniforms.translationMatrix = graphics.transform.worldTransform.toArray(true); + shaderTemp.uniforms.tint = utils.hex2rgb(graphics.tint); + shaderTemp.uniforms.alpha = graphics.worldAlpha; + + webGLData.vao.bind() + .draw(gl.TRIANGLE_STRIP, webGLData.indices.length) + .unbind(); + } +}; + +/** + * Updates the graphics object + * + * @private + * @param graphics {PIXI.Graphics} The graphics object to update + */ +GraphicsRenderer.prototype.updateGraphics = function(graphics) +{ + var gl = this.renderer.gl; + + // get the contexts graphics object + var webGL = graphics._webGL[this.CONTEXT_UID]; + + // if the graphics object does not exist in the webGL context time to create it! + if (!webGL) + { + webGL = graphics._webGL[this.CONTEXT_UID] = {lastIndex:0, data:[], gl:gl, clearDirty:-1, dirty:-1}; + + } + + // flag the graphics as not dirty as we are about to update it... + webGL.dirty = graphics.dirty; + + var i; + + // if the user cleared the graphics object we will need to clear every object + if (graphics.clearDirty !== webGL.clearDirty) + { + webGL.clearDirty = graphics.clearDirty; + + // loop through and return all the webGLDatas to the object pool so than can be reused later on + for (i = 0; i < webGL.data.length; i++) + { + var graphicsData = webGL.data[i]; + this.graphicsDataPool.push( graphicsData ); + } + + // clear the array and reset the index.. + webGL.data = []; + webGL.lastIndex = 0; + } + + var webGLData; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++) + { + var data = graphics.graphicsData[i]; + + //TODO - this can be simplified + webGLData = this.getWebGLData(webGL, 0); + + if (data.type === CONST.SHAPES.POLY) + { + buildPoly(data, webGLData); + } + if (data.type === CONST.SHAPES.RECT) + { + buildRectangle(data, webGLData); + } + else if (data.type === CONST.SHAPES.CIRC || data.type === CONST.SHAPES.ELIP) + { + buildCircle(data, webGLData); + } + else if (data.type === CONST.SHAPES.RREC) + { + buildRoundedRectangle(data, webGLData); + } + + webGL.lastIndex++; + } + + // upload all the dirty data... + for (i = 0; i < webGL.data.length; i++) + { + webGLData = webGL.data[i]; + + if (webGLData.dirty) + { + webGLData.upload(); + } + } +}; + +/** + * + * @private + * @param webGL {WebGLRenderingContext} the current WebGL drawing context + * @param type {number} TODO @Alvin + */ +GraphicsRenderer.prototype.getWebGLData = function (webGL, type) +{ + var webGLData = webGL.data[webGL.data.length-1]; + + if (!webGLData || webGLData.points.length > 320000) + { + webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData.reset(type); + webGL.data.push(webGLData); + } + + webGLData.dirty = true; + + return webGLData; +}; + +},{"../../const":43,"../../renderers/webgl/WebGLRenderer":81,"../../renderers/webgl/utils/ObjectRenderer":91,"../../utils":116,"./WebGLGraphicsData":55,"./shaders/PrimitiveShader":56,"./utils/buildCircle":57,"./utils/buildPoly":59,"./utils/buildRectangle":60,"./utils/buildRoundedRectangle":61}],55:[function(require,module,exports){ +var glCore = require('pixi-gl-core'); + + +/** + * An object containing WebGL specific properties to be used by the WebGL renderer + * + * @class + * @private + * @memberof PIXI + * @param gl {WebGLRenderingContext} The current WebGL drawing context + * @param shader {PIXI.Shader} The shader + * @param attribsState {object} The state for the VAO + */ +function WebGLGraphicsData(gl, shader, attribsState) +{ + + /** + * The current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + //TODO does this need to be split before uploding?? + /** + * An array of color components (r,g,b) + * @member {number[]} + */ + this.color = [0,0,0]; // color split! + + /** + * An array of points to draw + * @member {PIXI.Point[]} + */ + this.points = []; + + /** + * The indices of the vertices + * @member {number[]} + */ + this.indices = []; + /** + * The main buffer + * @member {WebGLBuffer} + */ + this.buffer = glCore.GLBuffer.createVertexBuffer(gl); + + /** + * The index buffer + * @member {WebGLBuffer} + */ + this.indexBuffer = glCore.GLBuffer.createIndexBuffer(gl); + + /** + * Whether this graphics is dirty or not + * @member {boolean} + */ + this.dirty = true; + + this.glPoints = null; + this.glIndices = null; + + /** + * + * @member {PIXI.Shader} + */ + this.shader = shader; + + this.vao = new glCore.VertexArrayObject(gl, attribsState) + .addIndex(this.indexBuffer) + .addAttribute(this.buffer, shader.attributes.aVertexPosition, gl.FLOAT, false, 4 * 6, 0) + .addAttribute(this.buffer, shader.attributes.aColor, gl.FLOAT, false, 4 * 6, 2 * 4); + + +} + +WebGLGraphicsData.prototype.constructor = WebGLGraphicsData; +module.exports = WebGLGraphicsData; + +/** + * Resets the vertices and the indices + */ +WebGLGraphicsData.prototype.reset = function () +{ + this.points.length = 0; + this.indices.length = 0; +}; + +/** + * Binds the buffers and uploads the data + */ +WebGLGraphicsData.prototype.upload = function () +{ + this.glPoints = new Float32Array(this.points); + this.buffer.upload( this.glPoints ); + + this.glIndices = new Uint16Array(this.indices); + this.indexBuffer.upload( this.glIndices ); + + this.dirty = false; +}; + + + +/** + * Empties all the data + */ +WebGLGraphicsData.prototype.destroy = function () +{ + this.color = null; + this.points = null; + this.indices = null; + + this.vao.destroy(); + this.buffer.destroy(); + this.indexBuffer.destroy(); + + this.gl = null; + + this.buffer = null; + this.indexBuffer = null; + + this.glPoints = null; + this.glIndices = null; +}; + +},{"pixi-gl-core":12}],56:[function(require,module,exports){ +var Shader = require('../../../Shader'); + +/** + * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. + * + * @class + * @memberof PIXI + * @extends PIXI.Shader + * @param gl {WebGLRenderingContext} The webgl shader manager this shader works for. + */ +function PrimitiveShader(gl) +{ + Shader.call(this, + gl, + // vertex shader + [ + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', + + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', + + 'uniform float alpha;', + 'uniform vec3 tint;', + + 'varying vec4 vColor;', + + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}' + ].join('\n'), + // fragment shader + [ + 'varying vec4 vColor;', + + 'void main(void){', + ' gl_FragColor = vColor;', + '}' + ].join('\n') + ); +} + +PrimitiveShader.prototype = Object.create(Shader.prototype); +PrimitiveShader.prototype.constructor = PrimitiveShader; + +module.exports = PrimitiveShader; + +},{"../../../Shader":42}],57:[function(require,module,exports){ +var buildLine = require('./buildLine'), + CONST = require('../../../const'), + utils = require('../../../utils'); + +/** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param graphicsData {PIXI.WebGLGraphicsData} The graphics object to draw + * @param webGLData {object} an object containing all the webGL-specific information to create this shape + */ +var buildCircle = function (graphicsData, webGLData) +{ + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width; + var height; + + // TODO - bit hacky?? + if (graphicsData.type === CONST.SHAPES.CIRC) + { + width = circleData.radius; + height = circleData.radius; + } + else + { + width = circleData.width; + height = circleData.height; + } + + var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); + var seg = (Math.PI * 2) / totalSegs ; + + var i = 0; + + if (graphicsData.fill) + { + var color = utils.hex2rgb(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length/6; + + indices.push(vecPos); + + for (i = 0; i < totalSegs + 1 ; i++) + { + verts.push(x,y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height, + r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos-1); + } + + if (graphicsData.lineWidth) + { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (i = 0; i < totalSegs + 1; i++) + { + graphicsData.points.push(x + Math.sin(seg * i) * width, + y + Math.cos(seg * i) * height); + } + + buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + + +module.exports = buildCircle; + +},{"../../../const":43,"../../../utils":116,"./buildLine":58}],58:[function(require,module,exports){ +var math = require('../../../math'), + utils = require('../../../utils'); + +/** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param graphicsData {PIXI.WebGLGraphicsData} The graphics object containing all the necessary properties + * @param webGLData {object} an object containing all the webGL-specific information to create this shape + */ +var buildLine = function (graphicsData, webGLData) +{ + // TODO OPTIMISE! + var i = 0; + var points = graphicsData.points; + + if (points.length === 0) + { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + + // get first and last point.. figure out the middle! + var firstPoint = new math.Point(points[0], points[1]); + var lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); + + // if the first point is the last point - gonna have issues :) + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) + { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new math.Point(points[points.length - 2], points[points.length - 1]); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length/6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = utils.hex2rgb(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var px, py, p1x, p1y, p2x, p2y, p3x, p3y; + var perpx, perpy, perp2x, perp2y, perp3x, perp3y; + var a1, b1, c1, a2, b2, c2; + var denom, pdist, dist; + + p1x = points[0]; + p1y = points[1]; + + p2x = points[2]; + p2y = points[3]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx , p1y - perpy, + r, g, b, alpha); + + verts.push(p1x + perpx , p1y + perpy, + r, g, b, alpha); + + for (i = 1; i < length-1; i++) + { + p1x = points[(i-1)*2]; + p1y = points[(i-1)*2 + 1]; + + p2x = points[(i)*2]; + p2y = points[(i)*2 + 1]; + + p3x = points[(i+1)*2]; + p3y = points[(i+1)*2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + a1 = (-perpy + p1y) - (-perpy + p2y); + b1 = (-perpx + p2x) - (-perpx + p1x); + c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + a2 = (-perp2y + p3y) - (-perp2y + p2y); + b2 = (-perp2x + p2x) - (-perp2x + p3x); + c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + denom = a1*b2 - a2*b1; + + if (Math.abs(denom) < 0.1 ) + { + + denom+=10.1; + verts.push(p2x - perpx , p2y - perpy, + r, g, b, alpha); + + verts.push(p2x + perpx , p2y + perpy, + r, g, b, alpha); + + continue; + } + + px = (b1*c2 - b2*c1)/denom; + py = (a2*c1 - a1*c2)/denom; + + + pdist = (px -p2x) * (px -p2x) + (py -p2y) * (py -p2y); + + + if (pdist > 140 * 140) + { + perp3x = perpx - perp2x; + perp3y = perpy - perp2y; + + dist = Math.sqrt(perp3x*perp3x + perp3y*perp3y); + perp3x /= dist; + perp3y /= dist; + perp3x *= width; + perp3y *= width; + + verts.push(p2x - perp3x, p2y -perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x + perp3x, p2y +perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x - perp3x, p2y -perp3y); + verts.push(r, g, b, alpha); + + indexCount++; + } + else + { + + verts.push(px , py); + verts.push(r, g, b, alpha); + + verts.push(p2x - (px-p2x), p2y - (py - p2y)); + verts.push(r, g, b, alpha); + } + } + + p1x = points[(length-2)*2]; + p1y = points[(length-2)*2 + 1]; + + p2x = points[(length-1)*2]; + p2y = points[(length-1)*2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx*perpx + perpy*perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + verts.push(p2x - perpx , p2y - perpy); + verts.push(r, g, b, alpha); + + verts.push(p2x + perpx , p2y + perpy); + verts.push(r, g, b, alpha); + + indices.push(indexStart); + + for (i = 0; i < indexCount; i++) + { + indices.push(indexStart++); + } + + indices.push(indexStart-1); +}; + +module.exports = buildLine; + +},{"../../../math":67,"../../../utils":116}],59:[function(require,module,exports){ +var buildLine = require('./buildLine'), + utils = require('../../../utils'), + earcut = require('earcut'); + +/** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param graphicsData {PIXI.WebGLGraphicsData} The graphics object containing all the necessary properties + * @param webGLData {object} an object containing all the webGL-specific information to create this shape + */ +var buildPoly = function (graphicsData, webGLData) +{ + graphicsData.points = graphicsData.shape.points.slice(); + + var points = graphicsData.points; + + if(graphicsData.fill && points.length >= 6) + { + var holeArray = []; + // Process holes.. + var holes = graphicsData.holes; + + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + + holeArray.push(points.length/2); + + points = points.concat(hole.points); + } + + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = utils.hex2rgb(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = earcut(points, holeArray, 2); + + if (!triangles) { + return; + } + + var vertPos = verts.length / 6; + + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vertPos); + indices.push(triangles[i] + vertPos); + indices.push(triangles[i+1] + vertPos); + indices.push(triangles[i+2] +vertPos); + indices.push(triangles[i+2] + vertPos); + } + + for (i = 0; i < length; i++) + { + verts.push(points[i * 2], points[i * 2 + 1], + r, g, b, alpha); + } + } + + if (graphicsData.lineWidth > 0) + { + buildLine(graphicsData, webGLData); + } +}; + + +module.exports = buildPoly; + +},{"../../../utils":116,"./buildLine":58,"earcut":2}],60:[function(require,module,exports){ +var buildLine = require('./buildLine'), + utils = require('../../../utils'); + +/** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param graphicsData {PIXI.WebGLGraphicsData} The graphics object containing all the necessary properties + * @param webGLData {object} an object containing all the webGL-specific information to create this shape + */ +var buildRectangle = function (graphicsData, webGLData) +{ + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if (graphicsData.fill) + { + var color = utils.hex2rgb(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vertPos = verts.length/6; + + // start + verts.push(x, y); + verts.push(r, g, b, alpha); + + verts.push(x + width, y); + verts.push(r, g, b, alpha); + + verts.push(x , y + height); + verts.push(r, g, b, alpha); + + verts.push(x + width, y + height); + verts.push(r, g, b, alpha); + + // insert 2 dead triangles.. + indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3); + } + + if (graphicsData.lineWidth) + { + var tempPoints = graphicsData.points; + + graphicsData.points = [x, y, + x + width, y, + x + width, y + height, + x, y + height, + x, y]; + + + buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +module.exports = buildRectangle; + +},{"../../../utils":116,"./buildLine":58}],61:[function(require,module,exports){ +var earcut = require('earcut'), + buildLine = require('./buildLine'), + utils = require('../../../utils'); + +/** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param graphicsData {PIXI.WebGLGraphicsData} The graphics object containing all the necessary properties + * @param webGLData {object} an object containing all the webGL-specific information to create this shape + */ +var buildRoundedRectangle = function (graphicsData, webGLData) +{ + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + recPoints.push(x, y + radius); + quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height, recPoints); + quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius, recPoints); + quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y, recPoints); + quadraticBezierCurve(x + radius, y, x, y, x, y + radius + 0.0000000001, recPoints); + + // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. + // TODO - fix this properly, this is not very elegant.. but it works for now. + + if (graphicsData.fill) + { + var color = utils.hex2rgb(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length/6; + + var triangles = earcut(recPoints, null, 2); + + var i = 0; + for (i = 0; i < triangles.length; i+=3) + { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i+1] + vecPos); + indices.push(triangles[i+2] + vecPos); + indices.push(triangles[i+2] + vecPos); + } + + for (i = 0; i < recPoints.length; i++) + { + verts.push(recPoints[i], recPoints[++i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) + { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + buildLine(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +}; + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param fromX {number} Origin point x + * @param fromY {number} Origin point x + * @param cpX {number} Control point x + * @param cpY {number} Control point y + * @param toX {number} Destination point x + * @param toY {number} Destination point y + * @param [out] {number[]} The output array to add points into. If not passed, a new array is created. + * @return {number[]} an array of points + */ +var quadraticBezierCurve = function (fromX, fromY, cpX, cpY, toX, toY, out)// jshint ignore:line +{ + var xa, + ya, + xb, + yb, + x, + y, + n = 20, + points = out || []; + + function getPt(n1 , n2, perc) { + var diff = n2 - n1; + + return n1 + ( diff * perc ); + } + + var j = 0; + for (var i = 0; i <= n; i++ ) { + j = i / n; + + // The Green Line + xa = getPt( fromX , cpX , j ); + ya = getPt( fromY , cpY , j ); + xb = getPt( cpX , toX , j ); + yb = getPt( cpY , toY , j ); + + // The Black Dot + x = getPt( xa , xb , j ); + y = getPt( ya , yb , j ); + + points.push(x, y); + } + + return points; +}; + + +module.exports = buildRoundedRectangle; + +},{"../../../utils":116,"./buildLine":58,"earcut":2}],62:[function(require,module,exports){ +/** + * @file Main export of the PIXI core library + * @author Mat Groves + * @copyright 2013-2015 GoodBoyDigital + * @license {@link https://github.com/pixijs/pixi.js/blob/master/LICENSE|MIT License} + */ + +/** + * @namespace PIXI + */ +// export core and const. We assign core to const so that the non-reference types in const remain in-tact +var core = module.exports = Object.assign(require('./const'), require('./math'), { + // utils + utils: require('./utils'), + ticker: require('./ticker'), + + // display + DisplayObject: require('./display/DisplayObject'), + Container: require('./display/Container'), + Transform: require('./display/Transform'), + TransformStatic: require('./display/TransformStatic'), + TransformBase: require('./display/TransformBase'), + + // sprites + Sprite: require('./sprites/Sprite'), + CanvasSpriteRenderer: require('./sprites/canvas/CanvasSpriteRenderer'), + CanvasTinter: require('./sprites/canvas/CanvasTinter'), + SpriteRenderer: require('./sprites/webgl/SpriteRenderer'), + + // text + Text: require('./text/Text'), + TextStyle: require('./text/TextStyle'), + // primitives + Graphics: require('./graphics/Graphics'), + GraphicsData: require('./graphics/GraphicsData'), + GraphicsRenderer: require('./graphics/webgl/GraphicsRenderer'), + CanvasGraphicsRenderer: require('./graphics/canvas/CanvasGraphicsRenderer'), + + // textures + Texture: require('./textures/Texture'), + BaseTexture: require('./textures/BaseTexture'), + RenderTexture: require('./textures/RenderTexture'), + BaseRenderTexture: require('./textures/BaseRenderTexture'), + VideoBaseTexture: require('./textures/VideoBaseTexture'), + TextureUvs: require('./textures/TextureUvs'), + + // renderers - canvas + CanvasRenderer: require('./renderers/canvas/CanvasRenderer'), + CanvasRenderTarget: require('./renderers/canvas/utils/CanvasRenderTarget'), + + // renderers - webgl + Shader: require('./Shader'), + WebGLRenderer: require('./renderers/webgl/WebGLRenderer'), + WebGLManager: require('./renderers/webgl/managers/WebGLManager'), + ObjectRenderer: require('./renderers/webgl/utils/ObjectRenderer'), + RenderTarget: require('./renderers/webgl/utils/RenderTarget'), + Quad: require('./renderers/webgl/utils/Quad'), + + // filters - webgl + SpriteMaskFilter: require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter'), + Filter: require('./renderers/webgl/filters/Filter'), + + glCore: require('pixi-gl-core'), + + /** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by + * the browser then this function will return a canvas renderer + * + * @memberof PIXI + * @param width=800 {number} the width of the renderers view + * @param height=600 {number} the height of the renderers view + * @param [options] {object} The optional renderer parameters + * @param [options.view] {HTMLCanvasElement} the canvas to use as a view, optional + * @param [options.transparent=false] {boolean} If the render view is transparent, default false + * @param [options.antialias=false] {boolean} sets antialias (only applicable in chrome at the moment) + * @param [options.preserveDrawingBuffer=false] {boolean} enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param [options.resolution=1] {number} The resolution / device pixel ratio of the renderer, retina would be 2 + * @param [noWebGL=false] {boolean} prevents selection of WebGL renderer, even if such is present + * + * @return {WebGLRenderer|CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ + autoDetectRenderer: function (width, height, options, noWebGL) + { + width = width || 800; + height = height || 600; + + if (!noWebGL && core.utils.isWebGLSupported()) + { + return new core.WebGLRenderer(width, height, options); + } + + return new core.CanvasRenderer(width, height, options); + } +}); + +},{"./Shader":42,"./const":43,"./display/Container":45,"./display/DisplayObject":46,"./display/Transform":47,"./display/TransformBase":48,"./display/TransformStatic":49,"./graphics/Graphics":50,"./graphics/GraphicsData":51,"./graphics/canvas/CanvasGraphicsRenderer":52,"./graphics/webgl/GraphicsRenderer":54,"./math":67,"./renderers/canvas/CanvasRenderer":74,"./renderers/canvas/utils/CanvasRenderTarget":76,"./renderers/webgl/WebGLRenderer":81,"./renderers/webgl/filters/Filter":83,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":86,"./renderers/webgl/managers/WebGLManager":90,"./renderers/webgl/utils/ObjectRenderer":91,"./renderers/webgl/utils/Quad":92,"./renderers/webgl/utils/RenderTarget":93,"./sprites/Sprite":98,"./sprites/canvas/CanvasSpriteRenderer":99,"./sprites/canvas/CanvasTinter":100,"./sprites/webgl/SpriteRenderer":102,"./text/Text":104,"./text/TextStyle":105,"./textures/BaseRenderTexture":106,"./textures/BaseTexture":107,"./textures/RenderTexture":108,"./textures/Texture":109,"./textures/TextureUvs":110,"./textures/VideoBaseTexture":111,"./ticker":113,"./utils":116,"pixi-gl-core":12}],63:[function(require,module,exports){ +// Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16 + +var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; +var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; +var tempMatrices = []; +var Matrix = require('./Matrix'); + +var mul = []; + +function signum(x) { + if (x < 0) { + return -1; + } + if (x > 0) { + return 1; + } + return 0; +} + +function init() { + for (var i = 0; i < 16; i++) { + var row = []; + mul.push(row); + for (var j = 0; j < 16; j++) { + var _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); + var _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); + var _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); + var _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + + for (i=0;i<16;i++) { + var mat = new Matrix(); + mat.set(ux[i], uy[i], vx[i], vy[i], 0, 0); + tempMatrices.push(mat); + } +} + +init(); + +/** + * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, D8 is the same but with diagonals + * Used for texture rotations + * Vector xX(i), xY(i) is U-axis of sprite with rotation i + * Vector yY(i), yY(i) is V-axis of sprite with rotation i + * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) + * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) + * This is the small part of gameofbombs.com portal system. It works. + * @author Ivan @ivanpopelyshev + * + * @namespace PIXI.GroupD8 + */ +var GroupD8 = { + E: 0, + SE: 1, + S: 2, + SW: 3, + W: 4, + NW: 5, + N: 6, + NE: 7, + MIRROR_VERTICAL: 8, + MIRROR_HORIZONTAL: 12, + uX: function (ind) { + return ux[ind]; + }, + uY: function (ind) { + return uy[ind]; + }, + vX: function (ind) { + return vx[ind]; + }, + vY: function (ind) { + return vy[ind]; + }, + inv: function (rotation) { + if (rotation & 8) { + return rotation & 15; + } + return (-rotation) & 7; + }, + add: function (rotationSecond, rotationFirst) { + return mul[rotationSecond][rotationFirst]; + }, + sub: function (rotationSecond, rotationFirst) { + return mul[rotationSecond][GroupD8.inv(rotationFirst)]; + }, + /** + * Adds 180 degrees to rotation. Commutative operation + * @param rotation + * @returns {number} + */ + rotate180: function (rotation) { + return rotation ^ 4; + }, + /** + * I dont know why sometimes width and heights needs to be swapped. We'll fix it later. + * @param rotation + * @returns {boolean} + */ + isSwapWidthHeight: function(rotation) { + return (rotation & 3) === 2; + }, + byDirection: function (dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return GroupD8.S; + } + else { + return GroupD8.N; + } + } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return GroupD8.E; + } + else { + return GroupD8.W; + } + } else { + if (dy > 0) { + if (dx > 0) { + return GroupD8.SE; + } + else { + return GroupD8.SW; + } + } + else if (dx > 0) { + return GroupD8.NE; + } + else { + return GroupD8.NW; + } + } + }, + /** + * Helps sprite to compensate texture packer rotation. + * @param matrix {PIXI.Matrix} sprite world matrix + * @param rotation {number} + * @param tx {number|*} sprite anchoring + * @param ty {number|*} sprite anchoring + */ + matrixAppendRotationInv: function (matrix, rotation, tx, ty) { + //Packer used "rotation", we use "inv(rotation)" + var mat = tempMatrices[GroupD8.inv(rotation)]; + tx = tx || 0; + ty = ty || 0; + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + } +}; + +module.exports = GroupD8; + +},{"./Matrix":64}],64:[function(require,module,exports){ +// @todo - ignore the too many parameters warning for now +// should either fix it or change the jshint config +// jshint -W072 + +var Point = require('./Point'); + +/** + * The pixi Matrix class as an object, which makes it a lot faster, + * here is a representation of it : + * | a | b | tx| + * | c | d | ty| + * | 0 | 0 | 1 | + * + * @class + * @memberof PIXI + */ +function Matrix() +{ + /** + * @member {number} + * @default 1 + */ + this.a = 1; + + /** + * @member {number} + * @default 0 + */ + this.b = 0; + + /** + * @member {number} + * @default 0 + */ + this.c = 0; + + /** + * @member {number} + * @default 1 + */ + this.d = 1; + + /** + * @member {number} + * @default 0 + */ + this.tx = 0; + + /** + * @member {number} + * @default 0 + */ + this.ty = 0; + + this.array = null; +} + +Matrix.prototype.constructor = Matrix; +module.exports = Matrix; + +/** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @param array {number[]} The array that the matrix will be populated from. + */ +Matrix.prototype.fromArray = function (array) +{ + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; +}; + + +/** + * sets the matrix properties + * + * @param {number} a + * @param {number} b + * @param {number} c + * @param {number} d + * @param {number} tx + * @param {number} ty + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.set = function (a, b, c, d, tx, ty) +{ + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; +}; + + +/** + * Creates an array from the current Matrix object. + * + * @param transpose {boolean} Whether we need to transpose the matrix or not + * @param [out=new Float32Array(9)] {Float32Array} If provided the array will be assigned to out + * @return {number[]} the newly created array which contains the matrix + */ +Matrix.prototype.toArray = function (transpose, out) +{ + if (!this.array) + { + this.array = new Float32Array(9); + } + + var array = out || this.array; + + if (transpose) + { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } + else + { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; +}; + +/** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * + * @param pos {PIXI.Point} The origin + * @param [newPos] {PIXI.Point} The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, transformed through this matrix + */ +Matrix.prototype.apply = function (pos, newPos) +{ + newPos = newPos || new Point(); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; + + return newPos; +}; + +/** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * + * @param pos {PIXI.Point} The origin + * @param [newPos] {PIXI.Point} The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, inverse-transformed through this matrix + */ +Matrix.prototype.applyInverse = function (pos, newPos) +{ + newPos = newPos || new Point(); + + var id = 1 / (this.a * this.d + this.c * -this.b); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; +}; + +/** + * Translates the matrix on the x and y. + * + * @param {number} x How much to translate x by + * @param {number} y How much to translate y by + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.translate = function (x, y) +{ + this.tx += x; + this.ty += y; + + return this; +}; + +/** + * Applies a scale transformation to the matrix. + * + * @param {number} x The amount to scale horizontally + * @param {number} y The amount to scale vertically + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.scale = function (x, y) +{ + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; +}; + + +/** + * Applies a rotation transformation to the matrix. + * + * @param {number} angle - The angle in radians. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.rotate = function (angle) +{ + var cos = Math.cos( angle ); + var sin = Math.sin( angle ); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos-this.b * sin; + this.b = a1 * sin+this.b * cos; + this.c = c1 * cos-this.d * sin; + this.d = c1 * sin+this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; +}; + +/** + * Appends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.append = function (matrix) +{ + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; +}; + +/** + * Sets the matrix based on all the available properties + * + * @param {number} x Position on the x axis + * @param {number} y Position on the y axis + * @param {number} pivotX Pivot on the x axis + * @param {number} pivotY Pivot on the y axis + * @param {number} scaleX Scale on the x axis + * @param {number} scaleY Scale on the y axis + * @param {number} rotation Rotation in radians + * @param {number} skewX Skew on the x axis + * @param {number} skewY Skew on the y axis + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.setTransform = function (x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) +{ + var a, b, c, d, sr, cr, cy, sy, nsx, cx; + + sr = Math.sin(rotation); + cr = Math.cos(rotation); + cy = Math.cos(skewY); + sy = Math.sin(skewY); + nsx = -Math.sin(skewX); + cx = Math.cos(skewX); + + a = cr * scaleX; + b = sr * scaleX; + c = -sr * scaleY; + d = cr * scaleY; + + this.a = cy * a + sy * c; + this.b = cy * b + sy * d; + this.c = nsx * a + cx * c; + this.d = nsx * b + cx * d; + + this.tx = x + ( pivotX * a + pivotY * c ); + this.ty = y + ( pivotX * b + pivotY * d ); + + return this; +}; + +/** + * Prepends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.prepend = function(matrix) +{ + var tx1 = this.tx; + + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) + { + var a1 = this.a; + var c1 = this.c; + this.a = a1*matrix.a+this.b*matrix.c; + this.b = a1*matrix.b+this.b*matrix.d; + this.c = c1*matrix.a+this.d*matrix.c; + this.d = c1*matrix.b+this.d*matrix.d; + } + + this.tx = tx1*matrix.a+this.ty*matrix.c+matrix.tx; + this.ty = tx1*matrix.b+this.ty*matrix.d+matrix.ty; + + return this; +}; + +/** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * @param transform {PIXI.Transform|PIXI.TransformStatic} the transform to apply the properties to. + * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properies +*/ +Matrix.prototype.decompose = function(transform) +{ + // sort out rotation / skew.. + var a = this.a, + b = this.b, + c = this.c, + d = this.d; + + var skewX = Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + + var delta = Math.abs(1-skewX/skewY); + + if (delta < 0.00001) + { + transform.rotation = skewY; + + if (a < 0 && d >= 0) + { + transform.rotation += (transform.rotation <= 0) ? Math.PI : -Math.PI; + } + + transform.skew.x = transform.skew.y = 0; + + } + else + { + transform.skew.x = skewX; + transform.skew.y = skewY; + } + + // next set scale + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); + + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; + + return transform; +}; + + +/** + * Inverts this matrix + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.invert = function() +{ + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1*d1-b1*c1; + + this.a = d1/n; + this.b = -b1/n; + this.c = -c1/n; + this.d = a1/n; + this.tx = (c1*this.ty-d1*tx1)/n; + this.ty = -(a1*this.ty-b1*tx1)/n; + + return this; +}; + + +/** + * Resets this Matix to an identity (default) matrix. + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ +Matrix.prototype.identity = function () +{ + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + + return this; +}; + +/** + * Creates a new Matrix object with the same values as this one. + * + * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. + */ +Matrix.prototype.clone = function () +{ + var matrix = new Matrix(); + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; +}; + +/** + * Changes the values of the given matrix to be the same as the ones in this matrix + * + * @return {PIXI.Matrix} The matrix given in parameter with its values updated. + */ +Matrix.prototype.copy = function (matrix) +{ + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; +}; + +/** + * A default (identity) matrix + * + * @static + * @const + */ +Matrix.IDENTITY = new Matrix(); + +/** + * A temp matrix + * + * @static + * @const + */ +Matrix.TEMP_MATRIX = new Matrix(); + +},{"./Point":66}],65:[function(require,module,exports){ +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * An observable point is a point that triggers a callback when the point's position is changed. + * + * @class + * @memberof PIXI + * @param cb {Function} callback when changed + * @param scope {Object} owner of callback + * @param [x=0] {number} position of the point on the x axis + * @param [y=0] {number} position of the point on the y axis + */ +function ObservablePoint(cb, scope, x, y) +{ + this._x = x || 0; + this._y = y || 0; + + this.cb = cb; + this.scope = scope; +} + +ObservablePoint.prototype.constructor = ObservablePoint; +module.exports = ObservablePoint; + + + +Object.defineProperties(ObservablePoint.prototype, { + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + * @memberof PIXI.ObservablePoint# + */ + x: { + get: function () + { + return this._x; + }, + set: function (value) + { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + } + }, + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + * @memberof PIXI.ObservablePoint# + */ + y: { + get: function () + { + return this._y; + }, + set: function (value) + { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + } + } +}); + +/** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param [x=0] {number} position of the point on the x axis + * @param [y=0] {number} position of the point on the y axis + */ +ObservablePoint.prototype.set = function (x, y) +{ + var _x = x || 0; + var _y = y || ( (y !== 0) ? _x : 0 ); + if (this._x !== _x || this._y !== _y) + { + this._x = _x; + this._y = _y; + this.cb.call(this.scope); + } +}; + +/** + * Copies the data from another point + * + * @param point {PIXI.Point|PIXI.ObservablePoint} point to copy from + */ +ObservablePoint.prototype.copy = function (point) +{ + if (this._x !== point.x || this._y !== point.y) + { + this._x = point.x; + this._y = point.y; + this.cb.call(this.scope); + } +}; + +},{}],66:[function(require,module,exports){ +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * + * @class + * @memberof PIXI + * @param [x=0] {number} position of the point on the x axis + * @param [y=0] {number} position of the point on the y axis + */ +function Point(x, y) +{ + /** + * @member {number} + * @default 0 + */ + this.x = x || 0; + + /** + * @member {number} + * @default 0 + */ + this.y = y || 0; +} + +Point.prototype.constructor = Point; +module.exports = Point; + +/** + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point + */ +Point.prototype.clone = function () +{ + return new Point(this.x, this.y); +}; + +/** + * Copies x and y from the given point + * + * @param p {PIXI.Point} + */ +Point.prototype.copy = function (p) { + this.set(p.x, p.y); +}; + +/** + * Returns true if the given point is equal to this point + * + * @param p {PIXI.Point} + * @returns {boolean} Whether the given point equal to this point + */ +Point.prototype.equals = function (p) { + return (p.x === this.x) && (p.y === this.y); +}; + +/** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param [x=0] {number} position of the point on the x axis + * @param [y=0] {number} position of the point on the y axis + */ +Point.prototype.set = function (x, y) +{ + this.x = x || 0; + this.y = y || ( (y !== 0) ? this.x : 0 ) ; +}; + +},{}],67:[function(require,module,exports){ +/** + * Math classes and utilities mixed into PIXI namespace. + * + * @lends PIXI + */ +module.exports = { + // These will be mixed to be made publicly available, + // while this module is used internally in core + // to avoid circular dependencies and cut down on + // internal module requires. + + Point: require('./Point'), + ObservablePoint: require('./ObservablePoint'), + Matrix: require('./Matrix'), + GroupD8: require('./GroupD8'), + + Circle: require('./shapes/Circle'), + Ellipse: require('./shapes/Ellipse'), + Polygon: require('./shapes/Polygon'), + Rectangle: require('./shapes/Rectangle'), + RoundedRectangle: require('./shapes/RoundedRectangle') +}; + +},{"./GroupD8":63,"./Matrix":64,"./ObservablePoint":65,"./Point":66,"./shapes/Circle":68,"./shapes/Ellipse":69,"./shapes/Polygon":70,"./shapes/Rectangle":71,"./shapes/RoundedRectangle":72}],68:[function(require,module,exports){ +var Rectangle = require('./Rectangle'), + CONST = require('../../const'); + +/** + * The Circle object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + * @param x {number} The X coordinate of the center of this circle + * @param y {number} The Y coordinate of the center of this circle + * @param radius {number} The radius of the circle + */ +function Circle(x, y, radius) +{ + /** + * @member {number} + * @default 0 + */ + this.x = x || 0; + + /** + * @member {number} + * @default 0 + */ + this.y = y || 0; + + /** + * @member {number} + * @default 0 + */ + this.radius = radius || 0; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default CONST.SHAPES.CIRC + * @see PIXI.SHAPES + */ + this.type = CONST.SHAPES.CIRC; +} + +Circle.prototype.constructor = Circle; +module.exports = Circle; + +/** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ +Circle.prototype.clone = function () +{ + return new Circle(this.x, this.y, this.radius); +}; + +/** + * Checks whether the x and y coordinates given are contained within this circle + * + * @param x {number} The X coordinate of the point to test + * @param y {number} The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Circle + */ +Circle.prototype.contains = function (x, y) +{ + if (this.radius <= 0) + { + return false; + } + + var dx = (this.x - x), + dy = (this.y - y), + r2 = this.radius * this.radius; + + dx *= dx; + dy *= dy; + + return (dx + dy <= r2); +}; + +/** +* Returns the framing rectangle of the circle as a Rectangle object +* +* @return {PIXI.Rectangle} the framing rectangle +*/ +Circle.prototype.getBounds = function () +{ + return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); +}; + +},{"../../const":43,"./Rectangle":71}],69:[function(require,module,exports){ +var Rectangle = require('./Rectangle'), + CONST = require('../../const'); + +/** + * The Ellipse object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + * @param x {number} The X coordinate of the center of the ellipse + * @param y {number} The Y coordinate of the center of the ellipse + * @param width {number} The half width of this ellipse + * @param height {number} The half height of this ellipse + */ +function Ellipse(x, y, width, height) +{ + /** + * @member {number} + * @default 0 + */ + this.x = x || 0; + + /** + * @member {number} + * @default 0 + */ + this.y = y || 0; + + /** + * @member {number} + * @default 0 + */ + this.width = width || 0; + + /** + * @member {number} + * @default 0 + */ + this.height = height || 0; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default CONST.SHAPES.ELIP + * @see PIXI.SHAPES + */ + this.type = CONST.SHAPES.ELIP; +} + +Ellipse.prototype.constructor = Ellipse; +module.exports = Ellipse; + +/** + * Creates a clone of this Ellipse instance + * + * @return {PIXI.Ellipse} a copy of the ellipse + */ +Ellipse.prototype.clone = function () +{ + return new Ellipse(this.x, this.y, this.width, this.height); +}; + +/** + * Checks whether the x and y coordinates given are contained within this ellipse + * + * @param x {number} The X coordinate of the point to test + * @param y {number} The Y coordinate of the point to test + * @return {boolean} Whether the x/y coords are within this ellipse + */ +Ellipse.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { + return false; + } + + //normalize the coords to an ellipse with center 0,0 + var normx = ((x - this.x) / this.width), + normy = ((y - this.y) / this.height); + + normx *= normx; + normy *= normy; + + return (normx + normy <= 1); +}; + +/** + * Returns the framing rectangle of the ellipse as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ +Ellipse.prototype.getBounds = function () +{ + return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); +}; + +},{"../../const":43,"./Rectangle":71}],70:[function(require,module,exports){ +var Point = require('../Point'), + CONST = require('../../const'); + +/** + * @class + * @memberof PIXI + * @param points_ {PIXI.Point[]|number[]|...PIXI.Point|...number} This can be an array of Points that form the polygon, + * a flat array of numbers that will be interpreted as [x,y, x,y, ...], or the arguments passed can be + * all the points of the polygon e.g. `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the + * arguments passed can be flat x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are + * Numbers. + */ +function Polygon(points_) +{ + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = points_; + + //if points isn't an array, use arguments as the array + if (!Array.isArray(points)) + { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var a = 0; a < points.length; ++a) { + points[a] = arguments[a]; + } + } + + // if this is an array of points, convert it to a flat array of numbers + if (points[0] instanceof Point) + { + var p = []; + for (var i = 0, il = points.length; i < il; i++) + { + p.push(points[i].x, points[i].y); + } + + points = p; + } + + this.closed = true; + + /** + * An array of the points of this polygon + * + * @member {number[]} + */ + this.points = points; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default CONST.SHAPES.POLY + * @see PIXI.SHAPES + */ + this.type = CONST.SHAPES.POLY; +} + +Polygon.prototype.constructor = Polygon; +module.exports = Polygon; + +/** + * Creates a clone of this polygon + * + * @return {PIXI.Polygon} a copy of the polygon + */ +Polygon.prototype.clone = function () +{ + return new Polygon(this.points.slice()); +}; + + +Polygon.prototype.close = function () +{ + var points = this.points; + + // close the poly if the value is true! + if (points[0] !== points[points.length-2] || points[1] !== points[points.length-1]) + { + points.push(points[0], points[1]); + } +}; + +/** + * Checks whether the x and y coordinates passed to this function are contained within this polygon + * + * @param x {number} The X coordinate of the point to test + * @param y {number} The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this polygon + */ +Polygon.prototype.contains = function (x, y) +{ + var inside = false; + + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + + for (var i = 0, j = length - 1; i < length; j = i++) + { + var xi = this.points[i * 2], yi = this.points[i * 2 + 1], + xj = this.points[j * 2], yj = this.points[j * 2 + 1], + intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); + + if (intersect) + { + inside = !inside; + } + } + + return inside; +}; + +},{"../../const":43,"../Point":66}],71:[function(require,module,exports){ +var CONST = require('../../const'); + +/** + * the Rectangle object is an area defined by its position, as indicated by its top-left corner point (x, y) and by its width and its height. + * + * @class + * @memberof PIXI + * @param x {number} The X coordinate of the upper-left corner of the rectangle + * @param y {number} The Y coordinate of the upper-left corner of the rectangle + * @param width {number} The overall width of this rectangle + * @param height {number} The overall height of this rectangle + */ +function Rectangle(x, y, width, height) +{ + /** + * @member {number} + * @default 0 + */ + this.x = x || 0; + + /** + * @member {number} + * @default 0 + */ + this.y = y || 0; + + /** + * @member {number} + * @default 0 + */ + this.width = width || 0; + + /** + * @member {number} + * @default 0 + */ + this.height = height || 0; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default CONST.SHAPES.RECT + * @see PIXI.SHAPES + */ + this.type = CONST.SHAPES.RECT; +} + +Rectangle.prototype.constructor = Rectangle; +module.exports = Rectangle; + + +Object.defineProperties(Rectangle.prototype, { + /** + * returns the left edge of the rectangle + * + * @member {number} + * @memberof PIXI.Rectangle# + */ + left: { + get: function () + { + return this.x; + } + }, + + /** + * returns the right edge of the rectangle + * + * @member {number} + * @memberof PIXI.Rectangle + */ + right: { + get: function () + { + return this.x + this.width; + } + }, + + /** + * returns the top edge of the rectangle + * + * @member {number} + * @memberof PIXI.Rectangle + */ + top: { + get: function () + { + return this.y; + } + }, + + /** + * returns the bottom edge of the rectangle + * + * @member {number} + * @memberof PIXI.Rectangle + */ + bottom: { + get: function () + { + return this.y + this.height; + } + } + +}); + +/** + * A constant empty rectangle. + * + * @static + * @constant + */ +Rectangle.EMPTY = new Rectangle(0, 0, 0, 0); + + +/** + * Creates a clone of this Rectangle + * + * @return {PIXI.Rectangle} a copy of the rectangle + */ +Rectangle.prototype.clone = function () +{ + return new Rectangle(this.x, this.y, this.width, this.height); +}; + +Rectangle.prototype.copy = function (rectangle) +{ + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + + return this; +}; + +/** + * Checks whether the x and y coordinates given are contained within this Rectangle + * + * @param x {number} The X coordinate of the point to test + * @param y {number} The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rectangle + */ +Rectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { + return false; + } + + if (x >= this.x && x < this.x + this.width) + { + if (y >= this.y && y < this.y + this.height) + { + return true; + } + } + + return false; +}; + +Rectangle.prototype.pad = function (paddingX, paddingY) +{ + paddingX = paddingX || 0; + paddingY = paddingY || ( (paddingY !== 0) ? paddingX : 0 ); + + this.x -= paddingX; + this.y -= paddingY; + + this.width += paddingX * 2; + this.height += paddingY * 2; +}; + +Rectangle.prototype.fit = function (rectangle) +{ + if (this.x < rectangle.x) + { + this.width += this.x; + if(this.width < 0) { + this.width = 0; + } + + this.x = rectangle.x; + } + + if (this.y < rectangle.y) + { + this.height += this.y; + if(this.height < 0) { + this.height = 0; + } + this.y = rectangle.y; + } + + if ( this.x + this.width > rectangle.x + rectangle.width ) + { + this.width = rectangle.width - this.x; + if(this.width < 0) { + this.width = 0; + } + } + + if ( this.y + this.height > rectangle.y + rectangle.height ) + { + this.height = rectangle.height - this.y; + if(this.height < 0) { + this.height = 0; + } + } +}; + +Rectangle.prototype.enlarge = function (rect) +{ + + if (rect === Rectangle.EMPTY) + { + return; + } + + var x1 = Math.min(this.x, rect.x); + var x2 = Math.max(this.x + this.width, rect.x + rect.width); + var y1 = Math.min(this.y, rect.y); + var y2 = Math.max(this.y + this.height, rect.y + rect.height); + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; +}; + +},{"../../const":43}],72:[function(require,module,exports){ +var CONST = require('../../const'); + +/** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its top-left corner point (x, y) and by its width and its height and its radius. + * + * @class + * @memberof PIXI + * @param x {number} The X coordinate of the upper-left corner of the rounded rectangle + * @param y {number} The Y coordinate of the upper-left corner of the rounded rectangle + * @param width {number} The overall width of this rounded rectangle + * @param height {number} The overall height of this rounded rectangle + * @param radius {number} Controls the radius of the rounded corners + */ +function RoundedRectangle(x, y, width, height, radius) +{ + /** + * @member {number} + * @default 0 + */ + this.x = x || 0; + + /** + * @member {number} + * @default 0 + */ + this.y = y || 0; + + /** + * @member {number} + * @default 0 + */ + this.width = width || 0; + + /** + * @member {number} + * @default 0 + */ + this.height = height || 0; + + /** + * @member {number} + * @default 20 + */ + this.radius = radius || 20; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readonly + * @default CONST.SHAPES.RREC + * @see PIXI.SHAPES + */ + this.type = CONST.SHAPES.RREC; +} + +RoundedRectangle.prototype.constructor = RoundedRectangle; +module.exports = RoundedRectangle; + +/** + * Creates a clone of this Rounded Rectangle + * + * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle + */ +RoundedRectangle.prototype.clone = function () +{ + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); +}; + +/** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * + * @param x {number} The X coordinate of the point to test + * @param y {number} The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + */ +RoundedRectangle.prototype.contains = function (x, y) +{ + if (this.width <= 0 || this.height <= 0) + { + return false; + } + + if (x >= this.x && x <= this.x + this.width) + { + if (y >= this.y && y <= this.y + this.height) + { + return true; + } + } + + return false; +}; + +},{"../../const":43}],73:[function(require,module,exports){ +var utils = require('../utils'), + math = require('../math'), + CONST = require('../const'), + Container = require('../display/Container'), + RenderTexture = require('../textures/RenderTexture'), + EventEmitter = require('eventemitter3'), + tempMatrix = new math.Matrix(); +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. + * Don't forget to add the CanvasRenderer.view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @param system {string} The name of the system this renderer is for. + * @param [width=800] {number} the width of the canvas view + * @param [height=600] {number} the height of the canvas view + * @param [options] {object} The optional renderer parameters + * @param [options.view] {HTMLCanvasElement} the canvas to use as a view, optional + * @param [options.transparent=false] {boolean} If the render view is transparent, default false + * @param [options.autoResize=false] {boolean} If the render view is automatically resized, default false + * @param [options.antialias=false] {boolean} sets antialias (only applicable in chrome at the moment) + * @param [options.resolution=1] {number} The resolution / device pixel ratio of the renderer. The resolution of the renderer retina would be 2. + * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. + * @param [options.backgroundColor=0x000000] {number} The background color of the rendered area (shown if not transparent). + * @param [options.roundPixels=false] {boolean} If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + */ +function SystemRenderer(system, width, height, options) +{ + EventEmitter.call(this); + + utils.sayHello(system); + + // prepare options + if (options) + { + for (var i in CONST.DEFAULT_RENDER_OPTIONS) + { + if (typeof options[i] === 'undefined') + { + options[i] = CONST.DEFAULT_RENDER_OPTIONS[i]; + } + } + } + else + { + options = CONST.DEFAULT_RENDER_OPTIONS; + } + + /** + * The type of the renderer. + * + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + this.type = CONST.RENDERER_TYPE.UNKNOWN; + + /** + * The width of the canvas view + * + * @member {number} + * @default 800 + */ + this.width = width || 800; + + /** + * The height of the canvas view + * + * @member {number} + * @default 600 + */ + this.height = height || 600; + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + this.view = options.view || document.createElement('canvas'); + + /** + * The resolution / device pixel ratio of the renderer + * + * @member {number} + * @default 1 + */ + this.resolution = options.resolution; + + /** + * Whether the render view is transparent + * + * @member {boolean} + */ + this.transparent = options.transparent; + + /** + * Whether the render view should be resized automatically + * + * @member {boolean} + */ + this.autoResize = options.autoResize || false; + + /** + * Tracks the blend modes useful for this renderer. + * + * @member {object} + */ + this.blendModes = null; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. + * + * @member {boolean} + */ + this.preserveDrawingBuffer = options.preserveDrawingBuffer; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent Pixi will use a canvas sized fillRect operation every frame to set the canvas background color. + * If the scene is transparent Pixi will use clearRect to clear the canvas every frame. + * Disable this by setting this to false. For example if your game has a canvas filling background image you often don't need this set. + * + * @member {boolean} + * @default + */ + this.clearBeforeRender = options.clearBeforeRender; + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + * + * @member {boolean} + */ + this.roundPixels = options.roundPixels; + + /** + * The background color as a number. + * + * @member {number} + * @private + */ + this._backgroundColor = 0x000000; + + /** + * The background color as an [R, G, B] array. + * + * @member {number[]} + * @private + */ + this._backgroundColorRgba = [0, 0, 0, 0]; + + /** + * The background color as a string. + * + * @member {string} + * @private + */ + this._backgroundColorString = '#000000'; + + this.backgroundColor = options.backgroundColor || this._backgroundColor; // run bg color setter + + /** + * This temporary display object used as the parent of the currently being rendered item + * + * @member {PIXI.DisplayObject} + * @private + */ + this._tempDisplayObjectParent = new Container(); + + /** + * The last root object that the renderer tried to render. + * + * @member {PIXI.DisplayObject} + * @private + */ + this._lastObjectRendered = this._tempDisplayObjectParent; +} + +// constructor +SystemRenderer.prototype = Object.create(EventEmitter.prototype); +SystemRenderer.prototype.constructor = SystemRenderer; +module.exports = SystemRenderer; + +Object.defineProperties(SystemRenderer.prototype, { + /** + * The background color to fill if not transparent + * + * @member {number} + * @memberof PIXI.SystemRenderer# + */ + backgroundColor: + { + get: function () + { + return this._backgroundColor; + }, + set: function (val) + { + this._backgroundColor = val; + this._backgroundColorString = utils.hex2string(val); + utils.hex2rgb(val, this._backgroundColorRgba); + } + } +}); + +/** + * Resizes the canvas view to the specified width and height + * + * @param width {number} the new width of the canvas view + * @param height {number} the new height of the canvas view + */ +SystemRenderer.prototype.resize = function (width, height) { + this.width = width * this.resolution; + this.height = height * this.resolution; + + this.view.width = this.width; + this.view.height = this.height; + + if (this.autoResize) + { + this.view.style.width = this.width / this.resolution + 'px'; + this.view.style.height = this.height / this.resolution + 'px'; + } +}; + +/** + * Useful function that returns a texture of the display object that can then be used to create sprites + * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. + * + * @param displayObject {PIXI.DisplayObject} The displayObject the object will be generated from + * @param scaleMode {number} Should be one of the scaleMode consts + * @param resolution {number} The resolution / device pixel ratio of the texture being generated + * @return {PIXI.Texture} a texture of the graphics object + */ +SystemRenderer.prototype.generateTexture = function (displayObject, scaleMode, resolution) { + + var bounds = displayObject.getLocalBounds(); + + var renderTexture = RenderTexture.create(bounds.width | 0, bounds.height | 0, scaleMode, resolution); + + tempMatrix.tx = -bounds.x; + tempMatrix.ty = -bounds.y; + + this.render(displayObject, renderTexture, false, tempMatrix, true); + + return renderTexture; +}; + +/** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. + */ +SystemRenderer.prototype.destroy = function (removeView) { + if (removeView && this.view.parentNode) + { + this.view.parentNode.removeChild(this.view); + } + + this.type = CONST.RENDERER_TYPE.UNKNOWN; + + this.width = 0; + this.height = 0; + + this.view = null; + + this.resolution = 0; + + this.transparent = false; + + this.autoResize = false; + + this.blendModes = null; + + this.preserveDrawingBuffer = false; + this.clearBeforeRender = false; + + this.roundPixels = false; + + this._backgroundColor = 0; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + + this.backgroundColor = 0; + this._tempDisplayObjectParent = null; + this._lastObjectRendered = null; +}; + +},{"../const":43,"../display/Container":45,"../math":67,"../textures/RenderTexture":108,"../utils":116,"eventemitter3":3}],74:[function(require,module,exports){ +var SystemRenderer = require('../SystemRenderer'), + CanvasMaskManager = require('./utils/CanvasMaskManager'), + CanvasRenderTarget = require('./utils/CanvasRenderTarget'), + mapCanvasBlendModesToPixi = require('./utils/mapCanvasBlendModesToPixi'), + utils = require('../../utils'), + CONST = require('../../const'); + +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. + * Don't forget to add the CanvasRenderer.view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + * @param [width=800] {number} the width of the canvas view + * @param [height=600] {number} the height of the canvas view + * @param [options] {object} The optional renderer parameters + * @param [options.view] {HTMLCanvasElement} the canvas to use as a view, optional + * @param [options.transparent=false] {boolean} If the render view is transparent, default false + * @param [options.autoResize=false] {boolean} If the render view is automatically resized, default false + * @param [options.antialias=false] {boolean} sets antialias (only applicable in chrome at the moment) + * @param [options.resolution=1] {number} The resolution / device pixel ratio of the renderer. The resolution of the renderer retina would be 2. + * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. + * @param [options.roundPixels=false] {boolean} If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + */ +function CanvasRenderer(width, height, options) +{ + options = options || {}; + + SystemRenderer.call(this, 'Canvas', width, height, options); + + this.type = CONST.RENDERER_TYPE.CANVAS; + + /** + * The canvas 2d context that everything is drawn with. + * + * @member {CanvasRenderingContext2D} + */ + this.rootContext = this.view.getContext('2d', { alpha: this.transparent }); + this.rootResolution = this.resolution; + + /** + * Boolean flag controlling canvas refresh. + * + * @member {boolean} + */ + this.refresh = true; + + /** + * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. + * + * @member {PIXI.CanvasMaskManager} + */ + this.maskManager = new CanvasMaskManager(this); + + /** + * The canvas property used to set the canvas smoothing property. + * + * @member {string} + */ + this.smoothProperty = 'imageSmoothingEnabled'; + + if (!this.rootContext.imageSmoothingEnabled) + { + if (this.rootContext.webkitImageSmoothingEnabled) + { + this.smoothProperty = 'webkitImageSmoothingEnabled'; + } + else if (this.rootContext.mozImageSmoothingEnabled) + { + this.smoothProperty = 'mozImageSmoothingEnabled'; + } + else if (this.rootContext.oImageSmoothingEnabled) + { + this.smoothProperty = 'oImageSmoothingEnabled'; + } + else if (this.rootContext.msImageSmoothingEnabled) + { + this.smoothProperty = 'msImageSmoothingEnabled'; + } + } + + this.initPlugins(); + + this.blendModes = mapCanvasBlendModesToPixi(); + this._activeBlendMode = null; + + this.context = null; + this.renderingToScreen = false; + + this.resize(width, height); +} + +// constructor +CanvasRenderer.prototype = Object.create(SystemRenderer.prototype); +CanvasRenderer.prototype.constructor = CanvasRenderer; +module.exports = CanvasRenderer; +utils.pluginTarget.mixin(CanvasRenderer); + + +/** + * Renders the object to this canvas view + * + * @param displayObject {PIXI.DisplayObject} The object to be rendered + * @param [renderTexture] {PIXI.RenderTexture} A render texture to be rendered to. If unset, it will render to the root context. + * @param [clear=false] {boolean} Whether to clear the canvas before drawing + * @param [transform] {PIXI.Transform} A transformation to be applied + * @param [skipUpdateTransform=false] {boolean} Whether to skip the update transform + */ +CanvasRenderer.prototype.render = function (displayObject, renderTexture, clear, transform, skipUpdateTransform) +{ + + if (!this.view){ + return; + } + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + if(renderTexture) + { + renderTexture = renderTexture.baseTexture || renderTexture; + + if(!renderTexture._canvasRenderTarget) + { + + renderTexture._canvasRenderTarget = new CanvasRenderTarget(renderTexture.width, renderTexture.height, renderTexture.resolution); + renderTexture.source = renderTexture._canvasRenderTarget.canvas; + renderTexture.valid = true; + } + + this.context = renderTexture._canvasRenderTarget.context; + this.resolution = renderTexture._canvasRenderTarget.resolution; + } + else + { + + this.context = this.rootContext; + this.resolution = this.rootResolution; + } + + var context = this.context; + + if(!renderTexture) + { + this._lastObjectRendered = displayObject; + } + + + + + if(!skipUpdateTransform) + { + // update the scene graph + var cacheParent = displayObject.parent; + var tempWt = this._tempDisplayObjectParent.transform.worldTransform; + + if(transform) + { + transform.copy(tempWt); + } + else + { + tempWt.identity(); + } + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + + context.setTransform(1, 0, 0, 1, 0, 0); + context.globalAlpha = 1; + context.globalCompositeOperation = this.blendModes[CONST.BLEND_MODES.NORMAL]; + + if (navigator.isCocoonJS && this.view.screencanvas) + { + context.fillStyle = 'black'; + context.clear(); + } + + if(clear !== undefined ? clear : this.clearBeforeRender) + { + if (this.renderingToScreen) { + if (this.transparent) { + context.clearRect(0, 0, this.width, this.height); + } + else { + context.fillStyle = this._backgroundColorString; + context.fillRect(0, 0, this.width, this.height); + } + } //else { + //TODO: implement background for CanvasRenderTarget or RenderTexture? + //} + } + + // TODO RENDER TARGET STUFF HERE.. + var tempContext = this.context; + + this.context = context; + displayObject.renderCanvas(this); + this.context = tempContext; + + this.emit('postrender'); +}; + + +CanvasRenderer.prototype.setBlendMode = function (blendMode) +{ + if(this._activeBlendMode === blendMode) { + return; + } + + this.context.globalCompositeOperation = this.blendModes[blendMode]; +}; + +/** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. + */ +CanvasRenderer.prototype.destroy = function (removeView) +{ + this.destroyPlugins(); + + // call the base destroy + SystemRenderer.prototype.destroy.call(this, removeView); + + this.context = null; + + this.refresh = true; + + this.maskManager.destroy(); + this.maskManager = null; + + this.smoothProperty = null; +}; + +/** + * Resizes the canvas view to the specified width and height. + * + * @extends PIXI.SystemRenderer#resize + * + * @param width {number} The new width of the canvas view + * @param height {number} The new height of the canvas view + */ +CanvasRenderer.prototype.resize = function (width, height) +{ + SystemRenderer.prototype.resize.call(this, width, height); + + //reset the scale mode.. oddly this seems to be reset when the canvas is resized. + //surely a browser bug?? Let pixi fix that for you.. + if(this.smoothProperty) + { + this.rootContext[this.smoothProperty] = (CONST.SCALE_MODES.DEFAULT === CONST.SCALE_MODES.LINEAR); + } + +}; + +},{"../../const":43,"../../utils":116,"../SystemRenderer":73,"./utils/CanvasMaskManager":75,"./utils/CanvasRenderTarget":76,"./utils/mapCanvasBlendModesToPixi":78}],75:[function(require,module,exports){ +var CONST = require('../../../const'); +/** + * A set of functions used to handle masking. + * + * @class + * @memberof PIXI + */ +function CanvasMaskManager(renderer) +{ + this.renderer = renderer; +} + +CanvasMaskManager.prototype.constructor = CanvasMaskManager; +module.exports = CanvasMaskManager; + +/** + * This method adds it to the current stack of masks. + * + * @param maskData {object} the maskData that will be pushed + */ +CanvasMaskManager.prototype.pushMask = function (maskData) +{ + var renderer = this.renderer; + + renderer.context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.transform.worldTransform; + var resolution = renderer.resolution; + + renderer.context.setTransform( + transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + transform.tx * resolution, + transform.ty * resolution + ); + + //TODO suport sprite alpha masks?? + //lots of effort required. If demand is great enough.. + if(!maskData._texture) + { + this.renderGraphicsShape(maskData); + renderer.context.clip(); + } + + maskData.worldAlpha = cacheAlpha; +}; + +CanvasMaskManager.prototype.renderGraphicsShape = function (graphics) +{ + var context = this.renderer.context; + var len = graphics.graphicsData.length; + + if (len === 0) + { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) + { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === CONST.SHAPES.POLY) + { + + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j=1; j < points.length/2; j++) + { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length-2] && points[1] === points[points.length-1]) + { + context.closePath(); + } + + } + else if (data.type === CONST.SHAPES.RECT) + { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } + else if (data.type === CONST.SHAPES.CIRC) + { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } + else if (data.type === CONST.SHAPES.ELIP) + { + + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w/2; + var y = shape.y - h/2; + + var kappa = 0.5522848, + ox = (w / 2) * kappa, // control point offset horizontal + oy = (h / 2) * kappa, // control point offset vertical + xe = x + w, // x-end + ye = y + h, // y-end + xm = x + w / 2, // x-middle + ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } + else if (data.type === CONST.SHAPES.RREC) + { + + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } +}; + +/** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @param renderer {PIXI.WebGLRenderer|PIXI.CanvasRenderer} The renderer context to use. + */ +CanvasMaskManager.prototype.popMask = function (renderer) +{ + renderer.context.restore(); +}; + +CanvasMaskManager.prototype.destroy = function () {}; + +},{"../../../const":43}],76:[function(require,module,exports){ +var CONST = require('../../../const'); + +/** + * Creates a Canvas element of the given size. + * + * @class + * @memberof PIXI + * @param width {number} the width for the newly created canvas + * @param height {number} the height for the newly created canvas + * @param [resolution=1] The resolution / device pixel ratio of the canvas + */ +function CanvasRenderTarget(width, height, resolution) +{ + /** + * The Canvas object that belongs to this CanvasRenderTarget. + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @member {CanvasRenderingContext2D} + */ + this.context = this.canvas.getContext('2d'); + + this.resolution = resolution || CONST.RESOLUTION; + + this.resize(width, height); +} + +CanvasRenderTarget.prototype.constructor = CanvasRenderTarget; +module.exports = CanvasRenderTarget; + +Object.defineProperties(CanvasRenderTarget.prototype, { + /** + * The width of the canvas buffer in pixels. + * + * @member {number} + * @memberof PIXI.CanvasRenderTarget# + */ + width: { + get: function () + { + return this.canvas.width; + }, + set: function (val) + { + this.canvas.width = val; + } + }, + /** + * The height of the canvas buffer in pixels. + * + * @member {number} + * @memberof PIXI.CanvasRenderTarget# + */ + height: { + get: function () + { + return this.canvas.height; + }, + set: function (val) + { + this.canvas.height = val; + } + } +}); + +/** + * Clears the canvas that was created by the CanvasRenderTarget class. + * + * @private + */ +CanvasRenderTarget.prototype.clear = function () +{ + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0,0, this.canvas.width, this.canvas.height); +}; + +/** + * Resizes the canvas to the specified width and height. + * + * @param width {number} the new width of the canvas + * @param height {number} the new height of the canvas + */ +CanvasRenderTarget.prototype.resize = function (width, height) +{ + + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; +}; + +/** + * Destroys this canvas. + * + */ +CanvasRenderTarget.prototype.destroy = function () +{ + this.context = null; + this.canvas = null; +}; + +},{"../../../const":43}],77:[function(require,module,exports){ + + +/** + * Creates a little colored canvas + * @return {canvas} a small canvas element + */ +var createColoredCanvas = function(color) +{ + var canvas = document.createElement('canvas'); + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + context.fillStyle = color; + context.fillRect(0,0,6,1); + return canvas; +}; + + +/** + * Checks whether the Canvas BlendModes are supported by the current browser + * + * @return {boolean} whether they are supported + */ +var canUseNewCanvasBlendModes = function () +{ + if (typeof document === 'undefined') + { + return false; + } + + var magenta = createColoredCanvas('#ff00ff'); + var yellow = createColoredCanvas('#ffff00'); + + var canvas = document.createElement('canvas'); + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + context.globalCompositeOperation = 'multiply'; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + var imageData = context.getImageData(2,0,1,1); + + if (!imageData) + { + return false; + } + + var data = imageData.data; + + return (data[0] === 255 && data[1] === 0 && data[2] === 0); +}; + + +module.exports = canUseNewCanvasBlendModes; + +},{}],78:[function(require,module,exports){ +var CONST = require('../../../const'), +canUseNewCanvasBlendModes = require('./canUseNewCanvasBlendModes'); + +/** + * Maps blend combinations to Canvas + * @class + * @memberof PIXI + * @param array + */ +function mapCanvasBlendModesToPixi(array) +{ + array = array || []; + + if (canUseNewCanvasBlendModes()) + { + array[CONST.BLEND_MODES.NORMAL] = 'source-over'; + array[CONST.BLEND_MODES.ADD] = 'lighter'; //IS THIS OK??? + array[CONST.BLEND_MODES.MULTIPLY] = 'multiply'; + array[CONST.BLEND_MODES.SCREEN] = 'screen'; + array[CONST.BLEND_MODES.OVERLAY] = 'overlay'; + array[CONST.BLEND_MODES.DARKEN] = 'darken'; + array[CONST.BLEND_MODES.LIGHTEN] = 'lighten'; + array[CONST.BLEND_MODES.COLOR_DODGE] = 'color-dodge'; + array[CONST.BLEND_MODES.COLOR_BURN] = 'color-burn'; + array[CONST.BLEND_MODES.HARD_LIGHT] = 'hard-light'; + array[CONST.BLEND_MODES.SOFT_LIGHT] = 'soft-light'; + array[CONST.BLEND_MODES.DIFFERENCE] = 'difference'; + array[CONST.BLEND_MODES.EXCLUSION] = 'exclusion'; + array[CONST.BLEND_MODES.HUE] = 'hue'; + array[CONST.BLEND_MODES.SATURATION] = 'saturate'; + array[CONST.BLEND_MODES.COLOR] = 'color'; + array[CONST.BLEND_MODES.LUMINOSITY] = 'luminosity'; + } + else + { + // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' + array[CONST.BLEND_MODES.NORMAL] = 'source-over'; + array[CONST.BLEND_MODES.ADD] = 'lighter'; //IS THIS OK??? + array[CONST.BLEND_MODES.MULTIPLY] = 'source-over'; + array[CONST.BLEND_MODES.SCREEN] = 'source-over'; + array[CONST.BLEND_MODES.OVERLAY] = 'source-over'; + array[CONST.BLEND_MODES.DARKEN] = 'source-over'; + array[CONST.BLEND_MODES.LIGHTEN] = 'source-over'; + array[CONST.BLEND_MODES.COLOR_DODGE] = 'source-over'; + array[CONST.BLEND_MODES.COLOR_BURN] = 'source-over'; + array[CONST.BLEND_MODES.HARD_LIGHT] = 'source-over'; + array[CONST.BLEND_MODES.SOFT_LIGHT] = 'source-over'; + array[CONST.BLEND_MODES.DIFFERENCE] = 'source-over'; + array[CONST.BLEND_MODES.EXCLUSION] = 'source-over'; + array[CONST.BLEND_MODES.HUE] = 'source-over'; + array[CONST.BLEND_MODES.SATURATION] = 'source-over'; + array[CONST.BLEND_MODES.COLOR] = 'source-over'; + array[CONST.BLEND_MODES.LUMINOSITY] = 'source-over'; + } + + return array; +} + +module.exports = mapCanvasBlendModesToPixi; + +},{"../../../const":43,"./canUseNewCanvasBlendModes":77}],79:[function(require,module,exports){ + +var CONST = require('../../const'); + +/** + * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged up with textures that are no longer being used. + * + * @class + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} The renderer this manager works for. + */ +function TextureGarbageCollector(renderer) +{ + this.renderer = renderer; + + this.count = 0; + this.checkCount = 0; + this.maxIdle = 60 * 60; + this.checkCountMax = 60 * 10; + + this.mode = CONST.GC_MODES.DEFAULT; +} + +TextureGarbageCollector.prototype.constructor = TextureGarbageCollector; +module.exports = TextureGarbageCollector; + +/** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ +TextureGarbageCollector.prototype.update = function() +{ + this.count++; + + if(this.mode === CONST.GC_MODES.MANUAL) + { + return; + } + + this.checkCount++; + + + if(this.checkCount > this.checkCountMax) + { + this.checkCount = 0; + + this.run(); + } +}; + +/** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ +TextureGarbageCollector.prototype.run = function() +{ + var tm = this.renderer.textureManager; + var managedTextures = tm._managedTextures; + var wasRemoved = false; + var i,j; + + for (i = 0; i < managedTextures.length; i++) + { + var texture = managedTextures[i]; + + // only supports non generated textures at the moment! + if (!texture._glRenderTargets && this.count - texture.touched > this.maxIdle) + { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + + if (wasRemoved) + { + j = 0; + + for (i = 0; i < managedTextures.length; i++) + { + if (managedTextures[i] !== null) + { + managedTextures[j++] = managedTextures[i]; + } + } + + managedTextures.length = j; + } +}; + +/** + * Removes all the textures within the specified displayObject and its children from the GPU + * + * @param displayObject {PIXI.DisplayObject} the displayObject to remove the textures from. + */ +TextureGarbageCollector.prototype.unload = function( displayObject ) +{ + var tm = this.renderer.textureManager; + + if(displayObject._texture) + { + tm.destroyTexture(displayObject._texture, true); + } + + for (var i = displayObject.children.length - 1; i >= 0; i--) { + + this.unload(displayObject.children[i]); + + } +}; + +},{"../../const":43}],80:[function(require,module,exports){ +var GLTexture = require('pixi-gl-core').GLTexture, + CONST = require('../../const'), + RenderTarget = require('./utils/RenderTarget'), + utils = require('../../utils'); + +/** + * Helper class to create a webGL Texture + * + * @class + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} A reference to the current renderer + */ +var TextureManager = function(renderer) +{ + /** + * A reference to the current renderer + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = renderer.gl; + + /** + * Track textures in the renderer so we can no longer listen to them on destruction. + * + * @member {Array<*>} + * @private + */ + this._managedTextures = []; +}; + +TextureManager.prototype.bindTexture = function() +{ +}; + + +TextureManager.prototype.getTexture = function() +{ +}; + +/** + * Updates and/or Creates a WebGL texture for the renderer's context. + * + * @param texture {PIXI.BaseTexture|PIXI.Texture} the texture to update + */ +TextureManager.prototype.updateTexture = function(texture) +{ + texture = texture.baseTexture || texture; + + var isRenderTexture = !!texture._glRenderTargets; + + if (!texture.hasLoaded) + { + return; + } + + var glTexture = texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!glTexture) + { + if(isRenderTexture) + { + var renderTarget = new RenderTarget(this.gl, texture.width, texture.height, texture.scaleMode, texture.resolution); + renderTarget.resize(texture.width, texture.height); + texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget; + glTexture = renderTarget.texture; + } + else + { + glTexture = new GLTexture(this.gl); + glTexture.premultiplyAlpha = true; + glTexture.upload(texture.source); + } + + texture._glTextures[this.renderer.CONTEXT_UID] = glTexture; + + texture.on('update', this.updateTexture, this); + texture.on('dispose', this.destroyTexture, this); + + this._managedTextures.push(texture); + + if(texture.isPowerOfTwo) + { + if(texture.mipmap) + { + glTexture.enableMipmap(); + } + + if(texture.wrapMode === CONST.WRAP_MODES.CLAMP) + { + glTexture.enableWrapClamp(); + } + else if(texture.wrapMode === CONST.WRAP_MODES.REPEAT) + { + glTexture.enableWrapRepeat(); + } + else + { + glTexture.enableWrapMirrorRepeat(); + } + } + else + { + glTexture.enableWrapClamp(); + } + + if(texture.scaleMode === CONST.SCALE_MODES.NEAREST) + { + glTexture.enableNearestScaling(); + } + else + { + glTexture.enableLinearScaling(); + } + } + else + { + // the textur ealrady exists so we only need to update it.. + if(isRenderTexture) + { + texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height); + } + else + { + glTexture.upload(texture.source); + } + } + + return glTexture; +}; + +/** + * Deletes the texture from WebGL + * + * @param texture {PIXI.BaseTexture|PIXI.Texture} the texture to destroy + * @param [skipRemove=false] {boolean} Whether to skip removing the texture from the TextureManager. + */ +TextureManager.prototype.destroyTexture = function(texture, skipRemove) +{ + texture = texture.baseTexture || texture; + + if (!texture.hasLoaded) + { + return; + } + + if (texture._glTextures[this.renderer.CONTEXT_UID]) + { + texture._glTextures[this.renderer.CONTEXT_UID].destroy(); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + + + delete texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!skipRemove) + { + var i = this._managedTextures.indexOf(texture); + if (i !== -1) { + utils.removeItems(this._managedTextures, i, 1); + } + } + } +}; + +/** + * Deletes all the textures from WebGL + */ +TextureManager.prototype.removeAll = function() +{ + // empty all the old gl textures as they are useless now + for (var i = 0; i < this._managedTextures.length; ++i) + { + var texture = this._managedTextures[i]; + if (texture._glTextures[this.renderer.CONTEXT_UID]) + { + delete texture._glTextures[this.renderer.CONTEXT_UID]; + } + } +}; + +/** + * Destroys this manager and removes all its textures + */ +TextureManager.prototype.destroy = function() +{ + // destroy managed textures + for (var i = 0; i < this._managedTextures.length; ++i) + { + var texture = this._managedTextures[i]; + this.destroyTexture(texture, true); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + } + + this._managedTextures = null; +}; + +module.exports = TextureManager; + +},{"../../const":43,"../../utils":116,"./utils/RenderTarget":93,"pixi-gl-core":12}],81:[function(require,module,exports){ +var SystemRenderer = require('../SystemRenderer'), + MaskManager = require('./managers/MaskManager'), + StencilManager = require('./managers/StencilManager'), + FilterManager = require('./managers/FilterManager'), + RenderTarget = require('./utils/RenderTarget'), + ObjectRenderer = require('./utils/ObjectRenderer'), + TextureManager = require('./TextureManager'), + TextureGarbageCollector = require('./TextureGarbageCollector'), + WebGLState = require('./WebGLState'), + createContext = require('pixi-gl-core').createContext, + mapWebGLDrawModesToPixi = require('./utils/mapWebGLDrawModesToPixi'), + validateContext = require('./utils/validateContext'), + utils = require('../../utils'), + glCore = require('pixi-gl-core'), + CONST = require('../../const'); + +var CONTEXT_UID = 0; + +/** + * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + * @param [width=0] {number} the width of the canvas view + * @param [height=0] {number} the height of the canvas view + * @param [options] {object} The optional renderer parameters + * @param [options.view] {HTMLCanvasElement} the canvas to use as a view, optional + * @param [options.transparent=false] {boolean} If the render view is transparent, default false + * @param [options.autoResize=false] {boolean} If the render view is automatically resized, default false + * @param [options.antialias=false] {boolean} sets antialias. If not available natively then FXAA antialiasing is used + * @param [options.forceFXAA=false] {boolean} forces FXAA antialiasing to be used over native. FXAA is faster, but may not always look as great + * @param [options.resolution=1] {number} The resolution / device pixel ratio of the renderer. The resolution of the renderer retina would be 2. + * @param [options.clearBeforeRender=true] {boolean} This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. If you wish to set this to false, you *must* set preserveDrawingBuffer to `true`. + * @param [options.preserveDrawingBuffer=false] {boolean} enables drawing buffer preservation, enable this if + * you need to call toDataUrl on the webgl context. + * @param [options.roundPixels=false] {boolean} If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + */ +function WebGLRenderer(width, height, options) +{ + options = options || {}; + + SystemRenderer.call(this, 'WebGL', width, height, options); + /** + * The type of this renderer as a standardised const + * + * @member {number} + * @see PIXI.RENDERER_TYPE + */ + this.type = CONST.RENDERER_TYPE.WEBGL; + + this.handleContextLost = this.handleContextLost.bind(this); + this.handleContextRestored = this.handleContextRestored.bind(this); + + this.view.addEventListener('webglcontextlost', this.handleContextLost, false); + this.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); + + /** + * The options passed in to create a new webgl context. + * + * @member {object} + * @private + */ + this._contextOptions = { + alpha: this.transparent, + antialias: options.antialias, + premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: options.preserveDrawingBuffer + }; + + this._backgroundColorRgba[3] = this.transparent ? 0 : 1; + + /** + * Manages the masks using the stencil buffer. + * + * @member {PIXI.MaskManager} + */ + this.maskManager = new MaskManager(this); + + /** + * Manages the stencil buffer. + * + * @member {PIXI.StencilManager} + */ + this.stencilManager = new StencilManager(this); + + /** + * An empty renderer. + * + * @member {PIXI.ObjectRenderer} + */ + this.emptyRenderer = new ObjectRenderer(this); + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.ObjectRenderer} + */ + this.currentRenderer = this.emptyRenderer; + + this.initPlugins(); + + /** + * The current WebGL rendering context, it is created here + * + * @member {WebGLRenderingContext} + */ + // initialize the context so it is ready for the managers. + if(options.context) + { + // checks to see if a context is valid.. + validateContext(options.context); + } + + this.gl = options.context || createContext(this.view, this._contextOptions); + + this.CONTEXT_UID = CONTEXT_UID++; + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.WebGLState} + */ + this.state = new WebGLState(this.gl); + + this.renderingToScreen = true; + + + + this._initContext(); + + /** + * Manages the filters. + * + * @member {PIXI.FilterManager} + */ + this.filterManager = new FilterManager(this); + // map some webGL blend and drawmodes.. + this.drawModes = mapWebGLDrawModesToPixi(this.gl); + + + /** + * Holds the current shader + * + * @member {PIXI.Shader} + */ + this._activeShader = null; + + /** + * Holds the current render target + * + * @member {PIXI.RenderTarget} + */ + this._activeRenderTarget = null; + this._activeTextureLocation = 999; + this._activeTexture = null; + + this.setBlendMode(0); + + +} + +// constructor +WebGLRenderer.prototype = Object.create(SystemRenderer.prototype); +WebGLRenderer.prototype.constructor = WebGLRenderer; +module.exports = WebGLRenderer; +utils.pluginTarget.mixin(WebGLRenderer); + +/** + * Creates the WebGL context + * + * @private + */ +WebGLRenderer.prototype._initContext = function () +{ + var gl = this.gl; + + // create a texture manager... + this.textureManager = new TextureManager(this); + this.textureGC = new TextureGarbageCollector(this); + + this.state.resetToDefault(); + + this.rootRenderTarget = new RenderTarget(gl, this.width, this.height, null, this.resolution, true); + this.rootRenderTarget.clearColor = this._backgroundColorRgba; + + + this.bindRenderTarget(this.rootRenderTarget); + + this.emit('context', gl); + + // setup the width/height properties and gl viewport + this.resize(this.width, this.height); +}; + +/** + * Renders the object to its webGL view + * + * @param displayObject {PIXI.DisplayObject} the object to be rendered + * @param renderTexture {PIXI.RenderTexture} + * @param [clear] {boolean} Should the canvas be cleared before the new render + * @param [transform] {PIXI.Transform} + * @param [skipUpdateTransform] {boolean} + */ +WebGLRenderer.prototype.render = function (displayObject, renderTexture, clear, transform, skipUpdateTransform) +{ + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + + // no point rendering if our context has been blown up! + if (!this.gl || this.gl.isContextLost()) + { + return; + } + + if(!renderTexture) + { + this._lastObjectRendered = displayObject; + } + + if(!skipUpdateTransform) + { + // update the scene graph + var cacheParent = displayObject.parent; + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + this.bindRenderTexture(renderTexture, transform); + + this.currentRenderer.start(); + + if(clear !== undefined ? clear : this.clearBeforeRender) + { + this._activeRenderTarget.clear(); + } + + displayObject.renderWebGL(this); + + // apply transform.. + this.currentRenderer.flush(); + + //this.setObjectRenderer(this.emptyRenderer); + + this.textureGC.update(); + + this.emit('postrender'); +}; + +/** + * Changes the current renderer to the one given in parameter + * + * @param objectRenderer {PIXI.ObjectRenderer} The object renderer to use. + */ +WebGLRenderer.prototype.setObjectRenderer = function (objectRenderer) +{ + if (this.currentRenderer === objectRenderer) + { + return; + } + + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); +}; + +/** + * This shoudl be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + * + */ +WebGLRenderer.prototype.flush = function () +{ + this.setObjectRenderer(this.emptyRenderer); +}; + +/** + * Resizes the webGL view to the specified width and height. + * + * @param width {number} the new width of the webGL view + * @param height {number} the new height of the webGL view + */ +WebGLRenderer.prototype.resize = function (width, height) +{ + // if(width * this.resolution === this.width && height * this.resolution === this.height)return; + + SystemRenderer.prototype.resize.call(this, width, height); + + this.rootRenderTarget.resize(width, height); + + if(this._activeRenderTarget === this.rootRenderTarget) + { + this.rootRenderTarget.activate(); + + if(this._activeShader) + { + this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true); + } + } +}; + +/** + * Resizes the webGL view to the specified width and height. + * + * @param blendMode {number} the desired blend mode + */ +WebGLRenderer.prototype.setBlendMode = function (blendMode) +{ + this.state.setBlendMode(blendMode); +}; + +/** + * Erases the active render target and fills the drawing area with a colour + * + * @param [clearColor] {number} The colour + */ +WebGLRenderer.prototype.clear = function (clearColor) +{ + this._activeRenderTarget.clear(clearColor); +}; + +/** + * Sets the transform of the active render target to the given matrix + * + * @param matrix {PIXI.Matrix} The transformation matrix + */ +WebGLRenderer.prototype.setTransform = function (matrix) +{ + this._activeRenderTarget.transform = matrix; +}; + + +/** + * Binds a render texture for rendering + * + * @param renderTexture {PIXI.RenderTexture} The render texture to render + * @param transform {PIXI.Transform} The transform to be applied to the render texture + */ +WebGLRenderer.prototype.bindRenderTexture = function (renderTexture, transform) +{ + var renderTarget; + + if(renderTexture) + { + var baseTexture = renderTexture.baseTexture; + var gl = this.gl; + + if(!baseTexture._glRenderTargets[this.CONTEXT_UID]) + { + + this.textureManager.updateTexture(baseTexture); + gl.bindTexture(gl.TEXTURE_2D, null); + } + else + { + // the texture needs to be unbound if its being rendererd too.. + this._activeTextureLocation = baseTexture._id; + gl.activeTexture(gl.TEXTURE0 + baseTexture._id); + gl.bindTexture(gl.TEXTURE_2D, null); + } + + + renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + renderTarget.setFrame(renderTexture.frame); + } + else + { + renderTarget = this.rootRenderTarget; + } + + renderTarget.transform = transform; + this.bindRenderTarget(renderTarget); + + return this; +}; + +/** + * Changes the current render target to the one given in parameter + * + * @param renderTarget {PIXI.RenderTarget} the new render target + */ +WebGLRenderer.prototype.bindRenderTarget = function (renderTarget) +{ + if(renderTarget !== this._activeRenderTarget) + { + this._activeRenderTarget = renderTarget; + renderTarget.activate(); + + if(this._activeShader) + { + this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true); + } + + + this.stencilManager.setMaskStack( renderTarget.stencilMaskStack ); + } + + return this; +}; + +/** + * Changes the current shader to the one given in parameter + * + * @param shader {PIXI.Shader} the new shader + */ +WebGLRenderer.prototype.bindShader = function (shader) +{ + //TODO cache + if(this._activeShader !== shader) + { + this._activeShader = shader; + shader.bind(); + + // automatically set the projection matrix + shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(true); + } + + return this; +}; + +/** + * Binds the texture ... @mat + * + * @param texture {PIXI.Texture} the new texture + * @param location {number} the texture location + */ +WebGLRenderer.prototype.bindTexture = function (texture, location) +{ + texture = texture.baseTexture || texture; + + var gl = this.gl; + + //TODO test perf of cache? + location = location || 0; + + if(this._activeTextureLocation !== location)// + { + this._activeTextureLocation = location; + gl.activeTexture(gl.TEXTURE0 + location ); + } + + //TODO - can we cache this texture too? + this._activeTexture = texture; + + if (!texture._glTextures[this.CONTEXT_UID]) + { + // this will also bind the texture.. + this.textureManager.updateTexture(texture); + + } + else + { + texture.touched = this.textureGC.count; + // bind the current texture + texture._glTextures[this.CONTEXT_UID].bind(); + } + + return this; +}; + +WebGLRenderer.prototype.createVao = function () +{ + return new glCore.VertexArrayObject(this.gl, this.state.attribState); +}; + +/** + * Resets the WebGL state so you can render things however you fancy! + */ +WebGLRenderer.prototype.reset = function () +{ + this.setObjectRenderer(this.emptyRenderer); + + this._activeShader = null; + this._activeRenderTarget = this.rootRenderTarget; + this._activeTextureLocation = 999; + this._activeTexture = null; + + // bind the main frame buffer (the screen); + this.rootRenderTarget.activate(); + + this.state.resetToDefault(); + + return this; +}; + +/** + * Handles a lost webgl context + * + * @private + */ +WebGLRenderer.prototype.handleContextLost = function (event) +{ + event.preventDefault(); +}; + +/** + * Handles a restored webgl context + * + * @private + */ +WebGLRenderer.prototype.handleContextRestored = function () +{ + this._initContext(); + this.textureManager.removeAll(); +}; + +/** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @param [removeView=false] {boolean} Removes the Canvas element from the DOM. https://github.com/pixijs/pixi.js/issues/2233 + */ +WebGLRenderer.prototype.destroy = function (removeView) +{ + this.destroyPlugins(); + + // remove listeners + this.view.removeEventListener('webglcontextlost', this.handleContextLost); + this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); + + this.textureManager.destroy(); + + // call base destroy + SystemRenderer.prototype.destroy.call(this, removeView); + + this.uid = 0; + + // destroy the managers + this.maskManager.destroy(); + this.stencilManager.destroy(); + this.filterManager.destroy(); + + this.maskManager = null; + this.filterManager = null; + this.textureManager = null; + this.currentRenderer = null; + + this.handleContextLost = null; + this.handleContextRestored = null; + + this._contextOptions = null; + this.gl.useProgram(null); + + if(this.gl.getExtension('WEBGL_lose_context')) + { + this.gl.getExtension('WEBGL_lose_context').loseContext(); + } + + this.gl = null; + + // this = null; +}; + +},{"../../const":43,"../../utils":116,"../SystemRenderer":73,"./TextureGarbageCollector":79,"./TextureManager":80,"./WebGLState":82,"./managers/FilterManager":87,"./managers/MaskManager":88,"./managers/StencilManager":89,"./utils/ObjectRenderer":91,"./utils/RenderTarget":93,"./utils/mapWebGLDrawModesToPixi":96,"./utils/validateContext":97,"pixi-gl-core":12}],82:[function(require,module,exports){ +var mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); + +/** + * A WebGL state machines + * + * @memberof PIXI + * @class + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function WebGLState(gl) +{ + /** + * The current active state + * + * @member {Uint8Array} + */ + this.activeState = new Uint8Array(16); + + /** + * The default state + * + * @member {Uint8Array} + */ + this.defaultState = new Uint8Array(16); + + // default blend mode.. + this.defaultState[0] = 1; + + /** + * The current state index in the stack + * + * @member {number} + * @private + */ + this.stackIndex = 0; + + /** + * The stack holding all the different states + * + * @member {Array<*>} + * @private + */ + this.stack = []; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + this.attribState = {tempAttribState:new Array(this.maxAttribs), + attribState:new Array(this.maxAttribs)}; + + this.blendModes = mapWebGLBlendModesToPixi(gl); + + // check we have vao.. + this.nativeVaoExtension = ( + gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object') + ); +} + +/** + * Pushes a new active state + */ +WebGLState.prototype.push = function() +{ + // next state.. + var state = this.stack[++this.stackIndex]; + + if(!state) + { + state = this.stack[this.stackIndex] = new Uint8Array(16); + } + + // copy state.. + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) + { + this.activeState[i] = state[i]; + } +}; + +var BLEND = 0, + DEPTH_TEST = 1, + FRONT_FACE = 2, + CULL_FACE = 3, + BLEND_FUNC = 4; + +/** + * Pops a state out + */ +WebGLState.prototype.pop = function() +{ + var state = this.stack[--this.stackIndex]; + this.setState(state); +}; + +/** + * Sets the current state + * @param state {number} + */ +WebGLState.prototype.setState = function(state) +{ + this.setBlend(state[BLEND]); + this.setDepthTest(state[DEPTH_TEST]); + this.setFrontFace(state[FRONT_FACE]); + this.setCullFace(state[CULL_FACE]); + this.setBlendMode(state[BLEND_FUNC]); +}; + +/** + * Sets the blend mode ? @mat + * @param value {number} + */ +WebGLState.prototype.setBlend = function(value) +{ + if(this.activeState[BLEND] === value|0) { + return; + } + + this.activeState[BLEND] = value|0; + + var gl = this.gl; + + if(value) + { + gl.enable(gl.BLEND); + } + else + { + gl.disable(gl.BLEND); + } +}; + +/** + * Sets the blend mode ? @mat + * @param value {number} + */ +WebGLState.prototype.setBlendMode = function(value) +{ + if(value === this.activeState[BLEND_FUNC]) { + return; + } + + this.activeState[BLEND_FUNC] = value; + + this.gl.blendFunc(this.blendModes[value][0], this.blendModes[value][1]); +}; + +/** + * Sets the depth test @mat + * @param value {number} + */ +WebGLState.prototype.setDepthTest = function(value) +{ + if(this.activeState[DEPTH_TEST] === value|0) { + return; + } + + this.activeState[DEPTH_TEST] = value|0; + + var gl = this.gl; + + if(value) + { + gl.enable(gl.DEPTH_TEST); + } + else + { + gl.disable(gl.DEPTH_TEST); + } +}; + +/** + * Sets the depth test @mat + * @param value {number} + */ +WebGLState.prototype.setCullFace = function(value) +{ + if(this.activeState[CULL_FACE] === value|0) { + return; + } + + this.activeState[CULL_FACE] = value|0; + + var gl = this.gl; + + if(value) + { + gl.enable(gl.CULL_FACE); + } + else + { + gl.disable(gl.CULL_FACE); + } +}; + +/** + * Sets the depth test @mat + * @param value {number} + */ +WebGLState.prototype.setFrontFace = function(value) +{ + if(this.activeState[FRONT_FACE] === value|0) { + return; + } + + this.activeState[FRONT_FACE] = value|0; + + var gl = this.gl; + + if(value) + { + gl.frontFace(gl.CW); + } + else + { + gl.frontFace(gl.CCW); + } +}; + +/** + * Disables all the vaos in use + */ +WebGLState.prototype.resetAttributes = function() +{ + var i; + + for ( i = 0; i < this.attribState.tempAttribState.length; i++) { + this.attribState.tempAttribState[i] = 0; + } + + for ( i = 0; i < this.attribState.attribState.length; i++) { + this.attribState.attribState[i] = 0; + } + + var gl = this.gl; + + // im going to assume one is always active for performance reasons. + for (i = 1; i < this.maxAttribs; i++) + { + gl.disableVertexAttribArray(i); + } +}; + +//used +/** + * Resets all the logic and disables the vaos + */ +WebGLState.prototype.resetToDefault = function() +{ + + // unbind any VAO if they exist.. + if(this.nativeVaoExtension) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + + // reset all attributs.. + this.resetAttributes(); + + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) + { + this.activeState[i] = 32; + } + + var gl = this.gl; + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); + + + this.setState(this.defaultState); +}; + +module.exports = WebGLState; + +},{"./utils/mapWebGLBlendModesToPixi":95}],83:[function(require,module,exports){ +var extractUniformsFromSrc = require('./extractUniformsFromSrc'), + utils = require('../../../utils'), + CONST = require('../../../const'), + SOURCE_KEY_MAP = {}; + +// var math = require('../../../math'); +/** + * @class + * @memberof PIXI + * @extends PIXI.Shader + * @param [vertexSrc] {string} The source of the vertex shader. + * @param [uniforms] {object} Custom uniforms to use to augment the built-in ones. + * @param [fragmentSrc] {string} The source of the fragment shader. + */ +function Filter(vertexSrc, fragmentSrc, uniforms) +{ + + /** + * The vertex shader. + * + * @member {string} + */ + this.vertexSrc = vertexSrc || Filter.defaultVertexSrc; + + /** + * The fragment shader. + * + * @member {string} + */ + this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc; + + this.blendMode = CONST.BLEND_MODES.NORMAL; + + // pull out the vertex and shader uniforms if they are not specified.. + // currently this does not extract structs only default types + this.uniformData = uniforms || extractUniformsFromSrc( this.vertexSrc, this.fragmentSrc, 'projectionMatrix|uSampler'); + + this.uniforms = {}; + + for (var i in this.uniformData) + { + this.uniforms[i] = this.uniformData[i].value; + } + + // this is where we store shader references.. + // TODO we could cache this! + this.glShaders = []; + + // used for cacheing.. sure there is a better way! + if(!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) + { + SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = utils.uid(); + } + + this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]; + + /** + * The padding of the filter. Some filters require extra space to breath such as a blur. Increasing this will add extra width and height to the bounds of the object that the filter is applied to. + */ + this.padding = 4; + + /** + * The resolution of the filter. Setting this to be lower will lower the quality but increase the performance of the filter. + * @member {number} + */ + this.resolution = 1; + + /** + * If enabled is true the filter is applied, if false it will not. + * @member {boolean} + */ + this.enabled = true; +} + +// constructor +//Filter.prototype.constructor = Filter; +module.exports = Filter; + +// var tempMatrix = new math.Matrix(); + +Filter.prototype.apply = function(filterManager, input, output, clear) +{ + // --- // + // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); + + // do as you please! + + filterManager.applyFilter(this, input, output, clear); + + // or just do a regular render.. +}; + +/** + * The default vertex shader source + * + * @static + * @constant + */ +Filter.defaultVertexSrc = [ + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + + 'uniform mat3 projectionMatrix;', + 'uniform mat3 filterMatrix;', + + 'varying vec2 vTextureCoord;', + 'varying vec2 vFilterCoord;', + + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;', + ' vTextureCoord = aTextureCoord ;', + '}' +].join('\n'); + +/** + * The default fragment shader source + * + * @static + * @constant + */ +Filter.defaultFragmentSrc = [ + 'varying vec2 vTextureCoord;', + 'varying vec2 vFilterCoord;', + + 'uniform sampler2D uSampler;', + 'uniform sampler2D filterSampler;', + + 'void main(void){', + ' vec4 masky = texture2D(filterSampler, vFilterCoord);', + ' vec4 sample = texture2D(uSampler, vTextureCoord);', + ' vec4 color;', + ' if(mod(vFilterCoord.x, 1.0) > 0.5)', + ' {', + ' color = vec4(1.0, 0.0, 0.0, 1.0);', + ' }', + ' else', + ' {', + ' color = vec4(0.0, 1.0, 0.0, 1.0);', + ' }', + // ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', + ' gl_FragColor = mix(sample, masky, 0.5);', + ' gl_FragColor *= sample.a;', + '}' +].join('\n'); + +},{"../../../const":43,"../../../utils":116,"./extractUniformsFromSrc":84}],84:[function(require,module,exports){ +var defaultValue = require('pixi-gl-core').shader.defaultValue; + +function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) +{ + var vertUniforms = extractUniformsFromString(vertexSrc, mask); + var fragUniforms = extractUniformsFromString(fragmentSrc, mask); + + return Object.assign(vertUniforms, fragUniforms); +} + + +function extractUniformsFromString(string) +{ + var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea)$'); + + var uniforms = {}; + var nameSplit; + + + // clean the lines a little - remove extra spaces / teabs etc + // then split along ';' + var lines = string.replace(/\s+/g,' ') + .split(/\s*;\s*/); + + // loop through.. + for (var i = 0; i < lines.length; i++) + { + var line = lines[i].trim(); + + if(line.indexOf('uniform') > -1) + { + var splitLine = line.split(' '); + var type = splitLine[1]; + + var name = splitLine[2]; + var size = 1; + + if(name.indexOf('[') > -1) + { + // array! + nameSplit = name.split(/\[|\]/); + name = nameSplit[0]; + size *= Number(nameSplit[1]); + } + + if(!name.match(maskRegex)) + { + uniforms[name] = { + value:defaultValue(type, size), + name:name, + type:type + }; + } + } + } + + return uniforms; +} + +module.exports = extractUniformsFromSrc; + +},{"pixi-gl-core":12}],85:[function(require,module,exports){ +var math = require('../../../math'); + +/* + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// thia returns a matrix that will normalise map filter cords in the filter to screen space +var calculateScreenSpaceMatrix = function (outputMatrix, filterArea, textureSize) +{ + //var worldTransform = sprite.worldTransform.copy(math.Matrix.TEMP_MATRIX), + // var texture = {width:1136, height:700};//sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height ); + + mappedMatrix.scale( textureSize.width , textureSize.height ); + + return mappedMatrix; + +}; + +var calculateNormalizedScreenSpaceMatrix = function (outputMatrix, filterArea, textureSize) +{ + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height ); + + var translateScaleX = (textureSize.width / filterArea.width); + var translateScaleY = (textureSize.height / filterArea.height); + + mappedMatrix.scale( translateScaleX , translateScaleY ); + + return mappedMatrix; +}; + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +var calculateSpriteMatrix = function (outputMatrix, filterArea, textureSize, sprite) +{ + var worldTransform = sprite.worldTransform.copy(math.Matrix.TEMP_MATRIX), + texture = sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + // scale.. + var ratio = textureSize.height / textureSize.width; + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height ); + + mappedMatrix.scale(1 , ratio); + + var translateScaleX = (textureSize.width / texture.width); + var translateScaleY = (textureSize.height / texture.height); + + worldTransform.tx /= texture.width * translateScaleX; + + //this...? free beer for anyone who can explain why this makes sense! + worldTransform.ty /= texture.width * translateScaleX; + // worldTransform.ty /= texture.height * translateScaleY; + + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + + // apply inverse scale.. + mappedMatrix.scale(1 , 1/ratio); + + mappedMatrix.scale( translateScaleX , translateScaleY ); + + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; +}; + +module.exports = { + calculateScreenSpaceMatrix:calculateScreenSpaceMatrix, + calculateNormalizedScreenSpaceMatrix:calculateNormalizedScreenSpaceMatrix, + calculateSpriteMatrix:calculateSpriteMatrix +}; + +},{"../../../math":67}],86:[function(require,module,exports){ +var Filter = require('../Filter'), + math = require('../../../../math'); + +// @see https://github.com/substack/brfs/issues/25 + +/** + * The SpriteMaskFilter class + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + * @param sprite {PIXI.Sprite} the target sprite + */ +function SpriteMaskFilter(sprite) +{ + var maskMatrix = new math.Matrix(); + + Filter.call(this, + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n", + "#define GLSLIFY 1\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n original *= (masky.r * masky.a * alpha * clip);\n gl_FragColor = original;\n}\n" + ); + + sprite.renderable = false; + + this.maskSprite = sprite; + this.maskMatrix = maskMatrix; +} + +SpriteMaskFilter.prototype = Object.create(Filter.prototype); +SpriteMaskFilter.prototype.constructor = SpriteMaskFilter; +module.exports = SpriteMaskFilter; + +/** + * Applies the filter + * + * @param filterManager {PIXI.FilterManager} The renderer to retrieve the filter from + * @param input {PIXI.RenderTarget} + * @param output {PIXI.RenderTarget} + */ +SpriteMaskFilter.prototype.apply = function (filterManager, input, output) +{ + var maskSprite = this.maskSprite; + + this.uniforms.mask = maskSprite._texture; + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite ); + this.uniforms.alpha = maskSprite.worldAlpha; + + filterManager.applyFilter(this, input, output); +}; + +},{"../../../../math":67,"../Filter":83}],87:[function(require,module,exports){ + +var WebGLManager = require('./WebGLManager'), + RenderTarget = require('../utils/RenderTarget'), + Quad = require('../utils/Quad'), + math = require('../../../math'), + Shader = require('../../../Shader'), + filterTransforms = require('../filters/filterTransforms'), + bitTwiddle = require('bit-twiddle'); + +var FilterState = function() +{ + this.renderTarget = null; + this.sourceFrame = new math.Rectangle(); + this.destinationFrame = new math.Rectangle(); + this.filters = []; + this.target = null; + this.resolution = 1; +}; + + +/** + * @class + * @memberof PIXI + * @extends PIXI.WebGLManager + * @param renderer {PIXI.WebGLRenderer} The renderer this manager works for. + */ +function FilterManager(renderer) +{ + WebGLManager.call(this, renderer); + + this.gl = this.renderer.gl; + // know about sprites! + this.quad = new Quad(this.gl, renderer.state.attribState); + + this.shaderCache = {}; + // todo add default! + this.pool = {}; + + this.filterData = null; +} + +FilterManager.prototype = Object.create(WebGLManager.prototype); +FilterManager.prototype.constructor = FilterManager; +module.exports = FilterManager; + +FilterManager.prototype.pushFilter = function(target, filters) +{ + var renderer = this.renderer; + + var filterData = this.filterData; + + if(!filterData) + { + filterData = this.renderer._activeRenderTarget.filterStack; + + // add new stack + var filterState = new FilterState(); + filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; + filterState.renderTarget = renderer._activeRenderTarget; + + this.renderer._activeRenderTarget.filterData = filterData = { + index:0, + stack:[filterState] + }; + + this.filterData = filterData; + } + + // get the current filter state.. + var currentState = filterData.stack[++filterData.index]; + if(!currentState) + { + currentState = filterData.stack[filterData.index] = new FilterState(); + } + + // for now we go off the filter of the first resolution.. + var resolution = filters[0].resolution; + var padding = filters[0].padding; + var targetBounds = target.filterArea || target.getBounds(true); + var sourceFrame = currentState.sourceFrame; + var destinationFrame = currentState.destinationFrame; + + sourceFrame.x = ((targetBounds.x * resolution) | 0) / resolution; + sourceFrame.y = ((targetBounds.y * resolution) | 0) / resolution; + sourceFrame.width = ((targetBounds.width * resolution) | 0) / resolution; + sourceFrame.height = ((targetBounds.height * resolution) | 0) / resolution; + + if(filterData.stack[0].renderTarget.transform) + {//jshint ignore:line + + + } + else + { + sourceFrame.fit(filterData.stack[0].destinationFrame); + } + + // lets pplay the padding After we fit the element to the screen. + // this should stop the strange side effects that can occour when cropping to the edges + sourceFrame.pad(padding); + + + + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + + var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); + + currentState.target = target; + currentState.filters = filters; + currentState.resolution = resolution; + currentState.renderTarget = renderTarget; + + // bind the render taget to draw the shape in the top corner.. + + renderTarget.setFrame(destinationFrame, sourceFrame); + // bind the render target + renderer.bindRenderTarget(renderTarget); + + // clear the renderTarget + renderer.clear();//[0.5,0.5,0.5, 1.0]); +}; + +FilterManager.prototype.popFilter = function() +{ + var filterData = this.filterData; + + var lastState = filterData.stack[filterData.index-1]; + var currentState = filterData.stack[filterData.index]; + + this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); + + var filters = currentState.filters; + + if(filters.length === 1) + { + filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false); + this.freePotRenderTarget(currentState.renderTarget); + } + else + { + var flip = currentState.renderTarget; + var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, 1); + flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + for (var i = 0; i < filters.length-1; i++) + { + filters[i].apply(this, flip, flop, true); + + var t = flip; + flip = flop; + flop = t; + } + + filters[i].apply(this, flip, lastState.renderTarget, false); + + this.freePotRenderTarget(flip); + this.freePotRenderTarget(flop); + } + + filterData.index--; + + if(filterData.index === 0) + { + this.filterData = null; + } +}; + +FilterManager.prototype.applyFilter = function (filter, input, output, clear) +{ + var renderer = this.renderer; + var shader = filter.glShaders[renderer.CONTEXT_UID]; + + // cacheing.. + if(!shader) + { + if(filter.glShaderKey) + { + shader = this.shaderCache[filter.glShaderKey]; + + if(!shader) + { + shader = filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = new Shader(this.gl, filter.vertexSrc, filter.fragmentSrc); + } + } + else + { + shader = filter.glShaders[renderer.CONTEXT_UID] = new Shader(this.gl, filter.vertexSrc, filter.fragmentSrc); + } + + //TODO - this only needs to be done once? + this.quad.initVao(shader); + } + + renderer.bindRenderTarget(output); + + + + if(clear) + { + var gl = renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + renderer.clear();//[1, 1, 1, 1]); + gl.enable(gl.SCISSOR_TEST); + } + + // in case the render target is being masked using a scissor rect + if(output === renderer.maskManager.scissorRenderTarget) + { + renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); + } + + renderer.bindShader(shader); + + // this syncs the pixi filters uniforms with glsl uniforms + this.syncUniforms(shader, filter); + + // bind the input texture.. + input.texture.bind(0); + // when you manually bind a texture, please switch active texture location to it + renderer._activeTextureLocation = 0; + + renderer.state.setBlendMode( filter.blendMode ); + + this.quad.draw(); +}; + +// this returns a matrix that will normalise map filter cords in the filter to screen space +FilterManager.prototype.syncUniforms = function (shader, filter) +{ + var uniformData = filter.uniformData; + var uniforms = filter.uniforms; + + // 0 is reserverd for the pixi texture so we start at 1! + var textureCount = 1; + var currentState; + + if(shader.uniforms.data.filterArea) + { + currentState = this.filterData.stack[this.filterData.index]; + var filterArea = shader.uniforms.filterArea; + + filterArea[0] = currentState.renderTarget.size.width; + filterArea[1] = currentState.renderTarget.size.height; + filterArea[2] = currentState.sourceFrame.x; + filterArea[3] = currentState.sourceFrame.y; + + shader.uniforms.filterArea = filterArea; + } + + // use this to clamp displaced texture coords so they belong to filterArea + // see displacementFilter fragment shader for an example + if(shader.uniforms.data.filterClamp) + { + currentState = this.filterData.stack[this.filterData.index]; + var filterClamp = shader.uniforms.filterClamp; + + filterClamp[0] = 0.5 / currentState.renderTarget.size.width; + filterClamp[1] = 0.5 / currentState.renderTarget.size.height; + filterClamp[2] = (currentState.sourceFrame.width - 0.5) / currentState.renderTarget.size.width; + filterClamp[3] = (currentState.sourceFrame.height - 0.5) / currentState.renderTarget.size.height; + + shader.uniforms.filterClamp = filterClamp; + } + + var val; + //TODO Cacheing layer.. + for(var i in uniformData) + { + if(uniformData[i].type === 'sampler2D') + { + shader.uniforms[i] = textureCount; + + if(uniforms[i].baseTexture) + { + this.renderer.bindTexture(uniforms[i].baseTexture, textureCount); + } + else + { + // this is helpful as renderTargets can also be set. + // Although thinking about it, we could probably + // make the filter texture cache return a RenderTexture + // rather than a renderTarget + var gl = this.renderer.gl; + this.renderer._activeTextureLocation = gl.TEXTURE0 + textureCount; + gl.activeTexture(gl.TEXTURE0 + textureCount ); + uniforms[i].texture.bind(); + } + + textureCount++; + } + else if(uniformData[i].type === 'mat3') + { + // check if its pixi matrix.. + if(uniforms[i].a !== undefined) + { + shader.uniforms[i] = uniforms[i].toArray(true); + } + else + { + shader.uniforms[i] = uniforms[i]; + } + } + else if(uniformData[i].type === 'vec2') + { + //check if its a point.. + if(uniforms[i].x !== undefined) + { + val = shader.uniforms[i] || new Float32Array(2); + val[0] = uniforms[i].x; + val[1] = uniforms[i].y; + shader.uniforms[i] = val; + } + else + { + shader.uniforms[i] = uniforms[i]; + } + } + else if(uniformData[i].type === 'float') + { + if(shader.uniforms.data[i].value !== uniformData[i]) + { + shader.uniforms[i] = uniforms[i]; + } + } + else + { + shader.uniforms[i] = uniforms[i]; + } + } +}; + + +FilterManager.prototype.getRenderTarget = function(clear, resolution) +{ + var currentState = this.filterData.stack[this.filterData.index]; + var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution); + renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + return renderTarget; +}; + +FilterManager.prototype.returnRenderTarget = function(renderTarget) +{ + return this.freePotRenderTarget(renderTarget); +}; + +/* + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// thia returns a matrix that will normalise map filter cords in the filter to screen space +FilterManager.prototype.calculateScreenSpaceMatrix = function (outputMatrix) +{ + var currentState = this.filterData.stack[this.filterData.index]; + return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); +}; + +/** + * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea + * + * @param outputMatrix {PIXI.Matrix} + */ +FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function (outputMatrix) +{ + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); +}; + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +FilterManager.prototype.calculateSpriteMatrix = function (outputMatrix, sprite) +{ + var currentState = this.filterData.stack[this.filterData.index]; + return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); +}; + +FilterManager.prototype.destroy = function() +{ + this.shaderCache = []; + this.emptyPool(); +}; + + + +//TODO move to a seperate class could be on renderer? +//also - could cause issue with multiple contexts? +FilterManager.prototype.getPotRenderTarget = function(gl, minWidth, minHeight, resolution) +{ + //TODO you coud return a bigger texture if there is not one in the pool? + minWidth = bitTwiddle.nextPow2(minWidth * resolution); + minHeight = bitTwiddle.nextPow2(minHeight * resolution); + + var key = ((minWidth & 0xFFFF) << 16) | ( minHeight & 0xFFFF); + + if(!this.pool[key]) { + this.pool[key] = []; + } + + var renderTarget = this.pool[key].pop() || new RenderTarget(gl, minWidth, minHeight, null, 1); + + //manually tweak the resolution... + //this will not modify the size of the frame buffer, just its resolution. + renderTarget.resolution = resolution; + renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution; + renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution; + return renderTarget; +}; + +FilterManager.prototype.emptyPool = function() +{ + for (var i in this.pool) + { + var textures = this.pool[i]; + if(textures) + { + for (var j = 0; j < textures.length; j++) + { + textures[j].destroy(true); + } + } + } + + this.pool = {}; +}; + +FilterManager.prototype.freePotRenderTarget = function(renderTarget) +{ + var minWidth = renderTarget.size.width * renderTarget.resolution; + var minHeight = renderTarget.size.height * renderTarget.resolution; + + var key = ((minWidth & 0xFFFF) << 16) | (minHeight & 0xFFFF); + this.pool[key].push(renderTarget); +}; + +},{"../../../Shader":42,"../../../math":67,"../filters/filterTransforms":85,"../utils/Quad":92,"../utils/RenderTarget":93,"./WebGLManager":90,"bit-twiddle":1}],88:[function(require,module,exports){ +var WebGLManager = require('./WebGLManager'), + AlphaMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); + +/** + * @class + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} The renderer this manager works for. + */ +function MaskManager(renderer) +{ + WebGLManager.call(this, renderer); + + //TODO - we don't need both! + this.scissor = false; + this.scissorData = null; + this.scissorRenderTarget = null; + + this.enableScissor = true; + + this.alphaMaskPool = []; + this.alphaMaskIndex = 0; +} + +MaskManager.prototype = Object.create(WebGLManager.prototype); +MaskManager.prototype.constructor = MaskManager; +module.exports = MaskManager; + +/** + * Applies the Mask and adds it to the current filter stack. + * + * @param target {PIXI.DisplayObject} Display Object to push the mask to + * @param maskData {PIXI.Sprite|PIXI.Graphics} + */ +MaskManager.prototype.pushMask = function (target, maskData) +{ + if (maskData.texture) + { + this.pushSpriteMask(target, maskData); + } + else + { + if(this.enableScissor && !this.scissor && !this.renderer.stencilManager.stencilMaskStack.length && maskData.isFastRect()) + { + var matrix = maskData.worldTransform; + + var rot = Math.atan2(matrix.b, matrix.a); + + // use the nearest degree! + rot = Math.round(rot * (180/Math.PI)); + + if(rot % 90) + { + this.pushStencilMask(maskData); + } + else + { + this.pushScissorMask(target, maskData); + } + } + else + { + this.pushStencilMask(maskData); + } + } +}; + +/** + * Removes the last mask from the mask stack and doesn't return it. + * + * @param target {PIXI.DisplayObject} Display Object to pop the mask from + * @param maskData {Array<*>} + */ +MaskManager.prototype.popMask = function (target, maskData) +{ + if (maskData.texture) + { + this.popSpriteMask(target, maskData); + } + else + { + if(this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length) + { + this.popScissorMask(target, maskData); + } + else + { + this.popStencilMask(target, maskData); + } + + } +}; + +/** + * Applies the Mask and adds it to the current filter stack. + * + * @param target {PIXI.RenderTarget} Display Object to push the sprite mask to + * @param maskData {PIXI.Sprite} Sprite to be used as the mask + */ +MaskManager.prototype.pushSpriteMask = function (target, maskData) +{ + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + + if (!alphaMaskFilter) + { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new AlphaMaskFilter(maskData)]; + } + + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskData; + + //TODO - may cause issues! + target.filterArea = maskData.getBounds(true); + + this.renderer.filterManager.pushFilter(target, alphaMaskFilter); + + this.alphaMaskIndex++; +}; + +/** + * Removes the last filter from the filter stack and doesn't return it. + * + */ +MaskManager.prototype.popSpriteMask = function () +{ + this.renderer.filterManager.popFilter(); + this.alphaMaskIndex--; +}; + + +/** + * Applies the Mask and adds it to the current filter stack. + * + * @param maskData {Array<*>} + */ +MaskManager.prototype.pushStencilMask = function (maskData) +{ + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.pushStencil(maskData); +}; + +/** + * Removes the last filter from the filter stack and doesn't return it. + * + */ +MaskManager.prototype.popStencilMask = function () +{ + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.popStencil(); +}; + +/** + * + * @param target {PIXI.RenderTarget} Display Object to push the scissor mask to + * @param maskData + */ +MaskManager.prototype.pushScissorMask = function (target, maskData) +{ + maskData.renderable = true; + + var renderTarget = this.renderer._activeRenderTarget; + + var bounds = maskData.getBounds(); + + bounds.fit(renderTarget.size); + maskData.renderable = false; + + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + + var resolution = this.renderer.resolution; + this.renderer.gl.scissor(bounds.x * resolution, + (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution, + bounds.width * resolution, + bounds.height * resolution); + + this.scissorRenderTarget = renderTarget; + this.scissorData = maskData; + this.scissor = true; +}; + +/** + * + * + */ +MaskManager.prototype.popScissorMask = function () +{ + this.scissorRenderTarget = null; + this.scissorData = null; + this.scissor = false; + + // must be scissor! + var gl = this.renderer.gl; + gl.disable(gl.SCISSOR_TEST); +}; + +},{"../filters/spriteMask/SpriteMaskFilter":86,"./WebGLManager":90}],89:[function(require,module,exports){ +var WebGLManager = require('./WebGLManager'); + +/** + * @class + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} The renderer this manager works for. + */ +function StencilManager(renderer) +{ + WebGLManager.call(this, renderer); + this.stencilMaskStack = null; +} + +StencilManager.prototype = Object.create(WebGLManager.prototype); +StencilManager.prototype.constructor = StencilManager; +module.exports = StencilManager; + +/** + * Changes the mask stack that is used by this manager. + * + * @param stencilMaskStack {PIXI.Graphics[]} The mask stack + */ +StencilManager.prototype.setMaskStack = function ( stencilMaskStack ) +{ + this.stencilMaskStack = stencilMaskStack; + + var gl = this.renderer.gl; + + if (stencilMaskStack.length === 0) + { + gl.disable(gl.STENCIL_TEST); + } + else + { + gl.enable(gl.STENCIL_TEST); + } +}; + +/** + * Applies the Mask and adds it to the current filter stack. @alvin + * + * @param graphics {PIXI.Graphics} + */ +StencilManager.prototype.pushStencil = function (graphics) +{ + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + this.renderer._activeRenderTarget.attachStencilBuffer(); + + var gl = this.renderer.gl, + sms = this.stencilMaskStack; + + if (sms.length === 0) + { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.stencilFunc(gl.ALWAYS,1,1); + } + + sms.push(graphics); + + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL,0, sms.length); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); +}; + +/** + * TODO @alvin + */ +StencilManager.prototype.popStencil = function () +{ + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + var gl = this.renderer.gl, + sms = this.stencilMaskStack; + + var graphics = sms.pop(); + + if (sms.length === 0) + { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + } + else + { + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); + } +}; + +/** + * Destroys the mask stack. + * + */ +StencilManager.prototype.destroy = function () +{ + WebGLManager.prototype.destroy.call(this); + + this.stencilMaskStack.stencilStack = null; +}; + +},{"./WebGLManager":90}],90:[function(require,module,exports){ +/** + * @class + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} The renderer this manager works for. + */ +function WebGLManager(renderer) +{ + /** + * The renderer this manager works for. + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + this.renderer.on('context', this.onContextChange, this); +} + +WebGLManager.prototype.constructor = WebGLManager; +module.exports = WebGLManager; + +/** + * Generic method called when there is a WebGL context change. + * + */ +WebGLManager.prototype.onContextChange = function () +{ + // do some codes init! +}; + +/** + * Generic destroy methods to be overridden by the subclass + * + */ +WebGLManager.prototype.destroy = function () +{ + this.renderer.off('context', this.onContextChange, this); + + this.renderer = null; +}; + +},{}],91:[function(require,module,exports){ +var WebGLManager = require('../managers/WebGLManager'); + +/** + * Base for a common object renderer that can be used as a system renderer plugin. + * + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} The renderer this object renderer works for. + */ +function ObjectRenderer(renderer) +{ + WebGLManager.call(this, renderer); +} + + +ObjectRenderer.prototype = Object.create(WebGLManager.prototype); +ObjectRenderer.prototype.constructor = ObjectRenderer; +module.exports = ObjectRenderer; + +/** + * Starts the renderer and sets the shader + * + */ +ObjectRenderer.prototype.start = function () +{ + // set the shader.. +}; + +/** + * Stops the renderer + * + */ +ObjectRenderer.prototype.stop = function () +{ + this.flush(); +}; + +/** + * Stub method for rendering content and emptying the current batch. + * + */ +ObjectRenderer.prototype.flush = function () +{ + // flush! +}; + +/** + * Renders an object + * + * @param object {PIXI.DisplayObject} The object to render. + */ +ObjectRenderer.prototype.render = function (object) // jshint unused:false +{ + // render the object +}; + +},{"../managers/WebGLManager":90}],92:[function(require,module,exports){ +var glCore = require('pixi-gl-core'), + createIndicesForQuads = require('../../../utils/createIndicesForQuads'); + +/** + * Helper class to create a quad + * + * @class + * @memberof PIXI + * @param gl {WebGLRenderingContext} The gl context for this quad to use. + * @param state {object} TODO: Description + */ +function Quad(gl, state) +{ + /* + * the current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = new Float32Array([ + -1,-1, + 1,-1, + 1,1, + -1,1 + ]); + + /** + * The Uvs of the quad + * + * @member {Float32Array} + */ + this.uvs = new Float32Array([ + 0,0, + 1,0, + 1,1, + 0,1 + ]); + + this.interleaved = new Float32Array(8 * 2); + + for (var i = 0; i < 4; i++) { + this.interleaved[i*4] = this.vertices[(i*2)]; + this.interleaved[(i*4)+1] = this.vertices[(i*2)+1]; + this.interleaved[(i*4)+2] = this.uvs[i*2]; + this.interleaved[(i*4)+3] = this.uvs[(i*2)+1]; + } + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + this.indices = createIndicesForQuads(1); + + /* + * @member {glCore.GLBuffer} The vertex buffer + */ + this.vertexBuffer = glCore.GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW); + + /* + * @member {glCore.GLBuffer} The index buffer + */ + this.indexBuffer = glCore.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + /* + * @member {glCore.VertexArrayObject} The index buffer + */ + this.vao = new glCore.VertexArrayObject(gl, state); + +} + +Quad.prototype.constructor = Quad; + +/** + * Initialises the vaos and uses the shader + * @param shader {PIXI.Shader} the shader to use + */ +Quad.prototype.initVao = function(shader) +{ + this.vao.clear() + .addIndex(this.indexBuffer) + .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) + .addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4); +}; + +/** + * Maps two Rectangle to the quad + * @param targetTextureFrame {PIXI.Rectangle} the first rectangle + * @param destinationFrame {PIXI.Rectangle} the second rectangle + */ +Quad.prototype.map = function(targetTextureFrame, destinationFrame) +{ + var x = 0; //destinationFrame.x / targetTextureFrame.width; + var y = 0; //destinationFrame.y / targetTextureFrame.height; + + this.uvs[0] = x; + this.uvs[1] = y; + + this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; + + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; + + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; + + /// ----- + x = destinationFrame.x; + y = destinationFrame.y; + + this.vertices[0] = x; + this.vertices[1] = y; + + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + + return this; +}; + +/** + * Draws the quad + */ +Quad.prototype.draw = function() +{ + this.vao.bind() + .draw(this.gl.TRIANGLES, 6, 0) + .unbind(); + + return this; +}; + +/** + * Binds the buffer and uploads the data + */ +Quad.prototype.upload = function() +{ + for (var i = 0; i < 4; i++) { + this.interleaved[i*4] = this.vertices[(i*2)]; + this.interleaved[(i*4)+1] = this.vertices[(i*2)+1]; + this.interleaved[(i*4)+2] = this.uvs[i*2]; + this.interleaved[(i*4)+3] = this.uvs[(i*2)+1]; + } + + this.vertexBuffer.upload(this.interleaved); + + return this; +}; + +/** + * Removes this quad from WebGL + */ +Quad.prototype.destroy = function() +{ + var gl = this.gl; + + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.indexBuffer); +}; + +module.exports = Quad; + +},{"../../../utils/createIndicesForQuads":114,"pixi-gl-core":12}],93:[function(require,module,exports){ +var math = require('../../../math'), + CONST = require('../../../const'), + GLFramebuffer = require('pixi-gl-core').GLFramebuffer; + +/** + * @author Mat Groves http://matgroves.com/ @Doormat23 + */ + +/** + * @class + * @memberof PIXI + * @param gl {WebGLRenderingContext} the current WebGL drawing context + * @param [width=0] {number} the horizontal range of the filter + * @param [height=0] {number} the vertical range of the filter + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @param [resolution=1] {number} The current resolution / device pixel ratio + * @param [root=false] {boolean} Whether this object is the root element or not + */ +var RenderTarget = function(gl, width, height, scaleMode, resolution, root) +{ + //TODO Resolution could go here ( eg low res blurs ) + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // next time to create a frame buffer and texture + + /** + * A frame buffer + * + * @member {PIXI.glCore.GLFramebuffer} + */ + this.frameBuffer = null; + + /** + * The texture + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The background colour of this render target, as an array of [r,g,b,a] values + * + * @member {number[]} + */ + this.clearColor = [0, 0, 0, 0]; + + /** + * The size of the object as a rectangle + * + * @member {PIXI.Rectangle} + */ + this.size = new math.Rectangle(0, 0, 1, 1); + + /** + * The current resolution / device pixel ratio + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || CONST.RESOLUTION; + + /** + * The projection matrix + * + * @member {PIXI.Matrix} + */ + this.projectionMatrix = new math.Matrix(); + + /** + * The object's transform + * + * @member {PIXI.Matrix} + */ + this.transform = null; + + /** + * The frame. + * + * @member {PIXI.Rectangle} + */ + this.frame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.defaultFrame = new math.Rectangle(); + this.destinationFrame = null; + this.sourceFrame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.stencilBuffer = null; + + /** + * The data structure for the stencil masks + * + * @member {PIXI.Graphics[]} + */ + this.stencilMaskStack = []; + + /** + * Stores filter data for the render target + * + * @member {object[]} + */ + this.filterData = null; + + /** + * The scale mode. + * + * @member {number} + * @default PIXI.SCALE_MODES.DEFAULT + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode || CONST.SCALE_MODES.DEFAULT; + + /** + * Whether this object is the root element or not + * + * @member {boolean} + */ + this.root = root; + + + if (!this.root) + { + this.frameBuffer = GLFramebuffer.createRGBA(gl, 100, 100); + + if( this.scaleMode === CONST.SCALE_MODES.NEAREST) + { + this.frameBuffer.texture.enableNearestScaling(); + } + else + { + this.frameBuffer.texture.enableLinearScaling(); + + } + /* + A frame buffer needs a target to render to.. + create a texture and bind it attach it to the framebuffer.. + */ + + // this is used by the base texture + this.texture = this.frameBuffer.texture; + } + else + { + // make it a null framebuffer.. + this.frameBuffer = new GLFramebuffer(gl, 100, 100); + this.frameBuffer.framebuffer = null; + + } + + this.setFrame(); + + this.resize(width, height); +}; + +RenderTarget.prototype.constructor = RenderTarget; +module.exports = RenderTarget; + +/** + * Clears the filter texture. + * + * @param [clearColor=this.clearColor] {number[]} Array of [r,g,b,a] to clear the framebuffer + */ +RenderTarget.prototype.clear = function(clearColor) +{ + var cc = clearColor || this.clearColor; + this.frameBuffer.clear(cc[0],cc[1],cc[2],cc[3]);//r,g,b,a); +}; + +/** + * Binds the stencil buffer. + * + */ +RenderTarget.prototype.attachStencilBuffer = function() +{ + //TODO check if stencil is done? + /** + * The stencil buffer is used for masking in pixi + * lets create one and then add attach it to the framebuffer.. + */ + if (!this.root) + { + this.frameBuffer.enableStencil(); + } +}; + +RenderTarget.prototype.setFrame = function(destinationFrame, sourceFrame) +{ + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; +}; + +/** + * Binds the buffers and initialises the viewport. + * + */ +RenderTarget.prototype.activate = function() +{ + //TOOD refactor usage of frame.. + var gl = this.gl; + + // make surethe texture is unbound! + this.frameBuffer.bind(); + + this.calculateProjection( this.destinationFrame, this.sourceFrame ); + + if(this.transform) + { + this.projectionMatrix.append(this.transform); + } + + //TODO add a check as them may be the same! + if(this.destinationFrame !== this.sourceFrame) + { + + gl.enable(gl.SCISSOR_TEST); + gl.scissor(this.destinationFrame.x | 0,this.destinationFrame.y | 0, (this.destinationFrame.width * this.resolution) | 0, (this.destinationFrame.height* this.resolution) | 0); + } + else + { + gl.disable(gl.SCISSOR_TEST); + } + + + // TODO - does not need to be updated all the time?? + gl.viewport(this.destinationFrame.x | 0,this.destinationFrame.y | 0, (this.destinationFrame.width * this.resolution) | 0, (this.destinationFrame.height * this.resolution)|0); + + +}; + + +/** + * Updates the projection matrix based on a projection frame (which is a rectangle) + * + */ +RenderTarget.prototype.calculateProjection = function (destinationFrame, sourceFrame) +{ + var pm = this.projectionMatrix; + + sourceFrame = sourceFrame || destinationFrame; + + pm.identity(); + + // TODO: make dest scale source + if (!this.root) + { + pm.a = 1 / destinationFrame.width*2; + pm.d = 1 / destinationFrame.height*2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = -1 - sourceFrame.y * pm.d; + } + else + { + pm.a = 1 / destinationFrame.width*2; + pm.d = -1 / destinationFrame.height*2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = 1 - sourceFrame.y * pm.d; + } +}; + + +/** + * Resizes the texture to the specified width and height + * + * @param width {Number} the new width of the texture + * @param height {Number} the new height of the texture + */ +RenderTarget.prototype.resize = function (width, height) +{ + width = width | 0; + height = height | 0; + + if (this.size.width === width && this.size.height === height) + { + return; + } + + this.size.width = width; + this.size.height = height; + + this.defaultFrame.width = width; + this.defaultFrame.height = height; + + + this.frameBuffer.resize(width * this.resolution, height * this.resolution); + + var projectionFrame = this.frame || this.size; + + this.calculateProjection( projectionFrame ); +}; + +/** + * Destroys the render target. + * + */ +RenderTarget.prototype.destroy = function () +{ + this.frameBuffer.destroy(); + + this.frameBuffer = null; + this.texture = null; +}; + +},{"../../../const":43,"../../../math":67,"pixi-gl-core":12}],94:[function(require,module,exports){ +var glCore = require('pixi-gl-core'); + +var fragTemplate = [ + 'precision mediump float;', + 'void main(void){', + 'float test = 0.1;', + '%forloop%', + 'gl_FragColor = vec4(0.0);', + '}' +].join('\n'); + +var checkMaxIfStatmentsInShader = function(maxIfs, gl) +{ + var createTempContext = !gl; + + if(createTempContext) + { + var tinyCanvas = document.createElement('canvas'); + tinyCanvas.width = 1; + tinyCanvas.height = 1; + + gl = glCore.createContext(tinyCanvas); + } + + var shader = gl.createShader(gl.FRAGMENT_SHADER); + + while(true) + { + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + + if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + maxIfs = (maxIfs/2)|0; + } + else + { + // valid! + break; + } + } + + if(createTempContext) + { + // get rid of context + if(gl.getExtension('WEBGL_lose_context')) + { + gl.getExtension('WEBGL_lose_context').loseContext(); + } + } + + return maxIfs; +}; + + + +function generateIfTestSrc(maxIfs) +{ + var src = ''; + + for (var i = 0; i < maxIfs; i++) + { + if(i > 0) + { + src += '\nelse '; + } + + if(i < maxIfs-1) + { + src += 'if(test == ' + i + '.0){}'; + } + } + + return src; +} + +module.exports = checkMaxIfStatmentsInShader; + +},{"pixi-gl-core":12}],95:[function(require,module,exports){ +var CONST = require('../../../const'); + +/** + * Maps gl blend combinations to WebGL + * @class + * @memberof PIXI + * @param gl {WebGLRenderingContext} The current WebGL drawing context + * @param array + */ +function mapWebGLBlendModesToPixi(gl, array) +{ + array = array || []; + + //TODO - premultiply alpha would be different. + //add a boolean for that! + array[CONST.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.ADD] = [gl.ONE, gl.DST_ALPHA]; + array[CONST.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + array[CONST.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[CONST.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + return array; +} + +module.exports = mapWebGLBlendModesToPixi; + +},{"../../../const":43}],96:[function(require,module,exports){ +var CONST = require('../../../const'); + +/** + * Generic Mask Stack data structure + * @class + * @memberof PIXI + * @param gl {WebGLRenderingContext} The current WebGL drawing context + * @param object + */ +function mapWebGLDrawModesToPixi(gl, object) +{ + object= object || {}; + + object[CONST.DRAW_MODES.POINTS] = gl.POINTS; + object[CONST.DRAW_MODES.LINES] = gl.LINES; + object[CONST.DRAW_MODES.LINE_LOOP] = gl.LINE_LOOP; + object[CONST.DRAW_MODES.LINE_STRIP] = gl.LINE_STRIP; + object[CONST.DRAW_MODES.TRIANGLES] = gl.TRIANGLES; + object[CONST.DRAW_MODES.TRIANGLE_STRIP] = gl.TRIANGLE_STRIP; + object[CONST.DRAW_MODES.TRIANGLE_FAN] = gl.TRIANGLE_FAN; + +} + +module.exports = mapWebGLDrawModesToPixi; + +},{"../../../const":43}],97:[function(require,module,exports){ + + +function validateContext(gl) +{ + var attributes = gl.getContextAttributes(); + + // this is going to be fairly simple for now.. but at least we have rom to grow! + if(!attributes.stencil) + { + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); // jshint ignore:line + } +} + +module.exports = validateContext; + +},{}],98:[function(require,module,exports){ +var math = require('../math'), + Texture = require('../textures/Texture'), + Container = require('../display/Container'), + utils = require('../utils'), + CONST = require('../const'), + tempPoint = new math.Point(); + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * var sprite = new PIXI.Sprite.fromImage('assets/image.png'); + * ``` + * + * @class + * @extends PIXI.Container + * @memberof PIXI + * @param texture {PIXI.Texture} The texture for this sprite + */ +function Sprite(texture) +{ + Container.call(this); + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + */ + this.anchor = new math.ObservablePoint(this.onAnchorUpdate, this); + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + * @private + */ + this._texture = null; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @member {number} + * @private + */ + this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @member {number} + * @private + */ + this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + this._tint = null; + this._tintRGB = null; + this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + this.blendMode = CONST.BLEND_MODES.NORMAL; + + /** + * The shader that will be used to render the sprite. Set to null to remove a current shader. + * + * @member {PIXI.AbstractFilter|PIXI.Shader} + */ + this.shader = null; + + /** + * An internal cached value of the tint. + * + * @member {number} + * @default 0xFFFFFF + * @private + */ + this.cachedTint = 0xFFFFFF; + + // call texture setter + this.texture = texture || Texture.EMPTY; + + /** + * this is used to store the vertex data of the sprite (basically a quad) + * @type {Float32Array} + */ + this.vertexData = new Float32Array(8); + + /** + * this is used to calculate the bounds of the object IF it is a trimmed sprite + * @type {Float32Array} + */ + this.vertexTrimmedData = null; + + this._transformID = -1; + this._textureID = -1; +} + +// constructor +Sprite.prototype = Object.create(Container.prototype); +Sprite.prototype.constructor = Sprite; +module.exports = Sprite; + +Object.defineProperties(Sprite.prototype, { + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Sprite# + */ + width: { + get: function () + { + return Math.abs(this.scale.x) * this.texture.orig.width; + }, + set: function (value) + { + var sign = utils.sign(this.scale.x) || 1; + this.scale.x = sign * value / this.texture.orig.width; + this._width = value; + } + }, + + /** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Sprite# + */ + height: { + get: function () + { + return Math.abs(this.scale.y) * this.texture.orig.height; + }, + set: function (value) + { + var sign = utils.sign(this.scale.y) || 1; + this.scale.y = sign * value / this.texture.orig.height; + this._height = value; + } + }, + + tint: { + get: function () + { + return this._tint; + }, + set: function (value) + { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + } + }, + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + * @memberof PIXI.Sprite# + */ + texture: { + get: function () + { + return this._texture; + }, + set: function (value) + { + if (this._texture === value) + { + return; + } + + this._texture = value; + this.cachedTint = 0xFFFFFF; + + this._textureID = -1; + + if (value) + { + // wait for the texture to load + if (value.baseTexture.hasLoaded) + { + this._onTextureUpdate(); + } + else + { + value.once('update', this._onTextureUpdate, this); + } + } + } + } +}); + +/** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ +Sprite.prototype._onTextureUpdate = function () +{ + this._textureID = -1; + + // so if _width is 0 then width was not set.. + if (this._width) + { + this.scale.x = utils.sign(this.scale.x) * this._width / this.texture.orig.width; + } + + if (this._height) + { + this.scale.y = utils.sign(this.scale.y) * this._height / this.texture.orig.height; + } +}; + +Sprite.prototype.onAnchorUpdate = function() +{ + this._transformID = -1; +}; + +/** + * calculates worldTransform * vertices, store it in vertexData + */ +Sprite.prototype.calculateVertices = function () +{ + if(this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) + { + return; + } + + this._transformID = this.transform._worldID; + this._textureID = this._texture._updateID; + + // set the vertex data + + var texture = this._texture, + wt = this.transform.worldTransform, + a = wt.a, b = wt.b, c = wt.c, d = wt.d, tx = wt.tx, ty = wt.ty, + vertexData = this.vertexData, + w0, w1, h0, h1, + trim = texture.trim, + orig = texture.orig; + + if (trim) + { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra space before transforming the sprite coords.. + w1 = trim.x - this.anchor._x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - this.anchor._y * orig.height; + h0 = h1 + trim.height; + + } + else + { + w0 = orig.width * (1-this.anchor._x); + w1 = orig.width * -this.anchor._x; + + h0 = orig.height * (1-this.anchor._y); + h1 = orig.height * -this.anchor._y; + } + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; +}; + +/** + * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData + * This is used to ensure that the true width and height of a trimmed texture is respected + */ +Sprite.prototype.calculateTrimmedVertices = function () +{ + if(!this.vertexTrimmedData) + { + this.vertexTrimmedData = new Float32Array(8); + } + + // lets do some special trim code! + var texture = this._texture, + vertexData = this.vertexTrimmedData, + orig = texture.orig; + + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform, + a = wt.a, b = wt.b, c = wt.c, d = wt.d, tx = wt.tx, ty = wt.ty, + w0, w1, h0, h1; + + w0 = (orig.width ) * (1-this.anchor._x); + w1 = (orig.width ) * -this.anchor._x; + + h0 = orig.height * (1-this.anchor._y); + h1 = orig.height * -this.anchor._y; + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; +}; + +/** +* +* Renders the object using the WebGL renderer +* +* @param renderer {PIXI.WebGLRenderer} +* @private +*/ +Sprite.prototype._renderWebGL = function (renderer) +{ + this.calculateVertices(); + + renderer.setObjectRenderer(renderer.plugins.sprite); + renderer.plugins.sprite.render(this); +}; + +/** +* Renders the object using the Canvas renderer +* +* @param renderer {PIXI.CanvasRenderer} The renderer +* @private +*/ +Sprite.prototype._renderCanvas = function (renderer) +{ + renderer.plugins.sprite.render(this); +}; + + +Sprite.prototype._calculateBounds = function () +{ + + var trim = this._texture.trim, + orig = this._texture.orig; + + //First lets check to see if the current texture has a trim.. + if (!trim || trim.width === orig.width && trim.height === orig.height) { + + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } + else + { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } +}; + +/** + * Gets the local bounds of the sprite object. + * + */ + +Sprite.prototype.getLocalBounds = function (rect) +{ + // we can do a fast local bounds if the sprite has no children! + if(this.children.length === 0) + { + + this._bounds.minX = -this._texture.orig.width * this.anchor._x; + this._bounds.minY = -this._texture.orig.height * this.anchor._y; + this._bounds.maxX = this._texture.orig.width; + this._bounds.maxY = this._texture.orig.height; + + if(!rect) + { + if(!this._localBoundsRect) + { + this._localBoundsRect = new math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + else + { + return Container.prototype.getLocalBounds.call(this, rect); + } + +}; + +/** +* Tests if a point is inside this sprite +* +* @param point {PIXI.Point} the point to test +* @return {boolean} the result of the test +*/ +Sprite.prototype.containsPoint = function( point ) +{ + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1; + + if ( tempPoint.x > x1 && tempPoint.x < x1 + width ) + { + y1 = -height * this.anchor.y; + + if ( tempPoint.y > y1 && tempPoint.y < y1 + height ) + { + return true; + } + } + + return false; +}; + + +/** + * Destroys this sprite and optionally its texture and children + * + * @param [options] {object|boolean} Options parameter. A boolean will act as if all options have been set to that value + * @param [options.children=false] {boolean} if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param [options.texture=false] {boolean} Should it destroy the current texture of the sprite as well + * @param [options.baseTexture=false] {boolean} Should it destroy the base texture of the sprite as well + */ +Sprite.prototype.destroy = function (options) +{ + Container.prototype.destroy.call(this, options); + + this.anchor = null; + + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + if (destroyTexture) + { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + this._texture.destroy(!!destroyBaseTexture); + } + + this._texture = null; + this.shader = null; +}; + +// some helper functions.. + +/** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ +Sprite.from = function (source) +{ + return new Sprite(Texture.from(source)); +}; + +/** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param frameId {string} The frame Id of the texture in the cache + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId + */ +Sprite.fromFrame = function (frameId) +{ + var texture = utils.TextureCache[frameId]; + + if (!texture) + { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return new Sprite(texture); +}; + +/** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param imageId {string} The image url of the texture + * @param [crossorigin=(auto)] {boolean} if you want to specify the cross-origin parameter + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} if you want to specify the scale mode, see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id + */ +Sprite.fromImage = function (imageId, crossorigin, scaleMode) +{ + return new Sprite(Texture.fromImage(imageId, crossorigin, scaleMode)); +}; + +},{"../const":43,"../display/Container":45,"../math":67,"../textures/Texture":109,"../utils":116}],99:[function(require,module,exports){ +var CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'), + CONST = require('../../const'), + math = require('../../math'), + canvasRenderWorldTransform = new math.Matrix(), + CanvasTinter = require('./CanvasTinter'); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasSpriteRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + * @param renderer {PIXI.WebGLRenderer} The renderer sprite this batch works for. + */ +function CanvasSpriteRenderer(renderer) +{ + this.renderer = renderer; +} + + +CanvasSpriteRenderer.prototype.constructor = CanvasSpriteRenderer; +module.exports = CanvasSpriteRenderer; + +CanvasRenderer.registerPlugin('sprite', CanvasSpriteRenderer); + +/** + * Renders the sprite object. + * + * @param sprite {PIXI.Sprite} the sprite to render when using this spritebatch + */ +CanvasSpriteRenderer.prototype.render = function (sprite) +{ + var texture = sprite._texture, + renderer = this.renderer, + wt = sprite.transform.worldTransform, + dx, + dy, + width = texture._frame.width, + height = texture._frame.height; + + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) + { + return; + } + + renderer.setBlendMode(sprite.blendMode); + + // Ignore null sources + if (texture.valid) + { + renderer.context.globalAlpha = sprite.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture + var smoothingEnabled = texture.baseTexture.scaleMode === CONST.SCALE_MODES.LINEAR; + if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) + { + renderer.context[renderer.smoothProperty] = smoothingEnabled; + } + + if (texture.trim) { + dx = texture.trim.width/2 + texture.trim.x - sprite.anchor.x * texture.orig.width; + dy = texture.trim.height/2 + texture.trim.y - sprite.anchor.y * texture.orig.height; + } else { + dx = (0.5 - sprite.anchor.x) * texture.orig.width; + dy = (0.5 - sprite.anchor.y) * texture.orig.height; + } + if(texture.rotate) { + wt.copy(canvasRenderWorldTransform); + wt = canvasRenderWorldTransform; + math.GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); + // the anchor has already been applied above, so lets set it to zero + dx = 0; + dy = 0; + } + dx -= width/2; + dy -= height/2; + // Allow for pixel rounding + if (renderer.roundPixels) + { + renderer.context.setTransform( + wt.a, + wt.b, + wt.c, + wt.d, + (wt.tx * renderer.resolution) | 0, + (wt.ty * renderer.resolution) | 0 + ); + + dx = dx | 0; + dy = dy | 0; + } + else + { + renderer.context.setTransform( + wt.a, + wt.b, + wt.c, + wt.d, + wt.tx * renderer.resolution, + wt.ty * renderer.resolution + ); + } + + var resolution = texture.baseTexture.resolution; + + if (sprite.tint !== 0xFFFFFF) + { + if (sprite.cachedTint !== sprite.tint) + { + sprite.cachedTint = sprite.tint; + + // TODO clean up caching - how to clean up the caches? + sprite.tintedTexture = CanvasTinter.getTintedTexture(sprite, sprite.tint); + } + + renderer.context.drawImage( + sprite.tintedTexture, + 0, + 0, + width * resolution, + height * resolution, + dx * renderer.resolution, + dy * renderer.resolution, + width * renderer.resolution, + height * renderer.resolution + ); + } + else + { + + renderer.context.drawImage( + texture.baseTexture.source, + texture._frame.x * resolution, + texture._frame.y * resolution, + width * resolution, + height * resolution, + dx * renderer.resolution, + dy * renderer.resolution, + width * renderer.resolution, + height * renderer.resolution + ); + } + } +}; + +/** + * destroy the sprite object. + * + */ +CanvasSpriteRenderer.prototype.destroy = function (){ + this.renderer = null; +}; + +},{"../../const":43,"../../math":67,"../../renderers/canvas/CanvasRenderer":74,"./CanvasTinter":100}],100:[function(require,module,exports){ +var utils = require('../../utils'), + canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); + +/** + * Utility methods for Sprite/Texture tinting. + * + * @namespace PIXI.CanvasTinter + */ +var CanvasTinter = module.exports = { + /** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @memberof PIXI.CanvasTinter + * @param sprite {PIXI.Sprite} the sprite to tint + * @param color {number} the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ + getTintedTexture: function (sprite, color) + { + var texture = sprite.texture; + + color = CanvasTinter.roundColor(color); + + var stringColor = '#' + ('00000' + ( color | 0).toString(16)).substr(-6); + + texture.tintCache = texture.tintCache || {}; + + if (texture.tintCache[stringColor]) + { + return texture.tintCache[stringColor]; + } + + // clone texture.. + var canvas = CanvasTinter.canvas || document.createElement('canvas'); + + //CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); + CanvasTinter.tintMethod(texture, color, canvas); + + if (CanvasTinter.convertTintToImage) + { + // is this better? + var tintImage = new Image(); + tintImage.src = canvas.toDataURL(); + + texture.tintCache[stringColor] = tintImage; + } + else + { + texture.tintCache[stringColor] = canvas; + // if we are not converting the texture to an image then we need to lose the reference to the canvas + CanvasTinter.canvas = null; + } + + return canvas; + }, + + /** + * Tint a texture using the 'multiply' operation. + * + * @memberof PIXI.CanvasTinter + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + tintWithMultiply: function (texture, color, canvas) + { + var context = canvas.getContext( '2d' ); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = crop.width; + canvas.height = crop.height; + + context.fillStyle = '#' + ('00000' + ( color | 0).toString(16)).substr(-6); + + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage( + texture.baseTexture.source, + crop.x, + crop.y, + crop.width, + crop.height, + 0, + 0, + crop.width, + crop.height + ); + + context.globalCompositeOperation = 'destination-atop'; + + context.drawImage( + texture.baseTexture.source, + crop.x, + crop.y, + crop.width, + crop.height, + 0, + 0, + crop.width, + crop.height + ); + }, + + /** + * Tint a texture using the 'overlay' operation. + * + * @memberof PIXI.CanvasTinter + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + tintWithOverlay: function (texture, color, canvas) + { + var context = canvas.getContext( '2d' ); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = crop.width; + canvas.height = crop.height; + + context.globalCompositeOperation = 'copy'; + context.fillStyle = '#' + ('00000' + ( color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + context.drawImage( + texture.baseTexture.source, + crop.x, + crop.y, + crop.width, + crop.height, + 0, + 0, + crop.width, + crop.height + ); + + // context.globalCompositeOperation = 'copy'; + }, + + /** + * Tint a texture pixel per pixel. + * + * @memberof PIXI.CanvasTinter + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + tintWithPerPixel: function (texture, color, canvas) + { + var context = canvas.getContext( '2d' ); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = crop.width; + canvas.height = crop.height; + + context.globalCompositeOperation = 'copy'; + context.drawImage( + texture.baseTexture.source, + crop.x, + crop.y, + crop.width, + crop.height, + 0, + 0, + crop.width, + crop.height + ); + + var rgbValues = utils.hex2rgb(color); + var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, crop.width, crop.height); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) + { + pixels[i+0] *= r; + pixels[i+1] *= g; + pixels[i+2] *= b; + } + + context.putImageData(pixelData, 0, 0); + }, + + /** + * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel. + * + * @memberof PIXI.CanvasTinter + * @param color {number} the color to round, should be a hex color + */ + roundColor: function (color) + { + var step = CanvasTinter.cacheStepsPerColorChannel; + + var rgbValues = utils.hex2rgb(color); + + rgbValues[0] = Math.min(255, (rgbValues[0] / step) * step); + rgbValues[1] = Math.min(255, (rgbValues[1] / step) * step); + rgbValues[2] = Math.min(255, (rgbValues[2] / step) * step); + + return utils.rgb2hex(rgbValues); + }, + + /** + * Number of steps which will be used as a cap when rounding colors. + * + * @memberof PIXI.CanvasTinter + * @type {number} + */ + cacheStepsPerColorChannel: 8, + + /** + * Tint cache boolean flag. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + convertTintToImage: false, + + /** + * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + canUseMultiply: canUseNewCanvasBlendModes(), + + /** + * The tinting method that will be used. + * + * @memberof PIXI.CanvasTinter + * @type {tintMethodFunctionType} + */ + tintMethod: 0 +}; + +CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply : CanvasTinter.tintWithPerPixel; + +/** + * The tintMethod type. + * + * @memberof PIXI.CanvasTinter + * @callback tintMethodFunctionType + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + +},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":77,"../../utils":116}],101:[function(require,module,exports){ + + + var Buffer = function(size) + { + + this.vertices = new ArrayBuffer(size); + + /** + * View on the vertices as a Float32Array for positions + * + * @member {Float32Array} + */ + this.float32View = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array for uvs + * + * @member {Float32Array} + */ + this.uint32View = new Uint32Array(this.vertices); + }; + + module.exports = Buffer; + + Buffer.prototype.destroy = function(){ + this.vertices = null; + this.positions = null; + this.uvs = null; + this.colors = null; + }; +},{}],102:[function(require,module,exports){ +var ObjectRenderer = require('../../renderers/webgl/utils/ObjectRenderer'), + WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'), + createIndicesForQuads = require('../../utils/createIndicesForQuads'), + generateMultiTextureShader = require('./generateMultiTextureShader'), + checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'), + Buffer = require('./BatchBuffer'), + CONST = require('../../const'), + glCore = require('pixi-gl-core'), + bitTwiddle = require('bit-twiddle'); + + var TICK = 0; +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + * @param renderer {PIXI.WebGLRenderer} The renderer this sprite batch works for. + */ +function SpriteRenderer(renderer) +{ + ObjectRenderer.call(this, renderer); + + /** + * Number of values sent in the vertex buffer. + * positionX, positionY, colorR, colorG, colorB = 5 + * + * @member {number} + */ + this.vertSize = 5; + + /** + * The size of the vertex information in bytes. + * + * @member {number} + */ + this.vertByteSize = this.vertSize * 4; + + /** + * The number of images in the SpriteBatch before it flushes. + * + * @member {number} + */ + this.size = CONST.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + + // the total number of bytes in our batch + // var numVerts = this.size * 4 * this.vertByteSize; + + this.buffers = []; + for (var i = 1; i <= bitTwiddle.nextPow2(this.size); i*=2) { + var numVertsTemp = i * 4 * this.vertByteSize; + this.buffers.push(new Buffer(numVertsTemp)); + } + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = createIndicesForQuads(this.size); + + /** + * The default shaders that is used if a sprite doesn't have a more specific one. + * there is a shader for each number of textures that can be rendererd. + * These shaders will also be generated on the fly as required. + * @member {PIXI.Shader[]} + */ + this.shaders = null; + + this.currentIndex = 0; + TICK =0; + this.groups = []; + + for (var k = 0; k < this.size; k++) + { + this.groups[k] = {textures:[], textureCount:0, ids:[], size:0, start:0, blend:0}; + } + + this.sprites = []; + + this.vertexBuffers = []; + this.vaos = []; + + this.vaoMax = 2; + this.vertexCount = 0; + + this.renderer.on('prerender', this.onPrerender, this); +} + + +SpriteRenderer.prototype = Object.create(ObjectRenderer.prototype); +SpriteRenderer.prototype.constructor = SpriteRenderer; +module.exports = SpriteRenderer; + +WebGLRenderer.registerPlugin('sprite', SpriteRenderer); + +/** + * Sets up the renderer context and necessary buffers. + * + * @private + */ +SpriteRenderer.prototype.onContextChange = function () +{ + var gl = this.renderer.gl; + + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), CONST.SPRITE_MAX_TEXTURES); + + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = checkMaxIfStatmentsInShader( this.MAX_TEXTURES, gl ); + + this.shaders = new Array(this.MAX_TEXTURES); + this.shaders[0] = generateMultiTextureShader(gl, 1); + this.shaders[1] = generateMultiTextureShader(gl, 2); + + // create a couple of buffers + this.indexBuffer = glCore.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + // we use the second shader as the first one depending on your browser may omit aTextureId + // as it is not used by the shader so is optimized out. + var shader = this.shaders[1]; + + for (var i = 0; i < this.vaoMax; i++) { + this.vertexBuffers[i] = glCore.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + + // build the vao object that will render.. + this.vaos[i] = this.renderer.createVao() + .addIndex(this.indexBuffer) + .addAttribute(this.vertexBuffers[i], shader.attributes.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0) + .addAttribute(this.vertexBuffers[i], shader.attributes.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4) + .addAttribute(this.vertexBuffers[i], shader.attributes.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4) + .addAttribute(this.vertexBuffers[i], shader.attributes.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vao = this.vaos[0]; + this.currentBlendMode = 99999; +}; + +SpriteRenderer.prototype.onPrerender = function () +{ + this.vertexCount = 0; +}; + +/** + * Renders the sprite object. + * + * @param sprite {PIXI.Sprite} the sprite to render when using this spritebatch + */ +SpriteRenderer.prototype.render = function (sprite) +{ + //TODO set blend modes.. + // check texture.. + if (this.currentIndex >= this.size) + { + this.flush(); + } + + + // get the uvs for the texture + + + // if the uvs have not updated then no point rendering just yet! + if (!sprite.texture._uvs) + { + return; + } + + // push a texture. + // increment the batchsize + this.sprites[this.currentIndex++] = sprite; +}; + +/** + * Renders the content and empties the current batch. + * + */ +SpriteRenderer.prototype.flush = function () +{ + if (this.currentIndex === 0) { + return; + } + + var gl = this.renderer.gl; + + var np2 = bitTwiddle.nextPow2(this.currentIndex); + var log2 = bitTwiddle.log2(np2); + var buffer = this.buffers[log2]; + + var sprites = this.sprites; + var groups = this.groups; + + var float32View = buffer.float32View; + var uint32View = buffer.uint32View; + + var index = 0; + var nextTexture; + var currentTexture; + var groupCount = 1; + var textureCount = 0; + var currentGroup = groups[0]; + var vertexData; + var tint; + var uvs; + var textureId; + var blendMode = sprites[0].blendMode; + var shader; + + currentGroup.textureCount = 0; + currentGroup.start = 0; + currentGroup.blend = blendMode; + + TICK++; + + for (var i = 0; i < this.currentIndex; i++) + { + // upload the sprite elemetns... + // they have all ready been calculated so we just need to push them into the buffer. + var sprite = sprites[i]; + + nextTexture = sprite._texture.baseTexture; + + if(blendMode !== sprite.blendMode) + { + blendMode = sprite.blendMode; + + // force the batch to break! + currentTexture = null; + textureCount = this.MAX_TEXTURES; + TICK++; + } + + if(currentTexture !== nextTexture) + { + currentTexture = nextTexture; + + if(nextTexture._enabled !== TICK) + { + if(textureCount === this.MAX_TEXTURES) + { + TICK++; + + textureCount = 0; + + currentGroup.size = i - currentGroup.start; + + currentGroup = groups[groupCount++]; + currentGroup.textureCount = 0; + currentGroup.blend = blendMode; + currentGroup.start = i; + } + + nextTexture._enabled = TICK; + nextTexture._id = textureCount; + + currentGroup.textures[currentGroup.textureCount++] = nextTexture; + textureCount++; + } + + } + + vertexData = sprite.vertexData; + + //TODO this sum does not need to be set each frame.. + tint = sprite._tintRGB + (sprite.worldAlpha * 255 << 24); + uvs = sprite._texture._uvs.uvsUint32; + textureId = nextTexture._id; + + if (this.renderer.roundPixels) + { + var resolution = this.renderer.resolution; + + //xy + float32View[index] = ((vertexData[0] * resolution) | 0) / resolution; + float32View[index+1] = ((vertexData[1] * resolution) | 0) / resolution; + + // xy + float32View[index+5] = ((vertexData[2] * resolution) | 0) / resolution; + float32View[index+6] = ((vertexData[3] * resolution) | 0) / resolution; + + // xy + float32View[index+10] = ((vertexData[4] * resolution) | 0) / resolution; + float32View[index+11] = ((vertexData[5] * resolution) | 0) / resolution; + + // xy + float32View[index+15] = ((vertexData[6] * resolution) | 0) / resolution; + float32View[index+16] = ((vertexData[7] * resolution) | 0) / resolution; + + } + else + { + //xy + float32View[index] = vertexData[0]; + float32View[index+1] = vertexData[1]; + + // xy + float32View[index+5] = vertexData[2]; + float32View[index+6] = vertexData[3]; + + // xy + float32View[index+10] = vertexData[4]; + float32View[index+11] = vertexData[5]; + + // xy + float32View[index+15] = vertexData[6]; + float32View[index+16] = vertexData[7]; + } + + uint32View[index+2] = uvs[0]; + uint32View[index+7] = uvs[1]; + uint32View[index+12] = uvs[2]; + uint32View[index+17] = uvs[3]; + + uint32View[index+3] = uint32View[index+8] = uint32View[index+13] = uint32View[index+18] = tint; + float32View[index+4] = float32View[index+9] = float32View[index+14] = float32View[index+19] = textureId; + + index += 20; + } + + currentGroup.size = i - currentGroup.start; + + this.vertexCount++; + + if(this.vaoMax <= this.vertexCount) + { + this.vaoMax++; + shader = this.shaders[1]; + this.vertexBuffers[this.vertexCount] = glCore.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + // build the vao object that will render.. + this.vaos[this.vertexCount] = this.renderer.createVao() + .addIndex(this.indexBuffer) + .addAttribute(this.vertexBuffers[this.vertexCount], shader.attributes.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0) + .addAttribute(this.vertexBuffers[this.vertexCount], shader.attributes.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4) + .addAttribute(this.vertexBuffers[this.vertexCount], shader.attributes.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4) + .addAttribute(this.vertexBuffers[this.vertexCount], shader.attributes.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0); + this.vao = this.vaos[this.vertexCount].bind(); + + /// render the groups.. + for (i = 0; i < groupCount; i++) { + + var group = groups[i]; + var groupTextureCount = group.textureCount; + shader = this.shaders[groupTextureCount-1]; + + if(!shader) + { + shader = this.shaders[groupTextureCount-1] = generateMultiTextureShader(gl, groupTextureCount); + //console.log("SHADER generated for " + textureCount + " textures") + } + + this.renderer.bindShader(shader); + + for (var j = 0; j < groupTextureCount; j++) + { + this.renderer.bindTexture(group.textures[j], j); + } + + // set the blend mode.. + this.renderer.state.setBlendMode( group.blend ); + + gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); + } + + // reset elements for the next flush + this.currentIndex = 0; +}; + +/** + * Starts a new sprite batch. + * + */ +SpriteRenderer.prototype.start = function () +{ + //this.renderer.bindShader(this.shader); + //TICK %= 1000; +}; + +SpriteRenderer.prototype.stop = function () +{ + this.flush(); + this.vao.unbind(); +}; +/** + * Destroys the SpriteBatch. + * + */ +SpriteRenderer.prototype.destroy = function () +{ + for (var i = 0; i < this.vaoMax; i++) { + this.vertexBuffers[i].destroy(); + this.vaos[i].destroy(); + } + + this.indexBuffer.destroy(); + + this.renderer.off('prerender', this.onPrerender, this); + ObjectRenderer.prototype.destroy.call(this); + + for (i = 0; i < this.shaders.length; i++) { + + if(this.shaders[i]) + { + this.shaders[i].destroy(); + } + } + + this.vertexBuffers = null; + this.vaos = null; + this.indexBuffer = null; + this.indices = null; + + this.sprites = null; + + for (i = 0; i < this.buffers.length; i++) { + this.buffers[i].destroy(); + } + +}; + +},{"../../const":43,"../../renderers/webgl/WebGLRenderer":81,"../../renderers/webgl/utils/ObjectRenderer":91,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":94,"../../utils/createIndicesForQuads":114,"./BatchBuffer":101,"./generateMultiTextureShader":103,"bit-twiddle":1,"pixi-gl-core":12}],103:[function(require,module,exports){ +var Shader = require('../../Shader'); + + +var fragTemplate = [ + 'varying vec2 vTextureCoord;', + 'varying vec4 vColor;', + 'varying float vTextureId;', + 'uniform sampler2D uSamplers[%count%];', + + 'void main(void){', + 'vec4 color;', + 'float textureId = floor(vTextureId+0.5);', + '%forloop%', + 'gl_FragColor = color * vColor;', + '}' +].join('\n'); + +function generateMultiTextureShader(gl, maxTextures) +{ + var vertexSrc = "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = vec4(aColor.rgb * aColor.a, aColor.a);\n}\n"; + var fragmentSrc = fragTemplate; + + fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); + + var shader = new Shader(gl, vertexSrc, fragmentSrc, {aVertexPosition:3, aColor:2, aTextureCoord:1, aTextureId:0}); + + var sampleValues = []; + for (var i = 0; i < maxTextures; i++) + { + sampleValues[i] = i; + } + + shader.bind(); + shader.uniforms.uSamplers = sampleValues; + + return shader; +} + +function generateSampleSrc(maxTextures) +{ + var src = ''; + + src += '\n'; + src += '\n'; + + for (var i = 0; i < maxTextures; i++) + { + if(i > 0) + { + src += '\nelse '; + } + + if(i < maxTextures-1) + { + src += 'if(textureId == ' + i + '.0)'; + } + + src += '\n{'; + src += '\n\tcolor = texture2D(uSamplers['+i+'], vTextureCoord);'; + src += '\n}'; + } + + src += '\n'; + src += '\n'; + + return src; +} + + + +module.exports = generateMultiTextureShader; + +},{"../../Shader":42}],104:[function(require,module,exports){ +var Sprite = require('../sprites/Sprite'), + Texture = require('../textures/Texture'), + math = require('../math'), + utils = require('../utils'), + CONST = require('../const'), + TextStyle = require('./TextStyle'); + + var defaultDestroyOptions = { + texture:true, + children:false, + baseTexture:true + }; +/** + * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string, + * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object. + * + * A Text can be created directly from a string and a style object + * + * ```js + * var text = new PIXI.Text('This is a pixi text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI + * @param text {string} The string that you would like the text to display + * @param [style] {object|PIXI.TextStyle} The style parameters + */ +function Text(text, style) +{ + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * The canvas 2d context that everything is drawn with + * @member {HTMLCanvasElement} + */ + this.context = this.canvas.getContext('2d'); + + /** + * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. + * @member {number} + * @default 1 + */ + this.resolution = CONST.RESOLUTION; + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + this._text = null; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + this._style = null; + /** + * Private listener to track style changes. + * + * @member {Function} + * @private + */ + this._styleListener = null; + + /** + * Private tracker for the current font. + * + * @member {string} + * @private + */ + this._font = ''; + + var texture = Texture.fromCanvas(this.canvas); + texture.orig = new math.Rectangle(); + texture.trim = new math.Rectangle(); + Sprite.call(this, texture); + + this.text = text; + this.style = style; + + this.localStyleID = -1; +} + +// constructor +Text.prototype = Object.create(Sprite.prototype); +Text.prototype.constructor = Text; +module.exports = Text; + +Text.fontPropertiesCache = {}; +Text.fontPropertiesCanvas = document.createElement('canvas'); +Text.fontPropertiesContext = Text.fontPropertiesCanvas.getContext('2d'); + +Object.defineProperties(Text.prototype, { + /** + * The width of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Text# + */ + width: { + get: function () + { + this.updateText(true); + + return Math.abs(this.scale.x) * this.texture.orig.width; + }, + set: function (value) + { + this.updateText(true); + + var sign = utils.sign(this.scale.x) || 1; + this.scale.x = sign * value / this.texture.orig.width; + this._width = value; + } + }, + + /** + * The height of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.Text# + */ + height: { + get: function () + { + this.updateText(true); + + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function (value) + { + this.updateText(true); + + var sign = utils.sign(this.scale.y) || 1; + this.scale.y = sign * value / this.texture.orig.height; + this._height = value; + } + }, + + /** + * Set the style of the text. Set up an event listener to listen for changes on the style object and mark the text as dirty. + * + * @member {object|PIXI.TextStyle} + * @memberof PIXI.Text# + */ + style: { + get: function () + { + return this._style; + }, + set: function (style) + { + + style = style || {}; + if (style instanceof TextStyle) + { + this._style = style; + } + else + { + this._style = new TextStyle(style); + } + + this.localStyleID = -1; + this.dirty = true; + } + }, + + /** + * Set the copy for the text object. To split a line you can use '\n'. + * + * @member {string} + * @memberof PIXI.Text# + */ + text: { + get: function() + { + return this._text; + }, + set: function (text){ + + text = text || ' '; + text = text.toString(); + + if (this._text === text) + { + return; + } + this._text = text; + this.dirty = true; + } + } +}); + +/** + * Renders text and updates it when needed + * @param respectDirty {boolean} Whether to abort updating the text if the Text isn't dirty and the function is called. + * @private + */ +Text.prototype.updateText = function (respectDirty) +{ + var style = this._style; + + // check if style has changed.. + if(this.localStyleID !== style.styleID) + { + this.dirty = true; + this.localStyleID = style.styleID; + } + + if (!this.dirty && respectDirty) { + return; + } + + // build canvas api font setting from invididual components. Convert a numeric style.fontSize to px + var fontSizeString = (typeof style.fontSize === 'number') ? style.fontSize + 'px' : style.fontSize; + this._font = style.fontStyle + ' ' + style.fontVariant + ' ' + style.fontWeight + ' ' + fontSizeString + ' ' + style.fontFamily; + + this.context.font = this._font; + + // word wrap + // preserve original text + var outputText = style.wordWrap ? this.wordWrap(this._text) : this._text; + + // split text into lines + var lines = outputText.split(/(?:\r\n|\r|\n)/); + + // calculate text width + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + var fontProperties = this.determineFontProperties(this._font); + + var i; + for (i = 0; i < lines.length; i++) + { + var lineWidth = this.context.measureText(lines[i]).width + ((lines[i].length - 1) * style.letterSpacing); + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + + var width = maxLineWidth + style.strokeThickness; + if (style.dropShadow) + { + width += style.dropShadowDistance; + } + + width += style.padding * 2; + + this.canvas.width = Math.ceil( ( width + this.context.lineWidth ) * this.resolution ); + + // calculate text height + var lineHeight = this.style.lineHeight || fontProperties.fontSize + style.strokeThickness; + + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * lineHeight; + if (style.dropShadow) + { + height += style.dropShadowDistance; + } + + this.canvas.height = Math.ceil( ( height + this._style.padding * 2 ) * this.resolution ); + + this.context.scale( this.resolution, this.resolution); + + if (navigator.isCocoonJS) + { + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + + } + +// this.context.fillStyle="#FF0000"; +// this.context.fillRect(0, 0, this.canvas.width, this.canvas.height); + + this.context.font = this._font; + this.context.strokeStyle = style.stroke; + this.context.lineWidth = style.strokeThickness; + this.context.textBaseline = style.textBaseline; + this.context.lineJoin = style.lineJoin; + this.context.miterLimit = style.miterLimit; + + var linePositionX; + var linePositionY; + + if (style.dropShadow) + { + if (style.dropShadowBlur > 0) { + this.context.shadowColor = style.dropShadowColor; + this.context.shadowBlur = style.dropShadowBlur; + } else { + this.context.fillStyle = style.dropShadowColor; + } + + var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + + for (i = 0; i < lines.length; i++) + { + linePositionX = style.strokeThickness / 2; + linePositionY = (style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent; + + if (style.align === 'right') + { + linePositionX += maxLineWidth - lineWidths[i]; + } + else if (style.align === 'center') + { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (style.fill) + { + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); + + if (style.stroke && style.strokeThickness) + { + this.context.strokeStyle = style.dropShadowColor; + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding, true); + this.context.strokeStyle = style.stroke; + } + } + } + } + + //set canvas text styles + this.context.fillStyle = this._generateFillStyle(style, lines); + + //draw lines line by line + for (i = 0; i < lines.length; i++) + { + linePositionX = style.strokeThickness / 2; + linePositionY = (style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent; + + if (style.align === 'right') + { + linePositionX += maxLineWidth - lineWidths[i]; + } + else if (style.align === 'center') + { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (style.stroke && style.strokeThickness) + { + this.drawLetterSpacing(lines[i], linePositionX + style.padding, linePositionY + style.padding, true); + } + + if (style.fill) + { + this.drawLetterSpacing(lines[i], linePositionX + style.padding, linePositionY + style.padding); + } + } + + this.updateTexture(); +}; + +/** + * Render the text with letter-spacing. + * @param {string} text - The text to draw + * @param {number} x - Horizontal position to draw the text + * @param {number} y - Vertical position to draw the text + * @param {boolean} isStroke - Is this drawing for the outside stroke of the text? If not, it's for the inside fill + * @private + */ +Text.prototype.drawLetterSpacing = function(text, x, y, isStroke) +{ + var style = this._style; + + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + + if (letterSpacing === 0) + { + if (isStroke) + { + this.context.strokeText(text, x, y); + } + else + { + this.context.fillText(text, x, y); + } + return; + } + + var characters = String.prototype.split.call(text, ''), + index = 0, + current, + currentPosition = x; + + while (index < text.length) + { + current = characters[index++]; + if (isStroke) + { + this.context.strokeText(current, currentPosition, y); + } + else + { + this.context.fillText(current, currentPosition, y); + } + currentPosition += this.context.measureText(current).width + letterSpacing; + } +}; + +/** + * Updates texture size based on canvas size + * + * @private + */ +Text.prototype.updateTexture = function () +{ + var texture = this._texture; + var style = this._style; + + texture.baseTexture.hasLoaded = true; + texture.baseTexture.resolution = this.resolution; + + texture.baseTexture.realWidth = this.canvas.width; + texture.baseTexture.realHeight = this.canvas.height; + texture.baseTexture.width = this.canvas.width / this.resolution; + texture.baseTexture.height = this.canvas.height / this.resolution; + texture.trim.width = texture._frame.width = this.canvas.width / this.resolution; + texture.trim.height = texture._frame.height = this.canvas.height / this.resolution; + + texture.trim.x = -style.padding; + texture.trim.y = -style.padding; + + texture.orig.width = texture._frame.width- style.padding*2; + texture.orig.height = texture._frame.height - style.padding*2; + + //call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + + texture.baseTexture.emit('update', texture.baseTexture); + + this.dirty = false; +}; + +/** + * Renders the object using the WebGL renderer + * + * @param renderer {PIXI.WebGLRenderer} The renderer + */ +Text.prototype.renderWebGL = function (renderer) +{ + if(this.resolution !== renderer.resolution) + { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + Sprite.prototype.renderWebGL.call(this, renderer); +}; + +/** + * Renders the object using the Canvas renderer + * + * @param renderer {PIXI.CanvasRenderer} The renderer + * @private + */ +Text.prototype._renderCanvas = function (renderer) +{ + if(this.resolution !== renderer.resolution) + { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + Sprite.prototype._renderCanvas.call(this, renderer); +}; + +/** + * Calculates the ascent, descent and fontSize of a given fontStyle + * + * @param fontStyle {string} String representing the style of the font + * @return {Object} Font properties object + * @private + */ +Text.prototype.determineFontProperties = function (fontStyle) +{ + var properties = Text.fontPropertiesCache[fontStyle]; + + if (!properties) + { + properties = {}; + + var canvas = Text.fontPropertiesCanvas; + var context = Text.fontPropertiesContext; + + context.font = fontStyle; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('M').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = fontStyle; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i, j; + + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; i++) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + if (!stop) + { + idx += line; + } + else + { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; i--) + { + for (j = 0; j < line; j += 4) + { + if (imagedata[idx + j] !== 255) + { + stop = true; + break; + } + } + if (!stop) + { + idx -= line; + } + else + { + break; + } + } + + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + + Text.fontPropertiesCache[fontStyle] = properties; + } + + return properties; +}; + +/** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @param text {string} String to apply word wrapping to + * @return {string} New string with new lines applied where required + * @private + */ +Text.prototype.wordWrap = function (text) +{ + // Greedy wrapping algorithm that will wrap words as the line grows longer + // than its horizontal bounds. + var result = ''; + var lines = text.split('\n'); + var wordWrapWidth = this._style.wordWrapWidth; + for (var i = 0; i < lines.length; i++) + { + var spaceLeft = wordWrapWidth; + var words = lines[i].split(' '); + for (var j = 0; j < words.length; j++) + { + var wordWidth = this.context.measureText(words[j]).width; + if (this._style.breakWords && wordWidth > wordWrapWidth) + { + // Word should be split in the middle + var characters = words[j].split(''); + for (var c = 0; c < characters.length; c++) + { + var characterWidth = this.context.measureText(characters[c]).width; + if (characterWidth > spaceLeft) + { + result += '\n' + characters[c]; + spaceLeft = wordWrapWidth - characterWidth; + } + else + { + if (c === 0) + { + result += ' '; + } + result += characters[c]; + spaceLeft -= characterWidth; + } + } + } + else + { + var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; + if (j === 0 || wordWidthWithSpace > spaceLeft) + { + // Skip printing the newline if it's the first word of the line that is + // greater than the word wrap width. + if (j > 0) + { + result += '\n'; + } + result += words[j]; + spaceLeft = wordWrapWidth - wordWidth; + } + else + { + spaceLeft -= wordWidthWithSpace; + result += ' ' + words[j]; + } + } + } + + if (i < lines.length-1) + { + result += '\n'; + } + } + return result; +}; + +/** + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + */ +Text.prototype._calculateBounds = function () +{ + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); +}; + +/** + * Method to be called upon a TextStyle change. + * @private + */ +Text.prototype._onStyleChange = function () +{ + this.dirty = true; +}; + +/** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * @return string|Number|CanvasGradient + * @private + */ +Text.prototype._generateFillStyle = function (style, lines) +{ + if (!Array.isArray(style.fill)) + { + return style.fill; + } + else + { + // cocoon on canvas+ cannot generate textures, so use the first colour instead + if ( navigator.isCocoonJS ) { + return style.fill[0]; + } + + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var i; + var gradient; + var totalIterations; + var currentIteration; + var stop; + + var width = this.canvas.width / this.resolution; + var height = this.canvas.height / this.resolution; + + if (style.fillGradientType === CONST.TEXT_GRADIENT.LINEAR_VERTICAL) + { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); + + // we need to repeat the gradient so that each invididual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + totalIterations = ( style.fill.length + 1 ) * lines.length; + currentIteration = 0; + for (i = 0; i < lines.length; i++) + { + currentIteration += 1; + for (var j = 0; j < style.fill.length; j++) + { + stop = (currentIteration / totalIterations); + gradient.addColorStop(stop, style.fill[j]); + currentIteration++; + } + } + } + else + { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); + + // can just evenly space out the gradients in this case, as multiple lines makes no difference to an even left to right gradient + totalIterations = style.fill.length + 1; + currentIteration = 1; + + for (i = 0; i < style.fill.length; i++) + { + stop = currentIteration / totalIterations; + gradient.addColorStop(stop, style.fill[i]); + currentIteration++; + } + } + + return gradient; + } +}; + +/** + * Destroys this text object. + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majorety of the time the texture will not be shared with any other Sprites. + * + * @param [options] {object|boolean} Options parameter. A boolean will act as if all options have been set to that value + * @param [options.children=false] {boolean} if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param [options.texture=true] {boolean} Should it destroy the current texture of the sprite as well + * @param [options.baseTexture=true] {boolean} Should it destroy the base texture of the sprite as well + */ +Text.prototype.destroy = function (options) +{ + if (typeof options === 'boolean') { + options = { children: options }; + } + + options = Object.assign({}, defaultDestroyOptions, options); + + Sprite.prototype.destroy.call(this, options); + + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + + this._style = null; +}; + +},{"../const":43,"../math":67,"../sprites/Sprite":98,"../textures/Texture":109,"../utils":116,"./TextStyle":105}],105:[function(require,module,exports){ +var CONST = require('../const'), + utils = require('../utils'); + +/** + * A TextStyle Object decorates a Text Object. It can be shared between + * multiple Text objects. Changing the style will update all text objects using it. + * + * @class + * @memberof PIXI + * @param [style] {object} The style parameters + * @param [style.align='left'] {string} Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text + * @param [style.breakWords=false] {boolean} Indicates if lines can be wrapped within words, it needs wordWrap to be set to true + * @param [style.dropShadow=false] {boolean} Set a drop shadow for the text + * @param [style.dropShadowAngle=Math.PI/6] {number} Set a angle of the drop shadow + * @param [style.dropShadowBlur=0] {number} Set a shadow blur radius + * @param [style.dropShadowColor='#000000'] {string} A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param [style.dropShadowDistance=5] {number} Set a distance of the drop shadow + * @param [style.fill='black'] {string|string[]|number|number[]|CanvasGradient|CanvasPattern} A canvas fillstyle that will be used on the + * text e.g 'red', '#00FF00'. Can be an array to create a gradient eg ['#000000','#FFFFFF'] @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] {number} If fills styles are supplied, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} for possible values + * @param [style.fontFamily='Arial'] {string} The font family + * @param [style.fontSize=26] {number|string} The font size (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em') + * @param [style.fontStyle='normal'] {string} The font style ('normal', 'italic' or 'oblique') + * @param [style.fontVariant='normal'] {string} The font variant ('normal' or 'small-caps') + * @param [style.fontWeight='normal'] {string} The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900') + * @param [style.letterSpacing=0] {number} The amount of spacing between letters, default is 0 + * @param [style.lineHeight] {number} The line height, a number that represents the vertical space that a letter uses + * @param [style.lineJoin='miter'] {string} The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Default is 'miter' (creates a sharp corner). + * @param [style.miterLimit=10] {number} The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param [style.padding=0] {number} Occasionally some fonts are cropped on top or bottom. Adding some padding will + * prevent this from happening by adding padding to the top and bottom of text height. + * @param [style.stroke='black'] {string|number} A canvas fillstyle that will be used on the text stroke e.g 'blue', '#FCFF00' + * @param [style.strokeThickness=0] {number} A number that represents the thickness of the stroke. Default is 0 (no stroke) + * @param [style.textBaseline='alphabetic'] {string} The baseline of the text that is rendered. + * @param [style.wordWrap=false] {boolean} Indicates if word wrap should be used + * @param [style.wordWrapWidth=100] {number} The width at which text will wrap, it needs wordWrap to be set to true + */ +function TextStyle(style) +{ + this.styleID = 0; + Object.assign(this, this._defaults, style); +} + +TextStyle.prototype.constructor = TextStyle; +module.exports = TextStyle; + +// Default settings. Explained in the constructor. +TextStyle.prototype._defaults = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: '#000000', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: CONST.TEXT_GRADIENT.LINEAR_VERTICAL, + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + wordWrap: false, + wordWrapWidth: 100 +}; + +/** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return {PIXI.TextStyle} New cloned TextStyle object + */ +TextStyle.prototype.clone = function () +{ + var clonedProperties = {}; + for (var key in this._defaults) + { + clonedProperties[key] = this[key]; + } + return new TextStyle(clonedProperties); +}; + +/** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ +TextStyle.prototype.reset = function () +{ + Object.assign(this, this._defaults); +}; + +/** + * Create setters and getters for each of the style properties. Converts colors where necessary. + */ +Object.defineProperties(TextStyle.prototype, { + align: { + get: function () + { + return this._align; + }, + set: function (align) + { + if (this._align !== align) + { + this._align = align; + this.styleID++; + } + } + }, + + breakWords: { + get: function () + { + return this._breakWords; + }, + set: function (breakWords) + { + if (this._breakWords !== breakWords) + { + this._breakWords = breakWords; + this.styleID++; + } + } + }, + + dropShadow: { + get: function () + { + return this._dropShadow; + }, + set: function (dropShadow) + { + if (this._dropShadow !== dropShadow) + { + this._dropShadow = dropShadow; + this.styleID++; + } + } + }, + + dropShadowAngle: { + get: function () + { + return this._dropShadowAngle; + }, + set: function (dropShadowAngle) + { + if (this._dropShadowAngle !== dropShadowAngle) + { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + } + }, + + dropShadowBlur: { + get: function () + { + return this._dropShadowBlur; + }, + set: function (dropShadowBlur) + { + if (this._dropShadowBlur !== dropShadowBlur) + { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + } + }, + + dropShadowColor: { + get: function () + { + return this._dropShadowColor; + }, + set: function (dropShadowColor) + { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) + { + this._dropShadowColor = outputColor; + this.styleID++; + } + } + }, + + dropShadowDistance: { + get: function () + { + return this._dropShadowDistance; + }, + set: function (dropShadowDistance) + { + if (this._dropShadowDistance !== dropShadowDistance) + { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + } + }, + + fill: { + get: function () + { + return this._fill; + }, + set: function (fill) + { + var outputColor = getColor(fill); + if (this._fill !== outputColor) + { + this._fill = outputColor; + this.styleID++; + } + } + }, + + fillGradientType: { + get: function () + { + return this._fillGradientType; + }, + set: function (fillGradientType) + { + if (this._fillGradientType !== fillGradientType) + { + this._fillGradientType = fillGradientType; + this.styleID++; + } + } + }, + + fontFamily: { + get: function () + { + return this._fontFamily; + }, + set: function (fontFamily) + { + if (this.fontFamily !== fontFamily) + { + this._fontFamily = fontFamily; + this.styleID++; + } + } + }, + + fontSize: { + get: function () + { + return this._fontSize; + }, + set: function (fontSize) + { + if (this._fontSize !== fontSize) + { + this._fontSize = fontSize; + this.styleID++; + } + } + }, + + fontStyle: { + get: function () + { + return this._fontStyle; + }, + set: function (fontStyle) + { + if (this._fontStyle !== fontStyle) + { + this._fontStyle = fontStyle; + this.styleID++; + } + } + }, + + fontVariant: { + get: function () + { + return this._fontVariant; + }, + set: function (fontVariant) + { + if (this._fontVariant !== fontVariant) + { + this._fontVariant = fontVariant; + this.styleID++; + } + } + }, + + fontWeight: { + get: function () + { + return this._fontWeight; + }, + set: function (fontWeight) + { + if (this._fontWeight !== fontWeight) + { + this._fontWeight = fontWeight; + this.styleID++; + } + } + }, + + letterSpacing: { + get: function () + { + return this._letterSpacing; + }, + set: function (letterSpacing) + { + if (this._letterSpacing !== letterSpacing) + { + this._letterSpacing = letterSpacing; + this.styleID++; + } + } + }, + + lineHeight: { + get: function () + { + return this._lineHeight; + }, + set: function (lineHeight) + { + if (this._lineHeight !== lineHeight) + { + this._lineHeight = lineHeight; + this.styleID++; + } + } + }, + + lineJoin: { + get: function () + { + return this._lineJoin; + }, + set: function (lineJoin) + { + if (this._lineJoin !== lineJoin) + { + this._lineJoin = lineJoin; + this.styleID++; + } + } + }, + + miterLimit: { + get: function () + { + return this._miterLimit; + }, + set: function (miterLimit) + { + if (this._miterLimit !== miterLimit) + { + this._miterLimit = miterLimit; + this.styleID++; + } + } + }, + + padding: { + get: function () + { + return this._padding; + }, + set: function (padding) + { + if (this._padding !== padding) + { + this._padding = padding; + this.styleID++; + } + } + }, + + stroke: { + get: function () + { + return this._stroke; + }, + set: function (stroke) + { + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) + { + this._stroke = outputColor; + this.styleID++; + } + } + }, + + strokeThickness: { + get: function () + { + return this._strokeThickness; + }, + set: function (strokeThickness) + { + if (this._strokeThickness !== strokeThickness) + { + this._strokeThickness = strokeThickness; + this.styleID++; + } + } + }, + + textBaseline: { + get: function () + { + return this._textBaseline; + }, + set: function (textBaseline) + { + if (this._textBaseline !== textBaseline) + { + this._textBaseline = textBaseline; + this.styleID++; + } + } + }, + + wordWrap: { + get: function () + { + return this._wordWrap; + }, + set: function (wordWrap) + { + if (this._wordWrap !== wordWrap) + { + this._wordWrap = wordWrap; + this.styleID++; + } + } + }, + + wordWrapWidth: { + get: function () + { + return this._wordWrapWidth; + }, + set: function (wordWrapWidth) + { + if (this._wordWrapWidth !== wordWrapWidth) + { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + } + } +}); + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * + * @return {string} The color as a string. + */ +function getColor(color) +{ + if (typeof color === 'number') + { + return utils.hex2string(color); + } + else if (Array.isArray(color)) + { + for (var i = 0; i < color.length; ++i) + { + if (typeof color[i] === 'number') + { + color[i] = utils.hex2string(color[i]); + } + } + } + + return color; +} + +},{"../const":43,"../utils":116}],106:[function(require,module,exports){ +var BaseTexture = require('./BaseTexture'), + CONST = require('../const'); + +/** + * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * var renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * var BaserenderTexture = new PIXI.BaseRenderTexture(renderer, 800, 600); + * var sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * BaserenderTexture.render(sprite); + * ``` + * + * The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual + * position a Container should be used: + * + * ```js + * var doc = new PIXI.Container(); + * + * doc.addChild(sprite); + * + * var baseRenderTexture = new PIXI.BaserenderTexture(100, 100); + * var renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(doc, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + * @param [width=100] {number} The width of the base render texture + * @param [height=100] {number} The height of the base render texture + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @param [resolution=1] {number} The resolution / device pixel ratio of the texture being generated + */ +function BaseRenderTexture(width, height, scaleMode, resolution) +{ + BaseTexture.call(this, null, scaleMode); + + this.resolution = resolution || CONST.RESOLUTION; + + this.width = width || 100; + this.height = height || 100; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + this.scaleMode = scaleMode || CONST.SCALE_MODES.DEFAULT; + this.hasLoaded = true; + + /** + * A map of renderer IDs to webgl renderTargets + * + * @member {object} + * @private + */ + this._glRenderTargets = []; + + /** + * A reference to the canvas render target (we only need one as this can be shared accross renderers) + * + * @member {object} + * @private + */ + this._canvasRenderTarget = null; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + this.valid = false; +} + +BaseRenderTexture.prototype = Object.create(BaseTexture.prototype); +BaseRenderTexture.prototype.constructor = BaseRenderTexture; +module.exports = BaseRenderTexture; + +/** + * Resizes the BaseRenderTexture. + * + * @param width {number} The width to resize to. + * @param height {number} The height to resize to. + */ +BaseRenderTexture.prototype.resize = function (width, height) +{ + + if (width === this.width && height === this.height) + { + return; + } + + this.valid = (width > 0 && height > 0); + + this.width = width; + this.height = height; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + if (!this.valid) + { + return; + } + + this.emit('update', this); + +}; + +/** + * Destroys this texture + * + */ +BaseRenderTexture.prototype.destroy = function () +{ + BaseTexture.prototype.destroy.call(this, true); + this.renderer = null; +}; + + +},{"../const":43,"./BaseTexture":107}],107:[function(require,module,exports){ +var utils = require('../utils'), + CONST = require('../const'), + EventEmitter = require('eventemitter3'), + determineCrossOrigin = require('../utils/determineCrossOrigin'), + bitTwiddle = require('bit-twiddle'); + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class + * @memberof PIXI + * @param [source ]{HTMLImageElement|HTMLCanvasElement} the source object of the texture. + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @param [resolution=1] {number} The resolution / device pixel ratio of the texture + */ +function BaseTexture(source, scaleMode, resolution) +{ + EventEmitter.call(this); + + this.uid = utils.uid(); + + this.touched = 0; + + /** + * The resolution / device pixel ratio of the texture + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || CONST.RESOLUTION; + + /** + * The width of the base texture set when the image has loaded + * + * @member {number} + * @readonly + */ + this.width = 100; + + /** + * The height of the base texture set when the image has loaded + * + * @member {number} + * @readonly + */ + this.height = 100; + + // TODO docs + // used to store the actual dimensions of the source + /** + * Used to store the actual width of the source of this texture + * + * @member {number} + * @readonly + */ + this.realWidth = 100; + /** + * Used to store the actual height of the source of this texture + * + * @member {number} + * @readonly + */ + this.realHeight = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @member {number} + * @default PIXI.SCALE_MODES.DEFAULT + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode || CONST.SCALE_MODES.DEFAULT; + + /** + * Set to true once the base texture has successfully loaded. + * + * This is never true if the underlying source fails to load or has no texture data. + * + * @member {boolean} + * @readonly + */ + this.hasLoaded = false; + + /** + * Set to true if the source is currently loading. + * + * If an Image source is loading the 'loaded' or 'error' event will be + * dispatched when the operation ends. An underyling source that is + * immediately-available bypasses loading entirely. + * + * @member {boolean} + * @readonly + */ + this.isLoading = false; + + /** + * The image source that is used to create the texture. + * + * TODO: Make this a setter that calls loadSource(); + * + * @member {HTMLImageElement|HTMLCanvasElement} + * @readonly + */ + this.source = null; // set in loadSource, if at all + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * All blend modes, and shaders written for default value. Change it on your own risk. + * + * @member {boolean} + * @default true + */ + this.premultipliedAlpha = true; + + /** + * The image url of the texture + * + * @member {string} + */ + this.imageUrl = null; + + /** + * Wether or not the texture is a power of two, try to use power of two textures as much as you can + * @member {boolean} + * @private + */ + this.isPowerOfTwo = false; + + // used for webGL + + /** + * + * Set this to true if a mipmap of this texture needs to be generated. This value needs to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @member {boolean} + * @see PIXI.MIPMAP_TEXTURES + */ + this.mipmap = CONST.MIPMAP_TEXTURES; + + /** + * + * WebGL Texture wrap mode + * + * @member {number} + * @see PIXI.WRAP_MODES + */ + this.wrapMode = CONST.WRAP_MODES.DEFAULT; + + /** + * A map of renderer IDs to webgl textures + * + * @member {object} + * @private + */ + this._glTextures = []; + this._enabled = 0; + this._id = 0; + + // if no source passed don't try to load + if (source) + { + this.loadSource(source); + } + + /** + * Fired when a not-immediately-available source finishes loading. + * + * @event loaded + * @memberof PIXI.BaseTexture# + * @protected + */ + + /** + * Fired when a not-immediately-available source fails to load. + * + * @event error + * @memberof PIXI.BaseTexture# + * @protected + */ +} + +BaseTexture.prototype = Object.create(EventEmitter.prototype); +BaseTexture.prototype.constructor = BaseTexture; +module.exports = BaseTexture; + +/** + * Updates the texture on all the webgl renderers, this also assumes the src has changed. + * + * @fires update + */ +BaseTexture.prototype.update = function () +{ + this.realWidth = this.source.naturalWidth || this.source.videoWidth || this.source.width; + this.realHeight = this.source.naturalHeight || this.source.videoHeight || this.source.height; + + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); + + this.emit('update', this); +}; + +/** + * Load a source. + * + * If the source is not-immediately-available, such as an image that needs to be + * downloaded, then the 'loaded' or 'error' event will be dispatched in the future + * and `hasLoaded` will remain false after this call. + * + * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: + * + * if (texture.hasLoaded) { + * // texture ready for use + * } else if (texture.isLoading) { + * // listen to 'loaded' and/or 'error' events on texture + * } else { + * // not loading, not going to load UNLESS the source is reloaded + * // (it may still make sense to listen to the events) + * } + * + * @protected + * @param source {HTMLImageElement|HTMLCanvasElement} the source object of the texture. + */ +BaseTexture.prototype.loadSource = function (source) +{ + var wasLoading = this.isLoading; + this.hasLoaded = false; + this.isLoading = false; + + if (wasLoading && this.source) + { + this.source.onload = null; + this.source.onerror = null; + } + + this.source = source; + + // Apply source if loaded. Otherwise setup appropriate loading monitors. + if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height) + { + this._sourceLoaded(); + } + else if (!source.getContext) + { + + // Image fail / not ready + this.isLoading = true; + + var scope = this; + + source.onload = function () + { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) + { + return; + } + + scope.isLoading = false; + scope._sourceLoaded(); + + scope.emit('loaded', scope); + }; + + source.onerror = function () + { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) + { + return; + } + + scope.isLoading = false; + scope.emit('error', scope); + }; + + // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element + // "The value of `complete` can thus change while a script is executing." + // So complete needs to be re-checked after the callbacks have been added.. + // NOTE: complete will be true if the image has no src so best to check if the src is set. + if (source.complete && source.src) + { + this.isLoading = false; + + // ..and if we're complete now, no need for callbacks + source.onload = null; + source.onerror = null; + + if (source.width && source.height) + { + this._sourceLoaded(); + + // If any previous subscribers possible + if (wasLoading) + { + this.emit('loaded', this); + } + } + else + { + // If any previous subscribers possible + if (wasLoading) + { + this.emit('error', this); + } + } + } + } +}; + +/** + * Used internally to update the width, height, and some other tracking vars once + * a source has successfully loaded. + * + * @private + */ +BaseTexture.prototype._sourceLoaded = function () +{ + this.hasLoaded = true; + this.update(); +}; + +/** + * Destroys this base texture + * + */ +BaseTexture.prototype.destroy = function () +{ + if (this.imageUrl) + { + delete utils.BaseTextureCache[this.imageUrl]; + delete utils.TextureCache[this.imageUrl]; + + this.imageUrl = null; + + if (!navigator.isCocoonJS) + { + this.source.src = ''; + } + } + else if (this.source && this.source._pixiId) + { + delete utils.BaseTextureCache[this.source._pixiId]; + } + + this.source = null; + + this.dispose(); +}; + +/** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + */ +BaseTexture.prototype.dispose = function () +{ + this.emit('dispose', this); + + // this should no longer be needed, the renderers should cleanup all the gl textures. + // this._glTextures = {}; +}; + +/** + * Changes the source image of the texture. + * The original source must be an Image element. + * + * @param newSrc {string} the path of the image + */ +BaseTexture.prototype.updateSourceImage = function (newSrc) +{ + this.source.src = newSrc; + + this.loadSource(this.source); +}; + +/** + * Helper function that creates a base texture from the given image url. + * If the image is not in the base texture cache it will be created and loaded. + * + * @static + * @param imageUrl {string} The image url of the texture + * @param [crossorigin=(auto)] {boolean} Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @return PIXI.BaseTexture + */ +BaseTexture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ + var baseTexture = utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) + { + // new Image() breaks tex loading in some versions of Chrome. + // See https://code.google.com/p/chromium/issues/detail?id=238071 + var image = new Image();//document.createElement('img'); + + + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) + { + image.crossOrigin = determineCrossOrigin(imageUrl); + } + + baseTexture = new BaseTexture(image, scaleMode); + baseTexture.imageUrl = imageUrl; + + image.src = imageUrl; + + utils.BaseTextureCache[imageUrl] = baseTexture; + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = utils.getResolutionOfUrl(imageUrl); + } + + return baseTexture; +}; + +/** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @param canvas {HTMLCanvasElement} The canvas element source of the texture + * @param scaleMode {number} See {@link PIXI.SCALE_MODES} for possible values + * @return PIXI.BaseTexture + */ +BaseTexture.fromCanvas = function (canvas, scaleMode) +{ + if (!canvas._pixiId) + { + canvas._pixiId = 'canvas_' + utils.uid(); + } + + var baseTexture = utils.BaseTextureCache[canvas._pixiId]; + + if (!baseTexture) + { + baseTexture = new BaseTexture(canvas, scaleMode); + utils.BaseTextureCache[canvas._pixiId] = baseTexture; + } + + return baseTexture; +}; + +},{"../const":43,"../utils":116,"../utils/determineCrossOrigin":115,"bit-twiddle":1,"eventemitter3":3}],108:[function(require,module,exports){ +var BaseRenderTexture = require('./BaseRenderTexture'), + Texture = require('./Texture'); + +/** + * A RenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * var renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * var renderTexture = PIXI.RenderTexture.create(800, 600); + * var sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual + * position a Container should be used: + * + * ```js + * var doc = new PIXI.Container(); + * + * doc.addChild(sprite); + * + * renderer.render(doc, renderTexture); // Renders to center of renderTexture + * ``` + * + * @class + * @extends PIXI.Texture + * @memberof PIXI + * @param baseRenderTexture {PIXI.BaseRenderTexture} The renderer used for this RenderTexture + * @param [frame] {PIXI.Rectangle} The rectangle frame of the texture to show + */ +function RenderTexture(baseRenderTexture, frame) +{ + // suport for legacy.. + this.legacyRenderer = null; + + if( !(baseRenderTexture instanceof BaseRenderTexture) ) + { + var width = arguments[1]; + var height = arguments[2]; + var scaleMode = arguments[3] || 0; + var resolution = arguments[4] || 1; + + // we have an old render texture.. + console.warn('v4 RenderTexture now expects a new BaseRenderTexture. Please use RenderTexture.create('+width+', '+height+')'); // jshint ignore:line + this.legacyRenderer = arguments[0]; + + frame = null; + baseRenderTexture = new BaseRenderTexture(width, height, scaleMode, resolution); + } + + + /** + * The base texture object that this texture uses + * + * @member {BaseTexture} + */ + Texture.call(this, + baseRenderTexture, + frame + ); + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + this.valid = true; + + this._updateUvs(); +} + +RenderTexture.prototype = Object.create(Texture.prototype); +RenderTexture.prototype.constructor = RenderTexture; +module.exports = RenderTexture; + +/** + * Resizes the RenderTexture. + * + * @param width {number} The width to resize to. + * @param height {number} The height to resize to. + * @param doNotResizeBaseTexture {boolean} Should the baseTexture.width and height values be resized as well? + */ +RenderTexture.prototype.resize = function (width, height, doNotResizeBaseTexture) +{ + + //TODO - could be not required.. + this.valid = (width > 0 && height > 0); + + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + + if (!doNotResizeBaseTexture) + { + this.baseTexture.resize(width, height); + } + + this._updateUvs(); +}; + +/** + * A short hand way of creating a render texture.. + * @param [width=100] {number} The width of the render texture + * @param [height=100] {number} The height of the render texture + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @param [resolution=1] {number} The resolution / device pixel ratio of the texture being generated + */ +RenderTexture.create = function(width, height, scaleMode, resolution) +{ + return new RenderTexture(new BaseRenderTexture(width, height, scaleMode, resolution)); +}; + +},{"./BaseRenderTexture":106,"./Texture":109}],109:[function(require,module,exports){ +var BaseTexture = require('./BaseTexture'), + VideoBaseTexture = require('./VideoBaseTexture'), + TextureUvs = require('./TextureUvs'), + EventEmitter = require('eventemitter3'), + math = require('../math'), + utils = require('../utils'); + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * var texture = PIXI.Texture.fromImage('assets/image.png'); + * var sprite1 = new PIXI.Sprite(texture); + * var sprite2 = new PIXI.Sprite(texture); + * ``` + * + * @class + * @memberof PIXI + * @param baseTexture {PIXI.BaseTexture} The base texture source to create the texture from + * @param [frame] {PIXI.Rectangle} The rectangle frame of the texture to show + * @param [orig] {PIXI.Rectangle} The area of original texture + * @param [trim] {PIXI.Rectangle} Trimmed rectangle of original texture + * @param [rotate] {number} indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8} + */ +function Texture(baseTexture, frame, orig, trim, rotate) +{ + EventEmitter.call(this); + + /** + * Does this Texture have any frame data assigned to it? + * + * @member {boolean} + */ + this.noFrame = false; + + if (!frame) + { + this.noFrame = true; + frame = new math.Rectangle(0, 0, 1, 1); + } + + if (baseTexture instanceof Texture) + { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @member {PIXI.BaseTexture} + */ + this.baseTexture = baseTexture; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @member {PIXI.Rectangle} + */ + this._frame = frame; + + /** + * This is the trimmed area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + this.valid = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @member {boolean} + */ + this.requiresUpdate = false; + + /** + * The WebGL UV data cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + this._uvs = null; + + /** + * This is the area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + this.orig = orig || frame;//new math.Rectangle(0, 0, 1, 1); + + this._rotate = +(rotate || 0); + + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + this._rotate = 2; + } else { + if (this._rotate % 2 !== 0) { + throw 'attempt to use diamond-shaped UVs. If you are sure, set rotation manually'; + } + } + + if (baseTexture.hasLoaded) + { + if (this.noFrame) + { + frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + + // if there is no frame we should monitor for any base texture changes.. + baseTexture.on('update', this.onBaseTextureUpdated, this); + } + this.frame = frame; + } + else + { + baseTexture.once('loaded', this.onBaseTextureLoaded, this); + } + + /** + * Fired when the texture is updated. This happens if the frame or the baseTexture is updated. + * + * @event update + * @memberof PIXI.Texture# + * @protected + */ + + + this._updateID = 0; +} + +Texture.prototype = Object.create(EventEmitter.prototype); +Texture.prototype.constructor = Texture; +module.exports = Texture; + +Object.defineProperties(Texture.prototype, { + /** + * The frame specifies the region of the base texture that this texture uses. + * + * @member {PIXI.Rectangle} + * @memberof PIXI.Texture# + */ + frame: { + get: function () + { + return this._frame; + }, + set: function (frame) + { + this._frame = frame; + + this.noFrame = false; + + if (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height) + { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this); + } + + //this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + this.valid = frame && frame.width && frame.height && this.baseTexture.hasLoaded; + + if (!this.trim && !this.rotate) + { + this.orig = frame; + } + + if (this.valid) + { + this._updateUvs(); + } + } + }, + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.GroupD8} for explanation + * + * @member {number} + */ + rotate: { + get: function () + { + return this._rotate; + }, + set: function (rotate) + { + this._rotate = rotate; + if (this.valid) + { + this._updateUvs(); + } + } + }, + + /** + * The width of the Texture in pixels. + * + * @member {number} + */ + width: { + get: function() { + return this.orig ? this.orig.width : 0; + } + }, + + /** + * The height of the Texture in pixels. + * + * @member {number} + */ + height: { + get: function() { + return this.orig ? this.orig.height : 0; + } + } +}); + +/** + * Updates this texture on the gpu. + * + */ +Texture.prototype.update = function () +{ + this.baseTexture.update(); +}; + +/** + * Called when the base texture is loaded + * + * @private + */ +Texture.prototype.onBaseTextureLoaded = function (baseTexture) +{ + this._updateID++; + + // TODO this code looks confusing.. boo to abusing getters and setterss! + if (this.noFrame) + { + this.frame = new math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } + else + { + this.frame = this._frame; + } + + this.baseTexture.on('update', this.onBaseTextureUpdated, this); + this.emit('update', this); + +}; + +/** + * Called when the base texture is updated + * + * @private + */ +Texture.prototype.onBaseTextureUpdated = function (baseTexture) +{ + this._updateID++; + + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + + this.emit('update', this); +}; + +/** + * Destroys this texture + * + * @param [destroyBase=false] {boolean} Whether to destroy the base texture as well + */ +Texture.prototype.destroy = function (destroyBase) +{ + if (this.baseTexture) + { + + if (destroyBase) + { + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destoryed too.. + if(utils.TextureCache[this.baseTexture.imageUrl]) + { + delete utils.TextureCache[this.baseTexture.imageUrl]; + } + + this.baseTexture.destroy(); + } + + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); + + this.baseTexture = null; + } + + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + + this.valid = false; + + this.off('dispose', this.dispose, this); + this.off('update', this.update, this); +}; + +/** + * Creates a new texture object that acts the same as this one. + * + * @return {PIXI.Texture} + */ +Texture.prototype.clone = function () +{ + return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); +}; + +/** + * Updates the internal WebGL UV cache. + * + * @protected + */ +Texture.prototype._updateUvs = function () +{ + if (!this._uvs) + { + this._uvs = new TextureUvs(); + } + + this._uvs.set(this._frame, this.baseTexture, this.rotate); + + this._updateID++; +}; + +/** + * Helper function that creates a Texture object from the given image url. + * If the image is not in the texture cache it will be created and loaded. + * + * @static + * @param imageUrl {string} The image url of the texture + * @param [crossorigin] {boolean} Whether requests should be treated as crossorigin + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ +Texture.fromImage = function (imageUrl, crossorigin, scaleMode) +{ + var texture = utils.TextureCache[imageUrl]; + + if (!texture) + { + texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode)); + utils.TextureCache[imageUrl] = texture; + } + + return texture; +}; + +/** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param frameId {string} The frame Id of the texture in the cache + * @return {PIXI.Texture} The newly created texture + */ +Texture.fromFrame = function (frameId) +{ + var texture = utils.TextureCache[frameId]; + + if (!texture) + { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return texture; +}; + +/** + * Helper function that creates a new Texture based on the given canvas element. + * + * @static + * @param canvas {HTMLCanvasElement} The canvas element source of the texture + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ +Texture.fromCanvas = function (canvas, scaleMode) +{ + return new Texture(BaseTexture.fromCanvas(canvas, scaleMode)); +}; + +/** + * Helper function that creates a new Texture based on the given video element. + * + * @static + * @param video {HTMLVideoElement|string} The URL or actual element of the video + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ +Texture.fromVideo = function (video, scaleMode) +{ + if (typeof video === 'string') + { + return Texture.fromVideoUrl(video, scaleMode); + } + else + { + return new Texture(VideoBaseTexture.fromVideo(video, scaleMode)); + } +}; + +/** + * Helper function that creates a new Texture based on the video url. + * + * @static + * @param videoUrl {string} URL of the video + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ +Texture.fromVideoUrl = function (videoUrl, scaleMode) +{ + return new Texture(VideoBaseTexture.fromUrl(videoUrl, scaleMode)); +}; + +/** + * Helper function that creates a new Texture based on the source you provide. + * The soucre can be - frame id, image url, video url, canvae element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ +Texture.from = function (source) +{ + //TODO auto detect cross origin.. + //TODO pass in scale mode? + if(typeof source === 'string') + { + var texture = utils.TextureCache[source]; + + if (!texture) + { + // check if its a video.. + var isVideo = source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/) !== null; + if(isVideo) + { + return Texture.fromVideoUrl(source); + } + + return Texture.fromImage(source); + } + + return texture; + } + else if(source instanceof HTMLCanvasElement) + { + return Texture.fromCanvas(source); + } + else if(source instanceof HTMLVideoElement) + { + return Texture.fromVideo(source); + } + else if(source instanceof BaseTexture) + { + return new Texture(BaseTexture); + } + else + { + // lets assume its a texture! + return source; + } +}; + + +/** + * Adds a texture to the global utils.TextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param texture {PIXI.Texture} The Texture to add to the cache. + * @param id {string} The id that the texture will be stored against. + */ +Texture.addTextureToCache = function (texture, id) +{ + utils.TextureCache[id] = texture; +}; + +/** + * Remove a texture from the global utils.TextureCache. + * + * @static + * @param id {string} The id of the texture to be removed + * @return {PIXI.Texture} The texture that was removed + */ +Texture.removeTextureFromCache = function (id) +{ + var texture = utils.TextureCache[id]; + + delete utils.TextureCache[id]; + delete utils.BaseTextureCache[id]; + + return texture; +}; + +/** + * An empty texture, used often to not have to create multiple empty textures. + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.EMPTY = new Texture(new BaseTexture()); +Texture.EMPTY.destroy = function() {}; +Texture.EMPTY.on = function() {}; +Texture.EMPTY.once = function() {}; +Texture.EMPTY.emit = function() {}; + + +},{"../math":67,"../utils":116,"./BaseTexture":107,"./TextureUvs":110,"./VideoBaseTexture":111,"eventemitter3":3}],110:[function(require,module,exports){ + +/** + * A standard object to store the Uvs of a texture + * + * @class + * @private + * @memberof PIXI + */ +function TextureUvs() +{ + this.x0 = 0; + this.y0 = 0; + + this.x1 = 1; + this.y1 = 0; + + this.x2 = 1; + this.y2 = 1; + + this.x3 = 0; + this.y3 = 1; + + this.uvsUint32 = new Uint32Array(4); +} + +module.exports = TextureUvs; + +var GroupD8 = require('../math/GroupD8'); + +/** + * Sets the texture Uvs based on the given frame information + * @param frame {PIXI.Rectangle} + * @param baseFrame {PIXI.Rectangle} + * @param rotate {number} Rotation of frame, see {@link PIXI.GroupD8} + * @private + */ +TextureUvs.prototype.set = function (frame, baseFrame, rotate) +{ + var tw = baseFrame.width; + var th = baseFrame.height; + + if(rotate) + { + //width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + //coordinates of center + var cX = frame.x / tw + w2; + var cY = frame.y / th + h2; + rotate = GroupD8.add(rotate, GroupD8.NW); //NW is top-left corner + this.x0 = cX + w2 * GroupD8.uX(rotate); + this.y0 = cY + h2 * GroupD8.uY(rotate); + rotate = GroupD8.add(rotate, 2); //rotate 90 degrees clockwise + this.x1 = cX + w2 * GroupD8.uX(rotate); + this.y1 = cY + h2 * GroupD8.uY(rotate); + rotate = GroupD8.add(rotate, 2); + this.x2 = cX + w2 * GroupD8.uX(rotate); + this.y2 = cY + h2 * GroupD8.uY(rotate); + rotate = GroupD8.add(rotate, 2); + this.x3 = cX + w2 * GroupD8.uX(rotate); + this.y3 = cY + h2 * GroupD8.uY(rotate); + } + else + { + + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + + this.uvsUint32[0] = (((this.y0 * 65535) & 0xFFFF) << 16) | ((this.x0 * 65535) & 0xFFFF); + this.uvsUint32[1] = (((this.y1 * 65535) & 0xFFFF) << 16) | ((this.x1 * 65535) & 0xFFFF); + this.uvsUint32[2] = (((this.y2 * 65535) & 0xFFFF) << 16) | ((this.x2 * 65535) & 0xFFFF); + this.uvsUint32[3] = (((this.y3 * 65535) & 0xFFFF) << 16) | ((this.x3 * 65535) & 0xFFFF); +}; + +},{"../math/GroupD8":63}],111:[function(require,module,exports){ +var BaseTexture = require('./BaseTexture'), + utils = require('../utils'); + +/** + * A texture of a [playing] Video. + * + * Video base textures mimic Pixi BaseTexture.from.... method in their creation process. + * + * This can be used in several ways, such as: + * + * ```js + * var texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4'); + * + * var texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' }); + * + * var texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']); + * + * var texture = PIXI.VideoBaseTexture.fromUrls([ + * { src: '/video.webm', mime: 'video/webm' }, + * { src: '/video.mp4', mime: 'video/mp4' } + * ]); + * ``` + * + * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/). + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + * @param source {HTMLVideoElement} Video source + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + */ +function VideoBaseTexture(source, scaleMode) +{ + if (!source) + { + throw new Error('No video source element specified.'); + } + + // hook in here to check if video is already available. + // BaseTexture looks for a source.complete boolean, plus width & height. + + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) + { + source.complete = true; + } + + BaseTexture.call(this, source, scaleMode); + + /** + * Should the base texture automatically update itself, set to true by default + * + * @member {boolean} + * @default true + */ + this.autoUpdate = false; + + this._onUpdate = this._onUpdate.bind(this); + this._onCanPlay = this._onCanPlay.bind(this); + + if (!source.complete) + { + source.addEventListener('canplay', this._onCanPlay); + source.addEventListener('canplaythrough', this._onCanPlay); + + // started playing.. + source.addEventListener('play', this._onPlayStart.bind(this)); + source.addEventListener('pause', this._onPlayStop.bind(this)); + } + + this.__loaded = false; +} + +VideoBaseTexture.prototype = Object.create(BaseTexture.prototype); +VideoBaseTexture.prototype.constructor = VideoBaseTexture; +module.exports = VideoBaseTexture; + +/** + * The internal update loop of the video base texture, only runs when autoUpdate is set to true + * + * @private + */ +VideoBaseTexture.prototype._onUpdate = function () +{ + if (this.autoUpdate) + { + window.requestAnimationFrame(this._onUpdate); + this.update(); + } +}; + +/** + * Runs the update loop when the video is ready to play + * + * @private + */ +VideoBaseTexture.prototype._onPlayStart = function () +{ + // Just in case the video has not recieved its can play even yet.. + if(!this.hasLoaded) + { + this._onCanPlay(); + } + + if (!this.autoUpdate) + { + window.requestAnimationFrame(this._onUpdate); + this.autoUpdate = true; + } +}; + +/** + * Fired when a pause event is triggered, stops the update loop + * + * @private + */ +VideoBaseTexture.prototype._onPlayStop = function () +{ + this.autoUpdate = false; +}; + +/** + * Fired when the video is loaded and ready to play + * + * @private + */ +VideoBaseTexture.prototype._onCanPlay = function () +{ + this.hasLoaded = true; + + if (this.source) + { + this.source.removeEventListener('canplay', this._onCanPlay); + this.source.removeEventListener('canplaythrough', this._onCanPlay); + + this.width = this.source.videoWidth; + this.height = this.source.videoHeight; + + this.source.play(); + + // prevent multiple loaded dispatches.. + if (!this.__loaded) + { + this.__loaded = true; + this.emit('loaded', this); + } + } +}; + +/** + * Destroys this texture + * + */ +VideoBaseTexture.prototype.destroy = function () +{ + if (this.source && this.source._pixiId) + { + delete utils.BaseTextureCache[ this.source._pixiId ]; + delete this.source._pixiId; + } + + BaseTexture.prototype.destroy.call(this); +}; + +/** + * Mimic Pixi BaseTexture.from.... method. + * + * @static + * @param video {HTMLVideoElement} Video to create texture from + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ +VideoBaseTexture.fromVideo = function (video, scaleMode) +{ + if (!video._pixiId) + { + video._pixiId = 'video_' + utils.uid(); + } + + var baseTexture = utils.BaseTextureCache[video._pixiId]; + + if (!baseTexture) + { + baseTexture = new VideoBaseTexture(video, scaleMode); + utils.BaseTextureCache[ video._pixiId ] = baseTexture; + } + + return baseTexture; +}; + +/** + * Helper function that creates a new BaseTexture based on the given video element. + * This BaseTexture can then be used to create a texture + * + * @static + * @param videoSrc {string|object|string[]|object[]} The URL(s) for the video. + * @param [videoSrc.src] {string} One of the source urls for the video + * @param [videoSrc.mime] {string} The mimetype of the video (e.g. 'video/mp4'). If not specified + * the url's extension will be used as the second part of the mime type. + * @param scaleMode {number} See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ +VideoBaseTexture.fromUrl = function (videoSrc, scaleMode) +{ + var video = document.createElement('video'); + + // array of objects or strings + if (Array.isArray(videoSrc)) + { + for (var i = 0; i < videoSrc.length; ++i) + { + video.appendChild(createSource(videoSrc[i].src || videoSrc[i], videoSrc[i].mime)); + } + } + // single object or string + else + { + video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); + } + + video.load(); + video.play(); + + return VideoBaseTexture.fromVideo(video, scaleMode); +}; + +VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; + +function createSource(path, type) +{ + if (!type) + { + type = 'video/' + path.substr(path.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = path; + source.type = type; + + return source; +} + +},{"../utils":116,"./BaseTexture":107}],112:[function(require,module,exports){ +var CONST = require('../const'), + EventEmitter = require('eventemitter3'), + // Internal event used by composed emitter + TICK = 'tick'; + +/** + * A Ticker class that runs an update loop that other objects listen to. + * This class is composed around an EventEmitter object to add listeners + * meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, + * e.g. When the ticker is started and the emitter has listeners. + * + * @class + * @memberof PIXI.ticker + */ +function Ticker() +{ + var _this = this; + + /** + * Internal tick method bound to ticker instance. + * This is because in early 2015, Function.bind + * is still 60% slower in high performance scenarios. + * Also separating frame requests from update method + * so listeners may be called at any time and with + * any animation API, just invoke ticker.update(time). + * + * @private + */ + this._tick = function _tick(time) { + + _this._requestId = null; + + if (_this.started) + { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._emitter.listeners(TICK, true)) + { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + + /** + * Internal emitter used to fire 'tick' event + * @private + */ + this._emitter = new EventEmitter(); + + /** + * Internal current frame request ID + * @private + */ + this._requestId = null; + + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + * @private + */ + this._maxElapsedMS = 100; + + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.ticker.Ticker#start} automatically + * when a listener is added. + * + * @member {boolean} + * @default false + */ + this.autoStart = false; + + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS} + * and is scaled with {@link PIXI.ticker.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * + * @member {number} + * @default 1 + */ + this.deltaTime = 1; + + /** + * Time elapsed in milliseconds from last frame to this frame. + * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime} + * is based, this value is neither capped nor scaled. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default 1 / TARGET_FPMS + */ + this.elapsedMS = 1 / CONST.TARGET_FPMS; // default to target frame time + + /** + * The last time {@link PIXI.ticker.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default 0 + */ + this.lastTime = 0; + + /** + * Factor of current {@link PIXI.ticker.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + * + * @member {number} + * @default 1 + */ + this.speed = 1; + + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.ticker.Ticker#start} has been called. + * `false` if {@link PIXI.ticker.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.ticker.Ticker#autoStart} being `true` + * and a listener is added. + * + * @member {boolean} + * @default false + */ + this.started = false; +} + +Object.defineProperties(Ticker.prototype, { + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.ticker.Ticker#speed}, which is specific + * to scaling {@link PIXI.ticker.Ticker#deltaTime}. + * + * @memberof PIXI.ticker.Ticker# + * @readonly + */ + FPS: { + get: function() + { + return 1000 / this.elapsedMS; + } + }, + + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.ticker.Ticker#update}. + * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.TARGET_FPMS * 1000`. + * + * @memberof PIXI.ticker.Ticker# + * @default 10 + */ + minFPS: { + get: function() + { + return 1000 / this._maxElapsedMS; + }, + set: function(fps) + { + // Clamp: 0 to TARGET_FPMS + var minFPMS = Math.min(Math.max(0, fps) / 1000, CONST.TARGET_FPMS); + this._maxElapsedMS = 1 / minFPMS; + } + } +}); + +/** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * + * @private + */ +Ticker.prototype._requestIfNeeded = function _requestIfNeeded() +{ + if (this._requestId === null && this._emitter.listeners(TICK, true)) + { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._requestId = requestAnimationFrame(this._tick); + } +}; + +/** + * Conditionally cancels a pending animation frame. + * + * @private + */ +Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() +{ + if (this._requestId !== null) + { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } +}; + +/** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * + * @private + */ +Ticker.prototype._startIfPossible = function _startIfPossible() +{ + if (this.started) + { + this._requestIfNeeded(); + } + else if (this.autoStart) + { + this.start(); + } +}; + +/** + * Calls {@link module:eventemitter3.EventEmitter#on} internally for the + * internal 'tick' event. It checks if the emitter has listeners, + * and if so it requests a new animation frame at this point. + * + * @param fn {Function} The listener function to be added for updates + * @param [context] {Function} The listener context + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ +Ticker.prototype.add = function add(fn, context) +{ + this._emitter.on(TICK, fn, context); + + this._startIfPossible(); + + return this; +}; + +/** + * Calls {@link module:eventemitter3.EventEmitter#once} internally for the + * internal 'tick' event. It checks if the emitter has listeners, + * and if so it requests a new animation frame at this point. + * + * @param fn {Function} The listener function to be added for one update + * @param [context] {Function} The listener context + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ +Ticker.prototype.addOnce = function addOnce(fn, context) +{ + this._emitter.once(TICK, fn, context); + + this._startIfPossible(); + + return this; +}; + +/** + * Calls {@link module:eventemitter3.EventEmitter#off} internally for 'tick' event. + * It checks if the emitter has listeners for 'tick' event. + * If it does, then it cancels the animation frame. + * + * @param [fn] {Function} The listener function to be removed + * @param [context] {Function} The listener context to be removed + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ +Ticker.prototype.remove = function remove(fn, context) +{ + this._emitter.off(TICK, fn, context); + + if (!this._emitter.listeners(TICK, true)) + { + this._cancelIfNeeded(); + } + + return this; +}; + +/** + * Starts the ticker. If the ticker has listeners + * a new animation frame is requested at this point. + */ +Ticker.prototype.start = function start() +{ + if (!this.started) + { + this.started = true; + this._requestIfNeeded(); + } +}; + +/** + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. + */ +Ticker.prototype.stop = function stop() +{ + if (this.started) + { + this.started = false; + this._cancelIfNeeded(); + } +}; + +/** + * Triggers an update. An update entails setting the + * current {@link PIXI.ticker.Ticker#elapsedMS}, + * the current {@link PIXI.ticker.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.ticker.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * + * @param [currentTime=performance.now()] {number} the current time of execution + */ +Ticker.prototype.update = function update(currentTime) +{ + var elapsedMS; + + // Allow calling update directly with default currentTime. + currentTime = currentTime || performance.now(); + + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + + if (currentTime > this.lastTime) + { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) + { + elapsedMS = this._maxElapsedMS; + } + + this.deltaTime = elapsedMS * CONST.TARGET_FPMS * this.speed; + + // Invoke listeners added to internal emitter + this._emitter.emit(TICK, this.deltaTime); + } + else + { + this.deltaTime = this.elapsedMS = 0; + } + + this.lastTime = currentTime; +}; + +module.exports = Ticker; + +},{"../const":43,"eventemitter3":3}],113:[function(require,module,exports){ +var Ticker = require('./Ticker'); + +/** + * The shared ticker instance used by {@link PIXI.extras.MovieClip}. + * and by {@link PIXI.interaction.InteractionManager}. + * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` + * for this instance. Please follow the examples for usage, including + * how to opt-out of auto-starting the shared ticker. + * + * @example + * var ticker = PIXI.ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * + * @example + * // You may use the shared ticker to render... + * var renderer = PIXI.autoDetectRenderer(800, 600); + * var stage = new PIXI.Container(); + * var interactionManager = PIXI.interaction.InteractionManager(renderer); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * + * @type {PIXI.ticker.Ticker} + * @memberof PIXI.ticker + */ +var shared = new Ticker(); +shared.autoStart = true; + +/** + * @namespace PIXI.ticker + */ +module.exports = { + shared: shared, + Ticker: Ticker +}; + +},{"./Ticker":112}],114:[function(require,module,exports){ +/** + * Generic Mask Stack data structure + * @class + * @memberof PIXI + * @param size {number} Number of quads + * @return {Uint16Array} indices + */ +var createIndicesForQuads = function (size) +{ + // the total number of indices in our array, there are 6 points per quad. + + var totalIndices = size * 6; + + var indices = new Uint16Array(totalIndices); + + // fill the indices with the quads to draw + for (var i=0, j=0; i < totalIndices; i += 6, j += 4) + { + indices[i + 0] = j + 0; + indices[i + 1] = j + 1; + indices[i + 2] = j + 2; + indices[i + 3] = j + 0; + indices[i + 4] = j + 2; + indices[i + 5] = j + 3; + } + + return indices; +}; + +module.exports = createIndicesForQuads; + +},{}],115:[function(require,module,exports){ +var tempAnchor; +var _url = require('url'); + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * @private + * @param url {string} The url to test. + * @param loc [location=window.location] {object} The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +var determineCrossOrigin = function (url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url.parse(tempAnchor.href); + + var samePort = (!url.port && loc.port === '') || (url.port === loc.port); + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +}; + +module.exports = determineCrossOrigin; + +},{"url":28}],116:[function(require,module,exports){ +var CONST = require('../const'); + +/** + * @namespace PIXI.utils + */ +var utils = module.exports = { + _uid: 0, + _saidHello: false, + + EventEmitter: require('eventemitter3'), + pluginTarget: require('./pluginTarget'), + + /** + * Gets the next unique identifier + * + * @memberof PIXI.utils + * @return {number} The next unique identifier to use. + */ + uid: function () + { + return ++utils._uid; + }, + + /** + * Converts a hex color number to an [R, G, B] array + * + * @memberof PIXI.utils + * @param hex {number} + * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one + * @return {number[]} An array representing the [R, G, B] of the color. + */ + hex2rgb: function (hex, out) + { + out = out || []; + + out[0] = (hex >> 16 & 0xFF) / 255; + out[1] = (hex >> 8 & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + + return out; + }, + + /** + * Converts a hex color number to a string. + * + * @memberof PIXI.utils + * @param hex {number} Number in hex + * @return {string} The string color. + */ + hex2string: function (hex) + { + hex = hex.toString(16); + hex = '000000'.substr(0, 6 - hex.length) + hex; + + return '#' + hex; + }, + + /** + * Converts a color as an [R, G, B] array to a hex number + * + * @memberof PIXI.utils + * @param rgb {number[]} rgb array + * @return {number} The color number + */ + rgb2hex: function (rgb) + { + return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255); + }, + + + /** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * + * @memberof PIXI.utils + * @param url {string} the image path + * @return {number} resolution / device pixel ratio of an asset + */ + getResolutionOfUrl: function (url) + { + var resolution = CONST.RETINA_PREFIX.exec(url); + + if (resolution) + { + return parseFloat(resolution[1]); + } + + return 1; + }, + + /** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can set `PIXI.utils._saidHello = true;` + * so the library thinks it already said it. Keep in mind that doing that will forever + * makes you a jerk face. + * + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + * @constant + * @static + */ + sayHello: function (type) + { + if (utils._saidHello) + { + return; + } + + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) + { + var args = [ + '\n %c %c %c Pixi.js ' + CONST.VERSION + ' - ✰ ' + type + ' ✰ %c ' + ' %c ' + ' http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n', + 'background: #ff66a5; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'color: #ff66a5; background: #030307; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'background: #ffc3dc; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;' + ]; + + window.console.log.apply(console, args); //jshint ignore:line + } + else if (window.console) + { + window.console.log('Pixi.js ' + CONST.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); //jshint ignore:line + } + + utils._saidHello = true; + }, + + /** + * Helper for checking for webgl support + * + * @memberof PIXI.utils + * @return {boolean} is webgl supported + */ + isWebGLSupported: function () + { + var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; + try + { + if (!window.WebGLRenderingContext) + { + return false; + } + + var canvas = document.createElement('canvas'), + gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); + + var success = !!(gl && gl.getContextAttributes().stencil); + if (gl) + { + var loseContext = gl.getExtension('WEBGL_lose_context'); + + if(loseContext) + { + loseContext.loseContext(); + } + } + gl = null; + + return success; + } + catch (e) + { + return false; + } + }, + + /** + * Returns sign of number + * + * @memberof PIXI.utils + * @param n {number} + * @returns {number} 0 if n is 0, -1 if n is negative, 1 if n i positive + */ + sign: function (n) + { + return n ? (n < 0 ? -1 : 1) : 0; + }, + + /** + * Remove a range of items from an array + * + * @memberof PIXI.utils + * @param {Array<*>} arr The target array + * @param {number} startIdx The index to begin removing from (inclusive) + * @param {number} removeCount How many items to remove + */ + removeItems: function (arr, startIdx, removeCount) + { + var length = arr.length; + + if (startIdx >= length || removeCount === 0) + { + return; + } + + removeCount = (startIdx+removeCount > length ? length-startIdx : removeCount); + for (var i = startIdx, len = length-removeCount; i < len; ++i) + { + arr[i] = arr[i + removeCount]; + } + + arr.length = len; + }, + + /** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ + TextureCache: {}, + + /** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ + BaseTextureCache: {} +}; + +},{"../const":43,"./pluginTarget":118,"eventemitter3":3}],117:[function(require,module,exports){ + + +var Device = require('ismobilejs'); + +var maxRecommendedTextures = function(max) +{ + + if(Device.tablet || Device.phone) + { + // check if the res is iphone 6 or higher.. + return 2; + } + else + { + // desktop should be ok + return max; + } +}; + +module.exports = maxRecommendedTextures; +},{"ismobilejs":4}],118:[function(require,module,exports){ +/** + * Mixins functionality to make an object have "plugins". + * + * @mixin + * @memberof PIXI.utils + * @param obj {object} The object to mix into. + * @example + * function MyObject() {} + * + * pluginTarget.mixin(MyObject); + */ +function pluginTarget(obj) +{ + obj.__plugins = {}; + + /** + * Adds a plugin to an object + * + * @param pluginName {string} The events that should be listed. + * @param ctor {Function} The constructor function for the plugin. + */ + obj.registerPlugin = function (pluginName, ctor) + { + obj.__plugins[pluginName] = ctor; + }; + + /** + * Instantiates all the plugins of this object + * + */ + obj.prototype.initPlugins = function () + { + this.plugins = this.plugins || {}; + + for (var o in obj.__plugins) + { + this.plugins[o] = new (obj.__plugins[o])(this); + } + }; + + /** + * Removes all the plugins of this object + * + */ + obj.prototype.destroyPlugins = function () + { + for (var o in this.plugins) + { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + + this.plugins = null; + }; +} + + +module.exports = { + /** + * Mixes in the properties of the pluginTarget into another object + * + * @param obj {object} The obj to mix into + */ + mixin: function mixin(obj) + { + pluginTarget(obj); + } +}; + +},{}],119:[function(require,module,exports){ +/*global console */ +var core = require('./core'), + mesh = require('./mesh'), + particles = require('./particles'), + extras = require('./extras'), + filters = require('./filters'); + +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code +function warn(msg) { + var stack = new Error().stack; + + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('Deprecation Warning: ', msg); + } + else { + // chop off the stack trace which includes pixi.js internal calls + stack = stack.split('\n').splice(3).join('\n'); + + if (console.groupCollapsed) { + console.groupCollapsed('%cDeprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', msg); + console.warn(stack); + console.groupEnd(); + } + else { + console.warn('Deprecation Warning: ', msg); + console.warn(stack); + } + } +} + +/** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ +core.SpriteBatch = function() +{ + throw new ReferenceError('SpriteBatch does not exist any more, please use the new ParticleContainer instead.'); +}; + +/** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ +core.AssetLoader = function() +{ + throw new ReferenceError('The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class.'); +}; + +Object.defineProperties(core, { + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + Stage: { + get: function() + { + warn('You do not need to use a PIXI Stage any more, you can simply render any container.'); + return core.Container; + } + }, + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + DisplayObjectContainer: { + get: function() + { + warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.'); + return core.Container; + } + }, + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + Strip: { + get: function() + { + warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.'); + return mesh.Mesh; + } + }, + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + Rope: { + get: function() + { + warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.'); + return mesh.Rope; + } + }, + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + ParticleContainer: { + get: function() { + warn('The ParticleContainer class has been moved to particles.ParticleContainer, please use particles.ParticleContainer from now on.'); + return particles.ParticleContainer; + } + }, + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + MovieClip: { + get: function() + { + warn('The MovieClip class has been moved to extras.MovieClip, please use extras.MovieClip from now on.'); + return extras.MovieClip; + } + }, + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + TilingSprite: { + get: function() + { + warn('The TilingSprite class has been moved to extras.TilingSprite, please use extras.TilingSprite from now on.'); + return extras.TilingSprite; + } + }, + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + BitmapText: { + get: function() + { + warn('The BitmapText class has been moved to extras.BitmapText, please use extras.BitmapText from now on.'); + return extras.BitmapText; + } + }, + + /** + * @class + * @private + * @name blendModes + * @memberof PIXI + * @see PIXI.BLEND_MODES + * @deprecated since version 3.0.0 + */ + blendModes: { + get: function() + { + warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.'); + return core.BLEND_MODES; + } + }, + + /** + * @class + * @private + * @name scaleModes + * @memberof PIXI + * @see PIXI.SCALE_MODES + * @deprecated since version 3.0.0 + */ + scaleModes: { + get: function() + { + warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.'); + return core.SCALE_MODES; + } + }, + + /** + * @class + * @private + * @name BaseTextureCache + * @memberof PIXI + * @see PIXI.utils.BaseTextureCache + * @deprecated since version 3.0.0 + */ + BaseTextureCache: { + get: function () + { + warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, please use utils.BaseTextureCache from now on.'); + return core.utils.BaseTextureCache; + } + }, + + /** + * @class + * @private + * @name TextureCache + * @memberof PIXI + * @see PIXI.utils.TextureCache + * @deprecated since version 3.0.0 + */ + TextureCache: { + get: function () + { + warn('The TextureCache class has been moved to utils.TextureCache, please use utils.TextureCache from now on.'); + return core.utils.TextureCache; + } + }, + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + math: { + get: function () + { + warn('The math namespace is deprecated, please access members already accessible on PIXI.'); + return core; + } + }, + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function() + { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + return core.Filter; + } + }, + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + TransformManual: { + get: function() + { + warn('TransformManual has been renamed to TransformBase, please update your pixi-spine'); + return core.TransformBase; + } + } +}); + +core.DisplayObject.prototype.generateTexture = function(renderer, scaleMode, resolution) +{ + warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); + return renderer.generateTexture(this, scaleMode, resolution); +}; + + +core.Graphics.prototype.generateTexture = function(scaleMode, resolution) +{ + warn('graphics generate texture has moved to the renderer. Or to render a graphics to a texture using canvas please use generateCanvasTexture'); + return this.generateCanvasTexture(scaleMode, resolution); +}; + +core.RenderTexture.prototype.render = function(displayObject, matrix, clear, updateTransform) +{ + this.legacyRenderer.render(displayObject, this, clear, matrix, !updateTransform); + warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)'); +}; + +core.RenderTexture.prototype.getImage = function(target) +{ + warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); + return this.legacyRenderer.extract.image(target); +}; + +core.RenderTexture.prototype.getBase64 = function(target) +{ + warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); + return this.legacyRenderer.extract.base64(target); +}; + +core.RenderTexture.prototype.getCanvas = function(target) +{ + warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); + return this.legacyRenderer.extract.canvas(target); +}; + +core.RenderTexture.prototype.getPixels = function(target) +{ + warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); + return this.legacyRenderer.pixels(target); +}; + + + +/** + * @method + * @private + * @name PIXI.Sprite#setTexture + * @see PIXI.Sprite#texture + * @deprecated since version 3.0.0 + */ +core.Sprite.prototype.setTexture = function(texture) +{ + this.texture = texture; + warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;'); +}; + + + +/** + * @method + * @name PIXI.extras.BitmapText#setText + * @see PIXI.extras.BitmapText#text + * @deprecated since version 3.0.0 + */ +extras.BitmapText.prototype.setText = function(text) +{ + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';'); +}; + +/** + * @method + * @name PIXI.Text#setText + * @see PIXI.Text#text + * @deprecated since version 3.0.0 + */ +core.Text.prototype.setText = function(text) +{ + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';'); +}; + +/** + * @method + * @name PIXI.Text#setStyle + * @see PIXI.Text#style + * @deprecated since version 3.0.0 + */ +core.Text.prototype.setStyle = function(style) +{ + this.style = style; + warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;'); +}; + +Object.defineProperties(core.TextStyle.prototype, { + /** + * Set all properties of a font as a single string + * + * @name PIXI.TextStyle#font + * @deprecated since version 4.0.0 + */ + font: { + get: function () + { + warn('text style property \'font\' is now deprecated, please use the \'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + var fontSizeString = (typeof this._fontSize === 'number') ? this._fontSize + 'px' : this._fontSize; + return this._fontStyle + ' ' + this._fontVariant + ' ' + this._fontWeight + ' ' + fontSizeString + ' ' + this._fontFamily; + }, + set: function (font) + { + warn('text style property \'font\' is now deprecated, please use the \'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + + // can work out fontStyle from search of whole string + if ( font.indexOf('italic') > 1 ) + { + this._fontStyle = 'italic'; + } + else if ( font.indexOf('oblique') > -1 ) + { + this._fontStyle = 'oblique'; + } + else + { + this._fontStyle = 'normal'; + } + + // can work out fontVariant from search of whole string + if ( font.indexOf('small-caps') > -1 ) + { + this._fontVariant = 'small-caps'; + } + else + { + this._fontVariant = 'normal'; + } + + // fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units + var splits = font.split(' '); + var i; + var fontSizeIndex = -1; + + this._fontSize = 26; + for ( i = 0; i < splits.length; ++i ) + { + if ( splits[i].match( /(px|pt|em|%)/ ) ) + { + fontSizeIndex = i; + this._fontSize = splits[i]; + break; + } + } + + // we can now search for fontWeight as we know it must occur before the fontSize + this._fontWeight = 'normal'; + for ( i = 0; i < fontSizeIndex; ++i ) + { + if ( splits[i].match( /(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/ ) ) + { + this._fontWeight = splits[i]; + break; + } + } + + // and finally join everything together after the fontSize in case the font family has multiple words + if ( fontSizeIndex > -1 && fontSizeIndex < splits.length-1 ) + { + this._fontFamily = ''; + for ( i = fontSizeIndex + 1; i < splits.length; ++i ) + { + this._fontFamily += splits[i] + ' '; + } + + this._fontFamily = this._fontFamily.slice(0, -1); + } + else + { + this._fontFamily = 'Arial'; + } + + this.styleID++; + } + } +} ); + +/** + * @method + * @name PIXI.Texture#setFrame + * @see PIXI.Texture#setFrame + * @deprecated since version 3.0.0 + */ +core.Texture.prototype.setFrame = function(frame) +{ + this.frame = frame; + warn('setFrame is now deprecated, please use the frame property, e.g : myTexture.frame = frame;'); +}; + +Object.defineProperties(filters, { + + /** + * @class + * @private + * @name PIXI.filters.AbstractFilter + * @see PIXI.AbstractFilter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function() + { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + return core.AbstractFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.SpriteMaskFilter + * @see PIXI.SpriteMaskFilter + * @deprecated since version 3.0.6 + */ + SpriteMaskFilter: { + get: function() + { + warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.'); + return core.SpriteMaskFilter; + } + } +}); + +/** + * @method + * @name PIXI.utils.uuid + * @see PIXI.utils.uid + * @deprecated since version 3.0.6 + */ +core.utils.uuid = function () +{ + warn('utils.uuid() is deprecated, please use utils.uid() from now on.'); + return core.utils.uid(); +}; + +/** + * @method + * @name PIXI.utils.canUseNewCanvasBlendModes + * @see PIXI.CanvasTinter + * @deprecated + */ +core.utils.canUseNewCanvasBlendModes = function() { + warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on'); + return core.CanvasTinter.canUseMultiply; +}; +},{"./core":62,"./extras":129,"./filters":140,"./mesh":156,"./particles":159}],120:[function(require,module,exports){ +var core = require('../../core'), + tempRect = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers + * @class + * @memberof PIXI + * @param renderer {PIXI.CanvasRenderer} A reference to the current renderer + */ +function CanvasExtract(renderer) +{ + this.renderer = renderer; + renderer.extract = this; +} + + +CanvasExtract.prototype.constructor = CanvasExtract; +module.exports = CanvasExtract; + +/** + * Will return a HTML Image of the target + * + * @param target {PIXI.DisplayObject|PIXI.RenderTexture} A displayObject or renderTexture to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ +CanvasExtract.prototype.image = function ( target ) +{ + var image = new Image(); + image.src = this.base64( target ); + return image; +}; + +/** + * Will return a a base64 encoded string of this target. It works by calling CanvasExtract.getCanvas and then running toDataURL on that. + * @param target {PIXI.DisplayObject|PIXI.RenderTexture} A displayObject or renderTexture to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ +CanvasExtract.prototype.base64 = function ( target ) +{ + return this.canvas( target ).toDataURL(); +}; + +/** + * Creates a Canvas element, renders this target to it and then returns it. + * @param target {PIXI.DisplayObject|PIXI.RenderTexture} A displayObject or renderTexture to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ +CanvasExtract.prototype.canvas = function ( target ) +{ + var renderer = this.renderer; + var context; + var resolution; + var frame; + var renderTexture; + + if(target) + { + if(target instanceof core.RenderTexture) + { + renderTexture = target; + } + else + { + renderTexture = renderer.generateTexture(target); + } + } + + if(renderTexture) + { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } + else + { + context = renderer.rootContext; + resolution = renderer.rootResolution; + + frame = tempRect; + frame.width = this.renderer.width; + frame.height = this.renderer.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); + canvasBuffer.context.putImageData(canvasData, 0, 0); + + + // send the canvas back.. + return canvasBuffer.canvas; +}; + +/** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA order, with integer values between 0 and 255 (included). + * @param target {PIXI.DisplayObject|PIXI.RenderTexture} A displayObject or renderTexture to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ +CanvasExtract.prototype.pixels = function ( target ) +{ + var renderer = this.renderer; + var context; + var resolution; + var frame; + var renderTexture; + + if(target) + { + if(target instanceof core.RenderTexture) + { + renderTexture = target; + } + else + { + renderTexture = renderer.generateTexture(target); + } + } + + if(renderTexture) + { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } + else + { + context = renderer.rootContext; + resolution = renderer.rootResolution; + + frame = tempRect; + frame.width = renderer.width; + frame.height = renderer.height; + } + + return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; +}; + +/** + * Destroys the extract + * + */ +CanvasExtract.prototype.destroy = function () +{ + this.renderer.extract = null; + this.renderer = null; +}; + +core.CanvasRenderer.registerPlugin('extract', CanvasExtract); + +},{"../../core":62}],121:[function(require,module,exports){ + +module.exports = { + webGL: require('./webgl/WebGLExtract'), + canvas: require('./canvas/CanvasExtract') +}; +},{"./canvas/CanvasExtract":120,"./webgl/WebGLExtract":122}],122:[function(require,module,exports){ +var core = require('../../core'), + tempRect = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers + * @class + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} A reference to the current renderer + */ +function WebGLExtract(renderer) +{ + this.renderer = renderer; + renderer.extract = this; +} + + +WebGLExtract.prototype.constructor = WebGLExtract; +module.exports = WebGLExtract; + +/** + * Will return a HTML Image of the target + * + * @param target {PIXI.DisplayObject|PIXI.RenderTexture} A displayObject or renderTexture to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ +WebGLExtract.prototype.image = function ( target ) +{ + var image = new Image(); + image.src = this.base64( target ); + return image; +}; + +/** + * Will return a a base64 encoded string of this target. It works by calling WebGLExtract.getCanvas and then running toDataURL on that. + * @param target {PIXI.DisplayObject|PIXI.RenderTexture} A displayObject or renderTexture to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ +WebGLExtract.prototype.base64 = function ( target ) +{ + return this.canvas( target ).toDataURL(); +}; + +/** + * Creates a Canvas element, renders this target to it and then returns it. + * @param target {PIXI.DisplayObject|PIXI.RenderTexture} A displayObject or renderTexture to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ +WebGLExtract.prototype.canvas = function ( target ) +{ + var renderer = this.renderer; + var textureBuffer; + var resolution; + var frame; + var flipY = false; + var renderTexture; + + if(target) + { + if(target instanceof core.RenderTexture) + { + renderTexture = target; + } + else + { + renderTexture = this.renderer.generateTexture(target); + + } + } + + if(renderTexture) + { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + flipY = false; + } + else + { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + flipY = true; + + frame = tempRect; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + + } + + + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + + if(textureBuffer) + { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + + // set up an array of pixels + var webGLPixels = new Uint8Array(4 * width * height); + + // read pixels to the array + var gl = renderer.gl; + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webGLPixels); + + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + canvasData.data.set(webGLPixels); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // pulling pixels + if(flipY) + { + canvasBuffer.context.scale(1, -1); + canvasBuffer.context.drawImage(canvasBuffer.canvas, 0,-height); + } + } + + // send the canvas back.. + return canvasBuffer.canvas; +}; + +/** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA order, with integer values between 0 and 255 (included). + * @param target {PIXI.DisplayObject|PIXI.RenderTexture} A displayObject or renderTexture to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ +WebGLExtract.prototype.pixels = function ( target ) +{ + var renderer = this.renderer; + var textureBuffer; + var resolution; + var frame; + var renderTexture; + + if(target) + { + if(target instanceof core.RenderTexture) + { + renderTexture = target; + } + else + { + renderTexture = this.renderer.generateTexture(target); + } + } + + if(renderTexture) + { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + + } + else + { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + + frame = tempRect; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var webGLPixels = new Uint8Array(4 * width * height); + + if(textureBuffer) + { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + // read pixels to the array + var gl = renderer.gl; + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webGLPixels); + } + + return webGLPixels; +}; + +/** + * Destroys the extract + * + */ +WebGLExtract.prototype.destroy = function () +{ + this.renderer.extract = null; + this.renderer = null; +}; + +core.WebGLRenderer.registerPlugin('extract', WebGLExtract); + +},{"../../core":62}],123:[function(require,module,exports){ +var core = require('../core'), + ObservablePoint = require('../core/math/ObservablePoint'); + +/** + * A BitmapText object will create a line or multiple lines of text using bitmap font. To + * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using: + * + * A BitmapText can only be created when the font is loaded + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * var bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); + * ``` + * + * http://www.angelcode.com/products/bmfont/ for windows or + * http://www.bmglyph.com/ for mac. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.extras + * @param text {string} The copy that you would like the text to display + * @param style {object} The style parameters + * @param style.font {string|object} The font descriptor for the object, can be passed as a string of form + * "24px FontName" or "FontName" or as an object with explicit name/size properties. + * @param [style.font.name] {string} The bitmap font id + * @param [style.font.size] {number} The size of the font in pixels, e.g. 24 + * @param [style.align='left'] {string} Alignment for multiline text ('left', 'center' or 'right'), does not affect + * single line text + * @param [style.tint=0xFFFFFF] {number} The tint color + */ +function BitmapText(text, style) +{ + core.Container.call(this); + + style = style || {}; + + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + this.textWidth = 0; + + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + this.textHeight = 0; + + /** + * Private tracker for the letter sprite pool. + * + * @member {PIXI.Sprite[]} + * @private + */ + this._glyphs = []; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + this._font = { + tint: style.tint !== undefined ? style.tint : 0xFFFFFF, + align: style.align || 'left', + name: null, + size: 0 + }; + + /** + * Private tracker for the current font. + * + * @member {object} + * @private + */ + this.font = style.font; // run font setter + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + this._text = text; + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + */ + this.maxWidth = 0; + + /** + * The max line height. This is useful when trying to use the total height of the Text, ie: when trying to vertically align. + * + * @member {number} + */ + this.maxLineHeight = 0; + + /** + * Text anchor. read-only + * + * @member {PIXI.ObservablePoint} + * @private + */ + this._anchor = new ObservablePoint(this.makeDirty, this, 0, 0); + + /** + * The dirty state of this object. + * + * @member {boolean} + */ + this.dirty = false; + + this.updateText(); +} + +// constructor +BitmapText.prototype = Object.create(core.Container.prototype); +BitmapText.prototype.constructor = BitmapText; +module.exports = BitmapText; + +Object.defineProperties(BitmapText.prototype, { + /** + * The tint of the BitmapText object + * + * @member {number} + * @memberof PIXI.extras.BitmapText# + */ + tint: { + get: function () + { + return this._font.tint; + }, + set: function (value) + { + this._font.tint = (typeof value === 'number' && value >= 0) ? value : 0xFFFFFF; + + this.dirty = true; + } + }, + + /** + * The alignment of the BitmapText object + * + * @member {string} + * @default 'left' + * @memberof PIXI.extras.BitmapText# + */ + align: { + get: function () + { + return this._font.align; + }, + set: function (value) + { + this._font.align = value || 'left'; + + this.dirty = true; + } + }, + + /** + * The anchor sets the origin point of the text. + * The default is 0,0 this means the text's origin is the top left + * Setting the anchor to 0.5,0.5 means the text's origin is centered + * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner + * + * @member {PIXI.Point | number} + * @memberof PIXI.extras.BitmapText# + */ + anchor: { + get : function() { + return this._anchor; + }, + set: function(value) { + if (typeof value === 'number'){ + this._anchor.set(value); + } + else { + this._anchor.copy(value); + } + } + }, + + /** + * The font descriptor of the BitmapText object + * + * @member {string|object} + * @memberof PIXI.extras.BitmapText# + */ + font: { + get: function () + { + return this._font; + }, + set: function (value) + { + if (!value) { + return; + } + + if (typeof value === 'string') { + value = value.split(' '); + + this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); + this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; + } + else { + this._font.name = value.name; + this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); + } + + this.dirty = true; + } + }, + + /** + * The text of the BitmapText object + * + * @member {string} + * @memberof PIXI.extras.BitmapText# + */ + text: { + get: function () + { + return this._text; + }, + set: function (value) + { + value = value.toString() || ' '; + if (this._text === value) + { + return; + } + this._text = value; + this.dirty = true; + } + } +}); + +/** + * Renders text and updates it when needed + * + * @private + */ +BitmapText.prototype.updateText = function () +{ + var data = BitmapText.fonts[this._font.name]; + var pos = new core.Point(); + var prevCharCode = null; + var chars = []; + var lastLineWidth = 0; + var maxLineWidth = 0; + var lineWidths = []; + var line = 0; + var scale = this._font.size / data.size; + var lastSpace = -1; + var lastSpaceWidth = 0; + var maxLineHeight = 0; + + for (var i = 0; i < this.text.length; i++) + { + var charCode = this.text.charCodeAt(i); + + if(/(\s)/.test(this.text.charAt(i))){ + lastSpace = i; + lastSpaceWidth = lastLineWidth; + } + + if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) + { + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + if (lastSpace !== -1 && this.maxWidth > 0 && pos.x * scale > this.maxWidth) + { + core.utils.removeItems(chars, lastSpace, i - lastSpace); + i = lastSpace; + lastSpace = -1; + + lineWidths.push(lastSpaceWidth); + maxLineWidth = Math.max(maxLineWidth, lastSpaceWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + var charData = data.chars[charCode]; + + if (!charData) + { + continue; + } + + if (prevCharCode && charData.kerning[prevCharCode]) + { + pos.x += charData.kerning[prevCharCode]; + } + + chars.push({texture:charData.texture, line: line, charCode: charCode, position: new core.Point(pos.x + charData.xOffset, pos.y + charData.yOffset)}); + lastLineWidth = pos.x + (charData.texture.width + charData.xOffset); + pos.x += charData.xAdvance; + maxLineHeight = Math.max(maxLineHeight, (charData.yOffset + charData.texture.height)); + prevCharCode = charCode; + } + + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + + var lineAlignOffsets = []; + + for (i = 0; i <= line; i++) + { + var alignOffset = 0; + + if (this._font.align === 'right') + { + alignOffset = maxLineWidth - lineWidths[i]; + } + else if (this._font.align === 'center') + { + alignOffset = (maxLineWidth - lineWidths[i]) / 2; + } + + lineAlignOffsets.push(alignOffset); + } + + var lenChars = chars.length; + var tint = this.tint; + + for (i = 0; i < lenChars; i++) + { + var c = this._glyphs[i]; // get the next glyph sprite + + if (c) + { + c.texture = chars[i].texture; + } + else + { + c = new core.Sprite(chars[i].texture); + this._glyphs.push(c); + } + + c.position.x = (chars[i].position.x + lineAlignOffsets[chars[i].line]) * scale; + c.position.y = chars[i].position.y * scale; + c.scale.x = c.scale.y = scale; + c.tint = tint; + + if (!c.parent) + { + this.addChild(c); + } + } + + // remove unnecessary children. + for (i = lenChars; i < this._glyphs.length; ++i) + { + this.removeChild(this._glyphs[i]); + } + + this.textWidth = maxLineWidth * scale; + this.textHeight = (pos.y + data.lineHeight) * scale; + + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) + { + for (i = 0; i < lenChars; i++) + { + this._glyphs[i].x -= this.textWidth * this.anchor.x; + this._glyphs[i].y -= this.textHeight * this.anchor.y; + } + } + this.maxLineHeight = maxLineHeight * scale; +}; + +/** + * Updates the transform of this object + * + * @private + */ +BitmapText.prototype.updateTransform = function () +{ + this.validate(); + this.containerUpdateTransform(); +}; + +/** + * Validates text before calling parent's getLocalBounds + * + * @return {PIXI.Rectangle} The rectangular bounding area + */ + +BitmapText.prototype.getLocalBounds = function() +{ + this.validate(); + return core.Container.prototype.getLocalBounds.call(this); +}; + +/** + * Updates text when needed + * + * @private + */ +BitmapText.prototype.validate = function() +{ + if (this.dirty) + { + this.updateText(); + this.dirty = false; + } +}; + +BitmapText.prototype.makeDirty = function() { + this.dirty = true; +}; + +BitmapText.fonts = {}; + +},{"../core":62,"../core/math/ObservablePoint":65}],124:[function(require,module,exports){ +var core = require('../core'); + +/** + * @typedef FrameObject + * @type {object} + * @property texture {PIXI.Texture} The {@link PIXI.Texture} of the frame + * @property time {number} the duration of the frame in ms + */ + +/** + * A MovieClip is a simple way to display an animation depicted by a list of textures. + * + * ```js + * var alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * var textureArray = []; + * + * for (var i=0; i < 4; i++) + * { + * var texture = PIXI.Texture.fromImage(alienImages[i]); + * textureArray.push(texture); + * }; + * + * var mc = new PIXI.MovieClip(textureArray); + * ``` + * + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + * @param textures {PIXI.Texture[]|FrameObject[]} an array of {@link PIXI.Texture} or frame objects that make up the animation + */ +function MovieClip(textures) +{ + core.Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture); + + /** + * @private + */ + this._textures = null; + + /** + * @private + */ + this._durations = null; + + this.textures = textures; + + /** + * The speed that the MovieClip will play at. Higher is faster, lower is slower + * + * @member {number} + * @default 1 + */ + this.animationSpeed = 1; + + /** + * Whether or not the movie clip repeats after playing. + * + * @member {boolean} + * @default true + */ + this.loop = true; + + /** + * Function to call when a MovieClip finishes playing + * + * @method + * @memberof PIXI.extras.MovieClip# + */ + this.onComplete = null; + + /** + * Elapsed time since animation has been started, used internally to display current texture + * + * @member {number} + * @private + */ + this._currentTime = 0; + + /** + * Indicates if the MovieClip is currently playing + * + * @member {boolean} + * @readonly + */ + this.playing = false; +} + +// constructor +MovieClip.prototype = Object.create(core.Sprite.prototype); +MovieClip.prototype.constructor = MovieClip; +module.exports = MovieClip; + +Object.defineProperties(MovieClip.prototype, { + /** + * totalFrames is the total number of frames in the MovieClip. This is the same as number of textures + * assigned to the MovieClip. + * + * @member {number} + * @memberof PIXI.extras.MovieClip# + * @default 0 + * @readonly + */ + totalFrames: { + get: function() + { + return this._textures.length; + } + }, + + /** + * The array of textures used for this MovieClip + * + * @member {PIXI.Texture[]} + * @memberof PIXI.extras.MovieClip# + * + */ + textures: { + get: function () + { + return this._textures; + }, + set: function (value) + { + if(value[0] instanceof core.Texture) + { + this._textures = value; + this._durations = null; + } + else + { + this._textures = []; + this._durations = []; + for(var i = 0; i < value.length; i++) + { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + } + }, + + /** + * The MovieClips current frame index + * + * @member {number} + * @memberof PIXI.extras.MovieClip# + * @readonly + */ + currentFrame: { + get: function () + { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + if (currentFrame < 0) + { + currentFrame += this._textures.length; + } + return currentFrame; + } + } + +}); + +/** + * Stops the MovieClip + * + */ +MovieClip.prototype.stop = function () +{ + if(!this.playing) + { + return; + } + + this.playing = false; + core.ticker.shared.remove(this.update, this); +}; + +/** + * Plays the MovieClip + * + */ +MovieClip.prototype.play = function () +{ + if(this.playing) + { + return; + } + + this.playing = true; + core.ticker.shared.add(this.update, this); +}; + +/** + * Stops the MovieClip and goes to a specific frame + * + * @param frameNumber {number} frame index to stop at + */ +MovieClip.prototype.gotoAndStop = function (frameNumber) +{ + this.stop(); + + this._currentTime = frameNumber; + + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; +}; + +/** + * Goes to a specific frame and begins playing the MovieClip + * + * @param frameNumber {number} frame index to start at + */ +MovieClip.prototype.gotoAndPlay = function (frameNumber) +{ + this._currentTime = frameNumber; + + this.play(); +}; + +/* + * Updates the object transform for rendering + * @private + */ +MovieClip.prototype.update = function (deltaTime) +{ + var elapsed = this.animationSpeed * deltaTime; + + if (this._durations !== null) + { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + + lag += elapsed / 60 * 1000; + + while (lag < 0) + { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + + var sign = Math.sign(this.animationSpeed * deltaTime); + this._currentTime = Math.floor(this._currentTime); + + while (lag >= this._durations[this.currentFrame]) + { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + + this._currentTime += lag / this._durations[this.currentFrame]; + } + else + { + this._currentTime += elapsed; + } + + if (this._currentTime < 0 && !this.loop) + { + this.gotoAndStop(0); + + if (this.onComplete) + { + this.onComplete(); + } + } + else if (this._currentTime >= this._textures.length && !this.loop) + { + this.gotoAndStop(this._textures.length - 1); + + if (this.onComplete) + { + this.onComplete(); + } + } + else + { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + } + +}; + +/* + * Stops the MovieClip and destroys it + * + */ +MovieClip.prototype.destroy = function ( ) +{ + this.stop(); + core.Sprite.prototype.destroy.call(this); +}; + +/** + * A short hand way of creating a movieclip from an array of frame ids + * + * @static + * @param frames {string[]} the array of frames ids the movieclip will use as its texture frames + */ +MovieClip.fromFrames = function (frames) +{ + var textures = []; + + for (var i = 0; i < frames.length; ++i) + { + textures.push(core.Texture.fromFrame(frames[i])); + } + + return new MovieClip(textures); +}; + +/** + * A short hand way of creating a movieclip from an array of image ids + * + * @static + * @param images {string[]} the array of image urls the movieclip will use as its texture frames + */ +MovieClip.fromImages = function (images) +{ + var textures = []; + + for (var i = 0; i < images.length; ++i) + { + textures.push(core.Texture.fromImage(images[i])); + } + + return new MovieClip(textures); +}; + +},{"../core":62}],125:[function(require,module,exports){ +var core = require('../core'), + tempPoint = new core.Point(), + Texture = require('../core/textures/Texture'), + CanvasTinter = require('../core/sprites/canvas/CanvasTinter'), + TilingShader = require('./webgl/TilingShader'), + tempArray = new Float32Array(4); +/** + * A tiling sprite is a fast way of rendering a tiling image + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + * @param texture {PIXI.Texture} the texture of the tiling sprite + * @param width {number} the width of the tiling sprite + * @param height {number} the height of the tiling sprite + */ +function TilingSprite(texture, width, height) +{ + core.Sprite.call(this, texture); + + /** + * The scaling of the image that is being tiled + * + * @member {PIXI.Point} + */ + this.tileScale = new core.Point(1,1); + + + /** + * The offset position of the image that is being tiled + * + * @member {PIXI.Point} + */ + this.tilePosition = new core.Point(0,0); + + ///// private + + /** + * The with of the tiling sprite + * + * @member {number} + * @private + */ + this._width = width || 100; + + /** + * The height of the tiling sprite + * + * @member {number} + * @private + */ + this._height = height || 100; + + /** + * An internal WebGL UV cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + this._uvs = new core.TextureUvs(); + + this._canvasPattern = null; + + this._glDatas = []; +} + +TilingSprite.prototype = Object.create(core.Sprite.prototype); +TilingSprite.prototype.constructor = TilingSprite; +module.exports = TilingSprite; + + +Object.defineProperties(TilingSprite.prototype, { + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.extras.TilingSprite# + */ + width: { + get: function () + { + return this._width; + }, + set: function (value) + { + this._width = value; + } + }, + + /** + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + * @memberof PIXI.extras.TilingSprite# + */ + height: { + get: function () + { + return this._height; + }, + set: function (value) + { + this._height = value; + } + } +}); + +TilingSprite.prototype._onTextureUpdate = function () +{ + return; +}; + + +/** + * Renders the object using the WebGL renderer + * + * @param renderer {PIXI.WebGLRenderer} The renderer + * @private + */ +TilingSprite.prototype._renderWebGL = function (renderer) +{ + + // tweak our texture temporarily.. + var texture = this._texture; + + if(!texture || !texture._uvs) + { + return; + } + + // get rid of any thing that may be batching. + renderer.flush(); + + var gl = renderer.gl; + var glData = this._glDatas[renderer.CONTEXT_UID]; + + if(!glData) + { + glData = { + shader:new TilingShader(gl), + quad:new core.Quad(gl) + }; + + this._glDatas[renderer.CONTEXT_UID] = glData; + + glData.quad.initVao(glData.shader); + } + + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra space before transforming the sprite coords.. + var vertices = glData.quad.vertices; + + vertices[0] = vertices[6] = ( this._width ) * -this.anchor.x; + vertices[1] = vertices[3] = this._height * -this.anchor.y; + + vertices[2] = vertices[4] = ( this._width ) * (1-this.anchor.x); + vertices[5] = vertices[7] = this._height * (1-this.anchor.y); + + glData.quad.upload(); + + renderer.bindShader(glData.shader); + + var textureUvs = texture._uvs, + textureWidth = texture._frame.width, + textureHeight = texture._frame.height, + textureBaseWidth = texture.baseTexture.width, + textureBaseHeight = texture.baseTexture.height; + + var uPixelSize = glData.shader.uniforms.uPixelSize; + uPixelSize[0] = 1.0/textureBaseWidth; + uPixelSize[1] = 1.0/textureBaseHeight; + glData.shader.uniforms.uPixelSize = uPixelSize; + + var uFrame = glData.shader.uniforms.uFrame; + uFrame[0] = textureUvs.x0; + uFrame[1] = textureUvs.y0; + uFrame[2] = textureUvs.x1 - textureUvs.x0; + uFrame[3] = textureUvs.y2 - textureUvs.y0; + glData.shader.uniforms.uFrame = uFrame; + + var uTransform = glData.shader.uniforms.uTransform; + uTransform[0] = (this.tilePosition.x % (textureWidth * this.tileScale.x)) / this._width; + uTransform[1] = (this.tilePosition.y % (textureHeight * this.tileScale.y)) / this._height; + uTransform[2] = ( textureBaseWidth / this._width ) * this.tileScale.x; + uTransform[3] = ( textureBaseHeight / this._height ) * this.tileScale.y; + glData.shader.uniforms.uTransform = uTransform; + + glData.shader.uniforms.translationMatrix = this.worldTransform.toArray(true); + + var color = tempArray; + + core.utils.hex2rgb(this.tint, color); + color[3] = this.worldAlpha; + + glData.shader.uniforms.uColor = color; + + renderer.bindTexture(this._texture, 0); + + renderer.state.setBlendMode( this.blendMode ); + glData.quad.draw(); +}; + +/** + * Renders the object using the Canvas renderer + * + * @param renderer {PIXI.CanvasRenderer} a reference to the canvas renderer + * @private + */ +TilingSprite.prototype._renderCanvas = function (renderer) +{ + var texture = this._texture; + + if (!texture.baseTexture.hasLoaded) + { + return; + } + + var context = renderer.context, + transform = this.worldTransform, + resolution = renderer.resolution, + baseTexture = texture.baseTexture, + modX = (this.tilePosition.x / this.tileScale.x) % texture._frame.width, + modY = (this.tilePosition.y / this.tileScale.y) % texture._frame.height; + + // create a nice shiny pattern! + // TODO this needs to be refreshed if texture changes.. + if(!this._canvasPattern) + { + // cut an object from a spritesheet.. + var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height); + + // Tint the tiling sprite + if (this.tint !== 0xFFFFFF) + { + if (this.cachedTint !== this.tint) + { + this.cachedTint = this.tint; + + this.tintedTexture = CanvasTinter.getTintedTexture(this, this.tint); + } + tempCanvas.context.drawImage(this.tintedTexture, 0, 0); + } + else + { + tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x, -texture._frame.y); + } + this._canvasPattern = tempCanvas.context.createPattern( tempCanvas.canvas, 'repeat' ); + } + + // set context state.. + context.globalAlpha = this.worldAlpha; + context.setTransform(transform.a * resolution, + transform.b * resolution, + transform.c * resolution, + transform.d * resolution, + transform.tx * resolution, + transform.ty * resolution); + + // TODO - this should be rolled into the setTransform above.. + context.scale(this.tileScale.x,this.tileScale.y); + + context.translate(modX + (this.anchor.x * -this._width ), + modY + (this.anchor.y * -this._height)); + + // check blend mode + var compositeOperation = renderer.blendModes[this.blendMode]; + if (compositeOperation !== renderer.context.globalCompositeOperation) + { + context.globalCompositeOperation = compositeOperation; + } + + // fill the pattern! + context.fillStyle = this._canvasPattern; + context.fillRect(-modX, + -modY, + this._width / this.tileScale.x, + this._height / this.tileScale.y); + + + //TODO - pretty sure this can be deleted... + //context.translate(-this.tilePosition.x + (this.anchor.x * this._width), -this.tilePosition.y + (this.anchor.y * this._height)); + //context.scale(1 / this.tileScale.x, 1 / this.tileScale.y); +}; + + +/** + * Returns the framing rectangle of the sprite as a Rectangle object +* + * @return {PIXI.Rectangle} the framing rectangle + */ +TilingSprite.prototype.getBounds = function () +{ + var width = this._width; + var height = this._height; + + var w0 = width * (1-this.anchor.x); + var w1 = width * -this.anchor.x; + + var h0 = height * (1-this.anchor.y); + var h1 = height * -this.anchor.y; + + var worldTransform = this.worldTransform; + + var a = worldTransform.a; + var b = worldTransform.b; + var c = worldTransform.c; + var d = worldTransform.d; + var tx = worldTransform.tx; + var ty = worldTransform.ty; + + var x1 = a * w1 + c * h1 + tx; + var y1 = d * h1 + b * w1 + ty; + + var x2 = a * w0 + c * h1 + tx; + var y2 = d * h1 + b * w0 + ty; + + var x3 = a * w0 + c * h0 + tx; + var y3 = d * h0 + b * w0 + ty; + + var x4 = a * w1 + c * h0 + tx; + var y4 = d * h0 + b * w1 + ty; + + var minX, + maxX, + minY, + maxY; + + minX = x1; + minX = x2 < minX ? x2 : minX; + minX = x3 < minX ? x3 : minX; + minX = x4 < minX ? x4 : minX; + + minY = y1; + minY = y2 < minY ? y2 : minY; + minY = y3 < minY ? y3 : minY; + minY = y4 < minY ? y4 : minY; + + maxX = x1; + maxX = x2 > maxX ? x2 : maxX; + maxX = x3 > maxX ? x3 : maxX; + maxX = x4 > maxX ? x4 : maxX; + + maxY = y1; + maxY = y2 > maxY ? y2 : maxY; + maxY = y3 > maxY ? y3 : maxY; + maxY = y4 > maxY ? y4 : maxY; + + var bounds = this._bounds; + + bounds.x = minX; + bounds.width = maxX - minX; + + bounds.y = minY; + bounds.height = maxY - minY; + + // store a reference so that if this function gets called again in the render cycle we do not have to recalculate + this._currentBounds = bounds; + + return bounds; +}; + +/** + * Checks if a point is inside this tiling sprite + * @param point {PIXI.Point} the point to check + */ +TilingSprite.prototype.containsPoint = function( point ) +{ + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor.x; + var y1; + + if ( tempPoint.x > x1 && tempPoint.x < x1 + width ) + { + y1 = -height * this.anchor.y; + + if ( tempPoint.y > y1 && tempPoint.y < y1 + height ) + { + return true; + } + } + + return false; +}; + +/** + * Destroys this tiling sprite + * + */ +TilingSprite.prototype.destroy = function () { + core.Sprite.prototype.destroy.call(this); + + this.tileScale = null; + this._tileScaleOffset = null; + this.tilePosition = null; + + this._uvs = null; +}; + +/** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from +* @param width {number} the width of the tiling sprite + * @param height {number} the height of the tiling sprite + * @return {PIXI.Texture} The newly created texture + */ +TilingSprite.from = function (source,width,height) +{ + return new TilingSprite(Texture.from(source),width,height); +}; + + + +/** + * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param frameId {string} The frame Id of the texture in the cache + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId + * @param width {number} the width of the tiling sprite + * @param height {number} the height of the tiling sprite + * @return {PIXI.extras.TilingSprite} A new TilingSprite + */ +TilingSprite.fromFrame = function (frameId,width,height) +{ + var texture = core.utils.TextureCache[frameId]; + + if (!texture) + { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this); + } + + return new TilingSprite(texture,width,height); +}; + +/** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param imageId {string} The image url of the texture + * @param width {number} the width of the tiling sprite + * @param height {number} the height of the tiling sprite + * @param [crossorigin=(auto)] {boolean} if you want to specify the cross-origin parameter + * @param [scaleMode=PIXI.SCALE_MODES.DEFAULT] {number} if you want to specify the scale mode, see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id + */ +TilingSprite.fromImage = function (imageId, width, height, crossorigin, scaleMode) +{ + return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode),width,height); +}; + +},{"../core":62,"../core/sprites/canvas/CanvasTinter":100,"../core/textures/Texture":109,"./webgl/TilingShader":130}],126:[function(require,module,exports){ +var core = require('../core'), + DisplayObject = core.DisplayObject, + _tempMatrix = new core.Matrix(); + +DisplayObject.prototype._cacheAsBitmap = false; +DisplayObject.prototype._cacheData = false; + +// figured theres no point adding ALL the extra variables to prototype. +// this model can hold the information needed. This can also be generated on demand as +// most objects are not cached as bitmaps. +var CacheData = function(){ + + this.originalRenderWebGL = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + + this.originalUpdateTransform = null; + this.originalHitTest = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.sprite = null; +}; + + +Object.defineProperties(DisplayObject.prototype, { + + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can provide a performance benefit for complex static displayObjects. + * To remove simply set this property to 'false' + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function () + { + return this._cacheAsBitmap; + }, + set: function (value) + { + if (this._cacheAsBitmap === value) + { + return; + } + + this._cacheAsBitmap = value; + + var data; + + if (value) + { + + if(!this._cacheData) + { + this._cacheData = new CacheData(); + } + + data = this._cacheData; + + data.originalRenderWebGL = this.renderWebGL; + data.originalRenderCanvas = this.renderCanvas; + + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this._calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + + data.originalDestroy = this.destroy; + + data.originalContainsPoint = this.containsPoint; + + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + + + + this.renderWebGL = this._renderCachedWebGL; + this.renderCanvas = this._renderCachedCanvas; + + this.destroy = this._cacheAsBitmapDestroy; + + } + else + { + data = this._cacheData; + + if (data.sprite) + { + this._destroyCachedDisplayObject(); + } + + + this.renderWebGL = data.originalRenderWebGL; + this.renderCanvas = data.originalRenderCanvas; + this._calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + + this.destroy = data.originalDestroy; + + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + } + } +}); +/** +* Renders a cached version of the sprite with WebGL +* +* @param renderer {PIXI.WebGLRenderer} the WebGL renderer +* @private +*/ +DisplayObject.prototype._renderCachedWebGL = function (renderer) +{ + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) + { + return; + } + + this._initCachedDisplayObject( renderer ); + + this._cacheData.sprite._transformID = -1; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderWebGL(renderer); +}; + +/** +* Prepares the WebGL renderer to cache the sprite +* +* @param renderer {PIXI.WebGLRenderer} the WebGL renderer +* @private +*/ +DisplayObject.prototype._initCachedDisplayObject = function (renderer) +{ + if(this._cacheData && this._cacheData.sprite) + { + return; + } + + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + this.alpha = 1; + + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.currentRenderer.flush(); + //this.filters= []; + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds().clone(); + + // add some padding! + if(this._filters) + { + var padding = this._filters[0].padding; + + bounds.pad(padding); + } + + // for now we cache the current renderTarget that the webGL renderer is currently using. + // this could be more elegent.. + var cachedRenderTarget = renderer._activeRenderTarget; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + var stack = renderer.filterManager.filterStack; + + // this renderTexture will be used to store the cached DisplayObject + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + // need to set // + var m = _tempMatrix; + m.tx = -bounds.x; + m.ty = -bounds.y; + + // reset + this.transform.worldTransform.identity(); + + // set all properties to there original so we can render to a texture + this.renderWebGL = this._cacheData.originalRenderWebGL; + + + renderer.render(this, renderTexture, true, m, true); + // now restore the state be setting the new properties + + renderer.bindRenderTarget(cachedRenderTarget); + + renderer.filterManager.filterStack = stack; + + this.renderWebGL = this._renderCachedWebGL; + this.updateTransform = this.displayObjectUpdateTransform; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -( bounds.x / bounds.width ); + cachedSprite.anchor.y = -( bounds.y / bounds.height ); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + + //easy bounds.. + this._calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + + this._cacheData.sprite = cachedSprite; + + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + this.updateTransform(); + + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** +* Renders a cached version of the sprite with canvas +* +* @param renderer {PIXI.CanvasRenderer} the Canvas renderer +* @private +*/ +DisplayObject.prototype._renderCachedCanvas = function (renderer) +{ + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) + { + return; + } + + this._initCachedDisplayObjectCanvas( renderer ); + + this._cacheData.sprite.worldAlpha = this.worldAlpha; + + this._cacheData.sprite.renderCanvas(renderer); +}; + +//TODO this can be the same as the webGL verison.. will need to do a little tweaking first though.. +/** +* Prepares the Canvas renderer to cache the sprite +* +* @param renderer {PIXI.CanvasRenderer} the Canvas renderer +* @private +*/ +DisplayObject.prototype._initCachedDisplayObjectCanvas = function (renderer) +{ + if(this._cacheData && this._cacheData.sprite) + { + return; + } + + //get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(); + + var cacheAlpha = this.alpha; + this.alpha = 1; + + var cachedRenderTarget = renderer.context; + + var renderTexture = new core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + // need to set // + var m = _tempMatrix; + this.transform.worldTransform.copy(m); + m.invert(); + + m.tx -= bounds.x; + m.ty -= bounds.y; + + //m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + + //renderTexture.render(this, m, true); + renderer.render(this, renderTexture, true, m, false); + + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + + this.renderCanvas = this._renderCachedCanvas; + this._calculateBounds = this._calculateCachedBounds; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -( bounds.x / bounds.width ); + cachedSprite.anchor.y = -( bounds.y / bounds.height ); + cachedSprite._bounds = this._bounds; + cachedSprite.alpha = cacheAlpha; + + this.updateTransform(); + this.updateTransform = this.displayObjectUpdateTransform; + + this._cacheData.sprite = cachedSprite; + + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); + + +}; + +/** +* Calculates the bounds of the cached sprite +* +* @private +*/ +DisplayObject.prototype._calculateCachedBounds = function () +{ + return this._cacheData.sprite._calculateBounds(); +}; + +DisplayObject.prototype._getCachedLocalBounds = function () +{ + return this._cacheData.sprite.getLocalBounds(); +}; + +/** +* Destroys the cached sprite. +* +* @private +*/ +DisplayObject.prototype._destroyCachedDisplayObject = function () +{ + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; +}; + +DisplayObject.prototype._cacheAsBitmapDestroy = function () +{ + this.cacheAsBitmap = false; + this.destroy(); +}; + +},{"../core":62}],127:[function(require,module,exports){ +var core = require('../core'); + +/** + * The instance name of the object. + * + * @memberof PIXI.DisplayObject# + * @member {string} + */ +core.DisplayObject.prototype.name = null; + +/** +* Returns the display object in the container +* +* @memberof PIXI.Container# +* @param name {string} instance name +* @return {PIXI.DisplayObject} +*/ +core.Container.prototype.getChildByName = function (name) +{ + for (var i = 0; i < this.children.length; i++) + { + if (this.children[i].name === name) + { + return this.children[i]; + } + } + return null; +}; + +},{"../core":62}],128:[function(require,module,exports){ +var core = require('../core'); + +/** +* Returns the global position of the displayObject +* +* @memberof PIXI.DisplayObject# +* @param point {Point} the point to write the global value to. If null a new point will be returned +* @return {Point} +*/ +core.DisplayObject.prototype.getGlobalPosition = function (point) +{ + point = point || new core.Point(); + + if(this.parent) + { + this.displayObjectUpdateTransform(); + + point.x = this.worldTransform.tx; + point.y = this.worldTransform.ty; + } + else + { + point.x = this.position.x; + point.y = this.position.y; + } + + return point; +}; + +},{"../core":62}],129:[function(require,module,exports){ +/** + * @file Main export of the PIXI extras library + * @author Mat Groves + * @copyright 2013-2015 GoodBoyDigital + * @license {@link https://github.com/pixijs/pixi.js/blob/master/LICENSE|MIT License} + */ + +require('./cacheAsBitmap'); +require('./getChildByName'); +require('./getGlobalPosition'); + +/** + * @namespace PIXI.extras + */ +module.exports = { + MovieClip: require('./MovieClip'), + TilingSprite: require('./TilingSprite'), + BitmapText: require('./BitmapText') +}; + +},{"./BitmapText":123,"./MovieClip":124,"./TilingSprite":125,"./cacheAsBitmap":126,"./getChildByName":127,"./getGlobalPosition":128}],130:[function(require,module,exports){ +var Shader = require('../../core/Shader'); + + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI.mesh + * @param gl {PIXI.Shader} The WebGL shader manager this shader works for. + */ +function TilingShader(gl) +{ + Shader.call(this, + gl, + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\n\nuniform vec4 uFrame;\nuniform vec4 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vec2 coord = aTextureCoord;\n coord -= uTransform.xy;\n coord /= uTransform.zw;\n vTextureCoord = coord;\n}\n", + "#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform vec4 uFrame;\nuniform vec2 uPixelSize;\n\nvoid main(void)\n{\n\n \tvec2 coord = mod(vTextureCoord, uFrame.zw);\n \tcoord = clamp(coord, uPixelSize, uFrame.zw - uPixelSize);\n \tcoord += uFrame.xy;\n\n \tvec4 sample = texture2D(uSampler, coord);\n \tvec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n \tgl_FragColor = sample * color ;\n}\n" + ); +} + +TilingShader.prototype = Object.create(Shader.prototype); +TilingShader.prototype.constructor = TilingShader; +module.exports = TilingShader; + + +},{"../../core/Shader":42}],131:[function(require,module,exports){ +var core = require('../../core'), + BlurXFilter = require('./BlurXFilter'), + BlurYFilter = require('./BlurYFilter'); + +/** + * The BlurFilter applies a Gaussian blur to an object. + * The strength of the blur can be set for x- and y-axis separately. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +function BlurFilter(strength, quality, resolution) +{ + core.Filter.call(this); + + this.blurXFilter = new BlurXFilter(); + this.blurYFilter = new BlurYFilter(); + this.resolution = 1; + + this.padding = 0; + this.resolution = resolution || 1; + this.quality = quality || 4; + this.blur = strength || 8; +} + +BlurFilter.prototype = Object.create(core.Filter.prototype); +BlurFilter.prototype.constructor = BlurFilter; +module.exports = BlurFilter; + +BlurFilter.prototype.apply = function (filterManager, input, output) +{ + + var renderTarget = filterManager.getRenderTarget(true); + + this.blurXFilter.apply(filterManager, input, renderTarget, true); + this.blurYFilter.apply(filterManager, renderTarget, output, false); + + filterManager.returnRenderTarget(renderTarget); +}; + +Object.defineProperties(BlurFilter.prototype, { + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * + * @member {number} + * @memberOf PIXI.filters.BlurFilter# + * @default 2 + */ + blur: { + get: function () + { + return this.blurXFilter.blur; + }, + set: function (value) + { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.padding = Math.max( Math.abs(this.blurYFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + }, + + /** + * Sets the number of passes for blur. More passes means higher quaility bluring. + * + * @member {number} + * @memberof PIXI.filters.BlurYFilter# + * @default 1 + */ + quality: { + get: function () + { + return this.blurXFilter.quality; + }, + set: function (value) + { + + this.blurXFilter.quality = this.blurYFilter.quality = value; + } + }, + + /** + * Sets the strength of the blurX property + * + * @member {number} + * @memberOf PIXI.filters.BlurFilter# + * @default 2 + */ + blurX: { + get: function () + { + return this.blurXFilter.blur; + }, + set: function (value) + { + this.blurXFilter.blur = value; + this.padding = Math.max( Math.abs(this.blurYFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + }, + + /** + * Sets the strength of the blurY property + * + * @member {number} + * @memberOf PIXI.filters.BlurFilter# + * @default 2 + */ + blurY: { + get: function () + { + return this.blurYFilter.blur; + }, + set: function (value) + { + this.blurYFilter.blur = value; + this.padding = Math.max( Math.abs(this.blurYFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + } +}); + +},{"../../core":62,"./BlurXFilter":132,"./BlurYFilter":133}],132:[function(require,module,exports){ +var core = require('../../core'); +var generateBlurVertSource = require('./generateBlurVertSource'); +var generateBlurFragSource = require('./generateBlurFragSource'); +var getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +/** + * The BlurXFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +function BlurXFilter(strength, quality, resolution) +{ + var vertSrc = generateBlurVertSource(5, true); + var fragSrc = generateBlurFragSource(5); + + core.Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc + ); + + this.resolution = resolution || 1; + + this._quality = 0; + + this.quality = quality || 4; + this.strength = strength || 8; + + this.firstRun = true; + +} + +BlurXFilter.prototype = Object.create(core.Filter.prototype); +BlurXFilter.prototype.constructor = BlurXFilter; +module.exports = BlurXFilter; + +BlurXFilter.prototype.apply = function (filterManager, input, output, clear) +{ + if(this.firstRun) + { + var gl = filterManager.renderer.gl; + var kernelSize = getMaxBlurKernelSize(gl); + + this.vertexSrc = generateBlurVertSource(kernelSize, true); + this.fragmentSrc = generateBlurFragSource(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = (1/output.size.width) * (output.size.width/input.size.width); /// // * 2 //4//this.strength / 4 / this.passes * (input.frame.width / input.size.width); + + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes;// / this.passes//Math.pow(1, this.passes); + + if(this.passes === 1) + { + filterManager.applyFilter(this, input, output, clear); + } + else + { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for(var i = 0; i < this.passes-1; i++) + { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } +}; + + +Object.defineProperties(BlurXFilter.prototype, { + /** + * Sets the strength of both the blur. + * + * @member {number} + * @memberof PIXI.filters.BlurXFilter# + * @default 16 + */ + blur: { + get: function () + { + return this.strength; + }, + set: function (value) + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + }, + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher quaility bluring but the lower the performance. + * + * @member {number} + * @memberof PIXI.filters.BlurXFilter# + * @default 4 + */ + quality: { + get: function () + { + return this._quality; + }, + set: function (value) + { + this._quality = value; + this.passes = value; + } + } +}); + +},{"../../core":62,"./generateBlurFragSource":134,"./generateBlurVertSource":135,"./getMaxBlurKernelSize":136}],133:[function(require,module,exports){ +var core = require('../../core'); +var generateBlurVertSource = require('./generateBlurVertSource'); +var generateBlurFragSource = require('./generateBlurFragSource'); +var getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +/** + * The BlurYFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +function BlurYFilter(strength, quality, resolution) +{ + var vertSrc = generateBlurVertSource(5, false); + var fragSrc = generateBlurFragSource(5); + + core.Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc + ); + + this.resolution = resolution || 1; + + this._quality = 0; + + this.quality = quality || 4; + this.strength = strength || 8; + + this.firstRun = true; +} + +BlurYFilter.prototype = Object.create(core.Filter.prototype); +BlurYFilter.prototype.constructor = BlurYFilter; +module.exports = BlurYFilter; + +BlurYFilter.prototype.apply = function (filterManager, input, output, clear) +{ + if(this.firstRun) + { + var gl = filterManager.renderer.gl; + var kernelSize = getMaxBlurKernelSize(gl); + + this.vertexSrc = generateBlurVertSource(kernelSize, false); + this.fragmentSrc = generateBlurFragSource(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = (1/output.size.height) * (output.size.height/input.size.height); /// // * 2 //4//this.strength / 4 / this.passes * (input.frame.width / input.size.width); + + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + + if(this.passes === 1) + { + filterManager.applyFilter(this, input, output, clear); + } + else + { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for(var i = 0; i < this.passes-1; i++) + { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } +}; + + +Object.defineProperties(BlurYFilter.prototype, { + /** + * Sets the strength of both the blur. + * + * @member {number} + * @memberof PIXI.filters.BlurYFilter# + * @default 2 + */ + blur: { + get: function () + { + return this.strength; + }, + set: function (value) + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + }, + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher quaility bluring but the lower the performance. + * + * @member {number} + * @memberof PIXI.filters.BlurXFilter# + * @default 4 + */ + quality: { + get: function () + { + return this._quality; + }, + set: function (value) + { + this._quality = value; + this.passes = value; + } + } +}); + +},{"../../core":62,"./generateBlurFragSource":134,"./generateBlurVertSource":135,"./getMaxBlurKernelSize":136}],134:[function(require,module,exports){ +var GAUSSIAN_VALUES = { + 5:[0.153388, 0.221461, 0.250301], + 7:[0.071303, 0.131514, 0.189879, 0.214607], + 9:[0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11:[0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13:[0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15:[0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] +}; + +var fragTemplate = [ + 'varying vec2 vBlurTexCoords[%size%];', + 'uniform sampler2D uSampler;', + + 'void main(void)', + '{', + ' gl_FragColor = vec4(0.0);', + ' %blur%', + '}' + +].join('\n'); + +var generateFragBlurSource = function(kernelSize) +{ + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + + var fragSource = fragTemplate; + + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value; + + for (var i = 0; i < kernelSize; i++) + { + var blur = template.replace('%index%', i); + + value = i; + + if(i >= halfLength) + { + value = kernelSize - i - 1; + } + + + blur = blur.replace('%value%', kernel[value]); + + blurLoop += blur; + blurLoop += '\n'; + } + + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize); + + + return fragSource; +}; + + + +module.exports = generateFragBlurSource; + +},{}],135:[function(require,module,exports){ + +var vertTemplate = [ + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + + 'uniform float strength;', + 'uniform mat3 projectionMatrix;', + + 'varying vec2 vBlurTexCoords[%size%];', + + 'void main(void)', + '{', + 'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);', + '%blur%', + '}' +].join('\n'); + +var generateVertBlurSource = function(kernelSize, x) +{ + var halfLength = Math.ceil(kernelSize/2); + + var vertSource = vertTemplate; + + var blurLoop = ''; + var template; + var value; + + if(x) + { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } + else + { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; + + } + + + for (var i = 0; i < kernelSize; i++) + { + var blur = template.replace('%index%', i); + + value = i; + + if(i >= halfLength) + { + value = kernelSize - i - 1; + } + + blur = blur.replace('%sampleIndex%', (i - (halfLength-1)) + '.0'); + + blurLoop += blur; + blurLoop += '\n'; + } + + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize); + + return vertSource; +}; + + + +module.exports = generateVertBlurSource; + +},{}],136:[function(require,module,exports){ + + +var getMaxKernelSize = function(gl) +{ + var maxVaryings = ( gl.getParameter(gl.MAX_VARYING_VECTORS) ); + var kernelSize = 15; + + while(kernelSize > maxVaryings) + { + kernelSize -= 2; + } + + return kernelSize; +}; + +module.exports = getMaxKernelSize; + +},{}],137:[function(require,module,exports){ +var core = require('../../core'); +// @see https://github.com/substack/brfs/issues/25 + + +/** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * var colorMatrix = new PIXI.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +function ColorMatrixFilter() +{ + core.Filter.call(this, + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}", + // fragment shader + "#define GLSLIFY 1\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\n\nvoid main(void)\n{\n\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n gl_FragColor.r = (m[0] * c.r);\n gl_FragColor.r += (m[1] * c.g);\n gl_FragColor.r += (m[2] * c.b);\n gl_FragColor.r += (m[3] * c.a);\n gl_FragColor.r += m[4] * c.a;\n\n gl_FragColor.g = (m[5] * c.r);\n gl_FragColor.g += (m[6] * c.g);\n gl_FragColor.g += (m[7] * c.b);\n gl_FragColor.g += (m[8] * c.a);\n gl_FragColor.g += m[9] * c.a;\n\n gl_FragColor.b = (m[10] * c.r);\n gl_FragColor.b += (m[11] * c.g);\n gl_FragColor.b += (m[12] * c.b);\n gl_FragColor.b += (m[13] * c.a);\n gl_FragColor.b += m[14] * c.a;\n\n gl_FragColor.a = (m[15] * c.r);\n gl_FragColor.a += (m[16] * c.g);\n gl_FragColor.a += (m[17] * c.b);\n gl_FragColor.a += (m[18] * c.a);\n gl_FragColor.a += m[19] * c.a;\n\n// gl_FragColor = vec4(m[0]);\n}\n" + ); + + this.uniforms.m = [ + 1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0]; + + +} + +ColorMatrixFilter.prototype = Object.create(core.Filter.prototype); +ColorMatrixFilter.prototype.constructor = ColorMatrixFilter; +module.exports = ColorMatrixFilter; + + +/** + * Transforms current matrix and set the new one + * + * @param matrix {number[]} (mat 5x4) + * @param multiply {boolean} if true, current matrix and matrix are multiplied. If false, just set the current matrix with @param matrix + */ +ColorMatrixFilter.prototype._loadMatrix = function (matrix, multiply) +{ + multiply = !!multiply; + + var newMatrix = matrix; + + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + + // set the new matrix + this.uniforms.m = newMatrix; +}; + +/** + * Multiplies two mat5's + * + * @param out {number[]} (mat 5x4) the receiving matrix + * @param a {number[]} (mat 5x4) the first operand + * @param b {number[]} (mat 5x4) the second operand + * @returns out {number[]} (mat 5x4) + */ +ColorMatrixFilter.prototype._multiply = function (out, a, b) +{ + + // Red Channel + out[0] = (a[0] * b[0]) + (a[1] * b[5]) + (a[2] * b[10]) + (a[3] * b[15]); + out[1] = (a[0] * b[1]) + (a[1] * b[6]) + (a[2] * b[11]) + (a[3] * b[16]); + out[2] = (a[0] * b[2]) + (a[1] * b[7]) + (a[2] * b[12]) + (a[3] * b[17]); + out[3] = (a[0] * b[3]) + (a[1] * b[8]) + (a[2] * b[13]) + (a[3] * b[18]); + out[4] = (a[0] * b[4]) + (a[1] * b[9]) + (a[2] * b[14]) + (a[3] * b[19]); + + // Green Channel + out[5] = (a[5] * b[0]) + (a[6] * b[5]) + (a[7] * b[10]) + (a[8] * b[15]); + out[6] = (a[5] * b[1]) + (a[6] * b[6]) + (a[7] * b[11]) + (a[8] * b[16]); + out[7] = (a[5] * b[2]) + (a[6] * b[7]) + (a[7] * b[12]) + (a[8] * b[17]); + out[8] = (a[5] * b[3]) + (a[6] * b[8]) + (a[7] * b[13]) + (a[8] * b[18]); + out[9] = (a[5] * b[4]) + (a[6] * b[9]) + (a[7] * b[14]) + (a[8] * b[19]); + + // Blue Channel + out[10] = (a[10] * b[0]) + (a[11] * b[5]) + (a[12] * b[10]) + (a[13] * b[15]); + out[11] = (a[10] * b[1]) + (a[11] * b[6]) + (a[12] * b[11]) + (a[13] * b[16]); + out[12] = (a[10] * b[2]) + (a[11] * b[7]) + (a[12] * b[12]) + (a[13] * b[17]); + out[13] = (a[10] * b[3]) + (a[11] * b[8]) + (a[12] * b[13]) + (a[13] * b[18]); + out[14] = (a[10] * b[4]) + (a[11] * b[9]) + (a[12] * b[14]) + (a[13] * b[19]); + + // Alpha Channel + out[15] = (a[15] * b[0]) + (a[16] * b[5]) + (a[17] * b[10]) + (a[18] * b[15]); + out[16] = (a[15] * b[1]) + (a[16] * b[6]) + (a[17] * b[11]) + (a[18] * b[16]); + out[17] = (a[15] * b[2]) + (a[16] * b[7]) + (a[17] * b[12]) + (a[18] * b[17]); + out[18] = (a[15] * b[3]) + (a[16] * b[8]) + (a[17] * b[13]) + (a[18] * b[18]); + out[19] = (a[15] * b[4]) + (a[16] * b[9]) + (a[17] * b[14]) + (a[18] * b[19]); + + return out; +}; + +/** + * Create a Float32 Array and normalize the offset component to 0-1 + * + * @param matrix {number[]} (mat 5x4) + * @return m {number[]} (mat 5x4) with all values between 0-1 + */ +ColorMatrixFilter.prototype._colorMatrix = function (matrix) +{ + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + + return m; +}; + +/** + * Adjusts brightness + * + * @param b {number} value of the brigthness (0 is black) + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.brightness = function (b, multiply) +{ + var matrix = [ + b, 0, 0, 0, 0, + 0, b, 0, 0, 0, + 0, 0, b, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Set the matrices in grey scales + * + * @param scale {number} value of the grey (0 is black) + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.greyscale = function (scale, multiply) +{ + var matrix = [ + scale, scale, scale, 0, 0, + scale, scale, scale, 0, 0, + scale, scale, scale, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; +//Americanized alias +ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + +/** + * Set the black and white matrice + * Multiply the current matrix + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.blackAndWhite = function (multiply) +{ + var matrix = [ + 0.3, 0.6, 0.1, 0, 0, + 0.3, 0.6, 0.1, 0, 0, + 0.3, 0.6, 0.1, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Set the hue property of the color + * + * @param rotation {number} in degrees + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.hue = function (rotation, multiply) +{ + rotation = (rotation || 0) / 180 * Math.PI; + + var cosR = Math.cos(rotation), + sinR = Math.sin(rotation), + sqrt = Math.sqrt; + + /*a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + + var w = 1/3, sqrW = sqrt(w);//weight is + + var a00 = cosR + (1.0 - cosR) * w; + var a01 = w * (1.0 - cosR) - sqrW * sinR; + var a02 = w * (1.0 - cosR) + sqrW * sinR; + + var a10 = w * (1.0 - cosR) + sqrW * sinR; + var a11 = cosR + w*(1.0 - cosR); + var a12 = w * (1.0 - cosR) - sqrW * sinR; + + var a20 = w * (1.0 - cosR) - sqrW * sinR; + var a21 = w * (1.0 - cosR) + sqrW * sinR; + var a22 = cosR + w * (1.0 - cosR); + + + var matrix = [ + a00, a01, a02, 0, 0, + a10, a11, a12, 0, 0, + a20, a21, a22, 0, 0, + 0, 0, 0, 1, 0, + ]; + + this._loadMatrix(matrix, multiply); +}; + + +/** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * + * @param amount {number} value of the contrast + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.contrast = function (amount, multiply) +{ + var v = (amount || 0) + 1; + var o = -128 * (v - 1); + + var matrix = [ + v, 0, 0, 0, o, + 0, v, 0, 0, o, + 0, 0, v, 0, o, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * + * @param [amount=0] {number} + * @param [multiply] {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.saturate = function (amount, multiply) +{ + var x = (amount || 0) * 2 / 3 + 1; + var y = ((x - 1) * -0.5); + + var matrix = [ + x, y, y, 0, 0, + y, x, y, 0, 0, + y, y, x, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Desaturate image (remove color) + * + * Call the saturate function + * + */ +ColorMatrixFilter.prototype.desaturate = function () // jshint unused:false +{ + this.saturate(-1); +}; + +/** + * Negative image (inverse of classic rgb matrix) + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.negative = function (multiply) +{ + var matrix = [ + 0, 1, 1, 0, 0, + 1, 0, 1, 0, 0, + 1, 1, 0, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Sepia image + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.sepia = function (multiply) +{ + var matrix = [ + 0.393, 0.7689999, 0.18899999, 0, 0, + 0.349, 0.6859999, 0.16799999, 0, 0, + 0.272, 0.5339999, 0.13099999, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.technicolor = function (multiply) +{ + var matrix = [ + 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, + -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, + -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Polaroid filter + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.polaroid = function (multiply) +{ + var matrix = [ + 1.438, -0.062, -0.062, 0, 0, + -0.122, 1.378, -0.122, 0, 0, + -0.016, -0.016, 1.483, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Filter who transforms : Red -> Blue and Blue -> Red + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.toBGR = function (multiply) +{ + var matrix = [ + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 1, 0, 0, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.kodachrome = function (multiply) +{ + var matrix = [ + 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, + -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, + -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/** + * Brown delicious browni filter (thanks Dominic Szablewski) + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.browni = function (multiply) +{ + var matrix = [ + 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, + -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, + 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/* + * Vintage filter (thanks Dominic Szablewski) + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.vintage = function (multiply) +{ + var matrix = [ + 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, + 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, + 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/* + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * + * @param desaturation {number} + * @param toned {number} + * @param lightColor {string} (example : "0xFFE580") + * @param darkColor {string} (example : "0xFFE580") + * + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.colorTone = function (desaturation, toned, lightColor, darkColor, multiply) +{ + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + + var lR = ((lightColor >> 16) & 0xFF) / 255; + var lG = ((lightColor >> 8) & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + + var dR = ((darkColor >> 16) & 0xFF) / 255; + var dG = ((darkColor >> 8) & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + + var matrix = [ + 0.3, 0.59, 0.11, 0, 0, + lR, lG, lB, desaturation, 0, + dR, dG, dB, toned, 0, + lR - dR, lG - dG, lB - dB, 0, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/* + * Night effect + * + * @param intensity {number} + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.night = function (intensity, multiply) +{ + intensity = intensity || 0.1; + var matrix = [ + intensity * ( -2.0), -intensity, 0, 0, 0, + -intensity, 0, intensity, 0, 0, + 0, intensity, intensity * 2.0, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + + +/* + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * + * @param amount {number} how much the predator feels his future victim + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.predator = function (amount, multiply) +{ + var matrix = [ + 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, + -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, + -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/* + * LSD effect + * + * Multiply the current matrix + * + * @param amount {number} How crazy is your effect + * @param multiply {boolean} refer to ._loadMatrix() method + */ +ColorMatrixFilter.prototype.lsd = function (multiply) +{ + var matrix = [ + 2, -0.4, 0.5, 0, 0, + -0.5, 2, -0.4, 0, 0, + -0.4, -0.5, 3, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, multiply); +}; + +/* + * Erase the current matrix by setting the default one + * + */ +ColorMatrixFilter.prototype.reset = function () +{ + var matrix = [ + 1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0 + ]; + + this._loadMatrix(matrix, false); +}; + + +Object.defineProperties(ColorMatrixFilter.prototype, { + /** + * Sets the matrix of the color matrix filter + * + * @member {number[]} + * @memberof PIXI.filters.ColorMatrixFilter# + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + matrix: { + get: function () + { + return this.uniforms.m; + }, + set: function (value) + { + this.uniforms.m = value; + } + } +}); + +},{"../../core":62}],138:[function(require,module,exports){ +var core = require('../../core'); + + +/** + * The DisplacementFilter class uses the pixel values from the specified texture (called the displacement map) to perform a displacement of an object. + * You can use this filter to apply all manor of crazy warping effects + * Currently the r property of the texture is used to offset the x and the g property of the texture is used to offset the y. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + * @param sprite {PIXI.Sprite} The sprite used for the displacement map. (make sure its added to the scene!) + * @param scale {number} The scale of the displacement + */ +function DisplacementFilter(sprite, scale) +{ + var maskMatrix = new core.Matrix(); + sprite.renderable = false; + + core.Filter.call(this, + // vertex shader +// glslify('./displacement.vert'), + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}", + // fragment shader + "#define GLSLIFY 1\nvarying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n" + + ); + + this.maskSprite = sprite; + this.maskMatrix = maskMatrix; + + this.uniforms.mapSampler = sprite.texture; + this.uniforms.filterMatrix = maskMatrix.toArray(true); + this.uniforms.scale = { x: 1, y: 1 }; + + if (scale === null || scale === undefined) + { + scale = 20; + } + + this.scale = new core.Point(scale, scale); +} + +DisplacementFilter.prototype = Object.create(core.Filter.prototype); +DisplacementFilter.prototype.constructor = DisplacementFilter; +module.exports = DisplacementFilter; + +DisplacementFilter.prototype.apply = function (filterManager, input, output) +{ + var ratio = (1/output.destinationFrame.width) * (output.size.width/input.size.width); /// // * 2 //4//this.strength / 4 / this.passes * (input.frame.width / input.size.width); + + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x * ratio; + this.uniforms.scale.y = this.scale.y * ratio; + + // draw the filter... + filterManager.applyFilter(this, input, output); +}; + + +Object.defineProperties(DisplacementFilter.prototype, { + /** + * The texture used for the displacement map. Must be power of 2 sized texture. + * + * @member {PIXI.Texture} + * @memberof PIXI.filters.DisplacementFilter# + */ + map: { + get: function () + { + return this.uniforms.mapSampler; + }, + set: function (value) + { + this.uniforms.mapSampler = value; + + } + } +}); + +},{"../../core":62}],139:[function(require,module,exports){ +var core = require('../../core'); + + +/** + * + * Basic FXAA implementation based on the code on geeks3d.com with the + * modification that the texture2DLod stuff was removed since it's + * unsupported by WebGL. + * + * @see https://github.com/mitsuhiko/webgl-meincraft + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + * + */ +function FXAAFilter() +{ + //TODO - needs work + core.Filter.call(this, + + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}", + // fragment shader + "#define GLSLIFY 1\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it's\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n \tvec2 fragCoord = vTextureCoord * filterArea.xy;\n\n \tvec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n \tgl_FragColor = color;\n}\n" + ); + +} + +FXAAFilter.prototype = Object.create(core.Filter.prototype); +FXAAFilter.prototype.constructor = FXAAFilter; + +module.exports = FXAAFilter; + +},{"../../core":62}],140:[function(require,module,exports){ +/** + * @file Main export of the PIXI filters library + * @author Mat Groves + * @copyright 2013-2015 GoodBoyDigital + * @license {@link https://github.com/pixijs/pixi.js/blob/master/LICENSE|MIT License} + */ + +/** + * @namespace PIXI.filters + */ +module.exports = { + FXAAFilter: require('./fxaa/FXAAFilter'), + NoiseFilter: require('./noise/NoiseFilter'), + DisplacementFilter: require('./displacement/DisplacementFilter'), + BlurFilter: require('./blur/BlurFilter'), + BlurXFilter: require('./blur/BlurXFilter'), + BlurYFilter: require('./blur/BlurYFilter'), + ColorMatrixFilter: require('./colormatrix/ColorMatrixFilter'), + VoidFilter: require('./void/VoidFilter') +}; + +},{"./blur/BlurFilter":131,"./blur/BlurXFilter":132,"./blur/BlurYFilter":133,"./colormatrix/ColorMatrixFilter":137,"./displacement/DisplacementFilter":138,"./fxaa/FXAAFilter":139,"./noise/NoiseFilter":141,"./void/VoidFilter":142}],141:[function(require,module,exports){ +var core = require('../../core'); + + +/** + * @author Vico @vicocotea + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + */ + +/** + * A Noise effect filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +function NoiseFilter() +{ + core.Filter.call(this, + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}", + // fragment shader + "precision highp float;\n#define GLSLIFY 1\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float noise;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n float diff = (rand(gl_FragCoord.xy) - 0.5) * noise;\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n gl_FragColor = color;\n}\n" + ); + + this.noise = 0.5; +} + +NoiseFilter.prototype = Object.create(core.Filter.prototype); +NoiseFilter.prototype.constructor = NoiseFilter; +module.exports = NoiseFilter; + +Object.defineProperties(NoiseFilter.prototype, { + /** + * The amount of noise to apply. + * + * @member {number} + * @memberof PIXI.filters.NoiseFilter# + * @default 0.5 + */ + noise: { + get: function () + { + return this.uniforms.noise; + }, + set: function (value) + { + this.uniforms.noise = value; + } + } +}); + +},{"../../core":62}],142:[function(require,module,exports){ +var core = require('../../core'); +// @see https://github.com/substack/brfs/issues/25 + + +/** + * Does nothing. Very handy. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +function VoidFilter() +{ + core.Filter.call(this, + // vertex shader + "#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}", + // fragment shader + "#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n" + ); + + this.glShaderKey = 'void'; +} + +VoidFilter.prototype = Object.create(core.Filter.prototype); +VoidFilter.prototype.constructor = VoidFilter; +module.exports = VoidFilter; + +},{"../../core":62}],143:[function(require,module,exports){ +var core = require('../core'); + +/** + * Holds all information related to an Interaction event + * + * @class + * @memberof PIXI.interaction + */ +function InteractionData() +{ + /** + * This point stores the global coords of where the touch/mouse event happened + * + * @member {PIXI.Point} + */ + this.global = new core.Point(); + + /** + * The target Sprite that was interacted with + * + * @member {PIXI.Sprite} + */ + this.target = null; + + /** + * When passed to an event handler, this will be the original DOM Event that was captured + * + * @member {Event} + */ + this.originalEvent = null; +} + +InteractionData.prototype.constructor = InteractionData; +module.exports = InteractionData; + +/** + * This will return the local coordinates of the specified displayObject for this InteractionData + * + * @param displayObject {PIXI.DisplayObject} The DisplayObject that you would like the local coords off + * @param [point] {PIXI.Point} A Point object in which to store the value, optional (otherwise will create a new point) + * @param [globalPos] {PIXI.Point} A Point object containing your custom global coords, optional (otherwise will use the current global coords) + * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative to the DisplayObject + */ +InteractionData.prototype.getLocalPosition = function (displayObject, point, globalPos) +{ + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); +}; + +},{"../core":62}],144:[function(require,module,exports){ +var core = require('../core'), + InteractionData = require('./InteractionData'), + EventEmitter = require('eventemitter3'); + +// Mix interactiveTarget into core.DisplayObject.prototype +Object.assign( + core.DisplayObject.prototype, + require('./interactiveTarget') +); + +/** + * The interaction manager deals with mouse and touch events. Any DisplayObject can be interactive + * if its interactive parameter is set to true + * This manager also supports multitouch. + * + * @class + * @extends EventEmitter + * @memberof PIXI.interaction + * @param renderer {PIXI.CanvasRenderer|PIXI.WebGLRenderer} A reference to the current renderer + * @param [options] {object} + * @param [options.autoPreventDefault=true] {boolean} Should the manager automatically prevent default browser actions. + * @param [options.interactionFrequency=10] {number} Frequency increases the interaction events will be checked. + */ +function InteractionManager(renderer, options) +{ + EventEmitter.call(this); + + options = options || {}; + + /** + * The renderer this interaction manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * Should default browser actions automatically be prevented. + * + * @member {boolean} + * @default true + */ + this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + + /** + * As this frequency increases the interaction events will be checked more often. + * + * @member {number} + * @default 10 + */ + this.interactionFrequency = options.interactionFrequency || 10; + + /** + * The mouse data + * + * @member {PIXI.interaction.InteractionData} + */ + this.mouse = new InteractionData(); + + // setting the pointer to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + this.mouse.global.set(-999999); + + /** + * An event data object to handle all the event tracking/dispatching + * + * @member {object} + */ + this.eventData = { + stopped: false, + target: null, + type: null, + data: this.mouse, + stopPropagation:function(){ + this.stopped = true; + } + }; + + /** + * Tiny little interactiveData pool ! + * + * @member {PIXI.interaction.InteractionData[]} + */ + this.interactiveDataPool = []; + + /** + * The DOM element to bind to. + * + * @member {HTMLElement} + * @private + */ + this.interactionDOMElement = null; + + /** + * This property determins if mousemove and touchmove events are fired only when the cursror is over the object + * Setting to true will make things work more in line with how the DOM verison works. + * Setting to false can make things easier for things like dragging + * It is currently set to false as this is how pixi used to work. This will be set to true in future versions of pixi. + * @member {boolean} + * @private + */ + this.moveWhenInside = false; + + /** + * Have events been attached to the dom element? + * + * @member {boolean} + * @private + */ + this.eventsAdded = false; + + //this will make it so that you don't have to call bind all the time + + /** + * @member {Function} + * @private + */ + this.onMouseUp = this.onMouseUp.bind(this); + this.processMouseUp = this.processMouseUp.bind( this ); + + + /** + * @member {Function} + * @private + */ + this.onMouseDown = this.onMouseDown.bind(this); + this.processMouseDown = this.processMouseDown.bind( this ); + + /** + * @member {Function} + * @private + */ + this.onMouseMove = this.onMouseMove.bind( this ); + this.processMouseMove = this.processMouseMove.bind( this ); + + /** + * @member {Function} + * @private + */ + this.onMouseOut = this.onMouseOut.bind(this); + this.processMouseOverOut = this.processMouseOverOut.bind( this ); + + /** + * @member {Function} + * @private + */ + this.onMouseOver = this.onMouseOver.bind(this); + + + /** + * @member {Function} + * @private + */ + this.onTouchStart = this.onTouchStart.bind(this); + this.processTouchStart = this.processTouchStart.bind(this); + + /** + * @member {Function} + * @private + */ + this.onTouchEnd = this.onTouchEnd.bind(this); + this.processTouchEnd = this.processTouchEnd.bind(this); + + /** + * @member {Function} + * @private + */ + this.onTouchMove = this.onTouchMove.bind(this); + this.processTouchMove = this.processTouchMove.bind(this); + + /** + * Every update cursor will be reset to this value, if some element wont override it in its hitTest + * @member {string} + * @default 'inherit' + */ + this.defaultCursorStyle = 'inherit'; + + /** + * The css style of the cursor that is being used + * @member {string} + */ + this.currentCursorStyle = 'inherit'; + + /** + * Internal cached var + * @member {PIXI.Point} + * @private + */ + this._tempPoint = new core.Point(); + + + /** + * The current resolution / device pixel ratio. + * @member {number} + * @default 1 + */ + this.resolution = 1; + + this.setTargetElement(this.renderer.view, this.renderer.resolution); + + /** + * Fired when a pointing device button (usually a mouse button) is pressed on the display object. + * + * @memberof PIXI.interaction.InteractionManager# + * @event mousedown + */ + + /** + * Fired when a pointing device secondary button (usually a mouse right-button) is pressed on the display object. + * + * @memberof PIXI.interaction.InteractionManager# + * @event rightdown + */ + + /** + * Fired when a pointing device button (usually a mouse button) is released over the display object. + * + * @memberof PIXI.interaction.InteractionManager# + * @event mouseup + */ + + /** + * Fired when a pointing device secondary button (usually a mouse right-button) is released over the display object. + * + * @memberof PIXI.interaction.InteractionManager# + * @event rightup + */ + + /** + * Fired when a pointing device button (usually a mouse button) is pressed and released on the display object. + * + * @event click + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointing device secondary button (usually a mouse right-button) is pressed and released on the display object. + * + * @event rightclick + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointing device button (usually a mouse button) is released outside the display object that initially registered a [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. + * + * @event mouseupoutside + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointing device secondary button (usually a mouse right-button) is released outside the display object that initially + * registered a [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. + * + * @event rightupoutside + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointing device (usually a mouse) is moved while over the display object + * + * @event mousemove + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointing device (usually a mouse) is moved onto the display object + * + * @event mouseover + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointing device (usually a mouse) is moved off the display object + * + * @event mouseout + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is placed on the display object. + * + * @event touchstart + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is removed from the display object. + * + * @event touchend + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * + * @event tap + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is removed outside of the display object that initially registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. + * + * @event touchendoutside + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is moved along the display object. + * + * @event touchmove + * @memberof PIXI.interaction.InteractionManager# + */ +} + +InteractionManager.prototype = Object.create(EventEmitter.prototype); +InteractionManager.prototype.constructor = InteractionManager; +module.exports = InteractionManager; + +/** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate + * another DOM element to receive those events. + * + * @param element {HTMLElement} the DOM element which will receive mouse and touch events. + * @param [resolution=1] {number} The resolution / device pixel ratio of the new element (relative to the canvas). + * @private + */ +InteractionManager.prototype.setTargetElement = function (element, resolution) +{ + this.removeEvents(); + + this.interactionDOMElement = element; + + this.resolution = resolution || 1; + + this.addEvents(); +}; + +/** + * Registers all the DOM events + * + * @private + */ +InteractionManager.prototype.addEvents = function () +{ + if (!this.interactionDOMElement) + { + return; + } + + core.ticker.shared.add(this.update, this); + + if (window.navigator.msPointerEnabled) + { + this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; + this.interactionDOMElement.style['-ms-touch-action'] = 'none'; + } + + window.document.addEventListener('mousemove', this.onMouseMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onMouseDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onMouseOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onMouseOver, true); + + this.interactionDOMElement.addEventListener('touchstart', this.onTouchStart, true); + this.interactionDOMElement.addEventListener('touchend', this.onTouchEnd, true); + this.interactionDOMElement.addEventListener('touchmove', this.onTouchMove, true); + + window.addEventListener('mouseup', this.onMouseUp, true); + + this.eventsAdded = true; +}; + +/** + * Removes all the DOM events that were previously registered + * + * @private + */ +InteractionManager.prototype.removeEvents = function () +{ + if (!this.interactionDOMElement) + { + return; + } + + core.ticker.shared.remove(this.update); + + if (window.navigator.msPointerEnabled) + { + this.interactionDOMElement.style['-ms-content-zooming'] = ''; + this.interactionDOMElement.style['-ms-touch-action'] = ''; + } + + window.document.removeEventListener('mousemove', this.onMouseMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onMouseDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onMouseOut, true); + this.interactionDOMElement.removeEventListener('mouseover', this.onMouseOver, true); + + this.interactionDOMElement.removeEventListener('touchstart', this.onTouchStart, true); + this.interactionDOMElement.removeEventListener('touchend', this.onTouchEnd, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onTouchMove, true); + + this.interactionDOMElement = null; + + window.removeEventListener('mouseup', this.onMouseUp, true); + + this.eventsAdded = false; +}; + +/** + * Updates the state of interactive objects. + * Invoked by a throttled ticker update from + * {@link PIXI.ticker.shared}. + * + * @param deltaTime {number} time delta since last tick + */ +InteractionManager.prototype.update = function (deltaTime) +{ + this._deltaTime += deltaTime; + + if (this._deltaTime < this.interactionFrequency) + { + return; + } + + this._deltaTime = 0; + + if (!this.interactionDOMElement) + { + return; + } + + // if the user move the mouse this check has already been dfone using the mouse move! + if(this.didMove) + { + this.didMove = false; + return; + } + + this.cursor = this.defaultCursorStyle; + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseOverOut, true ); + + if (this.currentCursorStyle !== this.cursor) + { + this.currentCursorStyle = this.cursor; + this.interactionDOMElement.style.cursor = this.cursor; + } + + //TODO +}; + +/** + * Dispatches an event on the display object that was interacted with + * + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} the display object in question + * @param eventString {string} the name of the event (e.g, mousedown) + * @param eventData {object} the event data object + * @private + */ +InteractionManager.prototype.dispatchEvent = function ( displayObject, eventString, eventData ) +{ + if(!eventData.stopped) + { + eventData.target = displayObject; + eventData.type = eventString; + + displayObject.emit( eventString, eventData ); + + if( displayObject[eventString] ) + { + displayObject[eventString]( eventData ); + } + } +}; + +/** + * Maps x and y coords from a DOM object and maps them correctly to the pixi view. The resulting value is stored in the point. + * This takes into account the fact that the DOM element could be scaled and positioned anywhere on the screen. + * + * @param {PIXI.Point} point the point that the result will be stored in + * @param {number} x the x coord of the position to map + * @param {number} y the y coord of the position to map + */ +InteractionManager.prototype.mapPositionToPoint = function ( point, x, y ) +{ + var rect; + // IE 11 fix + if(!this.interactionDOMElement.parentElement) + { + rect = { x: 0, y: 0, width: 0, height: 0 }; + } else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + + point.x = ( ( x - rect.left ) * (this.interactionDOMElement.width / rect.width ) ) / this.resolution; + point.y = ( ( y - rect.top ) * (this.interactionDOMElement.height / rect.height ) ) / this.resolution; +}; + +/** + * This function is provides a neat way of crawling through the scene graph and running a specified function on all interactive objects it finds. + * It will also take care of hit testing the interactive objects and passes the hit across in the function. + * + * @param point {PIXI.Point} the point that is tested for collision + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} the displayObject that will be hit test (recurcsivly crawls its children) + * @param [func] {Function} the function that will be called on each interactive object. The displayObject and hit will be passed to the function + * @param [hitTest] {boolean} this indicates if the objects inside should be hit test against the point + * @param [interactive] {boolean} Whether the displayObject is interactive + * @return {boolean} returns true if the displayObject hit the point + */ +InteractionManager.prototype.processInteractive = function (point, displayObject, func, hitTest, interactive) +{ + if(!displayObject || !displayObject.visible) + { + return false; + } + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + var hit = false, + interactiveParent = interactive = displayObject.interactive || interactive; + + + + + // if the displayobject has a hitArea, then it does not need to hitTest children. + if(displayObject.hitArea) + { + interactiveParent = false; + } + + // it has a mask! Then lets hit test that before continuing.. + if(hitTest && displayObject._mask) + { + if(!displayObject._mask.containsPoint(point)) + { + hitTest = false; + } + } + + // it has a filterArea! Same as mask but easier, its a rectangle + if(hitTest && displayObject.filterArea) + { + if(!displayObject.filterArea.contains(point.x, point.y)) + { + hitTest = false; + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow pixi to completly ignore and bypass checking the displayObjects children. + if(displayObject.interactiveChildren) + { + var children = displayObject.children; + + for (var i = children.length-1; i >= 0; i--) + { + var child = children[i]; + + // time to get recursive.. if this function will return if somthing is hit.. + if(this.processInteractive(point, child, func, hitTest, interactiveParent)) + { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if(!child.parent) + { + continue; + } + + hit = true; + + // we no longer need to hit test any more objects in this container as we we now know the parent has been hit + interactiveParent = false; + + // If the child is interactive , that means that the object hit was actually interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run through all objects, but we don't need to perform any hit tests. + + //{ + hitTest = false; + //} + + // we can break now as we have hit an object. + } + } + } + + + + // no point running this if the item is not interactive or does not have an interactive parent. + if(interactive) + { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children has already been hit! + if(hitTest && !hit) + { + + if(displayObject.hitArea) + { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + hit = displayObject.hitArea.contains( this._tempPoint.x, this._tempPoint.y ); + } + else if(displayObject.containsPoint) + { + hit = displayObject.containsPoint(point); + } + + + } + + if(displayObject.interactive) + { + func(displayObject, hit); + } + } + + return hit; + +}; + + +/** + * Is called when the mouse button is pressed down on the renderer element + * + * @param event {Event} The DOM event of a mouse button being pressed down + * @private + */ +InteractionManager.prototype.onMouseDown = function (event) +{ + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData.stopped = false; + + // Update internal mouse reference + this.mapPositionToPoint( this.mouse.global, event.clientX, event.clientY); + + if (this.autoPreventDefault) + { + this.mouse.originalEvent.preventDefault(); + } + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseDown, true ); + + var isRightButton = event.button === 2 || event.which === 3; + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); +}; + +/** + * Processes the result of the mouse down check and dispatches the event if need be + * + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} The display object that was tested + * @param hit {boolean} the result of the hit test on the dispay object + * @private + */ +InteractionManager.prototype.processMouseDown = function ( displayObject, hit ) +{ + var e = this.mouse.originalEvent; + + var isRightButton = e.button === 2 || e.which === 3; + + if(hit) + { + displayObject[ isRightButton ? '_isRightDown' : '_isLeftDown' ] = true; + this.dispatchEvent( displayObject, isRightButton ? 'rightdown' : 'mousedown', this.eventData ); + } +}; + +/** + * Is called when the mouse button is released on the renderer element + * + * @param event {Event} The DOM event of a mouse button being released + * @private + */ +InteractionManager.prototype.onMouseUp = function (event) +{ + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData.stopped = false; + + // Update internal mouse reference + this.mapPositionToPoint( this.mouse.global, event.clientX, event.clientY); + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseUp, true ); + + var isRightButton = event.button === 2 || event.which === 3; + this.emit(isRightButton ? 'rightup' : 'mouseup', this.eventData); +}; + +/** + * Processes the result of the mouse up check and dispatches the event if need be + * + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} The display object that was tested + * @param hit {boolean} the result of the hit test on the display object + * @private + */ +InteractionManager.prototype.processMouseUp = function ( displayObject, hit ) +{ + var e = this.mouse.originalEvent; + + var isRightButton = e.button === 2 || e.which === 3; + var isDown = isRightButton ? '_isRightDown' : '_isLeftDown'; + + if(hit) + { + this.dispatchEvent( displayObject, isRightButton ? 'rightup' : 'mouseup', this.eventData ); + + if( displayObject[ isDown ] ) + { + displayObject[ isDown ] = false; + this.dispatchEvent( displayObject, isRightButton ? 'rightclick' : 'click', this.eventData ); + } + } + else + { + if( displayObject[ isDown ] ) + { + displayObject[ isDown ] = false; + this.dispatchEvent( displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', this.eventData ); + } + } +}; + + +/** + * Is called when the mouse moves across the renderer element + * + * @param event {Event} The DOM event of the mouse moving + * @private + */ +InteractionManager.prototype.onMouseMove = function (event) +{ + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData.stopped = false; + + this.mapPositionToPoint( this.mouse.global, event.clientX, event.clientY); + + this.didMove = true; + + this.cursor = this.defaultCursorStyle; + + this.processInteractive(this.mouse.global, this.renderer._lastObjectRendered, this.processMouseMove, true ); + + this.emit('mousemove', this.eventData); + + if (this.currentCursorStyle !== this.cursor) + { + this.currentCursorStyle = this.cursor; + this.interactionDOMElement.style.cursor = this.cursor; + } + + //TODO BUG for parents ineractive object (border order issue) +}; + +/** + * Processes the result of the mouse move check and dispatches the event if need be + * + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} The display object that was tested + * @param hit {boolean} the result of the hit test on the display object + * @private + */ +InteractionManager.prototype.processMouseMove = function ( displayObject, hit ) +{ + this.processMouseOverOut(displayObject, hit); + + // only display on mouse over + if(!this.moveWhenInside || hit) + { + this.dispatchEvent( displayObject, 'mousemove', this.eventData); + } +}; + + +/** + * Is called when the mouse is moved out of the renderer element + * + * @param event {Event} The DOM event of a mouse being moved out + * @private + */ +InteractionManager.prototype.onMouseOut = function (event) +{ + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData.stopped = false; + + // Update internal mouse reference + this.mapPositionToPoint( this.mouse.global, event.clientX, event.clientY); + + this.interactionDOMElement.style.cursor = this.defaultCursorStyle; + + // TODO optimize by not check EVERY TIME! maybe half as often? // + this.mapPositionToPoint( this.mouse.global, event.clientX, event.clientY ); + + this.processInteractive( this.mouse.global, this.renderer._lastObjectRendered, this.processMouseOverOut, false ); + + this.emit('mouseout', this.eventData); +}; + +/** + * Processes the result of the mouse over/out check and dispatches the event if need be + * + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} The display object that was tested + * @param hit {boolean} the result of the hit test on the display object + * @private + */ +InteractionManager.prototype.processMouseOverOut = function ( displayObject, hit ) +{ + if(hit) + { + if(!displayObject._over) + { + displayObject._over = true; + this.dispatchEvent( displayObject, 'mouseover', this.eventData ); + } + + if (displayObject.buttonMode) + { + this.cursor = displayObject.defaultCursor; + } + } + else + { + if(displayObject._over) + { + displayObject._over = false; + this.dispatchEvent( displayObject, 'mouseout', this.eventData); + } + } +}; + +/** + * Is called when the mouse enters the renderer element area + * + * @param event {Event} The DOM event of the mouse moving into the renderer view + * @private + */ +InteractionManager.prototype.onMouseOver = function(event) +{ + this.mouse.originalEvent = event; + this.eventData.data = this.mouse; + this.eventData.stopped = false; + + this.emit('mouseover', this.eventData); +}; + + +/** + * Is called when a touch is started on the renderer element + * + * @param event {Event} The DOM event of a touch starting on the renderer view + * @private + */ +InteractionManager.prototype.onTouchStart = function (event) +{ + if (this.autoPreventDefault) + { + event.preventDefault(); + } + + var changedTouches = event.changedTouches; + var cLength = changedTouches.length; + + for (var i=0; i < cLength; i++) + { + var touchEvent = changedTouches[i]; + //TODO POOL + var touchData = this.getTouchData( touchEvent ); + + touchData.originalEvent = event; + + this.eventData.data = touchData; + this.eventData.stopped = false; + + this.processInteractive( touchData.global, this.renderer._lastObjectRendered, this.processTouchStart, true ); + + this.emit('touchstart', this.eventData); + + this.returnTouchData( touchData ); + } +}; + +/** + * Processes the result of a touch check and dispatches the event if need be + * + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} The display object that was tested + * @param hit {boolean} the result of the hit test on the display object + * @private + */ +InteractionManager.prototype.processTouchStart = function ( displayObject, hit ) +{ + if(hit) + { + displayObject._touchDown = true; + this.dispatchEvent( displayObject, 'touchstart', this.eventData ); + } +}; + + +/** + * Is called when a touch ends on the renderer element + * + * @param event {Event} The DOM event of a touch ending on the renderer view + * @private + */ +InteractionManager.prototype.onTouchEnd = function (event) +{ + if (this.autoPreventDefault) + { + event.preventDefault(); + } + + var changedTouches = event.changedTouches; + var cLength = changedTouches.length; + + for (var i=0; i < cLength; i++) + { + var touchEvent = changedTouches[i]; + + var touchData = this.getTouchData( touchEvent ); + + touchData.originalEvent = event; + + //TODO this should be passed along.. no set + this.eventData.data = touchData; + this.eventData.stopped = false; + + + this.processInteractive( touchData.global, this.renderer._lastObjectRendered, this.processTouchEnd, true ); + + this.emit('touchend', this.eventData); + + this.returnTouchData( touchData ); + } +}; + +/** + * Processes the result of the end of a touch and dispatches the event if need be + * + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} The display object that was tested + * @param hit {boolean} the result of the hit test on the display object + * @private + */ +InteractionManager.prototype.processTouchEnd = function ( displayObject, hit ) +{ + if(hit) + { + this.dispatchEvent( displayObject, 'touchend', this.eventData ); + + if( displayObject._touchDown ) + { + displayObject._touchDown = false; + this.dispatchEvent( displayObject, 'tap', this.eventData ); + } + } + else + { + if( displayObject._touchDown ) + { + displayObject._touchDown = false; + this.dispatchEvent( displayObject, 'touchendoutside', this.eventData ); + } + } +}; + +/** + * Is called when a touch is moved across the renderer element + * + * @param event {Event} The DOM event of a touch moving across the renderer view + * @private + */ +InteractionManager.prototype.onTouchMove = function (event) +{ + if (this.autoPreventDefault) + { + event.preventDefault(); + } + + var changedTouches = event.changedTouches; + var cLength = changedTouches.length; + + for (var i=0; i < cLength; i++) + { + var touchEvent = changedTouches[i]; + + var touchData = this.getTouchData( touchEvent ); + + touchData.originalEvent = event; + + this.eventData.data = touchData; + this.eventData.stopped = false; + + this.processInteractive( touchData.global, this.renderer._lastObjectRendered, this.processTouchMove, this.moveWhenInside ); + + this.emit('touchmove', this.eventData); + + this.returnTouchData( touchData ); + } +}; + +/** + * Processes the result of a touch move check and dispatches the event if need be + * + * @param displayObject {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} The display object that was tested + * @param hit {boolean} the result of the hit test on the display object + * @private + */ +InteractionManager.prototype.processTouchMove = function ( displayObject, hit ) +{ + if(!this.moveWhenInside || hit) + { + this.dispatchEvent( displayObject, 'touchmove', this.eventData); + } +}; + +/** + * Grabs an interaction data object from the internal pool + * + * @param touchEvent {object} The touch event we need to pair with an interactionData object + * + * @private + */ +InteractionManager.prototype.getTouchData = function (touchEvent) +{ + var touchData = this.interactiveDataPool.pop(); + + if(!touchData) + { + touchData = new InteractionData(); + } + + touchData.identifier = touchEvent.identifier; + this.mapPositionToPoint( touchData.global, touchEvent.clientX, touchEvent.clientY ); + + if(navigator.isCocoonJS) + { + touchData.global.x = touchData.global.x / this.resolution; + touchData.global.y = touchData.global.y / this.resolution; + } + + touchEvent.globalX = touchData.global.x; + touchEvent.globalY = touchData.global.y; + + return touchData; +}; + +/** + * Returns an interaction data object to the internal pool + * + * @param touchData {PIXI.interaction.InteractionData} The touch data object we want to return to the pool + * + * @private + */ +InteractionManager.prototype.returnTouchData = function ( touchData ) +{ + this.interactiveDataPool.push( touchData ); +}; + +/** + * Destroys the interaction manager + * + */ +InteractionManager.prototype.destroy = function () { + this.removeEvents(); + + this.removeAllListeners(); + + this.renderer = null; + + this.mouse = null; + + this.eventData = null; + + this.interactiveDataPool = null; + + this.interactionDOMElement = null; + + this.onMouseUp = null; + this.processMouseUp = null; + + + this.onMouseDown = null; + this.processMouseDown = null; + + this.onMouseMove = null; + this.processMouseMove = null; + + this.onMouseOut = null; + this.processMouseOverOut = null; + + this.onMouseOver = null; + + this.onTouchStart = null; + this.processTouchStart = null; + + this.onTouchEnd = null; + this.processTouchEnd = null; + + this.onTouchMove = null; + this.processTouchMove = null; + + this._tempPoint = null; +}; + +core.WebGLRenderer.registerPlugin('interaction', InteractionManager); +core.CanvasRenderer.registerPlugin('interaction', InteractionManager); + +},{"../core":62,"./InteractionData":143,"./interactiveTarget":146,"eventemitter3":3}],145:[function(require,module,exports){ +/** + * @file Main export of the PIXI interactions library + * @author Mat Groves + * @copyright 2013-2015 GoodBoyDigital + * @license {@link https://github.com/pixijs/pixi.js/blob/master/LICENSE|MIT License} + */ + +/** + * @namespace PIXI.interaction + */ +module.exports = { + InteractionData: require('./InteractionData'), + InteractionManager: require('./InteractionManager'), + interactiveTarget: require('./interactiveTarget') +}; + +},{"./InteractionData":143,"./InteractionManager":144,"./interactiveTarget":146}],146:[function(require,module,exports){ +/** + * Default property values of interactive objects + * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties + * + * @mixin + * @memberof PIXI.interaction + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.interaction.interactiveTarget + * ); + */ +var interactiveTarget = { + /** + * Determines if the displayObject be clicked/touched + * + * @inner {boolean} + */ + interactive: false, + + /** + * Determines if the children to the displayObject can be clicked/touched + * Setting this to false allows pixi to bypass a recursive hitTest function + * + * @inner {boolean} + */ + interactiveChildren: true, + + /** + * Interaction shape. Children will be hit first, then this shape will be checked. + * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. + * + * @inner {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle} + */ + hitArea: null, + + /** + * If enabled, the mouse cursor will change when hovered over the displayObject if it is interactive + * + * @inner {boolean} + */ + buttonMode: false, + + /** + * If buttonMode is enabled, this defines what CSS cursor property is used when the mouse cursor is hovered over the displayObject + * https://developer.mozilla.org/en/docs/Web/CSS/cursor + * + * @inner {string} + */ + defaultCursor: 'pointer', + + // some internal checks.. + /** + * Internal check to detect if the mouse cursor is hovered over the displayObject + * + * @inner {boolean} + * @private + */ + _over: false, + + /** + * Internal check to detect if the left mouse button is pressed on the displayObject + * + * @inner {boolean} + * @private + */ + _isLeftDown: false, + + /** + * Internal check to detect if the right mouse button is pressed on the displayObject + * + * @inner {boolean} + * @private + */ + _isRightDown: false, + + /** + * Internal check to detect if a user has touched the displayObject + * + * @inner {boolean} + * @private + */ + _touchDown: false + }; + +module.exports = interactiveTarget; + +},{}],147:[function(require,module,exports){ +var Resource = require('resource-loader').Resource, + core = require('../core'), + extras = require('../extras'), + path = require('path'); + + +function parse(resource, texture) { + var data = {}; + var info = resource.data.getElementsByTagName('info')[0]; + var common = resource.data.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10); + data.chars = {}; + + //parse letters + var letters = resource.data.getElementsByTagName('char'); + + for (var i = 0; i < letters.length; i++) + { + var charCode = parseInt(letters[i].getAttribute('id'), 10); + + var textureRect = new core.Rectangle( + parseInt(letters[i].getAttribute('x'), 10) + texture.frame.x, + parseInt(letters[i].getAttribute('y'), 10) + texture.frame.y, + parseInt(letters[i].getAttribute('width'), 10), + parseInt(letters[i].getAttribute('height'), 10) + ); + + data.chars[charCode] = { + xOffset: parseInt(letters[i].getAttribute('xoffset'), 10), + yOffset: parseInt(letters[i].getAttribute('yoffset'), 10), + xAdvance: parseInt(letters[i].getAttribute('xadvance'), 10), + kerning: {}, + texture: new core.Texture(texture.baseTexture, textureRect) + + }; + } + + //parse kernings + var kernings = resource.data.getElementsByTagName('kerning'); + for (i = 0; i < kernings.length; i++) + { + var first = parseInt(kernings[i].getAttribute('first'), 10); + var second = parseInt(kernings[i].getAttribute('second'), 10); + var amount = parseInt(kernings[i].getAttribute('amount'), 10); + + if(data.chars[second]) + { + data.chars[second].kerning[first] = amount; + } + } + + resource.bitmapFont = data; + + // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 + // but it's very likely to change + extras.BitmapText.fonts[data.font] = data; +} + + +module.exports = function () +{ + return function (resource, next) + { + // skip if no data or not xml data + if (!resource.data || !resource.isXml) + { + return next(); + } + + // skip if not bitmap font data, using some silly duck-typing + if ( + resource.data.getElementsByTagName('page').length === 0 || + resource.data.getElementsByTagName('info').length === 0 || + resource.data.getElementsByTagName('info')[0].getAttribute('face') === null + ) + { + return next(); + } + + var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; + + if (resource.isDataUrl) { + if (xmlUrl === '.') { + xmlUrl = ''; + } + + if (this.baseUrl && xmlUrl) { + // if baseurl has a trailing slash then add one to xmlUrl so the replace works below + if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { + xmlUrl += '/'; + } + + // remove baseUrl from xmlUrl + xmlUrl = xmlUrl.replace(this.baseUrl, ''); + } + } + + // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { + xmlUrl += '/'; + } + + var textureUrl = xmlUrl + resource.data.getElementsByTagName('page')[0].getAttribute('file'); + if (core.utils.TextureCache[textureUrl]) { + //reuse existing texture + parse(resource, core.utils.TextureCache[textureUrl]); + next(); + } + else { + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata + }; + // load the texture for the font + this.add(resource.name + '_image', textureUrl, loadOptions, function (res) { + parse(resource, res.texture); + next(); + }); + } + }; +}; + +},{"../core":62,"../extras":129,"path":22,"resource-loader":36}],148:[function(require,module,exports){ +/** + * @file Main export of the PIXI loaders library + * @author Mat Groves + * @copyright 2013-2015 GoodBoyDigital + * @license {@link https://github.com/pixijs/pixi.js/blob/master/LICENSE|MIT License} + */ + +/** + * @namespace PIXI.loaders + */ +module.exports = { + Loader: require('./loader'), + + // parsers + bitmapFontParser: require('./bitmapFontParser'), + spritesheetParser: require('./spritesheetParser'), + textureParser: require('./textureParser'), + Resource: require('resource-loader').Resource +}; + +},{"./bitmapFontParser":147,"./loader":149,"./spritesheetParser":150,"./textureParser":151,"resource-loader":36}],149:[function(require,module,exports){ +var ResourceLoader = require('resource-loader'), + textureParser = require('./textureParser'), + spritesheetParser = require('./spritesheetParser'), + bitmapFontParser = require('./bitmapFontParser'); + +/** + * + * The new loader, extends Resource Loader by Chad Engler : https://github.com/englercj/resource-loader + * + * ```js + * var loader = PIXI.loader; // pixi exposes a premade instance for you to use. + * //or + * var loader = new PIXI.loaders.Loader(); // you can also create your own if you want + * + * loader.add('bunny',"data/bunny.png"); + * + * loader.once('complete',onAssetsLoaded); + * + * loader.load(); + * ``` + * + * @class + * @extends module:resource-loader.ResourceLoader + * @memberof PIXI.loaders + * @param [baseUrl=''] {string} The base url for all resources loaded by this loader. + * @param [concurrency=10] {number} The number of resources to load concurrently. + * @see https://github.com/englercj/resource-loader + */ +function Loader(baseUrl, concurrency) +{ + ResourceLoader.call(this, baseUrl, concurrency); + + for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { + this.use(Loader._pixiMiddleware[i]()); + } +} + +Loader.prototype = Object.create(ResourceLoader.prototype); +Loader.prototype.constructor = Loader; + +module.exports = Loader; + +Loader._pixiMiddleware = [ + // parse any blob into more usable objects (e.g. Image) + ResourceLoader.middleware.parsing.blob, + // parse any Image objects into textures + textureParser, + // parse any spritesheet data into multiple textures + spritesheetParser, + // parse any spritesheet data into multiple textures + bitmapFontParser +]; + +Loader.addPixiMiddleware = function (fn) { + Loader._pixiMiddleware.push(fn); +}; + +// Add custom extentions +var Resource = ResourceLoader.Resource; + +Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); + +},{"./bitmapFontParser":147,"./spritesheetParser":150,"./textureParser":151,"resource-loader":36}],150:[function(require,module,exports){ +var Resource = require('resource-loader').Resource, + path = require('path'), + core = require('../core'); + +var BATCH_SIZE = 1000; + +module.exports = function () +{ + return function (resource, next) + { + var resourcePath; + var imageResourceName = resource.name + '_image'; + + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data || !resource.isJson || !resource.data.frames || this.resources[imageResourceName]) + { + return next(); + } + + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata + }; + + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) + { + resourcePath = resource.data.meta.image; + } + else + { + resourcePath = path.dirname(resource.url.replace(this.baseUrl, '')) + '/' + resource.data.meta.image; + } + + // load the image for this sheet + this.add(imageResourceName, resourcePath, loadOptions, function (res) + { + resource.textures = {}; + + var frames = resource.data.frames; + var frameKeys = Object.keys(frames); + var resolution = core.utils.getResolutionOfUrl(resource.url); + var batchIndex = 0; + + function processFrames(initialFrameIndex, maxFrames) + { + var frameIndex = initialFrameIndex; + + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < frameKeys.length) + { + var i = frameKeys[frameIndex]; + var rect = frames[i].frame; + + if (rect) + { + + var frame = null; + var trim = null; + var orig = new core.Rectangle(0, 0, frames[i].sourceSize.w / resolution, frames[i].sourceSize.h / resolution); + + if (frames[i].rotated) { + frame = new core.Rectangle(rect.x / resolution, rect.y / resolution, rect.h / resolution, rect.w / resolution); + } + else { + frame = new core.Rectangle(rect.x / resolution, rect.y / resolution, rect.w / resolution, rect.h / resolution); + } + + // Check to see if the sprite is trimmed + if (frames[i].trimmed) + { + trim = new core.Rectangle( + frames[i].spriteSourceSize.x / resolution, + frames[i].spriteSourceSize.y / resolution, + frames[i].spriteSourceSize.w / resolution, + frames[i].spriteSourceSize.h / resolution + ); + } + + resource.textures[i] = new core.Texture(res.texture.baseTexture, frame, orig, trim, frames[i].rotated ? 2 : 0); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage functions + core.utils.TextureCache[i] = resource.textures[i]; + + } + + frameIndex++; + } + } + + function shouldProcessNextBatch() + { + return batchIndex * BATCH_SIZE < frameKeys.length; + } + + function processNextBatch(done) + { + processFrames(batchIndex * BATCH_SIZE, BATCH_SIZE); + batchIndex++; + setTimeout(done, 0); + } + + function iteration() { + processNextBatch(function() { + if (shouldProcessNextBatch()) { + iteration(); + } else { + next(); + } + }); + } + + if (frameKeys.length <= BATCH_SIZE) + { + processFrames(0, BATCH_SIZE); + next(); + } + else + { + iteration(); + } + }); + }; +}; + +},{"../core":62,"path":22,"resource-loader":36}],151:[function(require,module,exports){ +var core = require('../core'); + +module.exports = function () +{ + return function (resource, next) + { + // create a new texture if the data is an Image object + if (resource.data && resource.isImage) + { + var baseTexture = new core.BaseTexture(resource.data, null, core.utils.getResolutionOfUrl(resource.url)); + baseTexture.imageUrl = resource.url; + resource.texture = new core.Texture(baseTexture); + // lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions + core.utils.BaseTextureCache[resource.url] = baseTexture; + core.utils.TextureCache[resource.url] = resource.texture; + } + + next(); + }; +}; + +},{"../core":62}],152:[function(require,module,exports){ +var core = require('../core'), + glCore = require('pixi-gl-core'), + Shader = require('./webgl/MeshShader'), + tempPoint = new core.Point(), + tempPolygon = new core.Polygon(); + +/** + * Base mesh class + * @class + * @extends PIXI.Container + * @memberof PIXI.mesh + * @param texture {PIXI.Texture} The texture to use + * @param [vertices] {Float32Array} if you want to specify the vertices + * @param [uvs] {Float32Array} if you want to specify the uvs + * @param [indices] {Uint16Array} if you want to specify the indices + * @param [drawMode] {number} the drawMode, can be any of the Mesh.DRAW_MODES consts + */ +function Mesh(texture, vertices, uvs, indices, drawMode) +{ + core.Container.call(this); + + /** + * The texture of the Mesh + * + * @member {PIXI.Texture} + * @private + */ + this._texture = null; + + /** + * The Uvs of the Mesh + * + * @member {Float32Array} + */ + this.uvs = uvs || new Float32Array([0, 0, + 1, 0, + 1, 1, + 0, 1]); + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = vertices || new Float32Array([0, 0, + 100, 0, + 100, 100, + 0, 100]); + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + // TODO auto generate this based on draw mode! + this.indices = indices || new Uint16Array([0, 1, 3, 2]); + + /** + * Whether the Mesh is dirty or not + * + * @member {number} + */ + this.dirty = 0; + this.indexDirty = 0; + + /** + * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove any blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other. + * + * @member {number} + */ + this.canvasPadding = 0; + + /** + * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts + * + * @member {number} + * @see PIXI.mesh.Mesh.DRAW_MODES + */ + this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH; + + // run texture setter; + this.texture = texture; + + /** + * The default shader that is used if a mesh doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + this.shader = null; + + + /** + * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any tint effect. + * + * @member {number} + * @memberof PIXI.mesh.Mesh# + */ + this.tintRgb = new Float32Array([1, 1, 1]); + + this._glDatas = []; +} + +// constructor +Mesh.prototype = Object.create(core.Container.prototype); +Mesh.prototype.constructor = Mesh; +module.exports = Mesh; + +Object.defineProperties(Mesh.prototype, { + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + * @memberof PIXI.mesh.Mesh# + */ + texture: { + get: function () + { + return this._texture; + }, + set: function (value) + { + if (this._texture === value) + { + return; + } + + this._texture = value; + + if (value) + { + // wait for the texture to load + if (value.baseTexture.hasLoaded) + { + this._onTextureUpdate(); + } + else + { + value.once('update', this._onTextureUpdate, this); + } + } + } + }, + /** + * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @memberof PIXI.mesh.Mesh# + * @default 0xFFFFFF + */ + tint: { + get: function() { + return core.utils.rgb2hex(this.tintRgb); + }, + set: function(value) { + this.tintRgb = core.utils.hex2rgb(value, this.tintRgb); + } + } +}); + +/** + * Renders the object using the WebGL renderer + * + * @param renderer {PIXI.WebGLRenderer} a reference to the WebGL renderer + * @private + */ +Mesh.prototype._renderWebGL = function (renderer) +{ + // get rid of any thing that may be batching. + renderer.flush(); + + // renderer.plugins.mesh.render(this); + var gl = renderer.gl; + var glData = this._glDatas[renderer.CONTEXT_UID]; + + if(!glData) + { + glData = { + shader:new Shader(gl), + vertexBuffer:glCore.GLBuffer.createVertexBuffer(gl, this.vertices, gl.STREAM_DRAW), + uvBuffer:glCore.GLBuffer.createVertexBuffer(gl, this.uvs, gl.STREAM_DRAW), + indexBuffer:glCore.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW), + // build the vao object that will render.. + vao:new glCore.VertexArrayObject(gl), + dirty:this.dirty, + indexDirty:this.indexDirty + }; + + // build the vao object that will render.. + glData.vao = new glCore.VertexArrayObject(gl) + .addIndex(glData.indexBuffer) + .addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0) + .addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); + + this._glDatas[renderer.CONTEXT_UID] = glData; + + + } + + if(this.dirty !== glData.dirty) + { + glData.dirty = this.dirty; + glData.uvBuffer.upload(); + + } + + if(this.indexDirty !== glData.indexDirty) + { + glData.indexDirty = this.indexDirty; + glData.indexBuffer.upload(); + } + + glData.vertexBuffer.upload(); + + renderer.bindShader(glData.shader); + renderer.bindTexture(this._texture, 0); + renderer.state.setBlendMode(this.blendMode); + + glData.shader.uniforms.translationMatrix = this.worldTransform.toArray(true); + glData.shader.uniforms.alpha = this.worldAlpha; + glData.shader.uniforms.tint = this.tintRgb; + + var drawMode = this.drawMode === Mesh.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + glData.vao.bind() + .draw(drawMode, this.indices.length) + .unbind(); +}; + +/** + * Renders the object using the Canvas renderer + * + * @param renderer {PIXI.CanvasRenderer} + * @private + */ +Mesh.prototype._renderCanvas = function (renderer) +{ + var context = renderer.context; + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) + { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, (transform.tx * res) | 0, (transform.ty * res) | 0); + } + else + { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + if (this.drawMode === Mesh.DRAW_MODES.TRIANGLE_MESH) + { + this._renderCanvasTriangleMesh(context); + } + else + { + this._renderCanvasTriangles(context); + } +}; + +/** + * Draws the object in Triangle Mesh mode using canvas + * + * @param context {CanvasRenderingContext2D} the current drawing context + * @private + */ +Mesh.prototype._renderCanvasTriangleMesh = function (context) +{ + // draw triangles!! + var vertices = this.vertices; + var uvs = this.uvs; + + var length = vertices.length / 2; + // this.count++; + + for (var i = 0; i < length - 2; i++) + { + // draw some triangles! + var index = i * 2; + this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4)); + } +}; + +/** + * Draws the object in triangle mode using canvas + * + * @param context {CanvasRenderingContext2D} the current drawing context + * @private + */ +Mesh.prototype._renderCanvasTriangles = function (context) +{ + // draw triangles!! + var vertices = this.vertices; + var uvs = this.uvs; + var indices = this.indices; + + var length = indices.length; + // this.count++; + + for (var i = 0; i < length; i += 3) + { + // draw some triangles! + var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2; + this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2); + } +}; + +/** + * Draws one of the triangles that form this Mesh + * + * @param context {CanvasRenderingContext2D} the current drawing context + * @param vertices {Float32Array} a reference to the vertices of the Mesh + * @param uvs {Float32Array} a reference to the uvs of the Mesh + * @param index0 {number} the index of the first vertex + * @param index1 {number} the index of the second vertex + * @param index2 {number} the index of the third vertex + * @private + */ +Mesh.prototype._renderCanvasDrawTriangle = function (context, vertices, uvs, index0, index1, index2) +{ + var base = this._texture.baseTexture; + var textureSource = base.source; + var textureWidth = base.width; + var textureHeight = base.height; + + var x0 = vertices[index0], x1 = vertices[index1], x2 = vertices[index2]; + var y0 = vertices[index0 + 1], y1 = vertices[index1 + 1], y2 = vertices[index2 + 1]; + + var u0 = uvs[index0] * base.width, u1 = uvs[index1] * base.width, u2 = uvs[index2] * base.width; + var v0 = uvs[index0 + 1] * base.height, v1 = uvs[index1 + 1] * base.height, v2 = uvs[index2 + 1] * base.height; + + if (this.canvasPadding > 0) + { + var paddingX = this.canvasPadding / this.worldTransform.a; + var paddingY = this.canvasPadding / this.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt(normX * normX + normY * normY); + x0 = centerX + (normX / dist) * (dist + paddingX); + y0 = centerY + (normY / dist) * (dist + paddingY); + + // + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x1 = centerX + (normX / dist) * (dist + paddingX); + y1 = centerY + (normY / dist) * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x2 = centerX + (normX / dist) * (dist + paddingX); + y2 = centerY + (normY / dist) * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = (u0 * v1) + (v0 * u2) + (u1 * v2) - (v1 * u2) - (v0 * u1) - (u0 * v2); + var deltaA = (x0 * v1) + (v0 * x2) + (x1 * v2) - (v1 * x2) - (v0 * x1) - (x0 * v2); + var deltaB = (u0 * x1) + (x0 * u2) + (u1 * x2) - (x1 * u2) - (x0 * u1) - (u0 * x2); + var deltaC = (u0 * v1 * x2) + (v0 * x1 * u2) + (x0 * u1 * v2) - (x0 * v1 * u2) - (v0 * u1 * x2) - (u0 * x1 * v2); + var deltaD = (y0 * v1) + (v0 * y2) + (y1 * v2) - (v1 * y2) - (v0 * y1) - (y0 * v2); + var deltaE = (u0 * y1) + (y0 * u2) + (u1 * y2) - (y1 * u2) - (y0 * u1) - (u0 * y2); + var deltaF = (u0 * v1 * y2) + (v0 * y1 * u2) + (y0 * u1 * v2) - (y0 * v1 * u2) - (v0 * u1 * y2) - (u0 * y1 * v2); + + context.transform(deltaA / delta, deltaD / delta, + deltaB / delta, deltaE / delta, + deltaC / delta, deltaF / delta); + + context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + context.restore(); +}; + + + +/** + * Renders a flat Mesh + * + * @param Mesh {PIXI.mesh.Mesh} The Mesh to render + * @private + */ +Mesh.prototype.renderMeshFlat = function (Mesh) +{ + var context = this.context; + var vertices = Mesh.vertices; + + var length = vertices.length/2; + // this.count++; + + context.beginPath(); + for (var i=1; i < length-2; i++) + { + // draw some triangles! + var index = i*2; + + var x0 = vertices[index], x1 = vertices[index+2], x2 = vertices[index+4]; + var y0 = vertices[index+1], y1 = vertices[index+3], y2 = vertices[index+5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); +}; + +/** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ +Mesh.prototype._onTextureUpdate = function () +{ + +}; + +/** + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + * @param [matrix=this.worldTransform] {PIXI.Matrix} the transformation matrix of the sprite + * @return {PIXI.Rectangle} the framing rectangle + */ +Mesh.prototype._calculateBounds = function () +{ + //TODO - we can cache local bounds and use them if they are dirty (like graphics) + this._bounds.addVertices(this.transform, this.vertices, 0, this.vertices.length); +}; + +/** + * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH + * + * @param point {PIXI.Point} the point to test + * @return {boolean} the result of the test + */ +Mesh.prototype.containsPoint = function( point ) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + this.worldTransform.applyInverse(point, tempPoint); + + var vertices = this.vertices; + var points = tempPolygon.points; + + var indices = this.indices; + var len = this.indices.length; + var step = this.drawMode === Mesh.DRAW_MODES.TRIANGLES ? 3 : 1; + for (var i=0;i+2 + * A B + * +---+----------------------+---+ + * C | 1 | 2 | 3 | + * +---+----------------------+---+ + * | | | | + * | 4 | 5 | 6 | + * | | | | + * +---+----------------------+---+ + * D | 7 | 8 | 9 | + * +---+----------------------+---+ + + * When changing this objects width and/or height: + * areas 1 3 7 and 9 will remain unscaled. + * areas 2 and 8 will be stretched horizontally + * areas 4 and 6 will be stretched vertically + * area 5 will be stretched both horizontally and vertically + * + * + * @class + * @extends PIXI.mesh.Plane + * @memberof PIXI.mesh + * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. + * @param {int} [leftWidth=10] size of the left vertical bar (A) + * @param {int} [topHeight=10] size of the top horizontal bar (C) + * @param {int} [rightWidth=10] size of the right vertical bar (B) + * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) + * + */ +function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) +{ + Plane.call(this, texture, 4, 4); + + var uvs = this.uvs; + // right and bottom uv's are always 1 + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + + this._origWidth = texture.width; + this._origHeight = texture.height; + this._uvw = 1 / this._origWidth; + this._uvh = 1 / this._origHeight; + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + this.width = texture.width; + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + this.height = texture.height; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = this._uvw * leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - this._uvw * rightWidth; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = this._uvh * topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - this._uvh * bottomHeight; + + /** + * The width of the left column (a) + * + * @member {number} + */ + this.leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; + /** + * The width of the right column (b) + * + * @member {number} + */ + this.rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; + /** + * The height of the top row (c) + * + * @member {number} + */ + this.topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; + /** + * The height of the bottom row (d) + * + * @member {number} + */ + this.bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; +} + + +// constructor +NineSlicePlane.prototype = Object.create( Plane.prototype ); +NineSlicePlane.prototype.constructor = NineSlicePlane; +module.exports = NineSlicePlane; + +Object.defineProperties(NineSlicePlane.prototype, { + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + width: { + get: function () + { + return this._width; + }, + set: function (value) + { + this._width = value; + this.updateVerticalVertices(); + } + }, + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + height: { + get: function () + { + return this._height; + }, + set: function (value) + { + this._height = value; + this.updateHorizontalVertices(); + } + }, + + /** + * The width of the left column + * + * @member {number} + */ + leftWidth: { + get: function() + { + return this._leftWidth; + }, + set: function (value) + { + this._leftWidth = value; + var uvs = this.uvs; + var vertices = this.vertices; + uvs[2] = uvs[10] = uvs[18] = uvs[26] = this._uvw * value; + vertices[2] = vertices[10] = vertices[18] = vertices[26] = value; + this.dirty=true; + } + }, + /** + * The width of the right column + * + * @member {number} + */ + rightWidth: { + get: function() + { + return this._rightWidth; + }, + set: function (value) + { + this._rightWidth = value; + var uvs = this.uvs; + var vertices = this.vertices; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - this._uvw * value; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - value; + this.dirty=true; + } + }, + /** + * The height of the top row + * + * @member {number} + */ + topHeight: { + get: function() + { + return this._topHeight; + }, + set: function (value) + { + this._topHeight = value; + var uvs = this.uvs; + var vertices = this.vertices; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = this._uvh * value; + vertices[9] = vertices[11] = vertices[13] = vertices[15] = value; + this.dirty=true; + } + }, + /** + * The height of the bottom row + * + * @member {number} + */ + bottomHeight: { + get: function() + { + return this._bottomHeight; + }, + set: function (value) + { + this._bottomHeight = value; + var uvs = this.uvs; + var vertices = this.vertices; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - this._uvh * value; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - value; + this.dirty=true; + } + } +}); + +NineSlicePlane.prototype.updateHorizontalVertices = function() { + var vertices = this.vertices; + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight; + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; +}; + +NineSlicePlane.prototype.updateVerticalVertices = function() { + var vertices = this.vertices; + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth; + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width ; +}; + +/** + * Renders the object using the Canvas renderer + * + * @param renderer {PIXI.CanvasRenderer} + * @private + */ +NineSlicePlane.prototype._renderCanvas= function (renderer) +{ + var context = renderer.context; + context.globalAlpha = this.worldAlpha; + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) + { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, (transform.tx * res) | 0, (transform.ty * res) | 0); + } + else + { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + var base = this._texture.baseTexture; + var textureSource = base.source; + var w = base.width; + var h = base.height; + + this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11); + this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13); + this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15); + this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19); + this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21); + this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23); + this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27); + this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29); + this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31); +}; + +/** + * Renders one segment of the plane. + * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure + * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used. + * + * @param context + * @param textureSource + * @param w width of the texture + * @param h height of the texture + * @param x1 + * @param y1 + * @param x2 + * @param y2 + * @private + */ +NineSlicePlane.prototype.drawSegment= function (context, textureSource, w, h, x1, y1, x2, y2) +{ + // otherwise you get weird results when using slices of that are 0 wide or high. + var uvs = this.uvs; + var vertices = this.vertices; + + var sw = (uvs[x2]-uvs[x1]) * w; + var sh = (uvs[y2]-uvs[y1]) * h; + var dw = vertices[x2] - vertices[x1]; + var dh = vertices[y2] - vertices[y1]; + + // make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn. + if (sw<1) { + sw=1; + } + if (sh<1) { + sh=1; + } + // make sure destination is at least 1 pixel wide and high, otherwise you get lines when rendering close to original size. + if (dw<1) { + dw=1; + } + if (dh<1) { + dh=1; + } + context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh); +}; + +},{"./Plane":154}],154:[function(require,module,exports){ +var Mesh = require('./Mesh'); + +/** + * The Plane allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (var i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * var Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * @param {PIXI.Texture} texture - The texture to use on the Plane. + * @param {number} verticesX - The number of vertices in the x-axis + * @param {number} verticesY - The number of vertices in the y-axis + * + */ +function Plane(texture, verticesX, verticesY) +{ + Mesh.call(this, texture); + + /** + * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + this._ready = true; + + this.verticesX = verticesX || 10; + this.verticesY = verticesY || 10; + + this.drawMode = Mesh.DRAW_MODES.TRIANGLES; + this.refresh(); + +} + + +// constructor +Plane.prototype = Object.create( Mesh.prototype ); +Plane.prototype.constructor = Plane; +module.exports = Plane; + +/** + * Refreshes + * + */ +Plane.prototype.refresh = function() +{ + var total = this.verticesX * this.verticesY; + var verts = []; + var colors = []; + var uvs = []; + var indices = []; + var texture = this.texture; + + var segmentsX = this.verticesX - 1; + var segmentsY = this.verticesY - 1; + var i = 0; + + var sizeX = texture.width / segmentsX; + var sizeY = texture.height / segmentsY; + + for (i = 0; i < total; i++) { + + var x = (i % this.verticesX); + var y = ( (i / this.verticesX ) | 0 ); + + + verts.push((x * sizeX), + (y * sizeY)); + + // this works for rectangular textures. + uvs.push(texture._uvs.x0 + (texture._uvs.x1 - texture._uvs.x0) * (x / (this.verticesX-1)), texture._uvs.y0 + (texture._uvs.y3-texture._uvs.y0) * (y/ (this.verticesY-1))); + } + + // cons + + var totalSub = segmentsX * segmentsY; + + for (i = 0; i < totalSub; i++) { + + var xpos = i % segmentsX; + var ypos = (i / segmentsX ) | 0; + + + var value = (ypos * this.verticesX) + xpos; + var value2 = (ypos * this.verticesX) + xpos + 1; + var value3 = ((ypos+1) * this.verticesX) + xpos; + var value4 = ((ypos+1) * this.verticesX) + xpos + 1; + + indices.push(value, value2, value3); + indices.push(value2, value4, value3); + } + + + //console.log(indices) + this.vertices = new Float32Array(verts); + this.uvs = new Float32Array(uvs); + this.colors = new Float32Array(colors); + this.indices = new Uint16Array(indices); + + this.indexDirty = true; +}; + +/** + * Clear texture UVs when new texture is set + * + * @private + */ +Plane.prototype._onTextureUpdate = function () +{ + Mesh.prototype._onTextureUpdate.call(this); + + // wait for the Plane ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } +}; + +},{"./Mesh":152}],155:[function(require,module,exports){ +var Mesh = require('./Mesh'); +var core = require('../core'); + +/** + * The rope allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (var i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * var rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * @param {PIXI.Texture} texture - The texture to use on the rope. + * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. + * + */ +function Rope(texture, points) +{ + Mesh.call(this, texture); + + /* + * @member {PIXI.Point[]} An array of points that determine the rope + */ + this.points = points; + + /* + * @member {Float32Array} An array of vertices used to construct this rope. + */ + this.vertices = new Float32Array(points.length * 4); + + /* + * @member {Float32Array} The WebGL Uvs of the rope. + */ + this.uvs = new Float32Array(points.length * 4); + + /* + * @member {Float32Array} An array containing the color components + */ + this.colors = new Float32Array(points.length * 2); + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + this.indices = new Uint16Array(points.length * 2); + + /** + * Tracker for if the rope is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + this._ready = true; + + this.refresh(); +} + + +// constructor +Rope.prototype = Object.create(Mesh.prototype); +Rope.prototype.constructor = Rope; +module.exports = Rope; + +/** + * Refreshes + * + */ +Rope.prototype.refresh = function () +{ + var points = this.points; + + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1 || !this._texture._uvs) + { + return; + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + var textureUvs = this._texture._uvs; + var offset = new core.Point(textureUvs.x0, textureUvs.y0); + var factor = new core.Point(textureUvs.x2 - textureUvs.x0, textureUvs.y2 - textureUvs.y0); + + uvs[0] = 0 + offset.x; + uvs[1] = 0 + offset.y; + uvs[2] = 0 + offset.x; + uvs[3] = 1 * factor.y + offset.y; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length, + point, index, amount; + + for (var i = 1; i < total; i++) + { + point = points[i]; + index = i * 4; + // time to do some smart drawing! + amount = i / (total-1); + + uvs[index] = amount * factor.x + offset.x; + uvs[index+1] = 0 + offset.y; + + uvs[index+2] = amount * factor.x + offset.x; + uvs[index+3] = 1 * factor.y + offset.y; + + index = i * 2; + colors[index] = 1; + colors[index+1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + + this.dirty = true; + this.indexDirty = true; +}; + +/** + * Clear texture UVs when new texture is set + * + * @private + */ +Rope.prototype._onTextureUpdate = function () +{ + + Mesh.prototype._onTextureUpdate.call(this); + + // wait for the Rope ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } +}; + +/** + * Updates the object transform for rendering + * + * @private + */ +Rope.prototype.updateTransform = function () +{ + var points = this.points; + + if (points.length < 1) + { + return; + } + + var lastPoint = points[0]; + var nextPoint; + var perpX = 0; + var perpY = 0; + + // this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length, + point, index, ratio, perpLength, num; + + for (var i = 0; i < total; i++) + { + point = points[i]; + index = i * 4; + + if (i < points.length-1) + { + nextPoint = points[i+1]; + } + else + { + nextPoint = point; + } + + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + + ratio = (1 - (i / (total-1))) * 10; + + if (ratio > 1) + { + ratio = 1; + } + + perpLength = Math.sqrt(perpX * perpX + perpY * perpY); + num = this._texture.height / 2; //(20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; + perpX /= perpLength; + perpY /= perpLength; + + perpX *= num; + perpY *= num; + + vertices[index] = point.x + perpX; + vertices[index+1] = point.y + perpY; + vertices[index+2] = point.x - perpX; + vertices[index+3] = point.y - perpY; + + lastPoint = point; + } + + this.containerUpdateTransform(); +}; + +},{"../core":62,"./Mesh":152}],156:[function(require,module,exports){ +/** + * @file Main export of the PIXI extras library + * @author Mat Groves + * @copyright 2013-2015 GoodBoyDigital + * @license {@link https://github.com/pixijs/pixi.js/blob/master/LICENSE|MIT License} + */ + +/** + * @namespace PIXI.mesh + */ +module.exports = { + Mesh: require('./Mesh'), + Plane: require('./Plane'), + NineSlicePlane: require('./NineSlicePlane'), + Rope: require('./Rope'), + MeshShader: require('./webgl/MeshShader') +}; + +},{"./Mesh":152,"./NineSlicePlane":153,"./Plane":154,"./Rope":155,"./webgl/MeshShader":157}],157:[function(require,module,exports){ +var Shader = require('../../core/Shader'); + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI.mesh + * @param gl {PIXI.Shader} TODO: Find a good explanation for this. + */ +function MeshShader(gl) +{ + Shader.call(this, + gl, + // vertex shader + [ + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', + + 'varying vec2 vTextureCoord;', + + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vTextureCoord = aTextureCoord;', + '}' + ].join('\n'), + [ + 'varying vec2 vTextureCoord;', + 'uniform float alpha;', + 'uniform vec3 tint;', + + 'uniform sampler2D uSampler;', + + 'void main(void){', + ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vec4(tint * alpha, alpha);', + // ' gl_FragColor = vec4(1.0);', + '}' + ].join('\n') + ); +} + +MeshShader.prototype = Object.create(Shader.prototype); +MeshShader.prototype.constructor = MeshShader; +module.exports = MeshShader; + + +},{"../../core/Shader":42}],158:[function(require,module,exports){ +var core = require('../core'); + +/** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that advanced + * functionality will not work. ParticleContainer implements only the basic object transform (position, scale, rotation). + * Any other functionality like tinting, masking, etc will not work on sprites in this batch. + * + * It's extremely easy to use : + * + * ```js + * var container = new ParticleContainer(); + * + * for (var i = 0; i < 100; ++i) + * { + * var sprite = new PIXI.Sprite.fromImage("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be renderer at the speed of light. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.particles + * @param [maxSize=15000] {number} The maximum number of particles that can be renderer by the container. + * @param [properties] {object} The properties of children that should be uploaded to the gpu and applied. + * @param [properties.scale=false] {boolean} When true, scale be uploaded and applied. + * @param [properties.position=true] {boolean} When true, position be uploaded and applied. + * @param [properties.rotation=false] {boolean} When true, rotation be uploaded and applied. + * @param [properties.uvs=false] {boolean} When true, uvs be uploaded and applied. + * @param [properties.alpha=false] {boolean} When true, alpha be uploaded and applied. + * @param [batchSize=15000] {number} Number of particles per batch. + */ +function ParticleContainer(maxSize, properties, batchSize) +{ + core.Container.call(this); + + batchSize = batchSize || 15000; //CONST.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + maxSize = maxSize || 15000; + + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var maxBatchSize = 16384; + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + + if (batchSize > maxSize) { + batchSize = maxSize; + } + + /** + * Set properties to be dynamic (true) / static (false) + * + * @member {boolean[]} + * @private + */ + this._properties = [false, true, false, false, false]; + + /** + * @member {number} + * @private + */ + this._maxSize = maxSize; + + /** + * @member {number} + * @private + */ + this._batchSize = batchSize; + + /** + * @member {WebGLBuffer} + * @private + */ + this._glBuffers = []; + + /** + * @member {number} + * @private + */ + this._bufferToUpdate = 0; + + /** + * @member {boolean} + * + */ + this.interactiveChildren = false; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Used for canvas renderering. If true then the elements will be positioned at the nearest pixel. This provides a nice speed boost. + * + * @member {boolean} + * @default true; + */ + this.roundPixels = true; + + this.baseTexture = null; + + this.setProperties(properties); +} + +ParticleContainer.prototype = Object.create(core.Container.prototype); +ParticleContainer.prototype.constructor = ParticleContainer; +module.exports = ParticleContainer; + +/** + * Sets the private properties array to dynamic / static based on the passed properties object + * + * @param properties {object} The properties to be uploaded + */ +ParticleContainer.prototype.setProperties = function(properties) +{ + if ( properties ) { + this._properties[0] = 'scale' in properties ? !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'alpha' in properties ? !!properties.alpha : this._properties[4]; + } +}; + +/** + * Updates the object transform for rendering + * + * @private + */ +ParticleContainer.prototype.updateTransform = function () +{ + + // TODO don't need to! + this.displayObjectUpdateTransform(); + // PIXI.Container.prototype.updateTransform.call( this ); +}; + +/** + * Renders the container using the WebGL renderer + * + * @param renderer {PIXI.WebGLRenderer} The webgl renderer + * @private + */ +ParticleContainer.prototype.renderWebGL = function (renderer) +{ + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) + { + return; + } + + + if(!this.baseTexture) + { + this.baseTexture = this.children[0]._texture.baseTexture; + if(!this.baseTexture.hasLoaded) + { + this.baseTexture.once('update', function(){ + this.onChildrenChange(0); + }, this); + } + } + + + renderer.setObjectRenderer( renderer.plugins.particle ); + renderer.plugins.particle.render( this ); +}; + +/** + * Set the flag that static data should be updated to true + * + * @private + */ +ParticleContainer.prototype.onChildrenChange = function (smallestChildIndex) +{ + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + if (bufferIndex < this._bufferToUpdate) { + this._bufferToUpdate = bufferIndex; + } +}; + +/** + * Renders the object using the Canvas renderer + * + * @param renderer {PIXI.CanvasRenderer} The canvas renderer + * @private + */ +ParticleContainer.prototype.renderCanvas = function (renderer) +{ + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) + { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var isRotated = true; + + var positionX = 0; + var positionY = 0; + + var finalWidth = 0; + var finalHeight = 0; + + var compositeOperation = renderer.blendModes[this.blendMode]; + if (compositeOperation !== context.globalCompositeOperation) + { + context.globalCompositeOperation = compositeOperation; + } + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + for (var i = 0; i < this.children.length; ++i) + { + var child = this.children[i]; + + if (!child.visible) + { + continue; + } + + var frame = child.texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) + { + // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call + if (isRotated) + { + context.setTransform( + transform.a, + transform.b, + transform.c, + transform.d, + transform.tx * renderer.resolution, + transform.ty * renderer.resolution + ); + + isRotated = false; + } + + positionX = ((child.anchor.x) * (-frame.width * child.scale.x) + child.position.x + 0.5); + positionY = ((child.anchor.y) * (-frame.height * child.scale.y) + child.position.y + 0.5); + + finalWidth = frame.width * child.scale.x; + finalHeight = frame.height * child.scale.y; + + } + else + { + if (!isRotated) + { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + + if (renderer.roundPixels) + { + context.setTransform( + childTransform.a, + childTransform.b, + childTransform.c, + childTransform.d, + (childTransform.tx * renderer.resolution) | 0, + (childTransform.ty * renderer.resolution) | 0 + ); + } + else + { + context.setTransform( + childTransform.a, + childTransform.b, + childTransform.c, + childTransform.d, + childTransform.tx * renderer.resolution, + childTransform.ty * renderer.resolution + ); + } + + positionX = ((child.anchor.x) * (-frame.width) + 0.5); + positionY = ((child.anchor.y) * (-frame.height) + 0.5); + + finalWidth = frame.width; + finalHeight = frame.height; + } + + var resolution = child.texture.baseTexture.resolution; + + context.drawImage( + child.texture.baseTexture.source, + frame.x * resolution, + frame.y * resolution, + frame.width * resolution, + frame.height * resolution, + positionX * resolution, + positionY * resolution, + finalWidth * resolution, + finalHeight * resolution + ); + } +}; + +/** + * Destroys the container + * + */ +ParticleContainer.prototype.destroy = function () { + core.Container.prototype.destroy.apply(this, arguments); + + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + } + + this._properties = null; + this._buffers = null; +}; + +},{"../core":62}],159:[function(require,module,exports){ +/** + * @file Main export of the PIXI extras library + * @author Mat Groves + * @copyright 2013-2015 GoodBoyDigital + * @license {@link https://github.com/pixijs/pixi.js/blob/master/LICENSE|MIT License} + */ + +/** + * @namespace PIXI.particles + */ +module.exports = { + ParticleContainer: require('./ParticleContainer'), + ParticleRenderer: require('./webgl/ParticleRenderer') +}; + +},{"./ParticleContainer":158,"./webgl/ParticleRenderer":161}],160:[function(require,module,exports){ +var glCore = require('pixi-gl-core'), + createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + +/** + * The particle buffer manages the static and dynamic buffers for a particle container. + * + * @class + * @private + * @memberof PIXI + */ +function ParticleBuffer(gl, properties, dynamicPropertyFlags, size) +{ + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * Size of a single vertex. + * + * @member {number} + */ + this.vertSize = 2; + + /** + * Size of a single vertex in bytes. + * + * @member {number} + */ + this.vertByteSize = this.vertSize * 4; + + /** + * The number of particles the buffer can hold + * + * @member {number} + */ + this.size = size; + + /** + * A list of the properties that are dynamic. + * + * @member {object[]} + */ + this.dynamicProperties = []; + + /** + * A list of the properties that are static. + * + * @member {object[]} + */ + this.staticProperties = []; + + for (var i = 0; i < properties.length; i++) + { + var property = properties[i]; + + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = + { + attribute:property.attribute, + size:property.size, + uploadFunction:property.uploadFunction, + offset:property.offset + }; + + if(dynamicPropertyFlags[i]) + { + this.dynamicProperties.push(property); + } + else + { + this.staticProperties.push(property); + } + } + + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + + this.initBuffers(); + +} + +ParticleBuffer.prototype.constructor = ParticleBuffer; +module.exports = ParticleBuffer; + +/** + * Sets up the renderer context and necessary buffers. + * + * @private + */ +ParticleBuffer.prototype.initBuffers = function () +{ + var gl = this.gl; + var i; + var property; + + var dynamicOffset = 0; + + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = createIndicesForQuads(this.size); + this.indexBuffer = glCore.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + + this.dynamicStride = 0; + + for (i = 0; i < this.dynamicProperties.length; i++) + { + property = this.dynamicProperties[i]; + + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + + this.dynamicData = new Float32Array( this.size * this.dynamicStride * 4); + this.dynamicBuffer = glCore.GLBuffer.createVertexBuffer(gl, this.dynamicData, gl.STREAM_DRAW); + + // static // + var staticOffset = 0; + this.staticStride = 0; + + for (i = 0; i < this.staticProperties.length; i++) + { + property = this.staticProperties[i]; + + property.offset = staticOffset; + staticOffset += property.size; + this.staticStride += property.size; + + + } + + this.staticData = new Float32Array( this.size * this.staticStride * 4); + this.staticBuffer = glCore.GLBuffer.createVertexBuffer(gl, this.staticData, gl.STATIC_DRAW); + + + this.vao = new glCore.VertexArrayObject(gl) + .addIndex(this.indexBuffer); + + for (i = 0; i < this.dynamicProperties.length; i++) + { + property = this.dynamicProperties[i]; + this.vao.addAttribute(this.dynamicBuffer, property.attribute, gl.FLOAT, false, this.dynamicStride * 4, property.offset * 4); + } + + for (i = 0; i < this.staticProperties.length; i++) + { + property = this.staticProperties[i]; + this.vao.addAttribute(this.staticBuffer, property.attribute, gl.FLOAT, false, this.staticStride * 4, property.offset * 4); + } +}; + +/** + * Uploads the dynamic properties. + * + */ +ParticleBuffer.prototype.uploadDynamic = function(children, startIndex, amount) +{ + for (var i = 0; i < this.dynamicProperties.length; i++) + { + var property = this.dynamicProperties[i]; + property.uploadFunction(children, startIndex, amount, this.dynamicData, this.dynamicStride, property.offset); + } + + this.dynamicBuffer.upload(); +}; + +/** + * Uploads the static properties. + * + */ +ParticleBuffer.prototype.uploadStatic = function(children, startIndex, amount) +{ + for (var i = 0; i < this.staticProperties.length; i++) + { + var property = this.staticProperties[i]; + property.uploadFunction(children, startIndex, amount, this.staticData, this.staticStride, property.offset); + } + + this.staticBuffer.upload(); +}; + +/** + * Binds the buffers to the GPU + * + */ +ParticleBuffer.prototype.bind = function () +{ + this.vao.bind(); +}; + +/** + * Destroys the ParticleBuffer. + * + */ +ParticleBuffer.prototype.destroy = function () +{ + this.dynamicProperties = null; + this.dynamicData = null; + this.dynamicBuffer.destroy(); + + this.staticProperties = null; + this.staticData = null; + this.staticBuffer.destroy(); +}; + +},{"../../core/utils/createIndicesForQuads":114,"pixi-gl-core":12}],161:[function(require,module,exports){ +var core = require('../../core'), + ParticleShader = require('./ParticleShader'), + ParticleBuffer = require('./ParticleBuffer'); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + +/** + * + * @class + * @private + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} The renderer this sprite batch works for. + */ +function ParticleRenderer(renderer) +{ + core.ObjectRenderer.call(this, renderer); + + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // var numIndices = 98304; + + /** + * The default shader that is used if a sprite doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + this.shader = null; + + this.indexBuffer = null; + + this.properties = null; + + this.tempMatrix = new core.Matrix(); + + this.CONTEXT_UID = 0; +} + +ParticleRenderer.prototype = Object.create(core.ObjectRenderer.prototype); +ParticleRenderer.prototype.constructor = ParticleRenderer; +module.exports = ParticleRenderer; + +core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + +/** + * When there is a WebGL context change + * + * @private + */ +ParticleRenderer.prototype.onContextChange = function () +{ + var gl = this.renderer.gl; + + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + + // setup default shader + this.shader = new ParticleShader(gl); + + this.properties = [ + // verticesData + { + attribute:this.shader.attributes.aVertexPosition, + size:2, + uploadFunction:this.uploadVertices, + offset:0 + }, + // positionData + { + attribute:this.shader.attributes.aPositionCoord, + size:2, + uploadFunction:this.uploadPosition, + offset:0 + }, + // rotationData + { + attribute:this.shader.attributes.aRotation, + size:1, + uploadFunction:this.uploadRotation, + offset:0 + }, + // uvsData + { + attribute:this.shader.attributes.aTextureCoord, + size:2, + uploadFunction:this.uploadUvs, + offset:0 + }, + // alphaData + { + attribute:this.shader.attributes.aColor, + size:1, + uploadFunction:this.uploadAlpha, + offset:0 + } + ]; + +}; + +/** + * Starts a new particle batch. + * + */ +ParticleRenderer.prototype.start = function () +{ + this.renderer.bindShader(this.shader); +}; + + +/** + * Renders the particle container object. + * + * @param container {PIXI.ParticleContainer} The container to render using this ParticleRenderer + */ +ParticleRenderer.prototype.render = function (container) +{ + var children = container.children, + totalChildren = children.length, + maxSize = container._maxSize, + batchSize = container._batchSize; + + if(totalChildren === 0) + { + return; + } + else if(totalChildren > maxSize) + { + totalChildren = maxSize; + } + + var buffers = container._glBuffers[this.renderer.CONTEXT_UID]; + + if(!buffers) + { + buffers = container._glBuffers[this.renderer.CONTEXT_UID] = this.generateBuffers( container ); + } + + // if the uvs have not updated then no point rendering just yet! + this.renderer.setBlendMode(container.blendMode); + + var gl = this.renderer.gl; + + var m = container.worldTransform.copy( this.tempMatrix ); + m.prepend( this.renderer._activeRenderTarget.projectionMatrix ); + this.shader.uniforms.projectionMatrix = m.toArray(true); + this.shader.uniforms.uAlpha = container.worldAlpha; + + + // make sure the texture is bound.. + var baseTexture = children[0]._texture.baseTexture; + + this.renderer.bindTexture(baseTexture); + + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) + { + var amount = ( totalChildren - i); + if(amount > batchSize) + { + amount = batchSize; + } + + var buffer = buffers[j]; + + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + + // we only upload the static content when we have to! + if(container._bufferToUpdate === j) + { + buffer.uploadStatic(children, i, amount); + container._bufferToUpdate = j + 1; + } + + // bind the buffer + buffer.vao.bind() + .draw(gl.TRIANGLES, amount * 6) + .unbind(); + + // now draw those suckas! + // gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0); + // this.renderer.drawCount++; + } +}; + +/** + * Creates one particle buffer for each child in the container we want to render and updates internal properties + * + * @param container {PIXI.ParticleContainer} The container to render using this ParticleRenderer + */ +ParticleRenderer.prototype.generateBuffers = function (container) +{ + var gl = this.renderer.gl, + buffers = [], + size = container._maxSize, + batchSize = container._batchSize, + dynamicPropertyFlags = container._properties, + i; + + for (i = 0; i < size; i += batchSize) + { + buffers.push(new ParticleBuffer(gl, this.properties, dynamicPropertyFlags, batchSize)); + } + + return buffers; +}; + +/** + * Uploads the verticies. + * + * @param children {PIXI.DisplayObject[]} the array of display objects to render + * @param startIndex {number} the index to start from in the children array + * @param amount {number} the amount of children that will have their vertices uploaded + * @param array {number[]} + * @param stride {number} + * @param offset {number} + */ +ParticleRenderer.prototype.uploadVertices = function (children, startIndex, amount, array, stride, offset) +{ + var sprite, + texture, + trim, + orig, + sx, + sy, + w0, w1, h0, h1; + + for (var i = 0; i < amount; i++) { + + sprite = children[startIndex + i]; + texture = sprite._texture; + sx = sprite.scale.x; + sy = sprite.scale.y; + trim = texture.trim; + orig = texture.orig; + + if (trim) + { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra space before transforming the sprite coords.. + w1 = trim.x - sprite.anchor.x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - sprite.anchor.y * orig.height; + h0 = h1 + trim.height; + + } + else + { + w0 = (orig.width ) * (1-sprite.anchor.x); + w1 = (orig.width ) * -sprite.anchor.x; + + h0 = orig.height * (1-sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + + array[offset + stride * 2] = w0 * sx; + array[offset + stride * 2 + 1] = h0 * sy; + + array[offset + stride * 3] = w1 * sx; + array[offset + stride * 3 + 1] = h0 * sy; + + offset += stride * 4; + } + +}; + +/** + * + * @param children {PIXI.DisplayObject[]} the array of display objects to render + * @param startIndex {number} the index to start from in the children array + * @param amount {number} the amount of children that will have their positions uploaded + * @param array {number[]} + * @param stride {number} + * @param offset {number} + */ +ParticleRenderer.prototype.uploadPosition = function (children,startIndex, amount, array, stride, offset) +{ + for (var i = 0; i < amount; i++) + { + var spritePosition = children[startIndex + i].position; + + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + + array[offset + stride * 2] = spritePosition.x; + array[offset + stride * 2 + 1] = spritePosition.y; + + array[offset + stride * 3] = spritePosition.x; + array[offset + stride * 3 + 1] = spritePosition.y; + + offset += stride * 4; + } + +}; + +/** + * + * @param children {PIXI.DisplayObject[]} the array of display objects to render + * @param startIndex {number} the index to start from in the children array + * @param amount {number} the amount of children that will have their rotation uploaded + * @param array {number[]} + * @param stride {number} + * @param offset {number} + */ +ParticleRenderer.prototype.uploadRotation = function (children,startIndex, amount, array, stride, offset) +{ + for (var i = 0; i < amount; i++) + { + var spriteRotation = children[startIndex + i].rotation; + + + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + stride * 2] = spriteRotation; + array[offset + stride * 3] = spriteRotation; + + offset += stride * 4; + } +}; + +/** + * + * @param children {PIXI.DisplayObject[]} the array of display objects to render + * @param startIndex {number} the index to start from in the children array + * @param amount {number} the amount of children that will have their Uvs uploaded + * @param array {number[]} + * @param stride {number} + * @param offset {number} + */ +ParticleRenderer.prototype.uploadUvs = function (children,startIndex, amount, array, stride, offset) +{ + for (var i = 0; i < amount; i++) + { + var textureUvs = children[startIndex + i]._texture._uvs; + + if (textureUvs) + { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + + array[offset + stride * 2] = textureUvs.x2; + array[offset + stride * 2 + 1] = textureUvs.y2; + + array[offset + stride * 3] = textureUvs.x3; + array[offset + stride * 3 + 1] = textureUvs.y3; + + offset += stride * 4; + } + else + { + //TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + + array[offset + stride * 2] = 0; + array[offset + stride * 2 + 1] = 0; + + array[offset + stride * 3] = 0; + array[offset + stride * 3 + 1] = 0; + + offset += stride * 4; + } + } +}; + +/** + * + * @param children {PIXI.DisplayObject[]} the array of display objects to render + * @param startIndex {number} the index to start from in the children array + * @param amount {number} the amount of children that will have their alpha uploaded + * @param array {number[]} + * @param stride {number} + * @param offset {number} + */ +ParticleRenderer.prototype.uploadAlpha = function (children,startIndex, amount, array, stride, offset) +{ + for (var i = 0; i < amount; i++) + { + var spriteAlpha = children[startIndex + i].alpha; + + array[offset] = spriteAlpha; + array[offset + stride] = spriteAlpha; + array[offset + stride * 2] = spriteAlpha; + array[offset + stride * 3] = spriteAlpha; + + offset += stride * 4; + } +}; + + +/** + * Destroys the ParticleRenderer. + * + */ +ParticleRenderer.prototype.destroy = function () +{ + if (this.renderer.gl) { + this.renderer.gl.deleteBuffer(this.indexBuffer); + } + core.ObjectRenderer.prototype.destroy.apply(this, arguments); + + this.shader.destroy(); + + this.indices = null; + this.tempMatrix = null; +}; + +},{"../../core":62,"./ParticleBuffer":160,"./ParticleShader":162}],162:[function(require,module,exports){ +var Shader = require('../../core/Shader'); + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI + * @param gl {PIXI.Shader} The webgl shader manager this shader works for. + */ +function ParticleShader(gl) +{ + Shader.call(this, + gl, + // vertex shader + [ + 'attribute vec2 aVertexPosition;', + 'attribute vec2 aTextureCoord;', + 'attribute float aColor;', + + 'attribute vec2 aPositionCoord;', + 'attribute vec2 aScale;', + 'attribute float aRotation;', + + 'uniform mat3 projectionMatrix;', + + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + + 'void main(void){', + ' vec2 v = aVertexPosition;', + + ' v.x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);', + ' v.y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);', + ' v = v + aPositionCoord;', + + ' gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);', + + ' vTextureCoord = aTextureCoord;', + ' vColor = aColor;', + '}' + ].join('\n'), + // hello + [ + 'varying vec2 vTextureCoord;', + 'varying float vColor;', + + 'uniform sampler2D uSampler;', + 'uniform float uAlpha;', + + 'void main(void){', + ' vec4 color = texture2D(uSampler, vTextureCoord) * vColor * uAlpha;', + ' if (color.a == 0.0) discard;', + ' gl_FragColor = color;', + '}' + ].join('\n') + ); + + // TEMP HACK + +} + +ParticleShader.prototype = Object.create(Shader.prototype); +ParticleShader.prototype.constructor = ParticleShader; + +module.exports = ParticleShader; + +},{"../../core/Shader":42}],163:[function(require,module,exports){ +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + +if (!Math.sign) +{ + Math.sign = function (x) { + x = +x; + if (x === 0 || isNaN(x)) + { + return x; + } + return x > 0 ? 1 : -1; + }; +} + +},{}],164:[function(require,module,exports){ +// References: +// https://github.com/sindresorhus/object-assign +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + +if (!Object.assign) +{ + Object.assign = require('object-assign'); +} + +},{"object-assign":5}],165:[function(require,module,exports){ +require('./Object.assign'); +require('./requestAnimationFrame'); +require('./Math.sign'); + +if(!window.ArrayBuffer){ + window.ArrayBuffer = Array; +} +if(!window.Float32Array) { + window.Float32Array = Array; +} +if(!window.Uint32Array){ + window.Uint32Array = Array; +} +if(!window.Uint16Array){ + window.Uint16Array = Array; +} + +},{"./Math.sign":163,"./Object.assign":164,"./requestAnimationFrame":166}],166:[function(require,module,exports){ +(function (global){ +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + +// Expected to be used with Browserfiy +// Browserify automatically detects the use of `global` and passes the +// correct reference of `global`, `self`, and finally `window` + +// Date.now +if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; +} + +// performance.now +if (!(global.performance && global.performance.now)) { + var startTime = Date.now(); + if (!global.performance) { + global.performance = {}; + } + global.performance.now = function () { + return Date.now() - startTime; + }; +} + +// requestAnimationFrame +var lastTime = Date.now(); +var vendors = ['ms', 'moz', 'webkit', 'o']; + +for(var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { + global.requestAnimationFrame = global[vendors[x] + 'RequestAnimationFrame']; + global.cancelAnimationFrame = global[vendors[x] + 'CancelAnimationFrame'] || + global[vendors[x] + 'CancelRequestAnimationFrame']; +} + +if (!global.requestAnimationFrame) { + global.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + 'is not a function'); + } + + var currentTime = Date.now(), + delay = 16 + lastTime - currentTime; + + if (delay < 0) { + delay = 0; + } + + lastTime = currentTime; + + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} + +if (!global.cancelAnimationFrame) { + global.cancelAnimationFrame = function(id) { + clearTimeout(id); + }; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],167:[function(require,module,exports){ +var core = require('../../core'); + +/** + * Prepare uploads elements to the GPU. The CanvasRenderer version of prepare + * provides the same APIs as the WebGL version, but doesn't do anything. + * @class + * @memberof PIXI + * @param renderer {PIXI.CanvasRenderer} A reference to the current renderer + */ +function CanvasPrepare() +{ +} + +CanvasPrepare.prototype.constructor = CanvasPrepare; +module.exports = CanvasPrepare; + +/** + * Stub method for upload. + * @param {Function|PIXI.DisplayObject|PIXI.Container} item Either + * the container or display object to search for items to upload or + * the callback function, if items have been added using `prepare.add`. + * @param {Function} done When completed + */ +CanvasPrepare.prototype.upload = function(displayObject, done) +{ + if (typeof displayObject === 'function') + { + done = displayObject; + displayObject = null; + } + done(); +}; + +/** + * Stub method for registering hooks. + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ +CanvasPrepare.prototype.register = function() +{ + return this; +}; + +/** + * Stub method for adding items. + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ +CanvasPrepare.prototype.add = function() +{ + return this; +}; + +/** + * Stub method for destroying plugin. + */ +CanvasPrepare.prototype.destroy = function() +{ +}; + +core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); +},{"../../core":62}],168:[function(require,module,exports){ + +module.exports = { + webGL: require('./webgl/WebGLPrepare'), + canvas: require('./canvas/CanvasPrepare') +}; +},{"./canvas/CanvasPrepare":167,"./webgl/WebGLPrepare":169}],169:[function(require,module,exports){ +var core = require('../../core'), + SharedTicker = core.ticker.shared; + +/** + * The prepare manager provides functionality to upload content to the GPU + * @class + * @memberof PIXI + * @param renderer {PIXI.WebGLRenderer} A reference to the current renderer + */ +function WebGLPrepare(renderer) +{ + /** + * Reference to the renderer. + * @type {PIXI.WebGLRenderer} + * @private + */ + this.renderer = renderer; + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + // Add textures and graphics to upload + this.register(findBaseTextures, uploadBaseTextures) + .register(findGraphics, uploadGraphics); +} + +/** + * The number of graphics or textures to upload to the GPU + * @property {number} UPLOADS_PER_FRAME + * @static + * @default 4 + */ +WebGLPrepare.UPLOADS_PER_FRAME = 4; + +WebGLPrepare.prototype.constructor = WebGLPrepare; +module.exports = WebGLPrepare; + +/** + * Upload all the textures and graphics to the GPU. + * @param {Function|PIXI.DisplayObject|PIXI.Container} item Either + * the container or display object to search for items to upload or + * the callback function, if items have been added using `prepare.add`. + * @param {Function} done When completed + */ +WebGLPrepare.prototype.upload = function(item, done) +{ + if (typeof item === 'function') + { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) + { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) + { + this.numLeft = WebGLPrepare.UPLOADS_PER_FRAME; + this.completes.push(done); + if (!this.ticking) + { + this.ticking = true; + SharedTicker.add(this.tick, this); + } + } + else + { + done(); + } +}; + +/** + * Handle tick update + * @private + */ +WebGLPrepare.prototype.tick = function() +{ + var i, len; + + // Upload the graphics + while(this.queue.length && this.numLeft > 0) + { + var item = this.queue[0]; + var uploaded = false; + for (i = 0, len = this.uploadHooks.length; i < len; i++) + { + if (this.uploadHooks[i](this.renderer, item)) + { + this.numLeft--; + this.queue.shift(); + uploaded = true; + break; + } + } + if (!uploaded) + { + this.queue.shift(); + } + } + + // We're finished + if (this.queue.length) + { + this.numLeft = WebGLPrepare.UPLOADS_PER_FRAME; + } + else + { + this.ticking = false; + SharedTicker.remove(this.tick, this); + var completes = this.completes.slice(0); + this.completes.length = 0; + for (i = 0, len = completes.length; i < len; i++) + { + completes[i](); + } + } +}; + +/** + * Adds hooks for finding and uploading items. + * @param {Function} [addHook] Function call that takes two parameters: `item:*, queue:Array` + function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] Function call that takes two parameters: `renderer:WebGLRenderer, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.WebGLPrepare} Instance of plugin for chaining. + */ +WebGLPrepare.prototype.register = function(addHook, uploadHook) +{ + if (addHook) + { + this.addHooks.push(addHook); + } + if (uploadHook) + { + this.uploadHooks.push(uploadHook); + } + return this; +}; + +/** + * Manually add an item to the uploading queue. + * @param {PIXI.DisplayObject|PIXI.Container|*} item Object to add to the queue + * @return {PIXI.WebGLPrepare} Instance of plugin for chaining. + */ +WebGLPrepare.prototype.add = function(item) +{ + var i, len; + + // Add additional hooks for finding elements on special + // types of objects that + for (i = 0, len = this.addHooks.length; i < len; i++) + { + if (this.addHooks[i](item, this.queue)) + { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) + { + for (i = item.children.length - 1; i >= 0; i--) + { + this.add(item.children[i]); + } + } + return this; +}; + +/** + * Destroys the plugin, don't use after this. + */ +WebGLPrepare.prototype.destroy = function() +{ + if (this.ticking) + { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; +}; + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU + * @private + * @param {*} item Item to check + * @return {boolean} If item was uploaded. + */ +function uploadBaseTextures(renderer, item) +{ + if (item instanceof core.BaseTexture) + { + renderer.textureManager.updateTexture(item); + return true; + } + return false; +} + +/** + * Built-in hook to upload PIXI.Graphics to the GPU + * @private + * @param {*} item Item to check + * @return {boolean} If item was uploaded. + */ +function uploadGraphics(renderer, item) +{ + if (item instanceof core.Graphics) + { + renderer.plugins.graphics.updateGraphics(item); + return true; + } + return false; +} + +/** + * Built-in hook to find textures from Sprites + * @private + * @param {PIXI.DisplayObject} item Display object to check + * @param {Array<*>} queue Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTextures(item, queue) +{ + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) + { + if (queue.indexOf(item) === -1) + { + queue.push(item); + } + return true; + } + else if (item._texture && item._texture instanceof core.Texture) + { + var texture = item._texture.baseTexture; + if (queue.indexOf(texture) === -1) + { + queue.push(texture); + } + return true; + } + return false; +} + +/** + * Built-in hook to find graphics + * @private + * @param {PIXI.DisplayObject} item Display object to check + * @param {Array<*>} queue Collection of items to upload + * @return {boolean} if a PIXI.Graphics object was found. + */ +function findGraphics(item, queue) +{ + if (item instanceof core.Graphics) + { + queue.push(item); + return true; + } + return false; +} + +core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); +},{"../../core":62}],170:[function(require,module,exports){ +(function (global){ +// run the polyfills +require('./polyfill'); + +var core = module.exports = require('./core'); + +// add core plugins. +core.extras = require('./extras'); +core.filters = require('./filters'); +core.interaction = require('./interaction'); +core.loaders = require('./loaders'); +core.mesh = require('./mesh'); +core.particles = require('./particles'); +core.accessibility = require('./accessibility'); +core.extract = require('./extract'); +core.prepare = require('./prepare'); + +// export a premade loader instance +/** + * A premade instance of the loader that can be used to loader resources. + * + * @name loader + * @memberof PIXI + * @property {PIXI.loaders.Loader} + */ +core.loader = new core.loaders.Loader(); + +// mixin the deprecation features. +Object.assign(core, require('./deprecation')); + +// Always export pixi globally. +global.PIXI = core; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"./accessibility":41,"./core":62,"./deprecation":119,"./extract":121,"./extras":129,"./filters":140,"./interaction":145,"./loaders":148,"./mesh":156,"./particles":159,"./polyfill":165,"./prepare":168}]},{},[170])(170) +}); + + +//# sourceMappingURL=pixi.js.map diff --git a/js/pixi/4.0.3/pixi.min.js b/js/pixi/4.0.3/pixi.min.js new file mode 100644 index 0000000..7e2c313 --- /dev/null +++ b/js/pixi/4.0.3/pixi.min.js @@ -0,0 +1,18 @@ +/*! + * pixi.js - v4.0.3 + * Compiled Thu Sep 29 2016 12:09:36 GMT-0400 (EDT) + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.PIXI=t()}}(function(){var t;return function t(e,r,i){function n(o,a){if(!r[o]){if(!e[o]){var h="function"==typeof require&&require;if(!a&&h)return h(o,!0);if(s)return s(o,!0);var u=new Error("Cannot find module '"+o+"'");throw u.code="MODULE_NOT_FOUND",u}var l=r[o]={exports:{}};e[o][0].call(l.exports,function(t){var r=e[o][1][t];return n(r?r:t)},l,l.exports,t,e,r,i)}return r[o].exports}for(var s="function"==typeof require&&require,o=0;o0)-(t<0)},r.abs=function(t){var e=t>>n-1;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,e|=r,e|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,t=(858993459&t)+(t>>>2&858993459),16843009*(t+(t>>>4)&252645135)>>>24},r.countTrailingZeros=i,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,t&=15,27030>>>t&1};var s=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,i=e,n=7;for(r>>>=1;r;r>>>=1)i<<=1,i|=1&r,--n;t[e]=i<>>8&255]<<16|s[t>>>16&255]<<8|s[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),t=65535&(t|t>>>16),t<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),t=1023&(t|t>>>16),t<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>i(t)+1}},{}],2:[function(t,e,r){"use strict";function i(t,e,r){r=r||2;var i=e&&e.length,s=i?e[0]*r:t.length,a=n(t,0,s,r,!0),h=[];if(!a)return h;var u,l,d,p,f,v,g;if(i&&(a=c(t,e,a,r)),t.length>80*r){u=d=t[0],l=p=t[1];for(var y=r;yd&&(d=f),v>p&&(p=v);g=Math.max(d-u,p-l)}return o(a,h,r,u,l,g),h}function n(t,e,r,i,n){var s,o;if(n===D(t,e,r,i)>0)for(s=e;s=e;s-=i)o=M(s,t[s],t[s+1],o);return o&&T(o,o.next)&&(A(o),o=o.next),o}function s(t,e){if(!t)return t;e||(e=t);var r,i=t;do if(r=!1,i.steiner||!T(i,i.next)&&0!==b(i.prev,i,i.next))i=i.next;else{if(A(i),i=e=i.prev,i===i.next)return null;r=!0}while(r||i!==e);return e}function o(t,e,r,i,n,c,d){if(t){!d&&c&&v(t,i,n,c);for(var p,f,g=t;t.prev!==t.next;)if(p=t.prev,f=t.next,c?h(t,i,n,c):a(t))e.push(p.i/r),e.push(t.i/r),e.push(f.i/r),A(t),t=f.next,g=f.next;else if(t=f,t===g){d?1===d?(t=u(t,e,r),o(t,e,r,i,n,c,2)):2===d&&l(t,e,r,i,n,c):o(s(t),e,r,i,n,c,1);break}}}function a(t){var e=t.prev,r=t,i=t.next;if(b(e,r,i)>=0)return!1;for(var n=t.next.next;n!==t.prev;){if(m(e.x,e.y,r.x,r.y,i.x,i.y,n.x,n.y)&&b(n.prev,n,n.next)>=0)return!1;n=n.next}return!0}function h(t,e,r,i){var n=t.prev,s=t,o=t.next;if(b(n,s,o)>=0)return!1;for(var a=n.xs.x?n.x>o.x?n.x:o.x:s.x>o.x?s.x:o.x,l=n.y>s.y?n.y>o.y?n.y:o.y:s.y>o.y?s.y:o.y,c=y(a,h,e,r,i),d=y(u,l,e,r,i),p=t.nextZ;p&&p.z<=d;){if(p!==t.prev&&p!==t.next&&m(n.x,n.y,s.x,s.y,o.x,o.y,p.x,p.y)&&b(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(p=t.prevZ;p&&p.z>=c;){if(p!==t.prev&&p!==t.next&&m(n.x,n.y,s.x,s.y,o.x,o.y,p.x,p.y)&&b(p.prev,p,p.next)>=0)return!1;p=p.prevZ}return!0}function u(t,e,r){var i=t;do{var n=i.prev,s=i.next.next;!T(n,s)&&E(n,i,i.next,s)&&S(n,s)&&S(s,n)&&(e.push(n.i/r),e.push(i.i/r),e.push(s.i/r),A(i),A(i.next),i=t=s),i=i.next}while(i!==t);return i}function l(t,e,r,i,n,a){var h=t;do{for(var u=h.next.next;u!==h.prev;){if(h.i!==u.i&&_(h,u)){var l=R(h,u);return h=s(h,h.next),l=s(l,l.next),o(h,e,r,i,n,a),void o(l,e,r,i,n,a)}u=u.next}h=h.next}while(h!==t)}function c(t,e,r,i){var o,a,h,u,l,c=[];for(o=0,a=e.length;o=i.next.y){var a=i.x+(s-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(a<=n&&a>o){if(o=a,a===n){if(s===i.y)return i;if(s===i.next.y)return i.next}r=i.x=i.x&&i.x>=l&&m(sr.x)&&S(i,t)&&(r=i,d=h)),i=i.next;return r}function v(t,e,r,i){var n=t;do null===n.z&&(n.z=y(n.x,n.y,e,r,i)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==t);n.prevZ.nextZ=null,n.prevZ=null,g(n)}function g(t){var e,r,i,n,s,o,a,h,u=1;do{for(r=t,t=null,s=null,o=0;r;){for(o++,i=r,a=0,e=0;e0||h>0&&i;)0===a?(n=i,i=i.nextZ,h--):0!==h&&i?r.z<=i.z?(n=r,r=r.nextZ,a--):(n=i,i=i.nextZ,h--):(n=r,r=r.nextZ,a--),s?s.nextZ=n:t=n,n.prevZ=s,s=n;r=i}s.nextZ=null,u*=2}while(o>1);return t}function y(t,e,r,i,n){return t=32767*(t-r)/n,e=32767*(e-i)/n,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1}function x(t){var e=t,r=t;do e.x=0&&(t-o)*(i-a)-(r-o)*(e-a)>=0&&(r-o)*(s-a)-(n-o)*(i-a)>=0}function _(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!w(t,e)&&S(t,e)&&S(e,t)&&C(t,e)}function b(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function T(t,e){return t.x===e.x&&t.y===e.y}function E(t,e,r,i){return!!(T(t,e)&&T(r,i)||T(t,i)&&T(r,e))||b(t,e,r)>0!=b(t,e,i)>0&&b(r,i,t)>0!=b(r,i,e)>0}function w(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&E(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}function S(t,e){return b(t.prev,t,t.next)<0?b(t,e,t.next)>=0&&b(t,t.prev,e)>=0:b(t,e,t.prev)<0||b(t,t.next,e)<0}function C(t,e){var r=t,i=!1,n=(t.x+e.x)/2,s=(t.y+e.y)/2;do r.y>s!=r.next.y>s&&n<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(i=!i),r=r.next;while(r!==t);return i}function R(t,e){var r=new O(t.i,t.x,t.y),i=new O(e.i,e.x,e.y),n=t.next,s=e.prev;return t.next=e,e.prev=t,r.next=n,n.prev=r,i.next=r,r.prev=i,s.next=i,i.prev=s,i}function M(t,e,r,i){var n=new O(t,e,r);return i?(n.next=i.next,n.prev=i,i.next.prev=n,i.next=n):(n.prev=n,n.next=n),n}function A(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function O(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function D(t,e,r,i){for(var n=0,s=e,o=r-i;s0&&(i+=t[n-1].length,r.holes.push(i))}return r}},{}],3:[function(t,e,r){"use strict";function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function n(){}var s=Object.prototype.hasOwnProperty,o="function"!=typeof Object.create&&"~";n.prototype._events=void 0,n.prototype.eventNames=function(){var t,e=this._events,r=[];if(!e)return r;for(t in e)s.call(e,t)&&r.push(o?t.slice(1):t);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(e)):r},n.prototype.listeners=function(t,e){var r=o?o+t:t,i=this._events&&this._events[r];if(e)return!!i;if(!i)return[];if(i.fn)return[i.fn];for(var n=0,s=i.length,a=new Array(s);n=t.byteLength?i.bufferSubData(this.type,e,t):i.bufferData(this.type,t,this.drawType),this.data=t},n.prototype.bind=function(){var t=this.gl;t.bindBuffer(this.type,this.buffer)},n.createVertexBuffer=function(t,e,r){return new n(t,t.ARRAY_BUFFER,e,r)},n.createIndexBuffer=function(t,e,r){return new n(t,t.ELEMENT_ARRAY_BUFFER,e,r)},n.create=function(t,e,r,i){return new n(t,e,i)},n.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer)},e.exports=n},{}],7:[function(t,e,r){var i=t("./GLTexture"),n=function(t,e,r){this.gl=t,this.framebuffer=t.createFramebuffer(),this.stencil=null,this.texture=null,this.width=e||100,this.height=r||100};n.prototype.enableTexture=function(t){var e=this.gl;this.texture=t||new i(e),this.texture.bind(),this.bind(),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0)},n.prototype.enableStencil=function(){if(!this.stencil){var t=this.gl;this.stencil=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.stencil),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.stencil),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,this.width,this.height)}},n.prototype.clear=function(t,e,r,i){this.bind();var n=this.gl;n.clearColor(t,e,r,i),n.clear(n.COLOR_BUFFER_BIT)},n.prototype.bind=function(){var t=this.gl;this.texture&&this.texture.unbind(),t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer)},n.prototype.unbind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)},n.prototype.resize=function(t,e){var r=this.gl;this.width=t,this.height=e,this.texture&&this.texture.uploadData(null,t,e),this.stencil&&(r.bindRenderbuffer(r.RENDERBUFFER,this.stencil),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e))},n.prototype.destroy=function(){var t=this.gl;this.texture&&this.texture.destroy(),t.deleteFramebuffer(this.framebuffer),this.gl=null,this.stencil=null,this.texture=null},n.createRGBA=function(t,e,r){var s=i.fromData(t,null,e,r);s.enableNearestScaling(),s.enableWrapClamp();var o=new n(t,e,r);return o.enableTexture(s),o.unbind(),o},n.createFloat32=function(t,e,r,s){var o=new i.fromData(t,s,e,r);o.enableNearestScaling(),o.enableWrapClamp();var a=new n(t,e,r);return a.enableTexture(o),a.unbind(),a},e.exports=n},{"./GLTexture":9}],8:[function(t,e,r){var i=t("./shader/compileProgram"),n=t("./shader/extractAttributes"),s=t("./shader/extractUniforms"),o=t("./shader/generateUniformAccessObject"),a=function(t,e,r){this.gl=t,this.program=i(t,e,r),this.attributes=n(t,this.program);var a=s(t,this.program);this.uniforms=o(t,a)};a.prototype.bind=function(){this.gl.useProgram(this.program)},a.prototype.destroy=function(){},e.exports=a},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18}],9:[function(t,e,r){var i=function(t,e,r,i,n){this.gl=t,this.texture=t.createTexture(),this.mipmap=!1,this.premultiplyAlpha=!1,this.width=e||0,this.height=r||0,this.format=i||t.RGBA,this.type=n||t.UNSIGNED_BYTE};i.prototype.upload=function(t){this.bind();var e=this.gl;this.width=t.videoWidth||t.width,this.height=t.videoHeight||t.height,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),e.texImage2D(e.TEXTURE_2D,0,this.format,this.format,this.type,t)};var n=!1;i.prototype.uploadData=function(t,e,r){this.bind();var i=this.gl;if(this.width=e||this.width,this.height=r||this.height,t instanceof Float32Array){if(!n){var s=i.getExtension("OES_texture_float");if(!s)throw new Error("floating point textures not available");n=!0}this.type=i.FLOAT}else this.type=i.UNSIGNED_BYTE;i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.texImage2D(i.TEXTURE_2D,0,this.format,this.width,this.height,0,this.format,this.type,t||null)},i.prototype.bind=function(t){var e=this.gl;void 0!==t&&e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,this.texture)},i.prototype.unbind=function(){var t=this.gl;t.bindTexture(t.TEXTURE_2D,null)},i.prototype.minFilter=function(t){var e=this.gl;this.bind(),this.mipmap?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR:e.NEAREST)},i.prototype.magFilter=function(t){var e=this.gl;this.bind(),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t?e.LINEAR:e.NEAREST)},i.prototype.enableMipmap=function(){var t=this.gl;this.bind(),this.mipmap=!0,t.generateMipmap(t.TEXTURE_2D)},i.prototype.enableLinearScaling=function(){this.minFilter(!0),this.magFilter(!0)},i.prototype.enableNearestScaling=function(){this.minFilter(!1),this.magFilter(!1)},i.prototype.enableWrapClamp=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)},i.prototype.enableWrapRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT)},i.prototype.enableWrapMirrorRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.MIRRORED_REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.MIRRORED_REPEAT)},i.prototype.destroy=function(){var t=this.gl;t.deleteTexture(this.texture)},i.fromSource=function(t,e,r){var n=new i(t);return n.premultiplyAlpha=r||!1,n.upload(e),n},i.fromData=function(t,e,r,n){var s=new i(t);return s.uploadData(e,r,n),s},e.exports=i},{}],10:[function(t,e,r){function i(t,e){if(this.nativeVaoExtension=null,i.FORCE_NATIVE||(this.nativeVaoExtension=t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object")),this.nativeState=e,this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var r=t.getParameter(t.MAX_VERTEX_ATTRIBS);this.nativeState={tempAttribState:new Array(r),attribState:new Array(r)}}this.gl=t,this.attributes=[],this.indexBuffer=null,this.dirty=!1}var n=t("./setVertexAttribArrays");i.prototype.constructor=i,e.exports=i,i.FORCE_NATIVE=!1,i.prototype.bind=function(){return this.nativeVao?(this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao),this.dirty&&(this.dirty=!1,this.activate())):this.activate(),this},i.prototype.unbind=function(){return this.nativeVao&&this.nativeVaoExtension.bindVertexArrayOES(null),this},i.prototype.activate=function(){for(var t=this.gl,e=null,r=0;r=0;i--){var n=t[i];"."===n?t.splice(i,1):".."===n?(t.splice(i,1),r++):r&&(t.splice(i,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}function i(t,e){if(t.filter)return t.filter(e);for(var r=[],i=0;i=-1&&!n;s--){var o=s>=0?arguments[s]:t.cwd();if("string"!=typeof o)throw new TypeError("Arguments to path.resolve must be strings");o&&(r=o+"/"+r,n="/"===o.charAt(0))}return r=e(i(r.split("/"),function(t){return!!t}),!n).join("/"),(n?"/":"")+r||"."},r.normalize=function(t){var n=r.isAbsolute(t),s="/"===o(t,-1);return t=e(i(t.split("/"),function(t){return!!t}),!n).join("/"),t||n||(t="."),t&&s&&(t+="/"),(n?"/":"")+t},r.isAbsolute=function(t){return"/"===t.charAt(0)},r.join=function(){var t=Array.prototype.slice.call(arguments,0);return r.normalize(i(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},r.relative=function(t,e){function i(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=r.resolve(t).substr(1),e=r.resolve(e).substr(1);for(var n=i(t.split("/")),s=i(e.split("/")),o=Math.min(n.length,s.length),a=o,h=0;h1)for(var r=1;r1&&(i=r[0]+"@",t=r[1]),t=t.replace(I,".");var n=t.split("."),s=o(n,e).join(".");return i+s}function h(t){for(var e,r,i=[],n=0,s=t.length;n=55296&&e<=56319&&n65535&&(t-=65536,e+=N(t>>>10&1023|55296),t=56320|1023&t),e+=N(t)}).join("")}function l(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:E}function c(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function d(t,e,r){var i=0;for(t=r?B(t/R):t>>1,t+=B(t/e);t>F*S>>1;i+=E)t=B(t/F);return B(i+(F+1)*t/(t+C))}function p(t){var e,r,i,n,o,a,h,c,p,f,v=[],g=t.length,y=0,x=A,m=M;for(r=t.lastIndexOf(O),r<0&&(r=0),i=0;i=128&&s("not-basic"),v.push(t.charCodeAt(i));for(n=r>0?r+1:0;n=g&&s("invalid-input"),c=l(t.charCodeAt(n++)),(c>=E||c>B((T-y)/a))&&s("overflow"),y+=c*a,p=h<=m?w:h>=m+S?S:h-m,!(cB(T/f)&&s("overflow"),a*=f;e=v.length+1,m=d(y-o,e,0==o),B(y/e)>T-x&&s("overflow"),x+=B(y/e),y%=e,v.splice(y++,0,x)}return u(v)}function f(t){var e,r,i,n,o,a,u,l,p,f,v,g,y,x,m,_=[];for(t=h(t),g=t.length,e=A,r=0,o=M,a=0;a=e&&vB((T-r)/y)&&s("overflow"),r+=(u-e)*y,e=u,a=0;aT&&s("overflow"),v==e){for(l=r,p=E;f=p<=o?w:p>=o+S?S:p-o,!(l= 0x80 (not a basic code point)","invalid-input":"Invalid input"},F=E-w,B=Math.floor,N=String.fromCharCode;if(_={version:"1.4.1",ucs2:{decode:h,encode:u},decode:p,encode:f,toASCII:g,toUnicode:v},"function"==typeof t&&"object"==typeof t.amd&&t.amd)t("punycode",function(){return _});else if(y&&x)if(r.exports==y)x.exports=_;else for(b in _)_.hasOwnProperty(b)&&(y[b]=_[b]);else n.punycode=_}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],25:[function(t,e,r){"use strict";function i(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,r,s){e=e||"&",r=r||"=";var o={};if("string"!=typeof t||0===t.length)return o;var a=/\+/g;t=t.split(e);var h=1e3;s&&"number"==typeof s.maxKeys&&(h=s.maxKeys);var u=t.length;h>0&&u>h&&(u=h);for(var l=0;l=0?(c=v.substr(0,g),d=v.substr(g+1)):(c=v,d=""),p=decodeURIComponent(c),f=decodeURIComponent(d),i(o,p)?n(o[p])?o[p].push(f):o[p]=[o[p],f]:o[p]=f}return o};var n=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],26:[function(t,e,r){"use strict";function i(t,e){if(t.map)return t.map(e);for(var r=[],i=0;i",'"',"`"," ","\r","\n","\t"],f=["{","}","|","\\","^","`"].concat(p),v=["'"].concat(f),g=["%","/","?",";","#"].concat(v),y=["/","?","#"],x=255,m=/^[+a-z0-9A-Z_-]{0,63}$/,_=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,b={javascript:!0,"javascript:":!0},T={javascript:!0,"javascript:":!0},E={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},w=t("querystring");i.prototype.parse=function(t,e,r){if(!u.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var i=t.indexOf("?"),n=i!==-1&&i127?"x":L[B];if(!F.match(m)){var U=P.slice(0,R),k=P.slice(R+1),j=L.match(_);j&&(U.push(j[1]),k.unshift(j[2])),k.length&&(a="/"+k.join(".")+a),this.hostname=U.join(".");break}}}this.hostname.length>x?this.hostname="":this.hostname=this.hostname.toLowerCase(),D||(this.hostname=h.toASCII(this.hostname));var W=this.port?":"+this.port:"",G=this.hostname||"";this.host=G+W,this.href+=this.host,D&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==a[0]&&(a="/"+a))}if(!b[f])for(var R=0,I=v.length;R0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return r.search=t.search,r.query=t.query,u.isNull(r.pathname)&&u.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!b.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var C=b.slice(-1)[0],R=(r.host||t.host||b.length>1)&&("."===C||".."===C)||""===C,M=0,A=b.length;A>=0;A--)C=b[A],"."===C?b.splice(A,1):".."===C?(b.splice(A,1),M++):M&&(b.splice(A,1),M--);if(!m&&!_)for(;M--;M)b.unshift("..");!m||""===b[0]||b[0]&&"/"===b[0].charAt(0)||b.unshift(""),R&&"/"!==b.join("/").substr(-1)&&b.push("");var O=""===b[0]||b[0]&&"/"===b[0].charAt(0);if(w){r.hostname=r.host=O?"":b.length?b.shift():"";var S=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return m=m||r.host&&b.length,m&&!O&&b.unshift(""),b.length?r.pathname=b.join("/"):(r.pathname=null,r.path=null),u.isNull(r.pathname)&&u.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},i.prototype.parseHost=function(){var t=this.host,e=c.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":29,punycode:24,querystring:27}],29:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],30:[function(t,e,r){"use strict";function i(){}function n(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function s(){this._events=new i,this._eventsCount=0}var o=Object.prototype.hasOwnProperty,a="~";Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(a=!1)),s.prototype.eventNames=function(){var t,e,r=[];if(0===this._eventsCount)return r;for(e in t=this._events)o.call(t,e)&&r.push(a?e.slice(1):e);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},s.prototype.listeners=function(t,e){var r=a?a+t:t,i=this._events[r];if(e)return!!i;if(!i)return[];if(i.fn)return[i.fn];for(var n=0,s=i.length,o=new Array(s);n0))return void this.abort("["+t.status+"]"+t.statusText+":"+t.responseURL);if(this.xhrType===i.XHR_RESPONSE_TYPE.TEXT)this.data=t.responseText;else if(this.xhrType===i.XHR_RESPONSE_TYPE.JSON)try{this.data=JSON.parse(t.responseText),this.isJson=!0}catch(t){return void this.abort("Error trying to parse loaded json:",t)}else if(this.xhrType===i.XHR_RESPONSE_TYPE.DOCUMENT)try{if(window.DOMParser){var r=new DOMParser;this.data=r.parseFromString(t.responseText,"text/xml")}else{var n=document.createElement("div");n.innerHTML=t.responseText,this.data=n}this.isXml=!0}catch(t){return void this.abort("Error trying to parse loaded xml:",t)}else this.data=t.response||t.responseText;this.complete()},i.prototype._determineCrossOrigin=function(t,e){if(0===t.indexOf("data:"))return"";e=e||window.location,u||(u=document.createElement("a")),u.href=t,t=a(u.href,{strictMode:!0});var r=!t.port&&""===e.port||t.port===e.port,i=t.protocol?t.protocol+":":"";return t.host===e.hostname&&r&&i===e.protocol?"":"anonymous"},i.prototype._determineXhrType=function(){return i._xhrTypeMap[this._getExtension()]||i.XHR_RESPONSE_TYPE.TEXT},i.prototype._determineLoadType=function(){return i._loadTypeMap[this._getExtension()]||i.LOAD_TYPE.XHR},i.prototype._getExtension=function(){var t=this.url,e="";if(this.isDataUrl){var r=t.indexOf("/");e=t.substring(r+1,t.indexOf(";",r))}else{var i=t.indexOf("?");i!==-1&&(t=t.substring(0,i)),e=t.substring(t.lastIndexOf(".")+1)}return e.toLowerCase()},i.prototype._getMimeFromXhrType=function(t){switch(t){case i.XHR_RESPONSE_TYPE.BUFFER:return"application/octet-binary";case i.XHR_RESPONSE_TYPE.BLOB:return"application/blob";case i.XHR_RESPONSE_TYPE.DOCUMENT:return"application/xml";case i.XHR_RESPONSE_TYPE.JSON:return"application/json";case i.XHR_RESPONSE_TYPE.DEFAULT:case i.XHR_RESPONSE_TYPE.TEXT:default:return"text/plain"}},i.LOAD_TYPE={XHR:1,IMAGE:2,AUDIO:3,VIDEO:4},i.XHR_RESPONSE_TYPE={DEFAULT:"text",BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"},i._loadTypeMap={gif:i.LOAD_TYPE.IMAGE,png:i.LOAD_TYPE.IMAGE,bmp:i.LOAD_TYPE.IMAGE,jpg:i.LOAD_TYPE.IMAGE,jpeg:i.LOAD_TYPE.IMAGE,tif:i.LOAD_TYPE.IMAGE,tiff:i.LOAD_TYPE.IMAGE,webp:i.LOAD_TYPE.IMAGE,tga:i.LOAD_TYPE.IMAGE,"svg+xml":i.LOAD_TYPE.IMAGE},i._xhrTypeMap={xhtml:i.XHR_RESPONSE_TYPE.DOCUMENT,html:i.XHR_RESPONSE_TYPE.DOCUMENT,htm:i.XHR_RESPONSE_TYPE.DOCUMENT,xml:i.XHR_RESPONSE_TYPE.DOCUMENT,tmx:i.XHR_RESPONSE_TYPE.DOCUMENT,tsx:i.XHR_RESPONSE_TYPE.DOCUMENT,svg:i.XHR_RESPONSE_TYPE.DOCUMENT,gif:i.XHR_RESPONSE_TYPE.BLOB,png:i.XHR_RESPONSE_TYPE.BLOB,bmp:i.XHR_RESPONSE_TYPE.BLOB,jpg:i.XHR_RESPONSE_TYPE.BLOB,jpeg:i.XHR_RESPONSE_TYPE.BLOB,tif:i.XHR_RESPONSE_TYPE.BLOB,tiff:i.XHR_RESPONSE_TYPE.BLOB,webp:i.XHR_RESPONSE_TYPE.BLOB,tga:i.XHR_RESPONSE_TYPE.BLOB,json:i.XHR_RESPONSE_TYPE.JSON,text:i.XHR_RESPONSE_TYPE.TEXT,txt:i.XHR_RESPONSE_TYPE.TEXT},i.setExtensionLoadType=function(t,e){s(i._loadTypeMap,t,e)},i.setExtensionXhrType=function(t,e){s(i._xhrTypeMap,t,e)}},{eventemitter3:30,"parse-uri":31}],34:[function(t,e,r){"use strict";function i(){}function n(t,e,r){var i=0,n=t.length;!function s(o){return o||i===n?void(r&&r(o)):void e(t[i++],s)}()}function s(t){return function(){if(null===t)throw new Error("Callback was already called.");var e=t;t=null,e.apply(this,arguments)}}function o(t,e){function r(t,e,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(a.started=!0,null==t&&a.idle())return void setTimeout(function(){a.drain()},1);var n={data:t,callback:"function"==typeof r?r:i};e?a._tasks.unshift(n):a._tasks.push(n),setTimeout(function(){a.process()},1)}function n(t){return function(){o-=1,t.callback.apply(t,arguments),null!=arguments[0]&&a.error(arguments[0],t.data),o<=a.concurrency-a.buffer&&a.unsaturated(),a.idle()&&a.drain(),a.process()}}if(null==e)e=1;else if(0===e)throw new Error("Concurrency must not be zero");var o=0,a={_tasks:[],concurrency:e,saturated:i,unsaturated:i,buffer:e/4,empty:i,drain:i,error:i,started:!1,paused:!1,push:function(t,e){r(t,!1,e)},kill:function(){a.drain=i,a._tasks=[]},unshift:function(t,e){r(t,!0,e)},process:function(){for(;!a.paused&&o>2,i[1]=(3&e[0])<<4|e[1]>>4,i[2]=(15&e[1])<<2|e[2]>>6,i[3]=63&e[2],o=n-(t.length-1)){case 2:i[3]=64,i[2]=64;break;case 1:i[3]=64}for(s=0;s=0;r--)this.updateAccessibleObjects(e[r])}},i.prototype.update=function(){if(this.renderer.renderingToScreen){this.updateAccessibleObjects(this.renderer._lastObjectRendered);var t=this.renderer.view.getBoundingClientRect(),e=t.width/this.renderer.width,r=t.height/this.renderer.height,i=this.div;i.style.left=t.left+"px",i.style.top=t.top+"px",i.style.width=this.renderer.width+"px",i.style.height=this.renderer.height+"px";for(var s=0;sthis.renderer.width&&(t.width=this.renderer.width-t.x),t.y+t.height>this.renderer.height&&(t.height=this.renderer.height-t.y)},i.prototype.addChild=function(t){var e=this.pool.pop();e||(e=document.createElement("button"),e.style.width="100px",e.style.height="100px",e.style.backgroundColor=this.debug?"rgba(255,0,0,0.5)":"transparent",e.style.position="absolute",e.style.zIndex=2,e.style.borderStyle="none",e.addEventListener("click",this._onClick.bind(this)),e.addEventListener("focus",this._onFocus.bind(this)),e.addEventListener("focusout",this._onFocusOut.bind(this))),t.accessibleTitle?e.title=t.accessibleTitle:t.accessibleTitle||t.accessibleHint||(e.title="displayObject "+this.tabIndex),t.accessibleHint&&e.setAttribute("aria-label",t.accessibleHint),t._accessibleActive=!0,t._accessibleDiv=e,e.displayObject=t,this.children.push(t),this.div.appendChild(t._accessibleDiv),t._accessibleDiv.tabIndex=t.tabIndex},i.prototype._onClick=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"click",e.eventData)},i.prototype._onFocus=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseover",e.eventData)},i.prototype._onFocusOut=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseout",e.eventData)},i.prototype._onKeyDown=function(t){9===t.keyCode&&this.activate()},i.prototype._onMouseMove=function(){this.deactivate()},i.prototype.destroy=function(){this.div=null;for(var t=0;tthis.maxX||this.minY>this.maxY},i.prototype.clear=function(){this.updateID++,this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0)},i.prototype.getRectangle=function(t){return this.minX>this.maxX||this.minY>this.maxY?s.EMPTY:(t=t||new s(0,0,1,1),t.x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)},i.prototype.addPoint=function(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)},i.prototype.addQuad=function(t){var e=this.minX,r=this.minY,i=this.maxX,n=this.maxY,s=t[0],o=t[1];e=si?s:i,n=o>n?o:n,s=t[2],o=t[3],e=si?s:i,n=o>n?o:n,s=t[4],o=t[5],e=si?s:i,n=o>n?o:n,s=t[6],o=t[7],e=si?s:i,n=o>n?o:n,this.minX=e,this.minY=r,this.maxX=i,this.maxY=n},i.prototype.addFrame=function(t,e,r,i,n){var s=t.worldTransform,o=s.a,a=s.b,h=s.c,u=s.d,l=s.tx,c=s.ty,d=this.minX,p=this.minY,f=this.maxX,v=this.maxY,g=o*e+h*r+l,y=a*e+u*r+c;d=gf?g:f,v=y>v?y:v,g=o*i+h*r+l,y=a*i+u*r+c,d=gf?g:f,v=y>v?y:v,g=o*e+h*n+l,y=a*e+u*n+c,d=gf?g:f,v=y>v?y:v,g=o*i+h*n+l,y=a*i+u*n+c,d=gf?g:f,v=y>v?y:v,this.minX=d,this.minY=p,this.maxX=f,this.maxY=v},i.prototype.addVertices=function(t,e,r,i){for(var n=t.worldTransform,s=n.a,o=n.b,a=n.c,h=n.d,u=n.tx,l=n.ty,c=this.minX,d=this.minY,p=this.maxX,f=this.maxY,v=r;vp?x:p,f=m>f?m:f}this.minX=c,this.minY=d,this.maxX=p,this.maxY=f},i.prototype.addBounds=function(t){var e=this.minX,r=this.minY,i=this.maxX,n=this.maxY;this.minX=t.minXi?t.maxX:i,this.maxY=t.maxY>n?t.maxY:n}},{"../math":67}],45:[function(t,e,r){function i(){s.call(this),this.children=[]}var n=t("../utils"),s=t("./DisplayObject");i.prototype=Object.create(s.prototype),i.prototype.constructor=i,e.exports=i,Object.defineProperties(i.prototype,{width:{get:function(){return this.scale.x*this.getLocalBounds().width},set:function(t){var e=this.getLocalBounds().width;0!==e?this.scale.x=t/e:this.scale.x=1,this._width=t}},height:{get:function(){return this.scale.y*this.getLocalBounds().height},set:function(t){var e=this.getLocalBounds().height;0!==e?this.scale.y=t/e:this.scale.y=1,this._height=t}}}),i.prototype.onChildrenChange=function(){},i.prototype.addChild=function(t){var e=arguments.length;if(e>1)for(var r=0;r=0&&e<=this.children.length)return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),this.onChildrenChange(e),t.emit("added",this),t;throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length)},i.prototype.swapChildren=function(t,e){if(t!==e){var r=this.getChildIndex(t),i=this.getChildIndex(e);if(r<0||i<0)throw new Error("swapChildren: Both the supplied DisplayObjects must be children of the caller.");this.children[r]=e,this.children[i]=t,this.onChildrenChange(r=this.children.length)throw new Error("The supplied index is out of bounds");var r=this.getChildIndex(t);n.removeItems(this.children,r,1),this.children.splice(e,0,t),this.onChildrenChange(e)},i.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Supplied index "+t+" does not exist in the child list, or the supplied DisplayObject is not a child of the caller");return this.children[t]},i.prototype.removeChild=function(t){var e=arguments.length;if(e>1)for(var r=0;r0&&o<=s){for(r=this.children.splice(n,o),i=0;i=0;i--){var n=r[i];n.parent=null,n.destroy(t)}}},{"../utils":116,"./DisplayObject":46}],46:[function(t,e,r){function i(){n.call(this);var t=s.TRANSFORM_MODE.DEFAULT===s.TRANSFORM_MODE.STATIC?o:a;this.transform=new t,this.alpha=1,this.visible=!0,this.renderable=!0,this.parent=null,this.worldAlpha=1,this.filterArea=null,this._filters=null,this._enabledFilters=null,this._bounds=new h,this._boundsID=0,this._lastBoundsID=-1,this._boundsRect=null,this._localBoundsRect=null,this._mask=null}var n=t("eventemitter3"),s=t("../const"),o=t("./TransformStatic"),a=t("./Transform"),h=t("./Bounds"),u=t("../math"),l=new i;i.prototype=Object.create(n.prototype),i.prototype.constructor=i,e.exports=i,Object.defineProperties(i.prototype,{x:{get:function(){return this.position.x},set:function(t){this.transform.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.transform.position.y=t}},worldTransform:{get:function(){return this.transform.worldTransform}},localTransform:{get:function(){return this.transform.localTransform}},position:{get:function(){return this.transform.position},set:function(t){this.transform.position.copy(t)}},scale:{get:function(){return this.transform.scale},set:function(t){this.transform.scale.copy(t)}},pivot:{get:function(){return this.transform.pivot},set:function(t){this.transform.pivot.copy(t)}},skew:{get:function(){return this.transform.skew},set:function(t){this.transform.skew.copy(t)}},rotation:{get:function(){return this.transform.rotation},set:function(t){this.transform.rotation=t}},worldVisible:{get:function(){var t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}},mask:{get:function(){return this._mask},set:function(t){this._mask&&(this._mask.renderable=!0),this._mask=t,this._mask&&(this._mask.renderable=!1)}},filters:{get:function(){return this._filters&&this._filters.slice()},set:function(t){this._filters=t&&t.slice()}}}),i.prototype.updateTransform=function(){this.transform.updateTransform(this.parent.transform),this.worldAlpha=this.alpha*this.parent.worldAlpha,this._bounds.updateID++},i.prototype.displayObjectUpdateTransform=i.prototype.updateTransform,i.prototype._recursivePostUpdateTransform=function(){this.parent?(this.parent._recursivePostUpdateTransform(),this.transform.updateTransform(this.parent.transform)):this.transform.updateTransform(l.transform)},i.prototype.getBounds=function(t,e){return t||(this.parent?(this._recursivePostUpdateTransform(),this.updateTransform()):(this.parent=l,this.parent.transform._worldID++,this.updateTransform(),this.parent=null)),this._boundsID!==this._lastBoundsID&&this.calculateBounds(),e||(this._boundsRect||(this._boundsRect=new u.Rectangle),e=this._boundsRect),this._bounds.getRectangle(e)},i.prototype.getLocalBounds=function(t){var e=this.transform,r=this.parent;this.parent=null,this.transform=l.transform,t||(this._localBoundsRect||(this._localBoundsRect=new u.Rectangle),t=this._localBoundsRect);var i=this.getBounds(!1,t);return this.parent=r,this.transform=e,i},i.prototype.toGlobal=function(t,e,r){return r||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=l,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)},i.prototype.toLocal=function(t,e,r,i){return e&&(t=e.toGlobal(t,r,i)),i||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=l,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,r)},i.prototype.renderWebGL=function(t){},i.prototype.renderCanvas=function(t){},i.prototype.setParent=function(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t},i.prototype.setTransform=function(t,e,r,i,n,s,o,a,h){return this.position.x=t||0,this.position.y=e||0,this.scale.x=r?r:1,this.scale.y=i?i:1,this.rotation=n||0,this.skew.x=s||0,this.skew.y=o||0,this.pivot.x=a||0,this.pivot.y=h||0,this},i.prototype.destroy=function(){this.removeAllListeners(),this.parent&&this.parent.removeChild(this),this.transform=null,this.parent=null,this._bounds=null,this._currentBounds=null,this._mask=null,this.filterArea=null,this.interactive=!1,this.interactiveChildren=!1}},{"../const":43,"../math":67,"./Bounds":44,"./Transform":47,"./TransformStatic":49,eventemitter3:3}],47:[function(t,e,r){function i(){s.call(this),this.position=new n.Point(0,0),this.scale=new n.Point(1,1),this.skew=new n.ObservablePoint(this.updateSkew,this,0,0),this.pivot=new n.Point(0,0),this._rotation=0,this._sr=Math.sin(0),this._cr=Math.cos(0),this._cy=Math.cos(0),this._sy=Math.sin(0),this._nsx=Math.sin(0),this._cx=Math.cos(0)}var n=t("../math"),s=t("./TransformBase");i.prototype=Object.create(s.prototype),i.prototype.constructor=i,i.prototype.updateSkew=function(){this._cy=Math.cos(this.skew.y),this._sy=Math.sin(this.skew.y),this._nsx=Math.sin(this.skew.x),this._cx=Math.cos(this.skew.x)},i.prototype.updateLocalTransform=function(){var t,e,r,i,n=this.localTransform;t=this._cr*this.scale.x,e=this._sr*this.scale.x,r=-this._sr*this.scale.y,i=this._cr*this.scale.y,n.a=this._cy*t+this._sy*r,n.b=this._cy*e+this._sy*i,n.c=this._nsx*t+this._cx*r,n.d=this._nsx*e+this._cx*i},i.prototype.updateTransform=function(t){var e,r,i,n,s=t.worldTransform,o=this.worldTransform,a=this.localTransform;e=this._cr*this.scale.x,r=this._sr*this.scale.x,i=-this._sr*this.scale.y,n=this._cr*this.scale.y,a.a=this._cy*e+this._sy*i,a.b=this._cy*r+this._sy*n,a.c=this._nsx*e+this._cx*i,a.d=this._nsx*r+this._cx*n,a.tx=this.position.x-(this.pivot.x*a.a+this.pivot.y*a.c),a.ty=this.position.y-(this.pivot.x*a.b+this.pivot.y*a.d),o.a=a.a*s.a+a.b*s.c,o.b=a.a*s.b+a.b*s.d,o.c=a.c*s.a+a.d*s.c,o.d=a.c*s.b+a.d*s.d,o.tx=a.tx*s.a+a.ty*s.c+s.tx,o.ty=a.tx*s.b+a.ty*s.d+s.ty,this._worldID++},i.prototype.setFromMatrix=function(t){t.decompose(this)},Object.defineProperties(i.prototype,{rotation:{get:function(){return this._rotation},set:function(t){this._rotation=t,this._sr=Math.sin(t),this._cr=Math.cos(t)}}}),e.exports=i},{"../math":67,"./TransformBase":48}],48:[function(t,e,r){function i(){this.worldTransform=new n.Matrix,this.localTransform=new n.Matrix,this._worldID=0}var n=t("../math");i.prototype.constructor=i,i.prototype.updateLocalTransform=function(){},i.prototype.updateTransform=function(t){var e=t.worldTransform,r=this.worldTransform,i=this.localTransform;r.a=i.a*e.a+i.b*e.c,r.b=i.a*e.b+i.b*e.d,r.c=i.c*e.a+i.d*e.c,r.d=i.c*e.b+i.d*e.d,r.tx=i.tx*e.a+i.ty*e.c+e.tx,r.ty=i.tx*e.b+i.ty*e.d+e.ty,this._worldID++},i.prototype.updateWorldTransform=i.prototype.updateTransform,i.IDENTITY=new i,e.exports=i},{"../math":67}],49:[function(t,e,r){function i(){s.call(this),this.position=new n.ObservablePoint(this.onChange,this,0,0),this.scale=new n.ObservablePoint(this.onChange,this,1,1),this.pivot=new n.ObservablePoint(this.onChange,this,0,0),this.skew=new n.ObservablePoint(this.updateSkew,this,0,0),this._rotation=0,this._sr=Math.sin(0),this._cr=Math.cos(0),this._cy=Math.cos(0),this._sy=Math.sin(0),this._nsx=Math.sin(0),this._cx=Math.cos(0),this._localID=0,this._currentLocalID=0}var n=t("../math"),s=t("./TransformBase");i.prototype=Object.create(s.prototype),i.prototype.constructor=i,i.prototype.onChange=function(){this._localID++},i.prototype.updateSkew=function(){this._cy=Math.cos(this.skew._y),this._sy=Math.sin(this.skew._y),this._nsx=Math.sin(this.skew._x),this._cx=Math.cos(this.skew._x),this._localID++},i.prototype.updateLocalTransform=function(){var t=this.localTransform;if(this._localID!==this._currentLocalID){var e,r,i,n;e=this._cr*this.scale._x,r=this._sr*this.scale._x,i=-this._sr*this.scale._y,n=this._cr*this.scale._y,t.a=this._cy*e+this._sy*i,t.b=this._cy*r+this._sy*n,t.c=this._nsx*e+this._cx*i,t.d=this._nsx*r+this._cx*n,t.tx=this.position._x-(this.pivot._x*t.a+this.pivot._y*t.c),t.ty=this.position._y-(this.pivot._x*t.b+this.pivot._y*t.d),this._currentLocalID=this._localID,this._parentID=-1}},i.prototype.updateTransform=function(t){var e=t.worldTransform,r=this.worldTransform,i=this.localTransform;if(this._localID!==this._currentLocalID){var n,s,o,a;n=this._cr*this.scale._x,s=this._sr*this.scale._x,o=-this._sr*this.scale._y,a=this._cr*this.scale._y,i.a=this._cy*n+this._sy*o,i.b=this._cy*s+this._sy*a,i.c=this._nsx*n+this._cx*o,i.d=this._nsx*s+this._cx*a,i.tx=this.position._x-(this.pivot._x*i.a+this.pivot._y*i.c),i.ty=this.position._y-(this.pivot._x*i.b+this.pivot._y*i.d),this._currentLocalID=this._localID,this._parentID=-1}this._parentID!==t._worldID&&(r.a=i.a*e.a+i.b*e.c,r.b=i.a*e.b+i.b*e.d,r.c=i.c*e.a+i.d*e.c,r.d=i.c*e.b+i.d*e.d,r.tx=i.tx*e.a+i.ty*e.c+e.tx,r.ty=i.tx*e.b+i.ty*e.d+e.ty,this._parentID=t._worldID,this._worldID++)},i.prototype.setFromMatrix=function(t){t.decompose(this),this._localID++},Object.defineProperties(i.prototype,{rotation:{get:function(){return this._rotation},set:function(t){this._rotation=t,this._sr=Math.sin(t),this._cr=Math.cos(t),this._localID++}}}),e.exports=i},{"../math":67,"./TransformBase":48}],50:[function(t,e,r){function i(){s.call(this),this.fillAlpha=1,this.lineWidth=0,this.lineColor=0,this.graphicsData=[],this.tint=16777215,this._prevTint=16777215,this.blendMode=c.BLEND_MODES.NORMAL,this.currentPath=null,this._webGL={},this.isMask=!1,this.boundsPadding=0,this._localBounds=new p,this.dirty=0,this.fastRectDirty=-1,this.clearDirty=0,this.boundsDirty=-1,this.cachedSpriteDirty=!1,this._spriteRect=null,this._fastRect=!1}var n,s=t("../display/Container"),o=t("../textures/RenderTexture"),a=t("../textures/Texture"),h=t("./GraphicsData"),u=t("../sprites/Sprite"),l=t("../math"),c=t("../const"),d=t("../utils"),p=t("../display/Bounds"),f=t("./utils/bezierCurveTo"),v=t("../renderers/canvas/CanvasRenderer"),g=new l.Matrix,y=new l.Point,x=new Float32Array(4),m=new Float32Array(4);i._SPRITE_TEXTURE=null,i.prototype=Object.create(s.prototype),i.prototype.constructor=i,e.exports=i,i.prototype.clone=function(){var t=new i;t.renderable=this.renderable,t.fillAlpha=this.fillAlpha,t.lineWidth=this.lineWidth,t.lineColor=this.lineColor,t.tint=this.tint,t.blendMode=this.blendMode,t.isMask=this.isMask,t.boundsPadding=this.boundsPadding,t.dirty=0,t.cachedSpriteDirty=this.cachedSpriteDirty;for(var e=0;ec*h)}return this.dirty++,this},i.prototype.arc=function(t,e,r,i,n,s){if(s=s||!1,i===n)return this;!s&&n<=i?n+=2*Math.PI:s&&i<=n&&(i+=2*Math.PI);var o=s?(i-n)*-1:n-i,a=40*Math.ceil(Math.abs(o)/(2*Math.PI));if(0===o)return this;var h=t+Math.cos(i)*r,u=e+Math.sin(i)*r;this.currentPath?this.currentPath.shape.points.push(h,u):this.moveTo(h,u);for(var l=this.currentPath.shape.points,c=o/(2*a),d=2*c,p=Math.cos(c),f=Math.sin(c),v=a-1,g=v%1/v,y=0;y<=v;y++){var x=y+g*y,m=c+i+d*x,_=Math.cos(m),b=-Math.sin(m);l.push((p*_+f*b)*r+t,(p*-b+f*_)*r+e)}return this.dirty++,this},i.prototype.beginFill=function(t,e){return this.filling=!0,this.fillColor=t||0,this.fillAlpha=void 0===e?1:e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},i.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},i.prototype.drawRect=function(t,e,r,i){return this.drawShape(new l.Rectangle(t,e,r,i)),this},i.prototype.drawRoundedRect=function(t,e,r,i,n){return this.drawShape(new l.RoundedRectangle(t,e,r,i,n)),this},i.prototype.drawCircle=function(t,e,r){return this.drawShape(new l.Circle(t,e,r)),this},i.prototype.drawEllipse=function(t,e,r,i){return this.drawShape(new l.Ellipse(t,e,r,i)),this},i.prototype.drawPolygon=function(t){var e=t,r=!0;if(e instanceof l.Polygon&&(r=e.closed,e=e.points),!Array.isArray(e)){e=new Array(arguments.length);for(var i=0;ie?o+h:e,r=ai?a+u:i;else if(p===c.SHAPES.CIRC)o=n.x,a=n.y,h=n.radius+f/2,u=n.radius+f/2,t=o-he?o+h:e,r=a-ui?a+u:i;else if(p===c.SHAPES.ELIP)o=n.x,a=n.y,h=n.width+f/2,u=n.height+f/2,t=o-he?o+h:e,r=a-ui?a+u:i;else{s=n.points;for(var v=0;ve?o+f:e,r=a-fi?a+f:i}}else t=0,e=0,r=0,i=0;var g=this.boundsPadding;this._localBounds.minX=t-g,this._localBounds.maxX=e+2*g,this._localBounds.minY=r-g,this._localBounds.maxY=i+2*g},i.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null;var e=new h(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===c.SHAPES.POLY&&(e.shape.closed=e.shape.closed||this.filling,this.currentPath=e),this.dirty++,e},i.prototype.generateCanvasTexture=function(t,e){e=e||1;var r=this.getLocalBounds(),i=new o.create(r.width*e,r.height*e);n||(n=new v),g.tx=-r.x,g.ty=-r.y,n.render(this,i,!1,g);var s=a.fromCanvas(i.baseTexture._canvasRenderTarget.canvas,t);return s.baseTexture.resolution=e,s},i.prototype.closePath=function(){var t=this.currentPath;return t&&t.shape&&t.shape.close(),this},i.prototype.addHole=function(){var t=this.graphicsData.pop();return this.currentPath=this.graphicsData[this.graphicsData.length-1],this.currentPath.addHole(t.shape),this.currentPath=null,this},i.prototype.destroy=function(){s.prototype.destroy.apply(this,arguments);for(var t=0;tO?O:A,r.beginPath(),r.moveTo(S,C+A),r.lineTo(S,C+M-A),r.quadraticCurveTo(S,C+M,S+A,C+M),r.lineTo(S+R-A,C+M),r.quadraticCurveTo(S+R,C+M,S+R,C+M-A),r.lineTo(S+R,C+A),r.quadraticCurveTo(S+R,C,S+R-A,C),r.lineTo(S+A,C),r.quadraticCurveTo(S,C,S,C+A),r.closePath(),(h.fillColor||0===h.fillColor)&&(r.globalAlpha=h.fillAlpha*i,r.fillStyle="#"+("00000"+(0|l).toString(16)).substr(-6),r.fill()),h.lineWidth&&(r.globalAlpha=h.lineAlpha*i,r.strokeStyle="#"+("00000"+(0|c).toString(16)).substr(-6),r.stroke())}}},i.prototype.updateGraphicsTint=function(t){t._prevTint=t.tint;for(var e=(t.tint>>16&255)/255,r=(t.tint>>8&255)/255,i=(255&t.tint)/255,n=0;n>16&255)/255*e*255<<16)+((o>>8&255)/255*r*255<<8)+(255&o)/255*i*255,s._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*r*255<<8)+(255&a)/255*i*255}},i.prototype.renderPolygon=function(t,e,r){r.moveTo(t[0],t[1]);for(var i=1;i32e4)&&(r=this.graphicsDataPool.pop()||new h(this.renderer.gl,this.primitiveShader,this.renderer.state.attribsState),r.reset(e),t.data.push(r)),r.dirty=!0,r}},{"../../const":43,"../../renderers/webgl/WebGLRenderer":81,"../../renderers/webgl/utils/ObjectRenderer":91,"../../utils":116,"./WebGLGraphicsData":55,"./shaders/PrimitiveShader":56,"./utils/buildCircle":57,"./utils/buildPoly":59,"./utils/buildRectangle":60,"./utils/buildRoundedRectangle":61}],55:[function(t,e,r){function i(t,e,r){this.gl=t,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=n.GLBuffer.createVertexBuffer(t),this.indexBuffer=n.GLBuffer.createIndexBuffer(t),this.dirty=!0,this.glPoints=null,this.glIndices=null,this.shader=e,this.vao=new n.VertexArrayObject(t,r).addIndex(this.indexBuffer).addAttribute(this.buffer,e.attributes.aVertexPosition,t.FLOAT,!1,24,0).addAttribute(this.buffer,e.attributes.aColor,t.FLOAT,!1,24,8)}var n=t("pixi-gl-core");i.prototype.constructor=i,e.exports=i,i.prototype.reset=function(){this.points.length=0,this.indices.length=0},i.prototype.upload=function(){this.glPoints=new Float32Array(this.points),this.buffer.upload(this.glPoints),this.glIndices=new Uint16Array(this.indices),this.indexBuffer.upload(this.glIndices),this.dirty=!1},i.prototype.destroy=function(){this.color=null,this.points=null,this.indices=null,this.vao.destroy(),this.buffer.destroy(),this.indexBuffer.destroy(),this.gl=null,this.buffer=null,this.indexBuffer=null,this.glPoints=null,this.glIndices=null}},{"pixi-gl-core":12}],56:[function(t,e,r){function i(t){n.call(this,t,["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","uniform float alpha;","uniform vec3 tint;","varying vec4 vColor;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"].join("\n"),["varying vec4 vColor;","void main(void){"," gl_FragColor = vColor;","}"].join("\n"))}var n=t("../../../Shader");i.prototype=Object.create(n.prototype),i.prototype.constructor=i,e.exports=i},{"../../../Shader":42}],57:[function(t,e,r){var i=t("./buildLine"),n=t("../../../const"),s=t("../../../utils"),o=function(t,e){var r,o,a=t.shape,h=a.x,u=a.y;t.type===n.SHAPES.CIRC?(r=a.radius,o=a.radius):(r=a.width,o=a.height);var l=Math.floor(30*Math.sqrt(a.radius))||Math.floor(15*Math.sqrt(a.width+a.height)),c=2*Math.PI/l,d=0;if(t.fill){var p=s.hex2rgb(t.fillColor),f=t.fillAlpha,v=p[0]*f,g=p[1]*f,y=p[2]*f,x=e.points,m=e.indices,_=x.length/6;for(m.push(_),d=0;d19600?(T=x-_,E=m-b,P=Math.sqrt(T*T+E*E),T/=P,E/=P,T*=U,E*=U,I.push(f-T,v-E),I.push(W,G,X,j),I.push(f+T,v+E),I.push(W,G,X,j),I.push(f-T,v-E),I.push(W,G,X,j),B++):(I.push(l,c),I.push(W,G,X,j),I.push(f-(l-f),v-(c-v)),I.push(W,G,X,j)));for(d=s[2*(F-2)],p=s[2*(F-2)+1],f=s[2*(F-1)],v=s[2*(F-1)+1],x=-(p-v),m=d-f,P=Math.sqrt(x*x+m*m),x/=P,m/=P,x*=U,m*=U,I.push(f-x,v-m),I.push(W,G,X,j),I.push(f+x,v+m),I.push(W,G,X,j),L.push(N),r=0;r=6){for(var o=[],a=t.holes,h=0;h0&&i(t,e)};e.exports=o},{"../../../utils":116,"./buildLine":58,earcut:2}],60:[function(t,e,r){var i=t("./buildLine"),n=t("../../../utils"),s=function(t,e){var r=t.shape,s=r.x,o=r.y,a=r.width,h=r.height;if(t.fill){var u=n.hex2rgb(t.fillColor),l=t.fillAlpha,c=u[0]*l,d=u[1]*l,p=u[2]*l,f=e.points,v=e.indices,g=f.length/6;f.push(s,o),f.push(c,d,p,l),f.push(s+a,o),f.push(c,d,p,l),f.push(s,o+h),f.push(c,d,p,l),f.push(s+a,o+h),f.push(c,d,p,l),v.push(g,g,g+1,g+2,g+3,g+3)}if(t.lineWidth){var y=t.points;t.points=[s,o,s+a,o,s+a,o+h,s,o+h,s,o],i(t,e),t.points=y}};e.exports=s},{"../../../utils":116,"./buildLine":58}],61:[function(t,e,r){var i=t("earcut"),n=t("./buildLine"),s=t("../../../utils"),o=function(t,e){var r=t.shape,o=r.x,h=r.y,u=r.width,l=r.height,c=r.radius,d=[];if(d.push(o,h+c),a(o,h+l-c,o,h+l,o+c,h+l,d),a(o+u-c,h+l,o+u,h+l,o+u,h+l-c,d),a(o+u,h+c,o+u,h,o+u-c,h,d),a(o+c,h,o,h,o,h+c+1e-10,d),t.fill){var p=s.hex2rgb(t.fillColor),f=t.fillAlpha,v=p[0]*f,g=p[1]*f,y=p[2]*f,x=e.points,m=e.indices,_=x.length/6,b=i(d,null,2),T=0;for(T=0;T0?1:0}function n(){for(var t=0;t<16;t++){var e=[];c.push(e);for(var r=0;r<16;r++)for(var n=i(s[t]*s[r]+a[t]*o[r]),d=i(o[t]*s[r]+h[t]*o[r]),p=i(s[t]*a[r]+a[t]*h[r]),f=i(o[t]*a[r]+h[t]*h[r]),v=0;v<16;v++)if(s[v]===n&&o[v]===d&&a[v]===p&&h[v]===f){e.push(v);break}}for(t=0;t<16;t++){var g=new l;g.set(s[t],o[t],a[t],h[t],0,0),u.push(g)}}var s=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],o=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],a=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],h=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],u=[],l=t("./Matrix"),c=[];n();var d={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MIRROR_HORIZONTAL:12,uX:function(t){return s[t]},uY:function(t){return o[t]},vX:function(t){return a[t]},vY:function(t){return h[t]},inv:function(t){return 8&t?15&t:7&-t},add:function(t,e){return c[t][e]},sub:function(t,e){return c[t][d.inv(e)]},rotate180:function(t){return 4^t},isSwapWidthHeight:function(t){return 2===(3&t)},byDirection:function(t,e){return 2*Math.abs(t)<=Math.abs(e)?e>=0?d.S:d.N:2*Math.abs(e)<=Math.abs(t)?t>0?d.E:d.W:e>0?t>0?d.SE:d.SW:t>0?d.NE:d.NW},matrixAppendRotationInv:function(t,e,r,i){var n=u[d.inv(e)];r=r||0,i=i||0,n.tx=r,n.ty=i,t.append(n)}};e.exports=d},{"./Matrix":64}],64:[function(t,e,r){function i(){this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this.array=null}var n=t("./Point");i.prototype.constructor=i,e.exports=i,i.prototype.fromArray=function(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]},i.prototype.set=function(t,e,r,i,n,s){return this.a=t,this.b=e,this.c=r,this.d=i,this.tx=n,this.ty=s,this},i.prototype.toArray=function(t,e){this.array||(this.array=new Float32Array(9));var r=e||this.array;return t?(r[0]=this.a,r[1]=this.b,r[2]=0,r[3]=this.c,r[4]=this.d,r[5]=0,r[6]=this.tx,r[7]=this.ty,r[8]=1):(r[0]=this.a,r[1]=this.c,r[2]=this.tx,r[3]=this.b,r[4]=this.d,r[5]=this.ty,r[6]=0,r[7]=0,r[8]=1),r},i.prototype.apply=function(t,e){e=e||new n;var r=t.x,i=t.y;return e.x=this.a*r+this.c*i+this.tx,e.y=this.b*r+this.d*i+this.ty,e},i.prototype.applyInverse=function(t,e){e=e||new n;var r=1/(this.a*this.d+this.c*-this.b),i=t.x,s=t.y;return e.x=this.d*r*i+-this.c*r*s+(this.ty*this.c-this.tx*this.d)*r,e.y=this.a*r*s+-this.b*r*i+(-this.ty*this.a+this.tx*this.b)*r,e},i.prototype.translate=function(t,e){return this.tx+=t,this.ty+=e,this},i.prototype.scale=function(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this},i.prototype.rotate=function(t){var e=Math.cos(t),r=Math.sin(t),i=this.a,n=this.c,s=this.tx;return this.a=i*e-this.b*r,this.b=i*r+this.b*e,this.c=n*e-this.d*r,this.d=n*r+this.d*e,this.tx=s*e-this.ty*r,this.ty=s*r+this.ty*e,this},i.prototype.append=function(t){var e=this.a,r=this.b,i=this.c,n=this.d;return this.a=t.a*e+t.b*i,this.b=t.a*r+t.b*n,this.c=t.c*e+t.d*i,this.d=t.c*r+t.d*n,this.tx=t.tx*e+t.ty*i+this.tx,this.ty=t.tx*r+t.ty*n+this.ty,this},i.prototype.setTransform=function(t,e,r,i,n,s,o,a,h){var u,l,c,d,p,f,v,g,y,x;return p=Math.sin(o),f=Math.cos(o),v=Math.cos(h),g=Math.sin(h),y=-Math.sin(a),x=Math.cos(a),u=f*n,l=p*n,c=-p*s,d=f*s,this.a=v*u+g*c,this.b=v*l+g*d,this.c=y*u+x*c,this.d=y*l+x*d,this.tx=t+(r*u+i*c),this.ty=e+(r*l+i*d),this},i.prototype.prepend=function(t){var e=this.tx;if(1!==t.a||0!==t.b||0!==t.c||1!==t.d){var r=this.a,i=this.c;this.a=r*t.a+this.b*t.c,this.b=r*t.b+this.b*t.d,this.c=i*t.a+this.d*t.c,this.d=i*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this},i.prototype.decompose=function(t){var e=this.a,r=this.b,i=this.c,n=this.d,s=Math.atan2(-i,n),o=Math.atan2(r,e),a=Math.abs(1-s/o);return a<1e-5?(t.rotation=o,e<0&&n>=0&&(t.rotation+=t.rotation<=0?Math.PI:-Math.PI),t.skew.x=t.skew.y=0):(t.skew.x=s,t.skew.y=o),t.scale.x=Math.sqrt(e*e+r*r),t.scale.y=Math.sqrt(i*i+n*n),t.position.x=this.tx,t.position.y=this.ty,t},i.prototype.invert=function(){var t=this.a,e=this.b,r=this.c,i=this.d,n=this.tx,s=t*i-e*r;return this.a=i/s,this.b=-e/s,this.c=-r/s,this.d=t/s,this.tx=(r*this.ty-i*n)/s,this.ty=-(t*this.ty-e*n)/s,this},i.prototype.identity=function(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this},i.prototype.clone=function(){var t=new i;return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t},i.prototype.copy=function(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t},i.IDENTITY=new i,i.TEMP_MATRIX=new i},{"./Point":66}],65:[function(t,e,r){function i(t,e,r,i){this._x=r||0,this._y=i||0,this.cb=t,this.scope=e}i.prototype.constructor=i,e.exports=i,Object.defineProperties(i.prototype,{x:{get:function(){return this._x},set:function(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}},y:{get:function(){return this._y},set:function(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}}),i.prototype.set=function(t,e){var r=t||0,i=e||(0!==e?r:0);this._x===r&&this._y===i||(this._x=r,this._y=i,this.cb.call(this.scope))},i.prototype.copy=function(t){this._x===t.x&&this._y===t.y||(this._x=t.x,this._y=t.y,this.cb.call(this.scope))}},{}],66:[function(t,e,r){function i(t,e){this.x=t||0,this.y=e||0}i.prototype.constructor=i,e.exports=i,i.prototype.clone=function(){return new i(this.x,this.y)},i.prototype.copy=function(t){this.set(t.x,t.y)},i.prototype.equals=function(t){return t.x===this.x&&t.y===this.y},i.prototype.set=function(t,e){this.x=t||0,this.y=e||(0!==e?this.x:0)}},{}],67:[function(t,e,r){e.exports={Point:t("./Point"),ObservablePoint:t("./ObservablePoint"),Matrix:t("./Matrix"),GroupD8:t("./GroupD8"),Circle:t("./shapes/Circle"),Ellipse:t("./shapes/Ellipse"),Polygon:t("./shapes/Polygon"),Rectangle:t("./shapes/Rectangle"),RoundedRectangle:t("./shapes/RoundedRectangle")}},{"./GroupD8":63,"./Matrix":64,"./ObservablePoint":65,"./Point":66,"./shapes/Circle":68,"./shapes/Ellipse":69,"./shapes/Polygon":70,"./shapes/Rectangle":71,"./shapes/RoundedRectangle":72}],68:[function(t,e,r){function i(t,e,r){this.x=t||0,this.y=e||0,this.radius=r||0,this.type=s.SHAPES.CIRC}var n=t("./Rectangle"),s=t("../../const");i.prototype.constructor=i,e.exports=i,i.prototype.clone=function(){return new i(this.x,this.y,this.radius)},i.prototype.contains=function(t,e){if(this.radius<=0)return!1;var r=this.x-t,i=this.y-e,n=this.radius*this.radius;return r*=r,i*=i,r+i<=n},i.prototype.getBounds=function(){return new n(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)}},{"../../const":43,"./Rectangle":71}],69:[function(t,e,r){function i(t,e,r,i){this.x=t||0,this.y=e||0,this.width=r||0,this.height=i||0,this.type=s.SHAPES.ELIP}var n=t("./Rectangle"),s=t("../../const");i.prototype.constructor=i,e.exports=i,i.prototype.clone=function(){return new i(this.x,this.y,this.width,this.height)},i.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;var r=(t-this.x)/this.width,i=(e-this.y)/this.height;return r*=r,i*=i,r+i<=1},i.prototype.getBounds=function(){return new n(this.x-this.width,this.y-this.height,this.width,this.height)}},{"../../const":43,"./Rectangle":71}],70:[function(t,e,r){function i(t){var e=t;if(!Array.isArray(e)){e=new Array(arguments.length);for(var r=0;re!=u>e&&t<(h-o)*(e-a)/(u-a)+o;l&&(r=!r)}return r}},{"../../const":43,"../Point":66}],71:[function(t,e,r){function i(t,e,r,i){this.x=t||0,this.y=e||0,this.width=r||0,this.height=i||0,this.type=n.SHAPES.RECT}var n=t("../../const");i.prototype.constructor=i,e.exports=i,Object.defineProperties(i.prototype,{left:{get:function(){return this.x}},right:{get:function(){return this.x+this.width}},top:{get:function(){return this.y}},bottom:{get:function(){return this.y+this.height}}}),i.EMPTY=new i(0,0,0,0),i.prototype.clone=function(){return new i(this.x,this.y,this.width,this.height)},i.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this},i.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t=this.y&&et.x+t.width&&(this.width=t.width-this.x,this.width<0&&(this.width=0)),this.y+this.height>t.y+t.height&&(this.height=t.height-this.y,this.height<0&&(this.height=0))},i.prototype.enlarge=function(t){if(t!==i.EMPTY){var e=Math.min(this.x,t.x),r=Math.max(this.x+this.width,t.x+t.width),n=Math.min(this.y,t.y),s=Math.max(this.y+this.height,t.y+t.height);this.x=e,this.width=r-e,this.y=n,this.height=s-n}}},{"../../const":43}],72:[function(t,e,r){function i(t,e,r,i,s){this.x=t||0,this.y=e||0,this.width=r||0,this.height=i||0,this.radius=s||20,this.type=n.SHAPES.RREC}var n=t("../../const");i.prototype.constructor=i,e.exports=i,i.prototype.clone=function(){return new i(this.x,this.y,this.width,this.height,this.radius)},i.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height)}},{"../../const":43}],73:[function(t,e,r){function i(t,e,r,i){if(u.call(this),n.sayHello(t),i)for(var s in o.DEFAULT_RENDER_OPTIONS)"undefined"==typeof i[s]&&(i[s]=o.DEFAULT_RENDER_OPTIONS[s]);else i=o.DEFAULT_RENDER_OPTIONS;this.type=o.RENDERER_TYPE.UNKNOWN,this.width=e||800,this.height=r||600,this.view=i.view||document.createElement("canvas"),this.resolution=i.resolution,this.transparent=i.transparent,this.autoResize=i.autoResize||!1,this.blendModes=null,this.preserveDrawingBuffer=i.preserveDrawingBuffer,this.clearBeforeRender=i.clearBeforeRender,this.roundPixels=i.roundPixels,this._backgroundColor=0,this._backgroundColorRgba=[0,0,0,0],this._backgroundColorString="#000000",this.backgroundColor=i.backgroundColor||this._backgroundColor,this._tempDisplayObjectParent=new a,this._lastObjectRendered=this._tempDisplayObjectParent}var n=t("../utils"),s=t("../math"),o=t("../const"),a=t("../display/Container"),h=t("../textures/RenderTexture"),u=t("eventemitter3"),l=new s.Matrix;i.prototype=Object.create(u.prototype),i.prototype.constructor=i,e.exports=i,Object.defineProperties(i.prototype,{backgroundColor:{get:function(){return this._backgroundColor},set:function(t){this._backgroundColor=t,this._backgroundColorString=n.hex2string(t),n.hex2rgb(t,this._backgroundColorRgba)}}}),i.prototype.resize=function(t,e){this.width=t*this.resolution,this.height=e*this.resolution,this.view.width=this.width,this.view.height=this.height,this.autoResize&&(this.view.style.width=this.width/this.resolution+"px",this.view.style.height=this.height/this.resolution+"px")},i.prototype.generateTexture=function(t,e,r){var i=t.getLocalBounds(),n=h.create(0|i.width,0|i.height,e,r);return l.tx=-i.x,l.ty=-i.y,this.render(t,n,!1,l,!0),n},i.prototype.destroy=function(t){t&&this.view.parentNode&&this.view.parentNode.removeChild(this.view),this.type=o.RENDERER_TYPE.UNKNOWN,this.width=0,this.height=0,this.view=null,this.resolution=0,this.transparent=!1,this.autoResize=!1,this.blendModes=null,this.preserveDrawingBuffer=!1,this.clearBeforeRender=!1,this.roundPixels=!1,this._backgroundColor=0,this._backgroundColorRgba=null,this._backgroundColorString=null,this.backgroundColor=0,this._tempDisplayObjectParent=null,this._lastObjectRendered=null}},{"../const":43,"../display/Container":45,"../math":67,"../textures/RenderTexture":108,"../utils":116,eventemitter3:3}],74:[function(t,e,r){function i(t,e,r){r=r||{},n.call(this,"Canvas",t,e,r),this.type=u.RENDERER_TYPE.CANVAS,this.rootContext=this.view.getContext("2d",{alpha:this.transparent}),this.rootResolution=this.resolution,this.refresh=!0,this.maskManager=new s(this),this.smoothProperty="imageSmoothingEnabled",this.rootContext.imageSmoothingEnabled||(this.rootContext.webkitImageSmoothingEnabled?this.smoothProperty="webkitImageSmoothingEnabled":this.rootContext.mozImageSmoothingEnabled?this.smoothProperty="mozImageSmoothingEnabled":this.rootContext.oImageSmoothingEnabled?this.smoothProperty="oImageSmoothingEnabled":this.rootContext.msImageSmoothingEnabled&&(this.smoothProperty="msImageSmoothingEnabled")),this.initPlugins(),this.blendModes=a(),this._activeBlendMode=null,this.context=null,this.renderingToScreen=!1,this.resize(t,e)}var n=t("../SystemRenderer"),s=t("./utils/CanvasMaskManager"),o=t("./utils/CanvasRenderTarget"),a=t("./utils/mapCanvasBlendModesToPixi"),h=t("../../utils"),u=t("../../const");i.prototype=Object.create(n.prototype),i.prototype.constructor=i,e.exports=i,h.pluginTarget.mixin(i),i.prototype.render=function(t,e,r,i,n){if(this.view){this.renderingToScreen=!e,this.emit("prerender"),e?(e=e.baseTexture||e,e._canvasRenderTarget||(e._canvasRenderTarget=new o(e.width,e.height,e.resolution),e.source=e._canvasRenderTarget.canvas,e.valid=!0),this.context=e._canvasRenderTarget.context,this.resolution=e._canvasRenderTarget.resolution):(this.context=this.rootContext,this.resolution=this.rootResolution);var s=this.context;if(e||(this._lastObjectRendered=t),!n){var a=t.parent,h=this._tempDisplayObjectParent.transform.worldTransform;i?i.copy(h):h.identity(),t.parent=this._tempDisplayObjectParent,t.updateTransform(),t.parent=a}s.setTransform(1,0,0,1,0,0),s.globalAlpha=1,s.globalCompositeOperation=this.blendModes[u.BLEND_MODES.NORMAL],navigator.isCocoonJS&&this.view.screencanvas&&(s.fillStyle="black",s.clear()),(void 0!==r?r:this.clearBeforeRender)&&this.renderingToScreen&&(this.transparent?s.clearRect(0,0,this.width,this.height):(s.fillStyle=this._backgroundColorString,s.fillRect(0,0,this.width,this.height)));var l=this.context;this.context=s,t.renderCanvas(this),this.context=l,this.emit("postrender")}},i.prototype.setBlendMode=function(t){this._activeBlendMode!==t&&(this.context.globalCompositeOperation=this.blendModes[t])},i.prototype.destroy=function(t){this.destroyPlugins(),n.prototype.destroy.call(this,t),this.context=null,this.refresh=!0,this.maskManager.destroy(),this.maskManager=null,this.smoothProperty=null},i.prototype.resize=function(t,e){n.prototype.resize.call(this,t,e),this.smoothProperty&&(this.rootContext[this.smoothProperty]=u.SCALE_MODES.DEFAULT===u.SCALE_MODES.LINEAR)}},{"../../const":43,"../../utils":116,"../SystemRenderer":73,"./utils/CanvasMaskManager":75,"./utils/CanvasRenderTarget":76,"./utils/mapCanvasBlendModesToPixi":78}],75:[function(t,e,r){function i(t){this.renderer=t}var n=t("../../../const");i.prototype.constructor=i,e.exports=i,i.prototype.pushMask=function(t){var e=this.renderer;e.context.save();var r=t.alpha,i=t.transform.worldTransform,n=e.resolution;e.context.setTransform(i.a*n,i.b*n,i.c*n,i.d*n,i.tx*n,i.ty*n),t._texture||(this.renderGraphicsShape(t),e.context.clip()),t.worldAlpha=r},i.prototype.renderGraphicsShape=function(t){var e=this.renderer.context,r=t.graphicsData.length;if(0!==r){e.beginPath();for(var i=0;iS?S:w,e.moveTo(_,b+w),e.lineTo(_,b+E-w),e.quadraticCurveTo(_,b+E,_+w,b+E),e.lineTo(_+T-w,b+E),e.quadraticCurveTo(_+T,b+E,_+T,b+E-w),e.lineTo(_+T,b+w),e.quadraticCurveTo(_+T,b,_+T-w,b),e.lineTo(_+w,b),e.quadraticCurveTo(_,b,_,b+w),e.closePath()}}}},i.prototype.popMask=function(t){t.context.restore()},i.prototype.destroy=function(){}},{"../../../const":43}],76:[function(t,e,r){function i(t,e,r){this.canvas=document.createElement("canvas"),this.context=this.canvas.getContext("2d"),this.resolution=r||n.RESOLUTION,this.resize(t,e)}var n=t("../../../const");i.prototype.constructor=i,e.exports=i,Object.defineProperties(i.prototype,{width:{get:function(){return this.canvas.width},set:function(t){this.canvas.width=t}},height:{get:function(){return this.canvas.height},set:function(t){this.canvas.height=t}}}),i.prototype.clear=function(){this.context.setTransform(1,0,0,1,0,0),this.context.clearRect(0,0,this.canvas.width,this.canvas.height)},i.prototype.resize=function(t,e){this.canvas.width=t*this.resolution,this.canvas.height=e*this.resolution},i.prototype.destroy=function(){this.context=null,this.canvas=null}},{"../../../const":43}],77:[function(t,e,r){var i=function(t){var e=document.createElement("canvas");e.width=6,e.height=1;var r=e.getContext("2d");return r.fillStyle=t,r.fillRect(0,0,6,1),e},n=function(){if("undefined"==typeof document)return!1;var t=i("#ff00ff"),e=i("#ffff00"),r=document.createElement("canvas");r.width=6,r.height=1;var n=r.getContext("2d");n.globalCompositeOperation="multiply",n.drawImage(t,0,0),n.drawImage(e,2,0);var s=n.getImageData(2,0,1,1);if(!s)return!1;var o=s.data;return 255===o[0]&&0===o[1]&&0===o[2]};e.exports=n},{}],78:[function(t,e,r){function i(t){return t=t||[],s()?(t[n.BLEND_MODES.NORMAL]="source-over",t[n.BLEND_MODES.ADD]="lighter",t[n.BLEND_MODES.MULTIPLY]="multiply",t[n.BLEND_MODES.SCREEN]="screen",t[n.BLEND_MODES.OVERLAY]="overlay",t[n.BLEND_MODES.DARKEN]="darken",t[n.BLEND_MODES.LIGHTEN]="lighten",t[n.BLEND_MODES.COLOR_DODGE]="color-dodge",t[n.BLEND_MODES.COLOR_BURN]="color-burn",t[n.BLEND_MODES.HARD_LIGHT]="hard-light",t[n.BLEND_MODES.SOFT_LIGHT]="soft-light",t[n.BLEND_MODES.DIFFERENCE]="difference",t[n.BLEND_MODES.EXCLUSION]="exclusion",t[n.BLEND_MODES.HUE]="hue",t[n.BLEND_MODES.SATURATION]="saturate",t[n.BLEND_MODES.COLOR]="color",t[n.BLEND_MODES.LUMINOSITY]="luminosity"):(t[n.BLEND_MODES.NORMAL]="source-over",t[n.BLEND_MODES.ADD]="lighter",t[n.BLEND_MODES.MULTIPLY]="source-over",t[n.BLEND_MODES.SCREEN]="source-over",t[n.BLEND_MODES.OVERLAY]="source-over",t[n.BLEND_MODES.DARKEN]="source-over",t[n.BLEND_MODES.LIGHTEN]="source-over",t[n.BLEND_MODES.COLOR_DODGE]="source-over",t[n.BLEND_MODES.COLOR_BURN]="source-over",t[n.BLEND_MODES.HARD_LIGHT]="source-over",t[n.BLEND_MODES.SOFT_LIGHT]="source-over",t[n.BLEND_MODES.DIFFERENCE]="source-over",t[n.BLEND_MODES.EXCLUSION]="source-over",t[n.BLEND_MODES.HUE]="source-over",t[n.BLEND_MODES.SATURATION]="source-over",t[n.BLEND_MODES.COLOR]="source-over",t[n.BLEND_MODES.LUMINOSITY]="source-over"),t}var n=t("../../../const"),s=t("./canUseNewCanvasBlendModes");e.exports=i},{"../../../const":43,"./canUseNewCanvasBlendModes":77}],79:[function(t,e,r){function i(t){this.renderer=t,this.count=0,this.checkCount=0,this.maxIdle=3600,this.checkCountMax=600,this.mode=n.GC_MODES.DEFAULT}var n=t("../../const");i.prototype.constructor=i,e.exports=i,i.prototype.update=function(){this.count++,this.mode!==n.GC_MODES.MANUAL&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run()))},i.prototype.run=function(){var t,e,r=this.renderer.textureManager,i=r._managedTextures,n=!1;for(t=0;tthis.maxIdle&&(r.destroyTexture(s,!0),i[t]=null,n=!0)}if(n){for(e=0,t=0;t=0;r--)this.unload(t.children[r])}},{"../../const":43}],80:[function(t,e,r){var i=t("pixi-gl-core").GLTexture,n=t("../../const"),s=t("./utils/RenderTarget"),o=t("../../utils"),a=function(t){this.renderer=t,this.gl=t.gl,this._managedTextures=[]};a.prototype.bindTexture=function(){},a.prototype.getTexture=function(){},a.prototype.updateTexture=function(t){t=t.baseTexture||t;var e=!!t._glRenderTargets;if(t.hasLoaded){var r=t._glTextures[this.renderer.CONTEXT_UID];if(r)e?t._glRenderTargets[this.renderer.CONTEXT_UID].resize(t.width,t.height):r.upload(t.source);else{if(e){var o=new s(this.gl,t.width,t.height,t.scaleMode,t.resolution);o.resize(t.width,t.height),t._glRenderTargets[this.renderer.CONTEXT_UID]=o,r=o.texture}else r=new i(this.gl),r.premultiplyAlpha=!0,r.upload(t.source);t._glTextures[this.renderer.CONTEXT_UID]=r,t.on("update",this.updateTexture,this),t.on("dispose",this.destroyTexture,this),this._managedTextures.push(t),t.isPowerOfTwo?(t.mipmap&&r.enableMipmap(),t.wrapMode===n.WRAP_MODES.CLAMP?r.enableWrapClamp():t.wrapMode===n.WRAP_MODES.REPEAT?r.enableWrapRepeat():r.enableWrapMirrorRepeat()):r.enableWrapClamp(),t.scaleMode===n.SCALE_MODES.NEAREST?r.enableNearestScaling():r.enableLinearScaling()}return r}},a.prototype.destroyTexture=function(t,e){if(t=t.baseTexture||t,t.hasLoaded&&t._glTextures[this.renderer.CONTEXT_UID]&&(t._glTextures[this.renderer.CONTEXT_UID].destroy(),t.off("update",this.updateTexture,this),t.off("dispose",this.destroyTexture,this),delete t._glTextures[this.renderer.CONTEXT_UID],!e)){var r=this._managedTextures.indexOf(t);r!==-1&&o.removeItems(this._managedTextures,r,1)}},a.prototype.removeAll=function(){for(var t=0;t 0.5)"," {"," color = vec4(1.0, 0.0, 0.0, 1.0);"," }"," else"," {"," color = vec4(0.0, 1.0, 0.0, 1.0);"," }"," gl_FragColor = mix(sample, masky, 0.5);"," gl_FragColor *= sample.a;","}"].join("\n")},{"../../../const":43,"../../../utils":116,"./extractUniformsFromSrc":84}],84:[function(t,e,r){function i(t,e,r){var i=n(t,r),s=n(e,r);return Object.assign(i,s)}function n(t){for(var e,r=new RegExp("^(projectionMatrix|uSampler|filterArea)$"),i={},n=t.replace(/\s+/g," ").split(/\s*;\s*/),o=0;o-1){var h=a.split(" "),u=h[1],l=h[2],c=1;l.indexOf("[")>-1&&(e=l.split(/\[|\]/),l=e[0],c*=Number(e[1])),l.match(r)||(i[l]={value:s(u,c),name:l,type:u})}}return i}var s=t("pixi-gl-core").shader.defaultValue;e.exports=i},{"pixi-gl-core":12}],85:[function(t,e,r){var i=t("../../../math"),n=function(t,e,r){var i=t.identity();return i.translate(e.x/r.width,e.y/r.height),i.scale(r.width,r.height),i},s=function(t,e,r){var i=t.identity();i.translate(e.x/r.width,e.y/r.height);var n=r.width/e.width,s=r.height/e.height;return i.scale(n,s),i},o=function(t,e,r,n){var s=n.worldTransform.copy(i.Matrix.TEMP_MATRIX),o=n._texture.baseTexture,a=t.identity(),h=r.height/r.width;a.translate(e.x/r.width,e.y/r.height),a.scale(1,h);var u=r.width/o.width,l=r.height/o.height;return s.tx/=o.width*u,s.ty/=o.width*u,s.invert(),a.prepend(s),a.scale(1,1/h),a.scale(u,l),a.translate(n.anchor.x,n.anchor.y),a};e.exports={calculateScreenSpaceMatrix:n,calculateNormalizedScreenSpaceMatrix:s,calculateSpriteMatrix:o}},{"../../../math":67}],86:[function(t,e,r){function i(t){var e=new s.Matrix;n.call(this,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n","#define GLSLIFY 1\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n original *= (masky.r * masky.a * alpha * clip);\n gl_FragColor = original;\n}\n"),t.renderable=!1,this.maskSprite=t,this.maskMatrix=e}var n=t("../Filter"),s=t("../../../../math");i.prototype=Object.create(n.prototype),i.prototype.constructor=i,e.exports=i,i.prototype.apply=function(t,e,r){var i=this.maskSprite;this.uniforms.mask=i._texture,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,i),this.uniforms.alpha=i.worldAlpha,t.applyFilter(this,e,r)}},{"../../../../math":67,"../Filter":83}],87:[function(t,e,r){function i(t){n.call(this,t),this.gl=this.renderer.gl,this.quad=new o(this.gl,t.state.attribState),this.shaderCache={},this.pool={},this.filterData=null}var n=t("./WebGLManager"),s=t("../utils/RenderTarget"),o=t("../utils/Quad"),a=t("../../../math"),h=t("../../../Shader"),u=t("../filters/filterTransforms"),l=t("bit-twiddle"),c=function(){this.renderTarget=null,this.sourceFrame=new a.Rectangle,this.destinationFrame=new a.Rectangle,this.filters=[],this.target=null,this.resolution=1};i.prototype=Object.create(n.prototype),i.prototype.constructor=i,e.exports=i,i.prototype.pushFilter=function(t,e){var r=this.renderer,i=this.filterData;if(!i){i=this.renderer._activeRenderTarget.filterStack;var n=new c;n.sourceFrame=n.destinationFrame=this.renderer._activeRenderTarget.size,n.renderTarget=r._activeRenderTarget,this.renderer._activeRenderTarget.filterData=i={index:0,stack:[n]},this.filterData=i}var s=i.stack[++i.index];s||(s=i.stack[i.index]=new c);var o=e[0].resolution,a=e[0].padding,h=t.filterArea||t.getBounds(!0),u=s.sourceFrame,l=s.destinationFrame;u.x=(h.x*o|0)/o,u.y=(h.y*o|0)/o,u.width=(h.width*o|0)/o,u.height=(h.height*o|0)/o,i.stack[0].renderTarget.transform||u.fit(i.stack[0].destinationFrame),u.pad(a),l.width=u.width,l.height=u.height;var d=this.getPotRenderTarget(r.gl,u.width,u.height,o);s.target=t,s.filters=e,s.resolution=o,s.renderTarget=d,d.setFrame(l,u),r.bindRenderTarget(d),r.clear()},i.prototype.popFilter=function(){var t=this.filterData,e=t.stack[t.index-1],r=t.stack[t.index];this.quad.map(r.renderTarget.size,r.sourceFrame).upload();var i=r.filters;if(1===i.length)i[0].apply(this,r.renderTarget,e.renderTarget,!1),this.freePotRenderTarget(r.renderTarget);else{var n=r.renderTarget,s=this.getPotRenderTarget(this.renderer.gl,r.sourceFrame.width,r.sourceFrame.height,1);s.setFrame(r.destinationFrame,r.sourceFrame);for(var o=0;o0&&(e+="\nelse "),r>16)+(65280&t)+((255&t)<<16)}},texture:{get:function(){return this._texture},set:function(t){this._texture!==t&&(this._texture=t,this.cachedTint=16777215,this._textureID=-1,t&&(t.baseTexture.hasLoaded?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}}),i.prototype._onTextureUpdate=function(){this._textureID=-1,this._width&&(this.scale.x=a.sign(this.scale.x)*this._width/this.texture.orig.width),this._height&&(this.scale.y=a.sign(this.scale.y)*this._height/this.texture.orig.height)},i.prototype.onAnchorUpdate=function(){this._transformID=-1},i.prototype.calculateVertices=function(){if(this._transformID!==this.transform._worldID||this._textureID!==this._texture._updateID){this._transformID=this.transform._worldID,this._textureID=this._texture._updateID;var t,e,r,i,n=this._texture,s=this.transform.worldTransform,o=s.a,a=s.b,h=s.c,u=s.d,l=s.tx,c=s.ty,d=this.vertexData,p=n.trim,f=n.orig;p?(e=p.x-this.anchor._x*f.width,t=e+p.width,i=p.y-this.anchor._y*f.height,r=i+p.height):(t=f.width*(1-this.anchor._x),e=f.width*-this.anchor._x,r=f.height*(1-this.anchor._y),i=f.height*-this.anchor._y),d[0]=o*e+h*i+l,d[1]=u*i+a*e+c,d[2]=o*t+h*i+l,d[3]=u*i+a*t+c,d[4]=o*t+h*r+l,d[5]=u*r+a*t+c,d[6]=o*e+h*r+l,d[7]=u*r+a*e+c}},i.prototype.calculateTrimmedVertices=function(){this.vertexTrimmedData||(this.vertexTrimmedData=new Float32Array(8));var t,e,r,i,n=this._texture,s=this.vertexTrimmedData,o=n.orig,a=this.transform.worldTransform,h=a.a,u=a.b,l=a.c,c=a.d,d=a.tx,p=a.ty;t=o.width*(1-this.anchor._x),e=o.width*-this.anchor._x,r=o.height*(1-this.anchor._y),i=o.height*-this.anchor._y,s[0]=h*e+l*i+d,s[1]=c*i+u*e+p,s[2]=h*t+l*i+d,s[3]=c*i+u*t+p,s[4]=h*t+l*r+d,s[5]=c*r+u*t+p,s[6]=h*e+l*r+d,s[7]=c*r+u*e+p},i.prototype._renderWebGL=function(t){this.calculateVertices(),t.setObjectRenderer(t.plugins.sprite),t.plugins.sprite.render(this)},i.prototype._renderCanvas=function(t){t.plugins.sprite.render(this)},i.prototype._calculateBounds=function(){var t=this._texture.trim,e=this._texture.orig;!t||t.width===e.width&&t.height===e.height?(this.calculateVertices(),this._bounds.addQuad(this.vertexData)):(this.calculateTrimmedVertices(),this._bounds.addQuad(this.vertexTrimmedData))},i.prototype.getLocalBounds=function(t){return 0===this.children.length?(this._bounds.minX=-this._texture.orig.width*this.anchor._x,this._bounds.minY=-this._texture.orig.height*this.anchor._y,this._bounds.maxX=this._texture.orig.width,this._bounds.maxY=this._texture.orig.height,t||(this._localBoundsRect||(this._localBoundsRect=new n.Rectangle),t=this._localBoundsRect),this._bounds.getRectangle(t)):o.prototype.getLocalBounds.call(this,t)},i.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,u);var e,r=this._texture.orig.width,i=this._texture.orig.height,n=-r*this.anchor.x;return u.x>n&&u.xe&&u.y=this.size&&this.flush(),t.texture._uvs&&(this.sprites[this.currentIndex++]=t)},i.prototype.flush=function(){if(0!==this.currentIndex){var t,e,r,i,n,s,o,h=this.renderer.gl,u=d.nextPow2(this.currentIndex),l=d.log2(u),f=this.buffers[l],v=this.sprites,g=this.groups,y=f.float32View,x=f.uint32View,m=0,_=1,b=0,T=g[0],E=v[0].blendMode;T.textureCount=0,T.start=0,T.blend=E,p++;for(var w=0;w0&&(e+="\nelse "),r0?(this.context.shadowColor=e.dropShadowColor,this.context.shadowBlur=e.dropShadowBlur):this.context.fillStyle=e.dropShadowColor;var v=Math.cos(e.dropShadowAngle)*e.dropShadowDistance,g=Math.sin(e.dropShadowAngle)*e.dropShadowDistance;for(i=0;io;h--){for(u=0;ui)for(var u=o[a].split(""),l=0;ls?(e+="\n"+u[l],s=i-c):(0===l&&(e+=" "),e+=u[l],s-=c)}else{var d=h+this.context.measureText(" ").width;0===a||d>s?(a>0&&(e+="\n"),e+=o[a],s=i-h):(s-=d,e+=" "+o[a])}}n0&&e>0,this.width=t,this.height=e,this.realWidth=this.width*this.resolution,this.realHeight=this.height*this.resolution,this.valid&&this.emit("update",this))},i.prototype.destroy=function(){n.prototype.destroy.call(this,!0),this.renderer=null}},{"../const":43,"./BaseTexture":107}],107:[function(t,e,r){function i(t,e,r){o.call(this), +this.uid=n.uid(),this.touched=0,this.resolution=r||s.RESOLUTION,this.width=100,this.height=100,this.realWidth=100,this.realHeight=100,this.scaleMode=e||s.SCALE_MODES.DEFAULT,this.hasLoaded=!1,this.isLoading=!1,this.source=null,this.premultipliedAlpha=!0,this.imageUrl=null,this.isPowerOfTwo=!1,this.mipmap=s.MIPMAP_TEXTURES,this.wrapMode=s.WRAP_MODES.DEFAULT,this._glTextures=[],this._enabled=0,this._id=0,t&&this.loadSource(t)}var n=t("../utils"),s=t("../const"),o=t("eventemitter3"),a=t("../utils/determineCrossOrigin"),h=t("bit-twiddle");i.prototype=Object.create(o.prototype),i.prototype.constructor=i,e.exports=i,i.prototype.update=function(){this.realWidth=this.source.naturalWidth||this.source.videoWidth||this.source.width,this.realHeight=this.source.naturalHeight||this.source.videoHeight||this.source.height,this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=h.isPow2(this.realWidth)&&h.isPow2(this.realHeight),this.emit("update",this)},i.prototype.loadSource=function(t){var e=this.isLoading;if(this.hasLoaded=!1,this.isLoading=!1,e&&this.source&&(this.source.onload=null,this.source.onerror=null),this.source=t,(this.source.complete||this.source.getContext)&&this.source.width&&this.source.height)this._sourceLoaded();else if(!t.getContext){this.isLoading=!0;var r=this;t.onload=function(){t.onload=null,t.onerror=null,r.isLoading&&(r.isLoading=!1,r._sourceLoaded(),r.emit("loaded",r))},t.onerror=function(){t.onload=null,t.onerror=null,r.isLoading&&(r.isLoading=!1,r.emit("error",r))},t.complete&&t.src&&(this.isLoading=!1,t.onload=null,t.onerror=null,t.width&&t.height?(this._sourceLoaded(),e&&this.emit("loaded",this)):e&&this.emit("error",this))}},i.prototype._sourceLoaded=function(){this.hasLoaded=!0,this.update()},i.prototype.destroy=function(){this.imageUrl?(delete n.BaseTextureCache[this.imageUrl],delete n.TextureCache[this.imageUrl],this.imageUrl=null,navigator.isCocoonJS||(this.source.src="")):this.source&&this.source._pixiId&&delete n.BaseTextureCache[this.source._pixiId],this.source=null,this.dispose()},i.prototype.dispose=function(){this.emit("dispose",this)},i.prototype.updateSourceImage=function(t){this.source.src=t,this.loadSource(this.source)},i.fromImage=function(t,e,r){var s=n.BaseTextureCache[t];if(!s){var o=new Image;void 0===e&&0!==t.indexOf("data:")&&(o.crossOrigin=a(t)),s=new i(o,r),s.imageUrl=t,o.src=t,n.BaseTextureCache[t]=s,s.resolution=n.getResolutionOfUrl(t)}return s},i.fromCanvas=function(t,e){t._pixiId||(t._pixiId="canvas_"+n.uid());var r=n.BaseTextureCache[t._pixiId];return r||(r=new i(t,e),n.BaseTextureCache[t._pixiId]=r),r}},{"../const":43,"../utils":116,"../utils/determineCrossOrigin":115,"bit-twiddle":1,eventemitter3:3}],108:[function(t,e,r){function i(t,e){if(this.legacyRenderer=null,!(t instanceof n)){var r=arguments[1],i=arguments[2],o=arguments[3]||0,a=arguments[4]||1;console.warn("v4 RenderTexture now expects a new BaseRenderTexture. Please use RenderTexture.create("+r+", "+i+")"),this.legacyRenderer=arguments[0],e=null,t=new n(r,i,o,a)}s.call(this,t,e),this.valid=!0,this._updateUvs()}var n=t("./BaseRenderTexture"),s=t("./Texture");i.prototype=Object.create(s.prototype),i.prototype.constructor=i,e.exports=i,i.prototype.resize=function(t,e,r){this.valid=t>0&&e>0,this._frame.width=this.orig.width=t,this._frame.height=this.orig.height=e,r||this.baseTexture.resize(t,e),this._updateUvs()},i.create=function(t,e,r,s){return new i(new n(t,e,r,s))}},{"./BaseRenderTexture":106,"./Texture":109}],109:[function(t,e,r){function i(t,e,r,n,s){if(a.call(this),this.noFrame=!1,e||(this.noFrame=!0,e=new h.Rectangle(0,0,1,1)),t instanceof i&&(t=t.baseTexture),this.baseTexture=t,this._frame=e,this.trim=n,this.valid=!1,this.requiresUpdate=!1,this._uvs=null,this.orig=r||e,this._rotate=+(s||0),s===!0)this._rotate=2;else if(this._rotate%2!==0)throw"attempt to use diamond-shaped UVs. If you are sure, set rotation manually";t.hasLoaded?(this.noFrame&&(e=new h.Rectangle(0,0,t.width,t.height),t.on("update",this.onBaseTextureUpdated,this)),this.frame=e):t.once("loaded",this.onBaseTextureLoaded,this),this._updateID=0}var n=t("./BaseTexture"),s=t("./VideoBaseTexture"),o=t("./TextureUvs"),a=t("eventemitter3"),h=t("../math"),u=t("../utils");i.prototype=Object.create(a.prototype),i.prototype.constructor=i,e.exports=i,Object.defineProperties(i.prototype,{frame:{get:function(){return this._frame},set:function(t){if(this._frame=t,this.noFrame=!1,t.x+t.width>this.baseTexture.width||t.y+t.height>this.baseTexture.height)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);this.valid=t&&t.width&&t.height&&this.baseTexture.hasLoaded,this.trim||this.rotate||(this.orig=t),this.valid&&this._updateUvs()}},rotate:{get:function(){return this._rotate},set:function(t){this._rotate=t,this.valid&&this._updateUvs()}},width:{get:function(){return this.orig?this.orig.width:0}},height:{get:function(){return this.orig?this.orig.height:0}}}),i.prototype.update=function(){this.baseTexture.update()},i.prototype.onBaseTextureLoaded=function(t){this._updateID++,this.noFrame?this.frame=new h.Rectangle(0,0,t.width,t.height):this.frame=this._frame,this.baseTexture.on("update",this.onBaseTextureUpdated,this),this.emit("update",this)},i.prototype.onBaseTextureUpdated=function(t){this._updateID++,this._frame.width=t.width,this._frame.height=t.height,this.emit("update",this)},i.prototype.destroy=function(t){this.baseTexture&&(t&&(u.TextureCache[this.baseTexture.imageUrl]&&delete u.TextureCache[this.baseTexture.imageUrl],this.baseTexture.destroy()),this.baseTexture.off("update",this.onBaseTextureUpdated,this),this.baseTexture.off("loaded",this.onBaseTextureLoaded,this),this.baseTexture=null),this._frame=null,this._uvs=null,this.trim=null,this.orig=null,this.valid=!1,this.off("dispose",this.dispose,this),this.off("update",this.update,this)},i.prototype.clone=function(){return new i(this.baseTexture,this.frame,this.orig,this.trim,this.rotate)},i.prototype._updateUvs=function(){this._uvs||(this._uvs=new o),this._uvs.set(this._frame,this.baseTexture,this.rotate),this._updateID++},i.fromImage=function(t,e,r){var s=u.TextureCache[t];return s||(s=new i(n.fromImage(t,e,r)),u.TextureCache[t]=s),s},i.fromFrame=function(t){var e=u.TextureCache[t];if(!e)throw new Error('The frameId "'+t+'" does not exist in the texture cache');return e},i.fromCanvas=function(t,e){return new i(n.fromCanvas(t,e))},i.fromVideo=function(t,e){return"string"==typeof t?i.fromVideoUrl(t,e):new i(s.fromVideo(t,e))},i.fromVideoUrl=function(t,e){return new i(s.fromUrl(t,e))},i.from=function(t){if("string"==typeof t){var e=u.TextureCache[t];if(!e){var r=null!==t.match(/\.(mp4|webm|ogg|h264|avi|mov)$/);return r?i.fromVideoUrl(t):i.fromImage(t)}return e}return t instanceof HTMLCanvasElement?i.fromCanvas(t):t instanceof HTMLVideoElement?i.fromVideo(t):t instanceof n?new i(n):t},i.addTextureToCache=function(t,e){u.TextureCache[e]=t},i.removeTextureFromCache=function(t){var e=u.TextureCache[t];return delete u.TextureCache[t],delete u.BaseTextureCache[t],e},i.EMPTY=new i(new n),i.EMPTY.destroy=function(){},i.EMPTY.on=function(){},i.EMPTY.once=function(){},i.EMPTY.emit=function(){}},{"../math":67,"../utils":116,"./BaseTexture":107,"./TextureUvs":110,"./VideoBaseTexture":111,eventemitter3:3}],110:[function(t,e,r){function i(){this.x0=0,this.y0=0,this.x1=1,this.y1=0,this.x2=1,this.y2=1,this.x3=0,this.y3=1,this.uvsUint32=new Uint32Array(4)}e.exports=i;var n=t("../math/GroupD8");i.prototype.set=function(t,e,r){var i=e.width,s=e.height;if(r){var o=t.width/2/i,a=t.height/2/s,h=t.x/i+o,u=t.y/s+a;r=n.add(r,n.NW),this.x0=h+o*n.uX(r),this.y0=u+a*n.uY(r),r=n.add(r,2),this.x1=h+o*n.uX(r),this.y1=u+a*n.uY(r),r=n.add(r,2),this.x2=h+o*n.uX(r),this.y2=u+a*n.uY(r),r=n.add(r,2),this.x3=h+o*n.uX(r),this.y3=u+a*n.uY(r)}else this.x0=t.x/i,this.y0=t.y/s,this.x1=(t.x+t.width)/i,this.y1=t.y/s,this.x2=(t.x+t.width)/i,this.y2=(t.y+t.height)/s,this.x3=t.x/i,this.y3=(t.y+t.height)/s;this.uvsUint32[0]=(65535*this.y0&65535)<<16|65535*this.x0&65535,this.uvsUint32[1]=(65535*this.y1&65535)<<16|65535*this.x1&65535,this.uvsUint32[2]=(65535*this.y2&65535)<<16|65535*this.x2&65535,this.uvsUint32[3]=(65535*this.y3&65535)<<16|65535*this.x3&65535}},{"../math/GroupD8":63}],111:[function(t,e,r){function i(t,e){if(!t)throw new Error("No video source element specified.");(t.readyState===t.HAVE_ENOUGH_DATA||t.readyState===t.HAVE_FUTURE_DATA)&&t.width&&t.height&&(t.complete=!0),s.call(this,t,e),this.autoUpdate=!1,this._onUpdate=this._onUpdate.bind(this),this._onCanPlay=this._onCanPlay.bind(this),t.complete||(t.addEventListener("canplay",this._onCanPlay),t.addEventListener("canplaythrough",this._onCanPlay),t.addEventListener("play",this._onPlayStart.bind(this)),t.addEventListener("pause",this._onPlayStop.bind(this))),this.__loaded=!1}function n(t,e){e||(e="video/"+t.substr(t.lastIndexOf(".")+1));var r=document.createElement("source");return r.src=t,r.type=e,r}var s=t("./BaseTexture"),o=t("../utils");i.prototype=Object.create(s.prototype),i.prototype.constructor=i,e.exports=i,i.prototype._onUpdate=function(){this.autoUpdate&&(window.requestAnimationFrame(this._onUpdate),this.update())},i.prototype._onPlayStart=function(){this.hasLoaded||this._onCanPlay(),this.autoUpdate||(window.requestAnimationFrame(this._onUpdate),this.autoUpdate=!0)},i.prototype._onPlayStop=function(){this.autoUpdate=!1},i.prototype._onCanPlay=function(){this.hasLoaded=!0,this.source&&(this.source.removeEventListener("canplay",this._onCanPlay),this.source.removeEventListener("canplaythrough",this._onCanPlay),this.width=this.source.videoWidth,this.height=this.source.videoHeight,this.source.play(),this.__loaded||(this.__loaded=!0,this.emit("loaded",this)))},i.prototype.destroy=function(){this.source&&this.source._pixiId&&(delete o.BaseTextureCache[this.source._pixiId],delete this.source._pixiId),s.prototype.destroy.call(this)},i.fromVideo=function(t,e){t._pixiId||(t._pixiId="video_"+o.uid());var r=o.BaseTextureCache[t._pixiId];return r||(r=new i(t,e),o.BaseTextureCache[t._pixiId]=r),r},i.fromUrl=function(t,e){var r=document.createElement("video");if(Array.isArray(t))for(var s=0;sthis.lastTime?(e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),this.deltaTime=e*n.TARGET_FPMS*this.speed,this._emitter.emit(o,this.deltaTime)):this.deltaTime=this.elapsedMS=0,this.lastTime=t},e.exports=i},{"../const":43,eventemitter3:3}],113:[function(t,e,r){var i=t("./Ticker"),n=new i;n.autoStart=!0,e.exports={shared:n,Ticker:i}},{"./Ticker":112}],114:[function(t,e,r){var i=function(t){for(var e=6*t,r=new Uint16Array(e),i=0,n=0;i>16&255)/255,e[1]=(t>>8&255)/255,e[2]=(255&t)/255,e},hex2string:function(t){return t=t.toString(16),t="000000".substr(0,6-t.length)+t,"#"+t},rgb2hex:function(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]},getResolutionOfUrl:function(t){var e=i.RETINA_PREFIX.exec(t);return e?parseFloat(e[1]):1},sayHello:function(t){if(!n._saidHello){if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var e=["\n %c %c %c Pixi.js "+i.VERSION+" - ✰ "+t+" ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n","background: #ff66a5; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff66a5; background: #030307; padding:5px 0;","background: #ff66a5; padding:5px 0;","background: #ffc3dc; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;"];window.console.log.apply(console,e)}else window.console&&window.console.log("Pixi.js "+i.VERSION+" - "+t+" - http://www.pixijs.com/");n._saidHello=!0}},isWebGLSupported:function(){var t={stencil:!0,failIfMajorPerformanceCaveat:!0};try{if(!window.WebGLRenderingContext)return!1;var e=document.createElement("canvas"),r=e.getContext("webgl",t)||e.getContext("experimental-webgl",t),i=!(!r||!r.getContextAttributes().stencil);if(r){var n=r.getExtension("WEBGL_lose_context");n&&n.loseContext()}return r=null,i}catch(t){return!1}},sign:function(t){return t?t<0?-1:1:0},removeItems:function(t,e,r){var i=t.length;if(!(e>=i||0===r)){r=e+r>i?i-e:r;for(var n=e,s=i-r;n1?this._fontStyle="italic":t.indexOf("oblique")>-1?this._fontStyle="oblique":this._fontStyle="normal",t.indexOf("small-caps")>-1?this._fontVariant="small-caps":this._fontVariant="normal";var e,r=t.split(" "),i=-1;for(this._fontSize=26,e=0;e-1&&i=0?t:16777215,this.dirty=!0}},align:{get:function(){return this._font.align},set:function(t){this._font.align=t||"left",this.dirty=!0}},anchor:{get:function(){return this._anchor},set:function(t){"number"==typeof t?this._anchor.set(t):this._anchor.copy(t)}},font:{get:function(){return this._font},set:function(t){t&&("string"==typeof t?(t=t.split(" "),this._font.name=1===t.length?t[0]:t.slice(1).join(" "),this._font.size=t.length>=2?parseInt(t[0],10):i.fonts[this._font.name].size):(this._font.name=t.name,this._font.size="number"==typeof t.size?t.size:parseInt(t.size,10)),this.dirty=!0)}},text:{get:function(){return this._text},set:function(t){t=t.toString()||" ",this._text!==t&&(this._text=t,this.dirty=!0)}}}),i.prototype.updateText=function(){for(var t=i.fonts[this._font.name],e=new n.Point,r=null,s=[],o=0,a=0,h=[],u=0,l=this._font.size/t.size,c=-1,d=0,p=0,f=0;f0&&e.x*l>this.maxWidth)n.utils.removeItems(s,c,f-c),f=c,c=-1,h.push(d),a=Math.max(a,d),u++,e.x=0,e.y+=t.lineHeight,r=null;else{var g=t.chars[v];g&&(r&&g.kerning[r]&&(e.x+=g.kerning[r]),s.push({texture:g.texture,line:u,charCode:v,position:new n.Point(e.x+g.xOffset,e.y+g.yOffset)}),o=e.x+(g.texture.width+g.xOffset),e.x+=g.xAdvance,p=Math.max(p,g.yOffset+g.texture.height),r=v)}}h.push(o),a=Math.max(a,o);var y=[];for(f=0;f<=u;f++){var x=0;"right"===this._font.align?x=a-h[f]:"center"===this._font.align&&(x=(a-h[f])/2),y.push(x)}var m=s.length,_=this.tint;for(f=0;f=this._durations[this.currentFrame];)r-=this._durations[this.currentFrame]*i,this._currentTime+=i;this._currentTime+=r/this._durations[this.currentFrame]}else this._currentTime+=e;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):(this._texture=this._textures[this.currentFrame],this._textureID=-1)},i.prototype.destroy=function(){this.stop(),n.Sprite.prototype.destroy.call(this)},i.fromFrames=function(t){for(var e=[],r=0;re?m:e,e=b>e?b:e,e=E>e?E:e,i=x,i=_>i?_:i,i=T>i?T:i,i=w>i?w:i;var S=this._bounds;return S.x=t,S.width=e-t,S.y=r,S.height=i-r,this._currentBounds=S,S},i.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,s);var e,r=this._width,i=this._height,n=-r*this.anchor.x;return s.x>n&&s.xe&&s.y=s&&(e=t-u-1),l=l.replace("%value%",r[e]),a+=l,a+="\n"}return o=o.replace("%blur%",a),o=o.replace("%size%",t)};e.exports=s},{}],135:[function(t,e,r){var i=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","uniform float strength;","uniform mat3 projectionMatrix;","varying vec2 vBlurTexCoords[%size%];","void main(void)","{","gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);","%blur%","}"].join("\n"),n=function(t,e){var r,n,s=Math.ceil(t/2),o=i,a="";r=e?"vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);":"vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);";for(var h=0;h=s&&(n=t-h-1),u=u.replace("%sampleIndex%",h-(s-1)+".0"),a+=u,a+="\n"}return o=o.replace("%blur%",a),o=o.replace("%size%",t)};e.exports=n},{}],136:[function(t,e,r){var i=function(t){for(var e=t.getParameter(t.MAX_VARYING_VECTORS),r=15;r>e;)r-=2;return r};e.exports=i},{}],137:[function(t,e,r){function i(){n.Filter.call(this,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","#define GLSLIFY 1\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\n\nvoid main(void)\n{\n\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n gl_FragColor.r = (m[0] * c.r);\n gl_FragColor.r += (m[1] * c.g);\n gl_FragColor.r += (m[2] * c.b);\n gl_FragColor.r += (m[3] * c.a);\n gl_FragColor.r += m[4] * c.a;\n\n gl_FragColor.g = (m[5] * c.r);\n gl_FragColor.g += (m[6] * c.g);\n gl_FragColor.g += (m[7] * c.b);\n gl_FragColor.g += (m[8] * c.a);\n gl_FragColor.g += m[9] * c.a;\n\n gl_FragColor.b = (m[10] * c.r);\n gl_FragColor.b += (m[11] * c.g);\n gl_FragColor.b += (m[12] * c.b);\n gl_FragColor.b += (m[13] * c.a);\n gl_FragColor.b += m[14] * c.a;\n\n gl_FragColor.a = (m[15] * c.r);\n gl_FragColor.a += (m[16] * c.g);\n gl_FragColor.a += (m[17] * c.b);\n gl_FragColor.a += (m[18] * c.a);\n gl_FragColor.a += m[19] * c.a;\n\n// gl_FragColor = vec4(m[0]);\n}\n"),this.uniforms.m=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0]}var n=t("../../core");i.prototype=Object.create(n.Filter.prototype),i.prototype.constructor=i,e.exports=i,i.prototype._loadMatrix=function(t,e){e=!!e;var r=t;e&&(this._multiply(r,this.uniforms.m,t),r=this._colorMatrix(r)),this.uniforms.m=r},i.prototype._multiply=function(t,e,r){return t[0]=e[0]*r[0]+e[1]*r[5]+e[2]*r[10]+e[3]*r[15],t[1]=e[0]*r[1]+e[1]*r[6]+e[2]*r[11]+e[3]*r[16],t[2]=e[0]*r[2]+e[1]*r[7]+e[2]*r[12]+e[3]*r[17],t[3]=e[0]*r[3]+e[1]*r[8]+e[2]*r[13]+e[3]*r[18],t[4]=e[0]*r[4]+e[1]*r[9]+e[2]*r[14]+e[3]*r[19],t[5]=e[5]*r[0]+e[6]*r[5]+e[7]*r[10]+e[8]*r[15],t[6]=e[5]*r[1]+e[6]*r[6]+e[7]*r[11]+e[8]*r[16],t[7]=e[5]*r[2]+e[6]*r[7]+e[7]*r[12]+e[8]*r[17],t[8]=e[5]*r[3]+e[6]*r[8]+e[7]*r[13]+e[8]*r[18],t[9]=e[5]*r[4]+e[6]*r[9]+e[7]*r[14]+e[8]*r[19],t[10]=e[10]*r[0]+e[11]*r[5]+e[12]*r[10]+e[13]*r[15],t[11]=e[10]*r[1]+e[11]*r[6]+e[12]*r[11]+e[13]*r[16],t[12]=e[10]*r[2]+e[11]*r[7]+e[12]*r[12]+e[13]*r[17],t[13]=e[10]*r[3]+e[11]*r[8]+e[12]*r[13]+e[13]*r[18],t[14]=e[10]*r[4]+e[11]*r[9]+e[12]*r[14]+e[13]*r[19],t[15]=e[15]*r[0]+e[16]*r[5]+e[17]*r[10]+e[18]*r[15],t[16]=e[15]*r[1]+e[16]*r[6]+e[17]*r[11]+e[18]*r[16],t[17]=e[15]*r[2]+e[16]*r[7]+e[17]*r[12]+e[18]*r[17],t[18]=e[15]*r[3]+e[16]*r[8]+e[17]*r[13]+e[18]*r[18],t[19]=e[15]*r[4]+e[16]*r[9]+e[17]*r[14]+e[18]*r[19],t},i.prototype._colorMatrix=function(t){var e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e},i.prototype.brightness=function(t,e){var r=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},i.prototype.greyscale=function(t,e){var r=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},i.prototype.grayscale=i.prototype.greyscale,i.prototype.blackAndWhite=function(t){var e=[.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.hue=function(t,e){t=(t||0)/180*Math.PI;var r=Math.cos(t),i=Math.sin(t),n=Math.sqrt,s=1/3,o=n(s),a=r+(1-r)*s,h=s*(1-r)-o*i,u=s*(1-r)+o*i,l=s*(1-r)+o*i,c=r+s*(1-r),d=s*(1-r)-o*i,p=s*(1-r)-o*i,f=s*(1-r)+o*i,v=r+s*(1-r),g=[a,h,u,0,0,l,c,d,0,0,p,f,v,0,0,0,0,0,1,0];this._loadMatrix(g,e)},i.prototype.contrast=function(t,e){var r=(t||0)+1,i=-128*(r-1),n=[r,0,0,0,i,0,r,0,0,i,0,0,r,0,i,0,0,0,1,0];this._loadMatrix(n,e)},i.prototype.saturate=function(t,e){var r=2*(t||0)/3+1,i=(r-1)*-.5,n=[r,i,i,0,0,i,r,i,0,0,i,i,r,0,0,0,0,0,1,0];this._loadMatrix(n,e)},i.prototype.desaturate=function(){this.saturate(-1)},i.prototype.negative=function(t){var e=[0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.sepia=function(t){var e=[.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.technicolor=function(t){var e=[1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.polaroid=function(t){var e=[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.toBGR=function(t){var e=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.kodachrome=function(t){var e=[1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.browni=function(t){var e=[.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.vintage=function(t){var e=[.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.colorTone=function(t,e,r,i,n){t=t||.2,e=e||.15,r=r||16770432,i=i||3375104;var s=(r>>16&255)/255,o=(r>>8&255)/255,a=(255&r)/255,h=(i>>16&255)/255,u=(i>>8&255)/255,l=(255&i)/255,c=[.3,.59,.11,0,0,s,o,a,t,0,h,u,l,e,0,s-h,o-u,a-l,0,0];this._loadMatrix(c,n)},i.prototype.night=function(t,e){t=t||.1;var r=[t*-2,-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},i.prototype.predator=function(t,e){var r=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(r,e)},i.prototype.lsd=function(t){var e=[2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0];this._loadMatrix(e,t)},i.prototype.reset=function(){var t=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(t,!1)},Object.defineProperties(i.prototype,{matrix:{get:function(){return this.uniforms.m},set:function(t){this.uniforms.m=t}}})},{"../../core":62}],138:[function(t,e,r){function i(t,e){var r=new n.Matrix;t.renderable=!1,n.Filter.call(this,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}","#define GLSLIFY 1\nvarying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n"),this.maskSprite=t,this.maskMatrix=r,this.uniforms.mapSampler=t.texture,this.uniforms.filterMatrix=r.toArray(!0),this.uniforms.scale={x:1,y:1},null!==e&&void 0!==e||(e=20),this.scale=new n.Point(e,e)}var n=t("../../core");i.prototype=Object.create(n.Filter.prototype),i.prototype.constructor=i,e.exports=i,i.prototype.apply=function(t,e,r){var i=1/r.destinationFrame.width*(r.size.width/e.size.width);this.uniforms.filterMatrix=t.calculateSpriteMatrix(this.maskMatrix,this.maskSprite),this.uniforms.scale.x=this.scale.x*i,this.uniforms.scale.y=this.scale.y*i,t.applyFilter(this,e,r)},Object.defineProperties(i.prototype,{map:{get:function(){return this.uniforms.mapSampler},set:function(t){this.uniforms.mapSampler=t}}})},{"../../core":62}],139:[function(t,e,r){function i(){n.Filter.call(this,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}",'#define GLSLIFY 1\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n \tvec2 fragCoord = vTextureCoord * filterArea.xy;\n\n \tvec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n \tgl_FragColor = color;\n}\n')}var n=t("../../core");i.prototype=Object.create(n.Filter.prototype),i.prototype.constructor=i,e.exports=i},{"../../core":62}],140:[function(t,e,r){e.exports={FXAAFilter:t("./fxaa/FXAAFilter"),NoiseFilter:t("./noise/NoiseFilter"),DisplacementFilter:t("./displacement/DisplacementFilter"),BlurFilter:t("./blur/BlurFilter"),BlurXFilter:t("./blur/BlurXFilter"),BlurYFilter:t("./blur/BlurYFilter"),ColorMatrixFilter:t("./colormatrix/ColorMatrixFilter"),VoidFilter:t("./void/VoidFilter")}},{"./blur/BlurFilter":131,"./blur/BlurXFilter":132,"./blur/BlurYFilter":133,"./colormatrix/ColorMatrixFilter":137,"./displacement/DisplacementFilter":138,"./fxaa/FXAAFilter":139,"./noise/NoiseFilter":141,"./void/VoidFilter":142}],141:[function(t,e,r){function i(){n.Filter.call(this,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","precision highp float;\n#define GLSLIFY 1\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float noise;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n float diff = (rand(gl_FragCoord.xy) - 0.5) * noise;\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n gl_FragColor = color;\n}\n"),this.noise=.5}var n=t("../../core");i.prototype=Object.create(n.Filter.prototype),i.prototype.constructor=i,e.exports=i,Object.defineProperties(i.prototype,{noise:{get:function(){return this.uniforms.noise},set:function(t){this.uniforms.noise=t}}})},{"../../core":62}],142:[function(t,e,r){function i(){n.Filter.call(this,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"),this.glShaderKey="void"}var n=t("../../core");i.prototype=Object.create(n.Filter.prototype),i.prototype.constructor=i,e.exports=i},{"../../core":62}],143:[function(t,e,r){function i(){this.global=new n.Point,this.target=null,this.originalEvent=null}var n=t("../core");i.prototype.constructor=i,e.exports=i,i.prototype.getLocalPosition=function(t,e,r){return t.worldTransform.applyInverse(r||this.global,e)}},{"../core":62}],144:[function(t,e,r){function i(t,e){o.call(this),e=e||{},this.renderer=t,this.autoPreventDefault=void 0===e.autoPreventDefault||e.autoPreventDefault,this.interactionFrequency=e.interactionFrequency||10,this.mouse=new s,this.mouse.global.set(-999999),this.eventData={stopped:!1,target:null,type:null,data:this.mouse,stopPropagation:function(){this.stopped=!0}},this.interactiveDataPool=[],this.interactionDOMElement=null,this.moveWhenInside=!1,this.eventsAdded=!1,this.onMouseUp=this.onMouseUp.bind(this),this.processMouseUp=this.processMouseUp.bind(this),this.onMouseDown=this.onMouseDown.bind(this),this.processMouseDown=this.processMouseDown.bind(this),this.onMouseMove=this.onMouseMove.bind(this),this.processMouseMove=this.processMouseMove.bind(this),this.onMouseOut=this.onMouseOut.bind(this),this.processMouseOverOut=this.processMouseOverOut.bind(this),this.onMouseOver=this.onMouseOver.bind(this),this.onTouchStart=this.onTouchStart.bind(this),this.processTouchStart=this.processTouchStart.bind(this),this.onTouchEnd=this.onTouchEnd.bind(this),this.processTouchEnd=this.processTouchEnd.bind(this),this.onTouchMove=this.onTouchMove.bind(this),this.processTouchMove=this.processTouchMove.bind(this),this.defaultCursorStyle="inherit",this.currentCursorStyle="inherit",this._tempPoint=new n.Point,this.resolution=1,this.setTargetElement(this.renderer.view,this.renderer.resolution)}var n=t("../core"),s=t("./InteractionData"),o=t("eventemitter3");Object.assign(n.DisplayObject.prototype,t("./interactiveTarget")),i.prototype=Object.create(o.prototype),i.prototype.constructor=i,e.exports=i,i.prototype.setTargetElement=function(t,e){this.removeEvents(),this.interactionDOMElement=t,this.resolution=e||1,this.addEvents()},i.prototype.addEvents=function(){this.interactionDOMElement&&(n.ticker.shared.add(this.update,this),window.navigator.msPointerEnabled&&(this.interactionDOMElement.style["-ms-content-zooming"]="none",this.interactionDOMElement.style["-ms-touch-action"]="none"),window.document.addEventListener("mousemove",this.onMouseMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onMouseDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onMouseOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onMouseOver,!0),this.interactionDOMElement.addEventListener("touchstart",this.onTouchStart,!0),this.interactionDOMElement.addEventListener("touchend",this.onTouchEnd,!0),this.interactionDOMElement.addEventListener("touchmove",this.onTouchMove,!0),window.addEventListener("mouseup",this.onMouseUp,!0),this.eventsAdded=!0)},i.prototype.removeEvents=function(){this.interactionDOMElement&&(n.ticker.shared.remove(this.update),window.navigator.msPointerEnabled&&(this.interactionDOMElement.style["-ms-content-zooming"]="",this.interactionDOMElement.style["-ms-touch-action"]=""),window.document.removeEventListener("mousemove",this.onMouseMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onMouseDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onMouseOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onMouseOver,!0),this.interactionDOMElement.removeEventListener("touchstart",this.onTouchStart,!0),this.interactionDOMElement.removeEventListener("touchend",this.onTouchEnd,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onTouchMove,!0),this.interactionDOMElement=null,window.removeEventListener("mouseup",this.onMouseUp,!0),this.eventsAdded=!1)},i.prototype.update=function(t){if(this._deltaTime+=t,!(this._deltaTime=0;h--){var u=a[h];if(this.processInteractive(t,u,r,i,o)){if(!u.parent)continue;s=!0,o=!1,i=!1}}return n&&(i&&!s&&(e.hitArea?(e.worldTransform.applyInverse(t,this._tempPoint),s=e.hitArea.contains(this._tempPoint.x,this._tempPoint.y)):e.containsPoint&&(s=e.containsPoint(t))),e.interactive&&r(e,s)),s},i.prototype.onMouseDown=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData.stopped=!1,this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.autoPreventDefault&&this.mouse.originalEvent.preventDefault(),this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseDown,!0);var e=2===t.button||3===t.which;this.emit(e?"rightdown":"mousedown",this.eventData)},i.prototype.processMouseDown=function(t,e){var r=this.mouse.originalEvent,i=2===r.button||3===r.which;e&&(t[i?"_isRightDown":"_isLeftDown"]=!0,this.dispatchEvent(t,i?"rightdown":"mousedown",this.eventData))},i.prototype.onMouseUp=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData.stopped=!1,this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseUp,!0);var e=2===t.button||3===t.which;this.emit(e?"rightup":"mouseup",this.eventData)},i.prototype.processMouseUp=function(t,e){var r=this.mouse.originalEvent,i=2===r.button||3===r.which,n=i?"_isRightDown":"_isLeftDown";e?(this.dispatchEvent(t,i?"rightup":"mouseup",this.eventData),t[n]&&(t[n]=!1,this.dispatchEvent(t,i?"rightclick":"click",this.eventData))):t[n]&&(t[n]=!1,this.dispatchEvent(t,i?"rightupoutside":"mouseupoutside",this.eventData))},i.prototype.onMouseMove=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData.stopped=!1,this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.didMove=!0,this.cursor=this.defaultCursorStyle,this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseMove,!0),this.emit("mousemove",this.eventData),this.currentCursorStyle!==this.cursor&&(this.currentCursorStyle=this.cursor,this.interactionDOMElement.style.cursor=this.cursor)},i.prototype.processMouseMove=function(t,e){this.processMouseOverOut(t,e),this.moveWhenInside&&!e||this.dispatchEvent(t,"mousemove",this.eventData)},i.prototype.onMouseOut=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData.stopped=!1,this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.interactionDOMElement.style.cursor=this.defaultCursorStyle,this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseOverOut,!1),this.emit("mouseout",this.eventData)},i.prototype.processMouseOverOut=function(t,e){e?(t._over||(t._over=!0,this.dispatchEvent(t,"mouseover",this.eventData)),t.buttonMode&&(this.cursor=t.defaultCursor)):t._over&&(t._over=!1,this.dispatchEvent(t,"mouseout",this.eventData))},i.prototype.onMouseOver=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData.stopped=!1,this.emit("mouseover",this.eventData)},i.prototype.onTouchStart=function(t){this.autoPreventDefault&&t.preventDefault();for(var e=t.changedTouches,r=e.length,i=0;i0){var T=this.canvasPadding/this.worldTransform.a,E=this.canvasPadding/this.worldTransform.d,w=(l+c+d)/3,S=(p+f+v)/3,C=l-w,R=p-S,M=Math.sqrt(C*C+R*R);l=w+C/M*(M+T),p=S+R/M*(M+E),C=c-w,R=f-S,M=Math.sqrt(C*C+R*R),c=w+C/M*(M+T),f=S+R/M*(M+E),C=d-w,R=v-S,M=Math.sqrt(C*C+R*R),d=w+C/M*(M+T),v=S+R/M*(M+E)}t.save(),t.beginPath(),t.moveTo(l,p),t.lineTo(c,f),t.lineTo(d,v),t.closePath(),t.clip();var A=g*_+m*x+y*b-_*x-m*y-g*b,O=l*_+m*d+c*b-_*d-m*c-l*b,D=g*c+l*x+y*d-c*x-l*y-g*d,P=g*_*d+m*c*x+l*y*b-l*_*x-m*y*d-g*c*b,I=p*_+m*v+f*b-_*v-m*f-p*b,L=g*f+p*x+y*v-f*x-p*y-g*v,F=g*_*v+m*f*x+p*y*b-p*_*x-m*y*v-g*f*b;t.transform(O/A,I/A,D/A,L/A,P/A,F/A),t.drawImage(a,0,0,h*o.resolution,u*o.resolution,0,0,h,u),t.restore()},i.prototype.renderMeshFlat=function(t){var e=this.context,r=t.vertices,i=r.length/2;e.beginPath();for(var n=1;n1&&(n=1),s=Math.sqrt(h*h+u*u),o=this._texture.height/2,h/=s,u/=s,h*=o,u*=o,l[i]=r.x+h,l[i+1]=r.y+u,l[i+2]=r.x-h,l[i+3]=r.y-u,a=r;this.containerUpdateTransform()}}},{"../core":62,"./Mesh":152}],156:[function(t,e,r){e.exports={Mesh:t("./Mesh"),Plane:t("./Plane"),NineSlicePlane:t("./NineSlicePlane"),Rope:t("./Rope"),MeshShader:t("./webgl/MeshShader")}},{"./Mesh":152,"./NineSlicePlane":153,"./Plane":154,"./Rope":155,"./webgl/MeshShader":157}],157:[function(t,e,r){function i(t){n.call(this,t,["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","varying vec2 vTextureCoord;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vTextureCoord = aTextureCoord;","}"].join("\n"),["varying vec2 vTextureCoord;","uniform float alpha;","uniform vec3 tint;","uniform sampler2D uSampler;","void main(void){"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vec4(tint * alpha, alpha);","}"].join("\n"))}var n=t("../../core/Shader");i.prototype=Object.create(n.prototype),i.prototype.constructor=i,e.exports=i},{"../../core/Shader":42}],158:[function(t,e,r){function i(t,e,r){n.Container.call(this),r=r||15e3,t=t||15e3;var i=16384;r>i&&(r=i),r>t&&(r=t),this._properties=[!1,!0,!1,!1,!1],this._maxSize=t,this._batchSize=r,this._glBuffers=[],this._bufferToUpdate=0,this.interactiveChildren=!1,this.blendMode=n.BLEND_MODES.NORMAL,this.roundPixels=!0,this.baseTexture=null,this.setProperties(e)}var n=t("../core");i.prototype=Object.create(n.Container.prototype),i.prototype.constructor=i,e.exports=i,i.prototype.setProperties=function(t){t&&(this._properties[0]="scale"in t?!!t.scale:this._properties[0],this._properties[1]="position"in t?!!t.position:this._properties[1],this._properties[2]="rotation"in t?!!t.rotation:this._properties[2],this._properties[3]="uvs"in t?!!t.uvs:this._properties[3],this._properties[4]="alpha"in t?!!t.alpha:this._properties[4])},i.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},i.prototype.renderWebGL=function(t){this.visible&&!(this.worldAlpha<=0)&&this.children.length&&this.renderable&&(this.baseTexture||(this.baseTexture=this.children[0]._texture.baseTexture,this.baseTexture.hasLoaded||this.baseTexture.once("update",function(){this.onChildrenChange(0)},this)),t.setObjectRenderer(t.plugins.particle),t.plugins.particle.render(this))},i.prototype.onChildrenChange=function(t){var e=Math.floor(t/this._batchSize);ei&&(r=i);var s=t._glBuffers[this.renderer.CONTEXT_UID];s||(s=t._glBuffers[this.renderer.CONTEXT_UID]=this.generateBuffers(t)),this.renderer.setBlendMode(t.blendMode);var o=this.renderer.gl,a=t.worldTransform.copy(this.tempMatrix);a.prepend(this.renderer._activeRenderTarget.projectionMatrix),this.shader.uniforms.projectionMatrix=a.toArray(!0),this.shader.uniforms.uAlpha=t.worldAlpha;var h=e[0]._texture.baseTexture;this.renderer.bindTexture(h);for(var u=0,l=0;un&&(c=n);var d=s[l];d.uploadDynamic(e,u,c),t._bufferToUpdate===l&&(d.uploadStatic(e,u,c),t._bufferToUpdate=l+1),d.vao.bind().draw(o.TRIANGLES,6*c).unbind()}}},i.prototype.generateBuffers=function(t){var e,r=this.renderer.gl,i=[],n=t._maxSize,s=t._batchSize,a=t._properties;for(e=0;e0?1:-1})},{}],164:[function(t,e,r){Object.assign||(Object.assign=t("object-assign"))},{"object-assign":5}],165:[function(t,e,r){t("./Object.assign"),t("./requestAnimationFrame"),t("./Math.sign"),window.ArrayBuffer||(window.ArrayBuffer=Array),window.Float32Array||(window.Float32Array=Array),window.Uint32Array||(window.Uint32Array=Array),window.Uint16Array||(window.Uint16Array=Array)},{"./Math.sign":163,"./Object.assign":164,"./requestAnimationFrame":166}],166:[function(t,e,r){(function(t){if(Date.now&&Date.prototype.getTime||(Date.now=function(){return(new Date).getTime()}),!t.performance||!t.performance.now){var e=Date.now();t.performance||(t.performance={}),t.performance.now=function(){return Date.now()-e}}for(var r=Date.now(),i=["ms","moz","webkit","o"],n=0;n0;){var r=this.queue[0],n=!1;for(t=0,e=this.uploadHooks.length;t=0;e--)this.add(t.children[e]);return this},i.prototype.destroy=function(){this.ticking&&u.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null},h.WebGLRenderer.registerPlugin("prepare",i)},{"../../core":62}],170:[function(t,e,r){(function(r){t("./polyfill");var i=e.exports=t("./core");i.extras=t("./extras"),i.filters=t("./filters"),i.interaction=t("./interaction"),i.loaders=t("./loaders"),i.mesh=t("./mesh"),i.particles=t("./particles"),i.accessibility=t("./accessibility"),i.extract=t("./extract"),i.prepare=t("./prepare"),i.loader=new i.loaders.Loader,Object.assign(i,t("./deprecation")),r.PIXI=i}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./accessibility":41,"./core":62,"./deprecation":119,"./extract":121,"./extras":129,"./filters":140,"./interaction":145,"./loaders":148,"./mesh":156,"./particles":159,"./polyfill":165,"./prepare":168}]},{},[170])(170)}); +//# sourceMappingURL=pixi.min.js.map diff --git a/js/pixi/4.1.1/pixi.js b/js/pixi/4.1.1/pixi.js new file mode 100644 index 0000000..aec5620 --- /dev/null +++ b/js/pixi/4.1.1/pixi.js @@ -0,0 +1,20 @@ +/*! + * pixi.js - v4.1.1 + * Compiled Tue Nov 01 2016 17:31:35 GMT+0000 (UTC) + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.PIXI=t()}}(function(){var t;return function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var h=new Error("Cannot find module '"+s+"'");throw h.code="MODULE_NOT_FOUND",h}var l=r[s]={exports:{}};e[s][0].call(l.exports,function(t){var r=e[s][1][t];return i(r?r:t)},l,l.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s0)-(t<0)},r.abs=function(t){var e=t>>i-1;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,e|=r,e|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,t=(858993459&t)+(t>>>2&858993459),16843009*(t+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,t&=15,27030>>>t&1};var o=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|o[t>>>16&255]<<8|o[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),t=65535&(t|t>>>16),t<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),t=1023&(t|t>>>16),t<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],2:[function(t,e,r){"use strict";function n(t,e,r){r=r||2;var n=e&&e.length,o=n?e[0]*r:t.length,a=i(t,0,o,r,!0),u=[];if(!a)return u;var h,l,f,d,p,v,y;if(n&&(a=c(t,e,a,r)),t.length>80*r){h=f=t[0],l=d=t[1];for(var g=r;gf&&(f=p),v>d&&(d=v);y=Math.max(f-h,d-l)}return s(a,u,r,h,l,y),u}function i(t,e,r,n,i){var o,s;if(i===D(t,e,r,n)>0)for(o=e;o=e;o-=n)s=P(o,t[o],t[o+1],s);return s&&T(s,s.next)&&(C(s),s=s.next),s}function o(t,e){if(!t)return t;e||(e=t);var r,n=t;do if(r=!1,n.steiner||!T(n,n.next)&&0!==x(n.prev,n,n.next))n=n.next;else{if(C(n),n=e=n.prev,n===n.next)return null;r=!0}while(r||n!==e);return e}function s(t,e,r,n,i,c,f){if(t){!f&&c&&v(t,n,i,c);for(var d,p,y=t;t.prev!==t.next;)if(d=t.prev,p=t.next,c?u(t,n,i,c):a(t))e.push(d.i/r),e.push(t.i/r),e.push(p.i/r),C(t),t=p.next,y=p.next;else if(t=p,t===y){f?1===f?(t=h(t,e,r),s(t,e,r,n,i,c,2)):2===f&&l(t,e,r,n,i,c):s(o(t),e,r,n,i,c,1);break}}}function a(t){var e=t.prev,r=t,n=t.next;if(x(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(_(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&x(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function u(t,e,r,n){var i=t.prev,o=t,s=t.next;if(x(i,o,s)>=0)return!1;for(var a=i.xo.x?i.x>s.x?i.x:s.x:o.x>s.x?o.x:s.x,l=i.y>o.y?i.y>s.y?i.y:s.y:o.y>s.y?o.y:s.y,c=g(a,u,e,r,n),f=g(h,l,e,r,n),d=t.nextZ;d&&d.z<=f;){if(d!==t.prev&&d!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,d.x,d.y)&&x(d.prev,d,d.next)>=0)return!1;d=d.nextZ}for(d=t.prevZ;d&&d.z>=c;){if(d!==t.prev&&d!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,d.x,d.y)&&x(d.prev,d,d.next)>=0)return!1;d=d.prevZ}return!0}function h(t,e,r){var n=t;do{var i=n.prev,o=n.next.next;!T(i,o)&&w(i,n,n.next,o)&&S(i,o)&&S(o,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(o.i/r),C(n),C(n.next),n=t=o),n=n.next}while(n!==t);return n}function l(t,e,r,n,i,a){var u=t;do{for(var h=u.next.next;h!==u.prev;){if(u.i!==h.i&&b(u,h)){var l=M(u,h);return u=o(u,u.next),l=o(l,l.next),s(u,e,r,n,i,a),void s(l,e,r,n,i,a)}h=h.next}u=u.next}while(u!==t)}function c(t,e,r,n){var s,a,u,h,l,c=[];for(s=0,a=e.length;s=n.next.y){var a=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=i&&a>s){if(s=a,a===i){if(o===n.y)return n;if(o===n.next.y)return n.next}r=n.x=n.x&&n.x>=l&&_(or.x)&&S(n,t)&&(r=n,f=u)),n=n.next;return r}function v(t,e,r,n){var i=t;do null===i.z&&(i.z=g(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,y(i)}function y(t){var e,r,n,i,o,s,a,u,h=1;do{for(r=t,t=null,o=null,s=0;r;){for(s++,n=r,a=0,e=0;e0||u>0&&n;)0===a?(i=n,n=n.nextZ,u--):0!==u&&n?r.z<=n.z?(i=r,r=r.nextZ,a--):(i=n,n=n.nextZ,u--):(i=r,r=r.nextZ,a--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;r=n}o.nextZ=null,h*=2}while(s>1);return t}function g(t,e,r,n,i){return t=32767*(t-r)/i,e=32767*(e-n)/i,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1}function m(t){var e=t,r=t;do e.x=0&&(t-s)*(n-a)-(r-s)*(e-a)>=0&&(r-s)*(o-a)-(i-s)*(n-a)>=0}function b(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!E(t,e)&&S(t,e)&&S(e,t)&&O(t,e)}function x(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function T(t,e){return t.x===e.x&&t.y===e.y}function w(t,e,r,n){return!!(T(t,e)&&T(r,n)||T(t,n)&&T(r,e))||x(t,e,r)>0!=x(t,e,n)>0&&x(r,n,t)>0!=x(r,n,e)>0}function E(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&w(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}function S(t,e){return x(t.prev,t,t.next)<0?x(t,e,t.next)>=0&&x(t,t.prev,e)>=0:x(t,e,t.prev)<0||x(t,t.next,e)<0}function O(t,e){var r=t,n=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do r.y>o!=r.next.y>o&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;while(r!==t);return n}function M(t,e){var r=new R(t.i,t.x,t.y),n=new R(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function P(t,e,r,n){var i=new R(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function C(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function R(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function D(t,e,r,n){for(var i=0,o=e,s=r-n;o0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],3:[function(t,e,r){"use strict";function n(){}function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function o(){this._events=new n,this._eventsCount=0}var s=Object.prototype.hasOwnProperty,a="~";Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(a=!1)),o.prototype.eventNames=function(){var t,e,r=[];if(0===this._eventsCount)return r;for(e in t=this._events)s.call(t,e)&&r.push(a?e.slice(1):e);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t,e){var r=a?a+t:t,n=this._events[r];if(e)return!!n;if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i=t.byteLength?n.bufferSubData(this.type,e,t):n.bufferData(this.type,t,this.drawType),this.data=t},i.prototype.bind=function(){var t=this.gl;t.bindBuffer(this.type,this.buffer)},i.createVertexBuffer=function(t,e,r){return new i(t,t.ARRAY_BUFFER,e,r)},i.createIndexBuffer=function(t,e,r){return new i(t,t.ELEMENT_ARRAY_BUFFER,e,r)},i.create=function(t,e,r,n){return new i(t,e,n)},i.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer)},e.exports=i},{}],7:[function(t,e,r){var n=t("./GLTexture"),i=function(t,e,r){this.gl=t,this.framebuffer=t.createFramebuffer(),this.stencil=null,this.texture=null,this.width=e||100,this.height=r||100};i.prototype.enableTexture=function(t){var e=this.gl;this.texture=t||new n(e),this.texture.bind(),this.bind(),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0)},i.prototype.enableStencil=function(){if(!this.stencil){var t=this.gl;this.stencil=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.stencil),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.stencil),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,this.width,this.height)}},i.prototype.clear=function(t,e,r,n){this.bind();var i=this.gl;i.clearColor(t,e,r,n),i.clear(i.COLOR_BUFFER_BIT)},i.prototype.bind=function(){var t=this.gl;this.texture&&this.texture.unbind(),t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer)},i.prototype.unbind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)},i.prototype.resize=function(t,e){var r=this.gl;this.width=t,this.height=e,this.texture&&this.texture.uploadData(null,t,e),this.stencil&&(r.bindRenderbuffer(r.RENDERBUFFER,this.stencil),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e))},i.prototype.destroy=function(){var t=this.gl;this.texture&&this.texture.destroy(),t.deleteFramebuffer(this.framebuffer),this.gl=null,this.stencil=null,this.texture=null},i.createRGBA=function(t,e,r){var o=n.fromData(t,null,e,r);o.enableNearestScaling(),o.enableWrapClamp();var s=new i(t,e,r);return s.enableTexture(o),s.unbind(),s},i.createFloat32=function(t,e,r,o){var s=new n.fromData(t,o,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},e.exports=i},{"./GLTexture":9}],8:[function(t,e,r){var n=t("./shader/compileProgram"),i=t("./shader/extractAttributes"),o=t("./shader/extractUniforms"),s=t("./shader/generateUniformAccessObject"),a=function(t,e,r){this.gl=t,this.program=n(t,e,r),this.attributes=i(t,this.program);var a=o(t,this.program);this.uniforms=s(t,a)};a.prototype.bind=function(){this.gl.useProgram(this.program)},a.prototype.destroy=function(){},e.exports=a},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18}],9:[function(t,e,r){var n=function(t,e,r,n,i){this.gl=t,this.texture=t.createTexture(),this.mipmap=!1,this.premultiplyAlpha=!1,this.width=e||0,this.height=r||0,this.format=n||t.RGBA,this.type=i||t.UNSIGNED_BYTE};n.prototype.upload=function(t){this.bind();var e=this.gl;this.width=t.videoWidth||t.width,this.height=t.videoHeight||t.height,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),e.texImage2D(e.TEXTURE_2D,0,this.format,this.format,this.type,t)};var i=!1;n.prototype.uploadData=function(t,e,r){this.bind();var n=this.gl;if(this.width=e||this.width,this.height=r||this.height,t instanceof Float32Array){if(!i){var o=n.getExtension("OES_texture_float");if(!o)throw new Error("floating point textures not available");i=!0}this.type=n.FLOAT}else this.type=n.UNSIGNED_BYTE;n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),n.texImage2D(n.TEXTURE_2D,0,this.format,this.width,this.height,0,this.format,this.type,t||null)},n.prototype.bind=function(t){var e=this.gl;void 0!==t&&e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,this.texture)},n.prototype.unbind=function(){var t=this.gl;t.bindTexture(t.TEXTURE_2D,null)},n.prototype.minFilter=function(t){var e=this.gl;this.bind(),this.mipmap?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.magFilter=function(t){var e=this.gl;this.bind(),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.enableMipmap=function(){var t=this.gl;this.bind(),this.mipmap=!0,t.generateMipmap(t.TEXTURE_2D)},n.prototype.enableLinearScaling=function(){this.minFilter(!0),this.magFilter(!0)},n.prototype.enableNearestScaling=function(){this.minFilter(!1),this.magFilter(!1)},n.prototype.enableWrapClamp=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)},n.prototype.enableWrapRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT)},n.prototype.enableWrapMirrorRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.MIRRORED_REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.MIRRORED_REPEAT)},n.prototype.destroy=function(){var t=this.gl;t.deleteTexture(this.texture)},n.fromSource=function(t,e,r){var i=new n(t);return i.premultiplyAlpha=r||!1,i.upload(e),i},n.fromData=function(t,e,r,i){var o=new n(t);return o.uploadData(e,r,i),o},e.exports=n},{}],10:[function(t,e,r){function n(t,e){if(this.nativeVaoExtension=null,n.FORCE_NATIVE||(this.nativeVaoExtension=t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object")),this.nativeState=e,this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var r=t.getParameter(t.MAX_VERTEX_ATTRIBS);this.nativeState={tempAttribState:new Array(r),attribState:new Array(r)}}this.gl=t,this.attributes=[],this.indexBuffer=null,this.dirty=!1}var i=t("./setVertexAttribArrays");n.prototype.constructor=n,e.exports=n,n.FORCE_NATIVE=!1,n.prototype.bind=function(){return this.nativeVao?(this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao),this.dirty&&(this.dirty=!1,this.activate())):this.activate(),this},n.prototype.unbind=function(){return this.nativeVao&&this.nativeVaoExtension.bindVertexArrayOES(null),this},n.prototype.activate=function(){for(var t=this.gl,e=null,r=0;r=0;n--){var i=t[n];"."===i?t.splice(n,1):".."===i?(t.splice(n,1),r++):r&&(t.splice(n,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}function n(t,e){if(t.filter)return t.filter(e);for(var r=[],n=0;n=-1&&!i;o--){var s=o>=0?arguments[o]:t.cwd();if("string"!=typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(r=s+"/"+r,i="/"===s.charAt(0))}return r=e(n(r.split("/"),function(t){return!!t}),!i).join("/"),(i?"/":"")+r||"."},r.normalize=function(t){var i=r.isAbsolute(t),o="/"===s(t,-1);return t=e(n(t.split("/"),function(t){return!!t}),!i).join("/"),t||i||(t="."),t&&o&&(t+="/"),(i?"/":"")+t},r.isAbsolute=function(t){return"/"===t.charAt(0)},r.join=function(){var t=Array.prototype.slice.call(arguments,0);return r.normalize(n(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},r.relative=function(t,e){function n(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=r.resolve(t).substr(1),e=r.resolve(e).substr(1);for(var i=n(t.split("/")),o=n(e.split("/")),s=Math.min(i.length,o.length),a=s,u=0;u1)for(var r=1;r1&&(n=r[0]+"@",t=r[1]),t=t.replace(I,".");var i=t.split("."),o=s(i,e).join(".");return n+o}function u(t){for(var e,r,n=[],i=0,o=t.length;i=55296&&e<=56319&&i65535&&(t-=65536,e+=B(t>>>10&1023|55296),t=56320|1023&t),e+=B(t)}).join("")}function l(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:w}function c(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function f(t,e,r){var n=0;for(t=r?F(t/M):t>>1,t+=F(t/e);t>j*S>>1;n+=w)t=F(t/j);return F(n+(j+1)*t/(t+O))}function d(t){var e,r,n,i,s,a,u,c,d,p,v=[],y=t.length,g=0,m=C,_=P;for(r=t.lastIndexOf(R),r<0&&(r=0),n=0;n=128&&o("not-basic"),v.push(t.charCodeAt(n));for(i=r>0?r+1:0;i=y&&o("invalid-input"),c=l(t.charCodeAt(i++)),(c>=w||c>F((T-g)/a))&&o("overflow"),g+=c*a,d=u<=_?E:u>=_+S?S:u-_,!(cF(T/p)&&o("overflow"),a*=p;e=v.length+1,_=f(g-s,e,0==s),F(g/e)>T-m&&o("overflow"),m+=F(g/e),g%=e,v.splice(g++,0,m)}return h(v)}function p(t){var e,r,n,i,s,a,h,l,d,p,v,y,g,m,_,b=[];for(t=u(t),y=t.length,e=C,r=0,s=P,a=0;a=e&&vF((T-r)/g)&&o("overflow"),r+=(h-e)*g,e=h,a=0;aT&&o("overflow"),v==e){for(l=r,d=w;p=d<=s?E:d>=s+S?S:d-s,!(l= 0x80 (not a basic code point)","invalid-input":"Invalid input"},j=w-E,F=Math.floor,B=String.fromCharCode;if(b={version:"1.4.1",ucs2:{decode:u,encode:h},decode:d,encode:p,toASCII:y,toUnicode:v},"function"==typeof t&&"object"==typeof t.amd&&t.amd)t("punycode",function(){return b});else if(g&&m)if(r.exports==g)m.exports=b;else for(x in b)b.hasOwnProperty(x)&&(g[x]=b[x]);else i.punycode=b}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],25:[function(t,e,r){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,r,o){e=e||"&",r=r||"=";var s={};if("string"!=typeof t||0===t.length)return s;var a=/\+/g;t=t.split(e);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var h=t.length;u>0&&h>u&&(h=u);for(var l=0;l=0?(c=v.substr(0,y),f=v.substr(y+1)):(c=v,f=""),d=decodeURIComponent(c),p=decodeURIComponent(f),n(s,d)?i(s[d])?s[d].push(p):s[d]=[s[d],p]:s[d]=p}return s};var i=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],26:[function(t,e,r){"use strict";function n(t,e){if(t.map)return t.map(e);for(var r=[],n=0;n",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(d),v=["'"].concat(p),y=["%","/","?",";","#"].concat(v),g=["/","?","#"],m=255,_=/^[+a-z0-9A-Z_-]{0,63}$/,b=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,x={javascript:!0,"javascript:":!0},T={javascript:!0,"javascript:":!0},w={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},E=t("querystring");n.prototype.parse=function(t,e,r){if(!h.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var n=t.indexOf("?"),i=n!==-1&&n127?"x":L[F];if(!j.match(_)){var k=A.slice(0,M),N=A.slice(M+1),U=L.match(b);U&&(k.push(U[1]),N.unshift(U[2])),N.length&&(a="/"+N.join(".")+a),this.hostname=k.join(".");break}}}this.hostname.length>m?this.hostname="":this.hostname=this.hostname.toLowerCase(),D||(this.hostname=u.toASCII(this.hostname));var X=this.port?":"+this.port:"",W=this.hostname||"";this.host=W+X,this.href+=this.host,D&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==a[0]&&(a="/"+a))}if(!x[p])for(var M=0,I=v.length;M0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return r.search=t.search,r.query=t.query,h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!x.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var O=x.slice(-1)[0],M=(r.host||t.host||x.length>1)&&("."===O||".."===O)||""===O,P=0,C=x.length;C>=0;C--)O=x[C],"."===O?x.splice(C,1):".."===O?(x.splice(C,1),P++):P&&(x.splice(C,1),P--);if(!_&&!b)for(;P--;P)x.unshift("..");!_||""===x[0]||x[0]&&"/"===x[0].charAt(0)||x.unshift(""),M&&"/"!==x.join("/").substr(-1)&&x.push("");var R=""===x[0]||x[0]&&"/"===x[0].charAt(0);if(E){r.hostname=r.host=R?"":x.length?x.shift():"";var S=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return _=_||r.host&&x.length,_&&!R&&x.unshift(""),x.length?r.pathname=x.join("/"):(r.pathname=null,r.path=null),h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},n.prototype.parseHost=function(){var t=this.host,e=c.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":29,punycode:24,querystring:27}],29:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],30:[function(t,e,r){arguments[4][3][0].apply(r,arguments)},{dup:3}],31:[function(t,e,r){"use strict";e.exports=function(t,e){e=e||{};for(var r={key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}},n=r.parser[e.strictMode?"strict":"loose"].exec(t),i={},o=14;o--;)i[r.key[o]]=n[o]||"";return i[r.q.name]={},i[r.key[12]].replace(r.q.parser,function(t,e,n){e&&(i[r.q.name][e]=n)}),i}},{}],32:[function(t,e,r){"use strict";function n(t,e){a.call(this),e=e||u,this.baseUrl=t||"",this.progress=0,this.loading=!1,this._progressChunk=0,this._beforeMiddleware=[],this._afterMiddleware=[],this._boundLoadResource=this._loadResource.bind(this),this._buffer=[],this._numToLoad=0,this._queue=o.queue(this._boundLoadResource,e),this.resources={}}var i=t("parse-uri"),o=t("./async"),s=t("./Resource"),a=t("eventemitter3"),u=10,h=100;n.prototype=Object.create(a.prototype),n.prototype.constructor=n,e.exports=n,n.prototype.add=n.prototype.enqueue=function(t,e,r,n){if(Array.isArray(t)){for(var i=0;i0))return void this.abort("["+t.status+"]"+t.statusText+":"+t.responseURL);if(this.xhrType===n.XHR_RESPONSE_TYPE.TEXT)this.data=t.responseText;else if(this.xhrType===n.XHR_RESPONSE_TYPE.JSON)try{this.data=JSON.parse(t.responseText),this.isJson=!0}catch(t){return void this.abort("Error trying to parse loaded json:",t)}else if(this.xhrType===n.XHR_RESPONSE_TYPE.DOCUMENT)try{if(window.DOMParser){var r=new DOMParser;this.data=r.parseFromString(t.responseText,"text/xml")}else{var i=document.createElement("div");i.innerHTML=t.responseText,this.data=i}this.isXml=!0}catch(t){return void this.abort("Error trying to parse loaded xml:",t)}else this.data=t.response||t.responseText;this.complete()},n.prototype._determineCrossOrigin=function(t,e){if(0===t.indexOf("data:"))return"";e=e||window.location,h||(h=document.createElement("a")),h.href=t,t=a(h.href,{strictMode:!0});var r=!t.port&&""===e.port||t.port===e.port,n=t.protocol?t.protocol+":":"";return t.host===e.hostname&&r&&n===e.protocol?"":"anonymous"},n.prototype._determineXhrType=function(){return n._xhrTypeMap[this._getExtension()]||n.XHR_RESPONSE_TYPE.TEXT},n.prototype._determineLoadType=function(){return n._loadTypeMap[this._getExtension()]||n.LOAD_TYPE.XHR},n.prototype._getExtension=function(){var t=this.url,e="";if(this.isDataUrl){var r=t.indexOf("/");e=t.substring(r+1,t.indexOf(";",r))}else{var n=t.indexOf("?");n!==-1&&(t=t.substring(0,n)),e=t.substring(t.lastIndexOf(".")+1)}return e.toLowerCase()},n.prototype._getMimeFromXhrType=function(t){switch(t){case n.XHR_RESPONSE_TYPE.BUFFER:return"application/octet-binary";case n.XHR_RESPONSE_TYPE.BLOB:return"application/blob";case n.XHR_RESPONSE_TYPE.DOCUMENT:return"application/xml";case n.XHR_RESPONSE_TYPE.JSON:return"application/json";case n.XHR_RESPONSE_TYPE.DEFAULT:case n.XHR_RESPONSE_TYPE.TEXT:default:return"text/plain"}},n.LOAD_TYPE={XHR:1,IMAGE:2,AUDIO:3,VIDEO:4},n.XHR_RESPONSE_TYPE={DEFAULT:"text",BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"},n._loadTypeMap={gif:n.LOAD_TYPE.IMAGE,png:n.LOAD_TYPE.IMAGE,bmp:n.LOAD_TYPE.IMAGE,jpg:n.LOAD_TYPE.IMAGE,jpeg:n.LOAD_TYPE.IMAGE,tif:n.LOAD_TYPE.IMAGE,tiff:n.LOAD_TYPE.IMAGE,webp:n.LOAD_TYPE.IMAGE,tga:n.LOAD_TYPE.IMAGE,"svg+xml":n.LOAD_TYPE.IMAGE},n._xhrTypeMap={xhtml:n.XHR_RESPONSE_TYPE.DOCUMENT,html:n.XHR_RESPONSE_TYPE.DOCUMENT,htm:n.XHR_RESPONSE_TYPE.DOCUMENT,xml:n.XHR_RESPONSE_TYPE.DOCUMENT,tmx:n.XHR_RESPONSE_TYPE.DOCUMENT,tsx:n.XHR_RESPONSE_TYPE.DOCUMENT,svg:n.XHR_RESPONSE_TYPE.DOCUMENT,gif:n.XHR_RESPONSE_TYPE.BLOB,png:n.XHR_RESPONSE_TYPE.BLOB,bmp:n.XHR_RESPONSE_TYPE.BLOB,jpg:n.XHR_RESPONSE_TYPE.BLOB,jpeg:n.XHR_RESPONSE_TYPE.BLOB,tif:n.XHR_RESPONSE_TYPE.BLOB,tiff:n.XHR_RESPONSE_TYPE.BLOB,webp:n.XHR_RESPONSE_TYPE.BLOB,tga:n.XHR_RESPONSE_TYPE.BLOB,json:n.XHR_RESPONSE_TYPE.JSON,text:n.XHR_RESPONSE_TYPE.TEXT,txt:n.XHR_RESPONSE_TYPE.TEXT},n.setExtensionLoadType=function(t,e){o(n._loadTypeMap,t,e)},n.setExtensionXhrType=function(t,e){o(n._xhrTypeMap,t,e)}},{eventemitter3:30,"parse-uri":31}],34:[function(t,e,r){"use strict";function n(){}function i(t,e,r){var n=0,i=t.length;!function o(s){return s||n===i?void(r&&r(s)):void e(t[n++],o)}()}function o(t){return function(){if(null===t)throw new Error("Callback was already called.");var e=t;t=null,e.apply(this,arguments)}}function s(t,e){function r(t,e,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(a.started=!0,null==t&&a.idle())return void setTimeout(function(){a.drain()},1);var i={data:t,callback:"function"==typeof r?r:n};e?a._tasks.unshift(i):a._tasks.push(i),setTimeout(function(){a.process()},1)}function i(t){return function(){s-=1,t.callback.apply(t,arguments),null!=arguments[0]&&a.error(arguments[0],t.data),s<=a.concurrency-a.buffer&&a.unsaturated(),a.idle()&&a.drain(),a.process()}}if(null==e)e=1;else if(0===e)throw new Error("Concurrency must not be zero");var s=0,a={_tasks:[],concurrency:e,saturated:n,unsaturated:n,buffer:e/4,empty:n,drain:n,error:n,started:!1,paused:!1,push:function(t,e){r(t,!1,e)},kill:function(){a.drain=n,a._tasks=[]},unshift:function(t,e){r(t,!0,e)},process:function(){for(;!a.paused&&s>2,n[1]=(3&e[0])<<4|e[1]>>4,n[2]=(15&e[1])<<2|e[2]>>6,n[3]=63&e[2],s=i-(t.length-1)){case 2:n[3]=64,n[2]=64;break;case 1:n[3]=64}for(o=0;o=0;r--)this.updateAccessibleObjects(e[r])}},t.prototype.update=function(){if(this.renderer.renderingToScreen){this.updateAccessibleObjects(this.renderer._lastObjectRendered);var t=this.renderer.view.getBoundingClientRect(),e=t.width/this.renderer.width,r=t.height/this.renderer.height,n=this.div;n.style.left=t.left+"px",n.style.top=t.top+"px",n.style.width=this.renderer.width+"px", +n.style.height=this.renderer.height+"px";for(var i=0;ithis.renderer.width&&(t.width=this.renderer.width-t.x),t.y+t.height>this.renderer.height&&(t.height=this.renderer.height-t.y)},t.prototype.addChild=function(t){var e=this.pool.pop();e||(e=document.createElement("button"),e.style.width=d+"px",e.style.height=d+"px",e.style.backgroundColor=this.debug?"rgba(255,0,0,0.5)":"transparent",e.style.position="absolute",e.style.zIndex=y,e.style.borderStyle="none",e.addEventListener("click",this._onClick.bind(this)),e.addEventListener("focus",this._onFocus.bind(this)),e.addEventListener("focusout",this._onFocusOut.bind(this))),t.accessibleTitle?e.title=t.accessibleTitle:t.accessibleTitle||t.accessibleHint||(e.title="displayObject "+this.tabIndex),t.accessibleHint&&e.setAttribute("aria-label",t.accessibleHint),t._accessibleActive=!0,t._accessibleDiv=e,e.displayObject=t,this.children.push(t),this.div.appendChild(t._accessibleDiv),t._accessibleDiv.tabIndex=t.tabIndex},t.prototype._onClick=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"click",e.eventData)},t.prototype._onFocus=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseover",e.eventData)},t.prototype._onFocusOut=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseout",e.eventData)},t.prototype._onKeyDown=function(t){t.keyCode===f&&this.activate()},t.prototype._onMouseMove=function(){this.deactivate()},t.prototype.destroy=function(){this.div=null;for(var t=0;t]*(?:\s(width|height)="(\d*(?:\.\d+)?)(?:px)?")[^>]*(?:\s(width|height)="(\d*(?:\.\d+)?)(?:px)?")[^>]*>/i,r.SHAPES={POLY:0,RECT:1,CIRC:2,ELIP:3,RREC:4},r.PRECISION={DEFAULT:"mediump",LOW:"lowp",MEDIUM:"mediump",HIGH:"highp"},r.TRANSFORM_MODE={DEFAULT:0,STATIC:0,DYNAMIC:1},r.TEXT_GRADIENT={LINEAR_VERTICAL:0,LINEAR_HORIZONTAL:1},r.SPRITE_BATCH_SIZE=4096,r.SPRITE_MAX_TEXTURES=(0,o.default)(32)},{"./utils/maxRecommendedTextures":117}],44:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../math"),o=function(){function t(){n(this,t),this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0),this.rect=null}return t.prototype.isEmpty=function(){return this.minX>this.maxX||this.minY>this.maxY},t.prototype.clear=function(){this.updateID++,this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0)},t.prototype.getRectangle=function(t){return this.minX>this.maxX||this.minY>this.maxY?i.Rectangle.EMPTY:(t=t||new i.Rectangle(0,0,1,1),t.x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)},t.prototype.addPoint=function(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)},t.prototype.addQuad=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY,o=t[0],s=t[1];e=on?o:n,i=s>i?s:i,o=t[2],s=t[3],e=on?o:n,i=s>i?s:i,o=t[4],s=t[5],e=on?o:n,i=s>i?s:i,o=t[6],s=t[7],e=on?o:n,i=s>i?s:i,this.minX=e,this.minY=r,this.maxX=n,this.maxY=i},t.prototype.addFrame=function(t,e,r,n,i){var o=t.worldTransform,s=o.a,a=o.b,u=o.c,h=o.d,l=o.tx,c=o.ty,f=this.minX,d=this.minY,p=this.maxX,v=this.maxY,y=s*e+u*r+l,g=a*e+h*r+c;f=yp?y:p,v=g>v?g:v,y=s*n+u*r+l,g=a*n+h*r+c,f=yp?y:p,v=g>v?g:v,y=s*e+u*i+l,g=a*e+h*i+c,f=yp?y:p,v=g>v?g:v,y=s*n+u*i+l,g=a*n+h*i+c,f=yp?y:p,v=g>v?g:v,this.minX=f,this.minY=d,this.maxX=p,this.maxY=v},t.prototype.addVertices=function(t,e,r,n){for(var i=t.worldTransform,o=i.a,s=i.b,a=i.c,u=i.d,h=i.tx,l=i.ty,c=this.minX,f=this.minY,d=this.maxX,p=this.maxY,v=r;vd?m:d,p=_>p?_:p}this.minX=c,this.minY=f,this.maxX=d,this.maxY=p},t.prototype.addBounds=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY;this.minX=t.minXn?t.maxX:n,this.maxY=t.maxY>i?t.maxY:i},t.prototype.addBoundsMask=function(t,e){var r=t.minX>e.minX?t.minX:e.minX,n=t.minY>e.minY?t.minY:e.minY,i=t.maxXu?i:u,this.maxY=o>h?o:h}},t.prototype.addBoundsArea=function(t,e){var r=t.minX>e.x?t.minX:e.x,n=t.minY>e.y?t.minY:e.y,i=t.maxXu?i:u,this.maxY=o>h?o:h}},t}();r.default=o},{"../math":67}],45:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rthis.children.length)throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length);return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),this.onChildrenChange(e),t.emit("added",this),t},e.prototype.swapChildren=function(t,e){if(t!==e){var r=this.getChildIndex(t),n=this.getChildIndex(e);this.children[r]=e,this.children[n]=t,this.onChildrenChange(r=this.children.length)throw new Error("The supplied index is out of bounds");var r=this.getChildIndex(t);(0,u.removeItems)(this.children,r,1),this.children.splice(e,0,t),this.onChildrenChange(e)},e.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Index ("+t+") does not exist.");return this.children[t]},e.prototype.removeChild=function(){for(var t=arguments.length,e=Array(t),r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=t,n="number"==typeof e?e:this.children.length,i=n-r,o=void 0;if(i>0&&i<=n){o=this.children.splice(r,i);for(var s=0;s2&&void 0!==arguments[2]&&arguments[2];return r||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)},e.prototype.toLocal=function(t,e,r,n){return e&&(t=e.toGlobal(t,r,n)),n||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,r)},e.prototype.renderWebGL=function(t){},e.prototype.renderCanvas=function(t){},e.prototype.setParent=function(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t},e.prototype.setTransform=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0,u=arguments.length>8&&void 0!==arguments[8]?arguments[8]:0;return this.position.x=t,this.position.y=e,this.scale.x=r?r:1,this.scale.y=n?n:1,this.rotation=i,this.skew.x=o,this.skew.y=s,this.pivot.x=a,this.pivot.y=u,this},e.prototype.destroy=function(){this.removeAllListeners(),this.parent&&this.parent.removeChild(this),this.transform=null,this.parent=null,this._bounds=null,this._currentBounds=null,this._mask=null,this.filterArea=null,this.interactive=!1,this.interactiveChildren=!1},a(e,[{key:"_tempDisplayObjectParent",get:function(){return null===this.tempDisplayObjectParent&&(this.tempDisplayObjectParent=new e),this.tempDisplayObjectParent}},{key:"x",get:function(){return this.position.x},set:function(t){this.transform.position.x=t}},{key:"y",get:function(){return this.position.y},set:function(t){this.transform.position.y=t}},{key:"worldTransform",get:function(){return this.transform.worldTransform}},{key:"localTransform",get:function(){return this.transform.localTransform}},{key:"position",get:function(){return this.transform.position},set:function(t){this.transform.position.copy(t)}},{key:"scale",get:function(){return this.transform.scale},set:function(t){this.transform.scale.copy(t)}},{key:"pivot",get:function(){return this.transform.pivot},set:function(t){this.transform.pivot.copy(t)}},{key:"skew",get:function(){return this.transform.skew},set:function(t){this.transform.skew.copy(t)}},{key:"rotation",get:function(){return this.transform.rotation},set:function(t){this.transform.rotation=t}},{key:"worldVisible",get:function(){var t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask&&(this._mask.renderable=!0),this._mask=t,this._mask&&(this._mask.renderable=!1)}},{key:"filters",get:function(){return this._filters&&this._filters.slice()},set:function(t){this._filters=t&&t.slice()}}]),e}(h.default);r.default=m,m.prototype.displayObjectUpdateTransform=m.prototype.updateTransform},{"../const":43,"../math":67,"./Bounds":44,"./Transform":47,"./TransformStatic":49,eventemitter3:3}],47:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;if(this.lineWidth=t,this.lineColor=e,this.lineAlpha=r,this.currentPath)if(this.currentPath.shape.points.length){var n=new g.Polygon(this.currentPath.shape.points.slice(-2));n.closed=!1,this.drawShape(n)}else this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha;return this},e.prototype.moveTo=function(t,e){var r=new g.Polygon([t,e]);return r.closed=!1,this.drawShape(r),this},e.prototype.lineTo=function(t,e){return this.currentPath.shape.points.push(t,e),this.dirty++,this},e.prototype.quadraticCurveTo=function(t,e,r,n){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var i=20,o=this.currentPath.shape.points,s=0,a=0;0===o.length&&this.moveTo(0,0);for(var u=o[o.length-2],h=o[o.length-1],l=1;l<=i;++l){var c=l/i;s=u+(t-u)*c,a=h+(e-h)*c,o.push(s+(t+(r-t)*c-s)*c,a+(e+(n-e)*c-a)*c)}return this.dirty++,this},e.prototype.bezierCurveTo=function(t,e,r,n,i,o){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var s=this.currentPath.shape.points,a=s[s.length-2],u=s[s.length-1];return s.length-=2,(0,w.default)(a,u,t,e,r,n,i,o,s),this.dirty++,this},e.prototype.arcTo=function(t,e,r,n,i){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(t,e):this.moveTo(t,e);var o=this.currentPath.shape.points,s=o[o.length-2],a=o[o.length-1],u=a-e,h=s-t,l=n-e,c=r-t,f=Math.abs(u*c-h*l);if(f<1e-8||0===i)o[o.length-2]===t&&o[o.length-1]===e||o.push(t,e);else{var d=u*u+h*h,p=l*l+c*c,v=u*l+h*c,y=i*Math.sqrt(d)/f,g=i*Math.sqrt(p)/f,m=y*v/d,_=g*v/p,b=y*c+g*h,x=y*l+g*u,T=h*(g+m),w=u*(g+m),E=c*(y+_),S=l*(y+_),O=Math.atan2(w-x,T-b),M=Math.atan2(S-x,E-b);this.arc(b+t,x+e,i,O,M,h*l>c*u)}return this.dirty++,this},e.prototype.arc=function(t,e,r,n,i){var o=arguments.length>5&&void 0!==arguments[5]&&arguments[5];if(n===i)return this;!o&&i<=n?i+=2*Math.PI:o&&n<=i&&(n+=2*Math.PI); +var s=o?n-i:i-n,a=40*Math.ceil(Math.abs(s)/(2*Math.PI));if(0===s)return this;var u=t+Math.cos(n)*r,h=e+Math.sin(n)*r,l=this.currentPath.shape.points;this.currentPath?l[l.length-2]===u&&l[l.length-1]===h||l.push(u,h):this.moveTo(u,h);for(var c=s/(2*a),f=2*c,d=Math.cos(c),p=Math.sin(c),v=a-1,y=v%1/v,g=0;g<=v;++g){var m=g+y*g,_=c+n+f*m,b=Math.cos(_),x=-Math.sin(_);l.push((d*b+p*x)*r+t,(d*-x+p*b)*r+e)}return this.dirty++,this},e.prototype.beginFill=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this.filling=!0,this.fillColor=t,this.fillAlpha=e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},e.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},e.prototype.drawRect=function(t,e,r,n){return this.drawShape(new g.Rectangle(t,e,r,n)),this},e.prototype.drawRoundedRect=function(t,e,r,n,i){return this.drawShape(new g.RoundedRectangle(t,e,r,n,i)),this},e.prototype.drawCircle=function(t,e,r){return this.drawShape(new g.Circle(t,e,r)),this},e.prototype.drawEllipse=function(t,e,r,n){return this.drawShape(new g.Ellipse(t,e,r,n)),this},e.prototype.drawPolygon=function(t){var e=t,r=!0;if(e instanceof g.Polygon&&(r=e.closed,e=e.points),!Array.isArray(e)){e=new Array(arguments.length);for(var n=0;n0)&&(this.lineWidth=0,this.filling=!1,this.dirty++,this.clearDirty++,this.graphicsData.length=0),this},e.prototype.isFastRect=function(){return 1===this.graphicsData.length&&this.graphicsData[0].shape.type===_.SHAPES.RECT&&!this.graphicsData[0].lineWidth},e.prototype._renderWebGL=function(t){this.dirty!==this.fastRectDirty&&(this.fastRectDirty=this.dirty,this._fastRect=this.isFastRect()),this._fastRect?this._renderSpriteRect(t):(t.setObjectRenderer(t.plugins.graphics),t.plugins.graphics.render(this))},e.prototype._renderSpriteRect=function(t){var r=this.graphicsData[0].shape;if(!this._spriteRect){if(!e._SPRITE_TEXTURE){e._SPRITE_TEXTURE=l.default.create(10,10);var n=document.createElement("canvas");n.width=10,n.height=10;var i=n.getContext("2d");i.fillStyle="white",i.fillRect(0,0,10,10),e._SPRITE_TEXTURE=f.default.fromCanvas(n)}this._spriteRect=new y.default(e._SPRITE_TEXTURE)}if(16777215===this.tint)this._spriteRect.tint=this.graphicsData[0].fillColor;else{var o=C,s=R;(0,m.hex2rgb)(this.graphicsData[0].fillColor,o),(0,m.hex2rgb)(this.tint,s),o[0]*=s[0],o[1]*=s[1],o[2]*=s[2],this._spriteRect.tint=(0,m.rgb2hex)(o)}this._spriteRect.alpha=this.graphicsData[0].fillAlpha,this._spriteRect.worldAlpha=this.worldAlpha*this._spriteRect.alpha,e._SPRITE_TEXTURE._frame.width=r.width,e._SPRITE_TEXTURE._frame.height=r.height,this._spriteRect.transform.worldTransform=this.transform.worldTransform,this._spriteRect.anchor.set(-r.x/r.width,-r.y/r.height),this._spriteRect._onAnchorUpdate(),this._spriteRect._renderWebGL(t)},e.prototype._renderCanvas=function(t){this.isMask!==!0&&t.plugins.graphics.render(this)},e.prototype._calculateBounds=function(){this.boundsDirty!==this.dirty&&(this.boundsDirty=this.dirty,this.updateLocalBounds(),this.dirty++,this.cachedSpriteDirty=!0);var t=this._localBounds;this._bounds.addFrame(this.transform,t.minX,t.minY,t.maxX,t.maxY)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,P);for(var e=this.graphicsData,r=0;re?o+a:e,r=sn?s+u:n;else if(c===_.SHAPES.CIRC)o=i.x,s=i.y,a=i.radius+f/2,u=i.radius+f/2,t=o-ae?o+a:e,r=s-un?s+u:n;else if(c===_.SHAPES.ELIP)o=i.x,s=i.y,a=i.width+f/2,u=i.height+f/2,t=o-ae?o+a:e,r=s-un?s+u:n;else for(var d=i.points,p=0;pe?o+f:e,r=s-fn?s+f:n}else t=0,e=0,r=0,n=0;var v=this.boundsPadding;this._localBounds.minX=t-v,this._localBounds.maxX=e+2*v,this._localBounds.minY=r-v,this._localBounds.maxY=n+2*v},e.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null;var e=new p.default(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===_.SHAPES.POLY&&(e.shape.closed=e.shape.closed||this.filling,this.currentPath=e),this.dirty++,e},e.prototype.generateCanvasTexture=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=this.getLocalBounds(),n=l.default.create(r.width,r.height,t,e);O||(O=new S.default),M.tx=-r.x,M.ty=-r.y,O.render(this,n,!1,M);var i=f.default.fromCanvas(n.baseTexture._canvasRenderTarget.canvas,t);return i.baseTexture.resolution=e,i.baseTexture.update(),i},e.prototype.closePath=function(){var t=this.currentPath;return t&&t.shape&&t.shape.close(),this},e.prototype.addHole=function(){var t=this.graphicsData.pop();return this.currentPath=this.graphicsData[this.graphicsData.length-1],this.currentPath.addHole(t.shape),this.currentPath=null,this},e.prototype.destroy=function(e){t.prototype.destroy.call(this,e);for(var r=0;rC?C:P,r.beginPath(),r.moveTo(E,S+P),r.lineTo(E,S+M-P),r.quadraticCurveTo(E,S+M,E+P,S+M),r.lineTo(E+O-P,S+M),r.quadraticCurveTo(E+O,S+M,E+O,S+M-P),r.lineTo(E+O,S+P),r.quadraticCurveTo(E+O,S,E+O-P,S),r.lineTo(E+P,S),r.quadraticCurveTo(E,S,E,S+P),r.closePath(),(u.fillColor||0===u.fillColor)&&(r.globalAlpha=u.fillAlpha*n,r.fillStyle="#"+("00000"+(0|l).toString(16)).substr(-6),r.fill()),u.lineWidth&&(r.globalAlpha=u.lineAlpha*n,r.strokeStyle="#"+("00000"+(0|c).toString(16)).substr(-6),r.stroke())}}},t.prototype.updateGraphicsTint=function(t){t._prevTint=t.tint;for(var e=(t.tint>>16&255)/255,r=(t.tint>>8&255)/255,n=(255&t.tint)/255,i=0;i>16&255)/255*e*255<<16)+((s>>8&255)/255*r*255<<8)+(255&s)/255*n*255,o._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*r*255<<8)+(255&a)/255*n*255}},t.prototype.renderPolygon=function(t,e,r){r.moveTo(t[0],t[1]);for(var n=1;n8&&void 0!==arguments[8]?arguments[8]:[],h=20,l=0,c=0,f=0,d=0,p=0;u.push(t,e);for(var v=1,y=0;v<=h;++v)y=v/h,l=1-y,c=l*l,f=c*l,d=y*y,p=d*y,u.push(f*t+3*c*y*r+3*l*d*i+p*s,f*e+3*c*y*n+3*l*d*o+p*a);return u}r.__esModule=!0,r.default=n},{}],54:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../utils"),u=t("../../const"),h=t("../../renderers/webgl/utils/ObjectRenderer"),l=n(h),c=t("../../renderers/webgl/WebGLRenderer"),f=n(c),d=t("./WebGLGraphicsData"),p=n(d),v=t("./shaders/PrimitiveShader"),y=n(v),g=t("./utils/buildPoly"),m=n(g),_=t("./utils/buildRectangle"),b=n(_),x=t("./utils/buildRoundedRectangle"),T=n(x),w=t("./utils/buildCircle"),E=n(w),S=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.graphicsDataPool=[],n.primitiveShader=null,n.gl=r.gl,n.CONTEXT_UID=0,n}return s(e,t),e.prototype.onContextChange=function(){this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.primitiveShader=new y.default(this.gl)},e.prototype.destroy=function(){l.default.prototype.destroy.call(this);for(var t=0;t32e4)&&(r=this.graphicsDataPool.pop()||new p.default(this.renderer.gl,this.primitiveShader,this.renderer.state.attribsState),r.reset(e),t.data.push(r)),r.dirty=!0,r},e}(l.default);r.default=S,f.default.registerPlugin("graphics",S)},{"../../const":43,"../../renderers/webgl/WebGLRenderer":81,"../../renderers/webgl/utils/ObjectRenderer":91,"../../utils":116,"./WebGLGraphicsData":55,"./shaders/PrimitiveShader":56,"./utils/buildCircle":57,"./utils/buildPoly":59,"./utils/buildRectangle":60,"./utils/buildRoundedRectangle":61}],55:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("pixi-gl-core"),s=n(o),a=function(){function t(e,r,n){i(this,t),this.gl=e,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=s.default.GLBuffer.createVertexBuffer(e),this.indexBuffer=s.default.GLBuffer.createIndexBuffer(e),this.dirty=!0,this.glPoints=null,this.glIndices=null,this.shader=r,this.vao=new s.default.VertexArrayObject(e,n).addIndex(this.indexBuffer).addAttribute(this.buffer,r.attributes.aVertexPosition,e.FLOAT,!1,24,0).addAttribute(this.buffer,r.attributes.aColor,e.FLOAT,!1,24,8)}return t.prototype.reset=function(){this.points.length=0,this.indices.length=0},t.prototype.upload=function(){this.glPoints=new Float32Array(this.points),this.buffer.upload(this.glPoints),this.glIndices=new Uint16Array(this.indices),this.indexBuffer.upload(this.glIndices),this.dirty=!1},t.prototype.destroy=function(){this.color=null,this.points=null,this.indices=null,this.vao.destroy(),this.buffer.destroy(),this.indexBuffer.destroy(),this.gl=null,this.buffer=null,this.indexBuffer=null,this.glPoints=null,this.glIndices=null},t}();r.default=a},{"pixi-gl-core":12}],56:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../../Shader"),u=n(a),h=function(t){function e(r){return i(this,e),o(this,t.call(this,r,["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","uniform float alpha;","uniform vec3 tint;","varying vec4 vColor;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"].join("\n"),["varying vec4 vColor;","void main(void){"," gl_FragColor = vColor;","}"].join("\n")))}return s(e,t),e}(u.default);r.default=h},{"../../../Shader":42}],57:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,o=void 0,h=void 0;t.type===a.SHAPES.CIRC?(o=r.radius,h=r.radius):(o=r.width,h=r.height);var l=Math.floor(30*Math.sqrt(r.radius))||Math.floor(15*Math.sqrt(r.width+r.height)),c=2*Math.PI/l;if(t.fill){var f=(0,u.hex2rgb)(t.fillColor),d=t.fillAlpha,p=f[0]*d,v=f[1]*d,y=f[2]*d,g=e.points,m=e.indices,_=g.length/6;m.push(_);for(var b=0;b196*p*p?(R=O-P,D=M-C,A=Math.sqrt(R*R+D*D),R/=A,D/=A,R*=p,D*=p,h.push(T-R,w-D),h.push(g,m,_,y),h.push(T+R,w+D),h.push(g,m,_,y),h.push(T-R,w-D),h.push(g,m,_,y),f++):(h.push(X,W),h.push(g,m,_,y),h.push(T-(X-T),w-(W-w)),h.push(g,m,_,y))}}b=r[2*(c-2)],x=r[2*(c-2)+1],T=r[2*(c-1)],w=r[2*(c-1)+1],O=-(x-w),M=b-T,A=Math.sqrt(O*O+M*M),O/=A,M/=A,O*=p,M*=p,h.push(T-O,w-M),h.push(g,m,_,y),h.push(T+O,w+M),h.push(g,m,_,y),l.push(d);for(var Y=0;Y=6){for(var n=[],i=t.holes,o=0;o0&&(0,s.default)(t,e)}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils"),u=t("earcut"),h=n(u)},{"../../../utils":116,"./buildLine":58,earcut:2}],60:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,o=r.width,u=r.height;if(t.fill){var h=(0,a.hex2rgb)(t.fillColor),l=t.fillAlpha,c=h[0]*l,f=h[1]*l,d=h[2]*l,p=e.points,v=e.indices,y=p.length/6;p.push(n,i),p.push(c,f,d,l),p.push(n+o,i),p.push(c,f,d,l),p.push(n,i+u),p.push(c,f,d,l),p.push(n+o,i+u),p.push(c,f,d,l),v.push(y,y,y+1,y+2,y+3,y+3)}if(t.lineWidth){var g=t.points;t.points=[n,i,n+o,i,n+o,i+u,n,i+u,n,i],(0,s.default)(t,e),t.points=g}}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils")},{"../../../utils":116,"./buildLine":58}],61:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,s=r.width,u=r.height,c=r.radius,f=[];if(f.push(n,i+c),o(n,i+u-c,n,i+u,n+c,i+u,f),o(n+s-c,i+u,n+s,i+u,n+s,i+u-c,f),o(n+s,i+c,n+s,i,n+s-c,i,f),o(n+c,i,n,i,n,i+c+1e-10,f),t.fill){for(var d=(0,l.hex2rgb)(t.fillColor),p=t.fillAlpha,v=d[0]*p,y=d[1]*p,g=d[2]*p,m=e.points,_=e.indices,b=m.length/6,x=(0,a.default)(f,null,2),T=0,w=x.length;T6&&void 0!==arguments[6]?arguments[6]:[],u=20,h=a,l=0,c=0,f=0,d=0,p=0,v=0,y=0,g=0;y<=u;++y)g=y/u,l=s(t,r,g),c=s(e,n,g),f=s(r,i,g),d=s(n,o,g),p=s(l,f,g),v=s(c,d,g),h.push(p,v);return h}r.__esModule=!0,r.default=i;var s=t("earcut"),a=n(s),u=t("./buildLine"),h=n(u),l=t("../../../utils")},{"../../../utils":116,"./buildLine":58,earcut:2}],62:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:800,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:600,r=arguments[2],n=arguments[3];return!n&&N.isWebGLSupported()?new H.default(t,e,r):new G.default(t,e,r)}r.__esModule=!0,r.Filter=r.SpriteMaskFilter=r.Quad=r.RenderTarget=r.ObjectRenderer=r.WebGLManager=r.Shader=r.CanvasRenderTarget=r.TextureUvs=r.VideoBaseTexture=r.BaseRenderTexture=r.RenderTexture=r.BaseTexture=r.Texture=r.CanvasGraphicsRenderer=r.GraphicsRenderer=r.GraphicsData=r.Graphics=r.TextStyle=r.Text=r.SpriteRenderer=r.CanvasTinter=r.CanvasSpriteRenderer=r.Sprite=r.TransformBase=r.TransformStatic=r.Transform=r.Container=r.DisplayObject=r.glCore=r.WebGLRenderer=r.CanvasRenderer=r.ticker=r.utils=void 0;var s=t("./const");Object.keys(s).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return s[t]}})});var a=t("./math");Object.keys(a).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return a[t]}})});var u=t("pixi-gl-core");Object.defineProperty(r,"glCore",{enumerable:!0,get:function(){return i(u).default}});var h=t("./display/DisplayObject");Object.defineProperty(r,"DisplayObject",{enumerable:!0,get:function(){return i(h).default}});var l=t("./display/Container");Object.defineProperty(r,"Container",{enumerable:!0,get:function(){return i(l).default}});var c=t("./display/Transform");Object.defineProperty(r,"Transform",{enumerable:!0,get:function(){return i(c).default}});var f=t("./display/TransformStatic");Object.defineProperty(r,"TransformStatic",{enumerable:!0,get:function(){return i(f).default}});var d=t("./display/TransformBase");Object.defineProperty(r,"TransformBase",{enumerable:!0,get:function(){return i(d).default}});var p=t("./sprites/Sprite");Object.defineProperty(r,"Sprite",{enumerable:!0,get:function(){return i(p).default}});var v=t("./sprites/canvas/CanvasSpriteRenderer");Object.defineProperty(r,"CanvasSpriteRenderer",{enumerable:!0,get:function(){return i(v).default}});var y=t("./sprites/canvas/CanvasTinter");Object.defineProperty(r,"CanvasTinter",{enumerable:!0,get:function(){return i(y).default}});var g=t("./sprites/webgl/SpriteRenderer");Object.defineProperty(r,"SpriteRenderer",{enumerable:!0,get:function(){return i(g).default}});var m=t("./text/Text");Object.defineProperty(r,"Text",{enumerable:!0,get:function(){return i(m).default}});var _=t("./text/TextStyle");Object.defineProperty(r,"TextStyle",{enumerable:!0,get:function(){return i(_).default}});var b=t("./graphics/Graphics");Object.defineProperty(r,"Graphics",{enumerable:!0,get:function(){return i(b).default}});var x=t("./graphics/GraphicsData");Object.defineProperty(r,"GraphicsData",{enumerable:!0,get:function(){return i(x).default}});var T=t("./graphics/webgl/GraphicsRenderer");Object.defineProperty(r,"GraphicsRenderer",{enumerable:!0,get:function(){return i(T).default}});var w=t("./graphics/canvas/CanvasGraphicsRenderer");Object.defineProperty(r,"CanvasGraphicsRenderer",{enumerable:!0,get:function(){return i(w).default}});var E=t("./textures/Texture");Object.defineProperty(r,"Texture",{enumerable:!0,get:function(){return i(E).default}});var S=t("./textures/BaseTexture");Object.defineProperty(r,"BaseTexture",{enumerable:!0,get:function(){return i(S).default}});var O=t("./textures/RenderTexture");Object.defineProperty(r,"RenderTexture",{enumerable:!0,get:function(){return i(O).default}});var M=t("./textures/BaseRenderTexture");Object.defineProperty(r,"BaseRenderTexture",{enumerable:!0,get:function(){return i(M).default}});var P=t("./textures/VideoBaseTexture");Object.defineProperty(r,"VideoBaseTexture",{enumerable:!0,get:function(){return i(P).default}});var C=t("./textures/TextureUvs");Object.defineProperty(r,"TextureUvs",{enumerable:!0,get:function(){return i(C).default}});var R=t("./renderers/canvas/utils/CanvasRenderTarget");Object.defineProperty(r,"CanvasRenderTarget",{enumerable:!0,get:function(){return i(R).default}});var D=t("./Shader");Object.defineProperty(r,"Shader",{enumerable:!0,get:function(){return i(D).default}});var A=t("./renderers/webgl/managers/WebGLManager");Object.defineProperty(r,"WebGLManager",{enumerable:!0,get:function(){return i(A).default}});var I=t("./renderers/webgl/utils/ObjectRenderer");Object.defineProperty(r,"ObjectRenderer",{enumerable:!0,get:function(){return i(I).default}});var L=t("./renderers/webgl/utils/RenderTarget");Object.defineProperty(r,"RenderTarget",{enumerable:!0,get:function(){return i(L).default}});var j=t("./renderers/webgl/utils/Quad");Object.defineProperty(r,"Quad",{enumerable:!0,get:function(){return i(j).default}});var F=t("./renderers/webgl/filters/spriteMask/SpriteMaskFilter");Object.defineProperty(r,"SpriteMaskFilter",{enumerable:!0,get:function(){return i(F).default}});var B=t("./renderers/webgl/filters/Filter");Object.defineProperty(r,"Filter",{enumerable:!0,get:function(){return i(B).default}}),r.autoDetectRenderer=o;var k=t("./utils"),N=n(k),U=t("./ticker"),X=n(U),W=t("./renderers/canvas/CanvasRenderer"),G=i(W),Y=t("./renderers/webgl/WebGLRenderer"),H=i(Y);r.utils=N,r.ticker=X,r.CanvasRenderer=G.default,r.WebGLRenderer=H.default},{"./Shader":42,"./const":43,"./display/Container":45,"./display/DisplayObject":46,"./display/Transform":47,"./display/TransformBase":48,"./display/TransformStatic":49,"./graphics/Graphics":50,"./graphics/GraphicsData":51,"./graphics/canvas/CanvasGraphicsRenderer":52,"./graphics/webgl/GraphicsRenderer":54,"./math":67,"./renderers/canvas/CanvasRenderer":74,"./renderers/canvas/utils/CanvasRenderTarget":76,"./renderers/webgl/WebGLRenderer":81,"./renderers/webgl/filters/Filter":83,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":86,"./renderers/webgl/managers/WebGLManager":90,"./renderers/webgl/utils/ObjectRenderer":91,"./renderers/webgl/utils/Quad":92,"./renderers/webgl/utils/RenderTarget":93,"./sprites/Sprite":98,"./sprites/canvas/CanvasSpriteRenderer":99,"./sprites/canvas/CanvasTinter":100,"./sprites/webgl/SpriteRenderer":102,"./text/Text":104,"./text/TextStyle":105,"./textures/BaseRenderTexture":106,"./textures/BaseTexture":107,"./textures/RenderTexture":108,"./textures/Texture":109,"./textures/TextureUvs":110,"./textures/VideoBaseTexture":111,"./ticker":113,"./utils":116,"pixi-gl-core":12}],63:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){return t<0?-1:t>0?1:0}function o(){for(var t=0;t<16;t++){var e=[];d.push(e);for(var r=0;r<16;r++)for(var n=i(u[t]*u[r]+l[t]*h[r]),o=i(h[t]*u[r]+c[t]*h[r]),s=i(u[t]*l[r]+l[t]*c[r]),p=i(h[t]*l[r]+c[t]*c[r]),v=0;v<16;v++)if(u[v]===n&&h[v]===o&&l[v]===s&&c[v]===p){e.push(v);break}}for(var y=0;y<16;y++){var g=new a.default;g.set(u[y],h[y],l[y],c[y],0,0),f.push(g)}}r.__esModule=!0;var s=t("./Matrix"),a=n(s),u=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],h=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],l=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],c=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],f=[],d=[];o();var p={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MIRROR_HORIZONTAL:12,uX:function(t){return u[t]},uY:function(t){return h[t]},vX:function(t){return l[t]},vY:function(t){return c[t]},inv:function(t){return 8&t?15&t:7&-t},add:function(t,e){return d[t][e]},sub:function(t,e){return d[t][p.inv(e)]},rotate180:function(t){return 4^t},isSwapWidthHeight:function(t){return 2===(3&t)},byDirection:function(t,e){return 2*Math.abs(t)<=Math.abs(e)?e>=0?p.S:p.N:2*Math.abs(e)<=Math.abs(t)?t>0?p.E:p.W:e>0?t>0?p.SE:p.SW:t>0?p.NE:p.NW},matrixAppendRotationInv:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=f[p.inv(e)];i.tx=r,i.ty=n,t.append(i)}};r.default=p},{"./Matrix":64}],64:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r=0&&(t.rotation+=t.rotation<=0?Math.PI:-Math.PI),t.skew.x=t.skew.y=0):(t.skew.x=o,t.skew.y=s),t.scale.x=Math.sqrt(e*e+r*r),t.scale.y=Math.sqrt(n*n+i*i),t.position.x=this.tx,t.position.y=this.ty,t},t.prototype.invert=function(){var t=this.a,e=this.b,r=this.c,n=this.d,i=this.tx,o=t*n-e*r;return this.a=n/o,this.b=-e/o,this.c=-r/o,this.d=t/o,this.tx=(r*this.ty-n*i)/o,this.ty=-(t*this.ty-e*i)/o,this},t.prototype.identity=function(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this},t.prototype.clone=function(){var e=new t;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e},t.prototype.copy=function(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t},o(t,null,[{key:"IDENTITY",get:function(){return new t}},{key:"TEMP_MATRIX",get:function(){return new t}}]),t}();r.default=u},{"./Point":66}],65:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this._x=i,this._y=o,this.cb=e,this.scope=r}return t.prototype.set=function(t,e){var r=t||0,n=e||(0!==e?r:0);this._x===r&&this._y===n||(this._x=r,this._y=n,this.cb.call(this.scope))},t.prototype.copy=function(t){this._x===t.x&&this._y===t.y||(this._x=t.x,this._y=t.y,this.cb.call(this.scope))},i(t,[{key:"x",get:function(){return this._x},set:function(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}},{key:"y",get:function(){return this._y},set:function(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}]),t}();r.default=o},{}],66:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;n(this,t),this.x=e,this.y=r}return t.prototype.clone=function(){return new t(this.x,this.y)},t.prototype.copy=function(t){this.set(t.x,t.y)},t.prototype.equals=function(t){return t.x===this.x&&t.y===this.y},t.prototype.set=function(t,e){this.x=t||0,this.y=e||(0!==e?this.x:0)},t}();r.default=i},{}],67:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./Point");Object.defineProperty(r,"Point",{enumerable:!0,get:function(){return n(i).default}});var o=t("./ObservablePoint");Object.defineProperty(r,"ObservablePoint",{enumerable:!0,get:function(){return n(o).default}});var s=t("./Matrix");Object.defineProperty(r,"Matrix",{enumerable:!0,get:function(){return n(s).default}});var a=t("./GroupD8");Object.defineProperty(r,"GroupD8",{enumerable:!0,get:function(){return n(a).default}});var u=t("./shapes/Circle");Object.defineProperty(r,"Circle",{enumerable:!0,get:function(){return n(u).default}});var h=t("./shapes/Ellipse");Object.defineProperty(r,"Ellipse",{enumerable:!0,get:function(){return n(h).default}});var l=t("./shapes/Polygon");Object.defineProperty(r,"Polygon",{enumerable:!0,get:function(){return n(l).default}});var c=t("./shapes/Rectangle");Object.defineProperty(r,"Rectangle",{enumerable:!0,get:function(){return n(c).default}});var f=t("./shapes/RoundedRectangle");Object.defineProperty(r,"RoundedRectangle",{enumerable:!0,get:function(){return n(f).default}})},{"./GroupD8":63,"./Matrix":64,"./ObservablePoint":65,"./Point":66,"./shapes/Circle":68,"./shapes/Ellipse":69,"./shapes/Polygon":70,"./shapes/Rectangle":71,"./shapes/RoundedRectangle":72}],68:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./Rectangle"),s=n(o),a=t("../../const"),u=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;i(this,t),this.x=e,this.y=r,this.radius=n,this.type=a.SHAPES.CIRC}return t.prototype.clone=function(){return new t(this.x,this.y,this.radius)},t.prototype.contains=function(t,e){if(this.radius<=0)return!1;var r=this.radius*this.radius,n=this.x-t,i=this.y-e;return n*=n,i*=i,n+i<=r},t.prototype.getBounds=function(){return new s.default(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)},t}();r.default=u},{"../../const":43,"./Rectangle":71}],69:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./Rectangle"),s=n(o),a=t("../../const"),u=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;i(this,t),this.x=e,this.y=r,this.width=n,this.height=o,this.type=a.SHAPES.ELIP}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;var r=(t-this.x)/this.width,n=(e-this.y)/this.height;return r*=r,n*=n,r+n<=1},t.prototype.getBounds=function(){return new s.default(this.x-this.width,this.y-this.height,this.width,this.height)},t}();r.default=u},{"../../const":43,"./Rectangle":71}],70:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../Point"),s=n(o),a=t("../../const"),u=function(){function t(){for(var e=arguments.length,r=Array(e),n=0;ne!=h>e&&t<(u-s)*((e-a)/(h-a))+s;l&&(r=!r)}return r},t}();r.default=u},{"../../const":43,"../Point":66}],71:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this.x=e,this.y=r,this.width=i,this.height=s,this.type=o.SHAPES.RECT}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this},t.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t=this.y&&et.x+t.width&&(this.width=t.width-this.x,this.width<0&&(this.width=0)),this.y+this.height>t.y+t.height&&(this.height=t.height-this.y,this.height<0&&(this.height=0))},t.prototype.enlarge=function(e){if(e!==t.EMPTY){var r=Math.min(this.x,e.x),n=Math.max(this.x+this.width,e.x+e.width),i=Math.min(this.y,e.y),o=Math.max(this.y+this.height,e.y+e.height);this.x=r,this.width=n-r,this.y=i,this.height=o-i}},i(t,[{key:"left",get:function(){return this.x}},{key:"right",get:function(){return this.x+this.width}},{key:"top",get:function(){return this.y}},{key:"bottom",get:function(){return this.y+this.height}}],[{key:"EMPTY",get:function(){return new t(0,0,0,0)}}]),t}();r.default=s},{"../../const":43}],72:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:20;n(this,t),this.x=e,this.y=r,this.width=o,this.height=s,this.radius=a,this.type=i.SHAPES.RREC}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height,this.radius)},t.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height)},t}();r.default=o},{"../../const":43}],73:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:{};i(this,e);var a=o(this,t.call(this,"Canvas",r,n,s));return a.type=y.RENDERER_TYPE.CANVAS,a.rootContext=a.view.getContext("2d",{alpha:a.transparent}),a.refresh=!0,a.maskManager=new l.default(a),a.smoothProperty="imageSmoothingEnabled",a.rootContext.imageSmoothingEnabled||(a.rootContext.webkitImageSmoothingEnabled?a.smoothProperty="webkitImageSmoothingEnabled":a.rootContext.mozImageSmoothingEnabled?a.smoothProperty="mozImageSmoothingEnabled":a.rootContext.oImageSmoothingEnabled?a.smoothProperty="oImageSmoothingEnabled":a.rootContext.msImageSmoothingEnabled&&(a.smoothProperty="msImageSmoothingEnabled")),a.initPlugins(),a.blendModes=(0,p.default)(),a._activeBlendMode=null,a.context=null,a.renderingToScreen=!1,a.resize(r,n),a}return s(e,t),e.prototype.render=function(t,e,r,n,i){if(this.view){this.renderingToScreen=!e,this.emit("prerender"),e?(e=e.baseTexture||e,e._canvasRenderTarget||(e._canvasRenderTarget=new f.default(e.width,e.height,e.resolution),e.source=e._canvasRenderTarget.canvas,e.valid=!0),this.context=e._canvasRenderTarget.context,this.resolution=e._canvasRenderTarget.resolution):this.context=this.rootContext;var o=this.context;if(e||(this._lastObjectRendered=t),!i){var s=t.parent,a=this._tempDisplayObjectParent.transform.worldTransform;n?n.copy(a):a.identity(),t.parent=this._tempDisplayObjectParent,t.updateTransform(),t.parent=s}o.setTransform(1,0,0,1,0,0),o.globalAlpha=1,o.globalCompositeOperation=this.blendModes[y.BLEND_MODES.NORMAL],navigator.isCocoonJS&&this.view.screencanvas&&(o.fillStyle="black",o.clear()),(void 0!==r?r:this.clearBeforeRender)&&this.renderingToScreen&&(this.transparent?o.clearRect(0,0,this.width,this.height):(o.fillStyle=this._backgroundColorString,o.fillRect(0,0,this.width,this.height)));var u=this.context;this.context=o,t.renderCanvas(this),this.context=u,this.emit("postrender")}},e.prototype.setBlendMode=function(t){this._activeBlendMode!==t&&(this.context.globalCompositeOperation=this.blendModes[t])},e.prototype.destroy=function(e){this.destroyPlugins(),t.prototype.destroy.call(this,e),this.context=null,this.refresh=!0,this.maskManager.destroy(),this.maskManager=null,this.smoothProperty=null},e.prototype.resize=function(e,r){t.prototype.resize.call(this,e,r),this.smoothProperty&&(this.rootContext[this.smoothProperty]=y.SCALE_MODES.DEFAULT===y.SCALE_MODES.LINEAR)},e}(u.default);r.default=g,v.pluginTarget.mixin(g)},{"../../const":43,"../../utils":116,"../SystemRenderer":73,"./utils/CanvasMaskManager":75,"./utils/CanvasRenderTarget":76,"./utils/mapCanvasBlendModesToPixi":78}],75:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../../const"),o=function(){function t(e){n(this,t),this.renderer=e}return t.prototype.pushMask=function(t){var e=this.renderer;e.context.save();var r=t.alpha,n=t.transform.worldTransform,i=e.resolution;e.context.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t._texture||(this.renderGraphicsShape(t),e.context.clip()),t.worldAlpha=r},t.prototype.renderGraphicsShape=function(t){var e=this.renderer.context,r=t.graphicsData.length;if(0!==r){e.beginPath();for(var n=0;nS?S:E,e.moveTo(b,x+E),e.lineTo(b,x+w-E),e.quadraticCurveTo(b,x+w,b+E,x+w),e.lineTo(b+T-E,x+w),e.quadraticCurveTo(b+T,x+w,b+T,x+w-E),e.lineTo(b+T,x+E),e.quadraticCurveTo(b+T,x,b+T-E,x),e.lineTo(b+E,x),e.quadraticCurveTo(b,x,b,x+E),e.closePath()}}}},t.prototype.popMask=function(t){t.context.restore()},t.prototype.destroy=function(){},t}();r.default=o},{"../../../const":43}],76:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:[];return(0,a.default)()?(t[o.BLEND_MODES.NORMAL]="source-over",t[o.BLEND_MODES.ADD]="lighter",t[o.BLEND_MODES.MULTIPLY]="multiply",t[o.BLEND_MODES.SCREEN]="screen",t[o.BLEND_MODES.OVERLAY]="overlay",t[o.BLEND_MODES.DARKEN]="darken",t[o.BLEND_MODES.LIGHTEN]="lighten",t[o.BLEND_MODES.COLOR_DODGE]="color-dodge",t[o.BLEND_MODES.COLOR_BURN]="color-burn",t[o.BLEND_MODES.HARD_LIGHT]="hard-light",t[o.BLEND_MODES.SOFT_LIGHT]="soft-light",t[o.BLEND_MODES.DIFFERENCE]="difference",t[o.BLEND_MODES.EXCLUSION]="exclusion",t[o.BLEND_MODES.HUE]="hue",t[o.BLEND_MODES.SATURATION]="saturate",t[o.BLEND_MODES.COLOR]="color",t[o.BLEND_MODES.LUMINOSITY]="luminosity"):(t[o.BLEND_MODES.NORMAL]="source-over",t[o.BLEND_MODES.ADD]="lighter",t[o.BLEND_MODES.MULTIPLY]="source-over",t[o.BLEND_MODES.SCREEN]="source-over",t[o.BLEND_MODES.OVERLAY]="source-over",t[o.BLEND_MODES.DARKEN]="source-over",t[o.BLEND_MODES.LIGHTEN]="source-over",t[o.BLEND_MODES.COLOR_DODGE]="source-over",t[o.BLEND_MODES.COLOR_BURN]="source-over",t[o.BLEND_MODES.HARD_LIGHT]="source-over",t[o.BLEND_MODES.SOFT_LIGHT]="source-over",t[o.BLEND_MODES.DIFFERENCE]="source-over",t[o.BLEND_MODES.EXCLUSION]="source-over",t[o.BLEND_MODES.HUE]="source-over",t[o.BLEND_MODES.SATURATION]="source-over",t[o.BLEND_MODES.COLOR]="source-over",t[o.BLEND_MODES.LUMINOSITY]="source-over"),t}r.__esModule=!0,r.default=i;var o=t("../../../const"),s=t("./canUseNewCanvasBlendModes"),a=n(s)},{"../../../const":43,"./canUseNewCanvasBlendModes":77}],79:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=function(){function t(e){n(this,t),this.renderer=e,this.count=0,this.checkCount=0,this.maxIdle=3600,this.checkCountMax=600,this.mode=i.GC_MODES.DEFAULT}return t.prototype.update=function(){this.count++,this.mode!==i.GC_MODES.MANUAL&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run()))},t.prototype.run=function(){for(var t=this.renderer.textureManager,e=t._managedTextures,r=!1,n=0;nthis.maxIdle&&(t.destroyTexture(i,!0),e[n]=null,r=!0)}if(r){for(var o=0,s=0;s=0;r--)this.unload(t.children[r])},t}();r.default=o},{"../../const":43}],80:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("pixi-gl-core"),s=t("../../const"),a=t("./utils/RenderTarget"),u=n(a),h=t("../../utils"),l=function(){function t(e){i(this,t),this.renderer=e,this.gl=e.gl,this._managedTextures=[]}return t.prototype.bindTexture=function(){},t.prototype.getTexture=function(){},t.prototype.updateTexture=function(t){t=t.baseTexture||t;var e=!!t._glRenderTargets;if(!t.hasLoaded)return null;var r=t._glTextures[this.renderer.CONTEXT_UID];if(r)e?t._glRenderTargets[this.renderer.CONTEXT_UID].resize(t.width,t.height):r.upload(t.source);else{if(e){var n=new u.default(this.gl,t.width,t.height,t.scaleMode,t.resolution);n.resize(t.width,t.height),t._glRenderTargets[this.renderer.CONTEXT_UID]=n,r=n.texture}else r=new o.GLTexture(this.gl),r.premultiplyAlpha=!0,r.upload(t.source);t._glTextures[this.renderer.CONTEXT_UID]=r,t.on("update",this.updateTexture,this),t.on("dispose",this.destroyTexture,this),this._managedTextures.push(t),t.isPowerOfTwo?(t.mipmap&&r.enableMipmap(),t.wrapMode===s.WRAP_MODES.CLAMP?r.enableWrapClamp():t.wrapMode===s.WRAP_MODES.REPEAT?r.enableWrapRepeat():r.enableWrapMirrorRepeat()):r.enableWrapClamp(),t.scaleMode===s.SCALE_MODES.NEAREST?r.enableNearestScaling():r.enableLinearScaling()}return r},t.prototype.destroyTexture=function(t,e){if(t=t.baseTexture||t,t.hasLoaded&&t._glTextures[this.renderer.CONTEXT_UID]&&(t._glTextures[this.renderer.CONTEXT_UID].destroy(),t.off("update",this.updateTexture,this),t.off("dispose",this.destroyTexture,this),delete t._glTextures[this.renderer.CONTEXT_UID],!e)){var r=this._managedTextures.indexOf(t);r!==-1&&(0,h.removeItems)(this._managedTextures,r,1)}},t.prototype.removeAll=function(){for(var t=0;t2&&void 0!==arguments[2]?arguments[2]:{};i(this,e);var a=o(this,t.call(this,"WebGL",r,n,s));return a.type=A.RENDERER_TYPE.WEBGL,a.handleContextLost=a.handleContextLost.bind(a),a.handleContextRestored=a.handleContextRestored.bind(a),a.view.addEventListener("webglcontextlost",a.handleContextLost,!1),a.view.addEventListener("webglcontextrestored",a.handleContextRestored,!1),a._contextOptions={alpha:a.transparent,antialias:s.antialias,premultipliedAlpha:a.transparent&&"notMultiplied"!==a.transparent,stencil:!0,preserveDrawingBuffer:s.preserveDrawingBuffer},a._backgroundColorRgba[3]=a.transparent?0:1,a.maskManager=new l.default(a),a.stencilManager=new f.default(a),a.emptyRenderer=new m.default(a),a.currentRenderer=a.emptyRenderer,a.initPlugins(),s.context&&(0,P.default)(s.context),a.gl=s.context||D.default.createContext(a.view,a._contextOptions),a.CONTEXT_UID=I++,a.state=new E.default(a.gl),a.renderingToScreen=!0,a._initContext(),a.filterManager=new p.default(a),a.drawModes=(0,O.default)(a.gl),a._activeShader=null,a._activeRenderTarget=null,a._activeTextureLocation=999,a._activeTexture=null,a.setBlendMode(0),a}return s(e,t),e.prototype._initContext=function(){var t=this.gl;t.isContextLost()&&t.getExtension("WEBGL_lose_context")&&t.getExtension("WEBGL_lose_context").restoreContext(),this.textureManager=new b.default(this),this.textureGC=new T.default(this),this.state.resetToDefault(),this.rootRenderTarget=new y.default(t,this.width,this.height,null,this.resolution,(!0)),this.rootRenderTarget.clearColor=this._backgroundColorRgba,this.bindRenderTarget(this.rootRenderTarget),this.emit("context",t),this.resize(this.width,this.height)},e.prototype.render=function(t,e,r,n,i){if(this.renderingToScreen=!e,this.emit("prerender"),this.gl&&!this.gl.isContextLost()){if(e||(this._lastObjectRendered=t),!i){var o=t.parent;t.parent=this._tempDisplayObjectParent,t.updateTransform(),t.parent=o}this.bindRenderTexture(e,n),this.currentRenderer.start(),(void 0!==r?r:this.clearBeforeRender)&&this._activeRenderTarget.clear(),t.renderWebGL(this),this.currentRenderer.flush(),this.textureGC.update(),this.emit("postrender")}},e.prototype.setObjectRenderer=function(t){this.currentRenderer!==t&&(this.currentRenderer.stop(),this.currentRenderer=t,this.currentRenderer.start())},e.prototype.flush=function(){this.setObjectRenderer(this.emptyRenderer)},e.prototype.resize=function(t,e){u.default.prototype.resize.call(this,t,e),this.rootRenderTarget.resize(t,e),this._activeRenderTarget===this.rootRenderTarget&&(this.rootRenderTarget.activate(),this._activeShader&&(this._activeShader.uniforms.projectionMatrix=this.rootRenderTarget.projectionMatrix.toArray(!0)))},e.prototype.setBlendMode=function(t){this.state.setBlendMode(t)},e.prototype.clear=function(t){this._activeRenderTarget.clear(t)},e.prototype.setTransform=function(t){this._activeRenderTarget.transform=t},e.prototype.bindRenderTexture=function(t,e){var r=void 0;if(t){var n=t.baseTexture,i=this.gl;n._glRenderTargets[this.CONTEXT_UID]?(this._activeTextureLocation=n._id,i.activeTexture(i.TEXTURE0+n._id),i.bindTexture(i.TEXTURE_2D,null)):(this.textureManager.updateTexture(n),i.bindTexture(i.TEXTURE_2D,null)),r=n._glRenderTargets[this.CONTEXT_UID],r.setFrame(t.frame)}else r=this.rootRenderTarget;return r.transform=e,this.bindRenderTarget(r),this},e.prototype.bindRenderTarget=function(t){return t!==this._activeRenderTarget&&(this._activeRenderTarget=t,t.activate(),this._activeShader&&(this._activeShader.uniforms.projectionMatrix=t.projectionMatrix.toArray(!0)),this.stencilManager.setMaskStack(t.stencilMaskStack)),this},e.prototype.bindShader=function(t){return this._activeShader!==t&&(this._activeShader=t,t.bind(),t.uniforms.projectionMatrix=this._activeRenderTarget.projectionMatrix.toArray(!0)),this},e.prototype.bindTexture=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;t=t.baseTexture||t;var r=this.gl;return this._activeTextureLocation!==e&&(this._activeTextureLocation=e,r.activeTexture(r.TEXTURE0+e)),this._activeTexture=t,t._glTextures[this.CONTEXT_UID]?(t.touched=this.textureGC.count,t._glTextures[this.CONTEXT_UID].bind()):this.textureManager.updateTexture(t),this},e.prototype.createVao=function(){return new D.default.VertexArrayObject(this.gl,this.state.attribState)},e.prototype.reset=function(){return this.setObjectRenderer(this.emptyRenderer),this._activeShader=null,this._activeRenderTarget=this.rootRenderTarget,this._activeTextureLocation=999,this._activeTexture=null,this.rootRenderTarget.activate(),this.state.resetToDefault(),this},e.prototype.handleContextLost=function(t){t.preventDefault()},e.prototype.handleContextRestored=function(){this._initContext(),this.textureManager.removeAll()},e.prototype.destroy=function(e){this.destroyPlugins(),this.view.removeEventListener("webglcontextlost",this.handleContextLost),this.view.removeEventListener("webglcontextrestored",this.handleContextRestored),this.textureManager.destroy(),t.prototype.destroy.call(this,e),this.uid=0,this.maskManager.destroy(), +this.stencilManager.destroy(),this.filterManager.destroy(),this.maskManager=null,this.filterManager=null,this.textureManager=null,this.currentRenderer=null,this.handleContextLost=null,this.handleContextRestored=null,this._contextOptions=null,this.gl.useProgram(null),this.gl.getExtension("WEBGL_lose_context")&&this.gl.getExtension("WEBGL_lose_context").loseContext(),this.gl=null},e}(u.default);r.default=L,C.pluginTarget.mixin(L)},{"../../const":43,"../../utils":116,"../SystemRenderer":73,"./TextureGarbageCollector":79,"./TextureManager":80,"./WebGLState":82,"./managers/FilterManager":87,"./managers/MaskManager":88,"./managers/StencilManager":89,"./utils/ObjectRenderer":91,"./utils/RenderTarget":93,"./utils/mapWebGLDrawModesToPixi":96,"./utils/validateContext":97,"pixi-gl-core":12}],82:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./utils/mapWebGLBlendModesToPixi"),s=n(o),a=0,u=1,h=2,l=3,c=4,f=function(){function t(e){i(this,t),this.activeState=new Uint8Array(16),this.defaultState=new Uint8Array(16),this.defaultState[0]=1,this.stackIndex=0,this.stack=[],this.gl=e,this.maxAttribs=e.getParameter(e.MAX_VERTEX_ATTRIBS),this.attribState={tempAttribState:new Array(this.maxAttribs),attribState:new Array(this.maxAttribs)},this.blendModes=(0,s.default)(e),this.nativeVaoExtension=e.getExtension("OES_vertex_array_object")||e.getExtension("MOZ_OES_vertex_array_object")||e.getExtension("WEBKIT_OES_vertex_array_object")}return t.prototype.push=function(){var t=this.stack[++this.stackIndex];t||(t=this.stack[this.stackIndex]=new Uint8Array(16));for(var e=0;e 0.5)"," {"," color = vec4(1.0, 0.0, 0.0, 1.0);"," }"," else"," {"," color = vec4(0.0, 1.0, 0.0, 1.0);"," }"," gl_FragColor = mix(sample, masky, 0.5);"," gl_FragColor *= sample.a;","}"].join("\n")}}]),t}();r.default=c},{"../../../const":43,"../../../utils":116,"./extractUniformsFromSrc":84}],84:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e,r){var n=o(t,r),i=o(e,r);return Object.assign(n,i)}function o(t){for(var e=new RegExp("^(projectionMatrix|uSampler|filterArea)$"),r={},n=void 0,i=t.replace(/\s+/g," ").split(/\s*;\s*/),o=0;o-1){var a=s.split(" "),h=a[1],l=a[2],c=1;l.indexOf("[")>-1&&(n=l.split(/\[|]/),l=n[0],c*=Number(n[1])),l.match(e)||(r[l]={value:u(h,c),name:l,type:h})}}return r}r.__esModule=!0,r.default=i;var s=t("pixi-gl-core"),a=n(s),u=a.default.shader.defaultValue},{"pixi-gl-core":12}],85:[function(t,e,r){"use strict";function n(t,e,r){var n=t.identity();return n.translate(e.x/r.width,e.y/r.height),n.scale(r.width,r.height),n}function i(t,e,r){var n=t.identity();n.translate(e.x/r.width,e.y/r.height);var i=r.width/e.width,o=r.height/e.height;return n.scale(i,o),n}function o(t,e,r,n){var i=n.worldTransform.copy(s.Matrix.TEMP_MATRIX),o=n._texture.baseTexture,a=t.identity(),u=r.height/r.width;a.translate(e.x/r.width,e.y/r.height),a.scale(1,u);var h=r.width/o.width,l=r.height/o.height;return i.tx/=o.width*h,i.ty/=o.width*h,i.invert(),a.prepend(i),a.scale(1,1/u),a.scale(h,l),a.translate(n.anchor.x,n.anchor.y),a}r.__esModule=!0,r.calculateScreenSpaceMatrix=n,r.calculateNormalizedScreenSpaceMatrix=i,r.calculateSpriteMatrix=o;var s=t("../../../math")},{"../../../math":67}],86:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../Filter"),u=n(a),h=t("../../../../math"),l=function(t){function e(r){i(this,e);var n=new h.Matrix,s=o(this,t.call(this,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n","#define GLSLIFY 1\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n"));return r.renderable=!1,s.maskSprite=r,s.maskMatrix=n,s}return s(e,t),e.prototype.apply=function(t,e,r){var n=this.maskSprite;this.uniforms.mask=n._texture,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,n),this.uniforms.alpha=n.worldAlpha,t.applyFilter(this,e,r)},e}(u.default);r.default=l},{"../../../../math":67,"../Filter":83}],87:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var u=t("./WebGLManager"),h=i(u),l=t("../utils/RenderTarget"),c=i(l),f=t("../utils/Quad"),d=i(f),p=t("../../../math"),v=t("../../../Shader"),y=i(v),g=t("../filters/filterTransforms"),m=n(g),_=t("bit-twiddle"),b=i(_),x=function t(){a(this,t),this.renderTarget=null,this.sourceFrame=new p.Rectangle,this.destinationFrame=new p.Rectangle,this.filters=[],this.target=null,this.resolution=1},T=function(t){function e(r){a(this,e);var n=o(this,t.call(this,r));return n.gl=n.renderer.gl,n.quad=new d.default(n.gl,r.state.attribState),n.shaderCache={},n.pool={},n.filterData=null,n}return s(e,t),e.prototype.pushFilter=function(t,e){var r=this.renderer,n=this.filterData;if(!n){n=this.renderer._activeRenderTarget.filterStack;var i=new x;i.sourceFrame=i.destinationFrame=this.renderer._activeRenderTarget.size,i.renderTarget=r._activeRenderTarget,this.renderer._activeRenderTarget.filterData=n={index:0,stack:[i]},this.filterData=n}var o=n.stack[++n.index];o||(o=n.stack[n.index]=new x);var s=e[0].resolution,a=0|e[0].padding,u=t.filterArea||t.getBounds(!0),h=o.sourceFrame,l=o.destinationFrame;h.x=(u.x*s|0)/s,h.y=(u.y*s|0)/s,h.width=(u.width*s|0)/s,h.height=(u.height*s|0)/s,n.stack[0].renderTarget.transform||h.fit(n.stack[0].destinationFrame),h.pad(a),l.width=h.width,l.height=h.height;var c=this.getPotRenderTarget(r.gl,h.width,h.height,s);o.target=t,o.filters=e,o.resolution=s,o.renderTarget=c,c.setFrame(l,h),r.bindRenderTarget(c),r.clear()},e.prototype.popFilter=function(){var t=this.filterData,e=t.stack[t.index-1],r=t.stack[t.index];this.quad.map(r.renderTarget.size,r.sourceFrame).upload();var n=r.filters;if(1===n.length)n[0].apply(this,r.renderTarget,e.renderTarget,!1),this.freePotRenderTarget(r.renderTarget);else{var i=r.renderTarget,o=this.getPotRenderTarget(this.renderer.gl,r.sourceFrame.width,r.sourceFrame.height,r.resolution);o.setFrame(r.destinationFrame,r.sourceFrame);var s=0;for(s=0;s0&&(e+="\nelse "),r1&&void 0!==arguments[1]?arguments[1]:[];return e[i.BLEND_MODES.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.ADD]=[t.ONE,t.DST_ALPHA],e[i.BLEND_MODES.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SCREEN]=[t.ONE,t.ONE_MINUS_SRC_COLOR],e[i.BLEND_MODES.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":43}],96:[function(t,e,r){"use strict";function n(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e[i.DRAW_MODES.POINTS]=t.POINTS,e[i.DRAW_MODES.LINES]=t.LINES,e[i.DRAW_MODES.LINE_LOOP]=t.LINE_LOOP,e[i.DRAW_MODES.LINE_STRIP]=t.LINE_STRIP,e[i.DRAW_MODES.TRIANGLES]=t.TRIANGLES,e[i.DRAW_MODES.TRIANGLE_STRIP]=t.TRIANGLE_STRIP,e[i.DRAW_MODES.TRIANGLE_FAN]=t.TRIANGLE_FAN,e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":43}],97:[function(t,e,r){"use strict";function n(t){var e=t.getContextAttributes();e.stencil||console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly")}r.__esModule=!0,r.default=n},{}],98:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rn&&v.xi&&v.y>16)+(65280&t)+((255&t)<<16)}},{key:"texture",get:function(){return this._texture},set:function(t){this._texture!==t&&(this._texture=t,this.cachedTint=16777215,this._textureID=-1,t&&(t.baseTexture.hasLoaded?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}]),e}(p.default);r.default=y},{"../const":43,"../display/Container":45,"../math":67,"../textures/Texture":109,"../utils":116}],99:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../renderers/canvas/CanvasRenderer"),s=n(o),a=t("../../const"),u=t("../../math"),h=t("./CanvasTinter"),l=n(h),c=new u.Matrix,f=function(){function t(e){i(this,t),this.renderer=e}return t.prototype.render=function(t){var e=t._texture,r=this.renderer,n=e._frame.width,i=e._frame.height,o=t.transform.worldTransform,s=0,h=0;if(!(e.orig.width<=0||e.orig.height<=0)&&e.baseTexture.source&&(r.setBlendMode(t.blendMode),e.valid)){r.context.globalAlpha=t.worldAlpha;var f=e.baseTexture.scaleMode===a.SCALE_MODES.LINEAR;r.smoothProperty&&r.context[r.smoothProperty]!==f&&(r.context[r.smoothProperty]=f),e.trim?(s=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,h=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(s=(.5-t.anchor.x)*e.orig.width,h=(.5-t.anchor.y)*e.orig.height),e.rotate&&(o.copy(c),o=c,u.GroupD8.matrixAppendRotationInv(o,e.rotate,s,h),s=0,h=0),s-=n/2,h-=i/2,r.roundPixels?(r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution|0,o.ty*r.resolution|0),s=0|s,h=0|h):r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution,o.ty*r.resolution);var d=e.baseTexture.resolution;16777215!==t.tint?(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=l.default.getTintedTexture(t,t.tint)),r.context.drawImage(t.tintedTexture,0,0,n*d,i*d,s*r.resolution,h*r.resolution,n*r.resolution,i*r.resolution)):r.context.drawImage(e.baseTexture.source,e._frame.x*d,e._frame.y*d,n*d,i*d,s*r.resolution,h*r.resolution,n*r.resolution,i*r.resolution)}},t.prototype.destroy=function(){this.renderer=null},t}();r.default=f,s.default.registerPlugin("sprite",f)},{"../../const":43,"../../math":67,"../../renderers/canvas/CanvasRenderer":74,"./CanvasTinter":100}],100:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("../../utils"),o=t("../../renderers/canvas/utils/canUseNewCanvasBlendModes"),s=n(o),a={getTintedTexture:function(t,e){var r=t.texture;e=a.roundColor(e);var n="#"+("00000"+(0|e).toString(16)).substr(-6);if(r.tintCache=r.tintCache||{},r.tintCache[n])return r.tintCache[n];var i=a.canvas||document.createElement("canvas");if(a.tintMethod(r,e,i),a.convertTintToImage){var o=new Image;o.src=i.toDataURL(),r.tintCache[n]=o}else r.tintCache[n]=i,a.canvas=null;return i},tintWithMultiply:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=i.width,r.height=i.height,n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="multiply",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},tintWithOverlay:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=i.width,r.height=i.height,n.globalCompositeOperation="copy",n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},tintWithPerPixel:function(t,e,r){var n=r.getContext("2d"),o=t._frame.clone(),s=t.baseTexture.resolution;o.x*=s,o.y*=s,o.width*=s,o.height*=s,r.width=o.width,r.height=o.height,n.globalCompositeOperation="copy",n.drawImage(t.baseTexture.source,o.x,o.y,o.width,o.height,0,0,o.width,o.height);for(var a=(0,i.hex2rgb)(e),u=a[0],h=a[1],l=a[2],c=n.getImageData(0,0,o.width,o.height),f=c.data,d=0;d=this.size&&this.flush(),t.texture._uvs&&(this.sprites[this.currentIndex++]=t)},e.prototype.flush=function(){if(0!==this.currentIndex){var t=this.renderer.gl,e=w.default.nextPow2(this.currentIndex),r=w.default.log2(e),n=this.buffers[r],i=this.sprites,o=this.groups,s=n.float32View,a=n.uint32View,u=0,h=void 0,l=void 0,c=1,f=0,d=o[0],v=void 0,y=void 0,g=void 0,m=void 0,_=i[0].blendMode,b=void 0;d.textureCount=0,d.start=0,d.blend=_,E++;var T=void 0;for(T=0;T0&&(e+="\nelse "),r0?(this.context.shadowColor=e.dropShadowColor,this.context.shadowBlur=e.dropShadowBlur):this.context.fillStyle=e.dropShadowColor;for(var v=Math.cos(e.dropShadowAngle)*e.dropShadowDistance,y=Math.sin(e.dropShadowAngle)*e.dropShadowDistance,g=0;g3&&void 0!==arguments[3]&&arguments[3],i=this._style,o=i.letterSpacing;if(0===o)return void(n?this.context.strokeText(t,e,r):this.context.fillText(t,e,r));for(var s=String.prototype.split.call(t,""),a=e,u=0,h="";us;--c){for(var v=0;vn)for(var h=s[a].split(""),l=0;lo?(e+="\n"+h[l],o=n-c):(0===l&&(e+=" "),e+=h[l],o-=c)}else{var f=u+this.context.measureText(" ").width;0===a||f>o?(a>0&&(e+="\n"),e+=s[a],o=n-u):(o-=f,e+=" "+s[a])}}i0&&void 0!==arguments[0]?arguments[0]:100,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,s=arguments[2],a=arguments[3];i(this,e);var u=o(this,t.call(this,null,s));return u.resolution=a||h.RESOLUTION,u.width=r,u.height=n,u.realWidth=u.width*u.resolution,u.realHeight=u.height*u.resolution,u.scaleMode=s||h.SCALE_MODES.DEFAULT,u.hasLoaded=!0,u._glRenderTargets={},u._canvasRenderTarget=null,u.valid=!1,u}return s(e,t),e.prototype.resize=function(t,e){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.realWidth=this.width*this.resolution,this.realHeight=this.height*this.resolution,this.valid&&this.emit("update",this))},e.prototype.destroy=function(){t.prototype.destroy.call(this,!0),this.renderer=null},e}(u.default);r.default=l},{"../const":43,"./BaseTexture":107}],107:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u=t("../utils"),h=t("../const"),l=t("eventemitter3"),c=n(l),f=t("../utils/determineCrossOrigin"),d=n(f),p=t("bit-twiddle"),v=n(p),y=function(t){function e(r,n,s){i(this,e);var a=o(this,t.call(this));return a.uid=(0,u.uid)(),a.touched=0,a.resolution=s||h.RESOLUTION,a.width=100,a.height=100,a.realWidth=100,a.realHeight=100,a.scaleMode=n||h.SCALE_MODES.DEFAULT,a.hasLoaded=!1,a.isLoading=!1,a.source=null,a.origSource=null,a.imageType=null,a.sourceScale=1,a.premultipliedAlpha=!0,a.imageUrl=null,a.isPowerOfTwo=!1,a.mipmap=h.MIPMAP_TEXTURES,a.wrapMode=h.WRAP_MODES.DEFAULT,a._glTextures={},a._enabled=0,a._id=0,r&&a.loadSource(r),a}return s(e,t),e.prototype.update=function(){"svg"!==this.imageType&&(this.realWidth=this.source.naturalWidth||this.source.videoWidth||this.source.width,this.realHeight=this.source.naturalHeight||this.source.videoHeight||this.source.height,this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=v.default.isPow2(this.realWidth)&&v.default.isPow2(this.realHeight)),this.emit("update",this)},e.prototype.loadSource=function(t){var e=this,r=this.isLoading;this.hasLoaded=!1,this.isLoading=!1,r&&this.source&&(this.source.onload=null,this.source.onerror=null);var n=!this.source;if(this.source=t,(t.src&&t.complete||t.getContext)&&t.width&&t.height)this._updateImageType(),"svg"===this.imageType?this._loadSvgSource():this._sourceLoaded(), +n&&this.emit("loaded",this);else if(!t.getContext){var i=function(){e.isLoading=!0;var n=e;if(t.onload=function(){if(n._updateImageType(),t.onload=null,t.onerror=null,n.isLoading)return n.isLoading=!1,n._sourceLoaded(),"svg"===n.imageType?void n._loadSvgSource():void n.emit("loaded",n)},t.onerror=function(){t.onload=null,t.onerror=null,n.isLoading&&(n.isLoading=!1,n.emit("error",n))},t.complete&&t.src){if(t.onload=null,t.onerror=null,"svg"===n.imageType)return n._loadSvgSource(),{v:void 0};e.isLoading=!1,t.width&&t.height?(e._sourceLoaded(),r&&e.emit("loaded",e)):r&&e.emit("error",e)}}();if("object"===("undefined"==typeof i?"undefined":a(i)))return i.v}},e.prototype._updateImageType=function(){if(this.imageUrl){var t=(0,u.decomposeDataUri)(this.imageUrl),e=void 0;if(t&&"image"===t.mediaType){var r=t.subType.split("+")[0];if(e=(0,u.getUrlFileExtension)("."+r),!e)throw new Error("Invalid image type in data URI.")}else if(e=(0,u.getUrlFileExtension)(this.imageUrl),!e)throw new Error("Invalid image type in URL.");this.imageType=e}},e.prototype._loadSvgSource=function(){if("svg"===this.imageType){var t=(0,u.decomposeDataUri)(this.imageUrl);t?this._loadSvgSourceUsingDataUri(t):this._loadSvgSourceUsingXhr()}},e.prototype._loadSvgSourceUsingDataUri=function(t){var e=void 0;if("base64"===t.encoding){if(!atob)throw new Error("Your browser doesn't support base64 conversions.");e=atob(t.data)}else e=t.data;this._loadSvgSourceUsingString(e)},e.prototype._loadSvgSourceUsingXhr=function(){var t=this,e=new XMLHttpRequest;e.onload=function(){if(e.readyState!==e.DONE||200!==e.status)throw new Error("Failed to load SVG using XHR.");t._loadSvgSourceUsingString(e.response)},e.onerror=function(){return t.emit("error",t)},e.open("GET",this.imageUrl,!0),e.send()},e.prototype._loadSvgSourceUsingString=function(t){var e=(0,u.getSvgSize)(t),r=e.width,n=e.height;if(!r||!n)throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them.");this.realWidth=Math.round(r*this.sourceScale),this.realHeight=Math.round(n*this.sourceScale),this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=v.default.isPow2(this.realWidth)&&v.default.isPow2(this.realHeight);var i=document.createElement("canvas");i.width=this.realWidth,i.height=this.realHeight,i._pixiId="canvas_"+(0,u.uid)(),i.getContext("2d").drawImage(this.source,0,0,r,n,0,0,this.realWidth,this.realHeight),this.origSource=this.source,this.source=i,u.BaseTextureCache[i._pixiId]=this,this.isLoading=!1,this._sourceLoaded(),this.emit("loaded",this)},e.prototype._sourceLoaded=function(){this.hasLoaded=!0,this.update()},e.prototype.destroy=function(){this.imageUrl&&(delete u.BaseTextureCache[this.imageUrl],delete u.TextureCache[this.imageUrl],this.imageUrl=null,navigator.isCocoonJS||(this.source.src="")),this.source&&this.source._pixiId&&delete u.BaseTextureCache[this.source._pixiId],this.source=null,this.dispose()},e.prototype.dispose=function(){this.emit("dispose",this)},e.prototype.updateSourceImage=function(t){this.source.src=t,this.loadSource(this.source)},e.fromImage=function(t,r,n,i){var o=u.BaseTextureCache[t];if(!o){var s=new Image;void 0===r&&0!==t.indexOf("data:")&&(s.crossOrigin=(0,d.default)(t)),o=new e(s,n),o.imageUrl=t,i&&(o.sourceScale=i),o.resolution=(0,u.getResolutionOfUrl)(t),s.src=t,u.BaseTextureCache[t]=o}return o},e.fromCanvas=function(t,r){t._pixiId||(t._pixiId="canvas_"+(0,u.uid)());var n=u.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),u.BaseTextureCache[t._pixiId]=n),n},e}(c.default);r.default=y},{"../const":43,"../utils":116,"../utils/determineCrossOrigin":115,"bit-twiddle":1,eventemitter3:3}],108:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("./BaseRenderTexture"),u=n(a),h=t("./Texture"),l=n(h),c=function(t){function e(r,n){i(this,e);var s=null;if(!(r instanceof u.default)){var a=arguments[1],h=arguments[2],l=arguments[3]||0,c=arguments[4]||1;console.warn("Please use RenderTexture.create("+a+", "+h+") instead of the ctor directly."),s=arguments[0],n=null,r=new u.default(a,h,l,c)}var f=o(this,t.call(this,r,n));return f.legacyRenderer=s,f.valid=!0,f._updateUvs(),f}return s(e,t),e.prototype.resize=function(t,e,r){this.valid=t>0&&e>0,this._frame.width=this.orig.width=t,this._frame.height=this.orig.height=e,r||this.baseTexture.resize(t,e),this._updateUvs()},e.create=function(t,r,n,i){return new e(new u.default(t,r,n,i))},e}(l.default);r.default=c},{"./BaseRenderTexture":106,"./Texture":109}],109:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rthis.baseTexture.width||t.y+t.height>this.baseTexture.height)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);this.valid=t&&t.width&&t.height&&this.baseTexture.hasLoaded,this.trim||this.rotate||(this.orig=t),this.valid&&this._updateUvs()}},{key:"rotate",get:function(){return this._rotate},set:function(t){this._rotate=t,this.valid&&this._updateUvs()}},{key:"width",get:function(){return this.orig?this.orig.width:0}},{key:"height",get:function(){return this.orig?this.orig.height:0}}]),e}(v.default);r.default=m,m.EMPTY=new m(new h.default),m.EMPTY.destroy=function(){},m.EMPTY.on=function(){},m.EMPTY.once=function(){},m.EMPTY.emit=function(){}},{"../math":67,"../utils":116,"./BaseTexture":107,"./TextureUvs":110,"./VideoBaseTexture":111,eventemitter3:3}],110:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../math/GroupD8"),s=n(o),a=function(){function t(){i(this,t),this.x0=0,this.y0=0,this.x1=1,this.y1=0,this.x2=1,this.y2=1,this.x3=0,this.y3=1,this.uvsUint32=new Uint32Array(4)}return t.prototype.set=function(t,e,r){var n=e.width,i=e.height;if(r){var o=t.width/2/n,a=t.height/2/i,u=t.x/n+o,h=t.y/i+a;r=s.default.add(r,s.default.NW),this.x0=u+o*s.default.uX(r),this.y0=h+a*s.default.uY(r),r=s.default.add(r,2),this.x1=u+o*s.default.uX(r),this.y1=h+a*s.default.uY(r),r=s.default.add(r,2),this.x2=u+o*s.default.uX(r),this.y2=h+a*s.default.uY(r),r=s.default.add(r,2),this.x3=u+o*s.default.uX(r),this.y3=h+a*s.default.uY(r)}else this.x0=t.x/n,this.y0=t.y/i,this.x1=(t.x+t.width)/n,this.y1=t.y/i,this.x2=(t.x+t.width)/n,this.y2=(t.y+t.height)/i,this.x3=t.x/n,this.y3=(t.y+t.height)/i;this.uvsUint32[0]=(65535*this.y0&65535)<<16|65535*this.x0&65535,this.uvsUint32[1]=(65535*this.y1&65535)<<16|65535*this.x1&65535,this.uvsUint32[2]=(65535*this.y2&65535)<<16|65535*this.x2&65535,this.uvsUint32[3]=(65535*this.y3&65535)<<16|65535*this.x3&65535},t}();r.default=a},{"../math/GroupD8":63}],111:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function u(t,e){e||(e="video/"+t.substr(t.lastIndexOf(".")+1));var r=document.createElement("source");return r.src=t,r.type=e,r}r.__esModule=!0;var h=function(){function t(t,e){for(var r=0;r0&&t.paused===!1&&t.ended===!1&&t.readyState>2},e.prototype._isSourceReady=function(){return 3===this.source.readyState||4===this.source.readyState},e.prototype._onPlayStart=function(){this.hasLoaded||this._onCanPlay(),!this._isAutoUpdating&&this.autoUpdate&&(p.shared.add(this.update,this),this._isAutoUpdating=!0)},e.prototype._onPlayStop=function(){this._isAutoUpdating&&(p.shared.remove(this.update,this),this._isAutoUpdating=!1)},e.prototype._onCanPlay=function(){this.hasLoaded=!0,this.source&&(this.source.removeEventListener("canplay",this._onCanPlay),this.source.removeEventListener("canplaythrough",this._onCanPlay),this.width=this.source.videoWidth,this.height=this.source.videoHeight,this.__loaded||(this.__loaded=!0,this.emit("loaded",this)),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.source.play())},e.prototype.destroy=function(){this._isAutoUpdating&&p.shared.remove(this.update,this),this.source&&this.source._pixiId&&(delete f.BaseTextureCache[this.source._pixiId],delete this.source._pixiId),t.prototype.destroy.call(this)},e.fromVideo=function(t,r){t._pixiId||(t._pixiId="video_"+(0,f.uid)());var n=f.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),f.BaseTextureCache[t._pixiId]=n),n},e.fromUrl=function(t,r){var n=document.createElement("video");if(n.setAttribute("webkit-playsinline",""),n.setAttribute("playsinline",""),Array.isArray(t))for(var i=0;i0&&void 0!==arguments[0]?arguments[0]:performance.now(),e=void 0;t>this.lastTime?(e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),this.deltaTime=e*s.TARGET_FPMS*this.speed,this._emitter.emit(h,this.deltaTime)):this.deltaTime=this.elapsedMS=0,this.lastTime=t},o(t,[{key:"FPS",get:function(){return 1e3/this.elapsedMS}},{key:"minFPS",get:function(){return 1e3/this._maxElapsedMS},set:function(t){var e=Math.min(Math.max(0,t)/1e3,s.TARGET_FPMS);this._maxElapsedMS=1/e}}]),t}();r.default=l},{"../const":43,eventemitter3:3}],113:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.Ticker=r.shared=void 0;var i=t("./Ticker"),o=n(i),s=new o.default;s.autoStart=!0,r.shared=s,r.Ticker=o.default},{"./Ticker":112}],114:[function(t,e,r){"use strict";function n(t){for(var e=6*t,r=new Uint16Array(e),n=0,i=0;n1&&void 0!==arguments[1]?arguments[1]:window.location;if(0===t.indexOf("data:"))return"";e=e||window.location,a||(a=document.createElement("a")),a.href=t,t=s.default.parse(a.href);var r=!t.port&&""===e.port||t.port===e.port;return t.hostname===e.hostname&&r&&t.protocol===e.protocol?"":"anonymous"}r.__esModule=!0,r.default=i;var o=t("url"),s=n(o),a=void 0},{url:28}],116:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(){return++T}function o(t,e){return e=e||[],e[0]=(t>>16&255)/255,e[1]=(t>>8&255)/255,e[2]=(255&t)/255,e}function s(t){return t=t.toString(16),t="000000".substr(0,6-t.length)+t,"#"+t}function a(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]}function u(t){var e=g.RETINA_PREFIX.exec(t);return e?parseFloat(e[1]):1}function h(t){var e=g.DATA_URI.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,encoding:e[3]?e[3].toLowerCase():void 0,data:e[4]}}function l(t){var e=g.URL_FILE_EXTENSION.exec(t);if(e)return e[1].toLowerCase()}function c(t){var e=g.SVG_SIZE.exec(t),r={};return e&&(r[e[1]]=Math.round(parseFloat(e[2])),r[e[3]]=Math.round(parseFloat(e[4]))),r}function f(){w=!0}function d(t){if(!w){if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var e=["\n %c %c %c Pixi.js "+g.VERSION+" - ✰ "+t+" ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n","background: #ff66a5; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff66a5; background: #030307; padding:5px 0;","background: #ff66a5; padding:5px 0;","background: #ffc3dc; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;"];window.console.log.apply(console,e)}else window.console&&window.console.log("Pixi.js "+g.VERSION+" - "+t+" - http://www.pixijs.com/");w=!0}}function p(){var t={stencil:!0,failIfMajorPerformanceCaveat:!0};try{if(!window.WebGLRenderingContext)return!1;var e=document.createElement("canvas"),r=e.getContext("webgl",t)||e.getContext("experimental-webgl",t),n=!(!r||!r.getContextAttributes().stencil);if(r){var i=r.getExtension("WEBGL_lose_context");i&&i.loseContext()}return r=null,n}catch(t){return!1}}function v(t){return 0===t?0:t<0?-1:1}function y(t,e,r){var n=t.length;if(!(e>=n||0===r)){r=e+r>n?n-e:r;for(var i=n-r,o=e;o1?this._fontStyle="italic":t.indexOf("oblique")>-1?this._fontStyle="oblique":this._fontStyle="normal",t.indexOf("small-caps")>-1?this._fontVariant="small-caps":this._fontVariant="normal";var e=t.split(" "),r=-1;this._fontSize=26;for(var n=0;n-1&&r1&&void 0!==arguments[1]?arguments[1]:{};o(this,e);var i=s(this,t.call(this));return i.textWidth=0,i.textHeight=0,i._glyphs=[],i._font={tint:void 0!==n.tint?n.tint:16777215,align:n.align||"left",name:null,size:0},i.font=n.font,i._text=r,i.maxWidth=0,i.maxLineHeight=0,i._anchor=new f.default(function(){i.dirty=!0},i,0,0),i.dirty=!1,i.updateText(),i}return a(e,t),e.prototype.updateText=function(){for(var t=e.fonts[this._font.name],r=this._font.size/t.size,n=new l.Point,i=[],o=[],s=null,a=0,u=0,h=0,c=-1,f=0,d=0,p=0;p0&&n.x*r>this.maxWidth)l.utils.removeItems(i,c,p-c),p=c,c=-1,o.push(f),u=Math.max(u,f),h++,n.x=0,n.y+=t.lineHeight,s=null;else{var y=t.chars[v];y&&(s&&y.kerning[s]&&(n.x+=y.kerning[s]),i.push({texture:y.texture,line:h,charCode:v,position:new l.Point(n.x+y.xOffset,n.y+y.yOffset)}),a=n.x+(y.texture.width+y.xOffset),n.x+=y.xAdvance,d=Math.max(d,y.yOffset+y.texture.height),s=v)}}o.push(a),u=Math.max(u,a);for(var g=[],m=0;m<=h;m++){var _=0;"right"===this._font.align?_=u-o[m]:"center"===this._font.align&&(_=(u-o[m])/2),g.push(_)}for(var b=i.length,x=this.tint,T=0;T=0?t:16777215,this.dirty=!0}},{key:"align",get:function(){return this._font.align},set:function(t){this._font.align=t||"left",this.dirty=!0}},{key:"anchor",get:function(){return this._anchor},set:function(t){"number"==typeof t?this._anchor.set(t):this._anchor.copy(t)}},{key:"font",get:function(){return this._font},set:function(t){t&&("string"==typeof t?(t=t.split(" "),this._font.name=1===t.length?t[0]:t.slice(1).join(" "),this._font.size=t.length>=2?parseInt(t[0],10):e.fonts[this._font.name].size):(this._font.name=t.name,this._font.size="number"==typeof t.size?t.size:parseInt(t.size,10)),this.dirty=!0)}},{key:"text",get:function(){return this._text},set:function(t){t=t.toString()||" ",this._text!==t&&(this._text=t,this.dirty=!0)}}]),e}(l.Container);r.default=d,d.fonts={}},{"../core":62,"../core/math/ObservablePoint":65}],124:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r=this._durations[this.currentFrame];)n-=this._durations[this.currentFrame]*i,this._currentTime+=i;this._currentTime+=n/this._durations[this.currentFrame]}else this._currentTime+=e;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):r!==this.currentFrame&&(this._texture=this._textures[this.currentFrame],this._textureID=-1,this.onFrameChange&&this.onFrameChange(this.currentFrame))},e.prototype.destroy=function(){this.stop(),t.prototype.destroy.call(this)},e.fromFrames=function(t){for(var r=[],n=0;n1&&void 0!==arguments[1]?arguments[1]:100,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:100;o(this,e);var a=s(this,t.call(this,r));return a.tileTransform=new l.TransformStatic,a._width=n,a._height=i,a._canvasPattern=null,a.uvTransform=r.transform||new p.default(r),a}return a(e,t),e.prototype._onTextureUpdate=function(){this.uvTransform&&(this.uvTransform.texture=this._texture)},e.prototype._renderWebGL=function(t){var e=this._texture;e&&e.valid&&(this.tileTransform.updateLocalTransform(),this.uvTransform.update(),t.setObjectRenderer(t.plugins.tilingSprite),t.plugins.tilingSprite.render(this))},e.prototype._renderCanvas=function(t){var e=this._texture;if(e.baseTexture.hasLoaded){var r=t.context,n=this.worldTransform,i=t.resolution,o=e.baseTexture,s=e.baseTexture.resolution,a=this.tilePosition.x/this.tileScale.x%e._frame.width,u=this.tilePosition.y/this.tileScale.y%e._frame.height;if(!this._canvasPattern){var h=new l.CanvasRenderTarget(e._frame.width,e._frame.height,s);16777215!==this.tint?(this.cachedTint!==this.tint&&(this.cachedTint=this.tint,this.tintedTexture=f.default.getTintedTexture(this,this.tint)),h.context.drawImage(this.tintedTexture,0,0)):h.context.drawImage(o.source,-e._frame.x,-e._frame.y),this._canvasPattern=h.context.createPattern(h.canvas,"repeat")}r.globalAlpha=this.worldAlpha,r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),r.scale(this.tileScale.x/s,this.tileScale.y/s),r.translate(a+this.anchor.x*-this._width,u+this.anchor.y*-this._height);var c=t.blendModes[this.blendMode];c!==t.context.globalCompositeOperation&&(r.globalCompositeOperation=c),r.fillStyle=this._canvasPattern,r.fillRect(-a,-u,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s)}},e.prototype._calculateBounds=function(){var t=this._width*-this._anchor._x,e=this._height*-this._anchor._y,r=this._width*(1-this._anchor._x),n=this._height*(1-this._anchor._y);this._bounds.addFrame(this.transform,t,e,r,n)},e.prototype.getLocalBounds=function(e){return 0===this.children.length?(this._bounds.minX=this._width*-this._anchor._x,this._bounds.minY=this._height*-this._anchor._y,this._bounds.maxX=this._width*(1-this._anchor._x),this._bounds.maxY=this._height*(1-this._anchor._x),e||(this._localBoundsRect||(this._localBoundsRect=new l.Rectangle),e=this._localBoundsRect),this._bounds.getRectangle(e)):t.prototype.getLocalBounds.call(this,e)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,v);var e=this._width,r=this._height,n=-e*this.anchor._x;if(v.x>n&&v.xi&&v.y0&&void 0!==arguments[0]?arguments[0]:new o.Point,e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.parent?this.parent.toGlobal(this.position,t,e):(t.x=this.position.x,t.y=this.position.y),t}},{"../core":62}],130:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./TextureTransform");Object.defineProperty(r,"TextureTransform",{enumerable:!0,get:function(){return n(i).default}});var o=t("./MovieClip");Object.defineProperty(r,"MovieClip",{enumerable:!0,get:function(){return n(o).default}});var s=t("./TilingSprite");Object.defineProperty(r,"TilingSprite",{enumerable:!0,get:function(){return n(s).default}});var a=t("./webgl/TilingSpriteRenderer");Object.defineProperty(r,"TilingSpriteRenderer",{enumerable:!0,get:function(){return n(a).default}});var u=t("./BitmapText");Object.defineProperty(r,"BitmapText",{enumerable:!0,get:function(){return n(u).default}});var h=t("./cacheAsBitmap");Object.defineProperty(r,"cacheAsBitmap",{enumerable:!0,get:function(){return n(h).default}});var l=t("./getChildByName");Object.defineProperty(r,"getChildByName",{enumerable:!0,get:function(){return n(l).default}});var c=t("./getGlobalPosition");Object.defineProperty(r,"getGlobalPosition",{enumerable:!0,get:function(){return n(c).default}})},{"./BitmapText":123,"./MovieClip":124,"./TextureTransform":125,"./TilingSprite":126,"./cacheAsBitmap":127,"./getChildByName":128,"./getGlobalPosition":129,"./webgl/TilingSpriteRenderer":131}],131:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0,r.TilingSpriteRenderer=void 0;var a=t("../../core"),u=n(a),h=t("../../core/const"),l=new u.Matrix,c=new Float32Array(4),f=r.TilingSpriteRenderer=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.shader=null,n.simpleShader=null,n.quad=null,n}return s(e,t),e.prototype.onContextChange=function(){var t=this.renderer.gl;this.shader=new u.Shader(t,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n gl_FragColor = sample * color ;\n}\n"),this.simpleShader=new u.Shader(t,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n gl_FragColor = sample * color;\n}\n"),this.quad=new u.Quad(t),this.quad.initVao(this.shader)},e.prototype.render=function(t){var e=this.quad,r=e.vertices;r[0]=r[6]=t._width*-t.anchor.x,r[1]=r[3]=t._height*-t.anchor.y,r[2]=r[4]=t._width*(1-t.anchor.x),r[5]=r[7]=t._height*(1-t.anchor.y),r=e.uvs,r[0]=r[6]=-t.anchor.x,r[1]=r[3]=-t.anchor.y,r[2]=r[4]=1-t.anchor.x,r[5]=r[7]=1-t.anchor.y,e.upload();var n=this.renderer,i=t._texture,o=i.baseTexture,s=t.tileTransform.localTransform,a=t.uvTransform,f=o.isPowerOfTwo&&i.frame.width===o.width&&i.frame.height===o.height;f&&(o._glTextures[n.CONTEXT_UID]?f=o.wrapMode!==h.WRAP_MODES.CLAMP:o.wrapMode===h.WRAP_MODES.CLAMP&&(o.wrapMode=h.WRAP_MODES.REPEAT));var d=f?this.simpleShader:this.shader;n.bindShader(d);var p=i.width,v=i.height,y=t._width,g=t._height;l.set(s.a*p/y,s.b*p/g,s.c*v/y,s.d*v/g,s.tx/y,s.ty/g),l.invert(),f?l.append(a.mapCoord):(d.uniforms.uMapCoord=a.mapCoord.toArray(!0),d.uniforms.uClampFrame=a.uClampFrame,d.uniforms.uClampOffset=a.uClampOffset),d.uniforms.uTransform=l.toArray(!0);var m=c;u.utils.hex2rgb(t.tint,m),m[3]=t.worldAlpha,d.uniforms.uColor=m,d.uniforms.translationMatrix=t.transform.worldTransform.toArray(!0),n.bindTexture(i),n.setBlendMode(t.blendMode),e.draw()},e}(u.ObjectRenderer);u.WebGLRenderer.registerPlugin("tilingSprite",f)},{"../../core":62,"../../core/const":43}],132:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var u=function(){function t(t,e){for(var r=0;r=r&&(u=t-h-1),l=l.replace("%value%",e[u]),s+=l,s+="\n"}return n=n.replace("%blur%",s),n=n.replace("%size%",t)}r.__esModule=!0,r.default=n;var i={5:[.153388,.221461,.250301],7:[.071303,.131514,.189879,.214607],9:[.028532,.067234,.124009,.179044,.20236],11:[.0093,.028002,.065984,.121703,.175713,.198596],13:[.002406,.009255,.027867,.065666,.121117,.174868,.197641],15:[489e-6,.002403,.009246,.02784,.065602,.120999,.174697,.197448]},o=["varying vec2 vBlurTexCoords[%size%];","uniform sampler2D uSampler;","void main(void)","{"," gl_FragColor = vec4(0.0);"," %blur%","}"].join("\n")},{}],136:[function(t,e,r){"use strict";function n(t,e){var r=Math.ceil(t/2),n=i,o="",s=void 0;s=e?"vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);":"vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);";for(var a=0;ae;)r-=2;return r}r.__esModule=!0,r.default=n},{}],138:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]&&arguments[1],r=t;e&&(this._multiply(r,this.uniforms.m,t),r=this._colorMatrix(r)),this.uniforms.m=r},e.prototype._multiply=function(t,e,r){return t[0]=e[0]*r[0]+e[1]*r[5]+e[2]*r[10]+e[3]*r[15],t[1]=e[0]*r[1]+e[1]*r[6]+e[2]*r[11]+e[3]*r[16],t[2]=e[0]*r[2]+e[1]*r[7]+e[2]*r[12]+e[3]*r[17],t[3]=e[0]*r[3]+e[1]*r[8]+e[2]*r[13]+e[3]*r[18],t[4]=e[0]*r[4]+e[1]*r[9]+e[2]*r[14]+e[3]*r[19],t[5]=e[5]*r[0]+e[6]*r[5]+e[7]*r[10]+e[8]*r[15],t[6]=e[5]*r[1]+e[6]*r[6]+e[7]*r[11]+e[8]*r[16],t[7]=e[5]*r[2]+e[6]*r[7]+e[7]*r[12]+e[8]*r[17],t[8]=e[5]*r[3]+e[6]*r[8]+e[7]*r[13]+e[8]*r[18],t[9]=e[5]*r[4]+e[6]*r[9]+e[7]*r[14]+e[8]*r[19],t[10]=e[10]*r[0]+e[11]*r[5]+e[12]*r[10]+e[13]*r[15],t[11]=e[10]*r[1]+e[11]*r[6]+e[12]*r[11]+e[13]*r[16],t[12]=e[10]*r[2]+e[11]*r[7]+e[12]*r[12]+e[13]*r[17],t[13]=e[10]*r[3]+e[11]*r[8]+e[12]*r[13]+e[13]*r[18],t[14]=e[10]*r[4]+e[11]*r[9]+e[12]*r[14]+e[13]*r[19],t[15]=e[15]*r[0]+e[16]*r[5]+e[17]*r[10]+e[18]*r[15],t[16]=e[15]*r[1]+e[16]*r[6]+e[17]*r[11]+e[18]*r[16],t[17]=e[15]*r[2]+e[16]*r[7]+e[17]*r[12]+e[18]*r[17],t[18]=e[15]*r[3]+e[16]*r[8]+e[17]*r[13]+e[18]*r[18],t[19]=e[15]*r[4]+e[16]*r[9]+e[17]*r[14]+e[18]*r[19],t},e.prototype._colorMatrix=function(t){var e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e},e.prototype.brightness=function(t,e){var r=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.greyscale=function(t,e){var r=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.blackAndWhite=function(t){var e=[.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.hue=function(t,e){t=(t||0)/180*Math.PI;var r=Math.cos(t),n=Math.sin(t),i=Math.sqrt,o=1/3,s=i(o),a=r+(1-r)*o,u=o*(1-r)-s*n,h=o*(1-r)+s*n,l=o*(1-r)+s*n,c=r+o*(1-r),f=o*(1-r)-s*n,d=o*(1-r)-s*n,p=o*(1-r)+s*n,v=r+o*(1-r),y=[a,u,h,0,0,l,c,f,0,0,d,p,v,0,0,0,0,0,1,0];this._loadMatrix(y,e)},e.prototype.contrast=function(t,e){var r=(t||0)+1,n=-128*(r-1),i=[r,0,0,0,n,0,r,0,0,n,0,0,r,0,n,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.saturate=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=2*t/3+1,n=(r-1)*-.5,i=[r,n,n,0,0,n,r,n,0,0,n,n,r,0,0,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.desaturate=function(){this.saturate(-1)},e.prototype.negative=function(t){var e=[0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.sepia=function(t){var e=[.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.technicolor=function(t){var e=[1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.polaroid=function(t){var e=[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.toBGR=function(t){var e=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.kodachrome=function(t){var e=[1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.browni=function(t){var e=[.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.vintage=function(t){var e=[.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.colorTone=function(t,e,r,n,i){t=t||.2,e=e||.15,r=r||16770432,n=n||3375104;var o=(r>>16&255)/255,s=(r>>8&255)/255,a=(255&r)/255,u=(n>>16&255)/255,h=(n>>8&255)/255,l=(255&n)/255,c=[.3,.59,.11,0,0,o,s,a,t,0,u,h,l,e,0,o-u,s-h,a-l,0,0];this._loadMatrix(c,i)},e.prototype.night=function(t,e){t=t||.1;var r=[t*-2,-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.predator=function(t,e){var r=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.lsd=function(t){var e=[2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.reset=function(){var t=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(t,!1)},a(e,[{key:"matrix",get:function(){return this.uniforms.m},set:function(t){this.uniforms.m=t}}]),e}(h.Filter);r.default=l,l.prototype.grayscale=l.prototype.greyscale},{"../../core":62}],139:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n'))}return s(e,t),e}(u.Filter);r.default=h},{"../../core":62}],141:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./fxaa/FXAAFilter");Object.defineProperty(r,"FXAAFilter",{enumerable:!0,get:function(){return n(i).default}});var o=t("./noise/NoiseFilter");Object.defineProperty(r,"NoiseFilter",{enumerable:!0,get:function(){return n(o).default}});var s=t("./displacement/DisplacementFilter");Object.defineProperty(r,"DisplacementFilter",{enumerable:!0,get:function(){return n(s).default}});var a=t("./blur/BlurFilter");Object.defineProperty(r,"BlurFilter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./blur/BlurXFilter");Object.defineProperty(r,"BlurXFilter",{enumerable:!0,get:function(){return n(u).default}});var h=t("./blur/BlurYFilter");Object.defineProperty(r,"BlurYFilter",{enumerable:!0,get:function(){return n(h).default}});var l=t("./colormatrix/ColorMatrixFilter");Object.defineProperty(r,"ColorMatrixFilter",{enumerable:!0,get:function(){return n(l).default}});var c=t("./void/VoidFilter");Object.defineProperty(r,"VoidFilter",{enumerable:!0,get:function(){return n(c).default}})},{"./blur/BlurFilter":132,"./blur/BlurXFilter":133,"./blur/BlurYFilter":134,"./colormatrix/ColorMatrixFilter":138,"./displacement/DisplacementFilter":139,"./fxaa/FXAAFilter":140,"./noise/NoiseFilter":142,"./void/VoidFilter":143}],142:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:1;this.removeEvents(),this.interactionDOMElement=t,this.resolution=e,this.addEvents()},e.prototype.addEvents=function(){this.interactionDOMElement&&(h.ticker.shared.add(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="none",this.interactionDOMElement.style["-ms-touch-action"]="none"):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]="none"),window.document.addEventListener("mousemove",this.onMouseMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onMouseDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onMouseOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onMouseOver,!0),window.addEventListener("mouseup",this.onMouseUp,!0),this.supportsTouchEvents&&(this.interactionDOMElement.addEventListener("touchstart",this.onTouchStart,!0),this.interactionDOMElement.addEventListener("touchend",this.onTouchEnd,!0),this.interactionDOMElement.addEventListener("touchmove",this.onTouchMove,!0)),this.supportsPointerEvents?(window.document.addEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("pointerout",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("pointerover",this.onPointerOver,!0),window.addEventListener("pointerup",this.onPointerUp,!0)):(this.normalizeTouchEvents&&(this.interactionDOMElement.addEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.addEventListener("touchmove",this.onPointerMove,!0)),this.normalizeMouseEvents&&(window.document.addEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onPointerOver,!0),window.addEventListener("mouseup",this.onPointerUp,!0))),this.eventsAdded=!0)},e.prototype.removeEvents=function(){this.interactionDOMElement&&(h.ticker.shared.remove(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="",this.interactionDOMElement.style["-ms-touch-action"]=""):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]=""),window.document.removeEventListener("mousemove",this.onMouseMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onMouseDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onMouseOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onMouseOver,!0),window.removeEventListener("mouseup",this.onMouseUp,!0),this.supportsTouchEvents&&(this.interactionDOMElement.removeEventListener("touchstart",this.onTouchStart,!0),this.interactionDOMElement.removeEventListener("touchend",this.onTouchEnd,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onTouchMove,!0)),this.supportsPointerEvents?(window.document.removeEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("pointerdown",this.onPointerDown,!0), +this.interactionDOMElement.removeEventListener("pointerout",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("pointerover",this.onPointerOver,!0),window.removeEventListener("pointerup",this.onPointerUp,!0)):(this.normalizeTouchEvents&&(this.interactionDOMElement.removeEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onPointerMove,!0)),this.normalizeMouseEvents&&(window.document.removeEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onPointerOver,!0),window.removeEventListener("mouseup",this.onPointerUp,!0))),this.interactionDOMElement=null,this.eventsAdded=!1)},e.prototype.update=function(t){if(this._deltaTime+=t,!(this._deltaTime=0;u--){var h=a[u];if(this.processInteractive(t,h,r,n,s)){if(!h.parent)continue;o=!0,s=!1,n=!1}}return i&&(n&&!o&&(e.hitArea?(e.worldTransform.applyInverse(t,this._tempPoint),o=e.hitArea.contains(this._tempPoint.x,this._tempPoint.y)):e.containsPoint&&(o=e.containsPoint(t))),e.interactive&&(o&&!this.eventData.target&&(this.eventData.target=e,this.mouse.target=e,this.pointer.target=e),r(e,o))),o},e.prototype.onMouseDown=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData._reset(),this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.autoPreventDefault&&this.mouse.originalEvent.preventDefault(),this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseDown,!0);var e=2===t.button||3===t.which;this.emit(e?"rightdown":"mousedown",this.eventData)},e.prototype.processMouseDown=function(t,e){var r=this.mouse.originalEvent,n=2===r.button||3===r.which;e&&(t[n?"_isRightDown":"_isLeftDown"]=!0,this.dispatchEvent(t,n?"rightdown":"mousedown",this.eventData))},e.prototype.onMouseUp=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData._reset(),this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseUp,!0);var e=2===t.button||3===t.which;this.emit(e?"rightup":"mouseup",this.eventData)},e.prototype.processMouseUp=function(t,e){var r=this.mouse.originalEvent,n=2===r.button||3===r.which,i=n?"_isRightDown":"_isLeftDown";e?(this.dispatchEvent(t,n?"rightup":"mouseup",this.eventData),t[i]&&(t[i]=!1,this.dispatchEvent(t,n?"rightclick":"click",this.eventData))):t[i]&&(t[i]=!1,this.dispatchEvent(t,n?"rightupoutside":"mouseupoutside",this.eventData))},e.prototype.onMouseMove=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData._reset(),this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.didMove=!0,this.cursor=this.defaultCursorStyle,this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseMove,!0),this.emit("mousemove",this.eventData),this.currentCursorStyle!==this.cursor&&(this.currentCursorStyle=this.cursor,this.interactionDOMElement.style.cursor=this.cursor)},e.prototype.processMouseMove=function(t,e){this.processMouseOverOut(t,e),this.moveWhenInside&&!e||this.dispatchEvent(t,"mousemove",this.eventData)},e.prototype.onMouseOut=function(t){this.mouseOverRenderer=!1,this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData._reset(),this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.interactionDOMElement.style.cursor=this.defaultCursorStyle,this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseOverOut,!1),this.emit("mouseout",this.eventData)},e.prototype.processMouseOverOut=function(t,e){e&&this.mouseOverRenderer?(t._mouseOver||(t._mouseOver=!0,this.dispatchEvent(t,"mouseover",this.eventData)),t.buttonMode&&(this.cursor=t.defaultCursor)):t._mouseOver&&(t._mouseOver=!1,this.dispatchEvent(t,"mouseout",this.eventData))},e.prototype.onMouseOver=function(t){this.mouseOverRenderer=!0,this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData._reset(),this.emit("mouseover",this.eventData)},e.prototype.onPointerDown=function(t){this.normalizeToPointerData(t),this.pointer.originalEvent=t,this.eventData.data=this.pointer,this.eventData._reset(),this.mapPositionToPoint(this.pointer.global,t.clientX,t.clientY),this.autoPreventDefault&&this.pointer.originalEvent.preventDefault(),this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerDown,!0),this.emit("pointerdown",this.eventData)},e.prototype.processPointerDown=function(t,e){e&&(t._pointerDown=!0,this.dispatchEvent(t,"pointerdown",this.eventData))},e.prototype.onPointerUp=function(t){this.normalizeToPointerData(t),this.pointer.originalEvent=t,this.eventData.data=this.pointer,this.eventData._reset(),this.mapPositionToPoint(this.pointer.global,t.clientX,t.clientY),this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerUp,!0),this.emit("pointerup",this.eventData)},e.prototype.processPointerUp=function(t,e){e?(this.dispatchEvent(t,"pointerup",this.eventData),t._pointerDown&&(t._pointerDown=!1,this.dispatchEvent(t,"pointertap",this.eventData))):t._pointerDown&&(t._pointerDown=!1,this.dispatchEvent(t,"pointerupoutside",this.eventData))},e.prototype.onPointerMove=function(t){this.normalizeToPointerData(t),this.pointer.originalEvent=t,this.eventData.data=this.pointer,this.eventData._reset(),this.mapPositionToPoint(this.pointer.global,t.clientX,t.clientY),this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerMove,!0),this.emit("pointermove",this.eventData)},e.prototype.processPointerMove=function(t,e){this.pointer.originalEvent.changedTouches||this.processPointerOverOut(t,e),this.moveWhenInside&&!e||this.dispatchEvent(t,"pointermove",this.eventData)},e.prototype.onPointerOut=function(t){this.normalizeToPointerData(t),this.pointer.originalEvent=t,this.eventData.data=this.pointer,this.eventData._reset(),this.mapPositionToPoint(this.pointer.global,t.clientX,t.clientY),this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerOverOut,!1),this.emit("pointerout",this.eventData)},e.prototype.processPointerOverOut=function(t,e){e&&this.mouseOverRenderer?t._pointerOver||(t._pointerOver=!0,this.dispatchEvent(t,"pointerover",this.eventData)):t._pointerOver&&(t._pointerOver=!1,this.dispatchEvent(t,"pointerout",this.eventData))},e.prototype.onPointerOver=function(t){this.pointer.originalEvent=t,this.eventData.data=this.pointer,this.eventData._reset(),this.emit("pointerover",this.eventData)},e.prototype.onTouchStart=function(t){this.autoPreventDefault&&t.preventDefault();for(var e=t.changedTouches,r=e.length,n=0;n1&&(l=1);var c=Math.sqrt(n*n+i*i),f=this._texture.height/2;n/=c,i/=c,n*=f,i*=f,o[h]=u.x+n,o[h+1]=u.y+i,o[h+2]=u.x-n,o[h+3]=u.y-i,e=u}this.containerUpdateTransform()}},e}(h.default);r.default=f},{"../core":62,"./Mesh":154}],158:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var s=t("../../core"),a=i(s),u=t("../Mesh"),h=n(u),l=function(){function t(e){o(this,t),this.renderer=e}return t.prototype.render=function(t){var e=this.renderer,r=e.context,n=t.worldTransform,i=e.resolution;e.roundPixels?r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i|0,n.ty*i|0):r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t.drawMode===h.default.DRAW_MODES.TRIANGLE_MESH?this._renderTriangleMesh(t):this._renderTriangles(t)},t.prototype._renderTriangleMesh=function(t){for(var e=t.vertices.length/2,r=0;r0){var E=t.canvasPadding/t.worldTransform.a,S=t.canvasPadding/t.worldTransform.d,O=(m+_+b)/3,M=(x+T+w)/3,P=m-O,C=x-M,R=Math.sqrt(P*P+C*C);m=O+P/R*(R+E),x=M+C/R*(R+S),P=_-O,C=T-M,R=Math.sqrt(P*P+C*C),_=O+P/R*(R+E),T=M+C/R*(R+S),P=b-O,C=w-M,R=Math.sqrt(P*P+C*C),b=O+P/R*(R+E),w=M+C/R*(R+S)}i.save(),i.beginPath(),i.moveTo(m,x),i.lineTo(_,T),i.lineTo(b,w),i.closePath(),i.clip();var D=f*y+v*p+d*g-y*p-v*d-f*g,A=m*y+v*b+_*g-y*b-v*_-m*g,I=f*_+m*p+d*b-_*p-m*d-f*b,L=f*y*b+v*_*p+m*d*g-m*y*p-v*d*b-f*_*g,j=x*y+v*w+T*g-y*w-v*T-x*g,F=f*T+x*p+d*w-T*p-x*d-f*w,B=f*y*w+v*T*p+x*d*g-x*y*p-v*d*w-f*T*g;i.transform(A/D,j/D,I/D,F/D,L/D,B/D),i.drawImage(h,0,0,l*u.resolution,c*u.resolution,0,0,l,c),i.restore()}},t.prototype.renderMeshFlat=function(t){var e=this.renderer.context,r=t.vertices,n=r.length/2;e.beginPath();for(var i=1;i0&&void 0!==arguments[0]?arguments[0]:1500,n=arguments[1],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16384;i(this,e);var a=o(this,t.call(this)),h=16384;return s>h&&(s=h),s>r&&(s=r),a._properties=[!1,!0,!1,!1,!1],a._maxSize=r,a._batchSize=s,a._glBuffers={},a._bufferToUpdate=0,a.interactiveChildren=!1,a.blendMode=u.BLEND_MODES.NORMAL,a.roundPixels=!0,a.baseTexture=null,a.setProperties(n),a}return s(e,t),e.prototype.setProperties=function(t){t&&(this._properties[0]="scale"in t?!!t.scale:this._properties[0],this._properties[1]="position"in t?!!t.position:this._properties[1],this._properties[2]="rotation"in t?!!t.rotation:this._properties[2],this._properties[3]="uvs"in t?!!t.uvs:this._properties[3],this._properties[4]="alpha"in t?!!t.alpha:this._properties[4])},e.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},e.prototype.renderWebGL=function(t){var e=this;this.visible&&!(this.worldAlpha<=0)&&this.children.length&&this.renderable&&(this.baseTexture||(this.baseTexture=this.children[0]._texture.baseTexture,this.baseTexture.hasLoaded||this.baseTexture.once("update",function(){return e.onChildrenChange(0)})),t.setObjectRenderer(t.plugins.particle),t.plugins.particle.render(this))},e.prototype.onChildrenChange=function(t){var e=Math.floor(t/this._batchSize);er&&(i=r);var o=t._glBuffers[this.renderer.CONTEXT_UID];o||(o=t._glBuffers[this.renderer.CONTEXT_UID]=this.generateBuffers(t)),this.renderer.setBlendMode(t.blendMode);var s=this.renderer.gl,a=t.worldTransform.copy(this.tempMatrix);a.prepend(this.renderer._activeRenderTarget.projectionMatrix),this.shader.uniforms.projectionMatrix=a.toArray(!0),this.shader.uniforms.uAlpha=t.worldAlpha;var u=e[0]._texture.baseTexture;this.renderer.bindTexture(u);for(var h=0,l=0;hn&&(c=n);var f=o[l];f.uploadDynamic(e,h,c),t._bufferToUpdate===l&&(f.uploadStatic(e,h,c),t._bufferToUpdate=l+1),f.vao.bind().draw(s.TRIANGLES,6*c).unbind()}}},e.prototype.generateBuffers=function(t){for(var e=this.renderer.gl,r=[],n=t._maxSize,i=t._batchSize,o=t._properties,s=0;s0?1:-1})},{}],167:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}var i=t("object-assign"),o=n(i);Object.assign||(Object.assign=o.default)},{"object-assign":5}],168:[function(t,e,r){"use strict";t("./Object.assign"),t("./requestAnimationFrame"),t("./Math.sign"),window.ArrayBuffer||(window.ArrayBuffer=Array),window.Float32Array||(window.Float32Array=Array),window.Uint32Array||(window.Uint32Array=Array),window.Uint16Array||(window.Uint16Array=Array)},{"./Math.sign":166,"./Object.assign":167,"./requestAnimationFrame":169}],169:[function(t,e,r){(function(t){"use strict";var e=16;Date.now&&Date.prototype.getTime||(Date.now=function(){return(new Date).getTime()}),t.performance&&t.performance.now||!function(){var e=Date.now();t.performance||(t.performance={}),t.performance.now=function(){return Date.now()-e}}();for(var r=Date.now(),n=["ms","moz","webkit","o"],i=0;i0;){for(var e=this.queue[0],r=!1,n=0,i=this.uploadHooks.length;n=0;n--)this.add(t.children[n]);return this},t.prototype.destroy=function(){this.ticking&&h.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null,this.ctx=null,this.canvas=null},t}();r.default=f,f.UPLOADS_PER_FRAME=c,u.CanvasRenderer.registerPlugin("prepare",f)},{"../../core":62}],171:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./webgl/WebGLPrepare");Object.defineProperty(r,"webgl",{enumerable:!0,get:function(){return n(i).default}});var o=t("./canvas/CanvasPrepare");Object.defineProperty(r,"canvas",{enumerable:!0,get:function(){return n(o).default}})},{"./canvas/CanvasPrepare":170,"./webgl/WebGLPrepare":172}],172:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){return e instanceof l.BaseTexture&&(t.textureManager.updateTexture(e),!0)}function s(t,e){return e instanceof l.Graphics&&(t.plugins.graphics.updateGraphics(e),!0)}function a(t,e){if(t instanceof l.BaseTexture)return e.indexOf(t)===-1&&e.push(t),!0;if(t._texture&&t._texture instanceof l.Texture){var r=t._texture.baseTexture;return e.indexOf(r)===-1&&e.push(r),!0}return!1}function u(t,e){return t instanceof l.Graphics&&(e.push(t),!0)}r.__esModule=!0;var h=t("../../core"),l=n(h),c=l.ticker.shared,f=4,d=function(){function t(e){i(this,t),this.renderer=e,this.queue=[],this.addHooks=[],this.uploadHooks=[],this.completes=[],this.ticking=!1,this.register(a,o).register(u,s)}return t.prototype.upload=function(e,r){"function"==typeof e&&(r=e,e=null),e&&this.add(e),this.queue.length?(this.numLeft=t.UPLOADS_PER_FRAME,r&&this.completes.push(r),this.ticking||(this.ticking=!0,c.add(this.tick,this))):r&&r()},t.prototype.tick=function(){for(;this.queue.length&&this.numLeft>0;){for(var e=this.queue[0],r=!1,n=0,i=this.uploadHooks.length;n=0;n--)this.add(t.children[n]);return this},t.prototype.destroy=function(){this.ticking&&c.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null},t}();r.default=d,d.UPLOADS_PER_FRAME=f,l.WebGLRenderer.registerPlugin("prepare",d)},{"../../core":62}],173:[function(t,e,r){(function(e){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}r.__esModule=!0,r.loader=r.prepare=r.particles=r.mesh=r.loaders=r.interaction=r.filters=r.extras=r.extract=r.accessibility=void 0;var i=t("./deprecation");Object.keys(i).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return i[t]}})});var o=t("./core");Object.keys(o).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return o[t]}})}),t("./polyfill");var s=t("./accessibility"),a=n(s),u=t("./extract"),h=n(u),l=t("./extras"),c=n(l),f=t("./filters"),d=n(f),p=t("./interaction"),v=n(p),y=t("./loaders"),g=n(y),m=t("./mesh"),_=n(m),b=t("./particles"),x=n(b),T=t("./prepare"),w=n(T);r.accessibility=a,r.extract=h,r.extras=c,r.filters=d,r.interaction=v,r.loaders=g,r.mesh=_,r.particles=x,r.prepare=w;var E=new g.Loader;r.loader=E,e.PIXI=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./accessibility":41,"./core":62,"./deprecation":119,"./extract":121,"./extras":130,"./filters":141,"./interaction":147,"./loaders":150,"./mesh":159,"./particles":162,"./polyfill":168,"./prepare":171}]},{},[173])(173)}); +//# sourceMappingURL=pixi.min.js.map diff --git a/js/pixi/4.1.1/pixi.min.js b/js/pixi/4.1.1/pixi.min.js new file mode 100644 index 0000000..aec5620 --- /dev/null +++ b/js/pixi/4.1.1/pixi.min.js @@ -0,0 +1,20 @@ +/*! + * pixi.js - v4.1.1 + * Compiled Tue Nov 01 2016 17:31:35 GMT+0000 (UTC) + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.PIXI=t()}}(function(){var t;return function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var h=new Error("Cannot find module '"+s+"'");throw h.code="MODULE_NOT_FOUND",h}var l=r[s]={exports:{}};e[s][0].call(l.exports,function(t){var r=e[s][1][t];return i(r?r:t)},l,l.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s0)-(t<0)},r.abs=function(t){var e=t>>i-1;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,e|=r,e|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,t=(858993459&t)+(t>>>2&858993459),16843009*(t+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,t&=15,27030>>>t&1};var o=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|o[t>>>16&255]<<8|o[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),t=65535&(t|t>>>16),t<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),t=1023&(t|t>>>16),t<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],2:[function(t,e,r){"use strict";function n(t,e,r){r=r||2;var n=e&&e.length,o=n?e[0]*r:t.length,a=i(t,0,o,r,!0),u=[];if(!a)return u;var h,l,f,d,p,v,y;if(n&&(a=c(t,e,a,r)),t.length>80*r){h=f=t[0],l=d=t[1];for(var g=r;gf&&(f=p),v>d&&(d=v);y=Math.max(f-h,d-l)}return s(a,u,r,h,l,y),u}function i(t,e,r,n,i){var o,s;if(i===D(t,e,r,n)>0)for(o=e;o=e;o-=n)s=P(o,t[o],t[o+1],s);return s&&T(s,s.next)&&(C(s),s=s.next),s}function o(t,e){if(!t)return t;e||(e=t);var r,n=t;do if(r=!1,n.steiner||!T(n,n.next)&&0!==x(n.prev,n,n.next))n=n.next;else{if(C(n),n=e=n.prev,n===n.next)return null;r=!0}while(r||n!==e);return e}function s(t,e,r,n,i,c,f){if(t){!f&&c&&v(t,n,i,c);for(var d,p,y=t;t.prev!==t.next;)if(d=t.prev,p=t.next,c?u(t,n,i,c):a(t))e.push(d.i/r),e.push(t.i/r),e.push(p.i/r),C(t),t=p.next,y=p.next;else if(t=p,t===y){f?1===f?(t=h(t,e,r),s(t,e,r,n,i,c,2)):2===f&&l(t,e,r,n,i,c):s(o(t),e,r,n,i,c,1);break}}}function a(t){var e=t.prev,r=t,n=t.next;if(x(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(_(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&x(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function u(t,e,r,n){var i=t.prev,o=t,s=t.next;if(x(i,o,s)>=0)return!1;for(var a=i.xo.x?i.x>s.x?i.x:s.x:o.x>s.x?o.x:s.x,l=i.y>o.y?i.y>s.y?i.y:s.y:o.y>s.y?o.y:s.y,c=g(a,u,e,r,n),f=g(h,l,e,r,n),d=t.nextZ;d&&d.z<=f;){if(d!==t.prev&&d!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,d.x,d.y)&&x(d.prev,d,d.next)>=0)return!1;d=d.nextZ}for(d=t.prevZ;d&&d.z>=c;){if(d!==t.prev&&d!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,d.x,d.y)&&x(d.prev,d,d.next)>=0)return!1;d=d.prevZ}return!0}function h(t,e,r){var n=t;do{var i=n.prev,o=n.next.next;!T(i,o)&&w(i,n,n.next,o)&&S(i,o)&&S(o,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(o.i/r),C(n),C(n.next),n=t=o),n=n.next}while(n!==t);return n}function l(t,e,r,n,i,a){var u=t;do{for(var h=u.next.next;h!==u.prev;){if(u.i!==h.i&&b(u,h)){var l=M(u,h);return u=o(u,u.next),l=o(l,l.next),s(u,e,r,n,i,a),void s(l,e,r,n,i,a)}h=h.next}u=u.next}while(u!==t)}function c(t,e,r,n){var s,a,u,h,l,c=[];for(s=0,a=e.length;s=n.next.y){var a=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=i&&a>s){if(s=a,a===i){if(o===n.y)return n;if(o===n.next.y)return n.next}r=n.x=n.x&&n.x>=l&&_(or.x)&&S(n,t)&&(r=n,f=u)),n=n.next;return r}function v(t,e,r,n){var i=t;do null===i.z&&(i.z=g(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,y(i)}function y(t){var e,r,n,i,o,s,a,u,h=1;do{for(r=t,t=null,o=null,s=0;r;){for(s++,n=r,a=0,e=0;e0||u>0&&n;)0===a?(i=n,n=n.nextZ,u--):0!==u&&n?r.z<=n.z?(i=r,r=r.nextZ,a--):(i=n,n=n.nextZ,u--):(i=r,r=r.nextZ,a--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;r=n}o.nextZ=null,h*=2}while(s>1);return t}function g(t,e,r,n,i){return t=32767*(t-r)/i,e=32767*(e-n)/i,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1}function m(t){var e=t,r=t;do e.x=0&&(t-s)*(n-a)-(r-s)*(e-a)>=0&&(r-s)*(o-a)-(i-s)*(n-a)>=0}function b(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!E(t,e)&&S(t,e)&&S(e,t)&&O(t,e)}function x(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function T(t,e){return t.x===e.x&&t.y===e.y}function w(t,e,r,n){return!!(T(t,e)&&T(r,n)||T(t,n)&&T(r,e))||x(t,e,r)>0!=x(t,e,n)>0&&x(r,n,t)>0!=x(r,n,e)>0}function E(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&w(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}function S(t,e){return x(t.prev,t,t.next)<0?x(t,e,t.next)>=0&&x(t,t.prev,e)>=0:x(t,e,t.prev)<0||x(t,t.next,e)<0}function O(t,e){var r=t,n=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do r.y>o!=r.next.y>o&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;while(r!==t);return n}function M(t,e){var r=new R(t.i,t.x,t.y),n=new R(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function P(t,e,r,n){var i=new R(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function C(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function R(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function D(t,e,r,n){for(var i=0,o=e,s=r-n;o0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],3:[function(t,e,r){"use strict";function n(){}function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function o(){this._events=new n,this._eventsCount=0}var s=Object.prototype.hasOwnProperty,a="~";Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(a=!1)),o.prototype.eventNames=function(){var t,e,r=[];if(0===this._eventsCount)return r;for(e in t=this._events)s.call(t,e)&&r.push(a?e.slice(1):e);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t,e){var r=a?a+t:t,n=this._events[r];if(e)return!!n;if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i=t.byteLength?n.bufferSubData(this.type,e,t):n.bufferData(this.type,t,this.drawType),this.data=t},i.prototype.bind=function(){var t=this.gl;t.bindBuffer(this.type,this.buffer)},i.createVertexBuffer=function(t,e,r){return new i(t,t.ARRAY_BUFFER,e,r)},i.createIndexBuffer=function(t,e,r){return new i(t,t.ELEMENT_ARRAY_BUFFER,e,r)},i.create=function(t,e,r,n){return new i(t,e,n)},i.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer)},e.exports=i},{}],7:[function(t,e,r){var n=t("./GLTexture"),i=function(t,e,r){this.gl=t,this.framebuffer=t.createFramebuffer(),this.stencil=null,this.texture=null,this.width=e||100,this.height=r||100};i.prototype.enableTexture=function(t){var e=this.gl;this.texture=t||new n(e),this.texture.bind(),this.bind(),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0)},i.prototype.enableStencil=function(){if(!this.stencil){var t=this.gl;this.stencil=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.stencil),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.stencil),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,this.width,this.height)}},i.prototype.clear=function(t,e,r,n){this.bind();var i=this.gl;i.clearColor(t,e,r,n),i.clear(i.COLOR_BUFFER_BIT)},i.prototype.bind=function(){var t=this.gl;this.texture&&this.texture.unbind(),t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer)},i.prototype.unbind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)},i.prototype.resize=function(t,e){var r=this.gl;this.width=t,this.height=e,this.texture&&this.texture.uploadData(null,t,e),this.stencil&&(r.bindRenderbuffer(r.RENDERBUFFER,this.stencil),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e))},i.prototype.destroy=function(){var t=this.gl;this.texture&&this.texture.destroy(),t.deleteFramebuffer(this.framebuffer),this.gl=null,this.stencil=null,this.texture=null},i.createRGBA=function(t,e,r){var o=n.fromData(t,null,e,r);o.enableNearestScaling(),o.enableWrapClamp();var s=new i(t,e,r);return s.enableTexture(o),s.unbind(),s},i.createFloat32=function(t,e,r,o){var s=new n.fromData(t,o,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},e.exports=i},{"./GLTexture":9}],8:[function(t,e,r){var n=t("./shader/compileProgram"),i=t("./shader/extractAttributes"),o=t("./shader/extractUniforms"),s=t("./shader/generateUniformAccessObject"),a=function(t,e,r){this.gl=t,this.program=n(t,e,r),this.attributes=i(t,this.program);var a=o(t,this.program);this.uniforms=s(t,a)};a.prototype.bind=function(){this.gl.useProgram(this.program)},a.prototype.destroy=function(){},e.exports=a},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18}],9:[function(t,e,r){var n=function(t,e,r,n,i){this.gl=t,this.texture=t.createTexture(),this.mipmap=!1,this.premultiplyAlpha=!1,this.width=e||0,this.height=r||0,this.format=n||t.RGBA,this.type=i||t.UNSIGNED_BYTE};n.prototype.upload=function(t){this.bind();var e=this.gl;this.width=t.videoWidth||t.width,this.height=t.videoHeight||t.height,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),e.texImage2D(e.TEXTURE_2D,0,this.format,this.format,this.type,t)};var i=!1;n.prototype.uploadData=function(t,e,r){this.bind();var n=this.gl;if(this.width=e||this.width,this.height=r||this.height,t instanceof Float32Array){if(!i){var o=n.getExtension("OES_texture_float");if(!o)throw new Error("floating point textures not available");i=!0}this.type=n.FLOAT}else this.type=n.UNSIGNED_BYTE;n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),n.texImage2D(n.TEXTURE_2D,0,this.format,this.width,this.height,0,this.format,this.type,t||null)},n.prototype.bind=function(t){var e=this.gl;void 0!==t&&e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,this.texture)},n.prototype.unbind=function(){var t=this.gl;t.bindTexture(t.TEXTURE_2D,null)},n.prototype.minFilter=function(t){var e=this.gl;this.bind(),this.mipmap?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.magFilter=function(t){var e=this.gl;this.bind(),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.enableMipmap=function(){var t=this.gl;this.bind(),this.mipmap=!0,t.generateMipmap(t.TEXTURE_2D)},n.prototype.enableLinearScaling=function(){this.minFilter(!0),this.magFilter(!0)},n.prototype.enableNearestScaling=function(){this.minFilter(!1),this.magFilter(!1)},n.prototype.enableWrapClamp=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)},n.prototype.enableWrapRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT)},n.prototype.enableWrapMirrorRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.MIRRORED_REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.MIRRORED_REPEAT)},n.prototype.destroy=function(){var t=this.gl;t.deleteTexture(this.texture)},n.fromSource=function(t,e,r){var i=new n(t);return i.premultiplyAlpha=r||!1,i.upload(e),i},n.fromData=function(t,e,r,i){var o=new n(t);return o.uploadData(e,r,i),o},e.exports=n},{}],10:[function(t,e,r){function n(t,e){if(this.nativeVaoExtension=null,n.FORCE_NATIVE||(this.nativeVaoExtension=t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object")),this.nativeState=e,this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var r=t.getParameter(t.MAX_VERTEX_ATTRIBS);this.nativeState={tempAttribState:new Array(r),attribState:new Array(r)}}this.gl=t,this.attributes=[],this.indexBuffer=null,this.dirty=!1}var i=t("./setVertexAttribArrays");n.prototype.constructor=n,e.exports=n,n.FORCE_NATIVE=!1,n.prototype.bind=function(){return this.nativeVao?(this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao),this.dirty&&(this.dirty=!1,this.activate())):this.activate(),this},n.prototype.unbind=function(){return this.nativeVao&&this.nativeVaoExtension.bindVertexArrayOES(null),this},n.prototype.activate=function(){for(var t=this.gl,e=null,r=0;r=0;n--){var i=t[n];"."===i?t.splice(n,1):".."===i?(t.splice(n,1),r++):r&&(t.splice(n,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}function n(t,e){if(t.filter)return t.filter(e);for(var r=[],n=0;n=-1&&!i;o--){var s=o>=0?arguments[o]:t.cwd();if("string"!=typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(r=s+"/"+r,i="/"===s.charAt(0))}return r=e(n(r.split("/"),function(t){return!!t}),!i).join("/"),(i?"/":"")+r||"."},r.normalize=function(t){var i=r.isAbsolute(t),o="/"===s(t,-1);return t=e(n(t.split("/"),function(t){return!!t}),!i).join("/"),t||i||(t="."),t&&o&&(t+="/"),(i?"/":"")+t},r.isAbsolute=function(t){return"/"===t.charAt(0)},r.join=function(){var t=Array.prototype.slice.call(arguments,0);return r.normalize(n(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},r.relative=function(t,e){function n(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=r.resolve(t).substr(1),e=r.resolve(e).substr(1);for(var i=n(t.split("/")),o=n(e.split("/")),s=Math.min(i.length,o.length),a=s,u=0;u1)for(var r=1;r1&&(n=r[0]+"@",t=r[1]),t=t.replace(I,".");var i=t.split("."),o=s(i,e).join(".");return n+o}function u(t){for(var e,r,n=[],i=0,o=t.length;i=55296&&e<=56319&&i65535&&(t-=65536,e+=B(t>>>10&1023|55296),t=56320|1023&t),e+=B(t)}).join("")}function l(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:w}function c(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function f(t,e,r){var n=0;for(t=r?F(t/M):t>>1,t+=F(t/e);t>j*S>>1;n+=w)t=F(t/j);return F(n+(j+1)*t/(t+O))}function d(t){var e,r,n,i,s,a,u,c,d,p,v=[],y=t.length,g=0,m=C,_=P;for(r=t.lastIndexOf(R),r<0&&(r=0),n=0;n=128&&o("not-basic"),v.push(t.charCodeAt(n));for(i=r>0?r+1:0;i=y&&o("invalid-input"),c=l(t.charCodeAt(i++)),(c>=w||c>F((T-g)/a))&&o("overflow"),g+=c*a,d=u<=_?E:u>=_+S?S:u-_,!(cF(T/p)&&o("overflow"),a*=p;e=v.length+1,_=f(g-s,e,0==s),F(g/e)>T-m&&o("overflow"),m+=F(g/e),g%=e,v.splice(g++,0,m)}return h(v)}function p(t){var e,r,n,i,s,a,h,l,d,p,v,y,g,m,_,b=[];for(t=u(t),y=t.length,e=C,r=0,s=P,a=0;a=e&&vF((T-r)/g)&&o("overflow"),r+=(h-e)*g,e=h,a=0;aT&&o("overflow"),v==e){for(l=r,d=w;p=d<=s?E:d>=s+S?S:d-s,!(l= 0x80 (not a basic code point)","invalid-input":"Invalid input"},j=w-E,F=Math.floor,B=String.fromCharCode;if(b={version:"1.4.1",ucs2:{decode:u,encode:h},decode:d,encode:p,toASCII:y,toUnicode:v},"function"==typeof t&&"object"==typeof t.amd&&t.amd)t("punycode",function(){return b});else if(g&&m)if(r.exports==g)m.exports=b;else for(x in b)b.hasOwnProperty(x)&&(g[x]=b[x]);else i.punycode=b}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],25:[function(t,e,r){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,r,o){e=e||"&",r=r||"=";var s={};if("string"!=typeof t||0===t.length)return s;var a=/\+/g;t=t.split(e);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var h=t.length;u>0&&h>u&&(h=u);for(var l=0;l=0?(c=v.substr(0,y),f=v.substr(y+1)):(c=v,f=""),d=decodeURIComponent(c),p=decodeURIComponent(f),n(s,d)?i(s[d])?s[d].push(p):s[d]=[s[d],p]:s[d]=p}return s};var i=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],26:[function(t,e,r){"use strict";function n(t,e){if(t.map)return t.map(e);for(var r=[],n=0;n",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(d),v=["'"].concat(p),y=["%","/","?",";","#"].concat(v),g=["/","?","#"],m=255,_=/^[+a-z0-9A-Z_-]{0,63}$/,b=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,x={javascript:!0,"javascript:":!0},T={javascript:!0,"javascript:":!0},w={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},E=t("querystring");n.prototype.parse=function(t,e,r){if(!h.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var n=t.indexOf("?"),i=n!==-1&&n127?"x":L[F];if(!j.match(_)){var k=A.slice(0,M),N=A.slice(M+1),U=L.match(b);U&&(k.push(U[1]),N.unshift(U[2])),N.length&&(a="/"+N.join(".")+a),this.hostname=k.join(".");break}}}this.hostname.length>m?this.hostname="":this.hostname=this.hostname.toLowerCase(),D||(this.hostname=u.toASCII(this.hostname));var X=this.port?":"+this.port:"",W=this.hostname||"";this.host=W+X,this.href+=this.host,D&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==a[0]&&(a="/"+a))}if(!x[p])for(var M=0,I=v.length;M0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return r.search=t.search,r.query=t.query,h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!x.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var O=x.slice(-1)[0],M=(r.host||t.host||x.length>1)&&("."===O||".."===O)||""===O,P=0,C=x.length;C>=0;C--)O=x[C],"."===O?x.splice(C,1):".."===O?(x.splice(C,1),P++):P&&(x.splice(C,1),P--);if(!_&&!b)for(;P--;P)x.unshift("..");!_||""===x[0]||x[0]&&"/"===x[0].charAt(0)||x.unshift(""),M&&"/"!==x.join("/").substr(-1)&&x.push("");var R=""===x[0]||x[0]&&"/"===x[0].charAt(0);if(E){r.hostname=r.host=R?"":x.length?x.shift():"";var S=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return _=_||r.host&&x.length,_&&!R&&x.unshift(""),x.length?r.pathname=x.join("/"):(r.pathname=null,r.path=null),h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},n.prototype.parseHost=function(){var t=this.host,e=c.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":29,punycode:24,querystring:27}],29:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],30:[function(t,e,r){arguments[4][3][0].apply(r,arguments)},{dup:3}],31:[function(t,e,r){"use strict";e.exports=function(t,e){e=e||{};for(var r={key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}},n=r.parser[e.strictMode?"strict":"loose"].exec(t),i={},o=14;o--;)i[r.key[o]]=n[o]||"";return i[r.q.name]={},i[r.key[12]].replace(r.q.parser,function(t,e,n){e&&(i[r.q.name][e]=n)}),i}},{}],32:[function(t,e,r){"use strict";function n(t,e){a.call(this),e=e||u,this.baseUrl=t||"",this.progress=0,this.loading=!1,this._progressChunk=0,this._beforeMiddleware=[],this._afterMiddleware=[],this._boundLoadResource=this._loadResource.bind(this),this._buffer=[],this._numToLoad=0,this._queue=o.queue(this._boundLoadResource,e),this.resources={}}var i=t("parse-uri"),o=t("./async"),s=t("./Resource"),a=t("eventemitter3"),u=10,h=100;n.prototype=Object.create(a.prototype),n.prototype.constructor=n,e.exports=n,n.prototype.add=n.prototype.enqueue=function(t,e,r,n){if(Array.isArray(t)){for(var i=0;i0))return void this.abort("["+t.status+"]"+t.statusText+":"+t.responseURL);if(this.xhrType===n.XHR_RESPONSE_TYPE.TEXT)this.data=t.responseText;else if(this.xhrType===n.XHR_RESPONSE_TYPE.JSON)try{this.data=JSON.parse(t.responseText),this.isJson=!0}catch(t){return void this.abort("Error trying to parse loaded json:",t)}else if(this.xhrType===n.XHR_RESPONSE_TYPE.DOCUMENT)try{if(window.DOMParser){var r=new DOMParser;this.data=r.parseFromString(t.responseText,"text/xml")}else{var i=document.createElement("div");i.innerHTML=t.responseText,this.data=i}this.isXml=!0}catch(t){return void this.abort("Error trying to parse loaded xml:",t)}else this.data=t.response||t.responseText;this.complete()},n.prototype._determineCrossOrigin=function(t,e){if(0===t.indexOf("data:"))return"";e=e||window.location,h||(h=document.createElement("a")),h.href=t,t=a(h.href,{strictMode:!0});var r=!t.port&&""===e.port||t.port===e.port,n=t.protocol?t.protocol+":":"";return t.host===e.hostname&&r&&n===e.protocol?"":"anonymous"},n.prototype._determineXhrType=function(){return n._xhrTypeMap[this._getExtension()]||n.XHR_RESPONSE_TYPE.TEXT},n.prototype._determineLoadType=function(){return n._loadTypeMap[this._getExtension()]||n.LOAD_TYPE.XHR},n.prototype._getExtension=function(){var t=this.url,e="";if(this.isDataUrl){var r=t.indexOf("/");e=t.substring(r+1,t.indexOf(";",r))}else{var n=t.indexOf("?");n!==-1&&(t=t.substring(0,n)),e=t.substring(t.lastIndexOf(".")+1)}return e.toLowerCase()},n.prototype._getMimeFromXhrType=function(t){switch(t){case n.XHR_RESPONSE_TYPE.BUFFER:return"application/octet-binary";case n.XHR_RESPONSE_TYPE.BLOB:return"application/blob";case n.XHR_RESPONSE_TYPE.DOCUMENT:return"application/xml";case n.XHR_RESPONSE_TYPE.JSON:return"application/json";case n.XHR_RESPONSE_TYPE.DEFAULT:case n.XHR_RESPONSE_TYPE.TEXT:default:return"text/plain"}},n.LOAD_TYPE={XHR:1,IMAGE:2,AUDIO:3,VIDEO:4},n.XHR_RESPONSE_TYPE={DEFAULT:"text",BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"},n._loadTypeMap={gif:n.LOAD_TYPE.IMAGE,png:n.LOAD_TYPE.IMAGE,bmp:n.LOAD_TYPE.IMAGE,jpg:n.LOAD_TYPE.IMAGE,jpeg:n.LOAD_TYPE.IMAGE,tif:n.LOAD_TYPE.IMAGE,tiff:n.LOAD_TYPE.IMAGE,webp:n.LOAD_TYPE.IMAGE,tga:n.LOAD_TYPE.IMAGE,"svg+xml":n.LOAD_TYPE.IMAGE},n._xhrTypeMap={xhtml:n.XHR_RESPONSE_TYPE.DOCUMENT,html:n.XHR_RESPONSE_TYPE.DOCUMENT,htm:n.XHR_RESPONSE_TYPE.DOCUMENT,xml:n.XHR_RESPONSE_TYPE.DOCUMENT,tmx:n.XHR_RESPONSE_TYPE.DOCUMENT,tsx:n.XHR_RESPONSE_TYPE.DOCUMENT,svg:n.XHR_RESPONSE_TYPE.DOCUMENT,gif:n.XHR_RESPONSE_TYPE.BLOB,png:n.XHR_RESPONSE_TYPE.BLOB,bmp:n.XHR_RESPONSE_TYPE.BLOB,jpg:n.XHR_RESPONSE_TYPE.BLOB,jpeg:n.XHR_RESPONSE_TYPE.BLOB,tif:n.XHR_RESPONSE_TYPE.BLOB,tiff:n.XHR_RESPONSE_TYPE.BLOB,webp:n.XHR_RESPONSE_TYPE.BLOB,tga:n.XHR_RESPONSE_TYPE.BLOB,json:n.XHR_RESPONSE_TYPE.JSON,text:n.XHR_RESPONSE_TYPE.TEXT,txt:n.XHR_RESPONSE_TYPE.TEXT},n.setExtensionLoadType=function(t,e){o(n._loadTypeMap,t,e)},n.setExtensionXhrType=function(t,e){o(n._xhrTypeMap,t,e)}},{eventemitter3:30,"parse-uri":31}],34:[function(t,e,r){"use strict";function n(){}function i(t,e,r){var n=0,i=t.length;!function o(s){return s||n===i?void(r&&r(s)):void e(t[n++],o)}()}function o(t){return function(){if(null===t)throw new Error("Callback was already called.");var e=t;t=null,e.apply(this,arguments)}}function s(t,e){function r(t,e,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(a.started=!0,null==t&&a.idle())return void setTimeout(function(){a.drain()},1);var i={data:t,callback:"function"==typeof r?r:n};e?a._tasks.unshift(i):a._tasks.push(i),setTimeout(function(){a.process()},1)}function i(t){return function(){s-=1,t.callback.apply(t,arguments),null!=arguments[0]&&a.error(arguments[0],t.data),s<=a.concurrency-a.buffer&&a.unsaturated(),a.idle()&&a.drain(),a.process()}}if(null==e)e=1;else if(0===e)throw new Error("Concurrency must not be zero");var s=0,a={_tasks:[],concurrency:e,saturated:n,unsaturated:n,buffer:e/4,empty:n,drain:n,error:n,started:!1,paused:!1,push:function(t,e){r(t,!1,e)},kill:function(){a.drain=n,a._tasks=[]},unshift:function(t,e){r(t,!0,e)},process:function(){for(;!a.paused&&s>2,n[1]=(3&e[0])<<4|e[1]>>4,n[2]=(15&e[1])<<2|e[2]>>6,n[3]=63&e[2],s=i-(t.length-1)){case 2:n[3]=64,n[2]=64;break;case 1:n[3]=64}for(o=0;o=0;r--)this.updateAccessibleObjects(e[r])}},t.prototype.update=function(){if(this.renderer.renderingToScreen){this.updateAccessibleObjects(this.renderer._lastObjectRendered);var t=this.renderer.view.getBoundingClientRect(),e=t.width/this.renderer.width,r=t.height/this.renderer.height,n=this.div;n.style.left=t.left+"px",n.style.top=t.top+"px",n.style.width=this.renderer.width+"px", +n.style.height=this.renderer.height+"px";for(var i=0;ithis.renderer.width&&(t.width=this.renderer.width-t.x),t.y+t.height>this.renderer.height&&(t.height=this.renderer.height-t.y)},t.prototype.addChild=function(t){var e=this.pool.pop();e||(e=document.createElement("button"),e.style.width=d+"px",e.style.height=d+"px",e.style.backgroundColor=this.debug?"rgba(255,0,0,0.5)":"transparent",e.style.position="absolute",e.style.zIndex=y,e.style.borderStyle="none",e.addEventListener("click",this._onClick.bind(this)),e.addEventListener("focus",this._onFocus.bind(this)),e.addEventListener("focusout",this._onFocusOut.bind(this))),t.accessibleTitle?e.title=t.accessibleTitle:t.accessibleTitle||t.accessibleHint||(e.title="displayObject "+this.tabIndex),t.accessibleHint&&e.setAttribute("aria-label",t.accessibleHint),t._accessibleActive=!0,t._accessibleDiv=e,e.displayObject=t,this.children.push(t),this.div.appendChild(t._accessibleDiv),t._accessibleDiv.tabIndex=t.tabIndex},t.prototype._onClick=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"click",e.eventData)},t.prototype._onFocus=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseover",e.eventData)},t.prototype._onFocusOut=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseout",e.eventData)},t.prototype._onKeyDown=function(t){t.keyCode===f&&this.activate()},t.prototype._onMouseMove=function(){this.deactivate()},t.prototype.destroy=function(){this.div=null;for(var t=0;t]*(?:\s(width|height)="(\d*(?:\.\d+)?)(?:px)?")[^>]*(?:\s(width|height)="(\d*(?:\.\d+)?)(?:px)?")[^>]*>/i,r.SHAPES={POLY:0,RECT:1,CIRC:2,ELIP:3,RREC:4},r.PRECISION={DEFAULT:"mediump",LOW:"lowp",MEDIUM:"mediump",HIGH:"highp"},r.TRANSFORM_MODE={DEFAULT:0,STATIC:0,DYNAMIC:1},r.TEXT_GRADIENT={LINEAR_VERTICAL:0,LINEAR_HORIZONTAL:1},r.SPRITE_BATCH_SIZE=4096,r.SPRITE_MAX_TEXTURES=(0,o.default)(32)},{"./utils/maxRecommendedTextures":117}],44:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../math"),o=function(){function t(){n(this,t),this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0),this.rect=null}return t.prototype.isEmpty=function(){return this.minX>this.maxX||this.minY>this.maxY},t.prototype.clear=function(){this.updateID++,this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0)},t.prototype.getRectangle=function(t){return this.minX>this.maxX||this.minY>this.maxY?i.Rectangle.EMPTY:(t=t||new i.Rectangle(0,0,1,1),t.x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)},t.prototype.addPoint=function(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)},t.prototype.addQuad=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY,o=t[0],s=t[1];e=on?o:n,i=s>i?s:i,o=t[2],s=t[3],e=on?o:n,i=s>i?s:i,o=t[4],s=t[5],e=on?o:n,i=s>i?s:i,o=t[6],s=t[7],e=on?o:n,i=s>i?s:i,this.minX=e,this.minY=r,this.maxX=n,this.maxY=i},t.prototype.addFrame=function(t,e,r,n,i){var o=t.worldTransform,s=o.a,a=o.b,u=o.c,h=o.d,l=o.tx,c=o.ty,f=this.minX,d=this.minY,p=this.maxX,v=this.maxY,y=s*e+u*r+l,g=a*e+h*r+c;f=yp?y:p,v=g>v?g:v,y=s*n+u*r+l,g=a*n+h*r+c,f=yp?y:p,v=g>v?g:v,y=s*e+u*i+l,g=a*e+h*i+c,f=yp?y:p,v=g>v?g:v,y=s*n+u*i+l,g=a*n+h*i+c,f=yp?y:p,v=g>v?g:v,this.minX=f,this.minY=d,this.maxX=p,this.maxY=v},t.prototype.addVertices=function(t,e,r,n){for(var i=t.worldTransform,o=i.a,s=i.b,a=i.c,u=i.d,h=i.tx,l=i.ty,c=this.minX,f=this.minY,d=this.maxX,p=this.maxY,v=r;vd?m:d,p=_>p?_:p}this.minX=c,this.minY=f,this.maxX=d,this.maxY=p},t.prototype.addBounds=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY;this.minX=t.minXn?t.maxX:n,this.maxY=t.maxY>i?t.maxY:i},t.prototype.addBoundsMask=function(t,e){var r=t.minX>e.minX?t.minX:e.minX,n=t.minY>e.minY?t.minY:e.minY,i=t.maxXu?i:u,this.maxY=o>h?o:h}},t.prototype.addBoundsArea=function(t,e){var r=t.minX>e.x?t.minX:e.x,n=t.minY>e.y?t.minY:e.y,i=t.maxXu?i:u,this.maxY=o>h?o:h}},t}();r.default=o},{"../math":67}],45:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rthis.children.length)throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length);return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),this.onChildrenChange(e),t.emit("added",this),t},e.prototype.swapChildren=function(t,e){if(t!==e){var r=this.getChildIndex(t),n=this.getChildIndex(e);this.children[r]=e,this.children[n]=t,this.onChildrenChange(r=this.children.length)throw new Error("The supplied index is out of bounds");var r=this.getChildIndex(t);(0,u.removeItems)(this.children,r,1),this.children.splice(e,0,t),this.onChildrenChange(e)},e.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Index ("+t+") does not exist.");return this.children[t]},e.prototype.removeChild=function(){for(var t=arguments.length,e=Array(t),r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=t,n="number"==typeof e?e:this.children.length,i=n-r,o=void 0;if(i>0&&i<=n){o=this.children.splice(r,i);for(var s=0;s2&&void 0!==arguments[2]&&arguments[2];return r||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)},e.prototype.toLocal=function(t,e,r,n){return e&&(t=e.toGlobal(t,r,n)),n||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,r)},e.prototype.renderWebGL=function(t){},e.prototype.renderCanvas=function(t){},e.prototype.setParent=function(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t},e.prototype.setTransform=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0,u=arguments.length>8&&void 0!==arguments[8]?arguments[8]:0;return this.position.x=t,this.position.y=e,this.scale.x=r?r:1,this.scale.y=n?n:1,this.rotation=i,this.skew.x=o,this.skew.y=s,this.pivot.x=a,this.pivot.y=u,this},e.prototype.destroy=function(){this.removeAllListeners(),this.parent&&this.parent.removeChild(this),this.transform=null,this.parent=null,this._bounds=null,this._currentBounds=null,this._mask=null,this.filterArea=null,this.interactive=!1,this.interactiveChildren=!1},a(e,[{key:"_tempDisplayObjectParent",get:function(){return null===this.tempDisplayObjectParent&&(this.tempDisplayObjectParent=new e),this.tempDisplayObjectParent}},{key:"x",get:function(){return this.position.x},set:function(t){this.transform.position.x=t}},{key:"y",get:function(){return this.position.y},set:function(t){this.transform.position.y=t}},{key:"worldTransform",get:function(){return this.transform.worldTransform}},{key:"localTransform",get:function(){return this.transform.localTransform}},{key:"position",get:function(){return this.transform.position},set:function(t){this.transform.position.copy(t)}},{key:"scale",get:function(){return this.transform.scale},set:function(t){this.transform.scale.copy(t)}},{key:"pivot",get:function(){return this.transform.pivot},set:function(t){this.transform.pivot.copy(t)}},{key:"skew",get:function(){return this.transform.skew},set:function(t){this.transform.skew.copy(t)}},{key:"rotation",get:function(){return this.transform.rotation},set:function(t){this.transform.rotation=t}},{key:"worldVisible",get:function(){var t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask&&(this._mask.renderable=!0),this._mask=t,this._mask&&(this._mask.renderable=!1)}},{key:"filters",get:function(){return this._filters&&this._filters.slice()},set:function(t){this._filters=t&&t.slice()}}]),e}(h.default);r.default=m,m.prototype.displayObjectUpdateTransform=m.prototype.updateTransform},{"../const":43,"../math":67,"./Bounds":44,"./Transform":47,"./TransformStatic":49,eventemitter3:3}],47:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;if(this.lineWidth=t,this.lineColor=e,this.lineAlpha=r,this.currentPath)if(this.currentPath.shape.points.length){var n=new g.Polygon(this.currentPath.shape.points.slice(-2));n.closed=!1,this.drawShape(n)}else this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha;return this},e.prototype.moveTo=function(t,e){var r=new g.Polygon([t,e]);return r.closed=!1,this.drawShape(r),this},e.prototype.lineTo=function(t,e){return this.currentPath.shape.points.push(t,e),this.dirty++,this},e.prototype.quadraticCurveTo=function(t,e,r,n){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var i=20,o=this.currentPath.shape.points,s=0,a=0;0===o.length&&this.moveTo(0,0);for(var u=o[o.length-2],h=o[o.length-1],l=1;l<=i;++l){var c=l/i;s=u+(t-u)*c,a=h+(e-h)*c,o.push(s+(t+(r-t)*c-s)*c,a+(e+(n-e)*c-a)*c)}return this.dirty++,this},e.prototype.bezierCurveTo=function(t,e,r,n,i,o){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var s=this.currentPath.shape.points,a=s[s.length-2],u=s[s.length-1];return s.length-=2,(0,w.default)(a,u,t,e,r,n,i,o,s),this.dirty++,this},e.prototype.arcTo=function(t,e,r,n,i){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(t,e):this.moveTo(t,e);var o=this.currentPath.shape.points,s=o[o.length-2],a=o[o.length-1],u=a-e,h=s-t,l=n-e,c=r-t,f=Math.abs(u*c-h*l);if(f<1e-8||0===i)o[o.length-2]===t&&o[o.length-1]===e||o.push(t,e);else{var d=u*u+h*h,p=l*l+c*c,v=u*l+h*c,y=i*Math.sqrt(d)/f,g=i*Math.sqrt(p)/f,m=y*v/d,_=g*v/p,b=y*c+g*h,x=y*l+g*u,T=h*(g+m),w=u*(g+m),E=c*(y+_),S=l*(y+_),O=Math.atan2(w-x,T-b),M=Math.atan2(S-x,E-b);this.arc(b+t,x+e,i,O,M,h*l>c*u)}return this.dirty++,this},e.prototype.arc=function(t,e,r,n,i){var o=arguments.length>5&&void 0!==arguments[5]&&arguments[5];if(n===i)return this;!o&&i<=n?i+=2*Math.PI:o&&n<=i&&(n+=2*Math.PI); +var s=o?n-i:i-n,a=40*Math.ceil(Math.abs(s)/(2*Math.PI));if(0===s)return this;var u=t+Math.cos(n)*r,h=e+Math.sin(n)*r,l=this.currentPath.shape.points;this.currentPath?l[l.length-2]===u&&l[l.length-1]===h||l.push(u,h):this.moveTo(u,h);for(var c=s/(2*a),f=2*c,d=Math.cos(c),p=Math.sin(c),v=a-1,y=v%1/v,g=0;g<=v;++g){var m=g+y*g,_=c+n+f*m,b=Math.cos(_),x=-Math.sin(_);l.push((d*b+p*x)*r+t,(d*-x+p*b)*r+e)}return this.dirty++,this},e.prototype.beginFill=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this.filling=!0,this.fillColor=t,this.fillAlpha=e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},e.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},e.prototype.drawRect=function(t,e,r,n){return this.drawShape(new g.Rectangle(t,e,r,n)),this},e.prototype.drawRoundedRect=function(t,e,r,n,i){return this.drawShape(new g.RoundedRectangle(t,e,r,n,i)),this},e.prototype.drawCircle=function(t,e,r){return this.drawShape(new g.Circle(t,e,r)),this},e.prototype.drawEllipse=function(t,e,r,n){return this.drawShape(new g.Ellipse(t,e,r,n)),this},e.prototype.drawPolygon=function(t){var e=t,r=!0;if(e instanceof g.Polygon&&(r=e.closed,e=e.points),!Array.isArray(e)){e=new Array(arguments.length);for(var n=0;n0)&&(this.lineWidth=0,this.filling=!1,this.dirty++,this.clearDirty++,this.graphicsData.length=0),this},e.prototype.isFastRect=function(){return 1===this.graphicsData.length&&this.graphicsData[0].shape.type===_.SHAPES.RECT&&!this.graphicsData[0].lineWidth},e.prototype._renderWebGL=function(t){this.dirty!==this.fastRectDirty&&(this.fastRectDirty=this.dirty,this._fastRect=this.isFastRect()),this._fastRect?this._renderSpriteRect(t):(t.setObjectRenderer(t.plugins.graphics),t.plugins.graphics.render(this))},e.prototype._renderSpriteRect=function(t){var r=this.graphicsData[0].shape;if(!this._spriteRect){if(!e._SPRITE_TEXTURE){e._SPRITE_TEXTURE=l.default.create(10,10);var n=document.createElement("canvas");n.width=10,n.height=10;var i=n.getContext("2d");i.fillStyle="white",i.fillRect(0,0,10,10),e._SPRITE_TEXTURE=f.default.fromCanvas(n)}this._spriteRect=new y.default(e._SPRITE_TEXTURE)}if(16777215===this.tint)this._spriteRect.tint=this.graphicsData[0].fillColor;else{var o=C,s=R;(0,m.hex2rgb)(this.graphicsData[0].fillColor,o),(0,m.hex2rgb)(this.tint,s),o[0]*=s[0],o[1]*=s[1],o[2]*=s[2],this._spriteRect.tint=(0,m.rgb2hex)(o)}this._spriteRect.alpha=this.graphicsData[0].fillAlpha,this._spriteRect.worldAlpha=this.worldAlpha*this._spriteRect.alpha,e._SPRITE_TEXTURE._frame.width=r.width,e._SPRITE_TEXTURE._frame.height=r.height,this._spriteRect.transform.worldTransform=this.transform.worldTransform,this._spriteRect.anchor.set(-r.x/r.width,-r.y/r.height),this._spriteRect._onAnchorUpdate(),this._spriteRect._renderWebGL(t)},e.prototype._renderCanvas=function(t){this.isMask!==!0&&t.plugins.graphics.render(this)},e.prototype._calculateBounds=function(){this.boundsDirty!==this.dirty&&(this.boundsDirty=this.dirty,this.updateLocalBounds(),this.dirty++,this.cachedSpriteDirty=!0);var t=this._localBounds;this._bounds.addFrame(this.transform,t.minX,t.minY,t.maxX,t.maxY)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,P);for(var e=this.graphicsData,r=0;re?o+a:e,r=sn?s+u:n;else if(c===_.SHAPES.CIRC)o=i.x,s=i.y,a=i.radius+f/2,u=i.radius+f/2,t=o-ae?o+a:e,r=s-un?s+u:n;else if(c===_.SHAPES.ELIP)o=i.x,s=i.y,a=i.width+f/2,u=i.height+f/2,t=o-ae?o+a:e,r=s-un?s+u:n;else for(var d=i.points,p=0;pe?o+f:e,r=s-fn?s+f:n}else t=0,e=0,r=0,n=0;var v=this.boundsPadding;this._localBounds.minX=t-v,this._localBounds.maxX=e+2*v,this._localBounds.minY=r-v,this._localBounds.maxY=n+2*v},e.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null;var e=new p.default(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===_.SHAPES.POLY&&(e.shape.closed=e.shape.closed||this.filling,this.currentPath=e),this.dirty++,e},e.prototype.generateCanvasTexture=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=this.getLocalBounds(),n=l.default.create(r.width,r.height,t,e);O||(O=new S.default),M.tx=-r.x,M.ty=-r.y,O.render(this,n,!1,M);var i=f.default.fromCanvas(n.baseTexture._canvasRenderTarget.canvas,t);return i.baseTexture.resolution=e,i.baseTexture.update(),i},e.prototype.closePath=function(){var t=this.currentPath;return t&&t.shape&&t.shape.close(),this},e.prototype.addHole=function(){var t=this.graphicsData.pop();return this.currentPath=this.graphicsData[this.graphicsData.length-1],this.currentPath.addHole(t.shape),this.currentPath=null,this},e.prototype.destroy=function(e){t.prototype.destroy.call(this,e);for(var r=0;rC?C:P,r.beginPath(),r.moveTo(E,S+P),r.lineTo(E,S+M-P),r.quadraticCurveTo(E,S+M,E+P,S+M),r.lineTo(E+O-P,S+M),r.quadraticCurveTo(E+O,S+M,E+O,S+M-P),r.lineTo(E+O,S+P),r.quadraticCurveTo(E+O,S,E+O-P,S),r.lineTo(E+P,S),r.quadraticCurveTo(E,S,E,S+P),r.closePath(),(u.fillColor||0===u.fillColor)&&(r.globalAlpha=u.fillAlpha*n,r.fillStyle="#"+("00000"+(0|l).toString(16)).substr(-6),r.fill()),u.lineWidth&&(r.globalAlpha=u.lineAlpha*n,r.strokeStyle="#"+("00000"+(0|c).toString(16)).substr(-6),r.stroke())}}},t.prototype.updateGraphicsTint=function(t){t._prevTint=t.tint;for(var e=(t.tint>>16&255)/255,r=(t.tint>>8&255)/255,n=(255&t.tint)/255,i=0;i>16&255)/255*e*255<<16)+((s>>8&255)/255*r*255<<8)+(255&s)/255*n*255,o._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*r*255<<8)+(255&a)/255*n*255}},t.prototype.renderPolygon=function(t,e,r){r.moveTo(t[0],t[1]);for(var n=1;n8&&void 0!==arguments[8]?arguments[8]:[],h=20,l=0,c=0,f=0,d=0,p=0;u.push(t,e);for(var v=1,y=0;v<=h;++v)y=v/h,l=1-y,c=l*l,f=c*l,d=y*y,p=d*y,u.push(f*t+3*c*y*r+3*l*d*i+p*s,f*e+3*c*y*n+3*l*d*o+p*a);return u}r.__esModule=!0,r.default=n},{}],54:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../utils"),u=t("../../const"),h=t("../../renderers/webgl/utils/ObjectRenderer"),l=n(h),c=t("../../renderers/webgl/WebGLRenderer"),f=n(c),d=t("./WebGLGraphicsData"),p=n(d),v=t("./shaders/PrimitiveShader"),y=n(v),g=t("./utils/buildPoly"),m=n(g),_=t("./utils/buildRectangle"),b=n(_),x=t("./utils/buildRoundedRectangle"),T=n(x),w=t("./utils/buildCircle"),E=n(w),S=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.graphicsDataPool=[],n.primitiveShader=null,n.gl=r.gl,n.CONTEXT_UID=0,n}return s(e,t),e.prototype.onContextChange=function(){this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.primitiveShader=new y.default(this.gl)},e.prototype.destroy=function(){l.default.prototype.destroy.call(this);for(var t=0;t32e4)&&(r=this.graphicsDataPool.pop()||new p.default(this.renderer.gl,this.primitiveShader,this.renderer.state.attribsState),r.reset(e),t.data.push(r)),r.dirty=!0,r},e}(l.default);r.default=S,f.default.registerPlugin("graphics",S)},{"../../const":43,"../../renderers/webgl/WebGLRenderer":81,"../../renderers/webgl/utils/ObjectRenderer":91,"../../utils":116,"./WebGLGraphicsData":55,"./shaders/PrimitiveShader":56,"./utils/buildCircle":57,"./utils/buildPoly":59,"./utils/buildRectangle":60,"./utils/buildRoundedRectangle":61}],55:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("pixi-gl-core"),s=n(o),a=function(){function t(e,r,n){i(this,t),this.gl=e,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=s.default.GLBuffer.createVertexBuffer(e),this.indexBuffer=s.default.GLBuffer.createIndexBuffer(e),this.dirty=!0,this.glPoints=null,this.glIndices=null,this.shader=r,this.vao=new s.default.VertexArrayObject(e,n).addIndex(this.indexBuffer).addAttribute(this.buffer,r.attributes.aVertexPosition,e.FLOAT,!1,24,0).addAttribute(this.buffer,r.attributes.aColor,e.FLOAT,!1,24,8)}return t.prototype.reset=function(){this.points.length=0,this.indices.length=0},t.prototype.upload=function(){this.glPoints=new Float32Array(this.points),this.buffer.upload(this.glPoints),this.glIndices=new Uint16Array(this.indices),this.indexBuffer.upload(this.glIndices),this.dirty=!1},t.prototype.destroy=function(){this.color=null,this.points=null,this.indices=null,this.vao.destroy(),this.buffer.destroy(),this.indexBuffer.destroy(),this.gl=null,this.buffer=null,this.indexBuffer=null,this.glPoints=null,this.glIndices=null},t}();r.default=a},{"pixi-gl-core":12}],56:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../../Shader"),u=n(a),h=function(t){function e(r){return i(this,e),o(this,t.call(this,r,["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","uniform float alpha;","uniform vec3 tint;","varying vec4 vColor;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"].join("\n"),["varying vec4 vColor;","void main(void){"," gl_FragColor = vColor;","}"].join("\n")))}return s(e,t),e}(u.default);r.default=h},{"../../../Shader":42}],57:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,o=void 0,h=void 0;t.type===a.SHAPES.CIRC?(o=r.radius,h=r.radius):(o=r.width,h=r.height);var l=Math.floor(30*Math.sqrt(r.radius))||Math.floor(15*Math.sqrt(r.width+r.height)),c=2*Math.PI/l;if(t.fill){var f=(0,u.hex2rgb)(t.fillColor),d=t.fillAlpha,p=f[0]*d,v=f[1]*d,y=f[2]*d,g=e.points,m=e.indices,_=g.length/6;m.push(_);for(var b=0;b196*p*p?(R=O-P,D=M-C,A=Math.sqrt(R*R+D*D),R/=A,D/=A,R*=p,D*=p,h.push(T-R,w-D),h.push(g,m,_,y),h.push(T+R,w+D),h.push(g,m,_,y),h.push(T-R,w-D),h.push(g,m,_,y),f++):(h.push(X,W),h.push(g,m,_,y),h.push(T-(X-T),w-(W-w)),h.push(g,m,_,y))}}b=r[2*(c-2)],x=r[2*(c-2)+1],T=r[2*(c-1)],w=r[2*(c-1)+1],O=-(x-w),M=b-T,A=Math.sqrt(O*O+M*M),O/=A,M/=A,O*=p,M*=p,h.push(T-O,w-M),h.push(g,m,_,y),h.push(T+O,w+M),h.push(g,m,_,y),l.push(d);for(var Y=0;Y=6){for(var n=[],i=t.holes,o=0;o0&&(0,s.default)(t,e)}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils"),u=t("earcut"),h=n(u)},{"../../../utils":116,"./buildLine":58,earcut:2}],60:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,o=r.width,u=r.height;if(t.fill){var h=(0,a.hex2rgb)(t.fillColor),l=t.fillAlpha,c=h[0]*l,f=h[1]*l,d=h[2]*l,p=e.points,v=e.indices,y=p.length/6;p.push(n,i),p.push(c,f,d,l),p.push(n+o,i),p.push(c,f,d,l),p.push(n,i+u),p.push(c,f,d,l),p.push(n+o,i+u),p.push(c,f,d,l),v.push(y,y,y+1,y+2,y+3,y+3)}if(t.lineWidth){var g=t.points;t.points=[n,i,n+o,i,n+o,i+u,n,i+u,n,i],(0,s.default)(t,e),t.points=g}}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils")},{"../../../utils":116,"./buildLine":58}],61:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,s=r.width,u=r.height,c=r.radius,f=[];if(f.push(n,i+c),o(n,i+u-c,n,i+u,n+c,i+u,f),o(n+s-c,i+u,n+s,i+u,n+s,i+u-c,f),o(n+s,i+c,n+s,i,n+s-c,i,f),o(n+c,i,n,i,n,i+c+1e-10,f),t.fill){for(var d=(0,l.hex2rgb)(t.fillColor),p=t.fillAlpha,v=d[0]*p,y=d[1]*p,g=d[2]*p,m=e.points,_=e.indices,b=m.length/6,x=(0,a.default)(f,null,2),T=0,w=x.length;T6&&void 0!==arguments[6]?arguments[6]:[],u=20,h=a,l=0,c=0,f=0,d=0,p=0,v=0,y=0,g=0;y<=u;++y)g=y/u,l=s(t,r,g),c=s(e,n,g),f=s(r,i,g),d=s(n,o,g),p=s(l,f,g),v=s(c,d,g),h.push(p,v);return h}r.__esModule=!0,r.default=i;var s=t("earcut"),a=n(s),u=t("./buildLine"),h=n(u),l=t("../../../utils")},{"../../../utils":116,"./buildLine":58,earcut:2}],62:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:800,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:600,r=arguments[2],n=arguments[3];return!n&&N.isWebGLSupported()?new H.default(t,e,r):new G.default(t,e,r)}r.__esModule=!0,r.Filter=r.SpriteMaskFilter=r.Quad=r.RenderTarget=r.ObjectRenderer=r.WebGLManager=r.Shader=r.CanvasRenderTarget=r.TextureUvs=r.VideoBaseTexture=r.BaseRenderTexture=r.RenderTexture=r.BaseTexture=r.Texture=r.CanvasGraphicsRenderer=r.GraphicsRenderer=r.GraphicsData=r.Graphics=r.TextStyle=r.Text=r.SpriteRenderer=r.CanvasTinter=r.CanvasSpriteRenderer=r.Sprite=r.TransformBase=r.TransformStatic=r.Transform=r.Container=r.DisplayObject=r.glCore=r.WebGLRenderer=r.CanvasRenderer=r.ticker=r.utils=void 0;var s=t("./const");Object.keys(s).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return s[t]}})});var a=t("./math");Object.keys(a).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return a[t]}})});var u=t("pixi-gl-core");Object.defineProperty(r,"glCore",{enumerable:!0,get:function(){return i(u).default}});var h=t("./display/DisplayObject");Object.defineProperty(r,"DisplayObject",{enumerable:!0,get:function(){return i(h).default}});var l=t("./display/Container");Object.defineProperty(r,"Container",{enumerable:!0,get:function(){return i(l).default}});var c=t("./display/Transform");Object.defineProperty(r,"Transform",{enumerable:!0,get:function(){return i(c).default}});var f=t("./display/TransformStatic");Object.defineProperty(r,"TransformStatic",{enumerable:!0,get:function(){return i(f).default}});var d=t("./display/TransformBase");Object.defineProperty(r,"TransformBase",{enumerable:!0,get:function(){return i(d).default}});var p=t("./sprites/Sprite");Object.defineProperty(r,"Sprite",{enumerable:!0,get:function(){return i(p).default}});var v=t("./sprites/canvas/CanvasSpriteRenderer");Object.defineProperty(r,"CanvasSpriteRenderer",{enumerable:!0,get:function(){return i(v).default}});var y=t("./sprites/canvas/CanvasTinter");Object.defineProperty(r,"CanvasTinter",{enumerable:!0,get:function(){return i(y).default}});var g=t("./sprites/webgl/SpriteRenderer");Object.defineProperty(r,"SpriteRenderer",{enumerable:!0,get:function(){return i(g).default}});var m=t("./text/Text");Object.defineProperty(r,"Text",{enumerable:!0,get:function(){return i(m).default}});var _=t("./text/TextStyle");Object.defineProperty(r,"TextStyle",{enumerable:!0,get:function(){return i(_).default}});var b=t("./graphics/Graphics");Object.defineProperty(r,"Graphics",{enumerable:!0,get:function(){return i(b).default}});var x=t("./graphics/GraphicsData");Object.defineProperty(r,"GraphicsData",{enumerable:!0,get:function(){return i(x).default}});var T=t("./graphics/webgl/GraphicsRenderer");Object.defineProperty(r,"GraphicsRenderer",{enumerable:!0,get:function(){return i(T).default}});var w=t("./graphics/canvas/CanvasGraphicsRenderer");Object.defineProperty(r,"CanvasGraphicsRenderer",{enumerable:!0,get:function(){return i(w).default}});var E=t("./textures/Texture");Object.defineProperty(r,"Texture",{enumerable:!0,get:function(){return i(E).default}});var S=t("./textures/BaseTexture");Object.defineProperty(r,"BaseTexture",{enumerable:!0,get:function(){return i(S).default}});var O=t("./textures/RenderTexture");Object.defineProperty(r,"RenderTexture",{enumerable:!0,get:function(){return i(O).default}});var M=t("./textures/BaseRenderTexture");Object.defineProperty(r,"BaseRenderTexture",{enumerable:!0,get:function(){return i(M).default}});var P=t("./textures/VideoBaseTexture");Object.defineProperty(r,"VideoBaseTexture",{enumerable:!0,get:function(){return i(P).default}});var C=t("./textures/TextureUvs");Object.defineProperty(r,"TextureUvs",{enumerable:!0,get:function(){return i(C).default}});var R=t("./renderers/canvas/utils/CanvasRenderTarget");Object.defineProperty(r,"CanvasRenderTarget",{enumerable:!0,get:function(){return i(R).default}});var D=t("./Shader");Object.defineProperty(r,"Shader",{enumerable:!0,get:function(){return i(D).default}});var A=t("./renderers/webgl/managers/WebGLManager");Object.defineProperty(r,"WebGLManager",{enumerable:!0,get:function(){return i(A).default}});var I=t("./renderers/webgl/utils/ObjectRenderer");Object.defineProperty(r,"ObjectRenderer",{enumerable:!0,get:function(){return i(I).default}});var L=t("./renderers/webgl/utils/RenderTarget");Object.defineProperty(r,"RenderTarget",{enumerable:!0,get:function(){return i(L).default}});var j=t("./renderers/webgl/utils/Quad");Object.defineProperty(r,"Quad",{enumerable:!0,get:function(){return i(j).default}});var F=t("./renderers/webgl/filters/spriteMask/SpriteMaskFilter");Object.defineProperty(r,"SpriteMaskFilter",{enumerable:!0,get:function(){return i(F).default}});var B=t("./renderers/webgl/filters/Filter");Object.defineProperty(r,"Filter",{enumerable:!0,get:function(){return i(B).default}}),r.autoDetectRenderer=o;var k=t("./utils"),N=n(k),U=t("./ticker"),X=n(U),W=t("./renderers/canvas/CanvasRenderer"),G=i(W),Y=t("./renderers/webgl/WebGLRenderer"),H=i(Y);r.utils=N,r.ticker=X,r.CanvasRenderer=G.default,r.WebGLRenderer=H.default},{"./Shader":42,"./const":43,"./display/Container":45,"./display/DisplayObject":46,"./display/Transform":47,"./display/TransformBase":48,"./display/TransformStatic":49,"./graphics/Graphics":50,"./graphics/GraphicsData":51,"./graphics/canvas/CanvasGraphicsRenderer":52,"./graphics/webgl/GraphicsRenderer":54,"./math":67,"./renderers/canvas/CanvasRenderer":74,"./renderers/canvas/utils/CanvasRenderTarget":76,"./renderers/webgl/WebGLRenderer":81,"./renderers/webgl/filters/Filter":83,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":86,"./renderers/webgl/managers/WebGLManager":90,"./renderers/webgl/utils/ObjectRenderer":91,"./renderers/webgl/utils/Quad":92,"./renderers/webgl/utils/RenderTarget":93,"./sprites/Sprite":98,"./sprites/canvas/CanvasSpriteRenderer":99,"./sprites/canvas/CanvasTinter":100,"./sprites/webgl/SpriteRenderer":102,"./text/Text":104,"./text/TextStyle":105,"./textures/BaseRenderTexture":106,"./textures/BaseTexture":107,"./textures/RenderTexture":108,"./textures/Texture":109,"./textures/TextureUvs":110,"./textures/VideoBaseTexture":111,"./ticker":113,"./utils":116,"pixi-gl-core":12}],63:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){return t<0?-1:t>0?1:0}function o(){for(var t=0;t<16;t++){var e=[];d.push(e);for(var r=0;r<16;r++)for(var n=i(u[t]*u[r]+l[t]*h[r]),o=i(h[t]*u[r]+c[t]*h[r]),s=i(u[t]*l[r]+l[t]*c[r]),p=i(h[t]*l[r]+c[t]*c[r]),v=0;v<16;v++)if(u[v]===n&&h[v]===o&&l[v]===s&&c[v]===p){e.push(v);break}}for(var y=0;y<16;y++){var g=new a.default;g.set(u[y],h[y],l[y],c[y],0,0),f.push(g)}}r.__esModule=!0;var s=t("./Matrix"),a=n(s),u=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],h=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],l=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],c=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],f=[],d=[];o();var p={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MIRROR_HORIZONTAL:12,uX:function(t){return u[t]},uY:function(t){return h[t]},vX:function(t){return l[t]},vY:function(t){return c[t]},inv:function(t){return 8&t?15&t:7&-t},add:function(t,e){return d[t][e]},sub:function(t,e){return d[t][p.inv(e)]},rotate180:function(t){return 4^t},isSwapWidthHeight:function(t){return 2===(3&t)},byDirection:function(t,e){return 2*Math.abs(t)<=Math.abs(e)?e>=0?p.S:p.N:2*Math.abs(e)<=Math.abs(t)?t>0?p.E:p.W:e>0?t>0?p.SE:p.SW:t>0?p.NE:p.NW},matrixAppendRotationInv:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=f[p.inv(e)];i.tx=r,i.ty=n,t.append(i)}};r.default=p},{"./Matrix":64}],64:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r=0&&(t.rotation+=t.rotation<=0?Math.PI:-Math.PI),t.skew.x=t.skew.y=0):(t.skew.x=o,t.skew.y=s),t.scale.x=Math.sqrt(e*e+r*r),t.scale.y=Math.sqrt(n*n+i*i),t.position.x=this.tx,t.position.y=this.ty,t},t.prototype.invert=function(){var t=this.a,e=this.b,r=this.c,n=this.d,i=this.tx,o=t*n-e*r;return this.a=n/o,this.b=-e/o,this.c=-r/o,this.d=t/o,this.tx=(r*this.ty-n*i)/o,this.ty=-(t*this.ty-e*i)/o,this},t.prototype.identity=function(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this},t.prototype.clone=function(){var e=new t;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e},t.prototype.copy=function(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t},o(t,null,[{key:"IDENTITY",get:function(){return new t}},{key:"TEMP_MATRIX",get:function(){return new t}}]),t}();r.default=u},{"./Point":66}],65:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this._x=i,this._y=o,this.cb=e,this.scope=r}return t.prototype.set=function(t,e){var r=t||0,n=e||(0!==e?r:0);this._x===r&&this._y===n||(this._x=r,this._y=n,this.cb.call(this.scope))},t.prototype.copy=function(t){this._x===t.x&&this._y===t.y||(this._x=t.x,this._y=t.y,this.cb.call(this.scope))},i(t,[{key:"x",get:function(){return this._x},set:function(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}},{key:"y",get:function(){return this._y},set:function(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}]),t}();r.default=o},{}],66:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;n(this,t),this.x=e,this.y=r}return t.prototype.clone=function(){return new t(this.x,this.y)},t.prototype.copy=function(t){this.set(t.x,t.y)},t.prototype.equals=function(t){return t.x===this.x&&t.y===this.y},t.prototype.set=function(t,e){this.x=t||0,this.y=e||(0!==e?this.x:0)},t}();r.default=i},{}],67:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./Point");Object.defineProperty(r,"Point",{enumerable:!0,get:function(){return n(i).default}});var o=t("./ObservablePoint");Object.defineProperty(r,"ObservablePoint",{enumerable:!0,get:function(){return n(o).default}});var s=t("./Matrix");Object.defineProperty(r,"Matrix",{enumerable:!0,get:function(){return n(s).default}});var a=t("./GroupD8");Object.defineProperty(r,"GroupD8",{enumerable:!0,get:function(){return n(a).default}});var u=t("./shapes/Circle");Object.defineProperty(r,"Circle",{enumerable:!0,get:function(){return n(u).default}});var h=t("./shapes/Ellipse");Object.defineProperty(r,"Ellipse",{enumerable:!0,get:function(){return n(h).default}});var l=t("./shapes/Polygon");Object.defineProperty(r,"Polygon",{enumerable:!0,get:function(){return n(l).default}});var c=t("./shapes/Rectangle");Object.defineProperty(r,"Rectangle",{enumerable:!0,get:function(){return n(c).default}});var f=t("./shapes/RoundedRectangle");Object.defineProperty(r,"RoundedRectangle",{enumerable:!0,get:function(){return n(f).default}})},{"./GroupD8":63,"./Matrix":64,"./ObservablePoint":65,"./Point":66,"./shapes/Circle":68,"./shapes/Ellipse":69,"./shapes/Polygon":70,"./shapes/Rectangle":71,"./shapes/RoundedRectangle":72}],68:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./Rectangle"),s=n(o),a=t("../../const"),u=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;i(this,t),this.x=e,this.y=r,this.radius=n,this.type=a.SHAPES.CIRC}return t.prototype.clone=function(){return new t(this.x,this.y,this.radius)},t.prototype.contains=function(t,e){if(this.radius<=0)return!1;var r=this.radius*this.radius,n=this.x-t,i=this.y-e;return n*=n,i*=i,n+i<=r},t.prototype.getBounds=function(){return new s.default(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)},t}();r.default=u},{"../../const":43,"./Rectangle":71}],69:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./Rectangle"),s=n(o),a=t("../../const"),u=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;i(this,t),this.x=e,this.y=r,this.width=n,this.height=o,this.type=a.SHAPES.ELIP}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;var r=(t-this.x)/this.width,n=(e-this.y)/this.height;return r*=r,n*=n,r+n<=1},t.prototype.getBounds=function(){return new s.default(this.x-this.width,this.y-this.height,this.width,this.height)},t}();r.default=u},{"../../const":43,"./Rectangle":71}],70:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../Point"),s=n(o),a=t("../../const"),u=function(){function t(){for(var e=arguments.length,r=Array(e),n=0;ne!=h>e&&t<(u-s)*((e-a)/(h-a))+s;l&&(r=!r)}return r},t}();r.default=u},{"../../const":43,"../Point":66}],71:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this.x=e,this.y=r,this.width=i,this.height=s,this.type=o.SHAPES.RECT}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this},t.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t=this.y&&et.x+t.width&&(this.width=t.width-this.x,this.width<0&&(this.width=0)),this.y+this.height>t.y+t.height&&(this.height=t.height-this.y,this.height<0&&(this.height=0))},t.prototype.enlarge=function(e){if(e!==t.EMPTY){var r=Math.min(this.x,e.x),n=Math.max(this.x+this.width,e.x+e.width),i=Math.min(this.y,e.y),o=Math.max(this.y+this.height,e.y+e.height);this.x=r,this.width=n-r,this.y=i,this.height=o-i}},i(t,[{key:"left",get:function(){return this.x}},{key:"right",get:function(){return this.x+this.width}},{key:"top",get:function(){return this.y}},{key:"bottom",get:function(){return this.y+this.height}}],[{key:"EMPTY",get:function(){return new t(0,0,0,0)}}]),t}();r.default=s},{"../../const":43}],72:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:20;n(this,t),this.x=e,this.y=r,this.width=o,this.height=s,this.radius=a,this.type=i.SHAPES.RREC}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height,this.radius)},t.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height)},t}();r.default=o},{"../../const":43}],73:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:{};i(this,e);var a=o(this,t.call(this,"Canvas",r,n,s));return a.type=y.RENDERER_TYPE.CANVAS,a.rootContext=a.view.getContext("2d",{alpha:a.transparent}),a.refresh=!0,a.maskManager=new l.default(a),a.smoothProperty="imageSmoothingEnabled",a.rootContext.imageSmoothingEnabled||(a.rootContext.webkitImageSmoothingEnabled?a.smoothProperty="webkitImageSmoothingEnabled":a.rootContext.mozImageSmoothingEnabled?a.smoothProperty="mozImageSmoothingEnabled":a.rootContext.oImageSmoothingEnabled?a.smoothProperty="oImageSmoothingEnabled":a.rootContext.msImageSmoothingEnabled&&(a.smoothProperty="msImageSmoothingEnabled")),a.initPlugins(),a.blendModes=(0,p.default)(),a._activeBlendMode=null,a.context=null,a.renderingToScreen=!1,a.resize(r,n),a}return s(e,t),e.prototype.render=function(t,e,r,n,i){if(this.view){this.renderingToScreen=!e,this.emit("prerender"),e?(e=e.baseTexture||e,e._canvasRenderTarget||(e._canvasRenderTarget=new f.default(e.width,e.height,e.resolution),e.source=e._canvasRenderTarget.canvas,e.valid=!0),this.context=e._canvasRenderTarget.context,this.resolution=e._canvasRenderTarget.resolution):this.context=this.rootContext;var o=this.context;if(e||(this._lastObjectRendered=t),!i){var s=t.parent,a=this._tempDisplayObjectParent.transform.worldTransform;n?n.copy(a):a.identity(),t.parent=this._tempDisplayObjectParent,t.updateTransform(),t.parent=s}o.setTransform(1,0,0,1,0,0),o.globalAlpha=1,o.globalCompositeOperation=this.blendModes[y.BLEND_MODES.NORMAL],navigator.isCocoonJS&&this.view.screencanvas&&(o.fillStyle="black",o.clear()),(void 0!==r?r:this.clearBeforeRender)&&this.renderingToScreen&&(this.transparent?o.clearRect(0,0,this.width,this.height):(o.fillStyle=this._backgroundColorString,o.fillRect(0,0,this.width,this.height)));var u=this.context;this.context=o,t.renderCanvas(this),this.context=u,this.emit("postrender")}},e.prototype.setBlendMode=function(t){this._activeBlendMode!==t&&(this.context.globalCompositeOperation=this.blendModes[t])},e.prototype.destroy=function(e){this.destroyPlugins(),t.prototype.destroy.call(this,e),this.context=null,this.refresh=!0,this.maskManager.destroy(),this.maskManager=null,this.smoothProperty=null},e.prototype.resize=function(e,r){t.prototype.resize.call(this,e,r),this.smoothProperty&&(this.rootContext[this.smoothProperty]=y.SCALE_MODES.DEFAULT===y.SCALE_MODES.LINEAR)},e}(u.default);r.default=g,v.pluginTarget.mixin(g)},{"../../const":43,"../../utils":116,"../SystemRenderer":73,"./utils/CanvasMaskManager":75,"./utils/CanvasRenderTarget":76,"./utils/mapCanvasBlendModesToPixi":78}],75:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../../const"),o=function(){function t(e){n(this,t),this.renderer=e}return t.prototype.pushMask=function(t){var e=this.renderer;e.context.save();var r=t.alpha,n=t.transform.worldTransform,i=e.resolution;e.context.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t._texture||(this.renderGraphicsShape(t),e.context.clip()),t.worldAlpha=r},t.prototype.renderGraphicsShape=function(t){var e=this.renderer.context,r=t.graphicsData.length;if(0!==r){e.beginPath();for(var n=0;nS?S:E,e.moveTo(b,x+E),e.lineTo(b,x+w-E),e.quadraticCurveTo(b,x+w,b+E,x+w),e.lineTo(b+T-E,x+w),e.quadraticCurveTo(b+T,x+w,b+T,x+w-E),e.lineTo(b+T,x+E),e.quadraticCurveTo(b+T,x,b+T-E,x),e.lineTo(b+E,x),e.quadraticCurveTo(b,x,b,x+E),e.closePath()}}}},t.prototype.popMask=function(t){t.context.restore()},t.prototype.destroy=function(){},t}();r.default=o},{"../../../const":43}],76:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:[];return(0,a.default)()?(t[o.BLEND_MODES.NORMAL]="source-over",t[o.BLEND_MODES.ADD]="lighter",t[o.BLEND_MODES.MULTIPLY]="multiply",t[o.BLEND_MODES.SCREEN]="screen",t[o.BLEND_MODES.OVERLAY]="overlay",t[o.BLEND_MODES.DARKEN]="darken",t[o.BLEND_MODES.LIGHTEN]="lighten",t[o.BLEND_MODES.COLOR_DODGE]="color-dodge",t[o.BLEND_MODES.COLOR_BURN]="color-burn",t[o.BLEND_MODES.HARD_LIGHT]="hard-light",t[o.BLEND_MODES.SOFT_LIGHT]="soft-light",t[o.BLEND_MODES.DIFFERENCE]="difference",t[o.BLEND_MODES.EXCLUSION]="exclusion",t[o.BLEND_MODES.HUE]="hue",t[o.BLEND_MODES.SATURATION]="saturate",t[o.BLEND_MODES.COLOR]="color",t[o.BLEND_MODES.LUMINOSITY]="luminosity"):(t[o.BLEND_MODES.NORMAL]="source-over",t[o.BLEND_MODES.ADD]="lighter",t[o.BLEND_MODES.MULTIPLY]="source-over",t[o.BLEND_MODES.SCREEN]="source-over",t[o.BLEND_MODES.OVERLAY]="source-over",t[o.BLEND_MODES.DARKEN]="source-over",t[o.BLEND_MODES.LIGHTEN]="source-over",t[o.BLEND_MODES.COLOR_DODGE]="source-over",t[o.BLEND_MODES.COLOR_BURN]="source-over",t[o.BLEND_MODES.HARD_LIGHT]="source-over",t[o.BLEND_MODES.SOFT_LIGHT]="source-over",t[o.BLEND_MODES.DIFFERENCE]="source-over",t[o.BLEND_MODES.EXCLUSION]="source-over",t[o.BLEND_MODES.HUE]="source-over",t[o.BLEND_MODES.SATURATION]="source-over",t[o.BLEND_MODES.COLOR]="source-over",t[o.BLEND_MODES.LUMINOSITY]="source-over"),t}r.__esModule=!0,r.default=i;var o=t("../../../const"),s=t("./canUseNewCanvasBlendModes"),a=n(s)},{"../../../const":43,"./canUseNewCanvasBlendModes":77}],79:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=function(){function t(e){n(this,t),this.renderer=e,this.count=0,this.checkCount=0,this.maxIdle=3600,this.checkCountMax=600,this.mode=i.GC_MODES.DEFAULT}return t.prototype.update=function(){this.count++,this.mode!==i.GC_MODES.MANUAL&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run()))},t.prototype.run=function(){for(var t=this.renderer.textureManager,e=t._managedTextures,r=!1,n=0;nthis.maxIdle&&(t.destroyTexture(i,!0),e[n]=null,r=!0)}if(r){for(var o=0,s=0;s=0;r--)this.unload(t.children[r])},t}();r.default=o},{"../../const":43}],80:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("pixi-gl-core"),s=t("../../const"),a=t("./utils/RenderTarget"),u=n(a),h=t("../../utils"),l=function(){function t(e){i(this,t),this.renderer=e,this.gl=e.gl,this._managedTextures=[]}return t.prototype.bindTexture=function(){},t.prototype.getTexture=function(){},t.prototype.updateTexture=function(t){t=t.baseTexture||t;var e=!!t._glRenderTargets;if(!t.hasLoaded)return null;var r=t._glTextures[this.renderer.CONTEXT_UID];if(r)e?t._glRenderTargets[this.renderer.CONTEXT_UID].resize(t.width,t.height):r.upload(t.source);else{if(e){var n=new u.default(this.gl,t.width,t.height,t.scaleMode,t.resolution);n.resize(t.width,t.height),t._glRenderTargets[this.renderer.CONTEXT_UID]=n,r=n.texture}else r=new o.GLTexture(this.gl),r.premultiplyAlpha=!0,r.upload(t.source);t._glTextures[this.renderer.CONTEXT_UID]=r,t.on("update",this.updateTexture,this),t.on("dispose",this.destroyTexture,this),this._managedTextures.push(t),t.isPowerOfTwo?(t.mipmap&&r.enableMipmap(),t.wrapMode===s.WRAP_MODES.CLAMP?r.enableWrapClamp():t.wrapMode===s.WRAP_MODES.REPEAT?r.enableWrapRepeat():r.enableWrapMirrorRepeat()):r.enableWrapClamp(),t.scaleMode===s.SCALE_MODES.NEAREST?r.enableNearestScaling():r.enableLinearScaling()}return r},t.prototype.destroyTexture=function(t,e){if(t=t.baseTexture||t,t.hasLoaded&&t._glTextures[this.renderer.CONTEXT_UID]&&(t._glTextures[this.renderer.CONTEXT_UID].destroy(),t.off("update",this.updateTexture,this),t.off("dispose",this.destroyTexture,this),delete t._glTextures[this.renderer.CONTEXT_UID],!e)){var r=this._managedTextures.indexOf(t);r!==-1&&(0,h.removeItems)(this._managedTextures,r,1)}},t.prototype.removeAll=function(){for(var t=0;t2&&void 0!==arguments[2]?arguments[2]:{};i(this,e);var a=o(this,t.call(this,"WebGL",r,n,s));return a.type=A.RENDERER_TYPE.WEBGL,a.handleContextLost=a.handleContextLost.bind(a),a.handleContextRestored=a.handleContextRestored.bind(a),a.view.addEventListener("webglcontextlost",a.handleContextLost,!1),a.view.addEventListener("webglcontextrestored",a.handleContextRestored,!1),a._contextOptions={alpha:a.transparent,antialias:s.antialias,premultipliedAlpha:a.transparent&&"notMultiplied"!==a.transparent,stencil:!0,preserveDrawingBuffer:s.preserveDrawingBuffer},a._backgroundColorRgba[3]=a.transparent?0:1,a.maskManager=new l.default(a),a.stencilManager=new f.default(a),a.emptyRenderer=new m.default(a),a.currentRenderer=a.emptyRenderer,a.initPlugins(),s.context&&(0,P.default)(s.context),a.gl=s.context||D.default.createContext(a.view,a._contextOptions),a.CONTEXT_UID=I++,a.state=new E.default(a.gl),a.renderingToScreen=!0,a._initContext(),a.filterManager=new p.default(a),a.drawModes=(0,O.default)(a.gl),a._activeShader=null,a._activeRenderTarget=null,a._activeTextureLocation=999,a._activeTexture=null,a.setBlendMode(0),a}return s(e,t),e.prototype._initContext=function(){var t=this.gl;t.isContextLost()&&t.getExtension("WEBGL_lose_context")&&t.getExtension("WEBGL_lose_context").restoreContext(),this.textureManager=new b.default(this),this.textureGC=new T.default(this),this.state.resetToDefault(),this.rootRenderTarget=new y.default(t,this.width,this.height,null,this.resolution,(!0)),this.rootRenderTarget.clearColor=this._backgroundColorRgba,this.bindRenderTarget(this.rootRenderTarget),this.emit("context",t),this.resize(this.width,this.height)},e.prototype.render=function(t,e,r,n,i){if(this.renderingToScreen=!e,this.emit("prerender"),this.gl&&!this.gl.isContextLost()){if(e||(this._lastObjectRendered=t),!i){var o=t.parent;t.parent=this._tempDisplayObjectParent,t.updateTransform(),t.parent=o}this.bindRenderTexture(e,n),this.currentRenderer.start(),(void 0!==r?r:this.clearBeforeRender)&&this._activeRenderTarget.clear(),t.renderWebGL(this),this.currentRenderer.flush(),this.textureGC.update(),this.emit("postrender")}},e.prototype.setObjectRenderer=function(t){this.currentRenderer!==t&&(this.currentRenderer.stop(),this.currentRenderer=t,this.currentRenderer.start())},e.prototype.flush=function(){this.setObjectRenderer(this.emptyRenderer)},e.prototype.resize=function(t,e){u.default.prototype.resize.call(this,t,e),this.rootRenderTarget.resize(t,e),this._activeRenderTarget===this.rootRenderTarget&&(this.rootRenderTarget.activate(),this._activeShader&&(this._activeShader.uniforms.projectionMatrix=this.rootRenderTarget.projectionMatrix.toArray(!0)))},e.prototype.setBlendMode=function(t){this.state.setBlendMode(t)},e.prototype.clear=function(t){this._activeRenderTarget.clear(t)},e.prototype.setTransform=function(t){this._activeRenderTarget.transform=t},e.prototype.bindRenderTexture=function(t,e){var r=void 0;if(t){var n=t.baseTexture,i=this.gl;n._glRenderTargets[this.CONTEXT_UID]?(this._activeTextureLocation=n._id,i.activeTexture(i.TEXTURE0+n._id),i.bindTexture(i.TEXTURE_2D,null)):(this.textureManager.updateTexture(n),i.bindTexture(i.TEXTURE_2D,null)),r=n._glRenderTargets[this.CONTEXT_UID],r.setFrame(t.frame)}else r=this.rootRenderTarget;return r.transform=e,this.bindRenderTarget(r),this},e.prototype.bindRenderTarget=function(t){return t!==this._activeRenderTarget&&(this._activeRenderTarget=t,t.activate(),this._activeShader&&(this._activeShader.uniforms.projectionMatrix=t.projectionMatrix.toArray(!0)),this.stencilManager.setMaskStack(t.stencilMaskStack)),this},e.prototype.bindShader=function(t){return this._activeShader!==t&&(this._activeShader=t,t.bind(),t.uniforms.projectionMatrix=this._activeRenderTarget.projectionMatrix.toArray(!0)),this},e.prototype.bindTexture=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;t=t.baseTexture||t;var r=this.gl;return this._activeTextureLocation!==e&&(this._activeTextureLocation=e,r.activeTexture(r.TEXTURE0+e)),this._activeTexture=t,t._glTextures[this.CONTEXT_UID]?(t.touched=this.textureGC.count,t._glTextures[this.CONTEXT_UID].bind()):this.textureManager.updateTexture(t),this},e.prototype.createVao=function(){return new D.default.VertexArrayObject(this.gl,this.state.attribState)},e.prototype.reset=function(){return this.setObjectRenderer(this.emptyRenderer),this._activeShader=null,this._activeRenderTarget=this.rootRenderTarget,this._activeTextureLocation=999,this._activeTexture=null,this.rootRenderTarget.activate(),this.state.resetToDefault(),this},e.prototype.handleContextLost=function(t){t.preventDefault()},e.prototype.handleContextRestored=function(){this._initContext(),this.textureManager.removeAll()},e.prototype.destroy=function(e){this.destroyPlugins(),this.view.removeEventListener("webglcontextlost",this.handleContextLost),this.view.removeEventListener("webglcontextrestored",this.handleContextRestored),this.textureManager.destroy(),t.prototype.destroy.call(this,e),this.uid=0,this.maskManager.destroy(), +this.stencilManager.destroy(),this.filterManager.destroy(),this.maskManager=null,this.filterManager=null,this.textureManager=null,this.currentRenderer=null,this.handleContextLost=null,this.handleContextRestored=null,this._contextOptions=null,this.gl.useProgram(null),this.gl.getExtension("WEBGL_lose_context")&&this.gl.getExtension("WEBGL_lose_context").loseContext(),this.gl=null},e}(u.default);r.default=L,C.pluginTarget.mixin(L)},{"../../const":43,"../../utils":116,"../SystemRenderer":73,"./TextureGarbageCollector":79,"./TextureManager":80,"./WebGLState":82,"./managers/FilterManager":87,"./managers/MaskManager":88,"./managers/StencilManager":89,"./utils/ObjectRenderer":91,"./utils/RenderTarget":93,"./utils/mapWebGLDrawModesToPixi":96,"./utils/validateContext":97,"pixi-gl-core":12}],82:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./utils/mapWebGLBlendModesToPixi"),s=n(o),a=0,u=1,h=2,l=3,c=4,f=function(){function t(e){i(this,t),this.activeState=new Uint8Array(16),this.defaultState=new Uint8Array(16),this.defaultState[0]=1,this.stackIndex=0,this.stack=[],this.gl=e,this.maxAttribs=e.getParameter(e.MAX_VERTEX_ATTRIBS),this.attribState={tempAttribState:new Array(this.maxAttribs),attribState:new Array(this.maxAttribs)},this.blendModes=(0,s.default)(e),this.nativeVaoExtension=e.getExtension("OES_vertex_array_object")||e.getExtension("MOZ_OES_vertex_array_object")||e.getExtension("WEBKIT_OES_vertex_array_object")}return t.prototype.push=function(){var t=this.stack[++this.stackIndex];t||(t=this.stack[this.stackIndex]=new Uint8Array(16));for(var e=0;e 0.5)"," {"," color = vec4(1.0, 0.0, 0.0, 1.0);"," }"," else"," {"," color = vec4(0.0, 1.0, 0.0, 1.0);"," }"," gl_FragColor = mix(sample, masky, 0.5);"," gl_FragColor *= sample.a;","}"].join("\n")}}]),t}();r.default=c},{"../../../const":43,"../../../utils":116,"./extractUniformsFromSrc":84}],84:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e,r){var n=o(t,r),i=o(e,r);return Object.assign(n,i)}function o(t){for(var e=new RegExp("^(projectionMatrix|uSampler|filterArea)$"),r={},n=void 0,i=t.replace(/\s+/g," ").split(/\s*;\s*/),o=0;o-1){var a=s.split(" "),h=a[1],l=a[2],c=1;l.indexOf("[")>-1&&(n=l.split(/\[|]/),l=n[0],c*=Number(n[1])),l.match(e)||(r[l]={value:u(h,c),name:l,type:h})}}return r}r.__esModule=!0,r.default=i;var s=t("pixi-gl-core"),a=n(s),u=a.default.shader.defaultValue},{"pixi-gl-core":12}],85:[function(t,e,r){"use strict";function n(t,e,r){var n=t.identity();return n.translate(e.x/r.width,e.y/r.height),n.scale(r.width,r.height),n}function i(t,e,r){var n=t.identity();n.translate(e.x/r.width,e.y/r.height);var i=r.width/e.width,o=r.height/e.height;return n.scale(i,o),n}function o(t,e,r,n){var i=n.worldTransform.copy(s.Matrix.TEMP_MATRIX),o=n._texture.baseTexture,a=t.identity(),u=r.height/r.width;a.translate(e.x/r.width,e.y/r.height),a.scale(1,u);var h=r.width/o.width,l=r.height/o.height;return i.tx/=o.width*h,i.ty/=o.width*h,i.invert(),a.prepend(i),a.scale(1,1/u),a.scale(h,l),a.translate(n.anchor.x,n.anchor.y),a}r.__esModule=!0,r.calculateScreenSpaceMatrix=n,r.calculateNormalizedScreenSpaceMatrix=i,r.calculateSpriteMatrix=o;var s=t("../../../math")},{"../../../math":67}],86:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../Filter"),u=n(a),h=t("../../../../math"),l=function(t){function e(r){i(this,e);var n=new h.Matrix,s=o(this,t.call(this,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n","#define GLSLIFY 1\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n"));return r.renderable=!1,s.maskSprite=r,s.maskMatrix=n,s}return s(e,t),e.prototype.apply=function(t,e,r){var n=this.maskSprite;this.uniforms.mask=n._texture,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,n),this.uniforms.alpha=n.worldAlpha,t.applyFilter(this,e,r)},e}(u.default);r.default=l},{"../../../../math":67,"../Filter":83}],87:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var u=t("./WebGLManager"),h=i(u),l=t("../utils/RenderTarget"),c=i(l),f=t("../utils/Quad"),d=i(f),p=t("../../../math"),v=t("../../../Shader"),y=i(v),g=t("../filters/filterTransforms"),m=n(g),_=t("bit-twiddle"),b=i(_),x=function t(){a(this,t),this.renderTarget=null,this.sourceFrame=new p.Rectangle,this.destinationFrame=new p.Rectangle,this.filters=[],this.target=null,this.resolution=1},T=function(t){function e(r){a(this,e);var n=o(this,t.call(this,r));return n.gl=n.renderer.gl,n.quad=new d.default(n.gl,r.state.attribState),n.shaderCache={},n.pool={},n.filterData=null,n}return s(e,t),e.prototype.pushFilter=function(t,e){var r=this.renderer,n=this.filterData;if(!n){n=this.renderer._activeRenderTarget.filterStack;var i=new x;i.sourceFrame=i.destinationFrame=this.renderer._activeRenderTarget.size,i.renderTarget=r._activeRenderTarget,this.renderer._activeRenderTarget.filterData=n={index:0,stack:[i]},this.filterData=n}var o=n.stack[++n.index];o||(o=n.stack[n.index]=new x);var s=e[0].resolution,a=0|e[0].padding,u=t.filterArea||t.getBounds(!0),h=o.sourceFrame,l=o.destinationFrame;h.x=(u.x*s|0)/s,h.y=(u.y*s|0)/s,h.width=(u.width*s|0)/s,h.height=(u.height*s|0)/s,n.stack[0].renderTarget.transform||h.fit(n.stack[0].destinationFrame),h.pad(a),l.width=h.width,l.height=h.height;var c=this.getPotRenderTarget(r.gl,h.width,h.height,s);o.target=t,o.filters=e,o.resolution=s,o.renderTarget=c,c.setFrame(l,h),r.bindRenderTarget(c),r.clear()},e.prototype.popFilter=function(){var t=this.filterData,e=t.stack[t.index-1],r=t.stack[t.index];this.quad.map(r.renderTarget.size,r.sourceFrame).upload();var n=r.filters;if(1===n.length)n[0].apply(this,r.renderTarget,e.renderTarget,!1),this.freePotRenderTarget(r.renderTarget);else{var i=r.renderTarget,o=this.getPotRenderTarget(this.renderer.gl,r.sourceFrame.width,r.sourceFrame.height,r.resolution);o.setFrame(r.destinationFrame,r.sourceFrame);var s=0;for(s=0;s0&&(e+="\nelse "),r1&&void 0!==arguments[1]?arguments[1]:[];return e[i.BLEND_MODES.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.ADD]=[t.ONE,t.DST_ALPHA],e[i.BLEND_MODES.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SCREEN]=[t.ONE,t.ONE_MINUS_SRC_COLOR],e[i.BLEND_MODES.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":43}],96:[function(t,e,r){"use strict";function n(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e[i.DRAW_MODES.POINTS]=t.POINTS,e[i.DRAW_MODES.LINES]=t.LINES,e[i.DRAW_MODES.LINE_LOOP]=t.LINE_LOOP,e[i.DRAW_MODES.LINE_STRIP]=t.LINE_STRIP,e[i.DRAW_MODES.TRIANGLES]=t.TRIANGLES,e[i.DRAW_MODES.TRIANGLE_STRIP]=t.TRIANGLE_STRIP,e[i.DRAW_MODES.TRIANGLE_FAN]=t.TRIANGLE_FAN,e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":43}],97:[function(t,e,r){"use strict";function n(t){var e=t.getContextAttributes();e.stencil||console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly")}r.__esModule=!0,r.default=n},{}],98:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rn&&v.xi&&v.y>16)+(65280&t)+((255&t)<<16)}},{key:"texture",get:function(){return this._texture},set:function(t){this._texture!==t&&(this._texture=t,this.cachedTint=16777215,this._textureID=-1,t&&(t.baseTexture.hasLoaded?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}]),e}(p.default);r.default=y},{"../const":43,"../display/Container":45,"../math":67,"../textures/Texture":109,"../utils":116}],99:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../renderers/canvas/CanvasRenderer"),s=n(o),a=t("../../const"),u=t("../../math"),h=t("./CanvasTinter"),l=n(h),c=new u.Matrix,f=function(){function t(e){i(this,t),this.renderer=e}return t.prototype.render=function(t){var e=t._texture,r=this.renderer,n=e._frame.width,i=e._frame.height,o=t.transform.worldTransform,s=0,h=0;if(!(e.orig.width<=0||e.orig.height<=0)&&e.baseTexture.source&&(r.setBlendMode(t.blendMode),e.valid)){r.context.globalAlpha=t.worldAlpha;var f=e.baseTexture.scaleMode===a.SCALE_MODES.LINEAR;r.smoothProperty&&r.context[r.smoothProperty]!==f&&(r.context[r.smoothProperty]=f),e.trim?(s=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,h=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(s=(.5-t.anchor.x)*e.orig.width,h=(.5-t.anchor.y)*e.orig.height),e.rotate&&(o.copy(c),o=c,u.GroupD8.matrixAppendRotationInv(o,e.rotate,s,h),s=0,h=0),s-=n/2,h-=i/2,r.roundPixels?(r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution|0,o.ty*r.resolution|0),s=0|s,h=0|h):r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution,o.ty*r.resolution);var d=e.baseTexture.resolution;16777215!==t.tint?(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=l.default.getTintedTexture(t,t.tint)),r.context.drawImage(t.tintedTexture,0,0,n*d,i*d,s*r.resolution,h*r.resolution,n*r.resolution,i*r.resolution)):r.context.drawImage(e.baseTexture.source,e._frame.x*d,e._frame.y*d,n*d,i*d,s*r.resolution,h*r.resolution,n*r.resolution,i*r.resolution)}},t.prototype.destroy=function(){this.renderer=null},t}();r.default=f,s.default.registerPlugin("sprite",f)},{"../../const":43,"../../math":67,"../../renderers/canvas/CanvasRenderer":74,"./CanvasTinter":100}],100:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("../../utils"),o=t("../../renderers/canvas/utils/canUseNewCanvasBlendModes"),s=n(o),a={getTintedTexture:function(t,e){var r=t.texture;e=a.roundColor(e);var n="#"+("00000"+(0|e).toString(16)).substr(-6);if(r.tintCache=r.tintCache||{},r.tintCache[n])return r.tintCache[n];var i=a.canvas||document.createElement("canvas");if(a.tintMethod(r,e,i),a.convertTintToImage){var o=new Image;o.src=i.toDataURL(),r.tintCache[n]=o}else r.tintCache[n]=i,a.canvas=null;return i},tintWithMultiply:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=i.width,r.height=i.height,n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="multiply",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},tintWithOverlay:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=i.width,r.height=i.height,n.globalCompositeOperation="copy",n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},tintWithPerPixel:function(t,e,r){var n=r.getContext("2d"),o=t._frame.clone(),s=t.baseTexture.resolution;o.x*=s,o.y*=s,o.width*=s,o.height*=s,r.width=o.width,r.height=o.height,n.globalCompositeOperation="copy",n.drawImage(t.baseTexture.source,o.x,o.y,o.width,o.height,0,0,o.width,o.height);for(var a=(0,i.hex2rgb)(e),u=a[0],h=a[1],l=a[2],c=n.getImageData(0,0,o.width,o.height),f=c.data,d=0;d=this.size&&this.flush(),t.texture._uvs&&(this.sprites[this.currentIndex++]=t)},e.prototype.flush=function(){if(0!==this.currentIndex){var t=this.renderer.gl,e=w.default.nextPow2(this.currentIndex),r=w.default.log2(e),n=this.buffers[r],i=this.sprites,o=this.groups,s=n.float32View,a=n.uint32View,u=0,h=void 0,l=void 0,c=1,f=0,d=o[0],v=void 0,y=void 0,g=void 0,m=void 0,_=i[0].blendMode,b=void 0;d.textureCount=0,d.start=0,d.blend=_,E++;var T=void 0;for(T=0;T0&&(e+="\nelse "),r0?(this.context.shadowColor=e.dropShadowColor,this.context.shadowBlur=e.dropShadowBlur):this.context.fillStyle=e.dropShadowColor;for(var v=Math.cos(e.dropShadowAngle)*e.dropShadowDistance,y=Math.sin(e.dropShadowAngle)*e.dropShadowDistance,g=0;g3&&void 0!==arguments[3]&&arguments[3],i=this._style,o=i.letterSpacing;if(0===o)return void(n?this.context.strokeText(t,e,r):this.context.fillText(t,e,r));for(var s=String.prototype.split.call(t,""),a=e,u=0,h="";us;--c){for(var v=0;vn)for(var h=s[a].split(""),l=0;lo?(e+="\n"+h[l],o=n-c):(0===l&&(e+=" "),e+=h[l],o-=c)}else{var f=u+this.context.measureText(" ").width;0===a||f>o?(a>0&&(e+="\n"),e+=s[a],o=n-u):(o-=f,e+=" "+s[a])}}i0&&void 0!==arguments[0]?arguments[0]:100,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,s=arguments[2],a=arguments[3];i(this,e);var u=o(this,t.call(this,null,s));return u.resolution=a||h.RESOLUTION,u.width=r,u.height=n,u.realWidth=u.width*u.resolution,u.realHeight=u.height*u.resolution,u.scaleMode=s||h.SCALE_MODES.DEFAULT,u.hasLoaded=!0,u._glRenderTargets={},u._canvasRenderTarget=null,u.valid=!1,u}return s(e,t),e.prototype.resize=function(t,e){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.realWidth=this.width*this.resolution,this.realHeight=this.height*this.resolution,this.valid&&this.emit("update",this))},e.prototype.destroy=function(){t.prototype.destroy.call(this,!0),this.renderer=null},e}(u.default);r.default=l},{"../const":43,"./BaseTexture":107}],107:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u=t("../utils"),h=t("../const"),l=t("eventemitter3"),c=n(l),f=t("../utils/determineCrossOrigin"),d=n(f),p=t("bit-twiddle"),v=n(p),y=function(t){function e(r,n,s){i(this,e);var a=o(this,t.call(this));return a.uid=(0,u.uid)(),a.touched=0,a.resolution=s||h.RESOLUTION,a.width=100,a.height=100,a.realWidth=100,a.realHeight=100,a.scaleMode=n||h.SCALE_MODES.DEFAULT,a.hasLoaded=!1,a.isLoading=!1,a.source=null,a.origSource=null,a.imageType=null,a.sourceScale=1,a.premultipliedAlpha=!0,a.imageUrl=null,a.isPowerOfTwo=!1,a.mipmap=h.MIPMAP_TEXTURES,a.wrapMode=h.WRAP_MODES.DEFAULT,a._glTextures={},a._enabled=0,a._id=0,r&&a.loadSource(r),a}return s(e,t),e.prototype.update=function(){"svg"!==this.imageType&&(this.realWidth=this.source.naturalWidth||this.source.videoWidth||this.source.width,this.realHeight=this.source.naturalHeight||this.source.videoHeight||this.source.height,this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=v.default.isPow2(this.realWidth)&&v.default.isPow2(this.realHeight)),this.emit("update",this)},e.prototype.loadSource=function(t){var e=this,r=this.isLoading;this.hasLoaded=!1,this.isLoading=!1,r&&this.source&&(this.source.onload=null,this.source.onerror=null);var n=!this.source;if(this.source=t,(t.src&&t.complete||t.getContext)&&t.width&&t.height)this._updateImageType(),"svg"===this.imageType?this._loadSvgSource():this._sourceLoaded(), +n&&this.emit("loaded",this);else if(!t.getContext){var i=function(){e.isLoading=!0;var n=e;if(t.onload=function(){if(n._updateImageType(),t.onload=null,t.onerror=null,n.isLoading)return n.isLoading=!1,n._sourceLoaded(),"svg"===n.imageType?void n._loadSvgSource():void n.emit("loaded",n)},t.onerror=function(){t.onload=null,t.onerror=null,n.isLoading&&(n.isLoading=!1,n.emit("error",n))},t.complete&&t.src){if(t.onload=null,t.onerror=null,"svg"===n.imageType)return n._loadSvgSource(),{v:void 0};e.isLoading=!1,t.width&&t.height?(e._sourceLoaded(),r&&e.emit("loaded",e)):r&&e.emit("error",e)}}();if("object"===("undefined"==typeof i?"undefined":a(i)))return i.v}},e.prototype._updateImageType=function(){if(this.imageUrl){var t=(0,u.decomposeDataUri)(this.imageUrl),e=void 0;if(t&&"image"===t.mediaType){var r=t.subType.split("+")[0];if(e=(0,u.getUrlFileExtension)("."+r),!e)throw new Error("Invalid image type in data URI.")}else if(e=(0,u.getUrlFileExtension)(this.imageUrl),!e)throw new Error("Invalid image type in URL.");this.imageType=e}},e.prototype._loadSvgSource=function(){if("svg"===this.imageType){var t=(0,u.decomposeDataUri)(this.imageUrl);t?this._loadSvgSourceUsingDataUri(t):this._loadSvgSourceUsingXhr()}},e.prototype._loadSvgSourceUsingDataUri=function(t){var e=void 0;if("base64"===t.encoding){if(!atob)throw new Error("Your browser doesn't support base64 conversions.");e=atob(t.data)}else e=t.data;this._loadSvgSourceUsingString(e)},e.prototype._loadSvgSourceUsingXhr=function(){var t=this,e=new XMLHttpRequest;e.onload=function(){if(e.readyState!==e.DONE||200!==e.status)throw new Error("Failed to load SVG using XHR.");t._loadSvgSourceUsingString(e.response)},e.onerror=function(){return t.emit("error",t)},e.open("GET",this.imageUrl,!0),e.send()},e.prototype._loadSvgSourceUsingString=function(t){var e=(0,u.getSvgSize)(t),r=e.width,n=e.height;if(!r||!n)throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them.");this.realWidth=Math.round(r*this.sourceScale),this.realHeight=Math.round(n*this.sourceScale),this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=v.default.isPow2(this.realWidth)&&v.default.isPow2(this.realHeight);var i=document.createElement("canvas");i.width=this.realWidth,i.height=this.realHeight,i._pixiId="canvas_"+(0,u.uid)(),i.getContext("2d").drawImage(this.source,0,0,r,n,0,0,this.realWidth,this.realHeight),this.origSource=this.source,this.source=i,u.BaseTextureCache[i._pixiId]=this,this.isLoading=!1,this._sourceLoaded(),this.emit("loaded",this)},e.prototype._sourceLoaded=function(){this.hasLoaded=!0,this.update()},e.prototype.destroy=function(){this.imageUrl&&(delete u.BaseTextureCache[this.imageUrl],delete u.TextureCache[this.imageUrl],this.imageUrl=null,navigator.isCocoonJS||(this.source.src="")),this.source&&this.source._pixiId&&delete u.BaseTextureCache[this.source._pixiId],this.source=null,this.dispose()},e.prototype.dispose=function(){this.emit("dispose",this)},e.prototype.updateSourceImage=function(t){this.source.src=t,this.loadSource(this.source)},e.fromImage=function(t,r,n,i){var o=u.BaseTextureCache[t];if(!o){var s=new Image;void 0===r&&0!==t.indexOf("data:")&&(s.crossOrigin=(0,d.default)(t)),o=new e(s,n),o.imageUrl=t,i&&(o.sourceScale=i),o.resolution=(0,u.getResolutionOfUrl)(t),s.src=t,u.BaseTextureCache[t]=o}return o},e.fromCanvas=function(t,r){t._pixiId||(t._pixiId="canvas_"+(0,u.uid)());var n=u.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),u.BaseTextureCache[t._pixiId]=n),n},e}(c.default);r.default=y},{"../const":43,"../utils":116,"../utils/determineCrossOrigin":115,"bit-twiddle":1,eventemitter3:3}],108:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("./BaseRenderTexture"),u=n(a),h=t("./Texture"),l=n(h),c=function(t){function e(r,n){i(this,e);var s=null;if(!(r instanceof u.default)){var a=arguments[1],h=arguments[2],l=arguments[3]||0,c=arguments[4]||1;console.warn("Please use RenderTexture.create("+a+", "+h+") instead of the ctor directly."),s=arguments[0],n=null,r=new u.default(a,h,l,c)}var f=o(this,t.call(this,r,n));return f.legacyRenderer=s,f.valid=!0,f._updateUvs(),f}return s(e,t),e.prototype.resize=function(t,e,r){this.valid=t>0&&e>0,this._frame.width=this.orig.width=t,this._frame.height=this.orig.height=e,r||this.baseTexture.resize(t,e),this._updateUvs()},e.create=function(t,r,n,i){return new e(new u.default(t,r,n,i))},e}(l.default);r.default=c},{"./BaseRenderTexture":106,"./Texture":109}],109:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rthis.baseTexture.width||t.y+t.height>this.baseTexture.height)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);this.valid=t&&t.width&&t.height&&this.baseTexture.hasLoaded,this.trim||this.rotate||(this.orig=t),this.valid&&this._updateUvs()}},{key:"rotate",get:function(){return this._rotate},set:function(t){this._rotate=t,this.valid&&this._updateUvs()}},{key:"width",get:function(){return this.orig?this.orig.width:0}},{key:"height",get:function(){return this.orig?this.orig.height:0}}]),e}(v.default);r.default=m,m.EMPTY=new m(new h.default),m.EMPTY.destroy=function(){},m.EMPTY.on=function(){},m.EMPTY.once=function(){},m.EMPTY.emit=function(){}},{"../math":67,"../utils":116,"./BaseTexture":107,"./TextureUvs":110,"./VideoBaseTexture":111,eventemitter3:3}],110:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../math/GroupD8"),s=n(o),a=function(){function t(){i(this,t),this.x0=0,this.y0=0,this.x1=1,this.y1=0,this.x2=1,this.y2=1,this.x3=0,this.y3=1,this.uvsUint32=new Uint32Array(4)}return t.prototype.set=function(t,e,r){var n=e.width,i=e.height;if(r){var o=t.width/2/n,a=t.height/2/i,u=t.x/n+o,h=t.y/i+a;r=s.default.add(r,s.default.NW),this.x0=u+o*s.default.uX(r),this.y0=h+a*s.default.uY(r),r=s.default.add(r,2),this.x1=u+o*s.default.uX(r),this.y1=h+a*s.default.uY(r),r=s.default.add(r,2),this.x2=u+o*s.default.uX(r),this.y2=h+a*s.default.uY(r),r=s.default.add(r,2),this.x3=u+o*s.default.uX(r),this.y3=h+a*s.default.uY(r)}else this.x0=t.x/n,this.y0=t.y/i,this.x1=(t.x+t.width)/n,this.y1=t.y/i,this.x2=(t.x+t.width)/n,this.y2=(t.y+t.height)/i,this.x3=t.x/n,this.y3=(t.y+t.height)/i;this.uvsUint32[0]=(65535*this.y0&65535)<<16|65535*this.x0&65535,this.uvsUint32[1]=(65535*this.y1&65535)<<16|65535*this.x1&65535,this.uvsUint32[2]=(65535*this.y2&65535)<<16|65535*this.x2&65535,this.uvsUint32[3]=(65535*this.y3&65535)<<16|65535*this.x3&65535},t}();r.default=a},{"../math/GroupD8":63}],111:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function u(t,e){e||(e="video/"+t.substr(t.lastIndexOf(".")+1));var r=document.createElement("source");return r.src=t,r.type=e,r}r.__esModule=!0;var h=function(){function t(t,e){for(var r=0;r0&&t.paused===!1&&t.ended===!1&&t.readyState>2},e.prototype._isSourceReady=function(){return 3===this.source.readyState||4===this.source.readyState},e.prototype._onPlayStart=function(){this.hasLoaded||this._onCanPlay(),!this._isAutoUpdating&&this.autoUpdate&&(p.shared.add(this.update,this),this._isAutoUpdating=!0)},e.prototype._onPlayStop=function(){this._isAutoUpdating&&(p.shared.remove(this.update,this),this._isAutoUpdating=!1)},e.prototype._onCanPlay=function(){this.hasLoaded=!0,this.source&&(this.source.removeEventListener("canplay",this._onCanPlay),this.source.removeEventListener("canplaythrough",this._onCanPlay),this.width=this.source.videoWidth,this.height=this.source.videoHeight,this.__loaded||(this.__loaded=!0,this.emit("loaded",this)),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.source.play())},e.prototype.destroy=function(){this._isAutoUpdating&&p.shared.remove(this.update,this),this.source&&this.source._pixiId&&(delete f.BaseTextureCache[this.source._pixiId],delete this.source._pixiId),t.prototype.destroy.call(this)},e.fromVideo=function(t,r){t._pixiId||(t._pixiId="video_"+(0,f.uid)());var n=f.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),f.BaseTextureCache[t._pixiId]=n),n},e.fromUrl=function(t,r){var n=document.createElement("video");if(n.setAttribute("webkit-playsinline",""),n.setAttribute("playsinline",""),Array.isArray(t))for(var i=0;i0&&void 0!==arguments[0]?arguments[0]:performance.now(),e=void 0;t>this.lastTime?(e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),this.deltaTime=e*s.TARGET_FPMS*this.speed,this._emitter.emit(h,this.deltaTime)):this.deltaTime=this.elapsedMS=0,this.lastTime=t},o(t,[{key:"FPS",get:function(){return 1e3/this.elapsedMS}},{key:"minFPS",get:function(){return 1e3/this._maxElapsedMS},set:function(t){var e=Math.min(Math.max(0,t)/1e3,s.TARGET_FPMS);this._maxElapsedMS=1/e}}]),t}();r.default=l},{"../const":43,eventemitter3:3}],113:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.Ticker=r.shared=void 0;var i=t("./Ticker"),o=n(i),s=new o.default;s.autoStart=!0,r.shared=s,r.Ticker=o.default},{"./Ticker":112}],114:[function(t,e,r){"use strict";function n(t){for(var e=6*t,r=new Uint16Array(e),n=0,i=0;n1&&void 0!==arguments[1]?arguments[1]:window.location;if(0===t.indexOf("data:"))return"";e=e||window.location,a||(a=document.createElement("a")),a.href=t,t=s.default.parse(a.href);var r=!t.port&&""===e.port||t.port===e.port;return t.hostname===e.hostname&&r&&t.protocol===e.protocol?"":"anonymous"}r.__esModule=!0,r.default=i;var o=t("url"),s=n(o),a=void 0},{url:28}],116:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(){return++T}function o(t,e){return e=e||[],e[0]=(t>>16&255)/255,e[1]=(t>>8&255)/255,e[2]=(255&t)/255,e}function s(t){return t=t.toString(16),t="000000".substr(0,6-t.length)+t,"#"+t}function a(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]}function u(t){var e=g.RETINA_PREFIX.exec(t);return e?parseFloat(e[1]):1}function h(t){var e=g.DATA_URI.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,encoding:e[3]?e[3].toLowerCase():void 0,data:e[4]}}function l(t){var e=g.URL_FILE_EXTENSION.exec(t);if(e)return e[1].toLowerCase()}function c(t){var e=g.SVG_SIZE.exec(t),r={};return e&&(r[e[1]]=Math.round(parseFloat(e[2])),r[e[3]]=Math.round(parseFloat(e[4]))),r}function f(){w=!0}function d(t){if(!w){if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var e=["\n %c %c %c Pixi.js "+g.VERSION+" - ✰ "+t+" ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n","background: #ff66a5; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff66a5; background: #030307; padding:5px 0;","background: #ff66a5; padding:5px 0;","background: #ffc3dc; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;"];window.console.log.apply(console,e)}else window.console&&window.console.log("Pixi.js "+g.VERSION+" - "+t+" - http://www.pixijs.com/");w=!0}}function p(){var t={stencil:!0,failIfMajorPerformanceCaveat:!0};try{if(!window.WebGLRenderingContext)return!1;var e=document.createElement("canvas"),r=e.getContext("webgl",t)||e.getContext("experimental-webgl",t),n=!(!r||!r.getContextAttributes().stencil);if(r){var i=r.getExtension("WEBGL_lose_context");i&&i.loseContext()}return r=null,n}catch(t){return!1}}function v(t){return 0===t?0:t<0?-1:1}function y(t,e,r){var n=t.length;if(!(e>=n||0===r)){r=e+r>n?n-e:r;for(var i=n-r,o=e;o1?this._fontStyle="italic":t.indexOf("oblique")>-1?this._fontStyle="oblique":this._fontStyle="normal",t.indexOf("small-caps")>-1?this._fontVariant="small-caps":this._fontVariant="normal";var e=t.split(" "),r=-1;this._fontSize=26;for(var n=0;n-1&&r1&&void 0!==arguments[1]?arguments[1]:{};o(this,e);var i=s(this,t.call(this));return i.textWidth=0,i.textHeight=0,i._glyphs=[],i._font={tint:void 0!==n.tint?n.tint:16777215,align:n.align||"left",name:null,size:0},i.font=n.font,i._text=r,i.maxWidth=0,i.maxLineHeight=0,i._anchor=new f.default(function(){i.dirty=!0},i,0,0),i.dirty=!1,i.updateText(),i}return a(e,t),e.prototype.updateText=function(){for(var t=e.fonts[this._font.name],r=this._font.size/t.size,n=new l.Point,i=[],o=[],s=null,a=0,u=0,h=0,c=-1,f=0,d=0,p=0;p0&&n.x*r>this.maxWidth)l.utils.removeItems(i,c,p-c),p=c,c=-1,o.push(f),u=Math.max(u,f),h++,n.x=0,n.y+=t.lineHeight,s=null;else{var y=t.chars[v];y&&(s&&y.kerning[s]&&(n.x+=y.kerning[s]),i.push({texture:y.texture,line:h,charCode:v,position:new l.Point(n.x+y.xOffset,n.y+y.yOffset)}),a=n.x+(y.texture.width+y.xOffset),n.x+=y.xAdvance,d=Math.max(d,y.yOffset+y.texture.height),s=v)}}o.push(a),u=Math.max(u,a);for(var g=[],m=0;m<=h;m++){var _=0;"right"===this._font.align?_=u-o[m]:"center"===this._font.align&&(_=(u-o[m])/2),g.push(_)}for(var b=i.length,x=this.tint,T=0;T=0?t:16777215,this.dirty=!0}},{key:"align",get:function(){return this._font.align},set:function(t){this._font.align=t||"left",this.dirty=!0}},{key:"anchor",get:function(){return this._anchor},set:function(t){"number"==typeof t?this._anchor.set(t):this._anchor.copy(t)}},{key:"font",get:function(){return this._font},set:function(t){t&&("string"==typeof t?(t=t.split(" "),this._font.name=1===t.length?t[0]:t.slice(1).join(" "),this._font.size=t.length>=2?parseInt(t[0],10):e.fonts[this._font.name].size):(this._font.name=t.name,this._font.size="number"==typeof t.size?t.size:parseInt(t.size,10)),this.dirty=!0)}},{key:"text",get:function(){return this._text},set:function(t){t=t.toString()||" ",this._text!==t&&(this._text=t,this.dirty=!0)}}]),e}(l.Container);r.default=d,d.fonts={}},{"../core":62,"../core/math/ObservablePoint":65}],124:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r=this._durations[this.currentFrame];)n-=this._durations[this.currentFrame]*i,this._currentTime+=i;this._currentTime+=n/this._durations[this.currentFrame]}else this._currentTime+=e;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):r!==this.currentFrame&&(this._texture=this._textures[this.currentFrame],this._textureID=-1,this.onFrameChange&&this.onFrameChange(this.currentFrame))},e.prototype.destroy=function(){this.stop(),t.prototype.destroy.call(this)},e.fromFrames=function(t){for(var r=[],n=0;n1&&void 0!==arguments[1]?arguments[1]:100,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:100;o(this,e);var a=s(this,t.call(this,r));return a.tileTransform=new l.TransformStatic,a._width=n,a._height=i,a._canvasPattern=null,a.uvTransform=r.transform||new p.default(r),a}return a(e,t),e.prototype._onTextureUpdate=function(){this.uvTransform&&(this.uvTransform.texture=this._texture)},e.prototype._renderWebGL=function(t){var e=this._texture;e&&e.valid&&(this.tileTransform.updateLocalTransform(),this.uvTransform.update(),t.setObjectRenderer(t.plugins.tilingSprite),t.plugins.tilingSprite.render(this))},e.prototype._renderCanvas=function(t){var e=this._texture;if(e.baseTexture.hasLoaded){var r=t.context,n=this.worldTransform,i=t.resolution,o=e.baseTexture,s=e.baseTexture.resolution,a=this.tilePosition.x/this.tileScale.x%e._frame.width,u=this.tilePosition.y/this.tileScale.y%e._frame.height;if(!this._canvasPattern){var h=new l.CanvasRenderTarget(e._frame.width,e._frame.height,s);16777215!==this.tint?(this.cachedTint!==this.tint&&(this.cachedTint=this.tint,this.tintedTexture=f.default.getTintedTexture(this,this.tint)),h.context.drawImage(this.tintedTexture,0,0)):h.context.drawImage(o.source,-e._frame.x,-e._frame.y),this._canvasPattern=h.context.createPattern(h.canvas,"repeat")}r.globalAlpha=this.worldAlpha,r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),r.scale(this.tileScale.x/s,this.tileScale.y/s),r.translate(a+this.anchor.x*-this._width,u+this.anchor.y*-this._height);var c=t.blendModes[this.blendMode];c!==t.context.globalCompositeOperation&&(r.globalCompositeOperation=c),r.fillStyle=this._canvasPattern,r.fillRect(-a,-u,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s)}},e.prototype._calculateBounds=function(){var t=this._width*-this._anchor._x,e=this._height*-this._anchor._y,r=this._width*(1-this._anchor._x),n=this._height*(1-this._anchor._y);this._bounds.addFrame(this.transform,t,e,r,n)},e.prototype.getLocalBounds=function(e){return 0===this.children.length?(this._bounds.minX=this._width*-this._anchor._x,this._bounds.minY=this._height*-this._anchor._y,this._bounds.maxX=this._width*(1-this._anchor._x),this._bounds.maxY=this._height*(1-this._anchor._x),e||(this._localBoundsRect||(this._localBoundsRect=new l.Rectangle),e=this._localBoundsRect),this._bounds.getRectangle(e)):t.prototype.getLocalBounds.call(this,e)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,v);var e=this._width,r=this._height,n=-e*this.anchor._x;if(v.x>n&&v.xi&&v.y0&&void 0!==arguments[0]?arguments[0]:new o.Point,e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.parent?this.parent.toGlobal(this.position,t,e):(t.x=this.position.x,t.y=this.position.y),t}},{"../core":62}],130:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./TextureTransform");Object.defineProperty(r,"TextureTransform",{enumerable:!0,get:function(){return n(i).default}});var o=t("./MovieClip");Object.defineProperty(r,"MovieClip",{enumerable:!0,get:function(){return n(o).default}});var s=t("./TilingSprite");Object.defineProperty(r,"TilingSprite",{enumerable:!0,get:function(){return n(s).default}});var a=t("./webgl/TilingSpriteRenderer");Object.defineProperty(r,"TilingSpriteRenderer",{enumerable:!0,get:function(){return n(a).default}});var u=t("./BitmapText");Object.defineProperty(r,"BitmapText",{enumerable:!0,get:function(){return n(u).default}});var h=t("./cacheAsBitmap");Object.defineProperty(r,"cacheAsBitmap",{enumerable:!0,get:function(){return n(h).default}});var l=t("./getChildByName");Object.defineProperty(r,"getChildByName",{enumerable:!0,get:function(){return n(l).default}});var c=t("./getGlobalPosition");Object.defineProperty(r,"getGlobalPosition",{enumerable:!0,get:function(){return n(c).default}})},{"./BitmapText":123,"./MovieClip":124,"./TextureTransform":125,"./TilingSprite":126,"./cacheAsBitmap":127,"./getChildByName":128,"./getGlobalPosition":129,"./webgl/TilingSpriteRenderer":131}],131:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0,r.TilingSpriteRenderer=void 0;var a=t("../../core"),u=n(a),h=t("../../core/const"),l=new u.Matrix,c=new Float32Array(4),f=r.TilingSpriteRenderer=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.shader=null,n.simpleShader=null,n.quad=null,n}return s(e,t),e.prototype.onContextChange=function(){var t=this.renderer.gl;this.shader=new u.Shader(t,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n gl_FragColor = sample * color ;\n}\n"),this.simpleShader=new u.Shader(t,"#define GLSLIFY 1\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","#define GLSLIFY 1\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n gl_FragColor = sample * color;\n}\n"),this.quad=new u.Quad(t),this.quad.initVao(this.shader)},e.prototype.render=function(t){var e=this.quad,r=e.vertices;r[0]=r[6]=t._width*-t.anchor.x,r[1]=r[3]=t._height*-t.anchor.y,r[2]=r[4]=t._width*(1-t.anchor.x),r[5]=r[7]=t._height*(1-t.anchor.y),r=e.uvs,r[0]=r[6]=-t.anchor.x,r[1]=r[3]=-t.anchor.y,r[2]=r[4]=1-t.anchor.x,r[5]=r[7]=1-t.anchor.y,e.upload();var n=this.renderer,i=t._texture,o=i.baseTexture,s=t.tileTransform.localTransform,a=t.uvTransform,f=o.isPowerOfTwo&&i.frame.width===o.width&&i.frame.height===o.height;f&&(o._glTextures[n.CONTEXT_UID]?f=o.wrapMode!==h.WRAP_MODES.CLAMP:o.wrapMode===h.WRAP_MODES.CLAMP&&(o.wrapMode=h.WRAP_MODES.REPEAT));var d=f?this.simpleShader:this.shader;n.bindShader(d);var p=i.width,v=i.height,y=t._width,g=t._height;l.set(s.a*p/y,s.b*p/g,s.c*v/y,s.d*v/g,s.tx/y,s.ty/g),l.invert(),f?l.append(a.mapCoord):(d.uniforms.uMapCoord=a.mapCoord.toArray(!0),d.uniforms.uClampFrame=a.uClampFrame,d.uniforms.uClampOffset=a.uClampOffset),d.uniforms.uTransform=l.toArray(!0);var m=c;u.utils.hex2rgb(t.tint,m),m[3]=t.worldAlpha,d.uniforms.uColor=m,d.uniforms.translationMatrix=t.transform.worldTransform.toArray(!0),n.bindTexture(i),n.setBlendMode(t.blendMode),e.draw()},e}(u.ObjectRenderer);u.WebGLRenderer.registerPlugin("tilingSprite",f)},{"../../core":62,"../../core/const":43}],132:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var u=function(){function t(t,e){for(var r=0;r=r&&(u=t-h-1),l=l.replace("%value%",e[u]),s+=l,s+="\n"}return n=n.replace("%blur%",s),n=n.replace("%size%",t)}r.__esModule=!0,r.default=n;var i={5:[.153388,.221461,.250301],7:[.071303,.131514,.189879,.214607],9:[.028532,.067234,.124009,.179044,.20236],11:[.0093,.028002,.065984,.121703,.175713,.198596],13:[.002406,.009255,.027867,.065666,.121117,.174868,.197641],15:[489e-6,.002403,.009246,.02784,.065602,.120999,.174697,.197448]},o=["varying vec2 vBlurTexCoords[%size%];","uniform sampler2D uSampler;","void main(void)","{"," gl_FragColor = vec4(0.0);"," %blur%","}"].join("\n")},{}],136:[function(t,e,r){"use strict";function n(t,e){var r=Math.ceil(t/2),n=i,o="",s=void 0;s=e?"vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);":"vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);";for(var a=0;ae;)r-=2;return r}r.__esModule=!0,r.default=n},{}],138:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]&&arguments[1],r=t;e&&(this._multiply(r,this.uniforms.m,t),r=this._colorMatrix(r)),this.uniforms.m=r},e.prototype._multiply=function(t,e,r){return t[0]=e[0]*r[0]+e[1]*r[5]+e[2]*r[10]+e[3]*r[15],t[1]=e[0]*r[1]+e[1]*r[6]+e[2]*r[11]+e[3]*r[16],t[2]=e[0]*r[2]+e[1]*r[7]+e[2]*r[12]+e[3]*r[17],t[3]=e[0]*r[3]+e[1]*r[8]+e[2]*r[13]+e[3]*r[18],t[4]=e[0]*r[4]+e[1]*r[9]+e[2]*r[14]+e[3]*r[19],t[5]=e[5]*r[0]+e[6]*r[5]+e[7]*r[10]+e[8]*r[15],t[6]=e[5]*r[1]+e[6]*r[6]+e[7]*r[11]+e[8]*r[16],t[7]=e[5]*r[2]+e[6]*r[7]+e[7]*r[12]+e[8]*r[17],t[8]=e[5]*r[3]+e[6]*r[8]+e[7]*r[13]+e[8]*r[18],t[9]=e[5]*r[4]+e[6]*r[9]+e[7]*r[14]+e[8]*r[19],t[10]=e[10]*r[0]+e[11]*r[5]+e[12]*r[10]+e[13]*r[15],t[11]=e[10]*r[1]+e[11]*r[6]+e[12]*r[11]+e[13]*r[16],t[12]=e[10]*r[2]+e[11]*r[7]+e[12]*r[12]+e[13]*r[17],t[13]=e[10]*r[3]+e[11]*r[8]+e[12]*r[13]+e[13]*r[18],t[14]=e[10]*r[4]+e[11]*r[9]+e[12]*r[14]+e[13]*r[19],t[15]=e[15]*r[0]+e[16]*r[5]+e[17]*r[10]+e[18]*r[15],t[16]=e[15]*r[1]+e[16]*r[6]+e[17]*r[11]+e[18]*r[16],t[17]=e[15]*r[2]+e[16]*r[7]+e[17]*r[12]+e[18]*r[17],t[18]=e[15]*r[3]+e[16]*r[8]+e[17]*r[13]+e[18]*r[18],t[19]=e[15]*r[4]+e[16]*r[9]+e[17]*r[14]+e[18]*r[19],t},e.prototype._colorMatrix=function(t){var e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e},e.prototype.brightness=function(t,e){var r=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.greyscale=function(t,e){var r=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.blackAndWhite=function(t){var e=[.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.hue=function(t,e){t=(t||0)/180*Math.PI;var r=Math.cos(t),n=Math.sin(t),i=Math.sqrt,o=1/3,s=i(o),a=r+(1-r)*o,u=o*(1-r)-s*n,h=o*(1-r)+s*n,l=o*(1-r)+s*n,c=r+o*(1-r),f=o*(1-r)-s*n,d=o*(1-r)-s*n,p=o*(1-r)+s*n,v=r+o*(1-r),y=[a,u,h,0,0,l,c,f,0,0,d,p,v,0,0,0,0,0,1,0];this._loadMatrix(y,e)},e.prototype.contrast=function(t,e){var r=(t||0)+1,n=-128*(r-1),i=[r,0,0,0,n,0,r,0,0,n,0,0,r,0,n,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.saturate=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=2*t/3+1,n=(r-1)*-.5,i=[r,n,n,0,0,n,r,n,0,0,n,n,r,0,0,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.desaturate=function(){this.saturate(-1)},e.prototype.negative=function(t){var e=[0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.sepia=function(t){var e=[.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.technicolor=function(t){var e=[1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.polaroid=function(t){var e=[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.toBGR=function(t){var e=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.kodachrome=function(t){var e=[1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.browni=function(t){var e=[.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.vintage=function(t){var e=[.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.colorTone=function(t,e,r,n,i){t=t||.2,e=e||.15,r=r||16770432,n=n||3375104;var o=(r>>16&255)/255,s=(r>>8&255)/255,a=(255&r)/255,u=(n>>16&255)/255,h=(n>>8&255)/255,l=(255&n)/255,c=[.3,.59,.11,0,0,o,s,a,t,0,u,h,l,e,0,o-u,s-h,a-l,0,0];this._loadMatrix(c,i)},e.prototype.night=function(t,e){t=t||.1;var r=[t*-2,-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.predator=function(t,e){var r=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.lsd=function(t){var e=[2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.reset=function(){var t=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(t,!1)},a(e,[{key:"matrix",get:function(){return this.uniforms.m},set:function(t){this.uniforms.m=t}}]),e}(h.Filter);r.default=l,l.prototype.grayscale=l.prototype.greyscale},{"../../core":62}],139:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n'))}return s(e,t),e}(u.Filter);r.default=h},{"../../core":62}],141:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./fxaa/FXAAFilter");Object.defineProperty(r,"FXAAFilter",{enumerable:!0,get:function(){return n(i).default}});var o=t("./noise/NoiseFilter");Object.defineProperty(r,"NoiseFilter",{enumerable:!0,get:function(){return n(o).default}});var s=t("./displacement/DisplacementFilter");Object.defineProperty(r,"DisplacementFilter",{enumerable:!0,get:function(){return n(s).default}});var a=t("./blur/BlurFilter");Object.defineProperty(r,"BlurFilter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./blur/BlurXFilter");Object.defineProperty(r,"BlurXFilter",{enumerable:!0,get:function(){return n(u).default}});var h=t("./blur/BlurYFilter");Object.defineProperty(r,"BlurYFilter",{enumerable:!0,get:function(){return n(h).default}});var l=t("./colormatrix/ColorMatrixFilter");Object.defineProperty(r,"ColorMatrixFilter",{enumerable:!0,get:function(){return n(l).default}});var c=t("./void/VoidFilter");Object.defineProperty(r,"VoidFilter",{enumerable:!0,get:function(){return n(c).default}})},{"./blur/BlurFilter":132,"./blur/BlurXFilter":133,"./blur/BlurYFilter":134,"./colormatrix/ColorMatrixFilter":138,"./displacement/DisplacementFilter":139,"./fxaa/FXAAFilter":140,"./noise/NoiseFilter":142,"./void/VoidFilter":143}],142:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:1;this.removeEvents(),this.interactionDOMElement=t,this.resolution=e,this.addEvents()},e.prototype.addEvents=function(){this.interactionDOMElement&&(h.ticker.shared.add(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="none",this.interactionDOMElement.style["-ms-touch-action"]="none"):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]="none"),window.document.addEventListener("mousemove",this.onMouseMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onMouseDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onMouseOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onMouseOver,!0),window.addEventListener("mouseup",this.onMouseUp,!0),this.supportsTouchEvents&&(this.interactionDOMElement.addEventListener("touchstart",this.onTouchStart,!0),this.interactionDOMElement.addEventListener("touchend",this.onTouchEnd,!0),this.interactionDOMElement.addEventListener("touchmove",this.onTouchMove,!0)),this.supportsPointerEvents?(window.document.addEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("pointerout",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("pointerover",this.onPointerOver,!0),window.addEventListener("pointerup",this.onPointerUp,!0)):(this.normalizeTouchEvents&&(this.interactionDOMElement.addEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.addEventListener("touchmove",this.onPointerMove,!0)),this.normalizeMouseEvents&&(window.document.addEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onPointerOver,!0),window.addEventListener("mouseup",this.onPointerUp,!0))),this.eventsAdded=!0)},e.prototype.removeEvents=function(){this.interactionDOMElement&&(h.ticker.shared.remove(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="",this.interactionDOMElement.style["-ms-touch-action"]=""):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]=""),window.document.removeEventListener("mousemove",this.onMouseMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onMouseDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onMouseOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onMouseOver,!0),window.removeEventListener("mouseup",this.onMouseUp,!0),this.supportsTouchEvents&&(this.interactionDOMElement.removeEventListener("touchstart",this.onTouchStart,!0),this.interactionDOMElement.removeEventListener("touchend",this.onTouchEnd,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onTouchMove,!0)),this.supportsPointerEvents?(window.document.removeEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("pointerdown",this.onPointerDown,!0), +this.interactionDOMElement.removeEventListener("pointerout",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("pointerover",this.onPointerOver,!0),window.removeEventListener("pointerup",this.onPointerUp,!0)):(this.normalizeTouchEvents&&(this.interactionDOMElement.removeEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onPointerMove,!0)),this.normalizeMouseEvents&&(window.document.removeEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onPointerOver,!0),window.removeEventListener("mouseup",this.onPointerUp,!0))),this.interactionDOMElement=null,this.eventsAdded=!1)},e.prototype.update=function(t){if(this._deltaTime+=t,!(this._deltaTime=0;u--){var h=a[u];if(this.processInteractive(t,h,r,n,s)){if(!h.parent)continue;o=!0,s=!1,n=!1}}return i&&(n&&!o&&(e.hitArea?(e.worldTransform.applyInverse(t,this._tempPoint),o=e.hitArea.contains(this._tempPoint.x,this._tempPoint.y)):e.containsPoint&&(o=e.containsPoint(t))),e.interactive&&(o&&!this.eventData.target&&(this.eventData.target=e,this.mouse.target=e,this.pointer.target=e),r(e,o))),o},e.prototype.onMouseDown=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData._reset(),this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.autoPreventDefault&&this.mouse.originalEvent.preventDefault(),this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseDown,!0);var e=2===t.button||3===t.which;this.emit(e?"rightdown":"mousedown",this.eventData)},e.prototype.processMouseDown=function(t,e){var r=this.mouse.originalEvent,n=2===r.button||3===r.which;e&&(t[n?"_isRightDown":"_isLeftDown"]=!0,this.dispatchEvent(t,n?"rightdown":"mousedown",this.eventData))},e.prototype.onMouseUp=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData._reset(),this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseUp,!0);var e=2===t.button||3===t.which;this.emit(e?"rightup":"mouseup",this.eventData)},e.prototype.processMouseUp=function(t,e){var r=this.mouse.originalEvent,n=2===r.button||3===r.which,i=n?"_isRightDown":"_isLeftDown";e?(this.dispatchEvent(t,n?"rightup":"mouseup",this.eventData),t[i]&&(t[i]=!1,this.dispatchEvent(t,n?"rightclick":"click",this.eventData))):t[i]&&(t[i]=!1,this.dispatchEvent(t,n?"rightupoutside":"mouseupoutside",this.eventData))},e.prototype.onMouseMove=function(t){this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData._reset(),this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.didMove=!0,this.cursor=this.defaultCursorStyle,this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseMove,!0),this.emit("mousemove",this.eventData),this.currentCursorStyle!==this.cursor&&(this.currentCursorStyle=this.cursor,this.interactionDOMElement.style.cursor=this.cursor)},e.prototype.processMouseMove=function(t,e){this.processMouseOverOut(t,e),this.moveWhenInside&&!e||this.dispatchEvent(t,"mousemove",this.eventData)},e.prototype.onMouseOut=function(t){this.mouseOverRenderer=!1,this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData._reset(),this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.interactionDOMElement.style.cursor=this.defaultCursorStyle,this.mapPositionToPoint(this.mouse.global,t.clientX,t.clientY),this.processInteractive(this.mouse.global,this.renderer._lastObjectRendered,this.processMouseOverOut,!1),this.emit("mouseout",this.eventData)},e.prototype.processMouseOverOut=function(t,e){e&&this.mouseOverRenderer?(t._mouseOver||(t._mouseOver=!0,this.dispatchEvent(t,"mouseover",this.eventData)),t.buttonMode&&(this.cursor=t.defaultCursor)):t._mouseOver&&(t._mouseOver=!1,this.dispatchEvent(t,"mouseout",this.eventData))},e.prototype.onMouseOver=function(t){this.mouseOverRenderer=!0,this.mouse.originalEvent=t,this.eventData.data=this.mouse,this.eventData._reset(),this.emit("mouseover",this.eventData)},e.prototype.onPointerDown=function(t){this.normalizeToPointerData(t),this.pointer.originalEvent=t,this.eventData.data=this.pointer,this.eventData._reset(),this.mapPositionToPoint(this.pointer.global,t.clientX,t.clientY),this.autoPreventDefault&&this.pointer.originalEvent.preventDefault(),this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerDown,!0),this.emit("pointerdown",this.eventData)},e.prototype.processPointerDown=function(t,e){e&&(t._pointerDown=!0,this.dispatchEvent(t,"pointerdown",this.eventData))},e.prototype.onPointerUp=function(t){this.normalizeToPointerData(t),this.pointer.originalEvent=t,this.eventData.data=this.pointer,this.eventData._reset(),this.mapPositionToPoint(this.pointer.global,t.clientX,t.clientY),this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerUp,!0),this.emit("pointerup",this.eventData)},e.prototype.processPointerUp=function(t,e){e?(this.dispatchEvent(t,"pointerup",this.eventData),t._pointerDown&&(t._pointerDown=!1,this.dispatchEvent(t,"pointertap",this.eventData))):t._pointerDown&&(t._pointerDown=!1,this.dispatchEvent(t,"pointerupoutside",this.eventData))},e.prototype.onPointerMove=function(t){this.normalizeToPointerData(t),this.pointer.originalEvent=t,this.eventData.data=this.pointer,this.eventData._reset(),this.mapPositionToPoint(this.pointer.global,t.clientX,t.clientY),this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerMove,!0),this.emit("pointermove",this.eventData)},e.prototype.processPointerMove=function(t,e){this.pointer.originalEvent.changedTouches||this.processPointerOverOut(t,e),this.moveWhenInside&&!e||this.dispatchEvent(t,"pointermove",this.eventData)},e.prototype.onPointerOut=function(t){this.normalizeToPointerData(t),this.pointer.originalEvent=t,this.eventData.data=this.pointer,this.eventData._reset(),this.mapPositionToPoint(this.pointer.global,t.clientX,t.clientY),this.processInteractive(this.pointer.global,this.renderer._lastObjectRendered,this.processPointerOverOut,!1),this.emit("pointerout",this.eventData)},e.prototype.processPointerOverOut=function(t,e){e&&this.mouseOverRenderer?t._pointerOver||(t._pointerOver=!0,this.dispatchEvent(t,"pointerover",this.eventData)):t._pointerOver&&(t._pointerOver=!1,this.dispatchEvent(t,"pointerout",this.eventData))},e.prototype.onPointerOver=function(t){this.pointer.originalEvent=t,this.eventData.data=this.pointer,this.eventData._reset(),this.emit("pointerover",this.eventData)},e.prototype.onTouchStart=function(t){this.autoPreventDefault&&t.preventDefault();for(var e=t.changedTouches,r=e.length,n=0;n1&&(l=1);var c=Math.sqrt(n*n+i*i),f=this._texture.height/2;n/=c,i/=c,n*=f,i*=f,o[h]=u.x+n,o[h+1]=u.y+i,o[h+2]=u.x-n,o[h+3]=u.y-i,e=u}this.containerUpdateTransform()}},e}(h.default);r.default=f},{"../core":62,"./Mesh":154}],158:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var s=t("../../core"),a=i(s),u=t("../Mesh"),h=n(u),l=function(){function t(e){o(this,t),this.renderer=e}return t.prototype.render=function(t){var e=this.renderer,r=e.context,n=t.worldTransform,i=e.resolution;e.roundPixels?r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i|0,n.ty*i|0):r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t.drawMode===h.default.DRAW_MODES.TRIANGLE_MESH?this._renderTriangleMesh(t):this._renderTriangles(t)},t.prototype._renderTriangleMesh=function(t){for(var e=t.vertices.length/2,r=0;r0){var E=t.canvasPadding/t.worldTransform.a,S=t.canvasPadding/t.worldTransform.d,O=(m+_+b)/3,M=(x+T+w)/3,P=m-O,C=x-M,R=Math.sqrt(P*P+C*C);m=O+P/R*(R+E),x=M+C/R*(R+S),P=_-O,C=T-M,R=Math.sqrt(P*P+C*C),_=O+P/R*(R+E),T=M+C/R*(R+S),P=b-O,C=w-M,R=Math.sqrt(P*P+C*C),b=O+P/R*(R+E),w=M+C/R*(R+S)}i.save(),i.beginPath(),i.moveTo(m,x),i.lineTo(_,T),i.lineTo(b,w),i.closePath(),i.clip();var D=f*y+v*p+d*g-y*p-v*d-f*g,A=m*y+v*b+_*g-y*b-v*_-m*g,I=f*_+m*p+d*b-_*p-m*d-f*b,L=f*y*b+v*_*p+m*d*g-m*y*p-v*d*b-f*_*g,j=x*y+v*w+T*g-y*w-v*T-x*g,F=f*T+x*p+d*w-T*p-x*d-f*w,B=f*y*w+v*T*p+x*d*g-x*y*p-v*d*w-f*T*g;i.transform(A/D,j/D,I/D,F/D,L/D,B/D),i.drawImage(h,0,0,l*u.resolution,c*u.resolution,0,0,l,c),i.restore()}},t.prototype.renderMeshFlat=function(t){var e=this.renderer.context,r=t.vertices,n=r.length/2;e.beginPath();for(var i=1;i0&&void 0!==arguments[0]?arguments[0]:1500,n=arguments[1],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16384;i(this,e);var a=o(this,t.call(this)),h=16384;return s>h&&(s=h),s>r&&(s=r),a._properties=[!1,!0,!1,!1,!1],a._maxSize=r,a._batchSize=s,a._glBuffers={},a._bufferToUpdate=0,a.interactiveChildren=!1,a.blendMode=u.BLEND_MODES.NORMAL,a.roundPixels=!0,a.baseTexture=null,a.setProperties(n),a}return s(e,t),e.prototype.setProperties=function(t){t&&(this._properties[0]="scale"in t?!!t.scale:this._properties[0],this._properties[1]="position"in t?!!t.position:this._properties[1],this._properties[2]="rotation"in t?!!t.rotation:this._properties[2],this._properties[3]="uvs"in t?!!t.uvs:this._properties[3],this._properties[4]="alpha"in t?!!t.alpha:this._properties[4])},e.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},e.prototype.renderWebGL=function(t){var e=this;this.visible&&!(this.worldAlpha<=0)&&this.children.length&&this.renderable&&(this.baseTexture||(this.baseTexture=this.children[0]._texture.baseTexture,this.baseTexture.hasLoaded||this.baseTexture.once("update",function(){return e.onChildrenChange(0)})),t.setObjectRenderer(t.plugins.particle),t.plugins.particle.render(this))},e.prototype.onChildrenChange=function(t){var e=Math.floor(t/this._batchSize);er&&(i=r);var o=t._glBuffers[this.renderer.CONTEXT_UID];o||(o=t._glBuffers[this.renderer.CONTEXT_UID]=this.generateBuffers(t)),this.renderer.setBlendMode(t.blendMode);var s=this.renderer.gl,a=t.worldTransform.copy(this.tempMatrix);a.prepend(this.renderer._activeRenderTarget.projectionMatrix),this.shader.uniforms.projectionMatrix=a.toArray(!0),this.shader.uniforms.uAlpha=t.worldAlpha;var u=e[0]._texture.baseTexture;this.renderer.bindTexture(u);for(var h=0,l=0;hn&&(c=n);var f=o[l];f.uploadDynamic(e,h,c),t._bufferToUpdate===l&&(f.uploadStatic(e,h,c),t._bufferToUpdate=l+1),f.vao.bind().draw(s.TRIANGLES,6*c).unbind()}}},e.prototype.generateBuffers=function(t){for(var e=this.renderer.gl,r=[],n=t._maxSize,i=t._batchSize,o=t._properties,s=0;s0?1:-1})},{}],167:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}var i=t("object-assign"),o=n(i);Object.assign||(Object.assign=o.default)},{"object-assign":5}],168:[function(t,e,r){"use strict";t("./Object.assign"),t("./requestAnimationFrame"),t("./Math.sign"),window.ArrayBuffer||(window.ArrayBuffer=Array),window.Float32Array||(window.Float32Array=Array),window.Uint32Array||(window.Uint32Array=Array),window.Uint16Array||(window.Uint16Array=Array)},{"./Math.sign":166,"./Object.assign":167,"./requestAnimationFrame":169}],169:[function(t,e,r){(function(t){"use strict";var e=16;Date.now&&Date.prototype.getTime||(Date.now=function(){return(new Date).getTime()}),t.performance&&t.performance.now||!function(){var e=Date.now();t.performance||(t.performance={}),t.performance.now=function(){return Date.now()-e}}();for(var r=Date.now(),n=["ms","moz","webkit","o"],i=0;i0;){for(var e=this.queue[0],r=!1,n=0,i=this.uploadHooks.length;n=0;n--)this.add(t.children[n]);return this},t.prototype.destroy=function(){this.ticking&&h.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null,this.ctx=null,this.canvas=null},t}();r.default=f,f.UPLOADS_PER_FRAME=c,u.CanvasRenderer.registerPlugin("prepare",f)},{"../../core":62}],171:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./webgl/WebGLPrepare");Object.defineProperty(r,"webgl",{enumerable:!0,get:function(){return n(i).default}});var o=t("./canvas/CanvasPrepare");Object.defineProperty(r,"canvas",{enumerable:!0,get:function(){return n(o).default}})},{"./canvas/CanvasPrepare":170,"./webgl/WebGLPrepare":172}],172:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){return e instanceof l.BaseTexture&&(t.textureManager.updateTexture(e),!0)}function s(t,e){return e instanceof l.Graphics&&(t.plugins.graphics.updateGraphics(e),!0)}function a(t,e){if(t instanceof l.BaseTexture)return e.indexOf(t)===-1&&e.push(t),!0;if(t._texture&&t._texture instanceof l.Texture){var r=t._texture.baseTexture;return e.indexOf(r)===-1&&e.push(r),!0}return!1}function u(t,e){return t instanceof l.Graphics&&(e.push(t),!0)}r.__esModule=!0;var h=t("../../core"),l=n(h),c=l.ticker.shared,f=4,d=function(){function t(e){i(this,t),this.renderer=e,this.queue=[],this.addHooks=[],this.uploadHooks=[],this.completes=[],this.ticking=!1,this.register(a,o).register(u,s)}return t.prototype.upload=function(e,r){"function"==typeof e&&(r=e,e=null),e&&this.add(e),this.queue.length?(this.numLeft=t.UPLOADS_PER_FRAME,r&&this.completes.push(r),this.ticking||(this.ticking=!0,c.add(this.tick,this))):r&&r()},t.prototype.tick=function(){for(;this.queue.length&&this.numLeft>0;){for(var e=this.queue[0],r=!1,n=0,i=this.uploadHooks.length;n=0;n--)this.add(t.children[n]);return this},t.prototype.destroy=function(){this.ticking&&c.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null},t}();r.default=d,d.UPLOADS_PER_FRAME=f,l.WebGLRenderer.registerPlugin("prepare",d)},{"../../core":62}],173:[function(t,e,r){(function(e){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}r.__esModule=!0,r.loader=r.prepare=r.particles=r.mesh=r.loaders=r.interaction=r.filters=r.extras=r.extract=r.accessibility=void 0;var i=t("./deprecation");Object.keys(i).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return i[t]}})});var o=t("./core");Object.keys(o).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return o[t]}})}),t("./polyfill");var s=t("./accessibility"),a=n(s),u=t("./extract"),h=n(u),l=t("./extras"),c=n(l),f=t("./filters"),d=n(f),p=t("./interaction"),v=n(p),y=t("./loaders"),g=n(y),m=t("./mesh"),_=n(m),b=t("./particles"),x=n(b),T=t("./prepare"),w=n(T);r.accessibility=a,r.extract=h,r.extras=c,r.filters=d,r.interaction=v,r.loaders=g,r.mesh=_,r.particles=x,r.prepare=w;var E=new g.Loader;r.loader=E,e.PIXI=r}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./accessibility":41,"./core":62,"./deprecation":119,"./extract":121,"./extras":130,"./filters":141,"./interaction":147,"./loaders":150,"./mesh":159,"./particles":162,"./polyfill":168,"./prepare":171}]},{},[173])(173)}); +//# sourceMappingURL=pixi.min.js.map diff --git a/js/pixi/4.3.5-dev/pixi.js b/js/pixi/4.3.5-dev/pixi.js new file mode 100644 index 0000000..870c62b --- /dev/null +++ b/js/pixi/4.3.5-dev/pixi.js @@ -0,0 +1,37801 @@ +/*! + * pixi.js - v4.3.5 + * Compiled Wed, 15 Feb 2017 17:11:27 UTC + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.PIXI = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],2:[function(require,module,exports){ +'use strict'; + +module.exports = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, size), + maxZ = zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, size); + earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and size of the data bounding box +function zOrder(x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; + +},{}],3:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @api private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {Mixed} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @api public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @api public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Boolean} exists Only check if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Add a one-time listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Remove the listeners of a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {Mixed} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn + && (!once || listeners.once) + && (!context || listeners.context === context) + ) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {String|Symbol} [event] The event name. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],4:[function(require,module,exports){ +/** + * isMobile.js v0.4.0 + * + * A simple library to detect Apple phones and tablets, + * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone), + * and any kind of seven inch device, via user agent sniffing. + * + * @author: Kai Mallea (kmallea@gmail.com) + * + * @license: http://creativecommons.org/publicdomain/zero/1.0/ + */ +(function (global) { + + var apple_phone = /iPhone/i, + apple_ipod = /iPod/i, + apple_tablet = /iPad/i, + android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i, // Match 'Android' AND 'Mobile' + android_tablet = /Android/i, + amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i, + amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i, + windows_phone = /IEMobile/i, + windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i, // Match 'Windows' AND 'ARM' + other_blackberry = /BlackBerry/i, + other_blackberry_10 = /BB10/i, + other_opera = /Opera Mini/i, + other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i, + other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i, // Match 'Firefox' AND 'Mobile' + seven_inch = new RegExp( + '(?:' + // Non-capturing group + + 'Nexus 7' + // Nexus 7 + + '|' + // OR + + 'BNTV250' + // B&N Nook Tablet 7 inch + + '|' + // OR + + 'Kindle Fire' + // Kindle Fire + + '|' + // OR + + 'Silk' + // Kindle Fire, Silk Accelerated + + '|' + // OR + + 'GT-P1000' + // Galaxy Tab 7 inch + + ')', // End non-capturing group + + 'i'); // Case-insensitive matching + + var match = function(regex, userAgent) { + return regex.test(userAgent); + }; + + var IsMobileClass = function(userAgent) { + var ua = userAgent || navigator.userAgent; + + // Facebook mobile app's integrated browser adds a bunch of strings that + // match everything. Strip it out if it exists. + var tmp = ua.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + // Twitter mobile app's integrated browser on iPad adds a "Twitter for + // iPhone" string. Same probable happens on other tablet platforms. + // This will confuse detection so strip it out if it exists. + tmp = ua.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + this.apple = { + phone: match(apple_phone, ua), + ipod: match(apple_ipod, ua), + tablet: !match(apple_phone, ua) && match(apple_tablet, ua), + device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua) + }; + this.amazon = { + phone: match(amazon_phone, ua), + tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) + }; + this.android = { + phone: match(amazon_phone, ua) || match(android_phone, ua), + tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua) + }; + this.windows = { + phone: match(windows_phone, ua), + tablet: match(windows_tablet, ua), + device: match(windows_phone, ua) || match(windows_tablet, ua) + }; + this.other = { + blackberry: match(other_blackberry, ua), + blackberry10: match(other_blackberry_10, ua), + opera: match(other_opera, ua), + firefox: match(other_firefox, ua), + chrome: match(other_chrome, ua), + device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua) + }; + this.seven_inch = match(seven_inch, ua); + this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch; + + // excludes 'other' devices and ipods, targeting touchscreen phones + this.phone = this.apple.phone || this.android.phone || this.windows.phone; + + // excludes 7 inch devices, classifying as phone or tablet is left to the user + this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet; + + if (typeof window === 'undefined') { + return this; + } + }; + + var instantiate = function() { + var IM = new IsMobileClass(); + IM.Class = IsMobileClass; + return IM; + }; + + if (typeof module !== 'undefined' && module.exports && typeof window === 'undefined') { + //node + module.exports = IsMobileClass; + } else if (typeof module !== 'undefined' && module.exports && typeof window !== 'undefined') { + //browserify + module.exports = instantiate(); + } else if (typeof define === 'function' && define.amd) { + //AMD + define('isMobile', [], global.isMobile = instantiate()); + } else { + global.isMobile = instantiate(); + } + +})(this); + +},{}],5:[function(require,module,exports){ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],6:[function(require,module,exports){ +var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); + +/** + * Helper class to create a webGL buffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ +var Buffer = function(gl, type, data, drawType) +{ + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The WebGL buffer, created upon instantiation + * + * @member {WebGLBuffer} + */ + this.buffer = gl.createBuffer(); + + /** + * The type of the buffer + * + * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} + */ + this.type = type || gl.ARRAY_BUFFER; + + /** + * The draw type of the buffer + * + * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ + this.drawType = drawType || gl.STATIC_DRAW; + + /** + * The data in the buffer, as a typed array + * + * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} + */ + this.data = EMPTY_ARRAY_BUFFER; + + if(data) + { + this.upload(data); + } +}; + +/** + * Uploads the buffer to the GPU + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload + * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract + * @param dontBind {Boolean} whether to bind the buffer before uploading it + */ +Buffer.prototype.upload = function(data, offset, dontBind) +{ + // todo - needed? + if(!dontBind) this.bind(); + + var gl = this.gl; + + data = data || this.data; + offset = offset || 0; + + if(this.data.byteLength >= data.byteLength) + { + gl.bufferSubData(this.type, offset, data); + } + else + { + gl.bufferData(this.type, data, this.drawType); + } + + this.data = data; +}; +/** + * Binds the buffer + * + */ +Buffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindBuffer(this.type, this.buffer); +}; + +Buffer.createVertexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); +}; + +Buffer.createIndexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); +}; + +Buffer.create = function(gl, type, data, drawType) +{ + return new Buffer(gl, type, data, drawType); +}; + +/** + * Destroys the buffer + * + */ +Buffer.prototype.destroy = function(){ + this.gl.deleteBuffer(this.buffer); +}; + +module.exports = Buffer; + +},{}],7:[function(require,module,exports){ + +var Texture = require('./GLTexture'); + +/** + * Helper class to create a webGL Framebuffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + */ +var Framebuffer = function(gl, width, height) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The frame buffer + * + * @member {WebGLFramebuffer} + */ + this.framebuffer = gl.createFramebuffer(); + + /** + * The stencil buffer + * + * @member {WebGLRenderbuffer} + */ + this.stencil = null; + + /** + * The stencil buffer + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The width of the drawing area of the buffer + * + * @member {Number} + */ + this.width = width || 100; + /** + * The height of the drawing area of the buffer + * + * @member {Number} + */ + this.height = height || 100; +}; + +/** + * Adds a texture to the frame buffer + * @param texture {PIXI.glCore.GLTexture} + */ +Framebuffer.prototype.enableTexture = function(texture) +{ + var gl = this.gl; + + this.texture = texture || new Texture(gl); + + this.texture.bind(); + + //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + this.bind(); + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); +}; + +/** + * Initialises the stencil buffer + */ +Framebuffer.prototype.enableStencil = function() +{ + if(this.stencil)return; + + var gl = this.gl; + + this.stencil = gl.createRenderbuffer(); + + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + + // TODO.. this is depth AND stencil? + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width , this.height ); +}; + +/** + * Erases the drawing area and fills it with a colour + * @param r {Number} the red value of the clearing colour + * @param g {Number} the green value of the clearing colour + * @param b {Number} the blue value of the clearing colour + * @param a {Number} the alpha value of the clearing colour + */ +Framebuffer.prototype.clear = function( r, g, b, a ) +{ + this.bind(); + + var gl = this.gl; + + gl.clearColor(r, g, b, a); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Binds the frame buffer to the WebGL context + */ +Framebuffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); +}; + +/** + * Unbinds the frame buffer to the WebGL context + */ +Framebuffer.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, null ); +}; +/** + * Resizes the drawing area of the buffer to the given width and height + * @param width {Number} the new width + * @param height {Number} the new height + */ +Framebuffer.prototype.resize = function(width, height) +{ + var gl = this.gl; + + this.width = width; + this.height = height; + + if ( this.texture ) + { + this.texture.uploadData(null, width, height); + } + + if ( this.stencil ) + { + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + } +}; + +/** + * Destroys this buffer + */ +Framebuffer.prototype.destroy = function() +{ + var gl = this.gl; + + //TODO + if(this.texture) + { + this.texture.destroy(); + } + + gl.deleteFramebuffer(this.framebuffer); + + this.gl = null; + + this.stencil = null; + this.texture = null; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createRGBA = function(gl, width, height, data) +{ + var texture = Texture.fromData(gl, null, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createFloat32 = function(gl, width, height, data) +{ + // create a new texture.. + var texture = new Texture.fromData(gl, data, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +module.exports = Framebuffer; + +},{"./GLTexture":9}],8:[function(require,module,exports){ + +var compileProgram = require('./shader/compileProgram'), + extractAttributes = require('./shader/extractAttributes'), + extractUniforms = require('./shader/extractUniforms'), + generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + +/** + * Helper class to create a webGL Shader + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + */ +var Shader = function(gl, vertexSrc, fragmentSrc) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc); + + + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); + + var uniformData = extractUniforms(gl, this.program); + + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject( gl, uniformData ); +}; +/** + * Uses this shader + */ +Shader.prototype.bind = function() +{ + this.gl.useProgram(this.program); +}; + +/** + * Destroys this shader + * TODO + */ +Shader.prototype.destroy = function() +{ + // var gl = this.gl; +}; + +module.exports = Shader; + +},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18}],9:[function(require,module,exports){ + +/** + * Helper class to create a WebGL Texture + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL context + * @param width {number} the width of the texture + * @param height {number} the height of the texture + * @param format {number} the pixel format of the texture. defaults to gl.RGBA + * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE + */ +var Texture = function(gl, width, height, format, type) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); + + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; + + + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; + + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; + + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + + +}; + +/** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ +Texture.prototype.upload = function(source) +{ + this.bind(); + + var gl = this.gl; + + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + var newWidth = source.videoWidth || source.width; + var newHeight = source.videoHeight || source.height; + + if(newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } + + // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + +}; + +var FLOATING_POINT_AVAILABLE = false; + +/** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.prototype.uploadData = function(data, width, height) +{ + this.bind(); + + var gl = this.gl; + + + if(data instanceof Float32Array) + { + if(!FLOATING_POINT_AVAILABLE) + { + var ext = gl.getExtension("OES_texture_float"); + + if(ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } + + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = gl.UNSIGNED_BYTE; + } + + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + + if(width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } + + this.width = width; + this.height = height; + + +// texSubImage2D +}; + +/** + * Binds the texture + * @param location + */ +Texture.prototype.bind = function(location) +{ + var gl = this.gl; + + if(location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } + + gl.bindTexture(gl.TEXTURE_2D, this.texture); +}; + +/** + * Unbinds the texture + */ +Texture.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, null); +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.minFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + if(this.mipmap) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.magFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); +}; + +/** + * Enables mipmapping + */ +Texture.prototype.enableMipmap = function() +{ + var gl = this.gl; + + this.bind(); + + this.mipmap = true; + + gl.generateMipmap(gl.TEXTURE_2D); +}; + +/** + * Enables linear filtering + */ +Texture.prototype.enableLinearScaling = function() +{ + this.minFilter(true); + this.magFilter(true); +}; + +/** + * Enables nearest neighbour interpolation + */ +Texture.prototype.enableNearestScaling = function() +{ + this.minFilter(false); + this.magFilter(false); +}; + +/** + * Enables clamping on the texture so WebGL will not repeat it + */ +Texture.prototype.enableWrapClamp = function() +{ + var gl = this.gl; + + this.bind(); + + 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); +}; + +/** + * Enable tiling on the texture + */ +Texture.prototype.enableWrapRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); +}; + +Texture.prototype.enableWrapMirrorRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); +}; + + +/** + * Destroys this texture + */ +Texture.prototype.destroy = function() +{ + var gl = this.gl; + //TODO + gl.deleteTexture(this.texture); +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ +Texture.fromSource = function(gl, source, premultiplyAlpha) +{ + var texture = new Texture(gl); + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); + + return texture; +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.fromData = function(gl, data, width, height) +{ + //console.log(data, width, height); + var texture = new Texture(gl); + texture.uploadData(data, width, height); + + return texture; +}; + + +module.exports = Texture; + +},{}],10:[function(require,module,exports){ + +// state object// +var setVertexAttribArrays = require( './setVertexAttribArrays' ); + +/** + * Helper class to work with WebGL VertexArrayObjects (vaos) + * Only works if WebGL extensions are enabled (they usually are) + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function VertexArrayObject(gl, state) +{ + this.nativeVaoExtension = null; + + if(!VertexArrayObject.FORCE_NATIVE) + { + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + this.nativeState = state; + + if(this.nativeVaoExtension) + { + this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + + var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + // VAO - overwrite the state.. + this.nativeState = { + tempAttribState: new Array(maxAttribs), + attribState: new Array(maxAttribs) + }; + } + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of attributes + * + * @member {Array} + */ + this.attributes = []; + + /** + * @member {PIXI.glCore.GLBuffer} + */ + this.indexBuffer = null; + + /** + * A boolean flag + * + * @member {Boolean} + */ + this.dirty = false; +} + +VertexArrayObject.prototype.constructor = VertexArrayObject; +module.exports = VertexArrayObject; + +/** +* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) +* If you find on older devices that things have gone a bit weird then set this to true. +*/ +/** + * Lets the VAO know if you should use the WebGL extension or the native methods. + * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) + * If you find on older devices that things have gone a bit weird then set this to true. + * @static + * @property {Boolean} FORCE_NATIVE + */ +VertexArrayObject.FORCE_NATIVE = false; + +/** + * Binds the buffer + */ +VertexArrayObject.prototype.bind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + + if(this.dirty) + { + this.dirty = false; + this.activate(); + } + } + else + { + + this.activate(); + } + + return this; +}; + +/** + * Unbinds the buffer + */ +VertexArrayObject.prototype.unbind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + return this; +}; + +/** + * Uses this vao + */ +VertexArrayObject.prototype.activate = function() +{ + + var gl = this.gl; + var lastBuffer = null; + + for (var i = 0; i < this.attributes.length; i++) + { + var attrib = this.attributes[i]; + + if(lastBuffer !== attrib.buffer) + { + attrib.buffer.bind(); + lastBuffer = attrib.buffer; + } + + //attrib.attribute.pointer(attrib.type, attrib.normalized, attrib.stride, attrib.start); + gl.vertexAttribPointer(attrib.attribute.location, + attrib.attribute.size, attrib.type || gl.FLOAT, + attrib.normalized || false, + attrib.stride || 0, + attrib.start || 0); + + + } + + setVertexAttribArrays(gl, this.attributes, this.nativeState); + + this.indexBuffer.bind(); + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + * @param attribute {*} + * @param type {String} + * @param normalized {Boolean} + * @param stride {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start) +{ + this.attributes.push({ + buffer: buffer, + attribute: attribute, + + location: attribute.location, + type: type || this.gl.FLOAT, + normalized: normalized || false, + stride: stride || 0, + start: start || 0 + }); + + this.dirty = true; + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + */ +VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) +{ + this.indexBuffer = buffer; + + this.dirty = true; + + return this; +}; + +/** + * Unbinds this vao and disables it + */ +VertexArrayObject.prototype.clear = function() +{ + // var gl = this.gl; + + // TODO - should this function unbind after clear? + // for now, no but lets see what happens in the real world! + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + } + + this.attributes.length = 0; + this.indexBuffer = null; + + return this; +}; + +/** + * @param type {Number} + * @param size {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.draw = function(type, size, start) +{ + var gl = this.gl; + gl.drawElements(type, size, gl.UNSIGNED_SHORT, start || 0); + + return this; +}; + +/** + * Destroy this vao + */ +VertexArrayObject.prototype.destroy = function() +{ + // lose references + this.gl = null; + this.indexBuffer = null; + this.attributes = null; + this.nativeState = null; + + if(this.nativeVao) + { + this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); + } + + this.nativeVaoExtension = null; + this.nativeVao = null; +}; + +},{"./setVertexAttribArrays":13}],11:[function(require,module,exports){ + +/** + * Helper class to create a webGL Context + * + * @class + * @memberof PIXI.glCore + * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from + * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * @return {WebGLRenderingContext} the WebGL context + */ +var createContext = function(canvas, options) +{ + var gl = canvas.getContext('webgl', options) || + canvas.getContext('experimental-webgl', options); + + if (!gl) + { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + return gl; +}; + +module.exports = createContext; + +},{}],12:[function(require,module,exports){ +var gl = { + createContext: require('./createContext'), + setVertexAttribArrays: require('./setVertexAttribArrays'), + GLBuffer: require('./GLBuffer'), + GLFramebuffer: require('./GLFramebuffer'), + GLShader: require('./GLShader'), + GLTexture: require('./GLTexture'), + VertexArrayObject: require('./VertexArrayObject'), + shader: require('./shader') +}; + +// Export for Node-compatible environments +if (typeof module !== 'undefined' && module.exports) +{ + // Export the module + module.exports = gl; +} + +// Add to the browser window pixi.gl +if (typeof window !== 'undefined') +{ + // add the window object + window.PIXI = window.PIXI || {}; + window.PIXI.glCore = gl; +} + +},{"./GLBuffer":6,"./GLFramebuffer":7,"./GLShader":8,"./GLTexture":9,"./VertexArrayObject":10,"./createContext":11,"./setVertexAttribArrays":13,"./shader":19}],13:[function(require,module,exports){ +// var GL_MAP = {}; + +/** + * @param gl {WebGLRenderingContext} The current WebGL context + * @param attribs {*} + * @param state {*} + */ +var setVertexAttribArrays = function (gl, attribs, state) +{ + var i; + if(state) + { + var tempAttribState = state.tempAttribState, + attribState = state.attribState; + + for (i = 0; i < tempAttribState.length; i++) + { + tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + tempAttribState[attribs[i].attribute.location] = true; + } + + for (i = 0; i < attribState.length; i++) + { + if (attribState[i] !== tempAttribState[i]) + { + attribState[i] = tempAttribState[i]; + + if (state.attribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } + + } + else + { + for (i = 0; i < attribs.length; i++) + { + var attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); + } + } +}; + +module.exports = setVertexAttribArrays; + +},{}],14:[function(require,module,exports){ + +/** + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @return {WebGLProgram} the shader program + */ +var compileProgram = function(gl, vertexSrc, fragmentSrc) +{ + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + + var program = gl.createProgram(); + + gl.attachShader(program, glVertShader); + gl.attachShader(program, glFragShader); + gl.linkProgram(program); + + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + console.error('Pixi.js Error: Could not initialize shader.'); + console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); + console.error('gl.getError()', gl.getError()); + + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') + { + console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + + gl.deleteProgram(program); + program = null; + } + + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + + return program; +}; + +/** + * @private + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @return {WebGLShader} the shader + */ +var compileShader = function (gl, type, src) +{ + var shader = gl.createShader(type); + + gl.shaderSource(shader, src); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + console.log(gl.getShaderInfoLog(shader)); + return null; + } + + return shader; +}; + +module.exports = compileProgram; + +},{}],15:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} Type of value + * @param size {Number} + */ +var defaultValue = function(type, size) +{ + switch (type) + { + case 'float': + return 0; + + case 'vec2': + return new Float32Array(2 * size); + + case 'vec3': + return new Float32Array(3 * size); + + case 'vec4': + return new Float32Array(4 * size); + + case 'int': + case 'sampler2D': + return 0; + + case 'ivec2': + return new Int32Array(2 * size); + + case 'ivec3': + return new Int32Array(3 * size); + + case 'ivec4': + return new Int32Array(4 * size); + + case 'bool': + return false; + + case 'bvec2': + + return booleanArray( 2 * size); + + case 'bvec3': + return booleanArray(3 * size); + + case 'bvec4': + return booleanArray(4 * size); + + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } +}; + +var booleanArray = function(size) +{ + var array = new Array(size); + + for (var i = 0; i < array.length; i++) + { + array[i] = false; + } + + return array; +}; + +module.exports = defaultValue; + +},{}],16:[function(require,module,exports){ + +var mapType = require('./mapType'); +var mapSize = require('./mapSize'); + +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the attributes from + * @return attributes {Object} + */ +var extractAttributes = function(gl, program) +{ + var attributes = {}; + + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + + for (var i = 0; i < totalAttributes; i++) + { + var attribData = gl.getActiveAttrib(program, i); + var type = mapType(gl, attribData.type); + + attributes[attribData.name] = { + type:type, + size:mapSize(type), + location:gl.getAttribLocation(program, attribData.name), + //TODO - make an attribute object + pointer: pointer + }; + } + + return attributes; +}; + +var pointer = function(type, normalized, stride, start){ + // console.log(this.location) + gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +}; + +module.exports = extractAttributes; + +},{"./mapSize":20,"./mapType":21}],17:[function(require,module,exports){ +var mapType = require('./mapType'); +var defaultValue = require('./defaultValue'); + +/** + * Extracts the uniforms + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the uniforms from + * @return uniforms {Object} + */ +var extractUniforms = function(gl, program) +{ + var uniforms = {}; + + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + + for (var i = 0; i < totalUniforms; i++) + { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]/, ""); + var type = mapType(gl, uniformData.type ); + + uniforms[name] = { + type:type, + size:uniformData.size, + location:gl.getUniformLocation(program, name), + value:defaultValue(type, uniformData.size) + }; + } + + return uniforms; +}; + +module.exports = extractUniforms; + +},{"./defaultValue":15,"./mapType":21}],18:[function(require,module,exports){ +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param uniforms {Array} @mat ? + * @return attributes {Object} + */ +var generateUniformAccessObject = function(gl, uniformData) +{ + // this is the object we will be sending back. + // an object hierachy will be created for structs + var uniforms = {data:{}}; + + uniforms.gl = gl; + + var uniformKeys= Object.keys(uniformData); + + for (var i = 0; i < uniformKeys.length; i++) + { + var fullName = uniformKeys[i]; + + var nameTokens = fullName.split('.'); + var name = nameTokens[nameTokens.length - 1]; + + var uniformGroup = getUniformGroup(nameTokens, uniforms); + + var uniform = uniformData[fullName]; + uniformGroup.data[name] = uniform; + + uniformGroup.gl = gl; + + Object.defineProperty(uniformGroup, name, { + get: generateGetter(name), + set: generateSetter(name, uniform) + }); + } + + return uniforms; +}; + +var generateGetter = function(name) +{ + var template = getterTemplate.replace('%%', name); + return new Function(template); // jshint ignore:line +}; + +var generateSetter = function(name, uniform) +{ + var template = setterTemplate.replace(/%%/g, name); + var setTemplate; + + if(uniform.size === 1) + { + setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; + } + else + { + setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; + } + + if(setTemplate) + { + template += "\nthis.gl." + setTemplate + ";"; + } + + return new Function('value', template); // jshint ignore:line +}; + +var getUniformGroup = function(nameTokens, uniform) +{ + var cur = uniform; + + for (var i = 0; i < nameTokens.length - 1; i++) + { + var o = cur[nameTokens[i]] || {data:{}}; + cur[nameTokens[i]] = o; + cur = o; + } + + return cur; +}; + +var getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +var setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;' +].join('\n'); + + +var GLSL_TO_SINGLE_SETTERS = { + + 'float': 'uniform1f(location, value)', + + 'vec2': 'uniform2f(location, value[0], value[1])', + 'vec3': 'uniform3f(location, value[0], value[1], value[2])', + 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', + + 'int': 'uniform1i(location, value)', + 'ivec2': 'uniform2i(location, value[0], value[1])', + 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', + 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'bool': 'uniform1i(location, value)', + 'bvec2': 'uniform2i(location, value[0], value[1])', + 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', + 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'mat2': 'uniformMatrix2fv(location, false, value)', + 'mat3': 'uniformMatrix3fv(location, false, value)', + 'mat4': 'uniformMatrix4fv(location, false, value)', + + 'sampler2D':'uniform1i(location, value)' +}; + +var GLSL_TO_ARRAY_SETTERS = { + + 'float': 'uniform1fv(location, value)', + + 'vec2': 'uniform2fv(location, value)', + 'vec3': 'uniform3fv(location, value)', + 'vec4': 'uniform4fv(location, value)', + + 'int': 'uniform1iv(location, value)', + 'ivec2': 'uniform2iv(location, value)', + 'ivec3': 'uniform3iv(location, value)', + 'ivec4': 'uniform4iv(location, value)', + + 'bool': 'uniform1iv(location, value)', + 'bvec2': 'uniform2iv(location, value)', + 'bvec3': 'uniform3iv(location, value)', + 'bvec4': 'uniform4iv(location, value)', + + 'sampler2D':'uniform1iv(location, value)' +}; + +module.exports = generateUniformAccessObject; + +},{}],19:[function(require,module,exports){ +module.exports = { + compileProgram: require('./compileProgram'), + defaultValue: require('./defaultValue'), + extractAttributes: require('./extractAttributes'), + extractUniforms: require('./extractUniforms'), + generateUniformAccessObject: require('./generateUniformAccessObject'), + mapSize: require('./mapSize'), + mapType: require('./mapType') +}; +},{"./compileProgram":14,"./defaultValue":15,"./extractAttributes":16,"./extractUniforms":17,"./generateUniformAccessObject":18,"./mapSize":20,"./mapType":21}],20:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} + * @return {Number} + */ +var mapSize = function(type) +{ + return GLSL_TO_SIZE[type]; +}; + + +var GLSL_TO_SIZE = { + 'float': 1, + 'vec2': 2, + 'vec3': 3, + 'vec4': 4, + + 'int': 1, + 'ivec2': 2, + 'ivec3': 3, + 'ivec4': 4, + + 'bool': 1, + 'bvec2': 2, + 'bvec3': 3, + 'bvec4': 4, + + 'mat2': 4, + 'mat3': 9, + 'mat4': 16, + + 'sampler2D': 1 +}; + +module.exports = mapSize; + +},{}],21:[function(require,module,exports){ + + +var mapSize = function(gl, type) +{ + if(!GL_TABLE) + { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + + GL_TABLE = {}; + + for(var i = 0; i < typeNames.length; ++i) + { + var tn = typeNames[i]; + GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + } + } + + return GL_TABLE[type]; +}; + +var GL_TABLE = null; + +var GL_TO_GLSL_TYPES = { + 'FLOAT': 'float', + 'FLOAT_VEC2': 'vec2', + 'FLOAT_VEC3': 'vec3', + 'FLOAT_VEC4': 'vec4', + + 'INT': 'int', + 'INT_VEC2': 'ivec2', + 'INT_VEC3': 'ivec3', + 'INT_VEC4': 'ivec4', + + 'BOOL': 'bool', + 'BOOL_VEC2': 'bvec2', + 'BOOL_VEC3': 'bvec3', + 'BOOL_VEC4': 'bvec4', + + 'FLOAT_MAT2': 'mat2', + 'FLOAT_MAT3': 'mat3', + 'FLOAT_MAT4': 'mat4', + + 'SAMPLER_2D': 'sampler2D' +}; + +module.exports = mapSize; + +},{}],22:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) + +},{"_process":23}],23:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],24:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],25:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],26:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],27:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":25,"./encode":26}],28:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":29,"punycode":24,"querystring":27}],29:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],30:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _async = require('./async'); + +var async = _interopRequireWildcard(_async); + +var _Resource = require('./Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// some constants +var MAX_PROGRESS = 100; +var rgxExtractUrlHash = /(#[\w-]+)?$/; + +/** + * Manages the state and loading of multiple resources to load. + * + * @class + */ + +var Loader = function () { + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader() { + var _this = this; + + var baseUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var concurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; + + _classCallCheck(this, Loader); + + /** + * The base url for all resources loaded by this loader. + * + * @member {string} + */ + this.baseUrl = baseUrl; + + /** + * The progress percent of the loader going through the queue. + * + * @member {number} + */ + this.progress = 0; + + /** + * Loading state of the loader, true if it is currently loading resources. + * + * @member {boolean} + */ + this.loading = false; + + /** + * A querystring to append to every URL added to the loader. + * + * This should be a valid query string *without* the question-mark (`?`). The loader will + * also *not* escape values for you. Make sure to escape your parameters with + * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. + * + * @example + * + * ```js + * const loader = new Loader(); + * + * loader.defaultQueryString = 'user=me&password=secret'; + * + * // This will request 'image.png?user=me&password=secret' + * loader.add('image.png').load(); + * + * loader.reset(); + * + * // This will request 'image.png?v=1&user=me&password=secret' + * loader.add('iamge.png?v=1').load(); + * ``` + */ + this.defaultQueryString = ''; + + /** + * The middleware to run before loading each resource. + * + * @member {function[]} + */ + this._beforeMiddleware = []; + + /** + * The middleware to run after loading each resource. + * + * @member {function[]} + */ + this._afterMiddleware = []; + + /** + * The tracks the resources we are currently completing parsing for. + * + * @member {Resource[]} + */ + this._resourcesParsing = []; + + /** + * The `_loadResource` function bound with this object context. + * + * @private + * @member {function} + * @param {Resource} r - The resource to load + * @param {Function} d - The dequeue function + * @return {undefined} + */ + this._boundLoadResource = function (r, d) { + return _this._loadResource(r, d); + }; + + /** + * The resources waiting to be loaded. + * + * @private + * @member {Resource[]} + */ + this._queue = async.queue(this._boundLoadResource, concurrency); + + this._queue.pause(); + + /** + * All the resources for this loader keyed by name. + * + * @member {object} + */ + this.resources = {}; + + /** + * Dispatched once per loaded or errored resource. + * + * The callback looks like {@link Loader.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once per errored resource. + * + * The callback looks like {@link Loader.OnErrorSignal}. + * + * @member {Signal} + */ + this.onError = new _miniSignals2.default(); + + /** + * Dispatched once per loaded resource. + * + * The callback looks like {@link Loader.OnLoadSignal}. + * + * @member {Signal} + */ + this.onLoad = new _miniSignals2.default(); + + /** + * Dispatched when the loader begins to process the queue. + * + * The callback looks like {@link Loader.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched when the queued resources all load. + * + * The callback looks like {@link Loader.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * When the progress changes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnProgressSignal + * @param {Loader} loader - The loader the progress is advancing on. + * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance. + */ + + /** + * When an error occurrs the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnErrorSignal + * @param {Loader} loader - The loader the error happened in. + * @param {Resource} resource - The resource that caused the error. + */ + + /** + * When a load completes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnLoadSignal + * @param {Loader} loader - The loader that laoded the resource. + * @param {Resource} resource - The resource that has completed loading. + */ + + /** + * When the loader starts loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnStartSignal + * @param {Loader} loader - The loader that has started loading resources. + */ + + /** + * When the loader completes loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnCompleteSignal + * @param {Loader} loader - The loader that has finished loading resources. + */ + } + + /** + * Adds a resource (or multiple resources) to the loader queue. + * + * This function can take a wide variety of different parameters. The only thing that is always + * required the url to load. All the following will work: + * + * ```js + * loader + * // normal param syntax + * .add('key', 'http://...', function () {}) + * .add('http://...', function () {}) + * .add('http://...') + * + * // object syntax + * .add({ + * name: 'key2', + * url: 'http://...' + * }, function () {}) + * .add({ + * url: 'http://...' + * }, function () {}) + * .add({ + * name: 'key3', + * url: 'http://...' + * onComplete: function () {} + * }) + * .add({ + * url: 'https://...', + * onComplete: function () {}, + * crossOrigin: true + * }) + * + * // you can also pass an array of objects or urls or both + * .add([ + * { name: 'key4', url: 'http://...', onComplete: function () {} }, + * { url: 'http://...', onComplete: function () {} }, + * 'http://...' + * ]) + * + * // and you can use both params and options + * .add('key', 'http://...', { crossOrigin: true }, function () {}) + * .add('http://...', { crossOrigin: true }, function () {}); + * ``` + * + * @param {string} [name] - The name of the resource to load, if not passed the url is used. + * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @param {object} [options] - The options for the load. + * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should + * the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @param {function} [cb] - Function to call when this specific resource completes loading. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.add = function add(name, url, options, cb) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + + return this; + } + + // if an object is passed instead of params + if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') { + cb = url || name.callback || name.onComplete; + options = name; + url = name.url; + name = name.name || name.key || name.url; + } + + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + cb = options; + options = url; + url = name; + } + + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + cb = options; + options = null; + } + + // if loading already you can only add resources that have a parent. + if (this.loading && (!options || !options.parentResource)) { + throw new Error('Cannot add resources while the loader is running.'); + } + + // check if resource already exists. + if (this.resources[name]) { + throw new Error('Resource named "' + name + '" already exists.'); + } + + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + + // create the store the resource + this.resources[name] = new _Resource2.default(name, url, options); + + if (typeof cb === 'function') { + this.resources[name].onAfterMiddleware.once(cb); + } + + // if actively loading, make sure to adjust progress chunks for that parent and its children + if (this.loading) { + var parent = options.parentResource; + var incompleteChildren = []; + + for (var _i = 0; _i < parent.children.length; ++_i) { + if (!parent.children[_i].isComplete) { + incompleteChildren.push(parent.children[_i]); + } + } + + var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent + var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child + + parent.children.push(this.resources[name]); + parent.progressChunk = eachChunk; + + for (var _i2 = 0; _i2 < incompleteChildren.length; ++_i2) { + incompleteChildren[_i2].progressChunk = eachChunk; + } + + this.resources[name].progressChunk = eachChunk; + } + + // add the resource to the queue + this._queue.push(this.resources[name]); + + return this; + }; + + /** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * + * @method before + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.pre = function pre(fn) { + this._beforeMiddleware.push(fn); + + return this; + }; + + /** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * + * @alias use + * @method after + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.use = function use(fn) { + this._afterMiddleware.push(fn); + + return this; + }; + + /** + * Resets the queue of the loader to prepare for a new load. + * + * @return {Loader} Returns itself. + */ + + + Loader.prototype.reset = function reset() { + this.progress = 0; + this.loading = false; + + this._queue.kill(); + this._queue.pause(); + + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + + if (res._onLoadBinding) { + res._onLoadBinding.detach(); + } + + if (res.isLoading) { + res.abort(); + } + } + + this.resources = {}; + + return this; + }; + + /** + * Starts loading the queued resources. + * + * @param {function} [cb] - Optional callback that will be bound to the `complete` event. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.load = function load(cb) { + // register complete callback if they pass one + if (typeof cb === 'function') { + this.onComplete.once(cb); + } + + // if the queue has already started we are done here + if (this.loading) { + return this; + } + + // distribute progress chunks + var chunk = 100 / this._queue._tasks.length; + + for (var i = 0; i < this._queue._tasks.length; ++i) { + this._queue._tasks[i].data.progressChunk = chunk; + } + + // update loading state + this.loading = true; + + // notify of start + this.onStart.dispatch(this); + + // start loading + this._queue.resume(); + + return this; + }; + + /** + * Prepares a url for usage based on the configuration of this object + * + * @private + * @param {string} url - The url to prepare. + * @return {string} The prepared url. + */ + + + Loader.prototype._prepareUrl = function _prepareUrl(url) { + var parsedUrl = (0, _parseUri2.default)(url, { strictMode: true }); + var result = void 0; + + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { + result = url; + } + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + else if (this.baseUrl.length && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 && url.charAt(0) !== '/') { + result = this.baseUrl + '/' + url; + } else { + result = this.baseUrl + url; + } + + // if we need to add a default querystring, there is a bit more work + if (this.defaultQueryString) { + var hash = rgxExtractUrlHash.exec(result)[0]; + + result = result.substr(0, result.length - hash.length); + + if (result.indexOf('?') !== -1) { + result += '&' + this.defaultQueryString; + } else { + result += '?' + this.defaultQueryString; + } + + result += hash; + } + + return result; + }; + + /** + * Loads a single resource. + * + * @private + * @param {Resource} resource - The resource to load. + * @param {function} dequeue - The function to call when we need to dequeue this item. + */ + + + Loader.prototype._loadResource = function _loadResource(resource, dequeue) { + var _this2 = this; + + resource._dequeue = dequeue; + + // run before middleware + async.eachSeries(this._beforeMiddleware, function (fn, next) { + fn.call(_this2, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, function () { + if (resource.isComplete) { + _this2._onLoad(resource); + } else { + resource._onLoadBinding = resource.onComplete.once(_this2._onLoad, _this2); + resource.load(); + } + }); + }; + + /** + * Called once each resource has loaded. + * + * @private + */ + + + Loader.prototype._onComplete = function _onComplete() { + this.loading = false; + + this.onComplete.dispatch(this, this.resources); + }; + + /** + * Called each time a resources is loaded. + * + * @private + * @param {Resource} resource - The resource that was loaded + */ + + + Loader.prototype._onLoad = function _onLoad(resource) { + var _this3 = this; + + resource._onLoadBinding = null; + + // remove this resource from the async queue, and add it to our list of resources that are being parsed + resource._dequeue(); + this._resourcesParsing.push(resource); + + // run middleware, this *must* happen before dequeue so sub-assets get added properly + async.eachSeries(this._afterMiddleware, function (fn, next) { + fn.call(_this3, resource, next); + }, function () { + resource.onAfterMiddleware.dispatch(resource); + + _this3.progress += resource.progressChunk; + _this3.onProgress.dispatch(_this3, resource); + + if (resource.error) { + _this3.onError.dispatch(resource.error, _this3, resource); + } else { + _this3.onLoad.dispatch(_this3, resource); + } + + _this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1); + + // do completion check + if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) { + _this3.progress = MAX_PROGRESS; + _this3._onComplete(); + } + }); + }; + + return Loader; +}(); + +exports.default = Loader; + +},{"./Resource":31,"./async":32,"mini-signals":36,"parse-uri":37}],31:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// tests is CORS is supported in XHR, if not we need to use XDR +var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest())); +var tempAnchor = null; + +// some status constants +var STATUS_NONE = 0; +var STATUS_OK = 200; +var STATUS_EMPTY = 204; + +// noop +function _noop() {} /* empty */ + +/** + * Manages the state and loading of a resource and all child resources. + * + * @class + */ + +var Resource = function () { + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. + */ + Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) { + setExtMap(Resource._loadTypeMap, extname, loadType); + }; + + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ + + + Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); + }; + + /** + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass + * an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + */ + + + function Resource(name, url, options) { + _classCallCheck(this, Resource); + + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + + options = options || {}; + + /** + * The state flags of this resource. + * + * @member {number} + */ + this._flags = 0; + + // set data url flag, needs to be set early for some _determineX checks to work. + this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); + + /** + * The name of this resource. + * + * @member {string} + * @readonly + */ + this.name = name; + + /** + * The url used to load this resource. + * + * @member {string} + * @readonly + */ + this.url = url; + + /** + * The extension used to load this resource. + * + * @member {string} + * @readonly + */ + this.extension = this._getExtension(); + + /** + * The data that was loaded by the resource. + * + * @member {any} + */ + this.data = null; + + /** + * Is this request cross-origin? If unset, determined automatically. + * + * @member {string} + */ + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + + /** + * The method of loading to use for this resource. + * + * @member {Resource.LOAD_TYPE} + */ + this.loadType = options.loadType || this._determineLoadType(); + + /** + * The type used to load the resource via XHR. If unset, determined automatically. + * + * @member {string} + */ + this.xhrType = options.xhrType; + + /** + * Extra info for middleware, and controlling specifics about how the resource loads. + * + * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + * Meaning it will modify it as it sees fit. + * + * @member {object} + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources + * to. + */ + this.metadata = options.metadata || {}; + + /** + * The error that occurred while loading (if any). + * + * @member {Error} + * @readonly + */ + this.error = null; + + /** + * The XHR object that was used to load this resource. This is only set + * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * + * @member {XMLHttpRequest} + * @readonly + */ + this.xhr = null; + + /** + * The child resources this resource owns. + * + * @member {Resource[]} + * @readonly + */ + this.children = []; + + /** + * The resource type. + * + * @member {Resource.TYPE} + * @readonly + */ + this.type = Resource.TYPE.UNKNOWN; + + /** + * The progress chunk owned by this resource. + * + * @member {number} + * @readonly + */ + this.progressChunk = 0; + + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * + * @private + * @member {function} + */ + this._dequeue = _noop; + + /** + * Used a storage place for the on load binding used privately by the loader. + * + * @private + * @member {function} + */ + this._onLoadBinding = null; + + /** + * The `complete` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundComplete = this.complete.bind(this); + + /** + * The `_onError` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnError = this._onError.bind(this); + + /** + * The `_onProgress` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnProgress = this._onProgress.bind(this); + + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + this._boundXdrOnTimeout = this._xdrOnTimeout.bind(this); + + /** + * Dispatched when the resource beings to load. + * + * The callback looks like {@link Resource.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched each time progress of this resource load updates. + * Not all resources types and loader systems can support this event + * so sometimes it may not be available. If the resource + * is being loaded on a modern browser, using XHR, and the remote server + * properly sets Content-Length headers, then this will be available. + * + * The callback looks like {@link Resource.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once this resource has loaded, if there was an error it will + * be in the `error` property. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * Dispatched after this resource has had all the *after* middleware run on it. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onAfterMiddleware = new _miniSignals2.default(); + + /** + * When the resource starts to load. + * + * @memberof Resource + * @callback OnStartSignal + * @param {Resource} resource - The resource that the event happened on. + */ + + /** + * When the resource reports loading progress. + * + * @memberof Resource + * @callback OnProgressSignal + * @param {Resource} resource - The resource that the event happened on. + * @param {number} percentage - The progress of the load in the range [0, 1]. + */ + + /** + * When the resource finishes loading. + * + * @memberof Resource + * @callback OnCompleteSignal + * @param {Resource} resource - The resource that the event happened on. + */ + } + + /** + * Stores whether or not this url is a data url. + * + * @member {boolean} + * @readonly + */ + + + /** + * Marks the resource as complete. + * + */ + Resource.prototype.complete = function complete() { + // TODO: Clean this up in a wrapper or something...gross.... + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + + this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true); + this._setFlag(Resource.STATUS_FLAGS.LOADING, false); + + this.onComplete.dispatch(this); + }; + + /** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ + + + Resource.prototype.abort = function abort(message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + + // store error + this.error = new Error(message); + + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } else if (this.xdr) { + this.xdr.abort(); + } else if (this.data) { + // single source + if (this.data.src) { + this.data.src = Resource.EMPTY_GIF; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + + // done now. + this.complete(); + }; + + /** + * Kicks off loading of this resource. This method is asynchronous. + * + * @param {function} [cb] - Optional callback to call once the resource is loaded. + */ + + + Resource.prototype.load = function load(cb) { + var _this = this; + + if (this.isLoading) { + return; + } + + if (this.isComplete) { + if (cb) { + setTimeout(function () { + return cb(_this); + }, 1); + } + + return; + } else if (cb) { + this.onComplete.once(cb); + } + + this._setFlag(Resource.STATUS_FLAGS.LOADING, true); + + this.onStart.dispatch(this); + + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + + switch (this.loadType) { + case Resource.LOAD_TYPE.IMAGE: + this.type = Resource.TYPE.IMAGE; + this._loadElement('image'); + break; + + case Resource.LOAD_TYPE.AUDIO: + this.type = Resource.TYPE.AUDIO; + this._loadSourceElement('audio'); + break; + + case Resource.LOAD_TYPE.VIDEO: + this.type = Resource.TYPE.VIDEO; + this._loadSourceElement('video'); + break; + + case Resource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } else { + this._loadXhr(); + } + break; + } + }; + + /** + * Checks if the flag is set. + * + * @private + * @param {number} flag - The flag to check. + * @return {boolean} True if the flag is set. + */ + + + Resource.prototype._hasFlag = function _hasFlag(flag) { + return !!(this._flags & flag); + }; + + /** + * (Un)Sets the flag. + * + * @private + * @param {number} flag - The flag to (un)set. + * @param {boolean} value - Whether to set or (un)set the flag. + */ + + + Resource.prototype._setFlag = function _setFlag(flag, value) { + this._flags = value ? this._flags | flag : this._flags & ~flag; + }; + + /** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadElement = function _loadElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'image' && typeof window.Image !== 'undefined') { + this.data = new Image(); + } else { + this.data = document.createElement(type); + } + + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + }; + + /** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadSourceElement = function _loadSourceElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'audio' && typeof window.Audio !== 'undefined') { + this.data = new Audio(); + } else { + this.data = document.createElement(type); + } + + if (this.data === null) { + this.abort('Unsupported element: ' + type); + + return; + } + + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } else if (Array.isArray(this.url)) { + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i])); + } + } else { + this.data.appendChild(this._createSource(type, this.url)); + } + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + + this.data.load(); + }; + + /** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ + + + Resource.prototype._loadXhr = function _loadXhr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xhr = this.xhr = new XMLHttpRequest(); + + // set the request type and url + xhr.open('GET', this.url, true); + + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; + } else { + xhr.responseType = this.xhrType; + } + + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + + xhr.send(); + }; + + /** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ + + + Resource.prototype._loadXdr = function _loadXdr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xdr = this.xhr = new XDomainRequest(); + + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = 5000; + + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXdrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + + xdr.open('GET', this.url, true); + + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { + return xdr.send(); + }, 1); + }; + + /** + * Creates a source used in loading via an element. + * + * @private + * @param {string} type - The element type (video or audio). + * @param {string} url - The source URL to load from. + * @param {string} [mime] - The mime type of the video + * @return {HTMLSourceElement} The source element. + */ + + + Resource.prototype._createSource = function _createSource(type, url, mime) { + if (!mime) { + mime = type + '/' + url.substr(url.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = url; + source.type = mime; + + return source; + }; + + /** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ + + + Resource.prototype._onError = function _onError(event) { + this.abort('Failed to load element using: ' + event.target.nodeName); + }; + + /** + * Called if a load progress event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ + + + Resource.prototype._onProgress = function _onProgress(event) { + if (event && event.lengthComputable) { + this.onProgress.dispatch(this, event.loaded / event.total); + } + }; + + /** + * Called if an error event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestErrorEvent|Event} event - Error event. + */ + + + Resource.prototype._xhrOnError = function _xhrOnError() { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"'); + }; + + /** + * Called if an abort event fires for xhr. + * + * @private + * @param {XMLHttpRequestAbortEvent} event - Abort Event + */ + + + Resource.prototype._xhrOnAbort = function _xhrOnAbort() { + this.abort(reqType(this.xhr) + ' Request was aborted by the user.'); + }; + + /** + * Called if a timeout event fires for xdr. + * + * @private + * @param {Event} event - Timeout event. + */ + + + Resource.prototype._xdrOnTimeout = function _xdrOnTimeout() { + this.abort(reqType(this.xhr) + ' Request timed out.'); + }; + + /** + * Called when data successfully loads from an xhr/xdr request. + * + * @private + * @param {XMLHttpRequestLoadEvent|Event} event - Load event + */ + + + Resource.prototype._xhrOnLoad = function _xhrOnLoad() { + var xhr = this.xhr; + var status = typeof xhr.status === 'undefined' ? xhr.status : STATUS_OK; // XDR has no `.status`, assume 200. + + // status can be 0 when using the `file://` protocol so we also check if a response is set + if (status === STATUS_OK || status === STATUS_EMPTY || status === STATUS_NONE && xhr.responseText.length > 0) { + // if text, just return it + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { + this.data = xhr.responseText; + this.type = Resource.TYPE.TEXT; + } + // if json, parse into json object + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(xhr.responseText); + this.type = Resource.TYPE.JSON; + } catch (e) { + this.abort('Error trying to parse loaded json: ' + e); + + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (window.DOMParser) { + var domparser = new DOMParser(); + + this.data = domparser.parseFromString(xhr.responseText, 'text/xml'); + } else { + var div = document.createElement('div'); + + div.innerHTML = xhr.responseText; + + this.data = div; + } + + this.type = Resource.TYPE.XML; + } catch (e) { + this.abort('Error trying to parse loaded xml: ' + e); + + return; + } + } + // other types just return the response + else { + this.data = xhr.response || xhr.responseText; + } + } else { + this.abort('[' + xhr.status + '] ' + xhr.statusText + ': ' + xhr.responseURL); + + return; + } + + this.complete(); + }; + + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * + * @private + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ + + + Resource.prototype._determineCrossOrigin = function _determineCrossOrigin(url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = (0, _parseUri2.default)(tempAnchor.href, { strictMode: true }); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + var protocol = url.protocol ? url.protocol + ':' : ''; + + // if cross origin + if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; + }; + + /** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. + */ + + + Resource.prototype._determineXhrType = function _determineXhrType() { + return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT; + }; + + /** + * Determines the loadType of a resource based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.LOAD_TYPE} The loadType to use. + */ + + + Resource.prototype._determineLoadType = function _determineLoadType() { + return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR; + }; + + /** + * Extracts the extension (sans '.') of the file being loaded by the resource. + * + * @private + * @return {string} The extension. + */ + + + Resource.prototype._getExtension = function _getExtension() { + var url = this.url; + var ext = ''; + + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } else { + var queryStart = url.indexOf('?'); + + if (queryStart !== -1) { + url = url.substring(0, queryStart); + } + + ext = url.substring(url.lastIndexOf('.') + 1); + } + + return ext.toLowerCase(); + }; + + /** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * + * @private + * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. + * @return {string} The mime type to use. + */ + + + Resource.prototype._getMimeFromXhrType = function _getMimeFromXhrType(type) { + switch (type) { + case Resource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + + case Resource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + + case Resource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + + case Resource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + + case Resource.XHR_RESPONSE_TYPE.DEFAULT: + case Resource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + + } + }; + + _createClass(Resource, [{ + key: 'isDataUrl', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL); + } + + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isComplete', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE); + } + + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isLoading', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.LOADING); + } + }]); + + return Resource; +}(); + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ + + +exports.default = Resource; +Resource.STATUS_FLAGS = { + NONE: 0, + DATA_URL: 1 << 0, + COMPLETE: 1 << 1, + LOADING: 1 << 2 +}; + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ +Resource.TYPE = { + UNKNOWN: 0, + JSON: 1, + XML: 2, + IMAGE: 3, + AUDIO: 4, + VIDEO: 5, + TEXT: 6 +}; + +/** + * The types of loading a resource can use. + * + * @static + * @readonly + * @enum {number} + */ +Resource.LOAD_TYPE = { + /** Uses XMLHttpRequest to load the resource. */ + XHR: 1, + /** Uses an `Image` object to load the resource. */ + IMAGE: 2, + /** Uses an `Audio` object to load the resource. */ + AUDIO: 3, + /** Uses a `Video` object to load the resource. */ + VIDEO: 4 +}; + +/** + * The XHR ready states, used internally. + * + * @static + * @readonly + * @enum {string} + */ +Resource.XHR_RESPONSE_TYPE = { + /** string */ + DEFAULT: 'text', + /** ArrayBuffer */ + BUFFER: 'arraybuffer', + /** Blob */ + BLOB: 'blob', + /** Document */ + DOCUMENT: 'document', + /** Object */ + JSON: 'json', + /** String */ + TEXT: 'text' +}; + +Resource._loadTypeMap = { + // images + gif: Resource.LOAD_TYPE.IMAGE, + png: Resource.LOAD_TYPE.IMAGE, + bmp: Resource.LOAD_TYPE.IMAGE, + jpg: Resource.LOAD_TYPE.IMAGE, + jpeg: Resource.LOAD_TYPE.IMAGE, + tif: Resource.LOAD_TYPE.IMAGE, + tiff: Resource.LOAD_TYPE.IMAGE, + webp: Resource.LOAD_TYPE.IMAGE, + tga: Resource.LOAD_TYPE.IMAGE, + svg: Resource.LOAD_TYPE.IMAGE, + 'svg+xml': Resource.LOAD_TYPE.IMAGE, // for SVG data urls + + // audio + mp3: Resource.LOAD_TYPE.AUDIO, + ogg: Resource.LOAD_TYPE.AUDIO, + wav: Resource.LOAD_TYPE.AUDIO, + + // videos + mp4: Resource.LOAD_TYPE.VIDEO, + webm: Resource.LOAD_TYPE.VIDEO +}; + +Resource._xhrTypeMap = { + // xml + xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. + // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, + // this should probably be fine. + tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // images + gif: Resource.XHR_RESPONSE_TYPE.BLOB, + png: Resource.XHR_RESPONSE_TYPE.BLOB, + bmp: Resource.XHR_RESPONSE_TYPE.BLOB, + jpg: Resource.XHR_RESPONSE_TYPE.BLOB, + jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, + tif: Resource.XHR_RESPONSE_TYPE.BLOB, + tiff: Resource.XHR_RESPONSE_TYPE.BLOB, + webp: Resource.XHR_RESPONSE_TYPE.BLOB, + tga: Resource.XHR_RESPONSE_TYPE.BLOB, + + // json + json: Resource.XHR_RESPONSE_TYPE.JSON, + + // text + text: Resource.XHR_RESPONSE_TYPE.TEXT, + txt: Resource.XHR_RESPONSE_TYPE.TEXT, + + // fonts + ttf: Resource.XHR_RESPONSE_TYPE.BUFFER, + otf: Resource.XHR_RESPONSE_TYPE.BUFFER +}; + +// We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif +Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; + +/** + * Quick helper to set a value on one of the extension maps. Ensures there is no + * dot at the start of the extension. + * + * @ignore + * @param {object} map - The map to set on. + * @param {string} extname - The extension (or key) to set. + * @param {number} val - The value to set. + */ +function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + + if (!extname) { + return; + } + + map[extname] = val; +} + +/** + * Quick helper to get string xhr type. + * + * @ignore + * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. + * @return {string} The type. + */ +function reqType(xhr) { + return xhr.toString().replace('object ', ''); +} + +},{"mini-signals":36,"parse-uri":37}],32:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.eachSeries = eachSeries; +exports.queue = queue; +/** + * Smaller version of the async library constructs. + * + */ +function _noop() {} /* empty */ + +/** + * Iterates an array in series. + * + * @param {*[]} array - Array to iterate. + * @param {function} iterator - Function to call for each element. + * @param {function} callback - Function to call when done, or on error. + */ +function eachSeries(array, iterator, callback) { + var i = 0; + var len = array.length; + + (function next(err) { + if (err || i === len) { + if (callback) { + callback(err); + } + + return; + } + + iterator(array[i++], next); + })(); +} + +/** + * Ensures a function is only called once. + * + * @param {function} fn - The function to wrap. + * @return {function} The wrapping function. + */ +function onlyOnce(fn) { + return function onceWrapper() { + if (fn === null) { + throw new Error('Callback was already called.'); + } + + var callFn = fn; + + fn = null; + callFn.apply(this, arguments); + }; +} + +/** + * Async queue implementation, + * + * @param {function} worker - The worker function to call for each task. + * @param {number} concurrency - How many workers to run in parrallel. + * @return {*} The async queue object. + */ +function queue(worker, concurrency) { + if (concurrency == null) { + // eslint-disable-line no-eq-null,eqeqeq + concurrency = 1; + } else if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + + var workers = 0; + var q = { + _tasks: [], + concurrency: concurrency, + saturated: _noop, + unsaturated: _noop, + buffer: concurrency / 4, + empty: _noop, + drain: _noop, + error: _noop, + started: false, + paused: false, + push: function push(data, callback) { + _insert(data, false, callback); + }, + kill: function kill() { + workers = 0; + q.drain = _noop; + q.started = false; + q._tasks = []; + }, + unshift: function unshift(data, callback) { + _insert(data, true, callback); + }, + process: function process() { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var task = q._tasks.shift(); + + if (q._tasks.length === 0) { + q.empty(); + } + + workers += 1; + + if (workers === q.concurrency) { + q.saturated(); + } + + worker(task.data, onlyOnce(_next(task))); + } + }, + length: function length() { + return q._tasks.length; + }, + running: function running() { + return workers; + }, + idle: function idle() { + return q._tasks.length + workers === 0; + }, + pause: function pause() { + if (q.paused === true) { + return; + } + + q.paused = true; + }, + resume: function resume() { + if (q.paused === false) { + return; + } + + q.paused = false; + + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= q.concurrency; w++) { + q.process(); + } + } + }; + + function _insert(data, insertAtFront, callback) { + if (callback != null && typeof callback !== 'function') { + // eslint-disable-line no-eq-null,eqeqeq + throw new Error('task callback must be a function'); + } + + q.started = true; + + if (data == null && q.idle()) { + // eslint-disable-line no-eq-null,eqeqeq + // call drain immediately if there are no tasks + setTimeout(function () { + return q.drain(); + }, 1); + + return; + } + + var item = { + data: data, + callback: typeof callback === 'function' ? callback : _noop + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + setTimeout(function () { + return q.process(); + }, 1); + } + + function _next(task) { + return function next() { + workers -= 1; + + task.callback.apply(task, arguments); + + if (arguments[0] != null) { + // eslint-disable-line no-eq-null,eqeqeq + q.error(arguments[0], task.data); + } + + if (workers <= q.concurrency - q.buffer) { + q.unsaturated(); + } + + if (q.idle()) { + q.drain(); + } + + q.process(); + }; + } + + return q; +} + +},{}],33:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.encodeBinary = encodeBinary; +var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +function encodeBinary(input) { + var output = ''; + var inx = 0; + + while (inx < input.length) { + // Fill byte buffer array + var bytebuffer = [0, 0, 0]; + var encodedCharIndexes = [0, 0, 0, 0]; + + for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } else { + bytebuffer[jnx] = 0; + } + } + + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4; + + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6; + + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + + // Determine whether padding happened, and adjust accordingly + var paddingBytes = inx - (input.length - 1); + + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + + default: + break; // No padding - proceed + } + + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) { + output += _keyStr.charAt(encodedCharIndexes[_jnx]); + } + } + + return output; +} + +},{}],34:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Loader = require('./Loader'); + +var _Loader2 = _interopRequireDefault(_Loader); + +var _Resource = require('./Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +var _async = require('./async'); + +var async = _interopRequireWildcard(_async); + +var _b = require('./b64'); + +var b64 = _interopRequireWildcard(_b); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +_Loader2.default.Resource = _Resource2.default; +_Loader2.default.async = async; +_Loader2.default.base64 = b64; + +// export manually, and also as default +module.exports = _Loader2.default; // eslint-disable-line no-undef +exports.default = _Loader2.default; + +},{"./Loader":30,"./Resource":31,"./async":32,"./b64":33}],35:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +exports.blobMiddlewareFactory = blobMiddlewareFactory; + +var _Resource = require('../../Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +var _b = require('../../b64'); + +var _b2 = _interopRequireDefault(_b); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Url = window.URL || window.webkitURL; + +// a middleware for transforming XHR loaded Blobs into more useful objects +function blobMiddlewareFactory() { + return function blobMiddleware(resource, next) { + if (!resource.data) { + next(); + + return; + } + + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === _Resource2.default.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!window.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = 'data:' + type + ';base64,' + _b2.default.encodeBinary(resource.xhr.responseText); + + resource.type = _Resource2.default.TYPE.IMAGE; + + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + + next(); + }; + + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var _ret = function () { + var src = Url.createObjectURL(resource.data); + + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src; + + resource.type = _Resource2.default.TYPE.IMAGE; + + // cleanup the no longer used blob after the image loads + // TODO: Is this correct? Will the image be invalid after revoking? + resource.data.onload = function () { + Url.revokeObjectURL(src); + resource.data.onload = null; + + next(); + }; + + // next will be called on load. + return { + v: void 0 + }; + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + } + + next(); + }; +} + +},{"../../Resource":31,"../../b64":33}],36:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + +var MiniSignalBinding = (function () { + function MiniSignalBinding(fn, once, thisArg) { + if (once === undefined) once = false; + + _classCallCheck(this, MiniSignalBinding); + + this._fn = fn; + this._once = once; + this._thisArg = thisArg; + this._next = this._prev = this._owner = null; + } + + _createClass(MiniSignalBinding, [{ + key: 'detach', + value: function detach() { + if (this._owner === null) return false; + this._owner.detach(this); + return true; + } + }]); + + return MiniSignalBinding; +})(); + +function _addMiniSignalBinding(self, node) { + if (!self._head) { + self._head = node; + self._tail = node; + } else { + self._tail._next = node; + node._prev = self._tail; + self._tail = node; + } + + node._owner = self; + + return node; +} + +var MiniSignal = (function () { + function MiniSignal() { + _classCallCheck(this, MiniSignal); + + this._head = this._tail = undefined; + } + + _createClass(MiniSignal, [{ + key: 'handlers', + value: function handlers() { + var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; + + var node = this._head; + + if (exists) return !!node; + + var ee = []; + + while (node) { + ee.push(node); + node = node._next; + } + + return ee; + } + }, { + key: 'has', + value: function has(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.'); + } + + return node._owner === this; + } + }, { + key: 'dispatch', + value: function dispatch() { + var node = this._head; + + if (!node) return false; + + while (node) { + if (node._once) this.detach(node); + node._fn.apply(node._thisArg, arguments); + node = node._next; + } + + return true; + } + }, { + key: 'add', + value: function add(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#add(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg)); + } + }, { + key: 'once', + value: function once(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#once(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg)); + } + }, { + key: 'detach', + value: function detach(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.'); + } + if (node._owner !== this) return this; + + if (node._prev) node._prev._next = node._next; + if (node._next) node._next._prev = node._prev; + + if (node === this._head) { + this._head = node._next; + if (node._next === null) { + this._tail = null; + } + } else if (node === this._tail) { + this._tail = node._prev; + this._tail._next = null; + } + + node._owner = null; + return this; + } + }, { + key: 'detachAll', + value: function detachAll() { + var node = this._head; + if (!node) return this; + + this._head = this._tail = null; + + while (node) { + node._owner = null; + node = node._next; + } + return this; + } + }]); + + return MiniSignal; +})(); + +MiniSignal.MiniSignalBinding = MiniSignalBinding; + +exports['default'] = MiniSignal; +module.exports = exports['default']; + +},{}],37:[function(require,module,exports){ +'use strict' + +module.exports = function parseURI (str, opts) { + opts = opts || {} + + var o = { + key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], + q: { + name: 'queryKey', + parser: /(?:^|&)([^&=]*)=?([^&]*)/g + }, + parser: { + strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, + loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ + } + } + + var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str) + var uri = {} + var i = 14 + + while (i--) uri[o.key[i]] = m[i] || '' + + uri[o.q.name] = {} + uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { + if ($1) uri[o.q.name][$1] = $2 + }) + + return uri +} + +},{}],38:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +var _accessibleTarget = require('./accessibleTarget'); + +var _accessibleTarget2 = _interopRequireDefault(_accessibleTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// add some extra variables to the container.. +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _accessibleTarget2.default); + +var KEY_CODE_TAB = 9; + +var DIV_TOUCH_SIZE = 100; +var DIV_TOUCH_POS_X = 0; +var DIV_TOUCH_POS_Y = 0; +var DIV_TOUCH_ZINDEX = 2; + +var DIV_HOOK_SIZE = 1; +var DIV_HOOK_POS_X = -1000; +var DIV_HOOK_POS_Y = -1000; +var DIV_HOOK_ZINDEX = 2; + +/** + * The Accessibility manager reacreates the ability to tab and and have content read by screen + * readers. This is very important as it can possibly help people with disabilities access pixi + * content. + * + * Much like interaction any DisplayObject can be made accessible. This manager will map the + * events as if the mouse was being used, minimizing the efferot required to implement. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.accessibility + * + * @class + * @memberof PIXI.accessibility + */ + +var AccessibilityManager = function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + _classCallCheck(this, AccessibilityManager); + + if ((_ismobilejs2.default.tablet || _ismobilejs2.default.phone) && !navigator.isCocoonJS) { + this.createTouchHook(); + } + + // first we create a div that will sit over the pixi element. This is where the div overlays will go. + var div = document.createElement('div'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + 'px'; + div.style.left = DIV_TOUCH_POS_Y + 'px'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + + /** + * This is the dom element that will sit over the pixi element. This is where the div overlays will go. + * + * @type {HTMLElement} + * @private + */ + this.div = div; + + /** + * A simple pool for storing divs. + * + * @type {*} + * @private + */ + this.pool = []; + + /** + * This is a tick used to check if an object is no longer being rendered. + * + * @type {Number} + * @private + */ + this.renderId = 0; + + /** + * Setting this to true will visually show the divs + * + * @type {boolean} + */ + this.debug = false; + + /** + * The renderer this accessibility manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * The array of currently active accessible items. + * + * @member {Array<*>} + * @private + */ + this.children = []; + + /** + * pre-bind the functions + * + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + + /** + * stores the state of the manager. If there are no accessible objects or the mouse is moving the will be false. + * + * @member {Array<*>} + * @private + */ + this.isActive = false; + this.isMobileAccessabillity = false; + + // let listen for tab.. once pressed we can fire up and show the accessibility layer + window.addEventListener('keydown', this._onKeyDown, false); + } + + /** + * Creates the touch hooks. + * + */ + + + AccessibilityManager.prototype.createTouchHook = function createTouchHook() { + var _this = this; + + var hookDiv = document.createElement('button'); + + hookDiv.style.width = DIV_HOOK_SIZE + 'px'; + hookDiv.style.height = DIV_HOOK_SIZE + 'px'; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + 'px'; + hookDiv.style.left = DIV_HOOK_POS_Y + 'px'; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX; + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'HOOK DIV'; + + hookDiv.addEventListener('focus', function () { + _this.isMobileAccessabillity = true; + _this.activate(); + document.body.removeChild(hookDiv); + }); + + document.body.appendChild(hookDiv); + }; + + /** + * Activating will cause the Accessibility layer to be shown. This is called when a user + * preses the tab key + * + * @private + */ + + + AccessibilityManager.prototype.activate = function activate() { + if (this.isActive) { + return; + } + + this.isActive = true; + + window.document.addEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown, false); + + this.renderer.on('postrender', this.update, this); + + if (this.renderer.view.parentNode) { + this.renderer.view.parentNode.appendChild(this.div); + } + }; + + /** + * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves + * the mouse + * + * @private + */ + + + AccessibilityManager.prototype.deactivate = function deactivate() { + if (!this.isActive || this.isMobileAccessabillity) { + return; + } + + this.isActive = false; + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.addEventListener('keydown', this._onKeyDown, false); + + this.renderer.off('postrender', this.update); + + if (this.div.parentNode) { + this.div.parentNode.removeChild(this.div); + } + }; + + /** + * This recursive function will run throught he scene graph and add any new accessible objects to the DOM layer. + * + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + + + AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects(displayObject) { + if (!displayObject.visible) { + return; + } + + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + + displayObject.renderId = this.renderId; + } + + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + this.updateAccessibleObjects(children[i]); + } + }; + + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * + * @private + */ + + + AccessibilityManager.prototype.update = function update() { + if (!this.renderer.renderingToScreen) { + return; + } + + // update children... + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + + var rect = this.renderer.view.getBoundingClientRect(); + var sx = rect.width / this.renderer.width; + var sy = rect.height / this.renderer.height; + + var div = this.div; + + div.style.left = rect.left + 'px'; + div.style.top = rect.top + 'px'; + div.style.width = this.renderer.width + 'px'; + div.style.height = this.renderer.height + 'px'; + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + + core.utils.removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + + i--; + + if (this.children.length === 0) { + this.deactivate(); + } + } else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + + if (child.hitArea) { + div.style.left = (wt.tx + hitArea.x * wt.a) * sx + 'px'; + div.style.top = (wt.ty + hitArea.y * wt.d) * sy + 'px'; + + div.style.width = hitArea.width * wt.a * sx + 'px'; + div.style.height = hitArea.height * wt.d * sy + 'px'; + } else { + hitArea = child.getBounds(); + + this.capHitArea(hitArea); + + div.style.left = hitArea.x * sx + 'px'; + div.style.top = hitArea.y * sy + 'px'; + + div.style.width = hitArea.width * sx + 'px'; + div.style.height = hitArea.height * sy + 'px'; + } + } + } + + // increment the render id.. + this.renderId++; + }; + + /** + * TODO: docs. + * + * @param {Rectangle} hitArea - TODO docs + */ + + + AccessibilityManager.prototype.capHitArea = function capHitArea(hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + + if (hitArea.x + hitArea.width > this.renderer.width) { + hitArea.width = this.renderer.width - hitArea.x; + } + + if (hitArea.y + hitArea.height > this.renderer.height) { + hitArea.height = this.renderer.height - hitArea.y; + } + }; + + /** + * Adds a DisplayObject to the accessibility manager + * + * @private + * @param {DisplayObject} displayObject - The child to make accessible. + */ + + + AccessibilityManager.prototype.addChild = function addChild(displayObject) { + // this.activate(); + + var div = this.pool.pop(); + + if (!div) { + div = document.createElement('button'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + div.style.borderStyle = 'none'; + + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + + if (displayObject.accessibleTitle) { + div.title = displayObject.accessibleTitle; + } else if (!displayObject.accessibleTitle && !displayObject.accessibleHint) { + div.title = 'displayObject ' + this.tabIndex; + } + + if (displayObject.accessibleHint) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + + // + + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + + /** + * Maps the div button press to pixi's InteractionManager (click) + * + * @private + * @param {MouseEvent} e - The click event. + */ + + + AccessibilityManager.prototype._onClick = function _onClick(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixis InteractionManager (mouseover) + * + * @private + * @param {FocusEvent} e - The focus event. + */ + + + AccessibilityManager.prototype._onFocus = function _onFocus(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixis InteractionManager (mouseout) + * + * @private + * @param {FocusEvent} e - The focusout event. + */ + + + AccessibilityManager.prototype._onFocusOut = function _onFocusOut(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); + }; + + /** + * Is called when a key is pressed + * + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + + + AccessibilityManager.prototype._onKeyDown = function _onKeyDown(e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + + this.activate(); + }; + + /** + * Is called when the mouse moves across the renderer element + * + * @private + */ + + + AccessibilityManager.prototype._onMouseMove = function _onMouseMove() { + this.deactivate(); + }; + + /** + * Destroys the accessibility manager + * + */ + + + AccessibilityManager.prototype.destroy = function destroy() { + this.div = null; + + for (var i = 0; i < this.children.length; i++) { + this.children[i].div = null; + } + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.removeEventListener('keydown', this._onKeyDown); + + this.pool = null; + this.children = null; + this.renderer = null; + }; + + return AccessibilityManager; +}(); + +exports.default = AccessibilityManager; + + +core.WebGLRenderer.registerPlugin('accessibility', AccessibilityManager); +core.CanvasRenderer.registerPlugin('accessibility', AccessibilityManager); + +},{"../core":63,"./accessibleTarget":39,"ismobilejs":4}],39:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Default property values of accessible objects + * used by {@link PIXI.accessibility.AccessibilityManager}. + * + * @function accessibleTarget + * @memberof PIXI.accessibility + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibility.accessibleTarget + * ); + */ +exports.default = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * + * @member {boolean} + */ + accessible: false, + + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * + * @member {string} + */ + accessibleTitle: null, + + /** + * Sets the aria-label attribute of the shadow div + * + * @member {string} + */ + accessibleHint: null, + + /** + * @todo Needs docs. + */ + tabIndex: 0, + + /** + * @todo Needs docs. + */ + _accessibleActive: false, + + /** + * @todo Needs docs. + */ + _accessibleDiv: false +}; + +},{}],40:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _accessibleTarget = require('./accessibleTarget'); + +Object.defineProperty(exports, 'accessibleTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_accessibleTarget).default; + } +}); + +var _AccessibilityManager = require('./AccessibilityManager'); + +Object.defineProperty(exports, 'AccessibilityManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AccessibilityManager).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./AccessibilityManager":38,"./accessibleTarget":39}],41:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +var _Container = require('./display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _ticker = require('./ticker'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Convenience class to create a new PIXI application. + * This class automatically creates the renderer, ticker + * and root container. + * + * @example + * // Create the application + * const app = new PIXI.Application(); + * + * // Add the view to the DOM + * document.body.appendChild(app.view); + * + * // ex, add display objects + * app.stage.addChild(PIXI.Sprite.fromImage('something.png')); + * + * @class + * @memberof PIXI + */ +var Application = function () { + /** + * @param {number} [width=800] - the width of the renderers view + * @param {number} [height=600] - the height of the renderers view + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [noWebGL=false] - prevents selection of WebGL renderer, even if such is present + * @param {boolean} [options.legacy=false] - If true Pixi will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering try setting this to true. + * @param {boolean} [useSharedTicker=false] - `true` to use PIXI.ticker.shared, `false` to create new ticker. + */ + function Application(width, height, options, noWebGL) { + var useSharedTicker = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; + + _classCallCheck(this, Application); + + /** + * WebGL renderer if available, otherwise CanvasRenderer + * @member {PIXI.WebGLRenderer|PIXI.CanvasRenderer} + */ + this.renderer = (0, _autoDetectRenderer.autoDetectRenderer)(width, height, options, noWebGL); + + /** + * The root display container that's rendered. + * @member {PIXI.Container} + */ + this.stage = new _Container2.default(); + + /** + * Internal reference to the ticker + * @member {PIXI.ticker.Ticker} + * @private + */ + this._ticker = null; + + /** + * Ticker for doing render updates. + * @member {PIXI.ticker.Ticker} + * @default PIXI.ticker.shared + */ + this.ticker = useSharedTicker ? _ticker.shared : new _ticker.Ticker(); + + // Start the rendering + this.start(); + } + + /** + * Render the current stage. + */ + Application.prototype.render = function render() { + this.renderer.render(this.stage); + }; + + /** + * Convenience method for stopping the render. + */ + + + Application.prototype.stop = function stop() { + this._ticker.stop(); + }; + + /** + * Convenience method for starting the render. + */ + + + Application.prototype.start = function start() { + this._ticker.start(); + }; + + /** + * Reference to the renderer's canvas element. + * @member {HTMLCanvasElement} + * @readonly + */ + + + /** + * Destroy and don't use after this. + * @param {Boolean} [removeView=false] Automatically remove canvas from DOM. + */ + Application.prototype.destroy = function destroy(removeView) { + this.stop(); + this.ticker = null; + + this.stage.destroy(); + this.stage = null; + + this.renderer.destroy(removeView); + this.renderer = null; + }; + + _createClass(Application, [{ + key: 'ticker', + set: function set(ticker) // eslint-disable-line require-jsdoc + { + if (this._ticker) { + this._ticker.remove(this.render, this); + } + this._ticker = ticker; + if (ticker) { + ticker.add(this.render, this); + } + }, + get: function get() // eslint-disable-line require-jsdoc + { + return this._ticker; + } + }, { + key: 'view', + get: function get() { + return this.renderer.view; + } + + /** + * Reference to the renderer's screen rectangle. Its safe to use as filterArea or hitArea for whole screen + * @member {PIXI.Rectangle} + * @readonly + */ + + }, { + key: 'screen', + get: function get() { + return this.renderer.screen; + } + }]); + + return Application; +}(); + +exports.default = Application; + +},{"./autoDetectRenderer":43,"./display/Container":46,"./ticker":116}],42:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var PRECISION = _settings2.default.PRECISION; + + +function checkPrecision(src) { + if (src instanceof Array) { + if (src[0].substring(0, 9) !== 'precision') { + var copy = src.slice(0); + + copy.unshift('precision ' + PRECISION + ' float;'); + + return copy; + } + } else if (src.substring(0, 9) !== 'precision') { + return 'precision ' + PRECISION + ' float;\n' + src; + } + + return src; +} + +/** + * Wrapper class, webGL Shader for Pixi. + * Adds precision string if vertexSrc or fragmentSrc have no mention of it. + * + * @class + * @extends GLShader + * @memberof PIXI + */ + +var Shader = function (_GLShader) { + _inherits(Shader, _GLShader); + + /** + * + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + * @param {string|string[]} vertexSrc - The vertex shader source as an array of strings. + * @param {string|string[]} fragmentSrc - The fragment shader source as an array of strings. + */ + function Shader(gl, vertexSrc, fragmentSrc) { + _classCallCheck(this, Shader); + + return _possibleConstructorReturn(this, _GLShader.call(this, gl, checkPrecision(vertexSrc), checkPrecision(fragmentSrc))); + } + + return Shader; +}(_pixiGlCore.GLShader); + +exports.default = Shader; + +},{"./settings":99,"pixi-gl-core":12}],43:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = autoDetectRenderer; + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by + * the browser then this function will return a canvas renderer + * + * @memberof PIXI + * @function autoDetectRenderer + * @param {number} [width=800] - the width of the renderers view + * @param {number} [height=600] - the height of the renderers view + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [noWebGL=false] - prevents selection of WebGL renderer, even if such is present + * @return {PIXI.WebGLRenderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ +function autoDetectRenderer() { + var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 800; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 600; + var options = arguments[2]; + var noWebGL = arguments[3]; + + if (!noWebGL && utils.isWebGLSupported()) { + return new _WebGLRenderer2.default(width, height, options); + } + + return new _CanvasRenderer2.default(width, height, options); +} + +},{"./renderers/canvas/CanvasRenderer":75,"./renderers/webgl/WebGLRenderer":82,"./utils":120}],44:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * String of the current PIXI version. + * + * @static + * @constant + * @memberof PIXI + * @name VERSION + * @type {string} + */ +var VERSION = exports.VERSION = '4.3.5'; + +/** + * Two Pi. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var PI_2 = exports.PI_2 = Math.PI * 2; + +/** + * Conversion factor for converting radians to degrees. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var RAD_TO_DEG = exports.RAD_TO_DEG = 180 / Math.PI; + +/** + * Conversion factor for converting degrees to radians. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var DEG_TO_RAD = exports.DEG_TO_RAD = Math.PI / 180; + +/** + * Constant to identify the Renderer Type. + * + * @static + * @constant + * @memberof PIXI + * @name RENDERER_TYPE + * @type {object} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ +var RENDERER_TYPE = exports.RENDERER_TYPE = { + UNKNOWN: 0, + WEBGL: 1, + CANVAS: 2 +}; + +/** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * + * @static + * @constant + * @memberof PIXI + * @name BLEND_MODES + * @type {object} + * @property {number} NORMAL + * @property {number} ADD + * @property {number} MULTIPLY + * @property {number} SCREEN + * @property {number} OVERLAY + * @property {number} DARKEN + * @property {number} LIGHTEN + * @property {number} COLOR_DODGE + * @property {number} COLOR_BURN + * @property {number} HARD_LIGHT + * @property {number} SOFT_LIGHT + * @property {number} DIFFERENCE + * @property {number} EXCLUSION + * @property {number} HUE + * @property {number} SATURATION + * @property {number} COLOR + * @property {number} LUMINOSITY + */ +var BLEND_MODES = exports.BLEND_MODES = { + NORMAL: 0, + ADD: 1, + MULTIPLY: 2, + SCREEN: 3, + OVERLAY: 4, + DARKEN: 5, + LIGHTEN: 6, + COLOR_DODGE: 7, + COLOR_BURN: 8, + HARD_LIGHT: 9, + SOFT_LIGHT: 10, + DIFFERENCE: 11, + EXCLUSION: 12, + HUE: 13, + SATURATION: 14, + COLOR: 15, + LUMINOSITY: 16 +}; + +/** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * + * @static + * @constant + * @memberof PIXI + * @name DRAW_MODES + * @type {object} + * @property {number} POINTS + * @property {number} LINES + * @property {number} LINE_LOOP + * @property {number} LINE_STRIP + * @property {number} TRIANGLES + * @property {number} TRIANGLE_STRIP + * @property {number} TRIANGLE_FAN + */ +var DRAW_MODES = exports.DRAW_MODES = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6 +}; + +/** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @static + * @constant + * @memberof PIXI + * @name SCALE_MODES + * @type {object} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ +var SCALE_MODES = exports.SCALE_MODES = { + LINEAR: 0, + NEAREST: 1 +}; + +/** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wraping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as webGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * + * @static + * @constant + * @name WRAP_MODES + * @memberof PIXI + * @type {object} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ +var WRAP_MODES = exports.WRAP_MODES = { + CLAMP: 0, + REPEAT: 1, + MIRRORED_REPEAT: 2 +}; + +/** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for pixi textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * + * @static + * @constant + * @name GC_MODES + * @memberof PIXI + * @type {object} + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ +var GC_MODES = exports.GC_MODES = { + AUTO: 0, + MANUAL: 1 +}; + +/** + * Regexp for image type by extension. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `image.png` + */ +var URL_FILE_EXTENSION = exports.URL_FILE_EXTENSION = /\.(\w{3,4})(?:$|\?|#)/i; + +/** + * Regexp for data URI. + * Based on: {@link https://github.com/ragingwind/data-uri-regex} + * + * @static + * @constant + * @name DATA_URI + * @memberof PIXI + * @type {RegExp|string} + * @example data:image/png;base64 + */ +var DATA_URI = exports.DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;(charset=[\w-]+|base64))?,(.*)/i; + +/** + * Regexp for SVG size. + * + * @static + * @constant + * @name SVG_SIZE + * @memberof PIXI + * @type {RegExp|string} + * @example <svg width="100" height="100"></svg> + */ +var SVG_SIZE = exports.SVG_SIZE = /]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len + +/** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * + * @static + * @constant + * @name SHAPES + * @memberof PIXI + * @type {object} + * @property {number} POLY Polygon + * @property {number} RECT Rectangle + * @property {number} CIRC Circle + * @property {number} ELIP Ellipse + * @property {number} RREC Rounded Rectangle + */ +var SHAPES = exports.SHAPES = { + POLY: 0, + RECT: 1, + CIRC: 2, + ELIP: 3, + RREC: 4 +}; + +/** + * Constants that specify float precision in shaders. + * + * @static + * @constant + * @name PRECISION + * @memberof PIXI + * @type {object} + * @property {string} LOW='lowp' + * @property {string} MEDIUM='mediump' + * @property {string} HIGH='highp' + */ +var PRECISION = exports.PRECISION = { + LOW: 'lowp', + MEDIUM: 'mediump', + HIGH: 'highp' +}; + +/** + * Constants that specify the transform type. + * + * @static + * @constant + * @name TRANSFORM_MODE + * @memberof PIXI + * @type {object} + * @property {number} STATIC + * @property {number} DYNAMIC + */ +var TRANSFORM_MODE = exports.TRANSFORM_MODE = { + STATIC: 0, + DYNAMIC: 1 +}; + +/** + * Constants that define the type of gradient on text. + * + * @static + * @constant + * @name TEXT_GRADIENT + * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL Vertical gradient + * @property {number} LINEAR_HORIZONTAL Linear gradient + */ +var TEXT_GRADIENT = exports.TEXT_GRADIENT = { + LINEAR_VERTICAL: 0, + LINEAR_HORIZONTAL: 1 +}; + +},{}],45:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * 'Builder' pattern for bounds rectangles + * Axis-Aligned Bounding Box + * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems + * + * @class + * @memberof PIXI + */ +var Bounds = function () { + /** + * + */ + function Bounds() { + _classCallCheck(this, Bounds); + + /** + * @member {number} + * @default 0 + */ + this.minX = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.minY = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxX = -Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxY = -Infinity; + + this.rect = null; + } + + /** + * Checks if bounds are empty. + * + * @return {boolean} True if empty. + */ + + + Bounds.prototype.isEmpty = function isEmpty() { + return this.minX > this.maxX || this.minY > this.maxY; + }; + + /** + * Clears the bounds and resets. + * + */ + + + Bounds.prototype.clear = function clear() { + this.updateID++; + + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * + * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty + * @returns {PIXI.Rectangle} A rectangle of the bounds + */ + + + Bounds.prototype.getRectangle = function getRectangle(rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return _math.Rectangle.EMPTY; + } + + rect = rect || new _math.Rectangle(0, 0, 1, 1); + + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + + return rect; + }; + + /** + * This function should be inlined when its possible. + * + * @param {PIXI.Point} point - The point to add. + */ + + + Bounds.prototype.addPoint = function addPoint(point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + }; + + /** + * Adds a quad, not transformed + * + * @param {Float32Array} vertices - The verts to add. + */ + + + Bounds.prototype.addQuad = function addQuad(vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = vertices[0]; + var y = vertices[1]; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds sprite frame, transformed. + * + * @param {PIXI.TransformBase} transform - TODO + * @param {number} x0 - TODO + * @param {number} y0 - TODO + * @param {number} x1 - TODO + * @param {number} y1 - TODO + */ + + + Bounds.prototype.addFrame = function addFrame(transform, x0, y0, x1, y1) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = a * x0 + c * y0 + tx; + var y = b * x0 + d * y0 + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y0 + tx; + y = b * x1 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x0 + c * y1 + tx; + y = b * x0 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y1 + tx; + y = b * x1 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Add an array of vertices + * + * @param {PIXI.TransformBase} transform - TODO + * @param {Float32Array} vertices - TODO + * @param {number} beginOffset - TODO + * @param {number} endOffset - TODO + */ + + + Bounds.prototype.addVertices = function addVertices(transform, vertices, beginOffset, endOffset) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = a * rawX + c * rawY + tx; + var y = d * rawY + b * rawX + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds other Bounds + * + * @param {PIXI.Bounds} bounds - TODO + */ + + + Bounds.prototype.addBounds = function addBounds(bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + }; + + /** + * Adds other Bounds, masked with Bounds + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Bounds} mask - TODO + */ + + + Bounds.prototype.addBoundsMask = function addBoundsMask(bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + /** + * Adds other Bounds, masked with Rectangle + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Rectangle} area - TODO + */ + + + Bounds.prototype.addBoundsArea = function addBoundsArea(bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : area.x + area.width; + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : area.y + area.height; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + return Bounds; +}(); + +exports.default = Bounds; + +},{"../math":68}],46:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _DisplayObject2 = require('./DisplayObject'); + +var _DisplayObject3 = _interopRequireDefault(_DisplayObject2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A Container represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + *```js + * let container = new PIXI.Container(); + * container.addChild(sprite); + * ``` + * + * @class + * @extends PIXI.DisplayObject + * @memberof PIXI + */ +var Container = function (_DisplayObject) { + _inherits(Container, _DisplayObject); + + /** + * + */ + function Container() { + _classCallCheck(this, Container); + + /** + * The array of children of this container. + * + * @member {PIXI.DisplayObject[]} + * @readonly + */ + var _this = _possibleConstructorReturn(this, _DisplayObject.call(this)); + + _this.children = []; + return _this; + } + + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified + * + * @private + */ + + + Container.prototype.onChildrenChange = function onChildrenChange() {} + /* empty */ + + + /** + * Adds one or more children to the container. + * + * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container + * @return {PIXI.DisplayObject} The first child that was added. + */ + ; + + Container.prototype.addChild = function addChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.addChild(arguments[i]); + } + } else { + // if the child has a parent then lets remove it as Pixi objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.push(child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + child.emit('added', this); + } + + return child; + }; + + /** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @return {PIXI.DisplayObject} The child that was added. + */ + + + Container.prototype.addChildAt = function addChildAt(child, index) { + if (index < 0 || index > this.children.length) { + throw new Error(child + 'addChildAt: The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.splice(index, 0, child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + + return child; + }; + + /** + * Swaps the position of 2 Display Objects within this container. + * + * @param {PIXI.DisplayObject} child - First display object to swap + * @param {PIXI.DisplayObject} child2 - Second display object to swap + */ + + + Container.prototype.swapChildren = function swapChildren(child, child2) { + if (child === child2) { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; + + /** + * Returns the index position of a child DisplayObject instance + * + * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify + * @return {number} The index position of the child display object to identify + */ + + + Container.prototype.getChildIndex = function getChildIndex(child) { + var index = this.children.indexOf(child); + + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + }; + + /** + * Changes the position of an existing child in the display object container + * + * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number + * @param {number} index - The resulting index number for the child display object + */ + + + Container.prototype.setChildIndex = function setChildIndex(child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + (0, _utils.removeItems)(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + + this.onChildrenChange(index); + }; + + /** + * Returns the child at the specified index + * + * @param {number} index - The index to get the child at + * @return {PIXI.DisplayObject} The child at the given index, if any. + */ + + + Container.prototype.getChildAt = function getChildAt(index) { + if (index < 0 || index >= this.children.length) { + throw new Error('getChildAt: Index (' + index + ') does not exist.'); + } + + return this.children[index]; + }; + + /** + * Removes one or more children from the container. + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove + * @return {PIXI.DisplayObject} The first child that was removed. + */ + + + Container.prototype.removeChild = function removeChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.removeChild(arguments[i]); + } + } else { + var index = this.children.indexOf(child); + + if (index === -1) return null; + + child.parent = null; + // ensure child transform will be recalculated + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + } + + return child; + }; + + /** + * Removes a child from the specified index position. + * + * @param {number} index - The index to get the child from + * @return {PIXI.DisplayObject} The child that was removed. + */ + + + Container.prototype.removeChildAt = function removeChildAt(index) { + var child = this.getChildAt(index); + + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + + return child; + }; + + /** + * Removes all children from this container that are within the begin and end indexes. + * + * @param {number} [beginIndex=0] - The beginning position. + * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. + * @returns {DisplayObject[]} List of removed children + */ + + + Container.prototype.removeChildren = function removeChildren() { + var beginIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var endIndex = arguments[1]; + + var begin = beginIndex; + var end = typeof endIndex === 'number' ? endIndex : this.children.length; + var range = end - begin; + var removed = void 0; + + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } + + this._boundsID++; + + this.onChildrenChange(beginIndex); + + for (var _i = 0; _i < removed.length; ++_i) { + removed[_i].emit('removed', this); + } + + return removed; + } else if (range === 0 && this.children.length === 0) { + return []; + } + + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + }; + + /** + * Updates the transform on all children of this container for rendering + */ + + + Container.prototype.updateTransform = function updateTransform() { + this._boundsID++; + + this.transform.updateTransform(this.parent.transform); + + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + + if (child.visible) { + child.updateTransform(); + } + } + }; + + /** + * Recalculates the bounds of the container. + * + */ + + + Container.prototype.calculateBounds = function calculateBounds() { + this._bounds.clear(); + + this._calculateBounds(); + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (!child.visible || !child.renderable) { + continue; + } + + child.calculateBounds(); + + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + child._mask.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, child._mask._bounds); + } else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } else { + this._bounds.addBounds(child._bounds); + } + } + + this._lastBoundsID = this._boundsID; + }; + + /** + * Recalculates the bounds of the object. Override this to + * calculate the bounds of the specific object (not including children). + * + */ + + + Container.prototype._calculateBounds = function _calculateBounds() {} + // FILL IN// + + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderWebGL = function renderWebGL(renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + // do a quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) { + this.renderAdvancedWebGL(renderer); + } else { + this._renderWebGL(renderer); + + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderWebGL(renderer); + } + } + }; + + /** + * Render the object using the WebGL renderer and advanced features. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { + renderer.flush(); + + var filters = this._filters; + var mask = this._mask; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + + this._enabledFilters.length = 0; + + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + + if (this._enabledFilters.length) { + renderer.filterManager.pushFilter(this, this._enabledFilters); + } + } + + if (mask) { + renderer.maskManager.pushMask(this, this._mask); + } + + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); + + // now loop through the children and make sure they get rendered + for (var _i2 = 0, j = this.children.length; _i2 < j; _i2++) { + this.children[_i2].renderWebGL(renderer); + } + + renderer.flush(); + + if (mask) { + renderer.maskManager.popMask(this, this._mask); + } + + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filterManager.popFilter(); + } + }; + + /** + * To be overridden by the subclasses. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype._renderWebGL = function _renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * To be overridden by the subclass + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype._renderCanvas = function _renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderCanvas = function renderCanvas(renderer) { + // if not visible or the alpha is 0 then no need to render this + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + if (this._mask) { + renderer.maskManager.pushMask(this._mask); + } + + this._renderCanvas(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderCanvas(renderer); + } + + if (this._mask) { + renderer.maskManager.popMask(renderer); + } + }; + + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Container.prototype.destroy = function destroy(options) { + _DisplayObject.prototype.destroy.call(this); + + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + + var oldChildren = this.removeChildren(0, this.children.length); + + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + }; + + /** + * The width of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Container, [{ + key: 'width', + get: function get() { + return this.scale.x * this.getLocalBounds().width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var width = this.getLocalBounds().width; + + if (width !== 0) { + this.scale.x = value / width; + } else { + this.scale.x = 1; + } + + this._width = value; + } + + /** + * The height of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.scale.y * this.getLocalBounds().height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var height = this.getLocalBounds().height; + + if (height !== 0) { + this.scale.y = value / height; + } else { + this.scale.y = 1; + } + + this._height = value; + } + }]); + + return Container; +}(_DisplayObject3.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = Container; +Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + +},{"../utils":120,"./DisplayObject":47}],47:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TransformStatic = require('./TransformStatic'); + +var _TransformStatic2 = _interopRequireDefault(_TransformStatic); + +var _Transform = require('./Transform'); + +var _Transform2 = _interopRequireDefault(_Transform); + +var _Bounds = require('./Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _math = require('../math'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// _tempDisplayObjectParent = new DisplayObject(); + +/** + * The base class for all objects that are rendered on the screen. + * This is an abstract class and should not be used on its own rather it should be extended. + * + * @class + * @extends EventEmitter + * @mixes PIXI.interaction.interactiveTarget + * @memberof PIXI + */ +var DisplayObject = function (_EventEmitter) { + _inherits(DisplayObject, _EventEmitter); + + /** + * + */ + function DisplayObject() { + _classCallCheck(this, DisplayObject); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + var TransformClass = _settings2.default.TRANSFORM_MODE === _const.TRANSFORM_MODE.STATIC ? _TransformStatic2.default : _Transform2.default; + + _this.tempDisplayObjectParent = null; + + // TODO: need to create Transform from factory + /** + * World transform and local transform of this object. + * This will become read-only later, please do not assign anything there unless you know what are you doing + * + * @member {PIXI.TransformBase} + */ + _this.transform = new TransformClass(); + + /** + * The opacity of the object. + * + * @member {number} + */ + _this.alpha = 1; + + /** + * The visibility of the object. If false the object will not be drawn, and + * the updateTransform function will not be called. + * + * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually + * + * @member {boolean} + */ + _this.visible = true; + + /** + * Can this object be rendered, if false the object will not be drawn but the updateTransform + * methods will still be called. + * + * Only affects recursive calls from parent. You can ask for bounds manually + * + * @member {boolean} + */ + _this.renderable = true; + + /** + * The display object container that contains this display object. + * + * @member {PIXI.Container} + * @readonly + */ + _this.parent = null; + + /** + * The multiplied alpha of the displayObject + * + * @member {number} + * @readonly + */ + _this.worldAlpha = 1; + + /** + * The area the filter is applied to. This is used as more of an optimisation + * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle + * + * Also works as an interaction mask + * + * @member {PIXI.Rectangle} + */ + _this.filterArea = null; + + _this._filters = null; + _this._enabledFilters = null; + + /** + * The bounds object, this is used to calculate and store the bounds of the displayObject + * + * @member {PIXI.Rectangle} + * @private + */ + _this._bounds = new _Bounds2.default(); + _this._boundsID = 0; + _this._lastBoundsID = -1; + _this._boundsRect = null; + _this._localBoundsRect = null; + + /** + * The original, cached mask of the object + * + * @member {PIXI.Graphics|PIXI.Sprite} + * @private + */ + _this._mask = null; + return _this; + } + + /** + * @private + * @member {PIXI.DisplayObject} + */ + + + /** + * Updates the object transform for rendering + * + * TODO - Optimization pass! + */ + DisplayObject.prototype.updateTransform = function updateTransform() { + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + this._bounds.updateID++; + }; + + /** + * recursively updates transform of all objects from the root to this one + * internal function for toLocal() + */ + + + DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform() { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + }; + + /** + * Retrieves the bounds of the displayObject as a rectangle object. + * + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @param {PIXI.Rectangle} rect - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getBounds = function getBounds(skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + + if (this._boundsID !== this._lastBoundsID) { + this.calculateBounds(); + } + + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new _math.Rectangle(); + } + + rect = this._boundsRect; + } + + return this._bounds.getRectangle(rect); + }; + + /** + * Retrieves the local bounds of the displayObject as a rectangle object + * + * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getLocalBounds = function getLocalBounds(rect) { + var transformRef = this.transform; + var parentRef = this.parent; + + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + var bounds = this.getBounds(false, rect); + + this.parent = parentRef; + this.transform = transformRef; + + return bounds; + }; + + /** + * Calculates the global position of the display object + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform. + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toGlobal = function toGlobal(position, point) { + var skipUpdate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; + + /** + * Calculates the local position of the display object relative to another point + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toLocal = function toLocal(position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + DisplayObject.prototype.renderCanvas = function renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Set the parent Container of this DisplayObject + * + * @param {PIXI.Container} container - The Container to add this DisplayObject to + * @return {PIXI.Container} The Container that this DisplayObject was added to + */ + ; + + DisplayObject.prototype.setParent = function setParent(container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); + } + + container.addChild(this); + + return container; + }; + + /** + * Convenience function to set the position, scale, skew and pivot at once. + * + * @param {number} [x=0] - The X position + * @param {number} [y=0] - The Y position + * @param {number} [scaleX=1] - The X scale value + * @param {number} [scaleY=1] - The Y scale value + * @param {number} [rotation=0] - The rotation + * @param {number} [skewX=0] - The X skew value + * @param {number} [skewY=0] - The Y skew value + * @param {number} [pivotX=0] - The X pivot value + * @param {number} [pivotY=0] - The Y pivot value + * @return {PIXI.DisplayObject} The DisplayObject instance + */ + + + DisplayObject.prototype.setTransform = function setTransform() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var scaleX = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var scaleY = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var rotation = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var skewX = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + var skewY = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + var pivotX = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; + var pivotY = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0; + + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + + return this; + }; + + /** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy`. + * + */ + + + DisplayObject.prototype.destroy = function destroy() { + this.removeAllListeners(); + if (this.parent) { + this.parent.removeChild(this); + } + this.transform = null; + + this.parent = null; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this.filterArea = null; + + this.interactive = false; + this.interactiveChildren = false; + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + * + * @member {number} + */ + + + _createClass(DisplayObject, [{ + key: '_tempDisplayObjectParent', + get: function get() { + if (this.tempDisplayObjectParent === null) { + this.tempDisplayObjectParent = new DisplayObject(); + } + + return this.tempDisplayObjectParent; + } + }, { + key: 'x', + get: function get() { + return this.position.x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.x = value; + } + + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + * + * @member {number} + */ + + }, { + key: 'y', + get: function get() { + return this.position.y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.y = value; + } + + /** + * Current transform of the object based on world (parent) factors + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'worldTransform', + get: function get() { + return this.transform.worldTransform; + } + + /** + * Current transform of the object based on local factors: position, scale, other stuff + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'localTransform', + get: function get() { + return this.transform.localTransform; + } + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'position', + get: function get() { + return this.transform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.copy(value); + } + + /** + * The scale factor of the object. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'scale', + get: function get() { + return this.transform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.scale.copy(value); + } + + /** + * The pivot point of the displayObject that it rotates around + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'pivot', + get: function get() { + return this.transform.pivot; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.pivot.copy(value); + } + + /** + * The skew factor for the object in radians. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'skew', + get: function get() { + return this.transform.skew; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.skew.copy(value); + } + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + }, { + key: 'rotation', + get: function get() { + return this.transform.rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.rotation = value; + } + + /** + * Indicates if the object is globally visible. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'worldVisible', + get: function get() { + var item = this; + + do { + if (!item.visible) { + return false; + } + + item = item.parent; + } while (item); + + return true; + } + + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PIXI a regular mask must be a + * PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it + * utilises shape clipping. To remove a mask, set this property to null. + * + * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + * + * @member {PIXI.Graphics|PIXI.Sprite} + */ + + }, { + key: 'mask', + get: function get() { + return this._mask; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._mask) { + this._mask.renderable = true; + } + + this._mask = value; + + if (this._mask) { + this._mask.renderable = false; + } + } + + /** + * Sets the filters for the displayObject. + * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * To remove filters simply set this property to 'null' + * + * @member {PIXI.Filter[]} + */ + + }, { + key: 'filters', + get: function get() { + return this._filters && this._filters.slice(); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._filters = value && value.slice(); + } + }]); + + return DisplayObject; +}(_eventemitter2.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = DisplayObject; +DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + +},{"../const":44,"../math":68,"../settings":99,"./Bounds":45,"./Transform":48,"./TransformStatic":50,"eventemitter3":3}],48:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Generic class to deal with traditional 2D matrix transforms + * local transformation is calculated from position,scale,skew and rotation + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var Transform = function (_TransformBase) { + _inherits(Transform, _TransformBase); + + /** + * + */ + function Transform() { + _classCallCheck(this, Transform); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.Point} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.Point(0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.Point} + */ + _this.scale = new _math.Point(1, 1); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.Point} + */ + _this.pivot = new _math.Point(0, 0); + + /** + * The rotation value of the object, in radians + * + * @member {Number} + * @private + */ + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + return _this; + } + + /** + * Updates the skew values when the skew or rotation changes. + * + * @private + */ + + + Transform.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + }; + + /** + * Updates only local matrix + */ + + + Transform.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + Transform.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + Transform.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(Transform, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return Transform; +}(_TransformBase3.default); + +exports.default = Transform; + +},{"../math":68,"./TransformBase":49}],49:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Generic class to deal with traditional 2D matrix transforms + * + * @class + * @memberof PIXI + */ +var TransformBase = function () { + /** + * + */ + function TransformBase() { + _classCallCheck(this, TransformBase); + + /** + * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds() + * + * @member {PIXI.Matrix} + */ + this.worldTransform = new _math.Matrix(); + + /** + * The local matrix transform + * + * @member {PIXI.Matrix} + */ + this.localTransform = new _math.Matrix(); + + this._worldID = 0; + this._parentID = 0; + } + + /** + * TransformBase does not have decomposition, so this function wont do anything + */ + + + TransformBase.prototype.updateLocalTransform = function updateLocalTransform() {} + // empty + + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.TransformBase} parentTransform - The transform of the parent of this object + */ + ; + + TransformBase.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + return TransformBase; +}(); + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ + + +exports.default = TransformBase; +TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; + +TransformBase.IDENTITY = new TransformBase(); + +},{"../math":68}],50:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Transform that takes care about its versions + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var TransformStatic = function (_TransformBase) { + _inherits(TransformStatic, _TransformBase); + + /** + * + */ + function TransformStatic() { + _classCallCheck(this, TransformStatic); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.ObservablePoint} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.ObservablePoint} + */ + _this.scale = new _math.ObservablePoint(_this.onChange, _this, 1, 1); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.ObservablePoint} + */ + _this.pivot = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + + _this._localID = 0; + _this._currentLocalID = 0; + return _this; + } + + /** + * Called when a value changes. + * + * @private + */ + + + TransformStatic.prototype.onChange = function onChange() { + this._localID++; + }; + + /** + * Called when skew or rotation changes + * + * @private + */ + + + TransformStatic.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + + this._localID++; + }; + + /** + * Updates only local matrix + */ + + + TransformStatic.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + TransformStatic.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._parentID = parentTransform._worldID; + + // update the id of the transform.. + this._worldID++; + } + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + TransformStatic.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + this._localID++; + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(TransformStatic, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return TransformStatic; +}(_TransformBase3.default); + +exports.default = TransformStatic; + +},{"../math":68,"./TransformBase":49}],51:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _GraphicsData = require('./GraphicsData'); + +var _GraphicsData2 = _interopRequireDefault(_GraphicsData); + +var _Sprite = require('../sprites/Sprite'); + +var _Sprite2 = _interopRequireDefault(_Sprite); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Bounds = require('../display/Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _bezierCurveTo2 = require('./utils/bezierCurveTo'); + +var _bezierCurveTo3 = _interopRequireDefault(_bezierCurveTo2); + +var _CanvasRenderer = require('../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var canvasRenderer = void 0; +var tempMatrix = new _math.Matrix(); +var tempPoint = new _math.Point(); +var tempColor1 = new Float32Array(4); +var tempColor2 = new Float32Array(4); + +/** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Graphics = function (_Container) { + _inherits(Graphics, _Container); + + /** + * + * @param {boolean} [nativeLines=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + */ + function Graphics() { + var nativeLines = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + _classCallCheck(this, Graphics); + + /** + * The alpha value used when filling the Graphics object. + * + * @member {number} + * @default 1 + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @member {number} + * @default 0 + */ + _this.lineWidth = 0; + + /** + * If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * + * @member {boolean} + */ + _this.nativeLines = nativeLines; + + /** + * The color of any lines drawn. + * + * @member {string} + * @default 0 + */ + _this.lineColor = 0; + + /** + * Graphics data + * + * @member {PIXI.GraphicsData[]} + * @private + */ + _this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to + * reset the tint. + * + * @member {number} + * @default 0xFFFFFF + */ + _this.tint = 0xFFFFFF; + + /** + * The previous tint applied to the graphic shape. Used to compare to the current tint and + * check if theres change. + * + * @member {number} + * @private + * @default 0xFFFFFF + */ + _this._prevTint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * Current path + * + * @member {PIXI.GraphicsData} + * @private + */ + _this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @member {object} + * @private + */ + // TODO - _webgl should use a prototype object, not a random undocumented object... + _this._webGL = {}; + + /** + * Whether this shape is being used as a mask. + * + * @member {boolean} + */ + _this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @member {number} + */ + _this.boundsPadding = 0; + + /** + * A cache of the local bounds to prevent recalculation. + * + * @member {PIXI.Rectangle} + * @private + */ + _this._localBounds = new _Bounds2.default(); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics + * object will be recalculated. + * + * @member {boolean} + * @private + */ + _this.dirty = 0; + + /** + * Used to detect if we need to do a fast rect check using the id compare method + * @type {Number} + */ + _this.fastRectDirty = -1; + + /** + * Used to detect if we clear the graphics webGL data + * @type {Number} + */ + _this.clearDirty = 0; + + /** + * Used to detect if we we need to recalculate local bounds + * @type {Number} + */ + _this.boundsDirty = -1; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @member {boolean} + * @private + */ + _this.cachedSpriteDirty = false; + + _this._spriteRect = null; + _this._fastRect = false; + + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ + return _this; + } + + /** + * Creates a new Graphics object with the same values as this one. + * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) + * + * @return {PIXI.Graphics} A clone of the graphics object + */ + + + Graphics.prototype.clone = function clone() { + var clone = new Graphics(); + + clone.renderable = this.renderable; + clone.fillAlpha = this.fillAlpha; + clone.lineWidth = this.lineWidth; + clone.lineColor = this.lineColor; + clone.tint = this.tint; + clone.blendMode = this.blendMode; + clone.isMask = this.isMask; + clone.boundsPadding = this.boundsPadding; + clone.dirty = 0; + clone.cachedSpriteDirty = this.cachedSpriteDirty; + + // copy graphics data + for (var i = 0; i < this.graphicsData.length; ++i) { + clone.graphicsData.push(this.graphicsData[i].clone()); + } + + clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; + + clone.updateLocalBounds(); + + return clone; + }; + + /** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() + * method or the drawCircle() method. + * + * @param {number} [lineWidth=0] - width of the line to draw, will update the objects stored style + * @param {number} [color=0] - color of the line to draw, will update the objects stored style + * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineStyle = function lineStyle() { + var lineWidth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var alpha = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + + this.lineWidth = lineWidth; + this.lineColor = color; + this.lineAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length) { + // halfway through a line? start a new one! + var shape = new _math.Polygon(this.currentPath.shape.points.slice(-2)); + + shape.closed = false; + + this.drawShape(shape); + } else { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + }; + + /** + * Moves the current drawing position to x, y. + * + * @param {number} x - the X coordinate to move to + * @param {number} y - the Y coordinate to move to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.moveTo = function moveTo(x, y) { + var shape = new _math.Polygon([x, y]); + + shape.closed = false; + this.drawShape(shape); + + return this; + }; + + /** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @param {number} x - the X coordinate to draw to + * @param {number} y - the Y coordinate to draw to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineTo = function lineTo(x, y) { + this.currentPath.shape.points.push(x, y); + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.quadraticCurveTo = function quadraticCurveTo(cpX, cpY, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var n = 20; + var points = this.currentPath.shape.points; + var xa = 0; + var ya = 0; + + if (points.length === 0) { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + for (var i = 1; i <= n; ++i) { + var j = i / n; + + xa = fromX + (cpX - fromX) * j; + ya = fromY + (cpY - fromY) * j; + + points.push(xa + (cpX + (toX - cpX) * j - xa) * j, ya + (cpY + (toY - cpY) * j - ya) * j); + } + + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a bezier curve and then draws it. + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.bezierCurveTo = function bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + points.length -= 2; + + (0, _bezierCurveTo3.default)(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, points); + + this.dirty++; + + return this; + }; + + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @param {number} x1 - The x-coordinate of the beginning of the arc + * @param {number} y1 - The y-coordinate of the beginning of the arc + * @param {number} x2 - The x-coordinate of the end of the arc + * @param {number} y2 - The y-coordinate of the end of the arc + * @param {number} radius - The radius of the arc + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arcTo = function arcTo(x1, y1, x2, y2, radius) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points.push(x1, y1); + } + } else { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + } else { + var dd = a1 * a1 + b1 * b1; + var cc = a2 * a2 + b2 * b2; + var tt = a1 * a2 + b1 * b2; + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = k1 * b2 + k2 * b1; + var cy = k1 * a2 + k2 * a1; + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty++; + + return this; + }; + + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @param {number} cx - The x-coordinate of the center of the circle + * @param {number} cy - The y-coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param {number} endAngle - The ending angle, in radians + * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arc = function arc(cx, cy, radius, startAngle, endAngle) { + var anticlockwise = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; + + if (startAngle === endAngle) { + return this; + } + + if (!anticlockwise && endAngle <= startAngle) { + endAngle += Math.PI * 2; + } else if (anticlockwise && startAngle <= endAngle) { + startAngle += Math.PI * 2; + } + + var sweep = endAngle - startAngle; + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * 40; + + if (sweep === 0) { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. + var points = this.currentPath ? this.currentPath.shape.points : null; + + if (points) { + if (points[points.length - 2] !== startX || points[points.length - 1] !== startY) { + points.push(startX, startY); + } + } else { + this.moveTo(startX, startY); + points = this.currentPath.shape.points; + } + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = segMinus % 1 / segMinus; + + for (var i = 0; i <= segMinus; ++i) { + var real = i + remainder * i; + + var angle = theta + startAngle + theta2 * real; + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push((cTheta * c + sTheta * s) * radius + cx, (cTheta * -s + sTheta * c) * radius + cy); + } + + this.dirty++; + + return this; + }; + + /** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @param {number} [color=0] - the color of the fill + * @param {number} [alpha=1] - the alpha of the fill + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.beginFill = function beginFill() { + var color = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var alpha = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.filling = true; + this.fillColor = color; + this.fillAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length <= 2) { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + }; + + /** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.endFill = function endFill() { + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRect = function drawRect(x, y, width, height) { + this.drawShape(new _math.Rectangle(x, y, width, height)); + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @param {number} radius - Radius of the rectangle corners + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRoundedRect = function drawRoundedRect(x, y, width, height, radius) { + this.drawShape(new _math.RoundedRectangle(x, y, width, height, radius)); + + return this; + }; + + /** + * Draws a circle. + * + * @param {number} x - The X coordinate of the center of the circle + * @param {number} y - The Y coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawCircle = function drawCircle(x, y, radius) { + this.drawShape(new _math.Circle(x, y, radius)); + + return this; + }; + + /** + * Draws an ellipse. + * + * @param {number} x - The X coordinate of the center of the ellipse + * @param {number} y - The Y coordinate of the center of the ellipse + * @param {number} width - The half width of the ellipse + * @param {number} height - The half height of the ellipse + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawEllipse = function drawEllipse(x, y, width, height) { + this.drawShape(new _math.Ellipse(x, y, width, height)); + + return this; + }; + + /** + * Draws a polygon using the given path. + * + * @param {number[]|PIXI.Point[]} path - The path data used to construct the polygon. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawPolygon = function drawPolygon(path) { + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + var closed = true; + + if (points instanceof _math.Polygon) { + closed = points.closed; + points = points.points; + } + + if (!Array.isArray(points)) { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) { + points[i] = arguments[i]; // eslint-disable-line prefer-rest-params + } + } + + var shape = new _math.Polygon(points); + + shape.closed = closed; + + this.drawShape(shape); + + return this; + }; + + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.clear = function clear() { + if (this.lineWidth || this.filling || this.graphicsData.length > 0) { + this.lineWidth = 0; + this.filling = false; + + this.boundsDirty = -1; + this.dirty++; + this.clearDirty++; + this.graphicsData.length = 0; + } + + this.currentPath = null; + this._spriteRect = null; + + return this; + }; + + /** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. + * + * @returns {boolean} True if only 1 rect. + */ + + + Graphics.prototype.isFastRect = function isFastRect() { + return this.graphicsData.length === 1 && this.graphicsData[0].shape.type === _const.SHAPES.RECT && !this.graphicsData[0].lineWidth; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderWebGL = function _renderWebGL(renderer) { + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.dirty !== this.fastRectDirty) { + this.fastRectDirty = this.dirty; + this._fastRect = this.isFastRect(); + } + + // TODO this check can be moved to dirty? + if (this._fastRect) { + this._renderSpriteRect(renderer); + } else { + renderer.setObjectRenderer(renderer.plugins.graphics); + renderer.plugins.graphics.render(this); + } + }; + + /** + * Renders a sprite rectangle. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderSpriteRect = function _renderSpriteRect(renderer) { + var rect = this.graphicsData[0].shape; + + if (!this._spriteRect) { + if (!Graphics._SPRITE_TEXTURE) { + Graphics._SPRITE_TEXTURE = _RenderTexture2.default.create(10, 10); + + var canvas = document.createElement('canvas'); + + canvas.width = 10; + canvas.height = 10; + + var context = canvas.getContext('2d'); + + context.fillStyle = 'white'; + context.fillRect(0, 0, 10, 10); + + Graphics._SPRITE_TEXTURE = _Texture2.default.fromCanvas(canvas); + } + + this._spriteRect = new _Sprite2.default(Graphics._SPRITE_TEXTURE); + } + if (this.tint === 0xffffff) { + this._spriteRect.tint = this.graphicsData[0].fillColor; + } else { + var t1 = tempColor1; + var t2 = tempColor2; + + (0, _utils.hex2rgb)(this.graphicsData[0].fillColor, t1); + (0, _utils.hex2rgb)(this.tint, t2); + + t1[0] *= t2[0]; + t1[1] *= t2[1]; + t1[2] *= t2[2]; + + this._spriteRect.tint = (0, _utils.rgb2hex)(t1); + } + this._spriteRect.alpha = this.graphicsData[0].fillAlpha; + this._spriteRect.worldAlpha = this.worldAlpha * this._spriteRect.alpha; + this._spriteRect.blendMode = this.blendMode; + + Graphics._SPRITE_TEXTURE._frame.width = rect.width; + Graphics._SPRITE_TEXTURE._frame.height = rect.height; + + this._spriteRect.transform.worldTransform = this.transform.worldTransform; + + this._spriteRect.anchor.set(-rect.x / rect.width, -rect.y / rect.height); + this._spriteRect._onAnchorUpdate(); + + this._spriteRect._renderWebGL(renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.isMask === true) { + return; + } + + renderer.plugins.graphics.render(this); + }; + + /** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @private + */ + + + Graphics.prototype._calculateBounds = function _calculateBounds() { + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.updateLocalBounds(); + + this.cachedSpriteDirty = true; + } + + var lb = this._localBounds; + + this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); + }; + + /** + * Tests if a point is inside this graphics object + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Graphics.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + + if (!data.fill) { + continue; + } + + // only deal with fills.. + if (data.shape) { + if (data.shape.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + } + + return false; + }; + + /** + * Update the bounds of the object + * + */ + + + Graphics.prototype.updateLocalBounds = function updateLocalBounds() { + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) { + var shape = 0; + var x = 0; + var y = 0; + var w = 0; + var h = 0; + + for (var i = 0; i < this.graphicsData.length; i++) { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + + shape = data.shape; + + if (type === _const.SHAPES.RECT || type === _const.SHAPES.RREC) { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.CIRC) { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.ELIP) { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else { + // POLY + var points = shape.points; + var x2 = 0; + var y2 = 0; + var dx = 0; + var dy = 0; + var rw = 0; + var rh = 0; + var cx = 0; + var cy = 0; + + for (var j = 0; j + 2 < points.length; j += 2) { + x = points[j]; + y = points[j + 1]; + x2 = points[j + 2]; + y2 = points[j + 3]; + dx = Math.abs(x2 - x); + dy = Math.abs(y2 - y); + h = lineWidth; + w = Math.sqrt(dx * dx + dy * dy); + + if (w < 1e-9) { + continue; + } + + rw = (h / w * dy + dx) / 2; + rh = (h / w * dx + dy) / 2; + cx = (x2 + x) / 2; + cy = (y2 + y) / 2; + + minX = cx - rw < minX ? cx - rw : minX; + maxX = cx + rw > maxX ? cx + rw : maxX; + + minY = cy - rh < minY ? cy - rh : minY; + maxY = cy + rh > maxY ? cy + rh : maxY; + } + } + } + } else { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.minX = minX - padding; + this._localBounds.maxX = maxX + padding * 2; + + this._localBounds.minY = minY - padding; + this._localBounds.maxY = maxY + padding * 2; + }; + + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @return {PIXI.GraphicsData} The generated GraphicsData object. + */ + + + Graphics.prototype.drawShape = function drawShape(shape) { + if (this.currentPath) { + // check current path! + if (this.currentPath.shape.points.length <= 2) { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + var data = new _GraphicsData2.default(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, this.nativeLines, shape); + + this.graphicsData.push(data); + + if (data.type === _const.SHAPES.POLY) { + data.shape.closed = data.shape.closed || this.filling; + this.currentPath = data; + } + + this.dirty++; + + return data; + }; + + /** + * Generates a canvas texture. + * + * @param {number} scaleMode - The scale mode of the texture. + * @param {number} resolution - The resolution of the texture. + * @return {PIXI.Texture} The new texture. + */ + + + Graphics.prototype.generateCanvasTexture = function generateCanvasTexture(scaleMode) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + var bounds = this.getLocalBounds(); + + var canvasBuffer = _RenderTexture2.default.create(bounds.width, bounds.height, scaleMode, resolution); + + if (!canvasRenderer) { + canvasRenderer = new _CanvasRenderer2.default(); + } + + this.transform.updateLocalTransform(); + this.transform.localTransform.copy(tempMatrix); + + tempMatrix.invert(); + + tempMatrix.tx -= bounds.x; + tempMatrix.ty -= bounds.y; + + canvasRenderer.render(this, canvasBuffer, true, tempMatrix); + + var texture = _Texture2.default.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas, scaleMode); + + texture.baseTexture.resolution = resolution; + texture.baseTexture.update(); + + return texture; + }; + + /** + * Closes the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.closePath = function closePath() { + // ok so close path assumes next one is a hole! + var currentPath = this.currentPath; + + if (currentPath && currentPath.shape) { + currentPath.shape.close(); + } + + return this; + }; + + /** + * Adds a hole in the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.addHole = function addHole() { + // this is a hole! + var hole = this.graphicsData.pop(); + + this.currentPath = this.graphicsData[this.graphicsData.length - 1]; + + this.currentPath.addHole(hole.shape); + this.currentPath = null; + + return this; + }; + + /** + * Destroys the Graphics object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Graphics.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._webgl) { + for (var j = 0; j < this._webgl[id].data.length; ++j) { + this._webgl[id].data[j].destroy(); + } + } + + if (this._spriteRect) { + this._spriteRect.destroy(); + } + + this.graphicsData = null; + + this.currentPath = null; + this._webgl = null; + this._localBounds = null; + }; + + return Graphics; +}(_Container3.default); + +exports.default = Graphics; + + +Graphics._SPRITE_TEXTURE = null; + +},{"../const":44,"../display/Bounds":45,"../display/Container":46,"../math":68,"../renderers/canvas/CanvasRenderer":75,"../sprites/Sprite":100,"../textures/RenderTexture":110,"../textures/Texture":112,"../utils":120,"./GraphicsData":52,"./utils/bezierCurveTo":54}],52:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + */ +var GraphicsData = function () { + /** + * + * @param {number} lineWidth - the width of the line to draw + * @param {number} lineColor - the color of the line to draw + * @param {number} lineAlpha - the alpha of the line to draw + * @param {number} fillColor - the color of the fill + * @param {number} fillAlpha - the alpha of the fill + * @param {boolean} fill - whether or not the shape is filled with a colour + * @param {boolean} nativeLines - the method for drawing lines + * @param {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} shape - The shape object to draw. + */ + function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, nativeLines, shape) { + _classCallCheck(this, GraphicsData); + + /** + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + /** + * @member {boolean} if true the liens will be draw using LINES instead of TRIANGLE_STRIP + */ + this.nativeLines = nativeLines; + + /** + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /** + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /** + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /** + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /** + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /** + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /** + * @member {boolean} whether or not the shape is filled with a colour + */ + this.fill = fill; + + this.holes = []; + + /** + * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} The shape object to draw. + */ + this.shape = shape; + + /** + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + } + + /** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {PIXI.GraphicsData} Cloned GraphicsData object + */ + + + GraphicsData.prototype.clone = function clone() { + return new GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.fill, this.nativeLines, this.shape); + }; + + /** + * Adds a hole to the shape. + * + * @param {PIXI.Rectangle|PIXI.Circle} shape - The shape of the hole. + */ + + + GraphicsData.prototype.addHole = function addHole(shape) { + this.holes.push(shape); + }; + + /** + * Destroys the Graphics data. + */ + + + GraphicsData.prototype.destroy = function destroy() { + this.shape = null; + this.holes = null; + }; + + return GraphicsData; +}(); + +exports.default = GraphicsData; + +},{}],53:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they + * now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasGraphicsRenderer: + * https://github.com/libgdx/libgdx/blob/1.0.0/gdx/src/com/badlogic/gdx/graphics/glutils/ShapeRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching graphics objects. + * + * @class + * @private + * @memberof PIXI + */ +var CanvasGraphicsRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The current PIXI renderer. + */ + function CanvasGraphicsRenderer(renderer) { + _classCallCheck(this, CanvasGraphicsRenderer); + + this.renderer = renderer; + } + + /** + * Renders a Graphics object to a canvas. + * + * @param {PIXI.Graphics} graphics - the actual graphics object to render + */ + + + CanvasGraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var context = renderer.context; + var worldAlpha = graphics.worldAlpha; + var transform = graphics.transform.worldTransform; + var resolution = renderer.resolution; + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) { + this.dirty = true; + } + + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + if (graphics.dirty) { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + renderer.setBlendMode(graphics.blendMode); + + for (var i = 0; i < graphics.graphicsData.length; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === _const.SHAPES.POLY) { + context.beginPath(); + + this.renderPolygon(shape.points, shape.closed, context); + + for (var j = 0; j < data.holes.length; j++) { + this.renderPolygon(data.holes[j].points, true, context); + } + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RECT) { + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + context.beginPath(); + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + }; + + /** + * Updates the tint of a graphics object + * + * @private + * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated + */ + + + CanvasGraphicsRenderer.prototype.updateGraphicsTint = function updateGraphicsTint(graphics) { + graphics._prevTint = graphics.tint; + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF) / 255; + + for (var i = 0; i < graphics.graphicsData.length; ++i) { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + // super inline cos im an optimization NAZI :) + data._fillTint = ((fillColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (fillColor & 0xFF) / 255 * tintB * 255; + + data._lineTint = ((lineColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (lineColor & 0xFF) / 255 * tintB * 255; + } + }; + + /** + * Renders a polygon. + * + * @param {PIXI.Point[]} points - The points to render + * @param {boolean} close - Should the polygon be closed + * @param {CanvasRenderingContext2D} context - The rendering context to use + */ + + + CanvasGraphicsRenderer.prototype.renderPolygon = function renderPolygon(points, close, context) { + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; ++j) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (close) { + context.closePath(); + } + }; + + /** + * destroy graphics object + * + */ + + + CanvasGraphicsRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasGraphicsRenderer; +}(); + +exports.default = CanvasGraphicsRenderer; + + +_CanvasRenderer2.default.registerPlugin('graphics', CanvasGraphicsRenderer); + +},{"../../const":44,"../../renderers/canvas/CanvasRenderer":75}],54:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = bezierCurveTo; +/** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [path=[]] - Path array to push points into + * @return {number[]} Array of points of the curve + */ +function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var path = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : []; + + var n = 20; + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + + path.push(fromX, fromY); + + for (var i = 1, j = 0; i <= n; ++i) { + j = i / n; + + dt = 1 - j; + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + path.push(dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + return path; +} + +},{}],55:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _WebGLGraphicsData = require('./WebGLGraphicsData'); + +var _WebGLGraphicsData2 = _interopRequireDefault(_WebGLGraphicsData); + +var _PrimitiveShader = require('./shaders/PrimitiveShader'); + +var _PrimitiveShader2 = _interopRequireDefault(_PrimitiveShader); + +var _buildPoly = require('./utils/buildPoly'); + +var _buildPoly2 = _interopRequireDefault(_buildPoly); + +var _buildRectangle = require('./utils/buildRectangle'); + +var _buildRectangle2 = _interopRequireDefault(_buildRectangle); + +var _buildRoundedRectangle = require('./utils/buildRoundedRectangle'); + +var _buildRoundedRectangle2 = _interopRequireDefault(_buildRoundedRectangle); + +var _buildCircle = require('./utils/buildCircle'); + +var _buildCircle2 = _interopRequireDefault(_buildCircle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Renders the graphics object. + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var GraphicsRenderer = function (_ObjectRenderer) { + _inherits(GraphicsRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this object renderer works for. + */ + function GraphicsRenderer(renderer) { + _classCallCheck(this, GraphicsRenderer); + + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.graphicsDataPool = []; + + _this.primitiveShader = null; + + _this.gl = renderer.gl; + + // easy access! + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * Called when there is a WebGL context change + * + * @private + * + */ + + + GraphicsRenderer.prototype.onContextChange = function onContextChange() { + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.primitiveShader = new _PrimitiveShader2.default(this.gl); + }; + + /** + * Destroys this renderer. + * + */ + + + GraphicsRenderer.prototype.destroy = function destroy() { + _ObjectRenderer3.default.prototype.destroy.call(this); + + for (var i = 0; i < this.graphicsDataPool.length; ++i) { + this.graphicsDataPool[i].destroy(); + } + + this.graphicsDataPool = null; + }; + + /** + * Renders a graphics object. + * + * @param {PIXI.Graphics} graphics - The graphics object to render. + */ + + + GraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var gl = renderer.gl; + + var webGLData = void 0; + var webGL = graphics._webGL[this.CONTEXT_UID]; + + if (!webGL || graphics.dirty !== webGL.dirty) { + this.updateGraphics(graphics); + + webGL = graphics._webGL[this.CONTEXT_UID]; + } + + // This could be speeded up for sure! + var shader = this.primitiveShader; + + renderer.bindShader(shader); + renderer.state.setBlendMode(graphics.blendMode); + + for (var i = 0, n = webGL.data.length; i < n; i++) { + webGLData = webGL.data[i]; + var shaderTemp = webGLData.shader; + + renderer.bindShader(shaderTemp); + shaderTemp.uniforms.translationMatrix = graphics.transform.worldTransform.toArray(true); + shaderTemp.uniforms.tint = (0, _utils.hex2rgb)(graphics.tint); + shaderTemp.uniforms.alpha = graphics.worldAlpha; + + renderer.bindVao(webGLData.vao); + + if (graphics.nativeLines) { + gl.drawArrays(gl.LINES, 0, webGLData.points.length / 6); + } else { + webGLData.vao.draw(gl.TRIANGLE_STRIP, webGLData.indices.length); + } + } + }; + + /** + * Updates the graphics object + * + * @private + * @param {PIXI.Graphics} graphics - The graphics object to update + */ + + + GraphicsRenderer.prototype.updateGraphics = function updateGraphics(graphics) { + var gl = this.renderer.gl; + + // get the contexts graphics object + var webGL = graphics._webGL[this.CONTEXT_UID]; + + // if the graphics object does not exist in the webGL context time to create it! + if (!webGL) { + webGL = graphics._webGL[this.CONTEXT_UID] = { lastIndex: 0, data: [], gl: gl, clearDirty: -1, dirty: -1 }; + } + + // flag the graphics as not dirty as we are about to update it... + webGL.dirty = graphics.dirty; + + // if the user cleared the graphics object we will need to clear every object + if (graphics.clearDirty !== webGL.clearDirty) { + webGL.clearDirty = graphics.clearDirty; + + // loop through and return all the webGLDatas to the object pool so than can be reused later on + for (var i = 0; i < webGL.data.length; i++) { + this.graphicsDataPool.push(webGL.data[i]); + } + + // clear the array and reset the index.. + webGL.data.length = 0; + webGL.lastIndex = 0; + } + + var webGLData = void 0; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (var _i = webGL.lastIndex; _i < graphics.graphicsData.length; _i++) { + var data = graphics.graphicsData[_i]; + + // TODO - this can be simplified + webGLData = this.getWebGLData(webGL, 0); + + if (data.type === _const.SHAPES.POLY) { + (0, _buildPoly2.default)(data, webGLData); + } + if (data.type === _const.SHAPES.RECT) { + (0, _buildRectangle2.default)(data, webGLData); + } else if (data.type === _const.SHAPES.CIRC || data.type === _const.SHAPES.ELIP) { + (0, _buildCircle2.default)(data, webGLData); + } else if (data.type === _const.SHAPES.RREC) { + (0, _buildRoundedRectangle2.default)(data, webGLData); + } + + webGL.lastIndex++; + } + + this.renderer.bindVao(null); + + // upload all the dirty data... + for (var _i2 = 0; _i2 < webGL.data.length; _i2++) { + webGLData = webGL.data[_i2]; + + if (webGLData.dirty) { + webGLData.upload(); + } + } + }; + + /** + * + * @private + * @param {WebGLRenderingContext} gl - the current WebGL drawing context + * @param {number} type - TODO @Alvin + * @return {*} TODO + */ + + + GraphicsRenderer.prototype.getWebGLData = function getWebGLData(gl, type) { + var webGLData = gl.data[gl.data.length - 1]; + + if (!webGLData || webGLData.points.length > 320000) { + webGLData = this.graphicsDataPool.pop() || new _WebGLGraphicsData2.default(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + + webGLData.reset(type); + gl.data.push(webGLData); + } + + webGLData.dirty = true; + + return webGLData; + }; + + return GraphicsRenderer; +}(_ObjectRenderer3.default); + +exports.default = GraphicsRenderer; + + +_WebGLRenderer2.default.registerPlugin('graphics', GraphicsRenderer); + +},{"../../const":44,"../../renderers/webgl/WebGLRenderer":82,"../../renderers/webgl/utils/ObjectRenderer":92,"../../utils":120,"./WebGLGraphicsData":56,"./shaders/PrimitiveShader":57,"./utils/buildCircle":58,"./utils/buildPoly":60,"./utils/buildRectangle":61,"./utils/buildRoundedRectangle":62}],56:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * An object containing WebGL specific properties to be used by the WebGL renderer + * + * @class + * @private + * @memberof PIXI + */ +var WebGLGraphicsData = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {PIXI.Shader} shader - The shader + * @param {object} attribsState - The state for the VAO + */ + function WebGLGraphicsData(gl, shader, attribsState) { + _classCallCheck(this, WebGLGraphicsData); + + /** + * The current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // TODO does this need to be split before uploading?? + /** + * An array of color components (r,g,b) + * @member {number[]} + */ + this.color = [0, 0, 0]; // color split! + + /** + * An array of points to draw + * @member {PIXI.Point[]} + */ + this.points = []; + + /** + * The indices of the vertices + * @member {number[]} + */ + this.indices = []; + /** + * The main buffer + * @member {WebGLBuffer} + */ + this.buffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl); + + /** + * The index buffer + * @member {WebGLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl); + + /** + * Whether this graphics is dirty or not + * @member {boolean} + */ + this.dirty = true; + + this.glPoints = null; + this.glIndices = null; + + /** + * + * @member {PIXI.Shader} + */ + this.shader = shader; + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, attribsState).addIndex(this.indexBuffer).addAttribute(this.buffer, shader.attributes.aVertexPosition, gl.FLOAT, false, 4 * 6, 0).addAttribute(this.buffer, shader.attributes.aColor, gl.FLOAT, false, 4 * 6, 2 * 4); + } + + /** + * Resets the vertices and the indices + */ + + + WebGLGraphicsData.prototype.reset = function reset() { + this.points.length = 0; + this.indices.length = 0; + }; + + /** + * Binds the buffers and uploads the data + */ + + + WebGLGraphicsData.prototype.upload = function upload() { + this.glPoints = new Float32Array(this.points); + this.buffer.upload(this.glPoints); + + this.glIndices = new Uint16Array(this.indices); + this.indexBuffer.upload(this.glIndices); + + this.dirty = false; + }; + + /** + * Empties all the data + */ + + + WebGLGraphicsData.prototype.destroy = function destroy() { + this.color = null; + this.points = null; + this.indices = null; + + this.vao.destroy(); + this.buffer.destroy(); + this.indexBuffer.destroy(); + + this.gl = null; + + this.buffer = null; + this.indexBuffer = null; + + this.glPoints = null; + this.glIndices = null; + }; + + return WebGLGraphicsData; +}(); + +exports.default = WebGLGraphicsData; + +},{"pixi-gl-core":12}],57:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../../Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. + * + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ +var PrimitiveShader = function (_Shader) { + _inherits(PrimitiveShader, _Shader); + + /** + * @param {WebGLRenderingContext} gl - The webgl shader manager this shader works for. + */ + function PrimitiveShader(gl) { + _classCallCheck(this, PrimitiveShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec4 aColor;', 'uniform mat3 translationMatrix;', 'uniform mat3 projectionMatrix;', 'uniform float alpha;', 'uniform vec3 tint;', 'varying vec4 vColor;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vColor = aColor * vec4(tint * alpha, alpha);', '}'].join('\n'), + // fragment shader + ['varying vec4 vColor;', 'void main(void){', ' gl_FragColor = vColor;', '}'].join('\n'))); + } + + return PrimitiveShader; +}(_Shader3.default); + +exports.default = PrimitiveShader; + +},{"../../../Shader":42}],58:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildCircle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _const = require('../../../const'); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildCircle(graphicsData, webGLData) { + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width = void 0; + var height = void 0; + + // TODO - bit hacky?? + if (graphicsData.type === _const.SHAPES.CIRC) { + width = circleData.radius; + height = circleData.radius; + } else { + width = circleData.width; + height = circleData.height; + } + + if (width === 0 || height === 0) { + return; + } + + var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); + + var seg = Math.PI * 2 / totalSegs; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + indices.push(vecPos); + + for (var i = 0; i < totalSegs + 1; i++) { + verts.push(x, y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos - 1); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (var _i = 0; _i < totalSegs + 1; _i++) { + graphicsData.points.push(x + Math.sin(seg * _i) * width, y + Math.cos(seg * _i) * height); + } + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +},{"../../../const":44,"../../../utils":120,"./buildLine":59}],59:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function (graphicsData, webGLData) { + if (graphicsData.nativeLines) { + buildNativeLine(graphicsData, webGLData); + } else { + buildLine(graphicsData, webGLData); + } +}; + +var _math = require('../../../math'); + +var _utils = require('../../../utils'); + +/** + * Builds a line to draw using the poligon method. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildLine(graphicsData, webGLData) { + // TODO OPTIMISE! + var points = graphicsData.points; + + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + + // get first and last point.. figure out the middle! + var firstPoint = new _math.Point(points[0], points[1]); + var lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + // if the first point is the last point - gonna have issues :) + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var p1x = points[0]; + var p1y = points[1]; + var p2x = points[2]; + var p2y = points[3]; + var p3x = 0; + var p3y = 0; + + var perpx = -(p1y - p2y); + var perpy = p1x - p2x; + var perp2x = 0; + var perp2y = 0; + var perp3x = 0; + var perp3y = 0; + + var dist = Math.sqrt(perpx * perpx + perpy * perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx, p1y - perpy, r, g, b, alpha); + + verts.push(p1x + perpx, p1y + perpy, r, g, b, alpha); + + for (var i = 1; i < length - 1; ++i) { + p1x = points[(i - 1) * 2]; + p1y = points[(i - 1) * 2 + 1]; + + p2x = points[i * 2]; + p2y = points[i * 2 + 1]; + + p3x = points[(i + 1) * 2]; + p3y = points[(i + 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + var a1 = -perpy + p1y - (-perpy + p2y); + var b1 = -perpx + p2x - (-perpx + p1x); + var c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + var a2 = -perp2y + p3y - (-perp2y + p2y); + var b2 = -perp2x + p2x - (-perp2x + p3x); + var c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + var denom = a1 * b2 - a2 * b1; + + if (Math.abs(denom) < 0.1) { + denom += 10.1; + verts.push(p2x - perpx, p2y - perpy, r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy, r, g, b, alpha); + + continue; + } + + var px = (b1 * c2 - b2 * c1) / denom; + var py = (a2 * c1 - a1 * c2) / denom; + var pdist = (px - p2x) * (px - p2x) + (py - p2y) * (py - p2y); + + if (pdist > 196 * width * width) { + perp3x = perpx - perp2x; + perp3y = perpy - perp2y; + + dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y); + perp3x /= dist; + perp3y /= dist; + perp3x *= width; + perp3y *= width; + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x + perp3x, p2y + perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + indexCount++; + } else { + verts.push(px, py); + verts.push(r, g, b, alpha); + + verts.push(p2x - (px - p2x), p2y - (py - p2y)); + verts.push(r, g, b, alpha); + } + } + + p1x = points[(length - 2) * 2]; + p1y = points[(length - 2) * 2 + 1]; + + p2x = points[(length - 1) * 2]; + p2y = points[(length - 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + verts.push(p2x - perpx, p2y - perpy); + verts.push(r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy); + verts.push(r, g, b, alpha); + + indices.push(indexStart); + + for (var _i = 0; _i < indexCount; ++_i) { + indices.push(indexStart++); + } + + indices.push(indexStart - 1); +} + +/** + * Builds a line to draw using the gl.drawArrays(gl.LINES) method + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ + + +/** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildNativeLine(graphicsData, webGLData) { + var i = 0; + var points = graphicsData.points; + + if (points.length === 0) return; + + var verts = webGLData.points; + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + for (i = 1; i < length; i++) { + var p1x = points[(i - 1) * 2]; + var p1y = points[(i - 1) * 2 + 1]; + + var p2x = points[i * 2]; + var p2y = points[i * 2 + 1]; + + verts.push(p1x, p1y); + verts.push(r, g, b, alpha); + + verts.push(p2x, p2y); + verts.push(r, g, b, alpha); + } +} + +},{"../../../math":68,"../../../utils":120}],60:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildPoly; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildPoly(graphicsData, webGLData) { + graphicsData.points = graphicsData.shape.points.slice(); + + var points = graphicsData.points; + + if (graphicsData.fill && points.length >= 6) { + var holeArray = []; + // Process holes.. + var holes = graphicsData.holes; + + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + + holeArray.push(points.length / 2); + + points = points.concat(hole.points); + } + + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = (0, _earcut2.default)(points, holeArray, 2); + + if (!triangles) { + return; + } + + var vertPos = verts.length / 6; + + for (var _i = 0; _i < triangles.length; _i += 3) { + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i + 1] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + } + + for (var _i2 = 0; _i2 < length; _i2++) { + verts.push(points[_i2 * 2], points[_i2 * 2 + 1], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth > 0) { + (0, _buildLine2.default)(graphicsData, webGLData); + } +} + +},{"../../../utils":120,"./buildLine":59,"earcut":2}],61:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRectangle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildRectangle(graphicsData, webGLData) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vertPos = verts.length / 6; + + // start + verts.push(x, y); + verts.push(r, g, b, alpha); + + verts.push(x + width, y); + verts.push(r, g, b, alpha); + + verts.push(x, y + height); + verts.push(r, g, b, alpha); + + verts.push(x + width, y + height); + verts.push(r, g, b, alpha); + + // insert 2 dead triangles.. + indices.push(vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y]; + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +},{"../../../utils":120,"./buildLine":59}],62:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRoundedRectangle; + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildRoundedRectangle(graphicsData, webGLData) { + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + + recPoints.push(x, y + radius); + quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height, recPoints); + quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius, recPoints); + quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y, recPoints); + quadraticBezierCurve(x + radius, y, x, y, x, y + radius + 0.0000000001, recPoints); + + // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. + // TODO - fix this properly, this is not very elegant.. but it works for now. + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + var triangles = (0, _earcut2.default)(recPoints, null, 2); + + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + + for (var _i = 0, _j = recPoints.length; _i < _j; _i++) { + verts.push(recPoints[_i], recPoints[++_i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +/** + * Calculate a single point for a quadratic bezier curve. + * Utility function used by quadraticBezierCurve. + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} n1 - first number + * @param {number} n2 - second number + * @param {number} perc - percentage + * @return {number} the result + * + */ +function getPt(n1, n2, perc) { + var diff = n2 - n1; + + return n1 + diff * perc; +} + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @return {number[]} an array of points + */ +function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY) { + var out = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : []; + + var n = 20; + var points = out; + + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + + points.push(x, y); + } + + return points; +} + +},{"../../../utils":120,"./buildLine":59,"earcut":2}],63:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = exports.Application = exports.Filter = exports.SpriteMaskFilter = exports.Quad = exports.RenderTarget = exports.ObjectRenderer = exports.WebGLManager = exports.Shader = exports.CanvasRenderTarget = exports.TextureUvs = exports.VideoBaseTexture = exports.BaseRenderTexture = exports.RenderTexture = exports.BaseTexture = exports.Texture = exports.Spritesheet = exports.CanvasGraphicsRenderer = exports.GraphicsRenderer = exports.GraphicsData = exports.Graphics = exports.TextStyle = exports.Text = exports.SpriteRenderer = exports.CanvasTinter = exports.CanvasSpriteRenderer = exports.Sprite = exports.TransformBase = exports.TransformStatic = exports.Transform = exports.Container = exports.DisplayObject = exports.Bounds = exports.glCore = exports.WebGLRenderer = exports.CanvasRenderer = exports.ticker = exports.utils = exports.settings = undefined; + +var _const = require('./const'); + +Object.keys(_const).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _const[key]; + } + }); +}); + +var _math = require('./math'); + +Object.keys(_math).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _math[key]; + } + }); +}); + +var _pixiGlCore = require('pixi-gl-core'); + +Object.defineProperty(exports, 'glCore', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_pixiGlCore).default; + } +}); + +var _Bounds = require('./display/Bounds'); + +Object.defineProperty(exports, 'Bounds', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Bounds).default; + } +}); + +var _DisplayObject = require('./display/DisplayObject'); + +Object.defineProperty(exports, 'DisplayObject', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplayObject).default; + } +}); + +var _Container = require('./display/Container'); + +Object.defineProperty(exports, 'Container', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Container).default; + } +}); + +var _Transform = require('./display/Transform'); + +Object.defineProperty(exports, 'Transform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Transform).default; + } +}); + +var _TransformStatic = require('./display/TransformStatic'); + +Object.defineProperty(exports, 'TransformStatic', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformStatic).default; + } +}); + +var _TransformBase = require('./display/TransformBase'); + +Object.defineProperty(exports, 'TransformBase', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformBase).default; + } +}); + +var _Sprite = require('./sprites/Sprite'); + +Object.defineProperty(exports, 'Sprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Sprite).default; + } +}); + +var _CanvasSpriteRenderer = require('./sprites/canvas/CanvasSpriteRenderer'); + +Object.defineProperty(exports, 'CanvasSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasSpriteRenderer).default; + } +}); + +var _CanvasTinter = require('./sprites/canvas/CanvasTinter'); + +Object.defineProperty(exports, 'CanvasTinter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasTinter).default; + } +}); + +var _SpriteRenderer = require('./sprites/webgl/SpriteRenderer'); + +Object.defineProperty(exports, 'SpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteRenderer).default; + } +}); + +var _Text = require('./text/Text'); + +Object.defineProperty(exports, 'Text', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Text).default; + } +}); + +var _TextStyle = require('./text/TextStyle'); + +Object.defineProperty(exports, 'TextStyle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextStyle).default; + } +}); + +var _Graphics = require('./graphics/Graphics'); + +Object.defineProperty(exports, 'Graphics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Graphics).default; + } +}); + +var _GraphicsData = require('./graphics/GraphicsData'); + +Object.defineProperty(exports, 'GraphicsData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsData).default; + } +}); + +var _GraphicsRenderer = require('./graphics/webgl/GraphicsRenderer'); + +Object.defineProperty(exports, 'GraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsRenderer).default; + } +}); + +var _CanvasGraphicsRenderer = require('./graphics/canvas/CanvasGraphicsRenderer'); + +Object.defineProperty(exports, 'CanvasGraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasGraphicsRenderer).default; + } +}); + +var _Spritesheet = require('./textures/Spritesheet'); + +Object.defineProperty(exports, 'Spritesheet', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Spritesheet).default; + } +}); + +var _Texture = require('./textures/Texture'); + +Object.defineProperty(exports, 'Texture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Texture).default; + } +}); + +var _BaseTexture = require('./textures/BaseTexture'); + +Object.defineProperty(exports, 'BaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseTexture).default; + } +}); + +var _RenderTexture = require('./textures/RenderTexture'); + +Object.defineProperty(exports, 'RenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTexture).default; + } +}); + +var _BaseRenderTexture = require('./textures/BaseRenderTexture'); + +Object.defineProperty(exports, 'BaseRenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseRenderTexture).default; + } +}); + +var _VideoBaseTexture = require('./textures/VideoBaseTexture'); + +Object.defineProperty(exports, 'VideoBaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VideoBaseTexture).default; + } +}); + +var _TextureUvs = require('./textures/TextureUvs'); + +Object.defineProperty(exports, 'TextureUvs', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureUvs).default; + } +}); + +var _CanvasRenderTarget = require('./renderers/canvas/utils/CanvasRenderTarget'); + +Object.defineProperty(exports, 'CanvasRenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasRenderTarget).default; + } +}); + +var _Shader = require('./Shader'); + +Object.defineProperty(exports, 'Shader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Shader).default; + } +}); + +var _WebGLManager = require('./renderers/webgl/managers/WebGLManager'); + +Object.defineProperty(exports, 'WebGLManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLManager).default; + } +}); + +var _ObjectRenderer = require('./renderers/webgl/utils/ObjectRenderer'); + +Object.defineProperty(exports, 'ObjectRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObjectRenderer).default; + } +}); + +var _RenderTarget = require('./renderers/webgl/utils/RenderTarget'); + +Object.defineProperty(exports, 'RenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTarget).default; + } +}); + +var _Quad = require('./renderers/webgl/utils/Quad'); + +Object.defineProperty(exports, 'Quad', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Quad).default; + } +}); + +var _SpriteMaskFilter = require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter'); + +Object.defineProperty(exports, 'SpriteMaskFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteMaskFilter).default; + } +}); + +var _Filter = require('./renderers/webgl/filters/Filter'); + +Object.defineProperty(exports, 'Filter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Filter).default; + } +}); + +var _Application = require('./Application'); + +Object.defineProperty(exports, 'Application', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Application).default; + } +}); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +Object.defineProperty(exports, 'autoDetectRenderer', { + enumerable: true, + get: function get() { + return _autoDetectRenderer.autoDetectRenderer; + } +}); + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _ticker = require('./ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.settings = _settings2.default; +exports.utils = utils; +exports.ticker = ticker; +exports.CanvasRenderer = _CanvasRenderer2.default; +exports.WebGLRenderer = _WebGLRenderer2.default; /** + * @namespace PIXI + */ + +},{"./Application":41,"./Shader":42,"./autoDetectRenderer":43,"./const":44,"./display/Bounds":45,"./display/Container":46,"./display/DisplayObject":47,"./display/Transform":48,"./display/TransformBase":49,"./display/TransformStatic":50,"./graphics/Graphics":51,"./graphics/GraphicsData":52,"./graphics/canvas/CanvasGraphicsRenderer":53,"./graphics/webgl/GraphicsRenderer":55,"./math":68,"./renderers/canvas/CanvasRenderer":75,"./renderers/canvas/utils/CanvasRenderTarget":77,"./renderers/webgl/WebGLRenderer":82,"./renderers/webgl/filters/Filter":84,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":87,"./renderers/webgl/managers/WebGLManager":91,"./renderers/webgl/utils/ObjectRenderer":92,"./renderers/webgl/utils/Quad":93,"./renderers/webgl/utils/RenderTarget":94,"./settings":99,"./sprites/Sprite":100,"./sprites/canvas/CanvasSpriteRenderer":101,"./sprites/canvas/CanvasTinter":102,"./sprites/webgl/SpriteRenderer":104,"./text/Text":106,"./text/TextStyle":107,"./textures/BaseRenderTexture":108,"./textures/BaseTexture":109,"./textures/RenderTexture":110,"./textures/Spritesheet":111,"./textures/Texture":112,"./textures/TextureUvs":113,"./textures/VideoBaseTexture":114,"./ticker":116,"./utils":120,"pixi-gl-core":12}],64:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Matrix = require('./Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16 + +var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; +var tempMatrices = []; + +var mul = []; + +function signum(x) { + if (x < 0) { + return -1; + } + if (x > 0) { + return 1; + } + + return 0; +} + +function init() { + for (var i = 0; i < 16; i++) { + var row = []; + + mul.push(row); + + for (var j = 0; j < 16; j++) { + var _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); + var _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); + var _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); + var _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); + + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + + for (var _i = 0; _i < 16; _i++) { + var mat = new _Matrix2.default(); + + mat.set(ux[_i], uy[_i], vx[_i], vy[_i], 0, 0); + tempMatrices.push(mat); + } +} + +init(); + +/** + * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, + * D8 is the same but with diagonals. Used for texture rotations. + * + * Vector xX(i), xY(i) is U-axis of sprite with rotation i + * Vector yY(i), yY(i) is V-axis of sprite with rotation i + * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) + * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) + * This is the small part of gameofbombs.com portal system. It works. + * + * @author Ivan @ivanpopelyshev + * @class + * @memberof PIXI + */ +var GroupD8 = { + E: 0, + SE: 1, + S: 2, + SW: 3, + W: 4, + NW: 5, + N: 6, + NE: 7, + MIRROR_VERTICAL: 8, + MIRROR_HORIZONTAL: 12, + uX: function uX(ind) { + return ux[ind]; + }, + uY: function uY(ind) { + return uy[ind]; + }, + vX: function vX(ind) { + return vx[ind]; + }, + vY: function vY(ind) { + return vy[ind]; + }, + inv: function inv(rotation) { + if (rotation & 8) { + return rotation & 15; + } + + return -rotation & 7; + }, + add: function add(rotationSecond, rotationFirst) { + return mul[rotationSecond][rotationFirst]; + }, + sub: function sub(rotationSecond, rotationFirst) { + return mul[rotationSecond][GroupD8.inv(rotationFirst)]; + }, + + /** + * Adds 180 degrees to rotation. Commutative operation. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to rotate. + * @returns {number} rotated number + */ + rotate180: function rotate180(rotation) { + return rotation ^ 4; + }, + + /** + * I dont know why sometimes width and heights needs to be swapped. We'll fix it later. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the width/height should be swapped. + */ + isSwapWidthHeight: function isSwapWidthHeight(rotation) { + return (rotation & 3) === 2; + }, + + /** + * @memberof PIXI.GroupD8 + * @param {number} dx - TODO + * @param {number} dy - TODO + * + * @return {number} TODO + */ + byDirection: function byDirection(dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return GroupD8.S; + } + + return GroupD8.N; + } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return GroupD8.E; + } + + return GroupD8.W; + } else if (dy > 0) { + if (dx > 0) { + return GroupD8.SE; + } + + return GroupD8.SW; + } else if (dx > 0) { + return GroupD8.NE; + } + + return GroupD8.NW; + }, + + /** + * Helps sprite to compensate texture packer rotation. + * + * @memberof PIXI.GroupD8 + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {number} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function matrixAppendRotationInv(matrix, rotation) { + var tx = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var ty = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + // Packer used "rotation", we use "inv(rotation)" + var mat = tempMatrices[GroupD8.inv(rotation)]; + + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + } +}; + +exports.default = GroupD8; + +},{"./Matrix":65}],65:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Point = require('./Point'); + +var _Point2 = _interopRequireDefault(_Point); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The pixi Matrix class as an object, which makes it a lot faster, + * here is a representation of it : + * | a | b | tx| + * | c | d | ty| + * | 0 | 0 | 1 | + * + * @class + * @memberof PIXI + */ +var Matrix = function () { + /** + * @param {number} [a=1] - x scale + * @param {number} [b=0] - y skew + * @param {number} [c=0] - x skew + * @param {number} [d=1] - y scale + * @param {number} [tx=0] - x translation + * @param {number} [ty=0] - y translation + */ + function Matrix() { + var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var d = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var tx = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var ty = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + + _classCallCheck(this, Matrix); + + /** + * @member {number} + * @default 1 + */ + this.a = a; + + /** + * @member {number} + * @default 0 + */ + this.b = b; + + /** + * @member {number} + * @default 0 + */ + this.c = c; + + /** + * @member {number} + * @default 1 + */ + this.d = d; + + /** + * @member {number} + * @default 0 + */ + this.tx = tx; + + /** + * @member {number} + * @default 0 + */ + this.ty = ty; + + this.array = null; + } + + /** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @param {number[]} array - The array that the matrix will be populated from. + */ + + + Matrix.prototype.fromArray = function fromArray(array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + }; + + /** + * sets the matrix properties + * + * @param {number} a - Matrix component + * @param {number} b - Matrix component + * @param {number} c - Matrix component + * @param {number} d - Matrix component + * @param {number} tx - Matrix component + * @param {number} ty - Matrix component + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.set = function set(a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + }; + + /** + * Creates an array from the current Matrix object. + * + * @param {boolean} transpose - Whether we need to transpose the matrix or not + * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out + * @return {number[]} the newly created array which contains the matrix + */ + + + Matrix.prototype.toArray = function toArray(transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + + var array = out || this.array; + + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + }; + + /** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, transformed through this matrix + */ + + + Matrix.prototype.apply = function apply(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; + + return newPos; + }; + + /** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, inverse-transformed through this matrix + */ + + + Matrix.prototype.applyInverse = function applyInverse(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var id = 1 / (this.a * this.d + this.c * -this.b); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + }; + + /** + * Translates the matrix on the x and y. + * + * @param {number} x How much to translate x by + * @param {number} y How much to translate y by + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.translate = function translate(x, y) { + this.tx += x; + this.ty += y; + + return this; + }; + + /** + * Applies a scale transformation to the matrix. + * + * @param {number} x The amount to scale horizontally + * @param {number} y The amount to scale vertically + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.scale = function scale(x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + }; + + /** + * Applies a rotation transformation to the matrix. + * + * @param {number} angle - The angle in radians. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.rotate = function rotate(angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos - this.b * sin; + this.b = a1 * sin + this.b * cos; + this.c = c1 * cos - this.d * sin; + this.d = c1 * sin + this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + }; + + /** + * Appends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to append. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.append = function append(matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + }; + + /** + * Sets the matrix based on all the available properties + * + * @param {number} x - Position on the x axis + * @param {number} y - Position on the y axis + * @param {number} pivotX - Pivot on the x axis + * @param {number} pivotY - Pivot on the y axis + * @param {number} scaleX - Scale on the x axis + * @param {number} scaleY - Scale on the y axis + * @param {number} rotation - Rotation in radians + * @param {number} skewX - Skew on the x axis + * @param {number} skewY - Skew on the y axis + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.setTransform = function setTransform(x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + var sr = Math.sin(rotation); + var cr = Math.cos(rotation); + var cy = Math.cos(skewY); + var sy = Math.sin(skewY); + var nsx = -Math.sin(skewX); + var cx = Math.cos(skewX); + + var a = cr * scaleX; + var b = sr * scaleX; + var c = -sr * scaleY; + var d = cr * scaleY; + + this.a = cy * a + sy * c; + this.b = cy * b + sy * d; + this.c = nsx * a + cx * c; + this.d = nsx * b + cx * d; + + this.tx = x + (pivotX * a + pivotY * c); + this.ty = y + (pivotX * b + pivotY * d); + + return this; + }; + + /** + * Prepends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to prepend + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.prepend = function prepend(matrix) { + var tx1 = this.tx; + + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + + this.a = a1 * matrix.a + this.b * matrix.c; + this.b = a1 * matrix.b + this.b * matrix.d; + this.c = c1 * matrix.a + this.d * matrix.c; + this.d = c1 * matrix.b + this.d * matrix.d; + } + + this.tx = tx1 * matrix.a + this.ty * matrix.c + matrix.tx; + this.ty = tx1 * matrix.b + this.ty * matrix.d + matrix.ty; + + return this; + }; + + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * + * @param {PIXI.Transform|PIXI.TransformStatic} transform - The transform to apply the properties to. + * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properties + */ + + + Matrix.prototype.decompose = function decompose(transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + + var skewX = -Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + + var delta = Math.abs(skewX + skewY); + + if (delta < 0.00001) { + transform.rotation = skewY; + + if (a < 0 && d >= 0) { + transform.rotation += transform.rotation <= 0 ? Math.PI : -Math.PI; + } + + transform.skew.x = transform.skew.y = 0; + } else { + transform.skew.x = skewX; + transform.skew.y = skewY; + } + + // next set scale + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); + + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; + + return transform; + }; + + /** + * Inverts this matrix + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.invert = function invert() { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1 * d1 - b1 * c1; + + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = (c1 * this.ty - d1 * tx1) / n; + this.ty = -(a1 * this.ty - b1 * tx1) / n; + + return this; + }; + + /** + * Resets this Matix to an identity (default) matrix. + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.identity = function identity() { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + + return this; + }; + + /** + * Creates a new Matrix object with the same values as this one. + * + * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. + */ + + + Matrix.prototype.clone = function clone() { + var matrix = new Matrix(); + + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * Changes the values of the given matrix to be the same as the ones in this matrix + * + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @return {PIXI.Matrix} The matrix given in parameter with its values updated. + */ + + + Matrix.prototype.copy = function copy(matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * A default (identity) matrix + * + * @static + * @const + */ + + + _createClass(Matrix, null, [{ + key: 'IDENTITY', + get: function get() { + return new Matrix(); + } + + /** + * A temp matrix + * + * @static + * @const + */ + + }, { + key: 'TEMP_MATRIX', + get: function get() { + return new Matrix(); + } + }]); + + return Matrix; +}(); + +exports.default = Matrix; + +},{"./Point":67}],66:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * An observable point is a point that triggers a callback when the point's position is changed. + * + * @class + * @memberof PIXI + */ +var ObservablePoint = function () { + /** + * @param {Function} cb - callback when changed + * @param {object} scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope) { + var x = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var y = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, ObservablePoint); + + this._x = x; + this._y = y; + + this.cb = cb; + this.scope = scope; + } + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + ObservablePoint.prototype.set = function set(x, y) { + var _x = x || 0; + var _y = y || (y !== 0 ? _x : 0); + + if (this._x !== _x || this._y !== _y) { + this._x = _x; + this._y = _y; + this.cb.call(this.scope); + } + }; + + /** + * Copies the data from another point + * + * @param {PIXI.Point|PIXI.ObservablePoint} point - point to copy from + */ + + + ObservablePoint.prototype.copy = function copy(point) { + if (this._x !== point.x || this._y !== point.y) { + this._x = point.x; + this._y = point.y; + this.cb.call(this.scope); + } + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + + _createClass(ObservablePoint, [{ + key: "x", + get: function get() { + return this._x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + } + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + }, { + key: "y", + get: function get() { + return this._y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + } + }]); + + return ObservablePoint; +}(); + +exports.default = ObservablePoint; + +},{}],67:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * + * @class + * @memberof PIXI + */ +var Point = function () { + /** + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function Point() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + + _classCallCheck(this, Point); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + } + + /** + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point + */ + + + Point.prototype.clone = function clone() { + return new Point(this.x, this.y); + }; + + /** + * Copies x and y from the given point + * + * @param {PIXI.Point} p - The point to copy. + */ + + + Point.prototype.copy = function copy(p) { + this.set(p.x, p.y); + }; + + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.Point} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + + + Point.prototype.equals = function equals(p) { + return p.x === this.x && p.y === this.y; + }; + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + Point.prototype.set = function set(x, y) { + this.x = x || 0; + this.y = y || (y !== 0 ? this.x : 0); + }; + + return Point; +}(); + +exports.default = Point; + +},{}],68:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('./Point'); + +Object.defineProperty(exports, 'Point', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Point).default; + } +}); + +var _ObservablePoint = require('./ObservablePoint'); + +Object.defineProperty(exports, 'ObservablePoint', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObservablePoint).default; + } +}); + +var _Matrix = require('./Matrix'); + +Object.defineProperty(exports, 'Matrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Matrix).default; + } +}); + +var _GroupD = require('./GroupD8'); + +Object.defineProperty(exports, 'GroupD8', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GroupD).default; + } +}); + +var _Circle = require('./shapes/Circle'); + +Object.defineProperty(exports, 'Circle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Circle).default; + } +}); + +var _Ellipse = require('./shapes/Ellipse'); + +Object.defineProperty(exports, 'Ellipse', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Ellipse).default; + } +}); + +var _Polygon = require('./shapes/Polygon'); + +Object.defineProperty(exports, 'Polygon', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Polygon).default; + } +}); + +var _Rectangle = require('./shapes/Rectangle'); + +Object.defineProperty(exports, 'Rectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rectangle).default; + } +}); + +var _RoundedRectangle = require('./shapes/RoundedRectangle'); + +Object.defineProperty(exports, 'RoundedRectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RoundedRectangle).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./GroupD8":64,"./Matrix":65,"./ObservablePoint":66,"./Point":67,"./shapes/Circle":69,"./shapes/Ellipse":70,"./shapes/Polygon":71,"./shapes/Rectangle":72,"./shapes/RoundedRectangle":73}],69:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Circle object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Circle = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [radius=0] - The radius of the circle + */ + function Circle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var radius = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + _classCallCheck(this, Circle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.CIRC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.CIRC; + } + + /** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ + + + Circle.prototype.clone = function clone() { + return new Circle(this.x, this.y, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this circle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Circle + */ + + + Circle.prototype.contains = function contains(x, y) { + if (this.radius <= 0) { + return false; + } + + var r2 = this.radius * this.radius; + var dx = this.x - x; + var dy = this.y - y; + + dx *= dx; + dy *= dy; + + return dx + dy <= r2; + }; + + /** + * Returns the framing rectangle of the circle as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Circle.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + + return Circle; +}(); + +exports.default = Circle; + +},{"../../const":44,"./Rectangle":72}],70:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Ellipse object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Ellipse = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [width=0] - The half width of this ellipse + * @param {number} [height=0] - The half height of this ellipse + */ + function Ellipse() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Ellipse); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.ELIP + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.ELIP; + } + + /** + * Creates a clone of this Ellipse instance + * + * @return {PIXI.Ellipse} a copy of the ellipse + */ + + + Ellipse.prototype.clone = function clone() { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coords are within this ellipse + */ + + + Ellipse.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + // normalize the coords to an ellipse with center 0,0 + var normx = (x - this.x) / this.width; + var normy = (y - this.y) / this.height; + + normx *= normx; + normy *= normy; + + return normx + normy <= 1; + }; + + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Ellipse.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.width, this.y - this.height, this.width, this.height); + }; + + return Ellipse; +}(); + +exports.default = Ellipse; + +},{"../../const":44,"./Rectangle":72}],71:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('../Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Polygon = function () { + /** + * @param {PIXI.Point[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + for (var _len = arguments.length, points = Array(_len), _key = 0; _key < _len; _key++) { + points[_key] = arguments[_key]; + } + + _classCallCheck(this, Polygon); + + if (Array.isArray(points[0])) { + points = points[0]; + } + + // if this is an array of points, convert it to a flat array of numbers + if (points[0] instanceof _Point2.default) { + var p = []; + + for (var i = 0, il = points.length; i < il; i++) { + p.push(points[i].x, points[i].y); + } + + points = p; + } + + this.closed = true; + + /** + * An array of the points of this polygon + * + * @member {number[]} + */ + this.points = points; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.POLY + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.POLY; + } + + /** + * Creates a clone of this polygon + * + * @return {PIXI.Polygon} a copy of the polygon + */ + + + Polygon.prototype.clone = function clone() { + return new Polygon(this.points.slice()); + }; + + /** + * Closes the polygon, adding points if necessary. + * + */ + + + Polygon.prototype.close = function close() { + var points = this.points; + + // close the poly if the value is true! + if (points[0] !== points[points.length - 2] || points[1] !== points[points.length - 1]) { + points.push(points[0], points[1]); + } + }; + + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this polygon + */ + + + Polygon.prototype.contains = function contains(x, y) { + var inside = false; + + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + + for (var i = 0, j = length - 1; i < length; j = i++) { + var xi = this.points[i * 2]; + var yi = this.points[i * 2 + 1]; + var xj = this.points[j * 2]; + var yj = this.points[j * 2 + 1]; + var intersect = yi > y !== yj > y && x < (xj - xi) * ((y - yi) / (yj - yi)) + xi; + + if (intersect) { + inside = !inside; + } + } + + return inside; + }; + + return Polygon; +}(); + +exports.default = Polygon; + +},{"../../const":44,"../Point":67}],72:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * + * @class + * @memberof PIXI + */ +var Rectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle + * @param {number} [width=0] - The overall width of this rectangle + * @param {number} [height=0] - The overall height of this rectangle + */ + function Rectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Rectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.RECT + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RECT; + } + + /** + * returns the left edge of the rectangle + * + * @member {number} + */ + + + /** + * Creates a clone of this Rectangle + * + * @return {PIXI.Rectangle} a copy of the rectangle + */ + Rectangle.prototype.clone = function clone() { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + + /** + * Copies another rectangle to this one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to copy. + * @return {PIXI.Rectangle} Returns itself. + */ + + + Rectangle.prototype.copy = function copy(rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + + return this; + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rectangle + */ + + + Rectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + + return false; + }; + + /** + * Pads the rectangle making it grow in all directions. + * + * @param {number} paddingX - The horizontal padding amount. + * @param {number} paddingY - The vertical padding amount. + */ + + + Rectangle.prototype.pad = function pad(paddingX, paddingY) { + paddingX = paddingX || 0; + paddingY = paddingY || (paddingY !== 0 ? paddingX : 0); + + this.x -= paddingX; + this.y -= paddingY; + + this.width += paddingX * 2; + this.height += paddingY * 2; + }; + + /** + * Fits this rectangle around the passed one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to fit. + */ + + + Rectangle.prototype.fit = function fit(rectangle) { + if (this.x < rectangle.x) { + this.width += this.x; + if (this.width < 0) { + this.width = 0; + } + + this.x = rectangle.x; + } + + if (this.y < rectangle.y) { + this.height += this.y; + if (this.height < 0) { + this.height = 0; + } + this.y = rectangle.y; + } + + if (this.x + this.width > rectangle.x + rectangle.width) { + this.width = rectangle.width - this.x; + if (this.width < 0) { + this.width = 0; + } + } + + if (this.y + this.height > rectangle.y + rectangle.height) { + this.height = rectangle.height - this.y; + if (this.height < 0) { + this.height = 0; + } + } + }; + + /** + * Enlarges this rectangle to include the passed rectangle. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to include. + */ + + + Rectangle.prototype.enlarge = function enlarge(rectangle) { + var x1 = Math.min(this.x, rectangle.x); + var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.min(this.y, rectangle.y); + var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); + + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + }; + + _createClass(Rectangle, [{ + key: 'left', + get: function get() { + return this.x; + } + + /** + * returns the right edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'right', + get: function get() { + return this.x + this.width; + } + + /** + * returns the top edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'top', + get: function get() { + return this.y; + } + + /** + * returns the bottom edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'bottom', + get: function get() { + return this.y + this.height; + } + + /** + * A constant empty rectangle. + * + * @static + * @constant + */ + + }], [{ + key: 'EMPTY', + get: function get() { + return new Rectangle(0, 0, 0, 0); + } + }]); + + return Rectangle; +}(); + +exports.default = Rectangle; + +},{"../../const":44}],73:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. + * + * @class + * @memberof PIXI + */ +var RoundedRectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle + * @param {number} [width=0] - The overall width of this rounded rectangle + * @param {number} [height=0] - The overall height of this rounded rectangle + * @param {number} [radius=20] - Controls the radius of the rounded corners + */ + function RoundedRectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var radius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 20; + + _classCallCheck(this, RoundedRectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * @member {number} + * @default 20 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readonly + * @default PIXI.SHAPES.RREC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RREC; + } + + /** + * Creates a clone of this Rounded Rectangle + * + * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle + */ + + + RoundedRectangle.prototype.clone = function clone() { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + */ + + + RoundedRectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + if (y >= this.y + this.radius && y <= this.y + this.height - this.radius || x >= this.x + this.radius && x <= this.x + this.width - this.radius) { + return true; + } + var dx = x - (this.x + this.radius); + var dy = y - (this.y + this.radius); + var radius2 = this.radius * this.radius; + + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.width - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dy = y - (this.y + this.height - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + } + } + + return false; + }; + + return RoundedRectangle; +}(); + +exports.default = RoundedRectangle; + +},{"../../const":44}],74:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _math = require('../math'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _Container = require('../display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMatrix = new _math.Matrix(); + +/** + * The SystemRenderer is the base for a Pixi Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.WebGLRenderer} which can be used for rendering a Pixi scene. + * + * @abstract + * @class + * @extends EventEmitter + * @memberof PIXI + */ + +var SystemRenderer = function (_EventEmitter) { + _inherits(SystemRenderer, _EventEmitter); + + /** + * @param {string} system - The name of the system this renderer is for. + * @param {number} [screenWidth=800] - the width of the screen + * @param {number} [screenHeight=600] - the height of the screen + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function SystemRenderer(system, screenWidth, screenHeight, options) { + _classCallCheck(this, SystemRenderer); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + (0, _utils.sayHello)(system); + + // prepare options + if (options) { + for (var i in _settings2.default.RENDER_OPTIONS) { + if (typeof options[i] === 'undefined') { + options[i] = _settings2.default.RENDER_OPTIONS[i]; + } + } + } else { + options = _settings2.default.RENDER_OPTIONS; + } + + /** + * The type of the renderer. + * + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.UNKNOWN; + + /** + * Measurements of the screen. (0, 0, screenWidth, screenHeight) + * + * Its safe to use as filterArea or hitArea for whole stage + * + * @member {PIXI.Rectangle} + */ + _this.screen = new _math.Rectangle(0, 0, screenWidth || 800, screenHeight || 600); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.view = options.view || document.createElement('canvas'); + + /** + * The resolution / device pixel ratio of the renderer + * + * @member {number} + * @default 1 + */ + _this.resolution = options.resolution || _settings2.default.RESOLUTION; + + /** + * Whether the render view is transparent + * + * @member {boolean} + */ + _this.transparent = options.transparent; + + /** + * Whether css dimensions of canvas view should be resized to screen dimensions automatically + * + * @member {boolean} + */ + _this.autoResize = options.autoResize || false; + + /** + * Tracks the blend modes useful for this renderer. + * + * @member {object} + */ + _this.blendModes = null; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent Pixi will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent Pixi will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example if + * your game has a canvas filling background image you often don't need this set. + * + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + * + * @member {boolean} + */ + _this.roundPixels = options.roundPixels; + + /** + * The background color as a number. + * + * @member {number} + * @private + */ + _this._backgroundColor = 0x000000; + + /** + * The background color as an [R, G, B] array. + * + * @member {number[]} + * @private + */ + _this._backgroundColorRgba = [0, 0, 0, 0]; + + /** + * The background color as a string. + * + * @member {string} + * @private + */ + _this._backgroundColorString = '#000000'; + + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + + /** + * This temporary display object used as the parent of the currently being rendered item + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._tempDisplayObjectParent = new _Container2.default(); + + /** + * The last root object that the renderer tried to render. + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._lastObjectRendered = _this._tempDisplayObjectParent; + return _this; + } + + /** + * Same as view.width, actual number of pixels in the canvas by horizontal + * + * @member {number} + * @readonly + * @default 800 + */ + + + /** + * Resizes the screen and canvas to the specified width and height + * Canvas dimensions are multiplied by resolution + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + SystemRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + this.screen.width = screenWidth; + this.screen.height = screenHeight; + + this.view.width = screenWidth * this.resolution; + this.view.height = screenHeight * this.resolution; + + if (this.autoResize) { + this.view.style.width = screenWidth + 'px'; + this.view.style.height = screenHeight + 'px'; + } + }; + + /** + * Useful function that returns a texture of the display object that can then be used to create sprites + * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. + * + * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from + * @param {number} scaleMode - Should be one of the scaleMode consts + * @param {number} resolution - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.Texture} a texture of the graphics object + */ + + + SystemRenderer.prototype.generateTexture = function generateTexture(displayObject, scaleMode, resolution) { + var bounds = displayObject.getLocalBounds(); + + var renderTexture = _RenderTexture2.default.create(bounds.width | 0, bounds.height | 0, scaleMode, resolution); + + tempMatrix.tx = -bounds.x; + tempMatrix.ty = -bounds.y; + + this.render(displayObject, renderTexture, false, tempMatrix, true); + + return renderTexture; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + SystemRenderer.prototype.destroy = function destroy(removeView) { + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } + + this.type = _const.RENDERER_TYPE.UNKNOWN; + + this.view = null; + + this.screen = null; + + this.resolution = 0; + + this.transparent = false; + + this.autoResize = false; + + this.blendModes = null; + + this.preserveDrawingBuffer = false; + this.clearBeforeRender = false; + + this.roundPixels = false; + + this._backgroundColor = 0; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + + this.backgroundColor = 0; + this._tempDisplayObjectParent = null; + this._lastObjectRendered = null; + }; + + /** + * The background color to fill if not transparent + * + * @member {number} + */ + + + _createClass(SystemRenderer, [{ + key: 'width', + get: function get() { + return this.view.width; + } + + /** + * Same as view.height, actual number of pixels in the canvas by vertical + * + * @member {number} + * @readonly + * @default 600 + */ + + }, { + key: 'height', + get: function get() { + return this.view.height; + } + }, { + key: 'backgroundColor', + get: function get() { + return this._backgroundColor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._backgroundColor = value; + this._backgroundColorString = (0, _utils.hex2string)(value); + (0, _utils.hex2rgb)(value, this._backgroundColorRgba); + } + }]); + + return SystemRenderer; +}(_eventemitter2.default); + +exports.default = SystemRenderer; + +},{"../const":44,"../display/Container":46,"../math":68,"../settings":99,"../textures/RenderTexture":110,"../utils":120,"eventemitter3":3}],75:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _CanvasMaskManager = require('./utils/CanvasMaskManager'); + +var _CanvasMaskManager2 = _interopRequireDefault(_CanvasMaskManager); + +var _CanvasRenderTarget = require('./utils/CanvasRenderTarget'); + +var _CanvasRenderTarget2 = _interopRequireDefault(_CanvasRenderTarget); + +var _mapCanvasBlendModesToPixi = require('./utils/mapCanvasBlendModesToPixi'); + +var _mapCanvasBlendModesToPixi2 = _interopRequireDefault(_mapCanvasBlendModesToPixi); + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should + * be used for browsers that do not support WebGL. Don't forget to add the CanvasRenderer.view to + * your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ +var CanvasRenderer = function (_SystemRenderer) { + _inherits(CanvasRenderer, _SystemRenderer); + + /** + * @param {number} [screenWidth=800] - the width of the screen + * @param {number} [screenHeight=600] - the height of the screen + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function CanvasRenderer(screenWidth, screenHeight) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + _classCallCheck(this, CanvasRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'Canvas', screenWidth, screenHeight, options)); + + _this.type = _const.RENDERER_TYPE.CANVAS; + + /** + * The canvas 2d context that everything is drawn with. + * + * @member {CanvasRenderingContext2D} + */ + _this.rootContext = _this.view.getContext('2d', { alpha: _this.transparent }); + + /** + * Boolean flag controlling canvas refresh. + * + * @member {boolean} + */ + _this.refresh = true; + + /** + * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. + * + * @member {PIXI.CanvasMaskManager} + */ + _this.maskManager = new _CanvasMaskManager2.default(_this); + + /** + * The canvas property used to set the canvas smoothing property. + * + * @member {string} + */ + _this.smoothProperty = 'imageSmoothingEnabled'; + + if (!_this.rootContext.imageSmoothingEnabled) { + if (_this.rootContext.webkitImageSmoothingEnabled) { + _this.smoothProperty = 'webkitImageSmoothingEnabled'; + } else if (_this.rootContext.mozImageSmoothingEnabled) { + _this.smoothProperty = 'mozImageSmoothingEnabled'; + } else if (_this.rootContext.oImageSmoothingEnabled) { + _this.smoothProperty = 'oImageSmoothingEnabled'; + } else if (_this.rootContext.msImageSmoothingEnabled) { + _this.smoothProperty = 'msImageSmoothingEnabled'; + } + } + + _this.initPlugins(); + + _this.blendModes = (0, _mapCanvasBlendModesToPixi2.default)(); + _this._activeBlendMode = null; + + _this.context = null; + _this.renderingToScreen = false; + + _this.resize(screenWidth, screenHeight); + return _this; + } + + /** + * Renders the object to this canvas view + * + * @param {PIXI.DisplayObject} displayObject - The object to be rendered + * @param {PIXI.RenderTexture} [renderTexture] - A render texture to be rendered to. + * If unset, it will render to the root context. + * @param {boolean} [clear=false] - Whether to clear the canvas before drawing + * @param {PIXI.Transform} [transform] - A transformation to be applied + * @param {boolean} [skipUpdateTransform=false] - Whether to skip the update transform + */ + + + CanvasRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!this.view) { + return; + } + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + var rootResolution = this.resolution; + + if (renderTexture) { + renderTexture = renderTexture.baseTexture || renderTexture; + + if (!renderTexture._canvasRenderTarget) { + renderTexture._canvasRenderTarget = new _CanvasRenderTarget2.default(renderTexture.width, renderTexture.height, renderTexture.resolution); + renderTexture.source = renderTexture._canvasRenderTarget.canvas; + renderTexture.valid = true; + } + + this.context = renderTexture._canvasRenderTarget.context; + this.resolution = renderTexture._canvasRenderTarget.resolution; + } else { + this.context = this.rootContext; + } + + var context = this.context; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + var tempWt = this._tempDisplayObjectParent.transform.worldTransform; + + if (transform) { + transform.copy(tempWt); + + // lets not forget to flag the parent transform as dirty... + this._tempDisplayObjectParent.transform._worldID = -1; + } else { + tempWt.identity(); + } + + displayObject.parent = this._tempDisplayObjectParent; + + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + context.setTransform(1, 0, 0, 1, 0, 0); + context.globalAlpha = 1; + context.globalCompositeOperation = this.blendModes[_const.BLEND_MODES.NORMAL]; + + if (navigator.isCocoonJS && this.view.screencanvas) { + context.fillStyle = 'black'; + context.clear(); + } + + if (clear !== undefined ? clear : this.clearBeforeRender) { + if (this.renderingToScreen) { + if (this.transparent) { + context.clearRect(0, 0, this.width, this.height); + } else { + context.fillStyle = this._backgroundColorString; + context.fillRect(0, 0, this.width, this.height); + } + } // else { + // TODO: implement background for CanvasRenderTarget or RenderTexture? + // } + } + + // TODO RENDER TARGET STUFF HERE.. + var tempContext = this.context; + + this.context = context; + displayObject.renderCanvas(this); + this.context = tempContext; + + this.resolution = rootResolution; + + this.emit('postrender'); + }; + + /** + * Clear the canvas of renderer. + * + * @param {string} [clearColor] - Clear the canvas with this color, except the canvas is transparent. + */ + + + CanvasRenderer.prototype.clear = function clear(clearColor) { + var context = this.context; + + clearColor = clearColor || this._backgroundColorString; + + if (!this.transparent && clearColor) { + context.fillStyle = clearColor; + context.fillRect(0, 0, this.width, this.height); + } else { + context.clearRect(0, 0, this.width, this.height); + } + }; + + /** + * Sets the blend mode of the renderer. + * + * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values. + */ + + + CanvasRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + if (this._activeBlendMode === blendMode) { + return; + } + + this._activeBlendMode = blendMode; + this.context.globalCompositeOperation = this.blendModes[blendMode]; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + CanvasRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // call the base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.context = null; + + this.refresh = true; + + this.maskManager.destroy(); + this.maskManager = null; + + this.smoothProperty = null; + }; + + /** + * Resizes the canvas view to the specified width and height. + * + * @extends PIXI.SystemRenderer#resize + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + CanvasRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + _SystemRenderer.prototype.resize.call(this, screenWidth, screenHeight); + + // reset the scale mode.. oddly this seems to be reset when the canvas is resized. + // surely a browser bug?? Let pixi fix that for you.. + if (this.smoothProperty) { + this.rootContext[this.smoothProperty] = _settings2.default.SCALE_MODE === _const.SCALE_MODES.LINEAR; + } + }; + + return CanvasRenderer; +}(_SystemRenderer3.default); + +exports.default = CanvasRenderer; + + +_utils.pluginTarget.mixin(CanvasRenderer); + +},{"../../const":44,"../../settings":99,"../../utils":120,"../SystemRenderer":74,"./utils/CanvasMaskManager":76,"./utils/CanvasRenderTarget":77,"./utils/mapCanvasBlendModesToPixi":79}],76:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A set of functions used to handle masking. + * + * @class + * @memberof PIXI + */ +var CanvasMaskManager = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + function CanvasMaskManager(renderer) { + _classCallCheck(this, CanvasMaskManager); + + this.renderer = renderer; + } + + /** + * This method adds it to the current stack of masks. + * + * @param {object} maskData - the maskData that will be pushed + */ + + + CanvasMaskManager.prototype.pushMask = function pushMask(maskData) { + var renderer = this.renderer; + + renderer.context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.transform.worldTransform; + var resolution = renderer.resolution; + + renderer.context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // TODO suport sprite alpha masks?? + // lots of effort required. If demand is great enough.. + if (!maskData._texture) { + this.renderGraphicsShape(maskData); + renderer.context.clip(); + } + + maskData.worldAlpha = cacheAlpha; + }; + + /** + * Renders a PIXI.Graphics shape. + * + * @param {PIXI.Graphics} graphics - The object to render. + */ + + + CanvasMaskManager.prototype.renderGraphicsShape = function renderGraphicsShape(graphics) { + var context = this.renderer.context; + var len = graphics.graphicsData.length; + + if (len === 0) { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === _const.SHAPES.POLY) { + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; j++) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) { + context.closePath(); + } + } else if (data.type === _const.SHAPES.RECT) { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } + }; + + /** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @param {PIXI.CanvasRenderer} renderer - The renderer context to use. + */ + + + CanvasMaskManager.prototype.popMask = function popMask(renderer) { + renderer.context.restore(); + }; + + /** + * Destroys this canvas mask manager. + * + */ + + + CanvasMaskManager.prototype.destroy = function destroy() { + /* empty */ + }; + + return CanvasMaskManager; +}(); + +exports.default = CanvasMaskManager; + +},{"../../../const":44}],77:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Creates a Canvas element of the given size. + * + * @class + * @memberof PIXI + */ +var CanvasRenderTarget = function () { + /** + * @param {number} width - the width for the newly created canvas + * @param {number} height - the height for the newly created canvas + * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + _classCallCheck(this, CanvasRenderTarget); + + /** + * The Canvas object that belongs to this CanvasRenderTarget. + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @member {CanvasRenderingContext2D} + */ + this.context = this.canvas.getContext('2d'); + + this.resolution = resolution || _settings2.default.RESOLUTION; + + this.resize(width, height); + } + + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * + * @private + */ + + + CanvasRenderTarget.prototype.clear = function clear() { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + + /** + * Resizes the canvas to the specified width and height. + * + * @param {number} width - the new width of the canvas + * @param {number} height - the new height of the canvas + */ + + + CanvasRenderTarget.prototype.resize = function resize(width, height) { + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; + }; + + /** + * Destroys this canvas. + * + */ + + + CanvasRenderTarget.prototype.destroy = function destroy() { + this.context = null; + this.canvas = null; + }; + + /** + * The width of the canvas buffer in pixels. + * + * @member {number} + */ + + + _createClass(CanvasRenderTarget, [{ + key: 'width', + get: function get() { + return this.canvas.width; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.width = val; + } + + /** + * The height of the canvas buffer in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.canvas.height; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.height = val; + } + }]); + + return CanvasRenderTarget; +}(); + +exports.default = CanvasRenderTarget; + +},{"../../../settings":99}],78:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = canUseNewCanvasBlendModes; +/** + * Creates a little colored canvas + * + * @ignore + * @param {string} color - The color to make the canvas + * @return {canvas} a small canvas element + */ +function createColoredCanvas(color) { + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.fillStyle = color; + context.fillRect(0, 0, 6, 1); + + return canvas; +} + +/** + * Checks whether the Canvas BlendModes are supported by the current browser + * + * @return {boolean} whether they are supported + */ +function canUseNewCanvasBlendModes() { + if (typeof document === 'undefined') { + return false; + } + + var magenta = createColoredCanvas('#ff00ff'); + var yellow = createColoredCanvas('#ffff00'); + + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.globalCompositeOperation = 'multiply'; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + var imageData = context.getImageData(2, 0, 1, 1); + + if (!imageData) { + return false; + } + + var data = imageData.data; + + return data[0] === 255 && data[1] === 0 && data[2] === 0; +} + +},{}],79:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapCanvasBlendModesToPixi; + +var _const = require('../../../const'); + +var _canUseNewCanvasBlendModes = require('./canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Maps blend combinations to Canvas. + * + * @memberof PIXI + * @function mapCanvasBlendModesToPixi + * @private + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapCanvasBlendModesToPixi() { + var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + + if ((0, _canUseNewCanvasBlendModes2.default)()) { + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'multiply'; + array[_const.BLEND_MODES.SCREEN] = 'screen'; + array[_const.BLEND_MODES.OVERLAY] = 'overlay'; + array[_const.BLEND_MODES.DARKEN] = 'darken'; + array[_const.BLEND_MODES.LIGHTEN] = 'lighten'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'color-dodge'; + array[_const.BLEND_MODES.COLOR_BURN] = 'color-burn'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'hard-light'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'soft-light'; + array[_const.BLEND_MODES.DIFFERENCE] = 'difference'; + array[_const.BLEND_MODES.EXCLUSION] = 'exclusion'; + array[_const.BLEND_MODES.HUE] = 'hue'; + array[_const.BLEND_MODES.SATURATION] = 'saturate'; + array[_const.BLEND_MODES.COLOR] = 'color'; + array[_const.BLEND_MODES.LUMINOSITY] = 'luminosity'; + } else { + // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'source-over'; + array[_const.BLEND_MODES.SCREEN] = 'source-over'; + array[_const.BLEND_MODES.OVERLAY] = 'source-over'; + array[_const.BLEND_MODES.DARKEN] = 'source-over'; + array[_const.BLEND_MODES.LIGHTEN] = 'source-over'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'source-over'; + array[_const.BLEND_MODES.COLOR_BURN] = 'source-over'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.DIFFERENCE] = 'source-over'; + array[_const.BLEND_MODES.EXCLUSION] = 'source-over'; + array[_const.BLEND_MODES.HUE] = 'source-over'; + array[_const.BLEND_MODES.SATURATION] = 'source-over'; + array[_const.BLEND_MODES.COLOR] = 'source-over'; + array[_const.BLEND_MODES.LUMINOSITY] = 'source-over'; + } + + return array; +} + +},{"../../../const":44,"./canUseNewCanvasBlendModes":78}],80:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged + * up with textures that are no longer being used. + * + * @class + * @memberof PIXI + */ +var TextureGarbageCollector = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function TextureGarbageCollector(renderer) { + _classCallCheck(this, TextureGarbageCollector); + + this.renderer = renderer; + + this.count = 0; + this.checkCount = 0; + this.maxIdle = _settings2.default.GC_MAX_IDLE; + this.checkCountMax = _settings2.default.GC_MAX_CHECK_COUNT; + this.mode = _settings2.default.GC_MODE; + } + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.update = function update() { + this.count++; + + if (this.mode === _const.GC_MODES.MANUAL) { + return; + } + + this.checkCount++; + + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + + this.run(); + } + }; + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.run = function run() { + var tm = this.renderer.textureManager; + var managedTextures = tm._managedTextures; + var wasRemoved = false; + + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + + // only supports non generated textures at the moment! + if (!texture._glRenderTargets && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + + if (wasRemoved) { + var j = 0; + + for (var _i = 0; _i < managedTextures.length; _i++) { + if (managedTextures[_i] !== null) { + managedTextures[j++] = managedTextures[_i]; + } + } + + managedTextures.length = j; + } + }; + + /** + * Removes all the textures within the specified displayObject and its children from the GPU + * + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + */ + + + TextureGarbageCollector.prototype.unload = function unload(displayObject) { + var tm = this.renderer.textureManager; + + // only destroy non generated textures + if (displayObject._texture && displayObject._texture._glRenderTargets) { + tm.destroyTexture(displayObject._texture, true); + } + + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + + return TextureGarbageCollector; +}(); + +exports.default = TextureGarbageCollector; + +},{"../../const":44,"../../settings":99}],81:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _const = require('../../const'); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _utils = require('../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a webGL Texture + * + * @class + * @memberof PIXI + */ +var TextureManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function TextureManager(renderer) { + _classCallCheck(this, TextureManager); + + /** + * A reference to the current renderer + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = renderer.gl; + + /** + * Track textures in the renderer so we can no longer listen to them on destruction. + * + * @member {Array<*>} + * @private + */ + this._managedTextures = []; + } + + /** + * Binds a texture. + * + */ + + + TextureManager.prototype.bindTexture = function bindTexture() {} + // empty + + + /** + * Gets a texture. + * + */ + ; + + TextureManager.prototype.getTexture = function getTexture() {} + // empty + + + /** + * Updates and/or Creates a WebGL texture for the renderer's context. + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update + * @param {number} location - the location the texture will be bound to. + * @return {GLTexture} The gl texture. + */ + ; + + TextureManager.prototype.updateTexture = function updateTexture(texture, location) { + // assume it good! + // texture = texture.baseTexture || texture; + + var gl = this.gl; + + var isRenderTexture = !!texture._glRenderTargets; + + if (!texture.hasLoaded) { + return null; + } + + var boundTextures = this.renderer.boundTextures; + + // if the location is undefined then this may have been called by n event. + // this being the case the texture may already be bound to a slot. As a texture can only be bound once + // we need to find its current location if it exists. + if (location === undefined) { + location = 0; + + // TODO maybe we can use texture bound ids later on... + // check if texture is already bound.. + for (var i = 0; i < boundTextures.length; ++i) { + if (boundTextures[i] === texture) { + location = i; + break; + } + } + } + + boundTextures[location] = texture; + + gl.activeTexture(gl.TEXTURE0 + location); + + var glTexture = texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!glTexture) { + if (isRenderTexture) { + var renderTarget = new _RenderTarget2.default(this.gl, texture.width, texture.height, texture.scaleMode, texture.resolution); + + renderTarget.resize(texture.width, texture.height); + texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget; + glTexture = renderTarget.texture; + } else { + glTexture = new _pixiGlCore.GLTexture(this.gl, null, null, null, null); + glTexture.bind(location); + glTexture.premultiplyAlpha = true; + glTexture.upload(texture.source); + } + + texture._glTextures[this.renderer.CONTEXT_UID] = glTexture; + + texture.on('update', this.updateTexture, this); + texture.on('dispose', this.destroyTexture, this); + + this._managedTextures.push(texture); + + if (texture.isPowerOfTwo) { + if (texture.mipmap) { + glTexture.enableMipmap(); + } + + if (texture.wrapMode === _const.WRAP_MODES.CLAMP) { + glTexture.enableWrapClamp(); + } else if (texture.wrapMode === _const.WRAP_MODES.REPEAT) { + glTexture.enableWrapRepeat(); + } else { + glTexture.enableWrapMirrorRepeat(); + } + } else { + glTexture.enableWrapClamp(); + } + + if (texture.scaleMode === _const.SCALE_MODES.NEAREST) { + glTexture.enableNearestScaling(); + } else { + glTexture.enableLinearScaling(); + } + } + // the texture already exists so we only need to update it.. + else if (isRenderTexture) { + texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height); + } else { + glTexture.upload(texture.source); + } + + return glTexture; + }; + + /** + * Deletes the texture from WebGL + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy + * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. + */ + + + TextureManager.prototype.destroyTexture = function destroyTexture(texture, skipRemove) { + texture = texture.baseTexture || texture; + + if (!texture.hasLoaded) { + return; + } + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + this.renderer.unbindTexture(texture); + + texture._glTextures[this.renderer.CONTEXT_UID].destroy(); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + + delete texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!skipRemove) { + var i = this._managedTextures.indexOf(texture); + + if (i !== -1) { + (0, _utils.removeItems)(this._managedTextures, i, 1); + } + } + } + }; + + /** + * Deletes all the textures from WebGL + */ + + + TextureManager.prototype.removeAll = function removeAll() { + // empty all the old gl textures as they are useless now + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + delete texture._glTextures[this.renderer.CONTEXT_UID]; + } + } + }; + + /** + * Destroys this manager and removes all its textures + */ + + + TextureManager.prototype.destroy = function destroy() { + // destroy managed textures + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + this.destroyTexture(texture, true); + + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + } + + this._managedTextures = null; + }; + + return TextureManager; +}(); + +exports.default = TextureManager; + +},{"../../const":44,"../../utils":120,"./utils/RenderTarget":94,"pixi-gl-core":12}],82:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _MaskManager = require('./managers/MaskManager'); + +var _MaskManager2 = _interopRequireDefault(_MaskManager); + +var _StencilManager = require('./managers/StencilManager'); + +var _StencilManager2 = _interopRequireDefault(_StencilManager); + +var _FilterManager = require('./managers/FilterManager'); + +var _FilterManager2 = _interopRequireDefault(_FilterManager); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _ObjectRenderer = require('./utils/ObjectRenderer'); + +var _ObjectRenderer2 = _interopRequireDefault(_ObjectRenderer); + +var _TextureManager = require('./TextureManager'); + +var _TextureManager2 = _interopRequireDefault(_TextureManager); + +var _BaseTexture = require('../../textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _TextureGarbageCollector = require('./TextureGarbageCollector'); + +var _TextureGarbageCollector2 = _interopRequireDefault(_TextureGarbageCollector); + +var _WebGLState = require('./WebGLState'); + +var _WebGLState2 = _interopRequireDefault(_WebGLState); + +var _mapWebGLDrawModesToPixi = require('./utils/mapWebGLDrawModesToPixi'); + +var _mapWebGLDrawModesToPixi2 = _interopRequireDefault(_mapWebGLDrawModesToPixi); + +var _validateContext = require('./utils/validateContext'); + +var _validateContext2 = _interopRequireDefault(_validateContext); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CONTEXT_UID = 0; + +/** + * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ + +var WebGLRenderer = function (_SystemRenderer) { + _inherits(WebGLRenderer, _SystemRenderer); + + /** + * + * @param {number} [screenWidth=800] - the width of the screen + * @param {number} [screenHeight=600] - the height of the screen + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias. If not available natively then FXAA + * antialiasing is used + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. + * The resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear + * the canvas or not before the new render pass. If you wish to set this to false, you *must* set + * preserveDrawingBuffer to `true`. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when + * rendering, stopping pixel interpolation. + * @param {boolean} [options.legacy=false] - If true Pixi will aim to ensure compatibility + * with older / less advanced devices. If you experiance unexplained flickering try setting this to true. + */ + function WebGLRenderer(screenWidth, screenHeight) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + _classCallCheck(this, WebGLRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'WebGL', screenWidth, screenHeight, options)); + + _this.legacy = !!options.legacy; + + if (_this.legacy) { + _pixiGlCore2.default.VertexArrayObject.FORCE_NATIVE = true; + } + + /** + * The type of this renderer as a standardised const + * + * @member {number} + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.WEBGL; + + _this.handleContextLost = _this.handleContextLost.bind(_this); + _this.handleContextRestored = _this.handleContextRestored.bind(_this); + + _this.view.addEventListener('webglcontextlost', _this.handleContextLost, false); + _this.view.addEventListener('webglcontextrestored', _this.handleContextRestored, false); + + /** + * The options passed in to create a new webgl context. + * + * @member {object} + * @private + */ + _this._contextOptions = { + alpha: _this.transparent, + antialias: options.antialias, + premultipliedAlpha: _this.transparent && _this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: options.preserveDrawingBuffer + }; + + _this._backgroundColorRgba[3] = _this.transparent ? 0 : 1; + + /** + * Manages the masks using the stencil buffer. + * + * @member {PIXI.MaskManager} + */ + _this.maskManager = new _MaskManager2.default(_this); + + /** + * Manages the stencil buffer. + * + * @member {PIXI.StencilManager} + */ + _this.stencilManager = new _StencilManager2.default(_this); + + /** + * An empty renderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.emptyRenderer = new _ObjectRenderer2.default(_this); + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.currentRenderer = _this.emptyRenderer; + + _this.initPlugins(); + + /** + * The current WebGL rendering context, it is created here + * + * @member {WebGLRenderingContext} + */ + // initialize the context so it is ready for the managers. + if (options.context) { + // checks to see if a context is valid.. + (0, _validateContext2.default)(options.context); + } + + _this.gl = options.context || _pixiGlCore2.default.createContext(_this.view, _this._contextOptions); + + _this.CONTEXT_UID = CONTEXT_UID++; + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.WebGLState} + */ + _this.state = new _WebGLState2.default(_this.gl); + + _this.renderingToScreen = true; + + /** + * Holds the current state of textures bound to the GPU. + * @type {Array} + */ + _this.boundTextures = null; + + /** + * Holds the current shader + * + * @member {PIXI.Shader} + */ + _this._activeShader = null; + + _this._activeVao = null; + + /** + * Holds the current render target + * + * @member {PIXI.RenderTarget} + */ + _this._activeRenderTarget = null; + + _this._initContext(); + + /** + * Manages the filters. + * + * @member {PIXI.FilterManager} + */ + _this.filterManager = new _FilterManager2.default(_this); + // map some webGL blend and drawmodes.. + _this.drawModes = (0, _mapWebGLDrawModesToPixi2.default)(_this.gl); + + _this._nextTextureLocation = 0; + + _this.setBlendMode(0); + return _this; + } + + /** + * Creates the WebGL context + * + * @private + */ + + + WebGLRenderer.prototype._initContext = function _initContext() { + var gl = this.gl; + + // restore a context if it was previously lost + if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').restoreContext(); + } + + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + + this.boundTextures = new Array(maxTextures); + this.emptyTextures = new Array(maxTextures); + + // create a texture manager... + this.textureManager = new _TextureManager2.default(this); + this.textureGC = new _TextureGarbageCollector2.default(this); + + this.state.resetToDefault(); + + this.rootRenderTarget = new _RenderTarget2.default(gl, this.width, this.height, null, this.resolution, true); + this.rootRenderTarget.clearColor = this._backgroundColorRgba; + + this.bindRenderTarget(this.rootRenderTarget); + + // now lets fill up the textures with empty ones! + var emptyGLTexture = new _pixiGlCore2.default.GLTexture.fromData(gl, null, 1, 1); + + var tempObj = { _glTextures: {} }; + + tempObj._glTextures[this.CONTEXT_UID] = {}; + + for (var i = 0; i < maxTextures; i++) { + var empty = new _BaseTexture2.default(); + + empty._glTextures[this.CONTEXT_UID] = emptyGLTexture; + + this.boundTextures[i] = tempObj; + this.emptyTextures[i] = empty; + this.bindTexture(null, i); + } + + this.emit('context', gl); + + // setup the width/height properties and gl viewport + this.resize(this.screen.width, this.screen.height); + }; + + /** + * Renders the object to its webGL view + * + * @param {PIXI.DisplayObject} displayObject - the object to be rendered + * @param {PIXI.RenderTexture} renderTexture - The render texture to render to. + * @param {boolean} [clear] - Should the canvas be cleared before the new render + * @param {PIXI.Transform} [transform] - A transform to apply to the render texture before rendering. + * @param {boolean} [skipUpdateTransform] - Should we skip the update transform pass? + */ + + + WebGLRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + // no point rendering if our context has been blown up! + if (!this.gl || this.gl.isContextLost()) { + return; + } + + this._nextTextureLocation = 0; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + this.bindRenderTexture(renderTexture, transform); + + this.currentRenderer.start(); + + if (clear !== undefined ? clear : this.clearBeforeRender) { + this._activeRenderTarget.clear(); + } + + displayObject.renderWebGL(this); + + // apply transform.. + this.currentRenderer.flush(); + + // this.setObjectRenderer(this.emptyRenderer); + + this.textureGC.update(); + + this.emit('postrender'); + }; + + /** + * Changes the current renderer to the one given in parameter + * + * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. + */ + + + WebGLRenderer.prototype.setObjectRenderer = function setObjectRenderer(objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; + + /** + * This should be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + * + */ + + + WebGLRenderer.prototype.flush = function flush() { + this.setObjectRenderer(this.emptyRenderer); + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + WebGLRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + // if(width * this.resolution === this.width && height * this.resolution === this.height)return; + + _SystemRenderer3.default.prototype.resize.call(this, screenWidth, screenHeight); + + this.rootRenderTarget.resize(screenWidth, screenHeight); + + if (this._activeRenderTarget === this.rootRenderTarget) { + this.rootRenderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true); + } + } + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} blendMode - the desired blend mode + */ + + + WebGLRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + this.state.setBlendMode(blendMode); + }; + + /** + * Erases the active render target and fills the drawing area with a colour + * + * @param {number} [clearColor] - The colour + */ + + + WebGLRenderer.prototype.clear = function clear(clearColor) { + this._activeRenderTarget.clear(clearColor); + }; + + /** + * Sets the transform of the active render target to the given matrix + * + * @param {PIXI.Matrix} matrix - The transformation matrix + */ + + + WebGLRenderer.prototype.setTransform = function setTransform(matrix) { + this._activeRenderTarget.transform = matrix; + }; + + /** + * Erases the render texture and fills the drawing area with a colour + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to clear + * @param {number} [clearColor] - The colour + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.clearRenderTexture = function clearRenderTexture(renderTexture, clearColor) { + var baseTexture = renderTexture.baseTexture; + var renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + + if (renderTarget) { + renderTarget.clear(clearColor); + } + + return this; + }; + + /** + * Binds a render texture for rendering + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to render + * @param {PIXI.Transform} transform - The transform to be applied to the render texture + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTexture = function bindRenderTexture(renderTexture, transform) { + var renderTarget = void 0; + + if (renderTexture) { + var baseTexture = renderTexture.baseTexture; + + if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) { + // bind the current texture + this.textureManager.updateTexture(baseTexture, 0); + } + + this.unbindTexture(baseTexture); + + renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + renderTarget.setFrame(renderTexture.frame); + } else { + renderTarget = this.rootRenderTarget; + } + + renderTarget.transform = transform; + this.bindRenderTarget(renderTarget); + + return this; + }; + + /** + * Changes the current render target to the one given in parameter + * + * @param {PIXI.RenderTarget} renderTarget - the new render target + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTarget = function bindRenderTarget(renderTarget) { + if (renderTarget !== this._activeRenderTarget) { + this._activeRenderTarget = renderTarget; + renderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true); + } + + this.stencilManager.setMaskStack(renderTarget.stencilMaskStack); + } + + return this; + }; + + /** + * Changes the current shader to the one given in parameter + * + * @param {PIXI.Shader} shader - the new shader + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindShader = function bindShader(shader) { + // TODO cache + if (this._activeShader !== shader) { + this._activeShader = shader; + shader.bind(); + + // automatically set the projection matrix + shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(true); + } + + return this; + }; + + /** + * Binds the texture. This will return the location of the bound texture. + * It may not be the same as the one you pass in. This is due to optimisation that prevents + * needless binding of textures. For example if the texture is already bound it will return the + * current location of the texture instead of the one provided. To bypass this use force location + * + * @param {PIXI.Texture} texture - the new texture + * @param {number} location - the suggested texture location + * @param {boolean} forceLocation - force the location + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindTexture = function bindTexture(texture, location, forceLocation) { + texture = texture || this.emptyTextures[location]; + texture = texture.baseTexture || texture; + texture.touched = this.textureGC.count; + + if (!forceLocation) { + // TODO - maybe look into adding boundIds.. save us the loop? + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + return i; + } + } + + if (location === undefined) { + this._nextTextureLocation++; + this._nextTextureLocation %= this.boundTextures.length; + location = this.boundTextures.length - this._nextTextureLocation - 1; + } + } else { + location = location || 0; + } + + var gl = this.gl; + var glTexture = texture._glTextures[this.CONTEXT_UID]; + + if (!glTexture) { + // this will also bind the texture.. + this.textureManager.updateTexture(texture, location); + } else { + // bind the current texture + this.boundTextures[location] = texture; + gl.activeTexture(gl.TEXTURE0 + location); + gl.bindTexture(gl.TEXTURE_2D, glTexture.texture); + } + + return location; + }; + + /** + * unbinds the texture ... + * + * @param {PIXI.Texture} texture - the texture to unbind + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.unbindTexture = function unbindTexture(texture) { + var gl = this.gl; + + texture = texture.baseTexture || texture; + + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + this.boundTextures[i] = this.emptyTextures[i]; + + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[i]._glTextures[this.CONTEXT_UID].texture); + } + } + + return this; + }; + + /** + * Creates a new VAO from this renderer's context and state. + * + * @return {VertexArrayObject} The new VAO. + */ + + + WebGLRenderer.prototype.createVao = function createVao() { + return new _pixiGlCore2.default.VertexArrayObject(this.gl, this.state.attribState); + }; + + /** + * Changes the current Vao to the one given in parameter + * + * @param {PIXI.VertexArrayObject} vao - the new Vao + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindVao = function bindVao(vao) { + if (this._activeVao === vao) { + return this; + } + + if (vao) { + vao.bind(); + } else if (this._activeVao) { + // TODO this should always be true i think? + this._activeVao.unbind(); + } + + this._activeVao = vao; + + return this; + }; + + /** + * Resets the WebGL state so you can render things however you fancy! + * + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.reset = function reset() { + this.setObjectRenderer(this.emptyRenderer); + + this._activeShader = null; + this._activeRenderTarget = this.rootRenderTarget; + + // bind the main frame buffer (the screen); + this.rootRenderTarget.activate(); + + this.state.resetToDefault(); + + return this; + }; + + /** + * Handles a lost webgl context + * + * @private + * @param {WebGLContextEvent} event - The context lost event. + */ + + + WebGLRenderer.prototype.handleContextLost = function handleContextLost(event) { + event.preventDefault(); + }; + + /** + * Handles a restored webgl context + * + * @private + */ + + + WebGLRenderer.prototype.handleContextRestored = function handleContextRestored() { + this._initContext(); + this.textureManager.removeAll(); + }; + + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + + + WebGLRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // remove listeners + this.view.removeEventListener('webglcontextlost', this.handleContextLost); + this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); + + this.textureManager.destroy(); + + // call base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.uid = 0; + + // destroy the managers + this.maskManager.destroy(); + this.stencilManager.destroy(); + this.filterManager.destroy(); + + this.maskManager = null; + this.filterManager = null; + this.textureManager = null; + this.currentRenderer = null; + + this.handleContextLost = null; + this.handleContextRestored = null; + + this._contextOptions = null; + this.gl.useProgram(null); + + if (this.gl.getExtension('WEBGL_lose_context')) { + this.gl.getExtension('WEBGL_lose_context').loseContext(); + } + + this.gl = null; + + // this = null; + }; + + return WebGLRenderer; +}(_SystemRenderer3.default); + +exports.default = WebGLRenderer; + + +_utils.pluginTarget.mixin(WebGLRenderer); + +},{"../../const":44,"../../textures/BaseTexture":109,"../../utils":120,"../SystemRenderer":74,"./TextureGarbageCollector":80,"./TextureManager":81,"./WebGLState":83,"./managers/FilterManager":88,"./managers/MaskManager":89,"./managers/StencilManager":90,"./utils/ObjectRenderer":92,"./utils/RenderTarget":94,"./utils/mapWebGLDrawModesToPixi":97,"./utils/validateContext":98,"pixi-gl-core":12}],83:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); + +var _mapWebGLBlendModesToPixi2 = _interopRequireDefault(_mapWebGLBlendModesToPixi); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var BLEND = 0; +var DEPTH_TEST = 1; +var FRONT_FACE = 2; +var CULL_FACE = 3; +var BLEND_FUNC = 4; + +/** + * A WebGL state machines + * + * @memberof PIXI + * @class + */ + +var WebGLState = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + */ + function WebGLState(gl) { + _classCallCheck(this, WebGLState); + + /** + * The current active state + * + * @member {Uint8Array} + */ + this.activeState = new Uint8Array(16); + + /** + * The default state + * + * @member {Uint8Array} + */ + this.defaultState = new Uint8Array(16); + + // default blend mode.. + this.defaultState[0] = 1; + + /** + * The current state index in the stack + * + * @member {number} + * @private + */ + this.stackIndex = 0; + + /** + * The stack holding all the different states + * + * @member {Array<*>} + * @private + */ + this.stack = []; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + this.attribState = { + tempAttribState: new Array(this.maxAttribs), + attribState: new Array(this.maxAttribs) + }; + + this.blendModes = (0, _mapWebGLBlendModesToPixi2.default)(gl); + + // check we have vao.. + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || gl.getExtension('MOZ_OES_vertex_array_object') || gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + /** + * Pushes a new active state + */ + + + WebGLState.prototype.push = function push() { + // next state.. + var state = this.stack[this.stackIndex]; + + if (!state) { + state = this.stack[this.stackIndex] = new Uint8Array(16); + } + + ++this.stackIndex; + + // copy state.. + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) { + state[i] = this.activeState[i]; + } + }; + + /** + * Pops a state out + */ + + + WebGLState.prototype.pop = function pop() { + var state = this.stack[--this.stackIndex]; + + this.setState(state); + }; + + /** + * Sets the current state + * + * @param {*} state - The state to set. + */ + + + WebGLState.prototype.setState = function setState(state) { + this.setBlend(state[BLEND]); + this.setDepthTest(state[DEPTH_TEST]); + this.setFrontFace(state[FRONT_FACE]); + this.setCullFace(state[CULL_FACE]); + this.setBlendMode(state[BLEND_FUNC]); + }; + + /** + * Enables or disabled blending. + * + * @param {boolean} value - Turn on or off webgl blending. + */ + + + WebGLState.prototype.setBlend = function setBlend(value) { + value = value ? 1 : 0; + + if (this.activeState[BLEND] === value) { + return; + } + + this.activeState[BLEND] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + }; + + /** + * Sets the blend mode. + * + * @param {number} value - The blend mode to set to. + */ + + + WebGLState.prototype.setBlendMode = function setBlendMode(value) { + if (value === this.activeState[BLEND_FUNC]) { + return; + } + + this.activeState[BLEND_FUNC] = value; + + this.gl.blendFunc(this.blendModes[value][0], this.blendModes[value][1]); + }; + + /** + * Sets whether to enable or disable depth test. + * + * @param {boolean} value - Turn on or off webgl depth testing. + */ + + + WebGLState.prototype.setDepthTest = function setDepthTest(value) { + value = value ? 1 : 0; + + if (this.activeState[DEPTH_TEST] === value) { + return; + } + + this.activeState[DEPTH_TEST] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + }; + + /** + * Sets whether to enable or disable cull face. + * + * @param {boolean} value - Turn on or off webgl cull face. + */ + + + WebGLState.prototype.setCullFace = function setCullFace(value) { + value = value ? 1 : 0; + + if (this.activeState[CULL_FACE] === value) { + return; + } + + this.activeState[CULL_FACE] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + }; + + /** + * Sets the gl front face. + * + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ + + + WebGLState.prototype.setFrontFace = function setFrontFace(value) { + value = value ? 1 : 0; + + if (this.activeState[FRONT_FACE] === value) { + return; + } + + this.activeState[FRONT_FACE] = value; + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); + }; + + /** + * Disables all the vaos in use + * + */ + + + WebGLState.prototype.resetAttributes = function resetAttributes() { + for (var i = 0; i < this.attribState.tempAttribState.length; i++) { + this.attribState.tempAttribState[i] = 0; + } + + for (var _i = 0; _i < this.attribState.attribState.length; _i++) { + this.attribState.attribState[_i] = 0; + } + + // im going to assume one is always active for performance reasons. + for (var _i2 = 1; _i2 < this.maxAttribs; _i2++) { + this.gl.disableVertexAttribArray(_i2); + } + }; + + // used + /** + * Resets all the logic and disables the vaos + */ + + + WebGLState.prototype.resetToDefault = function resetToDefault() { + // unbind any VAO if they exist.. + if (this.nativeVaoExtension) { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + // reset all attributes.. + this.resetAttributes(); + + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; ++i) { + this.activeState[i] = 32; + } + + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + + this.setState(this.defaultState); + }; + + return WebGLState; +}(); + +exports.default = WebGLState; + +},{"./utils/mapWebGLBlendModesToPixi":96}],84:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _extractUniformsFromSrc = require('./extractUniformsFromSrc'); + +var _extractUniformsFromSrc2 = _interopRequireDefault(_extractUniformsFromSrc); + +var _utils = require('../../../utils'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SOURCE_KEY_MAP = {}; + +// let math = require('../../../math'); +/** + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ + +var Filter = function () { + /** + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. + */ + function Filter(vertexSrc, fragmentSrc, uniforms) { + _classCallCheck(this, Filter); + + /** + * The vertex shader. + * + * @member {string} + */ + this.vertexSrc = vertexSrc || Filter.defaultVertexSrc; + + /** + * The fragment shader. + * + * @member {string} + */ + this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc; + + this.blendMode = _const.BLEND_MODES.NORMAL; + + this.uniformData = uniforms || (0, _extractUniformsFromSrc2.default)(this.vertexSrc, this.fragmentSrc, 'projectionMatrix|uSampler'); + + /** + * An object containing the current values of custom uniforms. + * @example Updating the value of a custom uniform + * filter.uniforms.time = performance.now(); + * + * @member {object} + */ + this.uniforms = {}; + + for (var i in this.uniformData) { + this.uniforms[i] = this.uniformData[i].value; + } + + // this is where we store shader references.. + // TODO we could cache this! + this.glShaders = {}; + + // used for cacheing.. sure there is a better way! + if (!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) { + SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = (0, _utils.uid)(); + } + + this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]; + + /** + * The padding of the filter. Some filters require extra space to breath such as a blur. + * Increasing this will add extra width and height to the bounds of the object that the + * filter is applied to. + * + * @member {number} + */ + this.padding = 4; + + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + * + * @member {number} + */ + this.resolution = _settings2.default.RESOLUTION; + + /** + * If enabled is true the filter is applied, if false it will not. + * + * @member {boolean} + */ + this.enabled = true; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + Filter.prototype.apply = function apply(filterManager, input, output, clear) { + // --- // + // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); + + // do as you please! + + filterManager.applyFilter(this, input, output, clear); + + // or just do a regular render.. + }; + + /** + * The default vertex shader source + * + * @static + * @constant + */ + + + _createClass(Filter, null, [{ + key: 'defaultVertexSrc', + get: function get() { + return ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform mat3 projectionMatrix;', 'uniform mat3 filterMatrix;', 'varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;', ' vTextureCoord = aTextureCoord ;', '}'].join('\n'); + } + + /** + * The default fragment shader source + * + * @static + * @constant + */ + + }, { + key: 'defaultFragmentSrc', + get: function get() { + return ['varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'uniform sampler2D uSampler;', 'uniform sampler2D filterSampler;', 'void main(void){', ' vec4 masky = texture2D(filterSampler, vFilterCoord);', ' vec4 sample = texture2D(uSampler, vTextureCoord);', ' vec4 color;', ' if(mod(vFilterCoord.x, 1.0) > 0.5)', ' {', ' color = vec4(1.0, 0.0, 0.0, 1.0);', ' }', ' else', ' {', ' color = vec4(0.0, 1.0, 0.0, 1.0);', ' }', + // ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', + ' gl_FragColor = mix(sample, masky, 0.5);', ' gl_FragColor *= sample.a;', '}'].join('\n'); + } + }]); + + return Filter; +}(); + +exports.default = Filter; + +},{"../../../const":44,"../../../settings":99,"../../../utils":120,"./extractUniformsFromSrc":85}],85:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = extractUniformsFromSrc; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var defaultValue = _pixiGlCore2.default.shader.defaultValue; + +function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) { + var vertUniforms = extractUniformsFromString(vertexSrc, mask); + var fragUniforms = extractUniformsFromString(fragmentSrc, mask); + + return Object.assign(vertUniforms, fragUniforms); +} + +function extractUniformsFromString(string) { + var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea)$'); + + var uniforms = {}; + var nameSplit = void 0; + + // clean the lines a little - remove extra spaces / tabs etc + // then split along ';' + var lines = string.replace(/\s+/g, ' ').split(/\s*;\s*/); + + // loop through.. + for (var i = 0; i < lines.length; i++) { + var line = lines[i].trim(); + + if (line.indexOf('uniform') > -1) { + var splitLine = line.split(' '); + var type = splitLine[1]; + + var name = splitLine[2]; + var size = 1; + + if (name.indexOf('[') > -1) { + // array! + nameSplit = name.split(/\[|]/); + name = nameSplit[0]; + size *= Number(nameSplit[1]); + } + + if (!name.match(maskRegex)) { + uniforms[name] = { + value: defaultValue(type, size), + name: name, + type: type + }; + } + } + } + + return uniforms; +} + +},{"pixi-gl-core":12}],86:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.calculateScreenSpaceMatrix = calculateScreenSpaceMatrix; +exports.calculateNormalizedScreenSpaceMatrix = calculateNormalizedScreenSpaceMatrix; +exports.calculateSpriteMatrix = calculateSpriteMatrix; + +var _math = require('../../../math'); + +/* + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// this returns a matrix that will normalise map filter cords in the filter to screen space +function calculateScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + // let worldTransform = sprite.worldTransform.copy(Matrix.TEMP_MATRIX), + // let texture = {width:1136, height:700};//sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(textureSize.width, textureSize.height); + + return mappedMatrix; +} + +function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + var translateScaleX = textureSize.width / filterArea.width; + var translateScaleY = textureSize.height / filterArea.height; + + mappedMatrix.scale(translateScaleX, translateScaleY); + + return mappedMatrix; +} + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +function calculateSpriteMatrix(outputMatrix, filterArea, textureSize, sprite) { + var worldTransform = sprite.worldTransform.copy(_math.Matrix.TEMP_MATRIX); + var texture = sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + // scale.. + var ratio = textureSize.height / textureSize.width; + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(1, ratio); + + var translateScaleX = textureSize.width / texture.width; + var translateScaleY = textureSize.height / texture.height; + + worldTransform.tx /= texture.width * translateScaleX; + + // this...? free beer for anyone who can explain why this makes sense! + worldTransform.ty /= texture.width * translateScaleX; + // worldTransform.ty /= texture.height * translateScaleY; + + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + + // apply inverse scale.. + mappedMatrix.scale(1, 1 / ratio); + + mappedMatrix.scale(translateScaleX, translateScaleY); + + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; +} + +},{"../../../math":68}],87:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Filter2 = require('../Filter'); + +var _Filter3 = _interopRequireDefault(_Filter2); + +var _math = require('../../../../math'); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The SpriteMaskFilter class + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + */ +var SpriteMaskFilter = function (_Filter) { + _inherits(SpriteMaskFilter, _Filter); + + /** + * @param {PIXI.Sprite} sprite - the target sprite + */ + function SpriteMaskFilter(sprite) { + _classCallCheck(this, SpriteMaskFilter); + + var maskMatrix = new _math.Matrix(); + + var _this = _possibleConstructorReturn(this, _Filter.call(this, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n', 'varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n')); + + sprite.renderable = false; + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + return _this; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + */ + + + SpriteMaskFilter.prototype.apply = function apply(filterManager, input, output) { + var maskSprite = this.maskSprite; + + this.uniforms.mask = maskSprite._texture; + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite); + this.uniforms.alpha = maskSprite.worldAlpha; + + filterManager.applyFilter(this, input, output); + }; + + return SpriteMaskFilter; +}(_Filter3.default); + +exports.default = SpriteMaskFilter; + +},{"../../../../math":68,"../Filter":84,"path":22}],88:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _RenderTarget = require('../utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _Quad = require('../utils/Quad'); + +var _Quad2 = _interopRequireDefault(_Quad); + +var _math = require('../../../math'); + +var _Shader = require('../../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _filterTransforms = require('../filters/filterTransforms'); + +var filterTransforms = _interopRequireWildcard(_filterTransforms); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @ignore + * @class + */ +var FilterState = +/** + * + */ +function FilterState() { + _classCallCheck(this, FilterState); + + this.renderTarget = null; + this.sourceFrame = new _math.Rectangle(); + this.destinationFrame = new _math.Rectangle(); + this.filters = []; + this.target = null; + this.resolution = 1; +}; + +/** + * @class + * @memberof PIXI + * @extends PIXI.WebGLManager + */ + + +var FilterManager = function (_WebGLManager) { + _inherits(FilterManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function FilterManager(renderer) { + _classCallCheck(this, FilterManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.gl = _this.renderer.gl; + // know about sprites! + _this.quad = new _Quad2.default(_this.gl, renderer.state.attribState); + + _this.shaderCache = {}; + // todo add default! + _this.pool = {}; + + _this.filterData = null; + return _this; + } + + /** + * Adds a new filter to the manager. + * + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param {PIXI.Filter[]} filters - The filters to apply. + */ + + + FilterManager.prototype.pushFilter = function pushFilter(target, filters) { + var renderer = this.renderer; + + var filterData = this.filterData; + + if (!filterData) { + filterData = this.renderer._activeRenderTarget.filterStack; + + // add new stack + var filterState = new FilterState(); + + filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; + filterState.renderTarget = renderer._activeRenderTarget; + + this.renderer._activeRenderTarget.filterData = filterData = { + index: 0, + stack: [filterState] + }; + + this.filterData = filterData; + } + + // get the current filter state.. + var currentState = filterData.stack[++filterData.index]; + + if (!currentState) { + currentState = filterData.stack[filterData.index] = new FilterState(); + } + + // for now we go off the filter of the first resolution.. + var resolution = filters[0].resolution; + var padding = filters[0].padding | 0; + var targetBounds = target.filterArea || target.getBounds(true); + var sourceFrame = currentState.sourceFrame; + var destinationFrame = currentState.destinationFrame; + + sourceFrame.x = (targetBounds.x * resolution | 0) / resolution; + sourceFrame.y = (targetBounds.y * resolution | 0) / resolution; + sourceFrame.width = (targetBounds.width * resolution | 0) / resolution; + sourceFrame.height = (targetBounds.height * resolution | 0) / resolution; + + if (filterData.stack[0].renderTarget.transform) {// + + // TODO we should fit the rect around the transform.. + } else { + sourceFrame.fit(filterData.stack[0].destinationFrame); + } + + // lets apply the padding After we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + sourceFrame.pad(padding); + + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + + // lets play the padding after we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + + var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); + + currentState.target = target; + currentState.filters = filters; + currentState.resolution = resolution; + currentState.renderTarget = renderTarget; + + // bind the render target to draw the shape in the top corner.. + + renderTarget.setFrame(destinationFrame, sourceFrame); + + // bind the render target + renderer.bindRenderTarget(renderTarget); + renderTarget.clear(); + }; + + /** + * Pops off the filter and applies it. + * + */ + + + FilterManager.prototype.popFilter = function popFilter() { + var filterData = this.filterData; + + var lastState = filterData.stack[filterData.index - 1]; + var currentState = filterData.stack[filterData.index]; + + this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); + + var filters = currentState.filters; + + if (filters.length === 1) { + filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false); + this.freePotRenderTarget(currentState.renderTarget); + } else { + var flip = currentState.renderTarget; + var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, currentState.resolution); + + flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + // finally lets clear the render target before drawing to it.. + flop.clear(); + + var i = 0; + + for (i = 0; i < filters.length - 1; ++i) { + filters[i].apply(this, flip, flop, true); + + var t = flip; + + flip = flop; + flop = t; + } + + filters[i].apply(this, flip, lastState.renderTarget, false); + + this.freePotRenderTarget(flip); + this.freePotRenderTarget(flop); + } + + filterData.index--; + + if (filterData.index === 0) { + this.filterData = null; + } + }; + + /** + * Draws a filter. + * + * @param {PIXI.Filter} filter - The filter to draw. + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + FilterManager.prototype.applyFilter = function applyFilter(filter, input, output, clear) { + var renderer = this.renderer; + var gl = renderer.gl; + + var shader = filter.glShaders[renderer.CONTEXT_UID]; + + // cacheing.. + if (!shader) { + if (filter.glShaderKey) { + shader = this.shaderCache[filter.glShaderKey]; + + if (!shader) { + shader = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + + filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = shader; + } + } else { + shader = filter.glShaders[renderer.CONTEXT_UID] = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + } + + // TODO - this only needs to be done once? + renderer.bindVao(null); + + this.quad.initVao(shader); + } + + renderer.bindVao(this.quad.vao); + + renderer.bindRenderTarget(output); + + if (clear) { + gl.disable(gl.SCISSOR_TEST); + renderer.clear(); // [1, 1, 1, 1]); + gl.enable(gl.SCISSOR_TEST); + } + + // in case the render target is being masked using a scissor rect + if (output === renderer.maskManager.scissorRenderTarget) { + renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); + } + + renderer.bindShader(shader); + + // free unit 0 for us, doesn't matter what was there + // don't try to restore it, because syncUniforms can upload it to another slot + // and it'll be a problem + var tex = this.renderer.emptyTextures[0]; + + this.renderer.boundTextures[0] = tex; + // this syncs the pixi filters uniforms with glsl uniforms + this.syncUniforms(shader, filter); + + renderer.state.setBlendMode(filter.blendMode); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, input.texture.texture); + + this.quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + }; + + /** + * Uploads the uniforms of the filter. + * + * @param {GLShader} shader - The underlying gl shader. + * @param {PIXI.Filter} filter - The filter we are synchronizing. + */ + + + FilterManager.prototype.syncUniforms = function syncUniforms(shader, filter) { + var uniformData = filter.uniformData; + var uniforms = filter.uniforms; + + // 0 is reserved for the pixi texture so we start at 1! + var textureCount = 1; + var currentState = void 0; + + if (uniforms.filterArea) { + currentState = this.filterData.stack[this.filterData.index]; + + var filterArea = uniforms.filterArea; + + filterArea[0] = currentState.renderTarget.size.width; + filterArea[1] = currentState.renderTarget.size.height; + filterArea[2] = currentState.sourceFrame.x; + filterArea[3] = currentState.sourceFrame.y; + + shader.uniforms.filterArea = filterArea; + } + + // use this to clamp displaced texture coords so they belong to filterArea + // see displacementFilter fragment shader for an example + if (uniforms.filterClamp) { + currentState = this.filterData.stack[this.filterData.index]; + + var filterClamp = uniforms.filterClamp; + + filterClamp[0] = 0; + filterClamp[1] = 0; + filterClamp[2] = (currentState.sourceFrame.width - 1) / currentState.renderTarget.size.width; + filterClamp[3] = (currentState.sourceFrame.height - 1) / currentState.renderTarget.size.height; + + shader.uniforms.filterClamp = filterClamp; + } + + // TODO Cacheing layer.. + for (var i in uniformData) { + if (uniformData[i].type === 'sampler2D' && uniforms[i] !== 0) { + if (uniforms[i].baseTexture) { + shader.uniforms[i] = this.renderer.bindTexture(uniforms[i].baseTexture, textureCount); + } else { + shader.uniforms[i] = textureCount; + + // TODO + // this is helpful as renderTargets can also be set. + // Although thinking about it, we could probably + // make the filter texture cache return a RenderTexture + // rather than a renderTarget + var gl = this.renderer.gl; + + this.renderer.boundTextures[textureCount] = this.renderer.emptyTextures[textureCount]; + gl.activeTexture(gl.TEXTURE0 + textureCount); + + uniforms[i].texture.bind(); + } + + textureCount++; + } else if (uniformData[i].type === 'mat3') { + // check if its pixi matrix.. + if (uniforms[i].a !== undefined) { + shader.uniforms[i] = uniforms[i].toArray(true); + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (uniformData[i].type === 'vec2') { + // check if its a point.. + if (uniforms[i].x !== undefined) { + var val = shader.uniforms[i] || new Float32Array(2); + + val[0] = uniforms[i].x; + val[1] = uniforms[i].y; + shader.uniforms[i] = val; + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (uniformData[i].type === 'float') { + if (shader.uniforms.data[i].value !== uniformData[i]) { + shader.uniforms[i] = uniforms[i]; + } + } else { + shader.uniforms[i] = uniforms[i]; + } + } + }; + + /** + * Gets a render target from the pool, or creates a new one. + * + * @param {boolean} clear - Should we clear the render texture when we get it? + * @param {number} resolution - The resolution of the target. + * @return {PIXI.RenderTarget} The new render target + */ + + + FilterManager.prototype.getRenderTarget = function getRenderTarget(clear, resolution) { + var currentState = this.filterData.stack[this.filterData.index]; + var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution); + + renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + return renderTarget; + }; + + /** + * Returns a render target to the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The render target to return. + */ + + + FilterManager.prototype.returnRenderTarget = function returnRenderTarget(renderTarget) { + this.freePotRenderTarget(renderTarget); + }; + + /** + * Calculates the mapped matrix. + * + * TODO playing around here.. this is temporary - (will end up in the shader) + * this returns a matrix that will normalise map filter cords in the filter to screen space + * + * @param {PIXI.Matrix} outputMatrix - the matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateScreenSpaceMatrix = function calculateScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); + }; + + /** + * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function calculateNormalizedScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); + }; + + /** + * This will map the filter coord so that a texture can be used based on the transform of a sprite + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateSpriteMatrix = function calculateSpriteMatrix(outputMatrix, sprite) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); + }; + + /** + * Destroys this Filter Manager. + * + */ + + + FilterManager.prototype.destroy = function destroy() { + this.shaderCache = {}; + this.emptyPool(); + }; + + /** + * Gets a Power-of-Two render texture. + * + * TODO move to a seperate class could be on renderer? + * also - could cause issue with multiple contexts? + * + * @private + * @param {WebGLRenderingContext} gl - The webgl rendering context + * @param {number} minWidth - The minimum width of the render target. + * @param {number} minHeight - The minimum height of the render target. + * @param {number} resolution - The resolution of the render target. + * @return {PIXI.RenderTarget} The new render target. + */ + + + FilterManager.prototype.getPotRenderTarget = function getPotRenderTarget(gl, minWidth, minHeight, resolution) { + // TODO you could return a bigger texture if there is not one in the pool? + minWidth = _bitTwiddle2.default.nextPow2(minWidth * resolution); + minHeight = _bitTwiddle2.default.nextPow2(minHeight * resolution); + + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + if (!this.pool[key]) { + this.pool[key] = []; + } + + var renderTarget = this.pool[key].pop(); + + // creating render target will cause texture to be bound! + if (!renderTarget) { + // temporary bypass cache.. + var tex = this.renderer.boundTextures[0]; + + gl.activeTexture(gl.TEXTURE0); + + // internally - this will cause a texture to be bound.. + renderTarget = new _RenderTarget2.default(gl, minWidth, minHeight, null, 1); + + // set the current one back + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + } + + // manually tweak the resolution... + // this will not modify the size of the frame buffer, just its resolution. + renderTarget.resolution = resolution; + renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution; + renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution; + + return renderTarget; + }; + + /** + * Empties the texture pool. + * + */ + + + FilterManager.prototype.emptyPool = function emptyPool() { + for (var i in this.pool) { + var textures = this.pool[i]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + + this.pool = {}; + }; + + /** + * Frees a render target back into the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free + */ + + + FilterManager.prototype.freePotRenderTarget = function freePotRenderTarget(renderTarget) { + var minWidth = renderTarget.size.width * renderTarget.resolution; + var minHeight = renderTarget.size.height * renderTarget.resolution; + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + this.pool[key].push(renderTarget); + }; + + return FilterManager; +}(_WebGLManager3.default); + +exports.default = FilterManager; + +},{"../../../Shader":42,"../../../math":68,"../filters/filterTransforms":86,"../utils/Quad":93,"../utils/RenderTarget":94,"./WebGLManager":91,"bit-twiddle":1}],89:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _SpriteMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); + +var _SpriteMaskFilter2 = _interopRequireDefault(_SpriteMaskFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var MaskManager = function (_WebGLManager) { + _inherits(MaskManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function MaskManager(renderer) { + _classCallCheck(this, MaskManager); + + // TODO - we don't need both! + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.scissor = false; + _this.scissorData = null; + _this.scissorRenderTarget = null; + + _this.enableScissor = true; + + _this.alphaMaskPool = []; + _this.alphaMaskIndex = 0; + return _this; + } + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushMask = function pushMask(target, maskData) { + // TODO the root check means scissor rect will not + // be used on render textures more info here: + // https://github.com/pixijs/pixi.js/pull/3545 + + if (maskData.texture) { + this.pushSpriteMask(target, maskData); + } else if (this.enableScissor && !this.scissor && this.renderer._activeRenderTarget.root && !this.renderer.stencilManager.stencilMaskStack.length && maskData.isFastRect()) { + var matrix = maskData.worldTransform; + + var rot = Math.atan2(matrix.b, matrix.a); + + // use the nearest degree! + rot = Math.round(rot * (180 / Math.PI)); + + if (rot % 90) { + this.pushStencilMask(maskData); + } else { + this.pushScissorMask(target, maskData); + } + } else { + this.pushStencilMask(maskData); + } + }; + + /** + * Removes the last mask from the mask stack and doesn't return it. + * + * @param {PIXI.DisplayObject} target - Display Object to pop the mask from + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.popMask = function popMask(target, maskData) { + if (maskData.texture) { + this.popSpriteMask(target, maskData); + } else if (this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length) { + this.popScissorMask(target, maskData); + } else { + this.popStencilMask(target, maskData); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.RenderTarget} target - Display Object to push the sprite mask to + * @param {PIXI.Sprite} maskData - Sprite to be used as the mask + */ + + + MaskManager.prototype.pushSpriteMask = function pushSpriteMask(target, maskData) { + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new _SpriteMaskFilter2.default(maskData)]; + } + + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskData; + + // TODO - may cause issues! + target.filterArea = maskData.getBounds(true); + + this.renderer.filterManager.pushFilter(target, alphaMaskFilter); + + this.alphaMaskIndex++; + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popSpriteMask = function popSpriteMask() { + this.renderer.filterManager.popFilter(); + this.alphaMaskIndex--; + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushStencilMask = function pushStencilMask(maskData) { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.pushStencil(maskData); + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popStencilMask = function popStencilMask() { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.popStencil(); + }; + + /** + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushScissorMask = function pushScissorMask(target, maskData) { + maskData.renderable = true; + + var renderTarget = this.renderer._activeRenderTarget; + + var bounds = maskData.getBounds(); + + bounds.fit(renderTarget.size); + maskData.renderable = false; + + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + + var resolution = this.renderer.resolution; + + this.renderer.gl.scissor(bounds.x * resolution, (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution, bounds.width * resolution, bounds.height * resolution); + + this.scissorRenderTarget = renderTarget; + this.scissorData = maskData; + this.scissor = true; + }; + + /** + * + * + */ + + + MaskManager.prototype.popScissorMask = function popScissorMask() { + this.scissorRenderTarget = null; + this.scissorData = null; + this.scissor = false; + + // must be scissor! + var gl = this.renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + }; + + return MaskManager; +}(_WebGLManager3.default); + +exports.default = MaskManager; + +},{"../filters/spriteMask/SpriteMaskFilter":87,"./WebGLManager":91}],90:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var StencilManager = function (_WebGLManager) { + _inherits(StencilManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function StencilManager(renderer) { + _classCallCheck(this, StencilManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.stencilMaskStack = null; + return _this; + } + + /** + * Changes the mask stack that is used by this manager. + * + * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack + */ + + + StencilManager.prototype.setMaskStack = function setMaskStack(stencilMaskStack) { + this.stencilMaskStack = stencilMaskStack; + + var gl = this.renderer.gl; + + if (stencilMaskStack.length === 0) { + gl.disable(gl.STENCIL_TEST); + } else { + gl.enable(gl.STENCIL_TEST); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. @alvin + * + * @param {PIXI.Graphics} graphics - The mask + */ + + + StencilManager.prototype.pushStencil = function pushStencil(graphics) { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + this.renderer._activeRenderTarget.attachStencilBuffer(); + + var gl = this.renderer.gl; + var sms = this.stencilMaskStack; + + if (sms.length === 0) { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.stencilFunc(gl.ALWAYS, 1, 1); + } + + sms.push(graphics); + + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; + + /** + * TODO @alvin + */ + + + StencilManager.prototype.popStencil = function popStencil() { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + var gl = this.renderer.gl; + var sms = this.stencilMaskStack; + + var graphics = sms.pop(); + + if (sms.length === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + } else { + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + } + }; + + /** + * Destroys the mask stack. + * + */ + + + StencilManager.prototype.destroy = function destroy() { + _WebGLManager3.default.prototype.destroy.call(this); + + this.stencilMaskStack.stencilStack = null; + }; + + return StencilManager; +}(_WebGLManager3.default); + +exports.default = StencilManager; + +},{"./WebGLManager":91}],91:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var WebGLManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function WebGLManager(renderer) { + _classCallCheck(this, WebGLManager); + + /** + * The renderer this manager works for. + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + this.renderer.on('context', this.onContextChange, this); + } + + /** + * Generic method called when there is a WebGL context change. + * + */ + + + WebGLManager.prototype.onContextChange = function onContextChange() {} + // do some codes init! + + + /** + * Generic destroy methods to be overridden by the subclass + * + */ + ; + + WebGLManager.prototype.destroy = function destroy() { + this.renderer.off('context', this.onContextChange, this); + + this.renderer = null; + }; + + return WebGLManager; +}(); + +exports.default = WebGLManager; + +},{}],92:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('../managers/WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Base for a common object renderer that can be used as a system renderer plugin. + * + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var ObjectRenderer = function (_WebGLManager) { + _inherits(ObjectRenderer, _WebGLManager); + + function ObjectRenderer() { + _classCallCheck(this, ObjectRenderer); + + return _possibleConstructorReturn(this, _WebGLManager.apply(this, arguments)); + } + + /** + * Starts the renderer and sets the shader + * + */ + ObjectRenderer.prototype.start = function start() {} + // set the shader.. + + + /** + * Stops the renderer + * + */ + ; + + ObjectRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Stub method for rendering content and emptying the current batch. + * + */ + + + ObjectRenderer.prototype.flush = function flush() {} + // flush! + + + /** + * Renders an object + * + * @param {PIXI.DisplayObject} object - The object to render. + */ + ; + + ObjectRenderer.prototype.render = function render(object) // eslint-disable-line no-unused-vars + { + // render the object + }; + + return ObjectRenderer; +}(_WebGLManager3.default); + +exports.default = ObjectRenderer; + +},{"../managers/WebGLManager":91}],93:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a quad + * + * @class + * @memberof PIXI + */ +var Quad = function () { + /** + * @param {WebGLRenderingContext} gl - The gl context for this quad to use. + * @param {object} state - TODO: Description + */ + function Quad(gl, state) { + _classCallCheck(this, Quad); + + /* + * the current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]); + + /** + * The Uvs of the quad + * + * @member {Float32Array} + */ + this.uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + this.interleaved = new Float32Array(8 * 2); + + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + this.indices = (0, _createIndicesForQuads2.default)(1); + + /* + * @member {glCore.GLBuffer} The vertex buffer + */ + this.vertexBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW); + + /* + * @member {glCore.GLBuffer} The index buffer + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + /* + * @member {glCore.VertexArrayObject} The index buffer + */ + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, state); + } + + /** + * Initialises the vaos and uses the shader. + * + * @param {PIXI.Shader} shader - the shader to use + */ + + + Quad.prototype.initVao = function initVao(shader) { + this.vao.clear().addIndex(this.indexBuffer).addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0).addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4); + }; + + /** + * Maps two Rectangle to the quad. + * + * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle + * @param {PIXI.Rectangle} destinationFrame - the second rectangle + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.map = function map(targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + + this.uvs[0] = x; + this.uvs[1] = y; + + this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; + + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; + + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; + + x = destinationFrame.x; + y = destinationFrame.y; + + this.vertices[0] = x; + this.vertices[1] = y; + + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + + return this; + }; + + /** + * Binds the buffer and uploads the data + * + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.upload = function upload() { + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + this.vertexBuffer.upload(this.interleaved); + + return this; + }; + + /** + * Removes this quad from WebGL + */ + + + Quad.prototype.destroy = function destroy() { + var gl = this.gl; + + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.indexBuffer); + }; + + return Quad; +}(); + +exports.default = Quad; + +},{"../../../utils/createIndicesForQuads":118,"pixi-gl-core":12}],94:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../../../math'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _pixiGlCore = require('pixi-gl-core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var RenderTarget = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {number} [width=0] - the horizontal range of the filter + * @param {number} [height=0] - the vertical range of the filter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The current resolution / device pixel ratio + * @param {boolean} [root=false] - Whether this object is the root element or not + */ + function RenderTarget(gl, width, height, scaleMode, resolution, root) { + _classCallCheck(this, RenderTarget); + + // TODO Resolution could go here ( eg low res blurs ) + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // next time to create a frame buffer and texture + + /** + * A frame buffer + * + * @member {PIXI.glCore.GLFramebuffer} + */ + this.frameBuffer = null; + + /** + * The texture + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The background colour of this render target, as an array of [r,g,b,a] values + * + * @member {number[]} + */ + this.clearColor = [0, 0, 0, 0]; + + /** + * The size of the object as a rectangle + * + * @member {PIXI.Rectangle} + */ + this.size = new _math.Rectangle(0, 0, 1, 1); + + /** + * The current resolution / device pixel ratio + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The projection matrix + * + * @member {PIXI.Matrix} + */ + this.projectionMatrix = new _math.Matrix(); + + /** + * The object's transform + * + * @member {PIXI.Matrix} + */ + this.transform = null; + + /** + * The frame. + * + * @member {PIXI.Rectangle} + */ + this.frame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.defaultFrame = new _math.Rectangle(); + this.destinationFrame = null; + this.sourceFrame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.stencilBuffer = null; + + /** + * The data structure for the stencil masks + * + * @member {PIXI.Graphics[]} + */ + this.stencilMaskStack = []; + + /** + * Stores filter data for the render target + * + * @member {object[]} + */ + this.filterData = null; + + /** + * The scale mode. + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Whether this object is the root element or not + * + * @member {boolean} + */ + this.root = root; + + if (!this.root) { + this.frameBuffer = _pixiGlCore.GLFramebuffer.createRGBA(gl, 100, 100); + + if (this.scaleMode === _const.SCALE_MODES.NEAREST) { + this.frameBuffer.texture.enableNearestScaling(); + } else { + this.frameBuffer.texture.enableLinearScaling(); + } + /* + A frame buffer needs a target to render to.. + create a texture and bind it attach it to the framebuffer.. + */ + + // this is used by the base texture + this.texture = this.frameBuffer.texture; + } else { + // make it a null framebuffer.. + this.frameBuffer = new _pixiGlCore.GLFramebuffer(gl, 100, 100); + this.frameBuffer.framebuffer = null; + } + + this.setFrame(); + + this.resize(width, height); + } + + /** + * Clears the filter texture. + * + * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer + */ + + + RenderTarget.prototype.clear = function clear(clearColor) { + var cc = clearColor || this.clearColor; + + this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a); + }; + + /** + * Binds the stencil buffer. + * + */ + + + RenderTarget.prototype.attachStencilBuffer = function attachStencilBuffer() { + // TODO check if stencil is done? + /** + * The stencil buffer is used for masking in pixi + * lets create one and then add attach it to the framebuffer.. + */ + if (!this.root) { + this.frameBuffer.enableStencil(); + } + }; + + /** + * Sets the frame of the render target. + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.setFrame = function setFrame(destinationFrame, sourceFrame) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; + }; + + /** + * Binds the buffers and initialises the viewport. + * + */ + + + RenderTarget.prototype.activate = function activate() { + // TOOD refactor usage of frame.. + var gl = this.gl; + + // make sure the texture is unbound! + this.frameBuffer.bind(); + + this.calculateProjection(this.destinationFrame, this.sourceFrame); + + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + + // TODO add a check as them may be the same! + if (this.destinationFrame !== this.sourceFrame) { + gl.enable(gl.SCISSOR_TEST); + gl.scissor(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + } else { + gl.disable(gl.SCISSOR_TEST); + } + + // TODO - does not need to be updated all the time?? + gl.viewport(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + }; + + /** + * Updates the projection matrix based on a projection frame (which is a rectangle) + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.calculateProjection = function calculateProjection(destinationFrame, sourceFrame) { + var pm = this.projectionMatrix; + + sourceFrame = sourceFrame || destinationFrame; + + pm.identity(); + + // TODO: make dest scale source + if (!this.root) { + pm.a = 1 / destinationFrame.width * 2; + pm.d = 1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = -1 - sourceFrame.y * pm.d; + } else { + pm.a = 1 / destinationFrame.width * 2; + pm.d = -1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = 1 - sourceFrame.y * pm.d; + } + }; + + /** + * Resizes the texture to the specified width and height + * + * @param {number} width - the new width of the texture + * @param {number} height - the new height of the texture + */ + + + RenderTarget.prototype.resize = function resize(width, height) { + width = width | 0; + height = height | 0; + + if (this.size.width === width && this.size.height === height) { + return; + } + + this.size.width = width; + this.size.height = height; + + this.defaultFrame.width = width; + this.defaultFrame.height = height; + + this.frameBuffer.resize(width * this.resolution, height * this.resolution); + + var projectionFrame = this.frame || this.size; + + this.calculateProjection(projectionFrame); + }; + + /** + * Destroys the render target. + * + */ + + + RenderTarget.prototype.destroy = function destroy() { + this.frameBuffer.destroy(); + + this.frameBuffer = null; + this.texture = null; + }; + + return RenderTarget; +}(); + +exports.default = RenderTarget; + +},{"../../../const":44,"../../../math":68,"../../../settings":99,"pixi-gl-core":12}],95:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = checkMaxIfStatmentsInShader; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['precision mediump float;', 'void main(void){', 'float test = 0.1;', '%forloop%', 'gl_FragColor = vec4(0.0);', '}'].join('\n'); + +function checkMaxIfStatmentsInShader(maxIfs, gl) { + var createTempContext = !gl; + + if (maxIfs === 0) { + throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); + } + + if (createTempContext) { + var tinyCanvas = document.createElement('canvas'); + + tinyCanvas.width = 1; + tinyCanvas.height = 1; + + gl = _pixiGlCore2.default.createContext(tinyCanvas); + } + + var shader = gl.createShader(gl.FRAGMENT_SHADER); + + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = maxIfs / 2 | 0; + } else { + // valid! + break; + } + } + + if (createTempContext) { + // get rid of context + if (gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').loseContext(); + } + } + + return maxIfs; +} + +function generateIfTestSrc(maxIfs) { + var src = ''; + + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxIfs - 1) { + src += 'if(test == ' + i + '.0){}'; + } + } + + return src; +} + +},{"pixi-gl-core":12}],96:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLBlendModesToPixi; + +var _const = require('../../../const'); + +/** + * Maps gl blend combinations to WebGL. + * + * @memberof PIXI + * @function mapWebGLBlendModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapWebGLBlendModesToPixi(gl) { + var array = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[_const.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD] = [gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + array[_const.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + return array; +} + +},{"../../../const":44}],97:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLDrawModesToPixi; + +var _const = require('../../../const'); + +/** + * Generic Mask Stack data structure. + * + * @memberof PIXI + * @function mapWebGLDrawModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {object} [object={}] - The object to map into + * @return {object} The mapped draw modes. + */ +function mapWebGLDrawModesToPixi(gl) { + var object = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + object[_const.DRAW_MODES.POINTS] = gl.POINTS; + object[_const.DRAW_MODES.LINES] = gl.LINES; + object[_const.DRAW_MODES.LINE_LOOP] = gl.LINE_LOOP; + object[_const.DRAW_MODES.LINE_STRIP] = gl.LINE_STRIP; + object[_const.DRAW_MODES.TRIANGLES] = gl.TRIANGLES; + object[_const.DRAW_MODES.TRIANGLE_STRIP] = gl.TRIANGLE_STRIP; + object[_const.DRAW_MODES.TRIANGLE_FAN] = gl.TRIANGLE_FAN; + + return object; +} + +},{"../../../const":44}],98:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = validateContext; +function validateContext(gl) { + var attributes = gl.getContextAttributes(); + + // this is going to be fairly simple for now.. but at least we have room to grow! + if (!attributes.stencil) { + /* eslint-disable no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable no-console */ + } +} + +},{}],99:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _maxRecommendedTextures = require('./utils/maxRecommendedTextures'); + +var _maxRecommendedTextures2 = _interopRequireDefault(_maxRecommendedTextures); + +var _canUploadSameBuffer = require('./utils/canUploadSameBuffer'); + +var _canUploadSameBuffer2 = _interopRequireDefault(_canUploadSameBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @namespace PIXI.settings + */ +exports.default = { + + /** + * Target frames per millisecond. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 0.06 + */ + TARGET_FPMS: 0.06, + + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * + * @static + * @memberof PIXI.settings + * @type {boolean} + * @default true + */ + MIPMAP_TEXTURES: true, + + /** + * Default resolution / device pixel ratio of the renderer. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + RESOLUTION: 1, + + /** + * Default filter resolution. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + FILTER_RESOLUTION: 1, + + /** + * The maximum textures that this device supports. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 32 + */ + SPRITE_MAX_TEXTURES: (0, _maxRecommendedTextures2.default)(32), + + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + + /** + * The prefix that denotes a URL is for a retina asset. + * + * @static + * @memberof PIXI.settings + * @type {RegExp|string} + * @example `@2x` + * @default /@(.+)x/ + */ + RETINA_PREFIX: /@(.+)x/, + + /** + * The default render options if none are supplied to {@link PIXI.WebGLRenderer} + * or {@link PIXI.CanvasRenderer}. + * + * @static + * @constant + * @memberof PIXI.settings + * @type {object} + * @property {HTMLCanvasElement} view=null + * @property {number} resolution=1 + * @property {boolean} antialias=false + * @property {boolean} forceFXAA=false + * @property {boolean} autoResize=false + * @property {boolean} transparent=false + * @property {number} backgroundColor=0x000000 + * @property {boolean} clearBeforeRender=true + * @property {boolean} preserveDrawingBuffer=false + * @property {boolean} roundPixels=false + */ + RENDER_OPTIONS: { + view: null, + antialias: false, + forceFXAA: false, + autoResize: false, + transparent: false, + backgroundColor: 0x000000, + clearBeforeRender: true, + preserveDrawingBuffer: false, + roundPixels: false + }, + + /** + * Default transform type. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.TRANSFORM_MODE} + * @default PIXI.TRANSFORM_MODE.STATIC + */ + TRANSFORM_MODE: 0, + + /** + * Default Garbage Collection mode. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO + */ + GC_MODE: 0, + + /** + * Default Garbage Collection max idle. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 3600 + */ + GC_MAX_IDLE: 60 * 60, + + /** + * Default Garbage Collection maximum check count. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 600 + */ + GC_MAX_CHECK_COUNT: 60 * 10, + + /** + * Default wrap modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP + */ + WRAP_MODE: 0, + + /** + * The scale modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR + */ + SCALE_MODE: 0, + + /** + * Default specify float precision in shaders. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM + */ + PRECISION: 'mediump', + + /** + * Can we upload the same buffer in a single frame? + * + * @static + * @constant + * @memberof PIXI + * @type {boolean} + */ + CAN_UPLOAD_SAME_BUFFER: (0, _canUploadSameBuffer2.default)() + +}; + +},{"./utils/canUploadSameBuffer":117,"./utils/maxRecommendedTextures":121}],100:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new _math.Point(); + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = new PIXI.Sprite.fromImage('assets/image.png'); + * ``` + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Sprite = function (_Container) { + _inherits(Sprite, _Container); + + /** + * @param {PIXI.Texture} texture - The texture for this sprite + */ + function Sprite(texture) { + _classCallCheck(this, Sprite); + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + * @private + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this._anchor = new _math.ObservablePoint(_this._onAnchorUpdate, _this); + + /** + * The texture that the sprite is using + * + * @private + * @member {PIXI.Texture} + */ + _this._texture = null; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = null; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * The shader that will be used to render the sprite. Set to null to remove a current shader. + * + * @member {PIXI.Filter|PIXI.Shader} + */ + _this.shader = null; + + /** + * An internal cached value of the tint. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this.cachedTint = 0xFFFFFF; + + // call texture setter + _this.texture = texture || _Texture2.default.EMPTY; + + /** + * this is used to store the vertex data of the sprite (basically a quad) + * + * @private + * @member {Float32Array} + */ + _this.vertexData = new Float32Array(8); + + /** + * This is used to calculate the bounds of the object IF it is a trimmed sprite + * + * @private + * @member {Float32Array} + */ + _this.vertexTrimmedData = null; + + _this._transformID = -1; + _this._textureID = -1; + + _this._transformTrimmedID = -1; + _this._textureTrimmedID = -1; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * + * @member {string} + * @default 'sprite' + */ + _this.pluginName = 'sprite'; + return _this; + } + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Sprite.prototype._onTextureUpdate = function _onTextureUpdate() { + this._textureID = -1; + this._textureTrimmedID = -1; + + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = (0, _utils.sign)(this.scale.x) * this._width / this.texture.orig.width; + } + + if (this._height) { + this.scale.y = (0, _utils.sign)(this.scale.y) * this._height / this.texture.orig.height; + } + }; + + /** + * Called when the anchor position updates. + * + * @private + */ + + + Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate() { + this._transformID = -1; + this._transformTrimmedID = -1; + }; + + /** + * calculates worldTransform * vertices, store it in vertexData + */ + + + Sprite.prototype.calculateVertices = function calculateVertices() { + if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) { + return; + } + + this._transformID = this.transform._worldID; + this._textureID = this._texture._updateID; + + // set the vertex data + + var texture = this._texture; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var anchor = this._anchor; + + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - anchor._x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - anchor._y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - anchor._x); + w1 = orig.width * -anchor._x; + + h0 = orig.height * (1 - anchor._y); + h1 = orig.height * -anchor._y; + } + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData + * This is used to ensure that the true width and height of a trimmed texture is respected + */ + + + Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices() { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { + return; + } + + this._transformTrimmedID = this.transform._worldID; + this._textureTrimmedID = this._texture._updateID; + + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + var anchor = this._anchor; + + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + + var w0 = orig.width * (1 - anchor._x); + var w1 = orig.width * -anchor._x; + + var h0 = orig.height * (1 - anchor._y); + var h1 = orig.height * -anchor._y; + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use. + */ + + + Sprite.prototype._renderWebGL = function _renderWebGL(renderer) { + this.calculateVertices(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Sprite.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Updates the bounds of the sprite. + * + * @private + */ + + + Sprite.prototype._calculateBounds = function _calculateBounds() { + var trim = this._texture.trim; + var orig = this._texture.orig; + + // First lets check to see if the current texture has a trim.. + if (!trim || trim.width === orig.width && trim.height === orig.height) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + Sprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._texture.orig.width * -this._anchor._x; + this._bounds.minY = this._texture.orig.height * -this._anchor._y; + this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x); + this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._x); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _Container.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Tests if a point is inside this sprite + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Sprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + + if (tempPoint.x > x1 && tempPoint.x < x1 + width) { + y1 = -height * this.anchor.y; + + if (tempPoint.y > y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + Sprite.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + this._anchor = null; + + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + + this._texture.destroy(!!destroyBaseTexture); + } + + this._texture = null; + this.shader = null; + }; + + // some helper functions.. + + /** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Sprite} The newly created texture + */ + + + Sprite.from = function from(source) { + return new Sprite(_Texture2.default.from(source)); + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId + */ + + + Sprite.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return new Sprite(texture); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id + */ + + + Sprite.fromImage = function fromImage(imageId, crossorigin, scaleMode) { + return new Sprite(_Texture2.default.fromImage(imageId, crossorigin, scaleMode)); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Sprite, [{ + key: 'width', + get: function get() { + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._anchor.copy(value); + } + + /** + * The tint applied to the sprite. This is a hex value. A value of + * 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + } + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + */ + + }, { + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + this.cachedTint = 0xFFFFFF; + + this._textureID = -1; + this._textureTrimmedID = -1; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + }]); + + return Sprite; +}(_Container3.default); + +exports.default = Sprite; + +},{"../const":44,"../display/Container":46,"../math":68,"../textures/Texture":112,"../utils":120}],101:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +var _math = require('../../math'); + +var _CanvasTinter = require('./CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var canvasRenderWorldTransform = new _math.Matrix(); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasSpriteRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + */ + +var CanvasSpriteRenderer = function () { + /** + * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for. + */ + function CanvasSpriteRenderer(renderer) { + _classCallCheck(this, CanvasSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + CanvasSpriteRenderer.prototype.render = function render(sprite) { + var texture = sprite._texture; + var renderer = this.renderer; + + var width = texture._frame.width; + var height = texture._frame.height; + + var wt = sprite.transform.worldTransform; + var dx = 0; + var dy = 0; + + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) { + return; + } + + renderer.setBlendMode(sprite.blendMode); + + // Ignore null sources + if (texture.valid) { + renderer.context.globalAlpha = sprite.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture + var smoothingEnabled = texture.baseTexture.scaleMode === _const.SCALE_MODES.LINEAR; + + if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) { + renderer.context[renderer.smoothProperty] = smoothingEnabled; + } + + if (texture.trim) { + dx = texture.trim.width / 2 + texture.trim.x - sprite.anchor.x * texture.orig.width; + dy = texture.trim.height / 2 + texture.trim.y - sprite.anchor.y * texture.orig.height; + } else { + dx = (0.5 - sprite.anchor.x) * texture.orig.width; + dy = (0.5 - sprite.anchor.y) * texture.orig.height; + } + + if (texture.rotate) { + wt.copy(canvasRenderWorldTransform); + wt = canvasRenderWorldTransform; + _math.GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); + // the anchor has already been applied above, so lets set it to zero + dx = 0; + dy = 0; + } + + dx -= width / 2; + dy -= height / 2; + + // Allow for pixel rounding + if (renderer.roundPixels) { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution | 0, wt.ty * renderer.resolution | 0); + + dx = dx | 0; + dy = dy | 0; + } else { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution, wt.ty * renderer.resolution); + } + + var resolution = texture.baseTexture.resolution; + + if (sprite.tint !== 0xFFFFFF) { + if (sprite.cachedTint !== sprite.tint) { + sprite.cachedTint = sprite.tint; + + // TODO clean up caching - how to clean up the caches? + sprite.tintedTexture = _CanvasTinter2.default.getTintedTexture(sprite, sprite.tint); + } + + renderer.context.drawImage(sprite.tintedTexture, 0, 0, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } else { + renderer.context.drawImage(texture.baseTexture.source, texture._frame.x * resolution, texture._frame.y * resolution, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } + } + }; + + /** + * destroy the sprite object. + * + */ + + + CanvasSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasSpriteRenderer; +}(); + +exports.default = CanvasSpriteRenderer; + + +_CanvasRenderer2.default.registerPlugin('sprite', CanvasSpriteRenderer); + +},{"../../const":44,"../../math":68,"../../renderers/canvas/CanvasRenderer":75,"./CanvasTinter":102}],102:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class + * @memberof PIXI + */ +var CanvasTinter = { + /** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Sprite} sprite - the sprite to tint + * @param {number} color - the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ + getTintedTexture: function getTintedTexture(sprite, color) { + var texture = sprite.texture; + + color = CanvasTinter.roundColor(color); + + var stringColor = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + texture.tintCache = texture.tintCache || {}; + + if (texture.tintCache[stringColor]) { + return texture.tintCache[stringColor]; + } + + // clone texture.. + var canvas = CanvasTinter.canvas || document.createElement('canvas'); + + // CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); + CanvasTinter.tintMethod(texture, color, canvas); + + if (CanvasTinter.convertTintToImage) { + // is this better? + var tintImage = new Image(); + + tintImage.src = canvas.toDataURL(); + + texture.tintCache[stringColor] = tintImage; + } else { + texture.tintCache[stringColor] = canvas; + // if we are not converting the texture to an image then we need to lose the reference to the canvas + CanvasTinter.canvas = null; + } + + return canvas; + }, + + /** + * Tint a texture using the 'multiply' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithMultiply: function tintWithMultiply(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = crop.width; + canvas.height = crop.height; + + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + }, + + /** + * Tint a texture using the 'overlay' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithOverlay: function tintWithOverlay(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = crop.width; + canvas.height = crop.height; + + context.globalCompositeOperation = 'copy'; + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + // context.globalCompositeOperation = 'copy'; + }, + + + /** + * Tint a texture pixel per pixel. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithPerPixel: function tintWithPerPixel(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = crop.width; + canvas.height = crop.height; + + context.globalCompositeOperation = 'copy'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + var rgbValues = (0, _utils.hex2rgb)(color); + var r = rgbValues[0]; + var g = rgbValues[1]; + var b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, crop.width, crop.height); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + } + + context.putImageData(pixelData, 0, 0); + }, + + /** + * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel. + * + * @memberof PIXI.CanvasTinter + * @param {number} color - the color to round, should be a hex color + * @return {number} The rounded color. + */ + roundColor: function roundColor(color) { + var step = CanvasTinter.cacheStepsPerColorChannel; + + var rgbValues = (0, _utils.hex2rgb)(color); + + rgbValues[0] = Math.min(255, rgbValues[0] / step * step); + rgbValues[1] = Math.min(255, rgbValues[1] / step * step); + rgbValues[2] = Math.min(255, rgbValues[2] / step * step); + + return (0, _utils.rgb2hex)(rgbValues); + }, + + /** + * Number of steps which will be used as a cap when rounding colors. + * + * @memberof PIXI.CanvasTinter + * @type {number} + */ + cacheStepsPerColorChannel: 8, + + /** + * Tint cache boolean flag. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + convertTintToImage: false, + + /** + * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + canUseMultiply: (0, _canUseNewCanvasBlendModes2.default)(), + + /** + * The tinting method that will be used. + * + * @memberof PIXI.CanvasTinter + * @type {tintMethodFunctionType} + */ + tintMethod: 0 +}; + +CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply : CanvasTinter.tintWithPerPixel; + +/** + * The tintMethod type. + * + * @memberof PIXI.CanvasTinter + * @callback tintMethodFunctionType + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + +exports.default = CanvasTinter; + +},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":78,"../../utils":120}],103:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Buffer = function () { + /** + * @param {number} size - The size of the buffer in bytes. + */ + function Buffer(size) { + _classCallCheck(this, Buffer); + + this.vertices = new ArrayBuffer(size); + + /** + * View on the vertices as a Float32Array for positions + * + * @member {Float32Array} + */ + this.float32View = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array for uvs + * + * @member {Float32Array} + */ + this.uint32View = new Uint32Array(this.vertices); + } + + /** + * Destroys the buffer. + * + */ + + + Buffer.prototype.destroy = function destroy() { + this.vertices = null; + this.positions = null; + this.uvs = null; + this.colors = null; + }; + + return Buffer; +}(); + +exports.default = Buffer; + +},{}],104:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _createIndicesForQuads = require('../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +var _generateMultiTextureShader = require('./generateMultiTextureShader'); + +var _generateMultiTextureShader2 = _interopRequireDefault(_generateMultiTextureShader); + +var _checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'); + +var _checkMaxIfStatmentsInShader2 = _interopRequireDefault(_checkMaxIfStatmentsInShader); + +var _BatchBuffer = require('./BatchBuffer'); + +var _BatchBuffer2 = _interopRequireDefault(_BatchBuffer); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var TICK = 0; +var TEXTURE_TICK = 0; + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var SpriteRenderer = function (_ObjectRenderer) { + _inherits(SpriteRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function SpriteRenderer(renderer) { + _classCallCheck(this, SpriteRenderer); + + /** + * Number of values sent in the vertex buffer. + * positionX, positionY, colorR, colorG, colorB = 5 + * + * @member {number} + */ + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.vertSize = 5; + + /** + * The size of the vertex information in bytes. + * + * @member {number} + */ + _this.vertByteSize = _this.vertSize * 4; + + /** + * The number of images in the SpriteRenderer before it flushes. + * + * @member {number} + */ + _this.size = _settings2.default.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + + // the total number of bytes in our batch + // let numVerts = this.size * 4 * this.vertByteSize; + + _this.buffers = []; + for (var i = 1; i <= _bitTwiddle2.default.nextPow2(_this.size); i *= 2) { + _this.buffers.push(new _BatchBuffer2.default(i * 4 * _this.vertByteSize)); + } + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + _this.indices = (0, _createIndicesForQuads2.default)(_this.size); + + /** + * The default shaders that is used if a sprite doesn't have a more specific one. + * there is a shader for each number of textures that can be rendererd. + * These shaders will also be generated on the fly as required. + * @member {PIXI.Shader[]} + */ + _this.shader = null; + + _this.currentIndex = 0; + TICK = 0; + _this.groups = []; + + for (var k = 0; k < _this.size; k++) { + _this.groups[k] = { textures: [], textureCount: 0, ids: [], size: 0, start: 0, blend: 0 }; + } + + _this.sprites = []; + + _this.vertexBuffers = []; + _this.vaos = []; + + _this.vaoMax = 2; + _this.vertexCount = 0; + + _this.renderer.on('prerender', _this.onPrerender, _this); + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + SpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + if (this.renderer.legacy) { + this.MAX_TEXTURES = 1; + } else { + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), _settings2.default.SPRITE_MAX_TEXTURES); + + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = (0, _checkMaxIfStatmentsInShader2.default)(this.MAX_TEXTURES, gl); + } + + var shader = this.shader = (0, _generateMultiTextureShader2.default)(gl, this.MAX_TEXTURES); + + // create a couple of buffers + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + // we use the second shader as the first one depending on your browser may omit aTextureId + // as it is not used by the shader so is optimized out. + + this.renderer.bindVao(null); + + for (var i = 0; i < this.vaoMax; i++) { + this.vertexBuffers[i] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + + /* eslint-disable max-len */ + + // build the vao object that will render.. + this.vaos[i] = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(this.vertexBuffers[i], shader.attributes.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(this.vertexBuffers[i], shader.attributes.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(this.vertexBuffers[i], shader.attributes.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (shader.attributes.aTextureId) { + this.vaos[i].addAttribute(this.vertexBuffers[i], shader.attributes.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + /* eslint-enable max-len */ + } + + this.vao = this.vaos[0]; + this.currentBlendMode = 99999; + + this.boundTextures = new Array(this.MAX_TEXTURES); + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + SpriteRenderer.prototype.onPrerender = function onPrerender() { + this.vertexCount = 0; + }; + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + SpriteRenderer.prototype.render = function render(sprite) { + // TODO set blend modes.. + // check texture.. + if (this.currentIndex >= this.size) { + this.flush(); + } + + // get the uvs for the texture + + // if the uvs have not updated then no point rendering just yet! + if (!sprite._texture._uvs) { + return; + } + + // push a texture. + // increment the batchsize + this.sprites[this.currentIndex++] = sprite; + }; + + /** + * Renders the content and empties the current batch. + * + */ + + + SpriteRenderer.prototype.flush = function flush() { + if (this.currentIndex === 0) { + return; + } + + var gl = this.renderer.gl; + var MAX_TEXTURES = this.MAX_TEXTURES; + + var np2 = _bitTwiddle2.default.nextPow2(this.currentIndex); + var log2 = _bitTwiddle2.default.log2(np2); + var buffer = this.buffers[log2]; + + var sprites = this.sprites; + var groups = this.groups; + + var float32View = buffer.float32View; + var uint32View = buffer.uint32View; + + var boundTextures = this.boundTextures; + var rendererBoundTextures = this.renderer.boundTextures; + var touch = this.renderer.textureGC.count; + + var index = 0; + var nextTexture = void 0; + var currentTexture = void 0; + var groupCount = 1; + var textureCount = 0; + var currentGroup = groups[0]; + var vertexData = void 0; + var uvs = void 0; + var blendMode = sprites[0].blendMode; + + currentGroup.textureCount = 0; + currentGroup.start = 0; + currentGroup.blend = blendMode; + + TICK++; + + var i = void 0; + + // copy textures.. + for (i = 0; i < MAX_TEXTURES; ++i) { + boundTextures[i] = rendererBoundTextures[i]; + boundTextures[i]._virtalBoundId = i; + } + + for (i = 0; i < this.currentIndex; ++i) { + // upload the sprite elemetns... + // they have all ready been calculated so we just need to push them into the buffer. + var sprite = sprites[i]; + + nextTexture = sprite._texture.baseTexture; + + if (blendMode !== sprite.blendMode) { + // finish a group.. + blendMode = sprite.blendMode; + + // force the batch to break! + currentTexture = null; + textureCount = MAX_TEXTURES; + TICK++; + } + + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + + if (nextTexture._enabled !== TICK) { + if (textureCount === MAX_TEXTURES) { + TICK++; + + currentGroup.size = i - currentGroup.start; + + textureCount = 0; + + currentGroup = groups[groupCount++]; + currentGroup.blend = blendMode; + currentGroup.textureCount = 0; + currentGroup.start = i; + } + + nextTexture.touched = touch; + + if (nextTexture._virtalBoundId === -1) { + for (var j = 0; j < MAX_TEXTURES; ++j) { + var tIndex = (j + TEXTURE_TICK) % MAX_TEXTURES; + + var t = boundTextures[tIndex]; + + if (t._enabled !== TICK) { + TEXTURE_TICK++; + + t._virtalBoundId = -1; + + nextTexture._virtalBoundId = tIndex; + + boundTextures[tIndex] = nextTexture; + break; + } + } + } + + nextTexture._enabled = TICK; + + currentGroup.textureCount++; + currentGroup.ids[textureCount] = nextTexture._virtalBoundId; + currentGroup.textures[textureCount++] = nextTexture; + } + } + + vertexData = sprite.vertexData; + + // TODO this sum does not need to be set each frame.. + uvs = sprite._texture._uvs.uvsUint32; + + if (this.renderer.roundPixels) { + var resolution = this.renderer.resolution; + + // xy + float32View[index] = (vertexData[0] * resolution | 0) / resolution; + float32View[index + 1] = (vertexData[1] * resolution | 0) / resolution; + + // xy + float32View[index + 5] = (vertexData[2] * resolution | 0) / resolution; + float32View[index + 6] = (vertexData[3] * resolution | 0) / resolution; + + // xy + float32View[index + 10] = (vertexData[4] * resolution | 0) / resolution; + float32View[index + 11] = (vertexData[5] * resolution | 0) / resolution; + + // xy + float32View[index + 15] = (vertexData[6] * resolution | 0) / resolution; + float32View[index + 16] = (vertexData[7] * resolution | 0) / resolution; + } else { + // xy + float32View[index] = vertexData[0]; + float32View[index + 1] = vertexData[1]; + + // xy + float32View[index + 5] = vertexData[2]; + float32View[index + 6] = vertexData[3]; + + // xy + float32View[index + 10] = vertexData[4]; + float32View[index + 11] = vertexData[5]; + + // xy + float32View[index + 15] = vertexData[6]; + float32View[index + 16] = vertexData[7]; + } + + uint32View[index + 2] = uvs[0]; + uint32View[index + 7] = uvs[1]; + uint32View[index + 12] = uvs[2]; + uint32View[index + 17] = uvs[3]; + + /* eslint-disable max-len */ + uint32View[index + 3] = uint32View[index + 8] = uint32View[index + 13] = uint32View[index + 18] = sprite._tintRGB + (Math.min(sprite.worldAlpha, 1) * 255 << 24); + + float32View[index + 4] = float32View[index + 9] = float32View[index + 14] = float32View[index + 19] = nextTexture._virtalBoundId; + /* eslint-enable max-len */ + + index += 20; + } + + currentGroup.size = i - currentGroup.start; + + if (!_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // this is still needed for IOS performance.. + // it really does not like uploading to the same buffer in a single frame! + if (this.vaoMax <= this.vertexCount) { + this.vaoMax++; + this.vertexBuffers[this.vertexCount] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + + /* eslint-disable max-len */ + + // build the vao object that will render.. + this.vaos[this.vertexCount] = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(this.vertexBuffers[this.vertexCount], this.shader.attributes.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(this.vertexBuffers[this.vertexCount], this.shader.attributes.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(this.vertexBuffers[this.vertexCount], this.shader.attributes.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (this.shader.attributes.aTextureId) { + this.vaos[this.vertexCount].addAttribute(this.vertexBuffers[this.vertexCount], this.shader.attributes.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + /* eslint-enable max-len */ + } + + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, false); + + this.vertexCount++; + } else { + // lets use the faster option, always use buffer number 0 + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, true); + } + + for (i = 0; i < MAX_TEXTURES; ++i) { + rendererBoundTextures[i]._virtalBoundId = -1; + } + + // render the groups.. + for (i = 0; i < groupCount; ++i) { + var group = groups[i]; + var groupTextureCount = group.textureCount; + + for (var _j = 0; _j < groupTextureCount; _j++) { + currentTexture = group.textures[_j]; + + // reset virtual ids.. + // lets do a quick check.. + if (rendererBoundTextures[group.ids[_j]] !== currentTexture) { + this.renderer.bindTexture(currentTexture, group.ids[_j], true); + } + + // reset the virtualId.. + currentTexture._virtalBoundId = -1; + } + + // set the blend mode.. + this.renderer.state.setBlendMode(group.blend); + + gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); + } + + // reset elements for the next flush + this.currentIndex = 0; + }; + + /** + * Starts a new sprite batch. + */ + + + SpriteRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + + if (_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // bind buffer #0, we don't need others + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].bind(); + } + }; + + /** + * Stops and flushes the current batch. + * + */ + + + SpriteRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Destroys the SpriteRenderer. + * + */ + + + SpriteRenderer.prototype.destroy = function destroy() { + for (var i = 0; i < this.vaoMax; i++) { + if (this.vertexBuffers[i]) { + this.vertexBuffers[i].destroy(); + } + if (this.vaos[i]) { + this.vaos[i].destroy(); + } + } + + if (this.indexBuffer) { + this.indexBuffer.destroy(); + } + + this.renderer.off('prerender', this.onPrerender, this); + + _ObjectRenderer.prototype.destroy.call(this); + + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } + + this.vertexBuffers = null; + this.vaos = null; + this.indexBuffer = null; + this.indices = null; + + this.sprites = null; + + for (var _i = 0; _i < this.buffers.length; ++_i) { + this.buffers[_i].destroy(); + } + }; + + return SpriteRenderer; +}(_ObjectRenderer3.default); + +exports.default = SpriteRenderer; + + +_WebGLRenderer2.default.registerPlugin('sprite', SpriteRenderer); + +},{"../../renderers/webgl/WebGLRenderer":82,"../../renderers/webgl/utils/ObjectRenderer":92,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":95,"../../settings":99,"../../utils/createIndicesForQuads":118,"./BatchBuffer":103,"./generateMultiTextureShader":105,"bit-twiddle":1,"pixi-gl-core":12}],105:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateMultiTextureShader; + +var _Shader = require('../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'varying float vTextureId;', 'uniform sampler2D uSamplers[%count%];', 'void main(void){', 'vec4 color;', 'float textureId = floor(vTextureId+0.5);', '%forloop%', 'gl_FragColor = color * vColor;', '}'].join('\n'); + +function generateMultiTextureShader(gl, maxTextures) { + var vertexSrc = 'precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = vec4(aColor.rgb * aColor.a, aColor.a);\n}\n'; + var fragmentSrc = fragTemplate; + + fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); + + var shader = new _Shader2.default(gl, vertexSrc, fragmentSrc); + + var sampleValues = []; + + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + + shader.bind(); + shader.uniforms.uSamplers = sampleValues; + + return shader; +} + +function generateSampleSrc(maxTextures) { + var src = ''; + + src += '\n'; + src += '\n'; + + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxTextures - 1) { + src += 'if(textureId == ' + i + '.0)'; + } + + src += '\n{'; + src += '\n\tcolor = texture2D(uSamplers[' + i + '], vTextureCoord);'; + src += '\n}'; + } + + src += '\n'; + src += '\n'; + + return src; +} + +},{"../../Shader":42,"path":22}],106:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Sprite2 = require('../sprites/Sprite'); + +var _Sprite3 = _interopRequireDefault(_Sprite2); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TextStyle = require('./TextStyle'); + +var _TextStyle2 = _interopRequireDefault(_TextStyle); + +var _trimCanvas = require('../utils/trimCanvas'); + +var _trimCanvas2 = _interopRequireDefault(_trimCanvas); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint max-depth: [2, 8] */ + + +var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true +}; + +/** + * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string, + * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object. + * + * A Text can be created directly from a string and a style object + * + * ```js + * let text = new PIXI.Text('This is a pixi text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI + */ + +var Text = function (_Sprite) { + _inherits(Text, _Sprite); + + /** + * @param {string} text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + * @param {HTMLCanvasElement} [canvas] - The canvas element for drawing text + */ + function Text(text, style, canvas) { + _classCallCheck(this, Text); + + canvas = canvas || document.createElement('canvas'); + + canvas.width = 3; + canvas.height = 3; + + var texture = _Texture2.default.fromCanvas(canvas); + + texture.orig = new _math.Rectangle(); + texture.trim = new _math.Rectangle(); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + var _this = _possibleConstructorReturn(this, _Sprite.call(this, texture)); + + _this.canvas = canvas; + + /** + * The canvas 2d context that everything is drawn with + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.canvas.getContext('2d'); + + /** + * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. + * @member {number} + * @default 1 + */ + _this.resolution = _settings2.default.RESOLUTION; + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = null; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._style = null; + /** + * Private listener to track style changes. + * + * @member {Function} + * @private + */ + _this._styleListener = null; + + /** + * Private tracker for the current font. + * + * @member {string} + * @private + */ + _this._font = ''; + + _this.text = text; + _this.style = style; + + _this.localStyleID = -1; + return _this; + } + + /** + * Renders text and updates it when needed. + * + * @private + * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. + */ + + + Text.prototype.updateText = function updateText(respectDirty) { + var style = this._style; + + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + + if (!this.dirty && respectDirty) { + return; + } + + this._font = Text.getFontStyle(style); + + this.context.font = this._font; + + // word wrap + // preserve original text + var outputText = style.wordWrap ? this.wordWrap(this._text) : this._text; + + // split text into lines + var lines = outputText.split(/(?:\r\n|\r|\n)/); + + // calculate text width + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + var fontProperties = Text.calculateFontProperties(this._font); + + for (var i = 0; i < lines.length; i++) { + var lineWidth = this.context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing; + + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + + var width = maxLineWidth + style.strokeThickness; + + if (style.dropShadow) { + width += style.dropShadowDistance; + } + + this.canvas.width = Math.ceil((width + style.padding * 2) * this.resolution); + + // calculate text height + var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * lineHeight; + + if (style.dropShadow) { + height += style.dropShadowDistance; + } + + this.canvas.height = Math.ceil((height + style.padding * 2) * this.resolution); + + this.context.scale(this.resolution, this.resolution); + + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + + this.context.font = this._font; + this.context.strokeStyle = style.stroke; + this.context.lineWidth = style.strokeThickness; + this.context.textBaseline = style.textBaseline; + this.context.lineJoin = style.lineJoin; + this.context.miterLimit = style.miterLimit; + + var linePositionX = void 0; + var linePositionY = void 0; + + if (style.dropShadow) { + this.context.shadowBlur = style.dropShadowBlur; + this.context.globalAlpha = style.dropShadowAlpha; + + if (style.dropShadowBlur > 0) { + this.context.shadowColor = style.dropShadowColor; + } else { + this.context.fillStyle = style.dropShadowColor; + } + + var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + + for (var _i = 0; _i < lines.length; _i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i]) / 2; + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); + + if (style.stroke && style.strokeThickness) { + this.context.strokeStyle = style.dropShadowColor; + this.drawLetterSpacing(lines[_i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding, true); + this.context.strokeStyle = style.stroke; + } + } + } + } + + // reset the shadow blur and alpha that was set by the drop shadow, for the regular text + this.context.shadowBlur = 0; + this.context.globalAlpha = 1; + + // set canvas text styles + this.context.fillStyle = this._generateFillStyle(style, lines); + + // draw lines line by line + for (var _i2 = 0; _i2 < lines.length; _i2++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i2 * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i2]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i2]) / 2; + } + + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[_i2], linePositionX + style.padding, linePositionY + style.padding, true); + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i2], linePositionX + style.padding, linePositionY + style.padding); + } + } + + this.updateTexture(); + }; + + /** + * Render the text with letter-spacing. + * @param {string} text - The text to draw + * @param {number} x - Horizontal position to draw the text + * @param {number} y - Vertical position to draw the text + * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + * @private + */ + + + Text.prototype.drawLetterSpacing = function drawLetterSpacing(text, x, y) { + var isStroke = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var style = this._style; + + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + + if (letterSpacing === 0) { + if (isStroke) { + this.context.strokeText(text, x, y); + } else { + this.context.fillText(text, x, y); + } + + return; + } + + var characters = String.prototype.split.call(text, ''); + var currentPosition = x; + var index = 0; + var current = ''; + + while (index < text.length) { + current = characters[index++]; + if (isStroke) { + this.context.strokeText(current, currentPosition, y); + } else { + this.context.fillText(current, currentPosition, y); + } + currentPosition += this.context.measureText(current).width + letterSpacing; + } + }; + + /** + * Updates texture size based on canvas size + * + * @private + */ + + + Text.prototype.updateTexture = function updateTexture() { + if (this._style.trim) { + var trimmed = (0, _trimCanvas2.default)(this.canvas); + + this.canvas.width = trimmed.width; + this.canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } + + var texture = this._texture; + var style = this._style; + + texture.baseTexture.hasLoaded = true; + texture.baseTexture.resolution = this.resolution; + + texture.baseTexture.realWidth = this.canvas.width; + texture.baseTexture.realHeight = this.canvas.height; + texture.baseTexture.width = this.canvas.width / this.resolution; + texture.baseTexture.height = this.canvas.height / this.resolution; + texture.trim.width = texture._frame.width = this.canvas.width / this.resolution; + texture.trim.height = texture._frame.height = this.canvas.height / this.resolution; + + texture.trim.x = -style.padding; + texture.trim.y = -style.padding; + + texture.orig.width = texture._frame.width - style.padding * 2; + texture.orig.height = texture._frame.height - style.padding * 2; + + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + + texture.baseTexture.emit('update', texture.baseTexture); + + this.dirty = false; + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Text.prototype.renderWebGL = function renderWebGL(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype.renderWebGL.call(this, renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Text.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype._renderCanvas.call(this, renderer); + }; + + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @private + * @param {string} text - String to apply word wrapping to + * @return {string} New string with new lines applied where required + */ + + + Text.prototype.wordWrap = function wordWrap(text) { + // Greedy wrapping algorithm that will wrap words as the line grows longer + // than its horizontal bounds. + var result = ''; + var style = this._style; + var lines = text.split('\n'); + var wordWrapWidth = style.wordWrapWidth; + + for (var i = 0; i < lines.length; i++) { + var spaceLeft = wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) { + var wordWidth = this.context.measureText(words[j]).width; + + if (style.breakWords && wordWidth > wordWrapWidth) { + // Word should be split in the middle + var characters = words[j].split(''); + + for (var c = 0; c < characters.length; c++) { + var characterWidth = this.context.measureText(characters[c]).width; + + if (characterWidth > spaceLeft) { + result += '\n' + characters[c]; + spaceLeft = wordWrapWidth - characterWidth; + } else { + if (c === 0) { + result += ' '; + } + + result += characters[c]; + spaceLeft -= characterWidth; + } + } + } else { + var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; + + if (j === 0 || wordWidthWithSpace > spaceLeft) { + // Skip printing the newline if it's the first word of the line that is + // greater than the word wrap width. + if (j > 0) { + result += '\n'; + } + result += words[j]; + spaceLeft = wordWrapWidth - wordWidth; + } else { + spaceLeft -= wordWidthWithSpace; + result += ' ' + words[j]; + } + } + } + + if (i < lines.length - 1) { + result += '\n'; + } + } + + return result; + }; + + /** + * Gets the local bounds of the text object. + * + * @param {Rectangle} rect - The output rectangle. + * @return {Rectangle} The bounds. + */ + + + Text.prototype.getLocalBounds = function getLocalBounds(rect) { + this.updateText(true); + + return _Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + */ + + + Text.prototype._calculateBounds = function _calculateBounds() { + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; + + /** + * Method to be called upon a TextStyle change. + * @private + */ + + + Text.prototype._onStyleChange = function _onStyleChange() { + this.dirty = true; + }; + + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * + * @private + * @param {object} style - The style. + * @param {string[]} lines - The lines of text. + * @return {string|number|CanvasGradient} The fill style + */ + + + Text.prototype._generateFillStyle = function _generateFillStyle(style, lines) { + if (!Array.isArray(style.fill)) { + return style.fill; + } + + // cocoon on canvas+ cannot generate textures, so use the first colour instead + if (navigator.isCocoonJS) { + return style.fill[0]; + } + + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient = void 0; + var totalIterations = void 0; + var currentIteration = void 0; + var stop = void 0; + + var width = this.canvas.width / this.resolution; + var height = this.canvas.height / this.resolution; + + // make a copy of the style settings, so we can manipulate them later + var fill = style.fill.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(style.fill[0]); + fillGradientStops.unshift(0); + + fill.push(style.fill[style.fill.length - 1]); + fillGradientStops.push(1); + + if (style.fillGradientType === _const.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); + + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + totalIterations = (fill.length + 1) * lines.length; + currentIteration = 0; + for (var _i3 = 0; _i3 < lines.length; _i3++) { + currentIteration += 1; + for (var j = 0; j < fill.length; j++) { + if (fillGradientStops[j]) { + stop = fillGradientStops[j] / lines.length + _i3 / lines.length; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[j]); + currentIteration++; + } + } + } else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); + + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + totalIterations = fill.length + 1; + currentIteration = 1; + + for (var _i4 = 0; _i4 < fill.length; _i4++) { + if (fillGradientStops[_i4]) { + stop = fillGradientStops[_i4]; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[_i4]); + currentIteration++; + } + } + + return gradient; + }; + + /** + * Destroys this text object. + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majority of the time the texture will not be shared with any other Sprites. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well + */ + + + Text.prototype.destroy = function destroy(options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + + options = Object.assign({}, defaultDestroyOptions, options); + + _Sprite.prototype.destroy.call(this, options); + + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + + this._style = null; + }; + + /** + * The width of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + /** + * Generates a font style string to use for Text.calculateFontProperties(). Takes the same parameter + * as Text.style. + * + * @static + * @param {object|TextStyle} style - String representing the style of the font + * @return {string} Font style string, for passing to Text.calculateFontProperties() + */ + Text.getFontStyle = function getFontStyle(style) { + style = style || {}; + + if (!(style instanceof _TextStyle2.default)) { + style = new _TextStyle2.default(style); + } + + // build canvas api font setting from individual components. Convert a numeric style.fontSize to px + var fontSizeString = typeof style.fontSize === 'number' ? style.fontSize + 'px' : style.fontSize; + + // Clean-up fontFamily property by quoting each font name + // this will support font names with spaces + var fontFamilies = style.fontFamily; + + if (!Array.isArray(style.fontFamily)) { + fontFamilies = style.fontFamily.split(','); + } + + for (var i = fontFamilies.length - 1; i >= 0; i--) { + // Trim any extra white-space + var fontFamily = fontFamilies[i].trim(); + + // Check if font already contains strings + if (!/([\"\'])[^\'\"]+\1/.test(fontFamily)) { + fontFamily = '"' + fontFamily + '"'; + } + fontFamilies[i] = fontFamily; + } + + return style.fontStyle + ' ' + style.fontVariant + ' ' + style.fontWeight + ' ' + fontSizeString + ' ' + fontFamilies.join(','); + }; + + /** + * Calculates the ascent, descent and fontSize of a given fontStyle + * + * @static + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ + + + Text.calculateFontProperties = function calculateFontProperties(fontStyle) { + // as this method is used for preparing assets, don't recalculate things if we don't need to + if (Text.fontPropertiesCache[fontStyle]) { + return Text.fontPropertiesCache[fontStyle]; + } + + var properties = {}; + + var canvas = Text.fontPropertiesCanvas; + var context = Text.fontPropertiesContext; + + context.font = fontStyle; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('M').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = fontStyle; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i = 0; + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } else { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var _j = 0; _j < line; _j += 4) { + if (imagedata[idx + _j] !== 255) { + stop = true; + break; + } + } + + if (!stop) { + idx -= line; + } else { + break; + } + } + + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + + Text.fontPropertiesCache[fontStyle] = properties; + + return properties; + }; + + _createClass(Text, [{ + key: 'width', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * Set the style of the text. Set up an event listener to listen for changes on the style + * object and mark the text as dirty. + * + * @member {object|PIXI.TextStyle} + */ + + }, { + key: 'style', + get: function get() { + return this._style; + }, + set: function set(style) // eslint-disable-line require-jsdoc + { + style = style || {}; + + if (style instanceof _TextStyle2.default) { + this._style = style; + } else { + this._style = new _TextStyle2.default(style); + } + + this.localStyleID = -1; + this.dirty = true; + } + + /** + * Set the copy for the text object. To split a line you can use '\n'. + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(text) // eslint-disable-line require-jsdoc + { + text = String(text === '' || text === null || text === undefined ? ' ' : text); + + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + } + }]); + + return Text; +}(_Sprite3.default); + +exports.default = Text; + + +Text.fontPropertiesCache = {}; +Text.fontPropertiesCanvas = document.createElement('canvas'); +Text.fontPropertiesContext = Text.fontPropertiesCanvas.getContext('2d'); + +},{"../const":44,"../math":68,"../settings":99,"../sprites/Sprite":100,"../textures/Texture":112,"../utils":120,"../utils/trimCanvas":124,"./TextStyle":107}],107:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // disabling eslint for now, going to rewrite this in v5 +/* eslint-disable */ + +var _const = require('../const'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: '#000000', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: _const.TEXT_GRADIENT.LINEAR_VERTICAL, + fillGradientStops: [], + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + trim: false, + wordWrap: false, + wordWrapWidth: 100 +}; + +/** + * A TextStyle Object decorates a Text Object. It can be shared between + * multiple Text objects. Changing the style will update all text objects using it. + * + * @class + * @memberof PIXI + */ + +var TextStyle = function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string} [style.dropShadowColor='#000000'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours + * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} + * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set + * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * @param {string|string[]} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', 800' or '900') + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Default is 'miter' (creates a sharp corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {boolean} [style.trim=false] - Trim transparent borders + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + _classCallCheck(this, TextStyle); + + this.styleID = 0; + + Object.assign(this, defaultStyle, style); + } + + /** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return {PIXI.TextStyle} New cloned TextStyle object + */ + + + TextStyle.prototype.clone = function clone() { + var clonedProperties = {}; + + for (var key in defaultStyle) { + clonedProperties[key] = this[key]; + } + + return new TextStyle(clonedProperties); + }; + + /** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ + + + TextStyle.prototype.reset = function reset() { + Object.assign(this, defaultStyle); + }; + + _createClass(TextStyle, [{ + key: 'align', + get: function get() { + return this._align; + }, + set: function set(align) { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + } + }, { + key: 'breakWords', + get: function get() { + return this._breakWords; + }, + set: function set(breakWords) { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + } + }, { + key: 'dropShadow', + get: function get() { + return this._dropShadow; + }, + set: function set(dropShadow) { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + } + }, { + key: 'dropShadowAlpha', + get: function get() { + return this._dropShadowAlpha; + }, + set: function set(dropShadowAlpha) { + if (this._dropShadowAlpha !== dropShadowAlpha) { + this._dropShadowAlpha = dropShadowAlpha; + this.styleID++; + } + } + }, { + key: 'dropShadowAngle', + get: function get() { + return this._dropShadowAngle; + }, + set: function set(dropShadowAngle) { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + } + }, { + key: 'dropShadowBlur', + get: function get() { + return this._dropShadowBlur; + }, + set: function set(dropShadowBlur) { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + } + }, { + key: 'dropShadowColor', + get: function get() { + return this._dropShadowColor; + }, + set: function set(dropShadowColor) { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + } + }, { + key: 'dropShadowDistance', + get: function get() { + return this._dropShadowDistance; + }, + set: function set(dropShadowDistance) { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + } + }, { + key: 'fill', + get: function get() { + return this._fill; + }, + set: function set(fill) { + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + } + }, { + key: 'fillGradientType', + get: function get() { + return this._fillGradientType; + }, + set: function set(fillGradientType) { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + } + }, { + key: 'fillGradientStops', + get: function get() { + return this._fillGradientStops; + }, + set: function set(fillGradientStops) { + if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { + this._fillGradientStops = fillGradientStops; + this.styleID++; + } + } + }, { + key: 'fontFamily', + get: function get() { + return this._fontFamily; + }, + set: function set(fontFamily) { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + } + }, { + key: 'fontSize', + get: function get() { + return this._fontSize; + }, + set: function set(fontSize) { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + } + }, { + key: 'fontStyle', + get: function get() { + return this._fontStyle; + }, + set: function set(fontStyle) { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + } + }, { + key: 'fontVariant', + get: function get() { + return this._fontVariant; + }, + set: function set(fontVariant) { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + } + }, { + key: 'fontWeight', + get: function get() { + return this._fontWeight; + }, + set: function set(fontWeight) { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + } + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(letterSpacing) { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + } + }, { + key: 'lineHeight', + get: function get() { + return this._lineHeight; + }, + set: function set(lineHeight) { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + } + }, { + key: 'lineJoin', + get: function get() { + return this._lineJoin; + }, + set: function set(lineJoin) { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + } + }, { + key: 'miterLimit', + get: function get() { + return this._miterLimit; + }, + set: function set(miterLimit) { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + } + }, { + key: 'padding', + get: function get() { + return this._padding; + }, + set: function set(padding) { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + } + }, { + key: 'stroke', + get: function get() { + return this._stroke; + }, + set: function set(stroke) { + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + } + }, { + key: 'strokeThickness', + get: function get() { + return this._strokeThickness; + }, + set: function set(strokeThickness) { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + } + }, { + key: 'textBaseline', + get: function get() { + return this._textBaseline; + }, + set: function set(textBaseline) { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + } + }, { + key: 'trim', + get: function get() { + return this._trim; + }, + set: function set(trim) { + if (this._trim !== trim) { + this._trim = trim; + this.styleID++; + } + } + }, { + key: 'wordWrap', + get: function get() { + return this._wordWrap; + }, + set: function set(wordWrap) { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + } + }, { + key: 'wordWrapWidth', + get: function get() { + return this._wordWrapWidth; + }, + set: function set(wordWrapWidth) { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + } + }]); + + return TextStyle; +}(); + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * + * @param {number|number[]} color + * @return {string} The color as a string. + */ + + +exports.default = TextStyle; +function getSingleColor(color) { + if (typeof color === 'number') { + return (0, _utils.hex2string)(color); + } else if (typeof color === 'string') { + if (color.indexOf('0x') === 0) { + color = color.replace('0x', '#'); + } + } + + return color; +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * + * @param {number|number[]} color + * @return {string} The color as a string. + */ +function getColor(color) { + if (!Array.isArray(color)) { + return getSingleColor(color); + } else { + for (var i = 0; i < color.length; ++i) { + color[i] = getSingleColor(color[i]); + } + + return color; + } +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * + * @param {Array} array1 First array to compare + * @param {Array} array2 Second array to compare + * @return {boolean} Do the arrays contain the same values in the same order + */ +function areArraysEqual(array1, array2) { + if (!Array.isArray(array1) || !Array.isArray(array2)) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } + + return true; +} + +},{"../const":44,"../utils":120}],108:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let baseRenderTexture = new PIXI.BaseRenderTexture(renderer, 800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * baseRenderTexture.render(sprite); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let baseRenderTexture = new PIXI.BaseRenderTexture(100, 100); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var BaseRenderTexture = function (_BaseTexture) { + _inherits(BaseRenderTexture, _BaseTexture); + + /** + * @param {number} [width=100] - The width of the base render texture + * @param {number} [height=100] - The height of the base render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + */ + function BaseRenderTexture() { + var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + + _classCallCheck(this, BaseRenderTexture); + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, null, scaleMode)); + + _this.resolution = resolution || _settings2.default.RESOLUTION; + + _this.width = width; + _this.height = height; + + _this.realWidth = _this.width * _this.resolution; + _this.realHeight = _this.height * _this.resolution; + + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + _this.hasLoaded = true; + + /** + * A map of renderer IDs to webgl renderTargets + * + * @private + * @member {object} + */ + _this._glRenderTargets = {}; + + /** + * A reference to the canvas render target (we only need one as this can be shared across renderers) + * + * @private + * @member {object} + */ + _this._canvasRenderTarget = null; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + return _this; + } + + /** + * Resizes the BaseRenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + */ + + + BaseRenderTexture.prototype.resize = function resize(width, height) { + if (width === this.width && height === this.height) { + return; + } + + this.valid = width > 0 && height > 0; + + this.width = width; + this.height = height; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + if (!this.valid) { + return; + } + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + */ + + + BaseRenderTexture.prototype.destroy = function destroy() { + _BaseTexture.prototype.destroy.call(this, true); + this.renderer = null; + }; + + return BaseRenderTexture; +}(_BaseTexture3.default); + +exports.default = BaseRenderTexture; + +},{"../settings":99,"./BaseTexture":109}],109:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var BaseTexture = function (_EventEmitter) { + _inherits(BaseTexture, _EventEmitter); + + /** + * @param {HTMLImageElement|HTMLCanvasElement} [source] - the source object of the texture. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture + */ + function BaseTexture(source, scaleMode, resolution) { + _classCallCheck(this, BaseTexture); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.uid = (0, _utils.uid)(); + + _this.touched = 0; + + /** + * The resolution / device pixel ratio of the texture + * + * @member {number} + * @default 1 + */ + _this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The width of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.width = 100; + + /** + * The height of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.height = 100; + + // TODO docs + // used to store the actual dimensions of the source + /** + * Used to store the actual width of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realWidth = 100; + /** + * Used to store the actual height of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realHeight = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Set to true once the base texture has successfully loaded. + * + * This is never true if the underlying source fails to load or has no texture data. + * + * @readonly + * @member {boolean} + */ + _this.hasLoaded = false; + + /** + * Set to true if the source is currently loading. + * + * If an Image source is loading the 'loaded' or 'error' event will be + * dispatched when the operation ends. An underyling source that is + * immediately-available bypasses loading entirely. + * + * @readonly + * @member {boolean} + */ + _this.isLoading = false; + + /** + * The image source that is used to create the texture. + * + * TODO: Make this a setter that calls loadSource(); + * + * @readonly + * @member {HTMLImageElement|HTMLCanvasElement} + */ + _this.source = null; // set in loadSource, if at all + + /** + * The image source that is used to create the texture. This is used to + * store the original Svg source when it is replaced with a canvas element. + * + * TODO: Currently not in use but could be used when re-scaling svg. + * + * @readonly + * @member {Image} + */ + _this.origSource = null; // set in loadSvg, if at all + + /** + * Type of image defined in source, eg. `png` or `svg` + * + * @readonly + * @member {string} + */ + _this.imageType = null; // set in updateImageType + + /** + * Scale for source image. Used with Svg images to scale them before rasterization. + * + * @readonly + * @member {number} + */ + _this.sourceScale = 1.0; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * All blend modes, and shaders written for default value. Change it on your own risk. + * + * @member {boolean} + * @default true + */ + _this.premultipliedAlpha = true; + + /** + * The image url of the texture + * + * @member {string} + */ + _this.imageUrl = null; + + /** + * Whether or not the texture is a power of two, try to use power of two textures as much + * as you can + * + * @private + * @member {boolean} + */ + _this.isPowerOfTwo = false; + + // used for webGL + + /** + * + * Set this to true if a mipmap of this texture needs to be generated. This value needs + * to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @member {boolean} + * @see PIXI.MIPMAP_TEXTURES + */ + _this.mipmap = _settings2.default.MIPMAP_TEXTURES; + + /** + * + * WebGL Texture wrap mode + * + * @member {number} + * @see PIXI.WRAP_MODES + */ + _this.wrapMode = _settings2.default.WRAP_MODE; + + /** + * A map of renderer IDs to webgl textures + * + * @private + * @member {object} + */ + _this._glTextures = {}; + + _this._enabled = 0; + _this._virtalBoundId = -1; + + // if no source passed don't try to load + if (source) { + _this.loadSource(source); + } + + /** + * Fired when a not-immediately-available source finishes loading. + * + * @protected + * @event loaded + * @memberof PIXI.BaseTexture# + */ + + /** + * Fired when a not-immediately-available source fails to load. + * + * @protected + * @event error + * @memberof PIXI.BaseTexture# + */ + return _this; + } + + /** + * Updates the texture on all the webgl renderers, this also assumes the src has changed. + * + * @fires update + */ + + + BaseTexture.prototype.update = function update() { + // Svg size is handled during load + if (this.imageType !== 'svg') { + this.realWidth = this.source.naturalWidth || this.source.videoWidth || this.source.width; + this.realHeight = this.source.naturalHeight || this.source.videoHeight || this.source.height; + + this._updateDimensions(); + } + + this.emit('update', this); + }; + + /** + * Update dimensions from real values + */ + + + BaseTexture.prototype._updateDimensions = function _updateDimensions() { + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + this.isPowerOfTwo = _bitTwiddle2.default.isPow2(this.realWidth) && _bitTwiddle2.default.isPow2(this.realHeight); + }; + + /** + * Load a source. + * + * If the source is not-immediately-available, such as an image that needs to be + * downloaded, then the 'loaded' or 'error' event will be dispatched in the future + * and `hasLoaded` will remain false after this call. + * + * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: + * + * if (texture.hasLoaded) { + * // texture ready for use + * } else if (texture.isLoading) { + * // listen to 'loaded' and/or 'error' events on texture + * } else { + * // not loading, not going to load UNLESS the source is reloaded + * // (it may still make sense to listen to the events) + * } + * + * @protected + * @param {HTMLImageElement|HTMLCanvasElement} source - the source object of the texture. + */ + + + BaseTexture.prototype.loadSource = function loadSource(source) { + var _this2 = this; + + var wasLoading = this.isLoading; + + this.hasLoaded = false; + this.isLoading = false; + + if (wasLoading && this.source) { + this.source.onload = null; + this.source.onerror = null; + } + + var firstSourceLoaded = !this.source; + + this.source = source; + + // Apply source if loaded. Otherwise setup appropriate loading monitors. + if ((source.src && source.complete || source.getContext) && source.width && source.height) { + this._updateImageType(); + + if (this.imageType === 'svg') { + this._loadSvgSource(); + } else { + this._sourceLoaded(); + } + + if (firstSourceLoaded) { + // send loaded event if previous source was null and we have been passed a pre-loaded IMG element + this.emit('loaded', this); + } + } else if (!source.getContext) { + var _ret = function () { + // Image fail / not ready + _this2.isLoading = true; + + var scope = _this2; + + source.onload = function () { + scope._updateImageType(); + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope._sourceLoaded(); + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + scope.emit('loaded', scope); + }; + + source.onerror = function () { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope.emit('error', scope); + }; + + // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element + // "The value of `complete` can thus change while a script is executing." + // So complete needs to be re-checked after the callbacks have been added.. + // NOTE: complete will be true if the image has no src so best to check if the src is set. + if (source.complete && source.src) { + // ..and if we're complete now, no need for callbacks + source.onload = null; + source.onerror = null; + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return { + v: void 0 + }; + } + + _this2.isLoading = false; + + if (source.width && source.height) { + _this2._sourceLoaded(); + + // If any previous subscribers possible + if (wasLoading) { + _this2.emit('loaded', _this2); + } + } + // If any previous subscribers possible + else if (wasLoading) { + _this2.emit('error', _this2); + } + } + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + }; + + /** + * Updates type of the source image. + */ + + + BaseTexture.prototype._updateImageType = function _updateImageType() { + if (!this.imageUrl) { + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + var imageType = void 0; + + if (dataUri && dataUri.mediaType === 'image') { + // Check for subType validity + var firstSubType = dataUri.subType.split('+')[0]; + + imageType = (0, _utils.getUrlFileExtension)('.' + firstSubType); + + if (!imageType) { + throw new Error('Invalid image type in data URI.'); + } + } else { + imageType = (0, _utils.getUrlFileExtension)(this.imageUrl); + + if (!imageType) { + imageType = 'png'; + } + } + + this.imageType = imageType; + }; + + /** + * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls + * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. + */ + + + BaseTexture.prototype._loadSvgSource = function _loadSvgSource() { + if (this.imageType !== 'svg') { + // Do nothing if source is not svg + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + + if (dataUri) { + this._loadSvgSourceUsingDataUri(dataUri); + } else { + // We got an URL, so we need to do an XHR to check the svg size + this._loadSvgSourceUsingXhr(); + } + }; + + /** + * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`. + * + * @param {string} dataUri - The data uri to load from. + */ + + + BaseTexture.prototype._loadSvgSourceUsingDataUri = function _loadSvgSourceUsingDataUri(dataUri) { + var svgString = void 0; + + if (dataUri.encoding === 'base64') { + if (!atob) { + throw new Error('Your browser doesn\'t support base64 conversions.'); + } + svgString = atob(dataUri.data); + } else { + svgString = dataUri.data; + } + + this._loadSvgSourceUsingString(svgString); + }; + + /** + * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. + */ + + + BaseTexture.prototype._loadSvgSourceUsingXhr = function _loadSvgSourceUsingXhr() { + var _this3 = this; + + var svgXhr = new XMLHttpRequest(); + + // This throws error on IE, so SVG Document can't be used + // svgXhr.responseType = 'document'; + + // This is not needed since we load the svg as string (breaks IE too) + // but overrideMimeType() can be used to force the response to be parsed as XML + // svgXhr.overrideMimeType('image/svg+xml'); + + svgXhr.onload = function () { + if (svgXhr.readyState !== svgXhr.DONE || svgXhr.status !== 200) { + throw new Error('Failed to load SVG using XHR.'); + } + + _this3._loadSvgSourceUsingString(svgXhr.response); + }; + + svgXhr.onerror = function () { + return _this3.emit('error', _this3); + }; + + svgXhr.open('GET', this.imageUrl, true); + svgXhr.send(); + }; + + /** + * Loads texture using an SVG string. The original SVG Image is stored as `origSource` and the + * created canvas is the new `source`. The SVG is scaled using `sourceScale`. Called by + * `_loadSvgSourceUsingXhr` or `_loadSvgSourceUsingDataUri`. + * + * @param {string} svgString SVG source as string + * + * @fires loaded + */ + + + BaseTexture.prototype._loadSvgSourceUsingString = function _loadSvgSourceUsingString(svgString) { + var svgSize = (0, _utils.getSvgSize)(svgString); + + var svgWidth = svgSize.width; + var svgHeight = svgSize.height; + + if (!svgWidth || !svgHeight) { + throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); + } + + // Scale realWidth and realHeight + this.realWidth = Math.round(svgWidth * this.sourceScale); + this.realHeight = Math.round(svgHeight * this.sourceScale); + + this._updateDimensions(); + + // Create a canvas element + var canvas = document.createElement('canvas'); + + canvas.width = this.realWidth; + canvas.height = this.realHeight; + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + + // Draw the Svg to the canvas + canvas.getContext('2d').drawImage(this.source, 0, 0, svgWidth, svgHeight, 0, 0, this.realWidth, this.realHeight); + + // Replace the original source image with the canvas + this.origSource = this.source; + this.source = canvas; + + // Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`) + _utils.BaseTextureCache[canvas._pixiId] = this; + + this.isLoading = false; + this._sourceLoaded(); + this.emit('loaded', this); + }; + + /** + * Used internally to update the width, height, and some other tracking vars once + * a source has successfully loaded. + * + * @private + */ + + + BaseTexture.prototype._sourceLoaded = function _sourceLoaded() { + this.hasLoaded = true; + this.update(); + }; + + /** + * Destroys this base texture + * + */ + + + BaseTexture.prototype.destroy = function destroy() { + if (this.imageUrl) { + delete _utils.BaseTextureCache[this.imageUrl]; + delete _utils.TextureCache[this.imageUrl]; + + this.imageUrl = null; + + if (!navigator.isCocoonJS) { + this.source.src = ''; + } + } + // An svg source has both `imageUrl` and `__pixiId`, so no `else if` here + if (this.source && this.source._pixiId) { + delete _utils.BaseTextureCache[this.source._pixiId]; + } + + this.source = null; + + this.dispose(); + }; + + /** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + */ + + + BaseTexture.prototype.dispose = function dispose() { + this.emit('dispose', this); + }; + + /** + * Changes the source image of the texture. + * The original source must be an Image element. + * + * @param {string} newSrc - the path of the image + */ + + + BaseTexture.prototype.updateSourceImage = function updateSourceImage(newSrc) { + this.source.src = newSrc; + + this.loadSource(this.source); + }; + + /** + * Helper function that creates a base texture from the given image url. + * If the image is not in the base texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + // new Image() breaks tex loading in some versions of Chrome. + // See https://code.google.com/p/chromium/issues/detail?id=238071 + var image = new Image(); // document.createElement('img'); + + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + image.crossOrigin = (0, _determineCrossOrigin2.default)(imageUrl); + } + + baseTexture = new BaseTexture(image, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + image.src = imageUrl; // Setting this triggers load + + _utils.BaseTextureCache[imageUrl] = baseTexture; + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode) { + if (!canvas._pixiId) { + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[canvas._pixiId]; + + if (!baseTexture) { + baseTexture = new BaseTexture(canvas, scaleMode); + _utils.BaseTextureCache[canvas._pixiId] = baseTexture; + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture based on the source you provide. + * The source can be - image url, image element, canvas element. + * + * @static + * @param {string|HTMLImageElement|HTMLCanvasElement} source - The source to create base texture from. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.from = function from(source, scaleMode, sourceScale) { + if (typeof source === 'string') { + return BaseTexture.fromImage(source, undefined, scaleMode, sourceScale); + } else if (source instanceof HTMLImageElement) { + var imageUrl = source.src; + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + baseTexture = new BaseTexture(source, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + _utils.BaseTextureCache[imageUrl] = baseTexture; + } + + return baseTexture; + } else if (source instanceof HTMLCanvasElement) { + return BaseTexture.fromCanvas(source, scaleMode); + } + + // lets assume its a base texture! + return source; + }; + + return BaseTexture; +}(_eventemitter2.default); + +exports.default = BaseTexture; + +},{"../settings":99,"../utils":120,"../utils/determineCrossOrigin":119,"bit-twiddle":1,"eventemitter3":3}],110:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseRenderTexture = require('./BaseRenderTexture'); + +var _BaseRenderTexture2 = _interopRequireDefault(_BaseRenderTexture); + +var _Texture2 = require('./Texture'); + +var _Texture3 = _interopRequireDefault(_Texture2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A RenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let renderTexture = PIXI.RenderTexture.create(800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let renderTexture = new PIXI.RenderTexture.create(100, 100); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.Texture + * @memberof PIXI + */ +var RenderTexture = function (_Texture) { + _inherits(RenderTexture, _Texture); + + /** + * @param {PIXI.BaseRenderTexture} baseRenderTexture - The renderer used for this RenderTexture + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + */ + function RenderTexture(baseRenderTexture, frame) { + _classCallCheck(this, RenderTexture); + + // support for legacy.. + var _legacyRenderer = null; + + if (!(baseRenderTexture instanceof _BaseRenderTexture2.default)) { + /* eslint-disable prefer-rest-params, no-console */ + var width = arguments[1]; + var height = arguments[2]; + var scaleMode = arguments[3]; + var resolution = arguments[4]; + + // we have an old render texture.. + console.warn('Please use RenderTexture.create(' + width + ', ' + height + ') instead of the ctor directly.'); + _legacyRenderer = arguments[0]; + /* eslint-enable prefer-rest-params, no-console */ + + frame = null; + baseRenderTexture = new _BaseRenderTexture2.default(width, height, scaleMode, resolution); + } + + /** + * The base texture object that this texture uses + * + * @member {BaseTexture} + */ + + var _this = _possibleConstructorReturn(this, _Texture.call(this, baseRenderTexture, frame)); + + _this.legacyRenderer = _legacyRenderer; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = true; + + _this._updateUvs(); + return _this; + } + + /** + * Resizes the RenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + * @param {boolean} doNotResizeBaseTexture - Should the baseTexture.width and height values be resized as well? + */ + + + RenderTexture.prototype.resize = function resize(width, height, doNotResizeBaseTexture) { + // TODO - could be not required.. + this.valid = width > 0 && height > 0; + + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + + if (!doNotResizeBaseTexture) { + this.baseTexture.resize(width, height); + } + + this._updateUvs(); + }; + + /** + * A short hand way of creating a render texture. + * + * @param {number} [width=100] - The width of the render texture + * @param {number} [height=100] - The height of the render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.RenderTexture} The new render texture + */ + + + RenderTexture.create = function create(width, height, scaleMode, resolution) { + return new RenderTexture(new _BaseRenderTexture2.default(width, height, scaleMode, resolution)); + }; + + return RenderTexture; +}(_Texture3.default); + +exports.default = RenderTexture; + +},{"./BaseRenderTexture":108,"./Texture":112}],111:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _ = require('../'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Utility class for maintaining reference to a collection + * of Textures on a single Spritesheet. + * + * @class + * @memberof PIXI + */ +var Spritesheet = function () { + _createClass(Spritesheet, null, [{ + key: 'BATCH_SIZE', + + /** + * The maximum number of Textures to build per process. + * + * @type {number} + * @default 1000 + */ + get: function get() { + return 1000; + } + + /** + * @param {PIXI.BaseTexture} baseTexture Reference to the source BaseTexture object. + * @param {Object} data - Spritesheet image data. + * @param {string} [resolutionFilename] - The filename to consider when determining + * the resolution of the spritesheet. If not provided, the imageUrl will + * be used on the BaseTexture. + */ + + }]); + + function Spritesheet(baseTexture, data) { + var resolutionFilename = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + _classCallCheck(this, Spritesheet); + + /** + * Reference to ths source texture + * @type {PIXI.BaseTexture} + */ + this.baseTexture = baseTexture; + + /** + * Map of spritesheet textures. + * @type {Object} + */ + this.textures = {}; + + /** + * Reference to the original JSON data. + * @type {Object} + */ + this.data = data; + + /** + * The resolution of the spritesheet. + * @type {number} + */ + this.resolution = this._updateResolution(resolutionFilename || this.baseTexture.imageUrl); + + /** + * Map of spritesheet frames. + * @type {Object} + * @private + */ + this._frames = this.data.frames; + + /** + * Collection of frame names. + * @type {string[]} + * @private + */ + this._frameKeys = Object.keys(this._frames); + + /** + * Current batch index being processed. + * @type {number} + * @private + */ + this._batchIndex = 0; + + /** + * Callback when parse is completed. + * @type {Function} + * @private + */ + this._callback = null; + } + + /** + * Generate the resolution from the filename or fallback + * to the meta.scale field of the JSON data. + * + * @private + * @param {string} resolutionFilename - The filename to use for resolving + * the default resolution. + * @return {number} Resolution to use for spritesheet. + */ + + + Spritesheet.prototype._updateResolution = function _updateResolution(resolutionFilename) { + var scale = this.data.meta.scale; + + // Use a defaultValue of `null` to check if a url-based resolution is set + var resolution = (0, _utils.getResolutionOfUrl)(resolutionFilename, null); + + // No resolution found via URL + if (resolution === null) { + // Use the scale value or default to 1 + resolution = scale !== undefined ? parseFloat(scale) : 1; + } + + // For non-1 resolutions, update baseTexture + if (resolution !== 1) { + this.baseTexture.resolution = resolution; + this.baseTexture.update(); + } + + return resolution; + }; + + /** + * Parser spritesheet from loaded data. This is done asynchronously + * to prevent creating too many Texture within a single process. + * + * @param {Function} callback - Callback when complete returns + * a map of the Textures for this spritesheet. + */ + + + Spritesheet.prototype.parse = function parse(callback) { + this._batchIndex = 0; + this._callback = callback; + + if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) { + this._processFrames(0); + this._parseComplete(); + } else { + this._nextBatch(); + } + }; + + /** + * Process a batch of frames + * + * @private + * @param {number} initialFrameIndex - The index of frame to start. + */ + + + Spritesheet.prototype._processFrames = function _processFrames(initialFrameIndex) { + var frameIndex = initialFrameIndex; + var maxFrames = Spritesheet.BATCH_SIZE; + + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { + var i = this._frameKeys[frameIndex]; + var rect = this._frames[i].frame; + + if (rect) { + var frame = null; + var trim = null; + var orig = new _.Rectangle(0, 0, this._frames[i].sourceSize.w / this.resolution, this._frames[i].sourceSize.h / this.resolution); + + if (this._frames[i].rotated) { + frame = new _.Rectangle(rect.x / this.resolution, rect.y / this.resolution, rect.h / this.resolution, rect.w / this.resolution); + } else { + frame = new _.Rectangle(rect.x / this.resolution, rect.y / this.resolution, rect.w / this.resolution, rect.h / this.resolution); + } + + // Check to see if the sprite is trimmed + if (this._frames[i].trimmed) { + trim = new _.Rectangle(this._frames[i].spriteSourceSize.x / this.resolution, this._frames[i].spriteSourceSize.y / this.resolution, rect.w / this.resolution, rect.h / this.resolution); + } + + this.textures[i] = new _.Texture(this.baseTexture, frame, orig, trim, this._frames[i].rotated ? 2 : 0); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage functions + _utils.TextureCache[i] = this.textures[i]; + } + + frameIndex++; + } + }; + + /** + * The parse has completed. + * + * @private + */ + + + Spritesheet.prototype._parseComplete = function _parseComplete() { + var callback = this._callback; + + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); + }; + + /** + * Begin the next batch of textures. + * + * @private + */ + + + Spritesheet.prototype._nextBatch = function _nextBatch() { + var _this = this; + + this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); + this._batchIndex++; + setTimeout(function () { + if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { + _this._nextBatch(); + } else { + _this._parseComplete(); + } + }, 0); + }; + + /** + * Destroy Spritesheet and don't use after this. + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Spritesheet.prototype.destroy = function destroy() { + var destroyBase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + for (var i in this.textures) { + this.textures[i].destroy(); + } + this._frames = null; + this._frameKeys = null; + this.data = null; + this.textures = null; + if (destroyBase) { + this.baseTexture.destroy(); + } + this.baseTexture = null; + }; + + return Spritesheet; +}(); + +exports.default = Spritesheet; + +},{"../":63,"../utils":120}],112:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture = require('./BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _VideoBaseTexture = require('./VideoBaseTexture'); + +var _VideoBaseTexture2 = _interopRequireDefault(_VideoBaseTexture); + +var _TextureUvs = require('./TextureUvs'); + +var _TextureUvs2 = _interopRequireDefault(_TextureUvs); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _math = require('../math'); + +var _utils = require('../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided + * then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * let texture = PIXI.Texture.fromImage('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` + * + * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. + * You can check for this by checking the sprite's _textureID property. + * ```js + * var texture = PIXI.Texture.fromImage('assets/image.svg'); + * var sprite1 = new PIXI.Sprite(texture); + * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file + * ``` + * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var Texture = function (_EventEmitter) { + _inherits(Texture, _EventEmitter); + + /** + * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + * @param {PIXI.Rectangle} [orig] - The area of original texture + * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture + * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8} + */ + function Texture(baseTexture, frame, orig, trim, rotate) { + _classCallCheck(this, Texture); + + /** + * Does this Texture have any frame data assigned to it? + * + * @member {boolean} + */ + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.noFrame = false; + + if (!frame) { + _this.noFrame = true; + frame = new _math.Rectangle(0, 0, 1, 1); + } + + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @member {PIXI.BaseTexture} + */ + _this.baseTexture = baseTexture; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @member {PIXI.Rectangle} + */ + _this._frame = frame; + + /** + * This is the trimmed area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @member {boolean} + */ + _this.requiresUpdate = false; + + /** + * The WebGL UV data cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + _this._uvs = null; + + /** + * This is the area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + + _this._rotate = Number(rotate || 0); + + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); + } + + if (baseTexture.hasLoaded) { + if (_this.noFrame) { + frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + + // if there is no frame we should monitor for any base texture changes.. + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + _this.frame = frame; + } else { + baseTexture.once('loaded', _this.onBaseTextureLoaded, _this); + } + + /** + * Fired when the texture is updated. This happens if the frame or the baseTexture is updated. + * + * @event update + * @memberof PIXI.Texture# + * @protected + */ + + _this._updateID = 0; + + /** + * Extra field for extra plugins. May contain clamp settings and some matrices + * @type {Object} + */ + _this.transform = null; + return _this; + } + + /** + * Updates this texture on the gpu. + * + */ + + + Texture.prototype.update = function update() { + this.baseTexture.update(); + }; + + /** + * Called when the base texture is loaded + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureLoaded = function onBaseTextureLoaded(baseTexture) { + this._updateID++; + + // TODO this code looks confusing.. boo to abusing getters and setters! + if (this.noFrame) { + this.frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } else { + this.frame = this._frame; + } + + this.baseTexture.on('update', this.onBaseTextureUpdated, this); + this.emit('update', this); + }; + + /** + * Called when the base texture is updated + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated(baseTexture) { + this._updateID++; + + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Texture.prototype.destroy = function destroy(destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destroyed too.. + if (_utils.TextureCache[this.baseTexture.imageUrl]) { + delete _utils.TextureCache[this.baseTexture.imageUrl]; + } + + this.baseTexture.destroy(); + } + + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); + + this.baseTexture = null; + } + + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + + this.valid = false; + + this.off('dispose', this.dispose, this); + this.off('update', this.update, this); + }; + + /** + * Creates a new texture object that acts the same as this one. + * + * @return {PIXI.Texture} The new texture + */ + + + Texture.prototype.clone = function clone() { + return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); + }; + + /** + * Updates the internal WebGL UV cache. + * + * @protected + */ + + + Texture.prototype._updateUvs = function _updateUvs() { + if (!this._uvs) { + this._uvs = new _TextureUvs2.default(); + } + + this._uvs.set(this._frame, this.baseTexture, this.rotate); + + this._updateID++; + }; + + /** + * Helper function that creates a Texture object from the given image url. + * If the image is not in the texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var texture = _utils.TextureCache[imageUrl]; + + if (!texture) { + texture = new Texture(_BaseTexture2.default.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); + _utils.TextureCache[imageUrl] = texture; + } + + return texture; + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return texture; + }; + + /** + * Helper function that creates a new Texture based on the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromCanvas = function fromCanvas(canvas, scaleMode) { + return new Texture(_BaseTexture2.default.fromCanvas(canvas, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the given video element. + * + * @static + * @param {HTMLVideoElement|string} video - The URL or actual element of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideo = function fromVideo(video, scaleMode) { + if (typeof video === 'string') { + return Texture.fromVideoUrl(video, scaleMode); + } + + return new Texture(_VideoBaseTexture2.default.fromVideo(video, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the video url. + * + * @static + * @param {string} videoUrl - URL of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideoUrl = function fromVideoUrl(videoUrl, scaleMode) { + return new Texture(_VideoBaseTexture2.default.fromUrl(videoUrl, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} + * source - Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.from = function from(source) { + // TODO auto detect cross origin.. + // TODO pass in scale mode? + if (typeof source === 'string') { + var texture = _utils.TextureCache[source]; + + if (!texture) { + // check if its a video.. + var isVideo = source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/) !== null; + + if (isVideo) { + return Texture.fromVideoUrl(source); + } + + return Texture.fromImage(source); + } + + return texture; + } else if (source instanceof HTMLImageElement) { + return new Texture(_BaseTexture2.default.from(source)); + } else if (source instanceof HTMLCanvasElement) { + return Texture.fromCanvas(source); + } else if (source instanceof HTMLVideoElement) { + return Texture.fromVideo(source); + } else if (source instanceof _BaseTexture2.default) { + return new Texture(source); + } + + // lets assume its a texture! + return source; + }; + + /** + * Create a texture from a source and add to the cache. + * + * @static + * @param {HTMLImageElement|HTMLCanvasElement} source - The input source. + * @param {String} imageUrl - File name of texture, for cache and resolving resolution. + * @param {String} [name] - Human readible name for the texture cache. If no name is + * specified, only `imageUrl` will be used as the cache ID. + * @return {PIXI.Texture} Output texture + */ + + + Texture.fromLoader = function fromLoader(source, imageUrl, name) { + var baseTexture = new _BaseTexture2.default(source, null, (0, _utils.getResolutionOfUrl)(imageUrl)); + var texture = new Texture(baseTexture); + + baseTexture.imageUrl = imageUrl; + + // No name, use imageUrl instead + if (!name) { + name = imageUrl; + } + + // lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions + _utils.BaseTextureCache[name] = baseTexture; + _utils.TextureCache[name] = texture; + + // also add references by url if they are different. + if (name !== imageUrl) { + _utils.BaseTextureCache[imageUrl] = baseTexture; + _utils.TextureCache[imageUrl] = texture; + } + + return texture; + }; + + /** + * Adds a texture to the global TextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the texture will be stored against. + */ + + + Texture.addTextureToCache = function addTextureToCache(texture, id) { + _utils.TextureCache[id] = texture; + }; + + /** + * Remove a texture from the global TextureCache. + * + * @static + * @param {string} id - The id of the texture to be removed + * @return {PIXI.Texture} The texture that was removed + */ + + + Texture.removeTextureFromCache = function removeTextureFromCache(id) { + var texture = _utils.TextureCache[id]; + + delete _utils.TextureCache[id]; + delete _utils.BaseTextureCache[id]; + + return texture; + }; + + /** + * The frame specifies the region of the base texture that this texture uses. + * + * @member {PIXI.Rectangle} + */ + + + _createClass(Texture, [{ + key: 'frame', + get: function get() { + return this._frame; + }, + set: function set(frame) // eslint-disable-line require-jsdoc + { + this._frame = frame; + + this.noFrame = false; + + if (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height) { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + ('X: ' + frame.x + ' + ' + frame.width + ' > ' + this.baseTexture.width + ' ') + ('Y: ' + frame.y + ' + ' + frame.height + ' > ' + this.baseTexture.height)); + } + + // this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + this.valid = frame && frame.width && frame.height && this.baseTexture.hasLoaded; + + if (!this.trim && !this.rotate) { + this.orig = frame; + } + + if (this.valid) { + this._updateUvs(); + } + } + + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.GroupD8} for explanation + * + * @member {number} + */ + + }, { + key: 'rotate', + get: function get() { + return this._rotate; + }, + set: function set(rotate) // eslint-disable-line require-jsdoc + { + this._rotate = rotate; + if (this.valid) { + this._updateUvs(); + } + } + + /** + * The width of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'width', + get: function get() { + return this.orig.width; + } + + /** + * The height of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.orig.height; + } + }]); + + return Texture; +}(_eventemitter2.default); + +/** + * An empty texture, used often to not have to create multiple empty textures. + * Can not be destroyed. + * + * @static + * @constant + */ + + +exports.default = Texture; +Texture.EMPTY = new Texture(new _BaseTexture2.default()); +Texture.EMPTY.destroy = function _emptyDestroy() {/* empty */}; +Texture.EMPTY.on = function _emptyOn() {/* empty */}; +Texture.EMPTY.once = function _emptyOnce() {/* empty */}; +Texture.EMPTY.emit = function _emptyEmit() {/* empty */}; + +},{"../math":68,"../utils":120,"./BaseTexture":109,"./TextureUvs":113,"./VideoBaseTexture":114,"eventemitter3":3}],113:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _GroupD = require('../math/GroupD8'); + +var _GroupD2 = _interopRequireDefault(_GroupD); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A standard object to store the Uvs of a texture + * + * @class + * @private + * @memberof PIXI + */ +var TextureUvs = function () { + /** + * + */ + function TextureUvs() { + _classCallCheck(this, TextureUvs); + + this.x0 = 0; + this.y0 = 0; + + this.x1 = 1; + this.y1 = 0; + + this.x2 = 1; + this.y2 = 1; + + this.x3 = 0; + this.y3 = 1; + + this.uvsUint32 = new Uint32Array(4); + } + + /** + * Sets the texture Uvs based on the given frame information. + * + * @private + * @param {PIXI.Rectangle} frame - The frame of the texture + * @param {PIXI.Rectangle} baseFrame - The base frame of the texture + * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8} + */ + + + TextureUvs.prototype.set = function set(frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + + // coordinates of center + var cX = frame.x / tw + w2; + var cY = frame.y / th + h2; + + rotate = _GroupD2.default.add(rotate, _GroupD2.default.NW); // NW is top-left corner + this.x0 = cX + w2 * _GroupD2.default.uX(rotate); + this.y0 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + w2 * _GroupD2.default.uX(rotate); + this.y1 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x2 = cX + w2 * _GroupD2.default.uX(rotate); + this.y2 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x3 = cX + w2 * _GroupD2.default.uX(rotate); + this.y3 = cY + h2 * _GroupD2.default.uY(rotate); + } else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + + this.uvsUint32[0] = (this.y0 * 65535 & 0xFFFF) << 16 | this.x0 * 65535 & 0xFFFF; + this.uvsUint32[1] = (this.y1 * 65535 & 0xFFFF) << 16 | this.x1 * 65535 & 0xFFFF; + this.uvsUint32[2] = (this.y2 * 65535 & 0xFFFF) << 16 | this.x2 * 65535 & 0xFFFF; + this.uvsUint32[3] = (this.y3 * 65535 & 0xFFFF) << 16 | this.x3 * 65535 & 0xFFFF; + }; + + return TextureUvs; +}(); + +exports.default = TextureUvs; + +},{"../math/GroupD8":64}],114:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _utils = require('../utils'); + +var _ticker = require('../ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture of a [playing] Video. + * + * Video base textures mimic Pixi BaseTexture.from.... method in their creation process. + * + * This can be used in several ways, such as: + * + * ```js + * let texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4'); + * + * let texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' }); + * + * let texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']); + * + * let texture = PIXI.VideoBaseTexture.fromUrls([ + * { src: '/video.webm', mime: 'video/webm' }, + * { src: '/video.mp4', mime: 'video/mp4' } + * ]); + * ``` + * + * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/). + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var VideoBaseTexture = function (_BaseTexture) { + _inherits(VideoBaseTexture, _BaseTexture); + + /** + * @param {HTMLVideoElement} source - Video source + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + */ + function VideoBaseTexture(source, scaleMode) { + _classCallCheck(this, VideoBaseTexture); + + if (!source) { + throw new Error('No video source element specified.'); + } + + // hook in here to check if video is already available. + // BaseTexture looks for a source.complete boolean, plus width & height. + + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + source.complete = true; + } + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, source, scaleMode)); + + _this.width = source.videoWidth; + _this.height = source.videoHeight; + + _this._autoUpdate = true; + _this._isAutoUpdating = false; + + /** + * When set to true will automatically play videos used by this texture once + * they are loaded. If false, it will not modify the playing state. + * + * @member {boolean} + * @default true + */ + _this.autoPlay = true; + + _this.update = _this.update.bind(_this); + _this._onCanPlay = _this._onCanPlay.bind(_this); + + source.addEventListener('play', _this._onPlayStart.bind(_this)); + source.addEventListener('pause', _this._onPlayStop.bind(_this)); + _this.hasLoaded = false; + _this.__loaded = false; + + if (!_this._isSourceReady()) { + source.addEventListener('canplay', _this._onCanPlay); + source.addEventListener('canplaythrough', _this._onCanPlay); + } else { + _this._onCanPlay(); + } + return _this; + } + + /** + * Returns true if the underlying source is playing. + * + * @private + * @return {boolean} True if playing. + */ + + + VideoBaseTexture.prototype._isSourcePlaying = function _isSourcePlaying() { + var source = this.source; + + return source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2; + }; + + /** + * Returns true if the underlying source is ready for playing. + * + * @private + * @return {boolean} True if ready. + */ + + + VideoBaseTexture.prototype._isSourceReady = function _isSourceReady() { + return this.source.readyState === 3 || this.source.readyState === 4; + }; + + /** + * Runs the update loop when the video is ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStart = function _onPlayStart() { + // Just in case the video has not received its can play even yet.. + if (!this.hasLoaded) { + this._onCanPlay(); + } + + if (!this._isAutoUpdating && this.autoUpdate) { + ticker.shared.add(this.update, this); + this._isAutoUpdating = true; + } + }; + + /** + * Fired when a pause event is triggered, stops the update loop + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStop = function _onPlayStop() { + if (this._isAutoUpdating) { + ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } + }; + + /** + * Fired when the video is loaded and ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onCanPlay = function _onCanPlay() { + this.hasLoaded = true; + + if (this.source) { + this.source.removeEventListener('canplay', this._onCanPlay); + this.source.removeEventListener('canplaythrough', this._onCanPlay); + + this.width = this.source.videoWidth; + this.height = this.source.videoHeight; + + // prevent multiple loaded dispatches.. + if (!this.__loaded) { + this.__loaded = true; + this.emit('loaded', this); + } + + if (this._isSourcePlaying()) { + this._onPlayStart(); + } else if (this.autoPlay) { + this.source.play(); + } + } + }; + + /** + * Destroys this texture + * + */ + + + VideoBaseTexture.prototype.destroy = function destroy() { + if (this._isAutoUpdating) { + ticker.shared.remove(this.update, this); + } + + if (this.source && this.source._pixiId) { + delete _utils.BaseTextureCache[this.source._pixiId]; + delete this.source._pixiId; + } + + _BaseTexture.prototype.destroy.call(this); + }; + + /** + * Mimic Pixi BaseTexture.from.... method. + * + * @static + * @param {HTMLVideoElement} video - Video to create texture from + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromVideo = function fromVideo(video, scaleMode) { + if (!video._pixiId) { + video._pixiId = 'video_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[video._pixiId]; + + if (!baseTexture) { + baseTexture = new VideoBaseTexture(video, scaleMode); + _utils.BaseTextureCache[video._pixiId] = baseTexture; + } + + return baseTexture; + }; + + /** + * Helper function that creates a new BaseTexture based on the given video element. + * This BaseTexture can then be used to create a texture + * + * @static + * @param {string|object|string[]|object[]} videoSrc - The URL(s) for the video. + * @param {string} [videoSrc.src] - One of the source urls for the video + * @param {string} [videoSrc.mime] - The mimetype of the video (e.g. 'video/mp4'). If not specified + * the url's extension will be used as the second part of the mime type. + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromUrl = function fromUrl(videoSrc, scaleMode) { + var video = document.createElement('video'); + + video.setAttribute('webkit-playsinline', ''); + video.setAttribute('playsinline', ''); + + // array of objects or strings + if (Array.isArray(videoSrc)) { + for (var i = 0; i < videoSrc.length; ++i) { + video.appendChild(createSource(videoSrc[i].src || videoSrc[i], videoSrc[i].mime)); + } + } + // single object or string + else { + video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); + } + + video.load(); + + return VideoBaseTexture.fromVideo(video, scaleMode); + }; + + /** + * Should the base texture automatically update itself, set to true by default + * + * @member {boolean} + */ + + + _createClass(VideoBaseTexture, [{ + key: 'autoUpdate', + get: function get() { + return this._autoUpdate; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + + if (!this._autoUpdate && this._isAutoUpdating) { + ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } else if (this._autoUpdate && !this._isAutoUpdating) { + ticker.shared.add(this.update, this); + this._isAutoUpdating = true; + } + } + } + }]); + + return VideoBaseTexture; +}(_BaseTexture3.default); + +exports.default = VideoBaseTexture; + + +VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; + +function createSource(path, type) { + if (!type) { + type = 'video/' + path.substr(path.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = path; + source.type = type; + + return source; +} + +},{"../ticker":116,"../utils":120,"./BaseTexture":109}],115:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// Internal event used by composed emitter +var TICK = 'tick'; + +/** + * A Ticker class that runs an update loop that other objects listen to. + * This class is composed around an EventEmitter object to add listeners + * meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, + * e.g. When the ticker is started and the emitter has listeners. + * + * @class + * @memberof PIXI.ticker + */ + +var Ticker = function () { + /** + * + */ + function Ticker() { + var _this = this; + + _classCallCheck(this, Ticker); + + /** + * Internal emitter used to fire 'tick' event + * @private + */ + this._emitter = new _eventemitter2.default(); + + /** + * Internal current frame request ID + * @private + */ + this._requestId = null; + + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + * @private + */ + this._maxElapsedMS = 100; + + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.ticker.Ticker#start} automatically + * when a listener is added. + * + * @member {boolean} + * @default false + */ + this.autoStart = false; + + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS} + * and is scaled with {@link PIXI.ticker.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * + * @member {number} + * @default 1 + */ + this.deltaTime = 1; + + /** + * Time elapsed in milliseconds from last frame to this frame. + * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime} + * is based, this value is neither capped nor scaled. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default 1 / TARGET_FPMS + */ + this.elapsedMS = 1 / _settings2.default.TARGET_FPMS; // default to target frame time + + /** + * The last time {@link PIXI.ticker.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default 0 + */ + this.lastTime = 0; + + /** + * Factor of current {@link PIXI.ticker.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + * + * @member {number} + * @default 1 + */ + this.speed = 1; + + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.ticker.Ticker#start} has been called. + * `false` if {@link PIXI.ticker.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.ticker.Ticker#autoStart} being `true` + * and a listener is added. + * + * @member {boolean} + * @default false + */ + this.started = false; + + /** + * Internal tick method bound to ticker instance. + * This is because in early 2015, Function.bind + * is still 60% slower in high performance scenarios. + * Also separating frame requests from update method + * so listeners may be called at any time and with + * any animation API, just invoke ticker.update(time). + * + * @private + * @param {number} time - Time since last tick. + */ + this._tick = function (time) { + _this._requestId = null; + + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._emitter.listeners(TICK, true)) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * + * @private + */ + + + Ticker.prototype._requestIfNeeded = function _requestIfNeeded() { + if (this._requestId === null && this._emitter.listeners(TICK, true)) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._requestId = requestAnimationFrame(this._tick); + } + }; + + /** + * Conditionally cancels a pending animation frame. + * + * @private + */ + + + Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; + + /** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * + * @private + */ + + + Ticker.prototype._startIfPossible = function _startIfPossible() { + if (this.started) { + this._requestIfNeeded(); + } else if (this.autoStart) { + this.start(); + } + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#on} internally for the + * internal 'tick' event. It checks if the emitter has listeners, + * and if so it requests a new animation frame at this point. + * + * @param {Function} fn - The listener function to be added for updates + * @param {Function} [context] - The listener context + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.add = function add(fn, context) { + this._emitter.on(TICK, fn, context); + + this._startIfPossible(); + + return this; + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#once} internally for the + * internal 'tick' event. It checks if the emitter has listeners, + * and if so it requests a new animation frame at this point. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context] - The listener context + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.addOnce = function addOnce(fn, context) { + this._emitter.once(TICK, fn, context); + + this._startIfPossible(); + + return this; + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#off} internally for 'tick' event. + * It checks if the emitter has listeners for 'tick' event. + * If it does, then it cancels the animation frame. + * + * @param {Function} [fn] - The listener function to be removed + * @param {Function} [context] - The listener context to be removed + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.remove = function remove(fn, context) { + this._emitter.off(TICK, fn, context); + + if (!this._emitter.listeners(TICK, true)) { + this._cancelIfNeeded(); + } + + return this; + }; + + /** + * Starts the ticker. If the ticker has listeners + * a new animation frame is requested at this point. + */ + + + Ticker.prototype.start = function start() { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + }; + + /** + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. + */ + + + Ticker.prototype.stop = function stop() { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; + + /** + * Triggers an update. An update entails setting the + * current {@link PIXI.ticker.Ticker#elapsedMS}, + * the current {@link PIXI.ticker.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.ticker.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + + + Ticker.prototype.update = function update() { + var currentTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : performance.now(); + + var elapsedMS = void 0; + + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + + this.deltaTime = elapsedMS * _settings2.default.TARGET_FPMS * this.speed; + + // Invoke listeners added to internal emitter + this._emitter.emit(TICK, this.deltaTime); + } else { + this.deltaTime = this.elapsedMS = 0; + } + + this.lastTime = currentTime; + }; + + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.ticker.Ticker#speed}, which is specific + * to scaling {@link PIXI.ticker.Ticker#deltaTime}. + * + * @member {number} + * @readonly + */ + + + _createClass(Ticker, [{ + key: 'FPS', + get: function get() { + return 1000 / this.elapsedMS; + } + + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.ticker.Ticker#update}. + * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.settings.TARGET_FPMS * 1000`. + * + * @member {number} + * @default 10 + */ + + }, { + key: 'minFPS', + get: function get() { + return 1000 / this._maxElapsedMS; + }, + set: function set(fps) // eslint-disable-line require-jsdoc + { + // Clamp: 0 to TARGET_FPMS + var minFPMS = Math.min(Math.max(0, fps) / 1000, _settings2.default.TARGET_FPMS); + + this._maxElapsedMS = 1 / minFPMS; + } + }]); + + return Ticker; +}(); + +exports.default = Ticker; + +},{"../settings":99,"eventemitter3":3}],116:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Ticker = exports.shared = undefined; + +var _Ticker = require('./Ticker'); + +var _Ticker2 = _interopRequireDefault(_Ticker); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The shared ticker instance used by {@link PIXI.extras.AnimatedSprite}. + * and by {@link PIXI.interaction.InteractionManager}. + * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` + * for this instance. Please follow the examples for usage, including + * how to opt-out of auto-starting the shared ticker. + * + * @example + * let ticker = PIXI.ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(800, 600); + * let stage = new PIXI.Container(); + * let interactionManager = PIXI.interaction.InteractionManager(renderer); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * + * @type {PIXI.ticker.Ticker} + * @memberof PIXI.ticker + */ +var shared = new _Ticker2.default(); + +shared.autoStart = true; + +/** + * @namespace PIXI.ticker + */ +exports.shared = shared; +exports.Ticker = _Ticker2.default; + +},{"./Ticker":115}],117:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = canUploadSameBuffer; +function canUploadSameBuffer() { + // Uploading the same buffer multiple times in a single frame can cause perf issues. + // Apparent on IOS so only check for that at the moment + // this check may become more complex if this issue pops up elsewhere. + var ios = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform); + + return !ios; +} + +},{}],118:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = createIndicesForQuads; +/** + * Generic Mask Stack data structure + * + * @memberof PIXI + * @function createIndicesForQuads + * @private + * @param {number} size - Number of quads + * @return {Uint16Array} indices + */ +function createIndicesForQuads(size) { + // the total number of indices in our array, there are 6 points per quad. + + var totalIndices = size * 6; + + var indices = new Uint16Array(totalIndices); + + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + indices[i + 0] = j + 0; + indices[i + 1] = j + 1; + indices[i + 2] = j + 2; + indices[i + 3] = j + 0; + indices[i + 4] = j + 2; + indices[i + 5] = j + 3; + } + + return indices; +} + +},{}],119:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = determineCrossOrigin; + +var _url2 = require('url'); + +var _url3 = _interopRequireDefault(_url2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var tempAnchor = void 0; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +function determineCrossOrigin(url) { + var loc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location; + + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url3.default.parse(tempAnchor.href); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +} + +},{"url":28}],120:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BaseTextureCache = exports.TextureCache = exports.mixins = exports.pluginTarget = exports.EventEmitter = exports.isMobile = undefined; +exports.uid = uid; +exports.hex2rgb = hex2rgb; +exports.hex2string = hex2string; +exports.rgb2hex = rgb2hex; +exports.getResolutionOfUrl = getResolutionOfUrl; +exports.decomposeDataUri = decomposeDataUri; +exports.getUrlFileExtension = getUrlFileExtension; +exports.getSvgSize = getSvgSize; +exports.skipHello = skipHello; +exports.sayHello = sayHello; +exports.isWebGLSupported = isWebGLSupported; +exports.sign = sign; +exports.removeItems = removeItems; + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _pluginTarget = require('./pluginTarget'); + +var _pluginTarget2 = _interopRequireDefault(_pluginTarget); + +var _mixin = require('./mixin'); + +var mixins = _interopRequireWildcard(_mixin); + +var _ismobilejs = require('ismobilejs'); + +var isMobile = _interopRequireWildcard(_ismobilejs); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var nextUid = 0; +var saidHello = false; + +/** + * @namespace PIXI.utils + */ +exports.isMobile = isMobile; +exports.EventEmitter = _eventemitter2.default; +exports.pluginTarget = _pluginTarget2.default; +exports.mixins = mixins; + +/** + * Gets the next unique identifier + * + * @memberof PIXI.utils + * @function uid + * @return {number} The next unique identifier to use. + */ + +function uid() { + return ++nextUid; +} + +/** + * Converts a hex color number to an [R, G, B] array + * + * @memberof PIXI.utils + * @function hex2rgb + * @param {number} hex - The number to convert + * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one + * @return {number[]} An array representing the [R, G, B] of the color. + */ +function hex2rgb(hex, out) { + out = out || []; + + out[0] = (hex >> 16 & 0xFF) / 255; + out[1] = (hex >> 8 & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + + return out; +} + +/** + * Converts a hex color number to a string. + * + * @memberof PIXI.utils + * @function hex2string + * @param {number} hex - Number in hex + * @return {string} The string color. + */ +function hex2string(hex) { + hex = hex.toString(16); + hex = '000000'.substr(0, 6 - hex.length) + hex; + + return '#' + hex; +} + +/** + * Converts a color as an [R, G, B] array to a hex number + * + * @memberof PIXI.utils + * @function rgb2hex + * @param {number[]} rgb - rgb array + * @return {number} The color number + */ +function rgb2hex(rgb) { + return (rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + (rgb[2] * 255 | 0); +} + +/** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * + * @memberof PIXI.utils + * @function getResolutionOfUrl + * @param {string} url - the image path + * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. + * @return {number} resolution / device pixel ratio of an asset + */ +function getResolutionOfUrl(url, defaultValue) { + var resolution = _settings2.default.RETINA_PREFIX.exec(url); + + if (resolution) { + return parseFloat(resolution[1]); + } + + return defaultValue !== undefined ? defaultValue : 1; +} + +/** + * Typedef for decomposeDataUri return object. + * + * @typedef {object} DecomposedDataUri + * @property {mediaType} Media type, eg. `image` + * @property {subType} Sub type, eg. `png` + * @property {encoding} Data encoding, eg. `base64` + * @property {data} The actual data + */ + +/** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. + * + * @memberof PIXI.utils + * @function decomposeDataUri + * @param {string} dataUri - the data URI to check + * @return {DecomposedDataUri|undefined} The decomposed data uri or undefined + */ +function decomposeDataUri(dataUri) { + var dataUriMatch = _const.DATA_URI.exec(dataUri); + + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + encoding: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + data: dataUriMatch[4] + }; + } + + return undefined; +} + +/** + * Get type of the image by regexp for extension. Returns undefined for unknown extensions. + * + * @memberof PIXI.utils + * @function getUrlFileExtension + * @param {string} url - the image path + * @return {string|undefined} image extension + */ +function getUrlFileExtension(url) { + var extension = _const.URL_FILE_EXTENSION.exec(url); + + if (extension) { + return extension[1].toLowerCase(); + } + + return undefined; +} + +/** + * Typedef for Size object. + * + * @typedef {object} Size + * @property {width} Width component + * @property {height} Height component + */ + +/** + * Get size from an svg string using regexp. + * + * @memberof PIXI.utils + * @function getSvgSize + * @param {string} svgString - a serialized svg element + * @return {Size|undefined} image extension + */ +function getSvgSize(svgString) { + var sizeMatch = _const.SVG_SIZE.exec(svgString); + var size = {}; + + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); + size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); + } + + return size; +} + +/** + * Skips the hello message of renderers that are created after this is run. + * + * @function skipHello + * @memberof PIXI.utils + */ +function skipHello() { + saidHello = true; +} + +/** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever makes you a jerk face. + * + * @static + * @function sayHello + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ +function sayHello(type) { + if (saidHello) { + return; + } + + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = ['\n %c %c %c Pixi.js ' + _const.VERSION + ' - \u2730 ' + type + ' \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n', 'background: #ff66a5; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff66a5; background: #030307; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'background: #ffc3dc; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;']; + + window.console.log.apply(console, args); + } else if (window.console) { + window.console.log('Pixi.js ' + _const.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); + } + + saidHello = true; +} + +/** + * Helper for checking for webgl support + * + * @memberof PIXI.utils + * @function isWebGLSupported + * @return {boolean} is webgl supported + */ +function isWebGLSupported() { + var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; + + try { + if (!window.WebGLRenderingContext) { + return false; + } + + var canvas = document.createElement('canvas'); + var gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); + + var success = !!(gl && gl.getContextAttributes().stencil); + + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + + if (loseContext) { + loseContext.loseContext(); + } + } + + gl = null; + + return success; + } catch (e) { + return false; + } +} + +/** + * Returns sign of number + * + * @memberof PIXI.utils + * @function sign + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ +function sign(n) { + if (n === 0) return 0; + + return n < 0 ? -1 : 1; +} + +/** + * Remove a range of items from an array + * + * @memberof PIXI.utils + * @function removeItems + * @param {Array<*>} arr The target array + * @param {number} startIdx The index to begin removing from (inclusive) + * @param {number} removeCount How many items to remove + */ +function removeItems(arr, startIdx, removeCount) { + var length = arr.length; + + if (startIdx >= length || removeCount === 0) { + return; + } + + removeCount = startIdx + removeCount > length ? length - startIdx : removeCount; + + var len = length - removeCount; + + for (var i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount]; + } + + arr.length = len; +} + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var TextureCache = exports.TextureCache = {}; + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var BaseTextureCache = exports.BaseTextureCache = {}; + +},{"../const":44,"../settings":99,"./mixin":122,"./pluginTarget":123,"eventemitter3":3,"ismobilejs":4}],121:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = maxRecommendedTextures; + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function maxRecommendedTextures(max) { + if (_ismobilejs2.default.tablet || _ismobilejs2.default.phone) { + // check if the res is iphone 6 or higher.. + return 4; + } + + // desktop should be ok + return max; +} + +},{"ismobilejs":4}],122:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.mixin = mixin; +exports.delayMixin = delayMixin; +exports.performMixins = performMixins; +/** + * Mixes all enumerable properties and methods from a source object to a target object. + * + * @memberof PIXI.utils.mixins + * @function mixin + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function mixin(target, source) { + if (!target || !source) return; + // in ES8/ES2017, this would be really easy: + // Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + + // get all the enumerable property keys + var keys = Object.keys(source); + + // loop through properties + for (var i = 0; i < keys.length; ++i) { + var propertyName = keys[i]; + + // Set the property using the property descriptor - this works for accessors and normal value properties + Object.defineProperty(target, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); + } +} + +var mixins = []; + +/** + * Queues a mixin to be handled towards the end of the initialization of PIXI, so that deprecation + * can take effect. + * + * @memberof PIXI.utils.mixins + * @function delayMixin + * @private + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function delayMixin(target, source) { + mixins.push(target, source); +} + +/** + * Handles all mixins queued via delayMixin(). + * + * @memberof PIXI.utils.mixins + * @function performMixins + * @private + */ +function performMixins() { + for (var i = 0; i < mixins.length; i += 2) { + mixin(mixins[i], mixins[i + 1]); + } + mixins.length = 0; +} + +},{}],123:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Mixins functionality to make an object have "plugins". + * + * @example + * function MyObject() {} + * + * pluginTarget.mixin(MyObject); + * + * @mixin + * @memberof PIXI.utils + * @param {object} obj - The object to mix into. + */ +function pluginTarget(obj) { + obj.__plugins = {}; + + /** + * Adds a plugin to an object + * + * @param {string} pluginName - The events that should be listed. + * @param {Function} ctor - The constructor function for the plugin. + */ + obj.registerPlugin = function registerPlugin(pluginName, ctor) { + obj.__plugins[pluginName] = ctor; + }; + + /** + * Instantiates all the plugins of this object + * + */ + obj.prototype.initPlugins = function initPlugins() { + this.plugins = this.plugins || {}; + + for (var o in obj.__plugins) { + this.plugins[o] = new obj.__plugins[o](this); + } + }; + + /** + * Removes all the plugins of this object + * + */ + obj.prototype.destroyPlugins = function destroyPlugins() { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + + this.plugins = null; + }; +} + +exports.default = { + /** + * Mixes in the properties of the pluginTarget into another object + * + * @param {object} obj - The obj to mix into + */ + mixin: function mixin(obj) { + pluginTarget(obj); + } +}; + +},{}],124:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = trimCanvas; +/** + * Trim transparent borders from a canvas + * + * @memberof PIXI + * @function trimCanvas + * @private + * @param {HTMLCanvasElement} canvas - the canvas to trim + * @returns {object} Trim data + */ +function trimCanvas(canvas) { + // https://gist.github.com/remy/784508 + + var width = canvas.width; + var height = canvas.height; + + var context = canvas.getContext('2d'); + var imageData = context.getImageData(0, 0, width, height); + var pixels = imageData.data; + var len = pixels.length; + + var bound = { + top: null, + left: null, + right: null, + bottom: null + }; + var i = void 0; + var x = void 0; + var y = void 0; + + for (i = 0; i < len; i += 4) { + if (pixels[i + 3] !== 0) { + x = i / 4 % width; + y = ~~(i / 4 / width); + + if (bound.top === null) { + bound.top = y; + } + + if (bound.left === null) { + bound.left = x; + } else if (x < bound.left) { + bound.left = x; + } + + if (bound.right === null) { + bound.right = x + 1; + } else if (bound.right < x) { + bound.right = x + 1; + } + + if (bound.bottom === null) { + bound.bottom = y; + } else if (bound.bottom < y) { + bound.bottom = y; + } + } + } + + width = bound.right - bound.left; + height = bound.bottom - bound.top + 1; + + var data = context.getImageData(bound.left, bound.top, width, height); + + return { + height: height, + width: width, + data: data + }; +} + +},{}],125:[function(require,module,exports){ +'use strict'; + +var _core = require('./core'); + +var core = _interopRequireWildcard(_core); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code +function warn(msg) { + /* eslint-disable no-console */ + var stack = new Error().stack; + + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('Deprecation Warning: ', msg); + } else { + // chop off the stack trace which includes pixi.js internal calls + stack = stack.split('\n').splice(3).join('\n'); + + if (console.groupCollapsed) { + console.groupCollapsed('%cDeprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', msg); + console.warn(stack); + console.groupEnd(); + } else { + console.warn('Deprecation Warning: ', msg); + console.warn(stack); + } + } + /* eslint-enable no-console */ +} + +/** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ +core.SpriteBatch = function () { + throw new ReferenceError('SpriteBatch does not exist any more, please use the new ParticleContainer instead.'); +}; + +/** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ +core.AssetLoader = function () { + throw new ReferenceError('The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class.'); +}; + +Object.defineProperties(core, { + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + Stage: { + enumerable: true, + get: function get() { + warn('You do not need to use a PIXI Stage any more, you can simply render any container.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + DisplayObjectContainer: { + enumerable: true, + get: function get() { + warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + Strip: { + enumerable: true, + get: function get() { + warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.'); + + return mesh.Mesh; + } + }, + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + Rope: { + enumerable: true, + get: function get() { + warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.'); + + return mesh.Rope; + } + }, + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + ParticleContainer: { + enumerable: true, + get: function get() { + warn('The ParticleContainer class has been moved to particles.ParticleContainer, ' + 'please use particles.ParticleContainer from now on.'); + + return particles.ParticleContainer; + } + }, + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + MovieClip: { + enumerable: true, + get: function get() { + warn('The MovieClip class has been moved to extras.AnimatedSprite, please use extras.AnimatedSprite.'); + + return extras.AnimatedSprite; + } + }, + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + TilingSprite: { + enumerable: true, + get: function get() { + warn('The TilingSprite class has been moved to extras.TilingSprite, ' + 'please use extras.TilingSprite from now on.'); + + return extras.TilingSprite; + } + }, + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + BitmapText: { + enumerable: true, + get: function get() { + warn('The BitmapText class has been moved to extras.BitmapText, ' + 'please use extras.BitmapText from now on.'); + + return extras.BitmapText; + } + }, + + /** + * @class + * @private + * @name blendModes + * @memberof PIXI + * @see PIXI.BLEND_MODES + * @deprecated since version 3.0.0 + */ + blendModes: { + enumerable: true, + get: function get() { + warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.'); + + return core.BLEND_MODES; + } + }, + + /** + * @class + * @private + * @name scaleModes + * @memberof PIXI + * @see PIXI.SCALE_MODES + * @deprecated since version 3.0.0 + */ + scaleModes: { + enumerable: true, + get: function get() { + warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.'); + + return core.SCALE_MODES; + } + }, + + /** + * @class + * @private + * @name BaseTextureCache + * @memberof PIXI + * @see PIXI.utils.BaseTextureCache + * @deprecated since version 3.0.0 + */ + BaseTextureCache: { + enumerable: true, + get: function get() { + warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, ' + 'please use utils.BaseTextureCache from now on.'); + + return core.utils.BaseTextureCache; + } + }, + + /** + * @class + * @private + * @name TextureCache + * @memberof PIXI + * @see PIXI.utils.TextureCache + * @deprecated since version 3.0.0 + */ + TextureCache: { + enumerable: true, + get: function get() { + warn('The TextureCache class has been moved to utils.TextureCache, ' + 'please use utils.TextureCache from now on.'); + + return core.utils.TextureCache; + } + }, + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + math: { + enumerable: true, + get: function get() { + warn('The math namespace is deprecated, please access members already accessible on PIXI.'); + + return core; + } + }, + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + enumerable: true, + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.Filter; + } + }, + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + TransformManual: { + enumerable: true, + get: function get() { + warn('TransformManual has been renamed to TransformBase, please update your pixi-spine'); + + return core.TransformBase; + } + }, + + /** + * @static + * @constant + * @name PIXI.TARGET_FPMS + * @see PIXI.settings.TARGET_FPMS + * @deprecated since version 4.2.0 + */ + TARGET_FPMS: { + enumerable: true, + get: function get() { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + return core.settings.TARGET_FPMS; + }, + set: function set(value) { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + core.settings.TARGET_FPMS = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.FILTER_RESOLUTION + * @see PIXI.settings.FILTER_RESOLUTION + * @deprecated since version 4.2.0 + */ + FILTER_RESOLUTION: { + enumerable: true, + get: function get() { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + return core.settings.FILTER_RESOLUTION; + }, + set: function set(value) { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + core.settings.FILTER_RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RESOLUTION + * @see PIXI.settings.RESOLUTION + * @deprecated since version 4.2.0 + */ + RESOLUTION: { + enumerable: true, + get: function get() { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + return core.settings.RESOLUTION; + }, + set: function set(value) { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + core.settings.RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.MIPMAP_TEXTURES + * @see PIXI.settings.MIPMAP_TEXTURES + * @deprecated since version 4.2.0 + */ + MIPMAP_TEXTURES: { + enumerable: true, + get: function get() { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + return core.settings.MIPMAP_TEXTURES; + }, + set: function set(value) { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + core.settings.MIPMAP_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_BATCH_SIZE + * @see PIXI.settings.SPRITE_BATCH_SIZE + * @deprecated since version 4.2.0 + */ + SPRITE_BATCH_SIZE: { + enumerable: true, + get: function get() { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + return core.settings.SPRITE_BATCH_SIZE; + }, + set: function set(value) { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + core.settings.SPRITE_BATCH_SIZE = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_MAX_TEXTURES + * @see PIXI.settings.SPRITE_MAX_TEXTURES + * @deprecated since version 4.2.0 + */ + SPRITE_MAX_TEXTURES: { + enumerable: true, + get: function get() { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + return core.settings.SPRITE_MAX_TEXTURES; + }, + set: function set(value) { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + core.settings.SPRITE_MAX_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RETINA_PREFIX + * @see PIXI.settings.RETINA_PREFIX + * @deprecated since version 4.2.0 + */ + RETINA_PREFIX: { + enumerable: true, + get: function get() { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + return core.settings.RETINA_PREFIX; + }, + set: function set(value) { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + core.settings.RETINA_PREFIX = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.DEFAULT_RENDER_OPTIONS + * @see PIXI.settings.RENDER_OPTIONS + * @deprecated since version 4.2.0 + */ + DEFAULT_RENDER_OPTIONS: { + enumerable: true, + get: function get() { + warn('PIXI.DEFAULT_RENDER_OPTIONS has been deprecated, please use PIXI.settings.DEFAULT_RENDER_OPTIONS'); + + return core.settings.RENDER_OPTIONS; + } + } +}); + +// Move the default properties to settings +var defaults = [{ parent: 'TRANSFORM_MODE', target: 'TRANSFORM_MODE' }, { parent: 'GC_MODES', target: 'GC_MODE' }, { parent: 'WRAP_MODES', target: 'WRAP_MODE' }, { parent: 'SCALE_MODES', target: 'SCALE_MODE' }, { parent: 'PRECISION', target: 'PRECISION' }]; + +var _loop = function _loop(i) { + var deprecation = defaults[i]; + + Object.defineProperty(core[deprecation.parent], 'DEFAULT', { + enumerable: true, + get: function get() { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, please use PIXI.settings.' + deprecation.target); + + return core.settings[deprecation.target]; + }, + set: function set(value) { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, please use PIXI.settings.' + deprecation.target); + + core.settings[deprecation.target] = value; + } + }); +}; + +for (var i = 0; i < defaults.length; i++) { + _loop(i); +} + +Object.defineProperties(extras, { + + /** + * @class + * @name MovieClip + * @memberof PIXI.extras + * @see PIXI.extras.AnimatedSprite + * @deprecated since version 4.2.0 + */ + MovieClip: { + enumerable: true, + get: function get() { + warn('The MovieClip class has been renamed to AnimatedSprite, please use AnimatedSprite from now on.'); + + return extras.AnimatedSprite; + } + } +}); + +core.DisplayObject.prototype.generateTexture = function generateTexture(renderer, scaleMode, resolution) { + warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); + + return renderer.generateTexture(this, scaleMode, resolution); +}; + +core.Graphics.prototype.generateTexture = function generateTexture(scaleMode, resolution) { + warn('graphics generate texture has moved to the renderer. ' + 'Or to render a graphics to a texture using canvas please use generateCanvasTexture'); + + return this.generateCanvasTexture(scaleMode, resolution); +}; + +core.RenderTexture.prototype.render = function render(displayObject, matrix, clear, updateTransform) { + this.legacyRenderer.render(displayObject, this, clear, matrix, !updateTransform); + warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)'); +}; + +core.RenderTexture.prototype.getImage = function getImage(target) { + warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); + + return this.legacyRenderer.extract.image(target); +}; + +core.RenderTexture.prototype.getBase64 = function getBase64(target) { + warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); + + return this.legacyRenderer.extract.base64(target); +}; + +core.RenderTexture.prototype.getCanvas = function getCanvas(target) { + warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); + + return this.legacyRenderer.extract.canvas(target); +}; + +core.RenderTexture.prototype.getPixels = function getPixels(target) { + warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); + + return this.legacyRenderer.pixels(target); +}; + +/** + * @method + * @private + * @name PIXI.Sprite#setTexture + * @see PIXI.Sprite#texture + * @deprecated since version 3.0.0 + * @param {PIXI.Texture} texture - The texture to set to. + */ +core.Sprite.prototype.setTexture = function setTexture(texture) { + this.texture = texture; + warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;'); +}; + +/** + * @method + * @name PIXI.extras.BitmapText#setText + * @see PIXI.extras.BitmapText#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ +extras.BitmapText.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';'); +}; + +/** + * @method + * @name PIXI.Text#setText + * @see PIXI.Text#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ +core.Text.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';'); +}; + +/** + * @method + * @name PIXI.Text#setStyle + * @see PIXI.Text#style + * @deprecated since version 3.0.0 + * @param {*} style - The style to set to. + */ +core.Text.prototype.setStyle = function setStyle(style) { + this.style = style; + warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;'); +}; + +/** + * @method + * @name PIXI.Text#determineFontProperties + * @see PIXI.Text#calculateFontProperties + * @deprecated since version 4.2.0 + * @private + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ +core.Text.prototype.determineFontProperties = function determineFontProperties(fontStyle) { + warn('determineFontProperties is now deprecated, please use the static calculateFontProperties method, ' + 'e.g : Text.calculateFontProperties(fontStyle);'); + + return core.Text.calculateFontProperties(fontStyle); +}; + +Object.defineProperties(core.TextStyle.prototype, { + /** + * Set all properties of a font as a single string + * + * @name PIXI.TextStyle#font + * @deprecated since version 4.0.0 + */ + font: { + get: function get() { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\', \'fontSize\', \'fontStyle\', \'fontVariant\' and \'fontWeight\' properties from now on'); + + var fontSizeString = typeof this._fontSize === 'number' ? this._fontSize + 'px' : this._fontSize; + + return this._fontStyle + ' ' + this._fontVariant + ' ' + this._fontWeight + ' ' + fontSizeString + ' ' + this._fontFamily; + }, + set: function set(font) { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + + // can work out fontStyle from search of whole string + if (font.indexOf('italic') > 1) { + this._fontStyle = 'italic'; + } else if (font.indexOf('oblique') > -1) { + this._fontStyle = 'oblique'; + } else { + this._fontStyle = 'normal'; + } + + // can work out fontVariant from search of whole string + if (font.indexOf('small-caps') > -1) { + this._fontVariant = 'small-caps'; + } else { + this._fontVariant = 'normal'; + } + + // fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units + var splits = font.split(' '); + var fontSizeIndex = -1; + + this._fontSize = 26; + for (var i = 0; i < splits.length; ++i) { + if (splits[i].match(/(px|pt|em|%)/)) { + fontSizeIndex = i; + this._fontSize = splits[i]; + break; + } + } + + // we can now search for fontWeight as we know it must occur before the fontSize + this._fontWeight = 'normal'; + for (var _i = 0; _i < fontSizeIndex; ++_i) { + if (splits[_i].match(/(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/)) { + this._fontWeight = splits[_i]; + break; + } + } + + // and finally join everything together after the fontSize in case the font family has multiple words + if (fontSizeIndex > -1 && fontSizeIndex < splits.length - 1) { + this._fontFamily = ''; + for (var _i2 = fontSizeIndex + 1; _i2 < splits.length; ++_i2) { + this._fontFamily += splits[_i2] + ' '; + } + + this._fontFamily = this._fontFamily.slice(0, -1); + } else { + this._fontFamily = 'Arial'; + } + + this.styleID++; + } + } +}); + +/** + * @method + * @name PIXI.Texture#setFrame + * @see PIXI.Texture#setFrame + * @deprecated since version 3.0.0 + * @param {PIXI.Rectangle} frame - The frame to set. + */ +core.Texture.prototype.setFrame = function setFrame(frame) { + this.frame = frame; + warn('setFrame is now deprecated, please use the frame property, e.g: myTexture.frame = frame;'); +}; + +Object.defineProperties(filters, { + + /** + * @class + * @private + * @name PIXI.filters.AbstractFilter + * @see PIXI.AbstractFilter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.AbstractFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.SpriteMaskFilter + * @see PIXI.SpriteMaskFilter + * @deprecated since version 3.0.6 + */ + SpriteMaskFilter: { + get: function get() { + warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.'); + + return core.SpriteMaskFilter; + } + } +}); + +/** + * @method + * @name PIXI.utils.uuid + * @see PIXI.utils.uid + * @deprecated since version 3.0.6 + * @return {number} The uid + */ +core.utils.uuid = function () { + warn('utils.uuid() is deprecated, please use utils.uid() from now on.'); + + return core.utils.uid(); +}; + +/** + * @method + * @name PIXI.utils.canUseNewCanvasBlendModes + * @see PIXI.CanvasTinter + * @deprecated + * @return {boolean} Can use blend modes. + */ +core.utils.canUseNewCanvasBlendModes = function () { + warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on'); + + return core.CanvasTinter.canUseMultiply; +}; + +var saidHello = true; + +/** + * @name PIXI.utils._saidHello + * @type {boolean} + * @see PIXI.utils.skipHello + * @deprecated since 4.1.0 + */ +Object.defineProperty(core.utils, '_saidHello', { + set: function set(bool) { + if (bool) { + warn('PIXI.utils._saidHello is deprecated, please use PIXI.utils.skipHello()'); + this.skipHello(); + } + saidHello = bool; + }, + get: function get() { + return saidHello; + } +}); + +/** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.canvas.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ +Object.defineProperty(prepare.canvas, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } +}); + +/** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.webgl.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ +Object.defineProperty(prepare.webgl, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } +}); + +Object.defineProperties(loaders.Resource.prototype, { + isJson: { + get: function get() { + warn('The isJson property is deprecated, please use `resource.type === Resource.TYPE.JSON`.'); + + return this.type === loaders.Loader.Resource.TYPE.JSON; + } + }, + isXml: { + get: function get() { + warn('The isXml property is deprecated, please use `resource.type === Resource.TYPE.XML`.'); + + return this.type === loaders.Loader.Resource.TYPE.XML; + } + }, + isImage: { + get: function get() { + warn('The isImage property is deprecated, please use `resource.type === Resource.TYPE.IMAGE`.'); + + return this.type === loaders.Loader.Resource.TYPE.IMAGE; + } + }, + isAudio: { + get: function get() { + warn('The isAudio property is deprecated, please use `resource.type === Resource.TYPE.AUDIO`.'); + + return this.type === loaders.Loader.Resource.TYPE.AUDIO; + } + }, + isVideo: { + get: function get() { + warn('The isVideo property is deprecated, please use `resource.type === Resource.TYPE.VIDEO`.'); + + return this.type === loaders.Loader.Resource.TYPE.VIDEO; + } + } +}); + +Object.defineProperties(loaders.Loader.prototype, { + before: { + get: function get() { + warn('The before() method is deprecated, please use pre().'); + + return this.pre; + } + }, + after: { + get: function get() { + warn('The after() method is deprecated, please use use().'); + + return this.use; + } + } +}); + +/** + * @name PIXI.interaction.interactiveTarget#defaultCursor + * @static + * @type {number} + * @see PIXI.interaction.interactiveTarget#cursor + * @deprecated since 4.3.0 + */ +Object.defineProperty(interaction.interactiveTarget, 'defaultCursor', { + set: function set(value) { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + this.cursor = value; + }, + get: function get() { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + + return this.cursor; + }, + + enumerable: true +}); + +/** + * @name PIXI.interaction.InteractionManager#defaultCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ +Object.defineProperty(interaction.InteractionManager, 'defaultCursorStyle', { + set: function set(value) { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + this.cursorStyles.default = value; + }, + get: function get() { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + + return this.cursorStyles.default; + } +}); + +/** + * @name PIXI.interaction.InteractionManager#currentCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ +Object.defineProperty(interaction.InteractionManager, 'currentCursorStyle', { + set: function set(value) { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + this.currentCursorMode = value; + }, + get: function get() { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + + return this.currentCursorMode; + } +}); + +},{"./core":63,"./extras":136,"./filters":147,"./interaction":154,"./loaders":157,"./mesh":166,"./particles":169,"./prepare":179}],126:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI + */ + +var CanvasExtract = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasExtract(renderer) { + _classCallCheck(this, CanvasExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.CanvasExtract} extract + * @memberof PIXI.CanvasRenderer# + * @see PIXI.CanvasExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + CanvasExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `CanvasExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + CanvasExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + CanvasExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = this.renderer.width; + frame.height = this.renderer.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + CanvasExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + + return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; + }; + + /** + * Destroys the extract + * + */ + + + CanvasExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return CanvasExtract; +}(); + +exports.default = CanvasExtract; + + +core.CanvasRenderer.registerPlugin('extract', CanvasExtract); + +},{"../../core":63}],127:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLExtract = require('./webgl/WebGLExtract'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLExtract).default; + } +}); + +var _CanvasExtract = require('./canvas/CanvasExtract'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasExtract).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./canvas/CanvasExtract":126,"./webgl/WebGLExtract":128}],128:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); +var BYTES_PER_PIXEL = 4; + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI + */ + +var WebGLExtract = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLExtract(renderer) { + _classCallCheck(this, WebGLExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.WebGLExtract} extract + * @memberof PIXI.WebGLRenderer# + * @see PIXI.WebGLExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + WebGLExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `WebGLExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + WebGLExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + WebGLExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var flipY = false; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + flipY = false; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + flipY = true; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + + // set up an array of pixels + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + + canvasData.data.set(webglPixels); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // pulling pixels + if (flipY) { + canvasBuffer.context.scale(1, -1); + canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); + } + } + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + WebGLExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + } + + return webglPixels; + }; + + /** + * Destroys the extract + * + */ + + + WebGLExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return WebGLExtract; +}(); + +exports.default = WebGLExtract; + + +core.WebGLRenderer.registerPlugin('extract', WebGLExtract); + +},{"../../core":63}],129:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @typedef FrameObject + * @type {object} + * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame + * @property {number} time - the duration of the frame in ms + */ + +/** + * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. + * + * ```js + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; + * + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.fromImage(alienImages[i]); + * textureArray.push(texture); + * }; + * + * let mc = new PIXI.AnimatedSprite(textureArray); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ +var AnimatedSprite = function (_core$Sprite) { + _inherits(AnimatedSprite, _core$Sprite); + + /** + * @param {PIXI.Texture[]|FrameObject[]} textures - an array of {@link PIXI.Texture} or frame + * objects that make up the animation + * @param {boolean} [autoUpdate=true] - Whether use PIXI.ticker.shared to auto update animation time. + */ + function AnimatedSprite(textures, autoUpdate) { + _classCallCheck(this, AnimatedSprite); + + /** + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture)); + + _this._textures = null; + + /** + * @private + */ + _this._durations = null; + + _this.textures = textures; + + /** + * `true` uses PIXI.ticker.shared to auto update animation time. + * @type {boolean} + * @default true + * @private + */ + _this._autoUpdate = autoUpdate !== false; + + /** + * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower + * + * @member {number} + * @default 1 + */ + _this.animationSpeed = 1; + + /** + * Whether or not the animate sprite repeats after playing. + * + * @member {boolean} + * @default true + */ + _this.loop = true; + + /** + * Function to call when a AnimatedSprite finishes playing + * + * @member {Function} + */ + _this.onComplete = null; + + /** + * Function to call when a AnimatedSprite changes which texture is being rendered + * + * @member {Function} + */ + _this.onFrameChange = null; + + /** + * Elapsed time since animation has been started, used internally to display current texture + * + * @member {number} + * @private + */ + _this._currentTime = 0; + + /** + * Indicates if the AnimatedSprite is currently playing + * + * @member {boolean} + * @readonly + */ + _this.playing = false; + return _this; + } + + /** + * Stops the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.stop = function stop() { + if (!this.playing) { + return; + } + + this.playing = false; + if (this._autoUpdate) { + core.ticker.shared.remove(this.update, this); + } + }; + + /** + * Plays the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.play = function play() { + if (this.playing) { + return; + } + + this.playing = true; + if (this._autoUpdate) { + core.ticker.shared.add(this.update, this); + } + }; + + /** + * Stops the AnimatedSprite and goes to a specific frame + * + * @param {number} frameNumber - frame index to stop at + */ + + + AnimatedSprite.prototype.gotoAndStop = function gotoAndStop(frameNumber) { + this.stop(); + + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + + /** + * Goes to a specific frame and begins playing the AnimatedSprite + * + * @param {number} frameNumber - frame index to start at + */ + + + AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay(frameNumber) { + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + + this.play(); + }; + + /** + * Updates the object transform for rendering. + * + * @private + * @param {number} deltaTime - Time since last tick. + */ + + + AnimatedSprite.prototype.update = function update(deltaTime) { + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + + lag += elapsed / 60 * 1000; + + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + + var sign = Math.sign(this.animationSpeed * deltaTime); + + this._currentTime = Math.floor(this._currentTime); + + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + + this._currentTime += lag / this._durations[this.currentFrame]; + } else { + this._currentTime += elapsed; + } + + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + + if (this.onComplete) { + this.onComplete(); + } + } else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + + if (this.onComplete) { + this.onComplete(); + } + } else if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + + /** + * Updates the displayed texture to match the current frame index + * + * @private + */ + + + AnimatedSprite.prototype.updateTexture = function updateTexture() { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + }; + + /** + * Stops the AnimatedSprite and destroys it + * + */ + + + AnimatedSprite.prototype.destroy = function destroy() { + this.stop(); + _core$Sprite.prototype.destroy.call(this); + }; + + /** + * A short hand way of creating a movieclip from an array of frame ids + * + * @static + * @param {string[]} frames - The array of frames ids the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animated sprite with the specified frames. + */ + + + AnimatedSprite.fromFrames = function fromFrames(frames) { + var textures = []; + + for (var i = 0; i < frames.length; ++i) { + textures.push(core.Texture.fromFrame(frames[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * A short hand way of creating a movieclip from an array of image ids + * + * @static + * @param {string[]} images - the array of image urls the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animate sprite with the specified images as frames. + */ + + + AnimatedSprite.fromImages = function fromImages(images) { + var textures = []; + + for (var i = 0; i < images.length; ++i) { + textures.push(core.Texture.fromImage(images[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * totalFrames is the total number of frames in the AnimatedSprite. This is the same as number of textures + * assigned to the AnimatedSprite. + * + * @readonly + * @member {number} + * @default 0 + */ + + + _createClass(AnimatedSprite, [{ + key: 'totalFrames', + get: function get() { + return this._textures.length; + } + + /** + * The array of textures used for this AnimatedSprite + * + * @member {PIXI.Texture[]} + */ + + }, { + key: 'textures', + get: function get() { + return this._textures; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value[0] instanceof core.Texture) { + this._textures = value; + this._durations = null; + } else { + this._textures = []; + this._durations = []; + + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + } + + /** + * The AnimatedSprites current frame index + * + * @member {number} + * @readonly + */ + + }, { + key: 'currentFrame', + get: function get() { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + + return currentFrame; + } + }]); + + return AnimatedSprite; +}(core.Sprite); + +exports.default = AnimatedSprite; + +},{"../core":63}],130:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ObservablePoint = require('../core/math/ObservablePoint'); + +var _ObservablePoint2 = _interopRequireDefault(_ObservablePoint); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BitmapText object will create a line or multiple lines of text using bitmap font. To + * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using: + * + * A BitmapText can only be created when the font is loaded + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); + * ``` + * + * http://www.angelcode.com/products/bmfont/ for windows or + * http://www.bmglyph.com/ for mac. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.extras + */ +var BitmapText = function (_core$Container) { + _inherits(BitmapText, _core$Container); + + /** + * @param {string} text - The copy that you would like the text to display + * @param {object} style - The style parameters + * @param {string|object} style.font - The font descriptor for the object, can be passed as a string of form + * "24px FontName" or "FontName" or as an object with explicit name/size properties. + * @param {string} [style.font.name] - The bitmap font id + * @param {number} [style.font.size] - The size of the font in pixels, e.g. 24 + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), does not affect + * single line text + * @param {number} [style.tint=0xFFFFFF] - The tint color + */ + function BitmapText(text) { + var style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _classCallCheck(this, BitmapText); + + /** + * Private tracker for the width of the overall text + * + * @member {number} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._textWidth = 0; + + /** + * Private tracker for the height of the overall text + * + * @member {number} + * @private + */ + _this._textHeight = 0; + + /** + * Private tracker for the letter sprite pool. + * + * @member {PIXI.Sprite[]} + * @private + */ + _this._glyphs = []; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._font = { + tint: style.tint !== undefined ? style.tint : 0xFFFFFF, + align: style.align || 'left', + name: null, + size: 0 + }; + + /** + * Private tracker for the current font. + * + * @member {object} + * @private + */ + _this.font = style.font; // run font setter + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = text; + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + */ + _this.maxWidth = 0; + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + */ + _this.maxLineHeight = 0; + + /** + * Text anchor. read-only + * + * @member {PIXI.ObservablePoint} + * @private + */ + _this._anchor = new _ObservablePoint2.default(function () { + _this.dirty = true; + }, _this, 0, 0); + + /** + * The dirty state of this object. + * + * @member {boolean} + */ + _this.dirty = false; + + _this.updateText(); + return _this; + } + + /** + * Renders text and updates it when needed + * + * @private + */ + + + BitmapText.prototype.updateText = function updateText() { + var data = BitmapText.fonts[this._font.name]; + var scale = this._font.size / data.size; + var pos = new core.Point(); + var chars = []; + var lineWidths = []; + + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastSpace = -1; + var lastSpaceWidth = 0; + var maxLineHeight = 0; + + for (var i = 0; i < this.text.length; i++) { + var charCode = this.text.charCodeAt(i); + + if (/(\s)/.test(this.text.charAt(i))) { + lastSpace = i; + lastSpaceWidth = lastLineWidth; + } + + if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) { + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + if (lastSpace !== -1 && this.maxWidth > 0 && pos.x * scale > this.maxWidth) { + core.utils.removeItems(chars, lastSpace, i - lastSpace); + i = lastSpace; + lastSpace = -1; + + lineWidths.push(lastSpaceWidth); + maxLineWidth = Math.max(maxLineWidth, lastSpaceWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + var charData = data.chars[charCode]; + + if (!charData) { + continue; + } + + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + + chars.push({ + texture: charData.texture, + line: line, + charCode: charCode, + position: new core.Point(pos.x + charData.xOffset, pos.y + charData.yOffset) + }); + lastLineWidth = pos.x + (charData.texture.width + charData.xOffset); + pos.x += charData.xAdvance; + maxLineHeight = Math.max(maxLineHeight, charData.yOffset + charData.texture.height); + prevCharCode = charCode; + } + + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + + var lineAlignOffsets = []; + + for (var _i = 0; _i <= line; _i++) { + var alignOffset = 0; + + if (this._font.align === 'right') { + alignOffset = maxLineWidth - lineWidths[_i]; + } else if (this._font.align === 'center') { + alignOffset = (maxLineWidth - lineWidths[_i]) / 2; + } + + lineAlignOffsets.push(alignOffset); + } + + var lenChars = chars.length; + var tint = this.tint; + + for (var _i2 = 0; _i2 < lenChars; _i2++) { + var c = this._glyphs[_i2]; // get the next glyph sprite + + if (c) { + c.texture = chars[_i2].texture; + } else { + c = new core.Sprite(chars[_i2].texture); + this._glyphs.push(c); + } + + c.position.x = (chars[_i2].position.x + lineAlignOffsets[chars[_i2].line]) * scale; + c.position.y = chars[_i2].position.y * scale; + c.scale.x = c.scale.y = scale; + c.tint = tint; + + if (!c.parent) { + this.addChild(c); + } + } + + // remove unnecessary children. + for (var _i3 = lenChars; _i3 < this._glyphs.length; ++_i3) { + this.removeChild(this._glyphs[_i3]); + } + + this._textWidth = maxLineWidth * scale; + this._textHeight = (pos.y + data.lineHeight) * scale; + + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + for (var _i4 = 0; _i4 < lenChars; _i4++) { + this._glyphs[_i4].x -= this._textWidth * this.anchor.x; + this._glyphs[_i4].y -= this._textHeight * this.anchor.y; + } + } + this.maxLineHeight = maxLineHeight * scale; + }; + + /** + * Updates the transform of this object + * + * @private + */ + + + BitmapText.prototype.updateTransform = function updateTransform() { + this.validate(); + this.containerUpdateTransform(); + }; + + /** + * Validates text before calling parent's getLocalBounds + * + * @return {PIXI.Rectangle} The rectangular bounding area + */ + + + BitmapText.prototype.getLocalBounds = function getLocalBounds() { + this.validate(); + + return _core$Container.prototype.getLocalBounds.call(this); + }; + + /** + * Updates text when needed + * + * @private + */ + + + BitmapText.prototype.validate = function validate() { + if (this.dirty) { + this.updateText(); + this.dirty = false; + } + }; + + /** + * The tint of the BitmapText object + * + * @member {number} + */ + + + /** + * Register a bitmap font with data and a texture. + * + * @static + * @param {XMLDocument} xml - The XML document data. + * @param {PIXI.Texture} texture - Texture with all symbols. + * @return {Object} Result font object with font, size, lineHeight and char fields. + */ + BitmapText.registerFont = function registerFont(xml, texture) { + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10); + data.chars = {}; + + // parse letters + var letters = xml.getElementsByTagName('char'); + + for (var i = 0; i < letters.length; i++) { + var letter = letters[i]; + var charCode = parseInt(letter.getAttribute('id'), 10); + + var textureRect = new core.Rectangle(parseInt(letter.getAttribute('x'), 10) + texture.frame.x, parseInt(letter.getAttribute('y'), 10) + texture.frame.y, parseInt(letter.getAttribute('width'), 10), parseInt(letter.getAttribute('height'), 10)); + + data.chars[charCode] = { + xOffset: parseInt(letter.getAttribute('xoffset'), 10), + yOffset: parseInt(letter.getAttribute('yoffset'), 10), + xAdvance: parseInt(letter.getAttribute('xadvance'), 10), + kerning: {}, + texture: new core.Texture(texture.baseTexture, textureRect) + + }; + } + + // parse kernings + var kernings = xml.getElementsByTagName('kerning'); + + for (var _i5 = 0; _i5 < kernings.length; _i5++) { + var kerning = kernings[_i5]; + var first = parseInt(kerning.getAttribute('first'), 10); + var second = parseInt(kerning.getAttribute('second'), 10); + var amount = parseInt(kerning.getAttribute('amount'), 10); + + if (data.chars[second]) { + data.chars[second].kerning[first] = amount; + } + } + + // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 + // but it's very likely to change + BitmapText.fonts[data.font] = data; + + return data; + }; + + _createClass(BitmapText, [{ + key: 'tint', + get: function get() { + return this._font.tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.tint = typeof value === 'number' && value >= 0 ? value : 0xFFFFFF; + + this.dirty = true; + } + + /** + * The alignment of the BitmapText object + * + * @member {string} + * @default 'left' + */ + + }, { + key: 'align', + get: function get() { + return this._font.align; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.align = value || 'left'; + + this.dirty = true; + } + + /** + * The anchor sets the origin point of the text. + * The default is 0,0 this means the text's origin is the top left + * Setting the anchor to 0.5,0.5 means the text's origin is centered + * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner + * + * @member {PIXI.Point | number} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (typeof value === 'number') { + this._anchor.set(value); + } else { + this._anchor.copy(value); + } + } + + /** + * The font descriptor of the BitmapText object + * + * @member {string|object} + */ + + }, { + key: 'font', + get: function get() { + return this._font; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (!value) { + return; + } + + if (typeof value === 'string') { + value = value.split(' '); + + this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); + this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; + } else { + this._font.name = value.name; + this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); + } + + this.dirty = true; + } + + /** + * The text of the BitmapText object + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + value = value.toString() || ' '; + if (this._text === value) { + return; + } + this._text = value; + this.dirty = true; + } + + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textWidth', + get: function get() { + this.validate(); + + return this._textWidth; + } + + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textHeight', + get: function get() { + this.validate(); + + return this._textHeight; + } + }]); + + return BitmapText; +}(core.Container); + +exports.default = BitmapText; + + +BitmapText.fonts = {}; + +},{"../core":63,"../core/math/ObservablePoint":66}],131:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Matrix = require('../core/math/Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var tempMat = new _Matrix2.default(); + +/** + * class controls uv transform and frame clamp for texture + * + * @class + * @memberof PIXI.extras + */ + +var TextureTransform = function () { + /** + * + * @param {PIXI.Texture} texture observed texture + * @param {number} [clampMargin] Changes frame clamping, 0.5 by default. Use -0.5 for extra border. + * @constructor + */ + function TextureTransform(texture, clampMargin) { + _classCallCheck(this, TextureTransform); + + this._texture = texture; + + this.mapCoord = new _Matrix2.default(); + + this.uClampFrame = new Float32Array(4); + + this.uClampOffset = new Float32Array(2); + + this._lastTextureID = -1; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders + * + * @default 0 + * @member {number} + */ + this.clampOffset = 0; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + this.clampMargin = typeof clampMargin === 'undefined' ? 0.5 : clampMargin; + } + + /** + * texture property + * @member {PIXI.Texture} + */ + + + /** + * updates matrices if texture was changed + * @param {boolean} forceUpdate if true, matrices will be updated any case + */ + TextureTransform.prototype.update = function update(forceUpdate) { + var tex = this._texture; + + if (!tex || !tex.valid) { + return; + } + + if (!forceUpdate && this._lastTextureID === tex._updateID) { + return; + } + + this._lastTextureID = tex._updateID; + + var uvs = tex._uvs; + + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + + var orig = tex.orig; + var trim = tex.trim; + + if (trim) { + tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat); + } + + var texBase = tex.baseTexture; + var frame = this.uClampFrame; + var margin = this.clampMargin / texBase.resolution; + var offset = this.clampOffset; + + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.uClampOffset[0] = offset / texBase.realWidth; + this.uClampOffset[1] = offset / texBase.realHeight; + }; + + _createClass(TextureTransform, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._texture = value; + this._lastTextureID = -1; + } + }]); + + return TextureTransform; +}(); + +exports.default = TextureTransform; + +},{"../core/math/Matrix":65}],132:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CanvasTinter = require('../core/sprites/canvas/CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +var _TextureTransform = require('./TextureTransform'); + +var _TextureTransform2 = _interopRequireDefault(_TextureTransform); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); + +/** + * A tiling sprite is a fast way of rendering a tiling image + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ + +var TilingSprite = function (_core$Sprite) { + _inherits(TilingSprite, _core$Sprite); + + /** + * @param {PIXI.Texture} texture - the texture of the tiling sprite + * @param {number} [width=100] - the width of the tiling sprite + * @param {number} [height=100] - the height of the tiling sprite + */ + function TilingSprite(texture) { + var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100; + + _classCallCheck(this, TilingSprite); + + /** + * Tile transform + * + * @member {PIXI.TransformStatic} + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, texture)); + + _this.tileTransform = new core.TransformStatic(); + + // /// private + + /** + * The with of the tiling sprite + * + * @member {number} + * @private + */ + _this._width = width; + + /** + * The height of the tiling sprite + * + * @member {number} + * @private + */ + _this._height = height; + + /** + * Canvas pattern + * + * @type {CanvasPattern} + * @private + */ + _this._canvasPattern = null; + + /** + * transform that is applied to UV to get the texture coords + * + * @member {PIXI.extras.TextureTransform} + */ + _this.uvTransform = texture.transform || new _TextureTransform2.default(texture); + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' method. + * + * @member {string} + * @default 'tilingSprite' + */ + _this.pluginName = 'tilingSprite'; + + /** + * Whether or not anchor affects uvs + * + * @member {boolean} + * @default false + */ + _this.uvRespectAnchor = false; + return _this; + } + /** + * Changes frame clamping in corresponding textureTransform, shortcut + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + + + /** + * @private + */ + TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate() { + if (this.uvTransform) { + this.uvTransform.texture = this._texture; + } + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + TilingSprite.prototype._renderWebGL = function _renderWebGL(renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + + if (!texture || !texture.valid) { + return; + } + + this.tileTransform.updateLocalTransform(); + this.uvTransform.update(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer + */ + + + TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { + var texture = this._texture; + + if (!texture.baseTexture.hasLoaded) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var resolution = renderer.resolution; + var baseTexture = texture.baseTexture; + var baseTextureResolution = texture.baseTexture.resolution; + var modX = this.tilePosition.x / this.tileScale.x % texture._frame.width; + var modY = this.tilePosition.y / this.tileScale.y % texture._frame.height; + + // create a nice shiny pattern! + // TODO this needs to be refreshed if texture changes.. + if (!this._canvasPattern) { + // cut an object from a spritesheet.. + var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height, baseTextureResolution); + + // Tint the tiling sprite + if (this.tint !== 0xFFFFFF) { + if (this.cachedTint !== this.tint) { + this.cachedTint = this.tint; + + this.tintedTexture = _CanvasTinter2.default.getTintedTexture(this, this.tint); + } + tempCanvas.context.drawImage(this.tintedTexture, 0, 0); + } else { + tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x, -texture._frame.y); + } + this._canvasPattern = tempCanvas.context.createPattern(tempCanvas.canvas, 'repeat'); + } + + // set context state.. + context.globalAlpha = this.worldAlpha; + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + renderer.setBlendMode(this.blendMode); + + // fill the pattern! + context.fillStyle = this._canvasPattern; + + // TODO - this should be rolled into the setTransform above.. + context.scale(this.tileScale.x / baseTextureResolution, this.tileScale.y / baseTextureResolution); + + var anchorX = this.anchor.x * -this._width; + var anchorY = this.anchor.y * -this._height; + + if (this.uvRespectAnchor) { + context.translate(modX, modY); + + context.fillRect(-modX + anchorX, -modY + anchorY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } else { + context.translate(modX + anchorX, modY + anchorY); + + context.fillRect(-modX, -modY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } + }; + + /** + * Updates the bounds of the tiling sprite. + * + * @private + */ + + + TilingSprite.prototype._calculateBounds = function _calculateBounds() { + var minX = this._width * -this._anchor._x; + var minY = this._height * -this._anchor._y; + var maxX = this._width * (1 - this._anchor._x); + var maxY = this._height * (1 - this._anchor._y); + + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + TilingSprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._width * -this._anchor._x; + this._bounds.minY = this._height * -this._anchor._y; + this._bounds.maxX = this._width * (1 - this._anchor._x); + this._bounds.maxY = this._height * (1 - this._anchor._x); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new core.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _core$Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Checks if a point is inside this tiling sprite. + * + * @param {PIXI.Point} point - the point to check + * @return {boolean} Whether or not the sprite contains the point. + */ + + + TilingSprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor._x; + + if (tempPoint.x > x1 && tempPoint.x < x1 + width) { + var y1 = -height * this.anchor._y; + + if (tempPoint.y > y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this tiling sprite + * + */ + + + TilingSprite.prototype.destroy = function destroy() { + _core$Sprite.prototype.destroy.call(this); + + this.tileTransform = null; + this.uvTransform = null; + }; + + /** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.Texture} The newly created texture + */ + + + TilingSprite.from = function from(source, width, height) { + return new TilingSprite(core.Texture.from(source), width, height); + }; + + /** + * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId + */ + + + TilingSprite.fromFrame = function fromFrame(frameId, width, height) { + var texture = core.utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this); + } + + return new TilingSprite(texture, width, height); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @param {boolean} [crossorigin] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id + */ + + + TilingSprite.fromImage = function fromImage(imageId, width, height, crossorigin, scaleMode) { + return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode), width, height); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(TilingSprite, [{ + key: 'clampMargin', + get: function get() { + return this.uvTransform.clampMargin; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uvTransform.clampMargin = value; + this.uvTransform.update(true); + } + + /** + * The scaling of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tileScale', + get: function get() { + return this.tileTransform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.scale.copy(value); + } + + /** + * The offset of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tilePosition', + get: function get() { + return this.tileTransform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.position.copy(value); + } + }, { + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + } + + /** + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + } + }]); + + return TilingSprite; +}(core.Sprite); + +exports.default = TilingSprite; + +},{"../core":63,"../core/sprites/canvas/CanvasTinter":102,"./TextureTransform":131}],133:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DisplayObject = core.DisplayObject; +var _tempMatrix = new core.Matrix(); + +DisplayObject.prototype._cacheAsBitmap = false; +DisplayObject.prototype._cacheData = false; + +// figured theres no point adding ALL the extra variables to prototype. +// this model can hold the information needed. This can also be generated on demand as +// most objects are not cached as bitmaps. +/** + * @class + * @ignore + */ + +var CacheData = +/** + * + */ +function CacheData() { + _classCallCheck(this, CacheData); + + this.originalRenderWebGL = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + + this.originalUpdateTransform = null; + this.originalHitTest = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.sprite = null; +}; + +Object.defineProperties(DisplayObject.prototype, { + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to 'false' + * + * IMPORTANT GOTCHA - make sure that all your textures are preloaded BEFORE setting this property to true + * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function get() { + return this._cacheAsBitmap; + }, + set: function set(value) { + if (this._cacheAsBitmap === value) { + return; + } + + this._cacheAsBitmap = value; + + var data = void 0; + + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + + data = this._cacheData; + + data.originalRenderWebGL = this.renderWebGL; + data.originalRenderCanvas = this.renderCanvas; + + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this._calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + + data.originalDestroy = this.destroy; + + data.originalContainsPoint = this.containsPoint; + + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + + this.renderWebGL = this._renderCachedWebGL; + this.renderCanvas = this._renderCachedCanvas; + + this.destroy = this._cacheAsBitmapDestroy; + } else { + data = this._cacheData; + + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + + this.renderWebGL = data.originalRenderWebGL; + this.renderCanvas = data.originalRenderCanvas; + this._calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + + this.destroy = data.originalDestroy; + + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + } + } +}); + +/** + * Renders a cached version of the sprite with WebGL + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedWebGL = function _renderCachedWebGL(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObject(renderer); + + this._cacheData.sprite._transformID = -1; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderWebGL(renderer); +}; + +/** + * Prepares the WebGL renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + + this.alpha = 1; + + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.currentRenderer.flush(); + // this.filters= []; + + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds().clone(); + + // add some padding! + if (this._filters) { + var padding = this._filters[0].padding; + + bounds.pad(padding); + } + + // for now we cache the current renderTarget that the webGL renderer is currently using. + // this could be more elegent.. + var cachedRenderTarget = renderer._activeRenderTarget; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + var stack = renderer.filterManager.filterStack; + + // this renderTexture will be used to store the cached DisplayObject + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + // need to set // + var m = _tempMatrix; + + m.tx = -bounds.x; + m.ty = -bounds.y; + + // reset + this.transform.worldTransform.identity(); + + // set all properties to there original so we can render to a texture + this.renderWebGL = this._cacheData.originalRenderWebGL; + + renderer.render(this, renderTexture, true, m, true); + // now restore the state be setting the new properties + + renderer.bindRenderTarget(cachedRenderTarget); + + renderer.filterManager.filterStack = stack; + + this.renderWebGL = this._renderCachedWebGL; + this.updateTransform = this.displayObjectUpdateTransform; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + + // easy bounds.. + this._calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + + this._cacheData.sprite = cachedSprite; + + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + this.updateTransform(); + + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Renders a cached version of the sprite with canvas + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObjectCanvas(renderer); + + this._cacheData.sprite.worldAlpha = this.worldAlpha; + + this._cacheData.sprite.renderCanvas(renderer); +}; + +// TODO this can be the same as the webGL verison.. will need to do a little tweaking first though.. +/** + * Prepares the Canvas renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(); + + var cacheAlpha = this.alpha; + + this.alpha = 1; + + var cachedRenderTarget = renderer.context; + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + // need to set // + var m = _tempMatrix; + + this.transform.localTransform.copy(m); + m.invert(); + + m.tx -= bounds.x; + m.ty -= bounds.y; + + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + + // renderTexture.render(this, m, true); + renderer.render(this, renderTexture, true, m, false); + + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + + this.renderCanvas = this._renderCachedCanvas; + this._calculateBounds = this._calculateCachedBounds; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite._bounds = this._bounds; + cachedSprite.alpha = cacheAlpha; + + this.updateTransform(); + this.updateTransform = this.displayObjectUpdateTransform; + + this._cacheData.sprite = cachedSprite; + + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Calculates the bounds of the cached sprite + * + * @private + */ +DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._cacheData.sprite._calculateBounds(); +}; + +/** + * Gets the bounds of the cached sprite. + * + * @private + * @return {Rectangle} The local bounds. + */ +DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(); +}; + +/** + * Destroys the cached sprite. + * + * @private + */ +DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; +}; + +/** + * Destroys the cached object. + * + * @private + */ +DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy() { + this.cacheAsBitmap = false; + this.destroy(); +}; + +},{"../core":63}],134:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * The instance name of the object. + * + * @memberof PIXI.DisplayObject# + * @member {string} + */ +core.DisplayObject.prototype.name = null; + +/** + * Returns the display object in the container + * + * @memberof PIXI.Container# + * @param {string} name - instance name + * @return {PIXI.DisplayObject} The child with the specified name. + */ +core.Container.prototype.getChildByName = function getChildByName(name) { + for (var i = 0; i < this.children.length; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + + return null; +}; + +},{"../core":63}],135:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. + * + * @memberof PIXI.DisplayObject# + * @param {Point} point - the point to write the global value to. If null a new point will be returned + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @return {Point} The updated point + */ +core.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition() { + var point = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new core.Point(); + var skipUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (this.parent) { + this.parent.toGlobal(this.position, point, skipUpdate); + } else { + point.x = this.position.x; + point.y = this.position.y; + } + + return point; +}; + +},{"../core":63}],136:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BitmapText = exports.TilingSpriteRenderer = exports.TilingSprite = exports.AnimatedSprite = exports.TextureTransform = undefined; + +var _TextureTransform = require('./TextureTransform'); + +Object.defineProperty(exports, 'TextureTransform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureTransform).default; + } +}); + +var _AnimatedSprite = require('./AnimatedSprite'); + +Object.defineProperty(exports, 'AnimatedSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AnimatedSprite).default; + } +}); + +var _TilingSprite = require('./TilingSprite'); + +Object.defineProperty(exports, 'TilingSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSprite).default; + } +}); + +var _TilingSpriteRenderer = require('./webgl/TilingSpriteRenderer'); + +Object.defineProperty(exports, 'TilingSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSpriteRenderer).default; + } +}); + +var _BitmapText = require('./BitmapText'); + +Object.defineProperty(exports, 'BitmapText', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BitmapText).default; + } +}); + +require('./cacheAsBitmap'); + +require('./getChildByName'); + +require('./getGlobalPosition'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// imported for side effect of extending the prototype only, contains no exports + +},{"./AnimatedSprite":129,"./BitmapText":130,"./TextureTransform":131,"./TilingSprite":132,"./cacheAsBitmap":133,"./getChildByName":134,"./getGlobalPosition":135,"./webgl/TilingSpriteRenderer":137}],137:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _const = require('../../core/const'); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMat = new core.Matrix(); +var tempArray = new Float32Array(4); + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var TilingSpriteRenderer = function (_core$ObjectRenderer) { + _inherits(TilingSpriteRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function TilingSpriteRenderer(renderer) { + _classCallCheck(this, TilingSpriteRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + _this.simpleShader = null; + _this.quad = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + TilingSpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n gl_FragColor = sample * color ;\n}\n'); + this.simpleShader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n gl_FragColor = sample * color;\n}\n'); + + this.renderer.bindVao(null); + this.quad = new core.Quad(gl, this.renderer.state.attribState); + this.quad.initVao(this.shader); + }; + + /** + * + * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered + */ + + + TilingSpriteRenderer.prototype.render = function render(ts) { + var renderer = this.renderer; + var quad = this.quad; + + renderer.bindVao(quad.vao); + + var vertices = quad.vertices; + + vertices[0] = vertices[6] = ts._width * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + + vertices[2] = vertices[4] = ts._width * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + + if (ts.uvRespectAnchor) { + vertices = quad.uvs; + + vertices[0] = vertices[6] = -ts.anchor.x; + vertices[1] = vertices[3] = -ts.anchor.y; + + vertices[2] = vertices[4] = 1.0 - ts.anchor.x; + vertices[5] = vertices[7] = 1.0 - ts.anchor.y; + } + + quad.upload(); + + var tex = ts._texture; + var baseTex = tex.baseTexture; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvTransform; + var isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === _const.WRAP_MODES.CLAMP) { + baseTex.wrapMode = _const.WRAP_MODES.REPEAT; + } + } else { + isSimple = baseTex.wrapMode !== _const.WRAP_MODES.CLAMP; + } + } + + var shader = isSimple ? this.simpleShader : this.shader; + + renderer.bindShader(shader); + + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + + tempMat.invert(); + if (isSimple) { + tempMat.append(uv.mapCoord); + } else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + + shader.uniforms.uTransform = tempMat.toArray(true); + + var color = tempArray; + + core.utils.hex2rgb(ts.tint, color); + color[3] = ts.worldAlpha; + shader.uniforms.uColor = color; + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + + shader.uniforms.uSampler = renderer.bindTexture(tex); + + renderer.setBlendMode(ts.blendMode); + + quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + }; + + return TilingSpriteRenderer; +}(core.ObjectRenderer); + +exports.default = TilingSpriteRenderer; + + +core.WebGLRenderer.registerPlugin('tilingSprite', TilingSpriteRenderer); + +},{"../../core":63,"../../core/const":44,"path":22}],138:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BlurXFilter = require('./BlurXFilter'); + +var _BlurXFilter2 = _interopRequireDefault(_BlurXFilter); + +var _BlurYFilter = require('./BlurYFilter'); + +var _BlurYFilter2 = _interopRequireDefault(_BlurYFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurFilter applies a Gaussian blur to an object. + * The strength of the blur can be set for x- and y-axis separately. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurFilter = function (_core$Filter) { + _inherits(BlurFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this)); + + _this.blurXFilter = new _BlurXFilter2.default(strength, quality, resolution, kernelSize); + _this.blurYFilter = new _BlurYFilter2.default(strength, quality, resolution, kernelSize); + + _this.padding = 0; + _this.resolution = resolution || core.settings.RESOLUTION; + _this.quality = quality || 4; + _this.blur = strength || 8; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + BlurFilter.prototype.apply = function apply(filterManager, input, output) { + var renderTarget = filterManager.getRenderTarget(true); + + this.blurXFilter.apply(filterManager, input, renderTarget, true); + this.blurYFilter.apply(filterManager, renderTarget, output, false); + + filterManager.returnRenderTarget(renderTarget); + }; + + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurFilter, [{ + key: 'blur', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the number of passes for blur. More passes means higher quaility bluring. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'quality', + get: function get() { + return this.blurXFilter.quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.quality = this.blurYFilter.quality = value; + } + + /** + * Sets the strength of the blurX property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurX', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the strength of the blurY property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurY', + get: function get() { + return this.blurYFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + }]); + + return BlurFilter; +}(core.Filter); + +exports.default = BlurFilter; + +},{"../../core":63,"./BlurXFilter":139,"./BlurYFilter":140}],139:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurXFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurXFilter = function (_core$Filter) { + _inherits(BlurXFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurXFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurXFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurXFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.width * (output.size.width / input.size.width); + + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; // / this.passes//Math.pow(1, this.passes); + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 16 + */ + + + _createClass(BlurXFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurXFilter; +}(core.Filter); + +exports.default = BlurXFilter; + +},{"../../core":63,"./generateBlurFragSource":141,"./generateBlurVertSource":142,"./getMaxBlurKernelSize":143}],140:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurYFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurYFilter = function (_core$Filter) { + _inherits(BlurYFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurYFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurYFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurYFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.height * (output.size.height / input.size.height); + + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurYFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurYFilter; +}(core.Filter); + +exports.default = BlurYFilter; + +},{"../../core":63,"./generateBlurFragSource":141,"./generateBlurVertSource":142,"./getMaxBlurKernelSize":143}],141:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateFragBlurSource; +var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] +}; + +var fragTemplate = ['varying vec2 vBlurTexCoords[%size%];', 'uniform sampler2D uSampler;', 'void main(void)', '{', ' gl_FragColor = vec4(0.0);', ' %blur%', '}'].join('\n'); + +function generateFragBlurSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + + var fragSource = fragTemplate; + + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value = void 0; + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + value = i; + + if (i >= halfLength) { + value = kernelSize - i - 1; + } + + blur = blur.replace('%value%', kernel[value]); + + blurLoop += blur; + blurLoop += '\n'; + } + + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize); + + return fragSource; +} + +},{}],142:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateVertBlurSource; +var vertTemplate = ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform float strength;', 'uniform mat3 projectionMatrix;', 'varying vec2 vBlurTexCoords[%size%];', 'void main(void)', '{', 'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);', '%blur%', '}'].join('\n'); + +function generateVertBlurSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + + var vertSource = vertTemplate; + + var blurLoop = ''; + var template = void 0; + // let value; + + if (x) { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } else { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + // value = i; + + // if(i >= halfLength) + // { + // value = kernelSize - i - 1; + // } + + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + '.0'); + + blurLoop += blur; + blurLoop += '\n'; + } + + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize); + + return vertSource; +} + +},{}],143:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = getMaxKernelSize; +function getMaxKernelSize(gl) { + var maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + var kernelSize = 15; + + while (kernelSize > maxVaryings) { + kernelSize -= 2; + } + + return kernelSize; +} + +},{}],144:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var ColorMatrixFilter = function (_core$Filter) { + _inherits(ColorMatrixFilter, _core$Filter); + + /** + * + */ + function ColorMatrixFilter() { + _classCallCheck(this, ColorMatrixFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n vec4 result;\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n // Premultiply alpha again.\n result.rgb *= result.a;\n\n gl_FragColor = result;\n}\n')); + + _this.uniforms.m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + return _this; + } + + /** + * Transforms current matrix and set the new one + * + * @param {number[]} matrix - 5x4 matrix + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix(matrix) { + var multiply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + var newMatrix = matrix; + + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + + // set the new matrix + this.uniforms.m = newMatrix; + }; + + /** + * Multiplies two mat5's + * + * @private + * @param {number[]} out - 5x4 matrix the receiving matrix + * @param {number[]} a - 5x4 matrix the first operand + * @param {number[]} b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix + */ + + + ColorMatrixFilter.prototype._multiply = function _multiply(out, a, b) { + // Red Channel + out[0] = a[0] * b[0] + a[1] * b[5] + a[2] * b[10] + a[3] * b[15]; + out[1] = a[0] * b[1] + a[1] * b[6] + a[2] * b[11] + a[3] * b[16]; + out[2] = a[0] * b[2] + a[1] * b[7] + a[2] * b[12] + a[3] * b[17]; + out[3] = a[0] * b[3] + a[1] * b[8] + a[2] * b[13] + a[3] * b[18]; + out[4] = a[0] * b[4] + a[1] * b[9] + a[2] * b[14] + a[3] * b[19] + a[4]; + + // Green Channel + out[5] = a[5] * b[0] + a[6] * b[5] + a[7] * b[10] + a[8] * b[15]; + out[6] = a[5] * b[1] + a[6] * b[6] + a[7] * b[11] + a[8] * b[16]; + out[7] = a[5] * b[2] + a[6] * b[7] + a[7] * b[12] + a[8] * b[17]; + out[8] = a[5] * b[3] + a[6] * b[8] + a[7] * b[13] + a[8] * b[18]; + out[9] = a[5] * b[4] + a[6] * b[9] + a[7] * b[14] + a[8] * b[19] + a[9]; + + // Blue Channel + out[10] = a[10] * b[0] + a[11] * b[5] + a[12] * b[10] + a[13] * b[15]; + out[11] = a[10] * b[1] + a[11] * b[6] + a[12] * b[11] + a[13] * b[16]; + out[12] = a[10] * b[2] + a[11] * b[7] + a[12] * b[12] + a[13] * b[17]; + out[13] = a[10] * b[3] + a[11] * b[8] + a[12] * b[13] + a[13] * b[18]; + out[14] = a[10] * b[4] + a[11] * b[9] + a[12] * b[14] + a[13] * b[19] + a[14]; + + // Alpha Channel + out[15] = a[15] * b[0] + a[16] * b[5] + a[17] * b[10] + a[18] * b[15]; + out[16] = a[15] * b[1] + a[16] * b[6] + a[17] * b[11] + a[18] * b[16]; + out[17] = a[15] * b[2] + a[16] * b[7] + a[17] * b[12] + a[18] * b[17]; + out[18] = a[15] * b[3] + a[16] * b[8] + a[17] * b[13] + a[18] * b[18]; + out[19] = a[15] * b[4] + a[16] * b[9] + a[17] * b[14] + a[18] * b[19] + a[19]; + + return out; + }; + + /** + * Create a Float32 Array and normalize the offset component to 0-1 + * + * @private + * @param {number[]} matrix - 5x4 matrix + * @return {number[]} 5x4 matrix with all values between 0-1 + */ + + + ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix(matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + + return m; + }; + + /** + * Adjusts brightness + * + * @param {number} b - value of the brigthness (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.brightness = function brightness(b, multiply) { + var matrix = [b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the matrices in grey scales + * + * @param {number} scale - value of the grey (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.greyscale = function greyscale(scale, multiply) { + var matrix = [scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the black and white matrice. + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite(multiply) { + var matrix = [0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the hue property of the color + * + * @param {number} rotation - in degrees + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.hue = function hue(rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + + var a00 = cosR + (1.0 - cosR) * w; + var a01 = w * (1.0 - cosR) - sqrW * sinR; + var a02 = w * (1.0 - cosR) + sqrW * sinR; + + var a10 = w * (1.0 - cosR) + sqrW * sinR; + var a11 = cosR + w * (1.0 - cosR); + var a12 = w * (1.0 - cosR) - sqrW * sinR; + + var a20 = w * (1.0 - cosR) - sqrW * sinR; + var a21 = w * (1.0 - cosR) + sqrW * sinR; + var a22 = cosR + w * (1.0 - cosR); + + var matrix = [a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * + * @param {number} amount - value of the contrast (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.contrast = function contrast(amount, multiply) { + var v = (amount || 0) + 1; + var o = -128 * (v - 1); + + var matrix = [v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * + * @param {number} amount - The saturation amount (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.saturate = function saturate() { + var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var multiply = arguments[1]; + + var x = amount * 2 / 3 + 1; + var y = (x - 1) * -0.5; + + var matrix = [x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Desaturate image (remove color) + * + * Call the saturate function + * + */ + + + ColorMatrixFilter.prototype.desaturate = function desaturate() // eslint-disable-line no-unused-vars + { + this.saturate(-1); + }; + + /** + * Negative image (inverse of classic rgb matrix) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.negative = function negative(multiply) { + var matrix = [0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Sepia image + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.sepia = function sepia(multiply) { + var matrix = [0.393, 0.7689999, 0.18899999, 0, 0, 0.349, 0.6859999, 0.16799999, 0, 0, 0.272, 0.5339999, 0.13099999, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.technicolor = function technicolor(multiply) { + var matrix = [1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Polaroid filter + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.polaroid = function polaroid(multiply) { + var matrix = [1.438, -0.062, -0.062, 0, 0, -0.122, 1.378, -0.122, 0, 0, -0.016, -0.016, 1.483, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Filter who transforms : Red -> Blue and Blue -> Red + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.toBGR = function toBGR(multiply) { + var matrix = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.kodachrome = function kodachrome(multiply) { + var matrix = [1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Brown delicious browni filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.browni = function browni(multiply) { + var matrix = [0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Vintage filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.vintage = function vintage(multiply) { + var matrix = [0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * + * @param {number} desaturation - Tone values. + * @param {number} toned - Tone values. + * @param {string} lightColor - Tone values, example: `0xFFE580` + * @param {string} darkColor - Tone values, example: `0xFFE580` + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.colorTone = function colorTone(desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + + var lR = (lightColor >> 16 & 0xFF) / 255; + var lG = (lightColor >> 8 & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + + var dR = (darkColor >> 16 & 0xFF) / 255; + var dG = (darkColor >> 8 & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + + var matrix = [0.3, 0.59, 0.11, 0, 0, lR, lG, lB, desaturation, 0, dR, dG, dB, toned, 0, lR - dR, lG - dG, lB - dB, 0, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Night effect + * + * @param {number} intensity - The intensity of the night effect. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.night = function night(intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [intensity * -2.0, -intensity, 0, 0, 0, -intensity, 0, intensity, 0, 0, 0, intensity, intensity * 2.0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * + * @param {number} amount - how much the predator feels his future victim + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.predator = function predator(amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * LSD effect + * + * Multiply the current matrix + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.lsd = function lsd(multiply) { + var matrix = [2, -0.4, 0.5, 0, 0, -0.5, 2, -0.4, 0, 0, -0.4, -0.5, 3, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Erase the current matrix by setting the default one + * + */ + + + ColorMatrixFilter.prototype.reset = function reset() { + var matrix = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, false); + }; + + /** + * The matrix of the color matrix filter + * + * @member {number[]} + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + + + _createClass(ColorMatrixFilter, [{ + key: 'matrix', + get: function get() { + return this.uniforms.m; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.m = value; + } + }]); + + return ColorMatrixFilter; +}(core.Filter); + +// Americanized alias + + +exports.default = ColorMatrixFilter; +ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + +},{"../../core":63,"path":22}],145:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. You can + * use this filter to apply all manor of crazy warping effects. Currently the r + * property of the texture is used to offset the x and the g property of the texture + * is used to offset the y. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var DisplacementFilter = function (_core$Filter) { + _inherits(DisplacementFilter, _core$Filter); + + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param {number} scale - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + _classCallCheck(this, DisplacementFilter); + + var maskMatrix = new core.Matrix(); + + sprite.renderable = false; + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n')); + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + + _this.uniforms.mapSampler = sprite.texture; + _this.uniforms.filterMatrix = maskMatrix; + _this.uniforms.scale = { x: 1, y: 1 }; + + if (scale === null || scale === undefined) { + scale = 20; + } + + _this.scale = new core.Point(scale, scale); + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + DisplacementFilter.prototype.apply = function apply(filterManager, input, output) { + var ratio = 1 / output.destinationFrame.width * (output.size.width / input.size.width); + + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x * ratio; + this.uniforms.scale.y = this.scale.y * ratio; + + // draw the filter... + filterManager.applyFilter(this, input, output); + }; + + /** + * The texture used for the displacement map. Must be power of 2 sized texture. + * + * @member {PIXI.Texture} + */ + + + _createClass(DisplacementFilter, [{ + key: 'map', + get: function get() { + return this.uniforms.mapSampler; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.mapSampler = value; + } + }]); + + return DisplacementFilter; +}(core.Filter); + +exports.default = DisplacementFilter; + +},{"../../core":63,"path":22}],146:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * Basic FXAA implementation based on the code on geeks3d.com with the + * modification that the texture2DLod stuff was removed since it's + * unsupported by WebGL. + * + * @see https://github.com/mitsuhiko/webgl-meincraft + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + * + */ +var FXAAFilter = function (_core$Filter) { + _inherits(FXAAFilter, _core$Filter); + + /** + * + */ + function FXAAFilter() { + _classCallCheck(this, FXAAFilter); + + // TODO - needs work + return _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + '\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}', + // fragment shader + 'varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n')); + } + + return FXAAFilter; +}(core.Filter); + +exports.default = FXAAFilter; + +},{"../../core":63,"path":22}],147:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _FXAAFilter = require('./fxaa/FXAAFilter'); + +Object.defineProperty(exports, 'FXAAFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_FXAAFilter).default; + } +}); + +var _NoiseFilter = require('./noise/NoiseFilter'); + +Object.defineProperty(exports, 'NoiseFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NoiseFilter).default; + } +}); + +var _DisplacementFilter = require('./displacement/DisplacementFilter'); + +Object.defineProperty(exports, 'DisplacementFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplacementFilter).default; + } +}); + +var _BlurFilter = require('./blur/BlurFilter'); + +Object.defineProperty(exports, 'BlurFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurFilter).default; + } +}); + +var _BlurXFilter = require('./blur/BlurXFilter'); + +Object.defineProperty(exports, 'BlurXFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurXFilter).default; + } +}); + +var _BlurYFilter = require('./blur/BlurYFilter'); + +Object.defineProperty(exports, 'BlurYFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurYFilter).default; + } +}); + +var _ColorMatrixFilter = require('./colormatrix/ColorMatrixFilter'); + +Object.defineProperty(exports, 'ColorMatrixFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ColorMatrixFilter).default; + } +}); + +var _VoidFilter = require('./void/VoidFilter'); + +Object.defineProperty(exports, 'VoidFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VoidFilter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./blur/BlurFilter":138,"./blur/BlurXFilter":139,"./blur/BlurYFilter":140,"./colormatrix/ColorMatrixFilter":144,"./displacement/DisplacementFilter":145,"./fxaa/FXAAFilter":146,"./noise/NoiseFilter":148,"./void/VoidFilter":149}],148:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Vico @vicocotea + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + */ + +/** + * A Noise effect filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var NoiseFilter = function (_core$Filter) { + _inherits(NoiseFilter, _core$Filter); + + /** + * + */ + function NoiseFilter() { + _classCallCheck(this, NoiseFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float noise;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n float diff = (rand(gl_FragCoord.xy) - 0.5) * noise;\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n gl_FragColor = color;\n}\n')); + + _this.noise = 0.5; + return _this; + } + + /** + * The amount of noise to apply. + * + * @member {number} + * @default 0.5 + */ + + + _createClass(NoiseFilter, [{ + key: 'noise', + get: function get() { + return this.uniforms.noise; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.noise = value; + } + }]); + + return NoiseFilter; +}(core.Filter); + +exports.default = NoiseFilter; + +},{"../../core":63,"path":22}],149:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Does nothing. Very handy. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var VoidFilter = function (_core$Filter) { + _inherits(VoidFilter, _core$Filter); + + /** + * + */ + function VoidFilter() { + _classCallCheck(this, VoidFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n')); + + _this.glShaderKey = 'void'; + return _this; + } + + return VoidFilter; +}(core.Filter); + +exports.default = VoidFilter; + +},{"../../core":63,"path":22}],150:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Holds all information related to an Interaction event + * + * @class + * @memberof PIXI.interaction + */ +var InteractionData = function () { + /** + * + */ + function InteractionData() { + _classCallCheck(this, InteractionData); + + /** + * This point stores the global coords of where the touch/mouse event happened + * + * @member {PIXI.Point} + */ + this.global = new core.Point(); + + /** + * The target DisplayObject that was interacted with + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * When passed to an event handler, this will be the original DOM Event that was captured + * + * @member {Event} + */ + this.originalEvent = null; + + /** + * Unique identifier for this interaction + * + * @member {number} + */ + this.identifier = null; + } + + /** + * This will return the local coordinates of the specified displayObject for this InteractionData + * + * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local + * coords off + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative + * to the DisplayObject + */ + + + InteractionData.prototype.getLocalPosition = function getLocalPosition(displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + + return InteractionData; +}(); + +exports.default = InteractionData; + +},{"../core":63}],151:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Event class that mimics native DOM events. + * + * @class + * @memberof PIXI.interaction + */ +var InteractionEvent = function () { + /** + * + */ + function InteractionEvent() { + _classCallCheck(this, InteractionEvent); + + /** + * Whether this event will continue propagating in the tree + * + * @member {boolean} + */ + this.stopped = false; + + /** + * The object which caused this event to be dispatched. + * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}. + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * The object whose event listener’s callback is currently being invoked. + * + * @member {PIXI.DisplayObject} + */ + this.currentTarget = null; + + /* + * Type of the event + * + * @member {string} + */ + this.type = null; + + /* + * InteractionData related to this event + * + * @member {PIXI.interaction.InteractionData} + */ + this.data = null; + } + + /** + * Prevents event from reaching any objects other than the current object. + * + */ + + + InteractionEvent.prototype.stopPropagation = function stopPropagation() { + this.stopped = true; + }; + + /** + * Resets the event. + * + * @private + */ + + + InteractionEvent.prototype._reset = function _reset() { + this.stopped = false; + this.currentTarget = null; + this.target = null; + }; + + return InteractionEvent; +}(); + +exports.default = InteractionEvent; + +},{}],152:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _InteractionData = require('./InteractionData'); + +var _InteractionData2 = _interopRequireDefault(_InteractionData); + +var _InteractionEvent = require('./InteractionEvent'); + +var _InteractionEvent2 = _interopRequireDefault(_InteractionEvent); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +var _InteractionTrackingData2 = _interopRequireDefault(_InteractionTrackingData); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _interactiveTarget = require('./interactiveTarget'); + +var _interactiveTarget2 = _interopRequireDefault(_interactiveTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// Mix interactiveTarget into core.DisplayObject.prototype, after deprecation has been handled +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _interactiveTarget2.default); + +var MOUSE_POINTER_ID = 'MOUSE'; + +/** + * The interaction manager deals with mouse, touch and pointer events. Any DisplayObject can be interactive + * if its interactive parameter is set to true + * This manager also supports multitouch. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.interaction + * + * @class + * @extends EventEmitter + * @memberof PIXI.interaction + */ + +var InteractionManager = function (_EventEmitter) { + _inherits(InteractionManager, _EventEmitter); + + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + * @param {object} [options] - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Frequency increases the interaction events will be checked. + */ + function InteractionManager(renderer, options) { + _classCallCheck(this, InteractionManager); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + options = options || {}; + + /** + * The renderer this interaction manager works for. + * + * @member {PIXI.SystemRenderer} + */ + _this.renderer = renderer; + + /** + * Should default browser actions automatically be prevented. + * Does not apply to pointer events for backwards compatibility + * preventDefault on pointer events stops mouse events from firing + * Thus, for every pointer event, there will always be either a mouse of touch event alongside it. + * + * @member {boolean} + * @default true + */ + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + + /** + * Frequency in milliseconds that the mousemove, moveover & mouseout interaction events will be checked. + * + * @member {number} + * @default 10 + */ + _this.interactionFrequency = options.interactionFrequency || 10; + + /** + * The mouse data + * + * @member {PIXI.interaction.InteractionData} + */ + _this.mouse = new _InteractionData2.default(); + _this.mouse.identifier = MOUSE_POINTER_ID; + + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + + /** + * Actively tracked InteractionData + * + * @private + * @member {Object.} + */ + _this.activeInteractionData = {}; + _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; + + /** + * Pool of unused InteractionData + * + * @private + * @member {PIXI.interation.InteractionData[]} + */ + _this.interactionDataPool = []; + + /** + * An event data object to handle all the event tracking/dispatching + * + * @member {object} + */ + _this.eventData = new _InteractionEvent2.default(); + + /** + * The DOM element to bind to. + * + * @private + * @member {HTMLElement} + */ + _this.interactionDOMElement = null; + + /** + * This property determines if mousemove and touchmove events are fired only when the cursor + * is over the object. + * Setting to true will make things work more in line with how the DOM verison works. + * Setting to false can make things easier for things like dragging + * It is currently set to false as this is how pixi used to work. This will be set to true in + * future versions of pixi. + * + * @member {boolean} + * @default false + */ + _this.moveWhenInside = false; + + /** + * Have events been attached to the dom element? + * + * @private + * @member {boolean} + */ + _this.eventsAdded = false; + + /** + * Is the mouse hovering over the renderer? + * + * @private + * @member {boolean} + */ + _this.mouseOverRenderer = false; + + /** + * Does the device support touch events + * https://www.w3.org/TR/touch-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsTouchEvents = 'ontouchstart' in window; + + /** + * Does the device support pointer events + * https://www.w3.org/Submission/pointer-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsPointerEvents = !!window.PointerEvent; + + // this will make it so that you don't have to call bind all the time + + /** + * @private + * @member {Function} + */ + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerCancel = _this.onPointerCancel.bind(_this); + _this.processPointerCancel = _this.processPointerCancel.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOver = _this.onPointerOver.bind(_this); + + /** + * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor + * values, objects are handled as dictionaries of CSS values for interactionDOMElement, + * and functions are called instead of changing the CSS. + * Default CSS cursor values are provided for 'default' and 'pointer' modes. + * @member {Object.)>} + */ + _this.cursorStyles = { + default: 'inherit', + pointer: 'pointer' + }; + + /** + * The mode of the cursor that is being used. + * The value of this is a key from the cursorStyles dictionary. + * + * @member {string} + */ + _this.currentCursorMode = null; + + /** + * Internal cached let. + * + * @private + * @member {string} + */ + _this.cursor = null; + + /** + * Internal cached let. + * + * @private + * @member {PIXI.Point} + */ + _this._tempPoint = new core.Point(); + + /** + * The current resolution / device pixel ratio. + * + * @member {number} + * @default 1 + */ + _this.resolution = 1; + + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + + /** + * Fired when a pointer device button (usually a mouse button) is pressed on the display + * object. + * + * @event mousedown + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * + * @event rightdown + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is released over the display + * object. + * + * @event mouseup + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * + * @event rightup + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is pressed and released on + * the display object. + * + * @event click + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * + * @event rightclick + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. + * + * @event mouseupoutside + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. + * + * @event rightupoutside + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * + * @event mousemove + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * + * @event mouseover + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * + * @event mouseout + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * + * @event pointerdown + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is released over the display object. + * + * @event pointerup + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when the operating system cancels a pointer event + * + * @event pointercancel + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * + * @event pointertap + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}. + * + * @event pointerupoutside + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved while over the display object + * + * @event pointermove + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved onto the display object + * + * @event pointerover + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved off the display object + * + * @event pointerout + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is placed on the display object. + * + * @event touchstart + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is removed from the display object. + * + * @event touchend + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when the operating system cancels a touch + * + * @event touchcancel + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * + * @event tap + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. + * + * @event touchendoutside + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is moved along the display object. + * + * @event touchmove + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + return _this; + } + + /** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate + * another DOM element to receive those events. + * + * @param {HTMLCanvasElement} element - the DOM element which will receive mouse and touch events. + * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). + * @private + */ + + + InteractionManager.prototype.setTargetElement = function setTargetElement(element) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.removeEvents(); + + this.interactionDOMElement = element; + + this.resolution = resolution; + + this.addEvents(); + }; + + /** + * Registers all the DOM events + * + * @private + */ + + + InteractionManager.prototype.addEvents = function addEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.add(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; + this.interactionDOMElement.style['-ms-touch-action'] = 'none'; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = 'none'; + } + + /** + * These events are added first, so that if pointer events are normalised, they are fired + * in the same order as non-normalised events. ie. pointer event 1st, mouse / touch 2nd + */ + if (this.supportsPointerEvents) { + window.document.addEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); + // pointerout is fired in addition to pointerup (for touch events) and pointercancel + // we already handle those, so for the purposes of what we do in onPointerOut, we only + // care about the pointerleave event + this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); + window.addEventListener('pointercancel', this.onPointerCancel, true); + window.addEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.addEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); + window.addEventListener('mouseup', this.onPointerUp, true); + + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); + } + } + + this.eventsAdded = true; + }; + + /** + * Removes all the DOM events that were previously registered + * + * @private + */ + + + InteractionManager.prototype.removeEvents = function removeEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.remove(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = ''; + this.interactionDOMElement.style['-ms-touch-action'] = ''; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = ''; + } + + if (this.supportsPointerEvents) { + window.document.removeEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); + window.removeEventListener('pointercancel', this.onPointerCancel, true); + window.removeEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.removeEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true); + window.removeEventListener('mouseup', this.onPointerUp, true); + + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); + } + } + + this.interactionDOMElement = null; + + this.eventsAdded = false; + }; + + /** + * Updates the state of interactive objects. + * Invoked by a throttled ticker update from {@link PIXI.ticker.shared}. + * + * @param {number} deltaTime - time delta since last tick + */ + + + InteractionManager.prototype.update = function update(deltaTime) { + this._deltaTime += deltaTime; + + if (this._deltaTime < this.interactionFrequency) { + return; + } + + this._deltaTime = 0; + + if (!this.interactionDOMElement) { + return; + } + + // if the user move the mouse this check has already been done using the mouse move! + if (this.didMove) { + this.didMove = false; + + return; + } + + this.cursor = null; + + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + for (var k in this.activeInteractionData) { + // eslint-disable-next-line no-prototype-builtins + if (this.activeInteractionData.hasOwnProperty(k)) { + var interactionData = this.activeInteractionData[k]; + + if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, true); + } + } + } + + this.setCursorMode(this.cursor); + + // TODO + }; + + /** + * Sets the current cursor mode, handling any callbacks or CSS style changes. + * + * @param {string} mode - cursor mode, a key from the cursorStyles dictionary + */ + + + InteractionManager.prototype.setCursorMode = function setCursorMode(mode) { + mode = mode || 'default'; + // if the mode didn't actually change, bail early + if (this.currentCursorMode === mode) { + return; + } + this.currentCursorMode = mode; + var style = this.cursorStyles[mode]; + + // only do things if there is a cursor style for it + if (style) { + switch (typeof style === 'undefined' ? 'undefined' : _typeof(style)) { + case 'string': + // string styles are handled as cursor CSS + this.interactionDOMElement.style.cursor = style; + break; + case 'function': + // functions are just called, and passed the cursor mode + style(mode); + break; + case 'object': + // if it is an object, assume that it is a dictionary of CSS styles, + // apply it to the interactionDOMElement + Object.assign(this.interactionDOMElement.style, style); + break; + } + } + }; + + /** + * Dispatches an event on the display object that was interacted with + * + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the display object in question + * @param {string} eventString - the name of the event (e.g, mousedown) + * @param {object} eventData - the event data object + * @private + */ + + + InteractionManager.prototype.dispatchEvent = function dispatchEvent(displayObject, eventString, eventData) { + if (!eventData.stopped) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + + displayObject.emit(eventString, eventData); + + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } + }; + + /** + * Maps x and y coords from a DOM object and maps them correctly to the pixi view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. + * + * @param {PIXI.Point} point - the point that the result will be stored in + * @param {number} x - the x coord of the position to map + * @param {number} y - the y coord of the position to map + */ + + + InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint(point, x, y) { + var rect = void 0; + + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { x: 0, y: 0, width: 0, height: 0 }; + } else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + + var resolutionMultiplier = navigator.isCocoonJS ? this.resolution : 1.0 / this.resolution; + + point.x = (x - rect.left) * (this.interactionDOMElement.width / rect.width) * resolutionMultiplier; + point.y = (y - rect.top) * (this.interactionDOMElement.height / rect.height) * resolutionMultiplier; + }; + + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * + * @private + * @param {InteractionEvent} interactionEvent - event containing the point that + * is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param {Function} [func] - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point + * @param {boolean} [interactive] - Whether the displayObject is interactive + * @return {boolean} returns true if the displayObject hit the point + */ + + + InteractionManager.prototype.processInteractive = function processInteractive(interactionEvent, displayObject, func, hitTest, interactive) { + if (!displayObject || !displayObject.visible) { + return false; + } + + var point = interactionEvent.data.global; + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + interactive = displayObject.interactive || interactive; + + var hit = false; + var interactiveParent = interactive; + + // if the displayobject has a hitArea, then it does not need to hitTest children. + if (displayObject.hitArea) { + interactiveParent = false; + } + // it has a mask! Then lets hit test that before continuing + else if (hitTest && displayObject._mask) { + if (!displayObject._mask.containsPoint(point)) { + hitTest = false; + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow pixi to completely ignore and bypass checking the displayObjects children. + if (displayObject.interactiveChildren && displayObject.children) { + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + + // time to get recursive.. if this function will return if something is hit.. + if (this.processInteractive(interactionEvent, child, func, hitTest, interactiveParent)) { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if (!child.parent) { + continue; + } + + hit = true; + + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + + // { + hitTest = false; + // } + + // we can break now as we have hit an object. + } + } + } + + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit! + if (hitTest && !hit) { + if (displayObject.hitArea) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + hit = displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y); + } else if (displayObject.containsPoint) { + hit = displayObject.containsPoint(point); + } + } + + if (displayObject.interactive) { + if (hit && !interactionEvent.target) { + interactionEvent.target = displayObject; + } + + func(interactionEvent, displayObject, hit); + } + } + + return hit; + }; + + /** + * Is called when the pointer button is pressed down on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down + */ + + + InteractionManager.prototype.onPointerDown = function onPointerDown(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + /** + * No need to prevent default on natural pointer events, as there are no side effects + * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, + * so still need to be prevented. + */ + + // Guaranteed that there will be at least one event in events, and all events must have the same pointer type + + if (this.autoPreventDefault && events[0].isNormalized) { + originalEvent.preventDefault(); + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event.pointerId); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerDown, true); + + this.emit('pointerdown', interactionEvent); + if (event.pointerType === 'touch') { + this.emit('touchstart', interactionEvent); + } else if (event.pointerType === 'mouse') { + var isRightButton = event.button === 2 || event.which === 3; + + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + } + }; + + /** + * Processes the result of the pointer down check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerDown = function processPointerDown(interactionEvent, displayObject, hit) { + var e = interactionEvent.data.originalEvent; + + var id = interactionEvent.data.identifier; + + if (hit) { + if (!displayObject.trackedPointers[id]) { + displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + + if (e.type === 'touchstart' || e.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchstart', interactionEvent); + } else if (e.type === 'mousedown' || e.pointerType === 'mouse') { + var isRightButton = e.button === 2 || e.which === 3; + + if (isRightButton) { + displayObject.trackedPointers[id].rightDown = true; + } else { + displayObject.trackedPointers[id].leftDown = true; + } + + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released + * @param {boolean} cancelled - true if the pointer is cancelled + * @param {Function} func - Function passed to {@link processInteractive} + */ + + + InteractionManager.prototype.onPointerComplete = function onPointerComplete(originalEvent, cancelled, func) { + var events = this.normalizeToPointerData(originalEvent); + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event.pointerId); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, func, true); + + this.emit(cancelled ? 'pointercancel' : 'pointerup', interactionEvent); + + if (event.pointerType === 'mouse') { + var isRightButton = event.button === 2 || event.which === 3; + + this.emit(isRightButton ? 'rightup' : 'mouseup', interactionEvent); + } else if (event.pointerType === 'touch') { + this.emit(cancelled ? 'touchcancel' : 'touchend', interactionEvent); + this.releaseInteractionDataForPointerId(event.pointerId, interactionData); + } + } + }; + + /** + * Is called when the pointer button is cancelled + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerCancel = function onPointerCancel(event) { + this.onPointerComplete(event, true, this.processPointerCancel); + }; + + /** + * Processes the result of the pointer cancel check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + */ + + + InteractionManager.prototype.processPointerCancel = function processPointerCancel(interactionEvent, displayObject) { + var e = interactionEvent.data.originalEvent; + + var id = interactionEvent.data.identifier; + + if (displayObject.trackedPointers[id] !== undefined) { + delete displayObject.trackedPointers[id]; + this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); + + if (e.type === 'touchcancel' || e.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerUp = function onPointerUp(event) { + this.onPointerComplete(event, false, this.processPointerUp); + }; + + /** + * Processes the result of the pointer up check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerUp = function processPointerUp(interactionEvent, displayObject, hit) { + var e = interactionEvent.data.originalEvent; + + var id = interactionEvent.data.identifier; + + var trackingData = displayObject.trackedPointers[id]; + + var isTouch = e.type === 'touchend' || e.pointerType === 'touch'; + + var isMouse = e.type.indexOf('mouse') === 0 || e.pointerType === 'mouse'; + + // Mouse only + if (isMouse) { + var isRightButton = e.button === 2 || e.which === 3; + + var flags = _InteractionTrackingData2.default.FLAGS; + + var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; + + var isDown = trackingData !== undefined && trackingData.flags | test; + + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); + + if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); + } + } else if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); + } + // update the down state of the tracking data + if (trackingData) { + if (isRightButton) { + trackingData.rightDown = hit; + } else { + trackingData.leftDown = hit; + } + } + } + + // Pointers and Touches, and Mouse + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchend', interactionEvent); + + if (trackingData) { + this.dispatchEvent(displayObject, 'pointertap', interactionEvent); + if (isTouch) { + this.dispatchEvent(displayObject, 'tap', interactionEvent); + // touches are no longer over (if they ever were) when we get the touchend + // so we should ensure that we don't keep pretending that they are + trackingData.over = false; + } + } + } else if (trackingData) { + this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); + } + // Only remove the tracking data if there is no over/down state still associated with it + if (trackingData && trackingData.none) { + delete displayObject.trackedPointers[id]; + } + }; + + /** + * Is called when the pointer moves across the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer moving + */ + + + InteractionManager.prototype.onPointerMove = function onPointerMove(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + if (events[0].pointerType === 'mouse') { + this.didMove = true; + + this.cursor = null; + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event.pointerId); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + var interactive = event.pointerType === 'touch' ? this.moveWhenInside : true; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerMove, interactive); + this.emit('pointermove', interactionEvent); + if (event.pointerType === 'touch') this.emit('touchmove', interactionEvent); + if (event.pointerType === 'mouse') this.emit('mousemove', interactionEvent); + } + + if (events[0].pointerType === 'mouse') { + this.setCursorMode(this.cursor); + + // TODO BUG for parents interactive object (border order issue) + } + }; + + /** + * Processes the result of the pointer move check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerMove = function processPointerMove(interactionEvent, displayObject, hit) { + var e = interactionEvent.data.originalEvent; + + var isTouch = e.type === 'touchmove' || e.pointerType === 'touch'; + + var isMouse = e.type === 'mousemove' || e.pointerType === 'mouse'; + + if (isMouse) { + this.processPointerOverOut(interactionEvent, displayObject, hit); + } + + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchmove', interactionEvent); + if (isMouse) this.dispatchEvent(displayObject, 'mousemove', interactionEvent); + } + }; + + /** + * Is called when the pointer is moved out of the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out + */ + + + InteractionManager.prototype.onPointerOut = function onPointerOut(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOut, so events will always be length 1 + var event = events[0]; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = false; + this.setCursorMode(null); + } + + var interactionData = this.getInteractionDataForPointerId(event.pointerId); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, false); + + this.emit('pointerout', interactionEvent); + if (event.pointerType === 'mouse') { + this.emit('mouseout', interactionEvent); + } + }; + + /** + * Processes the result of the pointer over/out check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerOverOut = function processPointerOverOut(interactionEvent, displayObject, hit) { + var e = interactionEvent.data.originalEvent; + + var id = interactionEvent.data.identifier; + + var isMouse = e.type === 'mouseover' || e.type === 'mouseout' || e.pointerType === 'mouse'; + + var trackingData = displayObject.trackedPointers[id]; + + // if we just moused over the display object, then we need to track that state + if (hit && !trackingData) { + trackingData = displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + + if (trackingData === undefined) return; + + if (hit && this.mouseOverRenderer) { + if (!trackingData.over) { + trackingData.over = true; + this.dispatchEvent(displayObject, 'pointerover', interactionEvent); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseover', interactionEvent); + } + } + + // only change the cursor if it has not already been changed (by something deeper in the + // display tree) + if (isMouse && this.cursor === null) { + this.cursor = displayObject.cursor; + } + } else if (trackingData.over) { + trackingData.over = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseout', interactionEvent); + } + // if there is no mouse down information for the pointer, then it is safe to delete + if (trackingData.none) { + delete displayObject.trackedPointers[id]; + } + } + }; + + /** + * Is called when the pointer is moved into the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view + */ + + + InteractionManager.prototype.onPointerOver = function onPointerOver(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOver, so events will always be length 1 + var event = events[0]; + + var interactionData = this.getInteractionDataForPointerId(event.pointerId); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = true; + } + + this.emit('pointerover', interactionEvent); + if (event.pointerType === 'mouse') { + this.emit('mouseover', interactionEvent); + } + }; + + /** + * Get InteractionData for a given pointerId. Store that data as well + * + * @private + * @param {number} pointerId - Identifier from a pointer event + * @return {InteractionData} - Interaction data for the given pointer identifier + */ + + + InteractionManager.prototype.getInteractionDataForPointerId = function getInteractionDataForPointerId(pointerId) { + if (pointerId === MOUSE_POINTER_ID) { + return this.mouse; + } else if (this.activeInteractionData[pointerId]) { + return this.activeInteractionData[pointerId]; + } + + var interactionData = this.interactionDataPool.pop() || new _InteractionData2.default(); + + interactionData.identifier = pointerId; + this.activeInteractionData[pointerId] = interactionData; + + return interactionData; + }; + + /** + * Return unused InteractionData to the pool, for a given pointerId + * + * @private + * @param {number} pointerId - Identifier from a pointer event + */ + + + InteractionManager.prototype.releaseInteractionDataForPointerId = function releaseInteractionDataForPointerId(pointerId) { + var interactionData = this.activeInteractionData[pointerId]; + + if (interactionData) { + delete this.activeInteractionData[pointerId]; + this.interactionDataPool.push(interactionData); + } + }; + + /** + * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData + * + * @private + * @param {InteractionEvent} interactionEvent - The event to be configured + * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent + * @param {InteractionData} interactionData - The InteractionData that will be paired with the InteractionEvent + * @return {InteractionEvent} the interaction event that was passed in + */ + + + InteractionManager.prototype.configureInteractionEventForDOMEvent = function configureInteractionEventForDOMEvent(interactionEvent, pointerEvent, interactionData) { + interactionEvent.data = interactionData; + + this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); + + // This is the way InteractionManager processed touch events before the refactoring, so I've kept + // it here. But it doesn't make that much sense to me, since mapPositionToPoint already factors + // in this.resolution, so this just divides by this.resolution twice for touch events... + if (navigator.isCocoonJS && pointerEvent.pointerType === 'touch') { + interactionData.global.x = interactionData.global.x / this.resolution; + interactionData.global.y = interactionData.global.y / this.resolution; + } + + // Not really sure why this is happening, but it's how a previous version handled things + if (pointerEvent.pointerType === 'touch') { + pointerEvent.globalX = interactionData.global.x; + pointerEvent.globalY = interactionData.global.y; + } + + interactionData.originalEvent = pointerEvent; + interactionEvent._reset(); + + return interactionEvent; + }; + + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * + * @private + * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event + * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer + * or mouse event, or a multiple normalized pointer events if there are multiple changed touches + */ + + + InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData(event) { + var normalizedEvents = []; + + if (this.supportsTouchEvents && event instanceof TouchEvent) { + for (var i = 0, li = event.changedTouches.length; i < li; i++) { + var touch = event.changedTouches[i]; + + if (typeof touch.button === 'undefined') touch.button = event.touches.length ? 1 : 0; + if (typeof touch.buttons === 'undefined') touch.buttons = event.touches.length ? 1 : 0; + if (typeof touch.isPrimary === 'undefined') touch.isPrimary = event.touches.length === 1; + if (typeof touch.width === 'undefined') touch.width = touch.radiusX || 1; + if (typeof touch.height === 'undefined') touch.height = touch.radiusY || 1; + if (typeof touch.tiltX === 'undefined') touch.tiltX = 0; + if (typeof touch.tiltY === 'undefined') touch.tiltY = 0; + if (typeof touch.pointerType === 'undefined') touch.pointerType = 'touch'; + if (typeof touch.pointerId === 'undefined') touch.pointerId = touch.identifier || 0; + if (typeof touch.pressure === 'undefined') touch.pressure = touch.force || 0.5; + if (typeof touch.rotation === 'undefined') touch.rotation = touch.rotationAngle || 0; + + if (typeof touch.layerX === 'undefined') touch.layerX = touch.offsetX = touch.clientX; + if (typeof touch.layerY === 'undefined') touch.layerY = touch.offsetY = touch.clientY; + + // mark the touch as normalized, just so that we know we did it + touch.isNormalized = true; + + normalizedEvents.push(touch); + } + } + // apparently PointerEvent subclasses MouseEvent, so yay + else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent))) { + if (typeof event.isPrimary === 'undefined') event.isPrimary = true; + if (typeof event.width === 'undefined') event.width = 1; + if (typeof event.height === 'undefined') event.height = 1; + if (typeof event.tiltX === 'undefined') event.tiltX = 0; + if (typeof event.tiltY === 'undefined') event.tiltY = 0; + if (typeof event.pointerType === 'undefined') event.pointerType = 'mouse'; + if (typeof event.pointerId === 'undefined') event.pointerId = MOUSE_POINTER_ID; + if (typeof event.pressure === 'undefined') event.pressure = 0.5; + if (typeof event.rotation === 'undefined') event.rotation = 0; + + // mark the mouse event as normalized, just so that we know we did it + event.isNormalized = true; + + normalizedEvents.push(event); + } else { + normalizedEvents.push(event); + } + + return normalizedEvents; + }; + + /** + * Destroys the interaction manager + * + */ + + + InteractionManager.prototype.destroy = function destroy() { + this.removeEvents(); + + this.removeAllListeners(); + + this.renderer = null; + + this.mouse = null; + + this.eventData = null; + + this.interactionDOMElement = null; + + this.onPointerDown = null; + this.processPointerDown = null; + + this.onPointerUp = null; + this.processPointerUp = null; + + this.onPointerCancel = null; + this.processPointerCancel = null; + + this.onPointerMove = null; + this.processPointerMove = null; + + this.onPointerOut = null; + this.processPointerOverOut = null; + + this.onPointerOver = null; + + this._tempPoint = null; + }; + + return InteractionManager; +}(_eventemitter2.default); + +exports.default = InteractionManager; + + +core.WebGLRenderer.registerPlugin('interaction', InteractionManager); +core.CanvasRenderer.registerPlugin('interaction', InteractionManager); + +},{"../core":63,"./InteractionData":150,"./InteractionEvent":151,"./InteractionTrackingData":153,"./interactiveTarget":155,"eventemitter3":3}],153:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * DisplayObjects with the {@link PIXI.interaction.interactiveTarget} mixin use this class to track interactions + * + * @class + * @private + * @memberof PIXI.interaction + */ +var InteractionTrackingData = function () { + /** + * @param {number} pointerId - Unique pointer id of the event + */ + function InteractionTrackingData(pointerId) { + _classCallCheck(this, InteractionTrackingData); + + this._pointerId = pointerId; + this._flags = InteractionTrackingData.FLAGS.NONE; + } + + /** + * + * @private + * @param {number} flag - The interaction flag to set + * @param {boolean} yn - Should the flag be set or unset + */ + + + InteractionTrackingData.prototype._doSet = function _doSet(flag, yn) { + if (yn) { + this._flags = this._flags | flag; + } else { + this._flags = this._flags & ~flag; + } + }; + + /** + * @readonly + * @type {number} Unique pointer id of the event + */ + + + _createClass(InteractionTrackingData, [{ + key: "pointerId", + get: function get() { + return this._pointerId; + } + + /** + * State of the tracking data, expressed as bit flags + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "flags", + get: function get() { + return this._flags; + } + + /** + * Set the flags for the tracking data + * + * @param {number} flags - Flags to set + */ + , + set: function set(flags) { + this._flags = flags; + } + + /** + * Is the tracked event inactive (not over or down)? + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "none", + get: function get() { + return this._flags === this.constructor.FLAGS.NONE; + } + + /** + * Is the tracked event over the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "over", + get: function get() { + return (this._flags & this.constructor.FLAGS.OVER) !== 0; + } + + /** + * Set the over flag + * + * @param {boolean} yn - Is the event over? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.OVER, yn); + } + + /** + * Did the right mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "rightDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.RIGHT_DOWN) !== 0; + } + + /** + * Set the right down flag + * + * @param {boolean} yn - Is the right mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.RIGHT_DOWN, yn); + } + + /** + * Did the left mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "leftDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.LEFT_DOWN) !== 0; + } + + /** + * Set the left down flag + * + * @param {boolean} yn - Is the left mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.LEFT_DOWN, yn); + } + }]); + + return InteractionTrackingData; +}(); + +exports.default = InteractionTrackingData; + + +InteractionTrackingData.FLAGS = Object.freeze({ + NONE: 0, + OVER: 1 << 0, + LEFT_DOWN: 1 << 1, + RIGHT_DOWN: 1 << 2 +}); + +},{}],154:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _InteractionData = require('./InteractionData'); + +Object.defineProperty(exports, 'InteractionData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionData).default; + } +}); + +var _InteractionManager = require('./InteractionManager'); + +Object.defineProperty(exports, 'InteractionManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionManager).default; + } +}); + +var _interactiveTarget = require('./interactiveTarget'); + +Object.defineProperty(exports, 'interactiveTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_interactiveTarget).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./InteractionData":150,"./InteractionManager":152,"./interactiveTarget":155}],155:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * Default property values of interactive objects + * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties + * + * @mixin + * @name interactiveTarget + * @memberof PIXI.interaction + * @example + * function MyObject() {} + * + * Object.assign( + * core.DisplayObject.prototype, + * PIXI.interaction.interactiveTarget + * ); + */ +exports.default = { + /** + * Determines if the displayObject be clicked/touched + * + * @inner {boolean} + */ + interactive: false, + + /** + * Determines if the children to the displayObject can be clicked/touched + * Setting this to false allows pixi to bypass a recursive hitTest function + * + * @inner {boolean} + */ + interactiveChildren: true, + + /** + * Interaction shape. Children will be hit first, then this shape will be checked. + * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. + * + * @inner {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle} + */ + hitArea: null, + + /** + * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive + * Setting this changes the 'cursor' property to `'pointer'`. + * + * @member {boolean} + * @memberof PIXI.interaction.interactiveTarget# + */ + get buttonMode() { + return this.cursor === 'pointer'; + }, + set buttonMode(value) { + if (value) { + this.cursor = 'pointer'; + } else if (this.cursor === 'pointer') { + this.cursor = null; + } + }, + + /** + * This defines what cursor mode is used when the mouse cursor + * is hovered over the displayObject. + * + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * + * @inner {string} + */ + cursor: null, + + /** + * Internal set of all active pointers, by identifier + * + * @member {Map} + * @memberof PIXI.interaction.interactiveTarget# + * @private + */ + get trackedPointers() { + if (this._trackedPointers === undefined) this._trackedPointers = {}; + + return this._trackedPointers; + }, + + /** + * Map of all tracked pointers, by identifier. Use trackedPointers to access. + * + * @private {Map} + */ + _trackedPointers: undefined +}; + +},{}],156:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.parse = parse; + +exports.default = function () { + return function bitmapFontParser(resource, next) { + // skip if no data or not xml data + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.XML) { + next(); + + return; + } + + // skip if not bitmap font data, using some silly duck-typing + if (resource.data.getElementsByTagName('page').length === 0 || resource.data.getElementsByTagName('info').length === 0 || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null) { + next(); + + return; + } + + var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; + + if (resource.isDataUrl) { + if (xmlUrl === '.') { + xmlUrl = ''; + } + + if (this.baseUrl && xmlUrl) { + // if baseurl has a trailing slash then add one to xmlUrl so the replace works below + if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { + xmlUrl += '/'; + } + + // remove baseUrl from xmlUrl + xmlUrl = xmlUrl.replace(this.baseUrl, ''); + } + } + + // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { + xmlUrl += '/'; + } + + var textureUrl = xmlUrl + resource.data.getElementsByTagName('page')[0].getAttribute('file'); + + if (_core.utils.TextureCache[textureUrl]) { + // reuse existing texture + parse(resource, _core.utils.TextureCache[textureUrl]); + next(); + } else { + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + // load the texture for the font + this.add(resource.name + '_image', textureUrl, loadOptions, function (res) { + parse(resource, res.texture); + next(); + }); + } + }; +}; + +var _path = require('path'); + +var path = _interopRequireWildcard(_path); + +var _core = require('../core'); + +var _resourceLoader = require('resource-loader'); + +var _extras = require('../extras'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Register a BitmapText font from loader resource. + * + * @function parseBitmapFontData + * @memberof PIXI.loaders + * @param {PIXI.loaders.Resource} resource - Loader resource. + * @param {PIXI.Texture} texture - Reference to texture. + */ +function parse(resource, texture) { + resource.bitmapFont = _extras.BitmapText.registerFont(resource.data, texture); +} + +},{"../core":63,"../extras":136,"path":22,"resource-loader":34}],157:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _loader = require('./loader'); + +Object.defineProperty(exports, 'Loader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_loader).default; + } +}); + +var _bitmapFontParser = require('./bitmapFontParser'); + +Object.defineProperty(exports, 'bitmapFontParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_bitmapFontParser).default; + } +}); +Object.defineProperty(exports, 'parseBitmapFontData', { + enumerable: true, + get: function get() { + return _bitmapFontParser.parse; + } +}); + +var _spritesheetParser = require('./spritesheetParser'); + +Object.defineProperty(exports, 'spritesheetParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_spritesheetParser).default; + } +}); + +var _textureParser = require('./textureParser'); + +Object.defineProperty(exports, 'textureParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_textureParser).default; + } +}); + +var _resourceLoader = require('resource-loader'); + +Object.defineProperty(exports, 'Resource', { + enumerable: true, + get: function get() { + return _resourceLoader.Resource; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./bitmapFontParser":156,"./loader":158,"./spritesheetParser":159,"./textureParser":160,"resource-loader":34}],158:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _resourceLoader = require('resource-loader'); + +var _resourceLoader2 = _interopRequireDefault(_resourceLoader); + +var _blob = require('resource-loader/lib/middlewares/parsing/blob'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _textureParser = require('./textureParser'); + +var _textureParser2 = _interopRequireDefault(_textureParser); + +var _spritesheetParser = require('./spritesheetParser'); + +var _spritesheetParser2 = _interopRequireDefault(_spritesheetParser); + +var _bitmapFontParser = require('./bitmapFontParser'); + +var _bitmapFontParser2 = _interopRequireDefault(_bitmapFontParser); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * The new loader, extends Resource Loader by Chad Engler : https://github.com/englercj/resource-loader + * + * ```js + * let loader = PIXI.loader; // pixi exposes a premade instance for you to use. + * //or + * let loader = new PIXI.loaders.Loader(); // you can also create your own if you want + * + * loader.add('bunny', 'data/bunny.png'); + * loader.add('spaceship', 'assets/spritesheet.json'); + * loader.add('scoreFont', 'assets/score.fnt'); + * + * loader.once('complete',onAssetsLoaded); + * + * loader.load(); + * ``` + * + * @see https://github.com/englercj/resource-loader + * + * @class + * @extends module:resource-loader.ResourceLoader + * @memberof PIXI.loaders + */ +var Loader = function (_ResourceLoader) { + _inherits(Loader, _ResourceLoader); + + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + _classCallCheck(this, Loader); + + var _this = _possibleConstructorReturn(this, _ResourceLoader.call(this, baseUrl, concurrency)); + + _eventemitter2.default.call(_this); + + for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { + _this.use(Loader._pixiMiddleware[i]()); + } + + // Compat layer, translate the new v2 signals into old v1 events. + _this.onStart.add(function (l) { + return _this.emit('start', l); + }); + _this.onProgress.add(function (l, r) { + return _this.emit('progress', l, r); + }); + _this.onError.add(function (e, l, r) { + return _this.emit('error', e, l, r); + }); + _this.onLoad.add(function (l, r) { + return _this.emit('load', l, r); + }); + _this.onComplete.add(function (l, r) { + return _this.emit('complete', l, r); + }); + return _this; + } + + /** + * Adds a default middleware to the pixi loader. + * + * @static + * @param {Function} fn - The middleware to add. + */ + + + Loader.addPixiMiddleware = function addPixiMiddleware(fn) { + Loader._pixiMiddleware.push(fn); + }; + + return Loader; +}(_resourceLoader2.default); + +// Copy EE3 prototype (mixin) + + +exports.default = Loader; +for (var k in _eventemitter2.default.prototype) { + Loader.prototype[k] = _eventemitter2.default.prototype[k]; +} + +Loader._pixiMiddleware = [ +// parse any blob into more usable objects (e.g. Image) +_blob.blobMiddlewareFactory, +// parse any Image objects into textures +_textureParser2.default, +// parse any spritesheet data into multiple textures +_spritesheetParser2.default, +// parse bitmap font data into multiple textures +_bitmapFontParser2.default]; + +// Add custom extentions +var Resource = _resourceLoader2.default.Resource; + +Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); + +},{"./bitmapFontParser":156,"./spritesheetParser":159,"./textureParser":160,"eventemitter3":3,"resource-loader":34,"resource-loader/lib/middlewares/parsing/blob":35}],159:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function spritesheetParser(resource, next) { + var resourcePath = void 0; + var imageResourceName = resource.name + '_image'; + + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.JSON || !resource.data.frames || this.resources[imageResourceName]) { + next(); + + return; + } + + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + resourcePath = resource.data.meta.image; + } else { + resourcePath = _path2.default.dirname(resource.url.replace(this.baseUrl, '')) + '/' + resource.data.meta.image; + } + + // load the image for this sheet + this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + var spritesheet = new _core.Spritesheet(res.texture.baseTexture, resource.data, resource.url); + + spritesheet.parse(function () { + resource.spritesheet = spritesheet; + resource.textures = spritesheet.textures; + next(); + }); + }); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _path = require('path'); + +var _path2 = _interopRequireDefault(_path); + +var _core = require('../core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"../core":63,"path":22,"resource-loader":34}],160:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function textureParser(resource, next) { + // create a new texture if the data is an Image object + if (resource.data && resource.type === _resourceLoader.Resource.TYPE.IMAGE) { + resource.texture = _Texture2.default.fromLoader(resource.data, resource.url, resource.name); + } + next(); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"../core/textures/Texture":112,"resource-loader":34}],161:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); +var tempPolygon = new core.Polygon(); + +/** + * Base mesh class + * @class + * @extends PIXI.Container + * @memberof PIXI.mesh + */ + +var Mesh = function (_core$Container) { + _inherits(Mesh, _core$Container); + + /** + * @param {PIXI.Texture} texture - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts + */ + function Mesh(texture, vertices, uvs, indices, drawMode) { + _classCallCheck(this, Mesh); + + /** + * The texture of the Mesh + * + * @member {PIXI.Texture} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._texture = null; + + /** + * The Uvs of the Mesh + * + * @member {Float32Array} + */ + _this.uvs = uvs || new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + /** + * An array of vertices + * + * @member {Float32Array} + */ + _this.vertices = vertices || new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]); + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + // TODO auto generate this based on draw mode! + _this.indices = indices || new Uint16Array([0, 1, 3, 2]); + + /** + * Version of mesh uvs are dirty or not + * + * @member {number} + */ + _this.dirty = 0; + + /** + * Version of mesh indices + * + * @member {number} + */ + _this.indexDirty = 0; + + /** + * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove + * any blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles + * to overlap a bit with each other. + * + * @member {number} + */ + _this.canvasPadding = 0; + + /** + * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts + * + * @member {number} + * @see PIXI.mesh.Mesh.DRAW_MODES + */ + _this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH; + + // run texture setter; + _this.texture = texture; + + /** + * The default shader that is used if a mesh doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + _this.shader = null; + + /** + * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any + * tint effect. + * + * @member {number} + */ + _this.tintRgb = new Float32Array([1, 1, 1]); + + /** + * A map of renderer IDs to webgl render data + * + * @private + * @member {object} + */ + _this._glDatas = {}; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * + * @member {string} + * @default 'mesh' + */ + _this.pluginName = 'mesh'; + return _this; + } + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - a reference to the WebGL renderer + */ + + + Mesh.prototype._renderWebGL = function _renderWebGL(renderer) { + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + + + Mesh.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins[this.pluginName].render(this); + }; + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Mesh.prototype._onTextureUpdate = function _onTextureUpdate() {} + /* empty */ + + + /** + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + */ + ; + + Mesh.prototype._calculateBounds = function _calculateBounds() { + // TODO - we can cache local bounds and use them if they are dirty (like graphics) + this._bounds.addVertices(this.transform, this.vertices, 0, this.vertices.length); + }; + + /** + * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Mesh.prototype.containsPoint = function containsPoint(point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + + this.worldTransform.applyInverse(point, tempPoint); + + var vertices = this.vertices; + var points = tempPolygon.points; + var indices = this.indices; + var len = this.indices.length; + var step = this.drawMode === Mesh.DRAW_MODES.TRIANGLES ? 3 : 1; + + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + + return false; + }; + + /** + * The texture that the mesh uses. + * + * @member {PIXI.Texture} + */ + + + _createClass(Mesh, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + + /** + * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return core.utils.rgb2hex(this.tintRgb); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tintRgb = core.utils.hex2rgb(value, this.tintRgb); + } + }]); + + return Mesh; +}(core.Container); + +/** + * Different drawing buffer modes supported + * + * @static + * @constant + * @type {object} + * @property {number} TRIANGLE_MESH + * @property {number} TRIANGLES + */ + + +exports.default = Mesh; +Mesh.DRAW_MODES = { + TRIANGLE_MESH: 0, + TRIANGLES: 1 +}; + +},{"../core":63}],162:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Plane2 = require('./Plane'); + +var _Plane3 = _interopRequireDefault(_Plane2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DEFAULT_BORDER_SIZE = 10; + +/** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.fromImage('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
+ *      A                          B
+ *    +---+----------------------+---+
+ *  C | 1 |          2           | 3 |
+ *    +---+----------------------+---+
+ *    |   |                      |   |
+ *    | 4 |          5           | 6 |
+ *    |   |                      |   |
+ *    +---+----------------------+---+
+ *  D | 7 |          8           | 9 |
+ *    +---+----------------------+---+
+
+ *  When changing this objects width and/or height:
+ *     areas 1 3 7 and 9 will remain unscaled.
+ *     areas 2 and 8 will be stretched horizontally
+ *     areas 4 and 6 will be stretched vertically
+ *     area 5 will be stretched both horizontally and vertically
+ * 
+ * + * @class + * @extends PIXI.mesh.Plane + * @memberof PIXI.mesh + * + */ + +var NineSlicePlane = function (_Plane) { + _inherits(NineSlicePlane, _Plane); + + /** + * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. + * @param {int} [leftWidth=10] size of the left vertical bar (A) + * @param {int} [topHeight=10] size of the top horizontal bar (C) + * @param {int} [rightWidth=10] size of the right vertical bar (B) + * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) + */ + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + _classCallCheck(this, NineSlicePlane); + + var _this = _possibleConstructorReturn(this, _Plane.call(this, texture, 4, 4)); + + var uvs = _this.uvs; + + // right and bottom uv's are always 1 + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + + _this._origWidth = texture.width; + _this._origHeight = texture.height; + _this._uvw = 1 / _this._origWidth; + _this._uvh = 1 / _this._origHeight; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.width = texture.width; + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.height = texture.height; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _this._uvw * leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - _this._uvw * rightWidth; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _this._uvh * topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - _this._uvh * bottomHeight; + + /** + * The width of the left column (a) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; + + /** + * The width of the right column (b) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; + + /** + * The height of the top row (c) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; + + /** + * The height of the bottom row (d) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; + return _this; + } + + /** + * Updates the horizontal vertices. + * + */ + + + NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices() { + var vertices = this.vertices; + + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight; + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + }; + + /** + * Updates the vertical vertices. + * + */ + + + NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices() { + var vertices = this.vertices; + + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth; + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with. + */ + + + NineSlicePlane.prototype._renderCanvas = function _renderCanvas(renderer) { + var context = renderer.context; + + context.globalAlpha = this.worldAlpha; + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + var base = this._texture.baseTexture; + var textureSource = base.source; + var w = base.width; + var h = base.height; + + this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11); + this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13); + this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15); + this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19); + this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21); + this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23); + this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27); + this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29); + this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31); + }; + + /** + * Renders one segment of the plane. + * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure + * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used. + * + * @private + * @param {CanvasRenderingContext2D} context - The context to draw with. + * @param {CanvasImageSource} textureSource - The source to draw. + * @param {number} w - width of the texture + * @param {number} h - height of the texture + * @param {number} x1 - x index 1 + * @param {number} y1 - y index 1 + * @param {number} x2 - x index 2 + * @param {number} y2 - y index 2 + */ + + + NineSlicePlane.prototype.drawSegment = function drawSegment(context, textureSource, w, h, x1, y1, x2, y2) { + // otherwise you get weird results when using slices of that are 0 wide or high. + var uvs = this.uvs; + var vertices = this.vertices; + + var sw = (uvs[x2] - uvs[x1]) * w; + var sh = (uvs[y2] - uvs[y1]) * h; + var dw = vertices[x2] - vertices[x1]; + var dh = vertices[y2] - vertices[y1]; + + // make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn. + if (sw < 1) { + sw = 1; + } + + if (sh < 1) { + sh = 1; + } + + // make sure destination is at least 1 pixel wide and high, otherwise you get + // lines when rendering close to original size. + if (dw < 1) { + dw = 1; + } + + if (dh < 1) { + dh = 1; + } + + context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh); + }; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + + _createClass(NineSlicePlane, [{ + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + this.updateVerticalVertices(); + } + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + this.updateHorizontalVertices(); + } + + /** + * The width of the left column + * + * @member {number} + */ + + }, { + key: 'leftWidth', + get: function get() { + return this._leftWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._leftWidth = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = this._uvw * value; + vertices[2] = vertices[10] = vertices[18] = vertices[26] = value; + + this.dirty = true; + } + + /** + * The width of the right column + * + * @member {number} + */ + + }, { + key: 'rightWidth', + get: function get() { + return this._rightWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rightWidth = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - this._uvw * value; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - value; + + this.dirty = true; + } + + /** + * The height of the top row + * + * @member {number} + */ + + }, { + key: 'topHeight', + get: function get() { + return this._topHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._topHeight = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[9] = uvs[11] = uvs[13] = uvs[15] = this._uvh * value; + vertices[9] = vertices[11] = vertices[13] = vertices[15] = value; + + this.dirty = true; + } + + /** + * The height of the bottom row + * + * @member {number} + */ + + }, { + key: 'bottomHeight', + get: function get() { + return this._bottomHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._bottomHeight = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - this._uvh * value; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - value; + + this.dirty = true; + } + }]); + + return NineSlicePlane; +}(_Plane3.default); + +exports.default = NineSlicePlane; + +},{"./Plane":163}],163:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The Plane allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Plane = function (_Mesh) { + _inherits(Plane, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the Plane. + * @param {number} verticesX - The number of vertices in the x-axis + * @param {number} verticesY - The number of vertices in the y-axis + */ + function Plane(texture, verticesX, verticesY) { + _classCallCheck(this, Plane); + + /** + * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this._ready = true; + + _this.verticesX = verticesX || 10; + _this.verticesY = verticesY || 10; + + _this.drawMode = _Mesh3.default.DRAW_MODES.TRIANGLES; + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Plane.prototype.refresh = function refresh() { + var total = this.verticesX * this.verticesY; + var verts = []; + var colors = []; + var uvs = []; + var indices = []; + var texture = this.texture; + + var segmentsX = this.verticesX - 1; + var segmentsY = this.verticesY - 1; + + var sizeX = texture.width / segmentsX; + var sizeY = texture.height / segmentsY; + + for (var i = 0; i < total; i++) { + if (texture._uvs) { + var x = i % this.verticesX; + var y = i / this.verticesX | 0; + + verts.push(x * sizeX, y * sizeY); + + // this works for rectangular textures. + uvs.push(texture._uvs.x0 + (texture._uvs.x1 - texture._uvs.x0) * (x / (this.verticesX - 1)), texture._uvs.y0 + (texture._uvs.y3 - texture._uvs.y0) * (y / (this.verticesY - 1))); + } else { + uvs.push(0); + } + } + + // cons + + var totalSub = segmentsX * segmentsY; + + for (var _i = 0; _i < totalSub; _i++) { + var xpos = _i % segmentsX; + var ypos = _i / segmentsX | 0; + + var value = ypos * this.verticesX + xpos; + var value2 = ypos * this.verticesX + xpos + 1; + var value3 = (ypos + 1) * this.verticesX + xpos; + var value4 = (ypos + 1) * this.verticesX + xpos + 1; + + indices.push(value, value2, value3); + indices.push(value2, value4, value3); + } + + // console.log(indices) + this.vertices = new Float32Array(verts); + this.uvs = new Float32Array(uvs); + this.colors = new Float32Array(colors); + this.indices = new Uint16Array(indices); + + this.indexDirty = true; + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Plane.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh3.default.prototype._onTextureUpdate.call(this); + + // wait for the Plane ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + return Plane; +}(_Mesh3.default); + +exports.default = Plane; + +},{"./Mesh":161}],164:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The rope allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Rope = function (_Mesh) { + _inherits(Rope, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the rope. + * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. + */ + function Rope(texture, points) { + _classCallCheck(this, Rope); + + /* + * @member {PIXI.Point[]} An array of points that determine the rope + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this.points = points; + + /* + * @member {Float32Array} An array of vertices used to construct this rope. + */ + _this.vertices = new Float32Array(points.length * 4); + + /* + * @member {Float32Array} The WebGL Uvs of the rope. + */ + _this.uvs = new Float32Array(points.length * 4); + + /* + * @member {Float32Array} An array containing the color components + */ + _this.colors = new Float32Array(points.length * 2); + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + _this.indices = new Uint16Array(points.length * 2); + + /** + * Tracker for if the rope is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + _this._ready = true; + + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Rope.prototype.refresh = function refresh() { + var points = this.points; + + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1 || !this._texture._uvs) { + return; + } + + // if the number of points has changed we will need to recreate the arraybuffers + if (this.vertices.length / 4 !== points.length) { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + var textureUvs = this._texture._uvs; + var offset = new core.Point(textureUvs.x0, textureUvs.y0); + var factor = new core.Point(textureUvs.x2 - textureUvs.x0, Number(textureUvs.y2 - textureUvs.y0)); + + uvs[0] = 0 + offset.x; + uvs[1] = 0 + offset.y; + uvs[2] = 0 + offset.x; + uvs[3] = factor.y + offset.y; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + + for (var i = 1; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + var amount = i / (total - 1); + + uvs[index] = amount * factor.x + offset.x; + uvs[index + 1] = 0 + offset.y; + + uvs[index + 2] = amount * factor.x + offset.x; + uvs[index + 3] = factor.y + offset.y; + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + + // ensure that the changes are uploaded + this.dirty++; + this.indexDirty++; + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Rope.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh.prototype._onTextureUpdate.call(this); + + // wait for the Rope ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + Rope.prototype.updateTransform = function updateTransform() { + var points = this.points; + + if (points.length < 1) { + return; + } + + var lastPoint = points[0]; + var nextPoint = void 0; + var perpX = 0; + var perpY = 0; + + // this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } else { + nextPoint = point; + } + + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + + var ratio = (1 - i / (total - 1)) * 10; + + if (ratio > 1) { + ratio = 1; + } + + var perpLength = Math.sqrt(perpX * perpX + perpY * perpY); + var num = this._texture.height / 2; // (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; + + perpX /= perpLength; + perpY /= perpLength; + + perpX *= num; + perpY *= num; + + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + + lastPoint = point; + } + + this.containerUpdateTransform(); + }; + + return Rope; +}(_Mesh3.default); + +exports.default = Rope; + +},{"../core":63,"./Mesh":161}],165:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Renderer dedicated to meshes. + * + * @class + * @private + * @memberof PIXI + */ +var MeshSpriteRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The renderer this downport works for + */ + function MeshSpriteRenderer(renderer) { + _classCallCheck(this, MeshSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the Mesh + * + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var context = renderer.context; + + var transform = mesh.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + renderer.setBlendMode(mesh.blendMode); + + if (mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH) { + this._renderTriangleMesh(mesh); + } else { + this._renderTriangles(mesh); + } + }; + + /** + * Draws the object in Triangle Mesh mode + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype._renderTriangleMesh = function _renderTriangleMesh(mesh) { + // draw triangles!! + var length = mesh.vertices.length / 2; + + for (var i = 0; i < length - 2; i++) { + // draw some triangles! + var index = i * 2; + + this._renderDrawTriangle(mesh, index, index + 2, index + 4); + } + }; + + /** + * Draws the object in triangle mode using canvas + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + */ + + + MeshSpriteRenderer.prototype._renderTriangles = function _renderTriangles(mesh) { + // draw triangles!! + var indices = mesh.indices; + var length = indices.length; + + for (var i = 0; i < length; i += 3) { + // draw some triangles! + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderDrawTriangle(mesh, index0, index1, index2); + } + }; + + /** + * Draws one of the triangles that from the Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + * @param {number} index0 - the index of the first vertex + * @param {number} index1 - the index of the second vertex + * @param {number} index2 - the index of the third vertex + */ + + + MeshSpriteRenderer.prototype._renderDrawTriangle = function _renderDrawTriangle(mesh, index0, index1, index2) { + var context = this.renderer.context; + var uvs = mesh.uvs; + var vertices = mesh.vertices; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var base = texture.baseTexture; + var textureSource = base.source; + var textureWidth = base.width; + var textureHeight = base.height; + + var u0 = uvs[index0] * base.width; + var u1 = uvs[index1] * base.width; + var u2 = uvs[index2] * base.width; + var v0 = uvs[index0 + 1] * base.height; + var v1 = uvs[index1 + 1] * base.height; + var v2 = uvs[index2 + 1] * base.height; + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + if (mesh.canvasPadding > 0) { + var paddingX = mesh.canvasPadding / mesh.worldTransform.a; + var paddingY = mesh.canvasPadding / mesh.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt(normX * normX + normY * normY); + + x0 = centerX + normX / dist * (dist + paddingX); + y0 = centerY + normY / dist * (dist + paddingY); + + // + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x1 = centerX + normX / dist * (dist + paddingX); + y1 = centerY + normY / dist * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x2 = centerX + normX / dist * (dist + paddingX); + y2 = centerY + normY / dist * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2; + var deltaA = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2; + var deltaB = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2; + var deltaC = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2; + var deltaD = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2; + var deltaE = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2; + var deltaF = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2; + + context.transform(deltaA / delta, deltaD / delta, deltaB / delta, deltaE / delta, deltaC / delta, deltaF / delta); + + context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + + context.restore(); + }; + + /** + * Renders a flat Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - The Mesh to render + */ + + + MeshSpriteRenderer.prototype.renderMeshFlat = function renderMeshFlat(mesh) { + var context = this.renderer.context; + var vertices = mesh.vertices; + var length = vertices.length / 2; + + // this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; ++i) { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var y0 = vertices[index + 1]; + + var x1 = vertices[index + 2]; + var y1 = vertices[index + 3]; + + var x2 = vertices[index + 4]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + }; + + /** + * destroy the the renderer. + * + */ + + + MeshSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return MeshSpriteRenderer; +}(); + +exports.default = MeshSpriteRenderer; + + +core.CanvasRenderer.registerPlugin('mesh', MeshSpriteRenderer); + +},{"../../core":63,"../Mesh":161}],166:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh = require('./Mesh'); + +Object.defineProperty(exports, 'Mesh', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Mesh).default; + } +}); + +var _MeshRenderer = require('./webgl/MeshRenderer'); + +Object.defineProperty(exports, 'MeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_MeshRenderer).default; + } +}); + +var _CanvasMeshRenderer = require('./canvas/CanvasMeshRenderer'); + +Object.defineProperty(exports, 'CanvasMeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasMeshRenderer).default; + } +}); + +var _Plane = require('./Plane'); + +Object.defineProperty(exports, 'Plane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Plane).default; + } +}); + +var _NineSlicePlane = require('./NineSlicePlane'); + +Object.defineProperty(exports, 'NineSlicePlane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NineSlicePlane).default; + } +}); + +var _Rope = require('./Rope'); + +Object.defineProperty(exports, 'Rope', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rope).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./Mesh":161,"./NineSlicePlane":162,"./Plane":163,"./Rope":164,"./canvas/CanvasMeshRenderer":165,"./webgl/MeshRenderer":167}],167:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var MeshRenderer = function (_core$ObjectRenderer) { + _inherits(MeshRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function MeshRenderer(renderer) { + _classCallCheck(this, MeshRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + MeshRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 translationMatrix;\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n}\n', 'varying vec2 vTextureCoord;\nuniform float alpha;\nuniform vec3 tint;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * vec4(tint * alpha, alpha);\n}\n'); + }; + + /** + * renders mesh + * + * @param {PIXI.mesh.Mesh} mesh mesh instance + */ + + + MeshRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var gl = renderer.gl; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var glData = mesh._glDatas[renderer.CONTEXT_UID]; + + if (!glData) { + renderer.bindVao(null); + + glData = { + shader: this.shader, + vertexBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.vertices, gl.STREAM_DRAW), + uvBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.uvs, gl.STREAM_DRAW), + indexBuffer: _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, mesh.indices, gl.STATIC_DRAW), + // build the vao object that will render.. + vao: null, + dirty: mesh.dirty, + indexDirty: mesh.indexDirty + }; + + // build the vao object that will render.. + glData.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(glData.indexBuffer).addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0).addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); + + mesh._glDatas[renderer.CONTEXT_UID] = glData; + } + + renderer.bindVao(glData.vao); + + if (mesh.dirty !== glData.dirty) { + glData.dirty = mesh.dirty; + glData.uvBuffer.upload(mesh.uvs); + } + + if (mesh.indexDirty !== glData.indexDirty) { + glData.indexDirty = mesh.indexDirty; + glData.indexBuffer.upload(mesh.indices); + } + + glData.vertexBuffer.upload(mesh.vertices); + + renderer.bindShader(glData.shader); + + glData.shader.uniforms.uSampler = renderer.bindTexture(texture); + + renderer.state.setBlendMode(mesh.blendMode); + + glData.shader.uniforms.translationMatrix = mesh.worldTransform.toArray(true); + glData.shader.uniforms.alpha = mesh.worldAlpha; + glData.shader.uniforms.tint = mesh.tintRgb; + + var drawMode = mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + glData.vao.draw(drawMode, mesh.indices.length, 0); + }; + + return MeshRenderer; +}(core.ObjectRenderer); + +exports.default = MeshRenderer; + + +core.WebGLRenderer.registerPlugin('mesh', MeshRenderer); + +},{"../../core":63,"../Mesh":161,"path":22,"pixi-gl-core":12}],168:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that advanced + * functionality will not work. ParticleContainer implements only the basic object transform (position, scale, rotation). + * Any other functionality like tinting, masking, etc will not work on sprites in this batch. + * + * It's extremely easy to use : + * + * ```js + * let container = new ParticleContainer(); + * + * for (let i = 0; i < 100; ++i) + * { + * let sprite = new PIXI.Sprite.fromImage("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be renderer at the speed of light. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.particles + */ +var ParticleContainer = function (_core$Container) { + _inherits(ParticleContainer, _core$Container); + + /** + * @param {number} [maxSize=15000] - The maximum number of particles that can be renderer by the container. + * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.scale=false] - When true, scale be uploaded and applied. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.alpha=false] - When true, alpha be uploaded and applied. + * @param {number} [batchSize=15000] - Number of particles per batch. + */ + function ParticleContainer() { + var maxSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1500; + var properties = arguments[1]; + var batchSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 16384; + + _classCallCheck(this, ParticleContainer); + + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + var maxBatchSize = 16384; + + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + + if (batchSize > maxSize) { + batchSize = maxSize; + } + + /** + * Set properties to be dynamic (true) / static (false) + * + * @member {boolean[]} + * @private + */ + _this._properties = [false, true, false, false, false]; + + /** + * @member {number} + * @private + */ + _this._maxSize = maxSize; + + /** + * @member {number} + * @private + */ + _this._batchSize = batchSize; + + /** + * @member {object} + * @private + */ + _this._glBuffers = {}; + + /** + * @member {number} + * @private + */ + _this._bufferToUpdate = 0; + + /** + * @member {boolean} + * + */ + _this.interactiveChildren = false; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` + * to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Used for canvas renderering. If true then the elements will be positioned at the + * nearest pixel. This provides a nice speed boost. + * + * @member {boolean} + * @default true; + */ + _this.roundPixels = true; + + /** + * The texture used to render the children. + * + * @readonly + * @member {BaseTexture} + */ + _this.baseTexture = null; + + _this.setProperties(properties); + return _this; + } + + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * + * @param {object} properties - The properties to be uploaded + */ + + + ParticleContainer.prototype.setProperties = function setProperties(properties) { + if (properties) { + this._properties[0] = 'scale' in properties ? !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'alpha' in properties ? !!properties.alpha : this._properties[4]; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + ParticleContainer.prototype.updateTransform = function updateTransform() { + // TODO don't need to! + this.displayObjectUpdateTransform(); + // PIXI.Container.prototype.updateTransform.call( this ); + }; + + /** + * Renders the container using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer + */ + + + ParticleContainer.prototype.renderWebGL = function renderWebGL(renderer) { + var _this2 = this; + + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.hasLoaded) { + this.baseTexture.once('update', function () { + return _this2.onChildrenChange(0); + }); + } + } + + renderer.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + + /** + * Set the flag that static data should be updated to true + * + * @private + * @param {number} smallestChildIndex - The smallest child index + */ + + + ParticleContainer.prototype.onChildrenChange = function onChildrenChange(smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + + if (bufferIndex < this._bufferToUpdate) { + this._bufferToUpdate = bufferIndex; + } + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + + + ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var isRotated = true; + + var positionX = 0; + var positionY = 0; + + var finalWidth = 0; + var finalHeight = 0; + + var compositeOperation = renderer.blendModes[this.blendMode]; + + if (compositeOperation !== context.globalCompositeOperation) { + context.globalCompositeOperation = compositeOperation; + } + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i]; + + if (!child.visible) { + continue; + } + + var frame = child._texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) { + // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call + if (isRotated) { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx * renderer.resolution, transform.ty * renderer.resolution); + + isRotated = false; + } + + positionX = child.anchor.x * (-frame.width * child.scale.x) + child.position.x + 0.5; + positionY = child.anchor.y * (-frame.height * child.scale.y) + child.position.y + 0.5; + + finalWidth = frame.width * child.scale.x; + finalHeight = frame.height * child.scale.y; + } else { + if (!isRotated) { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + + if (renderer.roundPixels) { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution | 0, childTransform.ty * renderer.resolution | 0); + } else { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution, childTransform.ty * renderer.resolution); + } + + positionX = child.anchor.x * -frame.width + 0.5; + positionY = child.anchor.y * -frame.height + 0.5; + + finalWidth = frame.width; + finalHeight = frame.height; + } + + var resolution = child._texture.baseTexture.resolution; + + context.drawImage(child._texture.baseTexture.source, frame.x * resolution, frame.y * resolution, frame.width * resolution, frame.height * resolution, positionX * resolution, positionY * resolution, finalWidth * resolution, finalHeight * resolution); + } + }; + + /** + * Destroys the container + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + ParticleContainer.prototype.destroy = function destroy(options) { + _core$Container.prototype.destroy.call(this, options); + + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + } + + this._properties = null; + this._buffers = null; + }; + + return ParticleContainer; +}(core.Container); + +exports.default = ParticleContainer; + +},{"../core":63}],169:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ParticleContainer = require('./ParticleContainer'); + +Object.defineProperty(exports, 'ParticleContainer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleContainer).default; + } +}); + +var _ParticleRenderer = require('./webgl/ParticleRenderer'); + +Object.defineProperty(exports, 'ParticleRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleRenderer).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./ParticleContainer":168,"./webgl/ParticleRenderer":171}],170:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + +/** + * The particle buffer manages the static and dynamic buffers for a particle container. + * + * @class + * @private + * @memberof PIXI + */ +var ParticleBuffer = function () { + /** + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(gl, properties, dynamicPropertyFlags, size) { + _classCallCheck(this, ParticleBuffer); + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * Size of a single vertex. + * + * @member {number} + */ + this.vertSize = 2; + + /** + * Size of a single vertex in bytes. + * + * @member {number} + */ + this.vertByteSize = this.vertSize * 4; + + /** + * The number of particles the buffer can hold + * + * @member {number} + */ + this.size = size; + + /** + * A list of the properties that are dynamic. + * + * @member {object[]} + */ + this.dynamicProperties = []; + + /** + * A list of the properties that are static. + * + * @member {object[]} + */ + this.staticProperties = []; + + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attribute: property.attribute, + size: property.size, + uploadFunction: property.uploadFunction, + offset: property.offset + }; + + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } else { + this.staticProperties.push(property); + } + } + + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + + this.initBuffers(); + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + ParticleBuffer.prototype.initBuffers = function initBuffers() { + var gl = this.gl; + var dynamicOffset = 0; + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(this.size); + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + this.dynamicStride = 0; + + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + + this.dynamicData = new Float32Array(this.size * this.dynamicStride * 4); + this.dynamicBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.dynamicData, gl.STREAM_DRAW); + + // static // + var staticOffset = 0; + + this.staticStride = 0; + + for (var _i = 0; _i < this.staticProperties.length; ++_i) { + var _property = this.staticProperties[_i]; + + _property.offset = staticOffset; + staticOffset += _property.size; + this.staticStride += _property.size; + } + + this.staticData = new Float32Array(this.size * this.staticStride * 4); + this.staticBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.staticData, gl.STATIC_DRAW); + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(this.indexBuffer); + + for (var _i2 = 0; _i2 < this.dynamicProperties.length; ++_i2) { + var _property2 = this.dynamicProperties[_i2]; + + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.FLOAT, false, this.dynamicStride * 4, _property2.offset * 4); + } + + for (var _i3 = 0; _i3 < this.staticProperties.length; ++_i3) { + var _property3 = this.staticProperties[_i3]; + + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.FLOAT, false, this.staticStride * 4, _property3.offset * 4); + } + }; + + /** + * Uploads the dynamic properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadDynamic = function uploadDynamic(children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + + property.uploadFunction(children, startIndex, amount, this.dynamicData, this.dynamicStride, property.offset); + } + + this.dynamicBuffer.upload(); + }; + + /** + * Uploads the static properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadStatic = function uploadStatic(children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + + property.uploadFunction(children, startIndex, amount, this.staticData, this.staticStride, property.offset); + } + + this.staticBuffer.upload(); + }; + + /** + * Destroys the ParticleBuffer. + * + */ + + + ParticleBuffer.prototype.destroy = function destroy() { + this.dynamicProperties = null; + this.dynamicData = null; + this.dynamicBuffer.destroy(); + + this.staticProperties = null; + this.staticData = null; + this.staticBuffer.destroy(); + }; + + return ParticleBuffer; +}(); + +exports.default = ParticleBuffer; + +},{"../../core/utils/createIndicesForQuads":118,"pixi-gl-core":12}],171:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _ParticleShader = require('./ParticleShader'); + +var _ParticleShader2 = _interopRequireDefault(_ParticleShader); + +var _ParticleBuffer = require('./ParticleBuffer'); + +var _ParticleBuffer2 = _interopRequireDefault(_ParticleBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + +/** + * + * @class + * @private + * @memberof PIXI + */ +var ParticleRenderer = function (_core$ObjectRenderer) { + _inherits(ParticleRenderer, _core$ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + _classCallCheck(this, ParticleRenderer); + + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; + + /** + * The default shader that is used if a sprite doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + + _this.indexBuffer = null; + + _this.properties = null; + + _this.tempMatrix = new core.Matrix(); + + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * When there is a WebGL context change + * + * @private + */ + + + ParticleRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + + // setup default shader + this.shader = new _ParticleShader2.default(gl); + + this.properties = [ + // verticesData + { + attribute: this.shader.attributes.aVertexPosition, + size: 2, + uploadFunction: this.uploadVertices, + offset: 0 + }, + // positionData + { + attribute: this.shader.attributes.aPositionCoord, + size: 2, + uploadFunction: this.uploadPosition, + offset: 0 + }, + // rotationData + { + attribute: this.shader.attributes.aRotation, + size: 1, + uploadFunction: this.uploadRotation, + offset: 0 + }, + // uvsData + { + attribute: this.shader.attributes.aTextureCoord, + size: 2, + uploadFunction: this.uploadUvs, + offset: 0 + }, + // alphaData + { + attribute: this.shader.attributes.aColor, + size: 1, + uploadFunction: this.uploadAlpha, + offset: 0 + }]; + }; + + /** + * Starts a new particle batch. + * + */ + + + ParticleRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + }; + + /** + * Renders the particle container object. + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + */ + + + ParticleRenderer.prototype.render = function render(container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var renderer = this.renderer; + var totalChildren = children.length; + + if (totalChildren === 0) { + return; + } else if (totalChildren > maxSize) { + totalChildren = maxSize; + } + + var buffers = container._glBuffers[renderer.CONTEXT_UID]; + + if (!buffers) { + buffers = container._glBuffers[renderer.CONTEXT_UID] = this.generateBuffers(container); + } + + // if the uvs have not updated then no point rendering just yet! + this.renderer.setBlendMode(container.blendMode); + + var gl = renderer.gl; + + var m = container.worldTransform.copy(this.tempMatrix); + + m.prepend(renderer._activeRenderTarget.projectionMatrix); + + this.shader.uniforms.projectionMatrix = m.toArray(true); + this.shader.uniforms.uAlpha = container.worldAlpha; + + // make sure the texture is bound.. + var baseTexture = children[0]._texture.baseTexture; + + this.shader.uniforms.uSampler = renderer.bindTexture(baseTexture); + + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = totalChildren - i; + + if (amount > batchSize) { + amount = batchSize; + } + + var buffer = buffers[j]; + + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + + // we only upload the static content when we have to! + if (container._bufferToUpdate === j) { + buffer.uploadStatic(children, i, amount); + container._bufferToUpdate = j + 1; + } + + // bind the buffer + renderer.bindVao(buffer.vao); + buffer.vao.draw(gl.TRIANGLES, amount * 6); + } + }; + + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer[]} The buffers + */ + + + ParticleRenderer.prototype.generateBuffers = function generateBuffers(container) { + var gl = this.renderer.gl; + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + for (var i = 0; i < size; i += batchSize) { + buffers.push(new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize)); + } + + return buffers; + }; + + /** + * Uploads the verticies. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their vertices uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadVertices = function uploadVertices(children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - sprite.anchor.x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - sprite.anchor.y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - sprite.anchor.x); + w1 = orig.width * -sprite.anchor.x; + + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + + array[offset + stride * 2] = w0 * sx; + array[offset + stride * 2 + 1] = h0 * sy; + + array[offset + stride * 3] = w1 * sx; + array[offset + stride * 3 + 1] = h0 * sy; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their positions uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadPosition = function uploadPosition(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + + array[offset + stride * 2] = spritePosition.x; + array[offset + stride * 2 + 1] = spritePosition.y; + + array[offset + stride * 3] = spritePosition.x; + array[offset + stride * 3 + 1] = spritePosition.y; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadRotation = function uploadRotation(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + stride * 2] = spriteRotation; + array[offset + stride * 3] = spriteRotation; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadUvs = function uploadUvs(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + + array[offset + stride * 2] = textureUvs.x2; + array[offset + stride * 2 + 1] = textureUvs.y2; + + array[offset + stride * 3] = textureUvs.x3; + array[offset + stride * 3 + 1] = textureUvs.y3; + + offset += stride * 4; + } else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + + array[offset + stride * 2] = 0; + array[offset + stride * 2 + 1] = 0; + + array[offset + stride * 3] = 0; + array[offset + stride * 3 + 1] = 0; + + offset += stride * 4; + } + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadAlpha = function uploadAlpha(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteAlpha = children[startIndex + i].alpha; + + array[offset] = spriteAlpha; + array[offset + stride] = spriteAlpha; + array[offset + stride * 2] = spriteAlpha; + array[offset + stride * 3] = spriteAlpha; + + offset += stride * 4; + } + }; + + /** + * Destroys the ParticleRenderer. + * + */ + + + ParticleRenderer.prototype.destroy = function destroy() { + if (this.renderer.gl) { + this.renderer.gl.deleteBuffer(this.indexBuffer); + } + + _core$ObjectRenderer.prototype.destroy.call(this); + + this.shader.destroy(); + + this.indices = null; + this.tempMatrix = null; + }; + + return ParticleRenderer; +}(core.ObjectRenderer); + +exports.default = ParticleRenderer; + + +core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + +},{"../../core":63,"./ParticleBuffer":170,"./ParticleShader":172}],172:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../core/Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI + */ +var ParticleShader = function (_Shader) { + _inherits(ParticleShader, _Shader); + + /** + * @param {PIXI.Shader} gl - The webgl shader manager this shader works for. + */ + function ParticleShader(gl) { + _classCallCheck(this, ParticleShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'attribute float aColor;', 'attribute vec2 aPositionCoord;', 'attribute vec2 aScale;', 'attribute float aRotation;', 'uniform mat3 projectionMatrix;', 'varying vec2 vTextureCoord;', 'varying float vColor;', 'void main(void){', ' vec2 v = aVertexPosition;', ' v.x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);', ' v.y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);', ' v = v + aPositionCoord;', ' gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = aColor;', '}'].join('\n'), + // hello + ['varying vec2 vTextureCoord;', 'varying float vColor;', 'uniform sampler2D uSampler;', 'uniform float uAlpha;', 'void main(void){', ' vec4 color = texture2D(uSampler, vTextureCoord) * vColor * uAlpha;', ' if (color.a == 0.0) discard;', ' gl_FragColor = color;', '}'].join('\n'))); + } + + return ParticleShader; +}(_Shader3.default); + +exports.default = ParticleShader; + +},{"../../core/Shader":42}],173:[function(require,module,exports){ +"use strict"; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + +if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + + if (x === 0 || isNaN(x)) { + return x; + } + + return x > 0 ? 1 : -1; + }; +} + +},{}],174:[function(require,module,exports){ +'use strict'; + +var _objectAssign = require('object-assign'); + +var _objectAssign2 = _interopRequireDefault(_objectAssign); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +if (!Object.assign) { + Object.assign = _objectAssign2.default; +} // References: +// https://github.com/sindresorhus/object-assign +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + +},{"object-assign":5}],175:[function(require,module,exports){ +'use strict'; + +require('./Object.assign'); + +require('./requestAnimationFrame'); + +require('./Math.sign'); + +if (!window.ArrayBuffer) { + window.ArrayBuffer = Array; +} + +if (!window.Float32Array) { + window.Float32Array = Array; +} + +if (!window.Uint32Array) { + window.Uint32Array = Array; +} + +if (!window.Uint16Array) { + window.Uint16Array = Array; +} + +},{"./Math.sign":173,"./Object.assign":174,"./requestAnimationFrame":176}],176:[function(require,module,exports){ +(function (global){ +'use strict'; + +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + +// Expected to be used with Browserfiy +// Browserify automatically detects the use of `global` and passes the +// correct reference of `global`, `self`, and finally `window` + +var ONE_FRAME_TIME = 16; + +// Date.now +if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; +} + +// performance.now +if (!(global.performance && global.performance.now)) { + (function () { + var startTime = Date.now(); + + if (!global.performance) { + global.performance = {}; + } + + global.performance.now = function () { + return Date.now() - startTime; + }; + })(); +} + +// requestAnimationFrame +var lastTime = Date.now(); +var vendors = ['ms', 'moz', 'webkit', 'o']; + +for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { + var p = vendors[x]; + + global.requestAnimationFrame = global[p + 'RequestAnimationFrame']; + global.cancelAnimationFrame = global[p + 'CancelAnimationFrame'] || global[p + 'CancelRequestAnimationFrame']; +} + +if (!global.requestAnimationFrame) { + global.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + 'is not a function'); + } + + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + + if (delay < 0) { + delay = 0; + } + + lastTime = currentTime; + + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} + +if (!global.cancelAnimationFrame) { + global.cancelAnimationFrame = function (id) { + return clearTimeout(id); + }; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],177:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CountLimiter = require('./limiters/CountLimiter'); + +var _CountLimiter2 = _interopRequireDefault(_CountLimiter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SharedTicker = core.ticker.shared; + +/** + * Default number of uploads per frame using prepare plugin. + * + * @static + * @memberof PIXI.settings + * @name UPLOADS_PER_FRAME + * @type {number} + * @default 4 + */ +core.settings.UPLOADS_PER_FRAME = 4; + +/** + * The prepare manager provides functionality to upload content to the GPU. BasePrepare handles + * basic queuing functionality and is extended by {@link PIXI.prepare.WebGLPrepare} and {@link PIXI.prepare.CanvasPrepare} + * to provide preparation capabilities specific to their respective renderers. + * + * @abstract + * @class + * @memberof PIXI.prepare + */ + +var BasePrepare = function () { + /** + * @param {PIXI.SystemRenderer} renderer - A reference to the current renderer + */ + function BasePrepare(renderer) { + var _this = this; + + _classCallCheck(this, BasePrepare); + + /** + * The limiter to be used to control how quickly items are prepared. + * @type {PIXI.prepare.CountLimiter|PIXI.prepare.TimeLimiter} + */ + this.limiter = new _CountLimiter2.default(core.settings.UPLOADS_PER_FRAME); + + /** + * Reference to the renderer. + * @type {PIXI.SystemRenderer} + * @protected + */ + this.renderer = renderer; + + /** + * The only real difference between CanvasPrepare and WebGLPrepare is what they pass + * to upload hooks. That different parameter is stored here. + * @type {PIXI.prepare.CanvasPrepare|PIXI.WebGLRenderer} + * @protected + */ + this.uploadHookHelper = null; + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + /** + * 'bound' call for prepareItems(). + * @type {Function} + * @private + */ + this.delayedTick = function () { + // unlikely, but in case we were destroyed between tick() and delayedTick() + if (!_this.queue) { + return; + } + _this.prepareItems(); + }; + + this.register(findText, drawText); + this.register(findTextStyle, calculateTextStyle); + } + + /** + * Upload all the textures and graphics to the GPU. + * + * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item - + * Either the container or display object to search for items to upload, the items to upload themselves, + * or the callback function, if items have been added using `prepare.add`. + * @param {Function} [done] - Optional callback when all queued uploads have completed + */ + + + BasePrepare.prototype.upload = function upload(item, done) { + if (typeof item === 'function') { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) { + if (done) { + this.completes.push(done); + } + + if (!this.ticking) { + this.ticking = true; + SharedTicker.addOnce(this.tick, this); + } + } else if (done) { + done(); + } + }; + + /** + * Handle tick update + * + * @private + */ + + + BasePrepare.prototype.tick = function tick() { + setTimeout(this.delayedTick, 0); + }; + + /** + * Actually prepare items. This is handled outside of the tick because it will take a while + * and we do NOT want to block the current animation frame from rendering. + * + * @private + */ + + + BasePrepare.prototype.prepareItems = function prepareItems() { + this.limiter.beginFrame(); + // Upload the graphics + while (this.queue.length && this.limiter.allowedToUpload()) { + var item = this.queue[0]; + var uploaded = false; + + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.uploadHookHelper, item)) { + this.queue.shift(); + uploaded = true; + break; + } + } + + if (!uploaded) { + this.queue.shift(); + } + } + + // We're finished + if (!this.queue.length) { + this.ticking = false; + + var completes = this.completes.slice(0); + + this.completes.length = 0; + + for (var _i = 0, _len = completes.length; _i < _len; _i++) { + completes[_i](); + } + } else { + // if we are not finished, on the next rAF do this again + SharedTicker.addOnce(this.tick, this); + } + }; + + /** + * Adds hooks for finding and uploading items. + * + * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array` + function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.register = function register(addHook, uploadHook) { + if (addHook) { + this.addHooks.push(addHook); + } + + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + + return this; + }; + + /** + * Manually add an item to the uploading queue. + * + * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to + * add to the queue + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.add = function add(item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) { + for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { + this.add(item.children[_i2]); + } + } + + return this; + }; + + /** + * Destroys the plugin, don't use after this. + * + */ + + + BasePrepare.prototype.destroy = function destroy() { + if (this.ticking) { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.limiter = null; + this.uploadHookHelper = null; + }; + + return BasePrepare; +}(); + +/** + * Built-in hook to draw PIXI.Text to its texture. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = BasePrepare; +function drawText(helper, item) { + if (item instanceof core.Text) { + // updating text will return early if it is not dirty + item.updateText(true); + + return true; + } + + return false; +} + +/** + * Built-in hook to calculate a text style for a PIXI.Text object. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function calculateTextStyle(helper, item) { + if (item instanceof core.TextStyle) { + var font = core.Text.getFontStyle(item); + + if (!core.Text.fontPropertiesCache[font]) { + core.Text.calculateFontProperties(font); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find Text objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Text object was found. + */ +function findText(item, queue) { + if (item instanceof core.Text) { + // push the text style to prepare it - this can be really expensive + if (queue.indexOf(item.style) === -1) { + queue.push(item.style); + } + // also push the text object so that we can render it (to canvas/texture) if needed + if (queue.indexOf(item) === -1) { + queue.push(item); + } + // also push the Text's texture for upload to GPU + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find TextStyle objects. + * + * @private + * @param {PIXI.TextStyle} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.TextStyle object was found. + */ +function findTextStyle(item, queue) { + if (item instanceof core.TextStyle) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +},{"../core":63,"./limiters/CountLimiter":180}],178:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CANVAS_START_SIZE = 16; + +/** + * The prepare manager provides functionality to upload content to the GPU + * This cannot be done directly for Canvas like in WebGL, but the effect can be achieved by drawing + * textures to an offline canvas. + * This draw call will force the texture to be moved onto the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ + +var CanvasPrepare = function (_BasePrepare) { + _inherits(CanvasPrepare, _BasePrepare); + + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasPrepare(renderer) { + _classCallCheck(this, CanvasPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this; + + /** + * An offline canvas to render textures to + * @type {HTMLCanvasElement} + * @private + */ + _this.canvas = document.createElement('canvas'); + _this.canvas.width = CANVAS_START_SIZE; + _this.canvas.height = CANVAS_START_SIZE; + + /** + * The context to the canvas + * @type {CanvasRenderingContext2D} + * @private + */ + _this.ctx = _this.canvas.getContext('2d'); + + // Add textures to upload + _this.register(findBaseTextures, uploadBaseTextures); + return _this; + } + + /** + * Destroys the plugin, don't use after this. + * + */ + + + CanvasPrepare.prototype.destroy = function destroy() { + _BasePrepare.prototype.destroy.call(this); + this.ctx = null; + this.canvas = null; + }; + + return CanvasPrepare; +}(_BasePrepare3.default); + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {*} prepare - Instance of CanvasPrepare + * @param {*} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = CanvasPrepare; +function uploadBaseTextures(prepare, item) { + if (item instanceof core.BaseTexture) { + var image = item.source; + + // Sometimes images (like atlas images) report a size of zero, causing errors on windows phone. + // So if the width or height is equal to zero then use the canvas size + // Otherwise use whatever is smaller, the image dimensions or the canvas dimensions. + var imageWidth = image.width === 0 ? prepare.canvas.width : Math.min(prepare.canvas.width, image.width); + var imageHeight = image.height === 0 ? prepare.canvas.height : Math.min(prepare.canvas.height, image.height); + + // Only a small subsections is required to be drawn to have the whole texture uploaded to the GPU + // A smaller draw can be faster. + prepare.ctx.drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, prepare.canvas.width, prepare.canvas.height); + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item -Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTextures(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } else if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); + +},{"../../core":63,"../BasePrepare":177}],179:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLPrepare = require('./webgl/WebGLPrepare'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLPrepare).default; + } +}); + +var _CanvasPrepare = require('./canvas/CanvasPrepare'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasPrepare).default; + } +}); + +var _BasePrepare = require('./BasePrepare'); + +Object.defineProperty(exports, 'BasePrepare', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BasePrepare).default; + } +}); + +var _CountLimiter = require('./limiters/CountLimiter'); + +Object.defineProperty(exports, 'CountLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CountLimiter).default; + } +}); + +var _TimeLimiter = require('./limiters/TimeLimiter'); + +Object.defineProperty(exports, 'TimeLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TimeLimiter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./BasePrepare":177,"./canvas/CanvasPrepare":178,"./limiters/CountLimiter":180,"./limiters/TimeLimiter":181,"./webgl/WebGLPrepare":182}],180:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * CountLimiter limits the number of items handled by a {@link PIXI.prepare.BasePrepare} to a specified + * number of items per frame. + * + * @class + * @memberof PIXI + */ +var CountLimiter = function () { + /** + * @param {number} maxItemsPerFrame - The maximum number of items that can be prepared each frame. + */ + function CountLimiter(maxItemsPerFrame) { + _classCallCheck(this, CountLimiter); + + /** + * The maximum number of items that can be prepared each frame. + * @private + */ + this.maxItemsPerFrame = maxItemsPerFrame; + /** + * The number of items that can be prepared in the current frame. + * @type {number} + * @private + */ + this.itemsLeft = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + CountLimiter.prototype.beginFrame = function beginFrame() { + this.itemsLeft = this.maxItemsPerFrame; + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + CountLimiter.prototype.allowedToUpload = function allowedToUpload() { + return this.itemsLeft-- > 0; + }; + + return CountLimiter; +}(); + +exports.default = CountLimiter; + +},{}],181:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of milliseconds per frame. + * + * @class + * @memberof PIXI + */ +var TimeLimiter = function () { + /** + * @param {number} maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. + */ + function TimeLimiter(maxMilliseconds) { + _classCallCheck(this, TimeLimiter); + + /** + * The maximum milliseconds that can be spent preparing items each frame. + * @private + */ + this.maxMilliseconds = maxMilliseconds; + /** + * The start time of the current frame. + * @type {number} + * @private + */ + this.frameStart = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + TimeLimiter.prototype.beginFrame = function beginFrame() { + this.frameStart = Date.now(); + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + TimeLimiter.prototype.allowedToUpload = function allowedToUpload() { + return Date.now() - this.frameStart < this.maxMilliseconds; + }; + + return TimeLimiter; +}(); + +exports.default = TimeLimiter; + +},{}],182:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The prepare manager provides functionality to upload content to the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ +var WebGLPrepare = function (_BasePrepare) { + _inherits(WebGLPrepare, _BasePrepare); + + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLPrepare(renderer) { + _classCallCheck(this, WebGLPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this.renderer; + + // Add textures and graphics to upload + _this.register(findBaseTextures, uploadBaseTextures).register(findGraphics, uploadGraphics); + return _this; + } + + return WebGLPrepare; +}(_BasePrepare3.default); + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = WebGLPrepare; +function uploadBaseTextures(renderer, item) { + if (item instanceof core.BaseTexture) { + // if the texture already has a GL texture, then the texture has been prepared or rendered + // before now. If the texture changed, then the changer should be calling texture.update() which + // reuploads the texture without need for preparing it again + if (!item._glTextures[renderer.CONTEXT_UID]) { + renderer.textureManager.updateTexture(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to upload PIXI.Graphics to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadGraphics(renderer, item) { + if (item instanceof core.Graphics) { + // if the item is not dirty and already has webgl data, then it got prepared or rendered + // before now and we shouldn't waste time updating it again + if (item.dirty || item.clearDirty || !item._webGL[renderer.plugins.graphics.CONTEXT_UID]) { + renderer.plugins.graphics.updateGraphics(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTextures(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } else if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find graphics. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Graphics object was found. + */ +function findGraphics(item, queue) { + if (item instanceof core.Graphics) { + queue.push(item); + + return true; + } + + return false; +} + +core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); + +},{"../../core":63,"../BasePrepare":177}],183:[function(require,module,exports){ +(function (global){ +'use strict'; + +exports.__esModule = true; +exports.loader = exports.prepare = exports.particles = exports.mesh = exports.loaders = exports.interaction = exports.filters = exports.extras = exports.extract = exports.accessibility = undefined; + +var _polyfill = require('./polyfill'); + +Object.keys(_polyfill).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _polyfill[key]; + } + }); +}); + +var _deprecation = require('./deprecation'); + +Object.keys(_deprecation).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _deprecation[key]; + } + }); +}); + +var _core = require('./core'); + +Object.keys(_core).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _core[key]; + } + }); +}); + +var _accessibility = require('./accessibility'); + +var accessibility = _interopRequireWildcard(_accessibility); + +var _extract = require('./extract'); + +var extract = _interopRequireWildcard(_extract); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// export libs + + +// export core +_core.utils.mixins.performMixins(); + +// handle mixins now, after all code has been added, including deprecation +// import polyfills. Done as an export to make sure polyfills are imported first +exports.accessibility = accessibility; +exports.extract = extract; +exports.extras = extras; +exports.filters = filters; +exports.interaction = interaction; +exports.loaders = loaders; +exports.mesh = mesh; +exports.particles = particles; +exports.prepare = prepare; + +/** + * A premade instance of the loader that can be used to load resources. + * + * @name loader + * @memberof PIXI + * @property {PIXI.loaders.Loader} + */ + +var loader = loaders && loaders.Loader ? new loaders.Loader() : null; // check is there in case user excludes loader lib + +exports.loader = loader; + +// Always export pixi globally. + +global.PIXI = exports; // eslint-disable-line + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"./accessibility":40,"./core":63,"./deprecation":125,"./extract":127,"./extras":136,"./filters":147,"./interaction":154,"./loaders":157,"./mesh":166,"./particles":169,"./polyfill":175,"./prepare":179}]},{},[183])(183) +}); + + +//# sourceMappingURL=pixi.js.map diff --git a/js/pixi/4.3.5-dev/pixi.min.js b/js/pixi/4.3.5-dev/pixi.min.js new file mode 100644 index 0000000..12df672 --- /dev/null +++ b/js/pixi/4.3.5-dev/pixi.min.js @@ -0,0 +1,21 @@ +/*! + * pixi.js - v4.3.5 + * Compiled Wed, 15 Feb 2017 17:11:47 UTC + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.PIXI=t()}}(function(){var t;return function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var h=new Error("Cannot find module '"+s+"'");throw h.code="MODULE_NOT_FOUND",h}var l=r[s]={exports:{}};e[s][0].call(l.exports,function(t){var r=e[s][1][t];return i(r?r:t)},l,l.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s0)-(t<0)},r.abs=function(t){var e=t>>i-1;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,e|=r,e|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,t=(858993459&t)+(t>>>2&858993459),16843009*(t+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,t&=15,27030>>>t&1};var o=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|o[t>>>16&255]<<8|o[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),t=65535&(t|t>>>16),t<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),t=1023&(t|t>>>16),t<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],2:[function(t,e,r){"use strict";function n(t,e,r){r=r||2;var n=e&&e.length,o=n?e[0]*r:t.length,a=i(t,0,o,r,!0),u=[];if(!a)return u;var h,l,f,d,p,v,y;if(n&&(a=c(t,e,a,r)),t.length>80*r){h=f=t[0],l=d=t[1];for(var g=r;gf&&(f=p),v>d&&(d=v);y=Math.max(f-h,d-l)}return s(a,u,r,h,l,y),u}function i(t,e,r,n,i){var o,s;if(i===A(t,e,r,n)>0)for(o=e;o=e;o-=n)s=M(o,t[o],t[o+1],s);return s&&T(s,s.next)&&(C(s),s=s.next),s}function o(t,e){if(!t)return t;e||(e=t);var r,n=t;do if(r=!1,n.steiner||!T(n,n.next)&&0!==x(n.prev,n,n.next))n=n.next;else{if(C(n),n=e=n.prev,n===n.next)return null;r=!0}while(r||n!==e);return e}function s(t,e,r,n,i,c,f){if(t){!f&&c&&v(t,n,i,c);for(var d,p,y=t;t.prev!==t.next;)if(d=t.prev,p=t.next,c?u(t,n,i,c):a(t))e.push(d.i/r),e.push(t.i/r),e.push(p.i/r),C(t),t=p.next,y=p.next;else if(t=p,t===y){f?1===f?(t=h(t,e,r),s(t,e,r,n,i,c,2)):2===f&&l(t,e,r,n,i,c):s(o(t),e,r,n,i,c,1);break}}}function a(t){var e=t.prev,r=t,n=t.next;if(x(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(_(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&x(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function u(t,e,r,n){var i=t.prev,o=t,s=t.next;if(x(i,o,s)>=0)return!1;for(var a=i.xo.x?i.x>s.x?i.x:s.x:o.x>s.x?o.x:s.x,l=i.y>o.y?i.y>s.y?i.y:s.y:o.y>s.y?o.y:s.y,c=g(a,u,e,r,n),f=g(h,l,e,r,n),d=t.nextZ;d&&d.z<=f;){if(d!==t.prev&&d!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,d.x,d.y)&&x(d.prev,d,d.next)>=0)return!1;d=d.nextZ}for(d=t.prevZ;d&&d.z>=c;){if(d!==t.prev&&d!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,d.x,d.y)&&x(d.prev,d,d.next)>=0)return!1;d=d.prevZ}return!0}function h(t,e,r){var n=t;do{var i=n.prev,o=n.next.next;!T(i,o)&&w(i,n,n.next,o)&&S(i,o)&&S(o,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(o.i/r),C(n),C(n.next),n=t=o),n=n.next}while(n!==t);return n}function l(t,e,r,n,i,a){var u=t;do{for(var h=u.next.next;h!==u.prev;){if(u.i!==h.i&&b(u,h)){var l=P(u,h);return u=o(u,u.next),l=o(l,l.next),s(u,e,r,n,i,a),void s(l,e,r,n,i,a)}h=h.next}u=u.next}while(u!==t)}function c(t,e,r,n){var s,a,u,h,l,c=[];for(s=0,a=e.length;s=n.next.y){var a=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=i&&a>s){if(s=a,a===i){if(o===n.y)return n;if(o===n.next.y)return n.next}r=n.x=n.x&&n.x>=l&&_(or.x)&&S(n,t)&&(r=n,f=u)),n=n.next;return r}function v(t,e,r,n){var i=t;do null===i.z&&(i.z=g(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,y(i)}function y(t){var e,r,n,i,o,s,a,u,h=1;do{for(r=t,t=null,o=null,s=0;r;){for(s++,n=r,a=0,e=0;e0||u>0&&n;)0===a?(i=n,n=n.nextZ,u--):0!==u&&n?r.z<=n.z?(i=r,r=r.nextZ,a--):(i=n,n=n.nextZ,u--):(i=r,r=r.nextZ,a--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;r=n}o.nextZ=null,h*=2}while(s>1);return t}function g(t,e,r,n,i){return t=32767*(t-r)/i,e=32767*(e-n)/i,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1}function m(t){var e=t,r=t;do e.x=0&&(t-s)*(n-a)-(r-s)*(e-a)>=0&&(r-s)*(o-a)-(i-s)*(n-a)>=0}function b(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!E(t,e)&&S(t,e)&&S(e,t)&&O(t,e)}function x(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function T(t,e){return t.x===e.x&&t.y===e.y}function w(t,e,r,n){return!!(T(t,e)&&T(r,n)||T(t,n)&&T(r,e))||x(t,e,r)>0!=x(t,e,n)>0&&x(r,n,t)>0!=x(r,n,e)>0}function E(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&w(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}function S(t,e){return x(t.prev,t,t.next)<0?x(t,e,t.next)>=0&&x(t,t.prev,e)>=0:x(t,e,t.prev)<0||x(t,t.next,e)<0}function O(t,e){var r=t,n=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do r.y>o!=r.next.y>o&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;while(r!==t);return n}function P(t,e){var r=new R(t.i,t.x,t.y),n=new R(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function M(t,e,r,n){var i=new R(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function C(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function R(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(t,e,r,n){for(var i=0,o=e,s=r-n;o0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],3:[function(t,e,r){"use strict";function n(){}function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function o(){this._events=new n,this._eventsCount=0}var s=Object.prototype.hasOwnProperty,a="~";Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(a=!1)),o.prototype.eventNames=function(){var t,e,r=[];if(0===this._eventsCount)return r;for(e in t=this._events)s.call(t,e)&&r.push(a?e.slice(1):e);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t,e){var r=a?a+t:t,n=this._events[r];if(e)return!!n;if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i=t.byteLength?n.bufferSubData(this.type,e,t):n.bufferData(this.type,t,this.drawType),this.data=t},i.prototype.bind=function(){var t=this.gl;t.bindBuffer(this.type,this.buffer)},i.createVertexBuffer=function(t,e,r){return new i(t,t.ARRAY_BUFFER,e,r)},i.createIndexBuffer=function(t,e,r){return new i(t,t.ELEMENT_ARRAY_BUFFER,e,r)},i.create=function(t,e,r,n){return new i(t,e,r,n)},i.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer)},e.exports=i},{}],7:[function(t,e,r){var n=t("./GLTexture"),i=function(t,e,r){this.gl=t,this.framebuffer=t.createFramebuffer(),this.stencil=null,this.texture=null,this.width=e||100,this.height=r||100};i.prototype.enableTexture=function(t){var e=this.gl;this.texture=t||new n(e),this.texture.bind(),this.bind(),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0)},i.prototype.enableStencil=function(){if(!this.stencil){var t=this.gl;this.stencil=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.stencil),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.stencil),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,this.width,this.height)}},i.prototype.clear=function(t,e,r,n){this.bind();var i=this.gl;i.clearColor(t,e,r,n),i.clear(i.COLOR_BUFFER_BIT)},i.prototype.bind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer)},i.prototype.unbind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)},i.prototype.resize=function(t,e){var r=this.gl;this.width=t,this.height=e,this.texture&&this.texture.uploadData(null,t,e),this.stencil&&(r.bindRenderbuffer(r.RENDERBUFFER,this.stencil),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e))},i.prototype.destroy=function(){var t=this.gl;this.texture&&this.texture.destroy(),t.deleteFramebuffer(this.framebuffer),this.gl=null,this.stencil=null,this.texture=null},i.createRGBA=function(t,e,r,o){var s=n.fromData(t,null,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},i.createFloat32=function(t,e,r,o){var s=new n.fromData(t,o,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},e.exports=i},{"./GLTexture":9}],8:[function(t,e,r){var n=t("./shader/compileProgram"),i=t("./shader/extractAttributes"),o=t("./shader/extractUniforms"),s=t("./shader/generateUniformAccessObject"),a=function(t,e,r){this.gl=t,this.program=n(t,e,r),this.attributes=i(t,this.program);var a=o(t,this.program);this.uniforms=s(t,a)};a.prototype.bind=function(){this.gl.useProgram(this.program)},a.prototype.destroy=function(){},e.exports=a},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18}],9:[function(t,e,r){var n=function(t,e,r,n,i){this.gl=t,this.texture=t.createTexture(),this.mipmap=!1,this.premultiplyAlpha=!1,this.width=e||-1,this.height=r||-1,this.format=n||t.RGBA,this.type=i||t.UNSIGNED_BYTE};n.prototype.upload=function(t){this.bind();var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var r=t.videoWidth||t.width,n=t.videoHeight||t.height;n!==this.height||r!==this.width?e.texImage2D(e.TEXTURE_2D,0,this.format,this.format,this.type,t):e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.format,this.type,t),this.width=r,this.height=n};var i=!1;n.prototype.uploadData=function(t,e,r){this.bind();var n=this.gl;if(t instanceof Float32Array){if(!i){var o=n.getExtension("OES_texture_float");if(!o)throw new Error("floating point textures not available");i=!0}this.type=n.FLOAT}else this.type=n.UNSIGNED_BYTE;n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),e!==this.width||r!==this.height?n.texImage2D(n.TEXTURE_2D,0,this.format,e,r,0,this.format,this.type,t||null):n.texSubImage2D(n.TEXTURE_2D,0,0,0,e,r,this.format,this.type,t||null),this.width=e,this.height=r},n.prototype.bind=function(t){var e=this.gl;void 0!==t&&e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,this.texture)},n.prototype.unbind=function(){var t=this.gl;t.bindTexture(t.TEXTURE_2D,null)},n.prototype.minFilter=function(t){var e=this.gl;this.bind(),this.mipmap?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.magFilter=function(t){var e=this.gl;this.bind(),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.enableMipmap=function(){var t=this.gl;this.bind(),this.mipmap=!0,t.generateMipmap(t.TEXTURE_2D)},n.prototype.enableLinearScaling=function(){this.minFilter(!0),this.magFilter(!0)},n.prototype.enableNearestScaling=function(){this.minFilter(!1),this.magFilter(!1)},n.prototype.enableWrapClamp=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)},n.prototype.enableWrapRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT)},n.prototype.enableWrapMirrorRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.MIRRORED_REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.MIRRORED_REPEAT)},n.prototype.destroy=function(){var t=this.gl;t.deleteTexture(this.texture)},n.fromSource=function(t,e,r){var i=new n(t);return i.premultiplyAlpha=r||!1,i.upload(e),i},n.fromData=function(t,e,r,i){var o=new n(t);return o.uploadData(e,r,i),o},e.exports=n},{}],10:[function(t,e,r){function n(t,e){if(this.nativeVaoExtension=null,n.FORCE_NATIVE||(this.nativeVaoExtension=t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object")),this.nativeState=e,this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var r=t.getParameter(t.MAX_VERTEX_ATTRIBS);this.nativeState={tempAttribState:new Array(r),attribState:new Array(r)}}this.gl=t,this.attributes=[],this.indexBuffer=null,this.dirty=!1}var i=t("./setVertexAttribArrays");n.prototype.constructor=n,e.exports=n,n.FORCE_NATIVE=!1,n.prototype.bind=function(){return this.nativeVao?(this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao),this.dirty&&(this.dirty=!1,this.activate())):this.activate(),this},n.prototype.unbind=function(){return this.nativeVao&&this.nativeVaoExtension.bindVertexArrayOES(null),this},n.prototype.activate=function(){for(var t=this.gl,e=null,r=0;r=0;n--){var i=t[n];"."===i?t.splice(n,1):".."===i?(t.splice(n,1),r++):r&&(t.splice(n,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}function n(t,e){if(t.filter)return t.filter(e);for(var r=[],n=0;n=-1&&!i;o--){var s=o>=0?arguments[o]:t.cwd();if("string"!=typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(r=s+"/"+r,i="/"===s.charAt(0))}return r=e(n(r.split("/"),function(t){return!!t}),!i).join("/"),(i?"/":"")+r||"."},r.normalize=function(t){var i=r.isAbsolute(t),o="/"===s(t,-1);return t=e(n(t.split("/"),function(t){return!!t}),!i).join("/"),t||i||(t="."),t&&o&&(t+="/"),(i?"/":"")+t},r.isAbsolute=function(t){return"/"===t.charAt(0)},r.join=function(){var t=Array.prototype.slice.call(arguments,0);return r.normalize(n(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},r.relative=function(t,e){function n(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=r.resolve(t).substr(1),e=r.resolve(e).substr(1);for(var i=n(t.split("/")),o=n(e.split("/")),s=Math.min(i.length,o.length),a=s,u=0;u1)for(var r=1;r1&&(n=r[0]+"@",t=r[1]),t=t.replace(D,".");var i=t.split("."),o=s(i,e).join(".");return n+o}function u(t){for(var e,r,n=[],i=0,o=t.length;i=55296&&e<=56319&&i65535&&(t-=65536,e+=B(t>>>10&1023|55296),t=56320|1023&t),e+=B(t)}).join("")}function l(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:w}function c(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function f(t,e,r){var n=0;for(t=r?N(t/P):t>>1,t+=N(t/e);t>F*S>>1;n+=w)t=N(t/F);return N(n+(F+1)*t/(t+O))}function d(t){var e,r,n,i,s,a,u,c,d,p,v=[],y=t.length,g=0,m=C,_=M;for(r=t.lastIndexOf(R),r<0&&(r=0),n=0;n=128&&o("not-basic"),v.push(t.charCodeAt(n));for(i=r>0?r+1:0;i=y&&o("invalid-input"),c=l(t.charCodeAt(i++)),(c>=w||c>N((T-g)/a))&&o("overflow"),g+=c*a,d=u<=_?E:u>=_+S?S:u-_,!(cN(T/p)&&o("overflow"),a*=p;e=v.length+1,_=f(g-s,e,0==s),N(g/e)>T-m&&o("overflow"),m+=N(g/e),g%=e,v.splice(g++,0,m)}return h(v)}function p(t){var e,r,n,i,s,a,h,l,d,p,v,y,g,m,_,b=[];for(t=u(t),y=t.length,e=C,r=0,s=M,a=0;a=e&&vN((T-r)/g)&&o("overflow"),r+=(h-e)*g,e=h,a=0;aT&&o("overflow"),v==e){for(l=r,d=w;p=d<=s?E:d>=s+S?S:d-s,!(l= 0x80 (not a basic code point)","invalid-input":"Invalid input"},F=w-E,N=Math.floor,B=String.fromCharCode;if(b={version:"1.4.1",ucs2:{decode:u,encode:h},decode:d,encode:p,toASCII:y,toUnicode:v},"function"==typeof t&&"object"==typeof t.amd&&t.amd)t("punycode",function(){return b});else if(g&&m)if(r.exports==g)m.exports=b;else for(x in b)b.hasOwnProperty(x)&&(g[x]=b[x]);else i.punycode=b}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],25:[function(t,e,r){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,r,o){e=e||"&",r=r||"=";var s={};if("string"!=typeof t||0===t.length)return s;var a=/\+/g;t=t.split(e);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var h=t.length;u>0&&h>u&&(h=u);for(var l=0;l=0?(c=v.substr(0,y),f=v.substr(y+1)):(c=v,f=""),d=decodeURIComponent(c),p=decodeURIComponent(f),n(s,d)?i(s[d])?s[d].push(p):s[d]=[s[d],p]:s[d]=p}return s};var i=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],26:[function(t,e,r){"use strict";function n(t,e){if(t.map)return t.map(e);for(var r=[],n=0;n",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(d),v=["'"].concat(p),y=["%","/","?",";","#"].concat(v),g=["/","?","#"],m=255,_=/^[+a-z0-9A-Z_-]{0,63}$/,b=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,x={javascript:!0,"javascript:":!0},T={javascript:!0,"javascript:":!0},w={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},E=t("querystring");n.prototype.parse=function(t,e,r){if(!h.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var n=t.indexOf("?"),i=n!==-1&&n127?"x":L[N];if(!F.match(_)){var j=I.slice(0,P),k=I.slice(P+1),U=L.match(b);U&&(j.push(U[1]),k.unshift(U[2])),k.length&&(a="/"+k.join(".")+a),this.hostname=j.join(".");break}}}this.hostname.length>m?this.hostname="":this.hostname=this.hostname.toLowerCase(),A||(this.hostname=u.toASCII(this.hostname));var X=this.port?":"+this.port:"",G=this.hostname||"";this.host=G+X,this.href+=this.host,A&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==a[0]&&(a="/"+a))}if(!x[p])for(var P=0,D=v.length;P0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return r.search=t.search,r.query=t.query,h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!x.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var O=x.slice(-1)[0],P=(r.host||t.host||x.length>1)&&("."===O||".."===O)||""===O,M=0,C=x.length;C>=0;C--)O=x[C],"."===O?x.splice(C,1):".."===O?(x.splice(C,1),M++):M&&(x.splice(C,1),M--);if(!_&&!b)for(;M--;M)x.unshift("..");!_||""===x[0]||x[0]&&"/"===x[0].charAt(0)||x.unshift(""),P&&"/"!==x.join("/").substr(-1)&&x.push("");var R=""===x[0]||x[0]&&"/"===x[0].charAt(0);if(E){r.hostname=r.host=R?"":x.length?x.shift():"";var S=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return _=_||r.host&&x.length,_&&!R&&x.unshift(""),x.length?r.pathname=x.join("/"):(r.pathname=null,r.path=null),h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},n.prototype.parseHost=function(){var t=this.host,e=c.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":29,punycode:24,querystring:27}],29:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],30:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a=t("mini-signals"),u=i(a),h=t("parse-uri"),l=i(h),c=t("./async"),f=n(c),d=t("./Resource"),p=i(d),v=100,y=/(#[\w-]+)?$/,g=function(){function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10;o(this,t),this.baseUrl=r,this.progress=0,this.loading=!1,this.defaultQueryString="",this._beforeMiddleware=[],this._afterMiddleware=[],this._resourcesParsing=[],this._boundLoadResource=function(t,r){return e._loadResource(t,r)},this._queue=f.queue(this._boundLoadResource,n),this._queue.pause(),this.resources={},this.onProgress=new u.default,this.onError=new u.default,this.onLoad=new u.default,this.onStart=new u.default,this.onComplete=new u.default}return t.prototype.add=function(t,e,r,n){if(Array.isArray(t)){for(var i=0;i0))return void this.abort("["+e.status+"] "+e.statusText+": "+e.responseURL);if(this.xhrType===t.XHR_RESPONSE_TYPE.TEXT)this.data=e.responseText,this.type=t.TYPE.TEXT;else if(this.xhrType===t.XHR_RESPONSE_TYPE.JSON)try{this.data=JSON.parse(e.responseText),this.type=t.TYPE.JSON}catch(t){return void this.abort("Error trying to parse loaded json: "+t)}else if(this.xhrType===t.XHR_RESPONSE_TYPE.DOCUMENT)try{if(window.DOMParser){var n=new DOMParser;this.data=n.parseFromString(e.responseText,"text/xml")}else{var i=document.createElement("div");i.innerHTML=e.responseText,this.data=i}this.type=t.TYPE.XML}catch(t){return void this.abort("Error trying to parse loaded xml: "+t)}else this.data=e.response||e.responseText;this.complete()},t.prototype._determineCrossOrigin=function(t,e){if(0===t.indexOf("data:"))return"";e=e||window.location,p||(p=document.createElement("a")),p.href=t,t=(0,l.default)(p.href,{strictMode:!0});var r=!t.port&&""===e.port||t.port===e.port,n=t.protocol?t.protocol+":":"";return t.host===e.hostname&&r&&n===e.protocol?"":"anonymous"},t.prototype._determineXhrType=function(){return t._xhrTypeMap[this.extension]||t.XHR_RESPONSE_TYPE.TEXT},t.prototype._determineLoadType=function(){return t._loadTypeMap[this.extension]||t.LOAD_TYPE.XHR},t.prototype._getExtension=function(){var t=this.url,e="";if(this.isDataUrl){var r=t.indexOf("/");e=t.substring(r+1,t.indexOf(";",r))}else{var n=t.indexOf("?");n!==-1&&(t=t.substring(0,n)),e=t.substring(t.lastIndexOf(".")+1)}return e.toLowerCase()},t.prototype._getMimeFromXhrType=function(e){switch(e){case t.XHR_RESPONSE_TYPE.BUFFER:return"application/octet-binary";case t.XHR_RESPONSE_TYPE.BLOB:return"application/blob";case t.XHR_RESPONSE_TYPE.DOCUMENT:return"application/xml";case t.XHR_RESPONSE_TYPE.JSON:return"application/json";case t.XHR_RESPONSE_TYPE.DEFAULT:case t.XHR_RESPONSE_TYPE.TEXT:default:return"text/plain"}},u(t,[{key:"isDataUrl",get:function(){return this._hasFlag(t.STATUS_FLAGS.DATA_URL)}},{key:"isComplete",get:function(){return this._hasFlag(t.STATUS_FLAGS.COMPLETE)}},{key:"isLoading",get:function(){return this._hasFlag(t.STATUS_FLAGS.LOADING)}}]),t}();r.default=m,m.STATUS_FLAGS={NONE:0,DATA_URL:1,COMPLETE:2,LOADING:4},m.TYPE={UNKNOWN:0,JSON:1,XML:2,IMAGE:3,AUDIO:4,VIDEO:5,TEXT:6},m.LOAD_TYPE={XHR:1,IMAGE:2,AUDIO:3,VIDEO:4},m.XHR_RESPONSE_TYPE={DEFAULT:"text",BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"},m._loadTypeMap={gif:m.LOAD_TYPE.IMAGE,png:m.LOAD_TYPE.IMAGE,bmp:m.LOAD_TYPE.IMAGE,jpg:m.LOAD_TYPE.IMAGE,jpeg:m.LOAD_TYPE.IMAGE,tif:m.LOAD_TYPE.IMAGE,tiff:m.LOAD_TYPE.IMAGE,webp:m.LOAD_TYPE.IMAGE,tga:m.LOAD_TYPE.IMAGE,svg:m.LOAD_TYPE.IMAGE,"svg+xml":m.LOAD_TYPE.IMAGE,mp3:m.LOAD_TYPE.AUDIO,ogg:m.LOAD_TYPE.AUDIO,wav:m.LOAD_TYPE.AUDIO,mp4:m.LOAD_TYPE.VIDEO,webm:m.LOAD_TYPE.VIDEO},m._xhrTypeMap={xhtml:m.XHR_RESPONSE_TYPE.DOCUMENT,html:m.XHR_RESPONSE_TYPE.DOCUMENT,htm:m.XHR_RESPONSE_TYPE.DOCUMENT,xml:m.XHR_RESPONSE_TYPE.DOCUMENT,tmx:m.XHR_RESPONSE_TYPE.DOCUMENT,svg:m.XHR_RESPONSE_TYPE.DOCUMENT,tsx:m.XHR_RESPONSE_TYPE.DOCUMENT,gif:m.XHR_RESPONSE_TYPE.BLOB,png:m.XHR_RESPONSE_TYPE.BLOB,bmp:m.XHR_RESPONSE_TYPE.BLOB,jpg:m.XHR_RESPONSE_TYPE.BLOB,jpeg:m.XHR_RESPONSE_TYPE.BLOB,tif:m.XHR_RESPONSE_TYPE.BLOB,tiff:m.XHR_RESPONSE_TYPE.BLOB,webp:m.XHR_RESPONSE_TYPE.BLOB,tga:m.XHR_RESPONSE_TYPE.BLOB,json:m.XHR_RESPONSE_TYPE.JSON,text:m.XHR_RESPONSE_TYPE.TEXT,txt:m.XHR_RESPONSE_TYPE.TEXT,ttf:m.XHR_RESPONSE_TYPE.BUFFER,otf:m.XHR_RESPONSE_TYPE.BUFFER},m.EMPTY_GIF="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="},{"mini-signals":36,"parse-uri":37}],32:[function(t,e,r){"use strict";function n(){}function i(t,e,r){var n=0,i=t.length;!function o(s){return s||n===i?void(r&&r(s)):void e(t[n++],o)}()}function o(t){return function(){if(null===t)throw new Error("Callback was already called.");var e=t;t=null,e.apply(this,arguments)}}function s(t,e){function r(t,e,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(a.started=!0,null==t&&a.idle())return void setTimeout(function(){return a.drain()},1);var i={data:t,callback:"function"==typeof r?r:n};e?a._tasks.unshift(i):a._tasks.push(i),setTimeout(function(){return a.process()},1)}function i(t){return function(){s-=1,t.callback.apply(t,arguments),null!=arguments[0]&&a.error(arguments[0],t.data),s<=a.concurrency-a.buffer&&a.unsaturated(),a.idle()&&a.drain(),a.process()}}if(null==e)e=1;else if(0===e)throw new Error("Concurrency must not be zero");var s=0,a={_tasks:[],concurrency:e,saturated:n,unsaturated:n,buffer:e/4,empty:n,drain:n,error:n,started:!1,paused:!1,push:function(t,e){r(t,!1,e)},kill:function(){s=0,a.drain=n,a.started=!1,a._tasks=[]},unshift:function(t,e){r(t,!0,e)},process:function(){for(;!a.paused&&s>2,o[1]=(3&n[0])<<4|n[1]>>4,o[2]=(15&n[1])<<2|n[2]>>6,o[3]=63&n[2];var a=r-(t.length-1);switch(a){case 2:o[3]=64,o[2]=64;break;case 1:o[3]=64}for(var u=0;u=0;r--)this.updateAccessibleObjects(e[r])}},t.prototype.update=function(){if(this.renderer.renderingToScreen){this.updateAccessibleObjects(this.renderer._lastObjectRendered);var t=this.renderer.view.getBoundingClientRect(),e=t.width/this.renderer.width,r=t.height/this.renderer.height,n=this.div;n.style.left=t.left+"px",n.style.top=t.top+"px",n.style.width=this.renderer.width+"px",n.style.height=this.renderer.height+"px";for(var i=0;ithis.renderer.width&&(t.width=this.renderer.width-t.x),t.y+t.height>this.renderer.height&&(t.height=this.renderer.height-t.y)},t.prototype.addChild=function(t){var e=this.pool.pop();e||(e=document.createElement("button"),e.style.width=d+"px",e.style.height=d+"px",e.style.backgroundColor=this.debug?"rgba(255,0,0,0.5)":"transparent",e.style.position="absolute",e.style.zIndex=y,e.style.borderStyle="none",e.addEventListener("click",this._onClick.bind(this)),e.addEventListener("focus",this._onFocus.bind(this)),e.addEventListener("focusout",this._onFocusOut.bind(this))),t.accessibleTitle?e.title=t.accessibleTitle:t.accessibleTitle||t.accessibleHint||(e.title="displayObject "+this.tabIndex),t.accessibleHint&&e.setAttribute("aria-label",t.accessibleHint),t._accessibleActive=!0,t._accessibleDiv=e,e.displayObject=t,this.children.push(t),this.div.appendChild(t._accessibleDiv),t._accessibleDiv.tabIndex=t.tabIndex},t.prototype._onClick=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"click",e.eventData)},t.prototype._onFocus=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseover",e.eventData)},t.prototype._onFocusOut=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseout",e.eventData)},t.prototype._onKeyDown=function(t){t.keyCode===f&&this.activate()},t.prototype._onMouseMove=function(){this.deactivate()},t.prototype.destroy=function(){this.div=null;for(var t=0;t4&&void 0!==arguments[4]&&arguments[4];i(this,t),this.renderer=(0,s.autoDetectRenderer)(e,r,n,o),this.stage=new u.default,this._ticker=null,this.ticker=a?h.shared:new h.Ticker,this.start()}return t.prototype.render=function(){this.renderer.render(this.stage)},t.prototype.stop=function(){this._ticker.stop()},t.prototype.start=function(){this._ticker.start()},t.prototype.destroy=function(t){this.stop(),this.ticker=null,this.stage.destroy(),this.stage=null,this.renderer.destroy(t),this.renderer=null},o(t,[{key:"ticker",set:function(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this)},get:function(){return this._ticker}},{key:"view",get:function(){return this.renderer.view}},{key:"screen",get:function(){return this.renderer.screen}}]),t}();r.default=l},{"./autoDetectRenderer":43,"./display/Container":46,"./ticker":116}],42:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t){if(t instanceof Array){if("precision"!==t[0].substring(0,9)){var e=t.slice(0);return e.unshift("precision "+c+" float;"),e}}else if("precision"!==t.substring(0,9))return"precision "+c+" float;\n"+t;return t}r.__esModule=!0;var u=t("pixi-gl-core"),h=t("./settings"),l=n(h),c=l.default.PRECISION,f=function(t){function e(r,n,s){return i(this,e),o(this,t.call(this,r,a(n),a(s)))}return s(e,t),e}(u.GLShader);r.default=f},{"./settings":99,"pixi-gl-core":12}],43:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:800,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:600,r=arguments[2],n=arguments[3];return!n&&a.isWebGLSupported()?new c.default(t,e,r):new h.default(t,e,r)}r.__esModule=!0,r.autoDetectRenderer=o;var s=t("./utils"),a=i(s),u=t("./renderers/canvas/CanvasRenderer"),h=n(u),l=t("./renderers/webgl/WebGLRenderer"),c=n(l)},{"./renderers/canvas/CanvasRenderer":75,"./renderers/webgl/WebGLRenderer":82,"./utils":120}],44:[function(t,e,r){"use strict";r.__esModule=!0;r.VERSION="4.3.5",r.PI_2=2*Math.PI,r.RAD_TO_DEG=180/Math.PI,r.DEG_TO_RAD=Math.PI/180,r.RENDERER_TYPE={UNKNOWN:0,WEBGL:1,CANVAS:2},r.BLEND_MODES={NORMAL:0,ADD:1,MULTIPLY:2,SCREEN:3,OVERLAY:4,DARKEN:5,LIGHTEN:6,COLOR_DODGE:7,COLOR_BURN:8,HARD_LIGHT:9,SOFT_LIGHT:10,DIFFERENCE:11,EXCLUSION:12,HUE:13,SATURATION:14,COLOR:15,LUMINOSITY:16},r.DRAW_MODES={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},r.SCALE_MODES={LINEAR:0,NEAREST:1},r.WRAP_MODES={CLAMP:0,REPEAT:1,MIRRORED_REPEAT:2},r.GC_MODES={AUTO:0,MANUAL:1},r.URL_FILE_EXTENSION=/\.(\w{3,4})(?:$|\?|#)/i,r.DATA_URI=/^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;(charset=[\w-]+|base64))?,(.*)/i,r.SVG_SIZE=/]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i,r.SHAPES={POLY:0,RECT:1,CIRC:2,ELIP:3,RREC:4},r.PRECISION={LOW:"lowp",MEDIUM:"mediump",HIGH:"highp"},r.TRANSFORM_MODE={STATIC:0,DYNAMIC:1},r.TEXT_GRADIENT={LINEAR_VERTICAL:0,LINEAR_HORIZONTAL:1}},{}],45:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../math"),o=function(){function t(){n(this,t),this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0),this.rect=null}return t.prototype.isEmpty=function(){return this.minX>this.maxX||this.minY>this.maxY},t.prototype.clear=function(){this.updateID++,this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0)},t.prototype.getRectangle=function(t){return this.minX>this.maxX||this.minY>this.maxY?i.Rectangle.EMPTY:(t=t||new i.Rectangle(0,0,1,1),t.x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)},t.prototype.addPoint=function(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)},t.prototype.addQuad=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY,o=t[0],s=t[1];e=on?o:n,i=s>i?s:i,o=t[2],s=t[3],e=on?o:n,i=s>i?s:i,o=t[4],s=t[5],e=on?o:n,i=s>i?s:i,o=t[6],s=t[7],e=on?o:n,i=s>i?s:i,this.minX=e,this.minY=r,this.maxX=n,this.maxY=i},t.prototype.addFrame=function(t,e,r,n,i){var o=t.worldTransform,s=o.a,a=o.b,u=o.c,h=o.d,l=o.tx,c=o.ty,f=this.minX,d=this.minY,p=this.maxX,v=this.maxY,y=s*e+u*r+l,g=a*e+h*r+c;f=yp?y:p,v=g>v?g:v,y=s*n+u*r+l,g=a*n+h*r+c,f=yp?y:p,v=g>v?g:v,y=s*e+u*i+l,g=a*e+h*i+c,f=yp?y:p,v=g>v?g:v,y=s*n+u*i+l,g=a*n+h*i+c,f=yp?y:p,v=g>v?g:v,this.minX=f,this.minY=d,this.maxX=p,this.maxY=v},t.prototype.addVertices=function(t,e,r,n){for(var i=t.worldTransform,o=i.a,s=i.b,a=i.c,u=i.d,h=i.tx,l=i.ty,c=this.minX,f=this.minY,d=this.maxX,p=this.maxY,v=r;vd?m:d,p=_>p?_:p}this.minX=c,this.minY=f,this.maxX=d,this.maxY=p},t.prototype.addBounds=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY;this.minX=t.minXn?t.maxX:n,this.maxY=t.maxY>i?t.maxY:i},t.prototype.addBoundsMask=function(t,e){var r=t.minX>e.minX?t.minX:e.minX,n=t.minY>e.minY?t.minY:e.minY,i=t.maxXu?i:u,this.maxY=o>h?o:h}},t.prototype.addBoundsArea=function(t,e){var r=t.minX>e.x?t.minX:e.x,n=t.minY>e.y?t.minY:e.y,i=t.maxXu?i:u,this.maxY=o>h?o:h}},t}();r.default=o},{"../math":68}],46:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r1)for(var r=0;rthis.children.length)throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length);return t.parent&&t.parent.removeChild(t),t.parent=this,t.transform._parentID=-1,this.children.splice(e,0,t),this._boundsID++,this.onChildrenChange(e),t.emit("added",this),t},e.prototype.swapChildren=function(t,e){if(t!==e){var r=this.getChildIndex(t),n=this.getChildIndex(e);this.children[r]=e,this.children[n]=t,this.onChildrenChange(r=this.children.length)throw new Error("The supplied index is out of bounds");var r=this.getChildIndex(t);(0,u.removeItems)(this.children,r,1),this.children.splice(e,0,t),this.onChildrenChange(e)},e.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Index ("+t+") does not exist.");return this.children[t]},e.prototype.removeChild=function(t){var e=arguments.length;if(e>1)for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=t,n="number"==typeof e?e:this.children.length,i=n-r,o=void 0;if(i>0&&i<=n){o=this.children.splice(r,i);for(var s=0;s2&&void 0!==arguments[2]&&arguments[2];return r||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)},e.prototype.toLocal=function(t,e,r,n){return e&&(t=e.toGlobal(t,r,n)),n||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,r)},e.prototype.renderWebGL=function(t){},e.prototype.renderCanvas=function(t){},e.prototype.setParent=function(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t},e.prototype.setTransform=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0,u=arguments.length>8&&void 0!==arguments[8]?arguments[8]:0;return this.position.x=t,this.position.y=e,this.scale.x=r?r:1,this.scale.y=n?n:1,this.rotation=i,this.skew.x=o,this.skew.y=s,this.pivot.x=a,this.pivot.y=u,this},e.prototype.destroy=function(){this.removeAllListeners(),this.parent&&this.parent.removeChild(this),this.transform=null,this.parent=null,this._bounds=null,this._currentBounds=null,this._mask=null,this.filterArea=null,this.interactive=!1,this.interactiveChildren=!1},a(e,[{key:"_tempDisplayObjectParent",get:function(){return null===this.tempDisplayObjectParent&&(this.tempDisplayObjectParent=new e),this.tempDisplayObjectParent}},{key:"x",get:function(){return this.position.x},set:function(t){this.transform.position.x=t}},{key:"y",get:function(){return this.position.y},set:function(t){this.transform.position.y=t}},{key:"worldTransform",get:function(){return this.transform.worldTransform}},{key:"localTransform",get:function(){return this.transform.localTransform}},{key:"position",get:function(){return this.transform.position},set:function(t){this.transform.position.copy(t)}},{key:"scale",get:function(){return this.transform.scale},set:function(t){this.transform.scale.copy(t)}},{key:"pivot",get:function(){return this.transform.pivot},set:function(t){this.transform.pivot.copy(t)}},{key:"skew",get:function(){return this.transform.skew},set:function(t){this.transform.skew.copy(t)}},{key:"rotation",get:function(){return this.transform.rotation},set:function(t){this.transform.rotation=t}},{key:"worldVisible",get:function(){var t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask&&(this._mask.renderable=!0),this._mask=t,this._mask&&(this._mask.renderable=!1)}},{key:"filters",get:function(){return this._filters&&this._filters.slice()},set:function(t){this._filters=t&&t.slice()}}]),e}(h.default);r.default=b,b.prototype.displayObjectUpdateTransform=b.prototype.updateTransform},{"../const":44,"../math":68,"../settings":99,"./Bounds":45,"./Transform":48,"./TransformStatic":50,eventemitter3:3}],48:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]&&arguments[0];i(this,e);var n=o(this,t.call(this));return n.fillAlpha=1,n.lineWidth=0,n.nativeLines=r,n.lineColor=0,n.graphicsData=[],n.tint=16777215,n._prevTint=16777215,n.blendMode=_.BLEND_MODES.NORMAL,n.currentPath=null,n._webGL={},n.isMask=!1,n.boundsPadding=0,n._localBounds=new x.default,n.dirty=0,n.fastRectDirty=-1,n.clearDirty=0,n.boundsDirty=-1,n.cachedSpriteDirty=!1,n._spriteRect=null,n._fastRect=!1,n}return s(e,t),e.prototype.clone=function t(){var t=new e;t.renderable=this.renderable,t.fillAlpha=this.fillAlpha,t.lineWidth=this.lineWidth,t.lineColor=this.lineColor,t.tint=this.tint,t.blendMode=this.blendMode,t.isMask=this.isMask,t.boundsPadding=this.boundsPadding,t.dirty=0,t.cachedSpriteDirty=this.cachedSpriteDirty;for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;if(this.lineWidth=t,this.lineColor=e,this.lineAlpha=r,this.currentPath)if(this.currentPath.shape.points.length){var n=new g.Polygon(this.currentPath.shape.points.slice(-2));n.closed=!1,this.drawShape(n)}else this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha;return this},e.prototype.moveTo=function(t,e){var r=new g.Polygon([t,e]);return r.closed=!1,this.drawShape(r),this},e.prototype.lineTo=function(t,e){return this.currentPath.shape.points.push(t,e),this.dirty++,this},e.prototype.quadraticCurveTo=function(t,e,r,n){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var i=20,o=this.currentPath.shape.points,s=0,a=0;0===o.length&&this.moveTo(0,0);for(var u=o[o.length-2],h=o[o.length-1],l=1;l<=i;++l){var c=l/i;s=u+(t-u)*c,a=h+(e-h)*c,o.push(s+(t+(r-t)*c-s)*c,a+(e+(n-e)*c-a)*c)}return this.dirty++,this},e.prototype.bezierCurveTo=function(t,e,r,n,i,o){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var s=this.currentPath.shape.points,a=s[s.length-2],u=s[s.length-1];return s.length-=2,(0,w.default)(a,u,t,e,r,n,i,o,s),this.dirty++,this},e.prototype.arcTo=function(t,e,r,n,i){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(t,e):this.moveTo(t,e);var o=this.currentPath.shape.points,s=o[o.length-2],a=o[o.length-1],u=a-e,h=s-t,l=n-e,c=r-t,f=Math.abs(u*c-h*l);if(f<1e-8||0===i)o[o.length-2]===t&&o[o.length-1]===e||o.push(t,e);else{var d=u*u+h*h,p=l*l+c*c,v=u*l+h*c,y=i*Math.sqrt(d)/f,g=i*Math.sqrt(p)/f,m=y*v/d,_=g*v/p,b=y*c+g*h,x=y*l+g*u,T=h*(g+m),w=u*(g+m),E=c*(y+_),S=l*(y+_),O=Math.atan2(w-x,T-b),P=Math.atan2(S-x,E-b);this.arc(b+t,x+e,i,O,P,h*l>c*u)}return this.dirty++,this},e.prototype.arc=function(t,e,r,n,i){var o=arguments.length>5&&void 0!==arguments[5]&&arguments[5];if(n===i)return this;!o&&i<=n?i+=2*Math.PI:o&&n<=i&&(n+=2*Math.PI);var s=i-n,a=40*Math.ceil(Math.abs(s)/(2*Math.PI));if(0===s)return this;var u=t+Math.cos(n)*r,h=e+Math.sin(n)*r,l=this.currentPath?this.currentPath.shape.points:null;l?l[l.length-2]===u&&l[l.length-1]===h||l.push(u,h):(this.moveTo(u,h),l=this.currentPath.shape.points);for(var c=s/(2*a),f=2*c,d=Math.cos(c),p=Math.sin(c),v=a-1,y=v%1/v,g=0;g<=v;++g){var m=g+y*g,_=c+n+f*m,b=Math.cos(_),x=-Math.sin(_);l.push((d*b+p*x)*r+t,(d*-x+p*b)*r+e)}return this.dirty++,this},e.prototype.beginFill=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this.filling=!0,this.fillColor=t,this.fillAlpha=e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},e.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},e.prototype.drawRect=function(t,e,r,n){return this.drawShape(new g.Rectangle(t,e,r,n)),this},e.prototype.drawRoundedRect=function(t,e,r,n,i){return this.drawShape(new g.RoundedRectangle(t,e,r,n,i)),this},e.prototype.drawCircle=function(t,e,r){return this.drawShape(new g.Circle(t,e,r)),this},e.prototype.drawEllipse=function(t,e,r,n){return this.drawShape(new g.Ellipse(t,e,r,n)),this},e.prototype.drawPolygon=function(t){var e=t,r=!0;if(e instanceof g.Polygon&&(r=e.closed,e=e.points),!Array.isArray(e)){e=new Array(arguments.length);for(var n=0;n0)&&(this.lineWidth=0,this.filling=!1,this.boundsDirty=-1,this.dirty++,this.clearDirty++,this.graphicsData.length=0),this.currentPath=null,this._spriteRect=null,this},e.prototype.isFastRect=function(){return 1===this.graphicsData.length&&this.graphicsData[0].shape.type===_.SHAPES.RECT&&!this.graphicsData[0].lineWidth},e.prototype._renderWebGL=function(t){this.dirty!==this.fastRectDirty&&(this.fastRectDirty=this.dirty,this._fastRect=this.isFastRect()),this._fastRect?this._renderSpriteRect(t):(t.setObjectRenderer(t.plugins.graphics),t.plugins.graphics.render(this))},e.prototype._renderSpriteRect=function(t){var r=this.graphicsData[0].shape;if(!this._spriteRect){if(!e._SPRITE_TEXTURE){e._SPRITE_TEXTURE=l.default.create(10,10);var n=document.createElement("canvas");n.width=10,n.height=10;var i=n.getContext("2d");i.fillStyle="white",i.fillRect(0,0,10,10),e._SPRITE_TEXTURE=f.default.fromCanvas(n)}this._spriteRect=new y.default(e._SPRITE_TEXTURE)}if(16777215===this.tint)this._spriteRect.tint=this.graphicsData[0].fillColor;else{var o=C,s=R;(0,m.hex2rgb)(this.graphicsData[0].fillColor,o),(0,m.hex2rgb)(this.tint,s),o[0]*=s[0],o[1]*=s[1],o[2]*=s[2],this._spriteRect.tint=(0,m.rgb2hex)(o)}this._spriteRect.alpha=this.graphicsData[0].fillAlpha,this._spriteRect.worldAlpha=this.worldAlpha*this._spriteRect.alpha,this._spriteRect.blendMode=this.blendMode,e._SPRITE_TEXTURE._frame.width=r.width,e._SPRITE_TEXTURE._frame.height=r.height,this._spriteRect.transform.worldTransform=this.transform.worldTransform,this._spriteRect.anchor.set(-r.x/r.width,-r.y/r.height),this._spriteRect._onAnchorUpdate(),this._spriteRect._renderWebGL(t)},e.prototype._renderCanvas=function(t){this.isMask!==!0&&t.plugins.graphics.render(this)},e.prototype._calculateBounds=function(){this.boundsDirty!==this.dirty&&(this.boundsDirty=this.dirty,this.updateLocalBounds(),this.cachedSpriteDirty=!0);var t=this._localBounds;this._bounds.addFrame(this.transform,t.minX,t.minY,t.maxX,t.maxY)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,M);for(var e=this.graphicsData,r=0;re?o+a:e,r=sn?s+u:n;else if(c===_.SHAPES.CIRC)o=i.x,s=i.y,a=i.radius+f/2,u=i.radius+f/2,t=o-ae?o+a:e,r=s-un?s+u:n;else if(c===_.SHAPES.ELIP)o=i.x,s=i.y,a=i.width+f/2,u=i.height+f/2,t=o-ae?o+a:e,r=s-un?s+u:n;else for(var d=i.points,p=0,v=0,y=0,g=0,m=0,b=0,x=0,T=0,w=0;w+2e?x+m:e,r=T-bn?T+b:n)}else t=0,e=0,r=0,n=0;var E=this.boundsPadding;this._localBounds.minX=t-E,this._localBounds.maxX=e+2*E,this._localBounds.minY=r-E,this._localBounds.maxY=n+2*E},e.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null;var e=new p.default(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,this.nativeLines,t);return this.graphicsData.push(e),e.type===_.SHAPES.POLY&&(e.shape.closed=e.shape.closed||this.filling,this.currentPath=e),this.dirty++,e},e.prototype.generateCanvasTexture=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=this.getLocalBounds(),n=l.default.create(r.width,r.height,t,e);O||(O=new S.default),this.transform.updateLocalTransform(),this.transform.localTransform.copy(P),P.invert(),P.tx-=r.x,P.ty-=r.y,O.render(this,n,!0,P);var i=f.default.fromCanvas(n.baseTexture._canvasRenderTarget.canvas,t);return i.baseTexture.resolution=e,i.baseTexture.update(),i},e.prototype.closePath=function(){var t=this.currentPath;return t&&t.shape&&t.shape.close(),this},e.prototype.addHole=function(){var t=this.graphicsData.pop();return this.currentPath=this.graphicsData[this.graphicsData.length-1],this.currentPath.addHole(t.shape),this.currentPath=null,this},e.prototype.destroy=function(e){t.prototype.destroy.call(this,e);for(var r=0;rC?C:M,r.beginPath(),r.moveTo(E,S+M),r.lineTo(E,S+P-M),r.quadraticCurveTo(E,S+P,E+M,S+P),r.lineTo(E+O-M,S+P),r.quadraticCurveTo(E+O,S+P,E+O,S+P-M),r.lineTo(E+O,S+M),r.quadraticCurveTo(E+O,S,E+O-M,S),r.lineTo(E+M,S),r.quadraticCurveTo(E,S,E,S+M),r.closePath(),(u.fillColor||0===u.fillColor)&&(r.globalAlpha=u.fillAlpha*n,r.fillStyle="#"+("00000"+(0|l).toString(16)).substr(-6),r.fill()),u.lineWidth&&(r.globalAlpha=u.lineAlpha*n,r.strokeStyle="#"+("00000"+(0|c).toString(16)).substr(-6),r.stroke())}}},t.prototype.updateGraphicsTint=function(t){t._prevTint=t.tint;for(var e=(t.tint>>16&255)/255,r=(t.tint>>8&255)/255,n=(255&t.tint)/255,i=0;i>16&255)/255*e*255<<16)+((s>>8&255)/255*r*255<<8)+(255&s)/255*n*255,o._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*r*255<<8)+(255&a)/255*n*255}},t.prototype.renderPolygon=function(t,e,r){r.moveTo(t[0],t[1]);for(var n=1;n8&&void 0!==arguments[8]?arguments[8]:[],h=20,l=0,c=0,f=0,d=0,p=0;u.push(t,e);for(var v=1,y=0;v<=h;++v)y=v/h,l=1-y,c=l*l,f=c*l,d=y*y,p=d*y,u.push(f*t+3*c*y*r+3*l*d*i+p*s,f*e+3*c*y*n+3*l*d*o+p*a);return u}r.__esModule=!0,r.default=n},{}],55:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../utils"),u=t("../../const"),h=t("../../renderers/webgl/utils/ObjectRenderer"),l=n(h),c=t("../../renderers/webgl/WebGLRenderer"),f=n(c),d=t("./WebGLGraphicsData"),p=n(d),v=t("./shaders/PrimitiveShader"),y=n(v),g=t("./utils/buildPoly"),m=n(g),_=t("./utils/buildRectangle"),b=n(_),x=t("./utils/buildRoundedRectangle"),T=n(x),w=t("./utils/buildCircle"),E=n(w),S=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.graphicsDataPool=[],n.primitiveShader=null,n.gl=r.gl,n.CONTEXT_UID=0,n}return s(e,t),e.prototype.onContextChange=function(){this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.primitiveShader=new y.default(this.gl)},e.prototype.destroy=function(){l.default.prototype.destroy.call(this);for(var t=0;t32e4)&&(r=this.graphicsDataPool.pop()||new p.default(this.renderer.gl,this.primitiveShader,this.renderer.state.attribsState),r.reset(e),t.data.push(r)),r.dirty=!0,r},e}(l.default);r.default=S,f.default.registerPlugin("graphics",S)},{"../../const":44,"../../renderers/webgl/WebGLRenderer":82,"../../renderers/webgl/utils/ObjectRenderer":92,"../../utils":120,"./WebGLGraphicsData":56,"./shaders/PrimitiveShader":57,"./utils/buildCircle":58,"./utils/buildPoly":60,"./utils/buildRectangle":61,"./utils/buildRoundedRectangle":62}],56:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("pixi-gl-core"),s=n(o),a=function(){function t(e,r,n){i(this,t),this.gl=e,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=s.default.GLBuffer.createVertexBuffer(e),this.indexBuffer=s.default.GLBuffer.createIndexBuffer(e),this.dirty=!0,this.glPoints=null,this.glIndices=null,this.shader=r,this.vao=new s.default.VertexArrayObject(e,n).addIndex(this.indexBuffer).addAttribute(this.buffer,r.attributes.aVertexPosition,e.FLOAT,!1,24,0).addAttribute(this.buffer,r.attributes.aColor,e.FLOAT,!1,24,8)}return t.prototype.reset=function(){this.points.length=0,this.indices.length=0},t.prototype.upload=function(){this.glPoints=new Float32Array(this.points),this.buffer.upload(this.glPoints),this.glIndices=new Uint16Array(this.indices),this.indexBuffer.upload(this.glIndices),this.dirty=!1},t.prototype.destroy=function(){this.color=null,this.points=null,this.indices=null,this.vao.destroy(),this.buffer.destroy(),this.indexBuffer.destroy(),this.gl=null,this.buffer=null,this.indexBuffer=null,this.glPoints=null,this.glIndices=null},t}();r.default=a},{"pixi-gl-core":12}],57:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../../Shader"),u=n(a),h=function(t){function e(r){return i(this,e),o(this,t.call(this,r,["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","uniform float alpha;","uniform vec3 tint;","varying vec4 vColor;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"].join("\n"),["varying vec4 vColor;","void main(void){"," gl_FragColor = vColor;","}"].join("\n")))}return s(e,t),e}(u.default);r.default=h},{"../../../Shader":42}],58:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,o=void 0,h=void 0;if(t.type===a.SHAPES.CIRC?(o=r.radius,h=r.radius):(o=r.width,h=r.height),0!==o&&0!==h){var l=Math.floor(30*Math.sqrt(r.radius))||Math.floor(15*Math.sqrt(r.width+r.height)),c=2*Math.PI/l;if(t.fill){var f=(0,u.hex2rgb)(t.fillColor),d=t.fillAlpha,p=f[0]*d,v=f[1]*d,y=f[2]*d,g=e.points,m=e.indices,_=g.length/6;m.push(_);for(var b=0;b196*p*p?(R=O-M,A=P-C,I=Math.sqrt(R*R+A*A),R/=I,A/=I,R*=p,A*=p,h.push(T-R,w-A),h.push(g,m,_,y),h.push(T+R,w+A),h.push(g,m,_,y),h.push(T-R,w-A),h.push(g,m,_,y),f++):(h.push(X,G),h.push(g,m,_,y),h.push(T-(X-T),w-(G-w)),h.push(g,m,_,y))}}b=r[2*(c-2)],x=r[2*(c-2)+1],T=r[2*(c-1)],w=r[2*(c-1)+1],O=-(x-w),P=b-T,I=Math.sqrt(O*O+P*P),O/=I,P/=I,O*=p,P*=p,h.push(T-O,w-P),h.push(g,m,_,y),h.push(T+O,w+P),h.push(g,m,_,y),l.push(d);for(var H=0;H=6){for(var n=[],i=t.holes,o=0;o0&&(0,s.default)(t,e)}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils"),u=t("earcut"),h=n(u)},{"../../../utils":120,"./buildLine":59,earcut:2}],61:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,o=r.width,u=r.height;if(t.fill){var h=(0,a.hex2rgb)(t.fillColor),l=t.fillAlpha,c=h[0]*l,f=h[1]*l,d=h[2]*l,p=e.points,v=e.indices,y=p.length/6;p.push(n,i),p.push(c,f,d,l),p.push(n+o,i),p.push(c,f,d,l),p.push(n,i+u),p.push(c,f,d,l),p.push(n+o,i+u),p.push(c,f,d,l),v.push(y,y,y+1,y+2,y+3,y+3)}if(t.lineWidth){var g=t.points;t.points=[n,i,n+o,i,n+o,i+u,n,i+u,n,i],(0,s.default)(t,e),t.points=g}}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils")},{"../../../utils":120,"./buildLine":59}],62:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,o=r.width,a=r.height,h=r.radius,f=[];if(f.push(n,i+h),s(n,i+a-h,n,i+a,n+h,i+a,f),s(n+o-h,i+a,n+o,i+a,n+o,i+a-h,f),s(n+o,i+h,n+o,i,n+o-h,i,f),s(n+h,i,n,i,n,i+h+1e-10,f),t.fill){for(var d=(0,c.hex2rgb)(t.fillColor),p=t.fillAlpha,v=d[0]*p,y=d[1]*p,g=d[2]*p,m=e.points,_=e.indices,b=m.length/6,x=(0,u.default)(f,null,2),T=0,w=x.length;T6&&void 0!==arguments[6]?arguments[6]:[],u=20,h=a,l=0,c=0,f=0,d=0,p=0,v=0,y=0,g=0;y<=u;++y)g=y/u,l=o(t,r,g),c=o(e,n,g),f=o(r,i,g),d=o(n,s,g),p=o(l,f,g),v=o(c,d,g),h.push(p,v);return h}r.__esModule=!0,r.default=i;var a=t("earcut"),u=n(a),h=t("./buildLine"),l=n(h),c=t("../../../utils")},{"../../../utils":120,"./buildLine":59,earcut:2}],63:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.autoDetectRenderer=r.Application=r.Filter=r.SpriteMaskFilter=r.Quad=r.RenderTarget=r.ObjectRenderer=r.WebGLManager=r.Shader=r.CanvasRenderTarget=r.TextureUvs=r.VideoBaseTexture=r.BaseRenderTexture=r.RenderTexture=r.BaseTexture=r.Texture=r.Spritesheet=r.CanvasGraphicsRenderer=r.GraphicsRenderer=r.GraphicsData=r.Graphics=r.TextStyle=r.Text=r.SpriteRenderer=r.CanvasTinter=r.CanvasSpriteRenderer=r.Sprite=r.TransformBase=r.TransformStatic=r.Transform=r.Container=r.DisplayObject=r.Bounds=r.glCore=r.WebGLRenderer=r.CanvasRenderer=r.ticker=r.utils=r.settings=void 0;var o=t("./const");Object.keys(o).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return o[t]}})});var s=t("./math");Object.keys(s).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return s[t]}})});var a=t("pixi-gl-core");Object.defineProperty(r,"glCore",{enumerable:!0,get:function(){return i(a).default}});var u=t("./display/Bounds");Object.defineProperty(r,"Bounds",{enumerable:!0,get:function(){return i(u).default}});var h=t("./display/DisplayObject");Object.defineProperty(r,"DisplayObject",{enumerable:!0,get:function(){return i(h).default}});var l=t("./display/Container");Object.defineProperty(r,"Container",{enumerable:!0,get:function(){return i(l).default}});var c=t("./display/Transform");Object.defineProperty(r,"Transform",{enumerable:!0,get:function(){return i(c).default}});var f=t("./display/TransformStatic");Object.defineProperty(r,"TransformStatic",{enumerable:!0,get:function(){return i(f).default}});var d=t("./display/TransformBase");Object.defineProperty(r,"TransformBase",{enumerable:!0,get:function(){return i(d).default}});var p=t("./sprites/Sprite");Object.defineProperty(r,"Sprite",{enumerable:!0,get:function(){return i(p).default}});var v=t("./sprites/canvas/CanvasSpriteRenderer");Object.defineProperty(r,"CanvasSpriteRenderer",{enumerable:!0,get:function(){return i(v).default}});var y=t("./sprites/canvas/CanvasTinter");Object.defineProperty(r,"CanvasTinter",{enumerable:!0,get:function(){return i(y).default}});var g=t("./sprites/webgl/SpriteRenderer"); +Object.defineProperty(r,"SpriteRenderer",{enumerable:!0,get:function(){return i(g).default}});var m=t("./text/Text");Object.defineProperty(r,"Text",{enumerable:!0,get:function(){return i(m).default}});var _=t("./text/TextStyle");Object.defineProperty(r,"TextStyle",{enumerable:!0,get:function(){return i(_).default}});var b=t("./graphics/Graphics");Object.defineProperty(r,"Graphics",{enumerable:!0,get:function(){return i(b).default}});var x=t("./graphics/GraphicsData");Object.defineProperty(r,"GraphicsData",{enumerable:!0,get:function(){return i(x).default}});var T=t("./graphics/webgl/GraphicsRenderer");Object.defineProperty(r,"GraphicsRenderer",{enumerable:!0,get:function(){return i(T).default}});var w=t("./graphics/canvas/CanvasGraphicsRenderer");Object.defineProperty(r,"CanvasGraphicsRenderer",{enumerable:!0,get:function(){return i(w).default}});var E=t("./textures/Spritesheet");Object.defineProperty(r,"Spritesheet",{enumerable:!0,get:function(){return i(E).default}});var S=t("./textures/Texture");Object.defineProperty(r,"Texture",{enumerable:!0,get:function(){return i(S).default}});var O=t("./textures/BaseTexture");Object.defineProperty(r,"BaseTexture",{enumerable:!0,get:function(){return i(O).default}});var P=t("./textures/RenderTexture");Object.defineProperty(r,"RenderTexture",{enumerable:!0,get:function(){return i(P).default}});var M=t("./textures/BaseRenderTexture");Object.defineProperty(r,"BaseRenderTexture",{enumerable:!0,get:function(){return i(M).default}});var C=t("./textures/VideoBaseTexture");Object.defineProperty(r,"VideoBaseTexture",{enumerable:!0,get:function(){return i(C).default}});var R=t("./textures/TextureUvs");Object.defineProperty(r,"TextureUvs",{enumerable:!0,get:function(){return i(R).default}});var A=t("./renderers/canvas/utils/CanvasRenderTarget");Object.defineProperty(r,"CanvasRenderTarget",{enumerable:!0,get:function(){return i(A).default}});var I=t("./Shader");Object.defineProperty(r,"Shader",{enumerable:!0,get:function(){return i(I).default}});var D=t("./renderers/webgl/managers/WebGLManager");Object.defineProperty(r,"WebGLManager",{enumerable:!0,get:function(){return i(D).default}});var L=t("./renderers/webgl/utils/ObjectRenderer");Object.defineProperty(r,"ObjectRenderer",{enumerable:!0,get:function(){return i(L).default}});var F=t("./renderers/webgl/utils/RenderTarget");Object.defineProperty(r,"RenderTarget",{enumerable:!0,get:function(){return i(F).default}});var N=t("./renderers/webgl/utils/Quad");Object.defineProperty(r,"Quad",{enumerable:!0,get:function(){return i(N).default}});var B=t("./renderers/webgl/filters/spriteMask/SpriteMaskFilter");Object.defineProperty(r,"SpriteMaskFilter",{enumerable:!0,get:function(){return i(B).default}});var j=t("./renderers/webgl/filters/Filter");Object.defineProperty(r,"Filter",{enumerable:!0,get:function(){return i(j).default}});var k=t("./Application");Object.defineProperty(r,"Application",{enumerable:!0,get:function(){return i(k).default}});var U=t("./autoDetectRenderer");Object.defineProperty(r,"autoDetectRenderer",{enumerable:!0,get:function(){return U.autoDetectRenderer}});var X=t("./utils"),G=n(X),W=t("./ticker"),H=n(W),V=t("./settings"),Y=i(V),z=t("./renderers/canvas/CanvasRenderer"),q=i(z),K=t("./renderers/webgl/WebGLRenderer"),Z=i(K);r.settings=Y.default,r.utils=G,r.ticker=H,r.CanvasRenderer=q.default,r.WebGLRenderer=Z.default},{"./Application":41,"./Shader":42,"./autoDetectRenderer":43,"./const":44,"./display/Bounds":45,"./display/Container":46,"./display/DisplayObject":47,"./display/Transform":48,"./display/TransformBase":49,"./display/TransformStatic":50,"./graphics/Graphics":51,"./graphics/GraphicsData":52,"./graphics/canvas/CanvasGraphicsRenderer":53,"./graphics/webgl/GraphicsRenderer":55,"./math":68,"./renderers/canvas/CanvasRenderer":75,"./renderers/canvas/utils/CanvasRenderTarget":77,"./renderers/webgl/WebGLRenderer":82,"./renderers/webgl/filters/Filter":84,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":87,"./renderers/webgl/managers/WebGLManager":91,"./renderers/webgl/utils/ObjectRenderer":92,"./renderers/webgl/utils/Quad":93,"./renderers/webgl/utils/RenderTarget":94,"./settings":99,"./sprites/Sprite":100,"./sprites/canvas/CanvasSpriteRenderer":101,"./sprites/canvas/CanvasTinter":102,"./sprites/webgl/SpriteRenderer":104,"./text/Text":106,"./text/TextStyle":107,"./textures/BaseRenderTexture":108,"./textures/BaseTexture":109,"./textures/RenderTexture":110,"./textures/Spritesheet":111,"./textures/Texture":112,"./textures/TextureUvs":113,"./textures/VideoBaseTexture":114,"./ticker":116,"./utils":120,"pixi-gl-core":12}],64:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){return t<0?-1:t>0?1:0}function o(){for(var t=0;t<16;t++){var e=[];d.push(e);for(var r=0;r<16;r++)for(var n=i(u[t]*u[r]+l[t]*h[r]),o=i(h[t]*u[r]+c[t]*h[r]),s=i(u[t]*l[r]+l[t]*c[r]),p=i(h[t]*l[r]+c[t]*c[r]),v=0;v<16;v++)if(u[v]===n&&h[v]===o&&l[v]===s&&c[v]===p){e.push(v);break}}for(var y=0;y<16;y++){var g=new a.default;g.set(u[y],h[y],l[y],c[y],0,0),f.push(g)}}r.__esModule=!0;var s=t("./Matrix"),a=n(s),u=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],h=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],l=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],c=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],f=[],d=[];o();var p={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MIRROR_HORIZONTAL:12,uX:function(t){return u[t]},uY:function(t){return h[t]},vX:function(t){return l[t]},vY:function(t){return c[t]},inv:function(t){return 8&t?15&t:7&-t},add:function(t,e){return d[t][e]},sub:function(t,e){return d[t][p.inv(e)]},rotate180:function(t){return 4^t},isSwapWidthHeight:function(t){return 2===(3&t)},byDirection:function(t,e){return 2*Math.abs(t)<=Math.abs(e)?e>=0?p.S:p.N:2*Math.abs(e)<=Math.abs(t)?t>0?p.E:p.W:e>0?t>0?p.SE:p.SW:t>0?p.NE:p.NW},matrixAppendRotationInv:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=f[p.inv(e)];i.tx=r,i.ty=n,t.append(i)}};r.default=p},{"./Matrix":65}],65:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:1,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;i(this,t),this.a=e,this.b=r,this.c=n,this.d=o,this.tx=s,this.ty=a,this.array=null}return t.prototype.fromArray=function(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]},t.prototype.set=function(t,e,r,n,i,o){return this.a=t,this.b=e,this.c=r,this.d=n,this.tx=i,this.ty=o,this},t.prototype.toArray=function(t,e){this.array||(this.array=new Float32Array(9));var r=e||this.array;return t?(r[0]=this.a,r[1]=this.b,r[2]=0,r[3]=this.c,r[4]=this.d,r[5]=0,r[6]=this.tx,r[7]=this.ty,r[8]=1):(r[0]=this.a,r[1]=this.c,r[2]=this.tx,r[3]=this.b,r[4]=this.d,r[5]=this.ty,r[6]=0,r[7]=0,r[8]=1),r},t.prototype.apply=function(t,e){e=e||new a.default;var r=t.x,n=t.y;return e.x=this.a*r+this.c*n+this.tx,e.y=this.b*r+this.d*n+this.ty,e},t.prototype.applyInverse=function(t,e){e=e||new a.default;var r=1/(this.a*this.d+this.c*-this.b),n=t.x,i=t.y;return e.x=this.d*r*n+-this.c*r*i+(this.ty*this.c-this.tx*this.d)*r,e.y=this.a*r*i+-this.b*r*n+(-this.ty*this.a+this.tx*this.b)*r,e},t.prototype.translate=function(t,e){return this.tx+=t,this.ty+=e,this},t.prototype.scale=function(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this},t.prototype.rotate=function(t){var e=Math.cos(t),r=Math.sin(t),n=this.a,i=this.c,o=this.tx;return this.a=n*e-this.b*r,this.b=n*r+this.b*e,this.c=i*e-this.d*r,this.d=i*r+this.d*e,this.tx=o*e-this.ty*r,this.ty=o*r+this.ty*e,this},t.prototype.append=function(t){var e=this.a,r=this.b,n=this.c,i=this.d;return this.a=t.a*e+t.b*n,this.b=t.a*r+t.b*i,this.c=t.c*e+t.d*n,this.d=t.c*r+t.d*i,this.tx=t.tx*e+t.ty*n+this.tx,this.ty=t.tx*r+t.ty*i+this.ty,this},t.prototype.setTransform=function(t,e,r,n,i,o,s,a,u){var h=Math.sin(s),l=Math.cos(s),c=Math.cos(u),f=Math.sin(u),d=-Math.sin(a),p=Math.cos(a),v=l*i,y=h*i,g=-h*o,m=l*o;return this.a=c*v+f*g,this.b=c*y+f*m,this.c=d*v+p*g,this.d=d*y+p*m,this.tx=t+(r*v+n*g),this.ty=e+(r*y+n*m),this},t.prototype.prepend=function(t){var e=this.tx;if(1!==t.a||0!==t.b||0!==t.c||1!==t.d){var r=this.a,n=this.c;this.a=r*t.a+this.b*t.c,this.b=r*t.b+this.b*t.d,this.c=n*t.a+this.d*t.c,this.d=n*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this},t.prototype.decompose=function(t){var e=this.a,r=this.b,n=this.c,i=this.d,o=-Math.atan2(-n,i),s=Math.atan2(r,e),a=Math.abs(o+s);return a<1e-5?(t.rotation=s,e<0&&i>=0&&(t.rotation+=t.rotation<=0?Math.PI:-Math.PI),t.skew.x=t.skew.y=0):(t.skew.x=o,t.skew.y=s),t.scale.x=Math.sqrt(e*e+r*r),t.scale.y=Math.sqrt(n*n+i*i),t.position.x=this.tx,t.position.y=this.ty,t},t.prototype.invert=function(){var t=this.a,e=this.b,r=this.c,n=this.d,i=this.tx,o=t*n-e*r;return this.a=n/o,this.b=-e/o,this.c=-r/o,this.d=t/o,this.tx=(r*this.ty-n*i)/o,this.ty=-(t*this.ty-e*i)/o,this},t.prototype.identity=function(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this},t.prototype.clone=function(){var e=new t;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e},t.prototype.copy=function(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t},o(t,null,[{key:"IDENTITY",get:function(){return new t}},{key:"TEMP_MATRIX",get:function(){return new t}}]),t}();r.default=u},{"./Point":67}],66:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this._x=i,this._y=o,this.cb=e,this.scope=r}return t.prototype.set=function(t,e){var r=t||0,n=e||(0!==e?r:0);this._x===r&&this._y===n||(this._x=r,this._y=n,this.cb.call(this.scope))},t.prototype.copy=function(t){this._x===t.x&&this._y===t.y||(this._x=t.x,this._y=t.y,this.cb.call(this.scope))},i(t,[{key:"x",get:function(){return this._x},set:function(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}},{key:"y",get:function(){return this._y},set:function(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}]),t}();r.default=o},{}],67:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;n(this,t),this.x=e,this.y=r}return t.prototype.clone=function(){return new t(this.x,this.y)},t.prototype.copy=function(t){this.set(t.x,t.y)},t.prototype.equals=function(t){return t.x===this.x&&t.y===this.y},t.prototype.set=function(t,e){this.x=t||0,this.y=e||(0!==e?this.x:0)},t}();r.default=i},{}],68:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./Point");Object.defineProperty(r,"Point",{enumerable:!0,get:function(){return n(i).default}});var o=t("./ObservablePoint");Object.defineProperty(r,"ObservablePoint",{enumerable:!0,get:function(){return n(o).default}});var s=t("./Matrix");Object.defineProperty(r,"Matrix",{enumerable:!0,get:function(){return n(s).default}});var a=t("./GroupD8");Object.defineProperty(r,"GroupD8",{enumerable:!0,get:function(){return n(a).default}});var u=t("./shapes/Circle");Object.defineProperty(r,"Circle",{enumerable:!0,get:function(){return n(u).default}});var h=t("./shapes/Ellipse");Object.defineProperty(r,"Ellipse",{enumerable:!0,get:function(){return n(h).default}});var l=t("./shapes/Polygon");Object.defineProperty(r,"Polygon",{enumerable:!0,get:function(){return n(l).default}});var c=t("./shapes/Rectangle");Object.defineProperty(r,"Rectangle",{enumerable:!0,get:function(){return n(c).default}});var f=t("./shapes/RoundedRectangle");Object.defineProperty(r,"RoundedRectangle",{enumerable:!0,get:function(){return n(f).default}})},{"./GroupD8":64,"./Matrix":65,"./ObservablePoint":66,"./Point":67,"./shapes/Circle":69,"./shapes/Ellipse":70,"./shapes/Polygon":71,"./shapes/Rectangle":72,"./shapes/RoundedRectangle":73}],69:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./Rectangle"),s=n(o),a=t("../../const"),u=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;i(this,t),this.x=e,this.y=r,this.radius=n,this.type=a.SHAPES.CIRC}return t.prototype.clone=function(){return new t(this.x,this.y,this.radius)},t.prototype.contains=function(t,e){if(this.radius<=0)return!1;var r=this.radius*this.radius,n=this.x-t,i=this.y-e;return n*=n,i*=i,n+i<=r},t.prototype.getBounds=function(){return new s.default(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)},t}();r.default=u},{"../../const":44,"./Rectangle":72}],70:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./Rectangle"),s=n(o),a=t("../../const"),u=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;i(this,t),this.x=e,this.y=r,this.width=n,this.height=o,this.type=a.SHAPES.ELIP}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;var r=(t-this.x)/this.width,n=(e-this.y)/this.height;return r*=r,n*=n,r+n<=1},t.prototype.getBounds=function(){return new s.default(this.x-this.width,this.y-this.height,this.width,this.height)},t}();r.default=u},{"../../const":44,"./Rectangle":72}],71:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../Point"),s=n(o),a=t("../../const"),u=function(){function t(){for(var e=arguments.length,r=Array(e),n=0;ne!=h>e&&t<(u-s)*((e-a)/(h-a))+s;l&&(r=!r)}return r},t}();r.default=u},{"../../const":44,"../Point":67}],72:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this.x=e,this.y=r,this.width=i,this.height=s,this.type=o.SHAPES.RECT}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this},t.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t=this.y&&et.x+t.width&&(this.width=t.width-this.x,this.width<0&&(this.width=0)),this.y+this.height>t.y+t.height&&(this.height=t.height-this.y,this.height<0&&(this.height=0))},t.prototype.enlarge=function(t){var e=Math.min(this.x,t.x),r=Math.max(this.x+this.width,t.x+t.width),n=Math.min(this.y,t.y),i=Math.max(this.y+this.height,t.y+t.height);this.x=e,this.width=r-e,this.y=n,this.height=i-n},i(t,[{key:"left",get:function(){return this.x}},{key:"right",get:function(){return this.x+this.width}},{key:"top",get:function(){return this.y}},{key:"bottom",get:function(){return this.y+this.height}}],[{key:"EMPTY",get:function(){return new t(0,0,0,0)}}]),t}();r.default=s},{"../../const":44}],73:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:20;n(this,t),this.x=e,this.y=r,this.width=o,this.height=s,this.radius=a,this.type=i.SHAPES.RREC}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height,this.radius)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){if(e>=this.y+this.radius&&e<=this.y+this.height-this.radius||t>=this.x+this.radius&&t<=this.x+this.width-this.radius)return!0;var r=t-(this.x+this.radius),n=e-(this.y+this.radius),i=this.radius*this.radius;if(r*r+n*n<=i)return!0;if(r=t-(this.x+this.width-this.radius),r*r+n*n<=i)return!0;if(n=e-(this.y+this.height-this.radius),r*r+n*n<=i)return!0;if(r=t-(this.x+this.radius),r*r+n*n<=i)return!0}return!1},t}();r.default=o},{"../../const":44}],74:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:{};i(this,e);var a=o(this,t.call(this,"Canvas",r,n,s));return a.type=y.RENDERER_TYPE.CANVAS,a.rootContext=a.view.getContext("2d",{alpha:a.transparent}),a.refresh=!0,a.maskManager=new l.default(a),a.smoothProperty="imageSmoothingEnabled",a.rootContext.imageSmoothingEnabled||(a.rootContext.webkitImageSmoothingEnabled?a.smoothProperty="webkitImageSmoothingEnabled":a.rootContext.mozImageSmoothingEnabled?a.smoothProperty="mozImageSmoothingEnabled":a.rootContext.oImageSmoothingEnabled?a.smoothProperty="oImageSmoothingEnabled":a.rootContext.msImageSmoothingEnabled&&(a.smoothProperty="msImageSmoothingEnabled")),a.initPlugins(),a.blendModes=(0,p.default)(),a._activeBlendMode=null,a.context=null,a.renderingToScreen=!1,a.resize(r,n),a}return s(e,t),e.prototype.render=function(t,e,r,n,i){if(this.view){this.renderingToScreen=!e,this.emit("prerender");var o=this.resolution;e?(e=e.baseTexture||e,e._canvasRenderTarget||(e._canvasRenderTarget=new f.default(e.width,e.height,e.resolution),e.source=e._canvasRenderTarget.canvas,e.valid=!0),this.context=e._canvasRenderTarget.context,this.resolution=e._canvasRenderTarget.resolution):this.context=this.rootContext;var s=this.context;if(e||(this._lastObjectRendered=t),!i){var a=t.parent,u=this._tempDisplayObjectParent.transform.worldTransform;n?(n.copy(u),this._tempDisplayObjectParent.transform._worldID=-1):u.identity(),t.parent=this._tempDisplayObjectParent,t.updateTransform(),t.parent=a}s.setTransform(1,0,0,1,0,0),s.globalAlpha=1,s.globalCompositeOperation=this.blendModes[y.BLEND_MODES.NORMAL],navigator.isCocoonJS&&this.view.screencanvas&&(s.fillStyle="black",s.clear()),(void 0!==r?r:this.clearBeforeRender)&&this.renderingToScreen&&(this.transparent?s.clearRect(0,0,this.width,this.height):(s.fillStyle=this._backgroundColorString,s.fillRect(0,0,this.width,this.height)));var h=this.context;this.context=s,t.renderCanvas(this),this.context=h,this.resolution=o,this.emit("postrender")}},e.prototype.clear=function(t){var e=this.context;t=t||this._backgroundColorString,!this.transparent&&t?(e.fillStyle=t,e.fillRect(0,0,this.width,this.height)):e.clearRect(0,0,this.width,this.height)},e.prototype.setBlendMode=function(t){this._activeBlendMode!==t&&(this._activeBlendMode=t,this.context.globalCompositeOperation=this.blendModes[t])},e.prototype.destroy=function(e){this.destroyPlugins(),t.prototype.destroy.call(this,e),this.context=null,this.refresh=!0,this.maskManager.destroy(),this.maskManager=null,this.smoothProperty=null},e.prototype.resize=function(e,r){t.prototype.resize.call(this,e,r),this.smoothProperty&&(this.rootContext[this.smoothProperty]=m.default.SCALE_MODE===y.SCALE_MODES.LINEAR)},e}(u.default);r.default=_,v.pluginTarget.mixin(_)},{"../../const":44,"../../settings":99,"../../utils":120,"../SystemRenderer":74,"./utils/CanvasMaskManager":76,"./utils/CanvasRenderTarget":77,"./utils/mapCanvasBlendModesToPixi":79}],76:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../../const"),o=function(){function t(e){n(this,t),this.renderer=e}return t.prototype.pushMask=function(t){var e=this.renderer;e.context.save();var r=t.alpha,n=t.transform.worldTransform,i=e.resolution;e.context.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t._texture||(this.renderGraphicsShape(t),e.context.clip()),t.worldAlpha=r},t.prototype.renderGraphicsShape=function(t){var e=this.renderer.context,r=t.graphicsData.length;if(0!==r){e.beginPath();for(var n=0;nS?S:E,e.moveTo(b,x+E),e.lineTo(b,x+w-E),e.quadraticCurveTo(b,x+w,b+E,x+w),e.lineTo(b+T-E,x+w),e.quadraticCurveTo(b+T,x+w,b+T,x+w-E),e.lineTo(b+T,x+E),e.quadraticCurveTo(b+T,x,b+T-E,x),e.lineTo(b+E,x),e.quadraticCurveTo(b,x,b,x+E),e.closePath()}}}},t.prototype.popMask=function(t){t.context.restore()},t.prototype.destroy=function(){},t}();r.default=o},{"../../../const":44}],77:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:[];return(0,a.default)()?(t[o.BLEND_MODES.NORMAL]="source-over",t[o.BLEND_MODES.ADD]="lighter",t[o.BLEND_MODES.MULTIPLY]="multiply",t[o.BLEND_MODES.SCREEN]="screen",t[o.BLEND_MODES.OVERLAY]="overlay",t[o.BLEND_MODES.DARKEN]="darken",t[o.BLEND_MODES.LIGHTEN]="lighten",t[o.BLEND_MODES.COLOR_DODGE]="color-dodge",t[o.BLEND_MODES.COLOR_BURN]="color-burn",t[o.BLEND_MODES.HARD_LIGHT]="hard-light",t[o.BLEND_MODES.SOFT_LIGHT]="soft-light",t[o.BLEND_MODES.DIFFERENCE]="difference",t[o.BLEND_MODES.EXCLUSION]="exclusion",t[o.BLEND_MODES.HUE]="hue",t[o.BLEND_MODES.SATURATION]="saturate",t[o.BLEND_MODES.COLOR]="color",t[o.BLEND_MODES.LUMINOSITY]="luminosity"):(t[o.BLEND_MODES.NORMAL]="source-over",t[o.BLEND_MODES.ADD]="lighter",t[o.BLEND_MODES.MULTIPLY]="source-over",t[o.BLEND_MODES.SCREEN]="source-over",t[o.BLEND_MODES.OVERLAY]="source-over",t[o.BLEND_MODES.DARKEN]="source-over",t[o.BLEND_MODES.LIGHTEN]="source-over",t[o.BLEND_MODES.COLOR_DODGE]="source-over",t[o.BLEND_MODES.COLOR_BURN]="source-over",t[o.BLEND_MODES.HARD_LIGHT]="source-over",t[o.BLEND_MODES.SOFT_LIGHT]="source-over",t[o.BLEND_MODES.DIFFERENCE]="source-over",t[o.BLEND_MODES.EXCLUSION]="source-over",t[o.BLEND_MODES.HUE]="source-over",t[o.BLEND_MODES.SATURATION]="source-over",t[o.BLEND_MODES.COLOR]="source-over",t[o.BLEND_MODES.LUMINOSITY]="source-over"),t}r.__esModule=!0,r.default=i;var o=t("../../../const"),s=t("./canUseNewCanvasBlendModes"),a=n(s)},{"../../../const":44,"./canUseNewCanvasBlendModes":78}],80:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../const"),s=t("../../settings"),a=n(s),u=function(){ +function t(e){i(this,t),this.renderer=e,this.count=0,this.checkCount=0,this.maxIdle=a.default.GC_MAX_IDLE,this.checkCountMax=a.default.GC_MAX_CHECK_COUNT,this.mode=a.default.GC_MODE}return t.prototype.update=function(){this.count++,this.mode!==o.GC_MODES.MANUAL&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run()))},t.prototype.run=function(){for(var t=this.renderer.textureManager,e=t._managedTextures,r=!1,n=0;nthis.maxIdle&&(t.destroyTexture(i,!0),e[n]=null,r=!0)}if(r){for(var o=0,s=0;s=0;r--)this.unload(t.children[r])},t}();r.default=u},{"../../const":44,"../../settings":99}],81:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("pixi-gl-core"),s=t("../../const"),a=t("./utils/RenderTarget"),u=n(a),h=t("../../utils"),l=function(){function t(e){i(this,t),this.renderer=e,this.gl=e.gl,this._managedTextures=[]}return t.prototype.bindTexture=function(){},t.prototype.getTexture=function(){},t.prototype.updateTexture=function(t,e){var r=this.gl,n=!!t._glRenderTargets;if(!t.hasLoaded)return null;var i=this.renderer.boundTextures;if(void 0===e){e=0;for(var a=0;a2&&void 0!==arguments[2]?arguments[2]:{};i(this,e);var a=o(this,t.call(this,"WebGL",r,n,s));return a.legacy=!!s.legacy,a.legacy&&(D.default.VertexArrayObject.FORCE_NATIVE=!0),a.type=L.RENDERER_TYPE.WEBGL,a.handleContextLost=a.handleContextLost.bind(a),a.handleContextRestored=a.handleContextRestored.bind(a),a.view.addEventListener("webglcontextlost",a.handleContextLost,!1),a.view.addEventListener("webglcontextrestored",a.handleContextRestored,!1),a._contextOptions={alpha:a.transparent,antialias:s.antialias,premultipliedAlpha:a.transparent&&"notMultiplied"!==a.transparent,stencil:!0,preserveDrawingBuffer:s.preserveDrawingBuffer},a._backgroundColorRgba[3]=a.transparent?0:1,a.maskManager=new l.default(a),a.stencilManager=new f.default(a),a.emptyRenderer=new m.default(a),a.currentRenderer=a.emptyRenderer,a.initPlugins(),s.context&&(0,R.default)(s.context),a.gl=s.context||D.default.createContext(a.view,a._contextOptions),a.CONTEXT_UID=F++,a.state=new O.default(a.gl),a.renderingToScreen=!0,a.boundTextures=null,a._activeShader=null,a._activeVao=null,a._activeRenderTarget=null,a._initContext(),a.filterManager=new p.default(a),a.drawModes=(0,M.default)(a.gl),a._nextTextureLocation=0,a.setBlendMode(0),a}return s(e,t),e.prototype._initContext=function(){var t=this.gl;t.isContextLost()&&t.getExtension("WEBGL_lose_context")&&t.getExtension("WEBGL_lose_context").restoreContext();var e=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);this.boundTextures=new Array(e),this.emptyTextures=new Array(e),this.textureManager=new b.default(this),this.textureGC=new E.default(this),this.state.resetToDefault(),this.rootRenderTarget=new y.default(t,this.width,this.height,null,this.resolution,(!0)),this.rootRenderTarget.clearColor=this._backgroundColorRgba,this.bindRenderTarget(this.rootRenderTarget);var r=new D.default.GLTexture.fromData(t,null,1,1),n={_glTextures:{}};n._glTextures[this.CONTEXT_UID]={};for(var i=0;i 0.5)"," {"," color = vec4(1.0, 0.0, 0.0, 1.0);"," }"," else"," {"," color = vec4(0.0, 1.0, 0.0, 1.0);"," }"," gl_FragColor = mix(sample, masky, 0.5);"," gl_FragColor *= sample.a;","}"].join("\n")}}]),t}();r.default=d},{"../../../const":44,"../../../settings":99,"../../../utils":120,"./extractUniformsFromSrc":85}],85:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e,r){var n=o(t,r),i=o(e,r);return Object.assign(n,i)}function o(t){for(var e=new RegExp("^(projectionMatrix|uSampler|filterArea)$"),r={},n=void 0,i=t.replace(/\s+/g," ").split(/\s*;\s*/),o=0;o-1){var a=s.split(" "),h=a[1],l=a[2],c=1;l.indexOf("[")>-1&&(n=l.split(/\[|]/),l=n[0],c*=Number(n[1])),l.match(e)||(r[l]={value:u(h,c),name:l,type:h})}}return r}r.__esModule=!0,r.default=i;var s=t("pixi-gl-core"),a=n(s),u=a.default.shader.defaultValue},{"pixi-gl-core":12}],86:[function(t,e,r){"use strict";function n(t,e,r){var n=t.identity();return n.translate(e.x/r.width,e.y/r.height),n.scale(r.width,r.height),n}function i(t,e,r){var n=t.identity();n.translate(e.x/r.width,e.y/r.height);var i=r.width/e.width,o=r.height/e.height;return n.scale(i,o),n}function o(t,e,r,n){var i=n.worldTransform.copy(s.Matrix.TEMP_MATRIX),o=n._texture.baseTexture,a=t.identity(),u=r.height/r.width;a.translate(e.x/r.width,e.y/r.height),a.scale(1,u);var h=r.width/o.width,l=r.height/o.height;return i.tx/=o.width*h,i.ty/=o.width*h,i.invert(),a.prepend(i),a.scale(1,1/u),a.scale(h,l),a.translate(n.anchor.x,n.anchor.y),a}r.__esModule=!0,r.calculateScreenSpaceMatrix=n,r.calculateNormalizedScreenSpaceMatrix=i,r.calculateSpriteMatrix=o;var s=t("../../../math")},{"../../../math":68}],87:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../Filter"),u=n(a),h=t("../../../../math"),l=(t("path"),function(t){function e(r){i(this,e);var n=new h.Matrix,s=o(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n","varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n"));return r.renderable=!1,s.maskSprite=r,s.maskMatrix=n,s}return s(e,t),e.prototype.apply=function(t,e,r){var n=this.maskSprite;this.uniforms.mask=n._texture,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,n),this.uniforms.alpha=n.worldAlpha,t.applyFilter(this,e,r)},e}(u.default));r.default=l},{"../../../../math":68,"../Filter":84,path:22}],88:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var u=t("./WebGLManager"),h=i(u),l=t("../utils/RenderTarget"),c=i(l),f=t("../utils/Quad"),d=i(f),p=t("../../../math"),v=t("../../../Shader"),y=i(v),g=t("../filters/filterTransforms"),m=n(g),_=t("bit-twiddle"),b=i(_),x=function t(){a(this,t),this.renderTarget=null,this.sourceFrame=new p.Rectangle,this.destinationFrame=new p.Rectangle,this.filters=[],this.target=null,this.resolution=1},T=function(t){function e(r){a(this,e);var n=o(this,t.call(this,r));return n.gl=n.renderer.gl,n.quad=new d.default(n.gl,r.state.attribState),n.shaderCache={},n.pool={},n.filterData=null,n}return s(e,t),e.prototype.pushFilter=function(t,e){var r=this.renderer,n=this.filterData;if(!n){n=this.renderer._activeRenderTarget.filterStack;var i=new x;i.sourceFrame=i.destinationFrame=this.renderer._activeRenderTarget.size,i.renderTarget=r._activeRenderTarget,this.renderer._activeRenderTarget.filterData=n={index:0,stack:[i]},this.filterData=n}var o=n.stack[++n.index];o||(o=n.stack[n.index]=new x);var s=e[0].resolution,a=0|e[0].padding,u=t.filterArea||t.getBounds(!0),h=o.sourceFrame,l=o.destinationFrame;h.x=(u.x*s|0)/s,h.y=(u.y*s|0)/s,h.width=(u.width*s|0)/s,h.height=(u.height*s|0)/s,n.stack[0].renderTarget.transform||h.fit(n.stack[0].destinationFrame),h.pad(a),l.width=h.width,l.height=h.height;var c=this.getPotRenderTarget(r.gl,h.width,h.height,s);o.target=t,o.filters=e,o.resolution=s,o.renderTarget=c,c.setFrame(l,h),r.bindRenderTarget(c),c.clear()},e.prototype.popFilter=function(){var t=this.filterData,e=t.stack[t.index-1],r=t.stack[t.index];this.quad.map(r.renderTarget.size,r.sourceFrame).upload();var n=r.filters;if(1===n.length)n[0].apply(this,r.renderTarget,e.renderTarget,!1),this.freePotRenderTarget(r.renderTarget);else{var i=r.renderTarget,o=this.getPotRenderTarget(this.renderer.gl,r.sourceFrame.width,r.sourceFrame.height,r.resolution);o.setFrame(r.destinationFrame,r.sourceFrame),o.clear();var s=0;for(s=0;s0&&(e+="\nelse "),r1&&void 0!==arguments[1]?arguments[1]:[];return e[i.BLEND_MODES.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.ADD]=[t.ONE,t.DST_ALPHA],e[i.BLEND_MODES.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SCREEN]=[t.ONE,t.ONE_MINUS_SRC_COLOR],e[i.BLEND_MODES.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":44}],97:[function(t,e,r){"use strict";function n(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e[i.DRAW_MODES.POINTS]=t.POINTS,e[i.DRAW_MODES.LINES]=t.LINES,e[i.DRAW_MODES.LINE_LOOP]=t.LINE_LOOP,e[i.DRAW_MODES.LINE_STRIP]=t.LINE_STRIP,e[i.DRAW_MODES.TRIANGLES]=t.TRIANGLES,e[i.DRAW_MODES.TRIANGLE_STRIP]=t.TRIANGLE_STRIP,e[i.DRAW_MODES.TRIANGLE_FAN]=t.TRIANGLE_FAN,e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":44}],98:[function(t,e,r){"use strict";function n(t){var e=t.getContextAttributes();e.stencil||console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly")}r.__esModule=!0,r.default=n},{}],99:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./utils/maxRecommendedTextures"),o=n(i),s=t("./utils/canUploadSameBuffer"),a=n(s);r.default={TARGET_FPMS:.06,MIPMAP_TEXTURES:!0,RESOLUTION:1,FILTER_RESOLUTION:1,SPRITE_MAX_TEXTURES:(0,o.default)(32),SPRITE_BATCH_SIZE:4096,RETINA_PREFIX:/@(.+)x/,RENDER_OPTIONS:{view:null,antialias:!1,forceFXAA:!1,autoResize:!1,transparent:!1,backgroundColor:0,clearBeforeRender:!0,preserveDrawingBuffer:!1,roundPixels:!1},TRANSFORM_MODE:0,GC_MODE:0,GC_MAX_IDLE:3600,GC_MAX_CHECK_COUNT:600,WRAP_MODE:0,SCALE_MODE:0,PRECISION:"mediump",CAN_UPLOAD_SAME_BUFFER:(0,a.default)()}},{"./utils/canUploadSameBuffer":117,"./utils/maxRecommendedTextures":121}],100:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rn&&v.xi&&v.y>16)+(65280&t)+((255&t)<<16)}},{key:"texture",get:function(){return this._texture},set:function(t){this._texture!==t&&(this._texture=t,this.cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,t&&(t.baseTexture.hasLoaded?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}]),e}(p.default);r.default=y},{"../const":44,"../display/Container":46,"../math":68,"../textures/Texture":112,"../utils":120}],101:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../renderers/canvas/CanvasRenderer"),s=n(o),a=t("../../const"),u=t("../../math"),h=t("./CanvasTinter"),l=n(h),c=new u.Matrix,f=function(){function t(e){i(this,t),this.renderer=e}return t.prototype.render=function(t){var e=t._texture,r=this.renderer,n=e._frame.width,i=e._frame.height,o=t.transform.worldTransform,s=0,h=0;if(!(e.orig.width<=0||e.orig.height<=0)&&e.baseTexture.source&&(r.setBlendMode(t.blendMode),e.valid)){r.context.globalAlpha=t.worldAlpha;var f=e.baseTexture.scaleMode===a.SCALE_MODES.LINEAR;r.smoothProperty&&r.context[r.smoothProperty]!==f&&(r.context[r.smoothProperty]=f),e.trim?(s=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,h=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(s=(.5-t.anchor.x)*e.orig.width,h=(.5-t.anchor.y)*e.orig.height),e.rotate&&(o.copy(c),o=c,u.GroupD8.matrixAppendRotationInv(o,e.rotate,s,h),s=0,h=0),s-=n/2,h-=i/2,r.roundPixels?(r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution|0,o.ty*r.resolution|0),s=0|s,h=0|h):r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution,o.ty*r.resolution);var d=e.baseTexture.resolution;16777215!==t.tint?(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=l.default.getTintedTexture(t,t.tint)),r.context.drawImage(t.tintedTexture,0,0,n*d,i*d,s*r.resolution,h*r.resolution,n*r.resolution,i*r.resolution)):r.context.drawImage(e.baseTexture.source,e._frame.x*d,e._frame.y*d,n*d,i*d,s*r.resolution,h*r.resolution,n*r.resolution,i*r.resolution)}},t.prototype.destroy=function(){this.renderer=null},t}();r.default=f,s.default.registerPlugin("sprite",f)},{"../../const":44,"../../math":68,"../../renderers/canvas/CanvasRenderer":75,"./CanvasTinter":102}],102:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("../../utils"),o=t("../../renderers/canvas/utils/canUseNewCanvasBlendModes"),s=n(o),a={getTintedTexture:function(t,e){var r=t.texture;e=a.roundColor(e);var n="#"+("00000"+(0|e).toString(16)).substr(-6);if(r.tintCache=r.tintCache||{},r.tintCache[n])return r.tintCache[n];var i=a.canvas||document.createElement("canvas");if(a.tintMethod(r,e,i),a.convertTintToImage){var o=new Image;o.src=i.toDataURL(),r.tintCache[n]=o}else r.tintCache[n]=i,a.canvas=null;return i},tintWithMultiply:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=i.width,r.height=i.height,n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="multiply",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},tintWithOverlay:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=i.width,r.height=i.height,n.globalCompositeOperation="copy",n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},tintWithPerPixel:function(t,e,r){var n=r.getContext("2d"),o=t._frame.clone(),s=t.baseTexture.resolution;o.x*=s,o.y*=s,o.width*=s,o.height*=s,r.width=o.width,r.height=o.height,n.globalCompositeOperation="copy",n.drawImage(t.baseTexture.source,o.x,o.y,o.width,o.height,0,0,o.width,o.height);for(var a=(0,i.hex2rgb)(e),u=a[0],h=a[1],l=a[2],c=n.getImageData(0,0,o.width,o.height),f=c.data,d=0;d=this.size&&this.flush(),t._texture._uvs&&(this.sprites[this.currentIndex++]=t)},e.prototype.flush=function(){if(0!==this.currentIndex){var t=this.renderer.gl,e=this.MAX_TEXTURES,r=E.default.nextPow2(this.currentIndex),n=E.default.log2(r),i=this.buffers[n],o=this.sprites,s=this.groups,a=i.float32View,u=i.uint32View,h=this.boundTextures,l=this.renderer.boundTextures,c=this.renderer.textureGC.count,f=0,d=void 0,p=void 0,v=1,y=0,g=s[0],m=void 0,_=void 0,x=o[0].blendMode;g.textureCount=0,g.start=0,g.blend=x,S++;var w=void 0;for(w=0;w0&&(e+="\nelse "),r0?this.context.shadowColor=r.dropShadowColor:this.context.fillStyle=r.dropShadowColor;for(var v=Math.cos(r.dropShadowAngle)*r.dropShadowDistance,y=Math.sin(r.dropShadowAngle)*r.dropShadowDistance,g=0;g3&&void 0!==arguments[3]&&arguments[3],i=this._style,o=i.letterSpacing;if(0===o)return void(n?this.context.strokeText(t,e,r):this.context.fillText(t,e,r));for(var s=String.prototype.split.call(t,""),a=e,u=0,h="";ui)for(var l=a[u].split(""),c=0;cs?(e+="\n"+l[c],s=i-f):(0===c&&(e+=" "),e+=l[c],s-=f)}else{var d=h+this.context.measureText(" ").width;0===u||d>s?(u>0&&(e+="\n"),e+=a[u],s=i-h):(s-=d,e+=" "+a[u])}}o=0;n--){var i=r[n].trim();/([\"\'])[^\'\"]+\1/.test(i)||(i='"'+i+'"'),r[n]=i}return t.fontStyle+" "+t.fontVariant+" "+t.fontWeight+" "+e+" "+r.join(",")},e.calculateFontProperties=function(t){if(e.fontPropertiesCache[t])return e.fontPropertiesCache[t];var r={},n=e.fontPropertiesCanvas,i=e.fontPropertiesContext;i.font=t;var o=Math.ceil(i.measureText("|MÉq").width),s=Math.ceil(i.measureText("M").width),a=2*s;s=1.4*s|0,n.width=o,n.height=a,i.fillStyle="#f00",i.fillRect(0,0,o,a),i.font=t,i.textBaseline="alphabetic",i.fillStyle="#000",i.fillText("|MÉq",0,s);var u=i.getImageData(0,0,o,a).data,h=u.length,l=4*o,c=0,f=0,d=!1;for(c=0;cs;--c){for(var v=0;v0&&void 0!==arguments[0]?arguments[0]:100,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,s=arguments[2],a=arguments[3];i(this,e);var u=o(this,t.call(this,null,s));return u.resolution=a||l.default.RESOLUTION,u.width=r,u.height=n,u.realWidth=u.width*u.resolution,u.realHeight=u.height*u.resolution,u.scaleMode=void 0!==s?s:l.default.SCALE_MODE,u.hasLoaded=!0,u._glRenderTargets={},u._canvasRenderTarget=null,u.valid=!1,u}return s(e,t),e.prototype.resize=function(t,e){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.realWidth=this.width*this.resolution,this.realHeight=this.height*this.resolution,this.valid&&this.emit("update",this))},e.prototype.destroy=function(){t.prototype.destroy.call(this,!0),this.renderer=null},e}(u.default);r.default=c},{"../settings":99,"./BaseTexture":109}],109:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u=t("../utils"),h=t("../settings"),l=n(h),c=t("eventemitter3"),f=n(c),d=t("../utils/determineCrossOrigin"),p=n(d),v=t("bit-twiddle"),y=n(v),g=function(t){function e(r,n,s){i(this,e);var a=o(this,t.call(this));return a.uid=(0,u.uid)(),a.touched=0,a.resolution=s||l.default.RESOLUTION,a.width=100,a.height=100,a.realWidth=100,a.realHeight=100,a.scaleMode=void 0!==n?n:l.default.SCALE_MODE,a.hasLoaded=!1,a.isLoading=!1,a.source=null,a.origSource=null,a.imageType=null,a.sourceScale=1,a.premultipliedAlpha=!0,a.imageUrl=null,a.isPowerOfTwo=!1,a.mipmap=l.default.MIPMAP_TEXTURES,a.wrapMode=l.default.WRAP_MODE,a._glTextures={},a._enabled=0,a._virtalBoundId=-1,r&&a.loadSource(r),a}return s(e,t),e.prototype.update=function(){"svg"!==this.imageType&&(this.realWidth=this.source.naturalWidth||this.source.videoWidth||this.source.width,this.realHeight=this.source.naturalHeight||this.source.videoHeight||this.source.height,this._updateDimensions()),this.emit("update",this)},e.prototype._updateDimensions=function(){this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=y.default.isPow2(this.realWidth)&&y.default.isPow2(this.realHeight)},e.prototype.loadSource=function(t){var e=this,r=this.isLoading;this.hasLoaded=!1,this.isLoading=!1,r&&this.source&&(this.source.onload=null,this.source.onerror=null);var n=!this.source;if(this.source=t,(t.src&&t.complete||t.getContext)&&t.width&&t.height)this._updateImageType(),"svg"===this.imageType?this._loadSvgSource():this._sourceLoaded(),n&&this.emit("loaded",this);else if(!t.getContext){var i=function(){e.isLoading=!0;var n=e;if(t.onload=function(){if(n._updateImageType(),t.onload=null,t.onerror=null,n.isLoading)return n.isLoading=!1,n._sourceLoaded(),"svg"===n.imageType?void n._loadSvgSource():void n.emit("loaded",n)},t.onerror=function(){t.onload=null,t.onerror=null,n.isLoading&&(n.isLoading=!1,n.emit("error",n))},t.complete&&t.src){if(t.onload=null,t.onerror=null,"svg"===n.imageType)return n._loadSvgSource(),{v:void 0};e.isLoading=!1,t.width&&t.height?(e._sourceLoaded(),r&&e.emit("loaded",e)):r&&e.emit("error",e)}}();if("object"===("undefined"==typeof i?"undefined":a(i)))return i.v}},e.prototype._updateImageType=function(){if(this.imageUrl){var t=(0,u.decomposeDataUri)(this.imageUrl),e=void 0;if(t&&"image"===t.mediaType){var r=t.subType.split("+")[0];if(e=(0,u.getUrlFileExtension)("."+r),!e)throw new Error("Invalid image type in data URI.")}else e=(0,u.getUrlFileExtension)(this.imageUrl),e||(e="png");this.imageType=e}},e.prototype._loadSvgSource=function(){if("svg"===this.imageType){var t=(0,u.decomposeDataUri)(this.imageUrl);t?this._loadSvgSourceUsingDataUri(t):this._loadSvgSourceUsingXhr()}},e.prototype._loadSvgSourceUsingDataUri=function(t){var e=void 0;if("base64"===t.encoding){if(!atob)throw new Error("Your browser doesn't support base64 conversions.");e=atob(t.data)}else e=t.data;this._loadSvgSourceUsingString(e)},e.prototype._loadSvgSourceUsingXhr=function(){var t=this,e=new XMLHttpRequest;e.onload=function(){if(e.readyState!==e.DONE||200!==e.status)throw new Error("Failed to load SVG using XHR.");t._loadSvgSourceUsingString(e.response)},e.onerror=function(){return t.emit("error",t)},e.open("GET",this.imageUrl,!0),e.send()},e.prototype._loadSvgSourceUsingString=function(t){var e=(0,u.getSvgSize)(t),r=e.width,n=e.height;if(!r||!n)throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them.");this.realWidth=Math.round(r*this.sourceScale),this.realHeight=Math.round(n*this.sourceScale),this._updateDimensions();var i=document.createElement("canvas");i.width=this.realWidth,i.height=this.realHeight,i._pixiId="canvas_"+(0,u.uid)(),i.getContext("2d").drawImage(this.source,0,0,r,n,0,0,this.realWidth,this.realHeight),this.origSource=this.source,this.source=i,u.BaseTextureCache[i._pixiId]=this,this.isLoading=!1,this._sourceLoaded(),this.emit("loaded",this)},e.prototype._sourceLoaded=function(){this.hasLoaded=!0,this.update()},e.prototype.destroy=function(){this.imageUrl&&(delete u.BaseTextureCache[this.imageUrl],delete u.TextureCache[this.imageUrl],this.imageUrl=null,navigator.isCocoonJS||(this.source.src="")),this.source&&this.source._pixiId&&delete u.BaseTextureCache[this.source._pixiId],this.source=null,this.dispose()},e.prototype.dispose=function(){this.emit("dispose",this)},e.prototype.updateSourceImage=function(t){this.source.src=t,this.loadSource(this.source)},e.fromImage=function(t,r,n,i){var o=u.BaseTextureCache[t];if(!o){var s=new Image;void 0===r&&0!==t.indexOf("data:")&&(s.crossOrigin=(0,p.default)(t)),o=new e(s,n),o.imageUrl=t,i&&(o.sourceScale=i),o.resolution=(0,u.getResolutionOfUrl)(t),s.src=t,u.BaseTextureCache[t]=o}return o},e.fromCanvas=function(t,r){t._pixiId||(t._pixiId="canvas_"+(0,u.uid)());var n=u.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),u.BaseTextureCache[t._pixiId]=n),n},e.from=function(t,r,n){if("string"==typeof t)return e.fromImage(t,void 0,r,n);if(t instanceof HTMLImageElement){var i=t.src,o=u.BaseTextureCache[i];return o||(o=new e(t,r),o.imageUrl=i,n&&(o.sourceScale=n),o.resolution=(0,u.getResolutionOfUrl)(i),u.BaseTextureCache[i]=o),o}return t instanceof HTMLCanvasElement?e.fromCanvas(t,r):t},e}(f.default);r.default=g},{"../settings":99,"../utils":120,"../utils/determineCrossOrigin":119,"bit-twiddle":1,eventemitter3:3}],110:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("./BaseRenderTexture"),u=n(a),h=t("./Texture"),l=n(h),c=function(t){function e(r,n){i(this,e);var s=null;if(!(r instanceof u.default)){var a=arguments[1],h=arguments[2],l=arguments[3],c=arguments[4];console.warn("Please use RenderTexture.create("+a+", "+h+") instead of the ctor directly."),s=arguments[0],n=null,r=new u.default(a,h,l,c)}var f=o(this,t.call(this,r,n));return f.legacyRenderer=s,f.valid=!0,f._updateUvs(),f}return s(e,t),e.prototype.resize=function(t,e,r){this.valid=t>0&&e>0,this._frame.width=this.orig.width=t,this._frame.height=this.orig.height=e,r||this.baseTexture.resize(t,e),this._updateUvs()},e.create=function(t,r,n,i){return new e(new u.default(t,r,n,i))},e}(l.default);r.default=c},{"./BaseRenderTexture":108,"./Texture":112}],111:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:null;n(this,t),this.baseTexture=e,this.textures={},this.data=r,this.resolution=this._updateResolution(i||this.baseTexture.imageUrl),this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}return i(t,null,[{key:"BATCH_SIZE",get:function(){return 1e3}}]),t.prototype._updateResolution=function(t){var e=this.data.meta.scale,r=(0,s.getResolutionOfUrl)(t,null);return null===r&&(r=void 0!==e?parseFloat(e):1),1!==r&&(this.baseTexture.resolution=r,this.baseTexture.update()),r},t.prototype.parse=function(e){this._batchIndex=0,this._callback=e,this._frameKeys.length<=t.BATCH_SIZE?(this._processFrames(0),this._parseComplete()):this._nextBatch()},t.prototype._processFrames=function(e){for(var r=e,n=t.BATCH_SIZE;r-e0&&void 0!==arguments[0]&&arguments[0];for(var e in this.textures)this.textures[e].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,t&&this.baseTexture.destroy(),this.baseTexture=null},t}();r.default=a},{"../":63,"../utils":120}],112:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rthis.baseTexture.width||t.y+t.height>this.baseTexture.height)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions: "+("X: "+t.x+" + "+t.width+" > "+this.baseTexture.width+" ")+("Y: "+t.y+" + "+t.height+" > "+this.baseTexture.height));this.valid=t&&t.width&&t.height&&this.baseTexture.hasLoaded,this.trim||this.rotate||(this.orig=t),this.valid&&this._updateUvs()}},{key:"rotate",get:function(){return this._rotate},set:function(t){this._rotate=t,this.valid&&this._updateUvs()}},{key:"width",get:function(){return this.orig.width}},{key:"height",get:function(){return this.orig.height}}]),e}(v.default);r.default=m,m.EMPTY=new m(new h.default),m.EMPTY.destroy=function(){},m.EMPTY.on=function(){},m.EMPTY.once=function(){},m.EMPTY.emit=function(){}},{"../math":68,"../utils":120,"./BaseTexture":109,"./TextureUvs":113,"./VideoBaseTexture":114,eventemitter3:3}],113:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../math/GroupD8"),s=n(o),a=function(){function t(){i(this,t),this.x0=0,this.y0=0,this.x1=1,this.y1=0,this.x2=1,this.y2=1,this.x3=0,this.y3=1,this.uvsUint32=new Uint32Array(4)}return t.prototype.set=function(t,e,r){var n=e.width,i=e.height;if(r){var o=t.width/2/n,a=t.height/2/i,u=t.x/n+o,h=t.y/i+a;r=s.default.add(r,s.default.NW),this.x0=u+o*s.default.uX(r),this.y0=h+a*s.default.uY(r),r=s.default.add(r,2),this.x1=u+o*s.default.uX(r),this.y1=h+a*s.default.uY(r),r=s.default.add(r,2),this.x2=u+o*s.default.uX(r),this.y2=h+a*s.default.uY(r),r=s.default.add(r,2),this.x3=u+o*s.default.uX(r),this.y3=h+a*s.default.uY(r)}else this.x0=t.x/n,this.y0=t.y/i,this.x1=(t.x+t.width)/n,this.y1=t.y/i,this.x2=(t.x+t.width)/n,this.y2=(t.y+t.height)/i,this.x3=t.x/n,this.y3=(t.y+t.height)/i;this.uvsUint32[0]=(65535*this.y0&65535)<<16|65535*this.x0&65535,this.uvsUint32[1]=(65535*this.y1&65535)<<16|65535*this.x1&65535,this.uvsUint32[2]=(65535*this.y2&65535)<<16|65535*this.x2&65535,this.uvsUint32[3]=(65535*this.y3&65535)<<16|65535*this.x3&65535},t}();r.default=a},{"../math/GroupD8":64}],114:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function u(t,e){e||(e="video/"+t.substr(t.lastIndexOf(".")+1));var r=document.createElement("source");return r.src=t,r.type=e,r}r.__esModule=!0;var h=function(){function t(t,e){for(var r=0;r0&&t.paused===!1&&t.ended===!1&&t.readyState>2},e.prototype._isSourceReady=function(){return 3===this.source.readyState||4===this.source.readyState},e.prototype._onPlayStart=function(){this.hasLoaded||this._onCanPlay(),!this._isAutoUpdating&&this.autoUpdate&&(p.shared.add(this.update,this),this._isAutoUpdating=!0)},e.prototype._onPlayStop=function(){this._isAutoUpdating&&(p.shared.remove(this.update,this),this._isAutoUpdating=!1)},e.prototype._onCanPlay=function(){ +this.hasLoaded=!0,this.source&&(this.source.removeEventListener("canplay",this._onCanPlay),this.source.removeEventListener("canplaythrough",this._onCanPlay),this.width=this.source.videoWidth,this.height=this.source.videoHeight,this.__loaded||(this.__loaded=!0,this.emit("loaded",this)),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.source.play())},e.prototype.destroy=function(){this._isAutoUpdating&&p.shared.remove(this.update,this),this.source&&this.source._pixiId&&(delete f.BaseTextureCache[this.source._pixiId],delete this.source._pixiId),t.prototype.destroy.call(this)},e.fromVideo=function(t,r){t._pixiId||(t._pixiId="video_"+(0,f.uid)());var n=f.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),f.BaseTextureCache[t._pixiId]=n),n},e.fromUrl=function(t,r){var n=document.createElement("video");if(n.setAttribute("webkit-playsinline",""),n.setAttribute("playsinline",""),Array.isArray(t))for(var i=0;i0&&void 0!==arguments[0]?arguments[0]:performance.now(),e=void 0;t>this.lastTime?(e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),this.deltaTime=e*a.default.TARGET_FPMS*this.speed,this._emitter.emit(l,this.deltaTime)):this.deltaTime=this.elapsedMS=0,this.lastTime=t},o(t,[{key:"FPS",get:function(){return 1e3/this.elapsedMS}},{key:"minFPS",get:function(){return 1e3/this._maxElapsedMS},set:function(t){var e=Math.min(Math.max(0,t)/1e3,a.default.TARGET_FPMS);this._maxElapsedMS=1/e}}]),t}();r.default=c},{"../settings":99,eventemitter3:3}],116:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.Ticker=r.shared=void 0;var i=t("./Ticker"),o=n(i),s=new o.default;s.autoStart=!0,r.shared=s,r.Ticker=o.default},{"./Ticker":115}],117:[function(t,e,r){"use strict";function n(){var t=!!navigator.platform&&/iPad|iPhone|iPod/.test(navigator.platform);return!t}r.__esModule=!0,r.default=n},{}],118:[function(t,e,r){"use strict";function n(t){for(var e=6*t,r=new Uint16Array(e),n=0,i=0;n1&&void 0!==arguments[1]?arguments[1]:window.location;if(0===t.indexOf("data:"))return"";e=e||window.location,a||(a=document.createElement("a")),a.href=t,t=s.default.parse(a.href);var r=!t.port&&""===e.port||t.port===e.port;return t.hostname===e.hostname&&r&&t.protocol===e.protocol?"":"anonymous"}r.__esModule=!0,r.default=i;var o=t("url"),s=n(o),a=void 0},{url:28}],120:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(){return++C}function s(t,e){return e=e||[],e[0]=(t>>16&255)/255,e[1]=(t>>8&255)/255,e[2]=(255&t)/255,e}function a(t){return t=t.toString(16),t="000000".substr(0,6-t.length)+t,"#"+t}function u(t){return(255*t[0]<<16)+(255*t[1]<<8)+(255*t[2]|0)}function h(t,e){var r=b.default.RETINA_PREFIX.exec(t);return r?parseFloat(r[1]):void 0!==e?e:1}function l(t){var e=m.DATA_URI.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,encoding:e[3]?e[3].toLowerCase():void 0,data:e[4]}}function c(t){var e=m.URL_FILE_EXTENSION.exec(t);if(e)return e[1].toLowerCase()}function f(t){var e=m.SVG_SIZE.exec(t),r={};return e&&(r[e[1]]=Math.round(parseFloat(e[3])),r[e[5]]=Math.round(parseFloat(e[7]))),r}function d(){R=!0}function p(t){if(!R){if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var e=["\n %c %c %c Pixi.js "+m.VERSION+" - ✰ "+t+" ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n","background: #ff66a5; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff66a5; background: #030307; padding:5px 0;","background: #ff66a5; padding:5px 0;","background: #ffc3dc; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;"];window.console.log.apply(console,e)}else window.console&&window.console.log("Pixi.js "+m.VERSION+" - "+t+" - http://www.pixijs.com/");R=!0}}function v(){var t={stencil:!0,failIfMajorPerformanceCaveat:!0};try{if(!window.WebGLRenderingContext)return!1;var e=document.createElement("canvas"),r=e.getContext("webgl",t)||e.getContext("experimental-webgl",t),n=!(!r||!r.getContextAttributes().stencil);if(r){var i=r.getExtension("WEBGL_lose_context");i&&i.loseContext()}return r=null,n}catch(t){return!1}}function y(t){return 0===t?0:t<0?-1:1}function g(t,e,r){var n=t.length;if(!(e>=n||0===r)){r=e+r>n?n-e:r;for(var i=n-r,o=e;o1?this._fontStyle="italic":t.indexOf("oblique")>-1?this._fontStyle="oblique":this._fontStyle="normal",t.indexOf("small-caps")>-1?this._fontVariant="small-caps":this._fontVariant="normal";var e=t.split(" "),r=-1;this._fontSize=26;for(var n=0;n-1&&r=this._durations[this.currentFrame];)n-=this._durations[this.currentFrame]*i,this._currentTime+=i;this._currentTime+=n/this._durations[this.currentFrame]}else this._currentTime+=e;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):r!==this.currentFrame&&this.updateTexture()},e.prototype.updateTexture=function(){this._texture=this._textures[this.currentFrame],this._textureID=-1,this.onFrameChange&&this.onFrameChange(this.currentFrame)},e.prototype.destroy=function(){this.stop(),t.prototype.destroy.call(this)},e.fromFrames=function(t){for(var r=[],n=0;n1&&void 0!==arguments[1]?arguments[1]:{};o(this,e);var i=s(this,t.call(this));return i._textWidth=0,i._textHeight=0,i._glyphs=[],i._font={tint:void 0!==n.tint?n.tint:16777215,align:n.align||"left",name:null,size:0},i.font=n.font,i._text=r,i.maxWidth=0,i.maxLineHeight=0,i._anchor=new f.default(function(){ +i.dirty=!0},i,0,0),i.dirty=!1,i.updateText(),i}return a(e,t),e.prototype.updateText=function(){for(var t=e.fonts[this._font.name],r=this._font.size/t.size,n=new l.Point,i=[],o=[],s=null,a=0,u=0,h=0,c=-1,f=0,d=0,p=0;p0&&n.x*r>this.maxWidth)l.utils.removeItems(i,c,p-c),p=c,c=-1,o.push(f),u=Math.max(u,f),h++,n.x=0,n.y+=t.lineHeight,s=null;else{var y=t.chars[v];y&&(s&&y.kerning[s]&&(n.x+=y.kerning[s]),i.push({texture:y.texture,line:h,charCode:v,position:new l.Point(n.x+y.xOffset,n.y+y.yOffset)}),a=n.x+(y.texture.width+y.xOffset),n.x+=y.xAdvance,d=Math.max(d,y.yOffset+y.texture.height),s=v)}}o.push(a),u=Math.max(u,a);for(var g=[],m=0;m<=h;m++){var _=0;"right"===this._font.align?_=u-o[m]:"center"===this._font.align&&(_=(u-o[m])/2),g.push(_)}for(var b=i.length,x=this.tint,T=0;T=0?t:16777215,this.dirty=!0}},{key:"align",get:function(){return this._font.align},set:function(t){this._font.align=t||"left",this.dirty=!0}},{key:"anchor",get:function(){return this._anchor},set:function(t){"number"==typeof t?this._anchor.set(t):this._anchor.copy(t)}},{key:"font",get:function(){return this._font},set:function(t){t&&("string"==typeof t?(t=t.split(" "),this._font.name=1===t.length?t[0]:t.slice(1).join(" "),this._font.size=t.length>=2?parseInt(t[0],10):e.fonts[this._font.name].size):(this._font.name=t.name,this._font.size="number"==typeof t.size?t.size:parseInt(t.size,10)),this.dirty=!0)}},{key:"text",get:function(){return this._text},set:function(t){t=t.toString()||" ",this._text!==t&&(this._text=t,this.dirty=!0)}},{key:"textWidth",get:function(){return this.validate(),this._textWidth}},{key:"textHeight",get:function(){return this.validate(),this._textHeight}}]),e}(l.Container);r.default=d,d.fonts={}},{"../core":63,"../core/math/ObservablePoint":66}],131:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:100,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:100;o(this,e);var a=s(this,t.call(this,r));return a.tileTransform=new l.TransformStatic,a._width=n,a._height=i,a._canvasPattern=null,a.uvTransform=r.transform||new p.default(r),a.pluginName="tilingSprite",a.uvRespectAnchor=!1,a}return a(e,t),e.prototype._onTextureUpdate=function(){this.uvTransform&&(this.uvTransform.texture=this._texture)},e.prototype._renderWebGL=function(t){var e=this._texture;e&&e.valid&&(this.tileTransform.updateLocalTransform(),this.uvTransform.update(),t.setObjectRenderer(t.plugins[this.pluginName]),t.plugins[this.pluginName].render(this))},e.prototype._renderCanvas=function(t){var e=this._texture;if(e.baseTexture.hasLoaded){var r=t.context,n=this.worldTransform,i=t.resolution,o=e.baseTexture,s=e.baseTexture.resolution,a=this.tilePosition.x/this.tileScale.x%e._frame.width,u=this.tilePosition.y/this.tileScale.y%e._frame.height;if(!this._canvasPattern){var h=new l.CanvasRenderTarget(e._frame.width,e._frame.height,s);16777215!==this.tint?(this.cachedTint!==this.tint&&(this.cachedTint=this.tint,this.tintedTexture=f.default.getTintedTexture(this,this.tint)),h.context.drawImage(this.tintedTexture,0,0)):h.context.drawImage(o.source,-e._frame.x,-e._frame.y),this._canvasPattern=h.context.createPattern(h.canvas,"repeat")}r.globalAlpha=this.worldAlpha,r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t.setBlendMode(this.blendMode),r.fillStyle=this._canvasPattern,r.scale(this.tileScale.x/s,this.tileScale.y/s);var c=this.anchor.x*-this._width,d=this.anchor.y*-this._height;this.uvRespectAnchor?(r.translate(a,u),r.fillRect(-a+c,-u+d,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s)):(r.translate(a+c,u+d),r.fillRect(-a,-u,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s))}},e.prototype._calculateBounds=function(){var t=this._width*-this._anchor._x,e=this._height*-this._anchor._y,r=this._width*(1-this._anchor._x),n=this._height*(1-this._anchor._y);this._bounds.addFrame(this.transform,t,e,r,n)},e.prototype.getLocalBounds=function(e){return 0===this.children.length?(this._bounds.minX=this._width*-this._anchor._x,this._bounds.minY=this._height*-this._anchor._y,this._bounds.maxX=this._width*(1-this._anchor._x),this._bounds.maxY=this._height*(1-this._anchor._x),e||(this._localBoundsRect||(this._localBoundsRect=new l.Rectangle),e=this._localBoundsRect),this._bounds.getRectangle(e)):t.prototype.getLocalBounds.call(this,e)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,v);var e=this._width,r=this._height,n=-e*this.anchor._x;if(v.x>n&&v.xi&&v.y0&&void 0!==arguments[0]?arguments[0]:new o.Point,e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.parent?this.parent.toGlobal(this.position,t,e):(t.x=this.position.x,t.y=this.position.y),t}},{"../core":63}],136:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.BitmapText=r.TilingSpriteRenderer=r.TilingSprite=r.AnimatedSprite=r.TextureTransform=void 0;var i=t("./TextureTransform");Object.defineProperty(r,"TextureTransform",{enumerable:!0,get:function(){return n(i).default}});var o=t("./AnimatedSprite");Object.defineProperty(r,"AnimatedSprite",{enumerable:!0,get:function(){return n(o).default}});var s=t("./TilingSprite");Object.defineProperty(r,"TilingSprite",{enumerable:!0,get:function(){return n(s).default}});var a=t("./webgl/TilingSpriteRenderer");Object.defineProperty(r,"TilingSpriteRenderer",{enumerable:!0,get:function(){return n(a).default}});var u=t("./BitmapText");Object.defineProperty(r,"BitmapText",{enumerable:!0,get:function(){return n(u).default}}),t("./cacheAsBitmap"),t("./getChildByName"),t("./getGlobalPosition")},{"./AnimatedSprite":129,"./BitmapText":130,"./TextureTransform":131,"./TilingSprite":132,"./cacheAsBitmap":133,"./getChildByName":134,"./getGlobalPosition":135,"./webgl/TilingSpriteRenderer":137}],137:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../core"),u=n(a),h=t("../../core/const"),l=(t("path"),new u.Matrix),c=new Float32Array(4),f=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.shader=null,n.simpleShader=null,n.quad=null,n}return s(e,t),e.prototype.onContextChange=function(){var t=this.renderer.gl;this.shader=new u.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n gl_FragColor = sample * color ;\n}\n"),this.simpleShader=new u.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n gl_FragColor = sample * color;\n}\n"),this.renderer.bindVao(null),this.quad=new u.Quad(t,this.renderer.state.attribState),this.quad.initVao(this.shader)},e.prototype.render=function(t){var e=this.renderer,r=this.quad;e.bindVao(r.vao);var n=r.vertices;n[0]=n[6]=t._width*-t.anchor.x,n[1]=n[3]=t._height*-t.anchor.y,n[2]=n[4]=t._width*(1-t.anchor.x),n[5]=n[7]=t._height*(1-t.anchor.y),t.uvRespectAnchor&&(n=r.uvs,n[0]=n[6]=-t.anchor.x,n[1]=n[3]=-t.anchor.y,n[2]=n[4]=1-t.anchor.x,n[5]=n[7]=1-t.anchor.y),r.upload();var i=t._texture,o=i.baseTexture,s=t.tileTransform.localTransform,a=t.uvTransform,f=o.isPowerOfTwo&&i.frame.width===o.width&&i.frame.height===o.height;f&&(o._glTextures[e.CONTEXT_UID]?f=o.wrapMode!==h.WRAP_MODES.CLAMP:o.wrapMode===h.WRAP_MODES.CLAMP&&(o.wrapMode=h.WRAP_MODES.REPEAT));var d=f?this.simpleShader:this.shader;e.bindShader(d);var p=i.width,v=i.height,y=t._width,g=t._height;l.set(s.a*p/y,s.b*p/g,s.c*v/y,s.d*v/g,s.tx/y,s.ty/g),l.invert(),f?l.append(a.mapCoord):(d.uniforms.uMapCoord=a.mapCoord.toArray(!0),d.uniforms.uClampFrame=a.uClampFrame,d.uniforms.uClampOffset=a.uClampOffset),d.uniforms.uTransform=l.toArray(!0);var m=c;u.utils.hex2rgb(t.tint,m),m[3]=t.worldAlpha,d.uniforms.uColor=m,d.uniforms.translationMatrix=t.transform.worldTransform.toArray(!0),d.uniforms.uSampler=e.bindTexture(i),e.setBlendMode(t.blendMode),r.vao.draw(this.renderer.gl.TRIANGLES,6,0)},e}(u.ObjectRenderer);r.default=f,u.WebGLRenderer.registerPlugin("tilingSprite",f)},{"../../core":63,"../../core/const":44,path:22}],138:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var u=function(){function t(t,e){for(var r=0;r=r&&(u=t-h-1),l=l.replace("%value%",e[u]),s+=l,s+="\n"}return n=n.replace("%blur%",s),n=n.replace("%size%",t)}r.__esModule=!0,r.default=n;var i={5:[.153388,.221461,.250301],7:[.071303,.131514,.189879,.214607],9:[.028532,.067234,.124009,.179044,.20236],11:[.0093,.028002,.065984,.121703,.175713,.198596],13:[.002406,.009255,.027867,.065666,.121117,.174868,.197641],15:[489e-6,.002403,.009246,.02784,.065602,.120999,.174697,.197448]},o=["varying vec2 vBlurTexCoords[%size%];","uniform sampler2D uSampler;","void main(void)","{"," gl_FragColor = vec4(0.0);"," %blur%","}"].join("\n")},{}],142:[function(t,e,r){"use strict";function n(t,e){var r=Math.ceil(t/2),n=i,o="",s=void 0;s=e?"vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);":"vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);";for(var a=0;ae;)r-=2;return r}r.__esModule=!0,r.default=n},{}],144:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r 0.0) {\n c.rgb /= c.a;\n }\n vec4 result;\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n // Premultiply alpha again.\n result.rgb *= result.a;\n\n gl_FragColor = result;\n}\n")); +return r.uniforms.m=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],r}return s(e,t),e.prototype._loadMatrix=function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t;e&&(this._multiply(r,this.uniforms.m,t),r=this._colorMatrix(r)),this.uniforms.m=r},e.prototype._multiply=function(t,e,r){return t[0]=e[0]*r[0]+e[1]*r[5]+e[2]*r[10]+e[3]*r[15],t[1]=e[0]*r[1]+e[1]*r[6]+e[2]*r[11]+e[3]*r[16],t[2]=e[0]*r[2]+e[1]*r[7]+e[2]*r[12]+e[3]*r[17],t[3]=e[0]*r[3]+e[1]*r[8]+e[2]*r[13]+e[3]*r[18],t[4]=e[0]*r[4]+e[1]*r[9]+e[2]*r[14]+e[3]*r[19]+e[4],t[5]=e[5]*r[0]+e[6]*r[5]+e[7]*r[10]+e[8]*r[15],t[6]=e[5]*r[1]+e[6]*r[6]+e[7]*r[11]+e[8]*r[16],t[7]=e[5]*r[2]+e[6]*r[7]+e[7]*r[12]+e[8]*r[17],t[8]=e[5]*r[3]+e[6]*r[8]+e[7]*r[13]+e[8]*r[18],t[9]=e[5]*r[4]+e[6]*r[9]+e[7]*r[14]+e[8]*r[19]+e[9],t[10]=e[10]*r[0]+e[11]*r[5]+e[12]*r[10]+e[13]*r[15],t[11]=e[10]*r[1]+e[11]*r[6]+e[12]*r[11]+e[13]*r[16],t[12]=e[10]*r[2]+e[11]*r[7]+e[12]*r[12]+e[13]*r[17],t[13]=e[10]*r[3]+e[11]*r[8]+e[12]*r[13]+e[13]*r[18],t[14]=e[10]*r[4]+e[11]*r[9]+e[12]*r[14]+e[13]*r[19]+e[14],t[15]=e[15]*r[0]+e[16]*r[5]+e[17]*r[10]+e[18]*r[15],t[16]=e[15]*r[1]+e[16]*r[6]+e[17]*r[11]+e[18]*r[16],t[17]=e[15]*r[2]+e[16]*r[7]+e[17]*r[12]+e[18]*r[17],t[18]=e[15]*r[3]+e[16]*r[8]+e[17]*r[13]+e[18]*r[18],t[19]=e[15]*r[4]+e[16]*r[9]+e[17]*r[14]+e[18]*r[19]+e[19],t},e.prototype._colorMatrix=function(t){var e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e},e.prototype.brightness=function(t,e){var r=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.greyscale=function(t,e){var r=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.blackAndWhite=function(t){var e=[.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.hue=function(t,e){t=(t||0)/180*Math.PI;var r=Math.cos(t),n=Math.sin(t),i=Math.sqrt,o=1/3,s=i(o),a=r+(1-r)*o,u=o*(1-r)-s*n,h=o*(1-r)+s*n,l=o*(1-r)+s*n,c=r+o*(1-r),f=o*(1-r)-s*n,d=o*(1-r)-s*n,p=o*(1-r)+s*n,v=r+o*(1-r),y=[a,u,h,0,0,l,c,f,0,0,d,p,v,0,0,0,0,0,1,0];this._loadMatrix(y,e)},e.prototype.contrast=function(t,e){var r=(t||0)+1,n=-128*(r-1),i=[r,0,0,0,n,0,r,0,0,n,0,0,r,0,n,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.saturate=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=2*t/3+1,n=(r-1)*-.5,i=[r,n,n,0,0,n,r,n,0,0,n,n,r,0,0,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.desaturate=function(){this.saturate(-1)},e.prototype.negative=function(t){var e=[0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.sepia=function(t){var e=[.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.technicolor=function(t){var e=[1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.polaroid=function(t){var e=[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.toBGR=function(t){var e=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.kodachrome=function(t){var e=[1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.browni=function(t){var e=[.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.vintage=function(t){var e=[.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.colorTone=function(t,e,r,n,i){t=t||.2,e=e||.15,r=r||16770432,n=n||3375104;var o=(r>>16&255)/255,s=(r>>8&255)/255,a=(255&r)/255,u=(n>>16&255)/255,h=(n>>8&255)/255,l=(255&n)/255,c=[.3,.59,.11,0,0,o,s,a,t,0,u,h,l,e,0,o-u,s-h,a-l,0,0];this._loadMatrix(c,i)},e.prototype.night=function(t,e){t=t||.1;var r=[t*-2,-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.predator=function(t,e){var r=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.lsd=function(t){var e=[2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.reset=function(){var t=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(t,!1)},a(e,[{key:"matrix",get:function(){return this.uniforms.m},set:function(t){this.uniforms.m=t}}]),e}(h.Filter));r.default=l,l.prototype.grayscale=l.prototype.greyscale},{"../../core":63,path:22}],145:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n'))}return s(e,t),e}(u.Filter));r.default=h},{"../../core":63,path:22}],147:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./fxaa/FXAAFilter");Object.defineProperty(r,"FXAAFilter",{enumerable:!0,get:function(){return n(i).default}});var o=t("./noise/NoiseFilter");Object.defineProperty(r,"NoiseFilter",{enumerable:!0,get:function(){return n(o).default}});var s=t("./displacement/DisplacementFilter");Object.defineProperty(r,"DisplacementFilter",{enumerable:!0,get:function(){return n(s).default}});var a=t("./blur/BlurFilter");Object.defineProperty(r,"BlurFilter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./blur/BlurXFilter");Object.defineProperty(r,"BlurXFilter",{enumerable:!0,get:function(){return n(u).default}});var h=t("./blur/BlurYFilter");Object.defineProperty(r,"BlurYFilter",{enumerable:!0,get:function(){return n(h).default}});var l=t("./colormatrix/ColorMatrixFilter");Object.defineProperty(r,"ColorMatrixFilter",{enumerable:!0,get:function(){return n(l).default}});var c=t("./void/VoidFilter");Object.defineProperty(r,"VoidFilter",{enumerable:!0,get:function(){return n(c).default}})},{"./blur/BlurFilter":138,"./blur/BlurXFilter":139,"./blur/BlurYFilter":140,"./colormatrix/ColorMatrixFilter":144,"./displacement/DisplacementFilter":145,"./fxaa/FXAAFilter":146,"./noise/NoiseFilter":148,"./void/VoidFilter":149}],148:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:1;this.removeEvents(),this.interactionDOMElement=t,this.resolution=e,this.addEvents()},e.prototype.addEvents=function(){this.interactionDOMElement&&(l.ticker.shared.add(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="none",this.interactionDOMElement.style["-ms-touch-action"]="none"):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]="none"),this.supportsPointerEvents?(window.document.addEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("pointerover",this.onPointerOver,!0),window.addEventListener("pointercancel",this.onPointerCancel,!0),window.addEventListener("pointerup",this.onPointerUp,!0)):(window.document.addEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onPointerOver,!0),window.addEventListener("mouseup",this.onPointerUp,!0),this.supportsTouchEvents&&(this.interactionDOMElement.addEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.addEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.addEventListener("touchmove",this.onPointerMove,!0))),this.eventsAdded=!0)},e.prototype.removeEvents=function(){this.interactionDOMElement&&(l.ticker.shared.remove(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="",this.interactionDOMElement.style["-ms-touch-action"]=""):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]=""),this.supportsPointerEvents?(window.document.removeEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("pointerover",this.onPointerOver,!0),window.removeEventListener("pointercancel",this.onPointerCancel,!0),window.removeEventListener("pointerup",this.onPointerUp,!0)):(window.document.removeEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onPointerOver,!0),window.removeEventListener("mouseup",this.onPointerUp,!0),this.supportsTouchEvents&&(this.interactionDOMElement.removeEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.removeEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onPointerMove,!0))),this.interactionDOMElement=null,this.eventsAdded=!1)},e.prototype.update=function(t){if(this._deltaTime+=t,!(this._deltaTime=0;h--){var l=u[h];if(this.processInteractive(t,l,r,n,a)){if(!l.parent)continue;s=!0,a=!1,n=!1}}return i&&(n&&!s&&(e.hitArea?(e.worldTransform.applyInverse(o,this._tempPoint),s=e.hitArea.contains(this._tempPoint.x,this._tempPoint.y)):e.containsPoint&&(s=e.containsPoint(o))),e.interactive&&(s&&!t.target&&(t.target=e),r(t,e,s))),s},e.prototype.onPointerDown=function(t){var e=this.normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&t.preventDefault();for(var r=e.length,n=0;n1&&(l=1);var c=Math.sqrt(n*n+i*i),f=this._texture.height/2;n/=c,i/=c,n*=f,i*=f,o[h]=u.x+n,o[h+1]=u.y+i,o[h+2]=u.x-n,o[h+3]=u.y-i,e=u}this.containerUpdateTransform()}},e}(h.default);r.default=f},{"../core":63,"./Mesh":161}],165:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var s=t("../../core"),a=i(s),u=t("../Mesh"),h=n(u),l=function(){function t(e){o(this,t),this.renderer=e}return t.prototype.render=function(t){var e=this.renderer,r=e.context,n=t.worldTransform,i=e.resolution;e.roundPixels?r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i|0,n.ty*i|0):r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),e.setBlendMode(t.blendMode),t.drawMode===h.default.DRAW_MODES.TRIANGLE_MESH?this._renderTriangleMesh(t):this._renderTriangles(t)},t.prototype._renderTriangleMesh=function(t){for(var e=t.vertices.length/2,r=0;r0){var E=t.canvasPadding/t.worldTransform.a,S=t.canvasPadding/t.worldTransform.d,O=(m+_+b)/3,P=(x+T+w)/3,M=m-O,C=x-P,R=Math.sqrt(M*M+C*C);m=O+M/R*(R+E),x=P+C/R*(R+S),M=_-O,C=T-P,R=Math.sqrt(M*M+C*C),_=O+M/R*(R+E),T=P+C/R*(R+S),M=b-O,C=w-P,R=Math.sqrt(M*M+C*C),b=O+M/R*(R+E),w=P+C/R*(R+S)}i.save(),i.beginPath(),i.moveTo(m,x),i.lineTo(_,T),i.lineTo(b,w),i.closePath(),i.clip();var A=f*y+v*p+d*g-y*p-v*d-f*g,I=m*y+v*b+_*g-y*b-v*_-m*g,D=f*_+m*p+d*b-_*p-m*d-f*b,L=f*y*b+v*_*p+m*d*g-m*y*p-v*d*b-f*_*g,F=x*y+v*w+T*g-y*w-v*T-x*g,N=f*T+x*p+d*w-T*p-x*d-f*w,B=f*y*w+v*T*p+x*d*g-x*y*p-v*d*w-f*T*g;i.transform(I/A,F/A,D/A,N/A,L/A,B/A),i.drawImage(h,0,0,l*u.resolution,c*u.resolution,0,0,l,c),i.restore()}},t.prototype.renderMeshFlat=function(t){var e=this.renderer.context,r=t.vertices,n=r.length/2;e.beginPath();for(var i=1;i0&&void 0!==arguments[0]?arguments[0]:1500,n=arguments[1],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16384;i(this,e);var a=o(this,t.call(this)),h=16384;return s>h&&(s=h),s>r&&(s=r),a._properties=[!1,!0,!1,!1,!1],a._maxSize=r,a._batchSize=s,a._glBuffers={},a._bufferToUpdate=0,a.interactiveChildren=!1,a.blendMode=u.BLEND_MODES.NORMAL,a.roundPixels=!0,a.baseTexture=null,a.setProperties(n),a}return s(e,t),e.prototype.setProperties=function(t){t&&(this._properties[0]="scale"in t?!!t.scale:this._properties[0],this._properties[1]="position"in t?!!t.position:this._properties[1],this._properties[2]="rotation"in t?!!t.rotation:this._properties[2],this._properties[3]="uvs"in t?!!t.uvs:this._properties[3],this._properties[4]="alpha"in t?!!t.alpha:this._properties[4])},e.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},e.prototype.renderWebGL=function(t){var e=this;this.visible&&!(this.worldAlpha<=0)&&this.children.length&&this.renderable&&(this.baseTexture||(this.baseTexture=this.children[0]._texture.baseTexture,this.baseTexture.hasLoaded||this.baseTexture.once("update",function(){return e.onChildrenChange(0)})),t.setObjectRenderer(t.plugins.particle),t.plugins.particle.render(this))},e.prototype.onChildrenChange=function(t){var e=Math.floor(t/this._batchSize);er&&(o=r);var s=t._glBuffers[i.CONTEXT_UID];s||(s=t._glBuffers[i.CONTEXT_UID]=this.generateBuffers(t)),this.renderer.setBlendMode(t.blendMode);var a=i.gl,u=t.worldTransform.copy(this.tempMatrix);u.prepend(i._activeRenderTarget.projectionMatrix),this.shader.uniforms.projectionMatrix=u.toArray(!0),this.shader.uniforms.uAlpha=t.worldAlpha;var h=e[0]._texture.baseTexture;this.shader.uniforms.uSampler=i.bindTexture(h);for(var l=0,c=0;ln&&(f=n);var d=s[c];d.uploadDynamic(e,l,f),t._bufferToUpdate===c&&(d.uploadStatic(e,l,f),t._bufferToUpdate=c+1),i.bindVao(d.vao),d.vao.draw(a.TRIANGLES,6*f)}}},e.prototype.generateBuffers=function(t){for(var e=this.renderer.gl,r=[],n=t._maxSize,i=t._batchSize,o=t._properties,s=0;s0?1:-1})},{}],174:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}var i=t("object-assign"),o=n(i);Object.assign||(Object.assign=o.default)},{"object-assign":5}],175:[function(t,e,r){"use strict";t("./Object.assign"),t("./requestAnimationFrame"),t("./Math.sign"),window.ArrayBuffer||(window.ArrayBuffer=Array),window.Float32Array||(window.Float32Array=Array),window.Uint32Array||(window.Uint32Array=Array),window.Uint16Array||(window.Uint16Array=Array)},{"./Math.sign":173,"./Object.assign":174,"./requestAnimationFrame":176}],176:[function(t,e,r){(function(t){"use strict";var e=16;Date.now&&Date.prototype.getTime||(Date.now=function(){return(new Date).getTime()}),t.performance&&t.performance.now||!function(){var e=Date.now();t.performance||(t.performance={}),t.performance.now=function(){return Date.now()-e}}();for(var r=Date.now(),n=["ms","moz","webkit","o"],i=0;i=0;n--)this.add(t.children[n]);return this},t.prototype.destroy=function(){this.ticking&&p.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null,this.limiter=null,this.uploadHookHelper=null},t}();r.default=v},{"../core":63,"./limiters/CountLimiter":180}],178:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function u(t,e){if(e instanceof c.BaseTexture){var r=e.source,n=0===r.width?t.canvas.width:Math.min(t.canvas.width,r.width),i=0===r.height?t.canvas.height:Math.min(t.canvas.height,r.height);return t.ctx.drawImage(r,0,0,n,i,0,0,t.canvas.width,t.canvas.height),!0}return!1}function h(t,e){if(t instanceof c.BaseTexture)return e.indexOf(t)===-1&&e.push(t),!0;if(t._texture&&t._texture instanceof c.Texture){var r=t._texture.baseTexture;return e.indexOf(r)===-1&&e.push(r),!0}return!1}r.__esModule=!0;var l=t("../../core"),c=i(l),f=t("../BasePrepare"),d=n(f),p=16,v=function(t){function e(r){o(this,e);var n=s(this,t.call(this,r));return n.uploadHookHelper=n,n.canvas=document.createElement("canvas"),n.canvas.width=p,n.canvas.height=p,n.ctx=n.canvas.getContext("2d"),n.register(h,u),n}return a(e,t),e.prototype.destroy=function(){t.prototype.destroy.call(this),this.ctx=null,this.canvas=null},e}(d.default);r.default=v,c.CanvasRenderer.registerPlugin("prepare",v)},{"../../core":63,"../BasePrepare":177}],179:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./webgl/WebGLPrepare");Object.defineProperty(r,"webgl",{enumerable:!0,get:function(){return n(i).default}});var o=t("./canvas/CanvasPrepare");Object.defineProperty(r,"canvas",{enumerable:!0,get:function(){return n(o).default}});var s=t("./BasePrepare");Object.defineProperty(r,"BasePrepare",{enumerable:!0,get:function(){return n(s).default}});var a=t("./limiters/CountLimiter");Object.defineProperty(r,"CountLimiter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./limiters/TimeLimiter");Object.defineProperty(r,"TimeLimiter",{enumerable:!0,get:function(){return n(u).default}})},{"./BasePrepare":177,"./canvas/CanvasPrepare":178,"./limiters/CountLimiter":180,"./limiters/TimeLimiter":181,"./webgl/WebGLPrepare":182}],180:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxItemsPerFrame=e,this.itemsLeft=0}return t.prototype.beginFrame=function(){this.itemsLeft=this.maxItemsPerFrame},t.prototype.allowedToUpload=function(){return this.itemsLeft-- >0},t}();r.default=i},{}],181:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxMilliseconds=e,this.frameStart=0}return t.prototype.beginFrame=function(){this.frameStart=Date.now()},t.prototype.allowedToUpload=function(){return Date.now()-this.frameStart 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],2:[function(require,module,exports){ +'use strict'; + +module.exports = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, size), + maxZ = zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, size); + earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and size of the data bounding box +function zOrder(x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; + +},{}],3:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @api private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {Mixed} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @api public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @api public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Boolean} exists Only check if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Add a one-time listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Remove the listeners of a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {Mixed} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn + && (!once || listeners.once) + && (!context || listeners.context === context) + ) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {String|Symbol} [event] The event name. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],4:[function(require,module,exports){ +/** + * isMobile.js v0.4.0 + * + * A simple library to detect Apple phones and tablets, + * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone), + * and any kind of seven inch device, via user agent sniffing. + * + * @author: Kai Mallea (kmallea@gmail.com) + * + * @license: http://creativecommons.org/publicdomain/zero/1.0/ + */ +(function (global) { + + var apple_phone = /iPhone/i, + apple_ipod = /iPod/i, + apple_tablet = /iPad/i, + android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i, // Match 'Android' AND 'Mobile' + android_tablet = /Android/i, + amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i, + amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i, + windows_phone = /IEMobile/i, + windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i, // Match 'Windows' AND 'ARM' + other_blackberry = /BlackBerry/i, + other_blackberry_10 = /BB10/i, + other_opera = /Opera Mini/i, + other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i, + other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i, // Match 'Firefox' AND 'Mobile' + seven_inch = new RegExp( + '(?:' + // Non-capturing group + + 'Nexus 7' + // Nexus 7 + + '|' + // OR + + 'BNTV250' + // B&N Nook Tablet 7 inch + + '|' + // OR + + 'Kindle Fire' + // Kindle Fire + + '|' + // OR + + 'Silk' + // Kindle Fire, Silk Accelerated + + '|' + // OR + + 'GT-P1000' + // Galaxy Tab 7 inch + + ')', // End non-capturing group + + 'i'); // Case-insensitive matching + + var match = function(regex, userAgent) { + return regex.test(userAgent); + }; + + var IsMobileClass = function(userAgent) { + var ua = userAgent || navigator.userAgent; + + // Facebook mobile app's integrated browser adds a bunch of strings that + // match everything. Strip it out if it exists. + var tmp = ua.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + // Twitter mobile app's integrated browser on iPad adds a "Twitter for + // iPhone" string. Same probable happens on other tablet platforms. + // This will confuse detection so strip it out if it exists. + tmp = ua.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + this.apple = { + phone: match(apple_phone, ua), + ipod: match(apple_ipod, ua), + tablet: !match(apple_phone, ua) && match(apple_tablet, ua), + device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua) + }; + this.amazon = { + phone: match(amazon_phone, ua), + tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) + }; + this.android = { + phone: match(amazon_phone, ua) || match(android_phone, ua), + tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua) + }; + this.windows = { + phone: match(windows_phone, ua), + tablet: match(windows_tablet, ua), + device: match(windows_phone, ua) || match(windows_tablet, ua) + }; + this.other = { + blackberry: match(other_blackberry, ua), + blackberry10: match(other_blackberry_10, ua), + opera: match(other_opera, ua), + firefox: match(other_firefox, ua), + chrome: match(other_chrome, ua), + device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua) + }; + this.seven_inch = match(seven_inch, ua); + this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch; + + // excludes 'other' devices and ipods, targeting touchscreen phones + this.phone = this.apple.phone || this.android.phone || this.windows.phone; + + // excludes 7 inch devices, classifying as phone or tablet is left to the user + this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet; + + if (typeof window === 'undefined') { + return this; + } + }; + + var instantiate = function() { + var IM = new IsMobileClass(); + IM.Class = IsMobileClass; + return IM; + }; + + if (typeof module !== 'undefined' && module.exports && typeof window === 'undefined') { + //node + module.exports = IsMobileClass; + } else if (typeof module !== 'undefined' && module.exports && typeof window !== 'undefined') { + //browserify + module.exports = instantiate(); + } else if (typeof define === 'function' && define.amd) { + //AMD + define('isMobile', [], global.isMobile = instantiate()); + } else { + global.isMobile = instantiate(); + } + +})(this); + +},{}],5:[function(require,module,exports){ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],6:[function(require,module,exports){ +var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); + +/** + * Helper class to create a webGL buffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ +var Buffer = function(gl, type, data, drawType) +{ + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The WebGL buffer, created upon instantiation + * + * @member {WebGLBuffer} + */ + this.buffer = gl.createBuffer(); + + /** + * The type of the buffer + * + * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} + */ + this.type = type || gl.ARRAY_BUFFER; + + /** + * The draw type of the buffer + * + * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ + this.drawType = drawType || gl.STATIC_DRAW; + + /** + * The data in the buffer, as a typed array + * + * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} + */ + this.data = EMPTY_ARRAY_BUFFER; + + if(data) + { + this.upload(data); + } +}; + +/** + * Uploads the buffer to the GPU + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload + * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract + * @param dontBind {Boolean} whether to bind the buffer before uploading it + */ +Buffer.prototype.upload = function(data, offset, dontBind) +{ + // todo - needed? + if(!dontBind) this.bind(); + + var gl = this.gl; + + data = data || this.data; + offset = offset || 0; + + if(this.data.byteLength >= data.byteLength) + { + gl.bufferSubData(this.type, offset, data); + } + else + { + gl.bufferData(this.type, data, this.drawType); + } + + this.data = data; +}; +/** + * Binds the buffer + * + */ +Buffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindBuffer(this.type, this.buffer); +}; + +Buffer.createVertexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); +}; + +Buffer.createIndexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); +}; + +Buffer.create = function(gl, type, data, drawType) +{ + return new Buffer(gl, type, data, drawType); +}; + +/** + * Destroys the buffer + * + */ +Buffer.prototype.destroy = function(){ + this.gl.deleteBuffer(this.buffer); +}; + +module.exports = Buffer; + +},{}],7:[function(require,module,exports){ + +var Texture = require('./GLTexture'); + +/** + * Helper class to create a webGL Framebuffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + */ +var Framebuffer = function(gl, width, height) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The frame buffer + * + * @member {WebGLFramebuffer} + */ + this.framebuffer = gl.createFramebuffer(); + + /** + * The stencil buffer + * + * @member {WebGLRenderbuffer} + */ + this.stencil = null; + + /** + * The stencil buffer + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The width of the drawing area of the buffer + * + * @member {Number} + */ + this.width = width || 100; + /** + * The height of the drawing area of the buffer + * + * @member {Number} + */ + this.height = height || 100; +}; + +/** + * Adds a texture to the frame buffer + * @param texture {PIXI.glCore.GLTexture} + */ +Framebuffer.prototype.enableTexture = function(texture) +{ + var gl = this.gl; + + this.texture = texture || new Texture(gl); + + this.texture.bind(); + + //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + this.bind(); + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); +}; + +/** + * Initialises the stencil buffer + */ +Framebuffer.prototype.enableStencil = function() +{ + if(this.stencil)return; + + var gl = this.gl; + + this.stencil = gl.createRenderbuffer(); + + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + + // TODO.. this is depth AND stencil? + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width , this.height ); +}; + +/** + * Erases the drawing area and fills it with a colour + * @param r {Number} the red value of the clearing colour + * @param g {Number} the green value of the clearing colour + * @param b {Number} the blue value of the clearing colour + * @param a {Number} the alpha value of the clearing colour + */ +Framebuffer.prototype.clear = function( r, g, b, a ) +{ + this.bind(); + + var gl = this.gl; + + gl.clearColor(r, g, b, a); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Binds the frame buffer to the WebGL context + */ +Framebuffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); +}; + +/** + * Unbinds the frame buffer to the WebGL context + */ +Framebuffer.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, null ); +}; +/** + * Resizes the drawing area of the buffer to the given width and height + * @param width {Number} the new width + * @param height {Number} the new height + */ +Framebuffer.prototype.resize = function(width, height) +{ + var gl = this.gl; + + this.width = width; + this.height = height; + + if ( this.texture ) + { + this.texture.uploadData(null, width, height); + } + + if ( this.stencil ) + { + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + } +}; + +/** + * Destroys this buffer + */ +Framebuffer.prototype.destroy = function() +{ + var gl = this.gl; + + //TODO + if(this.texture) + { + this.texture.destroy(); + } + + gl.deleteFramebuffer(this.framebuffer); + + this.gl = null; + + this.stencil = null; + this.texture = null; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createRGBA = function(gl, width, height, data) +{ + var texture = Texture.fromData(gl, null, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createFloat32 = function(gl, width, height, data) +{ + // create a new texture.. + var texture = new Texture.fromData(gl, data, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +module.exports = Framebuffer; + +},{"./GLTexture":9}],8:[function(require,module,exports){ + +var compileProgram = require('./shader/compileProgram'), + extractAttributes = require('./shader/extractAttributes'), + extractUniforms = require('./shader/extractUniforms'), + generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + +/** + * Helper class to create a webGL Shader + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + */ +var Shader = function(gl, vertexSrc, fragmentSrc) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc); + + + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); + + var uniformData = extractUniforms(gl, this.program); + + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject( gl, uniformData ); +}; +/** + * Uses this shader + */ +Shader.prototype.bind = function() +{ + this.gl.useProgram(this.program); +}; + +/** + * Destroys this shader + * TODO + */ +Shader.prototype.destroy = function() +{ + // var gl = this.gl; +}; + +module.exports = Shader; + +},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18}],9:[function(require,module,exports){ + +/** + * Helper class to create a WebGL Texture + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL context + * @param width {number} the width of the texture + * @param height {number} the height of the texture + * @param format {number} the pixel format of the texture. defaults to gl.RGBA + * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE + */ +var Texture = function(gl, width, height, format, type) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); + + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; + + + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; + + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; + + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + + +}; + +/** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ +Texture.prototype.upload = function(source) +{ + this.bind(); + + var gl = this.gl; + + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + var newWidth = source.videoWidth || source.width; + var newHeight = source.videoHeight || source.height; + + if(newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } + + // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + +}; + +var FLOATING_POINT_AVAILABLE = false; + +/** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.prototype.uploadData = function(data, width, height) +{ + this.bind(); + + var gl = this.gl; + + + if(data instanceof Float32Array) + { + if(!FLOATING_POINT_AVAILABLE) + { + var ext = gl.getExtension("OES_texture_float"); + + if(ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } + + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = gl.UNSIGNED_BYTE; + } + + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + + if(width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } + + this.width = width; + this.height = height; + + +// texSubImage2D +}; + +/** + * Binds the texture + * @param location + */ +Texture.prototype.bind = function(location) +{ + var gl = this.gl; + + if(location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } + + gl.bindTexture(gl.TEXTURE_2D, this.texture); +}; + +/** + * Unbinds the texture + */ +Texture.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, null); +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.minFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + if(this.mipmap) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.magFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); +}; + +/** + * Enables mipmapping + */ +Texture.prototype.enableMipmap = function() +{ + var gl = this.gl; + + this.bind(); + + this.mipmap = true; + + gl.generateMipmap(gl.TEXTURE_2D); +}; + +/** + * Enables linear filtering + */ +Texture.prototype.enableLinearScaling = function() +{ + this.minFilter(true); + this.magFilter(true); +}; + +/** + * Enables nearest neighbour interpolation + */ +Texture.prototype.enableNearestScaling = function() +{ + this.minFilter(false); + this.magFilter(false); +}; + +/** + * Enables clamping on the texture so WebGL will not repeat it + */ +Texture.prototype.enableWrapClamp = function() +{ + var gl = this.gl; + + this.bind(); + + 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); +}; + +/** + * Enable tiling on the texture + */ +Texture.prototype.enableWrapRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); +}; + +Texture.prototype.enableWrapMirrorRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); +}; + + +/** + * Destroys this texture + */ +Texture.prototype.destroy = function() +{ + var gl = this.gl; + //TODO + gl.deleteTexture(this.texture); +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ +Texture.fromSource = function(gl, source, premultiplyAlpha) +{ + var texture = new Texture(gl); + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); + + return texture; +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.fromData = function(gl, data, width, height) +{ + //console.log(data, width, height); + var texture = new Texture(gl); + texture.uploadData(data, width, height); + + return texture; +}; + + +module.exports = Texture; + +},{}],10:[function(require,module,exports){ + +// state object// +var setVertexAttribArrays = require( './setVertexAttribArrays' ); + +/** + * Helper class to work with WebGL VertexArrayObjects (vaos) + * Only works if WebGL extensions are enabled (they usually are) + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function VertexArrayObject(gl, state) +{ + this.nativeVaoExtension = null; + + if(!VertexArrayObject.FORCE_NATIVE) + { + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + this.nativeState = state; + + if(this.nativeVaoExtension) + { + this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + + var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + // VAO - overwrite the state.. + this.nativeState = { + tempAttribState: new Array(maxAttribs), + attribState: new Array(maxAttribs) + }; + } + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of attributes + * + * @member {Array} + */ + this.attributes = []; + + /** + * @member {PIXI.glCore.GLBuffer} + */ + this.indexBuffer = null; + + /** + * A boolean flag + * + * @member {Boolean} + */ + this.dirty = false; +} + +VertexArrayObject.prototype.constructor = VertexArrayObject; +module.exports = VertexArrayObject; + +/** +* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) +* If you find on older devices that things have gone a bit weird then set this to true. +*/ +/** + * Lets the VAO know if you should use the WebGL extension or the native methods. + * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) + * If you find on older devices that things have gone a bit weird then set this to true. + * @static + * @property {Boolean} FORCE_NATIVE + */ +VertexArrayObject.FORCE_NATIVE = false; + +/** + * Binds the buffer + */ +VertexArrayObject.prototype.bind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + + if(this.dirty) + { + this.dirty = false; + this.activate(); + } + } + else + { + + this.activate(); + } + + return this; +}; + +/** + * Unbinds the buffer + */ +VertexArrayObject.prototype.unbind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + return this; +}; + +/** + * Uses this vao + */ +VertexArrayObject.prototype.activate = function() +{ + + var gl = this.gl; + var lastBuffer = null; + + for (var i = 0; i < this.attributes.length; i++) + { + var attrib = this.attributes[i]; + + if(lastBuffer !== attrib.buffer) + { + attrib.buffer.bind(); + lastBuffer = attrib.buffer; + } + + //attrib.attribute.pointer(attrib.type, attrib.normalized, attrib.stride, attrib.start); + gl.vertexAttribPointer(attrib.attribute.location, + attrib.attribute.size, attrib.type || gl.FLOAT, + attrib.normalized || false, + attrib.stride || 0, + attrib.start || 0); + + + } + + setVertexAttribArrays(gl, this.attributes, this.nativeState); + + this.indexBuffer.bind(); + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + * @param attribute {*} + * @param type {String} + * @param normalized {Boolean} + * @param stride {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start) +{ + this.attributes.push({ + buffer: buffer, + attribute: attribute, + + location: attribute.location, + type: type || this.gl.FLOAT, + normalized: normalized || false, + stride: stride || 0, + start: start || 0 + }); + + this.dirty = true; + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + */ +VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) +{ + this.indexBuffer = buffer; + + this.dirty = true; + + return this; +}; + +/** + * Unbinds this vao and disables it + */ +VertexArrayObject.prototype.clear = function() +{ + // var gl = this.gl; + + // TODO - should this function unbind after clear? + // for now, no but lets see what happens in the real world! + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + } + + this.attributes.length = 0; + this.indexBuffer = null; + + return this; +}; + +/** + * @param type {Number} + * @param size {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.draw = function(type, size, start) +{ + var gl = this.gl; + gl.drawElements(type, size, gl.UNSIGNED_SHORT, start || 0); + + return this; +}; + +/** + * Destroy this vao + */ +VertexArrayObject.prototype.destroy = function() +{ + // lose references + this.gl = null; + this.indexBuffer = null; + this.attributes = null; + this.nativeState = null; + + if(this.nativeVao) + { + this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); + } + + this.nativeVaoExtension = null; + this.nativeVao = null; +}; + +},{"./setVertexAttribArrays":13}],11:[function(require,module,exports){ + +/** + * Helper class to create a webGL Context + * + * @class + * @memberof PIXI.glCore + * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from + * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * @return {WebGLRenderingContext} the WebGL context + */ +var createContext = function(canvas, options) +{ + var gl = canvas.getContext('webgl', options) || + canvas.getContext('experimental-webgl', options); + + if (!gl) + { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + return gl; +}; + +module.exports = createContext; + +},{}],12:[function(require,module,exports){ +var gl = { + createContext: require('./createContext'), + setVertexAttribArrays: require('./setVertexAttribArrays'), + GLBuffer: require('./GLBuffer'), + GLFramebuffer: require('./GLFramebuffer'), + GLShader: require('./GLShader'), + GLTexture: require('./GLTexture'), + VertexArrayObject: require('./VertexArrayObject'), + shader: require('./shader') +}; + +// Export for Node-compatible environments +if (typeof module !== 'undefined' && module.exports) +{ + // Export the module + module.exports = gl; +} + +// Add to the browser window pixi.gl +if (typeof window !== 'undefined') +{ + // add the window object + window.PIXI = window.PIXI || {}; + window.PIXI.glCore = gl; +} + +},{"./GLBuffer":6,"./GLFramebuffer":7,"./GLShader":8,"./GLTexture":9,"./VertexArrayObject":10,"./createContext":11,"./setVertexAttribArrays":13,"./shader":19}],13:[function(require,module,exports){ +// var GL_MAP = {}; + +/** + * @param gl {WebGLRenderingContext} The current WebGL context + * @param attribs {*} + * @param state {*} + */ +var setVertexAttribArrays = function (gl, attribs, state) +{ + var i; + if(state) + { + var tempAttribState = state.tempAttribState, + attribState = state.attribState; + + for (i = 0; i < tempAttribState.length; i++) + { + tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + tempAttribState[attribs[i].attribute.location] = true; + } + + for (i = 0; i < attribState.length; i++) + { + if (attribState[i] !== tempAttribState[i]) + { + attribState[i] = tempAttribState[i]; + + if (state.attribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } + + } + else + { + for (i = 0; i < attribs.length; i++) + { + var attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); + } + } +}; + +module.exports = setVertexAttribArrays; + +},{}],14:[function(require,module,exports){ + +/** + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @return {WebGLProgram} the shader program + */ +var compileProgram = function(gl, vertexSrc, fragmentSrc) +{ + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + + var program = gl.createProgram(); + + gl.attachShader(program, glVertShader); + gl.attachShader(program, glFragShader); + gl.linkProgram(program); + + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + console.error('Pixi.js Error: Could not initialize shader.'); + console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); + console.error('gl.getError()', gl.getError()); + + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') + { + console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + + gl.deleteProgram(program); + program = null; + } + + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + + return program; +}; + +/** + * @private + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @return {WebGLShader} the shader + */ +var compileShader = function (gl, type, src) +{ + var shader = gl.createShader(type); + + gl.shaderSource(shader, src); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + console.log(gl.getShaderInfoLog(shader)); + return null; + } + + return shader; +}; + +module.exports = compileProgram; + +},{}],15:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} Type of value + * @param size {Number} + */ +var defaultValue = function(type, size) +{ + switch (type) + { + case 'float': + return 0; + + case 'vec2': + return new Float32Array(2 * size); + + case 'vec3': + return new Float32Array(3 * size); + + case 'vec4': + return new Float32Array(4 * size); + + case 'int': + case 'sampler2D': + return 0; + + case 'ivec2': + return new Int32Array(2 * size); + + case 'ivec3': + return new Int32Array(3 * size); + + case 'ivec4': + return new Int32Array(4 * size); + + case 'bool': + return false; + + case 'bvec2': + + return booleanArray( 2 * size); + + case 'bvec3': + return booleanArray(3 * size); + + case 'bvec4': + return booleanArray(4 * size); + + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } +}; + +var booleanArray = function(size) +{ + var array = new Array(size); + + for (var i = 0; i < array.length; i++) + { + array[i] = false; + } + + return array; +}; + +module.exports = defaultValue; + +},{}],16:[function(require,module,exports){ + +var mapType = require('./mapType'); +var mapSize = require('./mapSize'); + +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the attributes from + * @return attributes {Object} + */ +var extractAttributes = function(gl, program) +{ + var attributes = {}; + + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + + for (var i = 0; i < totalAttributes; i++) + { + var attribData = gl.getActiveAttrib(program, i); + var type = mapType(gl, attribData.type); + + attributes[attribData.name] = { + type:type, + size:mapSize(type), + location:gl.getAttribLocation(program, attribData.name), + //TODO - make an attribute object + pointer: pointer + }; + } + + return attributes; +}; + +var pointer = function(type, normalized, stride, start){ + // console.log(this.location) + gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +}; + +module.exports = extractAttributes; + +},{"./mapSize":20,"./mapType":21}],17:[function(require,module,exports){ +var mapType = require('./mapType'); +var defaultValue = require('./defaultValue'); + +/** + * Extracts the uniforms + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the uniforms from + * @return uniforms {Object} + */ +var extractUniforms = function(gl, program) +{ + var uniforms = {}; + + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + + for (var i = 0; i < totalUniforms; i++) + { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]/, ""); + var type = mapType(gl, uniformData.type ); + + uniforms[name] = { + type:type, + size:uniformData.size, + location:gl.getUniformLocation(program, name), + value:defaultValue(type, uniformData.size) + }; + } + + return uniforms; +}; + +module.exports = extractUniforms; + +},{"./defaultValue":15,"./mapType":21}],18:[function(require,module,exports){ +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param uniforms {Array} @mat ? + * @return attributes {Object} + */ +var generateUniformAccessObject = function(gl, uniformData) +{ + // this is the object we will be sending back. + // an object hierachy will be created for structs + var uniforms = {data:{}}; + + uniforms.gl = gl; + + var uniformKeys= Object.keys(uniformData); + + for (var i = 0; i < uniformKeys.length; i++) + { + var fullName = uniformKeys[i]; + + var nameTokens = fullName.split('.'); + var name = nameTokens[nameTokens.length - 1]; + + var uniformGroup = getUniformGroup(nameTokens, uniforms); + + var uniform = uniformData[fullName]; + uniformGroup.data[name] = uniform; + + uniformGroup.gl = gl; + + Object.defineProperty(uniformGroup, name, { + get: generateGetter(name), + set: generateSetter(name, uniform) + }); + } + + return uniforms; +}; + +var generateGetter = function(name) +{ + var template = getterTemplate.replace('%%', name); + return new Function(template); // jshint ignore:line +}; + +var generateSetter = function(name, uniform) +{ + var template = setterTemplate.replace(/%%/g, name); + var setTemplate; + + if(uniform.size === 1) + { + setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; + } + else + { + setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; + } + + if(setTemplate) + { + template += "\nthis.gl." + setTemplate + ";"; + } + + return new Function('value', template); // jshint ignore:line +}; + +var getUniformGroup = function(nameTokens, uniform) +{ + var cur = uniform; + + for (var i = 0; i < nameTokens.length - 1; i++) + { + var o = cur[nameTokens[i]] || {data:{}}; + cur[nameTokens[i]] = o; + cur = o; + } + + return cur; +}; + +var getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +var setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;' +].join('\n'); + + +var GLSL_TO_SINGLE_SETTERS = { + + 'float': 'uniform1f(location, value)', + + 'vec2': 'uniform2f(location, value[0], value[1])', + 'vec3': 'uniform3f(location, value[0], value[1], value[2])', + 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', + + 'int': 'uniform1i(location, value)', + 'ivec2': 'uniform2i(location, value[0], value[1])', + 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', + 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'bool': 'uniform1i(location, value)', + 'bvec2': 'uniform2i(location, value[0], value[1])', + 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', + 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'mat2': 'uniformMatrix2fv(location, false, value)', + 'mat3': 'uniformMatrix3fv(location, false, value)', + 'mat4': 'uniformMatrix4fv(location, false, value)', + + 'sampler2D':'uniform1i(location, value)' +}; + +var GLSL_TO_ARRAY_SETTERS = { + + 'float': 'uniform1fv(location, value)', + + 'vec2': 'uniform2fv(location, value)', + 'vec3': 'uniform3fv(location, value)', + 'vec4': 'uniform4fv(location, value)', + + 'int': 'uniform1iv(location, value)', + 'ivec2': 'uniform2iv(location, value)', + 'ivec3': 'uniform3iv(location, value)', + 'ivec4': 'uniform4iv(location, value)', + + 'bool': 'uniform1iv(location, value)', + 'bvec2': 'uniform2iv(location, value)', + 'bvec3': 'uniform3iv(location, value)', + 'bvec4': 'uniform4iv(location, value)', + + 'sampler2D':'uniform1iv(location, value)' +}; + +module.exports = generateUniformAccessObject; + +},{}],19:[function(require,module,exports){ +module.exports = { + compileProgram: require('./compileProgram'), + defaultValue: require('./defaultValue'), + extractAttributes: require('./extractAttributes'), + extractUniforms: require('./extractUniforms'), + generateUniformAccessObject: require('./generateUniformAccessObject'), + mapSize: require('./mapSize'), + mapType: require('./mapType') +}; +},{"./compileProgram":14,"./defaultValue":15,"./extractAttributes":16,"./extractUniforms":17,"./generateUniformAccessObject":18,"./mapSize":20,"./mapType":21}],20:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} + * @return {Number} + */ +var mapSize = function(type) +{ + return GLSL_TO_SIZE[type]; +}; + + +var GLSL_TO_SIZE = { + 'float': 1, + 'vec2': 2, + 'vec3': 3, + 'vec4': 4, + + 'int': 1, + 'ivec2': 2, + 'ivec3': 3, + 'ivec4': 4, + + 'bool': 1, + 'bvec2': 2, + 'bvec3': 3, + 'bvec4': 4, + + 'mat2': 4, + 'mat3': 9, + 'mat4': 16, + + 'sampler2D': 1 +}; + +module.exports = mapSize; + +},{}],21:[function(require,module,exports){ + + +var mapSize = function(gl, type) +{ + if(!GL_TABLE) + { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + + GL_TABLE = {}; + + for(var i = 0; i < typeNames.length; ++i) + { + var tn = typeNames[i]; + GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + } + } + + return GL_TABLE[type]; +}; + +var GL_TABLE = null; + +var GL_TO_GLSL_TYPES = { + 'FLOAT': 'float', + 'FLOAT_VEC2': 'vec2', + 'FLOAT_VEC3': 'vec3', + 'FLOAT_VEC4': 'vec4', + + 'INT': 'int', + 'INT_VEC2': 'ivec2', + 'INT_VEC3': 'ivec3', + 'INT_VEC4': 'ivec4', + + 'BOOL': 'bool', + 'BOOL_VEC2': 'bvec2', + 'BOOL_VEC3': 'bvec3', + 'BOOL_VEC4': 'bvec4', + + 'FLOAT_MAT2': 'mat2', + 'FLOAT_MAT3': 'mat3', + 'FLOAT_MAT4': 'mat4', + + 'SAMPLER_2D': 'sampler2D' +}; + +module.exports = mapSize; + +},{}],22:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) + +},{"_process":23}],23:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],24:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],25:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],26:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],27:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":25,"./encode":26}],28:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":29,"punycode":24,"querystring":27}],29:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],30:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _async = require('./async'); + +var async = _interopRequireWildcard(_async); + +var _Resource = require('./Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// some constants +var MAX_PROGRESS = 100; +var rgxExtractUrlHash = /(#[\w-]+)?$/; + +/** + * Manages the state and loading of multiple resources to load. + * + * @class + */ + +var Loader = function () { + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader() { + var _this = this; + + var baseUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var concurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; + + _classCallCheck(this, Loader); + + /** + * The base url for all resources loaded by this loader. + * + * @member {string} + */ + this.baseUrl = baseUrl; + + /** + * The progress percent of the loader going through the queue. + * + * @member {number} + */ + this.progress = 0; + + /** + * Loading state of the loader, true if it is currently loading resources. + * + * @member {boolean} + */ + this.loading = false; + + /** + * A querystring to append to every URL added to the loader. + * + * This should be a valid query string *without* the question-mark (`?`). The loader will + * also *not* escape values for you. Make sure to escape your parameters with + * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. + * + * @example + * + * ```js + * const loader = new Loader(); + * + * loader.defaultQueryString = 'user=me&password=secret'; + * + * // This will request 'image.png?user=me&password=secret' + * loader.add('image.png').load(); + * + * loader.reset(); + * + * // This will request 'image.png?v=1&user=me&password=secret' + * loader.add('iamge.png?v=1').load(); + * ``` + */ + this.defaultQueryString = ''; + + /** + * The middleware to run before loading each resource. + * + * @member {function[]} + */ + this._beforeMiddleware = []; + + /** + * The middleware to run after loading each resource. + * + * @member {function[]} + */ + this._afterMiddleware = []; + + /** + * The tracks the resources we are currently completing parsing for. + * + * @member {Resource[]} + */ + this._resourcesParsing = []; + + /** + * The `_loadResource` function bound with this object context. + * + * @private + * @member {function} + * @param {Resource} r - The resource to load + * @param {Function} d - The dequeue function + * @return {undefined} + */ + this._boundLoadResource = function (r, d) { + return _this._loadResource(r, d); + }; + + /** + * The resources waiting to be loaded. + * + * @private + * @member {Resource[]} + */ + this._queue = async.queue(this._boundLoadResource, concurrency); + + this._queue.pause(); + + /** + * All the resources for this loader keyed by name. + * + * @member {object} + */ + this.resources = {}; + + /** + * Dispatched once per loaded or errored resource. + * + * The callback looks like {@link Loader.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once per errored resource. + * + * The callback looks like {@link Loader.OnErrorSignal}. + * + * @member {Signal} + */ + this.onError = new _miniSignals2.default(); + + /** + * Dispatched once per loaded resource. + * + * The callback looks like {@link Loader.OnLoadSignal}. + * + * @member {Signal} + */ + this.onLoad = new _miniSignals2.default(); + + /** + * Dispatched when the loader begins to process the queue. + * + * The callback looks like {@link Loader.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched when the queued resources all load. + * + * The callback looks like {@link Loader.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * When the progress changes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnProgressSignal + * @param {Loader} loader - The loader the progress is advancing on. + * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance. + */ + + /** + * When an error occurrs the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnErrorSignal + * @param {Loader} loader - The loader the error happened in. + * @param {Resource} resource - The resource that caused the error. + */ + + /** + * When a load completes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnLoadSignal + * @param {Loader} loader - The loader that laoded the resource. + * @param {Resource} resource - The resource that has completed loading. + */ + + /** + * When the loader starts loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnStartSignal + * @param {Loader} loader - The loader that has started loading resources. + */ + + /** + * When the loader completes loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnCompleteSignal + * @param {Loader} loader - The loader that has finished loading resources. + */ + } + + /** + * Adds a resource (or multiple resources) to the loader queue. + * + * This function can take a wide variety of different parameters. The only thing that is always + * required the url to load. All the following will work: + * + * ```js + * loader + * // normal param syntax + * .add('key', 'http://...', function () {}) + * .add('http://...', function () {}) + * .add('http://...') + * + * // object syntax + * .add({ + * name: 'key2', + * url: 'http://...' + * }, function () {}) + * .add({ + * url: 'http://...' + * }, function () {}) + * .add({ + * name: 'key3', + * url: 'http://...' + * onComplete: function () {} + * }) + * .add({ + * url: 'https://...', + * onComplete: function () {}, + * crossOrigin: true + * }) + * + * // you can also pass an array of objects or urls or both + * .add([ + * { name: 'key4', url: 'http://...', onComplete: function () {} }, + * { url: 'http://...', onComplete: function () {} }, + * 'http://...' + * ]) + * + * // and you can use both params and options + * .add('key', 'http://...', { crossOrigin: true }, function () {}) + * .add('http://...', { crossOrigin: true }, function () {}); + * ``` + * + * @param {string} [name] - The name of the resource to load, if not passed the url is used. + * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @param {object} [options] - The options for the load. + * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should + * the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @param {function} [cb] - Function to call when this specific resource completes loading. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.add = function add(name, url, options, cb) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + + return this; + } + + // if an object is passed instead of params + if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') { + cb = url || name.callback || name.onComplete; + options = name; + url = name.url; + name = name.name || name.key || name.url; + } + + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + cb = options; + options = url; + url = name; + } + + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + cb = options; + options = null; + } + + // if loading already you can only add resources that have a parent. + if (this.loading && (!options || !options.parentResource)) { + throw new Error('Cannot add resources while the loader is running.'); + } + + // check if resource already exists. + if (this.resources[name]) { + throw new Error('Resource named "' + name + '" already exists.'); + } + + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + + // create the store the resource + this.resources[name] = new _Resource2.default(name, url, options); + + if (typeof cb === 'function') { + this.resources[name].onAfterMiddleware.once(cb); + } + + // if actively loading, make sure to adjust progress chunks for that parent and its children + if (this.loading) { + var parent = options.parentResource; + var incompleteChildren = []; + + for (var _i = 0; _i < parent.children.length; ++_i) { + if (!parent.children[_i].isComplete) { + incompleteChildren.push(parent.children[_i]); + } + } + + var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent + var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child + + parent.children.push(this.resources[name]); + parent.progressChunk = eachChunk; + + for (var _i2 = 0; _i2 < incompleteChildren.length; ++_i2) { + incompleteChildren[_i2].progressChunk = eachChunk; + } + + this.resources[name].progressChunk = eachChunk; + } + + // add the resource to the queue + this._queue.push(this.resources[name]); + + return this; + }; + + /** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * + * @method before + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.pre = function pre(fn) { + this._beforeMiddleware.push(fn); + + return this; + }; + + /** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * + * @alias use + * @method after + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.use = function use(fn) { + this._afterMiddleware.push(fn); + + return this; + }; + + /** + * Resets the queue of the loader to prepare for a new load. + * + * @return {Loader} Returns itself. + */ + + + Loader.prototype.reset = function reset() { + this.progress = 0; + this.loading = false; + + this._queue.kill(); + this._queue.pause(); + + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + + if (res._onLoadBinding) { + res._onLoadBinding.detach(); + } + + if (res.isLoading) { + res.abort(); + } + } + + this.resources = {}; + + return this; + }; + + /** + * Starts loading the queued resources. + * + * @param {function} [cb] - Optional callback that will be bound to the `complete` event. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.load = function load(cb) { + // register complete callback if they pass one + if (typeof cb === 'function') { + this.onComplete.once(cb); + } + + // if the queue has already started we are done here + if (this.loading) { + return this; + } + + // distribute progress chunks + var chunk = 100 / this._queue._tasks.length; + + for (var i = 0; i < this._queue._tasks.length; ++i) { + this._queue._tasks[i].data.progressChunk = chunk; + } + + // update loading state + this.loading = true; + + // notify of start + this.onStart.dispatch(this); + + // start loading + this._queue.resume(); + + return this; + }; + + /** + * Prepares a url for usage based on the configuration of this object + * + * @private + * @param {string} url - The url to prepare. + * @return {string} The prepared url. + */ + + + Loader.prototype._prepareUrl = function _prepareUrl(url) { + var parsedUrl = (0, _parseUri2.default)(url, { strictMode: true }); + var result = void 0; + + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { + result = url; + } + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + else if (this.baseUrl.length && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 && url.charAt(0) !== '/') { + result = this.baseUrl + '/' + url; + } else { + result = this.baseUrl + url; + } + + // if we need to add a default querystring, there is a bit more work + if (this.defaultQueryString) { + var hash = rgxExtractUrlHash.exec(result)[0]; + + result = result.substr(0, result.length - hash.length); + + if (result.indexOf('?') !== -1) { + result += '&' + this.defaultQueryString; + } else { + result += '?' + this.defaultQueryString; + } + + result += hash; + } + + return result; + }; + + /** + * Loads a single resource. + * + * @private + * @param {Resource} resource - The resource to load. + * @param {function} dequeue - The function to call when we need to dequeue this item. + */ + + + Loader.prototype._loadResource = function _loadResource(resource, dequeue) { + var _this2 = this; + + resource._dequeue = dequeue; + + // run before middleware + async.eachSeries(this._beforeMiddleware, function (fn, next) { + fn.call(_this2, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, function () { + if (resource.isComplete) { + _this2._onLoad(resource); + } else { + resource._onLoadBinding = resource.onComplete.once(_this2._onLoad, _this2); + resource.load(); + } + }); + }; + + /** + * Called once each resource has loaded. + * + * @private + */ + + + Loader.prototype._onComplete = function _onComplete() { + this.loading = false; + + this.onComplete.dispatch(this, this.resources); + }; + + /** + * Called each time a resources is loaded. + * + * @private + * @param {Resource} resource - The resource that was loaded + */ + + + Loader.prototype._onLoad = function _onLoad(resource) { + var _this3 = this; + + resource._onLoadBinding = null; + + // remove this resource from the async queue, and add it to our list of resources that are being parsed + resource._dequeue(); + this._resourcesParsing.push(resource); + + // run middleware, this *must* happen before dequeue so sub-assets get added properly + async.eachSeries(this._afterMiddleware, function (fn, next) { + fn.call(_this3, resource, next); + }, function () { + resource.onAfterMiddleware.dispatch(resource); + + _this3.progress += resource.progressChunk; + _this3.onProgress.dispatch(_this3, resource); + + if (resource.error) { + _this3.onError.dispatch(resource.error, _this3, resource); + } else { + _this3.onLoad.dispatch(_this3, resource); + } + + _this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1); + + // do completion check + if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) { + _this3.progress = MAX_PROGRESS; + _this3._onComplete(); + } + }); + }; + + return Loader; +}(); + +exports.default = Loader; + +},{"./Resource":31,"./async":32,"mini-signals":36,"parse-uri":37}],31:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// tests is CORS is supported in XHR, if not we need to use XDR +var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest())); +var tempAnchor = null; + +// some status constants +var STATUS_NONE = 0; +var STATUS_OK = 200; +var STATUS_EMPTY = 204; + +// noop +function _noop() {} /* empty */ + +/** + * Manages the state and loading of a resource and all child resources. + * + * @class + */ + +var Resource = function () { + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. + */ + Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) { + setExtMap(Resource._loadTypeMap, extname, loadType); + }; + + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ + + + Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); + }; + + /** + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass + * an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + */ + + + function Resource(name, url, options) { + _classCallCheck(this, Resource); + + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + + options = options || {}; + + /** + * The state flags of this resource. + * + * @member {number} + */ + this._flags = 0; + + // set data url flag, needs to be set early for some _determineX checks to work. + this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); + + /** + * The name of this resource. + * + * @member {string} + * @readonly + */ + this.name = name; + + /** + * The url used to load this resource. + * + * @member {string} + * @readonly + */ + this.url = url; + + /** + * The extension used to load this resource. + * + * @member {string} + * @readonly + */ + this.extension = this._getExtension(); + + /** + * The data that was loaded by the resource. + * + * @member {any} + */ + this.data = null; + + /** + * Is this request cross-origin? If unset, determined automatically. + * + * @member {string} + */ + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + + /** + * The method of loading to use for this resource. + * + * @member {Resource.LOAD_TYPE} + */ + this.loadType = options.loadType || this._determineLoadType(); + + /** + * The type used to load the resource via XHR. If unset, determined automatically. + * + * @member {string} + */ + this.xhrType = options.xhrType; + + /** + * Extra info for middleware, and controlling specifics about how the resource loads. + * + * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + * Meaning it will modify it as it sees fit. + * + * @member {object} + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources + * to. + */ + this.metadata = options.metadata || {}; + + /** + * The error that occurred while loading (if any). + * + * @member {Error} + * @readonly + */ + this.error = null; + + /** + * The XHR object that was used to load this resource. This is only set + * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * + * @member {XMLHttpRequest} + * @readonly + */ + this.xhr = null; + + /** + * The child resources this resource owns. + * + * @member {Resource[]} + * @readonly + */ + this.children = []; + + /** + * The resource type. + * + * @member {Resource.TYPE} + * @readonly + */ + this.type = Resource.TYPE.UNKNOWN; + + /** + * The progress chunk owned by this resource. + * + * @member {number} + * @readonly + */ + this.progressChunk = 0; + + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * + * @private + * @member {function} + */ + this._dequeue = _noop; + + /** + * Used a storage place for the on load binding used privately by the loader. + * + * @private + * @member {function} + */ + this._onLoadBinding = null; + + /** + * The `complete` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundComplete = this.complete.bind(this); + + /** + * The `_onError` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnError = this._onError.bind(this); + + /** + * The `_onProgress` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnProgress = this._onProgress.bind(this); + + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + this._boundXdrOnTimeout = this._xdrOnTimeout.bind(this); + + /** + * Dispatched when the resource beings to load. + * + * The callback looks like {@link Resource.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched each time progress of this resource load updates. + * Not all resources types and loader systems can support this event + * so sometimes it may not be available. If the resource + * is being loaded on a modern browser, using XHR, and the remote server + * properly sets Content-Length headers, then this will be available. + * + * The callback looks like {@link Resource.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once this resource has loaded, if there was an error it will + * be in the `error` property. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * Dispatched after this resource has had all the *after* middleware run on it. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onAfterMiddleware = new _miniSignals2.default(); + + /** + * When the resource starts to load. + * + * @memberof Resource + * @callback OnStartSignal + * @param {Resource} resource - The resource that the event happened on. + */ + + /** + * When the resource reports loading progress. + * + * @memberof Resource + * @callback OnProgressSignal + * @param {Resource} resource - The resource that the event happened on. + * @param {number} percentage - The progress of the load in the range [0, 1]. + */ + + /** + * When the resource finishes loading. + * + * @memberof Resource + * @callback OnCompleteSignal + * @param {Resource} resource - The resource that the event happened on. + */ + } + + /** + * Stores whether or not this url is a data url. + * + * @member {boolean} + * @readonly + */ + + + /** + * Marks the resource as complete. + * + */ + Resource.prototype.complete = function complete() { + // TODO: Clean this up in a wrapper or something...gross.... + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + + this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true); + this._setFlag(Resource.STATUS_FLAGS.LOADING, false); + + this.onComplete.dispatch(this); + }; + + /** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ + + + Resource.prototype.abort = function abort(message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + + // store error + this.error = new Error(message); + + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } else if (this.xdr) { + this.xdr.abort(); + } else if (this.data) { + // single source + if (this.data.src) { + this.data.src = Resource.EMPTY_GIF; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + + // done now. + this.complete(); + }; + + /** + * Kicks off loading of this resource. This method is asynchronous. + * + * @param {function} [cb] - Optional callback to call once the resource is loaded. + */ + + + Resource.prototype.load = function load(cb) { + var _this = this; + + if (this.isLoading) { + return; + } + + if (this.isComplete) { + if (cb) { + setTimeout(function () { + return cb(_this); + }, 1); + } + + return; + } else if (cb) { + this.onComplete.once(cb); + } + + this._setFlag(Resource.STATUS_FLAGS.LOADING, true); + + this.onStart.dispatch(this); + + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + + switch (this.loadType) { + case Resource.LOAD_TYPE.IMAGE: + this.type = Resource.TYPE.IMAGE; + this._loadElement('image'); + break; + + case Resource.LOAD_TYPE.AUDIO: + this.type = Resource.TYPE.AUDIO; + this._loadSourceElement('audio'); + break; + + case Resource.LOAD_TYPE.VIDEO: + this.type = Resource.TYPE.VIDEO; + this._loadSourceElement('video'); + break; + + case Resource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } else { + this._loadXhr(); + } + break; + } + }; + + /** + * Checks if the flag is set. + * + * @private + * @param {number} flag - The flag to check. + * @return {boolean} True if the flag is set. + */ + + + Resource.prototype._hasFlag = function _hasFlag(flag) { + return !!(this._flags & flag); + }; + + /** + * (Un)Sets the flag. + * + * @private + * @param {number} flag - The flag to (un)set. + * @param {boolean} value - Whether to set or (un)set the flag. + */ + + + Resource.prototype._setFlag = function _setFlag(flag, value) { + this._flags = value ? this._flags | flag : this._flags & ~flag; + }; + + /** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadElement = function _loadElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'image' && typeof window.Image !== 'undefined') { + this.data = new Image(); + } else { + this.data = document.createElement(type); + } + + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + }; + + /** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadSourceElement = function _loadSourceElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'audio' && typeof window.Audio !== 'undefined') { + this.data = new Audio(); + } else { + this.data = document.createElement(type); + } + + if (this.data === null) { + this.abort('Unsupported element: ' + type); + + return; + } + + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } else if (Array.isArray(this.url)) { + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i])); + } + } else { + this.data.appendChild(this._createSource(type, this.url)); + } + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + + this.data.load(); + }; + + /** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ + + + Resource.prototype._loadXhr = function _loadXhr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xhr = this.xhr = new XMLHttpRequest(); + + // set the request type and url + xhr.open('GET', this.url, true); + + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; + } else { + xhr.responseType = this.xhrType; + } + + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + + xhr.send(); + }; + + /** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ + + + Resource.prototype._loadXdr = function _loadXdr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xdr = this.xhr = new XDomainRequest(); + + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = 5000; + + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXdrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + + xdr.open('GET', this.url, true); + + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { + return xdr.send(); + }, 1); + }; + + /** + * Creates a source used in loading via an element. + * + * @private + * @param {string} type - The element type (video or audio). + * @param {string} url - The source URL to load from. + * @param {string} [mime] - The mime type of the video + * @return {HTMLSourceElement} The source element. + */ + + + Resource.prototype._createSource = function _createSource(type, url, mime) { + if (!mime) { + mime = type + '/' + url.substr(url.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = url; + source.type = mime; + + return source; + }; + + /** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ + + + Resource.prototype._onError = function _onError(event) { + this.abort('Failed to load element using: ' + event.target.nodeName); + }; + + /** + * Called if a load progress event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ + + + Resource.prototype._onProgress = function _onProgress(event) { + if (event && event.lengthComputable) { + this.onProgress.dispatch(this, event.loaded / event.total); + } + }; + + /** + * Called if an error event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestErrorEvent|Event} event - Error event. + */ + + + Resource.prototype._xhrOnError = function _xhrOnError() { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"'); + }; + + /** + * Called if an abort event fires for xhr. + * + * @private + * @param {XMLHttpRequestAbortEvent} event - Abort Event + */ + + + Resource.prototype._xhrOnAbort = function _xhrOnAbort() { + this.abort(reqType(this.xhr) + ' Request was aborted by the user.'); + }; + + /** + * Called if a timeout event fires for xdr. + * + * @private + * @param {Event} event - Timeout event. + */ + + + Resource.prototype._xdrOnTimeout = function _xdrOnTimeout() { + this.abort(reqType(this.xhr) + ' Request timed out.'); + }; + + /** + * Called when data successfully loads from an xhr/xdr request. + * + * @private + * @param {XMLHttpRequestLoadEvent|Event} event - Load event + */ + + + Resource.prototype._xhrOnLoad = function _xhrOnLoad() { + var xhr = this.xhr; + var status = typeof xhr.status === 'undefined' ? xhr.status : STATUS_OK; // XDR has no `.status`, assume 200. + + // status can be 0 when using the `file://` protocol so we also check if a response is set + if (status === STATUS_OK || status === STATUS_EMPTY || status === STATUS_NONE && xhr.responseText.length > 0) { + // if text, just return it + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { + this.data = xhr.responseText; + this.type = Resource.TYPE.TEXT; + } + // if json, parse into json object + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(xhr.responseText); + this.type = Resource.TYPE.JSON; + } catch (e) { + this.abort('Error trying to parse loaded json: ' + e); + + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (window.DOMParser) { + var domparser = new DOMParser(); + + this.data = domparser.parseFromString(xhr.responseText, 'text/xml'); + } else { + var div = document.createElement('div'); + + div.innerHTML = xhr.responseText; + + this.data = div; + } + + this.type = Resource.TYPE.XML; + } catch (e) { + this.abort('Error trying to parse loaded xml: ' + e); + + return; + } + } + // other types just return the response + else { + this.data = xhr.response || xhr.responseText; + } + } else { + this.abort('[' + xhr.status + '] ' + xhr.statusText + ': ' + xhr.responseURL); + + return; + } + + this.complete(); + }; + + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * + * @private + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ + + + Resource.prototype._determineCrossOrigin = function _determineCrossOrigin(url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = (0, _parseUri2.default)(tempAnchor.href, { strictMode: true }); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + var protocol = url.protocol ? url.protocol + ':' : ''; + + // if cross origin + if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; + }; + + /** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. + */ + + + Resource.prototype._determineXhrType = function _determineXhrType() { + return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT; + }; + + /** + * Determines the loadType of a resource based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.LOAD_TYPE} The loadType to use. + */ + + + Resource.prototype._determineLoadType = function _determineLoadType() { + return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR; + }; + + /** + * Extracts the extension (sans '.') of the file being loaded by the resource. + * + * @private + * @return {string} The extension. + */ + + + Resource.prototype._getExtension = function _getExtension() { + var url = this.url; + var ext = ''; + + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } else { + var queryStart = url.indexOf('?'); + + if (queryStart !== -1) { + url = url.substring(0, queryStart); + } + + ext = url.substring(url.lastIndexOf('.') + 1); + } + + return ext.toLowerCase(); + }; + + /** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * + * @private + * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. + * @return {string} The mime type to use. + */ + + + Resource.prototype._getMimeFromXhrType = function _getMimeFromXhrType(type) { + switch (type) { + case Resource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + + case Resource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + + case Resource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + + case Resource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + + case Resource.XHR_RESPONSE_TYPE.DEFAULT: + case Resource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + + } + }; + + _createClass(Resource, [{ + key: 'isDataUrl', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL); + } + + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isComplete', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE); + } + + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isLoading', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.LOADING); + } + }]); + + return Resource; +}(); + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ + + +exports.default = Resource; +Resource.STATUS_FLAGS = { + NONE: 0, + DATA_URL: 1 << 0, + COMPLETE: 1 << 1, + LOADING: 1 << 2 +}; + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ +Resource.TYPE = { + UNKNOWN: 0, + JSON: 1, + XML: 2, + IMAGE: 3, + AUDIO: 4, + VIDEO: 5, + TEXT: 6 +}; + +/** + * The types of loading a resource can use. + * + * @static + * @readonly + * @enum {number} + */ +Resource.LOAD_TYPE = { + /** Uses XMLHttpRequest to load the resource. */ + XHR: 1, + /** Uses an `Image` object to load the resource. */ + IMAGE: 2, + /** Uses an `Audio` object to load the resource. */ + AUDIO: 3, + /** Uses a `Video` object to load the resource. */ + VIDEO: 4 +}; + +/** + * The XHR ready states, used internally. + * + * @static + * @readonly + * @enum {string} + */ +Resource.XHR_RESPONSE_TYPE = { + /** string */ + DEFAULT: 'text', + /** ArrayBuffer */ + BUFFER: 'arraybuffer', + /** Blob */ + BLOB: 'blob', + /** Document */ + DOCUMENT: 'document', + /** Object */ + JSON: 'json', + /** String */ + TEXT: 'text' +}; + +Resource._loadTypeMap = { + // images + gif: Resource.LOAD_TYPE.IMAGE, + png: Resource.LOAD_TYPE.IMAGE, + bmp: Resource.LOAD_TYPE.IMAGE, + jpg: Resource.LOAD_TYPE.IMAGE, + jpeg: Resource.LOAD_TYPE.IMAGE, + tif: Resource.LOAD_TYPE.IMAGE, + tiff: Resource.LOAD_TYPE.IMAGE, + webp: Resource.LOAD_TYPE.IMAGE, + tga: Resource.LOAD_TYPE.IMAGE, + svg: Resource.LOAD_TYPE.IMAGE, + 'svg+xml': Resource.LOAD_TYPE.IMAGE, // for SVG data urls + + // audio + mp3: Resource.LOAD_TYPE.AUDIO, + ogg: Resource.LOAD_TYPE.AUDIO, + wav: Resource.LOAD_TYPE.AUDIO, + + // videos + mp4: Resource.LOAD_TYPE.VIDEO, + webm: Resource.LOAD_TYPE.VIDEO +}; + +Resource._xhrTypeMap = { + // xml + xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. + // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, + // this should probably be fine. + tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // images + gif: Resource.XHR_RESPONSE_TYPE.BLOB, + png: Resource.XHR_RESPONSE_TYPE.BLOB, + bmp: Resource.XHR_RESPONSE_TYPE.BLOB, + jpg: Resource.XHR_RESPONSE_TYPE.BLOB, + jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, + tif: Resource.XHR_RESPONSE_TYPE.BLOB, + tiff: Resource.XHR_RESPONSE_TYPE.BLOB, + webp: Resource.XHR_RESPONSE_TYPE.BLOB, + tga: Resource.XHR_RESPONSE_TYPE.BLOB, + + // json + json: Resource.XHR_RESPONSE_TYPE.JSON, + + // text + text: Resource.XHR_RESPONSE_TYPE.TEXT, + txt: Resource.XHR_RESPONSE_TYPE.TEXT, + + // fonts + ttf: Resource.XHR_RESPONSE_TYPE.BUFFER, + otf: Resource.XHR_RESPONSE_TYPE.BUFFER +}; + +// We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif +Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; + +/** + * Quick helper to set a value on one of the extension maps. Ensures there is no + * dot at the start of the extension. + * + * @ignore + * @param {object} map - The map to set on. + * @param {string} extname - The extension (or key) to set. + * @param {number} val - The value to set. + */ +function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + + if (!extname) { + return; + } + + map[extname] = val; +} + +/** + * Quick helper to get string xhr type. + * + * @ignore + * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. + * @return {string} The type. + */ +function reqType(xhr) { + return xhr.toString().replace('object ', ''); +} + +},{"mini-signals":36,"parse-uri":37}],32:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.eachSeries = eachSeries; +exports.queue = queue; +/** + * Smaller version of the async library constructs. + * + */ +function _noop() {} /* empty */ + +/** + * Iterates an array in series. + * + * @param {*[]} array - Array to iterate. + * @param {function} iterator - Function to call for each element. + * @param {function} callback - Function to call when done, or on error. + */ +function eachSeries(array, iterator, callback) { + var i = 0; + var len = array.length; + + (function next(err) { + if (err || i === len) { + if (callback) { + callback(err); + } + + return; + } + + iterator(array[i++], next); + })(); +} + +/** + * Ensures a function is only called once. + * + * @param {function} fn - The function to wrap. + * @return {function} The wrapping function. + */ +function onlyOnce(fn) { + return function onceWrapper() { + if (fn === null) { + throw new Error('Callback was already called.'); + } + + var callFn = fn; + + fn = null; + callFn.apply(this, arguments); + }; +} + +/** + * Async queue implementation, + * + * @param {function} worker - The worker function to call for each task. + * @param {number} concurrency - How many workers to run in parrallel. + * @return {*} The async queue object. + */ +function queue(worker, concurrency) { + if (concurrency == null) { + // eslint-disable-line no-eq-null,eqeqeq + concurrency = 1; + } else if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + + var workers = 0; + var q = { + _tasks: [], + concurrency: concurrency, + saturated: _noop, + unsaturated: _noop, + buffer: concurrency / 4, + empty: _noop, + drain: _noop, + error: _noop, + started: false, + paused: false, + push: function push(data, callback) { + _insert(data, false, callback); + }, + kill: function kill() { + workers = 0; + q.drain = _noop; + q.started = false; + q._tasks = []; + }, + unshift: function unshift(data, callback) { + _insert(data, true, callback); + }, + process: function process() { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var task = q._tasks.shift(); + + if (q._tasks.length === 0) { + q.empty(); + } + + workers += 1; + + if (workers === q.concurrency) { + q.saturated(); + } + + worker(task.data, onlyOnce(_next(task))); + } + }, + length: function length() { + return q._tasks.length; + }, + running: function running() { + return workers; + }, + idle: function idle() { + return q._tasks.length + workers === 0; + }, + pause: function pause() { + if (q.paused === true) { + return; + } + + q.paused = true; + }, + resume: function resume() { + if (q.paused === false) { + return; + } + + q.paused = false; + + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= q.concurrency; w++) { + q.process(); + } + } + }; + + function _insert(data, insertAtFront, callback) { + if (callback != null && typeof callback !== 'function') { + // eslint-disable-line no-eq-null,eqeqeq + throw new Error('task callback must be a function'); + } + + q.started = true; + + if (data == null && q.idle()) { + // eslint-disable-line no-eq-null,eqeqeq + // call drain immediately if there are no tasks + setTimeout(function () { + return q.drain(); + }, 1); + + return; + } + + var item = { + data: data, + callback: typeof callback === 'function' ? callback : _noop + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + setTimeout(function () { + return q.process(); + }, 1); + } + + function _next(task) { + return function next() { + workers -= 1; + + task.callback.apply(task, arguments); + + if (arguments[0] != null) { + // eslint-disable-line no-eq-null,eqeqeq + q.error(arguments[0], task.data); + } + + if (workers <= q.concurrency - q.buffer) { + q.unsaturated(); + } + + if (q.idle()) { + q.drain(); + } + + q.process(); + }; + } + + return q; +} + +},{}],33:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.encodeBinary = encodeBinary; +var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +function encodeBinary(input) { + var output = ''; + var inx = 0; + + while (inx < input.length) { + // Fill byte buffer array + var bytebuffer = [0, 0, 0]; + var encodedCharIndexes = [0, 0, 0, 0]; + + for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } else { + bytebuffer[jnx] = 0; + } + } + + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4; + + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6; + + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + + // Determine whether padding happened, and adjust accordingly + var paddingBytes = inx - (input.length - 1); + + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + + default: + break; // No padding - proceed + } + + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) { + output += _keyStr.charAt(encodedCharIndexes[_jnx]); + } + } + + return output; +} + +},{}],34:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Loader = require('./Loader'); + +var _Loader2 = _interopRequireDefault(_Loader); + +var _Resource = require('./Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +var _async = require('./async'); + +var async = _interopRequireWildcard(_async); + +var _b = require('./b64'); + +var b64 = _interopRequireWildcard(_b); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +_Loader2.default.Resource = _Resource2.default; +_Loader2.default.async = async; +_Loader2.default.base64 = b64; + +// export manually, and also as default +module.exports = _Loader2.default; // eslint-disable-line no-undef +exports.default = _Loader2.default; + +},{"./Loader":30,"./Resource":31,"./async":32,"./b64":33}],35:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +exports.blobMiddlewareFactory = blobMiddlewareFactory; + +var _Resource = require('../../Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +var _b = require('../../b64'); + +var _b2 = _interopRequireDefault(_b); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Url = window.URL || window.webkitURL; + +// a middleware for transforming XHR loaded Blobs into more useful objects +function blobMiddlewareFactory() { + return function blobMiddleware(resource, next) { + if (!resource.data) { + next(); + + return; + } + + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === _Resource2.default.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!window.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = 'data:' + type + ';base64,' + _b2.default.encodeBinary(resource.xhr.responseText); + + resource.type = _Resource2.default.TYPE.IMAGE; + + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + + next(); + }; + + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var _ret = function () { + var src = Url.createObjectURL(resource.data); + + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src; + + resource.type = _Resource2.default.TYPE.IMAGE; + + // cleanup the no longer used blob after the image loads + // TODO: Is this correct? Will the image be invalid after revoking? + resource.data.onload = function () { + Url.revokeObjectURL(src); + resource.data.onload = null; + + next(); + }; + + // next will be called on load. + return { + v: void 0 + }; + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + } + + next(); + }; +} + +},{"../../Resource":31,"../../b64":33}],36:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + +var MiniSignalBinding = (function () { + function MiniSignalBinding(fn, once, thisArg) { + if (once === undefined) once = false; + + _classCallCheck(this, MiniSignalBinding); + + this._fn = fn; + this._once = once; + this._thisArg = thisArg; + this._next = this._prev = this._owner = null; + } + + _createClass(MiniSignalBinding, [{ + key: 'detach', + value: function detach() { + if (this._owner === null) return false; + this._owner.detach(this); + return true; + } + }]); + + return MiniSignalBinding; +})(); + +function _addMiniSignalBinding(self, node) { + if (!self._head) { + self._head = node; + self._tail = node; + } else { + self._tail._next = node; + node._prev = self._tail; + self._tail = node; + } + + node._owner = self; + + return node; +} + +var MiniSignal = (function () { + function MiniSignal() { + _classCallCheck(this, MiniSignal); + + this._head = this._tail = undefined; + } + + _createClass(MiniSignal, [{ + key: 'handlers', + value: function handlers() { + var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; + + var node = this._head; + + if (exists) return !!node; + + var ee = []; + + while (node) { + ee.push(node); + node = node._next; + } + + return ee; + } + }, { + key: 'has', + value: function has(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.'); + } + + return node._owner === this; + } + }, { + key: 'dispatch', + value: function dispatch() { + var node = this._head; + + if (!node) return false; + + while (node) { + if (node._once) this.detach(node); + node._fn.apply(node._thisArg, arguments); + node = node._next; + } + + return true; + } + }, { + key: 'add', + value: function add(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#add(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg)); + } + }, { + key: 'once', + value: function once(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#once(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg)); + } + }, { + key: 'detach', + value: function detach(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.'); + } + if (node._owner !== this) return this; + + if (node._prev) node._prev._next = node._next; + if (node._next) node._next._prev = node._prev; + + if (node === this._head) { + this._head = node._next; + if (node._next === null) { + this._tail = null; + } + } else if (node === this._tail) { + this._tail = node._prev; + this._tail._next = null; + } + + node._owner = null; + return this; + } + }, { + key: 'detachAll', + value: function detachAll() { + var node = this._head; + if (!node) return this; + + this._head = this._tail = null; + + while (node) { + node._owner = null; + node = node._next; + } + return this; + } + }]); + + return MiniSignal; +})(); + +MiniSignal.MiniSignalBinding = MiniSignalBinding; + +exports['default'] = MiniSignal; +module.exports = exports['default']; + +},{}],37:[function(require,module,exports){ +'use strict' + +module.exports = function parseURI (str, opts) { + opts = opts || {} + + var o = { + key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], + q: { + name: 'queryKey', + parser: /(?:^|&)([^&=]*)=?([^&]*)/g + }, + parser: { + strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, + loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ + } + } + + var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str) + var uri = {} + var i = 14 + + while (i--) uri[o.key[i]] = m[i] || '' + + uri[o.q.name] = {} + uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { + if ($1) uri[o.q.name][$1] = $2 + }) + + return uri +} + +},{}],38:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +var _accessibleTarget = require('./accessibleTarget'); + +var _accessibleTarget2 = _interopRequireDefault(_accessibleTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// add some extra variables to the container.. +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _accessibleTarget2.default); + +var KEY_CODE_TAB = 9; + +var DIV_TOUCH_SIZE = 100; +var DIV_TOUCH_POS_X = 0; +var DIV_TOUCH_POS_Y = 0; +var DIV_TOUCH_ZINDEX = 2; + +var DIV_HOOK_SIZE = 1; +var DIV_HOOK_POS_X = -1000; +var DIV_HOOK_POS_Y = -1000; +var DIV_HOOK_ZINDEX = 2; + +/** + * The Accessibility manager reacreates the ability to tab and and have content read by screen + * readers. This is very important as it can possibly help people with disabilities access pixi + * content. + * + * Much like interaction any DisplayObject can be made accessible. This manager will map the + * events as if the mouse was being used, minimizing the efferot required to implement. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.accessibility + * + * @class + * @memberof PIXI.accessibility + */ + +var AccessibilityManager = function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + _classCallCheck(this, AccessibilityManager); + + if ((_ismobilejs2.default.tablet || _ismobilejs2.default.phone) && !navigator.isCocoonJS) { + this.createTouchHook(); + } + + // first we create a div that will sit over the pixi element. This is where the div overlays will go. + var div = document.createElement('div'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + 'px'; + div.style.left = DIV_TOUCH_POS_Y + 'px'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + + /** + * This is the dom element that will sit over the pixi element. This is where the div overlays will go. + * + * @type {HTMLElement} + * @private + */ + this.div = div; + + /** + * A simple pool for storing divs. + * + * @type {*} + * @private + */ + this.pool = []; + + /** + * This is a tick used to check if an object is no longer being rendered. + * + * @type {Number} + * @private + */ + this.renderId = 0; + + /** + * Setting this to true will visually show the divs + * + * @type {boolean} + */ + this.debug = false; + + /** + * The renderer this accessibility manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * The array of currently active accessible items. + * + * @member {Array<*>} + * @private + */ + this.children = []; + + /** + * pre-bind the functions + * + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + + /** + * stores the state of the manager. If there are no accessible objects or the mouse is moving the will be false. + * + * @member {Array<*>} + * @private + */ + this.isActive = false; + this.isMobileAccessabillity = false; + + // let listen for tab.. once pressed we can fire up and show the accessibility layer + window.addEventListener('keydown', this._onKeyDown, false); + } + + /** + * Creates the touch hooks. + * + */ + + + AccessibilityManager.prototype.createTouchHook = function createTouchHook() { + var _this = this; + + var hookDiv = document.createElement('button'); + + hookDiv.style.width = DIV_HOOK_SIZE + 'px'; + hookDiv.style.height = DIV_HOOK_SIZE + 'px'; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + 'px'; + hookDiv.style.left = DIV_HOOK_POS_Y + 'px'; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX; + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'HOOK DIV'; + + hookDiv.addEventListener('focus', function () { + _this.isMobileAccessabillity = true; + _this.activate(); + document.body.removeChild(hookDiv); + }); + + document.body.appendChild(hookDiv); + }; + + /** + * Activating will cause the Accessibility layer to be shown. This is called when a user + * preses the tab key + * + * @private + */ + + + AccessibilityManager.prototype.activate = function activate() { + if (this.isActive) { + return; + } + + this.isActive = true; + + window.document.addEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown, false); + + this.renderer.on('postrender', this.update, this); + + if (this.renderer.view.parentNode) { + this.renderer.view.parentNode.appendChild(this.div); + } + }; + + /** + * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves + * the mouse + * + * @private + */ + + + AccessibilityManager.prototype.deactivate = function deactivate() { + if (!this.isActive || this.isMobileAccessabillity) { + return; + } + + this.isActive = false; + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.addEventListener('keydown', this._onKeyDown, false); + + this.renderer.off('postrender', this.update); + + if (this.div.parentNode) { + this.div.parentNode.removeChild(this.div); + } + }; + + /** + * This recursive function will run throught he scene graph and add any new accessible objects to the DOM layer. + * + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + + + AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects(displayObject) { + if (!displayObject.visible) { + return; + } + + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + + displayObject.renderId = this.renderId; + } + + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + this.updateAccessibleObjects(children[i]); + } + }; + + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * + * @private + */ + + + AccessibilityManager.prototype.update = function update() { + if (!this.renderer.renderingToScreen) { + return; + } + + // update children... + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + + var rect = this.renderer.view.getBoundingClientRect(); + var sx = rect.width / this.renderer.width; + var sy = rect.height / this.renderer.height; + + var div = this.div; + + div.style.left = rect.left + 'px'; + div.style.top = rect.top + 'px'; + div.style.width = this.renderer.width + 'px'; + div.style.height = this.renderer.height + 'px'; + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + + core.utils.removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + + i--; + + if (this.children.length === 0) { + this.deactivate(); + } + } else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + + if (child.hitArea) { + div.style.left = (wt.tx + hitArea.x * wt.a) * sx + 'px'; + div.style.top = (wt.ty + hitArea.y * wt.d) * sy + 'px'; + + div.style.width = hitArea.width * wt.a * sx + 'px'; + div.style.height = hitArea.height * wt.d * sy + 'px'; + } else { + hitArea = child.getBounds(); + + this.capHitArea(hitArea); + + div.style.left = hitArea.x * sx + 'px'; + div.style.top = hitArea.y * sy + 'px'; + + div.style.width = hitArea.width * sx + 'px'; + div.style.height = hitArea.height * sy + 'px'; + } + } + } + + // increment the render id.. + this.renderId++; + }; + + /** + * TODO: docs. + * + * @param {Rectangle} hitArea - TODO docs + */ + + + AccessibilityManager.prototype.capHitArea = function capHitArea(hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + + if (hitArea.x + hitArea.width > this.renderer.width) { + hitArea.width = this.renderer.width - hitArea.x; + } + + if (hitArea.y + hitArea.height > this.renderer.height) { + hitArea.height = this.renderer.height - hitArea.y; + } + }; + + /** + * Adds a DisplayObject to the accessibility manager + * + * @private + * @param {DisplayObject} displayObject - The child to make accessible. + */ + + + AccessibilityManager.prototype.addChild = function addChild(displayObject) { + // this.activate(); + + var div = this.pool.pop(); + + if (!div) { + div = document.createElement('button'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + div.style.borderStyle = 'none'; + + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + + if (displayObject.accessibleTitle) { + div.title = displayObject.accessibleTitle; + } else if (!displayObject.accessibleTitle && !displayObject.accessibleHint) { + div.title = 'displayObject ' + this.tabIndex; + } + + if (displayObject.accessibleHint) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + + // + + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + + /** + * Maps the div button press to pixi's InteractionManager (click) + * + * @private + * @param {MouseEvent} e - The click event. + */ + + + AccessibilityManager.prototype._onClick = function _onClick(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixis InteractionManager (mouseover) + * + * @private + * @param {FocusEvent} e - The focus event. + */ + + + AccessibilityManager.prototype._onFocus = function _onFocus(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixis InteractionManager (mouseout) + * + * @private + * @param {FocusEvent} e - The focusout event. + */ + + + AccessibilityManager.prototype._onFocusOut = function _onFocusOut(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); + }; + + /** + * Is called when a key is pressed + * + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + + + AccessibilityManager.prototype._onKeyDown = function _onKeyDown(e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + + this.activate(); + }; + + /** + * Is called when the mouse moves across the renderer element + * + * @private + */ + + + AccessibilityManager.prototype._onMouseMove = function _onMouseMove() { + this.deactivate(); + }; + + /** + * Destroys the accessibility manager + * + */ + + + AccessibilityManager.prototype.destroy = function destroy() { + this.div = null; + + for (var i = 0; i < this.children.length; i++) { + this.children[i].div = null; + } + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.removeEventListener('keydown', this._onKeyDown); + + this.pool = null; + this.children = null; + this.renderer = null; + }; + + return AccessibilityManager; +}(); + +exports.default = AccessibilityManager; + + +core.WebGLRenderer.registerPlugin('accessibility', AccessibilityManager); +core.CanvasRenderer.registerPlugin('accessibility', AccessibilityManager); + +},{"../core":63,"./accessibleTarget":39,"ismobilejs":4}],39:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Default property values of accessible objects + * used by {@link PIXI.accessibility.AccessibilityManager}. + * + * @function accessibleTarget + * @memberof PIXI.accessibility + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibility.accessibleTarget + * ); + */ +exports.default = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * + * @member {boolean} + */ + accessible: false, + + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * + * @member {string} + */ + accessibleTitle: null, + + /** + * Sets the aria-label attribute of the shadow div + * + * @member {string} + */ + accessibleHint: null, + + /** + * @todo Needs docs. + */ + tabIndex: 0, + + /** + * @todo Needs docs. + */ + _accessibleActive: false, + + /** + * @todo Needs docs. + */ + _accessibleDiv: false +}; + +},{}],40:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _accessibleTarget = require('./accessibleTarget'); + +Object.defineProperty(exports, 'accessibleTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_accessibleTarget).default; + } +}); + +var _AccessibilityManager = require('./AccessibilityManager'); + +Object.defineProperty(exports, 'AccessibilityManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AccessibilityManager).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./AccessibilityManager":38,"./accessibleTarget":39}],41:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +var _Container = require('./display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _ticker = require('./ticker'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Convenience class to create a new PIXI application. + * This class automatically creates the renderer, ticker + * and root container. + * + * @example + * // Create the application + * const app = new PIXI.Application(); + * + * // Add the view to the DOM + * document.body.appendChild(app.view); + * + * // ex, add display objects + * app.stage.addChild(PIXI.Sprite.fromImage('something.png')); + * + * @class + * @memberof PIXI + */ +var Application = function () { + /** + * @param {number} [width=800] - the width of the renderers view + * @param {number} [height=600] - the height of the renderers view + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [noWebGL=false] - prevents selection of WebGL renderer, even if such is present + * @param {boolean} [options.legacy=false] - If true Pixi will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering try setting this to true. + * @param {boolean} [useSharedTicker=false] - `true` to use PIXI.ticker.shared, `false` to create new ticker. + */ + function Application(width, height, options, noWebGL) { + var useSharedTicker = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; + + _classCallCheck(this, Application); + + /** + * WebGL renderer if available, otherwise CanvasRenderer + * @member {PIXI.WebGLRenderer|PIXI.CanvasRenderer} + */ + this.renderer = (0, _autoDetectRenderer.autoDetectRenderer)(width, height, options, noWebGL); + + /** + * The root display container that's rendered. + * @member {PIXI.Container} + */ + this.stage = new _Container2.default(); + + /** + * Internal reference to the ticker + * @member {PIXI.ticker.Ticker} + * @private + */ + this._ticker = null; + + /** + * Ticker for doing render updates. + * @member {PIXI.ticker.Ticker} + * @default PIXI.ticker.shared + */ + this.ticker = useSharedTicker ? _ticker.shared : new _ticker.Ticker(); + + // Start the rendering + this.start(); + } + + /** + * Render the current stage. + */ + Application.prototype.render = function render() { + this.renderer.render(this.stage); + }; + + /** + * Convenience method for stopping the render. + */ + + + Application.prototype.stop = function stop() { + this._ticker.stop(); + }; + + /** + * Convenience method for starting the render. + */ + + + Application.prototype.start = function start() { + this._ticker.start(); + }; + + /** + * Reference to the renderer's canvas element. + * @member {HTMLCanvasElement} + * @readonly + */ + + + /** + * Destroy and don't use after this. + * @param {Boolean} [removeView=false] Automatically remove canvas from DOM. + */ + Application.prototype.destroy = function destroy(removeView) { + this.stop(); + this.ticker = null; + + this.stage.destroy(); + this.stage = null; + + this.renderer.destroy(removeView); + this.renderer = null; + }; + + _createClass(Application, [{ + key: 'ticker', + set: function set(ticker) // eslint-disable-line require-jsdoc + { + if (this._ticker) { + this._ticker.remove(this.render, this); + } + this._ticker = ticker; + if (ticker) { + ticker.add(this.render, this); + } + }, + get: function get() // eslint-disable-line require-jsdoc + { + return this._ticker; + } + }, { + key: 'view', + get: function get() { + return this.renderer.view; + } + + /** + * Reference to the renderer's screen rectangle. Its safe to use as filterArea or hitArea for whole screen + * @member {PIXI.Rectangle} + * @readonly + */ + + }, { + key: 'screen', + get: function get() { + return this.renderer.screen; + } + }]); + + return Application; +}(); + +exports.default = Application; + +},{"./autoDetectRenderer":43,"./display/Container":46,"./ticker":116}],42:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function checkPrecision(src, def) { + if (src instanceof Array) { + if (src[0].substring(0, 9) !== 'precision') { + var copy = src.slice(0); + + copy.unshift('precision ' + def + ' float;'); + + return copy; + } + } else if (src.substring(0, 9) !== 'precision') { + return 'precision ' + def + ' float;\n' + src; + } + + return src; +} + +/** + * Wrapper class, webGL Shader for Pixi. + * Adds precision string if vertexSrc or fragmentSrc have no mention of it. + * + * @class + * @extends GLShader + * @memberof PIXI + */ + +var Shader = function (_GLShader) { + _inherits(Shader, _GLShader); + + /** + * + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + * @param {string|string[]} vertexSrc - The vertex shader source as an array of strings. + * @param {string|string[]} fragmentSrc - The fragment shader source as an array of strings. + */ + function Shader(gl, vertexSrc, fragmentSrc) { + _classCallCheck(this, Shader); + + return _possibleConstructorReturn(this, _GLShader.call(this, gl, checkPrecision(vertexSrc, _settings2.default.PRECISION_VERTEX), checkPrecision(fragmentSrc, _settings2.default.PRECISION_FRAGMENT))); + } + + return Shader; +}(_pixiGlCore.GLShader); + +exports.default = Shader; + +},{"./settings":99,"pixi-gl-core":12}],43:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = autoDetectRenderer; + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by + * the browser then this function will return a canvas renderer + * + * @memberof PIXI + * @function autoDetectRenderer + * @param {number} [width=800] - the width of the renderers view + * @param {number} [height=600] - the height of the renderers view + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [noWebGL=false] - prevents selection of WebGL renderer, even if such is present + * @return {PIXI.WebGLRenderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ +function autoDetectRenderer() { + var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 800; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 600; + var options = arguments[2]; + var noWebGL = arguments[3]; + + if (!noWebGL && utils.isWebGLSupported()) { + return new _WebGLRenderer2.default(width, height, options); + } + + return new _CanvasRenderer2.default(width, height, options); +} + +},{"./renderers/canvas/CanvasRenderer":75,"./renderers/webgl/WebGLRenderer":82,"./utils":120}],44:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * String of the current PIXI version. + * + * @static + * @constant + * @memberof PIXI + * @name VERSION + * @type {string} + */ +var VERSION = exports.VERSION = '4.4.0'; + +/** + * Two Pi. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var PI_2 = exports.PI_2 = Math.PI * 2; + +/** + * Conversion factor for converting radians to degrees. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var RAD_TO_DEG = exports.RAD_TO_DEG = 180 / Math.PI; + +/** + * Conversion factor for converting degrees to radians. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var DEG_TO_RAD = exports.DEG_TO_RAD = Math.PI / 180; + +/** + * Constant to identify the Renderer Type. + * + * @static + * @constant + * @memberof PIXI + * @name RENDERER_TYPE + * @type {object} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ +var RENDERER_TYPE = exports.RENDERER_TYPE = { + UNKNOWN: 0, + WEBGL: 1, + CANVAS: 2 +}; + +/** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * + * @static + * @constant + * @memberof PIXI + * @name BLEND_MODES + * @type {object} + * @property {number} NORMAL + * @property {number} ADD + * @property {number} MULTIPLY + * @property {number} SCREEN + * @property {number} OVERLAY + * @property {number} DARKEN + * @property {number} LIGHTEN + * @property {number} COLOR_DODGE + * @property {number} COLOR_BURN + * @property {number} HARD_LIGHT + * @property {number} SOFT_LIGHT + * @property {number} DIFFERENCE + * @property {number} EXCLUSION + * @property {number} HUE + * @property {number} SATURATION + * @property {number} COLOR + * @property {number} LUMINOSITY + */ +var BLEND_MODES = exports.BLEND_MODES = { + NORMAL: 0, + ADD: 1, + MULTIPLY: 2, + SCREEN: 3, + OVERLAY: 4, + DARKEN: 5, + LIGHTEN: 6, + COLOR_DODGE: 7, + COLOR_BURN: 8, + HARD_LIGHT: 9, + SOFT_LIGHT: 10, + DIFFERENCE: 11, + EXCLUSION: 12, + HUE: 13, + SATURATION: 14, + COLOR: 15, + LUMINOSITY: 16 +}; + +/** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * + * @static + * @constant + * @memberof PIXI + * @name DRAW_MODES + * @type {object} + * @property {number} POINTS + * @property {number} LINES + * @property {number} LINE_LOOP + * @property {number} LINE_STRIP + * @property {number} TRIANGLES + * @property {number} TRIANGLE_STRIP + * @property {number} TRIANGLE_FAN + */ +var DRAW_MODES = exports.DRAW_MODES = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6 +}; + +/** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @static + * @constant + * @memberof PIXI + * @name SCALE_MODES + * @type {object} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ +var SCALE_MODES = exports.SCALE_MODES = { + LINEAR: 0, + NEAREST: 1 +}; + +/** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wraping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as webGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * + * @static + * @constant + * @name WRAP_MODES + * @memberof PIXI + * @type {object} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ +var WRAP_MODES = exports.WRAP_MODES = { + CLAMP: 0, + REPEAT: 1, + MIRRORED_REPEAT: 2 +}; + +/** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for pixi textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * + * @static + * @constant + * @name GC_MODES + * @memberof PIXI + * @type {object} + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ +var GC_MODES = exports.GC_MODES = { + AUTO: 0, + MANUAL: 1 +}; + +/** + * Regexp for image type by extension. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `image.png` + */ +var URL_FILE_EXTENSION = exports.URL_FILE_EXTENSION = /\.(\w{3,4})(?:$|\?|#)/i; + +/** + * Regexp for data URI. + * Based on: {@link https://github.com/ragingwind/data-uri-regex} + * + * @static + * @constant + * @name DATA_URI + * @memberof PIXI + * @type {RegExp|string} + * @example data:image/png;base64 + */ +var DATA_URI = exports.DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;(charset=[\w-]+|base64))?,(.*)/i; + +/** + * Regexp for SVG size. + * + * @static + * @constant + * @name SVG_SIZE + * @memberof PIXI + * @type {RegExp|string} + * @example <svg width="100" height="100"></svg> + */ +var SVG_SIZE = exports.SVG_SIZE = /]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len + +/** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * + * @static + * @constant + * @name SHAPES + * @memberof PIXI + * @type {object} + * @property {number} POLY Polygon + * @property {number} RECT Rectangle + * @property {number} CIRC Circle + * @property {number} ELIP Ellipse + * @property {number} RREC Rounded Rectangle + */ +var SHAPES = exports.SHAPES = { + POLY: 0, + RECT: 1, + CIRC: 2, + ELIP: 3, + RREC: 4 +}; + +/** + * Constants that specify float precision in shaders. + * + * @static + * @constant + * @name PRECISION + * @memberof PIXI + * @type {object} + * @property {string} LOW='lowp' + * @property {string} MEDIUM='mediump' + * @property {string} HIGH='highp' + */ +var PRECISION = exports.PRECISION = { + LOW: 'lowp', + MEDIUM: 'mediump', + HIGH: 'highp' +}; + +/** + * Constants that specify the transform type. + * + * @static + * @constant + * @name TRANSFORM_MODE + * @memberof PIXI + * @type {object} + * @property {number} STATIC + * @property {number} DYNAMIC + */ +var TRANSFORM_MODE = exports.TRANSFORM_MODE = { + STATIC: 0, + DYNAMIC: 1 +}; + +/** + * Constants that define the type of gradient on text. + * + * @static + * @constant + * @name TEXT_GRADIENT + * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL Vertical gradient + * @property {number} LINEAR_HORIZONTAL Linear gradient + */ +var TEXT_GRADIENT = exports.TEXT_GRADIENT = { + LINEAR_VERTICAL: 0, + LINEAR_HORIZONTAL: 1 +}; + +},{}],45:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * 'Builder' pattern for bounds rectangles + * Axis-Aligned Bounding Box + * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems + * + * @class + * @memberof PIXI + */ +var Bounds = function () { + /** + * + */ + function Bounds() { + _classCallCheck(this, Bounds); + + /** + * @member {number} + * @default 0 + */ + this.minX = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.minY = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxX = -Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxY = -Infinity; + + this.rect = null; + } + + /** + * Checks if bounds are empty. + * + * @return {boolean} True if empty. + */ + + + Bounds.prototype.isEmpty = function isEmpty() { + return this.minX > this.maxX || this.minY > this.maxY; + }; + + /** + * Clears the bounds and resets. + * + */ + + + Bounds.prototype.clear = function clear() { + this.updateID++; + + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * + * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty + * @returns {PIXI.Rectangle} A rectangle of the bounds + */ + + + Bounds.prototype.getRectangle = function getRectangle(rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return _math.Rectangle.EMPTY; + } + + rect = rect || new _math.Rectangle(0, 0, 1, 1); + + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + + return rect; + }; + + /** + * This function should be inlined when its possible. + * + * @param {PIXI.Point} point - The point to add. + */ + + + Bounds.prototype.addPoint = function addPoint(point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + }; + + /** + * Adds a quad, not transformed + * + * @param {Float32Array} vertices - The verts to add. + */ + + + Bounds.prototype.addQuad = function addQuad(vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = vertices[0]; + var y = vertices[1]; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds sprite frame, transformed. + * + * @param {PIXI.TransformBase} transform - TODO + * @param {number} x0 - TODO + * @param {number} y0 - TODO + * @param {number} x1 - TODO + * @param {number} y1 - TODO + */ + + + Bounds.prototype.addFrame = function addFrame(transform, x0, y0, x1, y1) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = a * x0 + c * y0 + tx; + var y = b * x0 + d * y0 + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y0 + tx; + y = b * x1 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x0 + c * y1 + tx; + y = b * x0 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y1 + tx; + y = b * x1 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Add an array of vertices + * + * @param {PIXI.TransformBase} transform - TODO + * @param {Float32Array} vertices - TODO + * @param {number} beginOffset - TODO + * @param {number} endOffset - TODO + */ + + + Bounds.prototype.addVertices = function addVertices(transform, vertices, beginOffset, endOffset) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = a * rawX + c * rawY + tx; + var y = d * rawY + b * rawX + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds other Bounds + * + * @param {PIXI.Bounds} bounds - TODO + */ + + + Bounds.prototype.addBounds = function addBounds(bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + }; + + /** + * Adds other Bounds, masked with Bounds + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Bounds} mask - TODO + */ + + + Bounds.prototype.addBoundsMask = function addBoundsMask(bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + /** + * Adds other Bounds, masked with Rectangle + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Rectangle} area - TODO + */ + + + Bounds.prototype.addBoundsArea = function addBoundsArea(bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : area.x + area.width; + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : area.y + area.height; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + return Bounds; +}(); + +exports.default = Bounds; + +},{"../math":68}],46:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _DisplayObject2 = require('./DisplayObject'); + +var _DisplayObject3 = _interopRequireDefault(_DisplayObject2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A Container represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + *```js + * let container = new PIXI.Container(); + * container.addChild(sprite); + * ``` + * + * @class + * @extends PIXI.DisplayObject + * @memberof PIXI + */ +var Container = function (_DisplayObject) { + _inherits(Container, _DisplayObject); + + /** + * + */ + function Container() { + _classCallCheck(this, Container); + + /** + * The array of children of this container. + * + * @member {PIXI.DisplayObject[]} + * @readonly + */ + var _this = _possibleConstructorReturn(this, _DisplayObject.call(this)); + + _this.children = []; + return _this; + } + + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified + * + * @private + */ + + + Container.prototype.onChildrenChange = function onChildrenChange() {} + /* empty */ + + + /** + * Adds one or more children to the container. + * + * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container + * @return {PIXI.DisplayObject} The first child that was added. + */ + ; + + Container.prototype.addChild = function addChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.addChild(arguments[i]); + } + } else { + // if the child has a parent then lets remove it as Pixi objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.push(child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + child.emit('added', this); + } + + return child; + }; + + /** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @return {PIXI.DisplayObject} The child that was added. + */ + + + Container.prototype.addChildAt = function addChildAt(child, index) { + if (index < 0 || index > this.children.length) { + throw new Error(child + 'addChildAt: The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.splice(index, 0, child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + + return child; + }; + + /** + * Swaps the position of 2 Display Objects within this container. + * + * @param {PIXI.DisplayObject} child - First display object to swap + * @param {PIXI.DisplayObject} child2 - Second display object to swap + */ + + + Container.prototype.swapChildren = function swapChildren(child, child2) { + if (child === child2) { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; + + /** + * Returns the index position of a child DisplayObject instance + * + * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify + * @return {number} The index position of the child display object to identify + */ + + + Container.prototype.getChildIndex = function getChildIndex(child) { + var index = this.children.indexOf(child); + + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + }; + + /** + * Changes the position of an existing child in the display object container + * + * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number + * @param {number} index - The resulting index number for the child display object + */ + + + Container.prototype.setChildIndex = function setChildIndex(child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + (0, _utils.removeItems)(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + + this.onChildrenChange(index); + }; + + /** + * Returns the child at the specified index + * + * @param {number} index - The index to get the child at + * @return {PIXI.DisplayObject} The child at the given index, if any. + */ + + + Container.prototype.getChildAt = function getChildAt(index) { + if (index < 0 || index >= this.children.length) { + throw new Error('getChildAt: Index (' + index + ') does not exist.'); + } + + return this.children[index]; + }; + + /** + * Removes one or more children from the container. + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove + * @return {PIXI.DisplayObject} The first child that was removed. + */ + + + Container.prototype.removeChild = function removeChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.removeChild(arguments[i]); + } + } else { + var index = this.children.indexOf(child); + + if (index === -1) return null; + + child.parent = null; + // ensure child transform will be recalculated + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + } + + return child; + }; + + /** + * Removes a child from the specified index position. + * + * @param {number} index - The index to get the child from + * @return {PIXI.DisplayObject} The child that was removed. + */ + + + Container.prototype.removeChildAt = function removeChildAt(index) { + var child = this.getChildAt(index); + + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + + return child; + }; + + /** + * Removes all children from this container that are within the begin and end indexes. + * + * @param {number} [beginIndex=0] - The beginning position. + * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. + * @returns {DisplayObject[]} List of removed children + */ + + + Container.prototype.removeChildren = function removeChildren() { + var beginIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var endIndex = arguments[1]; + + var begin = beginIndex; + var end = typeof endIndex === 'number' ? endIndex : this.children.length; + var range = end - begin; + var removed = void 0; + + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } + + this._boundsID++; + + this.onChildrenChange(beginIndex); + + for (var _i = 0; _i < removed.length; ++_i) { + removed[_i].emit('removed', this); + } + + return removed; + } else if (range === 0 && this.children.length === 0) { + return []; + } + + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + }; + + /** + * Updates the transform on all children of this container for rendering + */ + + + Container.prototype.updateTransform = function updateTransform() { + this._boundsID++; + + this.transform.updateTransform(this.parent.transform); + + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + + if (child.visible) { + child.updateTransform(); + } + } + }; + + /** + * Recalculates the bounds of the container. + * + */ + + + Container.prototype.calculateBounds = function calculateBounds() { + this._bounds.clear(); + + this._calculateBounds(); + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (!child.visible || !child.renderable) { + continue; + } + + child.calculateBounds(); + + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + child._mask.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, child._mask._bounds); + } else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } else { + this._bounds.addBounds(child._bounds); + } + } + + this._lastBoundsID = this._boundsID; + }; + + /** + * Recalculates the bounds of the object. Override this to + * calculate the bounds of the specific object (not including children). + * + */ + + + Container.prototype._calculateBounds = function _calculateBounds() {} + // FILL IN// + + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderWebGL = function renderWebGL(renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + // do a quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) { + this.renderAdvancedWebGL(renderer); + } else { + this._renderWebGL(renderer); + + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderWebGL(renderer); + } + } + }; + + /** + * Render the object using the WebGL renderer and advanced features. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { + renderer.flush(); + + var filters = this._filters; + var mask = this._mask; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + + this._enabledFilters.length = 0; + + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + + if (this._enabledFilters.length) { + renderer.filterManager.pushFilter(this, this._enabledFilters); + } + } + + if (mask) { + renderer.maskManager.pushMask(this, this._mask); + } + + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); + + // now loop through the children and make sure they get rendered + for (var _i2 = 0, j = this.children.length; _i2 < j; _i2++) { + this.children[_i2].renderWebGL(renderer); + } + + renderer.flush(); + + if (mask) { + renderer.maskManager.popMask(this, this._mask); + } + + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filterManager.popFilter(); + } + }; + + /** + * To be overridden by the subclasses. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype._renderWebGL = function _renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * To be overridden by the subclass + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype._renderCanvas = function _renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderCanvas = function renderCanvas(renderer) { + // if not visible or the alpha is 0 then no need to render this + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + if (this._mask) { + renderer.maskManager.pushMask(this._mask); + } + + this._renderCanvas(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderCanvas(renderer); + } + + if (this._mask) { + renderer.maskManager.popMask(renderer); + } + }; + + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Container.prototype.destroy = function destroy(options) { + _DisplayObject.prototype.destroy.call(this); + + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + + var oldChildren = this.removeChildren(0, this.children.length); + + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + }; + + /** + * The width of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Container, [{ + key: 'width', + get: function get() { + return this.scale.x * this.getLocalBounds().width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var width = this.getLocalBounds().width; + + if (width !== 0) { + this.scale.x = value / width; + } else { + this.scale.x = 1; + } + + this._width = value; + } + + /** + * The height of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.scale.y * this.getLocalBounds().height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var height = this.getLocalBounds().height; + + if (height !== 0) { + this.scale.y = value / height; + } else { + this.scale.y = 1; + } + + this._height = value; + } + }]); + + return Container; +}(_DisplayObject3.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = Container; +Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + +},{"../utils":120,"./DisplayObject":47}],47:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TransformStatic = require('./TransformStatic'); + +var _TransformStatic2 = _interopRequireDefault(_TransformStatic); + +var _Transform = require('./Transform'); + +var _Transform2 = _interopRequireDefault(_Transform); + +var _Bounds = require('./Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _math = require('../math'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// _tempDisplayObjectParent = new DisplayObject(); + +/** + * The base class for all objects that are rendered on the screen. + * This is an abstract class and should not be used on its own rather it should be extended. + * + * @class + * @extends EventEmitter + * @mixes PIXI.interaction.interactiveTarget + * @memberof PIXI + */ +var DisplayObject = function (_EventEmitter) { + _inherits(DisplayObject, _EventEmitter); + + /** + * + */ + function DisplayObject() { + _classCallCheck(this, DisplayObject); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + var TransformClass = _settings2.default.TRANSFORM_MODE === _const.TRANSFORM_MODE.STATIC ? _TransformStatic2.default : _Transform2.default; + + _this.tempDisplayObjectParent = null; + + // TODO: need to create Transform from factory + /** + * World transform and local transform of this object. + * This will become read-only later, please do not assign anything there unless you know what are you doing + * + * @member {PIXI.TransformBase} + */ + _this.transform = new TransformClass(); + + /** + * The opacity of the object. + * + * @member {number} + */ + _this.alpha = 1; + + /** + * The visibility of the object. If false the object will not be drawn, and + * the updateTransform function will not be called. + * + * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually + * + * @member {boolean} + */ + _this.visible = true; + + /** + * Can this object be rendered, if false the object will not be drawn but the updateTransform + * methods will still be called. + * + * Only affects recursive calls from parent. You can ask for bounds manually + * + * @member {boolean} + */ + _this.renderable = true; + + /** + * The display object container that contains this display object. + * + * @member {PIXI.Container} + * @readonly + */ + _this.parent = null; + + /** + * The multiplied alpha of the displayObject + * + * @member {number} + * @readonly + */ + _this.worldAlpha = 1; + + /** + * The area the filter is applied to. This is used as more of an optimisation + * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle + * + * Also works as an interaction mask + * + * @member {PIXI.Rectangle} + */ + _this.filterArea = null; + + _this._filters = null; + _this._enabledFilters = null; + + /** + * The bounds object, this is used to calculate and store the bounds of the displayObject + * + * @member {PIXI.Rectangle} + * @private + */ + _this._bounds = new _Bounds2.default(); + _this._boundsID = 0; + _this._lastBoundsID = -1; + _this._boundsRect = null; + _this._localBoundsRect = null; + + /** + * The original, cached mask of the object + * + * @member {PIXI.Graphics|PIXI.Sprite} + * @private + */ + _this._mask = null; + return _this; + } + + /** + * @private + * @member {PIXI.DisplayObject} + */ + + + /** + * Updates the object transform for rendering + * + * TODO - Optimization pass! + */ + DisplayObject.prototype.updateTransform = function updateTransform() { + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + this._bounds.updateID++; + }; + + /** + * recursively updates transform of all objects from the root to this one + * internal function for toLocal() + */ + + + DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform() { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + }; + + /** + * Retrieves the bounds of the displayObject as a rectangle object. + * + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @param {PIXI.Rectangle} rect - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getBounds = function getBounds(skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + + if (this._boundsID !== this._lastBoundsID) { + this.calculateBounds(); + } + + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new _math.Rectangle(); + } + + rect = this._boundsRect; + } + + return this._bounds.getRectangle(rect); + }; + + /** + * Retrieves the local bounds of the displayObject as a rectangle object + * + * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getLocalBounds = function getLocalBounds(rect) { + var transformRef = this.transform; + var parentRef = this.parent; + + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + var bounds = this.getBounds(false, rect); + + this.parent = parentRef; + this.transform = transformRef; + + return bounds; + }; + + /** + * Calculates the global position of the display object + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform. + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toGlobal = function toGlobal(position, point) { + var skipUpdate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; + + /** + * Calculates the local position of the display object relative to another point + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toLocal = function toLocal(position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + DisplayObject.prototype.renderCanvas = function renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Set the parent Container of this DisplayObject + * + * @param {PIXI.Container} container - The Container to add this DisplayObject to + * @return {PIXI.Container} The Container that this DisplayObject was added to + */ + ; + + DisplayObject.prototype.setParent = function setParent(container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); + } + + container.addChild(this); + + return container; + }; + + /** + * Convenience function to set the position, scale, skew and pivot at once. + * + * @param {number} [x=0] - The X position + * @param {number} [y=0] - The Y position + * @param {number} [scaleX=1] - The X scale value + * @param {number} [scaleY=1] - The Y scale value + * @param {number} [rotation=0] - The rotation + * @param {number} [skewX=0] - The X skew value + * @param {number} [skewY=0] - The Y skew value + * @param {number} [pivotX=0] - The X pivot value + * @param {number} [pivotY=0] - The Y pivot value + * @return {PIXI.DisplayObject} The DisplayObject instance + */ + + + DisplayObject.prototype.setTransform = function setTransform() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var scaleX = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var scaleY = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var rotation = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var skewX = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + var skewY = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + var pivotX = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; + var pivotY = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0; + + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + + return this; + }; + + /** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy`. + * + */ + + + DisplayObject.prototype.destroy = function destroy() { + this.removeAllListeners(); + if (this.parent) { + this.parent.removeChild(this); + } + this.transform = null; + + this.parent = null; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this.filterArea = null; + + this.interactive = false; + this.interactiveChildren = false; + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + * + * @member {number} + */ + + + _createClass(DisplayObject, [{ + key: '_tempDisplayObjectParent', + get: function get() { + if (this.tempDisplayObjectParent === null) { + this.tempDisplayObjectParent = new DisplayObject(); + } + + return this.tempDisplayObjectParent; + } + }, { + key: 'x', + get: function get() { + return this.position.x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.x = value; + } + + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + * + * @member {number} + */ + + }, { + key: 'y', + get: function get() { + return this.position.y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.y = value; + } + + /** + * Current transform of the object based on world (parent) factors + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'worldTransform', + get: function get() { + return this.transform.worldTransform; + } + + /** + * Current transform of the object based on local factors: position, scale, other stuff + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'localTransform', + get: function get() { + return this.transform.localTransform; + } + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'position', + get: function get() { + return this.transform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.copy(value); + } + + /** + * The scale factor of the object. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'scale', + get: function get() { + return this.transform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.scale.copy(value); + } + + /** + * The pivot point of the displayObject that it rotates around + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'pivot', + get: function get() { + return this.transform.pivot; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.pivot.copy(value); + } + + /** + * The skew factor for the object in radians. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'skew', + get: function get() { + return this.transform.skew; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.skew.copy(value); + } + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + }, { + key: 'rotation', + get: function get() { + return this.transform.rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.rotation = value; + } + + /** + * Indicates if the object is globally visible. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'worldVisible', + get: function get() { + var item = this; + + do { + if (!item.visible) { + return false; + } + + item = item.parent; + } while (item); + + return true; + } + + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PIXI a regular mask must be a + * PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it + * utilises shape clipping. To remove a mask, set this property to null. + * + * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + * + * @member {PIXI.Graphics|PIXI.Sprite} + */ + + }, { + key: 'mask', + get: function get() { + return this._mask; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._mask) { + this._mask.renderable = true; + } + + this._mask = value; + + if (this._mask) { + this._mask.renderable = false; + } + } + + /** + * Sets the filters for the displayObject. + * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * To remove filters simply set this property to 'null' + * + * @member {PIXI.Filter[]} + */ + + }, { + key: 'filters', + get: function get() { + return this._filters && this._filters.slice(); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._filters = value && value.slice(); + } + }]); + + return DisplayObject; +}(_eventemitter2.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = DisplayObject; +DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + +},{"../const":44,"../math":68,"../settings":99,"./Bounds":45,"./Transform":48,"./TransformStatic":50,"eventemitter3":3}],48:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Generic class to deal with traditional 2D matrix transforms + * local transformation is calculated from position,scale,skew and rotation + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var Transform = function (_TransformBase) { + _inherits(Transform, _TransformBase); + + /** + * + */ + function Transform() { + _classCallCheck(this, Transform); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.Point} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.Point(0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.Point} + */ + _this.scale = new _math.Point(1, 1); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.Point} + */ + _this.pivot = new _math.Point(0, 0); + + /** + * The rotation value of the object, in radians + * + * @member {Number} + * @private + */ + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + return _this; + } + + /** + * Updates the skew values when the skew or rotation changes. + * + * @private + */ + + + Transform.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + }; + + /** + * Updates only local matrix + */ + + + Transform.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + Transform.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + Transform.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(Transform, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return Transform; +}(_TransformBase3.default); + +exports.default = Transform; + +},{"../math":68,"./TransformBase":49}],49:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Generic class to deal with traditional 2D matrix transforms + * + * @class + * @memberof PIXI + */ +var TransformBase = function () { + /** + * + */ + function TransformBase() { + _classCallCheck(this, TransformBase); + + /** + * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds() + * + * @member {PIXI.Matrix} + */ + this.worldTransform = new _math.Matrix(); + + /** + * The local matrix transform + * + * @member {PIXI.Matrix} + */ + this.localTransform = new _math.Matrix(); + + this._worldID = 0; + this._parentID = 0; + } + + /** + * TransformBase does not have decomposition, so this function wont do anything + */ + + + TransformBase.prototype.updateLocalTransform = function updateLocalTransform() {} + // empty + + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.TransformBase} parentTransform - The transform of the parent of this object + */ + ; + + TransformBase.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + return TransformBase; +}(); + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ + + +exports.default = TransformBase; +TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; + +TransformBase.IDENTITY = new TransformBase(); + +},{"../math":68}],50:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Transform that takes care about its versions + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var TransformStatic = function (_TransformBase) { + _inherits(TransformStatic, _TransformBase); + + /** + * + */ + function TransformStatic() { + _classCallCheck(this, TransformStatic); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.ObservablePoint} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.ObservablePoint} + */ + _this.scale = new _math.ObservablePoint(_this.onChange, _this, 1, 1); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.ObservablePoint} + */ + _this.pivot = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + + _this._localID = 0; + _this._currentLocalID = 0; + return _this; + } + + /** + * Called when a value changes. + * + * @private + */ + + + TransformStatic.prototype.onChange = function onChange() { + this._localID++; + }; + + /** + * Called when skew or rotation changes + * + * @private + */ + + + TransformStatic.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + + this._localID++; + }; + + /** + * Updates only local matrix + */ + + + TransformStatic.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + TransformStatic.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._parentID = parentTransform._worldID; + + // update the id of the transform.. + this._worldID++; + } + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + TransformStatic.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + this._localID++; + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(TransformStatic, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return TransformStatic; +}(_TransformBase3.default); + +exports.default = TransformStatic; + +},{"../math":68,"./TransformBase":49}],51:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _GraphicsData = require('./GraphicsData'); + +var _GraphicsData2 = _interopRequireDefault(_GraphicsData); + +var _Sprite = require('../sprites/Sprite'); + +var _Sprite2 = _interopRequireDefault(_Sprite); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Bounds = require('../display/Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _bezierCurveTo2 = require('./utils/bezierCurveTo'); + +var _bezierCurveTo3 = _interopRequireDefault(_bezierCurveTo2); + +var _CanvasRenderer = require('../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var canvasRenderer = void 0; +var tempMatrix = new _math.Matrix(); +var tempPoint = new _math.Point(); +var tempColor1 = new Float32Array(4); +var tempColor2 = new Float32Array(4); + +/** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Graphics = function (_Container) { + _inherits(Graphics, _Container); + + /** + * + * @param {boolean} [nativeLines=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + */ + function Graphics() { + var nativeLines = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + _classCallCheck(this, Graphics); + + /** + * The alpha value used when filling the Graphics object. + * + * @member {number} + * @default 1 + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @member {number} + * @default 0 + */ + _this.lineWidth = 0; + + /** + * If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * + * @member {boolean} + */ + _this.nativeLines = nativeLines; + + /** + * The color of any lines drawn. + * + * @member {string} + * @default 0 + */ + _this.lineColor = 0; + + /** + * Graphics data + * + * @member {PIXI.GraphicsData[]} + * @private + */ + _this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to + * reset the tint. + * + * @member {number} + * @default 0xFFFFFF + */ + _this.tint = 0xFFFFFF; + + /** + * The previous tint applied to the graphic shape. Used to compare to the current tint and + * check if theres change. + * + * @member {number} + * @private + * @default 0xFFFFFF + */ + _this._prevTint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * Current path + * + * @member {PIXI.GraphicsData} + * @private + */ + _this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @member {object} + * @private + */ + // TODO - _webgl should use a prototype object, not a random undocumented object... + _this._webGL = {}; + + /** + * Whether this shape is being used as a mask. + * + * @member {boolean} + */ + _this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @member {number} + */ + _this.boundsPadding = 0; + + /** + * A cache of the local bounds to prevent recalculation. + * + * @member {PIXI.Rectangle} + * @private + */ + _this._localBounds = new _Bounds2.default(); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics + * object will be recalculated. + * + * @member {boolean} + * @private + */ + _this.dirty = 0; + + /** + * Used to detect if we need to do a fast rect check using the id compare method + * @type {Number} + */ + _this.fastRectDirty = -1; + + /** + * Used to detect if we clear the graphics webGL data + * @type {Number} + */ + _this.clearDirty = 0; + + /** + * Used to detect if we we need to recalculate local bounds + * @type {Number} + */ + _this.boundsDirty = -1; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @member {boolean} + * @private + */ + _this.cachedSpriteDirty = false; + + _this._spriteRect = null; + _this._fastRect = false; + + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ + return _this; + } + + /** + * Creates a new Graphics object with the same values as this one. + * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) + * + * @return {PIXI.Graphics} A clone of the graphics object + */ + + + Graphics.prototype.clone = function clone() { + var clone = new Graphics(); + + clone.renderable = this.renderable; + clone.fillAlpha = this.fillAlpha; + clone.lineWidth = this.lineWidth; + clone.lineColor = this.lineColor; + clone.tint = this.tint; + clone.blendMode = this.blendMode; + clone.isMask = this.isMask; + clone.boundsPadding = this.boundsPadding; + clone.dirty = 0; + clone.cachedSpriteDirty = this.cachedSpriteDirty; + + // copy graphics data + for (var i = 0; i < this.graphicsData.length; ++i) { + clone.graphicsData.push(this.graphicsData[i].clone()); + } + + clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; + + clone.updateLocalBounds(); + + return clone; + }; + + /** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() + * method or the drawCircle() method. + * + * @param {number} [lineWidth=0] - width of the line to draw, will update the objects stored style + * @param {number} [color=0] - color of the line to draw, will update the objects stored style + * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineStyle = function lineStyle() { + var lineWidth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var alpha = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + + this.lineWidth = lineWidth; + this.lineColor = color; + this.lineAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length) { + // halfway through a line? start a new one! + var shape = new _math.Polygon(this.currentPath.shape.points.slice(-2)); + + shape.closed = false; + + this.drawShape(shape); + } else { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + }; + + /** + * Moves the current drawing position to x, y. + * + * @param {number} x - the X coordinate to move to + * @param {number} y - the Y coordinate to move to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.moveTo = function moveTo(x, y) { + var shape = new _math.Polygon([x, y]); + + shape.closed = false; + this.drawShape(shape); + + return this; + }; + + /** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @param {number} x - the X coordinate to draw to + * @param {number} y - the Y coordinate to draw to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineTo = function lineTo(x, y) { + this.currentPath.shape.points.push(x, y); + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.quadraticCurveTo = function quadraticCurveTo(cpX, cpY, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var n = 20; + var points = this.currentPath.shape.points; + var xa = 0; + var ya = 0; + + if (points.length === 0) { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + for (var i = 1; i <= n; ++i) { + var j = i / n; + + xa = fromX + (cpX - fromX) * j; + ya = fromY + (cpY - fromY) * j; + + points.push(xa + (cpX + (toX - cpX) * j - xa) * j, ya + (cpY + (toY - cpY) * j - ya) * j); + } + + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a bezier curve and then draws it. + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.bezierCurveTo = function bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + points.length -= 2; + + (0, _bezierCurveTo3.default)(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, points); + + this.dirty++; + + return this; + }; + + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @param {number} x1 - The x-coordinate of the beginning of the arc + * @param {number} y1 - The y-coordinate of the beginning of the arc + * @param {number} x2 - The x-coordinate of the end of the arc + * @param {number} y2 - The y-coordinate of the end of the arc + * @param {number} radius - The radius of the arc + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arcTo = function arcTo(x1, y1, x2, y2, radius) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points.push(x1, y1); + } + } else { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + } else { + var dd = a1 * a1 + b1 * b1; + var cc = a2 * a2 + b2 * b2; + var tt = a1 * a2 + b1 * b2; + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = k1 * b2 + k2 * b1; + var cy = k1 * a2 + k2 * a1; + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty++; + + return this; + }; + + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @param {number} cx - The x-coordinate of the center of the circle + * @param {number} cy - The y-coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param {number} endAngle - The ending angle, in radians + * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arc = function arc(cx, cy, radius, startAngle, endAngle) { + var anticlockwise = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; + + if (startAngle === endAngle) { + return this; + } + + if (!anticlockwise && endAngle <= startAngle) { + endAngle += Math.PI * 2; + } else if (anticlockwise && startAngle <= endAngle) { + startAngle += Math.PI * 2; + } + + var sweep = endAngle - startAngle; + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * 40; + + if (sweep === 0) { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. + var points = this.currentPath ? this.currentPath.shape.points : null; + + if (points) { + if (points[points.length - 2] !== startX || points[points.length - 1] !== startY) { + points.push(startX, startY); + } + } else { + this.moveTo(startX, startY); + points = this.currentPath.shape.points; + } + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = segMinus % 1 / segMinus; + + for (var i = 0; i <= segMinus; ++i) { + var real = i + remainder * i; + + var angle = theta + startAngle + theta2 * real; + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push((cTheta * c + sTheta * s) * radius + cx, (cTheta * -s + sTheta * c) * radius + cy); + } + + this.dirty++; + + return this; + }; + + /** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @param {number} [color=0] - the color of the fill + * @param {number} [alpha=1] - the alpha of the fill + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.beginFill = function beginFill() { + var color = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var alpha = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.filling = true; + this.fillColor = color; + this.fillAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length <= 2) { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + }; + + /** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.endFill = function endFill() { + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRect = function drawRect(x, y, width, height) { + this.drawShape(new _math.Rectangle(x, y, width, height)); + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @param {number} radius - Radius of the rectangle corners + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRoundedRect = function drawRoundedRect(x, y, width, height, radius) { + this.drawShape(new _math.RoundedRectangle(x, y, width, height, radius)); + + return this; + }; + + /** + * Draws a circle. + * + * @param {number} x - The X coordinate of the center of the circle + * @param {number} y - The Y coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawCircle = function drawCircle(x, y, radius) { + this.drawShape(new _math.Circle(x, y, radius)); + + return this; + }; + + /** + * Draws an ellipse. + * + * @param {number} x - The X coordinate of the center of the ellipse + * @param {number} y - The Y coordinate of the center of the ellipse + * @param {number} width - The half width of the ellipse + * @param {number} height - The half height of the ellipse + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawEllipse = function drawEllipse(x, y, width, height) { + this.drawShape(new _math.Ellipse(x, y, width, height)); + + return this; + }; + + /** + * Draws a polygon using the given path. + * + * @param {number[]|PIXI.Point[]} path - The path data used to construct the polygon. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawPolygon = function drawPolygon(path) { + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + var closed = true; + + if (points instanceof _math.Polygon) { + closed = points.closed; + points = points.points; + } + + if (!Array.isArray(points)) { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) { + points[i] = arguments[i]; // eslint-disable-line prefer-rest-params + } + } + + var shape = new _math.Polygon(points); + + shape.closed = closed; + + this.drawShape(shape); + + return this; + }; + + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.clear = function clear() { + if (this.lineWidth || this.filling || this.graphicsData.length > 0) { + this.lineWidth = 0; + this.filling = false; + + this.boundsDirty = -1; + this.dirty++; + this.clearDirty++; + this.graphicsData.length = 0; + } + + this.currentPath = null; + this._spriteRect = null; + + return this; + }; + + /** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. + * + * @returns {boolean} True if only 1 rect. + */ + + + Graphics.prototype.isFastRect = function isFastRect() { + return this.graphicsData.length === 1 && this.graphicsData[0].shape.type === _const.SHAPES.RECT && !this.graphicsData[0].lineWidth; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderWebGL = function _renderWebGL(renderer) { + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.dirty !== this.fastRectDirty) { + this.fastRectDirty = this.dirty; + this._fastRect = this.isFastRect(); + } + + // TODO this check can be moved to dirty? + if (this._fastRect) { + this._renderSpriteRect(renderer); + } else { + renderer.setObjectRenderer(renderer.plugins.graphics); + renderer.plugins.graphics.render(this); + } + }; + + /** + * Renders a sprite rectangle. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderSpriteRect = function _renderSpriteRect(renderer) { + var rect = this.graphicsData[0].shape; + + if (!this._spriteRect) { + this._spriteRect = new _Sprite2.default(new _Texture2.default(_Texture2.default.WHITE)); + } + + var sprite = this._spriteRect; + + if (this.tint === 0xffffff) { + sprite.tint = this.graphicsData[0].fillColor; + } else { + var t1 = tempColor1; + var t2 = tempColor2; + + (0, _utils.hex2rgb)(this.graphicsData[0].fillColor, t1); + (0, _utils.hex2rgb)(this.tint, t2); + + t1[0] *= t2[0]; + t1[1] *= t2[1]; + t1[2] *= t2[2]; + + sprite.tint = (0, _utils.rgb2hex)(t1); + } + sprite.alpha = this.graphicsData[0].fillAlpha; + sprite.worldAlpha = this.worldAlpha * sprite.alpha; + sprite.blendMode = this.blendMode; + + sprite.texture._frame.width = rect.width; + sprite.texture._frame.height = rect.height; + + sprite.transform.worldTransform = this.transform.worldTransform; + + sprite.anchor.set(-rect.x / rect.width, -rect.y / rect.height); + sprite._onAnchorUpdate(); + + sprite._renderWebGL(renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.isMask === true) { + return; + } + + renderer.plugins.graphics.render(this); + }; + + /** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @private + */ + + + Graphics.prototype._calculateBounds = function _calculateBounds() { + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.updateLocalBounds(); + + this.cachedSpriteDirty = true; + } + + var lb = this._localBounds; + + this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); + }; + + /** + * Tests if a point is inside this graphics object + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Graphics.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + + if (!data.fill) { + continue; + } + + // only deal with fills.. + if (data.shape) { + if (data.shape.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + } + + return false; + }; + + /** + * Update the bounds of the object + * + */ + + + Graphics.prototype.updateLocalBounds = function updateLocalBounds() { + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) { + var shape = 0; + var x = 0; + var y = 0; + var w = 0; + var h = 0; + + for (var i = 0; i < this.graphicsData.length; i++) { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + + shape = data.shape; + + if (type === _const.SHAPES.RECT || type === _const.SHAPES.RREC) { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.CIRC) { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.ELIP) { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else { + // POLY + var points = shape.points; + var x2 = 0; + var y2 = 0; + var dx = 0; + var dy = 0; + var rw = 0; + var rh = 0; + var cx = 0; + var cy = 0; + + for (var j = 0; j + 2 < points.length; j += 2) { + x = points[j]; + y = points[j + 1]; + x2 = points[j + 2]; + y2 = points[j + 3]; + dx = Math.abs(x2 - x); + dy = Math.abs(y2 - y); + h = lineWidth; + w = Math.sqrt(dx * dx + dy * dy); + + if (w < 1e-9) { + continue; + } + + rw = (h / w * dy + dx) / 2; + rh = (h / w * dx + dy) / 2; + cx = (x2 + x) / 2; + cy = (y2 + y) / 2; + + minX = cx - rw < minX ? cx - rw : minX; + maxX = cx + rw > maxX ? cx + rw : maxX; + + minY = cy - rh < minY ? cy - rh : minY; + maxY = cy + rh > maxY ? cy + rh : maxY; + } + } + } + } else { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.minX = minX - padding; + this._localBounds.maxX = maxX + padding * 2; + + this._localBounds.minY = minY - padding; + this._localBounds.maxY = maxY + padding * 2; + }; + + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @return {PIXI.GraphicsData} The generated GraphicsData object. + */ + + + Graphics.prototype.drawShape = function drawShape(shape) { + if (this.currentPath) { + // check current path! + if (this.currentPath.shape.points.length <= 2) { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + var data = new _GraphicsData2.default(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, this.nativeLines, shape); + + this.graphicsData.push(data); + + if (data.type === _const.SHAPES.POLY) { + data.shape.closed = data.shape.closed || this.filling; + this.currentPath = data; + } + + this.dirty++; + + return data; + }; + + /** + * Generates a canvas texture. + * + * @param {number} scaleMode - The scale mode of the texture. + * @param {number} resolution - The resolution of the texture. + * @return {PIXI.Texture} The new texture. + */ + + + Graphics.prototype.generateCanvasTexture = function generateCanvasTexture(scaleMode) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + var bounds = this.getLocalBounds(); + + var canvasBuffer = _RenderTexture2.default.create(bounds.width, bounds.height, scaleMode, resolution); + + if (!canvasRenderer) { + canvasRenderer = new _CanvasRenderer2.default(); + } + + this.transform.updateLocalTransform(); + this.transform.localTransform.copy(tempMatrix); + + tempMatrix.invert(); + + tempMatrix.tx -= bounds.x; + tempMatrix.ty -= bounds.y; + + canvasRenderer.render(this, canvasBuffer, true, tempMatrix); + + var texture = _Texture2.default.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas, scaleMode); + + texture.baseTexture.resolution = resolution; + texture.baseTexture.update(); + + return texture; + }; + + /** + * Closes the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.closePath = function closePath() { + // ok so close path assumes next one is a hole! + var currentPath = this.currentPath; + + if (currentPath && currentPath.shape) { + currentPath.shape.close(); + } + + return this; + }; + + /** + * Adds a hole in the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.addHole = function addHole() { + // this is a hole! + var hole = this.graphicsData.pop(); + + this.currentPath = this.graphicsData[this.graphicsData.length - 1]; + + this.currentPath.addHole(hole.shape); + this.currentPath = null; + + return this; + }; + + /** + * Destroys the Graphics object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Graphics.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._webgl) { + for (var j = 0; j < this._webgl[id].data.length; ++j) { + this._webgl[id].data[j].destroy(); + } + } + + if (this._spriteRect) { + this._spriteRect.destroy(); + } + + this.graphicsData = null; + + this.currentPath = null; + this._webgl = null; + this._localBounds = null; + }; + + return Graphics; +}(_Container3.default); + +exports.default = Graphics; + + +Graphics._SPRITE_TEXTURE = null; + +},{"../const":44,"../display/Bounds":45,"../display/Container":46,"../math":68,"../renderers/canvas/CanvasRenderer":75,"../sprites/Sprite":100,"../textures/RenderTexture":110,"../textures/Texture":112,"../utils":120,"./GraphicsData":52,"./utils/bezierCurveTo":54}],52:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + */ +var GraphicsData = function () { + /** + * + * @param {number} lineWidth - the width of the line to draw + * @param {number} lineColor - the color of the line to draw + * @param {number} lineAlpha - the alpha of the line to draw + * @param {number} fillColor - the color of the fill + * @param {number} fillAlpha - the alpha of the fill + * @param {boolean} fill - whether or not the shape is filled with a colour + * @param {boolean} nativeLines - the method for drawing lines + * @param {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} shape - The shape object to draw. + */ + function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, nativeLines, shape) { + _classCallCheck(this, GraphicsData); + + /** + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + /** + * @member {boolean} if true the liens will be draw using LINES instead of TRIANGLE_STRIP + */ + this.nativeLines = nativeLines; + + /** + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /** + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /** + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /** + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /** + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /** + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /** + * @member {boolean} whether or not the shape is filled with a colour + */ + this.fill = fill; + + this.holes = []; + + /** + * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} The shape object to draw. + */ + this.shape = shape; + + /** + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + } + + /** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {PIXI.GraphicsData} Cloned GraphicsData object + */ + + + GraphicsData.prototype.clone = function clone() { + return new GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.fill, this.nativeLines, this.shape); + }; + + /** + * Adds a hole to the shape. + * + * @param {PIXI.Rectangle|PIXI.Circle} shape - The shape of the hole. + */ + + + GraphicsData.prototype.addHole = function addHole(shape) { + this.holes.push(shape); + }; + + /** + * Destroys the Graphics data. + */ + + + GraphicsData.prototype.destroy = function destroy() { + this.shape = null; + this.holes = null; + }; + + return GraphicsData; +}(); + +exports.default = GraphicsData; + +},{}],53:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they + * now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasGraphicsRenderer: + * https://github.com/libgdx/libgdx/blob/1.0.0/gdx/src/com/badlogic/gdx/graphics/glutils/ShapeRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching graphics objects. + * + * @class + * @private + * @memberof PIXI + */ +var CanvasGraphicsRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The current PIXI renderer. + */ + function CanvasGraphicsRenderer(renderer) { + _classCallCheck(this, CanvasGraphicsRenderer); + + this.renderer = renderer; + } + + /** + * Renders a Graphics object to a canvas. + * + * @param {PIXI.Graphics} graphics - the actual graphics object to render + */ + + + CanvasGraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var context = renderer.context; + var worldAlpha = graphics.worldAlpha; + var transform = graphics.transform.worldTransform; + var resolution = renderer.resolution; + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) { + this.dirty = true; + } + + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + if (graphics.dirty) { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + renderer.setBlendMode(graphics.blendMode); + + for (var i = 0; i < graphics.graphicsData.length; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === _const.SHAPES.POLY) { + context.beginPath(); + + this.renderPolygon(shape.points, shape.closed, context); + + for (var j = 0; j < data.holes.length; j++) { + this.renderPolygon(data.holes[j].points, true, context); + } + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RECT) { + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + context.beginPath(); + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + }; + + /** + * Updates the tint of a graphics object + * + * @private + * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated + */ + + + CanvasGraphicsRenderer.prototype.updateGraphicsTint = function updateGraphicsTint(graphics) { + graphics._prevTint = graphics.tint; + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF) / 255; + + for (var i = 0; i < graphics.graphicsData.length; ++i) { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + // super inline cos im an optimization NAZI :) + data._fillTint = ((fillColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (fillColor & 0xFF) / 255 * tintB * 255; + + data._lineTint = ((lineColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (lineColor & 0xFF) / 255 * tintB * 255; + } + }; + + /** + * Renders a polygon. + * + * @param {PIXI.Point[]} points - The points to render + * @param {boolean} close - Should the polygon be closed + * @param {CanvasRenderingContext2D} context - The rendering context to use + */ + + + CanvasGraphicsRenderer.prototype.renderPolygon = function renderPolygon(points, close, context) { + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; ++j) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (close) { + context.closePath(); + } + }; + + /** + * destroy graphics object + * + */ + + + CanvasGraphicsRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasGraphicsRenderer; +}(); + +exports.default = CanvasGraphicsRenderer; + + +_CanvasRenderer2.default.registerPlugin('graphics', CanvasGraphicsRenderer); + +},{"../../const":44,"../../renderers/canvas/CanvasRenderer":75}],54:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = bezierCurveTo; +/** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [path=[]] - Path array to push points into + * @return {number[]} Array of points of the curve + */ +function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var path = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : []; + + var n = 20; + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + + path.push(fromX, fromY); + + for (var i = 1, j = 0; i <= n; ++i) { + j = i / n; + + dt = 1 - j; + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + path.push(dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + return path; +} + +},{}],55:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _WebGLGraphicsData = require('./WebGLGraphicsData'); + +var _WebGLGraphicsData2 = _interopRequireDefault(_WebGLGraphicsData); + +var _PrimitiveShader = require('./shaders/PrimitiveShader'); + +var _PrimitiveShader2 = _interopRequireDefault(_PrimitiveShader); + +var _buildPoly = require('./utils/buildPoly'); + +var _buildPoly2 = _interopRequireDefault(_buildPoly); + +var _buildRectangle = require('./utils/buildRectangle'); + +var _buildRectangle2 = _interopRequireDefault(_buildRectangle); + +var _buildRoundedRectangle = require('./utils/buildRoundedRectangle'); + +var _buildRoundedRectangle2 = _interopRequireDefault(_buildRoundedRectangle); + +var _buildCircle = require('./utils/buildCircle'); + +var _buildCircle2 = _interopRequireDefault(_buildCircle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Renders the graphics object. + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var GraphicsRenderer = function (_ObjectRenderer) { + _inherits(GraphicsRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this object renderer works for. + */ + function GraphicsRenderer(renderer) { + _classCallCheck(this, GraphicsRenderer); + + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.graphicsDataPool = []; + + _this.primitiveShader = null; + + _this.gl = renderer.gl; + + // easy access! + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * Called when there is a WebGL context change + * + * @private + * + */ + + + GraphicsRenderer.prototype.onContextChange = function onContextChange() { + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.primitiveShader = new _PrimitiveShader2.default(this.gl); + }; + + /** + * Destroys this renderer. + * + */ + + + GraphicsRenderer.prototype.destroy = function destroy() { + _ObjectRenderer3.default.prototype.destroy.call(this); + + for (var i = 0; i < this.graphicsDataPool.length; ++i) { + this.graphicsDataPool[i].destroy(); + } + + this.graphicsDataPool = null; + }; + + /** + * Renders a graphics object. + * + * @param {PIXI.Graphics} graphics - The graphics object to render. + */ + + + GraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var gl = renderer.gl; + + var webGLData = void 0; + var webGL = graphics._webGL[this.CONTEXT_UID]; + + if (!webGL || graphics.dirty !== webGL.dirty) { + this.updateGraphics(graphics); + + webGL = graphics._webGL[this.CONTEXT_UID]; + } + + // This could be speeded up for sure! + var shader = this.primitiveShader; + + renderer.bindShader(shader); + renderer.state.setBlendMode(graphics.blendMode); + + for (var i = 0, n = webGL.data.length; i < n; i++) { + webGLData = webGL.data[i]; + var shaderTemp = webGLData.shader; + + renderer.bindShader(shaderTemp); + shaderTemp.uniforms.translationMatrix = graphics.transform.worldTransform.toArray(true); + shaderTemp.uniforms.tint = (0, _utils.hex2rgb)(graphics.tint); + shaderTemp.uniforms.alpha = graphics.worldAlpha; + + renderer.bindVao(webGLData.vao); + + if (graphics.nativeLines) { + gl.drawArrays(gl.LINES, 0, webGLData.points.length / 6); + } else { + webGLData.vao.draw(gl.TRIANGLE_STRIP, webGLData.indices.length); + } + } + }; + + /** + * Updates the graphics object + * + * @private + * @param {PIXI.Graphics} graphics - The graphics object to update + */ + + + GraphicsRenderer.prototype.updateGraphics = function updateGraphics(graphics) { + var gl = this.renderer.gl; + + // get the contexts graphics object + var webGL = graphics._webGL[this.CONTEXT_UID]; + + // if the graphics object does not exist in the webGL context time to create it! + if (!webGL) { + webGL = graphics._webGL[this.CONTEXT_UID] = { lastIndex: 0, data: [], gl: gl, clearDirty: -1, dirty: -1 }; + } + + // flag the graphics as not dirty as we are about to update it... + webGL.dirty = graphics.dirty; + + // if the user cleared the graphics object we will need to clear every object + if (graphics.clearDirty !== webGL.clearDirty) { + webGL.clearDirty = graphics.clearDirty; + + // loop through and return all the webGLDatas to the object pool so than can be reused later on + for (var i = 0; i < webGL.data.length; i++) { + this.graphicsDataPool.push(webGL.data[i]); + } + + // clear the array and reset the index.. + webGL.data.length = 0; + webGL.lastIndex = 0; + } + + var webGLData = void 0; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (var _i = webGL.lastIndex; _i < graphics.graphicsData.length; _i++) { + var data = graphics.graphicsData[_i]; + + // TODO - this can be simplified + webGLData = this.getWebGLData(webGL, 0); + + if (data.type === _const.SHAPES.POLY) { + (0, _buildPoly2.default)(data, webGLData); + } + if (data.type === _const.SHAPES.RECT) { + (0, _buildRectangle2.default)(data, webGLData); + } else if (data.type === _const.SHAPES.CIRC || data.type === _const.SHAPES.ELIP) { + (0, _buildCircle2.default)(data, webGLData); + } else if (data.type === _const.SHAPES.RREC) { + (0, _buildRoundedRectangle2.default)(data, webGLData); + } + + webGL.lastIndex++; + } + + this.renderer.bindVao(null); + + // upload all the dirty data... + for (var _i2 = 0; _i2 < webGL.data.length; _i2++) { + webGLData = webGL.data[_i2]; + + if (webGLData.dirty) { + webGLData.upload(); + } + } + }; + + /** + * + * @private + * @param {WebGLRenderingContext} gl - the current WebGL drawing context + * @param {number} type - TODO @Alvin + * @return {*} TODO + */ + + + GraphicsRenderer.prototype.getWebGLData = function getWebGLData(gl, type) { + var webGLData = gl.data[gl.data.length - 1]; + + if (!webGLData || webGLData.points.length > 320000) { + webGLData = this.graphicsDataPool.pop() || new _WebGLGraphicsData2.default(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + + webGLData.reset(type); + gl.data.push(webGLData); + } + + webGLData.dirty = true; + + return webGLData; + }; + + return GraphicsRenderer; +}(_ObjectRenderer3.default); + +exports.default = GraphicsRenderer; + + +_WebGLRenderer2.default.registerPlugin('graphics', GraphicsRenderer); + +},{"../../const":44,"../../renderers/webgl/WebGLRenderer":82,"../../renderers/webgl/utils/ObjectRenderer":92,"../../utils":120,"./WebGLGraphicsData":56,"./shaders/PrimitiveShader":57,"./utils/buildCircle":58,"./utils/buildPoly":60,"./utils/buildRectangle":61,"./utils/buildRoundedRectangle":62}],56:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * An object containing WebGL specific properties to be used by the WebGL renderer + * + * @class + * @private + * @memberof PIXI + */ +var WebGLGraphicsData = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {PIXI.Shader} shader - The shader + * @param {object} attribsState - The state for the VAO + */ + function WebGLGraphicsData(gl, shader, attribsState) { + _classCallCheck(this, WebGLGraphicsData); + + /** + * The current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // TODO does this need to be split before uploading?? + /** + * An array of color components (r,g,b) + * @member {number[]} + */ + this.color = [0, 0, 0]; // color split! + + /** + * An array of points to draw + * @member {PIXI.Point[]} + */ + this.points = []; + + /** + * The indices of the vertices + * @member {number[]} + */ + this.indices = []; + /** + * The main buffer + * @member {WebGLBuffer} + */ + this.buffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl); + + /** + * The index buffer + * @member {WebGLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl); + + /** + * Whether this graphics is dirty or not + * @member {boolean} + */ + this.dirty = true; + + this.glPoints = null; + this.glIndices = null; + + /** + * + * @member {PIXI.Shader} + */ + this.shader = shader; + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, attribsState).addIndex(this.indexBuffer).addAttribute(this.buffer, shader.attributes.aVertexPosition, gl.FLOAT, false, 4 * 6, 0).addAttribute(this.buffer, shader.attributes.aColor, gl.FLOAT, false, 4 * 6, 2 * 4); + } + + /** + * Resets the vertices and the indices + */ + + + WebGLGraphicsData.prototype.reset = function reset() { + this.points.length = 0; + this.indices.length = 0; + }; + + /** + * Binds the buffers and uploads the data + */ + + + WebGLGraphicsData.prototype.upload = function upload() { + this.glPoints = new Float32Array(this.points); + this.buffer.upload(this.glPoints); + + this.glIndices = new Uint16Array(this.indices); + this.indexBuffer.upload(this.glIndices); + + this.dirty = false; + }; + + /** + * Empties all the data + */ + + + WebGLGraphicsData.prototype.destroy = function destroy() { + this.color = null; + this.points = null; + this.indices = null; + + this.vao.destroy(); + this.buffer.destroy(); + this.indexBuffer.destroy(); + + this.gl = null; + + this.buffer = null; + this.indexBuffer = null; + + this.glPoints = null; + this.glIndices = null; + }; + + return WebGLGraphicsData; +}(); + +exports.default = WebGLGraphicsData; + +},{"pixi-gl-core":12}],57:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../../Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. + * + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ +var PrimitiveShader = function (_Shader) { + _inherits(PrimitiveShader, _Shader); + + /** + * @param {WebGLRenderingContext} gl - The webgl shader manager this shader works for. + */ + function PrimitiveShader(gl) { + _classCallCheck(this, PrimitiveShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec4 aColor;', 'uniform mat3 translationMatrix;', 'uniform mat3 projectionMatrix;', 'uniform float alpha;', 'uniform vec3 tint;', 'varying vec4 vColor;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vColor = aColor * vec4(tint * alpha, alpha);', '}'].join('\n'), + // fragment shader + ['varying vec4 vColor;', 'void main(void){', ' gl_FragColor = vColor;', '}'].join('\n'))); + } + + return PrimitiveShader; +}(_Shader3.default); + +exports.default = PrimitiveShader; + +},{"../../../Shader":42}],58:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildCircle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _const = require('../../../const'); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildCircle(graphicsData, webGLData) { + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width = void 0; + var height = void 0; + + // TODO - bit hacky?? + if (graphicsData.type === _const.SHAPES.CIRC) { + width = circleData.radius; + height = circleData.radius; + } else { + width = circleData.width; + height = circleData.height; + } + + if (width === 0 || height === 0) { + return; + } + + var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); + + var seg = Math.PI * 2 / totalSegs; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + indices.push(vecPos); + + for (var i = 0; i < totalSegs + 1; i++) { + verts.push(x, y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos - 1); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (var _i = 0; _i < totalSegs + 1; _i++) { + graphicsData.points.push(x + Math.sin(seg * _i) * width, y + Math.cos(seg * _i) * height); + } + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +},{"../../../const":44,"../../../utils":120,"./buildLine":59}],59:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function (graphicsData, webGLData) { + if (graphicsData.nativeLines) { + buildNativeLine(graphicsData, webGLData); + } else { + buildLine(graphicsData, webGLData); + } +}; + +var _math = require('../../../math'); + +var _utils = require('../../../utils'); + +/** + * Builds a line to draw using the poligon method. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildLine(graphicsData, webGLData) { + // TODO OPTIMISE! + var points = graphicsData.points; + + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + + // get first and last point.. figure out the middle! + var firstPoint = new _math.Point(points[0], points[1]); + var lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + // if the first point is the last point - gonna have issues :) + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var p1x = points[0]; + var p1y = points[1]; + var p2x = points[2]; + var p2y = points[3]; + var p3x = 0; + var p3y = 0; + + var perpx = -(p1y - p2y); + var perpy = p1x - p2x; + var perp2x = 0; + var perp2y = 0; + var perp3x = 0; + var perp3y = 0; + + var dist = Math.sqrt(perpx * perpx + perpy * perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx, p1y - perpy, r, g, b, alpha); + + verts.push(p1x + perpx, p1y + perpy, r, g, b, alpha); + + for (var i = 1; i < length - 1; ++i) { + p1x = points[(i - 1) * 2]; + p1y = points[(i - 1) * 2 + 1]; + + p2x = points[i * 2]; + p2y = points[i * 2 + 1]; + + p3x = points[(i + 1) * 2]; + p3y = points[(i + 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + var a1 = -perpy + p1y - (-perpy + p2y); + var b1 = -perpx + p2x - (-perpx + p1x); + var c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + var a2 = -perp2y + p3y - (-perp2y + p2y); + var b2 = -perp2x + p2x - (-perp2x + p3x); + var c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + var denom = a1 * b2 - a2 * b1; + + if (Math.abs(denom) < 0.1) { + denom += 10.1; + verts.push(p2x - perpx, p2y - perpy, r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy, r, g, b, alpha); + + continue; + } + + var px = (b1 * c2 - b2 * c1) / denom; + var py = (a2 * c1 - a1 * c2) / denom; + var pdist = (px - p2x) * (px - p2x) + (py - p2y) * (py - p2y); + + if (pdist > 196 * width * width) { + perp3x = perpx - perp2x; + perp3y = perpy - perp2y; + + dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y); + perp3x /= dist; + perp3y /= dist; + perp3x *= width; + perp3y *= width; + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x + perp3x, p2y + perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + indexCount++; + } else { + verts.push(px, py); + verts.push(r, g, b, alpha); + + verts.push(p2x - (px - p2x), p2y - (py - p2y)); + verts.push(r, g, b, alpha); + } + } + + p1x = points[(length - 2) * 2]; + p1y = points[(length - 2) * 2 + 1]; + + p2x = points[(length - 1) * 2]; + p2y = points[(length - 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + verts.push(p2x - perpx, p2y - perpy); + verts.push(r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy); + verts.push(r, g, b, alpha); + + indices.push(indexStart); + + for (var _i = 0; _i < indexCount; ++_i) { + indices.push(indexStart++); + } + + indices.push(indexStart - 1); +} + +/** + * Builds a line to draw using the gl.drawArrays(gl.LINES) method + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ + + +/** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildNativeLine(graphicsData, webGLData) { + var i = 0; + var points = graphicsData.points; + + if (points.length === 0) return; + + var verts = webGLData.points; + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + for (i = 1; i < length; i++) { + var p1x = points[(i - 1) * 2]; + var p1y = points[(i - 1) * 2 + 1]; + + var p2x = points[i * 2]; + var p2y = points[i * 2 + 1]; + + verts.push(p1x, p1y); + verts.push(r, g, b, alpha); + + verts.push(p2x, p2y); + verts.push(r, g, b, alpha); + } +} + +},{"../../../math":68,"../../../utils":120}],60:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildPoly; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildPoly(graphicsData, webGLData) { + graphicsData.points = graphicsData.shape.points.slice(); + + var points = graphicsData.points; + + if (graphicsData.fill && points.length >= 6) { + var holeArray = []; + // Process holes.. + var holes = graphicsData.holes; + + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + + holeArray.push(points.length / 2); + + points = points.concat(hole.points); + } + + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = (0, _earcut2.default)(points, holeArray, 2); + + if (!triangles) { + return; + } + + var vertPos = verts.length / 6; + + for (var _i = 0; _i < triangles.length; _i += 3) { + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i + 1] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + } + + for (var _i2 = 0; _i2 < length; _i2++) { + verts.push(points[_i2 * 2], points[_i2 * 2 + 1], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth > 0) { + (0, _buildLine2.default)(graphicsData, webGLData); + } +} + +},{"../../../utils":120,"./buildLine":59,"earcut":2}],61:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRectangle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildRectangle(graphicsData, webGLData) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vertPos = verts.length / 6; + + // start + verts.push(x, y); + verts.push(r, g, b, alpha); + + verts.push(x + width, y); + verts.push(r, g, b, alpha); + + verts.push(x, y + height); + verts.push(r, g, b, alpha); + + verts.push(x + width, y + height); + verts.push(r, g, b, alpha); + + // insert 2 dead triangles.. + indices.push(vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y]; + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +},{"../../../utils":120,"./buildLine":59}],62:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRoundedRectangle; + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildRoundedRectangle(graphicsData, webGLData) { + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + + recPoints.push(x, y + radius); + quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height, recPoints); + quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius, recPoints); + quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y, recPoints); + quadraticBezierCurve(x + radius, y, x, y, x, y + radius + 0.0000000001, recPoints); + + // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. + // TODO - fix this properly, this is not very elegant.. but it works for now. + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + var triangles = (0, _earcut2.default)(recPoints, null, 2); + + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + + for (var _i = 0, _j = recPoints.length; _i < _j; _i++) { + verts.push(recPoints[_i], recPoints[++_i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +/** + * Calculate a single point for a quadratic bezier curve. + * Utility function used by quadraticBezierCurve. + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} n1 - first number + * @param {number} n2 - second number + * @param {number} perc - percentage + * @return {number} the result + * + */ +function getPt(n1, n2, perc) { + var diff = n2 - n1; + + return n1 + diff * perc; +} + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @return {number[]} an array of points + */ +function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY) { + var out = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : []; + + var n = 20; + var points = out; + + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + + points.push(x, y); + } + + return points; +} + +},{"../../../utils":120,"./buildLine":59,"earcut":2}],63:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = exports.Application = exports.Filter = exports.SpriteMaskFilter = exports.Quad = exports.RenderTarget = exports.ObjectRenderer = exports.WebGLManager = exports.Shader = exports.CanvasRenderTarget = exports.TextureUvs = exports.VideoBaseTexture = exports.BaseRenderTexture = exports.RenderTexture = exports.BaseTexture = exports.Texture = exports.Spritesheet = exports.CanvasGraphicsRenderer = exports.GraphicsRenderer = exports.GraphicsData = exports.Graphics = exports.TextStyle = exports.Text = exports.SpriteRenderer = exports.CanvasTinter = exports.CanvasSpriteRenderer = exports.Sprite = exports.TransformBase = exports.TransformStatic = exports.Transform = exports.Container = exports.DisplayObject = exports.Bounds = exports.glCore = exports.WebGLRenderer = exports.CanvasRenderer = exports.ticker = exports.utils = exports.settings = undefined; + +var _const = require('./const'); + +Object.keys(_const).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _const[key]; + } + }); +}); + +var _math = require('./math'); + +Object.keys(_math).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _math[key]; + } + }); +}); + +var _pixiGlCore = require('pixi-gl-core'); + +Object.defineProperty(exports, 'glCore', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_pixiGlCore).default; + } +}); + +var _Bounds = require('./display/Bounds'); + +Object.defineProperty(exports, 'Bounds', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Bounds).default; + } +}); + +var _DisplayObject = require('./display/DisplayObject'); + +Object.defineProperty(exports, 'DisplayObject', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplayObject).default; + } +}); + +var _Container = require('./display/Container'); + +Object.defineProperty(exports, 'Container', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Container).default; + } +}); + +var _Transform = require('./display/Transform'); + +Object.defineProperty(exports, 'Transform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Transform).default; + } +}); + +var _TransformStatic = require('./display/TransformStatic'); + +Object.defineProperty(exports, 'TransformStatic', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformStatic).default; + } +}); + +var _TransformBase = require('./display/TransformBase'); + +Object.defineProperty(exports, 'TransformBase', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformBase).default; + } +}); + +var _Sprite = require('./sprites/Sprite'); + +Object.defineProperty(exports, 'Sprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Sprite).default; + } +}); + +var _CanvasSpriteRenderer = require('./sprites/canvas/CanvasSpriteRenderer'); + +Object.defineProperty(exports, 'CanvasSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasSpriteRenderer).default; + } +}); + +var _CanvasTinter = require('./sprites/canvas/CanvasTinter'); + +Object.defineProperty(exports, 'CanvasTinter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasTinter).default; + } +}); + +var _SpriteRenderer = require('./sprites/webgl/SpriteRenderer'); + +Object.defineProperty(exports, 'SpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteRenderer).default; + } +}); + +var _Text = require('./text/Text'); + +Object.defineProperty(exports, 'Text', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Text).default; + } +}); + +var _TextStyle = require('./text/TextStyle'); + +Object.defineProperty(exports, 'TextStyle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextStyle).default; + } +}); + +var _Graphics = require('./graphics/Graphics'); + +Object.defineProperty(exports, 'Graphics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Graphics).default; + } +}); + +var _GraphicsData = require('./graphics/GraphicsData'); + +Object.defineProperty(exports, 'GraphicsData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsData).default; + } +}); + +var _GraphicsRenderer = require('./graphics/webgl/GraphicsRenderer'); + +Object.defineProperty(exports, 'GraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsRenderer).default; + } +}); + +var _CanvasGraphicsRenderer = require('./graphics/canvas/CanvasGraphicsRenderer'); + +Object.defineProperty(exports, 'CanvasGraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasGraphicsRenderer).default; + } +}); + +var _Spritesheet = require('./textures/Spritesheet'); + +Object.defineProperty(exports, 'Spritesheet', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Spritesheet).default; + } +}); + +var _Texture = require('./textures/Texture'); + +Object.defineProperty(exports, 'Texture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Texture).default; + } +}); + +var _BaseTexture = require('./textures/BaseTexture'); + +Object.defineProperty(exports, 'BaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseTexture).default; + } +}); + +var _RenderTexture = require('./textures/RenderTexture'); + +Object.defineProperty(exports, 'RenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTexture).default; + } +}); + +var _BaseRenderTexture = require('./textures/BaseRenderTexture'); + +Object.defineProperty(exports, 'BaseRenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseRenderTexture).default; + } +}); + +var _VideoBaseTexture = require('./textures/VideoBaseTexture'); + +Object.defineProperty(exports, 'VideoBaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VideoBaseTexture).default; + } +}); + +var _TextureUvs = require('./textures/TextureUvs'); + +Object.defineProperty(exports, 'TextureUvs', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureUvs).default; + } +}); + +var _CanvasRenderTarget = require('./renderers/canvas/utils/CanvasRenderTarget'); + +Object.defineProperty(exports, 'CanvasRenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasRenderTarget).default; + } +}); + +var _Shader = require('./Shader'); + +Object.defineProperty(exports, 'Shader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Shader).default; + } +}); + +var _WebGLManager = require('./renderers/webgl/managers/WebGLManager'); + +Object.defineProperty(exports, 'WebGLManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLManager).default; + } +}); + +var _ObjectRenderer = require('./renderers/webgl/utils/ObjectRenderer'); + +Object.defineProperty(exports, 'ObjectRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObjectRenderer).default; + } +}); + +var _RenderTarget = require('./renderers/webgl/utils/RenderTarget'); + +Object.defineProperty(exports, 'RenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTarget).default; + } +}); + +var _Quad = require('./renderers/webgl/utils/Quad'); + +Object.defineProperty(exports, 'Quad', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Quad).default; + } +}); + +var _SpriteMaskFilter = require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter'); + +Object.defineProperty(exports, 'SpriteMaskFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteMaskFilter).default; + } +}); + +var _Filter = require('./renderers/webgl/filters/Filter'); + +Object.defineProperty(exports, 'Filter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Filter).default; + } +}); + +var _Application = require('./Application'); + +Object.defineProperty(exports, 'Application', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Application).default; + } +}); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +Object.defineProperty(exports, 'autoDetectRenderer', { + enumerable: true, + get: function get() { + return _autoDetectRenderer.autoDetectRenderer; + } +}); + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _ticker = require('./ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.settings = _settings2.default; +exports.utils = utils; +exports.ticker = ticker; +exports.CanvasRenderer = _CanvasRenderer2.default; +exports.WebGLRenderer = _WebGLRenderer2.default; /** + * @namespace PIXI + */ + +},{"./Application":41,"./Shader":42,"./autoDetectRenderer":43,"./const":44,"./display/Bounds":45,"./display/Container":46,"./display/DisplayObject":47,"./display/Transform":48,"./display/TransformBase":49,"./display/TransformStatic":50,"./graphics/Graphics":51,"./graphics/GraphicsData":52,"./graphics/canvas/CanvasGraphicsRenderer":53,"./graphics/webgl/GraphicsRenderer":55,"./math":68,"./renderers/canvas/CanvasRenderer":75,"./renderers/canvas/utils/CanvasRenderTarget":77,"./renderers/webgl/WebGLRenderer":82,"./renderers/webgl/filters/Filter":84,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":87,"./renderers/webgl/managers/WebGLManager":91,"./renderers/webgl/utils/ObjectRenderer":92,"./renderers/webgl/utils/Quad":93,"./renderers/webgl/utils/RenderTarget":94,"./settings":99,"./sprites/Sprite":100,"./sprites/canvas/CanvasSpriteRenderer":101,"./sprites/canvas/CanvasTinter":102,"./sprites/webgl/SpriteRenderer":104,"./text/Text":106,"./text/TextStyle":107,"./textures/BaseRenderTexture":108,"./textures/BaseTexture":109,"./textures/RenderTexture":110,"./textures/Spritesheet":111,"./textures/Texture":112,"./textures/TextureUvs":113,"./textures/VideoBaseTexture":114,"./ticker":116,"./utils":120,"pixi-gl-core":12}],64:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Matrix = require('./Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16 + +var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; +var tempMatrices = []; + +var mul = []; + +function signum(x) { + if (x < 0) { + return -1; + } + if (x > 0) { + return 1; + } + + return 0; +} + +function init() { + for (var i = 0; i < 16; i++) { + var row = []; + + mul.push(row); + + for (var j = 0; j < 16; j++) { + var _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); + var _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); + var _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); + var _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); + + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + + for (var _i = 0; _i < 16; _i++) { + var mat = new _Matrix2.default(); + + mat.set(ux[_i], uy[_i], vx[_i], vy[_i], 0, 0); + tempMatrices.push(mat); + } +} + +init(); + +/** + * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, + * D8 is the same but with diagonals. Used for texture rotations. + * + * Vector xX(i), xY(i) is U-axis of sprite with rotation i + * Vector yY(i), yY(i) is V-axis of sprite with rotation i + * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) + * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) + * This is the small part of gameofbombs.com portal system. It works. + * + * @author Ivan @ivanpopelyshev + * @class + * @memberof PIXI + */ +var GroupD8 = { + E: 0, + SE: 1, + S: 2, + SW: 3, + W: 4, + NW: 5, + N: 6, + NE: 7, + MIRROR_VERTICAL: 8, + MIRROR_HORIZONTAL: 12, + uX: function uX(ind) { + return ux[ind]; + }, + uY: function uY(ind) { + return uy[ind]; + }, + vX: function vX(ind) { + return vx[ind]; + }, + vY: function vY(ind) { + return vy[ind]; + }, + inv: function inv(rotation) { + if (rotation & 8) { + return rotation & 15; + } + + return -rotation & 7; + }, + add: function add(rotationSecond, rotationFirst) { + return mul[rotationSecond][rotationFirst]; + }, + sub: function sub(rotationSecond, rotationFirst) { + return mul[rotationSecond][GroupD8.inv(rotationFirst)]; + }, + + /** + * Adds 180 degrees to rotation. Commutative operation. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to rotate. + * @returns {number} rotated number + */ + rotate180: function rotate180(rotation) { + return rotation ^ 4; + }, + + /** + * I dont know why sometimes width and heights needs to be swapped. We'll fix it later. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the width/height should be swapped. + */ + isSwapWidthHeight: function isSwapWidthHeight(rotation) { + return (rotation & 3) === 2; + }, + + /** + * @memberof PIXI.GroupD8 + * @param {number} dx - TODO + * @param {number} dy - TODO + * + * @return {number} TODO + */ + byDirection: function byDirection(dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return GroupD8.S; + } + + return GroupD8.N; + } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return GroupD8.E; + } + + return GroupD8.W; + } else if (dy > 0) { + if (dx > 0) { + return GroupD8.SE; + } + + return GroupD8.SW; + } else if (dx > 0) { + return GroupD8.NE; + } + + return GroupD8.NW; + }, + + /** + * Helps sprite to compensate texture packer rotation. + * + * @memberof PIXI.GroupD8 + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {number} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function matrixAppendRotationInv(matrix, rotation) { + var tx = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var ty = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + // Packer used "rotation", we use "inv(rotation)" + var mat = tempMatrices[GroupD8.inv(rotation)]; + + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + } +}; + +exports.default = GroupD8; + +},{"./Matrix":65}],65:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Point = require('./Point'); + +var _Point2 = _interopRequireDefault(_Point); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The pixi Matrix class as an object, which makes it a lot faster, + * here is a representation of it : + * | a | b | tx| + * | c | d | ty| + * | 0 | 0 | 1 | + * + * @class + * @memberof PIXI + */ +var Matrix = function () { + /** + * @param {number} [a=1] - x scale + * @param {number} [b=0] - y skew + * @param {number} [c=0] - x skew + * @param {number} [d=1] - y scale + * @param {number} [tx=0] - x translation + * @param {number} [ty=0] - y translation + */ + function Matrix() { + var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var d = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var tx = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var ty = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + + _classCallCheck(this, Matrix); + + /** + * @member {number} + * @default 1 + */ + this.a = a; + + /** + * @member {number} + * @default 0 + */ + this.b = b; + + /** + * @member {number} + * @default 0 + */ + this.c = c; + + /** + * @member {number} + * @default 1 + */ + this.d = d; + + /** + * @member {number} + * @default 0 + */ + this.tx = tx; + + /** + * @member {number} + * @default 0 + */ + this.ty = ty; + + this.array = null; + } + + /** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @param {number[]} array - The array that the matrix will be populated from. + */ + + + Matrix.prototype.fromArray = function fromArray(array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + }; + + /** + * sets the matrix properties + * + * @param {number} a - Matrix component + * @param {number} b - Matrix component + * @param {number} c - Matrix component + * @param {number} d - Matrix component + * @param {number} tx - Matrix component + * @param {number} ty - Matrix component + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.set = function set(a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + }; + + /** + * Creates an array from the current Matrix object. + * + * @param {boolean} transpose - Whether we need to transpose the matrix or not + * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out + * @return {number[]} the newly created array which contains the matrix + */ + + + Matrix.prototype.toArray = function toArray(transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + + var array = out || this.array; + + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + }; + + /** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, transformed through this matrix + */ + + + Matrix.prototype.apply = function apply(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; + + return newPos; + }; + + /** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, inverse-transformed through this matrix + */ + + + Matrix.prototype.applyInverse = function applyInverse(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var id = 1 / (this.a * this.d + this.c * -this.b); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + }; + + /** + * Translates the matrix on the x and y. + * + * @param {number} x How much to translate x by + * @param {number} y How much to translate y by + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.translate = function translate(x, y) { + this.tx += x; + this.ty += y; + + return this; + }; + + /** + * Applies a scale transformation to the matrix. + * + * @param {number} x The amount to scale horizontally + * @param {number} y The amount to scale vertically + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.scale = function scale(x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + }; + + /** + * Applies a rotation transformation to the matrix. + * + * @param {number} angle - The angle in radians. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.rotate = function rotate(angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos - this.b * sin; + this.b = a1 * sin + this.b * cos; + this.c = c1 * cos - this.d * sin; + this.d = c1 * sin + this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + }; + + /** + * Appends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to append. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.append = function append(matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + }; + + /** + * Sets the matrix based on all the available properties + * + * @param {number} x - Position on the x axis + * @param {number} y - Position on the y axis + * @param {number} pivotX - Pivot on the x axis + * @param {number} pivotY - Pivot on the y axis + * @param {number} scaleX - Scale on the x axis + * @param {number} scaleY - Scale on the y axis + * @param {number} rotation - Rotation in radians + * @param {number} skewX - Skew on the x axis + * @param {number} skewY - Skew on the y axis + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.setTransform = function setTransform(x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + var sr = Math.sin(rotation); + var cr = Math.cos(rotation); + var cy = Math.cos(skewY); + var sy = Math.sin(skewY); + var nsx = -Math.sin(skewX); + var cx = Math.cos(skewX); + + var a = cr * scaleX; + var b = sr * scaleX; + var c = -sr * scaleY; + var d = cr * scaleY; + + this.a = cy * a + sy * c; + this.b = cy * b + sy * d; + this.c = nsx * a + cx * c; + this.d = nsx * b + cx * d; + + this.tx = x + (pivotX * a + pivotY * c); + this.ty = y + (pivotX * b + pivotY * d); + + return this; + }; + + /** + * Prepends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to prepend + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.prepend = function prepend(matrix) { + var tx1 = this.tx; + + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + + this.a = a1 * matrix.a + this.b * matrix.c; + this.b = a1 * matrix.b + this.b * matrix.d; + this.c = c1 * matrix.a + this.d * matrix.c; + this.d = c1 * matrix.b + this.d * matrix.d; + } + + this.tx = tx1 * matrix.a + this.ty * matrix.c + matrix.tx; + this.ty = tx1 * matrix.b + this.ty * matrix.d + matrix.ty; + + return this; + }; + + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * + * @param {PIXI.Transform|PIXI.TransformStatic} transform - The transform to apply the properties to. + * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properties + */ + + + Matrix.prototype.decompose = function decompose(transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + + var skewX = -Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + + var delta = Math.abs(skewX + skewY); + + if (delta < 0.00001) { + transform.rotation = skewY; + + if (a < 0 && d >= 0) { + transform.rotation += transform.rotation <= 0 ? Math.PI : -Math.PI; + } + + transform.skew.x = transform.skew.y = 0; + } else { + transform.skew.x = skewX; + transform.skew.y = skewY; + } + + // next set scale + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); + + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; + + return transform; + }; + + /** + * Inverts this matrix + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.invert = function invert() { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1 * d1 - b1 * c1; + + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = (c1 * this.ty - d1 * tx1) / n; + this.ty = -(a1 * this.ty - b1 * tx1) / n; + + return this; + }; + + /** + * Resets this Matix to an identity (default) matrix. + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.identity = function identity() { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + + return this; + }; + + /** + * Creates a new Matrix object with the same values as this one. + * + * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. + */ + + + Matrix.prototype.clone = function clone() { + var matrix = new Matrix(); + + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * Changes the values of the given matrix to be the same as the ones in this matrix + * + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @return {PIXI.Matrix} The matrix given in parameter with its values updated. + */ + + + Matrix.prototype.copy = function copy(matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * A default (identity) matrix + * + * @static + * @const + */ + + + _createClass(Matrix, null, [{ + key: 'IDENTITY', + get: function get() { + return new Matrix(); + } + + /** + * A temp matrix + * + * @static + * @const + */ + + }, { + key: 'TEMP_MATRIX', + get: function get() { + return new Matrix(); + } + }]); + + return Matrix; +}(); + +exports.default = Matrix; + +},{"./Point":67}],66:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * An observable point is a point that triggers a callback when the point's position is changed. + * + * @class + * @memberof PIXI + */ +var ObservablePoint = function () { + /** + * @param {Function} cb - callback when changed + * @param {object} scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope) { + var x = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var y = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, ObservablePoint); + + this._x = x; + this._y = y; + + this.cb = cb; + this.scope = scope; + } + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + ObservablePoint.prototype.set = function set(x, y) { + var _x = x || 0; + var _y = y || (y !== 0 ? _x : 0); + + if (this._x !== _x || this._y !== _y) { + this._x = _x; + this._y = _y; + this.cb.call(this.scope); + } + }; + + /** + * Copies the data from another point + * + * @param {PIXI.Point|PIXI.ObservablePoint} point - point to copy from + */ + + + ObservablePoint.prototype.copy = function copy(point) { + if (this._x !== point.x || this._y !== point.y) { + this._x = point.x; + this._y = point.y; + this.cb.call(this.scope); + } + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + + _createClass(ObservablePoint, [{ + key: "x", + get: function get() { + return this._x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + } + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + }, { + key: "y", + get: function get() { + return this._y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + } + }]); + + return ObservablePoint; +}(); + +exports.default = ObservablePoint; + +},{}],67:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * + * @class + * @memberof PIXI + */ +var Point = function () { + /** + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function Point() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + + _classCallCheck(this, Point); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + } + + /** + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point + */ + + + Point.prototype.clone = function clone() { + return new Point(this.x, this.y); + }; + + /** + * Copies x and y from the given point + * + * @param {PIXI.Point} p - The point to copy. + */ + + + Point.prototype.copy = function copy(p) { + this.set(p.x, p.y); + }; + + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.Point} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + + + Point.prototype.equals = function equals(p) { + return p.x === this.x && p.y === this.y; + }; + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + Point.prototype.set = function set(x, y) { + this.x = x || 0; + this.y = y || (y !== 0 ? this.x : 0); + }; + + return Point; +}(); + +exports.default = Point; + +},{}],68:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('./Point'); + +Object.defineProperty(exports, 'Point', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Point).default; + } +}); + +var _ObservablePoint = require('./ObservablePoint'); + +Object.defineProperty(exports, 'ObservablePoint', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObservablePoint).default; + } +}); + +var _Matrix = require('./Matrix'); + +Object.defineProperty(exports, 'Matrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Matrix).default; + } +}); + +var _GroupD = require('./GroupD8'); + +Object.defineProperty(exports, 'GroupD8', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GroupD).default; + } +}); + +var _Circle = require('./shapes/Circle'); + +Object.defineProperty(exports, 'Circle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Circle).default; + } +}); + +var _Ellipse = require('./shapes/Ellipse'); + +Object.defineProperty(exports, 'Ellipse', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Ellipse).default; + } +}); + +var _Polygon = require('./shapes/Polygon'); + +Object.defineProperty(exports, 'Polygon', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Polygon).default; + } +}); + +var _Rectangle = require('./shapes/Rectangle'); + +Object.defineProperty(exports, 'Rectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rectangle).default; + } +}); + +var _RoundedRectangle = require('./shapes/RoundedRectangle'); + +Object.defineProperty(exports, 'RoundedRectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RoundedRectangle).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./GroupD8":64,"./Matrix":65,"./ObservablePoint":66,"./Point":67,"./shapes/Circle":69,"./shapes/Ellipse":70,"./shapes/Polygon":71,"./shapes/Rectangle":72,"./shapes/RoundedRectangle":73}],69:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Circle object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Circle = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [radius=0] - The radius of the circle + */ + function Circle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var radius = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + _classCallCheck(this, Circle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.CIRC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.CIRC; + } + + /** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ + + + Circle.prototype.clone = function clone() { + return new Circle(this.x, this.y, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this circle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Circle + */ + + + Circle.prototype.contains = function contains(x, y) { + if (this.radius <= 0) { + return false; + } + + var r2 = this.radius * this.radius; + var dx = this.x - x; + var dy = this.y - y; + + dx *= dx; + dy *= dy; + + return dx + dy <= r2; + }; + + /** + * Returns the framing rectangle of the circle as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Circle.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + + return Circle; +}(); + +exports.default = Circle; + +},{"../../const":44,"./Rectangle":72}],70:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Ellipse object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Ellipse = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [width=0] - The half width of this ellipse + * @param {number} [height=0] - The half height of this ellipse + */ + function Ellipse() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Ellipse); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.ELIP + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.ELIP; + } + + /** + * Creates a clone of this Ellipse instance + * + * @return {PIXI.Ellipse} a copy of the ellipse + */ + + + Ellipse.prototype.clone = function clone() { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coords are within this ellipse + */ + + + Ellipse.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + // normalize the coords to an ellipse with center 0,0 + var normx = (x - this.x) / this.width; + var normy = (y - this.y) / this.height; + + normx *= normx; + normy *= normy; + + return normx + normy <= 1; + }; + + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Ellipse.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.width, this.y - this.height, this.width, this.height); + }; + + return Ellipse; +}(); + +exports.default = Ellipse; + +},{"../../const":44,"./Rectangle":72}],71:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('../Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Polygon = function () { + /** + * @param {PIXI.Point[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + for (var _len = arguments.length, points = Array(_len), _key = 0; _key < _len; _key++) { + points[_key] = arguments[_key]; + } + + _classCallCheck(this, Polygon); + + if (Array.isArray(points[0])) { + points = points[0]; + } + + // if this is an array of points, convert it to a flat array of numbers + if (points[0] instanceof _Point2.default) { + var p = []; + + for (var i = 0, il = points.length; i < il; i++) { + p.push(points[i].x, points[i].y); + } + + points = p; + } + + this.closed = true; + + /** + * An array of the points of this polygon + * + * @member {number[]} + */ + this.points = points; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.POLY + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.POLY; + } + + /** + * Creates a clone of this polygon + * + * @return {PIXI.Polygon} a copy of the polygon + */ + + + Polygon.prototype.clone = function clone() { + return new Polygon(this.points.slice()); + }; + + /** + * Closes the polygon, adding points if necessary. + * + */ + + + Polygon.prototype.close = function close() { + var points = this.points; + + // close the poly if the value is true! + if (points[0] !== points[points.length - 2] || points[1] !== points[points.length - 1]) { + points.push(points[0], points[1]); + } + }; + + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this polygon + */ + + + Polygon.prototype.contains = function contains(x, y) { + var inside = false; + + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + + for (var i = 0, j = length - 1; i < length; j = i++) { + var xi = this.points[i * 2]; + var yi = this.points[i * 2 + 1]; + var xj = this.points[j * 2]; + var yj = this.points[j * 2 + 1]; + var intersect = yi > y !== yj > y && x < (xj - xi) * ((y - yi) / (yj - yi)) + xi; + + if (intersect) { + inside = !inside; + } + } + + return inside; + }; + + return Polygon; +}(); + +exports.default = Polygon; + +},{"../../const":44,"../Point":67}],72:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * + * @class + * @memberof PIXI + */ +var Rectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle + * @param {number} [width=0] - The overall width of this rectangle + * @param {number} [height=0] - The overall height of this rectangle + */ + function Rectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Rectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.RECT + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RECT; + } + + /** + * returns the left edge of the rectangle + * + * @member {number} + */ + + + /** + * Creates a clone of this Rectangle + * + * @return {PIXI.Rectangle} a copy of the rectangle + */ + Rectangle.prototype.clone = function clone() { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + + /** + * Copies another rectangle to this one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to copy. + * @return {PIXI.Rectangle} Returns itself. + */ + + + Rectangle.prototype.copy = function copy(rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + + return this; + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rectangle + */ + + + Rectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + + return false; + }; + + /** + * Pads the rectangle making it grow in all directions. + * + * @param {number} paddingX - The horizontal padding amount. + * @param {number} paddingY - The vertical padding amount. + */ + + + Rectangle.prototype.pad = function pad(paddingX, paddingY) { + paddingX = paddingX || 0; + paddingY = paddingY || (paddingY !== 0 ? paddingX : 0); + + this.x -= paddingX; + this.y -= paddingY; + + this.width += paddingX * 2; + this.height += paddingY * 2; + }; + + /** + * Fits this rectangle around the passed one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to fit. + */ + + + Rectangle.prototype.fit = function fit(rectangle) { + if (this.x < rectangle.x) { + this.width += this.x; + if (this.width < 0) { + this.width = 0; + } + + this.x = rectangle.x; + } + + if (this.y < rectangle.y) { + this.height += this.y; + if (this.height < 0) { + this.height = 0; + } + this.y = rectangle.y; + } + + if (this.x + this.width > rectangle.x + rectangle.width) { + this.width = rectangle.width - this.x; + if (this.width < 0) { + this.width = 0; + } + } + + if (this.y + this.height > rectangle.y + rectangle.height) { + this.height = rectangle.height - this.y; + if (this.height < 0) { + this.height = 0; + } + } + }; + + /** + * Enlarges this rectangle to include the passed rectangle. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to include. + */ + + + Rectangle.prototype.enlarge = function enlarge(rectangle) { + var x1 = Math.min(this.x, rectangle.x); + var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.min(this.y, rectangle.y); + var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); + + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + }; + + _createClass(Rectangle, [{ + key: 'left', + get: function get() { + return this.x; + } + + /** + * returns the right edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'right', + get: function get() { + return this.x + this.width; + } + + /** + * returns the top edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'top', + get: function get() { + return this.y; + } + + /** + * returns the bottom edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'bottom', + get: function get() { + return this.y + this.height; + } + + /** + * A constant empty rectangle. + * + * @static + * @constant + */ + + }], [{ + key: 'EMPTY', + get: function get() { + return new Rectangle(0, 0, 0, 0); + } + }]); + + return Rectangle; +}(); + +exports.default = Rectangle; + +},{"../../const":44}],73:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. + * + * @class + * @memberof PIXI + */ +var RoundedRectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle + * @param {number} [width=0] - The overall width of this rounded rectangle + * @param {number} [height=0] - The overall height of this rounded rectangle + * @param {number} [radius=20] - Controls the radius of the rounded corners + */ + function RoundedRectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var radius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 20; + + _classCallCheck(this, RoundedRectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * @member {number} + * @default 20 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readonly + * @default PIXI.SHAPES.RREC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RREC; + } + + /** + * Creates a clone of this Rounded Rectangle + * + * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle + */ + + + RoundedRectangle.prototype.clone = function clone() { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + */ + + + RoundedRectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + if (y >= this.y + this.radius && y <= this.y + this.height - this.radius || x >= this.x + this.radius && x <= this.x + this.width - this.radius) { + return true; + } + var dx = x - (this.x + this.radius); + var dy = y - (this.y + this.radius); + var radius2 = this.radius * this.radius; + + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.width - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dy = y - (this.y + this.height - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + } + } + + return false; + }; + + return RoundedRectangle; +}(); + +exports.default = RoundedRectangle; + +},{"../../const":44}],74:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _math = require('../math'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _Container = require('../display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMatrix = new _math.Matrix(); + +/** + * The SystemRenderer is the base for a Pixi Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.WebGLRenderer} which can be used for rendering a Pixi scene. + * + * @abstract + * @class + * @extends EventEmitter + * @memberof PIXI + */ + +var SystemRenderer = function (_EventEmitter) { + _inherits(SystemRenderer, _EventEmitter); + + /** + * @param {string} system - The name of the system this renderer is for. + * @param {number} [screenWidth=800] - the width of the screen + * @param {number} [screenHeight=600] - the height of the screen + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function SystemRenderer(system, screenWidth, screenHeight, options) { + _classCallCheck(this, SystemRenderer); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + (0, _utils.sayHello)(system); + + // prepare options + if (options) { + for (var i in _settings2.default.RENDER_OPTIONS) { + if (typeof options[i] === 'undefined') { + options[i] = _settings2.default.RENDER_OPTIONS[i]; + } + } + } else { + options = _settings2.default.RENDER_OPTIONS; + } + + /** + * The type of the renderer. + * + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.UNKNOWN; + + /** + * Measurements of the screen. (0, 0, screenWidth, screenHeight) + * + * Its safe to use as filterArea or hitArea for whole stage + * + * @member {PIXI.Rectangle} + */ + _this.screen = new _math.Rectangle(0, 0, screenWidth || 800, screenHeight || 600); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.view = options.view || document.createElement('canvas'); + + /** + * The resolution / device pixel ratio of the renderer + * + * @member {number} + * @default 1 + */ + _this.resolution = options.resolution || _settings2.default.RESOLUTION; + + /** + * Whether the render view is transparent + * + * @member {boolean} + */ + _this.transparent = options.transparent; + + /** + * Whether css dimensions of canvas view should be resized to screen dimensions automatically + * + * @member {boolean} + */ + _this.autoResize = options.autoResize || false; + + /** + * Tracks the blend modes useful for this renderer. + * + * @member {object} + */ + _this.blendModes = null; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent Pixi will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent Pixi will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example if + * your game has a canvas filling background image you often don't need this set. + * + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + * + * @member {boolean} + */ + _this.roundPixels = options.roundPixels; + + /** + * The background color as a number. + * + * @member {number} + * @private + */ + _this._backgroundColor = 0x000000; + + /** + * The background color as an [R, G, B] array. + * + * @member {number[]} + * @private + */ + _this._backgroundColorRgba = [0, 0, 0, 0]; + + /** + * The background color as a string. + * + * @member {string} + * @private + */ + _this._backgroundColorString = '#000000'; + + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + + /** + * This temporary display object used as the parent of the currently being rendered item + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._tempDisplayObjectParent = new _Container2.default(); + + /** + * The last root object that the renderer tried to render. + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._lastObjectRendered = _this._tempDisplayObjectParent; + return _this; + } + + /** + * Same as view.width, actual number of pixels in the canvas by horizontal + * + * @member {number} + * @readonly + * @default 800 + */ + + + /** + * Resizes the screen and canvas to the specified width and height + * Canvas dimensions are multiplied by resolution + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + SystemRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + this.screen.width = screenWidth; + this.screen.height = screenHeight; + + this.view.width = screenWidth * this.resolution; + this.view.height = screenHeight * this.resolution; + + if (this.autoResize) { + this.view.style.width = screenWidth + 'px'; + this.view.style.height = screenHeight + 'px'; + } + }; + + /** + * Useful function that returns a texture of the display object that can then be used to create sprites + * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. + * + * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from + * @param {number} scaleMode - Should be one of the scaleMode consts + * @param {number} resolution - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.Texture} a texture of the graphics object + */ + + + SystemRenderer.prototype.generateTexture = function generateTexture(displayObject, scaleMode, resolution) { + var bounds = displayObject.getLocalBounds(); + + var renderTexture = _RenderTexture2.default.create(bounds.width | 0, bounds.height | 0, scaleMode, resolution); + + tempMatrix.tx = -bounds.x; + tempMatrix.ty = -bounds.y; + + this.render(displayObject, renderTexture, false, tempMatrix, true); + + return renderTexture; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + SystemRenderer.prototype.destroy = function destroy(removeView) { + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } + + this.type = _const.RENDERER_TYPE.UNKNOWN; + + this.view = null; + + this.screen = null; + + this.resolution = 0; + + this.transparent = false; + + this.autoResize = false; + + this.blendModes = null; + + this.preserveDrawingBuffer = false; + this.clearBeforeRender = false; + + this.roundPixels = false; + + this._backgroundColor = 0; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + + this.backgroundColor = 0; + this._tempDisplayObjectParent = null; + this._lastObjectRendered = null; + }; + + /** + * The background color to fill if not transparent + * + * @member {number} + */ + + + _createClass(SystemRenderer, [{ + key: 'width', + get: function get() { + return this.view.width; + } + + /** + * Same as view.height, actual number of pixels in the canvas by vertical + * + * @member {number} + * @readonly + * @default 600 + */ + + }, { + key: 'height', + get: function get() { + return this.view.height; + } + }, { + key: 'backgroundColor', + get: function get() { + return this._backgroundColor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._backgroundColor = value; + this._backgroundColorString = (0, _utils.hex2string)(value); + (0, _utils.hex2rgb)(value, this._backgroundColorRgba); + } + }]); + + return SystemRenderer; +}(_eventemitter2.default); + +exports.default = SystemRenderer; + +},{"../const":44,"../display/Container":46,"../math":68,"../settings":99,"../textures/RenderTexture":110,"../utils":120,"eventemitter3":3}],75:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _CanvasMaskManager = require('./utils/CanvasMaskManager'); + +var _CanvasMaskManager2 = _interopRequireDefault(_CanvasMaskManager); + +var _CanvasRenderTarget = require('./utils/CanvasRenderTarget'); + +var _CanvasRenderTarget2 = _interopRequireDefault(_CanvasRenderTarget); + +var _mapCanvasBlendModesToPixi = require('./utils/mapCanvasBlendModesToPixi'); + +var _mapCanvasBlendModesToPixi2 = _interopRequireDefault(_mapCanvasBlendModesToPixi); + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should + * be used for browsers that do not support WebGL. Don't forget to add the CanvasRenderer.view to + * your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ +var CanvasRenderer = function (_SystemRenderer) { + _inherits(CanvasRenderer, _SystemRenderer); + + /** + * @param {number} [screenWidth=800] - the width of the screen + * @param {number} [screenHeight=600] - the height of the screen + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function CanvasRenderer(screenWidth, screenHeight) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + _classCallCheck(this, CanvasRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'Canvas', screenWidth, screenHeight, options)); + + _this.type = _const.RENDERER_TYPE.CANVAS; + + /** + * The canvas 2d context that everything is drawn with. + * + * @member {CanvasRenderingContext2D} + */ + _this.rootContext = _this.view.getContext('2d', { alpha: _this.transparent }); + + /** + * Boolean flag controlling canvas refresh. + * + * @member {boolean} + */ + _this.refresh = true; + + /** + * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. + * + * @member {PIXI.CanvasMaskManager} + */ + _this.maskManager = new _CanvasMaskManager2.default(_this); + + /** + * The canvas property used to set the canvas smoothing property. + * + * @member {string} + */ + _this.smoothProperty = 'imageSmoothingEnabled'; + + if (!_this.rootContext.imageSmoothingEnabled) { + if (_this.rootContext.webkitImageSmoothingEnabled) { + _this.smoothProperty = 'webkitImageSmoothingEnabled'; + } else if (_this.rootContext.mozImageSmoothingEnabled) { + _this.smoothProperty = 'mozImageSmoothingEnabled'; + } else if (_this.rootContext.oImageSmoothingEnabled) { + _this.smoothProperty = 'oImageSmoothingEnabled'; + } else if (_this.rootContext.msImageSmoothingEnabled) { + _this.smoothProperty = 'msImageSmoothingEnabled'; + } + } + + _this.initPlugins(); + + _this.blendModes = (0, _mapCanvasBlendModesToPixi2.default)(); + _this._activeBlendMode = null; + + _this.context = null; + _this.renderingToScreen = false; + + _this.resize(screenWidth, screenHeight); + return _this; + } + + /** + * Renders the object to this canvas view + * + * @param {PIXI.DisplayObject} displayObject - The object to be rendered + * @param {PIXI.RenderTexture} [renderTexture] - A render texture to be rendered to. + * If unset, it will render to the root context. + * @param {boolean} [clear=false] - Whether to clear the canvas before drawing + * @param {PIXI.Transform} [transform] - A transformation to be applied + * @param {boolean} [skipUpdateTransform=false] - Whether to skip the update transform + */ + + + CanvasRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!this.view) { + return; + } + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + var rootResolution = this.resolution; + + if (renderTexture) { + renderTexture = renderTexture.baseTexture || renderTexture; + + if (!renderTexture._canvasRenderTarget) { + renderTexture._canvasRenderTarget = new _CanvasRenderTarget2.default(renderTexture.width, renderTexture.height, renderTexture.resolution); + renderTexture.source = renderTexture._canvasRenderTarget.canvas; + renderTexture.valid = true; + } + + this.context = renderTexture._canvasRenderTarget.context; + this.resolution = renderTexture._canvasRenderTarget.resolution; + } else { + this.context = this.rootContext; + } + + var context = this.context; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + var tempWt = this._tempDisplayObjectParent.transform.worldTransform; + + if (transform) { + transform.copy(tempWt); + + // lets not forget to flag the parent transform as dirty... + this._tempDisplayObjectParent.transform._worldID = -1; + } else { + tempWt.identity(); + } + + displayObject.parent = this._tempDisplayObjectParent; + + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + context.setTransform(1, 0, 0, 1, 0, 0); + context.globalAlpha = 1; + context.globalCompositeOperation = this.blendModes[_const.BLEND_MODES.NORMAL]; + + if (navigator.isCocoonJS && this.view.screencanvas) { + context.fillStyle = 'black'; + context.clear(); + } + + if (clear !== undefined ? clear : this.clearBeforeRender) { + if (this.renderingToScreen) { + if (this.transparent) { + context.clearRect(0, 0, this.width, this.height); + } else { + context.fillStyle = this._backgroundColorString; + context.fillRect(0, 0, this.width, this.height); + } + } // else { + // TODO: implement background for CanvasRenderTarget or RenderTexture? + // } + } + + // TODO RENDER TARGET STUFF HERE.. + var tempContext = this.context; + + this.context = context; + displayObject.renderCanvas(this); + this.context = tempContext; + + this.resolution = rootResolution; + + this.emit('postrender'); + }; + + /** + * Clear the canvas of renderer. + * + * @param {string} [clearColor] - Clear the canvas with this color, except the canvas is transparent. + */ + + + CanvasRenderer.prototype.clear = function clear(clearColor) { + var context = this.context; + + clearColor = clearColor || this._backgroundColorString; + + if (!this.transparent && clearColor) { + context.fillStyle = clearColor; + context.fillRect(0, 0, this.width, this.height); + } else { + context.clearRect(0, 0, this.width, this.height); + } + }; + + /** + * Sets the blend mode of the renderer. + * + * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values. + */ + + + CanvasRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + if (this._activeBlendMode === blendMode) { + return; + } + + this._activeBlendMode = blendMode; + this.context.globalCompositeOperation = this.blendModes[blendMode]; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + CanvasRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // call the base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.context = null; + + this.refresh = true; + + this.maskManager.destroy(); + this.maskManager = null; + + this.smoothProperty = null; + }; + + /** + * Resizes the canvas view to the specified width and height. + * + * @extends PIXI.SystemRenderer#resize + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + CanvasRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + _SystemRenderer.prototype.resize.call(this, screenWidth, screenHeight); + + // reset the scale mode.. oddly this seems to be reset when the canvas is resized. + // surely a browser bug?? Let pixi fix that for you.. + if (this.smoothProperty) { + this.rootContext[this.smoothProperty] = _settings2.default.SCALE_MODE === _const.SCALE_MODES.LINEAR; + } + }; + + return CanvasRenderer; +}(_SystemRenderer3.default); + +exports.default = CanvasRenderer; + + +_utils.pluginTarget.mixin(CanvasRenderer); + +},{"../../const":44,"../../settings":99,"../../utils":120,"../SystemRenderer":74,"./utils/CanvasMaskManager":76,"./utils/CanvasRenderTarget":77,"./utils/mapCanvasBlendModesToPixi":79}],76:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A set of functions used to handle masking. + * + * @class + * @memberof PIXI + */ +var CanvasMaskManager = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + function CanvasMaskManager(renderer) { + _classCallCheck(this, CanvasMaskManager); + + this.renderer = renderer; + } + + /** + * This method adds it to the current stack of masks. + * + * @param {object} maskData - the maskData that will be pushed + */ + + + CanvasMaskManager.prototype.pushMask = function pushMask(maskData) { + var renderer = this.renderer; + + renderer.context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.transform.worldTransform; + var resolution = renderer.resolution; + + renderer.context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // TODO suport sprite alpha masks?? + // lots of effort required. If demand is great enough.. + if (!maskData._texture) { + this.renderGraphicsShape(maskData); + renderer.context.clip(); + } + + maskData.worldAlpha = cacheAlpha; + }; + + /** + * Renders a PIXI.Graphics shape. + * + * @param {PIXI.Graphics} graphics - The object to render. + */ + + + CanvasMaskManager.prototype.renderGraphicsShape = function renderGraphicsShape(graphics) { + var context = this.renderer.context; + var len = graphics.graphicsData.length; + + if (len === 0) { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === _const.SHAPES.POLY) { + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; j++) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) { + context.closePath(); + } + } else if (data.type === _const.SHAPES.RECT) { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } + }; + + /** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @param {PIXI.CanvasRenderer} renderer - The renderer context to use. + */ + + + CanvasMaskManager.prototype.popMask = function popMask(renderer) { + renderer.context.restore(); + }; + + /** + * Destroys this canvas mask manager. + * + */ + + + CanvasMaskManager.prototype.destroy = function destroy() { + /* empty */ + }; + + return CanvasMaskManager; +}(); + +exports.default = CanvasMaskManager; + +},{"../../../const":44}],77:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Creates a Canvas element of the given size. + * + * @class + * @memberof PIXI + */ +var CanvasRenderTarget = function () { + /** + * @param {number} width - the width for the newly created canvas + * @param {number} height - the height for the newly created canvas + * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + _classCallCheck(this, CanvasRenderTarget); + + /** + * The Canvas object that belongs to this CanvasRenderTarget. + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @member {CanvasRenderingContext2D} + */ + this.context = this.canvas.getContext('2d'); + + this.resolution = resolution || _settings2.default.RESOLUTION; + + this.resize(width, height); + } + + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * + * @private + */ + + + CanvasRenderTarget.prototype.clear = function clear() { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + + /** + * Resizes the canvas to the specified width and height. + * + * @param {number} width - the new width of the canvas + * @param {number} height - the new height of the canvas + */ + + + CanvasRenderTarget.prototype.resize = function resize(width, height) { + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; + }; + + /** + * Destroys this canvas. + * + */ + + + CanvasRenderTarget.prototype.destroy = function destroy() { + this.context = null; + this.canvas = null; + }; + + /** + * The width of the canvas buffer in pixels. + * + * @member {number} + */ + + + _createClass(CanvasRenderTarget, [{ + key: 'width', + get: function get() { + return this.canvas.width; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.width = val; + } + + /** + * The height of the canvas buffer in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.canvas.height; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.height = val; + } + }]); + + return CanvasRenderTarget; +}(); + +exports.default = CanvasRenderTarget; + +},{"../../../settings":99}],78:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = canUseNewCanvasBlendModes; +/** + * Creates a little colored canvas + * + * @ignore + * @param {string} color - The color to make the canvas + * @return {canvas} a small canvas element + */ +function createColoredCanvas(color) { + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.fillStyle = color; + context.fillRect(0, 0, 6, 1); + + return canvas; +} + +/** + * Checks whether the Canvas BlendModes are supported by the current browser + * + * @return {boolean} whether they are supported + */ +function canUseNewCanvasBlendModes() { + if (typeof document === 'undefined') { + return false; + } + + var magenta = createColoredCanvas('#ff00ff'); + var yellow = createColoredCanvas('#ffff00'); + + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.globalCompositeOperation = 'multiply'; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + var imageData = context.getImageData(2, 0, 1, 1); + + if (!imageData) { + return false; + } + + var data = imageData.data; + + return data[0] === 255 && data[1] === 0 && data[2] === 0; +} + +},{}],79:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapCanvasBlendModesToPixi; + +var _const = require('../../../const'); + +var _canUseNewCanvasBlendModes = require('./canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Maps blend combinations to Canvas. + * + * @memberof PIXI + * @function mapCanvasBlendModesToPixi + * @private + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapCanvasBlendModesToPixi() { + var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + + if ((0, _canUseNewCanvasBlendModes2.default)()) { + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'multiply'; + array[_const.BLEND_MODES.SCREEN] = 'screen'; + array[_const.BLEND_MODES.OVERLAY] = 'overlay'; + array[_const.BLEND_MODES.DARKEN] = 'darken'; + array[_const.BLEND_MODES.LIGHTEN] = 'lighten'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'color-dodge'; + array[_const.BLEND_MODES.COLOR_BURN] = 'color-burn'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'hard-light'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'soft-light'; + array[_const.BLEND_MODES.DIFFERENCE] = 'difference'; + array[_const.BLEND_MODES.EXCLUSION] = 'exclusion'; + array[_const.BLEND_MODES.HUE] = 'hue'; + array[_const.BLEND_MODES.SATURATION] = 'saturate'; + array[_const.BLEND_MODES.COLOR] = 'color'; + array[_const.BLEND_MODES.LUMINOSITY] = 'luminosity'; + } else { + // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'source-over'; + array[_const.BLEND_MODES.SCREEN] = 'source-over'; + array[_const.BLEND_MODES.OVERLAY] = 'source-over'; + array[_const.BLEND_MODES.DARKEN] = 'source-over'; + array[_const.BLEND_MODES.LIGHTEN] = 'source-over'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'source-over'; + array[_const.BLEND_MODES.COLOR_BURN] = 'source-over'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.DIFFERENCE] = 'source-over'; + array[_const.BLEND_MODES.EXCLUSION] = 'source-over'; + array[_const.BLEND_MODES.HUE] = 'source-over'; + array[_const.BLEND_MODES.SATURATION] = 'source-over'; + array[_const.BLEND_MODES.COLOR] = 'source-over'; + array[_const.BLEND_MODES.LUMINOSITY] = 'source-over'; + } + + return array; +} + +},{"../../../const":44,"./canUseNewCanvasBlendModes":78}],80:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged + * up with textures that are no longer being used. + * + * @class + * @memberof PIXI + */ +var TextureGarbageCollector = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function TextureGarbageCollector(renderer) { + _classCallCheck(this, TextureGarbageCollector); + + this.renderer = renderer; + + this.count = 0; + this.checkCount = 0; + this.maxIdle = _settings2.default.GC_MAX_IDLE; + this.checkCountMax = _settings2.default.GC_MAX_CHECK_COUNT; + this.mode = _settings2.default.GC_MODE; + } + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.update = function update() { + this.count++; + + if (this.mode === _const.GC_MODES.MANUAL) { + return; + } + + this.checkCount++; + + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + + this.run(); + } + }; + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.run = function run() { + var tm = this.renderer.textureManager; + var managedTextures = tm._managedTextures; + var wasRemoved = false; + + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + + // only supports non generated textures at the moment! + if (!texture._glRenderTargets && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + + if (wasRemoved) { + var j = 0; + + for (var _i = 0; _i < managedTextures.length; _i++) { + if (managedTextures[_i] !== null) { + managedTextures[j++] = managedTextures[_i]; + } + } + + managedTextures.length = j; + } + }; + + /** + * Removes all the textures within the specified displayObject and its children from the GPU + * + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + */ + + + TextureGarbageCollector.prototype.unload = function unload(displayObject) { + var tm = this.renderer.textureManager; + + // only destroy non generated textures + if (displayObject._texture && displayObject._texture._glRenderTargets) { + tm.destroyTexture(displayObject._texture, true); + } + + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + + return TextureGarbageCollector; +}(); + +exports.default = TextureGarbageCollector; + +},{"../../const":44,"../../settings":99}],81:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _const = require('../../const'); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _utils = require('../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a webGL Texture + * + * @class + * @memberof PIXI + */ +var TextureManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function TextureManager(renderer) { + _classCallCheck(this, TextureManager); + + /** + * A reference to the current renderer + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = renderer.gl; + + /** + * Track textures in the renderer so we can no longer listen to them on destruction. + * + * @member {Array<*>} + * @private + */ + this._managedTextures = []; + } + + /** + * Binds a texture. + * + */ + + + TextureManager.prototype.bindTexture = function bindTexture() {} + // empty + + + /** + * Gets a texture. + * + */ + ; + + TextureManager.prototype.getTexture = function getTexture() {} + // empty + + + /** + * Updates and/or Creates a WebGL texture for the renderer's context. + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update + * @param {number} location - the location the texture will be bound to. + * @return {GLTexture} The gl texture. + */ + ; + + TextureManager.prototype.updateTexture = function updateTexture(texture, location) { + // assume it good! + // texture = texture.baseTexture || texture; + + var gl = this.gl; + + var isRenderTexture = !!texture._glRenderTargets; + + if (!texture.hasLoaded) { + return null; + } + + var boundTextures = this.renderer.boundTextures; + + // if the location is undefined then this may have been called by n event. + // this being the case the texture may already be bound to a slot. As a texture can only be bound once + // we need to find its current location if it exists. + if (location === undefined) { + location = 0; + + // TODO maybe we can use texture bound ids later on... + // check if texture is already bound.. + for (var i = 0; i < boundTextures.length; ++i) { + if (boundTextures[i] === texture) { + location = i; + break; + } + } + } + + boundTextures[location] = texture; + + gl.activeTexture(gl.TEXTURE0 + location); + + var glTexture = texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!glTexture) { + if (isRenderTexture) { + var renderTarget = new _RenderTarget2.default(this.gl, texture.width, texture.height, texture.scaleMode, texture.resolution); + + renderTarget.resize(texture.width, texture.height); + texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget; + glTexture = renderTarget.texture; + } else { + glTexture = new _pixiGlCore.GLTexture(this.gl, null, null, null, null); + glTexture.bind(location); + glTexture.premultiplyAlpha = true; + glTexture.upload(texture.source); + } + + texture._glTextures[this.renderer.CONTEXT_UID] = glTexture; + + texture.on('update', this.updateTexture, this); + texture.on('dispose', this.destroyTexture, this); + + this._managedTextures.push(texture); + + if (texture.isPowerOfTwo) { + if (texture.mipmap) { + glTexture.enableMipmap(); + } + + if (texture.wrapMode === _const.WRAP_MODES.CLAMP) { + glTexture.enableWrapClamp(); + } else if (texture.wrapMode === _const.WRAP_MODES.REPEAT) { + glTexture.enableWrapRepeat(); + } else { + glTexture.enableWrapMirrorRepeat(); + } + } else { + glTexture.enableWrapClamp(); + } + + if (texture.scaleMode === _const.SCALE_MODES.NEAREST) { + glTexture.enableNearestScaling(); + } else { + glTexture.enableLinearScaling(); + } + } + // the texture already exists so we only need to update it.. + else if (isRenderTexture) { + texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height); + } else { + glTexture.upload(texture.source); + } + + return glTexture; + }; + + /** + * Deletes the texture from WebGL + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy + * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. + */ + + + TextureManager.prototype.destroyTexture = function destroyTexture(texture, skipRemove) { + texture = texture.baseTexture || texture; + + if (!texture.hasLoaded) { + return; + } + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + this.renderer.unbindTexture(texture); + + texture._glTextures[this.renderer.CONTEXT_UID].destroy(); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + + delete texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!skipRemove) { + var i = this._managedTextures.indexOf(texture); + + if (i !== -1) { + (0, _utils.removeItems)(this._managedTextures, i, 1); + } + } + } + }; + + /** + * Deletes all the textures from WebGL + */ + + + TextureManager.prototype.removeAll = function removeAll() { + // empty all the old gl textures as they are useless now + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + delete texture._glTextures[this.renderer.CONTEXT_UID]; + } + } + }; + + /** + * Destroys this manager and removes all its textures + */ + + + TextureManager.prototype.destroy = function destroy() { + // destroy managed textures + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + this.destroyTexture(texture, true); + + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + } + + this._managedTextures = null; + }; + + return TextureManager; +}(); + +exports.default = TextureManager; + +},{"../../const":44,"../../utils":120,"./utils/RenderTarget":94,"pixi-gl-core":12}],82:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _MaskManager = require('./managers/MaskManager'); + +var _MaskManager2 = _interopRequireDefault(_MaskManager); + +var _StencilManager = require('./managers/StencilManager'); + +var _StencilManager2 = _interopRequireDefault(_StencilManager); + +var _FilterManager = require('./managers/FilterManager'); + +var _FilterManager2 = _interopRequireDefault(_FilterManager); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _ObjectRenderer = require('./utils/ObjectRenderer'); + +var _ObjectRenderer2 = _interopRequireDefault(_ObjectRenderer); + +var _TextureManager = require('./TextureManager'); + +var _TextureManager2 = _interopRequireDefault(_TextureManager); + +var _BaseTexture = require('../../textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _TextureGarbageCollector = require('./TextureGarbageCollector'); + +var _TextureGarbageCollector2 = _interopRequireDefault(_TextureGarbageCollector); + +var _WebGLState = require('./WebGLState'); + +var _WebGLState2 = _interopRequireDefault(_WebGLState); + +var _mapWebGLDrawModesToPixi = require('./utils/mapWebGLDrawModesToPixi'); + +var _mapWebGLDrawModesToPixi2 = _interopRequireDefault(_mapWebGLDrawModesToPixi); + +var _validateContext = require('./utils/validateContext'); + +var _validateContext2 = _interopRequireDefault(_validateContext); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CONTEXT_UID = 0; + +/** + * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ + +var WebGLRenderer = function (_SystemRenderer) { + _inherits(WebGLRenderer, _SystemRenderer); + + /** + * + * @param {number} [screenWidth=800] - the width of the screen + * @param {number} [screenHeight=600] - the height of the screen + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias. If not available natively then FXAA + * antialiasing is used + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. + * The resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear + * the canvas or not before the new render pass. If you wish to set this to false, you *must* set + * preserveDrawingBuffer to `true`. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when + * rendering, stopping pixel interpolation. + * @param {boolean} [options.legacy=false] - If true Pixi will aim to ensure compatibility + * with older / less advanced devices. If you experiance unexplained flickering try setting this to true. + */ + function WebGLRenderer(screenWidth, screenHeight) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + _classCallCheck(this, WebGLRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'WebGL', screenWidth, screenHeight, options)); + + _this.legacy = !!options.legacy; + + if (_this.legacy) { + _pixiGlCore2.default.VertexArrayObject.FORCE_NATIVE = true; + } + + /** + * The type of this renderer as a standardised const + * + * @member {number} + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.WEBGL; + + _this.handleContextLost = _this.handleContextLost.bind(_this); + _this.handleContextRestored = _this.handleContextRestored.bind(_this); + + _this.view.addEventListener('webglcontextlost', _this.handleContextLost, false); + _this.view.addEventListener('webglcontextrestored', _this.handleContextRestored, false); + + /** + * The options passed in to create a new webgl context. + * + * @member {object} + * @private + */ + _this._contextOptions = { + alpha: _this.transparent, + antialias: options.antialias, + premultipliedAlpha: _this.transparent && _this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: options.preserveDrawingBuffer + }; + + _this._backgroundColorRgba[3] = _this.transparent ? 0 : 1; + + /** + * Manages the masks using the stencil buffer. + * + * @member {PIXI.MaskManager} + */ + _this.maskManager = new _MaskManager2.default(_this); + + /** + * Manages the stencil buffer. + * + * @member {PIXI.StencilManager} + */ + _this.stencilManager = new _StencilManager2.default(_this); + + /** + * An empty renderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.emptyRenderer = new _ObjectRenderer2.default(_this); + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.currentRenderer = _this.emptyRenderer; + + _this.initPlugins(); + + /** + * The current WebGL rendering context, it is created here + * + * @member {WebGLRenderingContext} + */ + // initialize the context so it is ready for the managers. + if (options.context) { + // checks to see if a context is valid.. + (0, _validateContext2.default)(options.context); + } + + _this.gl = options.context || _pixiGlCore2.default.createContext(_this.view, _this._contextOptions); + + _this.CONTEXT_UID = CONTEXT_UID++; + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.WebGLState} + */ + _this.state = new _WebGLState2.default(_this.gl); + + _this.renderingToScreen = true; + + /** + * Holds the current state of textures bound to the GPU. + * @type {Array} + */ + _this.boundTextures = null; + + /** + * Holds the current shader + * + * @member {PIXI.Shader} + */ + _this._activeShader = null; + + _this._activeVao = null; + + /** + * Holds the current render target + * + * @member {PIXI.RenderTarget} + */ + _this._activeRenderTarget = null; + + _this._initContext(); + + /** + * Manages the filters. + * + * @member {PIXI.FilterManager} + */ + _this.filterManager = new _FilterManager2.default(_this); + // map some webGL blend and drawmodes.. + _this.drawModes = (0, _mapWebGLDrawModesToPixi2.default)(_this.gl); + + _this._nextTextureLocation = 0; + + _this.setBlendMode(0); + return _this; + } + + /** + * Creates the WebGL context + * + * @private + */ + + + WebGLRenderer.prototype._initContext = function _initContext() { + var gl = this.gl; + + // restore a context if it was previously lost + if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').restoreContext(); + } + + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + + this.boundTextures = new Array(maxTextures); + this.emptyTextures = new Array(maxTextures); + + // create a texture manager... + this.textureManager = new _TextureManager2.default(this); + this.textureGC = new _TextureGarbageCollector2.default(this); + + this.state.resetToDefault(); + + this.rootRenderTarget = new _RenderTarget2.default(gl, this.width, this.height, null, this.resolution, true); + this.rootRenderTarget.clearColor = this._backgroundColorRgba; + + this.bindRenderTarget(this.rootRenderTarget); + + // now lets fill up the textures with empty ones! + var emptyGLTexture = new _pixiGlCore2.default.GLTexture.fromData(gl, null, 1, 1); + + var tempObj = { _glTextures: {} }; + + tempObj._glTextures[this.CONTEXT_UID] = {}; + + for (var i = 0; i < maxTextures; i++) { + var empty = new _BaseTexture2.default(); + + empty._glTextures[this.CONTEXT_UID] = emptyGLTexture; + + this.boundTextures[i] = tempObj; + this.emptyTextures[i] = empty; + this.bindTexture(null, i); + } + + this.emit('context', gl); + + // setup the width/height properties and gl viewport + this.resize(this.screen.width, this.screen.height); + }; + + /** + * Renders the object to its webGL view + * + * @param {PIXI.DisplayObject} displayObject - the object to be rendered + * @param {PIXI.RenderTexture} renderTexture - The render texture to render to. + * @param {boolean} [clear] - Should the canvas be cleared before the new render + * @param {PIXI.Transform} [transform] - A transform to apply to the render texture before rendering. + * @param {boolean} [skipUpdateTransform] - Should we skip the update transform pass? + */ + + + WebGLRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + // no point rendering if our context has been blown up! + if (!this.gl || this.gl.isContextLost()) { + return; + } + + this._nextTextureLocation = 0; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + this.bindRenderTexture(renderTexture, transform); + + this.currentRenderer.start(); + + if (clear !== undefined ? clear : this.clearBeforeRender) { + this._activeRenderTarget.clear(); + } + + displayObject.renderWebGL(this); + + // apply transform.. + this.currentRenderer.flush(); + + // this.setObjectRenderer(this.emptyRenderer); + + this.textureGC.update(); + + this.emit('postrender'); + }; + + /** + * Changes the current renderer to the one given in parameter + * + * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. + */ + + + WebGLRenderer.prototype.setObjectRenderer = function setObjectRenderer(objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; + + /** + * This should be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + * + */ + + + WebGLRenderer.prototype.flush = function flush() { + this.setObjectRenderer(this.emptyRenderer); + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + WebGLRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + // if(width * this.resolution === this.width && height * this.resolution === this.height)return; + + _SystemRenderer3.default.prototype.resize.call(this, screenWidth, screenHeight); + + this.rootRenderTarget.resize(screenWidth, screenHeight); + + if (this._activeRenderTarget === this.rootRenderTarget) { + this.rootRenderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true); + } + } + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} blendMode - the desired blend mode + */ + + + WebGLRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + this.state.setBlendMode(blendMode); + }; + + /** + * Erases the active render target and fills the drawing area with a colour + * + * @param {number} [clearColor] - The colour + */ + + + WebGLRenderer.prototype.clear = function clear(clearColor) { + this._activeRenderTarget.clear(clearColor); + }; + + /** + * Sets the transform of the active render target to the given matrix + * + * @param {PIXI.Matrix} matrix - The transformation matrix + */ + + + WebGLRenderer.prototype.setTransform = function setTransform(matrix) { + this._activeRenderTarget.transform = matrix; + }; + + /** + * Erases the render texture and fills the drawing area with a colour + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to clear + * @param {number} [clearColor] - The colour + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.clearRenderTexture = function clearRenderTexture(renderTexture, clearColor) { + var baseTexture = renderTexture.baseTexture; + var renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + + if (renderTarget) { + renderTarget.clear(clearColor); + } + + return this; + }; + + /** + * Binds a render texture for rendering + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to render + * @param {PIXI.Transform} transform - The transform to be applied to the render texture + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTexture = function bindRenderTexture(renderTexture, transform) { + var renderTarget = void 0; + + if (renderTexture) { + var baseTexture = renderTexture.baseTexture; + + if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) { + // bind the current texture + this.textureManager.updateTexture(baseTexture, 0); + } + + this.unbindTexture(baseTexture); + + renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + renderTarget.setFrame(renderTexture.frame); + } else { + renderTarget = this.rootRenderTarget; + } + + renderTarget.transform = transform; + this.bindRenderTarget(renderTarget); + + return this; + }; + + /** + * Changes the current render target to the one given in parameter + * + * @param {PIXI.RenderTarget} renderTarget - the new render target + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTarget = function bindRenderTarget(renderTarget) { + if (renderTarget !== this._activeRenderTarget) { + this._activeRenderTarget = renderTarget; + renderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true); + } + + this.stencilManager.setMaskStack(renderTarget.stencilMaskStack); + } + + return this; + }; + + /** + * Changes the current shader to the one given in parameter + * + * @param {PIXI.Shader} shader - the new shader + * @param {boolean} [autoProject=true] - Whether automatically set the projection matrix + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindShader = function bindShader(shader, autoProject) { + // TODO cache + if (this._activeShader !== shader) { + this._activeShader = shader; + shader.bind(); + + // `autoProject` normally would be a default parameter set to true + // but because of how Babel transpiles default parameters + // it hinders the performance of this method. + if (autoProject !== false) { + // automatically set the projection matrix + shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(true); + } + } + + return this; + }; + + /** + * Binds the texture. This will return the location of the bound texture. + * It may not be the same as the one you pass in. This is due to optimisation that prevents + * needless binding of textures. For example if the texture is already bound it will return the + * current location of the texture instead of the one provided. To bypass this use force location + * + * @param {PIXI.Texture} texture - the new texture + * @param {number} location - the suggested texture location + * @param {boolean} forceLocation - force the location + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindTexture = function bindTexture(texture, location, forceLocation) { + texture = texture || this.emptyTextures[location]; + texture = texture.baseTexture || texture; + texture.touched = this.textureGC.count; + + if (!forceLocation) { + // TODO - maybe look into adding boundIds.. save us the loop? + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + return i; + } + } + + if (location === undefined) { + this._nextTextureLocation++; + this._nextTextureLocation %= this.boundTextures.length; + location = this.boundTextures.length - this._nextTextureLocation - 1; + } + } else { + location = location || 0; + } + + var gl = this.gl; + var glTexture = texture._glTextures[this.CONTEXT_UID]; + + if (!glTexture) { + // this will also bind the texture.. + this.textureManager.updateTexture(texture, location); + } else { + // bind the current texture + this.boundTextures[location] = texture; + gl.activeTexture(gl.TEXTURE0 + location); + gl.bindTexture(gl.TEXTURE_2D, glTexture.texture); + } + + return location; + }; + + /** + * unbinds the texture ... + * + * @param {PIXI.Texture} texture - the texture to unbind + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.unbindTexture = function unbindTexture(texture) { + var gl = this.gl; + + texture = texture.baseTexture || texture; + + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + this.boundTextures[i] = this.emptyTextures[i]; + + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[i]._glTextures[this.CONTEXT_UID].texture); + } + } + + return this; + }; + + /** + * Creates a new VAO from this renderer's context and state. + * + * @return {VertexArrayObject} The new VAO. + */ + + + WebGLRenderer.prototype.createVao = function createVao() { + return new _pixiGlCore2.default.VertexArrayObject(this.gl, this.state.attribState); + }; + + /** + * Changes the current Vao to the one given in parameter + * + * @param {PIXI.VertexArrayObject} vao - the new Vao + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindVao = function bindVao(vao) { + if (this._activeVao === vao) { + return this; + } + + if (vao) { + vao.bind(); + } else if (this._activeVao) { + // TODO this should always be true i think? + this._activeVao.unbind(); + } + + this._activeVao = vao; + + return this; + }; + + /** + * Resets the WebGL state so you can render things however you fancy! + * + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.reset = function reset() { + this.setObjectRenderer(this.emptyRenderer); + + this._activeShader = null; + this._activeRenderTarget = this.rootRenderTarget; + + // bind the main frame buffer (the screen); + this.rootRenderTarget.activate(); + + this.state.resetToDefault(); + + return this; + }; + + /** + * Handles a lost webgl context + * + * @private + * @param {WebGLContextEvent} event - The context lost event. + */ + + + WebGLRenderer.prototype.handleContextLost = function handleContextLost(event) { + event.preventDefault(); + }; + + /** + * Handles a restored webgl context + * + * @private + */ + + + WebGLRenderer.prototype.handleContextRestored = function handleContextRestored() { + this._initContext(); + this.textureManager.removeAll(); + }; + + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + + + WebGLRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // remove listeners + this.view.removeEventListener('webglcontextlost', this.handleContextLost); + this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); + + this.textureManager.destroy(); + + // call base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.uid = 0; + + // destroy the managers + this.maskManager.destroy(); + this.stencilManager.destroy(); + this.filterManager.destroy(); + + this.maskManager = null; + this.filterManager = null; + this.textureManager = null; + this.currentRenderer = null; + + this.handleContextLost = null; + this.handleContextRestored = null; + + this._contextOptions = null; + this.gl.useProgram(null); + + if (this.gl.getExtension('WEBGL_lose_context')) { + this.gl.getExtension('WEBGL_lose_context').loseContext(); + } + + this.gl = null; + + // this = null; + }; + + return WebGLRenderer; +}(_SystemRenderer3.default); + +exports.default = WebGLRenderer; + + +_utils.pluginTarget.mixin(WebGLRenderer); + +},{"../../const":44,"../../textures/BaseTexture":109,"../../utils":120,"../SystemRenderer":74,"./TextureGarbageCollector":80,"./TextureManager":81,"./WebGLState":83,"./managers/FilterManager":88,"./managers/MaskManager":89,"./managers/StencilManager":90,"./utils/ObjectRenderer":92,"./utils/RenderTarget":94,"./utils/mapWebGLDrawModesToPixi":97,"./utils/validateContext":98,"pixi-gl-core":12}],83:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); + +var _mapWebGLBlendModesToPixi2 = _interopRequireDefault(_mapWebGLBlendModesToPixi); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var BLEND = 0; +var DEPTH_TEST = 1; +var FRONT_FACE = 2; +var CULL_FACE = 3; +var BLEND_FUNC = 4; + +/** + * A WebGL state machines + * + * @memberof PIXI + * @class + */ + +var WebGLState = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + */ + function WebGLState(gl) { + _classCallCheck(this, WebGLState); + + /** + * The current active state + * + * @member {Uint8Array} + */ + this.activeState = new Uint8Array(16); + + /** + * The default state + * + * @member {Uint8Array} + */ + this.defaultState = new Uint8Array(16); + + // default blend mode.. + this.defaultState[0] = 1; + + /** + * The current state index in the stack + * + * @member {number} + * @private + */ + this.stackIndex = 0; + + /** + * The stack holding all the different states + * + * @member {Array<*>} + * @private + */ + this.stack = []; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + this.attribState = { + tempAttribState: new Array(this.maxAttribs), + attribState: new Array(this.maxAttribs) + }; + + this.blendModes = (0, _mapWebGLBlendModesToPixi2.default)(gl); + + // check we have vao.. + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || gl.getExtension('MOZ_OES_vertex_array_object') || gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + /** + * Pushes a new active state + */ + + + WebGLState.prototype.push = function push() { + // next state.. + var state = this.stack[this.stackIndex]; + + if (!state) { + state = this.stack[this.stackIndex] = new Uint8Array(16); + } + + ++this.stackIndex; + + // copy state.. + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) { + state[i] = this.activeState[i]; + } + }; + + /** + * Pops a state out + */ + + + WebGLState.prototype.pop = function pop() { + var state = this.stack[--this.stackIndex]; + + this.setState(state); + }; + + /** + * Sets the current state + * + * @param {*} state - The state to set. + */ + + + WebGLState.prototype.setState = function setState(state) { + this.setBlend(state[BLEND]); + this.setDepthTest(state[DEPTH_TEST]); + this.setFrontFace(state[FRONT_FACE]); + this.setCullFace(state[CULL_FACE]); + this.setBlendMode(state[BLEND_FUNC]); + }; + + /** + * Enables or disabled blending. + * + * @param {boolean} value - Turn on or off webgl blending. + */ + + + WebGLState.prototype.setBlend = function setBlend(value) { + value = value ? 1 : 0; + + if (this.activeState[BLEND] === value) { + return; + } + + this.activeState[BLEND] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + }; + + /** + * Sets the blend mode. + * + * @param {number} value - The blend mode to set to. + */ + + + WebGLState.prototype.setBlendMode = function setBlendMode(value) { + if (value === this.activeState[BLEND_FUNC]) { + return; + } + + this.activeState[BLEND_FUNC] = value; + + this.gl.blendFunc(this.blendModes[value][0], this.blendModes[value][1]); + }; + + /** + * Sets whether to enable or disable depth test. + * + * @param {boolean} value - Turn on or off webgl depth testing. + */ + + + WebGLState.prototype.setDepthTest = function setDepthTest(value) { + value = value ? 1 : 0; + + if (this.activeState[DEPTH_TEST] === value) { + return; + } + + this.activeState[DEPTH_TEST] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + }; + + /** + * Sets whether to enable or disable cull face. + * + * @param {boolean} value - Turn on or off webgl cull face. + */ + + + WebGLState.prototype.setCullFace = function setCullFace(value) { + value = value ? 1 : 0; + + if (this.activeState[CULL_FACE] === value) { + return; + } + + this.activeState[CULL_FACE] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + }; + + /** + * Sets the gl front face. + * + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ + + + WebGLState.prototype.setFrontFace = function setFrontFace(value) { + value = value ? 1 : 0; + + if (this.activeState[FRONT_FACE] === value) { + return; + } + + this.activeState[FRONT_FACE] = value; + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); + }; + + /** + * Disables all the vaos in use + * + */ + + + WebGLState.prototype.resetAttributes = function resetAttributes() { + for (var i = 0; i < this.attribState.tempAttribState.length; i++) { + this.attribState.tempAttribState[i] = 0; + } + + for (var _i = 0; _i < this.attribState.attribState.length; _i++) { + this.attribState.attribState[_i] = 0; + } + + // im going to assume one is always active for performance reasons. + for (var _i2 = 1; _i2 < this.maxAttribs; _i2++) { + this.gl.disableVertexAttribArray(_i2); + } + }; + + // used + /** + * Resets all the logic and disables the vaos + */ + + + WebGLState.prototype.resetToDefault = function resetToDefault() { + // unbind any VAO if they exist.. + if (this.nativeVaoExtension) { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + // reset all attributes.. + this.resetAttributes(); + + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; ++i) { + this.activeState[i] = 32; + } + + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + + this.setState(this.defaultState); + }; + + return WebGLState; +}(); + +exports.default = WebGLState; + +},{"./utils/mapWebGLBlendModesToPixi":96}],84:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _extractUniformsFromSrc = require('./extractUniformsFromSrc'); + +var _extractUniformsFromSrc2 = _interopRequireDefault(_extractUniformsFromSrc); + +var _utils = require('../../../utils'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SOURCE_KEY_MAP = {}; + +// let math = require('../../../math'); +/** + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ + +var Filter = function () { + /** + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. + */ + function Filter(vertexSrc, fragmentSrc, uniforms) { + _classCallCheck(this, Filter); + + /** + * The vertex shader. + * + * @member {string} + */ + this.vertexSrc = vertexSrc || Filter.defaultVertexSrc; + + /** + * The fragment shader. + * + * @member {string} + */ + this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc; + + this.blendMode = _const.BLEND_MODES.NORMAL; + + this.uniformData = uniforms || (0, _extractUniformsFromSrc2.default)(this.vertexSrc, this.fragmentSrc, 'projectionMatrix|uSampler'); + + /** + * An object containing the current values of custom uniforms. + * @example Updating the value of a custom uniform + * filter.uniforms.time = performance.now(); + * + * @member {object} + */ + this.uniforms = {}; + + for (var i in this.uniformData) { + this.uniforms[i] = this.uniformData[i].value; + } + + // this is where we store shader references.. + // TODO we could cache this! + this.glShaders = {}; + + // used for cacheing.. sure there is a better way! + if (!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) { + SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = (0, _utils.uid)(); + } + + this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]; + + /** + * The padding of the filter. Some filters require extra space to breath such as a blur. + * Increasing this will add extra width and height to the bounds of the object that the + * filter is applied to. + * + * @member {number} + */ + this.padding = 4; + + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + * + * @member {number} + */ + this.resolution = _settings2.default.RESOLUTION; + + /** + * If enabled is true the filter is applied, if false it will not. + * + * @member {boolean} + */ + this.enabled = true; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + * @param {object} [currentState] - It's current state of filter. + * There are some useful properties in the currentState : + * target, filters, sourceFrame, destinationFrame, renderTarget, resolution + */ + + + Filter.prototype.apply = function apply(filterManager, input, output, clear, currentState) // eslint-disable-line no-unused-vars + { + // --- // + // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); + + // do as you please! + + filterManager.applyFilter(this, input, output, clear); + + // or just do a regular render.. + }; + + /** + * The default vertex shader source + * + * @static + * @constant + */ + + + _createClass(Filter, null, [{ + key: 'defaultVertexSrc', + get: function get() { + return ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform mat3 projectionMatrix;', 'uniform mat3 filterMatrix;', 'varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;', ' vTextureCoord = aTextureCoord ;', '}'].join('\n'); + } + + /** + * The default fragment shader source + * + * @static + * @constant + */ + + }, { + key: 'defaultFragmentSrc', + get: function get() { + return ['varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'uniform sampler2D uSampler;', 'uniform sampler2D filterSampler;', 'void main(void){', ' vec4 masky = texture2D(filterSampler, vFilterCoord);', ' vec4 sample = texture2D(uSampler, vTextureCoord);', ' vec4 color;', ' if(mod(vFilterCoord.x, 1.0) > 0.5)', ' {', ' color = vec4(1.0, 0.0, 0.0, 1.0);', ' }', ' else', ' {', ' color = vec4(0.0, 1.0, 0.0, 1.0);', ' }', + // ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', + ' gl_FragColor = mix(sample, masky, 0.5);', ' gl_FragColor *= sample.a;', '}'].join('\n'); + } + }]); + + return Filter; +}(); + +exports.default = Filter; + +},{"../../../const":44,"../../../settings":99,"../../../utils":120,"./extractUniformsFromSrc":85}],85:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = extractUniformsFromSrc; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var defaultValue = _pixiGlCore2.default.shader.defaultValue; + +function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) { + var vertUniforms = extractUniformsFromString(vertexSrc, mask); + var fragUniforms = extractUniformsFromString(fragmentSrc, mask); + + return Object.assign(vertUniforms, fragUniforms); +} + +function extractUniformsFromString(string) { + var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea|filterClamp)$'); + + var uniforms = {}; + var nameSplit = void 0; + + // clean the lines a little - remove extra spaces / tabs etc + // then split along ';' + var lines = string.replace(/\s+/g, ' ').split(/\s*;\s*/); + + // loop through.. + for (var i = 0; i < lines.length; i++) { + var line = lines[i].trim(); + + if (line.indexOf('uniform') > -1) { + var splitLine = line.split(' '); + var type = splitLine[1]; + + var name = splitLine[2]; + var size = 1; + + if (name.indexOf('[') > -1) { + // array! + nameSplit = name.split(/\[|]/); + name = nameSplit[0]; + size *= Number(nameSplit[1]); + } + + if (!name.match(maskRegex)) { + uniforms[name] = { + value: defaultValue(type, size), + name: name, + type: type + }; + } + } + } + + return uniforms; +} + +},{"pixi-gl-core":12}],86:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.calculateScreenSpaceMatrix = calculateScreenSpaceMatrix; +exports.calculateNormalizedScreenSpaceMatrix = calculateNormalizedScreenSpaceMatrix; +exports.calculateSpriteMatrix = calculateSpriteMatrix; + +var _math = require('../../../math'); + +/* + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// this returns a matrix that will normalise map filter cords in the filter to screen space +function calculateScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + // let worldTransform = sprite.worldTransform.copy(Matrix.TEMP_MATRIX), + // let texture = {width:1136, height:700};//sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(textureSize.width, textureSize.height); + + return mappedMatrix; +} + +function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + var translateScaleX = textureSize.width / filterArea.width; + var translateScaleY = textureSize.height / filterArea.height; + + mappedMatrix.scale(translateScaleX, translateScaleY); + + return mappedMatrix; +} + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +function calculateSpriteMatrix(outputMatrix, filterArea, textureSize, sprite) { + var worldTransform = sprite.worldTransform.copy(_math.Matrix.TEMP_MATRIX); + var texture = sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + // scale.. + var ratio = textureSize.height / textureSize.width; + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(1, ratio); + + var translateScaleX = textureSize.width / texture.width; + var translateScaleY = textureSize.height / texture.height; + + worldTransform.tx /= texture.width * translateScaleX; + + // this...? free beer for anyone who can explain why this makes sense! + worldTransform.ty /= texture.width * translateScaleX; + // worldTransform.ty /= texture.height * translateScaleY; + + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + + // apply inverse scale.. + mappedMatrix.scale(1, 1 / ratio); + + mappedMatrix.scale(translateScaleX, translateScaleY); + + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; +} + +},{"../../../math":68}],87:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Filter2 = require('../Filter'); + +var _Filter3 = _interopRequireDefault(_Filter2); + +var _math = require('../../../../math'); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The SpriteMaskFilter class + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + */ +var SpriteMaskFilter = function (_Filter) { + _inherits(SpriteMaskFilter, _Filter); + + /** + * @param {PIXI.Sprite} sprite - the target sprite + */ + function SpriteMaskFilter(sprite) { + _classCallCheck(this, SpriteMaskFilter); + + var maskMatrix = new _math.Matrix(); + + var _this = _possibleConstructorReturn(this, _Filter.call(this, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n', 'varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n')); + + sprite.renderable = false; + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + return _this; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + */ + + + SpriteMaskFilter.prototype.apply = function apply(filterManager, input, output) { + var maskSprite = this.maskSprite; + + this.uniforms.mask = maskSprite._texture; + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite); + this.uniforms.alpha = maskSprite.worldAlpha; + + filterManager.applyFilter(this, input, output); + }; + + return SpriteMaskFilter; +}(_Filter3.default); + +exports.default = SpriteMaskFilter; + +},{"../../../../math":68,"../Filter":84,"path":22}],88:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _RenderTarget = require('../utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _Quad = require('../utils/Quad'); + +var _Quad2 = _interopRequireDefault(_Quad); + +var _math = require('../../../math'); + +var _Shader = require('../../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _filterTransforms = require('../filters/filterTransforms'); + +var filterTransforms = _interopRequireWildcard(_filterTransforms); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @ignore + * @class + */ +var FilterState = +/** + * + */ +function FilterState() { + _classCallCheck(this, FilterState); + + this.renderTarget = null; + this.sourceFrame = new _math.Rectangle(); + this.destinationFrame = new _math.Rectangle(); + this.filters = []; + this.target = null; + this.resolution = 1; +}; + +/** + * @class + * @memberof PIXI + * @extends PIXI.WebGLManager + */ + + +var FilterManager = function (_WebGLManager) { + _inherits(FilterManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function FilterManager(renderer) { + _classCallCheck(this, FilterManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.gl = _this.renderer.gl; + // know about sprites! + _this.quad = new _Quad2.default(_this.gl, renderer.state.attribState); + + _this.shaderCache = {}; + // todo add default! + _this.pool = {}; + + _this.filterData = null; + return _this; + } + + /** + * Adds a new filter to the manager. + * + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param {PIXI.Filter[]} filters - The filters to apply. + */ + + + FilterManager.prototype.pushFilter = function pushFilter(target, filters) { + var renderer = this.renderer; + + var filterData = this.filterData; + + if (!filterData) { + filterData = this.renderer._activeRenderTarget.filterStack; + + // add new stack + var filterState = new FilterState(); + + filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; + filterState.renderTarget = renderer._activeRenderTarget; + + this.renderer._activeRenderTarget.filterData = filterData = { + index: 0, + stack: [filterState] + }; + + this.filterData = filterData; + } + + // get the current filter state.. + var currentState = filterData.stack[++filterData.index]; + + if (!currentState) { + currentState = filterData.stack[filterData.index] = new FilterState(); + } + + // for now we go off the filter of the first resolution.. + var resolution = filters[0].resolution; + var padding = filters[0].padding | 0; + var targetBounds = target.filterArea || target.getBounds(true); + var sourceFrame = currentState.sourceFrame; + var destinationFrame = currentState.destinationFrame; + + sourceFrame.x = (targetBounds.x * resolution | 0) / resolution; + sourceFrame.y = (targetBounds.y * resolution | 0) / resolution; + sourceFrame.width = (targetBounds.width * resolution | 0) / resolution; + sourceFrame.height = (targetBounds.height * resolution | 0) / resolution; + + if (filterData.stack[0].renderTarget.transform) {// + + // TODO we should fit the rect around the transform.. + } else { + sourceFrame.fit(filterData.stack[0].destinationFrame); + } + + // lets apply the padding After we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + sourceFrame.pad(padding); + + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + + // lets play the padding after we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + + var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); + + currentState.target = target; + currentState.filters = filters; + currentState.resolution = resolution; + currentState.renderTarget = renderTarget; + + // bind the render target to draw the shape in the top corner.. + + renderTarget.setFrame(destinationFrame, sourceFrame); + + // bind the render target + renderer.bindRenderTarget(renderTarget); + renderTarget.clear(); + }; + + /** + * Pops off the filter and applies it. + * + */ + + + FilterManager.prototype.popFilter = function popFilter() { + var filterData = this.filterData; + + var lastState = filterData.stack[filterData.index - 1]; + var currentState = filterData.stack[filterData.index]; + + this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); + + var filters = currentState.filters; + + if (filters.length === 1) { + filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false, currentState); + this.freePotRenderTarget(currentState.renderTarget); + } else { + var flip = currentState.renderTarget; + var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, currentState.resolution); + + flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + // finally lets clear the render target before drawing to it.. + flop.clear(); + + var i = 0; + + for (i = 0; i < filters.length - 1; ++i) { + filters[i].apply(this, flip, flop, true, currentState); + + var t = flip; + + flip = flop; + flop = t; + } + + filters[i].apply(this, flip, lastState.renderTarget, false, currentState); + + this.freePotRenderTarget(flip); + this.freePotRenderTarget(flop); + } + + filterData.index--; + + if (filterData.index === 0) { + this.filterData = null; + } + }; + + /** + * Draws a filter. + * + * @param {PIXI.Filter} filter - The filter to draw. + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + FilterManager.prototype.applyFilter = function applyFilter(filter, input, output, clear) { + var renderer = this.renderer; + var gl = renderer.gl; + + var shader = filter.glShaders[renderer.CONTEXT_UID]; + + // cacheing.. + if (!shader) { + if (filter.glShaderKey) { + shader = this.shaderCache[filter.glShaderKey]; + + if (!shader) { + shader = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + + filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = shader; + } + } else { + shader = filter.glShaders[renderer.CONTEXT_UID] = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + } + + // TODO - this only needs to be done once? + renderer.bindVao(null); + + this.quad.initVao(shader); + } + + renderer.bindVao(this.quad.vao); + + renderer.bindRenderTarget(output); + + if (clear) { + gl.disable(gl.SCISSOR_TEST); + renderer.clear(); // [1, 1, 1, 1]); + gl.enable(gl.SCISSOR_TEST); + } + + // in case the render target is being masked using a scissor rect + if (output === renderer.maskManager.scissorRenderTarget) { + renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); + } + + renderer.bindShader(shader); + + // free unit 0 for us, doesn't matter what was there + // don't try to restore it, because syncUniforms can upload it to another slot + // and it'll be a problem + var tex = this.renderer.emptyTextures[0]; + + this.renderer.boundTextures[0] = tex; + // this syncs the pixi filters uniforms with glsl uniforms + this.syncUniforms(shader, filter); + + renderer.state.setBlendMode(filter.blendMode); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, input.texture.texture); + + this.quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + }; + + /** + * Uploads the uniforms of the filter. + * + * @param {GLShader} shader - The underlying gl shader. + * @param {PIXI.Filter} filter - The filter we are synchronizing. + */ + + + FilterManager.prototype.syncUniforms = function syncUniforms(shader, filter) { + var uniformData = filter.uniformData; + var uniforms = filter.uniforms; + + // 0 is reserved for the pixi texture so we start at 1! + var textureCount = 1; + var currentState = void 0; + + // filterArea and filterClamp that are handled by FilterManager directly + // they must not appear in uniformData + + if (shader.uniforms.filterArea) { + currentState = this.filterData.stack[this.filterData.index]; + + var filterArea = shader.uniforms.filterArea; + + filterArea[0] = currentState.renderTarget.size.width; + filterArea[1] = currentState.renderTarget.size.height; + filterArea[2] = currentState.sourceFrame.x; + filterArea[3] = currentState.sourceFrame.y; + + shader.uniforms.filterArea = filterArea; + } + + // use this to clamp displaced texture coords so they belong to filterArea + // see displacementFilter fragment shader for an example + if (shader.uniforms.filterClamp) { + currentState = currentState || this.filterData.stack[this.filterData.index]; + + var filterClamp = shader.uniforms.filterClamp; + + filterClamp[0] = 0; + filterClamp[1] = 0; + filterClamp[2] = (currentState.sourceFrame.width - 1) / currentState.renderTarget.size.width; + filterClamp[3] = (currentState.sourceFrame.height - 1) / currentState.renderTarget.size.height; + + shader.uniforms.filterClamp = filterClamp; + } + + // TODO Cacheing layer.. + for (var i in uniformData) { + if (uniformData[i].type === 'sampler2D' && uniforms[i] !== 0) { + if (uniforms[i].baseTexture) { + shader.uniforms[i] = this.renderer.bindTexture(uniforms[i].baseTexture, textureCount); + } else { + shader.uniforms[i] = textureCount; + + // TODO + // this is helpful as renderTargets can also be set. + // Although thinking about it, we could probably + // make the filter texture cache return a RenderTexture + // rather than a renderTarget + var gl = this.renderer.gl; + + this.renderer.boundTextures[textureCount] = this.renderer.emptyTextures[textureCount]; + gl.activeTexture(gl.TEXTURE0 + textureCount); + + uniforms[i].texture.bind(); + } + + textureCount++; + } else if (uniformData[i].type === 'mat3') { + // check if its pixi matrix.. + if (uniforms[i].a !== undefined) { + shader.uniforms[i] = uniforms[i].toArray(true); + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (uniformData[i].type === 'vec2') { + // check if its a point.. + if (uniforms[i].x !== undefined) { + var val = shader.uniforms[i] || new Float32Array(2); + + val[0] = uniforms[i].x; + val[1] = uniforms[i].y; + shader.uniforms[i] = val; + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (uniformData[i].type === 'float') { + if (shader.uniforms.data[i].value !== uniformData[i]) { + shader.uniforms[i] = uniforms[i]; + } + } else { + shader.uniforms[i] = uniforms[i]; + } + } + }; + + /** + * Gets a render target from the pool, or creates a new one. + * + * @param {boolean} clear - Should we clear the render texture when we get it? + * @param {number} resolution - The resolution of the target. + * @return {PIXI.RenderTarget} The new render target + */ + + + FilterManager.prototype.getRenderTarget = function getRenderTarget(clear, resolution) { + var currentState = this.filterData.stack[this.filterData.index]; + var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution); + + renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + return renderTarget; + }; + + /** + * Returns a render target to the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The render target to return. + */ + + + FilterManager.prototype.returnRenderTarget = function returnRenderTarget(renderTarget) { + this.freePotRenderTarget(renderTarget); + }; + + /** + * Calculates the mapped matrix. + * + * TODO playing around here.. this is temporary - (will end up in the shader) + * this returns a matrix that will normalise map filter cords in the filter to screen space + * + * @param {PIXI.Matrix} outputMatrix - the matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateScreenSpaceMatrix = function calculateScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); + }; + + /** + * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function calculateNormalizedScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); + }; + + /** + * This will map the filter coord so that a texture can be used based on the transform of a sprite + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateSpriteMatrix = function calculateSpriteMatrix(outputMatrix, sprite) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); + }; + + /** + * Destroys this Filter Manager. + * + */ + + + FilterManager.prototype.destroy = function destroy() { + this.shaderCache = {}; + this.emptyPool(); + }; + + /** + * Gets a Power-of-Two render texture. + * + * TODO move to a seperate class could be on renderer? + * also - could cause issue with multiple contexts? + * + * @private + * @param {WebGLRenderingContext} gl - The webgl rendering context + * @param {number} minWidth - The minimum width of the render target. + * @param {number} minHeight - The minimum height of the render target. + * @param {number} resolution - The resolution of the render target. + * @return {PIXI.RenderTarget} The new render target. + */ + + + FilterManager.prototype.getPotRenderTarget = function getPotRenderTarget(gl, minWidth, minHeight, resolution) { + // TODO you could return a bigger texture if there is not one in the pool? + minWidth = _bitTwiddle2.default.nextPow2(minWidth * resolution); + minHeight = _bitTwiddle2.default.nextPow2(minHeight * resolution); + + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + if (!this.pool[key]) { + this.pool[key] = []; + } + + var renderTarget = this.pool[key].pop(); + + // creating render target will cause texture to be bound! + if (!renderTarget) { + // temporary bypass cache.. + var tex = this.renderer.boundTextures[0]; + + gl.activeTexture(gl.TEXTURE0); + + // internally - this will cause a texture to be bound.. + renderTarget = new _RenderTarget2.default(gl, minWidth, minHeight, null, 1); + + // set the current one back + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + } + + // manually tweak the resolution... + // this will not modify the size of the frame buffer, just its resolution. + renderTarget.resolution = resolution; + renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution; + renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution; + + return renderTarget; + }; + + /** + * Empties the texture pool. + * + */ + + + FilterManager.prototype.emptyPool = function emptyPool() { + for (var i in this.pool) { + var textures = this.pool[i]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + + this.pool = {}; + }; + + /** + * Frees a render target back into the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free + */ + + + FilterManager.prototype.freePotRenderTarget = function freePotRenderTarget(renderTarget) { + var minWidth = renderTarget.size.width * renderTarget.resolution; + var minHeight = renderTarget.size.height * renderTarget.resolution; + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + this.pool[key].push(renderTarget); + }; + + return FilterManager; +}(_WebGLManager3.default); + +exports.default = FilterManager; + +},{"../../../Shader":42,"../../../math":68,"../filters/filterTransforms":86,"../utils/Quad":93,"../utils/RenderTarget":94,"./WebGLManager":91,"bit-twiddle":1}],89:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _SpriteMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); + +var _SpriteMaskFilter2 = _interopRequireDefault(_SpriteMaskFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var MaskManager = function (_WebGLManager) { + _inherits(MaskManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function MaskManager(renderer) { + _classCallCheck(this, MaskManager); + + // TODO - we don't need both! + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.scissor = false; + _this.scissorData = null; + _this.scissorRenderTarget = null; + + _this.enableScissor = true; + + _this.alphaMaskPool = []; + _this.alphaMaskIndex = 0; + return _this; + } + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushMask = function pushMask(target, maskData) { + // TODO the root check means scissor rect will not + // be used on render textures more info here: + // https://github.com/pixijs/pixi.js/pull/3545 + + if (maskData.texture) { + this.pushSpriteMask(target, maskData); + } else if (this.enableScissor && !this.scissor && this.renderer._activeRenderTarget.root && !this.renderer.stencilManager.stencilMaskStack.length && maskData.isFastRect()) { + var matrix = maskData.worldTransform; + + var rot = Math.atan2(matrix.b, matrix.a); + + // use the nearest degree! + rot = Math.round(rot * (180 / Math.PI)); + + if (rot % 90) { + this.pushStencilMask(maskData); + } else { + this.pushScissorMask(target, maskData); + } + } else { + this.pushStencilMask(maskData); + } + }; + + /** + * Removes the last mask from the mask stack and doesn't return it. + * + * @param {PIXI.DisplayObject} target - Display Object to pop the mask from + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.popMask = function popMask(target, maskData) { + if (maskData.texture) { + this.popSpriteMask(target, maskData); + } else if (this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length) { + this.popScissorMask(target, maskData); + } else { + this.popStencilMask(target, maskData); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.RenderTarget} target - Display Object to push the sprite mask to + * @param {PIXI.Sprite} maskData - Sprite to be used as the mask + */ + + + MaskManager.prototype.pushSpriteMask = function pushSpriteMask(target, maskData) { + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new _SpriteMaskFilter2.default(maskData)]; + } + + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskData; + + // TODO - may cause issues! + target.filterArea = maskData.getBounds(true); + + this.renderer.filterManager.pushFilter(target, alphaMaskFilter); + + this.alphaMaskIndex++; + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popSpriteMask = function popSpriteMask() { + this.renderer.filterManager.popFilter(); + this.alphaMaskIndex--; + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushStencilMask = function pushStencilMask(maskData) { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.pushStencil(maskData); + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popStencilMask = function popStencilMask() { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.popStencil(); + }; + + /** + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushScissorMask = function pushScissorMask(target, maskData) { + maskData.renderable = true; + + var renderTarget = this.renderer._activeRenderTarget; + + var bounds = maskData.getBounds(); + + bounds.fit(renderTarget.size); + maskData.renderable = false; + + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + + var resolution = this.renderer.resolution; + + this.renderer.gl.scissor(bounds.x * resolution, (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution, bounds.width * resolution, bounds.height * resolution); + + this.scissorRenderTarget = renderTarget; + this.scissorData = maskData; + this.scissor = true; + }; + + /** + * + * + */ + + + MaskManager.prototype.popScissorMask = function popScissorMask() { + this.scissorRenderTarget = null; + this.scissorData = null; + this.scissor = false; + + // must be scissor! + var gl = this.renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + }; + + return MaskManager; +}(_WebGLManager3.default); + +exports.default = MaskManager; + +},{"../filters/spriteMask/SpriteMaskFilter":87,"./WebGLManager":91}],90:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var StencilManager = function (_WebGLManager) { + _inherits(StencilManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function StencilManager(renderer) { + _classCallCheck(this, StencilManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.stencilMaskStack = null; + return _this; + } + + /** + * Changes the mask stack that is used by this manager. + * + * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack + */ + + + StencilManager.prototype.setMaskStack = function setMaskStack(stencilMaskStack) { + this.stencilMaskStack = stencilMaskStack; + + var gl = this.renderer.gl; + + if (stencilMaskStack.length === 0) { + gl.disable(gl.STENCIL_TEST); + } else { + gl.enable(gl.STENCIL_TEST); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. @alvin + * + * @param {PIXI.Graphics} graphics - The mask + */ + + + StencilManager.prototype.pushStencil = function pushStencil(graphics) { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + this.renderer._activeRenderTarget.attachStencilBuffer(); + + var gl = this.renderer.gl; + var sms = this.stencilMaskStack; + + if (sms.length === 0) { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.stencilFunc(gl.ALWAYS, 1, 1); + } + + sms.push(graphics); + + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; + + /** + * TODO @alvin + */ + + + StencilManager.prototype.popStencil = function popStencil() { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + var gl = this.renderer.gl; + var sms = this.stencilMaskStack; + + var graphics = sms.pop(); + + if (sms.length === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + } else { + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + } + }; + + /** + * Destroys the mask stack. + * + */ + + + StencilManager.prototype.destroy = function destroy() { + _WebGLManager3.default.prototype.destroy.call(this); + + this.stencilMaskStack.stencilStack = null; + }; + + return StencilManager; +}(_WebGLManager3.default); + +exports.default = StencilManager; + +},{"./WebGLManager":91}],91:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var WebGLManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function WebGLManager(renderer) { + _classCallCheck(this, WebGLManager); + + /** + * The renderer this manager works for. + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + this.renderer.on('context', this.onContextChange, this); + } + + /** + * Generic method called when there is a WebGL context change. + * + */ + + + WebGLManager.prototype.onContextChange = function onContextChange() {} + // do some codes init! + + + /** + * Generic destroy methods to be overridden by the subclass + * + */ + ; + + WebGLManager.prototype.destroy = function destroy() { + this.renderer.off('context', this.onContextChange, this); + + this.renderer = null; + }; + + return WebGLManager; +}(); + +exports.default = WebGLManager; + +},{}],92:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('../managers/WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Base for a common object renderer that can be used as a system renderer plugin. + * + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var ObjectRenderer = function (_WebGLManager) { + _inherits(ObjectRenderer, _WebGLManager); + + function ObjectRenderer() { + _classCallCheck(this, ObjectRenderer); + + return _possibleConstructorReturn(this, _WebGLManager.apply(this, arguments)); + } + + /** + * Starts the renderer and sets the shader + * + */ + ObjectRenderer.prototype.start = function start() {} + // set the shader.. + + + /** + * Stops the renderer + * + */ + ; + + ObjectRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Stub method for rendering content and emptying the current batch. + * + */ + + + ObjectRenderer.prototype.flush = function flush() {} + // flush! + + + /** + * Renders an object + * + * @param {PIXI.DisplayObject} object - The object to render. + */ + ; + + ObjectRenderer.prototype.render = function render(object) // eslint-disable-line no-unused-vars + { + // render the object + }; + + return ObjectRenderer; +}(_WebGLManager3.default); + +exports.default = ObjectRenderer; + +},{"../managers/WebGLManager":91}],93:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a quad + * + * @class + * @memberof PIXI + */ +var Quad = function () { + /** + * @param {WebGLRenderingContext} gl - The gl context for this quad to use. + * @param {object} state - TODO: Description + */ + function Quad(gl, state) { + _classCallCheck(this, Quad); + + /* + * the current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]); + + /** + * The Uvs of the quad + * + * @member {Float32Array} + */ + this.uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + this.interleaved = new Float32Array(8 * 2); + + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + this.indices = (0, _createIndicesForQuads2.default)(1); + + /* + * @member {glCore.GLBuffer} The vertex buffer + */ + this.vertexBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW); + + /* + * @member {glCore.GLBuffer} The index buffer + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + /* + * @member {glCore.VertexArrayObject} The index buffer + */ + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, state); + } + + /** + * Initialises the vaos and uses the shader. + * + * @param {PIXI.Shader} shader - the shader to use + */ + + + Quad.prototype.initVao = function initVao(shader) { + this.vao.clear().addIndex(this.indexBuffer).addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0).addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4); + }; + + /** + * Maps two Rectangle to the quad. + * + * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle + * @param {PIXI.Rectangle} destinationFrame - the second rectangle + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.map = function map(targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + + this.uvs[0] = x; + this.uvs[1] = y; + + this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; + + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; + + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; + + x = destinationFrame.x; + y = destinationFrame.y; + + this.vertices[0] = x; + this.vertices[1] = y; + + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + + return this; + }; + + /** + * Binds the buffer and uploads the data + * + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.upload = function upload() { + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + this.vertexBuffer.upload(this.interleaved); + + return this; + }; + + /** + * Removes this quad from WebGL + */ + + + Quad.prototype.destroy = function destroy() { + var gl = this.gl; + + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.indexBuffer); + }; + + return Quad; +}(); + +exports.default = Quad; + +},{"../../../utils/createIndicesForQuads":118,"pixi-gl-core":12}],94:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../../../math'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _pixiGlCore = require('pixi-gl-core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var RenderTarget = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {number} [width=0] - the horizontal range of the filter + * @param {number} [height=0] - the vertical range of the filter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The current resolution / device pixel ratio + * @param {boolean} [root=false] - Whether this object is the root element or not + */ + function RenderTarget(gl, width, height, scaleMode, resolution, root) { + _classCallCheck(this, RenderTarget); + + // TODO Resolution could go here ( eg low res blurs ) + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // next time to create a frame buffer and texture + + /** + * A frame buffer + * + * @member {PIXI.glCore.GLFramebuffer} + */ + this.frameBuffer = null; + + /** + * The texture + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The background colour of this render target, as an array of [r,g,b,a] values + * + * @member {number[]} + */ + this.clearColor = [0, 0, 0, 0]; + + /** + * The size of the object as a rectangle + * + * @member {PIXI.Rectangle} + */ + this.size = new _math.Rectangle(0, 0, 1, 1); + + /** + * The current resolution / device pixel ratio + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The projection matrix + * + * @member {PIXI.Matrix} + */ + this.projectionMatrix = new _math.Matrix(); + + /** + * The object's transform + * + * @member {PIXI.Matrix} + */ + this.transform = null; + + /** + * The frame. + * + * @member {PIXI.Rectangle} + */ + this.frame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.defaultFrame = new _math.Rectangle(); + this.destinationFrame = null; + this.sourceFrame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.stencilBuffer = null; + + /** + * The data structure for the stencil masks + * + * @member {PIXI.Graphics[]} + */ + this.stencilMaskStack = []; + + /** + * Stores filter data for the render target + * + * @member {object[]} + */ + this.filterData = null; + + /** + * The scale mode. + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Whether this object is the root element or not + * + * @member {boolean} + */ + this.root = root; + + if (!this.root) { + this.frameBuffer = _pixiGlCore.GLFramebuffer.createRGBA(gl, 100, 100); + + if (this.scaleMode === _const.SCALE_MODES.NEAREST) { + this.frameBuffer.texture.enableNearestScaling(); + } else { + this.frameBuffer.texture.enableLinearScaling(); + } + /* + A frame buffer needs a target to render to.. + create a texture and bind it attach it to the framebuffer.. + */ + + // this is used by the base texture + this.texture = this.frameBuffer.texture; + } else { + // make it a null framebuffer.. + this.frameBuffer = new _pixiGlCore.GLFramebuffer(gl, 100, 100); + this.frameBuffer.framebuffer = null; + } + + this.setFrame(); + + this.resize(width, height); + } + + /** + * Clears the filter texture. + * + * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer + */ + + + RenderTarget.prototype.clear = function clear(clearColor) { + var cc = clearColor || this.clearColor; + + this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a); + }; + + /** + * Binds the stencil buffer. + * + */ + + + RenderTarget.prototype.attachStencilBuffer = function attachStencilBuffer() { + // TODO check if stencil is done? + /** + * The stencil buffer is used for masking in pixi + * lets create one and then add attach it to the framebuffer.. + */ + if (!this.root) { + this.frameBuffer.enableStencil(); + } + }; + + /** + * Sets the frame of the render target. + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.setFrame = function setFrame(destinationFrame, sourceFrame) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; + }; + + /** + * Binds the buffers and initialises the viewport. + * + */ + + + RenderTarget.prototype.activate = function activate() { + // TOOD refactor usage of frame.. + var gl = this.gl; + + // make sure the texture is unbound! + this.frameBuffer.bind(); + + this.calculateProjection(this.destinationFrame, this.sourceFrame); + + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + + // TODO add a check as them may be the same! + if (this.destinationFrame !== this.sourceFrame) { + gl.enable(gl.SCISSOR_TEST); + gl.scissor(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + } else { + gl.disable(gl.SCISSOR_TEST); + } + + // TODO - does not need to be updated all the time?? + gl.viewport(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + }; + + /** + * Updates the projection matrix based on a projection frame (which is a rectangle) + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.calculateProjection = function calculateProjection(destinationFrame, sourceFrame) { + var pm = this.projectionMatrix; + + sourceFrame = sourceFrame || destinationFrame; + + pm.identity(); + + // TODO: make dest scale source + if (!this.root) { + pm.a = 1 / destinationFrame.width * 2; + pm.d = 1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = -1 - sourceFrame.y * pm.d; + } else { + pm.a = 1 / destinationFrame.width * 2; + pm.d = -1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = 1 - sourceFrame.y * pm.d; + } + }; + + /** + * Resizes the texture to the specified width and height + * + * @param {number} width - the new width of the texture + * @param {number} height - the new height of the texture + */ + + + RenderTarget.prototype.resize = function resize(width, height) { + width = width | 0; + height = height | 0; + + if (this.size.width === width && this.size.height === height) { + return; + } + + this.size.width = width; + this.size.height = height; + + this.defaultFrame.width = width; + this.defaultFrame.height = height; + + this.frameBuffer.resize(width * this.resolution, height * this.resolution); + + var projectionFrame = this.frame || this.size; + + this.calculateProjection(projectionFrame); + }; + + /** + * Destroys the render target. + * + */ + + + RenderTarget.prototype.destroy = function destroy() { + this.frameBuffer.destroy(); + + this.frameBuffer = null; + this.texture = null; + }; + + return RenderTarget; +}(); + +exports.default = RenderTarget; + +},{"../../../const":44,"../../../math":68,"../../../settings":99,"pixi-gl-core":12}],95:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = checkMaxIfStatmentsInShader; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['precision mediump float;', 'void main(void){', 'float test = 0.1;', '%forloop%', 'gl_FragColor = vec4(0.0);', '}'].join('\n'); + +function checkMaxIfStatmentsInShader(maxIfs, gl) { + var createTempContext = !gl; + + if (maxIfs === 0) { + throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); + } + + if (createTempContext) { + var tinyCanvas = document.createElement('canvas'); + + tinyCanvas.width = 1; + tinyCanvas.height = 1; + + gl = _pixiGlCore2.default.createContext(tinyCanvas); + } + + var shader = gl.createShader(gl.FRAGMENT_SHADER); + + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = maxIfs / 2 | 0; + } else { + // valid! + break; + } + } + + if (createTempContext) { + // get rid of context + if (gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').loseContext(); + } + } + + return maxIfs; +} + +function generateIfTestSrc(maxIfs) { + var src = ''; + + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxIfs - 1) { + src += 'if(test == ' + i + '.0){}'; + } + } + + return src; +} + +},{"pixi-gl-core":12}],96:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLBlendModesToPixi; + +var _const = require('../../../const'); + +/** + * Maps gl blend combinations to WebGL. + * + * @memberof PIXI + * @function mapWebGLBlendModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapWebGLBlendModesToPixi(gl) { + var array = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[_const.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD] = [gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + array[_const.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + return array; +} + +},{"../../../const":44}],97:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLDrawModesToPixi; + +var _const = require('../../../const'); + +/** + * Generic Mask Stack data structure. + * + * @memberof PIXI + * @function mapWebGLDrawModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {object} [object={}] - The object to map into + * @return {object} The mapped draw modes. + */ +function mapWebGLDrawModesToPixi(gl) { + var object = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + object[_const.DRAW_MODES.POINTS] = gl.POINTS; + object[_const.DRAW_MODES.LINES] = gl.LINES; + object[_const.DRAW_MODES.LINE_LOOP] = gl.LINE_LOOP; + object[_const.DRAW_MODES.LINE_STRIP] = gl.LINE_STRIP; + object[_const.DRAW_MODES.TRIANGLES] = gl.TRIANGLES; + object[_const.DRAW_MODES.TRIANGLE_STRIP] = gl.TRIANGLE_STRIP; + object[_const.DRAW_MODES.TRIANGLE_FAN] = gl.TRIANGLE_FAN; + + return object; +} + +},{"../../../const":44}],98:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = validateContext; +function validateContext(gl) { + var attributes = gl.getContextAttributes(); + + // this is going to be fairly simple for now.. but at least we have room to grow! + if (!attributes.stencil) { + /* eslint-disable no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable no-console */ + } +} + +},{}],99:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _maxRecommendedTextures = require('./utils/maxRecommendedTextures'); + +var _maxRecommendedTextures2 = _interopRequireDefault(_maxRecommendedTextures); + +var _canUploadSameBuffer = require('./utils/canUploadSameBuffer'); + +var _canUploadSameBuffer2 = _interopRequireDefault(_canUploadSameBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @namespace PIXI.settings + */ +exports.default = { + + /** + * Target frames per millisecond. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 0.06 + */ + TARGET_FPMS: 0.06, + + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * + * @static + * @memberof PIXI.settings + * @type {boolean} + * @default true + */ + MIPMAP_TEXTURES: true, + + /** + * Default resolution / device pixel ratio of the renderer. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + RESOLUTION: 1, + + /** + * Default filter resolution. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + FILTER_RESOLUTION: 1, + + /** + * The maximum textures that this device supports. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 32 + */ + SPRITE_MAX_TEXTURES: (0, _maxRecommendedTextures2.default)(32), + + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + + /** + * The prefix that denotes a URL is for a retina asset. + * + * @static + * @memberof PIXI.settings + * @type {RegExp} + * @example `@2x` + * @default /@([0-9\.]+)x/ + */ + RETINA_PREFIX: /@([0-9\.]+)x/, + + /** + * The default render options if none are supplied to {@link PIXI.WebGLRenderer} + * or {@link PIXI.CanvasRenderer}. + * + * @static + * @constant + * @memberof PIXI.settings + * @type {object} + * @property {HTMLCanvasElement} view=null + * @property {number} resolution=1 + * @property {boolean} antialias=false + * @property {boolean} forceFXAA=false + * @property {boolean} autoResize=false + * @property {boolean} transparent=false + * @property {number} backgroundColor=0x000000 + * @property {boolean} clearBeforeRender=true + * @property {boolean} preserveDrawingBuffer=false + * @property {boolean} roundPixels=false + */ + RENDER_OPTIONS: { + view: null, + antialias: false, + forceFXAA: false, + autoResize: false, + transparent: false, + backgroundColor: 0x000000, + clearBeforeRender: true, + preserveDrawingBuffer: false, + roundPixels: false + }, + + /** + * Default transform type. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.TRANSFORM_MODE} + * @default PIXI.TRANSFORM_MODE.STATIC + */ + TRANSFORM_MODE: 0, + + /** + * Default Garbage Collection mode. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO + */ + GC_MODE: 0, + + /** + * Default Garbage Collection max idle. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 3600 + */ + GC_MAX_IDLE: 60 * 60, + + /** + * Default Garbage Collection maximum check count. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 600 + */ + GC_MAX_CHECK_COUNT: 60 * 10, + + /** + * Default wrap modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP + */ + WRAP_MODE: 0, + + /** + * The scale modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR + */ + SCALE_MODE: 0, + + /** + * Default specify float precision in vertex shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.HIGH + */ + PRECISION_VERTEX: 'highp', + + /** + * Default specify float precision in fragment shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM + */ + PRECISION_FRAGMENT: 'mediump', + + /** + * Can we upload the same buffer in a single frame? + * + * @static + * @constant + * @memberof PIXI + * @type {boolean} + */ + CAN_UPLOAD_SAME_BUFFER: (0, _canUploadSameBuffer2.default)() + +}; + +},{"./utils/canUploadSameBuffer":117,"./utils/maxRecommendedTextures":121}],100:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new _math.Point(); + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = new PIXI.Sprite.fromImage('assets/image.png'); + * ``` + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Sprite = function (_Container) { + _inherits(Sprite, _Container); + + /** + * @param {PIXI.Texture} texture - The texture for this sprite + */ + function Sprite(texture) { + _classCallCheck(this, Sprite); + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + * @private + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this._anchor = new _math.ObservablePoint(_this._onAnchorUpdate, _this); + + /** + * The texture that the sprite is using + * + * @private + * @member {PIXI.Texture} + */ + _this._texture = null; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = null; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * The shader that will be used to render the sprite. Set to null to remove a current shader. + * + * @member {PIXI.Filter|PIXI.Shader} + */ + _this.shader = null; + + /** + * An internal cached value of the tint. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this.cachedTint = 0xFFFFFF; + + // call texture setter + _this.texture = texture || _Texture2.default.EMPTY; + + /** + * this is used to store the vertex data of the sprite (basically a quad) + * + * @private + * @member {Float32Array} + */ + _this.vertexData = new Float32Array(8); + + /** + * This is used to calculate the bounds of the object IF it is a trimmed sprite + * + * @private + * @member {Float32Array} + */ + _this.vertexTrimmedData = null; + + _this._transformID = -1; + _this._textureID = -1; + + _this._transformTrimmedID = -1; + _this._textureTrimmedID = -1; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * + * @member {string} + * @default 'sprite' + */ + _this.pluginName = 'sprite'; + return _this; + } + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Sprite.prototype._onTextureUpdate = function _onTextureUpdate() { + this._textureID = -1; + this._textureTrimmedID = -1; + + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = (0, _utils.sign)(this.scale.x) * this._width / this.texture.orig.width; + } + + if (this._height) { + this.scale.y = (0, _utils.sign)(this.scale.y) * this._height / this.texture.orig.height; + } + }; + + /** + * Called when the anchor position updates. + * + * @private + */ + + + Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate() { + this._transformID = -1; + this._transformTrimmedID = -1; + }; + + /** + * calculates worldTransform * vertices, store it in vertexData + */ + + + Sprite.prototype.calculateVertices = function calculateVertices() { + if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) { + return; + } + + this._transformID = this.transform._worldID; + this._textureID = this._texture._updateID; + + // set the vertex data + + var texture = this._texture; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var anchor = this._anchor; + + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - anchor._x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - anchor._y * orig.height; + h0 = h1 + trim.height; + } else { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData + * This is used to ensure that the true width and height of a trimmed texture is respected + */ + + + Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices() { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { + return; + } + + this._transformTrimmedID = this.transform._worldID; + this._textureTrimmedID = this._texture._updateID; + + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + var anchor = this._anchor; + + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + + var w1 = -anchor._x * orig.width; + var w0 = w1 + orig.width; + + var h1 = -anchor._y * orig.height; + var h0 = h1 + orig.height; + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use. + */ + + + Sprite.prototype._renderWebGL = function _renderWebGL(renderer) { + this.calculateVertices(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Sprite.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Updates the bounds of the sprite. + * + * @private + */ + + + Sprite.prototype._calculateBounds = function _calculateBounds() { + var trim = this._texture.trim; + var orig = this._texture.orig; + + // First lets check to see if the current texture has a trim.. + if (!trim || trim.width === orig.width && trim.height === orig.height) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + Sprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._texture.orig.width * -this._anchor._x; + this._bounds.minY = this._texture.orig.height * -this._anchor._y; + this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x); + this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._x); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _Container.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Tests if a point is inside this sprite + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Sprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + + if (tempPoint.x > x1 && tempPoint.x < x1 + width) { + y1 = -height * this.anchor.y; + + if (tempPoint.y > y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + Sprite.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + this._anchor = null; + + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + + this._texture.destroy(!!destroyBaseTexture); + } + + this._texture = null; + this.shader = null; + }; + + // some helper functions.. + + /** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Sprite} The newly created sprite + */ + + + Sprite.from = function from(source) { + return new Sprite(_Texture2.default.from(source)); + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId + */ + + + Sprite.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return new Sprite(texture); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id + */ + + + Sprite.fromImage = function fromImage(imageId, crossorigin, scaleMode) { + return new Sprite(_Texture2.default.fromImage(imageId, crossorigin, scaleMode)); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Sprite, [{ + key: 'width', + get: function get() { + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._anchor.copy(value); + } + + /** + * The tint applied to the sprite. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + } + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + */ + + }, { + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + this.cachedTint = 0xFFFFFF; + + this._textureID = -1; + this._textureTrimmedID = -1; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + }]); + + return Sprite; +}(_Container3.default); + +exports.default = Sprite; + +},{"../const":44,"../display/Container":46,"../math":68,"../textures/Texture":112,"../utils":120}],101:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +var _math = require('../../math'); + +var _CanvasTinter = require('./CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var canvasRenderWorldTransform = new _math.Matrix(); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasSpriteRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + */ + +var CanvasSpriteRenderer = function () { + /** + * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for. + */ + function CanvasSpriteRenderer(renderer) { + _classCallCheck(this, CanvasSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + CanvasSpriteRenderer.prototype.render = function render(sprite) { + var texture = sprite._texture; + var renderer = this.renderer; + + var width = texture._frame.width; + var height = texture._frame.height; + + var wt = sprite.transform.worldTransform; + var dx = 0; + var dy = 0; + + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) { + return; + } + + renderer.setBlendMode(sprite.blendMode); + + // Ignore null sources + if (texture.valid) { + renderer.context.globalAlpha = sprite.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture + var smoothingEnabled = texture.baseTexture.scaleMode === _const.SCALE_MODES.LINEAR; + + if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) { + renderer.context[renderer.smoothProperty] = smoothingEnabled; + } + + if (texture.trim) { + dx = texture.trim.width / 2 + texture.trim.x - sprite.anchor.x * texture.orig.width; + dy = texture.trim.height / 2 + texture.trim.y - sprite.anchor.y * texture.orig.height; + } else { + dx = (0.5 - sprite.anchor.x) * texture.orig.width; + dy = (0.5 - sprite.anchor.y) * texture.orig.height; + } + + if (texture.rotate) { + wt.copy(canvasRenderWorldTransform); + wt = canvasRenderWorldTransform; + _math.GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); + // the anchor has already been applied above, so lets set it to zero + dx = 0; + dy = 0; + } + + dx -= width / 2; + dy -= height / 2; + + // Allow for pixel rounding + if (renderer.roundPixels) { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution | 0, wt.ty * renderer.resolution | 0); + + dx = dx | 0; + dy = dy | 0; + } else { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution, wt.ty * renderer.resolution); + } + + var resolution = texture.baseTexture.resolution; + + if (sprite.tint !== 0xFFFFFF) { + if (sprite.cachedTint !== sprite.tint) { + sprite.cachedTint = sprite.tint; + + // TODO clean up caching - how to clean up the caches? + sprite.tintedTexture = _CanvasTinter2.default.getTintedTexture(sprite, sprite.tint); + } + + renderer.context.drawImage(sprite.tintedTexture, 0, 0, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } else { + renderer.context.drawImage(texture.baseTexture.source, texture._frame.x * resolution, texture._frame.y * resolution, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } + } + }; + + /** + * destroy the sprite object. + * + */ + + + CanvasSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasSpriteRenderer; +}(); + +exports.default = CanvasSpriteRenderer; + + +_CanvasRenderer2.default.registerPlugin('sprite', CanvasSpriteRenderer); + +},{"../../const":44,"../../math":68,"../../renderers/canvas/CanvasRenderer":75,"./CanvasTinter":102}],102:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class + * @memberof PIXI + */ +var CanvasTinter = { + /** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Sprite} sprite - the sprite to tint + * @param {number} color - the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ + getTintedTexture: function getTintedTexture(sprite, color) { + var texture = sprite.texture; + + color = CanvasTinter.roundColor(color); + + var stringColor = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + texture.tintCache = texture.tintCache || {}; + + if (texture.tintCache[stringColor]) { + return texture.tintCache[stringColor]; + } + + // clone texture.. + var canvas = CanvasTinter.canvas || document.createElement('canvas'); + + // CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); + CanvasTinter.tintMethod(texture, color, canvas); + + if (CanvasTinter.convertTintToImage) { + // is this better? + var tintImage = new Image(); + + tintImage.src = canvas.toDataURL(); + + texture.tintCache[stringColor] = tintImage; + } else { + texture.tintCache[stringColor] = canvas; + // if we are not converting the texture to an image then we need to lose the reference to the canvas + CanvasTinter.canvas = null; + } + + return canvas; + }, + + /** + * Tint a texture using the 'multiply' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithMultiply: function tintWithMultiply(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + }, + + /** + * Tint a texture using the 'overlay' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithOverlay: function tintWithOverlay(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.globalCompositeOperation = 'copy'; + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + // context.globalCompositeOperation = 'copy'; + }, + + + /** + * Tint a texture pixel per pixel. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithPerPixel: function tintWithPerPixel(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.globalCompositeOperation = 'copy'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + var rgbValues = (0, _utils.hex2rgb)(color); + var r = rgbValues[0]; + var g = rgbValues[1]; + var b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, crop.width, crop.height); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + } + + context.putImageData(pixelData, 0, 0); + }, + + /** + * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel. + * + * @memberof PIXI.CanvasTinter + * @param {number} color - the color to round, should be a hex color + * @return {number} The rounded color. + */ + roundColor: function roundColor(color) { + var step = CanvasTinter.cacheStepsPerColorChannel; + + var rgbValues = (0, _utils.hex2rgb)(color); + + rgbValues[0] = Math.min(255, rgbValues[0] / step * step); + rgbValues[1] = Math.min(255, rgbValues[1] / step * step); + rgbValues[2] = Math.min(255, rgbValues[2] / step * step); + + return (0, _utils.rgb2hex)(rgbValues); + }, + + /** + * Number of steps which will be used as a cap when rounding colors. + * + * @memberof PIXI.CanvasTinter + * @type {number} + */ + cacheStepsPerColorChannel: 8, + + /** + * Tint cache boolean flag. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + convertTintToImage: false, + + /** + * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + canUseMultiply: (0, _canUseNewCanvasBlendModes2.default)(), + + /** + * The tinting method that will be used. + * + * @memberof PIXI.CanvasTinter + * @type {tintMethodFunctionType} + */ + tintMethod: 0 +}; + +CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply : CanvasTinter.tintWithPerPixel; + +/** + * The tintMethod type. + * + * @memberof PIXI.CanvasTinter + * @callback tintMethodFunctionType + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + +exports.default = CanvasTinter; + +},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":78,"../../utils":120}],103:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Buffer = function () { + /** + * @param {number} size - The size of the buffer in bytes. + */ + function Buffer(size) { + _classCallCheck(this, Buffer); + + this.vertices = new ArrayBuffer(size); + + /** + * View on the vertices as a Float32Array for positions + * + * @member {Float32Array} + */ + this.float32View = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array for uvs + * + * @member {Float32Array} + */ + this.uint32View = new Uint32Array(this.vertices); + } + + /** + * Destroys the buffer. + * + */ + + + Buffer.prototype.destroy = function destroy() { + this.vertices = null; + this.positions = null; + this.uvs = null; + this.colors = null; + }; + + return Buffer; +}(); + +exports.default = Buffer; + +},{}],104:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _createIndicesForQuads = require('../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +var _generateMultiTextureShader = require('./generateMultiTextureShader'); + +var _generateMultiTextureShader2 = _interopRequireDefault(_generateMultiTextureShader); + +var _checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'); + +var _checkMaxIfStatmentsInShader2 = _interopRequireDefault(_checkMaxIfStatmentsInShader); + +var _BatchBuffer = require('./BatchBuffer'); + +var _BatchBuffer2 = _interopRequireDefault(_BatchBuffer); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var TICK = 0; +var TEXTURE_TICK = 0; + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var SpriteRenderer = function (_ObjectRenderer) { + _inherits(SpriteRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function SpriteRenderer(renderer) { + _classCallCheck(this, SpriteRenderer); + + /** + * Number of values sent in the vertex buffer. + * aVertexPosition(2), aTextureCoord(1), aColor(1), aTextureId(1) = 5 + * + * @member {number} + */ + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.vertSize = 5; + + /** + * The size of the vertex information in bytes. + * + * @member {number} + */ + _this.vertByteSize = _this.vertSize * 4; + + /** + * The number of images in the SpriteRenderer before it flushes. + * + * @member {number} + */ + _this.size = _settings2.default.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + + // the total number of bytes in our batch + // let numVerts = this.size * 4 * this.vertByteSize; + + _this.buffers = []; + for (var i = 1; i <= _bitTwiddle2.default.nextPow2(_this.size); i *= 2) { + _this.buffers.push(new _BatchBuffer2.default(i * 4 * _this.vertByteSize)); + } + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + _this.indices = (0, _createIndicesForQuads2.default)(_this.size); + + /** + * The default shaders that is used if a sprite doesn't have a more specific one. + * there is a shader for each number of textures that can be rendererd. + * These shaders will also be generated on the fly as required. + * @member {PIXI.Shader[]} + */ + _this.shader = null; + + _this.currentIndex = 0; + _this.groups = []; + + for (var k = 0; k < _this.size; k++) { + _this.groups[k] = { textures: [], textureCount: 0, ids: [], size: 0, start: 0, blend: 0 }; + } + + _this.sprites = []; + + _this.vertexBuffers = []; + _this.vaos = []; + + _this.vaoMax = 2; + _this.vertexCount = 0; + + _this.renderer.on('prerender', _this.onPrerender, _this); + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + SpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + if (this.renderer.legacy) { + this.MAX_TEXTURES = 1; + } else { + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), _settings2.default.SPRITE_MAX_TEXTURES); + + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = (0, _checkMaxIfStatmentsInShader2.default)(this.MAX_TEXTURES, gl); + } + + var shader = this.shader = (0, _generateMultiTextureShader2.default)(gl, this.MAX_TEXTURES); + + // create a couple of buffers + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + // we use the second shader as the first one depending on your browser may omit aTextureId + // as it is not used by the shader so is optimized out. + + this.renderer.bindVao(null); + + for (var i = 0; i < this.vaoMax; i++) { + this.vertexBuffers[i] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + + /* eslint-disable max-len */ + + // build the vao object that will render.. + this.vaos[i] = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(this.vertexBuffers[i], shader.attributes.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(this.vertexBuffers[i], shader.attributes.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(this.vertexBuffers[i], shader.attributes.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (shader.attributes.aTextureId) { + this.vaos[i].addAttribute(this.vertexBuffers[i], shader.attributes.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + /* eslint-enable max-len */ + } + + this.vao = this.vaos[0]; + this.currentBlendMode = 99999; + + this.boundTextures = new Array(this.MAX_TEXTURES); + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + SpriteRenderer.prototype.onPrerender = function onPrerender() { + this.vertexCount = 0; + }; + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + SpriteRenderer.prototype.render = function render(sprite) { + // TODO set blend modes.. + // check texture.. + if (this.currentIndex >= this.size) { + this.flush(); + } + + // get the uvs for the texture + + // if the uvs have not updated then no point rendering just yet! + if (!sprite._texture._uvs) { + return; + } + + // push a texture. + // increment the batchsize + this.sprites[this.currentIndex++] = sprite; + }; + + /** + * Renders the content and empties the current batch. + * + */ + + + SpriteRenderer.prototype.flush = function flush() { + if (this.currentIndex === 0) { + return; + } + + var gl = this.renderer.gl; + var MAX_TEXTURES = this.MAX_TEXTURES; + + var np2 = _bitTwiddle2.default.nextPow2(this.currentIndex); + var log2 = _bitTwiddle2.default.log2(np2); + var buffer = this.buffers[log2]; + + var sprites = this.sprites; + var groups = this.groups; + + var float32View = buffer.float32View; + var uint32View = buffer.uint32View; + + var boundTextures = this.boundTextures; + var rendererBoundTextures = this.renderer.boundTextures; + var touch = this.renderer.textureGC.count; + + var index = 0; + var nextTexture = void 0; + var currentTexture = void 0; + var groupCount = 1; + var textureCount = 0; + var currentGroup = groups[0]; + var vertexData = void 0; + var uvs = void 0; + var blendMode = sprites[0].blendMode; + + currentGroup.textureCount = 0; + currentGroup.start = 0; + currentGroup.blend = blendMode; + + TICK++; + + var i = void 0; + + // copy textures.. + for (i = 0; i < MAX_TEXTURES; ++i) { + boundTextures[i] = rendererBoundTextures[i]; + boundTextures[i]._virtalBoundId = i; + } + + for (i = 0; i < this.currentIndex; ++i) { + // upload the sprite elemetns... + // they have all ready been calculated so we just need to push them into the buffer. + var sprite = sprites[i]; + + nextTexture = sprite._texture.baseTexture; + + if (blendMode !== sprite.blendMode) { + // finish a group.. + blendMode = sprite.blendMode; + + // force the batch to break! + currentTexture = null; + textureCount = MAX_TEXTURES; + TICK++; + } + + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + + if (nextTexture._enabled !== TICK) { + if (textureCount === MAX_TEXTURES) { + TICK++; + + currentGroup.size = i - currentGroup.start; + + textureCount = 0; + + currentGroup = groups[groupCount++]; + currentGroup.blend = blendMode; + currentGroup.textureCount = 0; + currentGroup.start = i; + } + + nextTexture.touched = touch; + + if (nextTexture._virtalBoundId === -1) { + for (var j = 0; j < MAX_TEXTURES; ++j) { + var tIndex = (j + TEXTURE_TICK) % MAX_TEXTURES; + + var t = boundTextures[tIndex]; + + if (t._enabled !== TICK) { + TEXTURE_TICK++; + + t._virtalBoundId = -1; + + nextTexture._virtalBoundId = tIndex; + + boundTextures[tIndex] = nextTexture; + break; + } + } + } + + nextTexture._enabled = TICK; + + currentGroup.textureCount++; + currentGroup.ids[textureCount] = nextTexture._virtalBoundId; + currentGroup.textures[textureCount++] = nextTexture; + } + } + + vertexData = sprite.vertexData; + + // TODO this sum does not need to be set each frame.. + uvs = sprite._texture._uvs.uvsUint32; + + if (this.renderer.roundPixels) { + var resolution = this.renderer.resolution; + + // xy + float32View[index] = (vertexData[0] * resolution | 0) / resolution; + float32View[index + 1] = (vertexData[1] * resolution | 0) / resolution; + + // xy + float32View[index + 5] = (vertexData[2] * resolution | 0) / resolution; + float32View[index + 6] = (vertexData[3] * resolution | 0) / resolution; + + // xy + float32View[index + 10] = (vertexData[4] * resolution | 0) / resolution; + float32View[index + 11] = (vertexData[5] * resolution | 0) / resolution; + + // xy + float32View[index + 15] = (vertexData[6] * resolution | 0) / resolution; + float32View[index + 16] = (vertexData[7] * resolution | 0) / resolution; + } else { + // xy + float32View[index] = vertexData[0]; + float32View[index + 1] = vertexData[1]; + + // xy + float32View[index + 5] = vertexData[2]; + float32View[index + 6] = vertexData[3]; + + // xy + float32View[index + 10] = vertexData[4]; + float32View[index + 11] = vertexData[5]; + + // xy + float32View[index + 15] = vertexData[6]; + float32View[index + 16] = vertexData[7]; + } + + uint32View[index + 2] = uvs[0]; + uint32View[index + 7] = uvs[1]; + uint32View[index + 12] = uvs[2]; + uint32View[index + 17] = uvs[3]; + + /* eslint-disable max-len */ + uint32View[index + 3] = uint32View[index + 8] = uint32View[index + 13] = uint32View[index + 18] = sprite._tintRGB + (Math.min(sprite.worldAlpha, 1) * 255 << 24); + + float32View[index + 4] = float32View[index + 9] = float32View[index + 14] = float32View[index + 19] = nextTexture._virtalBoundId; + /* eslint-enable max-len */ + + index += 20; + } + + currentGroup.size = i - currentGroup.start; + + if (!_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // this is still needed for IOS performance.. + // it really does not like uploading to the same buffer in a single frame! + if (this.vaoMax <= this.vertexCount) { + this.vaoMax++; + this.vertexBuffers[this.vertexCount] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + + /* eslint-disable max-len */ + + // build the vao object that will render.. + this.vaos[this.vertexCount] = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(this.vertexBuffers[this.vertexCount], this.shader.attributes.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(this.vertexBuffers[this.vertexCount], this.shader.attributes.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(this.vertexBuffers[this.vertexCount], this.shader.attributes.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (this.shader.attributes.aTextureId) { + this.vaos[this.vertexCount].addAttribute(this.vertexBuffers[this.vertexCount], this.shader.attributes.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + /* eslint-enable max-len */ + } + + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, false); + + this.vertexCount++; + } else { + // lets use the faster option, always use buffer number 0 + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, true); + } + + for (i = 0; i < MAX_TEXTURES; ++i) { + rendererBoundTextures[i]._virtalBoundId = -1; + } + + // render the groups.. + for (i = 0; i < groupCount; ++i) { + var group = groups[i]; + var groupTextureCount = group.textureCount; + + for (var _j = 0; _j < groupTextureCount; _j++) { + currentTexture = group.textures[_j]; + + // reset virtual ids.. + // lets do a quick check.. + if (rendererBoundTextures[group.ids[_j]] !== currentTexture) { + this.renderer.bindTexture(currentTexture, group.ids[_j], true); + } + + // reset the virtualId.. + currentTexture._virtalBoundId = -1; + } + + // set the blend mode.. + this.renderer.state.setBlendMode(group.blend); + + gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); + } + + // reset elements for the next flush + this.currentIndex = 0; + }; + + /** + * Starts a new sprite batch. + */ + + + SpriteRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + + if (_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // bind buffer #0, we don't need others + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].bind(); + } + }; + + /** + * Stops and flushes the current batch. + * + */ + + + SpriteRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Destroys the SpriteRenderer. + * + */ + + + SpriteRenderer.prototype.destroy = function destroy() { + for (var i = 0; i < this.vaoMax; i++) { + if (this.vertexBuffers[i]) { + this.vertexBuffers[i].destroy(); + } + if (this.vaos[i]) { + this.vaos[i].destroy(); + } + } + + if (this.indexBuffer) { + this.indexBuffer.destroy(); + } + + this.renderer.off('prerender', this.onPrerender, this); + + _ObjectRenderer.prototype.destroy.call(this); + + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } + + this.vertexBuffers = null; + this.vaos = null; + this.indexBuffer = null; + this.indices = null; + + this.sprites = null; + + for (var _i = 0; _i < this.buffers.length; ++_i) { + this.buffers[_i].destroy(); + } + }; + + return SpriteRenderer; +}(_ObjectRenderer3.default); + +exports.default = SpriteRenderer; + + +_WebGLRenderer2.default.registerPlugin('sprite', SpriteRenderer); + +},{"../../renderers/webgl/WebGLRenderer":82,"../../renderers/webgl/utils/ObjectRenderer":92,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":95,"../../settings":99,"../../utils/createIndicesForQuads":118,"./BatchBuffer":103,"./generateMultiTextureShader":105,"bit-twiddle":1,"pixi-gl-core":12}],105:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateMultiTextureShader; + +var _Shader = require('../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'varying float vTextureId;', 'uniform sampler2D uSamplers[%count%];', 'void main(void){', 'vec4 color;', 'float textureId = floor(vTextureId+0.5);', '%forloop%', 'gl_FragColor = color * vColor;', '}'].join('\n'); + +function generateMultiTextureShader(gl, maxTextures) { + var vertexSrc = 'precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = vec4(aColor.rgb * aColor.a, aColor.a);\n}\n'; + var fragmentSrc = fragTemplate; + + fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); + + var shader = new _Shader2.default(gl, vertexSrc, fragmentSrc); + + var sampleValues = []; + + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + + shader.bind(); + shader.uniforms.uSamplers = sampleValues; + + return shader; +} + +function generateSampleSrc(maxTextures) { + var src = ''; + + src += '\n'; + src += '\n'; + + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxTextures - 1) { + src += 'if(textureId == ' + i + '.0)'; + } + + src += '\n{'; + src += '\n\tcolor = texture2D(uSamplers[' + i + '], vTextureCoord);'; + src += '\n}'; + } + + src += '\n'; + src += '\n'; + + return src; +} + +},{"../../Shader":42,"path":22}],106:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Sprite2 = require('../sprites/Sprite'); + +var _Sprite3 = _interopRequireDefault(_Sprite2); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TextStyle = require('./TextStyle'); + +var _TextStyle2 = _interopRequireDefault(_TextStyle); + +var _trimCanvas = require('../utils/trimCanvas'); + +var _trimCanvas2 = _interopRequireDefault(_trimCanvas); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint max-depth: [2, 8] */ + + +var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true +}; + +/** + * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string, + * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object. + * + * A Text can be created directly from a string and a style object + * + * ```js + * let text = new PIXI.Text('This is a pixi text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI + */ + +var Text = function (_Sprite) { + _inherits(Text, _Sprite); + + /** + * @param {string} text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + * @param {HTMLCanvasElement} [canvas] - The canvas element for drawing text + */ + function Text(text, style, canvas) { + _classCallCheck(this, Text); + + canvas = canvas || document.createElement('canvas'); + + canvas.width = 3; + canvas.height = 3; + + var texture = _Texture2.default.fromCanvas(canvas); + + texture.orig = new _math.Rectangle(); + texture.trim = new _math.Rectangle(); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + var _this = _possibleConstructorReturn(this, _Sprite.call(this, texture)); + + _this.canvas = canvas; + + /** + * The canvas 2d context that everything is drawn with + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.canvas.getContext('2d'); + + /** + * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. + * @member {number} + * @default 1 + */ + _this.resolution = _settings2.default.RESOLUTION; + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = null; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._style = null; + /** + * Private listener to track style changes. + * + * @member {Function} + * @private + */ + _this._styleListener = null; + + /** + * Private tracker for the current font. + * + * @member {string} + * @private + */ + _this._font = ''; + + _this.text = text; + _this.style = style; + + _this.localStyleID = -1; + return _this; + } + + /** + * Renders text and updates it when needed. + * + * @private + * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. + */ + + + Text.prototype.updateText = function updateText(respectDirty) { + var style = this._style; + + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + + if (!this.dirty && respectDirty) { + return; + } + + this._font = Text.getFontStyle(style); + + this.context.font = this._font; + + // word wrap + // preserve original text + var outputText = style.wordWrap ? this.wordWrap(this._text) : this._text; + + // split text into lines + var lines = outputText.split(/(?:\r\n|\r|\n)/); + + // calculate text width + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + var fontProperties = Text.calculateFontProperties(this._font); + + for (var i = 0; i < lines.length; i++) { + var lineWidth = this.context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing; + + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + + var width = maxLineWidth + style.strokeThickness; + + if (style.dropShadow) { + width += style.dropShadowDistance; + } + + this.canvas.width = Math.ceil((width + style.padding * 2) * this.resolution); + + // calculate text height + var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * lineHeight; + + if (style.dropShadow) { + height += style.dropShadowDistance; + } + + this.canvas.height = Math.ceil((height + style.padding * 2) * this.resolution); + + this.context.scale(this.resolution, this.resolution); + + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + + this.context.font = this._font; + this.context.strokeStyle = style.stroke; + this.context.lineWidth = style.strokeThickness; + this.context.textBaseline = style.textBaseline; + this.context.lineJoin = style.lineJoin; + this.context.miterLimit = style.miterLimit; + + var linePositionX = void 0; + var linePositionY = void 0; + + if (style.dropShadow) { + this.context.shadowBlur = style.dropShadowBlur; + this.context.globalAlpha = style.dropShadowAlpha; + + if (style.dropShadowBlur > 0) { + this.context.shadowColor = style.dropShadowColor; + } else { + this.context.fillStyle = style.dropShadowColor; + } + + var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + + for (var _i = 0; _i < lines.length; _i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i]) / 2; + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); + + if (style.stroke && style.strokeThickness) { + this.context.strokeStyle = style.dropShadowColor; + this.drawLetterSpacing(lines[_i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding, true); + this.context.strokeStyle = style.stroke; + } + } + } + } + + // reset the shadow blur and alpha that was set by the drop shadow, for the regular text + this.context.shadowBlur = 0; + this.context.globalAlpha = 1; + + // set canvas text styles + this.context.fillStyle = this._generateFillStyle(style, lines); + + // draw lines line by line + for (var _i2 = 0; _i2 < lines.length; _i2++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i2 * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i2]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i2]) / 2; + } + + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[_i2], linePositionX + style.padding, linePositionY + style.padding, true); + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i2], linePositionX + style.padding, linePositionY + style.padding); + } + } + + this.updateTexture(); + }; + + /** + * Render the text with letter-spacing. + * @param {string} text - The text to draw + * @param {number} x - Horizontal position to draw the text + * @param {number} y - Vertical position to draw the text + * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + * @private + */ + + + Text.prototype.drawLetterSpacing = function drawLetterSpacing(text, x, y) { + var isStroke = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var style = this._style; + + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + + if (letterSpacing === 0) { + if (isStroke) { + this.context.strokeText(text, x, y); + } else { + this.context.fillText(text, x, y); + } + + return; + } + + var characters = String.prototype.split.call(text, ''); + var currentPosition = x; + var index = 0; + var current = ''; + + while (index < text.length) { + current = characters[index++]; + if (isStroke) { + this.context.strokeText(current, currentPosition, y); + } else { + this.context.fillText(current, currentPosition, y); + } + currentPosition += this.context.measureText(current).width + letterSpacing; + } + }; + + /** + * Updates texture size based on canvas size + * + * @private + */ + + + Text.prototype.updateTexture = function updateTexture() { + if (this._style.trim) { + var trimmed = (0, _trimCanvas2.default)(this.canvas); + + this.canvas.width = trimmed.width; + this.canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } + + var texture = this._texture; + var style = this._style; + + texture.baseTexture.hasLoaded = true; + texture.baseTexture.resolution = this.resolution; + + texture.baseTexture.realWidth = this.canvas.width; + texture.baseTexture.realHeight = this.canvas.height; + texture.baseTexture.width = this.canvas.width / this.resolution; + texture.baseTexture.height = this.canvas.height / this.resolution; + texture.trim.width = texture._frame.width = this.canvas.width / this.resolution; + texture.trim.height = texture._frame.height = this.canvas.height / this.resolution; + + texture.trim.x = -style.padding; + texture.trim.y = -style.padding; + + texture.orig.width = texture._frame.width - style.padding * 2; + texture.orig.height = texture._frame.height - style.padding * 2; + + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + + texture.baseTexture.emit('update', texture.baseTexture); + + this.dirty = false; + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Text.prototype.renderWebGL = function renderWebGL(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype.renderWebGL.call(this, renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Text.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype._renderCanvas.call(this, renderer); + }; + + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @private + * @param {string} text - String to apply word wrapping to + * @return {string} New string with new lines applied where required + */ + + + Text.prototype.wordWrap = function wordWrap(text) { + // Greedy wrapping algorithm that will wrap words as the line grows longer + // than its horizontal bounds. + var result = ''; + var style = this._style; + var lines = text.split('\n'); + var wordWrapWidth = style.wordWrapWidth; + + for (var i = 0; i < lines.length; i++) { + var spaceLeft = wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) { + var wordWidth = this.context.measureText(words[j]).width; + + if (style.breakWords && wordWidth > wordWrapWidth) { + // Word should be split in the middle + var characters = words[j].split(''); + + for (var c = 0; c < characters.length; c++) { + var characterWidth = this.context.measureText(characters[c]).width; + + if (characterWidth > spaceLeft) { + result += '\n' + characters[c]; + spaceLeft = wordWrapWidth - characterWidth; + } else { + if (c === 0) { + result += ' '; + } + + result += characters[c]; + spaceLeft -= characterWidth; + } + } + } else { + var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; + + if (j === 0 || wordWidthWithSpace > spaceLeft) { + // Skip printing the newline if it's the first word of the line that is + // greater than the word wrap width. + if (j > 0) { + result += '\n'; + } + result += words[j]; + spaceLeft = wordWrapWidth - wordWidth; + } else { + spaceLeft -= wordWidthWithSpace; + result += ' ' + words[j]; + } + } + } + + if (i < lines.length - 1) { + result += '\n'; + } + } + + return result; + }; + + /** + * Gets the local bounds of the text object. + * + * @param {Rectangle} rect - The output rectangle. + * @return {Rectangle} The bounds. + */ + + + Text.prototype.getLocalBounds = function getLocalBounds(rect) { + this.updateText(true); + + return _Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + */ + + + Text.prototype._calculateBounds = function _calculateBounds() { + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; + + /** + * Method to be called upon a TextStyle change. + * @private + */ + + + Text.prototype._onStyleChange = function _onStyleChange() { + this.dirty = true; + }; + + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * + * @private + * @param {object} style - The style. + * @param {string[]} lines - The lines of text. + * @return {string|number|CanvasGradient} The fill style + */ + + + Text.prototype._generateFillStyle = function _generateFillStyle(style, lines) { + if (!Array.isArray(style.fill)) { + return style.fill; + } + + // cocoon on canvas+ cannot generate textures, so use the first colour instead + if (navigator.isCocoonJS) { + return style.fill[0]; + } + + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient = void 0; + var totalIterations = void 0; + var currentIteration = void 0; + var stop = void 0; + + var width = this.canvas.width / this.resolution; + var height = this.canvas.height / this.resolution; + + // make a copy of the style settings, so we can manipulate them later + var fill = style.fill.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(style.fill[0]); + fillGradientStops.unshift(0); + + fill.push(style.fill[style.fill.length - 1]); + fillGradientStops.push(1); + + if (style.fillGradientType === _const.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); + + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + totalIterations = (fill.length + 1) * lines.length; + currentIteration = 0; + for (var _i3 = 0; _i3 < lines.length; _i3++) { + currentIteration += 1; + for (var j = 0; j < fill.length; j++) { + if (fillGradientStops[j]) { + stop = fillGradientStops[j] / lines.length + _i3 / lines.length; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[j]); + currentIteration++; + } + } + } else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); + + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + totalIterations = fill.length + 1; + currentIteration = 1; + + for (var _i4 = 0; _i4 < fill.length; _i4++) { + if (fillGradientStops[_i4]) { + stop = fillGradientStops[_i4]; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[_i4]); + currentIteration++; + } + } + + return gradient; + }; + + /** + * Destroys this text object. + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majority of the time the texture will not be shared with any other Sprites. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well + */ + + + Text.prototype.destroy = function destroy(options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + + options = Object.assign({}, defaultDestroyOptions, options); + + _Sprite.prototype.destroy.call(this, options); + + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + + this._style = null; + }; + + /** + * The width of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + /** + * Generates a font style string to use for Text.calculateFontProperties(). Takes the same parameter + * as Text.style. + * + * @static + * @param {object|TextStyle} style - String representing the style of the font + * @return {string} Font style string, for passing to Text.calculateFontProperties() + */ + Text.getFontStyle = function getFontStyle(style) { + style = style || {}; + + if (!(style instanceof _TextStyle2.default)) { + style = new _TextStyle2.default(style); + } + + // build canvas api font setting from individual components. Convert a numeric style.fontSize to px + var fontSizeString = typeof style.fontSize === 'number' ? style.fontSize + 'px' : style.fontSize; + + // Clean-up fontFamily property by quoting each font name + // this will support font names with spaces + var fontFamilies = style.fontFamily; + + if (!Array.isArray(style.fontFamily)) { + fontFamilies = style.fontFamily.split(','); + } + + for (var i = fontFamilies.length - 1; i >= 0; i--) { + // Trim any extra white-space + var fontFamily = fontFamilies[i].trim(); + + // Check if font already contains strings + if (!/([\"\'])[^\'\"]+\1/.test(fontFamily)) { + fontFamily = '"' + fontFamily + '"'; + } + fontFamilies[i] = fontFamily; + } + + return style.fontStyle + ' ' + style.fontVariant + ' ' + style.fontWeight + ' ' + fontSizeString + ' ' + fontFamilies.join(','); + }; + + /** + * Calculates the ascent, descent and fontSize of a given fontStyle + * + * @static + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ + + + Text.calculateFontProperties = function calculateFontProperties(fontStyle) { + // as this method is used for preparing assets, don't recalculate things if we don't need to + if (Text.fontPropertiesCache[fontStyle]) { + return Text.fontPropertiesCache[fontStyle]; + } + + var properties = {}; + + var canvas = Text.fontPropertiesCanvas; + var context = Text.fontPropertiesContext; + + context.font = fontStyle; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('M').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = fontStyle; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i = 0; + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } else { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var _j = 0; _j < line; _j += 4) { + if (imagedata[idx + _j] !== 255) { + stop = true; + break; + } + } + + if (!stop) { + idx -= line; + } else { + break; + } + } + + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + + Text.fontPropertiesCache[fontStyle] = properties; + + return properties; + }; + + _createClass(Text, [{ + key: 'width', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * Set the style of the text. Set up an event listener to listen for changes on the style + * object and mark the text as dirty. + * + * @member {object|PIXI.TextStyle} + */ + + }, { + key: 'style', + get: function get() { + return this._style; + }, + set: function set(style) // eslint-disable-line require-jsdoc + { + style = style || {}; + + if (style instanceof _TextStyle2.default) { + this._style = style; + } else { + this._style = new _TextStyle2.default(style); + } + + this.localStyleID = -1; + this.dirty = true; + } + + /** + * Set the copy for the text object. To split a line you can use '\n'. + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(text) // eslint-disable-line require-jsdoc + { + text = String(text === '' || text === null || text === undefined ? ' ' : text); + + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + } + }]); + + return Text; +}(_Sprite3.default); + +exports.default = Text; + + +Text.fontPropertiesCache = {}; +Text.fontPropertiesCanvas = document.createElement('canvas'); +Text.fontPropertiesContext = Text.fontPropertiesCanvas.getContext('2d'); + +},{"../const":44,"../math":68,"../settings":99,"../sprites/Sprite":100,"../textures/Texture":112,"../utils":120,"../utils/trimCanvas":124,"./TextStyle":107}],107:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // disabling eslint for now, going to rewrite this in v5 +/* eslint-disable */ + +var _const = require('../const'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: '#000000', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: _const.TEXT_GRADIENT.LINEAR_VERTICAL, + fillGradientStops: [], + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + trim: false, + wordWrap: false, + wordWrapWidth: 100 +}; + +/** + * A TextStyle Object decorates a Text Object. It can be shared between + * multiple Text objects. Changing the style will update all text objects using it. + * + * @class + * @memberof PIXI + */ + +var TextStyle = function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string} [style.dropShadowColor='#000000'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours + * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} + * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set + * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * @param {string|string[]} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', 800' or '900') + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Default is 'miter' (creates a sharp corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {boolean} [style.trim=false] - Trim transparent borders + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + _classCallCheck(this, TextStyle); + + this.styleID = 0; + + Object.assign(this, defaultStyle, style); + } + + /** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return {PIXI.TextStyle} New cloned TextStyle object + */ + + + TextStyle.prototype.clone = function clone() { + var clonedProperties = {}; + + for (var key in defaultStyle) { + clonedProperties[key] = this[key]; + } + + return new TextStyle(clonedProperties); + }; + + /** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ + + + TextStyle.prototype.reset = function reset() { + Object.assign(this, defaultStyle); + }; + + _createClass(TextStyle, [{ + key: 'align', + get: function get() { + return this._align; + }, + set: function set(align) { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + } + }, { + key: 'breakWords', + get: function get() { + return this._breakWords; + }, + set: function set(breakWords) { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + } + }, { + key: 'dropShadow', + get: function get() { + return this._dropShadow; + }, + set: function set(dropShadow) { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + } + }, { + key: 'dropShadowAlpha', + get: function get() { + return this._dropShadowAlpha; + }, + set: function set(dropShadowAlpha) { + if (this._dropShadowAlpha !== dropShadowAlpha) { + this._dropShadowAlpha = dropShadowAlpha; + this.styleID++; + } + } + }, { + key: 'dropShadowAngle', + get: function get() { + return this._dropShadowAngle; + }, + set: function set(dropShadowAngle) { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + } + }, { + key: 'dropShadowBlur', + get: function get() { + return this._dropShadowBlur; + }, + set: function set(dropShadowBlur) { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + } + }, { + key: 'dropShadowColor', + get: function get() { + return this._dropShadowColor; + }, + set: function set(dropShadowColor) { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + } + }, { + key: 'dropShadowDistance', + get: function get() { + return this._dropShadowDistance; + }, + set: function set(dropShadowDistance) { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + } + }, { + key: 'fill', + get: function get() { + return this._fill; + }, + set: function set(fill) { + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + } + }, { + key: 'fillGradientType', + get: function get() { + return this._fillGradientType; + }, + set: function set(fillGradientType) { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + } + }, { + key: 'fillGradientStops', + get: function get() { + return this._fillGradientStops; + }, + set: function set(fillGradientStops) { + if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { + this._fillGradientStops = fillGradientStops; + this.styleID++; + } + } + }, { + key: 'fontFamily', + get: function get() { + return this._fontFamily; + }, + set: function set(fontFamily) { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + } + }, { + key: 'fontSize', + get: function get() { + return this._fontSize; + }, + set: function set(fontSize) { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + } + }, { + key: 'fontStyle', + get: function get() { + return this._fontStyle; + }, + set: function set(fontStyle) { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + } + }, { + key: 'fontVariant', + get: function get() { + return this._fontVariant; + }, + set: function set(fontVariant) { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + } + }, { + key: 'fontWeight', + get: function get() { + return this._fontWeight; + }, + set: function set(fontWeight) { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + } + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(letterSpacing) { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + } + }, { + key: 'lineHeight', + get: function get() { + return this._lineHeight; + }, + set: function set(lineHeight) { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + } + }, { + key: 'lineJoin', + get: function get() { + return this._lineJoin; + }, + set: function set(lineJoin) { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + } + }, { + key: 'miterLimit', + get: function get() { + return this._miterLimit; + }, + set: function set(miterLimit) { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + } + }, { + key: 'padding', + get: function get() { + return this._padding; + }, + set: function set(padding) { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + } + }, { + key: 'stroke', + get: function get() { + return this._stroke; + }, + set: function set(stroke) { + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + } + }, { + key: 'strokeThickness', + get: function get() { + return this._strokeThickness; + }, + set: function set(strokeThickness) { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + } + }, { + key: 'textBaseline', + get: function get() { + return this._textBaseline; + }, + set: function set(textBaseline) { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + } + }, { + key: 'trim', + get: function get() { + return this._trim; + }, + set: function set(trim) { + if (this._trim !== trim) { + this._trim = trim; + this.styleID++; + } + } + }, { + key: 'wordWrap', + get: function get() { + return this._wordWrap; + }, + set: function set(wordWrap) { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + } + }, { + key: 'wordWrapWidth', + get: function get() { + return this._wordWrapWidth; + }, + set: function set(wordWrapWidth) { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + } + }]); + + return TextStyle; +}(); + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * + * @param {number|number[]} color + * @return {string} The color as a string. + */ + + +exports.default = TextStyle; +function getSingleColor(color) { + if (typeof color === 'number') { + return (0, _utils.hex2string)(color); + } else if (typeof color === 'string') { + if (color.indexOf('0x') === 0) { + color = color.replace('0x', '#'); + } + } + + return color; +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * + * @param {number|number[]} color + * @return {string} The color as a string. + */ +function getColor(color) { + if (!Array.isArray(color)) { + return getSingleColor(color); + } else { + for (var i = 0; i < color.length; ++i) { + color[i] = getSingleColor(color[i]); + } + + return color; + } +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * + * @param {Array} array1 First array to compare + * @param {Array} array2 Second array to compare + * @return {boolean} Do the arrays contain the same values in the same order + */ +function areArraysEqual(array1, array2) { + if (!Array.isArray(array1) || !Array.isArray(array2)) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } + + return true; +} + +},{"../const":44,"../utils":120}],108:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let baseRenderTexture = new PIXI.BaseRenderTexture(renderer, 800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * baseRenderTexture.render(sprite); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let baseRenderTexture = new PIXI.BaseRenderTexture(100, 100); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var BaseRenderTexture = function (_BaseTexture) { + _inherits(BaseRenderTexture, _BaseTexture); + + /** + * @param {number} [width=100] - The width of the base render texture + * @param {number} [height=100] - The height of the base render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + */ + function BaseRenderTexture() { + var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + + _classCallCheck(this, BaseRenderTexture); + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, null, scaleMode)); + + _this.resolution = resolution || _settings2.default.RESOLUTION; + + _this.width = width; + _this.height = height; + + _this.realWidth = _this.width * _this.resolution; + _this.realHeight = _this.height * _this.resolution; + + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + _this.hasLoaded = true; + + /** + * A map of renderer IDs to webgl renderTargets + * + * @private + * @member {object} + */ + _this._glRenderTargets = {}; + + /** + * A reference to the canvas render target (we only need one as this can be shared across renderers) + * + * @private + * @member {object} + */ + _this._canvasRenderTarget = null; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + return _this; + } + + /** + * Resizes the BaseRenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + */ + + + BaseRenderTexture.prototype.resize = function resize(width, height) { + if (width === this.width && height === this.height) { + return; + } + + this.valid = width > 0 && height > 0; + + this.width = width; + this.height = height; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + if (!this.valid) { + return; + } + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + */ + + + BaseRenderTexture.prototype.destroy = function destroy() { + _BaseTexture.prototype.destroy.call(this, true); + this.renderer = null; + }; + + return BaseRenderTexture; +}(_BaseTexture3.default); + +exports.default = BaseRenderTexture; + +},{"../settings":99,"./BaseTexture":109}],109:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var BaseTexture = function (_EventEmitter) { + _inherits(BaseTexture, _EventEmitter); + + /** + * @param {HTMLImageElement|HTMLCanvasElement} [source] - the source object of the texture. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture + */ + function BaseTexture(source, scaleMode, resolution) { + _classCallCheck(this, BaseTexture); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.uid = (0, _utils.uid)(); + + _this.touched = 0; + + /** + * The resolution / device pixel ratio of the texture + * + * @member {number} + * @default 1 + */ + _this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The width of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.width = 100; + + /** + * The height of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.height = 100; + + // TODO docs + // used to store the actual dimensions of the source + /** + * Used to store the actual width of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realWidth = 100; + /** + * Used to store the actual height of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realHeight = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Set to true once the base texture has successfully loaded. + * + * This is never true if the underlying source fails to load or has no texture data. + * + * @readonly + * @member {boolean} + */ + _this.hasLoaded = false; + + /** + * Set to true if the source is currently loading. + * + * If an Image source is loading the 'loaded' or 'error' event will be + * dispatched when the operation ends. An underyling source that is + * immediately-available bypasses loading entirely. + * + * @readonly + * @member {boolean} + */ + _this.isLoading = false; + + /** + * The image source that is used to create the texture. + * + * TODO: Make this a setter that calls loadSource(); + * + * @readonly + * @member {HTMLImageElement|HTMLCanvasElement} + */ + _this.source = null; // set in loadSource, if at all + + /** + * The image source that is used to create the texture. This is used to + * store the original Svg source when it is replaced with a canvas element. + * + * TODO: Currently not in use but could be used when re-scaling svg. + * + * @readonly + * @member {Image} + */ + _this.origSource = null; // set in loadSvg, if at all + + /** + * Type of image defined in source, eg. `png` or `svg` + * + * @readonly + * @member {string} + */ + _this.imageType = null; // set in updateImageType + + /** + * Scale for source image. Used with Svg images to scale them before rasterization. + * + * @readonly + * @member {number} + */ + _this.sourceScale = 1.0; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * All blend modes, and shaders written for default value. Change it on your own risk. + * + * @member {boolean} + * @default true + */ + _this.premultipliedAlpha = true; + + /** + * The image url of the texture + * + * @member {string} + */ + _this.imageUrl = null; + + /** + * Whether or not the texture is a power of two, try to use power of two textures as much + * as you can + * + * @private + * @member {boolean} + */ + _this.isPowerOfTwo = false; + + // used for webGL + + /** + * + * Set this to true if a mipmap of this texture needs to be generated. This value needs + * to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @member {boolean} + * @see PIXI.MIPMAP_TEXTURES + */ + _this.mipmap = _settings2.default.MIPMAP_TEXTURES; + + /** + * + * WebGL Texture wrap mode + * + * @member {number} + * @see PIXI.WRAP_MODES + */ + _this.wrapMode = _settings2.default.WRAP_MODE; + + /** + * A map of renderer IDs to webgl textures + * + * @private + * @member {object} + */ + _this._glTextures = {}; + + _this._enabled = 0; + _this._virtalBoundId = -1; + + // if no source passed don't try to load + if (source) { + _this.loadSource(source); + } + + /** + * Fired when a not-immediately-available source finishes loading. + * + * @protected + * @event loaded + * @memberof PIXI.BaseTexture# + */ + + /** + * Fired when a not-immediately-available source fails to load. + * + * @protected + * @event error + * @memberof PIXI.BaseTexture# + */ + return _this; + } + + /** + * Updates the texture on all the webgl renderers, this also assumes the src has changed. + * + * @fires update + */ + + + BaseTexture.prototype.update = function update() { + // Svg size is handled during load + if (this.imageType !== 'svg') { + this.realWidth = this.source.naturalWidth || this.source.videoWidth || this.source.width; + this.realHeight = this.source.naturalHeight || this.source.videoHeight || this.source.height; + + this._updateDimensions(); + } + + this.emit('update', this); + }; + + /** + * Update dimensions from real values + */ + + + BaseTexture.prototype._updateDimensions = function _updateDimensions() { + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + this.isPowerOfTwo = _bitTwiddle2.default.isPow2(this.realWidth) && _bitTwiddle2.default.isPow2(this.realHeight); + }; + + /** + * Load a source. + * + * If the source is not-immediately-available, such as an image that needs to be + * downloaded, then the 'loaded' or 'error' event will be dispatched in the future + * and `hasLoaded` will remain false after this call. + * + * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: + * + * if (texture.hasLoaded) { + * // texture ready for use + * } else if (texture.isLoading) { + * // listen to 'loaded' and/or 'error' events on texture + * } else { + * // not loading, not going to load UNLESS the source is reloaded + * // (it may still make sense to listen to the events) + * } + * + * @protected + * @param {HTMLImageElement|HTMLCanvasElement} source - the source object of the texture. + */ + + + BaseTexture.prototype.loadSource = function loadSource(source) { + var _this2 = this; + + var wasLoading = this.isLoading; + + this.hasLoaded = false; + this.isLoading = false; + + if (wasLoading && this.source) { + this.source.onload = null; + this.source.onerror = null; + } + + var firstSourceLoaded = !this.source; + + this.source = source; + + // Apply source if loaded. Otherwise setup appropriate loading monitors. + if ((source.src && source.complete || source.getContext) && source.width && source.height) { + this._updateImageType(); + + if (this.imageType === 'svg') { + this._loadSvgSource(); + } else { + this._sourceLoaded(); + } + + if (firstSourceLoaded) { + // send loaded event if previous source was null and we have been passed a pre-loaded IMG element + this.emit('loaded', this); + } + } else if (!source.getContext) { + var _ret = function () { + // Image fail / not ready + _this2.isLoading = true; + + var scope = _this2; + + source.onload = function () { + scope._updateImageType(); + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope._sourceLoaded(); + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + scope.emit('loaded', scope); + }; + + source.onerror = function () { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope.emit('error', scope); + }; + + // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element + // "The value of `complete` can thus change while a script is executing." + // So complete needs to be re-checked after the callbacks have been added.. + // NOTE: complete will be true if the image has no src so best to check if the src is set. + if (source.complete && source.src) { + // ..and if we're complete now, no need for callbacks + source.onload = null; + source.onerror = null; + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return { + v: void 0 + }; + } + + _this2.isLoading = false; + + if (source.width && source.height) { + _this2._sourceLoaded(); + + // If any previous subscribers possible + if (wasLoading) { + _this2.emit('loaded', _this2); + } + } + // If any previous subscribers possible + else if (wasLoading) { + _this2.emit('error', _this2); + } + } + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + }; + + /** + * Updates type of the source image. + */ + + + BaseTexture.prototype._updateImageType = function _updateImageType() { + if (!this.imageUrl) { + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + var imageType = void 0; + + if (dataUri && dataUri.mediaType === 'image') { + // Check for subType validity + var firstSubType = dataUri.subType.split('+')[0]; + + imageType = (0, _utils.getUrlFileExtension)('.' + firstSubType); + + if (!imageType) { + throw new Error('Invalid image type in data URI.'); + } + } else { + imageType = (0, _utils.getUrlFileExtension)(this.imageUrl); + + if (!imageType) { + imageType = 'png'; + } + } + + this.imageType = imageType; + }; + + /** + * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls + * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. + */ + + + BaseTexture.prototype._loadSvgSource = function _loadSvgSource() { + if (this.imageType !== 'svg') { + // Do nothing if source is not svg + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + + if (dataUri) { + this._loadSvgSourceUsingDataUri(dataUri); + } else { + // We got an URL, so we need to do an XHR to check the svg size + this._loadSvgSourceUsingXhr(); + } + }; + + /** + * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`. + * + * @param {string} dataUri - The data uri to load from. + */ + + + BaseTexture.prototype._loadSvgSourceUsingDataUri = function _loadSvgSourceUsingDataUri(dataUri) { + var svgString = void 0; + + if (dataUri.encoding === 'base64') { + if (!atob) { + throw new Error('Your browser doesn\'t support base64 conversions.'); + } + svgString = atob(dataUri.data); + } else { + svgString = dataUri.data; + } + + this._loadSvgSourceUsingString(svgString); + }; + + /** + * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. + */ + + + BaseTexture.prototype._loadSvgSourceUsingXhr = function _loadSvgSourceUsingXhr() { + var _this3 = this; + + var svgXhr = new XMLHttpRequest(); + + // This throws error on IE, so SVG Document can't be used + // svgXhr.responseType = 'document'; + + // This is not needed since we load the svg as string (breaks IE too) + // but overrideMimeType() can be used to force the response to be parsed as XML + // svgXhr.overrideMimeType('image/svg+xml'); + + svgXhr.onload = function () { + if (svgXhr.readyState !== svgXhr.DONE || svgXhr.status !== 200) { + throw new Error('Failed to load SVG using XHR.'); + } + + _this3._loadSvgSourceUsingString(svgXhr.response); + }; + + svgXhr.onerror = function () { + return _this3.emit('error', _this3); + }; + + svgXhr.open('GET', this.imageUrl, true); + svgXhr.send(); + }; + + /** + * Loads texture using an SVG string. The original SVG Image is stored as `origSource` and the + * created canvas is the new `source`. The SVG is scaled using `sourceScale`. Called by + * `_loadSvgSourceUsingXhr` or `_loadSvgSourceUsingDataUri`. + * + * @param {string} svgString SVG source as string + * + * @fires loaded + */ + + + BaseTexture.prototype._loadSvgSourceUsingString = function _loadSvgSourceUsingString(svgString) { + var svgSize = (0, _utils.getSvgSize)(svgString); + + var svgWidth = svgSize.width; + var svgHeight = svgSize.height; + + if (!svgWidth || !svgHeight) { + throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); + } + + // Scale realWidth and realHeight + this.realWidth = Math.round(svgWidth * this.sourceScale); + this.realHeight = Math.round(svgHeight * this.sourceScale); + + this._updateDimensions(); + + // Create a canvas element + var canvas = document.createElement('canvas'); + + canvas.width = this.realWidth; + canvas.height = this.realHeight; + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + + // Draw the Svg to the canvas + canvas.getContext('2d').drawImage(this.source, 0, 0, svgWidth, svgHeight, 0, 0, this.realWidth, this.realHeight); + + // Replace the original source image with the canvas + this.origSource = this.source; + this.source = canvas; + + // Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`) + _utils.BaseTextureCache[canvas._pixiId] = this; + + this.isLoading = false; + this._sourceLoaded(); + this.emit('loaded', this); + }; + + /** + * Used internally to update the width, height, and some other tracking vars once + * a source has successfully loaded. + * + * @private + */ + + + BaseTexture.prototype._sourceLoaded = function _sourceLoaded() { + this.hasLoaded = true; + this.update(); + }; + + /** + * Destroys this base texture + * + */ + + + BaseTexture.prototype.destroy = function destroy() { + if (this.imageUrl) { + delete _utils.BaseTextureCache[this.imageUrl]; + delete _utils.TextureCache[this.imageUrl]; + + this.imageUrl = null; + + if (!navigator.isCocoonJS) { + this.source.src = ''; + } + } + // An svg source has both `imageUrl` and `__pixiId`, so no `else if` here + if (this.source && this.source._pixiId) { + delete _utils.BaseTextureCache[this.source._pixiId]; + } + + this.source = null; + + this.dispose(); + }; + + /** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + */ + + + BaseTexture.prototype.dispose = function dispose() { + this.emit('dispose', this); + }; + + /** + * Changes the source image of the texture. + * The original source must be an Image element. + * + * @param {string} newSrc - the path of the image + */ + + + BaseTexture.prototype.updateSourceImage = function updateSourceImage(newSrc) { + this.source.src = newSrc; + + this.loadSource(this.source); + }; + + /** + * Helper function that creates a base texture from the given image url. + * If the image is not in the base texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + // new Image() breaks tex loading in some versions of Chrome. + // See https://code.google.com/p/chromium/issues/detail?id=238071 + var image = new Image(); // document.createElement('img'); + + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + image.crossOrigin = (0, _determineCrossOrigin2.default)(imageUrl); + } + + baseTexture = new BaseTexture(image, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + image.src = imageUrl; // Setting this triggers load + + _utils.BaseTextureCache[imageUrl] = baseTexture; + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode) { + if (!canvas._pixiId) { + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[canvas._pixiId]; + + if (!baseTexture) { + baseTexture = new BaseTexture(canvas, scaleMode); + _utils.BaseTextureCache[canvas._pixiId] = baseTexture; + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture based on the source you provide. + * The source can be - image url, image element, canvas element. + * + * @static + * @param {string|HTMLImageElement|HTMLCanvasElement} source - The source to create base texture from. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.from = function from(source, scaleMode, sourceScale) { + if (typeof source === 'string') { + return BaseTexture.fromImage(source, undefined, scaleMode, sourceScale); + } else if (source instanceof HTMLImageElement) { + var imageUrl = source.src; + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + baseTexture = new BaseTexture(source, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + _utils.BaseTextureCache[imageUrl] = baseTexture; + } + + return baseTexture; + } else if (source instanceof HTMLCanvasElement) { + return BaseTexture.fromCanvas(source, scaleMode); + } + + // lets assume its a base texture! + return source; + }; + + return BaseTexture; +}(_eventemitter2.default); + +exports.default = BaseTexture; + +},{"../settings":99,"../utils":120,"../utils/determineCrossOrigin":119,"bit-twiddle":1,"eventemitter3":3}],110:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseRenderTexture = require('./BaseRenderTexture'); + +var _BaseRenderTexture2 = _interopRequireDefault(_BaseRenderTexture); + +var _Texture2 = require('./Texture'); + +var _Texture3 = _interopRequireDefault(_Texture2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A RenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let renderTexture = PIXI.RenderTexture.create(800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let renderTexture = new PIXI.RenderTexture.create(100, 100); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.Texture + * @memberof PIXI + */ +var RenderTexture = function (_Texture) { + _inherits(RenderTexture, _Texture); + + /** + * @param {PIXI.BaseRenderTexture} baseRenderTexture - The renderer used for this RenderTexture + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + */ + function RenderTexture(baseRenderTexture, frame) { + _classCallCheck(this, RenderTexture); + + // support for legacy.. + var _legacyRenderer = null; + + if (!(baseRenderTexture instanceof _BaseRenderTexture2.default)) { + /* eslint-disable prefer-rest-params, no-console */ + var width = arguments[1]; + var height = arguments[2]; + var scaleMode = arguments[3]; + var resolution = arguments[4]; + + // we have an old render texture.. + console.warn('Please use RenderTexture.create(' + width + ', ' + height + ') instead of the ctor directly.'); + _legacyRenderer = arguments[0]; + /* eslint-enable prefer-rest-params, no-console */ + + frame = null; + baseRenderTexture = new _BaseRenderTexture2.default(width, height, scaleMode, resolution); + } + + /** + * The base texture object that this texture uses + * + * @member {BaseTexture} + */ + + var _this = _possibleConstructorReturn(this, _Texture.call(this, baseRenderTexture, frame)); + + _this.legacyRenderer = _legacyRenderer; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = true; + + _this._updateUvs(); + return _this; + } + + /** + * Resizes the RenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + * @param {boolean} doNotResizeBaseTexture - Should the baseTexture.width and height values be resized as well? + */ + + + RenderTexture.prototype.resize = function resize(width, height, doNotResizeBaseTexture) { + // TODO - could be not required.. + this.valid = width > 0 && height > 0; + + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + + if (!doNotResizeBaseTexture) { + this.baseTexture.resize(width, height); + } + + this._updateUvs(); + }; + + /** + * A short hand way of creating a render texture. + * + * @param {number} [width=100] - The width of the render texture + * @param {number} [height=100] - The height of the render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.RenderTexture} The new render texture + */ + + + RenderTexture.create = function create(width, height, scaleMode, resolution) { + return new RenderTexture(new _BaseRenderTexture2.default(width, height, scaleMode, resolution)); + }; + + return RenderTexture; +}(_Texture3.default); + +exports.default = RenderTexture; + +},{"./BaseRenderTexture":108,"./Texture":112}],111:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _ = require('../'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Utility class for maintaining reference to a collection + * of Textures on a single Spritesheet. + * + * @class + * @memberof PIXI + */ +var Spritesheet = function () { + _createClass(Spritesheet, null, [{ + key: 'BATCH_SIZE', + + /** + * The maximum number of Textures to build per process. + * + * @type {number} + * @default 1000 + */ + get: function get() { + return 1000; + } + + /** + * @param {PIXI.BaseTexture} baseTexture Reference to the source BaseTexture object. + * @param {Object} data - Spritesheet image data. + * @param {string} [resolutionFilename] - The filename to consider when determining + * the resolution of the spritesheet. If not provided, the imageUrl will + * be used on the BaseTexture. + */ + + }]); + + function Spritesheet(baseTexture, data) { + var resolutionFilename = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + _classCallCheck(this, Spritesheet); + + /** + * Reference to ths source texture + * @type {PIXI.BaseTexture} + */ + this.baseTexture = baseTexture; + + /** + * Map of spritesheet textures. + * @type {Object} + */ + this.textures = {}; + + /** + * Reference to the original JSON data. + * @type {Object} + */ + this.data = data; + + /** + * The resolution of the spritesheet. + * @type {number} + */ + this.resolution = this._updateResolution(resolutionFilename || this.baseTexture.imageUrl); + + /** + * Map of spritesheet frames. + * @type {Object} + * @private + */ + this._frames = this.data.frames; + + /** + * Collection of frame names. + * @type {string[]} + * @private + */ + this._frameKeys = Object.keys(this._frames); + + /** + * Current batch index being processed. + * @type {number} + * @private + */ + this._batchIndex = 0; + + /** + * Callback when parse is completed. + * @type {Function} + * @private + */ + this._callback = null; + } + + /** + * Generate the resolution from the filename or fallback + * to the meta.scale field of the JSON data. + * + * @private + * @param {string} resolutionFilename - The filename to use for resolving + * the default resolution. + * @return {number} Resolution to use for spritesheet. + */ + + + Spritesheet.prototype._updateResolution = function _updateResolution(resolutionFilename) { + var scale = this.data.meta.scale; + + // Use a defaultValue of `null` to check if a url-based resolution is set + var resolution = (0, _utils.getResolutionOfUrl)(resolutionFilename, null); + + // No resolution found via URL + if (resolution === null) { + // Use the scale value or default to 1 + resolution = scale !== undefined ? parseFloat(scale) : 1; + } + + // For non-1 resolutions, update baseTexture + if (resolution !== 1) { + this.baseTexture.resolution = resolution; + this.baseTexture.update(); + } + + return resolution; + }; + + /** + * Parser spritesheet from loaded data. This is done asynchronously + * to prevent creating too many Texture within a single process. + * + * @param {Function} callback - Callback when complete returns + * a map of the Textures for this spritesheet. + */ + + + Spritesheet.prototype.parse = function parse(callback) { + this._batchIndex = 0; + this._callback = callback; + + if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) { + this._processFrames(0); + this._parseComplete(); + } else { + this._nextBatch(); + } + }; + + /** + * Process a batch of frames + * + * @private + * @param {number} initialFrameIndex - The index of frame to start. + */ + + + Spritesheet.prototype._processFrames = function _processFrames(initialFrameIndex) { + var frameIndex = initialFrameIndex; + var maxFrames = Spritesheet.BATCH_SIZE; + + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { + var i = this._frameKeys[frameIndex]; + var rect = this._frames[i].frame; + + if (rect) { + var frame = null; + var trim = null; + var orig = new _.Rectangle(0, 0, this._frames[i].sourceSize.w / this.resolution, this._frames[i].sourceSize.h / this.resolution); + + if (this._frames[i].rotated) { + frame = new _.Rectangle(rect.x / this.resolution, rect.y / this.resolution, rect.h / this.resolution, rect.w / this.resolution); + } else { + frame = new _.Rectangle(rect.x / this.resolution, rect.y / this.resolution, rect.w / this.resolution, rect.h / this.resolution); + } + + // Check to see if the sprite is trimmed + if (this._frames[i].trimmed) { + trim = new _.Rectangle(this._frames[i].spriteSourceSize.x / this.resolution, this._frames[i].spriteSourceSize.y / this.resolution, rect.w / this.resolution, rect.h / this.resolution); + } + + this.textures[i] = new _.Texture(this.baseTexture, frame, orig, trim, this._frames[i].rotated ? 2 : 0); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage functions + _utils.TextureCache[i] = this.textures[i]; + } + + frameIndex++; + } + }; + + /** + * The parse has completed. + * + * @private + */ + + + Spritesheet.prototype._parseComplete = function _parseComplete() { + var callback = this._callback; + + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); + }; + + /** + * Begin the next batch of textures. + * + * @private + */ + + + Spritesheet.prototype._nextBatch = function _nextBatch() { + var _this = this; + + this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); + this._batchIndex++; + setTimeout(function () { + if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { + _this._nextBatch(); + } else { + _this._parseComplete(); + } + }, 0); + }; + + /** + * Destroy Spritesheet and don't use after this. + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Spritesheet.prototype.destroy = function destroy() { + var destroyBase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + for (var i in this.textures) { + this.textures[i].destroy(); + } + this._frames = null; + this._frameKeys = null; + this.data = null; + this.textures = null; + if (destroyBase) { + this.baseTexture.destroy(); + } + this.baseTexture = null; + }; + + return Spritesheet; +}(); + +exports.default = Spritesheet; + +},{"../":63,"../utils":120}],112:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture = require('./BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _VideoBaseTexture = require('./VideoBaseTexture'); + +var _VideoBaseTexture2 = _interopRequireDefault(_VideoBaseTexture); + +var _TextureUvs = require('./TextureUvs'); + +var _TextureUvs2 = _interopRequireDefault(_TextureUvs); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _math = require('../math'); + +var _utils = require('../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided + * then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * let texture = PIXI.Texture.fromImage('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` + * + * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. + * You can check for this by checking the sprite's _textureID property. + * ```js + * var texture = PIXI.Texture.fromImage('assets/image.svg'); + * var sprite1 = new PIXI.Sprite(texture); + * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file + * ``` + * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var Texture = function (_EventEmitter) { + _inherits(Texture, _EventEmitter); + + /** + * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + * @param {PIXI.Rectangle} [orig] - The area of original texture + * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture + * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8} + */ + function Texture(baseTexture, frame, orig, trim, rotate) { + _classCallCheck(this, Texture); + + /** + * Does this Texture have any frame data assigned to it? + * + * @member {boolean} + */ + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.noFrame = false; + + if (!frame) { + _this.noFrame = true; + frame = new _math.Rectangle(0, 0, 1, 1); + } + + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @member {PIXI.BaseTexture} + */ + _this.baseTexture = baseTexture; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @member {PIXI.Rectangle} + */ + _this._frame = frame; + + /** + * This is the trimmed area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @member {boolean} + */ + _this.requiresUpdate = false; + + /** + * The WebGL UV data cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + _this._uvs = null; + + /** + * This is the area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + + _this._rotate = Number(rotate || 0); + + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); + } + + if (baseTexture.hasLoaded) { + if (_this.noFrame) { + frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + + // if there is no frame we should monitor for any base texture changes.. + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + _this.frame = frame; + } else { + baseTexture.once('loaded', _this.onBaseTextureLoaded, _this); + } + + /** + * Fired when the texture is updated. This happens if the frame or the baseTexture is updated. + * + * @event update + * @memberof PIXI.Texture# + * @protected + */ + + _this._updateID = 0; + + /** + * Extra field for extra plugins. May contain clamp settings and some matrices + * @type {Object} + */ + _this.transform = null; + return _this; + } + + /** + * Updates this texture on the gpu. + * + */ + + + Texture.prototype.update = function update() { + this.baseTexture.update(); + }; + + /** + * Called when the base texture is loaded + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureLoaded = function onBaseTextureLoaded(baseTexture) { + this._updateID++; + + // TODO this code looks confusing.. boo to abusing getters and setters! + if (this.noFrame) { + this.frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } else { + this.frame = this._frame; + } + + this.baseTexture.on('update', this.onBaseTextureUpdated, this); + this.emit('update', this); + }; + + /** + * Called when the base texture is updated + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated(baseTexture) { + this._updateID++; + + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Texture.prototype.destroy = function destroy(destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destroyed too.. + if (_utils.TextureCache[this.baseTexture.imageUrl]) { + delete _utils.TextureCache[this.baseTexture.imageUrl]; + } + + this.baseTexture.destroy(); + } + + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); + + this.baseTexture = null; + } + + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + + this.valid = false; + + this.off('dispose', this.dispose, this); + this.off('update', this.update, this); + }; + + /** + * Creates a new texture object that acts the same as this one. + * + * @return {PIXI.Texture} The new texture + */ + + + Texture.prototype.clone = function clone() { + return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); + }; + + /** + * Updates the internal WebGL UV cache. + * + * @protected + */ + + + Texture.prototype._updateUvs = function _updateUvs() { + if (!this._uvs) { + this._uvs = new _TextureUvs2.default(); + } + + this._uvs.set(this._frame, this.baseTexture, this.rotate); + + this._updateID++; + }; + + /** + * Helper function that creates a Texture object from the given image url. + * If the image is not in the texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var texture = _utils.TextureCache[imageUrl]; + + if (!texture) { + texture = new Texture(_BaseTexture2.default.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); + _utils.TextureCache[imageUrl] = texture; + } + + return texture; + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return texture; + }; + + /** + * Helper function that creates a new Texture based on the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromCanvas = function fromCanvas(canvas, scaleMode) { + return new Texture(_BaseTexture2.default.fromCanvas(canvas, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the given video element. + * + * @static + * @param {HTMLVideoElement|string} video - The URL or actual element of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideo = function fromVideo(video, scaleMode) { + if (typeof video === 'string') { + return Texture.fromVideoUrl(video, scaleMode); + } + + return new Texture(_VideoBaseTexture2.default.fromVideo(video, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the video url. + * + * @static + * @param {string} videoUrl - URL of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideoUrl = function fromVideoUrl(videoUrl, scaleMode) { + return new Texture(_VideoBaseTexture2.default.fromUrl(videoUrl, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} + * source - Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.from = function from(source) { + // TODO auto detect cross origin.. + // TODO pass in scale mode? + if (typeof source === 'string') { + var texture = _utils.TextureCache[source]; + + if (!texture) { + // check if its a video.. + var isVideo = source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/) !== null; + + if (isVideo) { + return Texture.fromVideoUrl(source); + } + + return Texture.fromImage(source); + } + + return texture; + } else if (source instanceof HTMLImageElement) { + return new Texture(_BaseTexture2.default.from(source)); + } else if (source instanceof HTMLCanvasElement) { + return Texture.fromCanvas(source); + } else if (source instanceof HTMLVideoElement) { + return Texture.fromVideo(source); + } else if (source instanceof _BaseTexture2.default) { + return new Texture(source); + } + + // lets assume its a texture! + return source; + }; + + /** + * Create a texture from a source and add to the cache. + * + * @static + * @param {HTMLImageElement|HTMLCanvasElement} source - The input source. + * @param {String} imageUrl - File name of texture, for cache and resolving resolution. + * @param {String} [name] - Human readible name for the texture cache. If no name is + * specified, only `imageUrl` will be used as the cache ID. + * @return {PIXI.Texture} Output texture + */ + + + Texture.fromLoader = function fromLoader(source, imageUrl, name) { + var baseTexture = new _BaseTexture2.default(source, null, (0, _utils.getResolutionOfUrl)(imageUrl)); + var texture = new Texture(baseTexture); + + baseTexture.imageUrl = imageUrl; + + // No name, use imageUrl instead + if (!name) { + name = imageUrl; + } + + // lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions + _utils.BaseTextureCache[name] = baseTexture; + _utils.TextureCache[name] = texture; + + // also add references by url if they are different. + if (name !== imageUrl) { + _utils.BaseTextureCache[imageUrl] = baseTexture; + _utils.TextureCache[imageUrl] = texture; + } + + return texture; + }; + + /** + * Adds a texture to the global TextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the texture will be stored against. + */ + + + Texture.addTextureToCache = function addTextureToCache(texture, id) { + _utils.TextureCache[id] = texture; + }; + + /** + * Remove a texture from the global TextureCache. + * + * @static + * @param {string} id - The id of the texture to be removed + * @return {PIXI.Texture} The texture that was removed + */ + + + Texture.removeTextureFromCache = function removeTextureFromCache(id) { + var texture = _utils.TextureCache[id]; + + delete _utils.TextureCache[id]; + delete _utils.BaseTextureCache[id]; + + return texture; + }; + + /** + * The frame specifies the region of the base texture that this texture uses. + * + * @member {PIXI.Rectangle} + */ + + + _createClass(Texture, [{ + key: 'frame', + get: function get() { + return this._frame; + }, + set: function set(frame) // eslint-disable-line require-jsdoc + { + this._frame = frame; + + this.noFrame = false; + + if (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height) { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + ('X: ' + frame.x + ' + ' + frame.width + ' > ' + this.baseTexture.width + ' ') + ('Y: ' + frame.y + ' + ' + frame.height + ' > ' + this.baseTexture.height)); + } + + // this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + this.valid = frame && frame.width && frame.height && this.baseTexture.hasLoaded; + + if (!this.trim && !this.rotate) { + this.orig = frame; + } + + if (this.valid) { + this._updateUvs(); + } + } + + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.GroupD8} for explanation + * + * @member {number} + */ + + }, { + key: 'rotate', + get: function get() { + return this._rotate; + }, + set: function set(rotate) // eslint-disable-line require-jsdoc + { + this._rotate = rotate; + if (this.valid) { + this._updateUvs(); + } + } + + /** + * The width of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'width', + get: function get() { + return this.orig.width; + } + + /** + * The height of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.orig.height; + } + }]); + + return Texture; +}(_eventemitter2.default); + +exports.default = Texture; + + +function createWhiteTexture() { + var canvas = document.createElement('canvas'); + + canvas.width = 10; + canvas.height = 10; + + var context = canvas.getContext('2d'); + + context.fillStyle = 'white'; + context.fillRect(0, 0, 10, 10); + + return new Texture(new _BaseTexture2.default(canvas)); +} + +function removeAllHandlers(tex) { + tex.destroy = function _emptyDestroy() {/* empty */}; + tex.on = function _emptyOn() {/* empty */}; + tex.once = function _emptyOnce() {/* empty */}; + tex.emit = function _emptyEmit() {/* empty */}; +} + +/** + * An empty texture, used often to not have to create multiple empty textures. + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.EMPTY = new Texture(new _BaseTexture2.default()); +removeAllHandlers(Texture.EMPTY); + +/** + * A white texture of 10x10 size, used for graphics and other things + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.WHITE = createWhiteTexture(); +removeAllHandlers(Texture.WHITE); + +},{"../math":68,"../utils":120,"./BaseTexture":109,"./TextureUvs":113,"./VideoBaseTexture":114,"eventemitter3":3}],113:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _GroupD = require('../math/GroupD8'); + +var _GroupD2 = _interopRequireDefault(_GroupD); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A standard object to store the Uvs of a texture + * + * @class + * @private + * @memberof PIXI + */ +var TextureUvs = function () { + /** + * + */ + function TextureUvs() { + _classCallCheck(this, TextureUvs); + + this.x0 = 0; + this.y0 = 0; + + this.x1 = 1; + this.y1 = 0; + + this.x2 = 1; + this.y2 = 1; + + this.x3 = 0; + this.y3 = 1; + + this.uvsUint32 = new Uint32Array(4); + } + + /** + * Sets the texture Uvs based on the given frame information. + * + * @private + * @param {PIXI.Rectangle} frame - The frame of the texture + * @param {PIXI.Rectangle} baseFrame - The base frame of the texture + * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8} + */ + + + TextureUvs.prototype.set = function set(frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + + // coordinates of center + var cX = frame.x / tw + w2; + var cY = frame.y / th + h2; + + rotate = _GroupD2.default.add(rotate, _GroupD2.default.NW); // NW is top-left corner + this.x0 = cX + w2 * _GroupD2.default.uX(rotate); + this.y0 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + w2 * _GroupD2.default.uX(rotate); + this.y1 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x2 = cX + w2 * _GroupD2.default.uX(rotate); + this.y2 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x3 = cX + w2 * _GroupD2.default.uX(rotate); + this.y3 = cY + h2 * _GroupD2.default.uY(rotate); + } else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + + this.uvsUint32[0] = (this.y0 * 65535 & 0xFFFF) << 16 | this.x0 * 65535 & 0xFFFF; + this.uvsUint32[1] = (this.y1 * 65535 & 0xFFFF) << 16 | this.x1 * 65535 & 0xFFFF; + this.uvsUint32[2] = (this.y2 * 65535 & 0xFFFF) << 16 | this.x2 * 65535 & 0xFFFF; + this.uvsUint32[3] = (this.y3 * 65535 & 0xFFFF) << 16 | this.x3 * 65535 & 0xFFFF; + }; + + return TextureUvs; +}(); + +exports.default = TextureUvs; + +},{"../math/GroupD8":64}],114:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _utils = require('../utils'); + +var _ticker = require('../ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture of a [playing] Video. + * + * Video base textures mimic Pixi BaseTexture.from.... method in their creation process. + * + * This can be used in several ways, such as: + * + * ```js + * let texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4'); + * + * let texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' }); + * + * let texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']); + * + * let texture = PIXI.VideoBaseTexture.fromUrls([ + * { src: '/video.webm', mime: 'video/webm' }, + * { src: '/video.mp4', mime: 'video/mp4' } + * ]); + * ``` + * + * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/). + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var VideoBaseTexture = function (_BaseTexture) { + _inherits(VideoBaseTexture, _BaseTexture); + + /** + * @param {HTMLVideoElement} source - Video source + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + */ + function VideoBaseTexture(source, scaleMode) { + _classCallCheck(this, VideoBaseTexture); + + if (!source) { + throw new Error('No video source element specified.'); + } + + // hook in here to check if video is already available. + // BaseTexture looks for a source.complete boolean, plus width & height. + + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + source.complete = true; + } + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, source, scaleMode)); + + _this.width = source.videoWidth; + _this.height = source.videoHeight; + + _this._autoUpdate = true; + _this._isAutoUpdating = false; + + /** + * When set to true will automatically play videos used by this texture once + * they are loaded. If false, it will not modify the playing state. + * + * @member {boolean} + * @default true + */ + _this.autoPlay = true; + + _this.update = _this.update.bind(_this); + _this._onCanPlay = _this._onCanPlay.bind(_this); + + source.addEventListener('play', _this._onPlayStart.bind(_this)); + source.addEventListener('pause', _this._onPlayStop.bind(_this)); + _this.hasLoaded = false; + _this.__loaded = false; + + if (!_this._isSourceReady()) { + source.addEventListener('canplay', _this._onCanPlay); + source.addEventListener('canplaythrough', _this._onCanPlay); + } else { + _this._onCanPlay(); + } + return _this; + } + + /** + * Returns true if the underlying source is playing. + * + * @private + * @return {boolean} True if playing. + */ + + + VideoBaseTexture.prototype._isSourcePlaying = function _isSourcePlaying() { + var source = this.source; + + return source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2; + }; + + /** + * Returns true if the underlying source is ready for playing. + * + * @private + * @return {boolean} True if ready. + */ + + + VideoBaseTexture.prototype._isSourceReady = function _isSourceReady() { + return this.source.readyState === 3 || this.source.readyState === 4; + }; + + /** + * Runs the update loop when the video is ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStart = function _onPlayStart() { + // Just in case the video has not received its can play even yet.. + if (!this.hasLoaded) { + this._onCanPlay(); + } + + if (!this._isAutoUpdating && this.autoUpdate) { + ticker.shared.add(this.update, this); + this._isAutoUpdating = true; + } + }; + + /** + * Fired when a pause event is triggered, stops the update loop + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStop = function _onPlayStop() { + if (this._isAutoUpdating) { + ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } + }; + + /** + * Fired when the video is loaded and ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onCanPlay = function _onCanPlay() { + this.hasLoaded = true; + + if (this.source) { + this.source.removeEventListener('canplay', this._onCanPlay); + this.source.removeEventListener('canplaythrough', this._onCanPlay); + + this.width = this.source.videoWidth; + this.height = this.source.videoHeight; + + // prevent multiple loaded dispatches.. + if (!this.__loaded) { + this.__loaded = true; + this.emit('loaded', this); + } + + if (this._isSourcePlaying()) { + this._onPlayStart(); + } else if (this.autoPlay) { + this.source.play(); + } + } + }; + + /** + * Destroys this texture + * + */ + + + VideoBaseTexture.prototype.destroy = function destroy() { + if (this._isAutoUpdating) { + ticker.shared.remove(this.update, this); + } + + if (this.source && this.source._pixiId) { + delete _utils.BaseTextureCache[this.source._pixiId]; + delete this.source._pixiId; + } + + _BaseTexture.prototype.destroy.call(this); + }; + + /** + * Mimic Pixi BaseTexture.from.... method. + * + * @static + * @param {HTMLVideoElement} video - Video to create texture from + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromVideo = function fromVideo(video, scaleMode) { + if (!video._pixiId) { + video._pixiId = 'video_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[video._pixiId]; + + if (!baseTexture) { + baseTexture = new VideoBaseTexture(video, scaleMode); + _utils.BaseTextureCache[video._pixiId] = baseTexture; + } + + return baseTexture; + }; + + /** + * Helper function that creates a new BaseTexture based on the given video element. + * This BaseTexture can then be used to create a texture + * + * @static + * @param {string|object|string[]|object[]} videoSrc - The URL(s) for the video. + * @param {string} [videoSrc.src] - One of the source urls for the video + * @param {string} [videoSrc.mime] - The mimetype of the video (e.g. 'video/mp4'). If not specified + * the url's extension will be used as the second part of the mime type. + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromUrl = function fromUrl(videoSrc, scaleMode) { + var video = document.createElement('video'); + + video.setAttribute('webkit-playsinline', ''); + video.setAttribute('playsinline', ''); + + // array of objects or strings + if (Array.isArray(videoSrc)) { + for (var i = 0; i < videoSrc.length; ++i) { + video.appendChild(createSource(videoSrc[i].src || videoSrc[i], videoSrc[i].mime)); + } + } + // single object or string + else { + video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); + } + + video.load(); + + return VideoBaseTexture.fromVideo(video, scaleMode); + }; + + /** + * Should the base texture automatically update itself, set to true by default + * + * @member {boolean} + */ + + + _createClass(VideoBaseTexture, [{ + key: 'autoUpdate', + get: function get() { + return this._autoUpdate; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + + if (!this._autoUpdate && this._isAutoUpdating) { + ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } else if (this._autoUpdate && !this._isAutoUpdating) { + ticker.shared.add(this.update, this); + this._isAutoUpdating = true; + } + } + } + }]); + + return VideoBaseTexture; +}(_BaseTexture3.default); + +exports.default = VideoBaseTexture; + + +VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; + +function createSource(path, type) { + if (!type) { + type = 'video/' + path.substr(path.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = path; + source.type = type; + + return source; +} + +},{"../ticker":116,"../utils":120,"./BaseTexture":109}],115:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// Internal event used by composed emitter +var TICK = 'tick'; + +/** + * A Ticker class that runs an update loop that other objects listen to. + * This class is composed around an EventEmitter object to add listeners + * meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, + * e.g. When the ticker is started and the emitter has listeners. + * + * @class + * @memberof PIXI.ticker + */ + +var Ticker = function () { + /** + * + */ + function Ticker() { + var _this = this; + + _classCallCheck(this, Ticker); + + /** + * Internal emitter used to fire 'tick' event + * @private + */ + this._emitter = new _eventemitter2.default(); + + /** + * Internal current frame request ID + * @private + */ + this._requestId = null; + + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + * @private + */ + this._maxElapsedMS = 100; + + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.ticker.Ticker#start} automatically + * when a listener is added. + * + * @member {boolean} + * @default false + */ + this.autoStart = false; + + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS} + * and is scaled with {@link PIXI.ticker.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * + * @member {number} + * @default 1 + */ + this.deltaTime = 1; + + /** + * Time elapsed in milliseconds from last frame to this frame. + * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime} + * is based, this value is neither capped nor scaled. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * Defaults to target frame time + * + * @member {number} + * @default 16.66 + */ + this.elapsedMS = 1 / _settings2.default.TARGET_FPMS; + + /** + * The last time {@link PIXI.ticker.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default 0 + */ + this.lastTime = 0; + + /** + * Factor of current {@link PIXI.ticker.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + * + * @member {number} + * @default 1 + */ + this.speed = 1; + + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.ticker.Ticker#start} has been called. + * `false` if {@link PIXI.ticker.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.ticker.Ticker#autoStart} being `true` + * and a listener is added. + * + * @member {boolean} + * @default false + */ + this.started = false; + + /** + * Internal tick method bound to ticker instance. + * This is because in early 2015, Function.bind + * is still 60% slower in high performance scenarios. + * Also separating frame requests from update method + * so listeners may be called at any time and with + * any animation API, just invoke ticker.update(time). + * + * @private + * @param {number} time - Time since last tick. + */ + this._tick = function (time) { + _this._requestId = null; + + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._emitter.listeners(TICK, true)) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * + * @private + */ + + + Ticker.prototype._requestIfNeeded = function _requestIfNeeded() { + if (this._requestId === null && this._emitter.listeners(TICK, true)) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._requestId = requestAnimationFrame(this._tick); + } + }; + + /** + * Conditionally cancels a pending animation frame. + * + * @private + */ + + + Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; + + /** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * + * @private + */ + + + Ticker.prototype._startIfPossible = function _startIfPossible() { + if (this.started) { + this._requestIfNeeded(); + } else if (this.autoStart) { + this.start(); + } + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#on} internally for the + * internal 'tick' event. It checks if the emitter has listeners, + * and if so it requests a new animation frame at this point. + * + * @param {Function} fn - The listener function to be added for updates + * @param {Function} [context] - The listener context + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.add = function add(fn, context) { + this._emitter.on(TICK, fn, context); + + this._startIfPossible(); + + return this; + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#once} internally for the + * internal 'tick' event. It checks if the emitter has listeners, + * and if so it requests a new animation frame at this point. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context] - The listener context + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.addOnce = function addOnce(fn, context) { + this._emitter.once(TICK, fn, context); + + this._startIfPossible(); + + return this; + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#off} internally for 'tick' event. + * It checks if the emitter has listeners for 'tick' event. + * If it does, then it cancels the animation frame. + * + * @param {Function} [fn] - The listener function to be removed + * @param {Function} [context] - The listener context to be removed + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.remove = function remove(fn, context) { + this._emitter.off(TICK, fn, context); + + if (!this._emitter.listeners(TICK, true)) { + this._cancelIfNeeded(); + } + + return this; + }; + + /** + * Starts the ticker. If the ticker has listeners + * a new animation frame is requested at this point. + */ + + + Ticker.prototype.start = function start() { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + }; + + /** + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. + */ + + + Ticker.prototype.stop = function stop() { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; + + /** + * Triggers an update. An update entails setting the + * current {@link PIXI.ticker.Ticker#elapsedMS}, + * the current {@link PIXI.ticker.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.ticker.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + + + Ticker.prototype.update = function update() { + var currentTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : performance.now(); + + var elapsedMS = void 0; + + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + + this.deltaTime = elapsedMS * _settings2.default.TARGET_FPMS * this.speed; + + // Invoke listeners added to internal emitter + this._emitter.emit(TICK, this.deltaTime); + } else { + this.deltaTime = this.elapsedMS = 0; + } + + this.lastTime = currentTime; + }; + + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.ticker.Ticker#speed}, which is specific + * to scaling {@link PIXI.ticker.Ticker#deltaTime}. + * + * @member {number} + * @readonly + */ + + + _createClass(Ticker, [{ + key: 'FPS', + get: function get() { + return 1000 / this.elapsedMS; + } + + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.ticker.Ticker#update}. + * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.settings.TARGET_FPMS * 1000`. + * + * @member {number} + * @default 10 + */ + + }, { + key: 'minFPS', + get: function get() { + return 1000 / this._maxElapsedMS; + }, + set: function set(fps) // eslint-disable-line require-jsdoc + { + // Clamp: 0 to TARGET_FPMS + var minFPMS = Math.min(Math.max(0, fps) / 1000, _settings2.default.TARGET_FPMS); + + this._maxElapsedMS = 1 / minFPMS; + } + }]); + + return Ticker; +}(); + +exports.default = Ticker; + +},{"../settings":99,"eventemitter3":3}],116:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Ticker = exports.shared = undefined; + +var _Ticker = require('./Ticker'); + +var _Ticker2 = _interopRequireDefault(_Ticker); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The shared ticker instance used by {@link PIXI.extras.AnimatedSprite}. + * and by {@link PIXI.interaction.InteractionManager}. + * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` + * for this instance. Please follow the examples for usage, including + * how to opt-out of auto-starting the shared ticker. + * + * @example + * let ticker = PIXI.ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(800, 600); + * let stage = new PIXI.Container(); + * let interactionManager = PIXI.interaction.InteractionManager(renderer); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * + * @type {PIXI.ticker.Ticker} + * @memberof PIXI.ticker + */ +var shared = new _Ticker2.default(); + +shared.autoStart = true; + +/** + * @namespace PIXI.ticker + */ +exports.shared = shared; +exports.Ticker = _Ticker2.default; + +},{"./Ticker":115}],117:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = canUploadSameBuffer; +function canUploadSameBuffer() { + // Uploading the same buffer multiple times in a single frame can cause perf issues. + // Apparent on IOS so only check for that at the moment + // this check may become more complex if this issue pops up elsewhere. + var ios = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform); + + return !ios; +} + +},{}],118:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = createIndicesForQuads; +/** + * Generic Mask Stack data structure + * + * @memberof PIXI + * @function createIndicesForQuads + * @private + * @param {number} size - Number of quads + * @return {Uint16Array} indices + */ +function createIndicesForQuads(size) { + // the total number of indices in our array, there are 6 points per quad. + + var totalIndices = size * 6; + + var indices = new Uint16Array(totalIndices); + + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + indices[i + 0] = j + 0; + indices[i + 1] = j + 1; + indices[i + 2] = j + 2; + indices[i + 3] = j + 0; + indices[i + 4] = j + 2; + indices[i + 5] = j + 3; + } + + return indices; +} + +},{}],119:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = determineCrossOrigin; + +var _url2 = require('url'); + +var _url3 = _interopRequireDefault(_url2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var tempAnchor = void 0; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +function determineCrossOrigin(url) { + var loc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location; + + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url3.default.parse(tempAnchor.href); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +} + +},{"url":28}],120:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BaseTextureCache = exports.TextureCache = exports.mixins = exports.pluginTarget = exports.EventEmitter = exports.isMobile = undefined; +exports.uid = uid; +exports.hex2rgb = hex2rgb; +exports.hex2string = hex2string; +exports.rgb2hex = rgb2hex; +exports.getResolutionOfUrl = getResolutionOfUrl; +exports.decomposeDataUri = decomposeDataUri; +exports.getUrlFileExtension = getUrlFileExtension; +exports.getSvgSize = getSvgSize; +exports.skipHello = skipHello; +exports.sayHello = sayHello; +exports.isWebGLSupported = isWebGLSupported; +exports.sign = sign; +exports.removeItems = removeItems; +exports.destroyTextureCache = destroyTextureCache; +exports.clearTextureCache = clearTextureCache; + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _pluginTarget = require('./pluginTarget'); + +var _pluginTarget2 = _interopRequireDefault(_pluginTarget); + +var _mixin = require('./mixin'); + +var mixins = _interopRequireWildcard(_mixin); + +var _ismobilejs = require('ismobilejs'); + +var isMobile = _interopRequireWildcard(_ismobilejs); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var nextUid = 0; +var saidHello = false; + +/** + * @namespace PIXI.utils + */ +exports.isMobile = isMobile; +exports.EventEmitter = _eventemitter2.default; +exports.pluginTarget = _pluginTarget2.default; +exports.mixins = mixins; + +/** + * Gets the next unique identifier + * + * @memberof PIXI.utils + * @function uid + * @return {number} The next unique identifier to use. + */ + +function uid() { + return ++nextUid; +} + +/** + * Converts a hex color number to an [R, G, B] array + * + * @memberof PIXI.utils + * @function hex2rgb + * @param {number} hex - The number to convert + * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one + * @return {number[]} An array representing the [R, G, B] of the color. + */ +function hex2rgb(hex, out) { + out = out || []; + + out[0] = (hex >> 16 & 0xFF) / 255; + out[1] = (hex >> 8 & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + + return out; +} + +/** + * Converts a hex color number to a string. + * + * @memberof PIXI.utils + * @function hex2string + * @param {number} hex - Number in hex + * @return {string} The string color. + */ +function hex2string(hex) { + hex = hex.toString(16); + hex = '000000'.substr(0, 6 - hex.length) + hex; + + return '#' + hex; +} + +/** + * Converts a color as an [R, G, B] array to a hex number + * + * @memberof PIXI.utils + * @function rgb2hex + * @param {number[]} rgb - rgb array + * @return {number} The color number + */ +function rgb2hex(rgb) { + return (rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + (rgb[2] * 255 | 0); +} + +/** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * + * @memberof PIXI.utils + * @function getResolutionOfUrl + * @param {string} url - the image path + * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. + * @return {number} resolution / device pixel ratio of an asset + */ +function getResolutionOfUrl(url, defaultValue) { + var resolution = _settings2.default.RETINA_PREFIX.exec(url); + + if (resolution) { + return parseFloat(resolution[1]); + } + + return defaultValue !== undefined ? defaultValue : 1; +} + +/** + * Typedef for decomposeDataUri return object. + * + * @typedef {object} DecomposedDataUri + * @property {mediaType} Media type, eg. `image` + * @property {subType} Sub type, eg. `png` + * @property {encoding} Data encoding, eg. `base64` + * @property {data} The actual data + */ + +/** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. + * + * @memberof PIXI.utils + * @function decomposeDataUri + * @param {string} dataUri - the data URI to check + * @return {DecomposedDataUri|undefined} The decomposed data uri or undefined + */ +function decomposeDataUri(dataUri) { + var dataUriMatch = _const.DATA_URI.exec(dataUri); + + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + encoding: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + data: dataUriMatch[4] + }; + } + + return undefined; +} + +/** + * Get type of the image by regexp for extension. Returns undefined for unknown extensions. + * + * @memberof PIXI.utils + * @function getUrlFileExtension + * @param {string} url - the image path + * @return {string|undefined} image extension + */ +function getUrlFileExtension(url) { + var extension = _const.URL_FILE_EXTENSION.exec(url); + + if (extension) { + return extension[1].toLowerCase(); + } + + return undefined; +} + +/** + * Typedef for Size object. + * + * @typedef {object} Size + * @property {width} Width component + * @property {height} Height component + */ + +/** + * Get size from an svg string using regexp. + * + * @memberof PIXI.utils + * @function getSvgSize + * @param {string} svgString - a serialized svg element + * @return {Size|undefined} image extension + */ +function getSvgSize(svgString) { + var sizeMatch = _const.SVG_SIZE.exec(svgString); + var size = {}; + + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); + size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); + } + + return size; +} + +/** + * Skips the hello message of renderers that are created after this is run. + * + * @function skipHello + * @memberof PIXI.utils + */ +function skipHello() { + saidHello = true; +} + +/** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever makes you a jerk face. + * + * @static + * @function sayHello + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ +function sayHello(type) { + if (saidHello) { + return; + } + + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = ['\n %c %c %c Pixi.js ' + _const.VERSION + ' - \u2730 ' + type + ' \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n', 'background: #ff66a5; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff66a5; background: #030307; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'background: #ffc3dc; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;']; + + window.console.log.apply(console, args); + } else if (window.console) { + window.console.log('Pixi.js ' + _const.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); + } + + saidHello = true; +} + +/** + * Helper for checking for webgl support + * + * @memberof PIXI.utils + * @function isWebGLSupported + * @return {boolean} is webgl supported + */ +function isWebGLSupported() { + var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; + + try { + if (!window.WebGLRenderingContext) { + return false; + } + + var canvas = document.createElement('canvas'); + var gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); + + var success = !!(gl && gl.getContextAttributes().stencil); + + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + + if (loseContext) { + loseContext.loseContext(); + } + } + + gl = null; + + return success; + } catch (e) { + return false; + } +} + +/** + * Returns sign of number + * + * @memberof PIXI.utils + * @function sign + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ +function sign(n) { + if (n === 0) return 0; + + return n < 0 ? -1 : 1; +} + +/** + * Remove a range of items from an array + * + * @memberof PIXI.utils + * @function removeItems + * @param {Array<*>} arr The target array + * @param {number} startIdx The index to begin removing from (inclusive) + * @param {number} removeCount How many items to remove + */ +function removeItems(arr, startIdx, removeCount) { + var length = arr.length; + + if (startIdx >= length || removeCount === 0) { + return; + } + + removeCount = startIdx + removeCount > length ? length - startIdx : removeCount; + + var len = length - removeCount; + + for (var i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount]; + } + + arr.length = len; +} + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var TextureCache = exports.TextureCache = {}; + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var BaseTextureCache = exports.BaseTextureCache = {}; + +/** + * Destroys all texture in the cache + * + * @memberof PIXI.utils + * @function destroyTextureCache + */ +function destroyTextureCache() { + var key = void 0; + + for (key in TextureCache) { + TextureCache[key].destroy(); + } + for (key in BaseTextureCache) { + BaseTextureCache[key].destroy(); + } +} + +/** + * Removes all textures from cache, but does not destroy them + * + * @memberof PIXI.utils + * @function clearTextureCache + */ +function clearTextureCache() { + var key = void 0; + + for (key in TextureCache) { + delete TextureCache[key]; + } + for (key in BaseTextureCache) { + delete BaseTextureCache[key]; + } +} + +},{"../const":44,"../settings":99,"./mixin":122,"./pluginTarget":123,"eventemitter3":3,"ismobilejs":4}],121:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = maxRecommendedTextures; + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function maxRecommendedTextures(max) { + if (_ismobilejs2.default.tablet || _ismobilejs2.default.phone) { + // check if the res is iphone 6 or higher.. + return 4; + } + + // desktop should be ok + return max; +} + +},{"ismobilejs":4}],122:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.mixin = mixin; +exports.delayMixin = delayMixin; +exports.performMixins = performMixins; +/** + * Mixes all enumerable properties and methods from a source object to a target object. + * + * @memberof PIXI.utils.mixins + * @function mixin + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function mixin(target, source) { + if (!target || !source) return; + // in ES8/ES2017, this would be really easy: + // Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + + // get all the enumerable property keys + var keys = Object.keys(source); + + // loop through properties + for (var i = 0; i < keys.length; ++i) { + var propertyName = keys[i]; + + // Set the property using the property descriptor - this works for accessors and normal value properties + Object.defineProperty(target, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); + } +} + +var mixins = []; + +/** + * Queues a mixin to be handled towards the end of the initialization of PIXI, so that deprecation + * can take effect. + * + * @memberof PIXI.utils.mixins + * @function delayMixin + * @private + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function delayMixin(target, source) { + mixins.push(target, source); +} + +/** + * Handles all mixins queued via delayMixin(). + * + * @memberof PIXI.utils.mixins + * @function performMixins + * @private + */ +function performMixins() { + for (var i = 0; i < mixins.length; i += 2) { + mixin(mixins[i], mixins[i + 1]); + } + mixins.length = 0; +} + +},{}],123:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Mixins functionality to make an object have "plugins". + * + * @example + * function MyObject() {} + * + * pluginTarget.mixin(MyObject); + * + * @mixin + * @memberof PIXI.utils + * @param {object} obj - The object to mix into. + */ +function pluginTarget(obj) { + obj.__plugins = {}; + + /** + * Adds a plugin to an object + * + * @param {string} pluginName - The events that should be listed. + * @param {Function} ctor - The constructor function for the plugin. + */ + obj.registerPlugin = function registerPlugin(pluginName, ctor) { + obj.__plugins[pluginName] = ctor; + }; + + /** + * Instantiates all the plugins of this object + * + */ + obj.prototype.initPlugins = function initPlugins() { + this.plugins = this.plugins || {}; + + for (var o in obj.__plugins) { + this.plugins[o] = new obj.__plugins[o](this); + } + }; + + /** + * Removes all the plugins of this object + * + */ + obj.prototype.destroyPlugins = function destroyPlugins() { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + + this.plugins = null; + }; +} + +exports.default = { + /** + * Mixes in the properties of the pluginTarget into another object + * + * @param {object} obj - The obj to mix into + */ + mixin: function mixin(obj) { + pluginTarget(obj); + } +}; + +},{}],124:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = trimCanvas; +/** + * Trim transparent borders from a canvas + * + * @memberof PIXI + * @function trimCanvas + * @private + * @param {HTMLCanvasElement} canvas - the canvas to trim + * @returns {object} Trim data + */ +function trimCanvas(canvas) { + // https://gist.github.com/remy/784508 + + var width = canvas.width; + var height = canvas.height; + + var context = canvas.getContext('2d'); + var imageData = context.getImageData(0, 0, width, height); + var pixels = imageData.data; + var len = pixels.length; + + var bound = { + top: null, + left: null, + right: null, + bottom: null + }; + var i = void 0; + var x = void 0; + var y = void 0; + + for (i = 0; i < len; i += 4) { + if (pixels[i + 3] !== 0) { + x = i / 4 % width; + y = ~~(i / 4 / width); + + if (bound.top === null) { + bound.top = y; + } + + if (bound.left === null) { + bound.left = x; + } else if (x < bound.left) { + bound.left = x; + } + + if (bound.right === null) { + bound.right = x + 1; + } else if (bound.right < x) { + bound.right = x + 1; + } + + if (bound.bottom === null) { + bound.bottom = y; + } else if (bound.bottom < y) { + bound.bottom = y; + } + } + } + + width = bound.right - bound.left; + height = bound.bottom - bound.top + 1; + + var data = context.getImageData(bound.left, bound.top, width, height); + + return { + height: height, + width: width, + data: data + }; +} + +},{}],125:[function(require,module,exports){ +'use strict'; + +var _core = require('./core'); + +var core = _interopRequireWildcard(_core); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code +function warn(msg) { + /* eslint-disable no-console */ + var stack = new Error().stack; + + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('Deprecation Warning: ', msg); + } else { + // chop off the stack trace which includes pixi.js internal calls + stack = stack.split('\n').splice(3).join('\n'); + + if (console.groupCollapsed) { + console.groupCollapsed('%cDeprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', msg); + console.warn(stack); + console.groupEnd(); + } else { + console.warn('Deprecation Warning: ', msg); + console.warn(stack); + } + } + /* eslint-enable no-console */ +} + +/** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ +core.SpriteBatch = function () { + throw new ReferenceError('SpriteBatch does not exist any more, please use the new ParticleContainer instead.'); +}; + +/** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ +core.AssetLoader = function () { + throw new ReferenceError('The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class.'); +}; + +Object.defineProperties(core, { + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + Stage: { + enumerable: true, + get: function get() { + warn('You do not need to use a PIXI Stage any more, you can simply render any container.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + DisplayObjectContainer: { + enumerable: true, + get: function get() { + warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + Strip: { + enumerable: true, + get: function get() { + warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.'); + + return mesh.Mesh; + } + }, + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + Rope: { + enumerable: true, + get: function get() { + warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.'); + + return mesh.Rope; + } + }, + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + ParticleContainer: { + enumerable: true, + get: function get() { + warn('The ParticleContainer class has been moved to particles.ParticleContainer, ' + 'please use particles.ParticleContainer from now on.'); + + return particles.ParticleContainer; + } + }, + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + MovieClip: { + enumerable: true, + get: function get() { + warn('The MovieClip class has been moved to extras.AnimatedSprite, please use extras.AnimatedSprite.'); + + return extras.AnimatedSprite; + } + }, + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + TilingSprite: { + enumerable: true, + get: function get() { + warn('The TilingSprite class has been moved to extras.TilingSprite, ' + 'please use extras.TilingSprite from now on.'); + + return extras.TilingSprite; + } + }, + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + BitmapText: { + enumerable: true, + get: function get() { + warn('The BitmapText class has been moved to extras.BitmapText, ' + 'please use extras.BitmapText from now on.'); + + return extras.BitmapText; + } + }, + + /** + * @class + * @private + * @name blendModes + * @memberof PIXI + * @see PIXI.BLEND_MODES + * @deprecated since version 3.0.0 + */ + blendModes: { + enumerable: true, + get: function get() { + warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.'); + + return core.BLEND_MODES; + } + }, + + /** + * @class + * @private + * @name scaleModes + * @memberof PIXI + * @see PIXI.SCALE_MODES + * @deprecated since version 3.0.0 + */ + scaleModes: { + enumerable: true, + get: function get() { + warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.'); + + return core.SCALE_MODES; + } + }, + + /** + * @class + * @private + * @name BaseTextureCache + * @memberof PIXI + * @see PIXI.utils.BaseTextureCache + * @deprecated since version 3.0.0 + */ + BaseTextureCache: { + enumerable: true, + get: function get() { + warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, ' + 'please use utils.BaseTextureCache from now on.'); + + return core.utils.BaseTextureCache; + } + }, + + /** + * @class + * @private + * @name TextureCache + * @memberof PIXI + * @see PIXI.utils.TextureCache + * @deprecated since version 3.0.0 + */ + TextureCache: { + enumerable: true, + get: function get() { + warn('The TextureCache class has been moved to utils.TextureCache, ' + 'please use utils.TextureCache from now on.'); + + return core.utils.TextureCache; + } + }, + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + math: { + enumerable: true, + get: function get() { + warn('The math namespace is deprecated, please access members already accessible on PIXI.'); + + return core; + } + }, + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + enumerable: true, + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.Filter; + } + }, + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + TransformManual: { + enumerable: true, + get: function get() { + warn('TransformManual has been renamed to TransformBase, please update your pixi-spine'); + + return core.TransformBase; + } + }, + + /** + * @static + * @constant + * @name PIXI.TARGET_FPMS + * @see PIXI.settings.TARGET_FPMS + * @deprecated since version 4.2.0 + */ + TARGET_FPMS: { + enumerable: true, + get: function get() { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + return core.settings.TARGET_FPMS; + }, + set: function set(value) { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + core.settings.TARGET_FPMS = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.FILTER_RESOLUTION + * @see PIXI.settings.FILTER_RESOLUTION + * @deprecated since version 4.2.0 + */ + FILTER_RESOLUTION: { + enumerable: true, + get: function get() { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + return core.settings.FILTER_RESOLUTION; + }, + set: function set(value) { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + core.settings.FILTER_RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RESOLUTION + * @see PIXI.settings.RESOLUTION + * @deprecated since version 4.2.0 + */ + RESOLUTION: { + enumerable: true, + get: function get() { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + return core.settings.RESOLUTION; + }, + set: function set(value) { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + core.settings.RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.MIPMAP_TEXTURES + * @see PIXI.settings.MIPMAP_TEXTURES + * @deprecated since version 4.2.0 + */ + MIPMAP_TEXTURES: { + enumerable: true, + get: function get() { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + return core.settings.MIPMAP_TEXTURES; + }, + set: function set(value) { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + core.settings.MIPMAP_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_BATCH_SIZE + * @see PIXI.settings.SPRITE_BATCH_SIZE + * @deprecated since version 4.2.0 + */ + SPRITE_BATCH_SIZE: { + enumerable: true, + get: function get() { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + return core.settings.SPRITE_BATCH_SIZE; + }, + set: function set(value) { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + core.settings.SPRITE_BATCH_SIZE = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_MAX_TEXTURES + * @see PIXI.settings.SPRITE_MAX_TEXTURES + * @deprecated since version 4.2.0 + */ + SPRITE_MAX_TEXTURES: { + enumerable: true, + get: function get() { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + return core.settings.SPRITE_MAX_TEXTURES; + }, + set: function set(value) { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + core.settings.SPRITE_MAX_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RETINA_PREFIX + * @see PIXI.settings.RETINA_PREFIX + * @deprecated since version 4.2.0 + */ + RETINA_PREFIX: { + enumerable: true, + get: function get() { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + return core.settings.RETINA_PREFIX; + }, + set: function set(value) { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + core.settings.RETINA_PREFIX = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.DEFAULT_RENDER_OPTIONS + * @see PIXI.settings.RENDER_OPTIONS + * @deprecated since version 4.2.0 + */ + DEFAULT_RENDER_OPTIONS: { + enumerable: true, + get: function get() { + warn('PIXI.DEFAULT_RENDER_OPTIONS has been deprecated, please use PIXI.settings.DEFAULT_RENDER_OPTIONS'); + + return core.settings.RENDER_OPTIONS; + } + } +}); + +// Move the default properties to settings +var defaults = [{ parent: 'TRANSFORM_MODE', target: 'TRANSFORM_MODE' }, { parent: 'GC_MODES', target: 'GC_MODE' }, { parent: 'WRAP_MODES', target: 'WRAP_MODE' }, { parent: 'SCALE_MODES', target: 'SCALE_MODE' }, { parent: 'PRECISION', target: 'PRECISION_FRAGMENT' }]; + +var _loop = function _loop(i) { + var deprecation = defaults[i]; + + Object.defineProperty(core[deprecation.parent], 'DEFAULT', { + enumerable: true, + get: function get() { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, please use PIXI.settings.' + deprecation.target); + + return core.settings[deprecation.target]; + }, + set: function set(value) { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, please use PIXI.settings.' + deprecation.target); + + core.settings[deprecation.target] = value; + } + }); +}; + +for (var i = 0; i < defaults.length; i++) { + _loop(i); +} + +Object.defineProperties(core.settings, { + + /** + * @static + * @name PRECISION + * @memberof PIXI.settings + * @see PIXI.PRECISION + * @deprecated since version 4.4.0 + */ + PRECISION: { + enumerable: true, + get: function get() { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + return core.settings.PRECISION_FRAGMENT; + }, + set: function set(value) { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + core.settings.PRECISION_FRAGMENT = value; + } + } +}); + +Object.defineProperties(extras, { + + /** + * @class + * @name MovieClip + * @memberof PIXI.extras + * @see PIXI.extras.AnimatedSprite + * @deprecated since version 4.2.0 + */ + MovieClip: { + enumerable: true, + get: function get() { + warn('The MovieClip class has been renamed to AnimatedSprite, please use AnimatedSprite from now on.'); + + return extras.AnimatedSprite; + } + } +}); + +core.DisplayObject.prototype.generateTexture = function generateTexture(renderer, scaleMode, resolution) { + warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); + + return renderer.generateTexture(this, scaleMode, resolution); +}; + +core.Graphics.prototype.generateTexture = function generateTexture(scaleMode, resolution) { + warn('graphics generate texture has moved to the renderer. ' + 'Or to render a graphics to a texture using canvas please use generateCanvasTexture'); + + return this.generateCanvasTexture(scaleMode, resolution); +}; + +core.RenderTexture.prototype.render = function render(displayObject, matrix, clear, updateTransform) { + this.legacyRenderer.render(displayObject, this, clear, matrix, !updateTransform); + warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)'); +}; + +core.RenderTexture.prototype.getImage = function getImage(target) { + warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); + + return this.legacyRenderer.extract.image(target); +}; + +core.RenderTexture.prototype.getBase64 = function getBase64(target) { + warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); + + return this.legacyRenderer.extract.base64(target); +}; + +core.RenderTexture.prototype.getCanvas = function getCanvas(target) { + warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); + + return this.legacyRenderer.extract.canvas(target); +}; + +core.RenderTexture.prototype.getPixels = function getPixels(target) { + warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); + + return this.legacyRenderer.pixels(target); +}; + +/** + * @method + * @private + * @name PIXI.Sprite#setTexture + * @see PIXI.Sprite#texture + * @deprecated since version 3.0.0 + * @param {PIXI.Texture} texture - The texture to set to. + */ +core.Sprite.prototype.setTexture = function setTexture(texture) { + this.texture = texture; + warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;'); +}; + +/** + * @method + * @name PIXI.extras.BitmapText#setText + * @see PIXI.extras.BitmapText#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ +extras.BitmapText.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';'); +}; + +/** + * @method + * @name PIXI.Text#setText + * @see PIXI.Text#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ +core.Text.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';'); +}; + +/** + * @method + * @name PIXI.Text#setStyle + * @see PIXI.Text#style + * @deprecated since version 3.0.0 + * @param {*} style - The style to set to. + */ +core.Text.prototype.setStyle = function setStyle(style) { + this.style = style; + warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;'); +}; + +/** + * @method + * @name PIXI.Text#determineFontProperties + * @see PIXI.Text#calculateFontProperties + * @deprecated since version 4.2.0 + * @private + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ +core.Text.prototype.determineFontProperties = function determineFontProperties(fontStyle) { + warn('determineFontProperties is now deprecated, please use the static calculateFontProperties method, ' + 'e.g : Text.calculateFontProperties(fontStyle);'); + + return core.Text.calculateFontProperties(fontStyle); +}; + +Object.defineProperties(core.TextStyle.prototype, { + /** + * Set all properties of a font as a single string + * + * @name PIXI.TextStyle#font + * @deprecated since version 4.0.0 + */ + font: { + get: function get() { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\', \'fontSize\', \'fontStyle\', \'fontVariant\' and \'fontWeight\' properties from now on'); + + var fontSizeString = typeof this._fontSize === 'number' ? this._fontSize + 'px' : this._fontSize; + + return this._fontStyle + ' ' + this._fontVariant + ' ' + this._fontWeight + ' ' + fontSizeString + ' ' + this._fontFamily; + }, + set: function set(font) { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + + // can work out fontStyle from search of whole string + if (font.indexOf('italic') > 1) { + this._fontStyle = 'italic'; + } else if (font.indexOf('oblique') > -1) { + this._fontStyle = 'oblique'; + } else { + this._fontStyle = 'normal'; + } + + // can work out fontVariant from search of whole string + if (font.indexOf('small-caps') > -1) { + this._fontVariant = 'small-caps'; + } else { + this._fontVariant = 'normal'; + } + + // fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units + var splits = font.split(' '); + var fontSizeIndex = -1; + + this._fontSize = 26; + for (var i = 0; i < splits.length; ++i) { + if (splits[i].match(/(px|pt|em|%)/)) { + fontSizeIndex = i; + this._fontSize = splits[i]; + break; + } + } + + // we can now search for fontWeight as we know it must occur before the fontSize + this._fontWeight = 'normal'; + for (var _i = 0; _i < fontSizeIndex; ++_i) { + if (splits[_i].match(/(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/)) { + this._fontWeight = splits[_i]; + break; + } + } + + // and finally join everything together after the fontSize in case the font family has multiple words + if (fontSizeIndex > -1 && fontSizeIndex < splits.length - 1) { + this._fontFamily = ''; + for (var _i2 = fontSizeIndex + 1; _i2 < splits.length; ++_i2) { + this._fontFamily += splits[_i2] + ' '; + } + + this._fontFamily = this._fontFamily.slice(0, -1); + } else { + this._fontFamily = 'Arial'; + } + + this.styleID++; + } + } +}); + +/** + * @method + * @name PIXI.Texture#setFrame + * @see PIXI.Texture#setFrame + * @deprecated since version 3.0.0 + * @param {PIXI.Rectangle} frame - The frame to set. + */ +core.Texture.prototype.setFrame = function setFrame(frame) { + this.frame = frame; + warn('setFrame is now deprecated, please use the frame property, e.g: myTexture.frame = frame;'); +}; + +Object.defineProperties(filters, { + + /** + * @class + * @private + * @name PIXI.filters.AbstractFilter + * @see PIXI.AbstractFilter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.AbstractFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.SpriteMaskFilter + * @see PIXI.SpriteMaskFilter + * @deprecated since version 3.0.6 + */ + SpriteMaskFilter: { + get: function get() { + warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.'); + + return core.SpriteMaskFilter; + } + } +}); + +/** + * @method + * @name PIXI.utils.uuid + * @see PIXI.utils.uid + * @deprecated since version 3.0.6 + * @return {number} The uid + */ +core.utils.uuid = function () { + warn('utils.uuid() is deprecated, please use utils.uid() from now on.'); + + return core.utils.uid(); +}; + +/** + * @method + * @name PIXI.utils.canUseNewCanvasBlendModes + * @see PIXI.CanvasTinter + * @deprecated + * @return {boolean} Can use blend modes. + */ +core.utils.canUseNewCanvasBlendModes = function () { + warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on'); + + return core.CanvasTinter.canUseMultiply; +}; + +var saidHello = true; + +/** + * @name PIXI.utils._saidHello + * @type {boolean} + * @see PIXI.utils.skipHello + * @deprecated since 4.1.0 + */ +Object.defineProperty(core.utils, '_saidHello', { + set: function set(bool) { + if (bool) { + warn('PIXI.utils._saidHello is deprecated, please use PIXI.utils.skipHello()'); + this.skipHello(); + } + saidHello = bool; + }, + get: function get() { + return saidHello; + } +}); + +/** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.canvas.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ +Object.defineProperty(prepare.canvas, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } +}); + +/** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.webgl.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ +Object.defineProperty(prepare.webgl, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } +}); + +Object.defineProperties(loaders.Resource.prototype, { + isJson: { + get: function get() { + warn('The isJson property is deprecated, please use `resource.type === Resource.TYPE.JSON`.'); + + return this.type === loaders.Loader.Resource.TYPE.JSON; + } + }, + isXml: { + get: function get() { + warn('The isXml property is deprecated, please use `resource.type === Resource.TYPE.XML`.'); + + return this.type === loaders.Loader.Resource.TYPE.XML; + } + }, + isImage: { + get: function get() { + warn('The isImage property is deprecated, please use `resource.type === Resource.TYPE.IMAGE`.'); + + return this.type === loaders.Loader.Resource.TYPE.IMAGE; + } + }, + isAudio: { + get: function get() { + warn('The isAudio property is deprecated, please use `resource.type === Resource.TYPE.AUDIO`.'); + + return this.type === loaders.Loader.Resource.TYPE.AUDIO; + } + }, + isVideo: { + get: function get() { + warn('The isVideo property is deprecated, please use `resource.type === Resource.TYPE.VIDEO`.'); + + return this.type === loaders.Loader.Resource.TYPE.VIDEO; + } + } +}); + +Object.defineProperties(loaders.Loader.prototype, { + before: { + get: function get() { + warn('The before() method is deprecated, please use pre().'); + + return this.pre; + } + }, + after: { + get: function get() { + warn('The after() method is deprecated, please use use().'); + + return this.use; + } + } +}); + +/** + * @name PIXI.interaction.interactiveTarget#defaultCursor + * @static + * @type {number} + * @see PIXI.interaction.interactiveTarget#cursor + * @deprecated since 4.3.0 + */ +Object.defineProperty(interaction.interactiveTarget, 'defaultCursor', { + set: function set(value) { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + this.cursor = value; + }, + get: function get() { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + + return this.cursor; + }, + + enumerable: true +}); + +/** + * @name PIXI.interaction.InteractionManager#defaultCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ +Object.defineProperty(interaction.InteractionManager, 'defaultCursorStyle', { + set: function set(value) { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + this.cursorStyles.default = value; + }, + get: function get() { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + + return this.cursorStyles.default; + } +}); + +/** + * @name PIXI.interaction.InteractionManager#currentCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ +Object.defineProperty(interaction.InteractionManager, 'currentCursorStyle', { + set: function set(value) { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + this.currentCursorMode = value; + }, + get: function get() { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + + return this.currentCursorMode; + } +}); + +},{"./core":63,"./extras":136,"./filters":147,"./interaction":154,"./loaders":157,"./mesh":166,"./particles":169,"./prepare":179}],126:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI + */ + +var CanvasExtract = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasExtract(renderer) { + _classCallCheck(this, CanvasExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.CanvasExtract} extract + * @memberof PIXI.CanvasRenderer# + * @see PIXI.CanvasExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + CanvasExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `CanvasExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + CanvasExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + CanvasExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = this.renderer.width; + frame.height = this.renderer.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + CanvasExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + + return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; + }; + + /** + * Destroys the extract + * + */ + + + CanvasExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return CanvasExtract; +}(); + +exports.default = CanvasExtract; + + +core.CanvasRenderer.registerPlugin('extract', CanvasExtract); + +},{"../../core":63}],127:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLExtract = require('./webgl/WebGLExtract'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLExtract).default; + } +}); + +var _CanvasExtract = require('./canvas/CanvasExtract'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasExtract).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./canvas/CanvasExtract":126,"./webgl/WebGLExtract":128}],128:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); +var BYTES_PER_PIXEL = 4; + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI + */ + +var WebGLExtract = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLExtract(renderer) { + _classCallCheck(this, WebGLExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.WebGLExtract} extract + * @memberof PIXI.WebGLRenderer# + * @see PIXI.WebGLExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + WebGLExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `WebGLExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + WebGLExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + WebGLExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var flipY = false; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + flipY = false; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + flipY = true; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + + // set up an array of pixels + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + + canvasData.data.set(webglPixels); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // pulling pixels + if (flipY) { + canvasBuffer.context.scale(1, -1); + canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); + } + } + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + WebGLExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + } + + return webglPixels; + }; + + /** + * Destroys the extract + * + */ + + + WebGLExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return WebGLExtract; +}(); + +exports.default = WebGLExtract; + + +core.WebGLRenderer.registerPlugin('extract', WebGLExtract); + +},{"../../core":63}],129:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @typedef FrameObject + * @type {object} + * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame + * @property {number} time - the duration of the frame in ms + */ + +/** + * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. + * + * ```js + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; + * + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.fromImage(alienImages[i]); + * textureArray.push(texture); + * }; + * + * let mc = new PIXI.AnimatedSprite(textureArray); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ +var AnimatedSprite = function (_core$Sprite) { + _inherits(AnimatedSprite, _core$Sprite); + + /** + * @param {PIXI.Texture[]|FrameObject[]} textures - an array of {@link PIXI.Texture} or frame + * objects that make up the animation + * @param {boolean} [autoUpdate=true] - Whether use PIXI.ticker.shared to auto update animation time. + */ + function AnimatedSprite(textures, autoUpdate) { + _classCallCheck(this, AnimatedSprite); + + /** + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture)); + + _this._textures = null; + + /** + * @private + */ + _this._durations = null; + + _this.textures = textures; + + /** + * `true` uses PIXI.ticker.shared to auto update animation time. + * @type {boolean} + * @default true + * @private + */ + _this._autoUpdate = autoUpdate !== false; + + /** + * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower + * + * @member {number} + * @default 1 + */ + _this.animationSpeed = 1; + + /** + * Whether or not the animate sprite repeats after playing. + * + * @member {boolean} + * @default true + */ + _this.loop = true; + + /** + * Function to call when a AnimatedSprite finishes playing + * + * @member {Function} + */ + _this.onComplete = null; + + /** + * Function to call when a AnimatedSprite changes which texture is being rendered + * + * @member {Function} + */ + _this.onFrameChange = null; + + /** + * Elapsed time since animation has been started, used internally to display current texture + * + * @member {number} + * @private + */ + _this._currentTime = 0; + + /** + * Indicates if the AnimatedSprite is currently playing + * + * @member {boolean} + * @readonly + */ + _this.playing = false; + return _this; + } + + /** + * Stops the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.stop = function stop() { + if (!this.playing) { + return; + } + + this.playing = false; + if (this._autoUpdate) { + core.ticker.shared.remove(this.update, this); + } + }; + + /** + * Plays the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.play = function play() { + if (this.playing) { + return; + } + + this.playing = true; + if (this._autoUpdate) { + core.ticker.shared.add(this.update, this); + } + }; + + /** + * Stops the AnimatedSprite and goes to a specific frame + * + * @param {number} frameNumber - frame index to stop at + */ + + + AnimatedSprite.prototype.gotoAndStop = function gotoAndStop(frameNumber) { + this.stop(); + + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + + /** + * Goes to a specific frame and begins playing the AnimatedSprite + * + * @param {number} frameNumber - frame index to start at + */ + + + AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay(frameNumber) { + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + + this.play(); + }; + + /** + * Updates the object transform for rendering. + * + * @private + * @param {number} deltaTime - Time since last tick. + */ + + + AnimatedSprite.prototype.update = function update(deltaTime) { + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + + lag += elapsed / 60 * 1000; + + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + + var sign = Math.sign(this.animationSpeed * deltaTime); + + this._currentTime = Math.floor(this._currentTime); + + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + + this._currentTime += lag / this._durations[this.currentFrame]; + } else { + this._currentTime += elapsed; + } + + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + + if (this.onComplete) { + this.onComplete(); + } + } else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + + if (this.onComplete) { + this.onComplete(); + } + } else if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + + /** + * Updates the displayed texture to match the current frame index + * + * @private + */ + + + AnimatedSprite.prototype.updateTexture = function updateTexture() { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + }; + + /** + * Stops the AnimatedSprite and destroys it + * + */ + + + AnimatedSprite.prototype.destroy = function destroy() { + this.stop(); + _core$Sprite.prototype.destroy.call(this); + }; + + /** + * A short hand way of creating a movieclip from an array of frame ids + * + * @static + * @param {string[]} frames - The array of frames ids the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animated sprite with the specified frames. + */ + + + AnimatedSprite.fromFrames = function fromFrames(frames) { + var textures = []; + + for (var i = 0; i < frames.length; ++i) { + textures.push(core.Texture.fromFrame(frames[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * A short hand way of creating a movieclip from an array of image ids + * + * @static + * @param {string[]} images - the array of image urls the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animate sprite with the specified images as frames. + */ + + + AnimatedSprite.fromImages = function fromImages(images) { + var textures = []; + + for (var i = 0; i < images.length; ++i) { + textures.push(core.Texture.fromImage(images[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * totalFrames is the total number of frames in the AnimatedSprite. This is the same as number of textures + * assigned to the AnimatedSprite. + * + * @readonly + * @member {number} + * @default 0 + */ + + + _createClass(AnimatedSprite, [{ + key: 'totalFrames', + get: function get() { + return this._textures.length; + } + + /** + * The array of textures used for this AnimatedSprite + * + * @member {PIXI.Texture[]} + */ + + }, { + key: 'textures', + get: function get() { + return this._textures; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value[0] instanceof core.Texture) { + this._textures = value; + this._durations = null; + } else { + this._textures = []; + this._durations = []; + + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + } + + /** + * The AnimatedSprites current frame index + * + * @member {number} + * @readonly + */ + + }, { + key: 'currentFrame', + get: function get() { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + + return currentFrame; + } + }]); + + return AnimatedSprite; +}(core.Sprite); + +exports.default = AnimatedSprite; + +},{"../core":63}],130:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ObservablePoint = require('../core/math/ObservablePoint'); + +var _ObservablePoint2 = _interopRequireDefault(_ObservablePoint); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BitmapText object will create a line or multiple lines of text using bitmap font. To + * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using: + * + * A BitmapText can only be created when the font is loaded + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); + * ``` + * + * http://www.angelcode.com/products/bmfont/ for windows or + * http://www.bmglyph.com/ for mac. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.extras + */ +var BitmapText = function (_core$Container) { + _inherits(BitmapText, _core$Container); + + /** + * @param {string} text - The copy that you would like the text to display + * @param {object} style - The style parameters + * @param {string|object} style.font - The font descriptor for the object, can be passed as a string of form + * "24px FontName" or "FontName" or as an object with explicit name/size properties. + * @param {string} [style.font.name] - The bitmap font id + * @param {number} [style.font.size] - The size of the font in pixels, e.g. 24 + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), does not affect + * single line text + * @param {number} [style.tint=0xFFFFFF] - The tint color + */ + function BitmapText(text) { + var style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _classCallCheck(this, BitmapText); + + /** + * Private tracker for the width of the overall text + * + * @member {number} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._textWidth = 0; + + /** + * Private tracker for the height of the overall text + * + * @member {number} + * @private + */ + _this._textHeight = 0; + + /** + * Private tracker for the letter sprite pool. + * + * @member {PIXI.Sprite[]} + * @private + */ + _this._glyphs = []; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._font = { + tint: style.tint !== undefined ? style.tint : 0xFFFFFF, + align: style.align || 'left', + name: null, + size: 0 + }; + + /** + * Private tracker for the current font. + * + * @member {object} + * @private + */ + _this.font = style.font; // run font setter + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = text; + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + */ + _this.maxWidth = 0; + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + */ + _this.maxLineHeight = 0; + + /** + * Text anchor. read-only + * + * @member {PIXI.ObservablePoint} + * @private + */ + _this._anchor = new _ObservablePoint2.default(function () { + _this.dirty = true; + }, _this, 0, 0); + + /** + * The dirty state of this object. + * + * @member {boolean} + */ + _this.dirty = false; + + _this.updateText(); + return _this; + } + + /** + * Renders text and updates it when needed + * + * @private + */ + + + BitmapText.prototype.updateText = function updateText() { + var data = BitmapText.fonts[this._font.name]; + var scale = this._font.size / data.size; + var pos = new core.Point(); + var chars = []; + var lineWidths = []; + + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastSpace = -1; + var lastSpaceWidth = 0; + var maxLineHeight = 0; + + for (var i = 0; i < this.text.length; i++) { + var charCode = this.text.charCodeAt(i); + + if (/(\s)/.test(this.text.charAt(i))) { + lastSpace = i; + lastSpaceWidth = lastLineWidth; + } + + if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) { + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + if (lastSpace !== -1 && this.maxWidth > 0 && pos.x * scale > this.maxWidth) { + core.utils.removeItems(chars, lastSpace, i - lastSpace); + i = lastSpace; + lastSpace = -1; + + lineWidths.push(lastSpaceWidth); + maxLineWidth = Math.max(maxLineWidth, lastSpaceWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + var charData = data.chars[charCode]; + + if (!charData) { + continue; + } + + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + + chars.push({ + texture: charData.texture, + line: line, + charCode: charCode, + position: new core.Point(pos.x + charData.xOffset, pos.y + charData.yOffset) + }); + lastLineWidth = pos.x + (charData.texture.width + charData.xOffset); + pos.x += charData.xAdvance; + maxLineHeight = Math.max(maxLineHeight, charData.yOffset + charData.texture.height); + prevCharCode = charCode; + } + + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + + var lineAlignOffsets = []; + + for (var _i = 0; _i <= line; _i++) { + var alignOffset = 0; + + if (this._font.align === 'right') { + alignOffset = maxLineWidth - lineWidths[_i]; + } else if (this._font.align === 'center') { + alignOffset = (maxLineWidth - lineWidths[_i]) / 2; + } + + lineAlignOffsets.push(alignOffset); + } + + var lenChars = chars.length; + var tint = this.tint; + + for (var _i2 = 0; _i2 < lenChars; _i2++) { + var c = this._glyphs[_i2]; // get the next glyph sprite + + if (c) { + c.texture = chars[_i2].texture; + } else { + c = new core.Sprite(chars[_i2].texture); + this._glyphs.push(c); + } + + c.position.x = (chars[_i2].position.x + lineAlignOffsets[chars[_i2].line]) * scale; + c.position.y = chars[_i2].position.y * scale; + c.scale.x = c.scale.y = scale; + c.tint = tint; + + if (!c.parent) { + this.addChild(c); + } + } + + // remove unnecessary children. + for (var _i3 = lenChars; _i3 < this._glyphs.length; ++_i3) { + this.removeChild(this._glyphs[_i3]); + } + + this._textWidth = maxLineWidth * scale; + this._textHeight = (pos.y + data.lineHeight) * scale; + + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + for (var _i4 = 0; _i4 < lenChars; _i4++) { + this._glyphs[_i4].x -= this._textWidth * this.anchor.x; + this._glyphs[_i4].y -= this._textHeight * this.anchor.y; + } + } + this.maxLineHeight = maxLineHeight * scale; + }; + + /** + * Updates the transform of this object + * + * @private + */ + + + BitmapText.prototype.updateTransform = function updateTransform() { + this.validate(); + this.containerUpdateTransform(); + }; + + /** + * Validates text before calling parent's getLocalBounds + * + * @return {PIXI.Rectangle} The rectangular bounding area + */ + + + BitmapText.prototype.getLocalBounds = function getLocalBounds() { + this.validate(); + + return _core$Container.prototype.getLocalBounds.call(this); + }; + + /** + * Updates text when needed + * + * @private + */ + + + BitmapText.prototype.validate = function validate() { + if (this.dirty) { + this.updateText(); + this.dirty = false; + } + }; + + /** + * The tint of the BitmapText object + * + * @member {number} + */ + + + /** + * Register a bitmap font with data and a texture. + * + * @static + * @param {XMLDocument} xml - The XML document data. + * @param {PIXI.Texture} texture - Texture with all symbols. + * @return {Object} Result font object with font, size, lineHeight and char fields. + */ + BitmapText.registerFont = function registerFont(xml, texture) { + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10); + data.chars = {}; + + // parse letters + var letters = xml.getElementsByTagName('char'); + + for (var i = 0; i < letters.length; i++) { + var letter = letters[i]; + var charCode = parseInt(letter.getAttribute('id'), 10); + + var textureRect = new core.Rectangle(parseInt(letter.getAttribute('x'), 10) + texture.frame.x, parseInt(letter.getAttribute('y'), 10) + texture.frame.y, parseInt(letter.getAttribute('width'), 10), parseInt(letter.getAttribute('height'), 10)); + + data.chars[charCode] = { + xOffset: parseInt(letter.getAttribute('xoffset'), 10), + yOffset: parseInt(letter.getAttribute('yoffset'), 10), + xAdvance: parseInt(letter.getAttribute('xadvance'), 10), + kerning: {}, + texture: new core.Texture(texture.baseTexture, textureRect) + + }; + } + + // parse kernings + var kernings = xml.getElementsByTagName('kerning'); + + for (var _i5 = 0; _i5 < kernings.length; _i5++) { + var kerning = kernings[_i5]; + var first = parseInt(kerning.getAttribute('first'), 10); + var second = parseInt(kerning.getAttribute('second'), 10); + var amount = parseInt(kerning.getAttribute('amount'), 10); + + if (data.chars[second]) { + data.chars[second].kerning[first] = amount; + } + } + + // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 + // but it's very likely to change + BitmapText.fonts[data.font] = data; + + return data; + }; + + _createClass(BitmapText, [{ + key: 'tint', + get: function get() { + return this._font.tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.tint = typeof value === 'number' && value >= 0 ? value : 0xFFFFFF; + + this.dirty = true; + } + + /** + * The alignment of the BitmapText object + * + * @member {string} + * @default 'left' + */ + + }, { + key: 'align', + get: function get() { + return this._font.align; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.align = value || 'left'; + + this.dirty = true; + } + + /** + * The anchor sets the origin point of the text. + * The default is 0,0 this means the text's origin is the top left + * Setting the anchor to 0.5,0.5 means the text's origin is centered + * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner + * + * @member {PIXI.Point | number} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (typeof value === 'number') { + this._anchor.set(value); + } else { + this._anchor.copy(value); + } + } + + /** + * The font descriptor of the BitmapText object + * + * @member {string|object} + */ + + }, { + key: 'font', + get: function get() { + return this._font; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (!value) { + return; + } + + if (typeof value === 'string') { + value = value.split(' '); + + this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); + this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; + } else { + this._font.name = value.name; + this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); + } + + this.dirty = true; + } + + /** + * The text of the BitmapText object + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + value = value.toString() || ' '; + if (this._text === value) { + return; + } + this._text = value; + this.dirty = true; + } + + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textWidth', + get: function get() { + this.validate(); + + return this._textWidth; + } + + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textHeight', + get: function get() { + this.validate(); + + return this._textHeight; + } + }]); + + return BitmapText; +}(core.Container); + +exports.default = BitmapText; + + +BitmapText.fonts = {}; + +},{"../core":63,"../core/math/ObservablePoint":66}],131:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Matrix = require('../core/math/Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var tempMat = new _Matrix2.default(); + +/** + * class controls uv transform and frame clamp for texture + * + * @class + * @memberof PIXI.extras + */ + +var TextureTransform = function () { + /** + * + * @param {PIXI.Texture} texture observed texture + * @param {number} [clampMargin] Changes frame clamping, 0.5 by default. Use -0.5 for extra border. + * @constructor + */ + function TextureTransform(texture, clampMargin) { + _classCallCheck(this, TextureTransform); + + this._texture = texture; + + this.mapCoord = new _Matrix2.default(); + + this.uClampFrame = new Float32Array(4); + + this.uClampOffset = new Float32Array(2); + + this._lastTextureID = -1; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders + * + * @default 0 + * @member {number} + */ + this.clampOffset = 0; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + this.clampMargin = typeof clampMargin === 'undefined' ? 0.5 : clampMargin; + } + + /** + * texture property + * @member {PIXI.Texture} + */ + + + /** + * updates matrices if texture was changed + * @param {boolean} forceUpdate if true, matrices will be updated any case + */ + TextureTransform.prototype.update = function update(forceUpdate) { + var tex = this._texture; + + if (!tex || !tex.valid) { + return; + } + + if (!forceUpdate && this._lastTextureID === tex._updateID) { + return; + } + + this._lastTextureID = tex._updateID; + + var uvs = tex._uvs; + + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + + var orig = tex.orig; + var trim = tex.trim; + + if (trim) { + tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat); + } + + var texBase = tex.baseTexture; + var frame = this.uClampFrame; + var margin = this.clampMargin / texBase.resolution; + var offset = this.clampOffset; + + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.uClampOffset[0] = offset / texBase.realWidth; + this.uClampOffset[1] = offset / texBase.realHeight; + }; + + _createClass(TextureTransform, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._texture = value; + this._lastTextureID = -1; + } + }]); + + return TextureTransform; +}(); + +exports.default = TextureTransform; + +},{"../core/math/Matrix":65}],132:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CanvasTinter = require('../core/sprites/canvas/CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +var _TextureTransform = require('./TextureTransform'); + +var _TextureTransform2 = _interopRequireDefault(_TextureTransform); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); + +/** + * A tiling sprite is a fast way of rendering a tiling image + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ + +var TilingSprite = function (_core$Sprite) { + _inherits(TilingSprite, _core$Sprite); + + /** + * @param {PIXI.Texture} texture - the texture of the tiling sprite + * @param {number} [width=100] - the width of the tiling sprite + * @param {number} [height=100] - the height of the tiling sprite + */ + function TilingSprite(texture) { + var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100; + + _classCallCheck(this, TilingSprite); + + /** + * Tile transform + * + * @member {PIXI.TransformStatic} + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, texture)); + + _this.tileTransform = new core.TransformStatic(); + + // /// private + + /** + * The with of the tiling sprite + * + * @member {number} + * @private + */ + _this._width = width; + + /** + * The height of the tiling sprite + * + * @member {number} + * @private + */ + _this._height = height; + + /** + * Canvas pattern + * + * @type {CanvasPattern} + * @private + */ + _this._canvasPattern = null; + + /** + * transform that is applied to UV to get the texture coords + * + * @member {PIXI.extras.TextureTransform} + */ + _this.uvTransform = texture.transform || new _TextureTransform2.default(texture); + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' method. + * + * @member {string} + * @default 'tilingSprite' + */ + _this.pluginName = 'tilingSprite'; + + /** + * Whether or not anchor affects uvs + * + * @member {boolean} + * @default false + */ + _this.uvRespectAnchor = false; + return _this; + } + /** + * Changes frame clamping in corresponding textureTransform, shortcut + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + + + /** + * @private + */ + TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate() { + if (this.uvTransform) { + this.uvTransform.texture = this._texture; + } + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + TilingSprite.prototype._renderWebGL = function _renderWebGL(renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + + if (!texture || !texture.valid) { + return; + } + + this.tileTransform.updateLocalTransform(); + this.uvTransform.update(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer + */ + + + TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { + var texture = this._texture; + + if (!texture.baseTexture.hasLoaded) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var resolution = renderer.resolution; + var baseTexture = texture.baseTexture; + var baseTextureResolution = texture.baseTexture.resolution; + var modX = this.tilePosition.x / this.tileScale.x % texture._frame.width; + var modY = this.tilePosition.y / this.tileScale.y % texture._frame.height; + + // create a nice shiny pattern! + // TODO this needs to be refreshed if texture changes.. + if (!this._canvasPattern) { + // cut an object from a spritesheet.. + var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height, baseTextureResolution); + + // Tint the tiling sprite + if (this.tint !== 0xFFFFFF) { + if (this.cachedTint !== this.tint) { + this.cachedTint = this.tint; + + this.tintedTexture = _CanvasTinter2.default.getTintedTexture(this, this.tint); + } + tempCanvas.context.drawImage(this.tintedTexture, 0, 0); + } else { + tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x, -texture._frame.y); + } + this._canvasPattern = tempCanvas.context.createPattern(tempCanvas.canvas, 'repeat'); + } + + // set context state.. + context.globalAlpha = this.worldAlpha; + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + renderer.setBlendMode(this.blendMode); + + // fill the pattern! + context.fillStyle = this._canvasPattern; + + // TODO - this should be rolled into the setTransform above.. + context.scale(this.tileScale.x / baseTextureResolution, this.tileScale.y / baseTextureResolution); + + var anchorX = this.anchor.x * -this._width; + var anchorY = this.anchor.y * -this._height; + + if (this.uvRespectAnchor) { + context.translate(modX, modY); + + context.fillRect(-modX + anchorX, -modY + anchorY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } else { + context.translate(modX + anchorX, modY + anchorY); + + context.fillRect(-modX, -modY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } + }; + + /** + * Updates the bounds of the tiling sprite. + * + * @private + */ + + + TilingSprite.prototype._calculateBounds = function _calculateBounds() { + var minX = this._width * -this._anchor._x; + var minY = this._height * -this._anchor._y; + var maxX = this._width * (1 - this._anchor._x); + var maxY = this._height * (1 - this._anchor._y); + + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + TilingSprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._width * -this._anchor._x; + this._bounds.minY = this._height * -this._anchor._y; + this._bounds.maxX = this._width * (1 - this._anchor._x); + this._bounds.maxY = this._height * (1 - this._anchor._x); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new core.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _core$Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Checks if a point is inside this tiling sprite. + * + * @param {PIXI.Point} point - the point to check + * @return {boolean} Whether or not the sprite contains the point. + */ + + + TilingSprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor._x; + + if (tempPoint.x > x1 && tempPoint.x < x1 + width) { + var y1 = -height * this.anchor._y; + + if (tempPoint.y > y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this tiling sprite + * + */ + + + TilingSprite.prototype.destroy = function destroy() { + _core$Sprite.prototype.destroy.call(this); + + this.tileTransform = null; + this.uvTransform = null; + }; + + /** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.Texture} The newly created texture + */ + + + TilingSprite.from = function from(source, width, height) { + return new TilingSprite(core.Texture.from(source), width, height); + }; + + /** + * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId + */ + + + TilingSprite.fromFrame = function fromFrame(frameId, width, height) { + var texture = core.utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this); + } + + return new TilingSprite(texture, width, height); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @param {boolean} [crossorigin] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id + */ + + + TilingSprite.fromImage = function fromImage(imageId, width, height, crossorigin, scaleMode) { + return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode), width, height); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(TilingSprite, [{ + key: 'clampMargin', + get: function get() { + return this.uvTransform.clampMargin; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uvTransform.clampMargin = value; + this.uvTransform.update(true); + } + + /** + * The scaling of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tileScale', + get: function get() { + return this.tileTransform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.scale.copy(value); + } + + /** + * The offset of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tilePosition', + get: function get() { + return this.tileTransform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.position.copy(value); + } + }, { + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + } + + /** + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + } + }]); + + return TilingSprite; +}(core.Sprite); + +exports.default = TilingSprite; + +},{"../core":63,"../core/sprites/canvas/CanvasTinter":102,"./TextureTransform":131}],133:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DisplayObject = core.DisplayObject; +var _tempMatrix = new core.Matrix(); + +DisplayObject.prototype._cacheAsBitmap = false; +DisplayObject.prototype._cacheData = false; + +// figured theres no point adding ALL the extra variables to prototype. +// this model can hold the information needed. This can also be generated on demand as +// most objects are not cached as bitmaps. +/** + * @class + * @ignore + */ + +var CacheData = +/** + * + */ +function CacheData() { + _classCallCheck(this, CacheData); + + this.originalRenderWebGL = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + + this.originalUpdateTransform = null; + this.originalHitTest = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.sprite = null; +}; + +Object.defineProperties(DisplayObject.prototype, { + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to 'false' + * + * IMPORTANT GOTCHA - make sure that all your textures are preloaded BEFORE setting this property to true + * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function get() { + return this._cacheAsBitmap; + }, + set: function set(value) { + if (this._cacheAsBitmap === value) { + return; + } + + this._cacheAsBitmap = value; + + var data = void 0; + + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + + data = this._cacheData; + + data.originalRenderWebGL = this.renderWebGL; + data.originalRenderCanvas = this.renderCanvas; + + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this._calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + + data.originalDestroy = this.destroy; + + data.originalContainsPoint = this.containsPoint; + + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + + this.renderWebGL = this._renderCachedWebGL; + this.renderCanvas = this._renderCachedCanvas; + + this.destroy = this._cacheAsBitmapDestroy; + } else { + data = this._cacheData; + + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + + this.renderWebGL = data.originalRenderWebGL; + this.renderCanvas = data.originalRenderCanvas; + this._calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + + this.destroy = data.originalDestroy; + + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + } + } +}); + +/** + * Renders a cached version of the sprite with WebGL + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedWebGL = function _renderCachedWebGL(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObject(renderer); + + this._cacheData.sprite._transformID = -1; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderWebGL(renderer); +}; + +/** + * Prepares the WebGL renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + + this.alpha = 1; + + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.currentRenderer.flush(); + // this.filters= []; + + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds().clone(); + + // add some padding! + if (this._filters) { + var padding = this._filters[0].padding; + + bounds.pad(padding); + } + + // for now we cache the current renderTarget that the webGL renderer is currently using. + // this could be more elegent.. + var cachedRenderTarget = renderer._activeRenderTarget; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + var stack = renderer.filterManager.filterStack; + + // this renderTexture will be used to store the cached DisplayObject + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + // need to set // + var m = _tempMatrix; + + m.tx = -bounds.x; + m.ty = -bounds.y; + + // reset + this.transform.worldTransform.identity(); + + // set all properties to there original so we can render to a texture + this.renderWebGL = this._cacheData.originalRenderWebGL; + + renderer.render(this, renderTexture, true, m, true); + // now restore the state be setting the new properties + + renderer.bindRenderTarget(cachedRenderTarget); + + renderer.filterManager.filterStack = stack; + + this.renderWebGL = this._renderCachedWebGL; + this.updateTransform = this.displayObjectUpdateTransform; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + + // easy bounds.. + this._calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + + this._cacheData.sprite = cachedSprite; + + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + this.updateTransform(); + + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Renders a cached version of the sprite with canvas + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObjectCanvas(renderer); + + this._cacheData.sprite.worldAlpha = this.worldAlpha; + + this._cacheData.sprite.renderCanvas(renderer); +}; + +// TODO this can be the same as the webGL verison.. will need to do a little tweaking first though.. +/** + * Prepares the Canvas renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(); + + var cacheAlpha = this.alpha; + + this.alpha = 1; + + var cachedRenderTarget = renderer.context; + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + // need to set // + var m = _tempMatrix; + + this.transform.localTransform.copy(m); + m.invert(); + + m.tx -= bounds.x; + m.ty -= bounds.y; + + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + + // renderTexture.render(this, m, true); + renderer.render(this, renderTexture, true, m, false); + + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + + this.renderCanvas = this._renderCachedCanvas; + this._calculateBounds = this._calculateCachedBounds; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite._bounds = this._bounds; + cachedSprite.alpha = cacheAlpha; + + this.updateTransform(); + this.updateTransform = this.displayObjectUpdateTransform; + + this._cacheData.sprite = cachedSprite; + + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Calculates the bounds of the cached sprite + * + * @private + */ +DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._cacheData.sprite._calculateBounds(); +}; + +/** + * Gets the bounds of the cached sprite. + * + * @private + * @return {Rectangle} The local bounds. + */ +DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(); +}; + +/** + * Destroys the cached sprite. + * + * @private + */ +DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; +}; + +/** + * Destroys the cached object. + * + * @private + */ +DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy() { + this.cacheAsBitmap = false; + this.destroy(); +}; + +},{"../core":63}],134:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * The instance name of the object. + * + * @memberof PIXI.DisplayObject# + * @member {string} + */ +core.DisplayObject.prototype.name = null; + +/** + * Returns the display object in the container + * + * @memberof PIXI.Container# + * @param {string} name - instance name + * @return {PIXI.DisplayObject} The child with the specified name. + */ +core.Container.prototype.getChildByName = function getChildByName(name) { + for (var i = 0; i < this.children.length; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + + return null; +}; + +},{"../core":63}],135:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. + * + * @memberof PIXI.DisplayObject# + * @param {Point} point - the point to write the global value to. If null a new point will be returned + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @return {Point} The updated point + */ +core.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition() { + var point = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new core.Point(); + var skipUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (this.parent) { + this.parent.toGlobal(this.position, point, skipUpdate); + } else { + point.x = this.position.x; + point.y = this.position.y; + } + + return point; +}; + +},{"../core":63}],136:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BitmapText = exports.TilingSpriteRenderer = exports.TilingSprite = exports.AnimatedSprite = exports.TextureTransform = undefined; + +var _TextureTransform = require('./TextureTransform'); + +Object.defineProperty(exports, 'TextureTransform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureTransform).default; + } +}); + +var _AnimatedSprite = require('./AnimatedSprite'); + +Object.defineProperty(exports, 'AnimatedSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AnimatedSprite).default; + } +}); + +var _TilingSprite = require('./TilingSprite'); + +Object.defineProperty(exports, 'TilingSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSprite).default; + } +}); + +var _TilingSpriteRenderer = require('./webgl/TilingSpriteRenderer'); + +Object.defineProperty(exports, 'TilingSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSpriteRenderer).default; + } +}); + +var _BitmapText = require('./BitmapText'); + +Object.defineProperty(exports, 'BitmapText', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BitmapText).default; + } +}); + +require('./cacheAsBitmap'); + +require('./getChildByName'); + +require('./getGlobalPosition'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// imported for side effect of extending the prototype only, contains no exports + +},{"./AnimatedSprite":129,"./BitmapText":130,"./TextureTransform":131,"./TilingSprite":132,"./cacheAsBitmap":133,"./getChildByName":134,"./getGlobalPosition":135,"./webgl/TilingSpriteRenderer":137}],137:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _const = require('../../core/const'); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMat = new core.Matrix(); +var tempArray = new Float32Array(4); + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var TilingSpriteRenderer = function (_core$ObjectRenderer) { + _inherits(TilingSpriteRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function TilingSpriteRenderer(renderer) { + _classCallCheck(this, TilingSpriteRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + _this.simpleShader = null; + _this.quad = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + TilingSpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n gl_FragColor = sample * color ;\n}\n'); + this.simpleShader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n gl_FragColor = sample * color;\n}\n'); + + this.renderer.bindVao(null); + this.quad = new core.Quad(gl, this.renderer.state.attribState); + this.quad.initVao(this.shader); + }; + + /** + * + * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered + */ + + + TilingSpriteRenderer.prototype.render = function render(ts) { + var renderer = this.renderer; + var quad = this.quad; + + renderer.bindVao(quad.vao); + + var vertices = quad.vertices; + + vertices[0] = vertices[6] = ts._width * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + + vertices[2] = vertices[4] = ts._width * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + + if (ts.uvRespectAnchor) { + vertices = quad.uvs; + + vertices[0] = vertices[6] = -ts.anchor.x; + vertices[1] = vertices[3] = -ts.anchor.y; + + vertices[2] = vertices[4] = 1.0 - ts.anchor.x; + vertices[5] = vertices[7] = 1.0 - ts.anchor.y; + } + + quad.upload(); + + var tex = ts._texture; + var baseTex = tex.baseTexture; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvTransform; + var isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === _const.WRAP_MODES.CLAMP) { + baseTex.wrapMode = _const.WRAP_MODES.REPEAT; + } + } else { + isSimple = baseTex.wrapMode !== _const.WRAP_MODES.CLAMP; + } + } + + var shader = isSimple ? this.simpleShader : this.shader; + + renderer.bindShader(shader); + + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + + tempMat.invert(); + if (isSimple) { + tempMat.append(uv.mapCoord); + } else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + + shader.uniforms.uTransform = tempMat.toArray(true); + + var color = tempArray; + + core.utils.hex2rgb(ts.tint, color); + color[3] = ts.worldAlpha; + shader.uniforms.uColor = color; + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + + shader.uniforms.uSampler = renderer.bindTexture(tex); + + renderer.setBlendMode(ts.blendMode); + + quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + }; + + return TilingSpriteRenderer; +}(core.ObjectRenderer); + +exports.default = TilingSpriteRenderer; + + +core.WebGLRenderer.registerPlugin('tilingSprite', TilingSpriteRenderer); + +},{"../../core":63,"../../core/const":44,"path":22}],138:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BlurXFilter = require('./BlurXFilter'); + +var _BlurXFilter2 = _interopRequireDefault(_BlurXFilter); + +var _BlurYFilter = require('./BlurYFilter'); + +var _BlurYFilter2 = _interopRequireDefault(_BlurYFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurFilter applies a Gaussian blur to an object. + * The strength of the blur can be set for x- and y-axis separately. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurFilter = function (_core$Filter) { + _inherits(BlurFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this)); + + _this.blurXFilter = new _BlurXFilter2.default(strength, quality, resolution, kernelSize); + _this.blurYFilter = new _BlurYFilter2.default(strength, quality, resolution, kernelSize); + + _this.padding = 0; + _this.resolution = resolution || core.settings.RESOLUTION; + _this.quality = quality || 4; + _this.blur = strength || 8; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + BlurFilter.prototype.apply = function apply(filterManager, input, output) { + var renderTarget = filterManager.getRenderTarget(true); + + this.blurXFilter.apply(filterManager, input, renderTarget, true); + this.blurYFilter.apply(filterManager, renderTarget, output, false); + + filterManager.returnRenderTarget(renderTarget); + }; + + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurFilter, [{ + key: 'blur', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the number of passes for blur. More passes means higher quaility bluring. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'quality', + get: function get() { + return this.blurXFilter.quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.quality = this.blurYFilter.quality = value; + } + + /** + * Sets the strength of the blurX property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurX', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the strength of the blurY property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurY', + get: function get() { + return this.blurYFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + }]); + + return BlurFilter; +}(core.Filter); + +exports.default = BlurFilter; + +},{"../../core":63,"./BlurXFilter":139,"./BlurYFilter":140}],139:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurXFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurXFilter = function (_core$Filter) { + _inherits(BlurXFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurXFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurXFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurXFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.width * (output.size.width / input.size.width); + + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; // / this.passes//Math.pow(1, this.passes); + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 16 + */ + + + _createClass(BlurXFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurXFilter; +}(core.Filter); + +exports.default = BlurXFilter; + +},{"../../core":63,"./generateBlurFragSource":141,"./generateBlurVertSource":142,"./getMaxBlurKernelSize":143}],140:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurYFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurYFilter = function (_core$Filter) { + _inherits(BlurYFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurYFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurYFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurYFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.height * (output.size.height / input.size.height); + + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurYFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurYFilter; +}(core.Filter); + +exports.default = BlurYFilter; + +},{"../../core":63,"./generateBlurFragSource":141,"./generateBlurVertSource":142,"./getMaxBlurKernelSize":143}],141:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateFragBlurSource; +var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] +}; + +var fragTemplate = ['varying vec2 vBlurTexCoords[%size%];', 'uniform sampler2D uSampler;', 'void main(void)', '{', ' gl_FragColor = vec4(0.0);', ' %blur%', '}'].join('\n'); + +function generateFragBlurSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + + var fragSource = fragTemplate; + + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value = void 0; + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + value = i; + + if (i >= halfLength) { + value = kernelSize - i - 1; + } + + blur = blur.replace('%value%', kernel[value]); + + blurLoop += blur; + blurLoop += '\n'; + } + + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize); + + return fragSource; +} + +},{}],142:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateVertBlurSource; +var vertTemplate = ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform float strength;', 'uniform mat3 projectionMatrix;', 'varying vec2 vBlurTexCoords[%size%];', 'void main(void)', '{', 'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);', '%blur%', '}'].join('\n'); + +function generateVertBlurSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + + var vertSource = vertTemplate; + + var blurLoop = ''; + var template = void 0; + // let value; + + if (x) { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } else { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + // value = i; + + // if(i >= halfLength) + // { + // value = kernelSize - i - 1; + // } + + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + '.0'); + + blurLoop += blur; + blurLoop += '\n'; + } + + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize); + + return vertSource; +} + +},{}],143:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = getMaxKernelSize; +function getMaxKernelSize(gl) { + var maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + var kernelSize = 15; + + while (kernelSize > maxVaryings) { + kernelSize -= 2; + } + + return kernelSize; +} + +},{}],144:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var ColorMatrixFilter = function (_core$Filter) { + _inherits(ColorMatrixFilter, _core$Filter); + + /** + * + */ + function ColorMatrixFilter() { + _classCallCheck(this, ColorMatrixFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n vec4 result;\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n // Premultiply alpha again.\n result.rgb *= result.a;\n\n gl_FragColor = result;\n}\n')); + + _this.uniforms.m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + return _this; + } + + /** + * Transforms current matrix and set the new one + * + * @param {number[]} matrix - 5x4 matrix + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix(matrix) { + var multiply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + var newMatrix = matrix; + + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + + // set the new matrix + this.uniforms.m = newMatrix; + }; + + /** + * Multiplies two mat5's + * + * @private + * @param {number[]} out - 5x4 matrix the receiving matrix + * @param {number[]} a - 5x4 matrix the first operand + * @param {number[]} b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix + */ + + + ColorMatrixFilter.prototype._multiply = function _multiply(out, a, b) { + // Red Channel + out[0] = a[0] * b[0] + a[1] * b[5] + a[2] * b[10] + a[3] * b[15]; + out[1] = a[0] * b[1] + a[1] * b[6] + a[2] * b[11] + a[3] * b[16]; + out[2] = a[0] * b[2] + a[1] * b[7] + a[2] * b[12] + a[3] * b[17]; + out[3] = a[0] * b[3] + a[1] * b[8] + a[2] * b[13] + a[3] * b[18]; + out[4] = a[0] * b[4] + a[1] * b[9] + a[2] * b[14] + a[3] * b[19] + a[4]; + + // Green Channel + out[5] = a[5] * b[0] + a[6] * b[5] + a[7] * b[10] + a[8] * b[15]; + out[6] = a[5] * b[1] + a[6] * b[6] + a[7] * b[11] + a[8] * b[16]; + out[7] = a[5] * b[2] + a[6] * b[7] + a[7] * b[12] + a[8] * b[17]; + out[8] = a[5] * b[3] + a[6] * b[8] + a[7] * b[13] + a[8] * b[18]; + out[9] = a[5] * b[4] + a[6] * b[9] + a[7] * b[14] + a[8] * b[19] + a[9]; + + // Blue Channel + out[10] = a[10] * b[0] + a[11] * b[5] + a[12] * b[10] + a[13] * b[15]; + out[11] = a[10] * b[1] + a[11] * b[6] + a[12] * b[11] + a[13] * b[16]; + out[12] = a[10] * b[2] + a[11] * b[7] + a[12] * b[12] + a[13] * b[17]; + out[13] = a[10] * b[3] + a[11] * b[8] + a[12] * b[13] + a[13] * b[18]; + out[14] = a[10] * b[4] + a[11] * b[9] + a[12] * b[14] + a[13] * b[19] + a[14]; + + // Alpha Channel + out[15] = a[15] * b[0] + a[16] * b[5] + a[17] * b[10] + a[18] * b[15]; + out[16] = a[15] * b[1] + a[16] * b[6] + a[17] * b[11] + a[18] * b[16]; + out[17] = a[15] * b[2] + a[16] * b[7] + a[17] * b[12] + a[18] * b[17]; + out[18] = a[15] * b[3] + a[16] * b[8] + a[17] * b[13] + a[18] * b[18]; + out[19] = a[15] * b[4] + a[16] * b[9] + a[17] * b[14] + a[18] * b[19] + a[19]; + + return out; + }; + + /** + * Create a Float32 Array and normalize the offset component to 0-1 + * + * @private + * @param {number[]} matrix - 5x4 matrix + * @return {number[]} 5x4 matrix with all values between 0-1 + */ + + + ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix(matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + + return m; + }; + + /** + * Adjusts brightness + * + * @param {number} b - value of the brigthness (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.brightness = function brightness(b, multiply) { + var matrix = [b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the matrices in grey scales + * + * @param {number} scale - value of the grey (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.greyscale = function greyscale(scale, multiply) { + var matrix = [scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the black and white matrice. + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite(multiply) { + var matrix = [0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the hue property of the color + * + * @param {number} rotation - in degrees + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.hue = function hue(rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + + var a00 = cosR + (1.0 - cosR) * w; + var a01 = w * (1.0 - cosR) - sqrW * sinR; + var a02 = w * (1.0 - cosR) + sqrW * sinR; + + var a10 = w * (1.0 - cosR) + sqrW * sinR; + var a11 = cosR + w * (1.0 - cosR); + var a12 = w * (1.0 - cosR) - sqrW * sinR; + + var a20 = w * (1.0 - cosR) - sqrW * sinR; + var a21 = w * (1.0 - cosR) + sqrW * sinR; + var a22 = cosR + w * (1.0 - cosR); + + var matrix = [a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * + * @param {number} amount - value of the contrast (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.contrast = function contrast(amount, multiply) { + var v = (amount || 0) + 1; + var o = -128 * (v - 1); + + var matrix = [v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * + * @param {number} amount - The saturation amount (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.saturate = function saturate() { + var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var multiply = arguments[1]; + + var x = amount * 2 / 3 + 1; + var y = (x - 1) * -0.5; + + var matrix = [x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Desaturate image (remove color) + * + * Call the saturate function + * + */ + + + ColorMatrixFilter.prototype.desaturate = function desaturate() // eslint-disable-line no-unused-vars + { + this.saturate(-1); + }; + + /** + * Negative image (inverse of classic rgb matrix) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.negative = function negative(multiply) { + var matrix = [0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Sepia image + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.sepia = function sepia(multiply) { + var matrix = [0.393, 0.7689999, 0.18899999, 0, 0, 0.349, 0.6859999, 0.16799999, 0, 0, 0.272, 0.5339999, 0.13099999, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.technicolor = function technicolor(multiply) { + var matrix = [1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Polaroid filter + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.polaroid = function polaroid(multiply) { + var matrix = [1.438, -0.062, -0.062, 0, 0, -0.122, 1.378, -0.122, 0, 0, -0.016, -0.016, 1.483, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Filter who transforms : Red -> Blue and Blue -> Red + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.toBGR = function toBGR(multiply) { + var matrix = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.kodachrome = function kodachrome(multiply) { + var matrix = [1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Brown delicious browni filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.browni = function browni(multiply) { + var matrix = [0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Vintage filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.vintage = function vintage(multiply) { + var matrix = [0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * + * @param {number} desaturation - Tone values. + * @param {number} toned - Tone values. + * @param {string} lightColor - Tone values, example: `0xFFE580` + * @param {string} darkColor - Tone values, example: `0xFFE580` + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.colorTone = function colorTone(desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + + var lR = (lightColor >> 16 & 0xFF) / 255; + var lG = (lightColor >> 8 & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + + var dR = (darkColor >> 16 & 0xFF) / 255; + var dG = (darkColor >> 8 & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + + var matrix = [0.3, 0.59, 0.11, 0, 0, lR, lG, lB, desaturation, 0, dR, dG, dB, toned, 0, lR - dR, lG - dG, lB - dB, 0, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Night effect + * + * @param {number} intensity - The intensity of the night effect. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.night = function night(intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [intensity * -2.0, -intensity, 0, 0, 0, -intensity, 0, intensity, 0, 0, 0, intensity, intensity * 2.0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * + * @param {number} amount - how much the predator feels his future victim + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.predator = function predator(amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * LSD effect + * + * Multiply the current matrix + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.lsd = function lsd(multiply) { + var matrix = [2, -0.4, 0.5, 0, 0, -0.5, 2, -0.4, 0, 0, -0.4, -0.5, 3, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Erase the current matrix by setting the default one + * + */ + + + ColorMatrixFilter.prototype.reset = function reset() { + var matrix = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, false); + }; + + /** + * The matrix of the color matrix filter + * + * @member {number[]} + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + + + _createClass(ColorMatrixFilter, [{ + key: 'matrix', + get: function get() { + return this.uniforms.m; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.m = value; + } + }]); + + return ColorMatrixFilter; +}(core.Filter); + +// Americanized alias + + +exports.default = ColorMatrixFilter; +ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + +},{"../../core":63,"path":22}],145:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. You can + * use this filter to apply all manor of crazy warping effects. Currently the r + * property of the texture is used to offset the x and the g property of the texture + * is used to offset the y. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var DisplacementFilter = function (_core$Filter) { + _inherits(DisplacementFilter, _core$Filter); + + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param {number} scale - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + _classCallCheck(this, DisplacementFilter); + + var maskMatrix = new core.Matrix(); + + sprite.renderable = false; + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n')); + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + + _this.uniforms.mapSampler = sprite.texture; + _this.uniforms.filterMatrix = maskMatrix; + _this.uniforms.scale = { x: 1, y: 1 }; + + if (scale === null || scale === undefined) { + scale = 20; + } + + _this.scale = new core.Point(scale, scale); + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + DisplacementFilter.prototype.apply = function apply(filterManager, input, output) { + var ratio = 1 / output.destinationFrame.width * (output.size.width / input.size.width); + + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x * ratio; + this.uniforms.scale.y = this.scale.y * ratio; + + // draw the filter... + filterManager.applyFilter(this, input, output); + }; + + /** + * The texture used for the displacement map. Must be power of 2 sized texture. + * + * @member {PIXI.Texture} + */ + + + _createClass(DisplacementFilter, [{ + key: 'map', + get: function get() { + return this.uniforms.mapSampler; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.mapSampler = value; + } + }]); + + return DisplacementFilter; +}(core.Filter); + +exports.default = DisplacementFilter; + +},{"../../core":63,"path":22}],146:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * Basic FXAA implementation based on the code on geeks3d.com with the + * modification that the texture2DLod stuff was removed since it's + * unsupported by WebGL. + * + * @see https://github.com/mitsuhiko/webgl-meincraft + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + * + */ +var FXAAFilter = function (_core$Filter) { + _inherits(FXAAFilter, _core$Filter); + + /** + * + */ + function FXAAFilter() { + _classCallCheck(this, FXAAFilter); + + // TODO - needs work + return _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + '\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}', + // fragment shader + 'varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n')); + } + + return FXAAFilter; +}(core.Filter); + +exports.default = FXAAFilter; + +},{"../../core":63,"path":22}],147:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _FXAAFilter = require('./fxaa/FXAAFilter'); + +Object.defineProperty(exports, 'FXAAFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_FXAAFilter).default; + } +}); + +var _NoiseFilter = require('./noise/NoiseFilter'); + +Object.defineProperty(exports, 'NoiseFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NoiseFilter).default; + } +}); + +var _DisplacementFilter = require('./displacement/DisplacementFilter'); + +Object.defineProperty(exports, 'DisplacementFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplacementFilter).default; + } +}); + +var _BlurFilter = require('./blur/BlurFilter'); + +Object.defineProperty(exports, 'BlurFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurFilter).default; + } +}); + +var _BlurXFilter = require('./blur/BlurXFilter'); + +Object.defineProperty(exports, 'BlurXFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurXFilter).default; + } +}); + +var _BlurYFilter = require('./blur/BlurYFilter'); + +Object.defineProperty(exports, 'BlurYFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurYFilter).default; + } +}); + +var _ColorMatrixFilter = require('./colormatrix/ColorMatrixFilter'); + +Object.defineProperty(exports, 'ColorMatrixFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ColorMatrixFilter).default; + } +}); + +var _VoidFilter = require('./void/VoidFilter'); + +Object.defineProperty(exports, 'VoidFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VoidFilter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./blur/BlurFilter":138,"./blur/BlurXFilter":139,"./blur/BlurYFilter":140,"./colormatrix/ColorMatrixFilter":144,"./displacement/DisplacementFilter":145,"./fxaa/FXAAFilter":146,"./noise/NoiseFilter":148,"./void/VoidFilter":149}],148:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Vico @vicocotea + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + */ + +/** + * A Noise effect filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var NoiseFilter = function (_core$Filter) { + _inherits(NoiseFilter, _core$Filter); + + /** + * + */ + function NoiseFilter() { + _classCallCheck(this, NoiseFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float noise;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n float diff = (rand(gl_FragCoord.xy) - 0.5) * noise;\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n gl_FragColor = color;\n}\n')); + + _this.noise = 0.5; + return _this; + } + + /** + * The amount of noise to apply. + * + * @member {number} + * @default 0.5 + */ + + + _createClass(NoiseFilter, [{ + key: 'noise', + get: function get() { + return this.uniforms.noise; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.noise = value; + } + }]); + + return NoiseFilter; +}(core.Filter); + +exports.default = NoiseFilter; + +},{"../../core":63,"path":22}],149:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Does nothing. Very handy. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var VoidFilter = function (_core$Filter) { + _inherits(VoidFilter, _core$Filter); + + /** + * + */ + function VoidFilter() { + _classCallCheck(this, VoidFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n')); + + _this.glShaderKey = 'void'; + return _this; + } + + return VoidFilter; +}(core.Filter); + +exports.default = VoidFilter; + +},{"../../core":63,"path":22}],150:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Holds all information related to an Interaction event + * + * @class + * @memberof PIXI.interaction + */ +var InteractionData = function () { + /** + * + */ + function InteractionData() { + _classCallCheck(this, InteractionData); + + /** + * This point stores the global coords of where the touch/mouse event happened + * + * @member {PIXI.Point} + */ + this.global = new core.Point(); + + /** + * The target DisplayObject that was interacted with + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * When passed to an event handler, this will be the original DOM Event that was captured + * + * @member {Event} + */ + this.originalEvent = null; + + /** + * Unique identifier for this interaction + * + * @member {number} + */ + this.identifier = null; + } + + /** + * This will return the local coordinates of the specified displayObject for this InteractionData + * + * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local + * coords off + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative + * to the DisplayObject + */ + + + InteractionData.prototype.getLocalPosition = function getLocalPosition(displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + + return InteractionData; +}(); + +exports.default = InteractionData; + +},{"../core":63}],151:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Event class that mimics native DOM events. + * + * @class + * @memberof PIXI.interaction + */ +var InteractionEvent = function () { + /** + * + */ + function InteractionEvent() { + _classCallCheck(this, InteractionEvent); + + /** + * Whether this event will continue propagating in the tree + * + * @member {boolean} + */ + this.stopped = false; + + /** + * The object which caused this event to be dispatched. + * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}. + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * The object whose event listener’s callback is currently being invoked. + * + * @member {PIXI.DisplayObject} + */ + this.currentTarget = null; + + /* + * Type of the event + * + * @member {string} + */ + this.type = null; + + /* + * InteractionData related to this event + * + * @member {PIXI.interaction.InteractionData} + */ + this.data = null; + } + + /** + * Prevents event from reaching any objects other than the current object. + * + */ + + + InteractionEvent.prototype.stopPropagation = function stopPropagation() { + this.stopped = true; + }; + + /** + * Resets the event. + * + * @private + */ + + + InteractionEvent.prototype._reset = function _reset() { + this.stopped = false; + this.currentTarget = null; + this.target = null; + }; + + return InteractionEvent; +}(); + +exports.default = InteractionEvent; + +},{}],152:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _InteractionData = require('./InteractionData'); + +var _InteractionData2 = _interopRequireDefault(_InteractionData); + +var _InteractionEvent = require('./InteractionEvent'); + +var _InteractionEvent2 = _interopRequireDefault(_InteractionEvent); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +var _InteractionTrackingData2 = _interopRequireDefault(_InteractionTrackingData); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _interactiveTarget = require('./interactiveTarget'); + +var _interactiveTarget2 = _interopRequireDefault(_interactiveTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// Mix interactiveTarget into core.DisplayObject.prototype, after deprecation has been handled +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _interactiveTarget2.default); + +var MOUSE_POINTER_ID = 'MOUSE'; + +/** + * The interaction manager deals with mouse, touch and pointer events. Any DisplayObject can be interactive + * if its interactive parameter is set to true + * This manager also supports multitouch. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.interaction + * + * @class + * @extends EventEmitter + * @memberof PIXI.interaction + */ + +var InteractionManager = function (_EventEmitter) { + _inherits(InteractionManager, _EventEmitter); + + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + * @param {object} [options] - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Frequency increases the interaction events will be checked. + */ + function InteractionManager(renderer, options) { + _classCallCheck(this, InteractionManager); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + options = options || {}; + + /** + * The renderer this interaction manager works for. + * + * @member {PIXI.SystemRenderer} + */ + _this.renderer = renderer; + + /** + * Should default browser actions automatically be prevented. + * Does not apply to pointer events for backwards compatibility + * preventDefault on pointer events stops mouse events from firing + * Thus, for every pointer event, there will always be either a mouse of touch event alongside it. + * + * @member {boolean} + * @default true + */ + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + + /** + * Frequency in milliseconds that the mousemove, moveover & mouseout interaction events will be checked. + * + * @member {number} + * @default 10 + */ + _this.interactionFrequency = options.interactionFrequency || 10; + + /** + * The mouse data + * + * @member {PIXI.interaction.InteractionData} + */ + _this.mouse = new _InteractionData2.default(); + _this.mouse.identifier = MOUSE_POINTER_ID; + + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + + /** + * Actively tracked InteractionData + * + * @private + * @member {Object.} + */ + _this.activeInteractionData = {}; + _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; + + /** + * Pool of unused InteractionData + * + * @private + * @member {PIXI.interation.InteractionData[]} + */ + _this.interactionDataPool = []; + + /** + * An event data object to handle all the event tracking/dispatching + * + * @member {object} + */ + _this.eventData = new _InteractionEvent2.default(); + + /** + * The DOM element to bind to. + * + * @private + * @member {HTMLElement} + */ + _this.interactionDOMElement = null; + + /** + * This property determines if mousemove and touchmove events are fired only when the cursor + * is over the object. + * Setting to true will make things work more in line with how the DOM verison works. + * Setting to false can make things easier for things like dragging + * It is currently set to false as this is how pixi used to work. This will be set to true in + * future versions of pixi. + * + * @member {boolean} + * @default false + */ + _this.moveWhenInside = false; + + /** + * Have events been attached to the dom element? + * + * @private + * @member {boolean} + */ + _this.eventsAdded = false; + + /** + * Is the mouse hovering over the renderer? + * + * @private + * @member {boolean} + */ + _this.mouseOverRenderer = false; + + /** + * Does the device support touch events + * https://www.w3.org/TR/touch-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsTouchEvents = 'ontouchstart' in window; + + /** + * Does the device support pointer events + * https://www.w3.org/Submission/pointer-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsPointerEvents = !!window.PointerEvent; + + // this will make it so that you don't have to call bind all the time + + /** + * @private + * @member {Function} + */ + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerCancel = _this.onPointerCancel.bind(_this); + _this.processPointerCancel = _this.processPointerCancel.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOver = _this.onPointerOver.bind(_this); + + /** + * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor + * values, objects are handled as dictionaries of CSS values for interactionDOMElement, + * and functions are called instead of changing the CSS. + * Default CSS cursor values are provided for 'default' and 'pointer' modes. + * @member {Object.)>} + */ + _this.cursorStyles = { + default: 'inherit', + pointer: 'pointer' + }; + + /** + * The mode of the cursor that is being used. + * The value of this is a key from the cursorStyles dictionary. + * + * @member {string} + */ + _this.currentCursorMode = null; + + /** + * Internal cached let. + * + * @private + * @member {string} + */ + _this.cursor = null; + + /** + * Internal cached let. + * + * @private + * @member {PIXI.Point} + */ + _this._tempPoint = new core.Point(); + + /** + * The current resolution / device pixel ratio. + * + * @member {number} + * @default 1 + */ + _this.resolution = 1; + + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + + /** + * Fired when a pointer device button (usually a mouse button) is pressed on the display + * object. + * + * @event mousedown + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * + * @event rightdown + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is released over the display + * object. + * + * @event mouseup + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * + * @event rightup + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is pressed and released on + * the display object. + * + * @event click + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * + * @event rightclick + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. + * + * @event mouseupoutside + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. + * + * @event rightupoutside + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * + * @event mousemove + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * + * @event mouseover + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * + * @event mouseout + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * + * @event pointerdown + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is released over the display object. + * + * @event pointerup + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when the operating system cancels a pointer event + * + * @event pointercancel + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * + * @event pointertap + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}. + * + * @event pointerupoutside + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved while over the display object + * + * @event pointermove + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved onto the display object + * + * @event pointerover + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved off the display object + * + * @event pointerout + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is placed on the display object. + * + * @event touchstart + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is removed from the display object. + * + * @event touchend + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when the operating system cancels a touch + * + * @event touchcancel + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * + * @event tap + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. + * + * @event touchendoutside + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is moved along the display object. + * + * @event touchmove + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + return _this; + } + + /** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate + * another DOM element to receive those events. + * + * @param {HTMLCanvasElement} element - the DOM element which will receive mouse and touch events. + * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). + * @private + */ + + + InteractionManager.prototype.setTargetElement = function setTargetElement(element) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.removeEvents(); + + this.interactionDOMElement = element; + + this.resolution = resolution; + + this.addEvents(); + }; + + /** + * Registers all the DOM events + * + * @private + */ + + + InteractionManager.prototype.addEvents = function addEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.add(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; + this.interactionDOMElement.style['-ms-touch-action'] = 'none'; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = 'none'; + } + + /** + * These events are added first, so that if pointer events are normalised, they are fired + * in the same order as non-normalised events. ie. pointer event 1st, mouse / touch 2nd + */ + if (this.supportsPointerEvents) { + window.document.addEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); + // pointerout is fired in addition to pointerup (for touch events) and pointercancel + // we already handle those, so for the purposes of what we do in onPointerOut, we only + // care about the pointerleave event + this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); + window.addEventListener('pointercancel', this.onPointerCancel, true); + window.addEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.addEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); + window.addEventListener('mouseup', this.onPointerUp, true); + + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); + } + } + + this.eventsAdded = true; + }; + + /** + * Removes all the DOM events that were previously registered + * + * @private + */ + + + InteractionManager.prototype.removeEvents = function removeEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.remove(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = ''; + this.interactionDOMElement.style['-ms-touch-action'] = ''; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = ''; + } + + if (this.supportsPointerEvents) { + window.document.removeEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); + window.removeEventListener('pointercancel', this.onPointerCancel, true); + window.removeEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.removeEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true); + window.removeEventListener('mouseup', this.onPointerUp, true); + + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); + } + } + + this.interactionDOMElement = null; + + this.eventsAdded = false; + }; + + /** + * Updates the state of interactive objects. + * Invoked by a throttled ticker update from {@link PIXI.ticker.shared}. + * + * @param {number} deltaTime - time delta since last tick + */ + + + InteractionManager.prototype.update = function update(deltaTime) { + this._deltaTime += deltaTime; + + if (this._deltaTime < this.interactionFrequency) { + return; + } + + this._deltaTime = 0; + + if (!this.interactionDOMElement) { + return; + } + + // if the user move the mouse this check has already been done using the mouse move! + if (this.didMove) { + this.didMove = false; + + return; + } + + this.cursor = null; + + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + for (var k in this.activeInteractionData) { + // eslint-disable-next-line no-prototype-builtins + if (this.activeInteractionData.hasOwnProperty(k)) { + var interactionData = this.activeInteractionData[k]; + + if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, true); + } + } + } + + this.setCursorMode(this.cursor); + + // TODO + }; + + /** + * Sets the current cursor mode, handling any callbacks or CSS style changes. + * + * @param {string} mode - cursor mode, a key from the cursorStyles dictionary + */ + + + InteractionManager.prototype.setCursorMode = function setCursorMode(mode) { + mode = mode || 'default'; + // if the mode didn't actually change, bail early + if (this.currentCursorMode === mode) { + return; + } + this.currentCursorMode = mode; + var style = this.cursorStyles[mode]; + + // only do things if there is a cursor style for it + if (style) { + switch (typeof style === 'undefined' ? 'undefined' : _typeof(style)) { + case 'string': + // string styles are handled as cursor CSS + this.interactionDOMElement.style.cursor = style; + break; + case 'function': + // functions are just called, and passed the cursor mode + style(mode); + break; + case 'object': + // if it is an object, assume that it is a dictionary of CSS styles, + // apply it to the interactionDOMElement + Object.assign(this.interactionDOMElement.style, style); + break; + } + } + }; + + /** + * Dispatches an event on the display object that was interacted with + * + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the display object in question + * @param {string} eventString - the name of the event (e.g, mousedown) + * @param {object} eventData - the event data object + * @private + */ + + + InteractionManager.prototype.dispatchEvent = function dispatchEvent(displayObject, eventString, eventData) { + if (!eventData.stopped) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + + displayObject.emit(eventString, eventData); + + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } + }; + + /** + * Maps x and y coords from a DOM object and maps them correctly to the pixi view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. + * + * @param {PIXI.Point} point - the point that the result will be stored in + * @param {number} x - the x coord of the position to map + * @param {number} y - the y coord of the position to map + */ + + + InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint(point, x, y) { + var rect = void 0; + + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { x: 0, y: 0, width: 0, height: 0 }; + } else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + + var resolutionMultiplier = navigator.isCocoonJS ? this.resolution : 1.0 / this.resolution; + + point.x = (x - rect.left) * (this.interactionDOMElement.width / rect.width) * resolutionMultiplier; + point.y = (y - rect.top) * (this.interactionDOMElement.height / rect.height) * resolutionMultiplier; + }; + + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * + * @private + * @param {InteractionEvent} interactionEvent - event containing the point that + * is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param {Function} [func] - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point + * @param {boolean} [interactive] - Whether the displayObject is interactive + * @return {boolean} returns true if the displayObject hit the point + */ + + + InteractionManager.prototype.processInteractive = function processInteractive(interactionEvent, displayObject, func, hitTest, interactive) { + if (!displayObject || !displayObject.visible) { + return false; + } + + var point = interactionEvent.data.global; + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + interactive = displayObject.interactive || interactive; + + var hit = false; + var interactiveParent = interactive; + + // if the displayobject has a hitArea, then it does not need to hitTest children. + if (displayObject.hitArea) { + interactiveParent = false; + } + // it has a mask! Then lets hit test that before continuing + else if (hitTest && displayObject._mask) { + if (!displayObject._mask.containsPoint(point)) { + hitTest = false; + } + } + + var keepHitTestingAfterChildren = hitTest; + + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow pixi to completely ignore and bypass checking the displayObjects children. + if (displayObject.interactiveChildren && displayObject.children) { + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + + // time to get recursive.. if this function will return if something is hit.. + if (this.processInteractive(interactionEvent, child, func, hitTest, interactiveParent)) { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if (!child.parent) { + continue; + } + + hit = true; + + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + + keepHitTestingAfterChildren = false; + + if (child.interactive) { + hitTest = false; + } + + // we can break now as we have hit an object. + } + } + } + + hitTest = keepHitTestingAfterChildren; + + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit! + if (hitTest && !hit) { + if (displayObject.hitArea) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + hit = displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y); + } else if (displayObject.containsPoint) { + hit = displayObject.containsPoint(point); + } + } + + if (displayObject.interactive) { + if (hit && !interactionEvent.target) { + interactionEvent.target = displayObject; + } + + func(interactionEvent, displayObject, hit); + } + } + + return hit; + }; + + /** + * Is called when the pointer button is pressed down on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down + */ + + + InteractionManager.prototype.onPointerDown = function onPointerDown(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + /** + * No need to prevent default on natural pointer events, as there are no side effects + * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, + * so still need to be prevented. + */ + + // Guaranteed that there will be at least one event in events, and all events must have the same pointer type + + if (this.autoPreventDefault && events[0].isNormalized) { + originalEvent.preventDefault(); + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event.pointerId); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerDown, true); + + this.emit('pointerdown', interactionEvent); + if (event.pointerType === 'touch') { + this.emit('touchstart', interactionEvent); + } else if (event.pointerType === 'mouse') { + var isRightButton = event.button === 2 || event.which === 3; + + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + } + }; + + /** + * Processes the result of the pointer down check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerDown = function processPointerDown(interactionEvent, displayObject, hit) { + var e = interactionEvent.data.originalEvent; + + var id = interactionEvent.data.identifier; + + if (hit) { + if (!displayObject.trackedPointers[id]) { + displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + + if (e.type === 'touchstart' || e.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchstart', interactionEvent); + } else if (e.type === 'mousedown' || e.pointerType === 'mouse') { + var isRightButton = e.button === 2 || e.which === 3; + + if (isRightButton) { + displayObject.trackedPointers[id].rightDown = true; + } else { + displayObject.trackedPointers[id].leftDown = true; + } + + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released + * @param {boolean} cancelled - true if the pointer is cancelled + * @param {Function} func - Function passed to {@link processInteractive} + */ + + + InteractionManager.prototype.onPointerComplete = function onPointerComplete(originalEvent, cancelled, func) { + var events = this.normalizeToPointerData(originalEvent); + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event.pointerId); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, func, true); + + this.emit(cancelled ? 'pointercancel' : 'pointerup', interactionEvent); + + if (event.pointerType === 'mouse') { + var isRightButton = event.button === 2 || event.which === 3; + + this.emit(isRightButton ? 'rightup' : 'mouseup', interactionEvent); + } else if (event.pointerType === 'touch') { + this.emit(cancelled ? 'touchcancel' : 'touchend', interactionEvent); + this.releaseInteractionDataForPointerId(event.pointerId, interactionData); + } + } + }; + + /** + * Is called when the pointer button is cancelled + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerCancel = function onPointerCancel(event) { + this.onPointerComplete(event, true, this.processPointerCancel); + }; + + /** + * Processes the result of the pointer cancel check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + */ + + + InteractionManager.prototype.processPointerCancel = function processPointerCancel(interactionEvent, displayObject) { + var e = interactionEvent.data.originalEvent; + + var id = interactionEvent.data.identifier; + + if (displayObject.trackedPointers[id] !== undefined) { + delete displayObject.trackedPointers[id]; + this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); + + if (e.type === 'touchcancel' || e.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerUp = function onPointerUp(event) { + this.onPointerComplete(event, false, this.processPointerUp); + }; + + /** + * Processes the result of the pointer up check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerUp = function processPointerUp(interactionEvent, displayObject, hit) { + var e = interactionEvent.data.originalEvent; + + var id = interactionEvent.data.identifier; + + var trackingData = displayObject.trackedPointers[id]; + + var isTouch = e.type === 'touchend' || e.pointerType === 'touch'; + + var isMouse = e.type.indexOf('mouse') === 0 || e.pointerType === 'mouse'; + + // Mouse only + if (isMouse) { + var isRightButton = e.button === 2 || e.which === 3; + + var flags = _InteractionTrackingData2.default.FLAGS; + + var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; + + var isDown = trackingData !== undefined && trackingData.flags | test; + + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); + + if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); + } + } else if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); + } + // update the down state of the tracking data + if (trackingData) { + if (isRightButton) { + trackingData.rightDown = hit; + } else { + trackingData.leftDown = hit; + } + } + } + + // Pointers and Touches, and Mouse + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchend', interactionEvent); + + if (trackingData) { + this.dispatchEvent(displayObject, 'pointertap', interactionEvent); + if (isTouch) { + this.dispatchEvent(displayObject, 'tap', interactionEvent); + // touches are no longer over (if they ever were) when we get the touchend + // so we should ensure that we don't keep pretending that they are + trackingData.over = false; + } + } + } else if (trackingData) { + this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); + } + // Only remove the tracking data if there is no over/down state still associated with it + if (trackingData && trackingData.none) { + delete displayObject.trackedPointers[id]; + } + }; + + /** + * Is called when the pointer moves across the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer moving + */ + + + InteractionManager.prototype.onPointerMove = function onPointerMove(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + if (events[0].pointerType === 'mouse') { + this.didMove = true; + + this.cursor = null; + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event.pointerId); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + var interactive = event.pointerType === 'touch' ? this.moveWhenInside : true; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerMove, interactive); + this.emit('pointermove', interactionEvent); + if (event.pointerType === 'touch') this.emit('touchmove', interactionEvent); + if (event.pointerType === 'mouse') this.emit('mousemove', interactionEvent); + } + + if (events[0].pointerType === 'mouse') { + this.setCursorMode(this.cursor); + + // TODO BUG for parents interactive object (border order issue) + } + }; + + /** + * Processes the result of the pointer move check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerMove = function processPointerMove(interactionEvent, displayObject, hit) { + var e = interactionEvent.data.originalEvent; + + var isTouch = e.type === 'touchmove' || e.pointerType === 'touch'; + + var isMouse = e.type === 'mousemove' || e.pointerType === 'mouse'; + + if (isMouse) { + this.processPointerOverOut(interactionEvent, displayObject, hit); + } + + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchmove', interactionEvent); + if (isMouse) this.dispatchEvent(displayObject, 'mousemove', interactionEvent); + } + }; + + /** + * Is called when the pointer is moved out of the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out + */ + + + InteractionManager.prototype.onPointerOut = function onPointerOut(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOut, so events will always be length 1 + var event = events[0]; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = false; + this.setCursorMode(null); + } + + var interactionData = this.getInteractionDataForPointerId(event.pointerId); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, false); + + this.emit('pointerout', interactionEvent); + if (event.pointerType === 'mouse') { + this.emit('mouseout', interactionEvent); + } + }; + + /** + * Processes the result of the pointer over/out check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerOverOut = function processPointerOverOut(interactionEvent, displayObject, hit) { + var e = interactionEvent.data.originalEvent; + + var id = interactionEvent.data.identifier; + + var isMouse = e.type === 'mouseover' || e.type === 'mouseout' || e.pointerType === 'mouse'; + + var trackingData = displayObject.trackedPointers[id]; + + // if we just moused over the display object, then we need to track that state + if (hit && !trackingData) { + trackingData = displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + + if (trackingData === undefined) return; + + if (hit && this.mouseOverRenderer) { + if (!trackingData.over) { + trackingData.over = true; + this.dispatchEvent(displayObject, 'pointerover', interactionEvent); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseover', interactionEvent); + } + } + + // only change the cursor if it has not already been changed (by something deeper in the + // display tree) + if (isMouse && this.cursor === null) { + this.cursor = displayObject.cursor; + } + } else if (trackingData.over) { + trackingData.over = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseout', interactionEvent); + } + // if there is no mouse down information for the pointer, then it is safe to delete + if (trackingData.none) { + delete displayObject.trackedPointers[id]; + } + } + }; + + /** + * Is called when the pointer is moved into the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view + */ + + + InteractionManager.prototype.onPointerOver = function onPointerOver(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOver, so events will always be length 1 + var event = events[0]; + + var interactionData = this.getInteractionDataForPointerId(event.pointerId); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = true; + } + + this.emit('pointerover', interactionEvent); + if (event.pointerType === 'mouse') { + this.emit('mouseover', interactionEvent); + } + }; + + /** + * Get InteractionData for a given pointerId. Store that data as well + * + * @private + * @param {number} pointerId - Identifier from a pointer event + * @return {InteractionData} - Interaction data for the given pointer identifier + */ + + + InteractionManager.prototype.getInteractionDataForPointerId = function getInteractionDataForPointerId(pointerId) { + if (pointerId === MOUSE_POINTER_ID) { + return this.mouse; + } else if (this.activeInteractionData[pointerId]) { + return this.activeInteractionData[pointerId]; + } + + var interactionData = this.interactionDataPool.pop() || new _InteractionData2.default(); + + interactionData.identifier = pointerId; + this.activeInteractionData[pointerId] = interactionData; + + return interactionData; + }; + + /** + * Return unused InteractionData to the pool, for a given pointerId + * + * @private + * @param {number} pointerId - Identifier from a pointer event + */ + + + InteractionManager.prototype.releaseInteractionDataForPointerId = function releaseInteractionDataForPointerId(pointerId) { + var interactionData = this.activeInteractionData[pointerId]; + + if (interactionData) { + delete this.activeInteractionData[pointerId]; + this.interactionDataPool.push(interactionData); + } + }; + + /** + * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData + * + * @private + * @param {InteractionEvent} interactionEvent - The event to be configured + * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent + * @param {InteractionData} interactionData - The InteractionData that will be paired with the InteractionEvent + * @return {InteractionEvent} the interaction event that was passed in + */ + + + InteractionManager.prototype.configureInteractionEventForDOMEvent = function configureInteractionEventForDOMEvent(interactionEvent, pointerEvent, interactionData) { + interactionEvent.data = interactionData; + + this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); + + // This is the way InteractionManager processed touch events before the refactoring, so I've kept + // it here. But it doesn't make that much sense to me, since mapPositionToPoint already factors + // in this.resolution, so this just divides by this.resolution twice for touch events... + if (navigator.isCocoonJS && pointerEvent.pointerType === 'touch') { + interactionData.global.x = interactionData.global.x / this.resolution; + interactionData.global.y = interactionData.global.y / this.resolution; + } + + // Not really sure why this is happening, but it's how a previous version handled things + if (pointerEvent.pointerType === 'touch') { + pointerEvent.globalX = interactionData.global.x; + pointerEvent.globalY = interactionData.global.y; + } + + interactionData.originalEvent = pointerEvent; + interactionEvent._reset(); + + return interactionEvent; + }; + + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * + * @private + * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event + * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer + * or mouse event, or a multiple normalized pointer events if there are multiple changed touches + */ + + + InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData(event) { + var normalizedEvents = []; + + if (this.supportsTouchEvents && event instanceof TouchEvent) { + for (var i = 0, li = event.changedTouches.length; i < li; i++) { + var touch = event.changedTouches[i]; + + if (typeof touch.button === 'undefined') touch.button = event.touches.length ? 1 : 0; + if (typeof touch.buttons === 'undefined') touch.buttons = event.touches.length ? 1 : 0; + if (typeof touch.isPrimary === 'undefined') touch.isPrimary = event.touches.length === 1; + if (typeof touch.width === 'undefined') touch.width = touch.radiusX || 1; + if (typeof touch.height === 'undefined') touch.height = touch.radiusY || 1; + if (typeof touch.tiltX === 'undefined') touch.tiltX = 0; + if (typeof touch.tiltY === 'undefined') touch.tiltY = 0; + if (typeof touch.pointerType === 'undefined') touch.pointerType = 'touch'; + if (typeof touch.pointerId === 'undefined') touch.pointerId = touch.identifier || 0; + if (typeof touch.pressure === 'undefined') touch.pressure = touch.force || 0.5; + if (typeof touch.rotation === 'undefined') touch.rotation = touch.rotationAngle || 0; + + if (typeof touch.layerX === 'undefined') touch.layerX = touch.offsetX = touch.clientX; + if (typeof touch.layerY === 'undefined') touch.layerY = touch.offsetY = touch.clientY; + + // mark the touch as normalized, just so that we know we did it + touch.isNormalized = true; + + normalizedEvents.push(touch); + } + } + // apparently PointerEvent subclasses MouseEvent, so yay + else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent))) { + if (typeof event.isPrimary === 'undefined') event.isPrimary = true; + if (typeof event.width === 'undefined') event.width = 1; + if (typeof event.height === 'undefined') event.height = 1; + if (typeof event.tiltX === 'undefined') event.tiltX = 0; + if (typeof event.tiltY === 'undefined') event.tiltY = 0; + if (typeof event.pointerType === 'undefined') event.pointerType = 'mouse'; + if (typeof event.pointerId === 'undefined') event.pointerId = MOUSE_POINTER_ID; + if (typeof event.pressure === 'undefined') event.pressure = 0.5; + if (typeof event.rotation === 'undefined') event.rotation = 0; + + // mark the mouse event as normalized, just so that we know we did it + event.isNormalized = true; + + normalizedEvents.push(event); + } else { + normalizedEvents.push(event); + } + + return normalizedEvents; + }; + + /** + * Destroys the interaction manager + * + */ + + + InteractionManager.prototype.destroy = function destroy() { + this.removeEvents(); + + this.removeAllListeners(); + + this.renderer = null; + + this.mouse = null; + + this.eventData = null; + + this.interactionDOMElement = null; + + this.onPointerDown = null; + this.processPointerDown = null; + + this.onPointerUp = null; + this.processPointerUp = null; + + this.onPointerCancel = null; + this.processPointerCancel = null; + + this.onPointerMove = null; + this.processPointerMove = null; + + this.onPointerOut = null; + this.processPointerOverOut = null; + + this.onPointerOver = null; + + this._tempPoint = null; + }; + + return InteractionManager; +}(_eventemitter2.default); + +exports.default = InteractionManager; + + +core.WebGLRenderer.registerPlugin('interaction', InteractionManager); +core.CanvasRenderer.registerPlugin('interaction', InteractionManager); + +},{"../core":63,"./InteractionData":150,"./InteractionEvent":151,"./InteractionTrackingData":153,"./interactiveTarget":155,"eventemitter3":3}],153:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * DisplayObjects with the {@link PIXI.interaction.interactiveTarget} mixin use this class to track interactions + * + * @class + * @private + * @memberof PIXI.interaction + */ +var InteractionTrackingData = function () { + /** + * @param {number} pointerId - Unique pointer id of the event + */ + function InteractionTrackingData(pointerId) { + _classCallCheck(this, InteractionTrackingData); + + this._pointerId = pointerId; + this._flags = InteractionTrackingData.FLAGS.NONE; + } + + /** + * + * @private + * @param {number} flag - The interaction flag to set + * @param {boolean} yn - Should the flag be set or unset + */ + + + InteractionTrackingData.prototype._doSet = function _doSet(flag, yn) { + if (yn) { + this._flags = this._flags | flag; + } else { + this._flags = this._flags & ~flag; + } + }; + + /** + * @readonly + * @type {number} Unique pointer id of the event + */ + + + _createClass(InteractionTrackingData, [{ + key: "pointerId", + get: function get() { + return this._pointerId; + } + + /** + * State of the tracking data, expressed as bit flags + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "flags", + get: function get() { + return this._flags; + } + + /** + * Set the flags for the tracking data + * + * @param {number} flags - Flags to set + */ + , + set: function set(flags) { + this._flags = flags; + } + + /** + * Is the tracked event inactive (not over or down)? + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "none", + get: function get() { + return this._flags === this.constructor.FLAGS.NONE; + } + + /** + * Is the tracked event over the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "over", + get: function get() { + return (this._flags & this.constructor.FLAGS.OVER) !== 0; + } + + /** + * Set the over flag + * + * @param {boolean} yn - Is the event over? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.OVER, yn); + } + + /** + * Did the right mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "rightDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.RIGHT_DOWN) !== 0; + } + + /** + * Set the right down flag + * + * @param {boolean} yn - Is the right mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.RIGHT_DOWN, yn); + } + + /** + * Did the left mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "leftDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.LEFT_DOWN) !== 0; + } + + /** + * Set the left down flag + * + * @param {boolean} yn - Is the left mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.LEFT_DOWN, yn); + } + }]); + + return InteractionTrackingData; +}(); + +exports.default = InteractionTrackingData; + + +InteractionTrackingData.FLAGS = Object.freeze({ + NONE: 0, + OVER: 1 << 0, + LEFT_DOWN: 1 << 1, + RIGHT_DOWN: 1 << 2 +}); + +},{}],154:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _InteractionData = require('./InteractionData'); + +Object.defineProperty(exports, 'InteractionData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionData).default; + } +}); + +var _InteractionManager = require('./InteractionManager'); + +Object.defineProperty(exports, 'InteractionManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionManager).default; + } +}); + +var _interactiveTarget = require('./interactiveTarget'); + +Object.defineProperty(exports, 'interactiveTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_interactiveTarget).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./InteractionData":150,"./InteractionManager":152,"./interactiveTarget":155}],155:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * Default property values of interactive objects + * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties + * + * @mixin + * @name interactiveTarget + * @memberof PIXI.interaction + * @example + * function MyObject() {} + * + * Object.assign( + * core.DisplayObject.prototype, + * PIXI.interaction.interactiveTarget + * ); + */ +exports.default = { + /** + * Determines if the displayObject be clicked/touched + * + * @inner {boolean} + */ + interactive: false, + + /** + * Determines if the children to the displayObject can be clicked/touched + * Setting this to false allows pixi to bypass a recursive hitTest function + * + * @inner {boolean} + */ + interactiveChildren: true, + + /** + * Interaction shape. Children will be hit first, then this shape will be checked. + * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. + * + * @inner {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle} + */ + hitArea: null, + + /** + * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive + * Setting this changes the 'cursor' property to `'pointer'`. + * + * @member {boolean} + * @memberof PIXI.interaction.interactiveTarget# + */ + get buttonMode() { + return this.cursor === 'pointer'; + }, + set buttonMode(value) { + if (value) { + this.cursor = 'pointer'; + } else if (this.cursor === 'pointer') { + this.cursor = null; + } + }, + + /** + * This defines what cursor mode is used when the mouse cursor + * is hovered over the displayObject. + * + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * + * @inner {string} + */ + cursor: null, + + /** + * Internal set of all active pointers, by identifier + * + * @member {Map} + * @memberof PIXI.interaction.interactiveTarget# + * @private + */ + get trackedPointers() { + if (this._trackedPointers === undefined) this._trackedPointers = {}; + + return this._trackedPointers; + }, + + /** + * Map of all tracked pointers, by identifier. Use trackedPointers to access. + * + * @private {Map} + */ + _trackedPointers: undefined +}; + +},{}],156:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.parse = parse; + +exports.default = function () { + return function bitmapFontParser(resource, next) { + // skip if no data or not xml data + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.XML) { + next(); + + return; + } + + // skip if not bitmap font data, using some silly duck-typing + if (resource.data.getElementsByTagName('page').length === 0 || resource.data.getElementsByTagName('info').length === 0 || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null) { + next(); + + return; + } + + var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; + + if (resource.isDataUrl) { + if (xmlUrl === '.') { + xmlUrl = ''; + } + + if (this.baseUrl && xmlUrl) { + // if baseurl has a trailing slash then add one to xmlUrl so the replace works below + if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { + xmlUrl += '/'; + } + + // remove baseUrl from xmlUrl + xmlUrl = xmlUrl.replace(this.baseUrl, ''); + } + } + + // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { + xmlUrl += '/'; + } + + var textureUrl = xmlUrl + resource.data.getElementsByTagName('page')[0].getAttribute('file'); + + if (_core.utils.TextureCache[textureUrl]) { + // reuse existing texture + parse(resource, _core.utils.TextureCache[textureUrl]); + next(); + } else { + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + // load the texture for the font + this.add(resource.name + '_image', textureUrl, loadOptions, function (res) { + parse(resource, res.texture); + next(); + }); + } + }; +}; + +var _path = require('path'); + +var path = _interopRequireWildcard(_path); + +var _core = require('../core'); + +var _resourceLoader = require('resource-loader'); + +var _extras = require('../extras'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Register a BitmapText font from loader resource. + * + * @function parseBitmapFontData + * @memberof PIXI.loaders + * @param {PIXI.loaders.Resource} resource - Loader resource. + * @param {PIXI.Texture} texture - Reference to texture. + */ +function parse(resource, texture) { + resource.bitmapFont = _extras.BitmapText.registerFont(resource.data, texture); +} + +},{"../core":63,"../extras":136,"path":22,"resource-loader":34}],157:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _loader = require('./loader'); + +Object.defineProperty(exports, 'Loader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_loader).default; + } +}); + +var _bitmapFontParser = require('./bitmapFontParser'); + +Object.defineProperty(exports, 'bitmapFontParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_bitmapFontParser).default; + } +}); +Object.defineProperty(exports, 'parseBitmapFontData', { + enumerable: true, + get: function get() { + return _bitmapFontParser.parse; + } +}); + +var _spritesheetParser = require('./spritesheetParser'); + +Object.defineProperty(exports, 'spritesheetParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_spritesheetParser).default; + } +}); + +var _textureParser = require('./textureParser'); + +Object.defineProperty(exports, 'textureParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_textureParser).default; + } +}); + +var _resourceLoader = require('resource-loader'); + +Object.defineProperty(exports, 'Resource', { + enumerable: true, + get: function get() { + return _resourceLoader.Resource; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./bitmapFontParser":156,"./loader":158,"./spritesheetParser":159,"./textureParser":160,"resource-loader":34}],158:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _resourceLoader = require('resource-loader'); + +var _resourceLoader2 = _interopRequireDefault(_resourceLoader); + +var _blob = require('resource-loader/lib/middlewares/parsing/blob'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _textureParser = require('./textureParser'); + +var _textureParser2 = _interopRequireDefault(_textureParser); + +var _spritesheetParser = require('./spritesheetParser'); + +var _spritesheetParser2 = _interopRequireDefault(_spritesheetParser); + +var _bitmapFontParser = require('./bitmapFontParser'); + +var _bitmapFontParser2 = _interopRequireDefault(_bitmapFontParser); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader + * + * ```js + * const loader = PIXI.loader; // pixi exposes a premade instance for you to use. + * //or + * const loader = new PIXI.loaders.Loader(); // you can also create your own if you want + * + * const sprites = {}; + * + * // Chainable `add` to enqueue a resource + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.add('scoreFont', 'assets/score.fnt'); + * + * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. + * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). + * loader.pre(cachingMiddleware); + * + * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. + * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). + * loader.use(parsingMiddleware); + * + * // The `load` method loads the queue of resources, and calls the passed in callback called once all + * // resources have loaded. + * loader.load((loader, resources) => { + * // resources is an object where the key is the name of the resource loaded and the value is the resource object. + * // They have a couple default properties: + * // - `url`: The URL that the resource was loaded from + * // - `error`: The error that happened when trying to load (if any) + * // - `data`: The raw data that was loaded + * // also may contain other properties based on the middleware that runs. + * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); + * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); + * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); + * }); + * + * // throughout the process multiple signals can be dispatched. + * loader.onProgress.add(() => {}); // called once per loaded/errored file + * loader.onError.add(() => {}); // called once per errored file + * loader.onLoad.add(() => {}); // called once per loaded file + * loader.onComplete.add(() => {}); // called once when the queued resources all load. + * ``` + * + * @see https://github.com/englercj/resource-loader + * + * @class + * @extends module:resource-loader.ResourceLoader + * @memberof PIXI.loaders + */ +var Loader = function (_ResourceLoader) { + _inherits(Loader, _ResourceLoader); + + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + _classCallCheck(this, Loader); + + var _this = _possibleConstructorReturn(this, _ResourceLoader.call(this, baseUrl, concurrency)); + + _eventemitter2.default.call(_this); + + for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { + _this.use(Loader._pixiMiddleware[i]()); + } + + // Compat layer, translate the new v2 signals into old v1 events. + _this.onStart.add(function (l) { + return _this.emit('start', l); + }); + _this.onProgress.add(function (l, r) { + return _this.emit('progress', l, r); + }); + _this.onError.add(function (e, l, r) { + return _this.emit('error', e, l, r); + }); + _this.onLoad.add(function (l, r) { + return _this.emit('load', l, r); + }); + _this.onComplete.add(function (l, r) { + return _this.emit('complete', l, r); + }); + return _this; + } + + /** + * Adds a default middleware to the pixi loader. + * + * @static + * @param {Function} fn - The middleware to add. + */ + + + Loader.addPixiMiddleware = function addPixiMiddleware(fn) { + Loader._pixiMiddleware.push(fn); + }; + + return Loader; +}(_resourceLoader2.default); + +// Copy EE3 prototype (mixin) + + +exports.default = Loader; +for (var k in _eventemitter2.default.prototype) { + Loader.prototype[k] = _eventemitter2.default.prototype[k]; +} + +Loader._pixiMiddleware = [ +// parse any blob into more usable objects (e.g. Image) +_blob.blobMiddlewareFactory, +// parse any Image objects into textures +_textureParser2.default, +// parse any spritesheet data into multiple textures +_spritesheetParser2.default, +// parse bitmap font data into multiple textures +_bitmapFontParser2.default]; + +// Add custom extentions +var Resource = _resourceLoader2.default.Resource; + +Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); + +},{"./bitmapFontParser":156,"./spritesheetParser":159,"./textureParser":160,"eventemitter3":3,"resource-loader":34,"resource-loader/lib/middlewares/parsing/blob":35}],159:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function spritesheetParser(resource, next) { + var resourcePath = void 0; + var imageResourceName = resource.name + '_image'; + + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.JSON || !resource.data.frames || this.resources[imageResourceName]) { + next(); + + return; + } + + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + resourcePath = resource.data.meta.image; + } else { + resourcePath = _path2.default.dirname(resource.url.replace(this.baseUrl, '')) + '/' + resource.data.meta.image; + } + + // load the image for this sheet + this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + var spritesheet = new _core.Spritesheet(res.texture.baseTexture, resource.data, resource.url); + + spritesheet.parse(function () { + resource.spritesheet = spritesheet; + resource.textures = spritesheet.textures; + next(); + }); + }); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _path = require('path'); + +var _path2 = _interopRequireDefault(_path); + +var _core = require('../core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"../core":63,"path":22,"resource-loader":34}],160:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function textureParser(resource, next) { + // create a new texture if the data is an Image object + if (resource.data && resource.type === _resourceLoader.Resource.TYPE.IMAGE) { + resource.texture = _Texture2.default.fromLoader(resource.data, resource.url, resource.name); + } + next(); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"../core/textures/Texture":112,"resource-loader":34}],161:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); +var tempPolygon = new core.Polygon(); + +/** + * Base mesh class + * @class + * @extends PIXI.Container + * @memberof PIXI.mesh + */ + +var Mesh = function (_core$Container) { + _inherits(Mesh, _core$Container); + + /** + * @param {PIXI.Texture} texture - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts + */ + function Mesh(texture, vertices, uvs, indices, drawMode) { + _classCallCheck(this, Mesh); + + /** + * The texture of the Mesh + * + * @member {PIXI.Texture} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._texture = null; + + /** + * The Uvs of the Mesh + * + * @member {Float32Array} + */ + _this.uvs = uvs || new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + /** + * An array of vertices + * + * @member {Float32Array} + */ + _this.vertices = vertices || new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]); + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + // TODO auto generate this based on draw mode! + _this.indices = indices || new Uint16Array([0, 1, 3, 2]); + + /** + * Version of mesh uvs are dirty or not + * + * @member {number} + */ + _this.dirty = 0; + + /** + * Version of mesh indices + * + * @member {number} + */ + _this.indexDirty = 0; + + /** + * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove + * any blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles + * to overlap a bit with each other. + * + * @member {number} + */ + _this.canvasPadding = 0; + + /** + * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts + * + * @member {number} + * @see PIXI.mesh.Mesh.DRAW_MODES + */ + _this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH; + + // run texture setter; + _this.texture = texture; + + /** + * The default shader that is used if a mesh doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + _this.shader = null; + + /** + * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any + * tint effect. + * + * @member {number} + */ + _this.tintRgb = new Float32Array([1, 1, 1]); + + /** + * A map of renderer IDs to webgl render data + * + * @private + * @member {object} + */ + _this._glDatas = {}; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * + * @member {string} + * @default 'mesh' + */ + _this.pluginName = 'mesh'; + return _this; + } + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - a reference to the WebGL renderer + */ + + + Mesh.prototype._renderWebGL = function _renderWebGL(renderer) { + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + + + Mesh.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins[this.pluginName].render(this); + }; + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Mesh.prototype._onTextureUpdate = function _onTextureUpdate() {} + /* empty */ + + + /** + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + */ + ; + + Mesh.prototype._calculateBounds = function _calculateBounds() { + // TODO - we can cache local bounds and use them if they are dirty (like graphics) + this._bounds.addVertices(this.transform, this.vertices, 0, this.vertices.length); + }; + + /** + * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Mesh.prototype.containsPoint = function containsPoint(point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + + this.worldTransform.applyInverse(point, tempPoint); + + var vertices = this.vertices; + var points = tempPolygon.points; + var indices = this.indices; + var len = this.indices.length; + var step = this.drawMode === Mesh.DRAW_MODES.TRIANGLES ? 3 : 1; + + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + + return false; + }; + + /** + * The texture that the mesh uses. + * + * @member {PIXI.Texture} + */ + + + _createClass(Mesh, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + + /** + * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return core.utils.rgb2hex(this.tintRgb); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tintRgb = core.utils.hex2rgb(value, this.tintRgb); + } + }]); + + return Mesh; +}(core.Container); + +/** + * Different drawing buffer modes supported + * + * @static + * @constant + * @type {object} + * @property {number} TRIANGLE_MESH + * @property {number} TRIANGLES + */ + + +exports.default = Mesh; +Mesh.DRAW_MODES = { + TRIANGLE_MESH: 0, + TRIANGLES: 1 +}; + +},{"../core":63}],162:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Plane2 = require('./Plane'); + +var _Plane3 = _interopRequireDefault(_Plane2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DEFAULT_BORDER_SIZE = 10; + +/** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.fromImage('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
+ *      A                          B
+ *    +---+----------------------+---+
+ *  C | 1 |          2           | 3 |
+ *    +---+----------------------+---+
+ *    |   |                      |   |
+ *    | 4 |          5           | 6 |
+ *    |   |                      |   |
+ *    +---+----------------------+---+
+ *  D | 7 |          8           | 9 |
+ *    +---+----------------------+---+
+
+ *  When changing this objects width and/or height:
+ *     areas 1 3 7 and 9 will remain unscaled.
+ *     areas 2 and 8 will be stretched horizontally
+ *     areas 4 and 6 will be stretched vertically
+ *     area 5 will be stretched both horizontally and vertically
+ * 
+ * + * @class + * @extends PIXI.mesh.Plane + * @memberof PIXI.mesh + * + */ + +var NineSlicePlane = function (_Plane) { + _inherits(NineSlicePlane, _Plane); + + /** + * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. + * @param {int} [leftWidth=10] size of the left vertical bar (A) + * @param {int} [topHeight=10] size of the top horizontal bar (C) + * @param {int} [rightWidth=10] size of the right vertical bar (B) + * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) + */ + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + _classCallCheck(this, NineSlicePlane); + + var _this = _possibleConstructorReturn(this, _Plane.call(this, texture, 4, 4)); + + var uvs = _this.uvs; + + // right and bottom uv's are always 1 + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + + _this._origWidth = texture.width; + _this._origHeight = texture.height; + _this._uvw = 1 / _this._origWidth; + _this._uvh = 1 / _this._origHeight; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.width = texture.width; + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.height = texture.height; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _this._uvw * leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - _this._uvw * rightWidth; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _this._uvh * topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - _this._uvh * bottomHeight; + + /** + * The width of the left column (a) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; + + /** + * The width of the right column (b) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; + + /** + * The height of the top row (c) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; + + /** + * The height of the bottom row (d) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; + return _this; + } + + /** + * Updates the horizontal vertices. + * + */ + + + NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices() { + var vertices = this.vertices; + + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight; + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + }; + + /** + * Updates the vertical vertices. + * + */ + + + NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices() { + var vertices = this.vertices; + + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth; + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with. + */ + + + NineSlicePlane.prototype._renderCanvas = function _renderCanvas(renderer) { + var context = renderer.context; + + context.globalAlpha = this.worldAlpha; + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + var base = this._texture.baseTexture; + var textureSource = base.source; + var w = base.width; + var h = base.height; + + this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11); + this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13); + this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15); + this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19); + this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21); + this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23); + this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27); + this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29); + this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31); + }; + + /** + * Renders one segment of the plane. + * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure + * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used. + * + * @private + * @param {CanvasRenderingContext2D} context - The context to draw with. + * @param {CanvasImageSource} textureSource - The source to draw. + * @param {number} w - width of the texture + * @param {number} h - height of the texture + * @param {number} x1 - x index 1 + * @param {number} y1 - y index 1 + * @param {number} x2 - x index 2 + * @param {number} y2 - y index 2 + */ + + + NineSlicePlane.prototype.drawSegment = function drawSegment(context, textureSource, w, h, x1, y1, x2, y2) { + // otherwise you get weird results when using slices of that are 0 wide or high. + var uvs = this.uvs; + var vertices = this.vertices; + + var sw = (uvs[x2] - uvs[x1]) * w; + var sh = (uvs[y2] - uvs[y1]) * h; + var dw = vertices[x2] - vertices[x1]; + var dh = vertices[y2] - vertices[y1]; + + // make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn. + if (sw < 1) { + sw = 1; + } + + if (sh < 1) { + sh = 1; + } + + // make sure destination is at least 1 pixel wide and high, otherwise you get + // lines when rendering close to original size. + if (dw < 1) { + dw = 1; + } + + if (dh < 1) { + dh = 1; + } + + context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh); + }; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + + _createClass(NineSlicePlane, [{ + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + this.updateVerticalVertices(); + } + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + this.updateHorizontalVertices(); + } + + /** + * The width of the left column + * + * @member {number} + */ + + }, { + key: 'leftWidth', + get: function get() { + return this._leftWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._leftWidth = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = this._uvw * value; + vertices[2] = vertices[10] = vertices[18] = vertices[26] = value; + + this.dirty = true; + } + + /** + * The width of the right column + * + * @member {number} + */ + + }, { + key: 'rightWidth', + get: function get() { + return this._rightWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rightWidth = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - this._uvw * value; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - value; + + this.dirty = true; + } + + /** + * The height of the top row + * + * @member {number} + */ + + }, { + key: 'topHeight', + get: function get() { + return this._topHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._topHeight = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[9] = uvs[11] = uvs[13] = uvs[15] = this._uvh * value; + vertices[9] = vertices[11] = vertices[13] = vertices[15] = value; + + this.dirty = true; + } + + /** + * The height of the bottom row + * + * @member {number} + */ + + }, { + key: 'bottomHeight', + get: function get() { + return this._bottomHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._bottomHeight = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - this._uvh * value; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - value; + + this.dirty = true; + } + }]); + + return NineSlicePlane; +}(_Plane3.default); + +exports.default = NineSlicePlane; + +},{"./Plane":163}],163:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The Plane allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Plane = function (_Mesh) { + _inherits(Plane, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the Plane. + * @param {number} verticesX - The number of vertices in the x-axis + * @param {number} verticesY - The number of vertices in the y-axis + */ + function Plane(texture, verticesX, verticesY) { + _classCallCheck(this, Plane); + + /** + * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this._ready = true; + + _this.verticesX = verticesX || 10; + _this.verticesY = verticesY || 10; + + _this.drawMode = _Mesh3.default.DRAW_MODES.TRIANGLES; + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Plane.prototype.refresh = function refresh() { + var total = this.verticesX * this.verticesY; + var verts = []; + var colors = []; + var uvs = []; + var indices = []; + var texture = this.texture; + + var segmentsX = this.verticesX - 1; + var segmentsY = this.verticesY - 1; + + var sizeX = texture.width / segmentsX; + var sizeY = texture.height / segmentsY; + + for (var i = 0; i < total; i++) { + if (texture._uvs) { + var x = i % this.verticesX; + var y = i / this.verticesX | 0; + + verts.push(x * sizeX, y * sizeY); + + // this works for rectangular textures. + uvs.push(texture._uvs.x0 + (texture._uvs.x1 - texture._uvs.x0) * (x / (this.verticesX - 1)), texture._uvs.y0 + (texture._uvs.y3 - texture._uvs.y0) * (y / (this.verticesY - 1))); + } else { + uvs.push(0); + } + } + + // cons + + var totalSub = segmentsX * segmentsY; + + for (var _i = 0; _i < totalSub; _i++) { + var xpos = _i % segmentsX; + var ypos = _i / segmentsX | 0; + + var value = ypos * this.verticesX + xpos; + var value2 = ypos * this.verticesX + xpos + 1; + var value3 = (ypos + 1) * this.verticesX + xpos; + var value4 = (ypos + 1) * this.verticesX + xpos + 1; + + indices.push(value, value2, value3); + indices.push(value2, value4, value3); + } + + // console.log(indices) + this.vertices = new Float32Array(verts); + this.uvs = new Float32Array(uvs); + this.colors = new Float32Array(colors); + this.indices = new Uint16Array(indices); + + this.indexDirty = true; + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Plane.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh3.default.prototype._onTextureUpdate.call(this); + + // wait for the Plane ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + return Plane; +}(_Mesh3.default); + +exports.default = Plane; + +},{"./Mesh":161}],164:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The rope allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Rope = function (_Mesh) { + _inherits(Rope, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the rope. + * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. + */ + function Rope(texture, points) { + _classCallCheck(this, Rope); + + /* + * @member {PIXI.Point[]} An array of points that determine the rope + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this.points = points; + + /* + * @member {Float32Array} An array of vertices used to construct this rope. + */ + _this.vertices = new Float32Array(points.length * 4); + + /* + * @member {Float32Array} The WebGL Uvs of the rope. + */ + _this.uvs = new Float32Array(points.length * 4); + + /* + * @member {Float32Array} An array containing the color components + */ + _this.colors = new Float32Array(points.length * 2); + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + _this.indices = new Uint16Array(points.length * 2); + + /** + * Tracker for if the rope is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + _this._ready = true; + + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Rope.prototype.refresh = function refresh() { + var points = this.points; + + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1 || !this._texture._uvs) { + return; + } + + // if the number of points has changed we will need to recreate the arraybuffers + if (this.vertices.length / 4 !== points.length) { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + var textureUvs = this._texture._uvs; + var offset = new core.Point(textureUvs.x0, textureUvs.y0); + var factor = new core.Point(textureUvs.x2 - textureUvs.x0, Number(textureUvs.y2 - textureUvs.y0)); + + uvs[0] = 0 + offset.x; + uvs[1] = 0 + offset.y; + uvs[2] = 0 + offset.x; + uvs[3] = factor.y + offset.y; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + + for (var i = 1; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + var amount = i / (total - 1); + + uvs[index] = amount * factor.x + offset.x; + uvs[index + 1] = 0 + offset.y; + + uvs[index + 2] = amount * factor.x + offset.x; + uvs[index + 3] = factor.y + offset.y; + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + + // ensure that the changes are uploaded + this.dirty++; + this.indexDirty++; + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Rope.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh.prototype._onTextureUpdate.call(this); + + // wait for the Rope ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + Rope.prototype.updateTransform = function updateTransform() { + var points = this.points; + + if (points.length < 1) { + return; + } + + var lastPoint = points[0]; + var nextPoint = void 0; + var perpX = 0; + var perpY = 0; + + // this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } else { + nextPoint = point; + } + + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + + var ratio = (1 - i / (total - 1)) * 10; + + if (ratio > 1) { + ratio = 1; + } + + var perpLength = Math.sqrt(perpX * perpX + perpY * perpY); + var num = this._texture.height / 2; // (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; + + perpX /= perpLength; + perpY /= perpLength; + + perpX *= num; + perpY *= num; + + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + + lastPoint = point; + } + + this.containerUpdateTransform(); + }; + + return Rope; +}(_Mesh3.default); + +exports.default = Rope; + +},{"../core":63,"./Mesh":161}],165:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Renderer dedicated to meshes. + * + * @class + * @private + * @memberof PIXI + */ +var MeshSpriteRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The renderer this downport works for + */ + function MeshSpriteRenderer(renderer) { + _classCallCheck(this, MeshSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the Mesh + * + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var context = renderer.context; + + var transform = mesh.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + renderer.setBlendMode(mesh.blendMode); + + if (mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH) { + this._renderTriangleMesh(mesh); + } else { + this._renderTriangles(mesh); + } + }; + + /** + * Draws the object in Triangle Mesh mode + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype._renderTriangleMesh = function _renderTriangleMesh(mesh) { + // draw triangles!! + var length = mesh.vertices.length / 2; + + for (var i = 0; i < length - 2; i++) { + // draw some triangles! + var index = i * 2; + + this._renderDrawTriangle(mesh, index, index + 2, index + 4); + } + }; + + /** + * Draws the object in triangle mode using canvas + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + */ + + + MeshSpriteRenderer.prototype._renderTriangles = function _renderTriangles(mesh) { + // draw triangles!! + var indices = mesh.indices; + var length = indices.length; + + for (var i = 0; i < length; i += 3) { + // draw some triangles! + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderDrawTriangle(mesh, index0, index1, index2); + } + }; + + /** + * Draws one of the triangles that from the Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + * @param {number} index0 - the index of the first vertex + * @param {number} index1 - the index of the second vertex + * @param {number} index2 - the index of the third vertex + */ + + + MeshSpriteRenderer.prototype._renderDrawTriangle = function _renderDrawTriangle(mesh, index0, index1, index2) { + var context = this.renderer.context; + var uvs = mesh.uvs; + var vertices = mesh.vertices; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var base = texture.baseTexture; + var textureSource = base.source; + var textureWidth = base.width; + var textureHeight = base.height; + + var u0 = uvs[index0] * base.width; + var u1 = uvs[index1] * base.width; + var u2 = uvs[index2] * base.width; + var v0 = uvs[index0 + 1] * base.height; + var v1 = uvs[index1 + 1] * base.height; + var v2 = uvs[index2 + 1] * base.height; + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + if (mesh.canvasPadding > 0) { + var paddingX = mesh.canvasPadding / mesh.worldTransform.a; + var paddingY = mesh.canvasPadding / mesh.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt(normX * normX + normY * normY); + + x0 = centerX + normX / dist * (dist + paddingX); + y0 = centerY + normY / dist * (dist + paddingY); + + // + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x1 = centerX + normX / dist * (dist + paddingX); + y1 = centerY + normY / dist * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x2 = centerX + normX / dist * (dist + paddingX); + y2 = centerY + normY / dist * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2; + var deltaA = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2; + var deltaB = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2; + var deltaC = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2; + var deltaD = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2; + var deltaE = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2; + var deltaF = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2; + + context.transform(deltaA / delta, deltaD / delta, deltaB / delta, deltaE / delta, deltaC / delta, deltaF / delta); + + context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + + context.restore(); + }; + + /** + * Renders a flat Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - The Mesh to render + */ + + + MeshSpriteRenderer.prototype.renderMeshFlat = function renderMeshFlat(mesh) { + var context = this.renderer.context; + var vertices = mesh.vertices; + var length = vertices.length / 2; + + // this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; ++i) { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var y0 = vertices[index + 1]; + + var x1 = vertices[index + 2]; + var y1 = vertices[index + 3]; + + var x2 = vertices[index + 4]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + }; + + /** + * destroy the the renderer. + * + */ + + + MeshSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return MeshSpriteRenderer; +}(); + +exports.default = MeshSpriteRenderer; + + +core.CanvasRenderer.registerPlugin('mesh', MeshSpriteRenderer); + +},{"../../core":63,"../Mesh":161}],166:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh = require('./Mesh'); + +Object.defineProperty(exports, 'Mesh', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Mesh).default; + } +}); + +var _MeshRenderer = require('./webgl/MeshRenderer'); + +Object.defineProperty(exports, 'MeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_MeshRenderer).default; + } +}); + +var _CanvasMeshRenderer = require('./canvas/CanvasMeshRenderer'); + +Object.defineProperty(exports, 'CanvasMeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasMeshRenderer).default; + } +}); + +var _Plane = require('./Plane'); + +Object.defineProperty(exports, 'Plane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Plane).default; + } +}); + +var _NineSlicePlane = require('./NineSlicePlane'); + +Object.defineProperty(exports, 'NineSlicePlane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NineSlicePlane).default; + } +}); + +var _Rope = require('./Rope'); + +Object.defineProperty(exports, 'Rope', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rope).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./Mesh":161,"./NineSlicePlane":162,"./Plane":163,"./Rope":164,"./canvas/CanvasMeshRenderer":165,"./webgl/MeshRenderer":167}],167:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var MeshRenderer = function (_core$ObjectRenderer) { + _inherits(MeshRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function MeshRenderer(renderer) { + _classCallCheck(this, MeshRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + MeshRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 translationMatrix;\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n}\n', 'varying vec2 vTextureCoord;\nuniform float alpha;\nuniform vec3 tint;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * vec4(tint * alpha, alpha);\n}\n'); + }; + + /** + * renders mesh + * + * @param {PIXI.mesh.Mesh} mesh mesh instance + */ + + + MeshRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var gl = renderer.gl; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var glData = mesh._glDatas[renderer.CONTEXT_UID]; + + if (!glData) { + renderer.bindVao(null); + + glData = { + shader: this.shader, + vertexBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.vertices, gl.STREAM_DRAW), + uvBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.uvs, gl.STREAM_DRAW), + indexBuffer: _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, mesh.indices, gl.STATIC_DRAW), + // build the vao object that will render.. + vao: null, + dirty: mesh.dirty, + indexDirty: mesh.indexDirty + }; + + // build the vao object that will render.. + glData.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(glData.indexBuffer).addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0).addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); + + mesh._glDatas[renderer.CONTEXT_UID] = glData; + } + + renderer.bindVao(glData.vao); + + if (mesh.dirty !== glData.dirty) { + glData.dirty = mesh.dirty; + glData.uvBuffer.upload(mesh.uvs); + } + + if (mesh.indexDirty !== glData.indexDirty) { + glData.indexDirty = mesh.indexDirty; + glData.indexBuffer.upload(mesh.indices); + } + + glData.vertexBuffer.upload(mesh.vertices); + + renderer.bindShader(glData.shader); + + glData.shader.uniforms.uSampler = renderer.bindTexture(texture); + + renderer.state.setBlendMode(mesh.blendMode); + + glData.shader.uniforms.translationMatrix = mesh.worldTransform.toArray(true); + glData.shader.uniforms.alpha = mesh.worldAlpha; + glData.shader.uniforms.tint = mesh.tintRgb; + + var drawMode = mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + glData.vao.draw(drawMode, mesh.indices.length, 0); + }; + + return MeshRenderer; +}(core.ObjectRenderer); + +exports.default = MeshRenderer; + + +core.WebGLRenderer.registerPlugin('mesh', MeshRenderer); + +},{"../../core":63,"../Mesh":161,"path":22,"pixi-gl-core":12}],168:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that advanced + * functionality will not work. ParticleContainer implements only the basic object transform (position, scale, rotation). + * Any other functionality like tinting, masking, etc will not work on sprites in this batch. + * + * It's extremely easy to use : + * + * ```js + * let container = new ParticleContainer(); + * + * for (let i = 0; i < 100; ++i) + * { + * let sprite = new PIXI.Sprite.fromImage("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be renderer at the speed of light. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.particles + */ +var ParticleContainer = function (_core$Container) { + _inherits(ParticleContainer, _core$Container); + + /** + * @param {number} [maxSize=15000] - The maximum number of particles that can be renderer by the container. + * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.scale=false] - When true, scale be uploaded and applied. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.alpha=false] - When true, alpha be uploaded and applied. + * @param {number} [batchSize=15000] - Number of particles per batch. + */ + function ParticleContainer() { + var maxSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1500; + var properties = arguments[1]; + var batchSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 16384; + + _classCallCheck(this, ParticleContainer); + + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + var maxBatchSize = 16384; + + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + + if (batchSize > maxSize) { + batchSize = maxSize; + } + + /** + * Set properties to be dynamic (true) / static (false) + * + * @member {boolean[]} + * @private + */ + _this._properties = [false, true, false, false, false]; + + /** + * @member {number} + * @private + */ + _this._maxSize = maxSize; + + /** + * @member {number} + * @private + */ + _this._batchSize = batchSize; + + /** + * @member {object} + * @private + */ + _this._glBuffers = {}; + + /** + * @member {number} + * @private + */ + _this._bufferToUpdate = 0; + + /** + * @member {boolean} + * + */ + _this.interactiveChildren = false; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` + * to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Used for canvas renderering. If true then the elements will be positioned at the + * nearest pixel. This provides a nice speed boost. + * + * @member {boolean} + * @default true; + */ + _this.roundPixels = true; + + /** + * The texture used to render the children. + * + * @readonly + * @member {BaseTexture} + */ + _this.baseTexture = null; + + _this.setProperties(properties); + return _this; + } + + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * + * @param {object} properties - The properties to be uploaded + */ + + + ParticleContainer.prototype.setProperties = function setProperties(properties) { + if (properties) { + this._properties[0] = 'scale' in properties ? !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'alpha' in properties ? !!properties.alpha : this._properties[4]; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + ParticleContainer.prototype.updateTransform = function updateTransform() { + // TODO don't need to! + this.displayObjectUpdateTransform(); + // PIXI.Container.prototype.updateTransform.call( this ); + }; + + /** + * Renders the container using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer + */ + + + ParticleContainer.prototype.renderWebGL = function renderWebGL(renderer) { + var _this2 = this; + + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.hasLoaded) { + this.baseTexture.once('update', function () { + return _this2.onChildrenChange(0); + }); + } + } + + renderer.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + + /** + * Set the flag that static data should be updated to true + * + * @private + * @param {number} smallestChildIndex - The smallest child index + */ + + + ParticleContainer.prototype.onChildrenChange = function onChildrenChange(smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + + if (bufferIndex < this._bufferToUpdate) { + this._bufferToUpdate = bufferIndex; + } + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + + + ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var isRotated = true; + + var positionX = 0; + var positionY = 0; + + var finalWidth = 0; + var finalHeight = 0; + + var compositeOperation = renderer.blendModes[this.blendMode]; + + if (compositeOperation !== context.globalCompositeOperation) { + context.globalCompositeOperation = compositeOperation; + } + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i]; + + if (!child.visible) { + continue; + } + + var frame = child._texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) { + // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call + if (isRotated) { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx * renderer.resolution, transform.ty * renderer.resolution); + + isRotated = false; + } + + positionX = child.anchor.x * (-frame.width * child.scale.x) + child.position.x + 0.5; + positionY = child.anchor.y * (-frame.height * child.scale.y) + child.position.y + 0.5; + + finalWidth = frame.width * child.scale.x; + finalHeight = frame.height * child.scale.y; + } else { + if (!isRotated) { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + + if (renderer.roundPixels) { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution | 0, childTransform.ty * renderer.resolution | 0); + } else { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution, childTransform.ty * renderer.resolution); + } + + positionX = child.anchor.x * -frame.width + 0.5; + positionY = child.anchor.y * -frame.height + 0.5; + + finalWidth = frame.width; + finalHeight = frame.height; + } + + var resolution = child._texture.baseTexture.resolution; + + context.drawImage(child._texture.baseTexture.source, frame.x * resolution, frame.y * resolution, frame.width * resolution, frame.height * resolution, positionX * resolution, positionY * resolution, finalWidth * resolution, finalHeight * resolution); + } + }; + + /** + * Destroys the container + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + ParticleContainer.prototype.destroy = function destroy(options) { + _core$Container.prototype.destroy.call(this, options); + + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + } + + this._properties = null; + this._buffers = null; + }; + + return ParticleContainer; +}(core.Container); + +exports.default = ParticleContainer; + +},{"../core":63}],169:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ParticleContainer = require('./ParticleContainer'); + +Object.defineProperty(exports, 'ParticleContainer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleContainer).default; + } +}); + +var _ParticleRenderer = require('./webgl/ParticleRenderer'); + +Object.defineProperty(exports, 'ParticleRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleRenderer).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./ParticleContainer":168,"./webgl/ParticleRenderer":171}],170:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + +/** + * The particle buffer manages the static and dynamic buffers for a particle container. + * + * @class + * @private + * @memberof PIXI + */ +var ParticleBuffer = function () { + /** + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(gl, properties, dynamicPropertyFlags, size) { + _classCallCheck(this, ParticleBuffer); + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * Size of a single vertex. + * + * @member {number} + */ + this.vertSize = 2; + + /** + * Size of a single vertex in bytes. + * + * @member {number} + */ + this.vertByteSize = this.vertSize * 4; + + /** + * The number of particles the buffer can hold + * + * @member {number} + */ + this.size = size; + + /** + * A list of the properties that are dynamic. + * + * @member {object[]} + */ + this.dynamicProperties = []; + + /** + * A list of the properties that are static. + * + * @member {object[]} + */ + this.staticProperties = []; + + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attribute: property.attribute, + size: property.size, + uploadFunction: property.uploadFunction, + offset: property.offset + }; + + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } else { + this.staticProperties.push(property); + } + } + + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + + this.initBuffers(); + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + ParticleBuffer.prototype.initBuffers = function initBuffers() { + var gl = this.gl; + var dynamicOffset = 0; + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(this.size); + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + this.dynamicStride = 0; + + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + + this.dynamicData = new Float32Array(this.size * this.dynamicStride * 4); + this.dynamicBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.dynamicData, gl.STREAM_DRAW); + + // static // + var staticOffset = 0; + + this.staticStride = 0; + + for (var _i = 0; _i < this.staticProperties.length; ++_i) { + var _property = this.staticProperties[_i]; + + _property.offset = staticOffset; + staticOffset += _property.size; + this.staticStride += _property.size; + } + + this.staticData = new Float32Array(this.size * this.staticStride * 4); + this.staticBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.staticData, gl.STATIC_DRAW); + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(this.indexBuffer); + + for (var _i2 = 0; _i2 < this.dynamicProperties.length; ++_i2) { + var _property2 = this.dynamicProperties[_i2]; + + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.FLOAT, false, this.dynamicStride * 4, _property2.offset * 4); + } + + for (var _i3 = 0; _i3 < this.staticProperties.length; ++_i3) { + var _property3 = this.staticProperties[_i3]; + + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.FLOAT, false, this.staticStride * 4, _property3.offset * 4); + } + }; + + /** + * Uploads the dynamic properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadDynamic = function uploadDynamic(children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + + property.uploadFunction(children, startIndex, amount, this.dynamicData, this.dynamicStride, property.offset); + } + + this.dynamicBuffer.upload(); + }; + + /** + * Uploads the static properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadStatic = function uploadStatic(children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + + property.uploadFunction(children, startIndex, amount, this.staticData, this.staticStride, property.offset); + } + + this.staticBuffer.upload(); + }; + + /** + * Destroys the ParticleBuffer. + * + */ + + + ParticleBuffer.prototype.destroy = function destroy() { + this.dynamicProperties = null; + this.dynamicData = null; + this.dynamicBuffer.destroy(); + + this.staticProperties = null; + this.staticData = null; + this.staticBuffer.destroy(); + }; + + return ParticleBuffer; +}(); + +exports.default = ParticleBuffer; + +},{"../../core/utils/createIndicesForQuads":118,"pixi-gl-core":12}],171:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _ParticleShader = require('./ParticleShader'); + +var _ParticleShader2 = _interopRequireDefault(_ParticleShader); + +var _ParticleBuffer = require('./ParticleBuffer'); + +var _ParticleBuffer2 = _interopRequireDefault(_ParticleBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + +/** + * + * @class + * @private + * @memberof PIXI + */ +var ParticleRenderer = function (_core$ObjectRenderer) { + _inherits(ParticleRenderer, _core$ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + _classCallCheck(this, ParticleRenderer); + + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; + + /** + * The default shader that is used if a sprite doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + + _this.indexBuffer = null; + + _this.properties = null; + + _this.tempMatrix = new core.Matrix(); + + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * When there is a WebGL context change + * + * @private + */ + + + ParticleRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + + // setup default shader + this.shader = new _ParticleShader2.default(gl); + + this.properties = [ + // verticesData + { + attribute: this.shader.attributes.aVertexPosition, + size: 2, + uploadFunction: this.uploadVertices, + offset: 0 + }, + // positionData + { + attribute: this.shader.attributes.aPositionCoord, + size: 2, + uploadFunction: this.uploadPosition, + offset: 0 + }, + // rotationData + { + attribute: this.shader.attributes.aRotation, + size: 1, + uploadFunction: this.uploadRotation, + offset: 0 + }, + // uvsData + { + attribute: this.shader.attributes.aTextureCoord, + size: 2, + uploadFunction: this.uploadUvs, + offset: 0 + }, + // alphaData + { + attribute: this.shader.attributes.aColor, + size: 1, + uploadFunction: this.uploadAlpha, + offset: 0 + }]; + }; + + /** + * Starts a new particle batch. + * + */ + + + ParticleRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + }; + + /** + * Renders the particle container object. + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + */ + + + ParticleRenderer.prototype.render = function render(container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var renderer = this.renderer; + var totalChildren = children.length; + + if (totalChildren === 0) { + return; + } else if (totalChildren > maxSize) { + totalChildren = maxSize; + } + + var buffers = container._glBuffers[renderer.CONTEXT_UID]; + + if (!buffers) { + buffers = container._glBuffers[renderer.CONTEXT_UID] = this.generateBuffers(container); + } + + // if the uvs have not updated then no point rendering just yet! + this.renderer.setBlendMode(container.blendMode); + + var gl = renderer.gl; + + var m = container.worldTransform.copy(this.tempMatrix); + + m.prepend(renderer._activeRenderTarget.projectionMatrix); + + this.shader.uniforms.projectionMatrix = m.toArray(true); + this.shader.uniforms.uAlpha = container.worldAlpha; + + // make sure the texture is bound.. + var baseTexture = children[0]._texture.baseTexture; + + this.shader.uniforms.uSampler = renderer.bindTexture(baseTexture); + + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = totalChildren - i; + + if (amount > batchSize) { + amount = batchSize; + } + + var buffer = buffers[j]; + + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + + // we only upload the static content when we have to! + if (container._bufferToUpdate === j) { + buffer.uploadStatic(children, i, amount); + container._bufferToUpdate = j + 1; + } + + // bind the buffer + renderer.bindVao(buffer.vao); + buffer.vao.draw(gl.TRIANGLES, amount * 6); + } + }; + + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer[]} The buffers + */ + + + ParticleRenderer.prototype.generateBuffers = function generateBuffers(container) { + var gl = this.renderer.gl; + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + for (var i = 0; i < size; i += batchSize) { + buffers.push(new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize)); + } + + return buffers; + }; + + /** + * Uploads the verticies. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their vertices uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadVertices = function uploadVertices(children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - sprite.anchor.x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - sprite.anchor.y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - sprite.anchor.x); + w1 = orig.width * -sprite.anchor.x; + + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + + array[offset + stride * 2] = w0 * sx; + array[offset + stride * 2 + 1] = h0 * sy; + + array[offset + stride * 3] = w1 * sx; + array[offset + stride * 3 + 1] = h0 * sy; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their positions uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadPosition = function uploadPosition(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + + array[offset + stride * 2] = spritePosition.x; + array[offset + stride * 2 + 1] = spritePosition.y; + + array[offset + stride * 3] = spritePosition.x; + array[offset + stride * 3 + 1] = spritePosition.y; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadRotation = function uploadRotation(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + stride * 2] = spriteRotation; + array[offset + stride * 3] = spriteRotation; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadUvs = function uploadUvs(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + + array[offset + stride * 2] = textureUvs.x2; + array[offset + stride * 2 + 1] = textureUvs.y2; + + array[offset + stride * 3] = textureUvs.x3; + array[offset + stride * 3 + 1] = textureUvs.y3; + + offset += stride * 4; + } else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + + array[offset + stride * 2] = 0; + array[offset + stride * 2 + 1] = 0; + + array[offset + stride * 3] = 0; + array[offset + stride * 3 + 1] = 0; + + offset += stride * 4; + } + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadAlpha = function uploadAlpha(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteAlpha = children[startIndex + i].alpha; + + array[offset] = spriteAlpha; + array[offset + stride] = spriteAlpha; + array[offset + stride * 2] = spriteAlpha; + array[offset + stride * 3] = spriteAlpha; + + offset += stride * 4; + } + }; + + /** + * Destroys the ParticleRenderer. + * + */ + + + ParticleRenderer.prototype.destroy = function destroy() { + if (this.renderer.gl) { + this.renderer.gl.deleteBuffer(this.indexBuffer); + } + + _core$ObjectRenderer.prototype.destroy.call(this); + + this.shader.destroy(); + + this.indices = null; + this.tempMatrix = null; + }; + + return ParticleRenderer; +}(core.ObjectRenderer); + +exports.default = ParticleRenderer; + + +core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + +},{"../../core":63,"./ParticleBuffer":170,"./ParticleShader":172}],172:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../core/Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI + */ +var ParticleShader = function (_Shader) { + _inherits(ParticleShader, _Shader); + + /** + * @param {PIXI.Shader} gl - The webgl shader manager this shader works for. + */ + function ParticleShader(gl) { + _classCallCheck(this, ParticleShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'attribute float aColor;', 'attribute vec2 aPositionCoord;', 'attribute vec2 aScale;', 'attribute float aRotation;', 'uniform mat3 projectionMatrix;', 'varying vec2 vTextureCoord;', 'varying float vColor;', 'void main(void){', ' vec2 v = aVertexPosition;', ' v.x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);', ' v.y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);', ' v = v + aPositionCoord;', ' gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = aColor;', '}'].join('\n'), + // hello + ['varying vec2 vTextureCoord;', 'varying float vColor;', 'uniform sampler2D uSampler;', 'uniform float uAlpha;', 'void main(void){', ' vec4 color = texture2D(uSampler, vTextureCoord) * vColor * uAlpha;', ' if (color.a == 0.0) discard;', ' gl_FragColor = color;', '}'].join('\n'))); + } + + return ParticleShader; +}(_Shader3.default); + +exports.default = ParticleShader; + +},{"../../core/Shader":42}],173:[function(require,module,exports){ +"use strict"; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + +if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + + if (x === 0 || isNaN(x)) { + return x; + } + + return x > 0 ? 1 : -1; + }; +} + +},{}],174:[function(require,module,exports){ +'use strict'; + +var _objectAssign = require('object-assign'); + +var _objectAssign2 = _interopRequireDefault(_objectAssign); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +if (!Object.assign) { + Object.assign = _objectAssign2.default; +} // References: +// https://github.com/sindresorhus/object-assign +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + +},{"object-assign":5}],175:[function(require,module,exports){ +'use strict'; + +require('./Object.assign'); + +require('./requestAnimationFrame'); + +require('./Math.sign'); + +if (!window.ArrayBuffer) { + window.ArrayBuffer = Array; +} + +if (!window.Float32Array) { + window.Float32Array = Array; +} + +if (!window.Uint32Array) { + window.Uint32Array = Array; +} + +if (!window.Uint16Array) { + window.Uint16Array = Array; +} + +},{"./Math.sign":173,"./Object.assign":174,"./requestAnimationFrame":176}],176:[function(require,module,exports){ +(function (global){ +'use strict'; + +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + +// Expected to be used with Browserfiy +// Browserify automatically detects the use of `global` and passes the +// correct reference of `global`, `self`, and finally `window` + +var ONE_FRAME_TIME = 16; + +// Date.now +if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; +} + +// performance.now +if (!(global.performance && global.performance.now)) { + (function () { + var startTime = Date.now(); + + if (!global.performance) { + global.performance = {}; + } + + global.performance.now = function () { + return Date.now() - startTime; + }; + })(); +} + +// requestAnimationFrame +var lastTime = Date.now(); +var vendors = ['ms', 'moz', 'webkit', 'o']; + +for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { + var p = vendors[x]; + + global.requestAnimationFrame = global[p + 'RequestAnimationFrame']; + global.cancelAnimationFrame = global[p + 'CancelAnimationFrame'] || global[p + 'CancelRequestAnimationFrame']; +} + +if (!global.requestAnimationFrame) { + global.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + 'is not a function'); + } + + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + + if (delay < 0) { + delay = 0; + } + + lastTime = currentTime; + + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} + +if (!global.cancelAnimationFrame) { + global.cancelAnimationFrame = function (id) { + return clearTimeout(id); + }; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],177:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CountLimiter = require('./limiters/CountLimiter'); + +var _CountLimiter2 = _interopRequireDefault(_CountLimiter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SharedTicker = core.ticker.shared; + +/** + * Default number of uploads per frame using prepare plugin. + * + * @static + * @memberof PIXI.settings + * @name UPLOADS_PER_FRAME + * @type {number} + * @default 4 + */ +core.settings.UPLOADS_PER_FRAME = 4; + +/** + * The prepare manager provides functionality to upload content to the GPU. BasePrepare handles + * basic queuing functionality and is extended by {@link PIXI.prepare.WebGLPrepare} and {@link PIXI.prepare.CanvasPrepare} + * to provide preparation capabilities specific to their respective renderers. + * + * @abstract + * @class + * @memberof PIXI.prepare + */ + +var BasePrepare = function () { + /** + * @param {PIXI.SystemRenderer} renderer - A reference to the current renderer + */ + function BasePrepare(renderer) { + var _this = this; + + _classCallCheck(this, BasePrepare); + + /** + * The limiter to be used to control how quickly items are prepared. + * @type {PIXI.prepare.CountLimiter|PIXI.prepare.TimeLimiter} + */ + this.limiter = new _CountLimiter2.default(core.settings.UPLOADS_PER_FRAME); + + /** + * Reference to the renderer. + * @type {PIXI.SystemRenderer} + * @protected + */ + this.renderer = renderer; + + /** + * The only real difference between CanvasPrepare and WebGLPrepare is what they pass + * to upload hooks. That different parameter is stored here. + * @type {PIXI.prepare.CanvasPrepare|PIXI.WebGLRenderer} + * @protected + */ + this.uploadHookHelper = null; + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + /** + * 'bound' call for prepareItems(). + * @type {Function} + * @private + */ + this.delayedTick = function () { + // unlikely, but in case we were destroyed between tick() and delayedTick() + if (!_this.queue) { + return; + } + _this.prepareItems(); + }; + + this.register(findText, drawText); + this.register(findTextStyle, calculateTextStyle); + } + + /** + * Upload all the textures and graphics to the GPU. + * + * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item - + * Either the container or display object to search for items to upload, the items to upload themselves, + * or the callback function, if items have been added using `prepare.add`. + * @param {Function} [done] - Optional callback when all queued uploads have completed + */ + + + BasePrepare.prototype.upload = function upload(item, done) { + if (typeof item === 'function') { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) { + if (done) { + this.completes.push(done); + } + + if (!this.ticking) { + this.ticking = true; + SharedTicker.addOnce(this.tick, this); + } + } else if (done) { + done(); + } + }; + + /** + * Handle tick update + * + * @private + */ + + + BasePrepare.prototype.tick = function tick() { + setTimeout(this.delayedTick, 0); + }; + + /** + * Actually prepare items. This is handled outside of the tick because it will take a while + * and we do NOT want to block the current animation frame from rendering. + * + * @private + */ + + + BasePrepare.prototype.prepareItems = function prepareItems() { + this.limiter.beginFrame(); + // Upload the graphics + while (this.queue.length && this.limiter.allowedToUpload()) { + var item = this.queue[0]; + var uploaded = false; + + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.uploadHookHelper, item)) { + this.queue.shift(); + uploaded = true; + break; + } + } + + if (!uploaded) { + this.queue.shift(); + } + } + + // We're finished + if (!this.queue.length) { + this.ticking = false; + + var completes = this.completes.slice(0); + + this.completes.length = 0; + + for (var _i = 0, _len = completes.length; _i < _len; _i++) { + completes[_i](); + } + } else { + // if we are not finished, on the next rAF do this again + SharedTicker.addOnce(this.tick, this); + } + }; + + /** + * Adds hooks for finding and uploading items. + * + * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array` + function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.register = function register(addHook, uploadHook) { + if (addHook) { + this.addHooks.push(addHook); + } + + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + + return this; + }; + + /** + * Manually add an item to the uploading queue. + * + * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to + * add to the queue + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.add = function add(item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) { + for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { + this.add(item.children[_i2]); + } + } + + return this; + }; + + /** + * Destroys the plugin, don't use after this. + * + */ + + + BasePrepare.prototype.destroy = function destroy() { + if (this.ticking) { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.limiter = null; + this.uploadHookHelper = null; + }; + + return BasePrepare; +}(); + +/** + * Built-in hook to draw PIXI.Text to its texture. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = BasePrepare; +function drawText(helper, item) { + if (item instanceof core.Text) { + // updating text will return early if it is not dirty + item.updateText(true); + + return true; + } + + return false; +} + +/** + * Built-in hook to calculate a text style for a PIXI.Text object. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function calculateTextStyle(helper, item) { + if (item instanceof core.TextStyle) { + var font = core.Text.getFontStyle(item); + + if (!core.Text.fontPropertiesCache[font]) { + core.Text.calculateFontProperties(font); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find Text objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Text object was found. + */ +function findText(item, queue) { + if (item instanceof core.Text) { + // push the text style to prepare it - this can be really expensive + if (queue.indexOf(item.style) === -1) { + queue.push(item.style); + } + // also push the text object so that we can render it (to canvas/texture) if needed + if (queue.indexOf(item) === -1) { + queue.push(item); + } + // also push the Text's texture for upload to GPU + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find TextStyle objects. + * + * @private + * @param {PIXI.TextStyle} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.TextStyle object was found. + */ +function findTextStyle(item, queue) { + if (item instanceof core.TextStyle) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +},{"../core":63,"./limiters/CountLimiter":180}],178:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CANVAS_START_SIZE = 16; + +/** + * The prepare manager provides functionality to upload content to the GPU + * This cannot be done directly for Canvas like in WebGL, but the effect can be achieved by drawing + * textures to an offline canvas. + * This draw call will force the texture to be moved onto the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ + +var CanvasPrepare = function (_BasePrepare) { + _inherits(CanvasPrepare, _BasePrepare); + + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasPrepare(renderer) { + _classCallCheck(this, CanvasPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this; + + /** + * An offline canvas to render textures to + * @type {HTMLCanvasElement} + * @private + */ + _this.canvas = document.createElement('canvas'); + _this.canvas.width = CANVAS_START_SIZE; + _this.canvas.height = CANVAS_START_SIZE; + + /** + * The context to the canvas + * @type {CanvasRenderingContext2D} + * @private + */ + _this.ctx = _this.canvas.getContext('2d'); + + // Add textures to upload + _this.register(findBaseTextures, uploadBaseTextures); + return _this; + } + + /** + * Destroys the plugin, don't use after this. + * + */ + + + CanvasPrepare.prototype.destroy = function destroy() { + _BasePrepare.prototype.destroy.call(this); + this.ctx = null; + this.canvas = null; + }; + + return CanvasPrepare; +}(_BasePrepare3.default); + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {*} prepare - Instance of CanvasPrepare + * @param {*} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = CanvasPrepare; +function uploadBaseTextures(prepare, item) { + if (item instanceof core.BaseTexture) { + var image = item.source; + + // Sometimes images (like atlas images) report a size of zero, causing errors on windows phone. + // So if the width or height is equal to zero then use the canvas size + // Otherwise use whatever is smaller, the image dimensions or the canvas dimensions. + var imageWidth = image.width === 0 ? prepare.canvas.width : Math.min(prepare.canvas.width, image.width); + var imageHeight = image.height === 0 ? prepare.canvas.height : Math.min(prepare.canvas.height, image.height); + + // Only a small subsections is required to be drawn to have the whole texture uploaded to the GPU + // A smaller draw can be faster. + prepare.ctx.drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, prepare.canvas.width, prepare.canvas.height); + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item -Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTextures(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } else if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); + +},{"../../core":63,"../BasePrepare":177}],179:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLPrepare = require('./webgl/WebGLPrepare'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLPrepare).default; + } +}); + +var _CanvasPrepare = require('./canvas/CanvasPrepare'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasPrepare).default; + } +}); + +var _BasePrepare = require('./BasePrepare'); + +Object.defineProperty(exports, 'BasePrepare', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BasePrepare).default; + } +}); + +var _CountLimiter = require('./limiters/CountLimiter'); + +Object.defineProperty(exports, 'CountLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CountLimiter).default; + } +}); + +var _TimeLimiter = require('./limiters/TimeLimiter'); + +Object.defineProperty(exports, 'TimeLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TimeLimiter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./BasePrepare":177,"./canvas/CanvasPrepare":178,"./limiters/CountLimiter":180,"./limiters/TimeLimiter":181,"./webgl/WebGLPrepare":182}],180:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * CountLimiter limits the number of items handled by a {@link PIXI.prepare.BasePrepare} to a specified + * number of items per frame. + * + * @class + * @memberof PIXI + */ +var CountLimiter = function () { + /** + * @param {number} maxItemsPerFrame - The maximum number of items that can be prepared each frame. + */ + function CountLimiter(maxItemsPerFrame) { + _classCallCheck(this, CountLimiter); + + /** + * The maximum number of items that can be prepared each frame. + * @private + */ + this.maxItemsPerFrame = maxItemsPerFrame; + /** + * The number of items that can be prepared in the current frame. + * @type {number} + * @private + */ + this.itemsLeft = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + CountLimiter.prototype.beginFrame = function beginFrame() { + this.itemsLeft = this.maxItemsPerFrame; + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + CountLimiter.prototype.allowedToUpload = function allowedToUpload() { + return this.itemsLeft-- > 0; + }; + + return CountLimiter; +}(); + +exports.default = CountLimiter; + +},{}],181:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of milliseconds per frame. + * + * @class + * @memberof PIXI + */ +var TimeLimiter = function () { + /** + * @param {number} maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. + */ + function TimeLimiter(maxMilliseconds) { + _classCallCheck(this, TimeLimiter); + + /** + * The maximum milliseconds that can be spent preparing items each frame. + * @private + */ + this.maxMilliseconds = maxMilliseconds; + /** + * The start time of the current frame. + * @type {number} + * @private + */ + this.frameStart = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + TimeLimiter.prototype.beginFrame = function beginFrame() { + this.frameStart = Date.now(); + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + TimeLimiter.prototype.allowedToUpload = function allowedToUpload() { + return Date.now() - this.frameStart < this.maxMilliseconds; + }; + + return TimeLimiter; +}(); + +exports.default = TimeLimiter; + +},{}],182:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The prepare manager provides functionality to upload content to the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ +var WebGLPrepare = function (_BasePrepare) { + _inherits(WebGLPrepare, _BasePrepare); + + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLPrepare(renderer) { + _classCallCheck(this, WebGLPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this.renderer; + + // Add textures and graphics to upload + _this.register(findBaseTextures, uploadBaseTextures).register(findGraphics, uploadGraphics); + return _this; + } + + return WebGLPrepare; +}(_BasePrepare3.default); + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = WebGLPrepare; +function uploadBaseTextures(renderer, item) { + if (item instanceof core.BaseTexture) { + // if the texture already has a GL texture, then the texture has been prepared or rendered + // before now. If the texture changed, then the changer should be calling texture.update() which + // reuploads the texture without need for preparing it again + if (!item._glTextures[renderer.CONTEXT_UID]) { + renderer.textureManager.updateTexture(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to upload PIXI.Graphics to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadGraphics(renderer, item) { + if (item instanceof core.Graphics) { + // if the item is not dirty and already has webgl data, then it got prepared or rendered + // before now and we shouldn't waste time updating it again + if (item.dirty || item.clearDirty || !item._webGL[renderer.plugins.graphics.CONTEXT_UID]) { + renderer.plugins.graphics.updateGraphics(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTextures(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } else if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find graphics. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Graphics object was found. + */ +function findGraphics(item, queue) { + if (item instanceof core.Graphics) { + queue.push(item); + + return true; + } + + return false; +} + +core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); + +},{"../../core":63,"../BasePrepare":177}],183:[function(require,module,exports){ +(function (global){ +'use strict'; + +exports.__esModule = true; +exports.loader = exports.prepare = exports.particles = exports.mesh = exports.loaders = exports.interaction = exports.filters = exports.extras = exports.extract = exports.accessibility = undefined; + +var _polyfill = require('./polyfill'); + +Object.keys(_polyfill).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _polyfill[key]; + } + }); +}); + +var _deprecation = require('./deprecation'); + +Object.keys(_deprecation).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _deprecation[key]; + } + }); +}); + +var _core = require('./core'); + +Object.keys(_core).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _core[key]; + } + }); +}); + +var _accessibility = require('./accessibility'); + +var accessibility = _interopRequireWildcard(_accessibility); + +var _extract = require('./extract'); + +var extract = _interopRequireWildcard(_extract); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// export libs + + +// export core +_core.utils.mixins.performMixins(); + +// handle mixins now, after all code has been added, including deprecation +// import polyfills. Done as an export to make sure polyfills are imported first +exports.accessibility = accessibility; +exports.extract = extract; +exports.extras = extras; +exports.filters = filters; +exports.interaction = interaction; +exports.loaders = loaders; +exports.mesh = mesh; +exports.particles = particles; +exports.prepare = prepare; + +/** + * A premade instance of the loader that can be used to load resources. + * + * @name loader + * @memberof PIXI + * @property {PIXI.loaders.Loader} + */ + +var loader = loaders && loaders.Loader ? new loaders.Loader() : null; // check is there in case user excludes loader lib + +exports.loader = loader; + +// Always export pixi globally. + +global.PIXI = exports; // eslint-disable-line + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"./accessibility":40,"./core":63,"./deprecation":125,"./extract":127,"./extras":136,"./filters":147,"./interaction":154,"./loaders":157,"./mesh":166,"./particles":169,"./polyfill":175,"./prepare":179}]},{},[183])(183) +}); + + +//# sourceMappingURL=pixi.js.map diff --git a/js/pixi/4.4.0/pixi.min.js b/js/pixi/4.4.0/pixi.min.js new file mode 100644 index 0000000..78da1b2 --- /dev/null +++ b/js/pixi/4.4.0/pixi.min.js @@ -0,0 +1,21 @@ +/*! + * pixi.js - v4.4.0 + * Compiled Wed, 22 Feb 2017 17:51:14 UTC + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.PIXI=t()}}(function(){var t;return function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var h=r[s]={exports:{}};e[s][0].call(h.exports,function(t){var r=e[s][1][t];return i(r?r:t)},h,h.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s0)-(t<0)},r.abs=function(t){var e=t>>i-1;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,e|=r,e|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,t=(858993459&t)+(t>>>2&858993459),16843009*(t+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,t&=15,27030>>>t&1};var o=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|o[t>>>16&255]<<8|o[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),t=65535&(t|t>>>16),t<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),t=1023&(t|t>>>16),t<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],2:[function(t,e,r){"use strict";function n(t,e,r){r=r||2;var n=e&&e.length,o=n?e[0]*r:t.length,a=i(t,0,o,r,!0),u=[];if(!a)return u;var l,h,f,d,p,v,y;if(n&&(a=c(t,e,a,r)),t.length>80*r){l=f=t[0],h=d=t[1];for(var g=r;gf&&(f=p),v>d&&(d=v);y=Math.max(f-l,d-h)}return s(a,u,r,l,h,y),u}function i(t,e,r,n,i){var o,s;if(i===A(t,e,r,n)>0)for(o=e;o=e;o-=n)s=M(o,t[o],t[o+1],s);return s&&T(s,s.next)&&(C(s),s=s.next),s}function o(t,e){if(!t)return t;e||(e=t);var r,n=t;do if(r=!1,n.steiner||!T(n,n.next)&&0!==x(n.prev,n,n.next))n=n.next;else{if(C(n),n=e=n.prev,n===n.next)return null;r=!0}while(r||n!==e);return e}function s(t,e,r,n,i,c,f){if(t){!f&&c&&v(t,n,i,c);for(var d,p,y=t;t.prev!==t.next;)if(d=t.prev,p=t.next,c?u(t,n,i,c):a(t))e.push(d.i/r),e.push(t.i/r),e.push(p.i/r),C(t),t=p.next,y=p.next;else if(t=p,t===y){f?1===f?(t=l(t,e,r),s(t,e,r,n,i,c,2)):2===f&&h(t,e,r,n,i,c):s(o(t),e,r,n,i,c,1);break}}}function a(t){var e=t.prev,r=t,n=t.next;if(x(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(_(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&x(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function u(t,e,r,n){var i=t.prev,o=t,s=t.next;if(x(i,o,s)>=0)return!1;for(var a=i.xo.x?i.x>s.x?i.x:s.x:o.x>s.x?o.x:s.x,h=i.y>o.y?i.y>s.y?i.y:s.y:o.y>s.y?o.y:s.y,c=g(a,u,e,r,n),f=g(l,h,e,r,n),d=t.nextZ;d&&d.z<=f;){if(d!==t.prev&&d!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,d.x,d.y)&&x(d.prev,d,d.next)>=0)return!1;d=d.nextZ}for(d=t.prevZ;d&&d.z>=c;){if(d!==t.prev&&d!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,d.x,d.y)&&x(d.prev,d,d.next)>=0)return!1;d=d.prevZ}return!0}function l(t,e,r){var n=t;do{var i=n.prev,o=n.next.next;!T(i,o)&&w(i,n,n.next,o)&&S(i,o)&&S(o,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(o.i/r),C(n),C(n.next),n=t=o),n=n.next}while(n!==t);return n}function h(t,e,r,n,i,a){var u=t;do{for(var l=u.next.next;l!==u.prev;){if(u.i!==l.i&&b(u,l)){var h=P(u,l);return u=o(u,u.next),h=o(h,h.next),s(u,e,r,n,i,a),void s(h,e,r,n,i,a)}l=l.next}u=u.next}while(u!==t)}function c(t,e,r,n){var s,a,u,l,h,c=[];for(s=0,a=e.length;s=n.next.y){var a=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=i&&a>s){if(s=a,a===i){if(o===n.y)return n;if(o===n.next.y)return n.next}r=n.x=n.x&&n.x>=h&&_(or.x)&&S(n,t)&&(r=n,f=u)),n=n.next;return r}function v(t,e,r,n){var i=t;do null===i.z&&(i.z=g(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,y(i)}function y(t){var e,r,n,i,o,s,a,u,l=1;do{for(r=t,t=null,o=null,s=0;r;){for(s++,n=r,a=0,e=0;e0||u>0&&n;)0===a?(i=n,n=n.nextZ,u--):0!==u&&n?r.z<=n.z?(i=r,r=r.nextZ,a--):(i=n,n=n.nextZ,u--):(i=r,r=r.nextZ,a--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;r=n}o.nextZ=null,l*=2}while(s>1);return t}function g(t,e,r,n,i){return t=32767*(t-r)/i,e=32767*(e-n)/i,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1}function m(t){var e=t,r=t;do e.x=0&&(t-s)*(n-a)-(r-s)*(e-a)>=0&&(r-s)*(o-a)-(i-s)*(n-a)>=0}function b(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!E(t,e)&&S(t,e)&&S(e,t)&&O(t,e)}function x(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function T(t,e){return t.x===e.x&&t.y===e.y}function w(t,e,r,n){return!!(T(t,e)&&T(r,n)||T(t,n)&&T(r,e))||x(t,e,r)>0!=x(t,e,n)>0&&x(r,n,t)>0!=x(r,n,e)>0}function E(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&w(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}function S(t,e){return x(t.prev,t,t.next)<0?x(t,e,t.next)>=0&&x(t,t.prev,e)>=0:x(t,e,t.prev)<0||x(t,t.next,e)<0}function O(t,e){var r=t,n=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do r.y>o!=r.next.y>o&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;while(r!==t);return n}function P(t,e){var r=new R(t.i,t.x,t.y),n=new R(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function M(t,e,r,n){var i=new R(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function C(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function R(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(t,e,r,n){for(var i=0,o=e,s=r-n;o0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],3:[function(t,e,r){"use strict";function n(){}function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function o(){this._events=new n,this._eventsCount=0}var s=Object.prototype.hasOwnProperty,a="~";Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(a=!1)),o.prototype.eventNames=function(){var t,e,r=[];if(0===this._eventsCount)return r;for(e in t=this._events)s.call(t,e)&&r.push(a?e.slice(1):e);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t,e){var r=a?a+t:t,n=this._events[r];if(e)return!!n;if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i=t.byteLength?n.bufferSubData(this.type,e,t):n.bufferData(this.type,t,this.drawType),this.data=t},i.prototype.bind=function(){var t=this.gl;t.bindBuffer(this.type,this.buffer)},i.createVertexBuffer=function(t,e,r){return new i(t,t.ARRAY_BUFFER,e,r)},i.createIndexBuffer=function(t,e,r){return new i(t,t.ELEMENT_ARRAY_BUFFER,e,r)},i.create=function(t,e,r,n){return new i(t,e,r,n)},i.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer)},e.exports=i},{}],7:[function(t,e,r){var n=t("./GLTexture"),i=function(t,e,r){this.gl=t,this.framebuffer=t.createFramebuffer(),this.stencil=null,this.texture=null,this.width=e||100,this.height=r||100};i.prototype.enableTexture=function(t){var e=this.gl;this.texture=t||new n(e),this.texture.bind(),this.bind(),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0)},i.prototype.enableStencil=function(){if(!this.stencil){var t=this.gl;this.stencil=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.stencil),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.stencil),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,this.width,this.height)}},i.prototype.clear=function(t,e,r,n){this.bind();var i=this.gl;i.clearColor(t,e,r,n),i.clear(i.COLOR_BUFFER_BIT)},i.prototype.bind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer)},i.prototype.unbind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)},i.prototype.resize=function(t,e){var r=this.gl;this.width=t,this.height=e,this.texture&&this.texture.uploadData(null,t,e),this.stencil&&(r.bindRenderbuffer(r.RENDERBUFFER,this.stencil),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e))},i.prototype.destroy=function(){var t=this.gl;this.texture&&this.texture.destroy(),t.deleteFramebuffer(this.framebuffer),this.gl=null,this.stencil=null,this.texture=null},i.createRGBA=function(t,e,r,o){var s=n.fromData(t,null,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},i.createFloat32=function(t,e,r,o){var s=new n.fromData(t,o,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},e.exports=i},{"./GLTexture":9}],8:[function(t,e,r){var n=t("./shader/compileProgram"),i=t("./shader/extractAttributes"),o=t("./shader/extractUniforms"),s=t("./shader/generateUniformAccessObject"),a=function(t,e,r){this.gl=t,this.program=n(t,e,r),this.attributes=i(t,this.program);var a=o(t,this.program);this.uniforms=s(t,a)};a.prototype.bind=function(){this.gl.useProgram(this.program)},a.prototype.destroy=function(){},e.exports=a},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18}],9:[function(t,e,r){var n=function(t,e,r,n,i){this.gl=t,this.texture=t.createTexture(),this.mipmap=!1,this.premultiplyAlpha=!1,this.width=e||-1,this.height=r||-1,this.format=n||t.RGBA,this.type=i||t.UNSIGNED_BYTE};n.prototype.upload=function(t){this.bind();var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var r=t.videoWidth||t.width,n=t.videoHeight||t.height;n!==this.height||r!==this.width?e.texImage2D(e.TEXTURE_2D,0,this.format,this.format,this.type,t):e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.format,this.type,t),this.width=r,this.height=n};var i=!1;n.prototype.uploadData=function(t,e,r){this.bind();var n=this.gl;if(t instanceof Float32Array){if(!i){var o=n.getExtension("OES_texture_float");if(!o)throw new Error("floating point textures not available");i=!0}this.type=n.FLOAT}else this.type=n.UNSIGNED_BYTE;n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),e!==this.width||r!==this.height?n.texImage2D(n.TEXTURE_2D,0,this.format,e,r,0,this.format,this.type,t||null):n.texSubImage2D(n.TEXTURE_2D,0,0,0,e,r,this.format,this.type,t||null),this.width=e,this.height=r},n.prototype.bind=function(t){var e=this.gl;void 0!==t&&e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,this.texture)},n.prototype.unbind=function(){var t=this.gl;t.bindTexture(t.TEXTURE_2D,null)},n.prototype.minFilter=function(t){var e=this.gl;this.bind(),this.mipmap?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.magFilter=function(t){var e=this.gl;this.bind(),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.enableMipmap=function(){var t=this.gl;this.bind(),this.mipmap=!0,t.generateMipmap(t.TEXTURE_2D)},n.prototype.enableLinearScaling=function(){this.minFilter(!0),this.magFilter(!0)},n.prototype.enableNearestScaling=function(){this.minFilter(!1),this.magFilter(!1)},n.prototype.enableWrapClamp=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)},n.prototype.enableWrapRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT)},n.prototype.enableWrapMirrorRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.MIRRORED_REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.MIRRORED_REPEAT)},n.prototype.destroy=function(){var t=this.gl;t.deleteTexture(this.texture)},n.fromSource=function(t,e,r){var i=new n(t);return i.premultiplyAlpha=r||!1,i.upload(e),i},n.fromData=function(t,e,r,i){var o=new n(t);return o.uploadData(e,r,i),o},e.exports=n},{}],10:[function(t,e,r){function n(t,e){if(this.nativeVaoExtension=null,n.FORCE_NATIVE||(this.nativeVaoExtension=t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object")),this.nativeState=e,this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var r=t.getParameter(t.MAX_VERTEX_ATTRIBS);this.nativeState={tempAttribState:new Array(r),attribState:new Array(r)}}this.gl=t,this.attributes=[],this.indexBuffer=null,this.dirty=!1}var i=t("./setVertexAttribArrays");n.prototype.constructor=n,e.exports=n,n.FORCE_NATIVE=!1,n.prototype.bind=function(){return this.nativeVao?(this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao),this.dirty&&(this.dirty=!1,this.activate())):this.activate(),this},n.prototype.unbind=function(){return this.nativeVao&&this.nativeVaoExtension.bindVertexArrayOES(null),this},n.prototype.activate=function(){for(var t=this.gl,e=null,r=0;r=0;n--){var i=t[n];"."===i?t.splice(n,1):".."===i?(t.splice(n,1),r++):r&&(t.splice(n,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}function n(t,e){if(t.filter)return t.filter(e);for(var r=[],n=0;n=-1&&!i;o--){var s=o>=0?arguments[o]:t.cwd();if("string"!=typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(r=s+"/"+r,i="/"===s.charAt(0))}return r=e(n(r.split("/"),function(t){return!!t}),!i).join("/"),(i?"/":"")+r||"."},r.normalize=function(t){var i=r.isAbsolute(t),o="/"===s(t,-1);return t=e(n(t.split("/"),function(t){return!!t}),!i).join("/"),t||i||(t="."),t&&o&&(t+="/"),(i?"/":"")+t},r.isAbsolute=function(t){return"/"===t.charAt(0)},r.join=function(){var t=Array.prototype.slice.call(arguments,0);return r.normalize(n(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},r.relative=function(t,e){function n(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=r.resolve(t).substr(1),e=r.resolve(e).substr(1);for(var i=n(t.split("/")),o=n(e.split("/")),s=Math.min(i.length,o.length),a=s,u=0;u1)for(var r=1;r1&&(n=r[0]+"@",t=r[1]),t=t.replace(D,".");var i=t.split("."),o=s(i,e).join(".");return n+o}function u(t){for(var e,r,n=[],i=0,o=t.length;i=55296&&e<=56319&&i65535&&(t-=65536,e+=j(t>>>10&1023|55296),t=56320|1023&t),e+=j(t)}).join("")}function h(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:w}function c(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function f(t,e,r){var n=0;for(t=r?F(t/P):t>>1,t+=F(t/e);t>N*S>>1;n+=w)t=F(t/N);return F(n+(N+1)*t/(t+O))}function d(t){var e,r,n,i,s,a,u,c,d,p,v=[],y=t.length,g=0,m=C,_=M;for(r=t.lastIndexOf(R),r<0&&(r=0),n=0;n=128&&o("not-basic"),v.push(t.charCodeAt(n));for(i=r>0?r+1:0;i=y&&o("invalid-input"),c=h(t.charCodeAt(i++)),(c>=w||c>F((T-g)/a))&&o("overflow"),g+=c*a,d=u<=_?E:u>=_+S?S:u-_,!(cF(T/p)&&o("overflow"),a*=p;e=v.length+1,_=f(g-s,e,0==s),F(g/e)>T-m&&o("overflow"),m+=F(g/e),g%=e,v.splice(g++,0,m)}return l(v)}function p(t){var e,r,n,i,s,a,l,h,d,p,v,y,g,m,_,b=[];for(t=u(t),y=t.length,e=C,r=0,s=M,a=0;a=e&&vF((T-r)/g)&&o("overflow"),r+=(l-e)*g,e=l,a=0;aT&&o("overflow"),v==e){for(h=r,d=w;p=d<=s?E:d>=s+S?S:d-s,!(h= 0x80 (not a basic code point)","invalid-input":"Invalid input"},N=w-E,F=Math.floor,j=String.fromCharCode;if(b={version:"1.4.1",ucs2:{decode:u,encode:l},decode:d,encode:p,toASCII:y,toUnicode:v},"function"==typeof t&&"object"==typeof t.amd&&t.amd)t("punycode",function(){return b});else if(g&&m)if(r.exports==g)m.exports=b;else for(x in b)b.hasOwnProperty(x)&&(g[x]=b[x]);else i.punycode=b}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],25:[function(t,e,r){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,r,o){e=e||"&",r=r||"=";var s={};if("string"!=typeof t||0===t.length)return s;var a=/\+/g;t=t.split(e);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var l=t.length;u>0&&l>u&&(l=u);for(var h=0;h=0?(c=v.substr(0,y),f=v.substr(y+1)):(c=v,f=""),d=decodeURIComponent(c),p=decodeURIComponent(f),n(s,d)?i(s[d])?s[d].push(p):s[d]=[s[d],p]:s[d]=p}return s};var i=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],26:[function(t,e,r){"use strict";function n(t,e){if(t.map)return t.map(e);for(var r=[],n=0;n",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(d),v=["'"].concat(p),y=["%","/","?",";","#"].concat(v),g=["/","?","#"],m=255,_=/^[+a-z0-9A-Z_-]{0,63}$/,b=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,x={javascript:!0,"javascript:":!0},T={javascript:!0,"javascript:":!0},w={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},E=t("querystring");n.prototype.parse=function(t,e,r){if(!l.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var n=t.indexOf("?"),i=n!==-1&&n127?"x":L[F];if(!N.match(_)){var B=I.slice(0,P),k=I.slice(P+1),U=L.match(b);U&&(B.push(U[1]),k.unshift(U[2])),k.length&&(a="/"+k.join(".")+a),this.hostname=B.join(".");break}}}this.hostname.length>m?this.hostname="":this.hostname=this.hostname.toLowerCase(),A||(this.hostname=u.toASCII(this.hostname));var X=this.port?":"+this.port:"",G=this.hostname||"";this.host=G+X,this.href+=this.host,A&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==a[0]&&(a="/"+a))}if(!x[p])for(var P=0,D=v.length;P0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return r.search=t.search,r.query=t.query,l.isNull(r.pathname)&&l.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!x.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var O=x.slice(-1)[0],P=(r.host||t.host||x.length>1)&&("."===O||".."===O)||""===O,M=0,C=x.length;C>=0;C--)O=x[C],"."===O?x.splice(C,1):".."===O?(x.splice(C,1),M++):M&&(x.splice(C,1),M--);if(!_&&!b)for(;M--;M)x.unshift("..");!_||""===x[0]||x[0]&&"/"===x[0].charAt(0)||x.unshift(""),P&&"/"!==x.join("/").substr(-1)&&x.push("");var R=""===x[0]||x[0]&&"/"===x[0].charAt(0);if(E){r.hostname=r.host=R?"":x.length?x.shift():"";var S=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return _=_||r.host&&x.length,_&&!R&&x.unshift(""),x.length?r.pathname=x.join("/"):(r.pathname=null,r.path=null),l.isNull(r.pathname)&&l.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},n.prototype.parseHost=function(){var t=this.host,e=c.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":29,punycode:24,querystring:27}],29:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],30:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a=t("mini-signals"),u=i(a),l=t("parse-uri"),h=i(l),c=t("./async"),f=n(c),d=t("./Resource"),p=i(d),v=100,y=/(#[\w-]+)?$/,g=function(){function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10;o(this,t),this.baseUrl=r,this.progress=0,this.loading=!1,this.defaultQueryString="",this._beforeMiddleware=[],this._afterMiddleware=[],this._resourcesParsing=[],this._boundLoadResource=function(t,r){return e._loadResource(t,r)},this._queue=f.queue(this._boundLoadResource,n),this._queue.pause(),this.resources={},this.onProgress=new u.default,this.onError=new u.default,this.onLoad=new u.default,this.onStart=new u.default,this.onComplete=new u.default}return t.prototype.add=function(t,e,r,n){if(Array.isArray(t)){for(var i=0;i0))return void this.abort("["+e.status+"] "+e.statusText+": "+e.responseURL);if(this.xhrType===t.XHR_RESPONSE_TYPE.TEXT)this.data=e.responseText,this.type=t.TYPE.TEXT;else if(this.xhrType===t.XHR_RESPONSE_TYPE.JSON)try{this.data=JSON.parse(e.responseText),this.type=t.TYPE.JSON}catch(t){return void this.abort("Error trying to parse loaded json: "+t)}else if(this.xhrType===t.XHR_RESPONSE_TYPE.DOCUMENT)try{if(window.DOMParser){var n=new DOMParser;this.data=n.parseFromString(e.responseText,"text/xml")}else{var i=document.createElement("div");i.innerHTML=e.responseText,this.data=i}this.type=t.TYPE.XML}catch(t){return void this.abort("Error trying to parse loaded xml: "+t)}else this.data=e.response||e.responseText;this.complete()},t.prototype._determineCrossOrigin=function(t,e){if(0===t.indexOf("data:"))return"";e=e||window.location,p||(p=document.createElement("a")),p.href=t,t=(0,h.default)(p.href,{strictMode:!0});var r=!t.port&&""===e.port||t.port===e.port,n=t.protocol?t.protocol+":":"";return t.host===e.hostname&&r&&n===e.protocol?"":"anonymous"},t.prototype._determineXhrType=function(){return t._xhrTypeMap[this.extension]||t.XHR_RESPONSE_TYPE.TEXT},t.prototype._determineLoadType=function(){return t._loadTypeMap[this.extension]||t.LOAD_TYPE.XHR},t.prototype._getExtension=function(){var t=this.url,e="";if(this.isDataUrl){var r=t.indexOf("/");e=t.substring(r+1,t.indexOf(";",r))}else{var n=t.indexOf("?");n!==-1&&(t=t.substring(0,n)),e=t.substring(t.lastIndexOf(".")+1)}return e.toLowerCase()},t.prototype._getMimeFromXhrType=function(e){switch(e){case t.XHR_RESPONSE_TYPE.BUFFER:return"application/octet-binary";case t.XHR_RESPONSE_TYPE.BLOB:return"application/blob";case t.XHR_RESPONSE_TYPE.DOCUMENT:return"application/xml";case t.XHR_RESPONSE_TYPE.JSON:return"application/json";case t.XHR_RESPONSE_TYPE.DEFAULT:case t.XHR_RESPONSE_TYPE.TEXT:default:return"text/plain"}},u(t,[{key:"isDataUrl",get:function(){return this._hasFlag(t.STATUS_FLAGS.DATA_URL)}},{key:"isComplete",get:function(){return this._hasFlag(t.STATUS_FLAGS.COMPLETE)}},{key:"isLoading",get:function(){return this._hasFlag(t.STATUS_FLAGS.LOADING)}}]),t}();r.default=m,m.STATUS_FLAGS={NONE:0,DATA_URL:1,COMPLETE:2,LOADING:4},m.TYPE={UNKNOWN:0,JSON:1,XML:2,IMAGE:3,AUDIO:4,VIDEO:5,TEXT:6},m.LOAD_TYPE={XHR:1,IMAGE:2,AUDIO:3,VIDEO:4},m.XHR_RESPONSE_TYPE={DEFAULT:"text",BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"},m._loadTypeMap={gif:m.LOAD_TYPE.IMAGE,png:m.LOAD_TYPE.IMAGE,bmp:m.LOAD_TYPE.IMAGE,jpg:m.LOAD_TYPE.IMAGE,jpeg:m.LOAD_TYPE.IMAGE,tif:m.LOAD_TYPE.IMAGE,tiff:m.LOAD_TYPE.IMAGE,webp:m.LOAD_TYPE.IMAGE,tga:m.LOAD_TYPE.IMAGE,svg:m.LOAD_TYPE.IMAGE,"svg+xml":m.LOAD_TYPE.IMAGE,mp3:m.LOAD_TYPE.AUDIO,ogg:m.LOAD_TYPE.AUDIO,wav:m.LOAD_TYPE.AUDIO,mp4:m.LOAD_TYPE.VIDEO,webm:m.LOAD_TYPE.VIDEO},m._xhrTypeMap={xhtml:m.XHR_RESPONSE_TYPE.DOCUMENT,html:m.XHR_RESPONSE_TYPE.DOCUMENT,htm:m.XHR_RESPONSE_TYPE.DOCUMENT,xml:m.XHR_RESPONSE_TYPE.DOCUMENT,tmx:m.XHR_RESPONSE_TYPE.DOCUMENT,svg:m.XHR_RESPONSE_TYPE.DOCUMENT,tsx:m.XHR_RESPONSE_TYPE.DOCUMENT,gif:m.XHR_RESPONSE_TYPE.BLOB,png:m.XHR_RESPONSE_TYPE.BLOB,bmp:m.XHR_RESPONSE_TYPE.BLOB,jpg:m.XHR_RESPONSE_TYPE.BLOB,jpeg:m.XHR_RESPONSE_TYPE.BLOB,tif:m.XHR_RESPONSE_TYPE.BLOB,tiff:m.XHR_RESPONSE_TYPE.BLOB,webp:m.XHR_RESPONSE_TYPE.BLOB,tga:m.XHR_RESPONSE_TYPE.BLOB,json:m.XHR_RESPONSE_TYPE.JSON,text:m.XHR_RESPONSE_TYPE.TEXT,txt:m.XHR_RESPONSE_TYPE.TEXT,ttf:m.XHR_RESPONSE_TYPE.BUFFER,otf:m.XHR_RESPONSE_TYPE.BUFFER},m.EMPTY_GIF="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="},{"mini-signals":36,"parse-uri":37}],32:[function(t,e,r){"use strict";function n(){}function i(t,e,r){var n=0,i=t.length;!function o(s){return s||n===i?void(r&&r(s)):void e(t[n++],o)}()}function o(t){return function(){if(null===t)throw new Error("Callback was already called.");var e=t;t=null,e.apply(this,arguments)}}function s(t,e){function r(t,e,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(a.started=!0,null==t&&a.idle())return void setTimeout(function(){return a.drain()},1);var i={data:t,callback:"function"==typeof r?r:n};e?a._tasks.unshift(i):a._tasks.push(i),setTimeout(function(){return a.process()},1)}function i(t){return function(){s-=1,t.callback.apply(t,arguments),null!=arguments[0]&&a.error(arguments[0],t.data),s<=a.concurrency-a.buffer&&a.unsaturated(),a.idle()&&a.drain(),a.process()}}if(null==e)e=1;else if(0===e)throw new Error("Concurrency must not be zero");var s=0,a={_tasks:[],concurrency:e,saturated:n,unsaturated:n,buffer:e/4,empty:n,drain:n,error:n,started:!1,paused:!1,push:function(t,e){r(t,!1,e)},kill:function(){s=0,a.drain=n,a.started=!1,a._tasks=[]},unshift:function(t,e){r(t,!0,e)},process:function(){for(;!a.paused&&s>2,o[1]=(3&n[0])<<4|n[1]>>4,o[2]=(15&n[1])<<2|n[2]>>6,o[3]=63&n[2];var a=r-(t.length-1);switch(a){case 2:o[3]=64,o[2]=64;break;case 1:o[3]=64}for(var u=0;u=0;r--)this.updateAccessibleObjects(e[r])}},t.prototype.update=function(){if(this.renderer.renderingToScreen){this.updateAccessibleObjects(this.renderer._lastObjectRendered);var t=this.renderer.view.getBoundingClientRect(),e=t.width/this.renderer.width,r=t.height/this.renderer.height,n=this.div;n.style.left=t.left+"px",n.style.top=t.top+"px",n.style.width=this.renderer.width+"px",n.style.height=this.renderer.height+"px";for(var i=0;ithis.renderer.width&&(t.width=this.renderer.width-t.x),t.y+t.height>this.renderer.height&&(t.height=this.renderer.height-t.y)},t.prototype.addChild=function(t){var e=this.pool.pop();e||(e=document.createElement("button"),e.style.width=d+"px",e.style.height=d+"px",e.style.backgroundColor=this.debug?"rgba(255,0,0,0.5)":"transparent",e.style.position="absolute",e.style.zIndex=y,e.style.borderStyle="none",e.addEventListener("click",this._onClick.bind(this)),e.addEventListener("focus",this._onFocus.bind(this)),e.addEventListener("focusout",this._onFocusOut.bind(this))),t.accessibleTitle?e.title=t.accessibleTitle:t.accessibleTitle||t.accessibleHint||(e.title="displayObject "+this.tabIndex),t.accessibleHint&&e.setAttribute("aria-label",t.accessibleHint),t._accessibleActive=!0,t._accessibleDiv=e,e.displayObject=t,this.children.push(t),this.div.appendChild(t._accessibleDiv),t._accessibleDiv.tabIndex=t.tabIndex},t.prototype._onClick=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"click",e.eventData)},t.prototype._onFocus=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseover",e.eventData)},t.prototype._onFocusOut=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseout",e.eventData)},t.prototype._onKeyDown=function(t){t.keyCode===f&&this.activate()},t.prototype._onMouseMove=function(){this.deactivate()},t.prototype.destroy=function(){this.div=null;for(var t=0;t4&&void 0!==arguments[4]&&arguments[4];i(this,t),this.renderer=(0,s.autoDetectRenderer)(e,r,n,o),this.stage=new u.default,this._ticker=null,this.ticker=a?l.shared:new l.Ticker,this.start()}return t.prototype.render=function(){this.renderer.render(this.stage)},t.prototype.stop=function(){this._ticker.stop()},t.prototype.start=function(){this._ticker.start()},t.prototype.destroy=function(t){this.stop(),this.ticker=null,this.stage.destroy(),this.stage=null,this.renderer.destroy(t),this.renderer=null},o(t,[{key:"ticker",set:function(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this)},get:function(){return this._ticker}},{key:"view",get:function(){return this.renderer.view}},{key:"screen",get:function(){return this.renderer.screen}}]),t}();r.default=h},{"./autoDetectRenderer":43,"./display/Container":46,"./ticker":116}],42:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t,e){if(t instanceof Array){if("precision"!==t[0].substring(0,9)){var r=t.slice(0);return r.unshift("precision "+e+" float;"),r}}else if("precision"!==t.substring(0,9))return"precision "+e+" float;\n"+t;return t}r.__esModule=!0;var u=t("pixi-gl-core"),l=t("./settings"),h=n(l),c=function(t){function e(r,n,s){return i(this,e),o(this,t.call(this,r,a(n,h.default.PRECISION_VERTEX),a(s,h.default.PRECISION_FRAGMENT)))}return s(e,t),e}(u.GLShader);r.default=c},{"./settings":99,"pixi-gl-core":12}],43:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:800,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:600,r=arguments[2],n=arguments[3];return!n&&a.isWebGLSupported()?new c.default(t,e,r):new l.default(t,e,r)}r.__esModule=!0,r.autoDetectRenderer=o;var s=t("./utils"),a=i(s),u=t("./renderers/canvas/CanvasRenderer"),l=n(u),h=t("./renderers/webgl/WebGLRenderer"),c=n(h)},{"./renderers/canvas/CanvasRenderer":75,"./renderers/webgl/WebGLRenderer":82,"./utils":120}],44:[function(t,e,r){"use strict";r.__esModule=!0;r.VERSION="4.4.0",r.PI_2=2*Math.PI,r.RAD_TO_DEG=180/Math.PI,r.DEG_TO_RAD=Math.PI/180,r.RENDERER_TYPE={UNKNOWN:0,WEBGL:1,CANVAS:2},r.BLEND_MODES={NORMAL:0,ADD:1,MULTIPLY:2,SCREEN:3,OVERLAY:4,DARKEN:5,LIGHTEN:6,COLOR_DODGE:7,COLOR_BURN:8,HARD_LIGHT:9,SOFT_LIGHT:10,DIFFERENCE:11,EXCLUSION:12,HUE:13,SATURATION:14,COLOR:15,LUMINOSITY:16},r.DRAW_MODES={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},r.SCALE_MODES={LINEAR:0,NEAREST:1},r.WRAP_MODES={CLAMP:0,REPEAT:1,MIRRORED_REPEAT:2},r.GC_MODES={AUTO:0,MANUAL:1},r.URL_FILE_EXTENSION=/\.(\w{3,4})(?:$|\?|#)/i,r.DATA_URI=/^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;(charset=[\w-]+|base64))?,(.*)/i,r.SVG_SIZE=/]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i,r.SHAPES={POLY:0,RECT:1,CIRC:2,ELIP:3,RREC:4},r.PRECISION={LOW:"lowp",MEDIUM:"mediump",HIGH:"highp"},r.TRANSFORM_MODE={STATIC:0,DYNAMIC:1},r.TEXT_GRADIENT={LINEAR_VERTICAL:0,LINEAR_HORIZONTAL:1}},{}],45:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../math"),o=function(){function t(){n(this,t),this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0),this.rect=null}return t.prototype.isEmpty=function(){return this.minX>this.maxX||this.minY>this.maxY},t.prototype.clear=function(){this.updateID++,this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0)},t.prototype.getRectangle=function(t){return this.minX>this.maxX||this.minY>this.maxY?i.Rectangle.EMPTY:(t=t||new i.Rectangle(0,0,1,1),t.x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)},t.prototype.addPoint=function(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)},t.prototype.addQuad=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY,o=t[0],s=t[1];e=on?o:n,i=s>i?s:i,o=t[2],s=t[3],e=on?o:n,i=s>i?s:i,o=t[4],s=t[5],e=on?o:n,i=s>i?s:i,o=t[6],s=t[7],e=on?o:n,i=s>i?s:i,this.minX=e,this.minY=r,this.maxX=n,this.maxY=i},t.prototype.addFrame=function(t,e,r,n,i){var o=t.worldTransform,s=o.a,a=o.b,u=o.c,l=o.d,h=o.tx,c=o.ty,f=this.minX,d=this.minY,p=this.maxX,v=this.maxY,y=s*e+u*r+h,g=a*e+l*r+c;f=yp?y:p,v=g>v?g:v,y=s*n+u*r+h,g=a*n+l*r+c,f=yp?y:p,v=g>v?g:v,y=s*e+u*i+h,g=a*e+l*i+c,f=yp?y:p,v=g>v?g:v,y=s*n+u*i+h,g=a*n+l*i+c,f=yp?y:p,v=g>v?g:v,this.minX=f,this.minY=d,this.maxX=p,this.maxY=v},t.prototype.addVertices=function(t,e,r,n){for(var i=t.worldTransform,o=i.a,s=i.b,a=i.c,u=i.d,l=i.tx,h=i.ty,c=this.minX,f=this.minY,d=this.maxX,p=this.maxY,v=r;vd?m:d,p=_>p?_:p}this.minX=c,this.minY=f,this.maxX=d,this.maxY=p},t.prototype.addBounds=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY;this.minX=t.minXn?t.maxX:n,this.maxY=t.maxY>i?t.maxY:i},t.prototype.addBoundsMask=function(t,e){var r=t.minX>e.minX?t.minX:e.minX,n=t.minY>e.minY?t.minY:e.minY,i=t.maxXu?i:u,this.maxY=o>l?o:l}},t.prototype.addBoundsArea=function(t,e){var r=t.minX>e.x?t.minX:e.x,n=t.minY>e.y?t.minY:e.y,i=t.maxXu?i:u,this.maxY=o>l?o:l}},t}();r.default=o},{"../math":68}],46:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r1)for(var r=0;rthis.children.length)throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length);return t.parent&&t.parent.removeChild(t),t.parent=this,t.transform._parentID=-1,this.children.splice(e,0,t),this._boundsID++,this.onChildrenChange(e),t.emit("added",this),t},e.prototype.swapChildren=function(t,e){if(t!==e){var r=this.getChildIndex(t),n=this.getChildIndex(e);this.children[r]=e,this.children[n]=t,this.onChildrenChange(r=this.children.length)throw new Error("The supplied index is out of bounds");var r=this.getChildIndex(t);(0,u.removeItems)(this.children,r,1),this.children.splice(e,0,t),this.onChildrenChange(e)},e.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Index ("+t+") does not exist.");return this.children[t]},e.prototype.removeChild=function(t){var e=arguments.length;if(e>1)for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=t,n="number"==typeof e?e:this.children.length,i=n-r,o=void 0;if(i>0&&i<=n){o=this.children.splice(r,i);for(var s=0;s2&&void 0!==arguments[2]&&arguments[2];return r||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)},e.prototype.toLocal=function(t,e,r,n){return e&&(t=e.toGlobal(t,r,n)),n||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,r)},e.prototype.renderWebGL=function(t){},e.prototype.renderCanvas=function(t){},e.prototype.setParent=function(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t},e.prototype.setTransform=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0,u=arguments.length>8&&void 0!==arguments[8]?arguments[8]:0;return this.position.x=t,this.position.y=e,this.scale.x=r?r:1,this.scale.y=n?n:1,this.rotation=i,this.skew.x=o,this.skew.y=s,this.pivot.x=a,this.pivot.y=u,this},e.prototype.destroy=function(){this.removeAllListeners(),this.parent&&this.parent.removeChild(this),this.transform=null,this.parent=null,this._bounds=null,this._currentBounds=null,this._mask=null,this.filterArea=null,this.interactive=!1,this.interactiveChildren=!1},a(e,[{key:"_tempDisplayObjectParent",get:function(){return null===this.tempDisplayObjectParent&&(this.tempDisplayObjectParent=new e),this.tempDisplayObjectParent}},{key:"x",get:function(){return this.position.x},set:function(t){this.transform.position.x=t}},{key:"y",get:function(){return this.position.y},set:function(t){this.transform.position.y=t}},{key:"worldTransform",get:function(){return this.transform.worldTransform}},{key:"localTransform",get:function(){return this.transform.localTransform}},{key:"position",get:function(){return this.transform.position},set:function(t){this.transform.position.copy(t)}},{key:"scale",get:function(){return this.transform.scale},set:function(t){this.transform.scale.copy(t)}},{key:"pivot",get:function(){return this.transform.pivot},set:function(t){this.transform.pivot.copy(t)}},{key:"skew",get:function(){return this.transform.skew},set:function(t){this.transform.skew.copy(t)}},{key:"rotation",get:function(){return this.transform.rotation},set:function(t){this.transform.rotation=t}},{key:"worldVisible",get:function(){var t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask&&(this._mask.renderable=!0),this._mask=t,this._mask&&(this._mask.renderable=!1)}},{key:"filters",get:function(){return this._filters&&this._filters.slice()},set:function(t){this._filters=t&&t.slice()}}]),e}(l.default);r.default=b,b.prototype.displayObjectUpdateTransform=b.prototype.updateTransform},{"../const":44,"../math":68,"../settings":99,"./Bounds":45,"./Transform":48,"./TransformStatic":50,eventemitter3:3}],48:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]&&arguments[0];i(this,e);var n=o(this,t.call(this));return n.fillAlpha=1,n.lineWidth=0,n.nativeLines=r,n.lineColor=0,n.graphicsData=[],n.tint=16777215,n._prevTint=16777215,n.blendMode=_.BLEND_MODES.NORMAL,n.currentPath=null,n._webGL={},n.isMask=!1,n.boundsPadding=0,n._localBounds=new x.default,n.dirty=0,n.fastRectDirty=-1,n.clearDirty=0,n.boundsDirty=-1,n.cachedSpriteDirty=!1,n._spriteRect=null,n._fastRect=!1,n}return s(e,t),e.prototype.clone=function t(){var t=new e;t.renderable=this.renderable,t.fillAlpha=this.fillAlpha,t.lineWidth=this.lineWidth,t.lineColor=this.lineColor,t.tint=this.tint,t.blendMode=this.blendMode,t.isMask=this.isMask,t.boundsPadding=this.boundsPadding,t.dirty=0,t.cachedSpriteDirty=this.cachedSpriteDirty;for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;if(this.lineWidth=t,this.lineColor=e,this.lineAlpha=r,this.currentPath)if(this.currentPath.shape.points.length){var n=new g.Polygon(this.currentPath.shape.points.slice(-2));n.closed=!1,this.drawShape(n)}else this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha;return this},e.prototype.moveTo=function(t,e){var r=new g.Polygon([t,e]);return r.closed=!1,this.drawShape(r),this},e.prototype.lineTo=function(t,e){return this.currentPath.shape.points.push(t,e),this.dirty++,this},e.prototype.quadraticCurveTo=function(t,e,r,n){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var i=20,o=this.currentPath.shape.points,s=0,a=0;0===o.length&&this.moveTo(0,0);for(var u=o[o.length-2],l=o[o.length-1],h=1;h<=i;++h){var c=h/i;s=u+(t-u)*c,a=l+(e-l)*c,o.push(s+(t+(r-t)*c-s)*c,a+(e+(n-e)*c-a)*c)}return this.dirty++,this},e.prototype.bezierCurveTo=function(t,e,r,n,i,o){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var s=this.currentPath.shape.points,a=s[s.length-2],u=s[s.length-1];return s.length-=2,(0,w.default)(a,u,t,e,r,n,i,o,s),this.dirty++,this},e.prototype.arcTo=function(t,e,r,n,i){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(t,e):this.moveTo(t,e);var o=this.currentPath.shape.points,s=o[o.length-2],a=o[o.length-1],u=a-e,l=s-t,h=n-e,c=r-t,f=Math.abs(u*c-l*h);if(f<1e-8||0===i)o[o.length-2]===t&&o[o.length-1]===e||o.push(t,e);else{var d=u*u+l*l,p=h*h+c*c,v=u*h+l*c,y=i*Math.sqrt(d)/f,g=i*Math.sqrt(p)/f,m=y*v/d,_=g*v/p,b=y*c+g*l,x=y*h+g*u,T=l*(g+m),w=u*(g+m),E=c*(y+_),S=h*(y+_),O=Math.atan2(w-x,T-b),P=Math.atan2(S-x,E-b);this.arc(b+t,x+e,i,O,P,l*h>c*u)}return this.dirty++,this},e.prototype.arc=function(t,e,r,n,i){var o=arguments.length>5&&void 0!==arguments[5]&&arguments[5];if(n===i)return this;!o&&i<=n?i+=2*Math.PI:o&&n<=i&&(n+=2*Math.PI);var s=i-n,a=40*Math.ceil(Math.abs(s)/(2*Math.PI));if(0===s)return this;var u=t+Math.cos(n)*r,l=e+Math.sin(n)*r,h=this.currentPath?this.currentPath.shape.points:null;h?h[h.length-2]===u&&h[h.length-1]===l||h.push(u,l):(this.moveTo(u,l),h=this.currentPath.shape.points);for(var c=s/(2*a),f=2*c,d=Math.cos(c),p=Math.sin(c),v=a-1,y=v%1/v,g=0;g<=v;++g){var m=g+y*g,_=c+n+f*m,b=Math.cos(_),x=-Math.sin(_);h.push((d*b+p*x)*r+t,(d*-x+p*b)*r+e)}return this.dirty++,this},e.prototype.beginFill=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this.filling=!0,this.fillColor=t,this.fillAlpha=e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},e.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},e.prototype.drawRect=function(t,e,r,n){return this.drawShape(new g.Rectangle(t,e,r,n)),this},e.prototype.drawRoundedRect=function(t,e,r,n,i){return this.drawShape(new g.RoundedRectangle(t,e,r,n,i)),this},e.prototype.drawCircle=function(t,e,r){return this.drawShape(new g.Circle(t,e,r)),this},e.prototype.drawEllipse=function(t,e,r,n){return this.drawShape(new g.Ellipse(t,e,r,n)),this},e.prototype.drawPolygon=function(t){var e=t,r=!0;if(e instanceof g.Polygon&&(r=e.closed,e=e.points),!Array.isArray(e)){e=new Array(arguments.length);for(var n=0;n0)&&(this.lineWidth=0,this.filling=!1,this.boundsDirty=-1,this.dirty++,this.clearDirty++,this.graphicsData.length=0),this.currentPath=null,this._spriteRect=null,this},e.prototype.isFastRect=function(){return 1===this.graphicsData.length&&this.graphicsData[0].shape.type===_.SHAPES.RECT&&!this.graphicsData[0].lineWidth},e.prototype._renderWebGL=function(t){this.dirty!==this.fastRectDirty&&(this.fastRectDirty=this.dirty,this._fastRect=this.isFastRect()),this._fastRect?this._renderSpriteRect(t):(t.setObjectRenderer(t.plugins.graphics),t.plugins.graphics.render(this))},e.prototype._renderSpriteRect=function(t){var e=this.graphicsData[0].shape;this._spriteRect||(this._spriteRect=new y.default(new f.default(f.default.WHITE)));var r=this._spriteRect;if(16777215===this.tint)r.tint=this.graphicsData[0].fillColor;else{var n=C,i=R;(0,m.hex2rgb)(this.graphicsData[0].fillColor,n),(0,m.hex2rgb)(this.tint,i),n[0]*=i[0],n[1]*=i[1],n[2]*=i[2],r.tint=(0,m.rgb2hex)(n)}r.alpha=this.graphicsData[0].fillAlpha,r.worldAlpha=this.worldAlpha*r.alpha,r.blendMode=this.blendMode,r.texture._frame.width=e.width,r.texture._frame.height=e.height,r.transform.worldTransform=this.transform.worldTransform,r.anchor.set(-e.x/e.width,-e.y/e.height),r._onAnchorUpdate(),r._renderWebGL(t)},e.prototype._renderCanvas=function(t){this.isMask!==!0&&t.plugins.graphics.render(this)},e.prototype._calculateBounds=function(){this.boundsDirty!==this.dirty&&(this.boundsDirty=this.dirty,this.updateLocalBounds(),this.cachedSpriteDirty=!0);var t=this._localBounds;this._bounds.addFrame(this.transform,t.minX,t.minY,t.maxX,t.maxY)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,M);for(var e=this.graphicsData,r=0;re?o+a:e,r=sn?s+u:n;else if(c===_.SHAPES.CIRC)o=i.x,s=i.y,a=i.radius+f/2,u=i.radius+f/2,t=o-ae?o+a:e,r=s-un?s+u:n;else if(c===_.SHAPES.ELIP)o=i.x,s=i.y,a=i.width+f/2,u=i.height+f/2,t=o-ae?o+a:e,r=s-un?s+u:n;else for(var d=i.points,p=0,v=0,y=0,g=0,m=0,b=0,x=0,T=0,w=0;w+2e?x+m:e,r=T-bn?T+b:n)}else t=0,e=0,r=0,n=0;var E=this.boundsPadding;this._localBounds.minX=t-E,this._localBounds.maxX=e+2*E,this._localBounds.minY=r-E,this._localBounds.maxY=n+2*E},e.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null;var e=new p.default(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,this.nativeLines,t);return this.graphicsData.push(e),e.type===_.SHAPES.POLY&&(e.shape.closed=e.shape.closed||this.filling,this.currentPath=e),this.dirty++,e},e.prototype.generateCanvasTexture=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=this.getLocalBounds(),n=h.default.create(r.width,r.height,t,e);O||(O=new S.default),this.transform.updateLocalTransform(),this.transform.localTransform.copy(P),P.invert(),P.tx-=r.x,P.ty-=r.y,O.render(this,n,!0,P);var i=f.default.fromCanvas(n.baseTexture._canvasRenderTarget.canvas,t);return i.baseTexture.resolution=e,i.baseTexture.update(),i},e.prototype.closePath=function(){var t=this.currentPath;return t&&t.shape&&t.shape.close(),this},e.prototype.addHole=function(){var t=this.graphicsData.pop();return this.currentPath=this.graphicsData[this.graphicsData.length-1],this.currentPath.addHole(t.shape),this.currentPath=null,this},e.prototype.destroy=function(e){t.prototype.destroy.call(this,e);for(var r=0;rC?C:M,r.beginPath(),r.moveTo(E,S+M),r.lineTo(E,S+P-M),r.quadraticCurveTo(E,S+P,E+M,S+P),r.lineTo(E+O-M,S+P),r.quadraticCurveTo(E+O,S+P,E+O,S+P-M),r.lineTo(E+O,S+M),r.quadraticCurveTo(E+O,S,E+O-M,S),r.lineTo(E+M,S),r.quadraticCurveTo(E,S,E,S+M),r.closePath(),(u.fillColor||0===u.fillColor)&&(r.globalAlpha=u.fillAlpha*n,r.fillStyle="#"+("00000"+(0|h).toString(16)).substr(-6),r.fill()),u.lineWidth&&(r.globalAlpha=u.lineAlpha*n,r.strokeStyle="#"+("00000"+(0|c).toString(16)).substr(-6),r.stroke())}}},t.prototype.updateGraphicsTint=function(t){t._prevTint=t.tint;for(var e=(t.tint>>16&255)/255,r=(t.tint>>8&255)/255,n=(255&t.tint)/255,i=0;i>16&255)/255*e*255<<16)+((s>>8&255)/255*r*255<<8)+(255&s)/255*n*255,o._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*r*255<<8)+(255&a)/255*n*255}},t.prototype.renderPolygon=function(t,e,r){r.moveTo(t[0],t[1]);for(var n=1;n8&&void 0!==arguments[8]?arguments[8]:[],l=20,h=0,c=0,f=0,d=0,p=0;u.push(t,e);for(var v=1,y=0;v<=l;++v)y=v/l,h=1-y,c=h*h,f=c*h,d=y*y,p=d*y,u.push(f*t+3*c*y*r+3*h*d*i+p*s,f*e+3*c*y*n+3*h*d*o+p*a);return u}r.__esModule=!0,r.default=n},{}],55:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../utils"),u=t("../../const"),l=t("../../renderers/webgl/utils/ObjectRenderer"),h=n(l),c=t("../../renderers/webgl/WebGLRenderer"),f=n(c),d=t("./WebGLGraphicsData"),p=n(d),v=t("./shaders/PrimitiveShader"),y=n(v),g=t("./utils/buildPoly"),m=n(g),_=t("./utils/buildRectangle"),b=n(_),x=t("./utils/buildRoundedRectangle"),T=n(x),w=t("./utils/buildCircle"),E=n(w),S=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.graphicsDataPool=[],n.primitiveShader=null,n.gl=r.gl,n.CONTEXT_UID=0,n}return s(e,t),e.prototype.onContextChange=function(){this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.primitiveShader=new y.default(this.gl)},e.prototype.destroy=function(){h.default.prototype.destroy.call(this);for(var t=0;t32e4)&&(r=this.graphicsDataPool.pop()||new p.default(this.renderer.gl,this.primitiveShader,this.renderer.state.attribsState),r.reset(e),t.data.push(r)),r.dirty=!0,r},e}(h.default);r.default=S,f.default.registerPlugin("graphics",S)},{"../../const":44,"../../renderers/webgl/WebGLRenderer":82,"../../renderers/webgl/utils/ObjectRenderer":92,"../../utils":120,"./WebGLGraphicsData":56,"./shaders/PrimitiveShader":57,"./utils/buildCircle":58,"./utils/buildPoly":60,"./utils/buildRectangle":61,"./utils/buildRoundedRectangle":62}],56:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("pixi-gl-core"),s=n(o),a=function(){function t(e,r,n){i(this,t),this.gl=e,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=s.default.GLBuffer.createVertexBuffer(e),this.indexBuffer=s.default.GLBuffer.createIndexBuffer(e),this.dirty=!0,this.glPoints=null,this.glIndices=null,this.shader=r,this.vao=new s.default.VertexArrayObject(e,n).addIndex(this.indexBuffer).addAttribute(this.buffer,r.attributes.aVertexPosition,e.FLOAT,!1,24,0).addAttribute(this.buffer,r.attributes.aColor,e.FLOAT,!1,24,8)}return t.prototype.reset=function(){this.points.length=0,this.indices.length=0},t.prototype.upload=function(){this.glPoints=new Float32Array(this.points),this.buffer.upload(this.glPoints),this.glIndices=new Uint16Array(this.indices),this.indexBuffer.upload(this.glIndices),this.dirty=!1},t.prototype.destroy=function(){this.color=null,this.points=null,this.indices=null,this.vao.destroy(),this.buffer.destroy(),this.indexBuffer.destroy(),this.gl=null,this.buffer=null,this.indexBuffer=null,this.glPoints=null,this.glIndices=null},t}();r.default=a},{"pixi-gl-core":12}],57:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../../Shader"),u=n(a),l=function(t){function e(r){return i(this,e),o(this,t.call(this,r,["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","uniform float alpha;","uniform vec3 tint;","varying vec4 vColor;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"].join("\n"),["varying vec4 vColor;","void main(void){"," gl_FragColor = vColor;","}"].join("\n")))}return s(e,t),e}(u.default);r.default=l},{"../../../Shader":42}],58:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,o=void 0,l=void 0;if(t.type===a.SHAPES.CIRC?(o=r.radius,l=r.radius):(o=r.width,l=r.height),0!==o&&0!==l){var h=Math.floor(30*Math.sqrt(r.radius))||Math.floor(15*Math.sqrt(r.width+r.height)),c=2*Math.PI/h;if(t.fill){var f=(0,u.hex2rgb)(t.fillColor),d=t.fillAlpha,p=f[0]*d,v=f[1]*d,y=f[2]*d,g=e.points,m=e.indices,_=g.length/6;m.push(_);for(var b=0;b196*p*p?(R=O-M,A=P-C,I=Math.sqrt(R*R+A*A),R/=I,A/=I,R*=p,A*=p,l.push(T-R,w-A),l.push(g,m,_,y),l.push(T+R,w+A),l.push(g,m,_,y),l.push(T-R,w-A),l.push(g,m,_,y),f++):(l.push(X,G),l.push(g,m,_,y),l.push(T-(X-T),w-(G-w)),l.push(g,m,_,y))}}b=r[2*(c-2)],x=r[2*(c-2)+1],T=r[2*(c-1)],w=r[2*(c-1)+1],O=-(x-w),P=b-T,I=Math.sqrt(O*O+P*P),O/=I,P/=I,O*=p,P*=p,l.push(T-O,w-P),l.push(g,m,_,y),l.push(T+O,w+P),l.push(g,m,_,y),h.push(d);for(var H=0;H=6){for(var n=[],i=t.holes,o=0;o0&&(0,s.default)(t,e)}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils"),u=t("earcut"),l=n(u)},{"../../../utils":120,"./buildLine":59,earcut:2}],61:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,o=r.width,u=r.height;if(t.fill){var l=(0,a.hex2rgb)(t.fillColor),h=t.fillAlpha,c=l[0]*h,f=l[1]*h,d=l[2]*h,p=e.points,v=e.indices,y=p.length/6;p.push(n,i),p.push(c,f,d,h),p.push(n+o,i),p.push(c,f,d,h),p.push(n,i+u),p.push(c,f,d,h),p.push(n+o,i+u),p.push(c,f,d,h),v.push(y,y,y+1,y+2,y+3,y+3)}if(t.lineWidth){var g=t.points;t.points=[n,i,n+o,i,n+o,i+u,n,i+u,n,i],(0,s.default)(t,e),t.points=g}}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils")},{"../../../utils":120,"./buildLine":59}],62:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,o=r.width,a=r.height,l=r.radius,f=[];if(f.push(n,i+l),s(n,i+a-l,n,i+a,n+l,i+a,f),s(n+o-l,i+a,n+o,i+a,n+o,i+a-l,f),s(n+o,i+l,n+o,i,n+o-l,i,f),s(n+l,i,n,i,n,i+l+1e-10,f),t.fill){for(var d=(0,c.hex2rgb)(t.fillColor),p=t.fillAlpha,v=d[0]*p,y=d[1]*p,g=d[2]*p,m=e.points,_=e.indices,b=m.length/6,x=(0,u.default)(f,null,2),T=0,w=x.length;T6&&void 0!==arguments[6]?arguments[6]:[],u=20,l=a,h=0,c=0,f=0,d=0,p=0,v=0,y=0,g=0;y<=u;++y)g=y/u,h=o(t,r,g),c=o(e,n,g),f=o(r,i,g),d=o(n,s,g),p=o(h,f,g),v=o(c,d,g),l.push(p,v);return l}r.__esModule=!0,r.default=i;var a=t("earcut"),u=n(a),l=t("./buildLine"),h=n(l),c=t("../../../utils")},{"../../../utils":120,"./buildLine":59,earcut:2}],63:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.autoDetectRenderer=r.Application=r.Filter=r.SpriteMaskFilter=r.Quad=r.RenderTarget=r.ObjectRenderer=r.WebGLManager=r.Shader=r.CanvasRenderTarget=r.TextureUvs=r.VideoBaseTexture=r.BaseRenderTexture=r.RenderTexture=r.BaseTexture=r.Texture=r.Spritesheet=r.CanvasGraphicsRenderer=r.GraphicsRenderer=r.GraphicsData=r.Graphics=r.TextStyle=r.Text=r.SpriteRenderer=r.CanvasTinter=r.CanvasSpriteRenderer=r.Sprite=r.TransformBase=r.TransformStatic=r.Transform=r.Container=r.DisplayObject=r.Bounds=r.glCore=r.WebGLRenderer=r.CanvasRenderer=r.ticker=r.utils=r.settings=void 0;var o=t("./const");Object.keys(o).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return o[t]}})});var s=t("./math");Object.keys(s).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return s[t]}})});var a=t("pixi-gl-core");Object.defineProperty(r,"glCore",{enumerable:!0,get:function(){return i(a).default}});var u=t("./display/Bounds");Object.defineProperty(r,"Bounds",{enumerable:!0,get:function(){return i(u).default}});var l=t("./display/DisplayObject");Object.defineProperty(r,"DisplayObject",{enumerable:!0,get:function(){return i(l).default}});var h=t("./display/Container");Object.defineProperty(r,"Container",{enumerable:!0,get:function(){return i(h).default}});var c=t("./display/Transform");Object.defineProperty(r,"Transform",{enumerable:!0,get:function(){return i(c).default}});var f=t("./display/TransformStatic");Object.defineProperty(r,"TransformStatic",{enumerable:!0,get:function(){return i(f).default}});var d=t("./display/TransformBase");Object.defineProperty(r,"TransformBase",{enumerable:!0,get:function(){return i(d).default}});var p=t("./sprites/Sprite");Object.defineProperty(r,"Sprite",{enumerable:!0,get:function(){return i(p).default}});var v=t("./sprites/canvas/CanvasSpriteRenderer");Object.defineProperty(r,"CanvasSpriteRenderer",{enumerable:!0,get:function(){return i(v).default}});var y=t("./sprites/canvas/CanvasTinter");Object.defineProperty(r,"CanvasTinter",{enumerable:!0,get:function(){return i(y).default}});var g=t("./sprites/webgl/SpriteRenderer");Object.defineProperty(r,"SpriteRenderer",{enumerable:!0,get:function(){return i(g).default}});var m=t("./text/Text");Object.defineProperty(r,"Text",{enumerable:!0,get:function(){return i(m).default}});var _=t("./text/TextStyle"); +Object.defineProperty(r,"TextStyle",{enumerable:!0,get:function(){return i(_).default}});var b=t("./graphics/Graphics");Object.defineProperty(r,"Graphics",{enumerable:!0,get:function(){return i(b).default}});var x=t("./graphics/GraphicsData");Object.defineProperty(r,"GraphicsData",{enumerable:!0,get:function(){return i(x).default}});var T=t("./graphics/webgl/GraphicsRenderer");Object.defineProperty(r,"GraphicsRenderer",{enumerable:!0,get:function(){return i(T).default}});var w=t("./graphics/canvas/CanvasGraphicsRenderer");Object.defineProperty(r,"CanvasGraphicsRenderer",{enumerable:!0,get:function(){return i(w).default}});var E=t("./textures/Spritesheet");Object.defineProperty(r,"Spritesheet",{enumerable:!0,get:function(){return i(E).default}});var S=t("./textures/Texture");Object.defineProperty(r,"Texture",{enumerable:!0,get:function(){return i(S).default}});var O=t("./textures/BaseTexture");Object.defineProperty(r,"BaseTexture",{enumerable:!0,get:function(){return i(O).default}});var P=t("./textures/RenderTexture");Object.defineProperty(r,"RenderTexture",{enumerable:!0,get:function(){return i(P).default}});var M=t("./textures/BaseRenderTexture");Object.defineProperty(r,"BaseRenderTexture",{enumerable:!0,get:function(){return i(M).default}});var C=t("./textures/VideoBaseTexture");Object.defineProperty(r,"VideoBaseTexture",{enumerable:!0,get:function(){return i(C).default}});var R=t("./textures/TextureUvs");Object.defineProperty(r,"TextureUvs",{enumerable:!0,get:function(){return i(R).default}});var A=t("./renderers/canvas/utils/CanvasRenderTarget");Object.defineProperty(r,"CanvasRenderTarget",{enumerable:!0,get:function(){return i(A).default}});var I=t("./Shader");Object.defineProperty(r,"Shader",{enumerable:!0,get:function(){return i(I).default}});var D=t("./renderers/webgl/managers/WebGLManager");Object.defineProperty(r,"WebGLManager",{enumerable:!0,get:function(){return i(D).default}});var L=t("./renderers/webgl/utils/ObjectRenderer");Object.defineProperty(r,"ObjectRenderer",{enumerable:!0,get:function(){return i(L).default}});var N=t("./renderers/webgl/utils/RenderTarget");Object.defineProperty(r,"RenderTarget",{enumerable:!0,get:function(){return i(N).default}});var F=t("./renderers/webgl/utils/Quad");Object.defineProperty(r,"Quad",{enumerable:!0,get:function(){return i(F).default}});var j=t("./renderers/webgl/filters/spriteMask/SpriteMaskFilter");Object.defineProperty(r,"SpriteMaskFilter",{enumerable:!0,get:function(){return i(j).default}});var B=t("./renderers/webgl/filters/Filter");Object.defineProperty(r,"Filter",{enumerable:!0,get:function(){return i(B).default}});var k=t("./Application");Object.defineProperty(r,"Application",{enumerable:!0,get:function(){return i(k).default}});var U=t("./autoDetectRenderer");Object.defineProperty(r,"autoDetectRenderer",{enumerable:!0,get:function(){return U.autoDetectRenderer}});var X=t("./utils"),G=n(X),W=t("./ticker"),H=n(W),V=t("./settings"),Y=i(V),z=t("./renderers/canvas/CanvasRenderer"),q=i(z),K=t("./renderers/webgl/WebGLRenderer"),Z=i(K);r.settings=Y.default,r.utils=G,r.ticker=H,r.CanvasRenderer=q.default,r.WebGLRenderer=Z.default},{"./Application":41,"./Shader":42,"./autoDetectRenderer":43,"./const":44,"./display/Bounds":45,"./display/Container":46,"./display/DisplayObject":47,"./display/Transform":48,"./display/TransformBase":49,"./display/TransformStatic":50,"./graphics/Graphics":51,"./graphics/GraphicsData":52,"./graphics/canvas/CanvasGraphicsRenderer":53,"./graphics/webgl/GraphicsRenderer":55,"./math":68,"./renderers/canvas/CanvasRenderer":75,"./renderers/canvas/utils/CanvasRenderTarget":77,"./renderers/webgl/WebGLRenderer":82,"./renderers/webgl/filters/Filter":84,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":87,"./renderers/webgl/managers/WebGLManager":91,"./renderers/webgl/utils/ObjectRenderer":92,"./renderers/webgl/utils/Quad":93,"./renderers/webgl/utils/RenderTarget":94,"./settings":99,"./sprites/Sprite":100,"./sprites/canvas/CanvasSpriteRenderer":101,"./sprites/canvas/CanvasTinter":102,"./sprites/webgl/SpriteRenderer":104,"./text/Text":106,"./text/TextStyle":107,"./textures/BaseRenderTexture":108,"./textures/BaseTexture":109,"./textures/RenderTexture":110,"./textures/Spritesheet":111,"./textures/Texture":112,"./textures/TextureUvs":113,"./textures/VideoBaseTexture":114,"./ticker":116,"./utils":120,"pixi-gl-core":12}],64:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){return t<0?-1:t>0?1:0}function o(){for(var t=0;t<16;t++){var e=[];d.push(e);for(var r=0;r<16;r++)for(var n=i(u[t]*u[r]+h[t]*l[r]),o=i(l[t]*u[r]+c[t]*l[r]),s=i(u[t]*h[r]+h[t]*c[r]),p=i(l[t]*h[r]+c[t]*c[r]),v=0;v<16;v++)if(u[v]===n&&l[v]===o&&h[v]===s&&c[v]===p){e.push(v);break}}for(var y=0;y<16;y++){var g=new a.default;g.set(u[y],l[y],h[y],c[y],0,0),f.push(g)}}r.__esModule=!0;var s=t("./Matrix"),a=n(s),u=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],l=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],h=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],c=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],f=[],d=[];o();var p={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MIRROR_HORIZONTAL:12,uX:function(t){return u[t]},uY:function(t){return l[t]},vX:function(t){return h[t]},vY:function(t){return c[t]},inv:function(t){return 8&t?15&t:7&-t},add:function(t,e){return d[t][e]},sub:function(t,e){return d[t][p.inv(e)]},rotate180:function(t){return 4^t},isSwapWidthHeight:function(t){return 2===(3&t)},byDirection:function(t,e){return 2*Math.abs(t)<=Math.abs(e)?e>=0?p.S:p.N:2*Math.abs(e)<=Math.abs(t)?t>0?p.E:p.W:e>0?t>0?p.SE:p.SW:t>0?p.NE:p.NW},matrixAppendRotationInv:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=f[p.inv(e)];i.tx=r,i.ty=n,t.append(i)}};r.default=p},{"./Matrix":65}],65:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:1,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;i(this,t),this.a=e,this.b=r,this.c=n,this.d=o,this.tx=s,this.ty=a,this.array=null}return t.prototype.fromArray=function(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]},t.prototype.set=function(t,e,r,n,i,o){return this.a=t,this.b=e,this.c=r,this.d=n,this.tx=i,this.ty=o,this},t.prototype.toArray=function(t,e){this.array||(this.array=new Float32Array(9));var r=e||this.array;return t?(r[0]=this.a,r[1]=this.b,r[2]=0,r[3]=this.c,r[4]=this.d,r[5]=0,r[6]=this.tx,r[7]=this.ty,r[8]=1):(r[0]=this.a,r[1]=this.c,r[2]=this.tx,r[3]=this.b,r[4]=this.d,r[5]=this.ty,r[6]=0,r[7]=0,r[8]=1),r},t.prototype.apply=function(t,e){e=e||new a.default;var r=t.x,n=t.y;return e.x=this.a*r+this.c*n+this.tx,e.y=this.b*r+this.d*n+this.ty,e},t.prototype.applyInverse=function(t,e){e=e||new a.default;var r=1/(this.a*this.d+this.c*-this.b),n=t.x,i=t.y;return e.x=this.d*r*n+-this.c*r*i+(this.ty*this.c-this.tx*this.d)*r,e.y=this.a*r*i+-this.b*r*n+(-this.ty*this.a+this.tx*this.b)*r,e},t.prototype.translate=function(t,e){return this.tx+=t,this.ty+=e,this},t.prototype.scale=function(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this},t.prototype.rotate=function(t){var e=Math.cos(t),r=Math.sin(t),n=this.a,i=this.c,o=this.tx;return this.a=n*e-this.b*r,this.b=n*r+this.b*e,this.c=i*e-this.d*r,this.d=i*r+this.d*e,this.tx=o*e-this.ty*r,this.ty=o*r+this.ty*e,this},t.prototype.append=function(t){var e=this.a,r=this.b,n=this.c,i=this.d;return this.a=t.a*e+t.b*n,this.b=t.a*r+t.b*i,this.c=t.c*e+t.d*n,this.d=t.c*r+t.d*i,this.tx=t.tx*e+t.ty*n+this.tx,this.ty=t.tx*r+t.ty*i+this.ty,this},t.prototype.setTransform=function(t,e,r,n,i,o,s,a,u){var l=Math.sin(s),h=Math.cos(s),c=Math.cos(u),f=Math.sin(u),d=-Math.sin(a),p=Math.cos(a),v=h*i,y=l*i,g=-l*o,m=h*o;return this.a=c*v+f*g,this.b=c*y+f*m,this.c=d*v+p*g,this.d=d*y+p*m,this.tx=t+(r*v+n*g),this.ty=e+(r*y+n*m),this},t.prototype.prepend=function(t){var e=this.tx;if(1!==t.a||0!==t.b||0!==t.c||1!==t.d){var r=this.a,n=this.c;this.a=r*t.a+this.b*t.c,this.b=r*t.b+this.b*t.d,this.c=n*t.a+this.d*t.c,this.d=n*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this},t.prototype.decompose=function(t){var e=this.a,r=this.b,n=this.c,i=this.d,o=-Math.atan2(-n,i),s=Math.atan2(r,e),a=Math.abs(o+s);return a<1e-5?(t.rotation=s,e<0&&i>=0&&(t.rotation+=t.rotation<=0?Math.PI:-Math.PI),t.skew.x=t.skew.y=0):(t.skew.x=o,t.skew.y=s),t.scale.x=Math.sqrt(e*e+r*r),t.scale.y=Math.sqrt(n*n+i*i),t.position.x=this.tx,t.position.y=this.ty,t},t.prototype.invert=function(){var t=this.a,e=this.b,r=this.c,n=this.d,i=this.tx,o=t*n-e*r;return this.a=n/o,this.b=-e/o,this.c=-r/o,this.d=t/o,this.tx=(r*this.ty-n*i)/o,this.ty=-(t*this.ty-e*i)/o,this},t.prototype.identity=function(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this},t.prototype.clone=function(){var e=new t;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e},t.prototype.copy=function(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t},o(t,null,[{key:"IDENTITY",get:function(){return new t}},{key:"TEMP_MATRIX",get:function(){return new t}}]),t}();r.default=u},{"./Point":67}],66:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this._x=i,this._y=o,this.cb=e,this.scope=r}return t.prototype.set=function(t,e){var r=t||0,n=e||(0!==e?r:0);this._x===r&&this._y===n||(this._x=r,this._y=n,this.cb.call(this.scope))},t.prototype.copy=function(t){this._x===t.x&&this._y===t.y||(this._x=t.x,this._y=t.y,this.cb.call(this.scope))},i(t,[{key:"x",get:function(){return this._x},set:function(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}},{key:"y",get:function(){return this._y},set:function(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}]),t}();r.default=o},{}],67:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;n(this,t),this.x=e,this.y=r}return t.prototype.clone=function(){return new t(this.x,this.y)},t.prototype.copy=function(t){this.set(t.x,t.y)},t.prototype.equals=function(t){return t.x===this.x&&t.y===this.y},t.prototype.set=function(t,e){this.x=t||0,this.y=e||(0!==e?this.x:0)},t}();r.default=i},{}],68:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./Point");Object.defineProperty(r,"Point",{enumerable:!0,get:function(){return n(i).default}});var o=t("./ObservablePoint");Object.defineProperty(r,"ObservablePoint",{enumerable:!0,get:function(){return n(o).default}});var s=t("./Matrix");Object.defineProperty(r,"Matrix",{enumerable:!0,get:function(){return n(s).default}});var a=t("./GroupD8");Object.defineProperty(r,"GroupD8",{enumerable:!0,get:function(){return n(a).default}});var u=t("./shapes/Circle");Object.defineProperty(r,"Circle",{enumerable:!0,get:function(){return n(u).default}});var l=t("./shapes/Ellipse");Object.defineProperty(r,"Ellipse",{enumerable:!0,get:function(){return n(l).default}});var h=t("./shapes/Polygon");Object.defineProperty(r,"Polygon",{enumerable:!0,get:function(){return n(h).default}});var c=t("./shapes/Rectangle");Object.defineProperty(r,"Rectangle",{enumerable:!0,get:function(){return n(c).default}});var f=t("./shapes/RoundedRectangle");Object.defineProperty(r,"RoundedRectangle",{enumerable:!0,get:function(){return n(f).default}})},{"./GroupD8":64,"./Matrix":65,"./ObservablePoint":66,"./Point":67,"./shapes/Circle":69,"./shapes/Ellipse":70,"./shapes/Polygon":71,"./shapes/Rectangle":72,"./shapes/RoundedRectangle":73}],69:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./Rectangle"),s=n(o),a=t("../../const"),u=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;i(this,t),this.x=e,this.y=r,this.radius=n,this.type=a.SHAPES.CIRC}return t.prototype.clone=function(){return new t(this.x,this.y,this.radius)},t.prototype.contains=function(t,e){if(this.radius<=0)return!1;var r=this.radius*this.radius,n=this.x-t,i=this.y-e;return n*=n,i*=i,n+i<=r},t.prototype.getBounds=function(){return new s.default(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)},t}();r.default=u},{"../../const":44,"./Rectangle":72}],70:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./Rectangle"),s=n(o),a=t("../../const"),u=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;i(this,t),this.x=e,this.y=r,this.width=n,this.height=o,this.type=a.SHAPES.ELIP}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;var r=(t-this.x)/this.width,n=(e-this.y)/this.height;return r*=r,n*=n,r+n<=1},t.prototype.getBounds=function(){return new s.default(this.x-this.width,this.y-this.height,this.width,this.height)},t}();r.default=u},{"../../const":44,"./Rectangle":72}],71:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../Point"),s=n(o),a=t("../../const"),u=function(){function t(){for(var e=arguments.length,r=Array(e),n=0;ne!=l>e&&t<(u-s)*((e-a)/(l-a))+s;h&&(r=!r)}return r},t}();r.default=u},{"../../const":44,"../Point":67}],72:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this.x=e,this.y=r,this.width=i,this.height=s,this.type=o.SHAPES.RECT}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this},t.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t=this.y&&et.x+t.width&&(this.width=t.width-this.x,this.width<0&&(this.width=0)),this.y+this.height>t.y+t.height&&(this.height=t.height-this.y,this.height<0&&(this.height=0))},t.prototype.enlarge=function(t){var e=Math.min(this.x,t.x),r=Math.max(this.x+this.width,t.x+t.width),n=Math.min(this.y,t.y),i=Math.max(this.y+this.height,t.y+t.height);this.x=e,this.width=r-e,this.y=n,this.height=i-n},i(t,[{key:"left",get:function(){return this.x}},{key:"right",get:function(){return this.x+this.width}},{key:"top",get:function(){return this.y}},{key:"bottom",get:function(){return this.y+this.height}}],[{key:"EMPTY",get:function(){return new t(0,0,0,0)}}]),t}();r.default=s},{"../../const":44}],73:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:20;n(this,t),this.x=e,this.y=r,this.width=o,this.height=s,this.radius=a,this.type=i.SHAPES.RREC}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height,this.radius)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){if(e>=this.y+this.radius&&e<=this.y+this.height-this.radius||t>=this.x+this.radius&&t<=this.x+this.width-this.radius)return!0;var r=t-(this.x+this.radius),n=e-(this.y+this.radius),i=this.radius*this.radius;if(r*r+n*n<=i)return!0;if(r=t-(this.x+this.width-this.radius),r*r+n*n<=i)return!0;if(n=e-(this.y+this.height-this.radius),r*r+n*n<=i)return!0;if(r=t-(this.x+this.radius),r*r+n*n<=i)return!0}return!1},t}();r.default=o},{"../../const":44}],74:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:{};i(this,e);var a=o(this,t.call(this,"Canvas",r,n,s));return a.type=y.RENDERER_TYPE.CANVAS,a.rootContext=a.view.getContext("2d",{alpha:a.transparent}),a.refresh=!0,a.maskManager=new h.default(a),a.smoothProperty="imageSmoothingEnabled",a.rootContext.imageSmoothingEnabled||(a.rootContext.webkitImageSmoothingEnabled?a.smoothProperty="webkitImageSmoothingEnabled":a.rootContext.mozImageSmoothingEnabled?a.smoothProperty="mozImageSmoothingEnabled":a.rootContext.oImageSmoothingEnabled?a.smoothProperty="oImageSmoothingEnabled":a.rootContext.msImageSmoothingEnabled&&(a.smoothProperty="msImageSmoothingEnabled")),a.initPlugins(),a.blendModes=(0,p.default)(),a._activeBlendMode=null,a.context=null,a.renderingToScreen=!1,a.resize(r,n),a}return s(e,t),e.prototype.render=function(t,e,r,n,i){if(this.view){this.renderingToScreen=!e,this.emit("prerender");var o=this.resolution;e?(e=e.baseTexture||e,e._canvasRenderTarget||(e._canvasRenderTarget=new f.default(e.width,e.height,e.resolution),e.source=e._canvasRenderTarget.canvas,e.valid=!0),this.context=e._canvasRenderTarget.context,this.resolution=e._canvasRenderTarget.resolution):this.context=this.rootContext;var s=this.context;if(e||(this._lastObjectRendered=t),!i){var a=t.parent,u=this._tempDisplayObjectParent.transform.worldTransform;n?(n.copy(u),this._tempDisplayObjectParent.transform._worldID=-1):u.identity(),t.parent=this._tempDisplayObjectParent,t.updateTransform(),t.parent=a}s.setTransform(1,0,0,1,0,0),s.globalAlpha=1,s.globalCompositeOperation=this.blendModes[y.BLEND_MODES.NORMAL],navigator.isCocoonJS&&this.view.screencanvas&&(s.fillStyle="black",s.clear()),(void 0!==r?r:this.clearBeforeRender)&&this.renderingToScreen&&(this.transparent?s.clearRect(0,0,this.width,this.height):(s.fillStyle=this._backgroundColorString,s.fillRect(0,0,this.width,this.height)));var l=this.context;this.context=s,t.renderCanvas(this),this.context=l,this.resolution=o,this.emit("postrender")}},e.prototype.clear=function(t){var e=this.context;t=t||this._backgroundColorString,!this.transparent&&t?(e.fillStyle=t,e.fillRect(0,0,this.width,this.height)):e.clearRect(0,0,this.width,this.height)},e.prototype.setBlendMode=function(t){this._activeBlendMode!==t&&(this._activeBlendMode=t,this.context.globalCompositeOperation=this.blendModes[t])},e.prototype.destroy=function(e){this.destroyPlugins(),t.prototype.destroy.call(this,e),this.context=null,this.refresh=!0,this.maskManager.destroy(),this.maskManager=null,this.smoothProperty=null},e.prototype.resize=function(e,r){t.prototype.resize.call(this,e,r),this.smoothProperty&&(this.rootContext[this.smoothProperty]=m.default.SCALE_MODE===y.SCALE_MODES.LINEAR)},e}(u.default);r.default=_,v.pluginTarget.mixin(_)},{"../../const":44,"../../settings":99,"../../utils":120,"../SystemRenderer":74,"./utils/CanvasMaskManager":76,"./utils/CanvasRenderTarget":77,"./utils/mapCanvasBlendModesToPixi":79}],76:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../../const"),o=function(){function t(e){n(this,t),this.renderer=e}return t.prototype.pushMask=function(t){var e=this.renderer;e.context.save();var r=t.alpha,n=t.transform.worldTransform,i=e.resolution;e.context.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t._texture||(this.renderGraphicsShape(t),e.context.clip()),t.worldAlpha=r},t.prototype.renderGraphicsShape=function(t){var e=this.renderer.context,r=t.graphicsData.length;if(0!==r){e.beginPath();for(var n=0;nS?S:E,e.moveTo(b,x+E),e.lineTo(b,x+w-E),e.quadraticCurveTo(b,x+w,b+E,x+w),e.lineTo(b+T-E,x+w),e.quadraticCurveTo(b+T,x+w,b+T,x+w-E),e.lineTo(b+T,x+E),e.quadraticCurveTo(b+T,x,b+T-E,x),e.lineTo(b+E,x),e.quadraticCurveTo(b,x,b,x+E),e.closePath()}}}},t.prototype.popMask=function(t){t.context.restore()},t.prototype.destroy=function(){},t}();r.default=o},{"../../../const":44}],77:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:[];return(0,a.default)()?(t[o.BLEND_MODES.NORMAL]="source-over",t[o.BLEND_MODES.ADD]="lighter",t[o.BLEND_MODES.MULTIPLY]="multiply",t[o.BLEND_MODES.SCREEN]="screen",t[o.BLEND_MODES.OVERLAY]="overlay",t[o.BLEND_MODES.DARKEN]="darken",t[o.BLEND_MODES.LIGHTEN]="lighten",t[o.BLEND_MODES.COLOR_DODGE]="color-dodge",t[o.BLEND_MODES.COLOR_BURN]="color-burn",t[o.BLEND_MODES.HARD_LIGHT]="hard-light",t[o.BLEND_MODES.SOFT_LIGHT]="soft-light",t[o.BLEND_MODES.DIFFERENCE]="difference",t[o.BLEND_MODES.EXCLUSION]="exclusion",t[o.BLEND_MODES.HUE]="hue",t[o.BLEND_MODES.SATURATION]="saturate",t[o.BLEND_MODES.COLOR]="color",t[o.BLEND_MODES.LUMINOSITY]="luminosity"):(t[o.BLEND_MODES.NORMAL]="source-over",t[o.BLEND_MODES.ADD]="lighter",t[o.BLEND_MODES.MULTIPLY]="source-over",t[o.BLEND_MODES.SCREEN]="source-over",t[o.BLEND_MODES.OVERLAY]="source-over",t[o.BLEND_MODES.DARKEN]="source-over",t[o.BLEND_MODES.LIGHTEN]="source-over",t[o.BLEND_MODES.COLOR_DODGE]="source-over",t[o.BLEND_MODES.COLOR_BURN]="source-over",t[o.BLEND_MODES.HARD_LIGHT]="source-over",t[o.BLEND_MODES.SOFT_LIGHT]="source-over",t[o.BLEND_MODES.DIFFERENCE]="source-over",t[o.BLEND_MODES.EXCLUSION]="source-over",t[o.BLEND_MODES.HUE]="source-over",t[o.BLEND_MODES.SATURATION]="source-over",t[o.BLEND_MODES.COLOR]="source-over",t[o.BLEND_MODES.LUMINOSITY]="source-over"),t}r.__esModule=!0,r.default=i;var o=t("../../../const"),s=t("./canUseNewCanvasBlendModes"),a=n(s)},{"../../../const":44,"./canUseNewCanvasBlendModes":78}],80:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../const"),s=t("../../settings"),a=n(s),u=function(){function t(e){i(this,t),this.renderer=e,this.count=0,this.checkCount=0,this.maxIdle=a.default.GC_MAX_IDLE,this.checkCountMax=a.default.GC_MAX_CHECK_COUNT,this.mode=a.default.GC_MODE}return t.prototype.update=function(){this.count++, +this.mode!==o.GC_MODES.MANUAL&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run()))},t.prototype.run=function(){for(var t=this.renderer.textureManager,e=t._managedTextures,r=!1,n=0;nthis.maxIdle&&(t.destroyTexture(i,!0),e[n]=null,r=!0)}if(r){for(var o=0,s=0;s=0;r--)this.unload(t.children[r])},t}();r.default=u},{"../../const":44,"../../settings":99}],81:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("pixi-gl-core"),s=t("../../const"),a=t("./utils/RenderTarget"),u=n(a),l=t("../../utils"),h=function(){function t(e){i(this,t),this.renderer=e,this.gl=e.gl,this._managedTextures=[]}return t.prototype.bindTexture=function(){},t.prototype.getTexture=function(){},t.prototype.updateTexture=function(t,e){var r=this.gl,n=!!t._glRenderTargets;if(!t.hasLoaded)return null;var i=this.renderer.boundTextures;if(void 0===e){e=0;for(var a=0;a2&&void 0!==arguments[2]?arguments[2]:{};i(this,e);var a=o(this,t.call(this,"WebGL",r,n,s));return a.legacy=!!s.legacy,a.legacy&&(D.default.VertexArrayObject.FORCE_NATIVE=!0),a.type=L.RENDERER_TYPE.WEBGL,a.handleContextLost=a.handleContextLost.bind(a),a.handleContextRestored=a.handleContextRestored.bind(a),a.view.addEventListener("webglcontextlost",a.handleContextLost,!1),a.view.addEventListener("webglcontextrestored",a.handleContextRestored,!1),a._contextOptions={alpha:a.transparent,antialias:s.antialias,premultipliedAlpha:a.transparent&&"notMultiplied"!==a.transparent,stencil:!0,preserveDrawingBuffer:s.preserveDrawingBuffer},a._backgroundColorRgba[3]=a.transparent?0:1,a.maskManager=new h.default(a),a.stencilManager=new f.default(a),a.emptyRenderer=new m.default(a),a.currentRenderer=a.emptyRenderer,a.initPlugins(),s.context&&(0,R.default)(s.context),a.gl=s.context||D.default.createContext(a.view,a._contextOptions),a.CONTEXT_UID=N++,a.state=new O.default(a.gl),a.renderingToScreen=!0,a.boundTextures=null,a._activeShader=null,a._activeVao=null,a._activeRenderTarget=null,a._initContext(),a.filterManager=new p.default(a),a.drawModes=(0,M.default)(a.gl),a._nextTextureLocation=0,a.setBlendMode(0),a}return s(e,t),e.prototype._initContext=function(){var t=this.gl;t.isContextLost()&&t.getExtension("WEBGL_lose_context")&&t.getExtension("WEBGL_lose_context").restoreContext();var e=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);this.boundTextures=new Array(e),this.emptyTextures=new Array(e),this.textureManager=new b.default(this),this.textureGC=new E.default(this),this.state.resetToDefault(),this.rootRenderTarget=new y.default(t,this.width,this.height,null,this.resolution,(!0)),this.rootRenderTarget.clearColor=this._backgroundColorRgba,this.bindRenderTarget(this.rootRenderTarget);var r=new D.default.GLTexture.fromData(t,null,1,1),n={_glTextures:{}};n._glTextures[this.CONTEXT_UID]={};for(var i=0;i 0.5)"," {"," color = vec4(1.0, 0.0, 0.0, 1.0);"," }"," else"," {"," color = vec4(0.0, 1.0, 0.0, 1.0);"," }"," gl_FragColor = mix(sample, masky, 0.5);"," gl_FragColor *= sample.a;","}"].join("\n")}}]),t}();r.default=d},{"../../../const":44,"../../../settings":99,"../../../utils":120,"./extractUniformsFromSrc":85}],85:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e,r){var n=o(t,r),i=o(e,r);return Object.assign(n,i)}function o(t){for(var e=new RegExp("^(projectionMatrix|uSampler|filterArea|filterClamp)$"),r={},n=void 0,i=t.replace(/\s+/g," ").split(/\s*;\s*/),o=0;o-1){var a=s.split(" "),l=a[1],h=a[2],c=1;h.indexOf("[")>-1&&(n=h.split(/\[|]/),h=n[0],c*=Number(n[1])),h.match(e)||(r[h]={value:u(l,c),name:h,type:l})}}return r}r.__esModule=!0,r.default=i;var s=t("pixi-gl-core"),a=n(s),u=a.default.shader.defaultValue},{"pixi-gl-core":12}],86:[function(t,e,r){"use strict";function n(t,e,r){var n=t.identity();return n.translate(e.x/r.width,e.y/r.height),n.scale(r.width,r.height),n}function i(t,e,r){var n=t.identity();n.translate(e.x/r.width,e.y/r.height);var i=r.width/e.width,o=r.height/e.height;return n.scale(i,o),n}function o(t,e,r,n){var i=n.worldTransform.copy(s.Matrix.TEMP_MATRIX),o=n._texture.baseTexture,a=t.identity(),u=r.height/r.width;a.translate(e.x/r.width,e.y/r.height),a.scale(1,u);var l=r.width/o.width,h=r.height/o.height;return i.tx/=o.width*l,i.ty/=o.width*l,i.invert(),a.prepend(i),a.scale(1,1/u),a.scale(l,h),a.translate(n.anchor.x,n.anchor.y),a}r.__esModule=!0,r.calculateScreenSpaceMatrix=n,r.calculateNormalizedScreenSpaceMatrix=i,r.calculateSpriteMatrix=o;var s=t("../../../math")},{"../../../math":68}],87:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../Filter"),u=n(a),l=t("../../../../math"),h=(t("path"),function(t){function e(r){i(this,e);var n=new l.Matrix,s=o(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n","varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n"));return r.renderable=!1,s.maskSprite=r,s.maskMatrix=n,s}return s(e,t),e.prototype.apply=function(t,e,r){var n=this.maskSprite;this.uniforms.mask=n._texture,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,n),this.uniforms.alpha=n.worldAlpha,t.applyFilter(this,e,r)},e}(u.default));r.default=h},{"../../../../math":68,"../Filter":84,path:22}],88:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var u=t("./WebGLManager"),l=i(u),h=t("../utils/RenderTarget"),c=i(h),f=t("../utils/Quad"),d=i(f),p=t("../../../math"),v=t("../../../Shader"),y=i(v),g=t("../filters/filterTransforms"),m=n(g),_=t("bit-twiddle"),b=i(_),x=function t(){a(this,t),this.renderTarget=null,this.sourceFrame=new p.Rectangle,this.destinationFrame=new p.Rectangle,this.filters=[],this.target=null,this.resolution=1},T=function(t){function e(r){a(this,e);var n=o(this,t.call(this,r));return n.gl=n.renderer.gl,n.quad=new d.default(n.gl,r.state.attribState),n.shaderCache={},n.pool={},n.filterData=null,n}return s(e,t),e.prototype.pushFilter=function(t,e){var r=this.renderer,n=this.filterData;if(!n){n=this.renderer._activeRenderTarget.filterStack;var i=new x;i.sourceFrame=i.destinationFrame=this.renderer._activeRenderTarget.size,i.renderTarget=r._activeRenderTarget,this.renderer._activeRenderTarget.filterData=n={index:0,stack:[i]},this.filterData=n}var o=n.stack[++n.index];o||(o=n.stack[n.index]=new x);var s=e[0].resolution,a=0|e[0].padding,u=t.filterArea||t.getBounds(!0),l=o.sourceFrame,h=o.destinationFrame;l.x=(u.x*s|0)/s,l.y=(u.y*s|0)/s,l.width=(u.width*s|0)/s,l.height=(u.height*s|0)/s,n.stack[0].renderTarget.transform||l.fit(n.stack[0].destinationFrame),l.pad(a),h.width=l.width,h.height=l.height;var c=this.getPotRenderTarget(r.gl,l.width,l.height,s);o.target=t,o.filters=e,o.resolution=s,o.renderTarget=c,c.setFrame(h,l),r.bindRenderTarget(c),c.clear()},e.prototype.popFilter=function(){var t=this.filterData,e=t.stack[t.index-1],r=t.stack[t.index];this.quad.map(r.renderTarget.size,r.sourceFrame).upload();var n=r.filters;if(1===n.length)n[0].apply(this,r.renderTarget,e.renderTarget,!1,r),this.freePotRenderTarget(r.renderTarget);else{var i=r.renderTarget,o=this.getPotRenderTarget(this.renderer.gl,r.sourceFrame.width,r.sourceFrame.height,r.resolution);o.setFrame(r.destinationFrame,r.sourceFrame),o.clear();var s=0;for(s=0;s0&&(e+="\nelse "),r1&&void 0!==arguments[1]?arguments[1]:[];return e[i.BLEND_MODES.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.ADD]=[t.ONE,t.DST_ALPHA],e[i.BLEND_MODES.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SCREEN]=[t.ONE,t.ONE_MINUS_SRC_COLOR],e[i.BLEND_MODES.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":44}],97:[function(t,e,r){"use strict";function n(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e[i.DRAW_MODES.POINTS]=t.POINTS,e[i.DRAW_MODES.LINES]=t.LINES,e[i.DRAW_MODES.LINE_LOOP]=t.LINE_LOOP,e[i.DRAW_MODES.LINE_STRIP]=t.LINE_STRIP,e[i.DRAW_MODES.TRIANGLES]=t.TRIANGLES,e[i.DRAW_MODES.TRIANGLE_STRIP]=t.TRIANGLE_STRIP,e[i.DRAW_MODES.TRIANGLE_FAN]=t.TRIANGLE_FAN,e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":44}],98:[function(t,e,r){"use strict";function n(t){var e=t.getContextAttributes();e.stencil||console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly")}r.__esModule=!0,r.default=n},{}],99:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./utils/maxRecommendedTextures"),o=n(i),s=t("./utils/canUploadSameBuffer"),a=n(s);r.default={TARGET_FPMS:.06,MIPMAP_TEXTURES:!0,RESOLUTION:1,FILTER_RESOLUTION:1,SPRITE_MAX_TEXTURES:(0,o.default)(32),SPRITE_BATCH_SIZE:4096,RETINA_PREFIX:/@([0-9\.]+)x/,RENDER_OPTIONS:{view:null,antialias:!1,forceFXAA:!1,autoResize:!1,transparent:!1,backgroundColor:0,clearBeforeRender:!0,preserveDrawingBuffer:!1,roundPixels:!1},TRANSFORM_MODE:0,GC_MODE:0,GC_MAX_IDLE:3600,GC_MAX_CHECK_COUNT:600,WRAP_MODE:0,SCALE_MODE:0,PRECISION_VERTEX:"highp",PRECISION_FRAGMENT:"mediump",CAN_UPLOAD_SAME_BUFFER:(0,a.default)()}},{"./utils/canUploadSameBuffer":117,"./utils/maxRecommendedTextures":121}],100:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rn&&v.xi&&v.y>16)+(65280&t)+((255&t)<<16)}},{key:"texture",get:function(){return this._texture},set:function(t){this._texture!==t&&(this._texture=t,this.cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,t&&(t.baseTexture.hasLoaded?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}]),e}(p.default);r.default=y},{"../const":44,"../display/Container":46,"../math":68,"../textures/Texture":112,"../utils":120}],101:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../renderers/canvas/CanvasRenderer"),s=n(o),a=t("../../const"),u=t("../../math"),l=t("./CanvasTinter"),h=n(l),c=new u.Matrix,f=function(){function t(e){i(this,t),this.renderer=e}return t.prototype.render=function(t){var e=t._texture,r=this.renderer,n=e._frame.width,i=e._frame.height,o=t.transform.worldTransform,s=0,l=0;if(!(e.orig.width<=0||e.orig.height<=0)&&e.baseTexture.source&&(r.setBlendMode(t.blendMode),e.valid)){r.context.globalAlpha=t.worldAlpha;var f=e.baseTexture.scaleMode===a.SCALE_MODES.LINEAR;r.smoothProperty&&r.context[r.smoothProperty]!==f&&(r.context[r.smoothProperty]=f),e.trim?(s=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,l=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(s=(.5-t.anchor.x)*e.orig.width,l=(.5-t.anchor.y)*e.orig.height),e.rotate&&(o.copy(c),o=c,u.GroupD8.matrixAppendRotationInv(o,e.rotate,s,l),s=0,l=0),s-=n/2,l-=i/2,r.roundPixels?(r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution|0,o.ty*r.resolution|0),s=0|s,l=0|l):r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution,o.ty*r.resolution);var d=e.baseTexture.resolution;16777215!==t.tint?(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=h.default.getTintedTexture(t,t.tint)),r.context.drawImage(t.tintedTexture,0,0,n*d,i*d,s*r.resolution,l*r.resolution,n*r.resolution,i*r.resolution)):r.context.drawImage(e.baseTexture.source,e._frame.x*d,e._frame.y*d,n*d,i*d,s*r.resolution,l*r.resolution,n*r.resolution,i*r.resolution)}},t.prototype.destroy=function(){this.renderer=null},t}();r.default=f,s.default.registerPlugin("sprite",f)},{"../../const":44,"../../math":68,"../../renderers/canvas/CanvasRenderer":75,"./CanvasTinter":102}],102:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("../../utils"),o=t("../../renderers/canvas/utils/canUseNewCanvasBlendModes"),s=n(o),a={getTintedTexture:function(t,e){var r=t.texture;e=a.roundColor(e);var n="#"+("00000"+(0|e).toString(16)).substr(-6);if(r.tintCache=r.tintCache||{},r.tintCache[n])return r.tintCache[n];var i=a.canvas||document.createElement("canvas");if(a.tintMethod(r,e,i),a.convertTintToImage){var o=new Image;o.src=i.toDataURL(),r.tintCache[n]=o}else r.tintCache[n]=i,a.canvas=null;return i},tintWithMultiply:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="multiply",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},tintWithOverlay:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.globalCompositeOperation="copy",n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},tintWithPerPixel:function(t,e,r){var n=r.getContext("2d"),o=t._frame.clone(),s=t.baseTexture.resolution;o.x*=s,o.y*=s,o.width*=s,o.height*=s,r.width=Math.ceil(o.width),r.height=Math.ceil(o.height),n.globalCompositeOperation="copy",n.drawImage(t.baseTexture.source,o.x,o.y,o.width,o.height,0,0,o.width,o.height);for(var a=(0,i.hex2rgb)(e),u=a[0],l=a[1],h=a[2],c=n.getImageData(0,0,o.width,o.height),f=c.data,d=0;d=this.size&&this.flush(),t._texture._uvs&&(this.sprites[this.currentIndex++]=t)},e.prototype.flush=function(){if(0!==this.currentIndex){var t=this.renderer.gl,e=this.MAX_TEXTURES,r=E.default.nextPow2(this.currentIndex),n=E.default.log2(r),i=this.buffers[n],o=this.sprites,s=this.groups,a=i.float32View,u=i.uint32View,l=this.boundTextures,h=this.renderer.boundTextures,c=this.renderer.textureGC.count,f=0,d=void 0,p=void 0,v=1,y=0,g=s[0],m=void 0,_=void 0,x=o[0].blendMode;g.textureCount=0,g.start=0,g.blend=x,S++;var w=void 0;for(w=0;w0&&(e+="\nelse "),r0?this.context.shadowColor=r.dropShadowColor:this.context.fillStyle=r.dropShadowColor;for(var v=Math.cos(r.dropShadowAngle)*r.dropShadowDistance,y=Math.sin(r.dropShadowAngle)*r.dropShadowDistance,g=0;g3&&void 0!==arguments[3]&&arguments[3],i=this._style,o=i.letterSpacing;if(0===o)return void(n?this.context.strokeText(t,e,r):this.context.fillText(t,e,r));for(var s=String.prototype.split.call(t,""),a=e,u=0,l="";ui)for(var h=a[u].split(""),c=0;cs?(e+="\n"+h[c],s=i-f):(0===c&&(e+=" "),e+=h[c],s-=f)}else{var d=l+this.context.measureText(" ").width;0===u||d>s?(u>0&&(e+="\n"),e+=a[u],s=i-l):(s-=d,e+=" "+a[u])}}o=0;n--){var i=r[n].trim();/([\"\'])[^\'\"]+\1/.test(i)||(i='"'+i+'"'),r[n]=i}return t.fontStyle+" "+t.fontVariant+" "+t.fontWeight+" "+e+" "+r.join(",")},e.calculateFontProperties=function(t){if(e.fontPropertiesCache[t])return e.fontPropertiesCache[t];var r={},n=e.fontPropertiesCanvas,i=e.fontPropertiesContext;i.font=t;var o=Math.ceil(i.measureText("|MÉq").width),s=Math.ceil(i.measureText("M").width),a=2*s;s=1.4*s|0,n.width=o,n.height=a,i.fillStyle="#f00",i.fillRect(0,0,o,a),i.font=t,i.textBaseline="alphabetic",i.fillStyle="#000",i.fillText("|MÉq",0,s);var u=i.getImageData(0,0,o,a).data,l=u.length,h=4*o,c=0,f=0,d=!1;for(c=0;cs;--c){for(var v=0;v0&&void 0!==arguments[0]?arguments[0]:100,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,s=arguments[2],a=arguments[3];i(this,e);var u=o(this,t.call(this,null,s));return u.resolution=a||h.default.RESOLUTION,u.width=r,u.height=n,u.realWidth=u.width*u.resolution,u.realHeight=u.height*u.resolution,u.scaleMode=void 0!==s?s:h.default.SCALE_MODE,u.hasLoaded=!0,u._glRenderTargets={},u._canvasRenderTarget=null,u.valid=!1,u}return s(e,t),e.prototype.resize=function(t,e){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.realWidth=this.width*this.resolution,this.realHeight=this.height*this.resolution,this.valid&&this.emit("update",this))},e.prototype.destroy=function(){t.prototype.destroy.call(this,!0),this.renderer=null},e}(u.default);r.default=c},{"../settings":99,"./BaseTexture":109}],109:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u=t("../utils"),l=t("../settings"),h=n(l),c=t("eventemitter3"),f=n(c),d=t("../utils/determineCrossOrigin"),p=n(d),v=t("bit-twiddle"),y=n(v),g=function(t){function e(r,n,s){i(this,e);var a=o(this,t.call(this));return a.uid=(0,u.uid)(),a.touched=0,a.resolution=s||h.default.RESOLUTION,a.width=100,a.height=100,a.realWidth=100,a.realHeight=100,a.scaleMode=void 0!==n?n:h.default.SCALE_MODE,a.hasLoaded=!1,a.isLoading=!1,a.source=null,a.origSource=null,a.imageType=null,a.sourceScale=1,a.premultipliedAlpha=!0,a.imageUrl=null,a.isPowerOfTwo=!1,a.mipmap=h.default.MIPMAP_TEXTURES,a.wrapMode=h.default.WRAP_MODE,a._glTextures={},a._enabled=0,a._virtalBoundId=-1,r&&a.loadSource(r),a}return s(e,t),e.prototype.update=function(){"svg"!==this.imageType&&(this.realWidth=this.source.naturalWidth||this.source.videoWidth||this.source.width,this.realHeight=this.source.naturalHeight||this.source.videoHeight||this.source.height,this._updateDimensions()),this.emit("update",this)},e.prototype._updateDimensions=function(){this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=y.default.isPow2(this.realWidth)&&y.default.isPow2(this.realHeight)},e.prototype.loadSource=function(t){var e=this,r=this.isLoading;this.hasLoaded=!1,this.isLoading=!1,r&&this.source&&(this.source.onload=null,this.source.onerror=null);var n=!this.source;if(this.source=t,(t.src&&t.complete||t.getContext)&&t.width&&t.height)this._updateImageType(),"svg"===this.imageType?this._loadSvgSource():this._sourceLoaded(),n&&this.emit("loaded",this);else if(!t.getContext){var i=function(){e.isLoading=!0;var n=e;if(t.onload=function(){if(n._updateImageType(),t.onload=null,t.onerror=null,n.isLoading)return n.isLoading=!1,n._sourceLoaded(),"svg"===n.imageType?void n._loadSvgSource():void n.emit("loaded",n)},t.onerror=function(){t.onload=null,t.onerror=null,n.isLoading&&(n.isLoading=!1,n.emit("error",n))},t.complete&&t.src){if(t.onload=null,t.onerror=null,"svg"===n.imageType)return n._loadSvgSource(),{v:void 0};e.isLoading=!1,t.width&&t.height?(e._sourceLoaded(),r&&e.emit("loaded",e)):r&&e.emit("error",e)}}();if("object"===("undefined"==typeof i?"undefined":a(i)))return i.v}},e.prototype._updateImageType=function(){if(this.imageUrl){var t=(0,u.decomposeDataUri)(this.imageUrl),e=void 0;if(t&&"image"===t.mediaType){var r=t.subType.split("+")[0];if(e=(0,u.getUrlFileExtension)("."+r),!e)throw new Error("Invalid image type in data URI.")}else e=(0,u.getUrlFileExtension)(this.imageUrl),e||(e="png");this.imageType=e}},e.prototype._loadSvgSource=function(){if("svg"===this.imageType){var t=(0,u.decomposeDataUri)(this.imageUrl);t?this._loadSvgSourceUsingDataUri(t):this._loadSvgSourceUsingXhr()}},e.prototype._loadSvgSourceUsingDataUri=function(t){var e=void 0;if("base64"===t.encoding){if(!atob)throw new Error("Your browser doesn't support base64 conversions.");e=atob(t.data)}else e=t.data;this._loadSvgSourceUsingString(e)},e.prototype._loadSvgSourceUsingXhr=function(){var t=this,e=new XMLHttpRequest;e.onload=function(){if(e.readyState!==e.DONE||200!==e.status)throw new Error("Failed to load SVG using XHR.");t._loadSvgSourceUsingString(e.response)},e.onerror=function(){return t.emit("error",t)},e.open("GET",this.imageUrl,!0),e.send()},e.prototype._loadSvgSourceUsingString=function(t){var e=(0,u.getSvgSize)(t),r=e.width,n=e.height;if(!r||!n)throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them.");this.realWidth=Math.round(r*this.sourceScale),this.realHeight=Math.round(n*this.sourceScale),this._updateDimensions();var i=document.createElement("canvas");i.width=this.realWidth,i.height=this.realHeight,i._pixiId="canvas_"+(0,u.uid)(),i.getContext("2d").drawImage(this.source,0,0,r,n,0,0,this.realWidth,this.realHeight),this.origSource=this.source,this.source=i,u.BaseTextureCache[i._pixiId]=this,this.isLoading=!1,this._sourceLoaded(),this.emit("loaded",this)},e.prototype._sourceLoaded=function(){this.hasLoaded=!0,this.update()},e.prototype.destroy=function(){this.imageUrl&&(delete u.BaseTextureCache[this.imageUrl],delete u.TextureCache[this.imageUrl],this.imageUrl=null,navigator.isCocoonJS||(this.source.src="")),this.source&&this.source._pixiId&&delete u.BaseTextureCache[this.source._pixiId],this.source=null,this.dispose()},e.prototype.dispose=function(){this.emit("dispose",this)},e.prototype.updateSourceImage=function(t){this.source.src=t,this.loadSource(this.source)},e.fromImage=function(t,r,n,i){var o=u.BaseTextureCache[t];if(!o){var s=new Image;void 0===r&&0!==t.indexOf("data:")&&(s.crossOrigin=(0,p.default)(t)),o=new e(s,n),o.imageUrl=t,i&&(o.sourceScale=i),o.resolution=(0,u.getResolutionOfUrl)(t),s.src=t,u.BaseTextureCache[t]=o}return o},e.fromCanvas=function(t,r){t._pixiId||(t._pixiId="canvas_"+(0,u.uid)());var n=u.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),u.BaseTextureCache[t._pixiId]=n),n},e.from=function(t,r,n){if("string"==typeof t)return e.fromImage(t,void 0,r,n);if(t instanceof HTMLImageElement){var i=t.src,o=u.BaseTextureCache[i];return o||(o=new e(t,r),o.imageUrl=i,n&&(o.sourceScale=n),o.resolution=(0,u.getResolutionOfUrl)(i),u.BaseTextureCache[i]=o),o}return t instanceof HTMLCanvasElement?e.fromCanvas(t,r):t},e}(f.default);r.default=g},{"../settings":99,"../utils":120,"../utils/determineCrossOrigin":119,"bit-twiddle":1,eventemitter3:3}],110:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("./BaseRenderTexture"),u=n(a),l=t("./Texture"),h=n(l),c=function(t){function e(r,n){i(this,e);var s=null;if(!(r instanceof u.default)){var a=arguments[1],l=arguments[2],h=arguments[3],c=arguments[4];console.warn("Please use RenderTexture.create("+a+", "+l+") instead of the ctor directly."),s=arguments[0],n=null,r=new u.default(a,l,h,c)}var f=o(this,t.call(this,r,n));return f.legacyRenderer=s,f.valid=!0,f._updateUvs(),f}return s(e,t),e.prototype.resize=function(t,e,r){this.valid=t>0&&e>0,this._frame.width=this.orig.width=t,this._frame.height=this.orig.height=e,r||this.baseTexture.resize(t,e),this._updateUvs()},e.create=function(t,r,n,i){return new e(new u.default(t,r,n,i))},e}(h.default);r.default=c},{"./BaseRenderTexture":108,"./Texture":112}],111:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:null;n(this,t),this.baseTexture=e,this.textures={},this.data=r,this.resolution=this._updateResolution(i||this.baseTexture.imageUrl),this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}return i(t,null,[{key:"BATCH_SIZE",get:function(){return 1e3}}]),t.prototype._updateResolution=function(t){var e=this.data.meta.scale,r=(0,s.getResolutionOfUrl)(t,null);return null===r&&(r=void 0!==e?parseFloat(e):1),1!==r&&(this.baseTexture.resolution=r,this.baseTexture.update()),r},t.prototype.parse=function(e){this._batchIndex=0,this._callback=e,this._frameKeys.length<=t.BATCH_SIZE?(this._processFrames(0),this._parseComplete()):this._nextBatch()},t.prototype._processFrames=function(e){for(var r=e,n=t.BATCH_SIZE;r-e0&&void 0!==arguments[0]&&arguments[0];for(var e in this.textures)this.textures[e].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,t&&this.baseTexture.destroy(),this.baseTexture=null},t}();r.default=a},{"../":63,"../utils":120}],112:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(){var t=document.createElement("canvas");t.width=10,t.height=10;var e=t.getContext("2d");return e.fillStyle="white",e.fillRect(0,0,10,10),new b(new c.default(t))}function u(t){t.destroy=function(){},t.on=function(){},t.once=function(){},t.emit=function(){}}r.__esModule=!0;var l=function(){function t(t,e){for(var r=0;rthis.baseTexture.width||t.y+t.height>this.baseTexture.height)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions: "+("X: "+t.x+" + "+t.width+" > "+this.baseTexture.width+" ")+("Y: "+t.y+" + "+t.height+" > "+this.baseTexture.height));this.valid=t&&t.width&&t.height&&this.baseTexture.hasLoaded,this.trim||this.rotate||(this.orig=t),this.valid&&this._updateUvs()}},{key:"rotate",get:function(){return this._rotate},set:function(t){this._rotate=t,this.valid&&this._updateUvs()}},{key:"width",get:function(){return this.orig.width}},{key:"height",get:function(){return this.orig.height}}]),e}(g.default);r.default=b,b.EMPTY=new b(new c.default),u(b.EMPTY),b.WHITE=a(),u(b.WHITE)},{"../math":68,"../utils":120,"./BaseTexture":109,"./TextureUvs":113,"./VideoBaseTexture":114,eventemitter3:3}],113:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../math/GroupD8"),s=n(o),a=function(){function t(){i(this,t),this.x0=0,this.y0=0,this.x1=1,this.y1=0,this.x2=1,this.y2=1,this.x3=0,this.y3=1,this.uvsUint32=new Uint32Array(4)}return t.prototype.set=function(t,e,r){var n=e.width,i=e.height;if(r){var o=t.width/2/n,a=t.height/2/i,u=t.x/n+o,l=t.y/i+a;r=s.default.add(r,s.default.NW),this.x0=u+o*s.default.uX(r),this.y0=l+a*s.default.uY(r),r=s.default.add(r,2),this.x1=u+o*s.default.uX(r),this.y1=l+a*s.default.uY(r),r=s.default.add(r,2),this.x2=u+o*s.default.uX(r),this.y2=l+a*s.default.uY(r),r=s.default.add(r,2),this.x3=u+o*s.default.uX(r),this.y3=l+a*s.default.uY(r)}else this.x0=t.x/n,this.y0=t.y/i,this.x1=(t.x+t.width)/n,this.y1=t.y/i,this.x2=(t.x+t.width)/n,this.y2=(t.y+t.height)/i,this.x3=t.x/n,this.y3=(t.y+t.height)/i;this.uvsUint32[0]=(65535*this.y0&65535)<<16|65535*this.x0&65535,this.uvsUint32[1]=(65535*this.y1&65535)<<16|65535*this.x1&65535,this.uvsUint32[2]=(65535*this.y2&65535)<<16|65535*this.x2&65535,this.uvsUint32[3]=(65535*this.y3&65535)<<16|65535*this.x3&65535},t}();r.default=a},{"../math/GroupD8":64}],114:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function u(t,e){e||(e="video/"+t.substr(t.lastIndexOf(".")+1));var r=document.createElement("source");return r.src=t,r.type=e,r}r.__esModule=!0;var l=function(){function t(t,e){for(var r=0;r0&&t.paused===!1&&t.ended===!1&&t.readyState>2},e.prototype._isSourceReady=function(){return 3===this.source.readyState||4===this.source.readyState},e.prototype._onPlayStart=function(){this.hasLoaded||this._onCanPlay(),!this._isAutoUpdating&&this.autoUpdate&&(p.shared.add(this.update,this),this._isAutoUpdating=!0)},e.prototype._onPlayStop=function(){ +this._isAutoUpdating&&(p.shared.remove(this.update,this),this._isAutoUpdating=!1)},e.prototype._onCanPlay=function(){this.hasLoaded=!0,this.source&&(this.source.removeEventListener("canplay",this._onCanPlay),this.source.removeEventListener("canplaythrough",this._onCanPlay),this.width=this.source.videoWidth,this.height=this.source.videoHeight,this.__loaded||(this.__loaded=!0,this.emit("loaded",this)),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.source.play())},e.prototype.destroy=function(){this._isAutoUpdating&&p.shared.remove(this.update,this),this.source&&this.source._pixiId&&(delete f.BaseTextureCache[this.source._pixiId],delete this.source._pixiId),t.prototype.destroy.call(this)},e.fromVideo=function(t,r){t._pixiId||(t._pixiId="video_"+(0,f.uid)());var n=f.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),f.BaseTextureCache[t._pixiId]=n),n},e.fromUrl=function(t,r){var n=document.createElement("video");if(n.setAttribute("webkit-playsinline",""),n.setAttribute("playsinline",""),Array.isArray(t))for(var i=0;i0&&void 0!==arguments[0]?arguments[0]:performance.now(),e=void 0;t>this.lastTime?(e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),this.deltaTime=e*a.default.TARGET_FPMS*this.speed,this._emitter.emit(h,this.deltaTime)):this.deltaTime=this.elapsedMS=0,this.lastTime=t},o(t,[{key:"FPS",get:function(){return 1e3/this.elapsedMS}},{key:"minFPS",get:function(){return 1e3/this._maxElapsedMS},set:function(t){var e=Math.min(Math.max(0,t)/1e3,a.default.TARGET_FPMS);this._maxElapsedMS=1/e}}]),t}();r.default=c},{"../settings":99,eventemitter3:3}],116:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.Ticker=r.shared=void 0;var i=t("./Ticker"),o=n(i),s=new o.default;s.autoStart=!0,r.shared=s,r.Ticker=o.default},{"./Ticker":115}],117:[function(t,e,r){"use strict";function n(){var t=!!navigator.platform&&/iPad|iPhone|iPod/.test(navigator.platform);return!t}r.__esModule=!0,r.default=n},{}],118:[function(t,e,r){"use strict";function n(t){for(var e=6*t,r=new Uint16Array(e),n=0,i=0;n1&&void 0!==arguments[1]?arguments[1]:window.location;if(0===t.indexOf("data:"))return"";e=e||window.location,a||(a=document.createElement("a")),a.href=t,t=s.default.parse(a.href);var r=!t.port&&""===e.port||t.port===e.port;return t.hostname===e.hostname&&r&&t.protocol===e.protocol?"":"anonymous"}r.__esModule=!0,r.default=i;var o=t("url"),s=n(o),a=void 0},{url:28}],120:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(){return++A}function s(t,e){return e=e||[],e[0]=(t>>16&255)/255,e[1]=(t>>8&255)/255,e[2]=(255&t)/255,e}function a(t){return t=t.toString(16),t="000000".substr(0,6-t.length)+t,"#"+t}function u(t){return(255*t[0]<<16)+(255*t[1]<<8)+(255*t[2]|0)}function l(t,e){var r=T.default.RETINA_PREFIX.exec(t);return r?parseFloat(r[1]):void 0!==e?e:1}function h(t){var e=b.DATA_URI.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,encoding:e[3]?e[3].toLowerCase():void 0,data:e[4]}}function c(t){var e=b.URL_FILE_EXTENSION.exec(t);if(e)return e[1].toLowerCase()}function f(t){var e=b.SVG_SIZE.exec(t),r={};return e&&(r[e[1]]=Math.round(parseFloat(e[3])),r[e[5]]=Math.round(parseFloat(e[7]))),r}function d(){I=!0}function p(t){if(!I){if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var e=["\n %c %c %c Pixi.js "+b.VERSION+" - ✰ "+t+" ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n","background: #ff66a5; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff66a5; background: #030307; padding:5px 0;","background: #ff66a5; padding:5px 0;","background: #ffc3dc; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;"];window.console.log.apply(console,e)}else window.console&&window.console.log("Pixi.js "+b.VERSION+" - "+t+" - http://www.pixijs.com/");I=!0}}function v(){var t={stencil:!0,failIfMajorPerformanceCaveat:!0};try{if(!window.WebGLRenderingContext)return!1;var e=document.createElement("canvas"),r=e.getContext("webgl",t)||e.getContext("experimental-webgl",t),n=!(!r||!r.getContextAttributes().stencil);if(r){var i=r.getExtension("WEBGL_lose_context");i&&i.loseContext()}return r=null,n}catch(t){return!1}}function y(t){return 0===t?0:t<0?-1:1}function g(t,e,r){var n=t.length;if(!(e>=n||0===r)){r=e+r>n?n-e:r;for(var i=n-r,o=e;o1?this._fontStyle="italic":t.indexOf("oblique")>-1?this._fontStyle="oblique":this._fontStyle="normal",t.indexOf("small-caps")>-1?this._fontVariant="small-caps":this._fontVariant="normal";var e=t.split(" "),r=-1;this._fontSize=26;for(var n=0;n-1&&r=this._durations[this.currentFrame];)n-=this._durations[this.currentFrame]*i,this._currentTime+=i;this._currentTime+=n/this._durations[this.currentFrame]}else this._currentTime+=e;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):r!==this.currentFrame&&this.updateTexture()},e.prototype.updateTexture=function(){this._texture=this._textures[this.currentFrame],this._textureID=-1,this.onFrameChange&&this.onFrameChange(this.currentFrame)},e.prototype.destroy=function(){this.stop(),t.prototype.destroy.call(this)},e.fromFrames=function(t){for(var r=[],n=0;n1&&void 0!==arguments[1]?arguments[1]:{};o(this,e);var i=s(this,t.call(this));return i._textWidth=0,i._textHeight=0,i._glyphs=[],i._font={tint:void 0!==n.tint?n.tint:16777215,align:n.align||"left",name:null,size:0},i.font=n.font,i._text=r,i.maxWidth=0,i.maxLineHeight=0,i._anchor=new f.default(function(){i.dirty=!0},i,0,0),i.dirty=!1,i.updateText(),i}return a(e,t),e.prototype.updateText=function(){for(var t=e.fonts[this._font.name],r=this._font.size/t.size,n=new h.Point,i=[],o=[],s=null,a=0,u=0,l=0,c=-1,f=0,d=0,p=0;p0&&n.x*r>this.maxWidth)h.utils.removeItems(i,c,p-c),p=c,c=-1,o.push(f),u=Math.max(u,f),l++,n.x=0,n.y+=t.lineHeight,s=null;else{var y=t.chars[v];y&&(s&&y.kerning[s]&&(n.x+=y.kerning[s]),i.push({texture:y.texture,line:l,charCode:v,position:new h.Point(n.x+y.xOffset,n.y+y.yOffset)}),a=n.x+(y.texture.width+y.xOffset),n.x+=y.xAdvance,d=Math.max(d,y.yOffset+y.texture.height),s=v)}}o.push(a),u=Math.max(u,a);for(var g=[],m=0;m<=l;m++){var _=0;"right"===this._font.align?_=u-o[m]:"center"===this._font.align&&(_=(u-o[m])/2),g.push(_)}for(var b=i.length,x=this.tint,T=0;T=0?t:16777215,this.dirty=!0}},{key:"align",get:function(){return this._font.align},set:function(t){this._font.align=t||"left",this.dirty=!0}},{key:"anchor",get:function(){return this._anchor},set:function(t){"number"==typeof t?this._anchor.set(t):this._anchor.copy(t)}},{key:"font",get:function(){return this._font},set:function(t){t&&("string"==typeof t?(t=t.split(" "),this._font.name=1===t.length?t[0]:t.slice(1).join(" "),this._font.size=t.length>=2?parseInt(t[0],10):e.fonts[this._font.name].size):(this._font.name=t.name,this._font.size="number"==typeof t.size?t.size:parseInt(t.size,10)),this.dirty=!0)}},{key:"text",get:function(){return this._text},set:function(t){t=t.toString()||" ",this._text!==t&&(this._text=t,this.dirty=!0)}},{key:"textWidth",get:function(){return this.validate(),this._textWidth}},{key:"textHeight",get:function(){return this.validate(),this._textHeight}}]),e}(h.Container);r.default=d,d.fonts={}},{"../core":63,"../core/math/ObservablePoint":66}],131:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:100,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:100;o(this,e);var a=s(this,t.call(this,r));return a.tileTransform=new h.TransformStatic,a._width=n,a._height=i,a._canvasPattern=null,a.uvTransform=r.transform||new p.default(r),a.pluginName="tilingSprite",a.uvRespectAnchor=!1,a}return a(e,t),e.prototype._onTextureUpdate=function(){this.uvTransform&&(this.uvTransform.texture=this._texture)},e.prototype._renderWebGL=function(t){var e=this._texture;e&&e.valid&&(this.tileTransform.updateLocalTransform(),this.uvTransform.update(),t.setObjectRenderer(t.plugins[this.pluginName]),t.plugins[this.pluginName].render(this))},e.prototype._renderCanvas=function(t){var e=this._texture;if(e.baseTexture.hasLoaded){var r=t.context,n=this.worldTransform,i=t.resolution,o=e.baseTexture,s=e.baseTexture.resolution,a=this.tilePosition.x/this.tileScale.x%e._frame.width,u=this.tilePosition.y/this.tileScale.y%e._frame.height;if(!this._canvasPattern){var l=new h.CanvasRenderTarget(e._frame.width,e._frame.height,s);16777215!==this.tint?(this.cachedTint!==this.tint&&(this.cachedTint=this.tint,this.tintedTexture=f.default.getTintedTexture(this,this.tint)),l.context.drawImage(this.tintedTexture,0,0)):l.context.drawImage(o.source,-e._frame.x,-e._frame.y),this._canvasPattern=l.context.createPattern(l.canvas,"repeat")}r.globalAlpha=this.worldAlpha,r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t.setBlendMode(this.blendMode),r.fillStyle=this._canvasPattern,r.scale(this.tileScale.x/s,this.tileScale.y/s);var c=this.anchor.x*-this._width,d=this.anchor.y*-this._height;this.uvRespectAnchor?(r.translate(a,u),r.fillRect(-a+c,-u+d,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s)):(r.translate(a+c,u+d),r.fillRect(-a,-u,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s))}},e.prototype._calculateBounds=function(){var t=this._width*-this._anchor._x,e=this._height*-this._anchor._y,r=this._width*(1-this._anchor._x),n=this._height*(1-this._anchor._y);this._bounds.addFrame(this.transform,t,e,r,n)},e.prototype.getLocalBounds=function(e){return 0===this.children.length?(this._bounds.minX=this._width*-this._anchor._x,this._bounds.minY=this._height*-this._anchor._y,this._bounds.maxX=this._width*(1-this._anchor._x),this._bounds.maxY=this._height*(1-this._anchor._x),e||(this._localBoundsRect||(this._localBoundsRect=new h.Rectangle),e=this._localBoundsRect),this._bounds.getRectangle(e)):t.prototype.getLocalBounds.call(this,e)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,v);var e=this._width,r=this._height,n=-e*this.anchor._x;if(v.x>n&&v.xi&&v.y0&&void 0!==arguments[0]?arguments[0]:new o.Point,e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.parent?this.parent.toGlobal(this.position,t,e):(t.x=this.position.x,t.y=this.position.y),t}},{"../core":63}],136:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.BitmapText=r.TilingSpriteRenderer=r.TilingSprite=r.AnimatedSprite=r.TextureTransform=void 0;var i=t("./TextureTransform");Object.defineProperty(r,"TextureTransform",{enumerable:!0,get:function(){return n(i).default}});var o=t("./AnimatedSprite");Object.defineProperty(r,"AnimatedSprite",{enumerable:!0,get:function(){return n(o).default}});var s=t("./TilingSprite");Object.defineProperty(r,"TilingSprite",{enumerable:!0,get:function(){return n(s).default}});var a=t("./webgl/TilingSpriteRenderer");Object.defineProperty(r,"TilingSpriteRenderer",{enumerable:!0,get:function(){return n(a).default}});var u=t("./BitmapText");Object.defineProperty(r,"BitmapText",{enumerable:!0,get:function(){return n(u).default}}),t("./cacheAsBitmap"),t("./getChildByName"),t("./getGlobalPosition")},{"./AnimatedSprite":129,"./BitmapText":130,"./TextureTransform":131,"./TilingSprite":132,"./cacheAsBitmap":133,"./getChildByName":134,"./getGlobalPosition":135,"./webgl/TilingSpriteRenderer":137}],137:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../core"),u=n(a),l=t("../../core/const"),h=(t("path"),new u.Matrix),c=new Float32Array(4),f=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.shader=null,n.simpleShader=null,n.quad=null,n}return s(e,t),e.prototype.onContextChange=function(){var t=this.renderer.gl;this.shader=new u.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n gl_FragColor = sample * color ;\n}\n"),this.simpleShader=new u.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n gl_FragColor = sample * color;\n}\n"),this.renderer.bindVao(null),this.quad=new u.Quad(t,this.renderer.state.attribState),this.quad.initVao(this.shader)},e.prototype.render=function(t){var e=this.renderer,r=this.quad;e.bindVao(r.vao);var n=r.vertices;n[0]=n[6]=t._width*-t.anchor.x,n[1]=n[3]=t._height*-t.anchor.y,n[2]=n[4]=t._width*(1-t.anchor.x),n[5]=n[7]=t._height*(1-t.anchor.y),t.uvRespectAnchor&&(n=r.uvs,n[0]=n[6]=-t.anchor.x,n[1]=n[3]=-t.anchor.y,n[2]=n[4]=1-t.anchor.x,n[5]=n[7]=1-t.anchor.y),r.upload();var i=t._texture,o=i.baseTexture,s=t.tileTransform.localTransform,a=t.uvTransform,f=o.isPowerOfTwo&&i.frame.width===o.width&&i.frame.height===o.height;f&&(o._glTextures[e.CONTEXT_UID]?f=o.wrapMode!==l.WRAP_MODES.CLAMP:o.wrapMode===l.WRAP_MODES.CLAMP&&(o.wrapMode=l.WRAP_MODES.REPEAT));var d=f?this.simpleShader:this.shader;e.bindShader(d);var p=i.width,v=i.height,y=t._width,g=t._height;h.set(s.a*p/y,s.b*p/g,s.c*v/y,s.d*v/g,s.tx/y,s.ty/g),h.invert(),f?h.append(a.mapCoord):(d.uniforms.uMapCoord=a.mapCoord.toArray(!0),d.uniforms.uClampFrame=a.uClampFrame,d.uniforms.uClampOffset=a.uClampOffset),d.uniforms.uTransform=h.toArray(!0);var m=c;u.utils.hex2rgb(t.tint,m),m[3]=t.worldAlpha,d.uniforms.uColor=m,d.uniforms.translationMatrix=t.transform.worldTransform.toArray(!0),d.uniforms.uSampler=e.bindTexture(i),e.setBlendMode(t.blendMode),r.vao.draw(this.renderer.gl.TRIANGLES,6,0)},e}(u.ObjectRenderer);r.default=f,u.WebGLRenderer.registerPlugin("tilingSprite",f)},{"../../core":63,"../../core/const":44,path:22}],138:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var u=function(){function t(t,e){for(var r=0;r=r&&(u=t-l-1),h=h.replace("%value%",e[u]),s+=h,s+="\n"}return n=n.replace("%blur%",s),n=n.replace("%size%",t)}r.__esModule=!0,r.default=n;var i={5:[.153388,.221461,.250301],7:[.071303,.131514,.189879,.214607],9:[.028532,.067234,.124009,.179044,.20236],11:[.0093,.028002,.065984,.121703,.175713,.198596],13:[.002406,.009255,.027867,.065666,.121117,.174868,.197641],15:[489e-6,.002403,.009246,.02784,.065602,.120999,.174697,.197448]},o=["varying vec2 vBlurTexCoords[%size%];","uniform sampler2D uSampler;","void main(void)","{"," gl_FragColor = vec4(0.0);"," %blur%","}"].join("\n")},{}],142:[function(t,e,r){"use strict";function n(t,e){var r=Math.ceil(t/2),n=i,o="",s=void 0;s=e?"vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);":"vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);";for(var a=0;ae;)r-=2;return r}r.__esModule=!0,r.default=n},{}],144:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r 0.0) {\n c.rgb /= c.a;\n }\n vec4 result;\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n // Premultiply alpha again.\n result.rgb *= result.a;\n\n gl_FragColor = result;\n}\n")); +return r.uniforms.m=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],r}return s(e,t),e.prototype._loadMatrix=function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t;e&&(this._multiply(r,this.uniforms.m,t),r=this._colorMatrix(r)),this.uniforms.m=r},e.prototype._multiply=function(t,e,r){return t[0]=e[0]*r[0]+e[1]*r[5]+e[2]*r[10]+e[3]*r[15],t[1]=e[0]*r[1]+e[1]*r[6]+e[2]*r[11]+e[3]*r[16],t[2]=e[0]*r[2]+e[1]*r[7]+e[2]*r[12]+e[3]*r[17],t[3]=e[0]*r[3]+e[1]*r[8]+e[2]*r[13]+e[3]*r[18],t[4]=e[0]*r[4]+e[1]*r[9]+e[2]*r[14]+e[3]*r[19]+e[4],t[5]=e[5]*r[0]+e[6]*r[5]+e[7]*r[10]+e[8]*r[15],t[6]=e[5]*r[1]+e[6]*r[6]+e[7]*r[11]+e[8]*r[16],t[7]=e[5]*r[2]+e[6]*r[7]+e[7]*r[12]+e[8]*r[17],t[8]=e[5]*r[3]+e[6]*r[8]+e[7]*r[13]+e[8]*r[18],t[9]=e[5]*r[4]+e[6]*r[9]+e[7]*r[14]+e[8]*r[19]+e[9],t[10]=e[10]*r[0]+e[11]*r[5]+e[12]*r[10]+e[13]*r[15],t[11]=e[10]*r[1]+e[11]*r[6]+e[12]*r[11]+e[13]*r[16],t[12]=e[10]*r[2]+e[11]*r[7]+e[12]*r[12]+e[13]*r[17],t[13]=e[10]*r[3]+e[11]*r[8]+e[12]*r[13]+e[13]*r[18],t[14]=e[10]*r[4]+e[11]*r[9]+e[12]*r[14]+e[13]*r[19]+e[14],t[15]=e[15]*r[0]+e[16]*r[5]+e[17]*r[10]+e[18]*r[15],t[16]=e[15]*r[1]+e[16]*r[6]+e[17]*r[11]+e[18]*r[16],t[17]=e[15]*r[2]+e[16]*r[7]+e[17]*r[12]+e[18]*r[17],t[18]=e[15]*r[3]+e[16]*r[8]+e[17]*r[13]+e[18]*r[18],t[19]=e[15]*r[4]+e[16]*r[9]+e[17]*r[14]+e[18]*r[19]+e[19],t},e.prototype._colorMatrix=function(t){var e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e},e.prototype.brightness=function(t,e){var r=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.greyscale=function(t,e){var r=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.blackAndWhite=function(t){var e=[.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.hue=function(t,e){t=(t||0)/180*Math.PI;var r=Math.cos(t),n=Math.sin(t),i=Math.sqrt,o=1/3,s=i(o),a=r+(1-r)*o,u=o*(1-r)-s*n,l=o*(1-r)+s*n,h=o*(1-r)+s*n,c=r+o*(1-r),f=o*(1-r)-s*n,d=o*(1-r)-s*n,p=o*(1-r)+s*n,v=r+o*(1-r),y=[a,u,l,0,0,h,c,f,0,0,d,p,v,0,0,0,0,0,1,0];this._loadMatrix(y,e)},e.prototype.contrast=function(t,e){var r=(t||0)+1,n=-128*(r-1),i=[r,0,0,0,n,0,r,0,0,n,0,0,r,0,n,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.saturate=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=2*t/3+1,n=(r-1)*-.5,i=[r,n,n,0,0,n,r,n,0,0,n,n,r,0,0,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.desaturate=function(){this.saturate(-1)},e.prototype.negative=function(t){var e=[0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.sepia=function(t){var e=[.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.technicolor=function(t){var e=[1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.polaroid=function(t){var e=[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.toBGR=function(t){var e=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.kodachrome=function(t){var e=[1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.browni=function(t){var e=[.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.vintage=function(t){var e=[.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.colorTone=function(t,e,r,n,i){t=t||.2,e=e||.15,r=r||16770432,n=n||3375104;var o=(r>>16&255)/255,s=(r>>8&255)/255,a=(255&r)/255,u=(n>>16&255)/255,l=(n>>8&255)/255,h=(255&n)/255,c=[.3,.59,.11,0,0,o,s,a,t,0,u,l,h,e,0,o-u,s-l,a-h,0,0];this._loadMatrix(c,i)},e.prototype.night=function(t,e){t=t||.1;var r=[t*-2,-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.predator=function(t,e){var r=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.lsd=function(t){var e=[2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.reset=function(){var t=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(t,!1)},a(e,[{key:"matrix",get:function(){return this.uniforms.m},set:function(t){this.uniforms.m=t}}]),e}(l.Filter));r.default=h,h.prototype.grayscale=h.prototype.greyscale},{"../../core":63,path:22}],145:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n'))}return s(e,t),e}(u.Filter));r.default=l},{"../../core":63,path:22}],147:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./fxaa/FXAAFilter");Object.defineProperty(r,"FXAAFilter",{enumerable:!0,get:function(){return n(i).default}});var o=t("./noise/NoiseFilter");Object.defineProperty(r,"NoiseFilter",{enumerable:!0,get:function(){return n(o).default}});var s=t("./displacement/DisplacementFilter");Object.defineProperty(r,"DisplacementFilter",{enumerable:!0,get:function(){return n(s).default}});var a=t("./blur/BlurFilter");Object.defineProperty(r,"BlurFilter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./blur/BlurXFilter");Object.defineProperty(r,"BlurXFilter",{enumerable:!0,get:function(){return n(u).default}});var l=t("./blur/BlurYFilter");Object.defineProperty(r,"BlurYFilter",{enumerable:!0,get:function(){return n(l).default}});var h=t("./colormatrix/ColorMatrixFilter");Object.defineProperty(r,"ColorMatrixFilter",{enumerable:!0,get:function(){return n(h).default}});var c=t("./void/VoidFilter");Object.defineProperty(r,"VoidFilter",{enumerable:!0,get:function(){return n(c).default}})},{"./blur/BlurFilter":138,"./blur/BlurXFilter":139,"./blur/BlurYFilter":140,"./colormatrix/ColorMatrixFilter":144,"./displacement/DisplacementFilter":145,"./fxaa/FXAAFilter":146,"./noise/NoiseFilter":148,"./void/VoidFilter":149}],148:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:1;this.removeEvents(),this.interactionDOMElement=t,this.resolution=e,this.addEvents()},e.prototype.addEvents=function(){this.interactionDOMElement&&(h.ticker.shared.add(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="none",this.interactionDOMElement.style["-ms-touch-action"]="none"):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]="none"),this.supportsPointerEvents?(window.document.addEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("pointerover",this.onPointerOver,!0),window.addEventListener("pointercancel",this.onPointerCancel,!0),window.addEventListener("pointerup",this.onPointerUp,!0)):(window.document.addEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onPointerOver,!0),window.addEventListener("mouseup",this.onPointerUp,!0),this.supportsTouchEvents&&(this.interactionDOMElement.addEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.addEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.addEventListener("touchmove",this.onPointerMove,!0))),this.eventsAdded=!0)},e.prototype.removeEvents=function(){this.interactionDOMElement&&(h.ticker.shared.remove(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="",this.interactionDOMElement.style["-ms-touch-action"]=""):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]=""),this.supportsPointerEvents?(window.document.removeEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("pointerover",this.onPointerOver,!0),window.removeEventListener("pointercancel",this.onPointerCancel,!0),window.removeEventListener("pointerup",this.onPointerUp,!0)):(window.document.removeEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onPointerOver,!0),window.removeEventListener("mouseup",this.onPointerUp,!0),this.supportsTouchEvents&&(this.interactionDOMElement.removeEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.removeEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onPointerMove,!0))),this.interactionDOMElement=null,this.eventsAdded=!1)},e.prototype.update=function(t){if(this._deltaTime+=t,!(this._deltaTime=0;h--){var c=l[h];if(this.processInteractive(t,c,r,n,a)){if(!c.parent)continue;s=!0,a=!1,u=!1,c.interactive&&(n=!1)}}return n=u,i&&(n&&!s&&(e.hitArea?(e.worldTransform.applyInverse(o,this._tempPoint),s=e.hitArea.contains(this._tempPoint.x,this._tempPoint.y)):e.containsPoint&&(s=e.containsPoint(o))),e.interactive&&(s&&!t.target&&(t.target=e),r(t,e,s))),s},e.prototype.onPointerDown=function(t){var e=this.normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&t.preventDefault();for(var r=e.length,n=0;n1&&(h=1);var c=Math.sqrt(n*n+i*i),f=this._texture.height/2;n/=c,i/=c,n*=f,i*=f,o[l]=u.x+n,o[l+1]=u.y+i,o[l+2]=u.x-n,o[l+3]=u.y-i,e=u}this.containerUpdateTransform()}},e}(l.default);r.default=f},{"../core":63,"./Mesh":161}],165:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var s=t("../../core"),a=i(s),u=t("../Mesh"),l=n(u),h=function(){function t(e){o(this,t),this.renderer=e}return t.prototype.render=function(t){var e=this.renderer,r=e.context,n=t.worldTransform,i=e.resolution;e.roundPixels?r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i|0,n.ty*i|0):r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),e.setBlendMode(t.blendMode),t.drawMode===l.default.DRAW_MODES.TRIANGLE_MESH?this._renderTriangleMesh(t):this._renderTriangles(t)},t.prototype._renderTriangleMesh=function(t){for(var e=t.vertices.length/2,r=0;r0){var E=t.canvasPadding/t.worldTransform.a,S=t.canvasPadding/t.worldTransform.d,O=(m+_+b)/3,P=(x+T+w)/3,M=m-O,C=x-P,R=Math.sqrt(M*M+C*C);m=O+M/R*(R+E),x=P+C/R*(R+S),M=_-O,C=T-P,R=Math.sqrt(M*M+C*C),_=O+M/R*(R+E),T=P+C/R*(R+S),M=b-O,C=w-P,R=Math.sqrt(M*M+C*C),b=O+M/R*(R+E),w=P+C/R*(R+S)}i.save(),i.beginPath(),i.moveTo(m,x),i.lineTo(_,T),i.lineTo(b,w),i.closePath(),i.clip();var A=f*y+v*p+d*g-y*p-v*d-f*g,I=m*y+v*b+_*g-y*b-v*_-m*g,D=f*_+m*p+d*b-_*p-m*d-f*b,L=f*y*b+v*_*p+m*d*g-m*y*p-v*d*b-f*_*g,N=x*y+v*w+T*g-y*w-v*T-x*g,F=f*T+x*p+d*w-T*p-x*d-f*w,j=f*y*w+v*T*p+x*d*g-x*y*p-v*d*w-f*T*g;i.transform(I/A,N/A,D/A,F/A,L/A,j/A),i.drawImage(l,0,0,h*u.resolution,c*u.resolution,0,0,h,c),i.restore()}},t.prototype.renderMeshFlat=function(t){var e=this.renderer.context,r=t.vertices,n=r.length/2;e.beginPath();for(var i=1;i0&&void 0!==arguments[0]?arguments[0]:1500,n=arguments[1],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16384;i(this,e);var a=o(this,t.call(this)),l=16384;return s>l&&(s=l),s>r&&(s=r),a._properties=[!1,!0,!1,!1,!1],a._maxSize=r,a._batchSize=s,a._glBuffers={},a._bufferToUpdate=0,a.interactiveChildren=!1,a.blendMode=u.BLEND_MODES.NORMAL,a.roundPixels=!0,a.baseTexture=null,a.setProperties(n),a}return s(e,t),e.prototype.setProperties=function(t){t&&(this._properties[0]="scale"in t?!!t.scale:this._properties[0],this._properties[1]="position"in t?!!t.position:this._properties[1],this._properties[2]="rotation"in t?!!t.rotation:this._properties[2],this._properties[3]="uvs"in t?!!t.uvs:this._properties[3],this._properties[4]="alpha"in t?!!t.alpha:this._properties[4])},e.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},e.prototype.renderWebGL=function(t){var e=this;this.visible&&!(this.worldAlpha<=0)&&this.children.length&&this.renderable&&(this.baseTexture||(this.baseTexture=this.children[0]._texture.baseTexture,this.baseTexture.hasLoaded||this.baseTexture.once("update",function(){return e.onChildrenChange(0)})),t.setObjectRenderer(t.plugins.particle),t.plugins.particle.render(this))},e.prototype.onChildrenChange=function(t){var e=Math.floor(t/this._batchSize);er&&(o=r);var s=t._glBuffers[i.CONTEXT_UID];s||(s=t._glBuffers[i.CONTEXT_UID]=this.generateBuffers(t)),this.renderer.setBlendMode(t.blendMode);var a=i.gl,u=t.worldTransform.copy(this.tempMatrix);u.prepend(i._activeRenderTarget.projectionMatrix),this.shader.uniforms.projectionMatrix=u.toArray(!0),this.shader.uniforms.uAlpha=t.worldAlpha;var l=e[0]._texture.baseTexture;this.shader.uniforms.uSampler=i.bindTexture(l);for(var h=0,c=0;hn&&(f=n);var d=s[c];d.uploadDynamic(e,h,f),t._bufferToUpdate===c&&(d.uploadStatic(e,h,f),t._bufferToUpdate=c+1),i.bindVao(d.vao),d.vao.draw(a.TRIANGLES,6*f)}}},e.prototype.generateBuffers=function(t){for(var e=this.renderer.gl,r=[],n=t._maxSize,i=t._batchSize,o=t._properties,s=0;s0?1:-1})},{}],174:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}var i=t("object-assign"),o=n(i);Object.assign||(Object.assign=o.default)},{"object-assign":5}],175:[function(t,e,r){"use strict";t("./Object.assign"),t("./requestAnimationFrame"),t("./Math.sign"),window.ArrayBuffer||(window.ArrayBuffer=Array),window.Float32Array||(window.Float32Array=Array),window.Uint32Array||(window.Uint32Array=Array),window.Uint16Array||(window.Uint16Array=Array)},{"./Math.sign":173,"./Object.assign":174,"./requestAnimationFrame":176}],176:[function(t,e,r){(function(t){"use strict";var e=16;Date.now&&Date.prototype.getTime||(Date.now=function(){return(new Date).getTime()}),t.performance&&t.performance.now||!function(){var e=Date.now();t.performance||(t.performance={}),t.performance.now=function(){return Date.now()-e}}();for(var r=Date.now(),n=["ms","moz","webkit","o"],i=0;i=0;n--)this.add(t.children[n]);return this},t.prototype.destroy=function(){this.ticking&&p.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null,this.limiter=null,this.uploadHookHelper=null},t}();r.default=v},{"../core":63,"./limiters/CountLimiter":180}],178:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function u(t,e){if(e instanceof c.BaseTexture){var r=e.source,n=0===r.width?t.canvas.width:Math.min(t.canvas.width,r.width),i=0===r.height?t.canvas.height:Math.min(t.canvas.height,r.height);return t.ctx.drawImage(r,0,0,n,i,0,0,t.canvas.width,t.canvas.height),!0}return!1}function l(t,e){if(t instanceof c.BaseTexture)return e.indexOf(t)===-1&&e.push(t),!0;if(t._texture&&t._texture instanceof c.Texture){var r=t._texture.baseTexture;return e.indexOf(r)===-1&&e.push(r),!0}return!1}r.__esModule=!0;var h=t("../../core"),c=i(h),f=t("../BasePrepare"),d=n(f),p=16,v=function(t){function e(r){o(this,e);var n=s(this,t.call(this,r));return n.uploadHookHelper=n,n.canvas=document.createElement("canvas"),n.canvas.width=p,n.canvas.height=p,n.ctx=n.canvas.getContext("2d"),n.register(l,u),n}return a(e,t),e.prototype.destroy=function(){t.prototype.destroy.call(this),this.ctx=null,this.canvas=null},e}(d.default);r.default=v,c.CanvasRenderer.registerPlugin("prepare",v)},{"../../core":63,"../BasePrepare":177}],179:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./webgl/WebGLPrepare");Object.defineProperty(r,"webgl",{enumerable:!0,get:function(){return n(i).default}});var o=t("./canvas/CanvasPrepare");Object.defineProperty(r,"canvas",{enumerable:!0,get:function(){return n(o).default}});var s=t("./BasePrepare");Object.defineProperty(r,"BasePrepare",{enumerable:!0,get:function(){return n(s).default}});var a=t("./limiters/CountLimiter");Object.defineProperty(r,"CountLimiter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./limiters/TimeLimiter");Object.defineProperty(r,"TimeLimiter",{enumerable:!0,get:function(){return n(u).default}})},{"./BasePrepare":177,"./canvas/CanvasPrepare":178,"./limiters/CountLimiter":180,"./limiters/TimeLimiter":181,"./webgl/WebGLPrepare":182}],180:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxItemsPerFrame=e,this.itemsLeft=0}return t.prototype.beginFrame=function(){this.itemsLeft=this.maxItemsPerFrame},t.prototype.allowedToUpload=function(){return this.itemsLeft-- >0},t}();r.default=i},{}],181:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxMilliseconds=e,this.frameStart=0}return t.prototype.beginFrame=function(){this.frameStart=Date.now()},t.prototype.allowedToUpload=function(){return Date.now()-this.frameStart 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],2:[function(require,module,exports){ +'use strict'; + +module.exports = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, size), + maxZ = zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, size); + earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and size of the data bounding box +function zOrder(x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; + +},{}],3:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @api private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {Mixed} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @api public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @api public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Boolean} exists Only check if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Add a one-time listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Remove the listeners of a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {Mixed} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn + && (!once || listeners.once) + && (!context || listeners.context === context) + ) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {String|Symbol} [event] The event name. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],4:[function(require,module,exports){ +/** + * isMobile.js v0.4.0 + * + * A simple library to detect Apple phones and tablets, + * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone), + * and any kind of seven inch device, via user agent sniffing. + * + * @author: Kai Mallea (kmallea@gmail.com) + * + * @license: http://creativecommons.org/publicdomain/zero/1.0/ + */ +(function (global) { + + var apple_phone = /iPhone/i, + apple_ipod = /iPod/i, + apple_tablet = /iPad/i, + android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i, // Match 'Android' AND 'Mobile' + android_tablet = /Android/i, + amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i, + amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i, + windows_phone = /IEMobile/i, + windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i, // Match 'Windows' AND 'ARM' + other_blackberry = /BlackBerry/i, + other_blackberry_10 = /BB10/i, + other_opera = /Opera Mini/i, + other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i, + other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i, // Match 'Firefox' AND 'Mobile' + seven_inch = new RegExp( + '(?:' + // Non-capturing group + + 'Nexus 7' + // Nexus 7 + + '|' + // OR + + 'BNTV250' + // B&N Nook Tablet 7 inch + + '|' + // OR + + 'Kindle Fire' + // Kindle Fire + + '|' + // OR + + 'Silk' + // Kindle Fire, Silk Accelerated + + '|' + // OR + + 'GT-P1000' + // Galaxy Tab 7 inch + + ')', // End non-capturing group + + 'i'); // Case-insensitive matching + + var match = function(regex, userAgent) { + return regex.test(userAgent); + }; + + var IsMobileClass = function(userAgent) { + var ua = userAgent || navigator.userAgent; + + // Facebook mobile app's integrated browser adds a bunch of strings that + // match everything. Strip it out if it exists. + var tmp = ua.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + // Twitter mobile app's integrated browser on iPad adds a "Twitter for + // iPhone" string. Same probable happens on other tablet platforms. + // This will confuse detection so strip it out if it exists. + tmp = ua.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + this.apple = { + phone: match(apple_phone, ua), + ipod: match(apple_ipod, ua), + tablet: !match(apple_phone, ua) && match(apple_tablet, ua), + device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua) + }; + this.amazon = { + phone: match(amazon_phone, ua), + tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) + }; + this.android = { + phone: match(amazon_phone, ua) || match(android_phone, ua), + tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua) + }; + this.windows = { + phone: match(windows_phone, ua), + tablet: match(windows_tablet, ua), + device: match(windows_phone, ua) || match(windows_tablet, ua) + }; + this.other = { + blackberry: match(other_blackberry, ua), + blackberry10: match(other_blackberry_10, ua), + opera: match(other_opera, ua), + firefox: match(other_firefox, ua), + chrome: match(other_chrome, ua), + device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua) + }; + this.seven_inch = match(seven_inch, ua); + this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch; + + // excludes 'other' devices and ipods, targeting touchscreen phones + this.phone = this.apple.phone || this.android.phone || this.windows.phone; + + // excludes 7 inch devices, classifying as phone or tablet is left to the user + this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet; + + if (typeof window === 'undefined') { + return this; + } + }; + + var instantiate = function() { + var IM = new IsMobileClass(); + IM.Class = IsMobileClass; + return IM; + }; + + if (typeof module !== 'undefined' && module.exports && typeof window === 'undefined') { + //node + module.exports = IsMobileClass; + } else if (typeof module !== 'undefined' && module.exports && typeof window !== 'undefined') { + //browserify + module.exports = instantiate(); + } else if (typeof define === 'function' && define.amd) { + //AMD + define('isMobile', [], global.isMobile = instantiate()); + } else { + global.isMobile = instantiate(); + } + +})(this); + +},{}],5:[function(require,module,exports){ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],6:[function(require,module,exports){ +var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); + +/** + * Helper class to create a webGL buffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ +var Buffer = function(gl, type, data, drawType) +{ + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The WebGL buffer, created upon instantiation + * + * @member {WebGLBuffer} + */ + this.buffer = gl.createBuffer(); + + /** + * The type of the buffer + * + * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} + */ + this.type = type || gl.ARRAY_BUFFER; + + /** + * The draw type of the buffer + * + * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ + this.drawType = drawType || gl.STATIC_DRAW; + + /** + * The data in the buffer, as a typed array + * + * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} + */ + this.data = EMPTY_ARRAY_BUFFER; + + if(data) + { + this.upload(data); + } +}; + +/** + * Uploads the buffer to the GPU + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload + * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract + * @param dontBind {Boolean} whether to bind the buffer before uploading it + */ +Buffer.prototype.upload = function(data, offset, dontBind) +{ + // todo - needed? + if(!dontBind) this.bind(); + + var gl = this.gl; + + data = data || this.data; + offset = offset || 0; + + if(this.data.byteLength >= data.byteLength) + { + gl.bufferSubData(this.type, offset, data); + } + else + { + gl.bufferData(this.type, data, this.drawType); + } + + this.data = data; +}; +/** + * Binds the buffer + * + */ +Buffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindBuffer(this.type, this.buffer); +}; + +Buffer.createVertexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); +}; + +Buffer.createIndexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); +}; + +Buffer.create = function(gl, type, data, drawType) +{ + return new Buffer(gl, type, data, drawType); +}; + +/** + * Destroys the buffer + * + */ +Buffer.prototype.destroy = function(){ + this.gl.deleteBuffer(this.buffer); +}; + +module.exports = Buffer; + +},{}],7:[function(require,module,exports){ + +var Texture = require('./GLTexture'); + +/** + * Helper class to create a webGL Framebuffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + */ +var Framebuffer = function(gl, width, height) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The frame buffer + * + * @member {WebGLFramebuffer} + */ + this.framebuffer = gl.createFramebuffer(); + + /** + * The stencil buffer + * + * @member {WebGLRenderbuffer} + */ + this.stencil = null; + + /** + * The stencil buffer + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The width of the drawing area of the buffer + * + * @member {Number} + */ + this.width = width || 100; + /** + * The height of the drawing area of the buffer + * + * @member {Number} + */ + this.height = height || 100; +}; + +/** + * Adds a texture to the frame buffer + * @param texture {PIXI.glCore.GLTexture} + */ +Framebuffer.prototype.enableTexture = function(texture) +{ + var gl = this.gl; + + this.texture = texture || new Texture(gl); + + this.texture.bind(); + + //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + this.bind(); + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); +}; + +/** + * Initialises the stencil buffer + */ +Framebuffer.prototype.enableStencil = function() +{ + if(this.stencil)return; + + var gl = this.gl; + + this.stencil = gl.createRenderbuffer(); + + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + + // TODO.. this is depth AND stencil? + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width , this.height ); +}; + +/** + * Erases the drawing area and fills it with a colour + * @param r {Number} the red value of the clearing colour + * @param g {Number} the green value of the clearing colour + * @param b {Number} the blue value of the clearing colour + * @param a {Number} the alpha value of the clearing colour + */ +Framebuffer.prototype.clear = function( r, g, b, a ) +{ + this.bind(); + + var gl = this.gl; + + gl.clearColor(r, g, b, a); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Binds the frame buffer to the WebGL context + */ +Framebuffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); +}; + +/** + * Unbinds the frame buffer to the WebGL context + */ +Framebuffer.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, null ); +}; +/** + * Resizes the drawing area of the buffer to the given width and height + * @param width {Number} the new width + * @param height {Number} the new height + */ +Framebuffer.prototype.resize = function(width, height) +{ + var gl = this.gl; + + this.width = width; + this.height = height; + + if ( this.texture ) + { + this.texture.uploadData(null, width, height); + } + + if ( this.stencil ) + { + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + } +}; + +/** + * Destroys this buffer + */ +Framebuffer.prototype.destroy = function() +{ + var gl = this.gl; + + //TODO + if(this.texture) + { + this.texture.destroy(); + } + + gl.deleteFramebuffer(this.framebuffer); + + this.gl = null; + + this.stencil = null; + this.texture = null; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createRGBA = function(gl, width, height, data) +{ + var texture = Texture.fromData(gl, null, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createFloat32 = function(gl, width, height, data) +{ + // create a new texture.. + var texture = new Texture.fromData(gl, data, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +module.exports = Framebuffer; + +},{"./GLTexture":9}],8:[function(require,module,exports){ + +var compileProgram = require('./shader/compileProgram'), + extractAttributes = require('./shader/extractAttributes'), + extractUniforms = require('./shader/extractUniforms'), + generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + +/** + * Helper class to create a webGL Shader + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + */ +var Shader = function(gl, vertexSrc, fragmentSrc) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc); + + + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); + + var uniformData = extractUniforms(gl, this.program); + + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject( gl, uniformData ); +}; +/** + * Uses this shader + */ +Shader.prototype.bind = function() +{ + this.gl.useProgram(this.program); +}; + +/** + * Destroys this shader + * TODO + */ +Shader.prototype.destroy = function() +{ + // var gl = this.gl; +}; + +module.exports = Shader; + +},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18}],9:[function(require,module,exports){ + +/** + * Helper class to create a WebGL Texture + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL context + * @param width {number} the width of the texture + * @param height {number} the height of the texture + * @param format {number} the pixel format of the texture. defaults to gl.RGBA + * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE + */ +var Texture = function(gl, width, height, format, type) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); + + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; + + + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; + + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; + + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + + +}; + +/** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ +Texture.prototype.upload = function(source) +{ + this.bind(); + + var gl = this.gl; + + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + var newWidth = source.videoWidth || source.width; + var newHeight = source.videoHeight || source.height; + + if(newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } + + // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + +}; + +var FLOATING_POINT_AVAILABLE = false; + +/** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.prototype.uploadData = function(data, width, height) +{ + this.bind(); + + var gl = this.gl; + + + if(data instanceof Float32Array) + { + if(!FLOATING_POINT_AVAILABLE) + { + var ext = gl.getExtension("OES_texture_float"); + + if(ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } + + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = gl.UNSIGNED_BYTE; + } + + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + + if(width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } + + this.width = width; + this.height = height; + + +// texSubImage2D +}; + +/** + * Binds the texture + * @param location + */ +Texture.prototype.bind = function(location) +{ + var gl = this.gl; + + if(location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } + + gl.bindTexture(gl.TEXTURE_2D, this.texture); +}; + +/** + * Unbinds the texture + */ +Texture.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, null); +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.minFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + if(this.mipmap) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.magFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); +}; + +/** + * Enables mipmapping + */ +Texture.prototype.enableMipmap = function() +{ + var gl = this.gl; + + this.bind(); + + this.mipmap = true; + + gl.generateMipmap(gl.TEXTURE_2D); +}; + +/** + * Enables linear filtering + */ +Texture.prototype.enableLinearScaling = function() +{ + this.minFilter(true); + this.magFilter(true); +}; + +/** + * Enables nearest neighbour interpolation + */ +Texture.prototype.enableNearestScaling = function() +{ + this.minFilter(false); + this.magFilter(false); +}; + +/** + * Enables clamping on the texture so WebGL will not repeat it + */ +Texture.prototype.enableWrapClamp = function() +{ + var gl = this.gl; + + this.bind(); + + 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); +}; + +/** + * Enable tiling on the texture + */ +Texture.prototype.enableWrapRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); +}; + +Texture.prototype.enableWrapMirrorRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); +}; + + +/** + * Destroys this texture + */ +Texture.prototype.destroy = function() +{ + var gl = this.gl; + //TODO + gl.deleteTexture(this.texture); +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ +Texture.fromSource = function(gl, source, premultiplyAlpha) +{ + var texture = new Texture(gl); + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); + + return texture; +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.fromData = function(gl, data, width, height) +{ + //console.log(data, width, height); + var texture = new Texture(gl); + texture.uploadData(data, width, height); + + return texture; +}; + + +module.exports = Texture; + +},{}],10:[function(require,module,exports){ + +// state object// +var setVertexAttribArrays = require( './setVertexAttribArrays' ); + +/** + * Helper class to work with WebGL VertexArrayObjects (vaos) + * Only works if WebGL extensions are enabled (they usually are) + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function VertexArrayObject(gl, state) +{ + this.nativeVaoExtension = null; + + if(!VertexArrayObject.FORCE_NATIVE) + { + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + this.nativeState = state; + + if(this.nativeVaoExtension) + { + this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + + var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + // VAO - overwrite the state.. + this.nativeState = { + tempAttribState: new Array(maxAttribs), + attribState: new Array(maxAttribs) + }; + } + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of attributes + * + * @member {Array} + */ + this.attributes = []; + + /** + * @member {PIXI.glCore.GLBuffer} + */ + this.indexBuffer = null; + + /** + * A boolean flag + * + * @member {Boolean} + */ + this.dirty = false; +} + +VertexArrayObject.prototype.constructor = VertexArrayObject; +module.exports = VertexArrayObject; + +/** +* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) +* If you find on older devices that things have gone a bit weird then set this to true. +*/ +/** + * Lets the VAO know if you should use the WebGL extension or the native methods. + * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) + * If you find on older devices that things have gone a bit weird then set this to true. + * @static + * @property {Boolean} FORCE_NATIVE + */ +VertexArrayObject.FORCE_NATIVE = false; + +/** + * Binds the buffer + */ +VertexArrayObject.prototype.bind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + + if(this.dirty) + { + this.dirty = false; + this.activate(); + } + } + else + { + + this.activate(); + } + + return this; +}; + +/** + * Unbinds the buffer + */ +VertexArrayObject.prototype.unbind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + return this; +}; + +/** + * Uses this vao + */ +VertexArrayObject.prototype.activate = function() +{ + + var gl = this.gl; + var lastBuffer = null; + + for (var i = 0; i < this.attributes.length; i++) + { + var attrib = this.attributes[i]; + + if(lastBuffer !== attrib.buffer) + { + attrib.buffer.bind(); + lastBuffer = attrib.buffer; + } + + //attrib.attribute.pointer(attrib.type, attrib.normalized, attrib.stride, attrib.start); + gl.vertexAttribPointer(attrib.attribute.location, + attrib.attribute.size, attrib.type || gl.FLOAT, + attrib.normalized || false, + attrib.stride || 0, + attrib.start || 0); + + + } + + setVertexAttribArrays(gl, this.attributes, this.nativeState); + + this.indexBuffer.bind(); + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + * @param attribute {*} + * @param type {String} + * @param normalized {Boolean} + * @param stride {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start) +{ + this.attributes.push({ + buffer: buffer, + attribute: attribute, + + location: attribute.location, + type: type || this.gl.FLOAT, + normalized: normalized || false, + stride: stride || 0, + start: start || 0 + }); + + this.dirty = true; + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + */ +VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) +{ + this.indexBuffer = buffer; + + this.dirty = true; + + return this; +}; + +/** + * Unbinds this vao and disables it + */ +VertexArrayObject.prototype.clear = function() +{ + // var gl = this.gl; + + // TODO - should this function unbind after clear? + // for now, no but lets see what happens in the real world! + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + } + + this.attributes.length = 0; + this.indexBuffer = null; + + return this; +}; + +/** + * @param type {Number} + * @param size {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.draw = function(type, size, start) +{ + var gl = this.gl; + gl.drawElements(type, size, gl.UNSIGNED_SHORT, start || 0); + + return this; +}; + +/** + * Destroy this vao + */ +VertexArrayObject.prototype.destroy = function() +{ + // lose references + this.gl = null; + this.indexBuffer = null; + this.attributes = null; + this.nativeState = null; + + if(this.nativeVao) + { + this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); + } + + this.nativeVaoExtension = null; + this.nativeVao = null; +}; + +},{"./setVertexAttribArrays":13}],11:[function(require,module,exports){ + +/** + * Helper class to create a webGL Context + * + * @class + * @memberof PIXI.glCore + * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from + * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * @return {WebGLRenderingContext} the WebGL context + */ +var createContext = function(canvas, options) +{ + var gl = canvas.getContext('webgl', options) || + canvas.getContext('experimental-webgl', options); + + if (!gl) + { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + return gl; +}; + +module.exports = createContext; + +},{}],12:[function(require,module,exports){ +var gl = { + createContext: require('./createContext'), + setVertexAttribArrays: require('./setVertexAttribArrays'), + GLBuffer: require('./GLBuffer'), + GLFramebuffer: require('./GLFramebuffer'), + GLShader: require('./GLShader'), + GLTexture: require('./GLTexture'), + VertexArrayObject: require('./VertexArrayObject'), + shader: require('./shader') +}; + +// Export for Node-compatible environments +if (typeof module !== 'undefined' && module.exports) +{ + // Export the module + module.exports = gl; +} + +// Add to the browser window pixi.gl +if (typeof window !== 'undefined') +{ + // add the window object + window.PIXI = window.PIXI || {}; + window.PIXI.glCore = gl; +} + +},{"./GLBuffer":6,"./GLFramebuffer":7,"./GLShader":8,"./GLTexture":9,"./VertexArrayObject":10,"./createContext":11,"./setVertexAttribArrays":13,"./shader":19}],13:[function(require,module,exports){ +// var GL_MAP = {}; + +/** + * @param gl {WebGLRenderingContext} The current WebGL context + * @param attribs {*} + * @param state {*} + */ +var setVertexAttribArrays = function (gl, attribs, state) +{ + var i; + if(state) + { + var tempAttribState = state.tempAttribState, + attribState = state.attribState; + + for (i = 0; i < tempAttribState.length; i++) + { + tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + tempAttribState[attribs[i].attribute.location] = true; + } + + for (i = 0; i < attribState.length; i++) + { + if (attribState[i] !== tempAttribState[i]) + { + attribState[i] = tempAttribState[i]; + + if (state.attribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } + + } + else + { + for (i = 0; i < attribs.length; i++) + { + var attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); + } + } +}; + +module.exports = setVertexAttribArrays; + +},{}],14:[function(require,module,exports){ + +/** + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @return {WebGLProgram} the shader program + */ +var compileProgram = function(gl, vertexSrc, fragmentSrc) +{ + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + + var program = gl.createProgram(); + + gl.attachShader(program, glVertShader); + gl.attachShader(program, glFragShader); + gl.linkProgram(program); + + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + console.error('Pixi.js Error: Could not initialize shader.'); + console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); + console.error('gl.getError()', gl.getError()); + + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') + { + console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + + gl.deleteProgram(program); + program = null; + } + + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + + return program; +}; + +/** + * @private + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @return {WebGLShader} the shader + */ +var compileShader = function (gl, type, src) +{ + var shader = gl.createShader(type); + + gl.shaderSource(shader, src); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + console.log(gl.getShaderInfoLog(shader)); + return null; + } + + return shader; +}; + +module.exports = compileProgram; + +},{}],15:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} Type of value + * @param size {Number} + */ +var defaultValue = function(type, size) +{ + switch (type) + { + case 'float': + return 0; + + case 'vec2': + return new Float32Array(2 * size); + + case 'vec3': + return new Float32Array(3 * size); + + case 'vec4': + return new Float32Array(4 * size); + + case 'int': + case 'sampler2D': + return 0; + + case 'ivec2': + return new Int32Array(2 * size); + + case 'ivec3': + return new Int32Array(3 * size); + + case 'ivec4': + return new Int32Array(4 * size); + + case 'bool': + return false; + + case 'bvec2': + + return booleanArray( 2 * size); + + case 'bvec3': + return booleanArray(3 * size); + + case 'bvec4': + return booleanArray(4 * size); + + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } +}; + +var booleanArray = function(size) +{ + var array = new Array(size); + + for (var i = 0; i < array.length; i++) + { + array[i] = false; + } + + return array; +}; + +module.exports = defaultValue; + +},{}],16:[function(require,module,exports){ + +var mapType = require('./mapType'); +var mapSize = require('./mapSize'); + +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the attributes from + * @return attributes {Object} + */ +var extractAttributes = function(gl, program) +{ + var attributes = {}; + + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + + for (var i = 0; i < totalAttributes; i++) + { + var attribData = gl.getActiveAttrib(program, i); + var type = mapType(gl, attribData.type); + + attributes[attribData.name] = { + type:type, + size:mapSize(type), + location:gl.getAttribLocation(program, attribData.name), + //TODO - make an attribute object + pointer: pointer + }; + } + + return attributes; +}; + +var pointer = function(type, normalized, stride, start){ + // console.log(this.location) + gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +}; + +module.exports = extractAttributes; + +},{"./mapSize":20,"./mapType":21}],17:[function(require,module,exports){ +var mapType = require('./mapType'); +var defaultValue = require('./defaultValue'); + +/** + * Extracts the uniforms + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the uniforms from + * @return uniforms {Object} + */ +var extractUniforms = function(gl, program) +{ + var uniforms = {}; + + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + + for (var i = 0; i < totalUniforms; i++) + { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]/, ""); + var type = mapType(gl, uniformData.type ); + + uniforms[name] = { + type:type, + size:uniformData.size, + location:gl.getUniformLocation(program, name), + value:defaultValue(type, uniformData.size) + }; + } + + return uniforms; +}; + +module.exports = extractUniforms; + +},{"./defaultValue":15,"./mapType":21}],18:[function(require,module,exports){ +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param uniforms {Array} @mat ? + * @return attributes {Object} + */ +var generateUniformAccessObject = function(gl, uniformData) +{ + // this is the object we will be sending back. + // an object hierachy will be created for structs + var uniforms = {data:{}}; + + uniforms.gl = gl; + + var uniformKeys= Object.keys(uniformData); + + for (var i = 0; i < uniformKeys.length; i++) + { + var fullName = uniformKeys[i]; + + var nameTokens = fullName.split('.'); + var name = nameTokens[nameTokens.length - 1]; + + var uniformGroup = getUniformGroup(nameTokens, uniforms); + + var uniform = uniformData[fullName]; + uniformGroup.data[name] = uniform; + + uniformGroup.gl = gl; + + Object.defineProperty(uniformGroup, name, { + get: generateGetter(name), + set: generateSetter(name, uniform) + }); + } + + return uniforms; +}; + +var generateGetter = function(name) +{ + var template = getterTemplate.replace('%%', name); + return new Function(template); // jshint ignore:line +}; + +var generateSetter = function(name, uniform) +{ + var template = setterTemplate.replace(/%%/g, name); + var setTemplate; + + if(uniform.size === 1) + { + setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; + } + else + { + setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; + } + + if(setTemplate) + { + template += "\nthis.gl." + setTemplate + ";"; + } + + return new Function('value', template); // jshint ignore:line +}; + +var getUniformGroup = function(nameTokens, uniform) +{ + var cur = uniform; + + for (var i = 0; i < nameTokens.length - 1; i++) + { + var o = cur[nameTokens[i]] || {data:{}}; + cur[nameTokens[i]] = o; + cur = o; + } + + return cur; +}; + +var getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +var setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;' +].join('\n'); + + +var GLSL_TO_SINGLE_SETTERS = { + + 'float': 'uniform1f(location, value)', + + 'vec2': 'uniform2f(location, value[0], value[1])', + 'vec3': 'uniform3f(location, value[0], value[1], value[2])', + 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', + + 'int': 'uniform1i(location, value)', + 'ivec2': 'uniform2i(location, value[0], value[1])', + 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', + 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'bool': 'uniform1i(location, value)', + 'bvec2': 'uniform2i(location, value[0], value[1])', + 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', + 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'mat2': 'uniformMatrix2fv(location, false, value)', + 'mat3': 'uniformMatrix3fv(location, false, value)', + 'mat4': 'uniformMatrix4fv(location, false, value)', + + 'sampler2D':'uniform1i(location, value)' +}; + +var GLSL_TO_ARRAY_SETTERS = { + + 'float': 'uniform1fv(location, value)', + + 'vec2': 'uniform2fv(location, value)', + 'vec3': 'uniform3fv(location, value)', + 'vec4': 'uniform4fv(location, value)', + + 'int': 'uniform1iv(location, value)', + 'ivec2': 'uniform2iv(location, value)', + 'ivec3': 'uniform3iv(location, value)', + 'ivec4': 'uniform4iv(location, value)', + + 'bool': 'uniform1iv(location, value)', + 'bvec2': 'uniform2iv(location, value)', + 'bvec3': 'uniform3iv(location, value)', + 'bvec4': 'uniform4iv(location, value)', + + 'sampler2D':'uniform1iv(location, value)' +}; + +module.exports = generateUniformAccessObject; + +},{}],19:[function(require,module,exports){ +module.exports = { + compileProgram: require('./compileProgram'), + defaultValue: require('./defaultValue'), + extractAttributes: require('./extractAttributes'), + extractUniforms: require('./extractUniforms'), + generateUniformAccessObject: require('./generateUniformAccessObject'), + mapSize: require('./mapSize'), + mapType: require('./mapType') +}; +},{"./compileProgram":14,"./defaultValue":15,"./extractAttributes":16,"./extractUniforms":17,"./generateUniformAccessObject":18,"./mapSize":20,"./mapType":21}],20:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} + * @return {Number} + */ +var mapSize = function(type) +{ + return GLSL_TO_SIZE[type]; +}; + + +var GLSL_TO_SIZE = { + 'float': 1, + 'vec2': 2, + 'vec3': 3, + 'vec4': 4, + + 'int': 1, + 'ivec2': 2, + 'ivec3': 3, + 'ivec4': 4, + + 'bool': 1, + 'bvec2': 2, + 'bvec3': 3, + 'bvec4': 4, + + 'mat2': 4, + 'mat3': 9, + 'mat4': 16, + + 'sampler2D': 1 +}; + +module.exports = mapSize; + +},{}],21:[function(require,module,exports){ + + +var mapSize = function(gl, type) +{ + if(!GL_TABLE) + { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + + GL_TABLE = {}; + + for(var i = 0; i < typeNames.length; ++i) + { + var tn = typeNames[i]; + GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + } + } + + return GL_TABLE[type]; +}; + +var GL_TABLE = null; + +var GL_TO_GLSL_TYPES = { + 'FLOAT': 'float', + 'FLOAT_VEC2': 'vec2', + 'FLOAT_VEC3': 'vec3', + 'FLOAT_VEC4': 'vec4', + + 'INT': 'int', + 'INT_VEC2': 'ivec2', + 'INT_VEC3': 'ivec3', + 'INT_VEC4': 'ivec4', + + 'BOOL': 'bool', + 'BOOL_VEC2': 'bvec2', + 'BOOL_VEC3': 'bvec3', + 'BOOL_VEC4': 'bvec4', + + 'FLOAT_MAT2': 'mat2', + 'FLOAT_MAT3': 'mat3', + 'FLOAT_MAT4': 'mat4', + + 'SAMPLER_2D': 'sampler2D' +}; + +module.exports = mapSize; + +},{}],22:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) + +},{"_process":23}],23:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],24:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],25:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],26:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],27:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":25,"./encode":26}],28:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":29,"punycode":24,"querystring":27}],29:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],30:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _async = require('./async'); + +var async = _interopRequireWildcard(_async); + +var _Resource = require('./Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// some constants +var MAX_PROGRESS = 100; +var rgxExtractUrlHash = /(#[\w-]+)?$/; + +/** + * Manages the state and loading of multiple resources to load. + * + * @class + */ + +var Loader = function () { + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader() { + var _this = this; + + var baseUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var concurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; + + _classCallCheck(this, Loader); + + /** + * The base url for all resources loaded by this loader. + * + * @member {string} + */ + this.baseUrl = baseUrl; + + /** + * The progress percent of the loader going through the queue. + * + * @member {number} + */ + this.progress = 0; + + /** + * Loading state of the loader, true if it is currently loading resources. + * + * @member {boolean} + */ + this.loading = false; + + /** + * A querystring to append to every URL added to the loader. + * + * This should be a valid query string *without* the question-mark (`?`). The loader will + * also *not* escape values for you. Make sure to escape your parameters with + * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. + * + * @example + * + * ```js + * const loader = new Loader(); + * + * loader.defaultQueryString = 'user=me&password=secret'; + * + * // This will request 'image.png?user=me&password=secret' + * loader.add('image.png').load(); + * + * loader.reset(); + * + * // This will request 'image.png?v=1&user=me&password=secret' + * loader.add('iamge.png?v=1').load(); + * ``` + */ + this.defaultQueryString = ''; + + /** + * The middleware to run before loading each resource. + * + * @member {function[]} + */ + this._beforeMiddleware = []; + + /** + * The middleware to run after loading each resource. + * + * @member {function[]} + */ + this._afterMiddleware = []; + + /** + * The tracks the resources we are currently completing parsing for. + * + * @member {Resource[]} + */ + this._resourcesParsing = []; + + /** + * The `_loadResource` function bound with this object context. + * + * @private + * @member {function} + * @param {Resource} r - The resource to load + * @param {Function} d - The dequeue function + * @return {undefined} + */ + this._boundLoadResource = function (r, d) { + return _this._loadResource(r, d); + }; + + /** + * The resources waiting to be loaded. + * + * @private + * @member {Resource[]} + */ + this._queue = async.queue(this._boundLoadResource, concurrency); + + this._queue.pause(); + + /** + * All the resources for this loader keyed by name. + * + * @member {object} + */ + this.resources = {}; + + /** + * Dispatched once per loaded or errored resource. + * + * The callback looks like {@link Loader.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once per errored resource. + * + * The callback looks like {@link Loader.OnErrorSignal}. + * + * @member {Signal} + */ + this.onError = new _miniSignals2.default(); + + /** + * Dispatched once per loaded resource. + * + * The callback looks like {@link Loader.OnLoadSignal}. + * + * @member {Signal} + */ + this.onLoad = new _miniSignals2.default(); + + /** + * Dispatched when the loader begins to process the queue. + * + * The callback looks like {@link Loader.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched when the queued resources all load. + * + * The callback looks like {@link Loader.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * When the progress changes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnProgressSignal + * @param {Loader} loader - The loader the progress is advancing on. + * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance. + */ + + /** + * When an error occurrs the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnErrorSignal + * @param {Loader} loader - The loader the error happened in. + * @param {Resource} resource - The resource that caused the error. + */ + + /** + * When a load completes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnLoadSignal + * @param {Loader} loader - The loader that laoded the resource. + * @param {Resource} resource - The resource that has completed loading. + */ + + /** + * When the loader starts loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnStartSignal + * @param {Loader} loader - The loader that has started loading resources. + */ + + /** + * When the loader completes loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnCompleteSignal + * @param {Loader} loader - The loader that has finished loading resources. + */ + } + + /** + * Adds a resource (or multiple resources) to the loader queue. + * + * This function can take a wide variety of different parameters. The only thing that is always + * required the url to load. All the following will work: + * + * ```js + * loader + * // normal param syntax + * .add('key', 'http://...', function () {}) + * .add('http://...', function () {}) + * .add('http://...') + * + * // object syntax + * .add({ + * name: 'key2', + * url: 'http://...' + * }, function () {}) + * .add({ + * url: 'http://...' + * }, function () {}) + * .add({ + * name: 'key3', + * url: 'http://...' + * onComplete: function () {} + * }) + * .add({ + * url: 'https://...', + * onComplete: function () {}, + * crossOrigin: true + * }) + * + * // you can also pass an array of objects or urls or both + * .add([ + * { name: 'key4', url: 'http://...', onComplete: function () {} }, + * { url: 'http://...', onComplete: function () {} }, + * 'http://...' + * ]) + * + * // and you can use both params and options + * .add('key', 'http://...', { crossOrigin: true }, function () {}) + * .add('http://...', { crossOrigin: true }, function () {}); + * ``` + * + * @param {string} [name] - The name of the resource to load, if not passed the url is used. + * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @param {object} [options] - The options for the load. + * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should + * the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @param {function} [cb] - Function to call when this specific resource completes loading. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.add = function add(name, url, options, cb) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + + return this; + } + + // if an object is passed instead of params + if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') { + cb = url || name.callback || name.onComplete; + options = name; + url = name.url; + name = name.name || name.key || name.url; + } + + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + cb = options; + options = url; + url = name; + } + + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + cb = options; + options = null; + } + + // if loading already you can only add resources that have a parent. + if (this.loading && (!options || !options.parentResource)) { + throw new Error('Cannot add resources while the loader is running.'); + } + + // check if resource already exists. + if (this.resources[name]) { + throw new Error('Resource named "' + name + '" already exists.'); + } + + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + + // create the store the resource + this.resources[name] = new _Resource2.default(name, url, options); + + if (typeof cb === 'function') { + this.resources[name].onAfterMiddleware.once(cb); + } + + // if actively loading, make sure to adjust progress chunks for that parent and its children + if (this.loading) { + var parent = options.parentResource; + var incompleteChildren = []; + + for (var _i = 0; _i < parent.children.length; ++_i) { + if (!parent.children[_i].isComplete) { + incompleteChildren.push(parent.children[_i]); + } + } + + var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent + var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child + + parent.children.push(this.resources[name]); + parent.progressChunk = eachChunk; + + for (var _i2 = 0; _i2 < incompleteChildren.length; ++_i2) { + incompleteChildren[_i2].progressChunk = eachChunk; + } + + this.resources[name].progressChunk = eachChunk; + } + + // add the resource to the queue + this._queue.push(this.resources[name]); + + return this; + }; + + /** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * + * @method before + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.pre = function pre(fn) { + this._beforeMiddleware.push(fn); + + return this; + }; + + /** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * + * @alias use + * @method after + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.use = function use(fn) { + this._afterMiddleware.push(fn); + + return this; + }; + + /** + * Resets the queue of the loader to prepare for a new load. + * + * @return {Loader} Returns itself. + */ + + + Loader.prototype.reset = function reset() { + this.progress = 0; + this.loading = false; + + this._queue.kill(); + this._queue.pause(); + + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + + if (res._onLoadBinding) { + res._onLoadBinding.detach(); + } + + if (res.isLoading) { + res.abort(); + } + } + + this.resources = {}; + + return this; + }; + + /** + * Starts loading the queued resources. + * + * @param {function} [cb] - Optional callback that will be bound to the `complete` event. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.load = function load(cb) { + // register complete callback if they pass one + if (typeof cb === 'function') { + this.onComplete.once(cb); + } + + // if the queue has already started we are done here + if (this.loading) { + return this; + } + + // distribute progress chunks + var chunk = 100 / this._queue._tasks.length; + + for (var i = 0; i < this._queue._tasks.length; ++i) { + this._queue._tasks[i].data.progressChunk = chunk; + } + + // update loading state + this.loading = true; + + // notify of start + this.onStart.dispatch(this); + + // start loading + this._queue.resume(); + + return this; + }; + + /** + * Prepares a url for usage based on the configuration of this object + * + * @private + * @param {string} url - The url to prepare. + * @return {string} The prepared url. + */ + + + Loader.prototype._prepareUrl = function _prepareUrl(url) { + var parsedUrl = (0, _parseUri2.default)(url, { strictMode: true }); + var result = void 0; + + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { + result = url; + } + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + else if (this.baseUrl.length && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 && url.charAt(0) !== '/') { + result = this.baseUrl + '/' + url; + } else { + result = this.baseUrl + url; + } + + // if we need to add a default querystring, there is a bit more work + if (this.defaultQueryString) { + var hash = rgxExtractUrlHash.exec(result)[0]; + + result = result.substr(0, result.length - hash.length); + + if (result.indexOf('?') !== -1) { + result += '&' + this.defaultQueryString; + } else { + result += '?' + this.defaultQueryString; + } + + result += hash; + } + + return result; + }; + + /** + * Loads a single resource. + * + * @private + * @param {Resource} resource - The resource to load. + * @param {function} dequeue - The function to call when we need to dequeue this item. + */ + + + Loader.prototype._loadResource = function _loadResource(resource, dequeue) { + var _this2 = this; + + resource._dequeue = dequeue; + + // run before middleware + async.eachSeries(this._beforeMiddleware, function (fn, next) { + fn.call(_this2, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, function () { + if (resource.isComplete) { + _this2._onLoad(resource); + } else { + resource._onLoadBinding = resource.onComplete.once(_this2._onLoad, _this2); + resource.load(); + } + }); + }; + + /** + * Called once each resource has loaded. + * + * @private + */ + + + Loader.prototype._onComplete = function _onComplete() { + this.loading = false; + + this.onComplete.dispatch(this, this.resources); + }; + + /** + * Called each time a resources is loaded. + * + * @private + * @param {Resource} resource - The resource that was loaded + */ + + + Loader.prototype._onLoad = function _onLoad(resource) { + var _this3 = this; + + resource._onLoadBinding = null; + + // remove this resource from the async queue, and add it to our list of resources that are being parsed + resource._dequeue(); + this._resourcesParsing.push(resource); + + // run middleware, this *must* happen before dequeue so sub-assets get added properly + async.eachSeries(this._afterMiddleware, function (fn, next) { + fn.call(_this3, resource, next); + }, function () { + resource.onAfterMiddleware.dispatch(resource); + + _this3.progress += resource.progressChunk; + _this3.onProgress.dispatch(_this3, resource); + + if (resource.error) { + _this3.onError.dispatch(resource.error, _this3, resource); + } else { + _this3.onLoad.dispatch(_this3, resource); + } + + _this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1); + + // do completion check + if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) { + _this3.progress = MAX_PROGRESS; + _this3._onComplete(); + } + }); + }; + + return Loader; +}(); + +exports.default = Loader; + +},{"./Resource":31,"./async":32,"mini-signals":36,"parse-uri":37}],31:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// tests is CORS is supported in XHR, if not we need to use XDR +var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest())); +var tempAnchor = null; + +// some status constants +var STATUS_NONE = 0; +var STATUS_OK = 200; +var STATUS_EMPTY = 204; + +// noop +function _noop() {} /* empty */ + +/** + * Manages the state and loading of a resource and all child resources. + * + * @class + */ + +var Resource = function () { + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. + */ + Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) { + setExtMap(Resource._loadTypeMap, extname, loadType); + }; + + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ + + + Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); + }; + + /** + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass + * an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + */ + + + function Resource(name, url, options) { + _classCallCheck(this, Resource); + + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + + options = options || {}; + + /** + * The state flags of this resource. + * + * @member {number} + */ + this._flags = 0; + + // set data url flag, needs to be set early for some _determineX checks to work. + this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); + + /** + * The name of this resource. + * + * @member {string} + * @readonly + */ + this.name = name; + + /** + * The url used to load this resource. + * + * @member {string} + * @readonly + */ + this.url = url; + + /** + * The extension used to load this resource. + * + * @member {string} + * @readonly + */ + this.extension = this._getExtension(); + + /** + * The data that was loaded by the resource. + * + * @member {any} + */ + this.data = null; + + /** + * Is this request cross-origin? If unset, determined automatically. + * + * @member {string} + */ + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + + /** + * The method of loading to use for this resource. + * + * @member {Resource.LOAD_TYPE} + */ + this.loadType = options.loadType || this._determineLoadType(); + + /** + * The type used to load the resource via XHR. If unset, determined automatically. + * + * @member {string} + */ + this.xhrType = options.xhrType; + + /** + * Extra info for middleware, and controlling specifics about how the resource loads. + * + * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + * Meaning it will modify it as it sees fit. + * + * @member {object} + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources + * to. + */ + this.metadata = options.metadata || {}; + + /** + * The error that occurred while loading (if any). + * + * @member {Error} + * @readonly + */ + this.error = null; + + /** + * The XHR object that was used to load this resource. This is only set + * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * + * @member {XMLHttpRequest} + * @readonly + */ + this.xhr = null; + + /** + * The child resources this resource owns. + * + * @member {Resource[]} + * @readonly + */ + this.children = []; + + /** + * The resource type. + * + * @member {Resource.TYPE} + * @readonly + */ + this.type = Resource.TYPE.UNKNOWN; + + /** + * The progress chunk owned by this resource. + * + * @member {number} + * @readonly + */ + this.progressChunk = 0; + + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * + * @private + * @member {function} + */ + this._dequeue = _noop; + + /** + * Used a storage place for the on load binding used privately by the loader. + * + * @private + * @member {function} + */ + this._onLoadBinding = null; + + /** + * The `complete` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundComplete = this.complete.bind(this); + + /** + * The `_onError` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnError = this._onError.bind(this); + + /** + * The `_onProgress` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnProgress = this._onProgress.bind(this); + + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + this._boundXdrOnTimeout = this._xdrOnTimeout.bind(this); + + /** + * Dispatched when the resource beings to load. + * + * The callback looks like {@link Resource.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched each time progress of this resource load updates. + * Not all resources types and loader systems can support this event + * so sometimes it may not be available. If the resource + * is being loaded on a modern browser, using XHR, and the remote server + * properly sets Content-Length headers, then this will be available. + * + * The callback looks like {@link Resource.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once this resource has loaded, if there was an error it will + * be in the `error` property. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * Dispatched after this resource has had all the *after* middleware run on it. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onAfterMiddleware = new _miniSignals2.default(); + + /** + * When the resource starts to load. + * + * @memberof Resource + * @callback OnStartSignal + * @param {Resource} resource - The resource that the event happened on. + */ + + /** + * When the resource reports loading progress. + * + * @memberof Resource + * @callback OnProgressSignal + * @param {Resource} resource - The resource that the event happened on. + * @param {number} percentage - The progress of the load in the range [0, 1]. + */ + + /** + * When the resource finishes loading. + * + * @memberof Resource + * @callback OnCompleteSignal + * @param {Resource} resource - The resource that the event happened on. + */ + } + + /** + * Stores whether or not this url is a data url. + * + * @member {boolean} + * @readonly + */ + + + /** + * Marks the resource as complete. + * + */ + Resource.prototype.complete = function complete() { + // TODO: Clean this up in a wrapper or something...gross.... + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + + this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true); + this._setFlag(Resource.STATUS_FLAGS.LOADING, false); + + this.onComplete.dispatch(this); + }; + + /** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ + + + Resource.prototype.abort = function abort(message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + + // store error + this.error = new Error(message); + + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } else if (this.xdr) { + this.xdr.abort(); + } else if (this.data) { + // single source + if (this.data.src) { + this.data.src = Resource.EMPTY_GIF; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + + // done now. + this.complete(); + }; + + /** + * Kicks off loading of this resource. This method is asynchronous. + * + * @param {function} [cb] - Optional callback to call once the resource is loaded. + */ + + + Resource.prototype.load = function load(cb) { + var _this = this; + + if (this.isLoading) { + return; + } + + if (this.isComplete) { + if (cb) { + setTimeout(function () { + return cb(_this); + }, 1); + } + + return; + } else if (cb) { + this.onComplete.once(cb); + } + + this._setFlag(Resource.STATUS_FLAGS.LOADING, true); + + this.onStart.dispatch(this); + + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + + switch (this.loadType) { + case Resource.LOAD_TYPE.IMAGE: + this.type = Resource.TYPE.IMAGE; + this._loadElement('image'); + break; + + case Resource.LOAD_TYPE.AUDIO: + this.type = Resource.TYPE.AUDIO; + this._loadSourceElement('audio'); + break; + + case Resource.LOAD_TYPE.VIDEO: + this.type = Resource.TYPE.VIDEO; + this._loadSourceElement('video'); + break; + + case Resource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } else { + this._loadXhr(); + } + break; + } + }; + + /** + * Checks if the flag is set. + * + * @private + * @param {number} flag - The flag to check. + * @return {boolean} True if the flag is set. + */ + + + Resource.prototype._hasFlag = function _hasFlag(flag) { + return !!(this._flags & flag); + }; + + /** + * (Un)Sets the flag. + * + * @private + * @param {number} flag - The flag to (un)set. + * @param {boolean} value - Whether to set or (un)set the flag. + */ + + + Resource.prototype._setFlag = function _setFlag(flag, value) { + this._flags = value ? this._flags | flag : this._flags & ~flag; + }; + + /** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadElement = function _loadElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'image' && typeof window.Image !== 'undefined') { + this.data = new Image(); + } else { + this.data = document.createElement(type); + } + + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + }; + + /** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadSourceElement = function _loadSourceElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'audio' && typeof window.Audio !== 'undefined') { + this.data = new Audio(); + } else { + this.data = document.createElement(type); + } + + if (this.data === null) { + this.abort('Unsupported element: ' + type); + + return; + } + + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } else if (Array.isArray(this.url)) { + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i])); + } + } else { + this.data.appendChild(this._createSource(type, this.url)); + } + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + + this.data.load(); + }; + + /** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ + + + Resource.prototype._loadXhr = function _loadXhr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xhr = this.xhr = new XMLHttpRequest(); + + // set the request type and url + xhr.open('GET', this.url, true); + + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; + } else { + xhr.responseType = this.xhrType; + } + + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + + xhr.send(); + }; + + /** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ + + + Resource.prototype._loadXdr = function _loadXdr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xdr = this.xhr = new XDomainRequest(); + + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = 5000; + + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXdrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + + xdr.open('GET', this.url, true); + + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { + return xdr.send(); + }, 1); + }; + + /** + * Creates a source used in loading via an element. + * + * @private + * @param {string} type - The element type (video or audio). + * @param {string} url - The source URL to load from. + * @param {string} [mime] - The mime type of the video + * @return {HTMLSourceElement} The source element. + */ + + + Resource.prototype._createSource = function _createSource(type, url, mime) { + if (!mime) { + mime = type + '/' + url.substr(url.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = url; + source.type = mime; + + return source; + }; + + /** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ + + + Resource.prototype._onError = function _onError(event) { + this.abort('Failed to load element using: ' + event.target.nodeName); + }; + + /** + * Called if a load progress event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ + + + Resource.prototype._onProgress = function _onProgress(event) { + if (event && event.lengthComputable) { + this.onProgress.dispatch(this, event.loaded / event.total); + } + }; + + /** + * Called if an error event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestErrorEvent|Event} event - Error event. + */ + + + Resource.prototype._xhrOnError = function _xhrOnError() { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"'); + }; + + /** + * Called if an abort event fires for xhr. + * + * @private + * @param {XMLHttpRequestAbortEvent} event - Abort Event + */ + + + Resource.prototype._xhrOnAbort = function _xhrOnAbort() { + this.abort(reqType(this.xhr) + ' Request was aborted by the user.'); + }; + + /** + * Called if a timeout event fires for xdr. + * + * @private + * @param {Event} event - Timeout event. + */ + + + Resource.prototype._xdrOnTimeout = function _xdrOnTimeout() { + this.abort(reqType(this.xhr) + ' Request timed out.'); + }; + + /** + * Called when data successfully loads from an xhr/xdr request. + * + * @private + * @param {XMLHttpRequestLoadEvent|Event} event - Load event + */ + + + Resource.prototype._xhrOnLoad = function _xhrOnLoad() { + var xhr = this.xhr; + var status = typeof xhr.status === 'undefined' ? xhr.status : STATUS_OK; // XDR has no `.status`, assume 200. + + // status can be 0 when using the `file://` protocol so we also check if a response is set + if (status === STATUS_OK || status === STATUS_EMPTY || status === STATUS_NONE && xhr.responseText.length > 0) { + // if text, just return it + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { + this.data = xhr.responseText; + this.type = Resource.TYPE.TEXT; + } + // if json, parse into json object + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(xhr.responseText); + this.type = Resource.TYPE.JSON; + } catch (e) { + this.abort('Error trying to parse loaded json: ' + e); + + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (window.DOMParser) { + var domparser = new DOMParser(); + + this.data = domparser.parseFromString(xhr.responseText, 'text/xml'); + } else { + var div = document.createElement('div'); + + div.innerHTML = xhr.responseText; + + this.data = div; + } + + this.type = Resource.TYPE.XML; + } catch (e) { + this.abort('Error trying to parse loaded xml: ' + e); + + return; + } + } + // other types just return the response + else { + this.data = xhr.response || xhr.responseText; + } + } else { + this.abort('[' + xhr.status + '] ' + xhr.statusText + ': ' + xhr.responseURL); + + return; + } + + this.complete(); + }; + + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * + * @private + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ + + + Resource.prototype._determineCrossOrigin = function _determineCrossOrigin(url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = (0, _parseUri2.default)(tempAnchor.href, { strictMode: true }); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + var protocol = url.protocol ? url.protocol + ':' : ''; + + // if cross origin + if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; + }; + + /** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. + */ + + + Resource.prototype._determineXhrType = function _determineXhrType() { + return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT; + }; + + /** + * Determines the loadType of a resource based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.LOAD_TYPE} The loadType to use. + */ + + + Resource.prototype._determineLoadType = function _determineLoadType() { + return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR; + }; + + /** + * Extracts the extension (sans '.') of the file being loaded by the resource. + * + * @private + * @return {string} The extension. + */ + + + Resource.prototype._getExtension = function _getExtension() { + var url = this.url; + var ext = ''; + + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } else { + var queryStart = url.indexOf('?'); + + if (queryStart !== -1) { + url = url.substring(0, queryStart); + } + + ext = url.substring(url.lastIndexOf('.') + 1); + } + + return ext.toLowerCase(); + }; + + /** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * + * @private + * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. + * @return {string} The mime type to use. + */ + + + Resource.prototype._getMimeFromXhrType = function _getMimeFromXhrType(type) { + switch (type) { + case Resource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + + case Resource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + + case Resource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + + case Resource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + + case Resource.XHR_RESPONSE_TYPE.DEFAULT: + case Resource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + + } + }; + + _createClass(Resource, [{ + key: 'isDataUrl', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL); + } + + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isComplete', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE); + } + + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isLoading', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.LOADING); + } + }]); + + return Resource; +}(); + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ + + +exports.default = Resource; +Resource.STATUS_FLAGS = { + NONE: 0, + DATA_URL: 1 << 0, + COMPLETE: 1 << 1, + LOADING: 1 << 2 +}; + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ +Resource.TYPE = { + UNKNOWN: 0, + JSON: 1, + XML: 2, + IMAGE: 3, + AUDIO: 4, + VIDEO: 5, + TEXT: 6 +}; + +/** + * The types of loading a resource can use. + * + * @static + * @readonly + * @enum {number} + */ +Resource.LOAD_TYPE = { + /** Uses XMLHttpRequest to load the resource. */ + XHR: 1, + /** Uses an `Image` object to load the resource. */ + IMAGE: 2, + /** Uses an `Audio` object to load the resource. */ + AUDIO: 3, + /** Uses a `Video` object to load the resource. */ + VIDEO: 4 +}; + +/** + * The XHR ready states, used internally. + * + * @static + * @readonly + * @enum {string} + */ +Resource.XHR_RESPONSE_TYPE = { + /** string */ + DEFAULT: 'text', + /** ArrayBuffer */ + BUFFER: 'arraybuffer', + /** Blob */ + BLOB: 'blob', + /** Document */ + DOCUMENT: 'document', + /** Object */ + JSON: 'json', + /** String */ + TEXT: 'text' +}; + +Resource._loadTypeMap = { + // images + gif: Resource.LOAD_TYPE.IMAGE, + png: Resource.LOAD_TYPE.IMAGE, + bmp: Resource.LOAD_TYPE.IMAGE, + jpg: Resource.LOAD_TYPE.IMAGE, + jpeg: Resource.LOAD_TYPE.IMAGE, + tif: Resource.LOAD_TYPE.IMAGE, + tiff: Resource.LOAD_TYPE.IMAGE, + webp: Resource.LOAD_TYPE.IMAGE, + tga: Resource.LOAD_TYPE.IMAGE, + svg: Resource.LOAD_TYPE.IMAGE, + 'svg+xml': Resource.LOAD_TYPE.IMAGE, // for SVG data urls + + // audio + mp3: Resource.LOAD_TYPE.AUDIO, + ogg: Resource.LOAD_TYPE.AUDIO, + wav: Resource.LOAD_TYPE.AUDIO, + + // videos + mp4: Resource.LOAD_TYPE.VIDEO, + webm: Resource.LOAD_TYPE.VIDEO +}; + +Resource._xhrTypeMap = { + // xml + xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. + // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, + // this should probably be fine. + tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // images + gif: Resource.XHR_RESPONSE_TYPE.BLOB, + png: Resource.XHR_RESPONSE_TYPE.BLOB, + bmp: Resource.XHR_RESPONSE_TYPE.BLOB, + jpg: Resource.XHR_RESPONSE_TYPE.BLOB, + jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, + tif: Resource.XHR_RESPONSE_TYPE.BLOB, + tiff: Resource.XHR_RESPONSE_TYPE.BLOB, + webp: Resource.XHR_RESPONSE_TYPE.BLOB, + tga: Resource.XHR_RESPONSE_TYPE.BLOB, + + // json + json: Resource.XHR_RESPONSE_TYPE.JSON, + + // text + text: Resource.XHR_RESPONSE_TYPE.TEXT, + txt: Resource.XHR_RESPONSE_TYPE.TEXT, + + // fonts + ttf: Resource.XHR_RESPONSE_TYPE.BUFFER, + otf: Resource.XHR_RESPONSE_TYPE.BUFFER +}; + +// We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif +Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; + +/** + * Quick helper to set a value on one of the extension maps. Ensures there is no + * dot at the start of the extension. + * + * @ignore + * @param {object} map - The map to set on. + * @param {string} extname - The extension (or key) to set. + * @param {number} val - The value to set. + */ +function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + + if (!extname) { + return; + } + + map[extname] = val; +} + +/** + * Quick helper to get string xhr type. + * + * @ignore + * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. + * @return {string} The type. + */ +function reqType(xhr) { + return xhr.toString().replace('object ', ''); +} + +},{"mini-signals":36,"parse-uri":37}],32:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.eachSeries = eachSeries; +exports.queue = queue; +/** + * Smaller version of the async library constructs. + * + */ +function _noop() {} /* empty */ + +/** + * Iterates an array in series. + * + * @param {*[]} array - Array to iterate. + * @param {function} iterator - Function to call for each element. + * @param {function} callback - Function to call when done, or on error. + */ +function eachSeries(array, iterator, callback) { + var i = 0; + var len = array.length; + + (function next(err) { + if (err || i === len) { + if (callback) { + callback(err); + } + + return; + } + + iterator(array[i++], next); + })(); +} + +/** + * Ensures a function is only called once. + * + * @param {function} fn - The function to wrap. + * @return {function} The wrapping function. + */ +function onlyOnce(fn) { + return function onceWrapper() { + if (fn === null) { + throw new Error('Callback was already called.'); + } + + var callFn = fn; + + fn = null; + callFn.apply(this, arguments); + }; +} + +/** + * Async queue implementation, + * + * @param {function} worker - The worker function to call for each task. + * @param {number} concurrency - How many workers to run in parrallel. + * @return {*} The async queue object. + */ +function queue(worker, concurrency) { + if (concurrency == null) { + // eslint-disable-line no-eq-null,eqeqeq + concurrency = 1; + } else if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + + var workers = 0; + var q = { + _tasks: [], + concurrency: concurrency, + saturated: _noop, + unsaturated: _noop, + buffer: concurrency / 4, + empty: _noop, + drain: _noop, + error: _noop, + started: false, + paused: false, + push: function push(data, callback) { + _insert(data, false, callback); + }, + kill: function kill() { + workers = 0; + q.drain = _noop; + q.started = false; + q._tasks = []; + }, + unshift: function unshift(data, callback) { + _insert(data, true, callback); + }, + process: function process() { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var task = q._tasks.shift(); + + if (q._tasks.length === 0) { + q.empty(); + } + + workers += 1; + + if (workers === q.concurrency) { + q.saturated(); + } + + worker(task.data, onlyOnce(_next(task))); + } + }, + length: function length() { + return q._tasks.length; + }, + running: function running() { + return workers; + }, + idle: function idle() { + return q._tasks.length + workers === 0; + }, + pause: function pause() { + if (q.paused === true) { + return; + } + + q.paused = true; + }, + resume: function resume() { + if (q.paused === false) { + return; + } + + q.paused = false; + + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= q.concurrency; w++) { + q.process(); + } + } + }; + + function _insert(data, insertAtFront, callback) { + if (callback != null && typeof callback !== 'function') { + // eslint-disable-line no-eq-null,eqeqeq + throw new Error('task callback must be a function'); + } + + q.started = true; + + if (data == null && q.idle()) { + // eslint-disable-line no-eq-null,eqeqeq + // call drain immediately if there are no tasks + setTimeout(function () { + return q.drain(); + }, 1); + + return; + } + + var item = { + data: data, + callback: typeof callback === 'function' ? callback : _noop + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + setTimeout(function () { + return q.process(); + }, 1); + } + + function _next(task) { + return function next() { + workers -= 1; + + task.callback.apply(task, arguments); + + if (arguments[0] != null) { + // eslint-disable-line no-eq-null,eqeqeq + q.error(arguments[0], task.data); + } + + if (workers <= q.concurrency - q.buffer) { + q.unsaturated(); + } + + if (q.idle()) { + q.drain(); + } + + q.process(); + }; + } + + return q; +} + +},{}],33:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.encodeBinary = encodeBinary; +var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +function encodeBinary(input) { + var output = ''; + var inx = 0; + + while (inx < input.length) { + // Fill byte buffer array + var bytebuffer = [0, 0, 0]; + var encodedCharIndexes = [0, 0, 0, 0]; + + for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } else { + bytebuffer[jnx] = 0; + } + } + + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4; + + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6; + + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + + // Determine whether padding happened, and adjust accordingly + var paddingBytes = inx - (input.length - 1); + + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + + default: + break; // No padding - proceed + } + + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) { + output += _keyStr.charAt(encodedCharIndexes[_jnx]); + } + } + + return output; +} + +},{}],34:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Loader = require('./Loader'); + +var _Loader2 = _interopRequireDefault(_Loader); + +var _Resource = require('./Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +var _async = require('./async'); + +var async = _interopRequireWildcard(_async); + +var _b = require('./b64'); + +var b64 = _interopRequireWildcard(_b); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +_Loader2.default.Resource = _Resource2.default; +_Loader2.default.async = async; +_Loader2.default.base64 = b64; + +// export manually, and also as default +module.exports = _Loader2.default; // eslint-disable-line no-undef +exports.default = _Loader2.default; + +},{"./Loader":30,"./Resource":31,"./async":32,"./b64":33}],35:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +exports.blobMiddlewareFactory = blobMiddlewareFactory; + +var _Resource = require('../../Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +var _b = require('../../b64'); + +var _b2 = _interopRequireDefault(_b); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Url = window.URL || window.webkitURL; + +// a middleware for transforming XHR loaded Blobs into more useful objects +function blobMiddlewareFactory() { + return function blobMiddleware(resource, next) { + if (!resource.data) { + next(); + + return; + } + + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === _Resource2.default.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!window.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = 'data:' + type + ';base64,' + _b2.default.encodeBinary(resource.xhr.responseText); + + resource.type = _Resource2.default.TYPE.IMAGE; + + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + + next(); + }; + + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var _ret = function () { + var src = Url.createObjectURL(resource.data); + + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src; + + resource.type = _Resource2.default.TYPE.IMAGE; + + // cleanup the no longer used blob after the image loads + // TODO: Is this correct? Will the image be invalid after revoking? + resource.data.onload = function () { + Url.revokeObjectURL(src); + resource.data.onload = null; + + next(); + }; + + // next will be called on load. + return { + v: void 0 + }; + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + } + + next(); + }; +} + +},{"../../Resource":31,"../../b64":33}],36:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + +var MiniSignalBinding = (function () { + function MiniSignalBinding(fn, once, thisArg) { + if (once === undefined) once = false; + + _classCallCheck(this, MiniSignalBinding); + + this._fn = fn; + this._once = once; + this._thisArg = thisArg; + this._next = this._prev = this._owner = null; + } + + _createClass(MiniSignalBinding, [{ + key: 'detach', + value: function detach() { + if (this._owner === null) return false; + this._owner.detach(this); + return true; + } + }]); + + return MiniSignalBinding; +})(); + +function _addMiniSignalBinding(self, node) { + if (!self._head) { + self._head = node; + self._tail = node; + } else { + self._tail._next = node; + node._prev = self._tail; + self._tail = node; + } + + node._owner = self; + + return node; +} + +var MiniSignal = (function () { + function MiniSignal() { + _classCallCheck(this, MiniSignal); + + this._head = this._tail = undefined; + } + + _createClass(MiniSignal, [{ + key: 'handlers', + value: function handlers() { + var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; + + var node = this._head; + + if (exists) return !!node; + + var ee = []; + + while (node) { + ee.push(node); + node = node._next; + } + + return ee; + } + }, { + key: 'has', + value: function has(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.'); + } + + return node._owner === this; + } + }, { + key: 'dispatch', + value: function dispatch() { + var node = this._head; + + if (!node) return false; + + while (node) { + if (node._once) this.detach(node); + node._fn.apply(node._thisArg, arguments); + node = node._next; + } + + return true; + } + }, { + key: 'add', + value: function add(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#add(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg)); + } + }, { + key: 'once', + value: function once(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#once(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg)); + } + }, { + key: 'detach', + value: function detach(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.'); + } + if (node._owner !== this) return this; + + if (node._prev) node._prev._next = node._next; + if (node._next) node._next._prev = node._prev; + + if (node === this._head) { + this._head = node._next; + if (node._next === null) { + this._tail = null; + } + } else if (node === this._tail) { + this._tail = node._prev; + this._tail._next = null; + } + + node._owner = null; + return this; + } + }, { + key: 'detachAll', + value: function detachAll() { + var node = this._head; + if (!node) return this; + + this._head = this._tail = null; + + while (node) { + node._owner = null; + node = node._next; + } + return this; + } + }]); + + return MiniSignal; +})(); + +MiniSignal.MiniSignalBinding = MiniSignalBinding; + +exports['default'] = MiniSignal; +module.exports = exports['default']; + +},{}],37:[function(require,module,exports){ +'use strict' + +module.exports = function parseURI (str, opts) { + opts = opts || {} + + var o = { + key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], + q: { + name: 'queryKey', + parser: /(?:^|&)([^&=]*)=?([^&]*)/g + }, + parser: { + strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, + loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ + } + } + + var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str) + var uri = {} + var i = 14 + + while (i--) uri[o.key[i]] = m[i] || '' + + uri[o.q.name] = {} + uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { + if ($1) uri[o.q.name][$1] = $2 + }) + + return uri +} + +},{}],38:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +var _accessibleTarget = require('./accessibleTarget'); + +var _accessibleTarget2 = _interopRequireDefault(_accessibleTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// add some extra variables to the container.. +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _accessibleTarget2.default); + +var KEY_CODE_TAB = 9; + +var DIV_TOUCH_SIZE = 100; +var DIV_TOUCH_POS_X = 0; +var DIV_TOUCH_POS_Y = 0; +var DIV_TOUCH_ZINDEX = 2; + +var DIV_HOOK_SIZE = 1; +var DIV_HOOK_POS_X = -1000; +var DIV_HOOK_POS_Y = -1000; +var DIV_HOOK_ZINDEX = 2; + +/** + * The Accessibility manager reacreates the ability to tab and and have content read by screen + * readers. This is very important as it can possibly help people with disabilities access pixi + * content. + * + * Much like interaction any DisplayObject can be made accessible. This manager will map the + * events as if the mouse was being used, minimizing the efferot required to implement. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.accessibility + * + * @class + * @memberof PIXI.accessibility + */ + +var AccessibilityManager = function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + _classCallCheck(this, AccessibilityManager); + + if ((_ismobilejs2.default.tablet || _ismobilejs2.default.phone) && !navigator.isCocoonJS) { + this.createTouchHook(); + } + + // first we create a div that will sit over the pixi element. This is where the div overlays will go. + var div = document.createElement('div'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + 'px'; + div.style.left = DIV_TOUCH_POS_Y + 'px'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + + /** + * This is the dom element that will sit over the pixi element. This is where the div overlays will go. + * + * @type {HTMLElement} + * @private + */ + this.div = div; + + /** + * A simple pool for storing divs. + * + * @type {*} + * @private + */ + this.pool = []; + + /** + * This is a tick used to check if an object is no longer being rendered. + * + * @type {Number} + * @private + */ + this.renderId = 0; + + /** + * Setting this to true will visually show the divs + * + * @type {boolean} + */ + this.debug = false; + + /** + * The renderer this accessibility manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * The array of currently active accessible items. + * + * @member {Array<*>} + * @private + */ + this.children = []; + + /** + * pre-bind the functions + * + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + + /** + * stores the state of the manager. If there are no accessible objects or the mouse is moving the will be false. + * + * @member {Array<*>} + * @private + */ + this.isActive = false; + this.isMobileAccessabillity = false; + + // let listen for tab.. once pressed we can fire up and show the accessibility layer + window.addEventListener('keydown', this._onKeyDown, false); + } + + /** + * Creates the touch hooks. + * + */ + + + AccessibilityManager.prototype.createTouchHook = function createTouchHook() { + var _this = this; + + var hookDiv = document.createElement('button'); + + hookDiv.style.width = DIV_HOOK_SIZE + 'px'; + hookDiv.style.height = DIV_HOOK_SIZE + 'px'; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + 'px'; + hookDiv.style.left = DIV_HOOK_POS_Y + 'px'; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX; + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'HOOK DIV'; + + hookDiv.addEventListener('focus', function () { + _this.isMobileAccessabillity = true; + _this.activate(); + document.body.removeChild(hookDiv); + }); + + document.body.appendChild(hookDiv); + }; + + /** + * Activating will cause the Accessibility layer to be shown. This is called when a user + * preses the tab key + * + * @private + */ + + + AccessibilityManager.prototype.activate = function activate() { + if (this.isActive) { + return; + } + + this.isActive = true; + + window.document.addEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown, false); + + this.renderer.on('postrender', this.update, this); + + if (this.renderer.view.parentNode) { + this.renderer.view.parentNode.appendChild(this.div); + } + }; + + /** + * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves + * the mouse + * + * @private + */ + + + AccessibilityManager.prototype.deactivate = function deactivate() { + if (!this.isActive || this.isMobileAccessabillity) { + return; + } + + this.isActive = false; + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.addEventListener('keydown', this._onKeyDown, false); + + this.renderer.off('postrender', this.update); + + if (this.div.parentNode) { + this.div.parentNode.removeChild(this.div); + } + }; + + /** + * This recursive function will run throught he scene graph and add any new accessible objects to the DOM layer. + * + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + + + AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects(displayObject) { + if (!displayObject.visible) { + return; + } + + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + + displayObject.renderId = this.renderId; + } + + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + this.updateAccessibleObjects(children[i]); + } + }; + + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * + * @private + */ + + + AccessibilityManager.prototype.update = function update() { + if (!this.renderer.renderingToScreen) { + return; + } + + // update children... + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + + var rect = this.renderer.view.getBoundingClientRect(); + var sx = rect.width / this.renderer.width; + var sy = rect.height / this.renderer.height; + + var div = this.div; + + div.style.left = rect.left + 'px'; + div.style.top = rect.top + 'px'; + div.style.width = this.renderer.width + 'px'; + div.style.height = this.renderer.height + 'px'; + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + + core.utils.removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + + i--; + + if (this.children.length === 0) { + this.deactivate(); + } + } else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + + if (child.hitArea) { + div.style.left = (wt.tx + hitArea.x * wt.a) * sx + 'px'; + div.style.top = (wt.ty + hitArea.y * wt.d) * sy + 'px'; + + div.style.width = hitArea.width * wt.a * sx + 'px'; + div.style.height = hitArea.height * wt.d * sy + 'px'; + } else { + hitArea = child.getBounds(); + + this.capHitArea(hitArea); + + div.style.left = hitArea.x * sx + 'px'; + div.style.top = hitArea.y * sy + 'px'; + + div.style.width = hitArea.width * sx + 'px'; + div.style.height = hitArea.height * sy + 'px'; + } + } + } + + // increment the render id.. + this.renderId++; + }; + + /** + * TODO: docs. + * + * @param {Rectangle} hitArea - TODO docs + */ + + + AccessibilityManager.prototype.capHitArea = function capHitArea(hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + + if (hitArea.x + hitArea.width > this.renderer.width) { + hitArea.width = this.renderer.width - hitArea.x; + } + + if (hitArea.y + hitArea.height > this.renderer.height) { + hitArea.height = this.renderer.height - hitArea.y; + } + }; + + /** + * Adds a DisplayObject to the accessibility manager + * + * @private + * @param {DisplayObject} displayObject - The child to make accessible. + */ + + + AccessibilityManager.prototype.addChild = function addChild(displayObject) { + // this.activate(); + + var div = this.pool.pop(); + + if (!div) { + div = document.createElement('button'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + div.style.borderStyle = 'none'; + + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + + if (displayObject.accessibleTitle) { + div.title = displayObject.accessibleTitle; + } else if (!displayObject.accessibleTitle && !displayObject.accessibleHint) { + div.title = 'displayObject ' + this.tabIndex; + } + + if (displayObject.accessibleHint) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + + // + + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + + /** + * Maps the div button press to pixi's InteractionManager (click) + * + * @private + * @param {MouseEvent} e - The click event. + */ + + + AccessibilityManager.prototype._onClick = function _onClick(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixis InteractionManager (mouseover) + * + * @private + * @param {FocusEvent} e - The focus event. + */ + + + AccessibilityManager.prototype._onFocus = function _onFocus(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixis InteractionManager (mouseout) + * + * @private + * @param {FocusEvent} e - The focusout event. + */ + + + AccessibilityManager.prototype._onFocusOut = function _onFocusOut(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); + }; + + /** + * Is called when a key is pressed + * + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + + + AccessibilityManager.prototype._onKeyDown = function _onKeyDown(e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + + this.activate(); + }; + + /** + * Is called when the mouse moves across the renderer element + * + * @private + */ + + + AccessibilityManager.prototype._onMouseMove = function _onMouseMove() { + this.deactivate(); + }; + + /** + * Destroys the accessibility manager + * + */ + + + AccessibilityManager.prototype.destroy = function destroy() { + this.div = null; + + for (var i = 0; i < this.children.length; i++) { + this.children[i].div = null; + } + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.removeEventListener('keydown', this._onKeyDown); + + this.pool = null; + this.children = null; + this.renderer = null; + }; + + return AccessibilityManager; +}(); + +exports.default = AccessibilityManager; + + +core.WebGLRenderer.registerPlugin('accessibility', AccessibilityManager); +core.CanvasRenderer.registerPlugin('accessibility', AccessibilityManager); + +},{"../core":63,"./accessibleTarget":39,"ismobilejs":4}],39:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Default property values of accessible objects + * used by {@link PIXI.accessibility.AccessibilityManager}. + * + * @function accessibleTarget + * @memberof PIXI.accessibility + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibility.accessibleTarget + * ); + */ +exports.default = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * + * @member {boolean} + */ + accessible: false, + + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * + * @member {string} + */ + accessibleTitle: null, + + /** + * Sets the aria-label attribute of the shadow div + * + * @member {string} + */ + accessibleHint: null, + + /** + * @todo Needs docs. + */ + tabIndex: 0, + + /** + * @todo Needs docs. + */ + _accessibleActive: false, + + /** + * @todo Needs docs. + */ + _accessibleDiv: false +}; + +},{}],40:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _accessibleTarget = require('./accessibleTarget'); + +Object.defineProperty(exports, 'accessibleTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_accessibleTarget).default; + } +}); + +var _AccessibilityManager = require('./AccessibilityManager'); + +Object.defineProperty(exports, 'AccessibilityManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AccessibilityManager).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./AccessibilityManager":38,"./accessibleTarget":39}],41:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +var _Container = require('./display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _ticker = require('./ticker'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Convenience class to create a new PIXI application. + * This class automatically creates the renderer, ticker + * and root container. + * + * @example + * // Create the application + * const app = new PIXI.Application(); + * + * // Add the view to the DOM + * document.body.appendChild(app.view); + * + * // ex, add display objects + * app.stage.addChild(PIXI.Sprite.fromImage('something.png')); + * + * @class + * @memberof PIXI + */ +var Application = function () { + /** + * @param {number} [width=800] - the width of the renderers view + * @param {number} [height=600] - the height of the renderers view + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [noWebGL=false] - prevents selection of WebGL renderer, even if such is present + * @param {boolean} [options.legacy=false] - If true Pixi will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering try setting this to true. + * @param {boolean} [useSharedTicker=false] - `true` to use PIXI.ticker.shared, `false` to create new ticker. + */ + function Application(width, height, options, noWebGL) { + var useSharedTicker = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; + + _classCallCheck(this, Application); + + /** + * WebGL renderer if available, otherwise CanvasRenderer + * @member {PIXI.WebGLRenderer|PIXI.CanvasRenderer} + */ + this.renderer = (0, _autoDetectRenderer.autoDetectRenderer)(width, height, options, noWebGL); + + /** + * The root display container that's rendered. + * @member {PIXI.Container} + */ + this.stage = new _Container2.default(); + + /** + * Internal reference to the ticker + * @member {PIXI.ticker.Ticker} + * @private + */ + this._ticker = null; + + /** + * Ticker for doing render updates. + * @member {PIXI.ticker.Ticker} + * @default PIXI.ticker.shared + */ + this.ticker = useSharedTicker ? _ticker.shared : new _ticker.Ticker(); + + // Start the rendering + this.start(); + } + + /** + * Render the current stage. + */ + Application.prototype.render = function render() { + this.renderer.render(this.stage); + }; + + /** + * Convenience method for stopping the render. + */ + + + Application.prototype.stop = function stop() { + this._ticker.stop(); + }; + + /** + * Convenience method for starting the render. + */ + + + Application.prototype.start = function start() { + this._ticker.start(); + }; + + /** + * Reference to the renderer's canvas element. + * @member {HTMLCanvasElement} + * @readonly + */ + + + /** + * Destroy and don't use after this. + * @param {Boolean} [removeView=false] Automatically remove canvas from DOM. + */ + Application.prototype.destroy = function destroy(removeView) { + this.stop(); + this.ticker = null; + + this.stage.destroy(); + this.stage = null; + + this.renderer.destroy(removeView); + this.renderer = null; + }; + + _createClass(Application, [{ + key: 'ticker', + set: function set(ticker) // eslint-disable-line require-jsdoc + { + if (this._ticker) { + this._ticker.remove(this.render, this); + } + this._ticker = ticker; + if (ticker) { + ticker.add(this.render, this); + } + }, + get: function get() // eslint-disable-line require-jsdoc + { + return this._ticker; + } + }, { + key: 'view', + get: function get() { + return this.renderer.view; + } + + /** + * Reference to the renderer's screen rectangle. Its safe to use as filterArea or hitArea for whole screen + * @member {PIXI.Rectangle} + * @readonly + */ + + }, { + key: 'screen', + get: function get() { + return this.renderer.screen; + } + }]); + + return Application; +}(); + +exports.default = Application; + +},{"./autoDetectRenderer":43,"./display/Container":46,"./ticker":116}],42:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function checkPrecision(src, def) { + if (src instanceof Array) { + if (src[0].substring(0, 9) !== 'precision') { + var copy = src.slice(0); + + copy.unshift('precision ' + def + ' float;'); + + return copy; + } + } else if (src.substring(0, 9) !== 'precision') { + return 'precision ' + def + ' float;\n' + src; + } + + return src; +} + +/** + * Wrapper class, webGL Shader for Pixi. + * Adds precision string if vertexSrc or fragmentSrc have no mention of it. + * + * @class + * @extends GLShader + * @memberof PIXI + */ + +var Shader = function (_GLShader) { + _inherits(Shader, _GLShader); + + /** + * + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + * @param {string|string[]} vertexSrc - The vertex shader source as an array of strings. + * @param {string|string[]} fragmentSrc - The fragment shader source as an array of strings. + */ + function Shader(gl, vertexSrc, fragmentSrc) { + _classCallCheck(this, Shader); + + return _possibleConstructorReturn(this, _GLShader.call(this, gl, checkPrecision(vertexSrc, _settings2.default.PRECISION_VERTEX), checkPrecision(fragmentSrc, _settings2.default.PRECISION_FRAGMENT))); + } + + return Shader; +}(_pixiGlCore.GLShader); + +exports.default = Shader; + +},{"./settings":99,"pixi-gl-core":12}],43:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = autoDetectRenderer; + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by + * the browser then this function will return a canvas renderer + * + * @memberof PIXI + * @function autoDetectRenderer + * @param {number} [width=800] - the width of the renderers view + * @param {number} [height=600] - the height of the renderers view + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [noWebGL=false] - prevents selection of WebGL renderer, even if such is present + * @return {PIXI.WebGLRenderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ +function autoDetectRenderer() { + var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 800; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 600; + var options = arguments[2]; + var noWebGL = arguments[3]; + + if (!noWebGL && utils.isWebGLSupported()) { + return new _WebGLRenderer2.default(width, height, options); + } + + return new _CanvasRenderer2.default(width, height, options); +} + +},{"./renderers/canvas/CanvasRenderer":75,"./renderers/webgl/WebGLRenderer":82,"./utils":120}],44:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * String of the current PIXI version. + * + * @static + * @constant + * @memberof PIXI + * @name VERSION + * @type {string} + */ +var VERSION = exports.VERSION = '4.4.3'; + +/** + * Two Pi. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var PI_2 = exports.PI_2 = Math.PI * 2; + +/** + * Conversion factor for converting radians to degrees. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var RAD_TO_DEG = exports.RAD_TO_DEG = 180 / Math.PI; + +/** + * Conversion factor for converting degrees to radians. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var DEG_TO_RAD = exports.DEG_TO_RAD = Math.PI / 180; + +/** + * Constant to identify the Renderer Type. + * + * @static + * @constant + * @memberof PIXI + * @name RENDERER_TYPE + * @type {object} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ +var RENDERER_TYPE = exports.RENDERER_TYPE = { + UNKNOWN: 0, + WEBGL: 1, + CANVAS: 2 +}; + +/** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * + * @static + * @constant + * @memberof PIXI + * @name BLEND_MODES + * @type {object} + * @property {number} NORMAL + * @property {number} ADD + * @property {number} MULTIPLY + * @property {number} SCREEN + * @property {number} OVERLAY + * @property {number} DARKEN + * @property {number} LIGHTEN + * @property {number} COLOR_DODGE + * @property {number} COLOR_BURN + * @property {number} HARD_LIGHT + * @property {number} SOFT_LIGHT + * @property {number} DIFFERENCE + * @property {number} EXCLUSION + * @property {number} HUE + * @property {number} SATURATION + * @property {number} COLOR + * @property {number} LUMINOSITY + */ +var BLEND_MODES = exports.BLEND_MODES = { + NORMAL: 0, + ADD: 1, + MULTIPLY: 2, + SCREEN: 3, + OVERLAY: 4, + DARKEN: 5, + LIGHTEN: 6, + COLOR_DODGE: 7, + COLOR_BURN: 8, + HARD_LIGHT: 9, + SOFT_LIGHT: 10, + DIFFERENCE: 11, + EXCLUSION: 12, + HUE: 13, + SATURATION: 14, + COLOR: 15, + LUMINOSITY: 16 +}; + +/** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * + * @static + * @constant + * @memberof PIXI + * @name DRAW_MODES + * @type {object} + * @property {number} POINTS + * @property {number} LINES + * @property {number} LINE_LOOP + * @property {number} LINE_STRIP + * @property {number} TRIANGLES + * @property {number} TRIANGLE_STRIP + * @property {number} TRIANGLE_FAN + */ +var DRAW_MODES = exports.DRAW_MODES = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6 +}; + +/** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @static + * @constant + * @memberof PIXI + * @name SCALE_MODES + * @type {object} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ +var SCALE_MODES = exports.SCALE_MODES = { + LINEAR: 0, + NEAREST: 1 +}; + +/** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wraping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as webGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * + * @static + * @constant + * @name WRAP_MODES + * @memberof PIXI + * @type {object} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ +var WRAP_MODES = exports.WRAP_MODES = { + CLAMP: 0, + REPEAT: 1, + MIRRORED_REPEAT: 2 +}; + +/** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for pixi textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * + * @static + * @constant + * @name GC_MODES + * @memberof PIXI + * @type {object} + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ +var GC_MODES = exports.GC_MODES = { + AUTO: 0, + MANUAL: 1 +}; + +/** + * Regexp for image type by extension. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `image.png` + */ +var URL_FILE_EXTENSION = exports.URL_FILE_EXTENSION = /\.(\w{3,4})(?:$|\?|#)/i; + +/** + * Regexp for data URI. + * Based on: {@link https://github.com/ragingwind/data-uri-regex} + * + * @static + * @constant + * @name DATA_URI + * @memberof PIXI + * @type {RegExp|string} + * @example data:image/png;base64 + */ +var DATA_URI = exports.DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;(charset=[\w-]+|base64))?,(.*)/i; + +/** + * Regexp for SVG size. + * + * @static + * @constant + * @name SVG_SIZE + * @memberof PIXI + * @type {RegExp|string} + * @example <svg width="100" height="100"></svg> + */ +var SVG_SIZE = exports.SVG_SIZE = /]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len + +/** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * + * @static + * @constant + * @name SHAPES + * @memberof PIXI + * @type {object} + * @property {number} POLY Polygon + * @property {number} RECT Rectangle + * @property {number} CIRC Circle + * @property {number} ELIP Ellipse + * @property {number} RREC Rounded Rectangle + */ +var SHAPES = exports.SHAPES = { + POLY: 0, + RECT: 1, + CIRC: 2, + ELIP: 3, + RREC: 4 +}; + +/** + * Constants that specify float precision in shaders. + * + * @static + * @constant + * @name PRECISION + * @memberof PIXI + * @type {object} + * @property {string} LOW='lowp' + * @property {string} MEDIUM='mediump' + * @property {string} HIGH='highp' + */ +var PRECISION = exports.PRECISION = { + LOW: 'lowp', + MEDIUM: 'mediump', + HIGH: 'highp' +}; + +/** + * Constants that specify the transform type. + * + * @static + * @constant + * @name TRANSFORM_MODE + * @memberof PIXI + * @type {object} + * @property {number} STATIC + * @property {number} DYNAMIC + */ +var TRANSFORM_MODE = exports.TRANSFORM_MODE = { + STATIC: 0, + DYNAMIC: 1 +}; + +/** + * Constants that define the type of gradient on text. + * + * @static + * @constant + * @name TEXT_GRADIENT + * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL Vertical gradient + * @property {number} LINEAR_HORIZONTAL Linear gradient + */ +var TEXT_GRADIENT = exports.TEXT_GRADIENT = { + LINEAR_VERTICAL: 0, + LINEAR_HORIZONTAL: 1 +}; + +},{}],45:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * 'Builder' pattern for bounds rectangles + * Axis-Aligned Bounding Box + * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems + * + * @class + * @memberof PIXI + */ +var Bounds = function () { + /** + * + */ + function Bounds() { + _classCallCheck(this, Bounds); + + /** + * @member {number} + * @default 0 + */ + this.minX = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.minY = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxX = -Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxY = -Infinity; + + this.rect = null; + } + + /** + * Checks if bounds are empty. + * + * @return {boolean} True if empty. + */ + + + Bounds.prototype.isEmpty = function isEmpty() { + return this.minX > this.maxX || this.minY > this.maxY; + }; + + /** + * Clears the bounds and resets. + * + */ + + + Bounds.prototype.clear = function clear() { + this.updateID++; + + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * + * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty + * @returns {PIXI.Rectangle} A rectangle of the bounds + */ + + + Bounds.prototype.getRectangle = function getRectangle(rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return _math.Rectangle.EMPTY; + } + + rect = rect || new _math.Rectangle(0, 0, 1, 1); + + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + + return rect; + }; + + /** + * This function should be inlined when its possible. + * + * @param {PIXI.Point} point - The point to add. + */ + + + Bounds.prototype.addPoint = function addPoint(point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + }; + + /** + * Adds a quad, not transformed + * + * @param {Float32Array} vertices - The verts to add. + */ + + + Bounds.prototype.addQuad = function addQuad(vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = vertices[0]; + var y = vertices[1]; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds sprite frame, transformed. + * + * @param {PIXI.TransformBase} transform - TODO + * @param {number} x0 - TODO + * @param {number} y0 - TODO + * @param {number} x1 - TODO + * @param {number} y1 - TODO + */ + + + Bounds.prototype.addFrame = function addFrame(transform, x0, y0, x1, y1) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = a * x0 + c * y0 + tx; + var y = b * x0 + d * y0 + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y0 + tx; + y = b * x1 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x0 + c * y1 + tx; + y = b * x0 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y1 + tx; + y = b * x1 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Add an array of vertices + * + * @param {PIXI.TransformBase} transform - TODO + * @param {Float32Array} vertices - TODO + * @param {number} beginOffset - TODO + * @param {number} endOffset - TODO + */ + + + Bounds.prototype.addVertices = function addVertices(transform, vertices, beginOffset, endOffset) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = a * rawX + c * rawY + tx; + var y = d * rawY + b * rawX + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds other Bounds + * + * @param {PIXI.Bounds} bounds - TODO + */ + + + Bounds.prototype.addBounds = function addBounds(bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + }; + + /** + * Adds other Bounds, masked with Bounds + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Bounds} mask - TODO + */ + + + Bounds.prototype.addBoundsMask = function addBoundsMask(bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + /** + * Adds other Bounds, masked with Rectangle + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Rectangle} area - TODO + */ + + + Bounds.prototype.addBoundsArea = function addBoundsArea(bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : area.x + area.width; + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : area.y + area.height; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + return Bounds; +}(); + +exports.default = Bounds; + +},{"../math":68}],46:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _DisplayObject2 = require('./DisplayObject'); + +var _DisplayObject3 = _interopRequireDefault(_DisplayObject2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A Container represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + *```js + * let container = new PIXI.Container(); + * container.addChild(sprite); + * ``` + * + * @class + * @extends PIXI.DisplayObject + * @memberof PIXI + */ +var Container = function (_DisplayObject) { + _inherits(Container, _DisplayObject); + + /** + * + */ + function Container() { + _classCallCheck(this, Container); + + /** + * The array of children of this container. + * + * @member {PIXI.DisplayObject[]} + * @readonly + */ + var _this = _possibleConstructorReturn(this, _DisplayObject.call(this)); + + _this.children = []; + return _this; + } + + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified + * + * @private + */ + + + Container.prototype.onChildrenChange = function onChildrenChange() {} + /* empty */ + + + /** + * Adds one or more children to the container. + * + * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container + * @return {PIXI.DisplayObject} The first child that was added. + */ + ; + + Container.prototype.addChild = function addChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.addChild(arguments[i]); + } + } else { + // if the child has a parent then lets remove it as Pixi objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.push(child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + child.emit('added', this); + } + + return child; + }; + + /** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @return {PIXI.DisplayObject} The child that was added. + */ + + + Container.prototype.addChildAt = function addChildAt(child, index) { + if (index < 0 || index > this.children.length) { + throw new Error(child + 'addChildAt: The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.splice(index, 0, child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + + return child; + }; + + /** + * Swaps the position of 2 Display Objects within this container. + * + * @param {PIXI.DisplayObject} child - First display object to swap + * @param {PIXI.DisplayObject} child2 - Second display object to swap + */ + + + Container.prototype.swapChildren = function swapChildren(child, child2) { + if (child === child2) { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; + + /** + * Returns the index position of a child DisplayObject instance + * + * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify + * @return {number} The index position of the child display object to identify + */ + + + Container.prototype.getChildIndex = function getChildIndex(child) { + var index = this.children.indexOf(child); + + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + }; + + /** + * Changes the position of an existing child in the display object container + * + * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number + * @param {number} index - The resulting index number for the child display object + */ + + + Container.prototype.setChildIndex = function setChildIndex(child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + (0, _utils.removeItems)(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + + this.onChildrenChange(index); + }; + + /** + * Returns the child at the specified index + * + * @param {number} index - The index to get the child at + * @return {PIXI.DisplayObject} The child at the given index, if any. + */ + + + Container.prototype.getChildAt = function getChildAt(index) { + if (index < 0 || index >= this.children.length) { + throw new Error('getChildAt: Index (' + index + ') does not exist.'); + } + + return this.children[index]; + }; + + /** + * Removes one or more children from the container. + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove + * @return {PIXI.DisplayObject} The first child that was removed. + */ + + + Container.prototype.removeChild = function removeChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.removeChild(arguments[i]); + } + } else { + var index = this.children.indexOf(child); + + if (index === -1) return null; + + child.parent = null; + // ensure child transform will be recalculated + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + } + + return child; + }; + + /** + * Removes a child from the specified index position. + * + * @param {number} index - The index to get the child from + * @return {PIXI.DisplayObject} The child that was removed. + */ + + + Container.prototype.removeChildAt = function removeChildAt(index) { + var child = this.getChildAt(index); + + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + + return child; + }; + + /** + * Removes all children from this container that are within the begin and end indexes. + * + * @param {number} [beginIndex=0] - The beginning position. + * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. + * @returns {DisplayObject[]} List of removed children + */ + + + Container.prototype.removeChildren = function removeChildren() { + var beginIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var endIndex = arguments[1]; + + var begin = beginIndex; + var end = typeof endIndex === 'number' ? endIndex : this.children.length; + var range = end - begin; + var removed = void 0; + + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } + + this._boundsID++; + + this.onChildrenChange(beginIndex); + + for (var _i = 0; _i < removed.length; ++_i) { + removed[_i].emit('removed', this); + } + + return removed; + } else if (range === 0 && this.children.length === 0) { + return []; + } + + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + }; + + /** + * Updates the transform on all children of this container for rendering + */ + + + Container.prototype.updateTransform = function updateTransform() { + this._boundsID++; + + this.transform.updateTransform(this.parent.transform); + + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + + if (child.visible) { + child.updateTransform(); + } + } + }; + + /** + * Recalculates the bounds of the container. + * + */ + + + Container.prototype.calculateBounds = function calculateBounds() { + this._bounds.clear(); + + this._calculateBounds(); + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (!child.visible || !child.renderable) { + continue; + } + + child.calculateBounds(); + + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + child._mask.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, child._mask._bounds); + } else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } else { + this._bounds.addBounds(child._bounds); + } + } + + this._lastBoundsID = this._boundsID; + }; + + /** + * Recalculates the bounds of the object. Override this to + * calculate the bounds of the specific object (not including children). + * + */ + + + Container.prototype._calculateBounds = function _calculateBounds() {} + // FILL IN// + + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderWebGL = function renderWebGL(renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + // do a quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) { + this.renderAdvancedWebGL(renderer); + } else { + this._renderWebGL(renderer); + + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderWebGL(renderer); + } + } + }; + + /** + * Render the object using the WebGL renderer and advanced features. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { + renderer.flush(); + + var filters = this._filters; + var mask = this._mask; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + + this._enabledFilters.length = 0; + + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + + if (this._enabledFilters.length) { + renderer.filterManager.pushFilter(this, this._enabledFilters); + } + } + + if (mask) { + renderer.maskManager.pushMask(this, this._mask); + } + + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); + + // now loop through the children and make sure they get rendered + for (var _i2 = 0, j = this.children.length; _i2 < j; _i2++) { + this.children[_i2].renderWebGL(renderer); + } + + renderer.flush(); + + if (mask) { + renderer.maskManager.popMask(this, this._mask); + } + + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filterManager.popFilter(); + } + }; + + /** + * To be overridden by the subclasses. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype._renderWebGL = function _renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * To be overridden by the subclass + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype._renderCanvas = function _renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderCanvas = function renderCanvas(renderer) { + // if not visible or the alpha is 0 then no need to render this + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + if (this._mask) { + renderer.maskManager.pushMask(this._mask); + } + + this._renderCanvas(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderCanvas(renderer); + } + + if (this._mask) { + renderer.maskManager.popMask(renderer); + } + }; + + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Container.prototype.destroy = function destroy(options) { + _DisplayObject.prototype.destroy.call(this); + + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + + var oldChildren = this.removeChildren(0, this.children.length); + + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + }; + + /** + * The width of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Container, [{ + key: 'width', + get: function get() { + return this.scale.x * this.getLocalBounds().width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var width = this.getLocalBounds().width; + + if (width !== 0) { + this.scale.x = value / width; + } else { + this.scale.x = 1; + } + + this._width = value; + } + + /** + * The height of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.scale.y * this.getLocalBounds().height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var height = this.getLocalBounds().height; + + if (height !== 0) { + this.scale.y = value / height; + } else { + this.scale.y = 1; + } + + this._height = value; + } + }]); + + return Container; +}(_DisplayObject3.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = Container; +Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + +},{"../utils":120,"./DisplayObject":47}],47:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TransformStatic = require('./TransformStatic'); + +var _TransformStatic2 = _interopRequireDefault(_TransformStatic); + +var _Transform = require('./Transform'); + +var _Transform2 = _interopRequireDefault(_Transform); + +var _Bounds = require('./Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _math = require('../math'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// _tempDisplayObjectParent = new DisplayObject(); + +/** + * The base class for all objects that are rendered on the screen. + * This is an abstract class and should not be used on its own rather it should be extended. + * + * @class + * @extends EventEmitter + * @mixes PIXI.interaction.interactiveTarget + * @memberof PIXI + */ +var DisplayObject = function (_EventEmitter) { + _inherits(DisplayObject, _EventEmitter); + + /** + * + */ + function DisplayObject() { + _classCallCheck(this, DisplayObject); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + var TransformClass = _settings2.default.TRANSFORM_MODE === _const.TRANSFORM_MODE.STATIC ? _TransformStatic2.default : _Transform2.default; + + _this.tempDisplayObjectParent = null; + + // TODO: need to create Transform from factory + /** + * World transform and local transform of this object. + * This will become read-only later, please do not assign anything there unless you know what are you doing + * + * @member {PIXI.TransformBase} + */ + _this.transform = new TransformClass(); + + /** + * The opacity of the object. + * + * @member {number} + */ + _this.alpha = 1; + + /** + * The visibility of the object. If false the object will not be drawn, and + * the updateTransform function will not be called. + * + * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually + * + * @member {boolean} + */ + _this.visible = true; + + /** + * Can this object be rendered, if false the object will not be drawn but the updateTransform + * methods will still be called. + * + * Only affects recursive calls from parent. You can ask for bounds manually + * + * @member {boolean} + */ + _this.renderable = true; + + /** + * The display object container that contains this display object. + * + * @member {PIXI.Container} + * @readonly + */ + _this.parent = null; + + /** + * The multiplied alpha of the displayObject + * + * @member {number} + * @readonly + */ + _this.worldAlpha = 1; + + /** + * The area the filter is applied to. This is used as more of an optimisation + * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle + * + * Also works as an interaction mask + * + * @member {PIXI.Rectangle} + */ + _this.filterArea = null; + + _this._filters = null; + _this._enabledFilters = null; + + /** + * The bounds object, this is used to calculate and store the bounds of the displayObject + * + * @member {PIXI.Rectangle} + * @private + */ + _this._bounds = new _Bounds2.default(); + _this._boundsID = 0; + _this._lastBoundsID = -1; + _this._boundsRect = null; + _this._localBoundsRect = null; + + /** + * The original, cached mask of the object + * + * @member {PIXI.Graphics|PIXI.Sprite} + * @private + */ + _this._mask = null; + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + return _this; + } + + /** + * @private + * @member {PIXI.DisplayObject} + */ + + + /** + * Updates the object transform for rendering + * + * TODO - Optimization pass! + */ + DisplayObject.prototype.updateTransform = function updateTransform() { + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + this._bounds.updateID++; + }; + + /** + * recursively updates transform of all objects from the root to this one + * internal function for toLocal() + */ + + + DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform() { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + }; + + /** + * Retrieves the bounds of the displayObject as a rectangle object. + * + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @param {PIXI.Rectangle} rect - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getBounds = function getBounds(skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + + if (this._boundsID !== this._lastBoundsID) { + this.calculateBounds(); + } + + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new _math.Rectangle(); + } + + rect = this._boundsRect; + } + + return this._bounds.getRectangle(rect); + }; + + /** + * Retrieves the local bounds of the displayObject as a rectangle object + * + * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getLocalBounds = function getLocalBounds(rect) { + var transformRef = this.transform; + var parentRef = this.parent; + + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + var bounds = this.getBounds(false, rect); + + this.parent = parentRef; + this.transform = transformRef; + + return bounds; + }; + + /** + * Calculates the global position of the display object + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform. + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toGlobal = function toGlobal(position, point) { + var skipUpdate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; + + /** + * Calculates the local position of the display object relative to another point + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toLocal = function toLocal(position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + DisplayObject.prototype.renderCanvas = function renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Set the parent Container of this DisplayObject + * + * @param {PIXI.Container} container - The Container to add this DisplayObject to + * @return {PIXI.Container} The Container that this DisplayObject was added to + */ + ; + + DisplayObject.prototype.setParent = function setParent(container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); + } + + container.addChild(this); + + return container; + }; + + /** + * Convenience function to set the position, scale, skew and pivot at once. + * + * @param {number} [x=0] - The X position + * @param {number} [y=0] - The Y position + * @param {number} [scaleX=1] - The X scale value + * @param {number} [scaleY=1] - The Y scale value + * @param {number} [rotation=0] - The rotation + * @param {number} [skewX=0] - The X skew value + * @param {number} [skewY=0] - The Y skew value + * @param {number} [pivotX=0] - The X pivot value + * @param {number} [pivotY=0] - The Y pivot value + * @return {PIXI.DisplayObject} The DisplayObject instance + */ + + + DisplayObject.prototype.setTransform = function setTransform() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var scaleX = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var scaleY = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var rotation = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var skewX = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + var skewY = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + var pivotX = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; + var pivotY = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0; + + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + + return this; + }; + + /** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy`. + * + */ + + + DisplayObject.prototype.destroy = function destroy() { + this.removeAllListeners(); + if (this.parent) { + this.parent.removeChild(this); + } + this.transform = null; + + this.parent = null; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this.filterArea = null; + + this.interactive = false; + this.interactiveChildren = false; + + this._destroyed = true; + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + * + * @member {number} + */ + + + _createClass(DisplayObject, [{ + key: '_tempDisplayObjectParent', + get: function get() { + if (this.tempDisplayObjectParent === null) { + this.tempDisplayObjectParent = new DisplayObject(); + } + + return this.tempDisplayObjectParent; + } + }, { + key: 'x', + get: function get() { + return this.position.x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.x = value; + } + + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + * + * @member {number} + */ + + }, { + key: 'y', + get: function get() { + return this.position.y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.y = value; + } + + /** + * Current transform of the object based on world (parent) factors + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'worldTransform', + get: function get() { + return this.transform.worldTransform; + } + + /** + * Current transform of the object based on local factors: position, scale, other stuff + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'localTransform', + get: function get() { + return this.transform.localTransform; + } + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'position', + get: function get() { + return this.transform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.copy(value); + } + + /** + * The scale factor of the object. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'scale', + get: function get() { + return this.transform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.scale.copy(value); + } + + /** + * The pivot point of the displayObject that it rotates around + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'pivot', + get: function get() { + return this.transform.pivot; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.pivot.copy(value); + } + + /** + * The skew factor for the object in radians. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'skew', + get: function get() { + return this.transform.skew; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.skew.copy(value); + } + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + }, { + key: 'rotation', + get: function get() { + return this.transform.rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.rotation = value; + } + + /** + * Indicates if the object is globally visible. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'worldVisible', + get: function get() { + var item = this; + + do { + if (!item.visible) { + return false; + } + + item = item.parent; + } while (item); + + return true; + } + + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PIXI a regular mask must be a + * PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it + * utilises shape clipping. To remove a mask, set this property to null. + * + * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + * + * @member {PIXI.Graphics|PIXI.Sprite} + */ + + }, { + key: 'mask', + get: function get() { + return this._mask; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._mask) { + this._mask.renderable = true; + } + + this._mask = value; + + if (this._mask) { + this._mask.renderable = false; + } + } + + /** + * Sets the filters for the displayObject. + * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * To remove filters simply set this property to 'null' + * + * @member {PIXI.Filter[]} + */ + + }, { + key: 'filters', + get: function get() { + return this._filters && this._filters.slice(); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._filters = value && value.slice(); + } + }]); + + return DisplayObject; +}(_eventemitter2.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = DisplayObject; +DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + +},{"../const":44,"../math":68,"../settings":99,"./Bounds":45,"./Transform":48,"./TransformStatic":50,"eventemitter3":3}],48:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Generic class to deal with traditional 2D matrix transforms + * local transformation is calculated from position,scale,skew and rotation + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var Transform = function (_TransformBase) { + _inherits(Transform, _TransformBase); + + /** + * + */ + function Transform() { + _classCallCheck(this, Transform); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.Point} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.Point(0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.Point} + */ + _this.scale = new _math.Point(1, 1); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.Point} + */ + _this.pivot = new _math.Point(0, 0); + + /** + * The rotation value of the object, in radians + * + * @member {Number} + * @private + */ + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + return _this; + } + + /** + * Updates the skew values when the skew or rotation changes. + * + * @private + */ + + + Transform.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + }; + + /** + * Updates only local matrix + */ + + + Transform.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + Transform.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + Transform.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(Transform, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return Transform; +}(_TransformBase3.default); + +exports.default = Transform; + +},{"../math":68,"./TransformBase":49}],49:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Generic class to deal with traditional 2D matrix transforms + * + * @class + * @memberof PIXI + */ +var TransformBase = function () { + /** + * + */ + function TransformBase() { + _classCallCheck(this, TransformBase); + + /** + * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds() + * + * @member {PIXI.Matrix} + */ + this.worldTransform = new _math.Matrix(); + + /** + * The local matrix transform + * + * @member {PIXI.Matrix} + */ + this.localTransform = new _math.Matrix(); + + this._worldID = 0; + this._parentID = 0; + } + + /** + * TransformBase does not have decomposition, so this function wont do anything + */ + + + TransformBase.prototype.updateLocalTransform = function updateLocalTransform() {} + // empty + + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.TransformBase} parentTransform - The transform of the parent of this object + */ + ; + + TransformBase.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + return TransformBase; +}(); + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ + + +exports.default = TransformBase; +TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; + +TransformBase.IDENTITY = new TransformBase(); + +},{"../math":68}],50:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Transform that takes care about its versions + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var TransformStatic = function (_TransformBase) { + _inherits(TransformStatic, _TransformBase); + + /** + * + */ + function TransformStatic() { + _classCallCheck(this, TransformStatic); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.ObservablePoint} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.ObservablePoint} + */ + _this.scale = new _math.ObservablePoint(_this.onChange, _this, 1, 1); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.ObservablePoint} + */ + _this.pivot = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + + _this._localID = 0; + _this._currentLocalID = 0; + return _this; + } + + /** + * Called when a value changes. + * + * @private + */ + + + TransformStatic.prototype.onChange = function onChange() { + this._localID++; + }; + + /** + * Called when skew or rotation changes + * + * @private + */ + + + TransformStatic.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + + this._localID++; + }; + + /** + * Updates only local matrix + */ + + + TransformStatic.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + TransformStatic.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._parentID = parentTransform._worldID; + + // update the id of the transform.. + this._worldID++; + } + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + TransformStatic.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + this._localID++; + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(TransformStatic, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return TransformStatic; +}(_TransformBase3.default); + +exports.default = TransformStatic; + +},{"../math":68,"./TransformBase":49}],51:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _GraphicsData = require('./GraphicsData'); + +var _GraphicsData2 = _interopRequireDefault(_GraphicsData); + +var _Sprite = require('../sprites/Sprite'); + +var _Sprite2 = _interopRequireDefault(_Sprite); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Bounds = require('../display/Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _bezierCurveTo2 = require('./utils/bezierCurveTo'); + +var _bezierCurveTo3 = _interopRequireDefault(_bezierCurveTo2); + +var _CanvasRenderer = require('../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var canvasRenderer = void 0; +var tempMatrix = new _math.Matrix(); +var tempPoint = new _math.Point(); +var tempColor1 = new Float32Array(4); +var tempColor2 = new Float32Array(4); + +/** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Graphics = function (_Container) { + _inherits(Graphics, _Container); + + /** + * + * @param {boolean} [nativeLines=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + */ + function Graphics() { + var nativeLines = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + _classCallCheck(this, Graphics); + + /** + * The alpha value used when filling the Graphics object. + * + * @member {number} + * @default 1 + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @member {number} + * @default 0 + */ + _this.lineWidth = 0; + + /** + * If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * + * @member {boolean} + */ + _this.nativeLines = nativeLines; + + /** + * The color of any lines drawn. + * + * @member {string} + * @default 0 + */ + _this.lineColor = 0; + + /** + * Graphics data + * + * @member {PIXI.GraphicsData[]} + * @private + */ + _this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to + * reset the tint. + * + * @member {number} + * @default 0xFFFFFF + */ + _this.tint = 0xFFFFFF; + + /** + * The previous tint applied to the graphic shape. Used to compare to the current tint and + * check if theres change. + * + * @member {number} + * @private + * @default 0xFFFFFF + */ + _this._prevTint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * Current path + * + * @member {PIXI.GraphicsData} + * @private + */ + _this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @member {object} + * @private + */ + // TODO - _webgl should use a prototype object, not a random undocumented object... + _this._webGL = {}; + + /** + * Whether this shape is being used as a mask. + * + * @member {boolean} + */ + _this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @member {number} + */ + _this.boundsPadding = 0; + + /** + * A cache of the local bounds to prevent recalculation. + * + * @member {PIXI.Rectangle} + * @private + */ + _this._localBounds = new _Bounds2.default(); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics + * object will be recalculated. + * + * @member {boolean} + * @private + */ + _this.dirty = 0; + + /** + * Used to detect if we need to do a fast rect check using the id compare method + * @type {Number} + */ + _this.fastRectDirty = -1; + + /** + * Used to detect if we clear the graphics webGL data + * @type {Number} + */ + _this.clearDirty = 0; + + /** + * Used to detect if we we need to recalculate local bounds + * @type {Number} + */ + _this.boundsDirty = -1; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @member {boolean} + * @private + */ + _this.cachedSpriteDirty = false; + + _this._spriteRect = null; + _this._fastRect = false; + + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ + return _this; + } + + /** + * Creates a new Graphics object with the same values as this one. + * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) + * + * @return {PIXI.Graphics} A clone of the graphics object + */ + + + Graphics.prototype.clone = function clone() { + var clone = new Graphics(); + + clone.renderable = this.renderable; + clone.fillAlpha = this.fillAlpha; + clone.lineWidth = this.lineWidth; + clone.lineColor = this.lineColor; + clone.tint = this.tint; + clone.blendMode = this.blendMode; + clone.isMask = this.isMask; + clone.boundsPadding = this.boundsPadding; + clone.dirty = 0; + clone.cachedSpriteDirty = this.cachedSpriteDirty; + + // copy graphics data + for (var i = 0; i < this.graphicsData.length; ++i) { + clone.graphicsData.push(this.graphicsData[i].clone()); + } + + clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; + + clone.updateLocalBounds(); + + return clone; + }; + + /** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() + * method or the drawCircle() method. + * + * @param {number} [lineWidth=0] - width of the line to draw, will update the objects stored style + * @param {number} [color=0] - color of the line to draw, will update the objects stored style + * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineStyle = function lineStyle() { + var lineWidth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var alpha = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + + this.lineWidth = lineWidth; + this.lineColor = color; + this.lineAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length) { + // halfway through a line? start a new one! + var shape = new _math.Polygon(this.currentPath.shape.points.slice(-2)); + + shape.closed = false; + + this.drawShape(shape); + } else { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + }; + + /** + * Moves the current drawing position to x, y. + * + * @param {number} x - the X coordinate to move to + * @param {number} y - the Y coordinate to move to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.moveTo = function moveTo(x, y) { + var shape = new _math.Polygon([x, y]); + + shape.closed = false; + this.drawShape(shape); + + return this; + }; + + /** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @param {number} x - the X coordinate to draw to + * @param {number} y - the Y coordinate to draw to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineTo = function lineTo(x, y) { + this.currentPath.shape.points.push(x, y); + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.quadraticCurveTo = function quadraticCurveTo(cpX, cpY, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var n = 20; + var points = this.currentPath.shape.points; + var xa = 0; + var ya = 0; + + if (points.length === 0) { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + for (var i = 1; i <= n; ++i) { + var j = i / n; + + xa = fromX + (cpX - fromX) * j; + ya = fromY + (cpY - fromY) * j; + + points.push(xa + (cpX + (toX - cpX) * j - xa) * j, ya + (cpY + (toY - cpY) * j - ya) * j); + } + + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a bezier curve and then draws it. + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.bezierCurveTo = function bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + points.length -= 2; + + (0, _bezierCurveTo3.default)(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, points); + + this.dirty++; + + return this; + }; + + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @param {number} x1 - The x-coordinate of the beginning of the arc + * @param {number} y1 - The y-coordinate of the beginning of the arc + * @param {number} x2 - The x-coordinate of the end of the arc + * @param {number} y2 - The y-coordinate of the end of the arc + * @param {number} radius - The radius of the arc + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arcTo = function arcTo(x1, y1, x2, y2, radius) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points.push(x1, y1); + } + } else { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + } else { + var dd = a1 * a1 + b1 * b1; + var cc = a2 * a2 + b2 * b2; + var tt = a1 * a2 + b1 * b2; + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = k1 * b2 + k2 * b1; + var cy = k1 * a2 + k2 * a1; + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty++; + + return this; + }; + + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @param {number} cx - The x-coordinate of the center of the circle + * @param {number} cy - The y-coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param {number} endAngle - The ending angle, in radians + * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arc = function arc(cx, cy, radius, startAngle, endAngle) { + var anticlockwise = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; + + if (startAngle === endAngle) { + return this; + } + + if (!anticlockwise && endAngle <= startAngle) { + endAngle += Math.PI * 2; + } else if (anticlockwise && startAngle <= endAngle) { + startAngle += Math.PI * 2; + } + + var sweep = endAngle - startAngle; + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * 40; + + if (sweep === 0) { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. + var points = this.currentPath ? this.currentPath.shape.points : null; + + if (points) { + if (points[points.length - 2] !== startX || points[points.length - 1] !== startY) { + points.push(startX, startY); + } + } else { + this.moveTo(startX, startY); + points = this.currentPath.shape.points; + } + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = segMinus % 1 / segMinus; + + for (var i = 0; i <= segMinus; ++i) { + var real = i + remainder * i; + + var angle = theta + startAngle + theta2 * real; + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push((cTheta * c + sTheta * s) * radius + cx, (cTheta * -s + sTheta * c) * radius + cy); + } + + this.dirty++; + + return this; + }; + + /** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @param {number} [color=0] - the color of the fill + * @param {number} [alpha=1] - the alpha of the fill + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.beginFill = function beginFill() { + var color = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var alpha = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.filling = true; + this.fillColor = color; + this.fillAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length <= 2) { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + }; + + /** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.endFill = function endFill() { + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRect = function drawRect(x, y, width, height) { + this.drawShape(new _math.Rectangle(x, y, width, height)); + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @param {number} radius - Radius of the rectangle corners + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRoundedRect = function drawRoundedRect(x, y, width, height, radius) { + this.drawShape(new _math.RoundedRectangle(x, y, width, height, radius)); + + return this; + }; + + /** + * Draws a circle. + * + * @param {number} x - The X coordinate of the center of the circle + * @param {number} y - The Y coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawCircle = function drawCircle(x, y, radius) { + this.drawShape(new _math.Circle(x, y, radius)); + + return this; + }; + + /** + * Draws an ellipse. + * + * @param {number} x - The X coordinate of the center of the ellipse + * @param {number} y - The Y coordinate of the center of the ellipse + * @param {number} width - The half width of the ellipse + * @param {number} height - The half height of the ellipse + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawEllipse = function drawEllipse(x, y, width, height) { + this.drawShape(new _math.Ellipse(x, y, width, height)); + + return this; + }; + + /** + * Draws a polygon using the given path. + * + * @param {number[]|PIXI.Point[]} path - The path data used to construct the polygon. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawPolygon = function drawPolygon(path) { + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + var closed = true; + + if (points instanceof _math.Polygon) { + closed = points.closed; + points = points.points; + } + + if (!Array.isArray(points)) { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) { + points[i] = arguments[i]; // eslint-disable-line prefer-rest-params + } + } + + var shape = new _math.Polygon(points); + + shape.closed = closed; + + this.drawShape(shape); + + return this; + }; + + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.clear = function clear() { + if (this.lineWidth || this.filling || this.graphicsData.length > 0) { + this.lineWidth = 0; + this.filling = false; + + this.boundsDirty = -1; + this.dirty++; + this.clearDirty++; + this.graphicsData.length = 0; + } + + this.currentPath = null; + this._spriteRect = null; + + return this; + }; + + /** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. + * + * @returns {boolean} True if only 1 rect. + */ + + + Graphics.prototype.isFastRect = function isFastRect() { + return this.graphicsData.length === 1 && this.graphicsData[0].shape.type === _const.SHAPES.RECT && !this.graphicsData[0].lineWidth; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderWebGL = function _renderWebGL(renderer) { + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.dirty !== this.fastRectDirty) { + this.fastRectDirty = this.dirty; + this._fastRect = this.isFastRect(); + } + + // TODO this check can be moved to dirty? + if (this._fastRect) { + this._renderSpriteRect(renderer); + } else { + renderer.setObjectRenderer(renderer.plugins.graphics); + renderer.plugins.graphics.render(this); + } + }; + + /** + * Renders a sprite rectangle. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderSpriteRect = function _renderSpriteRect(renderer) { + var rect = this.graphicsData[0].shape; + + if (!this._spriteRect) { + this._spriteRect = new _Sprite2.default(new _Texture2.default(_Texture2.default.WHITE)); + } + + var sprite = this._spriteRect; + + if (this.tint === 0xffffff) { + sprite.tint = this.graphicsData[0].fillColor; + } else { + var t1 = tempColor1; + var t2 = tempColor2; + + (0, _utils.hex2rgb)(this.graphicsData[0].fillColor, t1); + (0, _utils.hex2rgb)(this.tint, t2); + + t1[0] *= t2[0]; + t1[1] *= t2[1]; + t1[2] *= t2[2]; + + sprite.tint = (0, _utils.rgb2hex)(t1); + } + sprite.alpha = this.graphicsData[0].fillAlpha; + sprite.worldAlpha = this.worldAlpha * sprite.alpha; + sprite.blendMode = this.blendMode; + + sprite.texture._frame.width = rect.width; + sprite.texture._frame.height = rect.height; + + sprite.transform.worldTransform = this.transform.worldTransform; + + sprite.anchor.set(-rect.x / rect.width, -rect.y / rect.height); + sprite._onAnchorUpdate(); + + sprite._renderWebGL(renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.isMask === true) { + return; + } + + renderer.plugins.graphics.render(this); + }; + + /** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @private + */ + + + Graphics.prototype._calculateBounds = function _calculateBounds() { + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.updateLocalBounds(); + + this.cachedSpriteDirty = true; + } + + var lb = this._localBounds; + + this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); + }; + + /** + * Tests if a point is inside this graphics object + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Graphics.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + + if (!data.fill) { + continue; + } + + // only deal with fills.. + if (data.shape) { + if (data.shape.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + } + + return false; + }; + + /** + * Update the bounds of the object + * + */ + + + Graphics.prototype.updateLocalBounds = function updateLocalBounds() { + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) { + var shape = 0; + var x = 0; + var y = 0; + var w = 0; + var h = 0; + + for (var i = 0; i < this.graphicsData.length; i++) { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + + shape = data.shape; + + if (type === _const.SHAPES.RECT || type === _const.SHAPES.RREC) { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.CIRC) { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.ELIP) { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else { + // POLY + var points = shape.points; + var x2 = 0; + var y2 = 0; + var dx = 0; + var dy = 0; + var rw = 0; + var rh = 0; + var cx = 0; + var cy = 0; + + for (var j = 0; j + 2 < points.length; j += 2) { + x = points[j]; + y = points[j + 1]; + x2 = points[j + 2]; + y2 = points[j + 3]; + dx = Math.abs(x2 - x); + dy = Math.abs(y2 - y); + h = lineWidth; + w = Math.sqrt(dx * dx + dy * dy); + + if (w < 1e-9) { + continue; + } + + rw = (h / w * dy + dx) / 2; + rh = (h / w * dx + dy) / 2; + cx = (x2 + x) / 2; + cy = (y2 + y) / 2; + + minX = cx - rw < minX ? cx - rw : minX; + maxX = cx + rw > maxX ? cx + rw : maxX; + + minY = cy - rh < minY ? cy - rh : minY; + maxY = cy + rh > maxY ? cy + rh : maxY; + } + } + } + } else { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.minX = minX - padding; + this._localBounds.maxX = maxX + padding * 2; + + this._localBounds.minY = minY - padding; + this._localBounds.maxY = maxY + padding * 2; + }; + + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @return {PIXI.GraphicsData} The generated GraphicsData object. + */ + + + Graphics.prototype.drawShape = function drawShape(shape) { + if (this.currentPath) { + // check current path! + if (this.currentPath.shape.points.length <= 2) { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + var data = new _GraphicsData2.default(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, this.nativeLines, shape); + + this.graphicsData.push(data); + + if (data.type === _const.SHAPES.POLY) { + data.shape.closed = data.shape.closed || this.filling; + this.currentPath = data; + } + + this.dirty++; + + return data; + }; + + /** + * Generates a canvas texture. + * + * @param {number} scaleMode - The scale mode of the texture. + * @param {number} resolution - The resolution of the texture. + * @return {PIXI.Texture} The new texture. + */ + + + Graphics.prototype.generateCanvasTexture = function generateCanvasTexture(scaleMode) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + var bounds = this.getLocalBounds(); + + var canvasBuffer = _RenderTexture2.default.create(bounds.width, bounds.height, scaleMode, resolution); + + if (!canvasRenderer) { + canvasRenderer = new _CanvasRenderer2.default(); + } + + this.transform.updateLocalTransform(); + this.transform.localTransform.copy(tempMatrix); + + tempMatrix.invert(); + + tempMatrix.tx -= bounds.x; + tempMatrix.ty -= bounds.y; + + canvasRenderer.render(this, canvasBuffer, true, tempMatrix); + + var texture = _Texture2.default.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas, scaleMode); + + texture.baseTexture.resolution = resolution; + texture.baseTexture.update(); + + return texture; + }; + + /** + * Closes the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.closePath = function closePath() { + // ok so close path assumes next one is a hole! + var currentPath = this.currentPath; + + if (currentPath && currentPath.shape) { + currentPath.shape.close(); + } + + return this; + }; + + /** + * Adds a hole in the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.addHole = function addHole() { + // this is a hole! + var hole = this.graphicsData.pop(); + + this.currentPath = this.graphicsData[this.graphicsData.length - 1]; + + this.currentPath.addHole(hole.shape); + this.currentPath = null; + + return this; + }; + + /** + * Destroys the Graphics object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Graphics.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._webgl) { + for (var j = 0; j < this._webgl[id].data.length; ++j) { + this._webgl[id].data[j].destroy(); + } + } + + if (this._spriteRect) { + this._spriteRect.destroy(); + } + + this.graphicsData = null; + + this.currentPath = null; + this._webgl = null; + this._localBounds = null; + }; + + return Graphics; +}(_Container3.default); + +exports.default = Graphics; + + +Graphics._SPRITE_TEXTURE = null; + +},{"../const":44,"../display/Bounds":45,"../display/Container":46,"../math":68,"../renderers/canvas/CanvasRenderer":75,"../sprites/Sprite":100,"../textures/RenderTexture":110,"../textures/Texture":112,"../utils":120,"./GraphicsData":52,"./utils/bezierCurveTo":54}],52:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + */ +var GraphicsData = function () { + /** + * + * @param {number} lineWidth - the width of the line to draw + * @param {number} lineColor - the color of the line to draw + * @param {number} lineAlpha - the alpha of the line to draw + * @param {number} fillColor - the color of the fill + * @param {number} fillAlpha - the alpha of the fill + * @param {boolean} fill - whether or not the shape is filled with a colour + * @param {boolean} nativeLines - the method for drawing lines + * @param {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} shape - The shape object to draw. + */ + function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, nativeLines, shape) { + _classCallCheck(this, GraphicsData); + + /** + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + /** + * @member {boolean} if true the liens will be draw using LINES instead of TRIANGLE_STRIP + */ + this.nativeLines = nativeLines; + + /** + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /** + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /** + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /** + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /** + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /** + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /** + * @member {boolean} whether or not the shape is filled with a colour + */ + this.fill = fill; + + this.holes = []; + + /** + * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} The shape object to draw. + */ + this.shape = shape; + + /** + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + } + + /** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {PIXI.GraphicsData} Cloned GraphicsData object + */ + + + GraphicsData.prototype.clone = function clone() { + return new GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.fill, this.nativeLines, this.shape); + }; + + /** + * Adds a hole to the shape. + * + * @param {PIXI.Rectangle|PIXI.Circle} shape - The shape of the hole. + */ + + + GraphicsData.prototype.addHole = function addHole(shape) { + this.holes.push(shape); + }; + + /** + * Destroys the Graphics data. + */ + + + GraphicsData.prototype.destroy = function destroy() { + this.shape = null; + this.holes = null; + }; + + return GraphicsData; +}(); + +exports.default = GraphicsData; + +},{}],53:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they + * now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasGraphicsRenderer: + * https://github.com/libgdx/libgdx/blob/1.0.0/gdx/src/com/badlogic/gdx/graphics/glutils/ShapeRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching graphics objects. + * + * @class + * @private + * @memberof PIXI + */ +var CanvasGraphicsRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The current PIXI renderer. + */ + function CanvasGraphicsRenderer(renderer) { + _classCallCheck(this, CanvasGraphicsRenderer); + + this.renderer = renderer; + } + + /** + * Renders a Graphics object to a canvas. + * + * @param {PIXI.Graphics} graphics - the actual graphics object to render + */ + + + CanvasGraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var context = renderer.context; + var worldAlpha = graphics.worldAlpha; + var transform = graphics.transform.worldTransform; + var resolution = renderer.resolution; + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) { + this.dirty = true; + } + + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + if (graphics.dirty) { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + renderer.setBlendMode(graphics.blendMode); + + for (var i = 0; i < graphics.graphicsData.length; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === _const.SHAPES.POLY) { + context.beginPath(); + + this.renderPolygon(shape.points, shape.closed, context); + + for (var j = 0; j < data.holes.length; j++) { + this.renderPolygon(data.holes[j].points, true, context); + } + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RECT) { + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + context.beginPath(); + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + }; + + /** + * Updates the tint of a graphics object + * + * @private + * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated + */ + + + CanvasGraphicsRenderer.prototype.updateGraphicsTint = function updateGraphicsTint(graphics) { + graphics._prevTint = graphics.tint; + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF) / 255; + + for (var i = 0; i < graphics.graphicsData.length; ++i) { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + // super inline cos im an optimization NAZI :) + data._fillTint = ((fillColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (fillColor & 0xFF) / 255 * tintB * 255; + + data._lineTint = ((lineColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (lineColor & 0xFF) / 255 * tintB * 255; + } + }; + + /** + * Renders a polygon. + * + * @param {PIXI.Point[]} points - The points to render + * @param {boolean} close - Should the polygon be closed + * @param {CanvasRenderingContext2D} context - The rendering context to use + */ + + + CanvasGraphicsRenderer.prototype.renderPolygon = function renderPolygon(points, close, context) { + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; ++j) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (close) { + context.closePath(); + } + }; + + /** + * destroy graphics object + * + */ + + + CanvasGraphicsRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasGraphicsRenderer; +}(); + +exports.default = CanvasGraphicsRenderer; + + +_CanvasRenderer2.default.registerPlugin('graphics', CanvasGraphicsRenderer); + +},{"../../const":44,"../../renderers/canvas/CanvasRenderer":75}],54:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = bezierCurveTo; +/** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [path=[]] - Path array to push points into + * @return {number[]} Array of points of the curve + */ +function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var path = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : []; + + var n = 20; + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + + path.push(fromX, fromY); + + for (var i = 1, j = 0; i <= n; ++i) { + j = i / n; + + dt = 1 - j; + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + path.push(dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + return path; +} + +},{}],55:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _WebGLGraphicsData = require('./WebGLGraphicsData'); + +var _WebGLGraphicsData2 = _interopRequireDefault(_WebGLGraphicsData); + +var _PrimitiveShader = require('./shaders/PrimitiveShader'); + +var _PrimitiveShader2 = _interopRequireDefault(_PrimitiveShader); + +var _buildPoly = require('./utils/buildPoly'); + +var _buildPoly2 = _interopRequireDefault(_buildPoly); + +var _buildRectangle = require('./utils/buildRectangle'); + +var _buildRectangle2 = _interopRequireDefault(_buildRectangle); + +var _buildRoundedRectangle = require('./utils/buildRoundedRectangle'); + +var _buildRoundedRectangle2 = _interopRequireDefault(_buildRoundedRectangle); + +var _buildCircle = require('./utils/buildCircle'); + +var _buildCircle2 = _interopRequireDefault(_buildCircle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Renders the graphics object. + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var GraphicsRenderer = function (_ObjectRenderer) { + _inherits(GraphicsRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this object renderer works for. + */ + function GraphicsRenderer(renderer) { + _classCallCheck(this, GraphicsRenderer); + + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.graphicsDataPool = []; + + _this.primitiveShader = null; + + _this.gl = renderer.gl; + + // easy access! + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * Called when there is a WebGL context change + * + * @private + * + */ + + + GraphicsRenderer.prototype.onContextChange = function onContextChange() { + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.primitiveShader = new _PrimitiveShader2.default(this.gl); + }; + + /** + * Destroys this renderer. + * + */ + + + GraphicsRenderer.prototype.destroy = function destroy() { + _ObjectRenderer3.default.prototype.destroy.call(this); + + for (var i = 0; i < this.graphicsDataPool.length; ++i) { + this.graphicsDataPool[i].destroy(); + } + + this.graphicsDataPool = null; + }; + + /** + * Renders a graphics object. + * + * @param {PIXI.Graphics} graphics - The graphics object to render. + */ + + + GraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var gl = renderer.gl; + + var webGLData = void 0; + var webGL = graphics._webGL[this.CONTEXT_UID]; + + if (!webGL || graphics.dirty !== webGL.dirty) { + this.updateGraphics(graphics); + + webGL = graphics._webGL[this.CONTEXT_UID]; + } + + // This could be speeded up for sure! + var shader = this.primitiveShader; + + renderer.bindShader(shader); + renderer.state.setBlendMode(graphics.blendMode); + + for (var i = 0, n = webGL.data.length; i < n; i++) { + webGLData = webGL.data[i]; + var shaderTemp = webGLData.shader; + + renderer.bindShader(shaderTemp); + shaderTemp.uniforms.translationMatrix = graphics.transform.worldTransform.toArray(true); + shaderTemp.uniforms.tint = (0, _utils.hex2rgb)(graphics.tint); + shaderTemp.uniforms.alpha = graphics.worldAlpha; + + renderer.bindVao(webGLData.vao); + + if (graphics.nativeLines) { + gl.drawArrays(gl.LINES, 0, webGLData.points.length / 6); + } else { + webGLData.vao.draw(gl.TRIANGLE_STRIP, webGLData.indices.length); + } + } + }; + + /** + * Updates the graphics object + * + * @private + * @param {PIXI.Graphics} graphics - The graphics object to update + */ + + + GraphicsRenderer.prototype.updateGraphics = function updateGraphics(graphics) { + var gl = this.renderer.gl; + + // get the contexts graphics object + var webGL = graphics._webGL[this.CONTEXT_UID]; + + // if the graphics object does not exist in the webGL context time to create it! + if (!webGL) { + webGL = graphics._webGL[this.CONTEXT_UID] = { lastIndex: 0, data: [], gl: gl, clearDirty: -1, dirty: -1 }; + } + + // flag the graphics as not dirty as we are about to update it... + webGL.dirty = graphics.dirty; + + // if the user cleared the graphics object we will need to clear every object + if (graphics.clearDirty !== webGL.clearDirty) { + webGL.clearDirty = graphics.clearDirty; + + // loop through and return all the webGLDatas to the object pool so than can be reused later on + for (var i = 0; i < webGL.data.length; i++) { + this.graphicsDataPool.push(webGL.data[i]); + } + + // clear the array and reset the index.. + webGL.data.length = 0; + webGL.lastIndex = 0; + } + + var webGLData = void 0; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (var _i = webGL.lastIndex; _i < graphics.graphicsData.length; _i++) { + var data = graphics.graphicsData[_i]; + + // TODO - this can be simplified + webGLData = this.getWebGLData(webGL, 0); + + if (data.type === _const.SHAPES.POLY) { + (0, _buildPoly2.default)(data, webGLData); + } + if (data.type === _const.SHAPES.RECT) { + (0, _buildRectangle2.default)(data, webGLData); + } else if (data.type === _const.SHAPES.CIRC || data.type === _const.SHAPES.ELIP) { + (0, _buildCircle2.default)(data, webGLData); + } else if (data.type === _const.SHAPES.RREC) { + (0, _buildRoundedRectangle2.default)(data, webGLData); + } + + webGL.lastIndex++; + } + + this.renderer.bindVao(null); + + // upload all the dirty data... + for (var _i2 = 0; _i2 < webGL.data.length; _i2++) { + webGLData = webGL.data[_i2]; + + if (webGLData.dirty) { + webGLData.upload(); + } + } + }; + + /** + * + * @private + * @param {WebGLRenderingContext} gl - the current WebGL drawing context + * @param {number} type - TODO @Alvin + * @return {*} TODO + */ + + + GraphicsRenderer.prototype.getWebGLData = function getWebGLData(gl, type) { + var webGLData = gl.data[gl.data.length - 1]; + + if (!webGLData || webGLData.points.length > 320000) { + webGLData = this.graphicsDataPool.pop() || new _WebGLGraphicsData2.default(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + + webGLData.reset(type); + gl.data.push(webGLData); + } + + webGLData.dirty = true; + + return webGLData; + }; + + return GraphicsRenderer; +}(_ObjectRenderer3.default); + +exports.default = GraphicsRenderer; + + +_WebGLRenderer2.default.registerPlugin('graphics', GraphicsRenderer); + +},{"../../const":44,"../../renderers/webgl/WebGLRenderer":82,"../../renderers/webgl/utils/ObjectRenderer":92,"../../utils":120,"./WebGLGraphicsData":56,"./shaders/PrimitiveShader":57,"./utils/buildCircle":58,"./utils/buildPoly":60,"./utils/buildRectangle":61,"./utils/buildRoundedRectangle":62}],56:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * An object containing WebGL specific properties to be used by the WebGL renderer + * + * @class + * @private + * @memberof PIXI + */ +var WebGLGraphicsData = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {PIXI.Shader} shader - The shader + * @param {object} attribsState - The state for the VAO + */ + function WebGLGraphicsData(gl, shader, attribsState) { + _classCallCheck(this, WebGLGraphicsData); + + /** + * The current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // TODO does this need to be split before uploading?? + /** + * An array of color components (r,g,b) + * @member {number[]} + */ + this.color = [0, 0, 0]; // color split! + + /** + * An array of points to draw + * @member {PIXI.Point[]} + */ + this.points = []; + + /** + * The indices of the vertices + * @member {number[]} + */ + this.indices = []; + /** + * The main buffer + * @member {WebGLBuffer} + */ + this.buffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl); + + /** + * The index buffer + * @member {WebGLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl); + + /** + * Whether this graphics is dirty or not + * @member {boolean} + */ + this.dirty = true; + + this.glPoints = null; + this.glIndices = null; + + /** + * + * @member {PIXI.Shader} + */ + this.shader = shader; + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, attribsState).addIndex(this.indexBuffer).addAttribute(this.buffer, shader.attributes.aVertexPosition, gl.FLOAT, false, 4 * 6, 0).addAttribute(this.buffer, shader.attributes.aColor, gl.FLOAT, false, 4 * 6, 2 * 4); + } + + /** + * Resets the vertices and the indices + */ + + + WebGLGraphicsData.prototype.reset = function reset() { + this.points.length = 0; + this.indices.length = 0; + }; + + /** + * Binds the buffers and uploads the data + */ + + + WebGLGraphicsData.prototype.upload = function upload() { + this.glPoints = new Float32Array(this.points); + this.buffer.upload(this.glPoints); + + this.glIndices = new Uint16Array(this.indices); + this.indexBuffer.upload(this.glIndices); + + this.dirty = false; + }; + + /** + * Empties all the data + */ + + + WebGLGraphicsData.prototype.destroy = function destroy() { + this.color = null; + this.points = null; + this.indices = null; + + this.vao.destroy(); + this.buffer.destroy(); + this.indexBuffer.destroy(); + + this.gl = null; + + this.buffer = null; + this.indexBuffer = null; + + this.glPoints = null; + this.glIndices = null; + }; + + return WebGLGraphicsData; +}(); + +exports.default = WebGLGraphicsData; + +},{"pixi-gl-core":12}],57:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../../Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. + * + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ +var PrimitiveShader = function (_Shader) { + _inherits(PrimitiveShader, _Shader); + + /** + * @param {WebGLRenderingContext} gl - The webgl shader manager this shader works for. + */ + function PrimitiveShader(gl) { + _classCallCheck(this, PrimitiveShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec4 aColor;', 'uniform mat3 translationMatrix;', 'uniform mat3 projectionMatrix;', 'uniform float alpha;', 'uniform vec3 tint;', 'varying vec4 vColor;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vColor = aColor * vec4(tint * alpha, alpha);', '}'].join('\n'), + // fragment shader + ['varying vec4 vColor;', 'void main(void){', ' gl_FragColor = vColor;', '}'].join('\n'))); + } + + return PrimitiveShader; +}(_Shader3.default); + +exports.default = PrimitiveShader; + +},{"../../../Shader":42}],58:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildCircle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _const = require('../../../const'); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildCircle(graphicsData, webGLData) { + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width = void 0; + var height = void 0; + + // TODO - bit hacky?? + if (graphicsData.type === _const.SHAPES.CIRC) { + width = circleData.radius; + height = circleData.radius; + } else { + width = circleData.width; + height = circleData.height; + } + + if (width === 0 || height === 0) { + return; + } + + var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); + + var seg = Math.PI * 2 / totalSegs; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + indices.push(vecPos); + + for (var i = 0; i < totalSegs + 1; i++) { + verts.push(x, y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos - 1); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (var _i = 0; _i < totalSegs + 1; _i++) { + graphicsData.points.push(x + Math.sin(seg * _i) * width, y + Math.cos(seg * _i) * height); + } + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +},{"../../../const":44,"../../../utils":120,"./buildLine":59}],59:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function (graphicsData, webGLData) { + if (graphicsData.nativeLines) { + buildNativeLine(graphicsData, webGLData); + } else { + buildLine(graphicsData, webGLData); + } +}; + +var _math = require('../../../math'); + +var _utils = require('../../../utils'); + +/** + * Builds a line to draw using the poligon method. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildLine(graphicsData, webGLData) { + // TODO OPTIMISE! + var points = graphicsData.points; + + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + + // get first and last point.. figure out the middle! + var firstPoint = new _math.Point(points[0], points[1]); + var lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + // if the first point is the last point - gonna have issues :) + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var p1x = points[0]; + var p1y = points[1]; + var p2x = points[2]; + var p2y = points[3]; + var p3x = 0; + var p3y = 0; + + var perpx = -(p1y - p2y); + var perpy = p1x - p2x; + var perp2x = 0; + var perp2y = 0; + var perp3x = 0; + var perp3y = 0; + + var dist = Math.sqrt(perpx * perpx + perpy * perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx, p1y - perpy, r, g, b, alpha); + + verts.push(p1x + perpx, p1y + perpy, r, g, b, alpha); + + for (var i = 1; i < length - 1; ++i) { + p1x = points[(i - 1) * 2]; + p1y = points[(i - 1) * 2 + 1]; + + p2x = points[i * 2]; + p2y = points[i * 2 + 1]; + + p3x = points[(i + 1) * 2]; + p3y = points[(i + 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + var a1 = -perpy + p1y - (-perpy + p2y); + var b1 = -perpx + p2x - (-perpx + p1x); + var c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + var a2 = -perp2y + p3y - (-perp2y + p2y); + var b2 = -perp2x + p2x - (-perp2x + p3x); + var c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + var denom = a1 * b2 - a2 * b1; + + if (Math.abs(denom) < 0.1) { + denom += 10.1; + verts.push(p2x - perpx, p2y - perpy, r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy, r, g, b, alpha); + + continue; + } + + var px = (b1 * c2 - b2 * c1) / denom; + var py = (a2 * c1 - a1 * c2) / denom; + var pdist = (px - p2x) * (px - p2x) + (py - p2y) * (py - p2y); + + if (pdist > 196 * width * width) { + perp3x = perpx - perp2x; + perp3y = perpy - perp2y; + + dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y); + perp3x /= dist; + perp3y /= dist; + perp3x *= width; + perp3y *= width; + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x + perp3x, p2y + perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + indexCount++; + } else { + verts.push(px, py); + verts.push(r, g, b, alpha); + + verts.push(p2x - (px - p2x), p2y - (py - p2y)); + verts.push(r, g, b, alpha); + } + } + + p1x = points[(length - 2) * 2]; + p1y = points[(length - 2) * 2 + 1]; + + p2x = points[(length - 1) * 2]; + p2y = points[(length - 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + verts.push(p2x - perpx, p2y - perpy); + verts.push(r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy); + verts.push(r, g, b, alpha); + + indices.push(indexStart); + + for (var _i = 0; _i < indexCount; ++_i) { + indices.push(indexStart++); + } + + indices.push(indexStart - 1); +} + +/** + * Builds a line to draw using the gl.drawArrays(gl.LINES) method + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ + + +/** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildNativeLine(graphicsData, webGLData) { + var i = 0; + var points = graphicsData.points; + + if (points.length === 0) return; + + var verts = webGLData.points; + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + for (i = 1; i < length; i++) { + var p1x = points[(i - 1) * 2]; + var p1y = points[(i - 1) * 2 + 1]; + + var p2x = points[i * 2]; + var p2y = points[i * 2 + 1]; + + verts.push(p1x, p1y); + verts.push(r, g, b, alpha); + + verts.push(p2x, p2y); + verts.push(r, g, b, alpha); + } +} + +},{"../../../math":68,"../../../utils":120}],60:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildPoly; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildPoly(graphicsData, webGLData) { + graphicsData.points = graphicsData.shape.points.slice(); + + var points = graphicsData.points; + + if (graphicsData.fill && points.length >= 6) { + var holeArray = []; + // Process holes.. + var holes = graphicsData.holes; + + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + + holeArray.push(points.length / 2); + + points = points.concat(hole.points); + } + + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = (0, _earcut2.default)(points, holeArray, 2); + + if (!triangles) { + return; + } + + var vertPos = verts.length / 6; + + for (var _i = 0; _i < triangles.length; _i += 3) { + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i + 1] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + } + + for (var _i2 = 0; _i2 < length; _i2++) { + verts.push(points[_i2 * 2], points[_i2 * 2 + 1], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth > 0) { + (0, _buildLine2.default)(graphicsData, webGLData); + } +} + +},{"../../../utils":120,"./buildLine":59,"earcut":2}],61:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRectangle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildRectangle(graphicsData, webGLData) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vertPos = verts.length / 6; + + // start + verts.push(x, y); + verts.push(r, g, b, alpha); + + verts.push(x + width, y); + verts.push(r, g, b, alpha); + + verts.push(x, y + height); + verts.push(r, g, b, alpha); + + verts.push(x + width, y + height); + verts.push(r, g, b, alpha); + + // insert 2 dead triangles.. + indices.push(vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y]; + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +},{"../../../utils":120,"./buildLine":59}],62:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRoundedRectangle; + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildRoundedRectangle(graphicsData, webGLData) { + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + + recPoints.push(x, y + radius); + quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height, recPoints); + quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius, recPoints); + quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y, recPoints); + quadraticBezierCurve(x + radius, y, x, y, x, y + radius + 0.0000000001, recPoints); + + // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. + // TODO - fix this properly, this is not very elegant.. but it works for now. + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + var triangles = (0, _earcut2.default)(recPoints, null, 2); + + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + + for (var _i = 0, _j = recPoints.length; _i < _j; _i++) { + verts.push(recPoints[_i], recPoints[++_i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +/** + * Calculate a single point for a quadratic bezier curve. + * Utility function used by quadraticBezierCurve. + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} n1 - first number + * @param {number} n2 - second number + * @param {number} perc - percentage + * @return {number} the result + * + */ +function getPt(n1, n2, perc) { + var diff = n2 - n1; + + return n1 + diff * perc; +} + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @return {number[]} an array of points + */ +function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY) { + var out = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : []; + + var n = 20; + var points = out; + + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + + points.push(x, y); + } + + return points; +} + +},{"../../../utils":120,"./buildLine":59,"earcut":2}],63:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = exports.Application = exports.Filter = exports.SpriteMaskFilter = exports.Quad = exports.RenderTarget = exports.ObjectRenderer = exports.WebGLManager = exports.Shader = exports.CanvasRenderTarget = exports.TextureUvs = exports.VideoBaseTexture = exports.BaseRenderTexture = exports.RenderTexture = exports.BaseTexture = exports.Texture = exports.Spritesheet = exports.CanvasGraphicsRenderer = exports.GraphicsRenderer = exports.GraphicsData = exports.Graphics = exports.TextStyle = exports.Text = exports.SpriteRenderer = exports.CanvasTinter = exports.CanvasSpriteRenderer = exports.Sprite = exports.TransformBase = exports.TransformStatic = exports.Transform = exports.Container = exports.DisplayObject = exports.Bounds = exports.glCore = exports.WebGLRenderer = exports.CanvasRenderer = exports.ticker = exports.utils = exports.settings = undefined; + +var _const = require('./const'); + +Object.keys(_const).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _const[key]; + } + }); +}); + +var _math = require('./math'); + +Object.keys(_math).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _math[key]; + } + }); +}); + +var _pixiGlCore = require('pixi-gl-core'); + +Object.defineProperty(exports, 'glCore', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_pixiGlCore).default; + } +}); + +var _Bounds = require('./display/Bounds'); + +Object.defineProperty(exports, 'Bounds', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Bounds).default; + } +}); + +var _DisplayObject = require('./display/DisplayObject'); + +Object.defineProperty(exports, 'DisplayObject', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplayObject).default; + } +}); + +var _Container = require('./display/Container'); + +Object.defineProperty(exports, 'Container', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Container).default; + } +}); + +var _Transform = require('./display/Transform'); + +Object.defineProperty(exports, 'Transform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Transform).default; + } +}); + +var _TransformStatic = require('./display/TransformStatic'); + +Object.defineProperty(exports, 'TransformStatic', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformStatic).default; + } +}); + +var _TransformBase = require('./display/TransformBase'); + +Object.defineProperty(exports, 'TransformBase', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformBase).default; + } +}); + +var _Sprite = require('./sprites/Sprite'); + +Object.defineProperty(exports, 'Sprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Sprite).default; + } +}); + +var _CanvasSpriteRenderer = require('./sprites/canvas/CanvasSpriteRenderer'); + +Object.defineProperty(exports, 'CanvasSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasSpriteRenderer).default; + } +}); + +var _CanvasTinter = require('./sprites/canvas/CanvasTinter'); + +Object.defineProperty(exports, 'CanvasTinter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasTinter).default; + } +}); + +var _SpriteRenderer = require('./sprites/webgl/SpriteRenderer'); + +Object.defineProperty(exports, 'SpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteRenderer).default; + } +}); + +var _Text = require('./text/Text'); + +Object.defineProperty(exports, 'Text', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Text).default; + } +}); + +var _TextStyle = require('./text/TextStyle'); + +Object.defineProperty(exports, 'TextStyle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextStyle).default; + } +}); + +var _Graphics = require('./graphics/Graphics'); + +Object.defineProperty(exports, 'Graphics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Graphics).default; + } +}); + +var _GraphicsData = require('./graphics/GraphicsData'); + +Object.defineProperty(exports, 'GraphicsData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsData).default; + } +}); + +var _GraphicsRenderer = require('./graphics/webgl/GraphicsRenderer'); + +Object.defineProperty(exports, 'GraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsRenderer).default; + } +}); + +var _CanvasGraphicsRenderer = require('./graphics/canvas/CanvasGraphicsRenderer'); + +Object.defineProperty(exports, 'CanvasGraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasGraphicsRenderer).default; + } +}); + +var _Spritesheet = require('./textures/Spritesheet'); + +Object.defineProperty(exports, 'Spritesheet', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Spritesheet).default; + } +}); + +var _Texture = require('./textures/Texture'); + +Object.defineProperty(exports, 'Texture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Texture).default; + } +}); + +var _BaseTexture = require('./textures/BaseTexture'); + +Object.defineProperty(exports, 'BaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseTexture).default; + } +}); + +var _RenderTexture = require('./textures/RenderTexture'); + +Object.defineProperty(exports, 'RenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTexture).default; + } +}); + +var _BaseRenderTexture = require('./textures/BaseRenderTexture'); + +Object.defineProperty(exports, 'BaseRenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseRenderTexture).default; + } +}); + +var _VideoBaseTexture = require('./textures/VideoBaseTexture'); + +Object.defineProperty(exports, 'VideoBaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VideoBaseTexture).default; + } +}); + +var _TextureUvs = require('./textures/TextureUvs'); + +Object.defineProperty(exports, 'TextureUvs', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureUvs).default; + } +}); + +var _CanvasRenderTarget = require('./renderers/canvas/utils/CanvasRenderTarget'); + +Object.defineProperty(exports, 'CanvasRenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasRenderTarget).default; + } +}); + +var _Shader = require('./Shader'); + +Object.defineProperty(exports, 'Shader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Shader).default; + } +}); + +var _WebGLManager = require('./renderers/webgl/managers/WebGLManager'); + +Object.defineProperty(exports, 'WebGLManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLManager).default; + } +}); + +var _ObjectRenderer = require('./renderers/webgl/utils/ObjectRenderer'); + +Object.defineProperty(exports, 'ObjectRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObjectRenderer).default; + } +}); + +var _RenderTarget = require('./renderers/webgl/utils/RenderTarget'); + +Object.defineProperty(exports, 'RenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTarget).default; + } +}); + +var _Quad = require('./renderers/webgl/utils/Quad'); + +Object.defineProperty(exports, 'Quad', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Quad).default; + } +}); + +var _SpriteMaskFilter = require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter'); + +Object.defineProperty(exports, 'SpriteMaskFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteMaskFilter).default; + } +}); + +var _Filter = require('./renderers/webgl/filters/Filter'); + +Object.defineProperty(exports, 'Filter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Filter).default; + } +}); + +var _Application = require('./Application'); + +Object.defineProperty(exports, 'Application', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Application).default; + } +}); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +Object.defineProperty(exports, 'autoDetectRenderer', { + enumerable: true, + get: function get() { + return _autoDetectRenderer.autoDetectRenderer; + } +}); + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _ticker = require('./ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.settings = _settings2.default; +exports.utils = utils; +exports.ticker = ticker; +exports.CanvasRenderer = _CanvasRenderer2.default; +exports.WebGLRenderer = _WebGLRenderer2.default; /** + * @namespace PIXI + */ + +},{"./Application":41,"./Shader":42,"./autoDetectRenderer":43,"./const":44,"./display/Bounds":45,"./display/Container":46,"./display/DisplayObject":47,"./display/Transform":48,"./display/TransformBase":49,"./display/TransformStatic":50,"./graphics/Graphics":51,"./graphics/GraphicsData":52,"./graphics/canvas/CanvasGraphicsRenderer":53,"./graphics/webgl/GraphicsRenderer":55,"./math":68,"./renderers/canvas/CanvasRenderer":75,"./renderers/canvas/utils/CanvasRenderTarget":77,"./renderers/webgl/WebGLRenderer":82,"./renderers/webgl/filters/Filter":84,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":87,"./renderers/webgl/managers/WebGLManager":91,"./renderers/webgl/utils/ObjectRenderer":92,"./renderers/webgl/utils/Quad":93,"./renderers/webgl/utils/RenderTarget":94,"./settings":99,"./sprites/Sprite":100,"./sprites/canvas/CanvasSpriteRenderer":101,"./sprites/canvas/CanvasTinter":102,"./sprites/webgl/SpriteRenderer":104,"./text/Text":106,"./text/TextStyle":107,"./textures/BaseRenderTexture":108,"./textures/BaseTexture":109,"./textures/RenderTexture":110,"./textures/Spritesheet":111,"./textures/Texture":112,"./textures/TextureUvs":113,"./textures/VideoBaseTexture":114,"./ticker":116,"./utils":120,"pixi-gl-core":12}],64:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Matrix = require('./Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16 + +var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; +var tempMatrices = []; + +var mul = []; + +function signum(x) { + if (x < 0) { + return -1; + } + if (x > 0) { + return 1; + } + + return 0; +} + +function init() { + for (var i = 0; i < 16; i++) { + var row = []; + + mul.push(row); + + for (var j = 0; j < 16; j++) { + var _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); + var _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); + var _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); + var _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); + + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + + for (var _i = 0; _i < 16; _i++) { + var mat = new _Matrix2.default(); + + mat.set(ux[_i], uy[_i], vx[_i], vy[_i], 0, 0); + tempMatrices.push(mat); + } +} + +init(); + +/** + * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, + * D8 is the same but with diagonals. Used for texture rotations. + * + * Vector xX(i), xY(i) is U-axis of sprite with rotation i + * Vector yY(i), yY(i) is V-axis of sprite with rotation i + * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) + * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) + * This is the small part of gameofbombs.com portal system. It works. + * + * @author Ivan @ivanpopelyshev + * @class + * @memberof PIXI + */ +var GroupD8 = { + E: 0, + SE: 1, + S: 2, + SW: 3, + W: 4, + NW: 5, + N: 6, + NE: 7, + MIRROR_VERTICAL: 8, + MIRROR_HORIZONTAL: 12, + uX: function uX(ind) { + return ux[ind]; + }, + uY: function uY(ind) { + return uy[ind]; + }, + vX: function vX(ind) { + return vx[ind]; + }, + vY: function vY(ind) { + return vy[ind]; + }, + inv: function inv(rotation) { + if (rotation & 8) { + return rotation & 15; + } + + return -rotation & 7; + }, + add: function add(rotationSecond, rotationFirst) { + return mul[rotationSecond][rotationFirst]; + }, + sub: function sub(rotationSecond, rotationFirst) { + return mul[rotationSecond][GroupD8.inv(rotationFirst)]; + }, + + /** + * Adds 180 degrees to rotation. Commutative operation. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to rotate. + * @returns {number} rotated number + */ + rotate180: function rotate180(rotation) { + return rotation ^ 4; + }, + + /** + * I dont know why sometimes width and heights needs to be swapped. We'll fix it later. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the width/height should be swapped. + */ + isSwapWidthHeight: function isSwapWidthHeight(rotation) { + return (rotation & 3) === 2; + }, + + /** + * @memberof PIXI.GroupD8 + * @param {number} dx - TODO + * @param {number} dy - TODO + * + * @return {number} TODO + */ + byDirection: function byDirection(dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return GroupD8.S; + } + + return GroupD8.N; + } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return GroupD8.E; + } + + return GroupD8.W; + } else if (dy > 0) { + if (dx > 0) { + return GroupD8.SE; + } + + return GroupD8.SW; + } else if (dx > 0) { + return GroupD8.NE; + } + + return GroupD8.NW; + }, + + /** + * Helps sprite to compensate texture packer rotation. + * + * @memberof PIXI.GroupD8 + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {number} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function matrixAppendRotationInv(matrix, rotation) { + var tx = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var ty = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + // Packer used "rotation", we use "inv(rotation)" + var mat = tempMatrices[GroupD8.inv(rotation)]; + + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + } +}; + +exports.default = GroupD8; + +},{"./Matrix":65}],65:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Point = require('./Point'); + +var _Point2 = _interopRequireDefault(_Point); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The pixi Matrix class as an object, which makes it a lot faster, + * here is a representation of it : + * | a | b | tx| + * | c | d | ty| + * | 0 | 0 | 1 | + * + * @class + * @memberof PIXI + */ +var Matrix = function () { + /** + * @param {number} [a=1] - x scale + * @param {number} [b=0] - y skew + * @param {number} [c=0] - x skew + * @param {number} [d=1] - y scale + * @param {number} [tx=0] - x translation + * @param {number} [ty=0] - y translation + */ + function Matrix() { + var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var d = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var tx = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var ty = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + + _classCallCheck(this, Matrix); + + /** + * @member {number} + * @default 1 + */ + this.a = a; + + /** + * @member {number} + * @default 0 + */ + this.b = b; + + /** + * @member {number} + * @default 0 + */ + this.c = c; + + /** + * @member {number} + * @default 1 + */ + this.d = d; + + /** + * @member {number} + * @default 0 + */ + this.tx = tx; + + /** + * @member {number} + * @default 0 + */ + this.ty = ty; + + this.array = null; + } + + /** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @param {number[]} array - The array that the matrix will be populated from. + */ + + + Matrix.prototype.fromArray = function fromArray(array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + }; + + /** + * sets the matrix properties + * + * @param {number} a - Matrix component + * @param {number} b - Matrix component + * @param {number} c - Matrix component + * @param {number} d - Matrix component + * @param {number} tx - Matrix component + * @param {number} ty - Matrix component + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.set = function set(a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + }; + + /** + * Creates an array from the current Matrix object. + * + * @param {boolean} transpose - Whether we need to transpose the matrix or not + * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out + * @return {number[]} the newly created array which contains the matrix + */ + + + Matrix.prototype.toArray = function toArray(transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + + var array = out || this.array; + + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + }; + + /** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, transformed through this matrix + */ + + + Matrix.prototype.apply = function apply(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; + + return newPos; + }; + + /** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, inverse-transformed through this matrix + */ + + + Matrix.prototype.applyInverse = function applyInverse(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var id = 1 / (this.a * this.d + this.c * -this.b); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + }; + + /** + * Translates the matrix on the x and y. + * + * @param {number} x How much to translate x by + * @param {number} y How much to translate y by + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.translate = function translate(x, y) { + this.tx += x; + this.ty += y; + + return this; + }; + + /** + * Applies a scale transformation to the matrix. + * + * @param {number} x The amount to scale horizontally + * @param {number} y The amount to scale vertically + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.scale = function scale(x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + }; + + /** + * Applies a rotation transformation to the matrix. + * + * @param {number} angle - The angle in radians. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.rotate = function rotate(angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos - this.b * sin; + this.b = a1 * sin + this.b * cos; + this.c = c1 * cos - this.d * sin; + this.d = c1 * sin + this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + }; + + /** + * Appends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to append. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.append = function append(matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + }; + + /** + * Sets the matrix based on all the available properties + * + * @param {number} x - Position on the x axis + * @param {number} y - Position on the y axis + * @param {number} pivotX - Pivot on the x axis + * @param {number} pivotY - Pivot on the y axis + * @param {number} scaleX - Scale on the x axis + * @param {number} scaleY - Scale on the y axis + * @param {number} rotation - Rotation in radians + * @param {number} skewX - Skew on the x axis + * @param {number} skewY - Skew on the y axis + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.setTransform = function setTransform(x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + var sr = Math.sin(rotation); + var cr = Math.cos(rotation); + var cy = Math.cos(skewY); + var sy = Math.sin(skewY); + var nsx = -Math.sin(skewX); + var cx = Math.cos(skewX); + + var a = cr * scaleX; + var b = sr * scaleX; + var c = -sr * scaleY; + var d = cr * scaleY; + + this.a = cy * a + sy * c; + this.b = cy * b + sy * d; + this.c = nsx * a + cx * c; + this.d = nsx * b + cx * d; + + this.tx = x + (pivotX * a + pivotY * c); + this.ty = y + (pivotX * b + pivotY * d); + + return this; + }; + + /** + * Prepends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to prepend + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.prepend = function prepend(matrix) { + var tx1 = this.tx; + + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + + this.a = a1 * matrix.a + this.b * matrix.c; + this.b = a1 * matrix.b + this.b * matrix.d; + this.c = c1 * matrix.a + this.d * matrix.c; + this.d = c1 * matrix.b + this.d * matrix.d; + } + + this.tx = tx1 * matrix.a + this.ty * matrix.c + matrix.tx; + this.ty = tx1 * matrix.b + this.ty * matrix.d + matrix.ty; + + return this; + }; + + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * + * @param {PIXI.Transform|PIXI.TransformStatic} transform - The transform to apply the properties to. + * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properties + */ + + + Matrix.prototype.decompose = function decompose(transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + + var skewX = -Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + + var delta = Math.abs(skewX + skewY); + + if (delta < 0.00001) { + transform.rotation = skewY; + + if (a < 0 && d >= 0) { + transform.rotation += transform.rotation <= 0 ? Math.PI : -Math.PI; + } + + transform.skew.x = transform.skew.y = 0; + } else { + transform.skew.x = skewX; + transform.skew.y = skewY; + } + + // next set scale + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); + + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; + + return transform; + }; + + /** + * Inverts this matrix + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.invert = function invert() { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1 * d1 - b1 * c1; + + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = (c1 * this.ty - d1 * tx1) / n; + this.ty = -(a1 * this.ty - b1 * tx1) / n; + + return this; + }; + + /** + * Resets this Matix to an identity (default) matrix. + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.identity = function identity() { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + + return this; + }; + + /** + * Creates a new Matrix object with the same values as this one. + * + * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. + */ + + + Matrix.prototype.clone = function clone() { + var matrix = new Matrix(); + + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * Changes the values of the given matrix to be the same as the ones in this matrix + * + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @return {PIXI.Matrix} The matrix given in parameter with its values updated. + */ + + + Matrix.prototype.copy = function copy(matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * A default (identity) matrix + * + * @static + * @const + */ + + + _createClass(Matrix, null, [{ + key: 'IDENTITY', + get: function get() { + return new Matrix(); + } + + /** + * A temp matrix + * + * @static + * @const + */ + + }, { + key: 'TEMP_MATRIX', + get: function get() { + return new Matrix(); + } + }]); + + return Matrix; +}(); + +exports.default = Matrix; + +},{"./Point":67}],66:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * An observable point is a point that triggers a callback when the point's position is changed. + * + * @class + * @memberof PIXI + */ +var ObservablePoint = function () { + /** + * @param {Function} cb - callback when changed + * @param {object} scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope) { + var x = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var y = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, ObservablePoint); + + this._x = x; + this._y = y; + + this.cb = cb; + this.scope = scope; + } + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + ObservablePoint.prototype.set = function set(x, y) { + var _x = x || 0; + var _y = y || (y !== 0 ? _x : 0); + + if (this._x !== _x || this._y !== _y) { + this._x = _x; + this._y = _y; + this.cb.call(this.scope); + } + }; + + /** + * Copies the data from another point + * + * @param {PIXI.Point|PIXI.ObservablePoint} point - point to copy from + */ + + + ObservablePoint.prototype.copy = function copy(point) { + if (this._x !== point.x || this._y !== point.y) { + this._x = point.x; + this._y = point.y; + this.cb.call(this.scope); + } + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + + _createClass(ObservablePoint, [{ + key: "x", + get: function get() { + return this._x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + } + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + }, { + key: "y", + get: function get() { + return this._y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + } + }]); + + return ObservablePoint; +}(); + +exports.default = ObservablePoint; + +},{}],67:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * + * @class + * @memberof PIXI + */ +var Point = function () { + /** + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function Point() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + + _classCallCheck(this, Point); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + } + + /** + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point + */ + + + Point.prototype.clone = function clone() { + return new Point(this.x, this.y); + }; + + /** + * Copies x and y from the given point + * + * @param {PIXI.Point} p - The point to copy. + */ + + + Point.prototype.copy = function copy(p) { + this.set(p.x, p.y); + }; + + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.Point} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + + + Point.prototype.equals = function equals(p) { + return p.x === this.x && p.y === this.y; + }; + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + Point.prototype.set = function set(x, y) { + this.x = x || 0; + this.y = y || (y !== 0 ? this.x : 0); + }; + + return Point; +}(); + +exports.default = Point; + +},{}],68:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('./Point'); + +Object.defineProperty(exports, 'Point', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Point).default; + } +}); + +var _ObservablePoint = require('./ObservablePoint'); + +Object.defineProperty(exports, 'ObservablePoint', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObservablePoint).default; + } +}); + +var _Matrix = require('./Matrix'); + +Object.defineProperty(exports, 'Matrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Matrix).default; + } +}); + +var _GroupD = require('./GroupD8'); + +Object.defineProperty(exports, 'GroupD8', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GroupD).default; + } +}); + +var _Circle = require('./shapes/Circle'); + +Object.defineProperty(exports, 'Circle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Circle).default; + } +}); + +var _Ellipse = require('./shapes/Ellipse'); + +Object.defineProperty(exports, 'Ellipse', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Ellipse).default; + } +}); + +var _Polygon = require('./shapes/Polygon'); + +Object.defineProperty(exports, 'Polygon', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Polygon).default; + } +}); + +var _Rectangle = require('./shapes/Rectangle'); + +Object.defineProperty(exports, 'Rectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rectangle).default; + } +}); + +var _RoundedRectangle = require('./shapes/RoundedRectangle'); + +Object.defineProperty(exports, 'RoundedRectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RoundedRectangle).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./GroupD8":64,"./Matrix":65,"./ObservablePoint":66,"./Point":67,"./shapes/Circle":69,"./shapes/Ellipse":70,"./shapes/Polygon":71,"./shapes/Rectangle":72,"./shapes/RoundedRectangle":73}],69:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Circle object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Circle = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [radius=0] - The radius of the circle + */ + function Circle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var radius = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + _classCallCheck(this, Circle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.CIRC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.CIRC; + } + + /** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ + + + Circle.prototype.clone = function clone() { + return new Circle(this.x, this.y, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this circle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Circle + */ + + + Circle.prototype.contains = function contains(x, y) { + if (this.radius <= 0) { + return false; + } + + var r2 = this.radius * this.radius; + var dx = this.x - x; + var dy = this.y - y; + + dx *= dx; + dy *= dy; + + return dx + dy <= r2; + }; + + /** + * Returns the framing rectangle of the circle as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Circle.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + + return Circle; +}(); + +exports.default = Circle; + +},{"../../const":44,"./Rectangle":72}],70:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Ellipse object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Ellipse = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [width=0] - The half width of this ellipse + * @param {number} [height=0] - The half height of this ellipse + */ + function Ellipse() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Ellipse); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.ELIP + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.ELIP; + } + + /** + * Creates a clone of this Ellipse instance + * + * @return {PIXI.Ellipse} a copy of the ellipse + */ + + + Ellipse.prototype.clone = function clone() { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coords are within this ellipse + */ + + + Ellipse.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + // normalize the coords to an ellipse with center 0,0 + var normx = (x - this.x) / this.width; + var normy = (y - this.y) / this.height; + + normx *= normx; + normy *= normy; + + return normx + normy <= 1; + }; + + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Ellipse.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.width, this.y - this.height, this.width, this.height); + }; + + return Ellipse; +}(); + +exports.default = Ellipse; + +},{"../../const":44,"./Rectangle":72}],71:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('../Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Polygon = function () { + /** + * @param {PIXI.Point[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + for (var _len = arguments.length, points = Array(_len), _key = 0; _key < _len; _key++) { + points[_key] = arguments[_key]; + } + + _classCallCheck(this, Polygon); + + if (Array.isArray(points[0])) { + points = points[0]; + } + + // if this is an array of points, convert it to a flat array of numbers + if (points[0] instanceof _Point2.default) { + var p = []; + + for (var i = 0, il = points.length; i < il; i++) { + p.push(points[i].x, points[i].y); + } + + points = p; + } + + this.closed = true; + + /** + * An array of the points of this polygon + * + * @member {number[]} + */ + this.points = points; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.POLY + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.POLY; + } + + /** + * Creates a clone of this polygon + * + * @return {PIXI.Polygon} a copy of the polygon + */ + + + Polygon.prototype.clone = function clone() { + return new Polygon(this.points.slice()); + }; + + /** + * Closes the polygon, adding points if necessary. + * + */ + + + Polygon.prototype.close = function close() { + var points = this.points; + + // close the poly if the value is true! + if (points[0] !== points[points.length - 2] || points[1] !== points[points.length - 1]) { + points.push(points[0], points[1]); + } + }; + + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this polygon + */ + + + Polygon.prototype.contains = function contains(x, y) { + var inside = false; + + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + + for (var i = 0, j = length - 1; i < length; j = i++) { + var xi = this.points[i * 2]; + var yi = this.points[i * 2 + 1]; + var xj = this.points[j * 2]; + var yj = this.points[j * 2 + 1]; + var intersect = yi > y !== yj > y && x < (xj - xi) * ((y - yi) / (yj - yi)) + xi; + + if (intersect) { + inside = !inside; + } + } + + return inside; + }; + + return Polygon; +}(); + +exports.default = Polygon; + +},{"../../const":44,"../Point":67}],72:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * + * @class + * @memberof PIXI + */ +var Rectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle + * @param {number} [width=0] - The overall width of this rectangle + * @param {number} [height=0] - The overall height of this rectangle + */ + function Rectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Rectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.RECT + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RECT; + } + + /** + * returns the left edge of the rectangle + * + * @member {number} + */ + + + /** + * Creates a clone of this Rectangle + * + * @return {PIXI.Rectangle} a copy of the rectangle + */ + Rectangle.prototype.clone = function clone() { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + + /** + * Copies another rectangle to this one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to copy. + * @return {PIXI.Rectangle} Returns itself. + */ + + + Rectangle.prototype.copy = function copy(rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + + return this; + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rectangle + */ + + + Rectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + + return false; + }; + + /** + * Pads the rectangle making it grow in all directions. + * + * @param {number} paddingX - The horizontal padding amount. + * @param {number} paddingY - The vertical padding amount. + */ + + + Rectangle.prototype.pad = function pad(paddingX, paddingY) { + paddingX = paddingX || 0; + paddingY = paddingY || (paddingY !== 0 ? paddingX : 0); + + this.x -= paddingX; + this.y -= paddingY; + + this.width += paddingX * 2; + this.height += paddingY * 2; + }; + + /** + * Fits this rectangle around the passed one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to fit. + */ + + + Rectangle.prototype.fit = function fit(rectangle) { + if (this.x < rectangle.x) { + this.width += this.x; + if (this.width < 0) { + this.width = 0; + } + + this.x = rectangle.x; + } + + if (this.y < rectangle.y) { + this.height += this.y; + if (this.height < 0) { + this.height = 0; + } + this.y = rectangle.y; + } + + if (this.x + this.width > rectangle.x + rectangle.width) { + this.width = rectangle.width - this.x; + if (this.width < 0) { + this.width = 0; + } + } + + if (this.y + this.height > rectangle.y + rectangle.height) { + this.height = rectangle.height - this.y; + if (this.height < 0) { + this.height = 0; + } + } + }; + + /** + * Enlarges this rectangle to include the passed rectangle. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to include. + */ + + + Rectangle.prototype.enlarge = function enlarge(rectangle) { + var x1 = Math.min(this.x, rectangle.x); + var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.min(this.y, rectangle.y); + var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); + + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + }; + + _createClass(Rectangle, [{ + key: 'left', + get: function get() { + return this.x; + } + + /** + * returns the right edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'right', + get: function get() { + return this.x + this.width; + } + + /** + * returns the top edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'top', + get: function get() { + return this.y; + } + + /** + * returns the bottom edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'bottom', + get: function get() { + return this.y + this.height; + } + + /** + * A constant empty rectangle. + * + * @static + * @constant + */ + + }], [{ + key: 'EMPTY', + get: function get() { + return new Rectangle(0, 0, 0, 0); + } + }]); + + return Rectangle; +}(); + +exports.default = Rectangle; + +},{"../../const":44}],73:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. + * + * @class + * @memberof PIXI + */ +var RoundedRectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle + * @param {number} [width=0] - The overall width of this rounded rectangle + * @param {number} [height=0] - The overall height of this rounded rectangle + * @param {number} [radius=20] - Controls the radius of the rounded corners + */ + function RoundedRectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var radius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 20; + + _classCallCheck(this, RoundedRectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * @member {number} + * @default 20 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readonly + * @default PIXI.SHAPES.RREC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RREC; + } + + /** + * Creates a clone of this Rounded Rectangle + * + * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle + */ + + + RoundedRectangle.prototype.clone = function clone() { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + */ + + + RoundedRectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + if (y >= this.y + this.radius && y <= this.y + this.height - this.radius || x >= this.x + this.radius && x <= this.x + this.width - this.radius) { + return true; + } + var dx = x - (this.x + this.radius); + var dy = y - (this.y + this.radius); + var radius2 = this.radius * this.radius; + + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.width - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dy = y - (this.y + this.height - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + } + } + + return false; + }; + + return RoundedRectangle; +}(); + +exports.default = RoundedRectangle; + +},{"../../const":44}],74:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _math = require('../math'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _Container = require('../display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMatrix = new _math.Matrix(); + +/** + * The SystemRenderer is the base for a Pixi Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.WebGLRenderer} which can be used for rendering a Pixi scene. + * + * @abstract + * @class + * @extends EventEmitter + * @memberof PIXI + */ + +var SystemRenderer = function (_EventEmitter) { + _inherits(SystemRenderer, _EventEmitter); + + /** + * @param {string} system - The name of the system this renderer is for. + * @param {number} [screenWidth=800] - the width of the screen + * @param {number} [screenHeight=600] - the height of the screen + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function SystemRenderer(system, screenWidth, screenHeight, options) { + _classCallCheck(this, SystemRenderer); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + (0, _utils.sayHello)(system); + + // prepare options + if (options) { + for (var i in _settings2.default.RENDER_OPTIONS) { + if (typeof options[i] === 'undefined') { + options[i] = _settings2.default.RENDER_OPTIONS[i]; + } + } + } else { + options = _settings2.default.RENDER_OPTIONS; + } + + /** + * The type of the renderer. + * + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.UNKNOWN; + + /** + * Measurements of the screen. (0, 0, screenWidth, screenHeight) + * + * Its safe to use as filterArea or hitArea for whole stage + * + * @member {PIXI.Rectangle} + */ + _this.screen = new _math.Rectangle(0, 0, screenWidth || 800, screenHeight || 600); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.view = options.view || document.createElement('canvas'); + + /** + * The resolution / device pixel ratio of the renderer + * + * @member {number} + * @default 1 + */ + _this.resolution = options.resolution || _settings2.default.RESOLUTION; + + /** + * Whether the render view is transparent + * + * @member {boolean} + */ + _this.transparent = options.transparent; + + /** + * Whether css dimensions of canvas view should be resized to screen dimensions automatically + * + * @member {boolean} + */ + _this.autoResize = options.autoResize || false; + + /** + * Tracks the blend modes useful for this renderer. + * + * @member {object} + */ + _this.blendModes = null; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent Pixi will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent Pixi will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example if + * your game has a canvas filling background image you often don't need this set. + * + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + * + * @member {boolean} + */ + _this.roundPixels = options.roundPixels; + + /** + * The background color as a number. + * + * @member {number} + * @private + */ + _this._backgroundColor = 0x000000; + + /** + * The background color as an [R, G, B] array. + * + * @member {number[]} + * @private + */ + _this._backgroundColorRgba = [0, 0, 0, 0]; + + /** + * The background color as a string. + * + * @member {string} + * @private + */ + _this._backgroundColorString = '#000000'; + + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + + /** + * This temporary display object used as the parent of the currently being rendered item + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._tempDisplayObjectParent = new _Container2.default(); + + /** + * The last root object that the renderer tried to render. + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._lastObjectRendered = _this._tempDisplayObjectParent; + return _this; + } + + /** + * Same as view.width, actual number of pixels in the canvas by horizontal + * + * @member {number} + * @readonly + * @default 800 + */ + + + /** + * Resizes the screen and canvas to the specified width and height + * Canvas dimensions are multiplied by resolution + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + SystemRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + this.screen.width = screenWidth; + this.screen.height = screenHeight; + + this.view.width = screenWidth * this.resolution; + this.view.height = screenHeight * this.resolution; + + if (this.autoResize) { + this.view.style.width = screenWidth + 'px'; + this.view.style.height = screenHeight + 'px'; + } + }; + + /** + * Useful function that returns a texture of the display object that can then be used to create sprites + * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. + * + * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from + * @param {number} scaleMode - Should be one of the scaleMode consts + * @param {number} resolution - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.Texture} a texture of the graphics object + */ + + + SystemRenderer.prototype.generateTexture = function generateTexture(displayObject, scaleMode, resolution) { + var bounds = displayObject.getLocalBounds(); + + var renderTexture = _RenderTexture2.default.create(bounds.width | 0, bounds.height | 0, scaleMode, resolution); + + tempMatrix.tx = -bounds.x; + tempMatrix.ty = -bounds.y; + + this.render(displayObject, renderTexture, false, tempMatrix, true); + + return renderTexture; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + SystemRenderer.prototype.destroy = function destroy(removeView) { + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } + + this.type = _const.RENDERER_TYPE.UNKNOWN; + + this.view = null; + + this.screen = null; + + this.resolution = 0; + + this.transparent = false; + + this.autoResize = false; + + this.blendModes = null; + + this.preserveDrawingBuffer = false; + this.clearBeforeRender = false; + + this.roundPixels = false; + + this._backgroundColor = 0; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + + this.backgroundColor = 0; + this._tempDisplayObjectParent = null; + this._lastObjectRendered = null; + }; + + /** + * The background color to fill if not transparent + * + * @member {number} + */ + + + _createClass(SystemRenderer, [{ + key: 'width', + get: function get() { + return this.view.width; + } + + /** + * Same as view.height, actual number of pixels in the canvas by vertical + * + * @member {number} + * @readonly + * @default 600 + */ + + }, { + key: 'height', + get: function get() { + return this.view.height; + } + }, { + key: 'backgroundColor', + get: function get() { + return this._backgroundColor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._backgroundColor = value; + this._backgroundColorString = (0, _utils.hex2string)(value); + (0, _utils.hex2rgb)(value, this._backgroundColorRgba); + } + }]); + + return SystemRenderer; +}(_eventemitter2.default); + +exports.default = SystemRenderer; + +},{"../const":44,"../display/Container":46,"../math":68,"../settings":99,"../textures/RenderTexture":110,"../utils":120,"eventemitter3":3}],75:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _CanvasMaskManager = require('./utils/CanvasMaskManager'); + +var _CanvasMaskManager2 = _interopRequireDefault(_CanvasMaskManager); + +var _CanvasRenderTarget = require('./utils/CanvasRenderTarget'); + +var _CanvasRenderTarget2 = _interopRequireDefault(_CanvasRenderTarget); + +var _mapCanvasBlendModesToPixi = require('./utils/mapCanvasBlendModesToPixi'); + +var _mapCanvasBlendModesToPixi2 = _interopRequireDefault(_mapCanvasBlendModesToPixi); + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should + * be used for browsers that do not support WebGL. Don't forget to add the CanvasRenderer.view to + * your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ +var CanvasRenderer = function (_SystemRenderer) { + _inherits(CanvasRenderer, _SystemRenderer); + + /** + * @param {number} [screenWidth=800] - the width of the screen + * @param {number} [screenHeight=600] - the height of the screen + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function CanvasRenderer(screenWidth, screenHeight) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + _classCallCheck(this, CanvasRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'Canvas', screenWidth, screenHeight, options)); + + _this.type = _const.RENDERER_TYPE.CANVAS; + + /** + * The canvas 2d context that everything is drawn with. + * + * @member {CanvasRenderingContext2D} + */ + _this.rootContext = _this.view.getContext('2d', { alpha: _this.transparent }); + + /** + * Boolean flag controlling canvas refresh. + * + * @member {boolean} + */ + _this.refresh = true; + + /** + * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. + * + * @member {PIXI.CanvasMaskManager} + */ + _this.maskManager = new _CanvasMaskManager2.default(_this); + + /** + * The canvas property used to set the canvas smoothing property. + * + * @member {string} + */ + _this.smoothProperty = 'imageSmoothingEnabled'; + + if (!_this.rootContext.imageSmoothingEnabled) { + if (_this.rootContext.webkitImageSmoothingEnabled) { + _this.smoothProperty = 'webkitImageSmoothingEnabled'; + } else if (_this.rootContext.mozImageSmoothingEnabled) { + _this.smoothProperty = 'mozImageSmoothingEnabled'; + } else if (_this.rootContext.oImageSmoothingEnabled) { + _this.smoothProperty = 'oImageSmoothingEnabled'; + } else if (_this.rootContext.msImageSmoothingEnabled) { + _this.smoothProperty = 'msImageSmoothingEnabled'; + } + } + + _this.initPlugins(); + + _this.blendModes = (0, _mapCanvasBlendModesToPixi2.default)(); + _this._activeBlendMode = null; + + _this.context = null; + _this.renderingToScreen = false; + + _this.resize(screenWidth, screenHeight); + return _this; + } + + /** + * Renders the object to this canvas view + * + * @param {PIXI.DisplayObject} displayObject - The object to be rendered + * @param {PIXI.RenderTexture} [renderTexture] - A render texture to be rendered to. + * If unset, it will render to the root context. + * @param {boolean} [clear=false] - Whether to clear the canvas before drawing + * @param {PIXI.Transform} [transform] - A transformation to be applied + * @param {boolean} [skipUpdateTransform=false] - Whether to skip the update transform + */ + + + CanvasRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!this.view) { + return; + } + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + var rootResolution = this.resolution; + + if (renderTexture) { + renderTexture = renderTexture.baseTexture || renderTexture; + + if (!renderTexture._canvasRenderTarget) { + renderTexture._canvasRenderTarget = new _CanvasRenderTarget2.default(renderTexture.width, renderTexture.height, renderTexture.resolution); + renderTexture.source = renderTexture._canvasRenderTarget.canvas; + renderTexture.valid = true; + } + + this.context = renderTexture._canvasRenderTarget.context; + this.resolution = renderTexture._canvasRenderTarget.resolution; + } else { + this.context = this.rootContext; + } + + var context = this.context; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + var tempWt = this._tempDisplayObjectParent.transform.worldTransform; + + if (transform) { + transform.copy(tempWt); + + // lets not forget to flag the parent transform as dirty... + this._tempDisplayObjectParent.transform._worldID = -1; + } else { + tempWt.identity(); + } + + displayObject.parent = this._tempDisplayObjectParent; + + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + context.setTransform(1, 0, 0, 1, 0, 0); + context.globalAlpha = 1; + context.globalCompositeOperation = this.blendModes[_const.BLEND_MODES.NORMAL]; + + if (navigator.isCocoonJS && this.view.screencanvas) { + context.fillStyle = 'black'; + context.clear(); + } + + if (clear !== undefined ? clear : this.clearBeforeRender) { + if (this.renderingToScreen) { + if (this.transparent) { + context.clearRect(0, 0, this.width, this.height); + } else { + context.fillStyle = this._backgroundColorString; + context.fillRect(0, 0, this.width, this.height); + } + } // else { + // TODO: implement background for CanvasRenderTarget or RenderTexture? + // } + } + + // TODO RENDER TARGET STUFF HERE.. + var tempContext = this.context; + + this.context = context; + displayObject.renderCanvas(this); + this.context = tempContext; + + this.resolution = rootResolution; + + this.emit('postrender'); + }; + + /** + * Clear the canvas of renderer. + * + * @param {string} [clearColor] - Clear the canvas with this color, except the canvas is transparent. + */ + + + CanvasRenderer.prototype.clear = function clear(clearColor) { + var context = this.context; + + clearColor = clearColor || this._backgroundColorString; + + if (!this.transparent && clearColor) { + context.fillStyle = clearColor; + context.fillRect(0, 0, this.width, this.height); + } else { + context.clearRect(0, 0, this.width, this.height); + } + }; + + /** + * Sets the blend mode of the renderer. + * + * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values. + */ + + + CanvasRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + if (this._activeBlendMode === blendMode) { + return; + } + + this._activeBlendMode = blendMode; + this.context.globalCompositeOperation = this.blendModes[blendMode]; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + CanvasRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // call the base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.context = null; + + this.refresh = true; + + this.maskManager.destroy(); + this.maskManager = null; + + this.smoothProperty = null; + }; + + /** + * Resizes the canvas view to the specified width and height. + * + * @extends PIXI.SystemRenderer#resize + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + CanvasRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + _SystemRenderer.prototype.resize.call(this, screenWidth, screenHeight); + + // reset the scale mode.. oddly this seems to be reset when the canvas is resized. + // surely a browser bug?? Let pixi fix that for you.. + if (this.smoothProperty) { + this.rootContext[this.smoothProperty] = _settings2.default.SCALE_MODE === _const.SCALE_MODES.LINEAR; + } + }; + + return CanvasRenderer; +}(_SystemRenderer3.default); + +exports.default = CanvasRenderer; + + +_utils.pluginTarget.mixin(CanvasRenderer); + +},{"../../const":44,"../../settings":99,"../../utils":120,"../SystemRenderer":74,"./utils/CanvasMaskManager":76,"./utils/CanvasRenderTarget":77,"./utils/mapCanvasBlendModesToPixi":79}],76:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A set of functions used to handle masking. + * + * @class + * @memberof PIXI + */ +var CanvasMaskManager = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + function CanvasMaskManager(renderer) { + _classCallCheck(this, CanvasMaskManager); + + this.renderer = renderer; + } + + /** + * This method adds it to the current stack of masks. + * + * @param {object} maskData - the maskData that will be pushed + */ + + + CanvasMaskManager.prototype.pushMask = function pushMask(maskData) { + var renderer = this.renderer; + + renderer.context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.transform.worldTransform; + var resolution = renderer.resolution; + + renderer.context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // TODO suport sprite alpha masks?? + // lots of effort required. If demand is great enough.. + if (!maskData._texture) { + this.renderGraphicsShape(maskData); + renderer.context.clip(); + } + + maskData.worldAlpha = cacheAlpha; + }; + + /** + * Renders a PIXI.Graphics shape. + * + * @param {PIXI.Graphics} graphics - The object to render. + */ + + + CanvasMaskManager.prototype.renderGraphicsShape = function renderGraphicsShape(graphics) { + var context = this.renderer.context; + var len = graphics.graphicsData.length; + + if (len === 0) { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === _const.SHAPES.POLY) { + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; j++) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) { + context.closePath(); + } + } else if (data.type === _const.SHAPES.RECT) { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } + }; + + /** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @param {PIXI.CanvasRenderer} renderer - The renderer context to use. + */ + + + CanvasMaskManager.prototype.popMask = function popMask(renderer) { + renderer.context.restore(); + }; + + /** + * Destroys this canvas mask manager. + * + */ + + + CanvasMaskManager.prototype.destroy = function destroy() { + /* empty */ + }; + + return CanvasMaskManager; +}(); + +exports.default = CanvasMaskManager; + +},{"../../../const":44}],77:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Creates a Canvas element of the given size. + * + * @class + * @memberof PIXI + */ +var CanvasRenderTarget = function () { + /** + * @param {number} width - the width for the newly created canvas + * @param {number} height - the height for the newly created canvas + * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + _classCallCheck(this, CanvasRenderTarget); + + /** + * The Canvas object that belongs to this CanvasRenderTarget. + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @member {CanvasRenderingContext2D} + */ + this.context = this.canvas.getContext('2d'); + + this.resolution = resolution || _settings2.default.RESOLUTION; + + this.resize(width, height); + } + + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * + * @private + */ + + + CanvasRenderTarget.prototype.clear = function clear() { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + + /** + * Resizes the canvas to the specified width and height. + * + * @param {number} width - the new width of the canvas + * @param {number} height - the new height of the canvas + */ + + + CanvasRenderTarget.prototype.resize = function resize(width, height) { + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; + }; + + /** + * Destroys this canvas. + * + */ + + + CanvasRenderTarget.prototype.destroy = function destroy() { + this.context = null; + this.canvas = null; + }; + + /** + * The width of the canvas buffer in pixels. + * + * @member {number} + */ + + + _createClass(CanvasRenderTarget, [{ + key: 'width', + get: function get() { + return this.canvas.width; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.width = val; + } + + /** + * The height of the canvas buffer in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.canvas.height; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.height = val; + } + }]); + + return CanvasRenderTarget; +}(); + +exports.default = CanvasRenderTarget; + +},{"../../../settings":99}],78:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = canUseNewCanvasBlendModes; +/** + * Creates a little colored canvas + * + * @ignore + * @param {string} color - The color to make the canvas + * @return {canvas} a small canvas element + */ +function createColoredCanvas(color) { + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.fillStyle = color; + context.fillRect(0, 0, 6, 1); + + return canvas; +} + +/** + * Checks whether the Canvas BlendModes are supported by the current browser + * + * @return {boolean} whether they are supported + */ +function canUseNewCanvasBlendModes() { + if (typeof document === 'undefined') { + return false; + } + + var magenta = createColoredCanvas('#ff00ff'); + var yellow = createColoredCanvas('#ffff00'); + + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.globalCompositeOperation = 'multiply'; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + var imageData = context.getImageData(2, 0, 1, 1); + + if (!imageData) { + return false; + } + + var data = imageData.data; + + return data[0] === 255 && data[1] === 0 && data[2] === 0; +} + +},{}],79:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapCanvasBlendModesToPixi; + +var _const = require('../../../const'); + +var _canUseNewCanvasBlendModes = require('./canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Maps blend combinations to Canvas. + * + * @memberof PIXI + * @function mapCanvasBlendModesToPixi + * @private + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapCanvasBlendModesToPixi() { + var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + + if ((0, _canUseNewCanvasBlendModes2.default)()) { + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'multiply'; + array[_const.BLEND_MODES.SCREEN] = 'screen'; + array[_const.BLEND_MODES.OVERLAY] = 'overlay'; + array[_const.BLEND_MODES.DARKEN] = 'darken'; + array[_const.BLEND_MODES.LIGHTEN] = 'lighten'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'color-dodge'; + array[_const.BLEND_MODES.COLOR_BURN] = 'color-burn'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'hard-light'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'soft-light'; + array[_const.BLEND_MODES.DIFFERENCE] = 'difference'; + array[_const.BLEND_MODES.EXCLUSION] = 'exclusion'; + array[_const.BLEND_MODES.HUE] = 'hue'; + array[_const.BLEND_MODES.SATURATION] = 'saturate'; + array[_const.BLEND_MODES.COLOR] = 'color'; + array[_const.BLEND_MODES.LUMINOSITY] = 'luminosity'; + } else { + // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'source-over'; + array[_const.BLEND_MODES.SCREEN] = 'source-over'; + array[_const.BLEND_MODES.OVERLAY] = 'source-over'; + array[_const.BLEND_MODES.DARKEN] = 'source-over'; + array[_const.BLEND_MODES.LIGHTEN] = 'source-over'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'source-over'; + array[_const.BLEND_MODES.COLOR_BURN] = 'source-over'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.DIFFERENCE] = 'source-over'; + array[_const.BLEND_MODES.EXCLUSION] = 'source-over'; + array[_const.BLEND_MODES.HUE] = 'source-over'; + array[_const.BLEND_MODES.SATURATION] = 'source-over'; + array[_const.BLEND_MODES.COLOR] = 'source-over'; + array[_const.BLEND_MODES.LUMINOSITY] = 'source-over'; + } + + return array; +} + +},{"../../../const":44,"./canUseNewCanvasBlendModes":78}],80:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged + * up with textures that are no longer being used. + * + * @class + * @memberof PIXI + */ +var TextureGarbageCollector = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function TextureGarbageCollector(renderer) { + _classCallCheck(this, TextureGarbageCollector); + + this.renderer = renderer; + + this.count = 0; + this.checkCount = 0; + this.maxIdle = _settings2.default.GC_MAX_IDLE; + this.checkCountMax = _settings2.default.GC_MAX_CHECK_COUNT; + this.mode = _settings2.default.GC_MODE; + } + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.update = function update() { + this.count++; + + if (this.mode === _const.GC_MODES.MANUAL) { + return; + } + + this.checkCount++; + + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + + this.run(); + } + }; + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.run = function run() { + var tm = this.renderer.textureManager; + var managedTextures = tm._managedTextures; + var wasRemoved = false; + + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + + // only supports non generated textures at the moment! + if (!texture._glRenderTargets && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + + if (wasRemoved) { + var j = 0; + + for (var _i = 0; _i < managedTextures.length; _i++) { + if (managedTextures[_i] !== null) { + managedTextures[j++] = managedTextures[_i]; + } + } + + managedTextures.length = j; + } + }; + + /** + * Removes all the textures within the specified displayObject and its children from the GPU + * + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + */ + + + TextureGarbageCollector.prototype.unload = function unload(displayObject) { + var tm = this.renderer.textureManager; + + // only destroy non generated textures + if (displayObject._texture && displayObject._texture._glRenderTargets) { + tm.destroyTexture(displayObject._texture, true); + } + + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + + return TextureGarbageCollector; +}(); + +exports.default = TextureGarbageCollector; + +},{"../../const":44,"../../settings":99}],81:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _const = require('../../const'); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _utils = require('../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a webGL Texture + * + * @class + * @memberof PIXI + */ +var TextureManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function TextureManager(renderer) { + _classCallCheck(this, TextureManager); + + /** + * A reference to the current renderer + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = renderer.gl; + + /** + * Track textures in the renderer so we can no longer listen to them on destruction. + * + * @member {Array<*>} + * @private + */ + this._managedTextures = []; + } + + /** + * Binds a texture. + * + */ + + + TextureManager.prototype.bindTexture = function bindTexture() {} + // empty + + + /** + * Gets a texture. + * + */ + ; + + TextureManager.prototype.getTexture = function getTexture() {} + // empty + + + /** + * Updates and/or Creates a WebGL texture for the renderer's context. + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update + * @param {number} location - the location the texture will be bound to. + * @return {GLTexture} The gl texture. + */ + ; + + TextureManager.prototype.updateTexture = function updateTexture(texture, location) { + // assume it good! + // texture = texture.baseTexture || texture; + + var gl = this.gl; + + var isRenderTexture = !!texture._glRenderTargets; + + if (!texture.hasLoaded) { + return null; + } + + var boundTextures = this.renderer.boundTextures; + + // if the location is undefined then this may have been called by n event. + // this being the case the texture may already be bound to a slot. As a texture can only be bound once + // we need to find its current location if it exists. + if (location === undefined) { + location = 0; + + // TODO maybe we can use texture bound ids later on... + // check if texture is already bound.. + for (var i = 0; i < boundTextures.length; ++i) { + if (boundTextures[i] === texture) { + location = i; + break; + } + } + } + + boundTextures[location] = texture; + + gl.activeTexture(gl.TEXTURE0 + location); + + var glTexture = texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!glTexture) { + if (isRenderTexture) { + var renderTarget = new _RenderTarget2.default(this.gl, texture.width, texture.height, texture.scaleMode, texture.resolution); + + renderTarget.resize(texture.width, texture.height); + texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget; + glTexture = renderTarget.texture; + } else { + glTexture = new _pixiGlCore.GLTexture(this.gl, null, null, null, null); + glTexture.bind(location); + glTexture.premultiplyAlpha = true; + glTexture.upload(texture.source); + } + + texture._glTextures[this.renderer.CONTEXT_UID] = glTexture; + + texture.on('update', this.updateTexture, this); + texture.on('dispose', this.destroyTexture, this); + + this._managedTextures.push(texture); + + if (texture.isPowerOfTwo) { + if (texture.mipmap) { + glTexture.enableMipmap(); + } + + if (texture.wrapMode === _const.WRAP_MODES.CLAMP) { + glTexture.enableWrapClamp(); + } else if (texture.wrapMode === _const.WRAP_MODES.REPEAT) { + glTexture.enableWrapRepeat(); + } else { + glTexture.enableWrapMirrorRepeat(); + } + } else { + glTexture.enableWrapClamp(); + } + + if (texture.scaleMode === _const.SCALE_MODES.NEAREST) { + glTexture.enableNearestScaling(); + } else { + glTexture.enableLinearScaling(); + } + } + // the texture already exists so we only need to update it.. + else if (isRenderTexture) { + texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height); + } else { + glTexture.upload(texture.source); + } + + return glTexture; + }; + + /** + * Deletes the texture from WebGL + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy + * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. + */ + + + TextureManager.prototype.destroyTexture = function destroyTexture(texture, skipRemove) { + texture = texture.baseTexture || texture; + + if (!texture.hasLoaded) { + return; + } + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + this.renderer.unbindTexture(texture); + + texture._glTextures[this.renderer.CONTEXT_UID].destroy(); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + + delete texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!skipRemove) { + var i = this._managedTextures.indexOf(texture); + + if (i !== -1) { + (0, _utils.removeItems)(this._managedTextures, i, 1); + } + } + } + }; + + /** + * Deletes all the textures from WebGL + */ + + + TextureManager.prototype.removeAll = function removeAll() { + // empty all the old gl textures as they are useless now + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + delete texture._glTextures[this.renderer.CONTEXT_UID]; + } + } + }; + + /** + * Destroys this manager and removes all its textures + */ + + + TextureManager.prototype.destroy = function destroy() { + // destroy managed textures + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + this.destroyTexture(texture, true); + + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + } + + this._managedTextures = null; + }; + + return TextureManager; +}(); + +exports.default = TextureManager; + +},{"../../const":44,"../../utils":120,"./utils/RenderTarget":94,"pixi-gl-core":12}],82:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _MaskManager = require('./managers/MaskManager'); + +var _MaskManager2 = _interopRequireDefault(_MaskManager); + +var _StencilManager = require('./managers/StencilManager'); + +var _StencilManager2 = _interopRequireDefault(_StencilManager); + +var _FilterManager = require('./managers/FilterManager'); + +var _FilterManager2 = _interopRequireDefault(_FilterManager); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _ObjectRenderer = require('./utils/ObjectRenderer'); + +var _ObjectRenderer2 = _interopRequireDefault(_ObjectRenderer); + +var _TextureManager = require('./TextureManager'); + +var _TextureManager2 = _interopRequireDefault(_TextureManager); + +var _BaseTexture = require('../../textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _TextureGarbageCollector = require('./TextureGarbageCollector'); + +var _TextureGarbageCollector2 = _interopRequireDefault(_TextureGarbageCollector); + +var _WebGLState = require('./WebGLState'); + +var _WebGLState2 = _interopRequireDefault(_WebGLState); + +var _mapWebGLDrawModesToPixi = require('./utils/mapWebGLDrawModesToPixi'); + +var _mapWebGLDrawModesToPixi2 = _interopRequireDefault(_mapWebGLDrawModesToPixi); + +var _validateContext = require('./utils/validateContext'); + +var _validateContext2 = _interopRequireDefault(_validateContext); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CONTEXT_UID = 0; + +/** + * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ + +var WebGLRenderer = function (_SystemRenderer) { + _inherits(WebGLRenderer, _SystemRenderer); + + /** + * + * @param {number} [screenWidth=800] - the width of the screen + * @param {number} [screenHeight=600] - the height of the screen + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias. If not available natively then FXAA + * antialiasing is used + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. + * The resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear + * the canvas or not before the new render pass. If you wish to set this to false, you *must* set + * preserveDrawingBuffer to `true`. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when + * rendering, stopping pixel interpolation. + * @param {boolean} [options.legacy=false] - If true Pixi will aim to ensure compatibility + * with older / less advanced devices. If you experiance unexplained flickering try setting this to true. + */ + function WebGLRenderer(screenWidth, screenHeight) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + _classCallCheck(this, WebGLRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'WebGL', screenWidth, screenHeight, options)); + + _this.legacy = !!options.legacy; + + if (_this.legacy) { + _pixiGlCore2.default.VertexArrayObject.FORCE_NATIVE = true; + } + + /** + * The type of this renderer as a standardised const + * + * @member {number} + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.WEBGL; + + _this.handleContextLost = _this.handleContextLost.bind(_this); + _this.handleContextRestored = _this.handleContextRestored.bind(_this); + + _this.view.addEventListener('webglcontextlost', _this.handleContextLost, false); + _this.view.addEventListener('webglcontextrestored', _this.handleContextRestored, false); + + /** + * The options passed in to create a new webgl context. + * + * @member {object} + * @private + */ + _this._contextOptions = { + alpha: _this.transparent, + antialias: options.antialias, + premultipliedAlpha: _this.transparent && _this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: options.preserveDrawingBuffer + }; + + _this._backgroundColorRgba[3] = _this.transparent ? 0 : 1; + + /** + * Manages the masks using the stencil buffer. + * + * @member {PIXI.MaskManager} + */ + _this.maskManager = new _MaskManager2.default(_this); + + /** + * Manages the stencil buffer. + * + * @member {PIXI.StencilManager} + */ + _this.stencilManager = new _StencilManager2.default(_this); + + /** + * An empty renderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.emptyRenderer = new _ObjectRenderer2.default(_this); + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.currentRenderer = _this.emptyRenderer; + + _this.initPlugins(); + + /** + * The current WebGL rendering context, it is created here + * + * @member {WebGLRenderingContext} + */ + // initialize the context so it is ready for the managers. + if (options.context) { + // checks to see if a context is valid.. + (0, _validateContext2.default)(options.context); + } + + _this.gl = options.context || _pixiGlCore2.default.createContext(_this.view, _this._contextOptions); + + _this.CONTEXT_UID = CONTEXT_UID++; + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.WebGLState} + */ + _this.state = new _WebGLState2.default(_this.gl); + + _this.renderingToScreen = true; + + /** + * Holds the current state of textures bound to the GPU. + * @type {Array} + */ + _this.boundTextures = null; + + /** + * Holds the current shader + * + * @member {PIXI.Shader} + */ + _this._activeShader = null; + + _this._activeVao = null; + + /** + * Holds the current render target + * + * @member {PIXI.RenderTarget} + */ + _this._activeRenderTarget = null; + + _this._initContext(); + + /** + * Manages the filters. + * + * @member {PIXI.FilterManager} + */ + _this.filterManager = new _FilterManager2.default(_this); + // map some webGL blend and drawmodes.. + _this.drawModes = (0, _mapWebGLDrawModesToPixi2.default)(_this.gl); + + _this._nextTextureLocation = 0; + + _this.setBlendMode(0); + return _this; + } + + /** + * Creates the WebGL context + * + * @private + */ + + + WebGLRenderer.prototype._initContext = function _initContext() { + var gl = this.gl; + + // restore a context if it was previously lost + if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').restoreContext(); + } + + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + + this.boundTextures = new Array(maxTextures); + this.emptyTextures = new Array(maxTextures); + + // create a texture manager... + this.textureManager = new _TextureManager2.default(this); + this.textureGC = new _TextureGarbageCollector2.default(this); + + this.state.resetToDefault(); + + this.rootRenderTarget = new _RenderTarget2.default(gl, this.width, this.height, null, this.resolution, true); + this.rootRenderTarget.clearColor = this._backgroundColorRgba; + + this.bindRenderTarget(this.rootRenderTarget); + + // now lets fill up the textures with empty ones! + var emptyGLTexture = new _pixiGlCore2.default.GLTexture.fromData(gl, null, 1, 1); + + var tempObj = { _glTextures: {} }; + + tempObj._glTextures[this.CONTEXT_UID] = {}; + + for (var i = 0; i < maxTextures; i++) { + var empty = new _BaseTexture2.default(); + + empty._glTextures[this.CONTEXT_UID] = emptyGLTexture; + + this.boundTextures[i] = tempObj; + this.emptyTextures[i] = empty; + this.bindTexture(null, i); + } + + this.emit('context', gl); + + // setup the width/height properties and gl viewport + this.resize(this.screen.width, this.screen.height); + }; + + /** + * Renders the object to its webGL view + * + * @param {PIXI.DisplayObject} displayObject - the object to be rendered + * @param {PIXI.RenderTexture} renderTexture - The render texture to render to. + * @param {boolean} [clear] - Should the canvas be cleared before the new render + * @param {PIXI.Transform} [transform] - A transform to apply to the render texture before rendering. + * @param {boolean} [skipUpdateTransform] - Should we skip the update transform pass? + */ + + + WebGLRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + // no point rendering if our context has been blown up! + if (!this.gl || this.gl.isContextLost()) { + return; + } + + this._nextTextureLocation = 0; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + this.bindRenderTexture(renderTexture, transform); + + this.currentRenderer.start(); + + if (clear !== undefined ? clear : this.clearBeforeRender) { + this._activeRenderTarget.clear(); + } + + displayObject.renderWebGL(this); + + // apply transform.. + this.currentRenderer.flush(); + + // this.setObjectRenderer(this.emptyRenderer); + + this.textureGC.update(); + + this.emit('postrender'); + }; + + /** + * Changes the current renderer to the one given in parameter + * + * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. + */ + + + WebGLRenderer.prototype.setObjectRenderer = function setObjectRenderer(objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; + + /** + * This should be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + * + */ + + + WebGLRenderer.prototype.flush = function flush() { + this.setObjectRenderer(this.emptyRenderer); + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + WebGLRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + // if(width * this.resolution === this.width && height * this.resolution === this.height)return; + + _SystemRenderer3.default.prototype.resize.call(this, screenWidth, screenHeight); + + this.rootRenderTarget.resize(screenWidth, screenHeight); + + if (this._activeRenderTarget === this.rootRenderTarget) { + this.rootRenderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true); + } + } + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} blendMode - the desired blend mode + */ + + + WebGLRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + this.state.setBlendMode(blendMode); + }; + + /** + * Erases the active render target and fills the drawing area with a colour + * + * @param {number} [clearColor] - The colour + */ + + + WebGLRenderer.prototype.clear = function clear(clearColor) { + this._activeRenderTarget.clear(clearColor); + }; + + /** + * Sets the transform of the active render target to the given matrix + * + * @param {PIXI.Matrix} matrix - The transformation matrix + */ + + + WebGLRenderer.prototype.setTransform = function setTransform(matrix) { + this._activeRenderTarget.transform = matrix; + }; + + /** + * Erases the render texture and fills the drawing area with a colour + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to clear + * @param {number} [clearColor] - The colour + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.clearRenderTexture = function clearRenderTexture(renderTexture, clearColor) { + var baseTexture = renderTexture.baseTexture; + var renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + + if (renderTarget) { + renderTarget.clear(clearColor); + } + + return this; + }; + + /** + * Binds a render texture for rendering + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to render + * @param {PIXI.Transform} transform - The transform to be applied to the render texture + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTexture = function bindRenderTexture(renderTexture, transform) { + var renderTarget = void 0; + + if (renderTexture) { + var baseTexture = renderTexture.baseTexture; + + if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) { + // bind the current texture + this.textureManager.updateTexture(baseTexture, 0); + } + + this.unbindTexture(baseTexture); + + renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + renderTarget.setFrame(renderTexture.frame); + } else { + renderTarget = this.rootRenderTarget; + } + + renderTarget.transform = transform; + this.bindRenderTarget(renderTarget); + + return this; + }; + + /** + * Changes the current render target to the one given in parameter + * + * @param {PIXI.RenderTarget} renderTarget - the new render target + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTarget = function bindRenderTarget(renderTarget) { + if (renderTarget !== this._activeRenderTarget) { + this._activeRenderTarget = renderTarget; + renderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true); + } + + this.stencilManager.setMaskStack(renderTarget.stencilMaskStack); + } + + return this; + }; + + /** + * Changes the current shader to the one given in parameter + * + * @param {PIXI.Shader} shader - the new shader + * @param {boolean} [autoProject=true] - Whether automatically set the projection matrix + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindShader = function bindShader(shader, autoProject) { + // TODO cache + if (this._activeShader !== shader) { + this._activeShader = shader; + shader.bind(); + + // `autoProject` normally would be a default parameter set to true + // but because of how Babel transpiles default parameters + // it hinders the performance of this method. + if (autoProject !== false) { + // automatically set the projection matrix + shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(true); + } + } + + return this; + }; + + /** + * Binds the texture. This will return the location of the bound texture. + * It may not be the same as the one you pass in. This is due to optimisation that prevents + * needless binding of textures. For example if the texture is already bound it will return the + * current location of the texture instead of the one provided. To bypass this use force location + * + * @param {PIXI.Texture} texture - the new texture + * @param {number} location - the suggested texture location + * @param {boolean} forceLocation - force the location + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindTexture = function bindTexture(texture, location, forceLocation) { + texture = texture || this.emptyTextures[location]; + texture = texture.baseTexture || texture; + texture.touched = this.textureGC.count; + + if (!forceLocation) { + // TODO - maybe look into adding boundIds.. save us the loop? + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + return i; + } + } + + if (location === undefined) { + this._nextTextureLocation++; + this._nextTextureLocation %= this.boundTextures.length; + location = this.boundTextures.length - this._nextTextureLocation - 1; + } + } else { + location = location || 0; + } + + var gl = this.gl; + var glTexture = texture._glTextures[this.CONTEXT_UID]; + + if (!glTexture) { + // this will also bind the texture.. + this.textureManager.updateTexture(texture, location); + } else { + // bind the current texture + this.boundTextures[location] = texture; + gl.activeTexture(gl.TEXTURE0 + location); + gl.bindTexture(gl.TEXTURE_2D, glTexture.texture); + } + + return location; + }; + + /** + * unbinds the texture ... + * + * @param {PIXI.Texture} texture - the texture to unbind + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.unbindTexture = function unbindTexture(texture) { + var gl = this.gl; + + texture = texture.baseTexture || texture; + + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + this.boundTextures[i] = this.emptyTextures[i]; + + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[i]._glTextures[this.CONTEXT_UID].texture); + } + } + + return this; + }; + + /** + * Creates a new VAO from this renderer's context and state. + * + * @return {VertexArrayObject} The new VAO. + */ + + + WebGLRenderer.prototype.createVao = function createVao() { + return new _pixiGlCore2.default.VertexArrayObject(this.gl, this.state.attribState); + }; + + /** + * Changes the current Vao to the one given in parameter + * + * @param {PIXI.VertexArrayObject} vao - the new Vao + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindVao = function bindVao(vao) { + if (this._activeVao === vao) { + return this; + } + + if (vao) { + vao.bind(); + } else if (this._activeVao) { + // TODO this should always be true i think? + this._activeVao.unbind(); + } + + this._activeVao = vao; + + return this; + }; + + /** + * Resets the WebGL state so you can render things however you fancy! + * + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.reset = function reset() { + this.setObjectRenderer(this.emptyRenderer); + + this._activeShader = null; + this._activeRenderTarget = this.rootRenderTarget; + + // bind the main frame buffer (the screen); + this.rootRenderTarget.activate(); + + this.state.resetToDefault(); + + return this; + }; + + /** + * Handles a lost webgl context + * + * @private + * @param {WebGLContextEvent} event - The context lost event. + */ + + + WebGLRenderer.prototype.handleContextLost = function handleContextLost(event) { + event.preventDefault(); + }; + + /** + * Handles a restored webgl context + * + * @private + */ + + + WebGLRenderer.prototype.handleContextRestored = function handleContextRestored() { + this._initContext(); + this.textureManager.removeAll(); + }; + + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + + + WebGLRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // remove listeners + this.view.removeEventListener('webglcontextlost', this.handleContextLost); + this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); + + this.textureManager.destroy(); + + // call base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.uid = 0; + + // destroy the managers + this.maskManager.destroy(); + this.stencilManager.destroy(); + this.filterManager.destroy(); + + this.maskManager = null; + this.filterManager = null; + this.textureManager = null; + this.currentRenderer = null; + + this.handleContextLost = null; + this.handleContextRestored = null; + + this._contextOptions = null; + this.gl.useProgram(null); + + if (this.gl.getExtension('WEBGL_lose_context')) { + this.gl.getExtension('WEBGL_lose_context').loseContext(); + } + + this.gl = null; + + // this = null; + }; + + return WebGLRenderer; +}(_SystemRenderer3.default); + +exports.default = WebGLRenderer; + + +_utils.pluginTarget.mixin(WebGLRenderer); + +},{"../../const":44,"../../textures/BaseTexture":109,"../../utils":120,"../SystemRenderer":74,"./TextureGarbageCollector":80,"./TextureManager":81,"./WebGLState":83,"./managers/FilterManager":88,"./managers/MaskManager":89,"./managers/StencilManager":90,"./utils/ObjectRenderer":92,"./utils/RenderTarget":94,"./utils/mapWebGLDrawModesToPixi":97,"./utils/validateContext":98,"pixi-gl-core":12}],83:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); + +var _mapWebGLBlendModesToPixi2 = _interopRequireDefault(_mapWebGLBlendModesToPixi); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var BLEND = 0; +var DEPTH_TEST = 1; +var FRONT_FACE = 2; +var CULL_FACE = 3; +var BLEND_FUNC = 4; + +/** + * A WebGL state machines + * + * @memberof PIXI + * @class + */ + +var WebGLState = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + */ + function WebGLState(gl) { + _classCallCheck(this, WebGLState); + + /** + * The current active state + * + * @member {Uint8Array} + */ + this.activeState = new Uint8Array(16); + + /** + * The default state + * + * @member {Uint8Array} + */ + this.defaultState = new Uint8Array(16); + + // default blend mode.. + this.defaultState[0] = 1; + + /** + * The current state index in the stack + * + * @member {number} + * @private + */ + this.stackIndex = 0; + + /** + * The stack holding all the different states + * + * @member {Array<*>} + * @private + */ + this.stack = []; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + this.attribState = { + tempAttribState: new Array(this.maxAttribs), + attribState: new Array(this.maxAttribs) + }; + + this.blendModes = (0, _mapWebGLBlendModesToPixi2.default)(gl); + + // check we have vao.. + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || gl.getExtension('MOZ_OES_vertex_array_object') || gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + /** + * Pushes a new active state + */ + + + WebGLState.prototype.push = function push() { + // next state.. + var state = this.stack[this.stackIndex]; + + if (!state) { + state = this.stack[this.stackIndex] = new Uint8Array(16); + } + + ++this.stackIndex; + + // copy state.. + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) { + state[i] = this.activeState[i]; + } + }; + + /** + * Pops a state out + */ + + + WebGLState.prototype.pop = function pop() { + var state = this.stack[--this.stackIndex]; + + this.setState(state); + }; + + /** + * Sets the current state + * + * @param {*} state - The state to set. + */ + + + WebGLState.prototype.setState = function setState(state) { + this.setBlend(state[BLEND]); + this.setDepthTest(state[DEPTH_TEST]); + this.setFrontFace(state[FRONT_FACE]); + this.setCullFace(state[CULL_FACE]); + this.setBlendMode(state[BLEND_FUNC]); + }; + + /** + * Enables or disabled blending. + * + * @param {boolean} value - Turn on or off webgl blending. + */ + + + WebGLState.prototype.setBlend = function setBlend(value) { + value = value ? 1 : 0; + + if (this.activeState[BLEND] === value) { + return; + } + + this.activeState[BLEND] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + }; + + /** + * Sets the blend mode. + * + * @param {number} value - The blend mode to set to. + */ + + + WebGLState.prototype.setBlendMode = function setBlendMode(value) { + if (value === this.activeState[BLEND_FUNC]) { + return; + } + + this.activeState[BLEND_FUNC] = value; + + this.gl.blendFunc(this.blendModes[value][0], this.blendModes[value][1]); + }; + + /** + * Sets whether to enable or disable depth test. + * + * @param {boolean} value - Turn on or off webgl depth testing. + */ + + + WebGLState.prototype.setDepthTest = function setDepthTest(value) { + value = value ? 1 : 0; + + if (this.activeState[DEPTH_TEST] === value) { + return; + } + + this.activeState[DEPTH_TEST] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + }; + + /** + * Sets whether to enable or disable cull face. + * + * @param {boolean} value - Turn on or off webgl cull face. + */ + + + WebGLState.prototype.setCullFace = function setCullFace(value) { + value = value ? 1 : 0; + + if (this.activeState[CULL_FACE] === value) { + return; + } + + this.activeState[CULL_FACE] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + }; + + /** + * Sets the gl front face. + * + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ + + + WebGLState.prototype.setFrontFace = function setFrontFace(value) { + value = value ? 1 : 0; + + if (this.activeState[FRONT_FACE] === value) { + return; + } + + this.activeState[FRONT_FACE] = value; + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); + }; + + /** + * Disables all the vaos in use + * + */ + + + WebGLState.prototype.resetAttributes = function resetAttributes() { + for (var i = 0; i < this.attribState.tempAttribState.length; i++) { + this.attribState.tempAttribState[i] = 0; + } + + for (var _i = 0; _i < this.attribState.attribState.length; _i++) { + this.attribState.attribState[_i] = 0; + } + + // im going to assume one is always active for performance reasons. + for (var _i2 = 1; _i2 < this.maxAttribs; _i2++) { + this.gl.disableVertexAttribArray(_i2); + } + }; + + // used + /** + * Resets all the logic and disables the vaos + */ + + + WebGLState.prototype.resetToDefault = function resetToDefault() { + // unbind any VAO if they exist.. + if (this.nativeVaoExtension) { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + // reset all attributes.. + this.resetAttributes(); + + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; ++i) { + this.activeState[i] = 32; + } + + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + + this.setState(this.defaultState); + }; + + return WebGLState; +}(); + +exports.default = WebGLState; + +},{"./utils/mapWebGLBlendModesToPixi":96}],84:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _extractUniformsFromSrc = require('./extractUniformsFromSrc'); + +var _extractUniformsFromSrc2 = _interopRequireDefault(_extractUniformsFromSrc); + +var _utils = require('../../../utils'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SOURCE_KEY_MAP = {}; + +// let math = require('../../../math'); +/** + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ + +var Filter = function () { + /** + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. + */ + function Filter(vertexSrc, fragmentSrc, uniforms) { + _classCallCheck(this, Filter); + + /** + * The vertex shader. + * + * @member {string} + */ + this.vertexSrc = vertexSrc || Filter.defaultVertexSrc; + + /** + * The fragment shader. + * + * @member {string} + */ + this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc; + + this.blendMode = _const.BLEND_MODES.NORMAL; + + this.uniformData = uniforms || (0, _extractUniformsFromSrc2.default)(this.vertexSrc, this.fragmentSrc, 'projectionMatrix|uSampler'); + + /** + * An object containing the current values of custom uniforms. + * @example Updating the value of a custom uniform + * filter.uniforms.time = performance.now(); + * + * @member {object} + */ + this.uniforms = {}; + + for (var i in this.uniformData) { + this.uniforms[i] = this.uniformData[i].value; + } + + // this is where we store shader references.. + // TODO we could cache this! + this.glShaders = {}; + + // used for cacheing.. sure there is a better way! + if (!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) { + SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = (0, _utils.uid)(); + } + + this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]; + + /** + * The padding of the filter. Some filters require extra space to breath such as a blur. + * Increasing this will add extra width and height to the bounds of the object that the + * filter is applied to. + * + * @member {number} + */ + this.padding = 4; + + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + * + * @member {number} + */ + this.resolution = _settings2.default.RESOLUTION; + + /** + * If enabled is true the filter is applied, if false it will not. + * + * @member {boolean} + */ + this.enabled = true; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + * @param {object} [currentState] - It's current state of filter. + * There are some useful properties in the currentState : + * target, filters, sourceFrame, destinationFrame, renderTarget, resolution + */ + + + Filter.prototype.apply = function apply(filterManager, input, output, clear, currentState) // eslint-disable-line no-unused-vars + { + // --- // + // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); + + // do as you please! + + filterManager.applyFilter(this, input, output, clear); + + // or just do a regular render.. + }; + + /** + * The default vertex shader source + * + * @static + * @constant + */ + + + _createClass(Filter, null, [{ + key: 'defaultVertexSrc', + get: function get() { + return ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform mat3 projectionMatrix;', 'uniform mat3 filterMatrix;', 'varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;', ' vTextureCoord = aTextureCoord ;', '}'].join('\n'); + } + + /** + * The default fragment shader source + * + * @static + * @constant + */ + + }, { + key: 'defaultFragmentSrc', + get: function get() { + return ['varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'uniform sampler2D uSampler;', 'uniform sampler2D filterSampler;', 'void main(void){', ' vec4 masky = texture2D(filterSampler, vFilterCoord);', ' vec4 sample = texture2D(uSampler, vTextureCoord);', ' vec4 color;', ' if(mod(vFilterCoord.x, 1.0) > 0.5)', ' {', ' color = vec4(1.0, 0.0, 0.0, 1.0);', ' }', ' else', ' {', ' color = vec4(0.0, 1.0, 0.0, 1.0);', ' }', + // ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', + ' gl_FragColor = mix(sample, masky, 0.5);', ' gl_FragColor *= sample.a;', '}'].join('\n'); + } + }]); + + return Filter; +}(); + +exports.default = Filter; + +},{"../../../const":44,"../../../settings":99,"../../../utils":120,"./extractUniformsFromSrc":85}],85:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = extractUniformsFromSrc; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var defaultValue = _pixiGlCore2.default.shader.defaultValue; + +function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) { + var vertUniforms = extractUniformsFromString(vertexSrc, mask); + var fragUniforms = extractUniformsFromString(fragmentSrc, mask); + + return Object.assign(vertUniforms, fragUniforms); +} + +function extractUniformsFromString(string) { + var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea|filterClamp)$'); + + var uniforms = {}; + var nameSplit = void 0; + + // clean the lines a little - remove extra spaces / tabs etc + // then split along ';' + var lines = string.replace(/\s+/g, ' ').split(/\s*;\s*/); + + // loop through.. + for (var i = 0; i < lines.length; i++) { + var line = lines[i].trim(); + + if (line.indexOf('uniform') > -1) { + var splitLine = line.split(' '); + var type = splitLine[1]; + + var name = splitLine[2]; + var size = 1; + + if (name.indexOf('[') > -1) { + // array! + nameSplit = name.split(/\[|]/); + name = nameSplit[0]; + size *= Number(nameSplit[1]); + } + + if (!name.match(maskRegex)) { + uniforms[name] = { + value: defaultValue(type, size), + name: name, + type: type + }; + } + } + } + + return uniforms; +} + +},{"pixi-gl-core":12}],86:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.calculateScreenSpaceMatrix = calculateScreenSpaceMatrix; +exports.calculateNormalizedScreenSpaceMatrix = calculateNormalizedScreenSpaceMatrix; +exports.calculateSpriteMatrix = calculateSpriteMatrix; + +var _math = require('../../../math'); + +/* + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// this returns a matrix that will normalise map filter cords in the filter to screen space +function calculateScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + // let worldTransform = sprite.worldTransform.copy(Matrix.TEMP_MATRIX), + // let texture = {width:1136, height:700};//sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(textureSize.width, textureSize.height); + + return mappedMatrix; +} + +function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + var translateScaleX = textureSize.width / filterArea.width; + var translateScaleY = textureSize.height / filterArea.height; + + mappedMatrix.scale(translateScaleX, translateScaleY); + + return mappedMatrix; +} + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +function calculateSpriteMatrix(outputMatrix, filterArea, textureSize, sprite) { + var worldTransform = sprite.worldTransform.copy(_math.Matrix.TEMP_MATRIX); + var texture = sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + // scale.. + var ratio = textureSize.height / textureSize.width; + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(1, ratio); + + var translateScaleX = textureSize.width / texture.width; + var translateScaleY = textureSize.height / texture.height; + + worldTransform.tx /= texture.width * translateScaleX; + + // this...? free beer for anyone who can explain why this makes sense! + worldTransform.ty /= texture.width * translateScaleX; + // worldTransform.ty /= texture.height * translateScaleY; + + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + + // apply inverse scale.. + mappedMatrix.scale(1, 1 / ratio); + + mappedMatrix.scale(translateScaleX, translateScaleY); + + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; +} + +},{"../../../math":68}],87:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Filter2 = require('../Filter'); + +var _Filter3 = _interopRequireDefault(_Filter2); + +var _math = require('../../../../math'); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The SpriteMaskFilter class + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + */ +var SpriteMaskFilter = function (_Filter) { + _inherits(SpriteMaskFilter, _Filter); + + /** + * @param {PIXI.Sprite} sprite - the target sprite + */ + function SpriteMaskFilter(sprite) { + _classCallCheck(this, SpriteMaskFilter); + + var maskMatrix = new _math.Matrix(); + + var _this = _possibleConstructorReturn(this, _Filter.call(this, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n', 'varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n')); + + sprite.renderable = false; + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + return _this; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + */ + + + SpriteMaskFilter.prototype.apply = function apply(filterManager, input, output) { + var maskSprite = this.maskSprite; + + this.uniforms.mask = maskSprite._texture; + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite); + this.uniforms.alpha = maskSprite.worldAlpha; + + filterManager.applyFilter(this, input, output); + }; + + return SpriteMaskFilter; +}(_Filter3.default); + +exports.default = SpriteMaskFilter; + +},{"../../../../math":68,"../Filter":84,"path":22}],88:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _RenderTarget = require('../utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _Quad = require('../utils/Quad'); + +var _Quad2 = _interopRequireDefault(_Quad); + +var _math = require('../../../math'); + +var _Shader = require('../../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _filterTransforms = require('../filters/filterTransforms'); + +var filterTransforms = _interopRequireWildcard(_filterTransforms); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @ignore + * @class + */ +var FilterState = +/** + * + */ +function FilterState() { + _classCallCheck(this, FilterState); + + this.renderTarget = null; + this.sourceFrame = new _math.Rectangle(); + this.destinationFrame = new _math.Rectangle(); + this.filters = []; + this.target = null; + this.resolution = 1; +}; + +/** + * @class + * @memberof PIXI + * @extends PIXI.WebGLManager + */ + + +var FilterManager = function (_WebGLManager) { + _inherits(FilterManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function FilterManager(renderer) { + _classCallCheck(this, FilterManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.gl = _this.renderer.gl; + // know about sprites! + _this.quad = new _Quad2.default(_this.gl, renderer.state.attribState); + + _this.shaderCache = {}; + // todo add default! + _this.pool = {}; + + _this.filterData = null; + return _this; + } + + /** + * Adds a new filter to the manager. + * + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param {PIXI.Filter[]} filters - The filters to apply. + */ + + + FilterManager.prototype.pushFilter = function pushFilter(target, filters) { + var renderer = this.renderer; + + var filterData = this.filterData; + + if (!filterData) { + filterData = this.renderer._activeRenderTarget.filterStack; + + // add new stack + var filterState = new FilterState(); + + filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; + filterState.renderTarget = renderer._activeRenderTarget; + + this.renderer._activeRenderTarget.filterData = filterData = { + index: 0, + stack: [filterState] + }; + + this.filterData = filterData; + } + + // get the current filter state.. + var currentState = filterData.stack[++filterData.index]; + + if (!currentState) { + currentState = filterData.stack[filterData.index] = new FilterState(); + } + + // for now we go off the filter of the first resolution.. + var resolution = filters[0].resolution; + var padding = filters[0].padding | 0; + var targetBounds = target.filterArea || target.getBounds(true); + var sourceFrame = currentState.sourceFrame; + var destinationFrame = currentState.destinationFrame; + + sourceFrame.x = (targetBounds.x * resolution | 0) / resolution; + sourceFrame.y = (targetBounds.y * resolution | 0) / resolution; + sourceFrame.width = (targetBounds.width * resolution | 0) / resolution; + sourceFrame.height = (targetBounds.height * resolution | 0) / resolution; + + if (filterData.stack[0].renderTarget.transform) {// + + // TODO we should fit the rect around the transform.. + } else { + sourceFrame.fit(filterData.stack[0].destinationFrame); + } + + // lets apply the padding After we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + sourceFrame.pad(padding); + + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + + // lets play the padding after we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + + var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); + + currentState.target = target; + currentState.filters = filters; + currentState.resolution = resolution; + currentState.renderTarget = renderTarget; + + // bind the render target to draw the shape in the top corner.. + + renderTarget.setFrame(destinationFrame, sourceFrame); + + // bind the render target + renderer.bindRenderTarget(renderTarget); + renderTarget.clear(); + }; + + /** + * Pops off the filter and applies it. + * + */ + + + FilterManager.prototype.popFilter = function popFilter() { + var filterData = this.filterData; + + var lastState = filterData.stack[filterData.index - 1]; + var currentState = filterData.stack[filterData.index]; + + this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); + + var filters = currentState.filters; + + if (filters.length === 1) { + filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false, currentState); + this.freePotRenderTarget(currentState.renderTarget); + } else { + var flip = currentState.renderTarget; + var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, currentState.resolution); + + flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + // finally lets clear the render target before drawing to it.. + flop.clear(); + + var i = 0; + + for (i = 0; i < filters.length - 1; ++i) { + filters[i].apply(this, flip, flop, true, currentState); + + var t = flip; + + flip = flop; + flop = t; + } + + filters[i].apply(this, flip, lastState.renderTarget, false, currentState); + + this.freePotRenderTarget(flip); + this.freePotRenderTarget(flop); + } + + filterData.index--; + + if (filterData.index === 0) { + this.filterData = null; + } + }; + + /** + * Draws a filter. + * + * @param {PIXI.Filter} filter - The filter to draw. + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + FilterManager.prototype.applyFilter = function applyFilter(filter, input, output, clear) { + var renderer = this.renderer; + var gl = renderer.gl; + + var shader = filter.glShaders[renderer.CONTEXT_UID]; + + // cacheing.. + if (!shader) { + if (filter.glShaderKey) { + shader = this.shaderCache[filter.glShaderKey]; + + if (!shader) { + shader = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + + filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = shader; + } + } else { + shader = filter.glShaders[renderer.CONTEXT_UID] = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + } + + // TODO - this only needs to be done once? + renderer.bindVao(null); + + this.quad.initVao(shader); + } + + renderer.bindVao(this.quad.vao); + + renderer.bindRenderTarget(output); + + if (clear) { + gl.disable(gl.SCISSOR_TEST); + renderer.clear(); // [1, 1, 1, 1]); + gl.enable(gl.SCISSOR_TEST); + } + + // in case the render target is being masked using a scissor rect + if (output === renderer.maskManager.scissorRenderTarget) { + renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); + } + + renderer.bindShader(shader); + + // free unit 0 for us, doesn't matter what was there + // don't try to restore it, because syncUniforms can upload it to another slot + // and it'll be a problem + var tex = this.renderer.emptyTextures[0]; + + this.renderer.boundTextures[0] = tex; + // this syncs the pixi filters uniforms with glsl uniforms + this.syncUniforms(shader, filter); + + renderer.state.setBlendMode(filter.blendMode); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, input.texture.texture); + + this.quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + }; + + /** + * Uploads the uniforms of the filter. + * + * @param {GLShader} shader - The underlying gl shader. + * @param {PIXI.Filter} filter - The filter we are synchronizing. + */ + + + FilterManager.prototype.syncUniforms = function syncUniforms(shader, filter) { + var uniformData = filter.uniformData; + var uniforms = filter.uniforms; + + // 0 is reserved for the pixi texture so we start at 1! + var textureCount = 1; + var currentState = void 0; + + // filterArea and filterClamp that are handled by FilterManager directly + // they must not appear in uniformData + + if (shader.uniforms.filterArea) { + currentState = this.filterData.stack[this.filterData.index]; + + var filterArea = shader.uniforms.filterArea; + + filterArea[0] = currentState.renderTarget.size.width; + filterArea[1] = currentState.renderTarget.size.height; + filterArea[2] = currentState.sourceFrame.x; + filterArea[3] = currentState.sourceFrame.y; + + shader.uniforms.filterArea = filterArea; + } + + // use this to clamp displaced texture coords so they belong to filterArea + // see displacementFilter fragment shader for an example + if (shader.uniforms.filterClamp) { + currentState = currentState || this.filterData.stack[this.filterData.index]; + + var filterClamp = shader.uniforms.filterClamp; + + filterClamp[0] = 0; + filterClamp[1] = 0; + filterClamp[2] = (currentState.sourceFrame.width - 1) / currentState.renderTarget.size.width; + filterClamp[3] = (currentState.sourceFrame.height - 1) / currentState.renderTarget.size.height; + + shader.uniforms.filterClamp = filterClamp; + } + + // TODO Cacheing layer.. + for (var i in uniformData) { + if (uniformData[i].type === 'sampler2D' && uniforms[i] !== 0) { + if (uniforms[i].baseTexture) { + shader.uniforms[i] = this.renderer.bindTexture(uniforms[i].baseTexture, textureCount); + } else { + shader.uniforms[i] = textureCount; + + // TODO + // this is helpful as renderTargets can also be set. + // Although thinking about it, we could probably + // make the filter texture cache return a RenderTexture + // rather than a renderTarget + var gl = this.renderer.gl; + + this.renderer.boundTextures[textureCount] = this.renderer.emptyTextures[textureCount]; + gl.activeTexture(gl.TEXTURE0 + textureCount); + + uniforms[i].texture.bind(); + } + + textureCount++; + } else if (uniformData[i].type === 'mat3') { + // check if its pixi matrix.. + if (uniforms[i].a !== undefined) { + shader.uniforms[i] = uniforms[i].toArray(true); + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (uniformData[i].type === 'vec2') { + // check if its a point.. + if (uniforms[i].x !== undefined) { + var val = shader.uniforms[i] || new Float32Array(2); + + val[0] = uniforms[i].x; + val[1] = uniforms[i].y; + shader.uniforms[i] = val; + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (uniformData[i].type === 'float') { + if (shader.uniforms.data[i].value !== uniformData[i]) { + shader.uniforms[i] = uniforms[i]; + } + } else { + shader.uniforms[i] = uniforms[i]; + } + } + }; + + /** + * Gets a render target from the pool, or creates a new one. + * + * @param {boolean} clear - Should we clear the render texture when we get it? + * @param {number} resolution - The resolution of the target. + * @return {PIXI.RenderTarget} The new render target + */ + + + FilterManager.prototype.getRenderTarget = function getRenderTarget(clear, resolution) { + var currentState = this.filterData.stack[this.filterData.index]; + var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution); + + renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + return renderTarget; + }; + + /** + * Returns a render target to the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The render target to return. + */ + + + FilterManager.prototype.returnRenderTarget = function returnRenderTarget(renderTarget) { + this.freePotRenderTarget(renderTarget); + }; + + /** + * Calculates the mapped matrix. + * + * TODO playing around here.. this is temporary - (will end up in the shader) + * this returns a matrix that will normalise map filter cords in the filter to screen space + * + * @param {PIXI.Matrix} outputMatrix - the matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateScreenSpaceMatrix = function calculateScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); + }; + + /** + * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function calculateNormalizedScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); + }; + + /** + * This will map the filter coord so that a texture can be used based on the transform of a sprite + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateSpriteMatrix = function calculateSpriteMatrix(outputMatrix, sprite) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); + }; + + /** + * Destroys this Filter Manager. + * + */ + + + FilterManager.prototype.destroy = function destroy() { + this.shaderCache = {}; + this.emptyPool(); + }; + + /** + * Gets a Power-of-Two render texture. + * + * TODO move to a seperate class could be on renderer? + * also - could cause issue with multiple contexts? + * + * @private + * @param {WebGLRenderingContext} gl - The webgl rendering context + * @param {number} minWidth - The minimum width of the render target. + * @param {number} minHeight - The minimum height of the render target. + * @param {number} resolution - The resolution of the render target. + * @return {PIXI.RenderTarget} The new render target. + */ + + + FilterManager.prototype.getPotRenderTarget = function getPotRenderTarget(gl, minWidth, minHeight, resolution) { + // TODO you could return a bigger texture if there is not one in the pool? + minWidth = _bitTwiddle2.default.nextPow2(minWidth * resolution); + minHeight = _bitTwiddle2.default.nextPow2(minHeight * resolution); + + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + if (!this.pool[key]) { + this.pool[key] = []; + } + + var renderTarget = this.pool[key].pop(); + + // creating render target will cause texture to be bound! + if (!renderTarget) { + // temporary bypass cache.. + var tex = this.renderer.boundTextures[0]; + + gl.activeTexture(gl.TEXTURE0); + + // internally - this will cause a texture to be bound.. + renderTarget = new _RenderTarget2.default(gl, minWidth, minHeight, null, 1); + + // set the current one back + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + } + + // manually tweak the resolution... + // this will not modify the size of the frame buffer, just its resolution. + renderTarget.resolution = resolution; + renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution; + renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution; + + return renderTarget; + }; + + /** + * Empties the texture pool. + * + */ + + + FilterManager.prototype.emptyPool = function emptyPool() { + for (var i in this.pool) { + var textures = this.pool[i]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + + this.pool = {}; + }; + + /** + * Frees a render target back into the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free + */ + + + FilterManager.prototype.freePotRenderTarget = function freePotRenderTarget(renderTarget) { + var minWidth = renderTarget.size.width * renderTarget.resolution; + var minHeight = renderTarget.size.height * renderTarget.resolution; + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + this.pool[key].push(renderTarget); + }; + + return FilterManager; +}(_WebGLManager3.default); + +exports.default = FilterManager; + +},{"../../../Shader":42,"../../../math":68,"../filters/filterTransforms":86,"../utils/Quad":93,"../utils/RenderTarget":94,"./WebGLManager":91,"bit-twiddle":1}],89:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _SpriteMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); + +var _SpriteMaskFilter2 = _interopRequireDefault(_SpriteMaskFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var MaskManager = function (_WebGLManager) { + _inherits(MaskManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function MaskManager(renderer) { + _classCallCheck(this, MaskManager); + + // TODO - we don't need both! + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.scissor = false; + _this.scissorData = null; + _this.scissorRenderTarget = null; + + _this.enableScissor = true; + + _this.alphaMaskPool = []; + _this.alphaMaskIndex = 0; + return _this; + } + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushMask = function pushMask(target, maskData) { + // TODO the root check means scissor rect will not + // be used on render textures more info here: + // https://github.com/pixijs/pixi.js/pull/3545 + + if (maskData.texture) { + this.pushSpriteMask(target, maskData); + } else if (this.enableScissor && !this.scissor && this.renderer._activeRenderTarget.root && !this.renderer.stencilManager.stencilMaskStack.length && maskData.isFastRect()) { + var matrix = maskData.worldTransform; + + var rot = Math.atan2(matrix.b, matrix.a); + + // use the nearest degree! + rot = Math.round(rot * (180 / Math.PI)); + + if (rot % 90) { + this.pushStencilMask(maskData); + } else { + this.pushScissorMask(target, maskData); + } + } else { + this.pushStencilMask(maskData); + } + }; + + /** + * Removes the last mask from the mask stack and doesn't return it. + * + * @param {PIXI.DisplayObject} target - Display Object to pop the mask from + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.popMask = function popMask(target, maskData) { + if (maskData.texture) { + this.popSpriteMask(target, maskData); + } else if (this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length) { + this.popScissorMask(target, maskData); + } else { + this.popStencilMask(target, maskData); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.RenderTarget} target - Display Object to push the sprite mask to + * @param {PIXI.Sprite} maskData - Sprite to be used as the mask + */ + + + MaskManager.prototype.pushSpriteMask = function pushSpriteMask(target, maskData) { + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new _SpriteMaskFilter2.default(maskData)]; + } + + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskData; + + // TODO - may cause issues! + target.filterArea = maskData.getBounds(true); + + this.renderer.filterManager.pushFilter(target, alphaMaskFilter); + + this.alphaMaskIndex++; + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popSpriteMask = function popSpriteMask() { + this.renderer.filterManager.popFilter(); + this.alphaMaskIndex--; + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushStencilMask = function pushStencilMask(maskData) { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.pushStencil(maskData); + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popStencilMask = function popStencilMask() { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.popStencil(); + }; + + /** + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushScissorMask = function pushScissorMask(target, maskData) { + maskData.renderable = true; + + var renderTarget = this.renderer._activeRenderTarget; + + var bounds = maskData.getBounds(); + + bounds.fit(renderTarget.size); + maskData.renderable = false; + + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + + var resolution = this.renderer.resolution; + + this.renderer.gl.scissor(bounds.x * resolution, (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution, bounds.width * resolution, bounds.height * resolution); + + this.scissorRenderTarget = renderTarget; + this.scissorData = maskData; + this.scissor = true; + }; + + /** + * + * + */ + + + MaskManager.prototype.popScissorMask = function popScissorMask() { + this.scissorRenderTarget = null; + this.scissorData = null; + this.scissor = false; + + // must be scissor! + var gl = this.renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + }; + + return MaskManager; +}(_WebGLManager3.default); + +exports.default = MaskManager; + +},{"../filters/spriteMask/SpriteMaskFilter":87,"./WebGLManager":91}],90:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var StencilManager = function (_WebGLManager) { + _inherits(StencilManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function StencilManager(renderer) { + _classCallCheck(this, StencilManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.stencilMaskStack = null; + return _this; + } + + /** + * Changes the mask stack that is used by this manager. + * + * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack + */ + + + StencilManager.prototype.setMaskStack = function setMaskStack(stencilMaskStack) { + this.stencilMaskStack = stencilMaskStack; + + var gl = this.renderer.gl; + + if (stencilMaskStack.length === 0) { + gl.disable(gl.STENCIL_TEST); + } else { + gl.enable(gl.STENCIL_TEST); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. @alvin + * + * @param {PIXI.Graphics} graphics - The mask + */ + + + StencilManager.prototype.pushStencil = function pushStencil(graphics) { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + this.renderer._activeRenderTarget.attachStencilBuffer(); + + var gl = this.renderer.gl; + var sms = this.stencilMaskStack; + + if (sms.length === 0) { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.stencilFunc(gl.ALWAYS, 1, 1); + } + + sms.push(graphics); + + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; + + /** + * TODO @alvin + */ + + + StencilManager.prototype.popStencil = function popStencil() { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + var gl = this.renderer.gl; + var sms = this.stencilMaskStack; + + var graphics = sms.pop(); + + if (sms.length === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + } else { + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + } + }; + + /** + * Destroys the mask stack. + * + */ + + + StencilManager.prototype.destroy = function destroy() { + _WebGLManager3.default.prototype.destroy.call(this); + + this.stencilMaskStack.stencilStack = null; + }; + + return StencilManager; +}(_WebGLManager3.default); + +exports.default = StencilManager; + +},{"./WebGLManager":91}],91:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var WebGLManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function WebGLManager(renderer) { + _classCallCheck(this, WebGLManager); + + /** + * The renderer this manager works for. + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + this.renderer.on('context', this.onContextChange, this); + } + + /** + * Generic method called when there is a WebGL context change. + * + */ + + + WebGLManager.prototype.onContextChange = function onContextChange() {} + // do some codes init! + + + /** + * Generic destroy methods to be overridden by the subclass + * + */ + ; + + WebGLManager.prototype.destroy = function destroy() { + this.renderer.off('context', this.onContextChange, this); + + this.renderer = null; + }; + + return WebGLManager; +}(); + +exports.default = WebGLManager; + +},{}],92:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('../managers/WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Base for a common object renderer that can be used as a system renderer plugin. + * + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var ObjectRenderer = function (_WebGLManager) { + _inherits(ObjectRenderer, _WebGLManager); + + function ObjectRenderer() { + _classCallCheck(this, ObjectRenderer); + + return _possibleConstructorReturn(this, _WebGLManager.apply(this, arguments)); + } + + /** + * Starts the renderer and sets the shader + * + */ + ObjectRenderer.prototype.start = function start() {} + // set the shader.. + + + /** + * Stops the renderer + * + */ + ; + + ObjectRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Stub method for rendering content and emptying the current batch. + * + */ + + + ObjectRenderer.prototype.flush = function flush() {} + // flush! + + + /** + * Renders an object + * + * @param {PIXI.DisplayObject} object - The object to render. + */ + ; + + ObjectRenderer.prototype.render = function render(object) // eslint-disable-line no-unused-vars + { + // render the object + }; + + return ObjectRenderer; +}(_WebGLManager3.default); + +exports.default = ObjectRenderer; + +},{"../managers/WebGLManager":91}],93:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a quad + * + * @class + * @memberof PIXI + */ +var Quad = function () { + /** + * @param {WebGLRenderingContext} gl - The gl context for this quad to use. + * @param {object} state - TODO: Description + */ + function Quad(gl, state) { + _classCallCheck(this, Quad); + + /* + * the current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]); + + /** + * The Uvs of the quad + * + * @member {Float32Array} + */ + this.uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + this.interleaved = new Float32Array(8 * 2); + + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + this.indices = (0, _createIndicesForQuads2.default)(1); + + /* + * @member {glCore.GLBuffer} The vertex buffer + */ + this.vertexBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW); + + /* + * @member {glCore.GLBuffer} The index buffer + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + /* + * @member {glCore.VertexArrayObject} The index buffer + */ + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, state); + } + + /** + * Initialises the vaos and uses the shader. + * + * @param {PIXI.Shader} shader - the shader to use + */ + + + Quad.prototype.initVao = function initVao(shader) { + this.vao.clear().addIndex(this.indexBuffer).addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0).addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4); + }; + + /** + * Maps two Rectangle to the quad. + * + * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle + * @param {PIXI.Rectangle} destinationFrame - the second rectangle + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.map = function map(targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + + this.uvs[0] = x; + this.uvs[1] = y; + + this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; + + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; + + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; + + x = destinationFrame.x; + y = destinationFrame.y; + + this.vertices[0] = x; + this.vertices[1] = y; + + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + + return this; + }; + + /** + * Binds the buffer and uploads the data + * + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.upload = function upload() { + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + this.vertexBuffer.upload(this.interleaved); + + return this; + }; + + /** + * Removes this quad from WebGL + */ + + + Quad.prototype.destroy = function destroy() { + var gl = this.gl; + + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.indexBuffer); + }; + + return Quad; +}(); + +exports.default = Quad; + +},{"../../../utils/createIndicesForQuads":118,"pixi-gl-core":12}],94:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../../../math'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _pixiGlCore = require('pixi-gl-core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var RenderTarget = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {number} [width=0] - the horizontal range of the filter + * @param {number} [height=0] - the vertical range of the filter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The current resolution / device pixel ratio + * @param {boolean} [root=false] - Whether this object is the root element or not + */ + function RenderTarget(gl, width, height, scaleMode, resolution, root) { + _classCallCheck(this, RenderTarget); + + // TODO Resolution could go here ( eg low res blurs ) + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // next time to create a frame buffer and texture + + /** + * A frame buffer + * + * @member {PIXI.glCore.GLFramebuffer} + */ + this.frameBuffer = null; + + /** + * The texture + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The background colour of this render target, as an array of [r,g,b,a] values + * + * @member {number[]} + */ + this.clearColor = [0, 0, 0, 0]; + + /** + * The size of the object as a rectangle + * + * @member {PIXI.Rectangle} + */ + this.size = new _math.Rectangle(0, 0, 1, 1); + + /** + * The current resolution / device pixel ratio + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The projection matrix + * + * @member {PIXI.Matrix} + */ + this.projectionMatrix = new _math.Matrix(); + + /** + * The object's transform + * + * @member {PIXI.Matrix} + */ + this.transform = null; + + /** + * The frame. + * + * @member {PIXI.Rectangle} + */ + this.frame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.defaultFrame = new _math.Rectangle(); + this.destinationFrame = null; + this.sourceFrame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.stencilBuffer = null; + + /** + * The data structure for the stencil masks + * + * @member {PIXI.Graphics[]} + */ + this.stencilMaskStack = []; + + /** + * Stores filter data for the render target + * + * @member {object[]} + */ + this.filterData = null; + + /** + * The scale mode. + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Whether this object is the root element or not + * + * @member {boolean} + */ + this.root = root; + + if (!this.root) { + this.frameBuffer = _pixiGlCore.GLFramebuffer.createRGBA(gl, 100, 100); + + if (this.scaleMode === _const.SCALE_MODES.NEAREST) { + this.frameBuffer.texture.enableNearestScaling(); + } else { + this.frameBuffer.texture.enableLinearScaling(); + } + /* + A frame buffer needs a target to render to.. + create a texture and bind it attach it to the framebuffer.. + */ + + // this is used by the base texture + this.texture = this.frameBuffer.texture; + } else { + // make it a null framebuffer.. + this.frameBuffer = new _pixiGlCore.GLFramebuffer(gl, 100, 100); + this.frameBuffer.framebuffer = null; + } + + this.setFrame(); + + this.resize(width, height); + } + + /** + * Clears the filter texture. + * + * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer + */ + + + RenderTarget.prototype.clear = function clear(clearColor) { + var cc = clearColor || this.clearColor; + + this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a); + }; + + /** + * Binds the stencil buffer. + * + */ + + + RenderTarget.prototype.attachStencilBuffer = function attachStencilBuffer() { + // TODO check if stencil is done? + /** + * The stencil buffer is used for masking in pixi + * lets create one and then add attach it to the framebuffer.. + */ + if (!this.root) { + this.frameBuffer.enableStencil(); + } + }; + + /** + * Sets the frame of the render target. + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.setFrame = function setFrame(destinationFrame, sourceFrame) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; + }; + + /** + * Binds the buffers and initialises the viewport. + * + */ + + + RenderTarget.prototype.activate = function activate() { + // TOOD refactor usage of frame.. + var gl = this.gl; + + // make sure the texture is unbound! + this.frameBuffer.bind(); + + this.calculateProjection(this.destinationFrame, this.sourceFrame); + + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + + // TODO add a check as them may be the same! + if (this.destinationFrame !== this.sourceFrame) { + gl.enable(gl.SCISSOR_TEST); + gl.scissor(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + } else { + gl.disable(gl.SCISSOR_TEST); + } + + // TODO - does not need to be updated all the time?? + gl.viewport(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + }; + + /** + * Updates the projection matrix based on a projection frame (which is a rectangle) + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.calculateProjection = function calculateProjection(destinationFrame, sourceFrame) { + var pm = this.projectionMatrix; + + sourceFrame = sourceFrame || destinationFrame; + + pm.identity(); + + // TODO: make dest scale source + if (!this.root) { + pm.a = 1 / destinationFrame.width * 2; + pm.d = 1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = -1 - sourceFrame.y * pm.d; + } else { + pm.a = 1 / destinationFrame.width * 2; + pm.d = -1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = 1 - sourceFrame.y * pm.d; + } + }; + + /** + * Resizes the texture to the specified width and height + * + * @param {number} width - the new width of the texture + * @param {number} height - the new height of the texture + */ + + + RenderTarget.prototype.resize = function resize(width, height) { + width = width | 0; + height = height | 0; + + if (this.size.width === width && this.size.height === height) { + return; + } + + this.size.width = width; + this.size.height = height; + + this.defaultFrame.width = width; + this.defaultFrame.height = height; + + this.frameBuffer.resize(width * this.resolution, height * this.resolution); + + var projectionFrame = this.frame || this.size; + + this.calculateProjection(projectionFrame); + }; + + /** + * Destroys the render target. + * + */ + + + RenderTarget.prototype.destroy = function destroy() { + this.frameBuffer.destroy(); + + this.frameBuffer = null; + this.texture = null; + }; + + return RenderTarget; +}(); + +exports.default = RenderTarget; + +},{"../../../const":44,"../../../math":68,"../../../settings":99,"pixi-gl-core":12}],95:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = checkMaxIfStatmentsInShader; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['precision mediump float;', 'void main(void){', 'float test = 0.1;', '%forloop%', 'gl_FragColor = vec4(0.0);', '}'].join('\n'); + +function checkMaxIfStatmentsInShader(maxIfs, gl) { + var createTempContext = !gl; + + if (maxIfs === 0) { + throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); + } + + if (createTempContext) { + var tinyCanvas = document.createElement('canvas'); + + tinyCanvas.width = 1; + tinyCanvas.height = 1; + + gl = _pixiGlCore2.default.createContext(tinyCanvas); + } + + var shader = gl.createShader(gl.FRAGMENT_SHADER); + + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = maxIfs / 2 | 0; + } else { + // valid! + break; + } + } + + if (createTempContext) { + // get rid of context + if (gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').loseContext(); + } + } + + return maxIfs; +} + +function generateIfTestSrc(maxIfs) { + var src = ''; + + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxIfs - 1) { + src += 'if(test == ' + i + '.0){}'; + } + } + + return src; +} + +},{"pixi-gl-core":12}],96:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLBlendModesToPixi; + +var _const = require('../../../const'); + +/** + * Maps gl blend combinations to WebGL. + * + * @memberof PIXI + * @function mapWebGLBlendModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapWebGLBlendModesToPixi(gl) { + var array = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[_const.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD] = [gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + array[_const.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + return array; +} + +},{"../../../const":44}],97:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLDrawModesToPixi; + +var _const = require('../../../const'); + +/** + * Generic Mask Stack data structure. + * + * @memberof PIXI + * @function mapWebGLDrawModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {object} [object={}] - The object to map into + * @return {object} The mapped draw modes. + */ +function mapWebGLDrawModesToPixi(gl) { + var object = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + object[_const.DRAW_MODES.POINTS] = gl.POINTS; + object[_const.DRAW_MODES.LINES] = gl.LINES; + object[_const.DRAW_MODES.LINE_LOOP] = gl.LINE_LOOP; + object[_const.DRAW_MODES.LINE_STRIP] = gl.LINE_STRIP; + object[_const.DRAW_MODES.TRIANGLES] = gl.TRIANGLES; + object[_const.DRAW_MODES.TRIANGLE_STRIP] = gl.TRIANGLE_STRIP; + object[_const.DRAW_MODES.TRIANGLE_FAN] = gl.TRIANGLE_FAN; + + return object; +} + +},{"../../../const":44}],98:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = validateContext; +function validateContext(gl) { + var attributes = gl.getContextAttributes(); + + // this is going to be fairly simple for now.. but at least we have room to grow! + if (!attributes.stencil) { + /* eslint-disable no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable no-console */ + } +} + +},{}],99:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _maxRecommendedTextures = require('./utils/maxRecommendedTextures'); + +var _maxRecommendedTextures2 = _interopRequireDefault(_maxRecommendedTextures); + +var _canUploadSameBuffer = require('./utils/canUploadSameBuffer'); + +var _canUploadSameBuffer2 = _interopRequireDefault(_canUploadSameBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @namespace PIXI.settings + */ +exports.default = { + + /** + * Target frames per millisecond. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 0.06 + */ + TARGET_FPMS: 0.06, + + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * + * @static + * @memberof PIXI.settings + * @type {boolean} + * @default true + */ + MIPMAP_TEXTURES: true, + + /** + * Default resolution / device pixel ratio of the renderer. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + RESOLUTION: 1, + + /** + * Default filter resolution. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + FILTER_RESOLUTION: 1, + + /** + * The maximum textures that this device supports. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 32 + */ + SPRITE_MAX_TEXTURES: (0, _maxRecommendedTextures2.default)(32), + + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + + /** + * The prefix that denotes a URL is for a retina asset. + * + * @static + * @memberof PIXI.settings + * @type {RegExp} + * @example `@2x` + * @default /@([0-9\.]+)x/ + */ + RETINA_PREFIX: /@([0-9\.]+)x/, + + /** + * The default render options if none are supplied to {@link PIXI.WebGLRenderer} + * or {@link PIXI.CanvasRenderer}. + * + * @static + * @constant + * @memberof PIXI.settings + * @type {object} + * @property {HTMLCanvasElement} view=null + * @property {number} resolution=1 + * @property {boolean} antialias=false + * @property {boolean} forceFXAA=false + * @property {boolean} autoResize=false + * @property {boolean} transparent=false + * @property {number} backgroundColor=0x000000 + * @property {boolean} clearBeforeRender=true + * @property {boolean} preserveDrawingBuffer=false + * @property {boolean} roundPixels=false + */ + RENDER_OPTIONS: { + view: null, + antialias: false, + forceFXAA: false, + autoResize: false, + transparent: false, + backgroundColor: 0x000000, + clearBeforeRender: true, + preserveDrawingBuffer: false, + roundPixels: false + }, + + /** + * Default transform type. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.TRANSFORM_MODE} + * @default PIXI.TRANSFORM_MODE.STATIC + */ + TRANSFORM_MODE: 0, + + /** + * Default Garbage Collection mode. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO + */ + GC_MODE: 0, + + /** + * Default Garbage Collection max idle. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 3600 + */ + GC_MAX_IDLE: 60 * 60, + + /** + * Default Garbage Collection maximum check count. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 600 + */ + GC_MAX_CHECK_COUNT: 60 * 10, + + /** + * Default wrap modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP + */ + WRAP_MODE: 0, + + /** + * The scale modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR + */ + SCALE_MODE: 0, + + /** + * Default specify float precision in vertex shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.HIGH + */ + PRECISION_VERTEX: 'highp', + + /** + * Default specify float precision in fragment shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM + */ + PRECISION_FRAGMENT: 'mediump', + + /** + * Can we upload the same buffer in a single frame? + * + * @static + * @constant + * @memberof PIXI + * @type {boolean} + */ + CAN_UPLOAD_SAME_BUFFER: (0, _canUploadSameBuffer2.default)() + +}; + +},{"./utils/canUploadSameBuffer":117,"./utils/maxRecommendedTextures":121}],100:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new _math.Point(); + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = new PIXI.Sprite.fromImage('assets/image.png'); + * ``` + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Sprite = function (_Container) { + _inherits(Sprite, _Container); + + /** + * @param {PIXI.Texture} texture - The texture for this sprite + */ + function Sprite(texture) { + _classCallCheck(this, Sprite); + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + * @private + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this._anchor = new _math.ObservablePoint(_this._onAnchorUpdate, _this); + + /** + * The texture that the sprite is using + * + * @private + * @member {PIXI.Texture} + */ + _this._texture = null; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = null; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * The shader that will be used to render the sprite. Set to null to remove a current shader. + * + * @member {PIXI.Filter|PIXI.Shader} + */ + _this.shader = null; + + /** + * An internal cached value of the tint. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this.cachedTint = 0xFFFFFF; + + // call texture setter + _this.texture = texture || _Texture2.default.EMPTY; + + /** + * this is used to store the vertex data of the sprite (basically a quad) + * + * @private + * @member {Float32Array} + */ + _this.vertexData = new Float32Array(8); + + /** + * This is used to calculate the bounds of the object IF it is a trimmed sprite + * + * @private + * @member {Float32Array} + */ + _this.vertexTrimmedData = null; + + _this._transformID = -1; + _this._textureID = -1; + + _this._transformTrimmedID = -1; + _this._textureTrimmedID = -1; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * + * @member {string} + * @default 'sprite' + */ + _this.pluginName = 'sprite'; + return _this; + } + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Sprite.prototype._onTextureUpdate = function _onTextureUpdate() { + this._textureID = -1; + this._textureTrimmedID = -1; + + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = (0, _utils.sign)(this.scale.x) * this._width / this.texture.orig.width; + } + + if (this._height) { + this.scale.y = (0, _utils.sign)(this.scale.y) * this._height / this.texture.orig.height; + } + }; + + /** + * Called when the anchor position updates. + * + * @private + */ + + + Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate() { + this._transformID = -1; + this._transformTrimmedID = -1; + }; + + /** + * calculates worldTransform * vertices, store it in vertexData + */ + + + Sprite.prototype.calculateVertices = function calculateVertices() { + if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) { + return; + } + + this._transformID = this.transform._worldID; + this._textureID = this._texture._updateID; + + // set the vertex data + + var texture = this._texture; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var anchor = this._anchor; + + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - anchor._x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - anchor._y * orig.height; + h0 = h1 + trim.height; + } else { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData + * This is used to ensure that the true width and height of a trimmed texture is respected + */ + + + Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices() { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { + return; + } + + this._transformTrimmedID = this.transform._worldID; + this._textureTrimmedID = this._texture._updateID; + + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + var anchor = this._anchor; + + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + + var w1 = -anchor._x * orig.width; + var w0 = w1 + orig.width; + + var h1 = -anchor._y * orig.height; + var h0 = h1 + orig.height; + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use. + */ + + + Sprite.prototype._renderWebGL = function _renderWebGL(renderer) { + this.calculateVertices(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Sprite.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Updates the bounds of the sprite. + * + * @private + */ + + + Sprite.prototype._calculateBounds = function _calculateBounds() { + var trim = this._texture.trim; + var orig = this._texture.orig; + + // First lets check to see if the current texture has a trim.. + if (!trim || trim.width === orig.width && trim.height === orig.height) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + Sprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._texture.orig.width * -this._anchor._x; + this._bounds.minY = this._texture.orig.height * -this._anchor._y; + this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x); + this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._x); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _Container.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Tests if a point is inside this sprite + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Sprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + + if (tempPoint.x > x1 && tempPoint.x < x1 + width) { + y1 = -height * this.anchor.y; + + if (tempPoint.y > y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + Sprite.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + this._anchor = null; + + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + + this._texture.destroy(!!destroyBaseTexture); + } + + this._texture = null; + this.shader = null; + }; + + // some helper functions.. + + /** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Sprite} The newly created sprite + */ + + + Sprite.from = function from(source) { + return new Sprite(_Texture2.default.from(source)); + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId + */ + + + Sprite.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return new Sprite(texture); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id + */ + + + Sprite.fromImage = function fromImage(imageId, crossorigin, scaleMode) { + return new Sprite(_Texture2.default.fromImage(imageId, crossorigin, scaleMode)); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Sprite, [{ + key: 'width', + get: function get() { + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._anchor.copy(value); + } + + /** + * The tint applied to the sprite. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + } + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + */ + + }, { + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + this.cachedTint = 0xFFFFFF; + + this._textureID = -1; + this._textureTrimmedID = -1; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + }]); + + return Sprite; +}(_Container3.default); + +exports.default = Sprite; + +},{"../const":44,"../display/Container":46,"../math":68,"../textures/Texture":112,"../utils":120}],101:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +var _math = require('../../math'); + +var _CanvasTinter = require('./CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var canvasRenderWorldTransform = new _math.Matrix(); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasSpriteRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + */ + +var CanvasSpriteRenderer = function () { + /** + * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for. + */ + function CanvasSpriteRenderer(renderer) { + _classCallCheck(this, CanvasSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + CanvasSpriteRenderer.prototype.render = function render(sprite) { + var texture = sprite._texture; + var renderer = this.renderer; + + var width = texture._frame.width; + var height = texture._frame.height; + + var wt = sprite.transform.worldTransform; + var dx = 0; + var dy = 0; + + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) { + return; + } + + renderer.setBlendMode(sprite.blendMode); + + // Ignore null sources + if (texture.valid) { + renderer.context.globalAlpha = sprite.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture + var smoothingEnabled = texture.baseTexture.scaleMode === _const.SCALE_MODES.LINEAR; + + if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) { + renderer.context[renderer.smoothProperty] = smoothingEnabled; + } + + if (texture.trim) { + dx = texture.trim.width / 2 + texture.trim.x - sprite.anchor.x * texture.orig.width; + dy = texture.trim.height / 2 + texture.trim.y - sprite.anchor.y * texture.orig.height; + } else { + dx = (0.5 - sprite.anchor.x) * texture.orig.width; + dy = (0.5 - sprite.anchor.y) * texture.orig.height; + } + + if (texture.rotate) { + wt.copy(canvasRenderWorldTransform); + wt = canvasRenderWorldTransform; + _math.GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); + // the anchor has already been applied above, so lets set it to zero + dx = 0; + dy = 0; + } + + dx -= width / 2; + dy -= height / 2; + + // Allow for pixel rounding + if (renderer.roundPixels) { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution | 0, wt.ty * renderer.resolution | 0); + + dx = dx | 0; + dy = dy | 0; + } else { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution, wt.ty * renderer.resolution); + } + + var resolution = texture.baseTexture.resolution; + + if (sprite.tint !== 0xFFFFFF) { + if (sprite.cachedTint !== sprite.tint) { + sprite.cachedTint = sprite.tint; + + // TODO clean up caching - how to clean up the caches? + sprite.tintedTexture = _CanvasTinter2.default.getTintedTexture(sprite, sprite.tint); + } + + renderer.context.drawImage(sprite.tintedTexture, 0, 0, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } else { + renderer.context.drawImage(texture.baseTexture.source, texture._frame.x * resolution, texture._frame.y * resolution, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } + } + }; + + /** + * destroy the sprite object. + * + */ + + + CanvasSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasSpriteRenderer; +}(); + +exports.default = CanvasSpriteRenderer; + + +_CanvasRenderer2.default.registerPlugin('sprite', CanvasSpriteRenderer); + +},{"../../const":44,"../../math":68,"../../renderers/canvas/CanvasRenderer":75,"./CanvasTinter":102}],102:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class + * @memberof PIXI + */ +var CanvasTinter = { + /** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Sprite} sprite - the sprite to tint + * @param {number} color - the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ + getTintedTexture: function getTintedTexture(sprite, color) { + var texture = sprite.texture; + + color = CanvasTinter.roundColor(color); + + var stringColor = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + texture.tintCache = texture.tintCache || {}; + + if (texture.tintCache[stringColor]) { + return texture.tintCache[stringColor]; + } + + // clone texture.. + var canvas = CanvasTinter.canvas || document.createElement('canvas'); + + // CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); + CanvasTinter.tintMethod(texture, color, canvas); + + if (CanvasTinter.convertTintToImage) { + // is this better? + var tintImage = new Image(); + + tintImage.src = canvas.toDataURL(); + + texture.tintCache[stringColor] = tintImage; + } else { + texture.tintCache[stringColor] = canvas; + // if we are not converting the texture to an image then we need to lose the reference to the canvas + CanvasTinter.canvas = null; + } + + return canvas; + }, + + /** + * Tint a texture using the 'multiply' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithMultiply: function tintWithMultiply(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + }, + + /** + * Tint a texture using the 'overlay' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithOverlay: function tintWithOverlay(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.globalCompositeOperation = 'copy'; + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + // context.globalCompositeOperation = 'copy'; + }, + + + /** + * Tint a texture pixel per pixel. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithPerPixel: function tintWithPerPixel(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.globalCompositeOperation = 'copy'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + var rgbValues = (0, _utils.hex2rgb)(color); + var r = rgbValues[0]; + var g = rgbValues[1]; + var b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, crop.width, crop.height); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + } + + context.putImageData(pixelData, 0, 0); + }, + + /** + * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel. + * + * @memberof PIXI.CanvasTinter + * @param {number} color - the color to round, should be a hex color + * @return {number} The rounded color. + */ + roundColor: function roundColor(color) { + var step = CanvasTinter.cacheStepsPerColorChannel; + + var rgbValues = (0, _utils.hex2rgb)(color); + + rgbValues[0] = Math.min(255, rgbValues[0] / step * step); + rgbValues[1] = Math.min(255, rgbValues[1] / step * step); + rgbValues[2] = Math.min(255, rgbValues[2] / step * step); + + return (0, _utils.rgb2hex)(rgbValues); + }, + + /** + * Number of steps which will be used as a cap when rounding colors. + * + * @memberof PIXI.CanvasTinter + * @type {number} + */ + cacheStepsPerColorChannel: 8, + + /** + * Tint cache boolean flag. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + convertTintToImage: false, + + /** + * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + canUseMultiply: (0, _canUseNewCanvasBlendModes2.default)(), + + /** + * The tinting method that will be used. + * + * @memberof PIXI.CanvasTinter + * @type {tintMethodFunctionType} + */ + tintMethod: 0 +}; + +CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply : CanvasTinter.tintWithPerPixel; + +/** + * The tintMethod type. + * + * @memberof PIXI.CanvasTinter + * @callback tintMethodFunctionType + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + +exports.default = CanvasTinter; + +},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":78,"../../utils":120}],103:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Buffer = function () { + /** + * @param {number} size - The size of the buffer in bytes. + */ + function Buffer(size) { + _classCallCheck(this, Buffer); + + this.vertices = new ArrayBuffer(size); + + /** + * View on the vertices as a Float32Array for positions + * + * @member {Float32Array} + */ + this.float32View = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array for uvs + * + * @member {Float32Array} + */ + this.uint32View = new Uint32Array(this.vertices); + } + + /** + * Destroys the buffer. + * + */ + + + Buffer.prototype.destroy = function destroy() { + this.vertices = null; + this.positions = null; + this.uvs = null; + this.colors = null; + }; + + return Buffer; +}(); + +exports.default = Buffer; + +},{}],104:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _createIndicesForQuads = require('../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +var _generateMultiTextureShader = require('./generateMultiTextureShader'); + +var _generateMultiTextureShader2 = _interopRequireDefault(_generateMultiTextureShader); + +var _checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'); + +var _checkMaxIfStatmentsInShader2 = _interopRequireDefault(_checkMaxIfStatmentsInShader); + +var _BatchBuffer = require('./BatchBuffer'); + +var _BatchBuffer2 = _interopRequireDefault(_BatchBuffer); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var TICK = 0; +var TEXTURE_TICK = 0; + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var SpriteRenderer = function (_ObjectRenderer) { + _inherits(SpriteRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function SpriteRenderer(renderer) { + _classCallCheck(this, SpriteRenderer); + + /** + * Number of values sent in the vertex buffer. + * aVertexPosition(2), aTextureCoord(1), aColor(1), aTextureId(1) = 5 + * + * @member {number} + */ + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.vertSize = 5; + + /** + * The size of the vertex information in bytes. + * + * @member {number} + */ + _this.vertByteSize = _this.vertSize * 4; + + /** + * The number of images in the SpriteRenderer before it flushes. + * + * @member {number} + */ + _this.size = _settings2.default.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + + // the total number of bytes in our batch + // let numVerts = this.size * 4 * this.vertByteSize; + + _this.buffers = []; + for (var i = 1; i <= _bitTwiddle2.default.nextPow2(_this.size); i *= 2) { + _this.buffers.push(new _BatchBuffer2.default(i * 4 * _this.vertByteSize)); + } + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + _this.indices = (0, _createIndicesForQuads2.default)(_this.size); + + /** + * The default shaders that is used if a sprite doesn't have a more specific one. + * there is a shader for each number of textures that can be rendererd. + * These shaders will also be generated on the fly as required. + * @member {PIXI.Shader[]} + */ + _this.shader = null; + + _this.currentIndex = 0; + _this.groups = []; + + for (var k = 0; k < _this.size; k++) { + _this.groups[k] = { textures: [], textureCount: 0, ids: [], size: 0, start: 0, blend: 0 }; + } + + _this.sprites = []; + + _this.vertexBuffers = []; + _this.vaos = []; + + _this.vaoMax = 2; + _this.vertexCount = 0; + + _this.renderer.on('prerender', _this.onPrerender, _this); + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + SpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + if (this.renderer.legacy) { + this.MAX_TEXTURES = 1; + } else { + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), _settings2.default.SPRITE_MAX_TEXTURES); + + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = (0, _checkMaxIfStatmentsInShader2.default)(this.MAX_TEXTURES, gl); + } + + var shader = this.shader = (0, _generateMultiTextureShader2.default)(gl, this.MAX_TEXTURES); + + // create a couple of buffers + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + // we use the second shader as the first one depending on your browser may omit aTextureId + // as it is not used by the shader so is optimized out. + + this.renderer.bindVao(null); + + for (var i = 0; i < this.vaoMax; i++) { + this.vertexBuffers[i] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + + /* eslint-disable max-len */ + + // build the vao object that will render.. + this.vaos[i] = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(this.vertexBuffers[i], shader.attributes.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(this.vertexBuffers[i], shader.attributes.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(this.vertexBuffers[i], shader.attributes.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (shader.attributes.aTextureId) { + this.vaos[i].addAttribute(this.vertexBuffers[i], shader.attributes.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + /* eslint-enable max-len */ + } + + this.vao = this.vaos[0]; + this.currentBlendMode = 99999; + + this.boundTextures = new Array(this.MAX_TEXTURES); + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + SpriteRenderer.prototype.onPrerender = function onPrerender() { + this.vertexCount = 0; + }; + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + SpriteRenderer.prototype.render = function render(sprite) { + // TODO set blend modes.. + // check texture.. + if (this.currentIndex >= this.size) { + this.flush(); + } + + // get the uvs for the texture + + // if the uvs have not updated then no point rendering just yet! + if (!sprite._texture._uvs) { + return; + } + + // push a texture. + // increment the batchsize + this.sprites[this.currentIndex++] = sprite; + }; + + /** + * Renders the content and empties the current batch. + * + */ + + + SpriteRenderer.prototype.flush = function flush() { + if (this.currentIndex === 0) { + return; + } + + var gl = this.renderer.gl; + var MAX_TEXTURES = this.MAX_TEXTURES; + + var np2 = _bitTwiddle2.default.nextPow2(this.currentIndex); + var log2 = _bitTwiddle2.default.log2(np2); + var buffer = this.buffers[log2]; + + var sprites = this.sprites; + var groups = this.groups; + + var float32View = buffer.float32View; + var uint32View = buffer.uint32View; + + var boundTextures = this.boundTextures; + var rendererBoundTextures = this.renderer.boundTextures; + var touch = this.renderer.textureGC.count; + + var index = 0; + var nextTexture = void 0; + var currentTexture = void 0; + var groupCount = 1; + var textureCount = 0; + var currentGroup = groups[0]; + var vertexData = void 0; + var uvs = void 0; + var blendMode = sprites[0].blendMode; + + currentGroup.textureCount = 0; + currentGroup.start = 0; + currentGroup.blend = blendMode; + + TICK++; + + var i = void 0; + + // copy textures.. + for (i = 0; i < MAX_TEXTURES; ++i) { + boundTextures[i] = rendererBoundTextures[i]; + boundTextures[i]._virtalBoundId = i; + } + + for (i = 0; i < this.currentIndex; ++i) { + // upload the sprite elemetns... + // they have all ready been calculated so we just need to push them into the buffer. + var sprite = sprites[i]; + + nextTexture = sprite._texture.baseTexture; + + if (blendMode !== sprite.blendMode) { + // finish a group.. + blendMode = sprite.blendMode; + + // force the batch to break! + currentTexture = null; + textureCount = MAX_TEXTURES; + TICK++; + } + + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + + if (nextTexture._enabled !== TICK) { + if (textureCount === MAX_TEXTURES) { + TICK++; + + currentGroup.size = i - currentGroup.start; + + textureCount = 0; + + currentGroup = groups[groupCount++]; + currentGroup.blend = blendMode; + currentGroup.textureCount = 0; + currentGroup.start = i; + } + + nextTexture.touched = touch; + + if (nextTexture._virtalBoundId === -1) { + for (var j = 0; j < MAX_TEXTURES; ++j) { + var tIndex = (j + TEXTURE_TICK) % MAX_TEXTURES; + + var t = boundTextures[tIndex]; + + if (t._enabled !== TICK) { + TEXTURE_TICK++; + + t._virtalBoundId = -1; + + nextTexture._virtalBoundId = tIndex; + + boundTextures[tIndex] = nextTexture; + break; + } + } + } + + nextTexture._enabled = TICK; + + currentGroup.textureCount++; + currentGroup.ids[textureCount] = nextTexture._virtalBoundId; + currentGroup.textures[textureCount++] = nextTexture; + } + } + + vertexData = sprite.vertexData; + + // TODO this sum does not need to be set each frame.. + uvs = sprite._texture._uvs.uvsUint32; + + if (this.renderer.roundPixels) { + var resolution = this.renderer.resolution; + + // xy + float32View[index] = (vertexData[0] * resolution | 0) / resolution; + float32View[index + 1] = (vertexData[1] * resolution | 0) / resolution; + + // xy + float32View[index + 5] = (vertexData[2] * resolution | 0) / resolution; + float32View[index + 6] = (vertexData[3] * resolution | 0) / resolution; + + // xy + float32View[index + 10] = (vertexData[4] * resolution | 0) / resolution; + float32View[index + 11] = (vertexData[5] * resolution | 0) / resolution; + + // xy + float32View[index + 15] = (vertexData[6] * resolution | 0) / resolution; + float32View[index + 16] = (vertexData[7] * resolution | 0) / resolution; + } else { + // xy + float32View[index] = vertexData[0]; + float32View[index + 1] = vertexData[1]; + + // xy + float32View[index + 5] = vertexData[2]; + float32View[index + 6] = vertexData[3]; + + // xy + float32View[index + 10] = vertexData[4]; + float32View[index + 11] = vertexData[5]; + + // xy + float32View[index + 15] = vertexData[6]; + float32View[index + 16] = vertexData[7]; + } + + uint32View[index + 2] = uvs[0]; + uint32View[index + 7] = uvs[1]; + uint32View[index + 12] = uvs[2]; + uint32View[index + 17] = uvs[3]; + + /* eslint-disable max-len */ + uint32View[index + 3] = uint32View[index + 8] = uint32View[index + 13] = uint32View[index + 18] = sprite._tintRGB + (Math.min(sprite.worldAlpha, 1) * 255 << 24); + + float32View[index + 4] = float32View[index + 9] = float32View[index + 14] = float32View[index + 19] = nextTexture._virtalBoundId; + /* eslint-enable max-len */ + + index += 20; + } + + currentGroup.size = i - currentGroup.start; + + if (!_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // this is still needed for IOS performance.. + // it really does not like uploading to the same buffer in a single frame! + if (this.vaoMax <= this.vertexCount) { + this.vaoMax++; + this.vertexBuffers[this.vertexCount] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + + /* eslint-disable max-len */ + + // build the vao object that will render.. + this.vaos[this.vertexCount] = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(this.vertexBuffers[this.vertexCount], this.shader.attributes.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(this.vertexBuffers[this.vertexCount], this.shader.attributes.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(this.vertexBuffers[this.vertexCount], this.shader.attributes.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (this.shader.attributes.aTextureId) { + this.vaos[this.vertexCount].addAttribute(this.vertexBuffers[this.vertexCount], this.shader.attributes.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + /* eslint-enable max-len */ + } + + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, false); + + this.vertexCount++; + } else { + // lets use the faster option, always use buffer number 0 + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, true); + } + + for (i = 0; i < MAX_TEXTURES; ++i) { + rendererBoundTextures[i]._virtalBoundId = -1; + } + + // render the groups.. + for (i = 0; i < groupCount; ++i) { + var group = groups[i]; + var groupTextureCount = group.textureCount; + + for (var _j = 0; _j < groupTextureCount; _j++) { + currentTexture = group.textures[_j]; + + // reset virtual ids.. + // lets do a quick check.. + if (rendererBoundTextures[group.ids[_j]] !== currentTexture) { + this.renderer.bindTexture(currentTexture, group.ids[_j], true); + } + + // reset the virtualId.. + currentTexture._virtalBoundId = -1; + } + + // set the blend mode.. + this.renderer.state.setBlendMode(group.blend); + + gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); + } + + // reset elements for the next flush + this.currentIndex = 0; + }; + + /** + * Starts a new sprite batch. + */ + + + SpriteRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + + if (_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // bind buffer #0, we don't need others + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].bind(); + } + }; + + /** + * Stops and flushes the current batch. + * + */ + + + SpriteRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Destroys the SpriteRenderer. + * + */ + + + SpriteRenderer.prototype.destroy = function destroy() { + for (var i = 0; i < this.vaoMax; i++) { + if (this.vertexBuffers[i]) { + this.vertexBuffers[i].destroy(); + } + if (this.vaos[i]) { + this.vaos[i].destroy(); + } + } + + if (this.indexBuffer) { + this.indexBuffer.destroy(); + } + + this.renderer.off('prerender', this.onPrerender, this); + + _ObjectRenderer.prototype.destroy.call(this); + + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } + + this.vertexBuffers = null; + this.vaos = null; + this.indexBuffer = null; + this.indices = null; + + this.sprites = null; + + for (var _i = 0; _i < this.buffers.length; ++_i) { + this.buffers[_i].destroy(); + } + }; + + return SpriteRenderer; +}(_ObjectRenderer3.default); + +exports.default = SpriteRenderer; + + +_WebGLRenderer2.default.registerPlugin('sprite', SpriteRenderer); + +},{"../../renderers/webgl/WebGLRenderer":82,"../../renderers/webgl/utils/ObjectRenderer":92,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":95,"../../settings":99,"../../utils/createIndicesForQuads":118,"./BatchBuffer":103,"./generateMultiTextureShader":105,"bit-twiddle":1,"pixi-gl-core":12}],105:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateMultiTextureShader; + +var _Shader = require('../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'varying float vTextureId;', 'uniform sampler2D uSamplers[%count%];', 'void main(void){', 'vec4 color;', 'float textureId = floor(vTextureId+0.5);', '%forloop%', 'gl_FragColor = color * vColor;', '}'].join('\n'); + +function generateMultiTextureShader(gl, maxTextures) { + var vertexSrc = 'precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = vec4(aColor.rgb * aColor.a, aColor.a);\n}\n'; + var fragmentSrc = fragTemplate; + + fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); + + var shader = new _Shader2.default(gl, vertexSrc, fragmentSrc); + + var sampleValues = []; + + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + + shader.bind(); + shader.uniforms.uSamplers = sampleValues; + + return shader; +} + +function generateSampleSrc(maxTextures) { + var src = ''; + + src += '\n'; + src += '\n'; + + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxTextures - 1) { + src += 'if(textureId == ' + i + '.0)'; + } + + src += '\n{'; + src += '\n\tcolor = texture2D(uSamplers[' + i + '], vTextureCoord);'; + src += '\n}'; + } + + src += '\n'; + src += '\n'; + + return src; +} + +},{"../../Shader":42,"path":22}],106:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Sprite2 = require('../sprites/Sprite'); + +var _Sprite3 = _interopRequireDefault(_Sprite2); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TextStyle = require('./TextStyle'); + +var _TextStyle2 = _interopRequireDefault(_TextStyle); + +var _trimCanvas = require('../utils/trimCanvas'); + +var _trimCanvas2 = _interopRequireDefault(_trimCanvas); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint max-depth: [2, 8] */ + + +var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true +}; + +/** + * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string, + * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object. + * + * A Text can be created directly from a string and a style object + * + * ```js + * let text = new PIXI.Text('This is a pixi text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI + */ + +var Text = function (_Sprite) { + _inherits(Text, _Sprite); + + /** + * @param {string} text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + * @param {HTMLCanvasElement} [canvas] - The canvas element for drawing text + */ + function Text(text, style, canvas) { + _classCallCheck(this, Text); + + canvas = canvas || document.createElement('canvas'); + + canvas.width = 3; + canvas.height = 3; + + var texture = _Texture2.default.fromCanvas(canvas); + + texture.orig = new _math.Rectangle(); + texture.trim = new _math.Rectangle(); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + var _this = _possibleConstructorReturn(this, _Sprite.call(this, texture)); + + _this.canvas = canvas; + + /** + * The canvas 2d context that everything is drawn with + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.canvas.getContext('2d'); + + /** + * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. + * @member {number} + * @default 1 + */ + _this.resolution = _settings2.default.RESOLUTION; + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = null; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._style = null; + /** + * Private listener to track style changes. + * + * @member {Function} + * @private + */ + _this._styleListener = null; + + /** + * Private tracker for the current font. + * + * @member {string} + * @private + */ + _this._font = ''; + + _this.text = text; + _this.style = style; + + _this.localStyleID = -1; + return _this; + } + + /** + * Renders text and updates it when needed. + * + * @private + * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. + */ + + + Text.prototype.updateText = function updateText(respectDirty) { + var style = this._style; + + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + + if (!this.dirty && respectDirty) { + return; + } + + this._font = Text.getFontStyle(style); + + this.context.font = this._font; + + // word wrap + // preserve original text + var outputText = style.wordWrap ? this.wordWrap(this._text) : this._text; + + // split text into lines + var lines = outputText.split(/(?:\r\n|\r|\n)/); + + // calculate text width + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + var fontProperties = Text.calculateFontProperties(this._font); + + for (var i = 0; i < lines.length; i++) { + var lineWidth = this.context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing; + + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + + var width = maxLineWidth + style.strokeThickness; + + if (style.dropShadow) { + width += style.dropShadowDistance; + } + + this.canvas.width = Math.ceil((width + style.padding * 2) * this.resolution); + + // calculate text height + var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * lineHeight; + + if (style.dropShadow) { + height += style.dropShadowDistance; + } + + this.canvas.height = Math.ceil((height + style.padding * 2) * this.resolution); + + this.context.scale(this.resolution, this.resolution); + + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + + this.context.font = this._font; + this.context.strokeStyle = style.stroke; + this.context.lineWidth = style.strokeThickness; + this.context.textBaseline = style.textBaseline; + this.context.lineJoin = style.lineJoin; + this.context.miterLimit = style.miterLimit; + + var linePositionX = void 0; + var linePositionY = void 0; + + if (style.dropShadow) { + this.context.shadowBlur = style.dropShadowBlur; + this.context.globalAlpha = style.dropShadowAlpha; + + if (style.dropShadowBlur > 0) { + this.context.shadowColor = style.dropShadowColor; + } else { + this.context.fillStyle = style.dropShadowColor; + } + + var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + + for (var _i = 0; _i < lines.length; _i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i]) / 2; + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); + + if (style.stroke && style.strokeThickness) { + this.context.strokeStyle = style.dropShadowColor; + this.drawLetterSpacing(lines[_i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding, true); + this.context.strokeStyle = style.stroke; + } + } + } + } + + // reset the shadow blur and alpha that was set by the drop shadow, for the regular text + this.context.shadowBlur = 0; + this.context.globalAlpha = 1; + + // set canvas text styles + this.context.fillStyle = this._generateFillStyle(style, lines); + + // draw lines line by line + for (var _i2 = 0; _i2 < lines.length; _i2++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i2 * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i2]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i2]) / 2; + } + + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[_i2], linePositionX + style.padding, linePositionY + style.padding, true); + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i2], linePositionX + style.padding, linePositionY + style.padding); + } + } + + this.updateTexture(); + }; + + /** + * Render the text with letter-spacing. + * @param {string} text - The text to draw + * @param {number} x - Horizontal position to draw the text + * @param {number} y - Vertical position to draw the text + * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + * @private + */ + + + Text.prototype.drawLetterSpacing = function drawLetterSpacing(text, x, y) { + var isStroke = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var style = this._style; + + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + + if (letterSpacing === 0) { + if (isStroke) { + this.context.strokeText(text, x, y); + } else { + this.context.fillText(text, x, y); + } + + return; + } + + var characters = String.prototype.split.call(text, ''); + var currentPosition = x; + var index = 0; + var current = ''; + + while (index < text.length) { + current = characters[index++]; + if (isStroke) { + this.context.strokeText(current, currentPosition, y); + } else { + this.context.fillText(current, currentPosition, y); + } + currentPosition += this.context.measureText(current).width + letterSpacing; + } + }; + + /** + * Updates texture size based on canvas size + * + * @private + */ + + + Text.prototype.updateTexture = function updateTexture() { + if (this._style.trim) { + var trimmed = (0, _trimCanvas2.default)(this.canvas); + + this.canvas.width = trimmed.width; + this.canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } + + var texture = this._texture; + var style = this._style; + + texture.baseTexture.hasLoaded = true; + texture.baseTexture.resolution = this.resolution; + + texture.baseTexture.realWidth = this.canvas.width; + texture.baseTexture.realHeight = this.canvas.height; + texture.baseTexture.width = this.canvas.width / this.resolution; + texture.baseTexture.height = this.canvas.height / this.resolution; + texture.trim.width = texture._frame.width = this.canvas.width / this.resolution; + texture.trim.height = texture._frame.height = this.canvas.height / this.resolution; + + texture.trim.x = -style.padding; + texture.trim.y = -style.padding; + + texture.orig.width = texture._frame.width - style.padding * 2; + texture.orig.height = texture._frame.height - style.padding * 2; + + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + + texture.baseTexture.emit('update', texture.baseTexture); + + this.dirty = false; + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Text.prototype.renderWebGL = function renderWebGL(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype.renderWebGL.call(this, renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Text.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype._renderCanvas.call(this, renderer); + }; + + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @private + * @param {string} text - String to apply word wrapping to + * @return {string} New string with new lines applied where required + */ + + + Text.prototype.wordWrap = function wordWrap(text) { + // Greedy wrapping algorithm that will wrap words as the line grows longer + // than its horizontal bounds. + var result = ''; + var style = this._style; + var lines = text.split('\n'); + var wordWrapWidth = style.wordWrapWidth; + + for (var i = 0; i < lines.length; i++) { + var spaceLeft = wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) { + var wordWidth = this.context.measureText(words[j]).width; + + if (style.breakWords && wordWidth > wordWrapWidth) { + // Word should be split in the middle + var characters = words[j].split(''); + + for (var c = 0; c < characters.length; c++) { + var characterWidth = this.context.measureText(characters[c]).width; + + if (characterWidth > spaceLeft) { + result += '\n' + characters[c]; + spaceLeft = wordWrapWidth - characterWidth; + } else { + if (c === 0) { + result += ' '; + } + + result += characters[c]; + spaceLeft -= characterWidth; + } + } + } else { + var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; + + if (j === 0 || wordWidthWithSpace > spaceLeft) { + // Skip printing the newline if it's the first word of the line that is + // greater than the word wrap width. + if (j > 0) { + result += '\n'; + } + result += words[j]; + spaceLeft = wordWrapWidth - wordWidth; + } else { + spaceLeft -= wordWidthWithSpace; + result += ' ' + words[j]; + } + } + } + + if (i < lines.length - 1) { + result += '\n'; + } + } + + return result; + }; + + /** + * Gets the local bounds of the text object. + * + * @param {Rectangle} rect - The output rectangle. + * @return {Rectangle} The bounds. + */ + + + Text.prototype.getLocalBounds = function getLocalBounds(rect) { + this.updateText(true); + + return _Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + */ + + + Text.prototype._calculateBounds = function _calculateBounds() { + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; + + /** + * Method to be called upon a TextStyle change. + * @private + */ + + + Text.prototype._onStyleChange = function _onStyleChange() { + this.dirty = true; + }; + + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * + * @private + * @param {object} style - The style. + * @param {string[]} lines - The lines of text. + * @return {string|number|CanvasGradient} The fill style + */ + + + Text.prototype._generateFillStyle = function _generateFillStyle(style, lines) { + if (!Array.isArray(style.fill)) { + return style.fill; + } + + // cocoon on canvas+ cannot generate textures, so use the first colour instead + if (navigator.isCocoonJS) { + return style.fill[0]; + } + + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient = void 0; + var totalIterations = void 0; + var currentIteration = void 0; + var stop = void 0; + + var width = this.canvas.width / this.resolution; + var height = this.canvas.height / this.resolution; + + // make a copy of the style settings, so we can manipulate them later + var fill = style.fill.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(style.fill[0]); + fillGradientStops.unshift(0); + + fill.push(style.fill[style.fill.length - 1]); + fillGradientStops.push(1); + + if (style.fillGradientType === _const.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); + + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + totalIterations = (fill.length + 1) * lines.length; + currentIteration = 0; + for (var _i3 = 0; _i3 < lines.length; _i3++) { + currentIteration += 1; + for (var j = 0; j < fill.length; j++) { + if (fillGradientStops[j]) { + stop = fillGradientStops[j] / lines.length + _i3 / lines.length; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[j]); + currentIteration++; + } + } + } else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); + + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + totalIterations = fill.length + 1; + currentIteration = 1; + + for (var _i4 = 0; _i4 < fill.length; _i4++) { + if (fillGradientStops[_i4]) { + stop = fillGradientStops[_i4]; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[_i4]); + currentIteration++; + } + } + + return gradient; + }; + + /** + * Destroys this text object. + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majority of the time the texture will not be shared with any other Sprites. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well + */ + + + Text.prototype.destroy = function destroy(options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + + options = Object.assign({}, defaultDestroyOptions, options); + + _Sprite.prototype.destroy.call(this, options); + + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + + this._style = null; + }; + + /** + * The width of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + /** + * Generates a font style string to use for Text.calculateFontProperties(). Takes the same parameter + * as Text.style. + * + * @static + * @param {object|TextStyle} style - String representing the style of the font + * @return {string} Font style string, for passing to Text.calculateFontProperties() + */ + Text.getFontStyle = function getFontStyle(style) { + style = style || {}; + + if (!(style instanceof _TextStyle2.default)) { + style = new _TextStyle2.default(style); + } + + // build canvas api font setting from individual components. Convert a numeric style.fontSize to px + var fontSizeString = typeof style.fontSize === 'number' ? style.fontSize + 'px' : style.fontSize; + + // Clean-up fontFamily property by quoting each font name + // this will support font names with spaces + var fontFamilies = style.fontFamily; + + if (!Array.isArray(style.fontFamily)) { + fontFamilies = style.fontFamily.split(','); + } + + for (var i = fontFamilies.length - 1; i >= 0; i--) { + // Trim any extra white-space + var fontFamily = fontFamilies[i].trim(); + + // Check if font already contains strings + if (!/([\"\'])[^\'\"]+\1/.test(fontFamily)) { + fontFamily = '"' + fontFamily + '"'; + } + fontFamilies[i] = fontFamily; + } + + return style.fontStyle + ' ' + style.fontVariant + ' ' + style.fontWeight + ' ' + fontSizeString + ' ' + fontFamilies.join(','); + }; + + /** + * Calculates the ascent, descent and fontSize of a given fontStyle + * + * @static + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ + + + Text.calculateFontProperties = function calculateFontProperties(fontStyle) { + // as this method is used for preparing assets, don't recalculate things if we don't need to + if (Text.fontPropertiesCache[fontStyle]) { + return Text.fontPropertiesCache[fontStyle]; + } + + var properties = {}; + + var canvas = Text.fontPropertiesCanvas; + var context = Text.fontPropertiesContext; + + context.font = fontStyle; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('M').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = fontStyle; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i = 0; + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } else { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var _j = 0; _j < line; _j += 4) { + if (imagedata[idx + _j] !== 255) { + stop = true; + break; + } + } + + if (!stop) { + idx -= line; + } else { + break; + } + } + + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + + Text.fontPropertiesCache[fontStyle] = properties; + + return properties; + }; + + _createClass(Text, [{ + key: 'width', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * Set the style of the text. Set up an event listener to listen for changes on the style + * object and mark the text as dirty. + * + * @member {object|PIXI.TextStyle} + */ + + }, { + key: 'style', + get: function get() { + return this._style; + }, + set: function set(style) // eslint-disable-line require-jsdoc + { + style = style || {}; + + if (style instanceof _TextStyle2.default) { + this._style = style; + } else { + this._style = new _TextStyle2.default(style); + } + + this.localStyleID = -1; + this.dirty = true; + } + + /** + * Set the copy for the text object. To split a line you can use '\n'. + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(text) // eslint-disable-line require-jsdoc + { + text = String(text === '' || text === null || text === undefined ? ' ' : text); + + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + } + }]); + + return Text; +}(_Sprite3.default); + +exports.default = Text; + + +Text.fontPropertiesCache = {}; +Text.fontPropertiesCanvas = document.createElement('canvas'); +Text.fontPropertiesContext = Text.fontPropertiesCanvas.getContext('2d'); + +},{"../const":44,"../math":68,"../settings":99,"../sprites/Sprite":100,"../textures/Texture":112,"../utils":120,"../utils/trimCanvas":124,"./TextStyle":107}],107:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // disabling eslint for now, going to rewrite this in v5 +/* eslint-disable */ + +var _const = require('../const'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: '#000000', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: _const.TEXT_GRADIENT.LINEAR_VERTICAL, + fillGradientStops: [], + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + trim: false, + wordWrap: false, + wordWrapWidth: 100 +}; + +/** + * A TextStyle Object decorates a Text Object. It can be shared between + * multiple Text objects. Changing the style will update all text objects using it. + * + * @class + * @memberof PIXI + */ + +var TextStyle = function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string} [style.dropShadowColor='#000000'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours + * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} + * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set + * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * @param {string|string[]} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', 800' or '900') + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Default is 'miter' (creates a sharp corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {boolean} [style.trim=false] - Trim transparent borders + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + _classCallCheck(this, TextStyle); + + this.styleID = 0; + + Object.assign(this, defaultStyle, style); + } + + /** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return {PIXI.TextStyle} New cloned TextStyle object + */ + + + TextStyle.prototype.clone = function clone() { + var clonedProperties = {}; + + for (var key in defaultStyle) { + clonedProperties[key] = this[key]; + } + + return new TextStyle(clonedProperties); + }; + + /** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ + + + TextStyle.prototype.reset = function reset() { + Object.assign(this, defaultStyle); + }; + + _createClass(TextStyle, [{ + key: 'align', + get: function get() { + return this._align; + }, + set: function set(align) { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + } + }, { + key: 'breakWords', + get: function get() { + return this._breakWords; + }, + set: function set(breakWords) { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + } + }, { + key: 'dropShadow', + get: function get() { + return this._dropShadow; + }, + set: function set(dropShadow) { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + } + }, { + key: 'dropShadowAlpha', + get: function get() { + return this._dropShadowAlpha; + }, + set: function set(dropShadowAlpha) { + if (this._dropShadowAlpha !== dropShadowAlpha) { + this._dropShadowAlpha = dropShadowAlpha; + this.styleID++; + } + } + }, { + key: 'dropShadowAngle', + get: function get() { + return this._dropShadowAngle; + }, + set: function set(dropShadowAngle) { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + } + }, { + key: 'dropShadowBlur', + get: function get() { + return this._dropShadowBlur; + }, + set: function set(dropShadowBlur) { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + } + }, { + key: 'dropShadowColor', + get: function get() { + return this._dropShadowColor; + }, + set: function set(dropShadowColor) { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + } + }, { + key: 'dropShadowDistance', + get: function get() { + return this._dropShadowDistance; + }, + set: function set(dropShadowDistance) { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + } + }, { + key: 'fill', + get: function get() { + return this._fill; + }, + set: function set(fill) { + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + } + }, { + key: 'fillGradientType', + get: function get() { + return this._fillGradientType; + }, + set: function set(fillGradientType) { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + } + }, { + key: 'fillGradientStops', + get: function get() { + return this._fillGradientStops; + }, + set: function set(fillGradientStops) { + if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { + this._fillGradientStops = fillGradientStops; + this.styleID++; + } + } + }, { + key: 'fontFamily', + get: function get() { + return this._fontFamily; + }, + set: function set(fontFamily) { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + } + }, { + key: 'fontSize', + get: function get() { + return this._fontSize; + }, + set: function set(fontSize) { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + } + }, { + key: 'fontStyle', + get: function get() { + return this._fontStyle; + }, + set: function set(fontStyle) { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + } + }, { + key: 'fontVariant', + get: function get() { + return this._fontVariant; + }, + set: function set(fontVariant) { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + } + }, { + key: 'fontWeight', + get: function get() { + return this._fontWeight; + }, + set: function set(fontWeight) { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + } + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(letterSpacing) { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + } + }, { + key: 'lineHeight', + get: function get() { + return this._lineHeight; + }, + set: function set(lineHeight) { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + } + }, { + key: 'lineJoin', + get: function get() { + return this._lineJoin; + }, + set: function set(lineJoin) { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + } + }, { + key: 'miterLimit', + get: function get() { + return this._miterLimit; + }, + set: function set(miterLimit) { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + } + }, { + key: 'padding', + get: function get() { + return this._padding; + }, + set: function set(padding) { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + } + }, { + key: 'stroke', + get: function get() { + return this._stroke; + }, + set: function set(stroke) { + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + } + }, { + key: 'strokeThickness', + get: function get() { + return this._strokeThickness; + }, + set: function set(strokeThickness) { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + } + }, { + key: 'textBaseline', + get: function get() { + return this._textBaseline; + }, + set: function set(textBaseline) { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + } + }, { + key: 'trim', + get: function get() { + return this._trim; + }, + set: function set(trim) { + if (this._trim !== trim) { + this._trim = trim; + this.styleID++; + } + } + }, { + key: 'wordWrap', + get: function get() { + return this._wordWrap; + }, + set: function set(wordWrap) { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + } + }, { + key: 'wordWrapWidth', + get: function get() { + return this._wordWrapWidth; + }, + set: function set(wordWrapWidth) { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + } + }]); + + return TextStyle; +}(); + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * + * @param {number|number[]} color + * @return {string} The color as a string. + */ + + +exports.default = TextStyle; +function getSingleColor(color) { + if (typeof color === 'number') { + return (0, _utils.hex2string)(color); + } else if (typeof color === 'string') { + if (color.indexOf('0x') === 0) { + color = color.replace('0x', '#'); + } + } + + return color; +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * + * @param {number|number[]} color + * @return {string} The color as a string. + */ +function getColor(color) { + if (!Array.isArray(color)) { + return getSingleColor(color); + } else { + for (var i = 0; i < color.length; ++i) { + color[i] = getSingleColor(color[i]); + } + + return color; + } +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * + * @param {Array} array1 First array to compare + * @param {Array} array2 Second array to compare + * @return {boolean} Do the arrays contain the same values in the same order + */ +function areArraysEqual(array1, array2) { + if (!Array.isArray(array1) || !Array.isArray(array2)) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } + + return true; +} + +},{"../const":44,"../utils":120}],108:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let baseRenderTexture = new PIXI.BaseRenderTexture(renderer, 800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * baseRenderTexture.render(sprite); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let baseRenderTexture = new PIXI.BaseRenderTexture(100, 100); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var BaseRenderTexture = function (_BaseTexture) { + _inherits(BaseRenderTexture, _BaseTexture); + + /** + * @param {number} [width=100] - The width of the base render texture + * @param {number} [height=100] - The height of the base render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + */ + function BaseRenderTexture() { + var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + + _classCallCheck(this, BaseRenderTexture); + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, null, scaleMode)); + + _this.resolution = resolution || _settings2.default.RESOLUTION; + + _this.width = width; + _this.height = height; + + _this.realWidth = _this.width * _this.resolution; + _this.realHeight = _this.height * _this.resolution; + + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + _this.hasLoaded = true; + + /** + * A map of renderer IDs to webgl renderTargets + * + * @private + * @member {object} + */ + _this._glRenderTargets = {}; + + /** + * A reference to the canvas render target (we only need one as this can be shared across renderers) + * + * @private + * @member {object} + */ + _this._canvasRenderTarget = null; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + return _this; + } + + /** + * Resizes the BaseRenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + */ + + + BaseRenderTexture.prototype.resize = function resize(width, height) { + if (width === this.width && height === this.height) { + return; + } + + this.valid = width > 0 && height > 0; + + this.width = width; + this.height = height; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + if (!this.valid) { + return; + } + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + */ + + + BaseRenderTexture.prototype.destroy = function destroy() { + _BaseTexture.prototype.destroy.call(this, true); + this.renderer = null; + }; + + return BaseRenderTexture; +}(_BaseTexture3.default); + +exports.default = BaseRenderTexture; + +},{"../settings":99,"./BaseTexture":109}],109:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var BaseTexture = function (_EventEmitter) { + _inherits(BaseTexture, _EventEmitter); + + /** + * @param {HTMLImageElement|HTMLCanvasElement} [source] - the source object of the texture. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture + */ + function BaseTexture(source, scaleMode, resolution) { + _classCallCheck(this, BaseTexture); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.uid = (0, _utils.uid)(); + + _this.touched = 0; + + /** + * The resolution / device pixel ratio of the texture + * + * @member {number} + * @default 1 + */ + _this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The width of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.width = 100; + + /** + * The height of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.height = 100; + + // TODO docs + // used to store the actual dimensions of the source + /** + * Used to store the actual width of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realWidth = 100; + /** + * Used to store the actual height of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realHeight = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Set to true once the base texture has successfully loaded. + * + * This is never true if the underlying source fails to load or has no texture data. + * + * @readonly + * @member {boolean} + */ + _this.hasLoaded = false; + + /** + * Set to true if the source is currently loading. + * + * If an Image source is loading the 'loaded' or 'error' event will be + * dispatched when the operation ends. An underyling source that is + * immediately-available bypasses loading entirely. + * + * @readonly + * @member {boolean} + */ + _this.isLoading = false; + + /** + * The image source that is used to create the texture. + * + * TODO: Make this a setter that calls loadSource(); + * + * @readonly + * @member {HTMLImageElement|HTMLCanvasElement} + */ + _this.source = null; // set in loadSource, if at all + + /** + * The image source that is used to create the texture. This is used to + * store the original Svg source when it is replaced with a canvas element. + * + * TODO: Currently not in use but could be used when re-scaling svg. + * + * @readonly + * @member {Image} + */ + _this.origSource = null; // set in loadSvg, if at all + + /** + * Type of image defined in source, eg. `png` or `svg` + * + * @readonly + * @member {string} + */ + _this.imageType = null; // set in updateImageType + + /** + * Scale for source image. Used with Svg images to scale them before rasterization. + * + * @readonly + * @member {number} + */ + _this.sourceScale = 1.0; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * All blend modes, and shaders written for default value. Change it on your own risk. + * + * @member {boolean} + * @default true + */ + _this.premultipliedAlpha = true; + + /** + * The image url of the texture + * + * @member {string} + */ + _this.imageUrl = null; + + /** + * Whether or not the texture is a power of two, try to use power of two textures as much + * as you can + * + * @private + * @member {boolean} + */ + _this.isPowerOfTwo = false; + + // used for webGL + + /** + * + * Set this to true if a mipmap of this texture needs to be generated. This value needs + * to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @member {boolean} + * @see PIXI.MIPMAP_TEXTURES + */ + _this.mipmap = _settings2.default.MIPMAP_TEXTURES; + + /** + * + * WebGL Texture wrap mode + * + * @member {number} + * @see PIXI.WRAP_MODES + */ + _this.wrapMode = _settings2.default.WRAP_MODE; + + /** + * A map of renderer IDs to webgl textures + * + * @private + * @member {object} + */ + _this._glTextures = {}; + + _this._enabled = 0; + _this._virtalBoundId = -1; + + // if no source passed don't try to load + if (source) { + _this.loadSource(source); + } + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + + /** + * Fired when a not-immediately-available source finishes loading. + * + * @protected + * @event loaded + * @memberof PIXI.BaseTexture# + */ + + /** + * Fired when a not-immediately-available source fails to load. + * + * @protected + * @event error + * @memberof PIXI.BaseTexture# + */ + return _this; + } + + /** + * Updates the texture on all the webgl renderers, this also assumes the src has changed. + * + * @fires update + */ + + + BaseTexture.prototype.update = function update() { + // Svg size is handled during load + if (this.imageType !== 'svg') { + this.realWidth = this.source.naturalWidth || this.source.videoWidth || this.source.width; + this.realHeight = this.source.naturalHeight || this.source.videoHeight || this.source.height; + + this._updateDimensions(); + } + + this.emit('update', this); + }; + + /** + * Update dimensions from real values + */ + + + BaseTexture.prototype._updateDimensions = function _updateDimensions() { + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + this.isPowerOfTwo = _bitTwiddle2.default.isPow2(this.realWidth) && _bitTwiddle2.default.isPow2(this.realHeight); + }; + + /** + * Load a source. + * + * If the source is not-immediately-available, such as an image that needs to be + * downloaded, then the 'loaded' or 'error' event will be dispatched in the future + * and `hasLoaded` will remain false after this call. + * + * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: + * + * if (texture.hasLoaded) { + * // texture ready for use + * } else if (texture.isLoading) { + * // listen to 'loaded' and/or 'error' events on texture + * } else { + * // not loading, not going to load UNLESS the source is reloaded + * // (it may still make sense to listen to the events) + * } + * + * @protected + * @param {HTMLImageElement|HTMLCanvasElement} source - the source object of the texture. + */ + + + BaseTexture.prototype.loadSource = function loadSource(source) { + var _this2 = this; + + var wasLoading = this.isLoading; + + this.hasLoaded = false; + this.isLoading = false; + + if (wasLoading && this.source) { + this.source.onload = null; + this.source.onerror = null; + } + + var firstSourceLoaded = !this.source; + + this.source = source; + + // Apply source if loaded. Otherwise setup appropriate loading monitors. + if ((source.src && source.complete || source.getContext) && source.width && source.height) { + this._updateImageType(); + + if (this.imageType === 'svg') { + this._loadSvgSource(); + } else { + this._sourceLoaded(); + } + + if (firstSourceLoaded) { + // send loaded event if previous source was null and we have been passed a pre-loaded IMG element + this.emit('loaded', this); + } + } else if (!source.getContext) { + var _ret = function () { + // Image fail / not ready + _this2.isLoading = true; + + var scope = _this2; + + source.onload = function () { + scope._updateImageType(); + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope._sourceLoaded(); + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + scope.emit('loaded', scope); + }; + + source.onerror = function () { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope.emit('error', scope); + }; + + // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element + // "The value of `complete` can thus change while a script is executing." + // So complete needs to be re-checked after the callbacks have been added.. + // NOTE: complete will be true if the image has no src so best to check if the src is set. + if (source.complete && source.src) { + // ..and if we're complete now, no need for callbacks + source.onload = null; + source.onerror = null; + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return { + v: void 0 + }; + } + + _this2.isLoading = false; + + if (source.width && source.height) { + _this2._sourceLoaded(); + + // If any previous subscribers possible + if (wasLoading) { + _this2.emit('loaded', _this2); + } + } + // If any previous subscribers possible + else if (wasLoading) { + _this2.emit('error', _this2); + } + } + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + }; + + /** + * Updates type of the source image. + */ + + + BaseTexture.prototype._updateImageType = function _updateImageType() { + if (!this.imageUrl) { + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + var imageType = void 0; + + if (dataUri && dataUri.mediaType === 'image') { + // Check for subType validity + var firstSubType = dataUri.subType.split('+')[0]; + + imageType = (0, _utils.getUrlFileExtension)('.' + firstSubType); + + if (!imageType) { + throw new Error('Invalid image type in data URI.'); + } + } else { + imageType = (0, _utils.getUrlFileExtension)(this.imageUrl); + + if (!imageType) { + imageType = 'png'; + } + } + + this.imageType = imageType; + }; + + /** + * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls + * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. + */ + + + BaseTexture.prototype._loadSvgSource = function _loadSvgSource() { + if (this.imageType !== 'svg') { + // Do nothing if source is not svg + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + + if (dataUri) { + this._loadSvgSourceUsingDataUri(dataUri); + } else { + // We got an URL, so we need to do an XHR to check the svg size + this._loadSvgSourceUsingXhr(); + } + }; + + /** + * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`. + * + * @param {string} dataUri - The data uri to load from. + */ + + + BaseTexture.prototype._loadSvgSourceUsingDataUri = function _loadSvgSourceUsingDataUri(dataUri) { + var svgString = void 0; + + if (dataUri.encoding === 'base64') { + if (!atob) { + throw new Error('Your browser doesn\'t support base64 conversions.'); + } + svgString = atob(dataUri.data); + } else { + svgString = dataUri.data; + } + + this._loadSvgSourceUsingString(svgString); + }; + + /** + * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. + */ + + + BaseTexture.prototype._loadSvgSourceUsingXhr = function _loadSvgSourceUsingXhr() { + var _this3 = this; + + var svgXhr = new XMLHttpRequest(); + + // This throws error on IE, so SVG Document can't be used + // svgXhr.responseType = 'document'; + + // This is not needed since we load the svg as string (breaks IE too) + // but overrideMimeType() can be used to force the response to be parsed as XML + // svgXhr.overrideMimeType('image/svg+xml'); + + svgXhr.onload = function () { + if (svgXhr.readyState !== svgXhr.DONE || svgXhr.status !== 200) { + throw new Error('Failed to load SVG using XHR.'); + } + + _this3._loadSvgSourceUsingString(svgXhr.response); + }; + + svgXhr.onerror = function () { + return _this3.emit('error', _this3); + }; + + svgXhr.open('GET', this.imageUrl, true); + svgXhr.send(); + }; + + /** + * Loads texture using an SVG string. The original SVG Image is stored as `origSource` and the + * created canvas is the new `source`. The SVG is scaled using `sourceScale`. Called by + * `_loadSvgSourceUsingXhr` or `_loadSvgSourceUsingDataUri`. + * + * @param {string} svgString SVG source as string + * + * @fires loaded + */ + + + BaseTexture.prototype._loadSvgSourceUsingString = function _loadSvgSourceUsingString(svgString) { + var svgSize = (0, _utils.getSvgSize)(svgString); + + var svgWidth = svgSize.width; + var svgHeight = svgSize.height; + + if (!svgWidth || !svgHeight) { + throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); + } + + // Scale realWidth and realHeight + this.realWidth = Math.round(svgWidth * this.sourceScale); + this.realHeight = Math.round(svgHeight * this.sourceScale); + + this._updateDimensions(); + + // Create a canvas element + var canvas = document.createElement('canvas'); + + canvas.width = this.realWidth; + canvas.height = this.realHeight; + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + + // Draw the Svg to the canvas + canvas.getContext('2d').drawImage(this.source, 0, 0, svgWidth, svgHeight, 0, 0, this.realWidth, this.realHeight); + + // Replace the original source image with the canvas + this.origSource = this.source; + this.source = canvas; + + // Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`) + _utils.BaseTextureCache[canvas._pixiId] = this; + + this.isLoading = false; + this._sourceLoaded(); + this.emit('loaded', this); + }; + + /** + * Used internally to update the width, height, and some other tracking vars once + * a source has successfully loaded. + * + * @private + */ + + + BaseTexture.prototype._sourceLoaded = function _sourceLoaded() { + this.hasLoaded = true; + this.update(); + }; + + /** + * Destroys this base texture + * + */ + + + BaseTexture.prototype.destroy = function destroy() { + if (this.imageUrl) { + delete _utils.BaseTextureCache[this.imageUrl]; + delete _utils.TextureCache[this.imageUrl]; + + this.imageUrl = null; + + if (!navigator.isCocoonJS) { + this.source.src = ''; + } + } + // An svg source has both `imageUrl` and `__pixiId`, so no `else if` here + if (this.source && this.source._pixiId) { + delete _utils.BaseTextureCache[this.source._pixiId]; + } + + this.source = null; + + this.dispose(); + + this._destroyed = true; + }; + + /** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + */ + + + BaseTexture.prototype.dispose = function dispose() { + this.emit('dispose', this); + }; + + /** + * Changes the source image of the texture. + * The original source must be an Image element. + * + * @param {string} newSrc - the path of the image + */ + + + BaseTexture.prototype.updateSourceImage = function updateSourceImage(newSrc) { + this.source.src = newSrc; + + this.loadSource(this.source); + }; + + /** + * Helper function that creates a base texture from the given image url. + * If the image is not in the base texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + // new Image() breaks tex loading in some versions of Chrome. + // See https://code.google.com/p/chromium/issues/detail?id=238071 + var image = new Image(); // document.createElement('img'); + + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + image.crossOrigin = (0, _determineCrossOrigin2.default)(imageUrl); + } + + baseTexture = new BaseTexture(image, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + image.src = imageUrl; // Setting this triggers load + + _utils.BaseTextureCache[imageUrl] = baseTexture; + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode) { + if (!canvas._pixiId) { + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[canvas._pixiId]; + + if (!baseTexture) { + baseTexture = new BaseTexture(canvas, scaleMode); + _utils.BaseTextureCache[canvas._pixiId] = baseTexture; + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture based on the source you provide. + * The source can be - image url, image element, canvas element. + * + * @static + * @param {string|HTMLImageElement|HTMLCanvasElement} source - The source to create base texture from. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.from = function from(source, scaleMode, sourceScale) { + if (typeof source === 'string') { + return BaseTexture.fromImage(source, undefined, scaleMode, sourceScale); + } else if (source instanceof HTMLImageElement) { + var imageUrl = source.src; + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + baseTexture = new BaseTexture(source, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + _utils.BaseTextureCache[imageUrl] = baseTexture; + } + + return baseTexture; + } else if (source instanceof HTMLCanvasElement) { + return BaseTexture.fromCanvas(source, scaleMode); + } + + // lets assume its a base texture! + return source; + }; + + return BaseTexture; +}(_eventemitter2.default); + +exports.default = BaseTexture; + +},{"../settings":99,"../utils":120,"../utils/determineCrossOrigin":119,"bit-twiddle":1,"eventemitter3":3}],110:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseRenderTexture = require('./BaseRenderTexture'); + +var _BaseRenderTexture2 = _interopRequireDefault(_BaseRenderTexture); + +var _Texture2 = require('./Texture'); + +var _Texture3 = _interopRequireDefault(_Texture2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A RenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let renderTexture = PIXI.RenderTexture.create(800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let renderTexture = new PIXI.RenderTexture.create(100, 100); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.Texture + * @memberof PIXI + */ +var RenderTexture = function (_Texture) { + _inherits(RenderTexture, _Texture); + + /** + * @param {PIXI.BaseRenderTexture} baseRenderTexture - The renderer used for this RenderTexture + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + */ + function RenderTexture(baseRenderTexture, frame) { + _classCallCheck(this, RenderTexture); + + // support for legacy.. + var _legacyRenderer = null; + + if (!(baseRenderTexture instanceof _BaseRenderTexture2.default)) { + /* eslint-disable prefer-rest-params, no-console */ + var width = arguments[1]; + var height = arguments[2]; + var scaleMode = arguments[3]; + var resolution = arguments[4]; + + // we have an old render texture.. + console.warn('Please use RenderTexture.create(' + width + ', ' + height + ') instead of the ctor directly.'); + _legacyRenderer = arguments[0]; + /* eslint-enable prefer-rest-params, no-console */ + + frame = null; + baseRenderTexture = new _BaseRenderTexture2.default(width, height, scaleMode, resolution); + } + + /** + * The base texture object that this texture uses + * + * @member {BaseTexture} + */ + + var _this = _possibleConstructorReturn(this, _Texture.call(this, baseRenderTexture, frame)); + + _this.legacyRenderer = _legacyRenderer; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = true; + + _this._updateUvs(); + return _this; + } + + /** + * Resizes the RenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + * @param {boolean} doNotResizeBaseTexture - Should the baseTexture.width and height values be resized as well? + */ + + + RenderTexture.prototype.resize = function resize(width, height, doNotResizeBaseTexture) { + // TODO - could be not required.. + this.valid = width > 0 && height > 0; + + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + + if (!doNotResizeBaseTexture) { + this.baseTexture.resize(width, height); + } + + this._updateUvs(); + }; + + /** + * A short hand way of creating a render texture. + * + * @param {number} [width=100] - The width of the render texture + * @param {number} [height=100] - The height of the render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.RenderTexture} The new render texture + */ + + + RenderTexture.create = function create(width, height, scaleMode, resolution) { + return new RenderTexture(new _BaseRenderTexture2.default(width, height, scaleMode, resolution)); + }; + + return RenderTexture; +}(_Texture3.default); + +exports.default = RenderTexture; + +},{"./BaseRenderTexture":108,"./Texture":112}],111:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _ = require('../'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Utility class for maintaining reference to a collection + * of Textures on a single Spritesheet. + * + * @class + * @memberof PIXI + */ +var Spritesheet = function () { + _createClass(Spritesheet, null, [{ + key: 'BATCH_SIZE', + + /** + * The maximum number of Textures to build per process. + * + * @type {number} + * @default 1000 + */ + get: function get() { + return 1000; + } + + /** + * @param {PIXI.BaseTexture} baseTexture Reference to the source BaseTexture object. + * @param {Object} data - Spritesheet image data. + * @param {string} [resolutionFilename] - The filename to consider when determining + * the resolution of the spritesheet. If not provided, the imageUrl will + * be used on the BaseTexture. + */ + + }]); + + function Spritesheet(baseTexture, data) { + var resolutionFilename = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + _classCallCheck(this, Spritesheet); + + /** + * Reference to ths source texture + * @type {PIXI.BaseTexture} + */ + this.baseTexture = baseTexture; + + /** + * Map of spritesheet textures. + * @type {Object} + */ + this.textures = {}; + + /** + * Reference to the original JSON data. + * @type {Object} + */ + this.data = data; + + /** + * The resolution of the spritesheet. + * @type {number} + */ + this.resolution = this._updateResolution(resolutionFilename || this.baseTexture.imageUrl); + + /** + * Map of spritesheet frames. + * @type {Object} + * @private + */ + this._frames = this.data.frames; + + /** + * Collection of frame names. + * @type {string[]} + * @private + */ + this._frameKeys = Object.keys(this._frames); + + /** + * Current batch index being processed. + * @type {number} + * @private + */ + this._batchIndex = 0; + + /** + * Callback when parse is completed. + * @type {Function} + * @private + */ + this._callback = null; + } + + /** + * Generate the resolution from the filename or fallback + * to the meta.scale field of the JSON data. + * + * @private + * @param {string} resolutionFilename - The filename to use for resolving + * the default resolution. + * @return {number} Resolution to use for spritesheet. + */ + + + Spritesheet.prototype._updateResolution = function _updateResolution(resolutionFilename) { + var scale = this.data.meta.scale; + + // Use a defaultValue of `null` to check if a url-based resolution is set + var resolution = (0, _utils.getResolutionOfUrl)(resolutionFilename, null); + + // No resolution found via URL + if (resolution === null) { + // Use the scale value or default to 1 + resolution = scale !== undefined ? parseFloat(scale) : 1; + } + + // For non-1 resolutions, update baseTexture + if (resolution !== 1) { + this.baseTexture.resolution = resolution; + this.baseTexture.update(); + } + + return resolution; + }; + + /** + * Parser spritesheet from loaded data. This is done asynchronously + * to prevent creating too many Texture within a single process. + * + * @param {Function} callback - Callback when complete returns + * a map of the Textures for this spritesheet. + */ + + + Spritesheet.prototype.parse = function parse(callback) { + this._batchIndex = 0; + this._callback = callback; + + if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) { + this._processFrames(0); + this._parseComplete(); + } else { + this._nextBatch(); + } + }; + + /** + * Process a batch of frames + * + * @private + * @param {number} initialFrameIndex - The index of frame to start. + */ + + + Spritesheet.prototype._processFrames = function _processFrames(initialFrameIndex) { + var frameIndex = initialFrameIndex; + var maxFrames = Spritesheet.BATCH_SIZE; + + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { + var i = this._frameKeys[frameIndex]; + var rect = this._frames[i].frame; + + if (rect) { + var frame = null; + var trim = null; + var orig = new _.Rectangle(0, 0, this._frames[i].sourceSize.w / this.resolution, this._frames[i].sourceSize.h / this.resolution); + + if (this._frames[i].rotated) { + frame = new _.Rectangle(rect.x / this.resolution, rect.y / this.resolution, rect.h / this.resolution, rect.w / this.resolution); + } else { + frame = new _.Rectangle(rect.x / this.resolution, rect.y / this.resolution, rect.w / this.resolution, rect.h / this.resolution); + } + + // Check to see if the sprite is trimmed + if (this._frames[i].trimmed) { + trim = new _.Rectangle(this._frames[i].spriteSourceSize.x / this.resolution, this._frames[i].spriteSourceSize.y / this.resolution, rect.w / this.resolution, rect.h / this.resolution); + } + + this.textures[i] = new _.Texture(this.baseTexture, frame, orig, trim, this._frames[i].rotated ? 2 : 0); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage functions + _utils.TextureCache[i] = this.textures[i]; + } + + frameIndex++; + } + }; + + /** + * The parse has completed. + * + * @private + */ + + + Spritesheet.prototype._parseComplete = function _parseComplete() { + var callback = this._callback; + + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); + }; + + /** + * Begin the next batch of textures. + * + * @private + */ + + + Spritesheet.prototype._nextBatch = function _nextBatch() { + var _this = this; + + this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); + this._batchIndex++; + setTimeout(function () { + if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { + _this._nextBatch(); + } else { + _this._parseComplete(); + } + }, 0); + }; + + /** + * Destroy Spritesheet and don't use after this. + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Spritesheet.prototype.destroy = function destroy() { + var destroyBase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + for (var i in this.textures) { + this.textures[i].destroy(); + } + this._frames = null; + this._frameKeys = null; + this.data = null; + this.textures = null; + if (destroyBase) { + this.baseTexture.destroy(); + } + this.baseTexture = null; + }; + + return Spritesheet; +}(); + +exports.default = Spritesheet; + +},{"../":63,"../utils":120}],112:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture = require('./BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _VideoBaseTexture = require('./VideoBaseTexture'); + +var _VideoBaseTexture2 = _interopRequireDefault(_VideoBaseTexture); + +var _TextureUvs = require('./TextureUvs'); + +var _TextureUvs2 = _interopRequireDefault(_TextureUvs); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _math = require('../math'); + +var _utils = require('../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided + * then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * let texture = PIXI.Texture.fromImage('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` + * + * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. + * You can check for this by checking the sprite's _textureID property. + * ```js + * var texture = PIXI.Texture.fromImage('assets/image.svg'); + * var sprite1 = new PIXI.Sprite(texture); + * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file + * ``` + * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var Texture = function (_EventEmitter) { + _inherits(Texture, _EventEmitter); + + /** + * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + * @param {PIXI.Rectangle} [orig] - The area of original texture + * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture + * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8} + */ + function Texture(baseTexture, frame, orig, trim, rotate) { + _classCallCheck(this, Texture); + + /** + * Does this Texture have any frame data assigned to it? + * + * @member {boolean} + */ + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.noFrame = false; + + if (!frame) { + _this.noFrame = true; + frame = new _math.Rectangle(0, 0, 1, 1); + } + + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @member {PIXI.BaseTexture} + */ + _this.baseTexture = baseTexture; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @member {PIXI.Rectangle} + */ + _this._frame = frame; + + /** + * This is the trimmed area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @member {boolean} + */ + _this.requiresUpdate = false; + + /** + * The WebGL UV data cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + _this._uvs = null; + + /** + * This is the area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + + _this._rotate = Number(rotate || 0); + + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); + } + + if (baseTexture.hasLoaded) { + if (_this.noFrame) { + frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + + // if there is no frame we should monitor for any base texture changes.. + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + _this.frame = frame; + } else { + baseTexture.once('loaded', _this.onBaseTextureLoaded, _this); + } + + /** + * Fired when the texture is updated. This happens if the frame or the baseTexture is updated. + * + * @event update + * @memberof PIXI.Texture# + * @protected + */ + + _this._updateID = 0; + + /** + * Extra field for extra plugins. May contain clamp settings and some matrices + * @type {Object} + */ + _this.transform = null; + return _this; + } + + /** + * Updates this texture on the gpu. + * + */ + + + Texture.prototype.update = function update() { + this.baseTexture.update(); + }; + + /** + * Called when the base texture is loaded + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureLoaded = function onBaseTextureLoaded(baseTexture) { + this._updateID++; + + // TODO this code looks confusing.. boo to abusing getters and setters! + if (this.noFrame) { + this.frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } else { + this.frame = this._frame; + } + + this.baseTexture.on('update', this.onBaseTextureUpdated, this); + this.emit('update', this); + }; + + /** + * Called when the base texture is updated + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated(baseTexture) { + this._updateID++; + + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Texture.prototype.destroy = function destroy(destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destroyed too.. + if (_utils.TextureCache[this.baseTexture.imageUrl]) { + delete _utils.TextureCache[this.baseTexture.imageUrl]; + } + + this.baseTexture.destroy(); + } + + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); + + this.baseTexture = null; + } + + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + + this.valid = false; + + this.off('dispose', this.dispose, this); + this.off('update', this.update, this); + }; + + /** + * Creates a new texture object that acts the same as this one. + * + * @return {PIXI.Texture} The new texture + */ + + + Texture.prototype.clone = function clone() { + return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); + }; + + /** + * Updates the internal WebGL UV cache. + * + * @protected + */ + + + Texture.prototype._updateUvs = function _updateUvs() { + if (!this._uvs) { + this._uvs = new _TextureUvs2.default(); + } + + this._uvs.set(this._frame, this.baseTexture, this.rotate); + + this._updateID++; + }; + + /** + * Helper function that creates a Texture object from the given image url. + * If the image is not in the texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var texture = _utils.TextureCache[imageUrl]; + + if (!texture) { + texture = new Texture(_BaseTexture2.default.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); + _utils.TextureCache[imageUrl] = texture; + } + + return texture; + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return texture; + }; + + /** + * Helper function that creates a new Texture based on the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromCanvas = function fromCanvas(canvas, scaleMode) { + return new Texture(_BaseTexture2.default.fromCanvas(canvas, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the given video element. + * + * @static + * @param {HTMLVideoElement|string} video - The URL or actual element of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideo = function fromVideo(video, scaleMode) { + if (typeof video === 'string') { + return Texture.fromVideoUrl(video, scaleMode); + } + + return new Texture(_VideoBaseTexture2.default.fromVideo(video, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the video url. + * + * @static + * @param {string} videoUrl - URL of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideoUrl = function fromVideoUrl(videoUrl, scaleMode) { + return new Texture(_VideoBaseTexture2.default.fromUrl(videoUrl, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} + * source - Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.from = function from(source) { + // TODO auto detect cross origin.. + // TODO pass in scale mode? + if (typeof source === 'string') { + var texture = _utils.TextureCache[source]; + + if (!texture) { + // check if its a video.. + var isVideo = source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/) !== null; + + if (isVideo) { + return Texture.fromVideoUrl(source); + } + + return Texture.fromImage(source); + } + + return texture; + } else if (source instanceof HTMLImageElement) { + return new Texture(_BaseTexture2.default.from(source)); + } else if (source instanceof HTMLCanvasElement) { + return Texture.fromCanvas(source); + } else if (source instanceof HTMLVideoElement) { + return Texture.fromVideo(source); + } else if (source instanceof _BaseTexture2.default) { + return new Texture(source); + } + + // lets assume its a texture! + return source; + }; + + /** + * Create a texture from a source and add to the cache. + * + * @static + * @param {HTMLImageElement|HTMLCanvasElement} source - The input source. + * @param {String} imageUrl - File name of texture, for cache and resolving resolution. + * @param {String} [name] - Human readible name for the texture cache. If no name is + * specified, only `imageUrl` will be used as the cache ID. + * @return {PIXI.Texture} Output texture + */ + + + Texture.fromLoader = function fromLoader(source, imageUrl, name) { + var baseTexture = new _BaseTexture2.default(source, undefined, (0, _utils.getResolutionOfUrl)(imageUrl)); + var texture = new Texture(baseTexture); + + baseTexture.imageUrl = imageUrl; + + // No name, use imageUrl instead + if (!name) { + name = imageUrl; + } + + // lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions + _utils.BaseTextureCache[name] = baseTexture; + _utils.TextureCache[name] = texture; + + // also add references by url if they are different. + if (name !== imageUrl) { + _utils.BaseTextureCache[imageUrl] = baseTexture; + _utils.TextureCache[imageUrl] = texture; + } + + return texture; + }; + + /** + * Adds a texture to the global TextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the texture will be stored against. + */ + + + Texture.addTextureToCache = function addTextureToCache(texture, id) { + _utils.TextureCache[id] = texture; + }; + + /** + * Remove a texture from the global TextureCache. + * + * @static + * @param {string} id - The id of the texture to be removed + * @return {PIXI.Texture} The texture that was removed + */ + + + Texture.removeTextureFromCache = function removeTextureFromCache(id) { + var texture = _utils.TextureCache[id]; + + delete _utils.TextureCache[id]; + delete _utils.BaseTextureCache[id]; + + return texture; + }; + + /** + * The frame specifies the region of the base texture that this texture uses. + * + * @member {PIXI.Rectangle} + */ + + + _createClass(Texture, [{ + key: 'frame', + get: function get() { + return this._frame; + }, + set: function set(frame) // eslint-disable-line require-jsdoc + { + this._frame = frame; + + this.noFrame = false; + + if (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height) { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + ('X: ' + frame.x + ' + ' + frame.width + ' > ' + this.baseTexture.width + ' ') + ('Y: ' + frame.y + ' + ' + frame.height + ' > ' + this.baseTexture.height)); + } + + // this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + this.valid = frame && frame.width && frame.height && this.baseTexture.hasLoaded; + + if (!this.trim && !this.rotate) { + this.orig = frame; + } + + if (this.valid) { + this._updateUvs(); + } + } + + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.GroupD8} for explanation + * + * @member {number} + */ + + }, { + key: 'rotate', + get: function get() { + return this._rotate; + }, + set: function set(rotate) // eslint-disable-line require-jsdoc + { + this._rotate = rotate; + if (this.valid) { + this._updateUvs(); + } + } + + /** + * The width of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'width', + get: function get() { + return this.orig.width; + } + + /** + * The height of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.orig.height; + } + }]); + + return Texture; +}(_eventemitter2.default); + +exports.default = Texture; + + +function createWhiteTexture() { + var canvas = document.createElement('canvas'); + + canvas.width = 10; + canvas.height = 10; + + var context = canvas.getContext('2d'); + + context.fillStyle = 'white'; + context.fillRect(0, 0, 10, 10); + + return new Texture(new _BaseTexture2.default(canvas)); +} + +function removeAllHandlers(tex) { + tex.destroy = function _emptyDestroy() {/* empty */}; + tex.on = function _emptyOn() {/* empty */}; + tex.once = function _emptyOnce() {/* empty */}; + tex.emit = function _emptyEmit() {/* empty */}; +} + +/** + * An empty texture, used often to not have to create multiple empty textures. + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.EMPTY = new Texture(new _BaseTexture2.default()); +removeAllHandlers(Texture.EMPTY); + +/** + * A white texture of 10x10 size, used for graphics and other things + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.WHITE = createWhiteTexture(); +removeAllHandlers(Texture.WHITE); + +},{"../math":68,"../utils":120,"./BaseTexture":109,"./TextureUvs":113,"./VideoBaseTexture":114,"eventemitter3":3}],113:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _GroupD = require('../math/GroupD8'); + +var _GroupD2 = _interopRequireDefault(_GroupD); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A standard object to store the Uvs of a texture + * + * @class + * @private + * @memberof PIXI + */ +var TextureUvs = function () { + /** + * + */ + function TextureUvs() { + _classCallCheck(this, TextureUvs); + + this.x0 = 0; + this.y0 = 0; + + this.x1 = 1; + this.y1 = 0; + + this.x2 = 1; + this.y2 = 1; + + this.x3 = 0; + this.y3 = 1; + + this.uvsUint32 = new Uint32Array(4); + } + + /** + * Sets the texture Uvs based on the given frame information. + * + * @private + * @param {PIXI.Rectangle} frame - The frame of the texture + * @param {PIXI.Rectangle} baseFrame - The base frame of the texture + * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8} + */ + + + TextureUvs.prototype.set = function set(frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + + // coordinates of center + var cX = frame.x / tw + w2; + var cY = frame.y / th + h2; + + rotate = _GroupD2.default.add(rotate, _GroupD2.default.NW); // NW is top-left corner + this.x0 = cX + w2 * _GroupD2.default.uX(rotate); + this.y0 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + w2 * _GroupD2.default.uX(rotate); + this.y1 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x2 = cX + w2 * _GroupD2.default.uX(rotate); + this.y2 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x3 = cX + w2 * _GroupD2.default.uX(rotate); + this.y3 = cY + h2 * _GroupD2.default.uY(rotate); + } else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + + this.uvsUint32[0] = (this.y0 * 65535 & 0xFFFF) << 16 | this.x0 * 65535 & 0xFFFF; + this.uvsUint32[1] = (this.y1 * 65535 & 0xFFFF) << 16 | this.x1 * 65535 & 0xFFFF; + this.uvsUint32[2] = (this.y2 * 65535 & 0xFFFF) << 16 | this.x2 * 65535 & 0xFFFF; + this.uvsUint32[3] = (this.y3 * 65535 & 0xFFFF) << 16 | this.x3 * 65535 & 0xFFFF; + }; + + return TextureUvs; +}(); + +exports.default = TextureUvs; + +},{"../math/GroupD8":64}],114:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _utils = require('../utils'); + +var _ticker = require('../ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture of a [playing] Video. + * + * Video base textures mimic Pixi BaseTexture.from.... method in their creation process. + * + * This can be used in several ways, such as: + * + * ```js + * let texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4'); + * + * let texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' }); + * + * let texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']); + * + * let texture = PIXI.VideoBaseTexture.fromUrls([ + * { src: '/video.webm', mime: 'video/webm' }, + * { src: '/video.mp4', mime: 'video/mp4' } + * ]); + * ``` + * + * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/). + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var VideoBaseTexture = function (_BaseTexture) { + _inherits(VideoBaseTexture, _BaseTexture); + + /** + * @param {HTMLVideoElement} source - Video source + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + */ + function VideoBaseTexture(source, scaleMode) { + _classCallCheck(this, VideoBaseTexture); + + if (!source) { + throw new Error('No video source element specified.'); + } + + // hook in here to check if video is already available. + // BaseTexture looks for a source.complete boolean, plus width & height. + + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + source.complete = true; + } + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, source, scaleMode)); + + _this.width = source.videoWidth; + _this.height = source.videoHeight; + + _this._autoUpdate = true; + _this._isAutoUpdating = false; + + /** + * When set to true will automatically play videos used by this texture once + * they are loaded. If false, it will not modify the playing state. + * + * @member {boolean} + * @default true + */ + _this.autoPlay = true; + + _this.update = _this.update.bind(_this); + _this._onCanPlay = _this._onCanPlay.bind(_this); + + source.addEventListener('play', _this._onPlayStart.bind(_this)); + source.addEventListener('pause', _this._onPlayStop.bind(_this)); + _this.hasLoaded = false; + _this.__loaded = false; + + if (!_this._isSourceReady()) { + source.addEventListener('canplay', _this._onCanPlay); + source.addEventListener('canplaythrough', _this._onCanPlay); + } else { + _this._onCanPlay(); + } + return _this; + } + + /** + * Returns true if the underlying source is playing. + * + * @private + * @return {boolean} True if playing. + */ + + + VideoBaseTexture.prototype._isSourcePlaying = function _isSourcePlaying() { + var source = this.source; + + return source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2; + }; + + /** + * Returns true if the underlying source is ready for playing. + * + * @private + * @return {boolean} True if ready. + */ + + + VideoBaseTexture.prototype._isSourceReady = function _isSourceReady() { + return this.source.readyState === 3 || this.source.readyState === 4; + }; + + /** + * Runs the update loop when the video is ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStart = function _onPlayStart() { + // Just in case the video has not received its can play even yet.. + if (!this.hasLoaded) { + this._onCanPlay(); + } + + if (!this._isAutoUpdating && this.autoUpdate) { + ticker.shared.add(this.update, this); + this._isAutoUpdating = true; + } + }; + + /** + * Fired when a pause event is triggered, stops the update loop + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStop = function _onPlayStop() { + if (this._isAutoUpdating) { + ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } + }; + + /** + * Fired when the video is loaded and ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onCanPlay = function _onCanPlay() { + this.hasLoaded = true; + + if (this.source) { + this.source.removeEventListener('canplay', this._onCanPlay); + this.source.removeEventListener('canplaythrough', this._onCanPlay); + + this.width = this.source.videoWidth; + this.height = this.source.videoHeight; + + // prevent multiple loaded dispatches.. + if (!this.__loaded) { + this.__loaded = true; + this.emit('loaded', this); + } + + if (this._isSourcePlaying()) { + this._onPlayStart(); + } else if (this.autoPlay) { + this.source.play(); + } + } + }; + + /** + * Destroys this texture + * + */ + + + VideoBaseTexture.prototype.destroy = function destroy() { + if (this._isAutoUpdating) { + ticker.shared.remove(this.update, this); + } + + if (this.source && this.source._pixiId) { + delete _utils.BaseTextureCache[this.source._pixiId]; + delete this.source._pixiId; + } + + _BaseTexture.prototype.destroy.call(this); + }; + + /** + * Mimic Pixi BaseTexture.from.... method. + * + * @static + * @param {HTMLVideoElement} video - Video to create texture from + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromVideo = function fromVideo(video, scaleMode) { + if (!video._pixiId) { + video._pixiId = 'video_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[video._pixiId]; + + if (!baseTexture) { + baseTexture = new VideoBaseTexture(video, scaleMode); + _utils.BaseTextureCache[video._pixiId] = baseTexture; + } + + return baseTexture; + }; + + /** + * Helper function that creates a new BaseTexture based on the given video element. + * This BaseTexture can then be used to create a texture + * + * @static + * @param {string|object|string[]|object[]} videoSrc - The URL(s) for the video. + * @param {string} [videoSrc.src] - One of the source urls for the video + * @param {string} [videoSrc.mime] - The mimetype of the video (e.g. 'video/mp4'). If not specified + * the url's extension will be used as the second part of the mime type. + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromUrl = function fromUrl(videoSrc, scaleMode) { + var video = document.createElement('video'); + + video.setAttribute('webkit-playsinline', ''); + video.setAttribute('playsinline', ''); + + // array of objects or strings + if (Array.isArray(videoSrc)) { + for (var i = 0; i < videoSrc.length; ++i) { + video.appendChild(createSource(videoSrc[i].src || videoSrc[i], videoSrc[i].mime)); + } + } + // single object or string + else { + video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); + } + + video.load(); + + return VideoBaseTexture.fromVideo(video, scaleMode); + }; + + /** + * Should the base texture automatically update itself, set to true by default + * + * @member {boolean} + */ + + + _createClass(VideoBaseTexture, [{ + key: 'autoUpdate', + get: function get() { + return this._autoUpdate; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + + if (!this._autoUpdate && this._isAutoUpdating) { + ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } else if (this._autoUpdate && !this._isAutoUpdating) { + ticker.shared.add(this.update, this); + this._isAutoUpdating = true; + } + } + } + }]); + + return VideoBaseTexture; +}(_BaseTexture3.default); + +exports.default = VideoBaseTexture; + + +VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; + +function createSource(path, type) { + if (!type) { + type = 'video/' + path.substr(path.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = path; + source.type = type; + + return source; +} + +},{"../ticker":116,"../utils":120,"./BaseTexture":109}],115:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// Internal event used by composed emitter +var TICK = 'tick'; + +/** + * A Ticker class that runs an update loop that other objects listen to. + * This class is composed around an EventEmitter object to add listeners + * meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, + * e.g. When the ticker is started and the emitter has listeners. + * + * @class + * @memberof PIXI.ticker + */ + +var Ticker = function () { + /** + * + */ + function Ticker() { + var _this = this; + + _classCallCheck(this, Ticker); + + /** + * Internal emitter used to fire 'tick' event + * @private + */ + this._emitter = new _eventemitter2.default(); + + /** + * Internal current frame request ID + * @private + */ + this._requestId = null; + + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + * @private + */ + this._maxElapsedMS = 100; + + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.ticker.Ticker#start} automatically + * when a listener is added. + * + * @member {boolean} + * @default false + */ + this.autoStart = false; + + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS} + * and is scaled with {@link PIXI.ticker.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * + * @member {number} + * @default 1 + */ + this.deltaTime = 1; + + /** + * Time elapsed in milliseconds from last frame to this frame. + * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime} + * is based, this value is neither capped nor scaled. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * Defaults to target frame time + * + * @member {number} + * @default 16.66 + */ + this.elapsedMS = 1 / _settings2.default.TARGET_FPMS; + + /** + * The last time {@link PIXI.ticker.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default 0 + */ + this.lastTime = 0; + + /** + * Factor of current {@link PIXI.ticker.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + * + * @member {number} + * @default 1 + */ + this.speed = 1; + + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.ticker.Ticker#start} has been called. + * `false` if {@link PIXI.ticker.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.ticker.Ticker#autoStart} being `true` + * and a listener is added. + * + * @member {boolean} + * @default false + */ + this.started = false; + + /** + * Internal tick method bound to ticker instance. + * This is because in early 2015, Function.bind + * is still 60% slower in high performance scenarios. + * Also separating frame requests from update method + * so listeners may be called at any time and with + * any animation API, just invoke ticker.update(time). + * + * @private + * @param {number} time - Time since last tick. + */ + this._tick = function (time) { + _this._requestId = null; + + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._emitter.listeners(TICK, true)) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * + * @private + */ + + + Ticker.prototype._requestIfNeeded = function _requestIfNeeded() { + if (this._requestId === null && this._emitter.listeners(TICK, true)) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._requestId = requestAnimationFrame(this._tick); + } + }; + + /** + * Conditionally cancels a pending animation frame. + * + * @private + */ + + + Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; + + /** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * + * @private + */ + + + Ticker.prototype._startIfPossible = function _startIfPossible() { + if (this.started) { + this._requestIfNeeded(); + } else if (this.autoStart) { + this.start(); + } + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#on} internally for the + * internal 'tick' event. It checks if the emitter has listeners, + * and if so it requests a new animation frame at this point. + * + * @param {Function} fn - The listener function to be added for updates + * @param {Function} [context] - The listener context + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.add = function add(fn, context) { + this._emitter.on(TICK, fn, context); + + this._startIfPossible(); + + return this; + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#once} internally for the + * internal 'tick' event. It checks if the emitter has listeners, + * and if so it requests a new animation frame at this point. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context] - The listener context + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.addOnce = function addOnce(fn, context) { + this._emitter.once(TICK, fn, context); + + this._startIfPossible(); + + return this; + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#off} internally for 'tick' event. + * It checks if the emitter has listeners for 'tick' event. + * If it does, then it cancels the animation frame. + * + * @param {Function} [fn] - The listener function to be removed + * @param {Function} [context] - The listener context to be removed + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.remove = function remove(fn, context) { + this._emitter.off(TICK, fn, context); + + if (!this._emitter.listeners(TICK, true)) { + this._cancelIfNeeded(); + } + + return this; + }; + + /** + * Starts the ticker. If the ticker has listeners + * a new animation frame is requested at this point. + */ + + + Ticker.prototype.start = function start() { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + }; + + /** + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. + */ + + + Ticker.prototype.stop = function stop() { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; + + /** + * Triggers an update. An update entails setting the + * current {@link PIXI.ticker.Ticker#elapsedMS}, + * the current {@link PIXI.ticker.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.ticker.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + + + Ticker.prototype.update = function update() { + var currentTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : performance.now(); + + var elapsedMS = void 0; + + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + + this.deltaTime = elapsedMS * _settings2.default.TARGET_FPMS * this.speed; + + // Invoke listeners added to internal emitter + this._emitter.emit(TICK, this.deltaTime); + } else { + this.deltaTime = this.elapsedMS = 0; + } + + this.lastTime = currentTime; + }; + + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.ticker.Ticker#speed}, which is specific + * to scaling {@link PIXI.ticker.Ticker#deltaTime}. + * + * @member {number} + * @readonly + */ + + + _createClass(Ticker, [{ + key: 'FPS', + get: function get() { + return 1000 / this.elapsedMS; + } + + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.ticker.Ticker#update}. + * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.settings.TARGET_FPMS * 1000`. + * + * @member {number} + * @default 10 + */ + + }, { + key: 'minFPS', + get: function get() { + return 1000 / this._maxElapsedMS; + }, + set: function set(fps) // eslint-disable-line require-jsdoc + { + // Clamp: 0 to TARGET_FPMS + var minFPMS = Math.min(Math.max(0, fps) / 1000, _settings2.default.TARGET_FPMS); + + this._maxElapsedMS = 1 / minFPMS; + } + }]); + + return Ticker; +}(); + +exports.default = Ticker; + +},{"../settings":99,"eventemitter3":3}],116:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Ticker = exports.shared = undefined; + +var _Ticker = require('./Ticker'); + +var _Ticker2 = _interopRequireDefault(_Ticker); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The shared ticker instance used by {@link PIXI.extras.AnimatedSprite}. + * and by {@link PIXI.interaction.InteractionManager}. + * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` + * for this instance. Please follow the examples for usage, including + * how to opt-out of auto-starting the shared ticker. + * + * @example + * let ticker = PIXI.ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(800, 600); + * let stage = new PIXI.Container(); + * let interactionManager = PIXI.interaction.InteractionManager(renderer); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * + * @type {PIXI.ticker.Ticker} + * @memberof PIXI.ticker + */ +var shared = new _Ticker2.default(); + +shared.autoStart = true; + +/** + * @namespace PIXI.ticker + */ +exports.shared = shared; +exports.Ticker = _Ticker2.default; + +},{"./Ticker":115}],117:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = canUploadSameBuffer; +function canUploadSameBuffer() { + // Uploading the same buffer multiple times in a single frame can cause perf issues. + // Apparent on IOS so only check for that at the moment + // this check may become more complex if this issue pops up elsewhere. + var ios = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform); + + return !ios; +} + +},{}],118:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = createIndicesForQuads; +/** + * Generic Mask Stack data structure + * + * @memberof PIXI + * @function createIndicesForQuads + * @private + * @param {number} size - Number of quads + * @return {Uint16Array} indices + */ +function createIndicesForQuads(size) { + // the total number of indices in our array, there are 6 points per quad. + + var totalIndices = size * 6; + + var indices = new Uint16Array(totalIndices); + + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + indices[i + 0] = j + 0; + indices[i + 1] = j + 1; + indices[i + 2] = j + 2; + indices[i + 3] = j + 0; + indices[i + 4] = j + 2; + indices[i + 5] = j + 3; + } + + return indices; +} + +},{}],119:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = determineCrossOrigin; + +var _url2 = require('url'); + +var _url3 = _interopRequireDefault(_url2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var tempAnchor = void 0; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +function determineCrossOrigin(url) { + var loc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location; + + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url3.default.parse(tempAnchor.href); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +} + +},{"url":28}],120:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BaseTextureCache = exports.TextureCache = exports.mixins = exports.pluginTarget = exports.EventEmitter = exports.isMobile = undefined; +exports.uid = uid; +exports.hex2rgb = hex2rgb; +exports.hex2string = hex2string; +exports.rgb2hex = rgb2hex; +exports.getResolutionOfUrl = getResolutionOfUrl; +exports.decomposeDataUri = decomposeDataUri; +exports.getUrlFileExtension = getUrlFileExtension; +exports.getSvgSize = getSvgSize; +exports.skipHello = skipHello; +exports.sayHello = sayHello; +exports.isWebGLSupported = isWebGLSupported; +exports.sign = sign; +exports.removeItems = removeItems; +exports.destroyTextureCache = destroyTextureCache; +exports.clearTextureCache = clearTextureCache; + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _pluginTarget = require('./pluginTarget'); + +var _pluginTarget2 = _interopRequireDefault(_pluginTarget); + +var _mixin = require('./mixin'); + +var mixins = _interopRequireWildcard(_mixin); + +var _ismobilejs = require('ismobilejs'); + +var isMobile = _interopRequireWildcard(_ismobilejs); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var nextUid = 0; +var saidHello = false; + +/** + * @namespace PIXI.utils + */ +exports.isMobile = isMobile; +exports.EventEmitter = _eventemitter2.default; +exports.pluginTarget = _pluginTarget2.default; +exports.mixins = mixins; + +/** + * Gets the next unique identifier + * + * @memberof PIXI.utils + * @function uid + * @return {number} The next unique identifier to use. + */ + +function uid() { + return ++nextUid; +} + +/** + * Converts a hex color number to an [R, G, B] array + * + * @memberof PIXI.utils + * @function hex2rgb + * @param {number} hex - The number to convert + * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one + * @return {number[]} An array representing the [R, G, B] of the color. + */ +function hex2rgb(hex, out) { + out = out || []; + + out[0] = (hex >> 16 & 0xFF) / 255; + out[1] = (hex >> 8 & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + + return out; +} + +/** + * Converts a hex color number to a string. + * + * @memberof PIXI.utils + * @function hex2string + * @param {number} hex - Number in hex + * @return {string} The string color. + */ +function hex2string(hex) { + hex = hex.toString(16); + hex = '000000'.substr(0, 6 - hex.length) + hex; + + return '#' + hex; +} + +/** + * Converts a color as an [R, G, B] array to a hex number + * + * @memberof PIXI.utils + * @function rgb2hex + * @param {number[]} rgb - rgb array + * @return {number} The color number + */ +function rgb2hex(rgb) { + return (rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + (rgb[2] * 255 | 0); +} + +/** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * + * @memberof PIXI.utils + * @function getResolutionOfUrl + * @param {string} url - the image path + * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. + * @return {number} resolution / device pixel ratio of an asset + */ +function getResolutionOfUrl(url, defaultValue) { + var resolution = _settings2.default.RETINA_PREFIX.exec(url); + + if (resolution) { + return parseFloat(resolution[1]); + } + + return defaultValue !== undefined ? defaultValue : 1; +} + +/** + * Typedef for decomposeDataUri return object. + * + * @typedef {object} DecomposedDataUri + * @property {mediaType} Media type, eg. `image` + * @property {subType} Sub type, eg. `png` + * @property {encoding} Data encoding, eg. `base64` + * @property {data} The actual data + */ + +/** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. + * + * @memberof PIXI.utils + * @function decomposeDataUri + * @param {string} dataUri - the data URI to check + * @return {DecomposedDataUri|undefined} The decomposed data uri or undefined + */ +function decomposeDataUri(dataUri) { + var dataUriMatch = _const.DATA_URI.exec(dataUri); + + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + encoding: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + data: dataUriMatch[4] + }; + } + + return undefined; +} + +/** + * Get type of the image by regexp for extension. Returns undefined for unknown extensions. + * + * @memberof PIXI.utils + * @function getUrlFileExtension + * @param {string} url - the image path + * @return {string|undefined} image extension + */ +function getUrlFileExtension(url) { + var extension = _const.URL_FILE_EXTENSION.exec(url); + + if (extension) { + return extension[1].toLowerCase(); + } + + return undefined; +} + +/** + * Typedef for Size object. + * + * @typedef {object} Size + * @property {width} Width component + * @property {height} Height component + */ + +/** + * Get size from an svg string using regexp. + * + * @memberof PIXI.utils + * @function getSvgSize + * @param {string} svgString - a serialized svg element + * @return {Size|undefined} image extension + */ +function getSvgSize(svgString) { + var sizeMatch = _const.SVG_SIZE.exec(svgString); + var size = {}; + + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); + size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); + } + + return size; +} + +/** + * Skips the hello message of renderers that are created after this is run. + * + * @function skipHello + * @memberof PIXI.utils + */ +function skipHello() { + saidHello = true; +} + +/** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever makes you a jerk face. + * + * @static + * @function sayHello + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ +function sayHello(type) { + if (saidHello) { + return; + } + + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = ['\n %c %c %c Pixi.js ' + _const.VERSION + ' - \u2730 ' + type + ' \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n', 'background: #ff66a5; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff66a5; background: #030307; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'background: #ffc3dc; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;']; + + window.console.log.apply(console, args); + } else if (window.console) { + window.console.log('Pixi.js ' + _const.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); + } + + saidHello = true; +} + +/** + * Helper for checking for webgl support + * + * @memberof PIXI.utils + * @function isWebGLSupported + * @return {boolean} is webgl supported + */ +function isWebGLSupported() { + var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; + + try { + if (!window.WebGLRenderingContext) { + return false; + } + + var canvas = document.createElement('canvas'); + var gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); + + var success = !!(gl && gl.getContextAttributes().stencil); + + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + + if (loseContext) { + loseContext.loseContext(); + } + } + + gl = null; + + return success; + } catch (e) { + return false; + } +} + +/** + * Returns sign of number + * + * @memberof PIXI.utils + * @function sign + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ +function sign(n) { + if (n === 0) return 0; + + return n < 0 ? -1 : 1; +} + +/** + * Remove a range of items from an array + * + * @memberof PIXI.utils + * @function removeItems + * @param {Array<*>} arr The target array + * @param {number} startIdx The index to begin removing from (inclusive) + * @param {number} removeCount How many items to remove + */ +function removeItems(arr, startIdx, removeCount) { + var length = arr.length; + + if (startIdx >= length || removeCount === 0) { + return; + } + + removeCount = startIdx + removeCount > length ? length - startIdx : removeCount; + + var len = length - removeCount; + + for (var i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount]; + } + + arr.length = len; +} + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var TextureCache = exports.TextureCache = {}; + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var BaseTextureCache = exports.BaseTextureCache = {}; + +/** + * Destroys all texture in the cache + * + * @memberof PIXI.utils + * @function destroyTextureCache + */ +function destroyTextureCache() { + var key = void 0; + + for (key in TextureCache) { + TextureCache[key].destroy(); + } + for (key in BaseTextureCache) { + BaseTextureCache[key].destroy(); + } +} + +/** + * Removes all textures from cache, but does not destroy them + * + * @memberof PIXI.utils + * @function clearTextureCache + */ +function clearTextureCache() { + var key = void 0; + + for (key in TextureCache) { + delete TextureCache[key]; + } + for (key in BaseTextureCache) { + delete BaseTextureCache[key]; + } +} + +},{"../const":44,"../settings":99,"./mixin":122,"./pluginTarget":123,"eventemitter3":3,"ismobilejs":4}],121:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = maxRecommendedTextures; + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function maxRecommendedTextures(max) { + if (_ismobilejs2.default.tablet || _ismobilejs2.default.phone) { + // check if the res is iphone 6 or higher.. + return 4; + } + + // desktop should be ok + return max; +} + +},{"ismobilejs":4}],122:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.mixin = mixin; +exports.delayMixin = delayMixin; +exports.performMixins = performMixins; +/** + * Mixes all enumerable properties and methods from a source object to a target object. + * + * @memberof PIXI.utils.mixins + * @function mixin + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function mixin(target, source) { + if (!target || !source) return; + // in ES8/ES2017, this would be really easy: + // Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + + // get all the enumerable property keys + var keys = Object.keys(source); + + // loop through properties + for (var i = 0; i < keys.length; ++i) { + var propertyName = keys[i]; + + // Set the property using the property descriptor - this works for accessors and normal value properties + Object.defineProperty(target, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); + } +} + +var mixins = []; + +/** + * Queues a mixin to be handled towards the end of the initialization of PIXI, so that deprecation + * can take effect. + * + * @memberof PIXI.utils.mixins + * @function delayMixin + * @private + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function delayMixin(target, source) { + mixins.push(target, source); +} + +/** + * Handles all mixins queued via delayMixin(). + * + * @memberof PIXI.utils.mixins + * @function performMixins + * @private + */ +function performMixins() { + for (var i = 0; i < mixins.length; i += 2) { + mixin(mixins[i], mixins[i + 1]); + } + mixins.length = 0; +} + +},{}],123:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Mixins functionality to make an object have "plugins". + * + * @example + * function MyObject() {} + * + * pluginTarget.mixin(MyObject); + * + * @mixin + * @memberof PIXI.utils + * @param {object} obj - The object to mix into. + */ +function pluginTarget(obj) { + obj.__plugins = {}; + + /** + * Adds a plugin to an object + * + * @param {string} pluginName - The events that should be listed. + * @param {Function} ctor - The constructor function for the plugin. + */ + obj.registerPlugin = function registerPlugin(pluginName, ctor) { + obj.__plugins[pluginName] = ctor; + }; + + /** + * Instantiates all the plugins of this object + * + */ + obj.prototype.initPlugins = function initPlugins() { + this.plugins = this.plugins || {}; + + for (var o in obj.__plugins) { + this.plugins[o] = new obj.__plugins[o](this); + } + }; + + /** + * Removes all the plugins of this object + * + */ + obj.prototype.destroyPlugins = function destroyPlugins() { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + + this.plugins = null; + }; +} + +exports.default = { + /** + * Mixes in the properties of the pluginTarget into another object + * + * @param {object} obj - The obj to mix into + */ + mixin: function mixin(obj) { + pluginTarget(obj); + } +}; + +},{}],124:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = trimCanvas; +/** + * Trim transparent borders from a canvas + * + * @memberof PIXI + * @function trimCanvas + * @private + * @param {HTMLCanvasElement} canvas - the canvas to trim + * @returns {object} Trim data + */ +function trimCanvas(canvas) { + // https://gist.github.com/remy/784508 + + var width = canvas.width; + var height = canvas.height; + + var context = canvas.getContext('2d'); + var imageData = context.getImageData(0, 0, width, height); + var pixels = imageData.data; + var len = pixels.length; + + var bound = { + top: null, + left: null, + right: null, + bottom: null + }; + var i = void 0; + var x = void 0; + var y = void 0; + + for (i = 0; i < len; i += 4) { + if (pixels[i + 3] !== 0) { + x = i / 4 % width; + y = ~~(i / 4 / width); + + if (bound.top === null) { + bound.top = y; + } + + if (bound.left === null) { + bound.left = x; + } else if (x < bound.left) { + bound.left = x; + } + + if (bound.right === null) { + bound.right = x + 1; + } else if (bound.right < x) { + bound.right = x + 1; + } + + if (bound.bottom === null) { + bound.bottom = y; + } else if (bound.bottom < y) { + bound.bottom = y; + } + } + } + + width = bound.right - bound.left; + height = bound.bottom - bound.top + 1; + + var data = context.getImageData(bound.left, bound.top, width, height); + + return { + height: height, + width: width, + data: data + }; +} + +},{}],125:[function(require,module,exports){ +'use strict'; + +var _core = require('./core'); + +var core = _interopRequireWildcard(_core); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code +function warn(msg) { + /* eslint-disable no-console */ + var stack = new Error().stack; + + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('Deprecation Warning: ', msg); + } else { + // chop off the stack trace which includes pixi.js internal calls + stack = stack.split('\n').splice(3).join('\n'); + + if (console.groupCollapsed) { + console.groupCollapsed('%cDeprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', msg); + console.warn(stack); + console.groupEnd(); + } else { + console.warn('Deprecation Warning: ', msg); + console.warn(stack); + } + } + /* eslint-enable no-console */ +} + +/** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ +core.SpriteBatch = function () { + throw new ReferenceError('SpriteBatch does not exist any more, please use the new ParticleContainer instead.'); +}; + +/** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ +core.AssetLoader = function () { + throw new ReferenceError('The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class.'); +}; + +Object.defineProperties(core, { + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + Stage: { + enumerable: true, + get: function get() { + warn('You do not need to use a PIXI Stage any more, you can simply render any container.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + DisplayObjectContainer: { + enumerable: true, + get: function get() { + warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + Strip: { + enumerable: true, + get: function get() { + warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.'); + + return mesh.Mesh; + } + }, + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + Rope: { + enumerable: true, + get: function get() { + warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.'); + + return mesh.Rope; + } + }, + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + ParticleContainer: { + enumerable: true, + get: function get() { + warn('The ParticleContainer class has been moved to particles.ParticleContainer, ' + 'please use particles.ParticleContainer from now on.'); + + return particles.ParticleContainer; + } + }, + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + MovieClip: { + enumerable: true, + get: function get() { + warn('The MovieClip class has been moved to extras.AnimatedSprite, please use extras.AnimatedSprite.'); + + return extras.AnimatedSprite; + } + }, + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + TilingSprite: { + enumerable: true, + get: function get() { + warn('The TilingSprite class has been moved to extras.TilingSprite, ' + 'please use extras.TilingSprite from now on.'); + + return extras.TilingSprite; + } + }, + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + BitmapText: { + enumerable: true, + get: function get() { + warn('The BitmapText class has been moved to extras.BitmapText, ' + 'please use extras.BitmapText from now on.'); + + return extras.BitmapText; + } + }, + + /** + * @class + * @private + * @name blendModes + * @memberof PIXI + * @see PIXI.BLEND_MODES + * @deprecated since version 3.0.0 + */ + blendModes: { + enumerable: true, + get: function get() { + warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.'); + + return core.BLEND_MODES; + } + }, + + /** + * @class + * @private + * @name scaleModes + * @memberof PIXI + * @see PIXI.SCALE_MODES + * @deprecated since version 3.0.0 + */ + scaleModes: { + enumerable: true, + get: function get() { + warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.'); + + return core.SCALE_MODES; + } + }, + + /** + * @class + * @private + * @name BaseTextureCache + * @memberof PIXI + * @see PIXI.utils.BaseTextureCache + * @deprecated since version 3.0.0 + */ + BaseTextureCache: { + enumerable: true, + get: function get() { + warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, ' + 'please use utils.BaseTextureCache from now on.'); + + return core.utils.BaseTextureCache; + } + }, + + /** + * @class + * @private + * @name TextureCache + * @memberof PIXI + * @see PIXI.utils.TextureCache + * @deprecated since version 3.0.0 + */ + TextureCache: { + enumerable: true, + get: function get() { + warn('The TextureCache class has been moved to utils.TextureCache, ' + 'please use utils.TextureCache from now on.'); + + return core.utils.TextureCache; + } + }, + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + math: { + enumerable: true, + get: function get() { + warn('The math namespace is deprecated, please access members already accessible on PIXI.'); + + return core; + } + }, + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + enumerable: true, + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.Filter; + } + }, + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + TransformManual: { + enumerable: true, + get: function get() { + warn('TransformManual has been renamed to TransformBase, please update your pixi-spine'); + + return core.TransformBase; + } + }, + + /** + * @static + * @constant + * @name PIXI.TARGET_FPMS + * @see PIXI.settings.TARGET_FPMS + * @deprecated since version 4.2.0 + */ + TARGET_FPMS: { + enumerable: true, + get: function get() { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + return core.settings.TARGET_FPMS; + }, + set: function set(value) { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + core.settings.TARGET_FPMS = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.FILTER_RESOLUTION + * @see PIXI.settings.FILTER_RESOLUTION + * @deprecated since version 4.2.0 + */ + FILTER_RESOLUTION: { + enumerable: true, + get: function get() { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + return core.settings.FILTER_RESOLUTION; + }, + set: function set(value) { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + core.settings.FILTER_RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RESOLUTION + * @see PIXI.settings.RESOLUTION + * @deprecated since version 4.2.0 + */ + RESOLUTION: { + enumerable: true, + get: function get() { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + return core.settings.RESOLUTION; + }, + set: function set(value) { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + core.settings.RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.MIPMAP_TEXTURES + * @see PIXI.settings.MIPMAP_TEXTURES + * @deprecated since version 4.2.0 + */ + MIPMAP_TEXTURES: { + enumerable: true, + get: function get() { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + return core.settings.MIPMAP_TEXTURES; + }, + set: function set(value) { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + core.settings.MIPMAP_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_BATCH_SIZE + * @see PIXI.settings.SPRITE_BATCH_SIZE + * @deprecated since version 4.2.0 + */ + SPRITE_BATCH_SIZE: { + enumerable: true, + get: function get() { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + return core.settings.SPRITE_BATCH_SIZE; + }, + set: function set(value) { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + core.settings.SPRITE_BATCH_SIZE = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_MAX_TEXTURES + * @see PIXI.settings.SPRITE_MAX_TEXTURES + * @deprecated since version 4.2.0 + */ + SPRITE_MAX_TEXTURES: { + enumerable: true, + get: function get() { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + return core.settings.SPRITE_MAX_TEXTURES; + }, + set: function set(value) { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + core.settings.SPRITE_MAX_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RETINA_PREFIX + * @see PIXI.settings.RETINA_PREFIX + * @deprecated since version 4.2.0 + */ + RETINA_PREFIX: { + enumerable: true, + get: function get() { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + return core.settings.RETINA_PREFIX; + }, + set: function set(value) { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + core.settings.RETINA_PREFIX = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.DEFAULT_RENDER_OPTIONS + * @see PIXI.settings.RENDER_OPTIONS + * @deprecated since version 4.2.0 + */ + DEFAULT_RENDER_OPTIONS: { + enumerable: true, + get: function get() { + warn('PIXI.DEFAULT_RENDER_OPTIONS has been deprecated, please use PIXI.settings.DEFAULT_RENDER_OPTIONS'); + + return core.settings.RENDER_OPTIONS; + } + } +}); + +// Move the default properties to settings +var defaults = [{ parent: 'TRANSFORM_MODE', target: 'TRANSFORM_MODE' }, { parent: 'GC_MODES', target: 'GC_MODE' }, { parent: 'WRAP_MODES', target: 'WRAP_MODE' }, { parent: 'SCALE_MODES', target: 'SCALE_MODE' }, { parent: 'PRECISION', target: 'PRECISION_FRAGMENT' }]; + +var _loop = function _loop(i) { + var deprecation = defaults[i]; + + Object.defineProperty(core[deprecation.parent], 'DEFAULT', { + enumerable: true, + get: function get() { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, please use PIXI.settings.' + deprecation.target); + + return core.settings[deprecation.target]; + }, + set: function set(value) { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, please use PIXI.settings.' + deprecation.target); + + core.settings[deprecation.target] = value; + } + }); +}; + +for (var i = 0; i < defaults.length; i++) { + _loop(i); +} + +Object.defineProperties(core.settings, { + + /** + * @static + * @name PRECISION + * @memberof PIXI.settings + * @see PIXI.PRECISION + * @deprecated since version 4.4.0 + */ + PRECISION: { + enumerable: true, + get: function get() { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + return core.settings.PRECISION_FRAGMENT; + }, + set: function set(value) { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + core.settings.PRECISION_FRAGMENT = value; + } + } +}); + +Object.defineProperties(extras, { + + /** + * @class + * @name MovieClip + * @memberof PIXI.extras + * @see PIXI.extras.AnimatedSprite + * @deprecated since version 4.2.0 + */ + MovieClip: { + enumerable: true, + get: function get() { + warn('The MovieClip class has been renamed to AnimatedSprite, please use AnimatedSprite from now on.'); + + return extras.AnimatedSprite; + } + } +}); + +core.DisplayObject.prototype.generateTexture = function generateTexture(renderer, scaleMode, resolution) { + warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); + + return renderer.generateTexture(this, scaleMode, resolution); +}; + +core.Graphics.prototype.generateTexture = function generateTexture(scaleMode, resolution) { + warn('graphics generate texture has moved to the renderer. ' + 'Or to render a graphics to a texture using canvas please use generateCanvasTexture'); + + return this.generateCanvasTexture(scaleMode, resolution); +}; + +core.RenderTexture.prototype.render = function render(displayObject, matrix, clear, updateTransform) { + this.legacyRenderer.render(displayObject, this, clear, matrix, !updateTransform); + warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)'); +}; + +core.RenderTexture.prototype.getImage = function getImage(target) { + warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); + + return this.legacyRenderer.extract.image(target); +}; + +core.RenderTexture.prototype.getBase64 = function getBase64(target) { + warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); + + return this.legacyRenderer.extract.base64(target); +}; + +core.RenderTexture.prototype.getCanvas = function getCanvas(target) { + warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); + + return this.legacyRenderer.extract.canvas(target); +}; + +core.RenderTexture.prototype.getPixels = function getPixels(target) { + warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); + + return this.legacyRenderer.pixels(target); +}; + +/** + * @method + * @private + * @name PIXI.Sprite#setTexture + * @see PIXI.Sprite#texture + * @deprecated since version 3.0.0 + * @param {PIXI.Texture} texture - The texture to set to. + */ +core.Sprite.prototype.setTexture = function setTexture(texture) { + this.texture = texture; + warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;'); +}; + +/** + * @method + * @name PIXI.extras.BitmapText#setText + * @see PIXI.extras.BitmapText#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ +extras.BitmapText.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';'); +}; + +/** + * @method + * @name PIXI.Text#setText + * @see PIXI.Text#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ +core.Text.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';'); +}; + +/** + * @method + * @name PIXI.Text#setStyle + * @see PIXI.Text#style + * @deprecated since version 3.0.0 + * @param {*} style - The style to set to. + */ +core.Text.prototype.setStyle = function setStyle(style) { + this.style = style; + warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;'); +}; + +/** + * @method + * @name PIXI.Text#determineFontProperties + * @see PIXI.Text#calculateFontProperties + * @deprecated since version 4.2.0 + * @private + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ +core.Text.prototype.determineFontProperties = function determineFontProperties(fontStyle) { + warn('determineFontProperties is now deprecated, please use the static calculateFontProperties method, ' + 'e.g : Text.calculateFontProperties(fontStyle);'); + + return core.Text.calculateFontProperties(fontStyle); +}; + +Object.defineProperties(core.TextStyle.prototype, { + /** + * Set all properties of a font as a single string + * + * @name PIXI.TextStyle#font + * @deprecated since version 4.0.0 + */ + font: { + get: function get() { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\', \'fontSize\', \'fontStyle\', \'fontVariant\' and \'fontWeight\' properties from now on'); + + var fontSizeString = typeof this._fontSize === 'number' ? this._fontSize + 'px' : this._fontSize; + + return this._fontStyle + ' ' + this._fontVariant + ' ' + this._fontWeight + ' ' + fontSizeString + ' ' + this._fontFamily; + }, + set: function set(font) { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + + // can work out fontStyle from search of whole string + if (font.indexOf('italic') > 1) { + this._fontStyle = 'italic'; + } else if (font.indexOf('oblique') > -1) { + this._fontStyle = 'oblique'; + } else { + this._fontStyle = 'normal'; + } + + // can work out fontVariant from search of whole string + if (font.indexOf('small-caps') > -1) { + this._fontVariant = 'small-caps'; + } else { + this._fontVariant = 'normal'; + } + + // fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units + var splits = font.split(' '); + var fontSizeIndex = -1; + + this._fontSize = 26; + for (var i = 0; i < splits.length; ++i) { + if (splits[i].match(/(px|pt|em|%)/)) { + fontSizeIndex = i; + this._fontSize = splits[i]; + break; + } + } + + // we can now search for fontWeight as we know it must occur before the fontSize + this._fontWeight = 'normal'; + for (var _i = 0; _i < fontSizeIndex; ++_i) { + if (splits[_i].match(/(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/)) { + this._fontWeight = splits[_i]; + break; + } + } + + // and finally join everything together after the fontSize in case the font family has multiple words + if (fontSizeIndex > -1 && fontSizeIndex < splits.length - 1) { + this._fontFamily = ''; + for (var _i2 = fontSizeIndex + 1; _i2 < splits.length; ++_i2) { + this._fontFamily += splits[_i2] + ' '; + } + + this._fontFamily = this._fontFamily.slice(0, -1); + } else { + this._fontFamily = 'Arial'; + } + + this.styleID++; + } + } +}); + +/** + * @method + * @name PIXI.Texture#setFrame + * @see PIXI.Texture#setFrame + * @deprecated since version 3.0.0 + * @param {PIXI.Rectangle} frame - The frame to set. + */ +core.Texture.prototype.setFrame = function setFrame(frame) { + this.frame = frame; + warn('setFrame is now deprecated, please use the frame property, e.g: myTexture.frame = frame;'); +}; + +Object.defineProperties(filters, { + + /** + * @class + * @private + * @name PIXI.filters.AbstractFilter + * @see PIXI.AbstractFilter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.AbstractFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.SpriteMaskFilter + * @see PIXI.SpriteMaskFilter + * @deprecated since version 3.0.6 + */ + SpriteMaskFilter: { + get: function get() { + warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.'); + + return core.SpriteMaskFilter; + } + } +}); + +/** + * @method + * @name PIXI.utils.uuid + * @see PIXI.utils.uid + * @deprecated since version 3.0.6 + * @return {number} The uid + */ +core.utils.uuid = function () { + warn('utils.uuid() is deprecated, please use utils.uid() from now on.'); + + return core.utils.uid(); +}; + +/** + * @method + * @name PIXI.utils.canUseNewCanvasBlendModes + * @see PIXI.CanvasTinter + * @deprecated + * @return {boolean} Can use blend modes. + */ +core.utils.canUseNewCanvasBlendModes = function () { + warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on'); + + return core.CanvasTinter.canUseMultiply; +}; + +var saidHello = true; + +/** + * @name PIXI.utils._saidHello + * @type {boolean} + * @see PIXI.utils.skipHello + * @deprecated since 4.1.0 + */ +Object.defineProperty(core.utils, '_saidHello', { + set: function set(bool) { + if (bool) { + warn('PIXI.utils._saidHello is deprecated, please use PIXI.utils.skipHello()'); + this.skipHello(); + } + saidHello = bool; + }, + get: function get() { + return saidHello; + } +}); + +/** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.canvas.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ +Object.defineProperty(prepare.canvas, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } +}); + +/** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.webgl.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ +Object.defineProperty(prepare.webgl, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } +}); + +Object.defineProperties(loaders.Resource.prototype, { + isJson: { + get: function get() { + warn('The isJson property is deprecated, please use `resource.type === Resource.TYPE.JSON`.'); + + return this.type === loaders.Loader.Resource.TYPE.JSON; + } + }, + isXml: { + get: function get() { + warn('The isXml property is deprecated, please use `resource.type === Resource.TYPE.XML`.'); + + return this.type === loaders.Loader.Resource.TYPE.XML; + } + }, + isImage: { + get: function get() { + warn('The isImage property is deprecated, please use `resource.type === Resource.TYPE.IMAGE`.'); + + return this.type === loaders.Loader.Resource.TYPE.IMAGE; + } + }, + isAudio: { + get: function get() { + warn('The isAudio property is deprecated, please use `resource.type === Resource.TYPE.AUDIO`.'); + + return this.type === loaders.Loader.Resource.TYPE.AUDIO; + } + }, + isVideo: { + get: function get() { + warn('The isVideo property is deprecated, please use `resource.type === Resource.TYPE.VIDEO`.'); + + return this.type === loaders.Loader.Resource.TYPE.VIDEO; + } + } +}); + +Object.defineProperties(loaders.Loader.prototype, { + before: { + get: function get() { + warn('The before() method is deprecated, please use pre().'); + + return this.pre; + } + }, + after: { + get: function get() { + warn('The after() method is deprecated, please use use().'); + + return this.use; + } + } +}); + +/** + * @name PIXI.interaction.interactiveTarget#defaultCursor + * @static + * @type {number} + * @see PIXI.interaction.interactiveTarget#cursor + * @deprecated since 4.3.0 + */ +Object.defineProperty(interaction.interactiveTarget, 'defaultCursor', { + set: function set(value) { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + this.cursor = value; + }, + get: function get() { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + + return this.cursor; + }, + + enumerable: true +}); + +/** + * @name PIXI.interaction.InteractionManager#defaultCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ +Object.defineProperty(interaction.InteractionManager, 'defaultCursorStyle', { + set: function set(value) { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + this.cursorStyles.default = value; + }, + get: function get() { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + + return this.cursorStyles.default; + } +}); + +/** + * @name PIXI.interaction.InteractionManager#currentCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ +Object.defineProperty(interaction.InteractionManager, 'currentCursorStyle', { + set: function set(value) { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + this.currentCursorMode = value; + }, + get: function get() { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + + return this.currentCursorMode; + } +}); + +},{"./core":63,"./extras":136,"./filters":147,"./interaction":154,"./loaders":157,"./mesh":166,"./particles":169,"./prepare":179}],126:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI + */ + +var CanvasExtract = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasExtract(renderer) { + _classCallCheck(this, CanvasExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.CanvasExtract} extract + * @memberof PIXI.CanvasRenderer# + * @see PIXI.CanvasExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + CanvasExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `CanvasExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + CanvasExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + CanvasExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = this.renderer.width; + frame.height = this.renderer.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + CanvasExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + + return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; + }; + + /** + * Destroys the extract + * + */ + + + CanvasExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return CanvasExtract; +}(); + +exports.default = CanvasExtract; + + +core.CanvasRenderer.registerPlugin('extract', CanvasExtract); + +},{"../../core":63}],127:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLExtract = require('./webgl/WebGLExtract'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLExtract).default; + } +}); + +var _CanvasExtract = require('./canvas/CanvasExtract'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasExtract).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./canvas/CanvasExtract":126,"./webgl/WebGLExtract":128}],128:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); +var BYTES_PER_PIXEL = 4; + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI + */ + +var WebGLExtract = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLExtract(renderer) { + _classCallCheck(this, WebGLExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.WebGLExtract} extract + * @memberof PIXI.WebGLRenderer# + * @see PIXI.WebGLExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + WebGLExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `WebGLExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + WebGLExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + WebGLExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var flipY = false; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + flipY = false; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + flipY = true; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + + // set up an array of pixels + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + + canvasData.data.set(webglPixels); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // pulling pixels + if (flipY) { + canvasBuffer.context.scale(1, -1); + canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); + } + } + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + WebGLExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + } + + return webglPixels; + }; + + /** + * Destroys the extract + * + */ + + + WebGLExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return WebGLExtract; +}(); + +exports.default = WebGLExtract; + + +core.WebGLRenderer.registerPlugin('extract', WebGLExtract); + +},{"../../core":63}],129:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @typedef FrameObject + * @type {object} + * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame + * @property {number} time - the duration of the frame in ms + */ + +/** + * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. + * + * ```js + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; + * + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.fromImage(alienImages[i]); + * textureArray.push(texture); + * }; + * + * let mc = new PIXI.AnimatedSprite(textureArray); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ +var AnimatedSprite = function (_core$Sprite) { + _inherits(AnimatedSprite, _core$Sprite); + + /** + * @param {PIXI.Texture[]|FrameObject[]} textures - an array of {@link PIXI.Texture} or frame + * objects that make up the animation + * @param {boolean} [autoUpdate=true] - Whether use PIXI.ticker.shared to auto update animation time. + */ + function AnimatedSprite(textures, autoUpdate) { + _classCallCheck(this, AnimatedSprite); + + /** + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture)); + + _this._textures = null; + + /** + * @private + */ + _this._durations = null; + + _this.textures = textures; + + /** + * `true` uses PIXI.ticker.shared to auto update animation time. + * @type {boolean} + * @default true + * @private + */ + _this._autoUpdate = autoUpdate !== false; + + /** + * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower + * + * @member {number} + * @default 1 + */ + _this.animationSpeed = 1; + + /** + * Whether or not the animate sprite repeats after playing. + * + * @member {boolean} + * @default true + */ + _this.loop = true; + + /** + * Function to call when a AnimatedSprite finishes playing + * + * @member {Function} + */ + _this.onComplete = null; + + /** + * Function to call when a AnimatedSprite changes which texture is being rendered + * + * @member {Function} + */ + _this.onFrameChange = null; + + /** + * Elapsed time since animation has been started, used internally to display current texture + * + * @member {number} + * @private + */ + _this._currentTime = 0; + + /** + * Indicates if the AnimatedSprite is currently playing + * + * @member {boolean} + * @readonly + */ + _this.playing = false; + return _this; + } + + /** + * Stops the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.stop = function stop() { + if (!this.playing) { + return; + } + + this.playing = false; + if (this._autoUpdate) { + core.ticker.shared.remove(this.update, this); + } + }; + + /** + * Plays the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.play = function play() { + if (this.playing) { + return; + } + + this.playing = true; + if (this._autoUpdate) { + core.ticker.shared.add(this.update, this); + } + }; + + /** + * Stops the AnimatedSprite and goes to a specific frame + * + * @param {number} frameNumber - frame index to stop at + */ + + + AnimatedSprite.prototype.gotoAndStop = function gotoAndStop(frameNumber) { + this.stop(); + + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + + /** + * Goes to a specific frame and begins playing the AnimatedSprite + * + * @param {number} frameNumber - frame index to start at + */ + + + AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay(frameNumber) { + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + + this.play(); + }; + + /** + * Updates the object transform for rendering. + * + * @private + * @param {number} deltaTime - Time since last tick. + */ + + + AnimatedSprite.prototype.update = function update(deltaTime) { + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + + lag += elapsed / 60 * 1000; + + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + + var sign = Math.sign(this.animationSpeed * deltaTime); + + this._currentTime = Math.floor(this._currentTime); + + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + + this._currentTime += lag / this._durations[this.currentFrame]; + } else { + this._currentTime += elapsed; + } + + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + + if (this.onComplete) { + this.onComplete(); + } + } else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + + if (this.onComplete) { + this.onComplete(); + } + } else if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + + /** + * Updates the displayed texture to match the current frame index + * + * @private + */ + + + AnimatedSprite.prototype.updateTexture = function updateTexture() { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + }; + + /** + * Stops the AnimatedSprite and destroys it + * + */ + + + AnimatedSprite.prototype.destroy = function destroy() { + this.stop(); + _core$Sprite.prototype.destroy.call(this); + }; + + /** + * A short hand way of creating a movieclip from an array of frame ids + * + * @static + * @param {string[]} frames - The array of frames ids the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animated sprite with the specified frames. + */ + + + AnimatedSprite.fromFrames = function fromFrames(frames) { + var textures = []; + + for (var i = 0; i < frames.length; ++i) { + textures.push(core.Texture.fromFrame(frames[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * A short hand way of creating a movieclip from an array of image ids + * + * @static + * @param {string[]} images - the array of image urls the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animate sprite with the specified images as frames. + */ + + + AnimatedSprite.fromImages = function fromImages(images) { + var textures = []; + + for (var i = 0; i < images.length; ++i) { + textures.push(core.Texture.fromImage(images[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * totalFrames is the total number of frames in the AnimatedSprite. This is the same as number of textures + * assigned to the AnimatedSprite. + * + * @readonly + * @member {number} + * @default 0 + */ + + + _createClass(AnimatedSprite, [{ + key: 'totalFrames', + get: function get() { + return this._textures.length; + } + + /** + * The array of textures used for this AnimatedSprite + * + * @member {PIXI.Texture[]} + */ + + }, { + key: 'textures', + get: function get() { + return this._textures; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value[0] instanceof core.Texture) { + this._textures = value; + this._durations = null; + } else { + this._textures = []; + this._durations = []; + + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + } + + /** + * The AnimatedSprites current frame index + * + * @member {number} + * @readonly + */ + + }, { + key: 'currentFrame', + get: function get() { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + + return currentFrame; + } + }]); + + return AnimatedSprite; +}(core.Sprite); + +exports.default = AnimatedSprite; + +},{"../core":63}],130:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ObservablePoint = require('../core/math/ObservablePoint'); + +var _ObservablePoint2 = _interopRequireDefault(_ObservablePoint); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BitmapText object will create a line or multiple lines of text using bitmap font. To + * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using: + * + * A BitmapText can only be created when the font is loaded + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); + * ``` + * + * http://www.angelcode.com/products/bmfont/ for windows or + * http://www.bmglyph.com/ for mac. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.extras + */ +var BitmapText = function (_core$Container) { + _inherits(BitmapText, _core$Container); + + /** + * @param {string} text - The copy that you would like the text to display + * @param {object} style - The style parameters + * @param {string|object} style.font - The font descriptor for the object, can be passed as a string of form + * "24px FontName" or "FontName" or as an object with explicit name/size properties. + * @param {string} [style.font.name] - The bitmap font id + * @param {number} [style.font.size] - The size of the font in pixels, e.g. 24 + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), does not affect + * single line text + * @param {number} [style.tint=0xFFFFFF] - The tint color + */ + function BitmapText(text) { + var style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _classCallCheck(this, BitmapText); + + /** + * Private tracker for the width of the overall text + * + * @member {number} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._textWidth = 0; + + /** + * Private tracker for the height of the overall text + * + * @member {number} + * @private + */ + _this._textHeight = 0; + + /** + * Private tracker for the letter sprite pool. + * + * @member {PIXI.Sprite[]} + * @private + */ + _this._glyphs = []; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._font = { + tint: style.tint !== undefined ? style.tint : 0xFFFFFF, + align: style.align || 'left', + name: null, + size: 0 + }; + + /** + * Private tracker for the current font. + * + * @member {object} + * @private + */ + _this.font = style.font; // run font setter + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = text; + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + */ + _this.maxWidth = 0; + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + */ + _this.maxLineHeight = 0; + + /** + * Text anchor. read-only + * + * @member {PIXI.ObservablePoint} + * @private + */ + _this._anchor = new _ObservablePoint2.default(function () { + _this.dirty = true; + }, _this, 0, 0); + + /** + * The dirty state of this object. + * + * @member {boolean} + */ + _this.dirty = false; + + _this.updateText(); + return _this; + } + + /** + * Renders text and updates it when needed + * + * @private + */ + + + BitmapText.prototype.updateText = function updateText() { + var data = BitmapText.fonts[this._font.name]; + var scale = this._font.size / data.size; + var pos = new core.Point(); + var chars = []; + var lineWidths = []; + + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastSpace = -1; + var lastSpaceWidth = 0; + var maxLineHeight = 0; + + for (var i = 0; i < this.text.length; i++) { + var charCode = this.text.charCodeAt(i); + + if (/(\s)/.test(this.text.charAt(i))) { + lastSpace = i; + lastSpaceWidth = lastLineWidth; + } + + if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) { + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + if (lastSpace !== -1 && this.maxWidth > 0 && pos.x * scale > this.maxWidth) { + core.utils.removeItems(chars, lastSpace, i - lastSpace); + i = lastSpace; + lastSpace = -1; + + lineWidths.push(lastSpaceWidth); + maxLineWidth = Math.max(maxLineWidth, lastSpaceWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + var charData = data.chars[charCode]; + + if (!charData) { + continue; + } + + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + + chars.push({ + texture: charData.texture, + line: line, + charCode: charCode, + position: new core.Point(pos.x + charData.xOffset, pos.y + charData.yOffset) + }); + lastLineWidth = pos.x + (charData.texture.width + charData.xOffset); + pos.x += charData.xAdvance; + maxLineHeight = Math.max(maxLineHeight, charData.yOffset + charData.texture.height); + prevCharCode = charCode; + } + + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + + var lineAlignOffsets = []; + + for (var _i = 0; _i <= line; _i++) { + var alignOffset = 0; + + if (this._font.align === 'right') { + alignOffset = maxLineWidth - lineWidths[_i]; + } else if (this._font.align === 'center') { + alignOffset = (maxLineWidth - lineWidths[_i]) / 2; + } + + lineAlignOffsets.push(alignOffset); + } + + var lenChars = chars.length; + var tint = this.tint; + + for (var _i2 = 0; _i2 < lenChars; _i2++) { + var c = this._glyphs[_i2]; // get the next glyph sprite + + if (c) { + c.texture = chars[_i2].texture; + } else { + c = new core.Sprite(chars[_i2].texture); + this._glyphs.push(c); + } + + c.position.x = (chars[_i2].position.x + lineAlignOffsets[chars[_i2].line]) * scale; + c.position.y = chars[_i2].position.y * scale; + c.scale.x = c.scale.y = scale; + c.tint = tint; + + if (!c.parent) { + this.addChild(c); + } + } + + // remove unnecessary children. + for (var _i3 = lenChars; _i3 < this._glyphs.length; ++_i3) { + this.removeChild(this._glyphs[_i3]); + } + + this._textWidth = maxLineWidth * scale; + this._textHeight = (pos.y + data.lineHeight) * scale; + + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + for (var _i4 = 0; _i4 < lenChars; _i4++) { + this._glyphs[_i4].x -= this._textWidth * this.anchor.x; + this._glyphs[_i4].y -= this._textHeight * this.anchor.y; + } + } + this.maxLineHeight = maxLineHeight * scale; + }; + + /** + * Updates the transform of this object + * + * @private + */ + + + BitmapText.prototype.updateTransform = function updateTransform() { + this.validate(); + this.containerUpdateTransform(); + }; + + /** + * Validates text before calling parent's getLocalBounds + * + * @return {PIXI.Rectangle} The rectangular bounding area + */ + + + BitmapText.prototype.getLocalBounds = function getLocalBounds() { + this.validate(); + + return _core$Container.prototype.getLocalBounds.call(this); + }; + + /** + * Updates text when needed + * + * @private + */ + + + BitmapText.prototype.validate = function validate() { + if (this.dirty) { + this.updateText(); + this.dirty = false; + } + }; + + /** + * The tint of the BitmapText object + * + * @member {number} + */ + + + /** + * Register a bitmap font with data and a texture. + * + * @static + * @param {XMLDocument} xml - The XML document data. + * @param {PIXI.Texture} texture - Texture with all symbols. + * @return {Object} Result font object with font, size, lineHeight and char fields. + */ + BitmapText.registerFont = function registerFont(xml, texture) { + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10); + data.chars = {}; + + // parse letters + var letters = xml.getElementsByTagName('char'); + + for (var i = 0; i < letters.length; i++) { + var letter = letters[i]; + var charCode = parseInt(letter.getAttribute('id'), 10); + + var textureRect = new core.Rectangle(parseInt(letter.getAttribute('x'), 10) + texture.frame.x, parseInt(letter.getAttribute('y'), 10) + texture.frame.y, parseInt(letter.getAttribute('width'), 10), parseInt(letter.getAttribute('height'), 10)); + + data.chars[charCode] = { + xOffset: parseInt(letter.getAttribute('xoffset'), 10), + yOffset: parseInt(letter.getAttribute('yoffset'), 10), + xAdvance: parseInt(letter.getAttribute('xadvance'), 10), + kerning: {}, + texture: new core.Texture(texture.baseTexture, textureRect) + + }; + } + + // parse kernings + var kernings = xml.getElementsByTagName('kerning'); + + for (var _i5 = 0; _i5 < kernings.length; _i5++) { + var kerning = kernings[_i5]; + var first = parseInt(kerning.getAttribute('first'), 10); + var second = parseInt(kerning.getAttribute('second'), 10); + var amount = parseInt(kerning.getAttribute('amount'), 10); + + if (data.chars[second]) { + data.chars[second].kerning[first] = amount; + } + } + + // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 + // but it's very likely to change + BitmapText.fonts[data.font] = data; + + return data; + }; + + _createClass(BitmapText, [{ + key: 'tint', + get: function get() { + return this._font.tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.tint = typeof value === 'number' && value >= 0 ? value : 0xFFFFFF; + + this.dirty = true; + } + + /** + * The alignment of the BitmapText object + * + * @member {string} + * @default 'left' + */ + + }, { + key: 'align', + get: function get() { + return this._font.align; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.align = value || 'left'; + + this.dirty = true; + } + + /** + * The anchor sets the origin point of the text. + * The default is 0,0 this means the text's origin is the top left + * Setting the anchor to 0.5,0.5 means the text's origin is centered + * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner + * + * @member {PIXI.Point | number} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (typeof value === 'number') { + this._anchor.set(value); + } else { + this._anchor.copy(value); + } + } + + /** + * The font descriptor of the BitmapText object + * + * @member {string|object} + */ + + }, { + key: 'font', + get: function get() { + return this._font; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (!value) { + return; + } + + if (typeof value === 'string') { + value = value.split(' '); + + this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); + this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; + } else { + this._font.name = value.name; + this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); + } + + this.dirty = true; + } + + /** + * The text of the BitmapText object + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + value = value.toString() || ' '; + if (this._text === value) { + return; + } + this._text = value; + this.dirty = true; + } + + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textWidth', + get: function get() { + this.validate(); + + return this._textWidth; + } + + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textHeight', + get: function get() { + this.validate(); + + return this._textHeight; + } + }]); + + return BitmapText; +}(core.Container); + +exports.default = BitmapText; + + +BitmapText.fonts = {}; + +},{"../core":63,"../core/math/ObservablePoint":66}],131:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Matrix = require('../core/math/Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var tempMat = new _Matrix2.default(); + +/** + * class controls uv transform and frame clamp for texture + * + * @class + * @memberof PIXI.extras + */ + +var TextureTransform = function () { + /** + * + * @param {PIXI.Texture} texture observed texture + * @param {number} [clampMargin] Changes frame clamping, 0.5 by default. Use -0.5 for extra border. + * @constructor + */ + function TextureTransform(texture, clampMargin) { + _classCallCheck(this, TextureTransform); + + this._texture = texture; + + this.mapCoord = new _Matrix2.default(); + + this.uClampFrame = new Float32Array(4); + + this.uClampOffset = new Float32Array(2); + + this._lastTextureID = -1; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders + * + * @default 0 + * @member {number} + */ + this.clampOffset = 0; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + this.clampMargin = typeof clampMargin === 'undefined' ? 0.5 : clampMargin; + } + + /** + * texture property + * @member {PIXI.Texture} + */ + + + /** + * updates matrices if texture was changed + * @param {boolean} forceUpdate if true, matrices will be updated any case + */ + TextureTransform.prototype.update = function update(forceUpdate) { + var tex = this._texture; + + if (!tex || !tex.valid) { + return; + } + + if (!forceUpdate && this._lastTextureID === tex._updateID) { + return; + } + + this._lastTextureID = tex._updateID; + + var uvs = tex._uvs; + + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + + var orig = tex.orig; + var trim = tex.trim; + + if (trim) { + tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat); + } + + var texBase = tex.baseTexture; + var frame = this.uClampFrame; + var margin = this.clampMargin / texBase.resolution; + var offset = this.clampOffset; + + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.uClampOffset[0] = offset / texBase.realWidth; + this.uClampOffset[1] = offset / texBase.realHeight; + }; + + _createClass(TextureTransform, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._texture = value; + this._lastTextureID = -1; + } + }]); + + return TextureTransform; +}(); + +exports.default = TextureTransform; + +},{"../core/math/Matrix":65}],132:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CanvasTinter = require('../core/sprites/canvas/CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +var _TextureTransform = require('./TextureTransform'); + +var _TextureTransform2 = _interopRequireDefault(_TextureTransform); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); + +/** + * A tiling sprite is a fast way of rendering a tiling image + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ + +var TilingSprite = function (_core$Sprite) { + _inherits(TilingSprite, _core$Sprite); + + /** + * @param {PIXI.Texture} texture - the texture of the tiling sprite + * @param {number} [width=100] - the width of the tiling sprite + * @param {number} [height=100] - the height of the tiling sprite + */ + function TilingSprite(texture) { + var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100; + + _classCallCheck(this, TilingSprite); + + /** + * Tile transform + * + * @member {PIXI.TransformStatic} + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, texture)); + + _this.tileTransform = new core.TransformStatic(); + + // /// private + + /** + * The with of the tiling sprite + * + * @member {number} + * @private + */ + _this._width = width; + + /** + * The height of the tiling sprite + * + * @member {number} + * @private + */ + _this._height = height; + + /** + * Canvas pattern + * + * @type {CanvasPattern} + * @private + */ + _this._canvasPattern = null; + + /** + * transform that is applied to UV to get the texture coords + * + * @member {PIXI.extras.TextureTransform} + */ + _this.uvTransform = texture.transform || new _TextureTransform2.default(texture); + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' method. + * + * @member {string} + * @default 'tilingSprite' + */ + _this.pluginName = 'tilingSprite'; + + /** + * Whether or not anchor affects uvs + * + * @member {boolean} + * @default false + */ + _this.uvRespectAnchor = false; + return _this; + } + /** + * Changes frame clamping in corresponding textureTransform, shortcut + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + + + /** + * @private + */ + TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate() { + if (this.uvTransform) { + this.uvTransform.texture = this._texture; + } + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + TilingSprite.prototype._renderWebGL = function _renderWebGL(renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + + if (!texture || !texture.valid) { + return; + } + + this.tileTransform.updateLocalTransform(); + this.uvTransform.update(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer + */ + + + TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { + var texture = this._texture; + + if (!texture.baseTexture.hasLoaded) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var resolution = renderer.resolution; + var baseTexture = texture.baseTexture; + var baseTextureResolution = texture.baseTexture.resolution; + var modX = this.tilePosition.x / this.tileScale.x % texture._frame.width; + var modY = this.tilePosition.y / this.tileScale.y % texture._frame.height; + + // create a nice shiny pattern! + // TODO this needs to be refreshed if texture changes.. + if (!this._canvasPattern) { + // cut an object from a spritesheet.. + var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height, baseTextureResolution); + + // Tint the tiling sprite + if (this.tint !== 0xFFFFFF) { + if (this.cachedTint !== this.tint) { + this.cachedTint = this.tint; + + this.tintedTexture = _CanvasTinter2.default.getTintedTexture(this, this.tint); + } + tempCanvas.context.drawImage(this.tintedTexture, 0, 0); + } else { + tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x, -texture._frame.y); + } + this._canvasPattern = tempCanvas.context.createPattern(tempCanvas.canvas, 'repeat'); + } + + // set context state.. + context.globalAlpha = this.worldAlpha; + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + renderer.setBlendMode(this.blendMode); + + // fill the pattern! + context.fillStyle = this._canvasPattern; + + // TODO - this should be rolled into the setTransform above.. + context.scale(this.tileScale.x / baseTextureResolution, this.tileScale.y / baseTextureResolution); + + var anchorX = this.anchor.x * -this._width; + var anchorY = this.anchor.y * -this._height; + + if (this.uvRespectAnchor) { + context.translate(modX, modY); + + context.fillRect(-modX + anchorX, -modY + anchorY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } else { + context.translate(modX + anchorX, modY + anchorY); + + context.fillRect(-modX, -modY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } + }; + + /** + * Updates the bounds of the tiling sprite. + * + * @private + */ + + + TilingSprite.prototype._calculateBounds = function _calculateBounds() { + var minX = this._width * -this._anchor._x; + var minY = this._height * -this._anchor._y; + var maxX = this._width * (1 - this._anchor._x); + var maxY = this._height * (1 - this._anchor._y); + + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + TilingSprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._width * -this._anchor._x; + this._bounds.minY = this._height * -this._anchor._y; + this._bounds.maxX = this._width * (1 - this._anchor._x); + this._bounds.maxY = this._height * (1 - this._anchor._x); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new core.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _core$Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Checks if a point is inside this tiling sprite. + * + * @param {PIXI.Point} point - the point to check + * @return {boolean} Whether or not the sprite contains the point. + */ + + + TilingSprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor._x; + + if (tempPoint.x > x1 && tempPoint.x < x1 + width) { + var y1 = -height * this.anchor._y; + + if (tempPoint.y > y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this tiling sprite + * + */ + + + TilingSprite.prototype.destroy = function destroy() { + _core$Sprite.prototype.destroy.call(this); + + this.tileTransform = null; + this.uvTransform = null; + }; + + /** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.Texture} The newly created texture + */ + + + TilingSprite.from = function from(source, width, height) { + return new TilingSprite(core.Texture.from(source), width, height); + }; + + /** + * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId + */ + + + TilingSprite.fromFrame = function fromFrame(frameId, width, height) { + var texture = core.utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this); + } + + return new TilingSprite(texture, width, height); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @param {boolean} [crossorigin] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id + */ + + + TilingSprite.fromImage = function fromImage(imageId, width, height, crossorigin, scaleMode) { + return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode), width, height); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(TilingSprite, [{ + key: 'clampMargin', + get: function get() { + return this.uvTransform.clampMargin; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uvTransform.clampMargin = value; + this.uvTransform.update(true); + } + + /** + * The scaling of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tileScale', + get: function get() { + return this.tileTransform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.scale.copy(value); + } + + /** + * The offset of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tilePosition', + get: function get() { + return this.tileTransform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.position.copy(value); + } + }, { + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + } + + /** + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + } + }]); + + return TilingSprite; +}(core.Sprite); + +exports.default = TilingSprite; + +},{"../core":63,"../core/sprites/canvas/CanvasTinter":102,"./TextureTransform":131}],133:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DisplayObject = core.DisplayObject; +var _tempMatrix = new core.Matrix(); + +DisplayObject.prototype._cacheAsBitmap = false; +DisplayObject.prototype._cacheData = false; + +// figured theres no point adding ALL the extra variables to prototype. +// this model can hold the information needed. This can also be generated on demand as +// most objects are not cached as bitmaps. +/** + * @class + * @ignore + */ + +var CacheData = +/** + * + */ +function CacheData() { + _classCallCheck(this, CacheData); + + this.originalRenderWebGL = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + + this.originalUpdateTransform = null; + this.originalHitTest = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.sprite = null; +}; + +Object.defineProperties(DisplayObject.prototype, { + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to 'false' + * + * IMPORTANT GOTCHA - make sure that all your textures are preloaded BEFORE setting this property to true + * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function get() { + return this._cacheAsBitmap; + }, + set: function set(value) { + if (this._cacheAsBitmap === value) { + return; + } + + this._cacheAsBitmap = value; + + var data = void 0; + + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + + data = this._cacheData; + + data.originalRenderWebGL = this.renderWebGL; + data.originalRenderCanvas = this.renderCanvas; + + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this._calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + + data.originalDestroy = this.destroy; + + data.originalContainsPoint = this.containsPoint; + + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + + this.renderWebGL = this._renderCachedWebGL; + this.renderCanvas = this._renderCachedCanvas; + + this.destroy = this._cacheAsBitmapDestroy; + } else { + data = this._cacheData; + + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + + this.renderWebGL = data.originalRenderWebGL; + this.renderCanvas = data.originalRenderCanvas; + this._calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + + this.destroy = data.originalDestroy; + + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + } + } +}); + +/** + * Renders a cached version of the sprite with WebGL + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedWebGL = function _renderCachedWebGL(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObject(renderer); + + this._cacheData.sprite._transformID = -1; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderWebGL(renderer); +}; + +/** + * Prepares the WebGL renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + + this.alpha = 1; + + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.currentRenderer.flush(); + // this.filters= []; + + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds().clone(); + + // add some padding! + if (this._filters) { + var padding = this._filters[0].padding; + + bounds.pad(padding); + } + + // for now we cache the current renderTarget that the webGL renderer is currently using. + // this could be more elegent.. + var cachedRenderTarget = renderer._activeRenderTarget; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + var stack = renderer.filterManager.filterStack; + + // this renderTexture will be used to store the cached DisplayObject + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + // need to set // + var m = _tempMatrix; + + m.tx = -bounds.x; + m.ty = -bounds.y; + + // reset + this.transform.worldTransform.identity(); + + // set all properties to there original so we can render to a texture + this.renderWebGL = this._cacheData.originalRenderWebGL; + + renderer.render(this, renderTexture, true, m, true); + // now restore the state be setting the new properties + + renderer.bindRenderTarget(cachedRenderTarget); + + renderer.filterManager.filterStack = stack; + + this.renderWebGL = this._renderCachedWebGL; + this.updateTransform = this.displayObjectUpdateTransform; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + + // easy bounds.. + this._calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + + this._cacheData.sprite = cachedSprite; + + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + this.updateTransform(); + + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Renders a cached version of the sprite with canvas + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObjectCanvas(renderer); + + this._cacheData.sprite.worldAlpha = this.worldAlpha; + + this._cacheData.sprite.renderCanvas(renderer); +}; + +// TODO this can be the same as the webGL verison.. will need to do a little tweaking first though.. +/** + * Prepares the Canvas renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(); + + var cacheAlpha = this.alpha; + + this.alpha = 1; + + var cachedRenderTarget = renderer.context; + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + // need to set // + var m = _tempMatrix; + + this.transform.localTransform.copy(m); + m.invert(); + + m.tx -= bounds.x; + m.ty -= bounds.y; + + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + + // renderTexture.render(this, m, true); + renderer.render(this, renderTexture, true, m, false); + + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + + this.renderCanvas = this._renderCachedCanvas; + this._calculateBounds = this._calculateCachedBounds; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite._bounds = this._bounds; + cachedSprite.alpha = cacheAlpha; + + this.updateTransform(); + this.updateTransform = this.displayObjectUpdateTransform; + + this._cacheData.sprite = cachedSprite; + + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Calculates the bounds of the cached sprite + * + * @private + */ +DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._cacheData.sprite._calculateBounds(); +}; + +/** + * Gets the bounds of the cached sprite. + * + * @private + * @return {Rectangle} The local bounds. + */ +DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(); +}; + +/** + * Destroys the cached sprite. + * + * @private + */ +DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; +}; + +/** + * Destroys the cached object. + * + * @private + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * Used when destroying containers, see the Container.destroy method. + */ +DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { + this.cacheAsBitmap = false; + this.destroy(options); +}; + +},{"../core":63}],134:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * The instance name of the object. + * + * @memberof PIXI.DisplayObject# + * @member {string} + */ +core.DisplayObject.prototype.name = null; + +/** + * Returns the display object in the container + * + * @memberof PIXI.Container# + * @param {string} name - instance name + * @return {PIXI.DisplayObject} The child with the specified name. + */ +core.Container.prototype.getChildByName = function getChildByName(name) { + for (var i = 0; i < this.children.length; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + + return null; +}; + +},{"../core":63}],135:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. + * + * @memberof PIXI.DisplayObject# + * @param {Point} point - the point to write the global value to. If null a new point will be returned + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @return {Point} The updated point + */ +core.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition() { + var point = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new core.Point(); + var skipUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (this.parent) { + this.parent.toGlobal(this.position, point, skipUpdate); + } else { + point.x = this.position.x; + point.y = this.position.y; + } + + return point; +}; + +},{"../core":63}],136:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BitmapText = exports.TilingSpriteRenderer = exports.TilingSprite = exports.AnimatedSprite = exports.TextureTransform = undefined; + +var _TextureTransform = require('./TextureTransform'); + +Object.defineProperty(exports, 'TextureTransform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureTransform).default; + } +}); + +var _AnimatedSprite = require('./AnimatedSprite'); + +Object.defineProperty(exports, 'AnimatedSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AnimatedSprite).default; + } +}); + +var _TilingSprite = require('./TilingSprite'); + +Object.defineProperty(exports, 'TilingSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSprite).default; + } +}); + +var _TilingSpriteRenderer = require('./webgl/TilingSpriteRenderer'); + +Object.defineProperty(exports, 'TilingSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSpriteRenderer).default; + } +}); + +var _BitmapText = require('./BitmapText'); + +Object.defineProperty(exports, 'BitmapText', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BitmapText).default; + } +}); + +require('./cacheAsBitmap'); + +require('./getChildByName'); + +require('./getGlobalPosition'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// imported for side effect of extending the prototype only, contains no exports + +},{"./AnimatedSprite":129,"./BitmapText":130,"./TextureTransform":131,"./TilingSprite":132,"./cacheAsBitmap":133,"./getChildByName":134,"./getGlobalPosition":135,"./webgl/TilingSpriteRenderer":137}],137:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _const = require('../../core/const'); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMat = new core.Matrix(); +var tempArray = new Float32Array(4); + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var TilingSpriteRenderer = function (_core$ObjectRenderer) { + _inherits(TilingSpriteRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function TilingSpriteRenderer(renderer) { + _classCallCheck(this, TilingSpriteRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + _this.simpleShader = null; + _this.quad = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + TilingSpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n gl_FragColor = sample * color ;\n}\n'); + this.simpleShader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n gl_FragColor = sample * color;\n}\n'); + + this.renderer.bindVao(null); + this.quad = new core.Quad(gl, this.renderer.state.attribState); + this.quad.initVao(this.shader); + }; + + /** + * + * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered + */ + + + TilingSpriteRenderer.prototype.render = function render(ts) { + var renderer = this.renderer; + var quad = this.quad; + + renderer.bindVao(quad.vao); + + var vertices = quad.vertices; + + vertices[0] = vertices[6] = ts._width * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + + vertices[2] = vertices[4] = ts._width * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + + if (ts.uvRespectAnchor) { + vertices = quad.uvs; + + vertices[0] = vertices[6] = -ts.anchor.x; + vertices[1] = vertices[3] = -ts.anchor.y; + + vertices[2] = vertices[4] = 1.0 - ts.anchor.x; + vertices[5] = vertices[7] = 1.0 - ts.anchor.y; + } + + quad.upload(); + + var tex = ts._texture; + var baseTex = tex.baseTexture; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvTransform; + var isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === _const.WRAP_MODES.CLAMP) { + baseTex.wrapMode = _const.WRAP_MODES.REPEAT; + } + } else { + isSimple = baseTex.wrapMode !== _const.WRAP_MODES.CLAMP; + } + } + + var shader = isSimple ? this.simpleShader : this.shader; + + renderer.bindShader(shader); + + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + + tempMat.invert(); + if (isSimple) { + tempMat.append(uv.mapCoord); + } else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + + shader.uniforms.uTransform = tempMat.toArray(true); + + var color = tempArray; + + core.utils.hex2rgb(ts.tint, color); + color[3] = ts.worldAlpha; + shader.uniforms.uColor = color; + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + + shader.uniforms.uSampler = renderer.bindTexture(tex); + + renderer.setBlendMode(ts.blendMode); + + quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + }; + + return TilingSpriteRenderer; +}(core.ObjectRenderer); + +exports.default = TilingSpriteRenderer; + + +core.WebGLRenderer.registerPlugin('tilingSprite', TilingSpriteRenderer); + +},{"../../core":63,"../../core/const":44,"path":22}],138:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BlurXFilter = require('./BlurXFilter'); + +var _BlurXFilter2 = _interopRequireDefault(_BlurXFilter); + +var _BlurYFilter = require('./BlurYFilter'); + +var _BlurYFilter2 = _interopRequireDefault(_BlurYFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurFilter applies a Gaussian blur to an object. + * The strength of the blur can be set for x- and y-axis separately. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurFilter = function (_core$Filter) { + _inherits(BlurFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this)); + + _this.blurXFilter = new _BlurXFilter2.default(strength, quality, resolution, kernelSize); + _this.blurYFilter = new _BlurYFilter2.default(strength, quality, resolution, kernelSize); + + _this.padding = 0; + _this.resolution = resolution || core.settings.RESOLUTION; + _this.quality = quality || 4; + _this.blur = strength || 8; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + BlurFilter.prototype.apply = function apply(filterManager, input, output) { + var renderTarget = filterManager.getRenderTarget(true); + + this.blurXFilter.apply(filterManager, input, renderTarget, true); + this.blurYFilter.apply(filterManager, renderTarget, output, false); + + filterManager.returnRenderTarget(renderTarget); + }; + + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurFilter, [{ + key: 'blur', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the number of passes for blur. More passes means higher quaility bluring. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'quality', + get: function get() { + return this.blurXFilter.quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.quality = this.blurYFilter.quality = value; + } + + /** + * Sets the strength of the blurX property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurX', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the strength of the blurY property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurY', + get: function get() { + return this.blurYFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + }]); + + return BlurFilter; +}(core.Filter); + +exports.default = BlurFilter; + +},{"../../core":63,"./BlurXFilter":139,"./BlurYFilter":140}],139:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurXFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurXFilter = function (_core$Filter) { + _inherits(BlurXFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurXFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurXFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurXFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.width * (output.size.width / input.size.width); + + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; // / this.passes//Math.pow(1, this.passes); + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 16 + */ + + + _createClass(BlurXFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurXFilter; +}(core.Filter); + +exports.default = BlurXFilter; + +},{"../../core":63,"./generateBlurFragSource":141,"./generateBlurVertSource":142,"./getMaxBlurKernelSize":143}],140:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurYFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurYFilter = function (_core$Filter) { + _inherits(BlurYFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurYFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurYFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurYFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.height * (output.size.height / input.size.height); + + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurYFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurYFilter; +}(core.Filter); + +exports.default = BlurYFilter; + +},{"../../core":63,"./generateBlurFragSource":141,"./generateBlurVertSource":142,"./getMaxBlurKernelSize":143}],141:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateFragBlurSource; +var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] +}; + +var fragTemplate = ['varying vec2 vBlurTexCoords[%size%];', 'uniform sampler2D uSampler;', 'void main(void)', '{', ' gl_FragColor = vec4(0.0);', ' %blur%', '}'].join('\n'); + +function generateFragBlurSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + + var fragSource = fragTemplate; + + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value = void 0; + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + value = i; + + if (i >= halfLength) { + value = kernelSize - i - 1; + } + + blur = blur.replace('%value%', kernel[value]); + + blurLoop += blur; + blurLoop += '\n'; + } + + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize); + + return fragSource; +} + +},{}],142:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateVertBlurSource; +var vertTemplate = ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform float strength;', 'uniform mat3 projectionMatrix;', 'varying vec2 vBlurTexCoords[%size%];', 'void main(void)', '{', 'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);', '%blur%', '}'].join('\n'); + +function generateVertBlurSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + + var vertSource = vertTemplate; + + var blurLoop = ''; + var template = void 0; + // let value; + + if (x) { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } else { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + // value = i; + + // if(i >= halfLength) + // { + // value = kernelSize - i - 1; + // } + + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + '.0'); + + blurLoop += blur; + blurLoop += '\n'; + } + + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize); + + return vertSource; +} + +},{}],143:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = getMaxKernelSize; +function getMaxKernelSize(gl) { + var maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + var kernelSize = 15; + + while (kernelSize > maxVaryings) { + kernelSize -= 2; + } + + return kernelSize; +} + +},{}],144:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var ColorMatrixFilter = function (_core$Filter) { + _inherits(ColorMatrixFilter, _core$Filter); + + /** + * + */ + function ColorMatrixFilter() { + _classCallCheck(this, ColorMatrixFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n vec4 result;\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n // Premultiply alpha again.\n result.rgb *= result.a;\n\n gl_FragColor = result;\n}\n')); + + _this.uniforms.m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + return _this; + } + + /** + * Transforms current matrix and set the new one + * + * @param {number[]} matrix - 5x4 matrix + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix(matrix) { + var multiply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + var newMatrix = matrix; + + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + + // set the new matrix + this.uniforms.m = newMatrix; + }; + + /** + * Multiplies two mat5's + * + * @private + * @param {number[]} out - 5x4 matrix the receiving matrix + * @param {number[]} a - 5x4 matrix the first operand + * @param {number[]} b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix + */ + + + ColorMatrixFilter.prototype._multiply = function _multiply(out, a, b) { + // Red Channel + out[0] = a[0] * b[0] + a[1] * b[5] + a[2] * b[10] + a[3] * b[15]; + out[1] = a[0] * b[1] + a[1] * b[6] + a[2] * b[11] + a[3] * b[16]; + out[2] = a[0] * b[2] + a[1] * b[7] + a[2] * b[12] + a[3] * b[17]; + out[3] = a[0] * b[3] + a[1] * b[8] + a[2] * b[13] + a[3] * b[18]; + out[4] = a[0] * b[4] + a[1] * b[9] + a[2] * b[14] + a[3] * b[19] + a[4]; + + // Green Channel + out[5] = a[5] * b[0] + a[6] * b[5] + a[7] * b[10] + a[8] * b[15]; + out[6] = a[5] * b[1] + a[6] * b[6] + a[7] * b[11] + a[8] * b[16]; + out[7] = a[5] * b[2] + a[6] * b[7] + a[7] * b[12] + a[8] * b[17]; + out[8] = a[5] * b[3] + a[6] * b[8] + a[7] * b[13] + a[8] * b[18]; + out[9] = a[5] * b[4] + a[6] * b[9] + a[7] * b[14] + a[8] * b[19] + a[9]; + + // Blue Channel + out[10] = a[10] * b[0] + a[11] * b[5] + a[12] * b[10] + a[13] * b[15]; + out[11] = a[10] * b[1] + a[11] * b[6] + a[12] * b[11] + a[13] * b[16]; + out[12] = a[10] * b[2] + a[11] * b[7] + a[12] * b[12] + a[13] * b[17]; + out[13] = a[10] * b[3] + a[11] * b[8] + a[12] * b[13] + a[13] * b[18]; + out[14] = a[10] * b[4] + a[11] * b[9] + a[12] * b[14] + a[13] * b[19] + a[14]; + + // Alpha Channel + out[15] = a[15] * b[0] + a[16] * b[5] + a[17] * b[10] + a[18] * b[15]; + out[16] = a[15] * b[1] + a[16] * b[6] + a[17] * b[11] + a[18] * b[16]; + out[17] = a[15] * b[2] + a[16] * b[7] + a[17] * b[12] + a[18] * b[17]; + out[18] = a[15] * b[3] + a[16] * b[8] + a[17] * b[13] + a[18] * b[18]; + out[19] = a[15] * b[4] + a[16] * b[9] + a[17] * b[14] + a[18] * b[19] + a[19]; + + return out; + }; + + /** + * Create a Float32 Array and normalize the offset component to 0-1 + * + * @private + * @param {number[]} matrix - 5x4 matrix + * @return {number[]} 5x4 matrix with all values between 0-1 + */ + + + ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix(matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + + return m; + }; + + /** + * Adjusts brightness + * + * @param {number} b - value of the brigthness (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.brightness = function brightness(b, multiply) { + var matrix = [b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the matrices in grey scales + * + * @param {number} scale - value of the grey (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.greyscale = function greyscale(scale, multiply) { + var matrix = [scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the black and white matrice. + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite(multiply) { + var matrix = [0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the hue property of the color + * + * @param {number} rotation - in degrees + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.hue = function hue(rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + + var a00 = cosR + (1.0 - cosR) * w; + var a01 = w * (1.0 - cosR) - sqrW * sinR; + var a02 = w * (1.0 - cosR) + sqrW * sinR; + + var a10 = w * (1.0 - cosR) + sqrW * sinR; + var a11 = cosR + w * (1.0 - cosR); + var a12 = w * (1.0 - cosR) - sqrW * sinR; + + var a20 = w * (1.0 - cosR) - sqrW * sinR; + var a21 = w * (1.0 - cosR) + sqrW * sinR; + var a22 = cosR + w * (1.0 - cosR); + + var matrix = [a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * + * @param {number} amount - value of the contrast (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.contrast = function contrast(amount, multiply) { + var v = (amount || 0) + 1; + var o = -128 * (v - 1); + + var matrix = [v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * + * @param {number} amount - The saturation amount (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.saturate = function saturate() { + var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var multiply = arguments[1]; + + var x = amount * 2 / 3 + 1; + var y = (x - 1) * -0.5; + + var matrix = [x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Desaturate image (remove color) + * + * Call the saturate function + * + */ + + + ColorMatrixFilter.prototype.desaturate = function desaturate() // eslint-disable-line no-unused-vars + { + this.saturate(-1); + }; + + /** + * Negative image (inverse of classic rgb matrix) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.negative = function negative(multiply) { + var matrix = [0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Sepia image + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.sepia = function sepia(multiply) { + var matrix = [0.393, 0.7689999, 0.18899999, 0, 0, 0.349, 0.6859999, 0.16799999, 0, 0, 0.272, 0.5339999, 0.13099999, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.technicolor = function technicolor(multiply) { + var matrix = [1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Polaroid filter + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.polaroid = function polaroid(multiply) { + var matrix = [1.438, -0.062, -0.062, 0, 0, -0.122, 1.378, -0.122, 0, 0, -0.016, -0.016, 1.483, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Filter who transforms : Red -> Blue and Blue -> Red + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.toBGR = function toBGR(multiply) { + var matrix = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.kodachrome = function kodachrome(multiply) { + var matrix = [1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Brown delicious browni filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.browni = function browni(multiply) { + var matrix = [0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Vintage filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.vintage = function vintage(multiply) { + var matrix = [0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * + * @param {number} desaturation - Tone values. + * @param {number} toned - Tone values. + * @param {string} lightColor - Tone values, example: `0xFFE580` + * @param {string} darkColor - Tone values, example: `0xFFE580` + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.colorTone = function colorTone(desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + + var lR = (lightColor >> 16 & 0xFF) / 255; + var lG = (lightColor >> 8 & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + + var dR = (darkColor >> 16 & 0xFF) / 255; + var dG = (darkColor >> 8 & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + + var matrix = [0.3, 0.59, 0.11, 0, 0, lR, lG, lB, desaturation, 0, dR, dG, dB, toned, 0, lR - dR, lG - dG, lB - dB, 0, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Night effect + * + * @param {number} intensity - The intensity of the night effect. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.night = function night(intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [intensity * -2.0, -intensity, 0, 0, 0, -intensity, 0, intensity, 0, 0, 0, intensity, intensity * 2.0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * + * @param {number} amount - how much the predator feels his future victim + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.predator = function predator(amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * LSD effect + * + * Multiply the current matrix + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.lsd = function lsd(multiply) { + var matrix = [2, -0.4, 0.5, 0, 0, -0.5, 2, -0.4, 0, 0, -0.4, -0.5, 3, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Erase the current matrix by setting the default one + * + */ + + + ColorMatrixFilter.prototype.reset = function reset() { + var matrix = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, false); + }; + + /** + * The matrix of the color matrix filter + * + * @member {number[]} + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + + + _createClass(ColorMatrixFilter, [{ + key: 'matrix', + get: function get() { + return this.uniforms.m; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.m = value; + } + }]); + + return ColorMatrixFilter; +}(core.Filter); + +// Americanized alias + + +exports.default = ColorMatrixFilter; +ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + +},{"../../core":63,"path":22}],145:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. You can + * use this filter to apply all manor of crazy warping effects. Currently the r + * property of the texture is used to offset the x and the g property of the texture + * is used to offset the y. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var DisplacementFilter = function (_core$Filter) { + _inherits(DisplacementFilter, _core$Filter); + + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param {number} scale - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + _classCallCheck(this, DisplacementFilter); + + var maskMatrix = new core.Matrix(); + + sprite.renderable = false; + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n')); + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + + _this.uniforms.mapSampler = sprite.texture; + _this.uniforms.filterMatrix = maskMatrix; + _this.uniforms.scale = { x: 1, y: 1 }; + + if (scale === null || scale === undefined) { + scale = 20; + } + + _this.scale = new core.Point(scale, scale); + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + DisplacementFilter.prototype.apply = function apply(filterManager, input, output) { + var ratio = 1 / output.destinationFrame.width * (output.size.width / input.size.width); + + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x * ratio; + this.uniforms.scale.y = this.scale.y * ratio; + + // draw the filter... + filterManager.applyFilter(this, input, output); + }; + + /** + * The texture used for the displacement map. Must be power of 2 sized texture. + * + * @member {PIXI.Texture} + */ + + + _createClass(DisplacementFilter, [{ + key: 'map', + get: function get() { + return this.uniforms.mapSampler; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.mapSampler = value; + } + }]); + + return DisplacementFilter; +}(core.Filter); + +exports.default = DisplacementFilter; + +},{"../../core":63,"path":22}],146:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * Basic FXAA implementation based on the code on geeks3d.com with the + * modification that the texture2DLod stuff was removed since it's + * unsupported by WebGL. + * + * @see https://github.com/mitsuhiko/webgl-meincraft + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + * + */ +var FXAAFilter = function (_core$Filter) { + _inherits(FXAAFilter, _core$Filter); + + /** + * + */ + function FXAAFilter() { + _classCallCheck(this, FXAAFilter); + + // TODO - needs work + return _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + '\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}', + // fragment shader + 'varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n')); + } + + return FXAAFilter; +}(core.Filter); + +exports.default = FXAAFilter; + +},{"../../core":63,"path":22}],147:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _FXAAFilter = require('./fxaa/FXAAFilter'); + +Object.defineProperty(exports, 'FXAAFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_FXAAFilter).default; + } +}); + +var _NoiseFilter = require('./noise/NoiseFilter'); + +Object.defineProperty(exports, 'NoiseFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NoiseFilter).default; + } +}); + +var _DisplacementFilter = require('./displacement/DisplacementFilter'); + +Object.defineProperty(exports, 'DisplacementFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplacementFilter).default; + } +}); + +var _BlurFilter = require('./blur/BlurFilter'); + +Object.defineProperty(exports, 'BlurFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurFilter).default; + } +}); + +var _BlurXFilter = require('./blur/BlurXFilter'); + +Object.defineProperty(exports, 'BlurXFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurXFilter).default; + } +}); + +var _BlurYFilter = require('./blur/BlurYFilter'); + +Object.defineProperty(exports, 'BlurYFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurYFilter).default; + } +}); + +var _ColorMatrixFilter = require('./colormatrix/ColorMatrixFilter'); + +Object.defineProperty(exports, 'ColorMatrixFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ColorMatrixFilter).default; + } +}); + +var _VoidFilter = require('./void/VoidFilter'); + +Object.defineProperty(exports, 'VoidFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VoidFilter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./blur/BlurFilter":138,"./blur/BlurXFilter":139,"./blur/BlurYFilter":140,"./colormatrix/ColorMatrixFilter":144,"./displacement/DisplacementFilter":145,"./fxaa/FXAAFilter":146,"./noise/NoiseFilter":148,"./void/VoidFilter":149}],148:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Vico @vicocotea + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + */ + +/** + * A Noise effect filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var NoiseFilter = function (_core$Filter) { + _inherits(NoiseFilter, _core$Filter); + + /** + * + */ + function NoiseFilter() { + _classCallCheck(this, NoiseFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float noise;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n float diff = (rand(gl_FragCoord.xy) - 0.5) * noise;\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n gl_FragColor = color;\n}\n')); + + _this.noise = 0.5; + return _this; + } + + /** + * The amount of noise to apply. + * + * @member {number} + * @default 0.5 + */ + + + _createClass(NoiseFilter, [{ + key: 'noise', + get: function get() { + return this.uniforms.noise; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.noise = value; + } + }]); + + return NoiseFilter; +}(core.Filter); + +exports.default = NoiseFilter; + +},{"../../core":63,"path":22}],149:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Does nothing. Very handy. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var VoidFilter = function (_core$Filter) { + _inherits(VoidFilter, _core$Filter); + + /** + * + */ + function VoidFilter() { + _classCallCheck(this, VoidFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n')); + + _this.glShaderKey = 'void'; + return _this; + } + + return VoidFilter; +}(core.Filter); + +exports.default = VoidFilter; + +},{"../../core":63,"path":22}],150:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Holds all information related to an Interaction event + * + * @class + * @memberof PIXI.interaction + */ +var InteractionData = function () { + /** + * + */ + function InteractionData() { + _classCallCheck(this, InteractionData); + + /** + * This point stores the global coords of where the touch/mouse event happened + * + * @member {PIXI.Point} + */ + this.global = new core.Point(); + + /** + * The target DisplayObject that was interacted with + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * When passed to an event handler, this will be the original DOM Event that was captured + * + * @member {Event} + */ + this.originalEvent = null; + + /** + * Unique identifier for this interaction + * + * @member {number} + */ + this.identifier = null; + } + + /** + * This will return the local coordinates of the specified displayObject for this InteractionData + * + * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local + * coords off + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative + * to the DisplayObject + */ + + + InteractionData.prototype.getLocalPosition = function getLocalPosition(displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + + return InteractionData; +}(); + +exports.default = InteractionData; + +},{"../core":63}],151:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Event class that mimics native DOM events. + * + * @class + * @memberof PIXI.interaction + */ +var InteractionEvent = function () { + /** + * + */ + function InteractionEvent() { + _classCallCheck(this, InteractionEvent); + + /** + * Whether this event will continue propagating in the tree + * + * @member {boolean} + */ + this.stopped = false; + + /** + * The object which caused this event to be dispatched. + * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}. + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * The object whose event listener’s callback is currently being invoked. + * + * @member {PIXI.DisplayObject} + */ + this.currentTarget = null; + + /* + * Type of the event + * + * @member {string} + */ + this.type = null; + + /* + * InteractionData related to this event + * + * @member {PIXI.interaction.InteractionData} + */ + this.data = null; + } + + /** + * Prevents event from reaching any objects other than the current object. + * + */ + + + InteractionEvent.prototype.stopPropagation = function stopPropagation() { + this.stopped = true; + }; + + /** + * Resets the event. + * + * @private + */ + + + InteractionEvent.prototype._reset = function _reset() { + this.stopped = false; + this.currentTarget = null; + this.target = null; + }; + + return InteractionEvent; +}(); + +exports.default = InteractionEvent; + +},{}],152:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _InteractionData = require('./InteractionData'); + +var _InteractionData2 = _interopRequireDefault(_InteractionData); + +var _InteractionEvent = require('./InteractionEvent'); + +var _InteractionEvent2 = _interopRequireDefault(_InteractionEvent); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +var _InteractionTrackingData2 = _interopRequireDefault(_InteractionTrackingData); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _interactiveTarget = require('./interactiveTarget'); + +var _interactiveTarget2 = _interopRequireDefault(_interactiveTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// Mix interactiveTarget into core.DisplayObject.prototype, after deprecation has been handled +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _interactiveTarget2.default); + +var MOUSE_POINTER_ID = 'MOUSE'; + +// private constants for use in processInteractive - tracks whether we hit anything at all, or an +// actual interactive child, so that we can keep that state going back up the display tree +var HIT_NONE = 0; +var HIT_ANY = 1; +var HIT_INTERACTIVE = 2; + +/** + * The interaction manager deals with mouse, touch and pointer events. Any DisplayObject can be interactive + * if its interactive parameter is set to true + * This manager also supports multitouch. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.interaction + * + * @class + * @extends EventEmitter + * @memberof PIXI.interaction + */ + +var InteractionManager = function (_EventEmitter) { + _inherits(InteractionManager, _EventEmitter); + + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + * @param {object} [options] - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Frequency increases the interaction events will be checked. + */ + function InteractionManager(renderer, options) { + _classCallCheck(this, InteractionManager); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + options = options || {}; + + /** + * The renderer this interaction manager works for. + * + * @member {PIXI.SystemRenderer} + */ + _this.renderer = renderer; + + /** + * Should default browser actions automatically be prevented. + * Does not apply to pointer events for backwards compatibility + * preventDefault on pointer events stops mouse events from firing + * Thus, for every pointer event, there will always be either a mouse of touch event alongside it. + * + * @member {boolean} + * @default true + */ + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + + /** + * Frequency in milliseconds that the mousemove, moveover & mouseout interaction events will be checked. + * + * @member {number} + * @default 10 + */ + _this.interactionFrequency = options.interactionFrequency || 10; + + /** + * The mouse data + * + * @member {PIXI.interaction.InteractionData} + */ + _this.mouse = new _InteractionData2.default(); + _this.mouse.identifier = MOUSE_POINTER_ID; + + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + + /** + * Actively tracked InteractionData + * + * @private + * @member {Object.} + */ + _this.activeInteractionData = {}; + _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; + + /** + * Pool of unused InteractionData + * + * @private + * @member {PIXI.interation.InteractionData[]} + */ + _this.interactionDataPool = []; + + /** + * An event data object to handle all the event tracking/dispatching + * + * @member {object} + */ + _this.eventData = new _InteractionEvent2.default(); + + /** + * The DOM element to bind to. + * + * @private + * @member {HTMLElement} + */ + _this.interactionDOMElement = null; + + /** + * This property determines if mousemove and touchmove events are fired only when the cursor + * is over the object. + * Setting to true will make things work more in line with how the DOM verison works. + * Setting to false can make things easier for things like dragging + * It is currently set to false as this is how pixi used to work. This will be set to true in + * future versions of pixi. + * + * @member {boolean} + * @default false + */ + _this.moveWhenInside = false; + + /** + * Have events been attached to the dom element? + * + * @private + * @member {boolean} + */ + _this.eventsAdded = false; + + /** + * Is the mouse hovering over the renderer? + * + * @private + * @member {boolean} + */ + _this.mouseOverRenderer = false; + + /** + * Does the device support touch events + * https://www.w3.org/TR/touch-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsTouchEvents = 'ontouchstart' in window; + + /** + * Does the device support pointer events + * https://www.w3.org/Submission/pointer-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsPointerEvents = !!window.PointerEvent; + + // this will make it so that you don't have to call bind all the time + + /** + * @private + * @member {Function} + */ + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerCancel = _this.onPointerCancel.bind(_this); + _this.processPointerCancel = _this.processPointerCancel.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOver = _this.onPointerOver.bind(_this); + + /** + * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor + * values, objects are handled as dictionaries of CSS values for interactionDOMElement, + * and functions are called instead of changing the CSS. + * Default CSS cursor values are provided for 'default' and 'pointer' modes. + * @member {Object.)>} + */ + _this.cursorStyles = { + default: 'inherit', + pointer: 'pointer' + }; + + /** + * The mode of the cursor that is being used. + * The value of this is a key from the cursorStyles dictionary. + * + * @member {string} + */ + _this.currentCursorMode = null; + + /** + * Internal cached let. + * + * @private + * @member {string} + */ + _this.cursor = null; + + /** + * Internal cached let. + * + * @private + * @member {PIXI.Point} + */ + _this._tempPoint = new core.Point(); + + /** + * The current resolution / device pixel ratio. + * + * @member {number} + * @default 1 + */ + _this.resolution = 1; + + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + + /** + * Fired when a pointer device button (usually a mouse button) is pressed on the display + * object. + * + * @event mousedown + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * + * @event rightdown + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is released over the display + * object. + * + * @event mouseup + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * + * @event rightup + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is pressed and released on + * the display object. + * + * @event click + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * + * @event rightclick + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. + * + * @event mouseupoutside + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. + * + * @event rightupoutside + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * + * @event mousemove + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * + * @event mouseover + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * + * @event mouseout + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * + * @event pointerdown + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is released over the display object. + * + * @event pointerup + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when the operating system cancels a pointer event + * + * @event pointercancel + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * + * @event pointertap + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}. + * + * @event pointerupoutside + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved while over the display object + * + * @event pointermove + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved onto the display object + * + * @event pointerover + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved off the display object + * + * @event pointerout + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is placed on the display object. + * + * @event touchstart + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is removed from the display object. + * + * @event touchend + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when the operating system cancels a touch + * + * @event touchcancel + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * + * @event tap + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. + * + * @event touchendoutside + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is moved along the display object. + * + * @event touchmove + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + return _this; + } + + /** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate + * another DOM element to receive those events. + * + * @param {HTMLCanvasElement} element - the DOM element which will receive mouse and touch events. + * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). + * @private + */ + + + InteractionManager.prototype.setTargetElement = function setTargetElement(element) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.removeEvents(); + + this.interactionDOMElement = element; + + this.resolution = resolution; + + this.addEvents(); + }; + + /** + * Registers all the DOM events + * + * @private + */ + + + InteractionManager.prototype.addEvents = function addEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.add(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; + this.interactionDOMElement.style['-ms-touch-action'] = 'none'; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = 'none'; + } + + /** + * These events are added first, so that if pointer events are normalised, they are fired + * in the same order as non-normalised events. ie. pointer event 1st, mouse / touch 2nd + */ + if (this.supportsPointerEvents) { + window.document.addEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); + // pointerout is fired in addition to pointerup (for touch events) and pointercancel + // we already handle those, so for the purposes of what we do in onPointerOut, we only + // care about the pointerleave event + this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); + window.addEventListener('pointercancel', this.onPointerCancel, true); + window.addEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.addEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); + window.addEventListener('mouseup', this.onPointerUp, true); + + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); + } + } + + this.eventsAdded = true; + }; + + /** + * Removes all the DOM events that were previously registered + * + * @private + */ + + + InteractionManager.prototype.removeEvents = function removeEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.remove(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = ''; + this.interactionDOMElement.style['-ms-touch-action'] = ''; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = ''; + } + + if (this.supportsPointerEvents) { + window.document.removeEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); + window.removeEventListener('pointercancel', this.onPointerCancel, true); + window.removeEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.removeEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true); + window.removeEventListener('mouseup', this.onPointerUp, true); + + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); + } + } + + this.interactionDOMElement = null; + + this.eventsAdded = false; + }; + + /** + * Updates the state of interactive objects. + * Invoked by a throttled ticker update from {@link PIXI.ticker.shared}. + * + * @param {number} deltaTime - time delta since last tick + */ + + + InteractionManager.prototype.update = function update(deltaTime) { + this._deltaTime += deltaTime; + + if (this._deltaTime < this.interactionFrequency) { + return; + } + + this._deltaTime = 0; + + if (!this.interactionDOMElement) { + return; + } + + // if the user move the mouse this check has already been done using the mouse move! + if (this.didMove) { + this.didMove = false; + + return; + } + + this.cursor = null; + + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + for (var k in this.activeInteractionData) { + // eslint-disable-next-line no-prototype-builtins + if (this.activeInteractionData.hasOwnProperty(k)) { + var interactionData = this.activeInteractionData[k]; + + if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, true); + } + } + } + + this.setCursorMode(this.cursor); + + // TODO + }; + + /** + * Sets the current cursor mode, handling any callbacks or CSS style changes. + * + * @param {string} mode - cursor mode, a key from the cursorStyles dictionary + */ + + + InteractionManager.prototype.setCursorMode = function setCursorMode(mode) { + mode = mode || 'default'; + // if the mode didn't actually change, bail early + if (this.currentCursorMode === mode) { + return; + } + this.currentCursorMode = mode; + var style = this.cursorStyles[mode]; + + // only do things if there is a cursor style for it + if (style) { + switch (typeof style === 'undefined' ? 'undefined' : _typeof(style)) { + case 'string': + // string styles are handled as cursor CSS + this.interactionDOMElement.style.cursor = style; + break; + case 'function': + // functions are just called, and passed the cursor mode + style(mode); + break; + case 'object': + // if it is an object, assume that it is a dictionary of CSS styles, + // apply it to the interactionDOMElement + Object.assign(this.interactionDOMElement.style, style); + break; + } + } + }; + + /** + * Dispatches an event on the display object that was interacted with + * + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the display object in question + * @param {string} eventString - the name of the event (e.g, mousedown) + * @param {object} eventData - the event data object + * @private + */ + + + InteractionManager.prototype.dispatchEvent = function dispatchEvent(displayObject, eventString, eventData) { + if (!eventData.stopped) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + + displayObject.emit(eventString, eventData); + + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } + }; + + /** + * Maps x and y coords from a DOM object and maps them correctly to the pixi view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. + * + * @param {PIXI.Point} point - the point that the result will be stored in + * @param {number} x - the x coord of the position to map + * @param {number} y - the y coord of the position to map + */ + + + InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint(point, x, y) { + var rect = void 0; + + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { x: 0, y: 0, width: 0, height: 0 }; + } else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + + var resolutionMultiplier = navigator.isCocoonJS ? this.resolution : 1.0 / this.resolution; + + point.x = (x - rect.left) * (this.interactionDOMElement.width / rect.width) * resolutionMultiplier; + point.y = (y - rect.top) * (this.interactionDOMElement.height / rect.height) * resolutionMultiplier; + }; + + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * + * @private + * @param {InteractionEvent} interactionEvent - event containing the point that + * is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param {Function} [func] - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point + * @param {boolean} [interactive] - Whether the displayObject is interactive + * @return {number} returns 1 or 2 if the displayObject hit the point, 0 if not + */ + + + InteractionManager.prototype.processInteractive = function processInteractive(interactionEvent, displayObject, func, hitTest, interactive) { + if (!displayObject || !displayObject.visible) { + return false; + } + + var point = interactionEvent.data.global; + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + interactive = displayObject.interactive || interactive; + + var hit = HIT_NONE; + var interactiveParent = interactive; + + // if the displayobject has a hitArea, then it does not need to hitTest children. + if (displayObject.hitArea) { + interactiveParent = false; + } + // it has a mask! Then lets hit test that before continuing + else if (hitTest && displayObject._mask) { + if (!displayObject._mask.containsPoint(point)) { + hitTest = false; + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow pixi to completely ignore and bypass checking the displayObjects children. + if (displayObject.interactiveChildren && displayObject.children) { + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + + // time to get recursive.. if this function will return if something is hit.. + var childHit = this.processInteractive(interactionEvent, child, func, hitTest, interactiveParent); + + if (childHit) { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if (!child.parent) { + continue; + } + + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + + if (childHit === HIT_INTERACTIVE) { + hitTest = false; + hit = HIT_INTERACTIVE; + } else if (hit === HIT_NONE) { + hit = HIT_ANY; + } + } + } + } + + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit - but only if it was interactive, otherwise we need to keep + // looking for an interactive child, just in case we hit one + if (hitTest && hit !== HIT_INTERACTIVE) { + if (displayObject.hitArea) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hit = displayObject.interactive ? HIT_INTERACTIVE : HIT_ANY; + } + } else if (displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = displayObject.interactive ? HIT_INTERACTIVE : HIT_ANY; + } + } + } + + if (displayObject.interactive) { + if (hit && !interactionEvent.target) { + interactionEvent.target = displayObject; + } + + func(interactionEvent, displayObject, !!hit); + } + } + + return hit; + }; + + /** + * Is called when the pointer button is pressed down on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down + */ + + + InteractionManager.prototype.onPointerDown = function onPointerDown(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + /** + * No need to prevent default on natural pointer events, as there are no side effects + * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, + * so still need to be prevented. + */ + + // Guaranteed that there will be at least one event in events, and all events must have the same pointer type + + if (this.autoPreventDefault && events[0].isNormalized) { + originalEvent.preventDefault(); + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerDown, true); + + this.emit('pointerdown', interactionEvent); + if (event.pointerType === 'touch') { + this.emit('touchstart', interactionEvent); + } else if (event.pointerType === 'mouse') { + var isRightButton = event.button === 2 || event.which === 3; + + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + } + }; + + /** + * Processes the result of the pointer down check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerDown = function processPointerDown(interactionEvent, displayObject, hit) { + var e = interactionEvent.data.originalEvent; + + var id = interactionEvent.data.identifier; + + if (hit) { + if (!displayObject.trackedPointers[id]) { + displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + + if (e.type === 'touchstart' || e.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchstart', interactionEvent); + } else if (e.type === 'mousedown' || e.pointerType === 'mouse') { + var isRightButton = e.button === 2 || e.which === 3; + + if (isRightButton) { + displayObject.trackedPointers[id].rightDown = true; + } else { + displayObject.trackedPointers[id].leftDown = true; + } + + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released + * @param {boolean} cancelled - true if the pointer is cancelled + * @param {Function} func - Function passed to {@link processInteractive} + */ + + + InteractionManager.prototype.onPointerComplete = function onPointerComplete(originalEvent, cancelled, func) { + var events = this.normalizeToPointerData(originalEvent); + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, func, true); + + this.emit(cancelled ? 'pointercancel' : 'pointerup', interactionEvent); + + if (event.pointerType === 'mouse') { + var isRightButton = event.button === 2 || event.which === 3; + + this.emit(isRightButton ? 'rightup' : 'mouseup', interactionEvent); + } else if (event.pointerType === 'touch') { + this.emit(cancelled ? 'touchcancel' : 'touchend', interactionEvent); + this.releaseInteractionDataForPointerId(event.pointerId, interactionData); + } + } + }; + + /** + * Is called when the pointer button is cancelled + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerCancel = function onPointerCancel(event) { + this.onPointerComplete(event, true, this.processPointerCancel); + }; + + /** + * Processes the result of the pointer cancel check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + */ + + + InteractionManager.prototype.processPointerCancel = function processPointerCancel(interactionEvent, displayObject) { + var e = interactionEvent.data.originalEvent; + + var id = interactionEvent.data.identifier; + + if (displayObject.trackedPointers[id] !== undefined) { + delete displayObject.trackedPointers[id]; + this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); + + if (e.type === 'touchcancel' || e.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerUp = function onPointerUp(event) { + this.onPointerComplete(event, false, this.processPointerUp); + }; + + /** + * Processes the result of the pointer up check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerUp = function processPointerUp(interactionEvent, displayObject, hit) { + var e = interactionEvent.data.originalEvent; + + var id = interactionEvent.data.identifier; + + var trackingData = displayObject.trackedPointers[id]; + + var isTouch = e.type === 'touchend' || e.pointerType === 'touch'; + + var isMouse = e.type.indexOf('mouse') === 0 || e.pointerType === 'mouse'; + + // Mouse only + if (isMouse) { + var isRightButton = e.button === 2 || e.which === 3; + + var flags = _InteractionTrackingData2.default.FLAGS; + + var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; + + var isDown = trackingData !== undefined && trackingData.flags & test; + + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); + + if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); + } + } else if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); + } + // update the down state of the tracking data + if (trackingData) { + if (isRightButton) { + trackingData.rightDown = false; + } else { + trackingData.leftDown = false; + } + } + } + + // Pointers and Touches, and Mouse + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchend', interactionEvent); + + if (trackingData) { + this.dispatchEvent(displayObject, 'pointertap', interactionEvent); + if (isTouch) { + this.dispatchEvent(displayObject, 'tap', interactionEvent); + // touches are no longer over (if they ever were) when we get the touchend + // so we should ensure that we don't keep pretending that they are + trackingData.over = false; + } + } + } else if (trackingData) { + this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); + } + // Only remove the tracking data if there is no over/down state still associated with it + if (trackingData && trackingData.none) { + delete displayObject.trackedPointers[id]; + } + }; + + /** + * Is called when the pointer moves across the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer moving + */ + + + InteractionManager.prototype.onPointerMove = function onPointerMove(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + if (events[0].pointerType === 'mouse') { + this.didMove = true; + + this.cursor = null; + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + var interactive = event.pointerType === 'touch' ? this.moveWhenInside : true; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerMove, interactive); + this.emit('pointermove', interactionEvent); + if (event.pointerType === 'touch') this.emit('touchmove', interactionEvent); + if (event.pointerType === 'mouse') this.emit('mousemove', interactionEvent); + } + + if (events[0].pointerType === 'mouse') { + this.setCursorMode(this.cursor); + + // TODO BUG for parents interactive object (border order issue) + } + }; + + /** + * Processes the result of the pointer move check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerMove = function processPointerMove(interactionEvent, displayObject, hit) { + var e = interactionEvent.data.originalEvent; + + var isTouch = e.type === 'touchmove' || e.pointerType === 'touch'; + + var isMouse = e.type === 'mousemove' || e.pointerType === 'mouse'; + + if (isMouse) { + this.processPointerOverOut(interactionEvent, displayObject, hit); + } + + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchmove', interactionEvent); + if (isMouse) this.dispatchEvent(displayObject, 'mousemove', interactionEvent); + } + }; + + /** + * Is called when the pointer is moved out of the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out + */ + + + InteractionManager.prototype.onPointerOut = function onPointerOut(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOut, so events will always be length 1 + var event = events[0]; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = false; + this.setCursorMode(null); + } + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, false); + + this.emit('pointerout', interactionEvent); + if (event.pointerType === 'mouse') { + this.emit('mouseout', interactionEvent); + } else { + // we can get touchleave events after touchend, so we want to make sure we don't + // introduce memory leaks + this.releaseInteractionDataForPointerId(interactionData.identifier); + } + }; + + /** + * Processes the result of the pointer over/out check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerOverOut = function processPointerOverOut(interactionEvent, displayObject, hit) { + var e = interactionEvent.data.originalEvent; + + var id = interactionEvent.data.identifier; + + var isMouse = e.type === 'mouseover' || e.type === 'mouseout' || e.pointerType === 'mouse'; + + var trackingData = displayObject.trackedPointers[id]; + + // if we just moused over the display object, then we need to track that state + if (hit && !trackingData) { + trackingData = displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + + if (trackingData === undefined) return; + + if (hit && this.mouseOverRenderer) { + if (!trackingData.over) { + trackingData.over = true; + this.dispatchEvent(displayObject, 'pointerover', interactionEvent); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseover', interactionEvent); + } + } + + // only change the cursor if it has not already been changed (by something deeper in the + // display tree) + if (isMouse && this.cursor === null) { + this.cursor = displayObject.cursor; + } + } else if (trackingData.over) { + trackingData.over = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseout', interactionEvent); + } + // if there is no mouse down information for the pointer, then it is safe to delete + if (trackingData.none) { + delete displayObject.trackedPointers[id]; + } + } + }; + + /** + * Is called when the pointer is moved into the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view + */ + + + InteractionManager.prototype.onPointerOver = function onPointerOver(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOver, so events will always be length 1 + var event = events[0]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = true; + } + + this.emit('pointerover', interactionEvent); + if (event.pointerType === 'mouse') { + this.emit('mouseover', interactionEvent); + } + }; + + /** + * Get InteractionData for a given pointerId. Store that data as well + * + * @private + * @param {PointerEvent} event - Normalized pointer event, output from normalizeToPointerData + * @return {InteractionData} - Interaction data for the given pointer identifier + */ + + + InteractionManager.prototype.getInteractionDataForPointerId = function getInteractionDataForPointerId(event) { + var pointerId = event.pointerId; + + if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { + return this.mouse; + } else if (this.activeInteractionData[pointerId]) { + return this.activeInteractionData[pointerId]; + } + + var interactionData = this.interactionDataPool.pop() || new _InteractionData2.default(); + + interactionData.identifier = pointerId; + this.activeInteractionData[pointerId] = interactionData; + + return interactionData; + }; + + /** + * Return unused InteractionData to the pool, for a given pointerId + * + * @private + * @param {number} pointerId - Identifier from a pointer event + */ + + + InteractionManager.prototype.releaseInteractionDataForPointerId = function releaseInteractionDataForPointerId(pointerId) { + var interactionData = this.activeInteractionData[pointerId]; + + if (interactionData) { + delete this.activeInteractionData[pointerId]; + this.interactionDataPool.push(interactionData); + } + }; + + /** + * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData + * + * @private + * @param {InteractionEvent} interactionEvent - The event to be configured + * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent + * @param {InteractionData} interactionData - The InteractionData that will be paired with the InteractionEvent + * @return {InteractionEvent} the interaction event that was passed in + */ + + + InteractionManager.prototype.configureInteractionEventForDOMEvent = function configureInteractionEventForDOMEvent(interactionEvent, pointerEvent, interactionData) { + interactionEvent.data = interactionData; + + this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); + + // This is the way InteractionManager processed touch events before the refactoring, so I've kept + // it here. But it doesn't make that much sense to me, since mapPositionToPoint already factors + // in this.resolution, so this just divides by this.resolution twice for touch events... + if (navigator.isCocoonJS && pointerEvent.pointerType === 'touch') { + interactionData.global.x = interactionData.global.x / this.resolution; + interactionData.global.y = interactionData.global.y / this.resolution; + } + + // Not really sure why this is happening, but it's how a previous version handled things + if (pointerEvent.pointerType === 'touch') { + pointerEvent.globalX = interactionData.global.x; + pointerEvent.globalY = interactionData.global.y; + } + + interactionData.originalEvent = pointerEvent; + interactionEvent._reset(); + + return interactionEvent; + }; + + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * + * @private + * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event + * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer + * or mouse event, or a multiple normalized pointer events if there are multiple changed touches + */ + + + InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData(event) { + var normalizedEvents = []; + + if (this.supportsTouchEvents && event instanceof TouchEvent) { + for (var i = 0, li = event.changedTouches.length; i < li; i++) { + var touch = event.changedTouches[i]; + + if (typeof touch.button === 'undefined') touch.button = event.touches.length ? 1 : 0; + if (typeof touch.buttons === 'undefined') touch.buttons = event.touches.length ? 1 : 0; + if (typeof touch.isPrimary === 'undefined') touch.isPrimary = event.touches.length === 1; + if (typeof touch.width === 'undefined') touch.width = touch.radiusX || 1; + if (typeof touch.height === 'undefined') touch.height = touch.radiusY || 1; + if (typeof touch.tiltX === 'undefined') touch.tiltX = 0; + if (typeof touch.tiltY === 'undefined') touch.tiltY = 0; + if (typeof touch.pointerType === 'undefined') touch.pointerType = 'touch'; + if (typeof touch.pointerId === 'undefined') touch.pointerId = touch.identifier || 0; + if (typeof touch.pressure === 'undefined') touch.pressure = touch.force || 0.5; + if (typeof touch.rotation === 'undefined') touch.rotation = touch.rotationAngle || 0; + + if (typeof touch.layerX === 'undefined') touch.layerX = touch.offsetX = touch.clientX; + if (typeof touch.layerY === 'undefined') touch.layerY = touch.offsetY = touch.clientY; + + // mark the touch as normalized, just so that we know we did it + touch.isNormalized = true; + + normalizedEvents.push(touch); + } + } + // apparently PointerEvent subclasses MouseEvent, so yay + else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent))) { + if (typeof event.isPrimary === 'undefined') event.isPrimary = true; + if (typeof event.width === 'undefined') event.width = 1; + if (typeof event.height === 'undefined') event.height = 1; + if (typeof event.tiltX === 'undefined') event.tiltX = 0; + if (typeof event.tiltY === 'undefined') event.tiltY = 0; + if (typeof event.pointerType === 'undefined') event.pointerType = 'mouse'; + if (typeof event.pointerId === 'undefined') event.pointerId = MOUSE_POINTER_ID; + if (typeof event.pressure === 'undefined') event.pressure = 0.5; + if (typeof event.rotation === 'undefined') event.rotation = 0; + + // mark the mouse event as normalized, just so that we know we did it + event.isNormalized = true; + + normalizedEvents.push(event); + } else { + normalizedEvents.push(event); + } + + return normalizedEvents; + }; + + /** + * Destroys the interaction manager + * + */ + + + InteractionManager.prototype.destroy = function destroy() { + this.removeEvents(); + + this.removeAllListeners(); + + this.renderer = null; + + this.mouse = null; + + this.eventData = null; + + this.interactionDOMElement = null; + + this.onPointerDown = null; + this.processPointerDown = null; + + this.onPointerUp = null; + this.processPointerUp = null; + + this.onPointerCancel = null; + this.processPointerCancel = null; + + this.onPointerMove = null; + this.processPointerMove = null; + + this.onPointerOut = null; + this.processPointerOverOut = null; + + this.onPointerOver = null; + + this._tempPoint = null; + }; + + return InteractionManager; +}(_eventemitter2.default); + +exports.default = InteractionManager; + + +core.WebGLRenderer.registerPlugin('interaction', InteractionManager); +core.CanvasRenderer.registerPlugin('interaction', InteractionManager); + +},{"../core":63,"./InteractionData":150,"./InteractionEvent":151,"./InteractionTrackingData":153,"./interactiveTarget":155,"eventemitter3":3}],153:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * DisplayObjects with the {@link PIXI.interaction.interactiveTarget} mixin use this class to track interactions + * + * @class + * @private + * @memberof PIXI.interaction + */ +var InteractionTrackingData = function () { + /** + * @param {number} pointerId - Unique pointer id of the event + */ + function InteractionTrackingData(pointerId) { + _classCallCheck(this, InteractionTrackingData); + + this._pointerId = pointerId; + this._flags = InteractionTrackingData.FLAGS.NONE; + } + + /** + * + * @private + * @param {number} flag - The interaction flag to set + * @param {boolean} yn - Should the flag be set or unset + */ + + + InteractionTrackingData.prototype._doSet = function _doSet(flag, yn) { + if (yn) { + this._flags = this._flags | flag; + } else { + this._flags = this._flags & ~flag; + } + }; + + /** + * @readonly + * @type {number} Unique pointer id of the event + */ + + + _createClass(InteractionTrackingData, [{ + key: "pointerId", + get: function get() { + return this._pointerId; + } + + /** + * State of the tracking data, expressed as bit flags + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "flags", + get: function get() { + return this._flags; + } + + /** + * Set the flags for the tracking data + * + * @param {number} flags - Flags to set + */ + , + set: function set(flags) { + this._flags = flags; + } + + /** + * Is the tracked event inactive (not over or down)? + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "none", + get: function get() { + return this._flags === this.constructor.FLAGS.NONE; + } + + /** + * Is the tracked event over the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "over", + get: function get() { + return (this._flags & this.constructor.FLAGS.OVER) !== 0; + } + + /** + * Set the over flag + * + * @param {boolean} yn - Is the event over? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.OVER, yn); + } + + /** + * Did the right mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "rightDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.RIGHT_DOWN) !== 0; + } + + /** + * Set the right down flag + * + * @param {boolean} yn - Is the right mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.RIGHT_DOWN, yn); + } + + /** + * Did the left mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "leftDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.LEFT_DOWN) !== 0; + } + + /** + * Set the left down flag + * + * @param {boolean} yn - Is the left mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.LEFT_DOWN, yn); + } + }]); + + return InteractionTrackingData; +}(); + +exports.default = InteractionTrackingData; + + +InteractionTrackingData.FLAGS = Object.freeze({ + NONE: 0, + OVER: 1 << 0, + LEFT_DOWN: 1 << 1, + RIGHT_DOWN: 1 << 2 +}); + +},{}],154:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _InteractionData = require('./InteractionData'); + +Object.defineProperty(exports, 'InteractionData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionData).default; + } +}); + +var _InteractionManager = require('./InteractionManager'); + +Object.defineProperty(exports, 'InteractionManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionManager).default; + } +}); + +var _interactiveTarget = require('./interactiveTarget'); + +Object.defineProperty(exports, 'interactiveTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_interactiveTarget).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./InteractionData":150,"./InteractionManager":152,"./interactiveTarget":155}],155:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * Default property values of interactive objects + * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties + * + * @mixin + * @name interactiveTarget + * @memberof PIXI.interaction + * @example + * function MyObject() {} + * + * Object.assign( + * core.DisplayObject.prototype, + * PIXI.interaction.interactiveTarget + * ); + */ +exports.default = { + /** + * Determines if the displayObject be clicked/touched + * + * @inner {boolean} + */ + interactive: false, + + /** + * Determines if the children to the displayObject can be clicked/touched + * Setting this to false allows pixi to bypass a recursive hitTest function + * + * @inner {boolean} + */ + interactiveChildren: true, + + /** + * Interaction shape. Children will be hit first, then this shape will be checked. + * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. + * + * @inner {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle} + */ + hitArea: null, + + /** + * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive + * Setting this changes the 'cursor' property to `'pointer'`. + * + * @member {boolean} + * @memberof PIXI.interaction.interactiveTarget# + */ + get buttonMode() { + return this.cursor === 'pointer'; + }, + set buttonMode(value) { + if (value) { + this.cursor = 'pointer'; + } else if (this.cursor === 'pointer') { + this.cursor = null; + } + }, + + /** + * This defines what cursor mode is used when the mouse cursor + * is hovered over the displayObject. + * + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * + * @inner {string} + */ + cursor: null, + + /** + * Internal set of all active pointers, by identifier + * + * @member {Map} + * @memberof PIXI.interaction.interactiveTarget# + * @private + */ + get trackedPointers() { + if (this._trackedPointers === undefined) this._trackedPointers = {}; + + return this._trackedPointers; + }, + + /** + * Map of all tracked pointers, by identifier. Use trackedPointers to access. + * + * @private {Map} + */ + _trackedPointers: undefined +}; + +},{}],156:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.parse = parse; + +exports.default = function () { + return function bitmapFontParser(resource, next) { + // skip if no data or not xml data + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.XML) { + next(); + + return; + } + + // skip if not bitmap font data, using some silly duck-typing + if (resource.data.getElementsByTagName('page').length === 0 || resource.data.getElementsByTagName('info').length === 0 || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null) { + next(); + + return; + } + + var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; + + if (resource.isDataUrl) { + if (xmlUrl === '.') { + xmlUrl = ''; + } + + if (this.baseUrl && xmlUrl) { + // if baseurl has a trailing slash then add one to xmlUrl so the replace works below + if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { + xmlUrl += '/'; + } + + // remove baseUrl from xmlUrl + xmlUrl = xmlUrl.replace(this.baseUrl, ''); + } + } + + // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { + xmlUrl += '/'; + } + + var textureUrl = xmlUrl + resource.data.getElementsByTagName('page')[0].getAttribute('file'); + + if (_core.utils.TextureCache[textureUrl]) { + // reuse existing texture + parse(resource, _core.utils.TextureCache[textureUrl]); + next(); + } else { + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + // load the texture for the font + this.add(resource.name + '_image', textureUrl, loadOptions, function (res) { + parse(resource, res.texture); + next(); + }); + } + }; +}; + +var _path = require('path'); + +var path = _interopRequireWildcard(_path); + +var _core = require('../core'); + +var _resourceLoader = require('resource-loader'); + +var _extras = require('../extras'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Register a BitmapText font from loader resource. + * + * @function parseBitmapFontData + * @memberof PIXI.loaders + * @param {PIXI.loaders.Resource} resource - Loader resource. + * @param {PIXI.Texture} texture - Reference to texture. + */ +function parse(resource, texture) { + resource.bitmapFont = _extras.BitmapText.registerFont(resource.data, texture); +} + +},{"../core":63,"../extras":136,"path":22,"resource-loader":34}],157:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _loader = require('./loader'); + +Object.defineProperty(exports, 'Loader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_loader).default; + } +}); + +var _bitmapFontParser = require('./bitmapFontParser'); + +Object.defineProperty(exports, 'bitmapFontParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_bitmapFontParser).default; + } +}); +Object.defineProperty(exports, 'parseBitmapFontData', { + enumerable: true, + get: function get() { + return _bitmapFontParser.parse; + } +}); + +var _spritesheetParser = require('./spritesheetParser'); + +Object.defineProperty(exports, 'spritesheetParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_spritesheetParser).default; + } +}); + +var _textureParser = require('./textureParser'); + +Object.defineProperty(exports, 'textureParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_textureParser).default; + } +}); + +var _resourceLoader = require('resource-loader'); + +Object.defineProperty(exports, 'Resource', { + enumerable: true, + get: function get() { + return _resourceLoader.Resource; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./bitmapFontParser":156,"./loader":158,"./spritesheetParser":159,"./textureParser":160,"resource-loader":34}],158:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _resourceLoader = require('resource-loader'); + +var _resourceLoader2 = _interopRequireDefault(_resourceLoader); + +var _blob = require('resource-loader/lib/middlewares/parsing/blob'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _textureParser = require('./textureParser'); + +var _textureParser2 = _interopRequireDefault(_textureParser); + +var _spritesheetParser = require('./spritesheetParser'); + +var _spritesheetParser2 = _interopRequireDefault(_spritesheetParser); + +var _bitmapFontParser = require('./bitmapFontParser'); + +var _bitmapFontParser2 = _interopRequireDefault(_bitmapFontParser); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader + * + * ```js + * const loader = PIXI.loader; // pixi exposes a premade instance for you to use. + * //or + * const loader = new PIXI.loaders.Loader(); // you can also create your own if you want + * + * const sprites = {}; + * + * // Chainable `add` to enqueue a resource + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.add('scoreFont', 'assets/score.fnt'); + * + * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. + * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). + * loader.pre(cachingMiddleware); + * + * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. + * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). + * loader.use(parsingMiddleware); + * + * // The `load` method loads the queue of resources, and calls the passed in callback called once all + * // resources have loaded. + * loader.load((loader, resources) => { + * // resources is an object where the key is the name of the resource loaded and the value is the resource object. + * // They have a couple default properties: + * // - `url`: The URL that the resource was loaded from + * // - `error`: The error that happened when trying to load (if any) + * // - `data`: The raw data that was loaded + * // also may contain other properties based on the middleware that runs. + * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); + * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); + * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); + * }); + * + * // throughout the process multiple signals can be dispatched. + * loader.onProgress.add(() => {}); // called once per loaded/errored file + * loader.onError.add(() => {}); // called once per errored file + * loader.onLoad.add(() => {}); // called once per loaded file + * loader.onComplete.add(() => {}); // called once when the queued resources all load. + * ``` + * + * @see https://github.com/englercj/resource-loader + * + * @class + * @extends module:resource-loader.ResourceLoader + * @memberof PIXI.loaders + */ +var Loader = function (_ResourceLoader) { + _inherits(Loader, _ResourceLoader); + + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + _classCallCheck(this, Loader); + + var _this = _possibleConstructorReturn(this, _ResourceLoader.call(this, baseUrl, concurrency)); + + _eventemitter2.default.call(_this); + + for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { + _this.use(Loader._pixiMiddleware[i]()); + } + + // Compat layer, translate the new v2 signals into old v1 events. + _this.onStart.add(function (l) { + return _this.emit('start', l); + }); + _this.onProgress.add(function (l, r) { + return _this.emit('progress', l, r); + }); + _this.onError.add(function (e, l, r) { + return _this.emit('error', e, l, r); + }); + _this.onLoad.add(function (l, r) { + return _this.emit('load', l, r); + }); + _this.onComplete.add(function (l, r) { + return _this.emit('complete', l, r); + }); + return _this; + } + + /** + * Adds a default middleware to the pixi loader. + * + * @static + * @param {Function} fn - The middleware to add. + */ + + + Loader.addPixiMiddleware = function addPixiMiddleware(fn) { + Loader._pixiMiddleware.push(fn); + }; + + return Loader; +}(_resourceLoader2.default); + +// Copy EE3 prototype (mixin) + + +exports.default = Loader; +for (var k in _eventemitter2.default.prototype) { + Loader.prototype[k] = _eventemitter2.default.prototype[k]; +} + +Loader._pixiMiddleware = [ +// parse any blob into more usable objects (e.g. Image) +_blob.blobMiddlewareFactory, +// parse any Image objects into textures +_textureParser2.default, +// parse any spritesheet data into multiple textures +_spritesheetParser2.default, +// parse bitmap font data into multiple textures +_bitmapFontParser2.default]; + +// Add custom extentions +var Resource = _resourceLoader2.default.Resource; + +Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); + +},{"./bitmapFontParser":156,"./spritesheetParser":159,"./textureParser":160,"eventemitter3":3,"resource-loader":34,"resource-loader/lib/middlewares/parsing/blob":35}],159:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function spritesheetParser(resource, next) { + var resourcePath = void 0; + var imageResourceName = resource.name + '_image'; + + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.JSON || !resource.data.frames || this.resources[imageResourceName]) { + next(); + + return; + } + + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + resourcePath = resource.data.meta.image; + } else { + resourcePath = _path2.default.dirname(resource.url.replace(this.baseUrl, '')) + '/' + resource.data.meta.image; + } + + // load the image for this sheet + this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + var spritesheet = new _core.Spritesheet(res.texture.baseTexture, resource.data, resource.url); + + spritesheet.parse(function () { + resource.spritesheet = spritesheet; + resource.textures = spritesheet.textures; + next(); + }); + }); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _path = require('path'); + +var _path2 = _interopRequireDefault(_path); + +var _core = require('../core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"../core":63,"path":22,"resource-loader":34}],160:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function textureParser(resource, next) { + // create a new texture if the data is an Image object + if (resource.data && resource.type === _resourceLoader.Resource.TYPE.IMAGE) { + resource.texture = _Texture2.default.fromLoader(resource.data, resource.url, resource.name); + } + next(); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"../core/textures/Texture":112,"resource-loader":34}],161:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); +var tempPolygon = new core.Polygon(); + +/** + * Base mesh class + * @class + * @extends PIXI.Container + * @memberof PIXI.mesh + */ + +var Mesh = function (_core$Container) { + _inherits(Mesh, _core$Container); + + /** + * @param {PIXI.Texture} texture - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts + */ + function Mesh(texture, vertices, uvs, indices, drawMode) { + _classCallCheck(this, Mesh); + + /** + * The texture of the Mesh + * + * @member {PIXI.Texture} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._texture = null; + + /** + * The Uvs of the Mesh + * + * @member {Float32Array} + */ + _this.uvs = uvs || new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + /** + * An array of vertices + * + * @member {Float32Array} + */ + _this.vertices = vertices || new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]); + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + // TODO auto generate this based on draw mode! + _this.indices = indices || new Uint16Array([0, 1, 3, 2]); + + /** + * Version of mesh uvs are dirty or not + * + * @member {number} + */ + _this.dirty = 0; + + /** + * Version of mesh indices + * + * @member {number} + */ + _this.indexDirty = 0; + + /** + * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove + * any blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles + * to overlap a bit with each other. + * + * @member {number} + */ + _this.canvasPadding = 0; + + /** + * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts + * + * @member {number} + * @see PIXI.mesh.Mesh.DRAW_MODES + */ + _this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH; + + // run texture setter; + _this.texture = texture; + + /** + * The default shader that is used if a mesh doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + _this.shader = null; + + /** + * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any + * tint effect. + * + * @member {number} + */ + _this.tintRgb = new Float32Array([1, 1, 1]); + + /** + * A map of renderer IDs to webgl render data + * + * @private + * @member {object} + */ + _this._glDatas = {}; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * + * @member {string} + * @default 'mesh' + */ + _this.pluginName = 'mesh'; + return _this; + } + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - a reference to the WebGL renderer + */ + + + Mesh.prototype._renderWebGL = function _renderWebGL(renderer) { + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + + + Mesh.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins[this.pluginName].render(this); + }; + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Mesh.prototype._onTextureUpdate = function _onTextureUpdate() {} + /* empty */ + + + /** + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + */ + ; + + Mesh.prototype._calculateBounds = function _calculateBounds() { + // TODO - we can cache local bounds and use them if they are dirty (like graphics) + this._bounds.addVertices(this.transform, this.vertices, 0, this.vertices.length); + }; + + /** + * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Mesh.prototype.containsPoint = function containsPoint(point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + + this.worldTransform.applyInverse(point, tempPoint); + + var vertices = this.vertices; + var points = tempPolygon.points; + var indices = this.indices; + var len = this.indices.length; + var step = this.drawMode === Mesh.DRAW_MODES.TRIANGLES ? 3 : 1; + + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + + return false; + }; + + /** + * The texture that the mesh uses. + * + * @member {PIXI.Texture} + */ + + + _createClass(Mesh, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + + /** + * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return core.utils.rgb2hex(this.tintRgb); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tintRgb = core.utils.hex2rgb(value, this.tintRgb); + } + }]); + + return Mesh; +}(core.Container); + +/** + * Different drawing buffer modes supported + * + * @static + * @constant + * @type {object} + * @property {number} TRIANGLE_MESH + * @property {number} TRIANGLES + */ + + +exports.default = Mesh; +Mesh.DRAW_MODES = { + TRIANGLE_MESH: 0, + TRIANGLES: 1 +}; + +},{"../core":63}],162:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Plane2 = require('./Plane'); + +var _Plane3 = _interopRequireDefault(_Plane2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DEFAULT_BORDER_SIZE = 10; + +/** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.fromImage('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
+ *      A                          B
+ *    +---+----------------------+---+
+ *  C | 1 |          2           | 3 |
+ *    +---+----------------------+---+
+ *    |   |                      |   |
+ *    | 4 |          5           | 6 |
+ *    |   |                      |   |
+ *    +---+----------------------+---+
+ *  D | 7 |          8           | 9 |
+ *    +---+----------------------+---+
+
+ *  When changing this objects width and/or height:
+ *     areas 1 3 7 and 9 will remain unscaled.
+ *     areas 2 and 8 will be stretched horizontally
+ *     areas 4 and 6 will be stretched vertically
+ *     area 5 will be stretched both horizontally and vertically
+ * 
+ * + * @class + * @extends PIXI.mesh.Plane + * @memberof PIXI.mesh + * + */ + +var NineSlicePlane = function (_Plane) { + _inherits(NineSlicePlane, _Plane); + + /** + * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. + * @param {int} [leftWidth=10] size of the left vertical bar (A) + * @param {int} [topHeight=10] size of the top horizontal bar (C) + * @param {int} [rightWidth=10] size of the right vertical bar (B) + * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) + */ + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + _classCallCheck(this, NineSlicePlane); + + var _this = _possibleConstructorReturn(this, _Plane.call(this, texture, 4, 4)); + + var uvs = _this.uvs; + + // right and bottom uv's are always 1 + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + + _this._origWidth = texture.width; + _this._origHeight = texture.height; + _this._uvw = 1 / _this._origWidth; + _this._uvh = 1 / _this._origHeight; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.width = texture.width; + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.height = texture.height; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _this._uvw * leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - _this._uvw * rightWidth; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _this._uvh * topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - _this._uvh * bottomHeight; + + /** + * The width of the left column (a) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; + + /** + * The width of the right column (b) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; + + /** + * The height of the top row (c) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; + + /** + * The height of the bottom row (d) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; + return _this; + } + + /** + * Updates the horizontal vertices. + * + */ + + + NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices() { + var vertices = this.vertices; + + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight; + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + }; + + /** + * Updates the vertical vertices. + * + */ + + + NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices() { + var vertices = this.vertices; + + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth; + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with. + */ + + + NineSlicePlane.prototype._renderCanvas = function _renderCanvas(renderer) { + var context = renderer.context; + + context.globalAlpha = this.worldAlpha; + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + var base = this._texture.baseTexture; + var textureSource = base.source; + var w = base.width; + var h = base.height; + + this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11); + this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13); + this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15); + this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19); + this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21); + this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23); + this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27); + this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29); + this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31); + }; + + /** + * Renders one segment of the plane. + * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure + * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used. + * + * @private + * @param {CanvasRenderingContext2D} context - The context to draw with. + * @param {CanvasImageSource} textureSource - The source to draw. + * @param {number} w - width of the texture + * @param {number} h - height of the texture + * @param {number} x1 - x index 1 + * @param {number} y1 - y index 1 + * @param {number} x2 - x index 2 + * @param {number} y2 - y index 2 + */ + + + NineSlicePlane.prototype.drawSegment = function drawSegment(context, textureSource, w, h, x1, y1, x2, y2) { + // otherwise you get weird results when using slices of that are 0 wide or high. + var uvs = this.uvs; + var vertices = this.vertices; + + var sw = (uvs[x2] - uvs[x1]) * w; + var sh = (uvs[y2] - uvs[y1]) * h; + var dw = vertices[x2] - vertices[x1]; + var dh = vertices[y2] - vertices[y1]; + + // make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn. + if (sw < 1) { + sw = 1; + } + + if (sh < 1) { + sh = 1; + } + + // make sure destination is at least 1 pixel wide and high, otherwise you get + // lines when rendering close to original size. + if (dw < 1) { + dw = 1; + } + + if (dh < 1) { + dh = 1; + } + + context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh); + }; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + + _createClass(NineSlicePlane, [{ + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + this.updateVerticalVertices(); + } + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + this.updateHorizontalVertices(); + } + + /** + * The width of the left column + * + * @member {number} + */ + + }, { + key: 'leftWidth', + get: function get() { + return this._leftWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._leftWidth = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = this._uvw * value; + vertices[2] = vertices[10] = vertices[18] = vertices[26] = value; + + this.dirty = true; + } + + /** + * The width of the right column + * + * @member {number} + */ + + }, { + key: 'rightWidth', + get: function get() { + return this._rightWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rightWidth = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - this._uvw * value; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - value; + + this.dirty = true; + } + + /** + * The height of the top row + * + * @member {number} + */ + + }, { + key: 'topHeight', + get: function get() { + return this._topHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._topHeight = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[9] = uvs[11] = uvs[13] = uvs[15] = this._uvh * value; + vertices[9] = vertices[11] = vertices[13] = vertices[15] = value; + + this.dirty = true; + } + + /** + * The height of the bottom row + * + * @member {number} + */ + + }, { + key: 'bottomHeight', + get: function get() { + return this._bottomHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._bottomHeight = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - this._uvh * value; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - value; + + this.dirty = true; + } + }]); + + return NineSlicePlane; +}(_Plane3.default); + +exports.default = NineSlicePlane; + +},{"./Plane":163}],163:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The Plane allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Plane = function (_Mesh) { + _inherits(Plane, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the Plane. + * @param {number} verticesX - The number of vertices in the x-axis + * @param {number} verticesY - The number of vertices in the y-axis + */ + function Plane(texture, verticesX, verticesY) { + _classCallCheck(this, Plane); + + /** + * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this._ready = true; + + _this.verticesX = verticesX || 10; + _this.verticesY = verticesY || 10; + + _this.drawMode = _Mesh3.default.DRAW_MODES.TRIANGLES; + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Plane.prototype.refresh = function refresh() { + var total = this.verticesX * this.verticesY; + var verts = []; + var colors = []; + var uvs = []; + var indices = []; + var texture = this.texture; + + var segmentsX = this.verticesX - 1; + var segmentsY = this.verticesY - 1; + + var sizeX = texture.width / segmentsX; + var sizeY = texture.height / segmentsY; + + for (var i = 0; i < total; i++) { + if (texture._uvs) { + var x = i % this.verticesX; + var y = i / this.verticesX | 0; + + verts.push(x * sizeX, y * sizeY); + + // this works for rectangular textures. + uvs.push(texture._uvs.x0 + (texture._uvs.x1 - texture._uvs.x0) * (x / (this.verticesX - 1)), texture._uvs.y0 + (texture._uvs.y3 - texture._uvs.y0) * (y / (this.verticesY - 1))); + } else { + uvs.push(0); + } + } + + // cons + + var totalSub = segmentsX * segmentsY; + + for (var _i = 0; _i < totalSub; _i++) { + var xpos = _i % segmentsX; + var ypos = _i / segmentsX | 0; + + var value = ypos * this.verticesX + xpos; + var value2 = ypos * this.verticesX + xpos + 1; + var value3 = (ypos + 1) * this.verticesX + xpos; + var value4 = (ypos + 1) * this.verticesX + xpos + 1; + + indices.push(value, value2, value3); + indices.push(value2, value4, value3); + } + + // console.log(indices) + this.vertices = new Float32Array(verts); + this.uvs = new Float32Array(uvs); + this.colors = new Float32Array(colors); + this.indices = new Uint16Array(indices); + + this.indexDirty = true; + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Plane.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh3.default.prototype._onTextureUpdate.call(this); + + // wait for the Plane ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + return Plane; +}(_Mesh3.default); + +exports.default = Plane; + +},{"./Mesh":161}],164:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The rope allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Rope = function (_Mesh) { + _inherits(Rope, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the rope. + * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. + */ + function Rope(texture, points) { + _classCallCheck(this, Rope); + + /* + * @member {PIXI.Point[]} An array of points that determine the rope + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this.points = points; + + /* + * @member {Float32Array} An array of vertices used to construct this rope. + */ + _this.vertices = new Float32Array(points.length * 4); + + /* + * @member {Float32Array} The WebGL Uvs of the rope. + */ + _this.uvs = new Float32Array(points.length * 4); + + /* + * @member {Float32Array} An array containing the color components + */ + _this.colors = new Float32Array(points.length * 2); + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + _this.indices = new Uint16Array(points.length * 2); + + /** + * Tracker for if the rope is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + _this._ready = true; + + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Rope.prototype.refresh = function refresh() { + var points = this.points; + + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1 || !this._texture._uvs) { + return; + } + + // if the number of points has changed we will need to recreate the arraybuffers + if (this.vertices.length / 4 !== points.length) { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + var textureUvs = this._texture._uvs; + var offset = new core.Point(textureUvs.x0, textureUvs.y0); + var factor = new core.Point(textureUvs.x2 - textureUvs.x0, Number(textureUvs.y2 - textureUvs.y0)); + + uvs[0] = 0 + offset.x; + uvs[1] = 0 + offset.y; + uvs[2] = 0 + offset.x; + uvs[3] = factor.y + offset.y; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + + for (var i = 1; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + var amount = i / (total - 1); + + uvs[index] = amount * factor.x + offset.x; + uvs[index + 1] = 0 + offset.y; + + uvs[index + 2] = amount * factor.x + offset.x; + uvs[index + 3] = factor.y + offset.y; + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + + // ensure that the changes are uploaded + this.dirty++; + this.indexDirty++; + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Rope.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh.prototype._onTextureUpdate.call(this); + + // wait for the Rope ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + Rope.prototype.updateTransform = function updateTransform() { + var points = this.points; + + if (points.length < 1) { + return; + } + + var lastPoint = points[0]; + var nextPoint = void 0; + var perpX = 0; + var perpY = 0; + + // this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } else { + nextPoint = point; + } + + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + + var ratio = (1 - i / (total - 1)) * 10; + + if (ratio > 1) { + ratio = 1; + } + + var perpLength = Math.sqrt(perpX * perpX + perpY * perpY); + var num = this._texture.height / 2; // (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; + + perpX /= perpLength; + perpY /= perpLength; + + perpX *= num; + perpY *= num; + + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + + lastPoint = point; + } + + this.containerUpdateTransform(); + }; + + return Rope; +}(_Mesh3.default); + +exports.default = Rope; + +},{"../core":63,"./Mesh":161}],165:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Renderer dedicated to meshes. + * + * @class + * @private + * @memberof PIXI + */ +var MeshSpriteRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The renderer this downport works for + */ + function MeshSpriteRenderer(renderer) { + _classCallCheck(this, MeshSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the Mesh + * + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var context = renderer.context; + + var transform = mesh.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + renderer.setBlendMode(mesh.blendMode); + + if (mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH) { + this._renderTriangleMesh(mesh); + } else { + this._renderTriangles(mesh); + } + }; + + /** + * Draws the object in Triangle Mesh mode + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype._renderTriangleMesh = function _renderTriangleMesh(mesh) { + // draw triangles!! + var length = mesh.vertices.length / 2; + + for (var i = 0; i < length - 2; i++) { + // draw some triangles! + var index = i * 2; + + this._renderDrawTriangle(mesh, index, index + 2, index + 4); + } + }; + + /** + * Draws the object in triangle mode using canvas + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + */ + + + MeshSpriteRenderer.prototype._renderTriangles = function _renderTriangles(mesh) { + // draw triangles!! + var indices = mesh.indices; + var length = indices.length; + + for (var i = 0; i < length; i += 3) { + // draw some triangles! + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderDrawTriangle(mesh, index0, index1, index2); + } + }; + + /** + * Draws one of the triangles that from the Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + * @param {number} index0 - the index of the first vertex + * @param {number} index1 - the index of the second vertex + * @param {number} index2 - the index of the third vertex + */ + + + MeshSpriteRenderer.prototype._renderDrawTriangle = function _renderDrawTriangle(mesh, index0, index1, index2) { + var context = this.renderer.context; + var uvs = mesh.uvs; + var vertices = mesh.vertices; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var base = texture.baseTexture; + var textureSource = base.source; + var textureWidth = base.width; + var textureHeight = base.height; + + var u0 = uvs[index0] * base.width; + var u1 = uvs[index1] * base.width; + var u2 = uvs[index2] * base.width; + var v0 = uvs[index0 + 1] * base.height; + var v1 = uvs[index1 + 1] * base.height; + var v2 = uvs[index2 + 1] * base.height; + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + if (mesh.canvasPadding > 0) { + var paddingX = mesh.canvasPadding / mesh.worldTransform.a; + var paddingY = mesh.canvasPadding / mesh.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt(normX * normX + normY * normY); + + x0 = centerX + normX / dist * (dist + paddingX); + y0 = centerY + normY / dist * (dist + paddingY); + + // + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x1 = centerX + normX / dist * (dist + paddingX); + y1 = centerY + normY / dist * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x2 = centerX + normX / dist * (dist + paddingX); + y2 = centerY + normY / dist * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2; + var deltaA = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2; + var deltaB = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2; + var deltaC = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2; + var deltaD = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2; + var deltaE = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2; + var deltaF = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2; + + context.transform(deltaA / delta, deltaD / delta, deltaB / delta, deltaE / delta, deltaC / delta, deltaF / delta); + + context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + + context.restore(); + }; + + /** + * Renders a flat Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - The Mesh to render + */ + + + MeshSpriteRenderer.prototype.renderMeshFlat = function renderMeshFlat(mesh) { + var context = this.renderer.context; + var vertices = mesh.vertices; + var length = vertices.length / 2; + + // this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; ++i) { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var y0 = vertices[index + 1]; + + var x1 = vertices[index + 2]; + var y1 = vertices[index + 3]; + + var x2 = vertices[index + 4]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + }; + + /** + * destroy the the renderer. + * + */ + + + MeshSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return MeshSpriteRenderer; +}(); + +exports.default = MeshSpriteRenderer; + + +core.CanvasRenderer.registerPlugin('mesh', MeshSpriteRenderer); + +},{"../../core":63,"../Mesh":161}],166:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh = require('./Mesh'); + +Object.defineProperty(exports, 'Mesh', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Mesh).default; + } +}); + +var _MeshRenderer = require('./webgl/MeshRenderer'); + +Object.defineProperty(exports, 'MeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_MeshRenderer).default; + } +}); + +var _CanvasMeshRenderer = require('./canvas/CanvasMeshRenderer'); + +Object.defineProperty(exports, 'CanvasMeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasMeshRenderer).default; + } +}); + +var _Plane = require('./Plane'); + +Object.defineProperty(exports, 'Plane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Plane).default; + } +}); + +var _NineSlicePlane = require('./NineSlicePlane'); + +Object.defineProperty(exports, 'NineSlicePlane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NineSlicePlane).default; + } +}); + +var _Rope = require('./Rope'); + +Object.defineProperty(exports, 'Rope', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rope).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./Mesh":161,"./NineSlicePlane":162,"./Plane":163,"./Rope":164,"./canvas/CanvasMeshRenderer":165,"./webgl/MeshRenderer":167}],167:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var MeshRenderer = function (_core$ObjectRenderer) { + _inherits(MeshRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function MeshRenderer(renderer) { + _classCallCheck(this, MeshRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + MeshRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 translationMatrix;\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n}\n', 'varying vec2 vTextureCoord;\nuniform float alpha;\nuniform vec3 tint;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * vec4(tint * alpha, alpha);\n}\n'); + }; + + /** + * renders mesh + * + * @param {PIXI.mesh.Mesh} mesh mesh instance + */ + + + MeshRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var gl = renderer.gl; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var glData = mesh._glDatas[renderer.CONTEXT_UID]; + + if (!glData) { + renderer.bindVao(null); + + glData = { + shader: this.shader, + vertexBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.vertices, gl.STREAM_DRAW), + uvBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.uvs, gl.STREAM_DRAW), + indexBuffer: _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, mesh.indices, gl.STATIC_DRAW), + // build the vao object that will render.. + vao: null, + dirty: mesh.dirty, + indexDirty: mesh.indexDirty + }; + + // build the vao object that will render.. + glData.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(glData.indexBuffer).addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0).addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); + + mesh._glDatas[renderer.CONTEXT_UID] = glData; + } + + renderer.bindVao(glData.vao); + + if (mesh.dirty !== glData.dirty) { + glData.dirty = mesh.dirty; + glData.uvBuffer.upload(mesh.uvs); + } + + if (mesh.indexDirty !== glData.indexDirty) { + glData.indexDirty = mesh.indexDirty; + glData.indexBuffer.upload(mesh.indices); + } + + glData.vertexBuffer.upload(mesh.vertices); + + renderer.bindShader(glData.shader); + + glData.shader.uniforms.uSampler = renderer.bindTexture(texture); + + renderer.state.setBlendMode(mesh.blendMode); + + glData.shader.uniforms.translationMatrix = mesh.worldTransform.toArray(true); + glData.shader.uniforms.alpha = mesh.worldAlpha; + glData.shader.uniforms.tint = mesh.tintRgb; + + var drawMode = mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + glData.vao.draw(drawMode, mesh.indices.length, 0); + }; + + return MeshRenderer; +}(core.ObjectRenderer); + +exports.default = MeshRenderer; + + +core.WebGLRenderer.registerPlugin('mesh', MeshRenderer); + +},{"../../core":63,"../Mesh":161,"path":22,"pixi-gl-core":12}],168:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that advanced + * functionality will not work. ParticleContainer implements only the basic object transform (position, scale, rotation). + * Any other functionality like tinting, masking, etc will not work on sprites in this batch. + * + * It's extremely easy to use : + * + * ```js + * let container = new ParticleContainer(); + * + * for (let i = 0; i < 100; ++i) + * { + * let sprite = new PIXI.Sprite.fromImage("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be renderer at the speed of light. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.particles + */ +var ParticleContainer = function (_core$Container) { + _inherits(ParticleContainer, _core$Container); + + /** + * @param {number} [maxSize=15000] - The maximum number of particles that can be renderer by the container. + * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.scale=false] - When true, scale be uploaded and applied. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.alpha=false] - When true, alpha be uploaded and applied. + * @param {number} [batchSize=15000] - Number of particles per batch. + */ + function ParticleContainer() { + var maxSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1500; + var properties = arguments[1]; + var batchSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 16384; + + _classCallCheck(this, ParticleContainer); + + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + var maxBatchSize = 16384; + + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + + if (batchSize > maxSize) { + batchSize = maxSize; + } + + /** + * Set properties to be dynamic (true) / static (false) + * + * @member {boolean[]} + * @private + */ + _this._properties = [false, true, false, false, false]; + + /** + * @member {number} + * @private + */ + _this._maxSize = maxSize; + + /** + * @member {number} + * @private + */ + _this._batchSize = batchSize; + + /** + * @member {object} + * @private + */ + _this._glBuffers = {}; + + /** + * @member {number} + * @private + */ + _this._bufferToUpdate = 0; + + /** + * @member {boolean} + * + */ + _this.interactiveChildren = false; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` + * to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Used for canvas renderering. If true then the elements will be positioned at the + * nearest pixel. This provides a nice speed boost. + * + * @member {boolean} + * @default true; + */ + _this.roundPixels = true; + + /** + * The texture used to render the children. + * + * @readonly + * @member {BaseTexture} + */ + _this.baseTexture = null; + + _this.setProperties(properties); + return _this; + } + + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * + * @param {object} properties - The properties to be uploaded + */ + + + ParticleContainer.prototype.setProperties = function setProperties(properties) { + if (properties) { + this._properties[0] = 'scale' in properties ? !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'alpha' in properties ? !!properties.alpha : this._properties[4]; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + ParticleContainer.prototype.updateTransform = function updateTransform() { + // TODO don't need to! + this.displayObjectUpdateTransform(); + // PIXI.Container.prototype.updateTransform.call( this ); + }; + + /** + * Renders the container using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer + */ + + + ParticleContainer.prototype.renderWebGL = function renderWebGL(renderer) { + var _this2 = this; + + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.hasLoaded) { + this.baseTexture.once('update', function () { + return _this2.onChildrenChange(0); + }); + } + } + + renderer.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + + /** + * Set the flag that static data should be updated to true + * + * @private + * @param {number} smallestChildIndex - The smallest child index + */ + + + ParticleContainer.prototype.onChildrenChange = function onChildrenChange(smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + + if (bufferIndex < this._bufferToUpdate) { + this._bufferToUpdate = bufferIndex; + } + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + + + ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var isRotated = true; + + var positionX = 0; + var positionY = 0; + + var finalWidth = 0; + var finalHeight = 0; + + var compositeOperation = renderer.blendModes[this.blendMode]; + + if (compositeOperation !== context.globalCompositeOperation) { + context.globalCompositeOperation = compositeOperation; + } + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i]; + + if (!child.visible) { + continue; + } + + var frame = child._texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) { + // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call + if (isRotated) { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx * renderer.resolution, transform.ty * renderer.resolution); + + isRotated = false; + } + + positionX = child.anchor.x * (-frame.width * child.scale.x) + child.position.x + 0.5; + positionY = child.anchor.y * (-frame.height * child.scale.y) + child.position.y + 0.5; + + finalWidth = frame.width * child.scale.x; + finalHeight = frame.height * child.scale.y; + } else { + if (!isRotated) { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + + if (renderer.roundPixels) { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution | 0, childTransform.ty * renderer.resolution | 0); + } else { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution, childTransform.ty * renderer.resolution); + } + + positionX = child.anchor.x * -frame.width + 0.5; + positionY = child.anchor.y * -frame.height + 0.5; + + finalWidth = frame.width; + finalHeight = frame.height; + } + + var resolution = child._texture.baseTexture.resolution; + + context.drawImage(child._texture.baseTexture.source, frame.x * resolution, frame.y * resolution, frame.width * resolution, frame.height * resolution, positionX * resolution, positionY * resolution, finalWidth * resolution, finalHeight * resolution); + } + }; + + /** + * Destroys the container + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + ParticleContainer.prototype.destroy = function destroy(options) { + _core$Container.prototype.destroy.call(this, options); + + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + } + + this._properties = null; + this._buffers = null; + }; + + return ParticleContainer; +}(core.Container); + +exports.default = ParticleContainer; + +},{"../core":63}],169:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ParticleContainer = require('./ParticleContainer'); + +Object.defineProperty(exports, 'ParticleContainer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleContainer).default; + } +}); + +var _ParticleRenderer = require('./webgl/ParticleRenderer'); + +Object.defineProperty(exports, 'ParticleRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleRenderer).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./ParticleContainer":168,"./webgl/ParticleRenderer":171}],170:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + +/** + * The particle buffer manages the static and dynamic buffers for a particle container. + * + * @class + * @private + * @memberof PIXI + */ +var ParticleBuffer = function () { + /** + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(gl, properties, dynamicPropertyFlags, size) { + _classCallCheck(this, ParticleBuffer); + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * Size of a single vertex. + * + * @member {number} + */ + this.vertSize = 2; + + /** + * Size of a single vertex in bytes. + * + * @member {number} + */ + this.vertByteSize = this.vertSize * 4; + + /** + * The number of particles the buffer can hold + * + * @member {number} + */ + this.size = size; + + /** + * A list of the properties that are dynamic. + * + * @member {object[]} + */ + this.dynamicProperties = []; + + /** + * A list of the properties that are static. + * + * @member {object[]} + */ + this.staticProperties = []; + + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attribute: property.attribute, + size: property.size, + uploadFunction: property.uploadFunction, + offset: property.offset + }; + + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } else { + this.staticProperties.push(property); + } + } + + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + + this.initBuffers(); + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + ParticleBuffer.prototype.initBuffers = function initBuffers() { + var gl = this.gl; + var dynamicOffset = 0; + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(this.size); + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + this.dynamicStride = 0; + + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + + this.dynamicData = new Float32Array(this.size * this.dynamicStride * 4); + this.dynamicBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.dynamicData, gl.STREAM_DRAW); + + // static // + var staticOffset = 0; + + this.staticStride = 0; + + for (var _i = 0; _i < this.staticProperties.length; ++_i) { + var _property = this.staticProperties[_i]; + + _property.offset = staticOffset; + staticOffset += _property.size; + this.staticStride += _property.size; + } + + this.staticData = new Float32Array(this.size * this.staticStride * 4); + this.staticBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.staticData, gl.STATIC_DRAW); + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(this.indexBuffer); + + for (var _i2 = 0; _i2 < this.dynamicProperties.length; ++_i2) { + var _property2 = this.dynamicProperties[_i2]; + + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.FLOAT, false, this.dynamicStride * 4, _property2.offset * 4); + } + + for (var _i3 = 0; _i3 < this.staticProperties.length; ++_i3) { + var _property3 = this.staticProperties[_i3]; + + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.FLOAT, false, this.staticStride * 4, _property3.offset * 4); + } + }; + + /** + * Uploads the dynamic properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadDynamic = function uploadDynamic(children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + + property.uploadFunction(children, startIndex, amount, this.dynamicData, this.dynamicStride, property.offset); + } + + this.dynamicBuffer.upload(); + }; + + /** + * Uploads the static properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadStatic = function uploadStatic(children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + + property.uploadFunction(children, startIndex, amount, this.staticData, this.staticStride, property.offset); + } + + this.staticBuffer.upload(); + }; + + /** + * Destroys the ParticleBuffer. + * + */ + + + ParticleBuffer.prototype.destroy = function destroy() { + this.dynamicProperties = null; + this.dynamicData = null; + this.dynamicBuffer.destroy(); + + this.staticProperties = null; + this.staticData = null; + this.staticBuffer.destroy(); + }; + + return ParticleBuffer; +}(); + +exports.default = ParticleBuffer; + +},{"../../core/utils/createIndicesForQuads":118,"pixi-gl-core":12}],171:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _ParticleShader = require('./ParticleShader'); + +var _ParticleShader2 = _interopRequireDefault(_ParticleShader); + +var _ParticleBuffer = require('./ParticleBuffer'); + +var _ParticleBuffer2 = _interopRequireDefault(_ParticleBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + +/** + * + * @class + * @private + * @memberof PIXI + */ +var ParticleRenderer = function (_core$ObjectRenderer) { + _inherits(ParticleRenderer, _core$ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + _classCallCheck(this, ParticleRenderer); + + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; + + /** + * The default shader that is used if a sprite doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + + _this.indexBuffer = null; + + _this.properties = null; + + _this.tempMatrix = new core.Matrix(); + + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * When there is a WebGL context change + * + * @private + */ + + + ParticleRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + + // setup default shader + this.shader = new _ParticleShader2.default(gl); + + this.properties = [ + // verticesData + { + attribute: this.shader.attributes.aVertexPosition, + size: 2, + uploadFunction: this.uploadVertices, + offset: 0 + }, + // positionData + { + attribute: this.shader.attributes.aPositionCoord, + size: 2, + uploadFunction: this.uploadPosition, + offset: 0 + }, + // rotationData + { + attribute: this.shader.attributes.aRotation, + size: 1, + uploadFunction: this.uploadRotation, + offset: 0 + }, + // uvsData + { + attribute: this.shader.attributes.aTextureCoord, + size: 2, + uploadFunction: this.uploadUvs, + offset: 0 + }, + // alphaData + { + attribute: this.shader.attributes.aColor, + size: 1, + uploadFunction: this.uploadAlpha, + offset: 0 + }]; + }; + + /** + * Starts a new particle batch. + * + */ + + + ParticleRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + }; + + /** + * Renders the particle container object. + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + */ + + + ParticleRenderer.prototype.render = function render(container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var renderer = this.renderer; + var totalChildren = children.length; + + if (totalChildren === 0) { + return; + } else if (totalChildren > maxSize) { + totalChildren = maxSize; + } + + var buffers = container._glBuffers[renderer.CONTEXT_UID]; + + if (!buffers) { + buffers = container._glBuffers[renderer.CONTEXT_UID] = this.generateBuffers(container); + } + + // if the uvs have not updated then no point rendering just yet! + this.renderer.setBlendMode(container.blendMode); + + var gl = renderer.gl; + + var m = container.worldTransform.copy(this.tempMatrix); + + m.prepend(renderer._activeRenderTarget.projectionMatrix); + + this.shader.uniforms.projectionMatrix = m.toArray(true); + this.shader.uniforms.uAlpha = container.worldAlpha; + + // make sure the texture is bound.. + var baseTexture = children[0]._texture.baseTexture; + + this.shader.uniforms.uSampler = renderer.bindTexture(baseTexture); + + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = totalChildren - i; + + if (amount > batchSize) { + amount = batchSize; + } + + var buffer = buffers[j]; + + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + + // we only upload the static content when we have to! + if (container._bufferToUpdate === j) { + buffer.uploadStatic(children, i, amount); + container._bufferToUpdate = j + 1; + } + + // bind the buffer + renderer.bindVao(buffer.vao); + buffer.vao.draw(gl.TRIANGLES, amount * 6); + } + }; + + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer[]} The buffers + */ + + + ParticleRenderer.prototype.generateBuffers = function generateBuffers(container) { + var gl = this.renderer.gl; + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + for (var i = 0; i < size; i += batchSize) { + buffers.push(new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize)); + } + + return buffers; + }; + + /** + * Uploads the verticies. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their vertices uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadVertices = function uploadVertices(children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - sprite.anchor.x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - sprite.anchor.y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - sprite.anchor.x); + w1 = orig.width * -sprite.anchor.x; + + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + + array[offset + stride * 2] = w0 * sx; + array[offset + stride * 2 + 1] = h0 * sy; + + array[offset + stride * 3] = w1 * sx; + array[offset + stride * 3 + 1] = h0 * sy; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their positions uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadPosition = function uploadPosition(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + + array[offset + stride * 2] = spritePosition.x; + array[offset + stride * 2 + 1] = spritePosition.y; + + array[offset + stride * 3] = spritePosition.x; + array[offset + stride * 3 + 1] = spritePosition.y; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadRotation = function uploadRotation(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + stride * 2] = spriteRotation; + array[offset + stride * 3] = spriteRotation; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadUvs = function uploadUvs(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + + array[offset + stride * 2] = textureUvs.x2; + array[offset + stride * 2 + 1] = textureUvs.y2; + + array[offset + stride * 3] = textureUvs.x3; + array[offset + stride * 3 + 1] = textureUvs.y3; + + offset += stride * 4; + } else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + + array[offset + stride * 2] = 0; + array[offset + stride * 2 + 1] = 0; + + array[offset + stride * 3] = 0; + array[offset + stride * 3 + 1] = 0; + + offset += stride * 4; + } + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadAlpha = function uploadAlpha(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteAlpha = children[startIndex + i].alpha; + + array[offset] = spriteAlpha; + array[offset + stride] = spriteAlpha; + array[offset + stride * 2] = spriteAlpha; + array[offset + stride * 3] = spriteAlpha; + + offset += stride * 4; + } + }; + + /** + * Destroys the ParticleRenderer. + * + */ + + + ParticleRenderer.prototype.destroy = function destroy() { + if (this.renderer.gl) { + this.renderer.gl.deleteBuffer(this.indexBuffer); + } + + _core$ObjectRenderer.prototype.destroy.call(this); + + this.shader.destroy(); + + this.indices = null; + this.tempMatrix = null; + }; + + return ParticleRenderer; +}(core.ObjectRenderer); + +exports.default = ParticleRenderer; + + +core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + +},{"../../core":63,"./ParticleBuffer":170,"./ParticleShader":172}],172:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../core/Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI + */ +var ParticleShader = function (_Shader) { + _inherits(ParticleShader, _Shader); + + /** + * @param {PIXI.Shader} gl - The webgl shader manager this shader works for. + */ + function ParticleShader(gl) { + _classCallCheck(this, ParticleShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'attribute float aColor;', 'attribute vec2 aPositionCoord;', 'attribute vec2 aScale;', 'attribute float aRotation;', 'uniform mat3 projectionMatrix;', 'varying vec2 vTextureCoord;', 'varying float vColor;', 'void main(void){', ' vec2 v = aVertexPosition;', ' v.x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);', ' v.y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);', ' v = v + aPositionCoord;', ' gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = aColor;', '}'].join('\n'), + // hello + ['varying vec2 vTextureCoord;', 'varying float vColor;', 'uniform sampler2D uSampler;', 'uniform float uAlpha;', 'void main(void){', ' vec4 color = texture2D(uSampler, vTextureCoord) * vColor * uAlpha;', ' if (color.a == 0.0) discard;', ' gl_FragColor = color;', '}'].join('\n'))); + } + + return ParticleShader; +}(_Shader3.default); + +exports.default = ParticleShader; + +},{"../../core/Shader":42}],173:[function(require,module,exports){ +"use strict"; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + +if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + + if (x === 0 || isNaN(x)) { + return x; + } + + return x > 0 ? 1 : -1; + }; +} + +},{}],174:[function(require,module,exports){ +'use strict'; + +var _objectAssign = require('object-assign'); + +var _objectAssign2 = _interopRequireDefault(_objectAssign); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +if (!Object.assign) { + Object.assign = _objectAssign2.default; +} // References: +// https://github.com/sindresorhus/object-assign +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + +},{"object-assign":5}],175:[function(require,module,exports){ +'use strict'; + +require('./Object.assign'); + +require('./requestAnimationFrame'); + +require('./Math.sign'); + +if (!window.ArrayBuffer) { + window.ArrayBuffer = Array; +} + +if (!window.Float32Array) { + window.Float32Array = Array; +} + +if (!window.Uint32Array) { + window.Uint32Array = Array; +} + +if (!window.Uint16Array) { + window.Uint16Array = Array; +} + +},{"./Math.sign":173,"./Object.assign":174,"./requestAnimationFrame":176}],176:[function(require,module,exports){ +(function (global){ +'use strict'; + +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + +// Expected to be used with Browserfiy +// Browserify automatically detects the use of `global` and passes the +// correct reference of `global`, `self`, and finally `window` + +var ONE_FRAME_TIME = 16; + +// Date.now +if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; +} + +// performance.now +if (!(global.performance && global.performance.now)) { + (function () { + var startTime = Date.now(); + + if (!global.performance) { + global.performance = {}; + } + + global.performance.now = function () { + return Date.now() - startTime; + }; + })(); +} + +// requestAnimationFrame +var lastTime = Date.now(); +var vendors = ['ms', 'moz', 'webkit', 'o']; + +for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { + var p = vendors[x]; + + global.requestAnimationFrame = global[p + 'RequestAnimationFrame']; + global.cancelAnimationFrame = global[p + 'CancelAnimationFrame'] || global[p + 'CancelRequestAnimationFrame']; +} + +if (!global.requestAnimationFrame) { + global.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + 'is not a function'); + } + + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + + if (delay < 0) { + delay = 0; + } + + lastTime = currentTime; + + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} + +if (!global.cancelAnimationFrame) { + global.cancelAnimationFrame = function (id) { + return clearTimeout(id); + }; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],177:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CountLimiter = require('./limiters/CountLimiter'); + +var _CountLimiter2 = _interopRequireDefault(_CountLimiter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SharedTicker = core.ticker.shared; + +/** + * Default number of uploads per frame using prepare plugin. + * + * @static + * @memberof PIXI.settings + * @name UPLOADS_PER_FRAME + * @type {number} + * @default 4 + */ +core.settings.UPLOADS_PER_FRAME = 4; + +/** + * The prepare manager provides functionality to upload content to the GPU. BasePrepare handles + * basic queuing functionality and is extended by {@link PIXI.prepare.WebGLPrepare} and {@link PIXI.prepare.CanvasPrepare} + * to provide preparation capabilities specific to their respective renderers. + * + * @abstract + * @class + * @memberof PIXI.prepare + */ + +var BasePrepare = function () { + /** + * @param {PIXI.SystemRenderer} renderer - A reference to the current renderer + */ + function BasePrepare(renderer) { + var _this = this; + + _classCallCheck(this, BasePrepare); + + /** + * The limiter to be used to control how quickly items are prepared. + * @type {PIXI.prepare.CountLimiter|PIXI.prepare.TimeLimiter} + */ + this.limiter = new _CountLimiter2.default(core.settings.UPLOADS_PER_FRAME); + + /** + * Reference to the renderer. + * @type {PIXI.SystemRenderer} + * @protected + */ + this.renderer = renderer; + + /** + * The only real difference between CanvasPrepare and WebGLPrepare is what they pass + * to upload hooks. That different parameter is stored here. + * @type {PIXI.prepare.CanvasPrepare|PIXI.WebGLRenderer} + * @protected + */ + this.uploadHookHelper = null; + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + /** + * 'bound' call for prepareItems(). + * @type {Function} + * @private + */ + this.delayedTick = function () { + // unlikely, but in case we were destroyed between tick() and delayedTick() + if (!_this.queue) { + return; + } + _this.prepareItems(); + }; + + this.register(findText, drawText); + this.register(findTextStyle, calculateTextStyle); + } + + /** + * Upload all the textures and graphics to the GPU. + * + * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item - + * Either the container or display object to search for items to upload, the items to upload themselves, + * or the callback function, if items have been added using `prepare.add`. + * @param {Function} [done] - Optional callback when all queued uploads have completed + */ + + + BasePrepare.prototype.upload = function upload(item, done) { + if (typeof item === 'function') { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) { + if (done) { + this.completes.push(done); + } + + if (!this.ticking) { + this.ticking = true; + SharedTicker.addOnce(this.tick, this); + } + } else if (done) { + done(); + } + }; + + /** + * Handle tick update + * + * @private + */ + + + BasePrepare.prototype.tick = function tick() { + setTimeout(this.delayedTick, 0); + }; + + /** + * Actually prepare items. This is handled outside of the tick because it will take a while + * and we do NOT want to block the current animation frame from rendering. + * + * @private + */ + + + BasePrepare.prototype.prepareItems = function prepareItems() { + this.limiter.beginFrame(); + // Upload the graphics + while (this.queue.length && this.limiter.allowedToUpload()) { + var item = this.queue[0]; + var uploaded = false; + + if (item && !item._destroyed) { + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.uploadHookHelper, item)) { + this.queue.shift(); + uploaded = true; + break; + } + } + } + + if (!uploaded) { + this.queue.shift(); + } + } + + // We're finished + if (!this.queue.length) { + this.ticking = false; + + var completes = this.completes.slice(0); + + this.completes.length = 0; + + for (var _i = 0, _len = completes.length; _i < _len; _i++) { + completes[_i](); + } + } else { + // if we are not finished, on the next rAF do this again + SharedTicker.addOnce(this.tick, this); + } + }; + + /** + * Adds hooks for finding and uploading items. + * + * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array` + function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.register = function register(addHook, uploadHook) { + if (addHook) { + this.addHooks.push(addHook); + } + + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + + return this; + }; + + /** + * Manually add an item to the uploading queue. + * + * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to + * add to the queue + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.add = function add(item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) { + for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { + this.add(item.children[_i2]); + } + } + + return this; + }; + + /** + * Destroys the plugin, don't use after this. + * + */ + + + BasePrepare.prototype.destroy = function destroy() { + if (this.ticking) { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.limiter = null; + this.uploadHookHelper = null; + }; + + return BasePrepare; +}(); + +/** + * Built-in hook to draw PIXI.Text to its texture. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = BasePrepare; +function drawText(helper, item) { + if (item instanceof core.Text) { + // updating text will return early if it is not dirty + item.updateText(true); + + return true; + } + + return false; +} + +/** + * Built-in hook to calculate a text style for a PIXI.Text object. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function calculateTextStyle(helper, item) { + if (item instanceof core.TextStyle) { + var font = core.Text.getFontStyle(item); + + if (!core.Text.fontPropertiesCache[font]) { + core.Text.calculateFontProperties(font); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find Text objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Text object was found. + */ +function findText(item, queue) { + if (item instanceof core.Text) { + // push the text style to prepare it - this can be really expensive + if (queue.indexOf(item.style) === -1) { + queue.push(item.style); + } + // also push the text object so that we can render it (to canvas/texture) if needed + if (queue.indexOf(item) === -1) { + queue.push(item); + } + // also push the Text's texture for upload to GPU + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find TextStyle objects. + * + * @private + * @param {PIXI.TextStyle} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.TextStyle object was found. + */ +function findTextStyle(item, queue) { + if (item instanceof core.TextStyle) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +},{"../core":63,"./limiters/CountLimiter":180}],178:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CANVAS_START_SIZE = 16; + +/** + * The prepare manager provides functionality to upload content to the GPU + * This cannot be done directly for Canvas like in WebGL, but the effect can be achieved by drawing + * textures to an offline canvas. + * This draw call will force the texture to be moved onto the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ + +var CanvasPrepare = function (_BasePrepare) { + _inherits(CanvasPrepare, _BasePrepare); + + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasPrepare(renderer) { + _classCallCheck(this, CanvasPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this; + + /** + * An offline canvas to render textures to + * @type {HTMLCanvasElement} + * @private + */ + _this.canvas = document.createElement('canvas'); + _this.canvas.width = CANVAS_START_SIZE; + _this.canvas.height = CANVAS_START_SIZE; + + /** + * The context to the canvas + * @type {CanvasRenderingContext2D} + * @private + */ + _this.ctx = _this.canvas.getContext('2d'); + + // Add textures to upload + _this.register(findBaseTextures, uploadBaseTextures); + return _this; + } + + /** + * Destroys the plugin, don't use after this. + * + */ + + + CanvasPrepare.prototype.destroy = function destroy() { + _BasePrepare.prototype.destroy.call(this); + this.ctx = null; + this.canvas = null; + }; + + return CanvasPrepare; +}(_BasePrepare3.default); + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {*} prepare - Instance of CanvasPrepare + * @param {*} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = CanvasPrepare; +function uploadBaseTextures(prepare, item) { + if (item instanceof core.BaseTexture) { + var image = item.source; + + // Sometimes images (like atlas images) report a size of zero, causing errors on windows phone. + // So if the width or height is equal to zero then use the canvas size + // Otherwise use whatever is smaller, the image dimensions or the canvas dimensions. + var imageWidth = image.width === 0 ? prepare.canvas.width : Math.min(prepare.canvas.width, image.width); + var imageHeight = image.height === 0 ? prepare.canvas.height : Math.min(prepare.canvas.height, image.height); + + // Only a small subsections is required to be drawn to have the whole texture uploaded to the GPU + // A smaller draw can be faster. + prepare.ctx.drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, prepare.canvas.width, prepare.canvas.height); + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item -Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTextures(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } else if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); + +},{"../../core":63,"../BasePrepare":177}],179:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLPrepare = require('./webgl/WebGLPrepare'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLPrepare).default; + } +}); + +var _CanvasPrepare = require('./canvas/CanvasPrepare'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasPrepare).default; + } +}); + +var _BasePrepare = require('./BasePrepare'); + +Object.defineProperty(exports, 'BasePrepare', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BasePrepare).default; + } +}); + +var _CountLimiter = require('./limiters/CountLimiter'); + +Object.defineProperty(exports, 'CountLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CountLimiter).default; + } +}); + +var _TimeLimiter = require('./limiters/TimeLimiter'); + +Object.defineProperty(exports, 'TimeLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TimeLimiter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./BasePrepare":177,"./canvas/CanvasPrepare":178,"./limiters/CountLimiter":180,"./limiters/TimeLimiter":181,"./webgl/WebGLPrepare":182}],180:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * CountLimiter limits the number of items handled by a {@link PIXI.prepare.BasePrepare} to a specified + * number of items per frame. + * + * @class + * @memberof PIXI + */ +var CountLimiter = function () { + /** + * @param {number} maxItemsPerFrame - The maximum number of items that can be prepared each frame. + */ + function CountLimiter(maxItemsPerFrame) { + _classCallCheck(this, CountLimiter); + + /** + * The maximum number of items that can be prepared each frame. + * @private + */ + this.maxItemsPerFrame = maxItemsPerFrame; + /** + * The number of items that can be prepared in the current frame. + * @type {number} + * @private + */ + this.itemsLeft = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + CountLimiter.prototype.beginFrame = function beginFrame() { + this.itemsLeft = this.maxItemsPerFrame; + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + CountLimiter.prototype.allowedToUpload = function allowedToUpload() { + return this.itemsLeft-- > 0; + }; + + return CountLimiter; +}(); + +exports.default = CountLimiter; + +},{}],181:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of milliseconds per frame. + * + * @class + * @memberof PIXI + */ +var TimeLimiter = function () { + /** + * @param {number} maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. + */ + function TimeLimiter(maxMilliseconds) { + _classCallCheck(this, TimeLimiter); + + /** + * The maximum milliseconds that can be spent preparing items each frame. + * @private + */ + this.maxMilliseconds = maxMilliseconds; + /** + * The start time of the current frame. + * @type {number} + * @private + */ + this.frameStart = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + TimeLimiter.prototype.beginFrame = function beginFrame() { + this.frameStart = Date.now(); + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + TimeLimiter.prototype.allowedToUpload = function allowedToUpload() { + return Date.now() - this.frameStart < this.maxMilliseconds; + }; + + return TimeLimiter; +}(); + +exports.default = TimeLimiter; + +},{}],182:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The prepare manager provides functionality to upload content to the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ +var WebGLPrepare = function (_BasePrepare) { + _inherits(WebGLPrepare, _BasePrepare); + + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLPrepare(renderer) { + _classCallCheck(this, WebGLPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this.renderer; + + // Add textures and graphics to upload + _this.register(findBaseTextures, uploadBaseTextures).register(findGraphics, uploadGraphics); + return _this; + } + + return WebGLPrepare; +}(_BasePrepare3.default); + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = WebGLPrepare; +function uploadBaseTextures(renderer, item) { + if (item instanceof core.BaseTexture) { + // if the texture already has a GL texture, then the texture has been prepared or rendered + // before now. If the texture changed, then the changer should be calling texture.update() which + // reuploads the texture without need for preparing it again + if (!item._glTextures[renderer.CONTEXT_UID]) { + renderer.textureManager.updateTexture(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to upload PIXI.Graphics to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadGraphics(renderer, item) { + if (item instanceof core.Graphics) { + // if the item is not dirty and already has webgl data, then it got prepared or rendered + // before now and we shouldn't waste time updating it again + if (item.dirty || item.clearDirty || !item._webGL[renderer.plugins.graphics.CONTEXT_UID]) { + renderer.plugins.graphics.updateGraphics(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTextures(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } else if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find graphics. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Graphics object was found. + */ +function findGraphics(item, queue) { + if (item instanceof core.Graphics) { + queue.push(item); + + return true; + } + + return false; +} + +core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); + +},{"../../core":63,"../BasePrepare":177}],183:[function(require,module,exports){ +(function (global){ +'use strict'; + +exports.__esModule = true; +exports.loader = exports.prepare = exports.particles = exports.mesh = exports.loaders = exports.interaction = exports.filters = exports.extras = exports.extract = exports.accessibility = undefined; + +var _polyfill = require('./polyfill'); + +Object.keys(_polyfill).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _polyfill[key]; + } + }); +}); + +var _deprecation = require('./deprecation'); + +Object.keys(_deprecation).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _deprecation[key]; + } + }); +}); + +var _core = require('./core'); + +Object.keys(_core).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _core[key]; + } + }); +}); + +var _accessibility = require('./accessibility'); + +var accessibility = _interopRequireWildcard(_accessibility); + +var _extract = require('./extract'); + +var extract = _interopRequireWildcard(_extract); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// export libs + + +// export core +_core.utils.mixins.performMixins(); + +// handle mixins now, after all code has been added, including deprecation +// import polyfills. Done as an export to make sure polyfills are imported first +exports.accessibility = accessibility; +exports.extract = extract; +exports.extras = extras; +exports.filters = filters; +exports.interaction = interaction; +exports.loaders = loaders; +exports.mesh = mesh; +exports.particles = particles; +exports.prepare = prepare; + +/** + * A premade instance of the loader that can be used to load resources. + * + * @name loader + * @memberof PIXI + * @property {PIXI.loaders.Loader} + */ + +var loader = loaders && loaders.Loader ? new loaders.Loader() : null; // check is there in case user excludes loader lib + +exports.loader = loader; + +// Always export pixi globally. + +global.PIXI = exports; // eslint-disable-line + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"./accessibility":40,"./core":63,"./deprecation":125,"./extract":127,"./extras":136,"./filters":147,"./interaction":154,"./loaders":157,"./mesh":166,"./particles":169,"./polyfill":175,"./prepare":179}]},{},[183])(183) +}); + + +//# sourceMappingURL=pixi.js.map diff --git a/js/pixi/4.4.3/pixi.min.js b/js/pixi/4.4.3/pixi.min.js new file mode 100644 index 0000000..0eba014 --- /dev/null +++ b/js/pixi/4.4.3/pixi.min.js @@ -0,0 +1,21 @@ +/*! + * pixi.js - v4.4.3 + * Compiled Thu, 23 Mar 2017 12:34:27 UTC + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.PIXI=t()}}(function(){var t;return function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var h=r[s]={exports:{}};e[s][0].call(h.exports,function(t){var r=e[s][1][t];return i(r?r:t)},h,h.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s0)-(t<0)},r.abs=function(t){var e=t>>i-1;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,e|=r,e|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,t=(858993459&t)+(t>>>2&858993459),16843009*(t+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,t&=15,27030>>>t&1};var o=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|o[t>>>16&255]<<8|o[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),t=65535&(t|t>>>16),t<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),t=1023&(t|t>>>16),t<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],2:[function(t,e,r){"use strict";function n(t,e,r){r=r||2;var n=e&&e.length,o=n?e[0]*r:t.length,a=i(t,0,o,r,!0),u=[];if(!a)return u;var l,h,f,d,p,v,y;if(n&&(a=c(t,e,a,r)),t.length>80*r){l=f=t[0],h=d=t[1];for(var g=r;gf&&(f=p),v>d&&(d=v);y=Math.max(f-l,d-h)}return s(a,u,r,l,h,y),u}function i(t,e,r,n,i){var o,s;if(i===A(t,e,r,n)>0)for(o=e;o=e;o-=n)s=M(o,t[o],t[o+1],s);return s&&T(s,s.next)&&(C(s),s=s.next),s}function o(t,e){if(!t)return t;e||(e=t);var r,n=t;do if(r=!1,n.steiner||!T(n,n.next)&&0!==x(n.prev,n,n.next))n=n.next;else{if(C(n),n=e=n.prev,n===n.next)return null;r=!0}while(r||n!==e);return e}function s(t,e,r,n,i,c,f){if(t){!f&&c&&v(t,n,i,c);for(var d,p,y=t;t.prev!==t.next;)if(d=t.prev,p=t.next,c?u(t,n,i,c):a(t))e.push(d.i/r),e.push(t.i/r),e.push(p.i/r),C(t),t=p.next,y=p.next;else if(t=p,t===y){f?1===f?(t=l(t,e,r),s(t,e,r,n,i,c,2)):2===f&&h(t,e,r,n,i,c):s(o(t),e,r,n,i,c,1);break}}}function a(t){var e=t.prev,r=t,n=t.next;if(x(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(_(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&x(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function u(t,e,r,n){var i=t.prev,o=t,s=t.next;if(x(i,o,s)>=0)return!1;for(var a=i.xo.x?i.x>s.x?i.x:s.x:o.x>s.x?o.x:s.x,h=i.y>o.y?i.y>s.y?i.y:s.y:o.y>s.y?o.y:s.y,c=g(a,u,e,r,n),f=g(l,h,e,r,n),d=t.nextZ;d&&d.z<=f;){if(d!==t.prev&&d!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,d.x,d.y)&&x(d.prev,d,d.next)>=0)return!1;d=d.nextZ}for(d=t.prevZ;d&&d.z>=c;){if(d!==t.prev&&d!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,d.x,d.y)&&x(d.prev,d,d.next)>=0)return!1;d=d.prevZ}return!0}function l(t,e,r){var n=t;do{var i=n.prev,o=n.next.next;!T(i,o)&&w(i,n,n.next,o)&&S(i,o)&&S(o,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(o.i/r),C(n),C(n.next),n=t=o),n=n.next}while(n!==t);return n}function h(t,e,r,n,i,a){var u=t;do{for(var l=u.next.next;l!==u.prev;){if(u.i!==l.i&&b(u,l)){var h=P(u,l);return u=o(u,u.next),h=o(h,h.next),s(u,e,r,n,i,a),void s(h,e,r,n,i,a)}l=l.next}u=u.next}while(u!==t)}function c(t,e,r,n){var s,a,u,l,h,c=[];for(s=0,a=e.length;s=n.next.y){var a=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=i&&a>s){if(s=a,a===i){if(o===n.y)return n;if(o===n.next.y)return n.next}r=n.x=n.x&&n.x>=h&&_(or.x)&&S(n,t)&&(r=n,f=u)),n=n.next;return r}function v(t,e,r,n){var i=t;do null===i.z&&(i.z=g(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,y(i)}function y(t){var e,r,n,i,o,s,a,u,l=1;do{for(r=t,t=null,o=null,s=0;r;){for(s++,n=r,a=0,e=0;e0||u>0&&n;)0===a?(i=n,n=n.nextZ,u--):0!==u&&n?r.z<=n.z?(i=r,r=r.nextZ,a--):(i=n,n=n.nextZ,u--):(i=r,r=r.nextZ,a--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;r=n}o.nextZ=null,l*=2}while(s>1);return t}function g(t,e,r,n,i){return t=32767*(t-r)/i,e=32767*(e-n)/i,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1}function m(t){var e=t,r=t;do e.x=0&&(t-s)*(n-a)-(r-s)*(e-a)>=0&&(r-s)*(o-a)-(i-s)*(n-a)>=0}function b(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!E(t,e)&&S(t,e)&&S(e,t)&&O(t,e)}function x(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function T(t,e){return t.x===e.x&&t.y===e.y}function w(t,e,r,n){return!!(T(t,e)&&T(r,n)||T(t,n)&&T(r,e))||x(t,e,r)>0!=x(t,e,n)>0&&x(r,n,t)>0!=x(r,n,e)>0}function E(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&w(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}function S(t,e){return x(t.prev,t,t.next)<0?x(t,e,t.next)>=0&&x(t,t.prev,e)>=0:x(t,e,t.prev)<0||x(t,t.next,e)<0}function O(t,e){var r=t,n=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do r.y>o!=r.next.y>o&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;while(r!==t);return n}function P(t,e){var r=new R(t.i,t.x,t.y),n=new R(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function M(t,e,r,n){var i=new R(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function C(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function R(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(t,e,r,n){for(var i=0,o=e,s=r-n;o0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],3:[function(t,e,r){"use strict";function n(){}function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function o(){this._events=new n,this._eventsCount=0}var s=Object.prototype.hasOwnProperty,a="~";Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(a=!1)),o.prototype.eventNames=function(){var t,e,r=[];if(0===this._eventsCount)return r;for(e in t=this._events)s.call(t,e)&&r.push(a?e.slice(1):e);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t,e){var r=a?a+t:t,n=this._events[r];if(e)return!!n;if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i=t.byteLength?n.bufferSubData(this.type,e,t):n.bufferData(this.type,t,this.drawType),this.data=t},i.prototype.bind=function(){var t=this.gl;t.bindBuffer(this.type,this.buffer)},i.createVertexBuffer=function(t,e,r){return new i(t,t.ARRAY_BUFFER,e,r)},i.createIndexBuffer=function(t,e,r){return new i(t,t.ELEMENT_ARRAY_BUFFER,e,r)},i.create=function(t,e,r,n){return new i(t,e,r,n)},i.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer)},e.exports=i},{}],7:[function(t,e,r){var n=t("./GLTexture"),i=function(t,e,r){this.gl=t,this.framebuffer=t.createFramebuffer(),this.stencil=null,this.texture=null,this.width=e||100,this.height=r||100};i.prototype.enableTexture=function(t){var e=this.gl;this.texture=t||new n(e),this.texture.bind(),this.bind(),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0)},i.prototype.enableStencil=function(){if(!this.stencil){var t=this.gl;this.stencil=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.stencil),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.stencil),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,this.width,this.height)}},i.prototype.clear=function(t,e,r,n){this.bind();var i=this.gl;i.clearColor(t,e,r,n),i.clear(i.COLOR_BUFFER_BIT)},i.prototype.bind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer)},i.prototype.unbind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)},i.prototype.resize=function(t,e){var r=this.gl;this.width=t,this.height=e,this.texture&&this.texture.uploadData(null,t,e),this.stencil&&(r.bindRenderbuffer(r.RENDERBUFFER,this.stencil),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e))},i.prototype.destroy=function(){var t=this.gl;this.texture&&this.texture.destroy(),t.deleteFramebuffer(this.framebuffer),this.gl=null,this.stencil=null,this.texture=null},i.createRGBA=function(t,e,r,o){var s=n.fromData(t,null,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},i.createFloat32=function(t,e,r,o){var s=new n.fromData(t,o,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},e.exports=i},{"./GLTexture":9}],8:[function(t,e,r){var n=t("./shader/compileProgram"),i=t("./shader/extractAttributes"),o=t("./shader/extractUniforms"),s=t("./shader/generateUniformAccessObject"),a=function(t,e,r){this.gl=t,this.program=n(t,e,r),this.attributes=i(t,this.program);var a=o(t,this.program);this.uniforms=s(t,a)};a.prototype.bind=function(){this.gl.useProgram(this.program)},a.prototype.destroy=function(){},e.exports=a},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18}],9:[function(t,e,r){var n=function(t,e,r,n,i){this.gl=t,this.texture=t.createTexture(),this.mipmap=!1,this.premultiplyAlpha=!1,this.width=e||-1,this.height=r||-1,this.format=n||t.RGBA,this.type=i||t.UNSIGNED_BYTE};n.prototype.upload=function(t){this.bind();var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var r=t.videoWidth||t.width,n=t.videoHeight||t.height;n!==this.height||r!==this.width?e.texImage2D(e.TEXTURE_2D,0,this.format,this.format,this.type,t):e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.format,this.type,t),this.width=r,this.height=n};var i=!1;n.prototype.uploadData=function(t,e,r){this.bind();var n=this.gl;if(t instanceof Float32Array){if(!i){var o=n.getExtension("OES_texture_float");if(!o)throw new Error("floating point textures not available");i=!0}this.type=n.FLOAT}else this.type=n.UNSIGNED_BYTE;n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),e!==this.width||r!==this.height?n.texImage2D(n.TEXTURE_2D,0,this.format,e,r,0,this.format,this.type,t||null):n.texSubImage2D(n.TEXTURE_2D,0,0,0,e,r,this.format,this.type,t||null),this.width=e,this.height=r},n.prototype.bind=function(t){var e=this.gl;void 0!==t&&e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,this.texture)},n.prototype.unbind=function(){var t=this.gl;t.bindTexture(t.TEXTURE_2D,null)},n.prototype.minFilter=function(t){var e=this.gl;this.bind(),this.mipmap?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.magFilter=function(t){var e=this.gl;this.bind(),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.enableMipmap=function(){var t=this.gl;this.bind(),this.mipmap=!0,t.generateMipmap(t.TEXTURE_2D)},n.prototype.enableLinearScaling=function(){this.minFilter(!0),this.magFilter(!0)},n.prototype.enableNearestScaling=function(){this.minFilter(!1),this.magFilter(!1)},n.prototype.enableWrapClamp=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)},n.prototype.enableWrapRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT)},n.prototype.enableWrapMirrorRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.MIRRORED_REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.MIRRORED_REPEAT)},n.prototype.destroy=function(){var t=this.gl;t.deleteTexture(this.texture)},n.fromSource=function(t,e,r){var i=new n(t);return i.premultiplyAlpha=r||!1,i.upload(e),i},n.fromData=function(t,e,r,i){var o=new n(t);return o.uploadData(e,r,i),o},e.exports=n},{}],10:[function(t,e,r){function n(t,e){if(this.nativeVaoExtension=null,n.FORCE_NATIVE||(this.nativeVaoExtension=t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object")),this.nativeState=e,this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var r=t.getParameter(t.MAX_VERTEX_ATTRIBS);this.nativeState={tempAttribState:new Array(r),attribState:new Array(r)}}this.gl=t,this.attributes=[],this.indexBuffer=null,this.dirty=!1}var i=t("./setVertexAttribArrays");n.prototype.constructor=n,e.exports=n,n.FORCE_NATIVE=!1,n.prototype.bind=function(){return this.nativeVao?(this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao),this.dirty&&(this.dirty=!1,this.activate())):this.activate(),this},n.prototype.unbind=function(){return this.nativeVao&&this.nativeVaoExtension.bindVertexArrayOES(null),this},n.prototype.activate=function(){for(var t=this.gl,e=null,r=0;r=0;n--){var i=t[n];"."===i?t.splice(n,1):".."===i?(t.splice(n,1),r++):r&&(t.splice(n,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}function n(t,e){if(t.filter)return t.filter(e);for(var r=[],n=0;n=-1&&!i;o--){var s=o>=0?arguments[o]:t.cwd();if("string"!=typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(r=s+"/"+r,i="/"===s.charAt(0))}return r=e(n(r.split("/"),function(t){return!!t}),!i).join("/"),(i?"/":"")+r||"."},r.normalize=function(t){var i=r.isAbsolute(t),o="/"===s(t,-1);return t=e(n(t.split("/"),function(t){return!!t}),!i).join("/"),t||i||(t="."),t&&o&&(t+="/"),(i?"/":"")+t},r.isAbsolute=function(t){return"/"===t.charAt(0)},r.join=function(){var t=Array.prototype.slice.call(arguments,0);return r.normalize(n(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},r.relative=function(t,e){function n(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=r.resolve(t).substr(1),e=r.resolve(e).substr(1);for(var i=n(t.split("/")),o=n(e.split("/")),s=Math.min(i.length,o.length),a=s,u=0;u1)for(var r=1;r1&&(n=r[0]+"@",t=r[1]),t=t.replace(D,".");var i=t.split("."),o=s(i,e).join(".");return n+o}function u(t){for(var e,r,n=[],i=0,o=t.length;i=55296&&e<=56319&&i65535&&(t-=65536,e+=j(t>>>10&1023|55296),t=56320|1023&t),e+=j(t)}).join("")}function h(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:w}function c(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function f(t,e,r){var n=0;for(t=r?F(t/P):t>>1,t+=F(t/e);t>N*S>>1;n+=w)t=F(t/N);return F(n+(N+1)*t/(t+O))}function d(t){var e,r,n,i,s,a,u,c,d,p,v=[],y=t.length,g=0,m=C,_=M;for(r=t.lastIndexOf(R),r<0&&(r=0),n=0;n=128&&o("not-basic"),v.push(t.charCodeAt(n));for(i=r>0?r+1:0;i=y&&o("invalid-input"),c=h(t.charCodeAt(i++)),(c>=w||c>F((T-g)/a))&&o("overflow"),g+=c*a,d=u<=_?E:u>=_+S?S:u-_,!(cF(T/p)&&o("overflow"),a*=p;e=v.length+1,_=f(g-s,e,0==s),F(g/e)>T-m&&o("overflow"),m+=F(g/e),g%=e,v.splice(g++,0,m)}return l(v)}function p(t){var e,r,n,i,s,a,l,h,d,p,v,y,g,m,_,b=[];for(t=u(t),y=t.length,e=C,r=0,s=M,a=0;a=e&&vF((T-r)/g)&&o("overflow"),r+=(l-e)*g,e=l,a=0;aT&&o("overflow"),v==e){for(h=r,d=w;p=d<=s?E:d>=s+S?S:d-s,!(h= 0x80 (not a basic code point)","invalid-input":"Invalid input"},N=w-E,F=Math.floor,j=String.fromCharCode;if(b={version:"1.4.1",ucs2:{decode:u,encode:l},decode:d,encode:p,toASCII:y,toUnicode:v},"function"==typeof t&&"object"==typeof t.amd&&t.amd)t("punycode",function(){return b});else if(g&&m)if(r.exports==g)m.exports=b;else for(x in b)b.hasOwnProperty(x)&&(g[x]=b[x]);else i.punycode=b}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],25:[function(t,e,r){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,r,o){e=e||"&",r=r||"=";var s={};if("string"!=typeof t||0===t.length)return s;var a=/\+/g;t=t.split(e);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var l=t.length;u>0&&l>u&&(l=u);for(var h=0;h=0?(c=v.substr(0,y),f=v.substr(y+1)):(c=v,f=""),d=decodeURIComponent(c),p=decodeURIComponent(f),n(s,d)?i(s[d])?s[d].push(p):s[d]=[s[d],p]:s[d]=p}return s};var i=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],26:[function(t,e,r){"use strict";function n(t,e){if(t.map)return t.map(e);for(var r=[],n=0;n",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(d),v=["'"].concat(p),y=["%","/","?",";","#"].concat(v),g=["/","?","#"],m=255,_=/^[+a-z0-9A-Z_-]{0,63}$/,b=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,x={javascript:!0,"javascript:":!0},T={javascript:!0,"javascript:":!0},w={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},E=t("querystring");n.prototype.parse=function(t,e,r){if(!l.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var n=t.indexOf("?"),i=n!==-1&&n127?"x":L[F];if(!N.match(_)){var B=I.slice(0,P),k=I.slice(P+1),U=L.match(b);U&&(B.push(U[1]),k.unshift(U[2])),k.length&&(a="/"+k.join(".")+a),this.hostname=B.join(".");break}}}this.hostname.length>m?this.hostname="":this.hostname=this.hostname.toLowerCase(),A||(this.hostname=u.toASCII(this.hostname));var X=this.port?":"+this.port:"",G=this.hostname||"";this.host=G+X,this.href+=this.host,A&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==a[0]&&(a="/"+a))}if(!x[p])for(var P=0,D=v.length;P0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return r.search=t.search,r.query=t.query,l.isNull(r.pathname)&&l.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!x.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var O=x.slice(-1)[0],P=(r.host||t.host||x.length>1)&&("."===O||".."===O)||""===O,M=0,C=x.length;C>=0;C--)O=x[C],"."===O?x.splice(C,1):".."===O?(x.splice(C,1),M++):M&&(x.splice(C,1),M--);if(!_&&!b)for(;M--;M)x.unshift("..");!_||""===x[0]||x[0]&&"/"===x[0].charAt(0)||x.unshift(""),P&&"/"!==x.join("/").substr(-1)&&x.push("");var R=""===x[0]||x[0]&&"/"===x[0].charAt(0);if(E){r.hostname=r.host=R?"":x.length?x.shift():"";var S=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return _=_||r.host&&x.length,_&&!R&&x.unshift(""),x.length?r.pathname=x.join("/"):(r.pathname=null,r.path=null),l.isNull(r.pathname)&&l.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},n.prototype.parseHost=function(){var t=this.host,e=c.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":29,punycode:24,querystring:27}],29:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],30:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a=t("mini-signals"),u=i(a),l=t("parse-uri"),h=i(l),c=t("./async"),f=n(c),d=t("./Resource"),p=i(d),v=100,y=/(#[\w-]+)?$/,g=function(){function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10;o(this,t),this.baseUrl=r,this.progress=0,this.loading=!1,this.defaultQueryString="",this._beforeMiddleware=[],this._afterMiddleware=[],this._resourcesParsing=[],this._boundLoadResource=function(t,r){return e._loadResource(t,r)},this._queue=f.queue(this._boundLoadResource,n),this._queue.pause(),this.resources={},this.onProgress=new u.default,this.onError=new u.default,this.onLoad=new u.default,this.onStart=new u.default,this.onComplete=new u.default}return t.prototype.add=function(t,e,r,n){if(Array.isArray(t)){for(var i=0;i0))return void this.abort("["+e.status+"] "+e.statusText+": "+e.responseURL);if(this.xhrType===t.XHR_RESPONSE_TYPE.TEXT)this.data=e.responseText,this.type=t.TYPE.TEXT;else if(this.xhrType===t.XHR_RESPONSE_TYPE.JSON)try{this.data=JSON.parse(e.responseText),this.type=t.TYPE.JSON}catch(t){return void this.abort("Error trying to parse loaded json: "+t)}else if(this.xhrType===t.XHR_RESPONSE_TYPE.DOCUMENT)try{if(window.DOMParser){var n=new DOMParser;this.data=n.parseFromString(e.responseText,"text/xml")}else{var i=document.createElement("div");i.innerHTML=e.responseText,this.data=i}this.type=t.TYPE.XML}catch(t){return void this.abort("Error trying to parse loaded xml: "+t)}else this.data=e.response||e.responseText;this.complete()},t.prototype._determineCrossOrigin=function(t,e){if(0===t.indexOf("data:"))return"";e=e||window.location,p||(p=document.createElement("a")),p.href=t,t=(0,h.default)(p.href,{strictMode:!0});var r=!t.port&&""===e.port||t.port===e.port,n=t.protocol?t.protocol+":":"";return t.host===e.hostname&&r&&n===e.protocol?"":"anonymous"},t.prototype._determineXhrType=function(){return t._xhrTypeMap[this.extension]||t.XHR_RESPONSE_TYPE.TEXT},t.prototype._determineLoadType=function(){return t._loadTypeMap[this.extension]||t.LOAD_TYPE.XHR},t.prototype._getExtension=function(){var t=this.url,e="";if(this.isDataUrl){var r=t.indexOf("/");e=t.substring(r+1,t.indexOf(";",r))}else{var n=t.indexOf("?");n!==-1&&(t=t.substring(0,n)),e=t.substring(t.lastIndexOf(".")+1)}return e.toLowerCase()},t.prototype._getMimeFromXhrType=function(e){switch(e){case t.XHR_RESPONSE_TYPE.BUFFER:return"application/octet-binary";case t.XHR_RESPONSE_TYPE.BLOB:return"application/blob";case t.XHR_RESPONSE_TYPE.DOCUMENT:return"application/xml";case t.XHR_RESPONSE_TYPE.JSON:return"application/json";case t.XHR_RESPONSE_TYPE.DEFAULT:case t.XHR_RESPONSE_TYPE.TEXT:default:return"text/plain"}},u(t,[{key:"isDataUrl",get:function(){return this._hasFlag(t.STATUS_FLAGS.DATA_URL)}},{key:"isComplete",get:function(){return this._hasFlag(t.STATUS_FLAGS.COMPLETE)}},{key:"isLoading",get:function(){return this._hasFlag(t.STATUS_FLAGS.LOADING)}}]),t}();r.default=m,m.STATUS_FLAGS={NONE:0,DATA_URL:1,COMPLETE:2,LOADING:4},m.TYPE={UNKNOWN:0,JSON:1,XML:2,IMAGE:3,AUDIO:4,VIDEO:5,TEXT:6},m.LOAD_TYPE={XHR:1,IMAGE:2,AUDIO:3,VIDEO:4},m.XHR_RESPONSE_TYPE={DEFAULT:"text",BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"},m._loadTypeMap={gif:m.LOAD_TYPE.IMAGE,png:m.LOAD_TYPE.IMAGE,bmp:m.LOAD_TYPE.IMAGE,jpg:m.LOAD_TYPE.IMAGE,jpeg:m.LOAD_TYPE.IMAGE,tif:m.LOAD_TYPE.IMAGE,tiff:m.LOAD_TYPE.IMAGE,webp:m.LOAD_TYPE.IMAGE,tga:m.LOAD_TYPE.IMAGE,svg:m.LOAD_TYPE.IMAGE,"svg+xml":m.LOAD_TYPE.IMAGE,mp3:m.LOAD_TYPE.AUDIO,ogg:m.LOAD_TYPE.AUDIO,wav:m.LOAD_TYPE.AUDIO,mp4:m.LOAD_TYPE.VIDEO,webm:m.LOAD_TYPE.VIDEO},m._xhrTypeMap={xhtml:m.XHR_RESPONSE_TYPE.DOCUMENT,html:m.XHR_RESPONSE_TYPE.DOCUMENT,htm:m.XHR_RESPONSE_TYPE.DOCUMENT,xml:m.XHR_RESPONSE_TYPE.DOCUMENT,tmx:m.XHR_RESPONSE_TYPE.DOCUMENT,svg:m.XHR_RESPONSE_TYPE.DOCUMENT,tsx:m.XHR_RESPONSE_TYPE.DOCUMENT,gif:m.XHR_RESPONSE_TYPE.BLOB,png:m.XHR_RESPONSE_TYPE.BLOB,bmp:m.XHR_RESPONSE_TYPE.BLOB,jpg:m.XHR_RESPONSE_TYPE.BLOB,jpeg:m.XHR_RESPONSE_TYPE.BLOB,tif:m.XHR_RESPONSE_TYPE.BLOB,tiff:m.XHR_RESPONSE_TYPE.BLOB,webp:m.XHR_RESPONSE_TYPE.BLOB,tga:m.XHR_RESPONSE_TYPE.BLOB,json:m.XHR_RESPONSE_TYPE.JSON,text:m.XHR_RESPONSE_TYPE.TEXT,txt:m.XHR_RESPONSE_TYPE.TEXT,ttf:m.XHR_RESPONSE_TYPE.BUFFER,otf:m.XHR_RESPONSE_TYPE.BUFFER},m.EMPTY_GIF="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="},{"mini-signals":36,"parse-uri":37}],32:[function(t,e,r){"use strict";function n(){}function i(t,e,r){var n=0,i=t.length;!function o(s){return s||n===i?void(r&&r(s)):void e(t[n++],o)}()}function o(t){return function(){if(null===t)throw new Error("Callback was already called.");var e=t;t=null,e.apply(this,arguments)}}function s(t,e){function r(t,e,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(a.started=!0,null==t&&a.idle())return void setTimeout(function(){return a.drain()},1);var i={data:t,callback:"function"==typeof r?r:n};e?a._tasks.unshift(i):a._tasks.push(i),setTimeout(function(){return a.process()},1)}function i(t){return function(){s-=1,t.callback.apply(t,arguments),null!=arguments[0]&&a.error(arguments[0],t.data),s<=a.concurrency-a.buffer&&a.unsaturated(),a.idle()&&a.drain(),a.process()}}if(null==e)e=1;else if(0===e)throw new Error("Concurrency must not be zero");var s=0,a={_tasks:[],concurrency:e,saturated:n,unsaturated:n,buffer:e/4,empty:n,drain:n,error:n,started:!1,paused:!1,push:function(t,e){r(t,!1,e)},kill:function(){s=0,a.drain=n,a.started=!1,a._tasks=[]},unshift:function(t,e){r(t,!0,e)},process:function(){for(;!a.paused&&s>2,o[1]=(3&n[0])<<4|n[1]>>4,o[2]=(15&n[1])<<2|n[2]>>6,o[3]=63&n[2];var a=r-(t.length-1);switch(a){case 2:o[3]=64,o[2]=64;break;case 1:o[3]=64}for(var u=0;u=0;r--)this.updateAccessibleObjects(e[r])}},t.prototype.update=function(){if(this.renderer.renderingToScreen){this.updateAccessibleObjects(this.renderer._lastObjectRendered);var t=this.renderer.view.getBoundingClientRect(),e=t.width/this.renderer.width,r=t.height/this.renderer.height,n=this.div;n.style.left=t.left+"px",n.style.top=t.top+"px",n.style.width=this.renderer.width+"px",n.style.height=this.renderer.height+"px";for(var i=0;ithis.renderer.width&&(t.width=this.renderer.width-t.x),t.y+t.height>this.renderer.height&&(t.height=this.renderer.height-t.y)},t.prototype.addChild=function(t){var e=this.pool.pop();e||(e=document.createElement("button"),e.style.width=d+"px",e.style.height=d+"px",e.style.backgroundColor=this.debug?"rgba(255,0,0,0.5)":"transparent",e.style.position="absolute",e.style.zIndex=y,e.style.borderStyle="none",e.addEventListener("click",this._onClick.bind(this)),e.addEventListener("focus",this._onFocus.bind(this)),e.addEventListener("focusout",this._onFocusOut.bind(this))),t.accessibleTitle?e.title=t.accessibleTitle:t.accessibleTitle||t.accessibleHint||(e.title="displayObject "+this.tabIndex),t.accessibleHint&&e.setAttribute("aria-label",t.accessibleHint),t._accessibleActive=!0,t._accessibleDiv=e,e.displayObject=t,this.children.push(t),this.div.appendChild(t._accessibleDiv),t._accessibleDiv.tabIndex=t.tabIndex},t.prototype._onClick=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"click",e.eventData)},t.prototype._onFocus=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseover",e.eventData)},t.prototype._onFocusOut=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseout",e.eventData)},t.prototype._onKeyDown=function(t){t.keyCode===f&&this.activate()},t.prototype._onMouseMove=function(){this.deactivate()},t.prototype.destroy=function(){this.div=null;for(var t=0;t4&&void 0!==arguments[4]&&arguments[4];i(this,t),this.renderer=(0,s.autoDetectRenderer)(e,r,n,o),this.stage=new u.default,this._ticker=null,this.ticker=a?l.shared:new l.Ticker,this.start()}return t.prototype.render=function(){this.renderer.render(this.stage)},t.prototype.stop=function(){this._ticker.stop()},t.prototype.start=function(){this._ticker.start()},t.prototype.destroy=function(t){this.stop(),this.ticker=null,this.stage.destroy(),this.stage=null,this.renderer.destroy(t),this.renderer=null},o(t,[{key:"ticker",set:function(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this)},get:function(){return this._ticker}},{key:"view",get:function(){return this.renderer.view}},{key:"screen",get:function(){return this.renderer.screen}}]),t}();r.default=h},{"./autoDetectRenderer":43,"./display/Container":46,"./ticker":116}],42:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t,e){if(t instanceof Array){if("precision"!==t[0].substring(0,9)){var r=t.slice(0);return r.unshift("precision "+e+" float;"),r}}else if("precision"!==t.substring(0,9))return"precision "+e+" float;\n"+t;return t}r.__esModule=!0;var u=t("pixi-gl-core"),l=t("./settings"),h=n(l),c=function(t){function e(r,n,s){return i(this,e),o(this,t.call(this,r,a(n,h.default.PRECISION_VERTEX),a(s,h.default.PRECISION_FRAGMENT)))}return s(e,t),e}(u.GLShader);r.default=c},{"./settings":99,"pixi-gl-core":12}],43:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:800,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:600,r=arguments[2],n=arguments[3];return!n&&a.isWebGLSupported()?new c.default(t,e,r):new l.default(t,e,r)}r.__esModule=!0,r.autoDetectRenderer=o;var s=t("./utils"),a=i(s),u=t("./renderers/canvas/CanvasRenderer"),l=n(u),h=t("./renderers/webgl/WebGLRenderer"),c=n(h)},{"./renderers/canvas/CanvasRenderer":75,"./renderers/webgl/WebGLRenderer":82,"./utils":120}],44:[function(t,e,r){"use strict";r.__esModule=!0;r.VERSION="4.4.3",r.PI_2=2*Math.PI,r.RAD_TO_DEG=180/Math.PI,r.DEG_TO_RAD=Math.PI/180,r.RENDERER_TYPE={UNKNOWN:0,WEBGL:1,CANVAS:2},r.BLEND_MODES={NORMAL:0,ADD:1,MULTIPLY:2,SCREEN:3,OVERLAY:4,DARKEN:5,LIGHTEN:6,COLOR_DODGE:7,COLOR_BURN:8,HARD_LIGHT:9,SOFT_LIGHT:10,DIFFERENCE:11,EXCLUSION:12,HUE:13,SATURATION:14,COLOR:15,LUMINOSITY:16},r.DRAW_MODES={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},r.SCALE_MODES={LINEAR:0,NEAREST:1},r.WRAP_MODES={CLAMP:0,REPEAT:1,MIRRORED_REPEAT:2},r.GC_MODES={AUTO:0,MANUAL:1},r.URL_FILE_EXTENSION=/\.(\w{3,4})(?:$|\?|#)/i,r.DATA_URI=/^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;(charset=[\w-]+|base64))?,(.*)/i,r.SVG_SIZE=/]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i,r.SHAPES={POLY:0,RECT:1,CIRC:2,ELIP:3,RREC:4},r.PRECISION={LOW:"lowp",MEDIUM:"mediump",HIGH:"highp"},r.TRANSFORM_MODE={STATIC:0,DYNAMIC:1},r.TEXT_GRADIENT={LINEAR_VERTICAL:0,LINEAR_HORIZONTAL:1}},{}],45:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../math"),o=function(){function t(){n(this,t),this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0),this.rect=null}return t.prototype.isEmpty=function(){return this.minX>this.maxX||this.minY>this.maxY},t.prototype.clear=function(){this.updateID++,this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0)},t.prototype.getRectangle=function(t){return this.minX>this.maxX||this.minY>this.maxY?i.Rectangle.EMPTY:(t=t||new i.Rectangle(0,0,1,1),t.x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)},t.prototype.addPoint=function(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)},t.prototype.addQuad=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY,o=t[0],s=t[1];e=on?o:n,i=s>i?s:i,o=t[2],s=t[3],e=on?o:n,i=s>i?s:i,o=t[4],s=t[5],e=on?o:n,i=s>i?s:i,o=t[6],s=t[7],e=on?o:n,i=s>i?s:i,this.minX=e,this.minY=r,this.maxX=n,this.maxY=i},t.prototype.addFrame=function(t,e,r,n,i){var o=t.worldTransform,s=o.a,a=o.b,u=o.c,l=o.d,h=o.tx,c=o.ty,f=this.minX,d=this.minY,p=this.maxX,v=this.maxY,y=s*e+u*r+h,g=a*e+l*r+c;f=yp?y:p,v=g>v?g:v,y=s*n+u*r+h,g=a*n+l*r+c,f=yp?y:p,v=g>v?g:v,y=s*e+u*i+h,g=a*e+l*i+c,f=yp?y:p,v=g>v?g:v,y=s*n+u*i+h,g=a*n+l*i+c,f=yp?y:p,v=g>v?g:v,this.minX=f,this.minY=d,this.maxX=p,this.maxY=v},t.prototype.addVertices=function(t,e,r,n){for(var i=t.worldTransform,o=i.a,s=i.b,a=i.c,u=i.d,l=i.tx,h=i.ty,c=this.minX,f=this.minY,d=this.maxX,p=this.maxY,v=r;vd?m:d,p=_>p?_:p}this.minX=c,this.minY=f,this.maxX=d,this.maxY=p},t.prototype.addBounds=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY;this.minX=t.minXn?t.maxX:n,this.maxY=t.maxY>i?t.maxY:i},t.prototype.addBoundsMask=function(t,e){var r=t.minX>e.minX?t.minX:e.minX,n=t.minY>e.minY?t.minY:e.minY,i=t.maxXu?i:u,this.maxY=o>l?o:l}},t.prototype.addBoundsArea=function(t,e){var r=t.minX>e.x?t.minX:e.x,n=t.minY>e.y?t.minY:e.y,i=t.maxXu?i:u,this.maxY=o>l?o:l}},t}();r.default=o},{"../math":68}],46:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r1)for(var r=0;rthis.children.length)throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length);return t.parent&&t.parent.removeChild(t),t.parent=this,t.transform._parentID=-1,this.children.splice(e,0,t),this._boundsID++,this.onChildrenChange(e),t.emit("added",this),t},e.prototype.swapChildren=function(t,e){if(t!==e){var r=this.getChildIndex(t),n=this.getChildIndex(e);this.children[r]=e,this.children[n]=t,this.onChildrenChange(r=this.children.length)throw new Error("The supplied index is out of bounds");var r=this.getChildIndex(t);(0,u.removeItems)(this.children,r,1),this.children.splice(e,0,t),this.onChildrenChange(e)},e.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Index ("+t+") does not exist.");return this.children[t]},e.prototype.removeChild=function(t){var e=arguments.length;if(e>1)for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=t,n="number"==typeof e?e:this.children.length,i=n-r,o=void 0;if(i>0&&i<=n){o=this.children.splice(r,i);for(var s=0;s2&&void 0!==arguments[2]&&arguments[2];return r||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)},e.prototype.toLocal=function(t,e,r,n){return e&&(t=e.toGlobal(t,r,n)),n||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,r)},e.prototype.renderWebGL=function(t){},e.prototype.renderCanvas=function(t){},e.prototype.setParent=function(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t},e.prototype.setTransform=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0,u=arguments.length>8&&void 0!==arguments[8]?arguments[8]:0;return this.position.x=t,this.position.y=e,this.scale.x=r?r:1,this.scale.y=n?n:1,this.rotation=i,this.skew.x=o,this.skew.y=s,this.pivot.x=a,this.pivot.y=u,this},e.prototype.destroy=function(){this.removeAllListeners(),this.parent&&this.parent.removeChild(this),this.transform=null,this.parent=null,this._bounds=null,this._currentBounds=null,this._mask=null,this.filterArea=null,this.interactive=!1,this.interactiveChildren=!1,this._destroyed=!0},a(e,[{key:"_tempDisplayObjectParent",get:function(){return null===this.tempDisplayObjectParent&&(this.tempDisplayObjectParent=new e),this.tempDisplayObjectParent}},{key:"x",get:function(){return this.position.x},set:function(t){this.transform.position.x=t}},{key:"y",get:function(){return this.position.y},set:function(t){this.transform.position.y=t}},{key:"worldTransform",get:function(){return this.transform.worldTransform}},{key:"localTransform",get:function(){return this.transform.localTransform}},{key:"position",get:function(){return this.transform.position},set:function(t){this.transform.position.copy(t)}},{key:"scale",get:function(){return this.transform.scale},set:function(t){this.transform.scale.copy(t)}},{key:"pivot",get:function(){return this.transform.pivot},set:function(t){this.transform.pivot.copy(t)}},{key:"skew",get:function(){return this.transform.skew},set:function(t){this.transform.skew.copy(t)}},{key:"rotation",get:function(){return this.transform.rotation},set:function(t){this.transform.rotation=t}},{key:"worldVisible",get:function(){var t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask&&(this._mask.renderable=!0),this._mask=t,this._mask&&(this._mask.renderable=!1)}},{key:"filters",get:function(){return this._filters&&this._filters.slice()},set:function(t){this._filters=t&&t.slice()}}]),e}(l.default);r.default=b,b.prototype.displayObjectUpdateTransform=b.prototype.updateTransform},{"../const":44,"../math":68,"../settings":99,"./Bounds":45,"./Transform":48,"./TransformStatic":50,eventemitter3:3}],48:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]&&arguments[0];i(this,e);var n=o(this,t.call(this));return n.fillAlpha=1,n.lineWidth=0,n.nativeLines=r,n.lineColor=0,n.graphicsData=[],n.tint=16777215,n._prevTint=16777215,n.blendMode=_.BLEND_MODES.NORMAL,n.currentPath=null,n._webGL={},n.isMask=!1,n.boundsPadding=0,n._localBounds=new x.default,n.dirty=0,n.fastRectDirty=-1,n.clearDirty=0,n.boundsDirty=-1,n.cachedSpriteDirty=!1,n._spriteRect=null,n._fastRect=!1,n}return s(e,t),e.prototype.clone=function t(){var t=new e;t.renderable=this.renderable,t.fillAlpha=this.fillAlpha,t.lineWidth=this.lineWidth,t.lineColor=this.lineColor,t.tint=this.tint,t.blendMode=this.blendMode,t.isMask=this.isMask,t.boundsPadding=this.boundsPadding,t.dirty=0,t.cachedSpriteDirty=this.cachedSpriteDirty;for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;if(this.lineWidth=t,this.lineColor=e,this.lineAlpha=r,this.currentPath)if(this.currentPath.shape.points.length){var n=new g.Polygon(this.currentPath.shape.points.slice(-2));n.closed=!1,this.drawShape(n)}else this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha;return this},e.prototype.moveTo=function(t,e){var r=new g.Polygon([t,e]);return r.closed=!1,this.drawShape(r),this},e.prototype.lineTo=function(t,e){return this.currentPath.shape.points.push(t,e),this.dirty++,this},e.prototype.quadraticCurveTo=function(t,e,r,n){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var i=20,o=this.currentPath.shape.points,s=0,a=0;0===o.length&&this.moveTo(0,0);for(var u=o[o.length-2],l=o[o.length-1],h=1;h<=i;++h){var c=h/i;s=u+(t-u)*c,a=l+(e-l)*c,o.push(s+(t+(r-t)*c-s)*c,a+(e+(n-e)*c-a)*c)}return this.dirty++,this},e.prototype.bezierCurveTo=function(t,e,r,n,i,o){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var s=this.currentPath.shape.points,a=s[s.length-2],u=s[s.length-1];return s.length-=2,(0,w.default)(a,u,t,e,r,n,i,o,s),this.dirty++,this},e.prototype.arcTo=function(t,e,r,n,i){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(t,e):this.moveTo(t,e);var o=this.currentPath.shape.points,s=o[o.length-2],a=o[o.length-1],u=a-e,l=s-t,h=n-e,c=r-t,f=Math.abs(u*c-l*h);if(f<1e-8||0===i)o[o.length-2]===t&&o[o.length-1]===e||o.push(t,e);else{var d=u*u+l*l,p=h*h+c*c,v=u*h+l*c,y=i*Math.sqrt(d)/f,g=i*Math.sqrt(p)/f,m=y*v/d,_=g*v/p,b=y*c+g*l,x=y*h+g*u,T=l*(g+m),w=u*(g+m),E=c*(y+_),S=h*(y+_),O=Math.atan2(w-x,T-b),P=Math.atan2(S-x,E-b);this.arc(b+t,x+e,i,O,P,l*h>c*u)}return this.dirty++,this},e.prototype.arc=function(t,e,r,n,i){var o=arguments.length>5&&void 0!==arguments[5]&&arguments[5];if(n===i)return this;!o&&i<=n?i+=2*Math.PI:o&&n<=i&&(n+=2*Math.PI);var s=i-n,a=40*Math.ceil(Math.abs(s)/(2*Math.PI));if(0===s)return this;var u=t+Math.cos(n)*r,l=e+Math.sin(n)*r,h=this.currentPath?this.currentPath.shape.points:null;h?h[h.length-2]===u&&h[h.length-1]===l||h.push(u,l):(this.moveTo(u,l),h=this.currentPath.shape.points);for(var c=s/(2*a),f=2*c,d=Math.cos(c),p=Math.sin(c),v=a-1,y=v%1/v,g=0;g<=v;++g){var m=g+y*g,_=c+n+f*m,b=Math.cos(_),x=-Math.sin(_);h.push((d*b+p*x)*r+t,(d*-x+p*b)*r+e)}return this.dirty++,this},e.prototype.beginFill=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this.filling=!0,this.fillColor=t,this.fillAlpha=e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},e.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},e.prototype.drawRect=function(t,e,r,n){return this.drawShape(new g.Rectangle(t,e,r,n)),this},e.prototype.drawRoundedRect=function(t,e,r,n,i){return this.drawShape(new g.RoundedRectangle(t,e,r,n,i)),this},e.prototype.drawCircle=function(t,e,r){return this.drawShape(new g.Circle(t,e,r)),this},e.prototype.drawEllipse=function(t,e,r,n){return this.drawShape(new g.Ellipse(t,e,r,n)),this},e.prototype.drawPolygon=function(t){var e=t,r=!0;if(e instanceof g.Polygon&&(r=e.closed,e=e.points),!Array.isArray(e)){e=new Array(arguments.length);for(var n=0;n0)&&(this.lineWidth=0,this.filling=!1,this.boundsDirty=-1,this.dirty++,this.clearDirty++,this.graphicsData.length=0),this.currentPath=null,this._spriteRect=null,this},e.prototype.isFastRect=function(){return 1===this.graphicsData.length&&this.graphicsData[0].shape.type===_.SHAPES.RECT&&!this.graphicsData[0].lineWidth},e.prototype._renderWebGL=function(t){this.dirty!==this.fastRectDirty&&(this.fastRectDirty=this.dirty,this._fastRect=this.isFastRect()),this._fastRect?this._renderSpriteRect(t):(t.setObjectRenderer(t.plugins.graphics),t.plugins.graphics.render(this))},e.prototype._renderSpriteRect=function(t){var e=this.graphicsData[0].shape;this._spriteRect||(this._spriteRect=new y.default(new f.default(f.default.WHITE)));var r=this._spriteRect;if(16777215===this.tint)r.tint=this.graphicsData[0].fillColor;else{var n=C,i=R;(0,m.hex2rgb)(this.graphicsData[0].fillColor,n),(0,m.hex2rgb)(this.tint,i),n[0]*=i[0],n[1]*=i[1],n[2]*=i[2],r.tint=(0,m.rgb2hex)(n)}r.alpha=this.graphicsData[0].fillAlpha,r.worldAlpha=this.worldAlpha*r.alpha,r.blendMode=this.blendMode,r.texture._frame.width=e.width,r.texture._frame.height=e.height,r.transform.worldTransform=this.transform.worldTransform,r.anchor.set(-e.x/e.width,-e.y/e.height),r._onAnchorUpdate(),r._renderWebGL(t)},e.prototype._renderCanvas=function(t){this.isMask!==!0&&t.plugins.graphics.render(this)},e.prototype._calculateBounds=function(){this.boundsDirty!==this.dirty&&(this.boundsDirty=this.dirty,this.updateLocalBounds(),this.cachedSpriteDirty=!0);var t=this._localBounds;this._bounds.addFrame(this.transform,t.minX,t.minY,t.maxX,t.maxY)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,M);for(var e=this.graphicsData,r=0;re?o+a:e,r=sn?s+u:n;else if(c===_.SHAPES.CIRC)o=i.x,s=i.y,a=i.radius+f/2,u=i.radius+f/2,t=o-ae?o+a:e,r=s-un?s+u:n;else if(c===_.SHAPES.ELIP)o=i.x,s=i.y,a=i.width+f/2,u=i.height+f/2,t=o-ae?o+a:e,r=s-un?s+u:n;else for(var d=i.points,p=0,v=0,y=0,g=0,m=0,b=0,x=0,T=0,w=0;w+2e?x+m:e,r=T-bn?T+b:n)}else t=0,e=0,r=0,n=0;var E=this.boundsPadding;this._localBounds.minX=t-E,this._localBounds.maxX=e+2*E,this._localBounds.minY=r-E,this._localBounds.maxY=n+2*E},e.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null;var e=new p.default(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,this.nativeLines,t);return this.graphicsData.push(e),e.type===_.SHAPES.POLY&&(e.shape.closed=e.shape.closed||this.filling,this.currentPath=e),this.dirty++,e},e.prototype.generateCanvasTexture=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=this.getLocalBounds(),n=h.default.create(r.width,r.height,t,e);O||(O=new S.default),this.transform.updateLocalTransform(),this.transform.localTransform.copy(P),P.invert(),P.tx-=r.x,P.ty-=r.y,O.render(this,n,!0,P);var i=f.default.fromCanvas(n.baseTexture._canvasRenderTarget.canvas,t);return i.baseTexture.resolution=e,i.baseTexture.update(),i},e.prototype.closePath=function(){var t=this.currentPath;return t&&t.shape&&t.shape.close(),this},e.prototype.addHole=function(){var t=this.graphicsData.pop();return this.currentPath=this.graphicsData[this.graphicsData.length-1],this.currentPath.addHole(t.shape),this.currentPath=null,this},e.prototype.destroy=function(e){t.prototype.destroy.call(this,e);for(var r=0;rC?C:M,r.beginPath(),r.moveTo(E,S+M),r.lineTo(E,S+P-M),r.quadraticCurveTo(E,S+P,E+M,S+P),r.lineTo(E+O-M,S+P),r.quadraticCurveTo(E+O,S+P,E+O,S+P-M),r.lineTo(E+O,S+M),r.quadraticCurveTo(E+O,S,E+O-M,S),r.lineTo(E+M,S),r.quadraticCurveTo(E,S,E,S+M),r.closePath(),(u.fillColor||0===u.fillColor)&&(r.globalAlpha=u.fillAlpha*n,r.fillStyle="#"+("00000"+(0|h).toString(16)).substr(-6),r.fill()),u.lineWidth&&(r.globalAlpha=u.lineAlpha*n,r.strokeStyle="#"+("00000"+(0|c).toString(16)).substr(-6),r.stroke())}}},t.prototype.updateGraphicsTint=function(t){t._prevTint=t.tint;for(var e=(t.tint>>16&255)/255,r=(t.tint>>8&255)/255,n=(255&t.tint)/255,i=0;i>16&255)/255*e*255<<16)+((s>>8&255)/255*r*255<<8)+(255&s)/255*n*255,o._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*r*255<<8)+(255&a)/255*n*255}},t.prototype.renderPolygon=function(t,e,r){r.moveTo(t[0],t[1]);for(var n=1;n8&&void 0!==arguments[8]?arguments[8]:[],l=20,h=0,c=0,f=0,d=0,p=0;u.push(t,e);for(var v=1,y=0;v<=l;++v)y=v/l,h=1-y,c=h*h,f=c*h,d=y*y,p=d*y,u.push(f*t+3*c*y*r+3*h*d*i+p*s,f*e+3*c*y*n+3*h*d*o+p*a);return u}r.__esModule=!0,r.default=n},{}],55:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../utils"),u=t("../../const"),l=t("../../renderers/webgl/utils/ObjectRenderer"),h=n(l),c=t("../../renderers/webgl/WebGLRenderer"),f=n(c),d=t("./WebGLGraphicsData"),p=n(d),v=t("./shaders/PrimitiveShader"),y=n(v),g=t("./utils/buildPoly"),m=n(g),_=t("./utils/buildRectangle"),b=n(_),x=t("./utils/buildRoundedRectangle"),T=n(x),w=t("./utils/buildCircle"),E=n(w),S=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.graphicsDataPool=[],n.primitiveShader=null,n.gl=r.gl,n.CONTEXT_UID=0,n}return s(e,t),e.prototype.onContextChange=function(){this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.primitiveShader=new y.default(this.gl)},e.prototype.destroy=function(){h.default.prototype.destroy.call(this);for(var t=0;t32e4)&&(r=this.graphicsDataPool.pop()||new p.default(this.renderer.gl,this.primitiveShader,this.renderer.state.attribsState),r.reset(e),t.data.push(r)),r.dirty=!0,r},e}(h.default);r.default=S,f.default.registerPlugin("graphics",S)},{"../../const":44,"../../renderers/webgl/WebGLRenderer":82,"../../renderers/webgl/utils/ObjectRenderer":92,"../../utils":120,"./WebGLGraphicsData":56,"./shaders/PrimitiveShader":57,"./utils/buildCircle":58,"./utils/buildPoly":60,"./utils/buildRectangle":61,"./utils/buildRoundedRectangle":62}],56:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("pixi-gl-core"),s=n(o),a=function(){function t(e,r,n){i(this,t),this.gl=e,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=s.default.GLBuffer.createVertexBuffer(e),this.indexBuffer=s.default.GLBuffer.createIndexBuffer(e),this.dirty=!0,this.glPoints=null,this.glIndices=null,this.shader=r,this.vao=new s.default.VertexArrayObject(e,n).addIndex(this.indexBuffer).addAttribute(this.buffer,r.attributes.aVertexPosition,e.FLOAT,!1,24,0).addAttribute(this.buffer,r.attributes.aColor,e.FLOAT,!1,24,8)}return t.prototype.reset=function(){this.points.length=0,this.indices.length=0},t.prototype.upload=function(){this.glPoints=new Float32Array(this.points),this.buffer.upload(this.glPoints),this.glIndices=new Uint16Array(this.indices),this.indexBuffer.upload(this.glIndices),this.dirty=!1},t.prototype.destroy=function(){this.color=null,this.points=null,this.indices=null,this.vao.destroy(),this.buffer.destroy(),this.indexBuffer.destroy(),this.gl=null,this.buffer=null,this.indexBuffer=null,this.glPoints=null,this.glIndices=null},t}();r.default=a},{"pixi-gl-core":12}],57:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../../Shader"),u=n(a),l=function(t){function e(r){return i(this,e),o(this,t.call(this,r,["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","uniform float alpha;","uniform vec3 tint;","varying vec4 vColor;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"].join("\n"),["varying vec4 vColor;","void main(void){"," gl_FragColor = vColor;","}"].join("\n")))}return s(e,t),e}(u.default);r.default=l},{"../../../Shader":42}],58:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,o=void 0,l=void 0;if(t.type===a.SHAPES.CIRC?(o=r.radius,l=r.radius):(o=r.width,l=r.height),0!==o&&0!==l){var h=Math.floor(30*Math.sqrt(r.radius))||Math.floor(15*Math.sqrt(r.width+r.height)),c=2*Math.PI/h;if(t.fill){var f=(0,u.hex2rgb)(t.fillColor),d=t.fillAlpha,p=f[0]*d,v=f[1]*d,y=f[2]*d,g=e.points,m=e.indices,_=g.length/6;m.push(_);for(var b=0;b196*p*p?(R=O-M,A=P-C,I=Math.sqrt(R*R+A*A),R/=I,A/=I,R*=p,A*=p,l.push(T-R,w-A),l.push(g,m,_,y),l.push(T+R,w+A),l.push(g,m,_,y),l.push(T-R,w-A),l.push(g,m,_,y),f++):(l.push(X,G),l.push(g,m,_,y),l.push(T-(X-T),w-(G-w)),l.push(g,m,_,y))}}b=r[2*(c-2)],x=r[2*(c-2)+1],T=r[2*(c-1)],w=r[2*(c-1)+1],O=-(x-w),P=b-T,I=Math.sqrt(O*O+P*P),O/=I,P/=I,O*=p,P*=p,l.push(T-O,w-P),l.push(g,m,_,y),l.push(T+O,w+P),l.push(g,m,_,y),h.push(d);for(var H=0;H=6){for(var n=[],i=t.holes,o=0;o0&&(0,s.default)(t,e)}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils"),u=t("earcut"),l=n(u)},{"../../../utils":120,"./buildLine":59,earcut:2}],61:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,o=r.width,u=r.height;if(t.fill){var l=(0,a.hex2rgb)(t.fillColor),h=t.fillAlpha,c=l[0]*h,f=l[1]*h,d=l[2]*h,p=e.points,v=e.indices,y=p.length/6;p.push(n,i),p.push(c,f,d,h),p.push(n+o,i),p.push(c,f,d,h),p.push(n,i+u),p.push(c,f,d,h),p.push(n+o,i+u),p.push(c,f,d,h),v.push(y,y,y+1,y+2,y+3,y+3)}if(t.lineWidth){var g=t.points;t.points=[n,i,n+o,i,n+o,i+u,n,i+u,n,i],(0,s.default)(t,e),t.points=g}}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils")},{"../../../utils":120,"./buildLine":59}],62:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,o=r.width,a=r.height,l=r.radius,f=[];if(f.push(n,i+l),s(n,i+a-l,n,i+a,n+l,i+a,f),s(n+o-l,i+a,n+o,i+a,n+o,i+a-l,f),s(n+o,i+l,n+o,i,n+o-l,i,f),s(n+l,i,n,i,n,i+l+1e-10,f),t.fill){for(var d=(0,c.hex2rgb)(t.fillColor),p=t.fillAlpha,v=d[0]*p,y=d[1]*p,g=d[2]*p,m=e.points,_=e.indices,b=m.length/6,x=(0,u.default)(f,null,2),T=0,w=x.length;T6&&void 0!==arguments[6]?arguments[6]:[],u=20,l=a,h=0,c=0,f=0,d=0,p=0,v=0,y=0,g=0;y<=u;++y)g=y/u,h=o(t,r,g),c=o(e,n,g),f=o(r,i,g),d=o(n,s,g),p=o(h,f,g),v=o(c,d,g),l.push(p,v);return l}r.__esModule=!0,r.default=i;var a=t("earcut"),u=n(a),l=t("./buildLine"),h=n(l),c=t("../../../utils")},{"../../../utils":120,"./buildLine":59,earcut:2}],63:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.autoDetectRenderer=r.Application=r.Filter=r.SpriteMaskFilter=r.Quad=r.RenderTarget=r.ObjectRenderer=r.WebGLManager=r.Shader=r.CanvasRenderTarget=r.TextureUvs=r.VideoBaseTexture=r.BaseRenderTexture=r.RenderTexture=r.BaseTexture=r.Texture=r.Spritesheet=r.CanvasGraphicsRenderer=r.GraphicsRenderer=r.GraphicsData=r.Graphics=r.TextStyle=r.Text=r.SpriteRenderer=r.CanvasTinter=r.CanvasSpriteRenderer=r.Sprite=r.TransformBase=r.TransformStatic=r.Transform=r.Container=r.DisplayObject=r.Bounds=r.glCore=r.WebGLRenderer=r.CanvasRenderer=r.ticker=r.utils=r.settings=void 0;var o=t("./const");Object.keys(o).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return o[t]}})});var s=t("./math");Object.keys(s).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return s[t]}})});var a=t("pixi-gl-core");Object.defineProperty(r,"glCore",{enumerable:!0,get:function(){return i(a).default}});var u=t("./display/Bounds");Object.defineProperty(r,"Bounds",{enumerable:!0,get:function(){return i(u).default}});var l=t("./display/DisplayObject");Object.defineProperty(r,"DisplayObject",{enumerable:!0,get:function(){return i(l).default}});var h=t("./display/Container");Object.defineProperty(r,"Container",{enumerable:!0,get:function(){return i(h).default}});var c=t("./display/Transform");Object.defineProperty(r,"Transform",{enumerable:!0,get:function(){return i(c).default}});var f=t("./display/TransformStatic");Object.defineProperty(r,"TransformStatic",{enumerable:!0,get:function(){return i(f).default}});var d=t("./display/TransformBase");Object.defineProperty(r,"TransformBase",{enumerable:!0,get:function(){return i(d).default}});var p=t("./sprites/Sprite");Object.defineProperty(r,"Sprite",{enumerable:!0,get:function(){return i(p).default}});var v=t("./sprites/canvas/CanvasSpriteRenderer");Object.defineProperty(r,"CanvasSpriteRenderer",{enumerable:!0,get:function(){return i(v).default}});var y=t("./sprites/canvas/CanvasTinter");Object.defineProperty(r,"CanvasTinter",{enumerable:!0,get:function(){return i(y).default}});var g=t("./sprites/webgl/SpriteRenderer");Object.defineProperty(r,"SpriteRenderer",{enumerable:!0,get:function(){return i(g).default}});var m=t("./text/Text");Object.defineProperty(r,"Text",{enumerable:!0,get:function(){return i(m).default}});var _=t("./text/TextStyle"); +Object.defineProperty(r,"TextStyle",{enumerable:!0,get:function(){return i(_).default}});var b=t("./graphics/Graphics");Object.defineProperty(r,"Graphics",{enumerable:!0,get:function(){return i(b).default}});var x=t("./graphics/GraphicsData");Object.defineProperty(r,"GraphicsData",{enumerable:!0,get:function(){return i(x).default}});var T=t("./graphics/webgl/GraphicsRenderer");Object.defineProperty(r,"GraphicsRenderer",{enumerable:!0,get:function(){return i(T).default}});var w=t("./graphics/canvas/CanvasGraphicsRenderer");Object.defineProperty(r,"CanvasGraphicsRenderer",{enumerable:!0,get:function(){return i(w).default}});var E=t("./textures/Spritesheet");Object.defineProperty(r,"Spritesheet",{enumerable:!0,get:function(){return i(E).default}});var S=t("./textures/Texture");Object.defineProperty(r,"Texture",{enumerable:!0,get:function(){return i(S).default}});var O=t("./textures/BaseTexture");Object.defineProperty(r,"BaseTexture",{enumerable:!0,get:function(){return i(O).default}});var P=t("./textures/RenderTexture");Object.defineProperty(r,"RenderTexture",{enumerable:!0,get:function(){return i(P).default}});var M=t("./textures/BaseRenderTexture");Object.defineProperty(r,"BaseRenderTexture",{enumerable:!0,get:function(){return i(M).default}});var C=t("./textures/VideoBaseTexture");Object.defineProperty(r,"VideoBaseTexture",{enumerable:!0,get:function(){return i(C).default}});var R=t("./textures/TextureUvs");Object.defineProperty(r,"TextureUvs",{enumerable:!0,get:function(){return i(R).default}});var A=t("./renderers/canvas/utils/CanvasRenderTarget");Object.defineProperty(r,"CanvasRenderTarget",{enumerable:!0,get:function(){return i(A).default}});var I=t("./Shader");Object.defineProperty(r,"Shader",{enumerable:!0,get:function(){return i(I).default}});var D=t("./renderers/webgl/managers/WebGLManager");Object.defineProperty(r,"WebGLManager",{enumerable:!0,get:function(){return i(D).default}});var L=t("./renderers/webgl/utils/ObjectRenderer");Object.defineProperty(r,"ObjectRenderer",{enumerable:!0,get:function(){return i(L).default}});var N=t("./renderers/webgl/utils/RenderTarget");Object.defineProperty(r,"RenderTarget",{enumerable:!0,get:function(){return i(N).default}});var F=t("./renderers/webgl/utils/Quad");Object.defineProperty(r,"Quad",{enumerable:!0,get:function(){return i(F).default}});var j=t("./renderers/webgl/filters/spriteMask/SpriteMaskFilter");Object.defineProperty(r,"SpriteMaskFilter",{enumerable:!0,get:function(){return i(j).default}});var B=t("./renderers/webgl/filters/Filter");Object.defineProperty(r,"Filter",{enumerable:!0,get:function(){return i(B).default}});var k=t("./Application");Object.defineProperty(r,"Application",{enumerable:!0,get:function(){return i(k).default}});var U=t("./autoDetectRenderer");Object.defineProperty(r,"autoDetectRenderer",{enumerable:!0,get:function(){return U.autoDetectRenderer}});var X=t("./utils"),G=n(X),W=t("./ticker"),H=n(W),V=t("./settings"),Y=i(V),z=t("./renderers/canvas/CanvasRenderer"),q=i(z),K=t("./renderers/webgl/WebGLRenderer"),Z=i(K);r.settings=Y.default,r.utils=G,r.ticker=H,r.CanvasRenderer=q.default,r.WebGLRenderer=Z.default},{"./Application":41,"./Shader":42,"./autoDetectRenderer":43,"./const":44,"./display/Bounds":45,"./display/Container":46,"./display/DisplayObject":47,"./display/Transform":48,"./display/TransformBase":49,"./display/TransformStatic":50,"./graphics/Graphics":51,"./graphics/GraphicsData":52,"./graphics/canvas/CanvasGraphicsRenderer":53,"./graphics/webgl/GraphicsRenderer":55,"./math":68,"./renderers/canvas/CanvasRenderer":75,"./renderers/canvas/utils/CanvasRenderTarget":77,"./renderers/webgl/WebGLRenderer":82,"./renderers/webgl/filters/Filter":84,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":87,"./renderers/webgl/managers/WebGLManager":91,"./renderers/webgl/utils/ObjectRenderer":92,"./renderers/webgl/utils/Quad":93,"./renderers/webgl/utils/RenderTarget":94,"./settings":99,"./sprites/Sprite":100,"./sprites/canvas/CanvasSpriteRenderer":101,"./sprites/canvas/CanvasTinter":102,"./sprites/webgl/SpriteRenderer":104,"./text/Text":106,"./text/TextStyle":107,"./textures/BaseRenderTexture":108,"./textures/BaseTexture":109,"./textures/RenderTexture":110,"./textures/Spritesheet":111,"./textures/Texture":112,"./textures/TextureUvs":113,"./textures/VideoBaseTexture":114,"./ticker":116,"./utils":120,"pixi-gl-core":12}],64:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){return t<0?-1:t>0?1:0}function o(){for(var t=0;t<16;t++){var e=[];d.push(e);for(var r=0;r<16;r++)for(var n=i(u[t]*u[r]+h[t]*l[r]),o=i(l[t]*u[r]+c[t]*l[r]),s=i(u[t]*h[r]+h[t]*c[r]),p=i(l[t]*h[r]+c[t]*c[r]),v=0;v<16;v++)if(u[v]===n&&l[v]===o&&h[v]===s&&c[v]===p){e.push(v);break}}for(var y=0;y<16;y++){var g=new a.default;g.set(u[y],l[y],h[y],c[y],0,0),f.push(g)}}r.__esModule=!0;var s=t("./Matrix"),a=n(s),u=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],l=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],h=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],c=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],f=[],d=[];o();var p={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MIRROR_HORIZONTAL:12,uX:function(t){return u[t]},uY:function(t){return l[t]},vX:function(t){return h[t]},vY:function(t){return c[t]},inv:function(t){return 8&t?15&t:7&-t},add:function(t,e){return d[t][e]},sub:function(t,e){return d[t][p.inv(e)]},rotate180:function(t){return 4^t},isSwapWidthHeight:function(t){return 2===(3&t)},byDirection:function(t,e){return 2*Math.abs(t)<=Math.abs(e)?e>=0?p.S:p.N:2*Math.abs(e)<=Math.abs(t)?t>0?p.E:p.W:e>0?t>0?p.SE:p.SW:t>0?p.NE:p.NW},matrixAppendRotationInv:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=f[p.inv(e)];i.tx=r,i.ty=n,t.append(i)}};r.default=p},{"./Matrix":65}],65:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:1,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;i(this,t),this.a=e,this.b=r,this.c=n,this.d=o,this.tx=s,this.ty=a,this.array=null}return t.prototype.fromArray=function(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]},t.prototype.set=function(t,e,r,n,i,o){return this.a=t,this.b=e,this.c=r,this.d=n,this.tx=i,this.ty=o,this},t.prototype.toArray=function(t,e){this.array||(this.array=new Float32Array(9));var r=e||this.array;return t?(r[0]=this.a,r[1]=this.b,r[2]=0,r[3]=this.c,r[4]=this.d,r[5]=0,r[6]=this.tx,r[7]=this.ty,r[8]=1):(r[0]=this.a,r[1]=this.c,r[2]=this.tx,r[3]=this.b,r[4]=this.d,r[5]=this.ty,r[6]=0,r[7]=0,r[8]=1),r},t.prototype.apply=function(t,e){e=e||new a.default;var r=t.x,n=t.y;return e.x=this.a*r+this.c*n+this.tx,e.y=this.b*r+this.d*n+this.ty,e},t.prototype.applyInverse=function(t,e){e=e||new a.default;var r=1/(this.a*this.d+this.c*-this.b),n=t.x,i=t.y;return e.x=this.d*r*n+-this.c*r*i+(this.ty*this.c-this.tx*this.d)*r,e.y=this.a*r*i+-this.b*r*n+(-this.ty*this.a+this.tx*this.b)*r,e},t.prototype.translate=function(t,e){return this.tx+=t,this.ty+=e,this},t.prototype.scale=function(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this},t.prototype.rotate=function(t){var e=Math.cos(t),r=Math.sin(t),n=this.a,i=this.c,o=this.tx;return this.a=n*e-this.b*r,this.b=n*r+this.b*e,this.c=i*e-this.d*r,this.d=i*r+this.d*e,this.tx=o*e-this.ty*r,this.ty=o*r+this.ty*e,this},t.prototype.append=function(t){var e=this.a,r=this.b,n=this.c,i=this.d;return this.a=t.a*e+t.b*n,this.b=t.a*r+t.b*i,this.c=t.c*e+t.d*n,this.d=t.c*r+t.d*i,this.tx=t.tx*e+t.ty*n+this.tx,this.ty=t.tx*r+t.ty*i+this.ty,this},t.prototype.setTransform=function(t,e,r,n,i,o,s,a,u){var l=Math.sin(s),h=Math.cos(s),c=Math.cos(u),f=Math.sin(u),d=-Math.sin(a),p=Math.cos(a),v=h*i,y=l*i,g=-l*o,m=h*o;return this.a=c*v+f*g,this.b=c*y+f*m,this.c=d*v+p*g,this.d=d*y+p*m,this.tx=t+(r*v+n*g),this.ty=e+(r*y+n*m),this},t.prototype.prepend=function(t){var e=this.tx;if(1!==t.a||0!==t.b||0!==t.c||1!==t.d){var r=this.a,n=this.c;this.a=r*t.a+this.b*t.c,this.b=r*t.b+this.b*t.d,this.c=n*t.a+this.d*t.c,this.d=n*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this},t.prototype.decompose=function(t){var e=this.a,r=this.b,n=this.c,i=this.d,o=-Math.atan2(-n,i),s=Math.atan2(r,e),a=Math.abs(o+s);return a<1e-5?(t.rotation=s,e<0&&i>=0&&(t.rotation+=t.rotation<=0?Math.PI:-Math.PI),t.skew.x=t.skew.y=0):(t.skew.x=o,t.skew.y=s),t.scale.x=Math.sqrt(e*e+r*r),t.scale.y=Math.sqrt(n*n+i*i),t.position.x=this.tx,t.position.y=this.ty,t},t.prototype.invert=function(){var t=this.a,e=this.b,r=this.c,n=this.d,i=this.tx,o=t*n-e*r;return this.a=n/o,this.b=-e/o,this.c=-r/o,this.d=t/o,this.tx=(r*this.ty-n*i)/o,this.ty=-(t*this.ty-e*i)/o,this},t.prototype.identity=function(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this},t.prototype.clone=function(){var e=new t;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e},t.prototype.copy=function(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t},o(t,null,[{key:"IDENTITY",get:function(){return new t}},{key:"TEMP_MATRIX",get:function(){return new t}}]),t}();r.default=u},{"./Point":67}],66:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this._x=i,this._y=o,this.cb=e,this.scope=r}return t.prototype.set=function(t,e){var r=t||0,n=e||(0!==e?r:0);this._x===r&&this._y===n||(this._x=r,this._y=n,this.cb.call(this.scope))},t.prototype.copy=function(t){this._x===t.x&&this._y===t.y||(this._x=t.x,this._y=t.y,this.cb.call(this.scope))},i(t,[{key:"x",get:function(){return this._x},set:function(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}},{key:"y",get:function(){return this._y},set:function(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}]),t}();r.default=o},{}],67:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;n(this,t),this.x=e,this.y=r}return t.prototype.clone=function(){return new t(this.x,this.y)},t.prototype.copy=function(t){this.set(t.x,t.y)},t.prototype.equals=function(t){return t.x===this.x&&t.y===this.y},t.prototype.set=function(t,e){this.x=t||0,this.y=e||(0!==e?this.x:0)},t}();r.default=i},{}],68:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./Point");Object.defineProperty(r,"Point",{enumerable:!0,get:function(){return n(i).default}});var o=t("./ObservablePoint");Object.defineProperty(r,"ObservablePoint",{enumerable:!0,get:function(){return n(o).default}});var s=t("./Matrix");Object.defineProperty(r,"Matrix",{enumerable:!0,get:function(){return n(s).default}});var a=t("./GroupD8");Object.defineProperty(r,"GroupD8",{enumerable:!0,get:function(){return n(a).default}});var u=t("./shapes/Circle");Object.defineProperty(r,"Circle",{enumerable:!0,get:function(){return n(u).default}});var l=t("./shapes/Ellipse");Object.defineProperty(r,"Ellipse",{enumerable:!0,get:function(){return n(l).default}});var h=t("./shapes/Polygon");Object.defineProperty(r,"Polygon",{enumerable:!0,get:function(){return n(h).default}});var c=t("./shapes/Rectangle");Object.defineProperty(r,"Rectangle",{enumerable:!0,get:function(){return n(c).default}});var f=t("./shapes/RoundedRectangle");Object.defineProperty(r,"RoundedRectangle",{enumerable:!0,get:function(){return n(f).default}})},{"./GroupD8":64,"./Matrix":65,"./ObservablePoint":66,"./Point":67,"./shapes/Circle":69,"./shapes/Ellipse":70,"./shapes/Polygon":71,"./shapes/Rectangle":72,"./shapes/RoundedRectangle":73}],69:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./Rectangle"),s=n(o),a=t("../../const"),u=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;i(this,t),this.x=e,this.y=r,this.radius=n,this.type=a.SHAPES.CIRC}return t.prototype.clone=function(){return new t(this.x,this.y,this.radius)},t.prototype.contains=function(t,e){if(this.radius<=0)return!1;var r=this.radius*this.radius,n=this.x-t,i=this.y-e;return n*=n,i*=i,n+i<=r},t.prototype.getBounds=function(){return new s.default(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)},t}();r.default=u},{"../../const":44,"./Rectangle":72}],70:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./Rectangle"),s=n(o),a=t("../../const"),u=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;i(this,t),this.x=e,this.y=r,this.width=n,this.height=o,this.type=a.SHAPES.ELIP}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;var r=(t-this.x)/this.width,n=(e-this.y)/this.height;return r*=r,n*=n,r+n<=1},t.prototype.getBounds=function(){return new s.default(this.x-this.width,this.y-this.height,this.width,this.height)},t}();r.default=u},{"../../const":44,"./Rectangle":72}],71:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../Point"),s=n(o),a=t("../../const"),u=function(){function t(){for(var e=arguments.length,r=Array(e),n=0;ne!=l>e&&t<(u-s)*((e-a)/(l-a))+s;h&&(r=!r)}return r},t}();r.default=u},{"../../const":44,"../Point":67}],72:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this.x=e,this.y=r,this.width=i,this.height=s,this.type=o.SHAPES.RECT}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this},t.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t=this.y&&et.x+t.width&&(this.width=t.width-this.x,this.width<0&&(this.width=0)),this.y+this.height>t.y+t.height&&(this.height=t.height-this.y,this.height<0&&(this.height=0))},t.prototype.enlarge=function(t){var e=Math.min(this.x,t.x),r=Math.max(this.x+this.width,t.x+t.width),n=Math.min(this.y,t.y),i=Math.max(this.y+this.height,t.y+t.height);this.x=e,this.width=r-e,this.y=n,this.height=i-n},i(t,[{key:"left",get:function(){return this.x}},{key:"right",get:function(){return this.x+this.width}},{key:"top",get:function(){return this.y}},{key:"bottom",get:function(){return this.y+this.height}}],[{key:"EMPTY",get:function(){return new t(0,0,0,0)}}]),t}();r.default=s},{"../../const":44}],73:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:20;n(this,t),this.x=e,this.y=r,this.width=o,this.height=s,this.radius=a,this.type=i.SHAPES.RREC}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height,this.radius)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){if(e>=this.y+this.radius&&e<=this.y+this.height-this.radius||t>=this.x+this.radius&&t<=this.x+this.width-this.radius)return!0;var r=t-(this.x+this.radius),n=e-(this.y+this.radius),i=this.radius*this.radius;if(r*r+n*n<=i)return!0;if(r=t-(this.x+this.width-this.radius),r*r+n*n<=i)return!0;if(n=e-(this.y+this.height-this.radius),r*r+n*n<=i)return!0;if(r=t-(this.x+this.radius),r*r+n*n<=i)return!0}return!1},t}();r.default=o},{"../../const":44}],74:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:{};i(this,e);var a=o(this,t.call(this,"Canvas",r,n,s));return a.type=y.RENDERER_TYPE.CANVAS,a.rootContext=a.view.getContext("2d",{alpha:a.transparent}),a.refresh=!0,a.maskManager=new h.default(a),a.smoothProperty="imageSmoothingEnabled",a.rootContext.imageSmoothingEnabled||(a.rootContext.webkitImageSmoothingEnabled?a.smoothProperty="webkitImageSmoothingEnabled":a.rootContext.mozImageSmoothingEnabled?a.smoothProperty="mozImageSmoothingEnabled":a.rootContext.oImageSmoothingEnabled?a.smoothProperty="oImageSmoothingEnabled":a.rootContext.msImageSmoothingEnabled&&(a.smoothProperty="msImageSmoothingEnabled")),a.initPlugins(),a.blendModes=(0,p.default)(),a._activeBlendMode=null,a.context=null,a.renderingToScreen=!1,a.resize(r,n),a}return s(e,t),e.prototype.render=function(t,e,r,n,i){if(this.view){this.renderingToScreen=!e,this.emit("prerender");var o=this.resolution;e?(e=e.baseTexture||e,e._canvasRenderTarget||(e._canvasRenderTarget=new f.default(e.width,e.height,e.resolution),e.source=e._canvasRenderTarget.canvas,e.valid=!0),this.context=e._canvasRenderTarget.context,this.resolution=e._canvasRenderTarget.resolution):this.context=this.rootContext;var s=this.context;if(e||(this._lastObjectRendered=t),!i){var a=t.parent,u=this._tempDisplayObjectParent.transform.worldTransform;n?(n.copy(u),this._tempDisplayObjectParent.transform._worldID=-1):u.identity(),t.parent=this._tempDisplayObjectParent,t.updateTransform(),t.parent=a}s.setTransform(1,0,0,1,0,0),s.globalAlpha=1,s.globalCompositeOperation=this.blendModes[y.BLEND_MODES.NORMAL],navigator.isCocoonJS&&this.view.screencanvas&&(s.fillStyle="black",s.clear()),(void 0!==r?r:this.clearBeforeRender)&&this.renderingToScreen&&(this.transparent?s.clearRect(0,0,this.width,this.height):(s.fillStyle=this._backgroundColorString,s.fillRect(0,0,this.width,this.height)));var l=this.context;this.context=s,t.renderCanvas(this),this.context=l,this.resolution=o,this.emit("postrender")}},e.prototype.clear=function(t){var e=this.context;t=t||this._backgroundColorString,!this.transparent&&t?(e.fillStyle=t,e.fillRect(0,0,this.width,this.height)):e.clearRect(0,0,this.width,this.height)},e.prototype.setBlendMode=function(t){this._activeBlendMode!==t&&(this._activeBlendMode=t,this.context.globalCompositeOperation=this.blendModes[t])},e.prototype.destroy=function(e){this.destroyPlugins(),t.prototype.destroy.call(this,e),this.context=null,this.refresh=!0,this.maskManager.destroy(),this.maskManager=null,this.smoothProperty=null},e.prototype.resize=function(e,r){t.prototype.resize.call(this,e,r),this.smoothProperty&&(this.rootContext[this.smoothProperty]=m.default.SCALE_MODE===y.SCALE_MODES.LINEAR)},e}(u.default);r.default=_,v.pluginTarget.mixin(_)},{"../../const":44,"../../settings":99,"../../utils":120,"../SystemRenderer":74,"./utils/CanvasMaskManager":76,"./utils/CanvasRenderTarget":77,"./utils/mapCanvasBlendModesToPixi":79}],76:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../../const"),o=function(){function t(e){n(this,t),this.renderer=e}return t.prototype.pushMask=function(t){var e=this.renderer;e.context.save();var r=t.alpha,n=t.transform.worldTransform,i=e.resolution;e.context.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t._texture||(this.renderGraphicsShape(t),e.context.clip()),t.worldAlpha=r},t.prototype.renderGraphicsShape=function(t){var e=this.renderer.context,r=t.graphicsData.length;if(0!==r){e.beginPath();for(var n=0;nS?S:E,e.moveTo(b,x+E),e.lineTo(b,x+w-E),e.quadraticCurveTo(b,x+w,b+E,x+w),e.lineTo(b+T-E,x+w),e.quadraticCurveTo(b+T,x+w,b+T,x+w-E),e.lineTo(b+T,x+E),e.quadraticCurveTo(b+T,x,b+T-E,x),e.lineTo(b+E,x),e.quadraticCurveTo(b,x,b,x+E),e.closePath()}}}},t.prototype.popMask=function(t){t.context.restore()},t.prototype.destroy=function(){},t}();r.default=o},{"../../../const":44}],77:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:[];return(0,a.default)()?(t[o.BLEND_MODES.NORMAL]="source-over",t[o.BLEND_MODES.ADD]="lighter",t[o.BLEND_MODES.MULTIPLY]="multiply",t[o.BLEND_MODES.SCREEN]="screen",t[o.BLEND_MODES.OVERLAY]="overlay",t[o.BLEND_MODES.DARKEN]="darken",t[o.BLEND_MODES.LIGHTEN]="lighten",t[o.BLEND_MODES.COLOR_DODGE]="color-dodge",t[o.BLEND_MODES.COLOR_BURN]="color-burn",t[o.BLEND_MODES.HARD_LIGHT]="hard-light",t[o.BLEND_MODES.SOFT_LIGHT]="soft-light",t[o.BLEND_MODES.DIFFERENCE]="difference",t[o.BLEND_MODES.EXCLUSION]="exclusion",t[o.BLEND_MODES.HUE]="hue",t[o.BLEND_MODES.SATURATION]="saturate",t[o.BLEND_MODES.COLOR]="color",t[o.BLEND_MODES.LUMINOSITY]="luminosity"):(t[o.BLEND_MODES.NORMAL]="source-over",t[o.BLEND_MODES.ADD]="lighter",t[o.BLEND_MODES.MULTIPLY]="source-over",t[o.BLEND_MODES.SCREEN]="source-over",t[o.BLEND_MODES.OVERLAY]="source-over",t[o.BLEND_MODES.DARKEN]="source-over",t[o.BLEND_MODES.LIGHTEN]="source-over",t[o.BLEND_MODES.COLOR_DODGE]="source-over",t[o.BLEND_MODES.COLOR_BURN]="source-over",t[o.BLEND_MODES.HARD_LIGHT]="source-over",t[o.BLEND_MODES.SOFT_LIGHT]="source-over",t[o.BLEND_MODES.DIFFERENCE]="source-over",t[o.BLEND_MODES.EXCLUSION]="source-over",t[o.BLEND_MODES.HUE]="source-over",t[o.BLEND_MODES.SATURATION]="source-over",t[o.BLEND_MODES.COLOR]="source-over",t[o.BLEND_MODES.LUMINOSITY]="source-over"),t}r.__esModule=!0,r.default=i;var o=t("../../../const"),s=t("./canUseNewCanvasBlendModes"),a=n(s)},{"../../../const":44,"./canUseNewCanvasBlendModes":78}],80:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../const"),s=t("../../settings"),a=n(s),u=function(){function t(e){i(this,t),this.renderer=e,this.count=0,this.checkCount=0,this.maxIdle=a.default.GC_MAX_IDLE,this.checkCountMax=a.default.GC_MAX_CHECK_COUNT,this.mode=a.default.GC_MODE}return t.prototype.update=function(){this.count++, +this.mode!==o.GC_MODES.MANUAL&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run()))},t.prototype.run=function(){for(var t=this.renderer.textureManager,e=t._managedTextures,r=!1,n=0;nthis.maxIdle&&(t.destroyTexture(i,!0),e[n]=null,r=!0)}if(r){for(var o=0,s=0;s=0;r--)this.unload(t.children[r])},t}();r.default=u},{"../../const":44,"../../settings":99}],81:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("pixi-gl-core"),s=t("../../const"),a=t("./utils/RenderTarget"),u=n(a),l=t("../../utils"),h=function(){function t(e){i(this,t),this.renderer=e,this.gl=e.gl,this._managedTextures=[]}return t.prototype.bindTexture=function(){},t.prototype.getTexture=function(){},t.prototype.updateTexture=function(t,e){var r=this.gl,n=!!t._glRenderTargets;if(!t.hasLoaded)return null;var i=this.renderer.boundTextures;if(void 0===e){e=0;for(var a=0;a2&&void 0!==arguments[2]?arguments[2]:{};i(this,e);var a=o(this,t.call(this,"WebGL",r,n,s));return a.legacy=!!s.legacy,a.legacy&&(D.default.VertexArrayObject.FORCE_NATIVE=!0),a.type=L.RENDERER_TYPE.WEBGL,a.handleContextLost=a.handleContextLost.bind(a),a.handleContextRestored=a.handleContextRestored.bind(a),a.view.addEventListener("webglcontextlost",a.handleContextLost,!1),a.view.addEventListener("webglcontextrestored",a.handleContextRestored,!1),a._contextOptions={alpha:a.transparent,antialias:s.antialias,premultipliedAlpha:a.transparent&&"notMultiplied"!==a.transparent,stencil:!0,preserveDrawingBuffer:s.preserveDrawingBuffer},a._backgroundColorRgba[3]=a.transparent?0:1,a.maskManager=new h.default(a),a.stencilManager=new f.default(a),a.emptyRenderer=new m.default(a),a.currentRenderer=a.emptyRenderer,a.initPlugins(),s.context&&(0,R.default)(s.context),a.gl=s.context||D.default.createContext(a.view,a._contextOptions),a.CONTEXT_UID=N++,a.state=new O.default(a.gl),a.renderingToScreen=!0,a.boundTextures=null,a._activeShader=null,a._activeVao=null,a._activeRenderTarget=null,a._initContext(),a.filterManager=new p.default(a),a.drawModes=(0,M.default)(a.gl),a._nextTextureLocation=0,a.setBlendMode(0),a}return s(e,t),e.prototype._initContext=function(){var t=this.gl;t.isContextLost()&&t.getExtension("WEBGL_lose_context")&&t.getExtension("WEBGL_lose_context").restoreContext();var e=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);this.boundTextures=new Array(e),this.emptyTextures=new Array(e),this.textureManager=new b.default(this),this.textureGC=new E.default(this),this.state.resetToDefault(),this.rootRenderTarget=new y.default(t,this.width,this.height,null,this.resolution,(!0)),this.rootRenderTarget.clearColor=this._backgroundColorRgba,this.bindRenderTarget(this.rootRenderTarget);var r=new D.default.GLTexture.fromData(t,null,1,1),n={_glTextures:{}};n._glTextures[this.CONTEXT_UID]={};for(var i=0;i 0.5)"," {"," color = vec4(1.0, 0.0, 0.0, 1.0);"," }"," else"," {"," color = vec4(0.0, 1.0, 0.0, 1.0);"," }"," gl_FragColor = mix(sample, masky, 0.5);"," gl_FragColor *= sample.a;","}"].join("\n")}}]),t}();r.default=d},{"../../../const":44,"../../../settings":99,"../../../utils":120,"./extractUniformsFromSrc":85}],85:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e,r){var n=o(t,r),i=o(e,r);return Object.assign(n,i)}function o(t){for(var e=new RegExp("^(projectionMatrix|uSampler|filterArea|filterClamp)$"),r={},n=void 0,i=t.replace(/\s+/g," ").split(/\s*;\s*/),o=0;o-1){var a=s.split(" "),l=a[1],h=a[2],c=1;h.indexOf("[")>-1&&(n=h.split(/\[|]/),h=n[0],c*=Number(n[1])),h.match(e)||(r[h]={value:u(l,c),name:h,type:l})}}return r}r.__esModule=!0,r.default=i;var s=t("pixi-gl-core"),a=n(s),u=a.default.shader.defaultValue},{"pixi-gl-core":12}],86:[function(t,e,r){"use strict";function n(t,e,r){var n=t.identity();return n.translate(e.x/r.width,e.y/r.height),n.scale(r.width,r.height),n}function i(t,e,r){var n=t.identity();n.translate(e.x/r.width,e.y/r.height);var i=r.width/e.width,o=r.height/e.height;return n.scale(i,o),n}function o(t,e,r,n){var i=n.worldTransform.copy(s.Matrix.TEMP_MATRIX),o=n._texture.baseTexture,a=t.identity(),u=r.height/r.width;a.translate(e.x/r.width,e.y/r.height),a.scale(1,u);var l=r.width/o.width,h=r.height/o.height;return i.tx/=o.width*l,i.ty/=o.width*l,i.invert(),a.prepend(i),a.scale(1,1/u),a.scale(l,h),a.translate(n.anchor.x,n.anchor.y),a}r.__esModule=!0,r.calculateScreenSpaceMatrix=n,r.calculateNormalizedScreenSpaceMatrix=i,r.calculateSpriteMatrix=o;var s=t("../../../math")},{"../../../math":68}],87:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../Filter"),u=n(a),l=t("../../../../math"),h=(t("path"),function(t){function e(r){i(this,e);var n=new l.Matrix,s=o(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n","varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n"));return r.renderable=!1,s.maskSprite=r,s.maskMatrix=n,s}return s(e,t),e.prototype.apply=function(t,e,r){var n=this.maskSprite;this.uniforms.mask=n._texture,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,n),this.uniforms.alpha=n.worldAlpha,t.applyFilter(this,e,r)},e}(u.default));r.default=h},{"../../../../math":68,"../Filter":84,path:22}],88:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var u=t("./WebGLManager"),l=i(u),h=t("../utils/RenderTarget"),c=i(h),f=t("../utils/Quad"),d=i(f),p=t("../../../math"),v=t("../../../Shader"),y=i(v),g=t("../filters/filterTransforms"),m=n(g),_=t("bit-twiddle"),b=i(_),x=function t(){a(this,t),this.renderTarget=null,this.sourceFrame=new p.Rectangle,this.destinationFrame=new p.Rectangle,this.filters=[],this.target=null,this.resolution=1},T=function(t){function e(r){a(this,e);var n=o(this,t.call(this,r));return n.gl=n.renderer.gl,n.quad=new d.default(n.gl,r.state.attribState),n.shaderCache={},n.pool={},n.filterData=null,n}return s(e,t),e.prototype.pushFilter=function(t,e){var r=this.renderer,n=this.filterData;if(!n){n=this.renderer._activeRenderTarget.filterStack;var i=new x;i.sourceFrame=i.destinationFrame=this.renderer._activeRenderTarget.size,i.renderTarget=r._activeRenderTarget,this.renderer._activeRenderTarget.filterData=n={index:0,stack:[i]},this.filterData=n}var o=n.stack[++n.index];o||(o=n.stack[n.index]=new x);var s=e[0].resolution,a=0|e[0].padding,u=t.filterArea||t.getBounds(!0),l=o.sourceFrame,h=o.destinationFrame;l.x=(u.x*s|0)/s,l.y=(u.y*s|0)/s,l.width=(u.width*s|0)/s,l.height=(u.height*s|0)/s,n.stack[0].renderTarget.transform||l.fit(n.stack[0].destinationFrame),l.pad(a),h.width=l.width,h.height=l.height;var c=this.getPotRenderTarget(r.gl,l.width,l.height,s);o.target=t,o.filters=e,o.resolution=s,o.renderTarget=c,c.setFrame(h,l),r.bindRenderTarget(c),c.clear()},e.prototype.popFilter=function(){var t=this.filterData,e=t.stack[t.index-1],r=t.stack[t.index];this.quad.map(r.renderTarget.size,r.sourceFrame).upload();var n=r.filters;if(1===n.length)n[0].apply(this,r.renderTarget,e.renderTarget,!1,r),this.freePotRenderTarget(r.renderTarget);else{var i=r.renderTarget,o=this.getPotRenderTarget(this.renderer.gl,r.sourceFrame.width,r.sourceFrame.height,r.resolution);o.setFrame(r.destinationFrame,r.sourceFrame),o.clear();var s=0;for(s=0;s0&&(e+="\nelse "),r1&&void 0!==arguments[1]?arguments[1]:[];return e[i.BLEND_MODES.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.ADD]=[t.ONE,t.DST_ALPHA],e[i.BLEND_MODES.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SCREEN]=[t.ONE,t.ONE_MINUS_SRC_COLOR],e[i.BLEND_MODES.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":44}],97:[function(t,e,r){"use strict";function n(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e[i.DRAW_MODES.POINTS]=t.POINTS,e[i.DRAW_MODES.LINES]=t.LINES,e[i.DRAW_MODES.LINE_LOOP]=t.LINE_LOOP,e[i.DRAW_MODES.LINE_STRIP]=t.LINE_STRIP,e[i.DRAW_MODES.TRIANGLES]=t.TRIANGLES,e[i.DRAW_MODES.TRIANGLE_STRIP]=t.TRIANGLE_STRIP,e[i.DRAW_MODES.TRIANGLE_FAN]=t.TRIANGLE_FAN,e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":44}],98:[function(t,e,r){"use strict";function n(t){var e=t.getContextAttributes();e.stencil||console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly")}r.__esModule=!0,r.default=n},{}],99:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./utils/maxRecommendedTextures"),o=n(i),s=t("./utils/canUploadSameBuffer"),a=n(s);r.default={TARGET_FPMS:.06,MIPMAP_TEXTURES:!0,RESOLUTION:1,FILTER_RESOLUTION:1,SPRITE_MAX_TEXTURES:(0,o.default)(32),SPRITE_BATCH_SIZE:4096,RETINA_PREFIX:/@([0-9\.]+)x/,RENDER_OPTIONS:{view:null,antialias:!1,forceFXAA:!1,autoResize:!1,transparent:!1,backgroundColor:0,clearBeforeRender:!0,preserveDrawingBuffer:!1,roundPixels:!1},TRANSFORM_MODE:0,GC_MODE:0,GC_MAX_IDLE:3600,GC_MAX_CHECK_COUNT:600,WRAP_MODE:0,SCALE_MODE:0,PRECISION_VERTEX:"highp",PRECISION_FRAGMENT:"mediump",CAN_UPLOAD_SAME_BUFFER:(0,a.default)()}},{"./utils/canUploadSameBuffer":117,"./utils/maxRecommendedTextures":121}],100:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rn&&v.xi&&v.y>16)+(65280&t)+((255&t)<<16)}},{key:"texture",get:function(){return this._texture},set:function(t){this._texture!==t&&(this._texture=t,this.cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,t&&(t.baseTexture.hasLoaded?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}]),e}(p.default);r.default=y},{"../const":44,"../display/Container":46,"../math":68,"../textures/Texture":112,"../utils":120}],101:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../renderers/canvas/CanvasRenderer"),s=n(o),a=t("../../const"),u=t("../../math"),l=t("./CanvasTinter"),h=n(l),c=new u.Matrix,f=function(){function t(e){i(this,t),this.renderer=e}return t.prototype.render=function(t){var e=t._texture,r=this.renderer,n=e._frame.width,i=e._frame.height,o=t.transform.worldTransform,s=0,l=0;if(!(e.orig.width<=0||e.orig.height<=0)&&e.baseTexture.source&&(r.setBlendMode(t.blendMode),e.valid)){r.context.globalAlpha=t.worldAlpha;var f=e.baseTexture.scaleMode===a.SCALE_MODES.LINEAR;r.smoothProperty&&r.context[r.smoothProperty]!==f&&(r.context[r.smoothProperty]=f),e.trim?(s=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,l=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(s=(.5-t.anchor.x)*e.orig.width,l=(.5-t.anchor.y)*e.orig.height),e.rotate&&(o.copy(c),o=c,u.GroupD8.matrixAppendRotationInv(o,e.rotate,s,l),s=0,l=0),s-=n/2,l-=i/2,r.roundPixels?(r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution|0,o.ty*r.resolution|0),s=0|s,l=0|l):r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution,o.ty*r.resolution);var d=e.baseTexture.resolution;16777215!==t.tint?(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=h.default.getTintedTexture(t,t.tint)),r.context.drawImage(t.tintedTexture,0,0,n*d,i*d,s*r.resolution,l*r.resolution,n*r.resolution,i*r.resolution)):r.context.drawImage(e.baseTexture.source,e._frame.x*d,e._frame.y*d,n*d,i*d,s*r.resolution,l*r.resolution,n*r.resolution,i*r.resolution)}},t.prototype.destroy=function(){this.renderer=null},t}();r.default=f,s.default.registerPlugin("sprite",f)},{"../../const":44,"../../math":68,"../../renderers/canvas/CanvasRenderer":75,"./CanvasTinter":102}],102:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("../../utils"),o=t("../../renderers/canvas/utils/canUseNewCanvasBlendModes"),s=n(o),a={getTintedTexture:function(t,e){var r=t.texture;e=a.roundColor(e);var n="#"+("00000"+(0|e).toString(16)).substr(-6);if(r.tintCache=r.tintCache||{},r.tintCache[n])return r.tintCache[n];var i=a.canvas||document.createElement("canvas");if(a.tintMethod(r,e,i),a.convertTintToImage){var o=new Image;o.src=i.toDataURL(),r.tintCache[n]=o}else r.tintCache[n]=i,a.canvas=null;return i},tintWithMultiply:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="multiply",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},tintWithOverlay:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.globalCompositeOperation="copy",n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},tintWithPerPixel:function(t,e,r){var n=r.getContext("2d"),o=t._frame.clone(),s=t.baseTexture.resolution;o.x*=s,o.y*=s,o.width*=s,o.height*=s,r.width=Math.ceil(o.width),r.height=Math.ceil(o.height),n.globalCompositeOperation="copy",n.drawImage(t.baseTexture.source,o.x,o.y,o.width,o.height,0,0,o.width,o.height);for(var a=(0,i.hex2rgb)(e),u=a[0],l=a[1],h=a[2],c=n.getImageData(0,0,o.width,o.height),f=c.data,d=0;d=this.size&&this.flush(),t._texture._uvs&&(this.sprites[this.currentIndex++]=t)},e.prototype.flush=function(){if(0!==this.currentIndex){var t=this.renderer.gl,e=this.MAX_TEXTURES,r=E.default.nextPow2(this.currentIndex),n=E.default.log2(r),i=this.buffers[n],o=this.sprites,s=this.groups,a=i.float32View,u=i.uint32View,l=this.boundTextures,h=this.renderer.boundTextures,c=this.renderer.textureGC.count,f=0,d=void 0,p=void 0,v=1,y=0,g=s[0],m=void 0,_=void 0,x=o[0].blendMode;g.textureCount=0,g.start=0,g.blend=x,S++;var w=void 0;for(w=0;w0&&(e+="\nelse "),r0?this.context.shadowColor=r.dropShadowColor:this.context.fillStyle=r.dropShadowColor;for(var v=Math.cos(r.dropShadowAngle)*r.dropShadowDistance,y=Math.sin(r.dropShadowAngle)*r.dropShadowDistance,g=0;g3&&void 0!==arguments[3]&&arguments[3],i=this._style,o=i.letterSpacing;if(0===o)return void(n?this.context.strokeText(t,e,r):this.context.fillText(t,e,r));for(var s=String.prototype.split.call(t,""),a=e,u=0,l="";ui)for(var h=a[u].split(""),c=0;cs?(e+="\n"+h[c],s=i-f):(0===c&&(e+=" "),e+=h[c],s-=f)}else{var d=l+this.context.measureText(" ").width;0===u||d>s?(u>0&&(e+="\n"),e+=a[u],s=i-l):(s-=d,e+=" "+a[u])}}o=0;n--){var i=r[n].trim();/([\"\'])[^\'\"]+\1/.test(i)||(i='"'+i+'"'),r[n]=i}return t.fontStyle+" "+t.fontVariant+" "+t.fontWeight+" "+e+" "+r.join(",")},e.calculateFontProperties=function(t){if(e.fontPropertiesCache[t])return e.fontPropertiesCache[t];var r={},n=e.fontPropertiesCanvas,i=e.fontPropertiesContext;i.font=t;var o=Math.ceil(i.measureText("|MÉq").width),s=Math.ceil(i.measureText("M").width),a=2*s;s=1.4*s|0,n.width=o,n.height=a,i.fillStyle="#f00",i.fillRect(0,0,o,a),i.font=t,i.textBaseline="alphabetic",i.fillStyle="#000",i.fillText("|MÉq",0,s);var u=i.getImageData(0,0,o,a).data,l=u.length,h=4*o,c=0,f=0,d=!1;for(c=0;cs;--c){for(var v=0;v0&&void 0!==arguments[0]?arguments[0]:100,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,s=arguments[2],a=arguments[3];i(this,e);var u=o(this,t.call(this,null,s));return u.resolution=a||h.default.RESOLUTION,u.width=r,u.height=n,u.realWidth=u.width*u.resolution,u.realHeight=u.height*u.resolution,u.scaleMode=void 0!==s?s:h.default.SCALE_MODE,u.hasLoaded=!0,u._glRenderTargets={},u._canvasRenderTarget=null,u.valid=!1,u}return s(e,t),e.prototype.resize=function(t,e){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.realWidth=this.width*this.resolution,this.realHeight=this.height*this.resolution,this.valid&&this.emit("update",this))},e.prototype.destroy=function(){t.prototype.destroy.call(this,!0),this.renderer=null},e}(u.default);r.default=c},{"../settings":99,"./BaseTexture":109}],109:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u=t("../utils"),l=t("../settings"),h=n(l),c=t("eventemitter3"),f=n(c),d=t("../utils/determineCrossOrigin"),p=n(d),v=t("bit-twiddle"),y=n(v),g=function(t){function e(r,n,s){i(this,e);var a=o(this,t.call(this));return a.uid=(0,u.uid)(),a.touched=0,a.resolution=s||h.default.RESOLUTION,a.width=100,a.height=100,a.realWidth=100,a.realHeight=100,a.scaleMode=void 0!==n?n:h.default.SCALE_MODE,a.hasLoaded=!1,a.isLoading=!1,a.source=null,a.origSource=null,a.imageType=null,a.sourceScale=1,a.premultipliedAlpha=!0,a.imageUrl=null,a.isPowerOfTwo=!1,a.mipmap=h.default.MIPMAP_TEXTURES,a.wrapMode=h.default.WRAP_MODE,a._glTextures={},a._enabled=0,a._virtalBoundId=-1,r&&a.loadSource(r),a._destroyed=!1,a}return s(e,t),e.prototype.update=function(){"svg"!==this.imageType&&(this.realWidth=this.source.naturalWidth||this.source.videoWidth||this.source.width,this.realHeight=this.source.naturalHeight||this.source.videoHeight||this.source.height,this._updateDimensions()),this.emit("update",this)},e.prototype._updateDimensions=function(){this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=y.default.isPow2(this.realWidth)&&y.default.isPow2(this.realHeight)},e.prototype.loadSource=function(t){var e=this,r=this.isLoading;this.hasLoaded=!1,this.isLoading=!1,r&&this.source&&(this.source.onload=null,this.source.onerror=null);var n=!this.source;if(this.source=t,(t.src&&t.complete||t.getContext)&&t.width&&t.height)this._updateImageType(),"svg"===this.imageType?this._loadSvgSource():this._sourceLoaded(),n&&this.emit("loaded",this);else if(!t.getContext){var i=function(){e.isLoading=!0;var n=e;if(t.onload=function(){if(n._updateImageType(),t.onload=null,t.onerror=null,n.isLoading)return n.isLoading=!1,n._sourceLoaded(),"svg"===n.imageType?void n._loadSvgSource():void n.emit("loaded",n)},t.onerror=function(){t.onload=null,t.onerror=null,n.isLoading&&(n.isLoading=!1,n.emit("error",n))},t.complete&&t.src){if(t.onload=null,t.onerror=null,"svg"===n.imageType)return n._loadSvgSource(),{v:void 0};e.isLoading=!1,t.width&&t.height?(e._sourceLoaded(),r&&e.emit("loaded",e)):r&&e.emit("error",e)}}();if("object"===("undefined"==typeof i?"undefined":a(i)))return i.v}},e.prototype._updateImageType=function(){if(this.imageUrl){var t=(0,u.decomposeDataUri)(this.imageUrl),e=void 0;if(t&&"image"===t.mediaType){var r=t.subType.split("+")[0];if(e=(0,u.getUrlFileExtension)("."+r),!e)throw new Error("Invalid image type in data URI.")}else e=(0,u.getUrlFileExtension)(this.imageUrl),e||(e="png");this.imageType=e}},e.prototype._loadSvgSource=function(){if("svg"===this.imageType){var t=(0,u.decomposeDataUri)(this.imageUrl);t?this._loadSvgSourceUsingDataUri(t):this._loadSvgSourceUsingXhr()}},e.prototype._loadSvgSourceUsingDataUri=function(t){var e=void 0;if("base64"===t.encoding){if(!atob)throw new Error("Your browser doesn't support base64 conversions.");e=atob(t.data)}else e=t.data;this._loadSvgSourceUsingString(e)},e.prototype._loadSvgSourceUsingXhr=function(){var t=this,e=new XMLHttpRequest;e.onload=function(){if(e.readyState!==e.DONE||200!==e.status)throw new Error("Failed to load SVG using XHR.");t._loadSvgSourceUsingString(e.response)},e.onerror=function(){return t.emit("error",t)},e.open("GET",this.imageUrl,!0),e.send()},e.prototype._loadSvgSourceUsingString=function(t){var e=(0,u.getSvgSize)(t),r=e.width,n=e.height;if(!r||!n)throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them.");this.realWidth=Math.round(r*this.sourceScale),this.realHeight=Math.round(n*this.sourceScale),this._updateDimensions();var i=document.createElement("canvas");i.width=this.realWidth,i.height=this.realHeight,i._pixiId="canvas_"+(0,u.uid)(),i.getContext("2d").drawImage(this.source,0,0,r,n,0,0,this.realWidth,this.realHeight),this.origSource=this.source,this.source=i,u.BaseTextureCache[i._pixiId]=this,this.isLoading=!1,this._sourceLoaded(),this.emit("loaded",this)},e.prototype._sourceLoaded=function(){this.hasLoaded=!0,this.update()},e.prototype.destroy=function(){this.imageUrl&&(delete u.BaseTextureCache[this.imageUrl],delete u.TextureCache[this.imageUrl],this.imageUrl=null,navigator.isCocoonJS||(this.source.src="")),this.source&&this.source._pixiId&&delete u.BaseTextureCache[this.source._pixiId],this.source=null,this.dispose(),this._destroyed=!0},e.prototype.dispose=function(){this.emit("dispose",this)},e.prototype.updateSourceImage=function(t){this.source.src=t,this.loadSource(this.source)},e.fromImage=function(t,r,n,i){var o=u.BaseTextureCache[t];if(!o){var s=new Image;void 0===r&&0!==t.indexOf("data:")&&(s.crossOrigin=(0,p.default)(t)),o=new e(s,n),o.imageUrl=t,i&&(o.sourceScale=i),o.resolution=(0,u.getResolutionOfUrl)(t),s.src=t,u.BaseTextureCache[t]=o}return o},e.fromCanvas=function(t,r){t._pixiId||(t._pixiId="canvas_"+(0,u.uid)());var n=u.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),u.BaseTextureCache[t._pixiId]=n),n},e.from=function(t,r,n){if("string"==typeof t)return e.fromImage(t,void 0,r,n);if(t instanceof HTMLImageElement){var i=t.src,o=u.BaseTextureCache[i];return o||(o=new e(t,r),o.imageUrl=i,n&&(o.sourceScale=n),o.resolution=(0,u.getResolutionOfUrl)(i),u.BaseTextureCache[i]=o),o}return t instanceof HTMLCanvasElement?e.fromCanvas(t,r):t},e}(f.default);r.default=g},{"../settings":99,"../utils":120,"../utils/determineCrossOrigin":119,"bit-twiddle":1,eventemitter3:3}],110:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("./BaseRenderTexture"),u=n(a),l=t("./Texture"),h=n(l),c=function(t){function e(r,n){i(this,e);var s=null;if(!(r instanceof u.default)){var a=arguments[1],l=arguments[2],h=arguments[3],c=arguments[4];console.warn("Please use RenderTexture.create("+a+", "+l+") instead of the ctor directly."),s=arguments[0],n=null,r=new u.default(a,l,h,c)}var f=o(this,t.call(this,r,n));return f.legacyRenderer=s,f.valid=!0,f._updateUvs(),f}return s(e,t),e.prototype.resize=function(t,e,r){this.valid=t>0&&e>0,this._frame.width=this.orig.width=t,this._frame.height=this.orig.height=e,r||this.baseTexture.resize(t,e),this._updateUvs()},e.create=function(t,r,n,i){return new e(new u.default(t,r,n,i))},e}(h.default);r.default=c},{"./BaseRenderTexture":108,"./Texture":112}],111:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:null;n(this,t),this.baseTexture=e,this.textures={},this.data=r,this.resolution=this._updateResolution(i||this.baseTexture.imageUrl),this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}return i(t,null,[{key:"BATCH_SIZE",get:function(){return 1e3}}]),t.prototype._updateResolution=function(t){var e=this.data.meta.scale,r=(0,s.getResolutionOfUrl)(t,null);return null===r&&(r=void 0!==e?parseFloat(e):1),1!==r&&(this.baseTexture.resolution=r,this.baseTexture.update()),r},t.prototype.parse=function(e){this._batchIndex=0,this._callback=e,this._frameKeys.length<=t.BATCH_SIZE?(this._processFrames(0),this._parseComplete()):this._nextBatch()},t.prototype._processFrames=function(e){for(var r=e,n=t.BATCH_SIZE;r-e0&&void 0!==arguments[0]&&arguments[0];for(var e in this.textures)this.textures[e].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,t&&this.baseTexture.destroy(),this.baseTexture=null},t}();r.default=a},{"../":63,"../utils":120}],112:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(){var t=document.createElement("canvas");t.width=10,t.height=10;var e=t.getContext("2d");return e.fillStyle="white",e.fillRect(0,0,10,10),new b(new c.default(t))}function u(t){t.destroy=function(){},t.on=function(){},t.once=function(){},t.emit=function(){}}r.__esModule=!0;var l=function(){function t(t,e){for(var r=0;rthis.baseTexture.width||t.y+t.height>this.baseTexture.height)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions: "+("X: "+t.x+" + "+t.width+" > "+this.baseTexture.width+" ")+("Y: "+t.y+" + "+t.height+" > "+this.baseTexture.height));this.valid=t&&t.width&&t.height&&this.baseTexture.hasLoaded,this.trim||this.rotate||(this.orig=t),this.valid&&this._updateUvs()}},{key:"rotate",get:function(){return this._rotate},set:function(t){this._rotate=t,this.valid&&this._updateUvs()}},{key:"width",get:function(){return this.orig.width}},{key:"height",get:function(){return this.orig.height}}]),e}(g.default);r.default=b,b.EMPTY=new b(new c.default),u(b.EMPTY),b.WHITE=a(),u(b.WHITE)},{"../math":68,"../utils":120,"./BaseTexture":109,"./TextureUvs":113,"./VideoBaseTexture":114,eventemitter3:3}],113:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../math/GroupD8"),s=n(o),a=function(){function t(){i(this,t),this.x0=0,this.y0=0,this.x1=1,this.y1=0,this.x2=1,this.y2=1,this.x3=0,this.y3=1,this.uvsUint32=new Uint32Array(4)}return t.prototype.set=function(t,e,r){var n=e.width,i=e.height;if(r){var o=t.width/2/n,a=t.height/2/i,u=t.x/n+o,l=t.y/i+a;r=s.default.add(r,s.default.NW),this.x0=u+o*s.default.uX(r),this.y0=l+a*s.default.uY(r),r=s.default.add(r,2),this.x1=u+o*s.default.uX(r),this.y1=l+a*s.default.uY(r),r=s.default.add(r,2),this.x2=u+o*s.default.uX(r),this.y2=l+a*s.default.uY(r),r=s.default.add(r,2),this.x3=u+o*s.default.uX(r),this.y3=l+a*s.default.uY(r)}else this.x0=t.x/n,this.y0=t.y/i,this.x1=(t.x+t.width)/n,this.y1=t.y/i,this.x2=(t.x+t.width)/n,this.y2=(t.y+t.height)/i,this.x3=t.x/n,this.y3=(t.y+t.height)/i;this.uvsUint32[0]=(65535*this.y0&65535)<<16|65535*this.x0&65535,this.uvsUint32[1]=(65535*this.y1&65535)<<16|65535*this.x1&65535,this.uvsUint32[2]=(65535*this.y2&65535)<<16|65535*this.x2&65535,this.uvsUint32[3]=(65535*this.y3&65535)<<16|65535*this.x3&65535},t}();r.default=a},{"../math/GroupD8":64}],114:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function u(t,e){e||(e="video/"+t.substr(t.lastIndexOf(".")+1));var r=document.createElement("source");return r.src=t,r.type=e,r}r.__esModule=!0;var l=function(){function t(t,e){for(var r=0;r0&&t.paused===!1&&t.ended===!1&&t.readyState>2},e.prototype._isSourceReady=function(){return 3===this.source.readyState||4===this.source.readyState},e.prototype._onPlayStart=function(){this.hasLoaded||this._onCanPlay(),!this._isAutoUpdating&&this.autoUpdate&&(p.shared.add(this.update,this),this._isAutoUpdating=!0); +},e.prototype._onPlayStop=function(){this._isAutoUpdating&&(p.shared.remove(this.update,this),this._isAutoUpdating=!1)},e.prototype._onCanPlay=function(){this.hasLoaded=!0,this.source&&(this.source.removeEventListener("canplay",this._onCanPlay),this.source.removeEventListener("canplaythrough",this._onCanPlay),this.width=this.source.videoWidth,this.height=this.source.videoHeight,this.__loaded||(this.__loaded=!0,this.emit("loaded",this)),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.source.play())},e.prototype.destroy=function(){this._isAutoUpdating&&p.shared.remove(this.update,this),this.source&&this.source._pixiId&&(delete f.BaseTextureCache[this.source._pixiId],delete this.source._pixiId),t.prototype.destroy.call(this)},e.fromVideo=function(t,r){t._pixiId||(t._pixiId="video_"+(0,f.uid)());var n=f.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),f.BaseTextureCache[t._pixiId]=n),n},e.fromUrl=function(t,r){var n=document.createElement("video");if(n.setAttribute("webkit-playsinline",""),n.setAttribute("playsinline",""),Array.isArray(t))for(var i=0;i0&&void 0!==arguments[0]?arguments[0]:performance.now(),e=void 0;t>this.lastTime?(e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),this.deltaTime=e*a.default.TARGET_FPMS*this.speed,this._emitter.emit(h,this.deltaTime)):this.deltaTime=this.elapsedMS=0,this.lastTime=t},o(t,[{key:"FPS",get:function(){return 1e3/this.elapsedMS}},{key:"minFPS",get:function(){return 1e3/this._maxElapsedMS},set:function(t){var e=Math.min(Math.max(0,t)/1e3,a.default.TARGET_FPMS);this._maxElapsedMS=1/e}}]),t}();r.default=c},{"../settings":99,eventemitter3:3}],116:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.Ticker=r.shared=void 0;var i=t("./Ticker"),o=n(i),s=new o.default;s.autoStart=!0,r.shared=s,r.Ticker=o.default},{"./Ticker":115}],117:[function(t,e,r){"use strict";function n(){var t=!!navigator.platform&&/iPad|iPhone|iPod/.test(navigator.platform);return!t}r.__esModule=!0,r.default=n},{}],118:[function(t,e,r){"use strict";function n(t){for(var e=6*t,r=new Uint16Array(e),n=0,i=0;n1&&void 0!==arguments[1]?arguments[1]:window.location;if(0===t.indexOf("data:"))return"";e=e||window.location,a||(a=document.createElement("a")),a.href=t,t=s.default.parse(a.href);var r=!t.port&&""===e.port||t.port===e.port;return t.hostname===e.hostname&&r&&t.protocol===e.protocol?"":"anonymous"}r.__esModule=!0,r.default=i;var o=t("url"),s=n(o),a=void 0},{url:28}],120:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(){return++A}function s(t,e){return e=e||[],e[0]=(t>>16&255)/255,e[1]=(t>>8&255)/255,e[2]=(255&t)/255,e}function a(t){return t=t.toString(16),t="000000".substr(0,6-t.length)+t,"#"+t}function u(t){return(255*t[0]<<16)+(255*t[1]<<8)+(255*t[2]|0)}function l(t,e){var r=T.default.RETINA_PREFIX.exec(t);return r?parseFloat(r[1]):void 0!==e?e:1}function h(t){var e=b.DATA_URI.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,encoding:e[3]?e[3].toLowerCase():void 0,data:e[4]}}function c(t){var e=b.URL_FILE_EXTENSION.exec(t);if(e)return e[1].toLowerCase()}function f(t){var e=b.SVG_SIZE.exec(t),r={};return e&&(r[e[1]]=Math.round(parseFloat(e[3])),r[e[5]]=Math.round(parseFloat(e[7]))),r}function d(){I=!0}function p(t){if(!I){if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var e=["\n %c %c %c Pixi.js "+b.VERSION+" - ✰ "+t+" ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n","background: #ff66a5; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff66a5; background: #030307; padding:5px 0;","background: #ff66a5; padding:5px 0;","background: #ffc3dc; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;"];window.console.log.apply(console,e)}else window.console&&window.console.log("Pixi.js "+b.VERSION+" - "+t+" - http://www.pixijs.com/");I=!0}}function v(){var t={stencil:!0,failIfMajorPerformanceCaveat:!0};try{if(!window.WebGLRenderingContext)return!1;var e=document.createElement("canvas"),r=e.getContext("webgl",t)||e.getContext("experimental-webgl",t),n=!(!r||!r.getContextAttributes().stencil);if(r){var i=r.getExtension("WEBGL_lose_context");i&&i.loseContext()}return r=null,n}catch(t){return!1}}function y(t){return 0===t?0:t<0?-1:1}function g(t,e,r){var n=t.length;if(!(e>=n||0===r)){r=e+r>n?n-e:r;for(var i=n-r,o=e;o1?this._fontStyle="italic":t.indexOf("oblique")>-1?this._fontStyle="oblique":this._fontStyle="normal",t.indexOf("small-caps")>-1?this._fontVariant="small-caps":this._fontVariant="normal";var e=t.split(" "),r=-1;this._fontSize=26;for(var n=0;n-1&&r=this._durations[this.currentFrame];)n-=this._durations[this.currentFrame]*i,this._currentTime+=i;this._currentTime+=n/this._durations[this.currentFrame]}else this._currentTime+=e;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):r!==this.currentFrame&&this.updateTexture()},e.prototype.updateTexture=function(){this._texture=this._textures[this.currentFrame],this._textureID=-1,this.onFrameChange&&this.onFrameChange(this.currentFrame)},e.prototype.destroy=function(){this.stop(),t.prototype.destroy.call(this)},e.fromFrames=function(t){for(var r=[],n=0;n1&&void 0!==arguments[1]?arguments[1]:{};o(this,e);var i=s(this,t.call(this));return i._textWidth=0,i._textHeight=0,i._glyphs=[],i._font={tint:void 0!==n.tint?n.tint:16777215,align:n.align||"left",name:null,size:0},i.font=n.font,i._text=r,i.maxWidth=0,i.maxLineHeight=0,i._anchor=new f.default(function(){i.dirty=!0},i,0,0),i.dirty=!1,i.updateText(),i}return a(e,t),e.prototype.updateText=function(){for(var t=e.fonts[this._font.name],r=this._font.size/t.size,n=new h.Point,i=[],o=[],s=null,a=0,u=0,l=0,c=-1,f=0,d=0,p=0;p0&&n.x*r>this.maxWidth)h.utils.removeItems(i,c,p-c),p=c,c=-1,o.push(f),u=Math.max(u,f),l++,n.x=0,n.y+=t.lineHeight,s=null;else{var y=t.chars[v];y&&(s&&y.kerning[s]&&(n.x+=y.kerning[s]),i.push({texture:y.texture,line:l,charCode:v,position:new h.Point(n.x+y.xOffset,n.y+y.yOffset)}),a=n.x+(y.texture.width+y.xOffset),n.x+=y.xAdvance,d=Math.max(d,y.yOffset+y.texture.height),s=v)}}o.push(a),u=Math.max(u,a);for(var g=[],m=0;m<=l;m++){var _=0;"right"===this._font.align?_=u-o[m]:"center"===this._font.align&&(_=(u-o[m])/2),g.push(_)}for(var b=i.length,x=this.tint,T=0;T=0?t:16777215,this.dirty=!0}},{key:"align",get:function(){return this._font.align},set:function(t){this._font.align=t||"left",this.dirty=!0}},{key:"anchor",get:function(){return this._anchor},set:function(t){"number"==typeof t?this._anchor.set(t):this._anchor.copy(t)}},{key:"font",get:function(){return this._font},set:function(t){t&&("string"==typeof t?(t=t.split(" "),this._font.name=1===t.length?t[0]:t.slice(1).join(" "),this._font.size=t.length>=2?parseInt(t[0],10):e.fonts[this._font.name].size):(this._font.name=t.name,this._font.size="number"==typeof t.size?t.size:parseInt(t.size,10)),this.dirty=!0)}},{key:"text",get:function(){return this._text},set:function(t){t=t.toString()||" ",this._text!==t&&(this._text=t,this.dirty=!0)}},{key:"textWidth",get:function(){return this.validate(),this._textWidth}},{key:"textHeight",get:function(){return this.validate(),this._textHeight}}]),e}(h.Container);r.default=d,d.fonts={}},{"../core":63,"../core/math/ObservablePoint":66}],131:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:100,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:100;o(this,e);var a=s(this,t.call(this,r));return a.tileTransform=new h.TransformStatic,a._width=n,a._height=i,a._canvasPattern=null,a.uvTransform=r.transform||new p.default(r),a.pluginName="tilingSprite",a.uvRespectAnchor=!1,a}return a(e,t),e.prototype._onTextureUpdate=function(){this.uvTransform&&(this.uvTransform.texture=this._texture)},e.prototype._renderWebGL=function(t){var e=this._texture;e&&e.valid&&(this.tileTransform.updateLocalTransform(),this.uvTransform.update(),t.setObjectRenderer(t.plugins[this.pluginName]),t.plugins[this.pluginName].render(this))},e.prototype._renderCanvas=function(t){var e=this._texture;if(e.baseTexture.hasLoaded){var r=t.context,n=this.worldTransform,i=t.resolution,o=e.baseTexture,s=e.baseTexture.resolution,a=this.tilePosition.x/this.tileScale.x%e._frame.width,u=this.tilePosition.y/this.tileScale.y%e._frame.height;if(!this._canvasPattern){var l=new h.CanvasRenderTarget(e._frame.width,e._frame.height,s);16777215!==this.tint?(this.cachedTint!==this.tint&&(this.cachedTint=this.tint,this.tintedTexture=f.default.getTintedTexture(this,this.tint)),l.context.drawImage(this.tintedTexture,0,0)):l.context.drawImage(o.source,-e._frame.x,-e._frame.y),this._canvasPattern=l.context.createPattern(l.canvas,"repeat")}r.globalAlpha=this.worldAlpha,r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t.setBlendMode(this.blendMode),r.fillStyle=this._canvasPattern,r.scale(this.tileScale.x/s,this.tileScale.y/s);var c=this.anchor.x*-this._width,d=this.anchor.y*-this._height;this.uvRespectAnchor?(r.translate(a,u),r.fillRect(-a+c,-u+d,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s)):(r.translate(a+c,u+d),r.fillRect(-a,-u,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s))}},e.prototype._calculateBounds=function(){var t=this._width*-this._anchor._x,e=this._height*-this._anchor._y,r=this._width*(1-this._anchor._x),n=this._height*(1-this._anchor._y);this._bounds.addFrame(this.transform,t,e,r,n)},e.prototype.getLocalBounds=function(e){return 0===this.children.length?(this._bounds.minX=this._width*-this._anchor._x,this._bounds.minY=this._height*-this._anchor._y,this._bounds.maxX=this._width*(1-this._anchor._x),this._bounds.maxY=this._height*(1-this._anchor._x),e||(this._localBoundsRect||(this._localBoundsRect=new h.Rectangle),e=this._localBoundsRect),this._bounds.getRectangle(e)):t.prototype.getLocalBounds.call(this,e)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,v);var e=this._width,r=this._height,n=-e*this.anchor._x;if(v.x>n&&v.xi&&v.y0&&void 0!==arguments[0]?arguments[0]:new o.Point,e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.parent?this.parent.toGlobal(this.position,t,e):(t.x=this.position.x,t.y=this.position.y),t}},{"../core":63}],136:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.BitmapText=r.TilingSpriteRenderer=r.TilingSprite=r.AnimatedSprite=r.TextureTransform=void 0;var i=t("./TextureTransform");Object.defineProperty(r,"TextureTransform",{enumerable:!0,get:function(){return n(i).default}});var o=t("./AnimatedSprite");Object.defineProperty(r,"AnimatedSprite",{enumerable:!0,get:function(){return n(o).default}});var s=t("./TilingSprite");Object.defineProperty(r,"TilingSprite",{enumerable:!0,get:function(){return n(s).default}});var a=t("./webgl/TilingSpriteRenderer");Object.defineProperty(r,"TilingSpriteRenderer",{enumerable:!0,get:function(){return n(a).default}});var u=t("./BitmapText");Object.defineProperty(r,"BitmapText",{enumerable:!0,get:function(){return n(u).default}}),t("./cacheAsBitmap"),t("./getChildByName"),t("./getGlobalPosition")},{"./AnimatedSprite":129,"./BitmapText":130,"./TextureTransform":131,"./TilingSprite":132,"./cacheAsBitmap":133,"./getChildByName":134,"./getGlobalPosition":135,"./webgl/TilingSpriteRenderer":137}],137:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../core"),u=n(a),l=t("../../core/const"),h=(t("path"),new u.Matrix),c=new Float32Array(4),f=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.shader=null,n.simpleShader=null,n.quad=null,n}return s(e,t),e.prototype.onContextChange=function(){var t=this.renderer.gl;this.shader=new u.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n gl_FragColor = sample * color ;\n}\n"),this.simpleShader=new u.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n gl_FragColor = sample * color;\n}\n"),this.renderer.bindVao(null),this.quad=new u.Quad(t,this.renderer.state.attribState),this.quad.initVao(this.shader)},e.prototype.render=function(t){var e=this.renderer,r=this.quad;e.bindVao(r.vao);var n=r.vertices;n[0]=n[6]=t._width*-t.anchor.x,n[1]=n[3]=t._height*-t.anchor.y,n[2]=n[4]=t._width*(1-t.anchor.x),n[5]=n[7]=t._height*(1-t.anchor.y),t.uvRespectAnchor&&(n=r.uvs,n[0]=n[6]=-t.anchor.x,n[1]=n[3]=-t.anchor.y,n[2]=n[4]=1-t.anchor.x,n[5]=n[7]=1-t.anchor.y),r.upload();var i=t._texture,o=i.baseTexture,s=t.tileTransform.localTransform,a=t.uvTransform,f=o.isPowerOfTwo&&i.frame.width===o.width&&i.frame.height===o.height;f&&(o._glTextures[e.CONTEXT_UID]?f=o.wrapMode!==l.WRAP_MODES.CLAMP:o.wrapMode===l.WRAP_MODES.CLAMP&&(o.wrapMode=l.WRAP_MODES.REPEAT));var d=f?this.simpleShader:this.shader;e.bindShader(d);var p=i.width,v=i.height,y=t._width,g=t._height;h.set(s.a*p/y,s.b*p/g,s.c*v/y,s.d*v/g,s.tx/y,s.ty/g),h.invert(),f?h.append(a.mapCoord):(d.uniforms.uMapCoord=a.mapCoord.toArray(!0),d.uniforms.uClampFrame=a.uClampFrame,d.uniforms.uClampOffset=a.uClampOffset),d.uniforms.uTransform=h.toArray(!0);var m=c;u.utils.hex2rgb(t.tint,m),m[3]=t.worldAlpha,d.uniforms.uColor=m,d.uniforms.translationMatrix=t.transform.worldTransform.toArray(!0),d.uniforms.uSampler=e.bindTexture(i),e.setBlendMode(t.blendMode),r.vao.draw(this.renderer.gl.TRIANGLES,6,0)},e}(u.ObjectRenderer);r.default=f,u.WebGLRenderer.registerPlugin("tilingSprite",f)},{"../../core":63,"../../core/const":44,path:22}],138:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var u=function(){function t(t,e){for(var r=0;r=r&&(u=t-l-1),h=h.replace("%value%",e[u]),s+=h,s+="\n"}return n=n.replace("%blur%",s),n=n.replace("%size%",t)}r.__esModule=!0,r.default=n;var i={5:[.153388,.221461,.250301],7:[.071303,.131514,.189879,.214607],9:[.028532,.067234,.124009,.179044,.20236],11:[.0093,.028002,.065984,.121703,.175713,.198596],13:[.002406,.009255,.027867,.065666,.121117,.174868,.197641],15:[489e-6,.002403,.009246,.02784,.065602,.120999,.174697,.197448]},o=["varying vec2 vBlurTexCoords[%size%];","uniform sampler2D uSampler;","void main(void)","{"," gl_FragColor = vec4(0.0);"," %blur%","}"].join("\n")},{}],142:[function(t,e,r){"use strict";function n(t,e){var r=Math.ceil(t/2),n=i,o="",s=void 0;s=e?"vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);":"vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);";for(var a=0;ae;)r-=2;return r}r.__esModule=!0,r.default=n},{}],144:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r 0.0) {\n c.rgb /= c.a;\n }\n vec4 result;\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n // Premultiply alpha again.\n result.rgb *= result.a;\n\n gl_FragColor = result;\n}\n")); +return r.uniforms.m=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],r}return s(e,t),e.prototype._loadMatrix=function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t;e&&(this._multiply(r,this.uniforms.m,t),r=this._colorMatrix(r)),this.uniforms.m=r},e.prototype._multiply=function(t,e,r){return t[0]=e[0]*r[0]+e[1]*r[5]+e[2]*r[10]+e[3]*r[15],t[1]=e[0]*r[1]+e[1]*r[6]+e[2]*r[11]+e[3]*r[16],t[2]=e[0]*r[2]+e[1]*r[7]+e[2]*r[12]+e[3]*r[17],t[3]=e[0]*r[3]+e[1]*r[8]+e[2]*r[13]+e[3]*r[18],t[4]=e[0]*r[4]+e[1]*r[9]+e[2]*r[14]+e[3]*r[19]+e[4],t[5]=e[5]*r[0]+e[6]*r[5]+e[7]*r[10]+e[8]*r[15],t[6]=e[5]*r[1]+e[6]*r[6]+e[7]*r[11]+e[8]*r[16],t[7]=e[5]*r[2]+e[6]*r[7]+e[7]*r[12]+e[8]*r[17],t[8]=e[5]*r[3]+e[6]*r[8]+e[7]*r[13]+e[8]*r[18],t[9]=e[5]*r[4]+e[6]*r[9]+e[7]*r[14]+e[8]*r[19]+e[9],t[10]=e[10]*r[0]+e[11]*r[5]+e[12]*r[10]+e[13]*r[15],t[11]=e[10]*r[1]+e[11]*r[6]+e[12]*r[11]+e[13]*r[16],t[12]=e[10]*r[2]+e[11]*r[7]+e[12]*r[12]+e[13]*r[17],t[13]=e[10]*r[3]+e[11]*r[8]+e[12]*r[13]+e[13]*r[18],t[14]=e[10]*r[4]+e[11]*r[9]+e[12]*r[14]+e[13]*r[19]+e[14],t[15]=e[15]*r[0]+e[16]*r[5]+e[17]*r[10]+e[18]*r[15],t[16]=e[15]*r[1]+e[16]*r[6]+e[17]*r[11]+e[18]*r[16],t[17]=e[15]*r[2]+e[16]*r[7]+e[17]*r[12]+e[18]*r[17],t[18]=e[15]*r[3]+e[16]*r[8]+e[17]*r[13]+e[18]*r[18],t[19]=e[15]*r[4]+e[16]*r[9]+e[17]*r[14]+e[18]*r[19]+e[19],t},e.prototype._colorMatrix=function(t){var e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e},e.prototype.brightness=function(t,e){var r=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.greyscale=function(t,e){var r=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.blackAndWhite=function(t){var e=[.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.hue=function(t,e){t=(t||0)/180*Math.PI;var r=Math.cos(t),n=Math.sin(t),i=Math.sqrt,o=1/3,s=i(o),a=r+(1-r)*o,u=o*(1-r)-s*n,l=o*(1-r)+s*n,h=o*(1-r)+s*n,c=r+o*(1-r),f=o*(1-r)-s*n,d=o*(1-r)-s*n,p=o*(1-r)+s*n,v=r+o*(1-r),y=[a,u,l,0,0,h,c,f,0,0,d,p,v,0,0,0,0,0,1,0];this._loadMatrix(y,e)},e.prototype.contrast=function(t,e){var r=(t||0)+1,n=-128*(r-1),i=[r,0,0,0,n,0,r,0,0,n,0,0,r,0,n,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.saturate=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=2*t/3+1,n=(r-1)*-.5,i=[r,n,n,0,0,n,r,n,0,0,n,n,r,0,0,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.desaturate=function(){this.saturate(-1)},e.prototype.negative=function(t){var e=[0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.sepia=function(t){var e=[.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.technicolor=function(t){var e=[1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.polaroid=function(t){var e=[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.toBGR=function(t){var e=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.kodachrome=function(t){var e=[1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.browni=function(t){var e=[.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.vintage=function(t){var e=[.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.colorTone=function(t,e,r,n,i){t=t||.2,e=e||.15,r=r||16770432,n=n||3375104;var o=(r>>16&255)/255,s=(r>>8&255)/255,a=(255&r)/255,u=(n>>16&255)/255,l=(n>>8&255)/255,h=(255&n)/255,c=[.3,.59,.11,0,0,o,s,a,t,0,u,l,h,e,0,o-u,s-l,a-h,0,0];this._loadMatrix(c,i)},e.prototype.night=function(t,e){t=t||.1;var r=[t*-2,-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.predator=function(t,e){var r=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.lsd=function(t){var e=[2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.reset=function(){var t=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(t,!1)},a(e,[{key:"matrix",get:function(){return this.uniforms.m},set:function(t){this.uniforms.m=t}}]),e}(l.Filter));r.default=h,h.prototype.grayscale=h.prototype.greyscale},{"../../core":63,path:22}],145:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n'))}return s(e,t),e}(u.Filter));r.default=l},{"../../core":63,path:22}],147:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./fxaa/FXAAFilter");Object.defineProperty(r,"FXAAFilter",{enumerable:!0,get:function(){return n(i).default}});var o=t("./noise/NoiseFilter");Object.defineProperty(r,"NoiseFilter",{enumerable:!0,get:function(){return n(o).default}});var s=t("./displacement/DisplacementFilter");Object.defineProperty(r,"DisplacementFilter",{enumerable:!0,get:function(){return n(s).default}});var a=t("./blur/BlurFilter");Object.defineProperty(r,"BlurFilter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./blur/BlurXFilter");Object.defineProperty(r,"BlurXFilter",{enumerable:!0,get:function(){return n(u).default}});var l=t("./blur/BlurYFilter");Object.defineProperty(r,"BlurYFilter",{enumerable:!0,get:function(){return n(l).default}});var h=t("./colormatrix/ColorMatrixFilter");Object.defineProperty(r,"ColorMatrixFilter",{enumerable:!0,get:function(){return n(h).default}});var c=t("./void/VoidFilter");Object.defineProperty(r,"VoidFilter",{enumerable:!0,get:function(){return n(c).default}})},{"./blur/BlurFilter":138,"./blur/BlurXFilter":139,"./blur/BlurYFilter":140,"./colormatrix/ColorMatrixFilter":144,"./displacement/DisplacementFilter":145,"./fxaa/FXAAFilter":146,"./noise/NoiseFilter":148,"./void/VoidFilter":149}],148:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:1;this.removeEvents(),this.interactionDOMElement=t,this.resolution=e,this.addEvents()},e.prototype.addEvents=function(){this.interactionDOMElement&&(h.ticker.shared.add(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="none",this.interactionDOMElement.style["-ms-touch-action"]="none"):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]="none"),this.supportsPointerEvents?(window.document.addEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("pointerover",this.onPointerOver,!0),window.addEventListener("pointercancel",this.onPointerCancel,!0),window.addEventListener("pointerup",this.onPointerUp,!0)):(window.document.addEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onPointerOver,!0),window.addEventListener("mouseup",this.onPointerUp,!0),this.supportsTouchEvents&&(this.interactionDOMElement.addEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.addEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.addEventListener("touchmove",this.onPointerMove,!0))),this.eventsAdded=!0)},e.prototype.removeEvents=function(){this.interactionDOMElement&&(h.ticker.shared.remove(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="",this.interactionDOMElement.style["-ms-touch-action"]=""):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]=""),this.supportsPointerEvents?(window.document.removeEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("pointerover",this.onPointerOver,!0),window.removeEventListener("pointercancel",this.onPointerCancel,!0),window.removeEventListener("pointerup",this.onPointerUp,!0)):(window.document.removeEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onPointerOver,!0),window.removeEventListener("mouseup",this.onPointerUp,!0),this.supportsTouchEvents&&(this.interactionDOMElement.removeEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.removeEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onPointerMove,!0))),this.interactionDOMElement=null,this.eventsAdded=!1)},e.prototype.update=function(t){if(this._deltaTime+=t,!(this._deltaTime=0;l--){var h=u[l],c=this.processInteractive(t,h,r,n,a);if(c){if(!h.parent)continue;a=!1,c===E?(n=!1,s=E):s===T&&(s=w)}}return i&&(n&&s!==E&&(e.hitArea?(e.worldTransform.applyInverse(o,this._tempPoint),e.hitArea.contains(this._tempPoint.x,this._tempPoint.y)&&(s=e.interactive?E:w)):e.containsPoint&&e.containsPoint(o)&&(s=e.interactive?E:w)),e.interactive&&(s&&!t.target&&(t.target=e),r(t,e,!!s))),s},e.prototype.onPointerDown=function(t){var e=this.normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&t.preventDefault();for(var r=e.length,n=0;n1&&(h=1);var c=Math.sqrt(n*n+i*i),f=this._texture.height/2;n/=c,i/=c,n*=f,i*=f,o[l]=u.x+n,o[l+1]=u.y+i,o[l+2]=u.x-n,o[l+3]=u.y-i,e=u}this.containerUpdateTransform()}},e}(l.default);r.default=f},{"../core":63,"./Mesh":161}],165:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var s=t("../../core"),a=i(s),u=t("../Mesh"),l=n(u),h=function(){function t(e){o(this,t),this.renderer=e}return t.prototype.render=function(t){var e=this.renderer,r=e.context,n=t.worldTransform,i=e.resolution;e.roundPixels?r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i|0,n.ty*i|0):r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),e.setBlendMode(t.blendMode),t.drawMode===l.default.DRAW_MODES.TRIANGLE_MESH?this._renderTriangleMesh(t):this._renderTriangles(t)},t.prototype._renderTriangleMesh=function(t){for(var e=t.vertices.length/2,r=0;r0){var E=t.canvasPadding/t.worldTransform.a,S=t.canvasPadding/t.worldTransform.d,O=(m+_+b)/3,P=(x+T+w)/3,M=m-O,C=x-P,R=Math.sqrt(M*M+C*C);m=O+M/R*(R+E),x=P+C/R*(R+S),M=_-O,C=T-P,R=Math.sqrt(M*M+C*C),_=O+M/R*(R+E),T=P+C/R*(R+S),M=b-O,C=w-P,R=Math.sqrt(M*M+C*C),b=O+M/R*(R+E),w=P+C/R*(R+S)}i.save(),i.beginPath(),i.moveTo(m,x),i.lineTo(_,T),i.lineTo(b,w),i.closePath(),i.clip();var A=f*y+v*p+d*g-y*p-v*d-f*g,I=m*y+v*b+_*g-y*b-v*_-m*g,D=f*_+m*p+d*b-_*p-m*d-f*b,L=f*y*b+v*_*p+m*d*g-m*y*p-v*d*b-f*_*g,N=x*y+v*w+T*g-y*w-v*T-x*g,F=f*T+x*p+d*w-T*p-x*d-f*w,j=f*y*w+v*T*p+x*d*g-x*y*p-v*d*w-f*T*g;i.transform(I/A,N/A,D/A,F/A,L/A,j/A),i.drawImage(l,0,0,h*u.resolution,c*u.resolution,0,0,h,c),i.restore()}},t.prototype.renderMeshFlat=function(t){var e=this.renderer.context,r=t.vertices,n=r.length/2;e.beginPath();for(var i=1;i0&&void 0!==arguments[0]?arguments[0]:1500,n=arguments[1],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16384;i(this,e);var a=o(this,t.call(this)),l=16384;return s>l&&(s=l),s>r&&(s=r),a._properties=[!1,!0,!1,!1,!1],a._maxSize=r,a._batchSize=s,a._glBuffers={},a._bufferToUpdate=0,a.interactiveChildren=!1,a.blendMode=u.BLEND_MODES.NORMAL,a.roundPixels=!0,a.baseTexture=null,a.setProperties(n),a}return s(e,t),e.prototype.setProperties=function(t){t&&(this._properties[0]="scale"in t?!!t.scale:this._properties[0],this._properties[1]="position"in t?!!t.position:this._properties[1],this._properties[2]="rotation"in t?!!t.rotation:this._properties[2],this._properties[3]="uvs"in t?!!t.uvs:this._properties[3],this._properties[4]="alpha"in t?!!t.alpha:this._properties[4])},e.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},e.prototype.renderWebGL=function(t){var e=this;this.visible&&!(this.worldAlpha<=0)&&this.children.length&&this.renderable&&(this.baseTexture||(this.baseTexture=this.children[0]._texture.baseTexture,this.baseTexture.hasLoaded||this.baseTexture.once("update",function(){return e.onChildrenChange(0)})),t.setObjectRenderer(t.plugins.particle),t.plugins.particle.render(this))},e.prototype.onChildrenChange=function(t){var e=Math.floor(t/this._batchSize);er&&(o=r);var s=t._glBuffers[i.CONTEXT_UID];s||(s=t._glBuffers[i.CONTEXT_UID]=this.generateBuffers(t)),this.renderer.setBlendMode(t.blendMode);var a=i.gl,u=t.worldTransform.copy(this.tempMatrix);u.prepend(i._activeRenderTarget.projectionMatrix),this.shader.uniforms.projectionMatrix=u.toArray(!0),this.shader.uniforms.uAlpha=t.worldAlpha;var l=e[0]._texture.baseTexture;this.shader.uniforms.uSampler=i.bindTexture(l);for(var h=0,c=0;hn&&(f=n);var d=s[c];d.uploadDynamic(e,h,f),t._bufferToUpdate===c&&(d.uploadStatic(e,h,f),t._bufferToUpdate=c+1),i.bindVao(d.vao),d.vao.draw(a.TRIANGLES,6*f)}}},e.prototype.generateBuffers=function(t){for(var e=this.renderer.gl,r=[],n=t._maxSize,i=t._batchSize,o=t._properties,s=0;s0?1:-1})},{}],174:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}var i=t("object-assign"),o=n(i);Object.assign||(Object.assign=o.default)},{"object-assign":5}],175:[function(t,e,r){"use strict";t("./Object.assign"),t("./requestAnimationFrame"),t("./Math.sign"),window.ArrayBuffer||(window.ArrayBuffer=Array),window.Float32Array||(window.Float32Array=Array),window.Uint32Array||(window.Uint32Array=Array),window.Uint16Array||(window.Uint16Array=Array)},{"./Math.sign":173,"./Object.assign":174,"./requestAnimationFrame":176}],176:[function(t,e,r){(function(t){"use strict";var e=16;Date.now&&Date.prototype.getTime||(Date.now=function(){return(new Date).getTime()}),t.performance&&t.performance.now||!function(){var e=Date.now();t.performance||(t.performance={}),t.performance.now=function(){return Date.now()-e}}();for(var r=Date.now(),n=["ms","moz","webkit","o"],i=0;i=0;n--)this.add(t.children[n]);return this},t.prototype.destroy=function(){this.ticking&&p.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null,this.limiter=null,this.uploadHookHelper=null},t}();r.default=v},{"../core":63,"./limiters/CountLimiter":180}],178:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function u(t,e){if(e instanceof c.BaseTexture){var r=e.source,n=0===r.width?t.canvas.width:Math.min(t.canvas.width,r.width),i=0===r.height?t.canvas.height:Math.min(t.canvas.height,r.height);return t.ctx.drawImage(r,0,0,n,i,0,0,t.canvas.width,t.canvas.height),!0}return!1}function l(t,e){if(t instanceof c.BaseTexture)return e.indexOf(t)===-1&&e.push(t),!0;if(t._texture&&t._texture instanceof c.Texture){var r=t._texture.baseTexture;return e.indexOf(r)===-1&&e.push(r),!0}return!1}r.__esModule=!0;var h=t("../../core"),c=i(h),f=t("../BasePrepare"),d=n(f),p=16,v=function(t){function e(r){o(this,e);var n=s(this,t.call(this,r));return n.uploadHookHelper=n,n.canvas=document.createElement("canvas"),n.canvas.width=p,n.canvas.height=p,n.ctx=n.canvas.getContext("2d"),n.register(l,u),n}return a(e,t),e.prototype.destroy=function(){t.prototype.destroy.call(this),this.ctx=null,this.canvas=null},e}(d.default);r.default=v,c.CanvasRenderer.registerPlugin("prepare",v)},{"../../core":63,"../BasePrepare":177}],179:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./webgl/WebGLPrepare");Object.defineProperty(r,"webgl",{enumerable:!0,get:function(){return n(i).default}});var o=t("./canvas/CanvasPrepare");Object.defineProperty(r,"canvas",{enumerable:!0,get:function(){return n(o).default}});var s=t("./BasePrepare");Object.defineProperty(r,"BasePrepare",{enumerable:!0,get:function(){return n(s).default}});var a=t("./limiters/CountLimiter");Object.defineProperty(r,"CountLimiter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./limiters/TimeLimiter");Object.defineProperty(r,"TimeLimiter",{enumerable:!0,get:function(){return n(u).default}})},{"./BasePrepare":177,"./canvas/CanvasPrepare":178,"./limiters/CountLimiter":180,"./limiters/TimeLimiter":181,"./webgl/WebGLPrepare":182}],180:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxItemsPerFrame=e,this.itemsLeft=0}return t.prototype.beginFrame=function(){this.itemsLeft=this.maxItemsPerFrame},t.prototype.allowedToUpload=function(){return this.itemsLeft-- >0},t}();r.default=i},{}],181:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxMilliseconds=e,this.frameStart=0}return t.prototype.beginFrame=function(){this.frameStart=Date.now()},t.prototype.allowedToUpload=function(){return Date.now()-this.frameStart 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],2:[function(require,module,exports){ +'use strict'; + +module.exports = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, size), + maxZ = zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, size); + earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and size of the data bounding box +function zOrder(x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; + +},{}],3:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @api private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {Mixed} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @api public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @api public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Boolean} exists Only check if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Add a one-time listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Remove the listeners of a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {Mixed} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn + && (!once || listeners.once) + && (!context || listeners.context === context) + ) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {String|Symbol} [event] The event name. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],4:[function(require,module,exports){ +/** + * isMobile.js v0.4.0 + * + * A simple library to detect Apple phones and tablets, + * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone), + * and any kind of seven inch device, via user agent sniffing. + * + * @author: Kai Mallea (kmallea@gmail.com) + * + * @license: http://creativecommons.org/publicdomain/zero/1.0/ + */ +(function (global) { + + var apple_phone = /iPhone/i, + apple_ipod = /iPod/i, + apple_tablet = /iPad/i, + android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i, // Match 'Android' AND 'Mobile' + android_tablet = /Android/i, + amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i, + amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i, + windows_phone = /IEMobile/i, + windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i, // Match 'Windows' AND 'ARM' + other_blackberry = /BlackBerry/i, + other_blackberry_10 = /BB10/i, + other_opera = /Opera Mini/i, + other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i, + other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i, // Match 'Firefox' AND 'Mobile' + seven_inch = new RegExp( + '(?:' + // Non-capturing group + + 'Nexus 7' + // Nexus 7 + + '|' + // OR + + 'BNTV250' + // B&N Nook Tablet 7 inch + + '|' + // OR + + 'Kindle Fire' + // Kindle Fire + + '|' + // OR + + 'Silk' + // Kindle Fire, Silk Accelerated + + '|' + // OR + + 'GT-P1000' + // Galaxy Tab 7 inch + + ')', // End non-capturing group + + 'i'); // Case-insensitive matching + + var match = function(regex, userAgent) { + return regex.test(userAgent); + }; + + var IsMobileClass = function(userAgent) { + var ua = userAgent || navigator.userAgent; + + // Facebook mobile app's integrated browser adds a bunch of strings that + // match everything. Strip it out if it exists. + var tmp = ua.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + // Twitter mobile app's integrated browser on iPad adds a "Twitter for + // iPhone" string. Same probable happens on other tablet platforms. + // This will confuse detection so strip it out if it exists. + tmp = ua.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + this.apple = { + phone: match(apple_phone, ua), + ipod: match(apple_ipod, ua), + tablet: !match(apple_phone, ua) && match(apple_tablet, ua), + device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua) + }; + this.amazon = { + phone: match(amazon_phone, ua), + tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) + }; + this.android = { + phone: match(amazon_phone, ua) || match(android_phone, ua), + tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua) + }; + this.windows = { + phone: match(windows_phone, ua), + tablet: match(windows_tablet, ua), + device: match(windows_phone, ua) || match(windows_tablet, ua) + }; + this.other = { + blackberry: match(other_blackberry, ua), + blackberry10: match(other_blackberry_10, ua), + opera: match(other_opera, ua), + firefox: match(other_firefox, ua), + chrome: match(other_chrome, ua), + device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua) + }; + this.seven_inch = match(seven_inch, ua); + this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch; + + // excludes 'other' devices and ipods, targeting touchscreen phones + this.phone = this.apple.phone || this.android.phone || this.windows.phone; + + // excludes 7 inch devices, classifying as phone or tablet is left to the user + this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet; + + if (typeof window === 'undefined') { + return this; + } + }; + + var instantiate = function() { + var IM = new IsMobileClass(); + IM.Class = IsMobileClass; + return IM; + }; + + if (typeof module !== 'undefined' && module.exports && typeof window === 'undefined') { + //node + module.exports = IsMobileClass; + } else if (typeof module !== 'undefined' && module.exports && typeof window !== 'undefined') { + //browserify + module.exports = instantiate(); + } else if (typeof define === 'function' && define.amd) { + //AMD + define('isMobile', [], global.isMobile = instantiate()); + } else { + global.isMobile = instantiate(); + } + +})(this); + +},{}],5:[function(require,module,exports){ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],6:[function(require,module,exports){ +var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); + +/** + * Helper class to create a webGL buffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ +var Buffer = function(gl, type, data, drawType) +{ + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The WebGL buffer, created upon instantiation + * + * @member {WebGLBuffer} + */ + this.buffer = gl.createBuffer(); + + /** + * The type of the buffer + * + * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} + */ + this.type = type || gl.ARRAY_BUFFER; + + /** + * The draw type of the buffer + * + * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ + this.drawType = drawType || gl.STATIC_DRAW; + + /** + * The data in the buffer, as a typed array + * + * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} + */ + this.data = EMPTY_ARRAY_BUFFER; + + if(data) + { + this.upload(data); + } +}; + +/** + * Uploads the buffer to the GPU + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload + * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract + * @param dontBind {Boolean} whether to bind the buffer before uploading it + */ +Buffer.prototype.upload = function(data, offset, dontBind) +{ + // todo - needed? + if(!dontBind) this.bind(); + + var gl = this.gl; + + data = data || this.data; + offset = offset || 0; + + if(this.data.byteLength >= data.byteLength) + { + gl.bufferSubData(this.type, offset, data); + } + else + { + gl.bufferData(this.type, data, this.drawType); + } + + this.data = data; +}; +/** + * Binds the buffer + * + */ +Buffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindBuffer(this.type, this.buffer); +}; + +Buffer.createVertexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); +}; + +Buffer.createIndexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); +}; + +Buffer.create = function(gl, type, data, drawType) +{ + return new Buffer(gl, type, data, drawType); +}; + +/** + * Destroys the buffer + * + */ +Buffer.prototype.destroy = function(){ + this.gl.deleteBuffer(this.buffer); +}; + +module.exports = Buffer; + +},{}],7:[function(require,module,exports){ + +var Texture = require('./GLTexture'); + +/** + * Helper class to create a webGL Framebuffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + */ +var Framebuffer = function(gl, width, height) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The frame buffer + * + * @member {WebGLFramebuffer} + */ + this.framebuffer = gl.createFramebuffer(); + + /** + * The stencil buffer + * + * @member {WebGLRenderbuffer} + */ + this.stencil = null; + + /** + * The stencil buffer + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The width of the drawing area of the buffer + * + * @member {Number} + */ + this.width = width || 100; + /** + * The height of the drawing area of the buffer + * + * @member {Number} + */ + this.height = height || 100; +}; + +/** + * Adds a texture to the frame buffer + * @param texture {PIXI.glCore.GLTexture} + */ +Framebuffer.prototype.enableTexture = function(texture) +{ + var gl = this.gl; + + this.texture = texture || new Texture(gl); + + this.texture.bind(); + + //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + this.bind(); + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); +}; + +/** + * Initialises the stencil buffer + */ +Framebuffer.prototype.enableStencil = function() +{ + if(this.stencil)return; + + var gl = this.gl; + + this.stencil = gl.createRenderbuffer(); + + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + + // TODO.. this is depth AND stencil? + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width , this.height ); +}; + +/** + * Erases the drawing area and fills it with a colour + * @param r {Number} the red value of the clearing colour + * @param g {Number} the green value of the clearing colour + * @param b {Number} the blue value of the clearing colour + * @param a {Number} the alpha value of the clearing colour + */ +Framebuffer.prototype.clear = function( r, g, b, a ) +{ + this.bind(); + + var gl = this.gl; + + gl.clearColor(r, g, b, a); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Binds the frame buffer to the WebGL context + */ +Framebuffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); +}; + +/** + * Unbinds the frame buffer to the WebGL context + */ +Framebuffer.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, null ); +}; +/** + * Resizes the drawing area of the buffer to the given width and height + * @param width {Number} the new width + * @param height {Number} the new height + */ +Framebuffer.prototype.resize = function(width, height) +{ + var gl = this.gl; + + this.width = width; + this.height = height; + + if ( this.texture ) + { + this.texture.uploadData(null, width, height); + } + + if ( this.stencil ) + { + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + } +}; + +/** + * Destroys this buffer + */ +Framebuffer.prototype.destroy = function() +{ + var gl = this.gl; + + //TODO + if(this.texture) + { + this.texture.destroy(); + } + + gl.deleteFramebuffer(this.framebuffer); + + this.gl = null; + + this.stencil = null; + this.texture = null; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createRGBA = function(gl, width, height, data) +{ + var texture = Texture.fromData(gl, null, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createFloat32 = function(gl, width, height, data) +{ + // create a new texture.. + var texture = new Texture.fromData(gl, data, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +module.exports = Framebuffer; + +},{"./GLTexture":9}],8:[function(require,module,exports){ + +var compileProgram = require('./shader/compileProgram'), + extractAttributes = require('./shader/extractAttributes'), + extractUniforms = require('./shader/extractUniforms'), + generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + +/** + * Helper class to create a webGL Shader + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + */ +var Shader = function(gl, vertexSrc, fragmentSrc) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc); + + + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); + + var uniformData = extractUniforms(gl, this.program); + + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject( gl, uniformData ); +}; +/** + * Uses this shader + */ +Shader.prototype.bind = function() +{ + this.gl.useProgram(this.program); +}; + +/** + * Destroys this shader + * TODO + */ +Shader.prototype.destroy = function() +{ + // var gl = this.gl; +}; + +module.exports = Shader; + +},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18}],9:[function(require,module,exports){ + +/** + * Helper class to create a WebGL Texture + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL context + * @param width {number} the width of the texture + * @param height {number} the height of the texture + * @param format {number} the pixel format of the texture. defaults to gl.RGBA + * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE + */ +var Texture = function(gl, width, height, format, type) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); + + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; + + + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; + + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; + + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + + +}; + +/** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ +Texture.prototype.upload = function(source) +{ + this.bind(); + + var gl = this.gl; + + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + var newWidth = source.videoWidth || source.width; + var newHeight = source.videoHeight || source.height; + + if(newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } + + // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + +}; + +var FLOATING_POINT_AVAILABLE = false; + +/** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.prototype.uploadData = function(data, width, height) +{ + this.bind(); + + var gl = this.gl; + + + if(data instanceof Float32Array) + { + if(!FLOATING_POINT_AVAILABLE) + { + var ext = gl.getExtension("OES_texture_float"); + + if(ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } + + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = gl.UNSIGNED_BYTE; + } + + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + + if(width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } + + this.width = width; + this.height = height; + + +// texSubImage2D +}; + +/** + * Binds the texture + * @param location + */ +Texture.prototype.bind = function(location) +{ + var gl = this.gl; + + if(location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } + + gl.bindTexture(gl.TEXTURE_2D, this.texture); +}; + +/** + * Unbinds the texture + */ +Texture.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, null); +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.minFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + if(this.mipmap) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.magFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); +}; + +/** + * Enables mipmapping + */ +Texture.prototype.enableMipmap = function() +{ + var gl = this.gl; + + this.bind(); + + this.mipmap = true; + + gl.generateMipmap(gl.TEXTURE_2D); +}; + +/** + * Enables linear filtering + */ +Texture.prototype.enableLinearScaling = function() +{ + this.minFilter(true); + this.magFilter(true); +}; + +/** + * Enables nearest neighbour interpolation + */ +Texture.prototype.enableNearestScaling = function() +{ + this.minFilter(false); + this.magFilter(false); +}; + +/** + * Enables clamping on the texture so WebGL will not repeat it + */ +Texture.prototype.enableWrapClamp = function() +{ + var gl = this.gl; + + this.bind(); + + 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); +}; + +/** + * Enable tiling on the texture + */ +Texture.prototype.enableWrapRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); +}; + +Texture.prototype.enableWrapMirrorRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); +}; + + +/** + * Destroys this texture + */ +Texture.prototype.destroy = function() +{ + var gl = this.gl; + //TODO + gl.deleteTexture(this.texture); +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ +Texture.fromSource = function(gl, source, premultiplyAlpha) +{ + var texture = new Texture(gl); + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); + + return texture; +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.fromData = function(gl, data, width, height) +{ + //console.log(data, width, height); + var texture = new Texture(gl); + texture.uploadData(data, width, height); + + return texture; +}; + + +module.exports = Texture; + +},{}],10:[function(require,module,exports){ + +// state object// +var setVertexAttribArrays = require( './setVertexAttribArrays' ); + +/** + * Helper class to work with WebGL VertexArrayObjects (vaos) + * Only works if WebGL extensions are enabled (they usually are) + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function VertexArrayObject(gl, state) +{ + this.nativeVaoExtension = null; + + if(!VertexArrayObject.FORCE_NATIVE) + { + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + this.nativeState = state; + + if(this.nativeVaoExtension) + { + this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + + var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + // VAO - overwrite the state.. + this.nativeState = { + tempAttribState: new Array(maxAttribs), + attribState: new Array(maxAttribs) + }; + } + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of attributes + * + * @member {Array} + */ + this.attributes = []; + + /** + * @member {PIXI.glCore.GLBuffer} + */ + this.indexBuffer = null; + + /** + * A boolean flag + * + * @member {Boolean} + */ + this.dirty = false; +} + +VertexArrayObject.prototype.constructor = VertexArrayObject; +module.exports = VertexArrayObject; + +/** +* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) +* If you find on older devices that things have gone a bit weird then set this to true. +*/ +/** + * Lets the VAO know if you should use the WebGL extension or the native methods. + * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) + * If you find on older devices that things have gone a bit weird then set this to true. + * @static + * @property {Boolean} FORCE_NATIVE + */ +VertexArrayObject.FORCE_NATIVE = false; + +/** + * Binds the buffer + */ +VertexArrayObject.prototype.bind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + + if(this.dirty) + { + this.dirty = false; + this.activate(); + } + } + else + { + + this.activate(); + } + + return this; +}; + +/** + * Unbinds the buffer + */ +VertexArrayObject.prototype.unbind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + return this; +}; + +/** + * Uses this vao + */ +VertexArrayObject.prototype.activate = function() +{ + + var gl = this.gl; + var lastBuffer = null; + + for (var i = 0; i < this.attributes.length; i++) + { + var attrib = this.attributes[i]; + + if(lastBuffer !== attrib.buffer) + { + attrib.buffer.bind(); + lastBuffer = attrib.buffer; + } + + //attrib.attribute.pointer(attrib.type, attrib.normalized, attrib.stride, attrib.start); + gl.vertexAttribPointer(attrib.attribute.location, + attrib.attribute.size, attrib.type || gl.FLOAT, + attrib.normalized || false, + attrib.stride || 0, + attrib.start || 0); + + + } + + setVertexAttribArrays(gl, this.attributes, this.nativeState); + + this.indexBuffer.bind(); + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + * @param attribute {*} + * @param type {String} + * @param normalized {Boolean} + * @param stride {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start) +{ + this.attributes.push({ + buffer: buffer, + attribute: attribute, + + location: attribute.location, + type: type || this.gl.FLOAT, + normalized: normalized || false, + stride: stride || 0, + start: start || 0 + }); + + this.dirty = true; + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + */ +VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) +{ + this.indexBuffer = buffer; + + this.dirty = true; + + return this; +}; + +/** + * Unbinds this vao and disables it + */ +VertexArrayObject.prototype.clear = function() +{ + // var gl = this.gl; + + // TODO - should this function unbind after clear? + // for now, no but lets see what happens in the real world! + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + } + + this.attributes.length = 0; + this.indexBuffer = null; + + return this; +}; + +/** + * @param type {Number} + * @param size {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.draw = function(type, size, start) +{ + var gl = this.gl; + gl.drawElements(type, size, gl.UNSIGNED_SHORT, start || 0); + + return this; +}; + +/** + * Destroy this vao + */ +VertexArrayObject.prototype.destroy = function() +{ + // lose references + this.gl = null; + this.indexBuffer = null; + this.attributes = null; + this.nativeState = null; + + if(this.nativeVao) + { + this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); + } + + this.nativeVaoExtension = null; + this.nativeVao = null; +}; + +},{"./setVertexAttribArrays":13}],11:[function(require,module,exports){ + +/** + * Helper class to create a webGL Context + * + * @class + * @memberof PIXI.glCore + * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from + * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * @return {WebGLRenderingContext} the WebGL context + */ +var createContext = function(canvas, options) +{ + var gl = canvas.getContext('webgl', options) || + canvas.getContext('experimental-webgl', options); + + if (!gl) + { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + return gl; +}; + +module.exports = createContext; + +},{}],12:[function(require,module,exports){ +var gl = { + createContext: require('./createContext'), + setVertexAttribArrays: require('./setVertexAttribArrays'), + GLBuffer: require('./GLBuffer'), + GLFramebuffer: require('./GLFramebuffer'), + GLShader: require('./GLShader'), + GLTexture: require('./GLTexture'), + VertexArrayObject: require('./VertexArrayObject'), + shader: require('./shader') +}; + +// Export for Node-compatible environments +if (typeof module !== 'undefined' && module.exports) +{ + // Export the module + module.exports = gl; +} + +// Add to the browser window pixi.gl +if (typeof window !== 'undefined') +{ + // add the window object + window.PIXI = window.PIXI || {}; + window.PIXI.glCore = gl; +} + +},{"./GLBuffer":6,"./GLFramebuffer":7,"./GLShader":8,"./GLTexture":9,"./VertexArrayObject":10,"./createContext":11,"./setVertexAttribArrays":13,"./shader":19}],13:[function(require,module,exports){ +// var GL_MAP = {}; + +/** + * @param gl {WebGLRenderingContext} The current WebGL context + * @param attribs {*} + * @param state {*} + */ +var setVertexAttribArrays = function (gl, attribs, state) +{ + var i; + if(state) + { + var tempAttribState = state.tempAttribState, + attribState = state.attribState; + + for (i = 0; i < tempAttribState.length; i++) + { + tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + tempAttribState[attribs[i].attribute.location] = true; + } + + for (i = 0; i < attribState.length; i++) + { + if (attribState[i] !== tempAttribState[i]) + { + attribState[i] = tempAttribState[i]; + + if (state.attribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } + + } + else + { + for (i = 0; i < attribs.length; i++) + { + var attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); + } + } +}; + +module.exports = setVertexAttribArrays; + +},{}],14:[function(require,module,exports){ + +/** + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @return {WebGLProgram} the shader program + */ +var compileProgram = function(gl, vertexSrc, fragmentSrc) +{ + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + + var program = gl.createProgram(); + + gl.attachShader(program, glVertShader); + gl.attachShader(program, glFragShader); + gl.linkProgram(program); + + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + console.error('Pixi.js Error: Could not initialize shader.'); + console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); + console.error('gl.getError()', gl.getError()); + + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') + { + console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + + gl.deleteProgram(program); + program = null; + } + + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + + return program; +}; + +/** + * @private + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @return {WebGLShader} the shader + */ +var compileShader = function (gl, type, src) +{ + var shader = gl.createShader(type); + + gl.shaderSource(shader, src); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + console.log(gl.getShaderInfoLog(shader)); + return null; + } + + return shader; +}; + +module.exports = compileProgram; + +},{}],15:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} Type of value + * @param size {Number} + */ +var defaultValue = function(type, size) +{ + switch (type) + { + case 'float': + return 0; + + case 'vec2': + return new Float32Array(2 * size); + + case 'vec3': + return new Float32Array(3 * size); + + case 'vec4': + return new Float32Array(4 * size); + + case 'int': + case 'sampler2D': + return 0; + + case 'ivec2': + return new Int32Array(2 * size); + + case 'ivec3': + return new Int32Array(3 * size); + + case 'ivec4': + return new Int32Array(4 * size); + + case 'bool': + return false; + + case 'bvec2': + + return booleanArray( 2 * size); + + case 'bvec3': + return booleanArray(3 * size); + + case 'bvec4': + return booleanArray(4 * size); + + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } +}; + +var booleanArray = function(size) +{ + var array = new Array(size); + + for (var i = 0; i < array.length; i++) + { + array[i] = false; + } + + return array; +}; + +module.exports = defaultValue; + +},{}],16:[function(require,module,exports){ + +var mapType = require('./mapType'); +var mapSize = require('./mapSize'); + +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the attributes from + * @return attributes {Object} + */ +var extractAttributes = function(gl, program) +{ + var attributes = {}; + + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + + for (var i = 0; i < totalAttributes; i++) + { + var attribData = gl.getActiveAttrib(program, i); + var type = mapType(gl, attribData.type); + + attributes[attribData.name] = { + type:type, + size:mapSize(type), + location:gl.getAttribLocation(program, attribData.name), + //TODO - make an attribute object + pointer: pointer + }; + } + + return attributes; +}; + +var pointer = function(type, normalized, stride, start){ + // console.log(this.location) + gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +}; + +module.exports = extractAttributes; + +},{"./mapSize":20,"./mapType":21}],17:[function(require,module,exports){ +var mapType = require('./mapType'); +var defaultValue = require('./defaultValue'); + +/** + * Extracts the uniforms + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the uniforms from + * @return uniforms {Object} + */ +var extractUniforms = function(gl, program) +{ + var uniforms = {}; + + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + + for (var i = 0; i < totalUniforms; i++) + { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]/, ""); + var type = mapType(gl, uniformData.type ); + + uniforms[name] = { + type:type, + size:uniformData.size, + location:gl.getUniformLocation(program, name), + value:defaultValue(type, uniformData.size) + }; + } + + return uniforms; +}; + +module.exports = extractUniforms; + +},{"./defaultValue":15,"./mapType":21}],18:[function(require,module,exports){ +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param uniforms {Array} @mat ? + * @return attributes {Object} + */ +var generateUniformAccessObject = function(gl, uniformData) +{ + // this is the object we will be sending back. + // an object hierachy will be created for structs + var uniforms = {data:{}}; + + uniforms.gl = gl; + + var uniformKeys= Object.keys(uniformData); + + for (var i = 0; i < uniformKeys.length; i++) + { + var fullName = uniformKeys[i]; + + var nameTokens = fullName.split('.'); + var name = nameTokens[nameTokens.length - 1]; + + var uniformGroup = getUniformGroup(nameTokens, uniforms); + + var uniform = uniformData[fullName]; + uniformGroup.data[name] = uniform; + + uniformGroup.gl = gl; + + Object.defineProperty(uniformGroup, name, { + get: generateGetter(name), + set: generateSetter(name, uniform) + }); + } + + return uniforms; +}; + +var generateGetter = function(name) +{ + var template = getterTemplate.replace('%%', name); + return new Function(template); // jshint ignore:line +}; + +var generateSetter = function(name, uniform) +{ + var template = setterTemplate.replace(/%%/g, name); + var setTemplate; + + if(uniform.size === 1) + { + setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; + } + else + { + setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; + } + + if(setTemplate) + { + template += "\nthis.gl." + setTemplate + ";"; + } + + return new Function('value', template); // jshint ignore:line +}; + +var getUniformGroup = function(nameTokens, uniform) +{ + var cur = uniform; + + for (var i = 0; i < nameTokens.length - 1; i++) + { + var o = cur[nameTokens[i]] || {data:{}}; + cur[nameTokens[i]] = o; + cur = o; + } + + return cur; +}; + +var getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +var setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;' +].join('\n'); + + +var GLSL_TO_SINGLE_SETTERS = { + + 'float': 'uniform1f(location, value)', + + 'vec2': 'uniform2f(location, value[0], value[1])', + 'vec3': 'uniform3f(location, value[0], value[1], value[2])', + 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', + + 'int': 'uniform1i(location, value)', + 'ivec2': 'uniform2i(location, value[0], value[1])', + 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', + 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'bool': 'uniform1i(location, value)', + 'bvec2': 'uniform2i(location, value[0], value[1])', + 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', + 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'mat2': 'uniformMatrix2fv(location, false, value)', + 'mat3': 'uniformMatrix3fv(location, false, value)', + 'mat4': 'uniformMatrix4fv(location, false, value)', + + 'sampler2D':'uniform1i(location, value)' +}; + +var GLSL_TO_ARRAY_SETTERS = { + + 'float': 'uniform1fv(location, value)', + + 'vec2': 'uniform2fv(location, value)', + 'vec3': 'uniform3fv(location, value)', + 'vec4': 'uniform4fv(location, value)', + + 'int': 'uniform1iv(location, value)', + 'ivec2': 'uniform2iv(location, value)', + 'ivec3': 'uniform3iv(location, value)', + 'ivec4': 'uniform4iv(location, value)', + + 'bool': 'uniform1iv(location, value)', + 'bvec2': 'uniform2iv(location, value)', + 'bvec3': 'uniform3iv(location, value)', + 'bvec4': 'uniform4iv(location, value)', + + 'sampler2D':'uniform1iv(location, value)' +}; + +module.exports = generateUniformAccessObject; + +},{}],19:[function(require,module,exports){ +module.exports = { + compileProgram: require('./compileProgram'), + defaultValue: require('./defaultValue'), + extractAttributes: require('./extractAttributes'), + extractUniforms: require('./extractUniforms'), + generateUniformAccessObject: require('./generateUniformAccessObject'), + mapSize: require('./mapSize'), + mapType: require('./mapType') +}; +},{"./compileProgram":14,"./defaultValue":15,"./extractAttributes":16,"./extractUniforms":17,"./generateUniformAccessObject":18,"./mapSize":20,"./mapType":21}],20:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} + * @return {Number} + */ +var mapSize = function(type) +{ + return GLSL_TO_SIZE[type]; +}; + + +var GLSL_TO_SIZE = { + 'float': 1, + 'vec2': 2, + 'vec3': 3, + 'vec4': 4, + + 'int': 1, + 'ivec2': 2, + 'ivec3': 3, + 'ivec4': 4, + + 'bool': 1, + 'bvec2': 2, + 'bvec3': 3, + 'bvec4': 4, + + 'mat2': 4, + 'mat3': 9, + 'mat4': 16, + + 'sampler2D': 1 +}; + +module.exports = mapSize; + +},{}],21:[function(require,module,exports){ + + +var mapSize = function(gl, type) +{ + if(!GL_TABLE) + { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + + GL_TABLE = {}; + + for(var i = 0; i < typeNames.length; ++i) + { + var tn = typeNames[i]; + GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + } + } + + return GL_TABLE[type]; +}; + +var GL_TABLE = null; + +var GL_TO_GLSL_TYPES = { + 'FLOAT': 'float', + 'FLOAT_VEC2': 'vec2', + 'FLOAT_VEC3': 'vec3', + 'FLOAT_VEC4': 'vec4', + + 'INT': 'int', + 'INT_VEC2': 'ivec2', + 'INT_VEC3': 'ivec3', + 'INT_VEC4': 'ivec4', + + 'BOOL': 'bool', + 'BOOL_VEC2': 'bvec2', + 'BOOL_VEC3': 'bvec3', + 'BOOL_VEC4': 'bvec4', + + 'FLOAT_MAT2': 'mat2', + 'FLOAT_MAT3': 'mat3', + 'FLOAT_MAT4': 'mat4', + + 'SAMPLER_2D': 'sampler2D' +}; + +module.exports = mapSize; + +},{}],22:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) + +},{"_process":23}],23:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],24:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],25:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],26:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],27:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":25,"./encode":26}],28:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":29,"punycode":24,"querystring":27}],29:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],30:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _async = require('./async'); + +var async = _interopRequireWildcard(_async); + +var _Resource = require('./Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// some constants +var MAX_PROGRESS = 100; +var rgxExtractUrlHash = /(#[\w-]+)?$/; + +/** + * Manages the state and loading of multiple resources to load. + * + * @class + */ + +var Loader = function () { + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader() { + var _this = this; + + var baseUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var concurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; + + _classCallCheck(this, Loader); + + /** + * The base url for all resources loaded by this loader. + * + * @member {string} + */ + this.baseUrl = baseUrl; + + /** + * The progress percent of the loader going through the queue. + * + * @member {number} + */ + this.progress = 0; + + /** + * Loading state of the loader, true if it is currently loading resources. + * + * @member {boolean} + */ + this.loading = false; + + /** + * A querystring to append to every URL added to the loader. + * + * This should be a valid query string *without* the question-mark (`?`). The loader will + * also *not* escape values for you. Make sure to escape your parameters with + * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. + * + * @example + * + * ```js + * const loader = new Loader(); + * + * loader.defaultQueryString = 'user=me&password=secret'; + * + * // This will request 'image.png?user=me&password=secret' + * loader.add('image.png').load(); + * + * loader.reset(); + * + * // This will request 'image.png?v=1&user=me&password=secret' + * loader.add('iamge.png?v=1').load(); + * ``` + */ + this.defaultQueryString = ''; + + /** + * The middleware to run before loading each resource. + * + * @member {function[]} + */ + this._beforeMiddleware = []; + + /** + * The middleware to run after loading each resource. + * + * @member {function[]} + */ + this._afterMiddleware = []; + + /** + * The tracks the resources we are currently completing parsing for. + * + * @member {Resource[]} + */ + this._resourcesParsing = []; + + /** + * The `_loadResource` function bound with this object context. + * + * @private + * @member {function} + * @param {Resource} r - The resource to load + * @param {Function} d - The dequeue function + * @return {undefined} + */ + this._boundLoadResource = function (r, d) { + return _this._loadResource(r, d); + }; + + /** + * The resources waiting to be loaded. + * + * @private + * @member {Resource[]} + */ + this._queue = async.queue(this._boundLoadResource, concurrency); + + this._queue.pause(); + + /** + * All the resources for this loader keyed by name. + * + * @member {object} + */ + this.resources = {}; + + /** + * Dispatched once per loaded or errored resource. + * + * The callback looks like {@link Loader.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once per errored resource. + * + * The callback looks like {@link Loader.OnErrorSignal}. + * + * @member {Signal} + */ + this.onError = new _miniSignals2.default(); + + /** + * Dispatched once per loaded resource. + * + * The callback looks like {@link Loader.OnLoadSignal}. + * + * @member {Signal} + */ + this.onLoad = new _miniSignals2.default(); + + /** + * Dispatched when the loader begins to process the queue. + * + * The callback looks like {@link Loader.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched when the queued resources all load. + * + * The callback looks like {@link Loader.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * When the progress changes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnProgressSignal + * @param {Loader} loader - The loader the progress is advancing on. + * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance. + */ + + /** + * When an error occurrs the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnErrorSignal + * @param {Loader} loader - The loader the error happened in. + * @param {Resource} resource - The resource that caused the error. + */ + + /** + * When a load completes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnLoadSignal + * @param {Loader} loader - The loader that laoded the resource. + * @param {Resource} resource - The resource that has completed loading. + */ + + /** + * When the loader starts loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnStartSignal + * @param {Loader} loader - The loader that has started loading resources. + */ + + /** + * When the loader completes loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnCompleteSignal + * @param {Loader} loader - The loader that has finished loading resources. + */ + } + + /** + * Adds a resource (or multiple resources) to the loader queue. + * + * This function can take a wide variety of different parameters. The only thing that is always + * required the url to load. All the following will work: + * + * ```js + * loader + * // normal param syntax + * .add('key', 'http://...', function () {}) + * .add('http://...', function () {}) + * .add('http://...') + * + * // object syntax + * .add({ + * name: 'key2', + * url: 'http://...' + * }, function () {}) + * .add({ + * url: 'http://...' + * }, function () {}) + * .add({ + * name: 'key3', + * url: 'http://...' + * onComplete: function () {} + * }) + * .add({ + * url: 'https://...', + * onComplete: function () {}, + * crossOrigin: true + * }) + * + * // you can also pass an array of objects or urls or both + * .add([ + * { name: 'key4', url: 'http://...', onComplete: function () {} }, + * { url: 'http://...', onComplete: function () {} }, + * 'http://...' + * ]) + * + * // and you can use both params and options + * .add('key', 'http://...', { crossOrigin: true }, function () {}) + * .add('http://...', { crossOrigin: true }, function () {}); + * ``` + * + * @param {string} [name] - The name of the resource to load, if not passed the url is used. + * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @param {object} [options] - The options for the load. + * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should + * the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @param {function} [cb] - Function to call when this specific resource completes loading. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.add = function add(name, url, options, cb) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + + return this; + } + + // if an object is passed instead of params + if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') { + cb = url || name.callback || name.onComplete; + options = name; + url = name.url; + name = name.name || name.key || name.url; + } + + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + cb = options; + options = url; + url = name; + } + + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + cb = options; + options = null; + } + + // if loading already you can only add resources that have a parent. + if (this.loading && (!options || !options.parentResource)) { + throw new Error('Cannot add resources while the loader is running.'); + } + + // check if resource already exists. + if (this.resources[name]) { + throw new Error('Resource named "' + name + '" already exists.'); + } + + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + + // create the store the resource + this.resources[name] = new _Resource2.default(name, url, options); + + if (typeof cb === 'function') { + this.resources[name].onAfterMiddleware.once(cb); + } + + // if actively loading, make sure to adjust progress chunks for that parent and its children + if (this.loading) { + var parent = options.parentResource; + var incompleteChildren = []; + + for (var _i = 0; _i < parent.children.length; ++_i) { + if (!parent.children[_i].isComplete) { + incompleteChildren.push(parent.children[_i]); + } + } + + var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent + var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child + + parent.children.push(this.resources[name]); + parent.progressChunk = eachChunk; + + for (var _i2 = 0; _i2 < incompleteChildren.length; ++_i2) { + incompleteChildren[_i2].progressChunk = eachChunk; + } + + this.resources[name].progressChunk = eachChunk; + } + + // add the resource to the queue + this._queue.push(this.resources[name]); + + return this; + }; + + /** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * + * @method before + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.pre = function pre(fn) { + this._beforeMiddleware.push(fn); + + return this; + }; + + /** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * + * @alias use + * @method after + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.use = function use(fn) { + this._afterMiddleware.push(fn); + + return this; + }; + + /** + * Resets the queue of the loader to prepare for a new load. + * + * @return {Loader} Returns itself. + */ + + + Loader.prototype.reset = function reset() { + this.progress = 0; + this.loading = false; + + this._queue.kill(); + this._queue.pause(); + + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + + if (res._onLoadBinding) { + res._onLoadBinding.detach(); + } + + if (res.isLoading) { + res.abort(); + } + } + + this.resources = {}; + + return this; + }; + + /** + * Starts loading the queued resources. + * + * @param {function} [cb] - Optional callback that will be bound to the `complete` event. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.load = function load(cb) { + // register complete callback if they pass one + if (typeof cb === 'function') { + this.onComplete.once(cb); + } + + // if the queue has already started we are done here + if (this.loading) { + return this; + } + + // distribute progress chunks + var chunk = 100 / this._queue._tasks.length; + + for (var i = 0; i < this._queue._tasks.length; ++i) { + this._queue._tasks[i].data.progressChunk = chunk; + } + + // update loading state + this.loading = true; + + // notify of start + this.onStart.dispatch(this); + + // start loading + this._queue.resume(); + + return this; + }; + + /** + * Prepares a url for usage based on the configuration of this object + * + * @private + * @param {string} url - The url to prepare. + * @return {string} The prepared url. + */ + + + Loader.prototype._prepareUrl = function _prepareUrl(url) { + var parsedUrl = (0, _parseUri2.default)(url, { strictMode: true }); + var result = void 0; + + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { + result = url; + } + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + else if (this.baseUrl.length && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 && url.charAt(0) !== '/') { + result = this.baseUrl + '/' + url; + } else { + result = this.baseUrl + url; + } + + // if we need to add a default querystring, there is a bit more work + if (this.defaultQueryString) { + var hash = rgxExtractUrlHash.exec(result)[0]; + + result = result.substr(0, result.length - hash.length); + + if (result.indexOf('?') !== -1) { + result += '&' + this.defaultQueryString; + } else { + result += '?' + this.defaultQueryString; + } + + result += hash; + } + + return result; + }; + + /** + * Loads a single resource. + * + * @private + * @param {Resource} resource - The resource to load. + * @param {function} dequeue - The function to call when we need to dequeue this item. + */ + + + Loader.prototype._loadResource = function _loadResource(resource, dequeue) { + var _this2 = this; + + resource._dequeue = dequeue; + + // run before middleware + async.eachSeries(this._beforeMiddleware, function (fn, next) { + fn.call(_this2, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, function () { + if (resource.isComplete) { + _this2._onLoad(resource); + } else { + resource._onLoadBinding = resource.onComplete.once(_this2._onLoad, _this2); + resource.load(); + } + }); + }; + + /** + * Called once each resource has loaded. + * + * @private + */ + + + Loader.prototype._onComplete = function _onComplete() { + this.loading = false; + + this.onComplete.dispatch(this, this.resources); + }; + + /** + * Called each time a resources is loaded. + * + * @private + * @param {Resource} resource - The resource that was loaded + */ + + + Loader.prototype._onLoad = function _onLoad(resource) { + var _this3 = this; + + resource._onLoadBinding = null; + + // remove this resource from the async queue, and add it to our list of resources that are being parsed + resource._dequeue(); + this._resourcesParsing.push(resource); + + // run middleware, this *must* happen before dequeue so sub-assets get added properly + async.eachSeries(this._afterMiddleware, function (fn, next) { + fn.call(_this3, resource, next); + }, function () { + resource.onAfterMiddleware.dispatch(resource); + + _this3.progress += resource.progressChunk; + _this3.onProgress.dispatch(_this3, resource); + + if (resource.error) { + _this3.onError.dispatch(resource.error, _this3, resource); + } else { + _this3.onLoad.dispatch(_this3, resource); + } + + _this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1); + + // do completion check + if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) { + _this3.progress = MAX_PROGRESS; + _this3._onComplete(); + } + }); + }; + + return Loader; +}(); + +exports.default = Loader; + +},{"./Resource":31,"./async":32,"mini-signals":36,"parse-uri":37}],31:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// tests is CORS is supported in XHR, if not we need to use XDR +var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest())); +var tempAnchor = null; + +// some status constants +var STATUS_NONE = 0; +var STATUS_OK = 200; +var STATUS_EMPTY = 204; + +// noop +function _noop() {} /* empty */ + +/** + * Manages the state and loading of a resource and all child resources. + * + * @class + */ + +var Resource = function () { + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. + */ + Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) { + setExtMap(Resource._loadTypeMap, extname, loadType); + }; + + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ + + + Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); + }; + + /** + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass + * an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + */ + + + function Resource(name, url, options) { + _classCallCheck(this, Resource); + + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + + options = options || {}; + + /** + * The state flags of this resource. + * + * @member {number} + */ + this._flags = 0; + + // set data url flag, needs to be set early for some _determineX checks to work. + this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); + + /** + * The name of this resource. + * + * @member {string} + * @readonly + */ + this.name = name; + + /** + * The url used to load this resource. + * + * @member {string} + * @readonly + */ + this.url = url; + + /** + * The extension used to load this resource. + * + * @member {string} + * @readonly + */ + this.extension = this._getExtension(); + + /** + * The data that was loaded by the resource. + * + * @member {any} + */ + this.data = null; + + /** + * Is this request cross-origin? If unset, determined automatically. + * + * @member {string} + */ + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + + /** + * The method of loading to use for this resource. + * + * @member {Resource.LOAD_TYPE} + */ + this.loadType = options.loadType || this._determineLoadType(); + + /** + * The type used to load the resource via XHR. If unset, determined automatically. + * + * @member {string} + */ + this.xhrType = options.xhrType; + + /** + * Extra info for middleware, and controlling specifics about how the resource loads. + * + * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + * Meaning it will modify it as it sees fit. + * + * @member {object} + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources + * to. + */ + this.metadata = options.metadata || {}; + + /** + * The error that occurred while loading (if any). + * + * @member {Error} + * @readonly + */ + this.error = null; + + /** + * The XHR object that was used to load this resource. This is only set + * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * + * @member {XMLHttpRequest} + * @readonly + */ + this.xhr = null; + + /** + * The child resources this resource owns. + * + * @member {Resource[]} + * @readonly + */ + this.children = []; + + /** + * The resource type. + * + * @member {Resource.TYPE} + * @readonly + */ + this.type = Resource.TYPE.UNKNOWN; + + /** + * The progress chunk owned by this resource. + * + * @member {number} + * @readonly + */ + this.progressChunk = 0; + + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * + * @private + * @member {function} + */ + this._dequeue = _noop; + + /** + * Used a storage place for the on load binding used privately by the loader. + * + * @private + * @member {function} + */ + this._onLoadBinding = null; + + /** + * The `complete` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundComplete = this.complete.bind(this); + + /** + * The `_onError` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnError = this._onError.bind(this); + + /** + * The `_onProgress` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnProgress = this._onProgress.bind(this); + + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + this._boundXdrOnTimeout = this._xdrOnTimeout.bind(this); + + /** + * Dispatched when the resource beings to load. + * + * The callback looks like {@link Resource.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched each time progress of this resource load updates. + * Not all resources types and loader systems can support this event + * so sometimes it may not be available. If the resource + * is being loaded on a modern browser, using XHR, and the remote server + * properly sets Content-Length headers, then this will be available. + * + * The callback looks like {@link Resource.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once this resource has loaded, if there was an error it will + * be in the `error` property. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * Dispatched after this resource has had all the *after* middleware run on it. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onAfterMiddleware = new _miniSignals2.default(); + + /** + * When the resource starts to load. + * + * @memberof Resource + * @callback OnStartSignal + * @param {Resource} resource - The resource that the event happened on. + */ + + /** + * When the resource reports loading progress. + * + * @memberof Resource + * @callback OnProgressSignal + * @param {Resource} resource - The resource that the event happened on. + * @param {number} percentage - The progress of the load in the range [0, 1]. + */ + + /** + * When the resource finishes loading. + * + * @memberof Resource + * @callback OnCompleteSignal + * @param {Resource} resource - The resource that the event happened on. + */ + } + + /** + * Stores whether or not this url is a data url. + * + * @member {boolean} + * @readonly + */ + + + /** + * Marks the resource as complete. + * + */ + Resource.prototype.complete = function complete() { + // TODO: Clean this up in a wrapper or something...gross.... + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + + this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true); + this._setFlag(Resource.STATUS_FLAGS.LOADING, false); + + this.onComplete.dispatch(this); + }; + + /** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ + + + Resource.prototype.abort = function abort(message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + + // store error + this.error = new Error(message); + + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } else if (this.xdr) { + this.xdr.abort(); + } else if (this.data) { + // single source + if (this.data.src) { + this.data.src = Resource.EMPTY_GIF; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + + // done now. + this.complete(); + }; + + /** + * Kicks off loading of this resource. This method is asynchronous. + * + * @param {function} [cb] - Optional callback to call once the resource is loaded. + */ + + + Resource.prototype.load = function load(cb) { + var _this = this; + + if (this.isLoading) { + return; + } + + if (this.isComplete) { + if (cb) { + setTimeout(function () { + return cb(_this); + }, 1); + } + + return; + } else if (cb) { + this.onComplete.once(cb); + } + + this._setFlag(Resource.STATUS_FLAGS.LOADING, true); + + this.onStart.dispatch(this); + + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + + switch (this.loadType) { + case Resource.LOAD_TYPE.IMAGE: + this.type = Resource.TYPE.IMAGE; + this._loadElement('image'); + break; + + case Resource.LOAD_TYPE.AUDIO: + this.type = Resource.TYPE.AUDIO; + this._loadSourceElement('audio'); + break; + + case Resource.LOAD_TYPE.VIDEO: + this.type = Resource.TYPE.VIDEO; + this._loadSourceElement('video'); + break; + + case Resource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } else { + this._loadXhr(); + } + break; + } + }; + + /** + * Checks if the flag is set. + * + * @private + * @param {number} flag - The flag to check. + * @return {boolean} True if the flag is set. + */ + + + Resource.prototype._hasFlag = function _hasFlag(flag) { + return !!(this._flags & flag); + }; + + /** + * (Un)Sets the flag. + * + * @private + * @param {number} flag - The flag to (un)set. + * @param {boolean} value - Whether to set or (un)set the flag. + */ + + + Resource.prototype._setFlag = function _setFlag(flag, value) { + this._flags = value ? this._flags | flag : this._flags & ~flag; + }; + + /** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadElement = function _loadElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'image' && typeof window.Image !== 'undefined') { + this.data = new Image(); + } else { + this.data = document.createElement(type); + } + + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + }; + + /** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadSourceElement = function _loadSourceElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'audio' && typeof window.Audio !== 'undefined') { + this.data = new Audio(); + } else { + this.data = document.createElement(type); + } + + if (this.data === null) { + this.abort('Unsupported element: ' + type); + + return; + } + + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } else if (Array.isArray(this.url)) { + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i])); + } + } else { + this.data.appendChild(this._createSource(type, this.url)); + } + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + + this.data.load(); + }; + + /** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ + + + Resource.prototype._loadXhr = function _loadXhr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xhr = this.xhr = new XMLHttpRequest(); + + // set the request type and url + xhr.open('GET', this.url, true); + + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; + } else { + xhr.responseType = this.xhrType; + } + + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + + xhr.send(); + }; + + /** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ + + + Resource.prototype._loadXdr = function _loadXdr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xdr = this.xhr = new XDomainRequest(); + + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = 5000; + + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXdrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + + xdr.open('GET', this.url, true); + + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { + return xdr.send(); + }, 1); + }; + + /** + * Creates a source used in loading via an element. + * + * @private + * @param {string} type - The element type (video or audio). + * @param {string} url - The source URL to load from. + * @param {string} [mime] - The mime type of the video + * @return {HTMLSourceElement} The source element. + */ + + + Resource.prototype._createSource = function _createSource(type, url, mime) { + if (!mime) { + mime = type + '/' + url.substr(url.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = url; + source.type = mime; + + return source; + }; + + /** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ + + + Resource.prototype._onError = function _onError(event) { + this.abort('Failed to load element using: ' + event.target.nodeName); + }; + + /** + * Called if a load progress event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ + + + Resource.prototype._onProgress = function _onProgress(event) { + if (event && event.lengthComputable) { + this.onProgress.dispatch(this, event.loaded / event.total); + } + }; + + /** + * Called if an error event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestErrorEvent|Event} event - Error event. + */ + + + Resource.prototype._xhrOnError = function _xhrOnError() { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"'); + }; + + /** + * Called if an abort event fires for xhr. + * + * @private + * @param {XMLHttpRequestAbortEvent} event - Abort Event + */ + + + Resource.prototype._xhrOnAbort = function _xhrOnAbort() { + this.abort(reqType(this.xhr) + ' Request was aborted by the user.'); + }; + + /** + * Called if a timeout event fires for xdr. + * + * @private + * @param {Event} event - Timeout event. + */ + + + Resource.prototype._xdrOnTimeout = function _xdrOnTimeout() { + this.abort(reqType(this.xhr) + ' Request timed out.'); + }; + + /** + * Called when data successfully loads from an xhr/xdr request. + * + * @private + * @param {XMLHttpRequestLoadEvent|Event} event - Load event + */ + + + Resource.prototype._xhrOnLoad = function _xhrOnLoad() { + var xhr = this.xhr; + var status = typeof xhr.status === 'undefined' ? xhr.status : STATUS_OK; // XDR has no `.status`, assume 200. + + // status can be 0 when using the `file://` protocol so we also check if a response is set + if (status === STATUS_OK || status === STATUS_EMPTY || status === STATUS_NONE && xhr.responseText.length > 0) { + // if text, just return it + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { + this.data = xhr.responseText; + this.type = Resource.TYPE.TEXT; + } + // if json, parse into json object + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(xhr.responseText); + this.type = Resource.TYPE.JSON; + } catch (e) { + this.abort('Error trying to parse loaded json: ' + e); + + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (window.DOMParser) { + var domparser = new DOMParser(); + + this.data = domparser.parseFromString(xhr.responseText, 'text/xml'); + } else { + var div = document.createElement('div'); + + div.innerHTML = xhr.responseText; + + this.data = div; + } + + this.type = Resource.TYPE.XML; + } catch (e) { + this.abort('Error trying to parse loaded xml: ' + e); + + return; + } + } + // other types just return the response + else { + this.data = xhr.response || xhr.responseText; + } + } else { + this.abort('[' + xhr.status + '] ' + xhr.statusText + ': ' + xhr.responseURL); + + return; + } + + this.complete(); + }; + + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * + * @private + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ + + + Resource.prototype._determineCrossOrigin = function _determineCrossOrigin(url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = (0, _parseUri2.default)(tempAnchor.href, { strictMode: true }); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + var protocol = url.protocol ? url.protocol + ':' : ''; + + // if cross origin + if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; + }; + + /** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. + */ + + + Resource.prototype._determineXhrType = function _determineXhrType() { + return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT; + }; + + /** + * Determines the loadType of a resource based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.LOAD_TYPE} The loadType to use. + */ + + + Resource.prototype._determineLoadType = function _determineLoadType() { + return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR; + }; + + /** + * Extracts the extension (sans '.') of the file being loaded by the resource. + * + * @private + * @return {string} The extension. + */ + + + Resource.prototype._getExtension = function _getExtension() { + var url = this.url; + var ext = ''; + + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } else { + var queryStart = url.indexOf('?'); + + if (queryStart !== -1) { + url = url.substring(0, queryStart); + } + + ext = url.substring(url.lastIndexOf('.') + 1); + } + + return ext.toLowerCase(); + }; + + /** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * + * @private + * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. + * @return {string} The mime type to use. + */ + + + Resource.prototype._getMimeFromXhrType = function _getMimeFromXhrType(type) { + switch (type) { + case Resource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + + case Resource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + + case Resource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + + case Resource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + + case Resource.XHR_RESPONSE_TYPE.DEFAULT: + case Resource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + + } + }; + + _createClass(Resource, [{ + key: 'isDataUrl', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL); + } + + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isComplete', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE); + } + + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isLoading', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.LOADING); + } + }]); + + return Resource; +}(); + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ + + +exports.default = Resource; +Resource.STATUS_FLAGS = { + NONE: 0, + DATA_URL: 1 << 0, + COMPLETE: 1 << 1, + LOADING: 1 << 2 +}; + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ +Resource.TYPE = { + UNKNOWN: 0, + JSON: 1, + XML: 2, + IMAGE: 3, + AUDIO: 4, + VIDEO: 5, + TEXT: 6 +}; + +/** + * The types of loading a resource can use. + * + * @static + * @readonly + * @enum {number} + */ +Resource.LOAD_TYPE = { + /** Uses XMLHttpRequest to load the resource. */ + XHR: 1, + /** Uses an `Image` object to load the resource. */ + IMAGE: 2, + /** Uses an `Audio` object to load the resource. */ + AUDIO: 3, + /** Uses a `Video` object to load the resource. */ + VIDEO: 4 +}; + +/** + * The XHR ready states, used internally. + * + * @static + * @readonly + * @enum {string} + */ +Resource.XHR_RESPONSE_TYPE = { + /** string */ + DEFAULT: 'text', + /** ArrayBuffer */ + BUFFER: 'arraybuffer', + /** Blob */ + BLOB: 'blob', + /** Document */ + DOCUMENT: 'document', + /** Object */ + JSON: 'json', + /** String */ + TEXT: 'text' +}; + +Resource._loadTypeMap = { + // images + gif: Resource.LOAD_TYPE.IMAGE, + png: Resource.LOAD_TYPE.IMAGE, + bmp: Resource.LOAD_TYPE.IMAGE, + jpg: Resource.LOAD_TYPE.IMAGE, + jpeg: Resource.LOAD_TYPE.IMAGE, + tif: Resource.LOAD_TYPE.IMAGE, + tiff: Resource.LOAD_TYPE.IMAGE, + webp: Resource.LOAD_TYPE.IMAGE, + tga: Resource.LOAD_TYPE.IMAGE, + svg: Resource.LOAD_TYPE.IMAGE, + 'svg+xml': Resource.LOAD_TYPE.IMAGE, // for SVG data urls + + // audio + mp3: Resource.LOAD_TYPE.AUDIO, + ogg: Resource.LOAD_TYPE.AUDIO, + wav: Resource.LOAD_TYPE.AUDIO, + + // videos + mp4: Resource.LOAD_TYPE.VIDEO, + webm: Resource.LOAD_TYPE.VIDEO +}; + +Resource._xhrTypeMap = { + // xml + xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. + // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, + // this should probably be fine. + tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // images + gif: Resource.XHR_RESPONSE_TYPE.BLOB, + png: Resource.XHR_RESPONSE_TYPE.BLOB, + bmp: Resource.XHR_RESPONSE_TYPE.BLOB, + jpg: Resource.XHR_RESPONSE_TYPE.BLOB, + jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, + tif: Resource.XHR_RESPONSE_TYPE.BLOB, + tiff: Resource.XHR_RESPONSE_TYPE.BLOB, + webp: Resource.XHR_RESPONSE_TYPE.BLOB, + tga: Resource.XHR_RESPONSE_TYPE.BLOB, + + // json + json: Resource.XHR_RESPONSE_TYPE.JSON, + + // text + text: Resource.XHR_RESPONSE_TYPE.TEXT, + txt: Resource.XHR_RESPONSE_TYPE.TEXT, + + // fonts + ttf: Resource.XHR_RESPONSE_TYPE.BUFFER, + otf: Resource.XHR_RESPONSE_TYPE.BUFFER +}; + +// We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif +Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; + +/** + * Quick helper to set a value on one of the extension maps. Ensures there is no + * dot at the start of the extension. + * + * @ignore + * @param {object} map - The map to set on. + * @param {string} extname - The extension (or key) to set. + * @param {number} val - The value to set. + */ +function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + + if (!extname) { + return; + } + + map[extname] = val; +} + +/** + * Quick helper to get string xhr type. + * + * @ignore + * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. + * @return {string} The type. + */ +function reqType(xhr) { + return xhr.toString().replace('object ', ''); +} + +},{"mini-signals":36,"parse-uri":37}],32:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.eachSeries = eachSeries; +exports.queue = queue; +/** + * Smaller version of the async library constructs. + * + */ +function _noop() {} /* empty */ + +/** + * Iterates an array in series. + * + * @param {*[]} array - Array to iterate. + * @param {function} iterator - Function to call for each element. + * @param {function} callback - Function to call when done, or on error. + */ +function eachSeries(array, iterator, callback) { + var i = 0; + var len = array.length; + + (function next(err) { + if (err || i === len) { + if (callback) { + callback(err); + } + + return; + } + + iterator(array[i++], next); + })(); +} + +/** + * Ensures a function is only called once. + * + * @param {function} fn - The function to wrap. + * @return {function} The wrapping function. + */ +function onlyOnce(fn) { + return function onceWrapper() { + if (fn === null) { + throw new Error('Callback was already called.'); + } + + var callFn = fn; + + fn = null; + callFn.apply(this, arguments); + }; +} + +/** + * Async queue implementation, + * + * @param {function} worker - The worker function to call for each task. + * @param {number} concurrency - How many workers to run in parrallel. + * @return {*} The async queue object. + */ +function queue(worker, concurrency) { + if (concurrency == null) { + // eslint-disable-line no-eq-null,eqeqeq + concurrency = 1; + } else if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + + var workers = 0; + var q = { + _tasks: [], + concurrency: concurrency, + saturated: _noop, + unsaturated: _noop, + buffer: concurrency / 4, + empty: _noop, + drain: _noop, + error: _noop, + started: false, + paused: false, + push: function push(data, callback) { + _insert(data, false, callback); + }, + kill: function kill() { + workers = 0; + q.drain = _noop; + q.started = false; + q._tasks = []; + }, + unshift: function unshift(data, callback) { + _insert(data, true, callback); + }, + process: function process() { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var task = q._tasks.shift(); + + if (q._tasks.length === 0) { + q.empty(); + } + + workers += 1; + + if (workers === q.concurrency) { + q.saturated(); + } + + worker(task.data, onlyOnce(_next(task))); + } + }, + length: function length() { + return q._tasks.length; + }, + running: function running() { + return workers; + }, + idle: function idle() { + return q._tasks.length + workers === 0; + }, + pause: function pause() { + if (q.paused === true) { + return; + } + + q.paused = true; + }, + resume: function resume() { + if (q.paused === false) { + return; + } + + q.paused = false; + + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= q.concurrency; w++) { + q.process(); + } + } + }; + + function _insert(data, insertAtFront, callback) { + if (callback != null && typeof callback !== 'function') { + // eslint-disable-line no-eq-null,eqeqeq + throw new Error('task callback must be a function'); + } + + q.started = true; + + if (data == null && q.idle()) { + // eslint-disable-line no-eq-null,eqeqeq + // call drain immediately if there are no tasks + setTimeout(function () { + return q.drain(); + }, 1); + + return; + } + + var item = { + data: data, + callback: typeof callback === 'function' ? callback : _noop + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + setTimeout(function () { + return q.process(); + }, 1); + } + + function _next(task) { + return function next() { + workers -= 1; + + task.callback.apply(task, arguments); + + if (arguments[0] != null) { + // eslint-disable-line no-eq-null,eqeqeq + q.error(arguments[0], task.data); + } + + if (workers <= q.concurrency - q.buffer) { + q.unsaturated(); + } + + if (q.idle()) { + q.drain(); + } + + q.process(); + }; + } + + return q; +} + +},{}],33:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.encodeBinary = encodeBinary; +var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +function encodeBinary(input) { + var output = ''; + var inx = 0; + + while (inx < input.length) { + // Fill byte buffer array + var bytebuffer = [0, 0, 0]; + var encodedCharIndexes = [0, 0, 0, 0]; + + for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } else { + bytebuffer[jnx] = 0; + } + } + + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4; + + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6; + + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + + // Determine whether padding happened, and adjust accordingly + var paddingBytes = inx - (input.length - 1); + + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + + default: + break; // No padding - proceed + } + + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) { + output += _keyStr.charAt(encodedCharIndexes[_jnx]); + } + } + + return output; +} + +},{}],34:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Loader = require('./Loader'); + +var _Loader2 = _interopRequireDefault(_Loader); + +var _Resource = require('./Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +var _async = require('./async'); + +var async = _interopRequireWildcard(_async); + +var _b = require('./b64'); + +var b64 = _interopRequireWildcard(_b); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +_Loader2.default.Resource = _Resource2.default; +_Loader2.default.async = async; +_Loader2.default.base64 = b64; + +// export manually, and also as default +module.exports = _Loader2.default; // eslint-disable-line no-undef +exports.default = _Loader2.default; + +},{"./Loader":30,"./Resource":31,"./async":32,"./b64":33}],35:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +exports.blobMiddlewareFactory = blobMiddlewareFactory; + +var _Resource = require('../../Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +var _b = require('../../b64'); + +var _b2 = _interopRequireDefault(_b); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Url = window.URL || window.webkitURL; + +// a middleware for transforming XHR loaded Blobs into more useful objects +function blobMiddlewareFactory() { + return function blobMiddleware(resource, next) { + if (!resource.data) { + next(); + + return; + } + + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === _Resource2.default.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!window.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = 'data:' + type + ';base64,' + _b2.default.encodeBinary(resource.xhr.responseText); + + resource.type = _Resource2.default.TYPE.IMAGE; + + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + + next(); + }; + + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var _ret = function () { + var src = Url.createObjectURL(resource.data); + + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src; + + resource.type = _Resource2.default.TYPE.IMAGE; + + // cleanup the no longer used blob after the image loads + // TODO: Is this correct? Will the image be invalid after revoking? + resource.data.onload = function () { + Url.revokeObjectURL(src); + resource.data.onload = null; + + next(); + }; + + // next will be called on load. + return { + v: void 0 + }; + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + } + + next(); + }; +} + +},{"../../Resource":31,"../../b64":33}],36:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + +var MiniSignalBinding = (function () { + function MiniSignalBinding(fn, once, thisArg) { + if (once === undefined) once = false; + + _classCallCheck(this, MiniSignalBinding); + + this._fn = fn; + this._once = once; + this._thisArg = thisArg; + this._next = this._prev = this._owner = null; + } + + _createClass(MiniSignalBinding, [{ + key: 'detach', + value: function detach() { + if (this._owner === null) return false; + this._owner.detach(this); + return true; + } + }]); + + return MiniSignalBinding; +})(); + +function _addMiniSignalBinding(self, node) { + if (!self._head) { + self._head = node; + self._tail = node; + } else { + self._tail._next = node; + node._prev = self._tail; + self._tail = node; + } + + node._owner = self; + + return node; +} + +var MiniSignal = (function () { + function MiniSignal() { + _classCallCheck(this, MiniSignal); + + this._head = this._tail = undefined; + } + + _createClass(MiniSignal, [{ + key: 'handlers', + value: function handlers() { + var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; + + var node = this._head; + + if (exists) return !!node; + + var ee = []; + + while (node) { + ee.push(node); + node = node._next; + } + + return ee; + } + }, { + key: 'has', + value: function has(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.'); + } + + return node._owner === this; + } + }, { + key: 'dispatch', + value: function dispatch() { + var node = this._head; + + if (!node) return false; + + while (node) { + if (node._once) this.detach(node); + node._fn.apply(node._thisArg, arguments); + node = node._next; + } + + return true; + } + }, { + key: 'add', + value: function add(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#add(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg)); + } + }, { + key: 'once', + value: function once(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#once(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg)); + } + }, { + key: 'detach', + value: function detach(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.'); + } + if (node._owner !== this) return this; + + if (node._prev) node._prev._next = node._next; + if (node._next) node._next._prev = node._prev; + + if (node === this._head) { + this._head = node._next; + if (node._next === null) { + this._tail = null; + } + } else if (node === this._tail) { + this._tail = node._prev; + this._tail._next = null; + } + + node._owner = null; + return this; + } + }, { + key: 'detachAll', + value: function detachAll() { + var node = this._head; + if (!node) return this; + + this._head = this._tail = null; + + while (node) { + node._owner = null; + node = node._next; + } + return this; + } + }]); + + return MiniSignal; +})(); + +MiniSignal.MiniSignalBinding = MiniSignalBinding; + +exports['default'] = MiniSignal; +module.exports = exports['default']; + +},{}],37:[function(require,module,exports){ +'use strict' + +module.exports = function parseURI (str, opts) { + opts = opts || {} + + var o = { + key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], + q: { + name: 'queryKey', + parser: /(?:^|&)([^&=]*)=?([^&]*)/g + }, + parser: { + strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, + loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ + } + } + + var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str) + var uri = {} + var i = 14 + + while (i--) uri[o.key[i]] = m[i] || '' + + uri[o.q.name] = {} + uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { + if ($1) uri[o.q.name][$1] = $2 + }) + + return uri +} + +},{}],38:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +var _accessibleTarget = require('./accessibleTarget'); + +var _accessibleTarget2 = _interopRequireDefault(_accessibleTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// add some extra variables to the container.. +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _accessibleTarget2.default); + +var KEY_CODE_TAB = 9; + +var DIV_TOUCH_SIZE = 100; +var DIV_TOUCH_POS_X = 0; +var DIV_TOUCH_POS_Y = 0; +var DIV_TOUCH_ZINDEX = 2; + +var DIV_HOOK_SIZE = 1; +var DIV_HOOK_POS_X = -1000; +var DIV_HOOK_POS_Y = -1000; +var DIV_HOOK_ZINDEX = 2; + +/** + * The Accessibility manager reacreates the ability to tab and and have content read by screen + * readers. This is very important as it can possibly help people with disabilities access pixi + * content. + * + * Much like interaction any DisplayObject can be made accessible. This manager will map the + * events as if the mouse was being used, minimizing the efferot required to implement. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.accessibility + * + * @class + * @memberof PIXI.accessibility + */ + +var AccessibilityManager = function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + _classCallCheck(this, AccessibilityManager); + + if ((_ismobilejs2.default.tablet || _ismobilejs2.default.phone) && !navigator.isCocoonJS) { + this.createTouchHook(); + } + + // first we create a div that will sit over the pixi element. This is where the div overlays will go. + var div = document.createElement('div'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + 'px'; + div.style.left = DIV_TOUCH_POS_Y + 'px'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + + /** + * This is the dom element that will sit over the pixi element. This is where the div overlays will go. + * + * @type {HTMLElement} + * @private + */ + this.div = div; + + /** + * A simple pool for storing divs. + * + * @type {*} + * @private + */ + this.pool = []; + + /** + * This is a tick used to check if an object is no longer being rendered. + * + * @type {Number} + * @private + */ + this.renderId = 0; + + /** + * Setting this to true will visually show the divs + * + * @type {boolean} + */ + this.debug = false; + + /** + * The renderer this accessibility manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * The array of currently active accessible items. + * + * @member {Array<*>} + * @private + */ + this.children = []; + + /** + * pre-bind the functions + * + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + + /** + * stores the state of the manager. If there are no accessible objects or the mouse is moving the will be false. + * + * @member {Array<*>} + * @private + */ + this.isActive = false; + this.isMobileAccessabillity = false; + + // let listen for tab.. once pressed we can fire up and show the accessibility layer + window.addEventListener('keydown', this._onKeyDown, false); + } + + /** + * Creates the touch hooks. + * + */ + + + AccessibilityManager.prototype.createTouchHook = function createTouchHook() { + var _this = this; + + var hookDiv = document.createElement('button'); + + hookDiv.style.width = DIV_HOOK_SIZE + 'px'; + hookDiv.style.height = DIV_HOOK_SIZE + 'px'; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + 'px'; + hookDiv.style.left = DIV_HOOK_POS_Y + 'px'; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX; + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'HOOK DIV'; + + hookDiv.addEventListener('focus', function () { + _this.isMobileAccessabillity = true; + _this.activate(); + document.body.removeChild(hookDiv); + }); + + document.body.appendChild(hookDiv); + }; + + /** + * Activating will cause the Accessibility layer to be shown. This is called when a user + * preses the tab key + * + * @private + */ + + + AccessibilityManager.prototype.activate = function activate() { + if (this.isActive) { + return; + } + + this.isActive = true; + + window.document.addEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown, false); + + this.renderer.on('postrender', this.update, this); + + if (this.renderer.view.parentNode) { + this.renderer.view.parentNode.appendChild(this.div); + } + }; + + /** + * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves + * the mouse + * + * @private + */ + + + AccessibilityManager.prototype.deactivate = function deactivate() { + if (!this.isActive || this.isMobileAccessabillity) { + return; + } + + this.isActive = false; + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.addEventListener('keydown', this._onKeyDown, false); + + this.renderer.off('postrender', this.update); + + if (this.div.parentNode) { + this.div.parentNode.removeChild(this.div); + } + }; + + /** + * This recursive function will run throught he scene graph and add any new accessible objects to the DOM layer. + * + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + + + AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects(displayObject) { + if (!displayObject.visible) { + return; + } + + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + + displayObject.renderId = this.renderId; + } + + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + this.updateAccessibleObjects(children[i]); + } + }; + + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * + * @private + */ + + + AccessibilityManager.prototype.update = function update() { + if (!this.renderer.renderingToScreen) { + return; + } + + // update children... + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + + var rect = this.renderer.view.getBoundingClientRect(); + var sx = rect.width / this.renderer.width; + var sy = rect.height / this.renderer.height; + + var div = this.div; + + div.style.left = rect.left + 'px'; + div.style.top = rect.top + 'px'; + div.style.width = this.renderer.width + 'px'; + div.style.height = this.renderer.height + 'px'; + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + + core.utils.removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + + i--; + + if (this.children.length === 0) { + this.deactivate(); + } + } else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + + if (child.hitArea) { + div.style.left = (wt.tx + hitArea.x * wt.a) * sx + 'px'; + div.style.top = (wt.ty + hitArea.y * wt.d) * sy + 'px'; + + div.style.width = hitArea.width * wt.a * sx + 'px'; + div.style.height = hitArea.height * wt.d * sy + 'px'; + } else { + hitArea = child.getBounds(); + + this.capHitArea(hitArea); + + div.style.left = hitArea.x * sx + 'px'; + div.style.top = hitArea.y * sy + 'px'; + + div.style.width = hitArea.width * sx + 'px'; + div.style.height = hitArea.height * sy + 'px'; + } + } + } + + // increment the render id.. + this.renderId++; + }; + + /** + * TODO: docs. + * + * @param {Rectangle} hitArea - TODO docs + */ + + + AccessibilityManager.prototype.capHitArea = function capHitArea(hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + + if (hitArea.x + hitArea.width > this.renderer.width) { + hitArea.width = this.renderer.width - hitArea.x; + } + + if (hitArea.y + hitArea.height > this.renderer.height) { + hitArea.height = this.renderer.height - hitArea.y; + } + }; + + /** + * Adds a DisplayObject to the accessibility manager + * + * @private + * @param {DisplayObject} displayObject - The child to make accessible. + */ + + + AccessibilityManager.prototype.addChild = function addChild(displayObject) { + // this.activate(); + + var div = this.pool.pop(); + + if (!div) { + div = document.createElement('button'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + div.style.borderStyle = 'none'; + + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + + if (displayObject.accessibleTitle) { + div.title = displayObject.accessibleTitle; + } else if (!displayObject.accessibleTitle && !displayObject.accessibleHint) { + div.title = 'displayObject ' + this.tabIndex; + } + + if (displayObject.accessibleHint) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + + // + + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + + /** + * Maps the div button press to pixi's InteractionManager (click) + * + * @private + * @param {MouseEvent} e - The click event. + */ + + + AccessibilityManager.prototype._onClick = function _onClick(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixis InteractionManager (mouseover) + * + * @private + * @param {FocusEvent} e - The focus event. + */ + + + AccessibilityManager.prototype._onFocus = function _onFocus(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixis InteractionManager (mouseout) + * + * @private + * @param {FocusEvent} e - The focusout event. + */ + + + AccessibilityManager.prototype._onFocusOut = function _onFocusOut(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); + }; + + /** + * Is called when a key is pressed + * + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + + + AccessibilityManager.prototype._onKeyDown = function _onKeyDown(e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + + this.activate(); + }; + + /** + * Is called when the mouse moves across the renderer element + * + * @private + */ + + + AccessibilityManager.prototype._onMouseMove = function _onMouseMove() { + this.deactivate(); + }; + + /** + * Destroys the accessibility manager + * + */ + + + AccessibilityManager.prototype.destroy = function destroy() { + this.div = null; + + for (var i = 0; i < this.children.length; i++) { + this.children[i].div = null; + } + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.removeEventListener('keydown', this._onKeyDown); + + this.pool = null; + this.children = null; + this.renderer = null; + }; + + return AccessibilityManager; +}(); + +exports.default = AccessibilityManager; + + +core.WebGLRenderer.registerPlugin('accessibility', AccessibilityManager); +core.CanvasRenderer.registerPlugin('accessibility', AccessibilityManager); + +},{"../core":63,"./accessibleTarget":39,"ismobilejs":4}],39:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Default property values of accessible objects + * used by {@link PIXI.accessibility.AccessibilityManager}. + * + * @function accessibleTarget + * @memberof PIXI.accessibility + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibility.accessibleTarget + * ); + */ +exports.default = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * + * @member {boolean} + */ + accessible: false, + + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * + * @member {string} + */ + accessibleTitle: null, + + /** + * Sets the aria-label attribute of the shadow div + * + * @member {string} + */ + accessibleHint: null, + + /** + * @todo Needs docs. + */ + tabIndex: 0, + + /** + * @todo Needs docs. + */ + _accessibleActive: false, + + /** + * @todo Needs docs. + */ + _accessibleDiv: false +}; + +},{}],40:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _accessibleTarget = require('./accessibleTarget'); + +Object.defineProperty(exports, 'accessibleTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_accessibleTarget).default; + } +}); + +var _AccessibilityManager = require('./AccessibilityManager'); + +Object.defineProperty(exports, 'AccessibilityManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AccessibilityManager).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./AccessibilityManager":38,"./accessibleTarget":39}],41:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +var _Container = require('./display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _ticker = require('./ticker'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Convenience class to create a new PIXI application. + * This class automatically creates the renderer, ticker + * and root container. + * + * @example + * // Create the application + * const app = new PIXI.Application(); + * + * // Add the view to the DOM + * document.body.appendChild(app.view); + * + * // ex, add display objects + * app.stage.addChild(PIXI.Sprite.fromImage('something.png')); + * + * @class + * @memberof PIXI + */ +var Application = function () { + /** + * @param {number} [width=800] - the width of the renderers view + * @param {number} [height=600] - the height of the renderers view + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [noWebGL=false] - prevents selection of WebGL renderer, even if such is present + * @param {boolean} [options.legacy=false] - If true Pixi will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering try setting this to true. + * @param {boolean} [useSharedTicker=false] - `true` to use PIXI.ticker.shared, `false` to create new ticker. + */ + function Application(width, height, options, noWebGL) { + var useSharedTicker = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; + + _classCallCheck(this, Application); + + /** + * WebGL renderer if available, otherwise CanvasRenderer + * @member {PIXI.WebGLRenderer|PIXI.CanvasRenderer} + */ + this.renderer = (0, _autoDetectRenderer.autoDetectRenderer)(width, height, options, noWebGL); + + /** + * The root display container that's rendered. + * @member {PIXI.Container} + */ + this.stage = new _Container2.default(); + + /** + * Internal reference to the ticker + * @member {PIXI.ticker.Ticker} + * @private + */ + this._ticker = null; + + /** + * Ticker for doing render updates. + * @member {PIXI.ticker.Ticker} + * @default PIXI.ticker.shared + */ + this.ticker = useSharedTicker ? _ticker.shared : new _ticker.Ticker(); + + // Start the rendering + this.start(); + } + + /** + * Render the current stage. + */ + Application.prototype.render = function render() { + this.renderer.render(this.stage); + }; + + /** + * Convenience method for stopping the render. + */ + + + Application.prototype.stop = function stop() { + this._ticker.stop(); + }; + + /** + * Convenience method for starting the render. + */ + + + Application.prototype.start = function start() { + this._ticker.start(); + }; + + /** + * Reference to the renderer's canvas element. + * @member {HTMLCanvasElement} + * @readonly + */ + + + /** + * Destroy and don't use after this. + * @param {Boolean} [removeView=false] Automatically remove canvas from DOM. + */ + Application.prototype.destroy = function destroy(removeView) { + this.stop(); + this.ticker = null; + + this.stage.destroy(); + this.stage = null; + + this.renderer.destroy(removeView); + this.renderer = null; + }; + + _createClass(Application, [{ + key: 'ticker', + set: function set(ticker) // eslint-disable-line require-jsdoc + { + if (this._ticker) { + this._ticker.remove(this.render, this); + } + this._ticker = ticker; + if (ticker) { + ticker.add(this.render, this); + } + }, + get: function get() // eslint-disable-line require-jsdoc + { + return this._ticker; + } + }, { + key: 'view', + get: function get() { + return this.renderer.view; + } + + /** + * Reference to the renderer's screen rectangle. Its safe to use as filterArea or hitArea for whole screen + * @member {PIXI.Rectangle} + * @readonly + */ + + }, { + key: 'screen', + get: function get() { + return this.renderer.screen; + } + }]); + + return Application; +}(); + +exports.default = Application; + +},{"./autoDetectRenderer":43,"./display/Container":46,"./ticker":116}],42:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function checkPrecision(src, def) { + if (src instanceof Array) { + if (src[0].substring(0, 9) !== 'precision') { + var copy = src.slice(0); + + copy.unshift('precision ' + def + ' float;'); + + return copy; + } + } else if (src.substring(0, 9) !== 'precision') { + return 'precision ' + def + ' float;\n' + src; + } + + return src; +} + +/** + * Wrapper class, webGL Shader for Pixi. + * Adds precision string if vertexSrc or fragmentSrc have no mention of it. + * + * @class + * @extends GLShader + * @memberof PIXI + */ + +var Shader = function (_GLShader) { + _inherits(Shader, _GLShader); + + /** + * + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + * @param {string|string[]} vertexSrc - The vertex shader source as an array of strings. + * @param {string|string[]} fragmentSrc - The fragment shader source as an array of strings. + */ + function Shader(gl, vertexSrc, fragmentSrc) { + _classCallCheck(this, Shader); + + return _possibleConstructorReturn(this, _GLShader.call(this, gl, checkPrecision(vertexSrc, _settings2.default.PRECISION_VERTEX), checkPrecision(fragmentSrc, _settings2.default.PRECISION_FRAGMENT))); + } + + return Shader; +}(_pixiGlCore.GLShader); + +exports.default = Shader; + +},{"./settings":99,"pixi-gl-core":12}],43:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = autoDetectRenderer; + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by + * the browser then this function will return a canvas renderer + * + * @memberof PIXI + * @function autoDetectRenderer + * @param {number} [width=800] - the width of the renderers view + * @param {number} [height=600] - the height of the renderers view + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [noWebGL=false] - prevents selection of WebGL renderer, even if such is present + * @return {PIXI.WebGLRenderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ +function autoDetectRenderer() { + var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 800; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 600; + var options = arguments[2]; + var noWebGL = arguments[3]; + + if (!noWebGL && utils.isWebGLSupported()) { + return new _WebGLRenderer2.default(width, height, options); + } + + return new _CanvasRenderer2.default(width, height, options); +} + +},{"./renderers/canvas/CanvasRenderer":75,"./renderers/webgl/WebGLRenderer":82,"./utils":120}],44:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * String of the current PIXI version. + * + * @static + * @constant + * @memberof PIXI + * @name VERSION + * @type {string} + */ +var VERSION = exports.VERSION = '4.4.4'; + +/** + * Two Pi. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var PI_2 = exports.PI_2 = Math.PI * 2; + +/** + * Conversion factor for converting radians to degrees. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var RAD_TO_DEG = exports.RAD_TO_DEG = 180 / Math.PI; + +/** + * Conversion factor for converting degrees to radians. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var DEG_TO_RAD = exports.DEG_TO_RAD = Math.PI / 180; + +/** + * Constant to identify the Renderer Type. + * + * @static + * @constant + * @memberof PIXI + * @name RENDERER_TYPE + * @type {object} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ +var RENDERER_TYPE = exports.RENDERER_TYPE = { + UNKNOWN: 0, + WEBGL: 1, + CANVAS: 2 +}; + +/** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * + * @static + * @constant + * @memberof PIXI + * @name BLEND_MODES + * @type {object} + * @property {number} NORMAL + * @property {number} ADD + * @property {number} MULTIPLY + * @property {number} SCREEN + * @property {number} OVERLAY + * @property {number} DARKEN + * @property {number} LIGHTEN + * @property {number} COLOR_DODGE + * @property {number} COLOR_BURN + * @property {number} HARD_LIGHT + * @property {number} SOFT_LIGHT + * @property {number} DIFFERENCE + * @property {number} EXCLUSION + * @property {number} HUE + * @property {number} SATURATION + * @property {number} COLOR + * @property {number} LUMINOSITY + */ +var BLEND_MODES = exports.BLEND_MODES = { + NORMAL: 0, + ADD: 1, + MULTIPLY: 2, + SCREEN: 3, + OVERLAY: 4, + DARKEN: 5, + LIGHTEN: 6, + COLOR_DODGE: 7, + COLOR_BURN: 8, + HARD_LIGHT: 9, + SOFT_LIGHT: 10, + DIFFERENCE: 11, + EXCLUSION: 12, + HUE: 13, + SATURATION: 14, + COLOR: 15, + LUMINOSITY: 16 +}; + +/** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * + * @static + * @constant + * @memberof PIXI + * @name DRAW_MODES + * @type {object} + * @property {number} POINTS + * @property {number} LINES + * @property {number} LINE_LOOP + * @property {number} LINE_STRIP + * @property {number} TRIANGLES + * @property {number} TRIANGLE_STRIP + * @property {number} TRIANGLE_FAN + */ +var DRAW_MODES = exports.DRAW_MODES = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6 +}; + +/** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @static + * @constant + * @memberof PIXI + * @name SCALE_MODES + * @type {object} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ +var SCALE_MODES = exports.SCALE_MODES = { + LINEAR: 0, + NEAREST: 1 +}; + +/** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wraping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as webGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * + * @static + * @constant + * @name WRAP_MODES + * @memberof PIXI + * @type {object} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ +var WRAP_MODES = exports.WRAP_MODES = { + CLAMP: 0, + REPEAT: 1, + MIRRORED_REPEAT: 2 +}; + +/** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for pixi textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * + * @static + * @constant + * @name GC_MODES + * @memberof PIXI + * @type {object} + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ +var GC_MODES = exports.GC_MODES = { + AUTO: 0, + MANUAL: 1 +}; + +/** + * Regexp for image type by extension. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `image.png` + */ +var URL_FILE_EXTENSION = exports.URL_FILE_EXTENSION = /\.(\w{3,4})(?:$|\?|#)/i; + +/** + * Regexp for data URI. + * Based on: {@link https://github.com/ragingwind/data-uri-regex} + * + * @static + * @constant + * @name DATA_URI + * @memberof PIXI + * @type {RegExp|string} + * @example data:image/png;base64 + */ +var DATA_URI = exports.DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;(charset=[\w-]+|base64))?,(.*)/i; + +/** + * Regexp for SVG size. + * + * @static + * @constant + * @name SVG_SIZE + * @memberof PIXI + * @type {RegExp|string} + * @example <svg width="100" height="100"></svg> + */ +var SVG_SIZE = exports.SVG_SIZE = /]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len + +/** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * + * @static + * @constant + * @name SHAPES + * @memberof PIXI + * @type {object} + * @property {number} POLY Polygon + * @property {number} RECT Rectangle + * @property {number} CIRC Circle + * @property {number} ELIP Ellipse + * @property {number} RREC Rounded Rectangle + */ +var SHAPES = exports.SHAPES = { + POLY: 0, + RECT: 1, + CIRC: 2, + ELIP: 3, + RREC: 4 +}; + +/** + * Constants that specify float precision in shaders. + * + * @static + * @constant + * @name PRECISION + * @memberof PIXI + * @type {object} + * @property {string} LOW='lowp' + * @property {string} MEDIUM='mediump' + * @property {string} HIGH='highp' + */ +var PRECISION = exports.PRECISION = { + LOW: 'lowp', + MEDIUM: 'mediump', + HIGH: 'highp' +}; + +/** + * Constants that specify the transform type. + * + * @static + * @constant + * @name TRANSFORM_MODE + * @memberof PIXI + * @type {object} + * @property {number} STATIC + * @property {number} DYNAMIC + */ +var TRANSFORM_MODE = exports.TRANSFORM_MODE = { + STATIC: 0, + DYNAMIC: 1 +}; + +/** + * Constants that define the type of gradient on text. + * + * @static + * @constant + * @name TEXT_GRADIENT + * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL Vertical gradient + * @property {number} LINEAR_HORIZONTAL Linear gradient + */ +var TEXT_GRADIENT = exports.TEXT_GRADIENT = { + LINEAR_VERTICAL: 0, + LINEAR_HORIZONTAL: 1 +}; + +},{}],45:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * 'Builder' pattern for bounds rectangles + * Axis-Aligned Bounding Box + * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems + * + * @class + * @memberof PIXI + */ +var Bounds = function () { + /** + * + */ + function Bounds() { + _classCallCheck(this, Bounds); + + /** + * @member {number} + * @default 0 + */ + this.minX = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.minY = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxX = -Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxY = -Infinity; + + this.rect = null; + } + + /** + * Checks if bounds are empty. + * + * @return {boolean} True if empty. + */ + + + Bounds.prototype.isEmpty = function isEmpty() { + return this.minX > this.maxX || this.minY > this.maxY; + }; + + /** + * Clears the bounds and resets. + * + */ + + + Bounds.prototype.clear = function clear() { + this.updateID++; + + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * + * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty + * @returns {PIXI.Rectangle} A rectangle of the bounds + */ + + + Bounds.prototype.getRectangle = function getRectangle(rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return _math.Rectangle.EMPTY; + } + + rect = rect || new _math.Rectangle(0, 0, 1, 1); + + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + + return rect; + }; + + /** + * This function should be inlined when its possible. + * + * @param {PIXI.Point} point - The point to add. + */ + + + Bounds.prototype.addPoint = function addPoint(point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + }; + + /** + * Adds a quad, not transformed + * + * @param {Float32Array} vertices - The verts to add. + */ + + + Bounds.prototype.addQuad = function addQuad(vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = vertices[0]; + var y = vertices[1]; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds sprite frame, transformed. + * + * @param {PIXI.TransformBase} transform - TODO + * @param {number} x0 - TODO + * @param {number} y0 - TODO + * @param {number} x1 - TODO + * @param {number} y1 - TODO + */ + + + Bounds.prototype.addFrame = function addFrame(transform, x0, y0, x1, y1) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = a * x0 + c * y0 + tx; + var y = b * x0 + d * y0 + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y0 + tx; + y = b * x1 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x0 + c * y1 + tx; + y = b * x0 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y1 + tx; + y = b * x1 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Add an array of vertices + * + * @param {PIXI.TransformBase} transform - TODO + * @param {Float32Array} vertices - TODO + * @param {number} beginOffset - TODO + * @param {number} endOffset - TODO + */ + + + Bounds.prototype.addVertices = function addVertices(transform, vertices, beginOffset, endOffset) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = a * rawX + c * rawY + tx; + var y = d * rawY + b * rawX + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds other Bounds + * + * @param {PIXI.Bounds} bounds - TODO + */ + + + Bounds.prototype.addBounds = function addBounds(bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + }; + + /** + * Adds other Bounds, masked with Bounds + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Bounds} mask - TODO + */ + + + Bounds.prototype.addBoundsMask = function addBoundsMask(bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + /** + * Adds other Bounds, masked with Rectangle + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Rectangle} area - TODO + */ + + + Bounds.prototype.addBoundsArea = function addBoundsArea(bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : area.x + area.width; + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : area.y + area.height; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + return Bounds; +}(); + +exports.default = Bounds; + +},{"../math":68}],46:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _DisplayObject2 = require('./DisplayObject'); + +var _DisplayObject3 = _interopRequireDefault(_DisplayObject2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A Container represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + *```js + * let container = new PIXI.Container(); + * container.addChild(sprite); + * ``` + * + * @class + * @extends PIXI.DisplayObject + * @memberof PIXI + */ +var Container = function (_DisplayObject) { + _inherits(Container, _DisplayObject); + + /** + * + */ + function Container() { + _classCallCheck(this, Container); + + /** + * The array of children of this container. + * + * @member {PIXI.DisplayObject[]} + * @readonly + */ + var _this = _possibleConstructorReturn(this, _DisplayObject.call(this)); + + _this.children = []; + return _this; + } + + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified + * + * @private + */ + + + Container.prototype.onChildrenChange = function onChildrenChange() {} + /* empty */ + + + /** + * Adds one or more children to the container. + * + * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container + * @return {PIXI.DisplayObject} The first child that was added. + */ + ; + + Container.prototype.addChild = function addChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.addChild(arguments[i]); + } + } else { + // if the child has a parent then lets remove it as Pixi objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.push(child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + child.emit('added', this); + } + + return child; + }; + + /** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @return {PIXI.DisplayObject} The child that was added. + */ + + + Container.prototype.addChildAt = function addChildAt(child, index) { + if (index < 0 || index > this.children.length) { + throw new Error(child + 'addChildAt: The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.splice(index, 0, child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + + return child; + }; + + /** + * Swaps the position of 2 Display Objects within this container. + * + * @param {PIXI.DisplayObject} child - First display object to swap + * @param {PIXI.DisplayObject} child2 - Second display object to swap + */ + + + Container.prototype.swapChildren = function swapChildren(child, child2) { + if (child === child2) { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; + + /** + * Returns the index position of a child DisplayObject instance + * + * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify + * @return {number} The index position of the child display object to identify + */ + + + Container.prototype.getChildIndex = function getChildIndex(child) { + var index = this.children.indexOf(child); + + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + }; + + /** + * Changes the position of an existing child in the display object container + * + * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number + * @param {number} index - The resulting index number for the child display object + */ + + + Container.prototype.setChildIndex = function setChildIndex(child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + (0, _utils.removeItems)(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + + this.onChildrenChange(index); + }; + + /** + * Returns the child at the specified index + * + * @param {number} index - The index to get the child at + * @return {PIXI.DisplayObject} The child at the given index, if any. + */ + + + Container.prototype.getChildAt = function getChildAt(index) { + if (index < 0 || index >= this.children.length) { + throw new Error('getChildAt: Index (' + index + ') does not exist.'); + } + + return this.children[index]; + }; + + /** + * Removes one or more children from the container. + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove + * @return {PIXI.DisplayObject} The first child that was removed. + */ + + + Container.prototype.removeChild = function removeChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.removeChild(arguments[i]); + } + } else { + var index = this.children.indexOf(child); + + if (index === -1) return null; + + child.parent = null; + // ensure child transform will be recalculated + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + } + + return child; + }; + + /** + * Removes a child from the specified index position. + * + * @param {number} index - The index to get the child from + * @return {PIXI.DisplayObject} The child that was removed. + */ + + + Container.prototype.removeChildAt = function removeChildAt(index) { + var child = this.getChildAt(index); + + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + + return child; + }; + + /** + * Removes all children from this container that are within the begin and end indexes. + * + * @param {number} [beginIndex=0] - The beginning position. + * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. + * @returns {DisplayObject[]} List of removed children + */ + + + Container.prototype.removeChildren = function removeChildren() { + var beginIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var endIndex = arguments[1]; + + var begin = beginIndex; + var end = typeof endIndex === 'number' ? endIndex : this.children.length; + var range = end - begin; + var removed = void 0; + + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } + + this._boundsID++; + + this.onChildrenChange(beginIndex); + + for (var _i = 0; _i < removed.length; ++_i) { + removed[_i].emit('removed', this); + } + + return removed; + } else if (range === 0 && this.children.length === 0) { + return []; + } + + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + }; + + /** + * Updates the transform on all children of this container for rendering + */ + + + Container.prototype.updateTransform = function updateTransform() { + this._boundsID++; + + this.transform.updateTransform(this.parent.transform); + + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + + if (child.visible) { + child.updateTransform(); + } + } + }; + + /** + * Recalculates the bounds of the container. + * + */ + + + Container.prototype.calculateBounds = function calculateBounds() { + this._bounds.clear(); + + this._calculateBounds(); + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (!child.visible || !child.renderable) { + continue; + } + + child.calculateBounds(); + + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + child._mask.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, child._mask._bounds); + } else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } else { + this._bounds.addBounds(child._bounds); + } + } + + this._lastBoundsID = this._boundsID; + }; + + /** + * Recalculates the bounds of the object. Override this to + * calculate the bounds of the specific object (not including children). + * + */ + + + Container.prototype._calculateBounds = function _calculateBounds() {} + // FILL IN// + + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderWebGL = function renderWebGL(renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + // do a quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) { + this.renderAdvancedWebGL(renderer); + } else { + this._renderWebGL(renderer); + + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderWebGL(renderer); + } + } + }; + + /** + * Render the object using the WebGL renderer and advanced features. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { + renderer.flush(); + + var filters = this._filters; + var mask = this._mask; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + + this._enabledFilters.length = 0; + + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + + if (this._enabledFilters.length) { + renderer.filterManager.pushFilter(this, this._enabledFilters); + } + } + + if (mask) { + renderer.maskManager.pushMask(this, this._mask); + } + + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); + + // now loop through the children and make sure they get rendered + for (var _i2 = 0, j = this.children.length; _i2 < j; _i2++) { + this.children[_i2].renderWebGL(renderer); + } + + renderer.flush(); + + if (mask) { + renderer.maskManager.popMask(this, this._mask); + } + + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filterManager.popFilter(); + } + }; + + /** + * To be overridden by the subclasses. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype._renderWebGL = function _renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * To be overridden by the subclass + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype._renderCanvas = function _renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderCanvas = function renderCanvas(renderer) { + // if not visible or the alpha is 0 then no need to render this + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + if (this._mask) { + renderer.maskManager.pushMask(this._mask); + } + + this._renderCanvas(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderCanvas(renderer); + } + + if (this._mask) { + renderer.maskManager.popMask(renderer); + } + }; + + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Container.prototype.destroy = function destroy(options) { + _DisplayObject.prototype.destroy.call(this); + + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + + var oldChildren = this.removeChildren(0, this.children.length); + + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + }; + + /** + * The width of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Container, [{ + key: 'width', + get: function get() { + return this.scale.x * this.getLocalBounds().width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var width = this.getLocalBounds().width; + + if (width !== 0) { + this.scale.x = value / width; + } else { + this.scale.x = 1; + } + + this._width = value; + } + + /** + * The height of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.scale.y * this.getLocalBounds().height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var height = this.getLocalBounds().height; + + if (height !== 0) { + this.scale.y = value / height; + } else { + this.scale.y = 1; + } + + this._height = value; + } + }]); + + return Container; +}(_DisplayObject3.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = Container; +Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + +},{"../utils":120,"./DisplayObject":47}],47:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TransformStatic = require('./TransformStatic'); + +var _TransformStatic2 = _interopRequireDefault(_TransformStatic); + +var _Transform = require('./Transform'); + +var _Transform2 = _interopRequireDefault(_Transform); + +var _Bounds = require('./Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _math = require('../math'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// _tempDisplayObjectParent = new DisplayObject(); + +/** + * The base class for all objects that are rendered on the screen. + * This is an abstract class and should not be used on its own rather it should be extended. + * + * @class + * @extends EventEmitter + * @mixes PIXI.interaction.interactiveTarget + * @memberof PIXI + */ +var DisplayObject = function (_EventEmitter) { + _inherits(DisplayObject, _EventEmitter); + + /** + * + */ + function DisplayObject() { + _classCallCheck(this, DisplayObject); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + var TransformClass = _settings2.default.TRANSFORM_MODE === _const.TRANSFORM_MODE.STATIC ? _TransformStatic2.default : _Transform2.default; + + _this.tempDisplayObjectParent = null; + + // TODO: need to create Transform from factory + /** + * World transform and local transform of this object. + * This will become read-only later, please do not assign anything there unless you know what are you doing + * + * @member {PIXI.TransformBase} + */ + _this.transform = new TransformClass(); + + /** + * The opacity of the object. + * + * @member {number} + */ + _this.alpha = 1; + + /** + * The visibility of the object. If false the object will not be drawn, and + * the updateTransform function will not be called. + * + * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually + * + * @member {boolean} + */ + _this.visible = true; + + /** + * Can this object be rendered, if false the object will not be drawn but the updateTransform + * methods will still be called. + * + * Only affects recursive calls from parent. You can ask for bounds manually + * + * @member {boolean} + */ + _this.renderable = true; + + /** + * The display object container that contains this display object. + * + * @member {PIXI.Container} + * @readonly + */ + _this.parent = null; + + /** + * The multiplied alpha of the displayObject + * + * @member {number} + * @readonly + */ + _this.worldAlpha = 1; + + /** + * The area the filter is applied to. This is used as more of an optimisation + * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle + * + * Also works as an interaction mask + * + * @member {PIXI.Rectangle} + */ + _this.filterArea = null; + + _this._filters = null; + _this._enabledFilters = null; + + /** + * The bounds object, this is used to calculate and store the bounds of the displayObject + * + * @member {PIXI.Rectangle} + * @private + */ + _this._bounds = new _Bounds2.default(); + _this._boundsID = 0; + _this._lastBoundsID = -1; + _this._boundsRect = null; + _this._localBoundsRect = null; + + /** + * The original, cached mask of the object + * + * @member {PIXI.Graphics|PIXI.Sprite} + * @private + */ + _this._mask = null; + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + return _this; + } + + /** + * @private + * @member {PIXI.DisplayObject} + */ + + + /** + * Updates the object transform for rendering + * + * TODO - Optimization pass! + */ + DisplayObject.prototype.updateTransform = function updateTransform() { + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + this._bounds.updateID++; + }; + + /** + * recursively updates transform of all objects from the root to this one + * internal function for toLocal() + */ + + + DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform() { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + }; + + /** + * Retrieves the bounds of the displayObject as a rectangle object. + * + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @param {PIXI.Rectangle} rect - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getBounds = function getBounds(skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + + if (this._boundsID !== this._lastBoundsID) { + this.calculateBounds(); + } + + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new _math.Rectangle(); + } + + rect = this._boundsRect; + } + + return this._bounds.getRectangle(rect); + }; + + /** + * Retrieves the local bounds of the displayObject as a rectangle object + * + * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getLocalBounds = function getLocalBounds(rect) { + var transformRef = this.transform; + var parentRef = this.parent; + + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + var bounds = this.getBounds(false, rect); + + this.parent = parentRef; + this.transform = transformRef; + + return bounds; + }; + + /** + * Calculates the global position of the display object + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform. + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toGlobal = function toGlobal(position, point) { + var skipUpdate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; + + /** + * Calculates the local position of the display object relative to another point + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toLocal = function toLocal(position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + DisplayObject.prototype.renderCanvas = function renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Set the parent Container of this DisplayObject + * + * @param {PIXI.Container} container - The Container to add this DisplayObject to + * @return {PIXI.Container} The Container that this DisplayObject was added to + */ + ; + + DisplayObject.prototype.setParent = function setParent(container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); + } + + container.addChild(this); + + return container; + }; + + /** + * Convenience function to set the position, scale, skew and pivot at once. + * + * @param {number} [x=0] - The X position + * @param {number} [y=0] - The Y position + * @param {number} [scaleX=1] - The X scale value + * @param {number} [scaleY=1] - The Y scale value + * @param {number} [rotation=0] - The rotation + * @param {number} [skewX=0] - The X skew value + * @param {number} [skewY=0] - The Y skew value + * @param {number} [pivotX=0] - The X pivot value + * @param {number} [pivotY=0] - The Y pivot value + * @return {PIXI.DisplayObject} The DisplayObject instance + */ + + + DisplayObject.prototype.setTransform = function setTransform() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var scaleX = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var scaleY = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var rotation = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var skewX = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + var skewY = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + var pivotX = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; + var pivotY = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0; + + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + + return this; + }; + + /** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy`. + * + */ + + + DisplayObject.prototype.destroy = function destroy() { + this.removeAllListeners(); + if (this.parent) { + this.parent.removeChild(this); + } + this.transform = null; + + this.parent = null; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this.filterArea = null; + + this.interactive = false; + this.interactiveChildren = false; + + this._destroyed = true; + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + * + * @member {number} + */ + + + _createClass(DisplayObject, [{ + key: '_tempDisplayObjectParent', + get: function get() { + if (this.tempDisplayObjectParent === null) { + this.tempDisplayObjectParent = new DisplayObject(); + } + + return this.tempDisplayObjectParent; + } + }, { + key: 'x', + get: function get() { + return this.position.x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.x = value; + } + + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + * + * @member {number} + */ + + }, { + key: 'y', + get: function get() { + return this.position.y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.y = value; + } + + /** + * Current transform of the object based on world (parent) factors + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'worldTransform', + get: function get() { + return this.transform.worldTransform; + } + + /** + * Current transform of the object based on local factors: position, scale, other stuff + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'localTransform', + get: function get() { + return this.transform.localTransform; + } + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'position', + get: function get() { + return this.transform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.copy(value); + } + + /** + * The scale factor of the object. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'scale', + get: function get() { + return this.transform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.scale.copy(value); + } + + /** + * The pivot point of the displayObject that it rotates around + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'pivot', + get: function get() { + return this.transform.pivot; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.pivot.copy(value); + } + + /** + * The skew factor for the object in radians. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'skew', + get: function get() { + return this.transform.skew; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.skew.copy(value); + } + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + }, { + key: 'rotation', + get: function get() { + return this.transform.rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.rotation = value; + } + + /** + * Indicates if the object is globally visible. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'worldVisible', + get: function get() { + var item = this; + + do { + if (!item.visible) { + return false; + } + + item = item.parent; + } while (item); + + return true; + } + + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PIXI a regular mask must be a + * PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it + * utilises shape clipping. To remove a mask, set this property to null. + * + * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + * + * @member {PIXI.Graphics|PIXI.Sprite} + */ + + }, { + key: 'mask', + get: function get() { + return this._mask; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._mask) { + this._mask.renderable = true; + } + + this._mask = value; + + if (this._mask) { + this._mask.renderable = false; + } + } + + /** + * Sets the filters for the displayObject. + * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * To remove filters simply set this property to 'null' + * + * @member {PIXI.Filter[]} + */ + + }, { + key: 'filters', + get: function get() { + return this._filters && this._filters.slice(); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._filters = value && value.slice(); + } + }]); + + return DisplayObject; +}(_eventemitter2.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = DisplayObject; +DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + +},{"../const":44,"../math":68,"../settings":99,"./Bounds":45,"./Transform":48,"./TransformStatic":50,"eventemitter3":3}],48:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Generic class to deal with traditional 2D matrix transforms + * local transformation is calculated from position,scale,skew and rotation + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var Transform = function (_TransformBase) { + _inherits(Transform, _TransformBase); + + /** + * + */ + function Transform() { + _classCallCheck(this, Transform); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.Point} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.Point(0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.Point} + */ + _this.scale = new _math.Point(1, 1); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.Point} + */ + _this.pivot = new _math.Point(0, 0); + + /** + * The rotation value of the object, in radians + * + * @member {Number} + * @private + */ + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + return _this; + } + + /** + * Updates the skew values when the skew or rotation changes. + * + * @private + */ + + + Transform.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + }; + + /** + * Updates only local matrix + */ + + + Transform.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + Transform.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + Transform.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(Transform, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return Transform; +}(_TransformBase3.default); + +exports.default = Transform; + +},{"../math":68,"./TransformBase":49}],49:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Generic class to deal with traditional 2D matrix transforms + * + * @class + * @memberof PIXI + */ +var TransformBase = function () { + /** + * + */ + function TransformBase() { + _classCallCheck(this, TransformBase); + + /** + * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds() + * + * @member {PIXI.Matrix} + */ + this.worldTransform = new _math.Matrix(); + + /** + * The local matrix transform + * + * @member {PIXI.Matrix} + */ + this.localTransform = new _math.Matrix(); + + this._worldID = 0; + this._parentID = 0; + } + + /** + * TransformBase does not have decomposition, so this function wont do anything + */ + + + TransformBase.prototype.updateLocalTransform = function updateLocalTransform() {} + // empty + + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.TransformBase} parentTransform - The transform of the parent of this object + */ + ; + + TransformBase.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + return TransformBase; +}(); + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ + + +exports.default = TransformBase; +TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; + +TransformBase.IDENTITY = new TransformBase(); + +},{"../math":68}],50:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Transform that takes care about its versions + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var TransformStatic = function (_TransformBase) { + _inherits(TransformStatic, _TransformBase); + + /** + * + */ + function TransformStatic() { + _classCallCheck(this, TransformStatic); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.ObservablePoint} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.ObservablePoint} + */ + _this.scale = new _math.ObservablePoint(_this.onChange, _this, 1, 1); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.ObservablePoint} + */ + _this.pivot = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + + _this._localID = 0; + _this._currentLocalID = 0; + return _this; + } + + /** + * Called when a value changes. + * + * @private + */ + + + TransformStatic.prototype.onChange = function onChange() { + this._localID++; + }; + + /** + * Called when skew or rotation changes + * + * @private + */ + + + TransformStatic.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + + this._localID++; + }; + + /** + * Updates only local matrix + */ + + + TransformStatic.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + TransformStatic.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._parentID = parentTransform._worldID; + + // update the id of the transform.. + this._worldID++; + } + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + TransformStatic.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + this._localID++; + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(TransformStatic, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return TransformStatic; +}(_TransformBase3.default); + +exports.default = TransformStatic; + +},{"../math":68,"./TransformBase":49}],51:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _GraphicsData = require('./GraphicsData'); + +var _GraphicsData2 = _interopRequireDefault(_GraphicsData); + +var _Sprite = require('../sprites/Sprite'); + +var _Sprite2 = _interopRequireDefault(_Sprite); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Bounds = require('../display/Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _bezierCurveTo2 = require('./utils/bezierCurveTo'); + +var _bezierCurveTo3 = _interopRequireDefault(_bezierCurveTo2); + +var _CanvasRenderer = require('../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var canvasRenderer = void 0; +var tempMatrix = new _math.Matrix(); +var tempPoint = new _math.Point(); +var tempColor1 = new Float32Array(4); +var tempColor2 = new Float32Array(4); + +/** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Graphics = function (_Container) { + _inherits(Graphics, _Container); + + /** + * + * @param {boolean} [nativeLines=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + */ + function Graphics() { + var nativeLines = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + _classCallCheck(this, Graphics); + + /** + * The alpha value used when filling the Graphics object. + * + * @member {number} + * @default 1 + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @member {number} + * @default 0 + */ + _this.lineWidth = 0; + + /** + * If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * + * @member {boolean} + */ + _this.nativeLines = nativeLines; + + /** + * The color of any lines drawn. + * + * @member {string} + * @default 0 + */ + _this.lineColor = 0; + + /** + * Graphics data + * + * @member {PIXI.GraphicsData[]} + * @private + */ + _this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to + * reset the tint. + * + * @member {number} + * @default 0xFFFFFF + */ + _this.tint = 0xFFFFFF; + + /** + * The previous tint applied to the graphic shape. Used to compare to the current tint and + * check if theres change. + * + * @member {number} + * @private + * @default 0xFFFFFF + */ + _this._prevTint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * Current path + * + * @member {PIXI.GraphicsData} + * @private + */ + _this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @member {object} + * @private + */ + // TODO - _webgl should use a prototype object, not a random undocumented object... + _this._webGL = {}; + + /** + * Whether this shape is being used as a mask. + * + * @member {boolean} + */ + _this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @member {number} + */ + _this.boundsPadding = 0; + + /** + * A cache of the local bounds to prevent recalculation. + * + * @member {PIXI.Rectangle} + * @private + */ + _this._localBounds = new _Bounds2.default(); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics + * object will be recalculated. + * + * @member {boolean} + * @private + */ + _this.dirty = 0; + + /** + * Used to detect if we need to do a fast rect check using the id compare method + * @type {Number} + */ + _this.fastRectDirty = -1; + + /** + * Used to detect if we clear the graphics webGL data + * @type {Number} + */ + _this.clearDirty = 0; + + /** + * Used to detect if we we need to recalculate local bounds + * @type {Number} + */ + _this.boundsDirty = -1; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @member {boolean} + * @private + */ + _this.cachedSpriteDirty = false; + + _this._spriteRect = null; + _this._fastRect = false; + + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ + return _this; + } + + /** + * Creates a new Graphics object with the same values as this one. + * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) + * + * @return {PIXI.Graphics} A clone of the graphics object + */ + + + Graphics.prototype.clone = function clone() { + var clone = new Graphics(); + + clone.renderable = this.renderable; + clone.fillAlpha = this.fillAlpha; + clone.lineWidth = this.lineWidth; + clone.lineColor = this.lineColor; + clone.tint = this.tint; + clone.blendMode = this.blendMode; + clone.isMask = this.isMask; + clone.boundsPadding = this.boundsPadding; + clone.dirty = 0; + clone.cachedSpriteDirty = this.cachedSpriteDirty; + + // copy graphics data + for (var i = 0; i < this.graphicsData.length; ++i) { + clone.graphicsData.push(this.graphicsData[i].clone()); + } + + clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; + + clone.updateLocalBounds(); + + return clone; + }; + + /** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() + * method or the drawCircle() method. + * + * @param {number} [lineWidth=0] - width of the line to draw, will update the objects stored style + * @param {number} [color=0] - color of the line to draw, will update the objects stored style + * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineStyle = function lineStyle() { + var lineWidth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var alpha = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + + this.lineWidth = lineWidth; + this.lineColor = color; + this.lineAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length) { + // halfway through a line? start a new one! + var shape = new _math.Polygon(this.currentPath.shape.points.slice(-2)); + + shape.closed = false; + + this.drawShape(shape); + } else { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + }; + + /** + * Moves the current drawing position to x, y. + * + * @param {number} x - the X coordinate to move to + * @param {number} y - the Y coordinate to move to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.moveTo = function moveTo(x, y) { + var shape = new _math.Polygon([x, y]); + + shape.closed = false; + this.drawShape(shape); + + return this; + }; + + /** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @param {number} x - the X coordinate to draw to + * @param {number} y - the Y coordinate to draw to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineTo = function lineTo(x, y) { + this.currentPath.shape.points.push(x, y); + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.quadraticCurveTo = function quadraticCurveTo(cpX, cpY, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var n = 20; + var points = this.currentPath.shape.points; + var xa = 0; + var ya = 0; + + if (points.length === 0) { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + for (var i = 1; i <= n; ++i) { + var j = i / n; + + xa = fromX + (cpX - fromX) * j; + ya = fromY + (cpY - fromY) * j; + + points.push(xa + (cpX + (toX - cpX) * j - xa) * j, ya + (cpY + (toY - cpY) * j - ya) * j); + } + + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a bezier curve and then draws it. + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.bezierCurveTo = function bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + points.length -= 2; + + (0, _bezierCurveTo3.default)(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, points); + + this.dirty++; + + return this; + }; + + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @param {number} x1 - The x-coordinate of the beginning of the arc + * @param {number} y1 - The y-coordinate of the beginning of the arc + * @param {number} x2 - The x-coordinate of the end of the arc + * @param {number} y2 - The y-coordinate of the end of the arc + * @param {number} radius - The radius of the arc + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arcTo = function arcTo(x1, y1, x2, y2, radius) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points.push(x1, y1); + } + } else { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + } else { + var dd = a1 * a1 + b1 * b1; + var cc = a2 * a2 + b2 * b2; + var tt = a1 * a2 + b1 * b2; + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = k1 * b2 + k2 * b1; + var cy = k1 * a2 + k2 * a1; + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty++; + + return this; + }; + + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @param {number} cx - The x-coordinate of the center of the circle + * @param {number} cy - The y-coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param {number} endAngle - The ending angle, in radians + * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arc = function arc(cx, cy, radius, startAngle, endAngle) { + var anticlockwise = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; + + if (startAngle === endAngle) { + return this; + } + + if (!anticlockwise && endAngle <= startAngle) { + endAngle += Math.PI * 2; + } else if (anticlockwise && startAngle <= endAngle) { + startAngle += Math.PI * 2; + } + + var sweep = endAngle - startAngle; + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * 40; + + if (sweep === 0) { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. + var points = this.currentPath ? this.currentPath.shape.points : null; + + if (points) { + if (points[points.length - 2] !== startX || points[points.length - 1] !== startY) { + points.push(startX, startY); + } + } else { + this.moveTo(startX, startY); + points = this.currentPath.shape.points; + } + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = segMinus % 1 / segMinus; + + for (var i = 0; i <= segMinus; ++i) { + var real = i + remainder * i; + + var angle = theta + startAngle + theta2 * real; + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push((cTheta * c + sTheta * s) * radius + cx, (cTheta * -s + sTheta * c) * radius + cy); + } + + this.dirty++; + + return this; + }; + + /** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @param {number} [color=0] - the color of the fill + * @param {number} [alpha=1] - the alpha of the fill + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.beginFill = function beginFill() { + var color = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var alpha = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.filling = true; + this.fillColor = color; + this.fillAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length <= 2) { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + }; + + /** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.endFill = function endFill() { + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRect = function drawRect(x, y, width, height) { + this.drawShape(new _math.Rectangle(x, y, width, height)); + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @param {number} radius - Radius of the rectangle corners + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRoundedRect = function drawRoundedRect(x, y, width, height, radius) { + this.drawShape(new _math.RoundedRectangle(x, y, width, height, radius)); + + return this; + }; + + /** + * Draws a circle. + * + * @param {number} x - The X coordinate of the center of the circle + * @param {number} y - The Y coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawCircle = function drawCircle(x, y, radius) { + this.drawShape(new _math.Circle(x, y, radius)); + + return this; + }; + + /** + * Draws an ellipse. + * + * @param {number} x - The X coordinate of the center of the ellipse + * @param {number} y - The Y coordinate of the center of the ellipse + * @param {number} width - The half width of the ellipse + * @param {number} height - The half height of the ellipse + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawEllipse = function drawEllipse(x, y, width, height) { + this.drawShape(new _math.Ellipse(x, y, width, height)); + + return this; + }; + + /** + * Draws a polygon using the given path. + * + * @param {number[]|PIXI.Point[]} path - The path data used to construct the polygon. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawPolygon = function drawPolygon(path) { + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + var closed = true; + + if (points instanceof _math.Polygon) { + closed = points.closed; + points = points.points; + } + + if (!Array.isArray(points)) { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) { + points[i] = arguments[i]; // eslint-disable-line prefer-rest-params + } + } + + var shape = new _math.Polygon(points); + + shape.closed = closed; + + this.drawShape(shape); + + return this; + }; + + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.clear = function clear() { + if (this.lineWidth || this.filling || this.graphicsData.length > 0) { + this.lineWidth = 0; + this.filling = false; + + this.boundsDirty = -1; + this.dirty++; + this.clearDirty++; + this.graphicsData.length = 0; + } + + this.currentPath = null; + this._spriteRect = null; + + return this; + }; + + /** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. + * + * @returns {boolean} True if only 1 rect. + */ + + + Graphics.prototype.isFastRect = function isFastRect() { + return this.graphicsData.length === 1 && this.graphicsData[0].shape.type === _const.SHAPES.RECT && !this.graphicsData[0].lineWidth; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderWebGL = function _renderWebGL(renderer) { + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.dirty !== this.fastRectDirty) { + this.fastRectDirty = this.dirty; + this._fastRect = this.isFastRect(); + } + + // TODO this check can be moved to dirty? + if (this._fastRect) { + this._renderSpriteRect(renderer); + } else { + renderer.setObjectRenderer(renderer.plugins.graphics); + renderer.plugins.graphics.render(this); + } + }; + + /** + * Renders a sprite rectangle. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderSpriteRect = function _renderSpriteRect(renderer) { + var rect = this.graphicsData[0].shape; + + if (!this._spriteRect) { + this._spriteRect = new _Sprite2.default(new _Texture2.default(_Texture2.default.WHITE)); + } + + var sprite = this._spriteRect; + + if (this.tint === 0xffffff) { + sprite.tint = this.graphicsData[0].fillColor; + } else { + var t1 = tempColor1; + var t2 = tempColor2; + + (0, _utils.hex2rgb)(this.graphicsData[0].fillColor, t1); + (0, _utils.hex2rgb)(this.tint, t2); + + t1[0] *= t2[0]; + t1[1] *= t2[1]; + t1[2] *= t2[2]; + + sprite.tint = (0, _utils.rgb2hex)(t1); + } + sprite.alpha = this.graphicsData[0].fillAlpha; + sprite.worldAlpha = this.worldAlpha * sprite.alpha; + sprite.blendMode = this.blendMode; + + sprite.texture._frame.width = rect.width; + sprite.texture._frame.height = rect.height; + + sprite.transform.worldTransform = this.transform.worldTransform; + + sprite.anchor.set(-rect.x / rect.width, -rect.y / rect.height); + sprite._onAnchorUpdate(); + + sprite._renderWebGL(renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.isMask === true) { + return; + } + + renderer.plugins.graphics.render(this); + }; + + /** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @private + */ + + + Graphics.prototype._calculateBounds = function _calculateBounds() { + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.updateLocalBounds(); + + this.cachedSpriteDirty = true; + } + + var lb = this._localBounds; + + this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); + }; + + /** + * Tests if a point is inside this graphics object + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Graphics.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + + if (!data.fill) { + continue; + } + + // only deal with fills.. + if (data.shape) { + if (data.shape.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + } + + return false; + }; + + /** + * Update the bounds of the object + * + */ + + + Graphics.prototype.updateLocalBounds = function updateLocalBounds() { + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) { + var shape = 0; + var x = 0; + var y = 0; + var w = 0; + var h = 0; + + for (var i = 0; i < this.graphicsData.length; i++) { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + + shape = data.shape; + + if (type === _const.SHAPES.RECT || type === _const.SHAPES.RREC) { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.CIRC) { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.ELIP) { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else { + // POLY + var points = shape.points; + var x2 = 0; + var y2 = 0; + var dx = 0; + var dy = 0; + var rw = 0; + var rh = 0; + var cx = 0; + var cy = 0; + + for (var j = 0; j + 2 < points.length; j += 2) { + x = points[j]; + y = points[j + 1]; + x2 = points[j + 2]; + y2 = points[j + 3]; + dx = Math.abs(x2 - x); + dy = Math.abs(y2 - y); + h = lineWidth; + w = Math.sqrt(dx * dx + dy * dy); + + if (w < 1e-9) { + continue; + } + + rw = (h / w * dy + dx) / 2; + rh = (h / w * dx + dy) / 2; + cx = (x2 + x) / 2; + cy = (y2 + y) / 2; + + minX = cx - rw < minX ? cx - rw : minX; + maxX = cx + rw > maxX ? cx + rw : maxX; + + minY = cy - rh < minY ? cy - rh : minY; + maxY = cy + rh > maxY ? cy + rh : maxY; + } + } + } + } else { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.minX = minX - padding; + this._localBounds.maxX = maxX + padding * 2; + + this._localBounds.minY = minY - padding; + this._localBounds.maxY = maxY + padding * 2; + }; + + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @return {PIXI.GraphicsData} The generated GraphicsData object. + */ + + + Graphics.prototype.drawShape = function drawShape(shape) { + if (this.currentPath) { + // check current path! + if (this.currentPath.shape.points.length <= 2) { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + var data = new _GraphicsData2.default(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, this.nativeLines, shape); + + this.graphicsData.push(data); + + if (data.type === _const.SHAPES.POLY) { + data.shape.closed = data.shape.closed || this.filling; + this.currentPath = data; + } + + this.dirty++; + + return data; + }; + + /** + * Generates a canvas texture. + * + * @param {number} scaleMode - The scale mode of the texture. + * @param {number} resolution - The resolution of the texture. + * @return {PIXI.Texture} The new texture. + */ + + + Graphics.prototype.generateCanvasTexture = function generateCanvasTexture(scaleMode) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + var bounds = this.getLocalBounds(); + + var canvasBuffer = _RenderTexture2.default.create(bounds.width, bounds.height, scaleMode, resolution); + + if (!canvasRenderer) { + canvasRenderer = new _CanvasRenderer2.default(); + } + + this.transform.updateLocalTransform(); + this.transform.localTransform.copy(tempMatrix); + + tempMatrix.invert(); + + tempMatrix.tx -= bounds.x; + tempMatrix.ty -= bounds.y; + + canvasRenderer.render(this, canvasBuffer, true, tempMatrix); + + var texture = _Texture2.default.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas, scaleMode); + + texture.baseTexture.resolution = resolution; + texture.baseTexture.update(); + + return texture; + }; + + /** + * Closes the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.closePath = function closePath() { + // ok so close path assumes next one is a hole! + var currentPath = this.currentPath; + + if (currentPath && currentPath.shape) { + currentPath.shape.close(); + } + + return this; + }; + + /** + * Adds a hole in the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.addHole = function addHole() { + // this is a hole! + var hole = this.graphicsData.pop(); + + this.currentPath = this.graphicsData[this.graphicsData.length - 1]; + + this.currentPath.addHole(hole.shape); + this.currentPath = null; + + return this; + }; + + /** + * Destroys the Graphics object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Graphics.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._webgl) { + for (var j = 0; j < this._webgl[id].data.length; ++j) { + this._webgl[id].data[j].destroy(); + } + } + + if (this._spriteRect) { + this._spriteRect.destroy(); + } + + this.graphicsData = null; + + this.currentPath = null; + this._webgl = null; + this._localBounds = null; + }; + + return Graphics; +}(_Container3.default); + +exports.default = Graphics; + + +Graphics._SPRITE_TEXTURE = null; + +},{"../const":44,"../display/Bounds":45,"../display/Container":46,"../math":68,"../renderers/canvas/CanvasRenderer":75,"../sprites/Sprite":100,"../textures/RenderTexture":110,"../textures/Texture":112,"../utils":120,"./GraphicsData":52,"./utils/bezierCurveTo":54}],52:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + */ +var GraphicsData = function () { + /** + * + * @param {number} lineWidth - the width of the line to draw + * @param {number} lineColor - the color of the line to draw + * @param {number} lineAlpha - the alpha of the line to draw + * @param {number} fillColor - the color of the fill + * @param {number} fillAlpha - the alpha of the fill + * @param {boolean} fill - whether or not the shape is filled with a colour + * @param {boolean} nativeLines - the method for drawing lines + * @param {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} shape - The shape object to draw. + */ + function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, nativeLines, shape) { + _classCallCheck(this, GraphicsData); + + /** + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + /** + * @member {boolean} if true the liens will be draw using LINES instead of TRIANGLE_STRIP + */ + this.nativeLines = nativeLines; + + /** + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /** + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /** + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /** + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /** + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /** + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /** + * @member {boolean} whether or not the shape is filled with a colour + */ + this.fill = fill; + + this.holes = []; + + /** + * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} The shape object to draw. + */ + this.shape = shape; + + /** + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + } + + /** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {PIXI.GraphicsData} Cloned GraphicsData object + */ + + + GraphicsData.prototype.clone = function clone() { + return new GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.fill, this.nativeLines, this.shape); + }; + + /** + * Adds a hole to the shape. + * + * @param {PIXI.Rectangle|PIXI.Circle} shape - The shape of the hole. + */ + + + GraphicsData.prototype.addHole = function addHole(shape) { + this.holes.push(shape); + }; + + /** + * Destroys the Graphics data. + */ + + + GraphicsData.prototype.destroy = function destroy() { + this.shape = null; + this.holes = null; + }; + + return GraphicsData; +}(); + +exports.default = GraphicsData; + +},{}],53:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they + * now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasGraphicsRenderer: + * https://github.com/libgdx/libgdx/blob/1.0.0/gdx/src/com/badlogic/gdx/graphics/glutils/ShapeRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching graphics objects. + * + * @class + * @private + * @memberof PIXI + */ +var CanvasGraphicsRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The current PIXI renderer. + */ + function CanvasGraphicsRenderer(renderer) { + _classCallCheck(this, CanvasGraphicsRenderer); + + this.renderer = renderer; + } + + /** + * Renders a Graphics object to a canvas. + * + * @param {PIXI.Graphics} graphics - the actual graphics object to render + */ + + + CanvasGraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var context = renderer.context; + var worldAlpha = graphics.worldAlpha; + var transform = graphics.transform.worldTransform; + var resolution = renderer.resolution; + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) { + this.dirty = true; + } + + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + if (graphics.dirty) { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + renderer.setBlendMode(graphics.blendMode); + + for (var i = 0; i < graphics.graphicsData.length; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === _const.SHAPES.POLY) { + context.beginPath(); + + this.renderPolygon(shape.points, shape.closed, context); + + for (var j = 0; j < data.holes.length; j++) { + this.renderPolygon(data.holes[j].points, true, context); + } + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RECT) { + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + context.beginPath(); + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + }; + + /** + * Updates the tint of a graphics object + * + * @private + * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated + */ + + + CanvasGraphicsRenderer.prototype.updateGraphicsTint = function updateGraphicsTint(graphics) { + graphics._prevTint = graphics.tint; + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF) / 255; + + for (var i = 0; i < graphics.graphicsData.length; ++i) { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + // super inline cos im an optimization NAZI :) + data._fillTint = ((fillColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (fillColor & 0xFF) / 255 * tintB * 255; + + data._lineTint = ((lineColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (lineColor & 0xFF) / 255 * tintB * 255; + } + }; + + /** + * Renders a polygon. + * + * @param {PIXI.Point[]} points - The points to render + * @param {boolean} close - Should the polygon be closed + * @param {CanvasRenderingContext2D} context - The rendering context to use + */ + + + CanvasGraphicsRenderer.prototype.renderPolygon = function renderPolygon(points, close, context) { + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; ++j) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (close) { + context.closePath(); + } + }; + + /** + * destroy graphics object + * + */ + + + CanvasGraphicsRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasGraphicsRenderer; +}(); + +exports.default = CanvasGraphicsRenderer; + + +_CanvasRenderer2.default.registerPlugin('graphics', CanvasGraphicsRenderer); + +},{"../../const":44,"../../renderers/canvas/CanvasRenderer":75}],54:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = bezierCurveTo; +/** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [path=[]] - Path array to push points into + * @return {number[]} Array of points of the curve + */ +function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var path = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : []; + + var n = 20; + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + + path.push(fromX, fromY); + + for (var i = 1, j = 0; i <= n; ++i) { + j = i / n; + + dt = 1 - j; + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + path.push(dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + return path; +} + +},{}],55:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _WebGLGraphicsData = require('./WebGLGraphicsData'); + +var _WebGLGraphicsData2 = _interopRequireDefault(_WebGLGraphicsData); + +var _PrimitiveShader = require('./shaders/PrimitiveShader'); + +var _PrimitiveShader2 = _interopRequireDefault(_PrimitiveShader); + +var _buildPoly = require('./utils/buildPoly'); + +var _buildPoly2 = _interopRequireDefault(_buildPoly); + +var _buildRectangle = require('./utils/buildRectangle'); + +var _buildRectangle2 = _interopRequireDefault(_buildRectangle); + +var _buildRoundedRectangle = require('./utils/buildRoundedRectangle'); + +var _buildRoundedRectangle2 = _interopRequireDefault(_buildRoundedRectangle); + +var _buildCircle = require('./utils/buildCircle'); + +var _buildCircle2 = _interopRequireDefault(_buildCircle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Renders the graphics object. + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var GraphicsRenderer = function (_ObjectRenderer) { + _inherits(GraphicsRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this object renderer works for. + */ + function GraphicsRenderer(renderer) { + _classCallCheck(this, GraphicsRenderer); + + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.graphicsDataPool = []; + + _this.primitiveShader = null; + + _this.gl = renderer.gl; + + // easy access! + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * Called when there is a WebGL context change + * + * @private + * + */ + + + GraphicsRenderer.prototype.onContextChange = function onContextChange() { + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.primitiveShader = new _PrimitiveShader2.default(this.gl); + }; + + /** + * Destroys this renderer. + * + */ + + + GraphicsRenderer.prototype.destroy = function destroy() { + _ObjectRenderer3.default.prototype.destroy.call(this); + + for (var i = 0; i < this.graphicsDataPool.length; ++i) { + this.graphicsDataPool[i].destroy(); + } + + this.graphicsDataPool = null; + }; + + /** + * Renders a graphics object. + * + * @param {PIXI.Graphics} graphics - The graphics object to render. + */ + + + GraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var gl = renderer.gl; + + var webGLData = void 0; + var webGL = graphics._webGL[this.CONTEXT_UID]; + + if (!webGL || graphics.dirty !== webGL.dirty) { + this.updateGraphics(graphics); + + webGL = graphics._webGL[this.CONTEXT_UID]; + } + + // This could be speeded up for sure! + var shader = this.primitiveShader; + + renderer.bindShader(shader); + renderer.state.setBlendMode(graphics.blendMode); + + for (var i = 0, n = webGL.data.length; i < n; i++) { + webGLData = webGL.data[i]; + var shaderTemp = webGLData.shader; + + renderer.bindShader(shaderTemp); + shaderTemp.uniforms.translationMatrix = graphics.transform.worldTransform.toArray(true); + shaderTemp.uniforms.tint = (0, _utils.hex2rgb)(graphics.tint); + shaderTemp.uniforms.alpha = graphics.worldAlpha; + + renderer.bindVao(webGLData.vao); + + if (graphics.nativeLines) { + gl.drawArrays(gl.LINES, 0, webGLData.points.length / 6); + } else { + webGLData.vao.draw(gl.TRIANGLE_STRIP, webGLData.indices.length); + } + } + }; + + /** + * Updates the graphics object + * + * @private + * @param {PIXI.Graphics} graphics - The graphics object to update + */ + + + GraphicsRenderer.prototype.updateGraphics = function updateGraphics(graphics) { + var gl = this.renderer.gl; + + // get the contexts graphics object + var webGL = graphics._webGL[this.CONTEXT_UID]; + + // if the graphics object does not exist in the webGL context time to create it! + if (!webGL) { + webGL = graphics._webGL[this.CONTEXT_UID] = { lastIndex: 0, data: [], gl: gl, clearDirty: -1, dirty: -1 }; + } + + // flag the graphics as not dirty as we are about to update it... + webGL.dirty = graphics.dirty; + + // if the user cleared the graphics object we will need to clear every object + if (graphics.clearDirty !== webGL.clearDirty) { + webGL.clearDirty = graphics.clearDirty; + + // loop through and return all the webGLDatas to the object pool so than can be reused later on + for (var i = 0; i < webGL.data.length; i++) { + this.graphicsDataPool.push(webGL.data[i]); + } + + // clear the array and reset the index.. + webGL.data.length = 0; + webGL.lastIndex = 0; + } + + var webGLData = void 0; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (var _i = webGL.lastIndex; _i < graphics.graphicsData.length; _i++) { + var data = graphics.graphicsData[_i]; + + // TODO - this can be simplified + webGLData = this.getWebGLData(webGL, 0); + + if (data.type === _const.SHAPES.POLY) { + (0, _buildPoly2.default)(data, webGLData); + } + if (data.type === _const.SHAPES.RECT) { + (0, _buildRectangle2.default)(data, webGLData); + } else if (data.type === _const.SHAPES.CIRC || data.type === _const.SHAPES.ELIP) { + (0, _buildCircle2.default)(data, webGLData); + } else if (data.type === _const.SHAPES.RREC) { + (0, _buildRoundedRectangle2.default)(data, webGLData); + } + + webGL.lastIndex++; + } + + this.renderer.bindVao(null); + + // upload all the dirty data... + for (var _i2 = 0; _i2 < webGL.data.length; _i2++) { + webGLData = webGL.data[_i2]; + + if (webGLData.dirty) { + webGLData.upload(); + } + } + }; + + /** + * + * @private + * @param {WebGLRenderingContext} gl - the current WebGL drawing context + * @param {number} type - TODO @Alvin + * @return {*} TODO + */ + + + GraphicsRenderer.prototype.getWebGLData = function getWebGLData(gl, type) { + var webGLData = gl.data[gl.data.length - 1]; + + if (!webGLData || webGLData.points.length > 320000) { + webGLData = this.graphicsDataPool.pop() || new _WebGLGraphicsData2.default(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + + webGLData.reset(type); + gl.data.push(webGLData); + } + + webGLData.dirty = true; + + return webGLData; + }; + + return GraphicsRenderer; +}(_ObjectRenderer3.default); + +exports.default = GraphicsRenderer; + + +_WebGLRenderer2.default.registerPlugin('graphics', GraphicsRenderer); + +},{"../../const":44,"../../renderers/webgl/WebGLRenderer":82,"../../renderers/webgl/utils/ObjectRenderer":92,"../../utils":120,"./WebGLGraphicsData":56,"./shaders/PrimitiveShader":57,"./utils/buildCircle":58,"./utils/buildPoly":60,"./utils/buildRectangle":61,"./utils/buildRoundedRectangle":62}],56:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * An object containing WebGL specific properties to be used by the WebGL renderer + * + * @class + * @private + * @memberof PIXI + */ +var WebGLGraphicsData = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {PIXI.Shader} shader - The shader + * @param {object} attribsState - The state for the VAO + */ + function WebGLGraphicsData(gl, shader, attribsState) { + _classCallCheck(this, WebGLGraphicsData); + + /** + * The current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // TODO does this need to be split before uploading?? + /** + * An array of color components (r,g,b) + * @member {number[]} + */ + this.color = [0, 0, 0]; // color split! + + /** + * An array of points to draw + * @member {PIXI.Point[]} + */ + this.points = []; + + /** + * The indices of the vertices + * @member {number[]} + */ + this.indices = []; + /** + * The main buffer + * @member {WebGLBuffer} + */ + this.buffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl); + + /** + * The index buffer + * @member {WebGLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl); + + /** + * Whether this graphics is dirty or not + * @member {boolean} + */ + this.dirty = true; + + this.glPoints = null; + this.glIndices = null; + + /** + * + * @member {PIXI.Shader} + */ + this.shader = shader; + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, attribsState).addIndex(this.indexBuffer).addAttribute(this.buffer, shader.attributes.aVertexPosition, gl.FLOAT, false, 4 * 6, 0).addAttribute(this.buffer, shader.attributes.aColor, gl.FLOAT, false, 4 * 6, 2 * 4); + } + + /** + * Resets the vertices and the indices + */ + + + WebGLGraphicsData.prototype.reset = function reset() { + this.points.length = 0; + this.indices.length = 0; + }; + + /** + * Binds the buffers and uploads the data + */ + + + WebGLGraphicsData.prototype.upload = function upload() { + this.glPoints = new Float32Array(this.points); + this.buffer.upload(this.glPoints); + + this.glIndices = new Uint16Array(this.indices); + this.indexBuffer.upload(this.glIndices); + + this.dirty = false; + }; + + /** + * Empties all the data + */ + + + WebGLGraphicsData.prototype.destroy = function destroy() { + this.color = null; + this.points = null; + this.indices = null; + + this.vao.destroy(); + this.buffer.destroy(); + this.indexBuffer.destroy(); + + this.gl = null; + + this.buffer = null; + this.indexBuffer = null; + + this.glPoints = null; + this.glIndices = null; + }; + + return WebGLGraphicsData; +}(); + +exports.default = WebGLGraphicsData; + +},{"pixi-gl-core":12}],57:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../../Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. + * + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ +var PrimitiveShader = function (_Shader) { + _inherits(PrimitiveShader, _Shader); + + /** + * @param {WebGLRenderingContext} gl - The webgl shader manager this shader works for. + */ + function PrimitiveShader(gl) { + _classCallCheck(this, PrimitiveShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec4 aColor;', 'uniform mat3 translationMatrix;', 'uniform mat3 projectionMatrix;', 'uniform float alpha;', 'uniform vec3 tint;', 'varying vec4 vColor;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vColor = aColor * vec4(tint * alpha, alpha);', '}'].join('\n'), + // fragment shader + ['varying vec4 vColor;', 'void main(void){', ' gl_FragColor = vColor;', '}'].join('\n'))); + } + + return PrimitiveShader; +}(_Shader3.default); + +exports.default = PrimitiveShader; + +},{"../../../Shader":42}],58:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildCircle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _const = require('../../../const'); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildCircle(graphicsData, webGLData) { + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width = void 0; + var height = void 0; + + // TODO - bit hacky?? + if (graphicsData.type === _const.SHAPES.CIRC) { + width = circleData.radius; + height = circleData.radius; + } else { + width = circleData.width; + height = circleData.height; + } + + if (width === 0 || height === 0) { + return; + } + + var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); + + var seg = Math.PI * 2 / totalSegs; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + indices.push(vecPos); + + for (var i = 0; i < totalSegs + 1; i++) { + verts.push(x, y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos - 1); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (var _i = 0; _i < totalSegs + 1; _i++) { + graphicsData.points.push(x + Math.sin(seg * _i) * width, y + Math.cos(seg * _i) * height); + } + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +},{"../../../const":44,"../../../utils":120,"./buildLine":59}],59:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function (graphicsData, webGLData) { + if (graphicsData.nativeLines) { + buildNativeLine(graphicsData, webGLData); + } else { + buildLine(graphicsData, webGLData); + } +}; + +var _math = require('../../../math'); + +var _utils = require('../../../utils'); + +/** + * Builds a line to draw using the poligon method. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildLine(graphicsData, webGLData) { + // TODO OPTIMISE! + var points = graphicsData.points; + + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + + // get first and last point.. figure out the middle! + var firstPoint = new _math.Point(points[0], points[1]); + var lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + // if the first point is the last point - gonna have issues :) + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var p1x = points[0]; + var p1y = points[1]; + var p2x = points[2]; + var p2y = points[3]; + var p3x = 0; + var p3y = 0; + + var perpx = -(p1y - p2y); + var perpy = p1x - p2x; + var perp2x = 0; + var perp2y = 0; + var perp3x = 0; + var perp3y = 0; + + var dist = Math.sqrt(perpx * perpx + perpy * perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx, p1y - perpy, r, g, b, alpha); + + verts.push(p1x + perpx, p1y + perpy, r, g, b, alpha); + + for (var i = 1; i < length - 1; ++i) { + p1x = points[(i - 1) * 2]; + p1y = points[(i - 1) * 2 + 1]; + + p2x = points[i * 2]; + p2y = points[i * 2 + 1]; + + p3x = points[(i + 1) * 2]; + p3y = points[(i + 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + var a1 = -perpy + p1y - (-perpy + p2y); + var b1 = -perpx + p2x - (-perpx + p1x); + var c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + var a2 = -perp2y + p3y - (-perp2y + p2y); + var b2 = -perp2x + p2x - (-perp2x + p3x); + var c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + var denom = a1 * b2 - a2 * b1; + + if (Math.abs(denom) < 0.1) { + denom += 10.1; + verts.push(p2x - perpx, p2y - perpy, r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy, r, g, b, alpha); + + continue; + } + + var px = (b1 * c2 - b2 * c1) / denom; + var py = (a2 * c1 - a1 * c2) / denom; + var pdist = (px - p2x) * (px - p2x) + (py - p2y) * (py - p2y); + + if (pdist > 196 * width * width) { + perp3x = perpx - perp2x; + perp3y = perpy - perp2y; + + dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y); + perp3x /= dist; + perp3y /= dist; + perp3x *= width; + perp3y *= width; + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x + perp3x, p2y + perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + indexCount++; + } else { + verts.push(px, py); + verts.push(r, g, b, alpha); + + verts.push(p2x - (px - p2x), p2y - (py - p2y)); + verts.push(r, g, b, alpha); + } + } + + p1x = points[(length - 2) * 2]; + p1y = points[(length - 2) * 2 + 1]; + + p2x = points[(length - 1) * 2]; + p2y = points[(length - 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + verts.push(p2x - perpx, p2y - perpy); + verts.push(r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy); + verts.push(r, g, b, alpha); + + indices.push(indexStart); + + for (var _i = 0; _i < indexCount; ++_i) { + indices.push(indexStart++); + } + + indices.push(indexStart - 1); +} + +/** + * Builds a line to draw using the gl.drawArrays(gl.LINES) method + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ + + +/** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildNativeLine(graphicsData, webGLData) { + var i = 0; + var points = graphicsData.points; + + if (points.length === 0) return; + + var verts = webGLData.points; + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + for (i = 1; i < length; i++) { + var p1x = points[(i - 1) * 2]; + var p1y = points[(i - 1) * 2 + 1]; + + var p2x = points[i * 2]; + var p2y = points[i * 2 + 1]; + + verts.push(p1x, p1y); + verts.push(r, g, b, alpha); + + verts.push(p2x, p2y); + verts.push(r, g, b, alpha); + } +} + +},{"../../../math":68,"../../../utils":120}],60:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildPoly; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildPoly(graphicsData, webGLData) { + graphicsData.points = graphicsData.shape.points.slice(); + + var points = graphicsData.points; + + if (graphicsData.fill && points.length >= 6) { + var holeArray = []; + // Process holes.. + var holes = graphicsData.holes; + + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + + holeArray.push(points.length / 2); + + points = points.concat(hole.points); + } + + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = (0, _earcut2.default)(points, holeArray, 2); + + if (!triangles) { + return; + } + + var vertPos = verts.length / 6; + + for (var _i = 0; _i < triangles.length; _i += 3) { + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i + 1] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + } + + for (var _i2 = 0; _i2 < length; _i2++) { + verts.push(points[_i2 * 2], points[_i2 * 2 + 1], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth > 0) { + (0, _buildLine2.default)(graphicsData, webGLData); + } +} + +},{"../../../utils":120,"./buildLine":59,"earcut":2}],61:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRectangle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildRectangle(graphicsData, webGLData) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vertPos = verts.length / 6; + + // start + verts.push(x, y); + verts.push(r, g, b, alpha); + + verts.push(x + width, y); + verts.push(r, g, b, alpha); + + verts.push(x, y + height); + verts.push(r, g, b, alpha); + + verts.push(x + width, y + height); + verts.push(r, g, b, alpha); + + // insert 2 dead triangles.. + indices.push(vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y]; + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +},{"../../../utils":120,"./buildLine":59}],62:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRoundedRectangle; + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildRoundedRectangle(graphicsData, webGLData) { + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + + recPoints.push(x, y + radius); + quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height, recPoints); + quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius, recPoints); + quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y, recPoints); + quadraticBezierCurve(x + radius, y, x, y, x, y + radius + 0.0000000001, recPoints); + + // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. + // TODO - fix this properly, this is not very elegant.. but it works for now. + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + var triangles = (0, _earcut2.default)(recPoints, null, 2); + + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + + for (var _i = 0, _j = recPoints.length; _i < _j; _i++) { + verts.push(recPoints[_i], recPoints[++_i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + (0, _buildLine2.default)(graphicsData, webGLData); + + graphicsData.points = tempPoints; + } +} + +/** + * Calculate a single point for a quadratic bezier curve. + * Utility function used by quadraticBezierCurve. + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} n1 - first number + * @param {number} n2 - second number + * @param {number} perc - percentage + * @return {number} the result + * + */ +function getPt(n1, n2, perc) { + var diff = n2 - n1; + + return n1 + diff * perc; +} + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @return {number[]} an array of points + */ +function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY) { + var out = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : []; + + var n = 20; + var points = out; + + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + + points.push(x, y); + } + + return points; +} + +},{"../../../utils":120,"./buildLine":59,"earcut":2}],63:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = exports.Application = exports.Filter = exports.SpriteMaskFilter = exports.Quad = exports.RenderTarget = exports.ObjectRenderer = exports.WebGLManager = exports.Shader = exports.CanvasRenderTarget = exports.TextureUvs = exports.VideoBaseTexture = exports.BaseRenderTexture = exports.RenderTexture = exports.BaseTexture = exports.Texture = exports.Spritesheet = exports.CanvasGraphicsRenderer = exports.GraphicsRenderer = exports.GraphicsData = exports.Graphics = exports.TextStyle = exports.Text = exports.SpriteRenderer = exports.CanvasTinter = exports.CanvasSpriteRenderer = exports.Sprite = exports.TransformBase = exports.TransformStatic = exports.Transform = exports.Container = exports.DisplayObject = exports.Bounds = exports.glCore = exports.WebGLRenderer = exports.CanvasRenderer = exports.ticker = exports.utils = exports.settings = undefined; + +var _const = require('./const'); + +Object.keys(_const).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _const[key]; + } + }); +}); + +var _math = require('./math'); + +Object.keys(_math).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _math[key]; + } + }); +}); + +var _pixiGlCore = require('pixi-gl-core'); + +Object.defineProperty(exports, 'glCore', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_pixiGlCore).default; + } +}); + +var _Bounds = require('./display/Bounds'); + +Object.defineProperty(exports, 'Bounds', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Bounds).default; + } +}); + +var _DisplayObject = require('./display/DisplayObject'); + +Object.defineProperty(exports, 'DisplayObject', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplayObject).default; + } +}); + +var _Container = require('./display/Container'); + +Object.defineProperty(exports, 'Container', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Container).default; + } +}); + +var _Transform = require('./display/Transform'); + +Object.defineProperty(exports, 'Transform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Transform).default; + } +}); + +var _TransformStatic = require('./display/TransformStatic'); + +Object.defineProperty(exports, 'TransformStatic', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformStatic).default; + } +}); + +var _TransformBase = require('./display/TransformBase'); + +Object.defineProperty(exports, 'TransformBase', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformBase).default; + } +}); + +var _Sprite = require('./sprites/Sprite'); + +Object.defineProperty(exports, 'Sprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Sprite).default; + } +}); + +var _CanvasSpriteRenderer = require('./sprites/canvas/CanvasSpriteRenderer'); + +Object.defineProperty(exports, 'CanvasSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasSpriteRenderer).default; + } +}); + +var _CanvasTinter = require('./sprites/canvas/CanvasTinter'); + +Object.defineProperty(exports, 'CanvasTinter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasTinter).default; + } +}); + +var _SpriteRenderer = require('./sprites/webgl/SpriteRenderer'); + +Object.defineProperty(exports, 'SpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteRenderer).default; + } +}); + +var _Text = require('./text/Text'); + +Object.defineProperty(exports, 'Text', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Text).default; + } +}); + +var _TextStyle = require('./text/TextStyle'); + +Object.defineProperty(exports, 'TextStyle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextStyle).default; + } +}); + +var _Graphics = require('./graphics/Graphics'); + +Object.defineProperty(exports, 'Graphics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Graphics).default; + } +}); + +var _GraphicsData = require('./graphics/GraphicsData'); + +Object.defineProperty(exports, 'GraphicsData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsData).default; + } +}); + +var _GraphicsRenderer = require('./graphics/webgl/GraphicsRenderer'); + +Object.defineProperty(exports, 'GraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsRenderer).default; + } +}); + +var _CanvasGraphicsRenderer = require('./graphics/canvas/CanvasGraphicsRenderer'); + +Object.defineProperty(exports, 'CanvasGraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasGraphicsRenderer).default; + } +}); + +var _Spritesheet = require('./textures/Spritesheet'); + +Object.defineProperty(exports, 'Spritesheet', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Spritesheet).default; + } +}); + +var _Texture = require('./textures/Texture'); + +Object.defineProperty(exports, 'Texture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Texture).default; + } +}); + +var _BaseTexture = require('./textures/BaseTexture'); + +Object.defineProperty(exports, 'BaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseTexture).default; + } +}); + +var _RenderTexture = require('./textures/RenderTexture'); + +Object.defineProperty(exports, 'RenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTexture).default; + } +}); + +var _BaseRenderTexture = require('./textures/BaseRenderTexture'); + +Object.defineProperty(exports, 'BaseRenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseRenderTexture).default; + } +}); + +var _VideoBaseTexture = require('./textures/VideoBaseTexture'); + +Object.defineProperty(exports, 'VideoBaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VideoBaseTexture).default; + } +}); + +var _TextureUvs = require('./textures/TextureUvs'); + +Object.defineProperty(exports, 'TextureUvs', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureUvs).default; + } +}); + +var _CanvasRenderTarget = require('./renderers/canvas/utils/CanvasRenderTarget'); + +Object.defineProperty(exports, 'CanvasRenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasRenderTarget).default; + } +}); + +var _Shader = require('./Shader'); + +Object.defineProperty(exports, 'Shader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Shader).default; + } +}); + +var _WebGLManager = require('./renderers/webgl/managers/WebGLManager'); + +Object.defineProperty(exports, 'WebGLManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLManager).default; + } +}); + +var _ObjectRenderer = require('./renderers/webgl/utils/ObjectRenderer'); + +Object.defineProperty(exports, 'ObjectRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObjectRenderer).default; + } +}); + +var _RenderTarget = require('./renderers/webgl/utils/RenderTarget'); + +Object.defineProperty(exports, 'RenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTarget).default; + } +}); + +var _Quad = require('./renderers/webgl/utils/Quad'); + +Object.defineProperty(exports, 'Quad', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Quad).default; + } +}); + +var _SpriteMaskFilter = require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter'); + +Object.defineProperty(exports, 'SpriteMaskFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteMaskFilter).default; + } +}); + +var _Filter = require('./renderers/webgl/filters/Filter'); + +Object.defineProperty(exports, 'Filter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Filter).default; + } +}); + +var _Application = require('./Application'); + +Object.defineProperty(exports, 'Application', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Application).default; + } +}); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +Object.defineProperty(exports, 'autoDetectRenderer', { + enumerable: true, + get: function get() { + return _autoDetectRenderer.autoDetectRenderer; + } +}); + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _ticker = require('./ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.settings = _settings2.default; +exports.utils = utils; +exports.ticker = ticker; +exports.CanvasRenderer = _CanvasRenderer2.default; +exports.WebGLRenderer = _WebGLRenderer2.default; /** + * @namespace PIXI + */ + +},{"./Application":41,"./Shader":42,"./autoDetectRenderer":43,"./const":44,"./display/Bounds":45,"./display/Container":46,"./display/DisplayObject":47,"./display/Transform":48,"./display/TransformBase":49,"./display/TransformStatic":50,"./graphics/Graphics":51,"./graphics/GraphicsData":52,"./graphics/canvas/CanvasGraphicsRenderer":53,"./graphics/webgl/GraphicsRenderer":55,"./math":68,"./renderers/canvas/CanvasRenderer":75,"./renderers/canvas/utils/CanvasRenderTarget":77,"./renderers/webgl/WebGLRenderer":82,"./renderers/webgl/filters/Filter":84,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":87,"./renderers/webgl/managers/WebGLManager":91,"./renderers/webgl/utils/ObjectRenderer":92,"./renderers/webgl/utils/Quad":93,"./renderers/webgl/utils/RenderTarget":94,"./settings":99,"./sprites/Sprite":100,"./sprites/canvas/CanvasSpriteRenderer":101,"./sprites/canvas/CanvasTinter":102,"./sprites/webgl/SpriteRenderer":104,"./text/Text":106,"./text/TextStyle":107,"./textures/BaseRenderTexture":108,"./textures/BaseTexture":109,"./textures/RenderTexture":110,"./textures/Spritesheet":111,"./textures/Texture":112,"./textures/TextureUvs":113,"./textures/VideoBaseTexture":114,"./ticker":116,"./utils":120,"pixi-gl-core":12}],64:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Matrix = require('./Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16 + +var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; +var tempMatrices = []; + +var mul = []; + +function signum(x) { + if (x < 0) { + return -1; + } + if (x > 0) { + return 1; + } + + return 0; +} + +function init() { + for (var i = 0; i < 16; i++) { + var row = []; + + mul.push(row); + + for (var j = 0; j < 16; j++) { + var _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); + var _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); + var _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); + var _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); + + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + + for (var _i = 0; _i < 16; _i++) { + var mat = new _Matrix2.default(); + + mat.set(ux[_i], uy[_i], vx[_i], vy[_i], 0, 0); + tempMatrices.push(mat); + } +} + +init(); + +/** + * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, + * D8 is the same but with diagonals. Used for texture rotations. + * + * Vector xX(i), xY(i) is U-axis of sprite with rotation i + * Vector yY(i), yY(i) is V-axis of sprite with rotation i + * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) + * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) + * This is the small part of gameofbombs.com portal system. It works. + * + * @author Ivan @ivanpopelyshev + * @class + * @memberof PIXI + */ +var GroupD8 = { + E: 0, + SE: 1, + S: 2, + SW: 3, + W: 4, + NW: 5, + N: 6, + NE: 7, + MIRROR_VERTICAL: 8, + MIRROR_HORIZONTAL: 12, + uX: function uX(ind) { + return ux[ind]; + }, + uY: function uY(ind) { + return uy[ind]; + }, + vX: function vX(ind) { + return vx[ind]; + }, + vY: function vY(ind) { + return vy[ind]; + }, + inv: function inv(rotation) { + if (rotation & 8) { + return rotation & 15; + } + + return -rotation & 7; + }, + add: function add(rotationSecond, rotationFirst) { + return mul[rotationSecond][rotationFirst]; + }, + sub: function sub(rotationSecond, rotationFirst) { + return mul[rotationSecond][GroupD8.inv(rotationFirst)]; + }, + + /** + * Adds 180 degrees to rotation. Commutative operation. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to rotate. + * @returns {number} rotated number + */ + rotate180: function rotate180(rotation) { + return rotation ^ 4; + }, + + /** + * I dont know why sometimes width and heights needs to be swapped. We'll fix it later. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the width/height should be swapped. + */ + isSwapWidthHeight: function isSwapWidthHeight(rotation) { + return (rotation & 3) === 2; + }, + + /** + * @memberof PIXI.GroupD8 + * @param {number} dx - TODO + * @param {number} dy - TODO + * + * @return {number} TODO + */ + byDirection: function byDirection(dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return GroupD8.S; + } + + return GroupD8.N; + } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return GroupD8.E; + } + + return GroupD8.W; + } else if (dy > 0) { + if (dx > 0) { + return GroupD8.SE; + } + + return GroupD8.SW; + } else if (dx > 0) { + return GroupD8.NE; + } + + return GroupD8.NW; + }, + + /** + * Helps sprite to compensate texture packer rotation. + * + * @memberof PIXI.GroupD8 + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {number} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function matrixAppendRotationInv(matrix, rotation) { + var tx = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var ty = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + // Packer used "rotation", we use "inv(rotation)" + var mat = tempMatrices[GroupD8.inv(rotation)]; + + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + } +}; + +exports.default = GroupD8; + +},{"./Matrix":65}],65:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Point = require('./Point'); + +var _Point2 = _interopRequireDefault(_Point); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The pixi Matrix class as an object, which makes it a lot faster, + * here is a representation of it : + * | a | b | tx| + * | c | d | ty| + * | 0 | 0 | 1 | + * + * @class + * @memberof PIXI + */ +var Matrix = function () { + /** + * @param {number} [a=1] - x scale + * @param {number} [b=0] - y skew + * @param {number} [c=0] - x skew + * @param {number} [d=1] - y scale + * @param {number} [tx=0] - x translation + * @param {number} [ty=0] - y translation + */ + function Matrix() { + var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var d = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var tx = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var ty = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + + _classCallCheck(this, Matrix); + + /** + * @member {number} + * @default 1 + */ + this.a = a; + + /** + * @member {number} + * @default 0 + */ + this.b = b; + + /** + * @member {number} + * @default 0 + */ + this.c = c; + + /** + * @member {number} + * @default 1 + */ + this.d = d; + + /** + * @member {number} + * @default 0 + */ + this.tx = tx; + + /** + * @member {number} + * @default 0 + */ + this.ty = ty; + + this.array = null; + } + + /** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @param {number[]} array - The array that the matrix will be populated from. + */ + + + Matrix.prototype.fromArray = function fromArray(array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + }; + + /** + * sets the matrix properties + * + * @param {number} a - Matrix component + * @param {number} b - Matrix component + * @param {number} c - Matrix component + * @param {number} d - Matrix component + * @param {number} tx - Matrix component + * @param {number} ty - Matrix component + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.set = function set(a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + }; + + /** + * Creates an array from the current Matrix object. + * + * @param {boolean} transpose - Whether we need to transpose the matrix or not + * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out + * @return {number[]} the newly created array which contains the matrix + */ + + + Matrix.prototype.toArray = function toArray(transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + + var array = out || this.array; + + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + }; + + /** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, transformed through this matrix + */ + + + Matrix.prototype.apply = function apply(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; + + return newPos; + }; + + /** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, inverse-transformed through this matrix + */ + + + Matrix.prototype.applyInverse = function applyInverse(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var id = 1 / (this.a * this.d + this.c * -this.b); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + }; + + /** + * Translates the matrix on the x and y. + * + * @param {number} x How much to translate x by + * @param {number} y How much to translate y by + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.translate = function translate(x, y) { + this.tx += x; + this.ty += y; + + return this; + }; + + /** + * Applies a scale transformation to the matrix. + * + * @param {number} x The amount to scale horizontally + * @param {number} y The amount to scale vertically + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.scale = function scale(x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + }; + + /** + * Applies a rotation transformation to the matrix. + * + * @param {number} angle - The angle in radians. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.rotate = function rotate(angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos - this.b * sin; + this.b = a1 * sin + this.b * cos; + this.c = c1 * cos - this.d * sin; + this.d = c1 * sin + this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + }; + + /** + * Appends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to append. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.append = function append(matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + }; + + /** + * Sets the matrix based on all the available properties + * + * @param {number} x - Position on the x axis + * @param {number} y - Position on the y axis + * @param {number} pivotX - Pivot on the x axis + * @param {number} pivotY - Pivot on the y axis + * @param {number} scaleX - Scale on the x axis + * @param {number} scaleY - Scale on the y axis + * @param {number} rotation - Rotation in radians + * @param {number} skewX - Skew on the x axis + * @param {number} skewY - Skew on the y axis + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.setTransform = function setTransform(x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + var sr = Math.sin(rotation); + var cr = Math.cos(rotation); + var cy = Math.cos(skewY); + var sy = Math.sin(skewY); + var nsx = -Math.sin(skewX); + var cx = Math.cos(skewX); + + var a = cr * scaleX; + var b = sr * scaleX; + var c = -sr * scaleY; + var d = cr * scaleY; + + this.a = cy * a + sy * c; + this.b = cy * b + sy * d; + this.c = nsx * a + cx * c; + this.d = nsx * b + cx * d; + + this.tx = x + (pivotX * a + pivotY * c); + this.ty = y + (pivotX * b + pivotY * d); + + return this; + }; + + /** + * Prepends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to prepend + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.prepend = function prepend(matrix) { + var tx1 = this.tx; + + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + + this.a = a1 * matrix.a + this.b * matrix.c; + this.b = a1 * matrix.b + this.b * matrix.d; + this.c = c1 * matrix.a + this.d * matrix.c; + this.d = c1 * matrix.b + this.d * matrix.d; + } + + this.tx = tx1 * matrix.a + this.ty * matrix.c + matrix.tx; + this.ty = tx1 * matrix.b + this.ty * matrix.d + matrix.ty; + + return this; + }; + + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * + * @param {PIXI.Transform|PIXI.TransformStatic} transform - The transform to apply the properties to. + * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properties + */ + + + Matrix.prototype.decompose = function decompose(transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + + var skewX = -Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + + var delta = Math.abs(skewX + skewY); + + if (delta < 0.00001) { + transform.rotation = skewY; + + if (a < 0 && d >= 0) { + transform.rotation += transform.rotation <= 0 ? Math.PI : -Math.PI; + } + + transform.skew.x = transform.skew.y = 0; + } else { + transform.skew.x = skewX; + transform.skew.y = skewY; + } + + // next set scale + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); + + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; + + return transform; + }; + + /** + * Inverts this matrix + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.invert = function invert() { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1 * d1 - b1 * c1; + + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = (c1 * this.ty - d1 * tx1) / n; + this.ty = -(a1 * this.ty - b1 * tx1) / n; + + return this; + }; + + /** + * Resets this Matix to an identity (default) matrix. + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.identity = function identity() { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + + return this; + }; + + /** + * Creates a new Matrix object with the same values as this one. + * + * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. + */ + + + Matrix.prototype.clone = function clone() { + var matrix = new Matrix(); + + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * Changes the values of the given matrix to be the same as the ones in this matrix + * + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @return {PIXI.Matrix} The matrix given in parameter with its values updated. + */ + + + Matrix.prototype.copy = function copy(matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * A default (identity) matrix + * + * @static + * @const + */ + + + _createClass(Matrix, null, [{ + key: 'IDENTITY', + get: function get() { + return new Matrix(); + } + + /** + * A temp matrix + * + * @static + * @const + */ + + }, { + key: 'TEMP_MATRIX', + get: function get() { + return new Matrix(); + } + }]); + + return Matrix; +}(); + +exports.default = Matrix; + +},{"./Point":67}],66:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * An observable point is a point that triggers a callback when the point's position is changed. + * + * @class + * @memberof PIXI + */ +var ObservablePoint = function () { + /** + * @param {Function} cb - callback when changed + * @param {object} scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope) { + var x = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var y = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, ObservablePoint); + + this._x = x; + this._y = y; + + this.cb = cb; + this.scope = scope; + } + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + ObservablePoint.prototype.set = function set(x, y) { + var _x = x || 0; + var _y = y || (y !== 0 ? _x : 0); + + if (this._x !== _x || this._y !== _y) { + this._x = _x; + this._y = _y; + this.cb.call(this.scope); + } + }; + + /** + * Copies the data from another point + * + * @param {PIXI.Point|PIXI.ObservablePoint} point - point to copy from + */ + + + ObservablePoint.prototype.copy = function copy(point) { + if (this._x !== point.x || this._y !== point.y) { + this._x = point.x; + this._y = point.y; + this.cb.call(this.scope); + } + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + + _createClass(ObservablePoint, [{ + key: "x", + get: function get() { + return this._x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + } + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + }, { + key: "y", + get: function get() { + return this._y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + } + }]); + + return ObservablePoint; +}(); + +exports.default = ObservablePoint; + +},{}],67:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * + * @class + * @memberof PIXI + */ +var Point = function () { + /** + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function Point() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + + _classCallCheck(this, Point); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + } + + /** + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point + */ + + + Point.prototype.clone = function clone() { + return new Point(this.x, this.y); + }; + + /** + * Copies x and y from the given point + * + * @param {PIXI.Point} p - The point to copy. + */ + + + Point.prototype.copy = function copy(p) { + this.set(p.x, p.y); + }; + + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.Point} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + + + Point.prototype.equals = function equals(p) { + return p.x === this.x && p.y === this.y; + }; + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + Point.prototype.set = function set(x, y) { + this.x = x || 0; + this.y = y || (y !== 0 ? this.x : 0); + }; + + return Point; +}(); + +exports.default = Point; + +},{}],68:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('./Point'); + +Object.defineProperty(exports, 'Point', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Point).default; + } +}); + +var _ObservablePoint = require('./ObservablePoint'); + +Object.defineProperty(exports, 'ObservablePoint', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObservablePoint).default; + } +}); + +var _Matrix = require('./Matrix'); + +Object.defineProperty(exports, 'Matrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Matrix).default; + } +}); + +var _GroupD = require('./GroupD8'); + +Object.defineProperty(exports, 'GroupD8', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GroupD).default; + } +}); + +var _Circle = require('./shapes/Circle'); + +Object.defineProperty(exports, 'Circle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Circle).default; + } +}); + +var _Ellipse = require('./shapes/Ellipse'); + +Object.defineProperty(exports, 'Ellipse', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Ellipse).default; + } +}); + +var _Polygon = require('./shapes/Polygon'); + +Object.defineProperty(exports, 'Polygon', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Polygon).default; + } +}); + +var _Rectangle = require('./shapes/Rectangle'); + +Object.defineProperty(exports, 'Rectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rectangle).default; + } +}); + +var _RoundedRectangle = require('./shapes/RoundedRectangle'); + +Object.defineProperty(exports, 'RoundedRectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RoundedRectangle).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./GroupD8":64,"./Matrix":65,"./ObservablePoint":66,"./Point":67,"./shapes/Circle":69,"./shapes/Ellipse":70,"./shapes/Polygon":71,"./shapes/Rectangle":72,"./shapes/RoundedRectangle":73}],69:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Circle object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Circle = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [radius=0] - The radius of the circle + */ + function Circle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var radius = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + _classCallCheck(this, Circle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.CIRC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.CIRC; + } + + /** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ + + + Circle.prototype.clone = function clone() { + return new Circle(this.x, this.y, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this circle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Circle + */ + + + Circle.prototype.contains = function contains(x, y) { + if (this.radius <= 0) { + return false; + } + + var r2 = this.radius * this.radius; + var dx = this.x - x; + var dy = this.y - y; + + dx *= dx; + dy *= dy; + + return dx + dy <= r2; + }; + + /** + * Returns the framing rectangle of the circle as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Circle.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + + return Circle; +}(); + +exports.default = Circle; + +},{"../../const":44,"./Rectangle":72}],70:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Ellipse object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Ellipse = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [width=0] - The half width of this ellipse + * @param {number} [height=0] - The half height of this ellipse + */ + function Ellipse() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Ellipse); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.ELIP + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.ELIP; + } + + /** + * Creates a clone of this Ellipse instance + * + * @return {PIXI.Ellipse} a copy of the ellipse + */ + + + Ellipse.prototype.clone = function clone() { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coords are within this ellipse + */ + + + Ellipse.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + // normalize the coords to an ellipse with center 0,0 + var normx = (x - this.x) / this.width; + var normy = (y - this.y) / this.height; + + normx *= normx; + normy *= normy; + + return normx + normy <= 1; + }; + + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Ellipse.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.width, this.y - this.height, this.width, this.height); + }; + + return Ellipse; +}(); + +exports.default = Ellipse; + +},{"../../const":44,"./Rectangle":72}],71:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('../Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Polygon = function () { + /** + * @param {PIXI.Point[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + for (var _len = arguments.length, points = Array(_len), _key = 0; _key < _len; _key++) { + points[_key] = arguments[_key]; + } + + _classCallCheck(this, Polygon); + + if (Array.isArray(points[0])) { + points = points[0]; + } + + // if this is an array of points, convert it to a flat array of numbers + if (points[0] instanceof _Point2.default) { + var p = []; + + for (var i = 0, il = points.length; i < il; i++) { + p.push(points[i].x, points[i].y); + } + + points = p; + } + + this.closed = true; + + /** + * An array of the points of this polygon + * + * @member {number[]} + */ + this.points = points; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.POLY + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.POLY; + } + + /** + * Creates a clone of this polygon + * + * @return {PIXI.Polygon} a copy of the polygon + */ + + + Polygon.prototype.clone = function clone() { + return new Polygon(this.points.slice()); + }; + + /** + * Closes the polygon, adding points if necessary. + * + */ + + + Polygon.prototype.close = function close() { + var points = this.points; + + // close the poly if the value is true! + if (points[0] !== points[points.length - 2] || points[1] !== points[points.length - 1]) { + points.push(points[0], points[1]); + } + }; + + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this polygon + */ + + + Polygon.prototype.contains = function contains(x, y) { + var inside = false; + + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + + for (var i = 0, j = length - 1; i < length; j = i++) { + var xi = this.points[i * 2]; + var yi = this.points[i * 2 + 1]; + var xj = this.points[j * 2]; + var yj = this.points[j * 2 + 1]; + var intersect = yi > y !== yj > y && x < (xj - xi) * ((y - yi) / (yj - yi)) + xi; + + if (intersect) { + inside = !inside; + } + } + + return inside; + }; + + return Polygon; +}(); + +exports.default = Polygon; + +},{"../../const":44,"../Point":67}],72:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * + * @class + * @memberof PIXI + */ +var Rectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle + * @param {number} [width=0] - The overall width of this rectangle + * @param {number} [height=0] - The overall height of this rectangle + */ + function Rectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Rectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.RECT + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RECT; + } + + /** + * returns the left edge of the rectangle + * + * @member {number} + */ + + + /** + * Creates a clone of this Rectangle + * + * @return {PIXI.Rectangle} a copy of the rectangle + */ + Rectangle.prototype.clone = function clone() { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + + /** + * Copies another rectangle to this one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to copy. + * @return {PIXI.Rectangle} Returns itself. + */ + + + Rectangle.prototype.copy = function copy(rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + + return this; + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rectangle + */ + + + Rectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + + return false; + }; + + /** + * Pads the rectangle making it grow in all directions. + * + * @param {number} paddingX - The horizontal padding amount. + * @param {number} paddingY - The vertical padding amount. + */ + + + Rectangle.prototype.pad = function pad(paddingX, paddingY) { + paddingX = paddingX || 0; + paddingY = paddingY || (paddingY !== 0 ? paddingX : 0); + + this.x -= paddingX; + this.y -= paddingY; + + this.width += paddingX * 2; + this.height += paddingY * 2; + }; + + /** + * Fits this rectangle around the passed one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to fit. + */ + + + Rectangle.prototype.fit = function fit(rectangle) { + if (this.x < rectangle.x) { + this.width += this.x; + if (this.width < 0) { + this.width = 0; + } + + this.x = rectangle.x; + } + + if (this.y < rectangle.y) { + this.height += this.y; + if (this.height < 0) { + this.height = 0; + } + this.y = rectangle.y; + } + + if (this.x + this.width > rectangle.x + rectangle.width) { + this.width = rectangle.width - this.x; + if (this.width < 0) { + this.width = 0; + } + } + + if (this.y + this.height > rectangle.y + rectangle.height) { + this.height = rectangle.height - this.y; + if (this.height < 0) { + this.height = 0; + } + } + }; + + /** + * Enlarges this rectangle to include the passed rectangle. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to include. + */ + + + Rectangle.prototype.enlarge = function enlarge(rectangle) { + var x1 = Math.min(this.x, rectangle.x); + var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.min(this.y, rectangle.y); + var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); + + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + }; + + _createClass(Rectangle, [{ + key: 'left', + get: function get() { + return this.x; + } + + /** + * returns the right edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'right', + get: function get() { + return this.x + this.width; + } + + /** + * returns the top edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'top', + get: function get() { + return this.y; + } + + /** + * returns the bottom edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'bottom', + get: function get() { + return this.y + this.height; + } + + /** + * A constant empty rectangle. + * + * @static + * @constant + */ + + }], [{ + key: 'EMPTY', + get: function get() { + return new Rectangle(0, 0, 0, 0); + } + }]); + + return Rectangle; +}(); + +exports.default = Rectangle; + +},{"../../const":44}],73:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. + * + * @class + * @memberof PIXI + */ +var RoundedRectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle + * @param {number} [width=0] - The overall width of this rounded rectangle + * @param {number} [height=0] - The overall height of this rounded rectangle + * @param {number} [radius=20] - Controls the radius of the rounded corners + */ + function RoundedRectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var radius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 20; + + _classCallCheck(this, RoundedRectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * @member {number} + * @default 20 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readonly + * @default PIXI.SHAPES.RREC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RREC; + } + + /** + * Creates a clone of this Rounded Rectangle + * + * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle + */ + + + RoundedRectangle.prototype.clone = function clone() { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + */ + + + RoundedRectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + if (y >= this.y + this.radius && y <= this.y + this.height - this.radius || x >= this.x + this.radius && x <= this.x + this.width - this.radius) { + return true; + } + var dx = x - (this.x + this.radius); + var dy = y - (this.y + this.radius); + var radius2 = this.radius * this.radius; + + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.width - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dy = y - (this.y + this.height - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + } + } + + return false; + }; + + return RoundedRectangle; +}(); + +exports.default = RoundedRectangle; + +},{"../../const":44}],74:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _math = require('../math'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _Container = require('../display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMatrix = new _math.Matrix(); + +/** + * The SystemRenderer is the base for a Pixi Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.WebGLRenderer} which can be used for rendering a Pixi scene. + * + * @abstract + * @class + * @extends EventEmitter + * @memberof PIXI + */ + +var SystemRenderer = function (_EventEmitter) { + _inherits(SystemRenderer, _EventEmitter); + + /** + * @param {string} system - The name of the system this renderer is for. + * @param {number} [screenWidth=800] - the width of the screen + * @param {number} [screenHeight=600] - the height of the screen + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function SystemRenderer(system, screenWidth, screenHeight, options) { + _classCallCheck(this, SystemRenderer); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + (0, _utils.sayHello)(system); + + // prepare options + if (options) { + for (var i in _settings2.default.RENDER_OPTIONS) { + if (typeof options[i] === 'undefined') { + options[i] = _settings2.default.RENDER_OPTIONS[i]; + } + } + } else { + options = _settings2.default.RENDER_OPTIONS; + } + + /** + * The type of the renderer. + * + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.UNKNOWN; + + /** + * Measurements of the screen. (0, 0, screenWidth, screenHeight) + * + * Its safe to use as filterArea or hitArea for whole stage + * + * @member {PIXI.Rectangle} + */ + _this.screen = new _math.Rectangle(0, 0, screenWidth || 800, screenHeight || 600); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.view = options.view || document.createElement('canvas'); + + /** + * The resolution / device pixel ratio of the renderer + * + * @member {number} + * @default 1 + */ + _this.resolution = options.resolution || _settings2.default.RESOLUTION; + + /** + * Whether the render view is transparent + * + * @member {boolean} + */ + _this.transparent = options.transparent; + + /** + * Whether css dimensions of canvas view should be resized to screen dimensions automatically + * + * @member {boolean} + */ + _this.autoResize = options.autoResize || false; + + /** + * Tracks the blend modes useful for this renderer. + * + * @member {object} + */ + _this.blendModes = null; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent Pixi will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent Pixi will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example if + * your game has a canvas filling background image you often don't need this set. + * + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + * + * @member {boolean} + */ + _this.roundPixels = options.roundPixels; + + /** + * The background color as a number. + * + * @member {number} + * @private + */ + _this._backgroundColor = 0x000000; + + /** + * The background color as an [R, G, B] array. + * + * @member {number[]} + * @private + */ + _this._backgroundColorRgba = [0, 0, 0, 0]; + + /** + * The background color as a string. + * + * @member {string} + * @private + */ + _this._backgroundColorString = '#000000'; + + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + + /** + * This temporary display object used as the parent of the currently being rendered item + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._tempDisplayObjectParent = new _Container2.default(); + + /** + * The last root object that the renderer tried to render. + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._lastObjectRendered = _this._tempDisplayObjectParent; + return _this; + } + + /** + * Same as view.width, actual number of pixels in the canvas by horizontal + * + * @member {number} + * @readonly + * @default 800 + */ + + + /** + * Resizes the screen and canvas to the specified width and height + * Canvas dimensions are multiplied by resolution + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + SystemRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + this.screen.width = screenWidth; + this.screen.height = screenHeight; + + this.view.width = screenWidth * this.resolution; + this.view.height = screenHeight * this.resolution; + + if (this.autoResize) { + this.view.style.width = screenWidth + 'px'; + this.view.style.height = screenHeight + 'px'; + } + }; + + /** + * Useful function that returns a texture of the display object that can then be used to create sprites + * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. + * + * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from + * @param {number} scaleMode - Should be one of the scaleMode consts + * @param {number} resolution - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.Texture} a texture of the graphics object + */ + + + SystemRenderer.prototype.generateTexture = function generateTexture(displayObject, scaleMode, resolution) { + var bounds = displayObject.getLocalBounds(); + + var renderTexture = _RenderTexture2.default.create(bounds.width | 0, bounds.height | 0, scaleMode, resolution); + + tempMatrix.tx = -bounds.x; + tempMatrix.ty = -bounds.y; + + this.render(displayObject, renderTexture, false, tempMatrix, true); + + return renderTexture; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + SystemRenderer.prototype.destroy = function destroy(removeView) { + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } + + this.type = _const.RENDERER_TYPE.UNKNOWN; + + this.view = null; + + this.screen = null; + + this.resolution = 0; + + this.transparent = false; + + this.autoResize = false; + + this.blendModes = null; + + this.preserveDrawingBuffer = false; + this.clearBeforeRender = false; + + this.roundPixels = false; + + this._backgroundColor = 0; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + + this.backgroundColor = 0; + this._tempDisplayObjectParent = null; + this._lastObjectRendered = null; + }; + + /** + * The background color to fill if not transparent + * + * @member {number} + */ + + + _createClass(SystemRenderer, [{ + key: 'width', + get: function get() { + return this.view.width; + } + + /** + * Same as view.height, actual number of pixels in the canvas by vertical + * + * @member {number} + * @readonly + * @default 600 + */ + + }, { + key: 'height', + get: function get() { + return this.view.height; + } + }, { + key: 'backgroundColor', + get: function get() { + return this._backgroundColor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._backgroundColor = value; + this._backgroundColorString = (0, _utils.hex2string)(value); + (0, _utils.hex2rgb)(value, this._backgroundColorRgba); + } + }]); + + return SystemRenderer; +}(_eventemitter2.default); + +exports.default = SystemRenderer; + +},{"../const":44,"../display/Container":46,"../math":68,"../settings":99,"../textures/RenderTexture":110,"../utils":120,"eventemitter3":3}],75:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _CanvasMaskManager = require('./utils/CanvasMaskManager'); + +var _CanvasMaskManager2 = _interopRequireDefault(_CanvasMaskManager); + +var _CanvasRenderTarget = require('./utils/CanvasRenderTarget'); + +var _CanvasRenderTarget2 = _interopRequireDefault(_CanvasRenderTarget); + +var _mapCanvasBlendModesToPixi = require('./utils/mapCanvasBlendModesToPixi'); + +var _mapCanvasBlendModesToPixi2 = _interopRequireDefault(_mapCanvasBlendModesToPixi); + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should + * be used for browsers that do not support WebGL. Don't forget to add the CanvasRenderer.view to + * your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ +var CanvasRenderer = function (_SystemRenderer) { + _inherits(CanvasRenderer, _SystemRenderer); + + /** + * @param {number} [screenWidth=800] - the width of the screen + * @param {number} [screenHeight=600] - the height of the screen + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function CanvasRenderer(screenWidth, screenHeight) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + _classCallCheck(this, CanvasRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'Canvas', screenWidth, screenHeight, options)); + + _this.type = _const.RENDERER_TYPE.CANVAS; + + /** + * The canvas 2d context that everything is drawn with. + * + * @member {CanvasRenderingContext2D} + */ + _this.rootContext = _this.view.getContext('2d', { alpha: _this.transparent }); + + /** + * Boolean flag controlling canvas refresh. + * + * @member {boolean} + */ + _this.refresh = true; + + /** + * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. + * + * @member {PIXI.CanvasMaskManager} + */ + _this.maskManager = new _CanvasMaskManager2.default(_this); + + /** + * The canvas property used to set the canvas smoothing property. + * + * @member {string} + */ + _this.smoothProperty = 'imageSmoothingEnabled'; + + if (!_this.rootContext.imageSmoothingEnabled) { + if (_this.rootContext.webkitImageSmoothingEnabled) { + _this.smoothProperty = 'webkitImageSmoothingEnabled'; + } else if (_this.rootContext.mozImageSmoothingEnabled) { + _this.smoothProperty = 'mozImageSmoothingEnabled'; + } else if (_this.rootContext.oImageSmoothingEnabled) { + _this.smoothProperty = 'oImageSmoothingEnabled'; + } else if (_this.rootContext.msImageSmoothingEnabled) { + _this.smoothProperty = 'msImageSmoothingEnabled'; + } + } + + _this.initPlugins(); + + _this.blendModes = (0, _mapCanvasBlendModesToPixi2.default)(); + _this._activeBlendMode = null; + + _this.context = null; + _this.renderingToScreen = false; + + _this.resize(screenWidth, screenHeight); + return _this; + } + + /** + * Renders the object to this canvas view + * + * @param {PIXI.DisplayObject} displayObject - The object to be rendered + * @param {PIXI.RenderTexture} [renderTexture] - A render texture to be rendered to. + * If unset, it will render to the root context. + * @param {boolean} [clear=false] - Whether to clear the canvas before drawing + * @param {PIXI.Transform} [transform] - A transformation to be applied + * @param {boolean} [skipUpdateTransform=false] - Whether to skip the update transform + */ + + + CanvasRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!this.view) { + return; + } + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + var rootResolution = this.resolution; + + if (renderTexture) { + renderTexture = renderTexture.baseTexture || renderTexture; + + if (!renderTexture._canvasRenderTarget) { + renderTexture._canvasRenderTarget = new _CanvasRenderTarget2.default(renderTexture.width, renderTexture.height, renderTexture.resolution); + renderTexture.source = renderTexture._canvasRenderTarget.canvas; + renderTexture.valid = true; + } + + this.context = renderTexture._canvasRenderTarget.context; + this.resolution = renderTexture._canvasRenderTarget.resolution; + } else { + this.context = this.rootContext; + } + + var context = this.context; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + var tempWt = this._tempDisplayObjectParent.transform.worldTransform; + + if (transform) { + transform.copy(tempWt); + + // lets not forget to flag the parent transform as dirty... + this._tempDisplayObjectParent.transform._worldID = -1; + } else { + tempWt.identity(); + } + + displayObject.parent = this._tempDisplayObjectParent; + + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + context.setTransform(1, 0, 0, 1, 0, 0); + context.globalAlpha = 1; + context.globalCompositeOperation = this.blendModes[_const.BLEND_MODES.NORMAL]; + + if (navigator.isCocoonJS && this.view.screencanvas) { + context.fillStyle = 'black'; + context.clear(); + } + + if (clear !== undefined ? clear : this.clearBeforeRender) { + if (this.renderingToScreen) { + if (this.transparent) { + context.clearRect(0, 0, this.width, this.height); + } else { + context.fillStyle = this._backgroundColorString; + context.fillRect(0, 0, this.width, this.height); + } + } // else { + // TODO: implement background for CanvasRenderTarget or RenderTexture? + // } + } + + // TODO RENDER TARGET STUFF HERE.. + var tempContext = this.context; + + this.context = context; + displayObject.renderCanvas(this); + this.context = tempContext; + + this.resolution = rootResolution; + + this.emit('postrender'); + }; + + /** + * Clear the canvas of renderer. + * + * @param {string} [clearColor] - Clear the canvas with this color, except the canvas is transparent. + */ + + + CanvasRenderer.prototype.clear = function clear(clearColor) { + var context = this.context; + + clearColor = clearColor || this._backgroundColorString; + + if (!this.transparent && clearColor) { + context.fillStyle = clearColor; + context.fillRect(0, 0, this.width, this.height); + } else { + context.clearRect(0, 0, this.width, this.height); + } + }; + + /** + * Sets the blend mode of the renderer. + * + * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values. + */ + + + CanvasRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + if (this._activeBlendMode === blendMode) { + return; + } + + this._activeBlendMode = blendMode; + this.context.globalCompositeOperation = this.blendModes[blendMode]; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + CanvasRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // call the base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.context = null; + + this.refresh = true; + + this.maskManager.destroy(); + this.maskManager = null; + + this.smoothProperty = null; + }; + + /** + * Resizes the canvas view to the specified width and height. + * + * @extends PIXI.SystemRenderer#resize + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + CanvasRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + _SystemRenderer.prototype.resize.call(this, screenWidth, screenHeight); + + // reset the scale mode.. oddly this seems to be reset when the canvas is resized. + // surely a browser bug?? Let pixi fix that for you.. + if (this.smoothProperty) { + this.rootContext[this.smoothProperty] = _settings2.default.SCALE_MODE === _const.SCALE_MODES.LINEAR; + } + }; + + return CanvasRenderer; +}(_SystemRenderer3.default); + +exports.default = CanvasRenderer; + + +_utils.pluginTarget.mixin(CanvasRenderer); + +},{"../../const":44,"../../settings":99,"../../utils":120,"../SystemRenderer":74,"./utils/CanvasMaskManager":76,"./utils/CanvasRenderTarget":77,"./utils/mapCanvasBlendModesToPixi":79}],76:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A set of functions used to handle masking. + * + * @class + * @memberof PIXI + */ +var CanvasMaskManager = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + function CanvasMaskManager(renderer) { + _classCallCheck(this, CanvasMaskManager); + + this.renderer = renderer; + } + + /** + * This method adds it to the current stack of masks. + * + * @param {object} maskData - the maskData that will be pushed + */ + + + CanvasMaskManager.prototype.pushMask = function pushMask(maskData) { + var renderer = this.renderer; + + renderer.context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.transform.worldTransform; + var resolution = renderer.resolution; + + renderer.context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // TODO suport sprite alpha masks?? + // lots of effort required. If demand is great enough.. + if (!maskData._texture) { + this.renderGraphicsShape(maskData); + renderer.context.clip(); + } + + maskData.worldAlpha = cacheAlpha; + }; + + /** + * Renders a PIXI.Graphics shape. + * + * @param {PIXI.Graphics} graphics - The object to render. + */ + + + CanvasMaskManager.prototype.renderGraphicsShape = function renderGraphicsShape(graphics) { + var context = this.renderer.context; + var len = graphics.graphicsData.length; + + if (len === 0) { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === _const.SHAPES.POLY) { + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; j++) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) { + context.closePath(); + } + } else if (data.type === _const.SHAPES.RECT) { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } + }; + + /** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @param {PIXI.CanvasRenderer} renderer - The renderer context to use. + */ + + + CanvasMaskManager.prototype.popMask = function popMask(renderer) { + renderer.context.restore(); + }; + + /** + * Destroys this canvas mask manager. + * + */ + + + CanvasMaskManager.prototype.destroy = function destroy() { + /* empty */ + }; + + return CanvasMaskManager; +}(); + +exports.default = CanvasMaskManager; + +},{"../../../const":44}],77:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Creates a Canvas element of the given size. + * + * @class + * @memberof PIXI + */ +var CanvasRenderTarget = function () { + /** + * @param {number} width - the width for the newly created canvas + * @param {number} height - the height for the newly created canvas + * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + _classCallCheck(this, CanvasRenderTarget); + + /** + * The Canvas object that belongs to this CanvasRenderTarget. + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @member {CanvasRenderingContext2D} + */ + this.context = this.canvas.getContext('2d'); + + this.resolution = resolution || _settings2.default.RESOLUTION; + + this.resize(width, height); + } + + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * + * @private + */ + + + CanvasRenderTarget.prototype.clear = function clear() { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + + /** + * Resizes the canvas to the specified width and height. + * + * @param {number} width - the new width of the canvas + * @param {number} height - the new height of the canvas + */ + + + CanvasRenderTarget.prototype.resize = function resize(width, height) { + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; + }; + + /** + * Destroys this canvas. + * + */ + + + CanvasRenderTarget.prototype.destroy = function destroy() { + this.context = null; + this.canvas = null; + }; + + /** + * The width of the canvas buffer in pixels. + * + * @member {number} + */ + + + _createClass(CanvasRenderTarget, [{ + key: 'width', + get: function get() { + return this.canvas.width; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.width = val; + } + + /** + * The height of the canvas buffer in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.canvas.height; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.height = val; + } + }]); + + return CanvasRenderTarget; +}(); + +exports.default = CanvasRenderTarget; + +},{"../../../settings":99}],78:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = canUseNewCanvasBlendModes; +/** + * Creates a little colored canvas + * + * @ignore + * @param {string} color - The color to make the canvas + * @return {canvas} a small canvas element + */ +function createColoredCanvas(color) { + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.fillStyle = color; + context.fillRect(0, 0, 6, 1); + + return canvas; +} + +/** + * Checks whether the Canvas BlendModes are supported by the current browser + * + * @return {boolean} whether they are supported + */ +function canUseNewCanvasBlendModes() { + if (typeof document === 'undefined') { + return false; + } + + var magenta = createColoredCanvas('#ff00ff'); + var yellow = createColoredCanvas('#ffff00'); + + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.globalCompositeOperation = 'multiply'; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + var imageData = context.getImageData(2, 0, 1, 1); + + if (!imageData) { + return false; + } + + var data = imageData.data; + + return data[0] === 255 && data[1] === 0 && data[2] === 0; +} + +},{}],79:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapCanvasBlendModesToPixi; + +var _const = require('../../../const'); + +var _canUseNewCanvasBlendModes = require('./canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Maps blend combinations to Canvas. + * + * @memberof PIXI + * @function mapCanvasBlendModesToPixi + * @private + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapCanvasBlendModesToPixi() { + var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + + if ((0, _canUseNewCanvasBlendModes2.default)()) { + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'multiply'; + array[_const.BLEND_MODES.SCREEN] = 'screen'; + array[_const.BLEND_MODES.OVERLAY] = 'overlay'; + array[_const.BLEND_MODES.DARKEN] = 'darken'; + array[_const.BLEND_MODES.LIGHTEN] = 'lighten'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'color-dodge'; + array[_const.BLEND_MODES.COLOR_BURN] = 'color-burn'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'hard-light'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'soft-light'; + array[_const.BLEND_MODES.DIFFERENCE] = 'difference'; + array[_const.BLEND_MODES.EXCLUSION] = 'exclusion'; + array[_const.BLEND_MODES.HUE] = 'hue'; + array[_const.BLEND_MODES.SATURATION] = 'saturate'; + array[_const.BLEND_MODES.COLOR] = 'color'; + array[_const.BLEND_MODES.LUMINOSITY] = 'luminosity'; + } else { + // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'source-over'; + array[_const.BLEND_MODES.SCREEN] = 'source-over'; + array[_const.BLEND_MODES.OVERLAY] = 'source-over'; + array[_const.BLEND_MODES.DARKEN] = 'source-over'; + array[_const.BLEND_MODES.LIGHTEN] = 'source-over'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'source-over'; + array[_const.BLEND_MODES.COLOR_BURN] = 'source-over'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.DIFFERENCE] = 'source-over'; + array[_const.BLEND_MODES.EXCLUSION] = 'source-over'; + array[_const.BLEND_MODES.HUE] = 'source-over'; + array[_const.BLEND_MODES.SATURATION] = 'source-over'; + array[_const.BLEND_MODES.COLOR] = 'source-over'; + array[_const.BLEND_MODES.LUMINOSITY] = 'source-over'; + } + + return array; +} + +},{"../../../const":44,"./canUseNewCanvasBlendModes":78}],80:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged + * up with textures that are no longer being used. + * + * @class + * @memberof PIXI + */ +var TextureGarbageCollector = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function TextureGarbageCollector(renderer) { + _classCallCheck(this, TextureGarbageCollector); + + this.renderer = renderer; + + this.count = 0; + this.checkCount = 0; + this.maxIdle = _settings2.default.GC_MAX_IDLE; + this.checkCountMax = _settings2.default.GC_MAX_CHECK_COUNT; + this.mode = _settings2.default.GC_MODE; + } + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.update = function update() { + this.count++; + + if (this.mode === _const.GC_MODES.MANUAL) { + return; + } + + this.checkCount++; + + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + + this.run(); + } + }; + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.run = function run() { + var tm = this.renderer.textureManager; + var managedTextures = tm._managedTextures; + var wasRemoved = false; + + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + + // only supports non generated textures at the moment! + if (!texture._glRenderTargets && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + + if (wasRemoved) { + var j = 0; + + for (var _i = 0; _i < managedTextures.length; _i++) { + if (managedTextures[_i] !== null) { + managedTextures[j++] = managedTextures[_i]; + } + } + + managedTextures.length = j; + } + }; + + /** + * Removes all the textures within the specified displayObject and its children from the GPU + * + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + */ + + + TextureGarbageCollector.prototype.unload = function unload(displayObject) { + var tm = this.renderer.textureManager; + + // only destroy non generated textures + if (displayObject._texture && displayObject._texture._glRenderTargets) { + tm.destroyTexture(displayObject._texture, true); + } + + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + + return TextureGarbageCollector; +}(); + +exports.default = TextureGarbageCollector; + +},{"../../const":44,"../../settings":99}],81:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _const = require('../../const'); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _utils = require('../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a webGL Texture + * + * @class + * @memberof PIXI + */ +var TextureManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function TextureManager(renderer) { + _classCallCheck(this, TextureManager); + + /** + * A reference to the current renderer + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = renderer.gl; + + /** + * Track textures in the renderer so we can no longer listen to them on destruction. + * + * @member {Array<*>} + * @private + */ + this._managedTextures = []; + } + + /** + * Binds a texture. + * + */ + + + TextureManager.prototype.bindTexture = function bindTexture() {} + // empty + + + /** + * Gets a texture. + * + */ + ; + + TextureManager.prototype.getTexture = function getTexture() {} + // empty + + + /** + * Updates and/or Creates a WebGL texture for the renderer's context. + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update + * @param {number} location - the location the texture will be bound to. + * @return {GLTexture} The gl texture. + */ + ; + + TextureManager.prototype.updateTexture = function updateTexture(texture, location) { + // assume it good! + // texture = texture.baseTexture || texture; + + var gl = this.gl; + + var isRenderTexture = !!texture._glRenderTargets; + + if (!texture.hasLoaded) { + return null; + } + + var boundTextures = this.renderer.boundTextures; + + // if the location is undefined then this may have been called by n event. + // this being the case the texture may already be bound to a slot. As a texture can only be bound once + // we need to find its current location if it exists. + if (location === undefined) { + location = 0; + + // TODO maybe we can use texture bound ids later on... + // check if texture is already bound.. + for (var i = 0; i < boundTextures.length; ++i) { + if (boundTextures[i] === texture) { + location = i; + break; + } + } + } + + boundTextures[location] = texture; + + gl.activeTexture(gl.TEXTURE0 + location); + + var glTexture = texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!glTexture) { + if (isRenderTexture) { + var renderTarget = new _RenderTarget2.default(this.gl, texture.width, texture.height, texture.scaleMode, texture.resolution); + + renderTarget.resize(texture.width, texture.height); + texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget; + glTexture = renderTarget.texture; + } else { + glTexture = new _pixiGlCore.GLTexture(this.gl, null, null, null, null); + glTexture.bind(location); + glTexture.premultiplyAlpha = true; + glTexture.upload(texture.source); + } + + texture._glTextures[this.renderer.CONTEXT_UID] = glTexture; + + texture.on('update', this.updateTexture, this); + texture.on('dispose', this.destroyTexture, this); + + this._managedTextures.push(texture); + + if (texture.isPowerOfTwo) { + if (texture.mipmap) { + glTexture.enableMipmap(); + } + + if (texture.wrapMode === _const.WRAP_MODES.CLAMP) { + glTexture.enableWrapClamp(); + } else if (texture.wrapMode === _const.WRAP_MODES.REPEAT) { + glTexture.enableWrapRepeat(); + } else { + glTexture.enableWrapMirrorRepeat(); + } + } else { + glTexture.enableWrapClamp(); + } + + if (texture.scaleMode === _const.SCALE_MODES.NEAREST) { + glTexture.enableNearestScaling(); + } else { + glTexture.enableLinearScaling(); + } + } + // the texture already exists so we only need to update it.. + else if (isRenderTexture) { + texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height); + } else { + glTexture.upload(texture.source); + } + + return glTexture; + }; + + /** + * Deletes the texture from WebGL + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy + * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. + */ + + + TextureManager.prototype.destroyTexture = function destroyTexture(texture, skipRemove) { + texture = texture.baseTexture || texture; + + if (!texture.hasLoaded) { + return; + } + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + this.renderer.unbindTexture(texture); + + texture._glTextures[this.renderer.CONTEXT_UID].destroy(); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + + delete texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!skipRemove) { + var i = this._managedTextures.indexOf(texture); + + if (i !== -1) { + (0, _utils.removeItems)(this._managedTextures, i, 1); + } + } + } + }; + + /** + * Deletes all the textures from WebGL + */ + + + TextureManager.prototype.removeAll = function removeAll() { + // empty all the old gl textures as they are useless now + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + delete texture._glTextures[this.renderer.CONTEXT_UID]; + } + } + }; + + /** + * Destroys this manager and removes all its textures + */ + + + TextureManager.prototype.destroy = function destroy() { + // destroy managed textures + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + this.destroyTexture(texture, true); + + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + } + + this._managedTextures = null; + }; + + return TextureManager; +}(); + +exports.default = TextureManager; + +},{"../../const":44,"../../utils":120,"./utils/RenderTarget":94,"pixi-gl-core":12}],82:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _MaskManager = require('./managers/MaskManager'); + +var _MaskManager2 = _interopRequireDefault(_MaskManager); + +var _StencilManager = require('./managers/StencilManager'); + +var _StencilManager2 = _interopRequireDefault(_StencilManager); + +var _FilterManager = require('./managers/FilterManager'); + +var _FilterManager2 = _interopRequireDefault(_FilterManager); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _ObjectRenderer = require('./utils/ObjectRenderer'); + +var _ObjectRenderer2 = _interopRequireDefault(_ObjectRenderer); + +var _TextureManager = require('./TextureManager'); + +var _TextureManager2 = _interopRequireDefault(_TextureManager); + +var _BaseTexture = require('../../textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _TextureGarbageCollector = require('./TextureGarbageCollector'); + +var _TextureGarbageCollector2 = _interopRequireDefault(_TextureGarbageCollector); + +var _WebGLState = require('./WebGLState'); + +var _WebGLState2 = _interopRequireDefault(_WebGLState); + +var _mapWebGLDrawModesToPixi = require('./utils/mapWebGLDrawModesToPixi'); + +var _mapWebGLDrawModesToPixi2 = _interopRequireDefault(_mapWebGLDrawModesToPixi); + +var _validateContext = require('./utils/validateContext'); + +var _validateContext2 = _interopRequireDefault(_validateContext); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CONTEXT_UID = 0; + +/** + * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ + +var WebGLRenderer = function (_SystemRenderer) { + _inherits(WebGLRenderer, _SystemRenderer); + + /** + * + * @param {number} [screenWidth=800] - the width of the screen + * @param {number} [screenHeight=600] - the height of the screen + * @param {object} [options] - The optional renderer parameters + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias. If not available natively then FXAA + * antialiasing is used + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. + * The resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the CanvasRenderer will clear + * the canvas or not before the new render pass. If you wish to set this to false, you *must* set + * preserveDrawingBuffer to `true`. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when + * rendering, stopping pixel interpolation. + * @param {boolean} [options.legacy=false] - If true Pixi will aim to ensure compatibility + * with older / less advanced devices. If you experiance unexplained flickering try setting this to true. + */ + function WebGLRenderer(screenWidth, screenHeight) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + _classCallCheck(this, WebGLRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'WebGL', screenWidth, screenHeight, options)); + + _this.legacy = !!options.legacy; + + if (_this.legacy) { + _pixiGlCore2.default.VertexArrayObject.FORCE_NATIVE = true; + } + + /** + * The type of this renderer as a standardised const + * + * @member {number} + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.WEBGL; + + _this.handleContextLost = _this.handleContextLost.bind(_this); + _this.handleContextRestored = _this.handleContextRestored.bind(_this); + + _this.view.addEventListener('webglcontextlost', _this.handleContextLost, false); + _this.view.addEventListener('webglcontextrestored', _this.handleContextRestored, false); + + /** + * The options passed in to create a new webgl context. + * + * @member {object} + * @private + */ + _this._contextOptions = { + alpha: _this.transparent, + antialias: options.antialias, + premultipliedAlpha: _this.transparent && _this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: options.preserveDrawingBuffer + }; + + _this._backgroundColorRgba[3] = _this.transparent ? 0 : 1; + + /** + * Manages the masks using the stencil buffer. + * + * @member {PIXI.MaskManager} + */ + _this.maskManager = new _MaskManager2.default(_this); + + /** + * Manages the stencil buffer. + * + * @member {PIXI.StencilManager} + */ + _this.stencilManager = new _StencilManager2.default(_this); + + /** + * An empty renderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.emptyRenderer = new _ObjectRenderer2.default(_this); + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.currentRenderer = _this.emptyRenderer; + + _this.initPlugins(); + + /** + * The current WebGL rendering context, it is created here + * + * @member {WebGLRenderingContext} + */ + // initialize the context so it is ready for the managers. + if (options.context) { + // checks to see if a context is valid.. + (0, _validateContext2.default)(options.context); + } + + _this.gl = options.context || _pixiGlCore2.default.createContext(_this.view, _this._contextOptions); + + _this.CONTEXT_UID = CONTEXT_UID++; + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.WebGLState} + */ + _this.state = new _WebGLState2.default(_this.gl); + + _this.renderingToScreen = true; + + /** + * Holds the current state of textures bound to the GPU. + * @type {Array} + */ + _this.boundTextures = null; + + /** + * Holds the current shader + * + * @member {PIXI.Shader} + */ + _this._activeShader = null; + + _this._activeVao = null; + + /** + * Holds the current render target + * + * @member {PIXI.RenderTarget} + */ + _this._activeRenderTarget = null; + + _this._initContext(); + + /** + * Manages the filters. + * + * @member {PIXI.FilterManager} + */ + _this.filterManager = new _FilterManager2.default(_this); + // map some webGL blend and drawmodes.. + _this.drawModes = (0, _mapWebGLDrawModesToPixi2.default)(_this.gl); + + _this._nextTextureLocation = 0; + + _this.setBlendMode(0); + return _this; + } + + /** + * Creates the WebGL context + * + * @private + */ + + + WebGLRenderer.prototype._initContext = function _initContext() { + var gl = this.gl; + + // restore a context if it was previously lost + if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').restoreContext(); + } + + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + + this.boundTextures = new Array(maxTextures); + this.emptyTextures = new Array(maxTextures); + + // create a texture manager... + this.textureManager = new _TextureManager2.default(this); + this.textureGC = new _TextureGarbageCollector2.default(this); + + this.state.resetToDefault(); + + this.rootRenderTarget = new _RenderTarget2.default(gl, this.width, this.height, null, this.resolution, true); + this.rootRenderTarget.clearColor = this._backgroundColorRgba; + + this.bindRenderTarget(this.rootRenderTarget); + + // now lets fill up the textures with empty ones! + var emptyGLTexture = new _pixiGlCore2.default.GLTexture.fromData(gl, null, 1, 1); + + var tempObj = { _glTextures: {} }; + + tempObj._glTextures[this.CONTEXT_UID] = {}; + + for (var i = 0; i < maxTextures; i++) { + var empty = new _BaseTexture2.default(); + + empty._glTextures[this.CONTEXT_UID] = emptyGLTexture; + + this.boundTextures[i] = tempObj; + this.emptyTextures[i] = empty; + this.bindTexture(null, i); + } + + this.emit('context', gl); + + // setup the width/height properties and gl viewport + this.resize(this.screen.width, this.screen.height); + }; + + /** + * Renders the object to its webGL view + * + * @param {PIXI.DisplayObject} displayObject - the object to be rendered + * @param {PIXI.RenderTexture} renderTexture - The render texture to render to. + * @param {boolean} [clear] - Should the canvas be cleared before the new render + * @param {PIXI.Transform} [transform] - A transform to apply to the render texture before rendering. + * @param {boolean} [skipUpdateTransform] - Should we skip the update transform pass? + */ + + + WebGLRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + // no point rendering if our context has been blown up! + if (!this.gl || this.gl.isContextLost()) { + return; + } + + this._nextTextureLocation = 0; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + this.bindRenderTexture(renderTexture, transform); + + this.currentRenderer.start(); + + if (clear !== undefined ? clear : this.clearBeforeRender) { + this._activeRenderTarget.clear(); + } + + displayObject.renderWebGL(this); + + // apply transform.. + this.currentRenderer.flush(); + + // this.setObjectRenderer(this.emptyRenderer); + + this.textureGC.update(); + + this.emit('postrender'); + }; + + /** + * Changes the current renderer to the one given in parameter + * + * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. + */ + + + WebGLRenderer.prototype.setObjectRenderer = function setObjectRenderer(objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; + + /** + * This should be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + * + */ + + + WebGLRenderer.prototype.flush = function flush() { + this.setObjectRenderer(this.emptyRenderer); + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + WebGLRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + // if(width * this.resolution === this.width && height * this.resolution === this.height)return; + + _SystemRenderer3.default.prototype.resize.call(this, screenWidth, screenHeight); + + this.rootRenderTarget.resize(screenWidth, screenHeight); + + if (this._activeRenderTarget === this.rootRenderTarget) { + this.rootRenderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true); + } + } + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} blendMode - the desired blend mode + */ + + + WebGLRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + this.state.setBlendMode(blendMode); + }; + + /** + * Erases the active render target and fills the drawing area with a colour + * + * @param {number} [clearColor] - The colour + */ + + + WebGLRenderer.prototype.clear = function clear(clearColor) { + this._activeRenderTarget.clear(clearColor); + }; + + /** + * Sets the transform of the active render target to the given matrix + * + * @param {PIXI.Matrix} matrix - The transformation matrix + */ + + + WebGLRenderer.prototype.setTransform = function setTransform(matrix) { + this._activeRenderTarget.transform = matrix; + }; + + /** + * Erases the render texture and fills the drawing area with a colour + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to clear + * @param {number} [clearColor] - The colour + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.clearRenderTexture = function clearRenderTexture(renderTexture, clearColor) { + var baseTexture = renderTexture.baseTexture; + var renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + + if (renderTarget) { + renderTarget.clear(clearColor); + } + + return this; + }; + + /** + * Binds a render texture for rendering + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to render + * @param {PIXI.Transform} transform - The transform to be applied to the render texture + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTexture = function bindRenderTexture(renderTexture, transform) { + var renderTarget = void 0; + + if (renderTexture) { + var baseTexture = renderTexture.baseTexture; + + if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) { + // bind the current texture + this.textureManager.updateTexture(baseTexture, 0); + } + + this.unbindTexture(baseTexture); + + renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + renderTarget.setFrame(renderTexture.frame); + } else { + renderTarget = this.rootRenderTarget; + } + + renderTarget.transform = transform; + this.bindRenderTarget(renderTarget); + + return this; + }; + + /** + * Changes the current render target to the one given in parameter + * + * @param {PIXI.RenderTarget} renderTarget - the new render target + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTarget = function bindRenderTarget(renderTarget) { + if (renderTarget !== this._activeRenderTarget) { + this._activeRenderTarget = renderTarget; + renderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true); + } + + this.stencilManager.setMaskStack(renderTarget.stencilMaskStack); + } + + return this; + }; + + /** + * Changes the current shader to the one given in parameter + * + * @param {PIXI.Shader} shader - the new shader + * @param {boolean} [autoProject=true] - Whether automatically set the projection matrix + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindShader = function bindShader(shader, autoProject) { + // TODO cache + if (this._activeShader !== shader) { + this._activeShader = shader; + shader.bind(); + + // `autoProject` normally would be a default parameter set to true + // but because of how Babel transpiles default parameters + // it hinders the performance of this method. + if (autoProject !== false) { + // automatically set the projection matrix + shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(true); + } + } + + return this; + }; + + /** + * Binds the texture. This will return the location of the bound texture. + * It may not be the same as the one you pass in. This is due to optimisation that prevents + * needless binding of textures. For example if the texture is already bound it will return the + * current location of the texture instead of the one provided. To bypass this use force location + * + * @param {PIXI.Texture} texture - the new texture + * @param {number} location - the suggested texture location + * @param {boolean} forceLocation - force the location + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindTexture = function bindTexture(texture, location, forceLocation) { + texture = texture || this.emptyTextures[location]; + texture = texture.baseTexture || texture; + texture.touched = this.textureGC.count; + + if (!forceLocation) { + // TODO - maybe look into adding boundIds.. save us the loop? + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + return i; + } + } + + if (location === undefined) { + this._nextTextureLocation++; + this._nextTextureLocation %= this.boundTextures.length; + location = this.boundTextures.length - this._nextTextureLocation - 1; + } + } else { + location = location || 0; + } + + var gl = this.gl; + var glTexture = texture._glTextures[this.CONTEXT_UID]; + + if (!glTexture) { + // this will also bind the texture.. + this.textureManager.updateTexture(texture, location); + } else { + // bind the current texture + this.boundTextures[location] = texture; + gl.activeTexture(gl.TEXTURE0 + location); + gl.bindTexture(gl.TEXTURE_2D, glTexture.texture); + } + + return location; + }; + + /** + * unbinds the texture ... + * + * @param {PIXI.Texture} texture - the texture to unbind + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.unbindTexture = function unbindTexture(texture) { + var gl = this.gl; + + texture = texture.baseTexture || texture; + + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + this.boundTextures[i] = this.emptyTextures[i]; + + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[i]._glTextures[this.CONTEXT_UID].texture); + } + } + + return this; + }; + + /** + * Creates a new VAO from this renderer's context and state. + * + * @return {VertexArrayObject} The new VAO. + */ + + + WebGLRenderer.prototype.createVao = function createVao() { + return new _pixiGlCore2.default.VertexArrayObject(this.gl, this.state.attribState); + }; + + /** + * Changes the current Vao to the one given in parameter + * + * @param {PIXI.VertexArrayObject} vao - the new Vao + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindVao = function bindVao(vao) { + if (this._activeVao === vao) { + return this; + } + + if (vao) { + vao.bind(); + } else if (this._activeVao) { + // TODO this should always be true i think? + this._activeVao.unbind(); + } + + this._activeVao = vao; + + return this; + }; + + /** + * Resets the WebGL state so you can render things however you fancy! + * + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.reset = function reset() { + this.setObjectRenderer(this.emptyRenderer); + + this._activeShader = null; + this._activeRenderTarget = this.rootRenderTarget; + + // bind the main frame buffer (the screen); + this.rootRenderTarget.activate(); + + this.state.resetToDefault(); + + return this; + }; + + /** + * Handles a lost webgl context + * + * @private + * @param {WebGLContextEvent} event - The context lost event. + */ + + + WebGLRenderer.prototype.handleContextLost = function handleContextLost(event) { + event.preventDefault(); + }; + + /** + * Handles a restored webgl context + * + * @private + */ + + + WebGLRenderer.prototype.handleContextRestored = function handleContextRestored() { + this._initContext(); + this.textureManager.removeAll(); + }; + + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + + + WebGLRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // remove listeners + this.view.removeEventListener('webglcontextlost', this.handleContextLost); + this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); + + this.textureManager.destroy(); + + // call base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.uid = 0; + + // destroy the managers + this.maskManager.destroy(); + this.stencilManager.destroy(); + this.filterManager.destroy(); + + this.maskManager = null; + this.filterManager = null; + this.textureManager = null; + this.currentRenderer = null; + + this.handleContextLost = null; + this.handleContextRestored = null; + + this._contextOptions = null; + this.gl.useProgram(null); + + if (this.gl.getExtension('WEBGL_lose_context')) { + this.gl.getExtension('WEBGL_lose_context').loseContext(); + } + + this.gl = null; + + // this = null; + }; + + return WebGLRenderer; +}(_SystemRenderer3.default); + +exports.default = WebGLRenderer; + + +_utils.pluginTarget.mixin(WebGLRenderer); + +},{"../../const":44,"../../textures/BaseTexture":109,"../../utils":120,"../SystemRenderer":74,"./TextureGarbageCollector":80,"./TextureManager":81,"./WebGLState":83,"./managers/FilterManager":88,"./managers/MaskManager":89,"./managers/StencilManager":90,"./utils/ObjectRenderer":92,"./utils/RenderTarget":94,"./utils/mapWebGLDrawModesToPixi":97,"./utils/validateContext":98,"pixi-gl-core":12}],83:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); + +var _mapWebGLBlendModesToPixi2 = _interopRequireDefault(_mapWebGLBlendModesToPixi); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var BLEND = 0; +var DEPTH_TEST = 1; +var FRONT_FACE = 2; +var CULL_FACE = 3; +var BLEND_FUNC = 4; + +/** + * A WebGL state machines + * + * @memberof PIXI + * @class + */ + +var WebGLState = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + */ + function WebGLState(gl) { + _classCallCheck(this, WebGLState); + + /** + * The current active state + * + * @member {Uint8Array} + */ + this.activeState = new Uint8Array(16); + + /** + * The default state + * + * @member {Uint8Array} + */ + this.defaultState = new Uint8Array(16); + + // default blend mode.. + this.defaultState[0] = 1; + + /** + * The current state index in the stack + * + * @member {number} + * @private + */ + this.stackIndex = 0; + + /** + * The stack holding all the different states + * + * @member {Array<*>} + * @private + */ + this.stack = []; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + this.attribState = { + tempAttribState: new Array(this.maxAttribs), + attribState: new Array(this.maxAttribs) + }; + + this.blendModes = (0, _mapWebGLBlendModesToPixi2.default)(gl); + + // check we have vao.. + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || gl.getExtension('MOZ_OES_vertex_array_object') || gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + /** + * Pushes a new active state + */ + + + WebGLState.prototype.push = function push() { + // next state.. + var state = this.stack[this.stackIndex]; + + if (!state) { + state = this.stack[this.stackIndex] = new Uint8Array(16); + } + + ++this.stackIndex; + + // copy state.. + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) { + state[i] = this.activeState[i]; + } + }; + + /** + * Pops a state out + */ + + + WebGLState.prototype.pop = function pop() { + var state = this.stack[--this.stackIndex]; + + this.setState(state); + }; + + /** + * Sets the current state + * + * @param {*} state - The state to set. + */ + + + WebGLState.prototype.setState = function setState(state) { + this.setBlend(state[BLEND]); + this.setDepthTest(state[DEPTH_TEST]); + this.setFrontFace(state[FRONT_FACE]); + this.setCullFace(state[CULL_FACE]); + this.setBlendMode(state[BLEND_FUNC]); + }; + + /** + * Enables or disabled blending. + * + * @param {boolean} value - Turn on or off webgl blending. + */ + + + WebGLState.prototype.setBlend = function setBlend(value) { + value = value ? 1 : 0; + + if (this.activeState[BLEND] === value) { + return; + } + + this.activeState[BLEND] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + }; + + /** + * Sets the blend mode. + * + * @param {number} value - The blend mode to set to. + */ + + + WebGLState.prototype.setBlendMode = function setBlendMode(value) { + if (value === this.activeState[BLEND_FUNC]) { + return; + } + + this.activeState[BLEND_FUNC] = value; + + this.gl.blendFunc(this.blendModes[value][0], this.blendModes[value][1]); + }; + + /** + * Sets whether to enable or disable depth test. + * + * @param {boolean} value - Turn on or off webgl depth testing. + */ + + + WebGLState.prototype.setDepthTest = function setDepthTest(value) { + value = value ? 1 : 0; + + if (this.activeState[DEPTH_TEST] === value) { + return; + } + + this.activeState[DEPTH_TEST] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + }; + + /** + * Sets whether to enable or disable cull face. + * + * @param {boolean} value - Turn on or off webgl cull face. + */ + + + WebGLState.prototype.setCullFace = function setCullFace(value) { + value = value ? 1 : 0; + + if (this.activeState[CULL_FACE] === value) { + return; + } + + this.activeState[CULL_FACE] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + }; + + /** + * Sets the gl front face. + * + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ + + + WebGLState.prototype.setFrontFace = function setFrontFace(value) { + value = value ? 1 : 0; + + if (this.activeState[FRONT_FACE] === value) { + return; + } + + this.activeState[FRONT_FACE] = value; + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); + }; + + /** + * Disables all the vaos in use + * + */ + + + WebGLState.prototype.resetAttributes = function resetAttributes() { + for (var i = 0; i < this.attribState.tempAttribState.length; i++) { + this.attribState.tempAttribState[i] = 0; + } + + for (var _i = 0; _i < this.attribState.attribState.length; _i++) { + this.attribState.attribState[_i] = 0; + } + + // im going to assume one is always active for performance reasons. + for (var _i2 = 1; _i2 < this.maxAttribs; _i2++) { + this.gl.disableVertexAttribArray(_i2); + } + }; + + // used + /** + * Resets all the logic and disables the vaos + */ + + + WebGLState.prototype.resetToDefault = function resetToDefault() { + // unbind any VAO if they exist.. + if (this.nativeVaoExtension) { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + // reset all attributes.. + this.resetAttributes(); + + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; ++i) { + this.activeState[i] = 32; + } + + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + + this.setState(this.defaultState); + }; + + return WebGLState; +}(); + +exports.default = WebGLState; + +},{"./utils/mapWebGLBlendModesToPixi":96}],84:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _extractUniformsFromSrc = require('./extractUniformsFromSrc'); + +var _extractUniformsFromSrc2 = _interopRequireDefault(_extractUniformsFromSrc); + +var _utils = require('../../../utils'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SOURCE_KEY_MAP = {}; + +// let math = require('../../../math'); +/** + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ + +var Filter = function () { + /** + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. + */ + function Filter(vertexSrc, fragmentSrc, uniforms) { + _classCallCheck(this, Filter); + + /** + * The vertex shader. + * + * @member {string} + */ + this.vertexSrc = vertexSrc || Filter.defaultVertexSrc; + + /** + * The fragment shader. + * + * @member {string} + */ + this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc; + + this.blendMode = _const.BLEND_MODES.NORMAL; + + this.uniformData = uniforms || (0, _extractUniformsFromSrc2.default)(this.vertexSrc, this.fragmentSrc, 'projectionMatrix|uSampler'); + + /** + * An object containing the current values of custom uniforms. + * @example Updating the value of a custom uniform + * filter.uniforms.time = performance.now(); + * + * @member {object} + */ + this.uniforms = {}; + + for (var i in this.uniformData) { + this.uniforms[i] = this.uniformData[i].value; + } + + // this is where we store shader references.. + // TODO we could cache this! + this.glShaders = {}; + + // used for cacheing.. sure there is a better way! + if (!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) { + SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = (0, _utils.uid)(); + } + + this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]; + + /** + * The padding of the filter. Some filters require extra space to breath such as a blur. + * Increasing this will add extra width and height to the bounds of the object that the + * filter is applied to. + * + * @member {number} + */ + this.padding = 4; + + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + * + * @member {number} + */ + this.resolution = _settings2.default.RESOLUTION; + + /** + * If enabled is true the filter is applied, if false it will not. + * + * @member {boolean} + */ + this.enabled = true; + + /** + * If enabled, pixi will fit the filter area into boundaries for better performance. + * Switch it off if it does not work for specific shader. + * + * @member {boolean} + */ + this.autoFit = true; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + * @param {object} [currentState] - It's current state of filter. + * There are some useful properties in the currentState : + * target, filters, sourceFrame, destinationFrame, renderTarget, resolution + */ + + + Filter.prototype.apply = function apply(filterManager, input, output, clear, currentState) // eslint-disable-line no-unused-vars + { + // --- // + // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); + + // do as you please! + + filterManager.applyFilter(this, input, output, clear); + + // or just do a regular render.. + }; + + /** + * The default vertex shader source + * + * @static + * @constant + */ + + + _createClass(Filter, null, [{ + key: 'defaultVertexSrc', + get: function get() { + return ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform mat3 projectionMatrix;', 'uniform mat3 filterMatrix;', 'varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;', ' vTextureCoord = aTextureCoord ;', '}'].join('\n'); + } + + /** + * The default fragment shader source + * + * @static + * @constant + */ + + }, { + key: 'defaultFragmentSrc', + get: function get() { + return ['varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'uniform sampler2D uSampler;', 'uniform sampler2D filterSampler;', 'void main(void){', ' vec4 masky = texture2D(filterSampler, vFilterCoord);', ' vec4 sample = texture2D(uSampler, vTextureCoord);', ' vec4 color;', ' if(mod(vFilterCoord.x, 1.0) > 0.5)', ' {', ' color = vec4(1.0, 0.0, 0.0, 1.0);', ' }', ' else', ' {', ' color = vec4(0.0, 1.0, 0.0, 1.0);', ' }', + // ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', + ' gl_FragColor = mix(sample, masky, 0.5);', ' gl_FragColor *= sample.a;', '}'].join('\n'); + } + }]); + + return Filter; +}(); + +exports.default = Filter; + +},{"../../../const":44,"../../../settings":99,"../../../utils":120,"./extractUniformsFromSrc":85}],85:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = extractUniformsFromSrc; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var defaultValue = _pixiGlCore2.default.shader.defaultValue; + +function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) { + var vertUniforms = extractUniformsFromString(vertexSrc, mask); + var fragUniforms = extractUniformsFromString(fragmentSrc, mask); + + return Object.assign(vertUniforms, fragUniforms); +} + +function extractUniformsFromString(string) { + var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea|filterClamp)$'); + + var uniforms = {}; + var nameSplit = void 0; + + // clean the lines a little - remove extra spaces / tabs etc + // then split along ';' + var lines = string.replace(/\s+/g, ' ').split(/\s*;\s*/); + + // loop through.. + for (var i = 0; i < lines.length; i++) { + var line = lines[i].trim(); + + if (line.indexOf('uniform') > -1) { + var splitLine = line.split(' '); + var type = splitLine[1]; + + var name = splitLine[2]; + var size = 1; + + if (name.indexOf('[') > -1) { + // array! + nameSplit = name.split(/\[|]/); + name = nameSplit[0]; + size *= Number(nameSplit[1]); + } + + if (!name.match(maskRegex)) { + uniforms[name] = { + value: defaultValue(type, size), + name: name, + type: type + }; + } + } + } + + return uniforms; +} + +},{"pixi-gl-core":12}],86:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.calculateScreenSpaceMatrix = calculateScreenSpaceMatrix; +exports.calculateNormalizedScreenSpaceMatrix = calculateNormalizedScreenSpaceMatrix; +exports.calculateSpriteMatrix = calculateSpriteMatrix; + +var _math = require('../../../math'); + +/* + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// this returns a matrix that will normalise map filter cords in the filter to screen space +function calculateScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + // let worldTransform = sprite.worldTransform.copy(Matrix.TEMP_MATRIX), + // let texture = {width:1136, height:700};//sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(textureSize.width, textureSize.height); + + return mappedMatrix; +} + +function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + var translateScaleX = textureSize.width / filterArea.width; + var translateScaleY = textureSize.height / filterArea.height; + + mappedMatrix.scale(translateScaleX, translateScaleY); + + return mappedMatrix; +} + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +function calculateSpriteMatrix(outputMatrix, filterArea, textureSize, sprite) { + var worldTransform = sprite.worldTransform.copy(_math.Matrix.TEMP_MATRIX); + var texture = sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + // scale.. + var ratio = textureSize.height / textureSize.width; + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(1, ratio); + + var translateScaleX = textureSize.width / texture.width; + var translateScaleY = textureSize.height / texture.height; + + worldTransform.tx /= texture.width * translateScaleX; + + // this...? free beer for anyone who can explain why this makes sense! + worldTransform.ty /= texture.width * translateScaleX; + // worldTransform.ty /= texture.height * translateScaleY; + + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + + // apply inverse scale.. + mappedMatrix.scale(1, 1 / ratio); + + mappedMatrix.scale(translateScaleX, translateScaleY); + + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; +} + +},{"../../../math":68}],87:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Filter2 = require('../Filter'); + +var _Filter3 = _interopRequireDefault(_Filter2); + +var _math = require('../../../../math'); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The SpriteMaskFilter class + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + */ +var SpriteMaskFilter = function (_Filter) { + _inherits(SpriteMaskFilter, _Filter); + + /** + * @param {PIXI.Sprite} sprite - the target sprite + */ + function SpriteMaskFilter(sprite) { + _classCallCheck(this, SpriteMaskFilter); + + var maskMatrix = new _math.Matrix(); + + var _this = _possibleConstructorReturn(this, _Filter.call(this, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n', 'varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n')); + + sprite.renderable = false; + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + return _this; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + */ + + + SpriteMaskFilter.prototype.apply = function apply(filterManager, input, output) { + var maskSprite = this.maskSprite; + + this.uniforms.mask = maskSprite._texture; + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite); + this.uniforms.alpha = maskSprite.worldAlpha; + + filterManager.applyFilter(this, input, output); + }; + + return SpriteMaskFilter; +}(_Filter3.default); + +exports.default = SpriteMaskFilter; + +},{"../../../../math":68,"../Filter":84,"path":22}],88:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _RenderTarget = require('../utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _Quad = require('../utils/Quad'); + +var _Quad2 = _interopRequireDefault(_Quad); + +var _math = require('../../../math'); + +var _Shader = require('../../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _filterTransforms = require('../filters/filterTransforms'); + +var filterTransforms = _interopRequireWildcard(_filterTransforms); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @ignore + * @class + */ +var FilterState = +/** + * + */ +function FilterState() { + _classCallCheck(this, FilterState); + + this.renderTarget = null; + this.sourceFrame = new _math.Rectangle(); + this.destinationFrame = new _math.Rectangle(); + this.filters = []; + this.target = null; + this.resolution = 1; +}; + +/** + * @class + * @memberof PIXI + * @extends PIXI.WebGLManager + */ + + +var FilterManager = function (_WebGLManager) { + _inherits(FilterManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function FilterManager(renderer) { + _classCallCheck(this, FilterManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.gl = _this.renderer.gl; + // know about sprites! + _this.quad = new _Quad2.default(_this.gl, renderer.state.attribState); + + _this.shaderCache = {}; + // todo add default! + _this.pool = {}; + + _this.filterData = null; + return _this; + } + + /** + * Adds a new filter to the manager. + * + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param {PIXI.Filter[]} filters - The filters to apply. + */ + + + FilterManager.prototype.pushFilter = function pushFilter(target, filters) { + var renderer = this.renderer; + + var filterData = this.filterData; + + if (!filterData) { + filterData = this.renderer._activeRenderTarget.filterStack; + + // add new stack + var filterState = new FilterState(); + + filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; + filterState.renderTarget = renderer._activeRenderTarget; + + this.renderer._activeRenderTarget.filterData = filterData = { + index: 0, + stack: [filterState] + }; + + this.filterData = filterData; + } + + // get the current filter state.. + var currentState = filterData.stack[++filterData.index]; + + if (!currentState) { + currentState = filterData.stack[filterData.index] = new FilterState(); + } + + // for now we go off the filter of the first resolution.. + var resolution = filters[0].resolution; + var padding = filters[0].padding | 0; + var targetBounds = target.filterArea || target.getBounds(true); + var sourceFrame = currentState.sourceFrame; + var destinationFrame = currentState.destinationFrame; + + sourceFrame.x = (targetBounds.x * resolution | 0) / resolution; + sourceFrame.y = (targetBounds.y * resolution | 0) / resolution; + sourceFrame.width = (targetBounds.width * resolution | 0) / resolution; + sourceFrame.height = (targetBounds.height * resolution | 0) / resolution; + + if (filterData.stack[0].renderTarget.transform) {// + + // TODO we should fit the rect around the transform.. + } else if (filters[0].autoFit) { + sourceFrame.fit(filterData.stack[0].destinationFrame); + } + + // lets apply the padding After we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + sourceFrame.pad(padding); + + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + + // lets play the padding after we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + + var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); + + currentState.target = target; + currentState.filters = filters; + currentState.resolution = resolution; + currentState.renderTarget = renderTarget; + + // bind the render target to draw the shape in the top corner.. + + renderTarget.setFrame(destinationFrame, sourceFrame); + + // bind the render target + renderer.bindRenderTarget(renderTarget); + renderTarget.clear(); + }; + + /** + * Pops off the filter and applies it. + * + */ + + + FilterManager.prototype.popFilter = function popFilter() { + var filterData = this.filterData; + + var lastState = filterData.stack[filterData.index - 1]; + var currentState = filterData.stack[filterData.index]; + + this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); + + var filters = currentState.filters; + + if (filters.length === 1) { + filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false, currentState); + this.freePotRenderTarget(currentState.renderTarget); + } else { + var flip = currentState.renderTarget; + var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, currentState.resolution); + + flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + // finally lets clear the render target before drawing to it.. + flop.clear(); + + var i = 0; + + for (i = 0; i < filters.length - 1; ++i) { + filters[i].apply(this, flip, flop, true, currentState); + + var t = flip; + + flip = flop; + flop = t; + } + + filters[i].apply(this, flip, lastState.renderTarget, false, currentState); + + this.freePotRenderTarget(flip); + this.freePotRenderTarget(flop); + } + + filterData.index--; + + if (filterData.index === 0) { + this.filterData = null; + } + }; + + /** + * Draws a filter. + * + * @param {PIXI.Filter} filter - The filter to draw. + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + FilterManager.prototype.applyFilter = function applyFilter(filter, input, output, clear) { + var renderer = this.renderer; + var gl = renderer.gl; + + var shader = filter.glShaders[renderer.CONTEXT_UID]; + + // cacheing.. + if (!shader) { + if (filter.glShaderKey) { + shader = this.shaderCache[filter.glShaderKey]; + + if (!shader) { + shader = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + + filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = shader; + } + } else { + shader = filter.glShaders[renderer.CONTEXT_UID] = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + } + + // TODO - this only needs to be done once? + renderer.bindVao(null); + + this.quad.initVao(shader); + } + + renderer.bindVao(this.quad.vao); + + renderer.bindRenderTarget(output); + + if (clear) { + gl.disable(gl.SCISSOR_TEST); + renderer.clear(); // [1, 1, 1, 1]); + gl.enable(gl.SCISSOR_TEST); + } + + // in case the render target is being masked using a scissor rect + if (output === renderer.maskManager.scissorRenderTarget) { + renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); + } + + renderer.bindShader(shader); + + // free unit 0 for us, doesn't matter what was there + // don't try to restore it, because syncUniforms can upload it to another slot + // and it'll be a problem + var tex = this.renderer.emptyTextures[0]; + + this.renderer.boundTextures[0] = tex; + // this syncs the pixi filters uniforms with glsl uniforms + this.syncUniforms(shader, filter); + + renderer.state.setBlendMode(filter.blendMode); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, input.texture.texture); + + this.quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + }; + + /** + * Uploads the uniforms of the filter. + * + * @param {GLShader} shader - The underlying gl shader. + * @param {PIXI.Filter} filter - The filter we are synchronizing. + */ + + + FilterManager.prototype.syncUniforms = function syncUniforms(shader, filter) { + var uniformData = filter.uniformData; + var uniforms = filter.uniforms; + + // 0 is reserved for the pixi texture so we start at 1! + var textureCount = 1; + var currentState = void 0; + + // filterArea and filterClamp that are handled by FilterManager directly + // they must not appear in uniformData + + if (shader.uniforms.filterArea) { + currentState = this.filterData.stack[this.filterData.index]; + + var filterArea = shader.uniforms.filterArea; + + filterArea[0] = currentState.renderTarget.size.width; + filterArea[1] = currentState.renderTarget.size.height; + filterArea[2] = currentState.sourceFrame.x; + filterArea[3] = currentState.sourceFrame.y; + + shader.uniforms.filterArea = filterArea; + } + + // use this to clamp displaced texture coords so they belong to filterArea + // see displacementFilter fragment shader for an example + if (shader.uniforms.filterClamp) { + currentState = currentState || this.filterData.stack[this.filterData.index]; + + var filterClamp = shader.uniforms.filterClamp; + + filterClamp[0] = 0; + filterClamp[1] = 0; + filterClamp[2] = (currentState.sourceFrame.width - 1) / currentState.renderTarget.size.width; + filterClamp[3] = (currentState.sourceFrame.height - 1) / currentState.renderTarget.size.height; + + shader.uniforms.filterClamp = filterClamp; + } + + // TODO Cacheing layer.. + for (var i in uniformData) { + if (uniformData[i].type === 'sampler2D' && uniforms[i] !== 0) { + if (uniforms[i].baseTexture) { + shader.uniforms[i] = this.renderer.bindTexture(uniforms[i].baseTexture, textureCount); + } else { + shader.uniforms[i] = textureCount; + + // TODO + // this is helpful as renderTargets can also be set. + // Although thinking about it, we could probably + // make the filter texture cache return a RenderTexture + // rather than a renderTarget + var gl = this.renderer.gl; + + this.renderer.boundTextures[textureCount] = this.renderer.emptyTextures[textureCount]; + gl.activeTexture(gl.TEXTURE0 + textureCount); + + uniforms[i].texture.bind(); + } + + textureCount++; + } else if (uniformData[i].type === 'mat3') { + // check if its pixi matrix.. + if (uniforms[i].a !== undefined) { + shader.uniforms[i] = uniforms[i].toArray(true); + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (uniformData[i].type === 'vec2') { + // check if its a point.. + if (uniforms[i].x !== undefined) { + var val = shader.uniforms[i] || new Float32Array(2); + + val[0] = uniforms[i].x; + val[1] = uniforms[i].y; + shader.uniforms[i] = val; + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (uniformData[i].type === 'float') { + if (shader.uniforms.data[i].value !== uniformData[i]) { + shader.uniforms[i] = uniforms[i]; + } + } else { + shader.uniforms[i] = uniforms[i]; + } + } + }; + + /** + * Gets a render target from the pool, or creates a new one. + * + * @param {boolean} clear - Should we clear the render texture when we get it? + * @param {number} resolution - The resolution of the target. + * @return {PIXI.RenderTarget} The new render target + */ + + + FilterManager.prototype.getRenderTarget = function getRenderTarget(clear, resolution) { + var currentState = this.filterData.stack[this.filterData.index]; + var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution); + + renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + return renderTarget; + }; + + /** + * Returns a render target to the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The render target to return. + */ + + + FilterManager.prototype.returnRenderTarget = function returnRenderTarget(renderTarget) { + this.freePotRenderTarget(renderTarget); + }; + + /** + * Calculates the mapped matrix. + * + * TODO playing around here.. this is temporary - (will end up in the shader) + * this returns a matrix that will normalise map filter cords in the filter to screen space + * + * @param {PIXI.Matrix} outputMatrix - the matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateScreenSpaceMatrix = function calculateScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); + }; + + /** + * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function calculateNormalizedScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); + }; + + /** + * This will map the filter coord so that a texture can be used based on the transform of a sprite + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateSpriteMatrix = function calculateSpriteMatrix(outputMatrix, sprite) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); + }; + + /** + * Destroys this Filter Manager. + * + */ + + + FilterManager.prototype.destroy = function destroy() { + this.shaderCache = {}; + this.emptyPool(); + }; + + /** + * Gets a Power-of-Two render texture. + * + * TODO move to a seperate class could be on renderer? + * also - could cause issue with multiple contexts? + * + * @private + * @param {WebGLRenderingContext} gl - The webgl rendering context + * @param {number} minWidth - The minimum width of the render target. + * @param {number} minHeight - The minimum height of the render target. + * @param {number} resolution - The resolution of the render target. + * @return {PIXI.RenderTarget} The new render target. + */ + + + FilterManager.prototype.getPotRenderTarget = function getPotRenderTarget(gl, minWidth, minHeight, resolution) { + // TODO you could return a bigger texture if there is not one in the pool? + minWidth = _bitTwiddle2.default.nextPow2(minWidth * resolution); + minHeight = _bitTwiddle2.default.nextPow2(minHeight * resolution); + + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + if (!this.pool[key]) { + this.pool[key] = []; + } + + var renderTarget = this.pool[key].pop(); + + // creating render target will cause texture to be bound! + if (!renderTarget) { + // temporary bypass cache.. + var tex = this.renderer.boundTextures[0]; + + gl.activeTexture(gl.TEXTURE0); + + // internally - this will cause a texture to be bound.. + renderTarget = new _RenderTarget2.default(gl, minWidth, minHeight, null, 1); + + // set the current one back + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + } + + // manually tweak the resolution... + // this will not modify the size of the frame buffer, just its resolution. + renderTarget.resolution = resolution; + renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution; + renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution; + + return renderTarget; + }; + + /** + * Empties the texture pool. + * + */ + + + FilterManager.prototype.emptyPool = function emptyPool() { + for (var i in this.pool) { + var textures = this.pool[i]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + + this.pool = {}; + }; + + /** + * Frees a render target back into the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free + */ + + + FilterManager.prototype.freePotRenderTarget = function freePotRenderTarget(renderTarget) { + var minWidth = renderTarget.size.width * renderTarget.resolution; + var minHeight = renderTarget.size.height * renderTarget.resolution; + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + this.pool[key].push(renderTarget); + }; + + return FilterManager; +}(_WebGLManager3.default); + +exports.default = FilterManager; + +},{"../../../Shader":42,"../../../math":68,"../filters/filterTransforms":86,"../utils/Quad":93,"../utils/RenderTarget":94,"./WebGLManager":91,"bit-twiddle":1}],89:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _SpriteMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); + +var _SpriteMaskFilter2 = _interopRequireDefault(_SpriteMaskFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var MaskManager = function (_WebGLManager) { + _inherits(MaskManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function MaskManager(renderer) { + _classCallCheck(this, MaskManager); + + // TODO - we don't need both! + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.scissor = false; + _this.scissorData = null; + _this.scissorRenderTarget = null; + + _this.enableScissor = true; + + _this.alphaMaskPool = []; + _this.alphaMaskIndex = 0; + return _this; + } + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushMask = function pushMask(target, maskData) { + // TODO the root check means scissor rect will not + // be used on render textures more info here: + // https://github.com/pixijs/pixi.js/pull/3545 + + if (maskData.texture) { + this.pushSpriteMask(target, maskData); + } else if (this.enableScissor && !this.scissor && this.renderer._activeRenderTarget.root && !this.renderer.stencilManager.stencilMaskStack.length && maskData.isFastRect()) { + var matrix = maskData.worldTransform; + + var rot = Math.atan2(matrix.b, matrix.a); + + // use the nearest degree! + rot = Math.round(rot * (180 / Math.PI)); + + if (rot % 90) { + this.pushStencilMask(maskData); + } else { + this.pushScissorMask(target, maskData); + } + } else { + this.pushStencilMask(maskData); + } + }; + + /** + * Removes the last mask from the mask stack and doesn't return it. + * + * @param {PIXI.DisplayObject} target - Display Object to pop the mask from + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.popMask = function popMask(target, maskData) { + if (maskData.texture) { + this.popSpriteMask(target, maskData); + } else if (this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length) { + this.popScissorMask(target, maskData); + } else { + this.popStencilMask(target, maskData); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.RenderTarget} target - Display Object to push the sprite mask to + * @param {PIXI.Sprite} maskData - Sprite to be used as the mask + */ + + + MaskManager.prototype.pushSpriteMask = function pushSpriteMask(target, maskData) { + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new _SpriteMaskFilter2.default(maskData)]; + } + + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskData; + + // TODO - may cause issues! + target.filterArea = maskData.getBounds(true); + + this.renderer.filterManager.pushFilter(target, alphaMaskFilter); + + this.alphaMaskIndex++; + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popSpriteMask = function popSpriteMask() { + this.renderer.filterManager.popFilter(); + this.alphaMaskIndex--; + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushStencilMask = function pushStencilMask(maskData) { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.pushStencil(maskData); + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popStencilMask = function popStencilMask() { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.popStencil(); + }; + + /** + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushScissorMask = function pushScissorMask(target, maskData) { + maskData.renderable = true; + + var renderTarget = this.renderer._activeRenderTarget; + + var bounds = maskData.getBounds(); + + bounds.fit(renderTarget.size); + maskData.renderable = false; + + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + + var resolution = this.renderer.resolution; + + this.renderer.gl.scissor(bounds.x * resolution, (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution, bounds.width * resolution, bounds.height * resolution); + + this.scissorRenderTarget = renderTarget; + this.scissorData = maskData; + this.scissor = true; + }; + + /** + * + * + */ + + + MaskManager.prototype.popScissorMask = function popScissorMask() { + this.scissorRenderTarget = null; + this.scissorData = null; + this.scissor = false; + + // must be scissor! + var gl = this.renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + }; + + return MaskManager; +}(_WebGLManager3.default); + +exports.default = MaskManager; + +},{"../filters/spriteMask/SpriteMaskFilter":87,"./WebGLManager":91}],90:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var StencilManager = function (_WebGLManager) { + _inherits(StencilManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function StencilManager(renderer) { + _classCallCheck(this, StencilManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.stencilMaskStack = null; + return _this; + } + + /** + * Changes the mask stack that is used by this manager. + * + * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack + */ + + + StencilManager.prototype.setMaskStack = function setMaskStack(stencilMaskStack) { + this.stencilMaskStack = stencilMaskStack; + + var gl = this.renderer.gl; + + if (stencilMaskStack.length === 0) { + gl.disable(gl.STENCIL_TEST); + } else { + gl.enable(gl.STENCIL_TEST); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. @alvin + * + * @param {PIXI.Graphics} graphics - The mask + */ + + + StencilManager.prototype.pushStencil = function pushStencil(graphics) { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + this.renderer._activeRenderTarget.attachStencilBuffer(); + + var gl = this.renderer.gl; + var sms = this.stencilMaskStack; + + if (sms.length === 0) { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.stencilFunc(gl.ALWAYS, 1, 1); + } + + sms.push(graphics); + + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; + + /** + * TODO @alvin + */ + + + StencilManager.prototype.popStencil = function popStencil() { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + var gl = this.renderer.gl; + var sms = this.stencilMaskStack; + + var graphics = sms.pop(); + + if (sms.length === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + } else { + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + } + }; + + /** + * Destroys the mask stack. + * + */ + + + StencilManager.prototype.destroy = function destroy() { + _WebGLManager3.default.prototype.destroy.call(this); + + this.stencilMaskStack.stencilStack = null; + }; + + return StencilManager; +}(_WebGLManager3.default); + +exports.default = StencilManager; + +},{"./WebGLManager":91}],91:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var WebGLManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function WebGLManager(renderer) { + _classCallCheck(this, WebGLManager); + + /** + * The renderer this manager works for. + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + this.renderer.on('context', this.onContextChange, this); + } + + /** + * Generic method called when there is a WebGL context change. + * + */ + + + WebGLManager.prototype.onContextChange = function onContextChange() {} + // do some codes init! + + + /** + * Generic destroy methods to be overridden by the subclass + * + */ + ; + + WebGLManager.prototype.destroy = function destroy() { + this.renderer.off('context', this.onContextChange, this); + + this.renderer = null; + }; + + return WebGLManager; +}(); + +exports.default = WebGLManager; + +},{}],92:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('../managers/WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Base for a common object renderer that can be used as a system renderer plugin. + * + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var ObjectRenderer = function (_WebGLManager) { + _inherits(ObjectRenderer, _WebGLManager); + + function ObjectRenderer() { + _classCallCheck(this, ObjectRenderer); + + return _possibleConstructorReturn(this, _WebGLManager.apply(this, arguments)); + } + + /** + * Starts the renderer and sets the shader + * + */ + ObjectRenderer.prototype.start = function start() {} + // set the shader.. + + + /** + * Stops the renderer + * + */ + ; + + ObjectRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Stub method for rendering content and emptying the current batch. + * + */ + + + ObjectRenderer.prototype.flush = function flush() {} + // flush! + + + /** + * Renders an object + * + * @param {PIXI.DisplayObject} object - The object to render. + */ + ; + + ObjectRenderer.prototype.render = function render(object) // eslint-disable-line no-unused-vars + { + // render the object + }; + + return ObjectRenderer; +}(_WebGLManager3.default); + +exports.default = ObjectRenderer; + +},{"../managers/WebGLManager":91}],93:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a quad + * + * @class + * @memberof PIXI + */ +var Quad = function () { + /** + * @param {WebGLRenderingContext} gl - The gl context for this quad to use. + * @param {object} state - TODO: Description + */ + function Quad(gl, state) { + _classCallCheck(this, Quad); + + /* + * the current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]); + + /** + * The Uvs of the quad + * + * @member {Float32Array} + */ + this.uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + this.interleaved = new Float32Array(8 * 2); + + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + this.indices = (0, _createIndicesForQuads2.default)(1); + + /* + * @member {glCore.GLBuffer} The vertex buffer + */ + this.vertexBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW); + + /* + * @member {glCore.GLBuffer} The index buffer + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + /* + * @member {glCore.VertexArrayObject} The index buffer + */ + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, state); + } + + /** + * Initialises the vaos and uses the shader. + * + * @param {PIXI.Shader} shader - the shader to use + */ + + + Quad.prototype.initVao = function initVao(shader) { + this.vao.clear().addIndex(this.indexBuffer).addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0).addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4); + }; + + /** + * Maps two Rectangle to the quad. + * + * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle + * @param {PIXI.Rectangle} destinationFrame - the second rectangle + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.map = function map(targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + + this.uvs[0] = x; + this.uvs[1] = y; + + this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; + + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; + + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; + + x = destinationFrame.x; + y = destinationFrame.y; + + this.vertices[0] = x; + this.vertices[1] = y; + + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + + return this; + }; + + /** + * Binds the buffer and uploads the data + * + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.upload = function upload() { + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + this.vertexBuffer.upload(this.interleaved); + + return this; + }; + + /** + * Removes this quad from WebGL + */ + + + Quad.prototype.destroy = function destroy() { + var gl = this.gl; + + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.indexBuffer); + }; + + return Quad; +}(); + +exports.default = Quad; + +},{"../../../utils/createIndicesForQuads":118,"pixi-gl-core":12}],94:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../../../math'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _pixiGlCore = require('pixi-gl-core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var RenderTarget = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {number} [width=0] - the horizontal range of the filter + * @param {number} [height=0] - the vertical range of the filter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The current resolution / device pixel ratio + * @param {boolean} [root=false] - Whether this object is the root element or not + */ + function RenderTarget(gl, width, height, scaleMode, resolution, root) { + _classCallCheck(this, RenderTarget); + + // TODO Resolution could go here ( eg low res blurs ) + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // next time to create a frame buffer and texture + + /** + * A frame buffer + * + * @member {PIXI.glCore.GLFramebuffer} + */ + this.frameBuffer = null; + + /** + * The texture + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The background colour of this render target, as an array of [r,g,b,a] values + * + * @member {number[]} + */ + this.clearColor = [0, 0, 0, 0]; + + /** + * The size of the object as a rectangle + * + * @member {PIXI.Rectangle} + */ + this.size = new _math.Rectangle(0, 0, 1, 1); + + /** + * The current resolution / device pixel ratio + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The projection matrix + * + * @member {PIXI.Matrix} + */ + this.projectionMatrix = new _math.Matrix(); + + /** + * The object's transform + * + * @member {PIXI.Matrix} + */ + this.transform = null; + + /** + * The frame. + * + * @member {PIXI.Rectangle} + */ + this.frame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.defaultFrame = new _math.Rectangle(); + this.destinationFrame = null; + this.sourceFrame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.stencilBuffer = null; + + /** + * The data structure for the stencil masks + * + * @member {PIXI.Graphics[]} + */ + this.stencilMaskStack = []; + + /** + * Stores filter data for the render target + * + * @member {object[]} + */ + this.filterData = null; + + /** + * The scale mode. + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Whether this object is the root element or not + * + * @member {boolean} + */ + this.root = root; + + if (!this.root) { + this.frameBuffer = _pixiGlCore.GLFramebuffer.createRGBA(gl, 100, 100); + + if (this.scaleMode === _const.SCALE_MODES.NEAREST) { + this.frameBuffer.texture.enableNearestScaling(); + } else { + this.frameBuffer.texture.enableLinearScaling(); + } + /* + A frame buffer needs a target to render to.. + create a texture and bind it attach it to the framebuffer.. + */ + + // this is used by the base texture + this.texture = this.frameBuffer.texture; + } else { + // make it a null framebuffer.. + this.frameBuffer = new _pixiGlCore.GLFramebuffer(gl, 100, 100); + this.frameBuffer.framebuffer = null; + } + + this.setFrame(); + + this.resize(width, height); + } + + /** + * Clears the filter texture. + * + * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer + */ + + + RenderTarget.prototype.clear = function clear(clearColor) { + var cc = clearColor || this.clearColor; + + this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a); + }; + + /** + * Binds the stencil buffer. + * + */ + + + RenderTarget.prototype.attachStencilBuffer = function attachStencilBuffer() { + // TODO check if stencil is done? + /** + * The stencil buffer is used for masking in pixi + * lets create one and then add attach it to the framebuffer.. + */ + if (!this.root) { + this.frameBuffer.enableStencil(); + } + }; + + /** + * Sets the frame of the render target. + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.setFrame = function setFrame(destinationFrame, sourceFrame) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; + }; + + /** + * Binds the buffers and initialises the viewport. + * + */ + + + RenderTarget.prototype.activate = function activate() { + // TOOD refactor usage of frame.. + var gl = this.gl; + + // make sure the texture is unbound! + this.frameBuffer.bind(); + + this.calculateProjection(this.destinationFrame, this.sourceFrame); + + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + + // TODO add a check as them may be the same! + if (this.destinationFrame !== this.sourceFrame) { + gl.enable(gl.SCISSOR_TEST); + gl.scissor(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + } else { + gl.disable(gl.SCISSOR_TEST); + } + + // TODO - does not need to be updated all the time?? + gl.viewport(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + }; + + /** + * Updates the projection matrix based on a projection frame (which is a rectangle) + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.calculateProjection = function calculateProjection(destinationFrame, sourceFrame) { + var pm = this.projectionMatrix; + + sourceFrame = sourceFrame || destinationFrame; + + pm.identity(); + + // TODO: make dest scale source + if (!this.root) { + pm.a = 1 / destinationFrame.width * 2; + pm.d = 1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = -1 - sourceFrame.y * pm.d; + } else { + pm.a = 1 / destinationFrame.width * 2; + pm.d = -1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = 1 - sourceFrame.y * pm.d; + } + }; + + /** + * Resizes the texture to the specified width and height + * + * @param {number} width - the new width of the texture + * @param {number} height - the new height of the texture + */ + + + RenderTarget.prototype.resize = function resize(width, height) { + width = width | 0; + height = height | 0; + + if (this.size.width === width && this.size.height === height) { + return; + } + + this.size.width = width; + this.size.height = height; + + this.defaultFrame.width = width; + this.defaultFrame.height = height; + + this.frameBuffer.resize(width * this.resolution, height * this.resolution); + + var projectionFrame = this.frame || this.size; + + this.calculateProjection(projectionFrame); + }; + + /** + * Destroys the render target. + * + */ + + + RenderTarget.prototype.destroy = function destroy() { + this.frameBuffer.destroy(); + + this.frameBuffer = null; + this.texture = null; + }; + + return RenderTarget; +}(); + +exports.default = RenderTarget; + +},{"../../../const":44,"../../../math":68,"../../../settings":99,"pixi-gl-core":12}],95:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = checkMaxIfStatmentsInShader; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['precision mediump float;', 'void main(void){', 'float test = 0.1;', '%forloop%', 'gl_FragColor = vec4(0.0);', '}'].join('\n'); + +function checkMaxIfStatmentsInShader(maxIfs, gl) { + var createTempContext = !gl; + + if (maxIfs === 0) { + throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); + } + + if (createTempContext) { + var tinyCanvas = document.createElement('canvas'); + + tinyCanvas.width = 1; + tinyCanvas.height = 1; + + gl = _pixiGlCore2.default.createContext(tinyCanvas); + } + + var shader = gl.createShader(gl.FRAGMENT_SHADER); + + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = maxIfs / 2 | 0; + } else { + // valid! + break; + } + } + + if (createTempContext) { + // get rid of context + if (gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').loseContext(); + } + } + + return maxIfs; +} + +function generateIfTestSrc(maxIfs) { + var src = ''; + + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxIfs - 1) { + src += 'if(test == ' + i + '.0){}'; + } + } + + return src; +} + +},{"pixi-gl-core":12}],96:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLBlendModesToPixi; + +var _const = require('../../../const'); + +/** + * Maps gl blend combinations to WebGL. + * + * @memberof PIXI + * @function mapWebGLBlendModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapWebGLBlendModesToPixi(gl) { + var array = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[_const.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD] = [gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + array[_const.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + return array; +} + +},{"../../../const":44}],97:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLDrawModesToPixi; + +var _const = require('../../../const'); + +/** + * Generic Mask Stack data structure. + * + * @memberof PIXI + * @function mapWebGLDrawModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {object} [object={}] - The object to map into + * @return {object} The mapped draw modes. + */ +function mapWebGLDrawModesToPixi(gl) { + var object = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + object[_const.DRAW_MODES.POINTS] = gl.POINTS; + object[_const.DRAW_MODES.LINES] = gl.LINES; + object[_const.DRAW_MODES.LINE_LOOP] = gl.LINE_LOOP; + object[_const.DRAW_MODES.LINE_STRIP] = gl.LINE_STRIP; + object[_const.DRAW_MODES.TRIANGLES] = gl.TRIANGLES; + object[_const.DRAW_MODES.TRIANGLE_STRIP] = gl.TRIANGLE_STRIP; + object[_const.DRAW_MODES.TRIANGLE_FAN] = gl.TRIANGLE_FAN; + + return object; +} + +},{"../../../const":44}],98:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = validateContext; +function validateContext(gl) { + var attributes = gl.getContextAttributes(); + + // this is going to be fairly simple for now.. but at least we have room to grow! + if (!attributes.stencil) { + /* eslint-disable no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable no-console */ + } +} + +},{}],99:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _maxRecommendedTextures = require('./utils/maxRecommendedTextures'); + +var _maxRecommendedTextures2 = _interopRequireDefault(_maxRecommendedTextures); + +var _canUploadSameBuffer = require('./utils/canUploadSameBuffer'); + +var _canUploadSameBuffer2 = _interopRequireDefault(_canUploadSameBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * @namespace PIXI.settings + */ +exports.default = { + + /** + * Target frames per millisecond. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 0.06 + */ + TARGET_FPMS: 0.06, + + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * + * @static + * @memberof PIXI.settings + * @type {boolean} + * @default true + */ + MIPMAP_TEXTURES: true, + + /** + * Default resolution / device pixel ratio of the renderer. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + RESOLUTION: 1, + + /** + * Default filter resolution. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + FILTER_RESOLUTION: 1, + + /** + * The maximum textures that this device supports. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 32 + */ + SPRITE_MAX_TEXTURES: (0, _maxRecommendedTextures2.default)(32), + + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + + /** + * The prefix that denotes a URL is for a retina asset. + * + * @static + * @memberof PIXI.settings + * @type {RegExp} + * @example `@2x` + * @default /@([0-9\.]+)x/ + */ + RETINA_PREFIX: /@([0-9\.]+)x/, + + /** + * The default render options if none are supplied to {@link PIXI.WebGLRenderer} + * or {@link PIXI.CanvasRenderer}. + * + * @static + * @constant + * @memberof PIXI.settings + * @type {object} + * @property {HTMLCanvasElement} view=null + * @property {number} resolution=1 + * @property {boolean} antialias=false + * @property {boolean} forceFXAA=false + * @property {boolean} autoResize=false + * @property {boolean} transparent=false + * @property {number} backgroundColor=0x000000 + * @property {boolean} clearBeforeRender=true + * @property {boolean} preserveDrawingBuffer=false + * @property {boolean} roundPixels=false + */ + RENDER_OPTIONS: { + view: null, + antialias: false, + forceFXAA: false, + autoResize: false, + transparent: false, + backgroundColor: 0x000000, + clearBeforeRender: true, + preserveDrawingBuffer: false, + roundPixels: false + }, + + /** + * Default transform type. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.TRANSFORM_MODE} + * @default PIXI.TRANSFORM_MODE.STATIC + */ + TRANSFORM_MODE: 0, + + /** + * Default Garbage Collection mode. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO + */ + GC_MODE: 0, + + /** + * Default Garbage Collection max idle. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 3600 + */ + GC_MAX_IDLE: 60 * 60, + + /** + * Default Garbage Collection maximum check count. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 600 + */ + GC_MAX_CHECK_COUNT: 60 * 10, + + /** + * Default wrap modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP + */ + WRAP_MODE: 0, + + /** + * The scale modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR + */ + SCALE_MODE: 0, + + /** + * Default specify float precision in vertex shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.HIGH + */ + PRECISION_VERTEX: 'highp', + + /** + * Default specify float precision in fragment shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM + */ + PRECISION_FRAGMENT: 'mediump', + + /** + * Can we upload the same buffer in a single frame? + * + * @static + * @constant + * @memberof PIXI + * @type {boolean} + */ + CAN_UPLOAD_SAME_BUFFER: (0, _canUploadSameBuffer2.default)() + +}; + +},{"./utils/canUploadSameBuffer":117,"./utils/maxRecommendedTextures":121}],100:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new _math.Point(); + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = new PIXI.Sprite.fromImage('assets/image.png'); + * ``` + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Sprite = function (_Container) { + _inherits(Sprite, _Container); + + /** + * @param {PIXI.Texture} texture - The texture for this sprite + */ + function Sprite(texture) { + _classCallCheck(this, Sprite); + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + * @private + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this._anchor = new _math.ObservablePoint(_this._onAnchorUpdate, _this); + + /** + * The texture that the sprite is using + * + * @private + * @member {PIXI.Texture} + */ + _this._texture = null; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = null; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * The shader that will be used to render the sprite. Set to null to remove a current shader. + * + * @member {PIXI.Filter|PIXI.Shader} + */ + _this.shader = null; + + /** + * An internal cached value of the tint. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this.cachedTint = 0xFFFFFF; + + // call texture setter + _this.texture = texture || _Texture2.default.EMPTY; + + /** + * this is used to store the vertex data of the sprite (basically a quad) + * + * @private + * @member {Float32Array} + */ + _this.vertexData = new Float32Array(8); + + /** + * This is used to calculate the bounds of the object IF it is a trimmed sprite + * + * @private + * @member {Float32Array} + */ + _this.vertexTrimmedData = null; + + _this._transformID = -1; + _this._textureID = -1; + + _this._transformTrimmedID = -1; + _this._textureTrimmedID = -1; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * + * @member {string} + * @default 'sprite' + */ + _this.pluginName = 'sprite'; + return _this; + } + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Sprite.prototype._onTextureUpdate = function _onTextureUpdate() { + this._textureID = -1; + this._textureTrimmedID = -1; + + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = (0, _utils.sign)(this.scale.x) * this._width / this.texture.orig.width; + } + + if (this._height) { + this.scale.y = (0, _utils.sign)(this.scale.y) * this._height / this.texture.orig.height; + } + }; + + /** + * Called when the anchor position updates. + * + * @private + */ + + + Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate() { + this._transformID = -1; + this._transformTrimmedID = -1; + }; + + /** + * calculates worldTransform * vertices, store it in vertexData + */ + + + Sprite.prototype.calculateVertices = function calculateVertices() { + if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) { + return; + } + + this._transformID = this.transform._worldID; + this._textureID = this._texture._updateID; + + // set the vertex data + + var texture = this._texture; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var anchor = this._anchor; + + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - anchor._x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - anchor._y * orig.height; + h0 = h1 + trim.height; + } else { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData + * This is used to ensure that the true width and height of a trimmed texture is respected + */ + + + Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices() { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { + return; + } + + this._transformTrimmedID = this.transform._worldID; + this._textureTrimmedID = this._texture._updateID; + + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + var anchor = this._anchor; + + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + + var w1 = -anchor._x * orig.width; + var w0 = w1 + orig.width; + + var h1 = -anchor._y * orig.height; + var h0 = h1 + orig.height; + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use. + */ + + + Sprite.prototype._renderWebGL = function _renderWebGL(renderer) { + this.calculateVertices(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Sprite.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Updates the bounds of the sprite. + * + * @private + */ + + + Sprite.prototype._calculateBounds = function _calculateBounds() { + var trim = this._texture.trim; + var orig = this._texture.orig; + + // First lets check to see if the current texture has a trim.. + if (!trim || trim.width === orig.width && trim.height === orig.height) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + Sprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._texture.orig.width * -this._anchor._x; + this._bounds.minY = this._texture.orig.height * -this._anchor._y; + this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x); + this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._x); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _Container.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Tests if a point is inside this sprite + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Sprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + + if (tempPoint.x > x1 && tempPoint.x < x1 + width) { + y1 = -height * this.anchor.y; + + if (tempPoint.y > y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + Sprite.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + this._anchor = null; + + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + + this._texture.destroy(!!destroyBaseTexture); + } + + this._texture = null; + this.shader = null; + }; + + // some helper functions.. + + /** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Sprite} The newly created sprite + */ + + + Sprite.from = function from(source) { + return new Sprite(_Texture2.default.from(source)); + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId + */ + + + Sprite.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return new Sprite(texture); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id + */ + + + Sprite.fromImage = function fromImage(imageId, crossorigin, scaleMode) { + return new Sprite(_Texture2.default.fromImage(imageId, crossorigin, scaleMode)); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Sprite, [{ + key: 'width', + get: function get() { + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._anchor.copy(value); + } + + /** + * The tint applied to the sprite. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + } + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + */ + + }, { + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + this.cachedTint = 0xFFFFFF; + + this._textureID = -1; + this._textureTrimmedID = -1; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + }]); + + return Sprite; +}(_Container3.default); + +exports.default = Sprite; + +},{"../const":44,"../display/Container":46,"../math":68,"../textures/Texture":112,"../utils":120}],101:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +var _math = require('../../math'); + +var _CanvasTinter = require('./CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var canvasRenderWorldTransform = new _math.Matrix(); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasSpriteRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + */ + +var CanvasSpriteRenderer = function () { + /** + * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for. + */ + function CanvasSpriteRenderer(renderer) { + _classCallCheck(this, CanvasSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + CanvasSpriteRenderer.prototype.render = function render(sprite) { + var texture = sprite._texture; + var renderer = this.renderer; + + var width = texture._frame.width; + var height = texture._frame.height; + + var wt = sprite.transform.worldTransform; + var dx = 0; + var dy = 0; + + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) { + return; + } + + renderer.setBlendMode(sprite.blendMode); + + // Ignore null sources + if (texture.valid) { + renderer.context.globalAlpha = sprite.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture + var smoothingEnabled = texture.baseTexture.scaleMode === _const.SCALE_MODES.LINEAR; + + if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) { + renderer.context[renderer.smoothProperty] = smoothingEnabled; + } + + if (texture.trim) { + dx = texture.trim.width / 2 + texture.trim.x - sprite.anchor.x * texture.orig.width; + dy = texture.trim.height / 2 + texture.trim.y - sprite.anchor.y * texture.orig.height; + } else { + dx = (0.5 - sprite.anchor.x) * texture.orig.width; + dy = (0.5 - sprite.anchor.y) * texture.orig.height; + } + + if (texture.rotate) { + wt.copy(canvasRenderWorldTransform); + wt = canvasRenderWorldTransform; + _math.GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); + // the anchor has already been applied above, so lets set it to zero + dx = 0; + dy = 0; + } + + dx -= width / 2; + dy -= height / 2; + + // Allow for pixel rounding + if (renderer.roundPixels) { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution | 0, wt.ty * renderer.resolution | 0); + + dx = dx | 0; + dy = dy | 0; + } else { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution, wt.ty * renderer.resolution); + } + + var resolution = texture.baseTexture.resolution; + + if (sprite.tint !== 0xFFFFFF) { + if (sprite.cachedTint !== sprite.tint) { + sprite.cachedTint = sprite.tint; + + // TODO clean up caching - how to clean up the caches? + sprite.tintedTexture = _CanvasTinter2.default.getTintedTexture(sprite, sprite.tint); + } + + renderer.context.drawImage(sprite.tintedTexture, 0, 0, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } else { + renderer.context.drawImage(texture.baseTexture.source, texture._frame.x * resolution, texture._frame.y * resolution, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } + } + }; + + /** + * destroy the sprite object. + * + */ + + + CanvasSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasSpriteRenderer; +}(); + +exports.default = CanvasSpriteRenderer; + + +_CanvasRenderer2.default.registerPlugin('sprite', CanvasSpriteRenderer); + +},{"../../const":44,"../../math":68,"../../renderers/canvas/CanvasRenderer":75,"./CanvasTinter":102}],102:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class + * @memberof PIXI + */ +var CanvasTinter = { + /** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Sprite} sprite - the sprite to tint + * @param {number} color - the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ + getTintedTexture: function getTintedTexture(sprite, color) { + var texture = sprite.texture; + + color = CanvasTinter.roundColor(color); + + var stringColor = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + texture.tintCache = texture.tintCache || {}; + + if (texture.tintCache[stringColor]) { + return texture.tintCache[stringColor]; + } + + // clone texture.. + var canvas = CanvasTinter.canvas || document.createElement('canvas'); + + // CanvasTinter.tintWithPerPixel(texture, stringColor, canvas); + CanvasTinter.tintMethod(texture, color, canvas); + + if (CanvasTinter.convertTintToImage) { + // is this better? + var tintImage = new Image(); + + tintImage.src = canvas.toDataURL(); + + texture.tintCache[stringColor] = tintImage; + } else { + texture.tintCache[stringColor] = canvas; + // if we are not converting the texture to an image then we need to lose the reference to the canvas + CanvasTinter.canvas = null; + } + + return canvas; + }, + + /** + * Tint a texture using the 'multiply' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithMultiply: function tintWithMultiply(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + }, + + /** + * Tint a texture using the 'overlay' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithOverlay: function tintWithOverlay(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.globalCompositeOperation = 'copy'; + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + // context.globalCompositeOperation = 'copy'; + }, + + + /** + * Tint a texture pixel per pixel. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithPerPixel: function tintWithPerPixel(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.globalCompositeOperation = 'copy'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + var rgbValues = (0, _utils.hex2rgb)(color); + var r = rgbValues[0]; + var g = rgbValues[1]; + var b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, crop.width, crop.height); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + } + + context.putImageData(pixelData, 0, 0); + }, + + /** + * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel. + * + * @memberof PIXI.CanvasTinter + * @param {number} color - the color to round, should be a hex color + * @return {number} The rounded color. + */ + roundColor: function roundColor(color) { + var step = CanvasTinter.cacheStepsPerColorChannel; + + var rgbValues = (0, _utils.hex2rgb)(color); + + rgbValues[0] = Math.min(255, rgbValues[0] / step * step); + rgbValues[1] = Math.min(255, rgbValues[1] / step * step); + rgbValues[2] = Math.min(255, rgbValues[2] / step * step); + + return (0, _utils.rgb2hex)(rgbValues); + }, + + /** + * Number of steps which will be used as a cap when rounding colors. + * + * @memberof PIXI.CanvasTinter + * @type {number} + */ + cacheStepsPerColorChannel: 8, + + /** + * Tint cache boolean flag. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + convertTintToImage: false, + + /** + * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + canUseMultiply: (0, _canUseNewCanvasBlendModes2.default)(), + + /** + * The tinting method that will be used. + * + * @memberof PIXI.CanvasTinter + * @type {tintMethodFunctionType} + */ + tintMethod: 0 +}; + +CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply : CanvasTinter.tintWithPerPixel; + +/** + * The tintMethod type. + * + * @memberof PIXI.CanvasTinter + * @callback tintMethodFunctionType + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + +exports.default = CanvasTinter; + +},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":78,"../../utils":120}],103:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Buffer = function () { + /** + * @param {number} size - The size of the buffer in bytes. + */ + function Buffer(size) { + _classCallCheck(this, Buffer); + + this.vertices = new ArrayBuffer(size); + + /** + * View on the vertices as a Float32Array for positions + * + * @member {Float32Array} + */ + this.float32View = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array for uvs + * + * @member {Float32Array} + */ + this.uint32View = new Uint32Array(this.vertices); + } + + /** + * Destroys the buffer. + * + */ + + + Buffer.prototype.destroy = function destroy() { + this.vertices = null; + this.positions = null; + this.uvs = null; + this.colors = null; + }; + + return Buffer; +}(); + +exports.default = Buffer; + +},{}],104:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _createIndicesForQuads = require('../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +var _generateMultiTextureShader = require('./generateMultiTextureShader'); + +var _generateMultiTextureShader2 = _interopRequireDefault(_generateMultiTextureShader); + +var _checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'); + +var _checkMaxIfStatmentsInShader2 = _interopRequireDefault(_checkMaxIfStatmentsInShader); + +var _BatchBuffer = require('./BatchBuffer'); + +var _BatchBuffer2 = _interopRequireDefault(_BatchBuffer); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var TICK = 0; +var TEXTURE_TICK = 0; + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var SpriteRenderer = function (_ObjectRenderer) { + _inherits(SpriteRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function SpriteRenderer(renderer) { + _classCallCheck(this, SpriteRenderer); + + /** + * Number of values sent in the vertex buffer. + * aVertexPosition(2), aTextureCoord(1), aColor(1), aTextureId(1) = 5 + * + * @member {number} + */ + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.vertSize = 5; + + /** + * The size of the vertex information in bytes. + * + * @member {number} + */ + _this.vertByteSize = _this.vertSize * 4; + + /** + * The number of images in the SpriteRenderer before it flushes. + * + * @member {number} + */ + _this.size = _settings2.default.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + + // the total number of bytes in our batch + // let numVerts = this.size * 4 * this.vertByteSize; + + _this.buffers = []; + for (var i = 1; i <= _bitTwiddle2.default.nextPow2(_this.size); i *= 2) { + _this.buffers.push(new _BatchBuffer2.default(i * 4 * _this.vertByteSize)); + } + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + _this.indices = (0, _createIndicesForQuads2.default)(_this.size); + + /** + * The default shaders that is used if a sprite doesn't have a more specific one. + * there is a shader for each number of textures that can be rendererd. + * These shaders will also be generated on the fly as required. + * @member {PIXI.Shader[]} + */ + _this.shader = null; + + _this.currentIndex = 0; + _this.groups = []; + + for (var k = 0; k < _this.size; k++) { + _this.groups[k] = { textures: [], textureCount: 0, ids: [], size: 0, start: 0, blend: 0 }; + } + + _this.sprites = []; + + _this.vertexBuffers = []; + _this.vaos = []; + + _this.vaoMax = 2; + _this.vertexCount = 0; + + _this.renderer.on('prerender', _this.onPrerender, _this); + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + SpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + if (this.renderer.legacy) { + this.MAX_TEXTURES = 1; + } else { + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), _settings2.default.SPRITE_MAX_TEXTURES); + + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = (0, _checkMaxIfStatmentsInShader2.default)(this.MAX_TEXTURES, gl); + } + + var shader = this.shader = (0, _generateMultiTextureShader2.default)(gl, this.MAX_TEXTURES); + + // create a couple of buffers + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + // we use the second shader as the first one depending on your browser may omit aTextureId + // as it is not used by the shader so is optimized out. + + this.renderer.bindVao(null); + + for (var i = 0; i < this.vaoMax; i++) { + this.vertexBuffers[i] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + + /* eslint-disable max-len */ + + // build the vao object that will render.. + this.vaos[i] = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(this.vertexBuffers[i], shader.attributes.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(this.vertexBuffers[i], shader.attributes.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(this.vertexBuffers[i], shader.attributes.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (shader.attributes.aTextureId) { + this.vaos[i].addAttribute(this.vertexBuffers[i], shader.attributes.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + /* eslint-enable max-len */ + } + + this.vao = this.vaos[0]; + this.currentBlendMode = 99999; + + this.boundTextures = new Array(this.MAX_TEXTURES); + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + SpriteRenderer.prototype.onPrerender = function onPrerender() { + this.vertexCount = 0; + }; + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + SpriteRenderer.prototype.render = function render(sprite) { + // TODO set blend modes.. + // check texture.. + if (this.currentIndex >= this.size) { + this.flush(); + } + + // get the uvs for the texture + + // if the uvs have not updated then no point rendering just yet! + if (!sprite._texture._uvs) { + return; + } + + // push a texture. + // increment the batchsize + this.sprites[this.currentIndex++] = sprite; + }; + + /** + * Renders the content and empties the current batch. + * + */ + + + SpriteRenderer.prototype.flush = function flush() { + if (this.currentIndex === 0) { + return; + } + + var gl = this.renderer.gl; + var MAX_TEXTURES = this.MAX_TEXTURES; + + var np2 = _bitTwiddle2.default.nextPow2(this.currentIndex); + var log2 = _bitTwiddle2.default.log2(np2); + var buffer = this.buffers[log2]; + + var sprites = this.sprites; + var groups = this.groups; + + var float32View = buffer.float32View; + var uint32View = buffer.uint32View; + + var boundTextures = this.boundTextures; + var rendererBoundTextures = this.renderer.boundTextures; + var touch = this.renderer.textureGC.count; + + var index = 0; + var nextTexture = void 0; + var currentTexture = void 0; + var groupCount = 1; + var textureCount = 0; + var currentGroup = groups[0]; + var vertexData = void 0; + var uvs = void 0; + var blendMode = sprites[0].blendMode; + + currentGroup.textureCount = 0; + currentGroup.start = 0; + currentGroup.blend = blendMode; + + TICK++; + + var i = void 0; + + // copy textures.. + for (i = 0; i < MAX_TEXTURES; ++i) { + boundTextures[i] = rendererBoundTextures[i]; + boundTextures[i]._virtalBoundId = i; + } + + for (i = 0; i < this.currentIndex; ++i) { + // upload the sprite elemetns... + // they have all ready been calculated so we just need to push them into the buffer. + var sprite = sprites[i]; + + nextTexture = sprite._texture.baseTexture; + + if (blendMode !== sprite.blendMode) { + // finish a group.. + blendMode = sprite.blendMode; + + // force the batch to break! + currentTexture = null; + textureCount = MAX_TEXTURES; + TICK++; + } + + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + + if (nextTexture._enabled !== TICK) { + if (textureCount === MAX_TEXTURES) { + TICK++; + + currentGroup.size = i - currentGroup.start; + + textureCount = 0; + + currentGroup = groups[groupCount++]; + currentGroup.blend = blendMode; + currentGroup.textureCount = 0; + currentGroup.start = i; + } + + nextTexture.touched = touch; + + if (nextTexture._virtalBoundId === -1) { + for (var j = 0; j < MAX_TEXTURES; ++j) { + var tIndex = (j + TEXTURE_TICK) % MAX_TEXTURES; + + var t = boundTextures[tIndex]; + + if (t._enabled !== TICK) { + TEXTURE_TICK++; + + t._virtalBoundId = -1; + + nextTexture._virtalBoundId = tIndex; + + boundTextures[tIndex] = nextTexture; + break; + } + } + } + + nextTexture._enabled = TICK; + + currentGroup.textureCount++; + currentGroup.ids[textureCount] = nextTexture._virtalBoundId; + currentGroup.textures[textureCount++] = nextTexture; + } + } + + vertexData = sprite.vertexData; + + // TODO this sum does not need to be set each frame.. + uvs = sprite._texture._uvs.uvsUint32; + + if (this.renderer.roundPixels) { + var resolution = this.renderer.resolution; + + // xy + float32View[index] = (vertexData[0] * resolution | 0) / resolution; + float32View[index + 1] = (vertexData[1] * resolution | 0) / resolution; + + // xy + float32View[index + 5] = (vertexData[2] * resolution | 0) / resolution; + float32View[index + 6] = (vertexData[3] * resolution | 0) / resolution; + + // xy + float32View[index + 10] = (vertexData[4] * resolution | 0) / resolution; + float32View[index + 11] = (vertexData[5] * resolution | 0) / resolution; + + // xy + float32View[index + 15] = (vertexData[6] * resolution | 0) / resolution; + float32View[index + 16] = (vertexData[7] * resolution | 0) / resolution; + } else { + // xy + float32View[index] = vertexData[0]; + float32View[index + 1] = vertexData[1]; + + // xy + float32View[index + 5] = vertexData[2]; + float32View[index + 6] = vertexData[3]; + + // xy + float32View[index + 10] = vertexData[4]; + float32View[index + 11] = vertexData[5]; + + // xy + float32View[index + 15] = vertexData[6]; + float32View[index + 16] = vertexData[7]; + } + + uint32View[index + 2] = uvs[0]; + uint32View[index + 7] = uvs[1]; + uint32View[index + 12] = uvs[2]; + uint32View[index + 17] = uvs[3]; + + /* eslint-disable max-len */ + uint32View[index + 3] = uint32View[index + 8] = uint32View[index + 13] = uint32View[index + 18] = sprite._tintRGB + (Math.min(sprite.worldAlpha, 1) * 255 << 24); + + float32View[index + 4] = float32View[index + 9] = float32View[index + 14] = float32View[index + 19] = nextTexture._virtalBoundId; + /* eslint-enable max-len */ + + index += 20; + } + + currentGroup.size = i - currentGroup.start; + + if (!_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // this is still needed for IOS performance.. + // it really does not like uploading to the same buffer in a single frame! + if (this.vaoMax <= this.vertexCount) { + this.vaoMax++; + this.vertexBuffers[this.vertexCount] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + + /* eslint-disable max-len */ + + // build the vao object that will render.. + this.vaos[this.vertexCount] = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(this.vertexBuffers[this.vertexCount], this.shader.attributes.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(this.vertexBuffers[this.vertexCount], this.shader.attributes.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(this.vertexBuffers[this.vertexCount], this.shader.attributes.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (this.shader.attributes.aTextureId) { + this.vaos[this.vertexCount].addAttribute(this.vertexBuffers[this.vertexCount], this.shader.attributes.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + /* eslint-enable max-len */ + } + + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, false); + + this.vertexCount++; + } else { + // lets use the faster option, always use buffer number 0 + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, true); + } + + for (i = 0; i < MAX_TEXTURES; ++i) { + rendererBoundTextures[i]._virtalBoundId = -1; + } + + // render the groups.. + for (i = 0; i < groupCount; ++i) { + var group = groups[i]; + var groupTextureCount = group.textureCount; + + for (var _j = 0; _j < groupTextureCount; _j++) { + currentTexture = group.textures[_j]; + + // reset virtual ids.. + // lets do a quick check.. + if (rendererBoundTextures[group.ids[_j]] !== currentTexture) { + this.renderer.bindTexture(currentTexture, group.ids[_j], true); + } + + // reset the virtualId.. + currentTexture._virtalBoundId = -1; + } + + // set the blend mode.. + this.renderer.state.setBlendMode(group.blend); + + gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); + } + + // reset elements for the next flush + this.currentIndex = 0; + }; + + /** + * Starts a new sprite batch. + */ + + + SpriteRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + + if (_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // bind buffer #0, we don't need others + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].bind(); + } + }; + + /** + * Stops and flushes the current batch. + * + */ + + + SpriteRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Destroys the SpriteRenderer. + * + */ + + + SpriteRenderer.prototype.destroy = function destroy() { + for (var i = 0; i < this.vaoMax; i++) { + if (this.vertexBuffers[i]) { + this.vertexBuffers[i].destroy(); + } + if (this.vaos[i]) { + this.vaos[i].destroy(); + } + } + + if (this.indexBuffer) { + this.indexBuffer.destroy(); + } + + this.renderer.off('prerender', this.onPrerender, this); + + _ObjectRenderer.prototype.destroy.call(this); + + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } + + this.vertexBuffers = null; + this.vaos = null; + this.indexBuffer = null; + this.indices = null; + + this.sprites = null; + + for (var _i = 0; _i < this.buffers.length; ++_i) { + this.buffers[_i].destroy(); + } + }; + + return SpriteRenderer; +}(_ObjectRenderer3.default); + +exports.default = SpriteRenderer; + + +_WebGLRenderer2.default.registerPlugin('sprite', SpriteRenderer); + +},{"../../renderers/webgl/WebGLRenderer":82,"../../renderers/webgl/utils/ObjectRenderer":92,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":95,"../../settings":99,"../../utils/createIndicesForQuads":118,"./BatchBuffer":103,"./generateMultiTextureShader":105,"bit-twiddle":1,"pixi-gl-core":12}],105:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateMultiTextureShader; + +var _Shader = require('../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'varying float vTextureId;', 'uniform sampler2D uSamplers[%count%];', 'void main(void){', 'vec4 color;', 'float textureId = floor(vTextureId+0.5);', '%forloop%', 'gl_FragColor = color * vColor;', '}'].join('\n'); + +function generateMultiTextureShader(gl, maxTextures) { + var vertexSrc = 'precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = vec4(aColor.rgb * aColor.a, aColor.a);\n}\n'; + var fragmentSrc = fragTemplate; + + fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); + + var shader = new _Shader2.default(gl, vertexSrc, fragmentSrc); + + var sampleValues = []; + + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + + shader.bind(); + shader.uniforms.uSamplers = sampleValues; + + return shader; +} + +function generateSampleSrc(maxTextures) { + var src = ''; + + src += '\n'; + src += '\n'; + + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxTextures - 1) { + src += 'if(textureId == ' + i + '.0)'; + } + + src += '\n{'; + src += '\n\tcolor = texture2D(uSamplers[' + i + '], vTextureCoord);'; + src += '\n}'; + } + + src += '\n'; + src += '\n'; + + return src; +} + +},{"../../Shader":42,"path":22}],106:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Sprite2 = require('../sprites/Sprite'); + +var _Sprite3 = _interopRequireDefault(_Sprite2); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TextStyle = require('./TextStyle'); + +var _TextStyle2 = _interopRequireDefault(_TextStyle); + +var _trimCanvas = require('../utils/trimCanvas'); + +var _trimCanvas2 = _interopRequireDefault(_trimCanvas); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint max-depth: [2, 8] */ + + +var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true +}; + +/** + * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string, + * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object. + * + * A Text can be created directly from a string and a style object + * + * ```js + * let text = new PIXI.Text('This is a pixi text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI + */ + +var Text = function (_Sprite) { + _inherits(Text, _Sprite); + + /** + * @param {string} text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + * @param {HTMLCanvasElement} [canvas] - The canvas element for drawing text + */ + function Text(text, style, canvas) { + _classCallCheck(this, Text); + + canvas = canvas || document.createElement('canvas'); + + canvas.width = 3; + canvas.height = 3; + + var texture = _Texture2.default.fromCanvas(canvas); + + texture.orig = new _math.Rectangle(); + texture.trim = new _math.Rectangle(); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + var _this = _possibleConstructorReturn(this, _Sprite.call(this, texture)); + + _this.canvas = canvas; + + /** + * The canvas 2d context that everything is drawn with + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.canvas.getContext('2d'); + + /** + * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. + * @member {number} + * @default 1 + */ + _this.resolution = _settings2.default.RESOLUTION; + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = null; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._style = null; + /** + * Private listener to track style changes. + * + * @member {Function} + * @private + */ + _this._styleListener = null; + + /** + * Private tracker for the current font. + * + * @member {string} + * @private + */ + _this._font = ''; + + _this.text = text; + _this.style = style; + + _this.localStyleID = -1; + return _this; + } + + /** + * Renders text and updates it when needed. + * + * @private + * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. + */ + + + Text.prototype.updateText = function updateText(respectDirty) { + var style = this._style; + + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + + if (!this.dirty && respectDirty) { + return; + } + + this._font = Text.getFontStyle(style); + + this.context.font = this._font; + + // word wrap + // preserve original text + var outputText = style.wordWrap ? this.wordWrap(this._text) : this._text; + + // split text into lines + var lines = outputText.split(/(?:\r\n|\r|\n)/); + + // calculate text width + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + var fontProperties = Text.calculateFontProperties(this._font); + + for (var i = 0; i < lines.length; i++) { + var lineWidth = this.context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing; + + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + + var width = maxLineWidth + style.strokeThickness; + + if (style.dropShadow) { + width += style.dropShadowDistance; + } + + this.canvas.width = Math.ceil((width + style.padding * 2) * this.resolution); + + // calculate text height + var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * lineHeight; + + if (style.dropShadow) { + height += style.dropShadowDistance; + } + + this.canvas.height = Math.ceil((height + style.padding * 2) * this.resolution); + + this.context.scale(this.resolution, this.resolution); + + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + + this.context.font = this._font; + this.context.strokeStyle = style.stroke; + this.context.lineWidth = style.strokeThickness; + this.context.textBaseline = style.textBaseline; + this.context.lineJoin = style.lineJoin; + this.context.miterLimit = style.miterLimit; + + var linePositionX = void 0; + var linePositionY = void 0; + + if (style.dropShadow) { + this.context.shadowBlur = style.dropShadowBlur; + this.context.globalAlpha = style.dropShadowAlpha; + + if (style.dropShadowBlur > 0) { + this.context.shadowColor = style.dropShadowColor; + } else { + this.context.fillStyle = style.dropShadowColor; + } + + var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + + for (var _i = 0; _i < lines.length; _i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i]) / 2; + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); + + if (style.stroke && style.strokeThickness) { + this.context.strokeStyle = style.dropShadowColor; + this.drawLetterSpacing(lines[_i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding, true); + this.context.strokeStyle = style.stroke; + } + } + } + } + + // reset the shadow blur and alpha that was set by the drop shadow, for the regular text + this.context.shadowBlur = 0; + this.context.globalAlpha = 1; + + // set canvas text styles + this.context.fillStyle = this._generateFillStyle(style, lines); + + // draw lines line by line + for (var _i2 = 0; _i2 < lines.length; _i2++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i2 * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i2]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i2]) / 2; + } + + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[_i2], linePositionX + style.padding, linePositionY + style.padding, true); + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i2], linePositionX + style.padding, linePositionY + style.padding); + } + } + + this.updateTexture(); + }; + + /** + * Render the text with letter-spacing. + * @param {string} text - The text to draw + * @param {number} x - Horizontal position to draw the text + * @param {number} y - Vertical position to draw the text + * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + * @private + */ + + + Text.prototype.drawLetterSpacing = function drawLetterSpacing(text, x, y) { + var isStroke = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var style = this._style; + + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + + if (letterSpacing === 0) { + if (isStroke) { + this.context.strokeText(text, x, y); + } else { + this.context.fillText(text, x, y); + } + + return; + } + + var characters = String.prototype.split.call(text, ''); + var currentPosition = x; + var index = 0; + var current = ''; + + while (index < text.length) { + current = characters[index++]; + if (isStroke) { + this.context.strokeText(current, currentPosition, y); + } else { + this.context.fillText(current, currentPosition, y); + } + currentPosition += this.context.measureText(current).width + letterSpacing; + } + }; + + /** + * Updates texture size based on canvas size + * + * @private + */ + + + Text.prototype.updateTexture = function updateTexture() { + if (this._style.trim) { + var trimmed = (0, _trimCanvas2.default)(this.canvas); + + this.canvas.width = trimmed.width; + this.canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } + + var texture = this._texture; + var style = this._style; + + texture.baseTexture.hasLoaded = true; + texture.baseTexture.resolution = this.resolution; + + texture.baseTexture.realWidth = this.canvas.width; + texture.baseTexture.realHeight = this.canvas.height; + texture.baseTexture.width = this.canvas.width / this.resolution; + texture.baseTexture.height = this.canvas.height / this.resolution; + texture.trim.width = texture._frame.width = this.canvas.width / this.resolution; + texture.trim.height = texture._frame.height = this.canvas.height / this.resolution; + + texture.trim.x = -style.padding; + texture.trim.y = -style.padding; + + texture.orig.width = texture._frame.width - style.padding * 2; + texture.orig.height = texture._frame.height - style.padding * 2; + + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + + texture.baseTexture.emit('update', texture.baseTexture); + + this.dirty = false; + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Text.prototype.renderWebGL = function renderWebGL(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype.renderWebGL.call(this, renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Text.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype._renderCanvas.call(this, renderer); + }; + + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @private + * @param {string} text - String to apply word wrapping to + * @return {string} New string with new lines applied where required + */ + + + Text.prototype.wordWrap = function wordWrap(text) { + // Greedy wrapping algorithm that will wrap words as the line grows longer + // than its horizontal bounds. + var result = ''; + var style = this._style; + var lines = text.split('\n'); + var wordWrapWidth = style.wordWrapWidth; + + for (var i = 0; i < lines.length; i++) { + var spaceLeft = wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) { + var wordWidth = this.context.measureText(words[j]).width; + + if (style.breakWords && wordWidth > wordWrapWidth) { + // Word should be split in the middle + var characters = words[j].split(''); + + for (var c = 0; c < characters.length; c++) { + var characterWidth = this.context.measureText(characters[c]).width; + + if (characterWidth > spaceLeft) { + result += '\n' + characters[c]; + spaceLeft = wordWrapWidth - characterWidth; + } else { + if (c === 0) { + result += ' '; + } + + result += characters[c]; + spaceLeft -= characterWidth; + } + } + } else { + var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width; + + if (j === 0 || wordWidthWithSpace > spaceLeft) { + // Skip printing the newline if it's the first word of the line that is + // greater than the word wrap width. + if (j > 0) { + result += '\n'; + } + result += words[j]; + spaceLeft = wordWrapWidth - wordWidth; + } else { + spaceLeft -= wordWidthWithSpace; + result += ' ' + words[j]; + } + } + } + + if (i < lines.length - 1) { + result += '\n'; + } + } + + return result; + }; + + /** + * Gets the local bounds of the text object. + * + * @param {Rectangle} rect - The output rectangle. + * @return {Rectangle} The bounds. + */ + + + Text.prototype.getLocalBounds = function getLocalBounds(rect) { + this.updateText(true); + + return _Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + */ + + + Text.prototype._calculateBounds = function _calculateBounds() { + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; + + /** + * Method to be called upon a TextStyle change. + * @private + */ + + + Text.prototype._onStyleChange = function _onStyleChange() { + this.dirty = true; + }; + + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * + * @private + * @param {object} style - The style. + * @param {string[]} lines - The lines of text. + * @return {string|number|CanvasGradient} The fill style + */ + + + Text.prototype._generateFillStyle = function _generateFillStyle(style, lines) { + if (!Array.isArray(style.fill)) { + return style.fill; + } + + // cocoon on canvas+ cannot generate textures, so use the first colour instead + if (navigator.isCocoonJS) { + return style.fill[0]; + } + + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient = void 0; + var totalIterations = void 0; + var currentIteration = void 0; + var stop = void 0; + + var width = this.canvas.width / this.resolution; + var height = this.canvas.height / this.resolution; + + // make a copy of the style settings, so we can manipulate them later + var fill = style.fill.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(style.fill[0]); + fillGradientStops.unshift(0); + + fill.push(style.fill[style.fill.length - 1]); + fillGradientStops.push(1); + + if (style.fillGradientType === _const.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); + + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + totalIterations = (fill.length + 1) * lines.length; + currentIteration = 0; + for (var _i3 = 0; _i3 < lines.length; _i3++) { + currentIteration += 1; + for (var j = 0; j < fill.length; j++) { + if (fillGradientStops[j]) { + stop = fillGradientStops[j] / lines.length + _i3 / lines.length; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[j]); + currentIteration++; + } + } + } else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); + + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + totalIterations = fill.length + 1; + currentIteration = 1; + + for (var _i4 = 0; _i4 < fill.length; _i4++) { + if (fillGradientStops[_i4]) { + stop = fillGradientStops[_i4]; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[_i4]); + currentIteration++; + } + } + + return gradient; + }; + + /** + * Destroys this text object. + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majority of the time the texture will not be shared with any other Sprites. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well + */ + + + Text.prototype.destroy = function destroy(options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + + options = Object.assign({}, defaultDestroyOptions, options); + + _Sprite.prototype.destroy.call(this, options); + + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + + this._style = null; + }; + + /** + * The width of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + /** + * Generates a font style string to use for Text.calculateFontProperties(). Takes the same parameter + * as Text.style. + * + * @static + * @param {object|TextStyle} style - String representing the style of the font + * @return {string} Font style string, for passing to Text.calculateFontProperties() + */ + Text.getFontStyle = function getFontStyle(style) { + style = style || {}; + + if (!(style instanceof _TextStyle2.default)) { + style = new _TextStyle2.default(style); + } + + // build canvas api font setting from individual components. Convert a numeric style.fontSize to px + var fontSizeString = typeof style.fontSize === 'number' ? style.fontSize + 'px' : style.fontSize; + + // Clean-up fontFamily property by quoting each font name + // this will support font names with spaces + var fontFamilies = style.fontFamily; + + if (!Array.isArray(style.fontFamily)) { + fontFamilies = style.fontFamily.split(','); + } + + for (var i = fontFamilies.length - 1; i >= 0; i--) { + // Trim any extra white-space + var fontFamily = fontFamilies[i].trim(); + + // Check if font already contains strings + if (!/([\"\'])[^\'\"]+\1/.test(fontFamily)) { + fontFamily = '"' + fontFamily + '"'; + } + fontFamilies[i] = fontFamily; + } + + return style.fontStyle + ' ' + style.fontVariant + ' ' + style.fontWeight + ' ' + fontSizeString + ' ' + fontFamilies.join(','); + }; + + /** + * Calculates the ascent, descent and fontSize of a given fontStyle + * + * @static + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ + + + Text.calculateFontProperties = function calculateFontProperties(fontStyle) { + // as this method is used for preparing assets, don't recalculate things if we don't need to + if (Text.fontPropertiesCache[fontStyle]) { + return Text.fontPropertiesCache[fontStyle]; + } + + var properties = {}; + + var canvas = Text.fontPropertiesCanvas; + var context = Text.fontPropertiesContext; + + context.font = fontStyle; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('M').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = fontStyle; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i = 0; + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } else { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var _j = 0; _j < line; _j += 4) { + if (imagedata[idx + _j] !== 255) { + stop = true; + break; + } + } + + if (!stop) { + idx -= line; + } else { + break; + } + } + + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + + Text.fontPropertiesCache[fontStyle] = properties; + + return properties; + }; + + _createClass(Text, [{ + key: 'width', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * Set the style of the text. Set up an event listener to listen for changes on the style + * object and mark the text as dirty. + * + * @member {object|PIXI.TextStyle} + */ + + }, { + key: 'style', + get: function get() { + return this._style; + }, + set: function set(style) // eslint-disable-line require-jsdoc + { + style = style || {}; + + if (style instanceof _TextStyle2.default) { + this._style = style; + } else { + this._style = new _TextStyle2.default(style); + } + + this.localStyleID = -1; + this.dirty = true; + } + + /** + * Set the copy for the text object. To split a line you can use '\n'. + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(text) // eslint-disable-line require-jsdoc + { + text = String(text === '' || text === null || text === undefined ? ' ' : text); + + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + } + }]); + + return Text; +}(_Sprite3.default); + +exports.default = Text; + + +Text.fontPropertiesCache = {}; +Text.fontPropertiesCanvas = document.createElement('canvas'); +Text.fontPropertiesContext = Text.fontPropertiesCanvas.getContext('2d'); + +},{"../const":44,"../math":68,"../settings":99,"../sprites/Sprite":100,"../textures/Texture":112,"../utils":120,"../utils/trimCanvas":124,"./TextStyle":107}],107:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // disabling eslint for now, going to rewrite this in v5 +/* eslint-disable */ + +var _const = require('../const'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: '#000000', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: _const.TEXT_GRADIENT.LINEAR_VERTICAL, + fillGradientStops: [], + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + trim: false, + wordWrap: false, + wordWrapWidth: 100 +}; + +/** + * A TextStyle Object decorates a Text Object. It can be shared between + * multiple Text objects. Changing the style will update all text objects using it. + * + * @class + * @memberof PIXI + */ + +var TextStyle = function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string} [style.dropShadowColor='#000000'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours + * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} + * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set + * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * @param {string|string[]} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', 800' or '900') + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Default is 'miter' (creates a sharp corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {boolean} [style.trim=false] - Trim transparent borders + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + _classCallCheck(this, TextStyle); + + this.styleID = 0; + + Object.assign(this, defaultStyle, style); + } + + /** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return {PIXI.TextStyle} New cloned TextStyle object + */ + + + TextStyle.prototype.clone = function clone() { + var clonedProperties = {}; + + for (var key in defaultStyle) { + clonedProperties[key] = this[key]; + } + + return new TextStyle(clonedProperties); + }; + + /** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ + + + TextStyle.prototype.reset = function reset() { + Object.assign(this, defaultStyle); + }; + + _createClass(TextStyle, [{ + key: 'align', + get: function get() { + return this._align; + }, + set: function set(align) { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + } + }, { + key: 'breakWords', + get: function get() { + return this._breakWords; + }, + set: function set(breakWords) { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + } + }, { + key: 'dropShadow', + get: function get() { + return this._dropShadow; + }, + set: function set(dropShadow) { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + } + }, { + key: 'dropShadowAlpha', + get: function get() { + return this._dropShadowAlpha; + }, + set: function set(dropShadowAlpha) { + if (this._dropShadowAlpha !== dropShadowAlpha) { + this._dropShadowAlpha = dropShadowAlpha; + this.styleID++; + } + } + }, { + key: 'dropShadowAngle', + get: function get() { + return this._dropShadowAngle; + }, + set: function set(dropShadowAngle) { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + } + }, { + key: 'dropShadowBlur', + get: function get() { + return this._dropShadowBlur; + }, + set: function set(dropShadowBlur) { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + } + }, { + key: 'dropShadowColor', + get: function get() { + return this._dropShadowColor; + }, + set: function set(dropShadowColor) { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + } + }, { + key: 'dropShadowDistance', + get: function get() { + return this._dropShadowDistance; + }, + set: function set(dropShadowDistance) { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + } + }, { + key: 'fill', + get: function get() { + return this._fill; + }, + set: function set(fill) { + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + } + }, { + key: 'fillGradientType', + get: function get() { + return this._fillGradientType; + }, + set: function set(fillGradientType) { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + } + }, { + key: 'fillGradientStops', + get: function get() { + return this._fillGradientStops; + }, + set: function set(fillGradientStops) { + if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { + this._fillGradientStops = fillGradientStops; + this.styleID++; + } + } + }, { + key: 'fontFamily', + get: function get() { + return this._fontFamily; + }, + set: function set(fontFamily) { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + } + }, { + key: 'fontSize', + get: function get() { + return this._fontSize; + }, + set: function set(fontSize) { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + } + }, { + key: 'fontStyle', + get: function get() { + return this._fontStyle; + }, + set: function set(fontStyle) { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + } + }, { + key: 'fontVariant', + get: function get() { + return this._fontVariant; + }, + set: function set(fontVariant) { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + } + }, { + key: 'fontWeight', + get: function get() { + return this._fontWeight; + }, + set: function set(fontWeight) { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + } + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(letterSpacing) { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + } + }, { + key: 'lineHeight', + get: function get() { + return this._lineHeight; + }, + set: function set(lineHeight) { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + } + }, { + key: 'lineJoin', + get: function get() { + return this._lineJoin; + }, + set: function set(lineJoin) { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + } + }, { + key: 'miterLimit', + get: function get() { + return this._miterLimit; + }, + set: function set(miterLimit) { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + } + }, { + key: 'padding', + get: function get() { + return this._padding; + }, + set: function set(padding) { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + } + }, { + key: 'stroke', + get: function get() { + return this._stroke; + }, + set: function set(stroke) { + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + } + }, { + key: 'strokeThickness', + get: function get() { + return this._strokeThickness; + }, + set: function set(strokeThickness) { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + } + }, { + key: 'textBaseline', + get: function get() { + return this._textBaseline; + }, + set: function set(textBaseline) { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + } + }, { + key: 'trim', + get: function get() { + return this._trim; + }, + set: function set(trim) { + if (this._trim !== trim) { + this._trim = trim; + this.styleID++; + } + } + }, { + key: 'wordWrap', + get: function get() { + return this._wordWrap; + }, + set: function set(wordWrap) { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + } + }, { + key: 'wordWrapWidth', + get: function get() { + return this._wordWrapWidth; + }, + set: function set(wordWrapWidth) { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + } + }]); + + return TextStyle; +}(); + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * + * @param {number|number[]} color + * @return {string} The color as a string. + */ + + +exports.default = TextStyle; +function getSingleColor(color) { + if (typeof color === 'number') { + return (0, _utils.hex2string)(color); + } else if (typeof color === 'string') { + if (color.indexOf('0x') === 0) { + color = color.replace('0x', '#'); + } + } + + return color; +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * + * @param {number|number[]} color + * @return {string} The color as a string. + */ +function getColor(color) { + if (!Array.isArray(color)) { + return getSingleColor(color); + } else { + for (var i = 0; i < color.length; ++i) { + color[i] = getSingleColor(color[i]); + } + + return color; + } +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * + * @param {Array} array1 First array to compare + * @param {Array} array2 Second array to compare + * @return {boolean} Do the arrays contain the same values in the same order + */ +function areArraysEqual(array1, array2) { + if (!Array.isArray(array1) || !Array.isArray(array2)) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } + + return true; +} + +},{"../const":44,"../utils":120}],108:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let baseRenderTexture = new PIXI.BaseRenderTexture(renderer, 800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * baseRenderTexture.render(sprite); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let baseRenderTexture = new PIXI.BaseRenderTexture(100, 100); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var BaseRenderTexture = function (_BaseTexture) { + _inherits(BaseRenderTexture, _BaseTexture); + + /** + * @param {number} [width=100] - The width of the base render texture + * @param {number} [height=100] - The height of the base render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + */ + function BaseRenderTexture() { + var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + + _classCallCheck(this, BaseRenderTexture); + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, null, scaleMode)); + + _this.resolution = resolution || _settings2.default.RESOLUTION; + + _this.width = width; + _this.height = height; + + _this.realWidth = _this.width * _this.resolution; + _this.realHeight = _this.height * _this.resolution; + + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + _this.hasLoaded = true; + + /** + * A map of renderer IDs to webgl renderTargets + * + * @private + * @member {object} + */ + _this._glRenderTargets = {}; + + /** + * A reference to the canvas render target (we only need one as this can be shared across renderers) + * + * @private + * @member {object} + */ + _this._canvasRenderTarget = null; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + return _this; + } + + /** + * Resizes the BaseRenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + */ + + + BaseRenderTexture.prototype.resize = function resize(width, height) { + if (width === this.width && height === this.height) { + return; + } + + this.valid = width > 0 && height > 0; + + this.width = width; + this.height = height; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + if (!this.valid) { + return; + } + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + */ + + + BaseRenderTexture.prototype.destroy = function destroy() { + _BaseTexture.prototype.destroy.call(this, true); + this.renderer = null; + }; + + return BaseRenderTexture; +}(_BaseTexture3.default); + +exports.default = BaseRenderTexture; + +},{"../settings":99,"./BaseTexture":109}],109:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var BaseTexture = function (_EventEmitter) { + _inherits(BaseTexture, _EventEmitter); + + /** + * @param {HTMLImageElement|HTMLCanvasElement} [source] - the source object of the texture. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture + */ + function BaseTexture(source, scaleMode, resolution) { + _classCallCheck(this, BaseTexture); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.uid = (0, _utils.uid)(); + + _this.touched = 0; + + /** + * The resolution / device pixel ratio of the texture + * + * @member {number} + * @default 1 + */ + _this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The width of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.width = 100; + + /** + * The height of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.height = 100; + + // TODO docs + // used to store the actual dimensions of the source + /** + * Used to store the actual width of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realWidth = 100; + /** + * Used to store the actual height of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realHeight = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Set to true once the base texture has successfully loaded. + * + * This is never true if the underlying source fails to load or has no texture data. + * + * @readonly + * @member {boolean} + */ + _this.hasLoaded = false; + + /** + * Set to true if the source is currently loading. + * + * If an Image source is loading the 'loaded' or 'error' event will be + * dispatched when the operation ends. An underyling source that is + * immediately-available bypasses loading entirely. + * + * @readonly + * @member {boolean} + */ + _this.isLoading = false; + + /** + * The image source that is used to create the texture. + * + * TODO: Make this a setter that calls loadSource(); + * + * @readonly + * @member {HTMLImageElement|HTMLCanvasElement} + */ + _this.source = null; // set in loadSource, if at all + + /** + * The image source that is used to create the texture. This is used to + * store the original Svg source when it is replaced with a canvas element. + * + * TODO: Currently not in use but could be used when re-scaling svg. + * + * @readonly + * @member {Image} + */ + _this.origSource = null; // set in loadSvg, if at all + + /** + * Type of image defined in source, eg. `png` or `svg` + * + * @readonly + * @member {string} + */ + _this.imageType = null; // set in updateImageType + + /** + * Scale for source image. Used with Svg images to scale them before rasterization. + * + * @readonly + * @member {number} + */ + _this.sourceScale = 1.0; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * All blend modes, and shaders written for default value. Change it on your own risk. + * + * @member {boolean} + * @default true + */ + _this.premultipliedAlpha = true; + + /** + * The image url of the texture + * + * @member {string} + */ + _this.imageUrl = null; + + /** + * Whether or not the texture is a power of two, try to use power of two textures as much + * as you can + * + * @private + * @member {boolean} + */ + _this.isPowerOfTwo = false; + + // used for webGL + + /** + * + * Set this to true if a mipmap of this texture needs to be generated. This value needs + * to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @member {boolean} + * @see PIXI.MIPMAP_TEXTURES + */ + _this.mipmap = _settings2.default.MIPMAP_TEXTURES; + + /** + * + * WebGL Texture wrap mode + * + * @member {number} + * @see PIXI.WRAP_MODES + */ + _this.wrapMode = _settings2.default.WRAP_MODE; + + /** + * A map of renderer IDs to webgl textures + * + * @private + * @member {object} + */ + _this._glTextures = {}; + + _this._enabled = 0; + _this._virtalBoundId = -1; + + // if no source passed don't try to load + if (source) { + _this.loadSource(source); + } + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + + /** + * Fired when a not-immediately-available source finishes loading. + * + * @protected + * @event loaded + * @memberof PIXI.BaseTexture# + */ + + /** + * Fired when a not-immediately-available source fails to load. + * + * @protected + * @event error + * @memberof PIXI.BaseTexture# + */ + return _this; + } + + /** + * Updates the texture on all the webgl renderers, this also assumes the src has changed. + * + * @fires update + */ + + + BaseTexture.prototype.update = function update() { + // Svg size is handled during load + if (this.imageType !== 'svg') { + this.realWidth = this.source.naturalWidth || this.source.videoWidth || this.source.width; + this.realHeight = this.source.naturalHeight || this.source.videoHeight || this.source.height; + + this._updateDimensions(); + } + + this.emit('update', this); + }; + + /** + * Update dimensions from real values + */ + + + BaseTexture.prototype._updateDimensions = function _updateDimensions() { + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + this.isPowerOfTwo = _bitTwiddle2.default.isPow2(this.realWidth) && _bitTwiddle2.default.isPow2(this.realHeight); + }; + + /** + * Load a source. + * + * If the source is not-immediately-available, such as an image that needs to be + * downloaded, then the 'loaded' or 'error' event will be dispatched in the future + * and `hasLoaded` will remain false after this call. + * + * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: + * + * if (texture.hasLoaded) { + * // texture ready for use + * } else if (texture.isLoading) { + * // listen to 'loaded' and/or 'error' events on texture + * } else { + * // not loading, not going to load UNLESS the source is reloaded + * // (it may still make sense to listen to the events) + * } + * + * @protected + * @param {HTMLImageElement|HTMLCanvasElement} source - the source object of the texture. + */ + + + BaseTexture.prototype.loadSource = function loadSource(source) { + var _this2 = this; + + var wasLoading = this.isLoading; + + this.hasLoaded = false; + this.isLoading = false; + + if (wasLoading && this.source) { + this.source.onload = null; + this.source.onerror = null; + } + + var firstSourceLoaded = !this.source; + + this.source = source; + + // Apply source if loaded. Otherwise setup appropriate loading monitors. + if ((source.src && source.complete || source.getContext) && source.width && source.height) { + this._updateImageType(); + + if (this.imageType === 'svg') { + this._loadSvgSource(); + } else { + this._sourceLoaded(); + } + + if (firstSourceLoaded) { + // send loaded event if previous source was null and we have been passed a pre-loaded IMG element + this.emit('loaded', this); + } + } else if (!source.getContext) { + var _ret = function () { + // Image fail / not ready + _this2.isLoading = true; + + var scope = _this2; + + source.onload = function () { + scope._updateImageType(); + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope._sourceLoaded(); + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + scope.emit('loaded', scope); + }; + + source.onerror = function () { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope.emit('error', scope); + }; + + // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element + // "The value of `complete` can thus change while a script is executing." + // So complete needs to be re-checked after the callbacks have been added.. + // NOTE: complete will be true if the image has no src so best to check if the src is set. + if (source.complete && source.src) { + // ..and if we're complete now, no need for callbacks + source.onload = null; + source.onerror = null; + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return { + v: void 0 + }; + } + + _this2.isLoading = false; + + if (source.width && source.height) { + _this2._sourceLoaded(); + + // If any previous subscribers possible + if (wasLoading) { + _this2.emit('loaded', _this2); + } + } + // If any previous subscribers possible + else if (wasLoading) { + _this2.emit('error', _this2); + } + } + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + }; + + /** + * Updates type of the source image. + */ + + + BaseTexture.prototype._updateImageType = function _updateImageType() { + if (!this.imageUrl) { + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + var imageType = void 0; + + if (dataUri && dataUri.mediaType === 'image') { + // Check for subType validity + var firstSubType = dataUri.subType.split('+')[0]; + + imageType = (0, _utils.getUrlFileExtension)('.' + firstSubType); + + if (!imageType) { + throw new Error('Invalid image type in data URI.'); + } + } else { + imageType = (0, _utils.getUrlFileExtension)(this.imageUrl); + + if (!imageType) { + imageType = 'png'; + } + } + + this.imageType = imageType; + }; + + /** + * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls + * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. + */ + + + BaseTexture.prototype._loadSvgSource = function _loadSvgSource() { + if (this.imageType !== 'svg') { + // Do nothing if source is not svg + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + + if (dataUri) { + this._loadSvgSourceUsingDataUri(dataUri); + } else { + // We got an URL, so we need to do an XHR to check the svg size + this._loadSvgSourceUsingXhr(); + } + }; + + /** + * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`. + * + * @param {string} dataUri - The data uri to load from. + */ + + + BaseTexture.prototype._loadSvgSourceUsingDataUri = function _loadSvgSourceUsingDataUri(dataUri) { + var svgString = void 0; + + if (dataUri.encoding === 'base64') { + if (!atob) { + throw new Error('Your browser doesn\'t support base64 conversions.'); + } + svgString = atob(dataUri.data); + } else { + svgString = dataUri.data; + } + + this._loadSvgSourceUsingString(svgString); + }; + + /** + * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. + */ + + + BaseTexture.prototype._loadSvgSourceUsingXhr = function _loadSvgSourceUsingXhr() { + var _this3 = this; + + var svgXhr = new XMLHttpRequest(); + + // This throws error on IE, so SVG Document can't be used + // svgXhr.responseType = 'document'; + + // This is not needed since we load the svg as string (breaks IE too) + // but overrideMimeType() can be used to force the response to be parsed as XML + // svgXhr.overrideMimeType('image/svg+xml'); + + svgXhr.onload = function () { + if (svgXhr.readyState !== svgXhr.DONE || svgXhr.status !== 200) { + throw new Error('Failed to load SVG using XHR.'); + } + + _this3._loadSvgSourceUsingString(svgXhr.response); + }; + + svgXhr.onerror = function () { + return _this3.emit('error', _this3); + }; + + svgXhr.open('GET', this.imageUrl, true); + svgXhr.send(); + }; + + /** + * Loads texture using an SVG string. The original SVG Image is stored as `origSource` and the + * created canvas is the new `source`. The SVG is scaled using `sourceScale`. Called by + * `_loadSvgSourceUsingXhr` or `_loadSvgSourceUsingDataUri`. + * + * @param {string} svgString SVG source as string + * + * @fires loaded + */ + + + BaseTexture.prototype._loadSvgSourceUsingString = function _loadSvgSourceUsingString(svgString) { + var svgSize = (0, _utils.getSvgSize)(svgString); + + var svgWidth = svgSize.width; + var svgHeight = svgSize.height; + + if (!svgWidth || !svgHeight) { + throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); + } + + // Scale realWidth and realHeight + this.realWidth = Math.round(svgWidth * this.sourceScale); + this.realHeight = Math.round(svgHeight * this.sourceScale); + + this._updateDimensions(); + + // Create a canvas element + var canvas = document.createElement('canvas'); + + canvas.width = this.realWidth; + canvas.height = this.realHeight; + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + + // Draw the Svg to the canvas + canvas.getContext('2d').drawImage(this.source, 0, 0, svgWidth, svgHeight, 0, 0, this.realWidth, this.realHeight); + + // Replace the original source image with the canvas + this.origSource = this.source; + this.source = canvas; + + // Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`) + _utils.BaseTextureCache[canvas._pixiId] = this; + + this.isLoading = false; + this._sourceLoaded(); + this.emit('loaded', this); + }; + + /** + * Used internally to update the width, height, and some other tracking vars once + * a source has successfully loaded. + * + * @private + */ + + + BaseTexture.prototype._sourceLoaded = function _sourceLoaded() { + this.hasLoaded = true; + this.update(); + }; + + /** + * Destroys this base texture + * + */ + + + BaseTexture.prototype.destroy = function destroy() { + if (this.imageUrl) { + delete _utils.BaseTextureCache[this.imageUrl]; + delete _utils.TextureCache[this.imageUrl]; + + this.imageUrl = null; + + if (!navigator.isCocoonJS) { + this.source.src = ''; + } + } + // An svg source has both `imageUrl` and `__pixiId`, so no `else if` here + if (this.source && this.source._pixiId) { + delete _utils.BaseTextureCache[this.source._pixiId]; + } + + this.source = null; + + this.dispose(); + + this._destroyed = true; + }; + + /** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + */ + + + BaseTexture.prototype.dispose = function dispose() { + this.emit('dispose', this); + }; + + /** + * Changes the source image of the texture. + * The original source must be an Image element. + * + * @param {string} newSrc - the path of the image + */ + + + BaseTexture.prototype.updateSourceImage = function updateSourceImage(newSrc) { + this.source.src = newSrc; + + this.loadSource(this.source); + }; + + /** + * Helper function that creates a base texture from the given image url. + * If the image is not in the base texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + // new Image() breaks tex loading in some versions of Chrome. + // See https://code.google.com/p/chromium/issues/detail?id=238071 + var image = new Image(); // document.createElement('img'); + + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + image.crossOrigin = (0, _determineCrossOrigin2.default)(imageUrl); + } + + baseTexture = new BaseTexture(image, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + image.src = imageUrl; // Setting this triggers load + + _utils.BaseTextureCache[imageUrl] = baseTexture; + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode) { + if (!canvas._pixiId) { + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[canvas._pixiId]; + + if (!baseTexture) { + baseTexture = new BaseTexture(canvas, scaleMode); + _utils.BaseTextureCache[canvas._pixiId] = baseTexture; + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture based on the source you provide. + * The source can be - image url, image element, canvas element. + * + * @static + * @param {string|HTMLImageElement|HTMLCanvasElement} source - The source to create base texture from. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.from = function from(source, scaleMode, sourceScale) { + if (typeof source === 'string') { + return BaseTexture.fromImage(source, undefined, scaleMode, sourceScale); + } else if (source instanceof HTMLImageElement) { + var imageUrl = source.src; + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + baseTexture = new BaseTexture(source, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + _utils.BaseTextureCache[imageUrl] = baseTexture; + } + + return baseTexture; + } else if (source instanceof HTMLCanvasElement) { + return BaseTexture.fromCanvas(source, scaleMode); + } + + // lets assume its a base texture! + return source; + }; + + return BaseTexture; +}(_eventemitter2.default); + +exports.default = BaseTexture; + +},{"../settings":99,"../utils":120,"../utils/determineCrossOrigin":119,"bit-twiddle":1,"eventemitter3":3}],110:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseRenderTexture = require('./BaseRenderTexture'); + +var _BaseRenderTexture2 = _interopRequireDefault(_BaseRenderTexture); + +var _Texture2 = require('./Texture'); + +var _Texture3 = _interopRequireDefault(_Texture2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A RenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let renderTexture = PIXI.RenderTexture.create(800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let renderTexture = new PIXI.RenderTexture.create(100, 100); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.Texture + * @memberof PIXI + */ +var RenderTexture = function (_Texture) { + _inherits(RenderTexture, _Texture); + + /** + * @param {PIXI.BaseRenderTexture} baseRenderTexture - The renderer used for this RenderTexture + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + */ + function RenderTexture(baseRenderTexture, frame) { + _classCallCheck(this, RenderTexture); + + // support for legacy.. + var _legacyRenderer = null; + + if (!(baseRenderTexture instanceof _BaseRenderTexture2.default)) { + /* eslint-disable prefer-rest-params, no-console */ + var width = arguments[1]; + var height = arguments[2]; + var scaleMode = arguments[3]; + var resolution = arguments[4]; + + // we have an old render texture.. + console.warn('Please use RenderTexture.create(' + width + ', ' + height + ') instead of the ctor directly.'); + _legacyRenderer = arguments[0]; + /* eslint-enable prefer-rest-params, no-console */ + + frame = null; + baseRenderTexture = new _BaseRenderTexture2.default(width, height, scaleMode, resolution); + } + + /** + * The base texture object that this texture uses + * + * @member {BaseTexture} + */ + + var _this = _possibleConstructorReturn(this, _Texture.call(this, baseRenderTexture, frame)); + + _this.legacyRenderer = _legacyRenderer; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = true; + + _this._updateUvs(); + return _this; + } + + /** + * Resizes the RenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + * @param {boolean} doNotResizeBaseTexture - Should the baseTexture.width and height values be resized as well? + */ + + + RenderTexture.prototype.resize = function resize(width, height, doNotResizeBaseTexture) { + // TODO - could be not required.. + this.valid = width > 0 && height > 0; + + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + + if (!doNotResizeBaseTexture) { + this.baseTexture.resize(width, height); + } + + this._updateUvs(); + }; + + /** + * A short hand way of creating a render texture. + * + * @param {number} [width=100] - The width of the render texture + * @param {number} [height=100] - The height of the render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.RenderTexture} The new render texture + */ + + + RenderTexture.create = function create(width, height, scaleMode, resolution) { + return new RenderTexture(new _BaseRenderTexture2.default(width, height, scaleMode, resolution)); + }; + + return RenderTexture; +}(_Texture3.default); + +exports.default = RenderTexture; + +},{"./BaseRenderTexture":108,"./Texture":112}],111:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _ = require('../'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Utility class for maintaining reference to a collection + * of Textures on a single Spritesheet. + * + * @class + * @memberof PIXI + */ +var Spritesheet = function () { + _createClass(Spritesheet, null, [{ + key: 'BATCH_SIZE', + + /** + * The maximum number of Textures to build per process. + * + * @type {number} + * @default 1000 + */ + get: function get() { + return 1000; + } + + /** + * @param {PIXI.BaseTexture} baseTexture Reference to the source BaseTexture object. + * @param {Object} data - Spritesheet image data. + * @param {string} [resolutionFilename] - The filename to consider when determining + * the resolution of the spritesheet. If not provided, the imageUrl will + * be used on the BaseTexture. + */ + + }]); + + function Spritesheet(baseTexture, data) { + var resolutionFilename = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + _classCallCheck(this, Spritesheet); + + /** + * Reference to ths source texture + * @type {PIXI.BaseTexture} + */ + this.baseTexture = baseTexture; + + /** + * Map of spritesheet textures. + * @type {Object} + */ + this.textures = {}; + + /** + * Reference to the original JSON data. + * @type {Object} + */ + this.data = data; + + /** + * The resolution of the spritesheet. + * @type {number} + */ + this.resolution = this._updateResolution(resolutionFilename || this.baseTexture.imageUrl); + + /** + * Map of spritesheet frames. + * @type {Object} + * @private + */ + this._frames = this.data.frames; + + /** + * Collection of frame names. + * @type {string[]} + * @private + */ + this._frameKeys = Object.keys(this._frames); + + /** + * Current batch index being processed. + * @type {number} + * @private + */ + this._batchIndex = 0; + + /** + * Callback when parse is completed. + * @type {Function} + * @private + */ + this._callback = null; + } + + /** + * Generate the resolution from the filename or fallback + * to the meta.scale field of the JSON data. + * + * @private + * @param {string} resolutionFilename - The filename to use for resolving + * the default resolution. + * @return {number} Resolution to use for spritesheet. + */ + + + Spritesheet.prototype._updateResolution = function _updateResolution(resolutionFilename) { + var scale = this.data.meta.scale; + + // Use a defaultValue of `null` to check if a url-based resolution is set + var resolution = (0, _utils.getResolutionOfUrl)(resolutionFilename, null); + + // No resolution found via URL + if (resolution === null) { + // Use the scale value or default to 1 + resolution = scale !== undefined ? parseFloat(scale) : 1; + } + + // For non-1 resolutions, update baseTexture + if (resolution !== 1) { + this.baseTexture.resolution = resolution; + this.baseTexture.update(); + } + + return resolution; + }; + + /** + * Parser spritesheet from loaded data. This is done asynchronously + * to prevent creating too many Texture within a single process. + * + * @param {Function} callback - Callback when complete returns + * a map of the Textures for this spritesheet. + */ + + + Spritesheet.prototype.parse = function parse(callback) { + this._batchIndex = 0; + this._callback = callback; + + if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) { + this._processFrames(0); + this._parseComplete(); + } else { + this._nextBatch(); + } + }; + + /** + * Process a batch of frames + * + * @private + * @param {number} initialFrameIndex - The index of frame to start. + */ + + + Spritesheet.prototype._processFrames = function _processFrames(initialFrameIndex) { + var frameIndex = initialFrameIndex; + var maxFrames = Spritesheet.BATCH_SIZE; + + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { + var i = this._frameKeys[frameIndex]; + var rect = this._frames[i].frame; + + if (rect) { + var frame = null; + var trim = null; + var orig = new _.Rectangle(0, 0, this._frames[i].sourceSize.w / this.resolution, this._frames[i].sourceSize.h / this.resolution); + + if (this._frames[i].rotated) { + frame = new _.Rectangle(rect.x / this.resolution, rect.y / this.resolution, rect.h / this.resolution, rect.w / this.resolution); + } else { + frame = new _.Rectangle(rect.x / this.resolution, rect.y / this.resolution, rect.w / this.resolution, rect.h / this.resolution); + } + + // Check to see if the sprite is trimmed + if (this._frames[i].trimmed) { + trim = new _.Rectangle(this._frames[i].spriteSourceSize.x / this.resolution, this._frames[i].spriteSourceSize.y / this.resolution, rect.w / this.resolution, rect.h / this.resolution); + } + + this.textures[i] = new _.Texture(this.baseTexture, frame, orig, trim, this._frames[i].rotated ? 2 : 0); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage functions + _utils.TextureCache[i] = this.textures[i]; + } + + frameIndex++; + } + }; + + /** + * The parse has completed. + * + * @private + */ + + + Spritesheet.prototype._parseComplete = function _parseComplete() { + var callback = this._callback; + + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); + }; + + /** + * Begin the next batch of textures. + * + * @private + */ + + + Spritesheet.prototype._nextBatch = function _nextBatch() { + var _this = this; + + this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); + this._batchIndex++; + setTimeout(function () { + if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { + _this._nextBatch(); + } else { + _this._parseComplete(); + } + }, 0); + }; + + /** + * Destroy Spritesheet and don't use after this. + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Spritesheet.prototype.destroy = function destroy() { + var destroyBase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + for (var i in this.textures) { + this.textures[i].destroy(); + } + this._frames = null; + this._frameKeys = null; + this.data = null; + this.textures = null; + if (destroyBase) { + this.baseTexture.destroy(); + } + this.baseTexture = null; + }; + + return Spritesheet; +}(); + +exports.default = Spritesheet; + +},{"../":63,"../utils":120}],112:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture = require('./BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _VideoBaseTexture = require('./VideoBaseTexture'); + +var _VideoBaseTexture2 = _interopRequireDefault(_VideoBaseTexture); + +var _TextureUvs = require('./TextureUvs'); + +var _TextureUvs2 = _interopRequireDefault(_TextureUvs); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _math = require('../math'); + +var _utils = require('../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided + * then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * let texture = PIXI.Texture.fromImage('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` + * + * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. + * You can check for this by checking the sprite's _textureID property. + * ```js + * var texture = PIXI.Texture.fromImage('assets/image.svg'); + * var sprite1 = new PIXI.Sprite(texture); + * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file + * ``` + * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var Texture = function (_EventEmitter) { + _inherits(Texture, _EventEmitter); + + /** + * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + * @param {PIXI.Rectangle} [orig] - The area of original texture + * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture + * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8} + */ + function Texture(baseTexture, frame, orig, trim, rotate) { + _classCallCheck(this, Texture); + + /** + * Does this Texture have any frame data assigned to it? + * + * @member {boolean} + */ + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.noFrame = false; + + if (!frame) { + _this.noFrame = true; + frame = new _math.Rectangle(0, 0, 1, 1); + } + + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @member {PIXI.BaseTexture} + */ + _this.baseTexture = baseTexture; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @member {PIXI.Rectangle} + */ + _this._frame = frame; + + /** + * This is the trimmed area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @member {boolean} + */ + _this.requiresUpdate = false; + + /** + * The WebGL UV data cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + _this._uvs = null; + + /** + * This is the area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + + _this._rotate = Number(rotate || 0); + + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); + } + + if (baseTexture.hasLoaded) { + if (_this.noFrame) { + frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + + // if there is no frame we should monitor for any base texture changes.. + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + _this.frame = frame; + } else { + baseTexture.once('loaded', _this.onBaseTextureLoaded, _this); + } + + /** + * Fired when the texture is updated. This happens if the frame or the baseTexture is updated. + * + * @event update + * @memberof PIXI.Texture# + * @protected + */ + + _this._updateID = 0; + + /** + * Extra field for extra plugins. May contain clamp settings and some matrices + * @type {Object} + */ + _this.transform = null; + return _this; + } + + /** + * Updates this texture on the gpu. + * + */ + + + Texture.prototype.update = function update() { + this.baseTexture.update(); + }; + + /** + * Called when the base texture is loaded + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureLoaded = function onBaseTextureLoaded(baseTexture) { + this._updateID++; + + // TODO this code looks confusing.. boo to abusing getters and setters! + if (this.noFrame) { + this.frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } else { + this.frame = this._frame; + } + + this.baseTexture.on('update', this.onBaseTextureUpdated, this); + this.emit('update', this); + }; + + /** + * Called when the base texture is updated + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated(baseTexture) { + this._updateID++; + + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Texture.prototype.destroy = function destroy(destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destroyed too.. + if (_utils.TextureCache[this.baseTexture.imageUrl]) { + delete _utils.TextureCache[this.baseTexture.imageUrl]; + } + + this.baseTexture.destroy(); + } + + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); + + this.baseTexture = null; + } + + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + + this.valid = false; + + this.off('dispose', this.dispose, this); + this.off('update', this.update, this); + }; + + /** + * Creates a new texture object that acts the same as this one. + * + * @return {PIXI.Texture} The new texture + */ + + + Texture.prototype.clone = function clone() { + return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); + }; + + /** + * Updates the internal WebGL UV cache. + * + * @protected + */ + + + Texture.prototype._updateUvs = function _updateUvs() { + if (!this._uvs) { + this._uvs = new _TextureUvs2.default(); + } + + this._uvs.set(this._frame, this.baseTexture, this.rotate); + + this._updateID++; + }; + + /** + * Helper function that creates a Texture object from the given image url. + * If the image is not in the texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var texture = _utils.TextureCache[imageUrl]; + + if (!texture) { + texture = new Texture(_BaseTexture2.default.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); + _utils.TextureCache[imageUrl] = texture; + } + + return texture; + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return texture; + }; + + /** + * Helper function that creates a new Texture based on the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromCanvas = function fromCanvas(canvas, scaleMode) { + return new Texture(_BaseTexture2.default.fromCanvas(canvas, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the given video element. + * + * @static + * @param {HTMLVideoElement|string} video - The URL or actual element of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideo = function fromVideo(video, scaleMode) { + if (typeof video === 'string') { + return Texture.fromVideoUrl(video, scaleMode); + } + + return new Texture(_VideoBaseTexture2.default.fromVideo(video, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the video url. + * + * @static + * @param {string} videoUrl - URL of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideoUrl = function fromVideoUrl(videoUrl, scaleMode) { + return new Texture(_VideoBaseTexture2.default.fromUrl(videoUrl, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} + * source - Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.from = function from(source) { + // TODO auto detect cross origin.. + // TODO pass in scale mode? + if (typeof source === 'string') { + var texture = _utils.TextureCache[source]; + + if (!texture) { + // check if its a video.. + var isVideo = source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/) !== null; + + if (isVideo) { + return Texture.fromVideoUrl(source); + } + + return Texture.fromImage(source); + } + + return texture; + } else if (source instanceof HTMLImageElement) { + return new Texture(_BaseTexture2.default.from(source)); + } else if (source instanceof HTMLCanvasElement) { + return Texture.fromCanvas(source); + } else if (source instanceof HTMLVideoElement) { + return Texture.fromVideo(source); + } else if (source instanceof _BaseTexture2.default) { + return new Texture(source); + } + + // lets assume its a texture! + return source; + }; + + /** + * Create a texture from a source and add to the cache. + * + * @static + * @param {HTMLImageElement|HTMLCanvasElement} source - The input source. + * @param {String} imageUrl - File name of texture, for cache and resolving resolution. + * @param {String} [name] - Human readible name for the texture cache. If no name is + * specified, only `imageUrl` will be used as the cache ID. + * @return {PIXI.Texture} Output texture + */ + + + Texture.fromLoader = function fromLoader(source, imageUrl, name) { + var baseTexture = new _BaseTexture2.default(source, undefined, (0, _utils.getResolutionOfUrl)(imageUrl)); + var texture = new Texture(baseTexture); + + baseTexture.imageUrl = imageUrl; + + // No name, use imageUrl instead + if (!name) { + name = imageUrl; + } + + // lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions + _utils.BaseTextureCache[name] = baseTexture; + _utils.TextureCache[name] = texture; + + // also add references by url if they are different. + if (name !== imageUrl) { + _utils.BaseTextureCache[imageUrl] = baseTexture; + _utils.TextureCache[imageUrl] = texture; + } + + return texture; + }; + + /** + * Adds a texture to the global TextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the texture will be stored against. + */ + + + Texture.addTextureToCache = function addTextureToCache(texture, id) { + _utils.TextureCache[id] = texture; + }; + + /** + * Remove a texture from the global TextureCache. + * + * @static + * @param {string} id - The id of the texture to be removed + * @return {PIXI.Texture} The texture that was removed + */ + + + Texture.removeTextureFromCache = function removeTextureFromCache(id) { + var texture = _utils.TextureCache[id]; + + delete _utils.TextureCache[id]; + delete _utils.BaseTextureCache[id]; + + return texture; + }; + + /** + * The frame specifies the region of the base texture that this texture uses. + * + * @member {PIXI.Rectangle} + */ + + + _createClass(Texture, [{ + key: 'frame', + get: function get() { + return this._frame; + }, + set: function set(frame) // eslint-disable-line require-jsdoc + { + this._frame = frame; + + this.noFrame = false; + + if (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height) { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + ('X: ' + frame.x + ' + ' + frame.width + ' > ' + this.baseTexture.width + ' ') + ('Y: ' + frame.y + ' + ' + frame.height + ' > ' + this.baseTexture.height)); + } + + // this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + this.valid = frame && frame.width && frame.height && this.baseTexture.hasLoaded; + + if (!this.trim && !this.rotate) { + this.orig = frame; + } + + if (this.valid) { + this._updateUvs(); + } + } + + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.GroupD8} for explanation + * + * @member {number} + */ + + }, { + key: 'rotate', + get: function get() { + return this._rotate; + }, + set: function set(rotate) // eslint-disable-line require-jsdoc + { + this._rotate = rotate; + if (this.valid) { + this._updateUvs(); + } + } + + /** + * The width of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'width', + get: function get() { + return this.orig.width; + } + + /** + * The height of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.orig.height; + } + }]); + + return Texture; +}(_eventemitter2.default); + +exports.default = Texture; + + +function createWhiteTexture() { + var canvas = document.createElement('canvas'); + + canvas.width = 10; + canvas.height = 10; + + var context = canvas.getContext('2d'); + + context.fillStyle = 'white'; + context.fillRect(0, 0, 10, 10); + + return new Texture(new _BaseTexture2.default(canvas)); +} + +function removeAllHandlers(tex) { + tex.destroy = function _emptyDestroy() {/* empty */}; + tex.on = function _emptyOn() {/* empty */}; + tex.once = function _emptyOnce() {/* empty */}; + tex.emit = function _emptyEmit() {/* empty */}; +} + +/** + * An empty texture, used often to not have to create multiple empty textures. + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.EMPTY = new Texture(new _BaseTexture2.default()); +removeAllHandlers(Texture.EMPTY); +removeAllHandlers(Texture.EMPTY.baseTexture); + +/** + * A white texture of 10x10 size, used for graphics and other things + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.WHITE = createWhiteTexture(); +removeAllHandlers(Texture.WHITE); +removeAllHandlers(Texture.WHITE.baseTexture); + +},{"../math":68,"../utils":120,"./BaseTexture":109,"./TextureUvs":113,"./VideoBaseTexture":114,"eventemitter3":3}],113:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _GroupD = require('../math/GroupD8'); + +var _GroupD2 = _interopRequireDefault(_GroupD); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A standard object to store the Uvs of a texture + * + * @class + * @private + * @memberof PIXI + */ +var TextureUvs = function () { + /** + * + */ + function TextureUvs() { + _classCallCheck(this, TextureUvs); + + this.x0 = 0; + this.y0 = 0; + + this.x1 = 1; + this.y1 = 0; + + this.x2 = 1; + this.y2 = 1; + + this.x3 = 0; + this.y3 = 1; + + this.uvsUint32 = new Uint32Array(4); + } + + /** + * Sets the texture Uvs based on the given frame information. + * + * @private + * @param {PIXI.Rectangle} frame - The frame of the texture + * @param {PIXI.Rectangle} baseFrame - The base frame of the texture + * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8} + */ + + + TextureUvs.prototype.set = function set(frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + + // coordinates of center + var cX = frame.x / tw + w2; + var cY = frame.y / th + h2; + + rotate = _GroupD2.default.add(rotate, _GroupD2.default.NW); // NW is top-left corner + this.x0 = cX + w2 * _GroupD2.default.uX(rotate); + this.y0 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + w2 * _GroupD2.default.uX(rotate); + this.y1 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x2 = cX + w2 * _GroupD2.default.uX(rotate); + this.y2 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x3 = cX + w2 * _GroupD2.default.uX(rotate); + this.y3 = cY + h2 * _GroupD2.default.uY(rotate); + } else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + + this.uvsUint32[0] = (this.y0 * 65535 & 0xFFFF) << 16 | this.x0 * 65535 & 0xFFFF; + this.uvsUint32[1] = (this.y1 * 65535 & 0xFFFF) << 16 | this.x1 * 65535 & 0xFFFF; + this.uvsUint32[2] = (this.y2 * 65535 & 0xFFFF) << 16 | this.x2 * 65535 & 0xFFFF; + this.uvsUint32[3] = (this.y3 * 65535 & 0xFFFF) << 16 | this.x3 * 65535 & 0xFFFF; + }; + + return TextureUvs; +}(); + +exports.default = TextureUvs; + +},{"../math/GroupD8":64}],114:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _utils = require('../utils'); + +var _ticker = require('../ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture of a [playing] Video. + * + * Video base textures mimic Pixi BaseTexture.from.... method in their creation process. + * + * This can be used in several ways, such as: + * + * ```js + * let texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4'); + * + * let texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' }); + * + * let texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']); + * + * let texture = PIXI.VideoBaseTexture.fromUrls([ + * { src: '/video.webm', mime: 'video/webm' }, + * { src: '/video.mp4', mime: 'video/mp4' } + * ]); + * ``` + * + * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/). + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var VideoBaseTexture = function (_BaseTexture) { + _inherits(VideoBaseTexture, _BaseTexture); + + /** + * @param {HTMLVideoElement} source - Video source + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + */ + function VideoBaseTexture(source, scaleMode) { + _classCallCheck(this, VideoBaseTexture); + + if (!source) { + throw new Error('No video source element specified.'); + } + + // hook in here to check if video is already available. + // BaseTexture looks for a source.complete boolean, plus width & height. + + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + source.complete = true; + } + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, source, scaleMode)); + + _this.width = source.videoWidth; + _this.height = source.videoHeight; + + _this._autoUpdate = true; + _this._isAutoUpdating = false; + + /** + * When set to true will automatically play videos used by this texture once + * they are loaded. If false, it will not modify the playing state. + * + * @member {boolean} + * @default true + */ + _this.autoPlay = true; + + _this.update = _this.update.bind(_this); + _this._onCanPlay = _this._onCanPlay.bind(_this); + + source.addEventListener('play', _this._onPlayStart.bind(_this)); + source.addEventListener('pause', _this._onPlayStop.bind(_this)); + _this.hasLoaded = false; + _this.__loaded = false; + + if (!_this._isSourceReady()) { + source.addEventListener('canplay', _this._onCanPlay); + source.addEventListener('canplaythrough', _this._onCanPlay); + } else { + _this._onCanPlay(); + } + return _this; + } + + /** + * Returns true if the underlying source is playing. + * + * @private + * @return {boolean} True if playing. + */ + + + VideoBaseTexture.prototype._isSourcePlaying = function _isSourcePlaying() { + var source = this.source; + + return source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2; + }; + + /** + * Returns true if the underlying source is ready for playing. + * + * @private + * @return {boolean} True if ready. + */ + + + VideoBaseTexture.prototype._isSourceReady = function _isSourceReady() { + return this.source.readyState === 3 || this.source.readyState === 4; + }; + + /** + * Runs the update loop when the video is ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStart = function _onPlayStart() { + // Just in case the video has not received its can play even yet.. + if (!this.hasLoaded) { + this._onCanPlay(); + } + + if (!this._isAutoUpdating && this.autoUpdate) { + ticker.shared.add(this.update, this); + this._isAutoUpdating = true; + } + }; + + /** + * Fired when a pause event is triggered, stops the update loop + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStop = function _onPlayStop() { + if (this._isAutoUpdating) { + ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } + }; + + /** + * Fired when the video is loaded and ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onCanPlay = function _onCanPlay() { + this.hasLoaded = true; + + if (this.source) { + this.source.removeEventListener('canplay', this._onCanPlay); + this.source.removeEventListener('canplaythrough', this._onCanPlay); + + this.width = this.source.videoWidth; + this.height = this.source.videoHeight; + + // prevent multiple loaded dispatches.. + if (!this.__loaded) { + this.__loaded = true; + this.emit('loaded', this); + } + + if (this._isSourcePlaying()) { + this._onPlayStart(); + } else if (this.autoPlay) { + this.source.play(); + } + } + }; + + /** + * Destroys this texture + * + */ + + + VideoBaseTexture.prototype.destroy = function destroy() { + if (this._isAutoUpdating) { + ticker.shared.remove(this.update, this); + } + + if (this.source && this.source._pixiId) { + delete _utils.BaseTextureCache[this.source._pixiId]; + delete this.source._pixiId; + } + + _BaseTexture.prototype.destroy.call(this); + }; + + /** + * Mimic Pixi BaseTexture.from.... method. + * + * @static + * @param {HTMLVideoElement} video - Video to create texture from + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromVideo = function fromVideo(video, scaleMode) { + if (!video._pixiId) { + video._pixiId = 'video_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[video._pixiId]; + + if (!baseTexture) { + baseTexture = new VideoBaseTexture(video, scaleMode); + _utils.BaseTextureCache[video._pixiId] = baseTexture; + } + + return baseTexture; + }; + + /** + * Helper function that creates a new BaseTexture based on the given video element. + * This BaseTexture can then be used to create a texture + * + * @static + * @param {string|object|string[]|object[]} videoSrc - The URL(s) for the video. + * @param {string} [videoSrc.src] - One of the source urls for the video + * @param {string} [videoSrc.mime] - The mimetype of the video (e.g. 'video/mp4'). If not specified + * the url's extension will be used as the second part of the mime type. + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromUrl = function fromUrl(videoSrc, scaleMode) { + var video = document.createElement('video'); + + video.setAttribute('webkit-playsinline', ''); + video.setAttribute('playsinline', ''); + + // array of objects or strings + if (Array.isArray(videoSrc)) { + for (var i = 0; i < videoSrc.length; ++i) { + video.appendChild(createSource(videoSrc[i].src || videoSrc[i], videoSrc[i].mime)); + } + } + // single object or string + else { + video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); + } + + video.load(); + + return VideoBaseTexture.fromVideo(video, scaleMode); + }; + + /** + * Should the base texture automatically update itself, set to true by default + * + * @member {boolean} + */ + + + _createClass(VideoBaseTexture, [{ + key: 'autoUpdate', + get: function get() { + return this._autoUpdate; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + + if (!this._autoUpdate && this._isAutoUpdating) { + ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } else if (this._autoUpdate && !this._isAutoUpdating) { + ticker.shared.add(this.update, this); + this._isAutoUpdating = true; + } + } + } + }]); + + return VideoBaseTexture; +}(_BaseTexture3.default); + +exports.default = VideoBaseTexture; + + +VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; + +function createSource(path, type) { + if (!type) { + type = 'video/' + path.substr(path.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = path; + source.type = type; + + return source; +} + +},{"../ticker":116,"../utils":120,"./BaseTexture":109}],115:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// Internal event used by composed emitter +var TICK = 'tick'; + +/** + * A Ticker class that runs an update loop that other objects listen to. + * This class is composed around an EventEmitter object to add listeners + * meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, + * e.g. When the ticker is started and the emitter has listeners. + * + * @class + * @memberof PIXI.ticker + */ + +var Ticker = function () { + /** + * + */ + function Ticker() { + var _this = this; + + _classCallCheck(this, Ticker); + + /** + * Internal emitter used to fire 'tick' event + * @private + */ + this._emitter = new _eventemitter2.default(); + + /** + * Internal current frame request ID + * @private + */ + this._requestId = null; + + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + * @private + */ + this._maxElapsedMS = 100; + + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.ticker.Ticker#start} automatically + * when a listener is added. + * + * @member {boolean} + * @default false + */ + this.autoStart = false; + + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS} + * and is scaled with {@link PIXI.ticker.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * + * @member {number} + * @default 1 + */ + this.deltaTime = 1; + + /** + * Time elapsed in milliseconds from last frame to this frame. + * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime} + * is based, this value is neither capped nor scaled. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * Defaults to target frame time + * + * @member {number} + * @default 16.66 + */ + this.elapsedMS = 1 / _settings2.default.TARGET_FPMS; + + /** + * The last time {@link PIXI.ticker.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default 0 + */ + this.lastTime = 0; + + /** + * Factor of current {@link PIXI.ticker.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + * + * @member {number} + * @default 1 + */ + this.speed = 1; + + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.ticker.Ticker#start} has been called. + * `false` if {@link PIXI.ticker.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.ticker.Ticker#autoStart} being `true` + * and a listener is added. + * + * @member {boolean} + * @default false + */ + this.started = false; + + /** + * Internal tick method bound to ticker instance. + * This is because in early 2015, Function.bind + * is still 60% slower in high performance scenarios. + * Also separating frame requests from update method + * so listeners may be called at any time and with + * any animation API, just invoke ticker.update(time). + * + * @private + * @param {number} time - Time since last tick. + */ + this._tick = function (time) { + _this._requestId = null; + + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._emitter.listeners(TICK, true)) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * + * @private + */ + + + Ticker.prototype._requestIfNeeded = function _requestIfNeeded() { + if (this._requestId === null && this._emitter.listeners(TICK, true)) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._requestId = requestAnimationFrame(this._tick); + } + }; + + /** + * Conditionally cancels a pending animation frame. + * + * @private + */ + + + Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; + + /** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * + * @private + */ + + + Ticker.prototype._startIfPossible = function _startIfPossible() { + if (this.started) { + this._requestIfNeeded(); + } else if (this.autoStart) { + this.start(); + } + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#on} internally for the + * internal 'tick' event. It checks if the emitter has listeners, + * and if so it requests a new animation frame at this point. + * + * @param {Function} fn - The listener function to be added for updates + * @param {Function} [context] - The listener context + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.add = function add(fn, context) { + this._emitter.on(TICK, fn, context); + + this._startIfPossible(); + + return this; + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#once} internally for the + * internal 'tick' event. It checks if the emitter has listeners, + * and if so it requests a new animation frame at this point. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context] - The listener context + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.addOnce = function addOnce(fn, context) { + this._emitter.once(TICK, fn, context); + + this._startIfPossible(); + + return this; + }; + + /** + * Calls {@link module:eventemitter3.EventEmitter#off} internally for 'tick' event. + * It checks if the emitter has listeners for 'tick' event. + * If it does, then it cancels the animation frame. + * + * @param {Function} [fn] - The listener function to be removed + * @param {Function} [context] - The listener context to be removed + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.remove = function remove(fn, context) { + this._emitter.off(TICK, fn, context); + + if (!this._emitter.listeners(TICK, true)) { + this._cancelIfNeeded(); + } + + return this; + }; + + /** + * Starts the ticker. If the ticker has listeners + * a new animation frame is requested at this point. + */ + + + Ticker.prototype.start = function start() { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + }; + + /** + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. + */ + + + Ticker.prototype.stop = function stop() { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; + + /** + * Triggers an update. An update entails setting the + * current {@link PIXI.ticker.Ticker#elapsedMS}, + * the current {@link PIXI.ticker.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.ticker.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + + + Ticker.prototype.update = function update() { + var currentTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : performance.now(); + + var elapsedMS = void 0; + + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + + this.deltaTime = elapsedMS * _settings2.default.TARGET_FPMS * this.speed; + + // Invoke listeners added to internal emitter + this._emitter.emit(TICK, this.deltaTime); + } else { + this.deltaTime = this.elapsedMS = 0; + } + + this.lastTime = currentTime; + }; + + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.ticker.Ticker#speed}, which is specific + * to scaling {@link PIXI.ticker.Ticker#deltaTime}. + * + * @member {number} + * @readonly + */ + + + _createClass(Ticker, [{ + key: 'FPS', + get: function get() { + return 1000 / this.elapsedMS; + } + + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.ticker.Ticker#update}. + * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.settings.TARGET_FPMS * 1000`. + * + * @member {number} + * @default 10 + */ + + }, { + key: 'minFPS', + get: function get() { + return 1000 / this._maxElapsedMS; + }, + set: function set(fps) // eslint-disable-line require-jsdoc + { + // Clamp: 0 to TARGET_FPMS + var minFPMS = Math.min(Math.max(0, fps) / 1000, _settings2.default.TARGET_FPMS); + + this._maxElapsedMS = 1 / minFPMS; + } + }]); + + return Ticker; +}(); + +exports.default = Ticker; + +},{"../settings":99,"eventemitter3":3}],116:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Ticker = exports.shared = undefined; + +var _Ticker = require('./Ticker'); + +var _Ticker2 = _interopRequireDefault(_Ticker); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The shared ticker instance used by {@link PIXI.extras.AnimatedSprite}. + * and by {@link PIXI.interaction.InteractionManager}. + * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` + * for this instance. Please follow the examples for usage, including + * how to opt-out of auto-starting the shared ticker. + * + * @example + * let ticker = PIXI.ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(800, 600); + * let stage = new PIXI.Container(); + * let interactionManager = PIXI.interaction.InteractionManager(renderer); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * + * @type {PIXI.ticker.Ticker} + * @memberof PIXI.ticker + */ +var shared = new _Ticker2.default(); + +shared.autoStart = true; + +/** + * @namespace PIXI.ticker + */ +exports.shared = shared; +exports.Ticker = _Ticker2.default; + +},{"./Ticker":115}],117:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = canUploadSameBuffer; +function canUploadSameBuffer() { + // Uploading the same buffer multiple times in a single frame can cause perf issues. + // Apparent on IOS so only check for that at the moment + // this check may become more complex if this issue pops up elsewhere. + var ios = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform); + + return !ios; +} + +},{}],118:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = createIndicesForQuads; +/** + * Generic Mask Stack data structure + * + * @memberof PIXI + * @function createIndicesForQuads + * @private + * @param {number} size - Number of quads + * @return {Uint16Array} indices + */ +function createIndicesForQuads(size) { + // the total number of indices in our array, there are 6 points per quad. + + var totalIndices = size * 6; + + var indices = new Uint16Array(totalIndices); + + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + indices[i + 0] = j + 0; + indices[i + 1] = j + 1; + indices[i + 2] = j + 2; + indices[i + 3] = j + 0; + indices[i + 4] = j + 2; + indices[i + 5] = j + 3; + } + + return indices; +} + +},{}],119:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = determineCrossOrigin; + +var _url2 = require('url'); + +var _url3 = _interopRequireDefault(_url2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var tempAnchor = void 0; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +function determineCrossOrigin(url) { + var loc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location; + + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url3.default.parse(tempAnchor.href); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +} + +},{"url":28}],120:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BaseTextureCache = exports.TextureCache = exports.mixins = exports.pluginTarget = exports.EventEmitter = exports.isMobile = undefined; +exports.uid = uid; +exports.hex2rgb = hex2rgb; +exports.hex2string = hex2string; +exports.rgb2hex = rgb2hex; +exports.getResolutionOfUrl = getResolutionOfUrl; +exports.decomposeDataUri = decomposeDataUri; +exports.getUrlFileExtension = getUrlFileExtension; +exports.getSvgSize = getSvgSize; +exports.skipHello = skipHello; +exports.sayHello = sayHello; +exports.isWebGLSupported = isWebGLSupported; +exports.sign = sign; +exports.removeItems = removeItems; +exports.destroyTextureCache = destroyTextureCache; +exports.clearTextureCache = clearTextureCache; + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _pluginTarget = require('./pluginTarget'); + +var _pluginTarget2 = _interopRequireDefault(_pluginTarget); + +var _mixin = require('./mixin'); + +var mixins = _interopRequireWildcard(_mixin); + +var _ismobilejs = require('ismobilejs'); + +var isMobile = _interopRequireWildcard(_ismobilejs); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var nextUid = 0; +var saidHello = false; + +/** + * @namespace PIXI.utils + */ +exports.isMobile = isMobile; +exports.EventEmitter = _eventemitter2.default; +exports.pluginTarget = _pluginTarget2.default; +exports.mixins = mixins; + +/** + * Gets the next unique identifier + * + * @memberof PIXI.utils + * @function uid + * @return {number} The next unique identifier to use. + */ + +function uid() { + return ++nextUid; +} + +/** + * Converts a hex color number to an [R, G, B] array + * + * @memberof PIXI.utils + * @function hex2rgb + * @param {number} hex - The number to convert + * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one + * @return {number[]} An array representing the [R, G, B] of the color. + */ +function hex2rgb(hex, out) { + out = out || []; + + out[0] = (hex >> 16 & 0xFF) / 255; + out[1] = (hex >> 8 & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + + return out; +} + +/** + * Converts a hex color number to a string. + * + * @memberof PIXI.utils + * @function hex2string + * @param {number} hex - Number in hex + * @return {string} The string color. + */ +function hex2string(hex) { + hex = hex.toString(16); + hex = '000000'.substr(0, 6 - hex.length) + hex; + + return '#' + hex; +} + +/** + * Converts a color as an [R, G, B] array to a hex number + * + * @memberof PIXI.utils + * @function rgb2hex + * @param {number[]} rgb - rgb array + * @return {number} The color number + */ +function rgb2hex(rgb) { + return (rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + (rgb[2] * 255 | 0); +} + +/** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * + * @memberof PIXI.utils + * @function getResolutionOfUrl + * @param {string} url - the image path + * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. + * @return {number} resolution / device pixel ratio of an asset + */ +function getResolutionOfUrl(url, defaultValue) { + var resolution = _settings2.default.RETINA_PREFIX.exec(url); + + if (resolution) { + return parseFloat(resolution[1]); + } + + return defaultValue !== undefined ? defaultValue : 1; +} + +/** + * Typedef for decomposeDataUri return object. + * + * @typedef {object} DecomposedDataUri + * @property {mediaType} Media type, eg. `image` + * @property {subType} Sub type, eg. `png` + * @property {encoding} Data encoding, eg. `base64` + * @property {data} The actual data + */ + +/** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. + * + * @memberof PIXI.utils + * @function decomposeDataUri + * @param {string} dataUri - the data URI to check + * @return {DecomposedDataUri|undefined} The decomposed data uri or undefined + */ +function decomposeDataUri(dataUri) { + var dataUriMatch = _const.DATA_URI.exec(dataUri); + + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + encoding: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + data: dataUriMatch[4] + }; + } + + return undefined; +} + +/** + * Get type of the image by regexp for extension. Returns undefined for unknown extensions. + * + * @memberof PIXI.utils + * @function getUrlFileExtension + * @param {string} url - the image path + * @return {string|undefined} image extension + */ +function getUrlFileExtension(url) { + var extension = _const.URL_FILE_EXTENSION.exec(url); + + if (extension) { + return extension[1].toLowerCase(); + } + + return undefined; +} + +/** + * Typedef for Size object. + * + * @typedef {object} Size + * @property {width} Width component + * @property {height} Height component + */ + +/** + * Get size from an svg string using regexp. + * + * @memberof PIXI.utils + * @function getSvgSize + * @param {string} svgString - a serialized svg element + * @return {Size|undefined} image extension + */ +function getSvgSize(svgString) { + var sizeMatch = _const.SVG_SIZE.exec(svgString); + var size = {}; + + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); + size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); + } + + return size; +} + +/** + * Skips the hello message of renderers that are created after this is run. + * + * @function skipHello + * @memberof PIXI.utils + */ +function skipHello() { + saidHello = true; +} + +/** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever makes you a jerk face. + * + * @static + * @function sayHello + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ +function sayHello(type) { + if (saidHello) { + return; + } + + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = ['\n %c %c %c Pixi.js ' + _const.VERSION + ' - \u2730 ' + type + ' \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n', 'background: #ff66a5; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff66a5; background: #030307; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'background: #ffc3dc; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;']; + + window.console.log.apply(console, args); + } else if (window.console) { + window.console.log('Pixi.js ' + _const.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); + } + + saidHello = true; +} + +/** + * Helper for checking for webgl support + * + * @memberof PIXI.utils + * @function isWebGLSupported + * @return {boolean} is webgl supported + */ +function isWebGLSupported() { + var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; + + try { + if (!window.WebGLRenderingContext) { + return false; + } + + var canvas = document.createElement('canvas'); + var gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); + + var success = !!(gl && gl.getContextAttributes().stencil); + + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + + if (loseContext) { + loseContext.loseContext(); + } + } + + gl = null; + + return success; + } catch (e) { + return false; + } +} + +/** + * Returns sign of number + * + * @memberof PIXI.utils + * @function sign + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ +function sign(n) { + if (n === 0) return 0; + + return n < 0 ? -1 : 1; +} + +/** + * Remove a range of items from an array + * + * @memberof PIXI.utils + * @function removeItems + * @param {Array<*>} arr The target array + * @param {number} startIdx The index to begin removing from (inclusive) + * @param {number} removeCount How many items to remove + */ +function removeItems(arr, startIdx, removeCount) { + var length = arr.length; + + if (startIdx >= length || removeCount === 0) { + return; + } + + removeCount = startIdx + removeCount > length ? length - startIdx : removeCount; + + var len = length - removeCount; + + for (var i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount]; + } + + arr.length = len; +} + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var TextureCache = exports.TextureCache = {}; + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var BaseTextureCache = exports.BaseTextureCache = {}; + +/** + * Destroys all texture in the cache + * + * @memberof PIXI.utils + * @function destroyTextureCache + */ +function destroyTextureCache() { + var key = void 0; + + for (key in TextureCache) { + TextureCache[key].destroy(); + } + for (key in BaseTextureCache) { + BaseTextureCache[key].destroy(); + } +} + +/** + * Removes all textures from cache, but does not destroy them + * + * @memberof PIXI.utils + * @function clearTextureCache + */ +function clearTextureCache() { + var key = void 0; + + for (key in TextureCache) { + delete TextureCache[key]; + } + for (key in BaseTextureCache) { + delete BaseTextureCache[key]; + } +} + +},{"../const":44,"../settings":99,"./mixin":122,"./pluginTarget":123,"eventemitter3":3,"ismobilejs":4}],121:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = maxRecommendedTextures; + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function maxRecommendedTextures(max) { + if (_ismobilejs2.default.tablet || _ismobilejs2.default.phone) { + // check if the res is iphone 6 or higher.. + return 4; + } + + // desktop should be ok + return max; +} + +},{"ismobilejs":4}],122:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.mixin = mixin; +exports.delayMixin = delayMixin; +exports.performMixins = performMixins; +/** + * Mixes all enumerable properties and methods from a source object to a target object. + * + * @memberof PIXI.utils.mixins + * @function mixin + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function mixin(target, source) { + if (!target || !source) return; + // in ES8/ES2017, this would be really easy: + // Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + + // get all the enumerable property keys + var keys = Object.keys(source); + + // loop through properties + for (var i = 0; i < keys.length; ++i) { + var propertyName = keys[i]; + + // Set the property using the property descriptor - this works for accessors and normal value properties + Object.defineProperty(target, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); + } +} + +var mixins = []; + +/** + * Queues a mixin to be handled towards the end of the initialization of PIXI, so that deprecation + * can take effect. + * + * @memberof PIXI.utils.mixins + * @function delayMixin + * @private + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function delayMixin(target, source) { + mixins.push(target, source); +} + +/** + * Handles all mixins queued via delayMixin(). + * + * @memberof PIXI.utils.mixins + * @function performMixins + * @private + */ +function performMixins() { + for (var i = 0; i < mixins.length; i += 2) { + mixin(mixins[i], mixins[i + 1]); + } + mixins.length = 0; +} + +},{}],123:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Mixins functionality to make an object have "plugins". + * + * @example + * function MyObject() {} + * + * pluginTarget.mixin(MyObject); + * + * @mixin + * @memberof PIXI.utils + * @param {object} obj - The object to mix into. + */ +function pluginTarget(obj) { + obj.__plugins = {}; + + /** + * Adds a plugin to an object + * + * @param {string} pluginName - The events that should be listed. + * @param {Function} ctor - The constructor function for the plugin. + */ + obj.registerPlugin = function registerPlugin(pluginName, ctor) { + obj.__plugins[pluginName] = ctor; + }; + + /** + * Instantiates all the plugins of this object + * + */ + obj.prototype.initPlugins = function initPlugins() { + this.plugins = this.plugins || {}; + + for (var o in obj.__plugins) { + this.plugins[o] = new obj.__plugins[o](this); + } + }; + + /** + * Removes all the plugins of this object + * + */ + obj.prototype.destroyPlugins = function destroyPlugins() { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + + this.plugins = null; + }; +} + +exports.default = { + /** + * Mixes in the properties of the pluginTarget into another object + * + * @param {object} obj - The obj to mix into + */ + mixin: function mixin(obj) { + pluginTarget(obj); + } +}; + +},{}],124:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = trimCanvas; +/** + * Trim transparent borders from a canvas + * + * @memberof PIXI + * @function trimCanvas + * @private + * @param {HTMLCanvasElement} canvas - the canvas to trim + * @returns {object} Trim data + */ +function trimCanvas(canvas) { + // https://gist.github.com/remy/784508 + + var width = canvas.width; + var height = canvas.height; + + var context = canvas.getContext('2d'); + var imageData = context.getImageData(0, 0, width, height); + var pixels = imageData.data; + var len = pixels.length; + + var bound = { + top: null, + left: null, + right: null, + bottom: null + }; + var i = void 0; + var x = void 0; + var y = void 0; + + for (i = 0; i < len; i += 4) { + if (pixels[i + 3] !== 0) { + x = i / 4 % width; + y = ~~(i / 4 / width); + + if (bound.top === null) { + bound.top = y; + } + + if (bound.left === null) { + bound.left = x; + } else if (x < bound.left) { + bound.left = x; + } + + if (bound.right === null) { + bound.right = x + 1; + } else if (bound.right < x) { + bound.right = x + 1; + } + + if (bound.bottom === null) { + bound.bottom = y; + } else if (bound.bottom < y) { + bound.bottom = y; + } + } + } + + width = bound.right - bound.left; + height = bound.bottom - bound.top + 1; + + var data = context.getImageData(bound.left, bound.top, width, height); + + return { + height: height, + width: width, + data: data + }; +} + +},{}],125:[function(require,module,exports){ +'use strict'; + +var _core = require('./core'); + +var core = _interopRequireWildcard(_core); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code +function warn(msg) { + /* eslint-disable no-console */ + var stack = new Error().stack; + + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('Deprecation Warning: ', msg); + } else { + // chop off the stack trace which includes pixi.js internal calls + stack = stack.split('\n').splice(3).join('\n'); + + if (console.groupCollapsed) { + console.groupCollapsed('%cDeprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', msg); + console.warn(stack); + console.groupEnd(); + } else { + console.warn('Deprecation Warning: ', msg); + console.warn(stack); + } + } + /* eslint-enable no-console */ +} + +/** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ +core.SpriteBatch = function () { + throw new ReferenceError('SpriteBatch does not exist any more, please use the new ParticleContainer instead.'); +}; + +/** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ +core.AssetLoader = function () { + throw new ReferenceError('The loader system was overhauled in pixi v3, please see the new PIXI.loaders.Loader class.'); +}; + +Object.defineProperties(core, { + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + Stage: { + enumerable: true, + get: function get() { + warn('You do not need to use a PIXI Stage any more, you can simply render any container.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + DisplayObjectContainer: { + enumerable: true, + get: function get() { + warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + Strip: { + enumerable: true, + get: function get() { + warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.'); + + return mesh.Mesh; + } + }, + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + Rope: { + enumerable: true, + get: function get() { + warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.'); + + return mesh.Rope; + } + }, + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + ParticleContainer: { + enumerable: true, + get: function get() { + warn('The ParticleContainer class has been moved to particles.ParticleContainer, ' + 'please use particles.ParticleContainer from now on.'); + + return particles.ParticleContainer; + } + }, + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + MovieClip: { + enumerable: true, + get: function get() { + warn('The MovieClip class has been moved to extras.AnimatedSprite, please use extras.AnimatedSprite.'); + + return extras.AnimatedSprite; + } + }, + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + TilingSprite: { + enumerable: true, + get: function get() { + warn('The TilingSprite class has been moved to extras.TilingSprite, ' + 'please use extras.TilingSprite from now on.'); + + return extras.TilingSprite; + } + }, + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + BitmapText: { + enumerable: true, + get: function get() { + warn('The BitmapText class has been moved to extras.BitmapText, ' + 'please use extras.BitmapText from now on.'); + + return extras.BitmapText; + } + }, + + /** + * @class + * @private + * @name blendModes + * @memberof PIXI + * @see PIXI.BLEND_MODES + * @deprecated since version 3.0.0 + */ + blendModes: { + enumerable: true, + get: function get() { + warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.'); + + return core.BLEND_MODES; + } + }, + + /** + * @class + * @private + * @name scaleModes + * @memberof PIXI + * @see PIXI.SCALE_MODES + * @deprecated since version 3.0.0 + */ + scaleModes: { + enumerable: true, + get: function get() { + warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.'); + + return core.SCALE_MODES; + } + }, + + /** + * @class + * @private + * @name BaseTextureCache + * @memberof PIXI + * @see PIXI.utils.BaseTextureCache + * @deprecated since version 3.0.0 + */ + BaseTextureCache: { + enumerable: true, + get: function get() { + warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, ' + 'please use utils.BaseTextureCache from now on.'); + + return core.utils.BaseTextureCache; + } + }, + + /** + * @class + * @private + * @name TextureCache + * @memberof PIXI + * @see PIXI.utils.TextureCache + * @deprecated since version 3.0.0 + */ + TextureCache: { + enumerable: true, + get: function get() { + warn('The TextureCache class has been moved to utils.TextureCache, ' + 'please use utils.TextureCache from now on.'); + + return core.utils.TextureCache; + } + }, + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + math: { + enumerable: true, + get: function get() { + warn('The math namespace is deprecated, please access members already accessible on PIXI.'); + + return core; + } + }, + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + enumerable: true, + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.Filter; + } + }, + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + TransformManual: { + enumerable: true, + get: function get() { + warn('TransformManual has been renamed to TransformBase, please update your pixi-spine'); + + return core.TransformBase; + } + }, + + /** + * @static + * @constant + * @name PIXI.TARGET_FPMS + * @see PIXI.settings.TARGET_FPMS + * @deprecated since version 4.2.0 + */ + TARGET_FPMS: { + enumerable: true, + get: function get() { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + return core.settings.TARGET_FPMS; + }, + set: function set(value) { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + core.settings.TARGET_FPMS = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.FILTER_RESOLUTION + * @see PIXI.settings.FILTER_RESOLUTION + * @deprecated since version 4.2.0 + */ + FILTER_RESOLUTION: { + enumerable: true, + get: function get() { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + return core.settings.FILTER_RESOLUTION; + }, + set: function set(value) { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + core.settings.FILTER_RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RESOLUTION + * @see PIXI.settings.RESOLUTION + * @deprecated since version 4.2.0 + */ + RESOLUTION: { + enumerable: true, + get: function get() { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + return core.settings.RESOLUTION; + }, + set: function set(value) { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + core.settings.RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.MIPMAP_TEXTURES + * @see PIXI.settings.MIPMAP_TEXTURES + * @deprecated since version 4.2.0 + */ + MIPMAP_TEXTURES: { + enumerable: true, + get: function get() { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + return core.settings.MIPMAP_TEXTURES; + }, + set: function set(value) { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + core.settings.MIPMAP_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_BATCH_SIZE + * @see PIXI.settings.SPRITE_BATCH_SIZE + * @deprecated since version 4.2.0 + */ + SPRITE_BATCH_SIZE: { + enumerable: true, + get: function get() { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + return core.settings.SPRITE_BATCH_SIZE; + }, + set: function set(value) { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + core.settings.SPRITE_BATCH_SIZE = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_MAX_TEXTURES + * @see PIXI.settings.SPRITE_MAX_TEXTURES + * @deprecated since version 4.2.0 + */ + SPRITE_MAX_TEXTURES: { + enumerable: true, + get: function get() { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + return core.settings.SPRITE_MAX_TEXTURES; + }, + set: function set(value) { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + core.settings.SPRITE_MAX_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RETINA_PREFIX + * @see PIXI.settings.RETINA_PREFIX + * @deprecated since version 4.2.0 + */ + RETINA_PREFIX: { + enumerable: true, + get: function get() { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + return core.settings.RETINA_PREFIX; + }, + set: function set(value) { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + core.settings.RETINA_PREFIX = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.DEFAULT_RENDER_OPTIONS + * @see PIXI.settings.RENDER_OPTIONS + * @deprecated since version 4.2.0 + */ + DEFAULT_RENDER_OPTIONS: { + enumerable: true, + get: function get() { + warn('PIXI.DEFAULT_RENDER_OPTIONS has been deprecated, please use PIXI.settings.DEFAULT_RENDER_OPTIONS'); + + return core.settings.RENDER_OPTIONS; + } + } +}); + +// Move the default properties to settings +var defaults = [{ parent: 'TRANSFORM_MODE', target: 'TRANSFORM_MODE' }, { parent: 'GC_MODES', target: 'GC_MODE' }, { parent: 'WRAP_MODES', target: 'WRAP_MODE' }, { parent: 'SCALE_MODES', target: 'SCALE_MODE' }, { parent: 'PRECISION', target: 'PRECISION_FRAGMENT' }]; + +var _loop = function _loop(i) { + var deprecation = defaults[i]; + + Object.defineProperty(core[deprecation.parent], 'DEFAULT', { + enumerable: true, + get: function get() { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, please use PIXI.settings.' + deprecation.target); + + return core.settings[deprecation.target]; + }, + set: function set(value) { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, please use PIXI.settings.' + deprecation.target); + + core.settings[deprecation.target] = value; + } + }); +}; + +for (var i = 0; i < defaults.length; i++) { + _loop(i); +} + +Object.defineProperties(core.settings, { + + /** + * @static + * @name PRECISION + * @memberof PIXI.settings + * @see PIXI.PRECISION + * @deprecated since version 4.4.0 + */ + PRECISION: { + enumerable: true, + get: function get() { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + return core.settings.PRECISION_FRAGMENT; + }, + set: function set(value) { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + core.settings.PRECISION_FRAGMENT = value; + } + } +}); + +Object.defineProperties(extras, { + + /** + * @class + * @name MovieClip + * @memberof PIXI.extras + * @see PIXI.extras.AnimatedSprite + * @deprecated since version 4.2.0 + */ + MovieClip: { + enumerable: true, + get: function get() { + warn('The MovieClip class has been renamed to AnimatedSprite, please use AnimatedSprite from now on.'); + + return extras.AnimatedSprite; + } + } +}); + +core.DisplayObject.prototype.generateTexture = function generateTexture(renderer, scaleMode, resolution) { + warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); + + return renderer.generateTexture(this, scaleMode, resolution); +}; + +core.Graphics.prototype.generateTexture = function generateTexture(scaleMode, resolution) { + warn('graphics generate texture has moved to the renderer. ' + 'Or to render a graphics to a texture using canvas please use generateCanvasTexture'); + + return this.generateCanvasTexture(scaleMode, resolution); +}; + +core.RenderTexture.prototype.render = function render(displayObject, matrix, clear, updateTransform) { + this.legacyRenderer.render(displayObject, this, clear, matrix, !updateTransform); + warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)'); +}; + +core.RenderTexture.prototype.getImage = function getImage(target) { + warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); + + return this.legacyRenderer.extract.image(target); +}; + +core.RenderTexture.prototype.getBase64 = function getBase64(target) { + warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); + + return this.legacyRenderer.extract.base64(target); +}; + +core.RenderTexture.prototype.getCanvas = function getCanvas(target) { + warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); + + return this.legacyRenderer.extract.canvas(target); +}; + +core.RenderTexture.prototype.getPixels = function getPixels(target) { + warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); + + return this.legacyRenderer.pixels(target); +}; + +/** + * @method + * @private + * @name PIXI.Sprite#setTexture + * @see PIXI.Sprite#texture + * @deprecated since version 3.0.0 + * @param {PIXI.Texture} texture - The texture to set to. + */ +core.Sprite.prototype.setTexture = function setTexture(texture) { + this.texture = texture; + warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;'); +}; + +/** + * @method + * @name PIXI.extras.BitmapText#setText + * @see PIXI.extras.BitmapText#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ +extras.BitmapText.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';'); +}; + +/** + * @method + * @name PIXI.Text#setText + * @see PIXI.Text#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ +core.Text.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';'); +}; + +/** + * @method + * @name PIXI.Text#setStyle + * @see PIXI.Text#style + * @deprecated since version 3.0.0 + * @param {*} style - The style to set to. + */ +core.Text.prototype.setStyle = function setStyle(style) { + this.style = style; + warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;'); +}; + +/** + * @method + * @name PIXI.Text#determineFontProperties + * @see PIXI.Text#calculateFontProperties + * @deprecated since version 4.2.0 + * @private + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ +core.Text.prototype.determineFontProperties = function determineFontProperties(fontStyle) { + warn('determineFontProperties is now deprecated, please use the static calculateFontProperties method, ' + 'e.g : Text.calculateFontProperties(fontStyle);'); + + return core.Text.calculateFontProperties(fontStyle); +}; + +Object.defineProperties(core.TextStyle.prototype, { + /** + * Set all properties of a font as a single string + * + * @name PIXI.TextStyle#font + * @deprecated since version 4.0.0 + */ + font: { + get: function get() { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\', \'fontSize\', \'fontStyle\', \'fontVariant\' and \'fontWeight\' properties from now on'); + + var fontSizeString = typeof this._fontSize === 'number' ? this._fontSize + 'px' : this._fontSize; + + return this._fontStyle + ' ' + this._fontVariant + ' ' + this._fontWeight + ' ' + fontSizeString + ' ' + this._fontFamily; + }, + set: function set(font) { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + + // can work out fontStyle from search of whole string + if (font.indexOf('italic') > 1) { + this._fontStyle = 'italic'; + } else if (font.indexOf('oblique') > -1) { + this._fontStyle = 'oblique'; + } else { + this._fontStyle = 'normal'; + } + + // can work out fontVariant from search of whole string + if (font.indexOf('small-caps') > -1) { + this._fontVariant = 'small-caps'; + } else { + this._fontVariant = 'normal'; + } + + // fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units + var splits = font.split(' '); + var fontSizeIndex = -1; + + this._fontSize = 26; + for (var i = 0; i < splits.length; ++i) { + if (splits[i].match(/(px|pt|em|%)/)) { + fontSizeIndex = i; + this._fontSize = splits[i]; + break; + } + } + + // we can now search for fontWeight as we know it must occur before the fontSize + this._fontWeight = 'normal'; + for (var _i = 0; _i < fontSizeIndex; ++_i) { + if (splits[_i].match(/(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/)) { + this._fontWeight = splits[_i]; + break; + } + } + + // and finally join everything together after the fontSize in case the font family has multiple words + if (fontSizeIndex > -1 && fontSizeIndex < splits.length - 1) { + this._fontFamily = ''; + for (var _i2 = fontSizeIndex + 1; _i2 < splits.length; ++_i2) { + this._fontFamily += splits[_i2] + ' '; + } + + this._fontFamily = this._fontFamily.slice(0, -1); + } else { + this._fontFamily = 'Arial'; + } + + this.styleID++; + } + } +}); + +/** + * @method + * @name PIXI.Texture#setFrame + * @see PIXI.Texture#setFrame + * @deprecated since version 3.0.0 + * @param {PIXI.Rectangle} frame - The frame to set. + */ +core.Texture.prototype.setFrame = function setFrame(frame) { + this.frame = frame; + warn('setFrame is now deprecated, please use the frame property, e.g: myTexture.frame = frame;'); +}; + +Object.defineProperties(filters, { + + /** + * @class + * @private + * @name PIXI.filters.AbstractFilter + * @see PIXI.AbstractFilter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.AbstractFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.SpriteMaskFilter + * @see PIXI.SpriteMaskFilter + * @deprecated since version 3.0.6 + */ + SpriteMaskFilter: { + get: function get() { + warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.'); + + return core.SpriteMaskFilter; + } + } +}); + +/** + * @method + * @name PIXI.utils.uuid + * @see PIXI.utils.uid + * @deprecated since version 3.0.6 + * @return {number} The uid + */ +core.utils.uuid = function () { + warn('utils.uuid() is deprecated, please use utils.uid() from now on.'); + + return core.utils.uid(); +}; + +/** + * @method + * @name PIXI.utils.canUseNewCanvasBlendModes + * @see PIXI.CanvasTinter + * @deprecated + * @return {boolean} Can use blend modes. + */ +core.utils.canUseNewCanvasBlendModes = function () { + warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on'); + + return core.CanvasTinter.canUseMultiply; +}; + +var saidHello = true; + +/** + * @name PIXI.utils._saidHello + * @type {boolean} + * @see PIXI.utils.skipHello + * @deprecated since 4.1.0 + */ +Object.defineProperty(core.utils, '_saidHello', { + set: function set(bool) { + if (bool) { + warn('PIXI.utils._saidHello is deprecated, please use PIXI.utils.skipHello()'); + this.skipHello(); + } + saidHello = bool; + }, + get: function get() { + return saidHello; + } +}); + +/** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.canvas.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ +Object.defineProperty(prepare.canvas, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } +}); + +/** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.webgl.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ +Object.defineProperty(prepare.webgl, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } +}); + +Object.defineProperties(loaders.Resource.prototype, { + isJson: { + get: function get() { + warn('The isJson property is deprecated, please use `resource.type === Resource.TYPE.JSON`.'); + + return this.type === loaders.Loader.Resource.TYPE.JSON; + } + }, + isXml: { + get: function get() { + warn('The isXml property is deprecated, please use `resource.type === Resource.TYPE.XML`.'); + + return this.type === loaders.Loader.Resource.TYPE.XML; + } + }, + isImage: { + get: function get() { + warn('The isImage property is deprecated, please use `resource.type === Resource.TYPE.IMAGE`.'); + + return this.type === loaders.Loader.Resource.TYPE.IMAGE; + } + }, + isAudio: { + get: function get() { + warn('The isAudio property is deprecated, please use `resource.type === Resource.TYPE.AUDIO`.'); + + return this.type === loaders.Loader.Resource.TYPE.AUDIO; + } + }, + isVideo: { + get: function get() { + warn('The isVideo property is deprecated, please use `resource.type === Resource.TYPE.VIDEO`.'); + + return this.type === loaders.Loader.Resource.TYPE.VIDEO; + } + } +}); + +Object.defineProperties(loaders.Loader.prototype, { + before: { + get: function get() { + warn('The before() method is deprecated, please use pre().'); + + return this.pre; + } + }, + after: { + get: function get() { + warn('The after() method is deprecated, please use use().'); + + return this.use; + } + } +}); + +/** + * @name PIXI.interaction.interactiveTarget#defaultCursor + * @static + * @type {number} + * @see PIXI.interaction.interactiveTarget#cursor + * @deprecated since 4.3.0 + */ +Object.defineProperty(interaction.interactiveTarget, 'defaultCursor', { + set: function set(value) { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + this.cursor = value; + }, + get: function get() { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + + return this.cursor; + }, + + enumerable: true +}); + +/** + * @name PIXI.interaction.InteractionManager#defaultCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ +Object.defineProperty(interaction.InteractionManager, 'defaultCursorStyle', { + set: function set(value) { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + this.cursorStyles.default = value; + }, + get: function get() { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + + return this.cursorStyles.default; + } +}); + +/** + * @name PIXI.interaction.InteractionManager#currentCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ +Object.defineProperty(interaction.InteractionManager, 'currentCursorStyle', { + set: function set(value) { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + this.currentCursorMode = value; + }, + get: function get() { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + + return this.currentCursorMode; + } +}); + +},{"./core":63,"./extras":136,"./filters":147,"./interaction":154,"./loaders":157,"./mesh":166,"./particles":169,"./prepare":179}],126:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI + */ + +var CanvasExtract = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasExtract(renderer) { + _classCallCheck(this, CanvasExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.CanvasExtract} extract + * @memberof PIXI.CanvasRenderer# + * @see PIXI.CanvasExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + CanvasExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `CanvasExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + CanvasExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + CanvasExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = this.renderer.width; + frame.height = this.renderer.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + CanvasExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + + return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; + }; + + /** + * Destroys the extract + * + */ + + + CanvasExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return CanvasExtract; +}(); + +exports.default = CanvasExtract; + + +core.CanvasRenderer.registerPlugin('extract', CanvasExtract); + +},{"../../core":63}],127:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLExtract = require('./webgl/WebGLExtract'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLExtract).default; + } +}); + +var _CanvasExtract = require('./canvas/CanvasExtract'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasExtract).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./canvas/CanvasExtract":126,"./webgl/WebGLExtract":128}],128:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); +var BYTES_PER_PIXEL = 4; + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI + */ + +var WebGLExtract = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLExtract(renderer) { + _classCallCheck(this, WebGLExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.WebGLExtract} extract + * @memberof PIXI.WebGLRenderer# + * @see PIXI.WebGLExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + WebGLExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `WebGLExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + WebGLExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + WebGLExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var flipY = false; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + flipY = false; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + flipY = true; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + + // set up an array of pixels + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + + canvasData.data.set(webglPixels); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // pulling pixels + if (flipY) { + canvasBuffer.context.scale(1, -1); + canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); + } + } + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + WebGLExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + } + + return webglPixels; + }; + + /** + * Destroys the extract + * + */ + + + WebGLExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return WebGLExtract; +}(); + +exports.default = WebGLExtract; + + +core.WebGLRenderer.registerPlugin('extract', WebGLExtract); + +},{"../../core":63}],129:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @typedef FrameObject + * @type {object} + * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame + * @property {number} time - the duration of the frame in ms + */ + +/** + * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. + * + * ```js + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; + * + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.fromImage(alienImages[i]); + * textureArray.push(texture); + * }; + * + * let mc = new PIXI.AnimatedSprite(textureArray); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ +var AnimatedSprite = function (_core$Sprite) { + _inherits(AnimatedSprite, _core$Sprite); + + /** + * @param {PIXI.Texture[]|FrameObject[]} textures - an array of {@link PIXI.Texture} or frame + * objects that make up the animation + * @param {boolean} [autoUpdate=true] - Whether use PIXI.ticker.shared to auto update animation time. + */ + function AnimatedSprite(textures, autoUpdate) { + _classCallCheck(this, AnimatedSprite); + + /** + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture)); + + _this._textures = null; + + /** + * @private + */ + _this._durations = null; + + _this.textures = textures; + + /** + * `true` uses PIXI.ticker.shared to auto update animation time. + * @type {boolean} + * @default true + * @private + */ + _this._autoUpdate = autoUpdate !== false; + + /** + * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower + * + * @member {number} + * @default 1 + */ + _this.animationSpeed = 1; + + /** + * Whether or not the animate sprite repeats after playing. + * + * @member {boolean} + * @default true + */ + _this.loop = true; + + /** + * Function to call when a AnimatedSprite finishes playing + * + * @member {Function} + */ + _this.onComplete = null; + + /** + * Function to call when a AnimatedSprite changes which texture is being rendered + * + * @member {Function} + */ + _this.onFrameChange = null; + + /** + * Elapsed time since animation has been started, used internally to display current texture + * + * @member {number} + * @private + */ + _this._currentTime = 0; + + /** + * Indicates if the AnimatedSprite is currently playing + * + * @member {boolean} + * @readonly + */ + _this.playing = false; + return _this; + } + + /** + * Stops the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.stop = function stop() { + if (!this.playing) { + return; + } + + this.playing = false; + if (this._autoUpdate) { + core.ticker.shared.remove(this.update, this); + } + }; + + /** + * Plays the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.play = function play() { + if (this.playing) { + return; + } + + this.playing = true; + if (this._autoUpdate) { + core.ticker.shared.add(this.update, this); + } + }; + + /** + * Stops the AnimatedSprite and goes to a specific frame + * + * @param {number} frameNumber - frame index to stop at + */ + + + AnimatedSprite.prototype.gotoAndStop = function gotoAndStop(frameNumber) { + this.stop(); + + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + + /** + * Goes to a specific frame and begins playing the AnimatedSprite + * + * @param {number} frameNumber - frame index to start at + */ + + + AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay(frameNumber) { + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + + this.play(); + }; + + /** + * Updates the object transform for rendering. + * + * @private + * @param {number} deltaTime - Time since last tick. + */ + + + AnimatedSprite.prototype.update = function update(deltaTime) { + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + + lag += elapsed / 60 * 1000; + + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + + var sign = Math.sign(this.animationSpeed * deltaTime); + + this._currentTime = Math.floor(this._currentTime); + + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + + this._currentTime += lag / this._durations[this.currentFrame]; + } else { + this._currentTime += elapsed; + } + + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + + if (this.onComplete) { + this.onComplete(); + } + } else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + + if (this.onComplete) { + this.onComplete(); + } + } else if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + + /** + * Updates the displayed texture to match the current frame index + * + * @private + */ + + + AnimatedSprite.prototype.updateTexture = function updateTexture() { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + }; + + /** + * Stops the AnimatedSprite and destroys it + * + */ + + + AnimatedSprite.prototype.destroy = function destroy() { + this.stop(); + _core$Sprite.prototype.destroy.call(this); + }; + + /** + * A short hand way of creating a movieclip from an array of frame ids + * + * @static + * @param {string[]} frames - The array of frames ids the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animated sprite with the specified frames. + */ + + + AnimatedSprite.fromFrames = function fromFrames(frames) { + var textures = []; + + for (var i = 0; i < frames.length; ++i) { + textures.push(core.Texture.fromFrame(frames[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * A short hand way of creating a movieclip from an array of image ids + * + * @static + * @param {string[]} images - the array of image urls the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animate sprite with the specified images as frames. + */ + + + AnimatedSprite.fromImages = function fromImages(images) { + var textures = []; + + for (var i = 0; i < images.length; ++i) { + textures.push(core.Texture.fromImage(images[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * totalFrames is the total number of frames in the AnimatedSprite. This is the same as number of textures + * assigned to the AnimatedSprite. + * + * @readonly + * @member {number} + * @default 0 + */ + + + _createClass(AnimatedSprite, [{ + key: 'totalFrames', + get: function get() { + return this._textures.length; + } + + /** + * The array of textures used for this AnimatedSprite + * + * @member {PIXI.Texture[]} + */ + + }, { + key: 'textures', + get: function get() { + return this._textures; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value[0] instanceof core.Texture) { + this._textures = value; + this._durations = null; + } else { + this._textures = []; + this._durations = []; + + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + } + + /** + * The AnimatedSprites current frame index + * + * @member {number} + * @readonly + */ + + }, { + key: 'currentFrame', + get: function get() { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + + return currentFrame; + } + }]); + + return AnimatedSprite; +}(core.Sprite); + +exports.default = AnimatedSprite; + +},{"../core":63}],130:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ObservablePoint = require('../core/math/ObservablePoint'); + +var _ObservablePoint2 = _interopRequireDefault(_ObservablePoint); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BitmapText object will create a line or multiple lines of text using bitmap font. To + * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using: + * + * A BitmapText can only be created when the font is loaded + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); + * ``` + * + * http://www.angelcode.com/products/bmfont/ for windows or + * http://www.bmglyph.com/ for mac. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.extras + */ +var BitmapText = function (_core$Container) { + _inherits(BitmapText, _core$Container); + + /** + * @param {string} text - The copy that you would like the text to display + * @param {object} style - The style parameters + * @param {string|object} style.font - The font descriptor for the object, can be passed as a string of form + * "24px FontName" or "FontName" or as an object with explicit name/size properties. + * @param {string} [style.font.name] - The bitmap font id + * @param {number} [style.font.size] - The size of the font in pixels, e.g. 24 + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), does not affect + * single line text + * @param {number} [style.tint=0xFFFFFF] - The tint color + */ + function BitmapText(text) { + var style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _classCallCheck(this, BitmapText); + + /** + * Private tracker for the width of the overall text + * + * @member {number} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._textWidth = 0; + + /** + * Private tracker for the height of the overall text + * + * @member {number} + * @private + */ + _this._textHeight = 0; + + /** + * Private tracker for the letter sprite pool. + * + * @member {PIXI.Sprite[]} + * @private + */ + _this._glyphs = []; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._font = { + tint: style.tint !== undefined ? style.tint : 0xFFFFFF, + align: style.align || 'left', + name: null, + size: 0 + }; + + /** + * Private tracker for the current font. + * + * @member {object} + * @private + */ + _this.font = style.font; // run font setter + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = text; + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + */ + _this.maxWidth = 0; + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + */ + _this.maxLineHeight = 0; + + /** + * Text anchor. read-only + * + * @member {PIXI.ObservablePoint} + * @private + */ + _this._anchor = new _ObservablePoint2.default(function () { + _this.dirty = true; + }, _this, 0, 0); + + /** + * The dirty state of this object. + * + * @member {boolean} + */ + _this.dirty = false; + + _this.updateText(); + return _this; + } + + /** + * Renders text and updates it when needed + * + * @private + */ + + + BitmapText.prototype.updateText = function updateText() { + var data = BitmapText.fonts[this._font.name]; + var scale = this._font.size / data.size; + var pos = new core.Point(); + var chars = []; + var lineWidths = []; + + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastSpace = -1; + var lastSpaceWidth = 0; + var maxLineHeight = 0; + + for (var i = 0; i < this.text.length; i++) { + var charCode = this.text.charCodeAt(i); + + if (/(\s)/.test(this.text.charAt(i))) { + lastSpace = i; + lastSpaceWidth = lastLineWidth; + } + + if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) { + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + if (lastSpace !== -1 && this.maxWidth > 0 && pos.x * scale > this.maxWidth) { + core.utils.removeItems(chars, lastSpace, i - lastSpace); + i = lastSpace; + lastSpace = -1; + + lineWidths.push(lastSpaceWidth); + maxLineWidth = Math.max(maxLineWidth, lastSpaceWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + var charData = data.chars[charCode]; + + if (!charData) { + continue; + } + + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + + chars.push({ + texture: charData.texture, + line: line, + charCode: charCode, + position: new core.Point(pos.x + charData.xOffset, pos.y + charData.yOffset) + }); + lastLineWidth = pos.x + (charData.texture.width + charData.xOffset); + pos.x += charData.xAdvance; + maxLineHeight = Math.max(maxLineHeight, charData.yOffset + charData.texture.height); + prevCharCode = charCode; + } + + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + + var lineAlignOffsets = []; + + for (var _i = 0; _i <= line; _i++) { + var alignOffset = 0; + + if (this._font.align === 'right') { + alignOffset = maxLineWidth - lineWidths[_i]; + } else if (this._font.align === 'center') { + alignOffset = (maxLineWidth - lineWidths[_i]) / 2; + } + + lineAlignOffsets.push(alignOffset); + } + + var lenChars = chars.length; + var tint = this.tint; + + for (var _i2 = 0; _i2 < lenChars; _i2++) { + var c = this._glyphs[_i2]; // get the next glyph sprite + + if (c) { + c.texture = chars[_i2].texture; + } else { + c = new core.Sprite(chars[_i2].texture); + this._glyphs.push(c); + } + + c.position.x = (chars[_i2].position.x + lineAlignOffsets[chars[_i2].line]) * scale; + c.position.y = chars[_i2].position.y * scale; + c.scale.x = c.scale.y = scale; + c.tint = tint; + + if (!c.parent) { + this.addChild(c); + } + } + + // remove unnecessary children. + for (var _i3 = lenChars; _i3 < this._glyphs.length; ++_i3) { + this.removeChild(this._glyphs[_i3]); + } + + this._textWidth = maxLineWidth * scale; + this._textHeight = (pos.y + data.lineHeight) * scale; + + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + for (var _i4 = 0; _i4 < lenChars; _i4++) { + this._glyphs[_i4].x -= this._textWidth * this.anchor.x; + this._glyphs[_i4].y -= this._textHeight * this.anchor.y; + } + } + this.maxLineHeight = maxLineHeight * scale; + }; + + /** + * Updates the transform of this object + * + * @private + */ + + + BitmapText.prototype.updateTransform = function updateTransform() { + this.validate(); + this.containerUpdateTransform(); + }; + + /** + * Validates text before calling parent's getLocalBounds + * + * @return {PIXI.Rectangle} The rectangular bounding area + */ + + + BitmapText.prototype.getLocalBounds = function getLocalBounds() { + this.validate(); + + return _core$Container.prototype.getLocalBounds.call(this); + }; + + /** + * Updates text when needed + * + * @private + */ + + + BitmapText.prototype.validate = function validate() { + if (this.dirty) { + this.updateText(); + this.dirty = false; + } + }; + + /** + * The tint of the BitmapText object + * + * @member {number} + */ + + + /** + * Register a bitmap font with data and a texture. + * + * @static + * @param {XMLDocument} xml - The XML document data. + * @param {PIXI.Texture} texture - Texture with all symbols. + * @return {Object} Result font object with font, size, lineHeight and char fields. + */ + BitmapText.registerFont = function registerFont(xml, texture) { + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10); + data.chars = {}; + + // parse letters + var letters = xml.getElementsByTagName('char'); + + for (var i = 0; i < letters.length; i++) { + var letter = letters[i]; + var charCode = parseInt(letter.getAttribute('id'), 10); + + var textureRect = new core.Rectangle(parseInt(letter.getAttribute('x'), 10) + texture.frame.x, parseInt(letter.getAttribute('y'), 10) + texture.frame.y, parseInt(letter.getAttribute('width'), 10), parseInt(letter.getAttribute('height'), 10)); + + data.chars[charCode] = { + xOffset: parseInt(letter.getAttribute('xoffset'), 10), + yOffset: parseInt(letter.getAttribute('yoffset'), 10), + xAdvance: parseInt(letter.getAttribute('xadvance'), 10), + kerning: {}, + texture: new core.Texture(texture.baseTexture, textureRect) + + }; + } + + // parse kernings + var kernings = xml.getElementsByTagName('kerning'); + + for (var _i5 = 0; _i5 < kernings.length; _i5++) { + var kerning = kernings[_i5]; + var first = parseInt(kerning.getAttribute('first'), 10); + var second = parseInt(kerning.getAttribute('second'), 10); + var amount = parseInt(kerning.getAttribute('amount'), 10); + + if (data.chars[second]) { + data.chars[second].kerning[first] = amount; + } + } + + // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 + // but it's very likely to change + BitmapText.fonts[data.font] = data; + + return data; + }; + + _createClass(BitmapText, [{ + key: 'tint', + get: function get() { + return this._font.tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.tint = typeof value === 'number' && value >= 0 ? value : 0xFFFFFF; + + this.dirty = true; + } + + /** + * The alignment of the BitmapText object + * + * @member {string} + * @default 'left' + */ + + }, { + key: 'align', + get: function get() { + return this._font.align; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.align = value || 'left'; + + this.dirty = true; + } + + /** + * The anchor sets the origin point of the text. + * The default is 0,0 this means the text's origin is the top left + * Setting the anchor to 0.5,0.5 means the text's origin is centered + * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner + * + * @member {PIXI.Point | number} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (typeof value === 'number') { + this._anchor.set(value); + } else { + this._anchor.copy(value); + } + } + + /** + * The font descriptor of the BitmapText object + * + * @member {string|object} + */ + + }, { + key: 'font', + get: function get() { + return this._font; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (!value) { + return; + } + + if (typeof value === 'string') { + value = value.split(' '); + + this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); + this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; + } else { + this._font.name = value.name; + this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); + } + + this.dirty = true; + } + + /** + * The text of the BitmapText object + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + value = value.toString() || ' '; + if (this._text === value) { + return; + } + this._text = value; + this.dirty = true; + } + + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textWidth', + get: function get() { + this.validate(); + + return this._textWidth; + } + + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textHeight', + get: function get() { + this.validate(); + + return this._textHeight; + } + }]); + + return BitmapText; +}(core.Container); + +exports.default = BitmapText; + + +BitmapText.fonts = {}; + +},{"../core":63,"../core/math/ObservablePoint":66}],131:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Matrix = require('../core/math/Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var tempMat = new _Matrix2.default(); + +/** + * class controls uv transform and frame clamp for texture + * + * @class + * @memberof PIXI.extras + */ + +var TextureTransform = function () { + /** + * + * @param {PIXI.Texture} texture observed texture + * @param {number} [clampMargin] Changes frame clamping, 0.5 by default. Use -0.5 for extra border. + * @constructor + */ + function TextureTransform(texture, clampMargin) { + _classCallCheck(this, TextureTransform); + + this._texture = texture; + + this.mapCoord = new _Matrix2.default(); + + this.uClampFrame = new Float32Array(4); + + this.uClampOffset = new Float32Array(2); + + this._lastTextureID = -1; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders + * + * @default 0 + * @member {number} + */ + this.clampOffset = 0; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + this.clampMargin = typeof clampMargin === 'undefined' ? 0.5 : clampMargin; + } + + /** + * texture property + * @member {PIXI.Texture} + */ + + + /** + * updates matrices if texture was changed + * @param {boolean} forceUpdate if true, matrices will be updated any case + */ + TextureTransform.prototype.update = function update(forceUpdate) { + var tex = this._texture; + + if (!tex || !tex.valid) { + return; + } + + if (!forceUpdate && this._lastTextureID === tex._updateID) { + return; + } + + this._lastTextureID = tex._updateID; + + var uvs = tex._uvs; + + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + + var orig = tex.orig; + var trim = tex.trim; + + if (trim) { + tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat); + } + + var texBase = tex.baseTexture; + var frame = this.uClampFrame; + var margin = this.clampMargin / texBase.resolution; + var offset = this.clampOffset; + + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.uClampOffset[0] = offset / texBase.realWidth; + this.uClampOffset[1] = offset / texBase.realHeight; + }; + + _createClass(TextureTransform, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._texture = value; + this._lastTextureID = -1; + } + }]); + + return TextureTransform; +}(); + +exports.default = TextureTransform; + +},{"../core/math/Matrix":65}],132:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CanvasTinter = require('../core/sprites/canvas/CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +var _TextureTransform = require('./TextureTransform'); + +var _TextureTransform2 = _interopRequireDefault(_TextureTransform); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); + +/** + * A tiling sprite is a fast way of rendering a tiling image + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ + +var TilingSprite = function (_core$Sprite) { + _inherits(TilingSprite, _core$Sprite); + + /** + * @param {PIXI.Texture} texture - the texture of the tiling sprite + * @param {number} [width=100] - the width of the tiling sprite + * @param {number} [height=100] - the height of the tiling sprite + */ + function TilingSprite(texture) { + var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100; + + _classCallCheck(this, TilingSprite); + + /** + * Tile transform + * + * @member {PIXI.TransformStatic} + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, texture)); + + _this.tileTransform = new core.TransformStatic(); + + // /// private + + /** + * The with of the tiling sprite + * + * @member {number} + * @private + */ + _this._width = width; + + /** + * The height of the tiling sprite + * + * @member {number} + * @private + */ + _this._height = height; + + /** + * Canvas pattern + * + * @type {CanvasPattern} + * @private + */ + _this._canvasPattern = null; + + /** + * transform that is applied to UV to get the texture coords + * + * @member {PIXI.extras.TextureTransform} + */ + _this.uvTransform = texture.transform || new _TextureTransform2.default(texture); + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' method. + * + * @member {string} + * @default 'tilingSprite' + */ + _this.pluginName = 'tilingSprite'; + + /** + * Whether or not anchor affects uvs + * + * @member {boolean} + * @default false + */ + _this.uvRespectAnchor = false; + return _this; + } + /** + * Changes frame clamping in corresponding textureTransform, shortcut + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + + + /** + * @private + */ + TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate() { + if (this.uvTransform) { + this.uvTransform.texture = this._texture; + } + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + TilingSprite.prototype._renderWebGL = function _renderWebGL(renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + + if (!texture || !texture.valid) { + return; + } + + this.tileTransform.updateLocalTransform(); + this.uvTransform.update(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer + */ + + + TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { + var texture = this._texture; + + if (!texture.baseTexture.hasLoaded) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var resolution = renderer.resolution; + var baseTexture = texture.baseTexture; + var baseTextureResolution = texture.baseTexture.resolution; + var modX = this.tilePosition.x / this.tileScale.x % texture._frame.width; + var modY = this.tilePosition.y / this.tileScale.y % texture._frame.height; + + // create a nice shiny pattern! + // TODO this needs to be refreshed if texture changes.. + if (!this._canvasPattern) { + // cut an object from a spritesheet.. + var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height, baseTextureResolution); + + // Tint the tiling sprite + if (this.tint !== 0xFFFFFF) { + if (this.cachedTint !== this.tint) { + this.cachedTint = this.tint; + + this.tintedTexture = _CanvasTinter2.default.getTintedTexture(this, this.tint); + } + tempCanvas.context.drawImage(this.tintedTexture, 0, 0); + } else { + tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x, -texture._frame.y); + } + this._canvasPattern = tempCanvas.context.createPattern(tempCanvas.canvas, 'repeat'); + } + + // set context state.. + context.globalAlpha = this.worldAlpha; + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + renderer.setBlendMode(this.blendMode); + + // fill the pattern! + context.fillStyle = this._canvasPattern; + + // TODO - this should be rolled into the setTransform above.. + context.scale(this.tileScale.x / baseTextureResolution, this.tileScale.y / baseTextureResolution); + + var anchorX = this.anchor.x * -this._width; + var anchorY = this.anchor.y * -this._height; + + if (this.uvRespectAnchor) { + context.translate(modX, modY); + + context.fillRect(-modX + anchorX, -modY + anchorY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } else { + context.translate(modX + anchorX, modY + anchorY); + + context.fillRect(-modX, -modY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } + }; + + /** + * Updates the bounds of the tiling sprite. + * + * @private + */ + + + TilingSprite.prototype._calculateBounds = function _calculateBounds() { + var minX = this._width * -this._anchor._x; + var minY = this._height * -this._anchor._y; + var maxX = this._width * (1 - this._anchor._x); + var maxY = this._height * (1 - this._anchor._y); + + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + TilingSprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._width * -this._anchor._x; + this._bounds.minY = this._height * -this._anchor._y; + this._bounds.maxX = this._width * (1 - this._anchor._x); + this._bounds.maxY = this._height * (1 - this._anchor._x); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new core.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _core$Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Checks if a point is inside this tiling sprite. + * + * @param {PIXI.Point} point - the point to check + * @return {boolean} Whether or not the sprite contains the point. + */ + + + TilingSprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor._x; + + if (tempPoint.x > x1 && tempPoint.x < x1 + width) { + var y1 = -height * this.anchor._y; + + if (tempPoint.y > y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this tiling sprite + * + */ + + + TilingSprite.prototype.destroy = function destroy() { + _core$Sprite.prototype.destroy.call(this); + + this.tileTransform = null; + this.uvTransform = null; + }; + + /** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.Texture} The newly created texture + */ + + + TilingSprite.from = function from(source, width, height) { + return new TilingSprite(core.Texture.from(source), width, height); + }; + + /** + * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId + */ + + + TilingSprite.fromFrame = function fromFrame(frameId, width, height) { + var texture = core.utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this); + } + + return new TilingSprite(texture, width, height); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @param {boolean} [crossorigin] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id + */ + + + TilingSprite.fromImage = function fromImage(imageId, width, height, crossorigin, scaleMode) { + return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode), width, height); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(TilingSprite, [{ + key: 'clampMargin', + get: function get() { + return this.uvTransform.clampMargin; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uvTransform.clampMargin = value; + this.uvTransform.update(true); + } + + /** + * The scaling of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tileScale', + get: function get() { + return this.tileTransform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.scale.copy(value); + } + + /** + * The offset of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tilePosition', + get: function get() { + return this.tileTransform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.position.copy(value); + } + }, { + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + } + + /** + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + } + }]); + + return TilingSprite; +}(core.Sprite); + +exports.default = TilingSprite; + +},{"../core":63,"../core/sprites/canvas/CanvasTinter":102,"./TextureTransform":131}],133:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DisplayObject = core.DisplayObject; +var _tempMatrix = new core.Matrix(); + +DisplayObject.prototype._cacheAsBitmap = false; +DisplayObject.prototype._cacheData = false; + +// figured theres no point adding ALL the extra variables to prototype. +// this model can hold the information needed. This can also be generated on demand as +// most objects are not cached as bitmaps. +/** + * @class + * @ignore + */ + +var CacheData = +/** + * + */ +function CacheData() { + _classCallCheck(this, CacheData); + + this.originalRenderWebGL = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + + this.originalUpdateTransform = null; + this.originalHitTest = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.sprite = null; +}; + +Object.defineProperties(DisplayObject.prototype, { + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to 'false' + * + * IMPORTANT GOTCHA - make sure that all your textures are preloaded BEFORE setting this property to true + * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function get() { + return this._cacheAsBitmap; + }, + set: function set(value) { + if (this._cacheAsBitmap === value) { + return; + } + + this._cacheAsBitmap = value; + + var data = void 0; + + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + + data = this._cacheData; + + data.originalRenderWebGL = this.renderWebGL; + data.originalRenderCanvas = this.renderCanvas; + + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this._calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + + data.originalDestroy = this.destroy; + + data.originalContainsPoint = this.containsPoint; + + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + + this.renderWebGL = this._renderCachedWebGL; + this.renderCanvas = this._renderCachedCanvas; + + this.destroy = this._cacheAsBitmapDestroy; + } else { + data = this._cacheData; + + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + + this.renderWebGL = data.originalRenderWebGL; + this.renderCanvas = data.originalRenderCanvas; + this._calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + + this.destroy = data.originalDestroy; + + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + } + } +}); + +/** + * Renders a cached version of the sprite with WebGL + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedWebGL = function _renderCachedWebGL(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObject(renderer); + + this._cacheData.sprite._transformID = -1; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderWebGL(renderer); +}; + +/** + * Prepares the WebGL renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + + this.alpha = 1; + + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.currentRenderer.flush(); + // this.filters= []; + + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds().clone(); + + // add some padding! + if (this._filters) { + var padding = this._filters[0].padding; + + bounds.pad(padding); + } + + // for now we cache the current renderTarget that the webGL renderer is currently using. + // this could be more elegent.. + var cachedRenderTarget = renderer._activeRenderTarget; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + var stack = renderer.filterManager.filterStack; + + // this renderTexture will be used to store the cached DisplayObject + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + // need to set // + var m = _tempMatrix; + + m.tx = -bounds.x; + m.ty = -bounds.y; + + // reset + this.transform.worldTransform.identity(); + + // set all properties to there original so we can render to a texture + this.renderWebGL = this._cacheData.originalRenderWebGL; + + renderer.render(this, renderTexture, true, m, true); + // now restore the state be setting the new properties + + renderer.bindRenderTarget(cachedRenderTarget); + + renderer.filterManager.filterStack = stack; + + this.renderWebGL = this._renderCachedWebGL; + this.updateTransform = this.displayObjectUpdateTransform; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + + // easy bounds.. + this._calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + + this._cacheData.sprite = cachedSprite; + + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + this.updateTransform(); + + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Renders a cached version of the sprite with canvas + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObjectCanvas(renderer); + + this._cacheData.sprite.worldAlpha = this.worldAlpha; + + this._cacheData.sprite.renderCanvas(renderer); +}; + +// TODO this can be the same as the webGL verison.. will need to do a little tweaking first though.. +/** + * Prepares the Canvas renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(); + + var cacheAlpha = this.alpha; + + this.alpha = 1; + + var cachedRenderTarget = renderer.context; + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + // need to set // + var m = _tempMatrix; + + this.transform.localTransform.copy(m); + m.invert(); + + m.tx -= bounds.x; + m.ty -= bounds.y; + + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + + // renderTexture.render(this, m, true); + renderer.render(this, renderTexture, true, m, false); + + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + + this.renderCanvas = this._renderCachedCanvas; + this._calculateBounds = this._calculateCachedBounds; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite._bounds = this._bounds; + cachedSprite.alpha = cacheAlpha; + + this.updateTransform(); + this.updateTransform = this.displayObjectUpdateTransform; + + this._cacheData.sprite = cachedSprite; + + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Calculates the bounds of the cached sprite + * + * @private + */ +DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._cacheData.sprite._calculateBounds(); +}; + +/** + * Gets the bounds of the cached sprite. + * + * @private + * @return {Rectangle} The local bounds. + */ +DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(); +}; + +/** + * Destroys the cached sprite. + * + * @private + */ +DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; +}; + +/** + * Destroys the cached object. + * + * @private + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * Used when destroying containers, see the Container.destroy method. + */ +DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { + this.cacheAsBitmap = false; + this.destroy(options); +}; + +},{"../core":63}],134:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * The instance name of the object. + * + * @memberof PIXI.DisplayObject# + * @member {string} + */ +core.DisplayObject.prototype.name = null; + +/** + * Returns the display object in the container + * + * @memberof PIXI.Container# + * @param {string} name - instance name + * @return {PIXI.DisplayObject} The child with the specified name. + */ +core.Container.prototype.getChildByName = function getChildByName(name) { + for (var i = 0; i < this.children.length; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + + return null; +}; + +},{"../core":63}],135:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. + * + * @memberof PIXI.DisplayObject# + * @param {Point} point - the point to write the global value to. If null a new point will be returned + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @return {Point} The updated point + */ +core.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition() { + var point = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new core.Point(); + var skipUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (this.parent) { + this.parent.toGlobal(this.position, point, skipUpdate); + } else { + point.x = this.position.x; + point.y = this.position.y; + } + + return point; +}; + +},{"../core":63}],136:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BitmapText = exports.TilingSpriteRenderer = exports.TilingSprite = exports.AnimatedSprite = exports.TextureTransform = undefined; + +var _TextureTransform = require('./TextureTransform'); + +Object.defineProperty(exports, 'TextureTransform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureTransform).default; + } +}); + +var _AnimatedSprite = require('./AnimatedSprite'); + +Object.defineProperty(exports, 'AnimatedSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AnimatedSprite).default; + } +}); + +var _TilingSprite = require('./TilingSprite'); + +Object.defineProperty(exports, 'TilingSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSprite).default; + } +}); + +var _TilingSpriteRenderer = require('./webgl/TilingSpriteRenderer'); + +Object.defineProperty(exports, 'TilingSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSpriteRenderer).default; + } +}); + +var _BitmapText = require('./BitmapText'); + +Object.defineProperty(exports, 'BitmapText', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BitmapText).default; + } +}); + +require('./cacheAsBitmap'); + +require('./getChildByName'); + +require('./getGlobalPosition'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// imported for side effect of extending the prototype only, contains no exports + +},{"./AnimatedSprite":129,"./BitmapText":130,"./TextureTransform":131,"./TilingSprite":132,"./cacheAsBitmap":133,"./getChildByName":134,"./getGlobalPosition":135,"./webgl/TilingSpriteRenderer":137}],137:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _const = require('../../core/const'); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMat = new core.Matrix(); +var tempArray = new Float32Array(4); + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var TilingSpriteRenderer = function (_core$ObjectRenderer) { + _inherits(TilingSpriteRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function TilingSpriteRenderer(renderer) { + _classCallCheck(this, TilingSpriteRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + _this.simpleShader = null; + _this.quad = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + TilingSpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n gl_FragColor = sample * color ;\n}\n'); + this.simpleShader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n gl_FragColor = sample * color;\n}\n'); + + this.renderer.bindVao(null); + this.quad = new core.Quad(gl, this.renderer.state.attribState); + this.quad.initVao(this.shader); + }; + + /** + * + * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered + */ + + + TilingSpriteRenderer.prototype.render = function render(ts) { + var renderer = this.renderer; + var quad = this.quad; + + renderer.bindVao(quad.vao); + + var vertices = quad.vertices; + + vertices[0] = vertices[6] = ts._width * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + + vertices[2] = vertices[4] = ts._width * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + + if (ts.uvRespectAnchor) { + vertices = quad.uvs; + + vertices[0] = vertices[6] = -ts.anchor.x; + vertices[1] = vertices[3] = -ts.anchor.y; + + vertices[2] = vertices[4] = 1.0 - ts.anchor.x; + vertices[5] = vertices[7] = 1.0 - ts.anchor.y; + } + + quad.upload(); + + var tex = ts._texture; + var baseTex = tex.baseTexture; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvTransform; + var isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === _const.WRAP_MODES.CLAMP) { + baseTex.wrapMode = _const.WRAP_MODES.REPEAT; + } + } else { + isSimple = baseTex.wrapMode !== _const.WRAP_MODES.CLAMP; + } + } + + var shader = isSimple ? this.simpleShader : this.shader; + + renderer.bindShader(shader); + + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + + tempMat.invert(); + if (isSimple) { + tempMat.append(uv.mapCoord); + } else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + + shader.uniforms.uTransform = tempMat.toArray(true); + + var color = tempArray; + + core.utils.hex2rgb(ts.tint, color); + color[3] = ts.worldAlpha; + shader.uniforms.uColor = color; + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + + shader.uniforms.uSampler = renderer.bindTexture(tex); + + renderer.setBlendMode(ts.blendMode); + + quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + }; + + return TilingSpriteRenderer; +}(core.ObjectRenderer); + +exports.default = TilingSpriteRenderer; + + +core.WebGLRenderer.registerPlugin('tilingSprite', TilingSpriteRenderer); + +},{"../../core":63,"../../core/const":44,"path":22}],138:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BlurXFilter = require('./BlurXFilter'); + +var _BlurXFilter2 = _interopRequireDefault(_BlurXFilter); + +var _BlurYFilter = require('./BlurYFilter'); + +var _BlurYFilter2 = _interopRequireDefault(_BlurYFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurFilter applies a Gaussian blur to an object. + * The strength of the blur can be set for x- and y-axis separately. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurFilter = function (_core$Filter) { + _inherits(BlurFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this)); + + _this.blurXFilter = new _BlurXFilter2.default(strength, quality, resolution, kernelSize); + _this.blurYFilter = new _BlurYFilter2.default(strength, quality, resolution, kernelSize); + + _this.padding = 0; + _this.resolution = resolution || core.settings.RESOLUTION; + _this.quality = quality || 4; + _this.blur = strength || 8; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + BlurFilter.prototype.apply = function apply(filterManager, input, output) { + var renderTarget = filterManager.getRenderTarget(true); + + this.blurXFilter.apply(filterManager, input, renderTarget, true); + this.blurYFilter.apply(filterManager, renderTarget, output, false); + + filterManager.returnRenderTarget(renderTarget); + }; + + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurFilter, [{ + key: 'blur', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the number of passes for blur. More passes means higher quaility bluring. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'quality', + get: function get() { + return this.blurXFilter.quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.quality = this.blurYFilter.quality = value; + } + + /** + * Sets the strength of the blurX property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurX', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the strength of the blurY property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurY', + get: function get() { + return this.blurYFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + }]); + + return BlurFilter; +}(core.Filter); + +exports.default = BlurFilter; + +},{"../../core":63,"./BlurXFilter":139,"./BlurYFilter":140}],139:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurXFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurXFilter = function (_core$Filter) { + _inherits(BlurXFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurXFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurXFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurXFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.width * (output.size.width / input.size.width); + + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; // / this.passes//Math.pow(1, this.passes); + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 16 + */ + + + _createClass(BlurXFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurXFilter; +}(core.Filter); + +exports.default = BlurXFilter; + +},{"../../core":63,"./generateBlurFragSource":141,"./generateBlurVertSource":142,"./getMaxBlurKernelSize":143}],140:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurYFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurYFilter = function (_core$Filter) { + _inherits(BlurYFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurYFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurYFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurYFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.height * (output.size.height / input.size.height); + + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurYFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurYFilter; +}(core.Filter); + +exports.default = BlurYFilter; + +},{"../../core":63,"./generateBlurFragSource":141,"./generateBlurVertSource":142,"./getMaxBlurKernelSize":143}],141:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateFragBlurSource; +var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] +}; + +var fragTemplate = ['varying vec2 vBlurTexCoords[%size%];', 'uniform sampler2D uSampler;', 'void main(void)', '{', ' gl_FragColor = vec4(0.0);', ' %blur%', '}'].join('\n'); + +function generateFragBlurSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + + var fragSource = fragTemplate; + + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value = void 0; + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + value = i; + + if (i >= halfLength) { + value = kernelSize - i - 1; + } + + blur = blur.replace('%value%', kernel[value]); + + blurLoop += blur; + blurLoop += '\n'; + } + + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize); + + return fragSource; +} + +},{}],142:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateVertBlurSource; +var vertTemplate = ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform float strength;', 'uniform mat3 projectionMatrix;', 'varying vec2 vBlurTexCoords[%size%];', 'void main(void)', '{', 'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);', '%blur%', '}'].join('\n'); + +function generateVertBlurSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + + var vertSource = vertTemplate; + + var blurLoop = ''; + var template = void 0; + // let value; + + if (x) { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } else { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + // value = i; + + // if(i >= halfLength) + // { + // value = kernelSize - i - 1; + // } + + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + '.0'); + + blurLoop += blur; + blurLoop += '\n'; + } + + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize); + + return vertSource; +} + +},{}],143:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = getMaxKernelSize; +function getMaxKernelSize(gl) { + var maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + var kernelSize = 15; + + while (kernelSize > maxVaryings) { + kernelSize -= 2; + } + + return kernelSize; +} + +},{}],144:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var ColorMatrixFilter = function (_core$Filter) { + _inherits(ColorMatrixFilter, _core$Filter); + + /** + * + */ + function ColorMatrixFilter() { + _classCallCheck(this, ColorMatrixFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n vec4 result;\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n // Premultiply alpha again.\n result.rgb *= result.a;\n\n gl_FragColor = result;\n}\n')); + + _this.uniforms.m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + return _this; + } + + /** + * Transforms current matrix and set the new one + * + * @param {number[]} matrix - 5x4 matrix + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix(matrix) { + var multiply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + var newMatrix = matrix; + + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + + // set the new matrix + this.uniforms.m = newMatrix; + }; + + /** + * Multiplies two mat5's + * + * @private + * @param {number[]} out - 5x4 matrix the receiving matrix + * @param {number[]} a - 5x4 matrix the first operand + * @param {number[]} b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix + */ + + + ColorMatrixFilter.prototype._multiply = function _multiply(out, a, b) { + // Red Channel + out[0] = a[0] * b[0] + a[1] * b[5] + a[2] * b[10] + a[3] * b[15]; + out[1] = a[0] * b[1] + a[1] * b[6] + a[2] * b[11] + a[3] * b[16]; + out[2] = a[0] * b[2] + a[1] * b[7] + a[2] * b[12] + a[3] * b[17]; + out[3] = a[0] * b[3] + a[1] * b[8] + a[2] * b[13] + a[3] * b[18]; + out[4] = a[0] * b[4] + a[1] * b[9] + a[2] * b[14] + a[3] * b[19] + a[4]; + + // Green Channel + out[5] = a[5] * b[0] + a[6] * b[5] + a[7] * b[10] + a[8] * b[15]; + out[6] = a[5] * b[1] + a[6] * b[6] + a[7] * b[11] + a[8] * b[16]; + out[7] = a[5] * b[2] + a[6] * b[7] + a[7] * b[12] + a[8] * b[17]; + out[8] = a[5] * b[3] + a[6] * b[8] + a[7] * b[13] + a[8] * b[18]; + out[9] = a[5] * b[4] + a[6] * b[9] + a[7] * b[14] + a[8] * b[19] + a[9]; + + // Blue Channel + out[10] = a[10] * b[0] + a[11] * b[5] + a[12] * b[10] + a[13] * b[15]; + out[11] = a[10] * b[1] + a[11] * b[6] + a[12] * b[11] + a[13] * b[16]; + out[12] = a[10] * b[2] + a[11] * b[7] + a[12] * b[12] + a[13] * b[17]; + out[13] = a[10] * b[3] + a[11] * b[8] + a[12] * b[13] + a[13] * b[18]; + out[14] = a[10] * b[4] + a[11] * b[9] + a[12] * b[14] + a[13] * b[19] + a[14]; + + // Alpha Channel + out[15] = a[15] * b[0] + a[16] * b[5] + a[17] * b[10] + a[18] * b[15]; + out[16] = a[15] * b[1] + a[16] * b[6] + a[17] * b[11] + a[18] * b[16]; + out[17] = a[15] * b[2] + a[16] * b[7] + a[17] * b[12] + a[18] * b[17]; + out[18] = a[15] * b[3] + a[16] * b[8] + a[17] * b[13] + a[18] * b[18]; + out[19] = a[15] * b[4] + a[16] * b[9] + a[17] * b[14] + a[18] * b[19] + a[19]; + + return out; + }; + + /** + * Create a Float32 Array and normalize the offset component to 0-1 + * + * @private + * @param {number[]} matrix - 5x4 matrix + * @return {number[]} 5x4 matrix with all values between 0-1 + */ + + + ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix(matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + + return m; + }; + + /** + * Adjusts brightness + * + * @param {number} b - value of the brigthness (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.brightness = function brightness(b, multiply) { + var matrix = [b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the matrices in grey scales + * + * @param {number} scale - value of the grey (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.greyscale = function greyscale(scale, multiply) { + var matrix = [scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the black and white matrice. + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite(multiply) { + var matrix = [0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the hue property of the color + * + * @param {number} rotation - in degrees + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.hue = function hue(rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + + var a00 = cosR + (1.0 - cosR) * w; + var a01 = w * (1.0 - cosR) - sqrW * sinR; + var a02 = w * (1.0 - cosR) + sqrW * sinR; + + var a10 = w * (1.0 - cosR) + sqrW * sinR; + var a11 = cosR + w * (1.0 - cosR); + var a12 = w * (1.0 - cosR) - sqrW * sinR; + + var a20 = w * (1.0 - cosR) - sqrW * sinR; + var a21 = w * (1.0 - cosR) + sqrW * sinR; + var a22 = cosR + w * (1.0 - cosR); + + var matrix = [a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * + * @param {number} amount - value of the contrast (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.contrast = function contrast(amount, multiply) { + var v = (amount || 0) + 1; + var o = -128 * (v - 1); + + var matrix = [v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * + * @param {number} amount - The saturation amount (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.saturate = function saturate() { + var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var multiply = arguments[1]; + + var x = amount * 2 / 3 + 1; + var y = (x - 1) * -0.5; + + var matrix = [x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Desaturate image (remove color) + * + * Call the saturate function + * + */ + + + ColorMatrixFilter.prototype.desaturate = function desaturate() // eslint-disable-line no-unused-vars + { + this.saturate(-1); + }; + + /** + * Negative image (inverse of classic rgb matrix) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.negative = function negative(multiply) { + var matrix = [0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Sepia image + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.sepia = function sepia(multiply) { + var matrix = [0.393, 0.7689999, 0.18899999, 0, 0, 0.349, 0.6859999, 0.16799999, 0, 0, 0.272, 0.5339999, 0.13099999, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.technicolor = function technicolor(multiply) { + var matrix = [1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Polaroid filter + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.polaroid = function polaroid(multiply) { + var matrix = [1.438, -0.062, -0.062, 0, 0, -0.122, 1.378, -0.122, 0, 0, -0.016, -0.016, 1.483, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Filter who transforms : Red -> Blue and Blue -> Red + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.toBGR = function toBGR(multiply) { + var matrix = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.kodachrome = function kodachrome(multiply) { + var matrix = [1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Brown delicious browni filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.browni = function browni(multiply) { + var matrix = [0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Vintage filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.vintage = function vintage(multiply) { + var matrix = [0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * + * @param {number} desaturation - Tone values. + * @param {number} toned - Tone values. + * @param {string} lightColor - Tone values, example: `0xFFE580` + * @param {string} darkColor - Tone values, example: `0xFFE580` + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.colorTone = function colorTone(desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + + var lR = (lightColor >> 16 & 0xFF) / 255; + var lG = (lightColor >> 8 & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + + var dR = (darkColor >> 16 & 0xFF) / 255; + var dG = (darkColor >> 8 & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + + var matrix = [0.3, 0.59, 0.11, 0, 0, lR, lG, lB, desaturation, 0, dR, dG, dB, toned, 0, lR - dR, lG - dG, lB - dB, 0, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Night effect + * + * @param {number} intensity - The intensity of the night effect. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.night = function night(intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [intensity * -2.0, -intensity, 0, 0, 0, -intensity, 0, intensity, 0, 0, 0, intensity, intensity * 2.0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * + * @param {number} amount - how much the predator feels his future victim + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.predator = function predator(amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * LSD effect + * + * Multiply the current matrix + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.lsd = function lsd(multiply) { + var matrix = [2, -0.4, 0.5, 0, 0, -0.5, 2, -0.4, 0, 0, -0.4, -0.5, 3, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Erase the current matrix by setting the default one + * + */ + + + ColorMatrixFilter.prototype.reset = function reset() { + var matrix = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, false); + }; + + /** + * The matrix of the color matrix filter + * + * @member {number[]} + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + + + _createClass(ColorMatrixFilter, [{ + key: 'matrix', + get: function get() { + return this.uniforms.m; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.m = value; + } + }]); + + return ColorMatrixFilter; +}(core.Filter); + +// Americanized alias + + +exports.default = ColorMatrixFilter; +ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + +},{"../../core":63,"path":22}],145:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. You can + * use this filter to apply all manor of crazy warping effects. Currently the r + * property of the texture is used to offset the x and the g property of the texture + * is used to offset the y. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var DisplacementFilter = function (_core$Filter) { + _inherits(DisplacementFilter, _core$Filter); + + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param {number} scale - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + _classCallCheck(this, DisplacementFilter); + + var maskMatrix = new core.Matrix(); + + sprite.renderable = false; + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n')); + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + + _this.uniforms.mapSampler = sprite.texture; + _this.uniforms.filterMatrix = maskMatrix; + _this.uniforms.scale = { x: 1, y: 1 }; + + if (scale === null || scale === undefined) { + scale = 20; + } + + _this.scale = new core.Point(scale, scale); + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + DisplacementFilter.prototype.apply = function apply(filterManager, input, output) { + var ratio = 1 / output.destinationFrame.width * (output.size.width / input.size.width); + + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x * ratio; + this.uniforms.scale.y = this.scale.y * ratio; + + // draw the filter... + filterManager.applyFilter(this, input, output); + }; + + /** + * The texture used for the displacement map. Must be power of 2 sized texture. + * + * @member {PIXI.Texture} + */ + + + _createClass(DisplacementFilter, [{ + key: 'map', + get: function get() { + return this.uniforms.mapSampler; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.mapSampler = value; + } + }]); + + return DisplacementFilter; +}(core.Filter); + +exports.default = DisplacementFilter; + +},{"../../core":63,"path":22}],146:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * Basic FXAA implementation based on the code on geeks3d.com with the + * modification that the texture2DLod stuff was removed since it's + * unsupported by WebGL. + * + * @see https://github.com/mitsuhiko/webgl-meincraft + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + * + */ +var FXAAFilter = function (_core$Filter) { + _inherits(FXAAFilter, _core$Filter); + + /** + * + */ + function FXAAFilter() { + _classCallCheck(this, FXAAFilter); + + // TODO - needs work + return _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + '\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}', + // fragment shader + 'varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n')); + } + + return FXAAFilter; +}(core.Filter); + +exports.default = FXAAFilter; + +},{"../../core":63,"path":22}],147:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _FXAAFilter = require('./fxaa/FXAAFilter'); + +Object.defineProperty(exports, 'FXAAFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_FXAAFilter).default; + } +}); + +var _NoiseFilter = require('./noise/NoiseFilter'); + +Object.defineProperty(exports, 'NoiseFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NoiseFilter).default; + } +}); + +var _DisplacementFilter = require('./displacement/DisplacementFilter'); + +Object.defineProperty(exports, 'DisplacementFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplacementFilter).default; + } +}); + +var _BlurFilter = require('./blur/BlurFilter'); + +Object.defineProperty(exports, 'BlurFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurFilter).default; + } +}); + +var _BlurXFilter = require('./blur/BlurXFilter'); + +Object.defineProperty(exports, 'BlurXFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurXFilter).default; + } +}); + +var _BlurYFilter = require('./blur/BlurYFilter'); + +Object.defineProperty(exports, 'BlurYFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurYFilter).default; + } +}); + +var _ColorMatrixFilter = require('./colormatrix/ColorMatrixFilter'); + +Object.defineProperty(exports, 'ColorMatrixFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ColorMatrixFilter).default; + } +}); + +var _VoidFilter = require('./void/VoidFilter'); + +Object.defineProperty(exports, 'VoidFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VoidFilter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./blur/BlurFilter":138,"./blur/BlurXFilter":139,"./blur/BlurYFilter":140,"./colormatrix/ColorMatrixFilter":144,"./displacement/DisplacementFilter":145,"./fxaa/FXAAFilter":146,"./noise/NoiseFilter":148,"./void/VoidFilter":149}],148:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Vico @vicocotea + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + */ + +/** + * A Noise effect filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var NoiseFilter = function (_core$Filter) { + _inherits(NoiseFilter, _core$Filter); + + /** + * + */ + function NoiseFilter() { + _classCallCheck(this, NoiseFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float noise;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n float diff = (rand(gl_FragCoord.xy) - 0.5) * noise;\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n gl_FragColor = color;\n}\n')); + + _this.noise = 0.5; + return _this; + } + + /** + * The amount of noise to apply. + * + * @member {number} + * @default 0.5 + */ + + + _createClass(NoiseFilter, [{ + key: 'noise', + get: function get() { + return this.uniforms.noise; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.noise = value; + } + }]); + + return NoiseFilter; +}(core.Filter); + +exports.default = NoiseFilter; + +},{"../../core":63,"path":22}],149:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Does nothing. Very handy. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var VoidFilter = function (_core$Filter) { + _inherits(VoidFilter, _core$Filter); + + /** + * + */ + function VoidFilter() { + _classCallCheck(this, VoidFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n')); + + _this.glShaderKey = 'void'; + return _this; + } + + return VoidFilter; +}(core.Filter); + +exports.default = VoidFilter; + +},{"../../core":63,"path":22}],150:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Holds all information related to an Interaction event + * + * @class + * @memberof PIXI.interaction + */ +var InteractionData = function () { + /** + * + */ + function InteractionData() { + _classCallCheck(this, InteractionData); + + /** + * This point stores the global coords of where the touch/mouse event happened + * + * @member {PIXI.Point} + */ + this.global = new core.Point(); + + /** + * The target DisplayObject that was interacted with + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * When passed to an event handler, this will be the original DOM Event that was captured + * + * @member {Event} + */ + this.originalEvent = null; + + /** + * Unique identifier for this interaction + * + * @member {number} + */ + this.identifier = null; + } + + /** + * This will return the local coordinates of the specified displayObject for this InteractionData + * + * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local + * coords off + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative + * to the DisplayObject + */ + + + InteractionData.prototype.getLocalPosition = function getLocalPosition(displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + + return InteractionData; +}(); + +exports.default = InteractionData; + +},{"../core":63}],151:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Event class that mimics native DOM events. + * + * @class + * @memberof PIXI.interaction + */ +var InteractionEvent = function () { + /** + * + */ + function InteractionEvent() { + _classCallCheck(this, InteractionEvent); + + /** + * Whether this event will continue propagating in the tree + * + * @member {boolean} + */ + this.stopped = false; + + /** + * The object which caused this event to be dispatched. + * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}. + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * The object whose event listener’s callback is currently being invoked. + * + * @member {PIXI.DisplayObject} + */ + this.currentTarget = null; + + /* + * Type of the event + * + * @member {string} + */ + this.type = null; + + /* + * InteractionData related to this event + * + * @member {PIXI.interaction.InteractionData} + */ + this.data = null; + } + + /** + * Prevents event from reaching any objects other than the current object. + * + */ + + + InteractionEvent.prototype.stopPropagation = function stopPropagation() { + this.stopped = true; + }; + + /** + * Resets the event. + * + * @private + */ + + + InteractionEvent.prototype._reset = function _reset() { + this.stopped = false; + this.currentTarget = null; + this.target = null; + }; + + return InteractionEvent; +}(); + +exports.default = InteractionEvent; + +},{}],152:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _InteractionData = require('./InteractionData'); + +var _InteractionData2 = _interopRequireDefault(_InteractionData); + +var _InteractionEvent = require('./InteractionEvent'); + +var _InteractionEvent2 = _interopRequireDefault(_InteractionEvent); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +var _InteractionTrackingData2 = _interopRequireDefault(_InteractionTrackingData); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _interactiveTarget = require('./interactiveTarget'); + +var _interactiveTarget2 = _interopRequireDefault(_interactiveTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// Mix interactiveTarget into core.DisplayObject.prototype, after deprecation has been handled +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _interactiveTarget2.default); + +var MOUSE_POINTER_ID = 'MOUSE'; + +/** + * The interaction manager deals with mouse, touch and pointer events. Any DisplayObject can be interactive + * if its interactive parameter is set to true + * This manager also supports multitouch. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.interaction + * + * @class + * @extends EventEmitter + * @memberof PIXI.interaction + */ + +var InteractionManager = function (_EventEmitter) { + _inherits(InteractionManager, _EventEmitter); + + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + * @param {object} [options] - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Frequency increases the interaction events will be checked. + */ + function InteractionManager(renderer, options) { + _classCallCheck(this, InteractionManager); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + options = options || {}; + + /** + * The renderer this interaction manager works for. + * + * @member {PIXI.SystemRenderer} + */ + _this.renderer = renderer; + + /** + * Should default browser actions automatically be prevented. + * Does not apply to pointer events for backwards compatibility + * preventDefault on pointer events stops mouse events from firing + * Thus, for every pointer event, there will always be either a mouse of touch event alongside it. + * + * @member {boolean} + * @default true + */ + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + + /** + * Frequency in milliseconds that the mousemove, moveover & mouseout interaction events will be checked. + * + * @member {number} + * @default 10 + */ + _this.interactionFrequency = options.interactionFrequency || 10; + + /** + * The mouse data + * + * @member {PIXI.interaction.InteractionData} + */ + _this.mouse = new _InteractionData2.default(); + _this.mouse.identifier = MOUSE_POINTER_ID; + + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + + /** + * Actively tracked InteractionData + * + * @private + * @member {Object.} + */ + _this.activeInteractionData = {}; + _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; + + /** + * Pool of unused InteractionData + * + * @private + * @member {PIXI.interation.InteractionData[]} + */ + _this.interactionDataPool = []; + + /** + * An event data object to handle all the event tracking/dispatching + * + * @member {object} + */ + _this.eventData = new _InteractionEvent2.default(); + + /** + * The DOM element to bind to. + * + * @private + * @member {HTMLElement} + */ + _this.interactionDOMElement = null; + + /** + * This property determines if mousemove and touchmove events are fired only when the cursor + * is over the object. + * Setting to true will make things work more in line with how the DOM verison works. + * Setting to false can make things easier for things like dragging + * It is currently set to false as this is how pixi used to work. This will be set to true in + * future versions of pixi. + * + * @member {boolean} + * @default false + */ + _this.moveWhenInside = false; + + /** + * Have events been attached to the dom element? + * + * @private + * @member {boolean} + */ + _this.eventsAdded = false; + + /** + * Is the mouse hovering over the renderer? + * + * @private + * @member {boolean} + */ + _this.mouseOverRenderer = false; + + /** + * Does the device support touch events + * https://www.w3.org/TR/touch-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsTouchEvents = 'ontouchstart' in window; + + /** + * Does the device support pointer events + * https://www.w3.org/Submission/pointer-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsPointerEvents = !!window.PointerEvent; + + // this will make it so that you don't have to call bind all the time + + /** + * @private + * @member {Function} + */ + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerCancel = _this.onPointerCancel.bind(_this); + _this.processPointerCancel = _this.processPointerCancel.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOver = _this.onPointerOver.bind(_this); + + /** + * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor + * values, objects are handled as dictionaries of CSS values for interactionDOMElement, + * and functions are called instead of changing the CSS. + * Default CSS cursor values are provided for 'default' and 'pointer' modes. + * @member {Object.)>} + */ + _this.cursorStyles = { + default: 'inherit', + pointer: 'pointer' + }; + + /** + * The mode of the cursor that is being used. + * The value of this is a key from the cursorStyles dictionary. + * + * @member {string} + */ + _this.currentCursorMode = null; + + /** + * Internal cached let. + * + * @private + * @member {string} + */ + _this.cursor = null; + + /** + * Internal cached let. + * + * @private + * @member {PIXI.Point} + */ + _this._tempPoint = new core.Point(); + + /** + * The current resolution / device pixel ratio. + * + * @member {number} + * @default 1 + */ + _this.resolution = 1; + + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + + /** + * Fired when a pointer device button (usually a mouse button) is pressed on the display + * object. + * + * @event mousedown + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * + * @event rightdown + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is released over the display + * object. + * + * @event mouseup + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * + * @event rightup + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is pressed and released on + * the display object. + * + * @event click + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * + * @event rightclick + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button (usually a mouse button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. + * + * @event mouseupoutside + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. + * + * @event rightupoutside + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * + * @event mousemove + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * + * @event mouseover + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * + * @event mouseout + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * + * @event pointerdown + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is released over the display object. + * + * @event pointerup + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when the operating system cancels a pointer event + * + * @event pointercancel + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * + * @event pointertap + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}. + * + * @event pointerupoutside + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved while over the display object + * + * @event pointermove + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved onto the display object + * + * @event pointerover + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a pointer device is moved off the display object + * + * @event pointerout + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is placed on the display object. + * + * @event touchstart + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is removed from the display object. + * + * @event touchend + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when the operating system cancels a touch + * + * @event touchcancel + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * + * @event tap + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. + * + * @event touchendoutside + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + + /** + * Fired when a touch point is moved along the display object. + * + * @event touchmove + * @type {PIXI.interaction.InteractionData} + * @memberof PIXI.interaction.InteractionManager# + */ + return _this; + } + + /** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate + * another DOM element to receive those events. + * + * @param {HTMLCanvasElement} element - the DOM element which will receive mouse and touch events. + * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). + * @private + */ + + + InteractionManager.prototype.setTargetElement = function setTargetElement(element) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.removeEvents(); + + this.interactionDOMElement = element; + + this.resolution = resolution; + + this.addEvents(); + }; + + /** + * Registers all the DOM events + * + * @private + */ + + + InteractionManager.prototype.addEvents = function addEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.add(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; + this.interactionDOMElement.style['-ms-touch-action'] = 'none'; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = 'none'; + } + + /** + * These events are added first, so that if pointer events are normalised, they are fired + * in the same order as non-normalised events. ie. pointer event 1st, mouse / touch 2nd + */ + if (this.supportsPointerEvents) { + window.document.addEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); + // pointerout is fired in addition to pointerup (for touch events) and pointercancel + // we already handle those, so for the purposes of what we do in onPointerOut, we only + // care about the pointerleave event + this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); + window.addEventListener('pointercancel', this.onPointerCancel, true); + window.addEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.addEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); + window.addEventListener('mouseup', this.onPointerUp, true); + + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); + } + } + + this.eventsAdded = true; + }; + + /** + * Removes all the DOM events that were previously registered + * + * @private + */ + + + InteractionManager.prototype.removeEvents = function removeEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.remove(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = ''; + this.interactionDOMElement.style['-ms-touch-action'] = ''; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = ''; + } + + if (this.supportsPointerEvents) { + window.document.removeEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); + window.removeEventListener('pointercancel', this.onPointerCancel, true); + window.removeEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.removeEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true); + window.removeEventListener('mouseup', this.onPointerUp, true); + + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); + } + } + + this.interactionDOMElement = null; + + this.eventsAdded = false; + }; + + /** + * Updates the state of interactive objects. + * Invoked by a throttled ticker update from {@link PIXI.ticker.shared}. + * + * @param {number} deltaTime - time delta since last tick + */ + + + InteractionManager.prototype.update = function update(deltaTime) { + this._deltaTime += deltaTime; + + if (this._deltaTime < this.interactionFrequency) { + return; + } + + this._deltaTime = 0; + + if (!this.interactionDOMElement) { + return; + } + + // if the user move the mouse this check has already been done using the mouse move! + if (this.didMove) { + this.didMove = false; + + return; + } + + this.cursor = null; + + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + for (var k in this.activeInteractionData) { + // eslint-disable-next-line no-prototype-builtins + if (this.activeInteractionData.hasOwnProperty(k)) { + var interactionData = this.activeInteractionData[k]; + + if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, true); + } + } + } + + this.setCursorMode(this.cursor); + + // TODO + }; + + /** + * Sets the current cursor mode, handling any callbacks or CSS style changes. + * + * @param {string} mode - cursor mode, a key from the cursorStyles dictionary + */ + + + InteractionManager.prototype.setCursorMode = function setCursorMode(mode) { + mode = mode || 'default'; + // if the mode didn't actually change, bail early + if (this.currentCursorMode === mode) { + return; + } + this.currentCursorMode = mode; + var style = this.cursorStyles[mode]; + + // only do things if there is a cursor style for it + if (style) { + switch (typeof style === 'undefined' ? 'undefined' : _typeof(style)) { + case 'string': + // string styles are handled as cursor CSS + this.interactionDOMElement.style.cursor = style; + break; + case 'function': + // functions are just called, and passed the cursor mode + style(mode); + break; + case 'object': + // if it is an object, assume that it is a dictionary of CSS styles, + // apply it to the interactionDOMElement + Object.assign(this.interactionDOMElement.style, style); + break; + } + } + }; + + /** + * Dispatches an event on the display object that was interacted with + * + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the display object in question + * @param {string} eventString - the name of the event (e.g, mousedown) + * @param {object} eventData - the event data object + * @private + */ + + + InteractionManager.prototype.dispatchEvent = function dispatchEvent(displayObject, eventString, eventData) { + if (!eventData.stopped) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + + displayObject.emit(eventString, eventData); + + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } + }; + + /** + * Maps x and y coords from a DOM object and maps them correctly to the pixi view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. + * + * @param {PIXI.Point} point - the point that the result will be stored in + * @param {number} x - the x coord of the position to map + * @param {number} y - the y coord of the position to map + */ + + + InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint(point, x, y) { + var rect = void 0; + + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { x: 0, y: 0, width: 0, height: 0 }; + } else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + + var resolutionMultiplier = navigator.isCocoonJS ? this.resolution : 1.0 / this.resolution; + + point.x = (x - rect.left) * (this.interactionDOMElement.width / rect.width) * resolutionMultiplier; + point.y = (y - rect.top) * (this.interactionDOMElement.height / rect.height) * resolutionMultiplier; + }; + + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * + * @private + * @param {InteractionEvent} interactionEvent - event containing the point that + * is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param {Function} [func] - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point + * @param {boolean} [interactive] - Whether the displayObject is interactive + * @return {boolean} returns true if the displayObject hit the point + */ + + + InteractionManager.prototype.processInteractive = function processInteractive(interactionEvent, displayObject, func, hitTest, interactive) { + if (!displayObject || !displayObject.visible) { + return false; + } + + var point = interactionEvent.data.global; + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + interactive = displayObject.interactive || interactive; + + var hit = false; + var interactiveParent = interactive; + + // if the displayobject has a hitArea, then it does not need to hitTest children. + if (displayObject.hitArea) { + interactiveParent = false; + } + // it has a mask! Then lets hit test that before continuing + else if (hitTest && displayObject._mask) { + if (!displayObject._mask.containsPoint(point)) { + hitTest = false; + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow pixi to completely ignore and bypass checking the displayObjects children. + if (displayObject.interactiveChildren && displayObject.children) { + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + + // time to get recursive.. if this function will return if something is hit.. + var childHit = this.processInteractive(interactionEvent, child, func, hitTest, interactiveParent); + + if (childHit) { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if (!child.parent) { + continue; + } + + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + + if (childHit) { + if (interactionEvent.target) { + hitTest = false; + } + hit = true; + } + } + } + } + + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit - but only if it was interactive, otherwise we need to keep + // looking for an interactive child, just in case we hit one + if (hitTest && !interactionEvent.target) { + if (displayObject.hitArea) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hit = true; + } + } else if (displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = true; + } + } + } + + if (displayObject.interactive) { + if (hit && !interactionEvent.target) { + interactionEvent.target = displayObject; + } + + func(interactionEvent, displayObject, !!hit); + } + } + + return hit; + }; + + /** + * Is called when the pointer button is pressed down on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down + */ + + + InteractionManager.prototype.onPointerDown = function onPointerDown(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + /** + * No need to prevent default on natural pointer events, as there are no side effects + * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, + * so still need to be prevented. + */ + + // Guaranteed that there will be at least one event in events, and all events must have the same pointer type + + if (this.autoPreventDefault && events[0].isNormalized) { + originalEvent.preventDefault(); + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerDown, true); + + this.emit('pointerdown', interactionEvent); + if (event.pointerType === 'touch') { + this.emit('touchstart', interactionEvent); + } else if (event.pointerType === 'mouse') { + var isRightButton = event.button === 2 || event.which === 3; + + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + } + }; + + /** + * Processes the result of the pointer down check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerDown = function processPointerDown(interactionEvent, displayObject, hit) { + var e = interactionEvent.data.originalEvent; + + var id = interactionEvent.data.identifier; + + if (hit) { + if (!displayObject.trackedPointers[id]) { + displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + + if (e.type === 'touchstart' || e.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchstart', interactionEvent); + } else if (e.type === 'mousedown' || e.pointerType === 'mouse') { + var isRightButton = e.button === 2 || e.which === 3; + + if (isRightButton) { + displayObject.trackedPointers[id].rightDown = true; + } else { + displayObject.trackedPointers[id].leftDown = true; + } + + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released + * @param {boolean} cancelled - true if the pointer is cancelled + * @param {Function} func - Function passed to {@link processInteractive} + */ + + + InteractionManager.prototype.onPointerComplete = function onPointerComplete(originalEvent, cancelled, func) { + var events = this.normalizeToPointerData(originalEvent); + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, func, true); + + this.emit(cancelled ? 'pointercancel' : 'pointerup', interactionEvent); + + if (event.pointerType === 'mouse') { + var isRightButton = event.button === 2 || event.which === 3; + + this.emit(isRightButton ? 'rightup' : 'mouseup', interactionEvent); + } else if (event.pointerType === 'touch') { + this.emit(cancelled ? 'touchcancel' : 'touchend', interactionEvent); + this.releaseInteractionDataForPointerId(event.pointerId, interactionData); + } + } + }; + + /** + * Is called when the pointer button is cancelled + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerCancel = function onPointerCancel(event) { + this.onPointerComplete(event, true, this.processPointerCancel); + }; + + /** + * Processes the result of the pointer cancel check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + */ + + + InteractionManager.prototype.processPointerCancel = function processPointerCancel(interactionEvent, displayObject) { + var e = interactionEvent.data.originalEvent; + + var id = interactionEvent.data.identifier; + + if (displayObject.trackedPointers[id] !== undefined) { + delete displayObject.trackedPointers[id]; + this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); + + if (e.type === 'touchcancel' || e.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerUp = function onPointerUp(event) { + this.onPointerComplete(event, false, this.processPointerUp); + }; + + /** + * Processes the result of the pointer up check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerUp = function processPointerUp(interactionEvent, displayObject, hit) { + var e = interactionEvent.data.originalEvent; + + var id = interactionEvent.data.identifier; + + var trackingData = displayObject.trackedPointers[id]; + + var isTouch = e.type === 'touchend' || e.pointerType === 'touch'; + + var isMouse = e.type.indexOf('mouse') === 0 || e.pointerType === 'mouse'; + + // Mouse only + if (isMouse) { + var isRightButton = e.button === 2 || e.which === 3; + + var flags = _InteractionTrackingData2.default.FLAGS; + + var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; + + var isDown = trackingData !== undefined && trackingData.flags & test; + + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); + + if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); + } + } else if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); + } + // update the down state of the tracking data + if (trackingData) { + if (isRightButton) { + trackingData.rightDown = false; + } else { + trackingData.leftDown = false; + } + } + } + + // Pointers and Touches, and Mouse + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchend', interactionEvent); + + if (trackingData) { + this.dispatchEvent(displayObject, 'pointertap', interactionEvent); + if (isTouch) { + this.dispatchEvent(displayObject, 'tap', interactionEvent); + // touches are no longer over (if they ever were) when we get the touchend + // so we should ensure that we don't keep pretending that they are + trackingData.over = false; + } + } + } else if (trackingData) { + this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); + } + // Only remove the tracking data if there is no over/down state still associated with it + if (trackingData && trackingData.none) { + delete displayObject.trackedPointers[id]; + } + }; + + /** + * Is called when the pointer moves across the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer moving + */ + + + InteractionManager.prototype.onPointerMove = function onPointerMove(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + if (events[0].pointerType === 'mouse') { + this.didMove = true; + + this.cursor = null; + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + var interactive = event.pointerType === 'touch' ? this.moveWhenInside : true; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerMove, interactive); + this.emit('pointermove', interactionEvent); + if (event.pointerType === 'touch') this.emit('touchmove', interactionEvent); + if (event.pointerType === 'mouse') this.emit('mousemove', interactionEvent); + } + + if (events[0].pointerType === 'mouse') { + this.setCursorMode(this.cursor); + + // TODO BUG for parents interactive object (border order issue) + } + }; + + /** + * Processes the result of the pointer move check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerMove = function processPointerMove(interactionEvent, displayObject, hit) { + var e = interactionEvent.data.originalEvent; + + var isTouch = e.type === 'touchmove' || e.pointerType === 'touch'; + + var isMouse = e.type === 'mousemove' || e.pointerType === 'mouse'; + + if (isMouse) { + this.processPointerOverOut(interactionEvent, displayObject, hit); + } + + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchmove', interactionEvent); + if (isMouse) this.dispatchEvent(displayObject, 'mousemove', interactionEvent); + } + }; + + /** + * Is called when the pointer is moved out of the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out + */ + + + InteractionManager.prototype.onPointerOut = function onPointerOut(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOut, so events will always be length 1 + var event = events[0]; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = false; + this.setCursorMode(null); + } + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, false); + + this.emit('pointerout', interactionEvent); + if (event.pointerType === 'mouse') { + this.emit('mouseout', interactionEvent); + } else { + // we can get touchleave events after touchend, so we want to make sure we don't + // introduce memory leaks + this.releaseInteractionDataForPointerId(interactionData.identifier); + } + }; + + /** + * Processes the result of the pointer over/out check and dispatches the event if need be + * + * @private + * @param {InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerOverOut = function processPointerOverOut(interactionEvent, displayObject, hit) { + var e = interactionEvent.data.originalEvent; + + var id = interactionEvent.data.identifier; + + var isMouse = e.type === 'mouseover' || e.type === 'mouseout' || e.pointerType === 'mouse'; + + var trackingData = displayObject.trackedPointers[id]; + + // if we just moused over the display object, then we need to track that state + if (hit && !trackingData) { + trackingData = displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + + if (trackingData === undefined) return; + + if (hit && this.mouseOverRenderer) { + if (!trackingData.over) { + trackingData.over = true; + this.dispatchEvent(displayObject, 'pointerover', interactionEvent); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseover', interactionEvent); + } + } + + // only change the cursor if it has not already been changed (by something deeper in the + // display tree) + if (isMouse && this.cursor === null) { + this.cursor = displayObject.cursor; + } + } else if (trackingData.over) { + trackingData.over = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseout', interactionEvent); + } + // if there is no mouse down information for the pointer, then it is safe to delete + if (trackingData.none) { + delete displayObject.trackedPointers[id]; + } + } + }; + + /** + * Is called when the pointer is moved into the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view + */ + + + InteractionManager.prototype.onPointerOver = function onPointerOver(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOver, so events will always be length 1 + var event = events[0]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = true; + } + + this.emit('pointerover', interactionEvent); + if (event.pointerType === 'mouse') { + this.emit('mouseover', interactionEvent); + } + }; + + /** + * Get InteractionData for a given pointerId. Store that data as well + * + * @private + * @param {PointerEvent} event - Normalized pointer event, output from normalizeToPointerData + * @return {InteractionData} - Interaction data for the given pointer identifier + */ + + + InteractionManager.prototype.getInteractionDataForPointerId = function getInteractionDataForPointerId(event) { + var pointerId = event.pointerId; + + if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { + return this.mouse; + } else if (this.activeInteractionData[pointerId]) { + return this.activeInteractionData[pointerId]; + } + + var interactionData = this.interactionDataPool.pop() || new _InteractionData2.default(); + + interactionData.identifier = pointerId; + this.activeInteractionData[pointerId] = interactionData; + + return interactionData; + }; + + /** + * Return unused InteractionData to the pool, for a given pointerId + * + * @private + * @param {number} pointerId - Identifier from a pointer event + */ + + + InteractionManager.prototype.releaseInteractionDataForPointerId = function releaseInteractionDataForPointerId(pointerId) { + var interactionData = this.activeInteractionData[pointerId]; + + if (interactionData) { + delete this.activeInteractionData[pointerId]; + this.interactionDataPool.push(interactionData); + } + }; + + /** + * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData + * + * @private + * @param {InteractionEvent} interactionEvent - The event to be configured + * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent + * @param {InteractionData} interactionData - The InteractionData that will be paired with the InteractionEvent + * @return {InteractionEvent} the interaction event that was passed in + */ + + + InteractionManager.prototype.configureInteractionEventForDOMEvent = function configureInteractionEventForDOMEvent(interactionEvent, pointerEvent, interactionData) { + interactionEvent.data = interactionData; + + this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); + + // This is the way InteractionManager processed touch events before the refactoring, so I've kept + // it here. But it doesn't make that much sense to me, since mapPositionToPoint already factors + // in this.resolution, so this just divides by this.resolution twice for touch events... + if (navigator.isCocoonJS && pointerEvent.pointerType === 'touch') { + interactionData.global.x = interactionData.global.x / this.resolution; + interactionData.global.y = interactionData.global.y / this.resolution; + } + + // Not really sure why this is happening, but it's how a previous version handled things + if (pointerEvent.pointerType === 'touch') { + pointerEvent.globalX = interactionData.global.x; + pointerEvent.globalY = interactionData.global.y; + } + + interactionData.originalEvent = pointerEvent; + interactionEvent._reset(); + + return interactionEvent; + }; + + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * + * @private + * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event + * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer + * or mouse event, or a multiple normalized pointer events if there are multiple changed touches + */ + + + InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData(event) { + var normalizedEvents = []; + + if (this.supportsTouchEvents && event instanceof TouchEvent) { + for (var i = 0, li = event.changedTouches.length; i < li; i++) { + var touch = event.changedTouches[i]; + + if (typeof touch.button === 'undefined') touch.button = event.touches.length ? 1 : 0; + if (typeof touch.buttons === 'undefined') touch.buttons = event.touches.length ? 1 : 0; + if (typeof touch.isPrimary === 'undefined') touch.isPrimary = event.touches.length === 1; + if (typeof touch.width === 'undefined') touch.width = touch.radiusX || 1; + if (typeof touch.height === 'undefined') touch.height = touch.radiusY || 1; + if (typeof touch.tiltX === 'undefined') touch.tiltX = 0; + if (typeof touch.tiltY === 'undefined') touch.tiltY = 0; + if (typeof touch.pointerType === 'undefined') touch.pointerType = 'touch'; + if (typeof touch.pointerId === 'undefined') touch.pointerId = touch.identifier || 0; + if (typeof touch.pressure === 'undefined') touch.pressure = touch.force || 0.5; + if (typeof touch.rotation === 'undefined') touch.rotation = touch.rotationAngle || 0; + + if (typeof touch.layerX === 'undefined') touch.layerX = touch.offsetX = touch.clientX; + if (typeof touch.layerY === 'undefined') touch.layerY = touch.offsetY = touch.clientY; + + // mark the touch as normalized, just so that we know we did it + touch.isNormalized = true; + + normalizedEvents.push(touch); + } + } + // apparently PointerEvent subclasses MouseEvent, so yay + else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent))) { + if (typeof event.isPrimary === 'undefined') event.isPrimary = true; + if (typeof event.width === 'undefined') event.width = 1; + if (typeof event.height === 'undefined') event.height = 1; + if (typeof event.tiltX === 'undefined') event.tiltX = 0; + if (typeof event.tiltY === 'undefined') event.tiltY = 0; + if (typeof event.pointerType === 'undefined') event.pointerType = 'mouse'; + if (typeof event.pointerId === 'undefined') event.pointerId = MOUSE_POINTER_ID; + if (typeof event.pressure === 'undefined') event.pressure = 0.5; + if (typeof event.rotation === 'undefined') event.rotation = 0; + + // mark the mouse event as normalized, just so that we know we did it + event.isNormalized = true; + + normalizedEvents.push(event); + } else { + normalizedEvents.push(event); + } + + return normalizedEvents; + }; + + /** + * Destroys the interaction manager + * + */ + + + InteractionManager.prototype.destroy = function destroy() { + this.removeEvents(); + + this.removeAllListeners(); + + this.renderer = null; + + this.mouse = null; + + this.eventData = null; + + this.interactionDOMElement = null; + + this.onPointerDown = null; + this.processPointerDown = null; + + this.onPointerUp = null; + this.processPointerUp = null; + + this.onPointerCancel = null; + this.processPointerCancel = null; + + this.onPointerMove = null; + this.processPointerMove = null; + + this.onPointerOut = null; + this.processPointerOverOut = null; + + this.onPointerOver = null; + + this._tempPoint = null; + }; + + return InteractionManager; +}(_eventemitter2.default); + +exports.default = InteractionManager; + + +core.WebGLRenderer.registerPlugin('interaction', InteractionManager); +core.CanvasRenderer.registerPlugin('interaction', InteractionManager); + +},{"../core":63,"./InteractionData":150,"./InteractionEvent":151,"./InteractionTrackingData":153,"./interactiveTarget":155,"eventemitter3":3}],153:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * DisplayObjects with the {@link PIXI.interaction.interactiveTarget} mixin use this class to track interactions + * + * @class + * @private + * @memberof PIXI.interaction + */ +var InteractionTrackingData = function () { + /** + * @param {number} pointerId - Unique pointer id of the event + */ + function InteractionTrackingData(pointerId) { + _classCallCheck(this, InteractionTrackingData); + + this._pointerId = pointerId; + this._flags = InteractionTrackingData.FLAGS.NONE; + } + + /** + * + * @private + * @param {number} flag - The interaction flag to set + * @param {boolean} yn - Should the flag be set or unset + */ + + + InteractionTrackingData.prototype._doSet = function _doSet(flag, yn) { + if (yn) { + this._flags = this._flags | flag; + } else { + this._flags = this._flags & ~flag; + } + }; + + /** + * @readonly + * @type {number} Unique pointer id of the event + */ + + + _createClass(InteractionTrackingData, [{ + key: "pointerId", + get: function get() { + return this._pointerId; + } + + /** + * State of the tracking data, expressed as bit flags + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "flags", + get: function get() { + return this._flags; + } + + /** + * Set the flags for the tracking data + * + * @param {number} flags - Flags to set + */ + , + set: function set(flags) { + this._flags = flags; + } + + /** + * Is the tracked event inactive (not over or down)? + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "none", + get: function get() { + return this._flags === this.constructor.FLAGS.NONE; + } + + /** + * Is the tracked event over the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "over", + get: function get() { + return (this._flags & this.constructor.FLAGS.OVER) !== 0; + } + + /** + * Set the over flag + * + * @param {boolean} yn - Is the event over? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.OVER, yn); + } + + /** + * Did the right mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "rightDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.RIGHT_DOWN) !== 0; + } + + /** + * Set the right down flag + * + * @param {boolean} yn - Is the right mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.RIGHT_DOWN, yn); + } + + /** + * Did the left mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "leftDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.LEFT_DOWN) !== 0; + } + + /** + * Set the left down flag + * + * @param {boolean} yn - Is the left mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.LEFT_DOWN, yn); + } + }]); + + return InteractionTrackingData; +}(); + +exports.default = InteractionTrackingData; + + +InteractionTrackingData.FLAGS = Object.freeze({ + NONE: 0, + OVER: 1 << 0, + LEFT_DOWN: 1 << 1, + RIGHT_DOWN: 1 << 2 +}); + +},{}],154:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _InteractionData = require('./InteractionData'); + +Object.defineProperty(exports, 'InteractionData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionData).default; + } +}); + +var _InteractionManager = require('./InteractionManager'); + +Object.defineProperty(exports, 'InteractionManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionManager).default; + } +}); + +var _interactiveTarget = require('./interactiveTarget'); + +Object.defineProperty(exports, 'interactiveTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_interactiveTarget).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./InteractionData":150,"./InteractionManager":152,"./interactiveTarget":155}],155:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * Default property values of interactive objects + * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties + * + * @mixin + * @name interactiveTarget + * @memberof PIXI.interaction + * @example + * function MyObject() {} + * + * Object.assign( + * core.DisplayObject.prototype, + * PIXI.interaction.interactiveTarget + * ); + */ +exports.default = { + /** + * Determines if the displayObject be clicked/touched + * + * @inner {boolean} + */ + interactive: false, + + /** + * Determines if the children to the displayObject can be clicked/touched + * Setting this to false allows pixi to bypass a recursive hitTest function + * + * @inner {boolean} + */ + interactiveChildren: true, + + /** + * Interaction shape. Children will be hit first, then this shape will be checked. + * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. + * + * @inner {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle} + */ + hitArea: null, + + /** + * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive + * Setting this changes the 'cursor' property to `'pointer'`. + * + * @member {boolean} + * @memberof PIXI.interaction.interactiveTarget# + */ + get buttonMode() { + return this.cursor === 'pointer'; + }, + set buttonMode(value) { + if (value) { + this.cursor = 'pointer'; + } else if (this.cursor === 'pointer') { + this.cursor = null; + } + }, + + /** + * This defines what cursor mode is used when the mouse cursor + * is hovered over the displayObject. + * + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * + * @inner {string} + */ + cursor: null, + + /** + * Internal set of all active pointers, by identifier + * + * @member {Map} + * @memberof PIXI.interaction.interactiveTarget# + * @private + */ + get trackedPointers() { + if (this._trackedPointers === undefined) this._trackedPointers = {}; + + return this._trackedPointers; + }, + + /** + * Map of all tracked pointers, by identifier. Use trackedPointers to access. + * + * @private {Map} + */ + _trackedPointers: undefined +}; + +},{}],156:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.parse = parse; + +exports.default = function () { + return function bitmapFontParser(resource, next) { + // skip if no data or not xml data + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.XML) { + next(); + + return; + } + + // skip if not bitmap font data, using some silly duck-typing + if (resource.data.getElementsByTagName('page').length === 0 || resource.data.getElementsByTagName('info').length === 0 || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null) { + next(); + + return; + } + + var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; + + if (resource.isDataUrl) { + if (xmlUrl === '.') { + xmlUrl = ''; + } + + if (this.baseUrl && xmlUrl) { + // if baseurl has a trailing slash then add one to xmlUrl so the replace works below + if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { + xmlUrl += '/'; + } + + // remove baseUrl from xmlUrl + xmlUrl = xmlUrl.replace(this.baseUrl, ''); + } + } + + // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { + xmlUrl += '/'; + } + + var textureUrl = xmlUrl + resource.data.getElementsByTagName('page')[0].getAttribute('file'); + + if (_core.utils.TextureCache[textureUrl]) { + // reuse existing texture + parse(resource, _core.utils.TextureCache[textureUrl]); + next(); + } else { + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + // load the texture for the font + this.add(resource.name + '_image', textureUrl, loadOptions, function (res) { + parse(resource, res.texture); + next(); + }); + } + }; +}; + +var _path = require('path'); + +var path = _interopRequireWildcard(_path); + +var _core = require('../core'); + +var _resourceLoader = require('resource-loader'); + +var _extras = require('../extras'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Register a BitmapText font from loader resource. + * + * @function parseBitmapFontData + * @memberof PIXI.loaders + * @param {PIXI.loaders.Resource} resource - Loader resource. + * @param {PIXI.Texture} texture - Reference to texture. + */ +function parse(resource, texture) { + resource.bitmapFont = _extras.BitmapText.registerFont(resource.data, texture); +} + +},{"../core":63,"../extras":136,"path":22,"resource-loader":34}],157:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _loader = require('./loader'); + +Object.defineProperty(exports, 'Loader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_loader).default; + } +}); + +var _bitmapFontParser = require('./bitmapFontParser'); + +Object.defineProperty(exports, 'bitmapFontParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_bitmapFontParser).default; + } +}); +Object.defineProperty(exports, 'parseBitmapFontData', { + enumerable: true, + get: function get() { + return _bitmapFontParser.parse; + } +}); + +var _spritesheetParser = require('./spritesheetParser'); + +Object.defineProperty(exports, 'spritesheetParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_spritesheetParser).default; + } +}); + +var _textureParser = require('./textureParser'); + +Object.defineProperty(exports, 'textureParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_textureParser).default; + } +}); + +var _resourceLoader = require('resource-loader'); + +Object.defineProperty(exports, 'Resource', { + enumerable: true, + get: function get() { + return _resourceLoader.Resource; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./bitmapFontParser":156,"./loader":158,"./spritesheetParser":159,"./textureParser":160,"resource-loader":34}],158:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _resourceLoader = require('resource-loader'); + +var _resourceLoader2 = _interopRequireDefault(_resourceLoader); + +var _blob = require('resource-loader/lib/middlewares/parsing/blob'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _textureParser = require('./textureParser'); + +var _textureParser2 = _interopRequireDefault(_textureParser); + +var _spritesheetParser = require('./spritesheetParser'); + +var _spritesheetParser2 = _interopRequireDefault(_spritesheetParser); + +var _bitmapFontParser = require('./bitmapFontParser'); + +var _bitmapFontParser2 = _interopRequireDefault(_bitmapFontParser); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader + * + * ```js + * const loader = PIXI.loader; // pixi exposes a premade instance for you to use. + * //or + * const loader = new PIXI.loaders.Loader(); // you can also create your own if you want + * + * const sprites = {}; + * + * // Chainable `add` to enqueue a resource + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.add('scoreFont', 'assets/score.fnt'); + * + * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. + * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). + * loader.pre(cachingMiddleware); + * + * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. + * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). + * loader.use(parsingMiddleware); + * + * // The `load` method loads the queue of resources, and calls the passed in callback called once all + * // resources have loaded. + * loader.load((loader, resources) => { + * // resources is an object where the key is the name of the resource loaded and the value is the resource object. + * // They have a couple default properties: + * // - `url`: The URL that the resource was loaded from + * // - `error`: The error that happened when trying to load (if any) + * // - `data`: The raw data that was loaded + * // also may contain other properties based on the middleware that runs. + * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); + * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); + * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); + * }); + * + * // throughout the process multiple signals can be dispatched. + * loader.onProgress.add(() => {}); // called once per loaded/errored file + * loader.onError.add(() => {}); // called once per errored file + * loader.onLoad.add(() => {}); // called once per loaded file + * loader.onComplete.add(() => {}); // called once when the queued resources all load. + * ``` + * + * @see https://github.com/englercj/resource-loader + * + * @class + * @extends module:resource-loader.ResourceLoader + * @memberof PIXI.loaders + */ +var Loader = function (_ResourceLoader) { + _inherits(Loader, _ResourceLoader); + + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + _classCallCheck(this, Loader); + + var _this = _possibleConstructorReturn(this, _ResourceLoader.call(this, baseUrl, concurrency)); + + _eventemitter2.default.call(_this); + + for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { + _this.use(Loader._pixiMiddleware[i]()); + } + + // Compat layer, translate the new v2 signals into old v1 events. + _this.onStart.add(function (l) { + return _this.emit('start', l); + }); + _this.onProgress.add(function (l, r) { + return _this.emit('progress', l, r); + }); + _this.onError.add(function (e, l, r) { + return _this.emit('error', e, l, r); + }); + _this.onLoad.add(function (l, r) { + return _this.emit('load', l, r); + }); + _this.onComplete.add(function (l, r) { + return _this.emit('complete', l, r); + }); + return _this; + } + + /** + * Adds a default middleware to the pixi loader. + * + * @static + * @param {Function} fn - The middleware to add. + */ + + + Loader.addPixiMiddleware = function addPixiMiddleware(fn) { + Loader._pixiMiddleware.push(fn); + }; + + return Loader; +}(_resourceLoader2.default); + +// Copy EE3 prototype (mixin) + + +exports.default = Loader; +for (var k in _eventemitter2.default.prototype) { + Loader.prototype[k] = _eventemitter2.default.prototype[k]; +} + +Loader._pixiMiddleware = [ +// parse any blob into more usable objects (e.g. Image) +_blob.blobMiddlewareFactory, +// parse any Image objects into textures +_textureParser2.default, +// parse any spritesheet data into multiple textures +_spritesheetParser2.default, +// parse bitmap font data into multiple textures +_bitmapFontParser2.default]; + +// Add custom extentions +var Resource = _resourceLoader2.default.Resource; + +Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); + +},{"./bitmapFontParser":156,"./spritesheetParser":159,"./textureParser":160,"eventemitter3":3,"resource-loader":34,"resource-loader/lib/middlewares/parsing/blob":35}],159:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function spritesheetParser(resource, next) { + var resourcePath = void 0; + var imageResourceName = resource.name + '_image'; + + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.JSON || !resource.data.frames || this.resources[imageResourceName]) { + next(); + + return; + } + + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + resourcePath = resource.data.meta.image; + } else { + resourcePath = _path2.default.dirname(resource.url.replace(this.baseUrl, '')) + '/' + resource.data.meta.image; + } + + // load the image for this sheet + this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + var spritesheet = new _core.Spritesheet(res.texture.baseTexture, resource.data, resource.url); + + spritesheet.parse(function () { + resource.spritesheet = spritesheet; + resource.textures = spritesheet.textures; + next(); + }); + }); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _path = require('path'); + +var _path2 = _interopRequireDefault(_path); + +var _core = require('../core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"../core":63,"path":22,"resource-loader":34}],160:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function textureParser(resource, next) { + // create a new texture if the data is an Image object + if (resource.data && resource.type === _resourceLoader.Resource.TYPE.IMAGE) { + resource.texture = _Texture2.default.fromLoader(resource.data, resource.url, resource.name); + } + next(); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"../core/textures/Texture":112,"resource-loader":34}],161:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); +var tempPolygon = new core.Polygon(); + +/** + * Base mesh class + * @class + * @extends PIXI.Container + * @memberof PIXI.mesh + */ + +var Mesh = function (_core$Container) { + _inherits(Mesh, _core$Container); + + /** + * @param {PIXI.Texture} texture - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts + */ + function Mesh(texture, vertices, uvs, indices, drawMode) { + _classCallCheck(this, Mesh); + + /** + * The texture of the Mesh + * + * @member {PIXI.Texture} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._texture = null; + + /** + * The Uvs of the Mesh + * + * @member {Float32Array} + */ + _this.uvs = uvs || new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + /** + * An array of vertices + * + * @member {Float32Array} + */ + _this.vertices = vertices || new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]); + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + // TODO auto generate this based on draw mode! + _this.indices = indices || new Uint16Array([0, 1, 3, 2]); + + /** + * Version of mesh uvs are dirty or not + * + * @member {number} + */ + _this.dirty = 0; + + /** + * Version of mesh indices + * + * @member {number} + */ + _this.indexDirty = 0; + + /** + * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove + * any blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles + * to overlap a bit with each other. + * + * @member {number} + */ + _this.canvasPadding = 0; + + /** + * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts + * + * @member {number} + * @see PIXI.mesh.Mesh.DRAW_MODES + */ + _this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH; + + // run texture setter; + _this.texture = texture; + + /** + * The default shader that is used if a mesh doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + _this.shader = null; + + /** + * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any + * tint effect. + * + * @member {number} + */ + _this.tintRgb = new Float32Array([1, 1, 1]); + + /** + * A map of renderer IDs to webgl render data + * + * @private + * @member {object} + */ + _this._glDatas = {}; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * + * @member {string} + * @default 'mesh' + */ + _this.pluginName = 'mesh'; + return _this; + } + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - a reference to the WebGL renderer + */ + + + Mesh.prototype._renderWebGL = function _renderWebGL(renderer) { + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + + + Mesh.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins[this.pluginName].render(this); + }; + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Mesh.prototype._onTextureUpdate = function _onTextureUpdate() {} + /* empty */ + + + /** + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + */ + ; + + Mesh.prototype._calculateBounds = function _calculateBounds() { + // TODO - we can cache local bounds and use them if they are dirty (like graphics) + this._bounds.addVertices(this.transform, this.vertices, 0, this.vertices.length); + }; + + /** + * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Mesh.prototype.containsPoint = function containsPoint(point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + + this.worldTransform.applyInverse(point, tempPoint); + + var vertices = this.vertices; + var points = tempPolygon.points; + var indices = this.indices; + var len = this.indices.length; + var step = this.drawMode === Mesh.DRAW_MODES.TRIANGLES ? 3 : 1; + + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + + return false; + }; + + /** + * The texture that the mesh uses. + * + * @member {PIXI.Texture} + */ + + + _createClass(Mesh, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + + /** + * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return core.utils.rgb2hex(this.tintRgb); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tintRgb = core.utils.hex2rgb(value, this.tintRgb); + } + }]); + + return Mesh; +}(core.Container); + +/** + * Different drawing buffer modes supported + * + * @static + * @constant + * @type {object} + * @property {number} TRIANGLE_MESH + * @property {number} TRIANGLES + */ + + +exports.default = Mesh; +Mesh.DRAW_MODES = { + TRIANGLE_MESH: 0, + TRIANGLES: 1 +}; + +},{"../core":63}],162:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Plane2 = require('./Plane'); + +var _Plane3 = _interopRequireDefault(_Plane2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DEFAULT_BORDER_SIZE = 10; + +/** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.fromImage('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
+ *      A                          B
+ *    +---+----------------------+---+
+ *  C | 1 |          2           | 3 |
+ *    +---+----------------------+---+
+ *    |   |                      |   |
+ *    | 4 |          5           | 6 |
+ *    |   |                      |   |
+ *    +---+----------------------+---+
+ *  D | 7 |          8           | 9 |
+ *    +---+----------------------+---+
+
+ *  When changing this objects width and/or height:
+ *     areas 1 3 7 and 9 will remain unscaled.
+ *     areas 2 and 8 will be stretched horizontally
+ *     areas 4 and 6 will be stretched vertically
+ *     area 5 will be stretched both horizontally and vertically
+ * 
+ * + * @class + * @extends PIXI.mesh.Plane + * @memberof PIXI.mesh + * + */ + +var NineSlicePlane = function (_Plane) { + _inherits(NineSlicePlane, _Plane); + + /** + * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. + * @param {int} [leftWidth=10] size of the left vertical bar (A) + * @param {int} [topHeight=10] size of the top horizontal bar (C) + * @param {int} [rightWidth=10] size of the right vertical bar (B) + * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) + */ + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + _classCallCheck(this, NineSlicePlane); + + var _this = _possibleConstructorReturn(this, _Plane.call(this, texture, 4, 4)); + + var uvs = _this.uvs; + + // right and bottom uv's are always 1 + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + + _this._origWidth = texture.width; + _this._origHeight = texture.height; + _this._uvw = 1 / _this._origWidth; + _this._uvh = 1 / _this._origHeight; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.width = texture.width; + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.height = texture.height; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _this._uvw * leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - _this._uvw * rightWidth; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _this._uvh * topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - _this._uvh * bottomHeight; + + /** + * The width of the left column (a) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; + + /** + * The width of the right column (b) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; + + /** + * The height of the top row (c) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; + + /** + * The height of the bottom row (d) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; + return _this; + } + + /** + * Updates the horizontal vertices. + * + */ + + + NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices() { + var vertices = this.vertices; + + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight; + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + }; + + /** + * Updates the vertical vertices. + * + */ + + + NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices() { + var vertices = this.vertices; + + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth; + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with. + */ + + + NineSlicePlane.prototype._renderCanvas = function _renderCanvas(renderer) { + var context = renderer.context; + + context.globalAlpha = this.worldAlpha; + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + var base = this._texture.baseTexture; + var textureSource = base.source; + var w = base.width; + var h = base.height; + + this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11); + this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13); + this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15); + this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19); + this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21); + this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23); + this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27); + this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29); + this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31); + }; + + /** + * Renders one segment of the plane. + * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure + * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used. + * + * @private + * @param {CanvasRenderingContext2D} context - The context to draw with. + * @param {CanvasImageSource} textureSource - The source to draw. + * @param {number} w - width of the texture + * @param {number} h - height of the texture + * @param {number} x1 - x index 1 + * @param {number} y1 - y index 1 + * @param {number} x2 - x index 2 + * @param {number} y2 - y index 2 + */ + + + NineSlicePlane.prototype.drawSegment = function drawSegment(context, textureSource, w, h, x1, y1, x2, y2) { + // otherwise you get weird results when using slices of that are 0 wide or high. + var uvs = this.uvs; + var vertices = this.vertices; + + var sw = (uvs[x2] - uvs[x1]) * w; + var sh = (uvs[y2] - uvs[y1]) * h; + var dw = vertices[x2] - vertices[x1]; + var dh = vertices[y2] - vertices[y1]; + + // make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn. + if (sw < 1) { + sw = 1; + } + + if (sh < 1) { + sh = 1; + } + + // make sure destination is at least 1 pixel wide and high, otherwise you get + // lines when rendering close to original size. + if (dw < 1) { + dw = 1; + } + + if (dh < 1) { + dh = 1; + } + + context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh); + }; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + + _createClass(NineSlicePlane, [{ + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + this.updateVerticalVertices(); + } + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + this.updateHorizontalVertices(); + } + + /** + * The width of the left column + * + * @member {number} + */ + + }, { + key: 'leftWidth', + get: function get() { + return this._leftWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._leftWidth = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = this._uvw * value; + vertices[2] = vertices[10] = vertices[18] = vertices[26] = value; + + this.dirty = true; + } + + /** + * The width of the right column + * + * @member {number} + */ + + }, { + key: 'rightWidth', + get: function get() { + return this._rightWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rightWidth = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - this._uvw * value; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - value; + + this.dirty = true; + } + + /** + * The height of the top row + * + * @member {number} + */ + + }, { + key: 'topHeight', + get: function get() { + return this._topHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._topHeight = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[9] = uvs[11] = uvs[13] = uvs[15] = this._uvh * value; + vertices[9] = vertices[11] = vertices[13] = vertices[15] = value; + + this.dirty = true; + } + + /** + * The height of the bottom row + * + * @member {number} + */ + + }, { + key: 'bottomHeight', + get: function get() { + return this._bottomHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._bottomHeight = value; + + var uvs = this.uvs; + var vertices = this.vertices; + + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - this._uvh * value; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - value; + + this.dirty = true; + } + }]); + + return NineSlicePlane; +}(_Plane3.default); + +exports.default = NineSlicePlane; + +},{"./Plane":163}],163:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The Plane allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Plane = function (_Mesh) { + _inherits(Plane, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the Plane. + * @param {number} verticesX - The number of vertices in the x-axis + * @param {number} verticesY - The number of vertices in the y-axis + */ + function Plane(texture, verticesX, verticesY) { + _classCallCheck(this, Plane); + + /** + * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this._ready = true; + + _this.verticesX = verticesX || 10; + _this.verticesY = verticesY || 10; + + _this.drawMode = _Mesh3.default.DRAW_MODES.TRIANGLES; + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Plane.prototype.refresh = function refresh() { + var total = this.verticesX * this.verticesY; + var verts = []; + var colors = []; + var uvs = []; + var indices = []; + var texture = this.texture; + + var segmentsX = this.verticesX - 1; + var segmentsY = this.verticesY - 1; + + var sizeX = texture.width / segmentsX; + var sizeY = texture.height / segmentsY; + + for (var i = 0; i < total; i++) { + if (texture._uvs) { + var x = i % this.verticesX; + var y = i / this.verticesX | 0; + + verts.push(x * sizeX, y * sizeY); + + // this works for rectangular textures. + uvs.push(texture._uvs.x0 + (texture._uvs.x1 - texture._uvs.x0) * (x / (this.verticesX - 1)), texture._uvs.y0 + (texture._uvs.y3 - texture._uvs.y0) * (y / (this.verticesY - 1))); + } else { + uvs.push(0); + } + } + + // cons + + var totalSub = segmentsX * segmentsY; + + for (var _i = 0; _i < totalSub; _i++) { + var xpos = _i % segmentsX; + var ypos = _i / segmentsX | 0; + + var value = ypos * this.verticesX + xpos; + var value2 = ypos * this.verticesX + xpos + 1; + var value3 = (ypos + 1) * this.verticesX + xpos; + var value4 = (ypos + 1) * this.verticesX + xpos + 1; + + indices.push(value, value2, value3); + indices.push(value2, value4, value3); + } + + // console.log(indices) + this.vertices = new Float32Array(verts); + this.uvs = new Float32Array(uvs); + this.colors = new Float32Array(colors); + this.indices = new Uint16Array(indices); + + this.indexDirty = true; + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Plane.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh3.default.prototype._onTextureUpdate.call(this); + + // wait for the Plane ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + return Plane; +}(_Mesh3.default); + +exports.default = Plane; + +},{"./Mesh":161}],164:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The rope allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Rope = function (_Mesh) { + _inherits(Rope, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the rope. + * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. + */ + function Rope(texture, points) { + _classCallCheck(this, Rope); + + /* + * @member {PIXI.Point[]} An array of points that determine the rope + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this.points = points; + + /* + * @member {Float32Array} An array of vertices used to construct this rope. + */ + _this.vertices = new Float32Array(points.length * 4); + + /* + * @member {Float32Array} The WebGL Uvs of the rope. + */ + _this.uvs = new Float32Array(points.length * 4); + + /* + * @member {Float32Array} An array containing the color components + */ + _this.colors = new Float32Array(points.length * 2); + + /* + * @member {Uint16Array} An array containing the indices of the vertices + */ + _this.indices = new Uint16Array(points.length * 2); + + /** + * Tracker for if the rope is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + _this._ready = true; + + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Rope.prototype.refresh = function refresh() { + var points = this.points; + + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1 || !this._texture._uvs) { + return; + } + + // if the number of points has changed we will need to recreate the arraybuffers + if (this.vertices.length / 4 !== points.length) { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + var textureUvs = this._texture._uvs; + var offset = new core.Point(textureUvs.x0, textureUvs.y0); + var factor = new core.Point(textureUvs.x2 - textureUvs.x0, Number(textureUvs.y2 - textureUvs.y0)); + + uvs[0] = 0 + offset.x; + uvs[1] = 0 + offset.y; + uvs[2] = 0 + offset.x; + uvs[3] = factor.y + offset.y; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + + for (var i = 1; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + var amount = i / (total - 1); + + uvs[index] = amount * factor.x + offset.x; + uvs[index + 1] = 0 + offset.y; + + uvs[index + 2] = amount * factor.x + offset.x; + uvs[index + 3] = factor.y + offset.y; + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + + // ensure that the changes are uploaded + this.dirty++; + this.indexDirty++; + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Rope.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh.prototype._onTextureUpdate.call(this); + + // wait for the Rope ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + Rope.prototype.updateTransform = function updateTransform() { + var points = this.points; + + if (points.length < 1) { + return; + } + + var lastPoint = points[0]; + var nextPoint = void 0; + var perpX = 0; + var perpY = 0; + + // this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } else { + nextPoint = point; + } + + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + + var ratio = (1 - i / (total - 1)) * 10; + + if (ratio > 1) { + ratio = 1; + } + + var perpLength = Math.sqrt(perpX * perpX + perpY * perpY); + var num = this._texture.height / 2; // (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; + + perpX /= perpLength; + perpY /= perpLength; + + perpX *= num; + perpY *= num; + + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + + lastPoint = point; + } + + this.containerUpdateTransform(); + }; + + return Rope; +}(_Mesh3.default); + +exports.default = Rope; + +},{"../core":63,"./Mesh":161}],165:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Renderer dedicated to meshes. + * + * @class + * @private + * @memberof PIXI + */ +var MeshSpriteRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The renderer this downport works for + */ + function MeshSpriteRenderer(renderer) { + _classCallCheck(this, MeshSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the Mesh + * + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var context = renderer.context; + + var transform = mesh.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + renderer.setBlendMode(mesh.blendMode); + + if (mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH) { + this._renderTriangleMesh(mesh); + } else { + this._renderTriangles(mesh); + } + }; + + /** + * Draws the object in Triangle Mesh mode + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype._renderTriangleMesh = function _renderTriangleMesh(mesh) { + // draw triangles!! + var length = mesh.vertices.length / 2; + + for (var i = 0; i < length - 2; i++) { + // draw some triangles! + var index = i * 2; + + this._renderDrawTriangle(mesh, index, index + 2, index + 4); + } + }; + + /** + * Draws the object in triangle mode using canvas + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + */ + + + MeshSpriteRenderer.prototype._renderTriangles = function _renderTriangles(mesh) { + // draw triangles!! + var indices = mesh.indices; + var length = indices.length; + + for (var i = 0; i < length; i += 3) { + // draw some triangles! + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderDrawTriangle(mesh, index0, index1, index2); + } + }; + + /** + * Draws one of the triangles that from the Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + * @param {number} index0 - the index of the first vertex + * @param {number} index1 - the index of the second vertex + * @param {number} index2 - the index of the third vertex + */ + + + MeshSpriteRenderer.prototype._renderDrawTriangle = function _renderDrawTriangle(mesh, index0, index1, index2) { + var context = this.renderer.context; + var uvs = mesh.uvs; + var vertices = mesh.vertices; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var base = texture.baseTexture; + var textureSource = base.source; + var textureWidth = base.width; + var textureHeight = base.height; + + var u0 = uvs[index0] * base.width; + var u1 = uvs[index1] * base.width; + var u2 = uvs[index2] * base.width; + var v0 = uvs[index0 + 1] * base.height; + var v1 = uvs[index1 + 1] * base.height; + var v2 = uvs[index2 + 1] * base.height; + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + if (mesh.canvasPadding > 0) { + var paddingX = mesh.canvasPadding / mesh.worldTransform.a; + var paddingY = mesh.canvasPadding / mesh.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt(normX * normX + normY * normY); + + x0 = centerX + normX / dist * (dist + paddingX); + y0 = centerY + normY / dist * (dist + paddingY); + + // + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x1 = centerX + normX / dist * (dist + paddingX); + y1 = centerY + normY / dist * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x2 = centerX + normX / dist * (dist + paddingX); + y2 = centerY + normY / dist * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2; + var deltaA = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2; + var deltaB = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2; + var deltaC = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2; + var deltaD = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2; + var deltaE = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2; + var deltaF = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2; + + context.transform(deltaA / delta, deltaD / delta, deltaB / delta, deltaE / delta, deltaC / delta, deltaF / delta); + + context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + + context.restore(); + }; + + /** + * Renders a flat Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - The Mesh to render + */ + + + MeshSpriteRenderer.prototype.renderMeshFlat = function renderMeshFlat(mesh) { + var context = this.renderer.context; + var vertices = mesh.vertices; + var length = vertices.length / 2; + + // this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; ++i) { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var y0 = vertices[index + 1]; + + var x1 = vertices[index + 2]; + var y1 = vertices[index + 3]; + + var x2 = vertices[index + 4]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + }; + + /** + * destroy the the renderer. + * + */ + + + MeshSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return MeshSpriteRenderer; +}(); + +exports.default = MeshSpriteRenderer; + + +core.CanvasRenderer.registerPlugin('mesh', MeshSpriteRenderer); + +},{"../../core":63,"../Mesh":161}],166:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh = require('./Mesh'); + +Object.defineProperty(exports, 'Mesh', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Mesh).default; + } +}); + +var _MeshRenderer = require('./webgl/MeshRenderer'); + +Object.defineProperty(exports, 'MeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_MeshRenderer).default; + } +}); + +var _CanvasMeshRenderer = require('./canvas/CanvasMeshRenderer'); + +Object.defineProperty(exports, 'CanvasMeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasMeshRenderer).default; + } +}); + +var _Plane = require('./Plane'); + +Object.defineProperty(exports, 'Plane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Plane).default; + } +}); + +var _NineSlicePlane = require('./NineSlicePlane'); + +Object.defineProperty(exports, 'NineSlicePlane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NineSlicePlane).default; + } +}); + +var _Rope = require('./Rope'); + +Object.defineProperty(exports, 'Rope', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rope).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./Mesh":161,"./NineSlicePlane":162,"./Plane":163,"./Rope":164,"./canvas/CanvasMeshRenderer":165,"./webgl/MeshRenderer":167}],167:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var MeshRenderer = function (_core$ObjectRenderer) { + _inherits(MeshRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function MeshRenderer(renderer) { + _classCallCheck(this, MeshRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + MeshRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 translationMatrix;\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n}\n', 'varying vec2 vTextureCoord;\nuniform float alpha;\nuniform vec3 tint;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * vec4(tint * alpha, alpha);\n}\n'); + }; + + /** + * renders mesh + * + * @param {PIXI.mesh.Mesh} mesh mesh instance + */ + + + MeshRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var gl = renderer.gl; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var glData = mesh._glDatas[renderer.CONTEXT_UID]; + + if (!glData) { + renderer.bindVao(null); + + glData = { + shader: this.shader, + vertexBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.vertices, gl.STREAM_DRAW), + uvBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.uvs, gl.STREAM_DRAW), + indexBuffer: _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, mesh.indices, gl.STATIC_DRAW), + // build the vao object that will render.. + vao: null, + dirty: mesh.dirty, + indexDirty: mesh.indexDirty + }; + + // build the vao object that will render.. + glData.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(glData.indexBuffer).addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0).addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); + + mesh._glDatas[renderer.CONTEXT_UID] = glData; + } + + renderer.bindVao(glData.vao); + + if (mesh.dirty !== glData.dirty) { + glData.dirty = mesh.dirty; + glData.uvBuffer.upload(mesh.uvs); + } + + if (mesh.indexDirty !== glData.indexDirty) { + glData.indexDirty = mesh.indexDirty; + glData.indexBuffer.upload(mesh.indices); + } + + glData.vertexBuffer.upload(mesh.vertices); + + renderer.bindShader(glData.shader); + + glData.shader.uniforms.uSampler = renderer.bindTexture(texture); + + renderer.state.setBlendMode(mesh.blendMode); + + glData.shader.uniforms.translationMatrix = mesh.worldTransform.toArray(true); + glData.shader.uniforms.alpha = mesh.worldAlpha; + glData.shader.uniforms.tint = mesh.tintRgb; + + var drawMode = mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + glData.vao.draw(drawMode, mesh.indices.length, 0); + }; + + return MeshRenderer; +}(core.ObjectRenderer); + +exports.default = MeshRenderer; + + +core.WebGLRenderer.registerPlugin('mesh', MeshRenderer); + +},{"../../core":63,"../Mesh":161,"path":22,"pixi-gl-core":12}],168:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that advanced + * functionality will not work. ParticleContainer implements only the basic object transform (position, scale, rotation). + * Any other functionality like tinting, masking, etc will not work on sprites in this batch. + * + * It's extremely easy to use : + * + * ```js + * let container = new ParticleContainer(); + * + * for (let i = 0; i < 100; ++i) + * { + * let sprite = new PIXI.Sprite.fromImage("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be renderer at the speed of light. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.particles + */ +var ParticleContainer = function (_core$Container) { + _inherits(ParticleContainer, _core$Container); + + /** + * @param {number} [maxSize=15000] - The maximum number of particles that can be renderer by the container. + * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.scale=false] - When true, scale be uploaded and applied. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.alpha=false] - When true, alpha be uploaded and applied. + * @param {number} [batchSize=15000] - Number of particles per batch. + */ + function ParticleContainer() { + var maxSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1500; + var properties = arguments[1]; + var batchSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 16384; + + _classCallCheck(this, ParticleContainer); + + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + var maxBatchSize = 16384; + + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + + if (batchSize > maxSize) { + batchSize = maxSize; + } + + /** + * Set properties to be dynamic (true) / static (false) + * + * @member {boolean[]} + * @private + */ + _this._properties = [false, true, false, false, false]; + + /** + * @member {number} + * @private + */ + _this._maxSize = maxSize; + + /** + * @member {number} + * @private + */ + _this._batchSize = batchSize; + + /** + * @member {object} + * @private + */ + _this._glBuffers = {}; + + /** + * @member {number} + * @private + */ + _this._bufferToUpdate = 0; + + /** + * @member {boolean} + * + */ + _this.interactiveChildren = false; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` + * to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Used for canvas renderering. If true then the elements will be positioned at the + * nearest pixel. This provides a nice speed boost. + * + * @member {boolean} + * @default true; + */ + _this.roundPixels = true; + + /** + * The texture used to render the children. + * + * @readonly + * @member {BaseTexture} + */ + _this.baseTexture = null; + + _this.setProperties(properties); + return _this; + } + + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * + * @param {object} properties - The properties to be uploaded + */ + + + ParticleContainer.prototype.setProperties = function setProperties(properties) { + if (properties) { + this._properties[0] = 'scale' in properties ? !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'alpha' in properties ? !!properties.alpha : this._properties[4]; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + ParticleContainer.prototype.updateTransform = function updateTransform() { + // TODO don't need to! + this.displayObjectUpdateTransform(); + // PIXI.Container.prototype.updateTransform.call( this ); + }; + + /** + * Renders the container using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer + */ + + + ParticleContainer.prototype.renderWebGL = function renderWebGL(renderer) { + var _this2 = this; + + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.hasLoaded) { + this.baseTexture.once('update', function () { + return _this2.onChildrenChange(0); + }); + } + } + + renderer.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + + /** + * Set the flag that static data should be updated to true + * + * @private + * @param {number} smallestChildIndex - The smallest child index + */ + + + ParticleContainer.prototype.onChildrenChange = function onChildrenChange(smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + + if (bufferIndex < this._bufferToUpdate) { + this._bufferToUpdate = bufferIndex; + } + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + + + ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var isRotated = true; + + var positionX = 0; + var positionY = 0; + + var finalWidth = 0; + var finalHeight = 0; + + var compositeOperation = renderer.blendModes[this.blendMode]; + + if (compositeOperation !== context.globalCompositeOperation) { + context.globalCompositeOperation = compositeOperation; + } + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i]; + + if (!child.visible) { + continue; + } + + var frame = child._texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) { + // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call + if (isRotated) { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx * renderer.resolution, transform.ty * renderer.resolution); + + isRotated = false; + } + + positionX = child.anchor.x * (-frame.width * child.scale.x) + child.position.x + 0.5; + positionY = child.anchor.y * (-frame.height * child.scale.y) + child.position.y + 0.5; + + finalWidth = frame.width * child.scale.x; + finalHeight = frame.height * child.scale.y; + } else { + if (!isRotated) { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + + if (renderer.roundPixels) { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution | 0, childTransform.ty * renderer.resolution | 0); + } else { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution, childTransform.ty * renderer.resolution); + } + + positionX = child.anchor.x * -frame.width + 0.5; + positionY = child.anchor.y * -frame.height + 0.5; + + finalWidth = frame.width; + finalHeight = frame.height; + } + + var resolution = child._texture.baseTexture.resolution; + + context.drawImage(child._texture.baseTexture.source, frame.x * resolution, frame.y * resolution, frame.width * resolution, frame.height * resolution, positionX * resolution, positionY * resolution, finalWidth * resolution, finalHeight * resolution); + } + }; + + /** + * Destroys the container + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + ParticleContainer.prototype.destroy = function destroy(options) { + _core$Container.prototype.destroy.call(this, options); + + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + } + + this._properties = null; + this._buffers = null; + }; + + return ParticleContainer; +}(core.Container); + +exports.default = ParticleContainer; + +},{"../core":63}],169:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ParticleContainer = require('./ParticleContainer'); + +Object.defineProperty(exports, 'ParticleContainer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleContainer).default; + } +}); + +var _ParticleRenderer = require('./webgl/ParticleRenderer'); + +Object.defineProperty(exports, 'ParticleRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleRenderer).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./ParticleContainer":168,"./webgl/ParticleRenderer":171}],170:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + +/** + * The particle buffer manages the static and dynamic buffers for a particle container. + * + * @class + * @private + * @memberof PIXI + */ +var ParticleBuffer = function () { + /** + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(gl, properties, dynamicPropertyFlags, size) { + _classCallCheck(this, ParticleBuffer); + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * Size of a single vertex. + * + * @member {number} + */ + this.vertSize = 2; + + /** + * Size of a single vertex in bytes. + * + * @member {number} + */ + this.vertByteSize = this.vertSize * 4; + + /** + * The number of particles the buffer can hold + * + * @member {number} + */ + this.size = size; + + /** + * A list of the properties that are dynamic. + * + * @member {object[]} + */ + this.dynamicProperties = []; + + /** + * A list of the properties that are static. + * + * @member {object[]} + */ + this.staticProperties = []; + + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attribute: property.attribute, + size: property.size, + uploadFunction: property.uploadFunction, + offset: property.offset + }; + + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } else { + this.staticProperties.push(property); + } + } + + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + + this.initBuffers(); + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + ParticleBuffer.prototype.initBuffers = function initBuffers() { + var gl = this.gl; + var dynamicOffset = 0; + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(this.size); + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + this.dynamicStride = 0; + + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + + this.dynamicData = new Float32Array(this.size * this.dynamicStride * 4); + this.dynamicBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.dynamicData, gl.STREAM_DRAW); + + // static // + var staticOffset = 0; + + this.staticStride = 0; + + for (var _i = 0; _i < this.staticProperties.length; ++_i) { + var _property = this.staticProperties[_i]; + + _property.offset = staticOffset; + staticOffset += _property.size; + this.staticStride += _property.size; + } + + this.staticData = new Float32Array(this.size * this.staticStride * 4); + this.staticBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.staticData, gl.STATIC_DRAW); + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(this.indexBuffer); + + for (var _i2 = 0; _i2 < this.dynamicProperties.length; ++_i2) { + var _property2 = this.dynamicProperties[_i2]; + + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.FLOAT, false, this.dynamicStride * 4, _property2.offset * 4); + } + + for (var _i3 = 0; _i3 < this.staticProperties.length; ++_i3) { + var _property3 = this.staticProperties[_i3]; + + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.FLOAT, false, this.staticStride * 4, _property3.offset * 4); + } + }; + + /** + * Uploads the dynamic properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadDynamic = function uploadDynamic(children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + + property.uploadFunction(children, startIndex, amount, this.dynamicData, this.dynamicStride, property.offset); + } + + this.dynamicBuffer.upload(); + }; + + /** + * Uploads the static properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadStatic = function uploadStatic(children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + + property.uploadFunction(children, startIndex, amount, this.staticData, this.staticStride, property.offset); + } + + this.staticBuffer.upload(); + }; + + /** + * Destroys the ParticleBuffer. + * + */ + + + ParticleBuffer.prototype.destroy = function destroy() { + this.dynamicProperties = null; + this.dynamicData = null; + this.dynamicBuffer.destroy(); + + this.staticProperties = null; + this.staticData = null; + this.staticBuffer.destroy(); + }; + + return ParticleBuffer; +}(); + +exports.default = ParticleBuffer; + +},{"../../core/utils/createIndicesForQuads":118,"pixi-gl-core":12}],171:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _ParticleShader = require('./ParticleShader'); + +var _ParticleShader2 = _interopRequireDefault(_ParticleShader); + +var _ParticleBuffer = require('./ParticleBuffer'); + +var _ParticleBuffer2 = _interopRequireDefault(_ParticleBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + +/** + * + * @class + * @private + * @memberof PIXI + */ +var ParticleRenderer = function (_core$ObjectRenderer) { + _inherits(ParticleRenderer, _core$ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + _classCallCheck(this, ParticleRenderer); + + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; + + /** + * The default shader that is used if a sprite doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + + _this.indexBuffer = null; + + _this.properties = null; + + _this.tempMatrix = new core.Matrix(); + + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * When there is a WebGL context change + * + * @private + */ + + + ParticleRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + + // setup default shader + this.shader = new _ParticleShader2.default(gl); + + this.properties = [ + // verticesData + { + attribute: this.shader.attributes.aVertexPosition, + size: 2, + uploadFunction: this.uploadVertices, + offset: 0 + }, + // positionData + { + attribute: this.shader.attributes.aPositionCoord, + size: 2, + uploadFunction: this.uploadPosition, + offset: 0 + }, + // rotationData + { + attribute: this.shader.attributes.aRotation, + size: 1, + uploadFunction: this.uploadRotation, + offset: 0 + }, + // uvsData + { + attribute: this.shader.attributes.aTextureCoord, + size: 2, + uploadFunction: this.uploadUvs, + offset: 0 + }, + // alphaData + { + attribute: this.shader.attributes.aColor, + size: 1, + uploadFunction: this.uploadAlpha, + offset: 0 + }]; + }; + + /** + * Starts a new particle batch. + * + */ + + + ParticleRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + }; + + /** + * Renders the particle container object. + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + */ + + + ParticleRenderer.prototype.render = function render(container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var renderer = this.renderer; + var totalChildren = children.length; + + if (totalChildren === 0) { + return; + } else if (totalChildren > maxSize) { + totalChildren = maxSize; + } + + var buffers = container._glBuffers[renderer.CONTEXT_UID]; + + if (!buffers) { + buffers = container._glBuffers[renderer.CONTEXT_UID] = this.generateBuffers(container); + } + + // if the uvs have not updated then no point rendering just yet! + this.renderer.setBlendMode(container.blendMode); + + var gl = renderer.gl; + + var m = container.worldTransform.copy(this.tempMatrix); + + m.prepend(renderer._activeRenderTarget.projectionMatrix); + + this.shader.uniforms.projectionMatrix = m.toArray(true); + this.shader.uniforms.uAlpha = container.worldAlpha; + + // make sure the texture is bound.. + var baseTexture = children[0]._texture.baseTexture; + + this.shader.uniforms.uSampler = renderer.bindTexture(baseTexture); + + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = totalChildren - i; + + if (amount > batchSize) { + amount = batchSize; + } + + var buffer = buffers[j]; + + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + + // we only upload the static content when we have to! + if (container._bufferToUpdate === j) { + buffer.uploadStatic(children, i, amount); + container._bufferToUpdate = j + 1; + } + + // bind the buffer + renderer.bindVao(buffer.vao); + buffer.vao.draw(gl.TRIANGLES, amount * 6); + } + }; + + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer[]} The buffers + */ + + + ParticleRenderer.prototype.generateBuffers = function generateBuffers(container) { + var gl = this.renderer.gl; + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + for (var i = 0; i < size; i += batchSize) { + buffers.push(new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize)); + } + + return buffers; + }; + + /** + * Uploads the verticies. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their vertices uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadVertices = function uploadVertices(children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - sprite.anchor.x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - sprite.anchor.y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - sprite.anchor.x); + w1 = orig.width * -sprite.anchor.x; + + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + + array[offset + stride * 2] = w0 * sx; + array[offset + stride * 2 + 1] = h0 * sy; + + array[offset + stride * 3] = w1 * sx; + array[offset + stride * 3 + 1] = h0 * sy; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their positions uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadPosition = function uploadPosition(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + + array[offset + stride * 2] = spritePosition.x; + array[offset + stride * 2 + 1] = spritePosition.y; + + array[offset + stride * 3] = spritePosition.x; + array[offset + stride * 3 + 1] = spritePosition.y; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadRotation = function uploadRotation(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + stride * 2] = spriteRotation; + array[offset + stride * 3] = spriteRotation; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadUvs = function uploadUvs(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + + array[offset + stride * 2] = textureUvs.x2; + array[offset + stride * 2 + 1] = textureUvs.y2; + + array[offset + stride * 3] = textureUvs.x3; + array[offset + stride * 3 + 1] = textureUvs.y3; + + offset += stride * 4; + } else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + + array[offset + stride * 2] = 0; + array[offset + stride * 2 + 1] = 0; + + array[offset + stride * 3] = 0; + array[offset + stride * 3 + 1] = 0; + + offset += stride * 4; + } + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadAlpha = function uploadAlpha(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteAlpha = children[startIndex + i].alpha; + + array[offset] = spriteAlpha; + array[offset + stride] = spriteAlpha; + array[offset + stride * 2] = spriteAlpha; + array[offset + stride * 3] = spriteAlpha; + + offset += stride * 4; + } + }; + + /** + * Destroys the ParticleRenderer. + * + */ + + + ParticleRenderer.prototype.destroy = function destroy() { + if (this.renderer.gl) { + this.renderer.gl.deleteBuffer(this.indexBuffer); + } + + _core$ObjectRenderer.prototype.destroy.call(this); + + this.shader.destroy(); + + this.indices = null; + this.tempMatrix = null; + }; + + return ParticleRenderer; +}(core.ObjectRenderer); + +exports.default = ParticleRenderer; + + +core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + +},{"../../core":63,"./ParticleBuffer":170,"./ParticleShader":172}],172:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../core/Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI + */ +var ParticleShader = function (_Shader) { + _inherits(ParticleShader, _Shader); + + /** + * @param {PIXI.Shader} gl - The webgl shader manager this shader works for. + */ + function ParticleShader(gl) { + _classCallCheck(this, ParticleShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'attribute float aColor;', 'attribute vec2 aPositionCoord;', 'attribute vec2 aScale;', 'attribute float aRotation;', 'uniform mat3 projectionMatrix;', 'varying vec2 vTextureCoord;', 'varying float vColor;', 'void main(void){', ' vec2 v = aVertexPosition;', ' v.x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);', ' v.y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);', ' v = v + aPositionCoord;', ' gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = aColor;', '}'].join('\n'), + // hello + ['varying vec2 vTextureCoord;', 'varying float vColor;', 'uniform sampler2D uSampler;', 'uniform float uAlpha;', 'void main(void){', ' vec4 color = texture2D(uSampler, vTextureCoord) * vColor * uAlpha;', ' if (color.a == 0.0) discard;', ' gl_FragColor = color;', '}'].join('\n'))); + } + + return ParticleShader; +}(_Shader3.default); + +exports.default = ParticleShader; + +},{"../../core/Shader":42}],173:[function(require,module,exports){ +"use strict"; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + +if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + + if (x === 0 || isNaN(x)) { + return x; + } + + return x > 0 ? 1 : -1; + }; +} + +},{}],174:[function(require,module,exports){ +'use strict'; + +var _objectAssign = require('object-assign'); + +var _objectAssign2 = _interopRequireDefault(_objectAssign); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +if (!Object.assign) { + Object.assign = _objectAssign2.default; +} // References: +// https://github.com/sindresorhus/object-assign +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + +},{"object-assign":5}],175:[function(require,module,exports){ +'use strict'; + +require('./Object.assign'); + +require('./requestAnimationFrame'); + +require('./Math.sign'); + +if (!window.ArrayBuffer) { + window.ArrayBuffer = Array; +} + +if (!window.Float32Array) { + window.Float32Array = Array; +} + +if (!window.Uint32Array) { + window.Uint32Array = Array; +} + +if (!window.Uint16Array) { + window.Uint16Array = Array; +} + +},{"./Math.sign":173,"./Object.assign":174,"./requestAnimationFrame":176}],176:[function(require,module,exports){ +(function (global){ +'use strict'; + +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + +// Expected to be used with Browserfiy +// Browserify automatically detects the use of `global` and passes the +// correct reference of `global`, `self`, and finally `window` + +var ONE_FRAME_TIME = 16; + +// Date.now +if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; +} + +// performance.now +if (!(global.performance && global.performance.now)) { + (function () { + var startTime = Date.now(); + + if (!global.performance) { + global.performance = {}; + } + + global.performance.now = function () { + return Date.now() - startTime; + }; + })(); +} + +// requestAnimationFrame +var lastTime = Date.now(); +var vendors = ['ms', 'moz', 'webkit', 'o']; + +for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { + var p = vendors[x]; + + global.requestAnimationFrame = global[p + 'RequestAnimationFrame']; + global.cancelAnimationFrame = global[p + 'CancelAnimationFrame'] || global[p + 'CancelRequestAnimationFrame']; +} + +if (!global.requestAnimationFrame) { + global.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + 'is not a function'); + } + + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + + if (delay < 0) { + delay = 0; + } + + lastTime = currentTime; + + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} + +if (!global.cancelAnimationFrame) { + global.cancelAnimationFrame = function (id) { + return clearTimeout(id); + }; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],177:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CountLimiter = require('./limiters/CountLimiter'); + +var _CountLimiter2 = _interopRequireDefault(_CountLimiter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SharedTicker = core.ticker.shared; + +/** + * Default number of uploads per frame using prepare plugin. + * + * @static + * @memberof PIXI.settings + * @name UPLOADS_PER_FRAME + * @type {number} + * @default 4 + */ +core.settings.UPLOADS_PER_FRAME = 4; + +/** + * The prepare manager provides functionality to upload content to the GPU. BasePrepare handles + * basic queuing functionality and is extended by {@link PIXI.prepare.WebGLPrepare} and {@link PIXI.prepare.CanvasPrepare} + * to provide preparation capabilities specific to their respective renderers. + * + * @abstract + * @class + * @memberof PIXI.prepare + */ + +var BasePrepare = function () { + /** + * @param {PIXI.SystemRenderer} renderer - A reference to the current renderer + */ + function BasePrepare(renderer) { + var _this = this; + + _classCallCheck(this, BasePrepare); + + /** + * The limiter to be used to control how quickly items are prepared. + * @type {PIXI.prepare.CountLimiter|PIXI.prepare.TimeLimiter} + */ + this.limiter = new _CountLimiter2.default(core.settings.UPLOADS_PER_FRAME); + + /** + * Reference to the renderer. + * @type {PIXI.SystemRenderer} + * @protected + */ + this.renderer = renderer; + + /** + * The only real difference between CanvasPrepare and WebGLPrepare is what they pass + * to upload hooks. That different parameter is stored here. + * @type {PIXI.prepare.CanvasPrepare|PIXI.WebGLRenderer} + * @protected + */ + this.uploadHookHelper = null; + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + /** + * 'bound' call for prepareItems(). + * @type {Function} + * @private + */ + this.delayedTick = function () { + // unlikely, but in case we were destroyed between tick() and delayedTick() + if (!_this.queue) { + return; + } + _this.prepareItems(); + }; + + this.register(findText, drawText); + this.register(findTextStyle, calculateTextStyle); + } + + /** + * Upload all the textures and graphics to the GPU. + * + * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item - + * Either the container or display object to search for items to upload, the items to upload themselves, + * or the callback function, if items have been added using `prepare.add`. + * @param {Function} [done] - Optional callback when all queued uploads have completed + */ + + + BasePrepare.prototype.upload = function upload(item, done) { + if (typeof item === 'function') { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) { + if (done) { + this.completes.push(done); + } + + if (!this.ticking) { + this.ticking = true; + SharedTicker.addOnce(this.tick, this); + } + } else if (done) { + done(); + } + }; + + /** + * Handle tick update + * + * @private + */ + + + BasePrepare.prototype.tick = function tick() { + setTimeout(this.delayedTick, 0); + }; + + /** + * Actually prepare items. This is handled outside of the tick because it will take a while + * and we do NOT want to block the current animation frame from rendering. + * + * @private + */ + + + BasePrepare.prototype.prepareItems = function prepareItems() { + this.limiter.beginFrame(); + // Upload the graphics + while (this.queue.length && this.limiter.allowedToUpload()) { + var item = this.queue[0]; + var uploaded = false; + + if (item && !item._destroyed) { + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.uploadHookHelper, item)) { + this.queue.shift(); + uploaded = true; + break; + } + } + } + + if (!uploaded) { + this.queue.shift(); + } + } + + // We're finished + if (!this.queue.length) { + this.ticking = false; + + var completes = this.completes.slice(0); + + this.completes.length = 0; + + for (var _i = 0, _len = completes.length; _i < _len; _i++) { + completes[_i](); + } + } else { + // if we are not finished, on the next rAF do this again + SharedTicker.addOnce(this.tick, this); + } + }; + + /** + * Adds hooks for finding and uploading items. + * + * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array` + function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.register = function register(addHook, uploadHook) { + if (addHook) { + this.addHooks.push(addHook); + } + + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + + return this; + }; + + /** + * Manually add an item to the uploading queue. + * + * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to + * add to the queue + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.add = function add(item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) { + for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { + this.add(item.children[_i2]); + } + } + + return this; + }; + + /** + * Destroys the plugin, don't use after this. + * + */ + + + BasePrepare.prototype.destroy = function destroy() { + if (this.ticking) { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.limiter = null; + this.uploadHookHelper = null; + }; + + return BasePrepare; +}(); + +/** + * Built-in hook to draw PIXI.Text to its texture. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = BasePrepare; +function drawText(helper, item) { + if (item instanceof core.Text) { + // updating text will return early if it is not dirty + item.updateText(true); + + return true; + } + + return false; +} + +/** + * Built-in hook to calculate a text style for a PIXI.Text object. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function calculateTextStyle(helper, item) { + if (item instanceof core.TextStyle) { + var font = core.Text.getFontStyle(item); + + if (!core.Text.fontPropertiesCache[font]) { + core.Text.calculateFontProperties(font); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find Text objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Text object was found. + */ +function findText(item, queue) { + if (item instanceof core.Text) { + // push the text style to prepare it - this can be really expensive + if (queue.indexOf(item.style) === -1) { + queue.push(item.style); + } + // also push the text object so that we can render it (to canvas/texture) if needed + if (queue.indexOf(item) === -1) { + queue.push(item); + } + // also push the Text's texture for upload to GPU + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find TextStyle objects. + * + * @private + * @param {PIXI.TextStyle} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.TextStyle object was found. + */ +function findTextStyle(item, queue) { + if (item instanceof core.TextStyle) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +},{"../core":63,"./limiters/CountLimiter":180}],178:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CANVAS_START_SIZE = 16; + +/** + * The prepare manager provides functionality to upload content to the GPU + * This cannot be done directly for Canvas like in WebGL, but the effect can be achieved by drawing + * textures to an offline canvas. + * This draw call will force the texture to be moved onto the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ + +var CanvasPrepare = function (_BasePrepare) { + _inherits(CanvasPrepare, _BasePrepare); + + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasPrepare(renderer) { + _classCallCheck(this, CanvasPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this; + + /** + * An offline canvas to render textures to + * @type {HTMLCanvasElement} + * @private + */ + _this.canvas = document.createElement('canvas'); + _this.canvas.width = CANVAS_START_SIZE; + _this.canvas.height = CANVAS_START_SIZE; + + /** + * The context to the canvas + * @type {CanvasRenderingContext2D} + * @private + */ + _this.ctx = _this.canvas.getContext('2d'); + + // Add textures to upload + _this.register(findBaseTextures, uploadBaseTextures); + return _this; + } + + /** + * Destroys the plugin, don't use after this. + * + */ + + + CanvasPrepare.prototype.destroy = function destroy() { + _BasePrepare.prototype.destroy.call(this); + this.ctx = null; + this.canvas = null; + }; + + return CanvasPrepare; +}(_BasePrepare3.default); + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {*} prepare - Instance of CanvasPrepare + * @param {*} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = CanvasPrepare; +function uploadBaseTextures(prepare, item) { + if (item instanceof core.BaseTexture) { + var image = item.source; + + // Sometimes images (like atlas images) report a size of zero, causing errors on windows phone. + // So if the width or height is equal to zero then use the canvas size + // Otherwise use whatever is smaller, the image dimensions or the canvas dimensions. + var imageWidth = image.width === 0 ? prepare.canvas.width : Math.min(prepare.canvas.width, image.width); + var imageHeight = image.height === 0 ? prepare.canvas.height : Math.min(prepare.canvas.height, image.height); + + // Only a small subsections is required to be drawn to have the whole texture uploaded to the GPU + // A smaller draw can be faster. + prepare.ctx.drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, prepare.canvas.width, prepare.canvas.height); + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item -Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTextures(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } else if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); + +},{"../../core":63,"../BasePrepare":177}],179:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLPrepare = require('./webgl/WebGLPrepare'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLPrepare).default; + } +}); + +var _CanvasPrepare = require('./canvas/CanvasPrepare'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasPrepare).default; + } +}); + +var _BasePrepare = require('./BasePrepare'); + +Object.defineProperty(exports, 'BasePrepare', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BasePrepare).default; + } +}); + +var _CountLimiter = require('./limiters/CountLimiter'); + +Object.defineProperty(exports, 'CountLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CountLimiter).default; + } +}); + +var _TimeLimiter = require('./limiters/TimeLimiter'); + +Object.defineProperty(exports, 'TimeLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TimeLimiter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./BasePrepare":177,"./canvas/CanvasPrepare":178,"./limiters/CountLimiter":180,"./limiters/TimeLimiter":181,"./webgl/WebGLPrepare":182}],180:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * CountLimiter limits the number of items handled by a {@link PIXI.prepare.BasePrepare} to a specified + * number of items per frame. + * + * @class + * @memberof PIXI + */ +var CountLimiter = function () { + /** + * @param {number} maxItemsPerFrame - The maximum number of items that can be prepared each frame. + */ + function CountLimiter(maxItemsPerFrame) { + _classCallCheck(this, CountLimiter); + + /** + * The maximum number of items that can be prepared each frame. + * @private + */ + this.maxItemsPerFrame = maxItemsPerFrame; + /** + * The number of items that can be prepared in the current frame. + * @type {number} + * @private + */ + this.itemsLeft = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + CountLimiter.prototype.beginFrame = function beginFrame() { + this.itemsLeft = this.maxItemsPerFrame; + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + CountLimiter.prototype.allowedToUpload = function allowedToUpload() { + return this.itemsLeft-- > 0; + }; + + return CountLimiter; +}(); + +exports.default = CountLimiter; + +},{}],181:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of milliseconds per frame. + * + * @class + * @memberof PIXI + */ +var TimeLimiter = function () { + /** + * @param {number} maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. + */ + function TimeLimiter(maxMilliseconds) { + _classCallCheck(this, TimeLimiter); + + /** + * The maximum milliseconds that can be spent preparing items each frame. + * @private + */ + this.maxMilliseconds = maxMilliseconds; + /** + * The start time of the current frame. + * @type {number} + * @private + */ + this.frameStart = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + TimeLimiter.prototype.beginFrame = function beginFrame() { + this.frameStart = Date.now(); + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + TimeLimiter.prototype.allowedToUpload = function allowedToUpload() { + return Date.now() - this.frameStart < this.maxMilliseconds; + }; + + return TimeLimiter; +}(); + +exports.default = TimeLimiter; + +},{}],182:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The prepare manager provides functionality to upload content to the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ +var WebGLPrepare = function (_BasePrepare) { + _inherits(WebGLPrepare, _BasePrepare); + + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLPrepare(renderer) { + _classCallCheck(this, WebGLPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this.renderer; + + // Add textures and graphics to upload + _this.register(findBaseTextures, uploadBaseTextures).register(findGraphics, uploadGraphics); + return _this; + } + + return WebGLPrepare; +}(_BasePrepare3.default); + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = WebGLPrepare; +function uploadBaseTextures(renderer, item) { + if (item instanceof core.BaseTexture) { + // if the texture already has a GL texture, then the texture has been prepared or rendered + // before now. If the texture changed, then the changer should be calling texture.update() which + // reuploads the texture without need for preparing it again + if (!item._glTextures[renderer.CONTEXT_UID]) { + renderer.textureManager.updateTexture(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to upload PIXI.Graphics to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadGraphics(renderer, item) { + if (item instanceof core.Graphics) { + // if the item is not dirty and already has webgl data, then it got prepared or rendered + // before now and we shouldn't waste time updating it again + if (item.dirty || item.clearDirty || !item._webGL[renderer.plugins.graphics.CONTEXT_UID]) { + renderer.plugins.graphics.updateGraphics(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTextures(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } else if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find graphics. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Graphics object was found. + */ +function findGraphics(item, queue) { + if (item instanceof core.Graphics) { + queue.push(item); + + return true; + } + + return false; +} + +core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); + +},{"../../core":63,"../BasePrepare":177}],183:[function(require,module,exports){ +(function (global){ +'use strict'; + +exports.__esModule = true; +exports.loader = exports.prepare = exports.particles = exports.mesh = exports.loaders = exports.interaction = exports.filters = exports.extras = exports.extract = exports.accessibility = undefined; + +var _polyfill = require('./polyfill'); + +Object.keys(_polyfill).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _polyfill[key]; + } + }); +}); + +var _deprecation = require('./deprecation'); + +Object.keys(_deprecation).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _deprecation[key]; + } + }); +}); + +var _core = require('./core'); + +Object.keys(_core).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _core[key]; + } + }); +}); + +var _accessibility = require('./accessibility'); + +var accessibility = _interopRequireWildcard(_accessibility); + +var _extract = require('./extract'); + +var extract = _interopRequireWildcard(_extract); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// export libs + + +// export core +_core.utils.mixins.performMixins(); + +// handle mixins now, after all code has been added, including deprecation +// import polyfills. Done as an export to make sure polyfills are imported first +exports.accessibility = accessibility; +exports.extract = extract; +exports.extras = extras; +exports.filters = filters; +exports.interaction = interaction; +exports.loaders = loaders; +exports.mesh = mesh; +exports.particles = particles; +exports.prepare = prepare; + +/** + * A premade instance of the loader that can be used to load resources. + * + * @name loader + * @memberof PIXI + * @property {PIXI.loaders.Loader} + */ + +var loader = loaders && loaders.Loader ? new loaders.Loader() : null; // check is there in case user excludes loader lib + +exports.loader = loader; + +// Always export pixi globally. + +global.PIXI = exports; // eslint-disable-line + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"./accessibility":40,"./core":63,"./deprecation":125,"./extract":127,"./extras":136,"./filters":147,"./interaction":154,"./loaders":157,"./mesh":166,"./particles":169,"./polyfill":175,"./prepare":179}]},{},[183])(183) +}); + + +//# sourceMappingURL=pixi.js.map diff --git a/js/pixi/4.4.4/pixi.min.js b/js/pixi/4.4.4/pixi.min.js new file mode 100644 index 0000000..4e5ef13 --- /dev/null +++ b/js/pixi/4.4.4/pixi.min.js @@ -0,0 +1,21 @@ +/*! + * pixi.js - v4.4.4 + * Compiled Fri, 31 Mar 2017 21:59:54 UTC + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.PIXI=t()}}(function(){var t;return function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var h=r[s]={exports:{}};e[s][0].call(h.exports,function(t){var r=e[s][1][t];return i(r?r:t)},h,h.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s0)-(t<0)},r.abs=function(t){var e=t>>i-1;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,e|=r,e|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,t=(858993459&t)+(t>>>2&858993459),16843009*(t+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,t&=15,27030>>>t&1};var o=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|o[t>>>16&255]<<8|o[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),t=65535&(t|t>>>16),t<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),t=1023&(t|t>>>16),t<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],2:[function(t,e,r){"use strict";function n(t,e,r){r=r||2;var n=e&&e.length,o=n?e[0]*r:t.length,a=i(t,0,o,r,!0),u=[];if(!a)return u;var l,h,f,d,p,v,y;if(n&&(a=c(t,e,a,r)),t.length>80*r){l=f=t[0],h=d=t[1];for(var g=r;gf&&(f=p),v>d&&(d=v);y=Math.max(f-l,d-h)}return s(a,u,r,l,h,y),u}function i(t,e,r,n,i){var o,s;if(i===A(t,e,r,n)>0)for(o=e;o=e;o-=n)s=M(o,t[o],t[o+1],s);return s&&T(s,s.next)&&(C(s),s=s.next),s}function o(t,e){if(!t)return t;e||(e=t);var r,n=t;do if(r=!1,n.steiner||!T(n,n.next)&&0!==x(n.prev,n,n.next))n=n.next;else{if(C(n),n=e=n.prev,n===n.next)return null;r=!0}while(r||n!==e);return e}function s(t,e,r,n,i,c,f){if(t){!f&&c&&v(t,n,i,c);for(var d,p,y=t;t.prev!==t.next;)if(d=t.prev,p=t.next,c?u(t,n,i,c):a(t))e.push(d.i/r),e.push(t.i/r),e.push(p.i/r),C(t),t=p.next,y=p.next;else if(t=p,t===y){f?1===f?(t=l(t,e,r),s(t,e,r,n,i,c,2)):2===f&&h(t,e,r,n,i,c):s(o(t),e,r,n,i,c,1);break}}}function a(t){var e=t.prev,r=t,n=t.next;if(x(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(_(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&x(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function u(t,e,r,n){var i=t.prev,o=t,s=t.next;if(x(i,o,s)>=0)return!1;for(var a=i.xo.x?i.x>s.x?i.x:s.x:o.x>s.x?o.x:s.x,h=i.y>o.y?i.y>s.y?i.y:s.y:o.y>s.y?o.y:s.y,c=g(a,u,e,r,n),f=g(l,h,e,r,n),d=t.nextZ;d&&d.z<=f;){if(d!==t.prev&&d!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,d.x,d.y)&&x(d.prev,d,d.next)>=0)return!1;d=d.nextZ}for(d=t.prevZ;d&&d.z>=c;){if(d!==t.prev&&d!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,d.x,d.y)&&x(d.prev,d,d.next)>=0)return!1;d=d.prevZ}return!0}function l(t,e,r){var n=t;do{var i=n.prev,o=n.next.next;!T(i,o)&&w(i,n,n.next,o)&&S(i,o)&&S(o,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(o.i/r),C(n),C(n.next),n=t=o),n=n.next}while(n!==t);return n}function h(t,e,r,n,i,a){var u=t;do{for(var l=u.next.next;l!==u.prev;){if(u.i!==l.i&&b(u,l)){var h=P(u,l);return u=o(u,u.next),h=o(h,h.next),s(u,e,r,n,i,a),void s(h,e,r,n,i,a)}l=l.next}u=u.next}while(u!==t)}function c(t,e,r,n){var s,a,u,l,h,c=[];for(s=0,a=e.length;s=n.next.y){var a=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=i&&a>s){if(s=a,a===i){if(o===n.y)return n;if(o===n.next.y)return n.next}r=n.x=n.x&&n.x>=h&&_(or.x)&&S(n,t)&&(r=n,f=u)),n=n.next;return r}function v(t,e,r,n){var i=t;do null===i.z&&(i.z=g(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,y(i)}function y(t){var e,r,n,i,o,s,a,u,l=1;do{for(r=t,t=null,o=null,s=0;r;){for(s++,n=r,a=0,e=0;e0||u>0&&n;)0===a?(i=n,n=n.nextZ,u--):0!==u&&n?r.z<=n.z?(i=r,r=r.nextZ,a--):(i=n,n=n.nextZ,u--):(i=r,r=r.nextZ,a--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;r=n}o.nextZ=null,l*=2}while(s>1);return t}function g(t,e,r,n,i){return t=32767*(t-r)/i,e=32767*(e-n)/i,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1}function m(t){var e=t,r=t;do e.x=0&&(t-s)*(n-a)-(r-s)*(e-a)>=0&&(r-s)*(o-a)-(i-s)*(n-a)>=0}function b(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!E(t,e)&&S(t,e)&&S(e,t)&&O(t,e)}function x(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function T(t,e){return t.x===e.x&&t.y===e.y}function w(t,e,r,n){return!!(T(t,e)&&T(r,n)||T(t,n)&&T(r,e))||x(t,e,r)>0!=x(t,e,n)>0&&x(r,n,t)>0!=x(r,n,e)>0}function E(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&w(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}function S(t,e){return x(t.prev,t,t.next)<0?x(t,e,t.next)>=0&&x(t,t.prev,e)>=0:x(t,e,t.prev)<0||x(t,t.next,e)<0}function O(t,e){var r=t,n=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do r.y>o!=r.next.y>o&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;while(r!==t);return n}function P(t,e){var r=new R(t.i,t.x,t.y),n=new R(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function M(t,e,r,n){var i=new R(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function C(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function R(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(t,e,r,n){for(var i=0,o=e,s=r-n;o0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],3:[function(t,e,r){"use strict";function n(){}function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function o(){this._events=new n,this._eventsCount=0}var s=Object.prototype.hasOwnProperty,a="~";Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(a=!1)),o.prototype.eventNames=function(){var t,e,r=[];if(0===this._eventsCount)return r;for(e in t=this._events)s.call(t,e)&&r.push(a?e.slice(1):e);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t,e){var r=a?a+t:t,n=this._events[r];if(e)return!!n;if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i=t.byteLength?n.bufferSubData(this.type,e,t):n.bufferData(this.type,t,this.drawType),this.data=t},i.prototype.bind=function(){var t=this.gl;t.bindBuffer(this.type,this.buffer)},i.createVertexBuffer=function(t,e,r){return new i(t,t.ARRAY_BUFFER,e,r)},i.createIndexBuffer=function(t,e,r){return new i(t,t.ELEMENT_ARRAY_BUFFER,e,r)},i.create=function(t,e,r,n){return new i(t,e,r,n)},i.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer)},e.exports=i},{}],7:[function(t,e,r){var n=t("./GLTexture"),i=function(t,e,r){this.gl=t,this.framebuffer=t.createFramebuffer(),this.stencil=null,this.texture=null,this.width=e||100,this.height=r||100};i.prototype.enableTexture=function(t){var e=this.gl;this.texture=t||new n(e),this.texture.bind(),this.bind(),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0)},i.prototype.enableStencil=function(){if(!this.stencil){var t=this.gl;this.stencil=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.stencil),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.stencil),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,this.width,this.height)}},i.prototype.clear=function(t,e,r,n){this.bind();var i=this.gl;i.clearColor(t,e,r,n),i.clear(i.COLOR_BUFFER_BIT)},i.prototype.bind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer)},i.prototype.unbind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)},i.prototype.resize=function(t,e){var r=this.gl;this.width=t,this.height=e,this.texture&&this.texture.uploadData(null,t,e),this.stencil&&(r.bindRenderbuffer(r.RENDERBUFFER,this.stencil),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e))},i.prototype.destroy=function(){var t=this.gl;this.texture&&this.texture.destroy(),t.deleteFramebuffer(this.framebuffer),this.gl=null,this.stencil=null,this.texture=null},i.createRGBA=function(t,e,r,o){var s=n.fromData(t,null,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},i.createFloat32=function(t,e,r,o){var s=new n.fromData(t,o,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},e.exports=i},{"./GLTexture":9}],8:[function(t,e,r){var n=t("./shader/compileProgram"),i=t("./shader/extractAttributes"),o=t("./shader/extractUniforms"),s=t("./shader/generateUniformAccessObject"),a=function(t,e,r){this.gl=t,this.program=n(t,e,r),this.attributes=i(t,this.program);var a=o(t,this.program);this.uniforms=s(t,a)};a.prototype.bind=function(){this.gl.useProgram(this.program)},a.prototype.destroy=function(){},e.exports=a},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18}],9:[function(t,e,r){var n=function(t,e,r,n,i){this.gl=t,this.texture=t.createTexture(),this.mipmap=!1,this.premultiplyAlpha=!1,this.width=e||-1,this.height=r||-1,this.format=n||t.RGBA,this.type=i||t.UNSIGNED_BYTE};n.prototype.upload=function(t){this.bind();var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var r=t.videoWidth||t.width,n=t.videoHeight||t.height;n!==this.height||r!==this.width?e.texImage2D(e.TEXTURE_2D,0,this.format,this.format,this.type,t):e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.format,this.type,t),this.width=r,this.height=n};var i=!1;n.prototype.uploadData=function(t,e,r){this.bind();var n=this.gl;if(t instanceof Float32Array){if(!i){var o=n.getExtension("OES_texture_float");if(!o)throw new Error("floating point textures not available");i=!0}this.type=n.FLOAT}else this.type=n.UNSIGNED_BYTE;n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),e!==this.width||r!==this.height?n.texImage2D(n.TEXTURE_2D,0,this.format,e,r,0,this.format,this.type,t||null):n.texSubImage2D(n.TEXTURE_2D,0,0,0,e,r,this.format,this.type,t||null),this.width=e,this.height=r},n.prototype.bind=function(t){var e=this.gl;void 0!==t&&e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,this.texture)},n.prototype.unbind=function(){var t=this.gl;t.bindTexture(t.TEXTURE_2D,null)},n.prototype.minFilter=function(t){var e=this.gl;this.bind(),this.mipmap?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.magFilter=function(t){var e=this.gl;this.bind(),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.enableMipmap=function(){var t=this.gl;this.bind(),this.mipmap=!0,t.generateMipmap(t.TEXTURE_2D)},n.prototype.enableLinearScaling=function(){this.minFilter(!0),this.magFilter(!0)},n.prototype.enableNearestScaling=function(){this.minFilter(!1),this.magFilter(!1)},n.prototype.enableWrapClamp=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)},n.prototype.enableWrapRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT)},n.prototype.enableWrapMirrorRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.MIRRORED_REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.MIRRORED_REPEAT)},n.prototype.destroy=function(){var t=this.gl;t.deleteTexture(this.texture)},n.fromSource=function(t,e,r){var i=new n(t);return i.premultiplyAlpha=r||!1,i.upload(e),i},n.fromData=function(t,e,r,i){var o=new n(t);return o.uploadData(e,r,i),o},e.exports=n},{}],10:[function(t,e,r){function n(t,e){if(this.nativeVaoExtension=null,n.FORCE_NATIVE||(this.nativeVaoExtension=t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object")),this.nativeState=e,this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var r=t.getParameter(t.MAX_VERTEX_ATTRIBS);this.nativeState={tempAttribState:new Array(r),attribState:new Array(r)}}this.gl=t,this.attributes=[],this.indexBuffer=null,this.dirty=!1}var i=t("./setVertexAttribArrays");n.prototype.constructor=n,e.exports=n,n.FORCE_NATIVE=!1,n.prototype.bind=function(){return this.nativeVao?(this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao),this.dirty&&(this.dirty=!1,this.activate())):this.activate(),this},n.prototype.unbind=function(){return this.nativeVao&&this.nativeVaoExtension.bindVertexArrayOES(null),this},n.prototype.activate=function(){for(var t=this.gl,e=null,r=0;r=0;n--){var i=t[n];"."===i?t.splice(n,1):".."===i?(t.splice(n,1),r++):r&&(t.splice(n,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}function n(t,e){if(t.filter)return t.filter(e);for(var r=[],n=0;n=-1&&!i;o--){var s=o>=0?arguments[o]:t.cwd();if("string"!=typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(r=s+"/"+r,i="/"===s.charAt(0))}return r=e(n(r.split("/"),function(t){return!!t}),!i).join("/"),(i?"/":"")+r||"."},r.normalize=function(t){var i=r.isAbsolute(t),o="/"===s(t,-1);return t=e(n(t.split("/"),function(t){return!!t}),!i).join("/"),t||i||(t="."),t&&o&&(t+="/"),(i?"/":"")+t},r.isAbsolute=function(t){return"/"===t.charAt(0)},r.join=function(){var t=Array.prototype.slice.call(arguments,0);return r.normalize(n(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},r.relative=function(t,e){function n(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=r.resolve(t).substr(1),e=r.resolve(e).substr(1);for(var i=n(t.split("/")),o=n(e.split("/")),s=Math.min(i.length,o.length),a=s,u=0;u1)for(var r=1;r1&&(n=r[0]+"@",t=r[1]),t=t.replace(D,".");var i=t.split("."),o=s(i,e).join(".");return n+o}function u(t){for(var e,r,n=[],i=0,o=t.length;i=55296&&e<=56319&&i65535&&(t-=65536,e+=j(t>>>10&1023|55296),t=56320|1023&t),e+=j(t)}).join("")}function h(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:w}function c(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function f(t,e,r){var n=0;for(t=r?F(t/P):t>>1,t+=F(t/e);t>N*S>>1;n+=w)t=F(t/N);return F(n+(N+1)*t/(t+O))}function d(t){var e,r,n,i,s,a,u,c,d,p,v=[],y=t.length,g=0,m=C,_=M;for(r=t.lastIndexOf(R),r<0&&(r=0),n=0;n=128&&o("not-basic"),v.push(t.charCodeAt(n));for(i=r>0?r+1:0;i=y&&o("invalid-input"),c=h(t.charCodeAt(i++)),(c>=w||c>F((T-g)/a))&&o("overflow"),g+=c*a,d=u<=_?E:u>=_+S?S:u-_,!(cF(T/p)&&o("overflow"),a*=p;e=v.length+1,_=f(g-s,e,0==s),F(g/e)>T-m&&o("overflow"),m+=F(g/e),g%=e,v.splice(g++,0,m)}return l(v)}function p(t){var e,r,n,i,s,a,l,h,d,p,v,y,g,m,_,b=[];for(t=u(t),y=t.length,e=C,r=0,s=M,a=0;a=e&&vF((T-r)/g)&&o("overflow"),r+=(l-e)*g,e=l,a=0;aT&&o("overflow"),v==e){for(h=r,d=w;p=d<=s?E:d>=s+S?S:d-s,!(h= 0x80 (not a basic code point)","invalid-input":"Invalid input"},N=w-E,F=Math.floor,j=String.fromCharCode;if(b={version:"1.4.1",ucs2:{decode:u,encode:l},decode:d,encode:p,toASCII:y,toUnicode:v},"function"==typeof t&&"object"==typeof t.amd&&t.amd)t("punycode",function(){return b});else if(g&&m)if(r.exports==g)m.exports=b;else for(x in b)b.hasOwnProperty(x)&&(g[x]=b[x]);else i.punycode=b}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],25:[function(t,e,r){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,r,o){e=e||"&",r=r||"=";var s={};if("string"!=typeof t||0===t.length)return s;var a=/\+/g;t=t.split(e);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var l=t.length;u>0&&l>u&&(l=u);for(var h=0;h=0?(c=v.substr(0,y),f=v.substr(y+1)):(c=v,f=""),d=decodeURIComponent(c),p=decodeURIComponent(f),n(s,d)?i(s[d])?s[d].push(p):s[d]=[s[d],p]:s[d]=p}return s};var i=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],26:[function(t,e,r){"use strict";function n(t,e){if(t.map)return t.map(e);for(var r=[],n=0;n",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(d),v=["'"].concat(p),y=["%","/","?",";","#"].concat(v),g=["/","?","#"],m=255,_=/^[+a-z0-9A-Z_-]{0,63}$/,b=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,x={javascript:!0,"javascript:":!0},T={javascript:!0,"javascript:":!0},w={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},E=t("querystring");n.prototype.parse=function(t,e,r){if(!l.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var n=t.indexOf("?"),i=n!==-1&&n127?"x":L[F];if(!N.match(_)){var B=I.slice(0,P),k=I.slice(P+1),U=L.match(b);U&&(B.push(U[1]),k.unshift(U[2])),k.length&&(a="/"+k.join(".")+a),this.hostname=B.join(".");break}}}this.hostname.length>m?this.hostname="":this.hostname=this.hostname.toLowerCase(),A||(this.hostname=u.toASCII(this.hostname));var X=this.port?":"+this.port:"",G=this.hostname||"";this.host=G+X,this.href+=this.host,A&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==a[0]&&(a="/"+a))}if(!x[p])for(var P=0,D=v.length;P0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return r.search=t.search,r.query=t.query,l.isNull(r.pathname)&&l.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!x.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var O=x.slice(-1)[0],P=(r.host||t.host||x.length>1)&&("."===O||".."===O)||""===O,M=0,C=x.length;C>=0;C--)O=x[C],"."===O?x.splice(C,1):".."===O?(x.splice(C,1),M++):M&&(x.splice(C,1),M--);if(!_&&!b)for(;M--;M)x.unshift("..");!_||""===x[0]||x[0]&&"/"===x[0].charAt(0)||x.unshift(""),P&&"/"!==x.join("/").substr(-1)&&x.push("");var R=""===x[0]||x[0]&&"/"===x[0].charAt(0);if(E){r.hostname=r.host=R?"":x.length?x.shift():"";var S=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return _=_||r.host&&x.length,_&&!R&&x.unshift(""),x.length?r.pathname=x.join("/"):(r.pathname=null,r.path=null),l.isNull(r.pathname)&&l.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},n.prototype.parseHost=function(){var t=this.host,e=c.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":29,punycode:24,querystring:27}],29:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],30:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a=t("mini-signals"),u=i(a),l=t("parse-uri"),h=i(l),c=t("./async"),f=n(c),d=t("./Resource"),p=i(d),v=100,y=/(#[\w-]+)?$/,g=function(){function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10;o(this,t),this.baseUrl=r,this.progress=0,this.loading=!1,this.defaultQueryString="",this._beforeMiddleware=[],this._afterMiddleware=[],this._resourcesParsing=[],this._boundLoadResource=function(t,r){return e._loadResource(t,r)},this._queue=f.queue(this._boundLoadResource,n),this._queue.pause(),this.resources={},this.onProgress=new u.default,this.onError=new u.default,this.onLoad=new u.default,this.onStart=new u.default,this.onComplete=new u.default}return t.prototype.add=function(t,e,r,n){if(Array.isArray(t)){for(var i=0;i0))return void this.abort("["+e.status+"] "+e.statusText+": "+e.responseURL);if(this.xhrType===t.XHR_RESPONSE_TYPE.TEXT)this.data=e.responseText,this.type=t.TYPE.TEXT;else if(this.xhrType===t.XHR_RESPONSE_TYPE.JSON)try{this.data=JSON.parse(e.responseText),this.type=t.TYPE.JSON}catch(t){return void this.abort("Error trying to parse loaded json: "+t)}else if(this.xhrType===t.XHR_RESPONSE_TYPE.DOCUMENT)try{if(window.DOMParser){var n=new DOMParser;this.data=n.parseFromString(e.responseText,"text/xml")}else{var i=document.createElement("div");i.innerHTML=e.responseText,this.data=i}this.type=t.TYPE.XML}catch(t){return void this.abort("Error trying to parse loaded xml: "+t)}else this.data=e.response||e.responseText;this.complete()},t.prototype._determineCrossOrigin=function(t,e){if(0===t.indexOf("data:"))return"";e=e||window.location,p||(p=document.createElement("a")),p.href=t,t=(0,h.default)(p.href,{strictMode:!0});var r=!t.port&&""===e.port||t.port===e.port,n=t.protocol?t.protocol+":":"";return t.host===e.hostname&&r&&n===e.protocol?"":"anonymous"},t.prototype._determineXhrType=function(){return t._xhrTypeMap[this.extension]||t.XHR_RESPONSE_TYPE.TEXT},t.prototype._determineLoadType=function(){return t._loadTypeMap[this.extension]||t.LOAD_TYPE.XHR},t.prototype._getExtension=function(){var t=this.url,e="";if(this.isDataUrl){var r=t.indexOf("/");e=t.substring(r+1,t.indexOf(";",r))}else{var n=t.indexOf("?");n!==-1&&(t=t.substring(0,n)),e=t.substring(t.lastIndexOf(".")+1)}return e.toLowerCase()},t.prototype._getMimeFromXhrType=function(e){switch(e){case t.XHR_RESPONSE_TYPE.BUFFER:return"application/octet-binary";case t.XHR_RESPONSE_TYPE.BLOB:return"application/blob";case t.XHR_RESPONSE_TYPE.DOCUMENT:return"application/xml";case t.XHR_RESPONSE_TYPE.JSON:return"application/json";case t.XHR_RESPONSE_TYPE.DEFAULT:case t.XHR_RESPONSE_TYPE.TEXT:default:return"text/plain"}},u(t,[{key:"isDataUrl",get:function(){return this._hasFlag(t.STATUS_FLAGS.DATA_URL)}},{key:"isComplete",get:function(){return this._hasFlag(t.STATUS_FLAGS.COMPLETE)}},{key:"isLoading",get:function(){return this._hasFlag(t.STATUS_FLAGS.LOADING)}}]),t}();r.default=m,m.STATUS_FLAGS={NONE:0,DATA_URL:1,COMPLETE:2,LOADING:4},m.TYPE={UNKNOWN:0,JSON:1,XML:2,IMAGE:3,AUDIO:4,VIDEO:5,TEXT:6},m.LOAD_TYPE={XHR:1,IMAGE:2,AUDIO:3,VIDEO:4},m.XHR_RESPONSE_TYPE={DEFAULT:"text",BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"},m._loadTypeMap={gif:m.LOAD_TYPE.IMAGE,png:m.LOAD_TYPE.IMAGE,bmp:m.LOAD_TYPE.IMAGE,jpg:m.LOAD_TYPE.IMAGE,jpeg:m.LOAD_TYPE.IMAGE,tif:m.LOAD_TYPE.IMAGE,tiff:m.LOAD_TYPE.IMAGE,webp:m.LOAD_TYPE.IMAGE,tga:m.LOAD_TYPE.IMAGE,svg:m.LOAD_TYPE.IMAGE,"svg+xml":m.LOAD_TYPE.IMAGE,mp3:m.LOAD_TYPE.AUDIO,ogg:m.LOAD_TYPE.AUDIO,wav:m.LOAD_TYPE.AUDIO,mp4:m.LOAD_TYPE.VIDEO,webm:m.LOAD_TYPE.VIDEO},m._xhrTypeMap={xhtml:m.XHR_RESPONSE_TYPE.DOCUMENT,html:m.XHR_RESPONSE_TYPE.DOCUMENT,htm:m.XHR_RESPONSE_TYPE.DOCUMENT,xml:m.XHR_RESPONSE_TYPE.DOCUMENT,tmx:m.XHR_RESPONSE_TYPE.DOCUMENT,svg:m.XHR_RESPONSE_TYPE.DOCUMENT,tsx:m.XHR_RESPONSE_TYPE.DOCUMENT,gif:m.XHR_RESPONSE_TYPE.BLOB,png:m.XHR_RESPONSE_TYPE.BLOB,bmp:m.XHR_RESPONSE_TYPE.BLOB,jpg:m.XHR_RESPONSE_TYPE.BLOB,jpeg:m.XHR_RESPONSE_TYPE.BLOB,tif:m.XHR_RESPONSE_TYPE.BLOB,tiff:m.XHR_RESPONSE_TYPE.BLOB,webp:m.XHR_RESPONSE_TYPE.BLOB,tga:m.XHR_RESPONSE_TYPE.BLOB,json:m.XHR_RESPONSE_TYPE.JSON,text:m.XHR_RESPONSE_TYPE.TEXT,txt:m.XHR_RESPONSE_TYPE.TEXT,ttf:m.XHR_RESPONSE_TYPE.BUFFER,otf:m.XHR_RESPONSE_TYPE.BUFFER},m.EMPTY_GIF="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="},{"mini-signals":36,"parse-uri":37}],32:[function(t,e,r){"use strict";function n(){}function i(t,e,r){var n=0,i=t.length;!function o(s){return s||n===i?void(r&&r(s)):void e(t[n++],o)}()}function o(t){return function(){if(null===t)throw new Error("Callback was already called.");var e=t;t=null,e.apply(this,arguments)}}function s(t,e){function r(t,e,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(a.started=!0,null==t&&a.idle())return void setTimeout(function(){return a.drain()},1);var i={data:t,callback:"function"==typeof r?r:n};e?a._tasks.unshift(i):a._tasks.push(i),setTimeout(function(){return a.process()},1)}function i(t){return function(){s-=1,t.callback.apply(t,arguments),null!=arguments[0]&&a.error(arguments[0],t.data),s<=a.concurrency-a.buffer&&a.unsaturated(),a.idle()&&a.drain(),a.process()}}if(null==e)e=1;else if(0===e)throw new Error("Concurrency must not be zero");var s=0,a={_tasks:[],concurrency:e,saturated:n,unsaturated:n,buffer:e/4,empty:n,drain:n,error:n,started:!1,paused:!1,push:function(t,e){r(t,!1,e)},kill:function(){s=0,a.drain=n,a.started=!1,a._tasks=[]},unshift:function(t,e){r(t,!0,e)},process:function(){for(;!a.paused&&s>2,o[1]=(3&n[0])<<4|n[1]>>4,o[2]=(15&n[1])<<2|n[2]>>6,o[3]=63&n[2];var a=r-(t.length-1);switch(a){case 2:o[3]=64,o[2]=64;break;case 1:o[3]=64}for(var u=0;u=0;r--)this.updateAccessibleObjects(e[r])}},t.prototype.update=function(){if(this.renderer.renderingToScreen){this.updateAccessibleObjects(this.renderer._lastObjectRendered);var t=this.renderer.view.getBoundingClientRect(),e=t.width/this.renderer.width,r=t.height/this.renderer.height,n=this.div;n.style.left=t.left+"px",n.style.top=t.top+"px",n.style.width=this.renderer.width+"px",n.style.height=this.renderer.height+"px";for(var i=0;ithis.renderer.width&&(t.width=this.renderer.width-t.x),t.y+t.height>this.renderer.height&&(t.height=this.renderer.height-t.y)},t.prototype.addChild=function(t){var e=this.pool.pop();e||(e=document.createElement("button"),e.style.width=d+"px",e.style.height=d+"px",e.style.backgroundColor=this.debug?"rgba(255,0,0,0.5)":"transparent",e.style.position="absolute",e.style.zIndex=y,e.style.borderStyle="none",e.addEventListener("click",this._onClick.bind(this)),e.addEventListener("focus",this._onFocus.bind(this)),e.addEventListener("focusout",this._onFocusOut.bind(this))),t.accessibleTitle?e.title=t.accessibleTitle:t.accessibleTitle||t.accessibleHint||(e.title="displayObject "+this.tabIndex),t.accessibleHint&&e.setAttribute("aria-label",t.accessibleHint),t._accessibleActive=!0,t._accessibleDiv=e,e.displayObject=t,this.children.push(t),this.div.appendChild(t._accessibleDiv),t._accessibleDiv.tabIndex=t.tabIndex},t.prototype._onClick=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"click",e.eventData)},t.prototype._onFocus=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseover",e.eventData)},t.prototype._onFocusOut=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseout",e.eventData)},t.prototype._onKeyDown=function(t){t.keyCode===f&&this.activate()},t.prototype._onMouseMove=function(){this.deactivate()},t.prototype.destroy=function(){this.div=null;for(var t=0;t4&&void 0!==arguments[4]&&arguments[4];i(this,t),this.renderer=(0,s.autoDetectRenderer)(e,r,n,o),this.stage=new u.default,this._ticker=null,this.ticker=a?l.shared:new l.Ticker,this.start()}return t.prototype.render=function(){this.renderer.render(this.stage)},t.prototype.stop=function(){this._ticker.stop()},t.prototype.start=function(){this._ticker.start()},t.prototype.destroy=function(t){this.stop(),this.ticker=null,this.stage.destroy(),this.stage=null,this.renderer.destroy(t),this.renderer=null},o(t,[{key:"ticker",set:function(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this)},get:function(){return this._ticker}},{key:"view",get:function(){return this.renderer.view}},{key:"screen",get:function(){return this.renderer.screen}}]),t}();r.default=h},{"./autoDetectRenderer":43,"./display/Container":46,"./ticker":116}],42:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t,e){if(t instanceof Array){if("precision"!==t[0].substring(0,9)){var r=t.slice(0);return r.unshift("precision "+e+" float;"),r}}else if("precision"!==t.substring(0,9))return"precision "+e+" float;\n"+t;return t}r.__esModule=!0;var u=t("pixi-gl-core"),l=t("./settings"),h=n(l),c=function(t){function e(r,n,s){return i(this,e),o(this,t.call(this,r,a(n,h.default.PRECISION_VERTEX),a(s,h.default.PRECISION_FRAGMENT)))}return s(e,t),e}(u.GLShader);r.default=c},{"./settings":99,"pixi-gl-core":12}],43:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:800,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:600,r=arguments[2],n=arguments[3];return!n&&a.isWebGLSupported()?new c.default(t,e,r):new l.default(t,e,r)}r.__esModule=!0,r.autoDetectRenderer=o;var s=t("./utils"),a=i(s),u=t("./renderers/canvas/CanvasRenderer"),l=n(u),h=t("./renderers/webgl/WebGLRenderer"),c=n(h)},{"./renderers/canvas/CanvasRenderer":75,"./renderers/webgl/WebGLRenderer":82,"./utils":120}],44:[function(t,e,r){"use strict";r.__esModule=!0;r.VERSION="4.4.4",r.PI_2=2*Math.PI,r.RAD_TO_DEG=180/Math.PI,r.DEG_TO_RAD=Math.PI/180,r.RENDERER_TYPE={UNKNOWN:0,WEBGL:1,CANVAS:2},r.BLEND_MODES={NORMAL:0,ADD:1,MULTIPLY:2,SCREEN:3,OVERLAY:4,DARKEN:5,LIGHTEN:6,COLOR_DODGE:7,COLOR_BURN:8,HARD_LIGHT:9,SOFT_LIGHT:10,DIFFERENCE:11,EXCLUSION:12,HUE:13,SATURATION:14,COLOR:15,LUMINOSITY:16},r.DRAW_MODES={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},r.SCALE_MODES={LINEAR:0,NEAREST:1},r.WRAP_MODES={CLAMP:0,REPEAT:1,MIRRORED_REPEAT:2},r.GC_MODES={AUTO:0,MANUAL:1},r.URL_FILE_EXTENSION=/\.(\w{3,4})(?:$|\?|#)/i,r.DATA_URI=/^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;(charset=[\w-]+|base64))?,(.*)/i,r.SVG_SIZE=/]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i,r.SHAPES={POLY:0,RECT:1,CIRC:2,ELIP:3,RREC:4},r.PRECISION={LOW:"lowp",MEDIUM:"mediump",HIGH:"highp"},r.TRANSFORM_MODE={STATIC:0,DYNAMIC:1},r.TEXT_GRADIENT={LINEAR_VERTICAL:0,LINEAR_HORIZONTAL:1}},{}],45:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../math"),o=function(){function t(){n(this,t),this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0),this.rect=null}return t.prototype.isEmpty=function(){return this.minX>this.maxX||this.minY>this.maxY},t.prototype.clear=function(){this.updateID++,this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0)},t.prototype.getRectangle=function(t){return this.minX>this.maxX||this.minY>this.maxY?i.Rectangle.EMPTY:(t=t||new i.Rectangle(0,0,1,1),t.x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)},t.prototype.addPoint=function(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)},t.prototype.addQuad=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY,o=t[0],s=t[1];e=on?o:n,i=s>i?s:i,o=t[2],s=t[3],e=on?o:n,i=s>i?s:i,o=t[4],s=t[5],e=on?o:n,i=s>i?s:i,o=t[6],s=t[7],e=on?o:n,i=s>i?s:i,this.minX=e,this.minY=r,this.maxX=n,this.maxY=i},t.prototype.addFrame=function(t,e,r,n,i){var o=t.worldTransform,s=o.a,a=o.b,u=o.c,l=o.d,h=o.tx,c=o.ty,f=this.minX,d=this.minY,p=this.maxX,v=this.maxY,y=s*e+u*r+h,g=a*e+l*r+c;f=yp?y:p,v=g>v?g:v,y=s*n+u*r+h,g=a*n+l*r+c,f=yp?y:p,v=g>v?g:v,y=s*e+u*i+h,g=a*e+l*i+c,f=yp?y:p,v=g>v?g:v,y=s*n+u*i+h,g=a*n+l*i+c,f=yp?y:p,v=g>v?g:v,this.minX=f,this.minY=d,this.maxX=p,this.maxY=v},t.prototype.addVertices=function(t,e,r,n){for(var i=t.worldTransform,o=i.a,s=i.b,a=i.c,u=i.d,l=i.tx,h=i.ty,c=this.minX,f=this.minY,d=this.maxX,p=this.maxY,v=r;vd?m:d,p=_>p?_:p}this.minX=c,this.minY=f,this.maxX=d,this.maxY=p},t.prototype.addBounds=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY;this.minX=t.minXn?t.maxX:n,this.maxY=t.maxY>i?t.maxY:i},t.prototype.addBoundsMask=function(t,e){var r=t.minX>e.minX?t.minX:e.minX,n=t.minY>e.minY?t.minY:e.minY,i=t.maxXu?i:u,this.maxY=o>l?o:l}},t.prototype.addBoundsArea=function(t,e){var r=t.minX>e.x?t.minX:e.x,n=t.minY>e.y?t.minY:e.y,i=t.maxXu?i:u,this.maxY=o>l?o:l}},t}();r.default=o},{"../math":68}],46:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r1)for(var r=0;rthis.children.length)throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length);return t.parent&&t.parent.removeChild(t),t.parent=this,t.transform._parentID=-1,this.children.splice(e,0,t),this._boundsID++,this.onChildrenChange(e),t.emit("added",this),t},e.prototype.swapChildren=function(t,e){if(t!==e){var r=this.getChildIndex(t),n=this.getChildIndex(e);this.children[r]=e,this.children[n]=t,this.onChildrenChange(r=this.children.length)throw new Error("The supplied index is out of bounds");var r=this.getChildIndex(t);(0,u.removeItems)(this.children,r,1),this.children.splice(e,0,t),this.onChildrenChange(e)},e.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Index ("+t+") does not exist.");return this.children[t]},e.prototype.removeChild=function(t){var e=arguments.length;if(e>1)for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=t,n="number"==typeof e?e:this.children.length,i=n-r,o=void 0;if(i>0&&i<=n){o=this.children.splice(r,i);for(var s=0;s2&&void 0!==arguments[2]&&arguments[2];return r||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)},e.prototype.toLocal=function(t,e,r,n){return e&&(t=e.toGlobal(t,r,n)),n||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,r)},e.prototype.renderWebGL=function(t){},e.prototype.renderCanvas=function(t){},e.prototype.setParent=function(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t},e.prototype.setTransform=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0,u=arguments.length>8&&void 0!==arguments[8]?arguments[8]:0;return this.position.x=t,this.position.y=e,this.scale.x=r?r:1,this.scale.y=n?n:1,this.rotation=i,this.skew.x=o,this.skew.y=s,this.pivot.x=a,this.pivot.y=u,this},e.prototype.destroy=function(){this.removeAllListeners(),this.parent&&this.parent.removeChild(this),this.transform=null,this.parent=null,this._bounds=null,this._currentBounds=null,this._mask=null,this.filterArea=null,this.interactive=!1,this.interactiveChildren=!1,this._destroyed=!0},a(e,[{key:"_tempDisplayObjectParent",get:function(){return null===this.tempDisplayObjectParent&&(this.tempDisplayObjectParent=new e),this.tempDisplayObjectParent}},{key:"x",get:function(){return this.position.x},set:function(t){this.transform.position.x=t}},{key:"y",get:function(){return this.position.y},set:function(t){this.transform.position.y=t}},{key:"worldTransform",get:function(){return this.transform.worldTransform}},{key:"localTransform",get:function(){return this.transform.localTransform}},{key:"position",get:function(){return this.transform.position},set:function(t){this.transform.position.copy(t)}},{key:"scale",get:function(){return this.transform.scale},set:function(t){this.transform.scale.copy(t)}},{key:"pivot",get:function(){return this.transform.pivot},set:function(t){this.transform.pivot.copy(t)}},{key:"skew",get:function(){return this.transform.skew},set:function(t){this.transform.skew.copy(t)}},{key:"rotation",get:function(){return this.transform.rotation},set:function(t){this.transform.rotation=t}},{key:"worldVisible",get:function(){var t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask&&(this._mask.renderable=!0),this._mask=t,this._mask&&(this._mask.renderable=!1)}},{key:"filters",get:function(){return this._filters&&this._filters.slice()},set:function(t){this._filters=t&&t.slice()}}]),e}(l.default);r.default=b,b.prototype.displayObjectUpdateTransform=b.prototype.updateTransform},{"../const":44,"../math":68,"../settings":99,"./Bounds":45,"./Transform":48,"./TransformStatic":50,eventemitter3:3}],48:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]&&arguments[0];i(this,e);var n=o(this,t.call(this));return n.fillAlpha=1,n.lineWidth=0,n.nativeLines=r,n.lineColor=0,n.graphicsData=[],n.tint=16777215,n._prevTint=16777215,n.blendMode=_.BLEND_MODES.NORMAL,n.currentPath=null,n._webGL={},n.isMask=!1,n.boundsPadding=0,n._localBounds=new x.default,n.dirty=0,n.fastRectDirty=-1,n.clearDirty=0,n.boundsDirty=-1,n.cachedSpriteDirty=!1,n._spriteRect=null,n._fastRect=!1,n}return s(e,t),e.prototype.clone=function t(){var t=new e;t.renderable=this.renderable,t.fillAlpha=this.fillAlpha,t.lineWidth=this.lineWidth,t.lineColor=this.lineColor,t.tint=this.tint,t.blendMode=this.blendMode,t.isMask=this.isMask,t.boundsPadding=this.boundsPadding,t.dirty=0,t.cachedSpriteDirty=this.cachedSpriteDirty;for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;if(this.lineWidth=t,this.lineColor=e,this.lineAlpha=r,this.currentPath)if(this.currentPath.shape.points.length){var n=new g.Polygon(this.currentPath.shape.points.slice(-2));n.closed=!1,this.drawShape(n)}else this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha;return this},e.prototype.moveTo=function(t,e){var r=new g.Polygon([t,e]);return r.closed=!1,this.drawShape(r),this},e.prototype.lineTo=function(t,e){return this.currentPath.shape.points.push(t,e),this.dirty++,this},e.prototype.quadraticCurveTo=function(t,e,r,n){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var i=20,o=this.currentPath.shape.points,s=0,a=0;0===o.length&&this.moveTo(0,0);for(var u=o[o.length-2],l=o[o.length-1],h=1;h<=i;++h){var c=h/i;s=u+(t-u)*c,a=l+(e-l)*c,o.push(s+(t+(r-t)*c-s)*c,a+(e+(n-e)*c-a)*c)}return this.dirty++,this},e.prototype.bezierCurveTo=function(t,e,r,n,i,o){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var s=this.currentPath.shape.points,a=s[s.length-2],u=s[s.length-1];return s.length-=2,(0,w.default)(a,u,t,e,r,n,i,o,s),this.dirty++,this},e.prototype.arcTo=function(t,e,r,n,i){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(t,e):this.moveTo(t,e);var o=this.currentPath.shape.points,s=o[o.length-2],a=o[o.length-1],u=a-e,l=s-t,h=n-e,c=r-t,f=Math.abs(u*c-l*h);if(f<1e-8||0===i)o[o.length-2]===t&&o[o.length-1]===e||o.push(t,e);else{var d=u*u+l*l,p=h*h+c*c,v=u*h+l*c,y=i*Math.sqrt(d)/f,g=i*Math.sqrt(p)/f,m=y*v/d,_=g*v/p,b=y*c+g*l,x=y*h+g*u,T=l*(g+m),w=u*(g+m),E=c*(y+_),S=h*(y+_),O=Math.atan2(w-x,T-b),P=Math.atan2(S-x,E-b);this.arc(b+t,x+e,i,O,P,l*h>c*u)}return this.dirty++,this},e.prototype.arc=function(t,e,r,n,i){var o=arguments.length>5&&void 0!==arguments[5]&&arguments[5];if(n===i)return this;!o&&i<=n?i+=2*Math.PI:o&&n<=i&&(n+=2*Math.PI);var s=i-n,a=40*Math.ceil(Math.abs(s)/(2*Math.PI));if(0===s)return this;var u=t+Math.cos(n)*r,l=e+Math.sin(n)*r,h=this.currentPath?this.currentPath.shape.points:null;h?h[h.length-2]===u&&h[h.length-1]===l||h.push(u,l):(this.moveTo(u,l),h=this.currentPath.shape.points);for(var c=s/(2*a),f=2*c,d=Math.cos(c),p=Math.sin(c),v=a-1,y=v%1/v,g=0;g<=v;++g){var m=g+y*g,_=c+n+f*m,b=Math.cos(_),x=-Math.sin(_);h.push((d*b+p*x)*r+t,(d*-x+p*b)*r+e)}return this.dirty++,this},e.prototype.beginFill=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this.filling=!0,this.fillColor=t,this.fillAlpha=e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},e.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},e.prototype.drawRect=function(t,e,r,n){return this.drawShape(new g.Rectangle(t,e,r,n)),this},e.prototype.drawRoundedRect=function(t,e,r,n,i){return this.drawShape(new g.RoundedRectangle(t,e,r,n,i)),this},e.prototype.drawCircle=function(t,e,r){return this.drawShape(new g.Circle(t,e,r)),this},e.prototype.drawEllipse=function(t,e,r,n){return this.drawShape(new g.Ellipse(t,e,r,n)),this},e.prototype.drawPolygon=function(t){var e=t,r=!0;if(e instanceof g.Polygon&&(r=e.closed,e=e.points),!Array.isArray(e)){e=new Array(arguments.length);for(var n=0;n0)&&(this.lineWidth=0,this.filling=!1,this.boundsDirty=-1,this.dirty++,this.clearDirty++,this.graphicsData.length=0),this.currentPath=null,this._spriteRect=null,this},e.prototype.isFastRect=function(){return 1===this.graphicsData.length&&this.graphicsData[0].shape.type===_.SHAPES.RECT&&!this.graphicsData[0].lineWidth},e.prototype._renderWebGL=function(t){this.dirty!==this.fastRectDirty&&(this.fastRectDirty=this.dirty,this._fastRect=this.isFastRect()),this._fastRect?this._renderSpriteRect(t):(t.setObjectRenderer(t.plugins.graphics),t.plugins.graphics.render(this))},e.prototype._renderSpriteRect=function(t){var e=this.graphicsData[0].shape;this._spriteRect||(this._spriteRect=new y.default(new f.default(f.default.WHITE)));var r=this._spriteRect;if(16777215===this.tint)r.tint=this.graphicsData[0].fillColor;else{var n=C,i=R;(0,m.hex2rgb)(this.graphicsData[0].fillColor,n),(0,m.hex2rgb)(this.tint,i),n[0]*=i[0],n[1]*=i[1],n[2]*=i[2],r.tint=(0,m.rgb2hex)(n)}r.alpha=this.graphicsData[0].fillAlpha,r.worldAlpha=this.worldAlpha*r.alpha,r.blendMode=this.blendMode,r.texture._frame.width=e.width,r.texture._frame.height=e.height,r.transform.worldTransform=this.transform.worldTransform,r.anchor.set(-e.x/e.width,-e.y/e.height),r._onAnchorUpdate(),r._renderWebGL(t)},e.prototype._renderCanvas=function(t){this.isMask!==!0&&t.plugins.graphics.render(this)},e.prototype._calculateBounds=function(){this.boundsDirty!==this.dirty&&(this.boundsDirty=this.dirty,this.updateLocalBounds(),this.cachedSpriteDirty=!0);var t=this._localBounds;this._bounds.addFrame(this.transform,t.minX,t.minY,t.maxX,t.maxY)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,M);for(var e=this.graphicsData,r=0;re?o+a:e,r=sn?s+u:n;else if(c===_.SHAPES.CIRC)o=i.x,s=i.y,a=i.radius+f/2,u=i.radius+f/2,t=o-ae?o+a:e,r=s-un?s+u:n;else if(c===_.SHAPES.ELIP)o=i.x,s=i.y,a=i.width+f/2,u=i.height+f/2,t=o-ae?o+a:e,r=s-un?s+u:n;else for(var d=i.points,p=0,v=0,y=0,g=0,m=0,b=0,x=0,T=0,w=0;w+2e?x+m:e,r=T-bn?T+b:n)}else t=0,e=0,r=0,n=0;var E=this.boundsPadding;this._localBounds.minX=t-E,this._localBounds.maxX=e+2*E,this._localBounds.minY=r-E,this._localBounds.maxY=n+2*E},e.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null;var e=new p.default(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,this.nativeLines,t);return this.graphicsData.push(e),e.type===_.SHAPES.POLY&&(e.shape.closed=e.shape.closed||this.filling,this.currentPath=e),this.dirty++,e},e.prototype.generateCanvasTexture=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=this.getLocalBounds(),n=h.default.create(r.width,r.height,t,e);O||(O=new S.default),this.transform.updateLocalTransform(),this.transform.localTransform.copy(P),P.invert(),P.tx-=r.x,P.ty-=r.y,O.render(this,n,!0,P);var i=f.default.fromCanvas(n.baseTexture._canvasRenderTarget.canvas,t);return i.baseTexture.resolution=e,i.baseTexture.update(),i},e.prototype.closePath=function(){var t=this.currentPath;return t&&t.shape&&t.shape.close(),this},e.prototype.addHole=function(){var t=this.graphicsData.pop();return this.currentPath=this.graphicsData[this.graphicsData.length-1],this.currentPath.addHole(t.shape),this.currentPath=null,this},e.prototype.destroy=function(e){t.prototype.destroy.call(this,e);for(var r=0;rC?C:M,r.beginPath(),r.moveTo(E,S+M),r.lineTo(E,S+P-M),r.quadraticCurveTo(E,S+P,E+M,S+P),r.lineTo(E+O-M,S+P),r.quadraticCurveTo(E+O,S+P,E+O,S+P-M),r.lineTo(E+O,S+M),r.quadraticCurveTo(E+O,S,E+O-M,S),r.lineTo(E+M,S),r.quadraticCurveTo(E,S,E,S+M),r.closePath(),(u.fillColor||0===u.fillColor)&&(r.globalAlpha=u.fillAlpha*n,r.fillStyle="#"+("00000"+(0|h).toString(16)).substr(-6),r.fill()),u.lineWidth&&(r.globalAlpha=u.lineAlpha*n,r.strokeStyle="#"+("00000"+(0|c).toString(16)).substr(-6),r.stroke())}}},t.prototype.updateGraphicsTint=function(t){t._prevTint=t.tint;for(var e=(t.tint>>16&255)/255,r=(t.tint>>8&255)/255,n=(255&t.tint)/255,i=0;i>16&255)/255*e*255<<16)+((s>>8&255)/255*r*255<<8)+(255&s)/255*n*255,o._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*r*255<<8)+(255&a)/255*n*255}},t.prototype.renderPolygon=function(t,e,r){r.moveTo(t[0],t[1]);for(var n=1;n8&&void 0!==arguments[8]?arguments[8]:[],l=20,h=0,c=0,f=0,d=0,p=0;u.push(t,e);for(var v=1,y=0;v<=l;++v)y=v/l,h=1-y,c=h*h,f=c*h,d=y*y,p=d*y,u.push(f*t+3*c*y*r+3*h*d*i+p*s,f*e+3*c*y*n+3*h*d*o+p*a);return u}r.__esModule=!0,r.default=n},{}],55:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../utils"),u=t("../../const"),l=t("../../renderers/webgl/utils/ObjectRenderer"),h=n(l),c=t("../../renderers/webgl/WebGLRenderer"),f=n(c),d=t("./WebGLGraphicsData"),p=n(d),v=t("./shaders/PrimitiveShader"),y=n(v),g=t("./utils/buildPoly"),m=n(g),_=t("./utils/buildRectangle"),b=n(_),x=t("./utils/buildRoundedRectangle"),T=n(x),w=t("./utils/buildCircle"),E=n(w),S=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.graphicsDataPool=[],n.primitiveShader=null,n.gl=r.gl,n.CONTEXT_UID=0,n}return s(e,t),e.prototype.onContextChange=function(){this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.primitiveShader=new y.default(this.gl)},e.prototype.destroy=function(){h.default.prototype.destroy.call(this);for(var t=0;t32e4)&&(r=this.graphicsDataPool.pop()||new p.default(this.renderer.gl,this.primitiveShader,this.renderer.state.attribsState),r.reset(e),t.data.push(r)),r.dirty=!0,r},e}(h.default);r.default=S,f.default.registerPlugin("graphics",S)},{"../../const":44,"../../renderers/webgl/WebGLRenderer":82,"../../renderers/webgl/utils/ObjectRenderer":92,"../../utils":120,"./WebGLGraphicsData":56,"./shaders/PrimitiveShader":57,"./utils/buildCircle":58,"./utils/buildPoly":60,"./utils/buildRectangle":61,"./utils/buildRoundedRectangle":62}],56:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("pixi-gl-core"),s=n(o),a=function(){function t(e,r,n){i(this,t),this.gl=e,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=s.default.GLBuffer.createVertexBuffer(e),this.indexBuffer=s.default.GLBuffer.createIndexBuffer(e),this.dirty=!0,this.glPoints=null,this.glIndices=null,this.shader=r,this.vao=new s.default.VertexArrayObject(e,n).addIndex(this.indexBuffer).addAttribute(this.buffer,r.attributes.aVertexPosition,e.FLOAT,!1,24,0).addAttribute(this.buffer,r.attributes.aColor,e.FLOAT,!1,24,8)}return t.prototype.reset=function(){this.points.length=0,this.indices.length=0},t.prototype.upload=function(){this.glPoints=new Float32Array(this.points),this.buffer.upload(this.glPoints),this.glIndices=new Uint16Array(this.indices),this.indexBuffer.upload(this.glIndices),this.dirty=!1},t.prototype.destroy=function(){this.color=null,this.points=null,this.indices=null,this.vao.destroy(),this.buffer.destroy(),this.indexBuffer.destroy(),this.gl=null,this.buffer=null,this.indexBuffer=null,this.glPoints=null,this.glIndices=null},t}();r.default=a},{"pixi-gl-core":12}],57:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../../Shader"),u=n(a),l=function(t){function e(r){return i(this,e),o(this,t.call(this,r,["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","uniform float alpha;","uniform vec3 tint;","varying vec4 vColor;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"].join("\n"),["varying vec4 vColor;","void main(void){"," gl_FragColor = vColor;","}"].join("\n")))}return s(e,t),e}(u.default);r.default=l},{"../../../Shader":42}],58:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,o=void 0,l=void 0;if(t.type===a.SHAPES.CIRC?(o=r.radius,l=r.radius):(o=r.width,l=r.height),0!==o&&0!==l){var h=Math.floor(30*Math.sqrt(r.radius))||Math.floor(15*Math.sqrt(r.width+r.height)),c=2*Math.PI/h;if(t.fill){var f=(0,u.hex2rgb)(t.fillColor),d=t.fillAlpha,p=f[0]*d,v=f[1]*d,y=f[2]*d,g=e.points,m=e.indices,_=g.length/6;m.push(_);for(var b=0;b196*p*p?(R=O-M,A=P-C,I=Math.sqrt(R*R+A*A),R/=I,A/=I,R*=p,A*=p,l.push(T-R,w-A),l.push(g,m,_,y),l.push(T+R,w+A),l.push(g,m,_,y),l.push(T-R,w-A),l.push(g,m,_,y),f++):(l.push(X,G),l.push(g,m,_,y),l.push(T-(X-T),w-(G-w)),l.push(g,m,_,y))}}b=r[2*(c-2)],x=r[2*(c-2)+1],T=r[2*(c-1)],w=r[2*(c-1)+1],O=-(x-w),P=b-T,I=Math.sqrt(O*O+P*P),O/=I,P/=I,O*=p,P*=p,l.push(T-O,w-P),l.push(g,m,_,y),l.push(T+O,w+P),l.push(g,m,_,y),h.push(d);for(var H=0;H=6){for(var n=[],i=t.holes,o=0;o0&&(0,s.default)(t,e)}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils"),u=t("earcut"),l=n(u)},{"../../../utils":120,"./buildLine":59,earcut:2}],61:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,o=r.width,u=r.height;if(t.fill){var l=(0,a.hex2rgb)(t.fillColor),h=t.fillAlpha,c=l[0]*h,f=l[1]*h,d=l[2]*h,p=e.points,v=e.indices,y=p.length/6;p.push(n,i),p.push(c,f,d,h),p.push(n+o,i),p.push(c,f,d,h),p.push(n,i+u),p.push(c,f,d,h),p.push(n+o,i+u),p.push(c,f,d,h),v.push(y,y,y+1,y+2,y+3,y+3)}if(t.lineWidth){var g=t.points;t.points=[n,i,n+o,i,n+o,i+u,n,i+u,n,i],(0,s.default)(t,e),t.points=g}}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils")},{"../../../utils":120,"./buildLine":59}],62:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){var r=t.shape,n=r.x,i=r.y,o=r.width,a=r.height,l=r.radius,f=[];if(f.push(n,i+l),s(n,i+a-l,n,i+a,n+l,i+a,f),s(n+o-l,i+a,n+o,i+a,n+o,i+a-l,f),s(n+o,i+l,n+o,i,n+o-l,i,f),s(n+l,i,n,i,n,i+l+1e-10,f),t.fill){for(var d=(0,c.hex2rgb)(t.fillColor),p=t.fillAlpha,v=d[0]*p,y=d[1]*p,g=d[2]*p,m=e.points,_=e.indices,b=m.length/6,x=(0,u.default)(f,null,2),T=0,w=x.length;T6&&void 0!==arguments[6]?arguments[6]:[],u=20,l=a,h=0,c=0,f=0,d=0,p=0,v=0,y=0,g=0;y<=u;++y)g=y/u,h=o(t,r,g),c=o(e,n,g),f=o(r,i,g),d=o(n,s,g),p=o(h,f,g),v=o(c,d,g),l.push(p,v);return l}r.__esModule=!0,r.default=i;var a=t("earcut"),u=n(a),l=t("./buildLine"),h=n(l),c=t("../../../utils")},{"../../../utils":120,"./buildLine":59,earcut:2}],63:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.autoDetectRenderer=r.Application=r.Filter=r.SpriteMaskFilter=r.Quad=r.RenderTarget=r.ObjectRenderer=r.WebGLManager=r.Shader=r.CanvasRenderTarget=r.TextureUvs=r.VideoBaseTexture=r.BaseRenderTexture=r.RenderTexture=r.BaseTexture=r.Texture=r.Spritesheet=r.CanvasGraphicsRenderer=r.GraphicsRenderer=r.GraphicsData=r.Graphics=r.TextStyle=r.Text=r.SpriteRenderer=r.CanvasTinter=r.CanvasSpriteRenderer=r.Sprite=r.TransformBase=r.TransformStatic=r.Transform=r.Container=r.DisplayObject=r.Bounds=r.glCore=r.WebGLRenderer=r.CanvasRenderer=r.ticker=r.utils=r.settings=void 0;var o=t("./const");Object.keys(o).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return o[t]}})});var s=t("./math");Object.keys(s).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return s[t]}})});var a=t("pixi-gl-core");Object.defineProperty(r,"glCore",{enumerable:!0,get:function(){return i(a).default}});var u=t("./display/Bounds");Object.defineProperty(r,"Bounds",{enumerable:!0,get:function(){return i(u).default}});var l=t("./display/DisplayObject");Object.defineProperty(r,"DisplayObject",{enumerable:!0,get:function(){return i(l).default}});var h=t("./display/Container");Object.defineProperty(r,"Container",{enumerable:!0,get:function(){return i(h).default}});var c=t("./display/Transform");Object.defineProperty(r,"Transform",{enumerable:!0,get:function(){return i(c).default}});var f=t("./display/TransformStatic");Object.defineProperty(r,"TransformStatic",{enumerable:!0,get:function(){return i(f).default}});var d=t("./display/TransformBase");Object.defineProperty(r,"TransformBase",{enumerable:!0,get:function(){return i(d).default}});var p=t("./sprites/Sprite");Object.defineProperty(r,"Sprite",{enumerable:!0,get:function(){return i(p).default}});var v=t("./sprites/canvas/CanvasSpriteRenderer");Object.defineProperty(r,"CanvasSpriteRenderer",{enumerable:!0,get:function(){return i(v).default}});var y=t("./sprites/canvas/CanvasTinter");Object.defineProperty(r,"CanvasTinter",{enumerable:!0,get:function(){return i(y).default}});var g=t("./sprites/webgl/SpriteRenderer");Object.defineProperty(r,"SpriteRenderer",{enumerable:!0,get:function(){return i(g).default}});var m=t("./text/Text");Object.defineProperty(r,"Text",{enumerable:!0,get:function(){return i(m).default}});var _=t("./text/TextStyle"); +Object.defineProperty(r,"TextStyle",{enumerable:!0,get:function(){return i(_).default}});var b=t("./graphics/Graphics");Object.defineProperty(r,"Graphics",{enumerable:!0,get:function(){return i(b).default}});var x=t("./graphics/GraphicsData");Object.defineProperty(r,"GraphicsData",{enumerable:!0,get:function(){return i(x).default}});var T=t("./graphics/webgl/GraphicsRenderer");Object.defineProperty(r,"GraphicsRenderer",{enumerable:!0,get:function(){return i(T).default}});var w=t("./graphics/canvas/CanvasGraphicsRenderer");Object.defineProperty(r,"CanvasGraphicsRenderer",{enumerable:!0,get:function(){return i(w).default}});var E=t("./textures/Spritesheet");Object.defineProperty(r,"Spritesheet",{enumerable:!0,get:function(){return i(E).default}});var S=t("./textures/Texture");Object.defineProperty(r,"Texture",{enumerable:!0,get:function(){return i(S).default}});var O=t("./textures/BaseTexture");Object.defineProperty(r,"BaseTexture",{enumerable:!0,get:function(){return i(O).default}});var P=t("./textures/RenderTexture");Object.defineProperty(r,"RenderTexture",{enumerable:!0,get:function(){return i(P).default}});var M=t("./textures/BaseRenderTexture");Object.defineProperty(r,"BaseRenderTexture",{enumerable:!0,get:function(){return i(M).default}});var C=t("./textures/VideoBaseTexture");Object.defineProperty(r,"VideoBaseTexture",{enumerable:!0,get:function(){return i(C).default}});var R=t("./textures/TextureUvs");Object.defineProperty(r,"TextureUvs",{enumerable:!0,get:function(){return i(R).default}});var A=t("./renderers/canvas/utils/CanvasRenderTarget");Object.defineProperty(r,"CanvasRenderTarget",{enumerable:!0,get:function(){return i(A).default}});var I=t("./Shader");Object.defineProperty(r,"Shader",{enumerable:!0,get:function(){return i(I).default}});var D=t("./renderers/webgl/managers/WebGLManager");Object.defineProperty(r,"WebGLManager",{enumerable:!0,get:function(){return i(D).default}});var L=t("./renderers/webgl/utils/ObjectRenderer");Object.defineProperty(r,"ObjectRenderer",{enumerable:!0,get:function(){return i(L).default}});var N=t("./renderers/webgl/utils/RenderTarget");Object.defineProperty(r,"RenderTarget",{enumerable:!0,get:function(){return i(N).default}});var F=t("./renderers/webgl/utils/Quad");Object.defineProperty(r,"Quad",{enumerable:!0,get:function(){return i(F).default}});var j=t("./renderers/webgl/filters/spriteMask/SpriteMaskFilter");Object.defineProperty(r,"SpriteMaskFilter",{enumerable:!0,get:function(){return i(j).default}});var B=t("./renderers/webgl/filters/Filter");Object.defineProperty(r,"Filter",{enumerable:!0,get:function(){return i(B).default}});var k=t("./Application");Object.defineProperty(r,"Application",{enumerable:!0,get:function(){return i(k).default}});var U=t("./autoDetectRenderer");Object.defineProperty(r,"autoDetectRenderer",{enumerable:!0,get:function(){return U.autoDetectRenderer}});var X=t("./utils"),G=n(X),W=t("./ticker"),H=n(W),V=t("./settings"),Y=i(V),z=t("./renderers/canvas/CanvasRenderer"),q=i(z),K=t("./renderers/webgl/WebGLRenderer"),Z=i(K);r.settings=Y.default,r.utils=G,r.ticker=H,r.CanvasRenderer=q.default,r.WebGLRenderer=Z.default},{"./Application":41,"./Shader":42,"./autoDetectRenderer":43,"./const":44,"./display/Bounds":45,"./display/Container":46,"./display/DisplayObject":47,"./display/Transform":48,"./display/TransformBase":49,"./display/TransformStatic":50,"./graphics/Graphics":51,"./graphics/GraphicsData":52,"./graphics/canvas/CanvasGraphicsRenderer":53,"./graphics/webgl/GraphicsRenderer":55,"./math":68,"./renderers/canvas/CanvasRenderer":75,"./renderers/canvas/utils/CanvasRenderTarget":77,"./renderers/webgl/WebGLRenderer":82,"./renderers/webgl/filters/Filter":84,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":87,"./renderers/webgl/managers/WebGLManager":91,"./renderers/webgl/utils/ObjectRenderer":92,"./renderers/webgl/utils/Quad":93,"./renderers/webgl/utils/RenderTarget":94,"./settings":99,"./sprites/Sprite":100,"./sprites/canvas/CanvasSpriteRenderer":101,"./sprites/canvas/CanvasTinter":102,"./sprites/webgl/SpriteRenderer":104,"./text/Text":106,"./text/TextStyle":107,"./textures/BaseRenderTexture":108,"./textures/BaseTexture":109,"./textures/RenderTexture":110,"./textures/Spritesheet":111,"./textures/Texture":112,"./textures/TextureUvs":113,"./textures/VideoBaseTexture":114,"./ticker":116,"./utils":120,"pixi-gl-core":12}],64:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){return t<0?-1:t>0?1:0}function o(){for(var t=0;t<16;t++){var e=[];d.push(e);for(var r=0;r<16;r++)for(var n=i(u[t]*u[r]+h[t]*l[r]),o=i(l[t]*u[r]+c[t]*l[r]),s=i(u[t]*h[r]+h[t]*c[r]),p=i(l[t]*h[r]+c[t]*c[r]),v=0;v<16;v++)if(u[v]===n&&l[v]===o&&h[v]===s&&c[v]===p){e.push(v);break}}for(var y=0;y<16;y++){var g=new a.default;g.set(u[y],l[y],h[y],c[y],0,0),f.push(g)}}r.__esModule=!0;var s=t("./Matrix"),a=n(s),u=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],l=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],h=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],c=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],f=[],d=[];o();var p={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MIRROR_HORIZONTAL:12,uX:function(t){return u[t]},uY:function(t){return l[t]},vX:function(t){return h[t]},vY:function(t){return c[t]},inv:function(t){return 8&t?15&t:7&-t},add:function(t,e){return d[t][e]},sub:function(t,e){return d[t][p.inv(e)]},rotate180:function(t){return 4^t},isSwapWidthHeight:function(t){return 2===(3&t)},byDirection:function(t,e){return 2*Math.abs(t)<=Math.abs(e)?e>=0?p.S:p.N:2*Math.abs(e)<=Math.abs(t)?t>0?p.E:p.W:e>0?t>0?p.SE:p.SW:t>0?p.NE:p.NW},matrixAppendRotationInv:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=f[p.inv(e)];i.tx=r,i.ty=n,t.append(i)}};r.default=p},{"./Matrix":65}],65:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:1,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;i(this,t),this.a=e,this.b=r,this.c=n,this.d=o,this.tx=s,this.ty=a,this.array=null}return t.prototype.fromArray=function(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]},t.prototype.set=function(t,e,r,n,i,o){return this.a=t,this.b=e,this.c=r,this.d=n,this.tx=i,this.ty=o,this},t.prototype.toArray=function(t,e){this.array||(this.array=new Float32Array(9));var r=e||this.array;return t?(r[0]=this.a,r[1]=this.b,r[2]=0,r[3]=this.c,r[4]=this.d,r[5]=0,r[6]=this.tx,r[7]=this.ty,r[8]=1):(r[0]=this.a,r[1]=this.c,r[2]=this.tx,r[3]=this.b,r[4]=this.d,r[5]=this.ty,r[6]=0,r[7]=0,r[8]=1),r},t.prototype.apply=function(t,e){e=e||new a.default;var r=t.x,n=t.y;return e.x=this.a*r+this.c*n+this.tx,e.y=this.b*r+this.d*n+this.ty,e},t.prototype.applyInverse=function(t,e){e=e||new a.default;var r=1/(this.a*this.d+this.c*-this.b),n=t.x,i=t.y;return e.x=this.d*r*n+-this.c*r*i+(this.ty*this.c-this.tx*this.d)*r,e.y=this.a*r*i+-this.b*r*n+(-this.ty*this.a+this.tx*this.b)*r,e},t.prototype.translate=function(t,e){return this.tx+=t,this.ty+=e,this},t.prototype.scale=function(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this},t.prototype.rotate=function(t){var e=Math.cos(t),r=Math.sin(t),n=this.a,i=this.c,o=this.tx;return this.a=n*e-this.b*r,this.b=n*r+this.b*e,this.c=i*e-this.d*r,this.d=i*r+this.d*e,this.tx=o*e-this.ty*r,this.ty=o*r+this.ty*e,this},t.prototype.append=function(t){var e=this.a,r=this.b,n=this.c,i=this.d;return this.a=t.a*e+t.b*n,this.b=t.a*r+t.b*i,this.c=t.c*e+t.d*n,this.d=t.c*r+t.d*i,this.tx=t.tx*e+t.ty*n+this.tx,this.ty=t.tx*r+t.ty*i+this.ty,this},t.prototype.setTransform=function(t,e,r,n,i,o,s,a,u){var l=Math.sin(s),h=Math.cos(s),c=Math.cos(u),f=Math.sin(u),d=-Math.sin(a),p=Math.cos(a),v=h*i,y=l*i,g=-l*o,m=h*o;return this.a=c*v+f*g,this.b=c*y+f*m,this.c=d*v+p*g,this.d=d*y+p*m,this.tx=t+(r*v+n*g),this.ty=e+(r*y+n*m),this},t.prototype.prepend=function(t){var e=this.tx;if(1!==t.a||0!==t.b||0!==t.c||1!==t.d){var r=this.a,n=this.c;this.a=r*t.a+this.b*t.c,this.b=r*t.b+this.b*t.d,this.c=n*t.a+this.d*t.c,this.d=n*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this},t.prototype.decompose=function(t){var e=this.a,r=this.b,n=this.c,i=this.d,o=-Math.atan2(-n,i),s=Math.atan2(r,e),a=Math.abs(o+s);return a<1e-5?(t.rotation=s,e<0&&i>=0&&(t.rotation+=t.rotation<=0?Math.PI:-Math.PI),t.skew.x=t.skew.y=0):(t.skew.x=o,t.skew.y=s),t.scale.x=Math.sqrt(e*e+r*r),t.scale.y=Math.sqrt(n*n+i*i),t.position.x=this.tx,t.position.y=this.ty,t},t.prototype.invert=function(){var t=this.a,e=this.b,r=this.c,n=this.d,i=this.tx,o=t*n-e*r;return this.a=n/o,this.b=-e/o,this.c=-r/o,this.d=t/o,this.tx=(r*this.ty-n*i)/o,this.ty=-(t*this.ty-e*i)/o,this},t.prototype.identity=function(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this},t.prototype.clone=function(){var e=new t;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e},t.prototype.copy=function(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t},o(t,null,[{key:"IDENTITY",get:function(){return new t}},{key:"TEMP_MATRIX",get:function(){return new t}}]),t}();r.default=u},{"./Point":67}],66:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this._x=i,this._y=o,this.cb=e,this.scope=r}return t.prototype.set=function(t,e){var r=t||0,n=e||(0!==e?r:0);this._x===r&&this._y===n||(this._x=r,this._y=n,this.cb.call(this.scope))},t.prototype.copy=function(t){this._x===t.x&&this._y===t.y||(this._x=t.x,this._y=t.y,this.cb.call(this.scope))},i(t,[{key:"x",get:function(){return this._x},set:function(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}},{key:"y",get:function(){return this._y},set:function(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}]),t}();r.default=o},{}],67:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;n(this,t),this.x=e,this.y=r}return t.prototype.clone=function(){return new t(this.x,this.y)},t.prototype.copy=function(t){this.set(t.x,t.y)},t.prototype.equals=function(t){return t.x===this.x&&t.y===this.y},t.prototype.set=function(t,e){this.x=t||0,this.y=e||(0!==e?this.x:0)},t}();r.default=i},{}],68:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./Point");Object.defineProperty(r,"Point",{enumerable:!0,get:function(){return n(i).default}});var o=t("./ObservablePoint");Object.defineProperty(r,"ObservablePoint",{enumerable:!0,get:function(){return n(o).default}});var s=t("./Matrix");Object.defineProperty(r,"Matrix",{enumerable:!0,get:function(){return n(s).default}});var a=t("./GroupD8");Object.defineProperty(r,"GroupD8",{enumerable:!0,get:function(){return n(a).default}});var u=t("./shapes/Circle");Object.defineProperty(r,"Circle",{enumerable:!0,get:function(){return n(u).default}});var l=t("./shapes/Ellipse");Object.defineProperty(r,"Ellipse",{enumerable:!0,get:function(){return n(l).default}});var h=t("./shapes/Polygon");Object.defineProperty(r,"Polygon",{enumerable:!0,get:function(){return n(h).default}});var c=t("./shapes/Rectangle");Object.defineProperty(r,"Rectangle",{enumerable:!0,get:function(){return n(c).default}});var f=t("./shapes/RoundedRectangle");Object.defineProperty(r,"RoundedRectangle",{enumerable:!0,get:function(){return n(f).default}})},{"./GroupD8":64,"./Matrix":65,"./ObservablePoint":66,"./Point":67,"./shapes/Circle":69,"./shapes/Ellipse":70,"./shapes/Polygon":71,"./shapes/Rectangle":72,"./shapes/RoundedRectangle":73}],69:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./Rectangle"),s=n(o),a=t("../../const"),u=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;i(this,t),this.x=e,this.y=r,this.radius=n,this.type=a.SHAPES.CIRC}return t.prototype.clone=function(){return new t(this.x,this.y,this.radius)},t.prototype.contains=function(t,e){if(this.radius<=0)return!1;var r=this.radius*this.radius,n=this.x-t,i=this.y-e;return n*=n,i*=i,n+i<=r},t.prototype.getBounds=function(){return new s.default(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)},t}();r.default=u},{"../../const":44,"./Rectangle":72}],70:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./Rectangle"),s=n(o),a=t("../../const"),u=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;i(this,t),this.x=e,this.y=r,this.width=n,this.height=o,this.type=a.SHAPES.ELIP}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;var r=(t-this.x)/this.width,n=(e-this.y)/this.height;return r*=r,n*=n,r+n<=1},t.prototype.getBounds=function(){return new s.default(this.x-this.width,this.y-this.height,this.width,this.height)},t}();r.default=u},{"../../const":44,"./Rectangle":72}],71:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../Point"),s=n(o),a=t("../../const"),u=function(){function t(){for(var e=arguments.length,r=Array(e),n=0;ne!=l>e&&t<(u-s)*((e-a)/(l-a))+s;h&&(r=!r)}return r},t}();r.default=u},{"../../const":44,"../Point":67}],72:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this.x=e,this.y=r,this.width=i,this.height=s,this.type=o.SHAPES.RECT}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this},t.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t=this.y&&et.x+t.width&&(this.width=t.width-this.x,this.width<0&&(this.width=0)),this.y+this.height>t.y+t.height&&(this.height=t.height-this.y,this.height<0&&(this.height=0))},t.prototype.enlarge=function(t){var e=Math.min(this.x,t.x),r=Math.max(this.x+this.width,t.x+t.width),n=Math.min(this.y,t.y),i=Math.max(this.y+this.height,t.y+t.height);this.x=e,this.width=r-e,this.y=n,this.height=i-n},i(t,[{key:"left",get:function(){return this.x}},{key:"right",get:function(){return this.x+this.width}},{key:"top",get:function(){return this.y}},{key:"bottom",get:function(){return this.y+this.height}}],[{key:"EMPTY",get:function(){return new t(0,0,0,0)}}]),t}();r.default=s},{"../../const":44}],73:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:20;n(this,t),this.x=e,this.y=r,this.width=o,this.height=s,this.radius=a,this.type=i.SHAPES.RREC}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height,this.radius)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){if(e>=this.y+this.radius&&e<=this.y+this.height-this.radius||t>=this.x+this.radius&&t<=this.x+this.width-this.radius)return!0;var r=t-(this.x+this.radius),n=e-(this.y+this.radius),i=this.radius*this.radius;if(r*r+n*n<=i)return!0;if(r=t-(this.x+this.width-this.radius),r*r+n*n<=i)return!0;if(n=e-(this.y+this.height-this.radius),r*r+n*n<=i)return!0;if(r=t-(this.x+this.radius),r*r+n*n<=i)return!0}return!1},t}();r.default=o},{"../../const":44}],74:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:{};i(this,e);var a=o(this,t.call(this,"Canvas",r,n,s));return a.type=y.RENDERER_TYPE.CANVAS,a.rootContext=a.view.getContext("2d",{alpha:a.transparent}),a.refresh=!0,a.maskManager=new h.default(a),a.smoothProperty="imageSmoothingEnabled",a.rootContext.imageSmoothingEnabled||(a.rootContext.webkitImageSmoothingEnabled?a.smoothProperty="webkitImageSmoothingEnabled":a.rootContext.mozImageSmoothingEnabled?a.smoothProperty="mozImageSmoothingEnabled":a.rootContext.oImageSmoothingEnabled?a.smoothProperty="oImageSmoothingEnabled":a.rootContext.msImageSmoothingEnabled&&(a.smoothProperty="msImageSmoothingEnabled")),a.initPlugins(),a.blendModes=(0,p.default)(),a._activeBlendMode=null,a.context=null,a.renderingToScreen=!1,a.resize(r,n),a}return s(e,t),e.prototype.render=function(t,e,r,n,i){if(this.view){this.renderingToScreen=!e,this.emit("prerender");var o=this.resolution;e?(e=e.baseTexture||e,e._canvasRenderTarget||(e._canvasRenderTarget=new f.default(e.width,e.height,e.resolution),e.source=e._canvasRenderTarget.canvas,e.valid=!0),this.context=e._canvasRenderTarget.context,this.resolution=e._canvasRenderTarget.resolution):this.context=this.rootContext;var s=this.context;if(e||(this._lastObjectRendered=t),!i){var a=t.parent,u=this._tempDisplayObjectParent.transform.worldTransform;n?(n.copy(u),this._tempDisplayObjectParent.transform._worldID=-1):u.identity(),t.parent=this._tempDisplayObjectParent,t.updateTransform(),t.parent=a}s.setTransform(1,0,0,1,0,0),s.globalAlpha=1,s.globalCompositeOperation=this.blendModes[y.BLEND_MODES.NORMAL],navigator.isCocoonJS&&this.view.screencanvas&&(s.fillStyle="black",s.clear()),(void 0!==r?r:this.clearBeforeRender)&&this.renderingToScreen&&(this.transparent?s.clearRect(0,0,this.width,this.height):(s.fillStyle=this._backgroundColorString,s.fillRect(0,0,this.width,this.height)));var l=this.context;this.context=s,t.renderCanvas(this),this.context=l,this.resolution=o,this.emit("postrender")}},e.prototype.clear=function(t){var e=this.context;t=t||this._backgroundColorString,!this.transparent&&t?(e.fillStyle=t,e.fillRect(0,0,this.width,this.height)):e.clearRect(0,0,this.width,this.height)},e.prototype.setBlendMode=function(t){this._activeBlendMode!==t&&(this._activeBlendMode=t,this.context.globalCompositeOperation=this.blendModes[t])},e.prototype.destroy=function(e){this.destroyPlugins(),t.prototype.destroy.call(this,e),this.context=null,this.refresh=!0,this.maskManager.destroy(),this.maskManager=null,this.smoothProperty=null},e.prototype.resize=function(e,r){t.prototype.resize.call(this,e,r),this.smoothProperty&&(this.rootContext[this.smoothProperty]=m.default.SCALE_MODE===y.SCALE_MODES.LINEAR)},e}(u.default);r.default=_,v.pluginTarget.mixin(_)},{"../../const":44,"../../settings":99,"../../utils":120,"../SystemRenderer":74,"./utils/CanvasMaskManager":76,"./utils/CanvasRenderTarget":77,"./utils/mapCanvasBlendModesToPixi":79}],76:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../../const"),o=function(){function t(e){n(this,t),this.renderer=e}return t.prototype.pushMask=function(t){var e=this.renderer;e.context.save();var r=t.alpha,n=t.transform.worldTransform,i=e.resolution;e.context.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t._texture||(this.renderGraphicsShape(t),e.context.clip()),t.worldAlpha=r},t.prototype.renderGraphicsShape=function(t){var e=this.renderer.context,r=t.graphicsData.length;if(0!==r){e.beginPath();for(var n=0;nS?S:E,e.moveTo(b,x+E),e.lineTo(b,x+w-E),e.quadraticCurveTo(b,x+w,b+E,x+w),e.lineTo(b+T-E,x+w),e.quadraticCurveTo(b+T,x+w,b+T,x+w-E),e.lineTo(b+T,x+E),e.quadraticCurveTo(b+T,x,b+T-E,x),e.lineTo(b+E,x),e.quadraticCurveTo(b,x,b,x+E),e.closePath()}}}},t.prototype.popMask=function(t){t.context.restore()},t.prototype.destroy=function(){},t}();r.default=o},{"../../../const":44}],77:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:[];return(0,a.default)()?(t[o.BLEND_MODES.NORMAL]="source-over",t[o.BLEND_MODES.ADD]="lighter",t[o.BLEND_MODES.MULTIPLY]="multiply",t[o.BLEND_MODES.SCREEN]="screen",t[o.BLEND_MODES.OVERLAY]="overlay",t[o.BLEND_MODES.DARKEN]="darken",t[o.BLEND_MODES.LIGHTEN]="lighten",t[o.BLEND_MODES.COLOR_DODGE]="color-dodge",t[o.BLEND_MODES.COLOR_BURN]="color-burn",t[o.BLEND_MODES.HARD_LIGHT]="hard-light",t[o.BLEND_MODES.SOFT_LIGHT]="soft-light",t[o.BLEND_MODES.DIFFERENCE]="difference",t[o.BLEND_MODES.EXCLUSION]="exclusion",t[o.BLEND_MODES.HUE]="hue",t[o.BLEND_MODES.SATURATION]="saturate",t[o.BLEND_MODES.COLOR]="color",t[o.BLEND_MODES.LUMINOSITY]="luminosity"):(t[o.BLEND_MODES.NORMAL]="source-over",t[o.BLEND_MODES.ADD]="lighter",t[o.BLEND_MODES.MULTIPLY]="source-over",t[o.BLEND_MODES.SCREEN]="source-over",t[o.BLEND_MODES.OVERLAY]="source-over",t[o.BLEND_MODES.DARKEN]="source-over",t[o.BLEND_MODES.LIGHTEN]="source-over",t[o.BLEND_MODES.COLOR_DODGE]="source-over",t[o.BLEND_MODES.COLOR_BURN]="source-over",t[o.BLEND_MODES.HARD_LIGHT]="source-over",t[o.BLEND_MODES.SOFT_LIGHT]="source-over",t[o.BLEND_MODES.DIFFERENCE]="source-over",t[o.BLEND_MODES.EXCLUSION]="source-over",t[o.BLEND_MODES.HUE]="source-over",t[o.BLEND_MODES.SATURATION]="source-over",t[o.BLEND_MODES.COLOR]="source-over",t[o.BLEND_MODES.LUMINOSITY]="source-over"),t}r.__esModule=!0,r.default=i;var o=t("../../../const"),s=t("./canUseNewCanvasBlendModes"),a=n(s)},{"../../../const":44,"./canUseNewCanvasBlendModes":78}],80:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../const"),s=t("../../settings"),a=n(s),u=function(){function t(e){i(this,t),this.renderer=e,this.count=0,this.checkCount=0,this.maxIdle=a.default.GC_MAX_IDLE,this.checkCountMax=a.default.GC_MAX_CHECK_COUNT,this.mode=a.default.GC_MODE}return t.prototype.update=function(){this.count++, +this.mode!==o.GC_MODES.MANUAL&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run()))},t.prototype.run=function(){for(var t=this.renderer.textureManager,e=t._managedTextures,r=!1,n=0;nthis.maxIdle&&(t.destroyTexture(i,!0),e[n]=null,r=!0)}if(r){for(var o=0,s=0;s=0;r--)this.unload(t.children[r])},t}();r.default=u},{"../../const":44,"../../settings":99}],81:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("pixi-gl-core"),s=t("../../const"),a=t("./utils/RenderTarget"),u=n(a),l=t("../../utils"),h=function(){function t(e){i(this,t),this.renderer=e,this.gl=e.gl,this._managedTextures=[]}return t.prototype.bindTexture=function(){},t.prototype.getTexture=function(){},t.prototype.updateTexture=function(t,e){var r=this.gl,n=!!t._glRenderTargets;if(!t.hasLoaded)return null;var i=this.renderer.boundTextures;if(void 0===e){e=0;for(var a=0;a2&&void 0!==arguments[2]?arguments[2]:{};i(this,e);var a=o(this,t.call(this,"WebGL",r,n,s));return a.legacy=!!s.legacy,a.legacy&&(D.default.VertexArrayObject.FORCE_NATIVE=!0),a.type=L.RENDERER_TYPE.WEBGL,a.handleContextLost=a.handleContextLost.bind(a),a.handleContextRestored=a.handleContextRestored.bind(a),a.view.addEventListener("webglcontextlost",a.handleContextLost,!1),a.view.addEventListener("webglcontextrestored",a.handleContextRestored,!1),a._contextOptions={alpha:a.transparent,antialias:s.antialias,premultipliedAlpha:a.transparent&&"notMultiplied"!==a.transparent,stencil:!0,preserveDrawingBuffer:s.preserveDrawingBuffer},a._backgroundColorRgba[3]=a.transparent?0:1,a.maskManager=new h.default(a),a.stencilManager=new f.default(a),a.emptyRenderer=new m.default(a),a.currentRenderer=a.emptyRenderer,a.initPlugins(),s.context&&(0,R.default)(s.context),a.gl=s.context||D.default.createContext(a.view,a._contextOptions),a.CONTEXT_UID=N++,a.state=new O.default(a.gl),a.renderingToScreen=!0,a.boundTextures=null,a._activeShader=null,a._activeVao=null,a._activeRenderTarget=null,a._initContext(),a.filterManager=new p.default(a),a.drawModes=(0,M.default)(a.gl),a._nextTextureLocation=0,a.setBlendMode(0),a}return s(e,t),e.prototype._initContext=function(){var t=this.gl;t.isContextLost()&&t.getExtension("WEBGL_lose_context")&&t.getExtension("WEBGL_lose_context").restoreContext();var e=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);this.boundTextures=new Array(e),this.emptyTextures=new Array(e),this.textureManager=new b.default(this),this.textureGC=new E.default(this),this.state.resetToDefault(),this.rootRenderTarget=new y.default(t,this.width,this.height,null,this.resolution,(!0)),this.rootRenderTarget.clearColor=this._backgroundColorRgba,this.bindRenderTarget(this.rootRenderTarget);var r=new D.default.GLTexture.fromData(t,null,1,1),n={_glTextures:{}};n._glTextures[this.CONTEXT_UID]={};for(var i=0;i 0.5)"," {"," color = vec4(1.0, 0.0, 0.0, 1.0);"," }"," else"," {"," color = vec4(0.0, 1.0, 0.0, 1.0);"," }"," gl_FragColor = mix(sample, masky, 0.5);"," gl_FragColor *= sample.a;","}"].join("\n")}}]),t}();r.default=d},{"../../../const":44,"../../../settings":99,"../../../utils":120,"./extractUniformsFromSrc":85}],85:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e,r){var n=o(t,r),i=o(e,r);return Object.assign(n,i)}function o(t){for(var e=new RegExp("^(projectionMatrix|uSampler|filterArea|filterClamp)$"),r={},n=void 0,i=t.replace(/\s+/g," ").split(/\s*;\s*/),o=0;o-1){var a=s.split(" "),l=a[1],h=a[2],c=1;h.indexOf("[")>-1&&(n=h.split(/\[|]/),h=n[0],c*=Number(n[1])),h.match(e)||(r[h]={value:u(l,c),name:h,type:l})}}return r}r.__esModule=!0,r.default=i;var s=t("pixi-gl-core"),a=n(s),u=a.default.shader.defaultValue},{"pixi-gl-core":12}],86:[function(t,e,r){"use strict";function n(t,e,r){var n=t.identity();return n.translate(e.x/r.width,e.y/r.height),n.scale(r.width,r.height),n}function i(t,e,r){var n=t.identity();n.translate(e.x/r.width,e.y/r.height);var i=r.width/e.width,o=r.height/e.height;return n.scale(i,o),n}function o(t,e,r,n){var i=n.worldTransform.copy(s.Matrix.TEMP_MATRIX),o=n._texture.baseTexture,a=t.identity(),u=r.height/r.width;a.translate(e.x/r.width,e.y/r.height),a.scale(1,u);var l=r.width/o.width,h=r.height/o.height;return i.tx/=o.width*l,i.ty/=o.width*l,i.invert(),a.prepend(i),a.scale(1,1/u),a.scale(l,h),a.translate(n.anchor.x,n.anchor.y),a}r.__esModule=!0,r.calculateScreenSpaceMatrix=n,r.calculateNormalizedScreenSpaceMatrix=i,r.calculateSpriteMatrix=o;var s=t("../../../math")},{"../../../math":68}],87:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../Filter"),u=n(a),l=t("../../../../math"),h=(t("path"),function(t){function e(r){i(this,e);var n=new l.Matrix,s=o(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n","varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n"));return r.renderable=!1,s.maskSprite=r,s.maskMatrix=n,s}return s(e,t),e.prototype.apply=function(t,e,r){var n=this.maskSprite;this.uniforms.mask=n._texture,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,n),this.uniforms.alpha=n.worldAlpha,t.applyFilter(this,e,r)},e}(u.default));r.default=h},{"../../../../math":68,"../Filter":84,path:22}],88:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var u=t("./WebGLManager"),l=i(u),h=t("../utils/RenderTarget"),c=i(h),f=t("../utils/Quad"),d=i(f),p=t("../../../math"),v=t("../../../Shader"),y=i(v),g=t("../filters/filterTransforms"),m=n(g),_=t("bit-twiddle"),b=i(_),x=function t(){a(this,t),this.renderTarget=null,this.sourceFrame=new p.Rectangle,this.destinationFrame=new p.Rectangle,this.filters=[],this.target=null,this.resolution=1},T=function(t){function e(r){a(this,e);var n=o(this,t.call(this,r));return n.gl=n.renderer.gl,n.quad=new d.default(n.gl,r.state.attribState),n.shaderCache={},n.pool={},n.filterData=null,n}return s(e,t),e.prototype.pushFilter=function(t,e){var r=this.renderer,n=this.filterData;if(!n){n=this.renderer._activeRenderTarget.filterStack;var i=new x;i.sourceFrame=i.destinationFrame=this.renderer._activeRenderTarget.size,i.renderTarget=r._activeRenderTarget,this.renderer._activeRenderTarget.filterData=n={index:0,stack:[i]},this.filterData=n}var o=n.stack[++n.index];o||(o=n.stack[n.index]=new x);var s=e[0].resolution,a=0|e[0].padding,u=t.filterArea||t.getBounds(!0),l=o.sourceFrame,h=o.destinationFrame;l.x=(u.x*s|0)/s,l.y=(u.y*s|0)/s,l.width=(u.width*s|0)/s,l.height=(u.height*s|0)/s,n.stack[0].renderTarget.transform||e[0].autoFit&&l.fit(n.stack[0].destinationFrame),l.pad(a),h.width=l.width,h.height=l.height;var c=this.getPotRenderTarget(r.gl,l.width,l.height,s);o.target=t,o.filters=e,o.resolution=s,o.renderTarget=c,c.setFrame(h,l),r.bindRenderTarget(c),c.clear()},e.prototype.popFilter=function(){var t=this.filterData,e=t.stack[t.index-1],r=t.stack[t.index];this.quad.map(r.renderTarget.size,r.sourceFrame).upload();var n=r.filters;if(1===n.length)n[0].apply(this,r.renderTarget,e.renderTarget,!1,r),this.freePotRenderTarget(r.renderTarget);else{var i=r.renderTarget,o=this.getPotRenderTarget(this.renderer.gl,r.sourceFrame.width,r.sourceFrame.height,r.resolution);o.setFrame(r.destinationFrame,r.sourceFrame),o.clear();var s=0;for(s=0;s0&&(e+="\nelse "),r1&&void 0!==arguments[1]?arguments[1]:[];return e[i.BLEND_MODES.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.ADD]=[t.ONE,t.DST_ALPHA],e[i.BLEND_MODES.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SCREEN]=[t.ONE,t.ONE_MINUS_SRC_COLOR],e[i.BLEND_MODES.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":44}],97:[function(t,e,r){"use strict";function n(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e[i.DRAW_MODES.POINTS]=t.POINTS,e[i.DRAW_MODES.LINES]=t.LINES,e[i.DRAW_MODES.LINE_LOOP]=t.LINE_LOOP,e[i.DRAW_MODES.LINE_STRIP]=t.LINE_STRIP,e[i.DRAW_MODES.TRIANGLES]=t.TRIANGLES,e[i.DRAW_MODES.TRIANGLE_STRIP]=t.TRIANGLE_STRIP,e[i.DRAW_MODES.TRIANGLE_FAN]=t.TRIANGLE_FAN,e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":44}],98:[function(t,e,r){"use strict";function n(t){var e=t.getContextAttributes();e.stencil||console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly")}r.__esModule=!0,r.default=n},{}],99:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./utils/maxRecommendedTextures"),o=n(i),s=t("./utils/canUploadSameBuffer"),a=n(s);r.default={TARGET_FPMS:.06,MIPMAP_TEXTURES:!0,RESOLUTION:1,FILTER_RESOLUTION:1,SPRITE_MAX_TEXTURES:(0,o.default)(32),SPRITE_BATCH_SIZE:4096,RETINA_PREFIX:/@([0-9\.]+)x/,RENDER_OPTIONS:{view:null,antialias:!1,forceFXAA:!1,autoResize:!1,transparent:!1,backgroundColor:0,clearBeforeRender:!0,preserveDrawingBuffer:!1,roundPixels:!1},TRANSFORM_MODE:0,GC_MODE:0,GC_MAX_IDLE:3600,GC_MAX_CHECK_COUNT:600,WRAP_MODE:0,SCALE_MODE:0,PRECISION_VERTEX:"highp",PRECISION_FRAGMENT:"mediump",CAN_UPLOAD_SAME_BUFFER:(0,a.default)()}},{"./utils/canUploadSameBuffer":117,"./utils/maxRecommendedTextures":121}],100:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rn&&v.xi&&v.y>16)+(65280&t)+((255&t)<<16)}},{key:"texture",get:function(){return this._texture},set:function(t){this._texture!==t&&(this._texture=t,this.cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,t&&(t.baseTexture.hasLoaded?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}]),e}(p.default);r.default=y},{"../const":44,"../display/Container":46,"../math":68,"../textures/Texture":112,"../utils":120}],101:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../renderers/canvas/CanvasRenderer"),s=n(o),a=t("../../const"),u=t("../../math"),l=t("./CanvasTinter"),h=n(l),c=new u.Matrix,f=function(){function t(e){i(this,t),this.renderer=e}return t.prototype.render=function(t){var e=t._texture,r=this.renderer,n=e._frame.width,i=e._frame.height,o=t.transform.worldTransform,s=0,l=0;if(!(e.orig.width<=0||e.orig.height<=0)&&e.baseTexture.source&&(r.setBlendMode(t.blendMode),e.valid)){r.context.globalAlpha=t.worldAlpha;var f=e.baseTexture.scaleMode===a.SCALE_MODES.LINEAR;r.smoothProperty&&r.context[r.smoothProperty]!==f&&(r.context[r.smoothProperty]=f),e.trim?(s=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,l=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(s=(.5-t.anchor.x)*e.orig.width,l=(.5-t.anchor.y)*e.orig.height),e.rotate&&(o.copy(c),o=c,u.GroupD8.matrixAppendRotationInv(o,e.rotate,s,l),s=0,l=0),s-=n/2,l-=i/2,r.roundPixels?(r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution|0,o.ty*r.resolution|0),s=0|s,l=0|l):r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution,o.ty*r.resolution);var d=e.baseTexture.resolution;16777215!==t.tint?(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=h.default.getTintedTexture(t,t.tint)),r.context.drawImage(t.tintedTexture,0,0,n*d,i*d,s*r.resolution,l*r.resolution,n*r.resolution,i*r.resolution)):r.context.drawImage(e.baseTexture.source,e._frame.x*d,e._frame.y*d,n*d,i*d,s*r.resolution,l*r.resolution,n*r.resolution,i*r.resolution)}},t.prototype.destroy=function(){this.renderer=null},t}();r.default=f,s.default.registerPlugin("sprite",f)},{"../../const":44,"../../math":68,"../../renderers/canvas/CanvasRenderer":75,"./CanvasTinter":102}],102:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("../../utils"),o=t("../../renderers/canvas/utils/canUseNewCanvasBlendModes"),s=n(o),a={getTintedTexture:function(t,e){var r=t.texture;e=a.roundColor(e);var n="#"+("00000"+(0|e).toString(16)).substr(-6);if(r.tintCache=r.tintCache||{},r.tintCache[n])return r.tintCache[n];var i=a.canvas||document.createElement("canvas");if(a.tintMethod(r,e,i),a.convertTintToImage){var o=new Image;o.src=i.toDataURL(),r.tintCache[n]=o}else r.tintCache[n]=i,a.canvas=null;return i},tintWithMultiply:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="multiply",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},tintWithOverlay:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.globalCompositeOperation="copy",n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},tintWithPerPixel:function(t,e,r){var n=r.getContext("2d"),o=t._frame.clone(),s=t.baseTexture.resolution;o.x*=s,o.y*=s,o.width*=s,o.height*=s,r.width=Math.ceil(o.width),r.height=Math.ceil(o.height),n.globalCompositeOperation="copy",n.drawImage(t.baseTexture.source,o.x,o.y,o.width,o.height,0,0,o.width,o.height);for(var a=(0,i.hex2rgb)(e),u=a[0],l=a[1],h=a[2],c=n.getImageData(0,0,o.width,o.height),f=c.data,d=0;d=this.size&&this.flush(),t._texture._uvs&&(this.sprites[this.currentIndex++]=t)},e.prototype.flush=function(){if(0!==this.currentIndex){var t=this.renderer.gl,e=this.MAX_TEXTURES,r=E.default.nextPow2(this.currentIndex),n=E.default.log2(r),i=this.buffers[n],o=this.sprites,s=this.groups,a=i.float32View,u=i.uint32View,l=this.boundTextures,h=this.renderer.boundTextures,c=this.renderer.textureGC.count,f=0,d=void 0,p=void 0,v=1,y=0,g=s[0],m=void 0,_=void 0,x=o[0].blendMode;g.textureCount=0,g.start=0,g.blend=x,S++;var w=void 0;for(w=0;w0&&(e+="\nelse "),r0?this.context.shadowColor=r.dropShadowColor:this.context.fillStyle=r.dropShadowColor;for(var v=Math.cos(r.dropShadowAngle)*r.dropShadowDistance,y=Math.sin(r.dropShadowAngle)*r.dropShadowDistance,g=0;g3&&void 0!==arguments[3]&&arguments[3],i=this._style,o=i.letterSpacing;if(0===o)return void(n?this.context.strokeText(t,e,r):this.context.fillText(t,e,r));for(var s=String.prototype.split.call(t,""),a=e,u=0,l="";ui)for(var h=a[u].split(""),c=0;cs?(e+="\n"+h[c],s=i-f):(0===c&&(e+=" "),e+=h[c],s-=f)}else{var d=l+this.context.measureText(" ").width;0===u||d>s?(u>0&&(e+="\n"),e+=a[u],s=i-l):(s-=d,e+=" "+a[u])}}o=0;n--){var i=r[n].trim();/([\"\'])[^\'\"]+\1/.test(i)||(i='"'+i+'"'),r[n]=i}return t.fontStyle+" "+t.fontVariant+" "+t.fontWeight+" "+e+" "+r.join(",")},e.calculateFontProperties=function(t){if(e.fontPropertiesCache[t])return e.fontPropertiesCache[t];var r={},n=e.fontPropertiesCanvas,i=e.fontPropertiesContext;i.font=t;var o=Math.ceil(i.measureText("|MÉq").width),s=Math.ceil(i.measureText("M").width),a=2*s;s=1.4*s|0,n.width=o,n.height=a,i.fillStyle="#f00",i.fillRect(0,0,o,a),i.font=t,i.textBaseline="alphabetic",i.fillStyle="#000",i.fillText("|MÉq",0,s);var u=i.getImageData(0,0,o,a).data,l=u.length,h=4*o,c=0,f=0,d=!1;for(c=0;cs;--c){for(var v=0;v0&&void 0!==arguments[0]?arguments[0]:100,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,s=arguments[2],a=arguments[3];i(this,e);var u=o(this,t.call(this,null,s));return u.resolution=a||h.default.RESOLUTION,u.width=r,u.height=n,u.realWidth=u.width*u.resolution,u.realHeight=u.height*u.resolution,u.scaleMode=void 0!==s?s:h.default.SCALE_MODE,u.hasLoaded=!0,u._glRenderTargets={},u._canvasRenderTarget=null,u.valid=!1,u}return s(e,t),e.prototype.resize=function(t,e){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.realWidth=this.width*this.resolution,this.realHeight=this.height*this.resolution,this.valid&&this.emit("update",this))},e.prototype.destroy=function(){t.prototype.destroy.call(this,!0),this.renderer=null},e}(u.default);r.default=c},{"../settings":99,"./BaseTexture":109}],109:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u=t("../utils"),l=t("../settings"),h=n(l),c=t("eventemitter3"),f=n(c),d=t("../utils/determineCrossOrigin"),p=n(d),v=t("bit-twiddle"),y=n(v),g=function(t){function e(r,n,s){i(this,e);var a=o(this,t.call(this));return a.uid=(0,u.uid)(),a.touched=0,a.resolution=s||h.default.RESOLUTION,a.width=100,a.height=100,a.realWidth=100,a.realHeight=100,a.scaleMode=void 0!==n?n:h.default.SCALE_MODE,a.hasLoaded=!1,a.isLoading=!1,a.source=null,a.origSource=null,a.imageType=null,a.sourceScale=1,a.premultipliedAlpha=!0,a.imageUrl=null,a.isPowerOfTwo=!1,a.mipmap=h.default.MIPMAP_TEXTURES,a.wrapMode=h.default.WRAP_MODE,a._glTextures={},a._enabled=0,a._virtalBoundId=-1,r&&a.loadSource(r),a._destroyed=!1,a}return s(e,t),e.prototype.update=function(){"svg"!==this.imageType&&(this.realWidth=this.source.naturalWidth||this.source.videoWidth||this.source.width,this.realHeight=this.source.naturalHeight||this.source.videoHeight||this.source.height,this._updateDimensions()),this.emit("update",this)},e.prototype._updateDimensions=function(){this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=y.default.isPow2(this.realWidth)&&y.default.isPow2(this.realHeight)},e.prototype.loadSource=function(t){var e=this,r=this.isLoading;this.hasLoaded=!1,this.isLoading=!1,r&&this.source&&(this.source.onload=null,this.source.onerror=null);var n=!this.source;if(this.source=t,(t.src&&t.complete||t.getContext)&&t.width&&t.height)this._updateImageType(),"svg"===this.imageType?this._loadSvgSource():this._sourceLoaded(),n&&this.emit("loaded",this);else if(!t.getContext){var i=function(){e.isLoading=!0;var n=e;if(t.onload=function(){if(n._updateImageType(),t.onload=null,t.onerror=null,n.isLoading)return n.isLoading=!1,n._sourceLoaded(),"svg"===n.imageType?void n._loadSvgSource():void n.emit("loaded",n)},t.onerror=function(){t.onload=null,t.onerror=null,n.isLoading&&(n.isLoading=!1,n.emit("error",n))},t.complete&&t.src){if(t.onload=null,t.onerror=null,"svg"===n.imageType)return n._loadSvgSource(),{v:void 0};e.isLoading=!1,t.width&&t.height?(e._sourceLoaded(),r&&e.emit("loaded",e)):r&&e.emit("error",e)}}();if("object"===("undefined"==typeof i?"undefined":a(i)))return i.v}},e.prototype._updateImageType=function(){if(this.imageUrl){var t=(0,u.decomposeDataUri)(this.imageUrl),e=void 0;if(t&&"image"===t.mediaType){var r=t.subType.split("+")[0];if(e=(0,u.getUrlFileExtension)("."+r),!e)throw new Error("Invalid image type in data URI.")}else e=(0,u.getUrlFileExtension)(this.imageUrl),e||(e="png");this.imageType=e}},e.prototype._loadSvgSource=function(){if("svg"===this.imageType){var t=(0,u.decomposeDataUri)(this.imageUrl);t?this._loadSvgSourceUsingDataUri(t):this._loadSvgSourceUsingXhr()}},e.prototype._loadSvgSourceUsingDataUri=function(t){var e=void 0;if("base64"===t.encoding){if(!atob)throw new Error("Your browser doesn't support base64 conversions.");e=atob(t.data)}else e=t.data;this._loadSvgSourceUsingString(e)},e.prototype._loadSvgSourceUsingXhr=function(){var t=this,e=new XMLHttpRequest;e.onload=function(){if(e.readyState!==e.DONE||200!==e.status)throw new Error("Failed to load SVG using XHR.");t._loadSvgSourceUsingString(e.response)},e.onerror=function(){return t.emit("error",t)},e.open("GET",this.imageUrl,!0),e.send()},e.prototype._loadSvgSourceUsingString=function(t){var e=(0,u.getSvgSize)(t),r=e.width,n=e.height;if(!r||!n)throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them.");this.realWidth=Math.round(r*this.sourceScale),this.realHeight=Math.round(n*this.sourceScale),this._updateDimensions();var i=document.createElement("canvas");i.width=this.realWidth,i.height=this.realHeight,i._pixiId="canvas_"+(0,u.uid)(),i.getContext("2d").drawImage(this.source,0,0,r,n,0,0,this.realWidth,this.realHeight),this.origSource=this.source,this.source=i,u.BaseTextureCache[i._pixiId]=this,this.isLoading=!1,this._sourceLoaded(),this.emit("loaded",this)},e.prototype._sourceLoaded=function(){this.hasLoaded=!0,this.update()},e.prototype.destroy=function(){this.imageUrl&&(delete u.BaseTextureCache[this.imageUrl],delete u.TextureCache[this.imageUrl],this.imageUrl=null,navigator.isCocoonJS||(this.source.src="")),this.source&&this.source._pixiId&&delete u.BaseTextureCache[this.source._pixiId],this.source=null,this.dispose(),this._destroyed=!0},e.prototype.dispose=function(){this.emit("dispose",this)},e.prototype.updateSourceImage=function(t){this.source.src=t,this.loadSource(this.source)},e.fromImage=function(t,r,n,i){var o=u.BaseTextureCache[t];if(!o){var s=new Image;void 0===r&&0!==t.indexOf("data:")&&(s.crossOrigin=(0,p.default)(t)),o=new e(s,n),o.imageUrl=t,i&&(o.sourceScale=i),o.resolution=(0,u.getResolutionOfUrl)(t),s.src=t,u.BaseTextureCache[t]=o}return o},e.fromCanvas=function(t,r){t._pixiId||(t._pixiId="canvas_"+(0,u.uid)());var n=u.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),u.BaseTextureCache[t._pixiId]=n),n},e.from=function(t,r,n){if("string"==typeof t)return e.fromImage(t,void 0,r,n);if(t instanceof HTMLImageElement){var i=t.src,o=u.BaseTextureCache[i];return o||(o=new e(t,r),o.imageUrl=i,n&&(o.sourceScale=n),o.resolution=(0,u.getResolutionOfUrl)(i),u.BaseTextureCache[i]=o),o}return t instanceof HTMLCanvasElement?e.fromCanvas(t,r):t},e}(f.default);r.default=g},{"../settings":99,"../utils":120,"../utils/determineCrossOrigin":119,"bit-twiddle":1,eventemitter3:3}],110:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("./BaseRenderTexture"),u=n(a),l=t("./Texture"),h=n(l),c=function(t){function e(r,n){i(this,e);var s=null;if(!(r instanceof u.default)){var a=arguments[1],l=arguments[2],h=arguments[3],c=arguments[4];console.warn("Please use RenderTexture.create("+a+", "+l+") instead of the ctor directly."),s=arguments[0],n=null,r=new u.default(a,l,h,c)}var f=o(this,t.call(this,r,n));return f.legacyRenderer=s,f.valid=!0,f._updateUvs(),f}return s(e,t),e.prototype.resize=function(t,e,r){this.valid=t>0&&e>0,this._frame.width=this.orig.width=t,this._frame.height=this.orig.height=e,r||this.baseTexture.resize(t,e),this._updateUvs()},e.create=function(t,r,n,i){return new e(new u.default(t,r,n,i))},e}(h.default);r.default=c},{"./BaseRenderTexture":108,"./Texture":112}],111:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:null;n(this,t),this.baseTexture=e,this.textures={},this.data=r,this.resolution=this._updateResolution(i||this.baseTexture.imageUrl),this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}return i(t,null,[{key:"BATCH_SIZE",get:function(){return 1e3}}]),t.prototype._updateResolution=function(t){var e=this.data.meta.scale,r=(0,s.getResolutionOfUrl)(t,null);return null===r&&(r=void 0!==e?parseFloat(e):1),1!==r&&(this.baseTexture.resolution=r,this.baseTexture.update()),r},t.prototype.parse=function(e){this._batchIndex=0,this._callback=e,this._frameKeys.length<=t.BATCH_SIZE?(this._processFrames(0),this._parseComplete()):this._nextBatch()},t.prototype._processFrames=function(e){for(var r=e,n=t.BATCH_SIZE;r-e0&&void 0!==arguments[0]&&arguments[0];for(var e in this.textures)this.textures[e].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,t&&this.baseTexture.destroy(),this.baseTexture=null},t}();r.default=a},{"../":63,"../utils":120}],112:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(){var t=document.createElement("canvas");t.width=10,t.height=10;var e=t.getContext("2d");return e.fillStyle="white",e.fillRect(0,0,10,10),new b(new c.default(t))}function u(t){t.destroy=function(){},t.on=function(){},t.once=function(){},t.emit=function(){}}r.__esModule=!0;var l=function(){function t(t,e){for(var r=0;rthis.baseTexture.width||t.y+t.height>this.baseTexture.height)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions: "+("X: "+t.x+" + "+t.width+" > "+this.baseTexture.width+" ")+("Y: "+t.y+" + "+t.height+" > "+this.baseTexture.height));this.valid=t&&t.width&&t.height&&this.baseTexture.hasLoaded,this.trim||this.rotate||(this.orig=t),this.valid&&this._updateUvs()}},{key:"rotate",get:function(){return this._rotate},set:function(t){this._rotate=t,this.valid&&this._updateUvs()}},{key:"width",get:function(){return this.orig.width}},{key:"height",get:function(){return this.orig.height}}]),e}(g.default);r.default=b,b.EMPTY=new b(new c.default),u(b.EMPTY),u(b.EMPTY.baseTexture),b.WHITE=a(),u(b.WHITE),u(b.WHITE.baseTexture)},{"../math":68,"../utils":120,"./BaseTexture":109,"./TextureUvs":113,"./VideoBaseTexture":114,eventemitter3:3}],113:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../math/GroupD8"),s=n(o),a=function(){function t(){i(this,t),this.x0=0,this.y0=0,this.x1=1,this.y1=0,this.x2=1,this.y2=1,this.x3=0,this.y3=1,this.uvsUint32=new Uint32Array(4)}return t.prototype.set=function(t,e,r){var n=e.width,i=e.height;if(r){var o=t.width/2/n,a=t.height/2/i,u=t.x/n+o,l=t.y/i+a;r=s.default.add(r,s.default.NW),this.x0=u+o*s.default.uX(r),this.y0=l+a*s.default.uY(r),r=s.default.add(r,2),this.x1=u+o*s.default.uX(r),this.y1=l+a*s.default.uY(r),r=s.default.add(r,2),this.x2=u+o*s.default.uX(r),this.y2=l+a*s.default.uY(r),r=s.default.add(r,2),this.x3=u+o*s.default.uX(r),this.y3=l+a*s.default.uY(r)}else this.x0=t.x/n,this.y0=t.y/i,this.x1=(t.x+t.width)/n,this.y1=t.y/i,this.x2=(t.x+t.width)/n,this.y2=(t.y+t.height)/i,this.x3=t.x/n,this.y3=(t.y+t.height)/i;this.uvsUint32[0]=(65535*this.y0&65535)<<16|65535*this.x0&65535,this.uvsUint32[1]=(65535*this.y1&65535)<<16|65535*this.x1&65535,this.uvsUint32[2]=(65535*this.y2&65535)<<16|65535*this.x2&65535,this.uvsUint32[3]=(65535*this.y3&65535)<<16|65535*this.x3&65535},t}();r.default=a},{"../math/GroupD8":64}],114:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function u(t,e){e||(e="video/"+t.substr(t.lastIndexOf(".")+1));var r=document.createElement("source");return r.src=t,r.type=e,r}r.__esModule=!0;var l=function(){function t(t,e){for(var r=0;r0&&t.paused===!1&&t.ended===!1&&t.readyState>2},e.prototype._isSourceReady=function(){return 3===this.source.readyState||4===this.source.readyState},e.prototype._onPlayStart=function(){this.hasLoaded||this._onCanPlay(),!this._isAutoUpdating&&this.autoUpdate&&(p.shared.add(this.update,this), +this._isAutoUpdating=!0)},e.prototype._onPlayStop=function(){this._isAutoUpdating&&(p.shared.remove(this.update,this),this._isAutoUpdating=!1)},e.prototype._onCanPlay=function(){this.hasLoaded=!0,this.source&&(this.source.removeEventListener("canplay",this._onCanPlay),this.source.removeEventListener("canplaythrough",this._onCanPlay),this.width=this.source.videoWidth,this.height=this.source.videoHeight,this.__loaded||(this.__loaded=!0,this.emit("loaded",this)),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.source.play())},e.prototype.destroy=function(){this._isAutoUpdating&&p.shared.remove(this.update,this),this.source&&this.source._pixiId&&(delete f.BaseTextureCache[this.source._pixiId],delete this.source._pixiId),t.prototype.destroy.call(this)},e.fromVideo=function(t,r){t._pixiId||(t._pixiId="video_"+(0,f.uid)());var n=f.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),f.BaseTextureCache[t._pixiId]=n),n},e.fromUrl=function(t,r){var n=document.createElement("video");if(n.setAttribute("webkit-playsinline",""),n.setAttribute("playsinline",""),Array.isArray(t))for(var i=0;i0&&void 0!==arguments[0]?arguments[0]:performance.now(),e=void 0;t>this.lastTime?(e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),this.deltaTime=e*a.default.TARGET_FPMS*this.speed,this._emitter.emit(h,this.deltaTime)):this.deltaTime=this.elapsedMS=0,this.lastTime=t},o(t,[{key:"FPS",get:function(){return 1e3/this.elapsedMS}},{key:"minFPS",get:function(){return 1e3/this._maxElapsedMS},set:function(t){var e=Math.min(Math.max(0,t)/1e3,a.default.TARGET_FPMS);this._maxElapsedMS=1/e}}]),t}();r.default=c},{"../settings":99,eventemitter3:3}],116:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.Ticker=r.shared=void 0;var i=t("./Ticker"),o=n(i),s=new o.default;s.autoStart=!0,r.shared=s,r.Ticker=o.default},{"./Ticker":115}],117:[function(t,e,r){"use strict";function n(){var t=!!navigator.platform&&/iPad|iPhone|iPod/.test(navigator.platform);return!t}r.__esModule=!0,r.default=n},{}],118:[function(t,e,r){"use strict";function n(t){for(var e=6*t,r=new Uint16Array(e),n=0,i=0;n1&&void 0!==arguments[1]?arguments[1]:window.location;if(0===t.indexOf("data:"))return"";e=e||window.location,a||(a=document.createElement("a")),a.href=t,t=s.default.parse(a.href);var r=!t.port&&""===e.port||t.port===e.port;return t.hostname===e.hostname&&r&&t.protocol===e.protocol?"":"anonymous"}r.__esModule=!0,r.default=i;var o=t("url"),s=n(o),a=void 0},{url:28}],120:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(){return++A}function s(t,e){return e=e||[],e[0]=(t>>16&255)/255,e[1]=(t>>8&255)/255,e[2]=(255&t)/255,e}function a(t){return t=t.toString(16),t="000000".substr(0,6-t.length)+t,"#"+t}function u(t){return(255*t[0]<<16)+(255*t[1]<<8)+(255*t[2]|0)}function l(t,e){var r=T.default.RETINA_PREFIX.exec(t);return r?parseFloat(r[1]):void 0!==e?e:1}function h(t){var e=b.DATA_URI.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,encoding:e[3]?e[3].toLowerCase():void 0,data:e[4]}}function c(t){var e=b.URL_FILE_EXTENSION.exec(t);if(e)return e[1].toLowerCase()}function f(t){var e=b.SVG_SIZE.exec(t),r={};return e&&(r[e[1]]=Math.round(parseFloat(e[3])),r[e[5]]=Math.round(parseFloat(e[7]))),r}function d(){I=!0}function p(t){if(!I){if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var e=["\n %c %c %c Pixi.js "+b.VERSION+" - ✰ "+t+" ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n","background: #ff66a5; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff66a5; background: #030307; padding:5px 0;","background: #ff66a5; padding:5px 0;","background: #ffc3dc; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;"];window.console.log.apply(console,e)}else window.console&&window.console.log("Pixi.js "+b.VERSION+" - "+t+" - http://www.pixijs.com/");I=!0}}function v(){var t={stencil:!0,failIfMajorPerformanceCaveat:!0};try{if(!window.WebGLRenderingContext)return!1;var e=document.createElement("canvas"),r=e.getContext("webgl",t)||e.getContext("experimental-webgl",t),n=!(!r||!r.getContextAttributes().stencil);if(r){var i=r.getExtension("WEBGL_lose_context");i&&i.loseContext()}return r=null,n}catch(t){return!1}}function y(t){return 0===t?0:t<0?-1:1}function g(t,e,r){var n=t.length;if(!(e>=n||0===r)){r=e+r>n?n-e:r;for(var i=n-r,o=e;o1?this._fontStyle="italic":t.indexOf("oblique")>-1?this._fontStyle="oblique":this._fontStyle="normal",t.indexOf("small-caps")>-1?this._fontVariant="small-caps":this._fontVariant="normal";var e=t.split(" "),r=-1;this._fontSize=26;for(var n=0;n-1&&r=this._durations[this.currentFrame];)n-=this._durations[this.currentFrame]*i,this._currentTime+=i;this._currentTime+=n/this._durations[this.currentFrame]}else this._currentTime+=e;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):r!==this.currentFrame&&this.updateTexture()},e.prototype.updateTexture=function(){this._texture=this._textures[this.currentFrame],this._textureID=-1,this.onFrameChange&&this.onFrameChange(this.currentFrame)},e.prototype.destroy=function(){this.stop(),t.prototype.destroy.call(this)},e.fromFrames=function(t){for(var r=[],n=0;n1&&void 0!==arguments[1]?arguments[1]:{};o(this,e);var i=s(this,t.call(this));return i._textWidth=0,i._textHeight=0,i._glyphs=[],i._font={tint:void 0!==n.tint?n.tint:16777215,align:n.align||"left",name:null,size:0},i.font=n.font,i._text=r,i.maxWidth=0,i.maxLineHeight=0,i._anchor=new f.default(function(){i.dirty=!0},i,0,0),i.dirty=!1,i.updateText(),i}return a(e,t),e.prototype.updateText=function(){for(var t=e.fonts[this._font.name],r=this._font.size/t.size,n=new h.Point,i=[],o=[],s=null,a=0,u=0,l=0,c=-1,f=0,d=0,p=0;p0&&n.x*r>this.maxWidth)h.utils.removeItems(i,c,p-c),p=c,c=-1,o.push(f),u=Math.max(u,f),l++,n.x=0,n.y+=t.lineHeight,s=null;else{var y=t.chars[v];y&&(s&&y.kerning[s]&&(n.x+=y.kerning[s]),i.push({texture:y.texture,line:l,charCode:v,position:new h.Point(n.x+y.xOffset,n.y+y.yOffset)}),a=n.x+(y.texture.width+y.xOffset),n.x+=y.xAdvance,d=Math.max(d,y.yOffset+y.texture.height),s=v)}}o.push(a),u=Math.max(u,a);for(var g=[],m=0;m<=l;m++){var _=0;"right"===this._font.align?_=u-o[m]:"center"===this._font.align&&(_=(u-o[m])/2),g.push(_)}for(var b=i.length,x=this.tint,T=0;T=0?t:16777215,this.dirty=!0}},{key:"align",get:function(){return this._font.align},set:function(t){this._font.align=t||"left",this.dirty=!0}},{key:"anchor",get:function(){return this._anchor},set:function(t){"number"==typeof t?this._anchor.set(t):this._anchor.copy(t)}},{key:"font",get:function(){return this._font},set:function(t){t&&("string"==typeof t?(t=t.split(" "),this._font.name=1===t.length?t[0]:t.slice(1).join(" "),this._font.size=t.length>=2?parseInt(t[0],10):e.fonts[this._font.name].size):(this._font.name=t.name,this._font.size="number"==typeof t.size?t.size:parseInt(t.size,10)),this.dirty=!0)}},{key:"text",get:function(){return this._text},set:function(t){t=t.toString()||" ",this._text!==t&&(this._text=t,this.dirty=!0)}},{key:"textWidth",get:function(){return this.validate(),this._textWidth}},{key:"textHeight",get:function(){return this.validate(),this._textHeight}}]),e}(h.Container);r.default=d,d.fonts={}},{"../core":63,"../core/math/ObservablePoint":66}],131:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:100,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:100;o(this,e);var a=s(this,t.call(this,r));return a.tileTransform=new h.TransformStatic,a._width=n,a._height=i,a._canvasPattern=null,a.uvTransform=r.transform||new p.default(r),a.pluginName="tilingSprite",a.uvRespectAnchor=!1,a}return a(e,t),e.prototype._onTextureUpdate=function(){this.uvTransform&&(this.uvTransform.texture=this._texture)},e.prototype._renderWebGL=function(t){var e=this._texture;e&&e.valid&&(this.tileTransform.updateLocalTransform(),this.uvTransform.update(),t.setObjectRenderer(t.plugins[this.pluginName]),t.plugins[this.pluginName].render(this))},e.prototype._renderCanvas=function(t){var e=this._texture;if(e.baseTexture.hasLoaded){var r=t.context,n=this.worldTransform,i=t.resolution,o=e.baseTexture,s=e.baseTexture.resolution,a=this.tilePosition.x/this.tileScale.x%e._frame.width,u=this.tilePosition.y/this.tileScale.y%e._frame.height;if(!this._canvasPattern){var l=new h.CanvasRenderTarget(e._frame.width,e._frame.height,s);16777215!==this.tint?(this.cachedTint!==this.tint&&(this.cachedTint=this.tint,this.tintedTexture=f.default.getTintedTexture(this,this.tint)),l.context.drawImage(this.tintedTexture,0,0)):l.context.drawImage(o.source,-e._frame.x,-e._frame.y),this._canvasPattern=l.context.createPattern(l.canvas,"repeat")}r.globalAlpha=this.worldAlpha,r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t.setBlendMode(this.blendMode),r.fillStyle=this._canvasPattern,r.scale(this.tileScale.x/s,this.tileScale.y/s);var c=this.anchor.x*-this._width,d=this.anchor.y*-this._height;this.uvRespectAnchor?(r.translate(a,u),r.fillRect(-a+c,-u+d,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s)):(r.translate(a+c,u+d),r.fillRect(-a,-u,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s))}},e.prototype._calculateBounds=function(){var t=this._width*-this._anchor._x,e=this._height*-this._anchor._y,r=this._width*(1-this._anchor._x),n=this._height*(1-this._anchor._y);this._bounds.addFrame(this.transform,t,e,r,n)},e.prototype.getLocalBounds=function(e){return 0===this.children.length?(this._bounds.minX=this._width*-this._anchor._x,this._bounds.minY=this._height*-this._anchor._y,this._bounds.maxX=this._width*(1-this._anchor._x),this._bounds.maxY=this._height*(1-this._anchor._x),e||(this._localBoundsRect||(this._localBoundsRect=new h.Rectangle),e=this._localBoundsRect),this._bounds.getRectangle(e)):t.prototype.getLocalBounds.call(this,e)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,v);var e=this._width,r=this._height,n=-e*this.anchor._x;if(v.x>n&&v.xi&&v.y0&&void 0!==arguments[0]?arguments[0]:new o.Point,e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.parent?this.parent.toGlobal(this.position,t,e):(t.x=this.position.x,t.y=this.position.y),t}},{"../core":63}],136:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.BitmapText=r.TilingSpriteRenderer=r.TilingSprite=r.AnimatedSprite=r.TextureTransform=void 0;var i=t("./TextureTransform");Object.defineProperty(r,"TextureTransform",{enumerable:!0,get:function(){return n(i).default}});var o=t("./AnimatedSprite");Object.defineProperty(r,"AnimatedSprite",{enumerable:!0,get:function(){return n(o).default}});var s=t("./TilingSprite");Object.defineProperty(r,"TilingSprite",{enumerable:!0,get:function(){return n(s).default}});var a=t("./webgl/TilingSpriteRenderer");Object.defineProperty(r,"TilingSpriteRenderer",{enumerable:!0,get:function(){return n(a).default}});var u=t("./BitmapText");Object.defineProperty(r,"BitmapText",{enumerable:!0,get:function(){return n(u).default}}),t("./cacheAsBitmap"),t("./getChildByName"),t("./getGlobalPosition")},{"./AnimatedSprite":129,"./BitmapText":130,"./TextureTransform":131,"./TilingSprite":132,"./cacheAsBitmap":133,"./getChildByName":134,"./getGlobalPosition":135,"./webgl/TilingSpriteRenderer":137}],137:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../core"),u=n(a),l=t("../../core/const"),h=(t("path"),new u.Matrix),c=new Float32Array(4),f=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.shader=null,n.simpleShader=null,n.quad=null,n}return s(e,t),e.prototype.onContextChange=function(){var t=this.renderer.gl;this.shader=new u.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n gl_FragColor = sample * color ;\n}\n"),this.simpleShader=new u.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n gl_FragColor = sample * color;\n}\n"),this.renderer.bindVao(null),this.quad=new u.Quad(t,this.renderer.state.attribState),this.quad.initVao(this.shader)},e.prototype.render=function(t){var e=this.renderer,r=this.quad;e.bindVao(r.vao);var n=r.vertices;n[0]=n[6]=t._width*-t.anchor.x,n[1]=n[3]=t._height*-t.anchor.y,n[2]=n[4]=t._width*(1-t.anchor.x),n[5]=n[7]=t._height*(1-t.anchor.y),t.uvRespectAnchor&&(n=r.uvs,n[0]=n[6]=-t.anchor.x,n[1]=n[3]=-t.anchor.y,n[2]=n[4]=1-t.anchor.x,n[5]=n[7]=1-t.anchor.y),r.upload();var i=t._texture,o=i.baseTexture,s=t.tileTransform.localTransform,a=t.uvTransform,f=o.isPowerOfTwo&&i.frame.width===o.width&&i.frame.height===o.height;f&&(o._glTextures[e.CONTEXT_UID]?f=o.wrapMode!==l.WRAP_MODES.CLAMP:o.wrapMode===l.WRAP_MODES.CLAMP&&(o.wrapMode=l.WRAP_MODES.REPEAT));var d=f?this.simpleShader:this.shader;e.bindShader(d);var p=i.width,v=i.height,y=t._width,g=t._height;h.set(s.a*p/y,s.b*p/g,s.c*v/y,s.d*v/g,s.tx/y,s.ty/g),h.invert(),f?h.append(a.mapCoord):(d.uniforms.uMapCoord=a.mapCoord.toArray(!0),d.uniforms.uClampFrame=a.uClampFrame,d.uniforms.uClampOffset=a.uClampOffset),d.uniforms.uTransform=h.toArray(!0);var m=c;u.utils.hex2rgb(t.tint,m),m[3]=t.worldAlpha,d.uniforms.uColor=m,d.uniforms.translationMatrix=t.transform.worldTransform.toArray(!0),d.uniforms.uSampler=e.bindTexture(i),e.setBlendMode(t.blendMode),r.vao.draw(this.renderer.gl.TRIANGLES,6,0)},e}(u.ObjectRenderer);r.default=f,u.WebGLRenderer.registerPlugin("tilingSprite",f)},{"../../core":63,"../../core/const":44,path:22}],138:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var u=function(){function t(t,e){for(var r=0;r=r&&(u=t-l-1),h=h.replace("%value%",e[u]),s+=h,s+="\n"}return n=n.replace("%blur%",s),n=n.replace("%size%",t)}r.__esModule=!0,r.default=n;var i={5:[.153388,.221461,.250301],7:[.071303,.131514,.189879,.214607],9:[.028532,.067234,.124009,.179044,.20236],11:[.0093,.028002,.065984,.121703,.175713,.198596],13:[.002406,.009255,.027867,.065666,.121117,.174868,.197641],15:[489e-6,.002403,.009246,.02784,.065602,.120999,.174697,.197448]},o=["varying vec2 vBlurTexCoords[%size%];","uniform sampler2D uSampler;","void main(void)","{"," gl_FragColor = vec4(0.0);"," %blur%","}"].join("\n")},{}],142:[function(t,e,r){"use strict";function n(t,e){var r=Math.ceil(t/2),n=i,o="",s=void 0;s=e?"vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);":"vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);";for(var a=0;ae;)r-=2;return r}r.__esModule=!0,r.default=n},{}],144:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r 0.0) {\n c.rgb /= c.a;\n }\n vec4 result;\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n // Premultiply alpha again.\n result.rgb *= result.a;\n\n gl_FragColor = result;\n}\n"));return r.uniforms.m=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],r}return s(e,t),e.prototype._loadMatrix=function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t;e&&(this._multiply(r,this.uniforms.m,t),r=this._colorMatrix(r)),this.uniforms.m=r},e.prototype._multiply=function(t,e,r){return t[0]=e[0]*r[0]+e[1]*r[5]+e[2]*r[10]+e[3]*r[15],t[1]=e[0]*r[1]+e[1]*r[6]+e[2]*r[11]+e[3]*r[16],t[2]=e[0]*r[2]+e[1]*r[7]+e[2]*r[12]+e[3]*r[17],t[3]=e[0]*r[3]+e[1]*r[8]+e[2]*r[13]+e[3]*r[18],t[4]=e[0]*r[4]+e[1]*r[9]+e[2]*r[14]+e[3]*r[19]+e[4],t[5]=e[5]*r[0]+e[6]*r[5]+e[7]*r[10]+e[8]*r[15],t[6]=e[5]*r[1]+e[6]*r[6]+e[7]*r[11]+e[8]*r[16],t[7]=e[5]*r[2]+e[6]*r[7]+e[7]*r[12]+e[8]*r[17],t[8]=e[5]*r[3]+e[6]*r[8]+e[7]*r[13]+e[8]*r[18],t[9]=e[5]*r[4]+e[6]*r[9]+e[7]*r[14]+e[8]*r[19]+e[9],t[10]=e[10]*r[0]+e[11]*r[5]+e[12]*r[10]+e[13]*r[15],t[11]=e[10]*r[1]+e[11]*r[6]+e[12]*r[11]+e[13]*r[16],t[12]=e[10]*r[2]+e[11]*r[7]+e[12]*r[12]+e[13]*r[17],t[13]=e[10]*r[3]+e[11]*r[8]+e[12]*r[13]+e[13]*r[18],t[14]=e[10]*r[4]+e[11]*r[9]+e[12]*r[14]+e[13]*r[19]+e[14],t[15]=e[15]*r[0]+e[16]*r[5]+e[17]*r[10]+e[18]*r[15],t[16]=e[15]*r[1]+e[16]*r[6]+e[17]*r[11]+e[18]*r[16],t[17]=e[15]*r[2]+e[16]*r[7]+e[17]*r[12]+e[18]*r[17],t[18]=e[15]*r[3]+e[16]*r[8]+e[17]*r[13]+e[18]*r[18],t[19]=e[15]*r[4]+e[16]*r[9]+e[17]*r[14]+e[18]*r[19]+e[19],t},e.prototype._colorMatrix=function(t){var e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e},e.prototype.brightness=function(t,e){var r=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.greyscale=function(t,e){var r=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.blackAndWhite=function(t){var e=[.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.hue=function(t,e){t=(t||0)/180*Math.PI;var r=Math.cos(t),n=Math.sin(t),i=Math.sqrt,o=1/3,s=i(o),a=r+(1-r)*o,u=o*(1-r)-s*n,l=o*(1-r)+s*n,h=o*(1-r)+s*n,c=r+o*(1-r),f=o*(1-r)-s*n,d=o*(1-r)-s*n,p=o*(1-r)+s*n,v=r+o*(1-r),y=[a,u,l,0,0,h,c,f,0,0,d,p,v,0,0,0,0,0,1,0];this._loadMatrix(y,e)},e.prototype.contrast=function(t,e){var r=(t||0)+1,n=-128*(r-1),i=[r,0,0,0,n,0,r,0,0,n,0,0,r,0,n,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.saturate=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=2*t/3+1,n=(r-1)*-.5,i=[r,n,n,0,0,n,r,n,0,0,n,n,r,0,0,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.desaturate=function(){this.saturate(-1)},e.prototype.negative=function(t){var e=[0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.sepia=function(t){var e=[.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.technicolor=function(t){var e=[1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.polaroid=function(t){var e=[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.toBGR=function(t){var e=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.kodachrome=function(t){var e=[1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.browni=function(t){var e=[.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.vintage=function(t){var e=[.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.colorTone=function(t,e,r,n,i){t=t||.2,e=e||.15,r=r||16770432,n=n||3375104;var o=(r>>16&255)/255,s=(r>>8&255)/255,a=(255&r)/255,u=(n>>16&255)/255,l=(n>>8&255)/255,h=(255&n)/255,c=[.3,.59,.11,0,0,o,s,a,t,0,u,l,h,e,0,o-u,s-l,a-h,0,0];this._loadMatrix(c,i)},e.prototype.night=function(t,e){t=t||.1;var r=[t*-2,-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.predator=function(t,e){var r=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.lsd=function(t){var e=[2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.reset=function(){var t=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(t,!1)},a(e,[{key:"matrix",get:function(){return this.uniforms.m},set:function(t){this.uniforms.m=t}}]),e}(l.Filter));r.default=h,h.prototype.grayscale=h.prototype.greyscale},{"../../core":63,path:22}],145:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n'))}return s(e,t),e}(u.Filter));r.default=l},{"../../core":63,path:22}],147:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./fxaa/FXAAFilter");Object.defineProperty(r,"FXAAFilter",{enumerable:!0,get:function(){return n(i).default}});var o=t("./noise/NoiseFilter");Object.defineProperty(r,"NoiseFilter",{enumerable:!0,get:function(){return n(o).default}});var s=t("./displacement/DisplacementFilter");Object.defineProperty(r,"DisplacementFilter",{enumerable:!0,get:function(){return n(s).default}});var a=t("./blur/BlurFilter");Object.defineProperty(r,"BlurFilter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./blur/BlurXFilter");Object.defineProperty(r,"BlurXFilter",{enumerable:!0,get:function(){return n(u).default}});var l=t("./blur/BlurYFilter");Object.defineProperty(r,"BlurYFilter",{enumerable:!0,get:function(){return n(l).default}});var h=t("./colormatrix/ColorMatrixFilter");Object.defineProperty(r,"ColorMatrixFilter",{enumerable:!0,get:function(){return n(h).default}});var c=t("./void/VoidFilter");Object.defineProperty(r,"VoidFilter",{enumerable:!0,get:function(){return n(c).default}})},{"./blur/BlurFilter":138,"./blur/BlurXFilter":139,"./blur/BlurYFilter":140,"./colormatrix/ColorMatrixFilter":144,"./displacement/DisplacementFilter":145,"./fxaa/FXAAFilter":146,"./noise/NoiseFilter":148,"./void/VoidFilter":149}],148:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:1;this.removeEvents(),this.interactionDOMElement=t,this.resolution=e,this.addEvents()},e.prototype.addEvents=function(){this.interactionDOMElement&&(h.ticker.shared.add(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="none",this.interactionDOMElement.style["-ms-touch-action"]="none"):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]="none"),this.supportsPointerEvents?(window.document.addEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("pointerover",this.onPointerOver,!0),window.addEventListener("pointercancel",this.onPointerCancel,!0),window.addEventListener("pointerup",this.onPointerUp,!0)):(window.document.addEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onPointerOver,!0),window.addEventListener("mouseup",this.onPointerUp,!0),this.supportsTouchEvents&&(this.interactionDOMElement.addEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.addEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.addEventListener("touchmove",this.onPointerMove,!0))),this.eventsAdded=!0)},e.prototype.removeEvents=function(){this.interactionDOMElement&&(h.ticker.shared.remove(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="",this.interactionDOMElement.style["-ms-touch-action"]=""):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]=""),this.supportsPointerEvents?(window.document.removeEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("pointerover",this.onPointerOver,!0),window.removeEventListener("pointercancel",this.onPointerCancel,!0),window.removeEventListener("pointerup",this.onPointerUp,!0)):(window.document.removeEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onPointerOver,!0),window.removeEventListener("mouseup",this.onPointerUp,!0),this.supportsTouchEvents&&(this.interactionDOMElement.removeEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.removeEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onPointerMove,!0))),this.interactionDOMElement=null,this.eventsAdded=!1)},e.prototype.update=function(t){if(this._deltaTime+=t,!(this._deltaTime=0;l--){var h=u[l],c=this.processInteractive(t,h,r,n,a);if(c){if(!h.parent)continue;a=!1,c&&(t.target&&(n=!1),s=!0)}}return i&&(n&&!t.target&&(e.hitArea?(e.worldTransform.applyInverse(o,this._tempPoint),e.hitArea.contains(this._tempPoint.x,this._tempPoint.y)&&(s=!0)):e.containsPoint&&e.containsPoint(o)&&(s=!0)),e.interactive&&(s&&!t.target&&(t.target=e),r(t,e,!!s))),s},e.prototype.onPointerDown=function(t){var e=this.normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&t.preventDefault();for(var r=e.length,n=0;n1&&(h=1);var c=Math.sqrt(n*n+i*i),f=this._texture.height/2;n/=c,i/=c,n*=f,i*=f,o[l]=u.x+n,o[l+1]=u.y+i,o[l+2]=u.x-n,o[l+3]=u.y-i,e=u}this.containerUpdateTransform()}},e}(l.default);r.default=f},{"../core":63,"./Mesh":161}],165:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var s=t("../../core"),a=i(s),u=t("../Mesh"),l=n(u),h=function(){function t(e){o(this,t),this.renderer=e}return t.prototype.render=function(t){var e=this.renderer,r=e.context,n=t.worldTransform,i=e.resolution;e.roundPixels?r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i|0,n.ty*i|0):r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),e.setBlendMode(t.blendMode),t.drawMode===l.default.DRAW_MODES.TRIANGLE_MESH?this._renderTriangleMesh(t):this._renderTriangles(t)},t.prototype._renderTriangleMesh=function(t){for(var e=t.vertices.length/2,r=0;r0){var E=t.canvasPadding/t.worldTransform.a,S=t.canvasPadding/t.worldTransform.d,O=(m+_+b)/3,P=(x+T+w)/3,M=m-O,C=x-P,R=Math.sqrt(M*M+C*C);m=O+M/R*(R+E),x=P+C/R*(R+S),M=_-O,C=T-P,R=Math.sqrt(M*M+C*C),_=O+M/R*(R+E),T=P+C/R*(R+S),M=b-O,C=w-P,R=Math.sqrt(M*M+C*C),b=O+M/R*(R+E),w=P+C/R*(R+S)}i.save(),i.beginPath(),i.moveTo(m,x),i.lineTo(_,T),i.lineTo(b,w),i.closePath(),i.clip();var A=f*y+v*p+d*g-y*p-v*d-f*g,I=m*y+v*b+_*g-y*b-v*_-m*g,D=f*_+m*p+d*b-_*p-m*d-f*b,L=f*y*b+v*_*p+m*d*g-m*y*p-v*d*b-f*_*g,N=x*y+v*w+T*g-y*w-v*T-x*g,F=f*T+x*p+d*w-T*p-x*d-f*w,j=f*y*w+v*T*p+x*d*g-x*y*p-v*d*w-f*T*g;i.transform(I/A,N/A,D/A,F/A,L/A,j/A),i.drawImage(l,0,0,h*u.resolution,c*u.resolution,0,0,h,c),i.restore()}},t.prototype.renderMeshFlat=function(t){var e=this.renderer.context,r=t.vertices,n=r.length/2;e.beginPath();for(var i=1;i0&&void 0!==arguments[0]?arguments[0]:1500,n=arguments[1],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16384; +i(this,e);var a=o(this,t.call(this)),l=16384;return s>l&&(s=l),s>r&&(s=r),a._properties=[!1,!0,!1,!1,!1],a._maxSize=r,a._batchSize=s,a._glBuffers={},a._bufferToUpdate=0,a.interactiveChildren=!1,a.blendMode=u.BLEND_MODES.NORMAL,a.roundPixels=!0,a.baseTexture=null,a.setProperties(n),a}return s(e,t),e.prototype.setProperties=function(t){t&&(this._properties[0]="scale"in t?!!t.scale:this._properties[0],this._properties[1]="position"in t?!!t.position:this._properties[1],this._properties[2]="rotation"in t?!!t.rotation:this._properties[2],this._properties[3]="uvs"in t?!!t.uvs:this._properties[3],this._properties[4]="alpha"in t?!!t.alpha:this._properties[4])},e.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},e.prototype.renderWebGL=function(t){var e=this;this.visible&&!(this.worldAlpha<=0)&&this.children.length&&this.renderable&&(this.baseTexture||(this.baseTexture=this.children[0]._texture.baseTexture,this.baseTexture.hasLoaded||this.baseTexture.once("update",function(){return e.onChildrenChange(0)})),t.setObjectRenderer(t.plugins.particle),t.plugins.particle.render(this))},e.prototype.onChildrenChange=function(t){var e=Math.floor(t/this._batchSize);er&&(o=r);var s=t._glBuffers[i.CONTEXT_UID];s||(s=t._glBuffers[i.CONTEXT_UID]=this.generateBuffers(t)),this.renderer.setBlendMode(t.blendMode);var a=i.gl,u=t.worldTransform.copy(this.tempMatrix);u.prepend(i._activeRenderTarget.projectionMatrix),this.shader.uniforms.projectionMatrix=u.toArray(!0),this.shader.uniforms.uAlpha=t.worldAlpha;var l=e[0]._texture.baseTexture;this.shader.uniforms.uSampler=i.bindTexture(l);for(var h=0,c=0;hn&&(f=n);var d=s[c];d.uploadDynamic(e,h,f),t._bufferToUpdate===c&&(d.uploadStatic(e,h,f),t._bufferToUpdate=c+1),i.bindVao(d.vao),d.vao.draw(a.TRIANGLES,6*f)}}},e.prototype.generateBuffers=function(t){for(var e=this.renderer.gl,r=[],n=t._maxSize,i=t._batchSize,o=t._properties,s=0;s0?1:-1})},{}],174:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}var i=t("object-assign"),o=n(i);Object.assign||(Object.assign=o.default)},{"object-assign":5}],175:[function(t,e,r){"use strict";t("./Object.assign"),t("./requestAnimationFrame"),t("./Math.sign"),window.ArrayBuffer||(window.ArrayBuffer=Array),window.Float32Array||(window.Float32Array=Array),window.Uint32Array||(window.Uint32Array=Array),window.Uint16Array||(window.Uint16Array=Array)},{"./Math.sign":173,"./Object.assign":174,"./requestAnimationFrame":176}],176:[function(t,e,r){(function(t){"use strict";var e=16;Date.now&&Date.prototype.getTime||(Date.now=function(){return(new Date).getTime()}),t.performance&&t.performance.now||!function(){var e=Date.now();t.performance||(t.performance={}),t.performance.now=function(){return Date.now()-e}}();for(var r=Date.now(),n=["ms","moz","webkit","o"],i=0;i=0;n--)this.add(t.children[n]);return this},t.prototype.destroy=function(){this.ticking&&p.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null,this.limiter=null,this.uploadHookHelper=null},t}();r.default=v},{"../core":63,"./limiters/CountLimiter":180}],178:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function u(t,e){if(e instanceof c.BaseTexture){var r=e.source,n=0===r.width?t.canvas.width:Math.min(t.canvas.width,r.width),i=0===r.height?t.canvas.height:Math.min(t.canvas.height,r.height);return t.ctx.drawImage(r,0,0,n,i,0,0,t.canvas.width,t.canvas.height),!0}return!1}function l(t,e){if(t instanceof c.BaseTexture)return e.indexOf(t)===-1&&e.push(t),!0;if(t._texture&&t._texture instanceof c.Texture){var r=t._texture.baseTexture;return e.indexOf(r)===-1&&e.push(r),!0}return!1}r.__esModule=!0;var h=t("../../core"),c=i(h),f=t("../BasePrepare"),d=n(f),p=16,v=function(t){function e(r){o(this,e);var n=s(this,t.call(this,r));return n.uploadHookHelper=n,n.canvas=document.createElement("canvas"),n.canvas.width=p,n.canvas.height=p,n.ctx=n.canvas.getContext("2d"),n.register(l,u),n}return a(e,t),e.prototype.destroy=function(){t.prototype.destroy.call(this),this.ctx=null,this.canvas=null},e}(d.default);r.default=v,c.CanvasRenderer.registerPlugin("prepare",v)},{"../../core":63,"../BasePrepare":177}],179:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./webgl/WebGLPrepare");Object.defineProperty(r,"webgl",{enumerable:!0,get:function(){return n(i).default}});var o=t("./canvas/CanvasPrepare");Object.defineProperty(r,"canvas",{enumerable:!0,get:function(){return n(o).default}});var s=t("./BasePrepare");Object.defineProperty(r,"BasePrepare",{enumerable:!0,get:function(){return n(s).default}});var a=t("./limiters/CountLimiter");Object.defineProperty(r,"CountLimiter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./limiters/TimeLimiter");Object.defineProperty(r,"TimeLimiter",{enumerable:!0,get:function(){return n(u).default}})},{"./BasePrepare":177,"./canvas/CanvasPrepare":178,"./limiters/CountLimiter":180,"./limiters/TimeLimiter":181,"./webgl/WebGLPrepare":182}],180:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxItemsPerFrame=e,this.itemsLeft=0}return t.prototype.beginFrame=function(){this.itemsLeft=this.maxItemsPerFrame},t.prototype.allowedToUpload=function(){return this.itemsLeft-- >0},t}();r.default=i},{}],181:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxMilliseconds=e,this.frameStart=0}return t.prototype.beginFrame=function(){this.frameStart=Date.now()},t.prototype.allowedToUpload=function(){return Date.now()-this.frameStart 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],2:[function(require,module,exports){ +'use strict'; + +module.exports = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, size), + maxZ = zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, size); + earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and size of the data bounding box +function zOrder(x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; + +},{}],3:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @api private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {Mixed} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @api public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @api public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Boolean} exists Only check if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Add a one-time listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Remove the listeners of a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {Mixed} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn + && (!once || listeners.once) + && (!context || listeners.context === context) + ) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {String|Symbol} [event] The event name. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],4:[function(require,module,exports){ +/** + * isMobile.js v0.4.0 + * + * A simple library to detect Apple phones and tablets, + * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone), + * and any kind of seven inch device, via user agent sniffing. + * + * @author: Kai Mallea (kmallea@gmail.com) + * + * @license: http://creativecommons.org/publicdomain/zero/1.0/ + */ +(function (global) { + + var apple_phone = /iPhone/i, + apple_ipod = /iPod/i, + apple_tablet = /iPad/i, + android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i, // Match 'Android' AND 'Mobile' + android_tablet = /Android/i, + amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i, + amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i, + windows_phone = /IEMobile/i, + windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i, // Match 'Windows' AND 'ARM' + other_blackberry = /BlackBerry/i, + other_blackberry_10 = /BB10/i, + other_opera = /Opera Mini/i, + other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i, + other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i, // Match 'Firefox' AND 'Mobile' + seven_inch = new RegExp( + '(?:' + // Non-capturing group + + 'Nexus 7' + // Nexus 7 + + '|' + // OR + + 'BNTV250' + // B&N Nook Tablet 7 inch + + '|' + // OR + + 'Kindle Fire' + // Kindle Fire + + '|' + // OR + + 'Silk' + // Kindle Fire, Silk Accelerated + + '|' + // OR + + 'GT-P1000' + // Galaxy Tab 7 inch + + ')', // End non-capturing group + + 'i'); // Case-insensitive matching + + var match = function(regex, userAgent) { + return regex.test(userAgent); + }; + + var IsMobileClass = function(userAgent) { + var ua = userAgent || navigator.userAgent; + + // Facebook mobile app's integrated browser adds a bunch of strings that + // match everything. Strip it out if it exists. + var tmp = ua.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + // Twitter mobile app's integrated browser on iPad adds a "Twitter for + // iPhone" string. Same probable happens on other tablet platforms. + // This will confuse detection so strip it out if it exists. + tmp = ua.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + this.apple = { + phone: match(apple_phone, ua), + ipod: match(apple_ipod, ua), + tablet: !match(apple_phone, ua) && match(apple_tablet, ua), + device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua) + }; + this.amazon = { + phone: match(amazon_phone, ua), + tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) + }; + this.android = { + phone: match(amazon_phone, ua) || match(android_phone, ua), + tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua) + }; + this.windows = { + phone: match(windows_phone, ua), + tablet: match(windows_tablet, ua), + device: match(windows_phone, ua) || match(windows_tablet, ua) + }; + this.other = { + blackberry: match(other_blackberry, ua), + blackberry10: match(other_blackberry_10, ua), + opera: match(other_opera, ua), + firefox: match(other_firefox, ua), + chrome: match(other_chrome, ua), + device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua) + }; + this.seven_inch = match(seven_inch, ua); + this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch; + + // excludes 'other' devices and ipods, targeting touchscreen phones + this.phone = this.apple.phone || this.android.phone || this.windows.phone; + + // excludes 7 inch devices, classifying as phone or tablet is left to the user + this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet; + + if (typeof window === 'undefined') { + return this; + } + }; + + var instantiate = function() { + var IM = new IsMobileClass(); + IM.Class = IsMobileClass; + return IM; + }; + + if (typeof module !== 'undefined' && module.exports && typeof window === 'undefined') { + //node + module.exports = IsMobileClass; + } else if (typeof module !== 'undefined' && module.exports && typeof window !== 'undefined') { + //browserify + module.exports = instantiate(); + } else if (typeof define === 'function' && define.amd) { + //AMD + define('isMobile', [], global.isMobile = instantiate()); + } else { + global.isMobile = instantiate(); + } + +})(this); + +},{}],5:[function(require,module,exports){ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],6:[function(require,module,exports){ +var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); + +/** + * Helper class to create a webGL buffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ +var Buffer = function(gl, type, data, drawType) +{ + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The WebGL buffer, created upon instantiation + * + * @member {WebGLBuffer} + */ + this.buffer = gl.createBuffer(); + + /** + * The type of the buffer + * + * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} + */ + this.type = type || gl.ARRAY_BUFFER; + + /** + * The draw type of the buffer + * + * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ + this.drawType = drawType || gl.STATIC_DRAW; + + /** + * The data in the buffer, as a typed array + * + * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} + */ + this.data = EMPTY_ARRAY_BUFFER; + + if(data) + { + this.upload(data); + } +}; + +/** + * Uploads the buffer to the GPU + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload + * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract + * @param dontBind {Boolean} whether to bind the buffer before uploading it + */ +Buffer.prototype.upload = function(data, offset, dontBind) +{ + // todo - needed? + if(!dontBind) this.bind(); + + var gl = this.gl; + + data = data || this.data; + offset = offset || 0; + + if(this.data.byteLength >= data.byteLength) + { + gl.bufferSubData(this.type, offset, data); + } + else + { + gl.bufferData(this.type, data, this.drawType); + } + + this.data = data; +}; +/** + * Binds the buffer + * + */ +Buffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindBuffer(this.type, this.buffer); +}; + +Buffer.createVertexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); +}; + +Buffer.createIndexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); +}; + +Buffer.create = function(gl, type, data, drawType) +{ + return new Buffer(gl, type, data, drawType); +}; + +/** + * Destroys the buffer + * + */ +Buffer.prototype.destroy = function(){ + this.gl.deleteBuffer(this.buffer); +}; + +module.exports = Buffer; + +},{}],7:[function(require,module,exports){ + +var Texture = require('./GLTexture'); + +/** + * Helper class to create a webGL Framebuffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + */ +var Framebuffer = function(gl, width, height) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The frame buffer + * + * @member {WebGLFramebuffer} + */ + this.framebuffer = gl.createFramebuffer(); + + /** + * The stencil buffer + * + * @member {WebGLRenderbuffer} + */ + this.stencil = null; + + /** + * The stencil buffer + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The width of the drawing area of the buffer + * + * @member {Number} + */ + this.width = width || 100; + /** + * The height of the drawing area of the buffer + * + * @member {Number} + */ + this.height = height || 100; +}; + +/** + * Adds a texture to the frame buffer + * @param texture {PIXI.glCore.GLTexture} + */ +Framebuffer.prototype.enableTexture = function(texture) +{ + var gl = this.gl; + + this.texture = texture || new Texture(gl); + + this.texture.bind(); + + //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + this.bind(); + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); +}; + +/** + * Initialises the stencil buffer + */ +Framebuffer.prototype.enableStencil = function() +{ + if(this.stencil)return; + + var gl = this.gl; + + this.stencil = gl.createRenderbuffer(); + + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + + // TODO.. this is depth AND stencil? + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width , this.height ); +}; + +/** + * Erases the drawing area and fills it with a colour + * @param r {Number} the red value of the clearing colour + * @param g {Number} the green value of the clearing colour + * @param b {Number} the blue value of the clearing colour + * @param a {Number} the alpha value of the clearing colour + */ +Framebuffer.prototype.clear = function( r, g, b, a ) +{ + this.bind(); + + var gl = this.gl; + + gl.clearColor(r, g, b, a); + gl.clear(gl.COLOR_BUFFER_BIT); +}; + +/** + * Binds the frame buffer to the WebGL context + */ +Framebuffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); +}; + +/** + * Unbinds the frame buffer to the WebGL context + */ +Framebuffer.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, null ); +}; +/** + * Resizes the drawing area of the buffer to the given width and height + * @param width {Number} the new width + * @param height {Number} the new height + */ +Framebuffer.prototype.resize = function(width, height) +{ + var gl = this.gl; + + this.width = width; + this.height = height; + + if ( this.texture ) + { + this.texture.uploadData(null, width, height); + } + + if ( this.stencil ) + { + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + } +}; + +/** + * Destroys this buffer + */ +Framebuffer.prototype.destroy = function() +{ + var gl = this.gl; + + //TODO + if(this.texture) + { + this.texture.destroy(); + } + + gl.deleteFramebuffer(this.framebuffer); + + this.gl = null; + + this.stencil = null; + this.texture = null; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createRGBA = function(gl, width, height, data) +{ + var texture = Texture.fromData(gl, null, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createFloat32 = function(gl, width, height, data) +{ + // create a new texture.. + var texture = new Texture.fromData(gl, data, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +module.exports = Framebuffer; + +},{"./GLTexture":9}],8:[function(require,module,exports){ + +var compileProgram = require('./shader/compileProgram'), + extractAttributes = require('./shader/extractAttributes'), + extractUniforms = require('./shader/extractUniforms'), + generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + +/** + * Helper class to create a webGL Shader + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + */ +var Shader = function(gl, vertexSrc, fragmentSrc) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc); + + + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); + + var uniformData = extractUniforms(gl, this.program); + + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject( gl, uniformData ); +}; +/** + * Uses this shader + */ +Shader.prototype.bind = function() +{ + this.gl.useProgram(this.program); +}; + +/** + * Destroys this shader + * TODO + */ +Shader.prototype.destroy = function() +{ + // var gl = this.gl; +}; + +module.exports = Shader; + +},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18}],9:[function(require,module,exports){ + +/** + * Helper class to create a WebGL Texture + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL context + * @param width {number} the width of the texture + * @param height {number} the height of the texture + * @param format {number} the pixel format of the texture. defaults to gl.RGBA + * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE + */ +var Texture = function(gl, width, height, format, type) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); + + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; + + + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; + + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; + + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + + +}; + +/** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ +Texture.prototype.upload = function(source) +{ + this.bind(); + + var gl = this.gl; + + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + var newWidth = source.videoWidth || source.width; + var newHeight = source.videoHeight || source.height; + + if(newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } + + // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + +}; + +var FLOATING_POINT_AVAILABLE = false; + +/** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.prototype.uploadData = function(data, width, height) +{ + this.bind(); + + var gl = this.gl; + + + if(data instanceof Float32Array) + { + if(!FLOATING_POINT_AVAILABLE) + { + var ext = gl.getExtension("OES_texture_float"); + + if(ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } + + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = gl.UNSIGNED_BYTE; + } + + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + + if(width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } + + this.width = width; + this.height = height; + + +// texSubImage2D +}; + +/** + * Binds the texture + * @param location + */ +Texture.prototype.bind = function(location) +{ + var gl = this.gl; + + if(location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } + + gl.bindTexture(gl.TEXTURE_2D, this.texture); +}; + +/** + * Unbinds the texture + */ +Texture.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, null); +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.minFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + if(this.mipmap) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.magFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); +}; + +/** + * Enables mipmapping + */ +Texture.prototype.enableMipmap = function() +{ + var gl = this.gl; + + this.bind(); + + this.mipmap = true; + + gl.generateMipmap(gl.TEXTURE_2D); +}; + +/** + * Enables linear filtering + */ +Texture.prototype.enableLinearScaling = function() +{ + this.minFilter(true); + this.magFilter(true); +}; + +/** + * Enables nearest neighbour interpolation + */ +Texture.prototype.enableNearestScaling = function() +{ + this.minFilter(false); + this.magFilter(false); +}; + +/** + * Enables clamping on the texture so WebGL will not repeat it + */ +Texture.prototype.enableWrapClamp = function() +{ + var gl = this.gl; + + this.bind(); + + 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); +}; + +/** + * Enable tiling on the texture + */ +Texture.prototype.enableWrapRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); +}; + +Texture.prototype.enableWrapMirrorRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); +}; + + +/** + * Destroys this texture + */ +Texture.prototype.destroy = function() +{ + var gl = this.gl; + //TODO + gl.deleteTexture(this.texture); +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ +Texture.fromSource = function(gl, source, premultiplyAlpha) +{ + var texture = new Texture(gl); + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); + + return texture; +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.fromData = function(gl, data, width, height) +{ + //console.log(data, width, height); + var texture = new Texture(gl); + texture.uploadData(data, width, height); + + return texture; +}; + + +module.exports = Texture; + +},{}],10:[function(require,module,exports){ + +// state object// +var setVertexAttribArrays = require( './setVertexAttribArrays' ); + +/** + * Helper class to work with WebGL VertexArrayObjects (vaos) + * Only works if WebGL extensions are enabled (they usually are) + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function VertexArrayObject(gl, state) +{ + this.nativeVaoExtension = null; + + if(!VertexArrayObject.FORCE_NATIVE) + { + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + this.nativeState = state; + + if(this.nativeVaoExtension) + { + this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + + var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + // VAO - overwrite the state.. + this.nativeState = { + tempAttribState: new Array(maxAttribs), + attribState: new Array(maxAttribs) + }; + } + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of attributes + * + * @member {Array} + */ + this.attributes = []; + + /** + * @member {PIXI.glCore.GLBuffer} + */ + this.indexBuffer = null; + + /** + * A boolean flag + * + * @member {Boolean} + */ + this.dirty = false; +} + +VertexArrayObject.prototype.constructor = VertexArrayObject; +module.exports = VertexArrayObject; + +/** +* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) +* If you find on older devices that things have gone a bit weird then set this to true. +*/ +/** + * Lets the VAO know if you should use the WebGL extension or the native methods. + * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) + * If you find on older devices that things have gone a bit weird then set this to true. + * @static + * @property {Boolean} FORCE_NATIVE + */ +VertexArrayObject.FORCE_NATIVE = false; + +/** + * Binds the buffer + */ +VertexArrayObject.prototype.bind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + + if(this.dirty) + { + this.dirty = false; + this.activate(); + } + } + else + { + + this.activate(); + } + + return this; +}; + +/** + * Unbinds the buffer + */ +VertexArrayObject.prototype.unbind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + return this; +}; + +/** + * Uses this vao + */ +VertexArrayObject.prototype.activate = function() +{ + + var gl = this.gl; + var lastBuffer = null; + + for (var i = 0; i < this.attributes.length; i++) + { + var attrib = this.attributes[i]; + + if(lastBuffer !== attrib.buffer) + { + attrib.buffer.bind(); + lastBuffer = attrib.buffer; + } + + //attrib.attribute.pointer(attrib.type, attrib.normalized, attrib.stride, attrib.start); + gl.vertexAttribPointer(attrib.attribute.location, + attrib.attribute.size, attrib.type || gl.FLOAT, + attrib.normalized || false, + attrib.stride || 0, + attrib.start || 0); + + + } + + setVertexAttribArrays(gl, this.attributes, this.nativeState); + + this.indexBuffer.bind(); + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + * @param attribute {*} + * @param type {String} + * @param normalized {Boolean} + * @param stride {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start) +{ + this.attributes.push({ + buffer: buffer, + attribute: attribute, + + location: attribute.location, + type: type || this.gl.FLOAT, + normalized: normalized || false, + stride: stride || 0, + start: start || 0 + }); + + this.dirty = true; + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + */ +VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) +{ + this.indexBuffer = buffer; + + this.dirty = true; + + return this; +}; + +/** + * Unbinds this vao and disables it + */ +VertexArrayObject.prototype.clear = function() +{ + // var gl = this.gl; + + // TODO - should this function unbind after clear? + // for now, no but lets see what happens in the real world! + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + } + + this.attributes.length = 0; + this.indexBuffer = null; + + return this; +}; + +/** + * @param type {Number} + * @param size {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.draw = function(type, size, start) +{ + var gl = this.gl; + gl.drawElements(type, size, gl.UNSIGNED_SHORT, start || 0); + + return this; +}; + +/** + * Destroy this vao + */ +VertexArrayObject.prototype.destroy = function() +{ + // lose references + this.gl = null; + this.indexBuffer = null; + this.attributes = null; + this.nativeState = null; + + if(this.nativeVao) + { + this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); + } + + this.nativeVaoExtension = null; + this.nativeVao = null; +}; + +},{"./setVertexAttribArrays":13}],11:[function(require,module,exports){ + +/** + * Helper class to create a webGL Context + * + * @class + * @memberof PIXI.glCore + * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from + * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * @return {WebGLRenderingContext} the WebGL context + */ +var createContext = function(canvas, options) +{ + var gl = canvas.getContext('webgl', options) || + canvas.getContext('experimental-webgl', options); + + if (!gl) + { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + return gl; +}; + +module.exports = createContext; + +},{}],12:[function(require,module,exports){ +var gl = { + createContext: require('./createContext'), + setVertexAttribArrays: require('./setVertexAttribArrays'), + GLBuffer: require('./GLBuffer'), + GLFramebuffer: require('./GLFramebuffer'), + GLShader: require('./GLShader'), + GLTexture: require('./GLTexture'), + VertexArrayObject: require('./VertexArrayObject'), + shader: require('./shader') +}; + +// Export for Node-compatible environments +if (typeof module !== 'undefined' && module.exports) +{ + // Export the module + module.exports = gl; +} + +// Add to the browser window pixi.gl +if (typeof window !== 'undefined') +{ + // add the window object + window.PIXI = window.PIXI || {}; + window.PIXI.glCore = gl; +} + +},{"./GLBuffer":6,"./GLFramebuffer":7,"./GLShader":8,"./GLTexture":9,"./VertexArrayObject":10,"./createContext":11,"./setVertexAttribArrays":13,"./shader":19}],13:[function(require,module,exports){ +// var GL_MAP = {}; + +/** + * @param gl {WebGLRenderingContext} The current WebGL context + * @param attribs {*} + * @param state {*} + */ +var setVertexAttribArrays = function (gl, attribs, state) +{ + var i; + if(state) + { + var tempAttribState = state.tempAttribState, + attribState = state.attribState; + + for (i = 0; i < tempAttribState.length; i++) + { + tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + tempAttribState[attribs[i].attribute.location] = true; + } + + for (i = 0; i < attribState.length; i++) + { + if (attribState[i] !== tempAttribState[i]) + { + attribState[i] = tempAttribState[i]; + + if (state.attribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } + + } + else + { + for (i = 0; i < attribs.length; i++) + { + var attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); + } + } +}; + +module.exports = setVertexAttribArrays; + +},{}],14:[function(require,module,exports){ + +/** + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @return {WebGLProgram} the shader program + */ +var compileProgram = function(gl, vertexSrc, fragmentSrc) +{ + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + + var program = gl.createProgram(); + + gl.attachShader(program, glVertShader); + gl.attachShader(program, glFragShader); + gl.linkProgram(program); + + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + console.error('Pixi.js Error: Could not initialize shader.'); + console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); + console.error('gl.getError()', gl.getError()); + + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') + { + console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + + gl.deleteProgram(program); + program = null; + } + + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + + return program; +}; + +/** + * @private + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @return {WebGLShader} the shader + */ +var compileShader = function (gl, type, src) +{ + var shader = gl.createShader(type); + + gl.shaderSource(shader, src); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + console.log(gl.getShaderInfoLog(shader)); + return null; + } + + return shader; +}; + +module.exports = compileProgram; + +},{}],15:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} Type of value + * @param size {Number} + */ +var defaultValue = function(type, size) +{ + switch (type) + { + case 'float': + return 0; + + case 'vec2': + return new Float32Array(2 * size); + + case 'vec3': + return new Float32Array(3 * size); + + case 'vec4': + return new Float32Array(4 * size); + + case 'int': + case 'sampler2D': + return 0; + + case 'ivec2': + return new Int32Array(2 * size); + + case 'ivec3': + return new Int32Array(3 * size); + + case 'ivec4': + return new Int32Array(4 * size); + + case 'bool': + return false; + + case 'bvec2': + + return booleanArray( 2 * size); + + case 'bvec3': + return booleanArray(3 * size); + + case 'bvec4': + return booleanArray(4 * size); + + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } +}; + +var booleanArray = function(size) +{ + var array = new Array(size); + + for (var i = 0; i < array.length; i++) + { + array[i] = false; + } + + return array; +}; + +module.exports = defaultValue; + +},{}],16:[function(require,module,exports){ + +var mapType = require('./mapType'); +var mapSize = require('./mapSize'); + +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the attributes from + * @return attributes {Object} + */ +var extractAttributes = function(gl, program) +{ + var attributes = {}; + + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + + for (var i = 0; i < totalAttributes; i++) + { + var attribData = gl.getActiveAttrib(program, i); + var type = mapType(gl, attribData.type); + + attributes[attribData.name] = { + type:type, + size:mapSize(type), + location:gl.getAttribLocation(program, attribData.name), + //TODO - make an attribute object + pointer: pointer + }; + } + + return attributes; +}; + +var pointer = function(type, normalized, stride, start){ + // console.log(this.location) + gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +}; + +module.exports = extractAttributes; + +},{"./mapSize":20,"./mapType":21}],17:[function(require,module,exports){ +var mapType = require('./mapType'); +var defaultValue = require('./defaultValue'); + +/** + * Extracts the uniforms + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the uniforms from + * @return uniforms {Object} + */ +var extractUniforms = function(gl, program) +{ + var uniforms = {}; + + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + + for (var i = 0; i < totalUniforms; i++) + { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]/, ""); + var type = mapType(gl, uniformData.type ); + + uniforms[name] = { + type:type, + size:uniformData.size, + location:gl.getUniformLocation(program, name), + value:defaultValue(type, uniformData.size) + }; + } + + return uniforms; +}; + +module.exports = extractUniforms; + +},{"./defaultValue":15,"./mapType":21}],18:[function(require,module,exports){ +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param uniforms {Array} @mat ? + * @return attributes {Object} + */ +var generateUniformAccessObject = function(gl, uniformData) +{ + // this is the object we will be sending back. + // an object hierachy will be created for structs + var uniforms = {data:{}}; + + uniforms.gl = gl; + + var uniformKeys= Object.keys(uniformData); + + for (var i = 0; i < uniformKeys.length; i++) + { + var fullName = uniformKeys[i]; + + var nameTokens = fullName.split('.'); + var name = nameTokens[nameTokens.length - 1]; + + var uniformGroup = getUniformGroup(nameTokens, uniforms); + + var uniform = uniformData[fullName]; + uniformGroup.data[name] = uniform; + + uniformGroup.gl = gl; + + Object.defineProperty(uniformGroup, name, { + get: generateGetter(name), + set: generateSetter(name, uniform) + }); + } + + return uniforms; +}; + +var generateGetter = function(name) +{ + var template = getterTemplate.replace('%%', name); + return new Function(template); // jshint ignore:line +}; + +var generateSetter = function(name, uniform) +{ + var template = setterTemplate.replace(/%%/g, name); + var setTemplate; + + if(uniform.size === 1) + { + setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; + } + else + { + setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; + } + + if(setTemplate) + { + template += "\nthis.gl." + setTemplate + ";"; + } + + return new Function('value', template); // jshint ignore:line +}; + +var getUniformGroup = function(nameTokens, uniform) +{ + var cur = uniform; + + for (var i = 0; i < nameTokens.length - 1; i++) + { + var o = cur[nameTokens[i]] || {data:{}}; + cur[nameTokens[i]] = o; + cur = o; + } + + return cur; +}; + +var getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +var setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;' +].join('\n'); + + +var GLSL_TO_SINGLE_SETTERS = { + + 'float': 'uniform1f(location, value)', + + 'vec2': 'uniform2f(location, value[0], value[1])', + 'vec3': 'uniform3f(location, value[0], value[1], value[2])', + 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', + + 'int': 'uniform1i(location, value)', + 'ivec2': 'uniform2i(location, value[0], value[1])', + 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', + 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'bool': 'uniform1i(location, value)', + 'bvec2': 'uniform2i(location, value[0], value[1])', + 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', + 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'mat2': 'uniformMatrix2fv(location, false, value)', + 'mat3': 'uniformMatrix3fv(location, false, value)', + 'mat4': 'uniformMatrix4fv(location, false, value)', + + 'sampler2D':'uniform1i(location, value)' +}; + +var GLSL_TO_ARRAY_SETTERS = { + + 'float': 'uniform1fv(location, value)', + + 'vec2': 'uniform2fv(location, value)', + 'vec3': 'uniform3fv(location, value)', + 'vec4': 'uniform4fv(location, value)', + + 'int': 'uniform1iv(location, value)', + 'ivec2': 'uniform2iv(location, value)', + 'ivec3': 'uniform3iv(location, value)', + 'ivec4': 'uniform4iv(location, value)', + + 'bool': 'uniform1iv(location, value)', + 'bvec2': 'uniform2iv(location, value)', + 'bvec3': 'uniform3iv(location, value)', + 'bvec4': 'uniform4iv(location, value)', + + 'sampler2D':'uniform1iv(location, value)' +}; + +module.exports = generateUniformAccessObject; + +},{}],19:[function(require,module,exports){ +module.exports = { + compileProgram: require('./compileProgram'), + defaultValue: require('./defaultValue'), + extractAttributes: require('./extractAttributes'), + extractUniforms: require('./extractUniforms'), + generateUniformAccessObject: require('./generateUniformAccessObject'), + mapSize: require('./mapSize'), + mapType: require('./mapType') +}; +},{"./compileProgram":14,"./defaultValue":15,"./extractAttributes":16,"./extractUniforms":17,"./generateUniformAccessObject":18,"./mapSize":20,"./mapType":21}],20:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} + * @return {Number} + */ +var mapSize = function(type) +{ + return GLSL_TO_SIZE[type]; +}; + + +var GLSL_TO_SIZE = { + 'float': 1, + 'vec2': 2, + 'vec3': 3, + 'vec4': 4, + + 'int': 1, + 'ivec2': 2, + 'ivec3': 3, + 'ivec4': 4, + + 'bool': 1, + 'bvec2': 2, + 'bvec3': 3, + 'bvec4': 4, + + 'mat2': 4, + 'mat3': 9, + 'mat4': 16, + + 'sampler2D': 1 +}; + +module.exports = mapSize; + +},{}],21:[function(require,module,exports){ + + +var mapSize = function(gl, type) +{ + if(!GL_TABLE) + { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + + GL_TABLE = {}; + + for(var i = 0; i < typeNames.length; ++i) + { + var tn = typeNames[i]; + GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + } + } + + return GL_TABLE[type]; +}; + +var GL_TABLE = null; + +var GL_TO_GLSL_TYPES = { + 'FLOAT': 'float', + 'FLOAT_VEC2': 'vec2', + 'FLOAT_VEC3': 'vec3', + 'FLOAT_VEC4': 'vec4', + + 'INT': 'int', + 'INT_VEC2': 'ivec2', + 'INT_VEC3': 'ivec3', + 'INT_VEC4': 'ivec4', + + 'BOOL': 'bool', + 'BOOL_VEC2': 'bvec2', + 'BOOL_VEC3': 'bvec3', + 'BOOL_VEC4': 'bvec4', + + 'FLOAT_MAT2': 'mat2', + 'FLOAT_MAT3': 'mat3', + 'FLOAT_MAT4': 'mat4', + + 'SAMPLER_2D': 'sampler2D' +}; + +module.exports = mapSize; + +},{}],22:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) + +},{"_process":23}],23:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],24:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],25:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],26:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],27:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":25,"./encode":26}],28:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":29,"punycode":24,"querystring":27}],29:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],30:[function(require,module,exports){ +'use strict' + +/** + * Remove a range of items from an array + * + * @function removeItems + * @param {Array<*>} arr The target array + * @param {number} startIdx The index to begin removing from (inclusive) + * @param {number} removeCount How many items to remove + */ +module.exports = function removeItems(arr, startIdx, removeCount) +{ + var i, length = arr.length + + if (startIdx >= length || removeCount === 0) { + return + } + + removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount) + + var len = length - removeCount + + for (i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount] + } + + arr.length = len +} + +},{}],31:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _async = require('./async'); + +var async = _interopRequireWildcard(_async); + +var _Resource = require('./Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// some constants +var MAX_PROGRESS = 100; +var rgxExtractUrlHash = /(#[\w-]+)?$/; + +/** + * Manages the state and loading of multiple resources to load. + * + * @class + */ + +var Loader = function () { + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader() { + var _this = this; + + var baseUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var concurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; + + _classCallCheck(this, Loader); + + /** + * The base url for all resources loaded by this loader. + * + * @member {string} + */ + this.baseUrl = baseUrl; + + /** + * The progress percent of the loader going through the queue. + * + * @member {number} + */ + this.progress = 0; + + /** + * Loading state of the loader, true if it is currently loading resources. + * + * @member {boolean} + */ + this.loading = false; + + /** + * A querystring to append to every URL added to the loader. + * + * This should be a valid query string *without* the question-mark (`?`). The loader will + * also *not* escape values for you. Make sure to escape your parameters with + * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. + * + * @example + * + * ```js + * const loader = new Loader(); + * + * loader.defaultQueryString = 'user=me&password=secret'; + * + * // This will request 'image.png?user=me&password=secret' + * loader.add('image.png').load(); + * + * loader.reset(); + * + * // This will request 'image.png?v=1&user=me&password=secret' + * loader.add('iamge.png?v=1').load(); + * ``` + */ + this.defaultQueryString = ''; + + /** + * The middleware to run before loading each resource. + * + * @member {function[]} + */ + this._beforeMiddleware = []; + + /** + * The middleware to run after loading each resource. + * + * @member {function[]} + */ + this._afterMiddleware = []; + + /** + * The tracks the resources we are currently completing parsing for. + * + * @member {Resource[]} + */ + this._resourcesParsing = []; + + /** + * The `_loadResource` function bound with this object context. + * + * @private + * @member {function} + * @param {Resource} r - The resource to load + * @param {Function} d - The dequeue function + * @return {undefined} + */ + this._boundLoadResource = function (r, d) { + return _this._loadResource(r, d); + }; + + /** + * The resources waiting to be loaded. + * + * @private + * @member {Resource[]} + */ + this._queue = async.queue(this._boundLoadResource, concurrency); + + this._queue.pause(); + + /** + * All the resources for this loader keyed by name. + * + * @member {object} + */ + this.resources = {}; + + /** + * Dispatched once per loaded or errored resource. + * + * The callback looks like {@link Loader.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once per errored resource. + * + * The callback looks like {@link Loader.OnErrorSignal}. + * + * @member {Signal} + */ + this.onError = new _miniSignals2.default(); + + /** + * Dispatched once per loaded resource. + * + * The callback looks like {@link Loader.OnLoadSignal}. + * + * @member {Signal} + */ + this.onLoad = new _miniSignals2.default(); + + /** + * Dispatched when the loader begins to process the queue. + * + * The callback looks like {@link Loader.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched when the queued resources all load. + * + * The callback looks like {@link Loader.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * When the progress changes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnProgressSignal + * @param {Loader} loader - The loader the progress is advancing on. + * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance. + */ + + /** + * When an error occurrs the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnErrorSignal + * @param {Loader} loader - The loader the error happened in. + * @param {Resource} resource - The resource that caused the error. + */ + + /** + * When a load completes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnLoadSignal + * @param {Loader} loader - The loader that laoded the resource. + * @param {Resource} resource - The resource that has completed loading. + */ + + /** + * When the loader starts loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnStartSignal + * @param {Loader} loader - The loader that has started loading resources. + */ + + /** + * When the loader completes loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnCompleteSignal + * @param {Loader} loader - The loader that has finished loading resources. + */ + } + + /** + * Adds a resource (or multiple resources) to the loader queue. + * + * This function can take a wide variety of different parameters. The only thing that is always + * required the url to load. All the following will work: + * + * ```js + * loader + * // normal param syntax + * .add('key', 'http://...', function () {}) + * .add('http://...', function () {}) + * .add('http://...') + * + * // object syntax + * .add({ + * name: 'key2', + * url: 'http://...' + * }, function () {}) + * .add({ + * url: 'http://...' + * }, function () {}) + * .add({ + * name: 'key3', + * url: 'http://...' + * onComplete: function () {} + * }) + * .add({ + * url: 'https://...', + * onComplete: function () {}, + * crossOrigin: true + * }) + * + * // you can also pass an array of objects or urls or both + * .add([ + * { name: 'key4', url: 'http://...', onComplete: function () {} }, + * { url: 'http://...', onComplete: function () {} }, + * 'http://...' + * ]) + * + * // and you can use both params and options + * .add('key', 'http://...', { crossOrigin: true }, function () {}) + * .add('http://...', { crossOrigin: true }, function () {}); + * ``` + * + * @param {string} [name] - The name of the resource to load, if not passed the url is used. + * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @param {object} [options] - The options for the load. + * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should + * the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @param {function} [cb] - Function to call when this specific resource completes loading. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.add = function add(name, url, options, cb) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + + return this; + } + + // if an object is passed instead of params + if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') { + cb = url || name.callback || name.onComplete; + options = name; + url = name.url; + name = name.name || name.key || name.url; + } + + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + cb = options; + options = url; + url = name; + } + + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + cb = options; + options = null; + } + + // if loading already you can only add resources that have a parent. + if (this.loading && (!options || !options.parentResource)) { + throw new Error('Cannot add resources while the loader is running.'); + } + + // check if resource already exists. + if (this.resources[name]) { + throw new Error('Resource named "' + name + '" already exists.'); + } + + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + + // create the store the resource + this.resources[name] = new _Resource2.default(name, url, options); + + if (typeof cb === 'function') { + this.resources[name].onAfterMiddleware.once(cb); + } + + // if actively loading, make sure to adjust progress chunks for that parent and its children + if (this.loading) { + var parent = options.parentResource; + var incompleteChildren = []; + + for (var _i = 0; _i < parent.children.length; ++_i) { + if (!parent.children[_i].isComplete) { + incompleteChildren.push(parent.children[_i]); + } + } + + var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent + var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child + + parent.children.push(this.resources[name]); + parent.progressChunk = eachChunk; + + for (var _i2 = 0; _i2 < incompleteChildren.length; ++_i2) { + incompleteChildren[_i2].progressChunk = eachChunk; + } + + this.resources[name].progressChunk = eachChunk; + } + + // add the resource to the queue + this._queue.push(this.resources[name]); + + return this; + }; + + /** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * + * @method before + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.pre = function pre(fn) { + this._beforeMiddleware.push(fn); + + return this; + }; + + /** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * + * @alias use + * @method after + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.use = function use(fn) { + this._afterMiddleware.push(fn); + + return this; + }; + + /** + * Resets the queue of the loader to prepare for a new load. + * + * @return {Loader} Returns itself. + */ + + + Loader.prototype.reset = function reset() { + this.progress = 0; + this.loading = false; + + this._queue.kill(); + this._queue.pause(); + + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + + if (res._onLoadBinding) { + res._onLoadBinding.detach(); + } + + if (res.isLoading) { + res.abort(); + } + } + + this.resources = {}; + + return this; + }; + + /** + * Starts loading the queued resources. + * + * @param {function} [cb] - Optional callback that will be bound to the `complete` event. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.load = function load(cb) { + // register complete callback if they pass one + if (typeof cb === 'function') { + this.onComplete.once(cb); + } + + // if the queue has already started we are done here + if (this.loading) { + return this; + } + + // distribute progress chunks + var chunk = 100 / this._queue._tasks.length; + + for (var i = 0; i < this._queue._tasks.length; ++i) { + this._queue._tasks[i].data.progressChunk = chunk; + } + + // update loading state + this.loading = true; + + // notify of start + this.onStart.dispatch(this); + + // start loading + this._queue.resume(); + + return this; + }; + + /** + * Prepares a url for usage based on the configuration of this object + * + * @private + * @param {string} url - The url to prepare. + * @return {string} The prepared url. + */ + + + Loader.prototype._prepareUrl = function _prepareUrl(url) { + var parsedUrl = (0, _parseUri2.default)(url, { strictMode: true }); + var result = void 0; + + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { + result = url; + } + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + else if (this.baseUrl.length && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 && url.charAt(0) !== '/') { + result = this.baseUrl + '/' + url; + } else { + result = this.baseUrl + url; + } + + // if we need to add a default querystring, there is a bit more work + if (this.defaultQueryString) { + var hash = rgxExtractUrlHash.exec(result)[0]; + + result = result.substr(0, result.length - hash.length); + + if (result.indexOf('?') !== -1) { + result += '&' + this.defaultQueryString; + } else { + result += '?' + this.defaultQueryString; + } + + result += hash; + } + + return result; + }; + + /** + * Loads a single resource. + * + * @private + * @param {Resource} resource - The resource to load. + * @param {function} dequeue - The function to call when we need to dequeue this item. + */ + + + Loader.prototype._loadResource = function _loadResource(resource, dequeue) { + var _this2 = this; + + resource._dequeue = dequeue; + + // run before middleware + async.eachSeries(this._beforeMiddleware, function (fn, next) { + fn.call(_this2, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, function () { + if (resource.isComplete) { + _this2._onLoad(resource); + } else { + resource._onLoadBinding = resource.onComplete.once(_this2._onLoad, _this2); + resource.load(); + } + }); + }; + + /** + * Called once each resource has loaded. + * + * @private + */ + + + Loader.prototype._onComplete = function _onComplete() { + this.loading = false; + + this.onComplete.dispatch(this, this.resources); + }; + + /** + * Called each time a resources is loaded. + * + * @private + * @param {Resource} resource - The resource that was loaded + */ + + + Loader.prototype._onLoad = function _onLoad(resource) { + var _this3 = this; + + resource._onLoadBinding = null; + + // remove this resource from the async queue, and add it to our list of resources that are being parsed + resource._dequeue(); + this._resourcesParsing.push(resource); + + // run middleware, this *must* happen before dequeue so sub-assets get added properly + async.eachSeries(this._afterMiddleware, function (fn, next) { + fn.call(_this3, resource, next); + }, function () { + resource.onAfterMiddleware.dispatch(resource); + + _this3.progress += resource.progressChunk; + _this3.onProgress.dispatch(_this3, resource); + + if (resource.error) { + _this3.onError.dispatch(resource.error, _this3, resource); + } else { + _this3.onLoad.dispatch(_this3, resource); + } + + _this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1); + + // do completion check + if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) { + _this3.progress = MAX_PROGRESS; + _this3._onComplete(); + } + }); + }; + + return Loader; +}(); + +exports.default = Loader; + +},{"./Resource":32,"./async":33,"mini-signals":37,"parse-uri":38}],32:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// tests is CORS is supported in XHR, if not we need to use XDR +var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest())); +var tempAnchor = null; + +// some status constants +var STATUS_NONE = 0; +var STATUS_OK = 200; +var STATUS_EMPTY = 204; + +// noop +function _noop() {} /* empty */ + +/** + * Manages the state and loading of a resource and all child resources. + * + * @class + */ + +var Resource = function () { + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. + */ + Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) { + setExtMap(Resource._loadTypeMap, extname, loadType); + }; + + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ + + + Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); + }; + + /** + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass + * an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + */ + + + function Resource(name, url, options) { + _classCallCheck(this, Resource); + + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + + options = options || {}; + + /** + * The state flags of this resource. + * + * @member {number} + */ + this._flags = 0; + + // set data url flag, needs to be set early for some _determineX checks to work. + this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); + + /** + * The name of this resource. + * + * @member {string} + * @readonly + */ + this.name = name; + + /** + * The url used to load this resource. + * + * @member {string} + * @readonly + */ + this.url = url; + + /** + * The extension used to load this resource. + * + * @member {string} + * @readonly + */ + this.extension = this._getExtension(); + + /** + * The data that was loaded by the resource. + * + * @member {any} + */ + this.data = null; + + /** + * Is this request cross-origin? If unset, determined automatically. + * + * @member {string} + */ + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + + /** + * The method of loading to use for this resource. + * + * @member {Resource.LOAD_TYPE} + */ + this.loadType = options.loadType || this._determineLoadType(); + + /** + * The type used to load the resource via XHR. If unset, determined automatically. + * + * @member {string} + */ + this.xhrType = options.xhrType; + + /** + * Extra info for middleware, and controlling specifics about how the resource loads. + * + * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + * Meaning it will modify it as it sees fit. + * + * @member {object} + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources + * to. + */ + this.metadata = options.metadata || {}; + + /** + * The error that occurred while loading (if any). + * + * @member {Error} + * @readonly + */ + this.error = null; + + /** + * The XHR object that was used to load this resource. This is only set + * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * + * @member {XMLHttpRequest} + * @readonly + */ + this.xhr = null; + + /** + * The child resources this resource owns. + * + * @member {Resource[]} + * @readonly + */ + this.children = []; + + /** + * The resource type. + * + * @member {Resource.TYPE} + * @readonly + */ + this.type = Resource.TYPE.UNKNOWN; + + /** + * The progress chunk owned by this resource. + * + * @member {number} + * @readonly + */ + this.progressChunk = 0; + + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * + * @private + * @member {function} + */ + this._dequeue = _noop; + + /** + * Used a storage place for the on load binding used privately by the loader. + * + * @private + * @member {function} + */ + this._onLoadBinding = null; + + /** + * The `complete` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundComplete = this.complete.bind(this); + + /** + * The `_onError` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnError = this._onError.bind(this); + + /** + * The `_onProgress` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnProgress = this._onProgress.bind(this); + + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + this._boundXdrOnTimeout = this._xdrOnTimeout.bind(this); + + /** + * Dispatched when the resource beings to load. + * + * The callback looks like {@link Resource.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched each time progress of this resource load updates. + * Not all resources types and loader systems can support this event + * so sometimes it may not be available. If the resource + * is being loaded on a modern browser, using XHR, and the remote server + * properly sets Content-Length headers, then this will be available. + * + * The callback looks like {@link Resource.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once this resource has loaded, if there was an error it will + * be in the `error` property. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * Dispatched after this resource has had all the *after* middleware run on it. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onAfterMiddleware = new _miniSignals2.default(); + + /** + * When the resource starts to load. + * + * @memberof Resource + * @callback OnStartSignal + * @param {Resource} resource - The resource that the event happened on. + */ + + /** + * When the resource reports loading progress. + * + * @memberof Resource + * @callback OnProgressSignal + * @param {Resource} resource - The resource that the event happened on. + * @param {number} percentage - The progress of the load in the range [0, 1]. + */ + + /** + * When the resource finishes loading. + * + * @memberof Resource + * @callback OnCompleteSignal + * @param {Resource} resource - The resource that the event happened on. + */ + } + + /** + * Stores whether or not this url is a data url. + * + * @member {boolean} + * @readonly + */ + + + /** + * Marks the resource as complete. + * + */ + Resource.prototype.complete = function complete() { + // TODO: Clean this up in a wrapper or something...gross.... + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + + this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true); + this._setFlag(Resource.STATUS_FLAGS.LOADING, false); + + this.onComplete.dispatch(this); + }; + + /** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ + + + Resource.prototype.abort = function abort(message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + + // store error + this.error = new Error(message); + + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } else if (this.xdr) { + this.xdr.abort(); + } else if (this.data) { + // single source + if (this.data.src) { + this.data.src = Resource.EMPTY_GIF; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + + // done now. + this.complete(); + }; + + /** + * Kicks off loading of this resource. This method is asynchronous. + * + * @param {function} [cb] - Optional callback to call once the resource is loaded. + */ + + + Resource.prototype.load = function load(cb) { + var _this = this; + + if (this.isLoading) { + return; + } + + if (this.isComplete) { + if (cb) { + setTimeout(function () { + return cb(_this); + }, 1); + } + + return; + } else if (cb) { + this.onComplete.once(cb); + } + + this._setFlag(Resource.STATUS_FLAGS.LOADING, true); + + this.onStart.dispatch(this); + + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + + switch (this.loadType) { + case Resource.LOAD_TYPE.IMAGE: + this.type = Resource.TYPE.IMAGE; + this._loadElement('image'); + break; + + case Resource.LOAD_TYPE.AUDIO: + this.type = Resource.TYPE.AUDIO; + this._loadSourceElement('audio'); + break; + + case Resource.LOAD_TYPE.VIDEO: + this.type = Resource.TYPE.VIDEO; + this._loadSourceElement('video'); + break; + + case Resource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } else { + this._loadXhr(); + } + break; + } + }; + + /** + * Checks if the flag is set. + * + * @private + * @param {number} flag - The flag to check. + * @return {boolean} True if the flag is set. + */ + + + Resource.prototype._hasFlag = function _hasFlag(flag) { + return !!(this._flags & flag); + }; + + /** + * (Un)Sets the flag. + * + * @private + * @param {number} flag - The flag to (un)set. + * @param {boolean} value - Whether to set or (un)set the flag. + */ + + + Resource.prototype._setFlag = function _setFlag(flag, value) { + this._flags = value ? this._flags | flag : this._flags & ~flag; + }; + + /** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadElement = function _loadElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'image' && typeof window.Image !== 'undefined') { + this.data = new Image(); + } else { + this.data = document.createElement(type); + } + + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + }; + + /** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadSourceElement = function _loadSourceElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'audio' && typeof window.Audio !== 'undefined') { + this.data = new Audio(); + } else { + this.data = document.createElement(type); + } + + if (this.data === null) { + this.abort('Unsupported element: ' + type); + + return; + } + + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } else if (Array.isArray(this.url)) { + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i])); + } + } else { + this.data.appendChild(this._createSource(type, this.url)); + } + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + + this.data.load(); + }; + + /** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ + + + Resource.prototype._loadXhr = function _loadXhr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xhr = this.xhr = new XMLHttpRequest(); + + // set the request type and url + xhr.open('GET', this.url, true); + + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; + } else { + xhr.responseType = this.xhrType; + } + + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + + xhr.send(); + }; + + /** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ + + + Resource.prototype._loadXdr = function _loadXdr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xdr = this.xhr = new XDomainRequest(); + + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = 5000; + + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXdrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + + xdr.open('GET', this.url, true); + + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { + return xdr.send(); + }, 1); + }; + + /** + * Creates a source used in loading via an element. + * + * @private + * @param {string} type - The element type (video or audio). + * @param {string} url - The source URL to load from. + * @param {string} [mime] - The mime type of the video + * @return {HTMLSourceElement} The source element. + */ + + + Resource.prototype._createSource = function _createSource(type, url, mime) { + if (!mime) { + mime = type + '/' + url.substr(url.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = url; + source.type = mime; + + return source; + }; + + /** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ + + + Resource.prototype._onError = function _onError(event) { + this.abort('Failed to load element using: ' + event.target.nodeName); + }; + + /** + * Called if a load progress event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ + + + Resource.prototype._onProgress = function _onProgress(event) { + if (event && event.lengthComputable) { + this.onProgress.dispatch(this, event.loaded / event.total); + } + }; + + /** + * Called if an error event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestErrorEvent|Event} event - Error event. + */ + + + Resource.prototype._xhrOnError = function _xhrOnError() { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"'); + }; + + /** + * Called if an abort event fires for xhr. + * + * @private + * @param {XMLHttpRequestAbortEvent} event - Abort Event + */ + + + Resource.prototype._xhrOnAbort = function _xhrOnAbort() { + this.abort(reqType(this.xhr) + ' Request was aborted by the user.'); + }; + + /** + * Called if a timeout event fires for xdr. + * + * @private + * @param {Event} event - Timeout event. + */ + + + Resource.prototype._xdrOnTimeout = function _xdrOnTimeout() { + this.abort(reqType(this.xhr) + ' Request timed out.'); + }; + + /** + * Called when data successfully loads from an xhr/xdr request. + * + * @private + * @param {XMLHttpRequestLoadEvent|Event} event - Load event + */ + + + Resource.prototype._xhrOnLoad = function _xhrOnLoad() { + var xhr = this.xhr; + var status = typeof xhr.status === 'undefined' ? xhr.status : STATUS_OK; // XDR has no `.status`, assume 200. + + // status can be 0 when using the `file://` protocol so we also check if a response is set + if (status === STATUS_OK || status === STATUS_EMPTY || status === STATUS_NONE && xhr.responseText.length > 0) { + // if text, just return it + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { + this.data = xhr.responseText; + this.type = Resource.TYPE.TEXT; + } + // if json, parse into json object + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(xhr.responseText); + this.type = Resource.TYPE.JSON; + } catch (e) { + this.abort('Error trying to parse loaded json: ' + e); + + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (window.DOMParser) { + var domparser = new DOMParser(); + + this.data = domparser.parseFromString(xhr.responseText, 'text/xml'); + } else { + var div = document.createElement('div'); + + div.innerHTML = xhr.responseText; + + this.data = div; + } + + this.type = Resource.TYPE.XML; + } catch (e) { + this.abort('Error trying to parse loaded xml: ' + e); + + return; + } + } + // other types just return the response + else { + this.data = xhr.response || xhr.responseText; + } + } else { + this.abort('[' + xhr.status + '] ' + xhr.statusText + ': ' + xhr.responseURL); + + return; + } + + this.complete(); + }; + + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * + * @private + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ + + + Resource.prototype._determineCrossOrigin = function _determineCrossOrigin(url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = (0, _parseUri2.default)(tempAnchor.href, { strictMode: true }); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + var protocol = url.protocol ? url.protocol + ':' : ''; + + // if cross origin + if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; + }; + + /** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. + */ + + + Resource.prototype._determineXhrType = function _determineXhrType() { + return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT; + }; + + /** + * Determines the loadType of a resource based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.LOAD_TYPE} The loadType to use. + */ + + + Resource.prototype._determineLoadType = function _determineLoadType() { + return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR; + }; + + /** + * Extracts the extension (sans '.') of the file being loaded by the resource. + * + * @private + * @return {string} The extension. + */ + + + Resource.prototype._getExtension = function _getExtension() { + var url = this.url; + var ext = ''; + + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } else { + var queryStart = url.indexOf('?'); + + if (queryStart !== -1) { + url = url.substring(0, queryStart); + } + + ext = url.substring(url.lastIndexOf('.') + 1); + } + + return ext.toLowerCase(); + }; + + /** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * + * @private + * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. + * @return {string} The mime type to use. + */ + + + Resource.prototype._getMimeFromXhrType = function _getMimeFromXhrType(type) { + switch (type) { + case Resource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + + case Resource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + + case Resource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + + case Resource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + + case Resource.XHR_RESPONSE_TYPE.DEFAULT: + case Resource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + + } + }; + + _createClass(Resource, [{ + key: 'isDataUrl', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL); + } + + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isComplete', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE); + } + + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isLoading', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.LOADING); + } + }]); + + return Resource; +}(); + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ + + +exports.default = Resource; +Resource.STATUS_FLAGS = { + NONE: 0, + DATA_URL: 1 << 0, + COMPLETE: 1 << 1, + LOADING: 1 << 2 +}; + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ +Resource.TYPE = { + UNKNOWN: 0, + JSON: 1, + XML: 2, + IMAGE: 3, + AUDIO: 4, + VIDEO: 5, + TEXT: 6 +}; + +/** + * The types of loading a resource can use. + * + * @static + * @readonly + * @enum {number} + */ +Resource.LOAD_TYPE = { + /** Uses XMLHttpRequest to load the resource. */ + XHR: 1, + /** Uses an `Image` object to load the resource. */ + IMAGE: 2, + /** Uses an `Audio` object to load the resource. */ + AUDIO: 3, + /** Uses a `Video` object to load the resource. */ + VIDEO: 4 +}; + +/** + * The XHR ready states, used internally. + * + * @static + * @readonly + * @enum {string} + */ +Resource.XHR_RESPONSE_TYPE = { + /** string */ + DEFAULT: 'text', + /** ArrayBuffer */ + BUFFER: 'arraybuffer', + /** Blob */ + BLOB: 'blob', + /** Document */ + DOCUMENT: 'document', + /** Object */ + JSON: 'json', + /** String */ + TEXT: 'text' +}; + +Resource._loadTypeMap = { + // images + gif: Resource.LOAD_TYPE.IMAGE, + png: Resource.LOAD_TYPE.IMAGE, + bmp: Resource.LOAD_TYPE.IMAGE, + jpg: Resource.LOAD_TYPE.IMAGE, + jpeg: Resource.LOAD_TYPE.IMAGE, + tif: Resource.LOAD_TYPE.IMAGE, + tiff: Resource.LOAD_TYPE.IMAGE, + webp: Resource.LOAD_TYPE.IMAGE, + tga: Resource.LOAD_TYPE.IMAGE, + svg: Resource.LOAD_TYPE.IMAGE, + 'svg+xml': Resource.LOAD_TYPE.IMAGE, // for SVG data urls + + // audio + mp3: Resource.LOAD_TYPE.AUDIO, + ogg: Resource.LOAD_TYPE.AUDIO, + wav: Resource.LOAD_TYPE.AUDIO, + + // videos + mp4: Resource.LOAD_TYPE.VIDEO, + webm: Resource.LOAD_TYPE.VIDEO +}; + +Resource._xhrTypeMap = { + // xml + xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. + // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, + // this should probably be fine. + tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // images + gif: Resource.XHR_RESPONSE_TYPE.BLOB, + png: Resource.XHR_RESPONSE_TYPE.BLOB, + bmp: Resource.XHR_RESPONSE_TYPE.BLOB, + jpg: Resource.XHR_RESPONSE_TYPE.BLOB, + jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, + tif: Resource.XHR_RESPONSE_TYPE.BLOB, + tiff: Resource.XHR_RESPONSE_TYPE.BLOB, + webp: Resource.XHR_RESPONSE_TYPE.BLOB, + tga: Resource.XHR_RESPONSE_TYPE.BLOB, + + // json + json: Resource.XHR_RESPONSE_TYPE.JSON, + + // text + text: Resource.XHR_RESPONSE_TYPE.TEXT, + txt: Resource.XHR_RESPONSE_TYPE.TEXT, + + // fonts + ttf: Resource.XHR_RESPONSE_TYPE.BUFFER, + otf: Resource.XHR_RESPONSE_TYPE.BUFFER +}; + +// We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif +Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; + +/** + * Quick helper to set a value on one of the extension maps. Ensures there is no + * dot at the start of the extension. + * + * @ignore + * @param {object} map - The map to set on. + * @param {string} extname - The extension (or key) to set. + * @param {number} val - The value to set. + */ +function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + + if (!extname) { + return; + } + + map[extname] = val; +} + +/** + * Quick helper to get string xhr type. + * + * @ignore + * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. + * @return {string} The type. + */ +function reqType(xhr) { + return xhr.toString().replace('object ', ''); +} + +},{"mini-signals":37,"parse-uri":38}],33:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.eachSeries = eachSeries; +exports.queue = queue; +/** + * Smaller version of the async library constructs. + * + */ +function _noop() {} /* empty */ + +/** + * Iterates an array in series. + * + * @param {*[]} array - Array to iterate. + * @param {function} iterator - Function to call for each element. + * @param {function} callback - Function to call when done, or on error. + */ +function eachSeries(array, iterator, callback) { + var i = 0; + var len = array.length; + + (function next(err) { + if (err || i === len) { + if (callback) { + callback(err); + } + + return; + } + + iterator(array[i++], next); + })(); +} + +/** + * Ensures a function is only called once. + * + * @param {function} fn - The function to wrap. + * @return {function} The wrapping function. + */ +function onlyOnce(fn) { + return function onceWrapper() { + if (fn === null) { + throw new Error('Callback was already called.'); + } + + var callFn = fn; + + fn = null; + callFn.apply(this, arguments); + }; +} + +/** + * Async queue implementation, + * + * @param {function} worker - The worker function to call for each task. + * @param {number} concurrency - How many workers to run in parrallel. + * @return {*} The async queue object. + */ +function queue(worker, concurrency) { + if (concurrency == null) { + // eslint-disable-line no-eq-null,eqeqeq + concurrency = 1; + } else if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + + var workers = 0; + var q = { + _tasks: [], + concurrency: concurrency, + saturated: _noop, + unsaturated: _noop, + buffer: concurrency / 4, + empty: _noop, + drain: _noop, + error: _noop, + started: false, + paused: false, + push: function push(data, callback) { + _insert(data, false, callback); + }, + kill: function kill() { + workers = 0; + q.drain = _noop; + q.started = false; + q._tasks = []; + }, + unshift: function unshift(data, callback) { + _insert(data, true, callback); + }, + process: function process() { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var task = q._tasks.shift(); + + if (q._tasks.length === 0) { + q.empty(); + } + + workers += 1; + + if (workers === q.concurrency) { + q.saturated(); + } + + worker(task.data, onlyOnce(_next(task))); + } + }, + length: function length() { + return q._tasks.length; + }, + running: function running() { + return workers; + }, + idle: function idle() { + return q._tasks.length + workers === 0; + }, + pause: function pause() { + if (q.paused === true) { + return; + } + + q.paused = true; + }, + resume: function resume() { + if (q.paused === false) { + return; + } + + q.paused = false; + + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= q.concurrency; w++) { + q.process(); + } + } + }; + + function _insert(data, insertAtFront, callback) { + if (callback != null && typeof callback !== 'function') { + // eslint-disable-line no-eq-null,eqeqeq + throw new Error('task callback must be a function'); + } + + q.started = true; + + if (data == null && q.idle()) { + // eslint-disable-line no-eq-null,eqeqeq + // call drain immediately if there are no tasks + setTimeout(function () { + return q.drain(); + }, 1); + + return; + } + + var item = { + data: data, + callback: typeof callback === 'function' ? callback : _noop + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + setTimeout(function () { + return q.process(); + }, 1); + } + + function _next(task) { + return function next() { + workers -= 1; + + task.callback.apply(task, arguments); + + if (arguments[0] != null) { + // eslint-disable-line no-eq-null,eqeqeq + q.error(arguments[0], task.data); + } + + if (workers <= q.concurrency - q.buffer) { + q.unsaturated(); + } + + if (q.idle()) { + q.drain(); + } + + q.process(); + }; + } + + return q; +} + +},{}],34:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.encodeBinary = encodeBinary; +var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +function encodeBinary(input) { + var output = ''; + var inx = 0; + + while (inx < input.length) { + // Fill byte buffer array + var bytebuffer = [0, 0, 0]; + var encodedCharIndexes = [0, 0, 0, 0]; + + for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } else { + bytebuffer[jnx] = 0; + } + } + + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4; + + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6; + + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + + // Determine whether padding happened, and adjust accordingly + var paddingBytes = inx - (input.length - 1); + + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + + default: + break; // No padding - proceed + } + + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) { + output += _keyStr.charAt(encodedCharIndexes[_jnx]); + } + } + + return output; +} + +},{}],35:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Loader = require('./Loader'); + +var _Loader2 = _interopRequireDefault(_Loader); + +var _Resource = require('./Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +var _async = require('./async'); + +var async = _interopRequireWildcard(_async); + +var _b = require('./b64'); + +var b64 = _interopRequireWildcard(_b); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +_Loader2.default.Resource = _Resource2.default; +_Loader2.default.async = async; +_Loader2.default.base64 = b64; + +// export manually, and also as default +module.exports = _Loader2.default; // eslint-disable-line no-undef +exports.default = _Loader2.default; + +},{"./Loader":31,"./Resource":32,"./async":33,"./b64":34}],36:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +exports.blobMiddlewareFactory = blobMiddlewareFactory; + +var _Resource = require('../../Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +var _b = require('../../b64'); + +var _b2 = _interopRequireDefault(_b); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Url = window.URL || window.webkitURL; + +// a middleware for transforming XHR loaded Blobs into more useful objects +function blobMiddlewareFactory() { + return function blobMiddleware(resource, next) { + if (!resource.data) { + next(); + + return; + } + + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === _Resource2.default.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!window.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = 'data:' + type + ';base64,' + _b2.default.encodeBinary(resource.xhr.responseText); + + resource.type = _Resource2.default.TYPE.IMAGE; + + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + + next(); + }; + + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var _ret = function () { + var src = Url.createObjectURL(resource.data); + + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src; + + resource.type = _Resource2.default.TYPE.IMAGE; + + // cleanup the no longer used blob after the image loads + // TODO: Is this correct? Will the image be invalid after revoking? + resource.data.onload = function () { + Url.revokeObjectURL(src); + resource.data.onload = null; + + next(); + }; + + // next will be called on load. + return { + v: void 0 + }; + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + } + + next(); + }; +} + +},{"../../Resource":32,"../../b64":34}],37:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + +var MiniSignalBinding = (function () { + function MiniSignalBinding(fn, once, thisArg) { + if (once === undefined) once = false; + + _classCallCheck(this, MiniSignalBinding); + + this._fn = fn; + this._once = once; + this._thisArg = thisArg; + this._next = this._prev = this._owner = null; + } + + _createClass(MiniSignalBinding, [{ + key: 'detach', + value: function detach() { + if (this._owner === null) return false; + this._owner.detach(this); + return true; + } + }]); + + return MiniSignalBinding; +})(); + +function _addMiniSignalBinding(self, node) { + if (!self._head) { + self._head = node; + self._tail = node; + } else { + self._tail._next = node; + node._prev = self._tail; + self._tail = node; + } + + node._owner = self; + + return node; +} + +var MiniSignal = (function () { + function MiniSignal() { + _classCallCheck(this, MiniSignal); + + this._head = this._tail = undefined; + } + + _createClass(MiniSignal, [{ + key: 'handlers', + value: function handlers() { + var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; + + var node = this._head; + + if (exists) return !!node; + + var ee = []; + + while (node) { + ee.push(node); + node = node._next; + } + + return ee; + } + }, { + key: 'has', + value: function has(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.'); + } + + return node._owner === this; + } + }, { + key: 'dispatch', + value: function dispatch() { + var node = this._head; + + if (!node) return false; + + while (node) { + if (node._once) this.detach(node); + node._fn.apply(node._thisArg, arguments); + node = node._next; + } + + return true; + } + }, { + key: 'add', + value: function add(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#add(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg)); + } + }, { + key: 'once', + value: function once(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#once(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg)); + } + }, { + key: 'detach', + value: function detach(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.'); + } + if (node._owner !== this) return this; + + if (node._prev) node._prev._next = node._next; + if (node._next) node._next._prev = node._prev; + + if (node === this._head) { + this._head = node._next; + if (node._next === null) { + this._tail = null; + } + } else if (node === this._tail) { + this._tail = node._prev; + this._tail._next = null; + } + + node._owner = null; + return this; + } + }, { + key: 'detachAll', + value: function detachAll() { + var node = this._head; + if (!node) return this; + + this._head = this._tail = null; + + while (node) { + node._owner = null; + node = node._next; + } + return this; + } + }]); + + return MiniSignal; +})(); + +MiniSignal.MiniSignalBinding = MiniSignalBinding; + +exports['default'] = MiniSignal; +module.exports = exports['default']; + +},{}],38:[function(require,module,exports){ +'use strict' + +module.exports = function parseURI (str, opts) { + opts = opts || {} + + var o = { + key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], + q: { + name: 'queryKey', + parser: /(?:^|&)([^&=]*)=?([^&]*)/g + }, + parser: { + strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, + loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ + } + } + + var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str) + var uri = {} + var i = 14 + + while (i--) uri[o.key[i]] = m[i] || '' + + uri[o.q.name] = {} + uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { + if ($1) uri[o.q.name][$1] = $2 + }) + + return uri +} + +},{}],39:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +var _accessibleTarget = require('./accessibleTarget'); + +var _accessibleTarget2 = _interopRequireDefault(_accessibleTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// add some extra variables to the container.. +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _accessibleTarget2.default); + +var KEY_CODE_TAB = 9; + +var DIV_TOUCH_SIZE = 100; +var DIV_TOUCH_POS_X = 0; +var DIV_TOUCH_POS_Y = 0; +var DIV_TOUCH_ZINDEX = 2; + +var DIV_HOOK_SIZE = 1; +var DIV_HOOK_POS_X = -1000; +var DIV_HOOK_POS_Y = -1000; +var DIV_HOOK_ZINDEX = 2; + +/** + * The Accessibility manager recreates the ability to tab and have content read by screen + * readers. This is very important as it can possibly help people with disabilities access pixi + * content. + * + * Much like interaction any DisplayObject can be made accessible. This manager will map the + * events as if the mouse was being used, minimizing the effort required to implement. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.accessibility + * + * @class + * @memberof PIXI.accessibility + */ + +var AccessibilityManager = function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + _classCallCheck(this, AccessibilityManager); + + if ((_ismobilejs2.default.tablet || _ismobilejs2.default.phone) && !navigator.isCocoonJS) { + this.createTouchHook(); + } + + // first we create a div that will sit over the pixi element. This is where the div overlays will go. + var div = document.createElement('div'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + 'px'; + div.style.left = DIV_TOUCH_POS_Y + 'px'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + + /** + * This is the dom element that will sit over the pixi element. This is where the div overlays will go. + * + * @type {HTMLElement} + * @private + */ + this.div = div; + + /** + * A simple pool for storing divs. + * + * @type {*} + * @private + */ + this.pool = []; + + /** + * This is a tick used to check if an object is no longer being rendered. + * + * @type {Number} + * @private + */ + this.renderId = 0; + + /** + * Setting this to true will visually show the divs. + * + * @type {boolean} + */ + this.debug = false; + + /** + * The renderer this accessibility manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * The array of currently active accessible items. + * + * @member {Array<*>} + * @private + */ + this.children = []; + + /** + * pre-bind the functions + * + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + + /** + * stores the state of the manager. If there are no accessible objects or the mouse is moving, this will be false. + * + * @member {Array<*>} + * @private + */ + this.isActive = false; + this.isMobileAccessabillity = false; + + // let listen for tab.. once pressed we can fire up and show the accessibility layer + window.addEventListener('keydown', this._onKeyDown, false); + } + + /** + * Creates the touch hooks. + * + */ + + + AccessibilityManager.prototype.createTouchHook = function createTouchHook() { + var _this = this; + + var hookDiv = document.createElement('button'); + + hookDiv.style.width = DIV_HOOK_SIZE + 'px'; + hookDiv.style.height = DIV_HOOK_SIZE + 'px'; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + 'px'; + hookDiv.style.left = DIV_HOOK_POS_Y + 'px'; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX; + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'HOOK DIV'; + + hookDiv.addEventListener('focus', function () { + _this.isMobileAccessabillity = true; + _this.activate(); + document.body.removeChild(hookDiv); + }); + + document.body.appendChild(hookDiv); + }; + + /** + * Activating will cause the Accessibility layer to be shown. This is called when a user + * preses the tab key. + * + * @private + */ + + + AccessibilityManager.prototype.activate = function activate() { + if (this.isActive) { + return; + } + + this.isActive = true; + + window.document.addEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown, false); + + this.renderer.on('postrender', this.update, this); + + if (this.renderer.view.parentNode) { + this.renderer.view.parentNode.appendChild(this.div); + } + }; + + /** + * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves + * the mouse. + * + * @private + */ + + + AccessibilityManager.prototype.deactivate = function deactivate() { + if (!this.isActive || this.isMobileAccessabillity) { + return; + } + + this.isActive = false; + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.addEventListener('keydown', this._onKeyDown, false); + + this.renderer.off('postrender', this.update); + + if (this.div.parentNode) { + this.div.parentNode.removeChild(this.div); + } + }; + + /** + * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. + * + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + + + AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects(displayObject) { + if (!displayObject.visible) { + return; + } + + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + + displayObject.renderId = this.renderId; + } + + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + this.updateAccessibleObjects(children[i]); + } + }; + + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * + * @private + */ + + + AccessibilityManager.prototype.update = function update() { + if (!this.renderer.renderingToScreen) { + return; + } + + // update children... + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + + var rect = this.renderer.view.getBoundingClientRect(); + var sx = rect.width / this.renderer.width; + var sy = rect.height / this.renderer.height; + + var div = this.div; + + div.style.left = rect.left + 'px'; + div.style.top = rect.top + 'px'; + div.style.width = this.renderer.width + 'px'; + div.style.height = this.renderer.height + 'px'; + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + + core.utils.removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + + i--; + + if (this.children.length === 0) { + this.deactivate(); + } + } else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + + if (child.hitArea) { + div.style.left = (wt.tx + hitArea.x * wt.a) * sx + 'px'; + div.style.top = (wt.ty + hitArea.y * wt.d) * sy + 'px'; + + div.style.width = hitArea.width * wt.a * sx + 'px'; + div.style.height = hitArea.height * wt.d * sy + 'px'; + } else { + hitArea = child.getBounds(); + + this.capHitArea(hitArea); + + div.style.left = hitArea.x * sx + 'px'; + div.style.top = hitArea.y * sy + 'px'; + + div.style.width = hitArea.width * sx + 'px'; + div.style.height = hitArea.height * sy + 'px'; + } + } + } + + // increment the render id.. + this.renderId++; + }; + + /** + * TODO: docs. + * + * @param {Rectangle} hitArea - TODO docs + */ + + + AccessibilityManager.prototype.capHitArea = function capHitArea(hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + + if (hitArea.x + hitArea.width > this.renderer.width) { + hitArea.width = this.renderer.width - hitArea.x; + } + + if (hitArea.y + hitArea.height > this.renderer.height) { + hitArea.height = this.renderer.height - hitArea.y; + } + }; + + /** + * Adds a DisplayObject to the accessibility manager + * + * @private + * @param {DisplayObject} displayObject - The child to make accessible. + */ + + + AccessibilityManager.prototype.addChild = function addChild(displayObject) { + // this.activate(); + + var div = this.pool.pop(); + + if (!div) { + div = document.createElement('button'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + div.style.borderStyle = 'none'; + + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + + if (displayObject.accessibleTitle) { + div.title = displayObject.accessibleTitle; + } else if (!displayObject.accessibleTitle && !displayObject.accessibleHint) { + div.title = 'displayObject ' + this.tabIndex; + } + + if (displayObject.accessibleHint) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + + // + + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + + /** + * Maps the div button press to pixi's InteractionManager (click) + * + * @private + * @param {MouseEvent} e - The click event. + */ + + + AccessibilityManager.prototype._onClick = function _onClick(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixi's InteractionManager (mouseover) + * + * @private + * @param {FocusEvent} e - The focus event. + */ + + + AccessibilityManager.prototype._onFocus = function _onFocus(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixi's InteractionManager (mouseout) + * + * @private + * @param {FocusEvent} e - The focusout event. + */ + + + AccessibilityManager.prototype._onFocusOut = function _onFocusOut(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); + }; + + /** + * Is called when a key is pressed + * + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + + + AccessibilityManager.prototype._onKeyDown = function _onKeyDown(e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + + this.activate(); + }; + + /** + * Is called when the mouse moves across the renderer element + * + * @private + */ + + + AccessibilityManager.prototype._onMouseMove = function _onMouseMove() { + this.deactivate(); + }; + + /** + * Destroys the accessibility manager + * + */ + + + AccessibilityManager.prototype.destroy = function destroy() { + this.div = null; + + for (var i = 0; i < this.children.length; i++) { + this.children[i].div = null; + } + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.removeEventListener('keydown', this._onKeyDown); + + this.pool = null; + this.children = null; + this.renderer = null; + }; + + return AccessibilityManager; +}(); + +exports.default = AccessibilityManager; + + +core.WebGLRenderer.registerPlugin('accessibility', AccessibilityManager); +core.CanvasRenderer.registerPlugin('accessibility', AccessibilityManager); + +},{"../core":64,"./accessibleTarget":40,"ismobilejs":4}],40:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Default property values of accessible objects + * used by {@link PIXI.accessibility.AccessibilityManager}. + * + * @function accessibleTarget + * @memberof PIXI.accessibility + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibility.accessibleTarget + * ); + */ +exports.default = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * + * @member {boolean} + */ + accessible: false, + + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * + * @member {string} + */ + accessibleTitle: null, + + /** + * Sets the aria-label attribute of the shadow div + * + * @member {string} + */ + accessibleHint: null, + + /** + * @todo Needs docs. + */ + tabIndex: 0, + + /** + * @todo Needs docs. + */ + _accessibleActive: false, + + /** + * @todo Needs docs. + */ + _accessibleDiv: false +}; + +},{}],41:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _accessibleTarget = require('./accessibleTarget'); + +Object.defineProperty(exports, 'accessibleTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_accessibleTarget).default; + } +}); + +var _AccessibilityManager = require('./AccessibilityManager'); + +Object.defineProperty(exports, 'AccessibilityManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AccessibilityManager).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./AccessibilityManager":39,"./accessibleTarget":40}],42:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +var _Container = require('./display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _ticker = require('./ticker'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _const = require('./const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Convenience class to create a new PIXI application. + * This class automatically creates the renderer, ticker + * and root container. + * + * @example + * // Create the application + * const app = new PIXI.Application(); + * + * // Add the view to the DOM + * document.body.appendChild(app.view); + * + * // ex, add display objects + * app.stage.addChild(PIXI.Sprite.fromImage('something.png')); + * + * @class + * @memberof PIXI + */ +var Application = function () { + // eslint-disable-next-line valid-jsdoc + /** + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great **webgl only** + * @param {boolean} [options.legacy=false] - `true` to ensure compatibility with older / less advanced devices. + * If you experience unexplained flickering try setting this to true. **webgl only** + * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.ticker.shared, `false` to create new ticker. + * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.loaders.shared, `false` to create new Loader. + */ + function Application(options, arg2, arg3, arg4, arg5) { + _classCallCheck(this, Application); + + // Support for constructor(width, height, options, noWebGL, useSharedTicker) + if (typeof options === 'number') { + options = Object.assign({ + width: options, + height: arg2 || _settings2.default.RENDER_OPTIONS.height, + forceCanvas: !!arg4, + sharedTicker: !!arg5 + }, arg3); + } + + /** + * The default options, so we mixin functionality later. + * @member {object} + * @protected + */ + this._options = options = Object.assign({ + sharedTicker: false, + forceCanvas: false, + sharedLoader: false + }, options); + + /** + * WebGL renderer if available, otherwise CanvasRenderer + * @member {PIXI.WebGLRenderer|PIXI.CanvasRenderer} + */ + this.renderer = (0, _autoDetectRenderer.autoDetectRenderer)(options); + + /** + * The root display container that's rendered. + * @member {PIXI.Container} + */ + this.stage = new _Container2.default(); + + /** + * Internal reference to the ticker + * @member {PIXI.ticker.Ticker} + * @private + */ + this._ticker = null; + + /** + * Ticker for doing render updates. + * @member {PIXI.ticker.Ticker} + * @default PIXI.ticker.shared + */ + this.ticker = options.sharedTicker ? _ticker.shared : new _ticker.Ticker(); + + // Start the rendering + this.start(); + } + + /** + * Render the current stage. + */ + Application.prototype.render = function render() { + this.renderer.render(this.stage); + }; + + /** + * Convenience method for stopping the render. + */ + + + Application.prototype.stop = function stop() { + this._ticker.stop(); + }; + + /** + * Convenience method for starting the render. + */ + + + Application.prototype.start = function start() { + this._ticker.start(); + }; + + /** + * Reference to the renderer's canvas element. + * @member {HTMLCanvasElement} + * @readonly + */ + + + /** + * Destroy and don't use after this. + * @param {Boolean} [removeView=false] Automatically remove canvas from DOM. + */ + Application.prototype.destroy = function destroy(removeView) { + var oldTicker = this._ticker; + + this.ticker = null; + + oldTicker.destroy(); + + this.stage.destroy(); + this.stage = null; + + this.renderer.destroy(removeView); + this.renderer = null; + + this._options = null; + }; + + _createClass(Application, [{ + key: 'ticker', + set: function set(ticker) // eslint-disable-line require-jsdoc + { + if (this._ticker) { + this._ticker.remove(this.render, this); + } + this._ticker = ticker; + if (ticker) { + ticker.add(this.render, this, _const.UPDATE_PRIORITY.LOW); + } + }, + get: function get() // eslint-disable-line require-jsdoc + { + return this._ticker; + } + }, { + key: 'view', + get: function get() { + return this.renderer.view; + } + + /** + * Reference to the renderer's screen rectangle. Its safe to use as filterArea or hitArea for whole screen + * @member {PIXI.Rectangle} + * @readonly + */ + + }, { + key: 'screen', + get: function get() { + return this.renderer.screen; + } + }]); + + return Application; +}(); + +exports.default = Application; + +},{"./autoDetectRenderer":44,"./const":45,"./display/Container":47,"./settings":100,"./ticker":119}],43:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function checkPrecision(src, def) { + if (src instanceof Array) { + if (src[0].substring(0, 9) !== 'precision') { + var copy = src.slice(0); + + copy.unshift('precision ' + def + ' float;'); + + return copy; + } + } else if (src.substring(0, 9) !== 'precision') { + return 'precision ' + def + ' float;\n' + src; + } + + return src; +} + +/** + * Wrapper class, webGL Shader for Pixi. + * Adds precision string if vertexSrc or fragmentSrc have no mention of it. + * + * @class + * @extends GLShader + * @memberof PIXI + */ + +var Shader = function (_GLShader) { + _inherits(Shader, _GLShader); + + /** + * + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + * @param {string|string[]} vertexSrc - The vertex shader source as an array of strings. + * @param {string|string[]} fragmentSrc - The fragment shader source as an array of strings. + */ + function Shader(gl, vertexSrc, fragmentSrc) { + _classCallCheck(this, Shader); + + return _possibleConstructorReturn(this, _GLShader.call(this, gl, checkPrecision(vertexSrc, _settings2.default.PRECISION_VERTEX), checkPrecision(fragmentSrc, _settings2.default.PRECISION_FRAGMENT))); + } + + return Shader; +}(_pixiGlCore.GLShader); + +exports.default = Shader; + +},{"./settings":100,"pixi-gl-core":12}],44:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = autoDetectRenderer; + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// eslint-disable-next-line valid-jsdoc +/** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by + * the browser then this function will return a canvas renderer + * + * @memberof PIXI + * @function autoDetectRenderer + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great **webgl only** + * @param {boolean} [options.legacy=false] - `true` to ensure compatibility with older / less advanced devices. + * If you experience unexplained flickering try setting this to true. **webgl only** + * @return {PIXI.WebGLRenderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ +function autoDetectRenderer(options, arg1, arg2, arg3) { + // Backward-compatible support for noWebGL option + var forceCanvas = options && options.forceCanvas; + + if (arg3 !== undefined) { + forceCanvas = arg3; + } + + if (!forceCanvas && utils.isWebGLSupported()) { + return new _WebGLRenderer2.default(options, arg1, arg2); + } + + return new _CanvasRenderer2.default(options, arg1, arg2); +} + +},{"./renderers/canvas/CanvasRenderer":76,"./renderers/webgl/WebGLRenderer":83,"./utils":123}],45:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * String of the current PIXI version. + * + * @static + * @constant + * @memberof PIXI + * @name VERSION + * @type {string} + */ +var VERSION = exports.VERSION = '4.5.3'; + +/** + * Two Pi. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var PI_2 = exports.PI_2 = Math.PI * 2; + +/** + * Conversion factor for converting radians to degrees. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var RAD_TO_DEG = exports.RAD_TO_DEG = 180 / Math.PI; + +/** + * Conversion factor for converting degrees to radians. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var DEG_TO_RAD = exports.DEG_TO_RAD = Math.PI / 180; + +/** + * Constant to identify the Renderer Type. + * + * @static + * @constant + * @memberof PIXI + * @name RENDERER_TYPE + * @type {object} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ +var RENDERER_TYPE = exports.RENDERER_TYPE = { + UNKNOWN: 0, + WEBGL: 1, + CANVAS: 2 +}; + +/** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * + * @static + * @constant + * @memberof PIXI + * @name BLEND_MODES + * @type {object} + * @property {number} NORMAL + * @property {number} ADD + * @property {number} MULTIPLY + * @property {number} SCREEN + * @property {number} OVERLAY + * @property {number} DARKEN + * @property {number} LIGHTEN + * @property {number} COLOR_DODGE + * @property {number} COLOR_BURN + * @property {number} HARD_LIGHT + * @property {number} SOFT_LIGHT + * @property {number} DIFFERENCE + * @property {number} EXCLUSION + * @property {number} HUE + * @property {number} SATURATION + * @property {number} COLOR + * @property {number} LUMINOSITY + */ +var BLEND_MODES = exports.BLEND_MODES = { + NORMAL: 0, + ADD: 1, + MULTIPLY: 2, + SCREEN: 3, + OVERLAY: 4, + DARKEN: 5, + LIGHTEN: 6, + COLOR_DODGE: 7, + COLOR_BURN: 8, + HARD_LIGHT: 9, + SOFT_LIGHT: 10, + DIFFERENCE: 11, + EXCLUSION: 12, + HUE: 13, + SATURATION: 14, + COLOR: 15, + LUMINOSITY: 16, + NORMAL_NPM: 17, + ADD_NPM: 18, + SCREEN_NPM: 19 +}; + +/** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * + * @static + * @constant + * @memberof PIXI + * @name DRAW_MODES + * @type {object} + * @property {number} POINTS + * @property {number} LINES + * @property {number} LINE_LOOP + * @property {number} LINE_STRIP + * @property {number} TRIANGLES + * @property {number} TRIANGLE_STRIP + * @property {number} TRIANGLE_FAN + */ +var DRAW_MODES = exports.DRAW_MODES = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6 +}; + +/** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @static + * @constant + * @memberof PIXI + * @name SCALE_MODES + * @type {object} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ +var SCALE_MODES = exports.SCALE_MODES = { + LINEAR: 0, + NEAREST: 1 +}; + +/** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wraping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as webGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * + * @static + * @constant + * @name WRAP_MODES + * @memberof PIXI + * @type {object} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ +var WRAP_MODES = exports.WRAP_MODES = { + CLAMP: 0, + REPEAT: 1, + MIRRORED_REPEAT: 2 +}; + +/** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for pixi textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * + * @static + * @constant + * @name GC_MODES + * @memberof PIXI + * @type {object} + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ +var GC_MODES = exports.GC_MODES = { + AUTO: 0, + MANUAL: 1 +}; + +/** + * Regexp for image type by extension. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `image.png` + */ +var URL_FILE_EXTENSION = exports.URL_FILE_EXTENSION = /\.(\w{3,4})(?:$|\?|#)/i; + +/** + * Regexp for data URI. + * Based on: {@link https://github.com/ragingwind/data-uri-regex} + * + * @static + * @constant + * @name DATA_URI + * @memberof PIXI + * @type {RegExp|string} + * @example data:image/png;base64 + */ +var DATA_URI = exports.DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;(charset=[\w-]+|base64))?,(.*)/i; + +/** + * Regexp for SVG size. + * + * @static + * @constant + * @name SVG_SIZE + * @memberof PIXI + * @type {RegExp|string} + * @example <svg width="100" height="100"></svg> + */ +var SVG_SIZE = exports.SVG_SIZE = /]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len + +/** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * + * @static + * @constant + * @name SHAPES + * @memberof PIXI + * @type {object} + * @property {number} POLY Polygon + * @property {number} RECT Rectangle + * @property {number} CIRC Circle + * @property {number} ELIP Ellipse + * @property {number} RREC Rounded Rectangle + */ +var SHAPES = exports.SHAPES = { + POLY: 0, + RECT: 1, + CIRC: 2, + ELIP: 3, + RREC: 4 +}; + +/** + * Constants that specify float precision in shaders. + * + * @static + * @constant + * @name PRECISION + * @memberof PIXI + * @type {object} + * @property {string} LOW='lowp' + * @property {string} MEDIUM='mediump' + * @property {string} HIGH='highp' + */ +var PRECISION = exports.PRECISION = { + LOW: 'lowp', + MEDIUM: 'mediump', + HIGH: 'highp' +}; + +/** + * Constants that specify the transform type. + * + * @static + * @constant + * @name TRANSFORM_MODE + * @memberof PIXI + * @type {object} + * @property {number} STATIC + * @property {number} DYNAMIC + */ +var TRANSFORM_MODE = exports.TRANSFORM_MODE = { + STATIC: 0, + DYNAMIC: 1 +}; + +/** + * Constants that define the type of gradient on text. + * + * @static + * @constant + * @name TEXT_GRADIENT + * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL Vertical gradient + * @property {number} LINEAR_HORIZONTAL Linear gradient + */ +var TEXT_GRADIENT = exports.TEXT_GRADIENT = { + LINEAR_VERTICAL: 0, + LINEAR_HORIZONTAL: 1 +}; + +/** + * Represents the update priorities used by internal PIXI classes when registered with + * the {@link PIXI.ticker.Ticker} object. Higher priority items are updated first and lower + * priority items, such as render, should go later. + * + * @static + * @constant + * @name UPDATE_PRIORITY + * @memberof PIXI + * @type {object} + * @property {number} INTERACTION=50 Highest priority, used for {@link PIXI.interaction.InteractionManager} + * @property {number} HIGH=25 High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.extras.AnimatedSprite} + * @property {number} NORMAL=0 Default priority for ticker events, see {@link PIXI.ticker.Ticker#add}. + * @property {number} LOW=-25 Low priority used for {@link PIXI.Application} rendering. + * @property {number} UTILITY=-50 Lowest priority used for {@link PIXI.prepare.BasePrepare} utility. + */ +var UPDATE_PRIORITY = exports.UPDATE_PRIORITY = { + INTERACTION: 50, + HIGH: 25, + NORMAL: 0, + LOW: -25, + UTILITY: -50 +}; + +},{}],46:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * 'Builder' pattern for bounds rectangles + * Axis-Aligned Bounding Box + * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems + * + * @class + * @memberof PIXI + */ +var Bounds = function () { + /** + * + */ + function Bounds() { + _classCallCheck(this, Bounds); + + /** + * @member {number} + * @default 0 + */ + this.minX = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.minY = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxX = -Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxY = -Infinity; + + this.rect = null; + } + + /** + * Checks if bounds are empty. + * + * @return {boolean} True if empty. + */ + + + Bounds.prototype.isEmpty = function isEmpty() { + return this.minX > this.maxX || this.minY > this.maxY; + }; + + /** + * Clears the bounds and resets. + * + */ + + + Bounds.prototype.clear = function clear() { + this.updateID++; + + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * + * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty + * @returns {PIXI.Rectangle} A rectangle of the bounds + */ + + + Bounds.prototype.getRectangle = function getRectangle(rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return _math.Rectangle.EMPTY; + } + + rect = rect || new _math.Rectangle(0, 0, 1, 1); + + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + + return rect; + }; + + /** + * This function should be inlined when its possible. + * + * @param {PIXI.Point} point - The point to add. + */ + + + Bounds.prototype.addPoint = function addPoint(point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + }; + + /** + * Adds a quad, not transformed + * + * @param {Float32Array} vertices - The verts to add. + */ + + + Bounds.prototype.addQuad = function addQuad(vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = vertices[0]; + var y = vertices[1]; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds sprite frame, transformed. + * + * @param {PIXI.TransformBase} transform - TODO + * @param {number} x0 - TODO + * @param {number} y0 - TODO + * @param {number} x1 - TODO + * @param {number} y1 - TODO + */ + + + Bounds.prototype.addFrame = function addFrame(transform, x0, y0, x1, y1) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = a * x0 + c * y0 + tx; + var y = b * x0 + d * y0 + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y0 + tx; + y = b * x1 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x0 + c * y1 + tx; + y = b * x0 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y1 + tx; + y = b * x1 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Add an array of vertices + * + * @param {PIXI.TransformBase} transform - TODO + * @param {Float32Array} vertices - TODO + * @param {number} beginOffset - TODO + * @param {number} endOffset - TODO + */ + + + Bounds.prototype.addVertices = function addVertices(transform, vertices, beginOffset, endOffset) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = a * rawX + c * rawY + tx; + var y = d * rawY + b * rawX + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds other Bounds + * + * @param {PIXI.Bounds} bounds - TODO + */ + + + Bounds.prototype.addBounds = function addBounds(bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + }; + + /** + * Adds other Bounds, masked with Bounds + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Bounds} mask - TODO + */ + + + Bounds.prototype.addBoundsMask = function addBoundsMask(bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + /** + * Adds other Bounds, masked with Rectangle + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Rectangle} area - TODO + */ + + + Bounds.prototype.addBoundsArea = function addBoundsArea(bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : area.x + area.width; + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : area.y + area.height; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + return Bounds; +}(); + +exports.default = Bounds; + +},{"../math":69}],47:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _DisplayObject2 = require('./DisplayObject'); + +var _DisplayObject3 = _interopRequireDefault(_DisplayObject2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A Container represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + *```js + * let container = new PIXI.Container(); + * container.addChild(sprite); + * ``` + * + * @class + * @extends PIXI.DisplayObject + * @memberof PIXI + */ +var Container = function (_DisplayObject) { + _inherits(Container, _DisplayObject); + + /** + * + */ + function Container() { + _classCallCheck(this, Container); + + /** + * The array of children of this container. + * + * @member {PIXI.DisplayObject[]} + * @readonly + */ + var _this = _possibleConstructorReturn(this, _DisplayObject.call(this)); + + _this.children = []; + return _this; + } + + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified + * + * @private + */ + + + Container.prototype.onChildrenChange = function onChildrenChange() {} + /* empty */ + + + /** + * Adds one or more children to the container. + * + * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container + * @return {PIXI.DisplayObject} The first child that was added. + */ + ; + + Container.prototype.addChild = function addChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.addChild(arguments[i]); + } + } else { + // if the child has a parent then lets remove it as Pixi objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.push(child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + child.emit('added', this); + } + + return child; + }; + + /** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @return {PIXI.DisplayObject} The child that was added. + */ + + + Container.prototype.addChildAt = function addChildAt(child, index) { + if (index < 0 || index > this.children.length) { + throw new Error(child + 'addChildAt: The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.splice(index, 0, child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + + return child; + }; + + /** + * Swaps the position of 2 Display Objects within this container. + * + * @param {PIXI.DisplayObject} child - First display object to swap + * @param {PIXI.DisplayObject} child2 - Second display object to swap + */ + + + Container.prototype.swapChildren = function swapChildren(child, child2) { + if (child === child2) { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; + + /** + * Returns the index position of a child DisplayObject instance + * + * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify + * @return {number} The index position of the child display object to identify + */ + + + Container.prototype.getChildIndex = function getChildIndex(child) { + var index = this.children.indexOf(child); + + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + }; + + /** + * Changes the position of an existing child in the display object container + * + * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number + * @param {number} index - The resulting index number for the child display object + */ + + + Container.prototype.setChildIndex = function setChildIndex(child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + (0, _utils.removeItems)(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + + this.onChildrenChange(index); + }; + + /** + * Returns the child at the specified index + * + * @param {number} index - The index to get the child at + * @return {PIXI.DisplayObject} The child at the given index, if any. + */ + + + Container.prototype.getChildAt = function getChildAt(index) { + if (index < 0 || index >= this.children.length) { + throw new Error('getChildAt: Index (' + index + ') does not exist.'); + } + + return this.children[index]; + }; + + /** + * Removes one or more children from the container. + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove + * @return {PIXI.DisplayObject} The first child that was removed. + */ + + + Container.prototype.removeChild = function removeChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.removeChild(arguments[i]); + } + } else { + var index = this.children.indexOf(child); + + if (index === -1) return null; + + child.parent = null; + // ensure child transform will be recalculated + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + } + + return child; + }; + + /** + * Removes a child from the specified index position. + * + * @param {number} index - The index to get the child from + * @return {PIXI.DisplayObject} The child that was removed. + */ + + + Container.prototype.removeChildAt = function removeChildAt(index) { + var child = this.getChildAt(index); + + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + + return child; + }; + + /** + * Removes all children from this container that are within the begin and end indexes. + * + * @param {number} [beginIndex=0] - The beginning position. + * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. + * @returns {DisplayObject[]} List of removed children + */ + + + Container.prototype.removeChildren = function removeChildren() { + var beginIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var endIndex = arguments[1]; + + var begin = beginIndex; + var end = typeof endIndex === 'number' ? endIndex : this.children.length; + var range = end - begin; + var removed = void 0; + + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } + + this._boundsID++; + + this.onChildrenChange(beginIndex); + + for (var _i = 0; _i < removed.length; ++_i) { + removed[_i].emit('removed', this); + } + + return removed; + } else if (range === 0 && this.children.length === 0) { + return []; + } + + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + }; + + /** + * Updates the transform on all children of this container for rendering + */ + + + Container.prototype.updateTransform = function updateTransform() { + this._boundsID++; + + this.transform.updateTransform(this.parent.transform); + + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + + if (child.visible) { + child.updateTransform(); + } + } + }; + + /** + * Recalculates the bounds of the container. + * + */ + + + Container.prototype.calculateBounds = function calculateBounds() { + this._bounds.clear(); + + this._calculateBounds(); + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (!child.visible || !child.renderable) { + continue; + } + + child.calculateBounds(); + + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + child._mask.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, child._mask._bounds); + } else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } else { + this._bounds.addBounds(child._bounds); + } + } + + this._lastBoundsID = this._boundsID; + }; + + /** + * Recalculates the bounds of the object. Override this to + * calculate the bounds of the specific object (not including children). + * + */ + + + Container.prototype._calculateBounds = function _calculateBounds() {} + // FILL IN// + + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderWebGL = function renderWebGL(renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + // do a quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) { + this.renderAdvancedWebGL(renderer); + } else { + this._renderWebGL(renderer); + + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderWebGL(renderer); + } + } + }; + + /** + * Render the object using the WebGL renderer and advanced features. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { + renderer.flush(); + + var filters = this._filters; + var mask = this._mask; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + + this._enabledFilters.length = 0; + + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + + if (this._enabledFilters.length) { + renderer.filterManager.pushFilter(this, this._enabledFilters); + } + } + + if (mask) { + renderer.maskManager.pushMask(this, this._mask); + } + + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); + + // now loop through the children and make sure they get rendered + for (var _i2 = 0, j = this.children.length; _i2 < j; _i2++) { + this.children[_i2].renderWebGL(renderer); + } + + renderer.flush(); + + if (mask) { + renderer.maskManager.popMask(this, this._mask); + } + + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filterManager.popFilter(); + } + }; + + /** + * To be overridden by the subclasses. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype._renderWebGL = function _renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * To be overridden by the subclass + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype._renderCanvas = function _renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderCanvas = function renderCanvas(renderer) { + // if not visible or the alpha is 0 then no need to render this + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + if (this._mask) { + renderer.maskManager.pushMask(this._mask); + } + + this._renderCanvas(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderCanvas(renderer); + } + + if (this._mask) { + renderer.maskManager.popMask(renderer); + } + }; + + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Container.prototype.destroy = function destroy(options) { + _DisplayObject.prototype.destroy.call(this); + + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + + var oldChildren = this.removeChildren(0, this.children.length); + + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + }; + + /** + * The width of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Container, [{ + key: 'width', + get: function get() { + return this.scale.x * this.getLocalBounds().width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var width = this.getLocalBounds().width; + + if (width !== 0) { + this.scale.x = value / width; + } else { + this.scale.x = 1; + } + + this._width = value; + } + + /** + * The height of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.scale.y * this.getLocalBounds().height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var height = this.getLocalBounds().height; + + if (height !== 0) { + this.scale.y = value / height; + } else { + this.scale.y = 1; + } + + this._height = value; + } + }]); + + return Container; +}(_DisplayObject3.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = Container; +Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + +},{"../utils":123,"./DisplayObject":48}],48:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TransformStatic = require('./TransformStatic'); + +var _TransformStatic2 = _interopRequireDefault(_TransformStatic); + +var _Transform = require('./Transform'); + +var _Transform2 = _interopRequireDefault(_Transform); + +var _Bounds = require('./Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _math = require('../math'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// _tempDisplayObjectParent = new DisplayObject(); + +/** + * The base class for all objects that are rendered on the screen. + * This is an abstract class and should not be used on its own rather it should be extended. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var DisplayObject = function (_EventEmitter) { + _inherits(DisplayObject, _EventEmitter); + + /** + * + */ + function DisplayObject() { + _classCallCheck(this, DisplayObject); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + var TransformClass = _settings2.default.TRANSFORM_MODE === _const.TRANSFORM_MODE.STATIC ? _TransformStatic2.default : _Transform2.default; + + _this.tempDisplayObjectParent = null; + + // TODO: need to create Transform from factory + /** + * World transform and local transform of this object. + * This will become read-only later, please do not assign anything there unless you know what are you doing + * + * @member {PIXI.TransformBase} + */ + _this.transform = new TransformClass(); + + /** + * The opacity of the object. + * + * @member {number} + */ + _this.alpha = 1; + + /** + * The visibility of the object. If false the object will not be drawn, and + * the updateTransform function will not be called. + * + * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually + * + * @member {boolean} + */ + _this.visible = true; + + /** + * Can this object be rendered, if false the object will not be drawn but the updateTransform + * methods will still be called. + * + * Only affects recursive calls from parent. You can ask for bounds manually + * + * @member {boolean} + */ + _this.renderable = true; + + /** + * The display object container that contains this display object. + * + * @member {PIXI.Container} + * @readonly + */ + _this.parent = null; + + /** + * The multiplied alpha of the displayObject + * + * @member {number} + * @readonly + */ + _this.worldAlpha = 1; + + /** + * The area the filter is applied to. This is used as more of an optimisation + * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle + * + * Also works as an interaction mask + * + * @member {PIXI.Rectangle} + */ + _this.filterArea = null; + + _this._filters = null; + _this._enabledFilters = null; + + /** + * The bounds object, this is used to calculate and store the bounds of the displayObject + * + * @member {PIXI.Rectangle} + * @private + */ + _this._bounds = new _Bounds2.default(); + _this._boundsID = 0; + _this._lastBoundsID = -1; + _this._boundsRect = null; + _this._localBoundsRect = null; + + /** + * The original, cached mask of the object + * + * @member {PIXI.Graphics|PIXI.Sprite} + * @private + */ + _this._mask = null; + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + + /** + * Fired when this DisplayObject is added to a Container. + * + * @event PIXI.DisplayObject#added + * @param {PIXI.Container} container - The container added to. + */ + + /** + * Fired when this DisplayObject is removed from a Container. + * + * @event PIXI.DisplayObject#removed + * @param {PIXI.Container} container - The container removed from. + */ + return _this; + } + + /** + * @private + * @member {PIXI.DisplayObject} + */ + + + /** + * Updates the object transform for rendering + * + * TODO - Optimization pass! + */ + DisplayObject.prototype.updateTransform = function updateTransform() { + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + this._bounds.updateID++; + }; + + /** + * recursively updates transform of all objects from the root to this one + * internal function for toLocal() + */ + + + DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform() { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + }; + + /** + * Retrieves the bounds of the displayObject as a rectangle object. + * + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @param {PIXI.Rectangle} rect - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getBounds = function getBounds(skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + + if (this._boundsID !== this._lastBoundsID) { + this.calculateBounds(); + } + + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new _math.Rectangle(); + } + + rect = this._boundsRect; + } + + return this._bounds.getRectangle(rect); + }; + + /** + * Retrieves the local bounds of the displayObject as a rectangle object + * + * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getLocalBounds = function getLocalBounds(rect) { + var transformRef = this.transform; + var parentRef = this.parent; + + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + var bounds = this.getBounds(false, rect); + + this.parent = parentRef; + this.transform = transformRef; + + return bounds; + }; + + /** + * Calculates the global position of the display object + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform. + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toGlobal = function toGlobal(position, point) { + var skipUpdate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; + + /** + * Calculates the local position of the display object relative to another point + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toLocal = function toLocal(position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + DisplayObject.prototype.renderCanvas = function renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Set the parent Container of this DisplayObject + * + * @param {PIXI.Container} container - The Container to add this DisplayObject to + * @return {PIXI.Container} The Container that this DisplayObject was added to + */ + ; + + DisplayObject.prototype.setParent = function setParent(container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); + } + + container.addChild(this); + + return container; + }; + + /** + * Convenience function to set the position, scale, skew and pivot at once. + * + * @param {number} [x=0] - The X position + * @param {number} [y=0] - The Y position + * @param {number} [scaleX=1] - The X scale value + * @param {number} [scaleY=1] - The Y scale value + * @param {number} [rotation=0] - The rotation + * @param {number} [skewX=0] - The X skew value + * @param {number} [skewY=0] - The Y skew value + * @param {number} [pivotX=0] - The X pivot value + * @param {number} [pivotY=0] - The Y pivot value + * @return {PIXI.DisplayObject} The DisplayObject instance + */ + + + DisplayObject.prototype.setTransform = function setTransform() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var scaleX = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var scaleY = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var rotation = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var skewX = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + var skewY = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + var pivotX = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; + var pivotY = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0; + + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + + return this; + }; + + /** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy`. + * + */ + + + DisplayObject.prototype.destroy = function destroy() { + this.removeAllListeners(); + if (this.parent) { + this.parent.removeChild(this); + } + this.transform = null; + + this.parent = null; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this.filterArea = null; + + this.interactive = false; + this.interactiveChildren = false; + + this._destroyed = true; + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + * + * @member {number} + */ + + + _createClass(DisplayObject, [{ + key: '_tempDisplayObjectParent', + get: function get() { + if (this.tempDisplayObjectParent === null) { + this.tempDisplayObjectParent = new DisplayObject(); + } + + return this.tempDisplayObjectParent; + } + }, { + key: 'x', + get: function get() { + return this.position.x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.x = value; + } + + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + * + * @member {number} + */ + + }, { + key: 'y', + get: function get() { + return this.position.y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.y = value; + } + + /** + * Current transform of the object based on world (parent) factors + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'worldTransform', + get: function get() { + return this.transform.worldTransform; + } + + /** + * Current transform of the object based on local factors: position, scale, other stuff + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'localTransform', + get: function get() { + return this.transform.localTransform; + } + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'position', + get: function get() { + return this.transform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.copy(value); + } + + /** + * The scale factor of the object. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'scale', + get: function get() { + return this.transform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.scale.copy(value); + } + + /** + * The pivot point of the displayObject that it rotates around + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'pivot', + get: function get() { + return this.transform.pivot; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.pivot.copy(value); + } + + /** + * The skew factor for the object in radians. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'skew', + get: function get() { + return this.transform.skew; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.skew.copy(value); + } + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + }, { + key: 'rotation', + get: function get() { + return this.transform.rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.rotation = value; + } + + /** + * Indicates if the object is globally visible. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'worldVisible', + get: function get() { + var item = this; + + do { + if (!item.visible) { + return false; + } + + item = item.parent; + } while (item); + + return true; + } + + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PIXI a regular mask must be a + * PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it + * utilises shape clipping. To remove a mask, set this property to null. + * + * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + * + * @member {PIXI.Graphics|PIXI.Sprite} + */ + + }, { + key: 'mask', + get: function get() { + return this._mask; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._mask) { + this._mask.renderable = true; + } + + this._mask = value; + + if (this._mask) { + this._mask.renderable = false; + } + } + + /** + * Sets the filters for the displayObject. + * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * To remove filters simply set this property to 'null' + * + * @member {PIXI.Filter[]} + */ + + }, { + key: 'filters', + get: function get() { + return this._filters && this._filters.slice(); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._filters = value && value.slice(); + } + }]); + + return DisplayObject; +}(_eventemitter2.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = DisplayObject; +DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + +},{"../const":45,"../math":69,"../settings":100,"./Bounds":46,"./Transform":49,"./TransformStatic":51,"eventemitter3":3}],49:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Generic class to deal with traditional 2D matrix transforms + * local transformation is calculated from position,scale,skew and rotation + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var Transform = function (_TransformBase) { + _inherits(Transform, _TransformBase); + + /** + * + */ + function Transform() { + _classCallCheck(this, Transform); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.Point} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.Point(0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.Point} + */ + _this.scale = new _math.Point(1, 1); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.Point} + */ + _this.pivot = new _math.Point(0, 0); + + /** + * The rotation value of the object, in radians + * + * @member {Number} + * @private + */ + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + return _this; + } + + /** + * Updates the skew values when the skew or rotation changes. + * + * @private + */ + + + Transform.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + }; + + /** + * Updates only local matrix + */ + + + Transform.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + Transform.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + Transform.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(Transform, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return Transform; +}(_TransformBase3.default); + +exports.default = Transform; + +},{"../math":69,"./TransformBase":50}],50:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Generic class to deal with traditional 2D matrix transforms + * + * @class + * @memberof PIXI + */ +var TransformBase = function () { + /** + * + */ + function TransformBase() { + _classCallCheck(this, TransformBase); + + /** + * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds() + * + * @member {PIXI.Matrix} + */ + this.worldTransform = new _math.Matrix(); + + /** + * The local matrix transform + * + * @member {PIXI.Matrix} + */ + this.localTransform = new _math.Matrix(); + + this._worldID = 0; + this._parentID = 0; + } + + /** + * TransformBase does not have decomposition, so this function wont do anything + */ + + + TransformBase.prototype.updateLocalTransform = function updateLocalTransform() {} + // empty + + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.TransformBase} parentTransform - The transform of the parent of this object + */ + ; + + TransformBase.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + return TransformBase; +}(); + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ + + +exports.default = TransformBase; +TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; + +TransformBase.IDENTITY = new TransformBase(); + +},{"../math":69}],51:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Transform that takes care about its versions + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var TransformStatic = function (_TransformBase) { + _inherits(TransformStatic, _TransformBase); + + /** + * + */ + function TransformStatic() { + _classCallCheck(this, TransformStatic); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.ObservablePoint} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.ObservablePoint} + */ + _this.scale = new _math.ObservablePoint(_this.onChange, _this, 1, 1); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.ObservablePoint} + */ + _this.pivot = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + + _this._localID = 0; + _this._currentLocalID = 0; + return _this; + } + + /** + * Called when a value changes. + * + * @private + */ + + + TransformStatic.prototype.onChange = function onChange() { + this._localID++; + }; + + /** + * Called when skew or rotation changes + * + * @private + */ + + + TransformStatic.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + + this._localID++; + }; + + /** + * Updates only local matrix + */ + + + TransformStatic.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + TransformStatic.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._parentID = parentTransform._worldID; + + // update the id of the transform.. + this._worldID++; + } + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + TransformStatic.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + this._localID++; + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(TransformStatic, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return TransformStatic; +}(_TransformBase3.default); + +exports.default = TransformStatic; + +},{"../math":69,"./TransformBase":50}],52:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _GraphicsData = require('./GraphicsData'); + +var _GraphicsData2 = _interopRequireDefault(_GraphicsData); + +var _Sprite = require('../sprites/Sprite'); + +var _Sprite2 = _interopRequireDefault(_Sprite); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Bounds = require('../display/Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _bezierCurveTo2 = require('./utils/bezierCurveTo'); + +var _bezierCurveTo3 = _interopRequireDefault(_bezierCurveTo2); + +var _CanvasRenderer = require('../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var canvasRenderer = void 0; +var tempMatrix = new _math.Matrix(); +var tempPoint = new _math.Point(); +var tempColor1 = new Float32Array(4); +var tempColor2 = new Float32Array(4); + +/** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Graphics = function (_Container) { + _inherits(Graphics, _Container); + + /** + * + * @param {boolean} [nativeLines=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + */ + function Graphics() { + var nativeLines = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + _classCallCheck(this, Graphics); + + /** + * The alpha value used when filling the Graphics object. + * + * @member {number} + * @default 1 + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @member {number} + * @default 0 + */ + _this.lineWidth = 0; + + /** + * If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * + * @member {boolean} + */ + _this.nativeLines = nativeLines; + + /** + * The color of any lines drawn. + * + * @member {string} + * @default 0 + */ + _this.lineColor = 0; + + /** + * Graphics data + * + * @member {PIXI.GraphicsData[]} + * @private + */ + _this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to + * reset the tint. + * + * @member {number} + * @default 0xFFFFFF + */ + _this.tint = 0xFFFFFF; + + /** + * The previous tint applied to the graphic shape. Used to compare to the current tint and + * check if theres change. + * + * @member {number} + * @private + * @default 0xFFFFFF + */ + _this._prevTint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * Current path + * + * @member {PIXI.GraphicsData} + * @private + */ + _this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @member {object} + * @private + */ + // TODO - _webgl should use a prototype object, not a random undocumented object... + _this._webGL = {}; + + /** + * Whether this shape is being used as a mask. + * + * @member {boolean} + */ + _this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @member {number} + */ + _this.boundsPadding = 0; + + /** + * A cache of the local bounds to prevent recalculation. + * + * @member {PIXI.Rectangle} + * @private + */ + _this._localBounds = new _Bounds2.default(); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics + * object will be recalculated. + * + * @member {boolean} + * @private + */ + _this.dirty = 0; + + /** + * Used to detect if we need to do a fast rect check using the id compare method + * @type {Number} + */ + _this.fastRectDirty = -1; + + /** + * Used to detect if we clear the graphics webGL data + * @type {Number} + */ + _this.clearDirty = 0; + + /** + * Used to detect if we we need to recalculate local bounds + * @type {Number} + */ + _this.boundsDirty = -1; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @member {boolean} + * @private + */ + _this.cachedSpriteDirty = false; + + _this._spriteRect = null; + _this._fastRect = false; + + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ + return _this; + } + + /** + * Creates a new Graphics object with the same values as this one. + * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) + * + * @return {PIXI.Graphics} A clone of the graphics object + */ + + + Graphics.prototype.clone = function clone() { + var clone = new Graphics(); + + clone.renderable = this.renderable; + clone.fillAlpha = this.fillAlpha; + clone.lineWidth = this.lineWidth; + clone.lineColor = this.lineColor; + clone.tint = this.tint; + clone.blendMode = this.blendMode; + clone.isMask = this.isMask; + clone.boundsPadding = this.boundsPadding; + clone.dirty = 0; + clone.cachedSpriteDirty = this.cachedSpriteDirty; + + // copy graphics data + for (var i = 0; i < this.graphicsData.length; ++i) { + clone.graphicsData.push(this.graphicsData[i].clone()); + } + + clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; + + clone.updateLocalBounds(); + + return clone; + }; + + /** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() + * method or the drawCircle() method. + * + * @param {number} [lineWidth=0] - width of the line to draw, will update the objects stored style + * @param {number} [color=0] - color of the line to draw, will update the objects stored style + * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineStyle = function lineStyle() { + var lineWidth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var alpha = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + + this.lineWidth = lineWidth; + this.lineColor = color; + this.lineAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length) { + // halfway through a line? start a new one! + var shape = new _math.Polygon(this.currentPath.shape.points.slice(-2)); + + shape.closed = false; + + this.drawShape(shape); + } else { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + }; + + /** + * Moves the current drawing position to x, y. + * + * @param {number} x - the X coordinate to move to + * @param {number} y - the Y coordinate to move to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.moveTo = function moveTo(x, y) { + var shape = new _math.Polygon([x, y]); + + shape.closed = false; + this.drawShape(shape); + + return this; + }; + + /** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @param {number} x - the X coordinate to draw to + * @param {number} y - the Y coordinate to draw to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineTo = function lineTo(x, y) { + this.currentPath.shape.points.push(x, y); + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.quadraticCurveTo = function quadraticCurveTo(cpX, cpY, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var n = 20; + var points = this.currentPath.shape.points; + var xa = 0; + var ya = 0; + + if (points.length === 0) { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + for (var i = 1; i <= n; ++i) { + var j = i / n; + + xa = fromX + (cpX - fromX) * j; + ya = fromY + (cpY - fromY) * j; + + points.push(xa + (cpX + (toX - cpX) * j - xa) * j, ya + (cpY + (toY - cpY) * j - ya) * j); + } + + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a bezier curve and then draws it. + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.bezierCurveTo = function bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + points.length -= 2; + + (0, _bezierCurveTo3.default)(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, points); + + this.dirty++; + + return this; + }; + + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @param {number} x1 - The x-coordinate of the beginning of the arc + * @param {number} y1 - The y-coordinate of the beginning of the arc + * @param {number} x2 - The x-coordinate of the end of the arc + * @param {number} y2 - The y-coordinate of the end of the arc + * @param {number} radius - The radius of the arc + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arcTo = function arcTo(x1, y1, x2, y2, radius) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points.push(x1, y1); + } + } else { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + } else { + var dd = a1 * a1 + b1 * b1; + var cc = a2 * a2 + b2 * b2; + var tt = a1 * a2 + b1 * b2; + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = k1 * b2 + k2 * b1; + var cy = k1 * a2 + k2 * a1; + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty++; + + return this; + }; + + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @param {number} cx - The x-coordinate of the center of the circle + * @param {number} cy - The y-coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param {number} endAngle - The ending angle, in radians + * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arc = function arc(cx, cy, radius, startAngle, endAngle) { + var anticlockwise = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; + + if (startAngle === endAngle) { + return this; + } + + if (!anticlockwise && endAngle <= startAngle) { + endAngle += Math.PI * 2; + } else if (anticlockwise && startAngle <= endAngle) { + startAngle += Math.PI * 2; + } + + var sweep = endAngle - startAngle; + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * 40; + + if (sweep === 0) { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. + var points = this.currentPath ? this.currentPath.shape.points : null; + + if (points) { + if (points[points.length - 2] !== startX || points[points.length - 1] !== startY) { + points.push(startX, startY); + } + } else { + this.moveTo(startX, startY); + points = this.currentPath.shape.points; + } + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = segMinus % 1 / segMinus; + + for (var i = 0; i <= segMinus; ++i) { + var real = i + remainder * i; + + var angle = theta + startAngle + theta2 * real; + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push((cTheta * c + sTheta * s) * radius + cx, (cTheta * -s + sTheta * c) * radius + cy); + } + + this.dirty++; + + return this; + }; + + /** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @param {number} [color=0] - the color of the fill + * @param {number} [alpha=1] - the alpha of the fill + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.beginFill = function beginFill() { + var color = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var alpha = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.filling = true; + this.fillColor = color; + this.fillAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length <= 2) { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + }; + + /** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.endFill = function endFill() { + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRect = function drawRect(x, y, width, height) { + this.drawShape(new _math.Rectangle(x, y, width, height)); + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @param {number} radius - Radius of the rectangle corners + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRoundedRect = function drawRoundedRect(x, y, width, height, radius) { + this.drawShape(new _math.RoundedRectangle(x, y, width, height, radius)); + + return this; + }; + + /** + * Draws a circle. + * + * @param {number} x - The X coordinate of the center of the circle + * @param {number} y - The Y coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawCircle = function drawCircle(x, y, radius) { + this.drawShape(new _math.Circle(x, y, radius)); + + return this; + }; + + /** + * Draws an ellipse. + * + * @param {number} x - The X coordinate of the center of the ellipse + * @param {number} y - The Y coordinate of the center of the ellipse + * @param {number} width - The half width of the ellipse + * @param {number} height - The half height of the ellipse + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawEllipse = function drawEllipse(x, y, width, height) { + this.drawShape(new _math.Ellipse(x, y, width, height)); + + return this; + }; + + /** + * Draws a polygon using the given path. + * + * @param {number[]|PIXI.Point[]} path - The path data used to construct the polygon. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawPolygon = function drawPolygon(path) { + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + var closed = true; + + if (points instanceof _math.Polygon) { + closed = points.closed; + points = points.points; + } + + if (!Array.isArray(points)) { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) { + points[i] = arguments[i]; // eslint-disable-line prefer-rest-params + } + } + + var shape = new _math.Polygon(points); + + shape.closed = closed; + + this.drawShape(shape); + + return this; + }; + + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.clear = function clear() { + if (this.lineWidth || this.filling || this.graphicsData.length > 0) { + this.lineWidth = 0; + this.filling = false; + + this.boundsDirty = -1; + this.dirty++; + this.clearDirty++; + this.graphicsData.length = 0; + } + + this.currentPath = null; + this._spriteRect = null; + + return this; + }; + + /** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. + * + * @returns {boolean} True if only 1 rect. + */ + + + Graphics.prototype.isFastRect = function isFastRect() { + return this.graphicsData.length === 1 && this.graphicsData[0].shape.type === _const.SHAPES.RECT && !this.graphicsData[0].lineWidth; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderWebGL = function _renderWebGL(renderer) { + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.dirty !== this.fastRectDirty) { + this.fastRectDirty = this.dirty; + this._fastRect = this.isFastRect(); + } + + // TODO this check can be moved to dirty? + if (this._fastRect) { + this._renderSpriteRect(renderer); + } else { + renderer.setObjectRenderer(renderer.plugins.graphics); + renderer.plugins.graphics.render(this); + } + }; + + /** + * Renders a sprite rectangle. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderSpriteRect = function _renderSpriteRect(renderer) { + var rect = this.graphicsData[0].shape; + + if (!this._spriteRect) { + this._spriteRect = new _Sprite2.default(new _Texture2.default(_Texture2.default.WHITE)); + } + + var sprite = this._spriteRect; + + if (this.tint === 0xffffff) { + sprite.tint = this.graphicsData[0].fillColor; + } else { + var t1 = tempColor1; + var t2 = tempColor2; + + (0, _utils.hex2rgb)(this.graphicsData[0].fillColor, t1); + (0, _utils.hex2rgb)(this.tint, t2); + + t1[0] *= t2[0]; + t1[1] *= t2[1]; + t1[2] *= t2[2]; + + sprite.tint = (0, _utils.rgb2hex)(t1); + } + sprite.alpha = this.graphicsData[0].fillAlpha; + sprite.worldAlpha = this.worldAlpha * sprite.alpha; + sprite.blendMode = this.blendMode; + + sprite._texture._frame.width = rect.width; + sprite._texture._frame.height = rect.height; + + sprite.transform.worldTransform = this.transform.worldTransform; + + sprite.anchor.set(-rect.x / rect.width, -rect.y / rect.height); + sprite._onAnchorUpdate(); + + sprite._renderWebGL(renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.isMask === true) { + return; + } + + renderer.plugins.graphics.render(this); + }; + + /** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @private + */ + + + Graphics.prototype._calculateBounds = function _calculateBounds() { + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.updateLocalBounds(); + + this.cachedSpriteDirty = true; + } + + var lb = this._localBounds; + + this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); + }; + + /** + * Tests if a point is inside this graphics object + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Graphics.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + + if (!data.fill) { + continue; + } + + // only deal with fills.. + if (data.shape) { + if (data.shape.contains(tempPoint.x, tempPoint.y)) { + if (data.holes) { + for (var _i = 0; _i < data.holes.length; _i++) { + var hole = data.holes[_i]; + + if (hole.contains(tempPoint.x, tempPoint.y)) { + return false; + } + } + } + + return true; + } + } + } + + return false; + }; + + /** + * Update the bounds of the object + * + */ + + + Graphics.prototype.updateLocalBounds = function updateLocalBounds() { + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) { + var shape = 0; + var x = 0; + var y = 0; + var w = 0; + var h = 0; + + for (var i = 0; i < this.graphicsData.length; i++) { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + + shape = data.shape; + + if (type === _const.SHAPES.RECT || type === _const.SHAPES.RREC) { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.CIRC) { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.ELIP) { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else { + // POLY + var points = shape.points; + var x2 = 0; + var y2 = 0; + var dx = 0; + var dy = 0; + var rw = 0; + var rh = 0; + var cx = 0; + var cy = 0; + + for (var j = 0; j + 2 < points.length; j += 2) { + x = points[j]; + y = points[j + 1]; + x2 = points[j + 2]; + y2 = points[j + 3]; + dx = Math.abs(x2 - x); + dy = Math.abs(y2 - y); + h = lineWidth; + w = Math.sqrt(dx * dx + dy * dy); + + if (w < 1e-9) { + continue; + } + + rw = (h / w * dy + dx) / 2; + rh = (h / w * dx + dy) / 2; + cx = (x2 + x) / 2; + cy = (y2 + y) / 2; + + minX = cx - rw < minX ? cx - rw : minX; + maxX = cx + rw > maxX ? cx + rw : maxX; + + minY = cy - rh < minY ? cy - rh : minY; + maxY = cy + rh > maxY ? cy + rh : maxY; + } + } + } + } else { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.minX = minX - padding; + this._localBounds.maxX = maxX + padding; + + this._localBounds.minY = minY - padding; + this._localBounds.maxY = maxY + padding; + }; + + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @return {PIXI.GraphicsData} The generated GraphicsData object. + */ + + + Graphics.prototype.drawShape = function drawShape(shape) { + if (this.currentPath) { + // check current path! + if (this.currentPath.shape.points.length <= 2) { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + var data = new _GraphicsData2.default(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, this.nativeLines, shape); + + this.graphicsData.push(data); + + if (data.type === _const.SHAPES.POLY) { + data.shape.closed = data.shape.closed || this.filling; + this.currentPath = data; + } + + this.dirty++; + + return data; + }; + + /** + * Generates a canvas texture. + * + * @param {number} scaleMode - The scale mode of the texture. + * @param {number} resolution - The resolution of the texture. + * @return {PIXI.Texture} The new texture. + */ + + + Graphics.prototype.generateCanvasTexture = function generateCanvasTexture(scaleMode) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + var bounds = this.getLocalBounds(); + + var canvasBuffer = _RenderTexture2.default.create(bounds.width, bounds.height, scaleMode, resolution); + + if (!canvasRenderer) { + canvasRenderer = new _CanvasRenderer2.default(); + } + + this.transform.updateLocalTransform(); + this.transform.localTransform.copy(tempMatrix); + + tempMatrix.invert(); + + tempMatrix.tx -= bounds.x; + tempMatrix.ty -= bounds.y; + + canvasRenderer.render(this, canvasBuffer, true, tempMatrix); + + var texture = _Texture2.default.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas, scaleMode, 'graphics'); + + texture.baseTexture.resolution = resolution; + texture.baseTexture.update(); + + return texture; + }; + + /** + * Closes the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.closePath = function closePath() { + // ok so close path assumes next one is a hole! + var currentPath = this.currentPath; + + if (currentPath && currentPath.shape) { + currentPath.shape.close(); + } + + return this; + }; + + /** + * Adds a hole in the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.addHole = function addHole() { + // this is a hole! + var hole = this.graphicsData.pop(); + + this.currentPath = this.graphicsData[this.graphicsData.length - 1]; + + this.currentPath.addHole(hole.shape); + this.currentPath = null; + + return this; + }; + + /** + * Destroys the Graphics object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Graphics.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._webgl) { + for (var j = 0; j < this._webgl[id].data.length; ++j) { + this._webgl[id].data[j].destroy(); + } + } + + if (this._spriteRect) { + this._spriteRect.destroy(); + } + + this.graphicsData = null; + + this.currentPath = null; + this._webgl = null; + this._localBounds = null; + }; + + return Graphics; +}(_Container3.default); + +exports.default = Graphics; + + +Graphics._SPRITE_TEXTURE = null; + +},{"../const":45,"../display/Bounds":46,"../display/Container":47,"../math":69,"../renderers/canvas/CanvasRenderer":76,"../sprites/Sprite":101,"../textures/RenderTexture":112,"../textures/Texture":114,"../utils":123,"./GraphicsData":53,"./utils/bezierCurveTo":55}],53:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + */ +var GraphicsData = function () { + /** + * + * @param {number} lineWidth - the width of the line to draw + * @param {number} lineColor - the color of the line to draw + * @param {number} lineAlpha - the alpha of the line to draw + * @param {number} fillColor - the color of the fill + * @param {number} fillAlpha - the alpha of the fill + * @param {boolean} fill - whether or not the shape is filled with a colour + * @param {boolean} nativeLines - the method for drawing lines + * @param {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} shape - The shape object to draw. + */ + function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, nativeLines, shape) { + _classCallCheck(this, GraphicsData); + + /** + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + /** + * @member {boolean} if true the liens will be draw using LINES instead of TRIANGLE_STRIP + */ + this.nativeLines = nativeLines; + + /** + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /** + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /** + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /** + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /** + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /** + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /** + * @member {boolean} whether or not the shape is filled with a colour + */ + this.fill = fill; + + this.holes = []; + + /** + * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} The shape object to draw. + */ + this.shape = shape; + + /** + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + } + + /** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {PIXI.GraphicsData} Cloned GraphicsData object + */ + + + GraphicsData.prototype.clone = function clone() { + return new GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.fill, this.nativeLines, this.shape); + }; + + /** + * Adds a hole to the shape. + * + * @param {PIXI.Rectangle|PIXI.Circle} shape - The shape of the hole. + */ + + + GraphicsData.prototype.addHole = function addHole(shape) { + this.holes.push(shape); + }; + + /** + * Destroys the Graphics data. + */ + + + GraphicsData.prototype.destroy = function destroy() { + this.shape = null; + this.holes = null; + }; + + return GraphicsData; +}(); + +exports.default = GraphicsData; + +},{}],54:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they + * now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasGraphicsRenderer: + * https://github.com/libgdx/libgdx/blob/1.0.0/gdx/src/com/badlogic/gdx/graphics/glutils/ShapeRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching graphics objects. + * + * @class + * @private + * @memberof PIXI + */ +var CanvasGraphicsRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The current PIXI renderer. + */ + function CanvasGraphicsRenderer(renderer) { + _classCallCheck(this, CanvasGraphicsRenderer); + + this.renderer = renderer; + } + + /** + * Renders a Graphics object to a canvas. + * + * @param {PIXI.Graphics} graphics - the actual graphics object to render + */ + + + CanvasGraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var context = renderer.context; + var worldAlpha = graphics.worldAlpha; + var transform = graphics.transform.worldTransform; + var resolution = renderer.resolution; + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) { + this.dirty = true; + } + + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + if (graphics.dirty) { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + renderer.setBlendMode(graphics.blendMode); + + for (var i = 0; i < graphics.graphicsData.length; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === _const.SHAPES.POLY) { + context.beginPath(); + + this.renderPolygon(shape.points, shape.closed, context); + + for (var j = 0; j < data.holes.length; j++) { + this.renderPolygon(data.holes[j].points, true, context); + } + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RECT) { + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + context.beginPath(); + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + }; + + /** + * Updates the tint of a graphics object + * + * @private + * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated + */ + + + CanvasGraphicsRenderer.prototype.updateGraphicsTint = function updateGraphicsTint(graphics) { + graphics._prevTint = graphics.tint; + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF) / 255; + + for (var i = 0; i < graphics.graphicsData.length; ++i) { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + // super inline cos im an optimization NAZI :) + data._fillTint = ((fillColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (fillColor & 0xFF) / 255 * tintB * 255; + + data._lineTint = ((lineColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (lineColor & 0xFF) / 255 * tintB * 255; + } + }; + + /** + * Renders a polygon. + * + * @param {PIXI.Point[]} points - The points to render + * @param {boolean} close - Should the polygon be closed + * @param {CanvasRenderingContext2D} context - The rendering context to use + */ + + + CanvasGraphicsRenderer.prototype.renderPolygon = function renderPolygon(points, close, context) { + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; ++j) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (close) { + context.closePath(); + } + }; + + /** + * destroy graphics object + * + */ + + + CanvasGraphicsRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasGraphicsRenderer; +}(); + +exports.default = CanvasGraphicsRenderer; + + +_CanvasRenderer2.default.registerPlugin('graphics', CanvasGraphicsRenderer); + +},{"../../const":45,"../../renderers/canvas/CanvasRenderer":76}],55:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = bezierCurveTo; +/** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [path=[]] - Path array to push points into + * @return {number[]} Array of points of the curve + */ +function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var path = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : []; + + var n = 20; + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + + path.push(fromX, fromY); + + for (var i = 1, j = 0; i <= n; ++i) { + j = i / n; + + dt = 1 - j; + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + path.push(dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + return path; +} + +},{}],56:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _WebGLGraphicsData = require('./WebGLGraphicsData'); + +var _WebGLGraphicsData2 = _interopRequireDefault(_WebGLGraphicsData); + +var _PrimitiveShader = require('./shaders/PrimitiveShader'); + +var _PrimitiveShader2 = _interopRequireDefault(_PrimitiveShader); + +var _buildPoly = require('./utils/buildPoly'); + +var _buildPoly2 = _interopRequireDefault(_buildPoly); + +var _buildRectangle = require('./utils/buildRectangle'); + +var _buildRectangle2 = _interopRequireDefault(_buildRectangle); + +var _buildRoundedRectangle = require('./utils/buildRoundedRectangle'); + +var _buildRoundedRectangle2 = _interopRequireDefault(_buildRoundedRectangle); + +var _buildCircle = require('./utils/buildCircle'); + +var _buildCircle2 = _interopRequireDefault(_buildCircle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Renders the graphics object. + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var GraphicsRenderer = function (_ObjectRenderer) { + _inherits(GraphicsRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this object renderer works for. + */ + function GraphicsRenderer(renderer) { + _classCallCheck(this, GraphicsRenderer); + + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.graphicsDataPool = []; + + _this.primitiveShader = null; + + _this.gl = renderer.gl; + + // easy access! + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * Called when there is a WebGL context change + * + * @private + * + */ + + + GraphicsRenderer.prototype.onContextChange = function onContextChange() { + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.primitiveShader = new _PrimitiveShader2.default(this.gl); + }; + + /** + * Destroys this renderer. + * + */ + + + GraphicsRenderer.prototype.destroy = function destroy() { + _ObjectRenderer3.default.prototype.destroy.call(this); + + for (var i = 0; i < this.graphicsDataPool.length; ++i) { + this.graphicsDataPool[i].destroy(); + } + + this.graphicsDataPool = null; + }; + + /** + * Renders a graphics object. + * + * @param {PIXI.Graphics} graphics - The graphics object to render. + */ + + + GraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var gl = renderer.gl; + + var webGLData = void 0; + var webGL = graphics._webGL[this.CONTEXT_UID]; + + if (!webGL || graphics.dirty !== webGL.dirty) { + this.updateGraphics(graphics); + + webGL = graphics._webGL[this.CONTEXT_UID]; + } + + // This could be speeded up for sure! + var shader = this.primitiveShader; + + renderer.bindShader(shader); + renderer.state.setBlendMode(graphics.blendMode); + + for (var i = 0, n = webGL.data.length; i < n; i++) { + webGLData = webGL.data[i]; + var shaderTemp = webGLData.shader; + + renderer.bindShader(shaderTemp); + shaderTemp.uniforms.translationMatrix = graphics.transform.worldTransform.toArray(true); + shaderTemp.uniforms.tint = (0, _utils.hex2rgb)(graphics.tint); + shaderTemp.uniforms.alpha = graphics.worldAlpha; + + renderer.bindVao(webGLData.vao); + + if (webGLData.nativeLines) { + gl.drawArrays(gl.LINES, 0, webGLData.points.length / 6); + } else { + webGLData.vao.draw(gl.TRIANGLE_STRIP, webGLData.indices.length); + } + } + }; + + /** + * Updates the graphics object + * + * @private + * @param {PIXI.Graphics} graphics - The graphics object to update + */ + + + GraphicsRenderer.prototype.updateGraphics = function updateGraphics(graphics) { + var gl = this.renderer.gl; + + // get the contexts graphics object + var webGL = graphics._webGL[this.CONTEXT_UID]; + + // if the graphics object does not exist in the webGL context time to create it! + if (!webGL) { + webGL = graphics._webGL[this.CONTEXT_UID] = { lastIndex: 0, data: [], gl: gl, clearDirty: -1, dirty: -1 }; + } + + // flag the graphics as not dirty as we are about to update it... + webGL.dirty = graphics.dirty; + + // if the user cleared the graphics object we will need to clear every object + if (graphics.clearDirty !== webGL.clearDirty) { + webGL.clearDirty = graphics.clearDirty; + + // loop through and return all the webGLDatas to the object pool so than can be reused later on + for (var i = 0; i < webGL.data.length; i++) { + this.graphicsDataPool.push(webGL.data[i]); + } + + // clear the array and reset the index.. + webGL.data.length = 0; + webGL.lastIndex = 0; + } + + var webGLData = void 0; + var webGLDataNativeLines = void 0; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (var _i = webGL.lastIndex; _i < graphics.graphicsData.length; _i++) { + var data = graphics.graphicsData[_i]; + + // TODO - this can be simplified + webGLData = this.getWebGLData(webGL, 0); + + if (data.nativeLines && data.lineWidth) { + webGLDataNativeLines = this.getWebGLData(webGL, 0, true); + webGL.lastIndex++; + } + + if (data.type === _const.SHAPES.POLY) { + (0, _buildPoly2.default)(data, webGLData, webGLDataNativeLines); + } + if (data.type === _const.SHAPES.RECT) { + (0, _buildRectangle2.default)(data, webGLData, webGLDataNativeLines); + } else if (data.type === _const.SHAPES.CIRC || data.type === _const.SHAPES.ELIP) { + (0, _buildCircle2.default)(data, webGLData, webGLDataNativeLines); + } else if (data.type === _const.SHAPES.RREC) { + (0, _buildRoundedRectangle2.default)(data, webGLData, webGLDataNativeLines); + } + + webGL.lastIndex++; + } + + this.renderer.bindVao(null); + + // upload all the dirty data... + for (var _i2 = 0; _i2 < webGL.data.length; _i2++) { + webGLData = webGL.data[_i2]; + + if (webGLData.dirty) { + webGLData.upload(); + } + } + }; + + /** + * + * @private + * @param {WebGLRenderingContext} gl - the current WebGL drawing context + * @param {number} type - TODO @Alvin + * @param {number} nativeLines - indicate whether the webGLData use for nativeLines. + * @return {*} TODO + */ + + + GraphicsRenderer.prototype.getWebGLData = function getWebGLData(gl, type, nativeLines) { + var webGLData = gl.data[gl.data.length - 1]; + + if (!webGLData || webGLData.nativeLines !== nativeLines || webGLData.points.length > 320000) { + webGLData = this.graphicsDataPool.pop() || new _WebGLGraphicsData2.default(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData.nativeLines = nativeLines; + webGLData.reset(type); + gl.data.push(webGLData); + } + + webGLData.dirty = true; + + return webGLData; + }; + + return GraphicsRenderer; +}(_ObjectRenderer3.default); + +exports.default = GraphicsRenderer; + + +_WebGLRenderer2.default.registerPlugin('graphics', GraphicsRenderer); + +},{"../../const":45,"../../renderers/webgl/WebGLRenderer":83,"../../renderers/webgl/utils/ObjectRenderer":93,"../../utils":123,"./WebGLGraphicsData":57,"./shaders/PrimitiveShader":58,"./utils/buildCircle":59,"./utils/buildPoly":61,"./utils/buildRectangle":62,"./utils/buildRoundedRectangle":63}],57:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * An object containing WebGL specific properties to be used by the WebGL renderer + * + * @class + * @private + * @memberof PIXI + */ +var WebGLGraphicsData = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {PIXI.Shader} shader - The shader + * @param {object} attribsState - The state for the VAO + */ + function WebGLGraphicsData(gl, shader, attribsState) { + _classCallCheck(this, WebGLGraphicsData); + + /** + * The current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // TODO does this need to be split before uploading?? + /** + * An array of color components (r,g,b) + * @member {number[]} + */ + this.color = [0, 0, 0]; // color split! + + /** + * An array of points to draw + * @member {PIXI.Point[]} + */ + this.points = []; + + /** + * The indices of the vertices + * @member {number[]} + */ + this.indices = []; + /** + * The main buffer + * @member {WebGLBuffer} + */ + this.buffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl); + + /** + * The index buffer + * @member {WebGLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl); + + /** + * Whether this graphics is dirty or not + * @member {boolean} + */ + this.dirty = true; + + /** + * Whether this graphics is nativeLines or not + * @member {boolean} + */ + this.nativeLines = false; + + this.glPoints = null; + this.glIndices = null; + + /** + * + * @member {PIXI.Shader} + */ + this.shader = shader; + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, attribsState).addIndex(this.indexBuffer).addAttribute(this.buffer, shader.attributes.aVertexPosition, gl.FLOAT, false, 4 * 6, 0).addAttribute(this.buffer, shader.attributes.aColor, gl.FLOAT, false, 4 * 6, 2 * 4); + } + + /** + * Resets the vertices and the indices + */ + + + WebGLGraphicsData.prototype.reset = function reset() { + this.points.length = 0; + this.indices.length = 0; + }; + + /** + * Binds the buffers and uploads the data + */ + + + WebGLGraphicsData.prototype.upload = function upload() { + this.glPoints = new Float32Array(this.points); + this.buffer.upload(this.glPoints); + + this.glIndices = new Uint16Array(this.indices); + this.indexBuffer.upload(this.glIndices); + + this.dirty = false; + }; + + /** + * Empties all the data + */ + + + WebGLGraphicsData.prototype.destroy = function destroy() { + this.color = null; + this.points = null; + this.indices = null; + + this.vao.destroy(); + this.buffer.destroy(); + this.indexBuffer.destroy(); + + this.gl = null; + + this.buffer = null; + this.indexBuffer = null; + + this.glPoints = null; + this.glIndices = null; + }; + + return WebGLGraphicsData; +}(); + +exports.default = WebGLGraphicsData; + +},{"pixi-gl-core":12}],58:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../../Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. + * + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ +var PrimitiveShader = function (_Shader) { + _inherits(PrimitiveShader, _Shader); + + /** + * @param {WebGLRenderingContext} gl - The webgl shader manager this shader works for. + */ + function PrimitiveShader(gl) { + _classCallCheck(this, PrimitiveShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec4 aColor;', 'uniform mat3 translationMatrix;', 'uniform mat3 projectionMatrix;', 'uniform float alpha;', 'uniform vec3 tint;', 'varying vec4 vColor;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vColor = aColor * vec4(tint * alpha, alpha);', '}'].join('\n'), + // fragment shader + ['varying vec4 vColor;', 'void main(void){', ' gl_FragColor = vColor;', '}'].join('\n'))); + } + + return PrimitiveShader; +}(_Shader3.default); + +exports.default = PrimitiveShader; + +},{"../../../Shader":43}],59:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildCircle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _const = require('../../../const'); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildCircle(graphicsData, webGLData, webGLDataNativeLines) { + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width = void 0; + var height = void 0; + + // TODO - bit hacky?? + if (graphicsData.type === _const.SHAPES.CIRC) { + width = circleData.radius; + height = circleData.radius; + } else { + width = circleData.width; + height = circleData.height; + } + + if (width === 0 || height === 0) { + return; + } + + var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); + + var seg = Math.PI * 2 / totalSegs; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + indices.push(vecPos); + + for (var i = 0; i < totalSegs + 1; i++) { + verts.push(x, y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos - 1); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (var _i = 0; _i < totalSegs + 1; _i++) { + graphicsData.points.push(x + Math.sin(seg * _i) * width, y + Math.cos(seg * _i) * height); + } + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +},{"../../../const":45,"../../../utils":123,"./buildLine":60}],60:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function (graphicsData, webGLData, webGLDataNativeLines) { + if (graphicsData.nativeLines) { + buildNativeLine(graphicsData, webGLDataNativeLines); + } else { + buildLine(graphicsData, webGLData); + } +}; + +var _math = require('../../../math'); + +var _utils = require('../../../utils'); + +/** + * Builds a line to draw using the poligon method. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildLine(graphicsData, webGLData) { + // TODO OPTIMISE! + var points = graphicsData.points; + + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + + // get first and last point.. figure out the middle! + var firstPoint = new _math.Point(points[0], points[1]); + var lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + // if the first point is the last point - gonna have issues :) + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var p1x = points[0]; + var p1y = points[1]; + var p2x = points[2]; + var p2y = points[3]; + var p3x = 0; + var p3y = 0; + + var perpx = -(p1y - p2y); + var perpy = p1x - p2x; + var perp2x = 0; + var perp2y = 0; + var perp3x = 0; + var perp3y = 0; + + var dist = Math.sqrt(perpx * perpx + perpy * perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx, p1y - perpy, r, g, b, alpha); + + verts.push(p1x + perpx, p1y + perpy, r, g, b, alpha); + + for (var i = 1; i < length - 1; ++i) { + p1x = points[(i - 1) * 2]; + p1y = points[(i - 1) * 2 + 1]; + + p2x = points[i * 2]; + p2y = points[i * 2 + 1]; + + p3x = points[(i + 1) * 2]; + p3y = points[(i + 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + var a1 = -perpy + p1y - (-perpy + p2y); + var b1 = -perpx + p2x - (-perpx + p1x); + var c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + var a2 = -perp2y + p3y - (-perp2y + p2y); + var b2 = -perp2x + p2x - (-perp2x + p3x); + var c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + var denom = a1 * b2 - a2 * b1; + + if (Math.abs(denom) < 0.1) { + denom += 10.1; + verts.push(p2x - perpx, p2y - perpy, r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy, r, g, b, alpha); + + continue; + } + + var px = (b1 * c2 - b2 * c1) / denom; + var py = (a2 * c1 - a1 * c2) / denom; + var pdist = (px - p2x) * (px - p2x) + (py - p2y) * (py - p2y); + + if (pdist > 196 * width * width) { + perp3x = perpx - perp2x; + perp3y = perpy - perp2y; + + dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y); + perp3x /= dist; + perp3y /= dist; + perp3x *= width; + perp3y *= width; + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x + perp3x, p2y + perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + indexCount++; + } else { + verts.push(px, py); + verts.push(r, g, b, alpha); + + verts.push(p2x - (px - p2x), p2y - (py - p2y)); + verts.push(r, g, b, alpha); + } + } + + p1x = points[(length - 2) * 2]; + p1y = points[(length - 2) * 2 + 1]; + + p2x = points[(length - 1) * 2]; + p2y = points[(length - 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + verts.push(p2x - perpx, p2y - perpy); + verts.push(r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy); + verts.push(r, g, b, alpha); + + indices.push(indexStart); + + for (var _i = 0; _i < indexCount; ++_i) { + indices.push(indexStart++); + } + + indices.push(indexStart - 1); +} + +/** + * Builds a line to draw using the gl.drawArrays(gl.LINES) method + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ + + +/** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildNativeLine(graphicsData, webGLData) { + var i = 0; + var points = graphicsData.points; + + if (points.length === 0) return; + + var verts = webGLData.points; + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + for (i = 1; i < length; i++) { + var p1x = points[(i - 1) * 2]; + var p1y = points[(i - 1) * 2 + 1]; + + var p2x = points[i * 2]; + var p2y = points[i * 2 + 1]; + + verts.push(p1x, p1y); + verts.push(r, g, b, alpha); + + verts.push(p2x, p2y); + verts.push(r, g, b, alpha); + } +} + +},{"../../../math":69,"../../../utils":123}],61:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildPoly; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildPoly(graphicsData, webGLData, webGLDataNativeLines) { + graphicsData.points = graphicsData.shape.points.slice(); + + var points = graphicsData.points; + + if (graphicsData.fill && points.length >= 6) { + var holeArray = []; + // Process holes.. + var holes = graphicsData.holes; + + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + + holeArray.push(points.length / 2); + + points = points.concat(hole.points); + } + + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = (0, _earcut2.default)(points, holeArray, 2); + + if (!triangles) { + return; + } + + var vertPos = verts.length / 6; + + for (var _i = 0; _i < triangles.length; _i += 3) { + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i + 1] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + } + + for (var _i2 = 0; _i2 < length; _i2++) { + verts.push(points[_i2 * 2], points[_i2 * 2 + 1], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth > 0) { + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + } +} + +},{"../../../utils":123,"./buildLine":60,"earcut":2}],62:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRectangle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildRectangle(graphicsData, webGLData, webGLDataNativeLines) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vertPos = verts.length / 6; + + // start + verts.push(x, y); + verts.push(r, g, b, alpha); + + verts.push(x + width, y); + verts.push(r, g, b, alpha); + + verts.push(x, y + height); + verts.push(r, g, b, alpha); + + verts.push(x + width, y + height); + verts.push(r, g, b, alpha); + + // insert 2 dead triangles.. + indices.push(vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y]; + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +},{"../../../utils":123,"./buildLine":60}],63:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRoundedRectangle; + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildRoundedRectangle(graphicsData, webGLData, webGLDataNativeLines) { + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + + recPoints.push(x, y + radius); + quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height, recPoints); + quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius, recPoints); + quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y, recPoints); + quadraticBezierCurve(x + radius, y, x, y, x, y + radius + 0.0000000001, recPoints); + + // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. + // TODO - fix this properly, this is not very elegant.. but it works for now. + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + var triangles = (0, _earcut2.default)(recPoints, null, 2); + + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + + for (var _i = 0, _j = recPoints.length; _i < _j; _i++) { + verts.push(recPoints[_i], recPoints[++_i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +/** + * Calculate a single point for a quadratic bezier curve. + * Utility function used by quadraticBezierCurve. + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} n1 - first number + * @param {number} n2 - second number + * @param {number} perc - percentage + * @return {number} the result + * + */ +function getPt(n1, n2, perc) { + var diff = n2 - n1; + + return n1 + diff * perc; +} + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @return {number[]} an array of points + */ +function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY) { + var out = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : []; + + var n = 20; + var points = out; + + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + + points.push(x, y); + } + + return points; +} + +},{"../../../utils":123,"./buildLine":60,"earcut":2}],64:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = exports.Application = exports.Filter = exports.SpriteMaskFilter = exports.Quad = exports.RenderTarget = exports.ObjectRenderer = exports.WebGLManager = exports.Shader = exports.CanvasRenderTarget = exports.TextureUvs = exports.VideoBaseTexture = exports.BaseRenderTexture = exports.RenderTexture = exports.BaseTexture = exports.Texture = exports.Spritesheet = exports.CanvasGraphicsRenderer = exports.GraphicsRenderer = exports.GraphicsData = exports.Graphics = exports.TextMetrics = exports.TextStyle = exports.Text = exports.SpriteRenderer = exports.CanvasTinter = exports.CanvasSpriteRenderer = exports.Sprite = exports.TransformBase = exports.TransformStatic = exports.Transform = exports.Container = exports.DisplayObject = exports.Bounds = exports.glCore = exports.WebGLRenderer = exports.CanvasRenderer = exports.ticker = exports.utils = exports.settings = undefined; + +var _const = require('./const'); + +Object.keys(_const).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _const[key]; + } + }); +}); + +var _math = require('./math'); + +Object.keys(_math).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _math[key]; + } + }); +}); + +var _pixiGlCore = require('pixi-gl-core'); + +Object.defineProperty(exports, 'glCore', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_pixiGlCore).default; + } +}); + +var _Bounds = require('./display/Bounds'); + +Object.defineProperty(exports, 'Bounds', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Bounds).default; + } +}); + +var _DisplayObject = require('./display/DisplayObject'); + +Object.defineProperty(exports, 'DisplayObject', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplayObject).default; + } +}); + +var _Container = require('./display/Container'); + +Object.defineProperty(exports, 'Container', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Container).default; + } +}); + +var _Transform = require('./display/Transform'); + +Object.defineProperty(exports, 'Transform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Transform).default; + } +}); + +var _TransformStatic = require('./display/TransformStatic'); + +Object.defineProperty(exports, 'TransformStatic', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformStatic).default; + } +}); + +var _TransformBase = require('./display/TransformBase'); + +Object.defineProperty(exports, 'TransformBase', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformBase).default; + } +}); + +var _Sprite = require('./sprites/Sprite'); + +Object.defineProperty(exports, 'Sprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Sprite).default; + } +}); + +var _CanvasSpriteRenderer = require('./sprites/canvas/CanvasSpriteRenderer'); + +Object.defineProperty(exports, 'CanvasSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasSpriteRenderer).default; + } +}); + +var _CanvasTinter = require('./sprites/canvas/CanvasTinter'); + +Object.defineProperty(exports, 'CanvasTinter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasTinter).default; + } +}); + +var _SpriteRenderer = require('./sprites/webgl/SpriteRenderer'); + +Object.defineProperty(exports, 'SpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteRenderer).default; + } +}); + +var _Text = require('./text/Text'); + +Object.defineProperty(exports, 'Text', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Text).default; + } +}); + +var _TextStyle = require('./text/TextStyle'); + +Object.defineProperty(exports, 'TextStyle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextStyle).default; + } +}); + +var _TextMetrics = require('./text/TextMetrics'); + +Object.defineProperty(exports, 'TextMetrics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextMetrics).default; + } +}); + +var _Graphics = require('./graphics/Graphics'); + +Object.defineProperty(exports, 'Graphics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Graphics).default; + } +}); + +var _GraphicsData = require('./graphics/GraphicsData'); + +Object.defineProperty(exports, 'GraphicsData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsData).default; + } +}); + +var _GraphicsRenderer = require('./graphics/webgl/GraphicsRenderer'); + +Object.defineProperty(exports, 'GraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsRenderer).default; + } +}); + +var _CanvasGraphicsRenderer = require('./graphics/canvas/CanvasGraphicsRenderer'); + +Object.defineProperty(exports, 'CanvasGraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasGraphicsRenderer).default; + } +}); + +var _Spritesheet = require('./textures/Spritesheet'); + +Object.defineProperty(exports, 'Spritesheet', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Spritesheet).default; + } +}); + +var _Texture = require('./textures/Texture'); + +Object.defineProperty(exports, 'Texture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Texture).default; + } +}); + +var _BaseTexture = require('./textures/BaseTexture'); + +Object.defineProperty(exports, 'BaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseTexture).default; + } +}); + +var _RenderTexture = require('./textures/RenderTexture'); + +Object.defineProperty(exports, 'RenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTexture).default; + } +}); + +var _BaseRenderTexture = require('./textures/BaseRenderTexture'); + +Object.defineProperty(exports, 'BaseRenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseRenderTexture).default; + } +}); + +var _VideoBaseTexture = require('./textures/VideoBaseTexture'); + +Object.defineProperty(exports, 'VideoBaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VideoBaseTexture).default; + } +}); + +var _TextureUvs = require('./textures/TextureUvs'); + +Object.defineProperty(exports, 'TextureUvs', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureUvs).default; + } +}); + +var _CanvasRenderTarget = require('./renderers/canvas/utils/CanvasRenderTarget'); + +Object.defineProperty(exports, 'CanvasRenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasRenderTarget).default; + } +}); + +var _Shader = require('./Shader'); + +Object.defineProperty(exports, 'Shader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Shader).default; + } +}); + +var _WebGLManager = require('./renderers/webgl/managers/WebGLManager'); + +Object.defineProperty(exports, 'WebGLManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLManager).default; + } +}); + +var _ObjectRenderer = require('./renderers/webgl/utils/ObjectRenderer'); + +Object.defineProperty(exports, 'ObjectRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObjectRenderer).default; + } +}); + +var _RenderTarget = require('./renderers/webgl/utils/RenderTarget'); + +Object.defineProperty(exports, 'RenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTarget).default; + } +}); + +var _Quad = require('./renderers/webgl/utils/Quad'); + +Object.defineProperty(exports, 'Quad', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Quad).default; + } +}); + +var _SpriteMaskFilter = require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter'); + +Object.defineProperty(exports, 'SpriteMaskFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteMaskFilter).default; + } +}); + +var _Filter = require('./renderers/webgl/filters/Filter'); + +Object.defineProperty(exports, 'Filter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Filter).default; + } +}); + +var _Application = require('./Application'); + +Object.defineProperty(exports, 'Application', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Application).default; + } +}); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +Object.defineProperty(exports, 'autoDetectRenderer', { + enumerable: true, + get: function get() { + return _autoDetectRenderer.autoDetectRenderer; + } +}); + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _ticker = require('./ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.settings = _settings2.default; +exports.utils = utils; +exports.ticker = ticker; +exports.CanvasRenderer = _CanvasRenderer2.default; +exports.WebGLRenderer = _WebGLRenderer2.default; /** + * @namespace PIXI + */ + +},{"./Application":42,"./Shader":43,"./autoDetectRenderer":44,"./const":45,"./display/Bounds":46,"./display/Container":47,"./display/DisplayObject":48,"./display/Transform":49,"./display/TransformBase":50,"./display/TransformStatic":51,"./graphics/Graphics":52,"./graphics/GraphicsData":53,"./graphics/canvas/CanvasGraphicsRenderer":54,"./graphics/webgl/GraphicsRenderer":56,"./math":69,"./renderers/canvas/CanvasRenderer":76,"./renderers/canvas/utils/CanvasRenderTarget":78,"./renderers/webgl/WebGLRenderer":83,"./renderers/webgl/filters/Filter":85,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":88,"./renderers/webgl/managers/WebGLManager":92,"./renderers/webgl/utils/ObjectRenderer":93,"./renderers/webgl/utils/Quad":94,"./renderers/webgl/utils/RenderTarget":95,"./settings":100,"./sprites/Sprite":101,"./sprites/canvas/CanvasSpriteRenderer":102,"./sprites/canvas/CanvasTinter":103,"./sprites/webgl/SpriteRenderer":105,"./text/Text":107,"./text/TextMetrics":108,"./text/TextStyle":109,"./textures/BaseRenderTexture":110,"./textures/BaseTexture":111,"./textures/RenderTexture":112,"./textures/Spritesheet":113,"./textures/Texture":114,"./textures/TextureUvs":115,"./textures/VideoBaseTexture":116,"./ticker":119,"./utils":123,"pixi-gl-core":12}],65:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Matrix = require('./Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16 + +var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; +var tempMatrices = []; + +var mul = []; + +function signum(x) { + if (x < 0) { + return -1; + } + if (x > 0) { + return 1; + } + + return 0; +} + +function init() { + for (var i = 0; i < 16; i++) { + var row = []; + + mul.push(row); + + for (var j = 0; j < 16; j++) { + var _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); + var _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); + var _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); + var _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); + + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + + for (var _i = 0; _i < 16; _i++) { + var mat = new _Matrix2.default(); + + mat.set(ux[_i], uy[_i], vx[_i], vy[_i], 0, 0); + tempMatrices.push(mat); + } +} + +init(); + +/** + * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, + * D8 is the same but with diagonals. Used for texture rotations. + * + * Vector xX(i), xY(i) is U-axis of sprite with rotation i + * Vector yY(i), yY(i) is V-axis of sprite with rotation i + * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) + * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) + * This is the small part of gameofbombs.com portal system. It works. + * + * @author Ivan @ivanpopelyshev + * @class + * @memberof PIXI + */ +var GroupD8 = { + E: 0, + SE: 1, + S: 2, + SW: 3, + W: 4, + NW: 5, + N: 6, + NE: 7, + MIRROR_VERTICAL: 8, + MIRROR_HORIZONTAL: 12, + uX: function uX(ind) { + return ux[ind]; + }, + uY: function uY(ind) { + return uy[ind]; + }, + vX: function vX(ind) { + return vx[ind]; + }, + vY: function vY(ind) { + return vy[ind]; + }, + inv: function inv(rotation) { + if (rotation & 8) { + return rotation & 15; + } + + return -rotation & 7; + }, + add: function add(rotationSecond, rotationFirst) { + return mul[rotationSecond][rotationFirst]; + }, + sub: function sub(rotationSecond, rotationFirst) { + return mul[rotationSecond][GroupD8.inv(rotationFirst)]; + }, + + /** + * Adds 180 degrees to rotation. Commutative operation. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to rotate. + * @returns {number} rotated number + */ + rotate180: function rotate180(rotation) { + return rotation ^ 4; + }, + + /** + * I dont know why sometimes width and heights needs to be swapped. We'll fix it later. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the width/height should be swapped. + */ + isSwapWidthHeight: function isSwapWidthHeight(rotation) { + return (rotation & 3) === 2; + }, + + /** + * @memberof PIXI.GroupD8 + * @param {number} dx - TODO + * @param {number} dy - TODO + * + * @return {number} TODO + */ + byDirection: function byDirection(dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return GroupD8.S; + } + + return GroupD8.N; + } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return GroupD8.E; + } + + return GroupD8.W; + } else if (dy > 0) { + if (dx > 0) { + return GroupD8.SE; + } + + return GroupD8.SW; + } else if (dx > 0) { + return GroupD8.NE; + } + + return GroupD8.NW; + }, + + /** + * Helps sprite to compensate texture packer rotation. + * + * @memberof PIXI.GroupD8 + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {number} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function matrixAppendRotationInv(matrix, rotation) { + var tx = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var ty = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + // Packer used "rotation", we use "inv(rotation)" + var mat = tempMatrices[GroupD8.inv(rotation)]; + + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + } +}; + +exports.default = GroupD8; + +},{"./Matrix":66}],66:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Point = require('./Point'); + +var _Point2 = _interopRequireDefault(_Point); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The pixi Matrix class as an object, which makes it a lot faster, + * here is a representation of it : + * | a | b | tx| + * | c | d | ty| + * | 0 | 0 | 1 | + * + * @class + * @memberof PIXI + */ +var Matrix = function () { + /** + * @param {number} [a=1] - x scale + * @param {number} [b=0] - y skew + * @param {number} [c=0] - x skew + * @param {number} [d=1] - y scale + * @param {number} [tx=0] - x translation + * @param {number} [ty=0] - y translation + */ + function Matrix() { + var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var d = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var tx = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var ty = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + + _classCallCheck(this, Matrix); + + /** + * @member {number} + * @default 1 + */ + this.a = a; + + /** + * @member {number} + * @default 0 + */ + this.b = b; + + /** + * @member {number} + * @default 0 + */ + this.c = c; + + /** + * @member {number} + * @default 1 + */ + this.d = d; + + /** + * @member {number} + * @default 0 + */ + this.tx = tx; + + /** + * @member {number} + * @default 0 + */ + this.ty = ty; + + this.array = null; + } + + /** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @param {number[]} array - The array that the matrix will be populated from. + */ + + + Matrix.prototype.fromArray = function fromArray(array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + }; + + /** + * sets the matrix properties + * + * @param {number} a - Matrix component + * @param {number} b - Matrix component + * @param {number} c - Matrix component + * @param {number} d - Matrix component + * @param {number} tx - Matrix component + * @param {number} ty - Matrix component + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.set = function set(a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + }; + + /** + * Creates an array from the current Matrix object. + * + * @param {boolean} transpose - Whether we need to transpose the matrix or not + * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out + * @return {number[]} the newly created array which contains the matrix + */ + + + Matrix.prototype.toArray = function toArray(transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + + var array = out || this.array; + + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + }; + + /** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, transformed through this matrix + */ + + + Matrix.prototype.apply = function apply(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; + + return newPos; + }; + + /** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, inverse-transformed through this matrix + */ + + + Matrix.prototype.applyInverse = function applyInverse(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var id = 1 / (this.a * this.d + this.c * -this.b); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + }; + + /** + * Translates the matrix on the x and y. + * + * @param {number} x How much to translate x by + * @param {number} y How much to translate y by + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.translate = function translate(x, y) { + this.tx += x; + this.ty += y; + + return this; + }; + + /** + * Applies a scale transformation to the matrix. + * + * @param {number} x The amount to scale horizontally + * @param {number} y The amount to scale vertically + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.scale = function scale(x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + }; + + /** + * Applies a rotation transformation to the matrix. + * + * @param {number} angle - The angle in radians. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.rotate = function rotate(angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos - this.b * sin; + this.b = a1 * sin + this.b * cos; + this.c = c1 * cos - this.d * sin; + this.d = c1 * sin + this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + }; + + /** + * Appends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to append. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.append = function append(matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + }; + + /** + * Sets the matrix based on all the available properties + * + * @param {number} x - Position on the x axis + * @param {number} y - Position on the y axis + * @param {number} pivotX - Pivot on the x axis + * @param {number} pivotY - Pivot on the y axis + * @param {number} scaleX - Scale on the x axis + * @param {number} scaleY - Scale on the y axis + * @param {number} rotation - Rotation in radians + * @param {number} skewX - Skew on the x axis + * @param {number} skewY - Skew on the y axis + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.setTransform = function setTransform(x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + var sr = Math.sin(rotation); + var cr = Math.cos(rotation); + var cy = Math.cos(skewY); + var sy = Math.sin(skewY); + var nsx = -Math.sin(skewX); + var cx = Math.cos(skewX); + + var a = cr * scaleX; + var b = sr * scaleX; + var c = -sr * scaleY; + var d = cr * scaleY; + + this.a = cy * a + sy * c; + this.b = cy * b + sy * d; + this.c = nsx * a + cx * c; + this.d = nsx * b + cx * d; + + this.tx = x + (pivotX * a + pivotY * c); + this.ty = y + (pivotX * b + pivotY * d); + + return this; + }; + + /** + * Prepends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to prepend + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.prepend = function prepend(matrix) { + var tx1 = this.tx; + + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + + this.a = a1 * matrix.a + this.b * matrix.c; + this.b = a1 * matrix.b + this.b * matrix.d; + this.c = c1 * matrix.a + this.d * matrix.c; + this.d = c1 * matrix.b + this.d * matrix.d; + } + + this.tx = tx1 * matrix.a + this.ty * matrix.c + matrix.tx; + this.ty = tx1 * matrix.b + this.ty * matrix.d + matrix.ty; + + return this; + }; + + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * + * @param {PIXI.Transform|PIXI.TransformStatic} transform - The transform to apply the properties to. + * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properties + */ + + + Matrix.prototype.decompose = function decompose(transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + + var skewX = -Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + + var delta = Math.abs(skewX + skewY); + + if (delta < 0.00001) { + transform.rotation = skewY; + + if (a < 0 && d >= 0) { + transform.rotation += transform.rotation <= 0 ? Math.PI : -Math.PI; + } + + transform.skew.x = transform.skew.y = 0; + } else { + transform.skew.x = skewX; + transform.skew.y = skewY; + } + + // next set scale + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); + + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; + + return transform; + }; + + /** + * Inverts this matrix + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.invert = function invert() { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1 * d1 - b1 * c1; + + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = (c1 * this.ty - d1 * tx1) / n; + this.ty = -(a1 * this.ty - b1 * tx1) / n; + + return this; + }; + + /** + * Resets this Matix to an identity (default) matrix. + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.identity = function identity() { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + + return this; + }; + + /** + * Creates a new Matrix object with the same values as this one. + * + * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. + */ + + + Matrix.prototype.clone = function clone() { + var matrix = new Matrix(); + + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * Changes the values of the given matrix to be the same as the ones in this matrix + * + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @return {PIXI.Matrix} The matrix given in parameter with its values updated. + */ + + + Matrix.prototype.copy = function copy(matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * A default (identity) matrix + * + * @static + * @const + */ + + + _createClass(Matrix, null, [{ + key: 'IDENTITY', + get: function get() { + return new Matrix(); + } + + /** + * A temp matrix + * + * @static + * @const + */ + + }, { + key: 'TEMP_MATRIX', + get: function get() { + return new Matrix(); + } + }]); + + return Matrix; +}(); + +exports.default = Matrix; + +},{"./Point":68}],67:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * An observable point is a point that triggers a callback when the point's position is changed. + * + * @class + * @memberof PIXI + */ +var ObservablePoint = function () { + /** + * @param {Function} cb - callback when changed + * @param {object} scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope) { + var x = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var y = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, ObservablePoint); + + this._x = x; + this._y = y; + + this.cb = cb; + this.scope = scope; + } + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + ObservablePoint.prototype.set = function set(x, y) { + var _x = x || 0; + var _y = y || (y !== 0 ? _x : 0); + + if (this._x !== _x || this._y !== _y) { + this._x = _x; + this._y = _y; + this.cb.call(this.scope); + } + }; + + /** + * Copies the data from another point + * + * @param {PIXI.Point|PIXI.ObservablePoint} point - point to copy from + */ + + + ObservablePoint.prototype.copy = function copy(point) { + if (this._x !== point.x || this._y !== point.y) { + this._x = point.x; + this._y = point.y; + this.cb.call(this.scope); + } + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + + _createClass(ObservablePoint, [{ + key: "x", + get: function get() { + return this._x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + } + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + }, { + key: "y", + get: function get() { + return this._y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + } + }]); + + return ObservablePoint; +}(); + +exports.default = ObservablePoint; + +},{}],68:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * + * @class + * @memberof PIXI + */ +var Point = function () { + /** + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function Point() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + + _classCallCheck(this, Point); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + } + + /** + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point + */ + + + Point.prototype.clone = function clone() { + return new Point(this.x, this.y); + }; + + /** + * Copies x and y from the given point + * + * @param {PIXI.Point} p - The point to copy. + */ + + + Point.prototype.copy = function copy(p) { + this.set(p.x, p.y); + }; + + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.Point} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + + + Point.prototype.equals = function equals(p) { + return p.x === this.x && p.y === this.y; + }; + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + Point.prototype.set = function set(x, y) { + this.x = x || 0; + this.y = y || (y !== 0 ? this.x : 0); + }; + + return Point; +}(); + +exports.default = Point; + +},{}],69:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('./Point'); + +Object.defineProperty(exports, 'Point', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Point).default; + } +}); + +var _ObservablePoint = require('./ObservablePoint'); + +Object.defineProperty(exports, 'ObservablePoint', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObservablePoint).default; + } +}); + +var _Matrix = require('./Matrix'); + +Object.defineProperty(exports, 'Matrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Matrix).default; + } +}); + +var _GroupD = require('./GroupD8'); + +Object.defineProperty(exports, 'GroupD8', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GroupD).default; + } +}); + +var _Circle = require('./shapes/Circle'); + +Object.defineProperty(exports, 'Circle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Circle).default; + } +}); + +var _Ellipse = require('./shapes/Ellipse'); + +Object.defineProperty(exports, 'Ellipse', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Ellipse).default; + } +}); + +var _Polygon = require('./shapes/Polygon'); + +Object.defineProperty(exports, 'Polygon', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Polygon).default; + } +}); + +var _Rectangle = require('./shapes/Rectangle'); + +Object.defineProperty(exports, 'Rectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rectangle).default; + } +}); + +var _RoundedRectangle = require('./shapes/RoundedRectangle'); + +Object.defineProperty(exports, 'RoundedRectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RoundedRectangle).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./GroupD8":65,"./Matrix":66,"./ObservablePoint":67,"./Point":68,"./shapes/Circle":70,"./shapes/Ellipse":71,"./shapes/Polygon":72,"./shapes/Rectangle":73,"./shapes/RoundedRectangle":74}],70:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Circle object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Circle = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [radius=0] - The radius of the circle + */ + function Circle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var radius = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + _classCallCheck(this, Circle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.CIRC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.CIRC; + } + + /** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ + + + Circle.prototype.clone = function clone() { + return new Circle(this.x, this.y, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this circle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Circle + */ + + + Circle.prototype.contains = function contains(x, y) { + if (this.radius <= 0) { + return false; + } + + var r2 = this.radius * this.radius; + var dx = this.x - x; + var dy = this.y - y; + + dx *= dx; + dy *= dy; + + return dx + dy <= r2; + }; + + /** + * Returns the framing rectangle of the circle as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Circle.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + + return Circle; +}(); + +exports.default = Circle; + +},{"../../const":45,"./Rectangle":73}],71:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Ellipse object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Ellipse = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [width=0] - The half width of this ellipse + * @param {number} [height=0] - The half height of this ellipse + */ + function Ellipse() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Ellipse); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.ELIP + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.ELIP; + } + + /** + * Creates a clone of this Ellipse instance + * + * @return {PIXI.Ellipse} a copy of the ellipse + */ + + + Ellipse.prototype.clone = function clone() { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coords are within this ellipse + */ + + + Ellipse.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + // normalize the coords to an ellipse with center 0,0 + var normx = (x - this.x) / this.width; + var normy = (y - this.y) / this.height; + + normx *= normx; + normy *= normy; + + return normx + normy <= 1; + }; + + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Ellipse.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.width, this.y - this.height, this.width, this.height); + }; + + return Ellipse; +}(); + +exports.default = Ellipse; + +},{"../../const":45,"./Rectangle":73}],72:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('../Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Polygon = function () { + /** + * @param {PIXI.Point[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + for (var _len = arguments.length, points = Array(_len), _key = 0; _key < _len; _key++) { + points[_key] = arguments[_key]; + } + + _classCallCheck(this, Polygon); + + if (Array.isArray(points[0])) { + points = points[0]; + } + + // if this is an array of points, convert it to a flat array of numbers + if (points[0] instanceof _Point2.default) { + var p = []; + + for (var i = 0, il = points.length; i < il; i++) { + p.push(points[i].x, points[i].y); + } + + points = p; + } + + this.closed = true; + + /** + * An array of the points of this polygon + * + * @member {number[]} + */ + this.points = points; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.POLY + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.POLY; + } + + /** + * Creates a clone of this polygon + * + * @return {PIXI.Polygon} a copy of the polygon + */ + + + Polygon.prototype.clone = function clone() { + return new Polygon(this.points.slice()); + }; + + /** + * Closes the polygon, adding points if necessary. + * + */ + + + Polygon.prototype.close = function close() { + var points = this.points; + + // close the poly if the value is true! + if (points[0] !== points[points.length - 2] || points[1] !== points[points.length - 1]) { + points.push(points[0], points[1]); + } + }; + + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this polygon + */ + + + Polygon.prototype.contains = function contains(x, y) { + var inside = false; + + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + + for (var i = 0, j = length - 1; i < length; j = i++) { + var xi = this.points[i * 2]; + var yi = this.points[i * 2 + 1]; + var xj = this.points[j * 2]; + var yj = this.points[j * 2 + 1]; + var intersect = yi > y !== yj > y && x < (xj - xi) * ((y - yi) / (yj - yi)) + xi; + + if (intersect) { + inside = !inside; + } + } + + return inside; + }; + + return Polygon; +}(); + +exports.default = Polygon; + +},{"../../const":45,"../Point":68}],73:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * + * @class + * @memberof PIXI + */ +var Rectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle + * @param {number} [width=0] - The overall width of this rectangle + * @param {number} [height=0] - The overall height of this rectangle + */ + function Rectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Rectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.RECT + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RECT; + } + + /** + * returns the left edge of the rectangle + * + * @member {number} + */ + + + /** + * Creates a clone of this Rectangle + * + * @return {PIXI.Rectangle} a copy of the rectangle + */ + Rectangle.prototype.clone = function clone() { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + + /** + * Copies another rectangle to this one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to copy. + * @return {PIXI.Rectangle} Returns itself. + */ + + + Rectangle.prototype.copy = function copy(rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + + return this; + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rectangle + */ + + + Rectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + + return false; + }; + + /** + * Pads the rectangle making it grow in all directions. + * + * @param {number} paddingX - The horizontal padding amount. + * @param {number} paddingY - The vertical padding amount. + */ + + + Rectangle.prototype.pad = function pad(paddingX, paddingY) { + paddingX = paddingX || 0; + paddingY = paddingY || (paddingY !== 0 ? paddingX : 0); + + this.x -= paddingX; + this.y -= paddingY; + + this.width += paddingX * 2; + this.height += paddingY * 2; + }; + + /** + * Fits this rectangle around the passed one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to fit. + */ + + + Rectangle.prototype.fit = function fit(rectangle) { + if (this.x < rectangle.x) { + this.width += this.x; + if (this.width < 0) { + this.width = 0; + } + + this.x = rectangle.x; + } + + if (this.y < rectangle.y) { + this.height += this.y; + if (this.height < 0) { + this.height = 0; + } + this.y = rectangle.y; + } + + if (this.x + this.width > rectangle.x + rectangle.width) { + this.width = rectangle.width - this.x; + if (this.width < 0) { + this.width = 0; + } + } + + if (this.y + this.height > rectangle.y + rectangle.height) { + this.height = rectangle.height - this.y; + if (this.height < 0) { + this.height = 0; + } + } + }; + + /** + * Enlarges this rectangle to include the passed rectangle. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to include. + */ + + + Rectangle.prototype.enlarge = function enlarge(rectangle) { + var x1 = Math.min(this.x, rectangle.x); + var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.min(this.y, rectangle.y); + var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); + + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + }; + + _createClass(Rectangle, [{ + key: 'left', + get: function get() { + return this.x; + } + + /** + * returns the right edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'right', + get: function get() { + return this.x + this.width; + } + + /** + * returns the top edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'top', + get: function get() { + return this.y; + } + + /** + * returns the bottom edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'bottom', + get: function get() { + return this.y + this.height; + } + + /** + * A constant empty rectangle. + * + * @static + * @constant + */ + + }], [{ + key: 'EMPTY', + get: function get() { + return new Rectangle(0, 0, 0, 0); + } + }]); + + return Rectangle; +}(); + +exports.default = Rectangle; + +},{"../../const":45}],74:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. + * + * @class + * @memberof PIXI + */ +var RoundedRectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle + * @param {number} [width=0] - The overall width of this rounded rectangle + * @param {number} [height=0] - The overall height of this rounded rectangle + * @param {number} [radius=20] - Controls the radius of the rounded corners + */ + function RoundedRectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var radius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 20; + + _classCallCheck(this, RoundedRectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * @member {number} + * @default 20 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readonly + * @default PIXI.SHAPES.RREC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RREC; + } + + /** + * Creates a clone of this Rounded Rectangle + * + * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle + */ + + + RoundedRectangle.prototype.clone = function clone() { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + */ + + + RoundedRectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + if (y >= this.y + this.radius && y <= this.y + this.height - this.radius || x >= this.x + this.radius && x <= this.x + this.width - this.radius) { + return true; + } + var dx = x - (this.x + this.radius); + var dy = y - (this.y + this.radius); + var radius2 = this.radius * this.radius; + + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.width - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dy = y - (this.y + this.height - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + } + } + + return false; + }; + + return RoundedRectangle; +}(); + +exports.default = RoundedRectangle; + +},{"../../const":45}],75:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _math = require('../math'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _Container = require('../display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMatrix = new _math.Matrix(); + +/** + * The SystemRenderer is the base for a Pixi Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.WebGLRenderer} which can be used for rendering a Pixi scene. + * + * @abstract + * @class + * @extends EventEmitter + * @memberof PIXI + */ + +var SystemRenderer = function (_EventEmitter) { + _inherits(SystemRenderer, _EventEmitter); + + // eslint-disable-next-line valid-jsdoc + /** + * @param {string} system - The name of the system this renderer is for. + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function SystemRenderer(system, options, arg2, arg3) { + _classCallCheck(this, SystemRenderer); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + (0, _utils.sayHello)(system); + + // Support for constructor(system, screenWidth, screenHeight, options) + if (typeof options === 'number') { + options = Object.assign({ + width: options, + height: arg2 || _settings2.default.RENDER_OPTIONS.height + }, arg3); + } + + // Add the default render options + options = Object.assign({}, _settings2.default.RENDER_OPTIONS, options); + + /** + * The supplied constructor options. + * + * @member {Object} + * @readOnly + */ + _this.options = options; + + /** + * The type of the renderer. + * + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.UNKNOWN; + + /** + * Measurements of the screen. (0, 0, screenWidth, screenHeight) + * + * Its safe to use as filterArea or hitArea for whole stage + * + * @member {PIXI.Rectangle} + */ + _this.screen = new _math.Rectangle(0, 0, options.width, options.height); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.view = options.view || document.createElement('canvas'); + + /** + * The resolution / device pixel ratio of the renderer + * + * @member {number} + * @default 1 + */ + _this.resolution = options.resolution || _settings2.default.RESOLUTION; + + /** + * Whether the render view is transparent + * + * @member {boolean} + */ + _this.transparent = options.transparent; + + /** + * Whether css dimensions of canvas view should be resized to screen dimensions automatically + * + * @member {boolean} + */ + _this.autoResize = options.autoResize || false; + + /** + * Tracks the blend modes useful for this renderer. + * + * @member {object} + */ + _this.blendModes = null; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent Pixi will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent Pixi will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example if + * your game has a canvas filling background image you often don't need this set. + * + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + + /** + * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + * + * @member {boolean} + */ + _this.roundPixels = options.roundPixels; + + /** + * The background color as a number. + * + * @member {number} + * @private + */ + _this._backgroundColor = 0x000000; + + /** + * The background color as an [R, G, B] array. + * + * @member {number[]} + * @private + */ + _this._backgroundColorRgba = [0, 0, 0, 0]; + + /** + * The background color as a string. + * + * @member {string} + * @private + */ + _this._backgroundColorString = '#000000'; + + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + + /** + * This temporary display object used as the parent of the currently being rendered item + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._tempDisplayObjectParent = new _Container2.default(); + + /** + * The last root object that the renderer tried to render. + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._lastObjectRendered = _this._tempDisplayObjectParent; + return _this; + } + + /** + * Same as view.width, actual number of pixels in the canvas by horizontal + * + * @member {number} + * @readonly + * @default 800 + */ + + + /** + * Resizes the screen and canvas to the specified width and height + * Canvas dimensions are multiplied by resolution + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + SystemRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + this.screen.width = screenWidth; + this.screen.height = screenHeight; + + this.view.width = screenWidth * this.resolution; + this.view.height = screenHeight * this.resolution; + + if (this.autoResize) { + this.view.style.width = screenWidth + 'px'; + this.view.style.height = screenHeight + 'px'; + } + }; + + /** + * Useful function that returns a texture of the display object that can then be used to create sprites + * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. + * + * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from + * @param {number} scaleMode - Should be one of the scaleMode consts + * @param {number} resolution - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.Texture} a texture of the graphics object + */ + + + SystemRenderer.prototype.generateTexture = function generateTexture(displayObject, scaleMode, resolution) { + var bounds = displayObject.getLocalBounds(); + + var renderTexture = _RenderTexture2.default.create(bounds.width | 0, bounds.height | 0, scaleMode, resolution); + + tempMatrix.tx = -bounds.x; + tempMatrix.ty = -bounds.y; + + this.render(displayObject, renderTexture, false, tempMatrix, true); + + return renderTexture; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + SystemRenderer.prototype.destroy = function destroy(removeView) { + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } + + this.type = _const.RENDERER_TYPE.UNKNOWN; + + this.view = null; + + this.screen = null; + + this.resolution = 0; + + this.transparent = false; + + this.autoResize = false; + + this.blendModes = null; + + this.options = null; + + this.preserveDrawingBuffer = false; + this.clearBeforeRender = false; + + this.roundPixels = false; + + this._backgroundColor = 0; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + + this._tempDisplayObjectParent = null; + this._lastObjectRendered = null; + }; + + /** + * The background color to fill if not transparent + * + * @member {number} + */ + + + _createClass(SystemRenderer, [{ + key: 'width', + get: function get() { + return this.view.width; + } + + /** + * Same as view.height, actual number of pixels in the canvas by vertical + * + * @member {number} + * @readonly + * @default 600 + */ + + }, { + key: 'height', + get: function get() { + return this.view.height; + } + }, { + key: 'backgroundColor', + get: function get() { + return this._backgroundColor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._backgroundColor = value; + this._backgroundColorString = (0, _utils.hex2string)(value); + (0, _utils.hex2rgb)(value, this._backgroundColorRgba); + } + }]); + + return SystemRenderer; +}(_eventemitter2.default); + +exports.default = SystemRenderer; + +},{"../const":45,"../display/Container":47,"../math":69,"../settings":100,"../textures/RenderTexture":112,"../utils":123,"eventemitter3":3}],76:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _CanvasMaskManager = require('./utils/CanvasMaskManager'); + +var _CanvasMaskManager2 = _interopRequireDefault(_CanvasMaskManager); + +var _CanvasRenderTarget = require('./utils/CanvasRenderTarget'); + +var _CanvasRenderTarget2 = _interopRequireDefault(_CanvasRenderTarget); + +var _mapCanvasBlendModesToPixi = require('./utils/mapCanvasBlendModesToPixi'); + +var _mapCanvasBlendModesToPixi2 = _interopRequireDefault(_mapCanvasBlendModesToPixi); + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should + * be used for browsers that do not support WebGL. Don't forget to add the CanvasRenderer.view to + * your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ +var CanvasRenderer = function (_SystemRenderer) { + _inherits(CanvasRenderer, _SystemRenderer); + + // eslint-disable-next-line valid-jsdoc + /** + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function CanvasRenderer(options, arg2, arg3) { + _classCallCheck(this, CanvasRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'Canvas', options, arg2, arg3)); + + _this.type = _const.RENDERER_TYPE.CANVAS; + + /** + * The root canvas 2d context that everything is drawn with. + * + * @member {CanvasRenderingContext2D} + */ + _this.rootContext = _this.view.getContext('2d', { alpha: _this.transparent }); + + /** + * The currently active canvas 2d context (could change with renderTextures) + * + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.rootContext; + + /** + * Boolean flag controlling canvas refresh. + * + * @member {boolean} + */ + _this.refresh = true; + + /** + * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. + * + * @member {PIXI.CanvasMaskManager} + */ + _this.maskManager = new _CanvasMaskManager2.default(_this); + + /** + * The canvas property used to set the canvas smoothing property. + * + * @member {string} + */ + _this.smoothProperty = 'imageSmoothingEnabled'; + + if (!_this.rootContext.imageSmoothingEnabled) { + if (_this.rootContext.webkitImageSmoothingEnabled) { + _this.smoothProperty = 'webkitImageSmoothingEnabled'; + } else if (_this.rootContext.mozImageSmoothingEnabled) { + _this.smoothProperty = 'mozImageSmoothingEnabled'; + } else if (_this.rootContext.oImageSmoothingEnabled) { + _this.smoothProperty = 'oImageSmoothingEnabled'; + } else if (_this.rootContext.msImageSmoothingEnabled) { + _this.smoothProperty = 'msImageSmoothingEnabled'; + } + } + + _this.initPlugins(); + + _this.blendModes = (0, _mapCanvasBlendModesToPixi2.default)(); + _this._activeBlendMode = null; + + _this.renderingToScreen = false; + + _this.resize(_this.options.width, _this.options.height); + + /** + * Fired after rendering finishes. + * + * @event PIXI.CanvasRenderer#postrender + */ + + /** + * Fired before rendering starts. + * + * @event PIXI.CanvasRenderer#prerender + */ + return _this; + } + + /** + * Renders the object to this canvas view + * + * @param {PIXI.DisplayObject} displayObject - The object to be rendered + * @param {PIXI.RenderTexture} [renderTexture] - A render texture to be rendered to. + * If unset, it will render to the root context. + * @param {boolean} [clear=false] - Whether to clear the canvas before drawing + * @param {PIXI.Transform} [transform] - A transformation to be applied + * @param {boolean} [skipUpdateTransform=false] - Whether to skip the update transform + */ + + + CanvasRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!this.view) { + return; + } + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + var rootResolution = this.resolution; + + if (renderTexture) { + renderTexture = renderTexture.baseTexture || renderTexture; + + if (!renderTexture._canvasRenderTarget) { + renderTexture._canvasRenderTarget = new _CanvasRenderTarget2.default(renderTexture.width, renderTexture.height, renderTexture.resolution); + renderTexture.source = renderTexture._canvasRenderTarget.canvas; + renderTexture.valid = true; + } + + this.context = renderTexture._canvasRenderTarget.context; + this.resolution = renderTexture._canvasRenderTarget.resolution; + } else { + this.context = this.rootContext; + } + + var context = this.context; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + var tempWt = this._tempDisplayObjectParent.transform.worldTransform; + + if (transform) { + transform.copy(tempWt); + + // lets not forget to flag the parent transform as dirty... + this._tempDisplayObjectParent.transform._worldID = -1; + } else { + tempWt.identity(); + } + + displayObject.parent = this._tempDisplayObjectParent; + + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + context.setTransform(1, 0, 0, 1, 0, 0); + context.globalAlpha = 1; + context.globalCompositeOperation = this.blendModes[_const.BLEND_MODES.NORMAL]; + + if (navigator.isCocoonJS && this.view.screencanvas) { + context.fillStyle = 'black'; + context.clear(); + } + + if (clear !== undefined ? clear : this.clearBeforeRender) { + if (this.renderingToScreen) { + if (this.transparent) { + context.clearRect(0, 0, this.width, this.height); + } else { + context.fillStyle = this._backgroundColorString; + context.fillRect(0, 0, this.width, this.height); + } + } // else { + // TODO: implement background for CanvasRenderTarget or RenderTexture? + // } + } + + // TODO RENDER TARGET STUFF HERE.. + var tempContext = this.context; + + this.context = context; + displayObject.renderCanvas(this); + this.context = tempContext; + + this.resolution = rootResolution; + + this.emit('postrender'); + }; + + /** + * Clear the canvas of renderer. + * + * @param {string} [clearColor] - Clear the canvas with this color, except the canvas is transparent. + */ + + + CanvasRenderer.prototype.clear = function clear(clearColor) { + var context = this.context; + + clearColor = clearColor || this._backgroundColorString; + + if (!this.transparent && clearColor) { + context.fillStyle = clearColor; + context.fillRect(0, 0, this.width, this.height); + } else { + context.clearRect(0, 0, this.width, this.height); + } + }; + + /** + * Sets the blend mode of the renderer. + * + * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values. + */ + + + CanvasRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + if (this._activeBlendMode === blendMode) { + return; + } + + this._activeBlendMode = blendMode; + this.context.globalCompositeOperation = this.blendModes[blendMode]; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + CanvasRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // call the base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.context = null; + + this.refresh = true; + + this.maskManager.destroy(); + this.maskManager = null; + + this.smoothProperty = null; + }; + + /** + * Resizes the canvas view to the specified width and height. + * + * @extends PIXI.SystemRenderer#resize + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + CanvasRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + _SystemRenderer.prototype.resize.call(this, screenWidth, screenHeight); + + // reset the scale mode.. oddly this seems to be reset when the canvas is resized. + // surely a browser bug?? Let pixi fix that for you.. + if (this.smoothProperty) { + this.rootContext[this.smoothProperty] = _settings2.default.SCALE_MODE === _const.SCALE_MODES.LINEAR; + } + }; + + return CanvasRenderer; +}(_SystemRenderer3.default); + +/** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @name PIXI.CanvasRenderer#plugins + * @type {object} + * @readonly + * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.extract.CanvasExtract} extract Extract image data from renderer. + * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.prepare.CanvasPrepare} prepare Pre-render display objects. + */ + +/** + * Adds a plugin to the renderer. + * + * @method PIXI.CanvasRenderer#registerPlugin + * @param {string} pluginName - The name of the plugin. + * @param {Function} ctor - The constructor function or class for the plugin. + */ + +exports.default = CanvasRenderer; +_utils.pluginTarget.mixin(CanvasRenderer); + +},{"../../const":45,"../../settings":100,"../../utils":123,"../SystemRenderer":75,"./utils/CanvasMaskManager":77,"./utils/CanvasRenderTarget":78,"./utils/mapCanvasBlendModesToPixi":80}],77:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A set of functions used to handle masking. + * + * @class + * @memberof PIXI + */ +var CanvasMaskManager = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + function CanvasMaskManager(renderer) { + _classCallCheck(this, CanvasMaskManager); + + this.renderer = renderer; + } + + /** + * This method adds it to the current stack of masks. + * + * @param {object} maskData - the maskData that will be pushed + */ + + + CanvasMaskManager.prototype.pushMask = function pushMask(maskData) { + var renderer = this.renderer; + + renderer.context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.transform.worldTransform; + var resolution = renderer.resolution; + + renderer.context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // TODO suport sprite alpha masks?? + // lots of effort required. If demand is great enough.. + if (!maskData._texture) { + this.renderGraphicsShape(maskData); + renderer.context.clip(); + } + + maskData.worldAlpha = cacheAlpha; + }; + + /** + * Renders a PIXI.Graphics shape. + * + * @param {PIXI.Graphics} graphics - The object to render. + */ + + + CanvasMaskManager.prototype.renderGraphicsShape = function renderGraphicsShape(graphics) { + var context = this.renderer.context; + var len = graphics.graphicsData.length; + + if (len === 0) { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === _const.SHAPES.POLY) { + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; j++) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) { + context.closePath(); + } + } else if (data.type === _const.SHAPES.RECT) { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } + }; + + /** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @param {PIXI.CanvasRenderer} renderer - The renderer context to use. + */ + + + CanvasMaskManager.prototype.popMask = function popMask(renderer) { + renderer.context.restore(); + }; + + /** + * Destroys this canvas mask manager. + * + */ + + + CanvasMaskManager.prototype.destroy = function destroy() { + /* empty */ + }; + + return CanvasMaskManager; +}(); + +exports.default = CanvasMaskManager; + +},{"../../../const":45}],78:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Creates a Canvas element of the given size. + * + * @class + * @memberof PIXI + */ +var CanvasRenderTarget = function () { + /** + * @param {number} width - the width for the newly created canvas + * @param {number} height - the height for the newly created canvas + * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + _classCallCheck(this, CanvasRenderTarget); + + /** + * The Canvas object that belongs to this CanvasRenderTarget. + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @member {CanvasRenderingContext2D} + */ + this.context = this.canvas.getContext('2d'); + + this.resolution = resolution || _settings2.default.RESOLUTION; + + this.resize(width, height); + } + + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * + * @private + */ + + + CanvasRenderTarget.prototype.clear = function clear() { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + + /** + * Resizes the canvas to the specified width and height. + * + * @param {number} width - the new width of the canvas + * @param {number} height - the new height of the canvas + */ + + + CanvasRenderTarget.prototype.resize = function resize(width, height) { + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; + }; + + /** + * Destroys this canvas. + * + */ + + + CanvasRenderTarget.prototype.destroy = function destroy() { + this.context = null; + this.canvas = null; + }; + + /** + * The width of the canvas buffer in pixels. + * + * @member {number} + */ + + + _createClass(CanvasRenderTarget, [{ + key: 'width', + get: function get() { + return this.canvas.width; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.width = val; + } + + /** + * The height of the canvas buffer in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.canvas.height; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.height = val; + } + }]); + + return CanvasRenderTarget; +}(); + +exports.default = CanvasRenderTarget; + +},{"../../../settings":100}],79:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = canUseNewCanvasBlendModes; +/** + * Creates a little colored canvas + * + * @ignore + * @param {string} color - The color to make the canvas + * @return {canvas} a small canvas element + */ +function createColoredCanvas(color) { + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.fillStyle = color; + context.fillRect(0, 0, 6, 1); + + return canvas; +} + +/** + * Checks whether the Canvas BlendModes are supported by the current browser + * + * @return {boolean} whether they are supported + */ +function canUseNewCanvasBlendModes() { + if (typeof document === 'undefined') { + return false; + } + + var magenta = createColoredCanvas('#ff00ff'); + var yellow = createColoredCanvas('#ffff00'); + + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.globalCompositeOperation = 'multiply'; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + var imageData = context.getImageData(2, 0, 1, 1); + + if (!imageData) { + return false; + } + + var data = imageData.data; + + return data[0] === 255 && data[1] === 0 && data[2] === 0; +} + +},{}],80:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapCanvasBlendModesToPixi; + +var _const = require('../../../const'); + +var _canUseNewCanvasBlendModes = require('./canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Maps blend combinations to Canvas. + * + * @memberof PIXI + * @function mapCanvasBlendModesToPixi + * @private + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapCanvasBlendModesToPixi() { + var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + + if ((0, _canUseNewCanvasBlendModes2.default)()) { + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'multiply'; + array[_const.BLEND_MODES.SCREEN] = 'screen'; + array[_const.BLEND_MODES.OVERLAY] = 'overlay'; + array[_const.BLEND_MODES.DARKEN] = 'darken'; + array[_const.BLEND_MODES.LIGHTEN] = 'lighten'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'color-dodge'; + array[_const.BLEND_MODES.COLOR_BURN] = 'color-burn'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'hard-light'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'soft-light'; + array[_const.BLEND_MODES.DIFFERENCE] = 'difference'; + array[_const.BLEND_MODES.EXCLUSION] = 'exclusion'; + array[_const.BLEND_MODES.HUE] = 'hue'; + array[_const.BLEND_MODES.SATURATION] = 'saturate'; + array[_const.BLEND_MODES.COLOR] = 'color'; + array[_const.BLEND_MODES.LUMINOSITY] = 'luminosity'; + } else { + // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'source-over'; + array[_const.BLEND_MODES.SCREEN] = 'source-over'; + array[_const.BLEND_MODES.OVERLAY] = 'source-over'; + array[_const.BLEND_MODES.DARKEN] = 'source-over'; + array[_const.BLEND_MODES.LIGHTEN] = 'source-over'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'source-over'; + array[_const.BLEND_MODES.COLOR_BURN] = 'source-over'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.DIFFERENCE] = 'source-over'; + array[_const.BLEND_MODES.EXCLUSION] = 'source-over'; + array[_const.BLEND_MODES.HUE] = 'source-over'; + array[_const.BLEND_MODES.SATURATION] = 'source-over'; + array[_const.BLEND_MODES.COLOR] = 'source-over'; + array[_const.BLEND_MODES.LUMINOSITY] = 'source-over'; + } + // not-premultiplied, only for webgl + array[_const.BLEND_MODES.NORMAL_NPM] = array[_const.BLEND_MODES.NORMAL]; + array[_const.BLEND_MODES.ADD_NPM] = array[_const.BLEND_MODES.ADD]; + array[_const.BLEND_MODES.SCREEN_NPM] = array[_const.BLEND_MODES.SCREEN]; + + return array; +} + +},{"../../../const":45,"./canUseNewCanvasBlendModes":79}],81:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged + * up with textures that are no longer being used. + * + * @class + * @memberof PIXI + */ +var TextureGarbageCollector = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function TextureGarbageCollector(renderer) { + _classCallCheck(this, TextureGarbageCollector); + + this.renderer = renderer; + + this.count = 0; + this.checkCount = 0; + this.maxIdle = _settings2.default.GC_MAX_IDLE; + this.checkCountMax = _settings2.default.GC_MAX_CHECK_COUNT; + this.mode = _settings2.default.GC_MODE; + } + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.update = function update() { + this.count++; + + if (this.mode === _const.GC_MODES.MANUAL) { + return; + } + + this.checkCount++; + + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + + this.run(); + } + }; + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.run = function run() { + var tm = this.renderer.textureManager; + var managedTextures = tm._managedTextures; + var wasRemoved = false; + + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + + // only supports non generated textures at the moment! + if (!texture._glRenderTargets && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + + if (wasRemoved) { + var j = 0; + + for (var _i = 0; _i < managedTextures.length; _i++) { + if (managedTextures[_i] !== null) { + managedTextures[j++] = managedTextures[_i]; + } + } + + managedTextures.length = j; + } + }; + + /** + * Removes all the textures within the specified displayObject and its children from the GPU + * + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + */ + + + TextureGarbageCollector.prototype.unload = function unload(displayObject) { + var tm = this.renderer.textureManager; + + // only destroy non generated textures + if (displayObject._texture && displayObject._texture._glRenderTargets) { + tm.destroyTexture(displayObject._texture, true); + } + + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + + return TextureGarbageCollector; +}(); + +exports.default = TextureGarbageCollector; + +},{"../../const":45,"../../settings":100}],82:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _const = require('../../const'); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _utils = require('../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a webGL Texture + * + * @class + * @memberof PIXI + */ +var TextureManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function TextureManager(renderer) { + _classCallCheck(this, TextureManager); + + /** + * A reference to the current renderer + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = renderer.gl; + + /** + * Track textures in the renderer so we can no longer listen to them on destruction. + * + * @member {Array<*>} + * @private + */ + this._managedTextures = []; + } + + /** + * Binds a texture. + * + */ + + + TextureManager.prototype.bindTexture = function bindTexture() {} + // empty + + + /** + * Gets a texture. + * + */ + ; + + TextureManager.prototype.getTexture = function getTexture() {} + // empty + + + /** + * Updates and/or Creates a WebGL texture for the renderer's context. + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update + * @param {number} location - the location the texture will be bound to. + * @return {GLTexture} The gl texture. + */ + ; + + TextureManager.prototype.updateTexture = function updateTexture(texture, location) { + // assume it good! + // texture = texture.baseTexture || texture; + + var gl = this.gl; + + var isRenderTexture = !!texture._glRenderTargets; + + if (!texture.hasLoaded) { + return null; + } + + var boundTextures = this.renderer.boundTextures; + + // if the location is undefined then this may have been called by n event. + // this being the case the texture may already be bound to a slot. As a texture can only be bound once + // we need to find its current location if it exists. + if (location === undefined) { + location = 0; + + // TODO maybe we can use texture bound ids later on... + // check if texture is already bound.. + for (var i = 0; i < boundTextures.length; ++i) { + if (boundTextures[i] === texture) { + location = i; + break; + } + } + } + + boundTextures[location] = texture; + + gl.activeTexture(gl.TEXTURE0 + location); + + var glTexture = texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!glTexture) { + if (isRenderTexture) { + var renderTarget = new _RenderTarget2.default(this.gl, texture.width, texture.height, texture.scaleMode, texture.resolution); + + renderTarget.resize(texture.width, texture.height); + texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget; + glTexture = renderTarget.texture; + } else { + glTexture = new _pixiGlCore.GLTexture(this.gl, null, null, null, null); + glTexture.bind(location); + glTexture.premultiplyAlpha = true; + glTexture.upload(texture.source); + } + + texture._glTextures[this.renderer.CONTEXT_UID] = glTexture; + + texture.on('update', this.updateTexture, this); + texture.on('dispose', this.destroyTexture, this); + + this._managedTextures.push(texture); + + if (texture.isPowerOfTwo) { + if (texture.mipmap) { + glTexture.enableMipmap(); + } + + if (texture.wrapMode === _const.WRAP_MODES.CLAMP) { + glTexture.enableWrapClamp(); + } else if (texture.wrapMode === _const.WRAP_MODES.REPEAT) { + glTexture.enableWrapRepeat(); + } else { + glTexture.enableWrapMirrorRepeat(); + } + } else { + glTexture.enableWrapClamp(); + } + + if (texture.scaleMode === _const.SCALE_MODES.NEAREST) { + glTexture.enableNearestScaling(); + } else { + glTexture.enableLinearScaling(); + } + } + // the texture already exists so we only need to update it.. + else if (isRenderTexture) { + texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height); + } else { + glTexture.upload(texture.source); + } + + return glTexture; + }; + + /** + * Deletes the texture from WebGL + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy + * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. + */ + + + TextureManager.prototype.destroyTexture = function destroyTexture(texture, skipRemove) { + texture = texture.baseTexture || texture; + + if (!texture.hasLoaded) { + return; + } + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + this.renderer.unbindTexture(texture); + + texture._glTextures[this.renderer.CONTEXT_UID].destroy(); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + + delete texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!skipRemove) { + var i = this._managedTextures.indexOf(texture); + + if (i !== -1) { + (0, _utils.removeItems)(this._managedTextures, i, 1); + } + } + } + }; + + /** + * Deletes all the textures from WebGL + */ + + + TextureManager.prototype.removeAll = function removeAll() { + // empty all the old gl textures as they are useless now + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + delete texture._glTextures[this.renderer.CONTEXT_UID]; + } + } + }; + + /** + * Destroys this manager and removes all its textures + */ + + + TextureManager.prototype.destroy = function destroy() { + // destroy managed textures + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + this.destroyTexture(texture, true); + + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + } + + this._managedTextures = null; + }; + + return TextureManager; +}(); + +exports.default = TextureManager; + +},{"../../const":45,"../../utils":123,"./utils/RenderTarget":95,"pixi-gl-core":12}],83:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _MaskManager = require('./managers/MaskManager'); + +var _MaskManager2 = _interopRequireDefault(_MaskManager); + +var _StencilManager = require('./managers/StencilManager'); + +var _StencilManager2 = _interopRequireDefault(_StencilManager); + +var _FilterManager = require('./managers/FilterManager'); + +var _FilterManager2 = _interopRequireDefault(_FilterManager); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _ObjectRenderer = require('./utils/ObjectRenderer'); + +var _ObjectRenderer2 = _interopRequireDefault(_ObjectRenderer); + +var _TextureManager = require('./TextureManager'); + +var _TextureManager2 = _interopRequireDefault(_TextureManager); + +var _BaseTexture = require('../../textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _TextureGarbageCollector = require('./TextureGarbageCollector'); + +var _TextureGarbageCollector2 = _interopRequireDefault(_TextureGarbageCollector); + +var _WebGLState = require('./WebGLState'); + +var _WebGLState2 = _interopRequireDefault(_WebGLState); + +var _mapWebGLDrawModesToPixi = require('./utils/mapWebGLDrawModesToPixi'); + +var _mapWebGLDrawModesToPixi2 = _interopRequireDefault(_mapWebGLDrawModesToPixi); + +var _validateContext = require('./utils/validateContext'); + +var _validateContext2 = _interopRequireDefault(_validateContext); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CONTEXT_UID = 0; + +/** + * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ + +var WebGLRenderer = function (_SystemRenderer) { + _inherits(WebGLRenderer, _SystemRenderer); + + // eslint-disable-next-line valid-jsdoc + /** + * + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias. If not available natively then FXAA + * antialiasing is used + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. + * The resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear + * the canvas or not before the new render pass. If you wish to set this to false, you *must* set + * preserveDrawingBuffer to `true`. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.roundPixels=false] - If true Pixi will Math.floor() x/y values when + * rendering, stopping pixel interpolation. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.legacy=false] - If true Pixi will aim to ensure compatibility + * with older / less advanced devices. If you experiance unexplained flickering try setting this to true. + */ + function WebGLRenderer(options, arg2, arg3) { + _classCallCheck(this, WebGLRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'WebGL', options, arg2, arg3)); + + _this.legacy = _this.options.legacy; + + if (_this.legacy) { + _pixiGlCore2.default.VertexArrayObject.FORCE_NATIVE = true; + } + + /** + * The type of this renderer as a standardised const + * + * @member {number} + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.WEBGL; + + _this.handleContextLost = _this.handleContextLost.bind(_this); + _this.handleContextRestored = _this.handleContextRestored.bind(_this); + + _this.view.addEventListener('webglcontextlost', _this.handleContextLost, false); + _this.view.addEventListener('webglcontextrestored', _this.handleContextRestored, false); + + /** + * The options passed in to create a new webgl context. + * + * @member {object} + * @private + */ + _this._contextOptions = { + alpha: _this.transparent, + antialias: _this.options.antialias, + premultipliedAlpha: _this.transparent && _this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: _this.options.preserveDrawingBuffer + }; + + _this._backgroundColorRgba[3] = _this.transparent ? 0 : 1; + + /** + * Manages the masks using the stencil buffer. + * + * @member {PIXI.MaskManager} + */ + _this.maskManager = new _MaskManager2.default(_this); + + /** + * Manages the stencil buffer. + * + * @member {PIXI.StencilManager} + */ + _this.stencilManager = new _StencilManager2.default(_this); + + /** + * An empty renderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.emptyRenderer = new _ObjectRenderer2.default(_this); + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.currentRenderer = _this.emptyRenderer; + + _this.initPlugins(); + + /** + * The current WebGL rendering context, it is created here + * + * @member {WebGLRenderingContext} + */ + // initialize the context so it is ready for the managers. + if (_this.options.context) { + // checks to see if a context is valid.. + (0, _validateContext2.default)(_this.options.context); + } + + _this.gl = _this.options.context || _pixiGlCore2.default.createContext(_this.view, _this._contextOptions); + + _this.CONTEXT_UID = CONTEXT_UID++; + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.WebGLState} + */ + _this.state = new _WebGLState2.default(_this.gl); + + _this.renderingToScreen = true; + + /** + * Holds the current state of textures bound to the GPU. + * @type {Array} + */ + _this.boundTextures = null; + + /** + * Holds the current shader + * + * @member {PIXI.Shader} + */ + _this._activeShader = null; + + _this._activeVao = null; + + /** + * Holds the current render target + * + * @member {PIXI.RenderTarget} + */ + _this._activeRenderTarget = null; + + _this._initContext(); + + /** + * Manages the filters. + * + * @member {PIXI.FilterManager} + */ + _this.filterManager = new _FilterManager2.default(_this); + // map some webGL blend and drawmodes.. + _this.drawModes = (0, _mapWebGLDrawModesToPixi2.default)(_this.gl); + + _this._nextTextureLocation = 0; + + _this.setBlendMode(0); + + /** + * Fired after rendering finishes. + * + * @event PIXI.WebGLRenderer#postrender + */ + + /** + * Fired before rendering starts. + * + * @event PIXI.WebGLRenderer#prerender + */ + + /** + * Fired when the WebGL context is set. + * + * @event PIXI.WebGLRenderer#context + * @param {WebGLRenderingContext} gl - WebGL context. + */ + return _this; + } + + /** + * Creates the WebGL context + * + * @private + */ + + + WebGLRenderer.prototype._initContext = function _initContext() { + var gl = this.gl; + + // restore a context if it was previously lost + if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').restoreContext(); + } + + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + + this._activeShader = null; + this._activeVao = null; + + this.boundTextures = new Array(maxTextures); + this.emptyTextures = new Array(maxTextures); + + // create a texture manager... + this.textureManager = new _TextureManager2.default(this); + this.textureGC = new _TextureGarbageCollector2.default(this); + + this.state.resetToDefault(); + + this.rootRenderTarget = new _RenderTarget2.default(gl, this.width, this.height, null, this.resolution, true); + this.rootRenderTarget.clearColor = this._backgroundColorRgba; + + this.bindRenderTarget(this.rootRenderTarget); + + // now lets fill up the textures with empty ones! + var emptyGLTexture = new _pixiGlCore2.default.GLTexture.fromData(gl, null, 1, 1); + + var tempObj = { _glTextures: {} }; + + tempObj._glTextures[this.CONTEXT_UID] = {}; + + for (var i = 0; i < maxTextures; i++) { + var empty = new _BaseTexture2.default(); + + empty._glTextures[this.CONTEXT_UID] = emptyGLTexture; + + this.boundTextures[i] = tempObj; + this.emptyTextures[i] = empty; + this.bindTexture(null, i); + } + + this.emit('context', gl); + + // setup the width/height properties and gl viewport + this.resize(this.screen.width, this.screen.height); + }; + + /** + * Renders the object to its webGL view + * + * @param {PIXI.DisplayObject} displayObject - the object to be rendered + * @param {PIXI.RenderTexture} renderTexture - The render texture to render to. + * @param {boolean} [clear] - Should the canvas be cleared before the new render + * @param {PIXI.Transform} [transform] - A transform to apply to the render texture before rendering. + * @param {boolean} [skipUpdateTransform] - Should we skip the update transform pass? + */ + + + WebGLRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + // no point rendering if our context has been blown up! + if (!this.gl || this.gl.isContextLost()) { + return; + } + + this._nextTextureLocation = 0; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + this.bindRenderTexture(renderTexture, transform); + + this.currentRenderer.start(); + + if (clear !== undefined ? clear : this.clearBeforeRender) { + this._activeRenderTarget.clear(); + } + + displayObject.renderWebGL(this); + + // apply transform.. + this.currentRenderer.flush(); + + // this.setObjectRenderer(this.emptyRenderer); + + this.textureGC.update(); + + this.emit('postrender'); + }; + + /** + * Changes the current renderer to the one given in parameter + * + * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. + */ + + + WebGLRenderer.prototype.setObjectRenderer = function setObjectRenderer(objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; + + /** + * This should be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + * + */ + + + WebGLRenderer.prototype.flush = function flush() { + this.setObjectRenderer(this.emptyRenderer); + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + WebGLRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + // if(width * this.resolution === this.width && height * this.resolution === this.height)return; + + _SystemRenderer3.default.prototype.resize.call(this, screenWidth, screenHeight); + + this.rootRenderTarget.resize(screenWidth, screenHeight); + + if (this._activeRenderTarget === this.rootRenderTarget) { + this.rootRenderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true); + } + } + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} blendMode - the desired blend mode + */ + + + WebGLRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + this.state.setBlendMode(blendMode); + }; + + /** + * Erases the active render target and fills the drawing area with a colour + * + * @param {number} [clearColor] - The colour + */ + + + WebGLRenderer.prototype.clear = function clear(clearColor) { + this._activeRenderTarget.clear(clearColor); + }; + + /** + * Sets the transform of the active render target to the given matrix + * + * @param {PIXI.Matrix} matrix - The transformation matrix + */ + + + WebGLRenderer.prototype.setTransform = function setTransform(matrix) { + this._activeRenderTarget.transform = matrix; + }; + + /** + * Erases the render texture and fills the drawing area with a colour + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to clear + * @param {number} [clearColor] - The colour + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.clearRenderTexture = function clearRenderTexture(renderTexture, clearColor) { + var baseTexture = renderTexture.baseTexture; + var renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + + if (renderTarget) { + renderTarget.clear(clearColor); + } + + return this; + }; + + /** + * Binds a render texture for rendering + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to render + * @param {PIXI.Transform} transform - The transform to be applied to the render texture + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTexture = function bindRenderTexture(renderTexture, transform) { + var renderTarget = void 0; + + if (renderTexture) { + var baseTexture = renderTexture.baseTexture; + + if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) { + // bind the current texture + this.textureManager.updateTexture(baseTexture, 0); + } + + this.unbindTexture(baseTexture); + + renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + renderTarget.setFrame(renderTexture.frame); + } else { + renderTarget = this.rootRenderTarget; + } + + renderTarget.transform = transform; + this.bindRenderTarget(renderTarget); + + return this; + }; + + /** + * Changes the current render target to the one given in parameter + * + * @param {PIXI.RenderTarget} renderTarget - the new render target + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTarget = function bindRenderTarget(renderTarget) { + if (renderTarget !== this._activeRenderTarget) { + this._activeRenderTarget = renderTarget; + renderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true); + } + + this.stencilManager.setMaskStack(renderTarget.stencilMaskStack); + } + + return this; + }; + + /** + * Changes the current shader to the one given in parameter + * + * @param {PIXI.Shader} shader - the new shader + * @param {boolean} [autoProject=true] - Whether automatically set the projection matrix + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindShader = function bindShader(shader, autoProject) { + // TODO cache + if (this._activeShader !== shader) { + this._activeShader = shader; + shader.bind(); + + // `autoProject` normally would be a default parameter set to true + // but because of how Babel transpiles default parameters + // it hinders the performance of this method. + if (autoProject !== false) { + // automatically set the projection matrix + shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(true); + } + } + + return this; + }; + + /** + * Binds the texture. This will return the location of the bound texture. + * It may not be the same as the one you pass in. This is due to optimisation that prevents + * needless binding of textures. For example if the texture is already bound it will return the + * current location of the texture instead of the one provided. To bypass this use force location + * + * @param {PIXI.Texture} texture - the new texture + * @param {number} location - the suggested texture location + * @param {boolean} forceLocation - force the location + * @return {number} bound texture location + */ + + + WebGLRenderer.prototype.bindTexture = function bindTexture(texture, location, forceLocation) { + texture = texture || this.emptyTextures[location]; + texture = texture.baseTexture || texture; + texture.touched = this.textureGC.count; + + if (!forceLocation) { + // TODO - maybe look into adding boundIds.. save us the loop? + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + return i; + } + } + + if (location === undefined) { + this._nextTextureLocation++; + this._nextTextureLocation %= this.boundTextures.length; + location = this.boundTextures.length - this._nextTextureLocation - 1; + } + } else { + location = location || 0; + } + + var gl = this.gl; + var glTexture = texture._glTextures[this.CONTEXT_UID]; + + if (!glTexture) { + // this will also bind the texture.. + this.textureManager.updateTexture(texture, location); + } else { + // bind the current texture + this.boundTextures[location] = texture; + gl.activeTexture(gl.TEXTURE0 + location); + gl.bindTexture(gl.TEXTURE_2D, glTexture.texture); + } + + return location; + }; + + /** + * unbinds the texture ... + * + * @param {PIXI.Texture} texture - the texture to unbind + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.unbindTexture = function unbindTexture(texture) { + var gl = this.gl; + + texture = texture.baseTexture || texture; + + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + this.boundTextures[i] = this.emptyTextures[i]; + + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[i]._glTextures[this.CONTEXT_UID].texture); + } + } + + return this; + }; + + /** + * Creates a new VAO from this renderer's context and state. + * + * @return {VertexArrayObject} The new VAO. + */ + + + WebGLRenderer.prototype.createVao = function createVao() { + return new _pixiGlCore2.default.VertexArrayObject(this.gl, this.state.attribState); + }; + + /** + * Changes the current Vao to the one given in parameter + * + * @param {PIXI.VertexArrayObject} vao - the new Vao + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindVao = function bindVao(vao) { + if (this._activeVao === vao) { + return this; + } + + if (vao) { + vao.bind(); + } else if (this._activeVao) { + // TODO this should always be true i think? + this._activeVao.unbind(); + } + + this._activeVao = vao; + + return this; + }; + + /** + * Resets the WebGL state so you can render things however you fancy! + * + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.reset = function reset() { + this.setObjectRenderer(this.emptyRenderer); + + this._activeShader = null; + this._activeRenderTarget = this.rootRenderTarget; + + // bind the main frame buffer (the screen); + this.rootRenderTarget.activate(); + + this.state.resetToDefault(); + + return this; + }; + + /** + * Handles a lost webgl context + * + * @private + * @param {WebGLContextEvent} event - The context lost event. + */ + + + WebGLRenderer.prototype.handleContextLost = function handleContextLost(event) { + event.preventDefault(); + }; + + /** + * Handles a restored webgl context + * + * @private + */ + + + WebGLRenderer.prototype.handleContextRestored = function handleContextRestored() { + this.textureManager.removeAll(); + this._initContext(); + }; + + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + + + WebGLRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // remove listeners + this.view.removeEventListener('webglcontextlost', this.handleContextLost); + this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); + + this.textureManager.destroy(); + + // call base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.uid = 0; + + // destroy the managers + this.maskManager.destroy(); + this.stencilManager.destroy(); + this.filterManager.destroy(); + + this.maskManager = null; + this.filterManager = null; + this.textureManager = null; + this.currentRenderer = null; + + this.handleContextLost = null; + this.handleContextRestored = null; + + this._contextOptions = null; + this.gl.useProgram(null); + + if (this.gl.getExtension('WEBGL_lose_context')) { + this.gl.getExtension('WEBGL_lose_context').loseContext(); + } + + this.gl = null; + + // this = null; + }; + + return WebGLRenderer; +}(_SystemRenderer3.default); + +/** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @name PIXI.WebGLRenderer#plugins + * @type {object} + * @readonly + * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.extract.WebGLExtract} extract Extract image data from renderer. + * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.prepare.WebGLPrepare} prepare Pre-render display objects. + */ + +/** + * Adds a plugin to the renderer. + * + * @method PIXI.WebGLRenderer#registerPlugin + * @param {string} pluginName - The name of the plugin. + * @param {Function} ctor - The constructor function or class for the plugin. + */ + +exports.default = WebGLRenderer; +_utils.pluginTarget.mixin(WebGLRenderer); + +},{"../../const":45,"../../textures/BaseTexture":111,"../../utils":123,"../SystemRenderer":75,"./TextureGarbageCollector":81,"./TextureManager":82,"./WebGLState":84,"./managers/FilterManager":89,"./managers/MaskManager":90,"./managers/StencilManager":91,"./utils/ObjectRenderer":93,"./utils/RenderTarget":95,"./utils/mapWebGLDrawModesToPixi":98,"./utils/validateContext":99,"pixi-gl-core":12}],84:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); + +var _mapWebGLBlendModesToPixi2 = _interopRequireDefault(_mapWebGLBlendModesToPixi); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var BLEND = 0; +var DEPTH_TEST = 1; +var FRONT_FACE = 2; +var CULL_FACE = 3; +var BLEND_FUNC = 4; + +/** + * A WebGL state machines + * + * @memberof PIXI + * @class + */ + +var WebGLState = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + */ + function WebGLState(gl) { + _classCallCheck(this, WebGLState); + + /** + * The current active state + * + * @member {Uint8Array} + */ + this.activeState = new Uint8Array(16); + + /** + * The default state + * + * @member {Uint8Array} + */ + this.defaultState = new Uint8Array(16); + + // default blend mode.. + this.defaultState[0] = 1; + + /** + * The current state index in the stack + * + * @member {number} + * @private + */ + this.stackIndex = 0; + + /** + * The stack holding all the different states + * + * @member {Array<*>} + * @private + */ + this.stack = []; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + this.attribState = { + tempAttribState: new Array(this.maxAttribs), + attribState: new Array(this.maxAttribs) + }; + + this.blendModes = (0, _mapWebGLBlendModesToPixi2.default)(gl); + + // check we have vao.. + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || gl.getExtension('MOZ_OES_vertex_array_object') || gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + /** + * Pushes a new active state + */ + + + WebGLState.prototype.push = function push() { + // next state.. + var state = this.stack[this.stackIndex]; + + if (!state) { + state = this.stack[this.stackIndex] = new Uint8Array(16); + } + + ++this.stackIndex; + + // copy state.. + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) { + state[i] = this.activeState[i]; + } + }; + + /** + * Pops a state out + */ + + + WebGLState.prototype.pop = function pop() { + var state = this.stack[--this.stackIndex]; + + this.setState(state); + }; + + /** + * Sets the current state + * + * @param {*} state - The state to set. + */ + + + WebGLState.prototype.setState = function setState(state) { + this.setBlend(state[BLEND]); + this.setDepthTest(state[DEPTH_TEST]); + this.setFrontFace(state[FRONT_FACE]); + this.setCullFace(state[CULL_FACE]); + this.setBlendMode(state[BLEND_FUNC]); + }; + + /** + * Enables or disabled blending. + * + * @param {boolean} value - Turn on or off webgl blending. + */ + + + WebGLState.prototype.setBlend = function setBlend(value) { + value = value ? 1 : 0; + + if (this.activeState[BLEND] === value) { + return; + } + + this.activeState[BLEND] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + }; + + /** + * Sets the blend mode. + * + * @param {number} value - The blend mode to set to. + */ + + + WebGLState.prototype.setBlendMode = function setBlendMode(value) { + if (value === this.activeState[BLEND_FUNC]) { + return; + } + + this.activeState[BLEND_FUNC] = value; + + var mode = this.blendModes[value]; + + if (mode.length === 2) { + this.gl.blendFunc(mode[0], mode[1]); + } else { + this.gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); + } + }; + + /** + * Sets whether to enable or disable depth test. + * + * @param {boolean} value - Turn on or off webgl depth testing. + */ + + + WebGLState.prototype.setDepthTest = function setDepthTest(value) { + value = value ? 1 : 0; + + if (this.activeState[DEPTH_TEST] === value) { + return; + } + + this.activeState[DEPTH_TEST] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + }; + + /** + * Sets whether to enable or disable cull face. + * + * @param {boolean} value - Turn on or off webgl cull face. + */ + + + WebGLState.prototype.setCullFace = function setCullFace(value) { + value = value ? 1 : 0; + + if (this.activeState[CULL_FACE] === value) { + return; + } + + this.activeState[CULL_FACE] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + }; + + /** + * Sets the gl front face. + * + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ + + + WebGLState.prototype.setFrontFace = function setFrontFace(value) { + value = value ? 1 : 0; + + if (this.activeState[FRONT_FACE] === value) { + return; + } + + this.activeState[FRONT_FACE] = value; + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); + }; + + /** + * Disables all the vaos in use + * + */ + + + WebGLState.prototype.resetAttributes = function resetAttributes() { + for (var i = 0; i < this.attribState.tempAttribState.length; i++) { + this.attribState.tempAttribState[i] = 0; + } + + for (var _i = 0; _i < this.attribState.attribState.length; _i++) { + this.attribState.attribState[_i] = 0; + } + + // im going to assume one is always active for performance reasons. + for (var _i2 = 1; _i2 < this.maxAttribs; _i2++) { + this.gl.disableVertexAttribArray(_i2); + } + }; + + // used + /** + * Resets all the logic and disables the vaos + */ + + + WebGLState.prototype.resetToDefault = function resetToDefault() { + // unbind any VAO if they exist.. + if (this.nativeVaoExtension) { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + // reset all attributes.. + this.resetAttributes(); + + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; ++i) { + this.activeState[i] = 32; + } + + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + + this.setState(this.defaultState); + }; + + return WebGLState; +}(); + +exports.default = WebGLState; + +},{"./utils/mapWebGLBlendModesToPixi":97}],85:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _extractUniformsFromSrc = require('./extractUniformsFromSrc'); + +var _extractUniformsFromSrc2 = _interopRequireDefault(_extractUniformsFromSrc); + +var _utils = require('../../../utils'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SOURCE_KEY_MAP = {}; + +// let math = require('../../../math'); +/** + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ + +var Filter = function () { + /** + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. + */ + function Filter(vertexSrc, fragmentSrc, uniforms) { + _classCallCheck(this, Filter); + + /** + * The vertex shader. + * + * @member {string} + */ + this.vertexSrc = vertexSrc || Filter.defaultVertexSrc; + + /** + * The fragment shader. + * + * @member {string} + */ + this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc; + + this.blendMode = _const.BLEND_MODES.NORMAL; + + this.uniformData = uniforms || (0, _extractUniformsFromSrc2.default)(this.vertexSrc, this.fragmentSrc, 'projectionMatrix|uSampler'); + + /** + * An object containing the current values of custom uniforms. + * @example Updating the value of a custom uniform + * filter.uniforms.time = performance.now(); + * + * @member {object} + */ + this.uniforms = {}; + + for (var i in this.uniformData) { + this.uniforms[i] = this.uniformData[i].value; + } + + // this is where we store shader references.. + // TODO we could cache this! + this.glShaders = {}; + + // used for cacheing.. sure there is a better way! + if (!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) { + SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = (0, _utils.uid)(); + } + + this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]; + + /** + * The padding of the filter. Some filters require extra space to breath such as a blur. + * Increasing this will add extra width and height to the bounds of the object that the + * filter is applied to. + * + * @member {number} + */ + this.padding = 4; + + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + * + * @member {number} + */ + this.resolution = _settings2.default.RESOLUTION; + + /** + * If enabled is true the filter is applied, if false it will not. + * + * @member {boolean} + */ + this.enabled = true; + + /** + * If enabled, pixi will fit the filter area into boundaries for better performance. + * Switch it off if it does not work for specific shader. + * + * @member {boolean} + */ + this.autoFit = true; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + * @param {object} [currentState] - It's current state of filter. + * There are some useful properties in the currentState : + * target, filters, sourceFrame, destinationFrame, renderTarget, resolution + */ + + + Filter.prototype.apply = function apply(filterManager, input, output, clear, currentState) // eslint-disable-line no-unused-vars + { + // --- // + // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); + + // do as you please! + + filterManager.applyFilter(this, input, output, clear); + + // or just do a regular render.. + }; + + /** + * The default vertex shader source + * + * @static + * @constant + */ + + + _createClass(Filter, null, [{ + key: 'defaultVertexSrc', + get: function get() { + return ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform mat3 projectionMatrix;', 'uniform mat3 filterMatrix;', 'varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;', ' vTextureCoord = aTextureCoord ;', '}'].join('\n'); + } + + /** + * The default fragment shader source + * + * @static + * @constant + */ + + }, { + key: 'defaultFragmentSrc', + get: function get() { + return ['varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'uniform sampler2D uSampler;', 'uniform sampler2D filterSampler;', 'void main(void){', ' vec4 masky = texture2D(filterSampler, vFilterCoord);', ' vec4 sample = texture2D(uSampler, vTextureCoord);', ' vec4 color;', ' if(mod(vFilterCoord.x, 1.0) > 0.5)', ' {', ' color = vec4(1.0, 0.0, 0.0, 1.0);', ' }', ' else', ' {', ' color = vec4(0.0, 1.0, 0.0, 1.0);', ' }', + // ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', + ' gl_FragColor = mix(sample, masky, 0.5);', ' gl_FragColor *= sample.a;', '}'].join('\n'); + } + }]); + + return Filter; +}(); + +exports.default = Filter; + +},{"../../../const":45,"../../../settings":100,"../../../utils":123,"./extractUniformsFromSrc":86}],86:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = extractUniformsFromSrc; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var defaultValue = _pixiGlCore2.default.shader.defaultValue; + +function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) { + var vertUniforms = extractUniformsFromString(vertexSrc, mask); + var fragUniforms = extractUniformsFromString(fragmentSrc, mask); + + return Object.assign(vertUniforms, fragUniforms); +} + +function extractUniformsFromString(string) { + var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea|filterClamp)$'); + + var uniforms = {}; + var nameSplit = void 0; + + // clean the lines a little - remove extra spaces / tabs etc + // then split along ';' + var lines = string.replace(/\s+/g, ' ').split(/\s*;\s*/); + + // loop through.. + for (var i = 0; i < lines.length; i++) { + var line = lines[i].trim(); + + if (line.indexOf('uniform') > -1) { + var splitLine = line.split(' '); + var type = splitLine[1]; + + var name = splitLine[2]; + var size = 1; + + if (name.indexOf('[') > -1) { + // array! + nameSplit = name.split(/\[|]/); + name = nameSplit[0]; + size *= Number(nameSplit[1]); + } + + if (!name.match(maskRegex)) { + uniforms[name] = { + value: defaultValue(type, size), + name: name, + type: type + }; + } + } + } + + return uniforms; +} + +},{"pixi-gl-core":12}],87:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.calculateScreenSpaceMatrix = calculateScreenSpaceMatrix; +exports.calculateNormalizedScreenSpaceMatrix = calculateNormalizedScreenSpaceMatrix; +exports.calculateSpriteMatrix = calculateSpriteMatrix; + +var _math = require('../../../math'); + +/** + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// this returns a matrix that will normalise map filter cords in the filter to screen space +function calculateScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + // let worldTransform = sprite.worldTransform.copy(Matrix.TEMP_MATRIX), + // let texture = {width:1136, height:700};//sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(textureSize.width, textureSize.height); + + return mappedMatrix; +} + +function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + var translateScaleX = textureSize.width / filterArea.width; + var translateScaleY = textureSize.height / filterArea.height; + + mappedMatrix.scale(translateScaleX, translateScaleY); + + return mappedMatrix; +} + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +function calculateSpriteMatrix(outputMatrix, filterArea, textureSize, sprite) { + var worldTransform = sprite.worldTransform.copy(_math.Matrix.TEMP_MATRIX); + var texture = sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + // scale.. + var ratio = textureSize.height / textureSize.width; + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(1, ratio); + + var translateScaleX = textureSize.width / texture.width; + var translateScaleY = textureSize.height / texture.height; + + worldTransform.tx /= texture.width * translateScaleX; + + // this...? free beer for anyone who can explain why this makes sense! + worldTransform.ty /= texture.width * translateScaleX; + // worldTransform.ty /= texture.height * translateScaleY; + + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + + // apply inverse scale.. + mappedMatrix.scale(1, 1 / ratio); + + mappedMatrix.scale(translateScaleX, translateScaleY); + + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; +} + +},{"../../../math":69}],88:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Filter2 = require('../Filter'); + +var _Filter3 = _interopRequireDefault(_Filter2); + +var _math = require('../../../../math'); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The SpriteMaskFilter class + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + */ +var SpriteMaskFilter = function (_Filter) { + _inherits(SpriteMaskFilter, _Filter); + + /** + * @param {PIXI.Sprite} sprite - the target sprite + */ + function SpriteMaskFilter(sprite) { + _classCallCheck(this, SpriteMaskFilter); + + var maskMatrix = new _math.Matrix(); + + var _this = _possibleConstructorReturn(this, _Filter.call(this, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n', 'varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n')); + + sprite.renderable = false; + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + return _this; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + */ + + + SpriteMaskFilter.prototype.apply = function apply(filterManager, input, output) { + var maskSprite = this.maskSprite; + + this.uniforms.mask = maskSprite._texture; + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite); + this.uniforms.alpha = maskSprite.worldAlpha; + + filterManager.applyFilter(this, input, output); + }; + + return SpriteMaskFilter; +}(_Filter3.default); + +exports.default = SpriteMaskFilter; + +},{"../../../../math":69,"../Filter":85,"path":22}],89:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _RenderTarget = require('../utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _Quad = require('../utils/Quad'); + +var _Quad2 = _interopRequireDefault(_Quad); + +var _math = require('../../../math'); + +var _Shader = require('../../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _filterTransforms = require('../filters/filterTransforms'); + +var filterTransforms = _interopRequireWildcard(_filterTransforms); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @ignore + * @class + */ +var FilterState = +/** + * + */ +function FilterState() { + _classCallCheck(this, FilterState); + + this.renderTarget = null; + this.sourceFrame = new _math.Rectangle(); + this.destinationFrame = new _math.Rectangle(); + this.filters = []; + this.target = null; + this.resolution = 1; +}; + +/** + * @class + * @memberof PIXI + * @extends PIXI.WebGLManager + */ + + +var FilterManager = function (_WebGLManager) { + _inherits(FilterManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function FilterManager(renderer) { + _classCallCheck(this, FilterManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.gl = _this.renderer.gl; + // know about sprites! + _this.quad = new _Quad2.default(_this.gl, renderer.state.attribState); + + _this.shaderCache = {}; + // todo add default! + _this.pool = {}; + + _this.filterData = null; + return _this; + } + + /** + * Adds a new filter to the manager. + * + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param {PIXI.Filter[]} filters - The filters to apply. + */ + + + FilterManager.prototype.pushFilter = function pushFilter(target, filters) { + var renderer = this.renderer; + + var filterData = this.filterData; + + if (!filterData) { + filterData = this.renderer._activeRenderTarget.filterStack; + + // add new stack + var filterState = new FilterState(); + + filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; + filterState.renderTarget = renderer._activeRenderTarget; + + this.renderer._activeRenderTarget.filterData = filterData = { + index: 0, + stack: [filterState] + }; + + this.filterData = filterData; + } + + // get the current filter state.. + var currentState = filterData.stack[++filterData.index]; + + if (!currentState) { + currentState = filterData.stack[filterData.index] = new FilterState(); + } + + // for now we go off the filter of the first resolution.. + var resolution = filters[0].resolution; + var padding = filters[0].padding | 0; + var targetBounds = target.filterArea || target.getBounds(true); + var sourceFrame = currentState.sourceFrame; + var destinationFrame = currentState.destinationFrame; + + sourceFrame.x = (targetBounds.x * resolution | 0) / resolution; + sourceFrame.y = (targetBounds.y * resolution | 0) / resolution; + sourceFrame.width = (targetBounds.width * resolution | 0) / resolution; + sourceFrame.height = (targetBounds.height * resolution | 0) / resolution; + + if (filterData.stack[0].renderTarget.transform) {// + + // TODO we should fit the rect around the transform.. + } else if (filters[0].autoFit) { + sourceFrame.fit(filterData.stack[0].destinationFrame); + } + + // lets apply the padding After we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + sourceFrame.pad(padding); + + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + + // lets play the padding after we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + + var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); + + currentState.target = target; + currentState.filters = filters; + currentState.resolution = resolution; + currentState.renderTarget = renderTarget; + + // bind the render target to draw the shape in the top corner.. + + renderTarget.setFrame(destinationFrame, sourceFrame); + + // bind the render target + renderer.bindRenderTarget(renderTarget); + renderTarget.clear(); + }; + + /** + * Pops off the filter and applies it. + * + */ + + + FilterManager.prototype.popFilter = function popFilter() { + var filterData = this.filterData; + + var lastState = filterData.stack[filterData.index - 1]; + var currentState = filterData.stack[filterData.index]; + + this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); + + var filters = currentState.filters; + + if (filters.length === 1) { + filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false, currentState); + this.freePotRenderTarget(currentState.renderTarget); + } else { + var flip = currentState.renderTarget; + var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, currentState.resolution); + + flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + // finally lets clear the render target before drawing to it.. + flop.clear(); + + var i = 0; + + for (i = 0; i < filters.length - 1; ++i) { + filters[i].apply(this, flip, flop, true, currentState); + + var t = flip; + + flip = flop; + flop = t; + } + + filters[i].apply(this, flip, lastState.renderTarget, false, currentState); + + this.freePotRenderTarget(flip); + this.freePotRenderTarget(flop); + } + + filterData.index--; + + if (filterData.index === 0) { + this.filterData = null; + } + }; + + /** + * Draws a filter. + * + * @param {PIXI.Filter} filter - The filter to draw. + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + FilterManager.prototype.applyFilter = function applyFilter(filter, input, output, clear) { + var renderer = this.renderer; + var gl = renderer.gl; + + var shader = filter.glShaders[renderer.CONTEXT_UID]; + + // cacheing.. + if (!shader) { + if (filter.glShaderKey) { + shader = this.shaderCache[filter.glShaderKey]; + + if (!shader) { + shader = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + + filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = shader; + } + } else { + shader = filter.glShaders[renderer.CONTEXT_UID] = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + } + + // TODO - this only needs to be done once? + renderer.bindVao(null); + + this.quad.initVao(shader); + } + + renderer.bindVao(this.quad.vao); + + renderer.bindRenderTarget(output); + + if (clear) { + gl.disable(gl.SCISSOR_TEST); + renderer.clear(); // [1, 1, 1, 1]); + gl.enable(gl.SCISSOR_TEST); + } + + // in case the render target is being masked using a scissor rect + if (output === renderer.maskManager.scissorRenderTarget) { + renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); + } + + renderer.bindShader(shader); + + // free unit 0 for us, doesn't matter what was there + // don't try to restore it, because syncUniforms can upload it to another slot + // and it'll be a problem + var tex = this.renderer.emptyTextures[0]; + + this.renderer.boundTextures[0] = tex; + // this syncs the pixi filters uniforms with glsl uniforms + this.syncUniforms(shader, filter); + + renderer.state.setBlendMode(filter.blendMode); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, input.texture.texture); + + this.quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + }; + + /** + * Uploads the uniforms of the filter. + * + * @param {GLShader} shader - The underlying gl shader. + * @param {PIXI.Filter} filter - The filter we are synchronizing. + */ + + + FilterManager.prototype.syncUniforms = function syncUniforms(shader, filter) { + var uniformData = filter.uniformData; + var uniforms = filter.uniforms; + + // 0 is reserved for the pixi texture so we start at 1! + var textureCount = 1; + var currentState = void 0; + + // filterArea and filterClamp that are handled by FilterManager directly + // they must not appear in uniformData + + if (shader.uniforms.filterArea) { + currentState = this.filterData.stack[this.filterData.index]; + + var filterArea = shader.uniforms.filterArea; + + filterArea[0] = currentState.renderTarget.size.width; + filterArea[1] = currentState.renderTarget.size.height; + filterArea[2] = currentState.sourceFrame.x; + filterArea[3] = currentState.sourceFrame.y; + + shader.uniforms.filterArea = filterArea; + } + + // use this to clamp displaced texture coords so they belong to filterArea + // see displacementFilter fragment shader for an example + if (shader.uniforms.filterClamp) { + currentState = currentState || this.filterData.stack[this.filterData.index]; + + var filterClamp = shader.uniforms.filterClamp; + + filterClamp[0] = 0; + filterClamp[1] = 0; + filterClamp[2] = (currentState.sourceFrame.width - 1) / currentState.renderTarget.size.width; + filterClamp[3] = (currentState.sourceFrame.height - 1) / currentState.renderTarget.size.height; + + shader.uniforms.filterClamp = filterClamp; + } + + // TODO Cacheing layer.. + for (var i in uniformData) { + if (uniformData[i].type === 'sampler2D' && uniforms[i] !== 0) { + if (uniforms[i].baseTexture) { + shader.uniforms[i] = this.renderer.bindTexture(uniforms[i].baseTexture, textureCount); + } else { + shader.uniforms[i] = textureCount; + + // TODO + // this is helpful as renderTargets can also be set. + // Although thinking about it, we could probably + // make the filter texture cache return a RenderTexture + // rather than a renderTarget + var gl = this.renderer.gl; + + this.renderer.boundTextures[textureCount] = this.renderer.emptyTextures[textureCount]; + gl.activeTexture(gl.TEXTURE0 + textureCount); + + uniforms[i].texture.bind(); + } + + textureCount++; + } else if (uniformData[i].type === 'mat3') { + // check if its pixi matrix.. + if (uniforms[i].a !== undefined) { + shader.uniforms[i] = uniforms[i].toArray(true); + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (uniformData[i].type === 'vec2') { + // check if its a point.. + if (uniforms[i].x !== undefined) { + var val = shader.uniforms[i] || new Float32Array(2); + + val[0] = uniforms[i].x; + val[1] = uniforms[i].y; + shader.uniforms[i] = val; + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (uniformData[i].type === 'float') { + if (shader.uniforms.data[i].value !== uniformData[i]) { + shader.uniforms[i] = uniforms[i]; + } + } else { + shader.uniforms[i] = uniforms[i]; + } + } + }; + + /** + * Gets a render target from the pool, or creates a new one. + * + * @param {boolean} clear - Should we clear the render texture when we get it? + * @param {number} resolution - The resolution of the target. + * @return {PIXI.RenderTarget} The new render target + */ + + + FilterManager.prototype.getRenderTarget = function getRenderTarget(clear, resolution) { + var currentState = this.filterData.stack[this.filterData.index]; + var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution); + + renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + return renderTarget; + }; + + /** + * Returns a render target to the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The render target to return. + */ + + + FilterManager.prototype.returnRenderTarget = function returnRenderTarget(renderTarget) { + this.freePotRenderTarget(renderTarget); + }; + + /** + * Calculates the mapped matrix. + * + * TODO playing around here.. this is temporary - (will end up in the shader) + * this returns a matrix that will normalise map filter cords in the filter to screen space + * + * @param {PIXI.Matrix} outputMatrix - the matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateScreenSpaceMatrix = function calculateScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); + }; + + /** + * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function calculateNormalizedScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); + }; + + /** + * This will map the filter coord so that a texture can be used based on the transform of a sprite + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateSpriteMatrix = function calculateSpriteMatrix(outputMatrix, sprite) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); + }; + + /** + * Destroys this Filter Manager. + * + */ + + + FilterManager.prototype.destroy = function destroy() { + this.shaderCache = {}; + this.emptyPool(); + }; + + /** + * Gets a Power-of-Two render texture. + * + * TODO move to a seperate class could be on renderer? + * also - could cause issue with multiple contexts? + * + * @private + * @param {WebGLRenderingContext} gl - The webgl rendering context + * @param {number} minWidth - The minimum width of the render target. + * @param {number} minHeight - The minimum height of the render target. + * @param {number} resolution - The resolution of the render target. + * @return {PIXI.RenderTarget} The new render target. + */ + + + FilterManager.prototype.getPotRenderTarget = function getPotRenderTarget(gl, minWidth, minHeight, resolution) { + // TODO you could return a bigger texture if there is not one in the pool? + minWidth = _bitTwiddle2.default.nextPow2(minWidth * resolution); + minHeight = _bitTwiddle2.default.nextPow2(minHeight * resolution); + + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + if (!this.pool[key]) { + this.pool[key] = []; + } + + var renderTarget = this.pool[key].pop(); + + // creating render target will cause texture to be bound! + if (!renderTarget) { + // temporary bypass cache.. + var tex = this.renderer.boundTextures[0]; + + gl.activeTexture(gl.TEXTURE0); + + // internally - this will cause a texture to be bound.. + renderTarget = new _RenderTarget2.default(gl, minWidth, minHeight, null, 1); + + // set the current one back + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + } + + // manually tweak the resolution... + // this will not modify the size of the frame buffer, just its resolution. + renderTarget.resolution = resolution; + renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution; + renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution; + + return renderTarget; + }; + + /** + * Empties the texture pool. + * + */ + + + FilterManager.prototype.emptyPool = function emptyPool() { + for (var i in this.pool) { + var textures = this.pool[i]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + + this.pool = {}; + }; + + /** + * Frees a render target back into the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free + */ + + + FilterManager.prototype.freePotRenderTarget = function freePotRenderTarget(renderTarget) { + var minWidth = renderTarget.size.width * renderTarget.resolution; + var minHeight = renderTarget.size.height * renderTarget.resolution; + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + this.pool[key].push(renderTarget); + }; + + return FilterManager; +}(_WebGLManager3.default); + +exports.default = FilterManager; + +},{"../../../Shader":43,"../../../math":69,"../filters/filterTransforms":87,"../utils/Quad":94,"../utils/RenderTarget":95,"./WebGLManager":92,"bit-twiddle":1}],90:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _SpriteMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); + +var _SpriteMaskFilter2 = _interopRequireDefault(_SpriteMaskFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var MaskManager = function (_WebGLManager) { + _inherits(MaskManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function MaskManager(renderer) { + _classCallCheck(this, MaskManager); + + // TODO - we don't need both! + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.scissor = false; + _this.scissorData = null; + _this.scissorRenderTarget = null; + + _this.enableScissor = true; + + _this.alphaMaskPool = []; + _this.alphaMaskIndex = 0; + return _this; + } + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushMask = function pushMask(target, maskData) { + // TODO the root check means scissor rect will not + // be used on render textures more info here: + // https://github.com/pixijs/pixi.js/pull/3545 + + if (maskData.texture) { + this.pushSpriteMask(target, maskData); + } else if (this.enableScissor && !this.scissor && this.renderer._activeRenderTarget.root && !this.renderer.stencilManager.stencilMaskStack.length && maskData.isFastRect()) { + var matrix = maskData.worldTransform; + + var rot = Math.atan2(matrix.b, matrix.a); + + // use the nearest degree! + rot = Math.round(rot * (180 / Math.PI)); + + if (rot % 90) { + this.pushStencilMask(maskData); + } else { + this.pushScissorMask(target, maskData); + } + } else { + this.pushStencilMask(maskData); + } + }; + + /** + * Removes the last mask from the mask stack and doesn't return it. + * + * @param {PIXI.DisplayObject} target - Display Object to pop the mask from + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.popMask = function popMask(target, maskData) { + if (maskData.texture) { + this.popSpriteMask(target, maskData); + } else if (this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length) { + this.popScissorMask(target, maskData); + } else { + this.popStencilMask(target, maskData); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.RenderTarget} target - Display Object to push the sprite mask to + * @param {PIXI.Sprite} maskData - Sprite to be used as the mask + */ + + + MaskManager.prototype.pushSpriteMask = function pushSpriteMask(target, maskData) { + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new _SpriteMaskFilter2.default(maskData)]; + } + + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskData; + + // TODO - may cause issues! + target.filterArea = maskData.getBounds(true); + + this.renderer.filterManager.pushFilter(target, alphaMaskFilter); + + this.alphaMaskIndex++; + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popSpriteMask = function popSpriteMask() { + this.renderer.filterManager.popFilter(); + this.alphaMaskIndex--; + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushStencilMask = function pushStencilMask(maskData) { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.pushStencil(maskData); + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popStencilMask = function popStencilMask() { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.popStencil(); + }; + + /** + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushScissorMask = function pushScissorMask(target, maskData) { + maskData.renderable = true; + + var renderTarget = this.renderer._activeRenderTarget; + + var bounds = maskData.getBounds(); + + bounds.fit(renderTarget.size); + maskData.renderable = false; + + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + + var resolution = this.renderer.resolution; + + this.renderer.gl.scissor(bounds.x * resolution, (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution, bounds.width * resolution, bounds.height * resolution); + + this.scissorRenderTarget = renderTarget; + this.scissorData = maskData; + this.scissor = true; + }; + + /** + * + * + */ + + + MaskManager.prototype.popScissorMask = function popScissorMask() { + this.scissorRenderTarget = null; + this.scissorData = null; + this.scissor = false; + + // must be scissor! + var gl = this.renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + }; + + return MaskManager; +}(_WebGLManager3.default); + +exports.default = MaskManager; + +},{"../filters/spriteMask/SpriteMaskFilter":88,"./WebGLManager":92}],91:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var StencilManager = function (_WebGLManager) { + _inherits(StencilManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function StencilManager(renderer) { + _classCallCheck(this, StencilManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.stencilMaskStack = null; + return _this; + } + + /** + * Changes the mask stack that is used by this manager. + * + * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack + */ + + + StencilManager.prototype.setMaskStack = function setMaskStack(stencilMaskStack) { + this.stencilMaskStack = stencilMaskStack; + + var gl = this.renderer.gl; + + if (stencilMaskStack.length === 0) { + gl.disable(gl.STENCIL_TEST); + } else { + gl.enable(gl.STENCIL_TEST); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. @alvin + * + * @param {PIXI.Graphics} graphics - The mask + */ + + + StencilManager.prototype.pushStencil = function pushStencil(graphics) { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + this.renderer._activeRenderTarget.attachStencilBuffer(); + + var gl = this.renderer.gl; + var sms = this.stencilMaskStack; + + if (sms.length === 0) { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.stencilFunc(gl.ALWAYS, 1, 1); + } + + sms.push(graphics); + + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; + + /** + * TODO @alvin + */ + + + StencilManager.prototype.popStencil = function popStencil() { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + var gl = this.renderer.gl; + var sms = this.stencilMaskStack; + + var graphics = sms.pop(); + + if (sms.length === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + } else { + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + } + }; + + /** + * Destroys the mask stack. + * + */ + + + StencilManager.prototype.destroy = function destroy() { + _WebGLManager3.default.prototype.destroy.call(this); + + this.stencilMaskStack.stencilStack = null; + }; + + return StencilManager; +}(_WebGLManager3.default); + +exports.default = StencilManager; + +},{"./WebGLManager":92}],92:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var WebGLManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function WebGLManager(renderer) { + _classCallCheck(this, WebGLManager); + + /** + * The renderer this manager works for. + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + this.renderer.on('context', this.onContextChange, this); + } + + /** + * Generic method called when there is a WebGL context change. + * + */ + + + WebGLManager.prototype.onContextChange = function onContextChange() {} + // do some codes init! + + + /** + * Generic destroy methods to be overridden by the subclass + * + */ + ; + + WebGLManager.prototype.destroy = function destroy() { + this.renderer.off('context', this.onContextChange, this); + + this.renderer = null; + }; + + return WebGLManager; +}(); + +exports.default = WebGLManager; + +},{}],93:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('../managers/WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Base for a common object renderer that can be used as a system renderer plugin. + * + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var ObjectRenderer = function (_WebGLManager) { + _inherits(ObjectRenderer, _WebGLManager); + + function ObjectRenderer() { + _classCallCheck(this, ObjectRenderer); + + return _possibleConstructorReturn(this, _WebGLManager.apply(this, arguments)); + } + + /** + * Starts the renderer and sets the shader + * + */ + ObjectRenderer.prototype.start = function start() {} + // set the shader.. + + + /** + * Stops the renderer + * + */ + ; + + ObjectRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Stub method for rendering content and emptying the current batch. + * + */ + + + ObjectRenderer.prototype.flush = function flush() {} + // flush! + + + /** + * Renders an object + * + * @param {PIXI.DisplayObject} object - The object to render. + */ + ; + + ObjectRenderer.prototype.render = function render(object) // eslint-disable-line no-unused-vars + { + // render the object + }; + + return ObjectRenderer; +}(_WebGLManager3.default); + +exports.default = ObjectRenderer; + +},{"../managers/WebGLManager":92}],94:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a quad + * + * @class + * @memberof PIXI + */ +var Quad = function () { + /** + * @param {WebGLRenderingContext} gl - The gl context for this quad to use. + * @param {object} state - TODO: Description + */ + function Quad(gl, state) { + _classCallCheck(this, Quad); + + /** + * the current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]); + + /** + * The Uvs of the quad + * + * @member {Float32Array} + */ + this.uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + this.interleaved = new Float32Array(8 * 2); + + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(1); + + /** + * The vertex buffer + * + * @member {glCore.GLBuffer} + */ + this.vertexBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW); + + /** + * The index buffer + * + * @member {glCore.GLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + /** + * The vertex array object + * + * @member {glCore.VertexArrayObject} + */ + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, state); + } + + /** + * Initialises the vaos and uses the shader. + * + * @param {PIXI.Shader} shader - the shader to use + */ + + + Quad.prototype.initVao = function initVao(shader) { + this.vao.clear().addIndex(this.indexBuffer).addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0).addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4); + }; + + /** + * Maps two Rectangle to the quad. + * + * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle + * @param {PIXI.Rectangle} destinationFrame - the second rectangle + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.map = function map(targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + + this.uvs[0] = x; + this.uvs[1] = y; + + this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; + + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; + + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; + + x = destinationFrame.x; + y = destinationFrame.y; + + this.vertices[0] = x; + this.vertices[1] = y; + + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + + return this; + }; + + /** + * Binds the buffer and uploads the data + * + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.upload = function upload() { + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + this.vertexBuffer.upload(this.interleaved); + + return this; + }; + + /** + * Removes this quad from WebGL + */ + + + Quad.prototype.destroy = function destroy() { + var gl = this.gl; + + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.indexBuffer); + }; + + return Quad; +}(); + +exports.default = Quad; + +},{"../../../utils/createIndicesForQuads":121,"pixi-gl-core":12}],95:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../../../math'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _pixiGlCore = require('pixi-gl-core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var RenderTarget = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {number} [width=0] - the horizontal range of the filter + * @param {number} [height=0] - the vertical range of the filter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The current resolution / device pixel ratio + * @param {boolean} [root=false] - Whether this object is the root element or not + */ + function RenderTarget(gl, width, height, scaleMode, resolution, root) { + _classCallCheck(this, RenderTarget); + + // TODO Resolution could go here ( eg low res blurs ) + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // next time to create a frame buffer and texture + + /** + * A frame buffer + * + * @member {PIXI.glCore.GLFramebuffer} + */ + this.frameBuffer = null; + + /** + * The texture + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The background colour of this render target, as an array of [r,g,b,a] values + * + * @member {number[]} + */ + this.clearColor = [0, 0, 0, 0]; + + /** + * The size of the object as a rectangle + * + * @member {PIXI.Rectangle} + */ + this.size = new _math.Rectangle(0, 0, 1, 1); + + /** + * The current resolution / device pixel ratio + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The projection matrix + * + * @member {PIXI.Matrix} + */ + this.projectionMatrix = new _math.Matrix(); + + /** + * The object's transform + * + * @member {PIXI.Matrix} + */ + this.transform = null; + + /** + * The frame. + * + * @member {PIXI.Rectangle} + */ + this.frame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.defaultFrame = new _math.Rectangle(); + this.destinationFrame = null; + this.sourceFrame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.stencilBuffer = null; + + /** + * The data structure for the stencil masks + * + * @member {PIXI.Graphics[]} + */ + this.stencilMaskStack = []; + + /** + * Stores filter data for the render target + * + * @member {object[]} + */ + this.filterData = null; + + /** + * The scale mode. + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Whether this object is the root element or not + * + * @member {boolean} + */ + this.root = root; + + if (!this.root) { + this.frameBuffer = _pixiGlCore.GLFramebuffer.createRGBA(gl, 100, 100); + + if (this.scaleMode === _const.SCALE_MODES.NEAREST) { + this.frameBuffer.texture.enableNearestScaling(); + } else { + this.frameBuffer.texture.enableLinearScaling(); + } + /* + A frame buffer needs a target to render to.. + create a texture and bind it attach it to the framebuffer.. + */ + + // this is used by the base texture + this.texture = this.frameBuffer.texture; + } else { + // make it a null framebuffer.. + this.frameBuffer = new _pixiGlCore.GLFramebuffer(gl, 100, 100); + this.frameBuffer.framebuffer = null; + } + + this.setFrame(); + + this.resize(width, height); + } + + /** + * Clears the filter texture. + * + * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer + */ + + + RenderTarget.prototype.clear = function clear(clearColor) { + var cc = clearColor || this.clearColor; + + this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a); + }; + + /** + * Binds the stencil buffer. + * + */ + + + RenderTarget.prototype.attachStencilBuffer = function attachStencilBuffer() { + // TODO check if stencil is done? + /** + * The stencil buffer is used for masking in pixi + * lets create one and then add attach it to the framebuffer.. + */ + if (!this.root) { + this.frameBuffer.enableStencil(); + } + }; + + /** + * Sets the frame of the render target. + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.setFrame = function setFrame(destinationFrame, sourceFrame) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || this.destinationFrame; + }; + + /** + * Binds the buffers and initialises the viewport. + * + */ + + + RenderTarget.prototype.activate = function activate() { + // TOOD refactor usage of frame.. + var gl = this.gl; + + // make sure the texture is unbound! + this.frameBuffer.bind(); + + this.calculateProjection(this.destinationFrame, this.sourceFrame); + + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + + // TODO add a check as them may be the same! + if (this.destinationFrame !== this.sourceFrame) { + gl.enable(gl.SCISSOR_TEST); + gl.scissor(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + } else { + gl.disable(gl.SCISSOR_TEST); + } + + // TODO - does not need to be updated all the time?? + gl.viewport(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + }; + + /** + * Updates the projection matrix based on a projection frame (which is a rectangle) + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.calculateProjection = function calculateProjection(destinationFrame, sourceFrame) { + var pm = this.projectionMatrix; + + sourceFrame = sourceFrame || destinationFrame; + + pm.identity(); + + // TODO: make dest scale source + if (!this.root) { + pm.a = 1 / destinationFrame.width * 2; + pm.d = 1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = -1 - sourceFrame.y * pm.d; + } else { + pm.a = 1 / destinationFrame.width * 2; + pm.d = -1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = 1 - sourceFrame.y * pm.d; + } + }; + + /** + * Resizes the texture to the specified width and height + * + * @param {number} width - the new width of the texture + * @param {number} height - the new height of the texture + */ + + + RenderTarget.prototype.resize = function resize(width, height) { + width = width | 0; + height = height | 0; + + if (this.size.width === width && this.size.height === height) { + return; + } + + this.size.width = width; + this.size.height = height; + + this.defaultFrame.width = width; + this.defaultFrame.height = height; + + this.frameBuffer.resize(width * this.resolution, height * this.resolution); + + var projectionFrame = this.frame || this.size; + + this.calculateProjection(projectionFrame); + }; + + /** + * Destroys the render target. + * + */ + + + RenderTarget.prototype.destroy = function destroy() { + this.frameBuffer.destroy(); + + this.frameBuffer = null; + this.texture = null; + }; + + return RenderTarget; +}(); + +exports.default = RenderTarget; + +},{"../../../const":45,"../../../math":69,"../../../settings":100,"pixi-gl-core":12}],96:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = checkMaxIfStatmentsInShader; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['precision mediump float;', 'void main(void){', 'float test = 0.1;', '%forloop%', 'gl_FragColor = vec4(0.0);', '}'].join('\n'); + +function checkMaxIfStatmentsInShader(maxIfs, gl) { + var createTempContext = !gl; + + if (maxIfs === 0) { + throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); + } + + if (createTempContext) { + var tinyCanvas = document.createElement('canvas'); + + tinyCanvas.width = 1; + tinyCanvas.height = 1; + + gl = _pixiGlCore2.default.createContext(tinyCanvas); + } + + var shader = gl.createShader(gl.FRAGMENT_SHADER); + + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = maxIfs / 2 | 0; + } else { + // valid! + break; + } + } + + if (createTempContext) { + // get rid of context + if (gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').loseContext(); + } + } + + return maxIfs; +} + +function generateIfTestSrc(maxIfs) { + var src = ''; + + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxIfs - 1) { + src += 'if(test == ' + i + '.0){}'; + } + } + + return src; +} + +},{"pixi-gl-core":12}],97:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLBlendModesToPixi; + +var _const = require('../../../const'); + +/** + * Maps gl blend combinations to WebGL. + * + * @memberof PIXI + * @function mapWebGLBlendModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapWebGLBlendModesToPixi(gl) { + var array = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[_const.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD] = [gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + array[_const.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + // not-premultiplied blend modes + array[_const.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.DST_ALPHA, gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + + return array; +} + +},{"../../../const":45}],98:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLDrawModesToPixi; + +var _const = require('../../../const'); + +/** + * Generic Mask Stack data structure. + * + * @memberof PIXI + * @function mapWebGLDrawModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {object} [object={}] - The object to map into + * @return {object} The mapped draw modes. + */ +function mapWebGLDrawModesToPixi(gl) { + var object = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + object[_const.DRAW_MODES.POINTS] = gl.POINTS; + object[_const.DRAW_MODES.LINES] = gl.LINES; + object[_const.DRAW_MODES.LINE_LOOP] = gl.LINE_LOOP; + object[_const.DRAW_MODES.LINE_STRIP] = gl.LINE_STRIP; + object[_const.DRAW_MODES.TRIANGLES] = gl.TRIANGLES; + object[_const.DRAW_MODES.TRIANGLE_STRIP] = gl.TRIANGLE_STRIP; + object[_const.DRAW_MODES.TRIANGLE_FAN] = gl.TRIANGLE_FAN; + + return object; +} + +},{"../../../const":45}],99:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = validateContext; +function validateContext(gl) { + var attributes = gl.getContextAttributes(); + + // this is going to be fairly simple for now.. but at least we have room to grow! + if (!attributes.stencil) { + /* eslint-disable no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable no-console */ + } +} + +},{}],100:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _maxRecommendedTextures = require('./utils/maxRecommendedTextures'); + +var _maxRecommendedTextures2 = _interopRequireDefault(_maxRecommendedTextures); + +var _canUploadSameBuffer = require('./utils/canUploadSameBuffer'); + +var _canUploadSameBuffer2 = _interopRequireDefault(_canUploadSameBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * User's customizable globals for overriding the default PIXI settings, such + * as a renderer's default resolution, framerate, float percision, etc. + * @example + * // Use the native window resolution as the default resolution + * // will support high-density displays when rendering + * PIXI.settings.RESOLUTION = window.devicePixelRatio. + * + * // Disable interpolation when scaling, will make texture be pixelated + * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; + * @namespace PIXI.settings + */ +exports.default = { + + /** + * Target frames per millisecond. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 0.06 + */ + TARGET_FPMS: 0.06, + + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * + * @static + * @memberof PIXI.settings + * @type {boolean} + * @default true + */ + MIPMAP_TEXTURES: true, + + /** + * Default resolution / device pixel ratio of the renderer. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + RESOLUTION: 1, + + /** + * Default filter resolution. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + FILTER_RESOLUTION: 1, + + /** + * The maximum textures that this device supports. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 32 + */ + SPRITE_MAX_TEXTURES: (0, _maxRecommendedTextures2.default)(32), + + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + + /** + * The prefix that denotes a URL is for a retina asset. + * + * @static + * @memberof PIXI.settings + * @type {RegExp} + * @example `@2x` + * @default /@([0-9\.]+)x/ + */ + RETINA_PREFIX: /@([0-9\.]+)x/, + + /** + * The default render options if none are supplied to {@link PIXI.WebGLRenderer} + * or {@link PIXI.CanvasRenderer}. + * + * @static + * @constant + * @memberof PIXI.settings + * @type {object} + * @property {HTMLCanvasElement} view=null + * @property {number} resolution=1 + * @property {boolean} antialias=false + * @property {boolean} forceFXAA=false + * @property {boolean} autoResize=false + * @property {boolean} transparent=false + * @property {number} backgroundColor=0x000000 + * @property {boolean} clearBeforeRender=true + * @property {boolean} preserveDrawingBuffer=false + * @property {boolean} roundPixels=false + * @property {number} width=800 + * @property {number} height=600 + * @property {boolean} legacy=false + */ + RENDER_OPTIONS: { + view: null, + antialias: false, + forceFXAA: false, + autoResize: false, + transparent: false, + backgroundColor: 0x000000, + clearBeforeRender: true, + preserveDrawingBuffer: false, + roundPixels: false, + width: 800, + height: 600, + legacy: false + }, + + /** + * Default transform type. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.TRANSFORM_MODE} + * @default PIXI.TRANSFORM_MODE.STATIC + */ + TRANSFORM_MODE: 0, + + /** + * Default Garbage Collection mode. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO + */ + GC_MODE: 0, + + /** + * Default Garbage Collection max idle. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 3600 + */ + GC_MAX_IDLE: 60 * 60, + + /** + * Default Garbage Collection maximum check count. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 600 + */ + GC_MAX_CHECK_COUNT: 60 * 10, + + /** + * Default wrap modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP + */ + WRAP_MODE: 0, + + /** + * The scale modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR + */ + SCALE_MODE: 0, + + /** + * Default specify float precision in vertex shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.HIGH + */ + PRECISION_VERTEX: 'highp', + + /** + * Default specify float precision in fragment shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM + */ + PRECISION_FRAGMENT: 'mediump', + + /** + * Can we upload the same buffer in a single frame? + * + * @static + * @constant + * @memberof PIXI + * @type {boolean} + */ + CAN_UPLOAD_SAME_BUFFER: (0, _canUploadSameBuffer2.default)() + +}; + +},{"./utils/canUploadSameBuffer":120,"./utils/maxRecommendedTextures":125}],101:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new _math.Point(); + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = new PIXI.Sprite.fromImage('assets/image.png'); + * ``` + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Sprite = function (_Container) { + _inherits(Sprite, _Container); + + /** + * @param {PIXI.Texture} texture - The texture for this sprite + */ + function Sprite(texture) { + _classCallCheck(this, Sprite); + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + * @private + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this._anchor = new _math.ObservablePoint(_this._onAnchorUpdate, _this); + + /** + * The texture that the sprite is using + * + * @private + * @member {PIXI.Texture} + */ + _this._texture = null; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = null; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * The shader that will be used to render the sprite. Set to null to remove a current shader. + * + * @member {PIXI.Filter|PIXI.Shader} + */ + _this.shader = null; + + /** + * An internal cached value of the tint. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this.cachedTint = 0xFFFFFF; + + // call texture setter + _this.texture = texture || _Texture2.default.EMPTY; + + /** + * this is used to store the vertex data of the sprite (basically a quad) + * + * @private + * @member {Float32Array} + */ + _this.vertexData = new Float32Array(8); + + /** + * This is used to calculate the bounds of the object IF it is a trimmed sprite + * + * @private + * @member {Float32Array} + */ + _this.vertexTrimmedData = null; + + _this._transformID = -1; + _this._textureID = -1; + + _this._transformTrimmedID = -1; + _this._textureTrimmedID = -1; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * + * @member {string} + * @default 'sprite' + */ + _this.pluginName = 'sprite'; + return _this; + } + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Sprite.prototype._onTextureUpdate = function _onTextureUpdate() { + this._textureID = -1; + this._textureTrimmedID = -1; + + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = (0, _utils.sign)(this.scale.x) * this._width / this._texture.orig.width; + } + + if (this._height) { + this.scale.y = (0, _utils.sign)(this.scale.y) * this._height / this._texture.orig.height; + } + }; + + /** + * Called when the anchor position updates. + * + * @private + */ + + + Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate() { + this._transformID = -1; + this._transformTrimmedID = -1; + }; + + /** + * calculates worldTransform * vertices, store it in vertexData + */ + + + Sprite.prototype.calculateVertices = function calculateVertices() { + if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) { + return; + } + + this._transformID = this.transform._worldID; + this._textureID = this._texture._updateID; + + // set the vertex data + + var texture = this._texture; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var anchor = this._anchor; + + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - anchor._x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - anchor._y * orig.height; + h0 = h1 + trim.height; + } else { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData + * This is used to ensure that the true width and height of a trimmed texture is respected + */ + + + Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices() { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { + return; + } + + this._transformTrimmedID = this.transform._worldID; + this._textureTrimmedID = this._texture._updateID; + + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + var anchor = this._anchor; + + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + + var w1 = -anchor._x * orig.width; + var w0 = w1 + orig.width; + + var h1 = -anchor._y * orig.height; + var h0 = h1 + orig.height; + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use. + */ + + + Sprite.prototype._renderWebGL = function _renderWebGL(renderer) { + this.calculateVertices(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Sprite.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Updates the bounds of the sprite. + * + * @private + */ + + + Sprite.prototype._calculateBounds = function _calculateBounds() { + var trim = this._texture.trim; + var orig = this._texture.orig; + + // First lets check to see if the current texture has a trim.. + if (!trim || trim.width === orig.width && trim.height === orig.height) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + Sprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._texture.orig.width * -this._anchor._x; + this._bounds.minY = this._texture.orig.height * -this._anchor._y; + this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x); + this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._x); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _Container.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Tests if a point is inside this sprite + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Sprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + y1 = -height * this.anchor.y; + + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + Sprite.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + this._anchor = null; + + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + + this._texture.destroy(!!destroyBaseTexture); + } + + this._texture = null; + this.shader = null; + }; + + // some helper functions.. + + /** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Sprite} The newly created sprite + */ + + + Sprite.from = function from(source) { + return new Sprite(_Texture2.default.from(source)); + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId + */ + + + Sprite.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return new Sprite(texture); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id + */ + + + Sprite.fromImage = function fromImage(imageId, crossorigin, scaleMode) { + return new Sprite(_Texture2.default.fromImage(imageId, crossorigin, scaleMode)); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Sprite, [{ + key: 'width', + get: function get() { + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._anchor.copy(value); + } + + /** + * The tint applied to the sprite. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + } + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + */ + + }, { + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + this.cachedTint = 0xFFFFFF; + + this._textureID = -1; + this._textureTrimmedID = -1; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + }]); + + return Sprite; +}(_Container3.default); + +exports.default = Sprite; + +},{"../const":45,"../display/Container":47,"../math":69,"../textures/Texture":114,"../utils":123}],102:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +var _math = require('../../math'); + +var _CanvasTinter = require('./CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var canvasRenderWorldTransform = new _math.Matrix(); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasSpriteRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + */ + +var CanvasSpriteRenderer = function () { + /** + * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for. + */ + function CanvasSpriteRenderer(renderer) { + _classCallCheck(this, CanvasSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + CanvasSpriteRenderer.prototype.render = function render(sprite) { + var texture = sprite._texture; + var renderer = this.renderer; + + var width = texture._frame.width; + var height = texture._frame.height; + + var wt = sprite.transform.worldTransform; + var dx = 0; + var dy = 0; + + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) { + return; + } + + renderer.setBlendMode(sprite.blendMode); + + // Ignore null sources + if (texture.valid) { + renderer.context.globalAlpha = sprite.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture + var smoothingEnabled = texture.baseTexture.scaleMode === _const.SCALE_MODES.LINEAR; + + if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) { + renderer.context[renderer.smoothProperty] = smoothingEnabled; + } + + if (texture.trim) { + dx = texture.trim.width / 2 + texture.trim.x - sprite.anchor.x * texture.orig.width; + dy = texture.trim.height / 2 + texture.trim.y - sprite.anchor.y * texture.orig.height; + } else { + dx = (0.5 - sprite.anchor.x) * texture.orig.width; + dy = (0.5 - sprite.anchor.y) * texture.orig.height; + } + + if (texture.rotate) { + wt.copy(canvasRenderWorldTransform); + wt = canvasRenderWorldTransform; + _math.GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); + // the anchor has already been applied above, so lets set it to zero + dx = 0; + dy = 0; + } + + dx -= width / 2; + dy -= height / 2; + + // Allow for pixel rounding + if (renderer.roundPixels) { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution | 0, wt.ty * renderer.resolution | 0); + + dx = dx | 0; + dy = dy | 0; + } else { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution, wt.ty * renderer.resolution); + } + + var resolution = texture.baseTexture.resolution; + + if (sprite.tint !== 0xFFFFFF) { + if (sprite.cachedTint !== sprite.tint || sprite.tintedTexture.tintId !== sprite._texture._updateID) { + sprite.cachedTint = sprite.tint; + + // TODO clean up caching - how to clean up the caches? + sprite.tintedTexture = _CanvasTinter2.default.getTintedTexture(sprite, sprite.tint); + } + + renderer.context.drawImage(sprite.tintedTexture, 0, 0, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } else { + renderer.context.drawImage(texture.baseTexture.source, texture._frame.x * resolution, texture._frame.y * resolution, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } + } + }; + + /** + * destroy the sprite object. + * + */ + + + CanvasSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasSpriteRenderer; +}(); + +exports.default = CanvasSpriteRenderer; + + +_CanvasRenderer2.default.registerPlugin('sprite', CanvasSpriteRenderer); + +},{"../../const":45,"../../math":69,"../../renderers/canvas/CanvasRenderer":76,"./CanvasTinter":103}],103:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class + * @memberof PIXI + */ +var CanvasTinter = { + /** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Sprite} sprite - the sprite to tint + * @param {number} color - the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ + getTintedTexture: function getTintedTexture(sprite, color) { + var texture = sprite._texture; + + color = CanvasTinter.roundColor(color); + + var stringColor = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + texture.tintCache = texture.tintCache || {}; + + var cachedTexture = texture.tintCache[stringColor]; + + var canvas = void 0; + + if (cachedTexture) { + if (cachedTexture.tintId === texture._updateID) { + return texture.tintCache[stringColor]; + } + + canvas = texture.tintCache[stringColor]; + } else { + canvas = CanvasTinter.canvas || document.createElement('canvas'); + } + + CanvasTinter.tintMethod(texture, color, canvas); + + canvas.tintId = texture._updateID; + + if (CanvasTinter.convertTintToImage) { + // is this better? + var tintImage = new Image(); + + tintImage.src = canvas.toDataURL(); + + texture.tintCache[stringColor] = tintImage; + } else { + texture.tintCache[stringColor] = canvas; + // if we are not converting the texture to an image then we need to lose the reference to the canvas + CanvasTinter.canvas = null; + } + + return canvas; + }, + + /** + * Tint a texture using the 'multiply' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithMultiply: function tintWithMultiply(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + }, + + /** + * Tint a texture using the 'overlay' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithOverlay: function tintWithOverlay(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.globalCompositeOperation = 'copy'; + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + // context.globalCompositeOperation = 'copy'; + }, + + + /** + * Tint a texture pixel per pixel. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithPerPixel: function tintWithPerPixel(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.globalCompositeOperation = 'copy'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + var rgbValues = (0, _utils.hex2rgb)(color); + var r = rgbValues[0]; + var g = rgbValues[1]; + var b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, crop.width, crop.height); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + } + + context.putImageData(pixelData, 0, 0); + }, + + /** + * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel. + * + * @memberof PIXI.CanvasTinter + * @param {number} color - the color to round, should be a hex color + * @return {number} The rounded color. + */ + roundColor: function roundColor(color) { + var step = CanvasTinter.cacheStepsPerColorChannel; + + var rgbValues = (0, _utils.hex2rgb)(color); + + rgbValues[0] = Math.min(255, rgbValues[0] / step * step); + rgbValues[1] = Math.min(255, rgbValues[1] / step * step); + rgbValues[2] = Math.min(255, rgbValues[2] / step * step); + + return (0, _utils.rgb2hex)(rgbValues); + }, + + /** + * Number of steps which will be used as a cap when rounding colors. + * + * @memberof PIXI.CanvasTinter + * @type {number} + */ + cacheStepsPerColorChannel: 8, + + /** + * Tint cache boolean flag. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + convertTintToImage: false, + + /** + * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + canUseMultiply: (0, _canUseNewCanvasBlendModes2.default)(), + + /** + * The tinting method that will be used. + * + * @memberof PIXI.CanvasTinter + * @type {tintMethodFunctionType} + */ + tintMethod: 0 +}; + +CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply : CanvasTinter.tintWithPerPixel; + +/** + * The tintMethod type. + * + * @memberof PIXI.CanvasTinter + * @callback tintMethodFunctionType + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + +exports.default = CanvasTinter; + +},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":79,"../../utils":123}],104:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Buffer = function () { + /** + * @param {number} size - The size of the buffer in bytes. + */ + function Buffer(size) { + _classCallCheck(this, Buffer); + + this.vertices = new ArrayBuffer(size); + + /** + * View on the vertices as a Float32Array for positions + * + * @member {Float32Array} + */ + this.float32View = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array for uvs + * + * @member {Float32Array} + */ + this.uint32View = new Uint32Array(this.vertices); + } + + /** + * Destroys the buffer. + * + */ + + + Buffer.prototype.destroy = function destroy() { + this.vertices = null; + this.positions = null; + this.uvs = null; + this.colors = null; + }; + + return Buffer; +}(); + +exports.default = Buffer; + +},{}],105:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _createIndicesForQuads = require('../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +var _generateMultiTextureShader = require('./generateMultiTextureShader'); + +var _generateMultiTextureShader2 = _interopRequireDefault(_generateMultiTextureShader); + +var _checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'); + +var _checkMaxIfStatmentsInShader2 = _interopRequireDefault(_checkMaxIfStatmentsInShader); + +var _BatchBuffer = require('./BatchBuffer'); + +var _BatchBuffer2 = _interopRequireDefault(_BatchBuffer); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var TICK = 0; +var TEXTURE_TICK = 0; + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var SpriteRenderer = function (_ObjectRenderer) { + _inherits(SpriteRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function SpriteRenderer(renderer) { + _classCallCheck(this, SpriteRenderer); + + /** + * Number of values sent in the vertex buffer. + * aVertexPosition(2), aTextureCoord(1), aColor(1), aTextureId(1) = 5 + * + * @member {number} + */ + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.vertSize = 5; + + /** + * The size of the vertex information in bytes. + * + * @member {number} + */ + _this.vertByteSize = _this.vertSize * 4; + + /** + * The number of images in the SpriteRenderer before it flushes. + * + * @member {number} + */ + _this.size = _settings2.default.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + + // the total number of bytes in our batch + // let numVerts = this.size * 4 * this.vertByteSize; + + _this.buffers = []; + for (var i = 1; i <= _bitTwiddle2.default.nextPow2(_this.size); i *= 2) { + _this.buffers.push(new _BatchBuffer2.default(i * 4 * _this.vertByteSize)); + } + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + _this.indices = (0, _createIndicesForQuads2.default)(_this.size); + + /** + * The default shaders that is used if a sprite doesn't have a more specific one. + * there is a shader for each number of textures that can be rendererd. + * These shaders will also be generated on the fly as required. + * @member {PIXI.Shader[]} + */ + _this.shader = null; + + _this.currentIndex = 0; + _this.groups = []; + + for (var k = 0; k < _this.size; k++) { + _this.groups[k] = { textures: [], textureCount: 0, ids: [], size: 0, start: 0, blend: 0 }; + } + + _this.sprites = []; + + _this.vertexBuffers = []; + _this.vaos = []; + + _this.vaoMax = 2; + _this.vertexCount = 0; + + _this.renderer.on('prerender', _this.onPrerender, _this); + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + SpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + if (this.renderer.legacy) { + this.MAX_TEXTURES = 1; + } else { + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), _settings2.default.SPRITE_MAX_TEXTURES); + + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = (0, _checkMaxIfStatmentsInShader2.default)(this.MAX_TEXTURES, gl); + } + + this.shader = (0, _generateMultiTextureShader2.default)(gl, this.MAX_TEXTURES); + + // create a couple of buffers + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + // we use the second shader as the first one depending on your browser may omit aTextureId + // as it is not used by the shader so is optimized out. + + this.renderer.bindVao(null); + + var attrs = this.shader.attributes; + + for (var i = 0; i < this.vaoMax; i++) { + /* eslint-disable max-len */ + var vertexBuffer = this.vertexBuffers[i] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + /* eslint-enable max-len */ + + // build the vao object that will render.. + var vao = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (attrs.aTextureId) { + vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vaos[i] = vao; + } + + this.vao = this.vaos[0]; + this.currentBlendMode = 99999; + + this.boundTextures = new Array(this.MAX_TEXTURES); + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + SpriteRenderer.prototype.onPrerender = function onPrerender() { + this.vertexCount = 0; + }; + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + SpriteRenderer.prototype.render = function render(sprite) { + // TODO set blend modes.. + // check texture.. + if (this.currentIndex >= this.size) { + this.flush(); + } + + // get the uvs for the texture + + // if the uvs have not updated then no point rendering just yet! + if (!sprite._texture._uvs) { + return; + } + + // push a texture. + // increment the batchsize + this.sprites[this.currentIndex++] = sprite; + }; + + /** + * Renders the content and empties the current batch. + * + */ + + + SpriteRenderer.prototype.flush = function flush() { + if (this.currentIndex === 0) { + return; + } + + var gl = this.renderer.gl; + var MAX_TEXTURES = this.MAX_TEXTURES; + + var np2 = _bitTwiddle2.default.nextPow2(this.currentIndex); + var log2 = _bitTwiddle2.default.log2(np2); + var buffer = this.buffers[log2]; + + var sprites = this.sprites; + var groups = this.groups; + + var float32View = buffer.float32View; + var uint32View = buffer.uint32View; + + var boundTextures = this.boundTextures; + var rendererBoundTextures = this.renderer.boundTextures; + var touch = this.renderer.textureGC.count; + + var index = 0; + var nextTexture = void 0; + var currentTexture = void 0; + var groupCount = 1; + var textureCount = 0; + var currentGroup = groups[0]; + var vertexData = void 0; + var uvs = void 0; + var blendMode = _utils.premultiplyBlendMode[sprites[0]._texture.baseTexture.premultipliedAlpha ? 1 : 0][sprites[0].blendMode]; + + currentGroup.textureCount = 0; + currentGroup.start = 0; + currentGroup.blend = blendMode; + + TICK++; + + var i = void 0; + + // copy textures.. + for (i = 0; i < MAX_TEXTURES; ++i) { + boundTextures[i] = rendererBoundTextures[i]; + boundTextures[i]._virtalBoundId = i; + } + + for (i = 0; i < this.currentIndex; ++i) { + // upload the sprite elemetns... + // they have all ready been calculated so we just need to push them into the buffer. + var sprite = sprites[i]; + + nextTexture = sprite._texture.baseTexture; + + var spriteBlendMode = _utils.premultiplyBlendMode[Number(nextTexture.premultipliedAlpha)][sprite.blendMode]; + + if (blendMode !== spriteBlendMode) { + // finish a group.. + blendMode = spriteBlendMode; + + // force the batch to break! + currentTexture = null; + textureCount = MAX_TEXTURES; + TICK++; + } + + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + + if (nextTexture._enabled !== TICK) { + if (textureCount === MAX_TEXTURES) { + TICK++; + + currentGroup.size = i - currentGroup.start; + + textureCount = 0; + + currentGroup = groups[groupCount++]; + currentGroup.blend = blendMode; + currentGroup.textureCount = 0; + currentGroup.start = i; + } + + nextTexture.touched = touch; + + if (nextTexture._virtalBoundId === -1) { + for (var j = 0; j < MAX_TEXTURES; ++j) { + var tIndex = (j + TEXTURE_TICK) % MAX_TEXTURES; + + var t = boundTextures[tIndex]; + + if (t._enabled !== TICK) { + TEXTURE_TICK++; + + t._virtalBoundId = -1; + + nextTexture._virtalBoundId = tIndex; + + boundTextures[tIndex] = nextTexture; + break; + } + } + } + + nextTexture._enabled = TICK; + + currentGroup.textureCount++; + currentGroup.ids[textureCount] = nextTexture._virtalBoundId; + currentGroup.textures[textureCount++] = nextTexture; + } + } + + vertexData = sprite.vertexData; + + // TODO this sum does not need to be set each frame.. + uvs = sprite._texture._uvs.uvsUint32; + + if (this.renderer.roundPixels) { + var resolution = this.renderer.resolution; + + // xy + float32View[index] = (vertexData[0] * resolution | 0) / resolution; + float32View[index + 1] = (vertexData[1] * resolution | 0) / resolution; + + // xy + float32View[index + 5] = (vertexData[2] * resolution | 0) / resolution; + float32View[index + 6] = (vertexData[3] * resolution | 0) / resolution; + + // xy + float32View[index + 10] = (vertexData[4] * resolution | 0) / resolution; + float32View[index + 11] = (vertexData[5] * resolution | 0) / resolution; + + // xy + float32View[index + 15] = (vertexData[6] * resolution | 0) / resolution; + float32View[index + 16] = (vertexData[7] * resolution | 0) / resolution; + } else { + // xy + float32View[index] = vertexData[0]; + float32View[index + 1] = vertexData[1]; + + // xy + float32View[index + 5] = vertexData[2]; + float32View[index + 6] = vertexData[3]; + + // xy + float32View[index + 10] = vertexData[4]; + float32View[index + 11] = vertexData[5]; + + // xy + float32View[index + 15] = vertexData[6]; + float32View[index + 16] = vertexData[7]; + } + + uint32View[index + 2] = uvs[0]; + uint32View[index + 7] = uvs[1]; + uint32View[index + 12] = uvs[2]; + uint32View[index + 17] = uvs[3]; + /* eslint-disable max-len */ + var alpha = Math.min(sprite.worldAlpha, 1.0); + // we dont call extra function if alpha is 1.0, that's faster + var argb = alpha < 1.0 && nextTexture.premultipliedAlpha ? (0, _utils.premultiplyTint)(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); + + uint32View[index + 3] = uint32View[index + 8] = uint32View[index + 13] = uint32View[index + 18] = argb; + float32View[index + 4] = float32View[index + 9] = float32View[index + 14] = float32View[index + 19] = nextTexture._virtalBoundId; + /* eslint-enable max-len */ + + index += 20; + } + + currentGroup.size = i - currentGroup.start; + + if (!_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // this is still needed for IOS performance.. + // it really does not like uploading to the same buffer in a single frame! + if (this.vaoMax <= this.vertexCount) { + this.vaoMax++; + + var attrs = this.shader.attributes; + + /* eslint-disable max-len */ + var vertexBuffer = this.vertexBuffers[this.vertexCount] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + /* eslint-enable max-len */ + + // build the vao object that will render.. + var vao = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (attrs.aTextureId) { + vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vaos[this.vertexCount] = vao; + } + + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, false); + + this.vertexCount++; + } else { + // lets use the faster option, always use buffer number 0 + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, true); + } + + for (i = 0; i < MAX_TEXTURES; ++i) { + rendererBoundTextures[i]._virtalBoundId = -1; + } + + // render the groups.. + for (i = 0; i < groupCount; ++i) { + var group = groups[i]; + var groupTextureCount = group.textureCount; + + for (var _j = 0; _j < groupTextureCount; _j++) { + currentTexture = group.textures[_j]; + + // reset virtual ids.. + // lets do a quick check.. + if (rendererBoundTextures[group.ids[_j]] !== currentTexture) { + this.renderer.bindTexture(currentTexture, group.ids[_j], true); + } + + // reset the virtualId.. + currentTexture._virtalBoundId = -1; + } + + // set the blend mode.. + this.renderer.state.setBlendMode(group.blend); + + gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); + } + + // reset elements for the next flush + this.currentIndex = 0; + }; + + /** + * Starts a new sprite batch. + */ + + + SpriteRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + + if (_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // bind buffer #0, we don't need others + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].bind(); + } + }; + + /** + * Stops and flushes the current batch. + * + */ + + + SpriteRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Destroys the SpriteRenderer. + * + */ + + + SpriteRenderer.prototype.destroy = function destroy() { + for (var i = 0; i < this.vaoMax; i++) { + if (this.vertexBuffers[i]) { + this.vertexBuffers[i].destroy(); + } + if (this.vaos[i]) { + this.vaos[i].destroy(); + } + } + + if (this.indexBuffer) { + this.indexBuffer.destroy(); + } + + this.renderer.off('prerender', this.onPrerender, this); + + _ObjectRenderer.prototype.destroy.call(this); + + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } + + this.vertexBuffers = null; + this.vaos = null; + this.indexBuffer = null; + this.indices = null; + + this.sprites = null; + + for (var _i = 0; _i < this.buffers.length; ++_i) { + this.buffers[_i].destroy(); + } + }; + + return SpriteRenderer; +}(_ObjectRenderer3.default); + +exports.default = SpriteRenderer; + + +_WebGLRenderer2.default.registerPlugin('sprite', SpriteRenderer); + +},{"../../renderers/webgl/WebGLRenderer":83,"../../renderers/webgl/utils/ObjectRenderer":93,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":96,"../../settings":100,"../../utils":123,"../../utils/createIndicesForQuads":121,"./BatchBuffer":104,"./generateMultiTextureShader":106,"bit-twiddle":1,"pixi-gl-core":12}],106:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateMultiTextureShader; + +var _Shader = require('../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'varying float vTextureId;', 'uniform sampler2D uSamplers[%count%];', 'void main(void){', 'vec4 color;', 'float textureId = floor(vTextureId+0.5);', '%forloop%', 'gl_FragColor = color * vColor;', '}'].join('\n'); + +function generateMultiTextureShader(gl, maxTextures) { + var vertexSrc = 'precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor;\n}\n'; + var fragmentSrc = fragTemplate; + + fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); + + var shader = new _Shader2.default(gl, vertexSrc, fragmentSrc); + + var sampleValues = []; + + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + + shader.bind(); + shader.uniforms.uSamplers = sampleValues; + + return shader; +} + +function generateSampleSrc(maxTextures) { + var src = ''; + + src += '\n'; + src += '\n'; + + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxTextures - 1) { + src += 'if(textureId == ' + i + '.0)'; + } + + src += '\n{'; + src += '\n\tcolor = texture2D(uSamplers[' + i + '], vTextureCoord);'; + src += '\n}'; + } + + src += '\n'; + src += '\n'; + + return src; +} + +},{"../../Shader":43,"path":22}],107:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Sprite2 = require('../sprites/Sprite'); + +var _Sprite3 = _interopRequireDefault(_Sprite2); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TextStyle = require('./TextStyle'); + +var _TextStyle2 = _interopRequireDefault(_TextStyle); + +var _TextMetrics = require('./TextMetrics'); + +var _TextMetrics2 = _interopRequireDefault(_TextMetrics); + +var _trimCanvas = require('../utils/trimCanvas'); + +var _trimCanvas2 = _interopRequireDefault(_trimCanvas); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint max-depth: [2, 8] */ + + +var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true +}; + +/** + * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string, + * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object. + * + * A Text can be created directly from a string and a style object + * + * ```js + * let text = new PIXI.Text('This is a pixi text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI + */ + +var Text = function (_Sprite) { + _inherits(Text, _Sprite); + + /** + * @param {string} text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + * @param {HTMLCanvasElement} [canvas] - The canvas element for drawing text + */ + function Text(text, style, canvas) { + _classCallCheck(this, Text); + + canvas = canvas || document.createElement('canvas'); + + canvas.width = 3; + canvas.height = 3; + + var texture = _Texture2.default.fromCanvas(canvas, _settings2.default.SCALE_MODE, 'text'); + + texture.orig = new _math.Rectangle(); + texture.trim = new _math.Rectangle(); + + // base texture is already automatically added to the cache, now adding the actual texture + var _this = _possibleConstructorReturn(this, _Sprite.call(this, texture)); + + _Texture2.default.addToCache(_this._texture, _this._texture.baseTexture.textureCacheIds[0]); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.canvas = canvas; + + /** + * The canvas 2d context that everything is drawn with + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.canvas.getContext('2d'); + + /** + * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. + * @member {number} + * @default 1 + */ + _this.resolution = _settings2.default.RESOLUTION; + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = null; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._style = null; + /** + * Private listener to track style changes. + * + * @member {Function} + * @private + */ + _this._styleListener = null; + + /** + * Private tracker for the current font. + * + * @member {string} + * @private + */ + _this._font = ''; + + _this.text = text; + _this.style = style; + + _this.localStyleID = -1; + return _this; + } + + /** + * Renders text and updates it when needed. + * + * @private + * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. + */ + + + Text.prototype.updateText = function updateText(respectDirty) { + var style = this._style; + + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + + if (!this.dirty && respectDirty) { + return; + } + + this._font = this._style.toFontString(); + + var context = this.context; + var measured = _TextMetrics2.default.measureText(this._text, this._style, this._style.wordWrap, this.canvas); + var width = measured.width; + var height = measured.height; + var lines = measured.lines; + var lineHeight = measured.lineHeight; + var lineWidths = measured.lineWidths; + var maxLineWidth = measured.maxLineWidth; + var fontProperties = measured.fontProperties; + + this.canvas.width = Math.ceil((width + style.padding * 2) * this.resolution); + this.canvas.height = Math.ceil((height + style.padding * 2) * this.resolution); + + context.scale(this.resolution, this.resolution); + + context.clearRect(0, 0, this.canvas.width, this.canvas.height); + + context.font = this._font; + context.strokeStyle = style.stroke; + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + + var linePositionX = void 0; + var linePositionY = void 0; + + if (style.dropShadow) { + context.fillStyle = style.dropShadowColor; + context.globalAlpha = style.dropShadowAlpha; + context.shadowBlur = style.dropShadowBlur; + + if (style.dropShadowBlur > 0) { + context.shadowColor = style.dropShadowColor; + } + + var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + + for (var i = 0; i < lines.length; i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (style.fill) { + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); + + if (style.stroke && style.strokeThickness) { + context.strokeStyle = style.dropShadowColor; + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding, true); + context.strokeStyle = style.stroke; + } + } + } + } + + // reset the shadow blur and alpha that was set by the drop shadow, for the regular text + context.shadowBlur = 0; + context.globalAlpha = 1; + + // set canvas text styles + context.fillStyle = this._generateFillStyle(style, lines); + + // draw lines line by line + for (var _i = 0; _i < lines.length; _i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i]) / 2; + } + + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding, true); + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding); + } + } + + this.updateTexture(); + }; + + /** + * Render the text with letter-spacing. + * @param {string} text - The text to draw + * @param {number} x - Horizontal position to draw the text + * @param {number} y - Vertical position to draw the text + * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + * @private + */ + + + Text.prototype.drawLetterSpacing = function drawLetterSpacing(text, x, y) { + var isStroke = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var style = this._style; + + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + + if (letterSpacing === 0) { + if (isStroke) { + this.context.strokeText(text, x, y); + } else { + this.context.fillText(text, x, y); + } + + return; + } + + var characters = String.prototype.split.call(text, ''); + var currentPosition = x; + var index = 0; + var current = ''; + + while (index < text.length) { + current = characters[index++]; + if (isStroke) { + this.context.strokeText(current, currentPosition, y); + } else { + this.context.fillText(current, currentPosition, y); + } + currentPosition += this.context.measureText(current).width + letterSpacing; + } + }; + + /** + * Updates texture size based on canvas size + * + * @private + */ + + + Text.prototype.updateTexture = function updateTexture() { + var canvas = this.canvas; + + if (this._style.trim) { + var trimmed = (0, _trimCanvas2.default)(canvas); + + canvas.width = trimmed.width; + canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } + + var texture = this._texture; + var style = this._style; + var padding = style.trim ? 0 : style.padding; + var baseTexture = texture.baseTexture; + + baseTexture.hasLoaded = true; + baseTexture.resolution = this.resolution; + + baseTexture.realWidth = canvas.width; + baseTexture.realHeight = canvas.height; + baseTexture.width = canvas.width / this.resolution; + baseTexture.height = canvas.height / this.resolution; + + texture.trim.width = texture._frame.width = canvas.width / this.resolution; + texture.trim.height = texture._frame.height = canvas.height / this.resolution; + texture.trim.x = -padding; + texture.trim.y = -padding; + + texture.orig.width = texture._frame.width - padding * 2; + texture.orig.height = texture._frame.height - padding * 2; + + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + + baseTexture.emit('update', baseTexture); + + this.dirty = false; + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Text.prototype.renderWebGL = function renderWebGL(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype.renderWebGL.call(this, renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Text.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype._renderCanvas.call(this, renderer); + }; + + /** + * Gets the local bounds of the text object. + * + * @param {Rectangle} rect - The output rectangle. + * @return {Rectangle} The bounds. + */ + + + Text.prototype.getLocalBounds = function getLocalBounds(rect) { + this.updateText(true); + + return _Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + */ + + + Text.prototype._calculateBounds = function _calculateBounds() { + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; + + /** + * Method to be called upon a TextStyle change. + * @private + */ + + + Text.prototype._onStyleChange = function _onStyleChange() { + this.dirty = true; + }; + + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * + * @private + * @param {object} style - The style. + * @param {string[]} lines - The lines of text. + * @return {string|number|CanvasGradient} The fill style + */ + + + Text.prototype._generateFillStyle = function _generateFillStyle(style, lines) { + if (!Array.isArray(style.fill)) { + return style.fill; + } + + // cocoon on canvas+ cannot generate textures, so use the first colour instead + if (navigator.isCocoonJS) { + return style.fill[0]; + } + + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient = void 0; + var totalIterations = void 0; + var currentIteration = void 0; + var stop = void 0; + + var width = this.canvas.width / this.resolution; + var height = this.canvas.height / this.resolution; + + // make a copy of the style settings, so we can manipulate them later + var fill = style.fill.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(style.fill[0]); + fillGradientStops.unshift(0); + + fill.push(style.fill[style.fill.length - 1]); + fillGradientStops.push(1); + + if (style.fillGradientType === _const.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); + + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + totalIterations = (fill.length + 1) * lines.length; + currentIteration = 0; + for (var _i2 = 0; _i2 < lines.length; _i2++) { + currentIteration += 1; + for (var j = 0; j < fill.length; j++) { + if (typeof fillGradientStops[j] === 'number') { + stop = fillGradientStops[j] / lines.length + _i2 / lines.length; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[j]); + currentIteration++; + } + } + } else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); + + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + totalIterations = fill.length + 1; + currentIteration = 1; + + for (var _i3 = 0; _i3 < fill.length; _i3++) { + if (typeof fillGradientStops[_i3] === 'number') { + stop = fillGradientStops[_i3]; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[_i3]); + currentIteration++; + } + } + + return gradient; + }; + + /** + * Destroys this text object. + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majority of the time the texture will not be shared with any other Sprites. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well + */ + + + Text.prototype.destroy = function destroy(options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + + options = Object.assign({}, defaultDestroyOptions, options); + + _Sprite.prototype.destroy.call(this, options); + + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + + this._style = null; + }; + + /** + * The width of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Text, [{ + key: 'width', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * Set the style of the text. Set up an event listener to listen for changes on the style + * object and mark the text as dirty. + * + * @member {object|PIXI.TextStyle} + */ + + }, { + key: 'style', + get: function get() { + return this._style; + }, + set: function set(style) // eslint-disable-line require-jsdoc + { + style = style || {}; + + if (style instanceof _TextStyle2.default) { + this._style = style; + } else { + this._style = new _TextStyle2.default(style); + } + + this.localStyleID = -1; + this.dirty = true; + } + + /** + * Set the copy for the text object. To split a line you can use '\n'. + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(text) // eslint-disable-line require-jsdoc + { + text = String(text === '' || text === null || text === undefined ? ' ' : text); + + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + } + }]); + + return Text; +}(_Sprite3.default); + +exports.default = Text; + +},{"../const":45,"../math":69,"../settings":100,"../sprites/Sprite":101,"../textures/Texture":114,"../utils":123,"../utils/trimCanvas":128,"./TextMetrics":108,"./TextStyle":109}],108:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The TextMetrics object represents the measurement of a block of text with a specified style. + * + * @class + * @memberOf PIXI + */ +var TextMetrics = function () { + /** + * @param {string} text - the text that was measured + * @param {PIXI.TextStyle} style - the style that was measured + * @param {number} width - the measured width of the text + * @param {number} height - the measured height of the text + * @param {array} lines - an array of the lines of text broken by new lines and wrapping if specified in style + * @param {array} lineWidths - an array of the line widths for each line matched to `lines` + * @param {number} lineHeight - the measured line height for this style + * @param {number} maxLineWidth - the maximum line width for all measured lines + * @param {Object} fontProperties - the font properties object from TextMetrics.measureFont + */ + function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) { + _classCallCheck(this, TextMetrics); + + this.text = text; + this.style = style; + this.width = width; + this.height = height; + this.lines = lines; + this.lineWidths = lineWidths; + this.lineHeight = lineHeight; + this.maxLineWidth = maxLineWidth; + this.fontProperties = fontProperties; + } + + /** + * Measures the supplied string of text and returns a Rectangle. + * + * @param {string} text - the text to measure. + * @param {PIXI.TextStyle} style - the text style to use for measuring + * @param {boolean} [wordWrap] - optional override for if word-wrap should be applied to the text. + * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. + * @return {PIXI.TextMetrics} measured width and height of the text. + */ + + + TextMetrics.measureText = function measureText(text, style, wordWrap) { + var canvas = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : TextMetrics._canvas; + + wordWrap = wordWrap || style.wordWrap; + var font = style.toFontString(); + var fontProperties = TextMetrics.measureFont(font); + var context = canvas.getContext('2d'); + + context.font = font; + + var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text; + var lines = outputText.split(/(?:\r\n|\r|\n)/); + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + + for (var i = 0; i < lines.length; i++) { + var lineWidth = context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing; + + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + var width = maxLineWidth + style.strokeThickness; + + if (style.dropShadow) { + width += style.dropShadowDistance; + } + + var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * lineHeight; + + if (style.dropShadow) { + height += style.dropShadowDistance; + } + + return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties); + }; + + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @private + * @param {string} text - String to apply word wrapping to + * @param {PIXI.TextStyle} style - the style to use when wrapping + * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. + * @return {string} New string with new lines applied where required + */ + + + TextMetrics.wordWrap = function wordWrap(text, style) { + var canvas = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : TextMetrics._canvas; + + var context = canvas.getContext('2d'); + + // Greedy wrapping algorithm that will wrap words as the line grows longer + // than its horizontal bounds. + var result = ''; + var lines = text.split('\n'); + var wordWrapWidth = style.wordWrapWidth; + var characterCache = {}; + + for (var i = 0; i < lines.length; i++) { + var spaceLeft = wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) { + var wordWidth = context.measureText(words[j]).width; + + if (style.breakWords && wordWidth > wordWrapWidth) { + // Word should be split in the middle + var characters = words[j].split(''); + + for (var c = 0; c < characters.length; c++) { + var character = characters[c]; + var characterWidth = characterCache[character]; + + if (characterWidth === undefined) { + characterWidth = context.measureText(character).width; + characterCache[character] = characterWidth; + } + + if (characterWidth > spaceLeft) { + result += '\n' + character; + spaceLeft = wordWrapWidth - characterWidth; + } else { + if (c === 0) { + result += ' '; + } + + result += character; + spaceLeft -= characterWidth; + } + } + } else { + var wordWidthWithSpace = wordWidth + context.measureText(' ').width; + + if (j === 0 || wordWidthWithSpace > spaceLeft) { + // Skip printing the newline if it's the first word of the line that is + // greater than the word wrap width. + if (j > 0) { + result += '\n'; + } + result += words[j]; + spaceLeft = wordWrapWidth - wordWidth; + } else { + spaceLeft -= wordWidthWithSpace; + result += ' ' + words[j]; + } + } + } + + if (i < lines.length - 1) { + result += '\n'; + } + } + + return result; + }; + + /** + * Calculates the ascent, descent and fontSize of a given font-style + * + * @static + * @param {string} font - String representing the style of the font + * @return {PIXI.TextMetrics~FontMetrics} Font properties object + */ + + + TextMetrics.measureFont = function measureFont(font) { + // as this method is used for preparing assets, don't recalculate things if we don't need to + if (TextMetrics._fonts[font]) { + return TextMetrics._fonts[font]; + } + + var properties = {}; + + var canvas = TextMetrics._canvas; + var context = TextMetrics._context; + + context.font = font; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('M').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = font; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i = 0; + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } else { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var _j = 0; _j < line; _j += 4) { + if (imagedata[idx + _j] !== 255) { + stop = true; + break; + } + } + + if (!stop) { + idx -= line; + } else { + break; + } + } + + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + + TextMetrics._fonts[font] = properties; + + return properties; + }; + + return TextMetrics; +}(); + +/** + * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}. + * @class FontMetrics + * @memberof PIXI.TextMetrics~ + * @property {number} ascent - The ascent distance + * @property {number} descent - The descent distance + * @property {number} fontSize - Font size from ascent to descent + */ + +exports.default = TextMetrics; +var canvas = document.createElement('canvas'); + +canvas.width = canvas.height = 10; + +/** + * Cached canvas element for measuring text + * @memberof PIXI.TextMetrics + * @type {HTMLCanvasElement} + * @private + */ +TextMetrics._canvas = canvas; + +/** + * Cache for context to use. + * @memberof PIXI.TextMetrics + * @type {CanvasRenderingContext2D} + * @private + */ +TextMetrics._context = canvas.getContext('2d'); + +/** + * Cache of PIXI.TextMetrics~FontMetrics objects. + * @memberof PIXI.TextMetrics + * @type {Object} + * @private + */ +TextMetrics._fonts = {}; + +},{}],109:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // disabling eslint for now, going to rewrite this in v5 +/* eslint-disable */ + +var _const = require('../const'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: 'black', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: _const.TEXT_GRADIENT.LINEAR_VERTICAL, + fillGradientStops: [], + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + trim: false, + wordWrap: false, + wordWrapWidth: 100 +}; + +/** + * A TextStyle Object decorates a Text Object. It can be shared between + * multiple Text objects. Changing the style will update all text objects using it. + * + * @class + * @memberof PIXI + */ + +var TextStyle = function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours + * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} + * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set + * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * @param {string|string[]} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', 800' or '900') + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Default is 'miter' (creates a sharp corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {boolean} [style.trim=false] - Trim transparent borders + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + _classCallCheck(this, TextStyle); + + this.styleID = 0; + + Object.assign(this, defaultStyle, style); + } + + /** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return {PIXI.TextStyle} New cloned TextStyle object + */ + + + TextStyle.prototype.clone = function clone() { + var clonedProperties = {}; + + for (var key in defaultStyle) { + clonedProperties[key] = this[key]; + } + + return new TextStyle(clonedProperties); + }; + + /** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ + + + TextStyle.prototype.reset = function reset() { + Object.assign(this, defaultStyle); + }; + + /** + * Generates a font style string to use for `TextMetrics.measureFont()`. + * + * @return {string} Font style string, for passing to `TextMetrics.measureFont()` + */ + TextStyle.prototype.toFontString = function toFontString() { + // build canvas api font setting from individual components. Convert a numeric this.fontSize to px + var fontSizeString = typeof this.fontSize === 'number' ? this.fontSize + 'px' : this.fontSize; + + // Clean-up fontFamily property by quoting each font name + // this will support font names with spaces + var fontFamilies = this.fontFamily; + + if (!Array.isArray(this.fontFamily)) { + fontFamilies = this.fontFamily.split(','); + } + + for (var i = fontFamilies.length - 1; i >= 0; i--) { + // Trim any extra white-space + var fontFamily = fontFamilies[i].trim(); + + // Check if font already contains strings + if (!/([\"\'])[^\'\"]+\1/.test(fontFamily)) { + fontFamily = '"' + fontFamily + '"'; + } + fontFamilies[i] = fontFamily; + } + + return this.fontStyle + ' ' + this.fontVariant + ' ' + this.fontWeight + ' ' + fontSizeString + ' ' + fontFamilies.join(','); + }; + + _createClass(TextStyle, [{ + key: 'align', + get: function get() { + return this._align; + }, + set: function set(align) { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + } + }, { + key: 'breakWords', + get: function get() { + return this._breakWords; + }, + set: function set(breakWords) { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + } + }, { + key: 'dropShadow', + get: function get() { + return this._dropShadow; + }, + set: function set(dropShadow) { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + } + }, { + key: 'dropShadowAlpha', + get: function get() { + return this._dropShadowAlpha; + }, + set: function set(dropShadowAlpha) { + if (this._dropShadowAlpha !== dropShadowAlpha) { + this._dropShadowAlpha = dropShadowAlpha; + this.styleID++; + } + } + }, { + key: 'dropShadowAngle', + get: function get() { + return this._dropShadowAngle; + }, + set: function set(dropShadowAngle) { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + } + }, { + key: 'dropShadowBlur', + get: function get() { + return this._dropShadowBlur; + }, + set: function set(dropShadowBlur) { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + } + }, { + key: 'dropShadowColor', + get: function get() { + return this._dropShadowColor; + }, + set: function set(dropShadowColor) { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + } + }, { + key: 'dropShadowDistance', + get: function get() { + return this._dropShadowDistance; + }, + set: function set(dropShadowDistance) { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + } + }, { + key: 'fill', + get: function get() { + return this._fill; + }, + set: function set(fill) { + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + } + }, { + key: 'fillGradientType', + get: function get() { + return this._fillGradientType; + }, + set: function set(fillGradientType) { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + } + }, { + key: 'fillGradientStops', + get: function get() { + return this._fillGradientStops; + }, + set: function set(fillGradientStops) { + if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { + this._fillGradientStops = fillGradientStops; + this.styleID++; + } + } + }, { + key: 'fontFamily', + get: function get() { + return this._fontFamily; + }, + set: function set(fontFamily) { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + } + }, { + key: 'fontSize', + get: function get() { + return this._fontSize; + }, + set: function set(fontSize) { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + } + }, { + key: 'fontStyle', + get: function get() { + return this._fontStyle; + }, + set: function set(fontStyle) { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + } + }, { + key: 'fontVariant', + get: function get() { + return this._fontVariant; + }, + set: function set(fontVariant) { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + } + }, { + key: 'fontWeight', + get: function get() { + return this._fontWeight; + }, + set: function set(fontWeight) { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + } + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(letterSpacing) { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + } + }, { + key: 'lineHeight', + get: function get() { + return this._lineHeight; + }, + set: function set(lineHeight) { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + } + }, { + key: 'lineJoin', + get: function get() { + return this._lineJoin; + }, + set: function set(lineJoin) { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + } + }, { + key: 'miterLimit', + get: function get() { + return this._miterLimit; + }, + set: function set(miterLimit) { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + } + }, { + key: 'padding', + get: function get() { + return this._padding; + }, + set: function set(padding) { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + } + }, { + key: 'stroke', + get: function get() { + return this._stroke; + }, + set: function set(stroke) { + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + } + }, { + key: 'strokeThickness', + get: function get() { + return this._strokeThickness; + }, + set: function set(strokeThickness) { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + } + }, { + key: 'textBaseline', + get: function get() { + return this._textBaseline; + }, + set: function set(textBaseline) { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + } + }, { + key: 'trim', + get: function get() { + return this._trim; + }, + set: function set(trim) { + if (this._trim !== trim) { + this._trim = trim; + this.styleID++; + } + } + }, { + key: 'wordWrap', + get: function get() { + return this._wordWrap; + }, + set: function set(wordWrap) { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + } + }, { + key: 'wordWrapWidth', + get: function get() { + return this._wordWrapWidth; + }, + set: function set(wordWrapWidth) { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + } + }]); + + return TextStyle; +}(); + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * + * @param {number|number[]} color + * @return {string} The color as a string. + */ + + +exports.default = TextStyle; +function getSingleColor(color) { + if (typeof color === 'number') { + return (0, _utils.hex2string)(color); + } else if (typeof color === 'string') { + if (color.indexOf('0x') === 0) { + color = color.replace('0x', '#'); + } + } + + return color; +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * + * @param {number|number[]} color + * @return {string} The color as a string. + */ +function getColor(color) { + if (!Array.isArray(color)) { + return getSingleColor(color); + } else { + for (var i = 0; i < color.length; ++i) { + color[i] = getSingleColor(color[i]); + } + + return color; + } +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * + * @param {Array} array1 First array to compare + * @param {Array} array2 Second array to compare + * @return {boolean} Do the arrays contain the same values in the same order + */ +function areArraysEqual(array1, array2) { + if (!Array.isArray(array1) || !Array.isArray(array2)) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } + + return true; +} + +},{"../const":45,"../utils":123}],110:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let baseRenderTexture = new PIXI.BaseRenderTexture(renderer, 800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * baseRenderTexture.render(sprite); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let baseRenderTexture = new PIXI.BaseRenderTexture(100, 100); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var BaseRenderTexture = function (_BaseTexture) { + _inherits(BaseRenderTexture, _BaseTexture); + + /** + * @param {number} [width=100] - The width of the base render texture + * @param {number} [height=100] - The height of the base render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + */ + function BaseRenderTexture() { + var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + + _classCallCheck(this, BaseRenderTexture); + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, null, scaleMode)); + + _this.resolution = resolution || _settings2.default.RESOLUTION; + + _this.width = width; + _this.height = height; + + _this.realWidth = _this.width * _this.resolution; + _this.realHeight = _this.height * _this.resolution; + + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + _this.hasLoaded = true; + + /** + * A map of renderer IDs to webgl renderTargets + * + * @private + * @member {object} + */ + _this._glRenderTargets = {}; + + /** + * A reference to the canvas render target (we only need one as this can be shared across renderers) + * + * @private + * @member {object} + */ + _this._canvasRenderTarget = null; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + return _this; + } + + /** + * Resizes the BaseRenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + */ + + + BaseRenderTexture.prototype.resize = function resize(width, height) { + if (width === this.width && height === this.height) { + return; + } + + this.valid = width > 0 && height > 0; + + this.width = width; + this.height = height; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + if (!this.valid) { + return; + } + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + */ + + + BaseRenderTexture.prototype.destroy = function destroy() { + _BaseTexture.prototype.destroy.call(this, true); + this.renderer = null; + }; + + return BaseRenderTexture; +}(_BaseTexture3.default); + +exports.default = BaseRenderTexture; + +},{"../settings":100,"./BaseTexture":111}],111:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var BaseTexture = function (_EventEmitter) { + _inherits(BaseTexture, _EventEmitter); + + /** + * @param {HTMLImageElement|HTMLCanvasElement} [source] - the source object of the texture. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture + */ + function BaseTexture(source, scaleMode, resolution) { + _classCallCheck(this, BaseTexture); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.uid = (0, _utils.uid)(); + + _this.touched = 0; + + /** + * The resolution / device pixel ratio of the texture + * + * @member {number} + * @default 1 + */ + _this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The width of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.width = 100; + + /** + * The height of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.height = 100; + + // TODO docs + // used to store the actual dimensions of the source + /** + * Used to store the actual width of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realWidth = 100; + /** + * Used to store the actual height of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realHeight = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Set to true once the base texture has successfully loaded. + * + * This is never true if the underlying source fails to load or has no texture data. + * + * @readonly + * @member {boolean} + */ + _this.hasLoaded = false; + + /** + * Set to true if the source is currently loading. + * + * If an Image source is loading the 'loaded' or 'error' event will be + * dispatched when the operation ends. An underyling source that is + * immediately-available bypasses loading entirely. + * + * @readonly + * @member {boolean} + */ + _this.isLoading = false; + + /** + * The image source that is used to create the texture. + * + * TODO: Make this a setter that calls loadSource(); + * + * @readonly + * @member {HTMLImageElement|HTMLCanvasElement} + */ + _this.source = null; // set in loadSource, if at all + + /** + * The image source that is used to create the texture. This is used to + * store the original Svg source when it is replaced with a canvas element. + * + * TODO: Currently not in use but could be used when re-scaling svg. + * + * @readonly + * @member {Image} + */ + _this.origSource = null; // set in loadSvg, if at all + + /** + * Type of image defined in source, eg. `png` or `svg` + * + * @readonly + * @member {string} + */ + _this.imageType = null; // set in updateImageType + + /** + * Scale for source image. Used with Svg images to scale them before rasterization. + * + * @readonly + * @member {number} + */ + _this.sourceScale = 1.0; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * All blend modes, and shaders written for default value. Change it on your own risk. + * + * @member {boolean} + * @default true + */ + _this.premultipliedAlpha = true; + + /** + * The image url of the texture + * + * @member {string} + */ + _this.imageUrl = null; + + /** + * Whether or not the texture is a power of two, try to use power of two textures as much + * as you can + * + * @private + * @member {boolean} + */ + _this.isPowerOfTwo = false; + + // used for webGL + + /** + * + * Set this to true if a mipmap of this texture needs to be generated. This value needs + * to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @member {boolean} + * @see PIXI.MIPMAP_TEXTURES + */ + _this.mipmap = _settings2.default.MIPMAP_TEXTURES; + + /** + * + * WebGL Texture wrap mode + * + * @member {number} + * @see PIXI.WRAP_MODES + */ + _this.wrapMode = _settings2.default.WRAP_MODE; + + /** + * A map of renderer IDs to webgl textures + * + * @private + * @member {object} + */ + _this._glTextures = {}; + + _this._enabled = 0; + _this._virtalBoundId = -1; + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + + /** + * The ids under which this BaseTexture has been added to the base texture cache. This is + * automatically set as long as BaseTexture.addToCache is used, but may not be set if a + * BaseTexture is added directly to the BaseTextureCache array. + * + * @member {string[]} + */ + _this.textureCacheIds = []; + + // if no source passed don't try to load + if (source) { + _this.loadSource(source); + } + + /** + * Fired when a not-immediately-available source finishes loading. + * + * @protected + * @event PIXI.BaseTexture#loaded + * @param {PIXI.BaseTexture} baseTexture - Resource loaded. + */ + + /** + * Fired when a not-immediately-available source fails to load. + * + * @protected + * @event PIXI.BaseTexture#error + * @param {PIXI.BaseTexture} baseTexture - Resource errored. + */ + + /** + * Fired when BaseTexture is updated. + * + * @protected + * @event PIXI.BaseTexture#update + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. + */ + + /** + * Fired when BaseTexture is destroyed. + * + * @protected + * @event PIXI.BaseTexture#dispose + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. + */ + return _this; + } + + /** + * Updates the texture on all the webgl renderers, this also assumes the src has changed. + * + * @fires PIXI.BaseTexture#update + */ + + + BaseTexture.prototype.update = function update() { + // Svg size is handled during load + if (this.imageType !== 'svg') { + this.realWidth = this.source.naturalWidth || this.source.videoWidth || this.source.width; + this.realHeight = this.source.naturalHeight || this.source.videoHeight || this.source.height; + + this._updateDimensions(); + } + + this.emit('update', this); + }; + + /** + * Update dimensions from real values + */ + + + BaseTexture.prototype._updateDimensions = function _updateDimensions() { + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + this.isPowerOfTwo = _bitTwiddle2.default.isPow2(this.realWidth) && _bitTwiddle2.default.isPow2(this.realHeight); + }; + + /** + * Load a source. + * + * If the source is not-immediately-available, such as an image that needs to be + * downloaded, then the 'loaded' or 'error' event will be dispatched in the future + * and `hasLoaded` will remain false after this call. + * + * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: + * + * if (texture.hasLoaded) { + * // texture ready for use + * } else if (texture.isLoading) { + * // listen to 'loaded' and/or 'error' events on texture + * } else { + * // not loading, not going to load UNLESS the source is reloaded + * // (it may still make sense to listen to the events) + * } + * + * @protected + * @param {HTMLImageElement|HTMLCanvasElement} source - the source object of the texture. + */ + + + BaseTexture.prototype.loadSource = function loadSource(source) { + var _this2 = this; + + var wasLoading = this.isLoading; + + this.hasLoaded = false; + this.isLoading = false; + + if (wasLoading && this.source) { + this.source.onload = null; + this.source.onerror = null; + } + + var firstSourceLoaded = !this.source; + + this.source = source; + + // Apply source if loaded. Otherwise setup appropriate loading monitors. + if ((source.src && source.complete || source.getContext) && source.width && source.height) { + this._updateImageType(); + + if (this.imageType === 'svg') { + this._loadSvgSource(); + } else { + this._sourceLoaded(); + } + + if (firstSourceLoaded) { + // send loaded event if previous source was null and we have been passed a pre-loaded IMG element + this.emit('loaded', this); + } + } else if (!source.getContext) { + var _ret = function () { + // Image fail / not ready + _this2.isLoading = true; + + var scope = _this2; + + source.onload = function () { + scope._updateImageType(); + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope._sourceLoaded(); + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + scope.emit('loaded', scope); + }; + + source.onerror = function () { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope.emit('error', scope); + }; + + // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element + // "The value of `complete` can thus change while a script is executing." + // So complete needs to be re-checked after the callbacks have been added.. + // NOTE: complete will be true if the image has no src so best to check if the src is set. + if (source.complete && source.src) { + // ..and if we're complete now, no need for callbacks + source.onload = null; + source.onerror = null; + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return { + v: void 0 + }; + } + + _this2.isLoading = false; + + if (source.width && source.height) { + _this2._sourceLoaded(); + + // If any previous subscribers possible + if (wasLoading) { + _this2.emit('loaded', _this2); + } + } + // If any previous subscribers possible + else if (wasLoading) { + _this2.emit('error', _this2); + } + } + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + }; + + /** + * Updates type of the source image. + */ + + + BaseTexture.prototype._updateImageType = function _updateImageType() { + if (!this.imageUrl) { + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + var imageType = void 0; + + if (dataUri && dataUri.mediaType === 'image') { + // Check for subType validity + var firstSubType = dataUri.subType.split('+')[0]; + + imageType = (0, _utils.getUrlFileExtension)('.' + firstSubType); + + if (!imageType) { + throw new Error('Invalid image type in data URI.'); + } + } else { + imageType = (0, _utils.getUrlFileExtension)(this.imageUrl); + + if (!imageType) { + imageType = 'png'; + } + } + + this.imageType = imageType; + }; + + /** + * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls + * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. + */ + + + BaseTexture.prototype._loadSvgSource = function _loadSvgSource() { + if (this.imageType !== 'svg') { + // Do nothing if source is not svg + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + + if (dataUri) { + this._loadSvgSourceUsingDataUri(dataUri); + } else { + // We got an URL, so we need to do an XHR to check the svg size + this._loadSvgSourceUsingXhr(); + } + }; + + /** + * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`. + * + * @param {string} dataUri - The data uri to load from. + */ + + + BaseTexture.prototype._loadSvgSourceUsingDataUri = function _loadSvgSourceUsingDataUri(dataUri) { + var svgString = void 0; + + if (dataUri.encoding === 'base64') { + if (!atob) { + throw new Error('Your browser doesn\'t support base64 conversions.'); + } + svgString = atob(dataUri.data); + } else { + svgString = dataUri.data; + } + + this._loadSvgSourceUsingString(svgString); + }; + + /** + * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. + */ + + + BaseTexture.prototype._loadSvgSourceUsingXhr = function _loadSvgSourceUsingXhr() { + var _this3 = this; + + var svgXhr = new XMLHttpRequest(); + + // This throws error on IE, so SVG Document can't be used + // svgXhr.responseType = 'document'; + + // This is not needed since we load the svg as string (breaks IE too) + // but overrideMimeType() can be used to force the response to be parsed as XML + // svgXhr.overrideMimeType('image/svg+xml'); + + svgXhr.onload = function () { + if (svgXhr.readyState !== svgXhr.DONE || svgXhr.status !== 200) { + throw new Error('Failed to load SVG using XHR.'); + } + + _this3._loadSvgSourceUsingString(svgXhr.response); + }; + + svgXhr.onerror = function () { + return _this3.emit('error', _this3); + }; + + svgXhr.open('GET', this.imageUrl, true); + svgXhr.send(); + }; + + /** + * Loads texture using an SVG string. The original SVG Image is stored as `origSource` and the + * created canvas is the new `source`. The SVG is scaled using `sourceScale`. Called by + * `_loadSvgSourceUsingXhr` or `_loadSvgSourceUsingDataUri`. + * + * @param {string} svgString SVG source as string + * + * @fires PIXI.BaseTexture#loaded + */ + + + BaseTexture.prototype._loadSvgSourceUsingString = function _loadSvgSourceUsingString(svgString) { + var svgSize = (0, _utils.getSvgSize)(svgString); + + var svgWidth = svgSize.width; + var svgHeight = svgSize.height; + + if (!svgWidth || !svgHeight) { + throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); + } + + // Scale realWidth and realHeight + this.realWidth = Math.round(svgWidth * this.sourceScale); + this.realHeight = Math.round(svgHeight * this.sourceScale); + + this._updateDimensions(); + + // Create a canvas element + var canvas = document.createElement('canvas'); + + canvas.width = this.realWidth; + canvas.height = this.realHeight; + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + + // Draw the Svg to the canvas + canvas.getContext('2d').drawImage(this.source, 0, 0, svgWidth, svgHeight, 0, 0, this.realWidth, this.realHeight); + + // Replace the original source image with the canvas + this.origSource = this.source; + this.source = canvas; + + // Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`) + BaseTexture.addToCache(this, canvas._pixiId); + + this.isLoading = false; + this._sourceLoaded(); + this.emit('loaded', this); + }; + + /** + * Used internally to update the width, height, and some other tracking vars once + * a source has successfully loaded. + * + * @private + */ + + + BaseTexture.prototype._sourceLoaded = function _sourceLoaded() { + this.hasLoaded = true; + this.update(); + }; + + /** + * Destroys this base texture + * + */ + + + BaseTexture.prototype.destroy = function destroy() { + if (this.imageUrl) { + delete _utils.TextureCache[this.imageUrl]; + + this.imageUrl = null; + + if (!navigator.isCocoonJS) { + this.source.src = ''; + } + } + + this.source = null; + + this.dispose(); + + BaseTexture.removeFromCache(this); + this.textureCacheIds = null; + + this._destroyed = true; + }; + + /** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + * @fires PIXI.BaseTexture#dispose + */ + + + BaseTexture.prototype.dispose = function dispose() { + this.emit('dispose', this); + }; + + /** + * Changes the source image of the texture. + * The original source must be an Image element. + * + * @param {string} newSrc - the path of the image + */ + + + BaseTexture.prototype.updateSourceImage = function updateSourceImage(newSrc) { + this.source.src = newSrc; + + this.loadSource(this.source); + }; + + /** + * Helper function that creates a base texture from the given image url. + * If the image is not in the base texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + // new Image() breaks tex loading in some versions of Chrome. + // See https://code.google.com/p/chromium/issues/detail?id=238071 + var image = new Image(); // document.createElement('img'); + + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + image.crossOrigin = (0, _determineCrossOrigin2.default)(imageUrl); + } else if (crossorigin) { + image.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; + } + + baseTexture = new BaseTexture(image, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + image.src = imageUrl; // Setting this triggers load + + BaseTexture.addToCache(baseTexture, imageUrl); + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @param {string} [origin='canvas'] - A string origin of who created the base texture + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode) { + var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; + + if (!canvas._pixiId) { + canvas._pixiId = origin + '_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[canvas._pixiId]; + + if (!baseTexture) { + baseTexture = new BaseTexture(canvas, scaleMode); + BaseTexture.addToCache(baseTexture, canvas._pixiId); + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture based on the source you provide. + * The source can be - image url, image element, canvas element. + * + * @static + * @param {string|HTMLImageElement|HTMLCanvasElement} source - The source to create base texture from. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.from = function from(source, scaleMode, sourceScale) { + if (typeof source === 'string') { + return BaseTexture.fromImage(source, undefined, scaleMode, sourceScale); + } else if (source instanceof HTMLImageElement) { + var imageUrl = source.src; + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + baseTexture = new BaseTexture(source, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + BaseTexture.addToCache(baseTexture, imageUrl); + } + + return baseTexture; + } else if (source instanceof HTMLCanvasElement) { + return BaseTexture.fromCanvas(source, scaleMode); + } + + // lets assume its a base texture! + return source; + }; + + /** + * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache. + * @param {string} id - The id that the BaseTexture will be stored against. + */ + + + BaseTexture.addToCache = function addToCache(baseTexture, id) { + if (id) { + if (baseTexture.textureCacheIds.indexOf(id) === -1) { + baseTexture.textureCacheIds.push(id); + } + + /* eslint-disable no-console */ + if (_utils.BaseTextureCache[id]) { + console.warn('BaseTexture added to the cache with an id [' + id + '] that already had an entry'); + } + /* eslint-enable no-console */ + + _utils.BaseTextureCache[id] = baseTexture; + } + }; + + /** + * Remove a BaseTexture from the global BaseTextureCache. + * + * @static + * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself. + * @return {PIXI.BaseTexture|null} The BaseTexture that was removed. + */ + + + BaseTexture.removeFromCache = function removeFromCache(baseTexture) { + if (typeof baseTexture === 'string') { + var baseTextureFromCache = _utils.BaseTextureCache[baseTexture]; + + if (baseTextureFromCache) { + var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); + + if (index > -1) { + baseTextureFromCache.textureCacheIds.splice(index, 1); + } + + delete _utils.BaseTextureCache[baseTexture]; + + return baseTextureFromCache; + } + } else if (baseTexture && baseTexture.textureCacheIds) { + for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { + delete _utils.BaseTextureCache[baseTexture.textureCacheIds[i]]; + } + + baseTexture.textureCacheIds.length = 0; + + return baseTexture; + } + + return null; + }; + + return BaseTexture; +}(_eventemitter2.default); + +exports.default = BaseTexture; + +},{"../settings":100,"../utils":123,"../utils/determineCrossOrigin":122,"bit-twiddle":1,"eventemitter3":3}],112:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseRenderTexture = require('./BaseRenderTexture'); + +var _BaseRenderTexture2 = _interopRequireDefault(_BaseRenderTexture); + +var _Texture2 = require('./Texture'); + +var _Texture3 = _interopRequireDefault(_Texture2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A RenderTexture is a special texture that allows any Pixi display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let renderTexture = PIXI.RenderTexture.create(800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let renderTexture = new PIXI.RenderTexture.create(100, 100); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.Texture + * @memberof PIXI + */ +var RenderTexture = function (_Texture) { + _inherits(RenderTexture, _Texture); + + /** + * @param {PIXI.BaseRenderTexture} baseRenderTexture - The renderer used for this RenderTexture + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + */ + function RenderTexture(baseRenderTexture, frame) { + _classCallCheck(this, RenderTexture); + + // support for legacy.. + var _legacyRenderer = null; + + if (!(baseRenderTexture instanceof _BaseRenderTexture2.default)) { + /* eslint-disable prefer-rest-params, no-console */ + var width = arguments[1]; + var height = arguments[2]; + var scaleMode = arguments[3]; + var resolution = arguments[4]; + + // we have an old render texture.. + console.warn('Please use RenderTexture.create(' + width + ', ' + height + ') instead of the ctor directly.'); + _legacyRenderer = arguments[0]; + /* eslint-enable prefer-rest-params, no-console */ + + frame = null; + baseRenderTexture = new _BaseRenderTexture2.default(width, height, scaleMode, resolution); + } + + /** + * The base texture object that this texture uses + * + * @member {BaseTexture} + */ + + var _this = _possibleConstructorReturn(this, _Texture.call(this, baseRenderTexture, frame)); + + _this.legacyRenderer = _legacyRenderer; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = true; + + _this._updateUvs(); + return _this; + } + + /** + * Resizes the RenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + * @param {boolean} doNotResizeBaseTexture - Should the baseTexture.width and height values be resized as well? + */ + + + RenderTexture.prototype.resize = function resize(width, height, doNotResizeBaseTexture) { + // TODO - could be not required.. + this.valid = width > 0 && height > 0; + + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + + if (!doNotResizeBaseTexture) { + this.baseTexture.resize(width, height); + } + + this._updateUvs(); + }; + + /** + * A short hand way of creating a render texture. + * + * @param {number} [width=100] - The width of the render texture + * @param {number} [height=100] - The height of the render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.RenderTexture} The new render texture + */ + + + RenderTexture.create = function create(width, height, scaleMode, resolution) { + return new RenderTexture(new _BaseRenderTexture2.default(width, height, scaleMode, resolution)); + }; + + return RenderTexture; +}(_Texture3.default); + +exports.default = RenderTexture; + +},{"./BaseRenderTexture":110,"./Texture":114}],113:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _ = require('../'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Utility class for maintaining reference to a collection + * of Textures on a single Spritesheet. + * + * @class + * @memberof PIXI + */ +var Spritesheet = function () { + _createClass(Spritesheet, null, [{ + key: 'BATCH_SIZE', + + /** + * The maximum number of Textures to build per process. + * + * @type {number} + * @default 1000 + */ + get: function get() { + return 1000; + } + + /** + * @param {PIXI.BaseTexture} baseTexture Reference to the source BaseTexture object. + * @param {Object} data - Spritesheet image data. + * @param {string} [resolutionFilename] - The filename to consider when determining + * the resolution of the spritesheet. If not provided, the imageUrl will + * be used on the BaseTexture. + */ + + }]); + + function Spritesheet(baseTexture, data) { + var resolutionFilename = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + _classCallCheck(this, Spritesheet); + + /** + * Reference to ths source texture + * @type {PIXI.BaseTexture} + */ + this.baseTexture = baseTexture; + + /** + * Map of spritesheet textures. + * @type {Object} + */ + this.textures = {}; + + /** + * Reference to the original JSON data. + * @type {Object} + */ + this.data = data; + + /** + * The resolution of the spritesheet. + * @type {number} + */ + this.resolution = this._updateResolution(resolutionFilename || this.baseTexture.imageUrl); + + /** + * Map of spritesheet frames. + * @type {Object} + * @private + */ + this._frames = this.data.frames; + + /** + * Collection of frame names. + * @type {string[]} + * @private + */ + this._frameKeys = Object.keys(this._frames); + + /** + * Current batch index being processed. + * @type {number} + * @private + */ + this._batchIndex = 0; + + /** + * Callback when parse is completed. + * @type {Function} + * @private + */ + this._callback = null; + } + + /** + * Generate the resolution from the filename or fallback + * to the meta.scale field of the JSON data. + * + * @private + * @param {string} resolutionFilename - The filename to use for resolving + * the default resolution. + * @return {number} Resolution to use for spritesheet. + */ + + + Spritesheet.prototype._updateResolution = function _updateResolution(resolutionFilename) { + var scale = this.data.meta.scale; + + // Use a defaultValue of `null` to check if a url-based resolution is set + var resolution = (0, _utils.getResolutionOfUrl)(resolutionFilename, null); + + // No resolution found via URL + if (resolution === null) { + // Use the scale value or default to 1 + resolution = scale !== undefined ? parseFloat(scale) : 1; + } + + // For non-1 resolutions, update baseTexture + if (resolution !== 1) { + this.baseTexture.resolution = resolution; + this.baseTexture.update(); + } + + return resolution; + }; + + /** + * Parser spritesheet from loaded data. This is done asynchronously + * to prevent creating too many Texture within a single process. + * + * @param {Function} callback - Callback when complete returns + * a map of the Textures for this spritesheet. + */ + + + Spritesheet.prototype.parse = function parse(callback) { + this._batchIndex = 0; + this._callback = callback; + + if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) { + this._processFrames(0); + this._parseComplete(); + } else { + this._nextBatch(); + } + }; + + /** + * Process a batch of frames + * + * @private + * @param {number} initialFrameIndex - The index of frame to start. + */ + + + Spritesheet.prototype._processFrames = function _processFrames(initialFrameIndex) { + var frameIndex = initialFrameIndex; + var maxFrames = Spritesheet.BATCH_SIZE; + + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { + var i = this._frameKeys[frameIndex]; + var rect = this._frames[i].frame; + + if (rect) { + var frame = null; + var trim = null; + var orig = new _.Rectangle(0, 0, this._frames[i].sourceSize.w / this.resolution, this._frames[i].sourceSize.h / this.resolution); + + if (this._frames[i].rotated) { + frame = new _.Rectangle(rect.x / this.resolution, rect.y / this.resolution, rect.h / this.resolution, rect.w / this.resolution); + } else { + frame = new _.Rectangle(rect.x / this.resolution, rect.y / this.resolution, rect.w / this.resolution, rect.h / this.resolution); + } + + // Check to see if the sprite is trimmed + if (this._frames[i].trimmed) { + trim = new _.Rectangle(this._frames[i].spriteSourceSize.x / this.resolution, this._frames[i].spriteSourceSize.y / this.resolution, rect.w / this.resolution, rect.h / this.resolution); + } + + this.textures[i] = new _.Texture(this.baseTexture, frame, orig, trim, this._frames[i].rotated ? 2 : 0); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage functions + _.Texture.addToCache(this.textures[i], i); + } + + frameIndex++; + } + }; + + /** + * The parse has completed. + * + * @private + */ + + + Spritesheet.prototype._parseComplete = function _parseComplete() { + var callback = this._callback; + + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); + }; + + /** + * Begin the next batch of textures. + * + * @private + */ + + + Spritesheet.prototype._nextBatch = function _nextBatch() { + var _this = this; + + this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); + this._batchIndex++; + setTimeout(function () { + if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { + _this._nextBatch(); + } else { + _this._parseComplete(); + } + }, 0); + }; + + /** + * Destroy Spritesheet and don't use after this. + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Spritesheet.prototype.destroy = function destroy() { + var destroyBase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + for (var i in this.textures) { + this.textures[i].destroy(); + } + this._frames = null; + this._frameKeys = null; + this.data = null; + this.textures = null; + if (destroyBase) { + this.baseTexture.destroy(); + } + this.baseTexture = null; + }; + + return Spritesheet; +}(); + +exports.default = Spritesheet; + +},{"../":64,"../utils":123}],114:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture = require('./BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _VideoBaseTexture = require('./VideoBaseTexture'); + +var _VideoBaseTexture2 = _interopRequireDefault(_VideoBaseTexture); + +var _TextureUvs = require('./TextureUvs'); + +var _TextureUvs2 = _interopRequireDefault(_TextureUvs); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided + * then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * let texture = PIXI.Texture.fromImage('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` + * + * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. + * You can check for this by checking the sprite's _textureID property. + * ```js + * var texture = PIXI.Texture.fromImage('assets/image.svg'); + * var sprite1 = new PIXI.Sprite(texture); + * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file + * ``` + * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var Texture = function (_EventEmitter) { + _inherits(Texture, _EventEmitter); + + /** + * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + * @param {PIXI.Rectangle} [orig] - The area of original texture + * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture + * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8} + */ + function Texture(baseTexture, frame, orig, trim, rotate) { + _classCallCheck(this, Texture); + + /** + * Does this Texture have any frame data assigned to it? + * + * @member {boolean} + */ + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.noFrame = false; + + if (!frame) { + _this.noFrame = true; + frame = new _math.Rectangle(0, 0, 1, 1); + } + + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @member {PIXI.BaseTexture} + */ + _this.baseTexture = baseTexture; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @member {PIXI.Rectangle} + */ + _this._frame = frame; + + /** + * This is the trimmed area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @member {boolean} + */ + _this.requiresUpdate = false; + + /** + * The WebGL UV data cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + _this._uvs = null; + + /** + * This is the area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + + _this._rotate = Number(rotate || 0); + + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); + } + + if (baseTexture.hasLoaded) { + if (_this.noFrame) { + frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + + // if there is no frame we should monitor for any base texture changes.. + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + _this.frame = frame; + } else { + baseTexture.once('loaded', _this.onBaseTextureLoaded, _this); + } + + /** + * Fired when the texture is updated. This happens if the frame or the baseTexture is updated. + * + * @event PIXI.Texture#update + * @protected + * @param {PIXI.Texture} texture - Instance of texture being updated. + */ + + _this._updateID = 0; + + /** + * Extra field for extra plugins. May contain clamp settings and some matrices + * @type {Object} + */ + _this.transform = null; + + /** + * The ids under which this Texture has been added to the texture cache. This is + * automatically set as long as Texture.addToCache is used, but may not be set if a + * Texture is added directly to the TextureCache array. + * + * @member {string[]} + */ + _this.textureCacheIds = []; + return _this; + } + + /** + * Updates this texture on the gpu. + * + */ + + + Texture.prototype.update = function update() { + this.baseTexture.update(); + }; + + /** + * Called when the base texture is loaded + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureLoaded = function onBaseTextureLoaded(baseTexture) { + this._updateID++; + + // TODO this code looks confusing.. boo to abusing getters and setters! + if (this.noFrame) { + this.frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } else { + this.frame = this._frame; + } + + this.baseTexture.on('update', this.onBaseTextureUpdated, this); + this.emit('update', this); + }; + + /** + * Called when the base texture is updated + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated(baseTexture) { + this._updateID++; + + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Texture.prototype.destroy = function destroy(destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destroyed too.. + if (_utils.TextureCache[this.baseTexture.imageUrl]) { + Texture.removeFromCache(this.baseTexture.imageUrl); + } + + this.baseTexture.destroy(); + } + + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); + + this.baseTexture = null; + } + + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + + this.valid = false; + + Texture.removeFromCache(this); + this.textureCacheIds = null; + }; + + /** + * Creates a new texture object that acts the same as this one. + * + * @return {PIXI.Texture} The new texture + */ + + + Texture.prototype.clone = function clone() { + return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); + }; + + /** + * Updates the internal WebGL UV cache. + * + * @protected + */ + + + Texture.prototype._updateUvs = function _updateUvs() { + if (!this._uvs) { + this._uvs = new _TextureUvs2.default(); + } + + this._uvs.set(this._frame, this.baseTexture, this.rotate); + + this._updateID++; + }; + + /** + * Helper function that creates a Texture object from the given image url. + * If the image is not in the texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var texture = _utils.TextureCache[imageUrl]; + + if (!texture) { + texture = new Texture(_BaseTexture2.default.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); + Texture.addToCache(texture, imageUrl); + } + + return texture; + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return texture; + }; + + /** + * Helper function that creates a new Texture based on the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {string} [origin='canvas'] - A string origin of who created the base texture + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromCanvas = function fromCanvas(canvas, scaleMode) { + var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; + + return new Texture(_BaseTexture2.default.fromCanvas(canvas, scaleMode, origin)); + }; + + /** + * Helper function that creates a new Texture based on the given video element. + * + * @static + * @param {HTMLVideoElement|string} video - The URL or actual element of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideo = function fromVideo(video, scaleMode) { + if (typeof video === 'string') { + return Texture.fromVideoUrl(video, scaleMode); + } + + return new Texture(_VideoBaseTexture2.default.fromVideo(video, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the video url. + * + * @static + * @param {string} videoUrl - URL of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideoUrl = function fromVideoUrl(videoUrl, scaleMode) { + return new Texture(_VideoBaseTexture2.default.fromUrl(videoUrl, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} + * source - Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.from = function from(source) { + // TODO auto detect cross origin.. + // TODO pass in scale mode? + if (typeof source === 'string') { + var texture = _utils.TextureCache[source]; + + if (!texture) { + // check if its a video.. + var isVideo = source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/) !== null; + + if (isVideo) { + return Texture.fromVideoUrl(source); + } + + return Texture.fromImage(source); + } + + return texture; + } else if (source instanceof HTMLImageElement) { + return new Texture(_BaseTexture2.default.from(source)); + } else if (source instanceof HTMLCanvasElement) { + return Texture.fromCanvas(source, _settings2.default.SCALE_MODE, 'HTMLCanvasElement'); + } else if (source instanceof HTMLVideoElement) { + return Texture.fromVideo(source); + } else if (source instanceof _BaseTexture2.default) { + return new Texture(source); + } + + // lets assume its a texture! + return source; + }; + + /** + * Create a texture from a source and add to the cache. + * + * @static + * @param {HTMLImageElement|HTMLCanvasElement} source - The input source. + * @param {String} imageUrl - File name of texture, for cache and resolving resolution. + * @param {String} [name] - Human readible name for the texture cache. If no name is + * specified, only `imageUrl` will be used as the cache ID. + * @return {PIXI.Texture} Output texture + */ + + + Texture.fromLoader = function fromLoader(source, imageUrl, name) { + var baseTexture = new _BaseTexture2.default(source, undefined, (0, _utils.getResolutionOfUrl)(imageUrl)); + var texture = new Texture(baseTexture); + + baseTexture.imageUrl = imageUrl; + + // No name, use imageUrl instead + if (!name) { + name = imageUrl; + } + + // lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions + _BaseTexture2.default.addToCache(texture.baseTexture, name); + Texture.addToCache(texture, name); + + // also add references by url if they are different. + if (name !== imageUrl) { + _BaseTexture2.default.addToCache(texture.baseTexture, imageUrl); + Texture.addToCache(texture, imageUrl); + } + + return texture; + }; + + /** + * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the Texture will be stored against. + */ + + + Texture.addToCache = function addToCache(texture, id) { + if (id) { + if (texture.textureCacheIds.indexOf(id) === -1) { + texture.textureCacheIds.push(id); + } + + /* eslint-disable no-console */ + if (_utils.TextureCache[id]) { + console.warn('Texture added to the cache with an id [' + id + '] that already had an entry'); + } + /* eslint-enable no-console */ + + _utils.TextureCache[id] = texture; + } + }; + + /** + * Remove a Texture from the global TextureCache. + * + * @static + * @param {string|PIXI.Texture} texture - id of a Texture to be removed, or a Texture instance itself + * @return {PIXI.Texture|null} The Texture that was removed + */ + + + Texture.removeFromCache = function removeFromCache(texture) { + if (typeof texture === 'string') { + var textureFromCache = _utils.TextureCache[texture]; + + if (textureFromCache) { + var index = textureFromCache.textureCacheIds.indexOf(texture); + + if (index > -1) { + textureFromCache.textureCacheIds.splice(index, 1); + } + + delete _utils.TextureCache[texture]; + + return textureFromCache; + } + } else if (texture && texture.textureCacheIds) { + for (var i = 0; i < texture.textureCacheIds.length; ++i) { + delete _utils.TextureCache[texture.textureCacheIds[i]]; + } + + texture.textureCacheIds.length = 0; + + return texture; + } + + return null; + }; + + /** + * The frame specifies the region of the base texture that this texture uses. + * + * @member {PIXI.Rectangle} + */ + + + _createClass(Texture, [{ + key: 'frame', + get: function get() { + return this._frame; + }, + set: function set(frame) // eslint-disable-line require-jsdoc + { + this._frame = frame; + + this.noFrame = false; + + if (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height) { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + ('X: ' + frame.x + ' + ' + frame.width + ' > ' + this.baseTexture.width + ' ') + ('Y: ' + frame.y + ' + ' + frame.height + ' > ' + this.baseTexture.height)); + } + + // this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + this.valid = frame && frame.width && frame.height && this.baseTexture.hasLoaded; + + if (!this.trim && !this.rotate) { + this.orig = frame; + } + + if (this.valid) { + this._updateUvs(); + } + } + + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.GroupD8} for explanation + * + * @member {number} + */ + + }, { + key: 'rotate', + get: function get() { + return this._rotate; + }, + set: function set(rotate) // eslint-disable-line require-jsdoc + { + this._rotate = rotate; + if (this.valid) { + this._updateUvs(); + } + } + + /** + * The width of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'width', + get: function get() { + return this.orig.width; + } + + /** + * The height of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.orig.height; + } + }]); + + return Texture; +}(_eventemitter2.default); + +exports.default = Texture; + + +function createWhiteTexture() { + var canvas = document.createElement('canvas'); + + canvas.width = 10; + canvas.height = 10; + + var context = canvas.getContext('2d'); + + context.fillStyle = 'white'; + context.fillRect(0, 0, 10, 10); + + return new Texture(new _BaseTexture2.default(canvas)); +} + +function removeAllHandlers(tex) { + tex.destroy = function _emptyDestroy() {/* empty */}; + tex.on = function _emptyOn() {/* empty */}; + tex.once = function _emptyOnce() {/* empty */}; + tex.emit = function _emptyEmit() {/* empty */}; +} + +/** + * An empty texture, used often to not have to create multiple empty textures. + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.EMPTY = new Texture(new _BaseTexture2.default()); +removeAllHandlers(Texture.EMPTY); +removeAllHandlers(Texture.EMPTY.baseTexture); + +/** + * A white texture of 10x10 size, used for graphics and other things + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.WHITE = createWhiteTexture(); +removeAllHandlers(Texture.WHITE); +removeAllHandlers(Texture.WHITE.baseTexture); + +},{"../math":69,"../settings":100,"../utils":123,"./BaseTexture":111,"./TextureUvs":115,"./VideoBaseTexture":116,"eventemitter3":3}],115:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _GroupD = require('../math/GroupD8'); + +var _GroupD2 = _interopRequireDefault(_GroupD); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A standard object to store the Uvs of a texture + * + * @class + * @private + * @memberof PIXI + */ +var TextureUvs = function () { + /** + * + */ + function TextureUvs() { + _classCallCheck(this, TextureUvs); + + this.x0 = 0; + this.y0 = 0; + + this.x1 = 1; + this.y1 = 0; + + this.x2 = 1; + this.y2 = 1; + + this.x3 = 0; + this.y3 = 1; + + this.uvsUint32 = new Uint32Array(4); + } + + /** + * Sets the texture Uvs based on the given frame information. + * + * @private + * @param {PIXI.Rectangle} frame - The frame of the texture + * @param {PIXI.Rectangle} baseFrame - The base frame of the texture + * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8} + */ + + + TextureUvs.prototype.set = function set(frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + + // coordinates of center + var cX = frame.x / tw + w2; + var cY = frame.y / th + h2; + + rotate = _GroupD2.default.add(rotate, _GroupD2.default.NW); // NW is top-left corner + this.x0 = cX + w2 * _GroupD2.default.uX(rotate); + this.y0 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + w2 * _GroupD2.default.uX(rotate); + this.y1 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x2 = cX + w2 * _GroupD2.default.uX(rotate); + this.y2 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x3 = cX + w2 * _GroupD2.default.uX(rotate); + this.y3 = cY + h2 * _GroupD2.default.uY(rotate); + } else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + + this.uvsUint32[0] = (this.y0 * 65535 & 0xFFFF) << 16 | this.x0 * 65535 & 0xFFFF; + this.uvsUint32[1] = (this.y1 * 65535 & 0xFFFF) << 16 | this.x1 * 65535 & 0xFFFF; + this.uvsUint32[2] = (this.y2 * 65535 & 0xFFFF) << 16 | this.x2 * 65535 & 0xFFFF; + this.uvsUint32[3] = (this.y3 * 65535 & 0xFFFF) << 16 | this.x3 * 65535 & 0xFFFF; + }; + + return TextureUvs; +}(); + +exports.default = TextureUvs; + +},{"../math/GroupD8":65}],116:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _utils = require('../utils'); + +var _ticker = require('../ticker'); + +var _const = require('../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture of a [playing] Video. + * + * Video base textures mimic Pixi BaseTexture.from.... method in their creation process. + * + * This can be used in several ways, such as: + * + * ```js + * let texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4'); + * + * let texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' }); + * + * let texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']); + * + * let texture = PIXI.VideoBaseTexture.fromUrls([ + * { src: '/video.webm', mime: 'video/webm' }, + * { src: '/video.mp4', mime: 'video/mp4' } + * ]); + * ``` + * + * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/). + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var VideoBaseTexture = function (_BaseTexture) { + _inherits(VideoBaseTexture, _BaseTexture); + + /** + * @param {HTMLVideoElement} source - Video source + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + */ + function VideoBaseTexture(source, scaleMode) { + _classCallCheck(this, VideoBaseTexture); + + if (!source) { + throw new Error('No video source element specified.'); + } + + // hook in here to check if video is already available. + // BaseTexture looks for a source.complete boolean, plus width & height. + + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + source.complete = true; + } + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, source, scaleMode)); + + _this.width = source.videoWidth; + _this.height = source.videoHeight; + + _this._autoUpdate = true; + _this._isAutoUpdating = false; + + /** + * When set to true will automatically play videos used by this texture once + * they are loaded. If false, it will not modify the playing state. + * + * @member {boolean} + * @default true + */ + _this.autoPlay = true; + + _this.update = _this.update.bind(_this); + _this._onCanPlay = _this._onCanPlay.bind(_this); + + source.addEventListener('play', _this._onPlayStart.bind(_this)); + source.addEventListener('pause', _this._onPlayStop.bind(_this)); + _this.hasLoaded = false; + _this.__loaded = false; + + if (!_this._isSourceReady()) { + source.addEventListener('canplay', _this._onCanPlay); + source.addEventListener('canplaythrough', _this._onCanPlay); + } else { + _this._onCanPlay(); + } + return _this; + } + + /** + * Returns true if the underlying source is playing. + * + * @private + * @return {boolean} True if playing. + */ + + + VideoBaseTexture.prototype._isSourcePlaying = function _isSourcePlaying() { + var source = this.source; + + return source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2; + }; + + /** + * Returns true if the underlying source is ready for playing. + * + * @private + * @return {boolean} True if ready. + */ + + + VideoBaseTexture.prototype._isSourceReady = function _isSourceReady() { + return this.source.readyState === 3 || this.source.readyState === 4; + }; + + /** + * Runs the update loop when the video is ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStart = function _onPlayStart() { + // Just in case the video has not received its can play even yet.. + if (!this.hasLoaded) { + this._onCanPlay(); + } + + if (!this._isAutoUpdating && this.autoUpdate) { + _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); + this._isAutoUpdating = true; + } + }; + + /** + * Fired when a pause event is triggered, stops the update loop + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStop = function _onPlayStop() { + if (this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } + }; + + /** + * Fired when the video is loaded and ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onCanPlay = function _onCanPlay() { + this.hasLoaded = true; + + if (this.source) { + this.source.removeEventListener('canplay', this._onCanPlay); + this.source.removeEventListener('canplaythrough', this._onCanPlay); + + this.width = this.source.videoWidth; + this.height = this.source.videoHeight; + + // prevent multiple loaded dispatches.. + if (!this.__loaded) { + this.__loaded = true; + this.emit('loaded', this); + } + + if (this._isSourcePlaying()) { + this._onPlayStart(); + } else if (this.autoPlay) { + this.source.play(); + } + } + }; + + /** + * Destroys this texture + * + */ + + + VideoBaseTexture.prototype.destroy = function destroy() { + if (this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + } + + if (this.source && this.source._pixiId) { + _BaseTexture3.default.removeFromCache(this.source._pixiId); + delete this.source._pixiId; + } + + _BaseTexture.prototype.destroy.call(this); + }; + + /** + * Mimic Pixi BaseTexture.from.... method. + * + * @static + * @param {HTMLVideoElement} video - Video to create texture from + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromVideo = function fromVideo(video, scaleMode) { + if (!video._pixiId) { + video._pixiId = 'video_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[video._pixiId]; + + if (!baseTexture) { + baseTexture = new VideoBaseTexture(video, scaleMode); + _BaseTexture3.default.addToCache(baseTexture, video._pixiId); + } + + return baseTexture; + }; + + /** + * Helper function that creates a new BaseTexture based on the given video element. + * This BaseTexture can then be used to create a texture + * + * @static + * @param {string|object|string[]|object[]} videoSrc - The URL(s) for the video. + * @param {string} [videoSrc.src] - One of the source urls for the video + * @param {string} [videoSrc.mime] - The mimetype of the video (e.g. 'video/mp4'). If not specified + * the url's extension will be used as the second part of the mime type. + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromUrl = function fromUrl(videoSrc, scaleMode) { + var video = document.createElement('video'); + + video.setAttribute('webkit-playsinline', ''); + video.setAttribute('playsinline', ''); + + // array of objects or strings + if (Array.isArray(videoSrc)) { + for (var i = 0; i < videoSrc.length; ++i) { + video.appendChild(createSource(videoSrc[i].src || videoSrc[i], videoSrc[i].mime)); + } + } + // single object or string + else { + video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); + } + + video.load(); + + return VideoBaseTexture.fromVideo(video, scaleMode); + }; + + /** + * Should the base texture automatically update itself, set to true by default + * + * @member {boolean} + */ + + + _createClass(VideoBaseTexture, [{ + key: 'autoUpdate', + get: function get() { + return this._autoUpdate; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + + if (!this._autoUpdate && this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } else if (this._autoUpdate && !this._isAutoUpdating) { + _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); + this._isAutoUpdating = true; + } + } + } + }]); + + return VideoBaseTexture; +}(_BaseTexture3.default); + +exports.default = VideoBaseTexture; + + +VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; + +function createSource(path, type) { + if (!type) { + type = 'video/' + path.substr(path.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = path; + source.type = type; + + return source; +} + +},{"../const":45,"../ticker":119,"../utils":123,"./BaseTexture":111}],117:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _const = require('../const'); + +var _TickerListener = require('./TickerListener'); + +var _TickerListener2 = _interopRequireDefault(_TickerListener); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A Ticker class that runs an update loop that other objects listen to. + * This class is composed around listeners + * meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, + * e.g. When the ticker is started and the emitter has listeners. + * + * @class + * @memberof PIXI.ticker + */ +var Ticker = function () { + /** + * + */ + function Ticker() { + var _this = this; + + _classCallCheck(this, Ticker); + + /** + * The first listener. All new listeners added are chained on this. + * @private + * @type {TickerListener} + */ + this._head = new _TickerListener2.default(null, null, Infinity); + + /** + * Internal current frame request ID + * @private + */ + this._requestId = null; + + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + * @private + */ + this._maxElapsedMS = 100; + + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.ticker.Ticker#start} automatically + * when a listener is added. + * + * @member {boolean} + * @default false + */ + this.autoStart = false; + + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS} + * and is scaled with {@link PIXI.ticker.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * + * @member {number} + * @default 1 + */ + this.deltaTime = 1; + + /** + * Time elapsed in milliseconds from last frame to this frame. + * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime} + * is based, this value is neither capped nor scaled. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * Defaults to target frame time + * + * @member {number} + * @default 16.66 + */ + this.elapsedMS = 1 / _settings2.default.TARGET_FPMS; + + /** + * The last time {@link PIXI.ticker.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default 0 + */ + this.lastTime = 0; + + /** + * Factor of current {@link PIXI.ticker.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + * + * @member {number} + * @default 1 + */ + this.speed = 1; + + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.ticker.Ticker#start} has been called. + * `false` if {@link PIXI.ticker.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.ticker.Ticker#autoStart} being `true` + * and a listener is added. + * + * @member {boolean} + * @default false + */ + this.started = false; + + /** + * Internal tick method bound to ticker instance. + * This is because in early 2015, Function.bind + * is still 60% slower in high performance scenarios. + * Also separating frame requests from update method + * so listeners may be called at any time and with + * any animation API, just invoke ticker.update(time). + * + * @private + * @param {number} time - Time since last tick. + */ + this._tick = function (time) { + _this._requestId = null; + + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._head.next) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * + * @private + */ + + + Ticker.prototype._requestIfNeeded = function _requestIfNeeded() { + if (this._requestId === null && this._head.next) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._requestId = requestAnimationFrame(this._tick); + } + }; + + /** + * Conditionally cancels a pending animation frame. + * + * @private + */ + + + Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; + + /** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * + * @private + */ + + + Ticker.prototype._startIfPossible = function _startIfPossible() { + if (this.started) { + this._requestIfNeeded(); + } else if (this.autoStart) { + this.start(); + } + }; + + /** + * Register a handler for tick events. Calls continuously unless + * it is removed or the ticker is stopped. + * + * @param {Function} fn - The listener function to be added for updates + * @param {Function} [context] - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.add = function add(fn, context) { + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _const.UPDATE_PRIORITY.NORMAL; + + return this._addListener(new _TickerListener2.default(fn, context, priority)); + }; + + /** + * Add a handler for the tick event which is only execute once. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context] - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.addOnce = function addOnce(fn, context) { + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _const.UPDATE_PRIORITY.NORMAL; + + return this._addListener(new _TickerListener2.default(fn, context, priority, true)); + }; + + /** + * Internally adds the event handler so that it can be sorted by priority. + * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run + * before the rendering. + * + * @private + * @param {TickerListener} listener - Current listener being added. + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype._addListener = function _addListener(listener) { + // For attaching to head + var current = this._head.next; + var previous = this._head; + + // Add the first item + if (!current) { + listener.connect(previous); + } else { + // Go from highest to lowest priority + while (current) { + if (listener.priority > current.priority) { + listener.connect(previous); + break; + } + previous = current; + current = current.next; + } + + // Not yet connected + if (!listener.previous) { + listener.connect(previous); + } + } + + this._startIfPossible(); + + return this; + }; + + /** + * Removes any handlers matching the function and context parameters. + * If no handlers are left after removing, then it cancels the animation frame. + * + * @param {Function} fn - The listener function to be removed + * @param {Function} [context] - The listener context to be removed + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.remove = function remove(fn, context) { + var listener = this._head.next; + + while (listener) { + // We found a match, lets remove it + // no break to delete all possible matches + // incase a listener was added 2+ times + if (listener.match(fn, context)) { + listener = listener.destroy(); + } else { + listener = listener.next; + } + } + + if (!this._head.next) { + this._cancelIfNeeded(); + } + + return this; + }; + + /** + * Starts the ticker. If the ticker has listeners + * a new animation frame is requested at this point. + */ + + + Ticker.prototype.start = function start() { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + }; + + /** + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. + */ + + + Ticker.prototype.stop = function stop() { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; + + /** + * Destroy the ticker and don't use after this. Calling + * this method removes all references to internal events. + */ + + + Ticker.prototype.destroy = function destroy() { + this.stop(); + + var listener = this._head.next; + + while (listener) { + listener = listener.destroy(true); + } + + this._head.destroy(); + this._head = null; + }; + + /** + * Triggers an update. An update entails setting the + * current {@link PIXI.ticker.Ticker#elapsedMS}, + * the current {@link PIXI.ticker.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.ticker.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + + + Ticker.prototype.update = function update() { + var currentTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : performance.now(); + + var elapsedMS = void 0; + + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + + this.deltaTime = elapsedMS * _settings2.default.TARGET_FPMS * this.speed; + + // Cache a local reference, in-case ticker is destroyed + // during the emit, we can still check for head.next + var head = this._head; + + // Invoke listeners added to internal emitter + var listener = head.next; + + while (listener) { + listener = listener.emit(this.deltaTime); + } + + if (!head.next) { + this._cancelIfNeeded(); + } + } else { + this.deltaTime = this.elapsedMS = 0; + } + + this.lastTime = currentTime; + }; + + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.ticker.Ticker#speed}, which is specific + * to scaling {@link PIXI.ticker.Ticker#deltaTime}. + * + * @member {number} + * @readonly + */ + + + _createClass(Ticker, [{ + key: 'FPS', + get: function get() { + return 1000 / this.elapsedMS; + } + + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.ticker.Ticker#update}. + * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.settings.TARGET_FPMS * 1000`. + * + * @member {number} + * @default 10 + */ + + }, { + key: 'minFPS', + get: function get() { + return 1000 / this._maxElapsedMS; + }, + set: function set(fps) // eslint-disable-line require-jsdoc + { + // Clamp: 0 to TARGET_FPMS + var minFPMS = Math.min(Math.max(0, fps) / 1000, _settings2.default.TARGET_FPMS); + + this._maxElapsedMS = 1 / minFPMS; + } + }]); + + return Ticker; +}(); + +exports.default = Ticker; + +},{"../const":45,"../settings":100,"./TickerListener":118}],118:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Internal class for handling the priority sorting of ticker handlers. + * + * @private + * @class + * @memberof PIXI.ticker + */ +var TickerListener = function () { + /** + * Constructor + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context=null] - The listener context + * @param {number} [priority=0] - The priority for emitting + * @param {boolean} [once=false] - If the handler should fire once + */ + function TickerListener(fn) { + var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var once = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + _classCallCheck(this, TickerListener); + + /** + * The handler function to execute. + * @member {Function} + */ + this.fn = fn; + + /** + * The calling to execute. + * @member {Function} + */ + this.context = context; + + /** + * The current priority. + * @member {number} + */ + this.priority = priority; + + /** + * If this should only execute once. + * @member {boolean} + */ + this.once = once; + + /** + * The next item in chain. + * @member {TickerListener} + */ + this.next = null; + + /** + * The previous item in chain. + * @member {TickerListener} + */ + this.previous = null; + + /** + * `true` if this listener has been destroyed already. + * @member {boolean} + * @private + */ + this._destroyed = false; + } + + /** + * Simple compare function to figure out if a function and context match. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} context - The listener context + * @return {boolean} `true` if the listener match the arguments + */ + + + TickerListener.prototype.match = function match(fn, context) { + context = context || null; + + return this.fn === fn && this.context === context; + }; + + /** + * Emit by calling the current function. + * @param {number} deltaTime - time since the last emit. + * @return {TickerListener} Next ticker + */ + + + TickerListener.prototype.emit = function emit(deltaTime) { + if (this.fn) { + if (this.context) { + this.fn.call(this.context, deltaTime); + } else { + this.fn(deltaTime); + } + } + + var redirect = this.next; + + if (this.once) { + this.destroy(true); + } + + // Soft-destroying should remove + // the next reference + if (this._destroyed) { + this.next = null; + } + + return redirect; + }; + + /** + * Connect to the list. + * @param {TickerListener} previous - Input node, previous listener + */ + + + TickerListener.prototype.connect = function connect(previous) { + this.previous = previous; + if (previous.next) { + previous.next.previous = this; + } + this.next = previous.next; + previous.next = this; + }; + + /** + * Destroy and don't use after this. + * @param {boolean} [hard = false] `true` to remove the `next` reference, this + * is considered a hard destroy. Soft destroy maintains the next reference. + * @return {TickerListener} The listener to redirect while emitting or removing. + */ + + + TickerListener.prototype.destroy = function destroy() { + var hard = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + this._destroyed = true; + this.fn = null; + this.context = null; + + // Disconnect, hook up next and previous + if (this.previous) { + this.previous.next = this.next; + } + + if (this.next) { + this.next.previous = this.previous; + } + + // Redirect to the next item + var redirect = this.previous; + + // Remove references + this.next = hard ? null : redirect; + this.previous = null; + + return redirect; + }; + + return TickerListener; +}(); + +exports.default = TickerListener; + +},{}],119:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Ticker = exports.shared = undefined; + +var _Ticker = require('./Ticker'); + +var _Ticker2 = _interopRequireDefault(_Ticker); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The shared ticker instance used by {@link PIXI.extras.AnimatedSprite}. + * and by {@link PIXI.interaction.InteractionManager}. + * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` + * for this instance. Please follow the examples for usage, including + * how to opt-out of auto-starting the shared ticker. + * + * @example + * let ticker = PIXI.ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(800, 600); + * let stage = new PIXI.Container(); + * let interactionManager = PIXI.interaction.InteractionManager(renderer); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * + * @type {PIXI.ticker.Ticker} + * @memberof PIXI.ticker + */ +var shared = new _Ticker2.default(); + +shared.autoStart = true; +shared.destroy = function () { + // protect destroying shared ticker + // this is used by other internal systems + // like AnimatedSprite and InteractionManager +}; + +/** + * This namespace contains an API for interacting with PIXI's internal global update loop. + * + * This ticker is used for rendering, {@link PIXI.extras.AnimatedSprite AnimatedSprite}, + * {@link PIXI.interaction.InteractionManager InteractionManager} and many other time-based PIXI systems. + * @example + * const ticker = new PIXI.ticker.Ticker(); + * ticker.stop(); + * ticker.add((deltaTime) => { + * // do something every frame + * }); + * ticker.start(); + * @namespace PIXI.ticker + */ +exports.shared = shared; +exports.Ticker = _Ticker2.default; + +},{"./Ticker":117}],120:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = canUploadSameBuffer; +function canUploadSameBuffer() { + // Uploading the same buffer multiple times in a single frame can cause perf issues. + // Apparent on IOS so only check for that at the moment + // this check may become more complex if this issue pops up elsewhere. + var ios = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform); + + return !ios; +} + +},{}],121:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = createIndicesForQuads; +/** + * Generic Mask Stack data structure + * + * @memberof PIXI + * @function createIndicesForQuads + * @private + * @param {number} size - Number of quads + * @return {Uint16Array} indices + */ +function createIndicesForQuads(size) { + // the total number of indices in our array, there are 6 points per quad. + + var totalIndices = size * 6; + + var indices = new Uint16Array(totalIndices); + + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + indices[i + 0] = j + 0; + indices[i + 1] = j + 1; + indices[i + 2] = j + 2; + indices[i + 3] = j + 0; + indices[i + 4] = j + 2; + indices[i + 5] = j + 3; + } + + return indices; +} + +},{}],122:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = determineCrossOrigin; + +var _url2 = require('url'); + +var _url3 = _interopRequireDefault(_url2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var tempAnchor = void 0; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +function determineCrossOrigin(url) { + var loc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location; + + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url3.default.parse(tempAnchor.href); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +} + +},{"url":28}],123:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.premultiplyBlendMode = exports.BaseTextureCache = exports.TextureCache = exports.mixins = exports.pluginTarget = exports.EventEmitter = exports.removeItems = exports.isMobile = undefined; +exports.uid = uid; +exports.hex2rgb = hex2rgb; +exports.hex2string = hex2string; +exports.rgb2hex = rgb2hex; +exports.getResolutionOfUrl = getResolutionOfUrl; +exports.decomposeDataUri = decomposeDataUri; +exports.getUrlFileExtension = getUrlFileExtension; +exports.getSvgSize = getSvgSize; +exports.skipHello = skipHello; +exports.sayHello = sayHello; +exports.isWebGLSupported = isWebGLSupported; +exports.sign = sign; +exports.destroyTextureCache = destroyTextureCache; +exports.clearTextureCache = clearTextureCache; +exports.correctBlendMode = correctBlendMode; +exports.premultiplyTint = premultiplyTint; +exports.premultiplyRgba = premultiplyRgba; +exports.premultiplyTintToRgba = premultiplyTintToRgba; + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _pluginTarget = require('./pluginTarget'); + +var _pluginTarget2 = _interopRequireDefault(_pluginTarget); + +var _mixin = require('./mixin'); + +var mixins = _interopRequireWildcard(_mixin); + +var _ismobilejs = require('ismobilejs'); + +var isMobile = _interopRequireWildcard(_ismobilejs); + +var _removeArrayItems = require('remove-array-items'); + +var _removeArrayItems2 = _interopRequireDefault(_removeArrayItems); + +var _mapPremultipliedBlendModes = require('./mapPremultipliedBlendModes'); + +var _mapPremultipliedBlendModes2 = _interopRequireDefault(_mapPremultipliedBlendModes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var nextUid = 0; +var saidHello = false; + +/** + * Generalized convenience utilities for PIXI. + * @example + * // Extend PIXI's internal Event Emitter. + * class MyEmitter extends PIXI.utils.EventEmitter { + * constructor() { + * super(); + * console.log("Emitter created!"); + * } + * } + * + * // Get info on current device + * console.log(PIXI.utils.isMobile); + * + * // Convert hex color to string + * console.log(PIXI.utils.hex2string(0xff00ff)); // returns: "#ff00ff" + * @namespace PIXI.utils + */ +exports.isMobile = isMobile; +exports.removeItems = _removeArrayItems2.default; +exports.EventEmitter = _eventemitter2.default; +exports.pluginTarget = _pluginTarget2.default; +exports.mixins = mixins; + +/** + * Gets the next unique identifier + * + * @memberof PIXI.utils + * @function uid + * @return {number} The next unique identifier to use. + */ + +function uid() { + return ++nextUid; +} + +/** + * Converts a hex color number to an [R, G, B] array + * + * @memberof PIXI.utils + * @function hex2rgb + * @param {number} hex - The number to convert + * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one + * @return {number[]} An array representing the [R, G, B] of the color. + */ +function hex2rgb(hex, out) { + out = out || []; + + out[0] = (hex >> 16 & 0xFF) / 255; + out[1] = (hex >> 8 & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + + return out; +} + +/** + * Converts a hex color number to a string. + * + * @memberof PIXI.utils + * @function hex2string + * @param {number} hex - Number in hex + * @return {string} The string color. + */ +function hex2string(hex) { + hex = hex.toString(16); + hex = '000000'.substr(0, 6 - hex.length) + hex; + + return '#' + hex; +} + +/** + * Converts a color as an [R, G, B] array to a hex number + * + * @memberof PIXI.utils + * @function rgb2hex + * @param {number[]} rgb - rgb array + * @return {number} The color number + */ +function rgb2hex(rgb) { + return (rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + (rgb[2] * 255 | 0); +} + +/** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * + * @memberof PIXI.utils + * @function getResolutionOfUrl + * @param {string} url - the image path + * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. + * @return {number} resolution / device pixel ratio of an asset + */ +function getResolutionOfUrl(url, defaultValue) { + var resolution = _settings2.default.RETINA_PREFIX.exec(url); + + if (resolution) { + return parseFloat(resolution[1]); + } + + return defaultValue !== undefined ? defaultValue : 1; +} + +/** + * Typedef for decomposeDataUri return object. + * + * @typedef {object} DecomposedDataUri + * @property {mediaType} Media type, eg. `image` + * @property {subType} Sub type, eg. `png` + * @property {encoding} Data encoding, eg. `base64` + * @property {data} The actual data + */ + +/** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. + * + * @memberof PIXI.utils + * @function decomposeDataUri + * @param {string} dataUri - the data URI to check + * @return {DecomposedDataUri|undefined} The decomposed data uri or undefined + */ +function decomposeDataUri(dataUri) { + var dataUriMatch = _const.DATA_URI.exec(dataUri); + + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + encoding: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + data: dataUriMatch[4] + }; + } + + return undefined; +} + +/** + * Get type of the image by regexp for extension. Returns undefined for unknown extensions. + * + * @memberof PIXI.utils + * @function getUrlFileExtension + * @param {string} url - the image path + * @return {string|undefined} image extension + */ +function getUrlFileExtension(url) { + var extension = _const.URL_FILE_EXTENSION.exec(url); + + if (extension) { + return extension[1].toLowerCase(); + } + + return undefined; +} + +/** + * Typedef for Size object. + * + * @typedef {object} Size + * @property {width} Width component + * @property {height} Height component + */ + +/** + * Get size from an svg string using regexp. + * + * @memberof PIXI.utils + * @function getSvgSize + * @param {string} svgString - a serialized svg element + * @return {Size|undefined} image extension + */ +function getSvgSize(svgString) { + var sizeMatch = _const.SVG_SIZE.exec(svgString); + var size = {}; + + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); + size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); + } + + return size; +} + +/** + * Skips the hello message of renderers that are created after this is run. + * + * @function skipHello + * @memberof PIXI.utils + */ +function skipHello() { + saidHello = true; +} + +/** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever makes you a jerk face. + * + * @static + * @function sayHello + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ +function sayHello(type) { + if (saidHello) { + return; + } + + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = ['\n %c %c %c Pixi.js ' + _const.VERSION + ' - \u2730 ' + type + ' \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n', 'background: #ff66a5; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff66a5; background: #030307; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'background: #ffc3dc; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;']; + + window.console.log.apply(console, args); + } else if (window.console) { + window.console.log('Pixi.js ' + _const.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); + } + + saidHello = true; +} + +/** + * Helper for checking for webgl support + * + * @memberof PIXI.utils + * @function isWebGLSupported + * @return {boolean} is webgl supported + */ +function isWebGLSupported() { + var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; + + try { + if (!window.WebGLRenderingContext) { + return false; + } + + var canvas = document.createElement('canvas'); + var gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); + + var success = !!(gl && gl.getContextAttributes().stencil); + + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + + if (loseContext) { + loseContext.loseContext(); + } + } + + gl = null; + + return success; + } catch (e) { + return false; + } +} + +/** + * Returns sign of number + * + * @memberof PIXI.utils + * @function sign + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ +function sign(n) { + if (n === 0) return 0; + + return n < 0 ? -1 : 1; +} + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var TextureCache = exports.TextureCache = Object.create(null); + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var BaseTextureCache = exports.BaseTextureCache = Object.create(null); + +/** + * Destroys all texture in the cache + * + * @memberof PIXI.utils + * @function destroyTextureCache + */ +function destroyTextureCache() { + var key = void 0; + + for (key in TextureCache) { + TextureCache[key].destroy(); + } + for (key in BaseTextureCache) { + BaseTextureCache[key].destroy(); + } +} + +/** + * Removes all textures from cache, but does not destroy them + * + * @memberof PIXI.utils + * @function clearTextureCache + */ +function clearTextureCache() { + var key = void 0; + + for (key in TextureCache) { + delete TextureCache[key]; + } + for (key in BaseTextureCache) { + delete BaseTextureCache[key]; + } +} + +/** + * @memberof PIXI.utils + * @const premultiplyBlendMode + * @type {Array} maps premultiply flag and blendMode to adjusted blendMode + */ +var premultiplyBlendMode = exports.premultiplyBlendMode = (0, _mapPremultipliedBlendModes2.default)(); + +/** + * changes blendMode according to texture format + * + * @memberof PIXI.utils + * @function correctBlendMode + * @param {number} blendMode supposed blend mode + * @param {boolean} premultiplied whether source is premultiplied + * @returns {number} true blend mode for this texture + */ +function correctBlendMode(blendMode, premultiplied) { + return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; +} + +/** + * premultiplies tint + * + * @param {number} tint integet RGB + * @param {number} alpha floating point alpha (0.0-1.0) + * @returns {number} tint multiplied by alpha + */ +function premultiplyTint(tint, alpha) { + if (alpha === 1.0) { + return (alpha * 255 << 24) + tint; + } + if (alpha === 0.0) { + return 0; + } + var R = tint >> 16 & 0xFF; + var G = tint >> 8 & 0xFF; + var B = tint & 0xFF; + + R = R * alpha + 0.5 | 0; + G = G * alpha + 0.5 | 0; + B = B * alpha + 0.5 | 0; + + return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; +} + +/** + * combines rgb and alpha to out array + * + * @param {Float32Array|number[]} rgb input rgb + * @param {number} alpha alpha param + * @param {Float32Array} [out] output + * @param {boolean} [premultiply=true] do premultiply it + * @returns {Float32Array} vec4 rgba + */ +function premultiplyRgba(rgb, alpha, out, premultiply) { + out = out || new Float32Array(4); + if (premultiply || premultiply === undefined) { + out[0] = rgb[0] * alpha; + out[1] = rgb[1] * alpha; + out[2] = rgb[2] * alpha; + } else { + out[0] = rgb[0]; + out[1] = rgb[1]; + out[2] = rgb[2]; + } + out[3] = alpha; + + return out; +} + +/** + * converts integer tint and float alpha to vec4 form, premultiplies by default + * + * @param {number} tint input tint + * @param {number} alpha alpha param + * @param {Float32Array} [out] output + * @param {boolean} [premultiply=true] do premultiply it + * @returns {Float32Array} vec4 rgba + */ +function premultiplyTintToRgba(tint, alpha, out, premultiply) { + out = out || new Float32Array(4); + out[0] = (tint >> 16 & 0xFF) / 255.0; + out[1] = (tint >> 8 & 0xFF) / 255.0; + out[2] = (tint & 0xFF) / 255.0; + if (premultiply || premultiply === undefined) { + out[0] *= alpha; + out[1] *= alpha; + out[2] *= alpha; + } + out[3] = alpha; + + return out; +} + +},{"../const":45,"../settings":100,"./mapPremultipliedBlendModes":124,"./mixin":126,"./pluginTarget":127,"eventemitter3":3,"ismobilejs":4,"remove-array-items":30}],124:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapPremultipliedBlendModes; + +var _const = require('../const'); + +/** + * Corrects pixi blend, takes premultiplied alpha into account + * + * @memberof PIXI + * @function mapPremultipliedBlendModes + * @private + * @param {Array} [array] - The array to output into. + * @return {Array} Mapped modes. + */ + +function mapPremultipliedBlendModes() { + var pm = []; + var npm = []; + + for (var i = 0; i < 32; i++) { + pm[i] = i; + npm[i] = i; + } + + pm[_const.BLEND_MODES.NORMAL_NPM] = _const.BLEND_MODES.NORMAL; + pm[_const.BLEND_MODES.ADD_NPM] = _const.BLEND_MODES.ADD; + pm[_const.BLEND_MODES.SCREEN_NPM] = _const.BLEND_MODES.SCREEN; + + npm[_const.BLEND_MODES.NORMAL] = _const.BLEND_MODES.NORMAL_NPM; + npm[_const.BLEND_MODES.ADD] = _const.BLEND_MODES.ADD_NPM; + npm[_const.BLEND_MODES.SCREEN] = _const.BLEND_MODES.SCREEN_NPM; + + var array = []; + + array.push(npm); + array.push(pm); + + return array; +} + +},{"../const":45}],125:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = maxRecommendedTextures; + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function maxRecommendedTextures(max) { + if (_ismobilejs2.default.tablet || _ismobilejs2.default.phone) { + // check if the res is iphone 6 or higher.. + return 4; + } + + // desktop should be ok + return max; +} + +},{"ismobilejs":4}],126:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.mixin = mixin; +exports.delayMixin = delayMixin; +exports.performMixins = performMixins; +/** + * Mixes all enumerable properties and methods from a source object to a target object. + * + * @memberof PIXI.utils.mixins + * @function mixin + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function mixin(target, source) { + if (!target || !source) return; + // in ES8/ES2017, this would be really easy: + // Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + + // get all the enumerable property keys + var keys = Object.keys(source); + + // loop through properties + for (var i = 0; i < keys.length; ++i) { + var propertyName = keys[i]; + + // Set the property using the property descriptor - this works for accessors and normal value properties + Object.defineProperty(target, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); + } +} + +var mixins = []; + +/** + * Queues a mixin to be handled towards the end of the initialization of PIXI, so that deprecation + * can take effect. + * + * @memberof PIXI.utils.mixins + * @function delayMixin + * @private + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function delayMixin(target, source) { + mixins.push(target, source); +} + +/** + * Handles all mixins queued via delayMixin(). + * + * @memberof PIXI.utils.mixins + * @function performMixins + * @private + */ +function performMixins() { + for (var i = 0; i < mixins.length; i += 2) { + mixin(mixins[i], mixins[i + 1]); + } + mixins.length = 0; +} + +},{}],127:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Mixins functionality to make an object have "plugins". + * + * @example + * function MyObject() {} + * + * pluginTarget.mixin(MyObject); + * + * @mixin + * @memberof PIXI.utils + * @param {object} obj - The object to mix into. + */ +function pluginTarget(obj) { + obj.__plugins = {}; + + /** + * Adds a plugin to an object + * + * @param {string} pluginName - The events that should be listed. + * @param {Function} ctor - The constructor function for the plugin. + */ + obj.registerPlugin = function registerPlugin(pluginName, ctor) { + obj.__plugins[pluginName] = ctor; + }; + + /** + * Instantiates all the plugins of this object + * + */ + obj.prototype.initPlugins = function initPlugins() { + this.plugins = this.plugins || {}; + + for (var o in obj.__plugins) { + this.plugins[o] = new obj.__plugins[o](this); + } + }; + + /** + * Removes all the plugins of this object + * + */ + obj.prototype.destroyPlugins = function destroyPlugins() { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + + this.plugins = null; + }; +} + +exports.default = { + /** + * Mixes in the properties of the pluginTarget into another object + * + * @param {object} obj - The obj to mix into + */ + mixin: function mixin(obj) { + pluginTarget(obj); + } +}; + +},{}],128:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = trimCanvas; +/** + * Trim transparent borders from a canvas + * + * @memberof PIXI + * @function trimCanvas + * @private + * @param {HTMLCanvasElement} canvas - the canvas to trim + * @returns {object} Trim data + */ +function trimCanvas(canvas) { + // https://gist.github.com/remy/784508 + + var width = canvas.width; + var height = canvas.height; + + var context = canvas.getContext('2d'); + var imageData = context.getImageData(0, 0, width, height); + var pixels = imageData.data; + var len = pixels.length; + + var bound = { + top: null, + left: null, + right: null, + bottom: null + }; + var i = void 0; + var x = void 0; + var y = void 0; + + for (i = 0; i < len; i += 4) { + if (pixels[i + 3] !== 0) { + x = i / 4 % width; + y = ~~(i / 4 / width); + + if (bound.top === null) { + bound.top = y; + } + + if (bound.left === null) { + bound.left = x; + } else if (x < bound.left) { + bound.left = x; + } + + if (bound.right === null) { + bound.right = x + 1; + } else if (bound.right < x) { + bound.right = x + 1; + } + + if (bound.bottom === null) { + bound.bottom = y; + } else if (bound.bottom < y) { + bound.bottom = y; + } + } + } + + width = bound.right - bound.left; + height = bound.bottom - bound.top + 1; + + var data = context.getImageData(bound.left, bound.top, width, height); + + return { + height: height, + width: width, + data: data + }; +} + +},{}],129:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = deprecation; +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code +function warn(msg) { + /* eslint-disable no-console */ + var stack = new Error().stack; + + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('Deprecation Warning: ', msg); + } else { + // chop off the stack trace which includes pixi.js internal calls + stack = stack.split('\n').splice(3).join('\n'); + + if (console.groupCollapsed) { + console.groupCollapsed('%cDeprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', msg); + console.warn(stack); + console.groupEnd(); + } else { + console.warn('Deprecation Warning: ', msg); + console.warn(stack); + } + } + /* eslint-enable no-console */ +} + +function deprecation(core) { + var mesh = core.mesh, + particles = core.particles, + extras = core.extras, + filters = core.filters, + prepare = core.prepare, + loaders = core.loaders, + interaction = core.interaction; + + + Object.defineProperties(core, { + + /** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ + SpriteBatch: { + get: function get() { + throw new ReferenceError('SpriteBatch does not exist any more, ' + 'please use the new ParticleContainer instead.'); + } + }, + + /** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in pixi v3, + * please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ + AssetLoader: { + get: function get() { + throw new ReferenceError('The loader system was overhauled in pixi v3, ' + 'please see the new PIXI.loaders.Loader class.'); + } + }, + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + Stage: { + get: function get() { + warn('You do not need to use a PIXI Stage any more, you can simply render any container.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + DisplayObjectContainer: { + get: function get() { + warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + Strip: { + get: function get() { + warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.'); + + return mesh.Mesh; + } + }, + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + Rope: { + get: function get() { + warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.'); + + return mesh.Rope; + } + }, + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + ParticleContainer: { + get: function get() { + warn('The ParticleContainer class has been moved to particles.ParticleContainer, ' + 'please use particles.ParticleContainer from now on.'); + + return particles.ParticleContainer; + } + }, + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + MovieClip: { + get: function get() { + warn('The MovieClip class has been moved to extras.AnimatedSprite, please use extras.AnimatedSprite.'); + + return extras.AnimatedSprite; + } + }, + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + TilingSprite: { + get: function get() { + warn('The TilingSprite class has been moved to extras.TilingSprite, ' + 'please use extras.TilingSprite from now on.'); + + return extras.TilingSprite; + } + }, + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + BitmapText: { + get: function get() { + warn('The BitmapText class has been moved to extras.BitmapText, ' + 'please use extras.BitmapText from now on.'); + + return extras.BitmapText; + } + }, + + /** + * @class + * @private + * @name blendModes + * @memberof PIXI + * @see PIXI.BLEND_MODES + * @deprecated since version 3.0.0 + */ + blendModes: { + get: function get() { + warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.'); + + return core.BLEND_MODES; + } + }, + + /** + * @class + * @private + * @name scaleModes + * @memberof PIXI + * @see PIXI.SCALE_MODES + * @deprecated since version 3.0.0 + */ + scaleModes: { + get: function get() { + warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.'); + + return core.SCALE_MODES; + } + }, + + /** + * @class + * @private + * @name BaseTextureCache + * @memberof PIXI + * @see PIXI.utils.BaseTextureCache + * @deprecated since version 3.0.0 + */ + BaseTextureCache: { + get: function get() { + warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, ' + 'please use utils.BaseTextureCache from now on.'); + + return core.utils.BaseTextureCache; + } + }, + + /** + * @class + * @private + * @name TextureCache + * @memberof PIXI + * @see PIXI.utils.TextureCache + * @deprecated since version 3.0.0 + */ + TextureCache: { + get: function get() { + warn('The TextureCache class has been moved to utils.TextureCache, ' + 'please use utils.TextureCache from now on.'); + + return core.utils.TextureCache; + } + }, + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + math: { + get: function get() { + warn('The math namespace is deprecated, please access members already accessible on PIXI.'); + + return core; + } + }, + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.Filter; + } + }, + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + TransformManual: { + get: function get() { + warn('TransformManual has been renamed to TransformBase, please update your pixi-spine'); + + return core.TransformBase; + } + }, + + /** + * @static + * @constant + * @name PIXI.TARGET_FPMS + * @see PIXI.settings.TARGET_FPMS + * @deprecated since version 4.2.0 + */ + TARGET_FPMS: { + get: function get() { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + return core.settings.TARGET_FPMS; + }, + set: function set(value) { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + core.settings.TARGET_FPMS = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.FILTER_RESOLUTION + * @see PIXI.settings.FILTER_RESOLUTION + * @deprecated since version 4.2.0 + */ + FILTER_RESOLUTION: { + get: function get() { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + return core.settings.FILTER_RESOLUTION; + }, + set: function set(value) { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + core.settings.FILTER_RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RESOLUTION + * @see PIXI.settings.RESOLUTION + * @deprecated since version 4.2.0 + */ + RESOLUTION: { + get: function get() { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + return core.settings.RESOLUTION; + }, + set: function set(value) { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + core.settings.RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.MIPMAP_TEXTURES + * @see PIXI.settings.MIPMAP_TEXTURES + * @deprecated since version 4.2.0 + */ + MIPMAP_TEXTURES: { + get: function get() { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + return core.settings.MIPMAP_TEXTURES; + }, + set: function set(value) { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + core.settings.MIPMAP_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_BATCH_SIZE + * @see PIXI.settings.SPRITE_BATCH_SIZE + * @deprecated since version 4.2.0 + */ + SPRITE_BATCH_SIZE: { + get: function get() { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + return core.settings.SPRITE_BATCH_SIZE; + }, + set: function set(value) { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + core.settings.SPRITE_BATCH_SIZE = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_MAX_TEXTURES + * @see PIXI.settings.SPRITE_MAX_TEXTURES + * @deprecated since version 4.2.0 + */ + SPRITE_MAX_TEXTURES: { + get: function get() { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + return core.settings.SPRITE_MAX_TEXTURES; + }, + set: function set(value) { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + core.settings.SPRITE_MAX_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RETINA_PREFIX + * @see PIXI.settings.RETINA_PREFIX + * @deprecated since version 4.2.0 + */ + RETINA_PREFIX: { + get: function get() { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + return core.settings.RETINA_PREFIX; + }, + set: function set(value) { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + core.settings.RETINA_PREFIX = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.DEFAULT_RENDER_OPTIONS + * @see PIXI.settings.RENDER_OPTIONS + * @deprecated since version 4.2.0 + */ + DEFAULT_RENDER_OPTIONS: { + get: function get() { + warn('PIXI.DEFAULT_RENDER_OPTIONS has been deprecated, please use PIXI.settings.DEFAULT_RENDER_OPTIONS'); + + return core.settings.RENDER_OPTIONS; + } + } + }); + + // Move the default properties to settings + var defaults = [{ parent: 'TRANSFORM_MODE', target: 'TRANSFORM_MODE' }, { parent: 'GC_MODES', target: 'GC_MODE' }, { parent: 'WRAP_MODES', target: 'WRAP_MODE' }, { parent: 'SCALE_MODES', target: 'SCALE_MODE' }, { parent: 'PRECISION', target: 'PRECISION_FRAGMENT' }]; + + var _loop = function _loop(i) { + var deprecation = defaults[i]; + + Object.defineProperty(core[deprecation.parent], 'DEFAULT', { + get: function get() { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); + + return core.settings[deprecation.target]; + }, + set: function set(value) { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); + + core.settings[deprecation.target] = value; + } + }); + }; + + for (var i = 0; i < defaults.length; i++) { + _loop(i); + } + + Object.defineProperties(core.settings, { + + /** + * @static + * @name PRECISION + * @memberof PIXI.settings + * @see PIXI.PRECISION + * @deprecated since version 4.4.0 + */ + PRECISION: { + get: function get() { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + return core.settings.PRECISION_FRAGMENT; + }, + set: function set(value) { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + core.settings.PRECISION_FRAGMENT = value; + } + } + }); + + if (extras.AnimatedSprite) { + Object.defineProperties(extras, { + + /** + * @class + * @name MovieClip + * @memberof PIXI.extras + * @see PIXI.extras.AnimatedSprite + * @deprecated since version 4.2.0 + */ + MovieClip: { + get: function get() { + warn('The MovieClip class has been renamed to AnimatedSprite, please use AnimatedSprite from now on.'); + + return extras.AnimatedSprite; + } + } + }); + } + + core.DisplayObject.prototype.generateTexture = function generateTexture(renderer, scaleMode, resolution) { + warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); + + return renderer.generateTexture(this, scaleMode, resolution); + }; + + core.Graphics.prototype.generateTexture = function generateTexture(scaleMode, resolution) { + warn('graphics generate texture has moved to the renderer. ' + 'Or to render a graphics to a texture using canvas please use generateCanvasTexture'); + + return this.generateCanvasTexture(scaleMode, resolution); + }; + + core.RenderTexture.prototype.render = function render(displayObject, matrix, clear, updateTransform) { + this.legacyRenderer.render(displayObject, this, clear, matrix, !updateTransform); + warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)'); + }; + + core.RenderTexture.prototype.getImage = function getImage(target) { + warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); + + return this.legacyRenderer.extract.image(target); + }; + + core.RenderTexture.prototype.getBase64 = function getBase64(target) { + warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); + + return this.legacyRenderer.extract.base64(target); + }; + + core.RenderTexture.prototype.getCanvas = function getCanvas(target) { + warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); + + return this.legacyRenderer.extract.canvas(target); + }; + + core.RenderTexture.prototype.getPixels = function getPixels(target) { + warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); + + return this.legacyRenderer.pixels(target); + }; + + /** + * @method + * @private + * @name PIXI.Sprite#setTexture + * @see PIXI.Sprite#texture + * @deprecated since version 3.0.0 + * @param {PIXI.Texture} texture - The texture to set to. + */ + core.Sprite.prototype.setTexture = function setTexture(texture) { + this.texture = texture; + warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;'); + }; + + if (extras.BitmapText) { + /** + * @method + * @name PIXI.extras.BitmapText#setText + * @see PIXI.extras.BitmapText#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ + extras.BitmapText.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';'); + }; + } + + /** + * @method + * @name PIXI.Text#setText + * @see PIXI.Text#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ + core.Text.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';'); + }; + + /** + * Calculates the ascent, descent and fontSize of a given fontStyle + * + * @name PIXI.Text.calculateFontProperties + * @see PIXI.TextMetrics.measureFont + * @deprecated since version 4.5.0 + * @param {string} font - String representing the style of the font + * @return {Object} Font properties object + */ + core.Text.calculateFontProperties = function calculateFontProperties(font) { + warn('Text.calculateFontProperties is now deprecated, please use the TextMetrics.measureFont'); + + return core.TextMetrics.measureFont(font); + }; + + Object.defineProperties(core.Text, { + fontPropertiesCache: { + get: function get() { + warn('Text.fontPropertiesCache is deprecated'); + + return core.TextMetrics._fonts; + } + }, + fontPropertiesCanvas: { + get: function get() { + warn('Text.fontPropertiesCanvas is deprecated'); + + return core.TextMetrics._canvas; + } + }, + fontPropertiesContext: { + get: function get() { + warn('Text.fontPropertiesContext is deprecated'); + + return core.TextMetrics._context; + } + } + }); + + /** + * @method + * @name PIXI.Text#setStyle + * @see PIXI.Text#style + * @deprecated since version 3.0.0 + * @param {*} style - The style to set to. + */ + core.Text.prototype.setStyle = function setStyle(style) { + this.style = style; + warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;'); + }; + + /** + * @method + * @name PIXI.Text#determineFontProperties + * @see PIXI.Text#measureFontProperties + * @deprecated since version 4.2.0 + * @private + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ + core.Text.prototype.determineFontProperties = function determineFontProperties(fontStyle) { + warn('determineFontProperties is now deprecated, please use TextMetrics.measureFont method'); + + return core.TextMetrics.measureFont(fontStyle); + }; + + /** + * @method + * @name PIXI.Text.getFontStyle + * @see PIXI.TextMetrics.getFontStyle + * @deprecated since version 4.5.0 + * @param {PIXI.TextStyle} style - The style to use. + * @return {string} Font string + */ + core.Text.getFontStyle = function getFontStyle(style) { + warn('getFontStyle is now deprecated, please use TextStyle.toFontString() instead'); + + style = style || {}; + + if (!(style instanceof core.TextStyle)) { + style = new core.TextStyle(style); + } + + return style.toFontString(); + }; + + Object.defineProperties(core.TextStyle.prototype, { + /** + * Set all properties of a font as a single string + * + * @name PIXI.TextStyle#font + * @deprecated since version 4.0.0 + */ + font: { + get: function get() { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\', \'fontSize\', \'fontStyle\', \'fontVariant\' and \'fontWeight\' properties from now on'); + + var fontSizeString = typeof this._fontSize === 'number' ? this._fontSize + 'px' : this._fontSize; + + return this._fontStyle + ' ' + this._fontVariant + ' ' + this._fontWeight + ' ' + fontSizeString + ' ' + this._fontFamily; + }, + set: function set(font) { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + + // can work out fontStyle from search of whole string + if (font.indexOf('italic') > 1) { + this._fontStyle = 'italic'; + } else if (font.indexOf('oblique') > -1) { + this._fontStyle = 'oblique'; + } else { + this._fontStyle = 'normal'; + } + + // can work out fontVariant from search of whole string + if (font.indexOf('small-caps') > -1) { + this._fontVariant = 'small-caps'; + } else { + this._fontVariant = 'normal'; + } + + // fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units + var splits = font.split(' '); + var fontSizeIndex = -1; + + this._fontSize = 26; + for (var i = 0; i < splits.length; ++i) { + if (splits[i].match(/(px|pt|em|%)/)) { + fontSizeIndex = i; + this._fontSize = splits[i]; + break; + } + } + + // we can now search for fontWeight as we know it must occur before the fontSize + this._fontWeight = 'normal'; + for (var _i = 0; _i < fontSizeIndex; ++_i) { + if (splits[_i].match(/(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/)) { + this._fontWeight = splits[_i]; + break; + } + } + + // and finally join everything together after the fontSize in case the font family has multiple words + if (fontSizeIndex > -1 && fontSizeIndex < splits.length - 1) { + this._fontFamily = ''; + for (var _i2 = fontSizeIndex + 1; _i2 < splits.length; ++_i2) { + this._fontFamily += splits[_i2] + ' '; + } + + this._fontFamily = this._fontFamily.slice(0, -1); + } else { + this._fontFamily = 'Arial'; + } + + this.styleID++; + } + } + }); + + /** + * @method + * @name PIXI.Texture#setFrame + * @see PIXI.Texture#setFrame + * @deprecated since version 3.0.0 + * @param {PIXI.Rectangle} frame - The frame to set. + */ + core.Texture.prototype.setFrame = function setFrame(frame) { + this.frame = frame; + warn('setFrame is now deprecated, please use the frame property, e.g: myTexture.frame = frame;'); + }; + + /** + * @static + * @function + * @name PIXI.Texture.addTextureToCache + * @see PIXI.Texture.addToCache + * @deprecated since 4.5.0 + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the texture will be stored against. + */ + core.Texture.addTextureToCache = function addTextureToCache(texture, id) { + core.Texture.addToCache(texture, id); + warn('Texture.addTextureToCache is deprecated, please use Texture.addToCache from now on.'); + }; + + /** + * @static + * @function + * @name PIXI.Texture.removeTextureFromCache + * @see PIXI.Texture.removeFromCache + * @deprecated since 4.5.0 + * @param {string} id - The id of the texture to be removed + * @return {PIXI.Texture|null} The texture that was removed + */ + core.Texture.removeTextureFromCache = function removeTextureFromCache(id) { + warn('Texture.removeTextureFromCache is deprecated, please use Texture.removeFromCache from now on. ' + 'Be aware that Texture.removeFromCache does not automatically its BaseTexture from the BaseTextureCache. ' + 'For that, use BaseTexture.removeFromCache'); + + core.BaseTexture.removeFromCache(id); + + return core.Texture.removeFromCache(id); + }; + + Object.defineProperties(filters, { + + /** + * @class + * @private + * @name PIXI.filters.AbstractFilter + * @see PIXI.AbstractFilter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.AbstractFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.SpriteMaskFilter + * @see PIXI.SpriteMaskFilter + * @deprecated since version 3.0.6 + */ + SpriteMaskFilter: { + get: function get() { + warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.'); + + return core.SpriteMaskFilter; + } + } + }); + + /** + * @method + * @name PIXI.utils.uuid + * @see PIXI.utils.uid + * @deprecated since version 3.0.6 + * @return {number} The uid + */ + core.utils.uuid = function () { + warn('utils.uuid() is deprecated, please use utils.uid() from now on.'); + + return core.utils.uid(); + }; + + /** + * @method + * @name PIXI.utils.canUseNewCanvasBlendModes + * @see PIXI.CanvasTinter + * @deprecated + * @return {boolean} Can use blend modes. + */ + core.utils.canUseNewCanvasBlendModes = function () { + warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on'); + + return core.CanvasTinter.canUseMultiply; + }; + + var saidHello = true; + + /** + * @name PIXI.utils._saidHello + * @type {boolean} + * @see PIXI.utils.skipHello + * @deprecated since 4.1.0 + */ + Object.defineProperty(core.utils, '_saidHello', { + set: function set(bool) { + if (bool) { + warn('PIXI.utils._saidHello is deprecated, please use PIXI.utils.skipHello()'); + this.skipHello(); + } + saidHello = bool; + }, + get: function get() { + return saidHello; + } + }); + + if (prepare.BasePrepare) { + /** + * @method + * @name PIXI.prepare.BasePrepare#register + * @see PIXI.prepare.BasePrepare#registerFindHook + * @deprecated since version 4.4.2 + * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + prepare.BasePrepare.prototype.register = function register(addHook, uploadHook) { + warn('renderer.plugins.prepare.register is now deprecated, ' + 'please use renderer.plugins.prepare.registerFindHook & renderer.plugins.prepare.registerUploadHook'); + + if (addHook) { + this.registerFindHook(addHook); + } + + if (uploadHook) { + this.registerUploadHook(uploadHook); + } + + return this; + }; + } + + if (prepare.canvas) { + /** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.canvas.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ + Object.defineProperty(prepare.canvas, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } + }); + } + + if (prepare.webgl) { + /** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.webgl.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ + Object.defineProperty(prepare.webgl, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } + }); + } + + if (loaders.Loader) { + (function () { + var Resource = loaders.Resource; + var Loader = loaders.Loader; + + Object.defineProperties(Resource.prototype, { + isJson: { + get: function get() { + warn('The isJson property is deprecated, please use `resource.type === Resource.TYPE.JSON`.'); + + return this.type === Resource.TYPE.JSON; + } + }, + isXml: { + get: function get() { + warn('The isXml property is deprecated, please use `resource.type === Resource.TYPE.XML`.'); + + return this.type === Resource.TYPE.XML; + } + }, + isImage: { + get: function get() { + warn('The isImage property is deprecated, please use `resource.type === Resource.TYPE.IMAGE`.'); + + return this.type === Resource.TYPE.IMAGE; + } + }, + isAudio: { + get: function get() { + warn('The isAudio property is deprecated, please use `resource.type === Resource.TYPE.AUDIO`.'); + + return this.type === Resource.TYPE.AUDIO; + } + }, + isVideo: { + get: function get() { + warn('The isVideo property is deprecated, please use `resource.type === Resource.TYPE.VIDEO`.'); + + return this.type === Resource.TYPE.VIDEO; + } + } + }); + + Object.defineProperties(Loader.prototype, { + before: { + get: function get() { + warn('The before() method is deprecated, please use pre().'); + + return this.pre; + } + }, + after: { + get: function get() { + warn('The after() method is deprecated, please use use().'); + + return this.use; + } + } + }); + })(); + } + + if (interaction.interactiveTarget) { + /** + * @name PIXI.interaction.interactiveTarget#defaultCursor + * @static + * @type {number} + * @see PIXI.interaction.interactiveTarget#cursor + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.interactiveTarget, 'defaultCursor', { + set: function set(value) { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + this.cursor = value; + }, + get: function get() { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + + return this.cursor; + } + }); + } + + if (interaction.InteractionManager) { + /** + * @name PIXI.interaction.InteractionManager#defaultCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.InteractionManager, 'defaultCursorStyle', { + set: function set(value) { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + this.cursorStyles.default = value; + }, + get: function get() { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + + return this.cursorStyles.default; + } + }); + + /** + * @name PIXI.interaction.InteractionManager#currentCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.InteractionManager, 'currentCursorStyle', { + set: function set(value) { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + this.currentCursorMode = value; + }, + get: function get() { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + + return this.currentCursorMode; + } + }); + } +} + +},{}],130:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI.extract + */ + +var CanvasExtract = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasExtract(renderer) { + _classCallCheck(this, CanvasExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.extract.CanvasExtract} extract + * @memberof PIXI.CanvasRenderer# + * @see PIXI.extract.CanvasExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + CanvasExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `CanvasExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + CanvasExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + CanvasExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = this.renderer.width; + frame.height = this.renderer.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + CanvasExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + + return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; + }; + + /** + * Destroys the extract + * + */ + + + CanvasExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return CanvasExtract; +}(); + +exports.default = CanvasExtract; + + +core.CanvasRenderer.registerPlugin('extract', CanvasExtract); + +},{"../../core":64}],131:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLExtract = require('./webgl/WebGLExtract'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLExtract).default; + } +}); + +var _CanvasExtract = require('./canvas/CanvasExtract'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasExtract).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./canvas/CanvasExtract":130,"./webgl/WebGLExtract":132}],132:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); +var BYTES_PER_PIXEL = 4; + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI.extract + */ + +var WebGLExtract = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLExtract(renderer) { + _classCallCheck(this, WebGLExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.extract.WebGLExtract} extract + * @memberof PIXI.WebGLRenderer# + * @see PIXI.extract.WebGLExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + WebGLExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `WebGLExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + WebGLExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + WebGLExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var flipY = false; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + flipY = false; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + flipY = true; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + + // set up an array of pixels + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + + canvasData.data.set(webglPixels); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // pulling pixels + if (flipY) { + canvasBuffer.context.scale(1, -1); + canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); + } + } + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + WebGLExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + } + + return webglPixels; + }; + + /** + * Destroys the extract + * + */ + + + WebGLExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return WebGLExtract; +}(); + +exports.default = WebGLExtract; + + +core.WebGLRenderer.registerPlugin('extract', WebGLExtract); + +},{"../../core":64}],133:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @typedef FrameObject + * @type {object} + * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame + * @property {number} time - the duration of the frame in ms + */ + +/** + * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. + * + * ```js + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; + * + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.fromImage(alienImages[i]); + * textureArray.push(texture); + * }; + * + * let mc = new PIXI.AnimatedSprite(textureArray); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ +var AnimatedSprite = function (_core$Sprite) { + _inherits(AnimatedSprite, _core$Sprite); + + /** + * @param {PIXI.Texture[]|FrameObject[]} textures - an array of {@link PIXI.Texture} or frame + * objects that make up the animation + * @param {boolean} [autoUpdate=true] - Whether use PIXI.ticker.shared to auto update animation time. + */ + function AnimatedSprite(textures, autoUpdate) { + _classCallCheck(this, AnimatedSprite); + + /** + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture)); + + _this._textures = null; + + /** + * @private + */ + _this._durations = null; + + _this.textures = textures; + + /** + * `true` uses PIXI.ticker.shared to auto update animation time. + * @type {boolean} + * @default true + * @private + */ + _this._autoUpdate = autoUpdate !== false; + + /** + * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower + * + * @member {number} + * @default 1 + */ + _this.animationSpeed = 1; + + /** + * Whether or not the animate sprite repeats after playing. + * + * @member {boolean} + * @default true + */ + _this.loop = true; + + /** + * Function to call when a AnimatedSprite finishes playing + * + * @member {Function} + */ + _this.onComplete = null; + + /** + * Function to call when a AnimatedSprite changes which texture is being rendered + * + * @member {Function} + */ + _this.onFrameChange = null; + + /** + * Function to call when 'loop' is true, and an AnimatedSprite is played and loops around to start again + * + * @member {Function} + */ + _this.onLoop = null; + + /** + * Elapsed time since animation has been started, used internally to display current texture + * + * @member {number} + * @private + */ + _this._currentTime = 0; + + /** + * Indicates if the AnimatedSprite is currently playing + * + * @member {boolean} + * @readonly + */ + _this.playing = false; + return _this; + } + + /** + * Stops the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.stop = function stop() { + if (!this.playing) { + return; + } + + this.playing = false; + if (this._autoUpdate) { + core.ticker.shared.remove(this.update, this); + } + }; + + /** + * Plays the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.play = function play() { + if (this.playing) { + return; + } + + this.playing = true; + if (this._autoUpdate) { + core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.HIGH); + } + }; + + /** + * Stops the AnimatedSprite and goes to a specific frame + * + * @param {number} frameNumber - frame index to stop at + */ + + + AnimatedSprite.prototype.gotoAndStop = function gotoAndStop(frameNumber) { + this.stop(); + + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + + /** + * Goes to a specific frame and begins playing the AnimatedSprite + * + * @param {number} frameNumber - frame index to start at + */ + + + AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay(frameNumber) { + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + + this.play(); + }; + + /** + * Updates the object transform for rendering. + * + * @private + * @param {number} deltaTime - Time since last tick. + */ + + + AnimatedSprite.prototype.update = function update(deltaTime) { + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + + lag += elapsed / 60 * 1000; + + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + + var sign = Math.sign(this.animationSpeed * deltaTime); + + this._currentTime = Math.floor(this._currentTime); + + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + + this._currentTime += lag / this._durations[this.currentFrame]; + } else { + this._currentTime += elapsed; + } + + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + + if (this.onComplete) { + this.onComplete(); + } + } else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + + if (this.onComplete) { + this.onComplete(); + } + } else if (previousFrame !== this.currentFrame) { + if (this.loop && this.onLoop) { + if (this.animationSpeed > 0 && this.currentFrame < previousFrame) { + this.onLoop(); + } else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) { + this.onLoop(); + } + } + + this.updateTexture(); + } + }; + + /** + * Updates the displayed texture to match the current frame index + * + * @private + */ + + + AnimatedSprite.prototype.updateTexture = function updateTexture() { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + }; + + /** + * Stops the AnimatedSprite and destroys it + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + AnimatedSprite.prototype.destroy = function destroy(options) { + this.stop(); + _core$Sprite.prototype.destroy.call(this, options); + }; + + /** + * A short hand way of creating a movieclip from an array of frame ids + * + * @static + * @param {string[]} frames - The array of frames ids the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animated sprite with the specified frames. + */ + + + AnimatedSprite.fromFrames = function fromFrames(frames) { + var textures = []; + + for (var i = 0; i < frames.length; ++i) { + textures.push(core.Texture.fromFrame(frames[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * A short hand way of creating a movieclip from an array of image ids + * + * @static + * @param {string[]} images - the array of image urls the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animate sprite with the specified images as frames. + */ + + + AnimatedSprite.fromImages = function fromImages(images) { + var textures = []; + + for (var i = 0; i < images.length; ++i) { + textures.push(core.Texture.fromImage(images[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * totalFrames is the total number of frames in the AnimatedSprite. This is the same as number of textures + * assigned to the AnimatedSprite. + * + * @readonly + * @member {number} + * @default 0 + */ + + + _createClass(AnimatedSprite, [{ + key: 'totalFrames', + get: function get() { + return this._textures.length; + } + + /** + * The array of textures used for this AnimatedSprite + * + * @member {PIXI.Texture[]} + */ + + }, { + key: 'textures', + get: function get() { + return this._textures; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value[0] instanceof core.Texture) { + this._textures = value; + this._durations = null; + } else { + this._textures = []; + this._durations = []; + + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + this.gotoAndStop(0); + this.updateTexture(); + } + + /** + * The AnimatedSprites current frame index + * + * @member {number} + * @readonly + */ + + }, { + key: 'currentFrame', + get: function get() { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + + return currentFrame; + } + }]); + + return AnimatedSprite; +}(core.Sprite); + +exports.default = AnimatedSprite; + +},{"../core":64}],134:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ObservablePoint = require('../core/math/ObservablePoint'); + +var _ObservablePoint2 = _interopRequireDefault(_ObservablePoint); + +var _settings = require('../core/settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BitmapText object will create a line or multiple lines of text using bitmap font. To + * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using: + * + * A BitmapText can only be created when the font is loaded + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); + * ``` + * + * http://www.angelcode.com/products/bmfont/ for windows or + * http://www.bmglyph.com/ for mac. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.extras + */ +var BitmapText = function (_core$Container) { + _inherits(BitmapText, _core$Container); + + /** + * @param {string} text - The copy that you would like the text to display + * @param {object} style - The style parameters + * @param {string|object} style.font - The font descriptor for the object, can be passed as a string of form + * "24px FontName" or "FontName" or as an object with explicit name/size properties. + * @param {string} [style.font.name] - The bitmap font id + * @param {number} [style.font.size] - The size of the font in pixels, e.g. 24 + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), does not affect + * single line text + * @param {number} [style.tint=0xFFFFFF] - The tint color + */ + function BitmapText(text) { + var style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _classCallCheck(this, BitmapText); + + /** + * Private tracker for the width of the overall text + * + * @member {number} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._textWidth = 0; + + /** + * Private tracker for the height of the overall text + * + * @member {number} + * @private + */ + _this._textHeight = 0; + + /** + * Private tracker for the letter sprite pool. + * + * @member {PIXI.Sprite[]} + * @private + */ + _this._glyphs = []; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._font = { + tint: style.tint !== undefined ? style.tint : 0xFFFFFF, + align: style.align || 'left', + name: null, + size: 0 + }; + + /** + * Private tracker for the current font. + * + * @member {object} + * @private + */ + _this.font = style.font; // run font setter + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = text; + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + * @private + */ + _this._maxWidth = 0; + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + * @private + */ + _this._maxLineHeight = 0; + + /** + * Text anchor. read-only + * + * @member {PIXI.ObservablePoint} + * @private + */ + _this._anchor = new _ObservablePoint2.default(function () { + _this.dirty = true; + }, _this, 0, 0); + + /** + * The dirty state of this object. + * + * @member {boolean} + */ + _this.dirty = false; + + _this.updateText(); + return _this; + } + + /** + * Renders text and updates it when needed + * + * @private + */ + + + BitmapText.prototype.updateText = function updateText() { + var data = BitmapText.fonts[this._font.name]; + var scale = this._font.size / data.size; + var pos = new core.Point(); + var chars = []; + var lineWidths = []; + + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastSpace = -1; + var lastSpaceWidth = 0; + var spacesRemoved = 0; + var maxLineHeight = 0; + + for (var i = 0; i < this.text.length; i++) { + var charCode = this.text.charCodeAt(i); + + if (/(\s)/.test(this.text.charAt(i))) { + lastSpace = i; + lastSpaceWidth = lastLineWidth; + } + + if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) { + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + if (lastSpace !== -1 && this._maxWidth > 0 && pos.x * scale > this._maxWidth) { + core.utils.removeItems(chars, lastSpace - spacesRemoved, i - lastSpace); + i = lastSpace; + lastSpace = -1; + ++spacesRemoved; + + lineWidths.push(lastSpaceWidth); + maxLineWidth = Math.max(maxLineWidth, lastSpaceWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + var charData = data.chars[charCode]; + + if (!charData) { + continue; + } + + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + + chars.push({ + texture: charData.texture, + line: line, + charCode: charCode, + position: new core.Point(pos.x + charData.xOffset, pos.y + charData.yOffset) + }); + lastLineWidth = pos.x + (charData.texture.width + charData.xOffset); + pos.x += charData.xAdvance; + maxLineHeight = Math.max(maxLineHeight, charData.yOffset + charData.texture.height); + prevCharCode = charCode; + } + + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + + var lineAlignOffsets = []; + + for (var _i = 0; _i <= line; _i++) { + var alignOffset = 0; + + if (this._font.align === 'right') { + alignOffset = maxLineWidth - lineWidths[_i]; + } else if (this._font.align === 'center') { + alignOffset = (maxLineWidth - lineWidths[_i]) / 2; + } + + lineAlignOffsets.push(alignOffset); + } + + var lenChars = chars.length; + var tint = this.tint; + + for (var _i2 = 0; _i2 < lenChars; _i2++) { + var c = this._glyphs[_i2]; // get the next glyph sprite + + if (c) { + c.texture = chars[_i2].texture; + } else { + c = new core.Sprite(chars[_i2].texture); + this._glyphs.push(c); + } + + c.position.x = (chars[_i2].position.x + lineAlignOffsets[chars[_i2].line]) * scale; + c.position.y = chars[_i2].position.y * scale; + c.scale.x = c.scale.y = scale; + c.tint = tint; + + if (!c.parent) { + this.addChild(c); + } + } + + // remove unnecessary children. + for (var _i3 = lenChars; _i3 < this._glyphs.length; ++_i3) { + this.removeChild(this._glyphs[_i3]); + } + + this._textWidth = maxLineWidth * scale; + this._textHeight = (pos.y + data.lineHeight) * scale; + + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + for (var _i4 = 0; _i4 < lenChars; _i4++) { + this._glyphs[_i4].x -= this._textWidth * this.anchor.x; + this._glyphs[_i4].y -= this._textHeight * this.anchor.y; + } + } + this._maxLineHeight = maxLineHeight * scale; + }; + + /** + * Updates the transform of this object + * + * @private + */ + + + BitmapText.prototype.updateTransform = function updateTransform() { + this.validate(); + this.containerUpdateTransform(); + }; + + /** + * Validates text before calling parent's getLocalBounds + * + * @return {PIXI.Rectangle} The rectangular bounding area + */ + + + BitmapText.prototype.getLocalBounds = function getLocalBounds() { + this.validate(); + + return _core$Container.prototype.getLocalBounds.call(this); + }; + + /** + * Updates text when needed + * + * @private + */ + + + BitmapText.prototype.validate = function validate() { + if (this.dirty) { + this.updateText(); + this.dirty = false; + } + }; + + /** + * The tint of the BitmapText object + * + * @member {number} + */ + + + /** + * Register a bitmap font with data and a texture. + * + * @static + * @param {XMLDocument} xml - The XML document data. + * @param {PIXI.Texture} texture - Texture with all symbols. + * @return {Object} Result font object with font, size, lineHeight and char fields. + */ + BitmapText.registerFont = function registerFont(xml, texture) { + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + var res = texture.baseTexture.resolution || _settings2.default.RESOLUTION; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) / res; + data.chars = {}; + + // parse letters + var letters = xml.getElementsByTagName('char'); + + for (var i = 0; i < letters.length; i++) { + var letter = letters[i]; + var charCode = parseInt(letter.getAttribute('id'), 10); + + var textureRect = new core.Rectangle(parseInt(letter.getAttribute('x'), 10) / res + texture.frame.x / res, parseInt(letter.getAttribute('y'), 10) / res + texture.frame.y / res, parseInt(letter.getAttribute('width'), 10) / res, parseInt(letter.getAttribute('height'), 10) / res); + + data.chars[charCode] = { + xOffset: parseInt(letter.getAttribute('xoffset'), 10) / res, + yOffset: parseInt(letter.getAttribute('yoffset'), 10) / res, + xAdvance: parseInt(letter.getAttribute('xadvance'), 10) / res, + kerning: {}, + texture: new core.Texture(texture.baseTexture, textureRect) + + }; + } + + // parse kernings + var kernings = xml.getElementsByTagName('kerning'); + + for (var _i5 = 0; _i5 < kernings.length; _i5++) { + var kerning = kernings[_i5]; + var first = parseInt(kerning.getAttribute('first'), 10) / res; + var second = parseInt(kerning.getAttribute('second'), 10) / res; + var amount = parseInt(kerning.getAttribute('amount'), 10) / res; + + if (data.chars[second]) { + data.chars[second].kerning[first] = amount; + } + } + + // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 + // but it's very likely to change + BitmapText.fonts[data.font] = data; + + return data; + }; + + _createClass(BitmapText, [{ + key: 'tint', + get: function get() { + return this._font.tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.tint = typeof value === 'number' && value >= 0 ? value : 0xFFFFFF; + + this.dirty = true; + } + + /** + * The alignment of the BitmapText object + * + * @member {string} + * @default 'left' + */ + + }, { + key: 'align', + get: function get() { + return this._font.align; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.align = value || 'left'; + + this.dirty = true; + } + + /** + * The anchor sets the origin point of the text. + * The default is 0,0 this means the text's origin is the top left + * Setting the anchor to 0.5,0.5 means the text's origin is centered + * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner + * + * @member {PIXI.Point | number} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (typeof value === 'number') { + this._anchor.set(value); + } else { + this._anchor.copy(value); + } + } + + /** + * The font descriptor of the BitmapText object + * + * @member {string|object} + */ + + }, { + key: 'font', + get: function get() { + return this._font; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (!value) { + return; + } + + if (typeof value === 'string') { + value = value.split(' '); + + this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); + this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; + } else { + this._font.name = value.name; + this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); + } + + this.dirty = true; + } + + /** + * The text of the BitmapText object + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + value = value.toString() || ' '; + if (this._text === value) { + return; + } + this._text = value; + this.dirty = true; + } + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + */ + + }, { + key: 'maxWidth', + get: function get() { + return this._maxWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._maxWidth === value) { + return; + } + this._maxWidth = value; + this.dirty = true; + } + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + * @readonly + */ + + }, { + key: 'maxLineHeight', + get: function get() { + this.validate(); + + return this._maxLineHeight; + } + + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textWidth', + get: function get() { + this.validate(); + + return this._textWidth; + } + + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textHeight', + get: function get() { + this.validate(); + + return this._textHeight; + } + }]); + + return BitmapText; +}(core.Container); + +exports.default = BitmapText; + + +BitmapText.fonts = {}; + +},{"../core":64,"../core/math/ObservablePoint":67,"../core/settings":100}],135:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Matrix = require('../core/math/Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var tempMat = new _Matrix2.default(); + +/** + * class controls uv transform and frame clamp for texture + * + * @class + * @memberof PIXI.extras + */ + +var TextureTransform = function () { + /** + * + * @param {PIXI.Texture} texture observed texture + * @param {number} [clampMargin] Changes frame clamping, 0.5 by default. Use -0.5 for extra border. + * @constructor + */ + function TextureTransform(texture, clampMargin) { + _classCallCheck(this, TextureTransform); + + this._texture = texture; + + this.mapCoord = new _Matrix2.default(); + + this.uClampFrame = new Float32Array(4); + + this.uClampOffset = new Float32Array(2); + + this._lastTextureID = -1; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders + * + * @default 0 + * @member {number} + */ + this.clampOffset = 0; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + this.clampMargin = typeof clampMargin === 'undefined' ? 0.5 : clampMargin; + } + + /** + * texture property + * @member {PIXI.Texture} + */ + + + /** + * Multiplies uvs array to transform + * @param {Float32Array} uvs mesh uvs + * @param {Float32Array} [out=uvs] output + * @returns {Float32Array} output + */ + TextureTransform.prototype.multiplyUvs = function multiplyUvs(uvs, out) { + if (out === undefined) { + out = uvs; + } + + var mat = this.mapCoord; + + for (var i = 0; i < uvs.length; i += 2) { + var x = uvs[i]; + var y = uvs[i + 1]; + + out[i] = x * mat.a + y * mat.c + mat.tx; + out[i + 1] = x * mat.b + y * mat.d + mat.ty; + } + + return out; + }; + + /** + * updates matrices if texture was changed + * @param {boolean} forceUpdate if true, matrices will be updated any case + * @returns {boolean} whether or not it was updated + */ + + + TextureTransform.prototype.update = function update(forceUpdate) { + var tex = this._texture; + + if (!tex || !tex.valid) { + return false; + } + + if (!forceUpdate && this._lastTextureID === tex._updateID) { + return false; + } + + this._lastTextureID = tex._updateID; + + var uvs = tex._uvs; + + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + + var orig = tex.orig; + var trim = tex.trim; + + if (trim) { + tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat); + } + + var texBase = tex.baseTexture; + var frame = this.uClampFrame; + var margin = this.clampMargin / texBase.resolution; + var offset = this.clampOffset; + + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.uClampOffset[0] = offset / texBase.realWidth; + this.uClampOffset[1] = offset / texBase.realHeight; + + return true; + }; + + _createClass(TextureTransform, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._texture = value; + this._lastTextureID = -1; + } + }]); + + return TextureTransform; +}(); + +exports.default = TextureTransform; + +},{"../core/math/Matrix":66}],136:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CanvasTinter = require('../core/sprites/canvas/CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +var _TextureTransform = require('./TextureTransform'); + +var _TextureTransform2 = _interopRequireDefault(_TextureTransform); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); + +/** + * A tiling sprite is a fast way of rendering a tiling image + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ + +var TilingSprite = function (_core$Sprite) { + _inherits(TilingSprite, _core$Sprite); + + /** + * @param {PIXI.Texture} texture - the texture of the tiling sprite + * @param {number} [width=100] - the width of the tiling sprite + * @param {number} [height=100] - the height of the tiling sprite + */ + function TilingSprite(texture) { + var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100; + + _classCallCheck(this, TilingSprite); + + /** + * Tile transform + * + * @member {PIXI.TransformStatic} + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, texture)); + + _this.tileTransform = new core.TransformStatic(); + + // /// private + + /** + * The with of the tiling sprite + * + * @member {number} + * @private + */ + _this._width = width; + + /** + * The height of the tiling sprite + * + * @member {number} + * @private + */ + _this._height = height; + + /** + * Canvas pattern + * + * @type {CanvasPattern} + * @private + */ + _this._canvasPattern = null; + + /** + * transform that is applied to UV to get the texture coords + * + * @member {PIXI.extras.TextureTransform} + */ + _this.uvTransform = texture.transform || new _TextureTransform2.default(texture); + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' method. + * + * @member {string} + * @default 'tilingSprite' + */ + _this.pluginName = 'tilingSprite'; + + /** + * Whether or not anchor affects uvs + * + * @member {boolean} + * @default false + */ + _this.uvRespectAnchor = false; + return _this; + } + /** + * Changes frame clamping in corresponding textureTransform, shortcut + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + + + /** + * @private + */ + TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate() { + if (this.uvTransform) { + this.uvTransform.texture = this._texture; + } + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + TilingSprite.prototype._renderWebGL = function _renderWebGL(renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + + if (!texture || !texture.valid) { + return; + } + + this.tileTransform.updateLocalTransform(); + this.uvTransform.update(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer + */ + + + TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { + var texture = this._texture; + + if (!texture.baseTexture.hasLoaded) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var resolution = renderer.resolution; + var baseTexture = texture.baseTexture; + var baseTextureResolution = baseTexture.resolution; + var modX = this.tilePosition.x / this.tileScale.x % texture._frame.width * baseTextureResolution; + var modY = this.tilePosition.y / this.tileScale.y % texture._frame.height * baseTextureResolution; + + // create a nice shiny pattern! + // TODO this needs to be refreshed if texture changes.. + if (!this._canvasPattern) { + // cut an object from a spritesheet.. + var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height, baseTextureResolution); + + // Tint the tiling sprite + if (this.tint !== 0xFFFFFF) { + if (this.cachedTint !== this.tint) { + this.cachedTint = this.tint; + + this.tintedTexture = _CanvasTinter2.default.getTintedTexture(this, this.tint); + } + tempCanvas.context.drawImage(this.tintedTexture, 0, 0); + } else { + tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x * baseTextureResolution, -texture._frame.y * baseTextureResolution); + } + this._canvasPattern = tempCanvas.context.createPattern(tempCanvas.canvas, 'repeat'); + } + + // set context state.. + context.globalAlpha = this.worldAlpha; + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + renderer.setBlendMode(this.blendMode); + + // fill the pattern! + context.fillStyle = this._canvasPattern; + + // TODO - this should be rolled into the setTransform above.. + context.scale(this.tileScale.x / baseTextureResolution, this.tileScale.y / baseTextureResolution); + + var anchorX = this.anchor.x * -this._width; + var anchorY = this.anchor.y * -this._height; + + if (this.uvRespectAnchor) { + context.translate(modX, modY); + + context.fillRect(-modX + anchorX, -modY + anchorY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } else { + context.translate(modX + anchorX, modY + anchorY); + + context.fillRect(-modX, -modY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } + }; + + /** + * Updates the bounds of the tiling sprite. + * + * @private + */ + + + TilingSprite.prototype._calculateBounds = function _calculateBounds() { + var minX = this._width * -this._anchor._x; + var minY = this._height * -this._anchor._y; + var maxX = this._width * (1 - this._anchor._x); + var maxY = this._height * (1 - this._anchor._y); + + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + TilingSprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._width * -this._anchor._x; + this._bounds.minY = this._height * -this._anchor._y; + this._bounds.maxX = this._width * (1 - this._anchor._x); + this._bounds.maxY = this._height * (1 - this._anchor._x); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new core.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _core$Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Checks if a point is inside this tiling sprite. + * + * @param {PIXI.Point} point - the point to check + * @return {boolean} Whether or not the sprite contains the point. + */ + + + TilingSprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor._x; + + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + var y1 = -height * this.anchor._y; + + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + TilingSprite.prototype.destroy = function destroy(options) { + _core$Sprite.prototype.destroy.call(this, options); + + this.tileTransform = null; + this.uvTransform = null; + }; + + /** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.Texture} The newly created texture + */ + + + TilingSprite.from = function from(source, width, height) { + return new TilingSprite(core.Texture.from(source), width, height); + }; + + /** + * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId + */ + + + TilingSprite.fromFrame = function fromFrame(frameId, width, height) { + var texture = core.utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this); + } + + return new TilingSprite(texture, width, height); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @param {boolean} [crossorigin] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id + */ + + + TilingSprite.fromImage = function fromImage(imageId, width, height, crossorigin, scaleMode) { + return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode), width, height); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(TilingSprite, [{ + key: 'clampMargin', + get: function get() { + return this.uvTransform.clampMargin; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uvTransform.clampMargin = value; + this.uvTransform.update(true); + } + + /** + * The scaling of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tileScale', + get: function get() { + return this.tileTransform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.scale.copy(value); + } + + /** + * The offset of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tilePosition', + get: function get() { + return this.tileTransform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.position.copy(value); + } + }, { + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + } + + /** + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + } + }]); + + return TilingSprite; +}(core.Sprite); + +exports.default = TilingSprite; + +},{"../core":64,"../core/sprites/canvas/CanvasTinter":103,"./TextureTransform":135}],137:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _BaseTexture = require('../core/textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _utils = require('../core/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DisplayObject = core.DisplayObject; +var _tempMatrix = new core.Matrix(); + +DisplayObject.prototype._cacheAsBitmap = false; +DisplayObject.prototype._cacheData = false; + +// figured theres no point adding ALL the extra variables to prototype. +// this model can hold the information needed. This can also be generated on demand as +// most objects are not cached as bitmaps. +/** + * @class + * @ignore + */ + +var CacheData = +/** + * + */ +function CacheData() { + _classCallCheck(this, CacheData); + + this.textureCacheId = null; + + this.originalRenderWebGL = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + + this.originalUpdateTransform = null; + this.originalHitTest = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.sprite = null; +}; + +Object.defineProperties(DisplayObject.prototype, { + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to 'false' + * + * IMPORTANT GOTCHA - make sure that all your textures are preloaded BEFORE setting this property to true + * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function get() { + return this._cacheAsBitmap; + }, + set: function set(value) { + if (this._cacheAsBitmap === value) { + return; + } + + this._cacheAsBitmap = value; + + var data = void 0; + + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + + data = this._cacheData; + + data.originalRenderWebGL = this.renderWebGL; + data.originalRenderCanvas = this.renderCanvas; + + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this._calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + + data.originalDestroy = this.destroy; + + data.originalContainsPoint = this.containsPoint; + + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + + this.renderWebGL = this._renderCachedWebGL; + this.renderCanvas = this._renderCachedCanvas; + + this.destroy = this._cacheAsBitmapDestroy; + } else { + data = this._cacheData; + + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + + this.renderWebGL = data.originalRenderWebGL; + this.renderCanvas = data.originalRenderCanvas; + this._calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + + this.destroy = data.originalDestroy; + + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + } + } +}); + +/** + * Renders a cached version of the sprite with WebGL + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedWebGL = function _renderCachedWebGL(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObject(renderer); + + this._cacheData.sprite._transformID = -1; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderWebGL(renderer); +}; + +/** + * Prepares the WebGL renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + + this.alpha = 1; + + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.currentRenderer.flush(); + // this.filters= []; + + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds().clone(); + + // add some padding! + if (this._filters) { + var padding = this._filters[0].padding; + + bounds.pad(padding); + } + + // for now we cache the current renderTarget that the webGL renderer is currently using. + // this could be more elegent.. + var cachedRenderTarget = renderer._activeRenderTarget; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + var stack = renderer.filterManager.filterStack; + + // this renderTexture will be used to store the cached DisplayObject + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); + + this._cacheData.textureCacheId = textureCacheId; + + _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); + _Texture2.default.addToCache(renderTexture, textureCacheId); + + // need to set // + var m = _tempMatrix; + + m.tx = -bounds.x; + m.ty = -bounds.y; + + // reset + this.transform.worldTransform.identity(); + + // set all properties to there original so we can render to a texture + this.renderWebGL = this._cacheData.originalRenderWebGL; + + renderer.render(this, renderTexture, true, m, true); + // now restore the state be setting the new properties + + renderer.bindRenderTarget(cachedRenderTarget); + + renderer.filterManager.filterStack = stack; + + this.renderWebGL = this._renderCachedWebGL; + this.updateTransform = this.displayObjectUpdateTransform; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + + // easy bounds.. + this._calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + + this._cacheData.sprite = cachedSprite; + + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this.updateTransform(); + } + + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Renders a cached version of the sprite with canvas + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObjectCanvas(renderer); + + this._cacheData.sprite.worldAlpha = this.worldAlpha; + + this._cacheData.sprite.renderCanvas(renderer); +}; + +// TODO this can be the same as the webGL verison.. will need to do a little tweaking first though.. +/** + * Prepares the Canvas renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(); + + var cacheAlpha = this.alpha; + + this.alpha = 1; + + var cachedRenderTarget = renderer.context; + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); + + this._cacheData.textureCacheId = textureCacheId; + + _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); + _Texture2.default.addToCache(renderTexture, textureCacheId); + + // need to set // + var m = _tempMatrix; + + this.transform.localTransform.copy(m); + m.invert(); + + m.tx -= bounds.x; + m.ty -= bounds.y; + + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + + // renderTexture.render(this, m, true); + renderer.render(this, renderTexture, true, m, false); + + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + + this.renderCanvas = this._renderCachedCanvas; + this._calculateBounds = this._calculateCachedBounds; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite._bounds = this._bounds; + cachedSprite.alpha = cacheAlpha; + + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this.updateTransform(); + } + + this.updateTransform = this.displayObjectUpdateTransform; + + this._cacheData.sprite = cachedSprite; + + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Calculates the bounds of the cached sprite + * + * @private + */ +DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._cacheData.sprite._calculateBounds(); +}; + +/** + * Gets the bounds of the cached sprite. + * + * @private + * @return {Rectangle} The local bounds. + */ +DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(); +}; + +/** + * Destroys the cached sprite. + * + * @private + */ +DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; + + _BaseTexture2.default.removeFromCache(this._cacheData.textureCacheId); + _Texture2.default.removeFromCache(this._cacheData.textureCacheId); + + this._cacheData.textureCacheId = null; +}; + +/** + * Destroys the cached object. + * + * @private + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * Used when destroying containers, see the Container.destroy method. + */ +DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { + this.cacheAsBitmap = false; + this.destroy(options); +}; + +},{"../core":64,"../core/textures/BaseTexture":111,"../core/textures/Texture":114,"../core/utils":123}],138:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * The instance name of the object. + * + * @memberof PIXI.DisplayObject# + * @member {string} + */ +core.DisplayObject.prototype.name = null; + +/** + * Returns the display object in the container + * + * @memberof PIXI.Container# + * @param {string} name - instance name + * @return {PIXI.DisplayObject} The child with the specified name. + */ +core.Container.prototype.getChildByName = function getChildByName(name) { + for (var i = 0; i < this.children.length; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + + return null; +}; + +},{"../core":64}],139:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. + * + * @memberof PIXI.DisplayObject# + * @param {Point} point - the point to write the global value to. If null a new point will be returned + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @return {Point} The updated point + */ +core.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition() { + var point = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new core.Point(); + var skipUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (this.parent) { + this.parent.toGlobal(this.position, point, skipUpdate); + } else { + point.x = this.position.x; + point.y = this.position.y; + } + + return point; +}; + +},{"../core":64}],140:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BitmapText = exports.TilingSpriteRenderer = exports.TilingSprite = exports.TextureTransform = exports.AnimatedSprite = undefined; + +var _AnimatedSprite = require('./AnimatedSprite'); + +Object.defineProperty(exports, 'AnimatedSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AnimatedSprite).default; + } +}); + +var _TextureTransform = require('./TextureTransform'); + +Object.defineProperty(exports, 'TextureTransform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureTransform).default; + } +}); + +var _TilingSprite = require('./TilingSprite'); + +Object.defineProperty(exports, 'TilingSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSprite).default; + } +}); + +var _TilingSpriteRenderer = require('./webgl/TilingSpriteRenderer'); + +Object.defineProperty(exports, 'TilingSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSpriteRenderer).default; + } +}); + +var _BitmapText = require('./BitmapText'); + +Object.defineProperty(exports, 'BitmapText', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BitmapText).default; + } +}); + +require('./cacheAsBitmap'); + +require('./getChildByName'); + +require('./getGlobalPosition'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// imported for side effect of extending the prototype only, contains no exports + +},{"./AnimatedSprite":133,"./BitmapText":134,"./TextureTransform":135,"./TilingSprite":136,"./cacheAsBitmap":137,"./getChildByName":138,"./getGlobalPosition":139,"./webgl/TilingSpriteRenderer":141}],141:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _const = require('../../core/const'); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMat = new core.Matrix(); + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI.extras + * @extends PIXI.ObjectRenderer + */ + +var TilingSpriteRenderer = function (_core$ObjectRenderer) { + _inherits(TilingSpriteRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function TilingSpriteRenderer(renderer) { + _classCallCheck(this, TilingSpriteRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + _this.simpleShader = null; + _this.quad = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + TilingSpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n gl_FragColor = sample * color ;\n}\n'); + this.simpleShader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n gl_FragColor = sample * color;\n}\n'); + + this.renderer.bindVao(null); + this.quad = new core.Quad(gl, this.renderer.state.attribState); + this.quad.initVao(this.shader); + }; + + /** + * + * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered + */ + + + TilingSpriteRenderer.prototype.render = function render(ts) { + var renderer = this.renderer; + var quad = this.quad; + + renderer.bindVao(quad.vao); + + var vertices = quad.vertices; + + vertices[0] = vertices[6] = ts._width * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + + vertices[2] = vertices[4] = ts._width * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + + if (ts.uvRespectAnchor) { + vertices = quad.uvs; + + vertices[0] = vertices[6] = -ts.anchor.x; + vertices[1] = vertices[3] = -ts.anchor.y; + + vertices[2] = vertices[4] = 1.0 - ts.anchor.x; + vertices[5] = vertices[7] = 1.0 - ts.anchor.y; + } + + quad.upload(); + + var tex = ts._texture; + var baseTex = tex.baseTexture; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvTransform; + var isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === _const.WRAP_MODES.CLAMP) { + baseTex.wrapMode = _const.WRAP_MODES.REPEAT; + } + } else { + isSimple = baseTex.wrapMode !== _const.WRAP_MODES.CLAMP; + } + } + + var shader = isSimple ? this.simpleShader : this.shader; + + renderer.bindShader(shader); + + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + + tempMat.invert(); + if (isSimple) { + tempMat.prepend(uv.mapCoord); + } else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + + shader.uniforms.uTransform = tempMat.toArray(true); + shader.uniforms.uColor = core.utils.premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, baseTex.premultipliedAlpha); + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + + shader.uniforms.uSampler = renderer.bindTexture(tex); + + renderer.setBlendMode(core.utils.correctBlendMode(ts.blendMode, baseTex.premultipliedAlpha)); + + quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + }; + + return TilingSpriteRenderer; +}(core.ObjectRenderer); + +exports.default = TilingSpriteRenderer; + + +core.WebGLRenderer.registerPlugin('tilingSprite', TilingSpriteRenderer); + +},{"../../core":64,"../../core/const":45,"path":22}],142:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BlurXFilter = require('./BlurXFilter'); + +var _BlurXFilter2 = _interopRequireDefault(_BlurXFilter); + +var _BlurYFilter = require('./BlurYFilter'); + +var _BlurYFilter2 = _interopRequireDefault(_BlurYFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurFilter applies a Gaussian blur to an object. + * The strength of the blur can be set for x- and y-axis separately. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurFilter = function (_core$Filter) { + _inherits(BlurFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this)); + + _this.blurXFilter = new _BlurXFilter2.default(strength, quality, resolution, kernelSize); + _this.blurYFilter = new _BlurYFilter2.default(strength, quality, resolution, kernelSize); + + _this.padding = 0; + _this.resolution = resolution || core.settings.RESOLUTION; + _this.quality = quality || 4; + _this.blur = strength || 8; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + BlurFilter.prototype.apply = function apply(filterManager, input, output) { + var renderTarget = filterManager.getRenderTarget(true); + + this.blurXFilter.apply(filterManager, input, renderTarget, true); + this.blurYFilter.apply(filterManager, renderTarget, output, false); + + filterManager.returnRenderTarget(renderTarget); + }; + + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurFilter, [{ + key: 'blur', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the number of passes for blur. More passes means higher quaility bluring. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'quality', + get: function get() { + return this.blurXFilter.quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.quality = this.blurYFilter.quality = value; + } + + /** + * Sets the strength of the blurX property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurX', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the strength of the blurY property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurY', + get: function get() { + return this.blurYFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + }]); + + return BlurFilter; +}(core.Filter); + +exports.default = BlurFilter; + +},{"../../core":64,"./BlurXFilter":143,"./BlurYFilter":144}],143:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurXFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurXFilter = function (_core$Filter) { + _inherits(BlurXFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurXFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurXFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurXFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.width * (output.size.width / input.size.width); + + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; // / this.passes//Math.pow(1, this.passes); + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 16 + */ + + + _createClass(BlurXFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurXFilter; +}(core.Filter); + +exports.default = BlurXFilter; + +},{"../../core":64,"./generateBlurFragSource":145,"./generateBlurVertSource":146,"./getMaxBlurKernelSize":147}],144:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurYFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurYFilter = function (_core$Filter) { + _inherits(BlurYFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurYFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurYFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurYFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.height * (output.size.height / input.size.height); + + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurYFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurYFilter; +}(core.Filter); + +exports.default = BlurYFilter; + +},{"../../core":64,"./generateBlurFragSource":145,"./generateBlurVertSource":146,"./getMaxBlurKernelSize":147}],145:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateFragBlurSource; +var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] +}; + +var fragTemplate = ['varying vec2 vBlurTexCoords[%size%];', 'uniform sampler2D uSampler;', 'void main(void)', '{', ' gl_FragColor = vec4(0.0);', ' %blur%', '}'].join('\n'); + +function generateFragBlurSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + + var fragSource = fragTemplate; + + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value = void 0; + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + value = i; + + if (i >= halfLength) { + value = kernelSize - i - 1; + } + + blur = blur.replace('%value%', kernel[value]); + + blurLoop += blur; + blurLoop += '\n'; + } + + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize); + + return fragSource; +} + +},{}],146:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateVertBlurSource; +var vertTemplate = ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform float strength;', 'uniform mat3 projectionMatrix;', 'varying vec2 vBlurTexCoords[%size%];', 'void main(void)', '{', 'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);', '%blur%', '}'].join('\n'); + +function generateVertBlurSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + + var vertSource = vertTemplate; + + var blurLoop = ''; + var template = void 0; + // let value; + + if (x) { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } else { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + // value = i; + + // if(i >= halfLength) + // { + // value = kernelSize - i - 1; + // } + + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + '.0'); + + blurLoop += blur; + blurLoop += '\n'; + } + + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize); + + return vertSource; +} + +},{}],147:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = getMaxKernelSize; +function getMaxKernelSize(gl) { + var maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + var kernelSize = 15; + + while (kernelSize > maxVaryings) { + kernelSize -= 2; + } + + return kernelSize; +} + +},{}],148:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var ColorMatrixFilter = function (_core$Filter) { + _inherits(ColorMatrixFilter, _core$Filter); + + /** + * + */ + function ColorMatrixFilter() { + _classCallCheck(this, ColorMatrixFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n')); + + _this.uniforms.m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + _this.alpha = 1; + return _this; + } + + /** + * Transforms current matrix and set the new one + * + * @param {number[]} matrix - 5x4 matrix + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix(matrix) { + var multiply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + var newMatrix = matrix; + + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + + // set the new matrix + this.uniforms.m = newMatrix; + }; + + /** + * Multiplies two mat5's + * + * @private + * @param {number[]} out - 5x4 matrix the receiving matrix + * @param {number[]} a - 5x4 matrix the first operand + * @param {number[]} b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix + */ + + + ColorMatrixFilter.prototype._multiply = function _multiply(out, a, b) { + // Red Channel + out[0] = a[0] * b[0] + a[1] * b[5] + a[2] * b[10] + a[3] * b[15]; + out[1] = a[0] * b[1] + a[1] * b[6] + a[2] * b[11] + a[3] * b[16]; + out[2] = a[0] * b[2] + a[1] * b[7] + a[2] * b[12] + a[3] * b[17]; + out[3] = a[0] * b[3] + a[1] * b[8] + a[2] * b[13] + a[3] * b[18]; + out[4] = a[0] * b[4] + a[1] * b[9] + a[2] * b[14] + a[3] * b[19] + a[4]; + + // Green Channel + out[5] = a[5] * b[0] + a[6] * b[5] + a[7] * b[10] + a[8] * b[15]; + out[6] = a[5] * b[1] + a[6] * b[6] + a[7] * b[11] + a[8] * b[16]; + out[7] = a[5] * b[2] + a[6] * b[7] + a[7] * b[12] + a[8] * b[17]; + out[8] = a[5] * b[3] + a[6] * b[8] + a[7] * b[13] + a[8] * b[18]; + out[9] = a[5] * b[4] + a[6] * b[9] + a[7] * b[14] + a[8] * b[19] + a[9]; + + // Blue Channel + out[10] = a[10] * b[0] + a[11] * b[5] + a[12] * b[10] + a[13] * b[15]; + out[11] = a[10] * b[1] + a[11] * b[6] + a[12] * b[11] + a[13] * b[16]; + out[12] = a[10] * b[2] + a[11] * b[7] + a[12] * b[12] + a[13] * b[17]; + out[13] = a[10] * b[3] + a[11] * b[8] + a[12] * b[13] + a[13] * b[18]; + out[14] = a[10] * b[4] + a[11] * b[9] + a[12] * b[14] + a[13] * b[19] + a[14]; + + // Alpha Channel + out[15] = a[15] * b[0] + a[16] * b[5] + a[17] * b[10] + a[18] * b[15]; + out[16] = a[15] * b[1] + a[16] * b[6] + a[17] * b[11] + a[18] * b[16]; + out[17] = a[15] * b[2] + a[16] * b[7] + a[17] * b[12] + a[18] * b[17]; + out[18] = a[15] * b[3] + a[16] * b[8] + a[17] * b[13] + a[18] * b[18]; + out[19] = a[15] * b[4] + a[16] * b[9] + a[17] * b[14] + a[18] * b[19] + a[19]; + + return out; + }; + + /** + * Create a Float32 Array and normalize the offset component to 0-1 + * + * @private + * @param {number[]} matrix - 5x4 matrix + * @return {number[]} 5x4 matrix with all values between 0-1 + */ + + + ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix(matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + + return m; + }; + + /** + * Adjusts brightness + * + * @param {number} b - value of the brigthness (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.brightness = function brightness(b, multiply) { + var matrix = [b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the matrices in grey scales + * + * @param {number} scale - value of the grey (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.greyscale = function greyscale(scale, multiply) { + var matrix = [scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the black and white matrice. + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite(multiply) { + var matrix = [0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the hue property of the color + * + * @param {number} rotation - in degrees + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.hue = function hue(rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + + var a00 = cosR + (1.0 - cosR) * w; + var a01 = w * (1.0 - cosR) - sqrW * sinR; + var a02 = w * (1.0 - cosR) + sqrW * sinR; + + var a10 = w * (1.0 - cosR) + sqrW * sinR; + var a11 = cosR + w * (1.0 - cosR); + var a12 = w * (1.0 - cosR) - sqrW * sinR; + + var a20 = w * (1.0 - cosR) - sqrW * sinR; + var a21 = w * (1.0 - cosR) + sqrW * sinR; + var a22 = cosR + w * (1.0 - cosR); + + var matrix = [a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * + * @param {number} amount - value of the contrast (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.contrast = function contrast(amount, multiply) { + var v = (amount || 0) + 1; + var o = -128 * (v - 1); + + var matrix = [v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * + * @param {number} amount - The saturation amount (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.saturate = function saturate() { + var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var multiply = arguments[1]; + + var x = amount * 2 / 3 + 1; + var y = (x - 1) * -0.5; + + var matrix = [x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Desaturate image (remove color) + * + * Call the saturate function + * + */ + + + ColorMatrixFilter.prototype.desaturate = function desaturate() // eslint-disable-line no-unused-vars + { + this.saturate(-1); + }; + + /** + * Negative image (inverse of classic rgb matrix) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.negative = function negative(multiply) { + var matrix = [0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Sepia image + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.sepia = function sepia(multiply) { + var matrix = [0.393, 0.7689999, 0.18899999, 0, 0, 0.349, 0.6859999, 0.16799999, 0, 0, 0.272, 0.5339999, 0.13099999, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.technicolor = function technicolor(multiply) { + var matrix = [1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Polaroid filter + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.polaroid = function polaroid(multiply) { + var matrix = [1.438, -0.062, -0.062, 0, 0, -0.122, 1.378, -0.122, 0, 0, -0.016, -0.016, 1.483, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Filter who transforms : Red -> Blue and Blue -> Red + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.toBGR = function toBGR(multiply) { + var matrix = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.kodachrome = function kodachrome(multiply) { + var matrix = [1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Brown delicious browni filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.browni = function browni(multiply) { + var matrix = [0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Vintage filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.vintage = function vintage(multiply) { + var matrix = [0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * + * @param {number} desaturation - Tone values. + * @param {number} toned - Tone values. + * @param {string} lightColor - Tone values, example: `0xFFE580` + * @param {string} darkColor - Tone values, example: `0xFFE580` + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.colorTone = function colorTone(desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + + var lR = (lightColor >> 16 & 0xFF) / 255; + var lG = (lightColor >> 8 & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + + var dR = (darkColor >> 16 & 0xFF) / 255; + var dG = (darkColor >> 8 & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + + var matrix = [0.3, 0.59, 0.11, 0, 0, lR, lG, lB, desaturation, 0, dR, dG, dB, toned, 0, lR - dR, lG - dG, lB - dB, 0, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Night effect + * + * @param {number} intensity - The intensity of the night effect. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.night = function night(intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [intensity * -2.0, -intensity, 0, 0, 0, -intensity, 0, intensity, 0, 0, 0, intensity, intensity * 2.0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * + * @param {number} amount - how much the predator feels his future victim + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.predator = function predator(amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * LSD effect + * + * Multiply the current matrix + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.lsd = function lsd(multiply) { + var matrix = [2, -0.4, 0.5, 0, 0, -0.5, 2, -0.4, 0, 0, -0.4, -0.5, 3, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Erase the current matrix by setting the default one + * + */ + + + ColorMatrixFilter.prototype.reset = function reset() { + var matrix = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, false); + }; + + /** + * The matrix of the color matrix filter + * + * @member {number[]} + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + + + _createClass(ColorMatrixFilter, [{ + key: 'matrix', + get: function get() { + return this.uniforms.m; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.m = value; + } + + /** + * The opacity value to use when mixing the original and resultant colors. + * + * When the value is 0, the original color is used without modification. + * When the value is 1, the result color is used. + * When in the range (0, 1) the color is interpolated between the original and result by this amount. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'alpha', + get: function get() { + return this.uniforms.uAlpha; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uAlpha = value; + } + }]); + + return ColorMatrixFilter; +}(core.Filter); + +// Americanized alias + + +exports.default = ColorMatrixFilter; +ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + +},{"../../core":64,"path":22}],149:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. You can + * use this filter to apply all manor of crazy warping effects. Currently the r + * property of the texture is used to offset the x and the g property of the texture + * is used to offset the y. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var DisplacementFilter = function (_core$Filter) { + _inherits(DisplacementFilter, _core$Filter); + + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param {number} scale - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + _classCallCheck(this, DisplacementFilter); + + var maskMatrix = new core.Matrix(); + + sprite.renderable = false; + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n')); + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + + _this.uniforms.mapSampler = sprite._texture; + _this.uniforms.filterMatrix = maskMatrix; + _this.uniforms.scale = { x: 1, y: 1 }; + + if (scale === null || scale === undefined) { + scale = 20; + } + + _this.scale = new core.Point(scale, scale); + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + DisplacementFilter.prototype.apply = function apply(filterManager, input, output) { + var ratio = 1 / output.destinationFrame.width * (output.size.width / input.size.width); + + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x * ratio; + this.uniforms.scale.y = this.scale.y * ratio; + + // draw the filter... + filterManager.applyFilter(this, input, output); + }; + + /** + * The texture used for the displacement map. Must be power of 2 sized texture. + * + * @member {PIXI.Texture} + */ + + + _createClass(DisplacementFilter, [{ + key: 'map', + get: function get() { + return this.uniforms.mapSampler; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.mapSampler = value; + } + }]); + + return DisplacementFilter; +}(core.Filter); + +exports.default = DisplacementFilter; + +},{"../../core":64,"path":22}],150:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * Basic FXAA implementation based on the code on geeks3d.com with the + * modification that the texture2DLod stuff was removed since it's + * unsupported by WebGL. + * + * @see https://github.com/mitsuhiko/webgl-meincraft + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + * + */ +var FXAAFilter = function (_core$Filter) { + _inherits(FXAAFilter, _core$Filter); + + /** + * + */ + function FXAAFilter() { + _classCallCheck(this, FXAAFilter); + + // TODO - needs work + return _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + '\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}', + // fragment shader + 'varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n')); + } + + return FXAAFilter; +}(core.Filter); + +exports.default = FXAAFilter; + +},{"../../core":64,"path":22}],151:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _FXAAFilter = require('./fxaa/FXAAFilter'); + +Object.defineProperty(exports, 'FXAAFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_FXAAFilter).default; + } +}); + +var _NoiseFilter = require('./noise/NoiseFilter'); + +Object.defineProperty(exports, 'NoiseFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NoiseFilter).default; + } +}); + +var _DisplacementFilter = require('./displacement/DisplacementFilter'); + +Object.defineProperty(exports, 'DisplacementFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplacementFilter).default; + } +}); + +var _BlurFilter = require('./blur/BlurFilter'); + +Object.defineProperty(exports, 'BlurFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurFilter).default; + } +}); + +var _BlurXFilter = require('./blur/BlurXFilter'); + +Object.defineProperty(exports, 'BlurXFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurXFilter).default; + } +}); + +var _BlurYFilter = require('./blur/BlurYFilter'); + +Object.defineProperty(exports, 'BlurYFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurYFilter).default; + } +}); + +var _ColorMatrixFilter = require('./colormatrix/ColorMatrixFilter'); + +Object.defineProperty(exports, 'ColorMatrixFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ColorMatrixFilter).default; + } +}); + +var _VoidFilter = require('./void/VoidFilter'); + +Object.defineProperty(exports, 'VoidFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VoidFilter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./blur/BlurFilter":142,"./blur/BlurXFilter":143,"./blur/BlurYFilter":144,"./colormatrix/ColorMatrixFilter":148,"./displacement/DisplacementFilter":149,"./fxaa/FXAAFilter":150,"./noise/NoiseFilter":152,"./void/VoidFilter":153}],152:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Vico @vicocotea + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + */ + +/** + * A Noise effect filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var NoiseFilter = function (_core$Filter) { + _inherits(NoiseFilter, _core$Filter); + + /** + * @param {number} noise - The noise intensity, should be a normalized value in the range [0, 1]. + * @param {number} seed - A random seed for the noise generation. Default is `Math.random()`. + */ + function NoiseFilter() { + var noise = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0.5; + var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Math.random(); + + _classCallCheck(this, NoiseFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n')); + + _this.noise = noise; + _this.seed = seed; + return _this; + } + + /** + * The amount of noise to apply, this value should be in the range (0, 1]. + * + * @member {number} + * @default 0.5 + */ + + + _createClass(NoiseFilter, [{ + key: 'noise', + get: function get() { + return this.uniforms.uNoise; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uNoise = value; + } + + /** + * A seed value to apply to the random noise generation. `Math.random()` is a good value to use. + * + * @member {number} + */ + + }, { + key: 'seed', + get: function get() { + return this.uniforms.uSeed; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uSeed = value; + } + }]); + + return NoiseFilter; +}(core.Filter); + +exports.default = NoiseFilter; + +},{"../../core":64,"path":22}],153:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Does nothing. Very handy. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var VoidFilter = function (_core$Filter) { + _inherits(VoidFilter, _core$Filter); + + /** + * + */ + function VoidFilter() { + _classCallCheck(this, VoidFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n')); + + _this.glShaderKey = 'void'; + return _this; + } + + return VoidFilter; +}(core.Filter); + +exports.default = VoidFilter; + +},{"../../core":64,"path":22}],154:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Holds all information related to an Interaction event + * + * @class + * @memberof PIXI.interaction + */ +var InteractionData = function () { + /** + * + */ + function InteractionData() { + _classCallCheck(this, InteractionData); + + /** + * This point stores the global coords of where the touch/mouse event happened + * + * @member {PIXI.Point} + */ + this.global = new core.Point(); + + /** + * The target DisplayObject that was interacted with + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * When passed to an event handler, this will be the original DOM Event that was captured + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent + * @see https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent + * @member {MouseEvent|TouchEvent|PointerEvent} + */ + this.originalEvent = null; + + /** + * Unique identifier for this interaction + * + * @member {number} + */ + this.identifier = null; + + /** + * Indicates whether or not the pointer device that created the event is the primary pointer. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary + * @type {Boolean} + */ + this.isPrimary = false; + + /** + * Indicates which button was pressed on the mouse or pointer device to trigger the event. + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button + * @type {number} + */ + this.button = 0; + + /** + * Indicates which buttons are pressed on the mouse or pointer device when the event is triggered. + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons + * @type {number} + */ + this.buttons = 0; + + /** + * The width of the pointer's contact along the x-axis, measured in CSS pixels. + * radiusX of TouchEvents will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width + * @type {number} + */ + this.width = 0; + + /** + * The height of the pointer's contact along the y-axis, measured in CSS pixels. + * radiusY of TouchEvents will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height + * @type {number} + */ + this.height = 0; + + /** + * The angle, in degrees, between the pointer device and the screen. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX + * @type {number} + */ + this.tiltX = 0; + + /** + * The angle, in degrees, between the pointer device and the screen. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY + * @type {number} + */ + this.tiltY = 0; + + /** + * The type of pointer that triggered the event. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType + * @type {string} + */ + this.pointerType = null; + + /** + * Pressure applied by the pointing device during the event. A Touch's force property + * will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure + * @type {number} + */ + this.pressure = 0; + + /** + * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch. + * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle + * @type {number} + */ + this.rotationAngle = 0; + + /** + * Twist of a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + * @type {number} + */ + this.twist = 0; + + /** + * Barrel pressure on a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + * @type {number} + */ + this.tangentialPressure = 0; + } + + /** + * The unique identifier of the pointer. It will be the same as `identifier`. + * @readonly + * @member {number} + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId + */ + + + /** + * This will return the local coordinates of the specified displayObject for this InteractionData + * + * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local + * coords off + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative + * to the DisplayObject + */ + InteractionData.prototype.getLocalPosition = function getLocalPosition(displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + + /** + * Copies properties from normalized event data. + * + * @param {Touch|MouseEvent|PointerEvent} event The normalized event data + * @private + */ + + + InteractionData.prototype._copyEvent = function _copyEvent(event) { + // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite + // it with "false" on later events when our shim for it on touch events might not be + // accurate + if (event.isPrimary) { + this.isPrimary = true; + } + this.button = event.button; + this.buttons = event.buttons; + this.width = event.width; + this.height = event.height; + this.tiltX = event.tiltX; + this.tiltY = event.tiltY; + this.pointerType = event.pointerType; + this.pressure = event.pressure; + this.rotationAngle = event.rotationAngle; + this.twist = event.twist || 0; + this.tangentialPressure = event.tangentialPressure || 0; + }; + + /** + * Resets the data for pooling. + * + * @private + */ + + + InteractionData.prototype._reset = function _reset() { + // isPrimary is the only property that we really need to reset - everything else is + // guaranteed to be overwritten + this.isPrimary = false; + }; + + _createClass(InteractionData, [{ + key: 'pointerId', + get: function get() { + return this.identifier; + } + }]); + + return InteractionData; +}(); + +exports.default = InteractionData; + +},{"../core":64}],155:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Event class that mimics native DOM events. + * + * @class + * @memberof PIXI.interaction + */ +var InteractionEvent = function () { + /** + * + */ + function InteractionEvent() { + _classCallCheck(this, InteractionEvent); + + /** + * Whether this event will continue propagating in the tree + * + * @member {boolean} + */ + this.stopped = false; + + /** + * The object which caused this event to be dispatched. + * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}. + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * The object whose event listener’s callback is currently being invoked. + * + * @member {PIXI.DisplayObject} + */ + this.currentTarget = null; + + /** + * Type of the event + * + * @member {string} + */ + this.type = null; + + /** + * InteractionData related to this event + * + * @member {PIXI.interaction.InteractionData} + */ + this.data = null; + } + + /** + * Prevents event from reaching any objects other than the current object. + * + */ + + + InteractionEvent.prototype.stopPropagation = function stopPropagation() { + this.stopped = true; + }; + + /** + * Resets the event. + * + * @private + */ + + + InteractionEvent.prototype._reset = function _reset() { + this.stopped = false; + this.currentTarget = null; + this.target = null; + }; + + return InteractionEvent; +}(); + +exports.default = InteractionEvent; + +},{}],156:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _InteractionData = require('./InteractionData'); + +var _InteractionData2 = _interopRequireDefault(_InteractionData); + +var _InteractionEvent = require('./InteractionEvent'); + +var _InteractionEvent2 = _interopRequireDefault(_InteractionEvent); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +var _InteractionTrackingData2 = _interopRequireDefault(_InteractionTrackingData); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _interactiveTarget = require('./interactiveTarget'); + +var _interactiveTarget2 = _interopRequireDefault(_interactiveTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// Mix interactiveTarget into core.DisplayObject.prototype, after deprecation has been handled +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _interactiveTarget2.default); + +var MOUSE_POINTER_ID = 'MOUSE'; + +// helpers for hitTest() - only used inside hitTest() +var hitTestEvent = { + target: null, + data: { + global: null + } +}; + +/** + * The interaction manager deals with mouse, touch and pointer events. Any DisplayObject can be interactive + * if its interactive parameter is set to true + * This manager also supports multitouch. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.interaction + * + * @class + * @extends EventEmitter + * @memberof PIXI.interaction + */ + +var InteractionManager = function (_EventEmitter) { + _inherits(InteractionManager, _EventEmitter); + + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + * @param {object} [options] - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Frequency increases the interaction events will be checked. + */ + function InteractionManager(renderer, options) { + _classCallCheck(this, InteractionManager); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + options = options || {}; + + /** + * The renderer this interaction manager works for. + * + * @member {PIXI.SystemRenderer} + */ + _this.renderer = renderer; + + /** + * Should default browser actions automatically be prevented. + * Does not apply to pointer events for backwards compatibility + * preventDefault on pointer events stops mouse events from firing + * Thus, for every pointer event, there will always be either a mouse of touch event alongside it. + * + * @member {boolean} + * @default true + */ + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + + /** + * Frequency in milliseconds that the mousemove, moveover & mouseout interaction events will be checked. + * + * @member {number} + * @default 10 + */ + _this.interactionFrequency = options.interactionFrequency || 10; + + /** + * The mouse data + * + * @member {PIXI.interaction.InteractionData} + */ + _this.mouse = new _InteractionData2.default(); + _this.mouse.identifier = MOUSE_POINTER_ID; + + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + + /** + * Actively tracked InteractionData + * + * @private + * @member {Object.} + */ + _this.activeInteractionData = {}; + _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; + + /** + * Pool of unused InteractionData + * + * @private + * @member {PIXI.interation.InteractionData[]} + */ + _this.interactionDataPool = []; + + /** + * An event data object to handle all the event tracking/dispatching + * + * @member {object} + */ + _this.eventData = new _InteractionEvent2.default(); + + /** + * The DOM element to bind to. + * + * @private + * @member {HTMLElement} + */ + _this.interactionDOMElement = null; + + /** + * This property determines if mousemove and touchmove events are fired only when the cursor + * is over the object. + * Setting to true will make things work more in line with how the DOM verison works. + * Setting to false can make things easier for things like dragging + * It is currently set to false as this is how pixi used to work. This will be set to true in + * future versions of pixi. + * + * @member {boolean} + * @default false + */ + _this.moveWhenInside = false; + + /** + * Have events been attached to the dom element? + * + * @private + * @member {boolean} + */ + _this.eventsAdded = false; + + /** + * Is the mouse hovering over the renderer? + * + * @private + * @member {boolean} + */ + _this.mouseOverRenderer = false; + + /** + * Does the device support touch events + * https://www.w3.org/TR/touch-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsTouchEvents = 'ontouchstart' in window; + + /** + * Does the device support pointer events + * https://www.w3.org/Submission/pointer-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsPointerEvents = !!window.PointerEvent; + + // this will make it so that you don't have to call bind all the time + + /** + * @private + * @member {Function} + */ + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerCancel = _this.onPointerCancel.bind(_this); + _this.processPointerCancel = _this.processPointerCancel.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOver = _this.onPointerOver.bind(_this); + + /** + * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor + * values, objects are handled as dictionaries of CSS values for interactionDOMElement, + * and functions are called instead of changing the CSS. + * Default CSS cursor values are provided for 'default' and 'pointer' modes. + * @member {Object.)>} + */ + _this.cursorStyles = { + default: 'inherit', + pointer: 'pointer' + }; + + /** + * The mode of the cursor that is being used. + * The value of this is a key from the cursorStyles dictionary. + * + * @member {string} + */ + _this.currentCursorMode = null; + + /** + * Internal cached let. + * + * @private + * @member {string} + */ + _this.cursor = null; + + /** + * Internal cached let. + * + * @private + * @member {PIXI.Point} + */ + _this._tempPoint = new core.Point(); + + /** + * The current resolution / device pixel ratio. + * + * @member {number} + * @default 1 + */ + _this.resolution = 1; + + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display + * object. + * + * @event PIXI.interaction.InteractionManager#mousedown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * + * @event PIXI.interaction.InteractionManager#rightdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. + * + * @event PIXI.interaction.InteractionManager#mouseup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * + * @event PIXI.interaction.InteractionManager#rightup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. + * + * @event PIXI.interaction.InteractionManager#click + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * + * @event PIXI.interaction.InteractionManager#rightclick + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. + * + * @event PIXI.interaction.InteractionManager#mouseupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. + * + * @event PIXI.interaction.InteractionManager#rightupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * + * @event PIXI.interaction.InteractionManager#mousemove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * + * @event PIXI.interaction.InteractionManager#mouseover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * + * @event PIXI.interaction.InteractionManager#mouseout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * + * @event PIXI.interaction.InteractionManager#pointerdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released over the display object. + * + * @event PIXI.interaction.InteractionManager#pointerup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a pointer event + * + * @event PIXI.interaction.InteractionManager#pointercancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * + * @event PIXI.interaction.InteractionManager#pointertap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}. + * + * @event PIXI.interaction.InteractionManager#pointerupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved while over the display object + * + * @event PIXI.interaction.InteractionManager#pointermove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved onto the display object + * + * @event PIXI.interaction.InteractionManager#pointerover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved off the display object + * + * @event PIXI.interaction.InteractionManager#pointerout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed on the display object. + * + * @event PIXI.interaction.InteractionManager#touchstart + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed from the display object. + * + * @event PIXI.interaction.InteractionManager#touchend + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a touch + * + * @event PIXI.interaction.InteractionManager#touchcancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * + * @event PIXI.interaction.InteractionManager#tap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. + * + * @event PIXI.interaction.InteractionManager#touchendoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is moved along the display object. + * + * @event PIXI.interaction.InteractionManager#touchmove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display. + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mousedown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#click + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightclick + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.DisplayObject#event:mousedown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.DisplayObject#event:rightdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mousemove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a pointer event. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointercancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointertap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointermove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchstart + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchend + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a touch. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchcancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#tap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchendoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is moved along the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchmove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + return _this; + } + + /** + * Hit tests a point against the display tree, returning the first interactive object that is hit. + * + * @param {PIXI.Point} globalPoint - A point to hit test with, in global space. + * @param {PIXI.Container} [root] - The root display object to start from. If omitted, defaults + * to the last rendered root of the associated renderer. + * @return {PIXI.DisplayObject} The hit display object, if any. + */ + + + InteractionManager.prototype.hitTest = function hitTest(globalPoint, root) { + // clear the target for our hit test + hitTestEvent.target = null; + // assign the global point + hitTestEvent.data.global = globalPoint; + // ensure safety of the root + if (!root) { + root = this.renderer._lastObjectRendered; + } + // run the hit test + this.processInteractive(hitTestEvent, root, null, true); + // return our found object - it'll be null if we didn't hit anything + + return hitTestEvent.target; + }; + + /** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate + * another DOM element to receive those events. + * + * @param {HTMLCanvasElement} element - the DOM element which will receive mouse and touch events. + * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). + * @private + */ + + + InteractionManager.prototype.setTargetElement = function setTargetElement(element) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.removeEvents(); + + this.interactionDOMElement = element; + + this.resolution = resolution; + + this.addEvents(); + }; + + /** + * Registers all the DOM events + * + * @private + */ + + + InteractionManager.prototype.addEvents = function addEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.INTERACTION); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; + this.interactionDOMElement.style['-ms-touch-action'] = 'none'; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = 'none'; + } + + /** + * These events are added first, so that if pointer events are normalised, they are fired + * in the same order as non-normalised events. ie. pointer event 1st, mouse / touch 2nd + */ + if (this.supportsPointerEvents) { + window.document.addEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); + // pointerout is fired in addition to pointerup (for touch events) and pointercancel + // we already handle those, so for the purposes of what we do in onPointerOut, we only + // care about the pointerleave event + this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); + window.addEventListener('pointercancel', this.onPointerCancel, true); + window.addEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.addEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); + window.addEventListener('mouseup', this.onPointerUp, true); + } + + // always look directly for touch events so that we can provide original data + // In a future version we should change this to being just a fallback and rely solely on + // PointerEvents whenever available + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); + } + + this.eventsAdded = true; + }; + + /** + * Removes all the DOM events that were previously registered + * + * @private + */ + + + InteractionManager.prototype.removeEvents = function removeEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.remove(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = ''; + this.interactionDOMElement.style['-ms-touch-action'] = ''; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = ''; + } + + if (this.supportsPointerEvents) { + window.document.removeEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); + window.removeEventListener('pointercancel', this.onPointerCancel, true); + window.removeEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.removeEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true); + window.removeEventListener('mouseup', this.onPointerUp, true); + } + + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); + } + + this.interactionDOMElement = null; + + this.eventsAdded = false; + }; + + /** + * Updates the state of interactive objects. + * Invoked by a throttled ticker update from {@link PIXI.ticker.shared}. + * + * @param {number} deltaTime - time delta since last tick + */ + + + InteractionManager.prototype.update = function update(deltaTime) { + this._deltaTime += deltaTime; + + if (this._deltaTime < this.interactionFrequency) { + return; + } + + this._deltaTime = 0; + + if (!this.interactionDOMElement) { + return; + } + + // if the user move the mouse this check has already been done using the mouse move! + if (this.didMove) { + this.didMove = false; + + return; + } + + this.cursor = null; + + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + for (var k in this.activeInteractionData) { + // eslint-disable-next-line no-prototype-builtins + if (this.activeInteractionData.hasOwnProperty(k)) { + var interactionData = this.activeInteractionData[k]; + + if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, true); + } + } + } + + this.setCursorMode(this.cursor); + + // TODO + }; + + /** + * Sets the current cursor mode, handling any callbacks or CSS style changes. + * + * @param {string} mode - cursor mode, a key from the cursorStyles dictionary + */ + + + InteractionManager.prototype.setCursorMode = function setCursorMode(mode) { + mode = mode || 'default'; + // if the mode didn't actually change, bail early + if (this.currentCursorMode === mode) { + return; + } + this.currentCursorMode = mode; + var style = this.cursorStyles[mode]; + + // only do things if there is a cursor style for it + if (style) { + switch (typeof style === 'undefined' ? 'undefined' : _typeof(style)) { + case 'string': + // string styles are handled as cursor CSS + this.interactionDOMElement.style.cursor = style; + break; + case 'function': + // functions are just called, and passed the cursor mode + style(mode); + break; + case 'object': + // if it is an object, assume that it is a dictionary of CSS styles, + // apply it to the interactionDOMElement + Object.assign(this.interactionDOMElement.style, style); + break; + } + } else if (typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) { + // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry + // for the mode, then assume that the dev wants it to be CSS for the cursor. + this.interactionDOMElement.style.cursor = mode; + } + }; + + /** + * Dispatches an event on the display object that was interacted with + * + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the display object in question + * @param {string} eventString - the name of the event (e.g, mousedown) + * @param {object} eventData - the event data object + * @private + */ + + + InteractionManager.prototype.dispatchEvent = function dispatchEvent(displayObject, eventString, eventData) { + if (!eventData.stopped) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + + displayObject.emit(eventString, eventData); + + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } + }; + + /** + * Maps x and y coords from a DOM object and maps them correctly to the pixi view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. + * + * @param {PIXI.Point} point - the point that the result will be stored in + * @param {number} x - the x coord of the position to map + * @param {number} y - the y coord of the position to map + */ + + + InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint(point, x, y) { + var rect = void 0; + + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { x: 0, y: 0, width: 0, height: 0 }; + } else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + + var resolutionMultiplier = navigator.isCocoonJS ? this.resolution : 1.0 / this.resolution; + + point.x = (x - rect.left) * (this.interactionDOMElement.width / rect.width) * resolutionMultiplier; + point.y = (y - rect.top) * (this.interactionDOMElement.height / rect.height) * resolutionMultiplier; + }; + + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that + * is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param {Function} [func] - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point + * @param {boolean} [interactive] - Whether the displayObject is interactive + * @return {boolean} returns true if the displayObject hit the point + */ + + + InteractionManager.prototype.processInteractive = function processInteractive(interactionEvent, displayObject, func, hitTest, interactive) { + if (!displayObject || !displayObject.visible) { + return false; + } + + var point = interactionEvent.data.global; + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + interactive = displayObject.interactive || interactive; + + var hit = false; + var interactiveParent = interactive; + + // if the displayobject has a hitArea, then it does not need to hitTest children. + if (displayObject.hitArea) { + interactiveParent = false; + } + // it has a mask! Then lets hit test that before continuing + else if (hitTest && displayObject._mask) { + if (!displayObject._mask.containsPoint(point)) { + hitTest = false; + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow pixi to completely ignore and bypass checking the displayObjects children. + if (displayObject.interactiveChildren && displayObject.children) { + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + + // time to get recursive.. if this function will return if something is hit.. + var childHit = this.processInteractive(interactionEvent, child, func, hitTest, interactiveParent); + + if (childHit) { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if (!child.parent) { + continue; + } + + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + + if (childHit) { + if (interactionEvent.target) { + hitTest = false; + } + hit = true; + } + } + } + } + + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit - but only if it was interactive, otherwise we need to keep + // looking for an interactive child, just in case we hit one + if (hitTest && !interactionEvent.target) { + if (displayObject.hitArea) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hit = true; + } + } else if (displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = true; + } + } + } + + if (displayObject.interactive) { + if (hit && !interactionEvent.target) { + interactionEvent.target = displayObject; + } + + if (func) { + func(interactionEvent, displayObject, !!hit); + } + } + } + + return hit; + }; + + /** + * Is called when the pointer button is pressed down on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down + */ + + + InteractionManager.prototype.onPointerDown = function onPointerDown(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + /** + * No need to prevent default on natural pointer events, as there are no side effects + * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, + * so still need to be prevented. + */ + + // Guaranteed that there will be at least one event in events, and all events must have the same pointer type + + if (this.autoPreventDefault && events[0].isNormalized) { + originalEvent.preventDefault(); + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerDown, true); + + this.emit('pointerdown', interactionEvent); + if (event.pointerType === 'touch') { + this.emit('touchstart', interactionEvent); + } + // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event + else if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + } + }; + + /** + * Processes the result of the pointer down check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerDown = function processPointerDown(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + + if (hit) { + if (!displayObject.trackedPointers[id]) { + displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchstart', interactionEvent); + } else if (data.pointerType === 'mouse' || data.pointerType === 'pen') { + var isRightButton = data.button === 2; + + if (isRightButton) { + displayObject.trackedPointers[id].rightDown = true; + } else { + displayObject.trackedPointers[id].leftDown = true; + } + + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released + * @param {boolean} cancelled - true if the pointer is cancelled + * @param {Function} func - Function passed to {@link processInteractive} + */ + + + InteractionManager.prototype.onPointerComplete = function onPointerComplete(originalEvent, cancelled, func) { + var events = this.normalizeToPointerData(originalEvent); + + var eventLen = events.length; + + // if the event wasn't targeting our canvas, then consider it to be pointerupoutside + // in all cases (unless it was a pointercancel) + var eventAppend = originalEvent.target !== this.interactionDOMElement ? 'outside' : ''; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + // perform hit testing for events targeting our canvas or cancel events + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, func, cancelled || !eventAppend); + + this.emit(cancelled ? 'pointercancel' : 'pointerup' + eventAppend, interactionEvent); + + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + + this.emit(isRightButton ? 'rightup' + eventAppend : 'mouseup' + eventAppend, interactionEvent); + } else if (event.pointerType === 'touch') { + this.emit(cancelled ? 'touchcancel' : 'touchend' + eventAppend, interactionEvent); + this.releaseInteractionDataForPointerId(event.pointerId, interactionData); + } + } + }; + + /** + * Is called when the pointer button is cancelled + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerCancel = function onPointerCancel(event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') return; + + this.onPointerComplete(event, true, this.processPointerCancel); + }; + + /** + * Processes the result of the pointer cancel check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + */ + + + InteractionManager.prototype.processPointerCancel = function processPointerCancel(interactionEvent, displayObject) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + if (displayObject.trackedPointers[id] !== undefined) { + delete displayObject.trackedPointers[id]; + this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); + + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerUp = function onPointerUp(event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') return; + + this.onPointerComplete(event, false, this.processPointerUp); + }; + + /** + * Processes the result of the pointer up check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerUp = function processPointerUp(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + var trackingData = displayObject.trackedPointers[id]; + + var isTouch = data.pointerType === 'touch'; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + // Mouse only + if (isMouse) { + var isRightButton = data.button === 2; + + var flags = _InteractionTrackingData2.default.FLAGS; + + var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; + + var isDown = trackingData !== undefined && trackingData.flags & test; + + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); + + if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); + } + } else if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); + } + // update the down state of the tracking data + if (trackingData) { + if (isRightButton) { + trackingData.rightDown = false; + } else { + trackingData.leftDown = false; + } + } + } + + // Pointers and Touches, and Mouse + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchend', interactionEvent); + + if (trackingData) { + this.dispatchEvent(displayObject, 'pointertap', interactionEvent); + if (isTouch) { + this.dispatchEvent(displayObject, 'tap', interactionEvent); + // touches are no longer over (if they ever were) when we get the touchend + // so we should ensure that we don't keep pretending that they are + trackingData.over = false; + } + } + } else if (trackingData) { + this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); + } + // Only remove the tracking data if there is no over/down state still associated with it + if (trackingData && trackingData.none) { + delete displayObject.trackedPointers[id]; + } + }; + + /** + * Is called when the pointer moves across the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer moving + */ + + + InteractionManager.prototype.onPointerMove = function onPointerMove(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + if (events[0].pointerType === 'mouse') { + this.didMove = true; + + this.cursor = null; + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + var interactive = event.pointerType === 'touch' ? this.moveWhenInside : true; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerMove, interactive); + this.emit('pointermove', interactionEvent); + if (event.pointerType === 'touch') this.emit('touchmove', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') this.emit('mousemove', interactionEvent); + } + + if (events[0].pointerType === 'mouse') { + this.setCursorMode(this.cursor); + + // TODO BUG for parents interactive object (border order issue) + } + }; + + /** + * Processes the result of the pointer move check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerMove = function processPointerMove(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var isTouch = data.pointerType === 'touch'; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + if (isMouse) { + this.processPointerOverOut(interactionEvent, displayObject, hit); + } + + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchmove', interactionEvent); + if (isMouse) this.dispatchEvent(displayObject, 'mousemove', interactionEvent); + } + }; + + /** + * Is called when the pointer is moved out of the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out + */ + + + InteractionManager.prototype.onPointerOut = function onPointerOut(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOut, so events will always be length 1 + var event = events[0]; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = false; + this.setCursorMode(null); + } + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, false); + + this.emit('pointerout', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseout', interactionEvent); + } else { + // we can get touchleave events after touchend, so we want to make sure we don't + // introduce memory leaks + this.releaseInteractionDataForPointerId(interactionData.identifier); + } + }; + + /** + * Processes the result of the pointer over/out check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerOverOut = function processPointerOverOut(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + var trackingData = displayObject.trackedPointers[id]; + + // if we just moused over the display object, then we need to track that state + if (hit && !trackingData) { + trackingData = displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + + if (trackingData === undefined) return; + + if (hit && this.mouseOverRenderer) { + if (!trackingData.over) { + trackingData.over = true; + this.dispatchEvent(displayObject, 'pointerover', interactionEvent); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseover', interactionEvent); + } + } + + // only change the cursor if it has not already been changed (by something deeper in the + // display tree) + if (isMouse && this.cursor === null) { + this.cursor = displayObject.cursor; + } + } else if (trackingData.over) { + trackingData.over = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseout', interactionEvent); + } + // if there is no mouse down information for the pointer, then it is safe to delete + if (trackingData.none) { + delete displayObject.trackedPointers[id]; + } + } + }; + + /** + * Is called when the pointer is moved into the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view + */ + + + InteractionManager.prototype.onPointerOver = function onPointerOver(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOver, so events will always be length 1 + var event = events[0]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = true; + } + + this.emit('pointerover', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseover', interactionEvent); + } + }; + + /** + * Get InteractionData for a given pointerId. Store that data as well + * + * @private + * @param {PointerEvent} event - Normalized pointer event, output from normalizeToPointerData + * @return {PIXI.interaction.InteractionData} - Interaction data for the given pointer identifier + */ + + + InteractionManager.prototype.getInteractionDataForPointerId = function getInteractionDataForPointerId(event) { + var pointerId = event.pointerId; + + var interactionData = void 0; + + if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { + interactionData = this.mouse; + } else if (this.activeInteractionData[pointerId]) { + interactionData = this.activeInteractionData[pointerId]; + } else { + interactionData = this.interactionDataPool.pop() || new _InteractionData2.default(); + interactionData.identifier = pointerId; + this.activeInteractionData[pointerId] = interactionData; + } + // copy properties from the event, so that we can make sure that touch/pointer specific + // data is available + interactionData._copyEvent(event); + + return interactionData; + }; + + /** + * Return unused InteractionData to the pool, for a given pointerId + * + * @private + * @param {number} pointerId - Identifier from a pointer event + */ + + + InteractionManager.prototype.releaseInteractionDataForPointerId = function releaseInteractionDataForPointerId(pointerId) { + var interactionData = this.activeInteractionData[pointerId]; + + if (interactionData) { + delete this.activeInteractionData[pointerId]; + interactionData._reset(); + this.interactionDataPool.push(interactionData); + } + }; + + /** + * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The event to be configured + * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent + * @param {PIXI.interaction.InteractionData} interactionData - The InteractionData that will be paired + * with the InteractionEvent + * @return {PIXI.interaction.InteractionEvent} the interaction event that was passed in + */ + + + InteractionManager.prototype.configureInteractionEventForDOMEvent = function configureInteractionEventForDOMEvent(interactionEvent, pointerEvent, interactionData) { + interactionEvent.data = interactionData; + + this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); + + // This is the way InteractionManager processed touch events before the refactoring, so I've kept + // it here. But it doesn't make that much sense to me, since mapPositionToPoint already factors + // in this.resolution, so this just divides by this.resolution twice for touch events... + if (navigator.isCocoonJS && pointerEvent.pointerType === 'touch') { + interactionData.global.x = interactionData.global.x / this.resolution; + interactionData.global.y = interactionData.global.y / this.resolution; + } + + // Not really sure why this is happening, but it's how a previous version handled things + if (pointerEvent.pointerType === 'touch') { + pointerEvent.globalX = interactionData.global.x; + pointerEvent.globalY = interactionData.global.y; + } + + interactionData.originalEvent = pointerEvent; + interactionEvent._reset(); + + return interactionEvent; + }; + + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * + * @private + * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event + * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer + * or mouse event, or a multiple normalized pointer events if there are multiple changed touches + */ + + + InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData(event) { + var normalizedEvents = []; + + if (this.supportsTouchEvents && event instanceof TouchEvent) { + for (var i = 0, li = event.changedTouches.length; i < li; i++) { + var touch = event.changedTouches[i]; + + if (typeof touch.button === 'undefined') touch.button = event.touches.length ? 1 : 0; + if (typeof touch.buttons === 'undefined') touch.buttons = event.touches.length ? 1 : 0; + if (typeof touch.isPrimary === 'undefined') { + touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart'; + } + if (typeof touch.width === 'undefined') touch.width = touch.radiusX || 1; + if (typeof touch.height === 'undefined') touch.height = touch.radiusY || 1; + if (typeof touch.tiltX === 'undefined') touch.tiltX = 0; + if (typeof touch.tiltY === 'undefined') touch.tiltY = 0; + if (typeof touch.pointerType === 'undefined') touch.pointerType = 'touch'; + if (typeof touch.pointerId === 'undefined') touch.pointerId = touch.identifier || 0; + if (typeof touch.pressure === 'undefined') touch.pressure = touch.force || 0.5; + touch.twist = 0; + touch.tangentialPressure = 0; + // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven + // support, and the fill ins are not quite the same + // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top + // left is not 0,0 on the page + if (typeof touch.layerX === 'undefined') touch.layerX = touch.offsetX = touch.clientX; + if (typeof touch.layerY === 'undefined') touch.layerY = touch.offsetY = touch.clientY; + + // mark the touch as normalized, just so that we know we did it + touch.isNormalized = true; + + normalizedEvents.push(touch); + } + } + // apparently PointerEvent subclasses MouseEvent, so yay + else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent))) { + if (typeof event.isPrimary === 'undefined') event.isPrimary = true; + if (typeof event.width === 'undefined') event.width = 1; + if (typeof event.height === 'undefined') event.height = 1; + if (typeof event.tiltX === 'undefined') event.tiltX = 0; + if (typeof event.tiltY === 'undefined') event.tiltY = 0; + if (typeof event.pointerType === 'undefined') event.pointerType = 'mouse'; + if (typeof event.pointerId === 'undefined') event.pointerId = MOUSE_POINTER_ID; + if (typeof event.pressure === 'undefined') event.pressure = 0.5; + event.twist = 0; + event.tangentialPressure = 0; + + // mark the mouse event as normalized, just so that we know we did it + event.isNormalized = true; + + normalizedEvents.push(event); + } else { + normalizedEvents.push(event); + } + + return normalizedEvents; + }; + + /** + * Destroys the interaction manager + * + */ + + + InteractionManager.prototype.destroy = function destroy() { + this.removeEvents(); + + this.removeAllListeners(); + + this.renderer = null; + + this.mouse = null; + + this.eventData = null; + + this.interactionDOMElement = null; + + this.onPointerDown = null; + this.processPointerDown = null; + + this.onPointerUp = null; + this.processPointerUp = null; + + this.onPointerCancel = null; + this.processPointerCancel = null; + + this.onPointerMove = null; + this.processPointerMove = null; + + this.onPointerOut = null; + this.processPointerOverOut = null; + + this.onPointerOver = null; + + this._tempPoint = null; + }; + + return InteractionManager; +}(_eventemitter2.default); + +exports.default = InteractionManager; + + +core.WebGLRenderer.registerPlugin('interaction', InteractionManager); +core.CanvasRenderer.registerPlugin('interaction', InteractionManager); + +},{"../core":64,"./InteractionData":154,"./InteractionEvent":155,"./InteractionTrackingData":157,"./interactiveTarget":159,"eventemitter3":3}],157:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * DisplayObjects with the {@link PIXI.interaction.interactiveTarget} mixin use this class to track interactions + * + * @class + * @private + * @memberof PIXI.interaction + */ +var InteractionTrackingData = function () { + /** + * @param {number} pointerId - Unique pointer id of the event + */ + function InteractionTrackingData(pointerId) { + _classCallCheck(this, InteractionTrackingData); + + this._pointerId = pointerId; + this._flags = InteractionTrackingData.FLAGS.NONE; + } + + /** + * + * @private + * @param {number} flag - The interaction flag to set + * @param {boolean} yn - Should the flag be set or unset + */ + + + InteractionTrackingData.prototype._doSet = function _doSet(flag, yn) { + if (yn) { + this._flags = this._flags | flag; + } else { + this._flags = this._flags & ~flag; + } + }; + + /** + * Unique pointer id of the event + * + * @readonly + * @member {number} + */ + + + _createClass(InteractionTrackingData, [{ + key: "pointerId", + get: function get() { + return this._pointerId; + } + + /** + * State of the tracking data, expressed as bit flags + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "flags", + get: function get() { + return this._flags; + } + + /** + * Set the flags for the tracking data + * + * @param {number} flags - Flags to set + */ + , + set: function set(flags) { + this._flags = flags; + } + + /** + * Is the tracked event inactive (not over or down)? + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "none", + get: function get() { + return this._flags === this.constructor.FLAGS.NONE; + } + + /** + * Is the tracked event over the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "over", + get: function get() { + return (this._flags & this.constructor.FLAGS.OVER) !== 0; + } + + /** + * Set the over flag + * + * @param {boolean} yn - Is the event over? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.OVER, yn); + } + + /** + * Did the right mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "rightDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.RIGHT_DOWN) !== 0; + } + + /** + * Set the right down flag + * + * @param {boolean} yn - Is the right mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.RIGHT_DOWN, yn); + } + + /** + * Did the left mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "leftDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.LEFT_DOWN) !== 0; + } + + /** + * Set the left down flag + * + * @param {boolean} yn - Is the left mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.LEFT_DOWN, yn); + } + }]); + + return InteractionTrackingData; +}(); + +exports.default = InteractionTrackingData; + + +InteractionTrackingData.FLAGS = Object.freeze({ + NONE: 0, + OVER: 1 << 0, + LEFT_DOWN: 1 << 1, + RIGHT_DOWN: 1 << 2 +}); + +},{}],158:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _InteractionData = require('./InteractionData'); + +Object.defineProperty(exports, 'InteractionData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionData).default; + } +}); + +var _InteractionManager = require('./InteractionManager'); + +Object.defineProperty(exports, 'InteractionManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionManager).default; + } +}); + +var _interactiveTarget = require('./interactiveTarget'); + +Object.defineProperty(exports, 'interactiveTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_interactiveTarget).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./InteractionData":154,"./InteractionManager":156,"./interactiveTarget":159}],159:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * Default property values of interactive objects + * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties + * + * @private + * @name interactiveTarget + * @memberof PIXI.interaction + * @example + * function MyObject() {} + * + * Object.assign( + * core.DisplayObject.prototype, + * PIXI.interaction.interactiveTarget + * ); + */ +exports.default = { + + /** + * Enable interaction events for the DisplayObject. Touch, pointer and mouse + * events will not be emitted unless `interactive` is set to `true`. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.on('tap', (event) => { + * //handle event + * }); + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + interactive: false, + + /** + * Determines if the children to the displayObject can be clicked/touched + * Setting this to false allows pixi to bypass a recursive `hitTest` function + * + * @member {boolean} + * @memberof PIXI.Container# + */ + interactiveChildren: true, + + /** + * Interaction shape. Children will be hit first, then this shape will be checked. + * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.hitArea = new PIXI.Rectangle(0, 0, 100, 100); + * @member {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle} + * @memberof PIXI.DisplayObject# + */ + hitArea: null, + + /** + * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive + * Setting this changes the 'cursor' property to `'pointer'`. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.buttonMode = true; + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + get buttonMode() { + return this.cursor === 'pointer'; + }, + set buttonMode(value) { + if (value) { + this.cursor = 'pointer'; + } else if (this.cursor === 'pointer') { + this.cursor = null; + } + }, + + /** + * This defines what cursor mode is used when the mouse cursor + * is hovered over the displayObject. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.cursor = 'wait'; + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * + * @member {string} + * @memberof PIXI.DisplayObject# + */ + cursor: null, + + /** + * Internal set of all active pointers, by identifier + * + * @member {Map} + * @memberof PIXI.DisplayObject# + * @private + */ + get trackedPointers() { + if (this._trackedPointers === undefined) this._trackedPointers = {}; + + return this._trackedPointers; + }, + + /** + * Map of all tracked pointers, by identifier. Use trackedPointers to access. + * + * @private + * @type {Map} + */ + _trackedPointers: undefined +}; + +},{}],160:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.parse = parse; + +exports.default = function () { + return function bitmapFontParser(resource, next) { + // skip if no data or not xml data + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.XML) { + next(); + + return; + } + + // skip if not bitmap font data, using some silly duck-typing + if (resource.data.getElementsByTagName('page').length === 0 || resource.data.getElementsByTagName('info').length === 0 || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null) { + next(); + + return; + } + + var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; + + if (resource.isDataUrl) { + if (xmlUrl === '.') { + xmlUrl = ''; + } + + if (this.baseUrl && xmlUrl) { + // if baseurl has a trailing slash then add one to xmlUrl so the replace works below + if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { + xmlUrl += '/'; + } + + // remove baseUrl from xmlUrl + xmlUrl = xmlUrl.replace(this.baseUrl, ''); + } + } + + // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { + xmlUrl += '/'; + } + + var textureUrl = xmlUrl + resource.data.getElementsByTagName('page')[0].getAttribute('file'); + + if (_core.utils.TextureCache[textureUrl]) { + // reuse existing texture + parse(resource, _core.utils.TextureCache[textureUrl]); + next(); + } else { + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + // load the texture for the font + this.add(resource.name + '_image', textureUrl, loadOptions, function (res) { + parse(resource, res.texture); + next(); + }); + } + }; +}; + +var _path = require('path'); + +var path = _interopRequireWildcard(_path); + +var _core = require('../core'); + +var _resourceLoader = require('resource-loader'); + +var _extras = require('../extras'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Register a BitmapText font from loader resource. + * + * @function parseBitmapFontData + * @memberof PIXI.loaders + * @param {PIXI.loaders.Resource} resource - Loader resource. + * @param {PIXI.Texture} texture - Reference to texture. + */ +function parse(resource, texture) { + resource.bitmapFont = _extras.BitmapText.registerFont(resource.data, texture); +} + +},{"../core":64,"../extras":140,"path":22,"resource-loader":35}],161:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.shared = exports.Resource = exports.textureParser = exports.getResourcePath = exports.spritesheetParser = exports.parseBitmapFontData = exports.bitmapFontParser = exports.Loader = undefined; + +var _bitmapFontParser = require('./bitmapFontParser'); + +Object.defineProperty(exports, 'bitmapFontParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_bitmapFontParser).default; + } +}); +Object.defineProperty(exports, 'parseBitmapFontData', { + enumerable: true, + get: function get() { + return _bitmapFontParser.parse; + } +}); + +var _spritesheetParser = require('./spritesheetParser'); + +Object.defineProperty(exports, 'spritesheetParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_spritesheetParser).default; + } +}); +Object.defineProperty(exports, 'getResourcePath', { + enumerable: true, + get: function get() { + return _spritesheetParser.getResourcePath; + } +}); + +var _textureParser = require('./textureParser'); + +Object.defineProperty(exports, 'textureParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_textureParser).default; + } +}); + +var _resourceLoader = require('resource-loader'); + +Object.defineProperty(exports, 'Resource', { + enumerable: true, + get: function get() { + return _resourceLoader.Resource; + } +}); + +var _Application = require('../core/Application'); + +var _Application2 = _interopRequireDefault(_Application); + +var _loader = require('./loader'); + +var _loader2 = _interopRequireDefault(_loader); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * This namespace contains APIs which extends the {@link https://github.com/englercj/resource-loader resource-loader} module + * for loading assets, data, and other resources dynamically. + * @example + * const loader = new PIXI.loaders.Loader(); + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.load((loader, resources) => { + * // resources.bunny + * // resources.spaceship + * }); + * @namespace PIXI.loaders + */ +exports.Loader = _loader2.default; + + +/** + * A premade instance of the loader that can be used to load resources. + * @name shared + * @memberof PIXI.loaders + * @type {PIXI.loaders.Loader} + */ +var shared = new _loader2.default(); + +shared.destroy = function () { + // protect destroying shared loader +}; + +exports.shared = shared; + +// Mixin the loader construction + +var AppPrototype = _Application2.default.prototype; + +AppPrototype._loader = null; + +/** + * Loader instance to help with asset loading. + * @name PIXI.Application#loader + * @type {PIXI.loaders.Loader} + */ +Object.defineProperty(AppPrototype, 'loader', { + get: function get() { + if (!this._loader) { + var sharedLoader = this._options.sharedLoader; + + this._loader = sharedLoader ? shared : new _loader2.default(); + } + + return this._loader; + } +}); + +// Override the destroy function +// making sure to destroy the current Loader +AppPrototype._parentDestroy = AppPrototype.destroy; +AppPrototype.destroy = function destroy(removeView) { + if (this._loader) { + this._loader.destroy(); + this._loader = null; + } + this._parentDestroy(removeView); +}; + +},{"../core/Application":42,"./bitmapFontParser":160,"./loader":162,"./spritesheetParser":163,"./textureParser":164,"resource-loader":35}],162:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _resourceLoader = require('resource-loader'); + +var _resourceLoader2 = _interopRequireDefault(_resourceLoader); + +var _blob = require('resource-loader/lib/middlewares/parsing/blob'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _textureParser = require('./textureParser'); + +var _textureParser2 = _interopRequireDefault(_textureParser); + +var _spritesheetParser = require('./spritesheetParser'); + +var _spritesheetParser2 = _interopRequireDefault(_spritesheetParser); + +var _bitmapFontParser = require('./bitmapFontParser'); + +var _bitmapFontParser2 = _interopRequireDefault(_bitmapFontParser); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader + * + * ```js + * const loader = PIXI.loader; // pixi exposes a premade instance for you to use. + * //or + * const loader = new PIXI.loaders.Loader(); // you can also create your own if you want + * + * const sprites = {}; + * + * // Chainable `add` to enqueue a resource + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.add('scoreFont', 'assets/score.fnt'); + * + * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. + * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). + * loader.pre(cachingMiddleware); + * + * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. + * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). + * loader.use(parsingMiddleware); + * + * // The `load` method loads the queue of resources, and calls the passed in callback called once all + * // resources have loaded. + * loader.load((loader, resources) => { + * // resources is an object where the key is the name of the resource loaded and the value is the resource object. + * // They have a couple default properties: + * // - `url`: The URL that the resource was loaded from + * // - `error`: The error that happened when trying to load (if any) + * // - `data`: The raw data that was loaded + * // also may contain other properties based on the middleware that runs. + * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); + * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); + * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); + * }); + * + * // throughout the process multiple signals can be dispatched. + * loader.onProgress.add(() => {}); // called once per loaded/errored file + * loader.onError.add(() => {}); // called once per errored file + * loader.onLoad.add(() => {}); // called once per loaded file + * loader.onComplete.add(() => {}); // called once when the queued resources all load. + * ``` + * + * @see https://github.com/englercj/resource-loader + * + * @class + * @extends module:resource-loader.ResourceLoader + * @memberof PIXI.loaders + */ +var Loader = function (_ResourceLoader) { + _inherits(Loader, _ResourceLoader); + + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + _classCallCheck(this, Loader); + + var _this = _possibleConstructorReturn(this, _ResourceLoader.call(this, baseUrl, concurrency)); + + _eventemitter2.default.call(_this); + + for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { + _this.use(Loader._pixiMiddleware[i]()); + } + + // Compat layer, translate the new v2 signals into old v1 events. + _this.onStart.add(function (l) { + return _this.emit('start', l); + }); + _this.onProgress.add(function (l, r) { + return _this.emit('progress', l, r); + }); + _this.onError.add(function (e, l, r) { + return _this.emit('error', e, l, r); + }); + _this.onLoad.add(function (l, r) { + return _this.emit('load', l, r); + }); + _this.onComplete.add(function (l, r) { + return _this.emit('complete', l, r); + }); + return _this; + } + + /** + * Adds a default middleware to the pixi loader. + * + * @static + * @param {Function} fn - The middleware to add. + */ + + + Loader.addPixiMiddleware = function addPixiMiddleware(fn) { + Loader._pixiMiddleware.push(fn); + }; + + /** + * Destroy the loader, removes references. + */ + + + Loader.prototype.destroy = function destroy() { + this.removeAllListeners(); + this.reset(); + }; + + return Loader; +}(_resourceLoader2.default); + +// Copy EE3 prototype (mixin) + + +exports.default = Loader; +for (var k in _eventemitter2.default.prototype) { + Loader.prototype[k] = _eventemitter2.default.prototype[k]; +} + +Loader._pixiMiddleware = [ +// parse any blob into more usable objects (e.g. Image) +_blob.blobMiddlewareFactory, +// parse any Image objects into textures +_textureParser2.default, +// parse any spritesheet data into multiple textures +_spritesheetParser2.default, +// parse bitmap font data into multiple textures +_bitmapFontParser2.default]; + +// Add custom extentions +var Resource = _resourceLoader2.default.Resource; + +Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); + +},{"./bitmapFontParser":160,"./spritesheetParser":163,"./textureParser":164,"eventemitter3":3,"resource-loader":35,"resource-loader/lib/middlewares/parsing/blob":36}],163:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function spritesheetParser(resource, next) { + var imageResourceName = resource.name + '_image'; + + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.JSON || !resource.data.frames || this.resources[imageResourceName]) { + next(); + + return; + } + + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + var resourcePath = getResourcePath(resource, this.baseUrl); + + // load the image for this sheet + this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + var spritesheet = new _core.Spritesheet(res.texture.baseTexture, resource.data, resource.url); + + spritesheet.parse(function () { + resource.spritesheet = spritesheet; + resource.textures = spritesheet.textures; + next(); + }); + }); + }; +}; + +exports.getResourcePath = getResourcePath; + +var _resourceLoader = require('resource-loader'); + +var _url = require('url'); + +var _url2 = _interopRequireDefault(_url); + +var _core = require('../core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function getResourcePath(resource, baseUrl) { + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + return resource.data.meta.image; + } + + return _url2.default.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); +} + +},{"../core":64,"resource-loader":35,"url":28}],164:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function textureParser(resource, next) { + // create a new texture if the data is an Image object + if (resource.data && resource.type === _resourceLoader.Resource.TYPE.IMAGE) { + resource.texture = _Texture2.default.fromLoader(resource.data, resource.url, resource.name); + } + next(); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"../core/textures/Texture":114,"resource-loader":35}],165:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _TextureTransform = require('../extras/TextureTransform'); + +var _TextureTransform2 = _interopRequireDefault(_TextureTransform); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); +var tempPolygon = new core.Polygon(); + +/** + * Base mesh class + * @class + * @extends PIXI.Container + * @memberof PIXI.mesh + */ + +var Mesh = function (_core$Container) { + _inherits(Mesh, _core$Container); + + /** + * @param {PIXI.Texture} texture - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts + */ + function Mesh(texture, vertices, uvs, indices, drawMode) { + _classCallCheck(this, Mesh); + + /** + * The texture of the Mesh + * + * @member {PIXI.Texture} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._texture = texture; + + /** + * The Uvs of the Mesh + * + * @member {Float32Array} + */ + _this.uvs = uvs || new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + /** + * An array of vertices + * + * @member {Float32Array} + */ + _this.vertices = vertices || new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]); + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + // TODO auto generate this based on draw mode! + _this.indices = indices || new Uint16Array([0, 1, 3, 2]); + + /** + * Version of mesh uvs are dirty or not + * + * @member {number} + */ + _this.dirty = 0; + + /** + * Version of mesh indices + * + * @member {number} + */ + _this.indexDirty = 0; + + /** + * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove + * any blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles + * to overlap a bit with each other. + * + * @member {number} + */ + _this.canvasPadding = 0; + + /** + * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts + * + * @member {number} + * @see PIXI.mesh.Mesh.DRAW_MODES + */ + _this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH; + + /** + * The default shader that is used if a mesh doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + _this.shader = null; + + /** + * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any + * tint effect. + * + * @member {number} + */ + _this.tintRgb = new Float32Array([1, 1, 1]); + + /** + * A map of renderer IDs to webgl render data + * + * @private + * @member {object} + */ + _this._glDatas = {}; + + /** + * transform that is applied to UV to get the texture coords + * its updated independently from texture uvTransform + * updates of uvs are tied to that thing + * + * @member {PIXI.extras.TextureTransform} + * @private + */ + _this._uvTransform = new _TextureTransform2.default(texture); + + /** + * whether or not upload uvTransform to shader + * if its false, then uvs should be pre-multiplied + * if you change it for generated mesh, please call 'refresh(true)' + * @member {boolean} + * @default false + */ + _this.uploadUvTransform = false; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * @member {string} + * @default 'mesh' + */ + _this.pluginName = 'mesh'; + return _this; + } + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - a reference to the WebGL renderer + */ + + + Mesh.prototype._renderWebGL = function _renderWebGL(renderer) { + this.refresh(); + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + + + Mesh.prototype._renderCanvas = function _renderCanvas(renderer) { + this.refresh(); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Mesh.prototype._onTextureUpdate = function _onTextureUpdate() { + this._uvTransform.texture = this._texture; + this.refresh(); + }; + + /** + * multiplies uvs only if uploadUvTransform is false + * call it after you change uvs manually + * make sure that texture is valid + */ + + + Mesh.prototype.multiplyUvs = function multiplyUvs() { + if (!this.uploadUvTransform) { + this._uvTransform.multiplyUvs(this.uvs); + } + }; + + /** + * Refreshes uvs for generated meshes (rope, plane) + * sometimes refreshes vertices too + * + * @param {boolean} [forceUpdate=false] if true, matrices will be updated any case + */ + + + Mesh.prototype.refresh = function refresh(forceUpdate) { + if (this._uvTransform.update(forceUpdate)) { + this._refresh(); + } + }; + + /** + * re-calculates mesh coords + * @protected + */ + + + Mesh.prototype._refresh = function _refresh() {} + /* empty */ + + + /** + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + */ + ; + + Mesh.prototype._calculateBounds = function _calculateBounds() { + // TODO - we can cache local bounds and use them if they are dirty (like graphics) + this._bounds.addVertices(this.transform, this.vertices, 0, this.vertices.length); + }; + + /** + * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Mesh.prototype.containsPoint = function containsPoint(point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + + this.worldTransform.applyInverse(point, tempPoint); + + var vertices = this.vertices; + var points = tempPolygon.points; + var indices = this.indices; + var len = this.indices.length; + var step = this.drawMode === Mesh.DRAW_MODES.TRIANGLES ? 3 : 1; + + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + + return false; + }; + + /** + * The texture that the mesh uses. + * + * @member {PIXI.Texture} + */ + + + _createClass(Mesh, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + + /** + * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return core.utils.rgb2hex(this.tintRgb); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tintRgb = core.utils.hex2rgb(value, this.tintRgb); + } + }]); + + return Mesh; +}(core.Container); + +/** + * Different drawing buffer modes supported + * + * @static + * @constant + * @type {object} + * @property {number} TRIANGLE_MESH + * @property {number} TRIANGLES + */ + + +exports.default = Mesh; +Mesh.DRAW_MODES = { + TRIANGLE_MESH: 0, + TRIANGLES: 1 +}; + +},{"../core":64,"../extras/TextureTransform":135}],166:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Plane2 = require('./Plane'); + +var _Plane3 = _interopRequireDefault(_Plane2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DEFAULT_BORDER_SIZE = 10; + +/** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.fromImage('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
+ *      A                          B
+ *    +---+----------------------+---+
+ *  C | 1 |          2           | 3 |
+ *    +---+----------------------+---+
+ *    |   |                      |   |
+ *    | 4 |          5           | 6 |
+ *    |   |                      |   |
+ *    +---+----------------------+---+
+ *  D | 7 |          8           | 9 |
+ *    +---+----------------------+---+
+
+ *  When changing this objects width and/or height:
+ *     areas 1 3 7 and 9 will remain unscaled.
+ *     areas 2 and 8 will be stretched horizontally
+ *     areas 4 and 6 will be stretched vertically
+ *     area 5 will be stretched both horizontally and vertically
+ * 
+ * + * @class + * @extends PIXI.mesh.Plane + * @memberof PIXI.mesh + * + */ + +var NineSlicePlane = function (_Plane) { + _inherits(NineSlicePlane, _Plane); + + /** + * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. + * @param {int} [leftWidth=10] size of the left vertical bar (A) + * @param {int} [topHeight=10] size of the top horizontal bar (C) + * @param {int} [rightWidth=10] size of the right vertical bar (B) + * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) + */ + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + _classCallCheck(this, NineSlicePlane); + + var _this = _possibleConstructorReturn(this, _Plane.call(this, texture, 4, 4)); + + _this._origWidth = texture.orig.width; + _this._origHeight = texture.orig.height; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._width = _this._origWidth; + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._height = _this._origHeight; + + /** + * The width of the left column (a) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; + + /** + * The width of the right column (b) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; + + /** + * The height of the top row (c) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; + + /** + * The height of the bottom row (d) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; + + _this.refresh(true); + return _this; + } + + /** + * Updates the horizontal vertices. + * + */ + + + NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices() { + var vertices = this.vertices; + + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight; + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + }; + + /** + * Updates the vertical vertices. + * + */ + + + NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices() { + var vertices = this.vertices; + + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth; + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with. + */ + + + NineSlicePlane.prototype._renderCanvas = function _renderCanvas(renderer) { + var context = renderer.context; + + context.globalAlpha = this.worldAlpha; + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + var base = this._texture.baseTexture; + var textureSource = base.source; + var w = base.width; + var h = base.height; + + this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11); + this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13); + this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15); + this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19); + this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21); + this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23); + this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27); + this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29); + this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31); + }; + + /** + * Renders one segment of the plane. + * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure + * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used. + * + * @private + * @param {CanvasRenderingContext2D} context - The context to draw with. + * @param {CanvasImageSource} textureSource - The source to draw. + * @param {number} w - width of the texture + * @param {number} h - height of the texture + * @param {number} x1 - x index 1 + * @param {number} y1 - y index 1 + * @param {number} x2 - x index 2 + * @param {number} y2 - y index 2 + */ + + + NineSlicePlane.prototype.drawSegment = function drawSegment(context, textureSource, w, h, x1, y1, x2, y2) { + // otherwise you get weird results when using slices of that are 0 wide or high. + var uvs = this.uvs; + var vertices = this.vertices; + + var sw = (uvs[x2] - uvs[x1]) * w; + var sh = (uvs[y2] - uvs[y1]) * h; + var dw = vertices[x2] - vertices[x1]; + var dh = vertices[y2] - vertices[y1]; + + // make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn. + if (sw < 1) { + sw = 1; + } + + if (sh < 1) { + sh = 1; + } + + // make sure destination is at least 1 pixel wide and high, otherwise you get + // lines when rendering close to original size. + if (dw < 1) { + dw = 1; + } + + if (dh < 1) { + dh = 1; + } + + context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh); + }; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + + /** + * Refreshes NineSlicePlane coords. All of them. + */ + NineSlicePlane.prototype._refresh = function _refresh() { + _Plane.prototype._refresh.call(this); + + var uvs = this.uvs; + var texture = this._texture; + + this._origWidth = texture.orig.width; + this._origHeight = texture.orig.height; + + var _uvw = 1.0 / this._origWidth; + var _uvh = 1.0 / this._origHeight; + + uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; + uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - _uvw * this._rightWidth; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - _uvh * this._bottomHeight; + + this.updateHorizontalVertices(); + this.updateVerticalVertices(); + + this.dirty = true; + + this.multiplyUvs(); + }; + + _createClass(NineSlicePlane, [{ + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + this._refresh(); + } + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + this._refresh(); + } + + /** + * The width of the left column + * + * @member {number} + */ + + }, { + key: 'leftWidth', + get: function get() { + return this._leftWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._leftWidth = value; + this._refresh(); + } + + /** + * The width of the right column + * + * @member {number} + */ + + }, { + key: 'rightWidth', + get: function get() { + return this._rightWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rightWidth = value; + this._refresh(); + } + + /** + * The height of the top row + * + * @member {number} + */ + + }, { + key: 'topHeight', + get: function get() { + return this._topHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._topHeight = value; + this._refresh(); + } + + /** + * The height of the bottom row + * + * @member {number} + */ + + }, { + key: 'bottomHeight', + get: function get() { + return this._bottomHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._bottomHeight = value; + this._refresh(); + } + }]); + + return NineSlicePlane; +}(_Plane3.default); + +exports.default = NineSlicePlane; + +},{"./Plane":167}],167:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The Plane allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Plane = function (_Mesh) { + _inherits(Plane, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the Plane. + * @param {number} verticesX - The number of vertices in the x-axis + * @param {number} verticesY - The number of vertices in the y-axis + */ + function Plane(texture, verticesX, verticesY) { + _classCallCheck(this, Plane); + + /** + * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this._ready = true; + + _this.verticesX = verticesX || 10; + _this.verticesY = verticesY || 10; + + _this.drawMode = _Mesh3.default.DRAW_MODES.TRIANGLES; + _this.refresh(); + return _this; + } + + /** + * Refreshes plane coordinates + * + */ + + + Plane.prototype._refresh = function _refresh() { + var texture = this._texture; + var total = this.verticesX * this.verticesY; + var verts = []; + var colors = []; + var uvs = []; + var indices = []; + + var segmentsX = this.verticesX - 1; + var segmentsY = this.verticesY - 1; + + var sizeX = texture.width / segmentsX; + var sizeY = texture.height / segmentsY; + + for (var i = 0; i < total; i++) { + var x = i % this.verticesX; + var y = i / this.verticesX | 0; + + verts.push(x * sizeX, y * sizeY); + + uvs.push(x / segmentsX, y / segmentsY); + } + + // cons + + var totalSub = segmentsX * segmentsY; + + for (var _i = 0; _i < totalSub; _i++) { + var xpos = _i % segmentsX; + var ypos = _i / segmentsX | 0; + + var value = ypos * this.verticesX + xpos; + var value2 = ypos * this.verticesX + xpos + 1; + var value3 = (ypos + 1) * this.verticesX + xpos; + var value4 = (ypos + 1) * this.verticesX + xpos + 1; + + indices.push(value, value2, value3); + indices.push(value2, value4, value3); + } + + // console.log(indices) + this.vertices = new Float32Array(verts); + this.uvs = new Float32Array(uvs); + this.colors = new Float32Array(colors); + this.indices = new Uint16Array(indices); + this.indexDirty = true; + + this.multiplyUvs(); + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Plane.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh3.default.prototype._onTextureUpdate.call(this); + + // wait for the Plane ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + return Plane; +}(_Mesh3.default); + +exports.default = Plane; + +},{"./Mesh":165}],168:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The rope allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Rope = function (_Mesh) { + _inherits(Rope, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the rope. + * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. + */ + function Rope(texture, points) { + _classCallCheck(this, Rope); + + /** + * An array of points that determine the rope + * + * @member {PIXI.Point[]} + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this.points = points; + + /** + * An array of vertices used to construct this rope. + * + * @member {Float32Array} + */ + _this.vertices = new Float32Array(points.length * 4); + + /** + * The WebGL Uvs of the rope. + * + * @member {Float32Array} + */ + _this.uvs = new Float32Array(points.length * 4); + + /** + * An array containing the color components + * + * @member {Float32Array} + */ + _this.colors = new Float32Array(points.length * 2); + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + _this.indices = new Uint16Array(points.length * 2); + + /** + * refreshes vertices on every updateTransform + * @member {boolean} + * @default true + */ + _this.autoUpdate = true; + + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Rope.prototype._refresh = function _refresh() { + var points = this.points; + + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1 || !this._texture._uvs) { + return; + } + + // if the number of points has changed we will need to recreate the arraybuffers + if (this.vertices.length / 4 !== points.length) { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + + for (var i = 1; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + var amount = i / (total - 1); + + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + + // ensure that the changes are uploaded + this.dirty++; + this.indexDirty++; + + this.multiplyUvs(); + this.refreshVertices(); + }; + + /** + * refreshes vertices of Rope mesh + */ + + + Rope.prototype.refreshVertices = function refreshVertices() { + var points = this.points; + + if (points.length < 1) { + return; + } + + var lastPoint = points[0]; + var nextPoint = void 0; + var perpX = 0; + var perpY = 0; + + // this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } else { + nextPoint = point; + } + + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + + var ratio = (1 - i / (total - 1)) * 10; + + if (ratio > 1) { + ratio = 1; + } + + var perpLength = Math.sqrt(perpX * perpX + perpY * perpY); + var num = this._texture.height / 2; // (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; + + perpX /= perpLength; + perpY /= perpLength; + + perpX *= num; + perpY *= num; + + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + + lastPoint = point; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + Rope.prototype.updateTransform = function updateTransform() { + if (this.autoUpdate) { + this.refreshVertices(); + } + this.containerUpdateTransform(); + }; + + return Rope; +}(_Mesh3.default); + +exports.default = Rope; + +},{"./Mesh":165}],169:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Renderer dedicated to meshes. + * + * @class + * @private + * @memberof PIXI + */ +var MeshSpriteRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The renderer this downport works for + */ + function MeshSpriteRenderer(renderer) { + _classCallCheck(this, MeshSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the Mesh + * + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var context = renderer.context; + + var transform = mesh.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + renderer.setBlendMode(mesh.blendMode); + + if (mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH) { + this._renderTriangleMesh(mesh); + } else { + this._renderTriangles(mesh); + } + }; + + /** + * Draws the object in Triangle Mesh mode + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype._renderTriangleMesh = function _renderTriangleMesh(mesh) { + // draw triangles!! + var length = mesh.vertices.length / 2; + + for (var i = 0; i < length - 2; i++) { + // draw some triangles! + var index = i * 2; + + this._renderDrawTriangle(mesh, index, index + 2, index + 4); + } + }; + + /** + * Draws the object in triangle mode using canvas + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + */ + + + MeshSpriteRenderer.prototype._renderTriangles = function _renderTriangles(mesh) { + // draw triangles!! + var indices = mesh.indices; + var length = indices.length; + + for (var i = 0; i < length; i += 3) { + // draw some triangles! + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderDrawTriangle(mesh, index0, index1, index2); + } + }; + + /** + * Draws one of the triangles that from the Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + * @param {number} index0 - the index of the first vertex + * @param {number} index1 - the index of the second vertex + * @param {number} index2 - the index of the third vertex + */ + + + MeshSpriteRenderer.prototype._renderDrawTriangle = function _renderDrawTriangle(mesh, index0, index1, index2) { + var context = this.renderer.context; + var uvs = mesh.uvs; + var vertices = mesh.vertices; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var base = texture.baseTexture; + var textureSource = base.source; + var textureWidth = base.width; + var textureHeight = base.height; + + var u0 = void 0; + var u1 = void 0; + var u2 = void 0; + var v0 = void 0; + var v1 = void 0; + var v2 = void 0; + + if (mesh.uploadUvTransform) { + var ut = mesh._uvTransform.mapCoord; + + u0 = (uvs[index0] * ut.a + uvs[index0 + 1] * ut.c + ut.tx) * base.width; + u1 = (uvs[index1] * ut.a + uvs[index1 + 1] * ut.c + ut.tx) * base.width; + u2 = (uvs[index2] * ut.a + uvs[index2 + 1] * ut.c + ut.tx) * base.width; + v0 = (uvs[index0] * ut.b + uvs[index0 + 1] * ut.d + ut.ty) * base.height; + v1 = (uvs[index1] * ut.b + uvs[index1 + 1] * ut.d + ut.ty) * base.height; + v2 = (uvs[index2] * ut.b + uvs[index2 + 1] * ut.d + ut.ty) * base.height; + } else { + u0 = uvs[index0] * base.width; + u1 = uvs[index1] * base.width; + u2 = uvs[index2] * base.width; + v0 = uvs[index0 + 1] * base.height; + v1 = uvs[index1 + 1] * base.height; + v2 = uvs[index2 + 1] * base.height; + } + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + if (mesh.canvasPadding > 0) { + var paddingX = mesh.canvasPadding / mesh.worldTransform.a; + var paddingY = mesh.canvasPadding / mesh.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt(normX * normX + normY * normY); + + x0 = centerX + normX / dist * (dist + paddingX); + y0 = centerY + normY / dist * (dist + paddingY); + + // + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x1 = centerX + normX / dist * (dist + paddingX); + y1 = centerY + normY / dist * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x2 = centerX + normX / dist * (dist + paddingX); + y2 = centerY + normY / dist * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2; + var deltaA = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2; + var deltaB = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2; + var deltaC = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2; + var deltaD = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2; + var deltaE = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2; + var deltaF = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2; + + context.transform(deltaA / delta, deltaD / delta, deltaB / delta, deltaE / delta, deltaC / delta, deltaF / delta); + + context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + + context.restore(); + }; + + /** + * Renders a flat Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - The Mesh to render + */ + + + MeshSpriteRenderer.prototype.renderMeshFlat = function renderMeshFlat(mesh) { + var context = this.renderer.context; + var vertices = mesh.vertices; + var length = vertices.length / 2; + + // this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; ++i) { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var y0 = vertices[index + 1]; + + var x1 = vertices[index + 2]; + var y1 = vertices[index + 3]; + + var x2 = vertices[index + 4]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + }; + + /** + * destroy the the renderer. + * + */ + + + MeshSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return MeshSpriteRenderer; +}(); + +exports.default = MeshSpriteRenderer; + + +core.CanvasRenderer.registerPlugin('mesh', MeshSpriteRenderer); + +},{"../../core":64,"../Mesh":165}],170:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh = require('./Mesh'); + +Object.defineProperty(exports, 'Mesh', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Mesh).default; + } +}); + +var _MeshRenderer = require('./webgl/MeshRenderer'); + +Object.defineProperty(exports, 'MeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_MeshRenderer).default; + } +}); + +var _CanvasMeshRenderer = require('./canvas/CanvasMeshRenderer'); + +Object.defineProperty(exports, 'CanvasMeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasMeshRenderer).default; + } +}); + +var _Plane = require('./Plane'); + +Object.defineProperty(exports, 'Plane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Plane).default; + } +}); + +var _NineSlicePlane = require('./NineSlicePlane'); + +Object.defineProperty(exports, 'NineSlicePlane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NineSlicePlane).default; + } +}); + +var _Rope = require('./Rope'); + +Object.defineProperty(exports, 'Rope', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rope).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./Mesh":165,"./NineSlicePlane":166,"./Plane":167,"./Rope":168,"./canvas/CanvasMeshRenderer":169,"./webgl/MeshRenderer":171}],171:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var matrixIdentity = core.Matrix.IDENTITY; + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var MeshRenderer = function (_core$ObjectRenderer) { + _inherits(MeshRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function MeshRenderer(renderer) { + _classCallCheck(this, MeshRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + MeshRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n'); + }; + + /** + * renders mesh + * + * @param {PIXI.mesh.Mesh} mesh mesh instance + */ + + + MeshRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var gl = renderer.gl; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var glData = mesh._glDatas[renderer.CONTEXT_UID]; + + if (!glData) { + renderer.bindVao(null); + + glData = { + shader: this.shader, + vertexBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.vertices, gl.STREAM_DRAW), + uvBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.uvs, gl.STREAM_DRAW), + indexBuffer: _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, mesh.indices, gl.STATIC_DRAW), + // build the vao object that will render.. + vao: null, + dirty: mesh.dirty, + indexDirty: mesh.indexDirty + }; + + // build the vao object that will render.. + glData.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(glData.indexBuffer).addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0).addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); + + mesh._glDatas[renderer.CONTEXT_UID] = glData; + } + + renderer.bindVao(glData.vao); + + if (mesh.dirty !== glData.dirty) { + glData.dirty = mesh.dirty; + glData.uvBuffer.upload(mesh.uvs); + } + + if (mesh.indexDirty !== glData.indexDirty) { + glData.indexDirty = mesh.indexDirty; + glData.indexBuffer.upload(mesh.indices); + } + + glData.vertexBuffer.upload(mesh.vertices); + + renderer.bindShader(glData.shader); + + glData.shader.uniforms.uSampler = renderer.bindTexture(texture); + + renderer.state.setBlendMode(core.utils.correctBlendMode(mesh.blendMode, texture.baseTexture.premultipliedAlpha)); + + if (glData.shader.uniforms.uTransform) { + if (mesh.uploadUvTransform) { + glData.shader.uniforms.uTransform = mesh._uvTransform.mapCoord.toArray(true); + } else { + glData.shader.uniforms.uTransform = matrixIdentity.toArray(true); + } + } + glData.shader.uniforms.translationMatrix = mesh.worldTransform.toArray(true); + + glData.shader.uniforms.uColor = core.utils.premultiplyRgba(mesh.tintRgb, mesh.worldAlpha, glData.shader.uniforms.uColor, texture.baseTexture.premultipliedAlpha); + + var drawMode = mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + glData.vao.draw(drawMode, mesh.indices.length, 0); + }; + + return MeshRenderer; +}(core.ObjectRenderer); + +exports.default = MeshRenderer; + + +core.WebGLRenderer.registerPlugin('mesh', MeshRenderer); + +},{"../../core":64,"../Mesh":165,"path":22,"pixi-gl-core":12}],172:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _utils = require('../core/utils'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that advanced + * functionality will not work. ParticleContainer implements only the basic object transform (position, scale, rotation). + * Any other functionality like tinting, masking, etc will not work on sprites in this batch. + * + * It's extremely easy to use : + * + * ```js + * let container = new ParticleContainer(); + * + * for (let i = 0; i < 100; ++i) + * { + * let sprite = new PIXI.Sprite.fromImage("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be renderer at the speed of light. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.particles + */ +var ParticleContainer = function (_core$Container) { + _inherits(ParticleContainer, _core$Container); + + /** + * @param {number} [maxSize=15000] - The maximum number of particles that can be renderer by the container. + * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.scale=false] - When true, scale be uploaded and applied. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.alpha=false] - When true, alpha be uploaded and applied. + * @param {number} [batchSize=15000] - Number of particles per batch. + */ + function ParticleContainer() { + var maxSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1500; + var properties = arguments[1]; + var batchSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 16384; + + _classCallCheck(this, ParticleContainer); + + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + var maxBatchSize = 16384; + + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + + if (batchSize > maxSize) { + batchSize = maxSize; + } + + /** + * Set properties to be dynamic (true) / static (false) + * + * @member {boolean[]} + * @private + */ + _this._properties = [false, true, false, false, false]; + + /** + * @member {number} + * @private + */ + _this._maxSize = maxSize; + + /** + * @member {number} + * @private + */ + _this._batchSize = batchSize; + + /** + * @member {object} + * @private + */ + _this._glBuffers = {}; + + /** + * @member {number} + * @private + */ + _this._bufferToUpdate = 0; + + /** + * @member {boolean} + * + */ + _this.interactiveChildren = false; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` + * to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Used for canvas renderering. If true then the elements will be positioned at the + * nearest pixel. This provides a nice speed boost. + * + * @member {boolean} + * @default true; + */ + _this.roundPixels = true; + + /** + * The texture used to render the children. + * + * @readonly + * @member {BaseTexture} + */ + _this.baseTexture = null; + + _this.setProperties(properties); + + /** + * The tint applied to the container. + * This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = 0; + _this.tintRgb = new Float32Array(4); + _this.tint = 0xFFFFFF; + return _this; + } + + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * + * @param {object} properties - The properties to be uploaded + */ + + + ParticleContainer.prototype.setProperties = function setProperties(properties) { + if (properties) { + this._properties[0] = 'scale' in properties ? !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'alpha' in properties ? !!properties.alpha : this._properties[4]; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + ParticleContainer.prototype.updateTransform = function updateTransform() { + // TODO don't need to! + this.displayObjectUpdateTransform(); + // PIXI.Container.prototype.updateTransform.call( this ); + }; + + /** + * The tint applied to the container. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + ** IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * @member {number} + * @default 0xFFFFFF + */ + + + /** + * Renders the container using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer + */ + ParticleContainer.prototype.renderWebGL = function renderWebGL(renderer) { + var _this2 = this; + + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.hasLoaded) { + this.baseTexture.once('update', function () { + return _this2.onChildrenChange(0); + }); + } + } + + renderer.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + + /** + * Set the flag that static data should be updated to true + * + * @private + * @param {number} smallestChildIndex - The smallest child index + */ + + + ParticleContainer.prototype.onChildrenChange = function onChildrenChange(smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + + if (bufferIndex < this._bufferToUpdate) { + this._bufferToUpdate = bufferIndex; + } + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + + + ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var isRotated = true; + + var positionX = 0; + var positionY = 0; + + var finalWidth = 0; + var finalHeight = 0; + + var compositeOperation = renderer.blendModes[this.blendMode]; + + if (compositeOperation !== context.globalCompositeOperation) { + context.globalCompositeOperation = compositeOperation; + } + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i]; + + if (!child.visible) { + continue; + } + + var frame = child._texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) { + // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call + if (isRotated) { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx * renderer.resolution, transform.ty * renderer.resolution); + + isRotated = false; + } + + positionX = child.anchor.x * (-frame.width * child.scale.x) + child.position.x + 0.5; + positionY = child.anchor.y * (-frame.height * child.scale.y) + child.position.y + 0.5; + + finalWidth = frame.width * child.scale.x; + finalHeight = frame.height * child.scale.y; + } else { + if (!isRotated) { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + + if (renderer.roundPixels) { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution | 0, childTransform.ty * renderer.resolution | 0); + } else { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution, childTransform.ty * renderer.resolution); + } + + positionX = child.anchor.x * -frame.width + 0.5; + positionY = child.anchor.y * -frame.height + 0.5; + + finalWidth = frame.width; + finalHeight = frame.height; + } + + var resolution = child._texture.baseTexture.resolution; + + context.drawImage(child._texture.baseTexture.source, frame.x * resolution, frame.y * resolution, frame.width * resolution, frame.height * resolution, positionX * renderer.resolution, positionY * renderer.resolution, finalWidth * renderer.resolution, finalHeight * renderer.resolution); + } + }; + + /** + * Destroys the container + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + ParticleContainer.prototype.destroy = function destroy(options) { + _core$Container.prototype.destroy.call(this, options); + + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + } + + this._properties = null; + this._buffers = null; + }; + + _createClass(ParticleContainer, [{ + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + (0, _utils.hex2rgb)(value, this.tintRgb); + } + }]); + + return ParticleContainer; +}(core.Container); + +exports.default = ParticleContainer; + +},{"../core":64,"../core/utils":123}],173:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ParticleContainer = require('./ParticleContainer'); + +Object.defineProperty(exports, 'ParticleContainer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleContainer).default; + } +}); + +var _ParticleRenderer = require('./webgl/ParticleRenderer'); + +Object.defineProperty(exports, 'ParticleRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleRenderer).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./ParticleContainer":172,"./webgl/ParticleRenderer":175}],174:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + +/** + * The particle buffer manages the static and dynamic buffers for a particle container. + * + * @class + * @private + * @memberof PIXI + */ +var ParticleBuffer = function () { + /** + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(gl, properties, dynamicPropertyFlags, size) { + _classCallCheck(this, ParticleBuffer); + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * Size of a single vertex. + * + * @member {number} + */ + this.vertSize = 2; + + /** + * Size of a single vertex in bytes. + * + * @member {number} + */ + this.vertByteSize = this.vertSize * 4; + + /** + * The number of particles the buffer can hold + * + * @member {number} + */ + this.size = size; + + /** + * A list of the properties that are dynamic. + * + * @member {object[]} + */ + this.dynamicProperties = []; + + /** + * A list of the properties that are static. + * + * @member {object[]} + */ + this.staticProperties = []; + + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attribute: property.attribute, + size: property.size, + uploadFunction: property.uploadFunction, + offset: property.offset + }; + + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } else { + this.staticProperties.push(property); + } + } + + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + + this.initBuffers(); + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + ParticleBuffer.prototype.initBuffers = function initBuffers() { + var gl = this.gl; + var dynamicOffset = 0; + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(this.size); + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + this.dynamicStride = 0; + + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + + this.dynamicData = new Float32Array(this.size * this.dynamicStride * 4); + this.dynamicBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.dynamicData, gl.STREAM_DRAW); + + // static // + var staticOffset = 0; + + this.staticStride = 0; + + for (var _i = 0; _i < this.staticProperties.length; ++_i) { + var _property = this.staticProperties[_i]; + + _property.offset = staticOffset; + staticOffset += _property.size; + this.staticStride += _property.size; + } + + this.staticData = new Float32Array(this.size * this.staticStride * 4); + this.staticBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.staticData, gl.STATIC_DRAW); + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(this.indexBuffer); + + for (var _i2 = 0; _i2 < this.dynamicProperties.length; ++_i2) { + var _property2 = this.dynamicProperties[_i2]; + + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.FLOAT, false, this.dynamicStride * 4, _property2.offset * 4); + } + + for (var _i3 = 0; _i3 < this.staticProperties.length; ++_i3) { + var _property3 = this.staticProperties[_i3]; + + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.FLOAT, false, this.staticStride * 4, _property3.offset * 4); + } + }; + + /** + * Uploads the dynamic properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadDynamic = function uploadDynamic(children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + + property.uploadFunction(children, startIndex, amount, this.dynamicData, this.dynamicStride, property.offset); + } + + this.dynamicBuffer.upload(); + }; + + /** + * Uploads the static properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadStatic = function uploadStatic(children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + + property.uploadFunction(children, startIndex, amount, this.staticData, this.staticStride, property.offset); + } + + this.staticBuffer.upload(); + }; + + /** + * Destroys the ParticleBuffer. + * + */ + + + ParticleBuffer.prototype.destroy = function destroy() { + this.dynamicProperties = null; + this.dynamicData = null; + this.dynamicBuffer.destroy(); + + this.staticProperties = null; + this.staticData = null; + this.staticBuffer.destroy(); + }; + + return ParticleBuffer; +}(); + +exports.default = ParticleBuffer; + +},{"../../core/utils/createIndicesForQuads":121,"pixi-gl-core":12}],175:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _ParticleShader = require('./ParticleShader'); + +var _ParticleShader2 = _interopRequireDefault(_ParticleShader); + +var _ParticleBuffer = require('./ParticleBuffer'); + +var _ParticleBuffer2 = _interopRequireDefault(_ParticleBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original pixi version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + +/** + * + * @class + * @private + * @memberof PIXI + */ +var ParticleRenderer = function (_core$ObjectRenderer) { + _inherits(ParticleRenderer, _core$ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + _classCallCheck(this, ParticleRenderer); + + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; + + /** + * The default shader that is used if a sprite doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + + _this.indexBuffer = null; + + _this.properties = null; + + _this.tempMatrix = new core.Matrix(); + + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * When there is a WebGL context change + * + * @private + */ + + + ParticleRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + + // setup default shader + this.shader = new _ParticleShader2.default(gl); + + this.properties = [ + // verticesData + { + attribute: this.shader.attributes.aVertexPosition, + size: 2, + uploadFunction: this.uploadVertices, + offset: 0 + }, + // positionData + { + attribute: this.shader.attributes.aPositionCoord, + size: 2, + uploadFunction: this.uploadPosition, + offset: 0 + }, + // rotationData + { + attribute: this.shader.attributes.aRotation, + size: 1, + uploadFunction: this.uploadRotation, + offset: 0 + }, + // uvsData + { + attribute: this.shader.attributes.aTextureCoord, + size: 2, + uploadFunction: this.uploadUvs, + offset: 0 + }, + // alphaData + { + attribute: this.shader.attributes.aColor, + size: 1, + uploadFunction: this.uploadAlpha, + offset: 0 + }]; + }; + + /** + * Starts a new particle batch. + * + */ + + + ParticleRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + }; + + /** + * Renders the particle container object. + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + */ + + + ParticleRenderer.prototype.render = function render(container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var renderer = this.renderer; + var totalChildren = children.length; + + if (totalChildren === 0) { + return; + } else if (totalChildren > maxSize) { + totalChildren = maxSize; + } + + var buffers = container._glBuffers[renderer.CONTEXT_UID]; + + if (!buffers) { + buffers = container._glBuffers[renderer.CONTEXT_UID] = this.generateBuffers(container); + } + + var baseTexture = children[0]._texture.baseTexture; + + // if the uvs have not updated then no point rendering just yet! + this.renderer.setBlendMode(core.utils.correctBlendMode(container.blendMode, baseTexture.premultipliedAlpha)); + + var gl = renderer.gl; + + var m = container.worldTransform.copy(this.tempMatrix); + + m.prepend(renderer._activeRenderTarget.projectionMatrix); + + this.shader.uniforms.projectionMatrix = m.toArray(true); + + this.shader.uniforms.uColor = core.utils.premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, baseTexture.premultipliedAlpha); + + // make sure the texture is bound.. + this.shader.uniforms.uSampler = renderer.bindTexture(baseTexture); + + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = totalChildren - i; + + if (amount > batchSize) { + amount = batchSize; + } + + var buffer = buffers[j]; + + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + + // we only upload the static content when we have to! + if (container._bufferToUpdate === j) { + buffer.uploadStatic(children, i, amount); + container._bufferToUpdate = j + 1; + } + + // bind the buffer + renderer.bindVao(buffer.vao); + buffer.vao.draw(gl.TRIANGLES, amount * 6); + } + }; + + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer[]} The buffers + */ + + + ParticleRenderer.prototype.generateBuffers = function generateBuffers(container) { + var gl = this.renderer.gl; + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + for (var i = 0; i < size; i += batchSize) { + buffers.push(new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize)); + } + + return buffers; + }; + + /** + * Uploads the verticies. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their vertices uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadVertices = function uploadVertices(children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - sprite.anchor.x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - sprite.anchor.y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - sprite.anchor.x); + w1 = orig.width * -sprite.anchor.x; + + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + + array[offset + stride * 2] = w0 * sx; + array[offset + stride * 2 + 1] = h0 * sy; + + array[offset + stride * 3] = w1 * sx; + array[offset + stride * 3 + 1] = h0 * sy; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their positions uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadPosition = function uploadPosition(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + + array[offset + stride * 2] = spritePosition.x; + array[offset + stride * 2 + 1] = spritePosition.y; + + array[offset + stride * 3] = spritePosition.x; + array[offset + stride * 3 + 1] = spritePosition.y; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadRotation = function uploadRotation(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + stride * 2] = spriteRotation; + array[offset + stride * 3] = spriteRotation; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadUvs = function uploadUvs(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + + array[offset + stride * 2] = textureUvs.x2; + array[offset + stride * 2 + 1] = textureUvs.y2; + + array[offset + stride * 3] = textureUvs.x3; + array[offset + stride * 3 + 1] = textureUvs.y3; + + offset += stride * 4; + } else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + + array[offset + stride * 2] = 0; + array[offset + stride * 2 + 1] = 0; + + array[offset + stride * 3] = 0; + array[offset + stride * 3 + 1] = 0; + + offset += stride * 4; + } + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadAlpha = function uploadAlpha(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteAlpha = children[startIndex + i].alpha; + + array[offset] = spriteAlpha; + array[offset + stride] = spriteAlpha; + array[offset + stride * 2] = spriteAlpha; + array[offset + stride * 3] = spriteAlpha; + + offset += stride * 4; + } + }; + + /** + * Destroys the ParticleRenderer. + * + */ + + + ParticleRenderer.prototype.destroy = function destroy() { + if (this.renderer.gl) { + this.renderer.gl.deleteBuffer(this.indexBuffer); + } + + _core$ObjectRenderer.prototype.destroy.call(this); + + this.shader.destroy(); + + this.indices = null; + this.tempMatrix = null; + }; + + return ParticleRenderer; +}(core.ObjectRenderer); + +exports.default = ParticleRenderer; + + +core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + +},{"../../core":64,"./ParticleBuffer":174,"./ParticleShader":176}],176:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../core/Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI + */ +var ParticleShader = function (_Shader) { + _inherits(ParticleShader, _Shader); + + /** + * @param {PIXI.Shader} gl - The webgl shader manager this shader works for. + */ + function ParticleShader(gl) { + _classCallCheck(this, ParticleShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'attribute float aColor;', 'attribute vec2 aPositionCoord;', 'attribute vec2 aScale;', 'attribute float aRotation;', 'uniform mat3 projectionMatrix;', 'varying vec2 vTextureCoord;', 'varying float vColor;', 'void main(void){', ' vec2 v = aVertexPosition;', ' v.x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);', ' v.y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);', ' v = v + aPositionCoord;', ' gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = aColor;', '}'].join('\n'), + // hello + ['varying vec2 vTextureCoord;', 'varying float vColor;', 'uniform sampler2D uSampler;', 'uniform vec4 uColor;', 'void main(void){', ' vec4 color = texture2D(uSampler, vTextureCoord) * vColor * uColor;', ' if (color.a == 0.0) discard;', ' gl_FragColor = color;', '}'].join('\n'))); + } + + return ParticleShader; +}(_Shader3.default); + +exports.default = ParticleShader; + +},{"../../core/Shader":43}],177:[function(require,module,exports){ +"use strict"; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + +if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + + if (x === 0 || isNaN(x)) { + return x; + } + + return x > 0 ? 1 : -1; + }; +} + +},{}],178:[function(require,module,exports){ +'use strict'; + +var _objectAssign = require('object-assign'); + +var _objectAssign2 = _interopRequireDefault(_objectAssign); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +if (!Object.assign) { + Object.assign = _objectAssign2.default; +} // References: +// https://github.com/sindresorhus/object-assign +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + +},{"object-assign":5}],179:[function(require,module,exports){ +'use strict'; + +require('./Object.assign'); + +require('./requestAnimationFrame'); + +require('./Math.sign'); + +if (!window.ArrayBuffer) { + window.ArrayBuffer = Array; +} + +if (!window.Float32Array) { + window.Float32Array = Array; +} + +if (!window.Uint32Array) { + window.Uint32Array = Array; +} + +if (!window.Uint16Array) { + window.Uint16Array = Array; +} + +},{"./Math.sign":177,"./Object.assign":178,"./requestAnimationFrame":180}],180:[function(require,module,exports){ +(function (global){ +'use strict'; + +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + +// Expected to be used with Browserfiy +// Browserify automatically detects the use of `global` and passes the +// correct reference of `global`, `self`, and finally `window` + +var ONE_FRAME_TIME = 16; + +// Date.now +if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; +} + +// performance.now +if (!(global.performance && global.performance.now)) { + (function () { + var startTime = Date.now(); + + if (!global.performance) { + global.performance = {}; + } + + global.performance.now = function () { + return Date.now() - startTime; + }; + })(); +} + +// requestAnimationFrame +var lastTime = Date.now(); +var vendors = ['ms', 'moz', 'webkit', 'o']; + +for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { + var p = vendors[x]; + + global.requestAnimationFrame = global[p + 'RequestAnimationFrame']; + global.cancelAnimationFrame = global[p + 'CancelAnimationFrame'] || global[p + 'CancelRequestAnimationFrame']; +} + +if (!global.requestAnimationFrame) { + global.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + 'is not a function'); + } + + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + + if (delay < 0) { + delay = 0; + } + + lastTime = currentTime; + + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} + +if (!global.cancelAnimationFrame) { + global.cancelAnimationFrame = function (id) { + return clearTimeout(id); + }; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],181:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CountLimiter = require('./limiters/CountLimiter'); + +var _CountLimiter2 = _interopRequireDefault(_CountLimiter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SharedTicker = core.ticker.shared; + +/** + * Default number of uploads per frame using prepare plugin. + * + * @static + * @memberof PIXI.settings + * @name UPLOADS_PER_FRAME + * @type {number} + * @default 4 + */ +core.settings.UPLOADS_PER_FRAME = 4; + +/** + * The prepare manager provides functionality to upload content to the GPU. BasePrepare handles + * basic queuing functionality and is extended by {@link PIXI.prepare.WebGLPrepare} and {@link PIXI.prepare.CanvasPrepare} + * to provide preparation capabilities specific to their respective renderers. + * + * @example + * // Create a sprite + * const sprite = new PIXI.Sprite.fromImage('something.png'); + * + * // Load object into GPU + * app.renderer.plugins.prepare.upload(sprite, () => { + * + * //Texture(s) has been uploaded to GPU + * app.stage.addChild(sprite); + * + * }) + * + * @abstract + * @class + * @memberof PIXI.prepare + */ + +var BasePrepare = function () { + /** + * @param {PIXI.SystemRenderer} renderer - A reference to the current renderer + */ + function BasePrepare(renderer) { + var _this = this; + + _classCallCheck(this, BasePrepare); + + /** + * The limiter to be used to control how quickly items are prepared. + * @type {PIXI.prepare.CountLimiter|PIXI.prepare.TimeLimiter} + */ + this.limiter = new _CountLimiter2.default(core.settings.UPLOADS_PER_FRAME); + + /** + * Reference to the renderer. + * @type {PIXI.SystemRenderer} + * @protected + */ + this.renderer = renderer; + + /** + * The only real difference between CanvasPrepare and WebGLPrepare is what they pass + * to upload hooks. That different parameter is stored here. + * @type {PIXI.prepare.CanvasPrepare|PIXI.WebGLRenderer} + * @protected + */ + this.uploadHookHelper = null; + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + /** + * 'bound' call for prepareItems(). + * @type {Function} + * @private + */ + this.delayedTick = function () { + // unlikely, but in case we were destroyed between tick() and delayedTick() + if (!_this.queue) { + return; + } + _this.prepareItems(); + }; + + // hooks to find the correct texture + this.registerFindHook(findText); + this.registerFindHook(findTextStyle); + this.registerFindHook(findMultipleBaseTextures); + this.registerFindHook(findBaseTexture); + this.registerFindHook(findTexture); + + // upload hooks + this.registerUploadHook(drawText); + this.registerUploadHook(calculateTextStyle); + } + + /** + * Upload all the textures and graphics to the GPU. + * + * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item - + * Either the container or display object to search for items to upload, the items to upload themselves, + * or the callback function, if items have been added using `prepare.add`. + * @param {Function} [done] - Optional callback when all queued uploads have completed + */ + + + BasePrepare.prototype.upload = function upload(item, done) { + if (typeof item === 'function') { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) { + if (done) { + this.completes.push(done); + } + + if (!this.ticking) { + this.ticking = true; + SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); + } + } else if (done) { + done(); + } + }; + + /** + * Handle tick update + * + * @private + */ + + + BasePrepare.prototype.tick = function tick() { + setTimeout(this.delayedTick, 0); + }; + + /** + * Actually prepare items. This is handled outside of the tick because it will take a while + * and we do NOT want to block the current animation frame from rendering. + * + * @private + */ + + + BasePrepare.prototype.prepareItems = function prepareItems() { + this.limiter.beginFrame(); + // Upload the graphics + while (this.queue.length && this.limiter.allowedToUpload()) { + var item = this.queue[0]; + var uploaded = false; + + if (item && !item._destroyed) { + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.uploadHookHelper, item)) { + this.queue.shift(); + uploaded = true; + break; + } + } + } + + if (!uploaded) { + this.queue.shift(); + } + } + + // We're finished + if (!this.queue.length) { + this.ticking = false; + + var completes = this.completes.slice(0); + + this.completes.length = 0; + + for (var _i = 0, _len = completes.length; _i < _len; _i++) { + completes[_i](); + } + } else { + // if we are not finished, on the next rAF do this again + SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); + } + }; + + /** + * Adds hooks for finding items. + * + * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.registerFindHook = function registerFindHook(addHook) { + if (addHook) { + this.addHooks.push(addHook); + } + + return this; + }; + + /** + * Adds hooks for uploading items. + * + * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.registerUploadHook = function registerUploadHook(uploadHook) { + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + + return this; + }; + + /** + * Manually add an item to the uploading queue. + * + * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to + * add to the queue + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.add = function add(item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) { + for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { + this.add(item.children[_i2]); + } + } + + return this; + }; + + /** + * Destroys the plugin, don't use after this. + * + */ + + + BasePrepare.prototype.destroy = function destroy() { + if (this.ticking) { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.limiter = null; + this.uploadHookHelper = null; + }; + + return BasePrepare; +}(); + +/** + * Built-in hook to find multiple textures from objects like AnimatedSprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ + + +exports.default = BasePrepare; +function findMultipleBaseTextures(item, queue) { + var result = false; + + // Objects with mutliple textures + if (item && item._textures && item._textures.length) { + for (var i = 0; i < item._textures.length; i++) { + if (item._textures[i] instanceof core.Texture) { + var baseTexture = item._textures[i].baseTexture; + + if (queue.indexOf(baseTexture) === -1) { + queue.push(baseTexture); + result = true; + } + } + } + } + + return result; +} + +/** + * Built-in hook to find BaseTextures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTexture(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findTexture(item, queue) { + if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to draw PIXI.Text to its texture. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function drawText(helper, item) { + if (item instanceof core.Text) { + // updating text will return early if it is not dirty + item.updateText(true); + + return true; + } + + return false; +} + +/** + * Built-in hook to calculate a text style for a PIXI.Text object. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function calculateTextStyle(helper, item) { + if (item instanceof core.TextStyle) { + var font = item.toFontString(); + + core.TextMetrics.measureFont(font); + + return true; + } + + return false; +} + +/** + * Built-in hook to find Text objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Text object was found. + */ +function findText(item, queue) { + if (item instanceof core.Text) { + // push the text style to prepare it - this can be really expensive + if (queue.indexOf(item.style) === -1) { + queue.push(item.style); + } + // also push the text object so that we can render it (to canvas/texture) if needed + if (queue.indexOf(item) === -1) { + queue.push(item); + } + // also push the Text's texture for upload to GPU + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find TextStyle objects. + * + * @private + * @param {PIXI.TextStyle} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.TextStyle object was found. + */ +function findTextStyle(item, queue) { + if (item instanceof core.TextStyle) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +},{"../core":64,"./limiters/CountLimiter":184}],182:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CANVAS_START_SIZE = 16; + +/** + * The prepare manager provides functionality to upload content to the GPU + * This cannot be done directly for Canvas like in WebGL, but the effect can be achieved by drawing + * textures to an offline canvas. + * This draw call will force the texture to be moved onto the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ + +var CanvasPrepare = function (_BasePrepare) { + _inherits(CanvasPrepare, _BasePrepare); + + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasPrepare(renderer) { + _classCallCheck(this, CanvasPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this; + + /** + * An offline canvas to render textures to + * @type {HTMLCanvasElement} + * @private + */ + _this.canvas = document.createElement('canvas'); + _this.canvas.width = CANVAS_START_SIZE; + _this.canvas.height = CANVAS_START_SIZE; + + /** + * The context to the canvas + * @type {CanvasRenderingContext2D} + * @private + */ + _this.ctx = _this.canvas.getContext('2d'); + + // Add textures to upload + _this.registerUploadHook(uploadBaseTextures); + return _this; + } + + /** + * Destroys the plugin, don't use after this. + * + */ + + + CanvasPrepare.prototype.destroy = function destroy() { + _BasePrepare.prototype.destroy.call(this); + this.ctx = null; + this.canvas = null; + }; + + return CanvasPrepare; +}(_BasePrepare3.default); + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {*} prepare - Instance of CanvasPrepare + * @param {*} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = CanvasPrepare; +function uploadBaseTextures(prepare, item) { + if (item instanceof core.BaseTexture) { + var image = item.source; + + // Sometimes images (like atlas images) report a size of zero, causing errors on windows phone. + // So if the width or height is equal to zero then use the canvas size + // Otherwise use whatever is smaller, the image dimensions or the canvas dimensions. + var imageWidth = image.width === 0 ? prepare.canvas.width : Math.min(prepare.canvas.width, image.width); + var imageHeight = image.height === 0 ? prepare.canvas.height : Math.min(prepare.canvas.height, image.height); + + // Only a small subsections is required to be drawn to have the whole texture uploaded to the GPU + // A smaller draw can be faster. + prepare.ctx.drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, prepare.canvas.width, prepare.canvas.height); + + return true; + } + + return false; +} + +core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); + +},{"../../core":64,"../BasePrepare":181}],183:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLPrepare = require('./webgl/WebGLPrepare'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLPrepare).default; + } +}); + +var _CanvasPrepare = require('./canvas/CanvasPrepare'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasPrepare).default; + } +}); + +var _BasePrepare = require('./BasePrepare'); + +Object.defineProperty(exports, 'BasePrepare', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BasePrepare).default; + } +}); + +var _CountLimiter = require('./limiters/CountLimiter'); + +Object.defineProperty(exports, 'CountLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CountLimiter).default; + } +}); + +var _TimeLimiter = require('./limiters/TimeLimiter'); + +Object.defineProperty(exports, 'TimeLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TimeLimiter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./BasePrepare":181,"./canvas/CanvasPrepare":182,"./limiters/CountLimiter":184,"./limiters/TimeLimiter":185,"./webgl/WebGLPrepare":186}],184:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * CountLimiter limits the number of items handled by a {@link PIXI.prepare.BasePrepare} to a specified + * number of items per frame. + * + * @class + * @memberof PIXI + */ +var CountLimiter = function () { + /** + * @param {number} maxItemsPerFrame - The maximum number of items that can be prepared each frame. + */ + function CountLimiter(maxItemsPerFrame) { + _classCallCheck(this, CountLimiter); + + /** + * The maximum number of items that can be prepared each frame. + * @private + */ + this.maxItemsPerFrame = maxItemsPerFrame; + /** + * The number of items that can be prepared in the current frame. + * @type {number} + * @private + */ + this.itemsLeft = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + CountLimiter.prototype.beginFrame = function beginFrame() { + this.itemsLeft = this.maxItemsPerFrame; + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + CountLimiter.prototype.allowedToUpload = function allowedToUpload() { + return this.itemsLeft-- > 0; + }; + + return CountLimiter; +}(); + +exports.default = CountLimiter; + +},{}],185:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of milliseconds per frame. + * + * @class + * @memberof PIXI + */ +var TimeLimiter = function () { + /** + * @param {number} maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. + */ + function TimeLimiter(maxMilliseconds) { + _classCallCheck(this, TimeLimiter); + + /** + * The maximum milliseconds that can be spent preparing items each frame. + * @private + */ + this.maxMilliseconds = maxMilliseconds; + /** + * The start time of the current frame. + * @type {number} + * @private + */ + this.frameStart = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + TimeLimiter.prototype.beginFrame = function beginFrame() { + this.frameStart = Date.now(); + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + TimeLimiter.prototype.allowedToUpload = function allowedToUpload() { + return Date.now() - this.frameStart < this.maxMilliseconds; + }; + + return TimeLimiter; +}(); + +exports.default = TimeLimiter; + +},{}],186:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The prepare manager provides functionality to upload content to the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ +var WebGLPrepare = function (_BasePrepare) { + _inherits(WebGLPrepare, _BasePrepare); + + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLPrepare(renderer) { + _classCallCheck(this, WebGLPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this.renderer; + + // Add textures and graphics to upload + _this.registerFindHook(findGraphics); + _this.registerUploadHook(uploadBaseTextures); + _this.registerUploadHook(uploadGraphics); + return _this; + } + + return WebGLPrepare; +}(_BasePrepare3.default); +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = WebGLPrepare; +function uploadBaseTextures(renderer, item) { + if (item instanceof core.BaseTexture) { + // if the texture already has a GL texture, then the texture has been prepared or rendered + // before now. If the texture changed, then the changer should be calling texture.update() which + // reuploads the texture without need for preparing it again + if (!item._glTextures[renderer.CONTEXT_UID]) { + renderer.textureManager.updateTexture(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to upload PIXI.Graphics to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadGraphics(renderer, item) { + if (item instanceof core.Graphics) { + // if the item is not dirty and already has webgl data, then it got prepared or rendered + // before now and we shouldn't waste time updating it again + if (item.dirty || item.clearDirty || !item._webGL[renderer.plugins.graphics.CONTEXT_UID]) { + renderer.plugins.graphics.updateGraphics(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find graphics. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Graphics object was found. + */ +function findGraphics(item, queue) { + if (item instanceof core.Graphics) { + queue.push(item); + + return true; + } + + return false; +} + +core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); + +},{"../../core":64,"../BasePrepare":181}],187:[function(require,module,exports){ +(function (global){ +'use strict'; + +exports.__esModule = true; +exports.loader = exports.prepare = exports.particles = exports.mesh = exports.loaders = exports.interaction = exports.filters = exports.extras = exports.extract = exports.accessibility = undefined; + +var _polyfill = require('./polyfill'); + +Object.keys(_polyfill).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _polyfill[key]; + } + }); +}); + +var _core = require('./core'); + +Object.keys(_core).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _core[key]; + } + }); +}); + +var _deprecation = require('./deprecation'); + +var _deprecation2 = _interopRequireDefault(_deprecation); + +var _accessibility = require('./accessibility'); + +var accessibility = _interopRequireWildcard(_accessibility); + +var _extract = require('./extract'); + +var extract = _interopRequireWildcard(_extract); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// export core +_core.utils.mixins.performMixins(); + +/** + * Alias for {@link PIXI.loaders.shared}. + * @name loader + * @memberof PIXI + * @type {PIXI.loader.Loader} + */ + + +// handle mixins now, after all code has been added, including deprecation + + +// export libs +// import polyfills. Done as an export to make sure polyfills are imported first +var loader = loaders.shared || null; + +exports.accessibility = accessibility; +exports.extract = extract; +exports.extras = extras; +exports.filters = filters; +exports.interaction = interaction; +exports.loaders = loaders; +exports.mesh = mesh; +exports.particles = particles; +exports.prepare = prepare; +exports.loader = loader; + +// Apply the deprecations + +if (typeof _deprecation2.default === 'function') { + (0, _deprecation2.default)(exports); +} + +// Always export pixi globally. +global.PIXI = exports; // eslint-disable-line + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"./accessibility":41,"./core":64,"./deprecation":129,"./extract":131,"./extras":140,"./filters":151,"./interaction":158,"./loaders":161,"./mesh":170,"./particles":173,"./polyfill":179,"./prepare":183}]},{},[187])(187) +}); + + +//# sourceMappingURL=pixi.js.map diff --git a/js/pixi/4.5.3/pixi.min.js b/js/pixi/4.5.3/pixi.min.js new file mode 100644 index 0000000..ec7bee8 --- /dev/null +++ b/js/pixi/4.5.3/pixi.min.js @@ -0,0 +1,22 @@ +/*! + * pixi.js - v4.5.3 + * Compiled Mon, 12 Jun 2017 14:48:33 UTC + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.PIXI=t()}}(function(){var t;return function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var h=new Error("Cannot find module '"+s+"'");throw h.code="MODULE_NOT_FOUND",h}var l=r[s]={exports:{}};e[s][0].call(l.exports,function(t){var r=e[s][1][t];return i(r?r:t)},l,l.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s0)-(t<0)},r.abs=function(t){var e=t>>i-1;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,e|=r,e|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,t=(858993459&t)+(t>>>2&858993459),16843009*(t+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,t&=15,27030>>>t&1};var o=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|o[t>>>16&255]<<8|o[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),t=65535&(t|t>>>16),t<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),t=1023&(t|t>>>16),t<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],2:[function(t,e,r){"use strict";function n(t,e,r){r=r||2;var n=e&&e.length,o=n?e[0]*r:t.length,a=i(t,0,o,r,!0),u=[];if(!a)return u;var h,l,d,f,p,v,y;if(n&&(a=c(t,e,a,r)),t.length>80*r){h=d=t[0],l=f=t[1];for(var g=r;gd&&(d=p),v>f&&(f=v);y=Math.max(d-h,f-l)}return s(a,u,r,h,l,y),u}function i(t,e,r,n,i){var o,s;if(i===A(t,e,r,n)>0)for(o=e;o=e;o-=n)s=M(o,t[o],t[o+1],s);return s&&T(s,s.next)&&(C(s),s=s.next),s}function o(t,e){if(!t)return t;e||(e=t);var r,n=t;do if(r=!1,n.steiner||!T(n,n.next)&&0!==x(n.prev,n,n.next))n=n.next;else{if(C(n),n=e=n.prev,n===n.next)return null;r=!0}while(r||n!==e);return e}function s(t,e,r,n,i,c,d){if(t){!d&&c&&v(t,n,i,c);for(var f,p,y=t;t.prev!==t.next;)if(f=t.prev,p=t.next,c?u(t,n,i,c):a(t))e.push(f.i/r),e.push(t.i/r),e.push(p.i/r),C(t),t=p.next,y=p.next;else if(t=p,t===y){d?1===d?(t=h(t,e,r),s(t,e,r,n,i,c,2)):2===d&&l(t,e,r,n,i,c):s(o(t),e,r,n,i,c,1);break}}}function a(t){var e=t.prev,r=t,n=t.next;if(x(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(_(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&x(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function u(t,e,r,n){var i=t.prev,o=t,s=t.next;if(x(i,o,s)>=0)return!1;for(var a=i.xo.x?i.x>s.x?i.x:s.x:o.x>s.x?o.x:s.x,l=i.y>o.y?i.y>s.y?i.y:s.y:o.y>s.y?o.y:s.y,c=g(a,u,e,r,n),d=g(h,l,e,r,n),f=t.nextZ;f&&f.z<=d;){if(f!==t.prev&&f!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,f.x,f.y)&&x(f.prev,f,f.next)>=0)return!1;f=f.nextZ}for(f=t.prevZ;f&&f.z>=c;){if(f!==t.prev&&f!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,f.x,f.y)&&x(f.prev,f,f.next)>=0)return!1;f=f.prevZ}return!0}function h(t,e,r){var n=t;do{var i=n.prev,o=n.next.next;!T(i,o)&&w(i,n,n.next,o)&&S(i,o)&&S(o,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(o.i/r),C(n),C(n.next),n=t=o),n=n.next}while(n!==t);return n}function l(t,e,r,n,i,a){var u=t;do{for(var h=u.next.next;h!==u.prev;){if(u.i!==h.i&&b(u,h)){var l=P(u,h);return u=o(u,u.next),l=o(l,l.next),s(u,e,r,n,i,a),void s(l,e,r,n,i,a)}h=h.next}u=u.next}while(u!==t)}function c(t,e,r,n){var s,a,u,h,l,c=[];for(s=0,a=e.length;s=n.next.y){var a=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=i&&a>s){if(s=a,a===i){if(o===n.y)return n;if(o===n.next.y)return n.next}r=n.x=n.x&&n.x>=l&&_(or.x)&&S(n,t)&&(r=n,d=u)),n=n.next;return r}function v(t,e,r,n){var i=t;do null===i.z&&(i.z=g(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,y(i)}function y(t){var e,r,n,i,o,s,a,u,h=1;do{for(r=t,t=null,o=null,s=0;r;){for(s++,n=r,a=0,e=0;e0||u>0&&n;)0===a?(i=n,n=n.nextZ,u--):0!==u&&n?r.z<=n.z?(i=r,r=r.nextZ,a--):(i=n,n=n.nextZ,u--):(i=r,r=r.nextZ,a--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;r=n}o.nextZ=null,h*=2}while(s>1);return t}function g(t,e,r,n,i){return t=32767*(t-r)/i,e=32767*(e-n)/i,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1}function m(t){var e=t,r=t;do e.x=0&&(t-s)*(n-a)-(r-s)*(e-a)>=0&&(r-s)*(o-a)-(i-s)*(n-a)>=0}function b(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!E(t,e)&&S(t,e)&&S(e,t)&&O(t,e)}function x(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function T(t,e){return t.x===e.x&&t.y===e.y}function w(t,e,r,n){return!!(T(t,e)&&T(r,n)||T(t,n)&&T(r,e))||x(t,e,r)>0!=x(t,e,n)>0&&x(r,n,t)>0!=x(r,n,e)>0}function E(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&w(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}function S(t,e){return x(t.prev,t,t.next)<0?x(t,e,t.next)>=0&&x(t,t.prev,e)>=0:x(t,e,t.prev)<0||x(t,t.next,e)<0}function O(t,e){var r=t,n=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do r.y>o!=r.next.y>o&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;while(r!==t);return n}function P(t,e){var r=new R(t.i,t.x,t.y),n=new R(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function M(t,e,r,n){var i=new R(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function C(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function R(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(t,e,r,n){for(var i=0,o=e,s=r-n;o0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],3:[function(t,e,r){"use strict";function n(){}function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function o(){this._events=new n,this._eventsCount=0}var s=Object.prototype.hasOwnProperty,a="~";Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(a=!1)),o.prototype.eventNames=function(){var t,e,r=[];if(0===this._eventsCount)return r;for(e in t=this._events)s.call(t,e)&&r.push(a?e.slice(1):e);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t,e){var r=a?a+t:t,n=this._events[r];if(e)return!!n;if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i=t.byteLength?n.bufferSubData(this.type,e,t):n.bufferData(this.type,t,this.drawType),this.data=t},i.prototype.bind=function(){var t=this.gl;t.bindBuffer(this.type,this.buffer)},i.createVertexBuffer=function(t,e,r){return new i(t,t.ARRAY_BUFFER,e,r)},i.createIndexBuffer=function(t,e,r){return new i(t,t.ELEMENT_ARRAY_BUFFER,e,r)},i.create=function(t,e,r,n){return new i(t,e,r,n)},i.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer)},e.exports=i},{}],7:[function(t,e,r){var n=t("./GLTexture"),i=function(t,e,r){this.gl=t,this.framebuffer=t.createFramebuffer(),this.stencil=null,this.texture=null,this.width=e||100,this.height=r||100};i.prototype.enableTexture=function(t){var e=this.gl;this.texture=t||new n(e),this.texture.bind(),this.bind(),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0)},i.prototype.enableStencil=function(){if(!this.stencil){var t=this.gl;this.stencil=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.stencil),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.stencil),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,this.width,this.height)}},i.prototype.clear=function(t,e,r,n){this.bind();var i=this.gl;i.clearColor(t,e,r,n),i.clear(i.COLOR_BUFFER_BIT)},i.prototype.bind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer)},i.prototype.unbind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)},i.prototype.resize=function(t,e){var r=this.gl;this.width=t,this.height=e,this.texture&&this.texture.uploadData(null,t,e),this.stencil&&(r.bindRenderbuffer(r.RENDERBUFFER,this.stencil),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e))},i.prototype.destroy=function(){var t=this.gl;this.texture&&this.texture.destroy(),t.deleteFramebuffer(this.framebuffer),this.gl=null,this.stencil=null,this.texture=null},i.createRGBA=function(t,e,r,o){var s=n.fromData(t,null,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},i.createFloat32=function(t,e,r,o){var s=new n.fromData(t,o,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},e.exports=i},{"./GLTexture":9}],8:[function(t,e,r){var n=t("./shader/compileProgram"),i=t("./shader/extractAttributes"),o=t("./shader/extractUniforms"),s=t("./shader/generateUniformAccessObject"),a=function(t,e,r){this.gl=t,this.program=n(t,e,r),this.attributes=i(t,this.program);var a=o(t,this.program);this.uniforms=s(t,a)};a.prototype.bind=function(){this.gl.useProgram(this.program)},a.prototype.destroy=function(){},e.exports=a},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18}],9:[function(t,e,r){var n=function(t,e,r,n,i){this.gl=t,this.texture=t.createTexture(),this.mipmap=!1,this.premultiplyAlpha=!1,this.width=e||-1,this.height=r||-1,this.format=n||t.RGBA,this.type=i||t.UNSIGNED_BYTE};n.prototype.upload=function(t){this.bind();var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var r=t.videoWidth||t.width,n=t.videoHeight||t.height;n!==this.height||r!==this.width?e.texImage2D(e.TEXTURE_2D,0,this.format,this.format,this.type,t):e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.format,this.type,t),this.width=r,this.height=n};var i=!1;n.prototype.uploadData=function(t,e,r){this.bind();var n=this.gl;if(t instanceof Float32Array){if(!i){var o=n.getExtension("OES_texture_float");if(!o)throw new Error("floating point textures not available");i=!0}this.type=n.FLOAT}else this.type=n.UNSIGNED_BYTE;n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),e!==this.width||r!==this.height?n.texImage2D(n.TEXTURE_2D,0,this.format,e,r,0,this.format,this.type,t||null):n.texSubImage2D(n.TEXTURE_2D,0,0,0,e,r,this.format,this.type,t||null),this.width=e,this.height=r},n.prototype.bind=function(t){var e=this.gl;void 0!==t&&e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,this.texture)},n.prototype.unbind=function(){var t=this.gl;t.bindTexture(t.TEXTURE_2D,null)},n.prototype.minFilter=function(t){var e=this.gl;this.bind(),this.mipmap?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.magFilter=function(t){var e=this.gl;this.bind(),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.enableMipmap=function(){var t=this.gl;this.bind(),this.mipmap=!0,t.generateMipmap(t.TEXTURE_2D)},n.prototype.enableLinearScaling=function(){this.minFilter(!0),this.magFilter(!0)},n.prototype.enableNearestScaling=function(){this.minFilter(!1),this.magFilter(!1)},n.prototype.enableWrapClamp=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)},n.prototype.enableWrapRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT)},n.prototype.enableWrapMirrorRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.MIRRORED_REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.MIRRORED_REPEAT)},n.prototype.destroy=function(){var t=this.gl;t.deleteTexture(this.texture)},n.fromSource=function(t,e,r){var i=new n(t);return i.premultiplyAlpha=r||!1,i.upload(e),i},n.fromData=function(t,e,r,i){var o=new n(t);return o.uploadData(e,r,i),o},e.exports=n},{}],10:[function(t,e,r){function n(t,e){if(this.nativeVaoExtension=null,n.FORCE_NATIVE||(this.nativeVaoExtension=t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object")),this.nativeState=e,this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var r=t.getParameter(t.MAX_VERTEX_ATTRIBS);this.nativeState={tempAttribState:new Array(r),attribState:new Array(r)}}this.gl=t,this.attributes=[],this.indexBuffer=null,this.dirty=!1}var i=t("./setVertexAttribArrays");n.prototype.constructor=n,e.exports=n,n.FORCE_NATIVE=!1,n.prototype.bind=function(){return this.nativeVao?(this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao),this.dirty&&(this.dirty=!1,this.activate())):this.activate(),this},n.prototype.unbind=function(){return this.nativeVao&&this.nativeVaoExtension.bindVertexArrayOES(null),this},n.prototype.activate=function(){for(var t=this.gl,e=null,r=0;r=0;n--){var i=t[n];"."===i?t.splice(n,1):".."===i?(t.splice(n,1),r++):r&&(t.splice(n,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}function n(t,e){if(t.filter)return t.filter(e);for(var r=[],n=0;n=-1&&!i;o--){var s=o>=0?arguments[o]:t.cwd();if("string"!=typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(r=s+"/"+r,i="/"===s.charAt(0))}return r=e(n(r.split("/"),function(t){return!!t}),!i).join("/"),(i?"/":"")+r||"."},r.normalize=function(t){var i=r.isAbsolute(t),o="/"===s(t,-1);return t=e(n(t.split("/"),function(t){return!!t}),!i).join("/"),t||i||(t="."),t&&o&&(t+="/"),(i?"/":"")+t},r.isAbsolute=function(t){return"/"===t.charAt(0)},r.join=function(){var t=Array.prototype.slice.call(arguments,0);return r.normalize(n(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},r.relative=function(t,e){function n(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=r.resolve(t).substr(1),e=r.resolve(e).substr(1);for(var i=n(t.split("/")),o=n(e.split("/")),s=Math.min(i.length,o.length),a=s,u=0;u1)for(var r=1;r1&&(n=r[0]+"@",t=r[1]),t=t.replace(D,".");var i=t.split("."),o=s(i,e).join(".");return n+o}function u(t){for(var e,r,n=[],i=0,o=t.length;i=55296&&e<=56319&&i65535&&(t-=65536,e+=B(t>>>10&1023|55296),t=56320|1023&t),e+=B(t)}).join("")}function l(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:w}function c(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function d(t,e,r){var n=0;for(t=r?F(t/P):t>>1,t+=F(t/e);t>N*S>>1;n+=w)t=F(t/N);return F(n+(N+1)*t/(t+O))}function f(t){var e,r,n,i,s,a,u,c,f,p,v=[],y=t.length,g=0,m=C,_=M;for(r=t.lastIndexOf(R),r<0&&(r=0),n=0;n=128&&o("not-basic"),v.push(t.charCodeAt(n));for(i=r>0?r+1:0;i=y&&o("invalid-input"),c=l(t.charCodeAt(i++)),(c>=w||c>F((T-g)/a))&&o("overflow"),g+=c*a,f=u<=_?E:u>=_+S?S:u-_,!(cF(T/p)&&o("overflow"),a*=p;e=v.length+1,_=d(g-s,e,0==s),F(g/e)>T-m&&o("overflow"),m+=F(g/e),g%=e,v.splice(g++,0,m)}return h(v)}function p(t){var e,r,n,i,s,a,h,l,f,p,v,y,g,m,_,b=[];for(t=u(t),y=t.length,e=C,r=0,s=M,a=0;a=e&&vF((T-r)/g)&&o("overflow"),r+=(h-e)*g,e=h,a=0;aT&&o("overflow"),v==e){for(l=r,f=w;p=f<=s?E:f>=s+S?S:f-s,!(l= 0x80 (not a basic code point)","invalid-input":"Invalid input"},N=w-E,F=Math.floor,B=String.fromCharCode;if(b={version:"1.4.1",ucs2:{decode:u,encode:h},decode:f,encode:p,toASCII:y,toUnicode:v},"function"==typeof t&&"object"==typeof t.amd&&t.amd)t("punycode",function(){return b});else if(g&&m)if(r.exports==g)m.exports=b;else for(x in b)b.hasOwnProperty(x)&&(g[x]=b[x]);else i.punycode=b}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],25:[function(t,e,r){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,r,o){e=e||"&",r=r||"=";var s={};if("string"!=typeof t||0===t.length)return s;var a=/\+/g;t=t.split(e);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var h=t.length;u>0&&h>u&&(h=u);for(var l=0;l=0?(c=v.substr(0,y),d=v.substr(y+1)):(c=v,d=""),f=decodeURIComponent(c),p=decodeURIComponent(d),n(s,f)?i(s[f])?s[f].push(p):s[f]=[s[f],p]:s[f]=p}return s};var i=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],26:[function(t,e,r){"use strict";function n(t,e){if(t.map)return t.map(e);for(var r=[],n=0;n",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(f),v=["'"].concat(p),y=["%","/","?",";","#"].concat(v),g=["/","?","#"],m=255,_=/^[+a-z0-9A-Z_-]{0,63}$/,b=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,x={javascript:!0,"javascript:":!0},T={javascript:!0,"javascript:":!0},w={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},E=t("querystring");n.prototype.parse=function(t,e,r){if(!h.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var n=t.indexOf("?"),i=n!==-1&&n127?"x":L[F];if(!N.match(_)){var k=I.slice(0,P),j=I.slice(P+1),U=L.match(b);U&&(k.push(U[1]),j.unshift(U[2])),j.length&&(a="/"+j.join(".")+a),this.hostname=k.join(".");break}}}this.hostname.length>m?this.hostname="":this.hostname=this.hostname.toLowerCase(),A||(this.hostname=u.toASCII(this.hostname));var X=this.port?":"+this.port:"",G=this.hostname||"";this.host=G+X,this.href+=this.host,A&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==a[0]&&(a="/"+a))}if(!x[p])for(var P=0,D=v.length;P0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return r.search=t.search,r.query=t.query,h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!x.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var O=x.slice(-1)[0],P=(r.host||t.host||x.length>1)&&("."===O||".."===O)||""===O,M=0,C=x.length;C>=0;C--)O=x[C],"."===O?x.splice(C,1):".."===O?(x.splice(C,1),M++):M&&(x.splice(C,1),M--);if(!_&&!b)for(;M--;M)x.unshift("..");!_||""===x[0]||x[0]&&"/"===x[0].charAt(0)||x.unshift(""),P&&"/"!==x.join("/").substr(-1)&&x.push("");var R=""===x[0]||x[0]&&"/"===x[0].charAt(0);if(E){r.hostname=r.host=R?"":x.length?x.shift():"";var S=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return _=_||r.host&&x.length,_&&!R&&x.unshift(""),x.length?r.pathname=x.join("/"):(r.pathname=null,r.path=null),h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},n.prototype.parseHost=function(){var t=this.host,e=c.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":29,punycode:24,querystring:27}],29:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],30:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n,i=t.length;if(!(e>=i||0===r)){r=e+r>i?i-e:r;var o=i-r;for(n=e;n0&&void 0!==arguments[0]?arguments[0]:"",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10;o(this,t),this.baseUrl=r,this.progress=0,this.loading=!1,this.defaultQueryString="",this._beforeMiddleware=[],this._afterMiddleware=[],this._resourcesParsing=[],this._boundLoadResource=function(t,r){return e._loadResource(t,r)},this._queue=d.queue(this._boundLoadResource,n),this._queue.pause(),this.resources={},this.onProgress=new u.default,this.onError=new u.default,this.onLoad=new u.default,this.onStart=new u.default,this.onComplete=new u.default}return t.prototype.add=function(t,e,r,n){if(Array.isArray(t)){for(var i=0;i0))return void this.abort("["+e.status+"] "+e.statusText+": "+e.responseURL);if(this.xhrType===t.XHR_RESPONSE_TYPE.TEXT)this.data=e.responseText,this.type=t.TYPE.TEXT;else if(this.xhrType===t.XHR_RESPONSE_TYPE.JSON)try{this.data=JSON.parse(e.responseText),this.type=t.TYPE.JSON}catch(t){return void this.abort("Error trying to parse loaded json: "+t)}else if(this.xhrType===t.XHR_RESPONSE_TYPE.DOCUMENT)try{if(window.DOMParser){var n=new DOMParser;this.data=n.parseFromString(e.responseText,"text/xml")}else{var i=document.createElement("div");i.innerHTML=e.responseText,this.data=i}this.type=t.TYPE.XML}catch(t){return void this.abort("Error trying to parse loaded xml: "+t)}else this.data=e.response||e.responseText;this.complete()},t.prototype._determineCrossOrigin=function(t,e){if(0===t.indexOf("data:"))return"";e=e||window.location,p||(p=document.createElement("a")),p.href=t,t=(0,l.default)(p.href,{strictMode:!0});var r=!t.port&&""===e.port||t.port===e.port,n=t.protocol?t.protocol+":":"";return t.host===e.hostname&&r&&n===e.protocol?"":"anonymous"},t.prototype._determineXhrType=function(){return t._xhrTypeMap[this.extension]||t.XHR_RESPONSE_TYPE.TEXT},t.prototype._determineLoadType=function(){return t._loadTypeMap[this.extension]||t.LOAD_TYPE.XHR},t.prototype._getExtension=function(){var t=this.url,e="";if(this.isDataUrl){var r=t.indexOf("/");e=t.substring(r+1,t.indexOf(";",r))}else{var n=t.indexOf("?");n!==-1&&(t=t.substring(0,n)),e=t.substring(t.lastIndexOf(".")+1)}return e.toLowerCase()},t.prototype._getMimeFromXhrType=function(e){switch(e){case t.XHR_RESPONSE_TYPE.BUFFER:return"application/octet-binary";case t.XHR_RESPONSE_TYPE.BLOB:return"application/blob";case t.XHR_RESPONSE_TYPE.DOCUMENT:return"application/xml";case t.XHR_RESPONSE_TYPE.JSON:return"application/json";case t.XHR_RESPONSE_TYPE.DEFAULT:case t.XHR_RESPONSE_TYPE.TEXT:default:return"text/plain"}},u(t,[{key:"isDataUrl",get:function(){return this._hasFlag(t.STATUS_FLAGS.DATA_URL)}},{key:"isComplete",get:function(){return this._hasFlag(t.STATUS_FLAGS.COMPLETE)}},{key:"isLoading",get:function(){return this._hasFlag(t.STATUS_FLAGS.LOADING)}}]),t}();r.default=m,m.STATUS_FLAGS={NONE:0,DATA_URL:1,COMPLETE:2,LOADING:4},m.TYPE={UNKNOWN:0,JSON:1,XML:2,IMAGE:3,AUDIO:4,VIDEO:5,TEXT:6},m.LOAD_TYPE={XHR:1,IMAGE:2,AUDIO:3,VIDEO:4},m.XHR_RESPONSE_TYPE={DEFAULT:"text",BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"},m._loadTypeMap={gif:m.LOAD_TYPE.IMAGE,png:m.LOAD_TYPE.IMAGE,bmp:m.LOAD_TYPE.IMAGE,jpg:m.LOAD_TYPE.IMAGE,jpeg:m.LOAD_TYPE.IMAGE,tif:m.LOAD_TYPE.IMAGE,tiff:m.LOAD_TYPE.IMAGE,webp:m.LOAD_TYPE.IMAGE,tga:m.LOAD_TYPE.IMAGE,svg:m.LOAD_TYPE.IMAGE,"svg+xml":m.LOAD_TYPE.IMAGE,mp3:m.LOAD_TYPE.AUDIO,ogg:m.LOAD_TYPE.AUDIO,wav:m.LOAD_TYPE.AUDIO,mp4:m.LOAD_TYPE.VIDEO,webm:m.LOAD_TYPE.VIDEO},m._xhrTypeMap={xhtml:m.XHR_RESPONSE_TYPE.DOCUMENT,html:m.XHR_RESPONSE_TYPE.DOCUMENT,htm:m.XHR_RESPONSE_TYPE.DOCUMENT,xml:m.XHR_RESPONSE_TYPE.DOCUMENT,tmx:m.XHR_RESPONSE_TYPE.DOCUMENT,svg:m.XHR_RESPONSE_TYPE.DOCUMENT,tsx:m.XHR_RESPONSE_TYPE.DOCUMENT,gif:m.XHR_RESPONSE_TYPE.BLOB,png:m.XHR_RESPONSE_TYPE.BLOB,bmp:m.XHR_RESPONSE_TYPE.BLOB,jpg:m.XHR_RESPONSE_TYPE.BLOB,jpeg:m.XHR_RESPONSE_TYPE.BLOB,tif:m.XHR_RESPONSE_TYPE.BLOB,tiff:m.XHR_RESPONSE_TYPE.BLOB,webp:m.XHR_RESPONSE_TYPE.BLOB,tga:m.XHR_RESPONSE_TYPE.BLOB,json:m.XHR_RESPONSE_TYPE.JSON,text:m.XHR_RESPONSE_TYPE.TEXT,txt:m.XHR_RESPONSE_TYPE.TEXT,ttf:m.XHR_RESPONSE_TYPE.BUFFER,otf:m.XHR_RESPONSE_TYPE.BUFFER},m.EMPTY_GIF="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="},{"mini-signals":37,"parse-uri":38}],33:[function(t,e,r){"use strict";function n(){}function i(t,e,r){var n=0,i=t.length;!function o(s){return s||n===i?void(r&&r(s)):void e(t[n++],o)}()}function o(t){return function(){if(null===t)throw new Error("Callback was already called.");var e=t;t=null,e.apply(this,arguments)}}function s(t,e){function r(t,e,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(a.started=!0,null==t&&a.idle())return void setTimeout(function(){return a.drain()},1);var i={data:t,callback:"function"==typeof r?r:n};e?a._tasks.unshift(i):a._tasks.push(i),setTimeout(function(){return a.process()},1)}function i(t){return function(){s-=1,t.callback.apply(t,arguments),null!=arguments[0]&&a.error(arguments[0],t.data),s<=a.concurrency-a.buffer&&a.unsaturated(),a.idle()&&a.drain(),a.process()}}if(null==e)e=1;else if(0===e)throw new Error("Concurrency must not be zero");var s=0,a={_tasks:[],concurrency:e,saturated:n,unsaturated:n,buffer:e/4,empty:n,drain:n,error:n,started:!1,paused:!1,push:function(t,e){r(t,!1,e)},kill:function(){s=0,a.drain=n,a.started=!1,a._tasks=[]},unshift:function(t,e){r(t,!0,e)},process:function(){for(;!a.paused&&s>2,o[1]=(3&n[0])<<4|n[1]>>4,o[2]=(15&n[1])<<2|n[2]>>6,o[3]=63&n[2];var a=r-(t.length-1);switch(a){case 2:o[3]=64,o[2]=64;break;case 1:o[3]=64}for(var u=0;u=0;r--)this.updateAccessibleObjects(e[r])}},t.prototype.update=function(){if(this.renderer.renderingToScreen){this.updateAccessibleObjects(this.renderer._lastObjectRendered);var t=this.renderer.view.getBoundingClientRect(),e=t.width/this.renderer.width,r=t.height/this.renderer.height,n=this.div;n.style.left=t.left+"px",n.style.top=t.top+"px",n.style.width=this.renderer.width+"px",n.style.height=this.renderer.height+"px";for(var i=0;ithis.renderer.width&&(t.width=this.renderer.width-t.x),t.y+t.height>this.renderer.height&&(t.height=this.renderer.height-t.y)},t.prototype.addChild=function(t){var e=this.pool.pop();e||(e=document.createElement("button"),e.style.width=f+"px",e.style.height=f+"px",e.style.backgroundColor=this.debug?"rgba(255,0,0,0.5)":"transparent",e.style.position="absolute",e.style.zIndex=y,e.style.borderStyle="none",e.addEventListener("click",this._onClick.bind(this)),e.addEventListener("focus",this._onFocus.bind(this)),e.addEventListener("focusout",this._onFocusOut.bind(this))),t.accessibleTitle?e.title=t.accessibleTitle:t.accessibleTitle||t.accessibleHint||(e.title="displayObject "+this.tabIndex),t.accessibleHint&&e.setAttribute("aria-label",t.accessibleHint),t._accessibleActive=!0,t._accessibleDiv=e,e.displayObject=t,this.children.push(t),this.div.appendChild(t._accessibleDiv),t._accessibleDiv.tabIndex=t.tabIndex},t.prototype._onClick=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"click",e.eventData)},t.prototype._onFocus=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseover",e.eventData)},t.prototype._onFocusOut=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseout",e.eventData)},t.prototype._onKeyDown=function(t){t.keyCode===d&&this.activate()},t.prototype._onMouseMove=function(){this.deactivate()},t.prototype.destroy=function(){this.div=null;for(var t=0;t]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i,r.SHAPES={POLY:0,RECT:1,CIRC:2,ELIP:3,RREC:4},r.PRECISION={LOW:"lowp",MEDIUM:"mediump",HIGH:"highp"},r.TRANSFORM_MODE={STATIC:0,DYNAMIC:1},r.TEXT_GRADIENT={LINEAR_VERTICAL:0,LINEAR_HORIZONTAL:1},r.UPDATE_PRIORITY={INTERACTION:50,HIGH:25,NORMAL:0,LOW:-25,UTILITY:-50}},{}],46:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../math"),o=function(){function t(){n(this,t),this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0),this.rect=null}return t.prototype.isEmpty=function(){return this.minX>this.maxX||this.minY>this.maxY},t.prototype.clear=function(){this.updateID++,this.minX=1/0,this.minY=1/0,this.maxX=-(1/0),this.maxY=-(1/0)},t.prototype.getRectangle=function(t){return this.minX>this.maxX||this.minY>this.maxY?i.Rectangle.EMPTY:(t=t||new i.Rectangle(0,0,1,1),t.x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)},t.prototype.addPoint=function(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)},t.prototype.addQuad=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY,o=t[0],s=t[1];e=on?o:n,i=s>i?s:i,o=t[2],s=t[3],e=on?o:n,i=s>i?s:i,o=t[4],s=t[5],e=on?o:n,i=s>i?s:i,o=t[6],s=t[7],e=on?o:n,i=s>i?s:i,this.minX=e,this.minY=r,this.maxX=n,this.maxY=i},t.prototype.addFrame=function(t,e,r,n,i){var o=t.worldTransform,s=o.a,a=o.b,u=o.c,h=o.d,l=o.tx,c=o.ty,d=this.minX,f=this.minY,p=this.maxX,v=this.maxY,y=s*e+u*r+l,g=a*e+h*r+c;d=yp?y:p,v=g>v?g:v,y=s*n+u*r+l,g=a*n+h*r+c,d=yp?y:p,v=g>v?g:v,y=s*e+u*i+l,g=a*e+h*i+c,d=yp?y:p,v=g>v?g:v,y=s*n+u*i+l,g=a*n+h*i+c,d=yp?y:p,v=g>v?g:v,this.minX=d,this.minY=f,this.maxX=p,this.maxY=v},t.prototype.addVertices=function(t,e,r,n){for(var i=t.worldTransform,o=i.a,s=i.b,a=i.c,u=i.d,h=i.tx,l=i.ty,c=this.minX,d=this.minY,f=this.maxX,p=this.maxY,v=r;vf?m:f,p=_>p?_:p}this.minX=c,this.minY=d,this.maxX=f,this.maxY=p},t.prototype.addBounds=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY;this.minX=t.minXn?t.maxX:n,this.maxY=t.maxY>i?t.maxY:i},t.prototype.addBoundsMask=function(t,e){var r=t.minX>e.minX?t.minX:e.minX,n=t.minY>e.minY?t.minY:e.minY,i=t.maxXu?i:u,this.maxY=o>h?o:h}},t.prototype.addBoundsArea=function(t,e){var r=t.minX>e.x?t.minX:e.x,n=t.minY>e.y?t.minY:e.y,i=t.maxXu?i:u,this.maxY=o>h?o:h}},t}();r.default=o},{"../math":69}],47:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r1)for(var r=0;rthis.children.length)throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length);return t.parent&&t.parent.removeChild(t),t.parent=this,t.transform._parentID=-1,this.children.splice(e,0,t),this._boundsID++,this.onChildrenChange(e),t.emit("added",this),t},e.prototype.swapChildren=function(t,e){if(t!==e){var r=this.getChildIndex(t),n=this.getChildIndex(e);this.children[r]=e,this.children[n]=t,this.onChildrenChange(r=this.children.length)throw new Error("The supplied index is out of bounds");var r=this.getChildIndex(t);(0,u.removeItems)(this.children,r,1),this.children.splice(e,0,t),this.onChildrenChange(e)},e.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Index ("+t+") does not exist.");return this.children[t]},e.prototype.removeChild=function(t){var e=arguments.length;if(e>1)for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=t,n="number"==typeof e?e:this.children.length,i=n-r,o=void 0;if(i>0&&i<=n){o=this.children.splice(r,i);for(var s=0;s2&&void 0!==arguments[2]&&arguments[2];return r||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)},e.prototype.toLocal=function(t,e,r,n){return e&&(t=e.toGlobal(t,r,n)),n||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,r)},e.prototype.renderWebGL=function(t){},e.prototype.renderCanvas=function(t){},e.prototype.setParent=function(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t},e.prototype.setTransform=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0,u=arguments.length>8&&void 0!==arguments[8]?arguments[8]:0;return this.position.x=t,this.position.y=e,this.scale.x=r?r:1,this.scale.y=n?n:1,this.rotation=i,this.skew.x=o,this.skew.y=s,this.pivot.x=a,this.pivot.y=u,this},e.prototype.destroy=function(){this.removeAllListeners(),this.parent&&this.parent.removeChild(this),this.transform=null,this.parent=null,this._bounds=null,this._currentBounds=null,this._mask=null,this.filterArea=null,this.interactive=!1,this.interactiveChildren=!1,this._destroyed=!0},a(e,[{key:"_tempDisplayObjectParent",get:function(){return null===this.tempDisplayObjectParent&&(this.tempDisplayObjectParent=new e),this.tempDisplayObjectParent}},{key:"x",get:function(){return this.position.x},set:function(t){this.transform.position.x=t}},{key:"y",get:function(){return this.position.y},set:function(t){this.transform.position.y=t}},{key:"worldTransform",get:function(){return this.transform.worldTransform}},{key:"localTransform",get:function(){return this.transform.localTransform}},{key:"position",get:function(){return this.transform.position},set:function(t){this.transform.position.copy(t)}},{key:"scale",get:function(){return this.transform.scale},set:function(t){this.transform.scale.copy(t)}},{key:"pivot",get:function(){return this.transform.pivot},set:function(t){this.transform.pivot.copy(t)}},{key:"skew",get:function(){return this.transform.skew},set:function(t){this.transform.skew.copy(t)}},{key:"rotation",get:function(){return this.transform.rotation},set:function(t){this.transform.rotation=t}},{key:"worldVisible",get:function(){var t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask&&(this._mask.renderable=!0),this._mask=t,this._mask&&(this._mask.renderable=!1)}},{key:"filters",get:function(){return this._filters&&this._filters.slice()},set:function(t){this._filters=t&&t.slice()}}]),e}(h.default);r.default=b,b.prototype.displayObjectUpdateTransform=b.prototype.updateTransform},{"../const":45,"../math":69,"../settings":100,"./Bounds":46,"./Transform":49,"./TransformStatic":51,eventemitter3:3}],49:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]&&arguments[0];i(this,e);var n=o(this,t.call(this));return n.fillAlpha=1,n.lineWidth=0,n.nativeLines=r,n.lineColor=0,n.graphicsData=[],n.tint=16777215,n._prevTint=16777215,n.blendMode=_.BLEND_MODES.NORMAL,n.currentPath=null,n._webGL={},n.isMask=!1,n.boundsPadding=0,n._localBounds=new x.default,n.dirty=0,n.fastRectDirty=-1,n.clearDirty=0,n.boundsDirty=-1,n.cachedSpriteDirty=!1,n._spriteRect=null,n._fastRect=!1,n}return s(e,t),e.prototype.clone=function t(){var t=new e;t.renderable=this.renderable,t.fillAlpha=this.fillAlpha,t.lineWidth=this.lineWidth,t.lineColor=this.lineColor,t.tint=this.tint,t.blendMode=this.blendMode,t.isMask=this.isMask,t.boundsPadding=this.boundsPadding,t.dirty=0,t.cachedSpriteDirty=this.cachedSpriteDirty;for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;if(this.lineWidth=t,this.lineColor=e,this.lineAlpha=r,this.currentPath)if(this.currentPath.shape.points.length){var n=new g.Polygon(this.currentPath.shape.points.slice(-2));n.closed=!1,this.drawShape(n)}else this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha;return this},e.prototype.moveTo=function(t,e){var r=new g.Polygon([t,e]);return r.closed=!1,this.drawShape(r),this},e.prototype.lineTo=function(t,e){return this.currentPath.shape.points.push(t,e),this.dirty++,this},e.prototype.quadraticCurveTo=function(t,e,r,n){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var i=20,o=this.currentPath.shape.points,s=0,a=0;0===o.length&&this.moveTo(0,0);for(var u=o[o.length-2],h=o[o.length-1],l=1;l<=i;++l){var c=l/i;s=u+(t-u)*c,a=h+(e-h)*c,o.push(s+(t+(r-t)*c-s)*c,a+(e+(n-e)*c-a)*c)}return this.dirty++,this},e.prototype.bezierCurveTo=function(t,e,r,n,i,o){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var s=this.currentPath.shape.points,a=s[s.length-2],u=s[s.length-1];return s.length-=2,(0,w.default)(a,u,t,e,r,n,i,o,s),this.dirty++,this},e.prototype.arcTo=function(t,e,r,n,i){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(t,e):this.moveTo(t,e);var o=this.currentPath.shape.points,s=o[o.length-2],a=o[o.length-1],u=a-e,h=s-t,l=n-e,c=r-t,d=Math.abs(u*c-h*l);if(d<1e-8||0===i)o[o.length-2]===t&&o[o.length-1]===e||o.push(t,e);else{var f=u*u+h*h,p=l*l+c*c,v=u*l+h*c,y=i*Math.sqrt(f)/d,g=i*Math.sqrt(p)/d,m=y*v/f,_=g*v/p,b=y*c+g*h,x=y*l+g*u,T=h*(g+m),w=u*(g+m),E=c*(y+_),S=l*(y+_),O=Math.atan2(w-x,T-b),P=Math.atan2(S-x,E-b);this.arc(b+t,x+e,i,O,P,h*l>c*u)}return this.dirty++,this},e.prototype.arc=function(t,e,r,n,i){var o=arguments.length>5&&void 0!==arguments[5]&&arguments[5];if(n===i)return this;!o&&i<=n?i+=2*Math.PI:o&&n<=i&&(n+=2*Math.PI);var s=i-n,a=40*Math.ceil(Math.abs(s)/(2*Math.PI));if(0===s)return this;var u=t+Math.cos(n)*r,h=e+Math.sin(n)*r,l=this.currentPath?this.currentPath.shape.points:null;l?l[l.length-2]===u&&l[l.length-1]===h||l.push(u,h):(this.moveTo(u,h),l=this.currentPath.shape.points);for(var c=s/(2*a),d=2*c,f=Math.cos(c),p=Math.sin(c),v=a-1,y=v%1/v,g=0;g<=v;++g){var m=g+y*g,_=c+n+d*m,b=Math.cos(_),x=-Math.sin(_);l.push((f*b+p*x)*r+t,(f*-x+p*b)*r+e)}return this.dirty++,this},e.prototype.beginFill=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this.filling=!0,this.fillColor=t,this.fillAlpha=e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},e.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},e.prototype.drawRect=function(t,e,r,n){return this.drawShape(new g.Rectangle(t,e,r,n)),this},e.prototype.drawRoundedRect=function(t,e,r,n,i){return this.drawShape(new g.RoundedRectangle(t,e,r,n,i)),this},e.prototype.drawCircle=function(t,e,r){return this.drawShape(new g.Circle(t,e,r)),this},e.prototype.drawEllipse=function(t,e,r,n){return this.drawShape(new g.Ellipse(t,e,r,n)),this},e.prototype.drawPolygon=function(t){var e=t,r=!0;if(e instanceof g.Polygon&&(r=e.closed,e=e.points),!Array.isArray(e)){e=new Array(arguments.length);for(var n=0;n0)&&(this.lineWidth=0,this.filling=!1,this.boundsDirty=-1,this.dirty++,this.clearDirty++,this.graphicsData.length=0),this.currentPath=null,this._spriteRect=null,this},e.prototype.isFastRect=function(){return 1===this.graphicsData.length&&this.graphicsData[0].shape.type===_.SHAPES.RECT&&!this.graphicsData[0].lineWidth},e.prototype._renderWebGL=function(t){this.dirty!==this.fastRectDirty&&(this.fastRectDirty=this.dirty,this._fastRect=this.isFastRect()),this._fastRect?this._renderSpriteRect(t):(t.setObjectRenderer(t.plugins.graphics),t.plugins.graphics.render(this))},e.prototype._renderSpriteRect=function(t){var e=this.graphicsData[0].shape;this._spriteRect||(this._spriteRect=new y.default(new d.default(d.default.WHITE)));var r=this._spriteRect;if(16777215===this.tint)r.tint=this.graphicsData[0].fillColor;else{var n=C,i=R;(0,m.hex2rgb)(this.graphicsData[0].fillColor,n),(0,m.hex2rgb)(this.tint,i),n[0]*=i[0],n[1]*=i[1],n[2]*=i[2],r.tint=(0,m.rgb2hex)(n)}r.alpha=this.graphicsData[0].fillAlpha,r.worldAlpha=this.worldAlpha*r.alpha,r.blendMode=this.blendMode,r._texture._frame.width=e.width,r._texture._frame.height=e.height,r.transform.worldTransform=this.transform.worldTransform,r.anchor.set(-e.x/e.width,-e.y/e.height),r._onAnchorUpdate(),r._renderWebGL(t)},e.prototype._renderCanvas=function(t){this.isMask!==!0&&t.plugins.graphics.render(this)},e.prototype._calculateBounds=function(){this.boundsDirty!==this.dirty&&(this.boundsDirty=this.dirty,this.updateLocalBounds(),this.cachedSpriteDirty=!0);var t=this._localBounds;this._bounds.addFrame(this.transform,t.minX,t.minY,t.maxX,t.maxY)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,M);for(var e=this.graphicsData,r=0;re?o+a:e,r=sn?s+u:n;else if(c===_.SHAPES.CIRC)o=i.x,s=i.y,a=i.radius+d/2,u=i.radius+d/2,t=o-ae?o+a:e,r=s-un?s+u:n;else if(c===_.SHAPES.ELIP)o=i.x,s=i.y,a=i.width+d/2,u=i.height+d/2,t=o-ae?o+a:e,r=s-un?s+u:n;else for(var f=i.points,p=0,v=0,y=0,g=0,m=0,b=0,x=0,T=0,w=0;w+2e?x+m:e,r=T-bn?T+b:n)}else t=0,e=0,r=0,n=0;var E=this.boundsPadding;this._localBounds.minX=t-E,this._localBounds.maxX=e+E,this._localBounds.minY=r-E,this._localBounds.maxY=n+E},e.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null;var e=new p.default(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,this.nativeLines,t);return this.graphicsData.push(e),e.type===_.SHAPES.POLY&&(e.shape.closed=e.shape.closed||this.filling,this.currentPath=e),this.dirty++,e},e.prototype.generateCanvasTexture=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=this.getLocalBounds(),n=l.default.create(r.width,r.height,t,e);O||(O=new S.default),this.transform.updateLocalTransform(),this.transform.localTransform.copy(P),P.invert(),P.tx-=r.x,P.ty-=r.y,O.render(this,n,!0,P);var i=d.default.fromCanvas(n.baseTexture._canvasRenderTarget.canvas,t,"graphics");return i.baseTexture.resolution=e,i.baseTexture.update(),i},e.prototype.closePath=function(){var t=this.currentPath;return t&&t.shape&&t.shape.close(),this},e.prototype.addHole=function(){var t=this.graphicsData.pop();return this.currentPath=this.graphicsData[this.graphicsData.length-1],this.currentPath.addHole(t.shape),this.currentPath=null,this},e.prototype.destroy=function(e){t.prototype.destroy.call(this,e);for(var r=0;rC?C:M,r.beginPath(),r.moveTo(E,S+M),r.lineTo(E,S+P-M),r.quadraticCurveTo(E,S+P,E+M,S+P),r.lineTo(E+O-M,S+P),r.quadraticCurveTo(E+O,S+P,E+O,S+P-M),r.lineTo(E+O,S+M),r.quadraticCurveTo(E+O,S,E+O-M,S),r.lineTo(E+M,S),r.quadraticCurveTo(E,S,E,S+M),r.closePath(),(u.fillColor||0===u.fillColor)&&(r.globalAlpha=u.fillAlpha*n,r.fillStyle="#"+("00000"+(0|l).toString(16)).substr(-6),r.fill()),u.lineWidth&&(r.globalAlpha=u.lineAlpha*n,r.strokeStyle="#"+("00000"+(0|c).toString(16)).substr(-6),r.stroke())}}},t.prototype.updateGraphicsTint=function(t){t._prevTint=t.tint;for(var e=(t.tint>>16&255)/255,r=(t.tint>>8&255)/255,n=(255&t.tint)/255,i=0;i>16&255)/255*e*255<<16)+((s>>8&255)/255*r*255<<8)+(255&s)/255*n*255,o._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*r*255<<8)+(255&a)/255*n*255}},t.prototype.renderPolygon=function(t,e,r){r.moveTo(t[0],t[1]);for(var n=1;n8&&void 0!==arguments[8]?arguments[8]:[],h=20,l=0,c=0,d=0,f=0,p=0;u.push(t,e);for(var v=1,y=0;v<=h;++v)y=v/h,l=1-y,c=l*l,d=c*l,f=y*y,p=f*y,u.push(d*t+3*c*y*r+3*l*f*i+p*s,d*e+3*c*y*n+3*l*f*o+p*a);return u}r.__esModule=!0,r.default=n},{}],56:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../utils"),u=t("../../const"),h=t("../../renderers/webgl/utils/ObjectRenderer"),l=n(h),c=t("../../renderers/webgl/WebGLRenderer"),d=n(c),f=t("./WebGLGraphicsData"),p=n(f),v=t("./shaders/PrimitiveShader"),y=n(v),g=t("./utils/buildPoly"),m=n(g),_=t("./utils/buildRectangle"),b=n(_),x=t("./utils/buildRoundedRectangle"),T=n(x),w=t("./utils/buildCircle"),E=n(w),S=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.graphicsDataPool=[],n.primitiveShader=null,n.gl=r.gl,n.CONTEXT_UID=0,n}return s(e,t),e.prototype.onContextChange=function(){this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.primitiveShader=new y.default(this.gl)},e.prototype.destroy=function(){l.default.prototype.destroy.call(this);for(var t=0;t32e4)&&(n=this.graphicsDataPool.pop()||new p.default(this.renderer.gl,this.primitiveShader,this.renderer.state.attribsState),n.nativeLines=r,n.reset(e),t.data.push(n)),n.dirty=!0,n},e}(l.default);r.default=S,d.default.registerPlugin("graphics",S)},{"../../const":45,"../../renderers/webgl/WebGLRenderer":83,"../../renderers/webgl/utils/ObjectRenderer":93,"../../utils":123,"./WebGLGraphicsData":57,"./shaders/PrimitiveShader":58,"./utils/buildCircle":59,"./utils/buildPoly":61,"./utils/buildRectangle":62,"./utils/buildRoundedRectangle":63}],57:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("pixi-gl-core"),s=n(o),a=function(){function t(e,r,n){i(this,t),this.gl=e,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=s.default.GLBuffer.createVertexBuffer(e),this.indexBuffer=s.default.GLBuffer.createIndexBuffer(e),this.dirty=!0,this.nativeLines=!1,this.glPoints=null,this.glIndices=null,this.shader=r,this.vao=new s.default.VertexArrayObject(e,n).addIndex(this.indexBuffer).addAttribute(this.buffer,r.attributes.aVertexPosition,e.FLOAT,!1,24,0).addAttribute(this.buffer,r.attributes.aColor,e.FLOAT,!1,24,8)}return t.prototype.reset=function(){this.points.length=0,this.indices.length=0},t.prototype.upload=function(){this.glPoints=new Float32Array(this.points),this.buffer.upload(this.glPoints),this.glIndices=new Uint16Array(this.indices),this.indexBuffer.upload(this.glIndices),this.dirty=!1},t.prototype.destroy=function(){this.color=null,this.points=null,this.indices=null,this.vao.destroy(),this.buffer.destroy(),this.indexBuffer.destroy(),this.gl=null,this.buffer=null,this.indexBuffer=null,this.glPoints=null,this.glIndices=null},t}();r.default=a},{"pixi-gl-core":12}],58:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../../Shader"),u=n(a),h=function(t){function e(r){return i(this,e),o(this,t.call(this,r,["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","uniform float alpha;","uniform vec3 tint;","varying vec4 vColor;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"].join("\n"),["varying vec4 vColor;","void main(void){"," gl_FragColor = vColor;","}"].join("\n")))}return s(e,t),e}(u.default);r.default=h},{"../../../Shader":43}],59:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e,r){var n=t.shape,i=n.x,o=n.y,h=void 0,l=void 0;if(t.type===a.SHAPES.CIRC?(h=n.radius,l=n.radius):(h=n.width,l=n.height),0!==h&&0!==l){var c=Math.floor(30*Math.sqrt(n.radius))||Math.floor(15*Math.sqrt(n.width+n.height)),d=2*Math.PI/c;if(t.fill){var f=(0,u.hex2rgb)(t.fillColor),p=t.fillAlpha,v=f[0]*p,y=f[1]*p,g=f[2]*p,m=e.points,_=e.indices,b=m.length/6;_.push(b);for(var x=0;x196*p*p?(R=O-M,A=P-C,I=Math.sqrt(R*R+A*A),R/=I,A/=I,R*=p,A*=p,h.push(T-R,w-A),h.push(g,m,_,y),h.push(T+R,w+A),h.push(g,m,_,y),h.push(T-R,w-A),h.push(g,m,_,y),d++):(h.push(X,G),h.push(g,m,_,y),h.push(T-(X-T),w-(G-w)),h.push(g,m,_,y))}}b=r[2*(c-2)],x=r[2*(c-2)+1],T=r[2*(c-1)],w=r[2*(c-1)+1],O=-(x-w),P=b-T,I=Math.sqrt(O*O+P*P),O/=I,P/=I,O*=p,P*=p,h.push(T-O,w-P),h.push(g,m,_,y),h.push(T+O,w+P),h.push(g,m,_,y),l.push(f);for(var H=0;H=6){for(var i=[],o=t.holes,u=0;u0&&(0,s.default)(t,e,r)}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils"),u=t("earcut"),h=n(u)},{"../../../utils":123,"./buildLine":60,earcut:2}],62:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e,r){var n=t.shape,i=n.x,o=n.y,u=n.width,h=n.height;if(t.fill){var l=(0,a.hex2rgb)(t.fillColor),c=t.fillAlpha,d=l[0]*c,f=l[1]*c,p=l[2]*c,v=e.points,y=e.indices,g=v.length/6;v.push(i,o),v.push(d,f,p,c),v.push(i+u,o),v.push(d,f,p,c),v.push(i,o+h),v.push(d,f,p,c),v.push(i+u,o+h),v.push(d,f,p,c),y.push(g,g,g+1,g+2,g+3,g+3)}if(t.lineWidth){var m=t.points;t.points=[i,o,i+u,o,i+u,o+h,i,o+h,i,o],(0,s.default)(t,e,r),t.points=m}}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils")},{"../../../utils":123,"./buildLine":60}],63:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e,r){var n=t.shape,i=n.x,o=n.y,a=n.width,h=n.height,d=n.radius,f=[];if(f.push(i,o+d),s(i,o+h-d,i,o+h,i+d,o+h,f),s(i+a-d,o+h,i+a,o+h,i+a,o+h-d,f),s(i+a,o+d,i+a,o,i+a-d,o,f),s(i+d,o,i,o,i,o+d+1e-10,f),t.fill){for(var p=(0,c.hex2rgb)(t.fillColor),v=t.fillAlpha,y=p[0]*v,g=p[1]*v,m=p[2]*v,_=e.points,b=e.indices,x=_.length/6,T=(0,u.default)(f,null,2),w=0,E=T.length;w6&&void 0!==arguments[6]?arguments[6]:[],u=20,h=a,l=0,c=0,d=0,f=0,p=0,v=0,y=0,g=0;y<=u;++y)g=y/u,l=o(t,r,g),c=o(e,n,g),d=o(r,i,g),f=o(n,s,g),p=o(l,d,g),v=o(c,f,g),h.push(p,v);return h}r.__esModule=!0,r.default=i;var a=t("earcut"),u=n(a),h=t("./buildLine"),l=n(h),c=t("../../../utils")},{"../../../utils":123,"./buildLine":60,earcut:2}],64:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.autoDetectRenderer=r.Application=r.Filter=r.SpriteMaskFilter=r.Quad=r.RenderTarget=r.ObjectRenderer=r.WebGLManager=r.Shader=r.CanvasRenderTarget=r.TextureUvs=r.VideoBaseTexture=r.BaseRenderTexture=r.RenderTexture=r.BaseTexture=r.Texture=r.Spritesheet=r.CanvasGraphicsRenderer=r.GraphicsRenderer=r.GraphicsData=r.Graphics=r.TextMetrics=r.TextStyle=r.Text=r.SpriteRenderer=r.CanvasTinter=r.CanvasSpriteRenderer=r.Sprite=r.TransformBase=r.TransformStatic=r.Transform=r.Container=r.DisplayObject=r.Bounds=r.glCore=r.WebGLRenderer=r.CanvasRenderer=r.ticker=r.utils=r.settings=void 0;var o=t("./const");Object.keys(o).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return o[t]}})});var s=t("./math");Object.keys(s).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return s[t]}})});var a=t("pixi-gl-core");Object.defineProperty(r,"glCore",{enumerable:!0,get:function(){return i(a).default}});var u=t("./display/Bounds");Object.defineProperty(r,"Bounds",{enumerable:!0,get:function(){return i(u).default}});var h=t("./display/DisplayObject");Object.defineProperty(r,"DisplayObject",{enumerable:!0,get:function(){return i(h).default}});var l=t("./display/Container");Object.defineProperty(r,"Container",{enumerable:!0,get:function(){return i(l).default}});var c=t("./display/Transform");Object.defineProperty(r,"Transform",{enumerable:!0,get:function(){return i(c).default}});var d=t("./display/TransformStatic");Object.defineProperty(r,"TransformStatic",{enumerable:!0,get:function(){return i(d).default}});var f=t("./display/TransformBase"); +Object.defineProperty(r,"TransformBase",{enumerable:!0,get:function(){return i(f).default}});var p=t("./sprites/Sprite");Object.defineProperty(r,"Sprite",{enumerable:!0,get:function(){return i(p).default}});var v=t("./sprites/canvas/CanvasSpriteRenderer");Object.defineProperty(r,"CanvasSpriteRenderer",{enumerable:!0,get:function(){return i(v).default}});var y=t("./sprites/canvas/CanvasTinter");Object.defineProperty(r,"CanvasTinter",{enumerable:!0,get:function(){return i(y).default}});var g=t("./sprites/webgl/SpriteRenderer");Object.defineProperty(r,"SpriteRenderer",{enumerable:!0,get:function(){return i(g).default}});var m=t("./text/Text");Object.defineProperty(r,"Text",{enumerable:!0,get:function(){return i(m).default}});var _=t("./text/TextStyle");Object.defineProperty(r,"TextStyle",{enumerable:!0,get:function(){return i(_).default}});var b=t("./text/TextMetrics");Object.defineProperty(r,"TextMetrics",{enumerable:!0,get:function(){return i(b).default}});var x=t("./graphics/Graphics");Object.defineProperty(r,"Graphics",{enumerable:!0,get:function(){return i(x).default}});var T=t("./graphics/GraphicsData");Object.defineProperty(r,"GraphicsData",{enumerable:!0,get:function(){return i(T).default}});var w=t("./graphics/webgl/GraphicsRenderer");Object.defineProperty(r,"GraphicsRenderer",{enumerable:!0,get:function(){return i(w).default}});var E=t("./graphics/canvas/CanvasGraphicsRenderer");Object.defineProperty(r,"CanvasGraphicsRenderer",{enumerable:!0,get:function(){return i(E).default}});var S=t("./textures/Spritesheet");Object.defineProperty(r,"Spritesheet",{enumerable:!0,get:function(){return i(S).default}});var O=t("./textures/Texture");Object.defineProperty(r,"Texture",{enumerable:!0,get:function(){return i(O).default}});var P=t("./textures/BaseTexture");Object.defineProperty(r,"BaseTexture",{enumerable:!0,get:function(){return i(P).default}});var M=t("./textures/RenderTexture");Object.defineProperty(r,"RenderTexture",{enumerable:!0,get:function(){return i(M).default}});var C=t("./textures/BaseRenderTexture");Object.defineProperty(r,"BaseRenderTexture",{enumerable:!0,get:function(){return i(C).default}});var R=t("./textures/VideoBaseTexture");Object.defineProperty(r,"VideoBaseTexture",{enumerable:!0,get:function(){return i(R).default}});var A=t("./textures/TextureUvs");Object.defineProperty(r,"TextureUvs",{enumerable:!0,get:function(){return i(A).default}});var I=t("./renderers/canvas/utils/CanvasRenderTarget");Object.defineProperty(r,"CanvasRenderTarget",{enumerable:!0,get:function(){return i(I).default}});var D=t("./Shader");Object.defineProperty(r,"Shader",{enumerable:!0,get:function(){return i(D).default}});var L=t("./renderers/webgl/managers/WebGLManager");Object.defineProperty(r,"WebGLManager",{enumerable:!0,get:function(){return i(L).default}});var N=t("./renderers/webgl/utils/ObjectRenderer");Object.defineProperty(r,"ObjectRenderer",{enumerable:!0,get:function(){return i(N).default}});var F=t("./renderers/webgl/utils/RenderTarget");Object.defineProperty(r,"RenderTarget",{enumerable:!0,get:function(){return i(F).default}});var B=t("./renderers/webgl/utils/Quad");Object.defineProperty(r,"Quad",{enumerable:!0,get:function(){return i(B).default}});var k=t("./renderers/webgl/filters/spriteMask/SpriteMaskFilter");Object.defineProperty(r,"SpriteMaskFilter",{enumerable:!0,get:function(){return i(k).default}});var j=t("./renderers/webgl/filters/Filter");Object.defineProperty(r,"Filter",{enumerable:!0,get:function(){return i(j).default}});var U=t("./Application");Object.defineProperty(r,"Application",{enumerable:!0,get:function(){return i(U).default}});var X=t("./autoDetectRenderer");Object.defineProperty(r,"autoDetectRenderer",{enumerable:!0,get:function(){return X.autoDetectRenderer}});var G=t("./utils"),W=n(G),H=t("./ticker"),Y=n(H),V=t("./settings"),z=i(V),q=t("./renderers/canvas/CanvasRenderer"),K=i(q),Z=t("./renderers/webgl/WebGLRenderer"),J=i(Z);r.settings=z.default,r.utils=W,r.ticker=Y,r.CanvasRenderer=K.default,r.WebGLRenderer=J.default},{"./Application":42,"./Shader":43,"./autoDetectRenderer":44,"./const":45,"./display/Bounds":46,"./display/Container":47,"./display/DisplayObject":48,"./display/Transform":49,"./display/TransformBase":50,"./display/TransformStatic":51,"./graphics/Graphics":52,"./graphics/GraphicsData":53,"./graphics/canvas/CanvasGraphicsRenderer":54,"./graphics/webgl/GraphicsRenderer":56,"./math":69,"./renderers/canvas/CanvasRenderer":76,"./renderers/canvas/utils/CanvasRenderTarget":78,"./renderers/webgl/WebGLRenderer":83,"./renderers/webgl/filters/Filter":85,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":88,"./renderers/webgl/managers/WebGLManager":92,"./renderers/webgl/utils/ObjectRenderer":93,"./renderers/webgl/utils/Quad":94,"./renderers/webgl/utils/RenderTarget":95,"./settings":100,"./sprites/Sprite":101,"./sprites/canvas/CanvasSpriteRenderer":102,"./sprites/canvas/CanvasTinter":103,"./sprites/webgl/SpriteRenderer":105,"./text/Text":107,"./text/TextMetrics":108,"./text/TextStyle":109,"./textures/BaseRenderTexture":110,"./textures/BaseTexture":111,"./textures/RenderTexture":112,"./textures/Spritesheet":113,"./textures/Texture":114,"./textures/TextureUvs":115,"./textures/VideoBaseTexture":116,"./ticker":119,"./utils":123,"pixi-gl-core":12}],65:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){return t<0?-1:t>0?1:0}function o(){for(var t=0;t<16;t++){var e=[];f.push(e);for(var r=0;r<16;r++)for(var n=i(u[t]*u[r]+l[t]*h[r]),o=i(h[t]*u[r]+c[t]*h[r]),s=i(u[t]*l[r]+l[t]*c[r]),p=i(h[t]*l[r]+c[t]*c[r]),v=0;v<16;v++)if(u[v]===n&&h[v]===o&&l[v]===s&&c[v]===p){e.push(v);break}}for(var y=0;y<16;y++){var g=new a.default;g.set(u[y],h[y],l[y],c[y],0,0),d.push(g)}}r.__esModule=!0;var s=t("./Matrix"),a=n(s),u=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],h=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],l=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],c=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],d=[],f=[];o();var p={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MIRROR_HORIZONTAL:12,uX:function(t){return u[t]},uY:function(t){return h[t]},vX:function(t){return l[t]},vY:function(t){return c[t]},inv:function(t){return 8&t?15&t:7&-t},add:function(t,e){return f[t][e]},sub:function(t,e){return f[t][p.inv(e)]},rotate180:function(t){return 4^t},isSwapWidthHeight:function(t){return 2===(3&t)},byDirection:function(t,e){return 2*Math.abs(t)<=Math.abs(e)?e>=0?p.S:p.N:2*Math.abs(e)<=Math.abs(t)?t>0?p.E:p.W:e>0?t>0?p.SE:p.SW:t>0?p.NE:p.NW},matrixAppendRotationInv:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=d[p.inv(e)];i.tx=r,i.ty=n,t.append(i)}};r.default=p},{"./Matrix":66}],66:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:1,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;i(this,t),this.a=e,this.b=r,this.c=n,this.d=o,this.tx=s,this.ty=a,this.array=null}return t.prototype.fromArray=function(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]},t.prototype.set=function(t,e,r,n,i,o){return this.a=t,this.b=e,this.c=r,this.d=n,this.tx=i,this.ty=o,this},t.prototype.toArray=function(t,e){this.array||(this.array=new Float32Array(9));var r=e||this.array;return t?(r[0]=this.a,r[1]=this.b,r[2]=0,r[3]=this.c,r[4]=this.d,r[5]=0,r[6]=this.tx,r[7]=this.ty,r[8]=1):(r[0]=this.a,r[1]=this.c,r[2]=this.tx,r[3]=this.b,r[4]=this.d,r[5]=this.ty,r[6]=0,r[7]=0,r[8]=1),r},t.prototype.apply=function(t,e){e=e||new a.default;var r=t.x,n=t.y;return e.x=this.a*r+this.c*n+this.tx,e.y=this.b*r+this.d*n+this.ty,e},t.prototype.applyInverse=function(t,e){e=e||new a.default;var r=1/(this.a*this.d+this.c*-this.b),n=t.x,i=t.y;return e.x=this.d*r*n+-this.c*r*i+(this.ty*this.c-this.tx*this.d)*r,e.y=this.a*r*i+-this.b*r*n+(-this.ty*this.a+this.tx*this.b)*r,e},t.prototype.translate=function(t,e){return this.tx+=t,this.ty+=e,this},t.prototype.scale=function(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this},t.prototype.rotate=function(t){var e=Math.cos(t),r=Math.sin(t),n=this.a,i=this.c,o=this.tx;return this.a=n*e-this.b*r,this.b=n*r+this.b*e,this.c=i*e-this.d*r,this.d=i*r+this.d*e,this.tx=o*e-this.ty*r,this.ty=o*r+this.ty*e,this},t.prototype.append=function(t){var e=this.a,r=this.b,n=this.c,i=this.d;return this.a=t.a*e+t.b*n,this.b=t.a*r+t.b*i,this.c=t.c*e+t.d*n,this.d=t.c*r+t.d*i,this.tx=t.tx*e+t.ty*n+this.tx,this.ty=t.tx*r+t.ty*i+this.ty,this},t.prototype.setTransform=function(t,e,r,n,i,o,s,a,u){var h=Math.sin(s),l=Math.cos(s),c=Math.cos(u),d=Math.sin(u),f=-Math.sin(a),p=Math.cos(a),v=l*i,y=h*i,g=-h*o,m=l*o;return this.a=c*v+d*g,this.b=c*y+d*m,this.c=f*v+p*g,this.d=f*y+p*m,this.tx=t+(r*v+n*g),this.ty=e+(r*y+n*m),this},t.prototype.prepend=function(t){var e=this.tx;if(1!==t.a||0!==t.b||0!==t.c||1!==t.d){var r=this.a,n=this.c;this.a=r*t.a+this.b*t.c,this.b=r*t.b+this.b*t.d,this.c=n*t.a+this.d*t.c,this.d=n*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this},t.prototype.decompose=function(t){var e=this.a,r=this.b,n=this.c,i=this.d,o=-Math.atan2(-n,i),s=Math.atan2(r,e),a=Math.abs(o+s);return a<1e-5?(t.rotation=s,e<0&&i>=0&&(t.rotation+=t.rotation<=0?Math.PI:-Math.PI),t.skew.x=t.skew.y=0):(t.skew.x=o,t.skew.y=s),t.scale.x=Math.sqrt(e*e+r*r),t.scale.y=Math.sqrt(n*n+i*i),t.position.x=this.tx,t.position.y=this.ty,t},t.prototype.invert=function(){var t=this.a,e=this.b,r=this.c,n=this.d,i=this.tx,o=t*n-e*r;return this.a=n/o,this.b=-e/o,this.c=-r/o,this.d=t/o,this.tx=(r*this.ty-n*i)/o,this.ty=-(t*this.ty-e*i)/o,this},t.prototype.identity=function(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this},t.prototype.clone=function(){var e=new t;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e},t.prototype.copy=function(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t},o(t,null,[{key:"IDENTITY",get:function(){return new t}},{key:"TEMP_MATRIX",get:function(){return new t}}]),t}();r.default=u},{"./Point":68}],67:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this._x=i,this._y=o,this.cb=e,this.scope=r}return t.prototype.set=function(t,e){var r=t||0,n=e||(0!==e?r:0);this._x===r&&this._y===n||(this._x=r,this._y=n,this.cb.call(this.scope))},t.prototype.copy=function(t){this._x===t.x&&this._y===t.y||(this._x=t.x,this._y=t.y,this.cb.call(this.scope))},i(t,[{key:"x",get:function(){return this._x},set:function(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}},{key:"y",get:function(){return this._y},set:function(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}]),t}();r.default=o},{}],68:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;n(this,t),this.x=e,this.y=r}return t.prototype.clone=function(){return new t(this.x,this.y)},t.prototype.copy=function(t){this.set(t.x,t.y)},t.prototype.equals=function(t){return t.x===this.x&&t.y===this.y},t.prototype.set=function(t,e){this.x=t||0,this.y=e||(0!==e?this.x:0)},t}();r.default=i},{}],69:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./Point");Object.defineProperty(r,"Point",{enumerable:!0,get:function(){return n(i).default}});var o=t("./ObservablePoint");Object.defineProperty(r,"ObservablePoint",{enumerable:!0,get:function(){return n(o).default}});var s=t("./Matrix");Object.defineProperty(r,"Matrix",{enumerable:!0,get:function(){return n(s).default}});var a=t("./GroupD8");Object.defineProperty(r,"GroupD8",{enumerable:!0,get:function(){return n(a).default}});var u=t("./shapes/Circle");Object.defineProperty(r,"Circle",{enumerable:!0,get:function(){return n(u).default}});var h=t("./shapes/Ellipse");Object.defineProperty(r,"Ellipse",{enumerable:!0,get:function(){return n(h).default}});var l=t("./shapes/Polygon");Object.defineProperty(r,"Polygon",{enumerable:!0,get:function(){return n(l).default}});var c=t("./shapes/Rectangle");Object.defineProperty(r,"Rectangle",{enumerable:!0,get:function(){return n(c).default}});var d=t("./shapes/RoundedRectangle");Object.defineProperty(r,"RoundedRectangle",{enumerable:!0,get:function(){return n(d).default}})},{"./GroupD8":65,"./Matrix":66,"./ObservablePoint":67,"./Point":68,"./shapes/Circle":70,"./shapes/Ellipse":71,"./shapes/Polygon":72,"./shapes/Rectangle":73,"./shapes/RoundedRectangle":74}],70:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./Rectangle"),s=n(o),a=t("../../const"),u=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;i(this,t),this.x=e,this.y=r,this.radius=n,this.type=a.SHAPES.CIRC}return t.prototype.clone=function(){return new t(this.x,this.y,this.radius)},t.prototype.contains=function(t,e){if(this.radius<=0)return!1;var r=this.radius*this.radius,n=this.x-t,i=this.y-e;return n*=n,i*=i,n+i<=r},t.prototype.getBounds=function(){return new s.default(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)},t}();r.default=u},{"../../const":45,"./Rectangle":73}],71:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("./Rectangle"),s=n(o),a=t("../../const"),u=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;i(this,t),this.x=e,this.y=r,this.width=n,this.height=o,this.type=a.SHAPES.ELIP}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;var r=(t-this.x)/this.width,n=(e-this.y)/this.height;return r*=r,n*=n,r+n<=1},t.prototype.getBounds=function(){return new s.default(this.x-this.width,this.y-this.height,this.width,this.height)},t}();r.default=u},{"../../const":45,"./Rectangle":73}],72:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../Point"),s=n(o),a=t("../../const"),u=function(){function t(){for(var e=arguments.length,r=Array(e),n=0;ne!=h>e&&t<(u-s)*((e-a)/(h-a))+s;l&&(r=!r)}return r},t}();r.default=u},{"../../const":45,"../Point":68}],73:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this.x=e,this.y=r,this.width=i,this.height=s,this.type=o.SHAPES.RECT}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this},t.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t=this.y&&et.x+t.width&&(this.width=t.width-this.x,this.width<0&&(this.width=0)),this.y+this.height>t.y+t.height&&(this.height=t.height-this.y,this.height<0&&(this.height=0))},t.prototype.enlarge=function(t){var e=Math.min(this.x,t.x),r=Math.max(this.x+this.width,t.x+t.width),n=Math.min(this.y,t.y),i=Math.max(this.y+this.height,t.y+t.height);this.x=e,this.width=r-e,this.y=n,this.height=i-n},i(t,[{key:"left",get:function(){return this.x}},{key:"right",get:function(){return this.x+this.width}},{key:"top",get:function(){return this.y}},{key:"bottom",get:function(){return this.y+this.height}}],[{key:"EMPTY",get:function(){return new t(0,0,0,0)}}]),t}();r.default=s},{"../../const":45}],74:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:20;n(this,t),this.x=e,this.y=r,this.width=o,this.height=s,this.radius=a,this.type=i.SHAPES.RREC}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height,this.radius)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){if(e>=this.y+this.radius&&e<=this.y+this.height-this.radius||t>=this.x+this.radius&&t<=this.x+this.width-this.radius)return!0;var r=t-(this.x+this.radius),n=e-(this.y+this.radius),i=this.radius*this.radius;if(r*r+n*n<=i)return!0;if(r=t-(this.x+this.width-this.radius),r*r+n*n<=i)return!0;if(n=e-(this.y+this.height-this.radius),r*r+n*n<=i)return!0;if(r=t-(this.x+this.radius),r*r+n*n<=i)return!0}return!1},t}();r.default=o},{"../../const":45}],75:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rS?S:E,e.moveTo(b,x+E),e.lineTo(b,x+w-E),e.quadraticCurveTo(b,x+w,b+E,x+w),e.lineTo(b+T-E,x+w),e.quadraticCurveTo(b+T,x+w,b+T,x+w-E),e.lineTo(b+T,x+E),e.quadraticCurveTo(b+T,x,b+T-E,x),e.lineTo(b+E,x),e.quadraticCurveTo(b,x,b,x+E),e.closePath()}}}},t.prototype.popMask=function(t){t.context.restore()},t.prototype.destroy=function(){},t}();r.default=o},{"../../../const":45}],78:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:[];return(0,a.default)()?(t[o.BLEND_MODES.NORMAL]="source-over",t[o.BLEND_MODES.ADD]="lighter",t[o.BLEND_MODES.MULTIPLY]="multiply",t[o.BLEND_MODES.SCREEN]="screen",t[o.BLEND_MODES.OVERLAY]="overlay",t[o.BLEND_MODES.DARKEN]="darken",t[o.BLEND_MODES.LIGHTEN]="lighten",t[o.BLEND_MODES.COLOR_DODGE]="color-dodge",t[o.BLEND_MODES.COLOR_BURN]="color-burn",t[o.BLEND_MODES.HARD_LIGHT]="hard-light",t[o.BLEND_MODES.SOFT_LIGHT]="soft-light",t[o.BLEND_MODES.DIFFERENCE]="difference",t[o.BLEND_MODES.EXCLUSION]="exclusion",t[o.BLEND_MODES.HUE]="hue",t[o.BLEND_MODES.SATURATION]="saturate",t[o.BLEND_MODES.COLOR]="color",t[o.BLEND_MODES.LUMINOSITY]="luminosity"):(t[o.BLEND_MODES.NORMAL]="source-over",t[o.BLEND_MODES.ADD]="lighter",t[o.BLEND_MODES.MULTIPLY]="source-over",t[o.BLEND_MODES.SCREEN]="source-over",t[o.BLEND_MODES.OVERLAY]="source-over",t[o.BLEND_MODES.DARKEN]="source-over",t[o.BLEND_MODES.LIGHTEN]="source-over",t[o.BLEND_MODES.COLOR_DODGE]="source-over",t[o.BLEND_MODES.COLOR_BURN]="source-over",t[o.BLEND_MODES.HARD_LIGHT]="source-over",t[o.BLEND_MODES.SOFT_LIGHT]="source-over", +t[o.BLEND_MODES.DIFFERENCE]="source-over",t[o.BLEND_MODES.EXCLUSION]="source-over",t[o.BLEND_MODES.HUE]="source-over",t[o.BLEND_MODES.SATURATION]="source-over",t[o.BLEND_MODES.COLOR]="source-over",t[o.BLEND_MODES.LUMINOSITY]="source-over"),t[o.BLEND_MODES.NORMAL_NPM]=t[o.BLEND_MODES.NORMAL],t[o.BLEND_MODES.ADD_NPM]=t[o.BLEND_MODES.ADD],t[o.BLEND_MODES.SCREEN_NPM]=t[o.BLEND_MODES.SCREEN],t}r.__esModule=!0,r.default=i;var o=t("../../../const"),s=t("./canUseNewCanvasBlendModes"),a=n(s)},{"../../../const":45,"./canUseNewCanvasBlendModes":79}],81:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../const"),s=t("../../settings"),a=n(s),u=function(){function t(e){i(this,t),this.renderer=e,this.count=0,this.checkCount=0,this.maxIdle=a.default.GC_MAX_IDLE,this.checkCountMax=a.default.GC_MAX_CHECK_COUNT,this.mode=a.default.GC_MODE}return t.prototype.update=function(){this.count++,this.mode!==o.GC_MODES.MANUAL&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run()))},t.prototype.run=function(){for(var t=this.renderer.textureManager,e=t._managedTextures,r=!1,n=0;nthis.maxIdle&&(t.destroyTexture(i,!0),e[n]=null,r=!0)}if(r){for(var o=0,s=0;s=0;r--)this.unload(t.children[r])},t}();r.default=u},{"../../const":45,"../../settings":100}],82:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("pixi-gl-core"),s=t("../../const"),a=t("./utils/RenderTarget"),u=n(a),h=t("../../utils"),l=function(){function t(e){i(this,t),this.renderer=e,this.gl=e.gl,this._managedTextures=[]}return t.prototype.bindTexture=function(){},t.prototype.getTexture=function(){},t.prototype.updateTexture=function(t,e){var r=this.gl,n=!!t._glRenderTargets;if(!t.hasLoaded)return null;var i=this.renderer.boundTextures;if(void 0===e){e=0;for(var a=0;a 0.5)"," {"," color = vec4(1.0, 0.0, 0.0, 1.0);"," }"," else"," {"," color = vec4(0.0, 1.0, 0.0, 1.0);"," }"," gl_FragColor = mix(sample, masky, 0.5);"," gl_FragColor *= sample.a;","}"].join("\n")}}]),t}();r.default=f},{"../../../const":45,"../../../settings":100,"../../../utils":123,"./extractUniformsFromSrc":86}],86:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e,r){var n=o(t,r),i=o(e,r);return Object.assign(n,i)}function o(t){for(var e=new RegExp("^(projectionMatrix|uSampler|filterArea|filterClamp)$"),r={},n=void 0,i=t.replace(/\s+/g," ").split(/\s*;\s*/),o=0;o-1){var a=s.split(" "),h=a[1],l=a[2],c=1;l.indexOf("[")>-1&&(n=l.split(/\[|]/),l=n[0],c*=Number(n[1])),l.match(e)||(r[l]={value:u(h,c),name:l,type:h})}}return r}r.__esModule=!0,r.default=i;var s=t("pixi-gl-core"),a=n(s),u=a.default.shader.defaultValue},{"pixi-gl-core":12}],87:[function(t,e,r){"use strict";function n(t,e,r){var n=t.identity();return n.translate(e.x/r.width,e.y/r.height),n.scale(r.width,r.height),n}function i(t,e,r){var n=t.identity();n.translate(e.x/r.width,e.y/r.height);var i=r.width/e.width,o=r.height/e.height;return n.scale(i,o),n}function o(t,e,r,n){var i=n.worldTransform.copy(s.Matrix.TEMP_MATRIX),o=n._texture.baseTexture,a=t.identity(),u=r.height/r.width;a.translate(e.x/r.width,e.y/r.height),a.scale(1,u);var h=r.width/o.width,l=r.height/o.height;return i.tx/=o.width*h,i.ty/=o.width*h,i.invert(),a.prepend(i),a.scale(1,1/u),a.scale(h,l),a.translate(n.anchor.x,n.anchor.y),a}r.__esModule=!0,r.calculateScreenSpaceMatrix=n,r.calculateNormalizedScreenSpaceMatrix=i,r.calculateSpriteMatrix=o;var s=t("../../../math")},{"../../../math":69}],88:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../Filter"),u=n(a),h=t("../../../../math"),l=(t("path"),function(t){function e(r){i(this,e);var n=new h.Matrix,s=o(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n","varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n"));return r.renderable=!1,s.maskSprite=r,s.maskMatrix=n,s}return s(e,t),e.prototype.apply=function(t,e,r){var n=this.maskSprite;this.uniforms.mask=n._texture,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,n),this.uniforms.alpha=n.worldAlpha,t.applyFilter(this,e,r)},e}(u.default));r.default=l},{"../../../../math":69,"../Filter":85,path:22}],89:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var u=t("./WebGLManager"),h=i(u),l=t("../utils/RenderTarget"),c=i(l),d=t("../utils/Quad"),f=i(d),p=t("../../../math"),v=t("../../../Shader"),y=i(v),g=t("../filters/filterTransforms"),m=n(g),_=t("bit-twiddle"),b=i(_),x=function t(){a(this,t),this.renderTarget=null,this.sourceFrame=new p.Rectangle,this.destinationFrame=new p.Rectangle,this.filters=[],this.target=null,this.resolution=1},T=function(t){function e(r){a(this,e);var n=o(this,t.call(this,r));return n.gl=n.renderer.gl,n.quad=new f.default(n.gl,r.state.attribState),n.shaderCache={},n.pool={},n.filterData=null,n}return s(e,t),e.prototype.pushFilter=function(t,e){var r=this.renderer,n=this.filterData;if(!n){n=this.renderer._activeRenderTarget.filterStack;var i=new x;i.sourceFrame=i.destinationFrame=this.renderer._activeRenderTarget.size,i.renderTarget=r._activeRenderTarget,this.renderer._activeRenderTarget.filterData=n={index:0,stack:[i]},this.filterData=n}var o=n.stack[++n.index];o||(o=n.stack[n.index]=new x);var s=e[0].resolution,a=0|e[0].padding,u=t.filterArea||t.getBounds(!0),h=o.sourceFrame,l=o.destinationFrame;h.x=(u.x*s|0)/s,h.y=(u.y*s|0)/s,h.width=(u.width*s|0)/s,h.height=(u.height*s|0)/s,n.stack[0].renderTarget.transform||e[0].autoFit&&h.fit(n.stack[0].destinationFrame),h.pad(a),l.width=h.width,l.height=h.height;var c=this.getPotRenderTarget(r.gl,h.width,h.height,s);o.target=t,o.filters=e,o.resolution=s,o.renderTarget=c,c.setFrame(l,h),r.bindRenderTarget(c),c.clear()},e.prototype.popFilter=function(){var t=this.filterData,e=t.stack[t.index-1],r=t.stack[t.index];this.quad.map(r.renderTarget.size,r.sourceFrame).upload();var n=r.filters;if(1===n.length)n[0].apply(this,r.renderTarget,e.renderTarget,!1,r),this.freePotRenderTarget(r.renderTarget);else{var i=r.renderTarget,o=this.getPotRenderTarget(this.renderer.gl,r.sourceFrame.width,r.sourceFrame.height,r.resolution);o.setFrame(r.destinationFrame,r.sourceFrame),o.clear();var s=0;for(s=0;s0&&(e+="\nelse "),r1&&void 0!==arguments[1]?arguments[1]:[];return e[i.BLEND_MODES.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.ADD]=[t.ONE,t.DST_ALPHA],e[i.BLEND_MODES.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SCREEN]=[t.ONE,t.ONE_MINUS_SRC_COLOR],e[i.BLEND_MODES.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.NORMAL_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.ADD_NPM]=[t.SRC_ALPHA,t.DST_ALPHA,t.ONE,t.DST_ALPHA],e[i.BLEND_MODES.SCREEN_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_COLOR,t.ONE,t.ONE_MINUS_SRC_COLOR],e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":45}],98:[function(t,e,r){"use strict";function n(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e[i.DRAW_MODES.POINTS]=t.POINTS,e[i.DRAW_MODES.LINES]=t.LINES,e[i.DRAW_MODES.LINE_LOOP]=t.LINE_LOOP,e[i.DRAW_MODES.LINE_STRIP]=t.LINE_STRIP,e[i.DRAW_MODES.TRIANGLES]=t.TRIANGLES,e[i.DRAW_MODES.TRIANGLE_STRIP]=t.TRIANGLE_STRIP,e[i.DRAW_MODES.TRIANGLE_FAN]=t.TRIANGLE_FAN,e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":45}],99:[function(t,e,r){"use strict";function n(t){var e=t.getContextAttributes();e.stencil||console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly")}r.__esModule=!0,r.default=n},{}],100:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./utils/maxRecommendedTextures"),o=n(i),s=t("./utils/canUploadSameBuffer"),a=n(s);r.default={TARGET_FPMS:.06,MIPMAP_TEXTURES:!0,RESOLUTION:1,FILTER_RESOLUTION:1,SPRITE_MAX_TEXTURES:(0,o.default)(32),SPRITE_BATCH_SIZE:4096,RETINA_PREFIX:/@([0-9\.]+)x/,RENDER_OPTIONS:{view:null,antialias:!1,forceFXAA:!1,autoResize:!1,transparent:!1,backgroundColor:0,clearBeforeRender:!0,preserveDrawingBuffer:!1,roundPixels:!1,width:800,height:600,legacy:!1},TRANSFORM_MODE:0,GC_MODE:0,GC_MAX_IDLE:3600,GC_MAX_CHECK_COUNT:600,WRAP_MODE:0,SCALE_MODE:0,PRECISION_VERTEX:"highp",PRECISION_FRAGMENT:"mediump",CAN_UPLOAD_SAME_BUFFER:(0,a.default)()}},{"./utils/canUploadSameBuffer":120,"./utils/maxRecommendedTextures":125}],101:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r=n&&v.x=i&&v.y>16)+(65280&t)+((255&t)<<16)}},{key:"texture",get:function(){return this._texture},set:function(t){this._texture!==t&&(this._texture=t,this.cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,t&&(t.baseTexture.hasLoaded?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}]),e}(p.default);r.default=y},{"../const":45,"../display/Container":47,"../math":69,"../textures/Texture":114,"../utils":123}],102:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../renderers/canvas/CanvasRenderer"),s=n(o),a=t("../../const"),u=t("../../math"),h=t("./CanvasTinter"),l=n(h),c=new u.Matrix,d=function(){function t(e){i(this,t),this.renderer=e}return t.prototype.render=function(t){var e=t._texture,r=this.renderer,n=e._frame.width,i=e._frame.height,o=t.transform.worldTransform,s=0,h=0;if(!(e.orig.width<=0||e.orig.height<=0)&&e.baseTexture.source&&(r.setBlendMode(t.blendMode),e.valid)){r.context.globalAlpha=t.worldAlpha;var d=e.baseTexture.scaleMode===a.SCALE_MODES.LINEAR;r.smoothProperty&&r.context[r.smoothProperty]!==d&&(r.context[r.smoothProperty]=d),e.trim?(s=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,h=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(s=(.5-t.anchor.x)*e.orig.width,h=(.5-t.anchor.y)*e.orig.height),e.rotate&&(o.copy(c),o=c,u.GroupD8.matrixAppendRotationInv(o,e.rotate,s,h),s=0,h=0),s-=n/2,h-=i/2,r.roundPixels?(r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution|0,o.ty*r.resolution|0),s=0|s,h=0|h):r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution,o.ty*r.resolution);var f=e.baseTexture.resolution;16777215!==t.tint?(t.cachedTint===t.tint&&t.tintedTexture.tintId===t._texture._updateID||(t.cachedTint=t.tint,t.tintedTexture=l.default.getTintedTexture(t,t.tint)),r.context.drawImage(t.tintedTexture,0,0,n*f,i*f,s*r.resolution,h*r.resolution,n*r.resolution,i*r.resolution)):r.context.drawImage(e.baseTexture.source,e._frame.x*f,e._frame.y*f,n*f,i*f,s*r.resolution,h*r.resolution,n*r.resolution,i*r.resolution)}},t.prototype.destroy=function(){this.renderer=null},t}();r.default=d,s.default.registerPlugin("sprite",d)},{"../../const":45,"../../math":69,"../../renderers/canvas/CanvasRenderer":76,"./CanvasTinter":103}],103:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("../../utils"),o=t("../../renderers/canvas/utils/canUseNewCanvasBlendModes"),s=n(o),a={getTintedTexture:function(t,e){var r=t._texture;e=a.roundColor(e);var n="#"+("00000"+(0|e).toString(16)).substr(-6);r.tintCache=r.tintCache||{};var i=r.tintCache[n],o=void 0;if(i){if(i.tintId===r._updateID)return r.tintCache[n];o=r.tintCache[n]}else o=a.canvas||document.createElement("canvas");if(a.tintMethod(r,e,o),o.tintId=r._updateID,a.convertTintToImage){var s=new Image;s.src=o.toDataURL(),r.tintCache[n]=s}else r.tintCache[n]=o,a.canvas=null;return o},tintWithMultiply:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="multiply",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},tintWithOverlay:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.globalCompositeOperation="copy",n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},tintWithPerPixel:function(t,e,r){var n=r.getContext("2d"),o=t._frame.clone(),s=t.baseTexture.resolution;o.x*=s,o.y*=s,o.width*=s,o.height*=s,r.width=Math.ceil(o.width),r.height=Math.ceil(o.height),n.globalCompositeOperation="copy",n.drawImage(t.baseTexture.source,o.x,o.y,o.width,o.height,0,0,o.width,o.height);for(var a=(0,i.hex2rgb)(e),u=a[0],h=a[1],l=a[2],c=n.getImageData(0,0,o.width,o.height),d=c.data,f=0;f=this.size&&this.flush(),t._texture._uvs&&(this.sprites[this.currentIndex++]=t)},e.prototype.flush=function(){if(0!==this.currentIndex){var t=this.renderer.gl,e=this.MAX_TEXTURES,r=S.default.nextPow2(this.currentIndex),n=S.default.log2(r),i=this.buffers[n],o=this.sprites,s=this.groups,a=i.float32View,u=i.uint32View,h=this.boundTextures,l=this.renderer.boundTextures,c=this.renderer.textureGC.count,d=0,f=void 0,p=void 0,v=1,y=0,g=s[0],m=void 0,_=void 0,T=x.premultiplyBlendMode[o[0]._texture.baseTexture.premultipliedAlpha?1:0][o[0].blendMode];g.textureCount=0,g.start=0,g.blend=T,O++;var E=void 0;for(E=0;E0&&(e+="\nelse "),r0&&(r.shadowColor=e.dropShadowColor);for(var f=Math.cos(e.dropShadowAngle)*e.dropShadowDistance,p=Math.sin(e.dropShadowAngle)*e.dropShadowDistance,v=0;v3&&void 0!==arguments[3]&&arguments[3],i=this._style,o=i.letterSpacing;if(0===o)return void(n?this.context.strokeText(t,e,r):this.context.fillText(t,e,r));for(var s=String.prototype.split.call(t,""),a=e,u=0,h="";u3&&void 0!==arguments[3]?arguments[3]:t._canvas;n=n||r.wordWrap;var o=r.toFontString(),s=t.measureFont(o),a=i.getContext("2d");a.font=o;for(var u=n?t.wordWrap(e,r,i):e,h=u.split(/(?:\r\n|\r|\n)/),l=new Array(h.length),c=0,d=0;d2&&void 0!==arguments[2]?arguments[2]:t._canvas,i=n.getContext("2d"),o="",s=e.split("\n"),a=r.wordWrapWidth,u={},h=0;ha)for(var p=c[d].split(""),v=0;vl?(o+="\n"+y,l=a-g):(0===v&&(o+=" "),o+=y,l-=g)}else{var m=f+i.measureText(" ").width;0===d||m>l?(d>0&&(o+="\n"),o+=c[d],l=a-f):(l-=m,o+=" "+c[d])}}hs;--c){for(var v=0;v=0;r--){var n=e[r].trim();/([\"\'])[^\'\"]+\1/.test(n)||(n='"'+n+'"'),e[r]=n}return this.fontStyle+" "+this.fontVariant+" "+this.fontWeight+" "+t+" "+e.join(",")},a(t,[{key:"align",get:function(){return this._align},set:function(t){this._align!==t&&(this._align=t,this.styleID++)}},{key:"breakWords",get:function(){return this._breakWords},set:function(t){this._breakWords!==t&&(this._breakWords=t,this.styleID++)}},{key:"dropShadow",get:function(){return this._dropShadow},set:function(t){this._dropShadow!==t&&(this._dropShadow=t,this.styleID++)}},{key:"dropShadowAlpha",get:function(){return this._dropShadowAlpha},set:function(t){this._dropShadowAlpha!==t&&(this._dropShadowAlpha=t,this.styleID++)}},{key:"dropShadowAngle",get:function(){return this._dropShadowAngle},set:function(t){this._dropShadowAngle!==t&&(this._dropShadowAngle=t,this.styleID++)}},{key:"dropShadowBlur",get:function(){return this._dropShadowBlur},set:function(t){this._dropShadowBlur!==t&&(this._dropShadowBlur=t,this.styleID++)}},{key:"dropShadowColor",get:function(){return this._dropShadowColor},set:function(t){var e=o(t);this._dropShadowColor!==e&&(this._dropShadowColor=e,this.styleID++)}},{key:"dropShadowDistance",get:function(){return this._dropShadowDistance},set:function(t){this._dropShadowDistance!==t&&(this._dropShadowDistance=t,this.styleID++)}},{key:"fill",get:function(){return this._fill},set:function(t){var e=o(t);this._fill!==e&&(this._fill=e,this.styleID++)}},{key:"fillGradientType",get:function(){return this._fillGradientType},set:function(t){this._fillGradientType!==t&&(this._fillGradientType=t,this.styleID++)}},{key:"fillGradientStops",get:function(){return this._fillGradientStops},set:function(t){s(this._fillGradientStops,t)||(this._fillGradientStops=t,this.styleID++)}},{key:"fontFamily",get:function(){return this._fontFamily},set:function(t){this.fontFamily!==t&&(this._fontFamily=t,this.styleID++)}},{key:"fontSize",get:function(){return this._fontSize},set:function(t){this._fontSize!==t&&(this._fontSize=t,this.styleID++)}},{key:"fontStyle",get:function(){return this._fontStyle},set:function(t){this._fontStyle!==t&&(this._fontStyle=t,this.styleID++)}},{key:"fontVariant",get:function(){return this._fontVariant},set:function(t){this._fontVariant!==t&&(this._fontVariant=t,this.styleID++)}},{key:"fontWeight",get:function(){return this._fontWeight},set:function(t){this._fontWeight!==t&&(this._fontWeight=t,this.styleID++)}},{key:"letterSpacing",get:function(){return this._letterSpacing},set:function(t){this._letterSpacing!==t&&(this._letterSpacing=t,this.styleID++)}},{key:"lineHeight",get:function(){return this._lineHeight},set:function(t){this._lineHeight!==t&&(this._lineHeight=t,this.styleID++)}},{key:"lineJoin",get:function(){return this._lineJoin},set:function(t){this._lineJoin!==t&&(this._lineJoin=t,this.styleID++)}},{key:"miterLimit",get:function(){return this._miterLimit},set:function(t){this._miterLimit!==t&&(this._miterLimit=t,this.styleID++)}},{key:"padding",get:function(){return this._padding},set:function(t){this._padding!==t&&(this._padding=t,this.styleID++)}},{key:"stroke",get:function(){return this._stroke},set:function(t){var e=o(t);this._stroke!==e&&(this._stroke=e,this.styleID++)}},{key:"strokeThickness",get:function(){return this._strokeThickness},set:function(t){this._strokeThickness!==t&&(this._strokeThickness=t,this.styleID++)}},{key:"textBaseline",get:function(){return this._textBaseline},set:function(t){this._textBaseline!==t&&(this._textBaseline=t,this.styleID++)}},{key:"trim",get:function(){return this._trim},set:function(t){this._trim!==t&&(this._trim=t,this.styleID++)}},{key:"wordWrap",get:function(){return this._wordWrap},set:function(t){this._wordWrap!==t&&(this._wordWrap=t,this.styleID++)}},{key:"wordWrapWidth",get:function(){return this._wordWrapWidth},set:function(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this.styleID++)}}]),t}();r.default=c},{"../const":45,"../utils":123}],110:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("./BaseTexture"),u=n(a),h=t("../settings"),l=n(h),c=function(t){function e(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,s=arguments[2],a=arguments[3];i(this,e);var u=o(this,t.call(this,null,s));return u.resolution=a||l.default.RESOLUTION,u.width=r,u.height=n,u.realWidth=u.width*u.resolution,u.realHeight=u.height*u.resolution,u.scaleMode=void 0!==s?s:l.default.SCALE_MODE,u.hasLoaded=!0,u._glRenderTargets={},u._canvasRenderTarget=null,u.valid=!1,u}return s(e,t),e.prototype.resize=function(t,e){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.realWidth=this.width*this.resolution,this.realHeight=this.height*this.resolution,this.valid&&this.emit("update",this))},e.prototype.destroy=function(){t.prototype.destroy.call(this,!0),this.renderer=null},e}(u.default);r.default=c},{"../settings":100,"./BaseTexture":111}],111:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u=t("../utils"),h=t("../settings"),l=n(h),c=t("eventemitter3"),d=n(c),f=t("../utils/determineCrossOrigin"),p=n(f),v=t("bit-twiddle"),y=n(v),g=function(t){function e(r,n,s){i(this,e);var a=o(this,t.call(this));return a.uid=(0,u.uid)(),a.touched=0,a.resolution=s||l.default.RESOLUTION,a.width=100,a.height=100,a.realWidth=100,a.realHeight=100,a.scaleMode=void 0!==n?n:l.default.SCALE_MODE,a.hasLoaded=!1,a.isLoading=!1,a.source=null,a.origSource=null,a.imageType=null,a.sourceScale=1,a.premultipliedAlpha=!0,a.imageUrl=null,a.isPowerOfTwo=!1,a.mipmap=l.default.MIPMAP_TEXTURES,a.wrapMode=l.default.WRAP_MODE,a._glTextures={},a._enabled=0,a._virtalBoundId=-1,a._destroyed=!1,a.textureCacheIds=[],r&&a.loadSource(r),a}return s(e,t),e.prototype.update=function(){"svg"!==this.imageType&&(this.realWidth=this.source.naturalWidth||this.source.videoWidth||this.source.width,this.realHeight=this.source.naturalHeight||this.source.videoHeight||this.source.height,this._updateDimensions()),this.emit("update",this)},e.prototype._updateDimensions=function(){this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=y.default.isPow2(this.realWidth)&&y.default.isPow2(this.realHeight)},e.prototype.loadSource=function(t){var e=this,r=this.isLoading;this.hasLoaded=!1,this.isLoading=!1,r&&this.source&&(this.source.onload=null,this.source.onerror=null);var n=!this.source;if(this.source=t,(t.src&&t.complete||t.getContext)&&t.width&&t.height)this._updateImageType(),"svg"===this.imageType?this._loadSvgSource():this._sourceLoaded(),n&&this.emit("loaded",this);else if(!t.getContext){var i=function(){e.isLoading=!0;var n=e;if(t.onload=function(){if(n._updateImageType(),t.onload=null,t.onerror=null,n.isLoading)return n.isLoading=!1,n._sourceLoaded(),"svg"===n.imageType?void n._loadSvgSource():void n.emit("loaded",n)},t.onerror=function(){t.onload=null,t.onerror=null,n.isLoading&&(n.isLoading=!1,n.emit("error",n))},t.complete&&t.src){if(t.onload=null,t.onerror=null,"svg"===n.imageType)return n._loadSvgSource(),{v:void 0};e.isLoading=!1,t.width&&t.height?(e._sourceLoaded(),r&&e.emit("loaded",e)):r&&e.emit("error",e)}}();if("object"===("undefined"==typeof i?"undefined":a(i)))return i.v}},e.prototype._updateImageType=function(){if(this.imageUrl){var t=(0,u.decomposeDataUri)(this.imageUrl),e=void 0;if(t&&"image"===t.mediaType){var r=t.subType.split("+")[0];if(e=(0,u.getUrlFileExtension)("."+r),!e)throw new Error("Invalid image type in data URI.")}else e=(0,u.getUrlFileExtension)(this.imageUrl),e||(e="png");this.imageType=e}},e.prototype._loadSvgSource=function(){if("svg"===this.imageType){var t=(0,u.decomposeDataUri)(this.imageUrl);t?this._loadSvgSourceUsingDataUri(t):this._loadSvgSourceUsingXhr()}},e.prototype._loadSvgSourceUsingDataUri=function(t){var e=void 0;if("base64"===t.encoding){if(!atob)throw new Error("Your browser doesn't support base64 conversions.");e=atob(t.data)}else e=t.data;this._loadSvgSourceUsingString(e)},e.prototype._loadSvgSourceUsingXhr=function(){var t=this,e=new XMLHttpRequest;e.onload=function(){if(e.readyState!==e.DONE||200!==e.status)throw new Error("Failed to load SVG using XHR.");t._loadSvgSourceUsingString(e.response)},e.onerror=function(){return t.emit("error",t)},e.open("GET",this.imageUrl,!0),e.send()},e.prototype._loadSvgSourceUsingString=function(t){var r=(0,u.getSvgSize)(t),n=r.width,i=r.height;if(!n||!i)throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them.");this.realWidth=Math.round(n*this.sourceScale),this.realHeight=Math.round(i*this.sourceScale),this._updateDimensions();var o=document.createElement("canvas");o.width=this.realWidth,o.height=this.realHeight,o._pixiId="canvas_"+(0,u.uid)(),o.getContext("2d").drawImage(this.source,0,0,n,i,0,0,this.realWidth,this.realHeight),this.origSource=this.source,this.source=o,e.addToCache(this,o._pixiId),this.isLoading=!1,this._sourceLoaded(),this.emit("loaded",this)},e.prototype._sourceLoaded=function(){this.hasLoaded=!0,this.update()},e.prototype.destroy=function(){this.imageUrl&&(delete u.TextureCache[this.imageUrl],this.imageUrl=null,navigator.isCocoonJS||(this.source.src="")),this.source=null,this.dispose(),e.removeFromCache(this),this.textureCacheIds=null,this._destroyed=!0},e.prototype.dispose=function(){this.emit("dispose",this)},e.prototype.updateSourceImage=function(t){this.source.src=t,this.loadSource(this.source)},e.fromImage=function(t,r,n,i){var o=u.BaseTextureCache[t];if(!o){var s=new Image;void 0===r&&0!==t.indexOf("data:")?s.crossOrigin=(0,p.default)(t):r&&(s.crossOrigin="string"==typeof r?r:"anonymous"),o=new e(s,n),o.imageUrl=t,i&&(o.sourceScale=i),o.resolution=(0,u.getResolutionOfUrl)(t),s.src=t,e.addToCache(o,t)}return o},e.fromCanvas=function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"canvas";t._pixiId||(t._pixiId=n+"_"+(0,u.uid)());var i=u.BaseTextureCache[t._pixiId];return i||(i=new e(t,r),e.addToCache(i,t._pixiId)),i},e.from=function(t,r,n){if("string"==typeof t)return e.fromImage(t,void 0,r,n);if(t instanceof HTMLImageElement){var i=t.src,o=u.BaseTextureCache[i];return o||(o=new e(t,r),o.imageUrl=i,n&&(o.sourceScale=n),o.resolution=(0,u.getResolutionOfUrl)(i),e.addToCache(o,i)),o}return t instanceof HTMLCanvasElement?e.fromCanvas(t,r):t},e.addToCache=function(t,e){e&&(t.textureCacheIds.indexOf(e)===-1&&t.textureCacheIds.push(e),u.BaseTextureCache[e]=t)},e.removeFromCache=function(t){if("string"==typeof t){var e=u.BaseTextureCache[t];if(e){var r=e.textureCacheIds.indexOf(t);return r>-1&&e.textureCacheIds.splice(r,1),delete u.BaseTextureCache[t],e}}else if(t&&t.textureCacheIds){for(var n=0;n0&&e>0,this._frame.width=this.orig.width=t,this._frame.height=this.orig.height=e,r||this.baseTexture.resize(t,e),this._updateUvs()},e.create=function(t,r,n,i){return new e(new u.default(t,r,n,i))},e}(l.default);r.default=c},{"./BaseRenderTexture":110,"./Texture":114}],113:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:null;n(this,t),this.baseTexture=e,this.textures={},this.data=r,this.resolution=this._updateResolution(i||this.baseTexture.imageUrl),this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}return i(t,null,[{key:"BATCH_SIZE",get:function(){return 1e3}}]),t.prototype._updateResolution=function(t){var e=this.data.meta.scale,r=(0,s.getResolutionOfUrl)(t,null);return null===r&&(r=void 0!==e?parseFloat(e):1),1!==r&&(this.baseTexture.resolution=r,this.baseTexture.update()),r},t.prototype.parse=function(e){this._batchIndex=0,this._callback=e,this._frameKeys.length<=t.BATCH_SIZE?(this._processFrames(0),this._parseComplete()):this._nextBatch()},t.prototype._processFrames=function(e){for(var r=e,n=t.BATCH_SIZE;r-e0&&void 0!==arguments[0]&&arguments[0];for(var e in this.textures)this.textures[e].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,t&&this.baseTexture.destroy(),this.baseTexture=null},t}();r.default=a},{"../":64,"../utils":123}],114:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(){var t=document.createElement("canvas");t.width=10,t.height=10;var e=t.getContext("2d");return e.fillStyle="white",e.fillRect(0,0,10,10),new T(new c.default(t))}function u(t){t.destroy=function(){},t.on=function(){},t.once=function(){},t.emit=function(){}}r.__esModule=!0;var h=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:"canvas";return new e(c.default.fromCanvas(t,r,n))},e.fromVideo=function(t,r){return"string"==typeof t?e.fromVideoUrl(t,r):new e(f.default.fromVideo(t,r))},e.fromVideoUrl=function(t,r){return new e(f.default.fromUrl(t,r))},e.from=function(t){if("string"==typeof t){var r=_.TextureCache[t];if(!r){var n=null!==t.match(/\.(mp4|webm|ogg|h264|avi|mov)$/);return n?e.fromVideoUrl(t):e.fromImage(t)}return r}return t instanceof HTMLImageElement?new e(c.default.from(t)):t instanceof HTMLCanvasElement?e.fromCanvas(t,x.default.SCALE_MODE,"HTMLCanvasElement"):t instanceof HTMLVideoElement?e.fromVideo(t):t instanceof c.default?new e(t):t},e.fromLoader=function(t,r,n){var i=new c.default(t,(void 0),(0,_.getResolutionOfUrl)(r)),o=new e(i);return i.imageUrl=r,n||(n=r),c.default.addToCache(o.baseTexture,n),e.addToCache(o,n),n!==r&&(c.default.addToCache(o.baseTexture,r),e.addToCache(o,r)),o},e.addToCache=function(t,e){e&&(t.textureCacheIds.indexOf(e)===-1&&t.textureCacheIds.push(e),_.TextureCache[e]=t)},e.removeFromCache=function(t){if("string"==typeof t){var e=_.TextureCache[t];if(e){var r=e.textureCacheIds.indexOf(t);return r>-1&&e.textureCacheIds.splice(r,1),delete _.TextureCache[t],e}}else if(t&&t.textureCacheIds){for(var n=0;nthis.baseTexture.width||t.y+t.height>this.baseTexture.height)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions: "+("X: "+t.x+" + "+t.width+" > "+this.baseTexture.width+" ")+("Y: "+t.y+" + "+t.height+" > "+this.baseTexture.height));this.valid=t&&t.width&&t.height&&this.baseTexture.hasLoaded,this.trim||this.rotate||(this.orig=t),this.valid&&this._updateUvs()}},{key:"rotate",get:function(){return this._rotate},set:function(t){this._rotate=t,this.valid&&this._updateUvs()}},{key:"width",get:function(){return this.orig.width}},{key:"height",get:function(){return this.orig.height}}]),e}(g.default);r.default=T,T.EMPTY=new T(new c.default),u(T.EMPTY),u(T.EMPTY.baseTexture),T.WHITE=a(),u(T.WHITE),u(T.WHITE.baseTexture)},{"../math":69,"../settings":100,"../utils":123,"./BaseTexture":111,"./TextureUvs":115,"./VideoBaseTexture":116,eventemitter3:3}],115:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../math/GroupD8"),s=n(o),a=function(){function t(){i(this,t),this.x0=0,this.y0=0,this.x1=1,this.y1=0,this.x2=1,this.y2=1,this.x3=0,this.y3=1,this.uvsUint32=new Uint32Array(4)}return t.prototype.set=function(t,e,r){var n=e.width,i=e.height;if(r){var o=t.width/2/n,a=t.height/2/i,u=t.x/n+o,h=t.y/i+a;r=s.default.add(r,s.default.NW),this.x0=u+o*s.default.uX(r),this.y0=h+a*s.default.uY(r),r=s.default.add(r,2),this.x1=u+o*s.default.uX(r), +this.y1=h+a*s.default.uY(r),r=s.default.add(r,2),this.x2=u+o*s.default.uX(r),this.y2=h+a*s.default.uY(r),r=s.default.add(r,2),this.x3=u+o*s.default.uX(r),this.y3=h+a*s.default.uY(r)}else this.x0=t.x/n,this.y0=t.y/i,this.x1=(t.x+t.width)/n,this.y1=t.y/i,this.x2=(t.x+t.width)/n,this.y2=(t.y+t.height)/i,this.x3=t.x/n,this.y3=(t.y+t.height)/i;this.uvsUint32[0]=(65535*this.y0&65535)<<16|65535*this.x0&65535,this.uvsUint32[1]=(65535*this.y1&65535)<<16|65535*this.x1&65535,this.uvsUint32[2]=(65535*this.y2&65535)<<16|65535*this.x2&65535,this.uvsUint32[3]=(65535*this.y3&65535)<<16|65535*this.x3&65535},t}();r.default=a},{"../math/GroupD8":65}],116:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t,e){e||(e="video/"+t.substr(t.lastIndexOf(".")+1));var r=document.createElement("source");return r.src=t,r.type=e,r}r.__esModule=!0;var u=function(){function t(t,e){for(var r=0;r0&&t.paused===!1&&t.ended===!1&&t.readyState>2},e.prototype._isSourceReady=function(){return 3===this.source.readyState||4===this.source.readyState},e.prototype._onPlayStart=function(){this.hasLoaded||this._onCanPlay(),!this._isAutoUpdating&&this.autoUpdate&&(d.shared.add(this.update,this,f.UPDATE_PRIORITY.HIGH),this._isAutoUpdating=!0)},e.prototype._onPlayStop=function(){this._isAutoUpdating&&(d.shared.remove(this.update,this),this._isAutoUpdating=!1)},e.prototype._onCanPlay=function(){this.hasLoaded=!0,this.source&&(this.source.removeEventListener("canplay",this._onCanPlay),this.source.removeEventListener("canplaythrough",this._onCanPlay),this.width=this.source.videoWidth,this.height=this.source.videoHeight,this.__loaded||(this.__loaded=!0,this.emit("loaded",this)),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.source.play())},e.prototype.destroy=function(){this._isAutoUpdating&&d.shared.remove(this.update,this),this.source&&this.source._pixiId&&(l.default.removeFromCache(this.source._pixiId),delete this.source._pixiId),t.prototype.destroy.call(this)},e.fromVideo=function(t,r){t._pixiId||(t._pixiId="video_"+(0,c.uid)());var n=c.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),l.default.addToCache(n,t._pixiId)),n},e.fromUrl=function(t,r){var n=document.createElement("video");if(n.setAttribute("webkit-playsinline",""),n.setAttribute("playsinline",""),Array.isArray(t))for(var i=0;i2&&void 0!==arguments[2]?arguments[2]:u.UPDATE_PRIORITY.NORMAL;return this._addListener(new l.default(t,e,r))},t.prototype.addOnce=function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:u.UPDATE_PRIORITY.NORMAL;return this._addListener(new l.default(t,e,r,(!0)))},t.prototype._addListener=function(t){var e=this._head.next,r=this._head;if(e){for(;e;){if(t.priority>e.priority){t.connect(r);break}r=e,e=e.next}t.previous||t.connect(r)}else t.connect(r);return this._startIfPossible(),this},t.prototype.remove=function(t,e){for(var r=this._head.next;r;)r=r.match(t,e)?r.destroy():r.next;return this._head.next||this._cancelIfNeeded(),this},t.prototype.start=function(){this.started||(this.started=!0,this._requestIfNeeded())},t.prototype.stop=function(){this.started&&(this.started=!1,this._cancelIfNeeded())},t.prototype.destroy=function(){this.stop();for(var t=this._head.next;t;)t=t.destroy(!0);this._head.destroy(),this._head=null},t.prototype.update=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:performance.now(),e=void 0;if(t>this.lastTime){e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),this.deltaTime=e*a.default.TARGET_FPMS*this.speed;for(var r=this._head,n=r.next;n;)n=n.emit(this.deltaTime);r.next||this._cancelIfNeeded()}else this.deltaTime=this.elapsedMS=0;this.lastTime=t},o(t,[{key:"FPS",get:function(){return 1e3/this.elapsedMS}},{key:"minFPS",get:function(){return 1e3/this._maxElapsedMS},set:function(t){var e=Math.min(Math.max(0,t)/1e3,a.default.TARGET_FPMS);this._maxElapsedMS=1/e}}]),t}();r.default=c},{"../const":45,"../settings":100,"./TickerListener":118}],118:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];n(this,t),this.fn=e,this.context=r,this.priority=i,this.once=o,this.next=null,this.previous=null,this._destroyed=!1}return t.prototype.match=function(t,e){return e=e||null,this.fn===t&&this.context===e},t.prototype.emit=function(t){this.fn&&(this.context?this.fn.call(this.context,t):this.fn(t));var e=this.next;return this.once&&this.destroy(!0),this._destroyed&&(this.next=null),e},t.prototype.connect=function(t){this.previous=t,t.next&&(t.next.previous=this),this.next=t.next,t.next=this},t.prototype.destroy=function(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._destroyed=!0,this.fn=null,this.context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);var e=this.previous;return this.next=t?null:e,this.previous=null,e},t}();r.default=i},{}],119:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.Ticker=r.shared=void 0;var i=t("./Ticker"),o=n(i),s=new o.default;s.autoStart=!0,s.destroy=function(){},r.shared=s,r.Ticker=o.default},{"./Ticker":117}],120:[function(t,e,r){"use strict";function n(){var t=!!navigator.platform&&/iPad|iPhone|iPod/.test(navigator.platform);return!t}r.__esModule=!0,r.default=n},{}],121:[function(t,e,r){"use strict";function n(t){for(var e=6*t,r=new Uint16Array(e),n=0,i=0;n1&&void 0!==arguments[1]?arguments[1]:window.location;if(0===t.indexOf("data:"))return"";e=e||window.location,a||(a=document.createElement("a")),a.href=t,t=s.default.parse(a.href);var r=!t.port&&""===e.port||t.port===e.port;return t.hostname===e.hostname&&r&&t.protocol===e.protocol?"":"anonymous"}r.__esModule=!0,r.default=i;var o=t("url"),s=n(o),a=void 0},{url:28}],123:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(){return++k}function s(t,e){return e=e||[],e[0]=(t>>16&255)/255,e[1]=(t>>8&255)/255,e[2]=(255&t)/255,e}function a(t){return t=t.toString(16),t="000000".substr(0,6-t.length)+t,"#"+t}function u(t){return(255*t[0]<<16)+(255*t[1]<<8)+(255*t[2]|0)}function h(t,e){var r=S.default.RETINA_PREFIX.exec(t);return r?parseFloat(r[1]):void 0!==e?e:1}function l(t){var e=w.DATA_URI.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,encoding:e[3]?e[3].toLowerCase():void 0,data:e[4]}}function c(t){var e=w.URL_FILE_EXTENSION.exec(t);if(e)return e[1].toLowerCase()}function d(t){var e=w.SVG_SIZE.exec(t),r={};return e&&(r[e[1]]=Math.round(parseFloat(e[3])),r[e[5]]=Math.round(parseFloat(e[7]))),r}function f(){j=!0}function p(t){if(!j){if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var e=["\n %c %c %c Pixi.js "+w.VERSION+" - ✰ "+t+" ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n","background: #ff66a5; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff66a5; background: #030307; padding:5px 0;","background: #ff66a5; padding:5px 0;","background: #ffc3dc; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;"];window.console.log.apply(console,e)}else window.console&&window.console.log("Pixi.js "+w.VERSION+" - "+t+" - http://www.pixijs.com/");j=!0}}function v(){var t={stencil:!0,failIfMajorPerformanceCaveat:!0};try{if(!window.WebGLRenderingContext)return!1;var e=document.createElement("canvas"),r=e.getContext("webgl",t)||e.getContext("experimental-webgl",t),n=!(!r||!r.getContextAttributes().stencil);if(r){var i=r.getExtension("WEBGL_lose_context");i&&i.loseContext()}return r=null,n}catch(t){return!1}}function y(t){return 0===t?0:t<0?-1:1}function g(){var t=void 0;for(t in U)U[t].destroy();for(t in X)X[t].destroy()}function m(){var t=void 0;for(t in U)delete U[t];for(t in X)delete X[t]}function _(t,e){return G[e?1:0][t]}function b(t,e){if(1===e)return(255*e<<24)+t;if(0===e)return 0;var r=t>>16&255,n=t>>8&255,i=255&t;return r=r*e+.5|0,n=n*e+.5|0,i=i*e+.5|0,(255*e<<24)+(r<<16)+(n<<8)+i}function x(t,e,r,n){return r=r||new Float32Array(4),n||void 0===n?(r[0]=t[0]*e,r[1]=t[1]*e,r[2]=t[2]*e):(r[0]=t[0],r[1]=t[1],r[2]=t[2]),r[3]=e,r}function T(t,e,r,n){return r=r||new Float32Array(4),r[0]=(t>>16&255)/255,r[1]=(t>>8&255)/255,r[2]=(255&t)/255,(n||void 0===n)&&(r[0]*=e,r[1]*=e,r[2]*=e),r[3]=e,r}r.__esModule=!0,r.premultiplyBlendMode=r.BaseTextureCache=r.TextureCache=r.mixins=r.pluginTarget=r.EventEmitter=r.removeItems=r.isMobile=void 0,r.uid=o,r.hex2rgb=s,r.hex2string=a,r.rgb2hex=u,r.getResolutionOfUrl=h,r.decomposeDataUri=l,r.getUrlFileExtension=c,r.getSvgSize=d,r.skipHello=f,r.sayHello=p,r.isWebGLSupported=v,r.sign=y,r.destroyTextureCache=g,r.clearTextureCache=m,r.correctBlendMode=_,r.premultiplyTint=b,r.premultiplyRgba=x,r.premultiplyTintToRgba=T;var w=t("../const"),E=t("../settings"),S=i(E),O=t("eventemitter3"),P=i(O),M=t("./pluginTarget"),C=i(M),R=t("./mixin"),A=n(R),I=t("ismobilejs"),D=n(I),L=t("remove-array-items"),N=i(L),F=t("./mapPremultipliedBlendModes"),B=i(F),k=0,j=!1;r.isMobile=D,r.removeItems=N.default,r.EventEmitter=P.default,r.pluginTarget=C.default,r.mixins=A;var U=r.TextureCache=Object.create(null),X=r.BaseTextureCache=Object.create(null),G=r.premultiplyBlendMode=(0,B.default)()},{"../const":45,"../settings":100,"./mapPremultipliedBlendModes":124,"./mixin":126,"./pluginTarget":127,eventemitter3:3,ismobilejs:4,"remove-array-items":30}],124:[function(t,e,r){"use strict";function n(){for(var t=[],e=[],r=0;r<32;r++)t[r]=r,e[r]=r;t[i.BLEND_MODES.NORMAL_NPM]=i.BLEND_MODES.NORMAL,t[i.BLEND_MODES.ADD_NPM]=i.BLEND_MODES.ADD,t[i.BLEND_MODES.SCREEN_NPM]=i.BLEND_MODES.SCREEN,e[i.BLEND_MODES.NORMAL]=i.BLEND_MODES.NORMAL_NPM,e[i.BLEND_MODES.ADD]=i.BLEND_MODES.ADD_NPM,e[i.BLEND_MODES.SCREEN]=i.BLEND_MODES.SCREEN_NPM;var n=[];return n.push(e),n.push(t),n}r.__esModule=!0,r.default=n;var i=t("../const")},{"../const":45}],125:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){return s.default.tablet||s.default.phone?4:t}r.__esModule=!0,r.default=i;var o=t("ismobilejs"),s=n(o)},{ismobilejs:4}],126:[function(t,e,r){"use strict";function n(t,e){if(t&&e)for(var r=Object.keys(e),n=0;n1?this._fontStyle="italic":t.indexOf("oblique")>-1?this._fontStyle="oblique":this._fontStyle="normal",t.indexOf("small-caps")>-1?this._fontVariant="small-caps":this._fontVariant="normal";var e=t.split(" "),r=-1;this._fontSize=26;for(var i=0;i-1&&r=this._durations[this.currentFrame];)n-=this._durations[this.currentFrame]*i,this._currentTime+=i;this._currentTime+=n/this._durations[this.currentFrame]}else this._currentTime+=e;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):r!==this.currentFrame&&(this.loop&&this.onLoop&&(this.animationSpeed>0&&this.currentFramer&&this.onLoop()),this.updateTexture())},e.prototype.updateTexture=function(){this._texture=this._textures[this.currentFrame],this._textureID=-1,this.onFrameChange&&this.onFrameChange(this.currentFrame)},e.prototype.destroy=function(e){this.stop(),t.prototype.destroy.call(this,e)},e.fromFrames=function(t){for(var r=[],n=0;n1&&void 0!==arguments[1]?arguments[1]:{};o(this,e);var i=s(this,t.call(this));return i._textWidth=0,i._textHeight=0,i._glyphs=[],i._font={tint:void 0!==n.tint?n.tint:16777215,align:n.align||"left",name:null,size:0},i.font=n.font,i._text=r,i._maxWidth=0,i._maxLineHeight=0,i._anchor=new d.default(function(){i.dirty=!0},i,0,0),i.dirty=!1,i.updateText(),i}return a(e,t),e.prototype.updateText=function(){for(var t=e.fonts[this._font.name],r=this._font.size/t.size,n=new l.Point,i=[],o=[],s=null,a=0,u=0,h=0,c=-1,d=0,f=0,p=0,v=0;v0&&n.x*r>this._maxWidth)l.utils.removeItems(i,c-f,v-c),v=c,c=-1,++f,o.push(d),u=Math.max(u,d),h++,n.x=0,n.y+=t.lineHeight,s=null;else{var g=t.chars[y];g&&(s&&g.kerning[s]&&(n.x+=g.kerning[s]),i.push({texture:g.texture,line:h,charCode:y,position:new l.Point(n.x+g.xOffset,n.y+g.yOffset)}),a=n.x+(g.texture.width+g.xOffset),n.x+=g.xAdvance,p=Math.max(p,g.yOffset+g.texture.height),s=y)}}o.push(a),u=Math.max(u,a);for(var m=[],_=0;_<=h;_++){var b=0;"right"===this._font.align?b=u-o[_]:"center"===this._font.align&&(b=(u-o[_])/2),m.push(b)}for(var x=i.length,T=this.tint,w=0;w=0?t:16777215,this.dirty=!0}},{key:"align",get:function(){return this._font.align},set:function(t){this._font.align=t||"left",this.dirty=!0}},{key:"anchor",get:function(){return this._anchor},set:function(t){"number"==typeof t?this._anchor.set(t):this._anchor.copy(t)}},{key:"font",get:function(){return this._font},set:function(t){t&&("string"==typeof t?(t=t.split(" "),this._font.name=1===t.length?t[0]:t.slice(1).join(" "),this._font.size=t.length>=2?parseInt(t[0],10):e.fonts[this._font.name].size):(this._font.name=t.name,this._font.size="number"==typeof t.size?t.size:parseInt(t.size,10)),this.dirty=!0)}},{key:"text",get:function(){return this._text},set:function(t){t=t.toString()||" ",this._text!==t&&(this._text=t,this.dirty=!0)}},{key:"maxWidth",get:function(){return this._maxWidth},set:function(t){this._maxWidth!==t&&(this._maxWidth=t,this.dirty=!0)}},{key:"maxLineHeight",get:function(){return this.validate(),this._maxLineHeight}},{key:"textWidth",get:function(){return this.validate(),this._textWidth}},{key:"textHeight",get:function(){return this.validate(),this._textHeight}}]),e}(l.Container);r.default=v,v.fonts={}},{"../core":64,"../core/math/ObservablePoint":67,"../core/settings":100}],135:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:100,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:100;o(this,e);var a=s(this,t.call(this,r));return a.tileTransform=new l.TransformStatic,a._width=n,a._height=i,a._canvasPattern=null,a.uvTransform=r.transform||new p.default(r),a.pluginName="tilingSprite",a.uvRespectAnchor=!1,a}return a(e,t),e.prototype._onTextureUpdate=function(){this.uvTransform&&(this.uvTransform.texture=this._texture)},e.prototype._renderWebGL=function(t){var e=this._texture;e&&e.valid&&(this.tileTransform.updateLocalTransform(),this.uvTransform.update(),t.setObjectRenderer(t.plugins[this.pluginName]),t.plugins[this.pluginName].render(this))},e.prototype._renderCanvas=function(t){var e=this._texture;if(e.baseTexture.hasLoaded){var r=t.context,n=this.worldTransform,i=t.resolution,o=e.baseTexture,s=o.resolution,a=this.tilePosition.x/this.tileScale.x%e._frame.width*s,u=this.tilePosition.y/this.tileScale.y%e._frame.height*s;if(!this._canvasPattern){var h=new l.CanvasRenderTarget(e._frame.width,e._frame.height,s);16777215!==this.tint?(this.cachedTint!==this.tint&&(this.cachedTint=this.tint,this.tintedTexture=d.default.getTintedTexture(this,this.tint)),h.context.drawImage(this.tintedTexture,0,0)):h.context.drawImage(o.source,-e._frame.x*s,-e._frame.y*s),this._canvasPattern=h.context.createPattern(h.canvas,"repeat")}r.globalAlpha=this.worldAlpha,r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t.setBlendMode(this.blendMode),r.fillStyle=this._canvasPattern,r.scale(this.tileScale.x/s,this.tileScale.y/s);var c=this.anchor.x*-this._width,f=this.anchor.y*-this._height;this.uvRespectAnchor?(r.translate(a,u),r.fillRect(-a+c,-u+f,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s)):(r.translate(a+c,u+f),r.fillRect(-a,-u,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s))}},e.prototype._calculateBounds=function(){var t=this._width*-this._anchor._x,e=this._height*-this._anchor._y,r=this._width*(1-this._anchor._x),n=this._height*(1-this._anchor._y);this._bounds.addFrame(this.transform,t,e,r,n)},e.prototype.getLocalBounds=function(e){return 0===this.children.length?(this._bounds.minX=this._width*-this._anchor._x,this._bounds.minY=this._height*-this._anchor._y,this._bounds.maxX=this._width*(1-this._anchor._x),this._bounds.maxY=this._height*(1-this._anchor._x),e||(this._localBoundsRect||(this._localBoundsRect=new l.Rectangle),e=this._localBoundsRect),this._bounds.getRectangle(e)):t.prototype.getLocalBounds.call(this,e)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,v);var e=this._width,r=this._height,n=-e*this.anchor._x;if(v.x>=n&&v.x=i&&v.y0&&void 0!==arguments[0]?arguments[0]:new o.Point,e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.parent?this.parent.toGlobal(this.position,t,e):(t.x=this.position.x,t.y=this.position.y),t}},{"../core":64}],140:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.BitmapText=r.TilingSpriteRenderer=r.TilingSprite=r.TextureTransform=r.AnimatedSprite=void 0;var i=t("./AnimatedSprite");Object.defineProperty(r,"AnimatedSprite",{enumerable:!0,get:function(){return n(i).default}});var o=t("./TextureTransform");Object.defineProperty(r,"TextureTransform",{enumerable:!0,get:function(){return n(o).default}});var s=t("./TilingSprite");Object.defineProperty(r,"TilingSprite",{enumerable:!0,get:function(){return n(s).default}});var a=t("./webgl/TilingSpriteRenderer");Object.defineProperty(r,"TilingSpriteRenderer",{enumerable:!0,get:function(){return n(a).default}});var u=t("./BitmapText");Object.defineProperty(r,"BitmapText",{enumerable:!0,get:function(){return n(u).default}}),t("./cacheAsBitmap"),t("./getChildByName"),t("./getGlobalPosition")},{"./AnimatedSprite":133,"./BitmapText":134,"./TextureTransform":135,"./TilingSprite":136,"./cacheAsBitmap":137,"./getChildByName":138,"./getGlobalPosition":139,"./webgl/TilingSpriteRenderer":141}],141:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../core"),u=n(a),h=t("../../core/const"),l=(t("path"),new u.Matrix),c=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.shader=null,n.simpleShader=null,n.quad=null,n}return s(e,t),e.prototype.onContextChange=function(){var t=this.renderer.gl;this.shader=new u.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n\n gl_FragColor = sample * color ;\n}\n"),this.simpleShader=new u.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n vec4 color = vec4(uColor.rgb * uColor.a, uColor.a);\n gl_FragColor = sample * color;\n}\n"),this.renderer.bindVao(null),this.quad=new u.Quad(t,this.renderer.state.attribState),this.quad.initVao(this.shader)},e.prototype.render=function(t){var e=this.renderer,r=this.quad;e.bindVao(r.vao);var n=r.vertices;n[0]=n[6]=t._width*-t.anchor.x,n[1]=n[3]=t._height*-t.anchor.y,n[2]=n[4]=t._width*(1-t.anchor.x),n[5]=n[7]=t._height*(1-t.anchor.y),t.uvRespectAnchor&&(n=r.uvs,n[0]=n[6]=-t.anchor.x,n[1]=n[3]=-t.anchor.y,n[2]=n[4]=1-t.anchor.x,n[5]=n[7]=1-t.anchor.y),r.upload();var i=t._texture,o=i.baseTexture,s=t.tileTransform.localTransform,a=t.uvTransform,c=o.isPowerOfTwo&&i.frame.width===o.width&&i.frame.height===o.height;c&&(o._glTextures[e.CONTEXT_UID]?c=o.wrapMode!==h.WRAP_MODES.CLAMP:o.wrapMode===h.WRAP_MODES.CLAMP&&(o.wrapMode=h.WRAP_MODES.REPEAT));var d=c?this.simpleShader:this.shader;e.bindShader(d);var f=i.width,p=i.height,v=t._width,y=t._height;l.set(s.a*f/v,s.b*f/y,s.c*p/v,s.d*p/y,s.tx/v,s.ty/y),l.invert(),c?l.prepend(a.mapCoord):(d.uniforms.uMapCoord=a.mapCoord.toArray(!0),d.uniforms.uClampFrame=a.uClampFrame,d.uniforms.uClampOffset=a.uClampOffset),d.uniforms.uTransform=l.toArray(!0),d.uniforms.uColor=u.utils.premultiplyTintToRgba(t.tint,t.worldAlpha,d.uniforms.uColor,o.premultipliedAlpha),d.uniforms.translationMatrix=t.transform.worldTransform.toArray(!0),d.uniforms.uSampler=e.bindTexture(i),e.setBlendMode(u.utils.correctBlendMode(t.blendMode,o.premultipliedAlpha)),r.vao.draw(this.renderer.gl.TRIANGLES,6,0)},e}(u.ObjectRenderer);r.default=c,u.WebGLRenderer.registerPlugin("tilingSprite",c)},{"../../core":64,"../../core/const":45,path:22}],142:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var u=function(){function t(t,e){for(var r=0;r=r&&(u=t-h-1),l=l.replace("%value%",e[u]),s+=l,s+="\n"}return n=n.replace("%blur%",s),n=n.replace("%size%",t)}r.__esModule=!0,r.default=n;var i={5:[.153388,.221461,.250301],7:[.071303,.131514,.189879,.214607],9:[.028532,.067234,.124009,.179044,.20236],11:[.0093,.028002,.065984,.121703,.175713,.198596],13:[.002406,.009255,.027867,.065666,.121117,.174868,.197641],15:[489e-6,.002403,.009246,.02784,.065602,.120999,.174697,.197448]},o=["varying vec2 vBlurTexCoords[%size%];","uniform sampler2D uSampler;","void main(void)","{"," gl_FragColor = vec4(0.0);"," %blur%","}"].join("\n")},{}],146:[function(t,e,r){"use strict";function n(t,e){var r=Math.ceil(t/2),n=i,o="",s=void 0;s=e?"vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);":"vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);";for(var a=0;ae;)r-=2;return r}r.__esModule=!0,r.default=n},{}],148:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n"));return r.uniforms.m=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],r.alpha=1,r}return s(e,t),e.prototype._loadMatrix=function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t;e&&(this._multiply(r,this.uniforms.m,t),r=this._colorMatrix(r)),this.uniforms.m=r},e.prototype._multiply=function(t,e,r){return t[0]=e[0]*r[0]+e[1]*r[5]+e[2]*r[10]+e[3]*r[15],t[1]=e[0]*r[1]+e[1]*r[6]+e[2]*r[11]+e[3]*r[16],t[2]=e[0]*r[2]+e[1]*r[7]+e[2]*r[12]+e[3]*r[17],t[3]=e[0]*r[3]+e[1]*r[8]+e[2]*r[13]+e[3]*r[18],t[4]=e[0]*r[4]+e[1]*r[9]+e[2]*r[14]+e[3]*r[19]+e[4],t[5]=e[5]*r[0]+e[6]*r[5]+e[7]*r[10]+e[8]*r[15],t[6]=e[5]*r[1]+e[6]*r[6]+e[7]*r[11]+e[8]*r[16],t[7]=e[5]*r[2]+e[6]*r[7]+e[7]*r[12]+e[8]*r[17],t[8]=e[5]*r[3]+e[6]*r[8]+e[7]*r[13]+e[8]*r[18],t[9]=e[5]*r[4]+e[6]*r[9]+e[7]*r[14]+e[8]*r[19]+e[9],t[10]=e[10]*r[0]+e[11]*r[5]+e[12]*r[10]+e[13]*r[15],t[11]=e[10]*r[1]+e[11]*r[6]+e[12]*r[11]+e[13]*r[16],t[12]=e[10]*r[2]+e[11]*r[7]+e[12]*r[12]+e[13]*r[17],t[13]=e[10]*r[3]+e[11]*r[8]+e[12]*r[13]+e[13]*r[18],t[14]=e[10]*r[4]+e[11]*r[9]+e[12]*r[14]+e[13]*r[19]+e[14],t[15]=e[15]*r[0]+e[16]*r[5]+e[17]*r[10]+e[18]*r[15],t[16]=e[15]*r[1]+e[16]*r[6]+e[17]*r[11]+e[18]*r[16],t[17]=e[15]*r[2]+e[16]*r[7]+e[17]*r[12]+e[18]*r[17],t[18]=e[15]*r[3]+e[16]*r[8]+e[17]*r[13]+e[18]*r[18],t[19]=e[15]*r[4]+e[16]*r[9]+e[17]*r[14]+e[18]*r[19]+e[19],t},e.prototype._colorMatrix=function(t){var e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e},e.prototype.brightness=function(t,e){var r=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.greyscale=function(t,e){var r=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.blackAndWhite=function(t){var e=[.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.hue=function(t,e){t=(t||0)/180*Math.PI;var r=Math.cos(t),n=Math.sin(t),i=Math.sqrt,o=1/3,s=i(o),a=r+(1-r)*o,u=o*(1-r)-s*n,h=o*(1-r)+s*n,l=o*(1-r)+s*n,c=r+o*(1-r),d=o*(1-r)-s*n,f=o*(1-r)-s*n,p=o*(1-r)+s*n,v=r+o*(1-r),y=[a,u,h,0,0,l,c,d,0,0,f,p,v,0,0,0,0,0,1,0];this._loadMatrix(y,e)},e.prototype.contrast=function(t,e){var r=(t||0)+1,n=-128*(r-1),i=[r,0,0,0,n,0,r,0,0,n,0,0,r,0,n,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.saturate=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=2*t/3+1,n=(r-1)*-.5,i=[r,n,n,0,0,n,r,n,0,0,n,n,r,0,0,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.desaturate=function(){this.saturate(-1)},e.prototype.negative=function(t){var e=[0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.sepia=function(t){var e=[.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.technicolor=function(t){var e=[1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.polaroid=function(t){var e=[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.toBGR=function(t){var e=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.kodachrome=function(t){var e=[1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.browni=function(t){var e=[.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.vintage=function(t){var e=[.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.colorTone=function(t,e,r,n,i){t=t||.2,e=e||.15,r=r||16770432,n=n||3375104;var o=(r>>16&255)/255,s=(r>>8&255)/255,a=(255&r)/255,u=(n>>16&255)/255,h=(n>>8&255)/255,l=(255&n)/255,c=[.3,.59,.11,0,0,o,s,a,t,0,u,h,l,e,0,o-u,s-h,a-l,0,0];this._loadMatrix(c,i)},e.prototype.night=function(t,e){t=t||.1;var r=[t*-2,-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.predator=function(t,e){var r=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.lsd=function(t){var e=[2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.reset=function(){var t=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(t,!1)},a(e,[{key:"matrix",get:function(){return this.uniforms.m},set:function(t){this.uniforms.m=t}},{key:"alpha",get:function(){return this.uniforms.uAlpha},set:function(t){this.uniforms.uAlpha=t}}]),e}(h.Filter));r.default=l,l.prototype.grayscale=l.prototype.greyscale},{"../../core":64,path:22}],149:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n'))}return s(e,t),e}(u.Filter));r.default=h},{"../../core":64,path:22}],151:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./fxaa/FXAAFilter");Object.defineProperty(r,"FXAAFilter",{enumerable:!0,get:function(){return n(i).default}});var o=t("./noise/NoiseFilter");Object.defineProperty(r,"NoiseFilter",{enumerable:!0,get:function(){return n(o).default}});var s=t("./displacement/DisplacementFilter");Object.defineProperty(r,"DisplacementFilter",{enumerable:!0,get:function(){return n(s).default}});var a=t("./blur/BlurFilter");Object.defineProperty(r,"BlurFilter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./blur/BlurXFilter");Object.defineProperty(r,"BlurXFilter",{enumerable:!0,get:function(){return n(u).default}});var h=t("./blur/BlurYFilter");Object.defineProperty(r,"BlurYFilter",{enumerable:!0,get:function(){return n(h).default}});var l=t("./colormatrix/ColorMatrixFilter");Object.defineProperty(r,"ColorMatrixFilter",{enumerable:!0,get:function(){return n(l).default}});var c=t("./void/VoidFilter");Object.defineProperty(r,"VoidFilter",{enumerable:!0,get:function(){return n(c).default}})},{"./blur/BlurFilter":142,"./blur/BlurXFilter":143,"./blur/BlurYFilter":144,"./colormatrix/ColorMatrixFilter":148,"./displacement/DisplacementFilter":149,"./fxaa/FXAAFilter":150,"./noise/NoiseFilter":152,"./void/VoidFilter":153}],152:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:.5,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Math.random();i(this,e);var s=o(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n"));return s.noise=r,s.seed=n,s}return s(e,t),a(e,[{key:"noise",get:function(){return this.uniforms.uNoise},set:function(t){this.uniforms.uNoise=t}},{key:"seed",get:function(){return this.uniforms.uSeed},set:function(t){this.uniforms.uSeed=t}}]),e}(h.Filter));r.default=l},{"../../core":64,path:22}],153:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../core"),u=n(a),h=(t("path"),function(t){function e(){i(this,e);var r=o(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"));return r.glShaderKey="void",r}return s(e,t),e}(u.Filter));r.default=h},{"../../core":64,path:22}],154:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:1;this.removeEvents(),this.interactionDOMElement=t,this.resolution=e,this.addEvents()},e.prototype.addEvents=function(){this.interactionDOMElement&&(l.ticker.shared.add(this.update,this,l.UPDATE_PRIORITY.INTERACTION),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="none",this.interactionDOMElement.style["-ms-touch-action"]="none"):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]="none"),this.supportsPointerEvents?(window.document.addEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("pointerover",this.onPointerOver,!0),window.addEventListener("pointercancel",this.onPointerCancel,!0),window.addEventListener("pointerup",this.onPointerUp,!0)):(window.document.addEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onPointerOver,!0),window.addEventListener("mouseup",this.onPointerUp,!0)),this.supportsTouchEvents&&(this.interactionDOMElement.addEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.addEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.addEventListener("touchmove",this.onPointerMove,!0)),this.eventsAdded=!0)},e.prototype.removeEvents=function(){this.interactionDOMElement&&(l.ticker.shared.remove(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="",this.interactionDOMElement.style["-ms-touch-action"]=""):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]=""),this.supportsPointerEvents?(window.document.removeEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("pointerover",this.onPointerOver,!0),window.removeEventListener("pointercancel",this.onPointerCancel,!0),window.removeEventListener("pointerup",this.onPointerUp,!0)):(window.document.removeEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onPointerOver,!0),window.removeEventListener("mouseup",this.onPointerUp,!0)),this.supportsTouchEvents&&(this.interactionDOMElement.removeEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.removeEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onPointerMove,!0)),this.interactionDOMElement=null,this.eventsAdded=!1)},e.prototype.update=function(t){if(this._deltaTime+=t,!(this._deltaTime=0;h--){var l=u[h],c=this.processInteractive(t,l,r,n,a);if(c){if(!l.parent)continue;a=!1,c&&(t.target&&(n=!1),s=!0)}}return i&&(n&&!t.target&&(e.hitArea?(e.worldTransform.applyInverse(o,this._tempPoint),e.hitArea.contains(this._tempPoint.x,this._tempPoint.y)&&(s=!0)):e.containsPoint&&e.containsPoint(o)&&(s=!0)),e.interactive&&(s&&!t.target&&(t.target=e),r&&r(t,e,!!s))),s},e.prototype.onPointerDown=function(t){if(!this.supportsTouchEvents||"touch"!==t.pointerType){var e=this.normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&t.preventDefault();for(var r=e.length,n=0;n1&&(l=1);var c=Math.sqrt(n*n+i*i),d=this._texture.height/2;n/=c,i/=c,n*=d,i*=d,o[h]=u.x+n,o[h+1]=u.y+i,o[h+2]=u.x-n,o[h+3]=u.y-i,e=u}},e.prototype.updateTransform=function(){this.autoUpdate&&this.refreshVertices(),this.containerUpdateTransform()},e}(u.default);r.default=h},{"./Mesh":165}],169:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var s=t("../../core"),a=i(s),u=t("../Mesh"),h=n(u),l=function(){function t(e){o(this,t),this.renderer=e}return t.prototype.render=function(t){var e=this.renderer,r=e.context,n=t.worldTransform,i=e.resolution;e.roundPixels?r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i|0,n.ty*i|0):r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),e.setBlendMode(t.blendMode),t.drawMode===h.default.DRAW_MODES.TRIANGLE_MESH?this._renderTriangleMesh(t):this._renderTriangles(t)},t.prototype._renderTriangleMesh=function(t){for(var e=t.vertices.length/2,r=0;r0){var S=t.canvasPadding/t.worldTransform.a,O=t.canvasPadding/t.worldTransform.d,P=(_+b+x)/3,M=(T+w+E)/3,C=_-P,R=T-M,A=Math.sqrt(C*C+R*R);_=P+C/A*(A+S),T=M+R/A*(A+O),C=b-P,R=w-M,A=Math.sqrt(C*C+R*R),b=P+C/A*(A+S),w=M+R/A*(A+O),C=x-P,R=E-M,A=Math.sqrt(C*C+R*R),x=P+C/A*(A+S),E=M+R/A*(A+O)}i.save(),i.beginPath(),i.moveTo(_,T),i.lineTo(b,w),i.lineTo(x,E),i.closePath(),i.clip();var I=d*y+v*p+f*g-y*p-v*f-d*g,D=_*y+v*x+b*g-y*x-v*b-_*g,L=d*b+_*p+f*x-b*p-_*f-d*x,N=d*y*x+v*b*p+_*f*g-_*y*p-v*f*x-d*b*g,F=T*y+v*E+w*g-y*E-v*w-T*g,B=d*w+T*p+f*E-w*p-T*f-d*E,k=d*y*E+v*w*p+T*f*g-T*y*p-v*f*E-d*w*g;i.transform(D/I,F/I,L/I,B/I,N/I,k/I),i.drawImage(h,0,0,l*u.resolution,c*u.resolution,0,0,l,c),i.restore()}},t.prototype.renderMeshFlat=function(t){var e=this.renderer.context,r=t.vertices,n=r.length/2;e.beginPath();for(var i=1;i0&&void 0!==arguments[0]?arguments[0]:1500,n=arguments[1],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16384;i(this,e);var a=o(this,t.call(this)),u=16384;return s>u&&(s=u),s>r&&(s=r),a._properties=[!1,!0,!1,!1,!1],a._maxSize=r,a._batchSize=s,a._glBuffers={},a._bufferToUpdate=0,a.interactiveChildren=!1,a.blendMode=h.BLEND_MODES.NORMAL,a.roundPixels=!0,a.baseTexture=null,a.setProperties(n),a._tint=0,a.tintRgb=new Float32Array(4),a.tint=16777215,a}return s(e,t),e.prototype.setProperties=function(t){t&&(this._properties[0]="scale"in t?!!t.scale:this._properties[0],this._properties[1]="position"in t?!!t.position:this._properties[1],this._properties[2]="rotation"in t?!!t.rotation:this._properties[2],this._properties[3]="uvs"in t?!!t.uvs:this._properties[3],this._properties[4]="alpha"in t?!!t.alpha:this._properties[4])},e.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},e.prototype.renderWebGL=function(t){var e=this;this.visible&&!(this.worldAlpha<=0)&&this.children.length&&this.renderable&&(this.baseTexture||(this.baseTexture=this.children[0]._texture.baseTexture,this.baseTexture.hasLoaded||this.baseTexture.once("update",function(){return e.onChildrenChange(0)})),t.setObjectRenderer(t.plugins.particle),t.plugins.particle.render(this))},e.prototype.onChildrenChange=function(t){var e=Math.floor(t/this._batchSize);er&&(o=r);var s=t._glBuffers[i.CONTEXT_UID];s||(s=t._glBuffers[i.CONTEXT_UID]=this.generateBuffers(t));var a=e[0]._texture.baseTexture;this.renderer.setBlendMode(h.utils.correctBlendMode(t.blendMode,a.premultipliedAlpha));var u=i.gl,l=t.worldTransform.copy(this.tempMatrix);l.prepend(i._activeRenderTarget.projectionMatrix),this.shader.uniforms.projectionMatrix=l.toArray(!0),this.shader.uniforms.uColor=h.utils.premultiplyRgba(t.tintRgb,t.worldAlpha,this.shader.uniforms.uColor,a.premultipliedAlpha),this.shader.uniforms.uSampler=i.bindTexture(a);for(var c=0,d=0;cn&&(f=n);var p=s[d];p.uploadDynamic(e,c,f),t._bufferToUpdate===d&&(p.uploadStatic(e,c,f),t._bufferToUpdate=d+1),i.bindVao(p.vao),p.vao.draw(u.TRIANGLES,6*f)}}},e.prototype.generateBuffers=function(t){for(var e=this.renderer.gl,r=[],n=t._maxSize,i=t._batchSize,o=t._properties,s=0;s0?1:-1})},{}],178:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}var i=t("object-assign"),o=n(i);Object.assign||(Object.assign=o.default)},{"object-assign":5}],179:[function(t,e,r){"use strict";t("./Object.assign"),t("./requestAnimationFrame"),t("./Math.sign"),window.ArrayBuffer||(window.ArrayBuffer=Array),window.Float32Array||(window.Float32Array=Array),window.Uint32Array||(window.Uint32Array=Array),window.Uint16Array||(window.Uint16Array=Array)},{"./Math.sign":177,"./Object.assign":178,"./requestAnimationFrame":180}],180:[function(t,e,r){(function(t){"use strict";var e=16;Date.now&&Date.prototype.getTime||(Date.now=function(){return(new Date).getTime()}),t.performance&&t.performance.now||!function(){var e=Date.now();t.performance||(t.performance={}),t.performance.now=function(){return Date.now()-e}}();for(var r=Date.now(),n=["ms","moz","webkit","o"],i=0;i=0;n--)this.add(t.children[n]);return this},t.prototype.destroy=function(){this.ticking&&g.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null,this.limiter=null,this.uploadHookHelper=null},t}();r.default=m},{"../core":64,"./limiters/CountLimiter":184}],182:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function u(t,e){if(e instanceof l.BaseTexture){var r=e.source,n=0===r.width?t.canvas.width:Math.min(t.canvas.width,r.width),i=0===r.height?t.canvas.height:Math.min(t.canvas.height,r.height);return t.ctx.drawImage(r,0,0,n,i,0,0,t.canvas.width,t.canvas.height),!0}return!1}r.__esModule=!0;var h=t("../../core"),l=i(h),c=t("../BasePrepare"),d=n(c),f=16,p=function(t){function e(r){o(this,e);var n=s(this,t.call(this,r));return n.uploadHookHelper=n,n.canvas=document.createElement("canvas"),n.canvas.width=f,n.canvas.height=f,n.ctx=n.canvas.getContext("2d"),n.registerUploadHook(u),n}return a(e,t),e.prototype.destroy=function(){t.prototype.destroy.call(this),this.ctx=null,this.canvas=null},e}(d.default);r.default=p,l.CanvasRenderer.registerPlugin("prepare",p)},{"../../core":64,"../BasePrepare":181}],183:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./webgl/WebGLPrepare");Object.defineProperty(r,"webgl",{enumerable:!0,get:function(){return n(i).default}});var o=t("./canvas/CanvasPrepare");Object.defineProperty(r,"canvas",{enumerable:!0,get:function(){return n(o).default}});var s=t("./BasePrepare");Object.defineProperty(r,"BasePrepare",{enumerable:!0,get:function(){return n(s).default}});var a=t("./limiters/CountLimiter");Object.defineProperty(r,"CountLimiter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./limiters/TimeLimiter");Object.defineProperty(r,"TimeLimiter",{enumerable:!0,get:function(){return n(u).default}})},{"./BasePrepare":181,"./canvas/CanvasPrepare":182,"./limiters/CountLimiter":184,"./limiters/TimeLimiter":185,"./webgl/WebGLPrepare":186}],184:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function"); +}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxItemsPerFrame=e,this.itemsLeft=0}return t.prototype.beginFrame=function(){this.itemsLeft=this.maxItemsPerFrame},t.prototype.allowedToUpload=function(){return this.itemsLeft-- >0},t}();r.default=i},{}],185:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxMilliseconds=e,this.frameStart=0}return t.prototype.beginFrame=function(){this.frameStart=Date.now()},t.prototype.allowedToUpload=function(){return Date.now()-this.frameStart 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],2:[function(require,module,exports){ +'use strict'; + +module.exports = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, size), + maxZ = zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, size); + earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and size of the data bounding box +function zOrder(x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; + +},{}],3:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @api private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {Mixed} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @api public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @api public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Boolean} exists Only check if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Add a one-time listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Remove the listeners of a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {Mixed} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn + && (!once || listeners.once) + && (!context || listeners.context === context) + ) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {String|Symbol} [event] The event name. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],4:[function(require,module,exports){ +/** + * isMobile.js v0.4.1 + * + * A simple library to detect Apple phones and tablets, + * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone), + * and any kind of seven inch device, via user agent sniffing. + * + * @author: Kai Mallea (kmallea@gmail.com) + * + * @license: http://creativecommons.org/publicdomain/zero/1.0/ + */ +(function (global) { + + var apple_phone = /iPhone/i, + apple_ipod = /iPod/i, + apple_tablet = /iPad/i, + android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i, // Match 'Android' AND 'Mobile' + android_tablet = /Android/i, + amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i, + amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i, + windows_phone = /Windows Phone/i, + windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i, // Match 'Windows' AND 'ARM' + other_blackberry = /BlackBerry/i, + other_blackberry_10 = /BB10/i, + other_opera = /Opera Mini/i, + other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i, + other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i, // Match 'Firefox' AND 'Mobile' + seven_inch = new RegExp( + '(?:' + // Non-capturing group + + 'Nexus 7' + // Nexus 7 + + '|' + // OR + + 'BNTV250' + // B&N Nook Tablet 7 inch + + '|' + // OR + + 'Kindle Fire' + // Kindle Fire + + '|' + // OR + + 'Silk' + // Kindle Fire, Silk Accelerated + + '|' + // OR + + 'GT-P1000' + // Galaxy Tab 7 inch + + ')', // End non-capturing group + + 'i'); // Case-insensitive matching + + var match = function(regex, userAgent) { + return regex.test(userAgent); + }; + + var IsMobileClass = function(userAgent) { + var ua = userAgent || navigator.userAgent; + + // Facebook mobile app's integrated browser adds a bunch of strings that + // match everything. Strip it out if it exists. + var tmp = ua.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + // Twitter mobile app's integrated browser on iPad adds a "Twitter for + // iPhone" string. Same probable happens on other tablet platforms. + // This will confuse detection so strip it out if it exists. + tmp = ua.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + this.apple = { + phone: match(apple_phone, ua), + ipod: match(apple_ipod, ua), + tablet: !match(apple_phone, ua) && match(apple_tablet, ua), + device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua) + }; + this.amazon = { + phone: match(amazon_phone, ua), + tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) + }; + this.android = { + phone: match(amazon_phone, ua) || match(android_phone, ua), + tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua) + }; + this.windows = { + phone: match(windows_phone, ua), + tablet: match(windows_tablet, ua), + device: match(windows_phone, ua) || match(windows_tablet, ua) + }; + this.other = { + blackberry: match(other_blackberry, ua), + blackberry10: match(other_blackberry_10, ua), + opera: match(other_opera, ua), + firefox: match(other_firefox, ua), + chrome: match(other_chrome, ua), + device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua) + }; + this.seven_inch = match(seven_inch, ua); + this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch; + + // excludes 'other' devices and ipods, targeting touchscreen phones + this.phone = this.apple.phone || this.android.phone || this.windows.phone; + + // excludes 7 inch devices, classifying as phone or tablet is left to the user + this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet; + + if (typeof window === 'undefined') { + return this; + } + }; + + var instantiate = function() { + var IM = new IsMobileClass(); + IM.Class = IsMobileClass; + return IM; + }; + + if (typeof module !== 'undefined' && module.exports && typeof window === 'undefined') { + //node + module.exports = IsMobileClass; + } else if (typeof module !== 'undefined' && module.exports && typeof window !== 'undefined') { + //browserify + module.exports = instantiate(); + } else if (typeof define === 'function' && define.amd) { + //AMD + define('isMobile', [], global.isMobile = instantiate()); + } else { + global.isMobile = instantiate(); + } + +})(this); + +},{}],5:[function(require,module,exports){ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],6:[function(require,module,exports){ +var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); + +/** + * Helper class to create a webGL buffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ +var Buffer = function(gl, type, data, drawType) +{ + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The WebGL buffer, created upon instantiation + * + * @member {WebGLBuffer} + */ + this.buffer = gl.createBuffer(); + + /** + * The type of the buffer + * + * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} + */ + this.type = type || gl.ARRAY_BUFFER; + + /** + * The draw type of the buffer + * + * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ + this.drawType = drawType || gl.STATIC_DRAW; + + /** + * The data in the buffer, as a typed array + * + * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} + */ + this.data = EMPTY_ARRAY_BUFFER; + + if(data) + { + this.upload(data); + } + + this._updateID = 0; +}; + +/** + * Uploads the buffer to the GPU + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload + * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract + * @param dontBind {Boolean} whether to bind the buffer before uploading it + */ +Buffer.prototype.upload = function(data, offset, dontBind) +{ + // todo - needed? + if(!dontBind) this.bind(); + + var gl = this.gl; + + data = data || this.data; + offset = offset || 0; + + if(this.data.byteLength >= data.byteLength) + { + gl.bufferSubData(this.type, offset, data); + } + else + { + gl.bufferData(this.type, data, this.drawType); + } + + this.data = data; +}; +/** + * Binds the buffer + * + */ +Buffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindBuffer(this.type, this.buffer); +}; + +Buffer.createVertexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); +}; + +Buffer.createIndexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); +}; + +Buffer.create = function(gl, type, data, drawType) +{ + return new Buffer(gl, type, data, drawType); +}; + +/** + * Destroys the buffer + * + */ +Buffer.prototype.destroy = function(){ + this.gl.deleteBuffer(this.buffer); +}; + +module.exports = Buffer; + +},{}],7:[function(require,module,exports){ + +var Texture = require('./GLTexture'); + +/** + * Helper class to create a webGL Framebuffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + */ +var Framebuffer = function(gl, width, height) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The frame buffer + * + * @member {WebGLFramebuffer} + */ + this.framebuffer = gl.createFramebuffer(); + + /** + * The stencil buffer + * + * @member {WebGLRenderbuffer} + */ + this.stencil = null; + + /** + * The stencil buffer + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The width of the drawing area of the buffer + * + * @member {Number} + */ + this.width = width || 100; + /** + * The height of the drawing area of the buffer + * + * @member {Number} + */ + this.height = height || 100; +}; + +/** + * Adds a texture to the frame buffer + * @param texture {PIXI.glCore.GLTexture} + */ +Framebuffer.prototype.enableTexture = function(texture) +{ + var gl = this.gl; + + this.texture = texture || new Texture(gl); + + this.texture.bind(); + + //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + this.bind(); + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); +}; + +/** + * Initialises the stencil buffer + */ +Framebuffer.prototype.enableStencil = function() +{ + if(this.stencil)return; + + var gl = this.gl; + + this.stencil = gl.createRenderbuffer(); + + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + + // TODO.. this is depth AND stencil? + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width , this.height ); + + +}; + +/** + * Erases the drawing area and fills it with a colour + * @param r {Number} the red value of the clearing colour + * @param g {Number} the green value of the clearing colour + * @param b {Number} the blue value of the clearing colour + * @param a {Number} the alpha value of the clearing colour + */ +Framebuffer.prototype.clear = function( r, g, b, a ) +{ + this.bind(); + + var gl = this.gl; + + gl.clearColor(r, g, b, a); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); +}; + +/** + * Binds the frame buffer to the WebGL context + */ +Framebuffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); +}; + +/** + * Unbinds the frame buffer to the WebGL context + */ +Framebuffer.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, null ); +}; +/** + * Resizes the drawing area of the buffer to the given width and height + * @param width {Number} the new width + * @param height {Number} the new height + */ +Framebuffer.prototype.resize = function(width, height) +{ + var gl = this.gl; + + this.width = width; + this.height = height; + + if ( this.texture ) + { + this.texture.uploadData(null, width, height); + } + + if ( this.stencil ) + { + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + } +}; + +/** + * Destroys this buffer + */ +Framebuffer.prototype.destroy = function() +{ + var gl = this.gl; + + //TODO + if(this.texture) + { + this.texture.destroy(); + } + + gl.deleteFramebuffer(this.framebuffer); + + this.gl = null; + + this.stencil = null; + this.texture = null; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createRGBA = function(gl, width, height, data) +{ + var texture = Texture.fromData(gl, null, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + //fbo.enableStencil(); // get this back on soon! + + fbo.unbind(); + + return fbo; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createFloat32 = function(gl, width, height, data) +{ + // create a new texture.. + var texture = new Texture.fromData(gl, data, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +module.exports = Framebuffer; + +},{"./GLTexture":9}],8:[function(require,module,exports){ + +var compileProgram = require('./shader/compileProgram'), + extractAttributes = require('./shader/extractAttributes'), + extractUniforms = require('./shader/extractUniforms'), + setPrecision = require('./shader/setPrecision'), + generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + +/** + * Helper class to create a webGL Shader + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @param precision {precision]} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + */ +var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + if(precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } + + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); + + this.uniformData = extractUniforms(gl, this.program); + + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + +}; +/** + * Uses this shader + */ +Shader.prototype.bind = function() +{ + this.gl.useProgram(this.program); +}; + +/** + * Destroys this shader + * TODO + */ +Shader.prototype.destroy = function() +{ + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + + var gl = this.gl; + gl.deleteProgram(this.program); +}; + + +module.exports = Shader; + +},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18,"./shader/setPrecision":22}],9:[function(require,module,exports){ + +/** + * Helper class to create a WebGL Texture + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL context + * @param width {number} the width of the texture + * @param height {number} the height of the texture + * @param format {number} the pixel format of the texture. defaults to gl.RGBA + * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE + */ +var Texture = function(gl, width, height, format, type) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); + + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; + + + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; + + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; + + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + + +}; + +/** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ +Texture.prototype.upload = function(source) +{ + this.bind(); + + var gl = this.gl; + + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + var newWidth = source.videoWidth || source.width; + var newHeight = source.videoHeight || source.height; + + if(newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } + + // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + +}; + +var FLOATING_POINT_AVAILABLE = false; + +/** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.prototype.uploadData = function(data, width, height) +{ + this.bind(); + + var gl = this.gl; + + + if(data instanceof Float32Array) + { + if(!FLOATING_POINT_AVAILABLE) + { + var ext = gl.getExtension("OES_texture_float"); + + if(ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } + + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } + + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + + if(width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } + + this.width = width; + this.height = height; + + +// texSubImage2D +}; + +/** + * Binds the texture + * @param location + */ +Texture.prototype.bind = function(location) +{ + var gl = this.gl; + + if(location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } + + gl.bindTexture(gl.TEXTURE_2D, this.texture); +}; + +/** + * Unbinds the texture + */ +Texture.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, null); +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.minFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + if(this.mipmap) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.magFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); +}; + +/** + * Enables mipmapping + */ +Texture.prototype.enableMipmap = function() +{ + var gl = this.gl; + + this.bind(); + + this.mipmap = true; + + gl.generateMipmap(gl.TEXTURE_2D); +}; + +/** + * Enables linear filtering + */ +Texture.prototype.enableLinearScaling = function() +{ + this.minFilter(true); + this.magFilter(true); +}; + +/** + * Enables nearest neighbour interpolation + */ +Texture.prototype.enableNearestScaling = function() +{ + this.minFilter(false); + this.magFilter(false); +}; + +/** + * Enables clamping on the texture so WebGL will not repeat it + */ +Texture.prototype.enableWrapClamp = function() +{ + var gl = this.gl; + + this.bind(); + + 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); +}; + +/** + * Enable tiling on the texture + */ +Texture.prototype.enableWrapRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); +}; + +Texture.prototype.enableWrapMirrorRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); +}; + + +/** + * Destroys this texture + */ +Texture.prototype.destroy = function() +{ + var gl = this.gl; + //TODO + gl.deleteTexture(this.texture); +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ +Texture.fromSource = function(gl, source, premultiplyAlpha) +{ + var texture = new Texture(gl); + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); + + return texture; +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.fromData = function(gl, data, width, height) +{ + //console.log(data, width, height); + var texture = new Texture(gl); + texture.uploadData(data, width, height); + + return texture; +}; + + +module.exports = Texture; + +},{}],10:[function(require,module,exports){ + +// state object// +var setVertexAttribArrays = require( './setVertexAttribArrays' ); + +/** + * Helper class to work with WebGL VertexArrayObjects (vaos) + * Only works if WebGL extensions are enabled (they usually are) + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function VertexArrayObject(gl, state) +{ + this.nativeVaoExtension = null; + + if(!VertexArrayObject.FORCE_NATIVE) + { + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + this.nativeState = state; + + if(this.nativeVaoExtension) + { + this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + + var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + // VAO - overwrite the state.. + this.nativeState = { + tempAttribState: new Array(maxAttribs), + attribState: new Array(maxAttribs) + }; + } + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of attributes + * + * @member {Array} + */ + this.attributes = []; + + /** + * @member {PIXI.glCore.GLBuffer} + */ + this.indexBuffer = null; + + /** + * A boolean flag + * + * @member {Boolean} + */ + this.dirty = false; +} + +VertexArrayObject.prototype.constructor = VertexArrayObject; +module.exports = VertexArrayObject; + +/** +* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) +* If you find on older devices that things have gone a bit weird then set this to true. +*/ +/** + * Lets the VAO know if you should use the WebGL extension or the native methods. + * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) + * If you find on older devices that things have gone a bit weird then set this to true. + * @static + * @property {Boolean} FORCE_NATIVE + */ +VertexArrayObject.FORCE_NATIVE = false; + +/** + * Binds the buffer + */ +VertexArrayObject.prototype.bind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + + if(this.dirty) + { + this.dirty = false; + this.activate(); + } + } + else + { + + this.activate(); + } + + return this; +}; + +/** + * Unbinds the buffer + */ +VertexArrayObject.prototype.unbind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + return this; +}; + +/** + * Uses this vao + */ +VertexArrayObject.prototype.activate = function() +{ + + var gl = this.gl; + var lastBuffer = null; + + for (var i = 0; i < this.attributes.length; i++) + { + var attrib = this.attributes[i]; + + if(lastBuffer !== attrib.buffer) + { + attrib.buffer.bind(); + lastBuffer = attrib.buffer; + } + + gl.vertexAttribPointer(attrib.attribute.location, + attrib.attribute.size, + attrib.type || gl.FLOAT, + attrib.normalized || false, + attrib.stride || 0, + attrib.start || 0); + } + + setVertexAttribArrays(gl, this.attributes, this.nativeState); + + if(this.indexBuffer) + { + this.indexBuffer.bind(); + } + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + * @param attribute {*} + * @param type {String} + * @param normalized {Boolean} + * @param stride {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start) +{ + this.attributes.push({ + buffer: buffer, + attribute: attribute, + + location: attribute.location, + type: type || this.gl.FLOAT, + normalized: normalized || false, + stride: stride || 0, + start: start || 0 + }); + + this.dirty = true; + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + */ +VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) +{ + this.indexBuffer = buffer; + + this.dirty = true; + + return this; +}; + +/** + * Unbinds this vao and disables it + */ +VertexArrayObject.prototype.clear = function() +{ + // var gl = this.gl; + + // TODO - should this function unbind after clear? + // for now, no but lets see what happens in the real world! + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + } + + this.attributes.length = 0; + this.indexBuffer = null; + + return this; +}; + +/** + * @param type {Number} + * @param size {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.draw = function(type, size, start) +{ + var gl = this.gl; + + if(this.indexBuffer) + { + gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + } + else + { + // TODO need a better way to calculate size.. + gl.drawArrays(type, start, size || this.getSize()); + } + + return this; +}; + +/** + * Destroy this vao + */ +VertexArrayObject.prototype.destroy = function() +{ + // lose references + this.gl = null; + this.indexBuffer = null; + this.attributes = null; + this.nativeState = null; + + if(this.nativeVao) + { + this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); + } + + this.nativeVaoExtension = null; + this.nativeVao = null; +}; + +VertexArrayObject.prototype.getSize = function() +{ + var attrib = this.attributes[0]; + return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); +}; + +},{"./setVertexAttribArrays":13}],11:[function(require,module,exports){ + +/** + * Helper class to create a webGL Context + * + * @class + * @memberof PIXI.glCore + * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from + * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * @return {WebGLRenderingContext} the WebGL context + */ +var createContext = function(canvas, options) +{ + var gl = canvas.getContext('webgl', options) || + canvas.getContext('experimental-webgl', options); + + if (!gl) + { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + return gl; +}; + +module.exports = createContext; + +},{}],12:[function(require,module,exports){ +var gl = { + createContext: require('./createContext'), + setVertexAttribArrays: require('./setVertexAttribArrays'), + GLBuffer: require('./GLBuffer'), + GLFramebuffer: require('./GLFramebuffer'), + GLShader: require('./GLShader'), + GLTexture: require('./GLTexture'), + VertexArrayObject: require('./VertexArrayObject'), + shader: require('./shader') +}; + +// Export for Node-compatible environments +if (typeof module !== 'undefined' && module.exports) +{ + // Export the module + module.exports = gl; +} + +// Add to the browser window pixi.gl +if (typeof window !== 'undefined') +{ + // add the window object + window.PIXI = window.PIXI || {}; + window.PIXI.glCore = gl; +} + +},{"./GLBuffer":6,"./GLFramebuffer":7,"./GLShader":8,"./GLTexture":9,"./VertexArrayObject":10,"./createContext":11,"./setVertexAttribArrays":13,"./shader":19}],13:[function(require,module,exports){ +// var GL_MAP = {}; + +/** + * @param gl {WebGLRenderingContext} The current WebGL context + * @param attribs {*} + * @param state {*} + */ +var setVertexAttribArrays = function (gl, attribs, state) +{ + var i; + if(state) + { + var tempAttribState = state.tempAttribState, + attribState = state.attribState; + + for (i = 0; i < tempAttribState.length; i++) + { + tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + tempAttribState[attribs[i].attribute.location] = true; + } + + for (i = 0; i < attribState.length; i++) + { + if (attribState[i] !== tempAttribState[i]) + { + attribState[i] = tempAttribState[i]; + + if (state.attribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } + + } + else + { + for (i = 0; i < attribs.length; i++) + { + var attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); + } + } +}; + +module.exports = setVertexAttribArrays; + +},{}],14:[function(require,module,exports){ + +/** + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations + * @return {WebGLProgram} the shader program + */ +var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +{ + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + + var program = gl.createProgram(); + + gl.attachShader(program, glVertShader); + gl.attachShader(program, glFragShader); + + // optionally, set the attributes manually for the program rather than letting WebGL decide.. + if(attributeLocations) + { + for(var i in attributeLocations) + { + gl.bindAttribLocation(program, attributeLocations[i], i); + } + } + + + gl.linkProgram(program); + + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + console.error('Pixi.js Error: Could not initialize shader.'); + console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); + console.error('gl.getError()', gl.getError()); + + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') + { + console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + + gl.deleteProgram(program); + program = null; + } + + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + + return program; +}; + +/** + * @private + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @return {WebGLShader} the shader + */ +var compileShader = function (gl, type, src) +{ + var shader = gl.createShader(type); + + gl.shaderSource(shader, src); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + console.log(gl.getShaderInfoLog(shader)); + return null; + } + + return shader; +}; + +module.exports = compileProgram; + +},{}],15:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} Type of value + * @param size {Number} + */ +var defaultValue = function(type, size) +{ + switch (type) + { + case 'float': + return 0; + + case 'vec2': + return new Float32Array(2 * size); + + case 'vec3': + return new Float32Array(3 * size); + + case 'vec4': + return new Float32Array(4 * size); + + case 'int': + case 'sampler2D': + return 0; + + case 'ivec2': + return new Int32Array(2 * size); + + case 'ivec3': + return new Int32Array(3 * size); + + case 'ivec4': + return new Int32Array(4 * size); + + case 'bool': + return false; + + case 'bvec2': + + return booleanArray( 2 * size); + + case 'bvec3': + return booleanArray(3 * size); + + case 'bvec4': + return booleanArray(4 * size); + + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } +}; + +var booleanArray = function(size) +{ + var array = new Array(size); + + for (var i = 0; i < array.length; i++) + { + array[i] = false; + } + + return array; +}; + +module.exports = defaultValue; + +},{}],16:[function(require,module,exports){ + +var mapType = require('./mapType'); +var mapSize = require('./mapSize'); + +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the attributes from + * @return attributes {Object} + */ +var extractAttributes = function(gl, program) +{ + var attributes = {}; + + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + + for (var i = 0; i < totalAttributes; i++) + { + var attribData = gl.getActiveAttrib(program, i); + var type = mapType(gl, attribData.type); + + attributes[attribData.name] = { + type:type, + size:mapSize(type), + location:gl.getAttribLocation(program, attribData.name), + //TODO - make an attribute object + pointer: pointer + }; + } + + return attributes; +}; + +var pointer = function(type, normalized, stride, start){ + // console.log(this.location) + gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +}; + +module.exports = extractAttributes; + +},{"./mapSize":20,"./mapType":21}],17:[function(require,module,exports){ +var mapType = require('./mapType'); +var defaultValue = require('./defaultValue'); + +/** + * Extracts the uniforms + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the uniforms from + * @return uniforms {Object} + */ +var extractUniforms = function(gl, program) +{ + var uniforms = {}; + + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + + for (var i = 0; i < totalUniforms; i++) + { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]/, ""); + var type = mapType(gl, uniformData.type ); + + uniforms[name] = { + type:type, + size:uniformData.size, + location:gl.getUniformLocation(program, name), + value:defaultValue(type, uniformData.size) + }; + } + + return uniforms; +}; + +module.exports = extractUniforms; + +},{"./defaultValue":15,"./mapType":21}],18:[function(require,module,exports){ +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param uniforms {Array} @mat ? + * @return attributes {Object} + */ +var generateUniformAccessObject = function(gl, uniformData) +{ + // this is the object we will be sending back. + // an object hierachy will be created for structs + var uniforms = {data:{}}; + + uniforms.gl = gl; + + var uniformKeys= Object.keys(uniformData); + + for (var i = 0; i < uniformKeys.length; i++) + { + var fullName = uniformKeys[i]; + + var nameTokens = fullName.split('.'); + var name = nameTokens[nameTokens.length - 1]; + + + var uniformGroup = getUniformGroup(nameTokens, uniforms); + + var uniform = uniformData[fullName]; + uniformGroup.data[name] = uniform; + + uniformGroup.gl = gl; + + Object.defineProperty(uniformGroup, name, { + get: generateGetter(name), + set: generateSetter(name, uniform) + }); + } + + return uniforms; +}; + +var generateGetter = function(name) +{ + var template = getterTemplate.replace('%%', name); + return new Function(template); // jshint ignore:line +}; + +var generateSetter = function(name, uniform) +{ + var template = setterTemplate.replace(/%%/g, name); + var setTemplate; + + if(uniform.size === 1) + { + setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; + } + else + { + setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; + } + + if(setTemplate) + { + template += "\nthis.gl." + setTemplate + ";"; + } + + return new Function('value', template); // jshint ignore:line +}; + +var getUniformGroup = function(nameTokens, uniform) +{ + var cur = uniform; + + for (var i = 0; i < nameTokens.length - 1; i++) + { + var o = cur[nameTokens[i]] || {data:{}}; + cur[nameTokens[i]] = o; + cur = o; + } + + return cur; +}; + +var getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +var setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;' +].join('\n'); + + +var GLSL_TO_SINGLE_SETTERS = { + + 'float': 'uniform1f(location, value)', + + 'vec2': 'uniform2f(location, value[0], value[1])', + 'vec3': 'uniform3f(location, value[0], value[1], value[2])', + 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', + + 'int': 'uniform1i(location, value)', + 'ivec2': 'uniform2i(location, value[0], value[1])', + 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', + 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'bool': 'uniform1i(location, value)', + 'bvec2': 'uniform2i(location, value[0], value[1])', + 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', + 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', + + 'mat2': 'uniformMatrix2fv(location, false, value)', + 'mat3': 'uniformMatrix3fv(location, false, value)', + 'mat4': 'uniformMatrix4fv(location, false, value)', + + 'sampler2D':'uniform1i(location, value)' +}; + +var GLSL_TO_ARRAY_SETTERS = { + + 'float': 'uniform1fv(location, value)', + + 'vec2': 'uniform2fv(location, value)', + 'vec3': 'uniform3fv(location, value)', + 'vec4': 'uniform4fv(location, value)', + + 'int': 'uniform1iv(location, value)', + 'ivec2': 'uniform2iv(location, value)', + 'ivec3': 'uniform3iv(location, value)', + 'ivec4': 'uniform4iv(location, value)', + + 'bool': 'uniform1iv(location, value)', + 'bvec2': 'uniform2iv(location, value)', + 'bvec3': 'uniform3iv(location, value)', + 'bvec4': 'uniform4iv(location, value)', + + 'sampler2D':'uniform1iv(location, value)' +}; + +module.exports = generateUniformAccessObject; + +},{}],19:[function(require,module,exports){ +module.exports = { + compileProgram: require('./compileProgram'), + defaultValue: require('./defaultValue'), + extractAttributes: require('./extractAttributes'), + extractUniforms: require('./extractUniforms'), + generateUniformAccessObject: require('./generateUniformAccessObject'), + setPrecision: require('./setPrecision'), + mapSize: require('./mapSize'), + mapType: require('./mapType') +}; +},{"./compileProgram":14,"./defaultValue":15,"./extractAttributes":16,"./extractUniforms":17,"./generateUniformAccessObject":18,"./mapSize":20,"./mapType":21,"./setPrecision":22}],20:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} + * @return {Number} + */ +var mapSize = function(type) +{ + return GLSL_TO_SIZE[type]; +}; + + +var GLSL_TO_SIZE = { + 'float': 1, + 'vec2': 2, + 'vec3': 3, + 'vec4': 4, + + 'int': 1, + 'ivec2': 2, + 'ivec3': 3, + 'ivec4': 4, + + 'bool': 1, + 'bvec2': 2, + 'bvec3': 3, + 'bvec4': 4, + + 'mat2': 4, + 'mat3': 9, + 'mat4': 16, + + 'sampler2D': 1 +}; + +module.exports = mapSize; + +},{}],21:[function(require,module,exports){ + + +var mapSize = function(gl, type) +{ + if(!GL_TABLE) + { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + + GL_TABLE = {}; + + for(var i = 0; i < typeNames.length; ++i) + { + var tn = typeNames[i]; + GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + } + } + + return GL_TABLE[type]; +}; + +var GL_TABLE = null; + +var GL_TO_GLSL_TYPES = { + 'FLOAT': 'float', + 'FLOAT_VEC2': 'vec2', + 'FLOAT_VEC3': 'vec3', + 'FLOAT_VEC4': 'vec4', + + 'INT': 'int', + 'INT_VEC2': 'ivec2', + 'INT_VEC3': 'ivec3', + 'INT_VEC4': 'ivec4', + + 'BOOL': 'bool', + 'BOOL_VEC2': 'bvec2', + 'BOOL_VEC3': 'bvec3', + 'BOOL_VEC4': 'bvec4', + + 'FLOAT_MAT2': 'mat2', + 'FLOAT_MAT3': 'mat3', + 'FLOAT_MAT4': 'mat4', + + 'SAMPLER_2D': 'sampler2D' +}; + +module.exports = mapSize; + +},{}],22:[function(require,module,exports){ +/** + * Sets the float precision on the shader. If the precision is already present this function will do nothing + * @param {string} src the shader source + * @param {string} precision The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + * + * @return {string} modified shader source + */ +var setPrecision = function(src, precision) +{ + if(src.substring(0, 9) !== 'precision') + { + return 'precision ' + precision + ' float;\n' + src; + } + + return src; +}; + +module.exports = setPrecision; + +},{}],23:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) + +},{"_process":24}],24:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],25:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],26:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],27:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],28:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":26,"./encode":27}],29:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":30,"punycode":25,"querystring":28}],30:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],31:[function(require,module,exports){ +'use strict' + +/** + * Remove a range of items from an array + * + * @function removeItems + * @param {Array<*>} arr The target array + * @param {number} startIdx The index to begin removing from (inclusive) + * @param {number} removeCount How many items to remove + */ +module.exports = function removeItems(arr, startIdx, removeCount) +{ + var i, length = arr.length + + if (startIdx >= length || removeCount === 0) { + return + } + + removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount) + + var len = length - removeCount + + for (i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount] + } + + arr.length = len +} + +},{}],32:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _async = require('./async'); + +var async = _interopRequireWildcard(_async); + +var _Resource = require('./Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// some constants +var MAX_PROGRESS = 100; +var rgxExtractUrlHash = /(#[\w-]+)?$/; + +/** + * Manages the state and loading of multiple resources to load. + * + * @class + */ + +var Loader = function () { + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader() { + var _this = this; + + var baseUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var concurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; + + _classCallCheck(this, Loader); + + /** + * The base url for all resources loaded by this loader. + * + * @member {string} + */ + this.baseUrl = baseUrl; + + /** + * The progress percent of the loader going through the queue. + * + * @member {number} + */ + this.progress = 0; + + /** + * Loading state of the loader, true if it is currently loading resources. + * + * @member {boolean} + */ + this.loading = false; + + /** + * A querystring to append to every URL added to the loader. + * + * This should be a valid query string *without* the question-mark (`?`). The loader will + * also *not* escape values for you. Make sure to escape your parameters with + * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. + * + * @example + * const loader = new Loader(); + * + * loader.defaultQueryString = 'user=me&password=secret'; + * + * // This will request 'image.png?user=me&password=secret' + * loader.add('image.png').load(); + * + * loader.reset(); + * + * // This will request 'image.png?v=1&user=me&password=secret' + * loader.add('iamge.png?v=1').load(); + */ + this.defaultQueryString = ''; + + /** + * The middleware to run before loading each resource. + * + * @member {function[]} + */ + this._beforeMiddleware = []; + + /** + * The middleware to run after loading each resource. + * + * @member {function[]} + */ + this._afterMiddleware = []; + + /** + * The tracks the resources we are currently completing parsing for. + * + * @member {Resource[]} + */ + this._resourcesParsing = []; + + /** + * The `_loadResource` function bound with this object context. + * + * @private + * @member {function} + * @param {Resource} r - The resource to load + * @param {Function} d - The dequeue function + * @return {undefined} + */ + this._boundLoadResource = function (r, d) { + return _this._loadResource(r, d); + }; + + /** + * The resources waiting to be loaded. + * + * @private + * @member {Resource[]} + */ + this._queue = async.queue(this._boundLoadResource, concurrency); + + this._queue.pause(); + + /** + * All the resources for this loader keyed by name. + * + * @member {object} + */ + this.resources = {}; + + /** + * Dispatched once per loaded or errored resource. + * + * The callback looks like {@link Loader.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once per errored resource. + * + * The callback looks like {@link Loader.OnErrorSignal}. + * + * @member {Signal} + */ + this.onError = new _miniSignals2.default(); + + /** + * Dispatched once per loaded resource. + * + * The callback looks like {@link Loader.OnLoadSignal}. + * + * @member {Signal} + */ + this.onLoad = new _miniSignals2.default(); + + /** + * Dispatched when the loader begins to process the queue. + * + * The callback looks like {@link Loader.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched when the queued resources all load. + * + * The callback looks like {@link Loader.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * When the progress changes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnProgressSignal + * @param {Loader} loader - The loader the progress is advancing on. + * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance. + */ + + /** + * When an error occurrs the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnErrorSignal + * @param {Loader} loader - The loader the error happened in. + * @param {Resource} resource - The resource that caused the error. + */ + + /** + * When a load completes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnLoadSignal + * @param {Loader} loader - The loader that laoded the resource. + * @param {Resource} resource - The resource that has completed loading. + */ + + /** + * When the loader starts loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnStartSignal + * @param {Loader} loader - The loader that has started loading resources. + */ + + /** + * When the loader completes loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnCompleteSignal + * @param {Loader} loader - The loader that has finished loading resources. + */ + } + + /** + * Adds a resource (or multiple resources) to the loader queue. + * + * This function can take a wide variety of different parameters. The only thing that is always + * required the url to load. All the following will work: + * + * ```js + * loader + * // normal param syntax + * .add('key', 'http://...', function () {}) + * .add('http://...', function () {}) + * .add('http://...') + * + * // object syntax + * .add({ + * name: 'key2', + * url: 'http://...' + * }, function () {}) + * .add({ + * url: 'http://...' + * }, function () {}) + * .add({ + * name: 'key3', + * url: 'http://...' + * onComplete: function () {} + * }) + * .add({ + * url: 'https://...', + * onComplete: function () {}, + * crossOrigin: true + * }) + * + * // you can also pass an array of objects or urls or both + * .add([ + * { name: 'key4', url: 'http://...', onComplete: function () {} }, + * { url: 'http://...', onComplete: function () {} }, + * 'http://...' + * ]) + * + * // and you can use both params and options + * .add('key', 'http://...', { crossOrigin: true }, function () {}) + * .add('http://...', { crossOrigin: true }, function () {}); + * ``` + * + * @param {string} [name] - The name of the resource to load, if not passed the url is used. + * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @param {object} [options] - The options for the load. + * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should + * the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @param {function} [cb] - Function to call when this specific resource completes loading. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.add = function add(name, url, options, cb) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + + return this; + } + + // if an object is passed instead of params + if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') { + cb = url || name.callback || name.onComplete; + options = name; + url = name.url; + name = name.name || name.key || name.url; + } + + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + cb = options; + options = url; + url = name; + } + + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + cb = options; + options = null; + } + + // if loading already you can only add resources that have a parent. + if (this.loading && (!options || !options.parentResource)) { + throw new Error('Cannot add resources while the loader is running.'); + } + + // check if resource already exists. + if (this.resources[name]) { + throw new Error('Resource named "' + name + '" already exists.'); + } + + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + + // create the store the resource + this.resources[name] = new _Resource2.default(name, url, options); + + if (typeof cb === 'function') { + this.resources[name].onAfterMiddleware.once(cb); + } + + // if actively loading, make sure to adjust progress chunks for that parent and its children + if (this.loading) { + var parent = options.parentResource; + var incompleteChildren = []; + + for (var _i = 0; _i < parent.children.length; ++_i) { + if (!parent.children[_i].isComplete) { + incompleteChildren.push(parent.children[_i]); + } + } + + var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent + var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child + + parent.children.push(this.resources[name]); + parent.progressChunk = eachChunk; + + for (var _i2 = 0; _i2 < incompleteChildren.length; ++_i2) { + incompleteChildren[_i2].progressChunk = eachChunk; + } + + this.resources[name].progressChunk = eachChunk; + } + + // add the resource to the queue + this._queue.push(this.resources[name]); + + return this; + }; + + /** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * + * @method before + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.pre = function pre(fn) { + this._beforeMiddleware.push(fn); + + return this; + }; + + /** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * + * @alias use + * @method after + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.use = function use(fn) { + this._afterMiddleware.push(fn); + + return this; + }; + + /** + * Resets the queue of the loader to prepare for a new load. + * + * @return {Loader} Returns itself. + */ + + + Loader.prototype.reset = function reset() { + this.progress = 0; + this.loading = false; + + this._queue.kill(); + this._queue.pause(); + + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + + if (res._onLoadBinding) { + res._onLoadBinding.detach(); + } + + if (res.isLoading) { + res.abort(); + } + } + + this.resources = {}; + + return this; + }; + + /** + * Starts loading the queued resources. + * + * @param {function} [cb] - Optional callback that will be bound to the `complete` event. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.load = function load(cb) { + // register complete callback if they pass one + if (typeof cb === 'function') { + this.onComplete.once(cb); + } + + // if the queue has already started we are done here + if (this.loading) { + return this; + } + + // distribute progress chunks + var chunk = 100 / this._queue._tasks.length; + + for (var i = 0; i < this._queue._tasks.length; ++i) { + this._queue._tasks[i].data.progressChunk = chunk; + } + + // update loading state + this.loading = true; + + // notify of start + this.onStart.dispatch(this); + + // start loading + this._queue.resume(); + + return this; + }; + + /** + * Prepares a url for usage based on the configuration of this object + * + * @private + * @param {string} url - The url to prepare. + * @return {string} The prepared url. + */ + + + Loader.prototype._prepareUrl = function _prepareUrl(url) { + var parsedUrl = (0, _parseUri2.default)(url, { strictMode: true }); + var result = void 0; + + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { + result = url; + } + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + else if (this.baseUrl.length && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 && url.charAt(0) !== '/') { + result = this.baseUrl + '/' + url; + } else { + result = this.baseUrl + url; + } + + // if we need to add a default querystring, there is a bit more work + if (this.defaultQueryString) { + var hash = rgxExtractUrlHash.exec(result)[0]; + + result = result.substr(0, result.length - hash.length); + + if (result.indexOf('?') !== -1) { + result += '&' + this.defaultQueryString; + } else { + result += '?' + this.defaultQueryString; + } + + result += hash; + } + + return result; + }; + + /** + * Loads a single resource. + * + * @private + * @param {Resource} resource - The resource to load. + * @param {function} dequeue - The function to call when we need to dequeue this item. + */ + + + Loader.prototype._loadResource = function _loadResource(resource, dequeue) { + var _this2 = this; + + resource._dequeue = dequeue; + + // run before middleware + async.eachSeries(this._beforeMiddleware, function (fn, next) { + fn.call(_this2, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, function () { + if (resource.isComplete) { + _this2._onLoad(resource); + } else { + resource._onLoadBinding = resource.onComplete.once(_this2._onLoad, _this2); + resource.load(); + } + }, true); + }; + + /** + * Called once each resource has loaded. + * + * @private + */ + + + Loader.prototype._onComplete = function _onComplete() { + this.loading = false; + + this.onComplete.dispatch(this, this.resources); + }; + + /** + * Called each time a resources is loaded. + * + * @private + * @param {Resource} resource - The resource that was loaded + */ + + + Loader.prototype._onLoad = function _onLoad(resource) { + var _this3 = this; + + resource._onLoadBinding = null; + + // remove this resource from the async queue, and add it to our list of resources that are being parsed + this._resourcesParsing.push(resource); + resource._dequeue(); + + // run all the after middleware for this resource + async.eachSeries(this._afterMiddleware, function (fn, next) { + fn.call(_this3, resource, next); + }, function () { + resource.onAfterMiddleware.dispatch(resource); + + _this3.progress += resource.progressChunk; + _this3.onProgress.dispatch(_this3, resource); + + if (resource.error) { + _this3.onError.dispatch(resource.error, _this3, resource); + } else { + _this3.onLoad.dispatch(_this3, resource); + } + + _this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1); + + // do completion check + if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) { + _this3.progress = MAX_PROGRESS; + _this3._onComplete(); + } + }, true); + }; + + return Loader; +}(); + +exports.default = Loader; + +},{"./Resource":33,"./async":34,"mini-signals":38,"parse-uri":39}],33:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// tests is CORS is supported in XHR, if not we need to use XDR +var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest())); +var tempAnchor = null; + +// some status constants +var STATUS_NONE = 0; +var STATUS_OK = 200; +var STATUS_EMPTY = 204; +var STATUS_IE_BUG_EMPTY = 1223; +var STATUS_TYPE_OK = 2; + +// noop +function _noop() {} /* empty */ + +/** + * Manages the state and loading of a resource and all child resources. + * + * @class + */ + +var Resource = function () { + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. + */ + Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) { + setExtMap(Resource._loadTypeMap, extname, loadType); + }; + + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ + + + Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); + }; + + /** + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass + * an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @param {string|string[]} [options.metadata.mimeType] - The mime type to use for the source element of a video/audio + * elment. If the urls are an array, you can pass this as an array as well where each index is the mime type to + * use for the corresponding url index. + */ + + + function Resource(name, url, options) { + _classCallCheck(this, Resource); + + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + + options = options || {}; + + /** + * The state flags of this resource. + * + * @member {number} + */ + this._flags = 0; + + // set data url flag, needs to be set early for some _determineX checks to work. + this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); + + /** + * The name of this resource. + * + * @member {string} + * @readonly + */ + this.name = name; + + /** + * The url used to load this resource. + * + * @member {string} + * @readonly + */ + this.url = url; + + /** + * The extension used to load this resource. + * + * @member {string} + * @readonly + */ + this.extension = this._getExtension(); + + /** + * The data that was loaded by the resource. + * + * @member {any} + */ + this.data = null; + + /** + * Is this request cross-origin? If unset, determined automatically. + * + * @member {string} + */ + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + + /** + * The method of loading to use for this resource. + * + * @member {Resource.LOAD_TYPE} + */ + this.loadType = options.loadType || this._determineLoadType(); + + /** + * The type used to load the resource via XHR. If unset, determined automatically. + * + * @member {string} + */ + this.xhrType = options.xhrType; + + /** + * Extra info for middleware, and controlling specifics about how the resource loads. + * + * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + * Meaning it will modify it as it sees fit. + * + * @member {object} + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources + * to. + */ + this.metadata = options.metadata || {}; + + /** + * The error that occurred while loading (if any). + * + * @member {Error} + * @readonly + */ + this.error = null; + + /** + * The XHR object that was used to load this resource. This is only set + * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * + * @member {XMLHttpRequest} + * @readonly + */ + this.xhr = null; + + /** + * The child resources this resource owns. + * + * @member {Resource[]} + * @readonly + */ + this.children = []; + + /** + * The resource type. + * + * @member {Resource.TYPE} + * @readonly + */ + this.type = Resource.TYPE.UNKNOWN; + + /** + * The progress chunk owned by this resource. + * + * @member {number} + * @readonly + */ + this.progressChunk = 0; + + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * + * @private + * @member {function} + */ + this._dequeue = _noop; + + /** + * Used a storage place for the on load binding used privately by the loader. + * + * @private + * @member {function} + */ + this._onLoadBinding = null; + + /** + * The `complete` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundComplete = this.complete.bind(this); + + /** + * The `_onError` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnError = this._onError.bind(this); + + /** + * The `_onProgress` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnProgress = this._onProgress.bind(this); + + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + this._boundXdrOnTimeout = this._xdrOnTimeout.bind(this); + + /** + * Dispatched when the resource beings to load. + * + * The callback looks like {@link Resource.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched each time progress of this resource load updates. + * Not all resources types and loader systems can support this event + * so sometimes it may not be available. If the resource + * is being loaded on a modern browser, using XHR, and the remote server + * properly sets Content-Length headers, then this will be available. + * + * The callback looks like {@link Resource.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once this resource has loaded, if there was an error it will + * be in the `error` property. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * Dispatched after this resource has had all the *after* middleware run on it. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onAfterMiddleware = new _miniSignals2.default(); + + /** + * When the resource starts to load. + * + * @memberof Resource + * @callback OnStartSignal + * @param {Resource} resource - The resource that the event happened on. + */ + + /** + * When the resource reports loading progress. + * + * @memberof Resource + * @callback OnProgressSignal + * @param {Resource} resource - The resource that the event happened on. + * @param {number} percentage - The progress of the load in the range [0, 1]. + */ + + /** + * When the resource finishes loading. + * + * @memberof Resource + * @callback OnCompleteSignal + * @param {Resource} resource - The resource that the event happened on. + */ + } + + /** + * Stores whether or not this url is a data url. + * + * @member {boolean} + * @readonly + */ + + + /** + * Marks the resource as complete. + * + */ + Resource.prototype.complete = function complete() { + // TODO: Clean this up in a wrapper or something...gross.... + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + + this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true); + this._setFlag(Resource.STATUS_FLAGS.LOADING, false); + + this.onComplete.dispatch(this); + }; + + /** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ + + + Resource.prototype.abort = function abort(message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + + // store error + this.error = new Error(message); + + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } else if (this.xdr) { + this.xdr.abort(); + } else if (this.data) { + // single source + if (this.data.src) { + this.data.src = Resource.EMPTY_GIF; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + + // done now. + this.complete(); + }; + + /** + * Kicks off loading of this resource. This method is asynchronous. + * + * @param {function} [cb] - Optional callback to call once the resource is loaded. + */ + + + Resource.prototype.load = function load(cb) { + var _this = this; + + if (this.isLoading) { + return; + } + + if (this.isComplete) { + if (cb) { + setTimeout(function () { + return cb(_this); + }, 1); + } + + return; + } else if (cb) { + this.onComplete.once(cb); + } + + this._setFlag(Resource.STATUS_FLAGS.LOADING, true); + + this.onStart.dispatch(this); + + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + + switch (this.loadType) { + case Resource.LOAD_TYPE.IMAGE: + this.type = Resource.TYPE.IMAGE; + this._loadElement('image'); + break; + + case Resource.LOAD_TYPE.AUDIO: + this.type = Resource.TYPE.AUDIO; + this._loadSourceElement('audio'); + break; + + case Resource.LOAD_TYPE.VIDEO: + this.type = Resource.TYPE.VIDEO; + this._loadSourceElement('video'); + break; + + case Resource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } else { + this._loadXhr(); + } + break; + } + }; + + /** + * Checks if the flag is set. + * + * @private + * @param {number} flag - The flag to check. + * @return {boolean} True if the flag is set. + */ + + + Resource.prototype._hasFlag = function _hasFlag(flag) { + return !!(this._flags & flag); + }; + + /** + * (Un)Sets the flag. + * + * @private + * @param {number} flag - The flag to (un)set. + * @param {boolean} value - Whether to set or (un)set the flag. + */ + + + Resource.prototype._setFlag = function _setFlag(flag, value) { + this._flags = value ? this._flags | flag : this._flags & ~flag; + }; + + /** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadElement = function _loadElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'image' && typeof window.Image !== 'undefined') { + this.data = new Image(); + } else { + this.data = document.createElement(type); + } + + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + }; + + /** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadSourceElement = function _loadSourceElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'audio' && typeof window.Audio !== 'undefined') { + this.data = new Audio(); + } else { + this.data = document.createElement(type); + } + + if (this.data === null) { + this.abort('Unsupported element: ' + type); + + return; + } + + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } else if (Array.isArray(this.url)) { + var mimeTypes = this.metadata.mimeType; + + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes)); + } + } else { + var _mimeTypes = this.metadata.mimeType; + + this.data.appendChild(this._createSource(type, this.url, Array.isArray(_mimeTypes) ? _mimeTypes[0] : _mimeTypes)); + } + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + + this.data.load(); + }; + + /** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ + + + Resource.prototype._loadXhr = function _loadXhr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xhr = this.xhr = new XMLHttpRequest(); + + // set the request type and url + xhr.open('GET', this.url, true); + + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; + } else { + xhr.responseType = this.xhrType; + } + + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + + xhr.send(); + }; + + /** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ + + + Resource.prototype._loadXdr = function _loadXdr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xdr = this.xhr = new XDomainRequest(); + + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = 5000; + + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXdrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + + xdr.open('GET', this.url, true); + + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { + return xdr.send(); + }, 1); + }; + + /** + * Creates a source used in loading via an element. + * + * @private + * @param {string} type - The element type (video or audio). + * @param {string} url - The source URL to load from. + * @param {string} [mime] - The mime type of the video + * @return {HTMLSourceElement} The source element. + */ + + + Resource.prototype._createSource = function _createSource(type, url, mime) { + if (!mime) { + mime = type + '/' + this._getExtension(url); + } + + var source = document.createElement('source'); + + source.src = url; + source.type = mime; + + return source; + }; + + /** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ + + + Resource.prototype._onError = function _onError(event) { + this.abort('Failed to load element using: ' + event.target.nodeName); + }; + + /** + * Called if a load progress event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ + + + Resource.prototype._onProgress = function _onProgress(event) { + if (event && event.lengthComputable) { + this.onProgress.dispatch(this, event.loaded / event.total); + } + }; + + /** + * Called if an error event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestErrorEvent|Event} event - Error event. + */ + + + Resource.prototype._xhrOnError = function _xhrOnError() { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"'); + }; + + /** + * Called if an abort event fires for xhr. + * + * @private + * @param {XMLHttpRequestAbortEvent} event - Abort Event + */ + + + Resource.prototype._xhrOnAbort = function _xhrOnAbort() { + this.abort(reqType(this.xhr) + ' Request was aborted by the user.'); + }; + + /** + * Called if a timeout event fires for xdr. + * + * @private + * @param {Event} event - Timeout event. + */ + + + Resource.prototype._xdrOnTimeout = function _xdrOnTimeout() { + this.abort(reqType(this.xhr) + ' Request timed out.'); + }; + + /** + * Called when data successfully loads from an xhr/xdr request. + * + * @private + * @param {XMLHttpRequestLoadEvent|Event} event - Load event + */ + + + Resource.prototype._xhrOnLoad = function _xhrOnLoad() { + var xhr = this.xhr; + var text = ''; + var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200. + + // responseText is accessible only if responseType is '' or 'text' and on older browsers + if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') { + text = xhr.responseText; + } + + // status can be 0 when using the `file://` protocol so we also check if a response is set. + // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request. + if (status === STATUS_NONE && text.length > 0) { + status = STATUS_OK; + } + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + else if (status === STATUS_IE_BUG_EMPTY) { + status = STATUS_EMPTY; + } + + var statusType = status / 100 | 0; + + if (statusType === STATUS_TYPE_OK) { + // if text, just return it + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { + this.data = text; + this.type = Resource.TYPE.TEXT; + } + // if json, parse into json object + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(text); + this.type = Resource.TYPE.JSON; + } catch (e) { + this.abort('Error trying to parse loaded json: ' + e); + + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (window.DOMParser) { + var domparser = new DOMParser(); + + this.data = domparser.parseFromString(text, 'text/xml'); + } else { + var div = document.createElement('div'); + + div.innerHTML = text; + + this.data = div; + } + + this.type = Resource.TYPE.XML; + } catch (e) { + this.abort('Error trying to parse loaded xml: ' + e); + + return; + } + } + // other types just return the response + else { + this.data = xhr.response || text; + } + } else { + this.abort('[' + xhr.status + '] ' + xhr.statusText + ': ' + xhr.responseURL); + + return; + } + + this.complete(); + }; + + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * + * @private + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ + + + Resource.prototype._determineCrossOrigin = function _determineCrossOrigin(url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = (0, _parseUri2.default)(tempAnchor.href, { strictMode: true }); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + var protocol = url.protocol ? url.protocol + ':' : ''; + + // if cross origin + if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; + }; + + /** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. + */ + + + Resource.prototype._determineXhrType = function _determineXhrType() { + return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT; + }; + + /** + * Determines the loadType of a resource based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.LOAD_TYPE} The loadType to use. + */ + + + Resource.prototype._determineLoadType = function _determineLoadType() { + return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR; + }; + + /** + * Extracts the extension (sans '.') of the file being loaded by the resource. + * + * @private + * @return {string} The extension. + */ + + + Resource.prototype._getExtension = function _getExtension() { + var url = this.url; + var ext = ''; + + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } else { + var queryStart = url.indexOf('?'); + var hashStart = url.indexOf('#'); + var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length); + + url = url.substring(0, index); + ext = url.substring(url.lastIndexOf('.') + 1); + } + + return ext.toLowerCase(); + }; + + /** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * + * @private + * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. + * @return {string} The mime type to use. + */ + + + Resource.prototype._getMimeFromXhrType = function _getMimeFromXhrType(type) { + switch (type) { + case Resource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + + case Resource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + + case Resource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + + case Resource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + + case Resource.XHR_RESPONSE_TYPE.DEFAULT: + case Resource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + + } + }; + + _createClass(Resource, [{ + key: 'isDataUrl', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL); + } + + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isComplete', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE); + } + + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isLoading', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.LOADING); + } + }]); + + return Resource; +}(); + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ + + +exports.default = Resource; +Resource.STATUS_FLAGS = { + NONE: 0, + DATA_URL: 1 << 0, + COMPLETE: 1 << 1, + LOADING: 1 << 2 +}; + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ +Resource.TYPE = { + UNKNOWN: 0, + JSON: 1, + XML: 2, + IMAGE: 3, + AUDIO: 4, + VIDEO: 5, + TEXT: 6 +}; + +/** + * The types of loading a resource can use. + * + * @static + * @readonly + * @enum {number} + */ +Resource.LOAD_TYPE = { + /** Uses XMLHttpRequest to load the resource. */ + XHR: 1, + /** Uses an `Image` object to load the resource. */ + IMAGE: 2, + /** Uses an `Audio` object to load the resource. */ + AUDIO: 3, + /** Uses a `Video` object to load the resource. */ + VIDEO: 4 +}; + +/** + * The XHR ready states, used internally. + * + * @static + * @readonly + * @enum {string} + */ +Resource.XHR_RESPONSE_TYPE = { + /** string */ + DEFAULT: 'text', + /** ArrayBuffer */ + BUFFER: 'arraybuffer', + /** Blob */ + BLOB: 'blob', + /** Document */ + DOCUMENT: 'document', + /** Object */ + JSON: 'json', + /** String */ + TEXT: 'text' +}; + +Resource._loadTypeMap = { + // images + gif: Resource.LOAD_TYPE.IMAGE, + png: Resource.LOAD_TYPE.IMAGE, + bmp: Resource.LOAD_TYPE.IMAGE, + jpg: Resource.LOAD_TYPE.IMAGE, + jpeg: Resource.LOAD_TYPE.IMAGE, + tif: Resource.LOAD_TYPE.IMAGE, + tiff: Resource.LOAD_TYPE.IMAGE, + webp: Resource.LOAD_TYPE.IMAGE, + tga: Resource.LOAD_TYPE.IMAGE, + svg: Resource.LOAD_TYPE.IMAGE, + 'svg+xml': Resource.LOAD_TYPE.IMAGE, // for SVG data urls + + // audio + mp3: Resource.LOAD_TYPE.AUDIO, + ogg: Resource.LOAD_TYPE.AUDIO, + wav: Resource.LOAD_TYPE.AUDIO, + + // videos + mp4: Resource.LOAD_TYPE.VIDEO, + webm: Resource.LOAD_TYPE.VIDEO +}; + +Resource._xhrTypeMap = { + // xml + xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. + // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, + // this should probably be fine. + tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // images + gif: Resource.XHR_RESPONSE_TYPE.BLOB, + png: Resource.XHR_RESPONSE_TYPE.BLOB, + bmp: Resource.XHR_RESPONSE_TYPE.BLOB, + jpg: Resource.XHR_RESPONSE_TYPE.BLOB, + jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, + tif: Resource.XHR_RESPONSE_TYPE.BLOB, + tiff: Resource.XHR_RESPONSE_TYPE.BLOB, + webp: Resource.XHR_RESPONSE_TYPE.BLOB, + tga: Resource.XHR_RESPONSE_TYPE.BLOB, + + // json + json: Resource.XHR_RESPONSE_TYPE.JSON, + + // text + text: Resource.XHR_RESPONSE_TYPE.TEXT, + txt: Resource.XHR_RESPONSE_TYPE.TEXT, + + // fonts + ttf: Resource.XHR_RESPONSE_TYPE.BUFFER, + otf: Resource.XHR_RESPONSE_TYPE.BUFFER +}; + +// We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif +Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; + +/** + * Quick helper to set a value on one of the extension maps. Ensures there is no + * dot at the start of the extension. + * + * @ignore + * @param {object} map - The map to set on. + * @param {string} extname - The extension (or key) to set. + * @param {number} val - The value to set. + */ +function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + + if (!extname) { + return; + } + + map[extname] = val; +} + +/** + * Quick helper to get string xhr type. + * + * @ignore + * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. + * @return {string} The type. + */ +function reqType(xhr) { + return xhr.toString().replace('object ', ''); +} + +},{"mini-signals":38,"parse-uri":39}],34:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.eachSeries = eachSeries; +exports.queue = queue; +/** + * Smaller version of the async library constructs. + * + */ +function _noop() {} /* empty */ + +/** + * Iterates an array in series. + * + * @param {Array.<*>} array - Array to iterate. + * @param {function} iterator - Function to call for each element. + * @param {function} callback - Function to call when done, or on error. + * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1. + */ +function eachSeries(array, iterator, callback, deferNext) { + var i = 0; + var len = array.length; + + (function next(err) { + if (err || i === len) { + if (callback) { + callback(err); + } + + return; + } + + if (deferNext) { + setTimeout(function () { + iterator(array[i++], next); + }, 1); + } else { + iterator(array[i++], next); + } + })(); +} + +/** + * Ensures a function is only called once. + * + * @param {function} fn - The function to wrap. + * @return {function} The wrapping function. + */ +function onlyOnce(fn) { + return function onceWrapper() { + if (fn === null) { + throw new Error('Callback was already called.'); + } + + var callFn = fn; + + fn = null; + callFn.apply(this, arguments); + }; +} + +/** + * Async queue implementation, + * + * @param {function} worker - The worker function to call for each task. + * @param {number} concurrency - How many workers to run in parrallel. + * @return {*} The async queue object. + */ +function queue(worker, concurrency) { + if (concurrency == null) { + // eslint-disable-line no-eq-null,eqeqeq + concurrency = 1; + } else if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + + var workers = 0; + var q = { + _tasks: [], + concurrency: concurrency, + saturated: _noop, + unsaturated: _noop, + buffer: concurrency / 4, + empty: _noop, + drain: _noop, + error: _noop, + started: false, + paused: false, + push: function push(data, callback) { + _insert(data, false, callback); + }, + kill: function kill() { + workers = 0; + q.drain = _noop; + q.started = false; + q._tasks = []; + }, + unshift: function unshift(data, callback) { + _insert(data, true, callback); + }, + process: function process() { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var task = q._tasks.shift(); + + if (q._tasks.length === 0) { + q.empty(); + } + + workers += 1; + + if (workers === q.concurrency) { + q.saturated(); + } + + worker(task.data, onlyOnce(_next(task))); + } + }, + length: function length() { + return q._tasks.length; + }, + running: function running() { + return workers; + }, + idle: function idle() { + return q._tasks.length + workers === 0; + }, + pause: function pause() { + if (q.paused === true) { + return; + } + + q.paused = true; + }, + resume: function resume() { + if (q.paused === false) { + return; + } + + q.paused = false; + + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= q.concurrency; w++) { + q.process(); + } + } + }; + + function _insert(data, insertAtFront, callback) { + if (callback != null && typeof callback !== 'function') { + // eslint-disable-line no-eq-null,eqeqeq + throw new Error('task callback must be a function'); + } + + q.started = true; + + if (data == null && q.idle()) { + // eslint-disable-line no-eq-null,eqeqeq + // call drain immediately if there are no tasks + setTimeout(function () { + return q.drain(); + }, 1); + + return; + } + + var item = { + data: data, + callback: typeof callback === 'function' ? callback : _noop + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + setTimeout(function () { + return q.process(); + }, 1); + } + + function _next(task) { + return function next() { + workers -= 1; + + task.callback.apply(task, arguments); + + if (arguments[0] != null) { + // eslint-disable-line no-eq-null,eqeqeq + q.error(arguments[0], task.data); + } + + if (workers <= q.concurrency - q.buffer) { + q.unsaturated(); + } + + if (q.idle()) { + q.drain(); + } + + q.process(); + }; + } + + return q; +} + +},{}],35:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.encodeBinary = encodeBinary; +var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +function encodeBinary(input) { + var output = ''; + var inx = 0; + + while (inx < input.length) { + // Fill byte buffer array + var bytebuffer = [0, 0, 0]; + var encodedCharIndexes = [0, 0, 0, 0]; + + for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } else { + bytebuffer[jnx] = 0; + } + } + + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4; + + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6; + + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + + // Determine whether padding happened, and adjust accordingly + var paddingBytes = inx - (input.length - 1); + + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + + default: + break; // No padding - proceed + } + + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) { + output += _keyStr.charAt(encodedCharIndexes[_jnx]); + } + } + + return output; +} + +},{}],36:[function(require,module,exports){ +'use strict'; + +// import Loader from './Loader'; +// import Resource from './Resource'; +// import * as async from './async'; +// import * as b64 from './b64'; + +/* eslint-disable no-undef */ + +var Loader = require('./Loader').default; +var Resource = require('./Resource').default; +var async = require('./async'); +var b64 = require('./b64'); + +Loader.Resource = Resource; +Loader.async = async; +Loader.base64 = b64; + +// export manually, and also as default +module.exports = Loader; +// export default Loader; +module.exports.default = Loader; + +},{"./Loader":32,"./Resource":33,"./async":34,"./b64":35}],37:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +exports.blobMiddlewareFactory = blobMiddlewareFactory; + +var _Resource = require('../../Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +var _b = require('../../b64'); + +var _b2 = _interopRequireDefault(_b); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Url = window.URL || window.webkitURL; + +// a middleware for transforming XHR loaded Blobs into more useful objects +function blobMiddlewareFactory() { + return function blobMiddleware(resource, next) { + if (!resource.data) { + next(); + + return; + } + + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === _Resource2.default.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!window.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = 'data:' + type + ';base64,' + _b2.default.encodeBinary(resource.xhr.responseText); + + resource.type = _Resource2.default.TYPE.IMAGE; + + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + + next(); + }; + + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var _ret = function () { + var src = Url.createObjectURL(resource.data); + + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src; + + resource.type = _Resource2.default.TYPE.IMAGE; + + // cleanup the no longer used blob after the image loads + // TODO: Is this correct? Will the image be invalid after revoking? + resource.data.onload = function () { + Url.revokeObjectURL(src); + resource.data.onload = null; + + next(); + }; + + // next will be called on load. + return { + v: void 0 + }; + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + } + + next(); + }; +} + +},{"../../Resource":33,"../../b64":35}],38:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + +var MiniSignalBinding = (function () { + function MiniSignalBinding(fn, once, thisArg) { + if (once === undefined) once = false; + + _classCallCheck(this, MiniSignalBinding); + + this._fn = fn; + this._once = once; + this._thisArg = thisArg; + this._next = this._prev = this._owner = null; + } + + _createClass(MiniSignalBinding, [{ + key: 'detach', + value: function detach() { + if (this._owner === null) return false; + this._owner.detach(this); + return true; + } + }]); + + return MiniSignalBinding; +})(); + +function _addMiniSignalBinding(self, node) { + if (!self._head) { + self._head = node; + self._tail = node; + } else { + self._tail._next = node; + node._prev = self._tail; + self._tail = node; + } + + node._owner = self; + + return node; +} + +var MiniSignal = (function () { + function MiniSignal() { + _classCallCheck(this, MiniSignal); + + this._head = this._tail = undefined; + } + + _createClass(MiniSignal, [{ + key: 'handlers', + value: function handlers() { + var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; + + var node = this._head; + + if (exists) return !!node; + + var ee = []; + + while (node) { + ee.push(node); + node = node._next; + } + + return ee; + } + }, { + key: 'has', + value: function has(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.'); + } + + return node._owner === this; + } + }, { + key: 'dispatch', + value: function dispatch() { + var node = this._head; + + if (!node) return false; + + while (node) { + if (node._once) this.detach(node); + node._fn.apply(node._thisArg, arguments); + node = node._next; + } + + return true; + } + }, { + key: 'add', + value: function add(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#add(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg)); + } + }, { + key: 'once', + value: function once(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#once(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg)); + } + }, { + key: 'detach', + value: function detach(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.'); + } + if (node._owner !== this) return this; + + if (node._prev) node._prev._next = node._next; + if (node._next) node._next._prev = node._prev; + + if (node === this._head) { + this._head = node._next; + if (node._next === null) { + this._tail = null; + } + } else if (node === this._tail) { + this._tail = node._prev; + this._tail._next = null; + } + + node._owner = null; + return this; + } + }, { + key: 'detachAll', + value: function detachAll() { + var node = this._head; + if (!node) return this; + + this._head = this._tail = null; + + while (node) { + node._owner = null; + node = node._next; + } + return this; + } + }]); + + return MiniSignal; +})(); + +MiniSignal.MiniSignalBinding = MiniSignalBinding; + +exports['default'] = MiniSignal; +module.exports = exports['default']; + +},{}],39:[function(require,module,exports){ +'use strict' + +module.exports = function parseURI (str, opts) { + opts = opts || {} + + var o = { + key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], + q: { + name: 'queryKey', + parser: /(?:^|&)([^&=]*)=?([^&]*)/g + }, + parser: { + strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, + loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ + } + } + + var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str) + var uri = {} + var i = 14 + + while (i--) uri[o.key[i]] = m[i] || '' + + uri[o.q.name] = {} + uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { + if ($1) uri[o.q.name][$1] = $2 + }) + + return uri +} + +},{}],40:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +var _accessibleTarget = require('./accessibleTarget'); + +var _accessibleTarget2 = _interopRequireDefault(_accessibleTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// add some extra variables to the container.. +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _accessibleTarget2.default); + +var KEY_CODE_TAB = 9; + +var DIV_TOUCH_SIZE = 100; +var DIV_TOUCH_POS_X = 0; +var DIV_TOUCH_POS_Y = 0; +var DIV_TOUCH_ZINDEX = 2; + +var DIV_HOOK_SIZE = 1; +var DIV_HOOK_POS_X = -1000; +var DIV_HOOK_POS_Y = -1000; +var DIV_HOOK_ZINDEX = 2; + +/** + * The Accessibility manager recreates the ability to tab and have content read by screen + * readers. This is very important as it can possibly help people with disabilities access pixi + * content. + * + * Much like interaction any DisplayObject can be made accessible. This manager will map the + * events as if the mouse was being used, minimizing the effort required to implement. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.accessibility + * + * @class + * @memberof PIXI.accessibility + */ + +var AccessibilityManager = function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + _classCallCheck(this, AccessibilityManager); + + if ((_ismobilejs2.default.tablet || _ismobilejs2.default.phone) && !navigator.isCocoonJS) { + this.createTouchHook(); + } + + // first we create a div that will sit over the PixiJS element. This is where the div overlays will go. + var div = document.createElement('div'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + 'px'; + div.style.left = DIV_TOUCH_POS_Y + 'px'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + + /** + * This is the dom element that will sit over the PixiJS element. This is where the div overlays will go. + * + * @type {HTMLElement} + * @private + */ + this.div = div; + + /** + * A simple pool for storing divs. + * + * @type {*} + * @private + */ + this.pool = []; + + /** + * This is a tick used to check if an object is no longer being rendered. + * + * @type {Number} + * @private + */ + this.renderId = 0; + + /** + * Setting this to true will visually show the divs. + * + * @type {boolean} + */ + this.debug = false; + + /** + * The renderer this accessibility manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * The array of currently active accessible items. + * + * @member {Array<*>} + * @private + */ + this.children = []; + + /** + * pre-bind the functions + * + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + + /** + * stores the state of the manager. If there are no accessible objects or the mouse is moving, this will be false. + * + * @member {Array<*>} + * @private + */ + this.isActive = false; + this.isMobileAccessabillity = false; + + // let listen for tab.. once pressed we can fire up and show the accessibility layer + window.addEventListener('keydown', this._onKeyDown, false); + } + + /** + * Creates the touch hooks. + * + */ + + + AccessibilityManager.prototype.createTouchHook = function createTouchHook() { + var _this = this; + + var hookDiv = document.createElement('button'); + + hookDiv.style.width = DIV_HOOK_SIZE + 'px'; + hookDiv.style.height = DIV_HOOK_SIZE + 'px'; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + 'px'; + hookDiv.style.left = DIV_HOOK_POS_Y + 'px'; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX; + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'HOOK DIV'; + + hookDiv.addEventListener('focus', function () { + _this.isMobileAccessabillity = true; + _this.activate(); + document.body.removeChild(hookDiv); + }); + + document.body.appendChild(hookDiv); + }; + + /** + * Activating will cause the Accessibility layer to be shown. This is called when a user + * preses the tab key. + * + * @private + */ + + + AccessibilityManager.prototype.activate = function activate() { + if (this.isActive) { + return; + } + + this.isActive = true; + + window.document.addEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown, false); + + this.renderer.on('postrender', this.update, this); + + if (this.renderer.view.parentNode) { + this.renderer.view.parentNode.appendChild(this.div); + } + }; + + /** + * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves + * the mouse. + * + * @private + */ + + + AccessibilityManager.prototype.deactivate = function deactivate() { + if (!this.isActive || this.isMobileAccessabillity) { + return; + } + + this.isActive = false; + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.addEventListener('keydown', this._onKeyDown, false); + + this.renderer.off('postrender', this.update); + + if (this.div.parentNode) { + this.div.parentNode.removeChild(this.div); + } + }; + + /** + * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. + * + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + + + AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects(displayObject) { + if (!displayObject.visible) { + return; + } + + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + + displayObject.renderId = this.renderId; + } + + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + this.updateAccessibleObjects(children[i]); + } + }; + + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * + * @private + */ + + + AccessibilityManager.prototype.update = function update() { + if (!this.renderer.renderingToScreen) { + return; + } + + // update children... + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + + var rect = this.renderer.view.getBoundingClientRect(); + var sx = rect.width / this.renderer.width; + var sy = rect.height / this.renderer.height; + + var div = this.div; + + div.style.left = rect.left + 'px'; + div.style.top = rect.top + 'px'; + div.style.width = this.renderer.width + 'px'; + div.style.height = this.renderer.height + 'px'; + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + + core.utils.removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + + i--; + + if (this.children.length === 0) { + this.deactivate(); + } + } else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + + if (child.hitArea) { + div.style.left = (wt.tx + hitArea.x * wt.a) * sx + 'px'; + div.style.top = (wt.ty + hitArea.y * wt.d) * sy + 'px'; + + div.style.width = hitArea.width * wt.a * sx + 'px'; + div.style.height = hitArea.height * wt.d * sy + 'px'; + } else { + hitArea = child.getBounds(); + + this.capHitArea(hitArea); + + div.style.left = hitArea.x * sx + 'px'; + div.style.top = hitArea.y * sy + 'px'; + + div.style.width = hitArea.width * sx + 'px'; + div.style.height = hitArea.height * sy + 'px'; + } + } + } + + // increment the render id.. + this.renderId++; + }; + + /** + * TODO: docs. + * + * @param {Rectangle} hitArea - TODO docs + */ + + + AccessibilityManager.prototype.capHitArea = function capHitArea(hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + + if (hitArea.x + hitArea.width > this.renderer.width) { + hitArea.width = this.renderer.width - hitArea.x; + } + + if (hitArea.y + hitArea.height > this.renderer.height) { + hitArea.height = this.renderer.height - hitArea.y; + } + }; + + /** + * Adds a DisplayObject to the accessibility manager + * + * @private + * @param {DisplayObject} displayObject - The child to make accessible. + */ + + + AccessibilityManager.prototype.addChild = function addChild(displayObject) { + // this.activate(); + + var div = this.pool.pop(); + + if (!div) { + div = document.createElement('button'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + div.style.borderStyle = 'none'; + + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + + if (displayObject.accessibleTitle) { + div.title = displayObject.accessibleTitle; + } else if (!displayObject.accessibleTitle && !displayObject.accessibleHint) { + div.title = 'displayObject ' + this.tabIndex; + } + + if (displayObject.accessibleHint) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + + // + + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + + /** + * Maps the div button press to pixi's InteractionManager (click) + * + * @private + * @param {MouseEvent} e - The click event. + */ + + + AccessibilityManager.prototype._onClick = function _onClick(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixi's InteractionManager (mouseover) + * + * @private + * @param {FocusEvent} e - The focus event. + */ + + + AccessibilityManager.prototype._onFocus = function _onFocus(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixi's InteractionManager (mouseout) + * + * @private + * @param {FocusEvent} e - The focusout event. + */ + + + AccessibilityManager.prototype._onFocusOut = function _onFocusOut(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); + }; + + /** + * Is called when a key is pressed + * + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + + + AccessibilityManager.prototype._onKeyDown = function _onKeyDown(e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + + this.activate(); + }; + + /** + * Is called when the mouse moves across the renderer element + * + * @private + */ + + + AccessibilityManager.prototype._onMouseMove = function _onMouseMove() { + this.deactivate(); + }; + + /** + * Destroys the accessibility manager + * + */ + + + AccessibilityManager.prototype.destroy = function destroy() { + this.div = null; + + for (var i = 0; i < this.children.length; i++) { + this.children[i].div = null; + } + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.removeEventListener('keydown', this._onKeyDown); + + this.pool = null; + this.children = null; + this.renderer = null; + }; + + return AccessibilityManager; +}(); + +exports.default = AccessibilityManager; + + +core.WebGLRenderer.registerPlugin('accessibility', AccessibilityManager); +core.CanvasRenderer.registerPlugin('accessibility', AccessibilityManager); + +},{"../core":65,"./accessibleTarget":41,"ismobilejs":4}],41:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Default property values of accessible objects + * used by {@link PIXI.accessibility.AccessibilityManager}. + * + * @function accessibleTarget + * @memberof PIXI.accessibility + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibility.accessibleTarget + * ); + */ +exports.default = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * + * @member {boolean} + */ + accessible: false, + + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * + * @member {string} + */ + accessibleTitle: null, + + /** + * Sets the aria-label attribute of the shadow div + * + * @member {string} + */ + accessibleHint: null, + + /** + * @todo Needs docs. + */ + tabIndex: 0, + + /** + * @todo Needs docs. + */ + _accessibleActive: false, + + /** + * @todo Needs docs. + */ + _accessibleDiv: false +}; + +},{}],42:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _accessibleTarget = require('./accessibleTarget'); + +Object.defineProperty(exports, 'accessibleTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_accessibleTarget).default; + } +}); + +var _AccessibilityManager = require('./AccessibilityManager'); + +Object.defineProperty(exports, 'AccessibilityManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AccessibilityManager).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./AccessibilityManager":40,"./accessibleTarget":41}],43:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +var _Container = require('./display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _ticker = require('./ticker'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _const = require('./const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Convenience class to create a new PIXI application. + * This class automatically creates the renderer, ticker + * and root container. + * + * @example + * // Create the application + * const app = new PIXI.Application(); + * + * // Add the view to the DOM + * document.body.appendChild(app.view); + * + * // ex, add display objects + * app.stage.addChild(PIXI.Sprite.fromImage('something.png')); + * + * @class + * @memberof PIXI + */ +var Application = function () { + // eslint-disable-next-line valid-jsdoc + /** + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great **webgl only** + * @param {boolean} [options.legacy=false] - `true` to ensure compatibility with older / less advanced devices. + * If you experience unexplained flickering try setting this to true. **webgl only** + * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.ticker.shared, `false` to create new ticker. + * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.loaders.shared, `false` to create new Loader. + */ + function Application(options, arg2, arg3, arg4, arg5) { + _classCallCheck(this, Application); + + // Support for constructor(width, height, options, noWebGL, useSharedTicker) + if (typeof options === 'number') { + options = Object.assign({ + width: options, + height: arg2 || _settings2.default.RENDER_OPTIONS.height, + forceCanvas: !!arg4, + sharedTicker: !!arg5 + }, arg3); + } + + /** + * The default options, so we mixin functionality later. + * @member {object} + * @protected + */ + this._options = options = Object.assign({ + sharedTicker: false, + forceCanvas: false, + sharedLoader: false + }, options); + + /** + * WebGL renderer if available, otherwise CanvasRenderer + * @member {PIXI.WebGLRenderer|PIXI.CanvasRenderer} + */ + this.renderer = (0, _autoDetectRenderer.autoDetectRenderer)(options); + + /** + * The root display container that's rendered. + * @member {PIXI.Container} + */ + this.stage = new _Container2.default(); + + /** + * Internal reference to the ticker + * @member {PIXI.ticker.Ticker} + * @private + */ + this._ticker = null; + + /** + * Ticker for doing render updates. + * @member {PIXI.ticker.Ticker} + * @default PIXI.ticker.shared + */ + this.ticker = options.sharedTicker ? _ticker.shared : new _ticker.Ticker(); + + // Start the rendering + this.start(); + } + + /** + * Render the current stage. + */ + Application.prototype.render = function render() { + this.renderer.render(this.stage); + }; + + /** + * Convenience method for stopping the render. + */ + + + Application.prototype.stop = function stop() { + this._ticker.stop(); + }; + + /** + * Convenience method for starting the render. + */ + + + Application.prototype.start = function start() { + this._ticker.start(); + }; + + /** + * Reference to the renderer's canvas element. + * @member {HTMLCanvasElement} + * @readonly + */ + + + /** + * Destroy and don't use after this. + * @param {Boolean} [removeView=false] Automatically remove canvas from DOM. + */ + Application.prototype.destroy = function destroy(removeView) { + var oldTicker = this._ticker; + + this.ticker = null; + + oldTicker.destroy(); + + this.stage.destroy(); + this.stage = null; + + this.renderer.destroy(removeView); + this.renderer = null; + + this._options = null; + }; + + _createClass(Application, [{ + key: 'ticker', + set: function set(ticker) // eslint-disable-line require-jsdoc + { + if (this._ticker) { + this._ticker.remove(this.render, this); + } + this._ticker = ticker; + if (ticker) { + ticker.add(this.render, this, _const.UPDATE_PRIORITY.LOW); + } + }, + get: function get() // eslint-disable-line require-jsdoc + { + return this._ticker; + } + }, { + key: 'view', + get: function get() { + return this.renderer.view; + } + + /** + * Reference to the renderer's screen rectangle. Its safe to use as filterArea or hitArea for whole screen + * @member {PIXI.Rectangle} + * @readonly + */ + + }, { + key: 'screen', + get: function get() { + return this.renderer.screen; + } + }]); + + return Application; +}(); + +exports.default = Application; + +},{"./autoDetectRenderer":45,"./const":46,"./display/Container":48,"./settings":101,"./ticker":120}],44:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function checkPrecision(src, def) { + if (src instanceof Array) { + if (src[0].substring(0, 9) !== 'precision') { + var copy = src.slice(0); + + copy.unshift('precision ' + def + ' float;'); + + return copy; + } + } else if (src.substring(0, 9) !== 'precision') { + return 'precision ' + def + ' float;\n' + src; + } + + return src; +} + +/** + * Wrapper class, webGL Shader for Pixi. + * Adds precision string if vertexSrc or fragmentSrc have no mention of it. + * + * @class + * @extends GLShader + * @memberof PIXI + */ + +var Shader = function (_GLShader) { + _inherits(Shader, _GLShader); + + /** + * + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + * @param {string|string[]} vertexSrc - The vertex shader source as an array of strings. + * @param {string|string[]} fragmentSrc - The fragment shader source as an array of strings. + */ + function Shader(gl, vertexSrc, fragmentSrc) { + _classCallCheck(this, Shader); + + return _possibleConstructorReturn(this, _GLShader.call(this, gl, checkPrecision(vertexSrc, _settings2.default.PRECISION_VERTEX), checkPrecision(fragmentSrc, _settings2.default.PRECISION_FRAGMENT))); + } + + return Shader; +}(_pixiGlCore.GLShader); + +exports.default = Shader; + +},{"./settings":101,"pixi-gl-core":12}],45:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = autoDetectRenderer; + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// eslint-disable-next-line valid-jsdoc +/** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by + * the browser then this function will return a canvas renderer + * + * @memberof PIXI + * @function autoDetectRenderer + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great **webgl only** + * @param {boolean} [options.legacy=false] - `true` to ensure compatibility with older / less advanced devices. + * If you experience unexplained flickering try setting this to true. **webgl only** + * @return {PIXI.WebGLRenderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ +function autoDetectRenderer(options, arg1, arg2, arg3) { + // Backward-compatible support for noWebGL option + var forceCanvas = options && options.forceCanvas; + + if (arg3 !== undefined) { + forceCanvas = arg3; + } + + if (!forceCanvas && utils.isWebGLSupported()) { + return new _WebGLRenderer2.default(options, arg1, arg2); + } + + return new _CanvasRenderer2.default(options, arg1, arg2); +} + +},{"./renderers/canvas/CanvasRenderer":77,"./renderers/webgl/WebGLRenderer":84,"./utils":124}],46:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * String of the current PIXI version. + * + * @static + * @constant + * @memberof PIXI + * @name VERSION + * @type {string} + */ +var VERSION = exports.VERSION = '4.5.4'; + +/** + * Two Pi. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var PI_2 = exports.PI_2 = Math.PI * 2; + +/** + * Conversion factor for converting radians to degrees. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var RAD_TO_DEG = exports.RAD_TO_DEG = 180 / Math.PI; + +/** + * Conversion factor for converting degrees to radians. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var DEG_TO_RAD = exports.DEG_TO_RAD = Math.PI / 180; + +/** + * Constant to identify the Renderer Type. + * + * @static + * @constant + * @memberof PIXI + * @name RENDERER_TYPE + * @type {object} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ +var RENDERER_TYPE = exports.RENDERER_TYPE = { + UNKNOWN: 0, + WEBGL: 1, + CANVAS: 2 +}; + +/** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * + * @static + * @constant + * @memberof PIXI + * @name BLEND_MODES + * @type {object} + * @property {number} NORMAL + * @property {number} ADD + * @property {number} MULTIPLY + * @property {number} SCREEN + * @property {number} OVERLAY + * @property {number} DARKEN + * @property {number} LIGHTEN + * @property {number} COLOR_DODGE + * @property {number} COLOR_BURN + * @property {number} HARD_LIGHT + * @property {number} SOFT_LIGHT + * @property {number} DIFFERENCE + * @property {number} EXCLUSION + * @property {number} HUE + * @property {number} SATURATION + * @property {number} COLOR + * @property {number} LUMINOSITY + */ +var BLEND_MODES = exports.BLEND_MODES = { + NORMAL: 0, + ADD: 1, + MULTIPLY: 2, + SCREEN: 3, + OVERLAY: 4, + DARKEN: 5, + LIGHTEN: 6, + COLOR_DODGE: 7, + COLOR_BURN: 8, + HARD_LIGHT: 9, + SOFT_LIGHT: 10, + DIFFERENCE: 11, + EXCLUSION: 12, + HUE: 13, + SATURATION: 14, + COLOR: 15, + LUMINOSITY: 16, + NORMAL_NPM: 17, + ADD_NPM: 18, + SCREEN_NPM: 19 +}; + +/** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * + * @static + * @constant + * @memberof PIXI + * @name DRAW_MODES + * @type {object} + * @property {number} POINTS + * @property {number} LINES + * @property {number} LINE_LOOP + * @property {number} LINE_STRIP + * @property {number} TRIANGLES + * @property {number} TRIANGLE_STRIP + * @property {number} TRIANGLE_FAN + */ +var DRAW_MODES = exports.DRAW_MODES = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6 +}; + +/** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @static + * @constant + * @memberof PIXI + * @name SCALE_MODES + * @type {object} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ +var SCALE_MODES = exports.SCALE_MODES = { + LINEAR: 0, + NEAREST: 1 +}; + +/** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wraping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as webGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * + * @static + * @constant + * @name WRAP_MODES + * @memberof PIXI + * @type {object} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ +var WRAP_MODES = exports.WRAP_MODES = { + CLAMP: 0, + REPEAT: 1, + MIRRORED_REPEAT: 2 +}; + +/** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * + * @static + * @constant + * @name GC_MODES + * @memberof PIXI + * @type {object} + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ +var GC_MODES = exports.GC_MODES = { + AUTO: 0, + MANUAL: 1 +}; + +/** + * Regexp for image type by extension. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `image.png` + */ +var URL_FILE_EXTENSION = exports.URL_FILE_EXTENSION = /\.(\w{3,4})(?:$|\?|#)/i; + +/** + * Regexp for data URI. + * Based on: {@link https://github.com/ragingwind/data-uri-regex} + * + * @static + * @constant + * @name DATA_URI + * @memberof PIXI + * @type {RegExp|string} + * @example data:image/png;base64 + */ +var DATA_URI = exports.DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;(charset=[\w-]+|base64))?,(.*)/i; + +/** + * Regexp for SVG size. + * + * @static + * @constant + * @name SVG_SIZE + * @memberof PIXI + * @type {RegExp|string} + * @example <svg width="100" height="100"></svg> + */ +var SVG_SIZE = exports.SVG_SIZE = /]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len + +/** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * + * @static + * @constant + * @name SHAPES + * @memberof PIXI + * @type {object} + * @property {number} POLY Polygon + * @property {number} RECT Rectangle + * @property {number} CIRC Circle + * @property {number} ELIP Ellipse + * @property {number} RREC Rounded Rectangle + */ +var SHAPES = exports.SHAPES = { + POLY: 0, + RECT: 1, + CIRC: 2, + ELIP: 3, + RREC: 4 +}; + +/** + * Constants that specify float precision in shaders. + * + * @static + * @constant + * @name PRECISION + * @memberof PIXI + * @type {object} + * @property {string} LOW='lowp' + * @property {string} MEDIUM='mediump' + * @property {string} HIGH='highp' + */ +var PRECISION = exports.PRECISION = { + LOW: 'lowp', + MEDIUM: 'mediump', + HIGH: 'highp' +}; + +/** + * Constants that specify the transform type. + * + * @static + * @constant + * @name TRANSFORM_MODE + * @memberof PIXI + * @type {object} + * @property {number} STATIC + * @property {number} DYNAMIC + */ +var TRANSFORM_MODE = exports.TRANSFORM_MODE = { + STATIC: 0, + DYNAMIC: 1 +}; + +/** + * Constants that define the type of gradient on text. + * + * @static + * @constant + * @name TEXT_GRADIENT + * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL Vertical gradient + * @property {number} LINEAR_HORIZONTAL Linear gradient + */ +var TEXT_GRADIENT = exports.TEXT_GRADIENT = { + LINEAR_VERTICAL: 0, + LINEAR_HORIZONTAL: 1 +}; + +/** + * Represents the update priorities used by internal PIXI classes when registered with + * the {@link PIXI.ticker.Ticker} object. Higher priority items are updated first and lower + * priority items, such as render, should go later. + * + * @static + * @constant + * @name UPDATE_PRIORITY + * @memberof PIXI + * @type {object} + * @property {number} INTERACTION=50 Highest priority, used for {@link PIXI.interaction.InteractionManager} + * @property {number} HIGH=25 High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.extras.AnimatedSprite} + * @property {number} NORMAL=0 Default priority for ticker events, see {@link PIXI.ticker.Ticker#add}. + * @property {number} LOW=-25 Low priority used for {@link PIXI.Application} rendering. + * @property {number} UTILITY=-50 Lowest priority used for {@link PIXI.prepare.BasePrepare} utility. + */ +var UPDATE_PRIORITY = exports.UPDATE_PRIORITY = { + INTERACTION: 50, + HIGH: 25, + NORMAL: 0, + LOW: -25, + UTILITY: -50 +}; + +},{}],47:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * 'Builder' pattern for bounds rectangles + * Axis-Aligned Bounding Box + * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems + * + * @class + * @memberof PIXI + */ +var Bounds = function () { + /** + * + */ + function Bounds() { + _classCallCheck(this, Bounds); + + /** + * @member {number} + * @default 0 + */ + this.minX = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.minY = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxX = -Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxY = -Infinity; + + this.rect = null; + } + + /** + * Checks if bounds are empty. + * + * @return {boolean} True if empty. + */ + + + Bounds.prototype.isEmpty = function isEmpty() { + return this.minX > this.maxX || this.minY > this.maxY; + }; + + /** + * Clears the bounds and resets. + * + */ + + + Bounds.prototype.clear = function clear() { + this.updateID++; + + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * + * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty + * @returns {PIXI.Rectangle} A rectangle of the bounds + */ + + + Bounds.prototype.getRectangle = function getRectangle(rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return _math.Rectangle.EMPTY; + } + + rect = rect || new _math.Rectangle(0, 0, 1, 1); + + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + + return rect; + }; + + /** + * This function should be inlined when its possible. + * + * @param {PIXI.Point} point - The point to add. + */ + + + Bounds.prototype.addPoint = function addPoint(point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + }; + + /** + * Adds a quad, not transformed + * + * @param {Float32Array} vertices - The verts to add. + */ + + + Bounds.prototype.addQuad = function addQuad(vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = vertices[0]; + var y = vertices[1]; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds sprite frame, transformed. + * + * @param {PIXI.TransformBase} transform - TODO + * @param {number} x0 - TODO + * @param {number} y0 - TODO + * @param {number} x1 - TODO + * @param {number} y1 - TODO + */ + + + Bounds.prototype.addFrame = function addFrame(transform, x0, y0, x1, y1) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = a * x0 + c * y0 + tx; + var y = b * x0 + d * y0 + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y0 + tx; + y = b * x1 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x0 + c * y1 + tx; + y = b * x0 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y1 + tx; + y = b * x1 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Add an array of vertices + * + * @param {PIXI.TransformBase} transform - TODO + * @param {Float32Array} vertices - TODO + * @param {number} beginOffset - TODO + * @param {number} endOffset - TODO + */ + + + Bounds.prototype.addVertices = function addVertices(transform, vertices, beginOffset, endOffset) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = a * rawX + c * rawY + tx; + var y = d * rawY + b * rawX + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds other Bounds + * + * @param {PIXI.Bounds} bounds - TODO + */ + + + Bounds.prototype.addBounds = function addBounds(bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + }; + + /** + * Adds other Bounds, masked with Bounds + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Bounds} mask - TODO + */ + + + Bounds.prototype.addBoundsMask = function addBoundsMask(bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + /** + * Adds other Bounds, masked with Rectangle + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Rectangle} area - TODO + */ + + + Bounds.prototype.addBoundsArea = function addBoundsArea(bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : area.x + area.width; + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : area.y + area.height; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + return Bounds; +}(); + +exports.default = Bounds; + +},{"../math":70}],48:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _DisplayObject2 = require('./DisplayObject'); + +var _DisplayObject3 = _interopRequireDefault(_DisplayObject2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A Container represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + *```js + * let container = new PIXI.Container(); + * container.addChild(sprite); + * ``` + * + * @class + * @extends PIXI.DisplayObject + * @memberof PIXI + */ +var Container = function (_DisplayObject) { + _inherits(Container, _DisplayObject); + + /** + * + */ + function Container() { + _classCallCheck(this, Container); + + /** + * The array of children of this container. + * + * @member {PIXI.DisplayObject[]} + * @readonly + */ + var _this = _possibleConstructorReturn(this, _DisplayObject.call(this)); + + _this.children = []; + return _this; + } + + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified + * + * @private + */ + + + Container.prototype.onChildrenChange = function onChildrenChange() {} + /* empty */ + + + /** + * Adds one or more children to the container. + * + * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container + * @return {PIXI.DisplayObject} The first child that was added. + */ + ; + + Container.prototype.addChild = function addChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.addChild(arguments[i]); + } + } else { + // if the child has a parent then lets remove it as PixiJS objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.push(child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + child.emit('added', this); + } + + return child; + }; + + /** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @return {PIXI.DisplayObject} The child that was added. + */ + + + Container.prototype.addChildAt = function addChildAt(child, index) { + if (index < 0 || index > this.children.length) { + throw new Error(child + 'addChildAt: The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.splice(index, 0, child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + + return child; + }; + + /** + * Swaps the position of 2 Display Objects within this container. + * + * @param {PIXI.DisplayObject} child - First display object to swap + * @param {PIXI.DisplayObject} child2 - Second display object to swap + */ + + + Container.prototype.swapChildren = function swapChildren(child, child2) { + if (child === child2) { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; + + /** + * Returns the index position of a child DisplayObject instance + * + * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify + * @return {number} The index position of the child display object to identify + */ + + + Container.prototype.getChildIndex = function getChildIndex(child) { + var index = this.children.indexOf(child); + + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + }; + + /** + * Changes the position of an existing child in the display object container + * + * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number + * @param {number} index - The resulting index number for the child display object + */ + + + Container.prototype.setChildIndex = function setChildIndex(child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + (0, _utils.removeItems)(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + + this.onChildrenChange(index); + }; + + /** + * Returns the child at the specified index + * + * @param {number} index - The index to get the child at + * @return {PIXI.DisplayObject} The child at the given index, if any. + */ + + + Container.prototype.getChildAt = function getChildAt(index) { + if (index < 0 || index >= this.children.length) { + throw new Error('getChildAt: Index (' + index + ') does not exist.'); + } + + return this.children[index]; + }; + + /** + * Removes one or more children from the container. + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove + * @return {PIXI.DisplayObject} The first child that was removed. + */ + + + Container.prototype.removeChild = function removeChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.removeChild(arguments[i]); + } + } else { + var index = this.children.indexOf(child); + + if (index === -1) return null; + + child.parent = null; + // ensure child transform will be recalculated + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + } + + return child; + }; + + /** + * Removes a child from the specified index position. + * + * @param {number} index - The index to get the child from + * @return {PIXI.DisplayObject} The child that was removed. + */ + + + Container.prototype.removeChildAt = function removeChildAt(index) { + var child = this.getChildAt(index); + + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + + return child; + }; + + /** + * Removes all children from this container that are within the begin and end indexes. + * + * @param {number} [beginIndex=0] - The beginning position. + * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. + * @returns {DisplayObject[]} List of removed children + */ + + + Container.prototype.removeChildren = function removeChildren() { + var beginIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var endIndex = arguments[1]; + + var begin = beginIndex; + var end = typeof endIndex === 'number' ? endIndex : this.children.length; + var range = end - begin; + var removed = void 0; + + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } + + this._boundsID++; + + this.onChildrenChange(beginIndex); + + for (var _i = 0; _i < removed.length; ++_i) { + removed[_i].emit('removed', this); + } + + return removed; + } else if (range === 0 && this.children.length === 0) { + return []; + } + + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + }; + + /** + * Updates the transform on all children of this container for rendering + */ + + + Container.prototype.updateTransform = function updateTransform() { + this._boundsID++; + + this.transform.updateTransform(this.parent.transform); + + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + + if (child.visible) { + child.updateTransform(); + } + } + }; + + /** + * Recalculates the bounds of the container. + * + */ + + + Container.prototype.calculateBounds = function calculateBounds() { + this._bounds.clear(); + + this._calculateBounds(); + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (!child.visible || !child.renderable) { + continue; + } + + child.calculateBounds(); + + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + child._mask.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, child._mask._bounds); + } else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } else { + this._bounds.addBounds(child._bounds); + } + } + + this._lastBoundsID = this._boundsID; + }; + + /** + * Recalculates the bounds of the object. Override this to + * calculate the bounds of the specific object (not including children). + * + */ + + + Container.prototype._calculateBounds = function _calculateBounds() {} + // FILL IN// + + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderWebGL = function renderWebGL(renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + // do a quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) { + this.renderAdvancedWebGL(renderer); + } else { + this._renderWebGL(renderer); + + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderWebGL(renderer); + } + } + }; + + /** + * Render the object using the WebGL renderer and advanced features. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { + renderer.flush(); + + var filters = this._filters; + var mask = this._mask; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + + this._enabledFilters.length = 0; + + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + + if (this._enabledFilters.length) { + renderer.filterManager.pushFilter(this, this._enabledFilters); + } + } + + if (mask) { + renderer.maskManager.pushMask(this, this._mask); + } + + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); + + // now loop through the children and make sure they get rendered + for (var _i2 = 0, j = this.children.length; _i2 < j; _i2++) { + this.children[_i2].renderWebGL(renderer); + } + + renderer.flush(); + + if (mask) { + renderer.maskManager.popMask(this, this._mask); + } + + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filterManager.popFilter(); + } + }; + + /** + * To be overridden by the subclasses. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype._renderWebGL = function _renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * To be overridden by the subclass + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype._renderCanvas = function _renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderCanvas = function renderCanvas(renderer) { + // if not visible or the alpha is 0 then no need to render this + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + if (this._mask) { + renderer.maskManager.pushMask(this._mask); + } + + this._renderCanvas(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderCanvas(renderer); + } + + if (this._mask) { + renderer.maskManager.popMask(renderer); + } + }; + + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Container.prototype.destroy = function destroy(options) { + _DisplayObject.prototype.destroy.call(this); + + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + + var oldChildren = this.removeChildren(0, this.children.length); + + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + }; + + /** + * The width of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Container, [{ + key: 'width', + get: function get() { + return this.scale.x * this.getLocalBounds().width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var width = this.getLocalBounds().width; + + if (width !== 0) { + this.scale.x = value / width; + } else { + this.scale.x = 1; + } + + this._width = value; + } + + /** + * The height of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.scale.y * this.getLocalBounds().height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var height = this.getLocalBounds().height; + + if (height !== 0) { + this.scale.y = value / height; + } else { + this.scale.y = 1; + } + + this._height = value; + } + }]); + + return Container; +}(_DisplayObject3.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = Container; +Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + +},{"../utils":124,"./DisplayObject":49}],49:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TransformStatic = require('./TransformStatic'); + +var _TransformStatic2 = _interopRequireDefault(_TransformStatic); + +var _Transform = require('./Transform'); + +var _Transform2 = _interopRequireDefault(_Transform); + +var _Bounds = require('./Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _math = require('../math'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// _tempDisplayObjectParent = new DisplayObject(); + +/** + * The base class for all objects that are rendered on the screen. + * This is an abstract class and should not be used on its own rather it should be extended. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var DisplayObject = function (_EventEmitter) { + _inherits(DisplayObject, _EventEmitter); + + /** + * + */ + function DisplayObject() { + _classCallCheck(this, DisplayObject); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + var TransformClass = _settings2.default.TRANSFORM_MODE === _const.TRANSFORM_MODE.STATIC ? _TransformStatic2.default : _Transform2.default; + + _this.tempDisplayObjectParent = null; + + // TODO: need to create Transform from factory + /** + * World transform and local transform of this object. + * This will become read-only later, please do not assign anything there unless you know what are you doing + * + * @member {PIXI.TransformBase} + */ + _this.transform = new TransformClass(); + + /** + * The opacity of the object. + * + * @member {number} + */ + _this.alpha = 1; + + /** + * The visibility of the object. If false the object will not be drawn, and + * the updateTransform function will not be called. + * + * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually + * + * @member {boolean} + */ + _this.visible = true; + + /** + * Can this object be rendered, if false the object will not be drawn but the updateTransform + * methods will still be called. + * + * Only affects recursive calls from parent. You can ask for bounds manually + * + * @member {boolean} + */ + _this.renderable = true; + + /** + * The display object container that contains this display object. + * + * @member {PIXI.Container} + * @readonly + */ + _this.parent = null; + + /** + * The multiplied alpha of the displayObject + * + * @member {number} + * @readonly + */ + _this.worldAlpha = 1; + + /** + * The area the filter is applied to. This is used as more of an optimisation + * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle + * + * Also works as an interaction mask + * + * @member {PIXI.Rectangle} + */ + _this.filterArea = null; + + _this._filters = null; + _this._enabledFilters = null; + + /** + * The bounds object, this is used to calculate and store the bounds of the displayObject + * + * @member {PIXI.Rectangle} + * @private + */ + _this._bounds = new _Bounds2.default(); + _this._boundsID = 0; + _this._lastBoundsID = -1; + _this._boundsRect = null; + _this._localBoundsRect = null; + + /** + * The original, cached mask of the object + * + * @member {PIXI.Graphics|PIXI.Sprite} + * @private + */ + _this._mask = null; + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + + /** + * Fired when this DisplayObject is added to a Container. + * + * @event PIXI.DisplayObject#added + * @param {PIXI.Container} container - The container added to. + */ + + /** + * Fired when this DisplayObject is removed from a Container. + * + * @event PIXI.DisplayObject#removed + * @param {PIXI.Container} container - The container removed from. + */ + return _this; + } + + /** + * @private + * @member {PIXI.DisplayObject} + */ + + + /** + * Updates the object transform for rendering + * + * TODO - Optimization pass! + */ + DisplayObject.prototype.updateTransform = function updateTransform() { + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + this._bounds.updateID++; + }; + + /** + * recursively updates transform of all objects from the root to this one + * internal function for toLocal() + */ + + + DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform() { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + }; + + /** + * Retrieves the bounds of the displayObject as a rectangle object. + * + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @param {PIXI.Rectangle} rect - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getBounds = function getBounds(skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + + if (this._boundsID !== this._lastBoundsID) { + this.calculateBounds(); + } + + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new _math.Rectangle(); + } + + rect = this._boundsRect; + } + + return this._bounds.getRectangle(rect); + }; + + /** + * Retrieves the local bounds of the displayObject as a rectangle object + * + * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getLocalBounds = function getLocalBounds(rect) { + var transformRef = this.transform; + var parentRef = this.parent; + + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + var bounds = this.getBounds(false, rect); + + this.parent = parentRef; + this.transform = transformRef; + + return bounds; + }; + + /** + * Calculates the global position of the display object + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform. + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toGlobal = function toGlobal(position, point) { + var skipUpdate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; + + /** + * Calculates the local position of the display object relative to another point + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toLocal = function toLocal(position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + DisplayObject.prototype.renderCanvas = function renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Set the parent Container of this DisplayObject + * + * @param {PIXI.Container} container - The Container to add this DisplayObject to + * @return {PIXI.Container} The Container that this DisplayObject was added to + */ + ; + + DisplayObject.prototype.setParent = function setParent(container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); + } + + container.addChild(this); + + return container; + }; + + /** + * Convenience function to set the position, scale, skew and pivot at once. + * + * @param {number} [x=0] - The X position + * @param {number} [y=0] - The Y position + * @param {number} [scaleX=1] - The X scale value + * @param {number} [scaleY=1] - The Y scale value + * @param {number} [rotation=0] - The rotation + * @param {number} [skewX=0] - The X skew value + * @param {number} [skewY=0] - The Y skew value + * @param {number} [pivotX=0] - The X pivot value + * @param {number} [pivotY=0] - The Y pivot value + * @return {PIXI.DisplayObject} The DisplayObject instance + */ + + + DisplayObject.prototype.setTransform = function setTransform() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var scaleX = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var scaleY = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var rotation = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var skewX = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + var skewY = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + var pivotX = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; + var pivotY = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0; + + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + + return this; + }; + + /** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy`. + * + */ + + + DisplayObject.prototype.destroy = function destroy() { + this.removeAllListeners(); + if (this.parent) { + this.parent.removeChild(this); + } + this.transform = null; + + this.parent = null; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this.filterArea = null; + + this.interactive = false; + this.interactiveChildren = false; + + this._destroyed = true; + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + * + * @member {number} + */ + + + _createClass(DisplayObject, [{ + key: '_tempDisplayObjectParent', + get: function get() { + if (this.tempDisplayObjectParent === null) { + this.tempDisplayObjectParent = new DisplayObject(); + } + + return this.tempDisplayObjectParent; + } + }, { + key: 'x', + get: function get() { + return this.position.x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.x = value; + } + + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + * + * @member {number} + */ + + }, { + key: 'y', + get: function get() { + return this.position.y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.y = value; + } + + /** + * Current transform of the object based on world (parent) factors + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'worldTransform', + get: function get() { + return this.transform.worldTransform; + } + + /** + * Current transform of the object based on local factors: position, scale, other stuff + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'localTransform', + get: function get() { + return this.transform.localTransform; + } + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'position', + get: function get() { + return this.transform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.copy(value); + } + + /** + * The scale factor of the object. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'scale', + get: function get() { + return this.transform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.scale.copy(value); + } + + /** + * The pivot point of the displayObject that it rotates around + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'pivot', + get: function get() { + return this.transform.pivot; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.pivot.copy(value); + } + + /** + * The skew factor for the object in radians. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'skew', + get: function get() { + return this.transform.skew; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.skew.copy(value); + } + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + }, { + key: 'rotation', + get: function get() { + return this.transform.rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.rotation = value; + } + + /** + * Indicates if the object is globally visible. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'worldVisible', + get: function get() { + var item = this; + + do { + if (!item.visible) { + return false; + } + + item = item.parent; + } while (item); + + return true; + } + + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PIXI a regular mask must be a + * PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it + * utilises shape clipping. To remove a mask, set this property to null. + * + * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + * + * @member {PIXI.Graphics|PIXI.Sprite} + */ + + }, { + key: 'mask', + get: function get() { + return this._mask; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._mask) { + this._mask.renderable = true; + } + + this._mask = value; + + if (this._mask) { + this._mask.renderable = false; + } + } + + /** + * Sets the filters for the displayObject. + * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * To remove filters simply set this property to 'null' + * + * @member {PIXI.Filter[]} + */ + + }, { + key: 'filters', + get: function get() { + return this._filters && this._filters.slice(); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._filters = value && value.slice(); + } + }]); + + return DisplayObject; +}(_eventemitter2.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = DisplayObject; +DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + +},{"../const":46,"../math":70,"../settings":101,"./Bounds":47,"./Transform":50,"./TransformStatic":52,"eventemitter3":3}],50:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Generic class to deal with traditional 2D matrix transforms + * local transformation is calculated from position,scale,skew and rotation + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var Transform = function (_TransformBase) { + _inherits(Transform, _TransformBase); + + /** + * + */ + function Transform() { + _classCallCheck(this, Transform); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.Point} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.Point(0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.Point} + */ + _this.scale = new _math.Point(1, 1); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.Point} + */ + _this.pivot = new _math.Point(0, 0); + + /** + * The rotation value of the object, in radians + * + * @member {Number} + * @private + */ + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + return _this; + } + + /** + * Updates the skew values when the skew or rotation changes. + * + * @private + */ + + + Transform.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + }; + + /** + * Updates only local matrix + */ + + + Transform.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + Transform.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + Transform.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(Transform, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return Transform; +}(_TransformBase3.default); + +exports.default = Transform; + +},{"../math":70,"./TransformBase":51}],51:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Generic class to deal with traditional 2D matrix transforms + * + * @class + * @memberof PIXI + */ +var TransformBase = function () { + /** + * + */ + function TransformBase() { + _classCallCheck(this, TransformBase); + + /** + * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds() + * + * @member {PIXI.Matrix} + */ + this.worldTransform = new _math.Matrix(); + + /** + * The local matrix transform + * + * @member {PIXI.Matrix} + */ + this.localTransform = new _math.Matrix(); + + this._worldID = 0; + this._parentID = 0; + } + + /** + * TransformBase does not have decomposition, so this function wont do anything + */ + + + TransformBase.prototype.updateLocalTransform = function updateLocalTransform() {} + // empty + + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.TransformBase} parentTransform - The transform of the parent of this object + */ + ; + + TransformBase.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + return TransformBase; +}(); + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ + + +exports.default = TransformBase; +TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; + +TransformBase.IDENTITY = new TransformBase(); + +},{"../math":70}],52:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Transform that takes care about its versions + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var TransformStatic = function (_TransformBase) { + _inherits(TransformStatic, _TransformBase); + + /** + * + */ + function TransformStatic() { + _classCallCheck(this, TransformStatic); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.ObservablePoint} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.ObservablePoint} + */ + _this.scale = new _math.ObservablePoint(_this.onChange, _this, 1, 1); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.ObservablePoint} + */ + _this.pivot = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + + _this._localID = 0; + _this._currentLocalID = 0; + return _this; + } + + /** + * Called when a value changes. + * + * @private + */ + + + TransformStatic.prototype.onChange = function onChange() { + this._localID++; + }; + + /** + * Called when skew or rotation changes + * + * @private + */ + + + TransformStatic.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + + this._localID++; + }; + + /** + * Updates only local matrix + */ + + + TransformStatic.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + TransformStatic.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._parentID = parentTransform._worldID; + + // update the id of the transform.. + this._worldID++; + } + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + TransformStatic.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + this._localID++; + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(TransformStatic, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return TransformStatic; +}(_TransformBase3.default); + +exports.default = TransformStatic; + +},{"../math":70,"./TransformBase":51}],53:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _GraphicsData = require('./GraphicsData'); + +var _GraphicsData2 = _interopRequireDefault(_GraphicsData); + +var _Sprite = require('../sprites/Sprite'); + +var _Sprite2 = _interopRequireDefault(_Sprite); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Bounds = require('../display/Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _bezierCurveTo2 = require('./utils/bezierCurveTo'); + +var _bezierCurveTo3 = _interopRequireDefault(_bezierCurveTo2); + +var _CanvasRenderer = require('../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var canvasRenderer = void 0; +var tempMatrix = new _math.Matrix(); +var tempPoint = new _math.Point(); +var tempColor1 = new Float32Array(4); +var tempColor2 = new Float32Array(4); + +/** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Graphics = function (_Container) { + _inherits(Graphics, _Container); + + /** + * + * @param {boolean} [nativeLines=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + */ + function Graphics() { + var nativeLines = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + _classCallCheck(this, Graphics); + + /** + * The alpha value used when filling the Graphics object. + * + * @member {number} + * @default 1 + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @member {number} + * @default 0 + */ + _this.lineWidth = 0; + + /** + * If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * + * @member {boolean} + */ + _this.nativeLines = nativeLines; + + /** + * The color of any lines drawn. + * + * @member {string} + * @default 0 + */ + _this.lineColor = 0; + + /** + * Graphics data + * + * @member {PIXI.GraphicsData[]} + * @private + */ + _this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to + * reset the tint. + * + * @member {number} + * @default 0xFFFFFF + */ + _this.tint = 0xFFFFFF; + + /** + * The previous tint applied to the graphic shape. Used to compare to the current tint and + * check if theres change. + * + * @member {number} + * @private + * @default 0xFFFFFF + */ + _this._prevTint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * Current path + * + * @member {PIXI.GraphicsData} + * @private + */ + _this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @member {object} + * @private + */ + // TODO - _webgl should use a prototype object, not a random undocumented object... + _this._webGL = {}; + + /** + * Whether this shape is being used as a mask. + * + * @member {boolean} + */ + _this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @member {number} + */ + _this.boundsPadding = 0; + + /** + * A cache of the local bounds to prevent recalculation. + * + * @member {PIXI.Rectangle} + * @private + */ + _this._localBounds = new _Bounds2.default(); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics + * object will be recalculated. + * + * @member {boolean} + * @private + */ + _this.dirty = 0; + + /** + * Used to detect if we need to do a fast rect check using the id compare method + * @type {Number} + */ + _this.fastRectDirty = -1; + + /** + * Used to detect if we clear the graphics webGL data + * @type {Number} + */ + _this.clearDirty = 0; + + /** + * Used to detect if we we need to recalculate local bounds + * @type {Number} + */ + _this.boundsDirty = -1; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @member {boolean} + * @private + */ + _this.cachedSpriteDirty = false; + + _this._spriteRect = null; + _this._fastRect = false; + + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ + return _this; + } + + /** + * Creates a new Graphics object with the same values as this one. + * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) + * + * @return {PIXI.Graphics} A clone of the graphics object + */ + + + Graphics.prototype.clone = function clone() { + var clone = new Graphics(); + + clone.renderable = this.renderable; + clone.fillAlpha = this.fillAlpha; + clone.lineWidth = this.lineWidth; + clone.lineColor = this.lineColor; + clone.tint = this.tint; + clone.blendMode = this.blendMode; + clone.isMask = this.isMask; + clone.boundsPadding = this.boundsPadding; + clone.dirty = 0; + clone.cachedSpriteDirty = this.cachedSpriteDirty; + + // copy graphics data + for (var i = 0; i < this.graphicsData.length; ++i) { + clone.graphicsData.push(this.graphicsData[i].clone()); + } + + clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; + + clone.updateLocalBounds(); + + return clone; + }; + + /** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() + * method or the drawCircle() method. + * + * @param {number} [lineWidth=0] - width of the line to draw, will update the objects stored style + * @param {number} [color=0] - color of the line to draw, will update the objects stored style + * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineStyle = function lineStyle() { + var lineWidth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var alpha = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + + this.lineWidth = lineWidth; + this.lineColor = color; + this.lineAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length) { + // halfway through a line? start a new one! + var shape = new _math.Polygon(this.currentPath.shape.points.slice(-2)); + + shape.closed = false; + + this.drawShape(shape); + } else { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + }; + + /** + * Moves the current drawing position to x, y. + * + * @param {number} x - the X coordinate to move to + * @param {number} y - the Y coordinate to move to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.moveTo = function moveTo(x, y) { + var shape = new _math.Polygon([x, y]); + + shape.closed = false; + this.drawShape(shape); + + return this; + }; + + /** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @param {number} x - the X coordinate to draw to + * @param {number} y - the Y coordinate to draw to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineTo = function lineTo(x, y) { + this.currentPath.shape.points.push(x, y); + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.quadraticCurveTo = function quadraticCurveTo(cpX, cpY, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var n = 20; + var points = this.currentPath.shape.points; + var xa = 0; + var ya = 0; + + if (points.length === 0) { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + for (var i = 1; i <= n; ++i) { + var j = i / n; + + xa = fromX + (cpX - fromX) * j; + ya = fromY + (cpY - fromY) * j; + + points.push(xa + (cpX + (toX - cpX) * j - xa) * j, ya + (cpY + (toY - cpY) * j - ya) * j); + } + + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a bezier curve and then draws it. + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.bezierCurveTo = function bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + points.length -= 2; + + (0, _bezierCurveTo3.default)(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, points); + + this.dirty++; + + return this; + }; + + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @param {number} x1 - The x-coordinate of the beginning of the arc + * @param {number} y1 - The y-coordinate of the beginning of the arc + * @param {number} x2 - The x-coordinate of the end of the arc + * @param {number} y2 - The y-coordinate of the end of the arc + * @param {number} radius - The radius of the arc + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arcTo = function arcTo(x1, y1, x2, y2, radius) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points.push(x1, y1); + } + } else { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + } else { + var dd = a1 * a1 + b1 * b1; + var cc = a2 * a2 + b2 * b2; + var tt = a1 * a2 + b1 * b2; + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = k1 * b2 + k2 * b1; + var cy = k1 * a2 + k2 * a1; + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty++; + + return this; + }; + + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @param {number} cx - The x-coordinate of the center of the circle + * @param {number} cy - The y-coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param {number} endAngle - The ending angle, in radians + * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arc = function arc(cx, cy, radius, startAngle, endAngle) { + var anticlockwise = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; + + if (startAngle === endAngle) { + return this; + } + + if (!anticlockwise && endAngle <= startAngle) { + endAngle += Math.PI * 2; + } else if (anticlockwise && startAngle <= endAngle) { + startAngle += Math.PI * 2; + } + + var sweep = endAngle - startAngle; + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * 40; + + if (sweep === 0) { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. + var points = this.currentPath ? this.currentPath.shape.points : null; + + if (points) { + if (points[points.length - 2] !== startX || points[points.length - 1] !== startY) { + points.push(startX, startY); + } + } else { + this.moveTo(startX, startY); + points = this.currentPath.shape.points; + } + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = segMinus % 1 / segMinus; + + for (var i = 0; i <= segMinus; ++i) { + var real = i + remainder * i; + + var angle = theta + startAngle + theta2 * real; + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push((cTheta * c + sTheta * s) * radius + cx, (cTheta * -s + sTheta * c) * radius + cy); + } + + this.dirty++; + + return this; + }; + + /** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @param {number} [color=0] - the color of the fill + * @param {number} [alpha=1] - the alpha of the fill + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.beginFill = function beginFill() { + var color = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var alpha = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.filling = true; + this.fillColor = color; + this.fillAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length <= 2) { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + }; + + /** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.endFill = function endFill() { + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRect = function drawRect(x, y, width, height) { + this.drawShape(new _math.Rectangle(x, y, width, height)); + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @param {number} radius - Radius of the rectangle corners + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRoundedRect = function drawRoundedRect(x, y, width, height, radius) { + this.drawShape(new _math.RoundedRectangle(x, y, width, height, radius)); + + return this; + }; + + /** + * Draws a circle. + * + * @param {number} x - The X coordinate of the center of the circle + * @param {number} y - The Y coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawCircle = function drawCircle(x, y, radius) { + this.drawShape(new _math.Circle(x, y, radius)); + + return this; + }; + + /** + * Draws an ellipse. + * + * @param {number} x - The X coordinate of the center of the ellipse + * @param {number} y - The Y coordinate of the center of the ellipse + * @param {number} width - The half width of the ellipse + * @param {number} height - The half height of the ellipse + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawEllipse = function drawEllipse(x, y, width, height) { + this.drawShape(new _math.Ellipse(x, y, width, height)); + + return this; + }; + + /** + * Draws a polygon using the given path. + * + * @param {number[]|PIXI.Point[]} path - The path data used to construct the polygon. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawPolygon = function drawPolygon(path) { + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + var closed = true; + + if (points instanceof _math.Polygon) { + closed = points.closed; + points = points.points; + } + + if (!Array.isArray(points)) { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) { + points[i] = arguments[i]; // eslint-disable-line prefer-rest-params + } + } + + var shape = new _math.Polygon(points); + + shape.closed = closed; + + this.drawShape(shape); + + return this; + }; + + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.clear = function clear() { + if (this.lineWidth || this.filling || this.graphicsData.length > 0) { + this.lineWidth = 0; + this.filling = false; + + this.boundsDirty = -1; + this.dirty++; + this.clearDirty++; + this.graphicsData.length = 0; + } + + this.currentPath = null; + this._spriteRect = null; + + return this; + }; + + /** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. + * + * @returns {boolean} True if only 1 rect. + */ + + + Graphics.prototype.isFastRect = function isFastRect() { + return this.graphicsData.length === 1 && this.graphicsData[0].shape.type === _const.SHAPES.RECT && !this.graphicsData[0].lineWidth; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderWebGL = function _renderWebGL(renderer) { + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.dirty !== this.fastRectDirty) { + this.fastRectDirty = this.dirty; + this._fastRect = this.isFastRect(); + } + + // TODO this check can be moved to dirty? + if (this._fastRect) { + this._renderSpriteRect(renderer); + } else { + renderer.setObjectRenderer(renderer.plugins.graphics); + renderer.plugins.graphics.render(this); + } + }; + + /** + * Renders a sprite rectangle. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderSpriteRect = function _renderSpriteRect(renderer) { + var rect = this.graphicsData[0].shape; + + if (!this._spriteRect) { + this._spriteRect = new _Sprite2.default(new _Texture2.default(_Texture2.default.WHITE)); + } + + var sprite = this._spriteRect; + + if (this.tint === 0xffffff) { + sprite.tint = this.graphicsData[0].fillColor; + } else { + var t1 = tempColor1; + var t2 = tempColor2; + + (0, _utils.hex2rgb)(this.graphicsData[0].fillColor, t1); + (0, _utils.hex2rgb)(this.tint, t2); + + t1[0] *= t2[0]; + t1[1] *= t2[1]; + t1[2] *= t2[2]; + + sprite.tint = (0, _utils.rgb2hex)(t1); + } + sprite.alpha = this.graphicsData[0].fillAlpha; + sprite.worldAlpha = this.worldAlpha * sprite.alpha; + sprite.blendMode = this.blendMode; + + sprite._texture._frame.width = rect.width; + sprite._texture._frame.height = rect.height; + + sprite.transform.worldTransform = this.transform.worldTransform; + + sprite.anchor.set(-rect.x / rect.width, -rect.y / rect.height); + sprite._onAnchorUpdate(); + + sprite._renderWebGL(renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.isMask === true) { + return; + } + + renderer.plugins.graphics.render(this); + }; + + /** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @private + */ + + + Graphics.prototype._calculateBounds = function _calculateBounds() { + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.updateLocalBounds(); + + this.cachedSpriteDirty = true; + } + + var lb = this._localBounds; + + this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); + }; + + /** + * Tests if a point is inside this graphics object + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Graphics.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + + if (!data.fill) { + continue; + } + + // only deal with fills.. + if (data.shape) { + if (data.shape.contains(tempPoint.x, tempPoint.y)) { + if (data.holes) { + for (var _i = 0; _i < data.holes.length; _i++) { + var hole = data.holes[_i]; + + if (hole.contains(tempPoint.x, tempPoint.y)) { + return false; + } + } + } + + return true; + } + } + } + + return false; + }; + + /** + * Update the bounds of the object + * + */ + + + Graphics.prototype.updateLocalBounds = function updateLocalBounds() { + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) { + var shape = 0; + var x = 0; + var y = 0; + var w = 0; + var h = 0; + + for (var i = 0; i < this.graphicsData.length; i++) { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + + shape = data.shape; + + if (type === _const.SHAPES.RECT || type === _const.SHAPES.RREC) { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.CIRC) { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.ELIP) { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else { + // POLY + var points = shape.points; + var x2 = 0; + var y2 = 0; + var dx = 0; + var dy = 0; + var rw = 0; + var rh = 0; + var cx = 0; + var cy = 0; + + for (var j = 0; j + 2 < points.length; j += 2) { + x = points[j]; + y = points[j + 1]; + x2 = points[j + 2]; + y2 = points[j + 3]; + dx = Math.abs(x2 - x); + dy = Math.abs(y2 - y); + h = lineWidth; + w = Math.sqrt(dx * dx + dy * dy); + + if (w < 1e-9) { + continue; + } + + rw = (h / w * dy + dx) / 2; + rh = (h / w * dx + dy) / 2; + cx = (x2 + x) / 2; + cy = (y2 + y) / 2; + + minX = cx - rw < minX ? cx - rw : minX; + maxX = cx + rw > maxX ? cx + rw : maxX; + + minY = cy - rh < minY ? cy - rh : minY; + maxY = cy + rh > maxY ? cy + rh : maxY; + } + } + } + } else { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.minX = minX - padding; + this._localBounds.maxX = maxX + padding; + + this._localBounds.minY = minY - padding; + this._localBounds.maxY = maxY + padding; + }; + + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @return {PIXI.GraphicsData} The generated GraphicsData object. + */ + + + Graphics.prototype.drawShape = function drawShape(shape) { + if (this.currentPath) { + // check current path! + if (this.currentPath.shape.points.length <= 2) { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + var data = new _GraphicsData2.default(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, this.nativeLines, shape); + + this.graphicsData.push(data); + + if (data.type === _const.SHAPES.POLY) { + data.shape.closed = data.shape.closed || this.filling; + this.currentPath = data; + } + + this.dirty++; + + return data; + }; + + /** + * Generates a canvas texture. + * + * @param {number} scaleMode - The scale mode of the texture. + * @param {number} resolution - The resolution of the texture. + * @return {PIXI.Texture} The new texture. + */ + + + Graphics.prototype.generateCanvasTexture = function generateCanvasTexture(scaleMode) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + var bounds = this.getLocalBounds(); + + var canvasBuffer = _RenderTexture2.default.create(bounds.width, bounds.height, scaleMode, resolution); + + if (!canvasRenderer) { + canvasRenderer = new _CanvasRenderer2.default(); + } + + this.transform.updateLocalTransform(); + this.transform.localTransform.copy(tempMatrix); + + tempMatrix.invert(); + + tempMatrix.tx -= bounds.x; + tempMatrix.ty -= bounds.y; + + canvasRenderer.render(this, canvasBuffer, true, tempMatrix); + + var texture = _Texture2.default.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas, scaleMode, 'graphics'); + + texture.baseTexture.resolution = resolution; + texture.baseTexture.update(); + + return texture; + }; + + /** + * Closes the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.closePath = function closePath() { + // ok so close path assumes next one is a hole! + var currentPath = this.currentPath; + + if (currentPath && currentPath.shape) { + currentPath.shape.close(); + } + + return this; + }; + + /** + * Adds a hole in the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.addHole = function addHole() { + // this is a hole! + var hole = this.graphicsData.pop(); + + this.currentPath = this.graphicsData[this.graphicsData.length - 1]; + + this.currentPath.addHole(hole.shape); + this.currentPath = null; + + return this; + }; + + /** + * Destroys the Graphics object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Graphics.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._webgl) { + for (var j = 0; j < this._webgl[id].data.length; ++j) { + this._webgl[id].data[j].destroy(); + } + } + + if (this._spriteRect) { + this._spriteRect.destroy(); + } + + this.graphicsData = null; + + this.currentPath = null; + this._webgl = null; + this._localBounds = null; + }; + + return Graphics; +}(_Container3.default); + +exports.default = Graphics; + + +Graphics._SPRITE_TEXTURE = null; + +},{"../const":46,"../display/Bounds":47,"../display/Container":48,"../math":70,"../renderers/canvas/CanvasRenderer":77,"../sprites/Sprite":102,"../textures/RenderTexture":113,"../textures/Texture":115,"../utils":124,"./GraphicsData":54,"./utils/bezierCurveTo":56}],54:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + */ +var GraphicsData = function () { + /** + * + * @param {number} lineWidth - the width of the line to draw + * @param {number} lineColor - the color of the line to draw + * @param {number} lineAlpha - the alpha of the line to draw + * @param {number} fillColor - the color of the fill + * @param {number} fillAlpha - the alpha of the fill + * @param {boolean} fill - whether or not the shape is filled with a colour + * @param {boolean} nativeLines - the method for drawing lines + * @param {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} shape - The shape object to draw. + */ + function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, nativeLines, shape) { + _classCallCheck(this, GraphicsData); + + /** + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + /** + * @member {boolean} if true the liens will be draw using LINES instead of TRIANGLE_STRIP + */ + this.nativeLines = nativeLines; + + /** + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /** + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /** + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /** + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /** + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /** + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /** + * @member {boolean} whether or not the shape is filled with a colour + */ + this.fill = fill; + + this.holes = []; + + /** + * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} The shape object to draw. + */ + this.shape = shape; + + /** + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + } + + /** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {PIXI.GraphicsData} Cloned GraphicsData object + */ + + + GraphicsData.prototype.clone = function clone() { + return new GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.fill, this.nativeLines, this.shape); + }; + + /** + * Adds a hole to the shape. + * + * @param {PIXI.Rectangle|PIXI.Circle} shape - The shape of the hole. + */ + + + GraphicsData.prototype.addHole = function addHole(shape) { + this.holes.push(shape); + }; + + /** + * Destroys the Graphics data. + */ + + + GraphicsData.prototype.destroy = function destroy() { + this.shape = null; + this.holes = null; + }; + + return GraphicsData; +}(); + +exports.default = GraphicsData; + +},{}],55:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they + * now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasGraphicsRenderer: + * https://github.com/libgdx/libgdx/blob/1.0.0/gdx/src/com/badlogic/gdx/graphics/glutils/ShapeRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching graphics objects. + * + * @class + * @private + * @memberof PIXI + */ +var CanvasGraphicsRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The current PIXI renderer. + */ + function CanvasGraphicsRenderer(renderer) { + _classCallCheck(this, CanvasGraphicsRenderer); + + this.renderer = renderer; + } + + /** + * Renders a Graphics object to a canvas. + * + * @param {PIXI.Graphics} graphics - the actual graphics object to render + */ + + + CanvasGraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var context = renderer.context; + var worldAlpha = graphics.worldAlpha; + var transform = graphics.transform.worldTransform; + var resolution = renderer.resolution; + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) { + this.dirty = true; + } + + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + if (graphics.dirty) { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + renderer.setBlendMode(graphics.blendMode); + + for (var i = 0; i < graphics.graphicsData.length; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === _const.SHAPES.POLY) { + context.beginPath(); + + this.renderPolygon(shape.points, shape.closed, context); + + for (var j = 0; j < data.holes.length; j++) { + this.renderPolygon(data.holes[j].points, true, context); + } + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RECT) { + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + context.beginPath(); + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + }; + + /** + * Updates the tint of a graphics object + * + * @private + * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated + */ + + + CanvasGraphicsRenderer.prototype.updateGraphicsTint = function updateGraphicsTint(graphics) { + graphics._prevTint = graphics.tint; + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF) / 255; + + for (var i = 0; i < graphics.graphicsData.length; ++i) { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + // super inline cos im an optimization NAZI :) + data._fillTint = ((fillColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (fillColor & 0xFF) / 255 * tintB * 255; + + data._lineTint = ((lineColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (lineColor & 0xFF) / 255 * tintB * 255; + } + }; + + /** + * Renders a polygon. + * + * @param {PIXI.Point[]} points - The points to render + * @param {boolean} close - Should the polygon be closed + * @param {CanvasRenderingContext2D} context - The rendering context to use + */ + + + CanvasGraphicsRenderer.prototype.renderPolygon = function renderPolygon(points, close, context) { + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; ++j) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (close) { + context.closePath(); + } + }; + + /** + * destroy graphics object + * + */ + + + CanvasGraphicsRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasGraphicsRenderer; +}(); + +exports.default = CanvasGraphicsRenderer; + + +_CanvasRenderer2.default.registerPlugin('graphics', CanvasGraphicsRenderer); + +},{"../../const":46,"../../renderers/canvas/CanvasRenderer":77}],56:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = bezierCurveTo; +/** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [path=[]] - Path array to push points into + * @return {number[]} Array of points of the curve + */ +function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var path = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : []; + + var n = 20; + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + + path.push(fromX, fromY); + + for (var i = 1, j = 0; i <= n; ++i) { + j = i / n; + + dt = 1 - j; + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + path.push(dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + return path; +} + +},{}],57:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _WebGLGraphicsData = require('./WebGLGraphicsData'); + +var _WebGLGraphicsData2 = _interopRequireDefault(_WebGLGraphicsData); + +var _PrimitiveShader = require('./shaders/PrimitiveShader'); + +var _PrimitiveShader2 = _interopRequireDefault(_PrimitiveShader); + +var _buildPoly = require('./utils/buildPoly'); + +var _buildPoly2 = _interopRequireDefault(_buildPoly); + +var _buildRectangle = require('./utils/buildRectangle'); + +var _buildRectangle2 = _interopRequireDefault(_buildRectangle); + +var _buildRoundedRectangle = require('./utils/buildRoundedRectangle'); + +var _buildRoundedRectangle2 = _interopRequireDefault(_buildRoundedRectangle); + +var _buildCircle = require('./utils/buildCircle'); + +var _buildCircle2 = _interopRequireDefault(_buildCircle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Renders the graphics object. + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var GraphicsRenderer = function (_ObjectRenderer) { + _inherits(GraphicsRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this object renderer works for. + */ + function GraphicsRenderer(renderer) { + _classCallCheck(this, GraphicsRenderer); + + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.graphicsDataPool = []; + + _this.primitiveShader = null; + + _this.gl = renderer.gl; + + // easy access! + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * Called when there is a WebGL context change + * + * @private + * + */ + + + GraphicsRenderer.prototype.onContextChange = function onContextChange() { + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.primitiveShader = new _PrimitiveShader2.default(this.gl); + }; + + /** + * Destroys this renderer. + * + */ + + + GraphicsRenderer.prototype.destroy = function destroy() { + _ObjectRenderer3.default.prototype.destroy.call(this); + + for (var i = 0; i < this.graphicsDataPool.length; ++i) { + this.graphicsDataPool[i].destroy(); + } + + this.graphicsDataPool = null; + }; + + /** + * Renders a graphics object. + * + * @param {PIXI.Graphics} graphics - The graphics object to render. + */ + + + GraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var gl = renderer.gl; + + var webGLData = void 0; + var webGL = graphics._webGL[this.CONTEXT_UID]; + + if (!webGL || graphics.dirty !== webGL.dirty) { + this.updateGraphics(graphics); + + webGL = graphics._webGL[this.CONTEXT_UID]; + } + + // This could be speeded up for sure! + var shader = this.primitiveShader; + + renderer.bindShader(shader); + renderer.state.setBlendMode(graphics.blendMode); + + for (var i = 0, n = webGL.data.length; i < n; i++) { + webGLData = webGL.data[i]; + var shaderTemp = webGLData.shader; + + renderer.bindShader(shaderTemp); + shaderTemp.uniforms.translationMatrix = graphics.transform.worldTransform.toArray(true); + shaderTemp.uniforms.tint = (0, _utils.hex2rgb)(graphics.tint); + shaderTemp.uniforms.alpha = graphics.worldAlpha; + + renderer.bindVao(webGLData.vao); + + if (webGLData.nativeLines) { + gl.drawArrays(gl.LINES, 0, webGLData.points.length / 6); + } else { + webGLData.vao.draw(gl.TRIANGLE_STRIP, webGLData.indices.length); + } + } + }; + + /** + * Updates the graphics object + * + * @private + * @param {PIXI.Graphics} graphics - The graphics object to update + */ + + + GraphicsRenderer.prototype.updateGraphics = function updateGraphics(graphics) { + var gl = this.renderer.gl; + + // get the contexts graphics object + var webGL = graphics._webGL[this.CONTEXT_UID]; + + // if the graphics object does not exist in the webGL context time to create it! + if (!webGL) { + webGL = graphics._webGL[this.CONTEXT_UID] = { lastIndex: 0, data: [], gl: gl, clearDirty: -1, dirty: -1 }; + } + + // flag the graphics as not dirty as we are about to update it... + webGL.dirty = graphics.dirty; + + // if the user cleared the graphics object we will need to clear every object + if (graphics.clearDirty !== webGL.clearDirty) { + webGL.clearDirty = graphics.clearDirty; + + // loop through and return all the webGLDatas to the object pool so than can be reused later on + for (var i = 0; i < webGL.data.length; i++) { + this.graphicsDataPool.push(webGL.data[i]); + } + + // clear the array and reset the index.. + webGL.data.length = 0; + webGL.lastIndex = 0; + } + + var webGLData = void 0; + var webGLDataNativeLines = void 0; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (var _i = webGL.lastIndex; _i < graphics.graphicsData.length; _i++) { + var data = graphics.graphicsData[_i]; + + // TODO - this can be simplified + webGLData = this.getWebGLData(webGL, 0); + + if (data.nativeLines && data.lineWidth) { + webGLDataNativeLines = this.getWebGLData(webGL, 0, true); + webGL.lastIndex++; + } + + if (data.type === _const.SHAPES.POLY) { + (0, _buildPoly2.default)(data, webGLData, webGLDataNativeLines); + } + if (data.type === _const.SHAPES.RECT) { + (0, _buildRectangle2.default)(data, webGLData, webGLDataNativeLines); + } else if (data.type === _const.SHAPES.CIRC || data.type === _const.SHAPES.ELIP) { + (0, _buildCircle2.default)(data, webGLData, webGLDataNativeLines); + } else if (data.type === _const.SHAPES.RREC) { + (0, _buildRoundedRectangle2.default)(data, webGLData, webGLDataNativeLines); + } + + webGL.lastIndex++; + } + + this.renderer.bindVao(null); + + // upload all the dirty data... + for (var _i2 = 0; _i2 < webGL.data.length; _i2++) { + webGLData = webGL.data[_i2]; + + if (webGLData.dirty) { + webGLData.upload(); + } + } + }; + + /** + * + * @private + * @param {WebGLRenderingContext} gl - the current WebGL drawing context + * @param {number} type - TODO @Alvin + * @param {number} nativeLines - indicate whether the webGLData use for nativeLines. + * @return {*} TODO + */ + + + GraphicsRenderer.prototype.getWebGLData = function getWebGLData(gl, type, nativeLines) { + var webGLData = gl.data[gl.data.length - 1]; + + if (!webGLData || webGLData.nativeLines !== nativeLines || webGLData.points.length > 320000) { + webGLData = this.graphicsDataPool.pop() || new _WebGLGraphicsData2.default(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData.nativeLines = nativeLines; + webGLData.reset(type); + gl.data.push(webGLData); + } + + webGLData.dirty = true; + + return webGLData; + }; + + return GraphicsRenderer; +}(_ObjectRenderer3.default); + +exports.default = GraphicsRenderer; + + +_WebGLRenderer2.default.registerPlugin('graphics', GraphicsRenderer); + +},{"../../const":46,"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../utils":124,"./WebGLGraphicsData":58,"./shaders/PrimitiveShader":59,"./utils/buildCircle":60,"./utils/buildPoly":62,"./utils/buildRectangle":63,"./utils/buildRoundedRectangle":64}],58:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * An object containing WebGL specific properties to be used by the WebGL renderer + * + * @class + * @private + * @memberof PIXI + */ +var WebGLGraphicsData = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {PIXI.Shader} shader - The shader + * @param {object} attribsState - The state for the VAO + */ + function WebGLGraphicsData(gl, shader, attribsState) { + _classCallCheck(this, WebGLGraphicsData); + + /** + * The current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // TODO does this need to be split before uploading?? + /** + * An array of color components (r,g,b) + * @member {number[]} + */ + this.color = [0, 0, 0]; // color split! + + /** + * An array of points to draw + * @member {PIXI.Point[]} + */ + this.points = []; + + /** + * The indices of the vertices + * @member {number[]} + */ + this.indices = []; + /** + * The main buffer + * @member {WebGLBuffer} + */ + this.buffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl); + + /** + * The index buffer + * @member {WebGLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl); + + /** + * Whether this graphics is dirty or not + * @member {boolean} + */ + this.dirty = true; + + /** + * Whether this graphics is nativeLines or not + * @member {boolean} + */ + this.nativeLines = false; + + this.glPoints = null; + this.glIndices = null; + + /** + * + * @member {PIXI.Shader} + */ + this.shader = shader; + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, attribsState).addIndex(this.indexBuffer).addAttribute(this.buffer, shader.attributes.aVertexPosition, gl.FLOAT, false, 4 * 6, 0).addAttribute(this.buffer, shader.attributes.aColor, gl.FLOAT, false, 4 * 6, 2 * 4); + } + + /** + * Resets the vertices and the indices + */ + + + WebGLGraphicsData.prototype.reset = function reset() { + this.points.length = 0; + this.indices.length = 0; + }; + + /** + * Binds the buffers and uploads the data + */ + + + WebGLGraphicsData.prototype.upload = function upload() { + this.glPoints = new Float32Array(this.points); + this.buffer.upload(this.glPoints); + + this.glIndices = new Uint16Array(this.indices); + this.indexBuffer.upload(this.glIndices); + + this.dirty = false; + }; + + /** + * Empties all the data + */ + + + WebGLGraphicsData.prototype.destroy = function destroy() { + this.color = null; + this.points = null; + this.indices = null; + + this.vao.destroy(); + this.buffer.destroy(); + this.indexBuffer.destroy(); + + this.gl = null; + + this.buffer = null; + this.indexBuffer = null; + + this.glPoints = null; + this.glIndices = null; + }; + + return WebGLGraphicsData; +}(); + +exports.default = WebGLGraphicsData; + +},{"pixi-gl-core":12}],59:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../../Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. + * + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ +var PrimitiveShader = function (_Shader) { + _inherits(PrimitiveShader, _Shader); + + /** + * @param {WebGLRenderingContext} gl - The webgl shader manager this shader works for. + */ + function PrimitiveShader(gl) { + _classCallCheck(this, PrimitiveShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec4 aColor;', 'uniform mat3 translationMatrix;', 'uniform mat3 projectionMatrix;', 'uniform float alpha;', 'uniform vec3 tint;', 'varying vec4 vColor;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vColor = aColor * vec4(tint * alpha, alpha);', '}'].join('\n'), + // fragment shader + ['varying vec4 vColor;', 'void main(void){', ' gl_FragColor = vColor;', '}'].join('\n'))); + } + + return PrimitiveShader; +}(_Shader3.default); + +exports.default = PrimitiveShader; + +},{"../../../Shader":44}],60:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildCircle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _const = require('../../../const'); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildCircle(graphicsData, webGLData, webGLDataNativeLines) { + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width = void 0; + var height = void 0; + + // TODO - bit hacky?? + if (graphicsData.type === _const.SHAPES.CIRC) { + width = circleData.radius; + height = circleData.radius; + } else { + width = circleData.width; + height = circleData.height; + } + + if (width === 0 || height === 0) { + return; + } + + var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); + + var seg = Math.PI * 2 / totalSegs; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + indices.push(vecPos); + + for (var i = 0; i < totalSegs + 1; i++) { + verts.push(x, y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos - 1); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (var _i = 0; _i < totalSegs + 1; _i++) { + graphicsData.points.push(x + Math.sin(seg * _i) * width, y + Math.cos(seg * _i) * height); + } + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +},{"../../../const":46,"../../../utils":124,"./buildLine":61}],61:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function (graphicsData, webGLData, webGLDataNativeLines) { + if (graphicsData.nativeLines) { + buildNativeLine(graphicsData, webGLDataNativeLines); + } else { + buildLine(graphicsData, webGLData); + } +}; + +var _math = require('../../../math'); + +var _utils = require('../../../utils'); + +/** + * Builds a line to draw using the poligon method. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildLine(graphicsData, webGLData) { + // TODO OPTIMISE! + var points = graphicsData.points; + + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + + // get first and last point.. figure out the middle! + var firstPoint = new _math.Point(points[0], points[1]); + var lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + // if the first point is the last point - gonna have issues :) + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var p1x = points[0]; + var p1y = points[1]; + var p2x = points[2]; + var p2y = points[3]; + var p3x = 0; + var p3y = 0; + + var perpx = -(p1y - p2y); + var perpy = p1x - p2x; + var perp2x = 0; + var perp2y = 0; + var perp3x = 0; + var perp3y = 0; + + var dist = Math.sqrt(perpx * perpx + perpy * perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx, p1y - perpy, r, g, b, alpha); + + verts.push(p1x + perpx, p1y + perpy, r, g, b, alpha); + + for (var i = 1; i < length - 1; ++i) { + p1x = points[(i - 1) * 2]; + p1y = points[(i - 1) * 2 + 1]; + + p2x = points[i * 2]; + p2y = points[i * 2 + 1]; + + p3x = points[(i + 1) * 2]; + p3y = points[(i + 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + var a1 = -perpy + p1y - (-perpy + p2y); + var b1 = -perpx + p2x - (-perpx + p1x); + var c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + var a2 = -perp2y + p3y - (-perp2y + p2y); + var b2 = -perp2x + p2x - (-perp2x + p3x); + var c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + var denom = a1 * b2 - a2 * b1; + + if (Math.abs(denom) < 0.1) { + denom += 10.1; + verts.push(p2x - perpx, p2y - perpy, r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy, r, g, b, alpha); + + continue; + } + + var px = (b1 * c2 - b2 * c1) / denom; + var py = (a2 * c1 - a1 * c2) / denom; + var pdist = (px - p2x) * (px - p2x) + (py - p2y) * (py - p2y); + + if (pdist > 196 * width * width) { + perp3x = perpx - perp2x; + perp3y = perpy - perp2y; + + dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y); + perp3x /= dist; + perp3y /= dist; + perp3x *= width; + perp3y *= width; + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x + perp3x, p2y + perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + indexCount++; + } else { + verts.push(px, py); + verts.push(r, g, b, alpha); + + verts.push(p2x - (px - p2x), p2y - (py - p2y)); + verts.push(r, g, b, alpha); + } + } + + p1x = points[(length - 2) * 2]; + p1y = points[(length - 2) * 2 + 1]; + + p2x = points[(length - 1) * 2]; + p2y = points[(length - 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + verts.push(p2x - perpx, p2y - perpy); + verts.push(r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy); + verts.push(r, g, b, alpha); + + indices.push(indexStart); + + for (var _i = 0; _i < indexCount; ++_i) { + indices.push(indexStart++); + } + + indices.push(indexStart - 1); +} + +/** + * Builds a line to draw using the gl.drawArrays(gl.LINES) method + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ + + +/** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildNativeLine(graphicsData, webGLData) { + var i = 0; + var points = graphicsData.points; + + if (points.length === 0) return; + + var verts = webGLData.points; + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + for (i = 1; i < length; i++) { + var p1x = points[(i - 1) * 2]; + var p1y = points[(i - 1) * 2 + 1]; + + var p2x = points[i * 2]; + var p2y = points[i * 2 + 1]; + + verts.push(p1x, p1y); + verts.push(r, g, b, alpha); + + verts.push(p2x, p2y); + verts.push(r, g, b, alpha); + } +} + +},{"../../../math":70,"../../../utils":124}],62:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildPoly; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildPoly(graphicsData, webGLData, webGLDataNativeLines) { + graphicsData.points = graphicsData.shape.points.slice(); + + var points = graphicsData.points; + + if (graphicsData.fill && points.length >= 6) { + var holeArray = []; + // Process holes.. + var holes = graphicsData.holes; + + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + + holeArray.push(points.length / 2); + + points = points.concat(hole.points); + } + + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = (0, _earcut2.default)(points, holeArray, 2); + + if (!triangles) { + return; + } + + var vertPos = verts.length / 6; + + for (var _i = 0; _i < triangles.length; _i += 3) { + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i + 1] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + } + + for (var _i2 = 0; _i2 < length; _i2++) { + verts.push(points[_i2 * 2], points[_i2 * 2 + 1], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth > 0) { + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + } +} + +},{"../../../utils":124,"./buildLine":61,"earcut":2}],63:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRectangle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildRectangle(graphicsData, webGLData, webGLDataNativeLines) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vertPos = verts.length / 6; + + // start + verts.push(x, y); + verts.push(r, g, b, alpha); + + verts.push(x + width, y); + verts.push(r, g, b, alpha); + + verts.push(x, y + height); + verts.push(r, g, b, alpha); + + verts.push(x + width, y + height); + verts.push(r, g, b, alpha); + + // insert 2 dead triangles.. + indices.push(vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y]; + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +},{"../../../utils":124,"./buildLine":61}],64:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRoundedRectangle; + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildRoundedRectangle(graphicsData, webGLData, webGLDataNativeLines) { + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + + recPoints.push(x, y + radius); + quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height, recPoints); + quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius, recPoints); + quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y, recPoints); + quadraticBezierCurve(x + radius, y, x, y, x, y + radius + 0.0000000001, recPoints); + + // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. + // TODO - fix this properly, this is not very elegant.. but it works for now. + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + var triangles = (0, _earcut2.default)(recPoints, null, 2); + + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + + for (var _i = 0, _j = recPoints.length; _i < _j; _i++) { + verts.push(recPoints[_i], recPoints[++_i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +/** + * Calculate a single point for a quadratic bezier curve. + * Utility function used by quadraticBezierCurve. + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} n1 - first number + * @param {number} n2 - second number + * @param {number} perc - percentage + * @return {number} the result + * + */ +function getPt(n1, n2, perc) { + var diff = n2 - n1; + + return n1 + diff * perc; +} + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @return {number[]} an array of points + */ +function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY) { + var out = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : []; + + var n = 20; + var points = out; + + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + + points.push(x, y); + } + + return points; +} + +},{"../../../utils":124,"./buildLine":61,"earcut":2}],65:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = exports.Application = exports.Filter = exports.SpriteMaskFilter = exports.Quad = exports.RenderTarget = exports.ObjectRenderer = exports.WebGLManager = exports.Shader = exports.CanvasRenderTarget = exports.TextureUvs = exports.VideoBaseTexture = exports.BaseRenderTexture = exports.RenderTexture = exports.BaseTexture = exports.Texture = exports.Spritesheet = exports.CanvasGraphicsRenderer = exports.GraphicsRenderer = exports.GraphicsData = exports.Graphics = exports.TextMetrics = exports.TextStyle = exports.Text = exports.SpriteRenderer = exports.CanvasTinter = exports.CanvasSpriteRenderer = exports.Sprite = exports.TransformBase = exports.TransformStatic = exports.Transform = exports.Container = exports.DisplayObject = exports.Bounds = exports.glCore = exports.WebGLRenderer = exports.CanvasRenderer = exports.ticker = exports.utils = exports.settings = undefined; + +var _const = require('./const'); + +Object.keys(_const).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _const[key]; + } + }); +}); + +var _math = require('./math'); + +Object.keys(_math).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _math[key]; + } + }); +}); + +var _pixiGlCore = require('pixi-gl-core'); + +Object.defineProperty(exports, 'glCore', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_pixiGlCore).default; + } +}); + +var _Bounds = require('./display/Bounds'); + +Object.defineProperty(exports, 'Bounds', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Bounds).default; + } +}); + +var _DisplayObject = require('./display/DisplayObject'); + +Object.defineProperty(exports, 'DisplayObject', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplayObject).default; + } +}); + +var _Container = require('./display/Container'); + +Object.defineProperty(exports, 'Container', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Container).default; + } +}); + +var _Transform = require('./display/Transform'); + +Object.defineProperty(exports, 'Transform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Transform).default; + } +}); + +var _TransformStatic = require('./display/TransformStatic'); + +Object.defineProperty(exports, 'TransformStatic', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformStatic).default; + } +}); + +var _TransformBase = require('./display/TransformBase'); + +Object.defineProperty(exports, 'TransformBase', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformBase).default; + } +}); + +var _Sprite = require('./sprites/Sprite'); + +Object.defineProperty(exports, 'Sprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Sprite).default; + } +}); + +var _CanvasSpriteRenderer = require('./sprites/canvas/CanvasSpriteRenderer'); + +Object.defineProperty(exports, 'CanvasSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasSpriteRenderer).default; + } +}); + +var _CanvasTinter = require('./sprites/canvas/CanvasTinter'); + +Object.defineProperty(exports, 'CanvasTinter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasTinter).default; + } +}); + +var _SpriteRenderer = require('./sprites/webgl/SpriteRenderer'); + +Object.defineProperty(exports, 'SpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteRenderer).default; + } +}); + +var _Text = require('./text/Text'); + +Object.defineProperty(exports, 'Text', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Text).default; + } +}); + +var _TextStyle = require('./text/TextStyle'); + +Object.defineProperty(exports, 'TextStyle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextStyle).default; + } +}); + +var _TextMetrics = require('./text/TextMetrics'); + +Object.defineProperty(exports, 'TextMetrics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextMetrics).default; + } +}); + +var _Graphics = require('./graphics/Graphics'); + +Object.defineProperty(exports, 'Graphics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Graphics).default; + } +}); + +var _GraphicsData = require('./graphics/GraphicsData'); + +Object.defineProperty(exports, 'GraphicsData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsData).default; + } +}); + +var _GraphicsRenderer = require('./graphics/webgl/GraphicsRenderer'); + +Object.defineProperty(exports, 'GraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsRenderer).default; + } +}); + +var _CanvasGraphicsRenderer = require('./graphics/canvas/CanvasGraphicsRenderer'); + +Object.defineProperty(exports, 'CanvasGraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasGraphicsRenderer).default; + } +}); + +var _Spritesheet = require('./textures/Spritesheet'); + +Object.defineProperty(exports, 'Spritesheet', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Spritesheet).default; + } +}); + +var _Texture = require('./textures/Texture'); + +Object.defineProperty(exports, 'Texture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Texture).default; + } +}); + +var _BaseTexture = require('./textures/BaseTexture'); + +Object.defineProperty(exports, 'BaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseTexture).default; + } +}); + +var _RenderTexture = require('./textures/RenderTexture'); + +Object.defineProperty(exports, 'RenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTexture).default; + } +}); + +var _BaseRenderTexture = require('./textures/BaseRenderTexture'); + +Object.defineProperty(exports, 'BaseRenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseRenderTexture).default; + } +}); + +var _VideoBaseTexture = require('./textures/VideoBaseTexture'); + +Object.defineProperty(exports, 'VideoBaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VideoBaseTexture).default; + } +}); + +var _TextureUvs = require('./textures/TextureUvs'); + +Object.defineProperty(exports, 'TextureUvs', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureUvs).default; + } +}); + +var _CanvasRenderTarget = require('./renderers/canvas/utils/CanvasRenderTarget'); + +Object.defineProperty(exports, 'CanvasRenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasRenderTarget).default; + } +}); + +var _Shader = require('./Shader'); + +Object.defineProperty(exports, 'Shader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Shader).default; + } +}); + +var _WebGLManager = require('./renderers/webgl/managers/WebGLManager'); + +Object.defineProperty(exports, 'WebGLManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLManager).default; + } +}); + +var _ObjectRenderer = require('./renderers/webgl/utils/ObjectRenderer'); + +Object.defineProperty(exports, 'ObjectRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObjectRenderer).default; + } +}); + +var _RenderTarget = require('./renderers/webgl/utils/RenderTarget'); + +Object.defineProperty(exports, 'RenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTarget).default; + } +}); + +var _Quad = require('./renderers/webgl/utils/Quad'); + +Object.defineProperty(exports, 'Quad', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Quad).default; + } +}); + +var _SpriteMaskFilter = require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter'); + +Object.defineProperty(exports, 'SpriteMaskFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteMaskFilter).default; + } +}); + +var _Filter = require('./renderers/webgl/filters/Filter'); + +Object.defineProperty(exports, 'Filter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Filter).default; + } +}); + +var _Application = require('./Application'); + +Object.defineProperty(exports, 'Application', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Application).default; + } +}); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +Object.defineProperty(exports, 'autoDetectRenderer', { + enumerable: true, + get: function get() { + return _autoDetectRenderer.autoDetectRenderer; + } +}); + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _ticker = require('./ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.settings = _settings2.default; +exports.utils = utils; +exports.ticker = ticker; +exports.CanvasRenderer = _CanvasRenderer2.default; +exports.WebGLRenderer = _WebGLRenderer2.default; /** + * @namespace PIXI + */ + +},{"./Application":43,"./Shader":44,"./autoDetectRenderer":45,"./const":46,"./display/Bounds":47,"./display/Container":48,"./display/DisplayObject":49,"./display/Transform":50,"./display/TransformBase":51,"./display/TransformStatic":52,"./graphics/Graphics":53,"./graphics/GraphicsData":54,"./graphics/canvas/CanvasGraphicsRenderer":55,"./graphics/webgl/GraphicsRenderer":57,"./math":70,"./renderers/canvas/CanvasRenderer":77,"./renderers/canvas/utils/CanvasRenderTarget":79,"./renderers/webgl/WebGLRenderer":84,"./renderers/webgl/filters/Filter":86,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":89,"./renderers/webgl/managers/WebGLManager":93,"./renderers/webgl/utils/ObjectRenderer":94,"./renderers/webgl/utils/Quad":95,"./renderers/webgl/utils/RenderTarget":96,"./settings":101,"./sprites/Sprite":102,"./sprites/canvas/CanvasSpriteRenderer":103,"./sprites/canvas/CanvasTinter":104,"./sprites/webgl/SpriteRenderer":106,"./text/Text":108,"./text/TextMetrics":109,"./text/TextStyle":110,"./textures/BaseRenderTexture":111,"./textures/BaseTexture":112,"./textures/RenderTexture":113,"./textures/Spritesheet":114,"./textures/Texture":115,"./textures/TextureUvs":116,"./textures/VideoBaseTexture":117,"./ticker":120,"./utils":124,"pixi-gl-core":12}],66:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Matrix = require('./Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16 + +var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; +var tempMatrices = []; + +var mul = []; + +function signum(x) { + if (x < 0) { + return -1; + } + if (x > 0) { + return 1; + } + + return 0; +} + +function init() { + for (var i = 0; i < 16; i++) { + var row = []; + + mul.push(row); + + for (var j = 0; j < 16; j++) { + var _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); + var _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); + var _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); + var _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); + + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + + for (var _i = 0; _i < 16; _i++) { + var mat = new _Matrix2.default(); + + mat.set(ux[_i], uy[_i], vx[_i], vy[_i], 0, 0); + tempMatrices.push(mat); + } +} + +init(); + +/** + * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, + * D8 is the same but with diagonals. Used for texture rotations. + * + * Vector xX(i), xY(i) is U-axis of sprite with rotation i + * Vector yY(i), yY(i) is V-axis of sprite with rotation i + * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) + * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) + * This is the small part of gameofbombs.com portal system. It works. + * + * @author Ivan @ivanpopelyshev + * @class + * @memberof PIXI + */ +var GroupD8 = { + E: 0, + SE: 1, + S: 2, + SW: 3, + W: 4, + NW: 5, + N: 6, + NE: 7, + MIRROR_VERTICAL: 8, + MIRROR_HORIZONTAL: 12, + uX: function uX(ind) { + return ux[ind]; + }, + uY: function uY(ind) { + return uy[ind]; + }, + vX: function vX(ind) { + return vx[ind]; + }, + vY: function vY(ind) { + return vy[ind]; + }, + inv: function inv(rotation) { + if (rotation & 8) { + return rotation & 15; + } + + return -rotation & 7; + }, + add: function add(rotationSecond, rotationFirst) { + return mul[rotationSecond][rotationFirst]; + }, + sub: function sub(rotationSecond, rotationFirst) { + return mul[rotationSecond][GroupD8.inv(rotationFirst)]; + }, + + /** + * Adds 180 degrees to rotation. Commutative operation. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to rotate. + * @returns {number} rotated number + */ + rotate180: function rotate180(rotation) { + return rotation ^ 4; + }, + + /** + * I dont know why sometimes width and heights needs to be swapped. We'll fix it later. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the width/height should be swapped. + */ + isSwapWidthHeight: function isSwapWidthHeight(rotation) { + return (rotation & 3) === 2; + }, + + /** + * @memberof PIXI.GroupD8 + * @param {number} dx - TODO + * @param {number} dy - TODO + * + * @return {number} TODO + */ + byDirection: function byDirection(dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return GroupD8.S; + } + + return GroupD8.N; + } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return GroupD8.E; + } + + return GroupD8.W; + } else if (dy > 0) { + if (dx > 0) { + return GroupD8.SE; + } + + return GroupD8.SW; + } else if (dx > 0) { + return GroupD8.NE; + } + + return GroupD8.NW; + }, + + /** + * Helps sprite to compensate texture packer rotation. + * + * @memberof PIXI.GroupD8 + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {number} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function matrixAppendRotationInv(matrix, rotation) { + var tx = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var ty = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + // Packer used "rotation", we use "inv(rotation)" + var mat = tempMatrices[GroupD8.inv(rotation)]; + + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + } +}; + +exports.default = GroupD8; + +},{"./Matrix":67}],67:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Point = require('./Point'); + +var _Point2 = _interopRequireDefault(_Point); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The PixiJS Matrix class as an object, which makes it a lot faster, + * here is a representation of it : + * | a | b | tx| + * | c | d | ty| + * | 0 | 0 | 1 | + * + * @class + * @memberof PIXI + */ +var Matrix = function () { + /** + * @param {number} [a=1] - x scale + * @param {number} [b=0] - y skew + * @param {number} [c=0] - x skew + * @param {number} [d=1] - y scale + * @param {number} [tx=0] - x translation + * @param {number} [ty=0] - y translation + */ + function Matrix() { + var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var d = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var tx = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var ty = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + + _classCallCheck(this, Matrix); + + /** + * @member {number} + * @default 1 + */ + this.a = a; + + /** + * @member {number} + * @default 0 + */ + this.b = b; + + /** + * @member {number} + * @default 0 + */ + this.c = c; + + /** + * @member {number} + * @default 1 + */ + this.d = d; + + /** + * @member {number} + * @default 0 + */ + this.tx = tx; + + /** + * @member {number} + * @default 0 + */ + this.ty = ty; + + this.array = null; + } + + /** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @param {number[]} array - The array that the matrix will be populated from. + */ + + + Matrix.prototype.fromArray = function fromArray(array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + }; + + /** + * sets the matrix properties + * + * @param {number} a - Matrix component + * @param {number} b - Matrix component + * @param {number} c - Matrix component + * @param {number} d - Matrix component + * @param {number} tx - Matrix component + * @param {number} ty - Matrix component + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.set = function set(a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + }; + + /** + * Creates an array from the current Matrix object. + * + * @param {boolean} transpose - Whether we need to transpose the matrix or not + * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out + * @return {number[]} the newly created array which contains the matrix + */ + + + Matrix.prototype.toArray = function toArray(transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + + var array = out || this.array; + + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + }; + + /** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, transformed through this matrix + */ + + + Matrix.prototype.apply = function apply(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; + + return newPos; + }; + + /** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, inverse-transformed through this matrix + */ + + + Matrix.prototype.applyInverse = function applyInverse(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var id = 1 / (this.a * this.d + this.c * -this.b); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + }; + + /** + * Translates the matrix on the x and y. + * + * @param {number} x How much to translate x by + * @param {number} y How much to translate y by + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.translate = function translate(x, y) { + this.tx += x; + this.ty += y; + + return this; + }; + + /** + * Applies a scale transformation to the matrix. + * + * @param {number} x The amount to scale horizontally + * @param {number} y The amount to scale vertically + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.scale = function scale(x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + }; + + /** + * Applies a rotation transformation to the matrix. + * + * @param {number} angle - The angle in radians. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.rotate = function rotate(angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos - this.b * sin; + this.b = a1 * sin + this.b * cos; + this.c = c1 * cos - this.d * sin; + this.d = c1 * sin + this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + }; + + /** + * Appends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to append. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.append = function append(matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + }; + + /** + * Sets the matrix based on all the available properties + * + * @param {number} x - Position on the x axis + * @param {number} y - Position on the y axis + * @param {number} pivotX - Pivot on the x axis + * @param {number} pivotY - Pivot on the y axis + * @param {number} scaleX - Scale on the x axis + * @param {number} scaleY - Scale on the y axis + * @param {number} rotation - Rotation in radians + * @param {number} skewX - Skew on the x axis + * @param {number} skewY - Skew on the y axis + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.setTransform = function setTransform(x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + var sr = Math.sin(rotation); + var cr = Math.cos(rotation); + var cy = Math.cos(skewY); + var sy = Math.sin(skewY); + var nsx = -Math.sin(skewX); + var cx = Math.cos(skewX); + + var a = cr * scaleX; + var b = sr * scaleX; + var c = -sr * scaleY; + var d = cr * scaleY; + + this.a = cy * a + sy * c; + this.b = cy * b + sy * d; + this.c = nsx * a + cx * c; + this.d = nsx * b + cx * d; + + this.tx = x + (pivotX * a + pivotY * c); + this.ty = y + (pivotX * b + pivotY * d); + + return this; + }; + + /** + * Prepends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to prepend + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.prepend = function prepend(matrix) { + var tx1 = this.tx; + + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + + this.a = a1 * matrix.a + this.b * matrix.c; + this.b = a1 * matrix.b + this.b * matrix.d; + this.c = c1 * matrix.a + this.d * matrix.c; + this.d = c1 * matrix.b + this.d * matrix.d; + } + + this.tx = tx1 * matrix.a + this.ty * matrix.c + matrix.tx; + this.ty = tx1 * matrix.b + this.ty * matrix.d + matrix.ty; + + return this; + }; + + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * + * @param {PIXI.Transform|PIXI.TransformStatic} transform - The transform to apply the properties to. + * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properties + */ + + + Matrix.prototype.decompose = function decompose(transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + + var skewX = -Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + + var delta = Math.abs(skewX + skewY); + + if (delta < 0.00001) { + transform.rotation = skewY; + + if (a < 0 && d >= 0) { + transform.rotation += transform.rotation <= 0 ? Math.PI : -Math.PI; + } + + transform.skew.x = transform.skew.y = 0; + } else { + transform.skew.x = skewX; + transform.skew.y = skewY; + } + + // next set scale + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); + + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; + + return transform; + }; + + /** + * Inverts this matrix + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.invert = function invert() { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1 * d1 - b1 * c1; + + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = (c1 * this.ty - d1 * tx1) / n; + this.ty = -(a1 * this.ty - b1 * tx1) / n; + + return this; + }; + + /** + * Resets this Matix to an identity (default) matrix. + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.identity = function identity() { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + + return this; + }; + + /** + * Creates a new Matrix object with the same values as this one. + * + * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. + */ + + + Matrix.prototype.clone = function clone() { + var matrix = new Matrix(); + + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * Changes the values of the given matrix to be the same as the ones in this matrix + * + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @return {PIXI.Matrix} The matrix given in parameter with its values updated. + */ + + + Matrix.prototype.copy = function copy(matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * A default (identity) matrix + * + * @static + * @const + */ + + + _createClass(Matrix, null, [{ + key: 'IDENTITY', + get: function get() { + return new Matrix(); + } + + /** + * A temp matrix + * + * @static + * @const + */ + + }, { + key: 'TEMP_MATRIX', + get: function get() { + return new Matrix(); + } + }]); + + return Matrix; +}(); + +exports.default = Matrix; + +},{"./Point":69}],68:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * An observable point is a point that triggers a callback when the point's position is changed. + * + * @class + * @memberof PIXI + */ +var ObservablePoint = function () { + /** + * @param {Function} cb - callback when changed + * @param {object} scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope) { + var x = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var y = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, ObservablePoint); + + this._x = x; + this._y = y; + + this.cb = cb; + this.scope = scope; + } + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + ObservablePoint.prototype.set = function set(x, y) { + var _x = x || 0; + var _y = y || (y !== 0 ? _x : 0); + + if (this._x !== _x || this._y !== _y) { + this._x = _x; + this._y = _y; + this.cb.call(this.scope); + } + }; + + /** + * Copies the data from another point + * + * @param {PIXI.Point|PIXI.ObservablePoint} point - point to copy from + */ + + + ObservablePoint.prototype.copy = function copy(point) { + if (this._x !== point.x || this._y !== point.y) { + this._x = point.x; + this._y = point.y; + this.cb.call(this.scope); + } + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + + _createClass(ObservablePoint, [{ + key: "x", + get: function get() { + return this._x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + } + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + }, { + key: "y", + get: function get() { + return this._y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + } + }]); + + return ObservablePoint; +}(); + +exports.default = ObservablePoint; + +},{}],69:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * + * @class + * @memberof PIXI + */ +var Point = function () { + /** + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function Point() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + + _classCallCheck(this, Point); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + } + + /** + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point + */ + + + Point.prototype.clone = function clone() { + return new Point(this.x, this.y); + }; + + /** + * Copies x and y from the given point + * + * @param {PIXI.Point} p - The point to copy. + */ + + + Point.prototype.copy = function copy(p) { + this.set(p.x, p.y); + }; + + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.Point} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + + + Point.prototype.equals = function equals(p) { + return p.x === this.x && p.y === this.y; + }; + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + Point.prototype.set = function set(x, y) { + this.x = x || 0; + this.y = y || (y !== 0 ? this.x : 0); + }; + + return Point; +}(); + +exports.default = Point; + +},{}],70:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('./Point'); + +Object.defineProperty(exports, 'Point', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Point).default; + } +}); + +var _ObservablePoint = require('./ObservablePoint'); + +Object.defineProperty(exports, 'ObservablePoint', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObservablePoint).default; + } +}); + +var _Matrix = require('./Matrix'); + +Object.defineProperty(exports, 'Matrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Matrix).default; + } +}); + +var _GroupD = require('./GroupD8'); + +Object.defineProperty(exports, 'GroupD8', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GroupD).default; + } +}); + +var _Circle = require('./shapes/Circle'); + +Object.defineProperty(exports, 'Circle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Circle).default; + } +}); + +var _Ellipse = require('./shapes/Ellipse'); + +Object.defineProperty(exports, 'Ellipse', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Ellipse).default; + } +}); + +var _Polygon = require('./shapes/Polygon'); + +Object.defineProperty(exports, 'Polygon', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Polygon).default; + } +}); + +var _Rectangle = require('./shapes/Rectangle'); + +Object.defineProperty(exports, 'Rectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rectangle).default; + } +}); + +var _RoundedRectangle = require('./shapes/RoundedRectangle'); + +Object.defineProperty(exports, 'RoundedRectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RoundedRectangle).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./GroupD8":66,"./Matrix":67,"./ObservablePoint":68,"./Point":69,"./shapes/Circle":71,"./shapes/Ellipse":72,"./shapes/Polygon":73,"./shapes/Rectangle":74,"./shapes/RoundedRectangle":75}],71:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Circle object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Circle = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [radius=0] - The radius of the circle + */ + function Circle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var radius = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + _classCallCheck(this, Circle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.CIRC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.CIRC; + } + + /** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ + + + Circle.prototype.clone = function clone() { + return new Circle(this.x, this.y, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this circle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Circle + */ + + + Circle.prototype.contains = function contains(x, y) { + if (this.radius <= 0) { + return false; + } + + var r2 = this.radius * this.radius; + var dx = this.x - x; + var dy = this.y - y; + + dx *= dx; + dy *= dy; + + return dx + dy <= r2; + }; + + /** + * Returns the framing rectangle of the circle as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Circle.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + + return Circle; +}(); + +exports.default = Circle; + +},{"../../const":46,"./Rectangle":74}],72:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Ellipse object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Ellipse = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [width=0] - The half width of this ellipse + * @param {number} [height=0] - The half height of this ellipse + */ + function Ellipse() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Ellipse); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.ELIP + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.ELIP; + } + + /** + * Creates a clone of this Ellipse instance + * + * @return {PIXI.Ellipse} a copy of the ellipse + */ + + + Ellipse.prototype.clone = function clone() { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coords are within this ellipse + */ + + + Ellipse.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + // normalize the coords to an ellipse with center 0,0 + var normx = (x - this.x) / this.width; + var normy = (y - this.y) / this.height; + + normx *= normx; + normy *= normy; + + return normx + normy <= 1; + }; + + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Ellipse.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.width, this.y - this.height, this.width, this.height); + }; + + return Ellipse; +}(); + +exports.default = Ellipse; + +},{"../../const":46,"./Rectangle":74}],73:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('../Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Polygon = function () { + /** + * @param {PIXI.Point[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + for (var _len = arguments.length, points = Array(_len), _key = 0; _key < _len; _key++) { + points[_key] = arguments[_key]; + } + + _classCallCheck(this, Polygon); + + if (Array.isArray(points[0])) { + points = points[0]; + } + + // if this is an array of points, convert it to a flat array of numbers + if (points[0] instanceof _Point2.default) { + var p = []; + + for (var i = 0, il = points.length; i < il; i++) { + p.push(points[i].x, points[i].y); + } + + points = p; + } + + this.closed = true; + + /** + * An array of the points of this polygon + * + * @member {number[]} + */ + this.points = points; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.POLY + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.POLY; + } + + /** + * Creates a clone of this polygon + * + * @return {PIXI.Polygon} a copy of the polygon + */ + + + Polygon.prototype.clone = function clone() { + return new Polygon(this.points.slice()); + }; + + /** + * Closes the polygon, adding points if necessary. + * + */ + + + Polygon.prototype.close = function close() { + var points = this.points; + + // close the poly if the value is true! + if (points[0] !== points[points.length - 2] || points[1] !== points[points.length - 1]) { + points.push(points[0], points[1]); + } + }; + + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this polygon + */ + + + Polygon.prototype.contains = function contains(x, y) { + var inside = false; + + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + + for (var i = 0, j = length - 1; i < length; j = i++) { + var xi = this.points[i * 2]; + var yi = this.points[i * 2 + 1]; + var xj = this.points[j * 2]; + var yj = this.points[j * 2 + 1]; + var intersect = yi > y !== yj > y && x < (xj - xi) * ((y - yi) / (yj - yi)) + xi; + + if (intersect) { + inside = !inside; + } + } + + return inside; + }; + + return Polygon; +}(); + +exports.default = Polygon; + +},{"../../const":46,"../Point":69}],74:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * + * @class + * @memberof PIXI + */ +var Rectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle + * @param {number} [width=0] - The overall width of this rectangle + * @param {number} [height=0] - The overall height of this rectangle + */ + function Rectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Rectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = Number(x); + + /** + * @member {number} + * @default 0 + */ + this.y = Number(y); + + /** + * @member {number} + * @default 0 + */ + this.width = Number(width); + + /** + * @member {number} + * @default 0 + */ + this.height = Number(height); + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.RECT + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RECT; + } + + /** + * returns the left edge of the rectangle + * + * @member {number} + */ + + + /** + * Creates a clone of this Rectangle + * + * @return {PIXI.Rectangle} a copy of the rectangle + */ + Rectangle.prototype.clone = function clone() { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + + /** + * Copies another rectangle to this one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to copy. + * @return {PIXI.Rectangle} Returns itself. + */ + + + Rectangle.prototype.copy = function copy(rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + + return this; + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rectangle + */ + + + Rectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + + return false; + }; + + /** + * Pads the rectangle making it grow in all directions. + * + * @param {number} paddingX - The horizontal padding amount. + * @param {number} paddingY - The vertical padding amount. + */ + + + Rectangle.prototype.pad = function pad(paddingX, paddingY) { + paddingX = paddingX || 0; + paddingY = paddingY || (paddingY !== 0 ? paddingX : 0); + + this.x -= paddingX; + this.y -= paddingY; + + this.width += paddingX * 2; + this.height += paddingY * 2; + }; + + /** + * Fits this rectangle around the passed one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to fit. + */ + + + Rectangle.prototype.fit = function fit(rectangle) { + if (this.x < rectangle.x) { + this.width += this.x; + if (this.width < 0) { + this.width = 0; + } + + this.x = rectangle.x; + } + + if (this.y < rectangle.y) { + this.height += this.y; + if (this.height < 0) { + this.height = 0; + } + this.y = rectangle.y; + } + + if (this.x + this.width > rectangle.x + rectangle.width) { + this.width = rectangle.width - this.x; + if (this.width < 0) { + this.width = 0; + } + } + + if (this.y + this.height > rectangle.y + rectangle.height) { + this.height = rectangle.height - this.y; + if (this.height < 0) { + this.height = 0; + } + } + }; + + /** + * Enlarges this rectangle to include the passed rectangle. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to include. + */ + + + Rectangle.prototype.enlarge = function enlarge(rectangle) { + var x1 = Math.min(this.x, rectangle.x); + var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.min(this.y, rectangle.y); + var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); + + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + }; + + _createClass(Rectangle, [{ + key: 'left', + get: function get() { + return this.x; + } + + /** + * returns the right edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'right', + get: function get() { + return this.x + this.width; + } + + /** + * returns the top edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'top', + get: function get() { + return this.y; + } + + /** + * returns the bottom edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'bottom', + get: function get() { + return this.y + this.height; + } + + /** + * A constant empty rectangle. + * + * @static + * @constant + */ + + }], [{ + key: 'EMPTY', + get: function get() { + return new Rectangle(0, 0, 0, 0); + } + }]); + + return Rectangle; +}(); + +exports.default = Rectangle; + +},{"../../const":46}],75:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. + * + * @class + * @memberof PIXI + */ +var RoundedRectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle + * @param {number} [width=0] - The overall width of this rounded rectangle + * @param {number} [height=0] - The overall height of this rounded rectangle + * @param {number} [radius=20] - Controls the radius of the rounded corners + */ + function RoundedRectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var radius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 20; + + _classCallCheck(this, RoundedRectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * @member {number} + * @default 20 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readonly + * @default PIXI.SHAPES.RREC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RREC; + } + + /** + * Creates a clone of this Rounded Rectangle + * + * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle + */ + + + RoundedRectangle.prototype.clone = function clone() { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + */ + + + RoundedRectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + if (y >= this.y + this.radius && y <= this.y + this.height - this.radius || x >= this.x + this.radius && x <= this.x + this.width - this.radius) { + return true; + } + var dx = x - (this.x + this.radius); + var dy = y - (this.y + this.radius); + var radius2 = this.radius * this.radius; + + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.width - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dy = y - (this.y + this.height - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + } + } + + return false; + }; + + return RoundedRectangle; +}(); + +exports.default = RoundedRectangle; + +},{"../../const":46}],76:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _math = require('../math'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _Container = require('../display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMatrix = new _math.Matrix(); + +/** + * The SystemRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.WebGLRenderer} which can be used for rendering a PixiJS scene. + * + * @abstract + * @class + * @extends EventEmitter + * @memberof PIXI + */ + +var SystemRenderer = function (_EventEmitter) { + _inherits(SystemRenderer, _EventEmitter); + + // eslint-disable-next-line valid-jsdoc + /** + * @param {string} system - The name of the system this renderer is for. + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function SystemRenderer(system, options, arg2, arg3) { + _classCallCheck(this, SystemRenderer); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + (0, _utils.sayHello)(system); + + // Support for constructor(system, screenWidth, screenHeight, options) + if (typeof options === 'number') { + options = Object.assign({ + width: options, + height: arg2 || _settings2.default.RENDER_OPTIONS.height + }, arg3); + } + + // Add the default render options + options = Object.assign({}, _settings2.default.RENDER_OPTIONS, options); + + /** + * The supplied constructor options. + * + * @member {Object} + * @readOnly + */ + _this.options = options; + + /** + * The type of the renderer. + * + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.UNKNOWN; + + /** + * Measurements of the screen. (0, 0, screenWidth, screenHeight) + * + * Its safe to use as filterArea or hitArea for whole stage + * + * @member {PIXI.Rectangle} + */ + _this.screen = new _math.Rectangle(0, 0, options.width, options.height); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.view = options.view || document.createElement('canvas'); + + /** + * The resolution / device pixel ratio of the renderer + * + * @member {number} + * @default 1 + */ + _this.resolution = options.resolution || _settings2.default.RESOLUTION; + + /** + * Whether the render view is transparent + * + * @member {boolean} + */ + _this.transparent = options.transparent; + + /** + * Whether css dimensions of canvas view should be resized to screen dimensions automatically + * + * @member {boolean} + */ + _this.autoResize = options.autoResize || false; + + /** + * Tracks the blend modes useful for this renderer. + * + * @member {object} + */ + _this.blendModes = null; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example if + * your game has a canvas filling background image you often don't need this set. + * + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + * + * @member {boolean} + */ + _this.roundPixels = options.roundPixels; + + /** + * The background color as a number. + * + * @member {number} + * @private + */ + _this._backgroundColor = 0x000000; + + /** + * The background color as an [R, G, B] array. + * + * @member {number[]} + * @private + */ + _this._backgroundColorRgba = [0, 0, 0, 0]; + + /** + * The background color as a string. + * + * @member {string} + * @private + */ + _this._backgroundColorString = '#000000'; + + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + + /** + * This temporary display object used as the parent of the currently being rendered item + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._tempDisplayObjectParent = new _Container2.default(); + + /** + * The last root object that the renderer tried to render. + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._lastObjectRendered = _this._tempDisplayObjectParent; + return _this; + } + + /** + * Same as view.width, actual number of pixels in the canvas by horizontal + * + * @member {number} + * @readonly + * @default 800 + */ + + + /** + * Resizes the screen and canvas to the specified width and height + * Canvas dimensions are multiplied by resolution + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + SystemRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + this.screen.width = screenWidth; + this.screen.height = screenHeight; + + this.view.width = screenWidth * this.resolution; + this.view.height = screenHeight * this.resolution; + + if (this.autoResize) { + this.view.style.width = screenWidth + 'px'; + this.view.style.height = screenHeight + 'px'; + } + }; + + /** + * Useful function that returns a texture of the display object that can then be used to create sprites + * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. + * + * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from + * @param {number} scaleMode - Should be one of the scaleMode consts + * @param {number} resolution - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.Texture} a texture of the graphics object + */ + + + SystemRenderer.prototype.generateTexture = function generateTexture(displayObject, scaleMode, resolution) { + var bounds = displayObject.getLocalBounds(); + + var renderTexture = _RenderTexture2.default.create(bounds.width | 0, bounds.height | 0, scaleMode, resolution); + + tempMatrix.tx = -bounds.x; + tempMatrix.ty = -bounds.y; + + this.render(displayObject, renderTexture, false, tempMatrix, true); + + return renderTexture; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + SystemRenderer.prototype.destroy = function destroy(removeView) { + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } + + this.type = _const.RENDERER_TYPE.UNKNOWN; + + this.view = null; + + this.screen = null; + + this.resolution = 0; + + this.transparent = false; + + this.autoResize = false; + + this.blendModes = null; + + this.options = null; + + this.preserveDrawingBuffer = false; + this.clearBeforeRender = false; + + this.roundPixels = false; + + this._backgroundColor = 0; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + + this._tempDisplayObjectParent = null; + this._lastObjectRendered = null; + }; + + /** + * The background color to fill if not transparent + * + * @member {number} + */ + + + _createClass(SystemRenderer, [{ + key: 'width', + get: function get() { + return this.view.width; + } + + /** + * Same as view.height, actual number of pixels in the canvas by vertical + * + * @member {number} + * @readonly + * @default 600 + */ + + }, { + key: 'height', + get: function get() { + return this.view.height; + } + }, { + key: 'backgroundColor', + get: function get() { + return this._backgroundColor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._backgroundColor = value; + this._backgroundColorString = (0, _utils.hex2string)(value); + (0, _utils.hex2rgb)(value, this._backgroundColorRgba); + } + }]); + + return SystemRenderer; +}(_eventemitter2.default); + +exports.default = SystemRenderer; + +},{"../const":46,"../display/Container":48,"../math":70,"../settings":101,"../textures/RenderTexture":113,"../utils":124,"eventemitter3":3}],77:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _CanvasMaskManager = require('./utils/CanvasMaskManager'); + +var _CanvasMaskManager2 = _interopRequireDefault(_CanvasMaskManager); + +var _CanvasRenderTarget = require('./utils/CanvasRenderTarget'); + +var _CanvasRenderTarget2 = _interopRequireDefault(_CanvasRenderTarget); + +var _mapCanvasBlendModesToPixi = require('./utils/mapCanvasBlendModesToPixi'); + +var _mapCanvasBlendModesToPixi2 = _interopRequireDefault(_mapCanvasBlendModesToPixi); + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should + * be used for browsers that do not support WebGL. Don't forget to add the CanvasRenderer.view to + * your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ +var CanvasRenderer = function (_SystemRenderer) { + _inherits(CanvasRenderer, _SystemRenderer); + + // eslint-disable-next-line valid-jsdoc + /** + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function CanvasRenderer(options, arg2, arg3) { + _classCallCheck(this, CanvasRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'Canvas', options, arg2, arg3)); + + _this.type = _const.RENDERER_TYPE.CANVAS; + + /** + * The root canvas 2d context that everything is drawn with. + * + * @member {CanvasRenderingContext2D} + */ + _this.rootContext = _this.view.getContext('2d', { alpha: _this.transparent }); + + /** + * The currently active canvas 2d context (could change with renderTextures) + * + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.rootContext; + + /** + * Boolean flag controlling canvas refresh. + * + * @member {boolean} + */ + _this.refresh = true; + + /** + * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. + * + * @member {PIXI.CanvasMaskManager} + */ + _this.maskManager = new _CanvasMaskManager2.default(_this); + + /** + * The canvas property used to set the canvas smoothing property. + * + * @member {string} + */ + _this.smoothProperty = 'imageSmoothingEnabled'; + + if (!_this.rootContext.imageSmoothingEnabled) { + if (_this.rootContext.webkitImageSmoothingEnabled) { + _this.smoothProperty = 'webkitImageSmoothingEnabled'; + } else if (_this.rootContext.mozImageSmoothingEnabled) { + _this.smoothProperty = 'mozImageSmoothingEnabled'; + } else if (_this.rootContext.oImageSmoothingEnabled) { + _this.smoothProperty = 'oImageSmoothingEnabled'; + } else if (_this.rootContext.msImageSmoothingEnabled) { + _this.smoothProperty = 'msImageSmoothingEnabled'; + } + } + + _this.initPlugins(); + + _this.blendModes = (0, _mapCanvasBlendModesToPixi2.default)(); + _this._activeBlendMode = null; + + _this.renderingToScreen = false; + + _this.resize(_this.options.width, _this.options.height); + + /** + * Fired after rendering finishes. + * + * @event PIXI.CanvasRenderer#postrender + */ + + /** + * Fired before rendering starts. + * + * @event PIXI.CanvasRenderer#prerender + */ + return _this; + } + + /** + * Renders the object to this canvas view + * + * @param {PIXI.DisplayObject} displayObject - The object to be rendered + * @param {PIXI.RenderTexture} [renderTexture] - A render texture to be rendered to. + * If unset, it will render to the root context. + * @param {boolean} [clear=false] - Whether to clear the canvas before drawing + * @param {PIXI.Transform} [transform] - A transformation to be applied + * @param {boolean} [skipUpdateTransform=false] - Whether to skip the update transform + */ + + + CanvasRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!this.view) { + return; + } + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + var rootResolution = this.resolution; + + if (renderTexture) { + renderTexture = renderTexture.baseTexture || renderTexture; + + if (!renderTexture._canvasRenderTarget) { + renderTexture._canvasRenderTarget = new _CanvasRenderTarget2.default(renderTexture.width, renderTexture.height, renderTexture.resolution); + renderTexture.source = renderTexture._canvasRenderTarget.canvas; + renderTexture.valid = true; + } + + this.context = renderTexture._canvasRenderTarget.context; + this.resolution = renderTexture._canvasRenderTarget.resolution; + } else { + this.context = this.rootContext; + } + + var context = this.context; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + var tempWt = this._tempDisplayObjectParent.transform.worldTransform; + + if (transform) { + transform.copy(tempWt); + + // lets not forget to flag the parent transform as dirty... + this._tempDisplayObjectParent.transform._worldID = -1; + } else { + tempWt.identity(); + } + + displayObject.parent = this._tempDisplayObjectParent; + + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + context.setTransform(1, 0, 0, 1, 0, 0); + context.globalAlpha = 1; + context.globalCompositeOperation = this.blendModes[_const.BLEND_MODES.NORMAL]; + + if (navigator.isCocoonJS && this.view.screencanvas) { + context.fillStyle = 'black'; + context.clear(); + } + + if (clear !== undefined ? clear : this.clearBeforeRender) { + if (this.renderingToScreen) { + if (this.transparent) { + context.clearRect(0, 0, this.width, this.height); + } else { + context.fillStyle = this._backgroundColorString; + context.fillRect(0, 0, this.width, this.height); + } + } // else { + // TODO: implement background for CanvasRenderTarget or RenderTexture? + // } + } + + // TODO RENDER TARGET STUFF HERE.. + var tempContext = this.context; + + this.context = context; + displayObject.renderCanvas(this); + this.context = tempContext; + + this.resolution = rootResolution; + + this.emit('postrender'); + }; + + /** + * Clear the canvas of renderer. + * + * @param {string} [clearColor] - Clear the canvas with this color, except the canvas is transparent. + */ + + + CanvasRenderer.prototype.clear = function clear(clearColor) { + var context = this.context; + + clearColor = clearColor || this._backgroundColorString; + + if (!this.transparent && clearColor) { + context.fillStyle = clearColor; + context.fillRect(0, 0, this.width, this.height); + } else { + context.clearRect(0, 0, this.width, this.height); + } + }; + + /** + * Sets the blend mode of the renderer. + * + * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values. + */ + + + CanvasRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + if (this._activeBlendMode === blendMode) { + return; + } + + this._activeBlendMode = blendMode; + this.context.globalCompositeOperation = this.blendModes[blendMode]; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + CanvasRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // call the base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.context = null; + + this.refresh = true; + + this.maskManager.destroy(); + this.maskManager = null; + + this.smoothProperty = null; + }; + + /** + * Resizes the canvas view to the specified width and height. + * + * @extends PIXI.SystemRenderer#resize + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + CanvasRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + _SystemRenderer.prototype.resize.call(this, screenWidth, screenHeight); + + // reset the scale mode.. oddly this seems to be reset when the canvas is resized. + // surely a browser bug?? Let PixiJS fix that for you.. + if (this.smoothProperty) { + this.rootContext[this.smoothProperty] = _settings2.default.SCALE_MODE === _const.SCALE_MODES.LINEAR; + } + }; + + return CanvasRenderer; +}(_SystemRenderer3.default); + +/** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @name PIXI.CanvasRenderer#plugins + * @type {object} + * @readonly + * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.extract.CanvasExtract} extract Extract image data from renderer. + * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.prepare.CanvasPrepare} prepare Pre-render display objects. + */ + +/** + * Adds a plugin to the renderer. + * + * @method PIXI.CanvasRenderer#registerPlugin + * @param {string} pluginName - The name of the plugin. + * @param {Function} ctor - The constructor function or class for the plugin. + */ + +exports.default = CanvasRenderer; +_utils.pluginTarget.mixin(CanvasRenderer); + +},{"../../const":46,"../../settings":101,"../../utils":124,"../SystemRenderer":76,"./utils/CanvasMaskManager":78,"./utils/CanvasRenderTarget":79,"./utils/mapCanvasBlendModesToPixi":81}],78:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A set of functions used to handle masking. + * + * @class + * @memberof PIXI + */ +var CanvasMaskManager = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + function CanvasMaskManager(renderer) { + _classCallCheck(this, CanvasMaskManager); + + this.renderer = renderer; + } + + /** + * This method adds it to the current stack of masks. + * + * @param {object} maskData - the maskData that will be pushed + */ + + + CanvasMaskManager.prototype.pushMask = function pushMask(maskData) { + var renderer = this.renderer; + + renderer.context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.transform.worldTransform; + var resolution = renderer.resolution; + + renderer.context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // TODO suport sprite alpha masks?? + // lots of effort required. If demand is great enough.. + if (!maskData._texture) { + this.renderGraphicsShape(maskData); + renderer.context.clip(); + } + + maskData.worldAlpha = cacheAlpha; + }; + + /** + * Renders a PIXI.Graphics shape. + * + * @param {PIXI.Graphics} graphics - The object to render. + */ + + + CanvasMaskManager.prototype.renderGraphicsShape = function renderGraphicsShape(graphics) { + var context = this.renderer.context; + var len = graphics.graphicsData.length; + + if (len === 0) { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === _const.SHAPES.POLY) { + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; j++) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) { + context.closePath(); + } + } else if (data.type === _const.SHAPES.RECT) { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } + }; + + /** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @param {PIXI.CanvasRenderer} renderer - The renderer context to use. + */ + + + CanvasMaskManager.prototype.popMask = function popMask(renderer) { + renderer.context.restore(); + }; + + /** + * Destroys this canvas mask manager. + * + */ + + + CanvasMaskManager.prototype.destroy = function destroy() { + /* empty */ + }; + + return CanvasMaskManager; +}(); + +exports.default = CanvasMaskManager; + +},{"../../../const":46}],79:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Creates a Canvas element of the given size. + * + * @class + * @memberof PIXI + */ +var CanvasRenderTarget = function () { + /** + * @param {number} width - the width for the newly created canvas + * @param {number} height - the height for the newly created canvas + * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + _classCallCheck(this, CanvasRenderTarget); + + /** + * The Canvas object that belongs to this CanvasRenderTarget. + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @member {CanvasRenderingContext2D} + */ + this.context = this.canvas.getContext('2d'); + + this.resolution = resolution || _settings2.default.RESOLUTION; + + this.resize(width, height); + } + + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * + * @private + */ + + + CanvasRenderTarget.prototype.clear = function clear() { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + + /** + * Resizes the canvas to the specified width and height. + * + * @param {number} width - the new width of the canvas + * @param {number} height - the new height of the canvas + */ + + + CanvasRenderTarget.prototype.resize = function resize(width, height) { + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; + }; + + /** + * Destroys this canvas. + * + */ + + + CanvasRenderTarget.prototype.destroy = function destroy() { + this.context = null; + this.canvas = null; + }; + + /** + * The width of the canvas buffer in pixels. + * + * @member {number} + */ + + + _createClass(CanvasRenderTarget, [{ + key: 'width', + get: function get() { + return this.canvas.width; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.width = val; + } + + /** + * The height of the canvas buffer in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.canvas.height; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.height = val; + } + }]); + + return CanvasRenderTarget; +}(); + +exports.default = CanvasRenderTarget; + +},{"../../../settings":101}],80:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = canUseNewCanvasBlendModes; +/** + * Creates a little colored canvas + * + * @ignore + * @param {string} color - The color to make the canvas + * @return {canvas} a small canvas element + */ +function createColoredCanvas(color) { + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.fillStyle = color; + context.fillRect(0, 0, 6, 1); + + return canvas; +} + +/** + * Checks whether the Canvas BlendModes are supported by the current browser + * + * @return {boolean} whether they are supported + */ +function canUseNewCanvasBlendModes() { + if (typeof document === 'undefined') { + return false; + } + + var magenta = createColoredCanvas('#ff00ff'); + var yellow = createColoredCanvas('#ffff00'); + + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.globalCompositeOperation = 'multiply'; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + var imageData = context.getImageData(2, 0, 1, 1); + + if (!imageData) { + return false; + } + + var data = imageData.data; + + return data[0] === 255 && data[1] === 0 && data[2] === 0; +} + +},{}],81:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapCanvasBlendModesToPixi; + +var _const = require('../../../const'); + +var _canUseNewCanvasBlendModes = require('./canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Maps blend combinations to Canvas. + * + * @memberof PIXI + * @function mapCanvasBlendModesToPixi + * @private + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapCanvasBlendModesToPixi() { + var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + + if ((0, _canUseNewCanvasBlendModes2.default)()) { + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'multiply'; + array[_const.BLEND_MODES.SCREEN] = 'screen'; + array[_const.BLEND_MODES.OVERLAY] = 'overlay'; + array[_const.BLEND_MODES.DARKEN] = 'darken'; + array[_const.BLEND_MODES.LIGHTEN] = 'lighten'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'color-dodge'; + array[_const.BLEND_MODES.COLOR_BURN] = 'color-burn'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'hard-light'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'soft-light'; + array[_const.BLEND_MODES.DIFFERENCE] = 'difference'; + array[_const.BLEND_MODES.EXCLUSION] = 'exclusion'; + array[_const.BLEND_MODES.HUE] = 'hue'; + array[_const.BLEND_MODES.SATURATION] = 'saturate'; + array[_const.BLEND_MODES.COLOR] = 'color'; + array[_const.BLEND_MODES.LUMINOSITY] = 'luminosity'; + } else { + // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'source-over'; + array[_const.BLEND_MODES.SCREEN] = 'source-over'; + array[_const.BLEND_MODES.OVERLAY] = 'source-over'; + array[_const.BLEND_MODES.DARKEN] = 'source-over'; + array[_const.BLEND_MODES.LIGHTEN] = 'source-over'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'source-over'; + array[_const.BLEND_MODES.COLOR_BURN] = 'source-over'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.DIFFERENCE] = 'source-over'; + array[_const.BLEND_MODES.EXCLUSION] = 'source-over'; + array[_const.BLEND_MODES.HUE] = 'source-over'; + array[_const.BLEND_MODES.SATURATION] = 'source-over'; + array[_const.BLEND_MODES.COLOR] = 'source-over'; + array[_const.BLEND_MODES.LUMINOSITY] = 'source-over'; + } + // not-premultiplied, only for webgl + array[_const.BLEND_MODES.NORMAL_NPM] = array[_const.BLEND_MODES.NORMAL]; + array[_const.BLEND_MODES.ADD_NPM] = array[_const.BLEND_MODES.ADD]; + array[_const.BLEND_MODES.SCREEN_NPM] = array[_const.BLEND_MODES.SCREEN]; + + return array; +} + +},{"../../../const":46,"./canUseNewCanvasBlendModes":80}],82:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged + * up with textures that are no longer being used. + * + * @class + * @memberof PIXI + */ +var TextureGarbageCollector = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function TextureGarbageCollector(renderer) { + _classCallCheck(this, TextureGarbageCollector); + + this.renderer = renderer; + + this.count = 0; + this.checkCount = 0; + this.maxIdle = _settings2.default.GC_MAX_IDLE; + this.checkCountMax = _settings2.default.GC_MAX_CHECK_COUNT; + this.mode = _settings2.default.GC_MODE; + } + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.update = function update() { + this.count++; + + if (this.mode === _const.GC_MODES.MANUAL) { + return; + } + + this.checkCount++; + + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + + this.run(); + } + }; + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.run = function run() { + var tm = this.renderer.textureManager; + var managedTextures = tm._managedTextures; + var wasRemoved = false; + + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + + // only supports non generated textures at the moment! + if (!texture._glRenderTargets && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + + if (wasRemoved) { + var j = 0; + + for (var _i = 0; _i < managedTextures.length; _i++) { + if (managedTextures[_i] !== null) { + managedTextures[j++] = managedTextures[_i]; + } + } + + managedTextures.length = j; + } + }; + + /** + * Removes all the textures within the specified displayObject and its children from the GPU + * + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + */ + + + TextureGarbageCollector.prototype.unload = function unload(displayObject) { + var tm = this.renderer.textureManager; + + // only destroy non generated textures + if (displayObject._texture && displayObject._texture._glRenderTargets) { + tm.destroyTexture(displayObject._texture, true); + } + + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + + return TextureGarbageCollector; +}(); + +exports.default = TextureGarbageCollector; + +},{"../../const":46,"../../settings":101}],83:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _const = require('../../const'); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _utils = require('../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a webGL Texture + * + * @class + * @memberof PIXI + */ +var TextureManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function TextureManager(renderer) { + _classCallCheck(this, TextureManager); + + /** + * A reference to the current renderer + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = renderer.gl; + + /** + * Track textures in the renderer so we can no longer listen to them on destruction. + * + * @member {Array<*>} + * @private + */ + this._managedTextures = []; + } + + /** + * Binds a texture. + * + */ + + + TextureManager.prototype.bindTexture = function bindTexture() {} + // empty + + + /** + * Gets a texture. + * + */ + ; + + TextureManager.prototype.getTexture = function getTexture() {} + // empty + + + /** + * Updates and/or Creates a WebGL texture for the renderer's context. + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update + * @param {number} location - the location the texture will be bound to. + * @return {GLTexture} The gl texture. + */ + ; + + TextureManager.prototype.updateTexture = function updateTexture(texture, location) { + // assume it good! + // texture = texture.baseTexture || texture; + + var gl = this.gl; + + var isRenderTexture = !!texture._glRenderTargets; + + if (!texture.hasLoaded) { + return null; + } + + var boundTextures = this.renderer.boundTextures; + + // if the location is undefined then this may have been called by n event. + // this being the case the texture may already be bound to a slot. As a texture can only be bound once + // we need to find its current location if it exists. + if (location === undefined) { + location = 0; + + // TODO maybe we can use texture bound ids later on... + // check if texture is already bound.. + for (var i = 0; i < boundTextures.length; ++i) { + if (boundTextures[i] === texture) { + location = i; + break; + } + } + } + + boundTextures[location] = texture; + + gl.activeTexture(gl.TEXTURE0 + location); + + var glTexture = texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!glTexture) { + if (isRenderTexture) { + var renderTarget = new _RenderTarget2.default(this.gl, texture.width, texture.height, texture.scaleMode, texture.resolution); + + renderTarget.resize(texture.width, texture.height); + texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget; + glTexture = renderTarget.texture; + } else { + glTexture = new _pixiGlCore.GLTexture(this.gl, null, null, null, null); + glTexture.bind(location); + glTexture.premultiplyAlpha = true; + glTexture.upload(texture.source); + } + + texture._glTextures[this.renderer.CONTEXT_UID] = glTexture; + + texture.on('update', this.updateTexture, this); + texture.on('dispose', this.destroyTexture, this); + + this._managedTextures.push(texture); + + if (texture.isPowerOfTwo) { + if (texture.mipmap) { + glTexture.enableMipmap(); + } + + if (texture.wrapMode === _const.WRAP_MODES.CLAMP) { + glTexture.enableWrapClamp(); + } else if (texture.wrapMode === _const.WRAP_MODES.REPEAT) { + glTexture.enableWrapRepeat(); + } else { + glTexture.enableWrapMirrorRepeat(); + } + } else { + glTexture.enableWrapClamp(); + } + + if (texture.scaleMode === _const.SCALE_MODES.NEAREST) { + glTexture.enableNearestScaling(); + } else { + glTexture.enableLinearScaling(); + } + } + // the texture already exists so we only need to update it.. + else if (isRenderTexture) { + texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height); + } else { + glTexture.upload(texture.source); + } + + return glTexture; + }; + + /** + * Deletes the texture from WebGL + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy + * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. + */ + + + TextureManager.prototype.destroyTexture = function destroyTexture(texture, skipRemove) { + texture = texture.baseTexture || texture; + + if (!texture.hasLoaded) { + return; + } + + var uid = this.renderer.CONTEXT_UID; + var glTextures = texture._glTextures; + var glRenderTargets = texture._glRenderTargets; + + if (glTextures[uid]) { + this.renderer.unbindTexture(texture); + + glTextures[uid].destroy(); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + + delete glTextures[uid]; + + if (!skipRemove) { + var i = this._managedTextures.indexOf(texture); + + if (i !== -1) { + (0, _utils.removeItems)(this._managedTextures, i, 1); + } + } + } + + if (glRenderTargets && glRenderTargets[uid]) { + glRenderTargets[uid].destroy(); + delete glRenderTargets[uid]; + } + }; + + /** + * Deletes all the textures from WebGL + */ + + + TextureManager.prototype.removeAll = function removeAll() { + // empty all the old gl textures as they are useless now + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + delete texture._glTextures[this.renderer.CONTEXT_UID]; + } + } + }; + + /** + * Destroys this manager and removes all its textures + */ + + + TextureManager.prototype.destroy = function destroy() { + // destroy managed textures + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + this.destroyTexture(texture, true); + + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + } + + this._managedTextures = null; + }; + + return TextureManager; +}(); + +exports.default = TextureManager; + +},{"../../const":46,"../../utils":124,"./utils/RenderTarget":96,"pixi-gl-core":12}],84:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _MaskManager = require('./managers/MaskManager'); + +var _MaskManager2 = _interopRequireDefault(_MaskManager); + +var _StencilManager = require('./managers/StencilManager'); + +var _StencilManager2 = _interopRequireDefault(_StencilManager); + +var _FilterManager = require('./managers/FilterManager'); + +var _FilterManager2 = _interopRequireDefault(_FilterManager); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _ObjectRenderer = require('./utils/ObjectRenderer'); + +var _ObjectRenderer2 = _interopRequireDefault(_ObjectRenderer); + +var _TextureManager = require('./TextureManager'); + +var _TextureManager2 = _interopRequireDefault(_TextureManager); + +var _BaseTexture = require('../../textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _TextureGarbageCollector = require('./TextureGarbageCollector'); + +var _TextureGarbageCollector2 = _interopRequireDefault(_TextureGarbageCollector); + +var _WebGLState = require('./WebGLState'); + +var _WebGLState2 = _interopRequireDefault(_WebGLState); + +var _mapWebGLDrawModesToPixi = require('./utils/mapWebGLDrawModesToPixi'); + +var _mapWebGLDrawModesToPixi2 = _interopRequireDefault(_mapWebGLDrawModesToPixi); + +var _validateContext = require('./utils/validateContext'); + +var _validateContext2 = _interopRequireDefault(_validateContext); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CONTEXT_UID = 0; + +/** + * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ + +var WebGLRenderer = function (_SystemRenderer) { + _inherits(WebGLRenderer, _SystemRenderer); + + // eslint-disable-next-line valid-jsdoc + /** + * + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias. If not available natively then FXAA + * antialiasing is used + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. + * The resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear + * the canvas or not before the new render pass. If you wish to set this to false, you *must* set + * preserveDrawingBuffer to `true`. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when + * rendering, stopping pixel interpolation. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.legacy=false] - If true PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experiance unexplained flickering try setting this to true. + */ + function WebGLRenderer(options, arg2, arg3) { + _classCallCheck(this, WebGLRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'WebGL', options, arg2, arg3)); + + _this.legacy = _this.options.legacy; + + if (_this.legacy) { + _pixiGlCore2.default.VertexArrayObject.FORCE_NATIVE = true; + } + + /** + * The type of this renderer as a standardised const + * + * @member {number} + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.WEBGL; + + _this.handleContextLost = _this.handleContextLost.bind(_this); + _this.handleContextRestored = _this.handleContextRestored.bind(_this); + + _this.view.addEventListener('webglcontextlost', _this.handleContextLost, false); + _this.view.addEventListener('webglcontextrestored', _this.handleContextRestored, false); + + /** + * The options passed in to create a new webgl context. + * + * @member {object} + * @private + */ + _this._contextOptions = { + alpha: _this.transparent, + antialias: _this.options.antialias, + premultipliedAlpha: _this.transparent && _this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: _this.options.preserveDrawingBuffer + }; + + _this._backgroundColorRgba[3] = _this.transparent ? 0 : 1; + + /** + * Manages the masks using the stencil buffer. + * + * @member {PIXI.MaskManager} + */ + _this.maskManager = new _MaskManager2.default(_this); + + /** + * Manages the stencil buffer. + * + * @member {PIXI.StencilManager} + */ + _this.stencilManager = new _StencilManager2.default(_this); + + /** + * An empty renderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.emptyRenderer = new _ObjectRenderer2.default(_this); + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.currentRenderer = _this.emptyRenderer; + + _this.initPlugins(); + + /** + * The current WebGL rendering context, it is created here + * + * @member {WebGLRenderingContext} + */ + // initialize the context so it is ready for the managers. + if (_this.options.context) { + // checks to see if a context is valid.. + (0, _validateContext2.default)(_this.options.context); + } + + _this.gl = _this.options.context || _pixiGlCore2.default.createContext(_this.view, _this._contextOptions); + + _this.CONTEXT_UID = CONTEXT_UID++; + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.WebGLState} + */ + _this.state = new _WebGLState2.default(_this.gl); + + _this.renderingToScreen = true; + + /** + * Holds the current state of textures bound to the GPU. + * @type {Array} + */ + _this.boundTextures = null; + + /** + * Holds the current shader + * + * @member {PIXI.Shader} + */ + _this._activeShader = null; + + _this._activeVao = null; + + /** + * Holds the current render target + * + * @member {PIXI.RenderTarget} + */ + _this._activeRenderTarget = null; + + _this._initContext(); + + /** + * Manages the filters. + * + * @member {PIXI.FilterManager} + */ + _this.filterManager = new _FilterManager2.default(_this); + // map some webGL blend and drawmodes.. + _this.drawModes = (0, _mapWebGLDrawModesToPixi2.default)(_this.gl); + + _this._nextTextureLocation = 0; + + _this.setBlendMode(0); + + /** + * Fired after rendering finishes. + * + * @event PIXI.WebGLRenderer#postrender + */ + + /** + * Fired before rendering starts. + * + * @event PIXI.WebGLRenderer#prerender + */ + + /** + * Fired when the WebGL context is set. + * + * @event PIXI.WebGLRenderer#context + * @param {WebGLRenderingContext} gl - WebGL context. + */ + return _this; + } + + /** + * Creates the WebGL context + * + * @private + */ + + + WebGLRenderer.prototype._initContext = function _initContext() { + var gl = this.gl; + + // restore a context if it was previously lost + if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').restoreContext(); + } + + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + + this._activeShader = null; + this._activeVao = null; + + this.boundTextures = new Array(maxTextures); + this.emptyTextures = new Array(maxTextures); + + // create a texture manager... + this.textureManager = new _TextureManager2.default(this); + this.textureGC = new _TextureGarbageCollector2.default(this); + + this.state.resetToDefault(); + + this.rootRenderTarget = new _RenderTarget2.default(gl, this.width, this.height, null, this.resolution, true); + this.rootRenderTarget.clearColor = this._backgroundColorRgba; + + this.bindRenderTarget(this.rootRenderTarget); + + // now lets fill up the textures with empty ones! + var emptyGLTexture = new _pixiGlCore2.default.GLTexture.fromData(gl, null, 1, 1); + + var tempObj = { _glTextures: {} }; + + tempObj._glTextures[this.CONTEXT_UID] = {}; + + for (var i = 0; i < maxTextures; i++) { + var empty = new _BaseTexture2.default(); + + empty._glTextures[this.CONTEXT_UID] = emptyGLTexture; + + this.boundTextures[i] = tempObj; + this.emptyTextures[i] = empty; + this.bindTexture(null, i); + } + + this.emit('context', gl); + + // setup the width/height properties and gl viewport + this.resize(this.screen.width, this.screen.height); + }; + + /** + * Renders the object to its webGL view + * + * @param {PIXI.DisplayObject} displayObject - the object to be rendered + * @param {PIXI.RenderTexture} renderTexture - The render texture to render to. + * @param {boolean} [clear] - Should the canvas be cleared before the new render + * @param {PIXI.Transform} [transform] - A transform to apply to the render texture before rendering. + * @param {boolean} [skipUpdateTransform] - Should we skip the update transform pass? + */ + + + WebGLRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + // no point rendering if our context has been blown up! + if (!this.gl || this.gl.isContextLost()) { + return; + } + + this._nextTextureLocation = 0; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + this.bindRenderTexture(renderTexture, transform); + + this.currentRenderer.start(); + + if (clear !== undefined ? clear : this.clearBeforeRender) { + this._activeRenderTarget.clear(); + } + + displayObject.renderWebGL(this); + + // apply transform.. + this.currentRenderer.flush(); + + // this.setObjectRenderer(this.emptyRenderer); + + this.textureGC.update(); + + this.emit('postrender'); + }; + + /** + * Changes the current renderer to the one given in parameter + * + * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. + */ + + + WebGLRenderer.prototype.setObjectRenderer = function setObjectRenderer(objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; + + /** + * This should be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + * + */ + + + WebGLRenderer.prototype.flush = function flush() { + this.setObjectRenderer(this.emptyRenderer); + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + WebGLRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + // if(width * this.resolution === this.width && height * this.resolution === this.height)return; + + _SystemRenderer3.default.prototype.resize.call(this, screenWidth, screenHeight); + + this.rootRenderTarget.resize(screenWidth, screenHeight); + + if (this._activeRenderTarget === this.rootRenderTarget) { + this.rootRenderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true); + } + } + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} blendMode - the desired blend mode + */ + + + WebGLRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + this.state.setBlendMode(blendMode); + }; + + /** + * Erases the active render target and fills the drawing area with a colour + * + * @param {number} [clearColor] - The colour + */ + + + WebGLRenderer.prototype.clear = function clear(clearColor) { + this._activeRenderTarget.clear(clearColor); + }; + + /** + * Sets the transform of the active render target to the given matrix + * + * @param {PIXI.Matrix} matrix - The transformation matrix + */ + + + WebGLRenderer.prototype.setTransform = function setTransform(matrix) { + this._activeRenderTarget.transform = matrix; + }; + + /** + * Erases the render texture and fills the drawing area with a colour + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to clear + * @param {number} [clearColor] - The colour + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.clearRenderTexture = function clearRenderTexture(renderTexture, clearColor) { + var baseTexture = renderTexture.baseTexture; + var renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + + if (renderTarget) { + renderTarget.clear(clearColor); + } + + return this; + }; + + /** + * Binds a render texture for rendering + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to render + * @param {PIXI.Transform} transform - The transform to be applied to the render texture + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTexture = function bindRenderTexture(renderTexture, transform) { + var renderTarget = void 0; + + if (renderTexture) { + var baseTexture = renderTexture.baseTexture; + + if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) { + // bind the current texture + this.textureManager.updateTexture(baseTexture, 0); + } + + this.unbindTexture(baseTexture); + + renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + renderTarget.setFrame(renderTexture.frame); + } else { + renderTarget = this.rootRenderTarget; + } + + renderTarget.transform = transform; + this.bindRenderTarget(renderTarget); + + return this; + }; + + /** + * Changes the current render target to the one given in parameter + * + * @param {PIXI.RenderTarget} renderTarget - the new render target + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTarget = function bindRenderTarget(renderTarget) { + if (renderTarget !== this._activeRenderTarget) { + this._activeRenderTarget = renderTarget; + renderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true); + } + + this.stencilManager.setMaskStack(renderTarget.stencilMaskStack); + } + + return this; + }; + + /** + * Changes the current shader to the one given in parameter + * + * @param {PIXI.Shader} shader - the new shader + * @param {boolean} [autoProject=true] - Whether automatically set the projection matrix + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindShader = function bindShader(shader, autoProject) { + // TODO cache + if (this._activeShader !== shader) { + this._activeShader = shader; + shader.bind(); + + // `autoProject` normally would be a default parameter set to true + // but because of how Babel transpiles default parameters + // it hinders the performance of this method. + if (autoProject !== false) { + // automatically set the projection matrix + shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(true); + } + } + + return this; + }; + + /** + * Binds the texture. This will return the location of the bound texture. + * It may not be the same as the one you pass in. This is due to optimisation that prevents + * needless binding of textures. For example if the texture is already bound it will return the + * current location of the texture instead of the one provided. To bypass this use force location + * + * @param {PIXI.Texture} texture - the new texture + * @param {number} location - the suggested texture location + * @param {boolean} forceLocation - force the location + * @return {number} bound texture location + */ + + + WebGLRenderer.prototype.bindTexture = function bindTexture(texture, location, forceLocation) { + texture = texture || this.emptyTextures[location]; + texture = texture.baseTexture || texture; + texture.touched = this.textureGC.count; + + if (!forceLocation) { + // TODO - maybe look into adding boundIds.. save us the loop? + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + return i; + } + } + + if (location === undefined) { + this._nextTextureLocation++; + this._nextTextureLocation %= this.boundTextures.length; + location = this.boundTextures.length - this._nextTextureLocation - 1; + } + } else { + location = location || 0; + } + + var gl = this.gl; + var glTexture = texture._glTextures[this.CONTEXT_UID]; + + if (!glTexture) { + // this will also bind the texture.. + this.textureManager.updateTexture(texture, location); + } else { + // bind the current texture + this.boundTextures[location] = texture; + gl.activeTexture(gl.TEXTURE0 + location); + gl.bindTexture(gl.TEXTURE_2D, glTexture.texture); + } + + return location; + }; + + /** + * unbinds the texture ... + * + * @param {PIXI.Texture} texture - the texture to unbind + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.unbindTexture = function unbindTexture(texture) { + var gl = this.gl; + + texture = texture.baseTexture || texture; + + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + this.boundTextures[i] = this.emptyTextures[i]; + + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[i]._glTextures[this.CONTEXT_UID].texture); + } + } + + return this; + }; + + /** + * Creates a new VAO from this renderer's context and state. + * + * @return {VertexArrayObject} The new VAO. + */ + + + WebGLRenderer.prototype.createVao = function createVao() { + return new _pixiGlCore2.default.VertexArrayObject(this.gl, this.state.attribState); + }; + + /** + * Changes the current Vao to the one given in parameter + * + * @param {PIXI.VertexArrayObject} vao - the new Vao + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindVao = function bindVao(vao) { + if (this._activeVao === vao) { + return this; + } + + if (vao) { + vao.bind(); + } else if (this._activeVao) { + // TODO this should always be true i think? + this._activeVao.unbind(); + } + + this._activeVao = vao; + + return this; + }; + + /** + * Resets the WebGL state so you can render things however you fancy! + * + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.reset = function reset() { + this.setObjectRenderer(this.emptyRenderer); + + this._activeShader = null; + this._activeRenderTarget = this.rootRenderTarget; + + // bind the main frame buffer (the screen); + this.rootRenderTarget.activate(); + + this.state.resetToDefault(); + + return this; + }; + + /** + * Handles a lost webgl context + * + * @private + * @param {WebGLContextEvent} event - The context lost event. + */ + + + WebGLRenderer.prototype.handleContextLost = function handleContextLost(event) { + event.preventDefault(); + }; + + /** + * Handles a restored webgl context + * + * @private + */ + + + WebGLRenderer.prototype.handleContextRestored = function handleContextRestored() { + this.textureManager.removeAll(); + this._initContext(); + }; + + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + + + WebGLRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // remove listeners + this.view.removeEventListener('webglcontextlost', this.handleContextLost); + this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); + + this.textureManager.destroy(); + + // call base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.uid = 0; + + // destroy the managers + this.maskManager.destroy(); + this.stencilManager.destroy(); + this.filterManager.destroy(); + + this.maskManager = null; + this.filterManager = null; + this.textureManager = null; + this.currentRenderer = null; + + this.handleContextLost = null; + this.handleContextRestored = null; + + this._contextOptions = null; + this.gl.useProgram(null); + + if (this.gl.getExtension('WEBGL_lose_context')) { + this.gl.getExtension('WEBGL_lose_context').loseContext(); + } + + this.gl = null; + + // this = null; + }; + + return WebGLRenderer; +}(_SystemRenderer3.default); + +/** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @name PIXI.WebGLRenderer#plugins + * @type {object} + * @readonly + * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.extract.WebGLExtract} extract Extract image data from renderer. + * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.prepare.WebGLPrepare} prepare Pre-render display objects. + */ + +/** + * Adds a plugin to the renderer. + * + * @method PIXI.WebGLRenderer#registerPlugin + * @param {string} pluginName - The name of the plugin. + * @param {Function} ctor - The constructor function or class for the plugin. + */ + +exports.default = WebGLRenderer; +_utils.pluginTarget.mixin(WebGLRenderer); + +},{"../../const":46,"../../textures/BaseTexture":112,"../../utils":124,"../SystemRenderer":76,"./TextureGarbageCollector":82,"./TextureManager":83,"./WebGLState":85,"./managers/FilterManager":90,"./managers/MaskManager":91,"./managers/StencilManager":92,"./utils/ObjectRenderer":94,"./utils/RenderTarget":96,"./utils/mapWebGLDrawModesToPixi":99,"./utils/validateContext":100,"pixi-gl-core":12}],85:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); + +var _mapWebGLBlendModesToPixi2 = _interopRequireDefault(_mapWebGLBlendModesToPixi); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var BLEND = 0; +var DEPTH_TEST = 1; +var FRONT_FACE = 2; +var CULL_FACE = 3; +var BLEND_FUNC = 4; + +/** + * A WebGL state machines + * + * @memberof PIXI + * @class + */ + +var WebGLState = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + */ + function WebGLState(gl) { + _classCallCheck(this, WebGLState); + + /** + * The current active state + * + * @member {Uint8Array} + */ + this.activeState = new Uint8Array(16); + + /** + * The default state + * + * @member {Uint8Array} + */ + this.defaultState = new Uint8Array(16); + + // default blend mode.. + this.defaultState[0] = 1; + + /** + * The current state index in the stack + * + * @member {number} + * @private + */ + this.stackIndex = 0; + + /** + * The stack holding all the different states + * + * @member {Array<*>} + * @private + */ + this.stack = []; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + this.attribState = { + tempAttribState: new Array(this.maxAttribs), + attribState: new Array(this.maxAttribs) + }; + + this.blendModes = (0, _mapWebGLBlendModesToPixi2.default)(gl); + + // check we have vao.. + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || gl.getExtension('MOZ_OES_vertex_array_object') || gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + /** + * Pushes a new active state + */ + + + WebGLState.prototype.push = function push() { + // next state.. + var state = this.stack[this.stackIndex]; + + if (!state) { + state = this.stack[this.stackIndex] = new Uint8Array(16); + } + + ++this.stackIndex; + + // copy state.. + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) { + state[i] = this.activeState[i]; + } + }; + + /** + * Pops a state out + */ + + + WebGLState.prototype.pop = function pop() { + var state = this.stack[--this.stackIndex]; + + this.setState(state); + }; + + /** + * Sets the current state + * + * @param {*} state - The state to set. + */ + + + WebGLState.prototype.setState = function setState(state) { + this.setBlend(state[BLEND]); + this.setDepthTest(state[DEPTH_TEST]); + this.setFrontFace(state[FRONT_FACE]); + this.setCullFace(state[CULL_FACE]); + this.setBlendMode(state[BLEND_FUNC]); + }; + + /** + * Enables or disabled blending. + * + * @param {boolean} value - Turn on or off webgl blending. + */ + + + WebGLState.prototype.setBlend = function setBlend(value) { + value = value ? 1 : 0; + + if (this.activeState[BLEND] === value) { + return; + } + + this.activeState[BLEND] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + }; + + /** + * Sets the blend mode. + * + * @param {number} value - The blend mode to set to. + */ + + + WebGLState.prototype.setBlendMode = function setBlendMode(value) { + if (value === this.activeState[BLEND_FUNC]) { + return; + } + + this.activeState[BLEND_FUNC] = value; + + var mode = this.blendModes[value]; + + if (mode.length === 2) { + this.gl.blendFunc(mode[0], mode[1]); + } else { + this.gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); + } + }; + + /** + * Sets whether to enable or disable depth test. + * + * @param {boolean} value - Turn on or off webgl depth testing. + */ + + + WebGLState.prototype.setDepthTest = function setDepthTest(value) { + value = value ? 1 : 0; + + if (this.activeState[DEPTH_TEST] === value) { + return; + } + + this.activeState[DEPTH_TEST] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + }; + + /** + * Sets whether to enable or disable cull face. + * + * @param {boolean} value - Turn on or off webgl cull face. + */ + + + WebGLState.prototype.setCullFace = function setCullFace(value) { + value = value ? 1 : 0; + + if (this.activeState[CULL_FACE] === value) { + return; + } + + this.activeState[CULL_FACE] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + }; + + /** + * Sets the gl front face. + * + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ + + + WebGLState.prototype.setFrontFace = function setFrontFace(value) { + value = value ? 1 : 0; + + if (this.activeState[FRONT_FACE] === value) { + return; + } + + this.activeState[FRONT_FACE] = value; + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); + }; + + /** + * Disables all the vaos in use + * + */ + + + WebGLState.prototype.resetAttributes = function resetAttributes() { + for (var i = 0; i < this.attribState.tempAttribState.length; i++) { + this.attribState.tempAttribState[i] = 0; + } + + for (var _i = 0; _i < this.attribState.attribState.length; _i++) { + this.attribState.attribState[_i] = 0; + } + + // im going to assume one is always active for performance reasons. + for (var _i2 = 1; _i2 < this.maxAttribs; _i2++) { + this.gl.disableVertexAttribArray(_i2); + } + }; + + // used + /** + * Resets all the logic and disables the vaos + */ + + + WebGLState.prototype.resetToDefault = function resetToDefault() { + // unbind any VAO if they exist.. + if (this.nativeVaoExtension) { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + // reset all attributes.. + this.resetAttributes(); + + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; ++i) { + this.activeState[i] = 32; + } + + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + + this.setState(this.defaultState); + }; + + return WebGLState; +}(); + +exports.default = WebGLState; + +},{"./utils/mapWebGLBlendModesToPixi":98}],86:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _extractUniformsFromSrc = require('./extractUniformsFromSrc'); + +var _extractUniformsFromSrc2 = _interopRequireDefault(_extractUniformsFromSrc); + +var _utils = require('../../../utils'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SOURCE_KEY_MAP = {}; + +// let math = require('../../../math'); +/** + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ + +var Filter = function () { + /** + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. + */ + function Filter(vertexSrc, fragmentSrc, uniforms) { + _classCallCheck(this, Filter); + + /** + * The vertex shader. + * + * @member {string} + */ + this.vertexSrc = vertexSrc || Filter.defaultVertexSrc; + + /** + * The fragment shader. + * + * @member {string} + */ + this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc; + + this._blendMode = _const.BLEND_MODES.NORMAL; + + this.uniformData = uniforms || (0, _extractUniformsFromSrc2.default)(this.vertexSrc, this.fragmentSrc, 'projectionMatrix|uSampler'); + + /** + * An object containing the current values of custom uniforms. + * @example Updating the value of a custom uniform + * filter.uniforms.time = performance.now(); + * + * @member {object} + */ + this.uniforms = {}; + + for (var i in this.uniformData) { + this.uniforms[i] = this.uniformData[i].value; + } + + // this is where we store shader references.. + // TODO we could cache this! + this.glShaders = {}; + + // used for cacheing.. sure there is a better way! + if (!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) { + SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = (0, _utils.uid)(); + } + + this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]; + + /** + * The padding of the filter. Some filters require extra space to breath such as a blur. + * Increasing this will add extra width and height to the bounds of the object that the + * filter is applied to. + * + * @member {number} + */ + this.padding = 4; + + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + * + * @member {number} + */ + this.resolution = _settings2.default.RESOLUTION; + + /** + * If enabled is true the filter is applied, if false it will not. + * + * @member {boolean} + */ + this.enabled = true; + + /** + * If enabled, PixiJS will fit the filter area into boundaries for better performance. + * Switch it off if it does not work for specific shader. + * + * @member {boolean} + */ + this.autoFit = true; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + * @param {object} [currentState] - It's current state of filter. + * There are some useful properties in the currentState : + * target, filters, sourceFrame, destinationFrame, renderTarget, resolution + */ + + + Filter.prototype.apply = function apply(filterManager, input, output, clear, currentState) // eslint-disable-line no-unused-vars + { + // --- // + // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); + + // do as you please! + + filterManager.applyFilter(this, input, output, clear); + + // or just do a regular render.. + }; + + /** + * Sets the blendmode of the filter + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + */ + + + _createClass(Filter, [{ + key: 'blendMode', + get: function get() { + return this._blendMode; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._blendMode = value; + } + + /** + * The default vertex shader source + * + * @static + * @constant + */ + + }], [{ + key: 'defaultVertexSrc', + get: function get() { + return ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform mat3 projectionMatrix;', 'uniform mat3 filterMatrix;', 'varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;', ' vTextureCoord = aTextureCoord ;', '}'].join('\n'); + } + + /** + * The default fragment shader source + * + * @static + * @constant + */ + + }, { + key: 'defaultFragmentSrc', + get: function get() { + return ['varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'uniform sampler2D uSampler;', 'uniform sampler2D filterSampler;', 'void main(void){', ' vec4 masky = texture2D(filterSampler, vFilterCoord);', ' vec4 sample = texture2D(uSampler, vTextureCoord);', ' vec4 color;', ' if(mod(vFilterCoord.x, 1.0) > 0.5)', ' {', ' color = vec4(1.0, 0.0, 0.0, 1.0);', ' }', ' else', ' {', ' color = vec4(0.0, 1.0, 0.0, 1.0);', ' }', + // ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', + ' gl_FragColor = mix(sample, masky, 0.5);', ' gl_FragColor *= sample.a;', '}'].join('\n'); + } + }]); + + return Filter; +}(); + +exports.default = Filter; + +},{"../../../const":46,"../../../settings":101,"../../../utils":124,"./extractUniformsFromSrc":87}],87:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = extractUniformsFromSrc; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var defaultValue = _pixiGlCore2.default.shader.defaultValue; + +function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) { + var vertUniforms = extractUniformsFromString(vertexSrc, mask); + var fragUniforms = extractUniformsFromString(fragmentSrc, mask); + + return Object.assign(vertUniforms, fragUniforms); +} + +function extractUniformsFromString(string) { + var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea|filterClamp)$'); + + var uniforms = {}; + var nameSplit = void 0; + + // clean the lines a little - remove extra spaces / tabs etc + // then split along ';' + var lines = string.replace(/\s+/g, ' ').split(/\s*;\s*/); + + // loop through.. + for (var i = 0; i < lines.length; i++) { + var line = lines[i].trim(); + + if (line.indexOf('uniform') > -1) { + var splitLine = line.split(' '); + var type = splitLine[1]; + + var name = splitLine[2]; + var size = 1; + + if (name.indexOf('[') > -1) { + // array! + nameSplit = name.split(/\[|]/); + name = nameSplit[0]; + size *= Number(nameSplit[1]); + } + + if (!name.match(maskRegex)) { + uniforms[name] = { + value: defaultValue(type, size), + name: name, + type: type + }; + } + } + } + + return uniforms; +} + +},{"pixi-gl-core":12}],88:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.calculateScreenSpaceMatrix = calculateScreenSpaceMatrix; +exports.calculateNormalizedScreenSpaceMatrix = calculateNormalizedScreenSpaceMatrix; +exports.calculateSpriteMatrix = calculateSpriteMatrix; + +var _math = require('../../../math'); + +/** + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// this returns a matrix that will normalise map filter cords in the filter to screen space +function calculateScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + // let worldTransform = sprite.worldTransform.copy(Matrix.TEMP_MATRIX), + // let texture = {width:1136, height:700};//sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(textureSize.width, textureSize.height); + + return mappedMatrix; +} + +function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + var translateScaleX = textureSize.width / filterArea.width; + var translateScaleY = textureSize.height / filterArea.height; + + mappedMatrix.scale(translateScaleX, translateScaleY); + + return mappedMatrix; +} + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +function calculateSpriteMatrix(outputMatrix, filterArea, textureSize, sprite) { + var worldTransform = sprite.worldTransform.copy(_math.Matrix.TEMP_MATRIX); + var texture = sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + // scale.. + var ratio = textureSize.height / textureSize.width; + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(1, ratio); + + var translateScaleX = textureSize.width / texture.width; + var translateScaleY = textureSize.height / texture.height; + + worldTransform.tx /= texture.width * translateScaleX; + + // this...? free beer for anyone who can explain why this makes sense! + worldTransform.ty /= texture.width * translateScaleX; + // worldTransform.ty /= texture.height * translateScaleY; + + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + + // apply inverse scale.. + mappedMatrix.scale(1, 1 / ratio); + + mappedMatrix.scale(translateScaleX, translateScaleY); + + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; +} + +},{"../../../math":70}],89:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Filter2 = require('../Filter'); + +var _Filter3 = _interopRequireDefault(_Filter2); + +var _math = require('../../../../math'); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The SpriteMaskFilter class + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + */ +var SpriteMaskFilter = function (_Filter) { + _inherits(SpriteMaskFilter, _Filter); + + /** + * @param {PIXI.Sprite} sprite - the target sprite + */ + function SpriteMaskFilter(sprite) { + _classCallCheck(this, SpriteMaskFilter); + + var maskMatrix = new _math.Matrix(); + + var _this = _possibleConstructorReturn(this, _Filter.call(this, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n', 'varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n')); + + sprite.renderable = false; + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + return _this; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + */ + + + SpriteMaskFilter.prototype.apply = function apply(filterManager, input, output) { + var maskSprite = this.maskSprite; + + this.uniforms.mask = maskSprite._texture; + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite); + this.uniforms.alpha = maskSprite.worldAlpha; + + filterManager.applyFilter(this, input, output); + }; + + return SpriteMaskFilter; +}(_Filter3.default); + +exports.default = SpriteMaskFilter; + +},{"../../../../math":70,"../Filter":86,"path":23}],90:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _RenderTarget = require('../utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _Quad = require('../utils/Quad'); + +var _Quad2 = _interopRequireDefault(_Quad); + +var _math = require('../../../math'); + +var _Shader = require('../../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _filterTransforms = require('../filters/filterTransforms'); + +var filterTransforms = _interopRequireWildcard(_filterTransforms); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @ignore + * @class + */ +var FilterState = +/** + * + */ +function FilterState() { + _classCallCheck(this, FilterState); + + this.renderTarget = null; + this.sourceFrame = new _math.Rectangle(); + this.destinationFrame = new _math.Rectangle(); + this.filters = []; + this.target = null; + this.resolution = 1; +}; + +/** + * @class + * @memberof PIXI + * @extends PIXI.WebGLManager + */ + + +var FilterManager = function (_WebGLManager) { + _inherits(FilterManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function FilterManager(renderer) { + _classCallCheck(this, FilterManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.gl = _this.renderer.gl; + // know about sprites! + _this.quad = new _Quad2.default(_this.gl, renderer.state.attribState); + + _this.shaderCache = {}; + // todo add default! + _this.pool = {}; + + _this.filterData = null; + return _this; + } + + /** + * Adds a new filter to the manager. + * + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param {PIXI.Filter[]} filters - The filters to apply. + */ + + + FilterManager.prototype.pushFilter = function pushFilter(target, filters) { + var renderer = this.renderer; + + var filterData = this.filterData; + + if (!filterData) { + filterData = this.renderer._activeRenderTarget.filterStack; + + // add new stack + var filterState = new FilterState(); + + filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; + filterState.renderTarget = renderer._activeRenderTarget; + + this.renderer._activeRenderTarget.filterData = filterData = { + index: 0, + stack: [filterState] + }; + + this.filterData = filterData; + } + + // get the current filter state.. + var currentState = filterData.stack[++filterData.index]; + + if (!currentState) { + currentState = filterData.stack[filterData.index] = new FilterState(); + } + + // for now we go off the filter of the first resolution.. + var resolution = filters[0].resolution; + var padding = filters[0].padding | 0; + var targetBounds = target.filterArea || target.getBounds(true); + var sourceFrame = currentState.sourceFrame; + var destinationFrame = currentState.destinationFrame; + + sourceFrame.x = (targetBounds.x * resolution | 0) / resolution; + sourceFrame.y = (targetBounds.y * resolution | 0) / resolution; + sourceFrame.width = (targetBounds.width * resolution | 0) / resolution; + sourceFrame.height = (targetBounds.height * resolution | 0) / resolution; + + if (filterData.stack[0].renderTarget.transform) {// + + // TODO we should fit the rect around the transform.. + } else if (filters[0].autoFit) { + sourceFrame.fit(filterData.stack[0].destinationFrame); + } + + // lets apply the padding After we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + sourceFrame.pad(padding); + + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + + // lets play the padding after we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + + var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); + + currentState.target = target; + currentState.filters = filters; + currentState.resolution = resolution; + currentState.renderTarget = renderTarget; + + // bind the render target to draw the shape in the top corner.. + + renderTarget.setFrame(destinationFrame, sourceFrame); + + // bind the render target + renderer.bindRenderTarget(renderTarget); + renderTarget.clear(); + }; + + /** + * Pops off the filter and applies it. + * + */ + + + FilterManager.prototype.popFilter = function popFilter() { + var filterData = this.filterData; + + var lastState = filterData.stack[filterData.index - 1]; + var currentState = filterData.stack[filterData.index]; + + this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); + + var filters = currentState.filters; + + if (filters.length === 1) { + filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false, currentState); + this.freePotRenderTarget(currentState.renderTarget); + } else { + var flip = currentState.renderTarget; + var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, currentState.resolution); + + flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + // finally lets clear the render target before drawing to it.. + flop.clear(); + + var i = 0; + + for (i = 0; i < filters.length - 1; ++i) { + filters[i].apply(this, flip, flop, true, currentState); + + var t = flip; + + flip = flop; + flop = t; + } + + filters[i].apply(this, flip, lastState.renderTarget, false, currentState); + + this.freePotRenderTarget(flip); + this.freePotRenderTarget(flop); + } + + filterData.index--; + + if (filterData.index === 0) { + this.filterData = null; + } + }; + + /** + * Draws a filter. + * + * @param {PIXI.Filter} filter - The filter to draw. + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + FilterManager.prototype.applyFilter = function applyFilter(filter, input, output, clear) { + var renderer = this.renderer; + var gl = renderer.gl; + + var shader = filter.glShaders[renderer.CONTEXT_UID]; + + // cacheing.. + if (!shader) { + if (filter.glShaderKey) { + shader = this.shaderCache[filter.glShaderKey]; + + if (!shader) { + shader = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + + filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = shader; + } + } else { + shader = filter.glShaders[renderer.CONTEXT_UID] = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + } + + // TODO - this only needs to be done once? + renderer.bindVao(null); + + this.quad.initVao(shader); + } + + renderer.bindVao(this.quad.vao); + + renderer.bindRenderTarget(output); + + if (clear) { + gl.disable(gl.SCISSOR_TEST); + renderer.clear(); // [1, 1, 1, 1]); + gl.enable(gl.SCISSOR_TEST); + } + + // in case the render target is being masked using a scissor rect + if (output === renderer.maskManager.scissorRenderTarget) { + renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); + } + + renderer.bindShader(shader); + + // free unit 0 for us, doesn't matter what was there + // don't try to restore it, because syncUniforms can upload it to another slot + // and it'll be a problem + var tex = this.renderer.emptyTextures[0]; + + this.renderer.boundTextures[0] = tex; + // this syncs the PixiJS filters uniforms with glsl uniforms + this.syncUniforms(shader, filter); + + renderer.state.setBlendMode(filter.blendMode); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, input.texture.texture); + + this.quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + }; + + /** + * Uploads the uniforms of the filter. + * + * @param {GLShader} shader - The underlying gl shader. + * @param {PIXI.Filter} filter - The filter we are synchronizing. + */ + + + FilterManager.prototype.syncUniforms = function syncUniforms(shader, filter) { + var uniformData = filter.uniformData; + var uniforms = filter.uniforms; + + // 0 is reserved for the PixiJS texture so we start at 1! + var textureCount = 1; + var currentState = void 0; + + // filterArea and filterClamp that are handled by FilterManager directly + // they must not appear in uniformData + + if (shader.uniforms.filterArea) { + currentState = this.filterData.stack[this.filterData.index]; + + var filterArea = shader.uniforms.filterArea; + + filterArea[0] = currentState.renderTarget.size.width; + filterArea[1] = currentState.renderTarget.size.height; + filterArea[2] = currentState.sourceFrame.x; + filterArea[3] = currentState.sourceFrame.y; + + shader.uniforms.filterArea = filterArea; + } + + // use this to clamp displaced texture coords so they belong to filterArea + // see displacementFilter fragment shader for an example + if (shader.uniforms.filterClamp) { + currentState = currentState || this.filterData.stack[this.filterData.index]; + + var filterClamp = shader.uniforms.filterClamp; + + filterClamp[0] = 0; + filterClamp[1] = 0; + filterClamp[2] = (currentState.sourceFrame.width - 1) / currentState.renderTarget.size.width; + filterClamp[3] = (currentState.sourceFrame.height - 1) / currentState.renderTarget.size.height; + + shader.uniforms.filterClamp = filterClamp; + } + + // TODO Cacheing layer.. + for (var i in uniformData) { + if (uniformData[i].type === 'sampler2D' && uniforms[i] !== 0) { + if (uniforms[i].baseTexture) { + shader.uniforms[i] = this.renderer.bindTexture(uniforms[i].baseTexture, textureCount); + } else { + shader.uniforms[i] = textureCount; + + // TODO + // this is helpful as renderTargets can also be set. + // Although thinking about it, we could probably + // make the filter texture cache return a RenderTexture + // rather than a renderTarget + var gl = this.renderer.gl; + + this.renderer.boundTextures[textureCount] = this.renderer.emptyTextures[textureCount]; + gl.activeTexture(gl.TEXTURE0 + textureCount); + + uniforms[i].texture.bind(); + } + + textureCount++; + } else if (uniformData[i].type === 'mat3') { + // check if its PixiJS matrix.. + if (uniforms[i].a !== undefined) { + shader.uniforms[i] = uniforms[i].toArray(true); + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (uniformData[i].type === 'vec2') { + // check if its a point.. + if (uniforms[i].x !== undefined) { + var val = shader.uniforms[i] || new Float32Array(2); + + val[0] = uniforms[i].x; + val[1] = uniforms[i].y; + shader.uniforms[i] = val; + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (uniformData[i].type === 'float') { + if (shader.uniforms.data[i].value !== uniformData[i]) { + shader.uniforms[i] = uniforms[i]; + } + } else { + shader.uniforms[i] = uniforms[i]; + } + } + }; + + /** + * Gets a render target from the pool, or creates a new one. + * + * @param {boolean} clear - Should we clear the render texture when we get it? + * @param {number} resolution - The resolution of the target. + * @return {PIXI.RenderTarget} The new render target + */ + + + FilterManager.prototype.getRenderTarget = function getRenderTarget(clear, resolution) { + var currentState = this.filterData.stack[this.filterData.index]; + var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution); + + renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + return renderTarget; + }; + + /** + * Returns a render target to the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The render target to return. + */ + + + FilterManager.prototype.returnRenderTarget = function returnRenderTarget(renderTarget) { + this.freePotRenderTarget(renderTarget); + }; + + /** + * Calculates the mapped matrix. + * + * TODO playing around here.. this is temporary - (will end up in the shader) + * this returns a matrix that will normalise map filter cords in the filter to screen space + * + * @param {PIXI.Matrix} outputMatrix - the matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateScreenSpaceMatrix = function calculateScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); + }; + + /** + * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function calculateNormalizedScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); + }; + + /** + * This will map the filter coord so that a texture can be used based on the transform of a sprite + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateSpriteMatrix = function calculateSpriteMatrix(outputMatrix, sprite) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); + }; + + /** + * Destroys this Filter Manager. + * + */ + + + FilterManager.prototype.destroy = function destroy() { + this.shaderCache = {}; + this.emptyPool(); + }; + + /** + * Gets a Power-of-Two render texture. + * + * TODO move to a seperate class could be on renderer? + * also - could cause issue with multiple contexts? + * + * @private + * @param {WebGLRenderingContext} gl - The webgl rendering context + * @param {number} minWidth - The minimum width of the render target. + * @param {number} minHeight - The minimum height of the render target. + * @param {number} resolution - The resolution of the render target. + * @return {PIXI.RenderTarget} The new render target. + */ + + + FilterManager.prototype.getPotRenderTarget = function getPotRenderTarget(gl, minWidth, minHeight, resolution) { + // TODO you could return a bigger texture if there is not one in the pool? + minWidth = _bitTwiddle2.default.nextPow2(minWidth * resolution); + minHeight = _bitTwiddle2.default.nextPow2(minHeight * resolution); + + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + if (!this.pool[key]) { + this.pool[key] = []; + } + + var renderTarget = this.pool[key].pop(); + + // creating render target will cause texture to be bound! + if (!renderTarget) { + // temporary bypass cache.. + var tex = this.renderer.boundTextures[0]; + + gl.activeTexture(gl.TEXTURE0); + + // internally - this will cause a texture to be bound.. + renderTarget = new _RenderTarget2.default(gl, minWidth, minHeight, null, 1); + + // set the current one back + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + } + + // manually tweak the resolution... + // this will not modify the size of the frame buffer, just its resolution. + renderTarget.resolution = resolution; + renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution; + renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution; + + return renderTarget; + }; + + /** + * Empties the texture pool. + * + */ + + + FilterManager.prototype.emptyPool = function emptyPool() { + for (var i in this.pool) { + var textures = this.pool[i]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + + this.pool = {}; + }; + + /** + * Frees a render target back into the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free + */ + + + FilterManager.prototype.freePotRenderTarget = function freePotRenderTarget(renderTarget) { + var minWidth = renderTarget.size.width * renderTarget.resolution; + var minHeight = renderTarget.size.height * renderTarget.resolution; + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + this.pool[key].push(renderTarget); + }; + + return FilterManager; +}(_WebGLManager3.default); + +exports.default = FilterManager; + +},{"../../../Shader":44,"../../../math":70,"../filters/filterTransforms":88,"../utils/Quad":95,"../utils/RenderTarget":96,"./WebGLManager":93,"bit-twiddle":1}],91:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _SpriteMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); + +var _SpriteMaskFilter2 = _interopRequireDefault(_SpriteMaskFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var MaskManager = function (_WebGLManager) { + _inherits(MaskManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function MaskManager(renderer) { + _classCallCheck(this, MaskManager); + + // TODO - we don't need both! + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.scissor = false; + _this.scissorData = null; + _this.scissorRenderTarget = null; + + _this.enableScissor = true; + + _this.alphaMaskPool = []; + _this.alphaMaskIndex = 0; + return _this; + } + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushMask = function pushMask(target, maskData) { + // TODO the root check means scissor rect will not + // be used on render textures more info here: + // https://github.com/pixijs/pixi.js/pull/3545 + + if (maskData.texture) { + this.pushSpriteMask(target, maskData); + } else if (this.enableScissor && !this.scissor && this.renderer._activeRenderTarget.root && !this.renderer.stencilManager.stencilMaskStack.length && maskData.isFastRect()) { + var matrix = maskData.worldTransform; + + var rot = Math.atan2(matrix.b, matrix.a); + + // use the nearest degree! + rot = Math.round(rot * (180 / Math.PI)); + + if (rot % 90) { + this.pushStencilMask(maskData); + } else { + this.pushScissorMask(target, maskData); + } + } else { + this.pushStencilMask(maskData); + } + }; + + /** + * Removes the last mask from the mask stack and doesn't return it. + * + * @param {PIXI.DisplayObject} target - Display Object to pop the mask from + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.popMask = function popMask(target, maskData) { + if (maskData.texture) { + this.popSpriteMask(target, maskData); + } else if (this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length) { + this.popScissorMask(target, maskData); + } else { + this.popStencilMask(target, maskData); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.RenderTarget} target - Display Object to push the sprite mask to + * @param {PIXI.Sprite} maskData - Sprite to be used as the mask + */ + + + MaskManager.prototype.pushSpriteMask = function pushSpriteMask(target, maskData) { + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new _SpriteMaskFilter2.default(maskData)]; + } + + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskData; + + // TODO - may cause issues! + target.filterArea = maskData.getBounds(true); + + this.renderer.filterManager.pushFilter(target, alphaMaskFilter); + + this.alphaMaskIndex++; + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popSpriteMask = function popSpriteMask() { + this.renderer.filterManager.popFilter(); + this.alphaMaskIndex--; + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushStencilMask = function pushStencilMask(maskData) { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.pushStencil(maskData); + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popStencilMask = function popStencilMask() { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.popStencil(); + }; + + /** + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushScissorMask = function pushScissorMask(target, maskData) { + maskData.renderable = true; + + var renderTarget = this.renderer._activeRenderTarget; + + var bounds = maskData.getBounds(); + + bounds.fit(renderTarget.size); + maskData.renderable = false; + + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + + var resolution = this.renderer.resolution; + + this.renderer.gl.scissor(bounds.x * resolution, (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution, bounds.width * resolution, bounds.height * resolution); + + this.scissorRenderTarget = renderTarget; + this.scissorData = maskData; + this.scissor = true; + }; + + /** + * + * + */ + + + MaskManager.prototype.popScissorMask = function popScissorMask() { + this.scissorRenderTarget = null; + this.scissorData = null; + this.scissor = false; + + // must be scissor! + var gl = this.renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + }; + + return MaskManager; +}(_WebGLManager3.default); + +exports.default = MaskManager; + +},{"../filters/spriteMask/SpriteMaskFilter":89,"./WebGLManager":93}],92:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var StencilManager = function (_WebGLManager) { + _inherits(StencilManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function StencilManager(renderer) { + _classCallCheck(this, StencilManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.stencilMaskStack = null; + return _this; + } + + /** + * Changes the mask stack that is used by this manager. + * + * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack + */ + + + StencilManager.prototype.setMaskStack = function setMaskStack(stencilMaskStack) { + this.stencilMaskStack = stencilMaskStack; + + var gl = this.renderer.gl; + + if (stencilMaskStack.length === 0) { + gl.disable(gl.STENCIL_TEST); + } else { + gl.enable(gl.STENCIL_TEST); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. @alvin + * + * @param {PIXI.Graphics} graphics - The mask + */ + + + StencilManager.prototype.pushStencil = function pushStencil(graphics) { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + this.renderer._activeRenderTarget.attachStencilBuffer(); + + var gl = this.renderer.gl; + var sms = this.stencilMaskStack; + + if (sms.length === 0) { + gl.enable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.stencilFunc(gl.ALWAYS, 1, 1); + } + + sms.push(graphics); + + gl.colorMask(false, false, false, false); + gl.stencilFunc(gl.EQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; + + /** + * TODO @alvin + */ + + + StencilManager.prototype.popStencil = function popStencil() { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + var gl = this.renderer.gl; + var sms = this.stencilMaskStack; + + var graphics = sms.pop(); + + if (sms.length === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + } else { + gl.colorMask(false, false, false, false); + gl.stencilFunc(gl.EQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + + this.renderer.plugins.graphics.render(graphics); + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.NOTEQUAL, 0, sms.length); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + } + }; + + /** + * Destroys the mask stack. + * + */ + + + StencilManager.prototype.destroy = function destroy() { + _WebGLManager3.default.prototype.destroy.call(this); + + this.stencilMaskStack.stencilStack = null; + }; + + return StencilManager; +}(_WebGLManager3.default); + +exports.default = StencilManager; + +},{"./WebGLManager":93}],93:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var WebGLManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function WebGLManager(renderer) { + _classCallCheck(this, WebGLManager); + + /** + * The renderer this manager works for. + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + this.renderer.on('context', this.onContextChange, this); + } + + /** + * Generic method called when there is a WebGL context change. + * + */ + + + WebGLManager.prototype.onContextChange = function onContextChange() {} + // do some codes init! + + + /** + * Generic destroy methods to be overridden by the subclass + * + */ + ; + + WebGLManager.prototype.destroy = function destroy() { + this.renderer.off('context', this.onContextChange, this); + + this.renderer = null; + }; + + return WebGLManager; +}(); + +exports.default = WebGLManager; + +},{}],94:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('../managers/WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Base for a common object renderer that can be used as a system renderer plugin. + * + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var ObjectRenderer = function (_WebGLManager) { + _inherits(ObjectRenderer, _WebGLManager); + + function ObjectRenderer() { + _classCallCheck(this, ObjectRenderer); + + return _possibleConstructorReturn(this, _WebGLManager.apply(this, arguments)); + } + + /** + * Starts the renderer and sets the shader + * + */ + ObjectRenderer.prototype.start = function start() {} + // set the shader.. + + + /** + * Stops the renderer + * + */ + ; + + ObjectRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Stub method for rendering content and emptying the current batch. + * + */ + + + ObjectRenderer.prototype.flush = function flush() {} + // flush! + + + /** + * Renders an object + * + * @param {PIXI.DisplayObject} object - The object to render. + */ + ; + + ObjectRenderer.prototype.render = function render(object) // eslint-disable-line no-unused-vars + { + // render the object + }; + + return ObjectRenderer; +}(_WebGLManager3.default); + +exports.default = ObjectRenderer; + +},{"../managers/WebGLManager":93}],95:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a quad + * + * @class + * @memberof PIXI + */ +var Quad = function () { + /** + * @param {WebGLRenderingContext} gl - The gl context for this quad to use. + * @param {object} state - TODO: Description + */ + function Quad(gl, state) { + _classCallCheck(this, Quad); + + /** + * the current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]); + + /** + * The Uvs of the quad + * + * @member {Float32Array} + */ + this.uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + this.interleaved = new Float32Array(8 * 2); + + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(1); + + /** + * The vertex buffer + * + * @member {glCore.GLBuffer} + */ + this.vertexBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW); + + /** + * The index buffer + * + * @member {glCore.GLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + /** + * The vertex array object + * + * @member {glCore.VertexArrayObject} + */ + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, state); + } + + /** + * Initialises the vaos and uses the shader. + * + * @param {PIXI.Shader} shader - the shader to use + */ + + + Quad.prototype.initVao = function initVao(shader) { + this.vao.clear().addIndex(this.indexBuffer).addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0).addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4); + }; + + /** + * Maps two Rectangle to the quad. + * + * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle + * @param {PIXI.Rectangle} destinationFrame - the second rectangle + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.map = function map(targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + + this.uvs[0] = x; + this.uvs[1] = y; + + this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; + + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; + + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; + + x = destinationFrame.x; + y = destinationFrame.y; + + this.vertices[0] = x; + this.vertices[1] = y; + + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + + return this; + }; + + /** + * Binds the buffer and uploads the data + * + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.upload = function upload() { + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + this.vertexBuffer.upload(this.interleaved); + + return this; + }; + + /** + * Removes this quad from WebGL + */ + + + Quad.prototype.destroy = function destroy() { + var gl = this.gl; + + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.indexBuffer); + }; + + return Quad; +}(); + +exports.default = Quad; + +},{"../../../utils/createIndicesForQuads":122,"pixi-gl-core":12}],96:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../../../math'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _pixiGlCore = require('pixi-gl-core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var RenderTarget = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {number} [width=0] - the horizontal range of the filter + * @param {number} [height=0] - the vertical range of the filter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The current resolution / device pixel ratio + * @param {boolean} [root=false] - Whether this object is the root element or not + */ + function RenderTarget(gl, width, height, scaleMode, resolution, root) { + _classCallCheck(this, RenderTarget); + + // TODO Resolution could go here ( eg low res blurs ) + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // next time to create a frame buffer and texture + + /** + * A frame buffer + * + * @member {PIXI.glCore.GLFramebuffer} + */ + this.frameBuffer = null; + + /** + * The texture + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The background colour of this render target, as an array of [r,g,b,a] values + * + * @member {number[]} + */ + this.clearColor = [0, 0, 0, 0]; + + /** + * The size of the object as a rectangle + * + * @member {PIXI.Rectangle} + */ + this.size = new _math.Rectangle(0, 0, 1, 1); + + /** + * The current resolution / device pixel ratio + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The projection matrix + * + * @member {PIXI.Matrix} + */ + this.projectionMatrix = new _math.Matrix(); + + /** + * The object's transform + * + * @member {PIXI.Matrix} + */ + this.transform = null; + + /** + * The frame. + * + * @member {PIXI.Rectangle} + */ + this.frame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.defaultFrame = new _math.Rectangle(); + this.destinationFrame = null; + this.sourceFrame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.stencilBuffer = null; + + /** + * The data structure for the stencil masks + * + * @member {PIXI.Graphics[]} + */ + this.stencilMaskStack = []; + + /** + * Stores filter data for the render target + * + * @member {object[]} + */ + this.filterData = null; + + /** + * The scale mode. + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Whether this object is the root element or not + * + * @member {boolean} + */ + this.root = root; + + if (!this.root) { + this.frameBuffer = _pixiGlCore.GLFramebuffer.createRGBA(gl, 100, 100); + + if (this.scaleMode === _const.SCALE_MODES.NEAREST) { + this.frameBuffer.texture.enableNearestScaling(); + } else { + this.frameBuffer.texture.enableLinearScaling(); + } + /* + A frame buffer needs a target to render to.. + create a texture and bind it attach it to the framebuffer.. + */ + + // this is used by the base texture + this.texture = this.frameBuffer.texture; + } else { + // make it a null framebuffer.. + this.frameBuffer = new _pixiGlCore.GLFramebuffer(gl, 100, 100); + this.frameBuffer.framebuffer = null; + } + + this.setFrame(); + + this.resize(width, height); + } + + /** + * Clears the filter texture. + * + * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer + */ + + + RenderTarget.prototype.clear = function clear(clearColor) { + var cc = clearColor || this.clearColor; + + this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a); + }; + + /** + * Binds the stencil buffer. + * + */ + + + RenderTarget.prototype.attachStencilBuffer = function attachStencilBuffer() { + // TODO check if stencil is done? + /** + * The stencil buffer is used for masking in pixi + * lets create one and then add attach it to the framebuffer.. + */ + if (!this.root) { + this.frameBuffer.enableStencil(); + } + }; + + /** + * Sets the frame of the render target. + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.setFrame = function setFrame(destinationFrame, sourceFrame) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || this.destinationFrame; + }; + + /** + * Binds the buffers and initialises the viewport. + * + */ + + + RenderTarget.prototype.activate = function activate() { + // TOOD refactor usage of frame.. + var gl = this.gl; + + // make sure the texture is unbound! + this.frameBuffer.bind(); + + this.calculateProjection(this.destinationFrame, this.sourceFrame); + + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + + // TODO add a check as them may be the same! + if (this.destinationFrame !== this.sourceFrame) { + gl.enable(gl.SCISSOR_TEST); + gl.scissor(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + } else { + gl.disable(gl.SCISSOR_TEST); + } + + // TODO - does not need to be updated all the time?? + gl.viewport(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + }; + + /** + * Updates the projection matrix based on a projection frame (which is a rectangle) + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.calculateProjection = function calculateProjection(destinationFrame, sourceFrame) { + var pm = this.projectionMatrix; + + sourceFrame = sourceFrame || destinationFrame; + + pm.identity(); + + // TODO: make dest scale source + if (!this.root) { + pm.a = 1 / destinationFrame.width * 2; + pm.d = 1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = -1 - sourceFrame.y * pm.d; + } else { + pm.a = 1 / destinationFrame.width * 2; + pm.d = -1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = 1 - sourceFrame.y * pm.d; + } + }; + + /** + * Resizes the texture to the specified width and height + * + * @param {number} width - the new width of the texture + * @param {number} height - the new height of the texture + */ + + + RenderTarget.prototype.resize = function resize(width, height) { + width = width | 0; + height = height | 0; + + if (this.size.width === width && this.size.height === height) { + return; + } + + this.size.width = width; + this.size.height = height; + + this.defaultFrame.width = width; + this.defaultFrame.height = height; + + this.frameBuffer.resize(width * this.resolution, height * this.resolution); + + var projectionFrame = this.frame || this.size; + + this.calculateProjection(projectionFrame); + }; + + /** + * Destroys the render target. + * + */ + + + RenderTarget.prototype.destroy = function destroy() { + this.frameBuffer.destroy(); + + this.frameBuffer = null; + this.texture = null; + }; + + return RenderTarget; +}(); + +exports.default = RenderTarget; + +},{"../../../const":46,"../../../math":70,"../../../settings":101,"pixi-gl-core":12}],97:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = checkMaxIfStatmentsInShader; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['precision mediump float;', 'void main(void){', 'float test = 0.1;', '%forloop%', 'gl_FragColor = vec4(0.0);', '}'].join('\n'); + +function checkMaxIfStatmentsInShader(maxIfs, gl) { + var createTempContext = !gl; + + if (maxIfs === 0) { + throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); + } + + if (createTempContext) { + var tinyCanvas = document.createElement('canvas'); + + tinyCanvas.width = 1; + tinyCanvas.height = 1; + + gl = _pixiGlCore2.default.createContext(tinyCanvas); + } + + var shader = gl.createShader(gl.FRAGMENT_SHADER); + + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = maxIfs / 2 | 0; + } else { + // valid! + break; + } + } + + if (createTempContext) { + // get rid of context + if (gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').loseContext(); + } + } + + return maxIfs; +} + +function generateIfTestSrc(maxIfs) { + var src = ''; + + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxIfs - 1) { + src += 'if(test == ' + i + '.0){}'; + } + } + + return src; +} + +},{"pixi-gl-core":12}],98:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLBlendModesToPixi; + +var _const = require('../../../const'); + +/** + * Maps gl blend combinations to WebGL. + * + * @memberof PIXI + * @function mapWebGLBlendModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapWebGLBlendModesToPixi(gl) { + var array = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[_const.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD] = [gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + array[_const.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + // not-premultiplied blend modes + array[_const.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.DST_ALPHA, gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + + return array; +} + +},{"../../../const":46}],99:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLDrawModesToPixi; + +var _const = require('../../../const'); + +/** + * Generic Mask Stack data structure. + * + * @memberof PIXI + * @function mapWebGLDrawModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {object} [object={}] - The object to map into + * @return {object} The mapped draw modes. + */ +function mapWebGLDrawModesToPixi(gl) { + var object = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + object[_const.DRAW_MODES.POINTS] = gl.POINTS; + object[_const.DRAW_MODES.LINES] = gl.LINES; + object[_const.DRAW_MODES.LINE_LOOP] = gl.LINE_LOOP; + object[_const.DRAW_MODES.LINE_STRIP] = gl.LINE_STRIP; + object[_const.DRAW_MODES.TRIANGLES] = gl.TRIANGLES; + object[_const.DRAW_MODES.TRIANGLE_STRIP] = gl.TRIANGLE_STRIP; + object[_const.DRAW_MODES.TRIANGLE_FAN] = gl.TRIANGLE_FAN; + + return object; +} + +},{"../../../const":46}],100:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = validateContext; +function validateContext(gl) { + var attributes = gl.getContextAttributes(); + + // this is going to be fairly simple for now.. but at least we have room to grow! + if (!attributes.stencil) { + /* eslint-disable no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable no-console */ + } +} + +},{}],101:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _maxRecommendedTextures = require('./utils/maxRecommendedTextures'); + +var _maxRecommendedTextures2 = _interopRequireDefault(_maxRecommendedTextures); + +var _canUploadSameBuffer = require('./utils/canUploadSameBuffer'); + +var _canUploadSameBuffer2 = _interopRequireDefault(_canUploadSameBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * User's customizable globals for overriding the default PIXI settings, such + * as a renderer's default resolution, framerate, float percision, etc. + * @example + * // Use the native window resolution as the default resolution + * // will support high-density displays when rendering + * PIXI.settings.RESOLUTION = window.devicePixelRatio. + * + * // Disable interpolation when scaling, will make texture be pixelated + * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; + * @namespace PIXI.settings + */ +exports.default = { + + /** + * Target frames per millisecond. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 0.06 + */ + TARGET_FPMS: 0.06, + + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * + * @static + * @memberof PIXI.settings + * @type {boolean} + * @default true + */ + MIPMAP_TEXTURES: true, + + /** + * Default resolution / device pixel ratio of the renderer. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + RESOLUTION: 1, + + /** + * Default filter resolution. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + FILTER_RESOLUTION: 1, + + /** + * The maximum textures that this device supports. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 32 + */ + SPRITE_MAX_TEXTURES: (0, _maxRecommendedTextures2.default)(32), + + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + + /** + * The prefix that denotes a URL is for a retina asset. + * + * @static + * @memberof PIXI.settings + * @type {RegExp} + * @example `@2x` + * @default /@([0-9\.]+)x/ + */ + RETINA_PREFIX: /@([0-9\.]+)x/, + + /** + * The default render options if none are supplied to {@link PIXI.WebGLRenderer} + * or {@link PIXI.CanvasRenderer}. + * + * @static + * @constant + * @memberof PIXI.settings + * @type {object} + * @property {HTMLCanvasElement} view=null + * @property {number} resolution=1 + * @property {boolean} antialias=false + * @property {boolean} forceFXAA=false + * @property {boolean} autoResize=false + * @property {boolean} transparent=false + * @property {number} backgroundColor=0x000000 + * @property {boolean} clearBeforeRender=true + * @property {boolean} preserveDrawingBuffer=false + * @property {boolean} roundPixels=false + * @property {number} width=800 + * @property {number} height=600 + * @property {boolean} legacy=false + */ + RENDER_OPTIONS: { + view: null, + antialias: false, + forceFXAA: false, + autoResize: false, + transparent: false, + backgroundColor: 0x000000, + clearBeforeRender: true, + preserveDrawingBuffer: false, + roundPixels: false, + width: 800, + height: 600, + legacy: false + }, + + /** + * Default transform type. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.TRANSFORM_MODE} + * @default PIXI.TRANSFORM_MODE.STATIC + */ + TRANSFORM_MODE: 0, + + /** + * Default Garbage Collection mode. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO + */ + GC_MODE: 0, + + /** + * Default Garbage Collection max idle. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 3600 + */ + GC_MAX_IDLE: 60 * 60, + + /** + * Default Garbage Collection maximum check count. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 600 + */ + GC_MAX_CHECK_COUNT: 60 * 10, + + /** + * Default wrap modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP + */ + WRAP_MODE: 0, + + /** + * The scale modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR + */ + SCALE_MODE: 0, + + /** + * Default specify float precision in vertex shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.HIGH + */ + PRECISION_VERTEX: 'highp', + + /** + * Default specify float precision in fragment shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM + */ + PRECISION_FRAGMENT: 'mediump', + + /** + * Can we upload the same buffer in a single frame? + * + * @static + * @constant + * @memberof PIXI + * @type {boolean} + */ + CAN_UPLOAD_SAME_BUFFER: (0, _canUploadSameBuffer2.default)() + +}; + +},{"./utils/canUploadSameBuffer":121,"./utils/maxRecommendedTextures":126}],102:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new _math.Point(); + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = new PIXI.Sprite.fromImage('assets/image.png'); + * ``` + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Sprite = function (_Container) { + _inherits(Sprite, _Container); + + /** + * @param {PIXI.Texture} texture - The texture for this sprite + */ + function Sprite(texture) { + _classCallCheck(this, Sprite); + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + * @private + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this._anchor = new _math.ObservablePoint(_this._onAnchorUpdate, _this); + + /** + * The texture that the sprite is using + * + * @private + * @member {PIXI.Texture} + */ + _this._texture = null; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = null; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * The shader that will be used to render the sprite. Set to null to remove a current shader. + * + * @member {PIXI.Filter|PIXI.Shader} + */ + _this.shader = null; + + /** + * An internal cached value of the tint. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this.cachedTint = 0xFFFFFF; + + // call texture setter + _this.texture = texture || _Texture2.default.EMPTY; + + /** + * this is used to store the vertex data of the sprite (basically a quad) + * + * @private + * @member {Float32Array} + */ + _this.vertexData = new Float32Array(8); + + /** + * This is used to calculate the bounds of the object IF it is a trimmed sprite + * + * @private + * @member {Float32Array} + */ + _this.vertexTrimmedData = null; + + _this._transformID = -1; + _this._textureID = -1; + + _this._transformTrimmedID = -1; + _this._textureTrimmedID = -1; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * + * @member {string} + * @default 'sprite' + */ + _this.pluginName = 'sprite'; + return _this; + } + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Sprite.prototype._onTextureUpdate = function _onTextureUpdate() { + this._textureID = -1; + this._textureTrimmedID = -1; + + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = (0, _utils.sign)(this.scale.x) * this._width / this._texture.orig.width; + } + + if (this._height) { + this.scale.y = (0, _utils.sign)(this.scale.y) * this._height / this._texture.orig.height; + } + }; + + /** + * Called when the anchor position updates. + * + * @private + */ + + + Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate() { + this._transformID = -1; + this._transformTrimmedID = -1; + }; + + /** + * calculates worldTransform * vertices, store it in vertexData + */ + + + Sprite.prototype.calculateVertices = function calculateVertices() { + if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) { + return; + } + + this._transformID = this.transform._worldID; + this._textureID = this._texture._updateID; + + // set the vertex data + + var texture = this._texture; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var anchor = this._anchor; + + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - anchor._x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - anchor._y * orig.height; + h0 = h1 + trim.height; + } else { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData + * This is used to ensure that the true width and height of a trimmed texture is respected + */ + + + Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices() { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { + return; + } + + this._transformTrimmedID = this.transform._worldID; + this._textureTrimmedID = this._texture._updateID; + + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + var anchor = this._anchor; + + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + + var w1 = -anchor._x * orig.width; + var w0 = w1 + orig.width; + + var h1 = -anchor._y * orig.height; + var h0 = h1 + orig.height; + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use. + */ + + + Sprite.prototype._renderWebGL = function _renderWebGL(renderer) { + this.calculateVertices(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Sprite.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Updates the bounds of the sprite. + * + * @private + */ + + + Sprite.prototype._calculateBounds = function _calculateBounds() { + var trim = this._texture.trim; + var orig = this._texture.orig; + + // First lets check to see if the current texture has a trim.. + if (!trim || trim.width === orig.width && trim.height === orig.height) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + Sprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._texture.orig.width * -this._anchor._x; + this._bounds.minY = this._texture.orig.height * -this._anchor._y; + this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x); + this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._x); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _Container.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Tests if a point is inside this sprite + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Sprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + y1 = -height * this.anchor.y; + + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + Sprite.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + this._anchor = null; + + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + + this._texture.destroy(!!destroyBaseTexture); + } + + this._texture = null; + this.shader = null; + }; + + // some helper functions.. + + /** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Sprite} The newly created sprite + */ + + + Sprite.from = function from(source) { + return new Sprite(_Texture2.default.from(source)); + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId + */ + + + Sprite.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return new Sprite(texture); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id + */ + + + Sprite.fromImage = function fromImage(imageId, crossorigin, scaleMode) { + return new Sprite(_Texture2.default.fromImage(imageId, crossorigin, scaleMode)); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Sprite, [{ + key: 'width', + get: function get() { + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._anchor.copy(value); + } + + /** + * The tint applied to the sprite. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + } + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + */ + + }, { + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + this.cachedTint = 0xFFFFFF; + + this._textureID = -1; + this._textureTrimmedID = -1; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + }]); + + return Sprite; +}(_Container3.default); + +exports.default = Sprite; + +},{"../const":46,"../display/Container":48,"../math":70,"../textures/Texture":115,"../utils":124}],103:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +var _math = require('../../math'); + +var _CanvasTinter = require('./CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var canvasRenderWorldTransform = new _math.Matrix(); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasSpriteRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + */ + +var CanvasSpriteRenderer = function () { + /** + * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for. + */ + function CanvasSpriteRenderer(renderer) { + _classCallCheck(this, CanvasSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + CanvasSpriteRenderer.prototype.render = function render(sprite) { + var texture = sprite._texture; + var renderer = this.renderer; + + var width = texture._frame.width; + var height = texture._frame.height; + + var wt = sprite.transform.worldTransform; + var dx = 0; + var dy = 0; + + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) { + return; + } + + renderer.setBlendMode(sprite.blendMode); + + // Ignore null sources + if (texture.valid) { + renderer.context.globalAlpha = sprite.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture + var smoothingEnabled = texture.baseTexture.scaleMode === _const.SCALE_MODES.LINEAR; + + if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) { + renderer.context[renderer.smoothProperty] = smoothingEnabled; + } + + if (texture.trim) { + dx = texture.trim.width / 2 + texture.trim.x - sprite.anchor.x * texture.orig.width; + dy = texture.trim.height / 2 + texture.trim.y - sprite.anchor.y * texture.orig.height; + } else { + dx = (0.5 - sprite.anchor.x) * texture.orig.width; + dy = (0.5 - sprite.anchor.y) * texture.orig.height; + } + + if (texture.rotate) { + wt.copy(canvasRenderWorldTransform); + wt = canvasRenderWorldTransform; + _math.GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); + // the anchor has already been applied above, so lets set it to zero + dx = 0; + dy = 0; + } + + dx -= width / 2; + dy -= height / 2; + + // Allow for pixel rounding + if (renderer.roundPixels) { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution | 0, wt.ty * renderer.resolution | 0); + + dx = dx | 0; + dy = dy | 0; + } else { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution, wt.ty * renderer.resolution); + } + + var resolution = texture.baseTexture.resolution; + + if (sprite.tint !== 0xFFFFFF) { + if (sprite.cachedTint !== sprite.tint || sprite.tintedTexture.tintId !== sprite._texture._updateID) { + sprite.cachedTint = sprite.tint; + + // TODO clean up caching - how to clean up the caches? + sprite.tintedTexture = _CanvasTinter2.default.getTintedTexture(sprite, sprite.tint); + } + + renderer.context.drawImage(sprite.tintedTexture, 0, 0, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } else { + renderer.context.drawImage(texture.baseTexture.source, texture._frame.x * resolution, texture._frame.y * resolution, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } + } + }; + + /** + * destroy the sprite object. + * + */ + + + CanvasSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasSpriteRenderer; +}(); + +exports.default = CanvasSpriteRenderer; + + +_CanvasRenderer2.default.registerPlugin('sprite', CanvasSpriteRenderer); + +},{"../../const":46,"../../math":70,"../../renderers/canvas/CanvasRenderer":77,"./CanvasTinter":104}],104:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class + * @memberof PIXI + */ +var CanvasTinter = { + /** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Sprite} sprite - the sprite to tint + * @param {number} color - the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ + getTintedTexture: function getTintedTexture(sprite, color) { + var texture = sprite._texture; + + color = CanvasTinter.roundColor(color); + + var stringColor = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + texture.tintCache = texture.tintCache || {}; + + var cachedTexture = texture.tintCache[stringColor]; + + var canvas = void 0; + + if (cachedTexture) { + if (cachedTexture.tintId === texture._updateID) { + return texture.tintCache[stringColor]; + } + + canvas = texture.tintCache[stringColor]; + } else { + canvas = CanvasTinter.canvas || document.createElement('canvas'); + } + + CanvasTinter.tintMethod(texture, color, canvas); + + canvas.tintId = texture._updateID; + + if (CanvasTinter.convertTintToImage) { + // is this better? + var tintImage = new Image(); + + tintImage.src = canvas.toDataURL(); + + texture.tintCache[stringColor] = tintImage; + } else { + texture.tintCache[stringColor] = canvas; + // if we are not converting the texture to an image then we need to lose the reference to the canvas + CanvasTinter.canvas = null; + } + + return canvas; + }, + + /** + * Tint a texture using the 'multiply' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithMultiply: function tintWithMultiply(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + }, + + /** + * Tint a texture using the 'overlay' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithOverlay: function tintWithOverlay(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.globalCompositeOperation = 'copy'; + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + // context.globalCompositeOperation = 'copy'; + }, + + + /** + * Tint a texture pixel per pixel. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithPerPixel: function tintWithPerPixel(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.globalCompositeOperation = 'copy'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + var rgbValues = (0, _utils.hex2rgb)(color); + var r = rgbValues[0]; + var g = rgbValues[1]; + var b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, crop.width, crop.height); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + } + + context.putImageData(pixelData, 0, 0); + }, + + /** + * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel. + * + * @memberof PIXI.CanvasTinter + * @param {number} color - the color to round, should be a hex color + * @return {number} The rounded color. + */ + roundColor: function roundColor(color) { + var step = CanvasTinter.cacheStepsPerColorChannel; + + var rgbValues = (0, _utils.hex2rgb)(color); + + rgbValues[0] = Math.min(255, rgbValues[0] / step * step); + rgbValues[1] = Math.min(255, rgbValues[1] / step * step); + rgbValues[2] = Math.min(255, rgbValues[2] / step * step); + + return (0, _utils.rgb2hex)(rgbValues); + }, + + /** + * Number of steps which will be used as a cap when rounding colors. + * + * @memberof PIXI.CanvasTinter + * @type {number} + */ + cacheStepsPerColorChannel: 8, + + /** + * Tint cache boolean flag. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + convertTintToImage: false, + + /** + * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + canUseMultiply: (0, _canUseNewCanvasBlendModes2.default)(), + + /** + * The tinting method that will be used. + * + * @memberof PIXI.CanvasTinter + * @type {tintMethodFunctionType} + */ + tintMethod: 0 +}; + +CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply : CanvasTinter.tintWithPerPixel; + +/** + * The tintMethod type. + * + * @memberof PIXI.CanvasTinter + * @callback tintMethodFunctionType + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + +exports.default = CanvasTinter; + +},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":80,"../../utils":124}],105:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Buffer = function () { + /** + * @param {number} size - The size of the buffer in bytes. + */ + function Buffer(size) { + _classCallCheck(this, Buffer); + + this.vertices = new ArrayBuffer(size); + + /** + * View on the vertices as a Float32Array for positions + * + * @member {Float32Array} + */ + this.float32View = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array for uvs + * + * @member {Float32Array} + */ + this.uint32View = new Uint32Array(this.vertices); + } + + /** + * Destroys the buffer. + * + */ + + + Buffer.prototype.destroy = function destroy() { + this.vertices = null; + this.positions = null; + this.uvs = null; + this.colors = null; + }; + + return Buffer; +}(); + +exports.default = Buffer; + +},{}],106:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _createIndicesForQuads = require('../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +var _generateMultiTextureShader = require('./generateMultiTextureShader'); + +var _generateMultiTextureShader2 = _interopRequireDefault(_generateMultiTextureShader); + +var _checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'); + +var _checkMaxIfStatmentsInShader2 = _interopRequireDefault(_checkMaxIfStatmentsInShader); + +var _BatchBuffer = require('./BatchBuffer'); + +var _BatchBuffer2 = _interopRequireDefault(_BatchBuffer); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var TICK = 0; +var TEXTURE_TICK = 0; + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var SpriteRenderer = function (_ObjectRenderer) { + _inherits(SpriteRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function SpriteRenderer(renderer) { + _classCallCheck(this, SpriteRenderer); + + /** + * Number of values sent in the vertex buffer. + * aVertexPosition(2), aTextureCoord(1), aColor(1), aTextureId(1) = 5 + * + * @member {number} + */ + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.vertSize = 5; + + /** + * The size of the vertex information in bytes. + * + * @member {number} + */ + _this.vertByteSize = _this.vertSize * 4; + + /** + * The number of images in the SpriteRenderer before it flushes. + * + * @member {number} + */ + _this.size = _settings2.default.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + + // the total number of bytes in our batch + // let numVerts = this.size * 4 * this.vertByteSize; + + _this.buffers = []; + for (var i = 1; i <= _bitTwiddle2.default.nextPow2(_this.size); i *= 2) { + _this.buffers.push(new _BatchBuffer2.default(i * 4 * _this.vertByteSize)); + } + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + _this.indices = (0, _createIndicesForQuads2.default)(_this.size); + + /** + * The default shaders that is used if a sprite doesn't have a more specific one. + * there is a shader for each number of textures that can be rendererd. + * These shaders will also be generated on the fly as required. + * @member {PIXI.Shader[]} + */ + _this.shader = null; + + _this.currentIndex = 0; + _this.groups = []; + + for (var k = 0; k < _this.size; k++) { + _this.groups[k] = { textures: [], textureCount: 0, ids: [], size: 0, start: 0, blend: 0 }; + } + + _this.sprites = []; + + _this.vertexBuffers = []; + _this.vaos = []; + + _this.vaoMax = 2; + _this.vertexCount = 0; + + _this.renderer.on('prerender', _this.onPrerender, _this); + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + SpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + if (this.renderer.legacy) { + this.MAX_TEXTURES = 1; + } else { + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), _settings2.default.SPRITE_MAX_TEXTURES); + + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = (0, _checkMaxIfStatmentsInShader2.default)(this.MAX_TEXTURES, gl); + } + + this.shader = (0, _generateMultiTextureShader2.default)(gl, this.MAX_TEXTURES); + + // create a couple of buffers + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + // we use the second shader as the first one depending on your browser may omit aTextureId + // as it is not used by the shader so is optimized out. + + this.renderer.bindVao(null); + + var attrs = this.shader.attributes; + + for (var i = 0; i < this.vaoMax; i++) { + /* eslint-disable max-len */ + var vertexBuffer = this.vertexBuffers[i] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + /* eslint-enable max-len */ + + // build the vao object that will render.. + var vao = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (attrs.aTextureId) { + vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vaos[i] = vao; + } + + this.vao = this.vaos[0]; + this.currentBlendMode = 99999; + + this.boundTextures = new Array(this.MAX_TEXTURES); + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + SpriteRenderer.prototype.onPrerender = function onPrerender() { + this.vertexCount = 0; + }; + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + SpriteRenderer.prototype.render = function render(sprite) { + // TODO set blend modes.. + // check texture.. + if (this.currentIndex >= this.size) { + this.flush(); + } + + // get the uvs for the texture + + // if the uvs have not updated then no point rendering just yet! + if (!sprite._texture._uvs) { + return; + } + + // push a texture. + // increment the batchsize + this.sprites[this.currentIndex++] = sprite; + }; + + /** + * Renders the content and empties the current batch. + * + */ + + + SpriteRenderer.prototype.flush = function flush() { + if (this.currentIndex === 0) { + return; + } + + var gl = this.renderer.gl; + var MAX_TEXTURES = this.MAX_TEXTURES; + + var np2 = _bitTwiddle2.default.nextPow2(this.currentIndex); + var log2 = _bitTwiddle2.default.log2(np2); + var buffer = this.buffers[log2]; + + var sprites = this.sprites; + var groups = this.groups; + + var float32View = buffer.float32View; + var uint32View = buffer.uint32View; + + var boundTextures = this.boundTextures; + var rendererBoundTextures = this.renderer.boundTextures; + var touch = this.renderer.textureGC.count; + + var index = 0; + var nextTexture = void 0; + var currentTexture = void 0; + var groupCount = 1; + var textureCount = 0; + var currentGroup = groups[0]; + var vertexData = void 0; + var uvs = void 0; + var blendMode = _utils.premultiplyBlendMode[sprites[0]._texture.baseTexture.premultipliedAlpha ? 1 : 0][sprites[0].blendMode]; + + currentGroup.textureCount = 0; + currentGroup.start = 0; + currentGroup.blend = blendMode; + + TICK++; + + var i = void 0; + + // copy textures.. + for (i = 0; i < MAX_TEXTURES; ++i) { + boundTextures[i] = rendererBoundTextures[i]; + boundTextures[i]._virtalBoundId = i; + } + + for (i = 0; i < this.currentIndex; ++i) { + // upload the sprite elemetns... + // they have all ready been calculated so we just need to push them into the buffer. + var sprite = sprites[i]; + + nextTexture = sprite._texture.baseTexture; + + var spriteBlendMode = _utils.premultiplyBlendMode[Number(nextTexture.premultipliedAlpha)][sprite.blendMode]; + + if (blendMode !== spriteBlendMode) { + // finish a group.. + blendMode = spriteBlendMode; + + // force the batch to break! + currentTexture = null; + textureCount = MAX_TEXTURES; + TICK++; + } + + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + + if (nextTexture._enabled !== TICK) { + if (textureCount === MAX_TEXTURES) { + TICK++; + + currentGroup.size = i - currentGroup.start; + + textureCount = 0; + + currentGroup = groups[groupCount++]; + currentGroup.blend = blendMode; + currentGroup.textureCount = 0; + currentGroup.start = i; + } + + nextTexture.touched = touch; + + if (nextTexture._virtalBoundId === -1) { + for (var j = 0; j < MAX_TEXTURES; ++j) { + var tIndex = (j + TEXTURE_TICK) % MAX_TEXTURES; + + var t = boundTextures[tIndex]; + + if (t._enabled !== TICK) { + TEXTURE_TICK++; + + t._virtalBoundId = -1; + + nextTexture._virtalBoundId = tIndex; + + boundTextures[tIndex] = nextTexture; + break; + } + } + } + + nextTexture._enabled = TICK; + + currentGroup.textureCount++; + currentGroup.ids[textureCount] = nextTexture._virtalBoundId; + currentGroup.textures[textureCount++] = nextTexture; + } + } + + vertexData = sprite.vertexData; + + // TODO this sum does not need to be set each frame.. + uvs = sprite._texture._uvs.uvsUint32; + + if (this.renderer.roundPixels) { + var resolution = this.renderer.resolution; + + // xy + float32View[index] = (vertexData[0] * resolution | 0) / resolution; + float32View[index + 1] = (vertexData[1] * resolution | 0) / resolution; + + // xy + float32View[index + 5] = (vertexData[2] * resolution | 0) / resolution; + float32View[index + 6] = (vertexData[3] * resolution | 0) / resolution; + + // xy + float32View[index + 10] = (vertexData[4] * resolution | 0) / resolution; + float32View[index + 11] = (vertexData[5] * resolution | 0) / resolution; + + // xy + float32View[index + 15] = (vertexData[6] * resolution | 0) / resolution; + float32View[index + 16] = (vertexData[7] * resolution | 0) / resolution; + } else { + // xy + float32View[index] = vertexData[0]; + float32View[index + 1] = vertexData[1]; + + // xy + float32View[index + 5] = vertexData[2]; + float32View[index + 6] = vertexData[3]; + + // xy + float32View[index + 10] = vertexData[4]; + float32View[index + 11] = vertexData[5]; + + // xy + float32View[index + 15] = vertexData[6]; + float32View[index + 16] = vertexData[7]; + } + + uint32View[index + 2] = uvs[0]; + uint32View[index + 7] = uvs[1]; + uint32View[index + 12] = uvs[2]; + uint32View[index + 17] = uvs[3]; + /* eslint-disable max-len */ + var alpha = Math.min(sprite.worldAlpha, 1.0); + // we dont call extra function if alpha is 1.0, that's faster + var argb = alpha < 1.0 && nextTexture.premultipliedAlpha ? (0, _utils.premultiplyTint)(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); + + uint32View[index + 3] = uint32View[index + 8] = uint32View[index + 13] = uint32View[index + 18] = argb; + float32View[index + 4] = float32View[index + 9] = float32View[index + 14] = float32View[index + 19] = nextTexture._virtalBoundId; + /* eslint-enable max-len */ + + index += 20; + } + + currentGroup.size = i - currentGroup.start; + + if (!_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // this is still needed for IOS performance.. + // it really does not like uploading to the same buffer in a single frame! + if (this.vaoMax <= this.vertexCount) { + this.vaoMax++; + + var attrs = this.shader.attributes; + + /* eslint-disable max-len */ + var vertexBuffer = this.vertexBuffers[this.vertexCount] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + /* eslint-enable max-len */ + + // build the vao object that will render.. + var vao = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (attrs.aTextureId) { + vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vaos[this.vertexCount] = vao; + } + + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, false); + + this.vertexCount++; + } else { + // lets use the faster option, always use buffer number 0 + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, true); + } + + for (i = 0; i < MAX_TEXTURES; ++i) { + rendererBoundTextures[i]._virtalBoundId = -1; + } + + // render the groups.. + for (i = 0; i < groupCount; ++i) { + var group = groups[i]; + var groupTextureCount = group.textureCount; + + for (var _j = 0; _j < groupTextureCount; _j++) { + currentTexture = group.textures[_j]; + + // reset virtual ids.. + // lets do a quick check.. + if (rendererBoundTextures[group.ids[_j]] !== currentTexture) { + this.renderer.bindTexture(currentTexture, group.ids[_j], true); + } + + // reset the virtualId.. + currentTexture._virtalBoundId = -1; + } + + // set the blend mode.. + this.renderer.state.setBlendMode(group.blend); + + gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); + } + + // reset elements for the next flush + this.currentIndex = 0; + }; + + /** + * Starts a new sprite batch. + */ + + + SpriteRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + + if (_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // bind buffer #0, we don't need others + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].bind(); + } + }; + + /** + * Stops and flushes the current batch. + * + */ + + + SpriteRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Destroys the SpriteRenderer. + * + */ + + + SpriteRenderer.prototype.destroy = function destroy() { + for (var i = 0; i < this.vaoMax; i++) { + if (this.vertexBuffers[i]) { + this.vertexBuffers[i].destroy(); + } + if (this.vaos[i]) { + this.vaos[i].destroy(); + } + } + + if (this.indexBuffer) { + this.indexBuffer.destroy(); + } + + this.renderer.off('prerender', this.onPrerender, this); + + _ObjectRenderer.prototype.destroy.call(this); + + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } + + this.vertexBuffers = null; + this.vaos = null; + this.indexBuffer = null; + this.indices = null; + + this.sprites = null; + + for (var _i = 0; _i < this.buffers.length; ++_i) { + this.buffers[_i].destroy(); + } + }; + + return SpriteRenderer; +}(_ObjectRenderer3.default); + +exports.default = SpriteRenderer; + + +_WebGLRenderer2.default.registerPlugin('sprite', SpriteRenderer); + +},{"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":97,"../../settings":101,"../../utils":124,"../../utils/createIndicesForQuads":122,"./BatchBuffer":105,"./generateMultiTextureShader":107,"bit-twiddle":1,"pixi-gl-core":12}],107:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateMultiTextureShader; + +var _Shader = require('../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'varying float vTextureId;', 'uniform sampler2D uSamplers[%count%];', 'void main(void){', 'vec4 color;', 'float textureId = floor(vTextureId+0.5);', '%forloop%', 'gl_FragColor = color * vColor;', '}'].join('\n'); + +function generateMultiTextureShader(gl, maxTextures) { + var vertexSrc = 'precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor;\n}\n'; + var fragmentSrc = fragTemplate; + + fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); + + var shader = new _Shader2.default(gl, vertexSrc, fragmentSrc); + + var sampleValues = []; + + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + + shader.bind(); + shader.uniforms.uSamplers = sampleValues; + + return shader; +} + +function generateSampleSrc(maxTextures) { + var src = ''; + + src += '\n'; + src += '\n'; + + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxTextures - 1) { + src += 'if(textureId == ' + i + '.0)'; + } + + src += '\n{'; + src += '\n\tcolor = texture2D(uSamplers[' + i + '], vTextureCoord);'; + src += '\n}'; + } + + src += '\n'; + src += '\n'; + + return src; +} + +},{"../../Shader":44,"path":23}],108:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Sprite2 = require('../sprites/Sprite'); + +var _Sprite3 = _interopRequireDefault(_Sprite2); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TextStyle = require('./TextStyle'); + +var _TextStyle2 = _interopRequireDefault(_TextStyle); + +var _TextMetrics = require('./TextMetrics'); + +var _TextMetrics2 = _interopRequireDefault(_TextMetrics); + +var _trimCanvas = require('../utils/trimCanvas'); + +var _trimCanvas2 = _interopRequireDefault(_trimCanvas); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint max-depth: [2, 8] */ + + +var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true +}; + +/** + * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string, + * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object. + * + * A Text can be created directly from a string and a style object + * + * ```js + * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI + */ + +var Text = function (_Sprite) { + _inherits(Text, _Sprite); + + /** + * @param {string} text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + * @param {HTMLCanvasElement} [canvas] - The canvas element for drawing text + */ + function Text(text, style, canvas) { + _classCallCheck(this, Text); + + canvas = canvas || document.createElement('canvas'); + + canvas.width = 3; + canvas.height = 3; + + var texture = _Texture2.default.fromCanvas(canvas, _settings2.default.SCALE_MODE, 'text'); + + texture.orig = new _math.Rectangle(); + texture.trim = new _math.Rectangle(); + + // base texture is already automatically added to the cache, now adding the actual texture + var _this = _possibleConstructorReturn(this, _Sprite.call(this, texture)); + + _Texture2.default.addToCache(_this._texture, _this._texture.baseTexture.textureCacheIds[0]); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.canvas = canvas; + + /** + * The canvas 2d context that everything is drawn with + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.canvas.getContext('2d'); + + /** + * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. + * @member {number} + * @default 1 + */ + _this.resolution = _settings2.default.RESOLUTION; + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = null; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._style = null; + /** + * Private listener to track style changes. + * + * @member {Function} + * @private + */ + _this._styleListener = null; + + /** + * Private tracker for the current font. + * + * @member {string} + * @private + */ + _this._font = ''; + + _this.text = text; + _this.style = style; + + _this.localStyleID = -1; + return _this; + } + + /** + * Renders text and updates it when needed. + * + * @private + * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. + */ + + + Text.prototype.updateText = function updateText(respectDirty) { + var style = this._style; + + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + + if (!this.dirty && respectDirty) { + return; + } + + this._font = this._style.toFontString(); + + var context = this.context; + var measured = _TextMetrics2.default.measureText(this._text, this._style, this._style.wordWrap, this.canvas); + var width = measured.width; + var height = measured.height; + var lines = measured.lines; + var lineHeight = measured.lineHeight; + var lineWidths = measured.lineWidths; + var maxLineWidth = measured.maxLineWidth; + var fontProperties = measured.fontProperties; + + this.canvas.width = Math.ceil((width + style.padding * 2) * this.resolution); + this.canvas.height = Math.ceil((height + style.padding * 2) * this.resolution); + + context.scale(this.resolution, this.resolution); + + context.clearRect(0, 0, this.canvas.width, this.canvas.height); + + context.font = this._font; + context.strokeStyle = style.stroke; + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + + var linePositionX = void 0; + var linePositionY = void 0; + + if (style.dropShadow) { + context.fillStyle = style.dropShadowColor; + context.globalAlpha = style.dropShadowAlpha; + context.shadowBlur = style.dropShadowBlur; + + if (style.dropShadowBlur > 0) { + context.shadowColor = style.dropShadowColor; + } + + var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + + for (var i = 0; i < lines.length; i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (style.fill) { + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); + + if (style.stroke && style.strokeThickness) { + context.strokeStyle = style.dropShadowColor; + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding, true); + context.strokeStyle = style.stroke; + } + } + } + } + + // reset the shadow blur and alpha that was set by the drop shadow, for the regular text + context.shadowBlur = 0; + context.globalAlpha = 1; + + // set canvas text styles + context.fillStyle = this._generateFillStyle(style, lines); + + // draw lines line by line + for (var _i = 0; _i < lines.length; _i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i]) / 2; + } + + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding, true); + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding); + } + } + + this.updateTexture(); + }; + + /** + * Render the text with letter-spacing. + * @param {string} text - The text to draw + * @param {number} x - Horizontal position to draw the text + * @param {number} y - Vertical position to draw the text + * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + * @private + */ + + + Text.prototype.drawLetterSpacing = function drawLetterSpacing(text, x, y) { + var isStroke = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var style = this._style; + + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + + if (letterSpacing === 0) { + if (isStroke) { + this.context.strokeText(text, x, y); + } else { + this.context.fillText(text, x, y); + } + + return; + } + + var characters = String.prototype.split.call(text, ''); + var currentPosition = x; + var index = 0; + var current = ''; + + while (index < text.length) { + current = characters[index++]; + if (isStroke) { + this.context.strokeText(current, currentPosition, y); + } else { + this.context.fillText(current, currentPosition, y); + } + currentPosition += this.context.measureText(current).width + letterSpacing; + } + }; + + /** + * Updates texture size based on canvas size + * + * @private + */ + + + Text.prototype.updateTexture = function updateTexture() { + var canvas = this.canvas; + + if (this._style.trim) { + var trimmed = (0, _trimCanvas2.default)(canvas); + + canvas.width = trimmed.width; + canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } + + var texture = this._texture; + var style = this._style; + var padding = style.trim ? 0 : style.padding; + var baseTexture = texture.baseTexture; + + baseTexture.hasLoaded = true; + baseTexture.resolution = this.resolution; + + baseTexture.realWidth = canvas.width; + baseTexture.realHeight = canvas.height; + baseTexture.width = canvas.width / this.resolution; + baseTexture.height = canvas.height / this.resolution; + + texture.trim.width = texture._frame.width = canvas.width / this.resolution; + texture.trim.height = texture._frame.height = canvas.height / this.resolution; + texture.trim.x = -padding; + texture.trim.y = -padding; + + texture.orig.width = texture._frame.width - padding * 2; + texture.orig.height = texture._frame.height - padding * 2; + + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + + baseTexture.emit('update', baseTexture); + + this.dirty = false; + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Text.prototype.renderWebGL = function renderWebGL(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype.renderWebGL.call(this, renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Text.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype._renderCanvas.call(this, renderer); + }; + + /** + * Gets the local bounds of the text object. + * + * @param {Rectangle} rect - The output rectangle. + * @return {Rectangle} The bounds. + */ + + + Text.prototype.getLocalBounds = function getLocalBounds(rect) { + this.updateText(true); + + return _Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + */ + + + Text.prototype._calculateBounds = function _calculateBounds() { + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; + + /** + * Method to be called upon a TextStyle change. + * @private + */ + + + Text.prototype._onStyleChange = function _onStyleChange() { + this.dirty = true; + }; + + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * + * @private + * @param {object} style - The style. + * @param {string[]} lines - The lines of text. + * @return {string|number|CanvasGradient} The fill style + */ + + + Text.prototype._generateFillStyle = function _generateFillStyle(style, lines) { + if (!Array.isArray(style.fill)) { + return style.fill; + } + + // cocoon on canvas+ cannot generate textures, so use the first colour instead + if (navigator.isCocoonJS) { + return style.fill[0]; + } + + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient = void 0; + var totalIterations = void 0; + var currentIteration = void 0; + var stop = void 0; + + var width = this.canvas.width / this.resolution; + var height = this.canvas.height / this.resolution; + + // make a copy of the style settings, so we can manipulate them later + var fill = style.fill.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(style.fill[0]); + fillGradientStops.unshift(0); + + fill.push(style.fill[style.fill.length - 1]); + fillGradientStops.push(1); + + if (style.fillGradientType === _const.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); + + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + totalIterations = (fill.length + 1) * lines.length; + currentIteration = 0; + for (var _i2 = 0; _i2 < lines.length; _i2++) { + currentIteration += 1; + for (var j = 0; j < fill.length; j++) { + if (typeof fillGradientStops[j] === 'number') { + stop = fillGradientStops[j] / lines.length + _i2 / lines.length; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[j]); + currentIteration++; + } + } + } else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); + + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + totalIterations = fill.length + 1; + currentIteration = 1; + + for (var _i3 = 0; _i3 < fill.length; _i3++) { + if (typeof fillGradientStops[_i3] === 'number') { + stop = fillGradientStops[_i3]; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[_i3]); + currentIteration++; + } + } + + return gradient; + }; + + /** + * Destroys this text object. + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majority of the time the texture will not be shared with any other Sprites. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well + */ + + + Text.prototype.destroy = function destroy(options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + + options = Object.assign({}, defaultDestroyOptions, options); + + _Sprite.prototype.destroy.call(this, options); + + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + + this._style = null; + }; + + /** + * The width of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Text, [{ + key: 'width', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * Set the style of the text. Set up an event listener to listen for changes on the style + * object and mark the text as dirty. + * + * @member {object|PIXI.TextStyle} + */ + + }, { + key: 'style', + get: function get() { + return this._style; + }, + set: function set(style) // eslint-disable-line require-jsdoc + { + style = style || {}; + + if (style instanceof _TextStyle2.default) { + this._style = style; + } else { + this._style = new _TextStyle2.default(style); + } + + this.localStyleID = -1; + this.dirty = true; + } + + /** + * Set the copy for the text object. To split a line you can use '\n'. + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(text) // eslint-disable-line require-jsdoc + { + text = String(text === '' || text === null || text === undefined ? ' ' : text); + + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + } + }]); + + return Text; +}(_Sprite3.default); + +exports.default = Text; + +},{"../const":46,"../math":70,"../settings":101,"../sprites/Sprite":102,"../textures/Texture":115,"../utils":124,"../utils/trimCanvas":129,"./TextMetrics":109,"./TextStyle":110}],109:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The TextMetrics object represents the measurement of a block of text with a specified style. + * + * @class + * @memberOf PIXI + */ +var TextMetrics = function () { + /** + * @param {string} text - the text that was measured + * @param {PIXI.TextStyle} style - the style that was measured + * @param {number} width - the measured width of the text + * @param {number} height - the measured height of the text + * @param {array} lines - an array of the lines of text broken by new lines and wrapping if specified in style + * @param {array} lineWidths - an array of the line widths for each line matched to `lines` + * @param {number} lineHeight - the measured line height for this style + * @param {number} maxLineWidth - the maximum line width for all measured lines + * @param {Object} fontProperties - the font properties object from TextMetrics.measureFont + */ + function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) { + _classCallCheck(this, TextMetrics); + + this.text = text; + this.style = style; + this.width = width; + this.height = height; + this.lines = lines; + this.lineWidths = lineWidths; + this.lineHeight = lineHeight; + this.maxLineWidth = maxLineWidth; + this.fontProperties = fontProperties; + } + + /** + * Measures the supplied string of text and returns a Rectangle. + * + * @param {string} text - the text to measure. + * @param {PIXI.TextStyle} style - the text style to use for measuring + * @param {boolean} [wordWrap] - optional override for if word-wrap should be applied to the text. + * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. + * @return {PIXI.TextMetrics} measured width and height of the text. + */ + + + TextMetrics.measureText = function measureText(text, style, wordWrap) { + var canvas = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : TextMetrics._canvas; + + wordWrap = wordWrap || style.wordWrap; + var font = style.toFontString(); + var fontProperties = TextMetrics.measureFont(font); + var context = canvas.getContext('2d'); + + context.font = font; + + var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text; + var lines = outputText.split(/(?:\r\n|\r|\n)/); + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + + for (var i = 0; i < lines.length; i++) { + var lineWidth = context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing; + + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + var width = maxLineWidth + style.strokeThickness; + + if (style.dropShadow) { + width += style.dropShadowDistance; + } + + var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * lineHeight; + + if (style.dropShadow) { + height += style.dropShadowDistance; + } + + return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties); + }; + + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @private + * @param {string} text - String to apply word wrapping to + * @param {PIXI.TextStyle} style - the style to use when wrapping + * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. + * @return {string} New string with new lines applied where required + */ + + + TextMetrics.wordWrap = function wordWrap(text, style) { + var canvas = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : TextMetrics._canvas; + + var context = canvas.getContext('2d'); + + // Greedy wrapping algorithm that will wrap words as the line grows longer + // than its horizontal bounds. + var result = ''; + var lines = text.split('\n'); + var wordWrapWidth = style.wordWrapWidth; + var characterCache = {}; + + for (var i = 0; i < lines.length; i++) { + var spaceLeft = wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) { + var wordWidth = context.measureText(words[j]).width; + + if (style.breakWords && wordWidth > wordWrapWidth) { + // Word should be split in the middle + var characters = words[j].split(''); + + for (var c = 0; c < characters.length; c++) { + var character = characters[c]; + var characterWidth = characterCache[character]; + + if (characterWidth === undefined) { + characterWidth = context.measureText(character).width; + characterCache[character] = characterWidth; + } + + if (characterWidth > spaceLeft) { + result += '\n' + character; + spaceLeft = wordWrapWidth - characterWidth; + } else { + if (c === 0) { + result += ' '; + } + + result += character; + spaceLeft -= characterWidth; + } + } + } else { + var wordWidthWithSpace = wordWidth + context.measureText(' ').width; + + if (j === 0 || wordWidthWithSpace > spaceLeft) { + // Skip printing the newline if it's the first word of the line that is + // greater than the word wrap width. + if (j > 0) { + result += '\n'; + } + result += words[j]; + spaceLeft = wordWrapWidth - wordWidth; + } else { + spaceLeft -= wordWidthWithSpace; + result += ' ' + words[j]; + } + } + } + + if (i < lines.length - 1) { + result += '\n'; + } + } + + return result; + }; + + /** + * Calculates the ascent, descent and fontSize of a given font-style + * + * @static + * @param {string} font - String representing the style of the font + * @return {PIXI.TextMetrics~FontMetrics} Font properties object + */ + + + TextMetrics.measureFont = function measureFont(font) { + // as this method is used for preparing assets, don't recalculate things if we don't need to + if (TextMetrics._fonts[font]) { + return TextMetrics._fonts[font]; + } + + var properties = {}; + + var canvas = TextMetrics._canvas; + var context = TextMetrics._context; + + context.font = font; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('M').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = font; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i = 0; + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } else { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var _j = 0; _j < line; _j += 4) { + if (imagedata[idx + _j] !== 255) { + stop = true; + break; + } + } + + if (!stop) { + idx -= line; + } else { + break; + } + } + + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + + TextMetrics._fonts[font] = properties; + + return properties; + }; + + return TextMetrics; +}(); + +/** + * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}. + * @class FontMetrics + * @memberof PIXI.TextMetrics~ + * @property {number} ascent - The ascent distance + * @property {number} descent - The descent distance + * @property {number} fontSize - Font size from ascent to descent + */ + +exports.default = TextMetrics; +var canvas = document.createElement('canvas'); + +canvas.width = canvas.height = 10; + +/** + * Cached canvas element for measuring text + * @memberof PIXI.TextMetrics + * @type {HTMLCanvasElement} + * @private + */ +TextMetrics._canvas = canvas; + +/** + * Cache for context to use. + * @memberof PIXI.TextMetrics + * @type {CanvasRenderingContext2D} + * @private + */ +TextMetrics._context = canvas.getContext('2d'); + +/** + * Cache of PIXI.TextMetrics~FontMetrics objects. + * @memberof PIXI.TextMetrics + * @type {Object} + * @private + */ +TextMetrics._fonts = {}; + +},{}],110:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // disabling eslint for now, going to rewrite this in v5 +/* eslint-disable */ + +var _const = require('../const'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: 'black', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: _const.TEXT_GRADIENT.LINEAR_VERTICAL, + fillGradientStops: [], + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + trim: false, + wordWrap: false, + wordWrapWidth: 100 +}; + +/** + * A TextStyle Object decorates a Text Object. It can be shared between + * multiple Text objects. Changing the style will update all text objects using it. + * + * @class + * @memberof PIXI + */ + +var TextStyle = function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours + * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} + * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set + * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * @param {string|string[]} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', 800' or '900') + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Default is 'miter' (creates a sharp corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {boolean} [style.trim=false] - Trim transparent borders + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + _classCallCheck(this, TextStyle); + + this.styleID = 0; + + Object.assign(this, defaultStyle, style); + } + + /** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return {PIXI.TextStyle} New cloned TextStyle object + */ + + + TextStyle.prototype.clone = function clone() { + var clonedProperties = {}; + + for (var key in defaultStyle) { + clonedProperties[key] = this[key]; + } + + return new TextStyle(clonedProperties); + }; + + /** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ + + + TextStyle.prototype.reset = function reset() { + Object.assign(this, defaultStyle); + }; + + /** + * Generates a font style string to use for `TextMetrics.measureFont()`. + * + * @return {string} Font style string, for passing to `TextMetrics.measureFont()` + */ + TextStyle.prototype.toFontString = function toFontString() { + // build canvas api font setting from individual components. Convert a numeric this.fontSize to px + var fontSizeString = typeof this.fontSize === 'number' ? this.fontSize + 'px' : this.fontSize; + + // Clean-up fontFamily property by quoting each font name + // this will support font names with spaces + var fontFamilies = this.fontFamily; + + if (!Array.isArray(this.fontFamily)) { + fontFamilies = this.fontFamily.split(','); + } + + for (var i = fontFamilies.length - 1; i >= 0; i--) { + // Trim any extra white-space + var fontFamily = fontFamilies[i].trim(); + + // Check if font already contains strings + if (!/([\"\'])[^\'\"]+\1/.test(fontFamily)) { + fontFamily = '"' + fontFamily + '"'; + } + fontFamilies[i] = fontFamily; + } + + return this.fontStyle + ' ' + this.fontVariant + ' ' + this.fontWeight + ' ' + fontSizeString + ' ' + fontFamilies.join(','); + }; + + _createClass(TextStyle, [{ + key: 'align', + get: function get() { + return this._align; + }, + set: function set(align) { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + } + }, { + key: 'breakWords', + get: function get() { + return this._breakWords; + }, + set: function set(breakWords) { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + } + }, { + key: 'dropShadow', + get: function get() { + return this._dropShadow; + }, + set: function set(dropShadow) { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + } + }, { + key: 'dropShadowAlpha', + get: function get() { + return this._dropShadowAlpha; + }, + set: function set(dropShadowAlpha) { + if (this._dropShadowAlpha !== dropShadowAlpha) { + this._dropShadowAlpha = dropShadowAlpha; + this.styleID++; + } + } + }, { + key: 'dropShadowAngle', + get: function get() { + return this._dropShadowAngle; + }, + set: function set(dropShadowAngle) { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + } + }, { + key: 'dropShadowBlur', + get: function get() { + return this._dropShadowBlur; + }, + set: function set(dropShadowBlur) { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + } + }, { + key: 'dropShadowColor', + get: function get() { + return this._dropShadowColor; + }, + set: function set(dropShadowColor) { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + } + }, { + key: 'dropShadowDistance', + get: function get() { + return this._dropShadowDistance; + }, + set: function set(dropShadowDistance) { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + } + }, { + key: 'fill', + get: function get() { + return this._fill; + }, + set: function set(fill) { + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + } + }, { + key: 'fillGradientType', + get: function get() { + return this._fillGradientType; + }, + set: function set(fillGradientType) { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + } + }, { + key: 'fillGradientStops', + get: function get() { + return this._fillGradientStops; + }, + set: function set(fillGradientStops) { + if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { + this._fillGradientStops = fillGradientStops; + this.styleID++; + } + } + }, { + key: 'fontFamily', + get: function get() { + return this._fontFamily; + }, + set: function set(fontFamily) { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + } + }, { + key: 'fontSize', + get: function get() { + return this._fontSize; + }, + set: function set(fontSize) { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + } + }, { + key: 'fontStyle', + get: function get() { + return this._fontStyle; + }, + set: function set(fontStyle) { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + } + }, { + key: 'fontVariant', + get: function get() { + return this._fontVariant; + }, + set: function set(fontVariant) { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + } + }, { + key: 'fontWeight', + get: function get() { + return this._fontWeight; + }, + set: function set(fontWeight) { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + } + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(letterSpacing) { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + } + }, { + key: 'lineHeight', + get: function get() { + return this._lineHeight; + }, + set: function set(lineHeight) { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + } + }, { + key: 'lineJoin', + get: function get() { + return this._lineJoin; + }, + set: function set(lineJoin) { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + } + }, { + key: 'miterLimit', + get: function get() { + return this._miterLimit; + }, + set: function set(miterLimit) { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + } + }, { + key: 'padding', + get: function get() { + return this._padding; + }, + set: function set(padding) { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + } + }, { + key: 'stroke', + get: function get() { + return this._stroke; + }, + set: function set(stroke) { + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + } + }, { + key: 'strokeThickness', + get: function get() { + return this._strokeThickness; + }, + set: function set(strokeThickness) { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + } + }, { + key: 'textBaseline', + get: function get() { + return this._textBaseline; + }, + set: function set(textBaseline) { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + } + }, { + key: 'trim', + get: function get() { + return this._trim; + }, + set: function set(trim) { + if (this._trim !== trim) { + this._trim = trim; + this.styleID++; + } + } + }, { + key: 'wordWrap', + get: function get() { + return this._wordWrap; + }, + set: function set(wordWrap) { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + } + }, { + key: 'wordWrapWidth', + get: function get() { + return this._wordWrapWidth; + }, + set: function set(wordWrapWidth) { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + } + }]); + + return TextStyle; +}(); + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * + * @param {number|number[]} color + * @return {string} The color as a string. + */ + + +exports.default = TextStyle; +function getSingleColor(color) { + if (typeof color === 'number') { + return (0, _utils.hex2string)(color); + } else if (typeof color === 'string') { + if (color.indexOf('0x') === 0) { + color = color.replace('0x', '#'); + } + } + + return color; +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * + * @param {number|number[]} color + * @return {string} The color as a string. + */ +function getColor(color) { + if (!Array.isArray(color)) { + return getSingleColor(color); + } else { + for (var i = 0; i < color.length; ++i) { + color[i] = getSingleColor(color[i]); + } + + return color; + } +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * + * @param {Array} array1 First array to compare + * @param {Array} array2 Second array to compare + * @return {boolean} Do the arrays contain the same values in the same order + */ +function areArraysEqual(array1, array2) { + if (!Array.isArray(array1) || !Array.isArray(array2)) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } + + return true; +} + +},{"../const":46,"../utils":124}],111:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let baseRenderTexture = new PIXI.BaseRenderTexture(renderer, 800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * baseRenderTexture.render(sprite); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let baseRenderTexture = new PIXI.BaseRenderTexture(100, 100); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var BaseRenderTexture = function (_BaseTexture) { + _inherits(BaseRenderTexture, _BaseTexture); + + /** + * @param {number} [width=100] - The width of the base render texture + * @param {number} [height=100] - The height of the base render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + */ + function BaseRenderTexture() { + var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + + _classCallCheck(this, BaseRenderTexture); + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, null, scaleMode)); + + _this.resolution = resolution || _settings2.default.RESOLUTION; + + _this.width = width; + _this.height = height; + + _this.realWidth = _this.width * _this.resolution; + _this.realHeight = _this.height * _this.resolution; + + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + _this.hasLoaded = true; + + /** + * A map of renderer IDs to webgl renderTargets + * + * @private + * @member {object} + */ + _this._glRenderTargets = {}; + + /** + * A reference to the canvas render target (we only need one as this can be shared across renderers) + * + * @private + * @member {object} + */ + _this._canvasRenderTarget = null; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + return _this; + } + + /** + * Resizes the BaseRenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + */ + + + BaseRenderTexture.prototype.resize = function resize(width, height) { + if (width === this.width && height === this.height) { + return; + } + + this.valid = width > 0 && height > 0; + + this.width = width; + this.height = height; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + if (!this.valid) { + return; + } + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + */ + + + BaseRenderTexture.prototype.destroy = function destroy() { + _BaseTexture.prototype.destroy.call(this, true); + this.renderer = null; + }; + + return BaseRenderTexture; +}(_BaseTexture3.default); + +exports.default = BaseRenderTexture; + +},{"../settings":101,"./BaseTexture":112}],112:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var BaseTexture = function (_EventEmitter) { + _inherits(BaseTexture, _EventEmitter); + + /** + * @param {HTMLImageElement|HTMLCanvasElement} [source] - the source object of the texture. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture + */ + function BaseTexture(source, scaleMode, resolution) { + _classCallCheck(this, BaseTexture); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.uid = (0, _utils.uid)(); + + _this.touched = 0; + + /** + * The resolution / device pixel ratio of the texture + * + * @member {number} + * @default 1 + */ + _this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The width of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.width = 100; + + /** + * The height of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.height = 100; + + // TODO docs + // used to store the actual dimensions of the source + /** + * Used to store the actual width of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realWidth = 100; + /** + * Used to store the actual height of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realHeight = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Set to true once the base texture has successfully loaded. + * + * This is never true if the underlying source fails to load or has no texture data. + * + * @readonly + * @member {boolean} + */ + _this.hasLoaded = false; + + /** + * Set to true if the source is currently loading. + * + * If an Image source is loading the 'loaded' or 'error' event will be + * dispatched when the operation ends. An underyling source that is + * immediately-available bypasses loading entirely. + * + * @readonly + * @member {boolean} + */ + _this.isLoading = false; + + /** + * The image source that is used to create the texture. + * + * TODO: Make this a setter that calls loadSource(); + * + * @readonly + * @member {HTMLImageElement|HTMLCanvasElement} + */ + _this.source = null; // set in loadSource, if at all + + /** + * The image source that is used to create the texture. This is used to + * store the original Svg source when it is replaced with a canvas element. + * + * TODO: Currently not in use but could be used when re-scaling svg. + * + * @readonly + * @member {Image} + */ + _this.origSource = null; // set in loadSvg, if at all + + /** + * Type of image defined in source, eg. `png` or `svg` + * + * @readonly + * @member {string} + */ + _this.imageType = null; // set in updateImageType + + /** + * Scale for source image. Used with Svg images to scale them before rasterization. + * + * @readonly + * @member {number} + */ + _this.sourceScale = 1.0; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * All blend modes, and shaders written for default value. Change it on your own risk. + * + * @member {boolean} + * @default true + */ + _this.premultipliedAlpha = true; + + /** + * The image url of the texture + * + * @member {string} + */ + _this.imageUrl = null; + + /** + * Whether or not the texture is a power of two, try to use power of two textures as much + * as you can + * + * @private + * @member {boolean} + */ + _this.isPowerOfTwo = false; + + // used for webGL + + /** + * + * Set this to true if a mipmap of this texture needs to be generated. This value needs + * to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @member {boolean} + * @see PIXI.MIPMAP_TEXTURES + */ + _this.mipmap = _settings2.default.MIPMAP_TEXTURES; + + /** + * + * WebGL Texture wrap mode + * + * @member {number} + * @see PIXI.WRAP_MODES + */ + _this.wrapMode = _settings2.default.WRAP_MODE; + + /** + * A map of renderer IDs to webgl textures + * + * @private + * @member {object} + */ + _this._glTextures = {}; + + _this._enabled = 0; + _this._virtalBoundId = -1; + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + + /** + * The ids under which this BaseTexture has been added to the base texture cache. This is + * automatically set as long as BaseTexture.addToCache is used, but may not be set if a + * BaseTexture is added directly to the BaseTextureCache array. + * + * @member {string[]} + */ + _this.textureCacheIds = []; + + // if no source passed don't try to load + if (source) { + _this.loadSource(source); + } + + /** + * Fired when a not-immediately-available source finishes loading. + * + * @protected + * @event PIXI.BaseTexture#loaded + * @param {PIXI.BaseTexture} baseTexture - Resource loaded. + */ + + /** + * Fired when a not-immediately-available source fails to load. + * + * @protected + * @event PIXI.BaseTexture#error + * @param {PIXI.BaseTexture} baseTexture - Resource errored. + */ + + /** + * Fired when BaseTexture is updated. + * + * @protected + * @event PIXI.BaseTexture#update + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. + */ + + /** + * Fired when BaseTexture is destroyed. + * + * @protected + * @event PIXI.BaseTexture#dispose + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. + */ + return _this; + } + + /** + * Updates the texture on all the webgl renderers, this also assumes the src has changed. + * + * @fires PIXI.BaseTexture#update + */ + + + BaseTexture.prototype.update = function update() { + // Svg size is handled during load + if (this.imageType !== 'svg') { + this.realWidth = this.source.naturalWidth || this.source.videoWidth || this.source.width; + this.realHeight = this.source.naturalHeight || this.source.videoHeight || this.source.height; + + this._updateDimensions(); + } + + this.emit('update', this); + }; + + /** + * Update dimensions from real values + */ + + + BaseTexture.prototype._updateDimensions = function _updateDimensions() { + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + this.isPowerOfTwo = _bitTwiddle2.default.isPow2(this.realWidth) && _bitTwiddle2.default.isPow2(this.realHeight); + }; + + /** + * Load a source. + * + * If the source is not-immediately-available, such as an image that needs to be + * downloaded, then the 'loaded' or 'error' event will be dispatched in the future + * and `hasLoaded` will remain false after this call. + * + * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: + * + * if (texture.hasLoaded) { + * // texture ready for use + * } else if (texture.isLoading) { + * // listen to 'loaded' and/or 'error' events on texture + * } else { + * // not loading, not going to load UNLESS the source is reloaded + * // (it may still make sense to listen to the events) + * } + * + * @protected + * @param {HTMLImageElement|HTMLCanvasElement} source - the source object of the texture. + */ + + + BaseTexture.prototype.loadSource = function loadSource(source) { + var wasLoading = this.isLoading; + + this.hasLoaded = false; + this.isLoading = false; + + if (wasLoading && this.source) { + this.source.onload = null; + this.source.onerror = null; + } + + var firstSourceLoaded = !this.source; + + this.source = source; + + // Apply source if loaded. Otherwise setup appropriate loading monitors. + if ((source.src && source.complete || source.getContext) && source.width && source.height) { + this._updateImageType(); + + if (this.imageType === 'svg') { + this._loadSvgSource(); + } else { + this._sourceLoaded(); + } + + if (firstSourceLoaded) { + // send loaded event if previous source was null and we have been passed a pre-loaded IMG element + this.emit('loaded', this); + } + } else if (!source.getContext) { + // Image fail / not ready + this.isLoading = true; + + var scope = this; + + source.onload = function () { + scope._updateImageType(); + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope._sourceLoaded(); + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + scope.emit('loaded', scope); + }; + + source.onerror = function () { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope.emit('error', scope); + }; + + // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element + // "The value of `complete` can thus change while a script is executing." + // So complete needs to be re-checked after the callbacks have been added.. + // NOTE: complete will be true if the image has no src so best to check if the src is set. + if (source.complete && source.src) { + // ..and if we're complete now, no need for callbacks + source.onload = null; + source.onerror = null; + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + this.isLoading = false; + + if (source.width && source.height) { + this._sourceLoaded(); + + // If any previous subscribers possible + if (wasLoading) { + this.emit('loaded', this); + } + } + // If any previous subscribers possible + else if (wasLoading) { + this.emit('error', this); + } + } + } + }; + + /** + * Updates type of the source image. + */ + + + BaseTexture.prototype._updateImageType = function _updateImageType() { + if (!this.imageUrl) { + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + var imageType = void 0; + + if (dataUri && dataUri.mediaType === 'image') { + // Check for subType validity + var firstSubType = dataUri.subType.split('+')[0]; + + imageType = (0, _utils.getUrlFileExtension)('.' + firstSubType); + + if (!imageType) { + throw new Error('Invalid image type in data URI.'); + } + } else { + imageType = (0, _utils.getUrlFileExtension)(this.imageUrl); + + if (!imageType) { + imageType = 'png'; + } + } + + this.imageType = imageType; + }; + + /** + * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls + * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. + */ + + + BaseTexture.prototype._loadSvgSource = function _loadSvgSource() { + if (this.imageType !== 'svg') { + // Do nothing if source is not svg + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + + if (dataUri) { + this._loadSvgSourceUsingDataUri(dataUri); + } else { + // We got an URL, so we need to do an XHR to check the svg size + this._loadSvgSourceUsingXhr(); + } + }; + + /** + * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`. + * + * @param {string} dataUri - The data uri to load from. + */ + + + BaseTexture.prototype._loadSvgSourceUsingDataUri = function _loadSvgSourceUsingDataUri(dataUri) { + var svgString = void 0; + + if (dataUri.encoding === 'base64') { + if (!atob) { + throw new Error('Your browser doesn\'t support base64 conversions.'); + } + svgString = atob(dataUri.data); + } else { + svgString = dataUri.data; + } + + this._loadSvgSourceUsingString(svgString); + }; + + /** + * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. + */ + + + BaseTexture.prototype._loadSvgSourceUsingXhr = function _loadSvgSourceUsingXhr() { + var _this2 = this; + + var svgXhr = new XMLHttpRequest(); + + // This throws error on IE, so SVG Document can't be used + // svgXhr.responseType = 'document'; + + // This is not needed since we load the svg as string (breaks IE too) + // but overrideMimeType() can be used to force the response to be parsed as XML + // svgXhr.overrideMimeType('image/svg+xml'); + + svgXhr.onload = function () { + if (svgXhr.readyState !== svgXhr.DONE || svgXhr.status !== 200) { + throw new Error('Failed to load SVG using XHR.'); + } + + _this2._loadSvgSourceUsingString(svgXhr.response); + }; + + svgXhr.onerror = function () { + return _this2.emit('error', _this2); + }; + + svgXhr.open('GET', this.imageUrl, true); + svgXhr.send(); + }; + + /** + * Loads texture using an SVG string. The original SVG Image is stored as `origSource` and the + * created canvas is the new `source`. The SVG is scaled using `sourceScale`. Called by + * `_loadSvgSourceUsingXhr` or `_loadSvgSourceUsingDataUri`. + * + * @param {string} svgString SVG source as string + * + * @fires PIXI.BaseTexture#loaded + */ + + + BaseTexture.prototype._loadSvgSourceUsingString = function _loadSvgSourceUsingString(svgString) { + var svgSize = (0, _utils.getSvgSize)(svgString); + + var svgWidth = svgSize.width; + var svgHeight = svgSize.height; + + if (!svgWidth || !svgHeight) { + throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); + } + + // Scale realWidth and realHeight + this.realWidth = Math.round(svgWidth * this.sourceScale); + this.realHeight = Math.round(svgHeight * this.sourceScale); + + this._updateDimensions(); + + // Create a canvas element + var canvas = document.createElement('canvas'); + + canvas.width = this.realWidth; + canvas.height = this.realHeight; + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + + // Draw the Svg to the canvas + canvas.getContext('2d').drawImage(this.source, 0, 0, svgWidth, svgHeight, 0, 0, this.realWidth, this.realHeight); + + // Replace the original source image with the canvas + this.origSource = this.source; + this.source = canvas; + + // Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`) + BaseTexture.addToCache(this, canvas._pixiId); + + this.isLoading = false; + this._sourceLoaded(); + this.emit('loaded', this); + }; + + /** + * Used internally to update the width, height, and some other tracking vars once + * a source has successfully loaded. + * + * @private + */ + + + BaseTexture.prototype._sourceLoaded = function _sourceLoaded() { + this.hasLoaded = true; + this.update(); + }; + + /** + * Destroys this base texture + * + */ + + + BaseTexture.prototype.destroy = function destroy() { + if (this.imageUrl) { + delete _utils.TextureCache[this.imageUrl]; + + this.imageUrl = null; + + if (!navigator.isCocoonJS) { + this.source.src = ''; + } + } + + this.source = null; + + this.dispose(); + + BaseTexture.removeFromCache(this); + this.textureCacheIds = null; + + this._destroyed = true; + }; + + /** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + * @fires PIXI.BaseTexture#dispose + */ + + + BaseTexture.prototype.dispose = function dispose() { + this.emit('dispose', this); + }; + + /** + * Changes the source image of the texture. + * The original source must be an Image element. + * + * @param {string} newSrc - the path of the image + */ + + + BaseTexture.prototype.updateSourceImage = function updateSourceImage(newSrc) { + this.source.src = newSrc; + + this.loadSource(this.source); + }; + + /** + * Helper function that creates a base texture from the given image url. + * If the image is not in the base texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + // new Image() breaks tex loading in some versions of Chrome. + // See https://code.google.com/p/chromium/issues/detail?id=238071 + var image = new Image(); // document.createElement('img'); + + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + image.crossOrigin = (0, _determineCrossOrigin2.default)(imageUrl); + } else if (crossorigin) { + image.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; + } + + baseTexture = new BaseTexture(image, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + image.src = imageUrl; // Setting this triggers load + + BaseTexture.addToCache(baseTexture, imageUrl); + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @param {string} [origin='canvas'] - A string origin of who created the base texture + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode) { + var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; + + if (!canvas._pixiId) { + canvas._pixiId = origin + '_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[canvas._pixiId]; + + if (!baseTexture) { + baseTexture = new BaseTexture(canvas, scaleMode); + BaseTexture.addToCache(baseTexture, canvas._pixiId); + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture based on the source you provide. + * The source can be - image url, image element, canvas element. + * + * @static + * @param {string|HTMLImageElement|HTMLCanvasElement} source - The source to create base texture from. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.from = function from(source, scaleMode, sourceScale) { + if (typeof source === 'string') { + return BaseTexture.fromImage(source, undefined, scaleMode, sourceScale); + } else if (source instanceof HTMLImageElement) { + var imageUrl = source.src; + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + baseTexture = new BaseTexture(source, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + BaseTexture.addToCache(baseTexture, imageUrl); + } + + return baseTexture; + } else if (source instanceof HTMLCanvasElement) { + return BaseTexture.fromCanvas(source, scaleMode); + } + + // lets assume its a base texture! + return source; + }; + + /** + * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache. + * @param {string} id - The id that the BaseTexture will be stored against. + */ + + + BaseTexture.addToCache = function addToCache(baseTexture, id) { + if (id) { + if (baseTexture.textureCacheIds.indexOf(id) === -1) { + baseTexture.textureCacheIds.push(id); + } + + /* eslint-disable no-console */ + if (_utils.BaseTextureCache[id]) { + console.warn('BaseTexture added to the cache with an id [' + id + '] that already had an entry'); + } + /* eslint-enable no-console */ + + _utils.BaseTextureCache[id] = baseTexture; + } + }; + + /** + * Remove a BaseTexture from the global BaseTextureCache. + * + * @static + * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself. + * @return {PIXI.BaseTexture|null} The BaseTexture that was removed. + */ + + + BaseTexture.removeFromCache = function removeFromCache(baseTexture) { + if (typeof baseTexture === 'string') { + var baseTextureFromCache = _utils.BaseTextureCache[baseTexture]; + + if (baseTextureFromCache) { + var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); + + if (index > -1) { + baseTextureFromCache.textureCacheIds.splice(index, 1); + } + + delete _utils.BaseTextureCache[baseTexture]; + + return baseTextureFromCache; + } + } else if (baseTexture && baseTexture.textureCacheIds) { + for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { + delete _utils.BaseTextureCache[baseTexture.textureCacheIds[i]]; + } + + baseTexture.textureCacheIds.length = 0; + + return baseTexture; + } + + return null; + }; + + return BaseTexture; +}(_eventemitter2.default); + +exports.default = BaseTexture; + +},{"../settings":101,"../utils":124,"../utils/determineCrossOrigin":123,"bit-twiddle":1,"eventemitter3":3}],113:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseRenderTexture = require('./BaseRenderTexture'); + +var _BaseRenderTexture2 = _interopRequireDefault(_BaseRenderTexture); + +var _Texture2 = require('./Texture'); + +var _Texture3 = _interopRequireDefault(_Texture2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let renderTexture = PIXI.RenderTexture.create(800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let renderTexture = new PIXI.RenderTexture.create(100, 100); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.Texture + * @memberof PIXI + */ +var RenderTexture = function (_Texture) { + _inherits(RenderTexture, _Texture); + + /** + * @param {PIXI.BaseRenderTexture} baseRenderTexture - The renderer used for this RenderTexture + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + */ + function RenderTexture(baseRenderTexture, frame) { + _classCallCheck(this, RenderTexture); + + // support for legacy.. + var _legacyRenderer = null; + + if (!(baseRenderTexture instanceof _BaseRenderTexture2.default)) { + /* eslint-disable prefer-rest-params, no-console */ + var width = arguments[1]; + var height = arguments[2]; + var scaleMode = arguments[3]; + var resolution = arguments[4]; + + // we have an old render texture.. + console.warn('Please use RenderTexture.create(' + width + ', ' + height + ') instead of the ctor directly.'); + _legacyRenderer = arguments[0]; + /* eslint-enable prefer-rest-params, no-console */ + + frame = null; + baseRenderTexture = new _BaseRenderTexture2.default(width, height, scaleMode, resolution); + } + + /** + * The base texture object that this texture uses + * + * @member {BaseTexture} + */ + + var _this = _possibleConstructorReturn(this, _Texture.call(this, baseRenderTexture, frame)); + + _this.legacyRenderer = _legacyRenderer; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = true; + + _this._updateUvs(); + return _this; + } + + /** + * Resizes the RenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + * @param {boolean} doNotResizeBaseTexture - Should the baseTexture.width and height values be resized as well? + */ + + + RenderTexture.prototype.resize = function resize(width, height, doNotResizeBaseTexture) { + // TODO - could be not required.. + this.valid = width > 0 && height > 0; + + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + + if (!doNotResizeBaseTexture) { + this.baseTexture.resize(width, height); + } + + this._updateUvs(); + }; + + /** + * A short hand way of creating a render texture. + * + * @param {number} [width=100] - The width of the render texture + * @param {number} [height=100] - The height of the render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.RenderTexture} The new render texture + */ + + + RenderTexture.create = function create(width, height, scaleMode, resolution) { + return new RenderTexture(new _BaseRenderTexture2.default(width, height, scaleMode, resolution)); + }; + + return RenderTexture; +}(_Texture3.default); + +exports.default = RenderTexture; + +},{"./BaseRenderTexture":111,"./Texture":115}],114:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _ = require('../'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Utility class for maintaining reference to a collection + * of Textures on a single Spritesheet. + * + * @class + * @memberof PIXI + */ +var Spritesheet = function () { + _createClass(Spritesheet, null, [{ + key: 'BATCH_SIZE', + + /** + * The maximum number of Textures to build per process. + * + * @type {number} + * @default 1000 + */ + get: function get() { + return 1000; + } + + /** + * @param {PIXI.BaseTexture} baseTexture Reference to the source BaseTexture object. + * @param {Object} data - Spritesheet image data. + * @param {string} [resolutionFilename] - The filename to consider when determining + * the resolution of the spritesheet. If not provided, the imageUrl will + * be used on the BaseTexture. + */ + + }]); + + function Spritesheet(baseTexture, data) { + var resolutionFilename = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + _classCallCheck(this, Spritesheet); + + /** + * Reference to ths source texture + * @type {PIXI.BaseTexture} + */ + this.baseTexture = baseTexture; + + /** + * Map of spritesheet textures. + * @type {Object} + */ + this.textures = {}; + + /** + * Reference to the original JSON data. + * @type {Object} + */ + this.data = data; + + /** + * The resolution of the spritesheet. + * @type {number} + */ + this.resolution = this._updateResolution(resolutionFilename || this.baseTexture.imageUrl); + + /** + * Map of spritesheet frames. + * @type {Object} + * @private + */ + this._frames = this.data.frames; + + /** + * Collection of frame names. + * @type {string[]} + * @private + */ + this._frameKeys = Object.keys(this._frames); + + /** + * Current batch index being processed. + * @type {number} + * @private + */ + this._batchIndex = 0; + + /** + * Callback when parse is completed. + * @type {Function} + * @private + */ + this._callback = null; + } + + /** + * Generate the resolution from the filename or fallback + * to the meta.scale field of the JSON data. + * + * @private + * @param {string} resolutionFilename - The filename to use for resolving + * the default resolution. + * @return {number} Resolution to use for spritesheet. + */ + + + Spritesheet.prototype._updateResolution = function _updateResolution(resolutionFilename) { + var scale = this.data.meta.scale; + + // Use a defaultValue of `null` to check if a url-based resolution is set + var resolution = (0, _utils.getResolutionOfUrl)(resolutionFilename, null); + + // No resolution found via URL + if (resolution === null) { + // Use the scale value or default to 1 + resolution = scale !== undefined ? parseFloat(scale) : 1; + } + + // For non-1 resolutions, update baseTexture + if (resolution !== 1) { + this.baseTexture.resolution = resolution; + this.baseTexture.update(); + } + + return resolution; + }; + + /** + * Parser spritesheet from loaded data. This is done asynchronously + * to prevent creating too many Texture within a single process. + * + * @param {Function} callback - Callback when complete returns + * a map of the Textures for this spritesheet. + */ + + + Spritesheet.prototype.parse = function parse(callback) { + this._batchIndex = 0; + this._callback = callback; + + if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) { + this._processFrames(0); + this._parseComplete(); + } else { + this._nextBatch(); + } + }; + + /** + * Process a batch of frames + * + * @private + * @param {number} initialFrameIndex - The index of frame to start. + */ + + + Spritesheet.prototype._processFrames = function _processFrames(initialFrameIndex) { + var frameIndex = initialFrameIndex; + var maxFrames = Spritesheet.BATCH_SIZE; + + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { + var i = this._frameKeys[frameIndex]; + var rect = this._frames[i].frame; + + if (rect) { + var frame = null; + var trim = null; + var orig = new _.Rectangle(0, 0, this._frames[i].sourceSize.w / this.resolution, this._frames[i].sourceSize.h / this.resolution); + + if (this._frames[i].rotated) { + frame = new _.Rectangle(rect.x / this.resolution, rect.y / this.resolution, rect.h / this.resolution, rect.w / this.resolution); + } else { + frame = new _.Rectangle(rect.x / this.resolution, rect.y / this.resolution, rect.w / this.resolution, rect.h / this.resolution); + } + + // Check to see if the sprite is trimmed + if (this._frames[i].trimmed) { + trim = new _.Rectangle(this._frames[i].spriteSourceSize.x / this.resolution, this._frames[i].spriteSourceSize.y / this.resolution, rect.w / this.resolution, rect.h / this.resolution); + } + + this.textures[i] = new _.Texture(this.baseTexture, frame, orig, trim, this._frames[i].rotated ? 2 : 0); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage functions + _.Texture.addToCache(this.textures[i], i); + } + + frameIndex++; + } + }; + + /** + * The parse has completed. + * + * @private + */ + + + Spritesheet.prototype._parseComplete = function _parseComplete() { + var callback = this._callback; + + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); + }; + + /** + * Begin the next batch of textures. + * + * @private + */ + + + Spritesheet.prototype._nextBatch = function _nextBatch() { + var _this = this; + + this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); + this._batchIndex++; + setTimeout(function () { + if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { + _this._nextBatch(); + } else { + _this._parseComplete(); + } + }, 0); + }; + + /** + * Destroy Spritesheet and don't use after this. + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Spritesheet.prototype.destroy = function destroy() { + var destroyBase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + for (var i in this.textures) { + this.textures[i].destroy(); + } + this._frames = null; + this._frameKeys = null; + this.data = null; + this.textures = null; + if (destroyBase) { + this.baseTexture.destroy(); + } + this.baseTexture = null; + }; + + return Spritesheet; +}(); + +exports.default = Spritesheet; + +},{"../":65,"../utils":124}],115:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture = require('./BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _VideoBaseTexture = require('./VideoBaseTexture'); + +var _VideoBaseTexture2 = _interopRequireDefault(_VideoBaseTexture); + +var _TextureUvs = require('./TextureUvs'); + +var _TextureUvs2 = _interopRequireDefault(_TextureUvs); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided + * then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * let texture = PIXI.Texture.fromImage('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` + * + * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. + * You can check for this by checking the sprite's _textureID property. + * ```js + * var texture = PIXI.Texture.fromImage('assets/image.svg'); + * var sprite1 = new PIXI.Sprite(texture); + * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file + * ``` + * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var Texture = function (_EventEmitter) { + _inherits(Texture, _EventEmitter); + + /** + * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + * @param {PIXI.Rectangle} [orig] - The area of original texture + * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture + * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8} + */ + function Texture(baseTexture, frame, orig, trim, rotate) { + _classCallCheck(this, Texture); + + /** + * Does this Texture have any frame data assigned to it? + * + * @member {boolean} + */ + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.noFrame = false; + + if (!frame) { + _this.noFrame = true; + frame = new _math.Rectangle(0, 0, 1, 1); + } + + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @member {PIXI.BaseTexture} + */ + _this.baseTexture = baseTexture; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @member {PIXI.Rectangle} + */ + _this._frame = frame; + + /** + * This is the trimmed area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @member {boolean} + */ + _this.requiresUpdate = false; + + /** + * The WebGL UV data cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + _this._uvs = null; + + /** + * This is the area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + + _this._rotate = Number(rotate || 0); + + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); + } + + if (baseTexture.hasLoaded) { + if (_this.noFrame) { + frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + + // if there is no frame we should monitor for any base texture changes.. + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + _this.frame = frame; + } else { + baseTexture.once('loaded', _this.onBaseTextureLoaded, _this); + } + + /** + * Fired when the texture is updated. This happens if the frame or the baseTexture is updated. + * + * @event PIXI.Texture#update + * @protected + * @param {PIXI.Texture} texture - Instance of texture being updated. + */ + + _this._updateID = 0; + + /** + * Extra field for extra plugins. May contain clamp settings and some matrices + * @type {Object} + */ + _this.transform = null; + + /** + * The ids under which this Texture has been added to the texture cache. This is + * automatically set as long as Texture.addToCache is used, but may not be set if a + * Texture is added directly to the TextureCache array. + * + * @member {string[]} + */ + _this.textureCacheIds = []; + return _this; + } + + /** + * Updates this texture on the gpu. + * + */ + + + Texture.prototype.update = function update() { + this.baseTexture.update(); + }; + + /** + * Called when the base texture is loaded + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureLoaded = function onBaseTextureLoaded(baseTexture) { + this._updateID++; + + // TODO this code looks confusing.. boo to abusing getters and setters! + if (this.noFrame) { + this.frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } else { + this.frame = this._frame; + } + + this.baseTexture.on('update', this.onBaseTextureUpdated, this); + this.emit('update', this); + }; + + /** + * Called when the base texture is updated + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated(baseTexture) { + this._updateID++; + + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Texture.prototype.destroy = function destroy(destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destroyed too.. + if (_utils.TextureCache[this.baseTexture.imageUrl]) { + Texture.removeFromCache(this.baseTexture.imageUrl); + } + + this.baseTexture.destroy(); + } + + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); + + this.baseTexture = null; + } + + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + + this.valid = false; + + Texture.removeFromCache(this); + this.textureCacheIds = null; + }; + + /** + * Creates a new texture object that acts the same as this one. + * + * @return {PIXI.Texture} The new texture + */ + + + Texture.prototype.clone = function clone() { + return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); + }; + + /** + * Updates the internal WebGL UV cache. + * + * @protected + */ + + + Texture.prototype._updateUvs = function _updateUvs() { + if (!this._uvs) { + this._uvs = new _TextureUvs2.default(); + } + + this._uvs.set(this._frame, this.baseTexture, this.rotate); + + this._updateID++; + }; + + /** + * Helper function that creates a Texture object from the given image url. + * If the image is not in the texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var texture = _utils.TextureCache[imageUrl]; + + if (!texture) { + texture = new Texture(_BaseTexture2.default.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); + Texture.addToCache(texture, imageUrl); + } + + return texture; + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return texture; + }; + + /** + * Helper function that creates a new Texture based on the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {string} [origin='canvas'] - A string origin of who created the base texture + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromCanvas = function fromCanvas(canvas, scaleMode) { + var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; + + return new Texture(_BaseTexture2.default.fromCanvas(canvas, scaleMode, origin)); + }; + + /** + * Helper function that creates a new Texture based on the given video element. + * + * @static + * @param {HTMLVideoElement|string} video - The URL or actual element of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideo = function fromVideo(video, scaleMode) { + if (typeof video === 'string') { + return Texture.fromVideoUrl(video, scaleMode); + } + + return new Texture(_VideoBaseTexture2.default.fromVideo(video, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the video url. + * + * @static + * @param {string} videoUrl - URL of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideoUrl = function fromVideoUrl(videoUrl, scaleMode) { + return new Texture(_VideoBaseTexture2.default.fromUrl(videoUrl, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} + * source - Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.from = function from(source) { + // TODO auto detect cross origin.. + // TODO pass in scale mode? + if (typeof source === 'string') { + var texture = _utils.TextureCache[source]; + + if (!texture) { + // check if its a video.. + var isVideo = source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/) !== null; + + if (isVideo) { + return Texture.fromVideoUrl(source); + } + + return Texture.fromImage(source); + } + + return texture; + } else if (source instanceof HTMLImageElement) { + return new Texture(_BaseTexture2.default.from(source)); + } else if (source instanceof HTMLCanvasElement) { + return Texture.fromCanvas(source, _settings2.default.SCALE_MODE, 'HTMLCanvasElement'); + } else if (source instanceof HTMLVideoElement) { + return Texture.fromVideo(source); + } else if (source instanceof _BaseTexture2.default) { + return new Texture(source); + } + + // lets assume its a texture! + return source; + }; + + /** + * Create a texture from a source and add to the cache. + * + * @static + * @param {HTMLImageElement|HTMLCanvasElement} source - The input source. + * @param {String} imageUrl - File name of texture, for cache and resolving resolution. + * @param {String} [name] - Human readible name for the texture cache. If no name is + * specified, only `imageUrl` will be used as the cache ID. + * @return {PIXI.Texture} Output texture + */ + + + Texture.fromLoader = function fromLoader(source, imageUrl, name) { + var baseTexture = new _BaseTexture2.default(source, undefined, (0, _utils.getResolutionOfUrl)(imageUrl)); + var texture = new Texture(baseTexture); + + baseTexture.imageUrl = imageUrl; + + // No name, use imageUrl instead + if (!name) { + name = imageUrl; + } + + // lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions + _BaseTexture2.default.addToCache(texture.baseTexture, name); + Texture.addToCache(texture, name); + + // also add references by url if they are different. + if (name !== imageUrl) { + _BaseTexture2.default.addToCache(texture.baseTexture, imageUrl); + Texture.addToCache(texture, imageUrl); + } + + return texture; + }; + + /** + * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the Texture will be stored against. + */ + + + Texture.addToCache = function addToCache(texture, id) { + if (id) { + if (texture.textureCacheIds.indexOf(id) === -1) { + texture.textureCacheIds.push(id); + } + + /* eslint-disable no-console */ + if (_utils.TextureCache[id]) { + console.warn('Texture added to the cache with an id [' + id + '] that already had an entry'); + } + /* eslint-enable no-console */ + + _utils.TextureCache[id] = texture; + } + }; + + /** + * Remove a Texture from the global TextureCache. + * + * @static + * @param {string|PIXI.Texture} texture - id of a Texture to be removed, or a Texture instance itself + * @return {PIXI.Texture|null} The Texture that was removed + */ + + + Texture.removeFromCache = function removeFromCache(texture) { + if (typeof texture === 'string') { + var textureFromCache = _utils.TextureCache[texture]; + + if (textureFromCache) { + var index = textureFromCache.textureCacheIds.indexOf(texture); + + if (index > -1) { + textureFromCache.textureCacheIds.splice(index, 1); + } + + delete _utils.TextureCache[texture]; + + return textureFromCache; + } + } else if (texture && texture.textureCacheIds) { + for (var i = 0; i < texture.textureCacheIds.length; ++i) { + delete _utils.TextureCache[texture.textureCacheIds[i]]; + } + + texture.textureCacheIds.length = 0; + + return texture; + } + + return null; + }; + + /** + * The frame specifies the region of the base texture that this texture uses. + * + * @member {PIXI.Rectangle} + */ + + + _createClass(Texture, [{ + key: 'frame', + get: function get() { + return this._frame; + }, + set: function set(frame) // eslint-disable-line require-jsdoc + { + this._frame = frame; + + this.noFrame = false; + + if (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height) { + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + ('X: ' + frame.x + ' + ' + frame.width + ' = ' + (frame.x + frame.width) + ' > ' + this.baseTexture.width + ' ') + ('Y: ' + frame.y + ' + ' + frame.height + ' = ' + (frame.y + frame.height) + ' > ' + this.baseTexture.height)); + } + + // this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded; + this.valid = frame && frame.width && frame.height && this.baseTexture.hasLoaded; + + if (!this.trim && !this.rotate) { + this.orig = frame; + } + + if (this.valid) { + this._updateUvs(); + } + } + + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.GroupD8} for explanation + * + * @member {number} + */ + + }, { + key: 'rotate', + get: function get() { + return this._rotate; + }, + set: function set(rotate) // eslint-disable-line require-jsdoc + { + this._rotate = rotate; + if (this.valid) { + this._updateUvs(); + } + } + + /** + * The width of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'width', + get: function get() { + return this.orig.width; + } + + /** + * The height of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.orig.height; + } + }]); + + return Texture; +}(_eventemitter2.default); + +exports.default = Texture; + + +function createWhiteTexture() { + var canvas = document.createElement('canvas'); + + canvas.width = 10; + canvas.height = 10; + + var context = canvas.getContext('2d'); + + context.fillStyle = 'white'; + context.fillRect(0, 0, 10, 10); + + return new Texture(new _BaseTexture2.default(canvas)); +} + +function removeAllHandlers(tex) { + tex.destroy = function _emptyDestroy() {/* empty */}; + tex.on = function _emptyOn() {/* empty */}; + tex.once = function _emptyOnce() {/* empty */}; + tex.emit = function _emptyEmit() {/* empty */}; +} + +/** + * An empty texture, used often to not have to create multiple empty textures. + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.EMPTY = new Texture(new _BaseTexture2.default()); +removeAllHandlers(Texture.EMPTY); +removeAllHandlers(Texture.EMPTY.baseTexture); + +/** + * A white texture of 10x10 size, used for graphics and other things + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.WHITE = createWhiteTexture(); +removeAllHandlers(Texture.WHITE); +removeAllHandlers(Texture.WHITE.baseTexture); + +},{"../math":70,"../settings":101,"../utils":124,"./BaseTexture":112,"./TextureUvs":116,"./VideoBaseTexture":117,"eventemitter3":3}],116:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _GroupD = require('../math/GroupD8'); + +var _GroupD2 = _interopRequireDefault(_GroupD); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A standard object to store the Uvs of a texture + * + * @class + * @private + * @memberof PIXI + */ +var TextureUvs = function () { + /** + * + */ + function TextureUvs() { + _classCallCheck(this, TextureUvs); + + this.x0 = 0; + this.y0 = 0; + + this.x1 = 1; + this.y1 = 0; + + this.x2 = 1; + this.y2 = 1; + + this.x3 = 0; + this.y3 = 1; + + this.uvsUint32 = new Uint32Array(4); + } + + /** + * Sets the texture Uvs based on the given frame information. + * + * @private + * @param {PIXI.Rectangle} frame - The frame of the texture + * @param {PIXI.Rectangle} baseFrame - The base frame of the texture + * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8} + */ + + + TextureUvs.prototype.set = function set(frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + + // coordinates of center + var cX = frame.x / tw + w2; + var cY = frame.y / th + h2; + + rotate = _GroupD2.default.add(rotate, _GroupD2.default.NW); // NW is top-left corner + this.x0 = cX + w2 * _GroupD2.default.uX(rotate); + this.y0 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + w2 * _GroupD2.default.uX(rotate); + this.y1 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x2 = cX + w2 * _GroupD2.default.uX(rotate); + this.y2 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x3 = cX + w2 * _GroupD2.default.uX(rotate); + this.y3 = cY + h2 * _GroupD2.default.uY(rotate); + } else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + + this.uvsUint32[0] = (this.y0 * 65535 & 0xFFFF) << 16 | this.x0 * 65535 & 0xFFFF; + this.uvsUint32[1] = (this.y1 * 65535 & 0xFFFF) << 16 | this.x1 * 65535 & 0xFFFF; + this.uvsUint32[2] = (this.y2 * 65535 & 0xFFFF) << 16 | this.x2 * 65535 & 0xFFFF; + this.uvsUint32[3] = (this.y3 * 65535 & 0xFFFF) << 16 | this.x3 * 65535 & 0xFFFF; + }; + + return TextureUvs; +}(); + +exports.default = TextureUvs; + +},{"../math/GroupD8":66}],117:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _utils = require('../utils'); + +var _ticker = require('../ticker'); + +var _const = require('../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture of a [playing] Video. + * + * Video base textures mimic PixiJS BaseTexture.from.... method in their creation process. + * + * This can be used in several ways, such as: + * + * ```js + * let texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4'); + * + * let texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' }); + * + * let texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']); + * + * let texture = PIXI.VideoBaseTexture.fromUrls([ + * { src: '/video.webm', mime: 'video/webm' }, + * { src: '/video.mp4', mime: 'video/mp4' } + * ]); + * ``` + * + * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/). + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var VideoBaseTexture = function (_BaseTexture) { + _inherits(VideoBaseTexture, _BaseTexture); + + /** + * @param {HTMLVideoElement} source - Video source + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + */ + function VideoBaseTexture(source, scaleMode) { + _classCallCheck(this, VideoBaseTexture); + + if (!source) { + throw new Error('No video source element specified.'); + } + + // hook in here to check if video is already available. + // BaseTexture looks for a source.complete boolean, plus width & height. + + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + source.complete = true; + } + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, source, scaleMode)); + + _this.width = source.videoWidth; + _this.height = source.videoHeight; + + _this._autoUpdate = true; + _this._isAutoUpdating = false; + + /** + * When set to true will automatically play videos used by this texture once + * they are loaded. If false, it will not modify the playing state. + * + * @member {boolean} + * @default true + */ + _this.autoPlay = true; + + _this.update = _this.update.bind(_this); + _this._onCanPlay = _this._onCanPlay.bind(_this); + + source.addEventListener('play', _this._onPlayStart.bind(_this)); + source.addEventListener('pause', _this._onPlayStop.bind(_this)); + _this.hasLoaded = false; + _this.__loaded = false; + + if (!_this._isSourceReady()) { + source.addEventListener('canplay', _this._onCanPlay); + source.addEventListener('canplaythrough', _this._onCanPlay); + } else { + _this._onCanPlay(); + } + return _this; + } + + /** + * Returns true if the underlying source is playing. + * + * @private + * @return {boolean} True if playing. + */ + + + VideoBaseTexture.prototype._isSourcePlaying = function _isSourcePlaying() { + var source = this.source; + + return source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2; + }; + + /** + * Returns true if the underlying source is ready for playing. + * + * @private + * @return {boolean} True if ready. + */ + + + VideoBaseTexture.prototype._isSourceReady = function _isSourceReady() { + return this.source.readyState === 3 || this.source.readyState === 4; + }; + + /** + * Runs the update loop when the video is ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStart = function _onPlayStart() { + // Just in case the video has not received its can play even yet.. + if (!this.hasLoaded) { + this._onCanPlay(); + } + + if (!this._isAutoUpdating && this.autoUpdate) { + _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); + this._isAutoUpdating = true; + } + }; + + /** + * Fired when a pause event is triggered, stops the update loop + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStop = function _onPlayStop() { + if (this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } + }; + + /** + * Fired when the video is loaded and ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onCanPlay = function _onCanPlay() { + this.hasLoaded = true; + + if (this.source) { + this.source.removeEventListener('canplay', this._onCanPlay); + this.source.removeEventListener('canplaythrough', this._onCanPlay); + + this.width = this.source.videoWidth; + this.height = this.source.videoHeight; + + // prevent multiple loaded dispatches.. + if (!this.__loaded) { + this.__loaded = true; + this.emit('loaded', this); + } + + if (this._isSourcePlaying()) { + this._onPlayStart(); + } else if (this.autoPlay) { + this.source.play(); + } + } + }; + + /** + * Destroys this texture + * + */ + + + VideoBaseTexture.prototype.destroy = function destroy() { + if (this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + } + + if (this.source && this.source._pixiId) { + _BaseTexture3.default.removeFromCache(this.source._pixiId); + delete this.source._pixiId; + } + + _BaseTexture.prototype.destroy.call(this); + }; + + /** + * Mimic PixiJS BaseTexture.from.... method. + * + * @static + * @param {HTMLVideoElement} video - Video to create texture from + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromVideo = function fromVideo(video, scaleMode) { + if (!video._pixiId) { + video._pixiId = 'video_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[video._pixiId]; + + if (!baseTexture) { + baseTexture = new VideoBaseTexture(video, scaleMode); + _BaseTexture3.default.addToCache(baseTexture, video._pixiId); + } + + return baseTexture; + }; + + /** + * Helper function that creates a new BaseTexture based on the given video element. + * This BaseTexture can then be used to create a texture + * + * @static + * @param {string|object|string[]|object[]} videoSrc - The URL(s) for the video. + * @param {string} [videoSrc.src] - One of the source urls for the video + * @param {string} [videoSrc.mime] - The mimetype of the video (e.g. 'video/mp4'). If not specified + * the url's extension will be used as the second part of the mime type. + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromUrl = function fromUrl(videoSrc, scaleMode) { + var video = document.createElement('video'); + + video.setAttribute('webkit-playsinline', ''); + video.setAttribute('playsinline', ''); + + // array of objects or strings + if (Array.isArray(videoSrc)) { + for (var i = 0; i < videoSrc.length; ++i) { + video.appendChild(createSource(videoSrc[i].src || videoSrc[i], videoSrc[i].mime)); + } + } + // single object or string + else { + video.appendChild(createSource(videoSrc.src || videoSrc, videoSrc.mime)); + } + + video.load(); + + return VideoBaseTexture.fromVideo(video, scaleMode); + }; + + /** + * Should the base texture automatically update itself, set to true by default + * + * @member {boolean} + */ + + + _createClass(VideoBaseTexture, [{ + key: 'autoUpdate', + get: function get() { + return this._autoUpdate; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + + if (!this._autoUpdate && this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } else if (this._autoUpdate && !this._isAutoUpdating) { + _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); + this._isAutoUpdating = true; + } + } + } + }]); + + return VideoBaseTexture; +}(_BaseTexture3.default); + +exports.default = VideoBaseTexture; + + +VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; + +function createSource(path, type) { + if (!type) { + type = 'video/' + path.substr(path.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = path; + source.type = type; + + return source; +} + +},{"../const":46,"../ticker":120,"../utils":124,"./BaseTexture":112}],118:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _const = require('../const'); + +var _TickerListener = require('./TickerListener'); + +var _TickerListener2 = _interopRequireDefault(_TickerListener); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A Ticker class that runs an update loop that other objects listen to. + * This class is composed around listeners + * meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, + * e.g. When the ticker is started and the emitter has listeners. + * + * @class + * @memberof PIXI.ticker + */ +var Ticker = function () { + /** + * + */ + function Ticker() { + var _this = this; + + _classCallCheck(this, Ticker); + + /** + * The first listener. All new listeners added are chained on this. + * @private + * @type {TickerListener} + */ + this._head = new _TickerListener2.default(null, null, Infinity); + + /** + * Internal current frame request ID + * @private + */ + this._requestId = null; + + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + * @private + */ + this._maxElapsedMS = 100; + + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.ticker.Ticker#start} automatically + * when a listener is added. + * + * @member {boolean} + * @default false + */ + this.autoStart = false; + + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS} + * and is scaled with {@link PIXI.ticker.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * + * @member {number} + * @default 1 + */ + this.deltaTime = 1; + + /** + * Time elapsed in milliseconds from last frame to this frame. + * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime} + * is based, this value is neither capped nor scaled. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * Defaults to target frame time + * + * @member {number} + * @default 16.66 + */ + this.elapsedMS = 1 / _settings2.default.TARGET_FPMS; + + /** + * The last time {@link PIXI.ticker.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default 0 + */ + this.lastTime = 0; + + /** + * Factor of current {@link PIXI.ticker.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + * + * @member {number} + * @default 1 + */ + this.speed = 1; + + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.ticker.Ticker#start} has been called. + * `false` if {@link PIXI.ticker.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.ticker.Ticker#autoStart} being `true` + * and a listener is added. + * + * @member {boolean} + * @default false + */ + this.started = false; + + /** + * Internal tick method bound to ticker instance. + * This is because in early 2015, Function.bind + * is still 60% slower in high performance scenarios. + * Also separating frame requests from update method + * so listeners may be called at any time and with + * any animation API, just invoke ticker.update(time). + * + * @private + * @param {number} time - Time since last tick. + */ + this._tick = function (time) { + _this._requestId = null; + + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._head.next) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * + * @private + */ + + + Ticker.prototype._requestIfNeeded = function _requestIfNeeded() { + if (this._requestId === null && this._head.next) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._requestId = requestAnimationFrame(this._tick); + } + }; + + /** + * Conditionally cancels a pending animation frame. + * + * @private + */ + + + Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; + + /** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * + * @private + */ + + + Ticker.prototype._startIfPossible = function _startIfPossible() { + if (this.started) { + this._requestIfNeeded(); + } else if (this.autoStart) { + this.start(); + } + }; + + /** + * Register a handler for tick events. Calls continuously unless + * it is removed or the ticker is stopped. + * + * @param {Function} fn - The listener function to be added for updates + * @param {Function} [context] - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.add = function add(fn, context) { + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _const.UPDATE_PRIORITY.NORMAL; + + return this._addListener(new _TickerListener2.default(fn, context, priority)); + }; + + /** + * Add a handler for the tick event which is only execute once. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context] - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.addOnce = function addOnce(fn, context) { + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _const.UPDATE_PRIORITY.NORMAL; + + return this._addListener(new _TickerListener2.default(fn, context, priority, true)); + }; + + /** + * Internally adds the event handler so that it can be sorted by priority. + * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run + * before the rendering. + * + * @private + * @param {TickerListener} listener - Current listener being added. + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype._addListener = function _addListener(listener) { + // For attaching to head + var current = this._head.next; + var previous = this._head; + + // Add the first item + if (!current) { + listener.connect(previous); + } else { + // Go from highest to lowest priority + while (current) { + if (listener.priority > current.priority) { + listener.connect(previous); + break; + } + previous = current; + current = current.next; + } + + // Not yet connected + if (!listener.previous) { + listener.connect(previous); + } + } + + this._startIfPossible(); + + return this; + }; + + /** + * Removes any handlers matching the function and context parameters. + * If no handlers are left after removing, then it cancels the animation frame. + * + * @param {Function} fn - The listener function to be removed + * @param {Function} [context] - The listener context to be removed + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.remove = function remove(fn, context) { + var listener = this._head.next; + + while (listener) { + // We found a match, lets remove it + // no break to delete all possible matches + // incase a listener was added 2+ times + if (listener.match(fn, context)) { + listener = listener.destroy(); + } else { + listener = listener.next; + } + } + + if (!this._head.next) { + this._cancelIfNeeded(); + } + + return this; + }; + + /** + * Starts the ticker. If the ticker has listeners + * a new animation frame is requested at this point. + */ + + + Ticker.prototype.start = function start() { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + }; + + /** + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. + */ + + + Ticker.prototype.stop = function stop() { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; + + /** + * Destroy the ticker and don't use after this. Calling + * this method removes all references to internal events. + */ + + + Ticker.prototype.destroy = function destroy() { + this.stop(); + + var listener = this._head.next; + + while (listener) { + listener = listener.destroy(true); + } + + this._head.destroy(); + this._head = null; + }; + + /** + * Triggers an update. An update entails setting the + * current {@link PIXI.ticker.Ticker#elapsedMS}, + * the current {@link PIXI.ticker.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.ticker.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + + + Ticker.prototype.update = function update() { + var currentTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : performance.now(); + + var elapsedMS = void 0; + + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + + this.deltaTime = elapsedMS * _settings2.default.TARGET_FPMS * this.speed; + + // Cache a local reference, in-case ticker is destroyed + // during the emit, we can still check for head.next + var head = this._head; + + // Invoke listeners added to internal emitter + var listener = head.next; + + while (listener) { + listener = listener.emit(this.deltaTime); + } + + if (!head.next) { + this._cancelIfNeeded(); + } + } else { + this.deltaTime = this.elapsedMS = 0; + } + + this.lastTime = currentTime; + }; + + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.ticker.Ticker#speed}, which is specific + * to scaling {@link PIXI.ticker.Ticker#deltaTime}. + * + * @member {number} + * @readonly + */ + + + _createClass(Ticker, [{ + key: 'FPS', + get: function get() { + return 1000 / this.elapsedMS; + } + + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.ticker.Ticker#update}. + * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.settings.TARGET_FPMS * 1000`. + * + * @member {number} + * @default 10 + */ + + }, { + key: 'minFPS', + get: function get() { + return 1000 / this._maxElapsedMS; + }, + set: function set(fps) // eslint-disable-line require-jsdoc + { + // Clamp: 0 to TARGET_FPMS + var minFPMS = Math.min(Math.max(0, fps) / 1000, _settings2.default.TARGET_FPMS); + + this._maxElapsedMS = 1 / minFPMS; + } + }]); + + return Ticker; +}(); + +exports.default = Ticker; + +},{"../const":46,"../settings":101,"./TickerListener":119}],119:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Internal class for handling the priority sorting of ticker handlers. + * + * @private + * @class + * @memberof PIXI.ticker + */ +var TickerListener = function () { + /** + * Constructor + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context=null] - The listener context + * @param {number} [priority=0] - The priority for emitting + * @param {boolean} [once=false] - If the handler should fire once + */ + function TickerListener(fn) { + var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var once = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + _classCallCheck(this, TickerListener); + + /** + * The handler function to execute. + * @member {Function} + */ + this.fn = fn; + + /** + * The calling to execute. + * @member {Function} + */ + this.context = context; + + /** + * The current priority. + * @member {number} + */ + this.priority = priority; + + /** + * If this should only execute once. + * @member {boolean} + */ + this.once = once; + + /** + * The next item in chain. + * @member {TickerListener} + */ + this.next = null; + + /** + * The previous item in chain. + * @member {TickerListener} + */ + this.previous = null; + + /** + * `true` if this listener has been destroyed already. + * @member {boolean} + * @private + */ + this._destroyed = false; + } + + /** + * Simple compare function to figure out if a function and context match. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} context - The listener context + * @return {boolean} `true` if the listener match the arguments + */ + + + TickerListener.prototype.match = function match(fn, context) { + context = context || null; + + return this.fn === fn && this.context === context; + }; + + /** + * Emit by calling the current function. + * @param {number} deltaTime - time since the last emit. + * @return {TickerListener} Next ticker + */ + + + TickerListener.prototype.emit = function emit(deltaTime) { + if (this.fn) { + if (this.context) { + this.fn.call(this.context, deltaTime); + } else { + this.fn(deltaTime); + } + } + + var redirect = this.next; + + if (this.once) { + this.destroy(true); + } + + // Soft-destroying should remove + // the next reference + if (this._destroyed) { + this.next = null; + } + + return redirect; + }; + + /** + * Connect to the list. + * @param {TickerListener} previous - Input node, previous listener + */ + + + TickerListener.prototype.connect = function connect(previous) { + this.previous = previous; + if (previous.next) { + previous.next.previous = this; + } + this.next = previous.next; + previous.next = this; + }; + + /** + * Destroy and don't use after this. + * @param {boolean} [hard = false] `true` to remove the `next` reference, this + * is considered a hard destroy. Soft destroy maintains the next reference. + * @return {TickerListener} The listener to redirect while emitting or removing. + */ + + + TickerListener.prototype.destroy = function destroy() { + var hard = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + this._destroyed = true; + this.fn = null; + this.context = null; + + // Disconnect, hook up next and previous + if (this.previous) { + this.previous.next = this.next; + } + + if (this.next) { + this.next.previous = this.previous; + } + + // Redirect to the next item + var redirect = this.previous; + + // Remove references + this.next = hard ? null : redirect; + this.previous = null; + + return redirect; + }; + + return TickerListener; +}(); + +exports.default = TickerListener; + +},{}],120:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Ticker = exports.shared = undefined; + +var _Ticker = require('./Ticker'); + +var _Ticker2 = _interopRequireDefault(_Ticker); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The shared ticker instance used by {@link PIXI.extras.AnimatedSprite}. + * and by {@link PIXI.interaction.InteractionManager}. + * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` + * for this instance. Please follow the examples for usage, including + * how to opt-out of auto-starting the shared ticker. + * + * @example + * let ticker = PIXI.ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(800, 600); + * let stage = new PIXI.Container(); + * let interactionManager = PIXI.interaction.InteractionManager(renderer); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * + * @type {PIXI.ticker.Ticker} + * @memberof PIXI.ticker + */ +var shared = new _Ticker2.default(); + +shared.autoStart = true; +shared.destroy = function () { + // protect destroying shared ticker + // this is used by other internal systems + // like AnimatedSprite and InteractionManager +}; + +/** + * This namespace contains an API for interacting with PIXI's internal global update loop. + * + * This ticker is used for rendering, {@link PIXI.extras.AnimatedSprite AnimatedSprite}, + * {@link PIXI.interaction.InteractionManager InteractionManager} and many other time-based PIXI systems. + * @example + * const ticker = new PIXI.ticker.Ticker(); + * ticker.stop(); + * ticker.add((deltaTime) => { + * // do something every frame + * }); + * ticker.start(); + * @namespace PIXI.ticker + */ +exports.shared = shared; +exports.Ticker = _Ticker2.default; + +},{"./Ticker":118}],121:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = canUploadSameBuffer; +function canUploadSameBuffer() { + // Uploading the same buffer multiple times in a single frame can cause perf issues. + // Apparent on IOS so only check for that at the moment + // this check may become more complex if this issue pops up elsewhere. + var ios = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform); + + return !ios; +} + +},{}],122:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = createIndicesForQuads; +/** + * Generic Mask Stack data structure + * + * @memberof PIXI + * @function createIndicesForQuads + * @private + * @param {number} size - Number of quads + * @return {Uint16Array} indices + */ +function createIndicesForQuads(size) { + // the total number of indices in our array, there are 6 points per quad. + + var totalIndices = size * 6; + + var indices = new Uint16Array(totalIndices); + + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + indices[i + 0] = j + 0; + indices[i + 1] = j + 1; + indices[i + 2] = j + 2; + indices[i + 3] = j + 0; + indices[i + 4] = j + 2; + indices[i + 5] = j + 3; + } + + return indices; +} + +},{}],123:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = determineCrossOrigin; + +var _url2 = require('url'); + +var _url3 = _interopRequireDefault(_url2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var tempAnchor = void 0; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +function determineCrossOrigin(url) { + var loc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location; + + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url3.default.parse(tempAnchor.href); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +} + +},{"url":29}],124:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.premultiplyBlendMode = exports.BaseTextureCache = exports.TextureCache = exports.mixins = exports.pluginTarget = exports.EventEmitter = exports.removeItems = exports.isMobile = undefined; +exports.uid = uid; +exports.hex2rgb = hex2rgb; +exports.hex2string = hex2string; +exports.rgb2hex = rgb2hex; +exports.getResolutionOfUrl = getResolutionOfUrl; +exports.decomposeDataUri = decomposeDataUri; +exports.getUrlFileExtension = getUrlFileExtension; +exports.getSvgSize = getSvgSize; +exports.skipHello = skipHello; +exports.sayHello = sayHello; +exports.isWebGLSupported = isWebGLSupported; +exports.sign = sign; +exports.destroyTextureCache = destroyTextureCache; +exports.clearTextureCache = clearTextureCache; +exports.correctBlendMode = correctBlendMode; +exports.premultiplyTint = premultiplyTint; +exports.premultiplyRgba = premultiplyRgba; +exports.premultiplyTintToRgba = premultiplyTintToRgba; + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _pluginTarget = require('./pluginTarget'); + +var _pluginTarget2 = _interopRequireDefault(_pluginTarget); + +var _mixin = require('./mixin'); + +var mixins = _interopRequireWildcard(_mixin); + +var _ismobilejs = require('ismobilejs'); + +var isMobile = _interopRequireWildcard(_ismobilejs); + +var _removeArrayItems = require('remove-array-items'); + +var _removeArrayItems2 = _interopRequireDefault(_removeArrayItems); + +var _mapPremultipliedBlendModes = require('./mapPremultipliedBlendModes'); + +var _mapPremultipliedBlendModes2 = _interopRequireDefault(_mapPremultipliedBlendModes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var nextUid = 0; +var saidHello = false; + +/** + * Generalized convenience utilities for PIXI. + * @example + * // Extend PIXI's internal Event Emitter. + * class MyEmitter extends PIXI.utils.EventEmitter { + * constructor() { + * super(); + * console.log("Emitter created!"); + * } + * } + * + * // Get info on current device + * console.log(PIXI.utils.isMobile); + * + * // Convert hex color to string + * console.log(PIXI.utils.hex2string(0xff00ff)); // returns: "#ff00ff" + * @namespace PIXI.utils + */ +exports.isMobile = isMobile; +exports.removeItems = _removeArrayItems2.default; +exports.EventEmitter = _eventemitter2.default; +exports.pluginTarget = _pluginTarget2.default; +exports.mixins = mixins; + +/** + * Gets the next unique identifier + * + * @memberof PIXI.utils + * @function uid + * @return {number} The next unique identifier to use. + */ + +function uid() { + return ++nextUid; +} + +/** + * Converts a hex color number to an [R, G, B] array + * + * @memberof PIXI.utils + * @function hex2rgb + * @param {number} hex - The number to convert + * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one + * @return {number[]} An array representing the [R, G, B] of the color. + */ +function hex2rgb(hex, out) { + out = out || []; + + out[0] = (hex >> 16 & 0xFF) / 255; + out[1] = (hex >> 8 & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + + return out; +} + +/** + * Converts a hex color number to a string. + * + * @memberof PIXI.utils + * @function hex2string + * @param {number} hex - Number in hex + * @return {string} The string color. + */ +function hex2string(hex) { + hex = hex.toString(16); + hex = '000000'.substr(0, 6 - hex.length) + hex; + + return '#' + hex; +} + +/** + * Converts a color as an [R, G, B] array to a hex number + * + * @memberof PIXI.utils + * @function rgb2hex + * @param {number[]} rgb - rgb array + * @return {number} The color number + */ +function rgb2hex(rgb) { + return (rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + (rgb[2] * 255 | 0); +} + +/** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * + * @memberof PIXI.utils + * @function getResolutionOfUrl + * @param {string} url - the image path + * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. + * @return {number} resolution / device pixel ratio of an asset + */ +function getResolutionOfUrl(url, defaultValue) { + var resolution = _settings2.default.RETINA_PREFIX.exec(url); + + if (resolution) { + return parseFloat(resolution[1]); + } + + return defaultValue !== undefined ? defaultValue : 1; +} + +/** + * Typedef for decomposeDataUri return object. + * + * @typedef {object} DecomposedDataUri + * @property {mediaType} Media type, eg. `image` + * @property {subType} Sub type, eg. `png` + * @property {encoding} Data encoding, eg. `base64` + * @property {data} The actual data + */ + +/** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. + * + * @memberof PIXI.utils + * @function decomposeDataUri + * @param {string} dataUri - the data URI to check + * @return {DecomposedDataUri|undefined} The decomposed data uri or undefined + */ +function decomposeDataUri(dataUri) { + var dataUriMatch = _const.DATA_URI.exec(dataUri); + + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + encoding: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + data: dataUriMatch[4] + }; + } + + return undefined; +} + +/** + * Get type of the image by regexp for extension. Returns undefined for unknown extensions. + * + * @memberof PIXI.utils + * @function getUrlFileExtension + * @param {string} url - the image path + * @return {string|undefined} image extension + */ +function getUrlFileExtension(url) { + var extension = _const.URL_FILE_EXTENSION.exec(url); + + if (extension) { + return extension[1].toLowerCase(); + } + + return undefined; +} + +/** + * Typedef for Size object. + * + * @typedef {object} Size + * @property {width} Width component + * @property {height} Height component + */ + +/** + * Get size from an svg string using regexp. + * + * @memberof PIXI.utils + * @function getSvgSize + * @param {string} svgString - a serialized svg element + * @return {Size|undefined} image extension + */ +function getSvgSize(svgString) { + var sizeMatch = _const.SVG_SIZE.exec(svgString); + var size = {}; + + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); + size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); + } + + return size; +} + +/** + * Skips the hello message of renderers that are created after this is run. + * + * @function skipHello + * @memberof PIXI.utils + */ +function skipHello() { + saidHello = true; +} + +/** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever makes you a jerk face. + * + * @static + * @function sayHello + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ +function sayHello(type) { + if (saidHello) { + return; + } + + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = ['\n %c %c %c PixiJS ' + _const.VERSION + ' - \u2730 ' + type + ' \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n', 'background: #ff66a5; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff66a5; background: #030307; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'background: #ffc3dc; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;']; + + window.console.log.apply(console, args); + } else if (window.console) { + window.console.log('PixiJS ' + _const.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); + } + + saidHello = true; +} + +/** + * Helper for checking for webgl support + * + * @memberof PIXI.utils + * @function isWebGLSupported + * @return {boolean} is webgl supported + */ +function isWebGLSupported() { + var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; + + try { + if (!window.WebGLRenderingContext) { + return false; + } + + var canvas = document.createElement('canvas'); + var gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); + + var success = !!(gl && gl.getContextAttributes().stencil); + + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + + if (loseContext) { + loseContext.loseContext(); + } + } + + gl = null; + + return success; + } catch (e) { + return false; + } +} + +/** + * Returns sign of number + * + * @memberof PIXI.utils + * @function sign + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ +function sign(n) { + if (n === 0) return 0; + + return n < 0 ? -1 : 1; +} + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var TextureCache = exports.TextureCache = Object.create(null); + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var BaseTextureCache = exports.BaseTextureCache = Object.create(null); + +/** + * Destroys all texture in the cache + * + * @memberof PIXI.utils + * @function destroyTextureCache + */ +function destroyTextureCache() { + var key = void 0; + + for (key in TextureCache) { + TextureCache[key].destroy(); + } + for (key in BaseTextureCache) { + BaseTextureCache[key].destroy(); + } +} + +/** + * Removes all textures from cache, but does not destroy them + * + * @memberof PIXI.utils + * @function clearTextureCache + */ +function clearTextureCache() { + var key = void 0; + + for (key in TextureCache) { + delete TextureCache[key]; + } + for (key in BaseTextureCache) { + delete BaseTextureCache[key]; + } +} + +/** + * maps premultiply flag and blendMode to adjusted blendMode + * @memberof PIXI.utils + * @const premultiplyBlendMode + * @type {Array} + */ +var premultiplyBlendMode = exports.premultiplyBlendMode = (0, _mapPremultipliedBlendModes2.default)(); + +/** + * changes blendMode according to texture format + * + * @memberof PIXI.utils + * @function correctBlendMode + * @param {number} blendMode supposed blend mode + * @param {boolean} premultiplied whether source is premultiplied + * @returns {number} true blend mode for this texture + */ +function correctBlendMode(blendMode, premultiplied) { + return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; +} + +/** + * premultiplies tint + * + * @param {number} tint integet RGB + * @param {number} alpha floating point alpha (0.0-1.0) + * @returns {number} tint multiplied by alpha + */ +function premultiplyTint(tint, alpha) { + if (alpha === 1.0) { + return (alpha * 255 << 24) + tint; + } + if (alpha === 0.0) { + return 0; + } + var R = tint >> 16 & 0xFF; + var G = tint >> 8 & 0xFF; + var B = tint & 0xFF; + + R = R * alpha + 0.5 | 0; + G = G * alpha + 0.5 | 0; + B = B * alpha + 0.5 | 0; + + return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; +} + +/** + * combines rgb and alpha to out array + * + * @param {Float32Array|number[]} rgb input rgb + * @param {number} alpha alpha param + * @param {Float32Array} [out] output + * @param {boolean} [premultiply=true] do premultiply it + * @returns {Float32Array} vec4 rgba + */ +function premultiplyRgba(rgb, alpha, out, premultiply) { + out = out || new Float32Array(4); + if (premultiply || premultiply === undefined) { + out[0] = rgb[0] * alpha; + out[1] = rgb[1] * alpha; + out[2] = rgb[2] * alpha; + } else { + out[0] = rgb[0]; + out[1] = rgb[1]; + out[2] = rgb[2]; + } + out[3] = alpha; + + return out; +} + +/** + * converts integer tint and float alpha to vec4 form, premultiplies by default + * + * @param {number} tint input tint + * @param {number} alpha alpha param + * @param {Float32Array} [out] output + * @param {boolean} [premultiply=true] do premultiply it + * @returns {Float32Array} vec4 rgba + */ +function premultiplyTintToRgba(tint, alpha, out, premultiply) { + out = out || new Float32Array(4); + out[0] = (tint >> 16 & 0xFF) / 255.0; + out[1] = (tint >> 8 & 0xFF) / 255.0; + out[2] = (tint & 0xFF) / 255.0; + if (premultiply || premultiply === undefined) { + out[0] *= alpha; + out[1] *= alpha; + out[2] *= alpha; + } + out[3] = alpha; + + return out; +} + +},{"../const":46,"../settings":101,"./mapPremultipliedBlendModes":125,"./mixin":127,"./pluginTarget":128,"eventemitter3":3,"ismobilejs":4,"remove-array-items":31}],125:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapPremultipliedBlendModes; + +var _const = require('../const'); + +/** + * Corrects PixiJS blend, takes premultiplied alpha into account + * + * @memberof PIXI + * @function mapPremultipliedBlendModes + * @private + * @param {Array} [array] - The array to output into. + * @return {Array} Mapped modes. + */ + +function mapPremultipliedBlendModes() { + var pm = []; + var npm = []; + + for (var i = 0; i < 32; i++) { + pm[i] = i; + npm[i] = i; + } + + pm[_const.BLEND_MODES.NORMAL_NPM] = _const.BLEND_MODES.NORMAL; + pm[_const.BLEND_MODES.ADD_NPM] = _const.BLEND_MODES.ADD; + pm[_const.BLEND_MODES.SCREEN_NPM] = _const.BLEND_MODES.SCREEN; + + npm[_const.BLEND_MODES.NORMAL] = _const.BLEND_MODES.NORMAL_NPM; + npm[_const.BLEND_MODES.ADD] = _const.BLEND_MODES.ADD_NPM; + npm[_const.BLEND_MODES.SCREEN] = _const.BLEND_MODES.SCREEN_NPM; + + var array = []; + + array.push(npm); + array.push(pm); + + return array; +} + +},{"../const":46}],126:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = maxRecommendedTextures; + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function maxRecommendedTextures(max) { + if (_ismobilejs2.default.tablet || _ismobilejs2.default.phone) { + // check if the res is iphone 6 or higher.. + return 4; + } + + // desktop should be ok + return max; +} + +},{"ismobilejs":4}],127:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.mixin = mixin; +exports.delayMixin = delayMixin; +exports.performMixins = performMixins; +/** + * Mixes all enumerable properties and methods from a source object to a target object. + * + * @memberof PIXI.utils.mixins + * @function mixin + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function mixin(target, source) { + if (!target || !source) return; + // in ES8/ES2017, this would be really easy: + // Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + + // get all the enumerable property keys + var keys = Object.keys(source); + + // loop through properties + for (var i = 0; i < keys.length; ++i) { + var propertyName = keys[i]; + + // Set the property using the property descriptor - this works for accessors and normal value properties + Object.defineProperty(target, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); + } +} + +var mixins = []; + +/** + * Queues a mixin to be handled towards the end of the initialization of PIXI, so that deprecation + * can take effect. + * + * @memberof PIXI.utils.mixins + * @function delayMixin + * @private + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function delayMixin(target, source) { + mixins.push(target, source); +} + +/** + * Handles all mixins queued via delayMixin(). + * + * @memberof PIXI.utils.mixins + * @function performMixins + * @private + */ +function performMixins() { + for (var i = 0; i < mixins.length; i += 2) { + mixin(mixins[i], mixins[i + 1]); + } + mixins.length = 0; +} + +},{}],128:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Mixins functionality to make an object have "plugins". + * + * @example + * function MyObject() {} + * + * pluginTarget.mixin(MyObject); + * + * @mixin + * @memberof PIXI.utils + * @param {object} obj - The object to mix into. + */ +function pluginTarget(obj) { + obj.__plugins = {}; + + /** + * Adds a plugin to an object + * + * @param {string} pluginName - The events that should be listed. + * @param {Function} ctor - The constructor function for the plugin. + */ + obj.registerPlugin = function registerPlugin(pluginName, ctor) { + obj.__plugins[pluginName] = ctor; + }; + + /** + * Instantiates all the plugins of this object + * + */ + obj.prototype.initPlugins = function initPlugins() { + this.plugins = this.plugins || {}; + + for (var o in obj.__plugins) { + this.plugins[o] = new obj.__plugins[o](this); + } + }; + + /** + * Removes all the plugins of this object + * + */ + obj.prototype.destroyPlugins = function destroyPlugins() { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + + this.plugins = null; + }; +} + +exports.default = { + /** + * Mixes in the properties of the pluginTarget into another object + * + * @param {object} obj - The obj to mix into + */ + mixin: function mixin(obj) { + pluginTarget(obj); + } +}; + +},{}],129:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = trimCanvas; +/** + * Trim transparent borders from a canvas + * + * @memberof PIXI + * @function trimCanvas + * @private + * @param {HTMLCanvasElement} canvas - the canvas to trim + * @returns {object} Trim data + */ +function trimCanvas(canvas) { + // https://gist.github.com/remy/784508 + + var width = canvas.width; + var height = canvas.height; + + var context = canvas.getContext('2d'); + var imageData = context.getImageData(0, 0, width, height); + var pixels = imageData.data; + var len = pixels.length; + + var bound = { + top: null, + left: null, + right: null, + bottom: null + }; + var i = void 0; + var x = void 0; + var y = void 0; + + for (i = 0; i < len; i += 4) { + if (pixels[i + 3] !== 0) { + x = i / 4 % width; + y = ~~(i / 4 / width); + + if (bound.top === null) { + bound.top = y; + } + + if (bound.left === null) { + bound.left = x; + } else if (x < bound.left) { + bound.left = x; + } + + if (bound.right === null) { + bound.right = x + 1; + } else if (bound.right < x) { + bound.right = x + 1; + } + + if (bound.bottom === null) { + bound.bottom = y; + } else if (bound.bottom < y) { + bound.bottom = y; + } + } + } + + width = bound.right - bound.left; + height = bound.bottom - bound.top + 1; + + var data = context.getImageData(bound.left, bound.top, width, height); + + return { + height: height, + width: width, + data: data + }; +} + +},{}],130:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = deprecation; +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code +function warn(msg) { + /* eslint-disable no-console */ + var stack = new Error().stack; + + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('Deprecation Warning: ', msg); + } else { + // chop off the stack trace which includes pixi.js internal calls + stack = stack.split('\n').splice(3).join('\n'); + + if (console.groupCollapsed) { + console.groupCollapsed('%cDeprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', msg); + console.warn(stack); + console.groupEnd(); + } else { + console.warn('Deprecation Warning: ', msg); + console.warn(stack); + } + } + /* eslint-enable no-console */ +} + +function deprecation(core) { + var mesh = core.mesh, + particles = core.particles, + extras = core.extras, + filters = core.filters, + prepare = core.prepare, + loaders = core.loaders, + interaction = core.interaction; + + + Object.defineProperties(core, { + + /** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ + SpriteBatch: { + get: function get() { + throw new ReferenceError('SpriteBatch does not exist any more, ' + 'please use the new ParticleContainer instead.'); + } + }, + + /** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in PixiJS v3, + * please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ + AssetLoader: { + get: function get() { + throw new ReferenceError('The loader system was overhauled in PixiJS v3, ' + 'please see the new PIXI.loaders.Loader class.'); + } + }, + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + Stage: { + get: function get() { + warn('You do not need to use a PIXI Stage any more, you can simply render any container.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + DisplayObjectContainer: { + get: function get() { + warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + Strip: { + get: function get() { + warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.'); + + return mesh.Mesh; + } + }, + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + Rope: { + get: function get() { + warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.'); + + return mesh.Rope; + } + }, + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + ParticleContainer: { + get: function get() { + warn('The ParticleContainer class has been moved to particles.ParticleContainer, ' + 'please use particles.ParticleContainer from now on.'); + + return particles.ParticleContainer; + } + }, + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + MovieClip: { + get: function get() { + warn('The MovieClip class has been moved to extras.AnimatedSprite, please use extras.AnimatedSprite.'); + + return extras.AnimatedSprite; + } + }, + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + TilingSprite: { + get: function get() { + warn('The TilingSprite class has been moved to extras.TilingSprite, ' + 'please use extras.TilingSprite from now on.'); + + return extras.TilingSprite; + } + }, + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + BitmapText: { + get: function get() { + warn('The BitmapText class has been moved to extras.BitmapText, ' + 'please use extras.BitmapText from now on.'); + + return extras.BitmapText; + } + }, + + /** + * @class + * @private + * @name blendModes + * @memberof PIXI + * @see PIXI.BLEND_MODES + * @deprecated since version 3.0.0 + */ + blendModes: { + get: function get() { + warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.'); + + return core.BLEND_MODES; + } + }, + + /** + * @class + * @private + * @name scaleModes + * @memberof PIXI + * @see PIXI.SCALE_MODES + * @deprecated since version 3.0.0 + */ + scaleModes: { + get: function get() { + warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.'); + + return core.SCALE_MODES; + } + }, + + /** + * @class + * @private + * @name BaseTextureCache + * @memberof PIXI + * @see PIXI.utils.BaseTextureCache + * @deprecated since version 3.0.0 + */ + BaseTextureCache: { + get: function get() { + warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, ' + 'please use utils.BaseTextureCache from now on.'); + + return core.utils.BaseTextureCache; + } + }, + + /** + * @class + * @private + * @name TextureCache + * @memberof PIXI + * @see PIXI.utils.TextureCache + * @deprecated since version 3.0.0 + */ + TextureCache: { + get: function get() { + warn('The TextureCache class has been moved to utils.TextureCache, ' + 'please use utils.TextureCache from now on.'); + + return core.utils.TextureCache; + } + }, + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + math: { + get: function get() { + warn('The math namespace is deprecated, please access members already accessible on PIXI.'); + + return core; + } + }, + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.Filter; + } + }, + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + TransformManual: { + get: function get() { + warn('TransformManual has been renamed to TransformBase, please update your pixi-spine'); + + return core.TransformBase; + } + }, + + /** + * @static + * @constant + * @name PIXI.TARGET_FPMS + * @see PIXI.settings.TARGET_FPMS + * @deprecated since version 4.2.0 + */ + TARGET_FPMS: { + get: function get() { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + return core.settings.TARGET_FPMS; + }, + set: function set(value) { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + core.settings.TARGET_FPMS = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.FILTER_RESOLUTION + * @see PIXI.settings.FILTER_RESOLUTION + * @deprecated since version 4.2.0 + */ + FILTER_RESOLUTION: { + get: function get() { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + return core.settings.FILTER_RESOLUTION; + }, + set: function set(value) { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + core.settings.FILTER_RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RESOLUTION + * @see PIXI.settings.RESOLUTION + * @deprecated since version 4.2.0 + */ + RESOLUTION: { + get: function get() { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + return core.settings.RESOLUTION; + }, + set: function set(value) { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + core.settings.RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.MIPMAP_TEXTURES + * @see PIXI.settings.MIPMAP_TEXTURES + * @deprecated since version 4.2.0 + */ + MIPMAP_TEXTURES: { + get: function get() { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + return core.settings.MIPMAP_TEXTURES; + }, + set: function set(value) { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + core.settings.MIPMAP_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_BATCH_SIZE + * @see PIXI.settings.SPRITE_BATCH_SIZE + * @deprecated since version 4.2.0 + */ + SPRITE_BATCH_SIZE: { + get: function get() { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + return core.settings.SPRITE_BATCH_SIZE; + }, + set: function set(value) { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + core.settings.SPRITE_BATCH_SIZE = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_MAX_TEXTURES + * @see PIXI.settings.SPRITE_MAX_TEXTURES + * @deprecated since version 4.2.0 + */ + SPRITE_MAX_TEXTURES: { + get: function get() { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + return core.settings.SPRITE_MAX_TEXTURES; + }, + set: function set(value) { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + core.settings.SPRITE_MAX_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RETINA_PREFIX + * @see PIXI.settings.RETINA_PREFIX + * @deprecated since version 4.2.0 + */ + RETINA_PREFIX: { + get: function get() { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + return core.settings.RETINA_PREFIX; + }, + set: function set(value) { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + core.settings.RETINA_PREFIX = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.DEFAULT_RENDER_OPTIONS + * @see PIXI.settings.RENDER_OPTIONS + * @deprecated since version 4.2.0 + */ + DEFAULT_RENDER_OPTIONS: { + get: function get() { + warn('PIXI.DEFAULT_RENDER_OPTIONS has been deprecated, please use PIXI.settings.DEFAULT_RENDER_OPTIONS'); + + return core.settings.RENDER_OPTIONS; + } + } + }); + + // Move the default properties to settings + var defaults = [{ parent: 'TRANSFORM_MODE', target: 'TRANSFORM_MODE' }, { parent: 'GC_MODES', target: 'GC_MODE' }, { parent: 'WRAP_MODES', target: 'WRAP_MODE' }, { parent: 'SCALE_MODES', target: 'SCALE_MODE' }, { parent: 'PRECISION', target: 'PRECISION_FRAGMENT' }]; + + var _loop = function _loop(i) { + var deprecation = defaults[i]; + + Object.defineProperty(core[deprecation.parent], 'DEFAULT', { + get: function get() { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); + + return core.settings[deprecation.target]; + }, + set: function set(value) { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); + + core.settings[deprecation.target] = value; + } + }); + }; + + for (var i = 0; i < defaults.length; i++) { + _loop(i); + } + + Object.defineProperties(core.settings, { + + /** + * @static + * @name PRECISION + * @memberof PIXI.settings + * @see PIXI.PRECISION + * @deprecated since version 4.4.0 + */ + PRECISION: { + get: function get() { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + return core.settings.PRECISION_FRAGMENT; + }, + set: function set(value) { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + core.settings.PRECISION_FRAGMENT = value; + } + } + }); + + if (extras.AnimatedSprite) { + Object.defineProperties(extras, { + + /** + * @class + * @name MovieClip + * @memberof PIXI.extras + * @see PIXI.extras.AnimatedSprite + * @deprecated since version 4.2.0 + */ + MovieClip: { + get: function get() { + warn('The MovieClip class has been renamed to AnimatedSprite, please use AnimatedSprite from now on.'); + + return extras.AnimatedSprite; + } + } + }); + } + + core.DisplayObject.prototype.generateTexture = function generateTexture(renderer, scaleMode, resolution) { + warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); + + return renderer.generateTexture(this, scaleMode, resolution); + }; + + core.Graphics.prototype.generateTexture = function generateTexture(scaleMode, resolution) { + warn('graphics generate texture has moved to the renderer. ' + 'Or to render a graphics to a texture using canvas please use generateCanvasTexture'); + + return this.generateCanvasTexture(scaleMode, resolution); + }; + + core.RenderTexture.prototype.render = function render(displayObject, matrix, clear, updateTransform) { + this.legacyRenderer.render(displayObject, this, clear, matrix, !updateTransform); + warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)'); + }; + + core.RenderTexture.prototype.getImage = function getImage(target) { + warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); + + return this.legacyRenderer.extract.image(target); + }; + + core.RenderTexture.prototype.getBase64 = function getBase64(target) { + warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); + + return this.legacyRenderer.extract.base64(target); + }; + + core.RenderTexture.prototype.getCanvas = function getCanvas(target) { + warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); + + return this.legacyRenderer.extract.canvas(target); + }; + + core.RenderTexture.prototype.getPixels = function getPixels(target) { + warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); + + return this.legacyRenderer.pixels(target); + }; + + /** + * @method + * @private + * @name PIXI.Sprite#setTexture + * @see PIXI.Sprite#texture + * @deprecated since version 3.0.0 + * @param {PIXI.Texture} texture - The texture to set to. + */ + core.Sprite.prototype.setTexture = function setTexture(texture) { + this.texture = texture; + warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;'); + }; + + if (extras.BitmapText) { + /** + * @method + * @name PIXI.extras.BitmapText#setText + * @see PIXI.extras.BitmapText#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ + extras.BitmapText.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';'); + }; + } + + /** + * @method + * @name PIXI.Text#setText + * @see PIXI.Text#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ + core.Text.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';'); + }; + + /** + * Calculates the ascent, descent and fontSize of a given fontStyle + * + * @name PIXI.Text.calculateFontProperties + * @see PIXI.TextMetrics.measureFont + * @deprecated since version 4.5.0 + * @param {string} font - String representing the style of the font + * @return {Object} Font properties object + */ + core.Text.calculateFontProperties = function calculateFontProperties(font) { + warn('Text.calculateFontProperties is now deprecated, please use the TextMetrics.measureFont'); + + return core.TextMetrics.measureFont(font); + }; + + Object.defineProperties(core.Text, { + fontPropertiesCache: { + get: function get() { + warn('Text.fontPropertiesCache is deprecated'); + + return core.TextMetrics._fonts; + } + }, + fontPropertiesCanvas: { + get: function get() { + warn('Text.fontPropertiesCanvas is deprecated'); + + return core.TextMetrics._canvas; + } + }, + fontPropertiesContext: { + get: function get() { + warn('Text.fontPropertiesContext is deprecated'); + + return core.TextMetrics._context; + } + } + }); + + /** + * @method + * @name PIXI.Text#setStyle + * @see PIXI.Text#style + * @deprecated since version 3.0.0 + * @param {*} style - The style to set to. + */ + core.Text.prototype.setStyle = function setStyle(style) { + this.style = style; + warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;'); + }; + + /** + * @method + * @name PIXI.Text#determineFontProperties + * @see PIXI.Text#measureFontProperties + * @deprecated since version 4.2.0 + * @private + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ + core.Text.prototype.determineFontProperties = function determineFontProperties(fontStyle) { + warn('determineFontProperties is now deprecated, please use TextMetrics.measureFont method'); + + return core.TextMetrics.measureFont(fontStyle); + }; + + /** + * @method + * @name PIXI.Text.getFontStyle + * @see PIXI.TextMetrics.getFontStyle + * @deprecated since version 4.5.0 + * @param {PIXI.TextStyle} style - The style to use. + * @return {string} Font string + */ + core.Text.getFontStyle = function getFontStyle(style) { + warn('getFontStyle is now deprecated, please use TextStyle.toFontString() instead'); + + style = style || {}; + + if (!(style instanceof core.TextStyle)) { + style = new core.TextStyle(style); + } + + return style.toFontString(); + }; + + Object.defineProperties(core.TextStyle.prototype, { + /** + * Set all properties of a font as a single string + * + * @name PIXI.TextStyle#font + * @deprecated since version 4.0.0 + */ + font: { + get: function get() { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\', \'fontSize\', \'fontStyle\', \'fontVariant\' and \'fontWeight\' properties from now on'); + + var fontSizeString = typeof this._fontSize === 'number' ? this._fontSize + 'px' : this._fontSize; + + return this._fontStyle + ' ' + this._fontVariant + ' ' + this._fontWeight + ' ' + fontSizeString + ' ' + this._fontFamily; + }, + set: function set(font) { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + + // can work out fontStyle from search of whole string + if (font.indexOf('italic') > 1) { + this._fontStyle = 'italic'; + } else if (font.indexOf('oblique') > -1) { + this._fontStyle = 'oblique'; + } else { + this._fontStyle = 'normal'; + } + + // can work out fontVariant from search of whole string + if (font.indexOf('small-caps') > -1) { + this._fontVariant = 'small-caps'; + } else { + this._fontVariant = 'normal'; + } + + // fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units + var splits = font.split(' '); + var fontSizeIndex = -1; + + this._fontSize = 26; + for (var i = 0; i < splits.length; ++i) { + if (splits[i].match(/(px|pt|em|%)/)) { + fontSizeIndex = i; + this._fontSize = splits[i]; + break; + } + } + + // we can now search for fontWeight as we know it must occur before the fontSize + this._fontWeight = 'normal'; + for (var _i = 0; _i < fontSizeIndex; ++_i) { + if (splits[_i].match(/(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/)) { + this._fontWeight = splits[_i]; + break; + } + } + + // and finally join everything together after the fontSize in case the font family has multiple words + if (fontSizeIndex > -1 && fontSizeIndex < splits.length - 1) { + this._fontFamily = ''; + for (var _i2 = fontSizeIndex + 1; _i2 < splits.length; ++_i2) { + this._fontFamily += splits[_i2] + ' '; + } + + this._fontFamily = this._fontFamily.slice(0, -1); + } else { + this._fontFamily = 'Arial'; + } + + this.styleID++; + } + } + }); + + /** + * @method + * @name PIXI.Texture#setFrame + * @see PIXI.Texture#setFrame + * @deprecated since version 3.0.0 + * @param {PIXI.Rectangle} frame - The frame to set. + */ + core.Texture.prototype.setFrame = function setFrame(frame) { + this.frame = frame; + warn('setFrame is now deprecated, please use the frame property, e.g: myTexture.frame = frame;'); + }; + + /** + * @static + * @function + * @name PIXI.Texture.addTextureToCache + * @see PIXI.Texture.addToCache + * @deprecated since 4.5.0 + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the texture will be stored against. + */ + core.Texture.addTextureToCache = function addTextureToCache(texture, id) { + core.Texture.addToCache(texture, id); + warn('Texture.addTextureToCache is deprecated, please use Texture.addToCache from now on.'); + }; + + /** + * @static + * @function + * @name PIXI.Texture.removeTextureFromCache + * @see PIXI.Texture.removeFromCache + * @deprecated since 4.5.0 + * @param {string} id - The id of the texture to be removed + * @return {PIXI.Texture|null} The texture that was removed + */ + core.Texture.removeTextureFromCache = function removeTextureFromCache(id) { + warn('Texture.removeTextureFromCache is deprecated, please use Texture.removeFromCache from now on. ' + 'Be aware that Texture.removeFromCache does not automatically its BaseTexture from the BaseTextureCache. ' + 'For that, use BaseTexture.removeFromCache'); + + core.BaseTexture.removeFromCache(id); + + return core.Texture.removeFromCache(id); + }; + + Object.defineProperties(filters, { + + /** + * @class + * @private + * @name PIXI.filters.AbstractFilter + * @see PIXI.AbstractFilter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.AbstractFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.SpriteMaskFilter + * @see PIXI.SpriteMaskFilter + * @deprecated since version 3.0.6 + */ + SpriteMaskFilter: { + get: function get() { + warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.'); + + return core.SpriteMaskFilter; + } + } + }); + + /** + * @method + * @name PIXI.utils.uuid + * @see PIXI.utils.uid + * @deprecated since version 3.0.6 + * @return {number} The uid + */ + core.utils.uuid = function () { + warn('utils.uuid() is deprecated, please use utils.uid() from now on.'); + + return core.utils.uid(); + }; + + /** + * @method + * @name PIXI.utils.canUseNewCanvasBlendModes + * @see PIXI.CanvasTinter + * @deprecated + * @return {boolean} Can use blend modes. + */ + core.utils.canUseNewCanvasBlendModes = function () { + warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on'); + + return core.CanvasTinter.canUseMultiply; + }; + + var saidHello = true; + + /** + * @name PIXI.utils._saidHello + * @type {boolean} + * @see PIXI.utils.skipHello + * @deprecated since 4.1.0 + */ + Object.defineProperty(core.utils, '_saidHello', { + set: function set(bool) { + if (bool) { + warn('PIXI.utils._saidHello is deprecated, please use PIXI.utils.skipHello()'); + this.skipHello(); + } + saidHello = bool; + }, + get: function get() { + return saidHello; + } + }); + + if (prepare.BasePrepare) { + /** + * @method + * @name PIXI.prepare.BasePrepare#register + * @see PIXI.prepare.BasePrepare#registerFindHook + * @deprecated since version 4.4.2 + * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + prepare.BasePrepare.prototype.register = function register(addHook, uploadHook) { + warn('renderer.plugins.prepare.register is now deprecated, ' + 'please use renderer.plugins.prepare.registerFindHook & renderer.plugins.prepare.registerUploadHook'); + + if (addHook) { + this.registerFindHook(addHook); + } + + if (uploadHook) { + this.registerUploadHook(uploadHook); + } + + return this; + }; + } + + if (prepare.canvas) { + /** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.canvas.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ + Object.defineProperty(prepare.canvas, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } + }); + } + + if (prepare.webgl) { + /** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.webgl.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ + Object.defineProperty(prepare.webgl, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } + }); + } + + if (loaders.Loader) { + var Resource = loaders.Resource; + var Loader = loaders.Loader; + + Object.defineProperties(Resource.prototype, { + isJson: { + get: function get() { + warn('The isJson property is deprecated, please use `resource.type === Resource.TYPE.JSON`.'); + + return this.type === Resource.TYPE.JSON; + } + }, + isXml: { + get: function get() { + warn('The isXml property is deprecated, please use `resource.type === Resource.TYPE.XML`.'); + + return this.type === Resource.TYPE.XML; + } + }, + isImage: { + get: function get() { + warn('The isImage property is deprecated, please use `resource.type === Resource.TYPE.IMAGE`.'); + + return this.type === Resource.TYPE.IMAGE; + } + }, + isAudio: { + get: function get() { + warn('The isAudio property is deprecated, please use `resource.type === Resource.TYPE.AUDIO`.'); + + return this.type === Resource.TYPE.AUDIO; + } + }, + isVideo: { + get: function get() { + warn('The isVideo property is deprecated, please use `resource.type === Resource.TYPE.VIDEO`.'); + + return this.type === Resource.TYPE.VIDEO; + } + } + }); + + Object.defineProperties(Loader.prototype, { + before: { + get: function get() { + warn('The before() method is deprecated, please use pre().'); + + return this.pre; + } + }, + after: { + get: function get() { + warn('The after() method is deprecated, please use use().'); + + return this.use; + } + } + }); + } + + if (interaction.interactiveTarget) { + /** + * @name PIXI.interaction.interactiveTarget#defaultCursor + * @static + * @type {number} + * @see PIXI.interaction.interactiveTarget#cursor + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.interactiveTarget, 'defaultCursor', { + set: function set(value) { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + this.cursor = value; + }, + get: function get() { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + + return this.cursor; + } + }); + } + + if (interaction.InteractionManager) { + /** + * @name PIXI.interaction.InteractionManager#defaultCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.InteractionManager, 'defaultCursorStyle', { + set: function set(value) { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + this.cursorStyles.default = value; + }, + get: function get() { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + + return this.cursorStyles.default; + } + }); + + /** + * @name PIXI.interaction.InteractionManager#currentCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.InteractionManager, 'currentCursorStyle', { + set: function set(value) { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + this.currentCursorMode = value; + }, + get: function get() { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + + return this.currentCursorMode; + } + }); + } +} + +},{}],131:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI.extract + */ + +var CanvasExtract = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasExtract(renderer) { + _classCallCheck(this, CanvasExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.extract.CanvasExtract} extract + * @memberof PIXI.CanvasRenderer# + * @see PIXI.extract.CanvasExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + CanvasExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `CanvasExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + CanvasExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + CanvasExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = this.renderer.width; + frame.height = this.renderer.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + CanvasExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + + return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; + }; + + /** + * Destroys the extract + * + */ + + + CanvasExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return CanvasExtract; +}(); + +exports.default = CanvasExtract; + + +core.CanvasRenderer.registerPlugin('extract', CanvasExtract); + +},{"../../core":65}],132:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLExtract = require('./webgl/WebGLExtract'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLExtract).default; + } +}); + +var _CanvasExtract = require('./canvas/CanvasExtract'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasExtract).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./canvas/CanvasExtract":131,"./webgl/WebGLExtract":133}],133:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); +var BYTES_PER_PIXEL = 4; + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI.extract + */ + +var WebGLExtract = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLExtract(renderer) { + _classCallCheck(this, WebGLExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.extract.WebGLExtract} extract + * @memberof PIXI.WebGLRenderer# + * @see PIXI.extract.WebGLExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + WebGLExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `WebGLExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + WebGLExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + WebGLExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var flipY = false; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + flipY = false; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + flipY = true; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + + // set up an array of pixels + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + + canvasData.data.set(webglPixels); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // pulling pixels + if (flipY) { + canvasBuffer.context.scale(1, -1); + canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); + } + } + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + WebGLExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + } + + return webglPixels; + }; + + /** + * Destroys the extract + * + */ + + + WebGLExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return WebGLExtract; +}(); + +exports.default = WebGLExtract; + + +core.WebGLRenderer.registerPlugin('extract', WebGLExtract); + +},{"../../core":65}],134:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @typedef FrameObject + * @type {object} + * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame + * @property {number} time - the duration of the frame in ms + */ + +/** + * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. + * + * ```js + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; + * + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.fromImage(alienImages[i]); + * textureArray.push(texture); + * }; + * + * let mc = new PIXI.AnimatedSprite(textureArray); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ +var AnimatedSprite = function (_core$Sprite) { + _inherits(AnimatedSprite, _core$Sprite); + + /** + * @param {PIXI.Texture[]|FrameObject[]} textures - an array of {@link PIXI.Texture} or frame + * objects that make up the animation + * @param {boolean} [autoUpdate=true] - Whether to use PIXI.ticker.shared to auto update animation time. + */ + function AnimatedSprite(textures, autoUpdate) { + _classCallCheck(this, AnimatedSprite); + + /** + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture)); + + _this._textures = null; + + /** + * @private + */ + _this._durations = null; + + _this.textures = textures; + + /** + * `true` uses PIXI.ticker.shared to auto update animation time. + * @type {boolean} + * @default true + * @private + */ + _this._autoUpdate = autoUpdate !== false; + + /** + * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower + * + * @member {number} + * @default 1 + */ + _this.animationSpeed = 1; + + /** + * Whether or not the animate sprite repeats after playing. + * + * @member {boolean} + * @default true + */ + _this.loop = true; + + /** + * Function to call when a AnimatedSprite finishes playing + * + * @member {Function} + */ + _this.onComplete = null; + + /** + * Function to call when a AnimatedSprite changes which texture is being rendered + * + * @member {Function} + */ + _this.onFrameChange = null; + + /** + * Function to call when 'loop' is true, and an AnimatedSprite is played and loops around to start again + * + * @member {Function} + */ + _this.onLoop = null; + + /** + * Elapsed time since animation has been started, used internally to display current texture + * + * @member {number} + * @private + */ + _this._currentTime = 0; + + /** + * Indicates if the AnimatedSprite is currently playing + * + * @member {boolean} + * @readonly + */ + _this.playing = false; + return _this; + } + + /** + * Stops the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.stop = function stop() { + if (!this.playing) { + return; + } + + this.playing = false; + if (this._autoUpdate) { + core.ticker.shared.remove(this.update, this); + } + }; + + /** + * Plays the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.play = function play() { + if (this.playing) { + return; + } + + this.playing = true; + if (this._autoUpdate) { + core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.HIGH); + } + }; + + /** + * Stops the AnimatedSprite and goes to a specific frame + * + * @param {number} frameNumber - frame index to stop at + */ + + + AnimatedSprite.prototype.gotoAndStop = function gotoAndStop(frameNumber) { + this.stop(); + + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + + /** + * Goes to a specific frame and begins playing the AnimatedSprite + * + * @param {number} frameNumber - frame index to start at + */ + + + AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay(frameNumber) { + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + + this.play(); + }; + + /** + * Updates the object transform for rendering. + * + * @private + * @param {number} deltaTime - Time since last tick. + */ + + + AnimatedSprite.prototype.update = function update(deltaTime) { + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + + lag += elapsed / 60 * 1000; + + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + + var sign = Math.sign(this.animationSpeed * deltaTime); + + this._currentTime = Math.floor(this._currentTime); + + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + + this._currentTime += lag / this._durations[this.currentFrame]; + } else { + this._currentTime += elapsed; + } + + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + + if (this.onComplete) { + this.onComplete(); + } + } else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + + if (this.onComplete) { + this.onComplete(); + } + } else if (previousFrame !== this.currentFrame) { + if (this.loop && this.onLoop) { + if (this.animationSpeed > 0 && this.currentFrame < previousFrame) { + this.onLoop(); + } else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) { + this.onLoop(); + } + } + + this.updateTexture(); + } + }; + + /** + * Updates the displayed texture to match the current frame index + * + * @private + */ + + + AnimatedSprite.prototype.updateTexture = function updateTexture() { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + }; + + /** + * Stops the AnimatedSprite and destroys it + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + AnimatedSprite.prototype.destroy = function destroy(options) { + this.stop(); + _core$Sprite.prototype.destroy.call(this, options); + }; + + /** + * A short hand way of creating a movieclip from an array of frame ids + * + * @static + * @param {string[]} frames - The array of frames ids the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animated sprite with the specified frames. + */ + + + AnimatedSprite.fromFrames = function fromFrames(frames) { + var textures = []; + + for (var i = 0; i < frames.length; ++i) { + textures.push(core.Texture.fromFrame(frames[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * A short hand way of creating a movieclip from an array of image ids + * + * @static + * @param {string[]} images - the array of image urls the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animate sprite with the specified images as frames. + */ + + + AnimatedSprite.fromImages = function fromImages(images) { + var textures = []; + + for (var i = 0; i < images.length; ++i) { + textures.push(core.Texture.fromImage(images[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * totalFrames is the total number of frames in the AnimatedSprite. This is the same as number of textures + * assigned to the AnimatedSprite. + * + * @readonly + * @member {number} + * @default 0 + */ + + + _createClass(AnimatedSprite, [{ + key: 'totalFrames', + get: function get() { + return this._textures.length; + } + + /** + * The array of textures used for this AnimatedSprite + * + * @member {PIXI.Texture[]} + */ + + }, { + key: 'textures', + get: function get() { + return this._textures; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value[0] instanceof core.Texture) { + this._textures = value; + this._durations = null; + } else { + this._textures = []; + this._durations = []; + + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + this.gotoAndStop(0); + this.updateTexture(); + } + + /** + * The AnimatedSprites current frame index + * + * @member {number} + * @readonly + */ + + }, { + key: 'currentFrame', + get: function get() { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + + return currentFrame; + } + }]); + + return AnimatedSprite; +}(core.Sprite); + +exports.default = AnimatedSprite; + +},{"../core":65}],135:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ObservablePoint = require('../core/math/ObservablePoint'); + +var _ObservablePoint2 = _interopRequireDefault(_ObservablePoint); + +var _settings = require('../core/settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BitmapText object will create a line or multiple lines of text using bitmap font. To + * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using: + * + * A BitmapText can only be created when the font is loaded + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); + * ``` + * + * http://www.angelcode.com/products/bmfont/ for windows or + * http://www.bmglyph.com/ for mac. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.extras + */ +var BitmapText = function (_core$Container) { + _inherits(BitmapText, _core$Container); + + /** + * @param {string} text - The copy that you would like the text to display + * @param {object} style - The style parameters + * @param {string|object} style.font - The font descriptor for the object, can be passed as a string of form + * "24px FontName" or "FontName" or as an object with explicit name/size properties. + * @param {string} [style.font.name] - The bitmap font id + * @param {number} [style.font.size] - The size of the font in pixels, e.g. 24 + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), does not affect + * single line text + * @param {number} [style.tint=0xFFFFFF] - The tint color + */ + function BitmapText(text) { + var style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _classCallCheck(this, BitmapText); + + /** + * Private tracker for the width of the overall text + * + * @member {number} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._textWidth = 0; + + /** + * Private tracker for the height of the overall text + * + * @member {number} + * @private + */ + _this._textHeight = 0; + + /** + * Private tracker for the letter sprite pool. + * + * @member {PIXI.Sprite[]} + * @private + */ + _this._glyphs = []; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._font = { + tint: style.tint !== undefined ? style.tint : 0xFFFFFF, + align: style.align || 'left', + name: null, + size: 0 + }; + + /** + * Private tracker for the current font. + * + * @member {object} + * @private + */ + _this.font = style.font; // run font setter + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = text; + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + * @private + */ + _this._maxWidth = 0; + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + * @private + */ + _this._maxLineHeight = 0; + + /** + * Text anchor. read-only + * + * @member {PIXI.ObservablePoint} + * @private + */ + _this._anchor = new _ObservablePoint2.default(function () { + _this.dirty = true; + }, _this, 0, 0); + + /** + * The dirty state of this object. + * + * @member {boolean} + */ + _this.dirty = false; + + _this.updateText(); + return _this; + } + + /** + * Renders text and updates it when needed + * + * @private + */ + + + BitmapText.prototype.updateText = function updateText() { + var data = BitmapText.fonts[this._font.name]; + var scale = this._font.size / data.size; + var pos = new core.Point(); + var chars = []; + var lineWidths = []; + + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastSpace = -1; + var lastSpaceWidth = 0; + var spacesRemoved = 0; + var maxLineHeight = 0; + + for (var i = 0; i < this.text.length; i++) { + var charCode = this.text.charCodeAt(i); + + if (/(\s)/.test(this.text.charAt(i))) { + lastSpace = i; + lastSpaceWidth = lastLineWidth; + } + + if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) { + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + if (lastSpace !== -1 && this._maxWidth > 0 && pos.x * scale > this._maxWidth) { + core.utils.removeItems(chars, lastSpace - spacesRemoved, i - lastSpace); + i = lastSpace; + lastSpace = -1; + ++spacesRemoved; + + lineWidths.push(lastSpaceWidth); + maxLineWidth = Math.max(maxLineWidth, lastSpaceWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + var charData = data.chars[charCode]; + + if (!charData) { + continue; + } + + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + + chars.push({ + texture: charData.texture, + line: line, + charCode: charCode, + position: new core.Point(pos.x + charData.xOffset, pos.y + charData.yOffset) + }); + lastLineWidth = pos.x + (charData.texture.width + charData.xOffset); + pos.x += charData.xAdvance; + maxLineHeight = Math.max(maxLineHeight, charData.yOffset + charData.texture.height); + prevCharCode = charCode; + } + + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + + var lineAlignOffsets = []; + + for (var _i = 0; _i <= line; _i++) { + var alignOffset = 0; + + if (this._font.align === 'right') { + alignOffset = maxLineWidth - lineWidths[_i]; + } else if (this._font.align === 'center') { + alignOffset = (maxLineWidth - lineWidths[_i]) / 2; + } + + lineAlignOffsets.push(alignOffset); + } + + var lenChars = chars.length; + var tint = this.tint; + + for (var _i2 = 0; _i2 < lenChars; _i2++) { + var c = this._glyphs[_i2]; // get the next glyph sprite + + if (c) { + c.texture = chars[_i2].texture; + } else { + c = new core.Sprite(chars[_i2].texture); + this._glyphs.push(c); + } + + c.position.x = (chars[_i2].position.x + lineAlignOffsets[chars[_i2].line]) * scale; + c.position.y = chars[_i2].position.y * scale; + c.scale.x = c.scale.y = scale; + c.tint = tint; + + if (!c.parent) { + this.addChild(c); + } + } + + // remove unnecessary children. + for (var _i3 = lenChars; _i3 < this._glyphs.length; ++_i3) { + this.removeChild(this._glyphs[_i3]); + } + + this._textWidth = maxLineWidth * scale; + this._textHeight = (pos.y + data.lineHeight) * scale; + + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + for (var _i4 = 0; _i4 < lenChars; _i4++) { + this._glyphs[_i4].x -= this._textWidth * this.anchor.x; + this._glyphs[_i4].y -= this._textHeight * this.anchor.y; + } + } + this._maxLineHeight = maxLineHeight * scale; + }; + + /** + * Updates the transform of this object + * + * @private + */ + + + BitmapText.prototype.updateTransform = function updateTransform() { + this.validate(); + this.containerUpdateTransform(); + }; + + /** + * Validates text before calling parent's getLocalBounds + * + * @return {PIXI.Rectangle} The rectangular bounding area + */ + + + BitmapText.prototype.getLocalBounds = function getLocalBounds() { + this.validate(); + + return _core$Container.prototype.getLocalBounds.call(this); + }; + + /** + * Updates text when needed + * + * @private + */ + + + BitmapText.prototype.validate = function validate() { + if (this.dirty) { + this.updateText(); + this.dirty = false; + } + }; + + /** + * The tint of the BitmapText object + * + * @member {number} + */ + + + /** + * Register a bitmap font with data and a texture. + * + * @static + * @param {XMLDocument} xml - The XML document data. + * @param {PIXI.Texture} texture - Texture with all symbols. + * @return {Object} Result font object with font, size, lineHeight and char fields. + */ + BitmapText.registerFont = function registerFont(xml, texture) { + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + var res = texture.baseTexture.resolution || _settings2.default.RESOLUTION; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) / res; + data.chars = {}; + + // parse letters + var letters = xml.getElementsByTagName('char'); + + for (var i = 0; i < letters.length; i++) { + var letter = letters[i]; + var charCode = parseInt(letter.getAttribute('id'), 10); + + var textureRect = new core.Rectangle(parseInt(letter.getAttribute('x'), 10) / res + texture.frame.x / res, parseInt(letter.getAttribute('y'), 10) / res + texture.frame.y / res, parseInt(letter.getAttribute('width'), 10) / res, parseInt(letter.getAttribute('height'), 10) / res); + + data.chars[charCode] = { + xOffset: parseInt(letter.getAttribute('xoffset'), 10) / res, + yOffset: parseInt(letter.getAttribute('yoffset'), 10) / res, + xAdvance: parseInt(letter.getAttribute('xadvance'), 10) / res, + kerning: {}, + texture: new core.Texture(texture.baseTexture, textureRect) + + }; + } + + // parse kernings + var kernings = xml.getElementsByTagName('kerning'); + + for (var _i5 = 0; _i5 < kernings.length; _i5++) { + var kerning = kernings[_i5]; + var first = parseInt(kerning.getAttribute('first'), 10) / res; + var second = parseInt(kerning.getAttribute('second'), 10) / res; + var amount = parseInt(kerning.getAttribute('amount'), 10) / res; + + if (data.chars[second]) { + data.chars[second].kerning[first] = amount; + } + } + + // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 + // but it's very likely to change + BitmapText.fonts[data.font] = data; + + return data; + }; + + _createClass(BitmapText, [{ + key: 'tint', + get: function get() { + return this._font.tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.tint = typeof value === 'number' && value >= 0 ? value : 0xFFFFFF; + + this.dirty = true; + } + + /** + * The alignment of the BitmapText object + * + * @member {string} + * @default 'left' + */ + + }, { + key: 'align', + get: function get() { + return this._font.align; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.align = value || 'left'; + + this.dirty = true; + } + + /** + * The anchor sets the origin point of the text. + * The default is 0,0 this means the text's origin is the top left + * Setting the anchor to 0.5,0.5 means the text's origin is centered + * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner + * + * @member {PIXI.Point | number} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (typeof value === 'number') { + this._anchor.set(value); + } else { + this._anchor.copy(value); + } + } + + /** + * The font descriptor of the BitmapText object + * + * @member {string|object} + */ + + }, { + key: 'font', + get: function get() { + return this._font; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (!value) { + return; + } + + if (typeof value === 'string') { + value = value.split(' '); + + this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); + this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; + } else { + this._font.name = value.name; + this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); + } + + this.dirty = true; + } + + /** + * The text of the BitmapText object + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + value = value.toString() || ' '; + if (this._text === value) { + return; + } + this._text = value; + this.dirty = true; + } + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + */ + + }, { + key: 'maxWidth', + get: function get() { + return this._maxWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._maxWidth === value) { + return; + } + this._maxWidth = value; + this.dirty = true; + } + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + * @readonly + */ + + }, { + key: 'maxLineHeight', + get: function get() { + this.validate(); + + return this._maxLineHeight; + } + + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textWidth', + get: function get() { + this.validate(); + + return this._textWidth; + } + + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textHeight', + get: function get() { + this.validate(); + + return this._textHeight; + } + }]); + + return BitmapText; +}(core.Container); + +exports.default = BitmapText; + + +BitmapText.fonts = {}; + +},{"../core":65,"../core/math/ObservablePoint":68,"../core/settings":101}],136:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Matrix = require('../core/math/Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var tempMat = new _Matrix2.default(); + +/** + * class controls uv transform and frame clamp for texture + * + * @class + * @memberof PIXI.extras + */ + +var TextureTransform = function () { + /** + * + * @param {PIXI.Texture} texture observed texture + * @param {number} [clampMargin] Changes frame clamping, 0.5 by default. Use -0.5 for extra border. + * @constructor + */ + function TextureTransform(texture, clampMargin) { + _classCallCheck(this, TextureTransform); + + this._texture = texture; + + this.mapCoord = new _Matrix2.default(); + + this.uClampFrame = new Float32Array(4); + + this.uClampOffset = new Float32Array(2); + + this._lastTextureID = -1; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders + * + * @default 0 + * @member {number} + */ + this.clampOffset = 0; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + this.clampMargin = typeof clampMargin === 'undefined' ? 0.5 : clampMargin; + } + + /** + * texture property + * @member {PIXI.Texture} + */ + + + /** + * Multiplies uvs array to transform + * @param {Float32Array} uvs mesh uvs + * @param {Float32Array} [out=uvs] output + * @returns {Float32Array} output + */ + TextureTransform.prototype.multiplyUvs = function multiplyUvs(uvs, out) { + if (out === undefined) { + out = uvs; + } + + var mat = this.mapCoord; + + for (var i = 0; i < uvs.length; i += 2) { + var x = uvs[i]; + var y = uvs[i + 1]; + + out[i] = x * mat.a + y * mat.c + mat.tx; + out[i + 1] = x * mat.b + y * mat.d + mat.ty; + } + + return out; + }; + + /** + * updates matrices if texture was changed + * @param {boolean} forceUpdate if true, matrices will be updated any case + * @returns {boolean} whether or not it was updated + */ + + + TextureTransform.prototype.update = function update(forceUpdate) { + var tex = this._texture; + + if (!tex || !tex.valid) { + return false; + } + + if (!forceUpdate && this._lastTextureID === tex._updateID) { + return false; + } + + this._lastTextureID = tex._updateID; + + var uvs = tex._uvs; + + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + + var orig = tex.orig; + var trim = tex.trim; + + if (trim) { + tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat); + } + + var texBase = tex.baseTexture; + var frame = this.uClampFrame; + var margin = this.clampMargin / texBase.resolution; + var offset = this.clampOffset; + + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.uClampOffset[0] = offset / texBase.realWidth; + this.uClampOffset[1] = offset / texBase.realHeight; + + return true; + }; + + _createClass(TextureTransform, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._texture = value; + this._lastTextureID = -1; + } + }]); + + return TextureTransform; +}(); + +exports.default = TextureTransform; + +},{"../core/math/Matrix":67}],137:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CanvasTinter = require('../core/sprites/canvas/CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +var _TextureTransform = require('./TextureTransform'); + +var _TextureTransform2 = _interopRequireDefault(_TextureTransform); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); + +/** + * A tiling sprite is a fast way of rendering a tiling image + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ + +var TilingSprite = function (_core$Sprite) { + _inherits(TilingSprite, _core$Sprite); + + /** + * @param {PIXI.Texture} texture - the texture of the tiling sprite + * @param {number} [width=100] - the width of the tiling sprite + * @param {number} [height=100] - the height of the tiling sprite + */ + function TilingSprite(texture) { + var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100; + + _classCallCheck(this, TilingSprite); + + /** + * Tile transform + * + * @member {PIXI.TransformStatic} + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, texture)); + + _this.tileTransform = new core.TransformStatic(); + + // /// private + + /** + * The with of the tiling sprite + * + * @member {number} + * @private + */ + _this._width = width; + + /** + * The height of the tiling sprite + * + * @member {number} + * @private + */ + _this._height = height; + + /** + * Canvas pattern + * + * @type {CanvasPattern} + * @private + */ + _this._canvasPattern = null; + + /** + * transform that is applied to UV to get the texture coords + * + * @member {PIXI.extras.TextureTransform} + */ + _this.uvTransform = texture.transform || new _TextureTransform2.default(texture); + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' method. + * + * @member {string} + * @default 'tilingSprite' + */ + _this.pluginName = 'tilingSprite'; + + /** + * Whether or not anchor affects uvs + * + * @member {boolean} + * @default false + */ + _this.uvRespectAnchor = false; + return _this; + } + /** + * Changes frame clamping in corresponding textureTransform, shortcut + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + + + /** + * @private + */ + TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate() { + if (this.uvTransform) { + this.uvTransform.texture = this._texture; + } + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + TilingSprite.prototype._renderWebGL = function _renderWebGL(renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + + if (!texture || !texture.valid) { + return; + } + + this.tileTransform.updateLocalTransform(); + this.uvTransform.update(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer + */ + + + TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { + var texture = this._texture; + + if (!texture.baseTexture.hasLoaded) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var resolution = renderer.resolution; + var baseTexture = texture.baseTexture; + var baseTextureResolution = baseTexture.resolution; + var modX = this.tilePosition.x / this.tileScale.x % texture._frame.width * baseTextureResolution; + var modY = this.tilePosition.y / this.tileScale.y % texture._frame.height * baseTextureResolution; + + // create a nice shiny pattern! + // TODO this needs to be refreshed if texture changes.. + if (!this._canvasPattern) { + // cut an object from a spritesheet.. + var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height, baseTextureResolution); + + // Tint the tiling sprite + if (this.tint !== 0xFFFFFF) { + if (this.cachedTint !== this.tint) { + this.cachedTint = this.tint; + + this.tintedTexture = _CanvasTinter2.default.getTintedTexture(this, this.tint); + } + tempCanvas.context.drawImage(this.tintedTexture, 0, 0); + } else { + tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x * baseTextureResolution, -texture._frame.y * baseTextureResolution); + } + this._canvasPattern = tempCanvas.context.createPattern(tempCanvas.canvas, 'repeat'); + } + + // set context state.. + context.globalAlpha = this.worldAlpha; + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + renderer.setBlendMode(this.blendMode); + + // fill the pattern! + context.fillStyle = this._canvasPattern; + + // TODO - this should be rolled into the setTransform above.. + context.scale(this.tileScale.x / baseTextureResolution, this.tileScale.y / baseTextureResolution); + + var anchorX = this.anchor.x * -this._width; + var anchorY = this.anchor.y * -this._height; + + if (this.uvRespectAnchor) { + context.translate(modX, modY); + + context.fillRect(-modX + anchorX, -modY + anchorY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } else { + context.translate(modX + anchorX, modY + anchorY); + + context.fillRect(-modX, -modY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } + }; + + /** + * Updates the bounds of the tiling sprite. + * + * @private + */ + + + TilingSprite.prototype._calculateBounds = function _calculateBounds() { + var minX = this._width * -this._anchor._x; + var minY = this._height * -this._anchor._y; + var maxX = this._width * (1 - this._anchor._x); + var maxY = this._height * (1 - this._anchor._y); + + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + TilingSprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._width * -this._anchor._x; + this._bounds.minY = this._height * -this._anchor._y; + this._bounds.maxX = this._width * (1 - this._anchor._x); + this._bounds.maxY = this._height * (1 - this._anchor._x); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new core.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _core$Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Checks if a point is inside this tiling sprite. + * + * @param {PIXI.Point} point - the point to check + * @return {boolean} Whether or not the sprite contains the point. + */ + + + TilingSprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor._x; + + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + var y1 = -height * this.anchor._y; + + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + TilingSprite.prototype.destroy = function destroy(options) { + _core$Sprite.prototype.destroy.call(this, options); + + this.tileTransform = null; + this.uvTransform = null; + }; + + /** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.Texture} The newly created texture + */ + + + TilingSprite.from = function from(source, width, height) { + return new TilingSprite(core.Texture.from(source), width, height); + }; + + /** + * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId + */ + + + TilingSprite.fromFrame = function fromFrame(frameId, width, height) { + var texture = core.utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this); + } + + return new TilingSprite(texture, width, height); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @param {boolean} [crossorigin] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id + */ + + + TilingSprite.fromImage = function fromImage(imageId, width, height, crossorigin, scaleMode) { + return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode), width, height); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(TilingSprite, [{ + key: 'clampMargin', + get: function get() { + return this.uvTransform.clampMargin; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uvTransform.clampMargin = value; + this.uvTransform.update(true); + } + + /** + * The scaling of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tileScale', + get: function get() { + return this.tileTransform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.scale.copy(value); + } + + /** + * The offset of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tilePosition', + get: function get() { + return this.tileTransform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.position.copy(value); + } + }, { + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + } + + /** + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + } + }]); + + return TilingSprite; +}(core.Sprite); + +exports.default = TilingSprite; + +},{"../core":65,"../core/sprites/canvas/CanvasTinter":104,"./TextureTransform":136}],138:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _BaseTexture = require('../core/textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _utils = require('../core/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DisplayObject = core.DisplayObject; +var _tempMatrix = new core.Matrix(); + +DisplayObject.prototype._cacheAsBitmap = false; +DisplayObject.prototype._cacheData = false; + +// figured theres no point adding ALL the extra variables to prototype. +// this model can hold the information needed. This can also be generated on demand as +// most objects are not cached as bitmaps. +/** + * @class + * @ignore + */ + +var CacheData = +/** + * + */ +function CacheData() { + _classCallCheck(this, CacheData); + + this.textureCacheId = null; + + this.originalRenderWebGL = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + + this.originalUpdateTransform = null; + this.originalHitTest = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.sprite = null; +}; + +Object.defineProperties(DisplayObject.prototype, { + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to 'false' + * + * IMPORTANT GOTCHA - make sure that all your textures are preloaded BEFORE setting this property to true + * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function get() { + return this._cacheAsBitmap; + }, + set: function set(value) { + if (this._cacheAsBitmap === value) { + return; + } + + this._cacheAsBitmap = value; + + var data = void 0; + + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + + data = this._cacheData; + + data.originalRenderWebGL = this.renderWebGL; + data.originalRenderCanvas = this.renderCanvas; + + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this._calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + + data.originalDestroy = this.destroy; + + data.originalContainsPoint = this.containsPoint; + + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + + this.renderWebGL = this._renderCachedWebGL; + this.renderCanvas = this._renderCachedCanvas; + + this.destroy = this._cacheAsBitmapDestroy; + } else { + data = this._cacheData; + + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + + this.renderWebGL = data.originalRenderWebGL; + this.renderCanvas = data.originalRenderCanvas; + this._calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + + this.destroy = data.originalDestroy; + + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + } + } +}); + +/** + * Renders a cached version of the sprite with WebGL + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedWebGL = function _renderCachedWebGL(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObject(renderer); + + this._cacheData.sprite._transformID = -1; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderWebGL(renderer); +}; + +/** + * Prepares the WebGL renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + + this.alpha = 1; + + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.currentRenderer.flush(); + // this.filters= []; + + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds().clone(); + + // add some padding! + if (this._filters) { + var padding = this._filters[0].padding; + + bounds.pad(padding); + } + + // for now we cache the current renderTarget that the webGL renderer is currently using. + // this could be more elegent.. + var cachedRenderTarget = renderer._activeRenderTarget; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + var stack = renderer.filterManager.filterStack; + + // this renderTexture will be used to store the cached DisplayObject + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); + + this._cacheData.textureCacheId = textureCacheId; + + _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); + _Texture2.default.addToCache(renderTexture, textureCacheId); + + // need to set // + var m = _tempMatrix; + + m.tx = -bounds.x; + m.ty = -bounds.y; + + // reset + this.transform.worldTransform.identity(); + + // set all properties to there original so we can render to a texture + this.renderWebGL = this._cacheData.originalRenderWebGL; + + renderer.render(this, renderTexture, true, m, true); + // now restore the state be setting the new properties + + renderer.bindRenderTarget(cachedRenderTarget); + + renderer.filterManager.filterStack = stack; + + this.renderWebGL = this._renderCachedWebGL; + this.updateTransform = this.displayObjectUpdateTransform; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + + // easy bounds.. + this._calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + + this._cacheData.sprite = cachedSprite; + + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this.updateTransform(); + } + + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Renders a cached version of the sprite with canvas + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObjectCanvas(renderer); + + this._cacheData.sprite.worldAlpha = this.worldAlpha; + + this._cacheData.sprite.renderCanvas(renderer); +}; + +// TODO this can be the same as the webGL verison.. will need to do a little tweaking first though.. +/** + * Prepares the Canvas renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(); + + var cacheAlpha = this.alpha; + + this.alpha = 1; + + var cachedRenderTarget = renderer.context; + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); + + this._cacheData.textureCacheId = textureCacheId; + + _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); + _Texture2.default.addToCache(renderTexture, textureCacheId); + + // need to set // + var m = _tempMatrix; + + this.transform.localTransform.copy(m); + m.invert(); + + m.tx -= bounds.x; + m.ty -= bounds.y; + + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + + // renderTexture.render(this, m, true); + renderer.render(this, renderTexture, true, m, false); + + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + + this.renderCanvas = this._renderCachedCanvas; + this._calculateBounds = this._calculateCachedBounds; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite._bounds = this._bounds; + cachedSprite.alpha = cacheAlpha; + + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this.updateTransform(); + } + + this.updateTransform = this.displayObjectUpdateTransform; + + this._cacheData.sprite = cachedSprite; + + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Calculates the bounds of the cached sprite + * + * @private + */ +DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._cacheData.sprite._calculateBounds(); +}; + +/** + * Gets the bounds of the cached sprite. + * + * @private + * @return {Rectangle} The local bounds. + */ +DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(); +}; + +/** + * Destroys the cached sprite. + * + * @private + */ +DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; + + _BaseTexture2.default.removeFromCache(this._cacheData.textureCacheId); + _Texture2.default.removeFromCache(this._cacheData.textureCacheId); + + this._cacheData.textureCacheId = null; +}; + +/** + * Destroys the cached object. + * + * @private + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * Used when destroying containers, see the Container.destroy method. + */ +DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { + this.cacheAsBitmap = false; + this.destroy(options); +}; + +},{"../core":65,"../core/textures/BaseTexture":112,"../core/textures/Texture":115,"../core/utils":124}],139:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * The instance name of the object. + * + * @memberof PIXI.DisplayObject# + * @member {string} + */ +core.DisplayObject.prototype.name = null; + +/** + * Returns the display object in the container + * + * @memberof PIXI.Container# + * @param {string} name - instance name + * @return {PIXI.DisplayObject} The child with the specified name. + */ +core.Container.prototype.getChildByName = function getChildByName(name) { + for (var i = 0; i < this.children.length; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + + return null; +}; + +},{"../core":65}],140:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. + * + * @memberof PIXI.DisplayObject# + * @param {Point} point - the point to write the global value to. If null a new point will be returned + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @return {Point} The updated point + */ +core.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition() { + var point = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new core.Point(); + var skipUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (this.parent) { + this.parent.toGlobal(this.position, point, skipUpdate); + } else { + point.x = this.position.x; + point.y = this.position.y; + } + + return point; +}; + +},{"../core":65}],141:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BitmapText = exports.TilingSpriteRenderer = exports.TilingSprite = exports.TextureTransform = exports.AnimatedSprite = undefined; + +var _AnimatedSprite = require('./AnimatedSprite'); + +Object.defineProperty(exports, 'AnimatedSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AnimatedSprite).default; + } +}); + +var _TextureTransform = require('./TextureTransform'); + +Object.defineProperty(exports, 'TextureTransform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureTransform).default; + } +}); + +var _TilingSprite = require('./TilingSprite'); + +Object.defineProperty(exports, 'TilingSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSprite).default; + } +}); + +var _TilingSpriteRenderer = require('./webgl/TilingSpriteRenderer'); + +Object.defineProperty(exports, 'TilingSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSpriteRenderer).default; + } +}); + +var _BitmapText = require('./BitmapText'); + +Object.defineProperty(exports, 'BitmapText', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BitmapText).default; + } +}); + +require('./cacheAsBitmap'); + +require('./getChildByName'); + +require('./getGlobalPosition'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// imported for side effect of extending the prototype only, contains no exports + +},{"./AnimatedSprite":134,"./BitmapText":135,"./TextureTransform":136,"./TilingSprite":137,"./cacheAsBitmap":138,"./getChildByName":139,"./getGlobalPosition":140,"./webgl/TilingSpriteRenderer":142}],142:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _const = require('../../core/const'); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMat = new core.Matrix(); + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI.extras + * @extends PIXI.ObjectRenderer + */ + +var TilingSpriteRenderer = function (_core$ObjectRenderer) { + _inherits(TilingSpriteRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function TilingSpriteRenderer(renderer) { + _classCallCheck(this, TilingSpriteRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + _this.simpleShader = null; + _this.quad = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + TilingSpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n gl_FragColor = sample * uColor;\n}\n'); + this.simpleShader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = sample * uColor;\n}\n'); + + this.renderer.bindVao(null); + this.quad = new core.Quad(gl, this.renderer.state.attribState); + this.quad.initVao(this.shader); + }; + + /** + * + * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered + */ + + + TilingSpriteRenderer.prototype.render = function render(ts) { + var renderer = this.renderer; + var quad = this.quad; + + renderer.bindVao(quad.vao); + + var vertices = quad.vertices; + + vertices[0] = vertices[6] = ts._width * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + + vertices[2] = vertices[4] = ts._width * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + + if (ts.uvRespectAnchor) { + vertices = quad.uvs; + + vertices[0] = vertices[6] = -ts.anchor.x; + vertices[1] = vertices[3] = -ts.anchor.y; + + vertices[2] = vertices[4] = 1.0 - ts.anchor.x; + vertices[5] = vertices[7] = 1.0 - ts.anchor.y; + } + + quad.upload(); + + var tex = ts._texture; + var baseTex = tex.baseTexture; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvTransform; + var isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === _const.WRAP_MODES.CLAMP) { + baseTex.wrapMode = _const.WRAP_MODES.REPEAT; + } + } else { + isSimple = baseTex.wrapMode !== _const.WRAP_MODES.CLAMP; + } + } + + var shader = isSimple ? this.simpleShader : this.shader; + + renderer.bindShader(shader); + + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + + tempMat.invert(); + if (isSimple) { + tempMat.prepend(uv.mapCoord); + } else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + + shader.uniforms.uTransform = tempMat.toArray(true); + shader.uniforms.uColor = core.utils.premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, baseTex.premultipliedAlpha); + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + + shader.uniforms.uSampler = renderer.bindTexture(tex); + + renderer.setBlendMode(core.utils.correctBlendMode(ts.blendMode, baseTex.premultipliedAlpha)); + + quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + }; + + return TilingSpriteRenderer; +}(core.ObjectRenderer); + +exports.default = TilingSpriteRenderer; + + +core.WebGLRenderer.registerPlugin('tilingSprite', TilingSpriteRenderer); + +},{"../../core":65,"../../core/const":46,"path":23}],143:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BlurXFilter = require('./BlurXFilter'); + +var _BlurXFilter2 = _interopRequireDefault(_BlurXFilter); + +var _BlurYFilter = require('./BlurYFilter'); + +var _BlurYFilter2 = _interopRequireDefault(_BlurYFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurFilter applies a Gaussian blur to an object. + * The strength of the blur can be set for x- and y-axis separately. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurFilter = function (_core$Filter) { + _inherits(BlurFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this)); + + _this.blurXFilter = new _BlurXFilter2.default(strength, quality, resolution, kernelSize); + _this.blurYFilter = new _BlurYFilter2.default(strength, quality, resolution, kernelSize); + + _this.padding = 0; + _this.resolution = resolution || core.settings.RESOLUTION; + _this.quality = quality || 4; + _this.blur = strength || 8; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + BlurFilter.prototype.apply = function apply(filterManager, input, output) { + var renderTarget = filterManager.getRenderTarget(true); + + this.blurXFilter.apply(filterManager, input, renderTarget, true); + this.blurYFilter.apply(filterManager, renderTarget, output, false); + + filterManager.returnRenderTarget(renderTarget); + }; + + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurFilter, [{ + key: 'blur', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the number of passes for blur. More passes means higher quaility bluring. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'quality', + get: function get() { + return this.blurXFilter.quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.quality = this.blurYFilter.quality = value; + } + + /** + * Sets the strength of the blurX property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurX', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the strength of the blurY property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurY', + get: function get() { + return this.blurYFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the blendmode of the filter + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + */ + + }, { + key: 'blendMode', + get: function get() { + return this.blurYFilter._blendMode; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter._blendMode = value; + } + }]); + + return BlurFilter; +}(core.Filter); + +exports.default = BlurFilter; + +},{"../../core":65,"./BlurXFilter":144,"./BlurYFilter":145}],144:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurXFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurXFilter = function (_core$Filter) { + _inherits(BlurXFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurXFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurXFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurXFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.width * (output.size.width / input.size.width); + + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; // / this.passes//Math.pow(1, this.passes); + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 16 + */ + + + _createClass(BlurXFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurXFilter; +}(core.Filter); + +exports.default = BlurXFilter; + +},{"../../core":65,"./generateBlurFragSource":146,"./generateBlurVertSource":147,"./getMaxBlurKernelSize":148}],145:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurYFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurYFilter = function (_core$Filter) { + _inherits(BlurYFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurYFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurYFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurYFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.height * (output.size.height / input.size.height); + + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurYFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurYFilter; +}(core.Filter); + +exports.default = BlurYFilter; + +},{"../../core":65,"./generateBlurFragSource":146,"./generateBlurVertSource":147,"./getMaxBlurKernelSize":148}],146:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateFragBlurSource; +var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] +}; + +var fragTemplate = ['varying vec2 vBlurTexCoords[%size%];', 'uniform sampler2D uSampler;', 'void main(void)', '{', ' gl_FragColor = vec4(0.0);', ' %blur%', '}'].join('\n'); + +function generateFragBlurSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + + var fragSource = fragTemplate; + + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value = void 0; + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + value = i; + + if (i >= halfLength) { + value = kernelSize - i - 1; + } + + blur = blur.replace('%value%', kernel[value]); + + blurLoop += blur; + blurLoop += '\n'; + } + + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize); + + return fragSource; +} + +},{}],147:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateVertBlurSource; +var vertTemplate = ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform float strength;', 'uniform mat3 projectionMatrix;', 'varying vec2 vBlurTexCoords[%size%];', 'void main(void)', '{', 'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);', '%blur%', '}'].join('\n'); + +function generateVertBlurSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + + var vertSource = vertTemplate; + + var blurLoop = ''; + var template = void 0; + // let value; + + if (x) { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } else { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + // value = i; + + // if(i >= halfLength) + // { + // value = kernelSize - i - 1; + // } + + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + '.0'); + + blurLoop += blur; + blurLoop += '\n'; + } + + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize); + + return vertSource; +} + +},{}],148:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = getMaxKernelSize; +function getMaxKernelSize(gl) { + var maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + var kernelSize = 15; + + while (kernelSize > maxVaryings) { + kernelSize -= 2; + } + + return kernelSize; +} + +},{}],149:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var ColorMatrixFilter = function (_core$Filter) { + _inherits(ColorMatrixFilter, _core$Filter); + + /** + * + */ + function ColorMatrixFilter() { + _classCallCheck(this, ColorMatrixFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n')); + + _this.uniforms.m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + _this.alpha = 1; + return _this; + } + + /** + * Transforms current matrix and set the new one + * + * @param {number[]} matrix - 5x4 matrix + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix(matrix) { + var multiply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + var newMatrix = matrix; + + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + + // set the new matrix + this.uniforms.m = newMatrix; + }; + + /** + * Multiplies two mat5's + * + * @private + * @param {number[]} out - 5x4 matrix the receiving matrix + * @param {number[]} a - 5x4 matrix the first operand + * @param {number[]} b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix + */ + + + ColorMatrixFilter.prototype._multiply = function _multiply(out, a, b) { + // Red Channel + out[0] = a[0] * b[0] + a[1] * b[5] + a[2] * b[10] + a[3] * b[15]; + out[1] = a[0] * b[1] + a[1] * b[6] + a[2] * b[11] + a[3] * b[16]; + out[2] = a[0] * b[2] + a[1] * b[7] + a[2] * b[12] + a[3] * b[17]; + out[3] = a[0] * b[3] + a[1] * b[8] + a[2] * b[13] + a[3] * b[18]; + out[4] = a[0] * b[4] + a[1] * b[9] + a[2] * b[14] + a[3] * b[19] + a[4]; + + // Green Channel + out[5] = a[5] * b[0] + a[6] * b[5] + a[7] * b[10] + a[8] * b[15]; + out[6] = a[5] * b[1] + a[6] * b[6] + a[7] * b[11] + a[8] * b[16]; + out[7] = a[5] * b[2] + a[6] * b[7] + a[7] * b[12] + a[8] * b[17]; + out[8] = a[5] * b[3] + a[6] * b[8] + a[7] * b[13] + a[8] * b[18]; + out[9] = a[5] * b[4] + a[6] * b[9] + a[7] * b[14] + a[8] * b[19] + a[9]; + + // Blue Channel + out[10] = a[10] * b[0] + a[11] * b[5] + a[12] * b[10] + a[13] * b[15]; + out[11] = a[10] * b[1] + a[11] * b[6] + a[12] * b[11] + a[13] * b[16]; + out[12] = a[10] * b[2] + a[11] * b[7] + a[12] * b[12] + a[13] * b[17]; + out[13] = a[10] * b[3] + a[11] * b[8] + a[12] * b[13] + a[13] * b[18]; + out[14] = a[10] * b[4] + a[11] * b[9] + a[12] * b[14] + a[13] * b[19] + a[14]; + + // Alpha Channel + out[15] = a[15] * b[0] + a[16] * b[5] + a[17] * b[10] + a[18] * b[15]; + out[16] = a[15] * b[1] + a[16] * b[6] + a[17] * b[11] + a[18] * b[16]; + out[17] = a[15] * b[2] + a[16] * b[7] + a[17] * b[12] + a[18] * b[17]; + out[18] = a[15] * b[3] + a[16] * b[8] + a[17] * b[13] + a[18] * b[18]; + out[19] = a[15] * b[4] + a[16] * b[9] + a[17] * b[14] + a[18] * b[19] + a[19]; + + return out; + }; + + /** + * Create a Float32 Array and normalize the offset component to 0-1 + * + * @private + * @param {number[]} matrix - 5x4 matrix + * @return {number[]} 5x4 matrix with all values between 0-1 + */ + + + ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix(matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + + return m; + }; + + /** + * Adjusts brightness + * + * @param {number} b - value of the brigthness (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.brightness = function brightness(b, multiply) { + var matrix = [b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the matrices in grey scales + * + * @param {number} scale - value of the grey (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.greyscale = function greyscale(scale, multiply) { + var matrix = [scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the black and white matrice. + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite(multiply) { + var matrix = [0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the hue property of the color + * + * @param {number} rotation - in degrees + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.hue = function hue(rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + + var a00 = cosR + (1.0 - cosR) * w; + var a01 = w * (1.0 - cosR) - sqrW * sinR; + var a02 = w * (1.0 - cosR) + sqrW * sinR; + + var a10 = w * (1.0 - cosR) + sqrW * sinR; + var a11 = cosR + w * (1.0 - cosR); + var a12 = w * (1.0 - cosR) - sqrW * sinR; + + var a20 = w * (1.0 - cosR) - sqrW * sinR; + var a21 = w * (1.0 - cosR) + sqrW * sinR; + var a22 = cosR + w * (1.0 - cosR); + + var matrix = [a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * + * @param {number} amount - value of the contrast (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.contrast = function contrast(amount, multiply) { + var v = (amount || 0) + 1; + var o = -0.5 * (v - 1); + + var matrix = [v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * + * @param {number} amount - The saturation amount (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.saturate = function saturate() { + var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var multiply = arguments[1]; + + var x = amount * 2 / 3 + 1; + var y = (x - 1) * -0.5; + + var matrix = [x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Desaturate image (remove color) + * + * Call the saturate function + * + */ + + + ColorMatrixFilter.prototype.desaturate = function desaturate() // eslint-disable-line no-unused-vars + { + this.saturate(-1); + }; + + /** + * Negative image (inverse of classic rgb matrix) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.negative = function negative(multiply) { + var matrix = [0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Sepia image + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.sepia = function sepia(multiply) { + var matrix = [0.393, 0.7689999, 0.18899999, 0, 0, 0.349, 0.6859999, 0.16799999, 0, 0, 0.272, 0.5339999, 0.13099999, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.technicolor = function technicolor(multiply) { + var matrix = [1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Polaroid filter + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.polaroid = function polaroid(multiply) { + var matrix = [1.438, -0.062, -0.062, 0, 0, -0.122, 1.378, -0.122, 0, 0, -0.016, -0.016, 1.483, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Filter who transforms : Red -> Blue and Blue -> Red + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.toBGR = function toBGR(multiply) { + var matrix = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.kodachrome = function kodachrome(multiply) { + var matrix = [1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Brown delicious browni filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.browni = function browni(multiply) { + var matrix = [0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Vintage filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.vintage = function vintage(multiply) { + var matrix = [0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * + * @param {number} desaturation - Tone values. + * @param {number} toned - Tone values. + * @param {string} lightColor - Tone values, example: `0xFFE580` + * @param {string} darkColor - Tone values, example: `0xFFE580` + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.colorTone = function colorTone(desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + + var lR = (lightColor >> 16 & 0xFF) / 255; + var lG = (lightColor >> 8 & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + + var dR = (darkColor >> 16 & 0xFF) / 255; + var dG = (darkColor >> 8 & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + + var matrix = [0.3, 0.59, 0.11, 0, 0, lR, lG, lB, desaturation, 0, dR, dG, dB, toned, 0, lR - dR, lG - dG, lB - dB, 0, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Night effect + * + * @param {number} intensity - The intensity of the night effect. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.night = function night(intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [intensity * -2.0, -intensity, 0, 0, 0, -intensity, 0, intensity, 0, 0, 0, intensity, intensity * 2.0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * + * @param {number} amount - how much the predator feels his future victim + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.predator = function predator(amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * LSD effect + * + * Multiply the current matrix + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.lsd = function lsd(multiply) { + var matrix = [2, -0.4, 0.5, 0, 0, -0.5, 2, -0.4, 0, 0, -0.4, -0.5, 3, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Erase the current matrix by setting the default one + * + */ + + + ColorMatrixFilter.prototype.reset = function reset() { + var matrix = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, false); + }; + + /** + * The matrix of the color matrix filter + * + * @member {number[]} + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + + + _createClass(ColorMatrixFilter, [{ + key: 'matrix', + get: function get() { + return this.uniforms.m; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.m = value; + } + + /** + * The opacity value to use when mixing the original and resultant colors. + * + * When the value is 0, the original color is used without modification. + * When the value is 1, the result color is used. + * When in the range (0, 1) the color is interpolated between the original and result by this amount. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'alpha', + get: function get() { + return this.uniforms.uAlpha; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uAlpha = value; + } + }]); + + return ColorMatrixFilter; +}(core.Filter); + +// Americanized alias + + +exports.default = ColorMatrixFilter; +ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + +},{"../../core":65,"path":23}],150:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. You can + * use this filter to apply all manor of crazy warping effects. Currently the r + * property of the texture is used to offset the x and the g property of the texture + * is used to offset the y. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var DisplacementFilter = function (_core$Filter) { + _inherits(DisplacementFilter, _core$Filter); + + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param {number} scale - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + _classCallCheck(this, DisplacementFilter); + + var maskMatrix = new core.Matrix(); + + sprite.renderable = false; + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n')); + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + + _this.uniforms.mapSampler = sprite._texture; + _this.uniforms.filterMatrix = maskMatrix; + _this.uniforms.scale = { x: 1, y: 1 }; + + if (scale === null || scale === undefined) { + scale = 20; + } + + _this.scale = new core.Point(scale, scale); + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + DisplacementFilter.prototype.apply = function apply(filterManager, input, output) { + var ratio = 1 / output.destinationFrame.width * (output.size.width / input.size.width); + + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x * ratio; + this.uniforms.scale.y = this.scale.y * ratio; + + // draw the filter... + filterManager.applyFilter(this, input, output); + }; + + /** + * The texture used for the displacement map. Must be power of 2 sized texture. + * + * @member {PIXI.Texture} + */ + + + _createClass(DisplacementFilter, [{ + key: 'map', + get: function get() { + return this.uniforms.mapSampler; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.mapSampler = value; + } + }]); + + return DisplacementFilter; +}(core.Filter); + +exports.default = DisplacementFilter; + +},{"../../core":65,"path":23}],151:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * Basic FXAA implementation based on the code on geeks3d.com with the + * modification that the texture2DLod stuff was removed since it's + * unsupported by WebGL. + * + * @see https://github.com/mitsuhiko/webgl-meincraft + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + * + */ +var FXAAFilter = function (_core$Filter) { + _inherits(FXAAFilter, _core$Filter); + + /** + * + */ + function FXAAFilter() { + _classCallCheck(this, FXAAFilter); + + // TODO - needs work + return _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + '\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}', + // fragment shader + 'varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n')); + } + + return FXAAFilter; +}(core.Filter); + +exports.default = FXAAFilter; + +},{"../../core":65,"path":23}],152:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _FXAAFilter = require('./fxaa/FXAAFilter'); + +Object.defineProperty(exports, 'FXAAFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_FXAAFilter).default; + } +}); + +var _NoiseFilter = require('./noise/NoiseFilter'); + +Object.defineProperty(exports, 'NoiseFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NoiseFilter).default; + } +}); + +var _DisplacementFilter = require('./displacement/DisplacementFilter'); + +Object.defineProperty(exports, 'DisplacementFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplacementFilter).default; + } +}); + +var _BlurFilter = require('./blur/BlurFilter'); + +Object.defineProperty(exports, 'BlurFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurFilter).default; + } +}); + +var _BlurXFilter = require('./blur/BlurXFilter'); + +Object.defineProperty(exports, 'BlurXFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurXFilter).default; + } +}); + +var _BlurYFilter = require('./blur/BlurYFilter'); + +Object.defineProperty(exports, 'BlurYFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurYFilter).default; + } +}); + +var _ColorMatrixFilter = require('./colormatrix/ColorMatrixFilter'); + +Object.defineProperty(exports, 'ColorMatrixFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ColorMatrixFilter).default; + } +}); + +var _VoidFilter = require('./void/VoidFilter'); + +Object.defineProperty(exports, 'VoidFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VoidFilter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./blur/BlurFilter":143,"./blur/BlurXFilter":144,"./blur/BlurYFilter":145,"./colormatrix/ColorMatrixFilter":149,"./displacement/DisplacementFilter":150,"./fxaa/FXAAFilter":151,"./noise/NoiseFilter":153,"./void/VoidFilter":154}],153:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Vico @vicocotea + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + */ + +/** + * A Noise effect filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var NoiseFilter = function (_core$Filter) { + _inherits(NoiseFilter, _core$Filter); + + /** + * @param {number} noise - The noise intensity, should be a normalized value in the range [0, 1]. + * @param {number} seed - A random seed for the noise generation. Default is `Math.random()`. + */ + function NoiseFilter() { + var noise = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0.5; + var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Math.random(); + + _classCallCheck(this, NoiseFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n')); + + _this.noise = noise; + _this.seed = seed; + return _this; + } + + /** + * The amount of noise to apply, this value should be in the range (0, 1]. + * + * @member {number} + * @default 0.5 + */ + + + _createClass(NoiseFilter, [{ + key: 'noise', + get: function get() { + return this.uniforms.uNoise; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uNoise = value; + } + + /** + * A seed value to apply to the random noise generation. `Math.random()` is a good value to use. + * + * @member {number} + */ + + }, { + key: 'seed', + get: function get() { + return this.uniforms.uSeed; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uSeed = value; + } + }]); + + return NoiseFilter; +}(core.Filter); + +exports.default = NoiseFilter; + +},{"../../core":65,"path":23}],154:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Does nothing. Very handy. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var VoidFilter = function (_core$Filter) { + _inherits(VoidFilter, _core$Filter); + + /** + * + */ + function VoidFilter() { + _classCallCheck(this, VoidFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n')); + + _this.glShaderKey = 'void'; + return _this; + } + + return VoidFilter; +}(core.Filter); + +exports.default = VoidFilter; + +},{"../../core":65,"path":23}],155:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Holds all information related to an Interaction event + * + * @class + * @memberof PIXI.interaction + */ +var InteractionData = function () { + /** + * + */ + function InteractionData() { + _classCallCheck(this, InteractionData); + + /** + * This point stores the global coords of where the touch/mouse event happened + * + * @member {PIXI.Point} + */ + this.global = new core.Point(); + + /** + * The target DisplayObject that was interacted with + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * When passed to an event handler, this will be the original DOM Event that was captured + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent + * @see https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent + * @member {MouseEvent|TouchEvent|PointerEvent} + */ + this.originalEvent = null; + + /** + * Unique identifier for this interaction + * + * @member {number} + */ + this.identifier = null; + + /** + * Indicates whether or not the pointer device that created the event is the primary pointer. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary + * @type {Boolean} + */ + this.isPrimary = false; + + /** + * Indicates which button was pressed on the mouse or pointer device to trigger the event. + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button + * @type {number} + */ + this.button = 0; + + /** + * Indicates which buttons are pressed on the mouse or pointer device when the event is triggered. + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons + * @type {number} + */ + this.buttons = 0; + + /** + * The width of the pointer's contact along the x-axis, measured in CSS pixels. + * radiusX of TouchEvents will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width + * @type {number} + */ + this.width = 0; + + /** + * The height of the pointer's contact along the y-axis, measured in CSS pixels. + * radiusY of TouchEvents will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height + * @type {number} + */ + this.height = 0; + + /** + * The angle, in degrees, between the pointer device and the screen. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX + * @type {number} + */ + this.tiltX = 0; + + /** + * The angle, in degrees, between the pointer device and the screen. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY + * @type {number} + */ + this.tiltY = 0; + + /** + * The type of pointer that triggered the event. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType + * @type {string} + */ + this.pointerType = null; + + /** + * Pressure applied by the pointing device during the event. A Touch's force property + * will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure + * @type {number} + */ + this.pressure = 0; + + /** + * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch. + * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle + * @type {number} + */ + this.rotationAngle = 0; + + /** + * Twist of a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + * @type {number} + */ + this.twist = 0; + + /** + * Barrel pressure on a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + * @type {number} + */ + this.tangentialPressure = 0; + } + + /** + * The unique identifier of the pointer. It will be the same as `identifier`. + * @readonly + * @member {number} + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId + */ + + + /** + * This will return the local coordinates of the specified displayObject for this InteractionData + * + * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local + * coords off + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative + * to the DisplayObject + */ + InteractionData.prototype.getLocalPosition = function getLocalPosition(displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + + /** + * Copies properties from normalized event data. + * + * @param {Touch|MouseEvent|PointerEvent} event The normalized event data + * @private + */ + + + InteractionData.prototype._copyEvent = function _copyEvent(event) { + // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite + // it with "false" on later events when our shim for it on touch events might not be + // accurate + if (event.isPrimary) { + this.isPrimary = true; + } + this.button = event.button; + this.buttons = event.buttons; + this.width = event.width; + this.height = event.height; + this.tiltX = event.tiltX; + this.tiltY = event.tiltY; + this.pointerType = event.pointerType; + this.pressure = event.pressure; + this.rotationAngle = event.rotationAngle; + this.twist = event.twist || 0; + this.tangentialPressure = event.tangentialPressure || 0; + }; + + /** + * Resets the data for pooling. + * + * @private + */ + + + InteractionData.prototype._reset = function _reset() { + // isPrimary is the only property that we really need to reset - everything else is + // guaranteed to be overwritten + this.isPrimary = false; + }; + + _createClass(InteractionData, [{ + key: 'pointerId', + get: function get() { + return this.identifier; + } + }]); + + return InteractionData; +}(); + +exports.default = InteractionData; + +},{"../core":65}],156:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Event class that mimics native DOM events. + * + * @class + * @memberof PIXI.interaction + */ +var InteractionEvent = function () { + /** + * + */ + function InteractionEvent() { + _classCallCheck(this, InteractionEvent); + + /** + * Whether this event will continue propagating in the tree + * + * @member {boolean} + */ + this.stopped = false; + + /** + * The object which caused this event to be dispatched. + * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}. + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * The object whose event listener’s callback is currently being invoked. + * + * @member {PIXI.DisplayObject} + */ + this.currentTarget = null; + + /** + * Type of the event + * + * @member {string} + */ + this.type = null; + + /** + * InteractionData related to this event + * + * @member {PIXI.interaction.InteractionData} + */ + this.data = null; + } + + /** + * Prevents event from reaching any objects other than the current object. + * + */ + + + InteractionEvent.prototype.stopPropagation = function stopPropagation() { + this.stopped = true; + }; + + /** + * Resets the event. + * + * @private + */ + + + InteractionEvent.prototype._reset = function _reset() { + this.stopped = false; + this.currentTarget = null; + this.target = null; + }; + + return InteractionEvent; +}(); + +exports.default = InteractionEvent; + +},{}],157:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _InteractionData = require('./InteractionData'); + +var _InteractionData2 = _interopRequireDefault(_InteractionData); + +var _InteractionEvent = require('./InteractionEvent'); + +var _InteractionEvent2 = _interopRequireDefault(_InteractionEvent); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +var _InteractionTrackingData2 = _interopRequireDefault(_InteractionTrackingData); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _interactiveTarget = require('./interactiveTarget'); + +var _interactiveTarget2 = _interopRequireDefault(_interactiveTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// Mix interactiveTarget into core.DisplayObject.prototype, after deprecation has been handled +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _interactiveTarget2.default); + +var MOUSE_POINTER_ID = 'MOUSE'; + +// helpers for hitTest() - only used inside hitTest() +var hitTestEvent = { + target: null, + data: { + global: null + } +}; + +/** + * The interaction manager deals with mouse, touch and pointer events. Any DisplayObject can be interactive + * if its interactive parameter is set to true + * This manager also supports multitouch. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.interaction + * + * @class + * @extends EventEmitter + * @memberof PIXI.interaction + */ + +var InteractionManager = function (_EventEmitter) { + _inherits(InteractionManager, _EventEmitter); + + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + * @param {object} [options] - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Frequency increases the interaction events will be checked. + */ + function InteractionManager(renderer, options) { + _classCallCheck(this, InteractionManager); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + options = options || {}; + + /** + * The renderer this interaction manager works for. + * + * @member {PIXI.SystemRenderer} + */ + _this.renderer = renderer; + + /** + * Should default browser actions automatically be prevented. + * Does not apply to pointer events for backwards compatibility + * preventDefault on pointer events stops mouse events from firing + * Thus, for every pointer event, there will always be either a mouse of touch event alongside it. + * + * @member {boolean} + * @default true + */ + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + + /** + * Frequency in milliseconds that the mousemove, moveover & mouseout interaction events will be checked. + * + * @member {number} + * @default 10 + */ + _this.interactionFrequency = options.interactionFrequency || 10; + + /** + * The mouse data + * + * @member {PIXI.interaction.InteractionData} + */ + _this.mouse = new _InteractionData2.default(); + _this.mouse.identifier = MOUSE_POINTER_ID; + + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + + /** + * Actively tracked InteractionData + * + * @private + * @member {Object.} + */ + _this.activeInteractionData = {}; + _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; + + /** + * Pool of unused InteractionData + * + * @private + * @member {PIXI.interation.InteractionData[]} + */ + _this.interactionDataPool = []; + + /** + * An event data object to handle all the event tracking/dispatching + * + * @member {object} + */ + _this.eventData = new _InteractionEvent2.default(); + + /** + * The DOM element to bind to. + * + * @private + * @member {HTMLElement} + */ + _this.interactionDOMElement = null; + + /** + * This property determines if mousemove and touchmove events are fired only when the cursor + * is over the object. + * Setting to true will make things work more in line with how the DOM verison works. + * Setting to false can make things easier for things like dragging + * It is currently set to false as this is how PixiJS used to work. This will be set to true in + * future versions of pixi. + * + * @member {boolean} + * @default false + */ + _this.moveWhenInside = false; + + /** + * Have events been attached to the dom element? + * + * @private + * @member {boolean} + */ + _this.eventsAdded = false; + + /** + * Is the mouse hovering over the renderer? + * + * @private + * @member {boolean} + */ + _this.mouseOverRenderer = false; + + /** + * Does the device support touch events + * https://www.w3.org/TR/touch-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsTouchEvents = 'ontouchstart' in window; + + /** + * Does the device support pointer events + * https://www.w3.org/Submission/pointer-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsPointerEvents = !!window.PointerEvent; + + // this will make it so that you don't have to call bind all the time + + /** + * @private + * @member {Function} + */ + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerCancel = _this.onPointerCancel.bind(_this); + _this.processPointerCancel = _this.processPointerCancel.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOver = _this.onPointerOver.bind(_this); + + /** + * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor + * values, objects are handled as dictionaries of CSS values for interactionDOMElement, + * and functions are called instead of changing the CSS. + * Default CSS cursor values are provided for 'default' and 'pointer' modes. + * @member {Object.)>} + */ + _this.cursorStyles = { + default: 'inherit', + pointer: 'pointer' + }; + + /** + * The mode of the cursor that is being used. + * The value of this is a key from the cursorStyles dictionary. + * + * @member {string} + */ + _this.currentCursorMode = null; + + /** + * Internal cached let. + * + * @private + * @member {string} + */ + _this.cursor = null; + + /** + * Internal cached let. + * + * @private + * @member {PIXI.Point} + */ + _this._tempPoint = new core.Point(); + + /** + * The current resolution / device pixel ratio. + * + * @member {number} + * @default 1 + */ + _this.resolution = 1; + + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display + * object. + * + * @event PIXI.interaction.InteractionManager#mousedown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * + * @event PIXI.interaction.InteractionManager#rightdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. + * + * @event PIXI.interaction.InteractionManager#mouseup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * + * @event PIXI.interaction.InteractionManager#rightup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. + * + * @event PIXI.interaction.InteractionManager#click + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * + * @event PIXI.interaction.InteractionManager#rightclick + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. + * + * @event PIXI.interaction.InteractionManager#mouseupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. + * + * @event PIXI.interaction.InteractionManager#rightupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * + * @event PIXI.interaction.InteractionManager#mousemove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * + * @event PIXI.interaction.InteractionManager#mouseover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * + * @event PIXI.interaction.InteractionManager#mouseout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * + * @event PIXI.interaction.InteractionManager#pointerdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released over the display object. + * + * @event PIXI.interaction.InteractionManager#pointerup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a pointer event + * + * @event PIXI.interaction.InteractionManager#pointercancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * + * @event PIXI.interaction.InteractionManager#pointertap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}. + * + * @event PIXI.interaction.InteractionManager#pointerupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved while over the display object + * + * @event PIXI.interaction.InteractionManager#pointermove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved onto the display object + * + * @event PIXI.interaction.InteractionManager#pointerover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved off the display object + * + * @event PIXI.interaction.InteractionManager#pointerout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed on the display object. + * + * @event PIXI.interaction.InteractionManager#touchstart + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed from the display object. + * + * @event PIXI.interaction.InteractionManager#touchend + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a touch + * + * @event PIXI.interaction.InteractionManager#touchcancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * + * @event PIXI.interaction.InteractionManager#tap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. + * + * @event PIXI.interaction.InteractionManager#touchendoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is moved along the display object. + * + * @event PIXI.interaction.InteractionManager#touchmove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display. + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mousedown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#click + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightclick + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.DisplayObject#event:mousedown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.DisplayObject#event:rightdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mousemove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a pointer event. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointercancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointertap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointermove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchstart + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchend + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a touch. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchcancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#tap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchendoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is moved along the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchmove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + return _this; + } + + /** + * Hit tests a point against the display tree, returning the first interactive object that is hit. + * + * @param {PIXI.Point} globalPoint - A point to hit test with, in global space. + * @param {PIXI.Container} [root] - The root display object to start from. If omitted, defaults + * to the last rendered root of the associated renderer. + * @return {PIXI.DisplayObject} The hit display object, if any. + */ + + + InteractionManager.prototype.hitTest = function hitTest(globalPoint, root) { + // clear the target for our hit test + hitTestEvent.target = null; + // assign the global point + hitTestEvent.data.global = globalPoint; + // ensure safety of the root + if (!root) { + root = this.renderer._lastObjectRendered; + } + // run the hit test + this.processInteractive(hitTestEvent, root, null, true); + // return our found object - it'll be null if we didn't hit anything + + return hitTestEvent.target; + }; + + /** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate + * another DOM element to receive those events. + * + * @param {HTMLCanvasElement} element - the DOM element which will receive mouse and touch events. + * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). + * @private + */ + + + InteractionManager.prototype.setTargetElement = function setTargetElement(element) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.removeEvents(); + + this.interactionDOMElement = element; + + this.resolution = resolution; + + this.addEvents(); + }; + + /** + * Registers all the DOM events + * + * @private + */ + + + InteractionManager.prototype.addEvents = function addEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.INTERACTION); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; + this.interactionDOMElement.style['-ms-touch-action'] = 'none'; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = 'none'; + } + + /** + * These events are added first, so that if pointer events are normalised, they are fired + * in the same order as non-normalised events. ie. pointer event 1st, mouse / touch 2nd + */ + if (this.supportsPointerEvents) { + window.document.addEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); + // pointerout is fired in addition to pointerup (for touch events) and pointercancel + // we already handle those, so for the purposes of what we do in onPointerOut, we only + // care about the pointerleave event + this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); + window.addEventListener('pointercancel', this.onPointerCancel, true); + window.addEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.addEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); + window.addEventListener('mouseup', this.onPointerUp, true); + } + + // always look directly for touch events so that we can provide original data + // In a future version we should change this to being just a fallback and rely solely on + // PointerEvents whenever available + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); + } + + this.eventsAdded = true; + }; + + /** + * Removes all the DOM events that were previously registered + * + * @private + */ + + + InteractionManager.prototype.removeEvents = function removeEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.remove(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = ''; + this.interactionDOMElement.style['-ms-touch-action'] = ''; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = ''; + } + + if (this.supportsPointerEvents) { + window.document.removeEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); + window.removeEventListener('pointercancel', this.onPointerCancel, true); + window.removeEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.removeEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true); + window.removeEventListener('mouseup', this.onPointerUp, true); + } + + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); + } + + this.interactionDOMElement = null; + + this.eventsAdded = false; + }; + + /** + * Updates the state of interactive objects. + * Invoked by a throttled ticker update from {@link PIXI.ticker.shared}. + * + * @param {number} deltaTime - time delta since last tick + */ + + + InteractionManager.prototype.update = function update(deltaTime) { + this._deltaTime += deltaTime; + + if (this._deltaTime < this.interactionFrequency) { + return; + } + + this._deltaTime = 0; + + if (!this.interactionDOMElement) { + return; + } + + // if the user move the mouse this check has already been done using the mouse move! + if (this.didMove) { + this.didMove = false; + + return; + } + + this.cursor = null; + + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + for (var k in this.activeInteractionData) { + // eslint-disable-next-line no-prototype-builtins + if (this.activeInteractionData.hasOwnProperty(k)) { + var interactionData = this.activeInteractionData[k]; + + if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, true); + } + } + } + + this.setCursorMode(this.cursor); + + // TODO + }; + + /** + * Sets the current cursor mode, handling any callbacks or CSS style changes. + * + * @param {string} mode - cursor mode, a key from the cursorStyles dictionary + */ + + + InteractionManager.prototype.setCursorMode = function setCursorMode(mode) { + mode = mode || 'default'; + // if the mode didn't actually change, bail early + if (this.currentCursorMode === mode) { + return; + } + this.currentCursorMode = mode; + var style = this.cursorStyles[mode]; + + // only do things if there is a cursor style for it + if (style) { + switch (typeof style === 'undefined' ? 'undefined' : _typeof(style)) { + case 'string': + // string styles are handled as cursor CSS + this.interactionDOMElement.style.cursor = style; + break; + case 'function': + // functions are just called, and passed the cursor mode + style(mode); + break; + case 'object': + // if it is an object, assume that it is a dictionary of CSS styles, + // apply it to the interactionDOMElement + Object.assign(this.interactionDOMElement.style, style); + break; + } + } else if (typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) { + // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry + // for the mode, then assume that the dev wants it to be CSS for the cursor. + this.interactionDOMElement.style.cursor = mode; + } + }; + + /** + * Dispatches an event on the display object that was interacted with + * + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the display object in question + * @param {string} eventString - the name of the event (e.g, mousedown) + * @param {object} eventData - the event data object + * @private + */ + + + InteractionManager.prototype.dispatchEvent = function dispatchEvent(displayObject, eventString, eventData) { + if (!eventData.stopped) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + + displayObject.emit(eventString, eventData); + + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } + }; + + /** + * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. + * + * @param {PIXI.Point} point - the point that the result will be stored in + * @param {number} x - the x coord of the position to map + * @param {number} y - the y coord of the position to map + */ + + + InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint(point, x, y) { + var rect = void 0; + + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { x: 0, y: 0, width: 0, height: 0 }; + } else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + + var resolutionMultiplier = navigator.isCocoonJS ? this.resolution : 1.0 / this.resolution; + + point.x = (x - rect.left) * (this.interactionDOMElement.width / rect.width) * resolutionMultiplier; + point.y = (y - rect.top) * (this.interactionDOMElement.height / rect.height) * resolutionMultiplier; + }; + + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that + * is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param {Function} [func] - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point + * @param {boolean} [interactive] - Whether the displayObject is interactive + * @return {boolean} returns true if the displayObject hit the point + */ + + + InteractionManager.prototype.processInteractive = function processInteractive(interactionEvent, displayObject, func, hitTest, interactive) { + if (!displayObject || !displayObject.visible) { + return false; + } + + var point = interactionEvent.data.global; + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + interactive = displayObject.interactive || interactive; + + var hit = false; + var interactiveParent = interactive; + + // if the displayobject has a hitArea, then it does not need to hitTest children. + if (displayObject.hitArea) { + interactiveParent = false; + } + // it has a mask! Then lets hit test that before continuing + else if (hitTest && displayObject._mask) { + if (!displayObject._mask.containsPoint(point)) { + hitTest = false; + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow PixiJS to completely ignore and bypass checking the displayObjects children. + if (displayObject.interactiveChildren && displayObject.children) { + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + + // time to get recursive.. if this function will return if something is hit.. + var childHit = this.processInteractive(interactionEvent, child, func, hitTest, interactiveParent); + + if (childHit) { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if (!child.parent) { + continue; + } + + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + + if (childHit) { + if (interactionEvent.target) { + hitTest = false; + } + hit = true; + } + } + } + } + + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit - but only if it was interactive, otherwise we need to keep + // looking for an interactive child, just in case we hit one + if (hitTest && !interactionEvent.target) { + if (displayObject.hitArea) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hit = true; + } + } else if (displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = true; + } + } + } + + if (displayObject.interactive) { + if (hit && !interactionEvent.target) { + interactionEvent.target = displayObject; + } + + if (func) { + func(interactionEvent, displayObject, !!hit); + } + } + } + + return hit; + }; + + /** + * Is called when the pointer button is pressed down on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down + */ + + + InteractionManager.prototype.onPointerDown = function onPointerDown(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + /** + * No need to prevent default on natural pointer events, as there are no side effects + * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, + * so still need to be prevented. + */ + + // Guaranteed that there will be at least one event in events, and all events must have the same pointer type + + if (this.autoPreventDefault && events[0].isNormalized) { + originalEvent.preventDefault(); + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerDown, true); + + this.emit('pointerdown', interactionEvent); + if (event.pointerType === 'touch') { + this.emit('touchstart', interactionEvent); + } + // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event + else if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + } + }; + + /** + * Processes the result of the pointer down check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerDown = function processPointerDown(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + + if (hit) { + if (!displayObject.trackedPointers[id]) { + displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchstart', interactionEvent); + } else if (data.pointerType === 'mouse' || data.pointerType === 'pen') { + var isRightButton = data.button === 2; + + if (isRightButton) { + displayObject.trackedPointers[id].rightDown = true; + } else { + displayObject.trackedPointers[id].leftDown = true; + } + + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released + * @param {boolean} cancelled - true if the pointer is cancelled + * @param {Function} func - Function passed to {@link processInteractive} + */ + + + InteractionManager.prototype.onPointerComplete = function onPointerComplete(originalEvent, cancelled, func) { + var events = this.normalizeToPointerData(originalEvent); + + var eventLen = events.length; + + // if the event wasn't targeting our canvas, then consider it to be pointerupoutside + // in all cases (unless it was a pointercancel) + var eventAppend = originalEvent.target !== this.interactionDOMElement ? 'outside' : ''; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + // perform hit testing for events targeting our canvas or cancel events + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, func, cancelled || !eventAppend); + + this.emit(cancelled ? 'pointercancel' : 'pointerup' + eventAppend, interactionEvent); + + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + + this.emit(isRightButton ? 'rightup' + eventAppend : 'mouseup' + eventAppend, interactionEvent); + } else if (event.pointerType === 'touch') { + this.emit(cancelled ? 'touchcancel' : 'touchend' + eventAppend, interactionEvent); + this.releaseInteractionDataForPointerId(event.pointerId, interactionData); + } + } + }; + + /** + * Is called when the pointer button is cancelled + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerCancel = function onPointerCancel(event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') return; + + this.onPointerComplete(event, true, this.processPointerCancel); + }; + + /** + * Processes the result of the pointer cancel check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + */ + + + InteractionManager.prototype.processPointerCancel = function processPointerCancel(interactionEvent, displayObject) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + if (displayObject.trackedPointers[id] !== undefined) { + delete displayObject.trackedPointers[id]; + this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); + + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerUp = function onPointerUp(event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') return; + + this.onPointerComplete(event, false, this.processPointerUp); + }; + + /** + * Processes the result of the pointer up check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerUp = function processPointerUp(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + var trackingData = displayObject.trackedPointers[id]; + + var isTouch = data.pointerType === 'touch'; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + // Mouse only + if (isMouse) { + var isRightButton = data.button === 2; + + var flags = _InteractionTrackingData2.default.FLAGS; + + var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; + + var isDown = trackingData !== undefined && trackingData.flags & test; + + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); + + if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); + } + } else if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); + } + // update the down state of the tracking data + if (trackingData) { + if (isRightButton) { + trackingData.rightDown = false; + } else { + trackingData.leftDown = false; + } + } + } + + // Pointers and Touches, and Mouse + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchend', interactionEvent); + + if (trackingData) { + this.dispatchEvent(displayObject, 'pointertap', interactionEvent); + if (isTouch) { + this.dispatchEvent(displayObject, 'tap', interactionEvent); + // touches are no longer over (if they ever were) when we get the touchend + // so we should ensure that we don't keep pretending that they are + trackingData.over = false; + } + } + } else if (trackingData) { + this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); + } + // Only remove the tracking data if there is no over/down state still associated with it + if (trackingData && trackingData.none) { + delete displayObject.trackedPointers[id]; + } + }; + + /** + * Is called when the pointer moves across the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer moving + */ + + + InteractionManager.prototype.onPointerMove = function onPointerMove(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + if (events[0].pointerType === 'mouse') { + this.didMove = true; + + this.cursor = null; + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + var interactive = event.pointerType === 'touch' ? this.moveWhenInside : true; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerMove, interactive); + this.emit('pointermove', interactionEvent); + if (event.pointerType === 'touch') this.emit('touchmove', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') this.emit('mousemove', interactionEvent); + } + + if (events[0].pointerType === 'mouse') { + this.setCursorMode(this.cursor); + + // TODO BUG for parents interactive object (border order issue) + } + }; + + /** + * Processes the result of the pointer move check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerMove = function processPointerMove(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var isTouch = data.pointerType === 'touch'; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + if (isMouse) { + this.processPointerOverOut(interactionEvent, displayObject, hit); + } + + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchmove', interactionEvent); + if (isMouse) this.dispatchEvent(displayObject, 'mousemove', interactionEvent); + } + }; + + /** + * Is called when the pointer is moved out of the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out + */ + + + InteractionManager.prototype.onPointerOut = function onPointerOut(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOut, so events will always be length 1 + var event = events[0]; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = false; + this.setCursorMode(null); + } + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, false); + + this.emit('pointerout', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseout', interactionEvent); + } else { + // we can get touchleave events after touchend, so we want to make sure we don't + // introduce memory leaks + this.releaseInteractionDataForPointerId(interactionData.identifier); + } + }; + + /** + * Processes the result of the pointer over/out check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerOverOut = function processPointerOverOut(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + var trackingData = displayObject.trackedPointers[id]; + + // if we just moused over the display object, then we need to track that state + if (hit && !trackingData) { + trackingData = displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + + if (trackingData === undefined) return; + + if (hit && this.mouseOverRenderer) { + if (!trackingData.over) { + trackingData.over = true; + this.dispatchEvent(displayObject, 'pointerover', interactionEvent); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseover', interactionEvent); + } + } + + // only change the cursor if it has not already been changed (by something deeper in the + // display tree) + if (isMouse && this.cursor === null) { + this.cursor = displayObject.cursor; + } + } else if (trackingData.over) { + trackingData.over = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseout', interactionEvent); + } + // if there is no mouse down information for the pointer, then it is safe to delete + if (trackingData.none) { + delete displayObject.trackedPointers[id]; + } + } + }; + + /** + * Is called when the pointer is moved into the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view + */ + + + InteractionManager.prototype.onPointerOver = function onPointerOver(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOver, so events will always be length 1 + var event = events[0]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = true; + } + + this.emit('pointerover', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseover', interactionEvent); + } + }; + + /** + * Get InteractionData for a given pointerId. Store that data as well + * + * @private + * @param {PointerEvent} event - Normalized pointer event, output from normalizeToPointerData + * @return {PIXI.interaction.InteractionData} - Interaction data for the given pointer identifier + */ + + + InteractionManager.prototype.getInteractionDataForPointerId = function getInteractionDataForPointerId(event) { + var pointerId = event.pointerId; + + var interactionData = void 0; + + if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { + interactionData = this.mouse; + } else if (this.activeInteractionData[pointerId]) { + interactionData = this.activeInteractionData[pointerId]; + } else { + interactionData = this.interactionDataPool.pop() || new _InteractionData2.default(); + interactionData.identifier = pointerId; + this.activeInteractionData[pointerId] = interactionData; + } + // copy properties from the event, so that we can make sure that touch/pointer specific + // data is available + interactionData._copyEvent(event); + + return interactionData; + }; + + /** + * Return unused InteractionData to the pool, for a given pointerId + * + * @private + * @param {number} pointerId - Identifier from a pointer event + */ + + + InteractionManager.prototype.releaseInteractionDataForPointerId = function releaseInteractionDataForPointerId(pointerId) { + var interactionData = this.activeInteractionData[pointerId]; + + if (interactionData) { + delete this.activeInteractionData[pointerId]; + interactionData._reset(); + this.interactionDataPool.push(interactionData); + } + }; + + /** + * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The event to be configured + * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent + * @param {PIXI.interaction.InteractionData} interactionData - The InteractionData that will be paired + * with the InteractionEvent + * @return {PIXI.interaction.InteractionEvent} the interaction event that was passed in + */ + + + InteractionManager.prototype.configureInteractionEventForDOMEvent = function configureInteractionEventForDOMEvent(interactionEvent, pointerEvent, interactionData) { + interactionEvent.data = interactionData; + + this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); + + // This is the way InteractionManager processed touch events before the refactoring, so I've kept + // it here. But it doesn't make that much sense to me, since mapPositionToPoint already factors + // in this.resolution, so this just divides by this.resolution twice for touch events... + if (navigator.isCocoonJS && pointerEvent.pointerType === 'touch') { + interactionData.global.x = interactionData.global.x / this.resolution; + interactionData.global.y = interactionData.global.y / this.resolution; + } + + // Not really sure why this is happening, but it's how a previous version handled things + if (pointerEvent.pointerType === 'touch') { + pointerEvent.globalX = interactionData.global.x; + pointerEvent.globalY = interactionData.global.y; + } + + interactionData.originalEvent = pointerEvent; + interactionEvent._reset(); + + return interactionEvent; + }; + + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * + * @private + * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event + * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer + * or mouse event, or a multiple normalized pointer events if there are multiple changed touches + */ + + + InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData(event) { + var normalizedEvents = []; + + if (this.supportsTouchEvents && event instanceof TouchEvent) { + for (var i = 0, li = event.changedTouches.length; i < li; i++) { + var touch = event.changedTouches[i]; + + if (typeof touch.button === 'undefined') touch.button = event.touches.length ? 1 : 0; + if (typeof touch.buttons === 'undefined') touch.buttons = event.touches.length ? 1 : 0; + if (typeof touch.isPrimary === 'undefined') { + touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart'; + } + if (typeof touch.width === 'undefined') touch.width = touch.radiusX || 1; + if (typeof touch.height === 'undefined') touch.height = touch.radiusY || 1; + if (typeof touch.tiltX === 'undefined') touch.tiltX = 0; + if (typeof touch.tiltY === 'undefined') touch.tiltY = 0; + if (typeof touch.pointerType === 'undefined') touch.pointerType = 'touch'; + if (typeof touch.pointerId === 'undefined') touch.pointerId = touch.identifier || 0; + if (typeof touch.pressure === 'undefined') touch.pressure = touch.force || 0.5; + touch.twist = 0; + touch.tangentialPressure = 0; + // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven + // support, and the fill ins are not quite the same + // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top + // left is not 0,0 on the page + if (typeof touch.layerX === 'undefined') touch.layerX = touch.offsetX = touch.clientX; + if (typeof touch.layerY === 'undefined') touch.layerY = touch.offsetY = touch.clientY; + + // mark the touch as normalized, just so that we know we did it + touch.isNormalized = true; + + normalizedEvents.push(touch); + } + } + // apparently PointerEvent subclasses MouseEvent, so yay + else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent))) { + if (typeof event.isPrimary === 'undefined') event.isPrimary = true; + if (typeof event.width === 'undefined') event.width = 1; + if (typeof event.height === 'undefined') event.height = 1; + if (typeof event.tiltX === 'undefined') event.tiltX = 0; + if (typeof event.tiltY === 'undefined') event.tiltY = 0; + if (typeof event.pointerType === 'undefined') event.pointerType = 'mouse'; + if (typeof event.pointerId === 'undefined') event.pointerId = MOUSE_POINTER_ID; + if (typeof event.pressure === 'undefined') event.pressure = 0.5; + event.twist = 0; + event.tangentialPressure = 0; + + // mark the mouse event as normalized, just so that we know we did it + event.isNormalized = true; + + normalizedEvents.push(event); + } else { + normalizedEvents.push(event); + } + + return normalizedEvents; + }; + + /** + * Destroys the interaction manager + * + */ + + + InteractionManager.prototype.destroy = function destroy() { + this.removeEvents(); + + this.removeAllListeners(); + + this.renderer = null; + + this.mouse = null; + + this.eventData = null; + + this.interactionDOMElement = null; + + this.onPointerDown = null; + this.processPointerDown = null; + + this.onPointerUp = null; + this.processPointerUp = null; + + this.onPointerCancel = null; + this.processPointerCancel = null; + + this.onPointerMove = null; + this.processPointerMove = null; + + this.onPointerOut = null; + this.processPointerOverOut = null; + + this.onPointerOver = null; + + this._tempPoint = null; + }; + + return InteractionManager; +}(_eventemitter2.default); + +exports.default = InteractionManager; + + +core.WebGLRenderer.registerPlugin('interaction', InteractionManager); +core.CanvasRenderer.registerPlugin('interaction', InteractionManager); + +},{"../core":65,"./InteractionData":155,"./InteractionEvent":156,"./InteractionTrackingData":158,"./interactiveTarget":160,"eventemitter3":3}],158:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * DisplayObjects with the {@link PIXI.interaction.interactiveTarget} mixin use this class to track interactions + * + * @class + * @private + * @memberof PIXI.interaction + */ +var InteractionTrackingData = function () { + /** + * @param {number} pointerId - Unique pointer id of the event + */ + function InteractionTrackingData(pointerId) { + _classCallCheck(this, InteractionTrackingData); + + this._pointerId = pointerId; + this._flags = InteractionTrackingData.FLAGS.NONE; + } + + /** + * + * @private + * @param {number} flag - The interaction flag to set + * @param {boolean} yn - Should the flag be set or unset + */ + + + InteractionTrackingData.prototype._doSet = function _doSet(flag, yn) { + if (yn) { + this._flags = this._flags | flag; + } else { + this._flags = this._flags & ~flag; + } + }; + + /** + * Unique pointer id of the event + * + * @readonly + * @member {number} + */ + + + _createClass(InteractionTrackingData, [{ + key: "pointerId", + get: function get() { + return this._pointerId; + } + + /** + * State of the tracking data, expressed as bit flags + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "flags", + get: function get() { + return this._flags; + } + + /** + * Set the flags for the tracking data + * + * @param {number} flags - Flags to set + */ + , + set: function set(flags) { + this._flags = flags; + } + + /** + * Is the tracked event inactive (not over or down)? + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "none", + get: function get() { + return this._flags === this.constructor.FLAGS.NONE; + } + + /** + * Is the tracked event over the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "over", + get: function get() { + return (this._flags & this.constructor.FLAGS.OVER) !== 0; + } + + /** + * Set the over flag + * + * @param {boolean} yn - Is the event over? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.OVER, yn); + } + + /** + * Did the right mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "rightDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.RIGHT_DOWN) !== 0; + } + + /** + * Set the right down flag + * + * @param {boolean} yn - Is the right mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.RIGHT_DOWN, yn); + } + + /** + * Did the left mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "leftDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.LEFT_DOWN) !== 0; + } + + /** + * Set the left down flag + * + * @param {boolean} yn - Is the left mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.LEFT_DOWN, yn); + } + }]); + + return InteractionTrackingData; +}(); + +exports.default = InteractionTrackingData; + + +InteractionTrackingData.FLAGS = Object.freeze({ + NONE: 0, + OVER: 1 << 0, + LEFT_DOWN: 1 << 1, + RIGHT_DOWN: 1 << 2 +}); + +},{}],159:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _InteractionData = require('./InteractionData'); + +Object.defineProperty(exports, 'InteractionData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionData).default; + } +}); + +var _InteractionManager = require('./InteractionManager'); + +Object.defineProperty(exports, 'InteractionManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionManager).default; + } +}); + +var _interactiveTarget = require('./interactiveTarget'); + +Object.defineProperty(exports, 'interactiveTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_interactiveTarget).default; + } +}); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +Object.defineProperty(exports, 'InteractionTrackingData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionTrackingData).default; + } +}); + +var _InteractionEvent = require('./InteractionEvent'); + +Object.defineProperty(exports, 'InteractionEvent', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionEvent).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./InteractionData":155,"./InteractionEvent":156,"./InteractionManager":157,"./InteractionTrackingData":158,"./interactiveTarget":160}],160:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * Default property values of interactive objects + * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties + * + * @private + * @name interactiveTarget + * @memberof PIXI.interaction + * @example + * function MyObject() {} + * + * Object.assign( + * core.DisplayObject.prototype, + * PIXI.interaction.interactiveTarget + * ); + */ +exports.default = { + + /** + * Enable interaction events for the DisplayObject. Touch, pointer and mouse + * events will not be emitted unless `interactive` is set to `true`. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.on('tap', (event) => { + * //handle event + * }); + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + interactive: false, + + /** + * Determines if the children to the displayObject can be clicked/touched + * Setting this to false allows PixiJS to bypass a recursive `hitTest` function + * + * @member {boolean} + * @memberof PIXI.Container# + */ + interactiveChildren: true, + + /** + * Interaction shape. Children will be hit first, then this shape will be checked. + * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.hitArea = new PIXI.Rectangle(0, 0, 100, 100); + * @member {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle} + * @memberof PIXI.DisplayObject# + */ + hitArea: null, + + /** + * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive + * Setting this changes the 'cursor' property to `'pointer'`. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.buttonMode = true; + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + get buttonMode() { + return this.cursor === 'pointer'; + }, + set buttonMode(value) { + if (value) { + this.cursor = 'pointer'; + } else if (this.cursor === 'pointer') { + this.cursor = null; + } + }, + + /** + * This defines what cursor mode is used when the mouse cursor + * is hovered over the displayObject. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.cursor = 'wait'; + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * + * @member {string} + * @memberof PIXI.DisplayObject# + */ + cursor: null, + + /** + * Internal set of all active pointers, by identifier + * + * @member {Map} + * @memberof PIXI.DisplayObject# + * @private + */ + get trackedPointers() { + if (this._trackedPointers === undefined) this._trackedPointers = {}; + + return this._trackedPointers; + }, + + /** + * Map of all tracked pointers, by identifier. Use trackedPointers to access. + * + * @private + * @type {Map} + */ + _trackedPointers: undefined +}; + +},{}],161:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.parse = parse; + +exports.default = function () { + return function bitmapFontParser(resource, next) { + // skip if no data or not xml data + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.XML) { + next(); + + return; + } + + // skip if not bitmap font data, using some silly duck-typing + if (resource.data.getElementsByTagName('page').length === 0 || resource.data.getElementsByTagName('info').length === 0 || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null) { + next(); + + return; + } + + var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; + + if (resource.isDataUrl) { + if (xmlUrl === '.') { + xmlUrl = ''; + } + + if (this.baseUrl && xmlUrl) { + // if baseurl has a trailing slash then add one to xmlUrl so the replace works below + if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { + xmlUrl += '/'; + } + } + } + + // remove baseUrl from xmlUrl + xmlUrl = xmlUrl.replace(this.baseUrl, ''); + + // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { + xmlUrl += '/'; + } + + var textureUrl = xmlUrl + resource.data.getElementsByTagName('page')[0].getAttribute('file'); + + if (_core.utils.TextureCache[textureUrl]) { + // reuse existing texture + parse(resource, _core.utils.TextureCache[textureUrl]); + next(); + } else { + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + // load the texture for the font + this.add(resource.name + '_image', textureUrl, loadOptions, function (res) { + parse(resource, res.texture); + next(); + }); + } + }; +}; + +var _path = require('path'); + +var path = _interopRequireWildcard(_path); + +var _core = require('../core'); + +var _resourceLoader = require('resource-loader'); + +var _extras = require('../extras'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Register a BitmapText font from loader resource. + * + * @function parseBitmapFontData + * @memberof PIXI.loaders + * @param {PIXI.loaders.Resource} resource - Loader resource. + * @param {PIXI.Texture} texture - Reference to texture. + */ +function parse(resource, texture) { + resource.bitmapFont = _extras.BitmapText.registerFont(resource.data, texture); +} + +},{"../core":65,"../extras":141,"path":23,"resource-loader":36}],162:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.shared = exports.Resource = exports.textureParser = exports.getResourcePath = exports.spritesheetParser = exports.parseBitmapFontData = exports.bitmapFontParser = exports.Loader = undefined; + +var _bitmapFontParser = require('./bitmapFontParser'); + +Object.defineProperty(exports, 'bitmapFontParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_bitmapFontParser).default; + } +}); +Object.defineProperty(exports, 'parseBitmapFontData', { + enumerable: true, + get: function get() { + return _bitmapFontParser.parse; + } +}); + +var _spritesheetParser = require('./spritesheetParser'); + +Object.defineProperty(exports, 'spritesheetParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_spritesheetParser).default; + } +}); +Object.defineProperty(exports, 'getResourcePath', { + enumerable: true, + get: function get() { + return _spritesheetParser.getResourcePath; + } +}); + +var _textureParser = require('./textureParser'); + +Object.defineProperty(exports, 'textureParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_textureParser).default; + } +}); + +var _resourceLoader = require('resource-loader'); + +Object.defineProperty(exports, 'Resource', { + enumerable: true, + get: function get() { + return _resourceLoader.Resource; + } +}); + +var _Application = require('../core/Application'); + +var _Application2 = _interopRequireDefault(_Application); + +var _loader = require('./loader'); + +var _loader2 = _interopRequireDefault(_loader); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * This namespace contains APIs which extends the {@link https://github.com/englercj/resource-loader resource-loader} module + * for loading assets, data, and other resources dynamically. + * @example + * const loader = new PIXI.loaders.Loader(); + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.load((loader, resources) => { + * // resources.bunny + * // resources.spaceship + * }); + * @namespace PIXI.loaders + */ +exports.Loader = _loader2.default; + + +/** + * A premade instance of the loader that can be used to load resources. + * @name shared + * @memberof PIXI.loaders + * @type {PIXI.loaders.Loader} + */ +var shared = new _loader2.default(); + +shared.destroy = function () { + // protect destroying shared loader +}; + +exports.shared = shared; + +// Mixin the loader construction + +var AppPrototype = _Application2.default.prototype; + +AppPrototype._loader = null; + +/** + * Loader instance to help with asset loading. + * @name PIXI.Application#loader + * @type {PIXI.loaders.Loader} + */ +Object.defineProperty(AppPrototype, 'loader', { + get: function get() { + if (!this._loader) { + var sharedLoader = this._options.sharedLoader; + + this._loader = sharedLoader ? shared : new _loader2.default(); + } + + return this._loader; + } +}); + +// Override the destroy function +// making sure to destroy the current Loader +AppPrototype._parentDestroy = AppPrototype.destroy; +AppPrototype.destroy = function destroy(removeView) { + if (this._loader) { + this._loader.destroy(); + this._loader = null; + } + this._parentDestroy(removeView); +}; + +},{"../core/Application":43,"./bitmapFontParser":161,"./loader":163,"./spritesheetParser":164,"./textureParser":165,"resource-loader":36}],163:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _resourceLoader = require('resource-loader'); + +var _resourceLoader2 = _interopRequireDefault(_resourceLoader); + +var _blob = require('resource-loader/lib/middlewares/parsing/blob'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _textureParser = require('./textureParser'); + +var _textureParser2 = _interopRequireDefault(_textureParser); + +var _spritesheetParser = require('./spritesheetParser'); + +var _spritesheetParser2 = _interopRequireDefault(_spritesheetParser); + +var _bitmapFontParser = require('./bitmapFontParser'); + +var _bitmapFontParser2 = _interopRequireDefault(_bitmapFontParser); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader + * + * ```js + * const loader = PIXI.loader; // PixiJS exposes a premade instance for you to use. + * //or + * const loader = new PIXI.loaders.Loader(); // you can also create your own if you want + * + * const sprites = {}; + * + * // Chainable `add` to enqueue a resource + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.add('scoreFont', 'assets/score.fnt'); + * + * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. + * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). + * loader.pre(cachingMiddleware); + * + * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. + * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). + * loader.use(parsingMiddleware); + * + * // The `load` method loads the queue of resources, and calls the passed in callback called once all + * // resources have loaded. + * loader.load((loader, resources) => { + * // resources is an object where the key is the name of the resource loaded and the value is the resource object. + * // They have a couple default properties: + * // - `url`: The URL that the resource was loaded from + * // - `error`: The error that happened when trying to load (if any) + * // - `data`: The raw data that was loaded + * // also may contain other properties based on the middleware that runs. + * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); + * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); + * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); + * }); + * + * // throughout the process multiple signals can be dispatched. + * loader.onProgress.add(() => {}); // called once per loaded/errored file + * loader.onError.add(() => {}); // called once per errored file + * loader.onLoad.add(() => {}); // called once per loaded file + * loader.onComplete.add(() => {}); // called once when the queued resources all load. + * ``` + * + * @see https://github.com/englercj/resource-loader + * + * @class + * @extends module:resource-loader.ResourceLoader + * @memberof PIXI.loaders + */ +var Loader = function (_ResourceLoader) { + _inherits(Loader, _ResourceLoader); + + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + _classCallCheck(this, Loader); + + var _this = _possibleConstructorReturn(this, _ResourceLoader.call(this, baseUrl, concurrency)); + + _eventemitter2.default.call(_this); + + for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { + _this.use(Loader._pixiMiddleware[i]()); + } + + // Compat layer, translate the new v2 signals into old v1 events. + _this.onStart.add(function (l) { + return _this.emit('start', l); + }); + _this.onProgress.add(function (l, r) { + return _this.emit('progress', l, r); + }); + _this.onError.add(function (e, l, r) { + return _this.emit('error', e, l, r); + }); + _this.onLoad.add(function (l, r) { + return _this.emit('load', l, r); + }); + _this.onComplete.add(function (l, r) { + return _this.emit('complete', l, r); + }); + return _this; + } + + /** + * Adds a default middleware to the PixiJS loader. + * + * @static + * @param {Function} fn - The middleware to add. + */ + + + Loader.addPixiMiddleware = function addPixiMiddleware(fn) { + Loader._pixiMiddleware.push(fn); + }; + + /** + * Destroy the loader, removes references. + */ + + + Loader.prototype.destroy = function destroy() { + this.removeAllListeners(); + this.reset(); + }; + + return Loader; +}(_resourceLoader2.default); + +// Copy EE3 prototype (mixin) + + +exports.default = Loader; +for (var k in _eventemitter2.default.prototype) { + Loader.prototype[k] = _eventemitter2.default.prototype[k]; +} + +Loader._pixiMiddleware = [ +// parse any blob into more usable objects (e.g. Image) +_blob.blobMiddlewareFactory, +// parse any Image objects into textures +_textureParser2.default, +// parse any spritesheet data into multiple textures +_spritesheetParser2.default, +// parse bitmap font data into multiple textures +_bitmapFontParser2.default]; + +// Add custom extentions +var Resource = _resourceLoader2.default.Resource; + +Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); + +},{"./bitmapFontParser":161,"./spritesheetParser":164,"./textureParser":165,"eventemitter3":3,"resource-loader":36,"resource-loader/lib/middlewares/parsing/blob":37}],164:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function spritesheetParser(resource, next) { + var imageResourceName = resource.name + '_image'; + + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.JSON || !resource.data.frames || this.resources[imageResourceName]) { + next(); + + return; + } + + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + var resourcePath = getResourcePath(resource, this.baseUrl); + + // load the image for this sheet + this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + var spritesheet = new _core.Spritesheet(res.texture.baseTexture, resource.data, resource.url); + + spritesheet.parse(function () { + resource.spritesheet = spritesheet; + resource.textures = spritesheet.textures; + next(); + }); + }); + }; +}; + +exports.getResourcePath = getResourcePath; + +var _resourceLoader = require('resource-loader'); + +var _url = require('url'); + +var _url2 = _interopRequireDefault(_url); + +var _core = require('../core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function getResourcePath(resource, baseUrl) { + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + return resource.data.meta.image; + } + + return _url2.default.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); +} + +},{"../core":65,"resource-loader":36,"url":29}],165:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function textureParser(resource, next) { + // create a new texture if the data is an Image object + if (resource.data && resource.type === _resourceLoader.Resource.TYPE.IMAGE) { + resource.texture = _Texture2.default.fromLoader(resource.data, resource.url, resource.name); + } + next(); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"../core/textures/Texture":115,"resource-loader":36}],166:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _TextureTransform = require('../extras/TextureTransform'); + +var _TextureTransform2 = _interopRequireDefault(_TextureTransform); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); +var tempPolygon = new core.Polygon(); + +/** + * Base mesh class + * @class + * @extends PIXI.Container + * @memberof PIXI.mesh + */ + +var Mesh = function (_core$Container) { + _inherits(Mesh, _core$Container); + + /** + * @param {PIXI.Texture} texture - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts + */ + function Mesh(texture, vertices, uvs, indices, drawMode) { + _classCallCheck(this, Mesh); + + /** + * The texture of the Mesh + * + * @member {PIXI.Texture} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._texture = texture; + + /** + * The Uvs of the Mesh + * + * @member {Float32Array} + */ + _this.uvs = uvs || new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + /** + * An array of vertices + * + * @member {Float32Array} + */ + _this.vertices = vertices || new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]); + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + // TODO auto generate this based on draw mode! + _this.indices = indices || new Uint16Array([0, 1, 3, 2]); + + /** + * Version of mesh uvs are dirty or not + * + * @member {number} + */ + _this.dirty = 0; + + /** + * Version of mesh indices + * + * @member {number} + */ + _this.indexDirty = 0; + + /** + * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove + * any blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles + * to overlap a bit with each other. + * + * @member {number} + */ + _this.canvasPadding = 0; + + /** + * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts + * + * @member {number} + * @see PIXI.mesh.Mesh.DRAW_MODES + */ + _this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH; + + /** + * The default shader that is used if a mesh doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + _this.shader = null; + + /** + * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any + * tint effect. + * + * @member {number} + */ + _this.tintRgb = new Float32Array([1, 1, 1]); + + /** + * A map of renderer IDs to webgl render data + * + * @private + * @member {object} + */ + _this._glDatas = {}; + + /** + * transform that is applied to UV to get the texture coords + * its updated independently from texture uvTransform + * updates of uvs are tied to that thing + * + * @member {PIXI.extras.TextureTransform} + * @private + */ + _this._uvTransform = new _TextureTransform2.default(texture); + + /** + * whether or not upload uvTransform to shader + * if its false, then uvs should be pre-multiplied + * if you change it for generated mesh, please call 'refresh(true)' + * @member {boolean} + * @default false + */ + _this.uploadUvTransform = false; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * @member {string} + * @default 'mesh' + */ + _this.pluginName = 'mesh'; + return _this; + } + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - a reference to the WebGL renderer + */ + + + Mesh.prototype._renderWebGL = function _renderWebGL(renderer) { + this.refresh(); + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + + + Mesh.prototype._renderCanvas = function _renderCanvas(renderer) { + this.refresh(); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Mesh.prototype._onTextureUpdate = function _onTextureUpdate() { + this._uvTransform.texture = this._texture; + this.refresh(); + }; + + /** + * multiplies uvs only if uploadUvTransform is false + * call it after you change uvs manually + * make sure that texture is valid + */ + + + Mesh.prototype.multiplyUvs = function multiplyUvs() { + if (!this.uploadUvTransform) { + this._uvTransform.multiplyUvs(this.uvs); + } + }; + + /** + * Refreshes uvs for generated meshes (rope, plane) + * sometimes refreshes vertices too + * + * @param {boolean} [forceUpdate=false] if true, matrices will be updated any case + */ + + + Mesh.prototype.refresh = function refresh(forceUpdate) { + if (this._uvTransform.update(forceUpdate)) { + this._refresh(); + } + }; + + /** + * re-calculates mesh coords + * @protected + */ + + + Mesh.prototype._refresh = function _refresh() {} + /* empty */ + + + /** + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + */ + ; + + Mesh.prototype._calculateBounds = function _calculateBounds() { + // TODO - we can cache local bounds and use them if they are dirty (like graphics) + this._bounds.addVertices(this.transform, this.vertices, 0, this.vertices.length); + }; + + /** + * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Mesh.prototype.containsPoint = function containsPoint(point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + + this.worldTransform.applyInverse(point, tempPoint); + + var vertices = this.vertices; + var points = tempPolygon.points; + var indices = this.indices; + var len = this.indices.length; + var step = this.drawMode === Mesh.DRAW_MODES.TRIANGLES ? 3 : 1; + + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + + return false; + }; + + /** + * The texture that the mesh uses. + * + * @member {PIXI.Texture} + */ + + + _createClass(Mesh, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + + /** + * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return core.utils.rgb2hex(this.tintRgb); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tintRgb = core.utils.hex2rgb(value, this.tintRgb); + } + }]); + + return Mesh; +}(core.Container); + +/** + * Different drawing buffer modes supported + * + * @static + * @constant + * @type {object} + * @property {number} TRIANGLE_MESH + * @property {number} TRIANGLES + */ + + +exports.default = Mesh; +Mesh.DRAW_MODES = { + TRIANGLE_MESH: 0, + TRIANGLES: 1 +}; + +},{"../core":65,"../extras/TextureTransform":136}],167:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Plane2 = require('./Plane'); + +var _Plane3 = _interopRequireDefault(_Plane2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DEFAULT_BORDER_SIZE = 10; + +/** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.fromImage('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
+ *      A                          B
+ *    +---+----------------------+---+
+ *  C | 1 |          2           | 3 |
+ *    +---+----------------------+---+
+ *    |   |                      |   |
+ *    | 4 |          5           | 6 |
+ *    |   |                      |   |
+ *    +---+----------------------+---+
+ *  D | 7 |          8           | 9 |
+ *    +---+----------------------+---+
+
+ *  When changing this objects width and/or height:
+ *     areas 1 3 7 and 9 will remain unscaled.
+ *     areas 2 and 8 will be stretched horizontally
+ *     areas 4 and 6 will be stretched vertically
+ *     area 5 will be stretched both horizontally and vertically
+ * 
+ * + * @class + * @extends PIXI.mesh.Plane + * @memberof PIXI.mesh + * + */ + +var NineSlicePlane = function (_Plane) { + _inherits(NineSlicePlane, _Plane); + + /** + * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. + * @param {int} [leftWidth=10] size of the left vertical bar (A) + * @param {int} [topHeight=10] size of the top horizontal bar (C) + * @param {int} [rightWidth=10] size of the right vertical bar (B) + * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) + */ + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + _classCallCheck(this, NineSlicePlane); + + var _this = _possibleConstructorReturn(this, _Plane.call(this, texture, 4, 4)); + + _this._origWidth = texture.orig.width; + _this._origHeight = texture.orig.height; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._width = _this._origWidth; + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._height = _this._origHeight; + + /** + * The width of the left column (a) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; + + /** + * The width of the right column (b) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; + + /** + * The height of the top row (c) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; + + /** + * The height of the bottom row (d) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; + + _this.refresh(true); + return _this; + } + + /** + * Updates the horizontal vertices. + * + */ + + + NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices() { + var vertices = this.vertices; + + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight; + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + }; + + /** + * Updates the vertical vertices. + * + */ + + + NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices() { + var vertices = this.vertices; + + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth; + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with. + */ + + + NineSlicePlane.prototype._renderCanvas = function _renderCanvas(renderer) { + var context = renderer.context; + + context.globalAlpha = this.worldAlpha; + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + var base = this._texture.baseTexture; + var textureSource = base.source; + var w = base.width; + var h = base.height; + + this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11); + this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13); + this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15); + this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19); + this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21); + this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23); + this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27); + this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29); + this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31); + }; + + /** + * Renders one segment of the plane. + * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure + * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used. + * + * @private + * @param {CanvasRenderingContext2D} context - The context to draw with. + * @param {CanvasImageSource} textureSource - The source to draw. + * @param {number} w - width of the texture + * @param {number} h - height of the texture + * @param {number} x1 - x index 1 + * @param {number} y1 - y index 1 + * @param {number} x2 - x index 2 + * @param {number} y2 - y index 2 + */ + + + NineSlicePlane.prototype.drawSegment = function drawSegment(context, textureSource, w, h, x1, y1, x2, y2) { + // otherwise you get weird results when using slices of that are 0 wide or high. + var uvs = this.uvs; + var vertices = this.vertices; + + var sw = (uvs[x2] - uvs[x1]) * w; + var sh = (uvs[y2] - uvs[y1]) * h; + var dw = vertices[x2] - vertices[x1]; + var dh = vertices[y2] - vertices[y1]; + + // make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn. + if (sw < 1) { + sw = 1; + } + + if (sh < 1) { + sh = 1; + } + + // make sure destination is at least 1 pixel wide and high, otherwise you get + // lines when rendering close to original size. + if (dw < 1) { + dw = 1; + } + + if (dh < 1) { + dh = 1; + } + + context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh); + }; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + + /** + * Refreshes NineSlicePlane coords. All of them. + */ + NineSlicePlane.prototype._refresh = function _refresh() { + _Plane.prototype._refresh.call(this); + + var uvs = this.uvs; + var texture = this._texture; + + this._origWidth = texture.orig.width; + this._origHeight = texture.orig.height; + + var _uvw = 1.0 / this._origWidth; + var _uvh = 1.0 / this._origHeight; + + uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; + uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - _uvw * this._rightWidth; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - _uvh * this._bottomHeight; + + this.updateHorizontalVertices(); + this.updateVerticalVertices(); + + this.dirty = true; + + this.multiplyUvs(); + }; + + _createClass(NineSlicePlane, [{ + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + this._refresh(); + } + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + this._refresh(); + } + + /** + * The width of the left column + * + * @member {number} + */ + + }, { + key: 'leftWidth', + get: function get() { + return this._leftWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._leftWidth = value; + this._refresh(); + } + + /** + * The width of the right column + * + * @member {number} + */ + + }, { + key: 'rightWidth', + get: function get() { + return this._rightWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rightWidth = value; + this._refresh(); + } + + /** + * The height of the top row + * + * @member {number} + */ + + }, { + key: 'topHeight', + get: function get() { + return this._topHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._topHeight = value; + this._refresh(); + } + + /** + * The height of the bottom row + * + * @member {number} + */ + + }, { + key: 'bottomHeight', + get: function get() { + return this._bottomHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._bottomHeight = value; + this._refresh(); + } + }]); + + return NineSlicePlane; +}(_Plane3.default); + +exports.default = NineSlicePlane; + +},{"./Plane":168}],168:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The Plane allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Plane = function (_Mesh) { + _inherits(Plane, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the Plane. + * @param {number} verticesX - The number of vertices in the x-axis + * @param {number} verticesY - The number of vertices in the y-axis + */ + function Plane(texture, verticesX, verticesY) { + _classCallCheck(this, Plane); + + /** + * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this._ready = true; + + _this.verticesX = verticesX || 10; + _this.verticesY = verticesY || 10; + + _this.drawMode = _Mesh3.default.DRAW_MODES.TRIANGLES; + _this.refresh(); + return _this; + } + + /** + * Refreshes plane coordinates + * + */ + + + Plane.prototype._refresh = function _refresh() { + var texture = this._texture; + var total = this.verticesX * this.verticesY; + var verts = []; + var colors = []; + var uvs = []; + var indices = []; + + var segmentsX = this.verticesX - 1; + var segmentsY = this.verticesY - 1; + + var sizeX = texture.width / segmentsX; + var sizeY = texture.height / segmentsY; + + for (var i = 0; i < total; i++) { + var x = i % this.verticesX; + var y = i / this.verticesX | 0; + + verts.push(x * sizeX, y * sizeY); + + uvs.push(x / segmentsX, y / segmentsY); + } + + // cons + + var totalSub = segmentsX * segmentsY; + + for (var _i = 0; _i < totalSub; _i++) { + var xpos = _i % segmentsX; + var ypos = _i / segmentsX | 0; + + var value = ypos * this.verticesX + xpos; + var value2 = ypos * this.verticesX + xpos + 1; + var value3 = (ypos + 1) * this.verticesX + xpos; + var value4 = (ypos + 1) * this.verticesX + xpos + 1; + + indices.push(value, value2, value3); + indices.push(value2, value4, value3); + } + + // console.log(indices) + this.vertices = new Float32Array(verts); + this.uvs = new Float32Array(uvs); + this.colors = new Float32Array(colors); + this.indices = new Uint16Array(indices); + this.indexDirty = true; + + this.multiplyUvs(); + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Plane.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh3.default.prototype._onTextureUpdate.call(this); + + // wait for the Plane ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + return Plane; +}(_Mesh3.default); + +exports.default = Plane; + +},{"./Mesh":166}],169:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The rope allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Rope = function (_Mesh) { + _inherits(Rope, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the rope. + * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. + */ + function Rope(texture, points) { + _classCallCheck(this, Rope); + + /** + * An array of points that determine the rope + * + * @member {PIXI.Point[]} + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this.points = points; + + /** + * An array of vertices used to construct this rope. + * + * @member {Float32Array} + */ + _this.vertices = new Float32Array(points.length * 4); + + /** + * The WebGL Uvs of the rope. + * + * @member {Float32Array} + */ + _this.uvs = new Float32Array(points.length * 4); + + /** + * An array containing the color components + * + * @member {Float32Array} + */ + _this.colors = new Float32Array(points.length * 2); + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + _this.indices = new Uint16Array(points.length * 2); + + /** + * refreshes vertices on every updateTransform + * @member {boolean} + * @default true + */ + _this.autoUpdate = true; + + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Rope.prototype._refresh = function _refresh() { + var points = this.points; + + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1 || !this._texture._uvs) { + return; + } + + // if the number of points has changed we will need to recreate the arraybuffers + if (this.vertices.length / 4 !== points.length) { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + + for (var i = 1; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + var amount = i / (total - 1); + + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + + // ensure that the changes are uploaded + this.dirty++; + this.indexDirty++; + + this.multiplyUvs(); + this.refreshVertices(); + }; + + /** + * refreshes vertices of Rope mesh + */ + + + Rope.prototype.refreshVertices = function refreshVertices() { + var points = this.points; + + if (points.length < 1) { + return; + } + + var lastPoint = points[0]; + var nextPoint = void 0; + var perpX = 0; + var perpY = 0; + + // this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } else { + nextPoint = point; + } + + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + + var ratio = (1 - i / (total - 1)) * 10; + + if (ratio > 1) { + ratio = 1; + } + + var perpLength = Math.sqrt(perpX * perpX + perpY * perpY); + var num = this._texture.height / 2; // (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; + + perpX /= perpLength; + perpY /= perpLength; + + perpX *= num; + perpY *= num; + + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + + lastPoint = point; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + Rope.prototype.updateTransform = function updateTransform() { + if (this.autoUpdate) { + this.refreshVertices(); + } + this.containerUpdateTransform(); + }; + + return Rope; +}(_Mesh3.default); + +exports.default = Rope; + +},{"./Mesh":166}],170:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Renderer dedicated to meshes. + * + * @class + * @private + * @memberof PIXI + */ +var MeshSpriteRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The renderer this downport works for + */ + function MeshSpriteRenderer(renderer) { + _classCallCheck(this, MeshSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the Mesh + * + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var context = renderer.context; + + var transform = mesh.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + renderer.setBlendMode(mesh.blendMode); + + if (mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH) { + this._renderTriangleMesh(mesh); + } else { + this._renderTriangles(mesh); + } + }; + + /** + * Draws the object in Triangle Mesh mode + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype._renderTriangleMesh = function _renderTriangleMesh(mesh) { + // draw triangles!! + var length = mesh.vertices.length / 2; + + for (var i = 0; i < length - 2; i++) { + // draw some triangles! + var index = i * 2; + + this._renderDrawTriangle(mesh, index, index + 2, index + 4); + } + }; + + /** + * Draws the object in triangle mode using canvas + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + */ + + + MeshSpriteRenderer.prototype._renderTriangles = function _renderTriangles(mesh) { + // draw triangles!! + var indices = mesh.indices; + var length = indices.length; + + for (var i = 0; i < length; i += 3) { + // draw some triangles! + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderDrawTriangle(mesh, index0, index1, index2); + } + }; + + /** + * Draws one of the triangles that from the Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + * @param {number} index0 - the index of the first vertex + * @param {number} index1 - the index of the second vertex + * @param {number} index2 - the index of the third vertex + */ + + + MeshSpriteRenderer.prototype._renderDrawTriangle = function _renderDrawTriangle(mesh, index0, index1, index2) { + var context = this.renderer.context; + var uvs = mesh.uvs; + var vertices = mesh.vertices; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var base = texture.baseTexture; + var textureSource = base.source; + var textureWidth = base.width; + var textureHeight = base.height; + + var u0 = void 0; + var u1 = void 0; + var u2 = void 0; + var v0 = void 0; + var v1 = void 0; + var v2 = void 0; + + if (mesh.uploadUvTransform) { + var ut = mesh._uvTransform.mapCoord; + + u0 = (uvs[index0] * ut.a + uvs[index0 + 1] * ut.c + ut.tx) * base.width; + u1 = (uvs[index1] * ut.a + uvs[index1 + 1] * ut.c + ut.tx) * base.width; + u2 = (uvs[index2] * ut.a + uvs[index2 + 1] * ut.c + ut.tx) * base.width; + v0 = (uvs[index0] * ut.b + uvs[index0 + 1] * ut.d + ut.ty) * base.height; + v1 = (uvs[index1] * ut.b + uvs[index1 + 1] * ut.d + ut.ty) * base.height; + v2 = (uvs[index2] * ut.b + uvs[index2 + 1] * ut.d + ut.ty) * base.height; + } else { + u0 = uvs[index0] * base.width; + u1 = uvs[index1] * base.width; + u2 = uvs[index2] * base.width; + v0 = uvs[index0 + 1] * base.height; + v1 = uvs[index1 + 1] * base.height; + v2 = uvs[index2 + 1] * base.height; + } + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + if (mesh.canvasPadding > 0) { + var paddingX = mesh.canvasPadding / mesh.worldTransform.a; + var paddingY = mesh.canvasPadding / mesh.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt(normX * normX + normY * normY); + + x0 = centerX + normX / dist * (dist + paddingX); + y0 = centerY + normY / dist * (dist + paddingY); + + // + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x1 = centerX + normX / dist * (dist + paddingX); + y1 = centerY + normY / dist * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x2 = centerX + normX / dist * (dist + paddingX); + y2 = centerY + normY / dist * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2; + var deltaA = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2; + var deltaB = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2; + var deltaC = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2; + var deltaD = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2; + var deltaE = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2; + var deltaF = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2; + + context.transform(deltaA / delta, deltaD / delta, deltaB / delta, deltaE / delta, deltaC / delta, deltaF / delta); + + context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + + context.restore(); + }; + + /** + * Renders a flat Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - The Mesh to render + */ + + + MeshSpriteRenderer.prototype.renderMeshFlat = function renderMeshFlat(mesh) { + var context = this.renderer.context; + var vertices = mesh.vertices; + var length = vertices.length / 2; + + // this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; ++i) { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var y0 = vertices[index + 1]; + + var x1 = vertices[index + 2]; + var y1 = vertices[index + 3]; + + var x2 = vertices[index + 4]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + }; + + /** + * destroy the the renderer. + * + */ + + + MeshSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return MeshSpriteRenderer; +}(); + +exports.default = MeshSpriteRenderer; + + +core.CanvasRenderer.registerPlugin('mesh', MeshSpriteRenderer); + +},{"../../core":65,"../Mesh":166}],171:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh = require('./Mesh'); + +Object.defineProperty(exports, 'Mesh', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Mesh).default; + } +}); + +var _MeshRenderer = require('./webgl/MeshRenderer'); + +Object.defineProperty(exports, 'MeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_MeshRenderer).default; + } +}); + +var _CanvasMeshRenderer = require('./canvas/CanvasMeshRenderer'); + +Object.defineProperty(exports, 'CanvasMeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasMeshRenderer).default; + } +}); + +var _Plane = require('./Plane'); + +Object.defineProperty(exports, 'Plane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Plane).default; + } +}); + +var _NineSlicePlane = require('./NineSlicePlane'); + +Object.defineProperty(exports, 'NineSlicePlane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NineSlicePlane).default; + } +}); + +var _Rope = require('./Rope'); + +Object.defineProperty(exports, 'Rope', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rope).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./Mesh":166,"./NineSlicePlane":167,"./Plane":168,"./Rope":169,"./canvas/CanvasMeshRenderer":170,"./webgl/MeshRenderer":172}],172:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var matrixIdentity = core.Matrix.IDENTITY; + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var MeshRenderer = function (_core$ObjectRenderer) { + _inherits(MeshRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function MeshRenderer(renderer) { + _classCallCheck(this, MeshRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + MeshRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n'); + }; + + /** + * renders mesh + * + * @param {PIXI.mesh.Mesh} mesh mesh instance + */ + + + MeshRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var gl = renderer.gl; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var glData = mesh._glDatas[renderer.CONTEXT_UID]; + + if (!glData) { + renderer.bindVao(null); + + glData = { + shader: this.shader, + vertexBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.vertices, gl.STREAM_DRAW), + uvBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.uvs, gl.STREAM_DRAW), + indexBuffer: _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, mesh.indices, gl.STATIC_DRAW), + // build the vao object that will render.. + vao: null, + dirty: mesh.dirty, + indexDirty: mesh.indexDirty + }; + + // build the vao object that will render.. + glData.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(glData.indexBuffer).addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0).addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); + + mesh._glDatas[renderer.CONTEXT_UID] = glData; + } + + renderer.bindVao(glData.vao); + + if (mesh.dirty !== glData.dirty) { + glData.dirty = mesh.dirty; + glData.uvBuffer.upload(mesh.uvs); + } + + if (mesh.indexDirty !== glData.indexDirty) { + glData.indexDirty = mesh.indexDirty; + glData.indexBuffer.upload(mesh.indices); + } + + glData.vertexBuffer.upload(mesh.vertices); + + renderer.bindShader(glData.shader); + + glData.shader.uniforms.uSampler = renderer.bindTexture(texture); + + renderer.state.setBlendMode(core.utils.correctBlendMode(mesh.blendMode, texture.baseTexture.premultipliedAlpha)); + + if (glData.shader.uniforms.uTransform) { + if (mesh.uploadUvTransform) { + glData.shader.uniforms.uTransform = mesh._uvTransform.mapCoord.toArray(true); + } else { + glData.shader.uniforms.uTransform = matrixIdentity.toArray(true); + } + } + glData.shader.uniforms.translationMatrix = mesh.worldTransform.toArray(true); + + glData.shader.uniforms.uColor = core.utils.premultiplyRgba(mesh.tintRgb, mesh.worldAlpha, glData.shader.uniforms.uColor, texture.baseTexture.premultipliedAlpha); + + var drawMode = mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + glData.vao.draw(drawMode, mesh.indices.length, 0); + }; + + return MeshRenderer; +}(core.ObjectRenderer); + +exports.default = MeshRenderer; + + +core.WebGLRenderer.registerPlugin('mesh', MeshRenderer); + +},{"../../core":65,"../Mesh":166,"path":23,"pixi-gl-core":12}],173:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _utils = require('../core/utils'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that advanced + * functionality will not work. ParticleContainer implements only the basic object transform (position, scale, rotation). + * Any other functionality like tinting, masking, etc will not work on sprites in this batch. + * + * It's extremely easy to use : + * + * ```js + * let container = new ParticleContainer(); + * + * for (let i = 0; i < 100; ++i) + * { + * let sprite = new PIXI.Sprite.fromImage("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be rendered at the speed of light. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.particles + */ +var ParticleContainer = function (_core$Container) { + _inherits(ParticleContainer, _core$Container); + + /** + * @param {number} [maxSize=15000] - The maximum number of particles that can be renderer by the container. + * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.scale=false] - When true, scale be uploaded and applied. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.alpha=false] - When true, alpha be uploaded and applied. + * @param {number} [batchSize=15000] - Number of particles per batch. + */ + function ParticleContainer() { + var maxSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1500; + var properties = arguments[1]; + var batchSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 16384; + + _classCallCheck(this, ParticleContainer); + + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + var maxBatchSize = 16384; + + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + + if (batchSize > maxSize) { + batchSize = maxSize; + } + + /** + * Set properties to be dynamic (true) / static (false) + * + * @member {boolean[]} + * @private + */ + _this._properties = [false, true, false, false, false]; + + /** + * @member {number} + * @private + */ + _this._maxSize = maxSize; + + /** + * @member {number} + * @private + */ + _this._batchSize = batchSize; + + /** + * @member {object} + * @private + */ + _this._glBuffers = {}; + + /** + * @member {number} + * @private + */ + _this._bufferToUpdate = 0; + + /** + * @member {boolean} + * + */ + _this.interactiveChildren = false; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` + * to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Used for canvas renderering. If true then the elements will be positioned at the + * nearest pixel. This provides a nice speed boost. + * + * @member {boolean} + * @default true; + */ + _this.roundPixels = true; + + /** + * The texture used to render the children. + * + * @readonly + * @member {BaseTexture} + */ + _this.baseTexture = null; + + _this.setProperties(properties); + + /** + * The tint applied to the container. + * This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = 0; + _this.tintRgb = new Float32Array(4); + _this.tint = 0xFFFFFF; + return _this; + } + + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * + * @param {object} properties - The properties to be uploaded + */ + + + ParticleContainer.prototype.setProperties = function setProperties(properties) { + if (properties) { + this._properties[0] = 'scale' in properties ? !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'alpha' in properties ? !!properties.alpha : this._properties[4]; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + ParticleContainer.prototype.updateTransform = function updateTransform() { + // TODO don't need to! + this.displayObjectUpdateTransform(); + // PIXI.Container.prototype.updateTransform.call( this ); + }; + + /** + * The tint applied to the container. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + ** IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * @member {number} + * @default 0xFFFFFF + */ + + + /** + * Renders the container using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer + */ + ParticleContainer.prototype.renderWebGL = function renderWebGL(renderer) { + var _this2 = this; + + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.hasLoaded) { + this.baseTexture.once('update', function () { + return _this2.onChildrenChange(0); + }); + } + } + + renderer.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + + /** + * Set the flag that static data should be updated to true + * + * @private + * @param {number} smallestChildIndex - The smallest child index + */ + + + ParticleContainer.prototype.onChildrenChange = function onChildrenChange(smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + + if (bufferIndex < this._bufferToUpdate) { + this._bufferToUpdate = bufferIndex; + } + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + + + ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var isRotated = true; + + var positionX = 0; + var positionY = 0; + + var finalWidth = 0; + var finalHeight = 0; + + var compositeOperation = renderer.blendModes[this.blendMode]; + + if (compositeOperation !== context.globalCompositeOperation) { + context.globalCompositeOperation = compositeOperation; + } + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i]; + + if (!child.visible) { + continue; + } + + var frame = child._texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) { + // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call + if (isRotated) { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx * renderer.resolution, transform.ty * renderer.resolution); + + isRotated = false; + } + + positionX = child.anchor.x * (-frame.width * child.scale.x) + child.position.x + 0.5; + positionY = child.anchor.y * (-frame.height * child.scale.y) + child.position.y + 0.5; + + finalWidth = frame.width * child.scale.x; + finalHeight = frame.height * child.scale.y; + } else { + if (!isRotated) { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + + if (renderer.roundPixels) { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution | 0, childTransform.ty * renderer.resolution | 0); + } else { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution, childTransform.ty * renderer.resolution); + } + + positionX = child.anchor.x * -frame.width + 0.5; + positionY = child.anchor.y * -frame.height + 0.5; + + finalWidth = frame.width; + finalHeight = frame.height; + } + + var resolution = child._texture.baseTexture.resolution; + + context.drawImage(child._texture.baseTexture.source, frame.x * resolution, frame.y * resolution, frame.width * resolution, frame.height * resolution, positionX * renderer.resolution, positionY * renderer.resolution, finalWidth * renderer.resolution, finalHeight * renderer.resolution); + } + }; + + /** + * Destroys the container + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + ParticleContainer.prototype.destroy = function destroy(options) { + _core$Container.prototype.destroy.call(this, options); + + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + } + + this._properties = null; + this._buffers = null; + }; + + _createClass(ParticleContainer, [{ + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + (0, _utils.hex2rgb)(value, this.tintRgb); + } + }]); + + return ParticleContainer; +}(core.Container); + +exports.default = ParticleContainer; + +},{"../core":65,"../core/utils":124}],174:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ParticleContainer = require('./ParticleContainer'); + +Object.defineProperty(exports, 'ParticleContainer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleContainer).default; + } +}); + +var _ParticleRenderer = require('./webgl/ParticleRenderer'); + +Object.defineProperty(exports, 'ParticleRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleRenderer).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./ParticleContainer":173,"./webgl/ParticleRenderer":176}],175:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + +/** + * The particle buffer manages the static and dynamic buffers for a particle container. + * + * @class + * @private + * @memberof PIXI + */ +var ParticleBuffer = function () { + /** + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(gl, properties, dynamicPropertyFlags, size) { + _classCallCheck(this, ParticleBuffer); + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * Size of a single vertex. + * + * @member {number} + */ + this.vertSize = 2; + + /** + * Size of a single vertex in bytes. + * + * @member {number} + */ + this.vertByteSize = this.vertSize * 4; + + /** + * The number of particles the buffer can hold + * + * @member {number} + */ + this.size = size; + + /** + * A list of the properties that are dynamic. + * + * @member {object[]} + */ + this.dynamicProperties = []; + + /** + * A list of the properties that are static. + * + * @member {object[]} + */ + this.staticProperties = []; + + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attribute: property.attribute, + size: property.size, + uploadFunction: property.uploadFunction, + offset: property.offset + }; + + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } else { + this.staticProperties.push(property); + } + } + + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + + this.initBuffers(); + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + ParticleBuffer.prototype.initBuffers = function initBuffers() { + var gl = this.gl; + var dynamicOffset = 0; + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(this.size); + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + this.dynamicStride = 0; + + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + + this.dynamicData = new Float32Array(this.size * this.dynamicStride * 4); + this.dynamicBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.dynamicData, gl.STREAM_DRAW); + + // static // + var staticOffset = 0; + + this.staticStride = 0; + + for (var _i = 0; _i < this.staticProperties.length; ++_i) { + var _property = this.staticProperties[_i]; + + _property.offset = staticOffset; + staticOffset += _property.size; + this.staticStride += _property.size; + } + + this.staticData = new Float32Array(this.size * this.staticStride * 4); + this.staticBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.staticData, gl.STATIC_DRAW); + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(this.indexBuffer); + + for (var _i2 = 0; _i2 < this.dynamicProperties.length; ++_i2) { + var _property2 = this.dynamicProperties[_i2]; + + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.FLOAT, false, this.dynamicStride * 4, _property2.offset * 4); + } + + for (var _i3 = 0; _i3 < this.staticProperties.length; ++_i3) { + var _property3 = this.staticProperties[_i3]; + + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.FLOAT, false, this.staticStride * 4, _property3.offset * 4); + } + }; + + /** + * Uploads the dynamic properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadDynamic = function uploadDynamic(children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + + property.uploadFunction(children, startIndex, amount, this.dynamicData, this.dynamicStride, property.offset); + } + + this.dynamicBuffer.upload(); + }; + + /** + * Uploads the static properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadStatic = function uploadStatic(children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + + property.uploadFunction(children, startIndex, amount, this.staticData, this.staticStride, property.offset); + } + + this.staticBuffer.upload(); + }; + + /** + * Destroys the ParticleBuffer. + * + */ + + + ParticleBuffer.prototype.destroy = function destroy() { + this.dynamicProperties = null; + this.dynamicData = null; + this.dynamicBuffer.destroy(); + + this.staticProperties = null; + this.staticData = null; + this.staticBuffer.destroy(); + }; + + return ParticleBuffer; +}(); + +exports.default = ParticleBuffer; + +},{"../../core/utils/createIndicesForQuads":122,"pixi-gl-core":12}],176:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _ParticleShader = require('./ParticleShader'); + +var _ParticleShader2 = _interopRequireDefault(_ParticleShader); + +var _ParticleBuffer = require('./ParticleBuffer'); + +var _ParticleBuffer2 = _interopRequireDefault(_ParticleBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + +/** + * + * @class + * @private + * @memberof PIXI + */ +var ParticleRenderer = function (_core$ObjectRenderer) { + _inherits(ParticleRenderer, _core$ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + _classCallCheck(this, ParticleRenderer); + + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; + + /** + * The default shader that is used if a sprite doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + + _this.indexBuffer = null; + + _this.properties = null; + + _this.tempMatrix = new core.Matrix(); + + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * When there is a WebGL context change + * + * @private + */ + + + ParticleRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + + // setup default shader + this.shader = new _ParticleShader2.default(gl); + + this.properties = [ + // verticesData + { + attribute: this.shader.attributes.aVertexPosition, + size: 2, + uploadFunction: this.uploadVertices, + offset: 0 + }, + // positionData + { + attribute: this.shader.attributes.aPositionCoord, + size: 2, + uploadFunction: this.uploadPosition, + offset: 0 + }, + // rotationData + { + attribute: this.shader.attributes.aRotation, + size: 1, + uploadFunction: this.uploadRotation, + offset: 0 + }, + // uvsData + { + attribute: this.shader.attributes.aTextureCoord, + size: 2, + uploadFunction: this.uploadUvs, + offset: 0 + }, + // alphaData + { + attribute: this.shader.attributes.aColor, + size: 1, + uploadFunction: this.uploadAlpha, + offset: 0 + }]; + }; + + /** + * Starts a new particle batch. + * + */ + + + ParticleRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + }; + + /** + * Renders the particle container object. + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + */ + + + ParticleRenderer.prototype.render = function render(container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var renderer = this.renderer; + var totalChildren = children.length; + + if (totalChildren === 0) { + return; + } else if (totalChildren > maxSize) { + totalChildren = maxSize; + } + + var buffers = container._glBuffers[renderer.CONTEXT_UID]; + + if (!buffers) { + buffers = container._glBuffers[renderer.CONTEXT_UID] = this.generateBuffers(container); + } + + var baseTexture = children[0]._texture.baseTexture; + + // if the uvs have not updated then no point rendering just yet! + this.renderer.setBlendMode(core.utils.correctBlendMode(container.blendMode, baseTexture.premultipliedAlpha)); + + var gl = renderer.gl; + + var m = container.worldTransform.copy(this.tempMatrix); + + m.prepend(renderer._activeRenderTarget.projectionMatrix); + + this.shader.uniforms.projectionMatrix = m.toArray(true); + + this.shader.uniforms.uColor = core.utils.premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, baseTexture.premultipliedAlpha); + + // make sure the texture is bound.. + this.shader.uniforms.uSampler = renderer.bindTexture(baseTexture); + + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = totalChildren - i; + + if (amount > batchSize) { + amount = batchSize; + } + + var buffer = buffers[j]; + + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + + // we only upload the static content when we have to! + if (container._bufferToUpdate === j) { + buffer.uploadStatic(children, i, amount); + container._bufferToUpdate = j + 1; + } + + // bind the buffer + renderer.bindVao(buffer.vao); + buffer.vao.draw(gl.TRIANGLES, amount * 6); + } + }; + + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer[]} The buffers + */ + + + ParticleRenderer.prototype.generateBuffers = function generateBuffers(container) { + var gl = this.renderer.gl; + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + for (var i = 0; i < size; i += batchSize) { + buffers.push(new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize)); + } + + return buffers; + }; + + /** + * Uploads the verticies. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their vertices uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadVertices = function uploadVertices(children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - sprite.anchor.x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - sprite.anchor.y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - sprite.anchor.x); + w1 = orig.width * -sprite.anchor.x; + + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + + array[offset + stride * 2] = w0 * sx; + array[offset + stride * 2 + 1] = h0 * sy; + + array[offset + stride * 3] = w1 * sx; + array[offset + stride * 3 + 1] = h0 * sy; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their positions uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadPosition = function uploadPosition(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + + array[offset + stride * 2] = spritePosition.x; + array[offset + stride * 2 + 1] = spritePosition.y; + + array[offset + stride * 3] = spritePosition.x; + array[offset + stride * 3 + 1] = spritePosition.y; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadRotation = function uploadRotation(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + stride * 2] = spriteRotation; + array[offset + stride * 3] = spriteRotation; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadUvs = function uploadUvs(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + + array[offset + stride * 2] = textureUvs.x2; + array[offset + stride * 2 + 1] = textureUvs.y2; + + array[offset + stride * 3] = textureUvs.x3; + array[offset + stride * 3 + 1] = textureUvs.y3; + + offset += stride * 4; + } else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + + array[offset + stride * 2] = 0; + array[offset + stride * 2 + 1] = 0; + + array[offset + stride * 3] = 0; + array[offset + stride * 3 + 1] = 0; + + offset += stride * 4; + } + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadAlpha = function uploadAlpha(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteAlpha = children[startIndex + i].alpha; + + array[offset] = spriteAlpha; + array[offset + stride] = spriteAlpha; + array[offset + stride * 2] = spriteAlpha; + array[offset + stride * 3] = spriteAlpha; + + offset += stride * 4; + } + }; + + /** + * Destroys the ParticleRenderer. + * + */ + + + ParticleRenderer.prototype.destroy = function destroy() { + if (this.renderer.gl) { + this.renderer.gl.deleteBuffer(this.indexBuffer); + } + + _core$ObjectRenderer.prototype.destroy.call(this); + + this.shader.destroy(); + + this.indices = null; + this.tempMatrix = null; + }; + + return ParticleRenderer; +}(core.ObjectRenderer); + +exports.default = ParticleRenderer; + + +core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + +},{"../../core":65,"./ParticleBuffer":175,"./ParticleShader":177}],177:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../core/Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI + */ +var ParticleShader = function (_Shader) { + _inherits(ParticleShader, _Shader); + + /** + * @param {PIXI.Shader} gl - The webgl shader manager this shader works for. + */ + function ParticleShader(gl) { + _classCallCheck(this, ParticleShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'attribute float aColor;', 'attribute vec2 aPositionCoord;', 'attribute vec2 aScale;', 'attribute float aRotation;', 'uniform mat3 projectionMatrix;', 'varying vec2 vTextureCoord;', 'varying float vColor;', 'void main(void){', ' vec2 v = aVertexPosition;', ' v.x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);', ' v.y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);', ' v = v + aPositionCoord;', ' gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = aColor;', '}'].join('\n'), + // hello + ['varying vec2 vTextureCoord;', 'varying float vColor;', 'uniform sampler2D uSampler;', 'uniform vec4 uColor;', 'void main(void){', ' vec4 color = texture2D(uSampler, vTextureCoord) * vColor * uColor;', ' if (color.a == 0.0) discard;', ' gl_FragColor = color;', '}'].join('\n'))); + } + + return ParticleShader; +}(_Shader3.default); + +exports.default = ParticleShader; + +},{"../../core/Shader":44}],178:[function(require,module,exports){ +"use strict"; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + +if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + + if (x === 0 || isNaN(x)) { + return x; + } + + return x > 0 ? 1 : -1; + }; +} + +},{}],179:[function(require,module,exports){ +'use strict'; + +var _objectAssign = require('object-assign'); + +var _objectAssign2 = _interopRequireDefault(_objectAssign); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +if (!Object.assign) { + Object.assign = _objectAssign2.default; +} // References: +// https://github.com/sindresorhus/object-assign +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + +},{"object-assign":5}],180:[function(require,module,exports){ +'use strict'; + +require('./Object.assign'); + +require('./requestAnimationFrame'); + +require('./Math.sign'); + +if (!window.ArrayBuffer) { + window.ArrayBuffer = Array; +} + +if (!window.Float32Array) { + window.Float32Array = Array; +} + +if (!window.Uint32Array) { + window.Uint32Array = Array; +} + +if (!window.Uint16Array) { + window.Uint16Array = Array; +} + +},{"./Math.sign":178,"./Object.assign":179,"./requestAnimationFrame":181}],181:[function(require,module,exports){ +(function (global){ +'use strict'; + +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + +// Expected to be used with Browserfiy +// Browserify automatically detects the use of `global` and passes the +// correct reference of `global`, `self`, and finally `window` + +var ONE_FRAME_TIME = 16; + +// Date.now +if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; +} + +// performance.now +if (!(global.performance && global.performance.now)) { + var startTime = Date.now(); + + if (!global.performance) { + global.performance = {}; + } + + global.performance.now = function () { + return Date.now() - startTime; + }; +} + +// requestAnimationFrame +var lastTime = Date.now(); +var vendors = ['ms', 'moz', 'webkit', 'o']; + +for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { + var p = vendors[x]; + + global.requestAnimationFrame = global[p + 'RequestAnimationFrame']; + global.cancelAnimationFrame = global[p + 'CancelAnimationFrame'] || global[p + 'CancelRequestAnimationFrame']; +} + +if (!global.requestAnimationFrame) { + global.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + 'is not a function'); + } + + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + + if (delay < 0) { + delay = 0; + } + + lastTime = currentTime; + + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} + +if (!global.cancelAnimationFrame) { + global.cancelAnimationFrame = function (id) { + return clearTimeout(id); + }; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],182:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CountLimiter = require('./limiters/CountLimiter'); + +var _CountLimiter2 = _interopRequireDefault(_CountLimiter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SharedTicker = core.ticker.shared; + +/** + * Default number of uploads per frame using prepare plugin. + * + * @static + * @memberof PIXI.settings + * @name UPLOADS_PER_FRAME + * @type {number} + * @default 4 + */ +core.settings.UPLOADS_PER_FRAME = 4; + +/** + * The prepare manager provides functionality to upload content to the GPU. BasePrepare handles + * basic queuing functionality and is extended by {@link PIXI.prepare.WebGLPrepare} and {@link PIXI.prepare.CanvasPrepare} + * to provide preparation capabilities specific to their respective renderers. + * + * @example + * // Create a sprite + * const sprite = new PIXI.Sprite.fromImage('something.png'); + * + * // Load object into GPU + * app.renderer.plugins.prepare.upload(sprite, () => { + * + * //Texture(s) has been uploaded to GPU + * app.stage.addChild(sprite); + * + * }) + * + * @abstract + * @class + * @memberof PIXI.prepare + */ + +var BasePrepare = function () { + /** + * @param {PIXI.SystemRenderer} renderer - A reference to the current renderer + */ + function BasePrepare(renderer) { + var _this = this; + + _classCallCheck(this, BasePrepare); + + /** + * The limiter to be used to control how quickly items are prepared. + * @type {PIXI.prepare.CountLimiter|PIXI.prepare.TimeLimiter} + */ + this.limiter = new _CountLimiter2.default(core.settings.UPLOADS_PER_FRAME); + + /** + * Reference to the renderer. + * @type {PIXI.SystemRenderer} + * @protected + */ + this.renderer = renderer; + + /** + * The only real difference between CanvasPrepare and WebGLPrepare is what they pass + * to upload hooks. That different parameter is stored here. + * @type {PIXI.prepare.CanvasPrepare|PIXI.WebGLRenderer} + * @protected + */ + this.uploadHookHelper = null; + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + /** + * 'bound' call for prepareItems(). + * @type {Function} + * @private + */ + this.delayedTick = function () { + // unlikely, but in case we were destroyed between tick() and delayedTick() + if (!_this.queue) { + return; + } + _this.prepareItems(); + }; + + // hooks to find the correct texture + this.registerFindHook(findText); + this.registerFindHook(findTextStyle); + this.registerFindHook(findMultipleBaseTextures); + this.registerFindHook(findBaseTexture); + this.registerFindHook(findTexture); + + // upload hooks + this.registerUploadHook(drawText); + this.registerUploadHook(calculateTextStyle); + } + + /** + * Upload all the textures and graphics to the GPU. + * + * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item - + * Either the container or display object to search for items to upload, the items to upload themselves, + * or the callback function, if items have been added using `prepare.add`. + * @param {Function} [done] - Optional callback when all queued uploads have completed + */ + + + BasePrepare.prototype.upload = function upload(item, done) { + if (typeof item === 'function') { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) { + if (done) { + this.completes.push(done); + } + + if (!this.ticking) { + this.ticking = true; + SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); + } + } else if (done) { + done(); + } + }; + + /** + * Handle tick update + * + * @private + */ + + + BasePrepare.prototype.tick = function tick() { + setTimeout(this.delayedTick, 0); + }; + + /** + * Actually prepare items. This is handled outside of the tick because it will take a while + * and we do NOT want to block the current animation frame from rendering. + * + * @private + */ + + + BasePrepare.prototype.prepareItems = function prepareItems() { + this.limiter.beginFrame(); + // Upload the graphics + while (this.queue.length && this.limiter.allowedToUpload()) { + var item = this.queue[0]; + var uploaded = false; + + if (item && !item._destroyed) { + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.uploadHookHelper, item)) { + this.queue.shift(); + uploaded = true; + break; + } + } + } + + if (!uploaded) { + this.queue.shift(); + } + } + + // We're finished + if (!this.queue.length) { + this.ticking = false; + + var completes = this.completes.slice(0); + + this.completes.length = 0; + + for (var _i = 0, _len = completes.length; _i < _len; _i++) { + completes[_i](); + } + } else { + // if we are not finished, on the next rAF do this again + SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); + } + }; + + /** + * Adds hooks for finding items. + * + * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.registerFindHook = function registerFindHook(addHook) { + if (addHook) { + this.addHooks.push(addHook); + } + + return this; + }; + + /** + * Adds hooks for uploading items. + * + * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.registerUploadHook = function registerUploadHook(uploadHook) { + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + + return this; + }; + + /** + * Manually add an item to the uploading queue. + * + * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to + * add to the queue + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.add = function add(item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) { + for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { + this.add(item.children[_i2]); + } + } + + return this; + }; + + /** + * Destroys the plugin, don't use after this. + * + */ + + + BasePrepare.prototype.destroy = function destroy() { + if (this.ticking) { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.limiter = null; + this.uploadHookHelper = null; + }; + + return BasePrepare; +}(); + +/** + * Built-in hook to find multiple textures from objects like AnimatedSprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ + + +exports.default = BasePrepare; +function findMultipleBaseTextures(item, queue) { + var result = false; + + // Objects with mutliple textures + if (item && item._textures && item._textures.length) { + for (var i = 0; i < item._textures.length; i++) { + if (item._textures[i] instanceof core.Texture) { + var baseTexture = item._textures[i].baseTexture; + + if (queue.indexOf(baseTexture) === -1) { + queue.push(baseTexture); + result = true; + } + } + } + } + + return result; +} + +/** + * Built-in hook to find BaseTextures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTexture(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findTexture(item, queue) { + if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to draw PIXI.Text to its texture. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function drawText(helper, item) { + if (item instanceof core.Text) { + // updating text will return early if it is not dirty + item.updateText(true); + + return true; + } + + return false; +} + +/** + * Built-in hook to calculate a text style for a PIXI.Text object. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function calculateTextStyle(helper, item) { + if (item instanceof core.TextStyle) { + var font = item.toFontString(); + + core.TextMetrics.measureFont(font); + + return true; + } + + return false; +} + +/** + * Built-in hook to find Text objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Text object was found. + */ +function findText(item, queue) { + if (item instanceof core.Text) { + // push the text style to prepare it - this can be really expensive + if (queue.indexOf(item.style) === -1) { + queue.push(item.style); + } + // also push the text object so that we can render it (to canvas/texture) if needed + if (queue.indexOf(item) === -1) { + queue.push(item); + } + // also push the Text's texture for upload to GPU + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find TextStyle objects. + * + * @private + * @param {PIXI.TextStyle} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.TextStyle object was found. + */ +function findTextStyle(item, queue) { + if (item instanceof core.TextStyle) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +},{"../core":65,"./limiters/CountLimiter":185}],183:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CANVAS_START_SIZE = 16; + +/** + * The prepare manager provides functionality to upload content to the GPU + * This cannot be done directly for Canvas like in WebGL, but the effect can be achieved by drawing + * textures to an offline canvas. + * This draw call will force the texture to be moved onto the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ + +var CanvasPrepare = function (_BasePrepare) { + _inherits(CanvasPrepare, _BasePrepare); + + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasPrepare(renderer) { + _classCallCheck(this, CanvasPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this; + + /** + * An offline canvas to render textures to + * @type {HTMLCanvasElement} + * @private + */ + _this.canvas = document.createElement('canvas'); + _this.canvas.width = CANVAS_START_SIZE; + _this.canvas.height = CANVAS_START_SIZE; + + /** + * The context to the canvas + * @type {CanvasRenderingContext2D} + * @private + */ + _this.ctx = _this.canvas.getContext('2d'); + + // Add textures to upload + _this.registerUploadHook(uploadBaseTextures); + return _this; + } + + /** + * Destroys the plugin, don't use after this. + * + */ + + + CanvasPrepare.prototype.destroy = function destroy() { + _BasePrepare.prototype.destroy.call(this); + this.ctx = null; + this.canvas = null; + }; + + return CanvasPrepare; +}(_BasePrepare3.default); + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {*} prepare - Instance of CanvasPrepare + * @param {*} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = CanvasPrepare; +function uploadBaseTextures(prepare, item) { + if (item instanceof core.BaseTexture) { + var image = item.source; + + // Sometimes images (like atlas images) report a size of zero, causing errors on windows phone. + // So if the width or height is equal to zero then use the canvas size + // Otherwise use whatever is smaller, the image dimensions or the canvas dimensions. + var imageWidth = image.width === 0 ? prepare.canvas.width : Math.min(prepare.canvas.width, image.width); + var imageHeight = image.height === 0 ? prepare.canvas.height : Math.min(prepare.canvas.height, image.height); + + // Only a small subsections is required to be drawn to have the whole texture uploaded to the GPU + // A smaller draw can be faster. + prepare.ctx.drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, prepare.canvas.width, prepare.canvas.height); + + return true; + } + + return false; +} + +core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); + +},{"../../core":65,"../BasePrepare":182}],184:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLPrepare = require('./webgl/WebGLPrepare'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLPrepare).default; + } +}); + +var _CanvasPrepare = require('./canvas/CanvasPrepare'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasPrepare).default; + } +}); + +var _BasePrepare = require('./BasePrepare'); + +Object.defineProperty(exports, 'BasePrepare', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BasePrepare).default; + } +}); + +var _CountLimiter = require('./limiters/CountLimiter'); + +Object.defineProperty(exports, 'CountLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CountLimiter).default; + } +}); + +var _TimeLimiter = require('./limiters/TimeLimiter'); + +Object.defineProperty(exports, 'TimeLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TimeLimiter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./BasePrepare":182,"./canvas/CanvasPrepare":183,"./limiters/CountLimiter":185,"./limiters/TimeLimiter":186,"./webgl/WebGLPrepare":187}],185:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * CountLimiter limits the number of items handled by a {@link PIXI.prepare.BasePrepare} to a specified + * number of items per frame. + * + * @class + * @memberof PIXI + */ +var CountLimiter = function () { + /** + * @param {number} maxItemsPerFrame - The maximum number of items that can be prepared each frame. + */ + function CountLimiter(maxItemsPerFrame) { + _classCallCheck(this, CountLimiter); + + /** + * The maximum number of items that can be prepared each frame. + * @private + */ + this.maxItemsPerFrame = maxItemsPerFrame; + /** + * The number of items that can be prepared in the current frame. + * @type {number} + * @private + */ + this.itemsLeft = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + CountLimiter.prototype.beginFrame = function beginFrame() { + this.itemsLeft = this.maxItemsPerFrame; + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + CountLimiter.prototype.allowedToUpload = function allowedToUpload() { + return this.itemsLeft-- > 0; + }; + + return CountLimiter; +}(); + +exports.default = CountLimiter; + +},{}],186:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of milliseconds per frame. + * + * @class + * @memberof PIXI + */ +var TimeLimiter = function () { + /** + * @param {number} maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. + */ + function TimeLimiter(maxMilliseconds) { + _classCallCheck(this, TimeLimiter); + + /** + * The maximum milliseconds that can be spent preparing items each frame. + * @private + */ + this.maxMilliseconds = maxMilliseconds; + /** + * The start time of the current frame. + * @type {number} + * @private + */ + this.frameStart = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + TimeLimiter.prototype.beginFrame = function beginFrame() { + this.frameStart = Date.now(); + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + TimeLimiter.prototype.allowedToUpload = function allowedToUpload() { + return Date.now() - this.frameStart < this.maxMilliseconds; + }; + + return TimeLimiter; +}(); + +exports.default = TimeLimiter; + +},{}],187:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The prepare manager provides functionality to upload content to the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ +var WebGLPrepare = function (_BasePrepare) { + _inherits(WebGLPrepare, _BasePrepare); + + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLPrepare(renderer) { + _classCallCheck(this, WebGLPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this.renderer; + + // Add textures and graphics to upload + _this.registerFindHook(findGraphics); + _this.registerUploadHook(uploadBaseTextures); + _this.registerUploadHook(uploadGraphics); + return _this; + } + + return WebGLPrepare; +}(_BasePrepare3.default); +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = WebGLPrepare; +function uploadBaseTextures(renderer, item) { + if (item instanceof core.BaseTexture) { + // if the texture already has a GL texture, then the texture has been prepared or rendered + // before now. If the texture changed, then the changer should be calling texture.update() which + // reuploads the texture without need for preparing it again + if (!item._glTextures[renderer.CONTEXT_UID]) { + renderer.textureManager.updateTexture(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to upload PIXI.Graphics to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadGraphics(renderer, item) { + if (item instanceof core.Graphics) { + // if the item is not dirty and already has webgl data, then it got prepared or rendered + // before now and we shouldn't waste time updating it again + if (item.dirty || item.clearDirty || !item._webGL[renderer.plugins.graphics.CONTEXT_UID]) { + renderer.plugins.graphics.updateGraphics(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find graphics. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Graphics object was found. + */ +function findGraphics(item, queue) { + if (item instanceof core.Graphics) { + queue.push(item); + + return true; + } + + return false; +} + +core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); + +},{"../../core":65,"../BasePrepare":182}],188:[function(require,module,exports){ +(function (global){ +'use strict'; + +exports.__esModule = true; +exports.loader = exports.prepare = exports.particles = exports.mesh = exports.loaders = exports.interaction = exports.filters = exports.extras = exports.extract = exports.accessibility = undefined; + +var _polyfill = require('./polyfill'); + +Object.keys(_polyfill).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _polyfill[key]; + } + }); +}); + +var _core = require('./core'); + +Object.keys(_core).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _core[key]; + } + }); +}); + +var _deprecation = require('./deprecation'); + +var _deprecation2 = _interopRequireDefault(_deprecation); + +var _accessibility = require('./accessibility'); + +var accessibility = _interopRequireWildcard(_accessibility); + +var _extract = require('./extract'); + +var extract = _interopRequireWildcard(_extract); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// export core +_core.utils.mixins.performMixins(); + +/** + * Alias for {@link PIXI.loaders.shared}. + * @name loader + * @memberof PIXI + * @type {PIXI.loader.Loader} + */ + + +// handle mixins now, after all code has been added, including deprecation + + +// export libs +// import polyfills. Done as an export to make sure polyfills are imported first +var loader = loaders.shared || null; + +exports.accessibility = accessibility; +exports.extract = extract; +exports.extras = extras; +exports.filters = filters; +exports.interaction = interaction; +exports.loaders = loaders; +exports.mesh = mesh; +exports.particles = particles; +exports.prepare = prepare; +exports.loader = loader; + +// Apply the deprecations + +if (typeof _deprecation2.default === 'function') { + (0, _deprecation2.default)(exports); +} + +// Always export PixiJS globally. +global.PIXI = exports; // eslint-disable-line + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"./accessibility":42,"./core":65,"./deprecation":130,"./extract":132,"./extras":141,"./filters":152,"./interaction":159,"./loaders":162,"./mesh":171,"./particles":174,"./polyfill":180,"./prepare":184}]},{},[188])(188) +}); + + +//# sourceMappingURL=pixi.js.map diff --git a/js/pixi/4.5.4/pixi.min.js b/js/pixi/4.5.4/pixi.min.js new file mode 100644 index 0000000..4a6e9ff --- /dev/null +++ b/js/pixi/4.5.4/pixi.min.js @@ -0,0 +1,22 @@ +/*! + * pixi.js - v4.5.4 + * Compiled Mon, 24 Jul 2017 18:13:36 UTC + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.PIXI=t()}}(function(){var t;return function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var h=new Error("Cannot find module '"+s+"'");throw h.code="MODULE_NOT_FOUND",h}var l=r[s]={exports:{}};e[s][0].call(l.exports,function(t){var r=e[s][1][t];return i(r||t)},l,l.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s0)-(t<0)},r.abs=function(t){var e=t>>31;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,(e|=r)|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,16843009*((t=(858993459&t)+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var i=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|i[t>>>16&255]<<8|i[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),(t=65535&(t|t>>>16))<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),(t=1023&(t|t>>>16))<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],2:[function(t,e,r){"use strict";function n(t,e,r){r=r||2;var n=e&&e.length,o=n?e[0]*r:t.length,a=i(t,0,o,r,!0),u=[];if(!a)return u;var h,l,d,f,p,v,y;if(n&&(a=c(t,e,a,r)),t.length>80*r){h=d=t[0],l=f=t[1];for(var g=r;gd&&(d=p),v>f&&(f=v);y=Math.max(d-h,f-l)}return s(a,u,r,h,l,y),u}function i(t,e,r,n,i){var o,s;if(i===A(t,e,r,n)>0)for(o=e;o=e;o-=n)s=M(o,t[o],t[o+1],s);return s&&T(s,s.next)&&(C(s),s=s.next),s}function o(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!T(n,n.next)&&0!==x(n.prev,n,n.next))n=n.next;else{if(C(n),(n=e=n.prev)===n.next)return null;r=!0}}while(r||n!==e);return e}function s(t,e,r,n,i,c,d){if(t){!d&&c&&v(t,n,i,c);for(var f,p,y=t;t.prev!==t.next;)if(f=t.prev,p=t.next,c?u(t,n,i,c):a(t))e.push(f.i/r),e.push(t.i/r),e.push(p.i/r),C(t),t=p.next,y=p.next;else if((t=p)===y){d?1===d?(t=h(t,e,r),s(t,e,r,n,i,c,2)):2===d&&l(t,e,r,n,i,c):s(o(t),e,r,n,i,c,1);break}}}function a(t){var e=t.prev,r=t,n=t.next;if(x(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(_(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&x(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function u(t,e,r,n){var i=t.prev,o=t,s=t.next;if(x(i,o,s)>=0)return!1;for(var a=i.xo.x?i.x>s.x?i.x:s.x:o.x>s.x?o.x:s.x,l=i.y>o.y?i.y>s.y?i.y:s.y:o.y>s.y?o.y:s.y,c=g(a,u,e,r,n),d=g(h,l,e,r,n),f=t.nextZ;f&&f.z<=d;){if(f!==t.prev&&f!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,f.x,f.y)&&x(f.prev,f,f.next)>=0)return!1;f=f.nextZ}for(f=t.prevZ;f&&f.z>=c;){if(f!==t.prev&&f!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,f.x,f.y)&&x(f.prev,f,f.next)>=0)return!1;f=f.prevZ}return!0}function h(t,e,r){var n=t;do{var i=n.prev,o=n.next.next;!T(i,o)&&w(i,n,n.next,o)&&S(i,o)&&S(o,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(o.i/r),C(n),C(n.next),n=t=o),n=n.next}while(n!==t);return n}function l(t,e,r,n,i,a){var u=t;do{for(var h=u.next.next;h!==u.prev;){if(u.i!==h.i&&b(u,h)){var l=P(u,h);return u=o(u,u.next),l=o(l,l.next),s(u,e,r,n,i,a),void s(l,e,r,n,i,a)}h=h.next}u=u.next}while(u!==t)}function c(t,e,r,n){var s,a,u,h,l,c=[];for(s=0,a=e.length;s=n.next.y){var a=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=i&&a>s){if(s=a,a===i){if(o===n.y)return n;if(o===n.next.y)return n.next}r=n.x=n.x&&n.x>=l&&_(or.x)&&S(n,t)&&(r=n,d=u),n=n.next;return r}function v(t,e,r,n){var i=t;do{null===i.z&&(i.z=g(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,y(i)}function y(t){var e,r,n,i,o,s,a,u,h=1;do{for(r=t,t=null,o=null,s=0;r;){for(s++,n=r,a=0,e=0;e0||u>0&&n;)0===a?(i=n,n=n.nextZ,u--):0!==u&&n?r.z<=n.z?(i=r,r=r.nextZ,a--):(i=n,n=n.nextZ,u--):(i=r,r=r.nextZ,a--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;r=n}o.nextZ=null,h*=2}while(s>1);return t}function g(t,e,r,n,i){return t=32767*(t-r)/i,e=32767*(e-n)/i,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1}function m(t){var e=t,r=t;do{e.x=0&&(t-s)*(n-a)-(r-s)*(e-a)>=0&&(r-s)*(o-a)-(i-s)*(n-a)>=0}function b(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!E(t,e)&&S(t,e)&&S(e,t)&&O(t,e)}function x(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function T(t,e){return t.x===e.x&&t.y===e.y}function w(t,e,r,n){return!!(T(t,e)&&T(r,n)||T(t,n)&&T(r,e))||x(t,e,r)>0!=x(t,e,n)>0&&x(r,n,t)>0!=x(r,n,e)>0}function E(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&w(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}function S(t,e){return x(t.prev,t,t.next)<0?x(t,e,t.next)>=0&&x(t,t.prev,e)>=0:x(t,e,t.prev)<0||x(t,t.next,e)<0}function O(t,e){var r=t,n=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{r.y>o!=r.next.y>o&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}function P(t,e){var r=new R(t.i,t.x,t.y),n=new R(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function M(t,e,r,n){var i=new R(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function C(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function R(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(t,e,r,n){for(var i=0,o=e,s=r-n;o0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],3:[function(t,e,r){"use strict";function n(){}function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function o(){this._events=new n,this._eventsCount=0}var s=Object.prototype.hasOwnProperty,a="~";Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(a=!1)),o.prototype.eventNames=function(){var t,e,r=[];if(0===this._eventsCount)return r;for(e in t=this._events)s.call(t,e)&&r.push(a?e.slice(1):e);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t,e){var r=a?a+t:t,n=this._events[r];if(e)return!!n;if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i=t.byteLength?n.bufferSubData(this.type,e,t):n.bufferData(this.type,t,this.drawType),this.data=t},i.prototype.bind=function(){this.gl.bindBuffer(this.type,this.buffer)},i.createVertexBuffer=function(t,e,r){return new i(t,t.ARRAY_BUFFER,e,r)},i.createIndexBuffer=function(t,e,r){return new i(t,t.ELEMENT_ARRAY_BUFFER,e,r)},i.create=function(t,e,r,n){return new i(t,e,r,n)},i.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer)},e.exports=i},{}],7:[function(t,e,r){var n=t("./GLTexture"),i=function(t,e,r){this.gl=t,this.framebuffer=t.createFramebuffer(),this.stencil=null,this.texture=null,this.width=e||100,this.height=r||100};i.prototype.enableTexture=function(t){var e=this.gl;this.texture=t||new n(e),this.texture.bind(),this.bind(),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0)},i.prototype.enableStencil=function(){if(!this.stencil){var t=this.gl;this.stencil=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.stencil),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.stencil),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,this.width,this.height)}},i.prototype.clear=function(t,e,r,n){this.bind();var i=this.gl;i.clearColor(t,e,r,n),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT)},i.prototype.bind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer)},i.prototype.unbind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)},i.prototype.resize=function(t,e){var r=this.gl;this.width=t,this.height=e,this.texture&&this.texture.uploadData(null,t,e),this.stencil&&(r.bindRenderbuffer(r.RENDERBUFFER,this.stencil),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e))},i.prototype.destroy=function(){var t=this.gl;this.texture&&this.texture.destroy(),t.deleteFramebuffer(this.framebuffer),this.gl=null,this.stencil=null,this.texture=null},i.createRGBA=function(t,e,r,o){var s=n.fromData(t,null,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},i.createFloat32=function(t,e,r,o){var s=new n.fromData(t,o,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},e.exports=i},{"./GLTexture":9}],8:[function(t,e,r){var n=t("./shader/compileProgram"),i=t("./shader/extractAttributes"),o=t("./shader/extractUniforms"),s=t("./shader/setPrecision"),a=t("./shader/generateUniformAccessObject"),u=function(t,e,r,u,h){this.gl=t,u&&(e=s(e,u),r=s(r,u)),this.program=n(t,e,r,h),this.attributes=i(t,this.program),this.uniformData=o(t,this.program),this.uniforms=a(t,this.uniformData)};u.prototype.bind=function(){this.gl.useProgram(this.program)},u.prototype.destroy=function(){this.attributes=null,this.uniformData=null,this.uniforms=null,this.gl.deleteProgram(this.program)},e.exports=u},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18,"./shader/setPrecision":22}],9:[function(t,e,r){var n=function(t,e,r,n,i){this.gl=t,this.texture=t.createTexture(),this.mipmap=!1,this.premultiplyAlpha=!1,this.width=e||-1,this.height=r||-1,this.format=n||t.RGBA,this.type=i||t.UNSIGNED_BYTE};n.prototype.upload=function(t){this.bind();var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var r=t.videoWidth||t.width,n=t.videoHeight||t.height;n!==this.height||r!==this.width?e.texImage2D(e.TEXTURE_2D,0,this.format,this.format,this.type,t):e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.format,this.type,t),this.width=r,this.height=n};var i=!1;n.prototype.uploadData=function(t,e,r){this.bind();var n=this.gl;if(t instanceof Float32Array){if(!i){if(!n.getExtension("OES_texture_float"))throw new Error("floating point textures not available");i=!0}this.type=n.FLOAT}else this.type=this.type||n.UNSIGNED_BYTE;n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),e!==this.width||r!==this.height?n.texImage2D(n.TEXTURE_2D,0,this.format,e,r,0,this.format,this.type,t||null):n.texSubImage2D(n.TEXTURE_2D,0,0,0,e,r,this.format,this.type,t||null),this.width=e,this.height=r},n.prototype.bind=function(t){var e=this.gl;void 0!==t&&e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,this.texture)},n.prototype.unbind=function(){var t=this.gl;t.bindTexture(t.TEXTURE_2D,null)},n.prototype.minFilter=function(t){var e=this.gl;this.bind(),this.mipmap?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.magFilter=function(t){var e=this.gl;this.bind(),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.enableMipmap=function(){var t=this.gl;this.bind(),this.mipmap=!0,t.generateMipmap(t.TEXTURE_2D)},n.prototype.enableLinearScaling=function(){this.minFilter(!0),this.magFilter(!0)},n.prototype.enableNearestScaling=function(){this.minFilter(!1),this.magFilter(!1)},n.prototype.enableWrapClamp=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)},n.prototype.enableWrapRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT)},n.prototype.enableWrapMirrorRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.MIRRORED_REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.MIRRORED_REPEAT)},n.prototype.destroy=function(){this.gl.deleteTexture(this.texture)},n.fromSource=function(t,e,r){var i=new n(t);return i.premultiplyAlpha=r||!1,i.upload(e),i},n.fromData=function(t,e,r,i){var o=new n(t);return o.uploadData(e,r,i),o},e.exports=n},{}],10:[function(t,e,r){function n(t,e){if(this.nativeVaoExtension=null,n.FORCE_NATIVE||(this.nativeVaoExtension=t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object")),this.nativeState=e,this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var r=t.getParameter(t.MAX_VERTEX_ATTRIBS);this.nativeState={tempAttribState:new Array(r),attribState:new Array(r)}}this.gl=t,this.attributes=[],this.indexBuffer=null,this.dirty=!1}var i=t("./setVertexAttribArrays");n.prototype.constructor=n,e.exports=n,n.FORCE_NATIVE=!1,n.prototype.bind=function(){return this.nativeVao?(this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao),this.dirty&&(this.dirty=!1,this.activate())):this.activate(),this},n.prototype.unbind=function(){return this.nativeVao&&this.nativeVaoExtension.bindVertexArrayOES(null),this},n.prototype.activate=function(){for(var t=this.gl,e=null,r=0;r=0;n--){var i=t[n];"."===i?t.splice(n,1):".."===i?(t.splice(n,1),r++):r&&(t.splice(n,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}function n(t,e){if(t.filter)return t.filter(e);for(var r=[],n=0;n=-1&&!i;o--){var s=o>=0?arguments[o]:t.cwd();if("string"!=typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(r=s+"/"+r,i="/"===s.charAt(0))}return r=e(n(r.split("/"),function(t){return!!t}),!i).join("/"),(i?"/":"")+r||"."},r.normalize=function(t){var i=r.isAbsolute(t),o="/"===s(t,-1);return t=e(n(t.split("/"),function(t){return!!t}),!i).join("/"),t||i||(t="."),t&&o&&(t+="/"),(i?"/":"")+t},r.isAbsolute=function(t){return"/"===t.charAt(0)},r.join=function(){var t=Array.prototype.slice.call(arguments,0);return r.normalize(n(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},r.relative=function(t,e){function n(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=r.resolve(t).substr(1),e=r.resolve(e).substr(1);for(var i=n(t.split("/")),o=n(e.split("/")),s=Math.min(i.length,o.length),a=s,u=0;u1)for(var r=1;r1&&(n=r[0]+"@",t=r[1]),t=t.replace(D,"."),n+s(t.split("."),e).join(".")}function u(t){for(var e,r,n=[],i=0,o=t.length;i=55296&&e<=56319&&i65535&&(t-=65536,e+=B(t>>>10&1023|55296),t=56320|1023&t),e+=B(t)}).join("")}function l(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:w}function c(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function d(t,e,r){var n=0;for(t=r?F(t/P):t>>1,t+=F(t/e);t>N*S>>1;n+=w)t=F(t/N);return F(n+(N+1)*t/(t+O))}function f(t){var e,r,n,i,s,a,u,c,f,p,v=[],y=t.length,g=0,m=C,_=M;for(r=t.lastIndexOf(R),r<0&&(r=0),n=0;n=128&&o("not-basic"),v.push(t.charCodeAt(n));for(i=r>0?r+1:0;i=y&&o("invalid-input"),c=l(t.charCodeAt(i++)),(c>=w||c>F((T-g)/a))&&o("overflow"),g+=c*a,f=u<=_?E:u>=_+S?S:u-_,!(cF(T/p)&&o("overflow"),a*=p;e=v.length+1,_=d(g-s,e,0==s),F(g/e)>T-m&&o("overflow"),m+=F(g/e),g%=e,v.splice(g++,0,m)}return h(v)}function p(t){var e,r,n,i,s,a,h,l,f,p,v,y,g,m,_,b=[];for(t=u(t),y=t.length,e=C,r=0,s=M,a=0;a=e&&vF((T-r)/g)&&o("overflow"),r+=(h-e)*g,e=h,a=0;aT&&o("overflow"),v==e){for(l=r,f=w;p=f<=s?E:f>=s+S?S:f-s,!(l= 0x80 (not a basic code point)","invalid-input":"Invalid input"},N=w-E,F=Math.floor,B=String.fromCharCode;if(b={version:"1.4.1",ucs2:{decode:u,encode:h},decode:f,encode:p,toASCII:y,toUnicode:v},"function"==typeof t&&"object"==typeof t.amd&&t.amd)t("punycode",function(){return b});else if(g&&m)if(r.exports==g)m.exports=b;else for(x in b)b.hasOwnProperty(x)&&(g[x]=b[x]);else i.punycode=b}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],26:[function(t,e,r){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,r,o){e=e||"&",r=r||"=";var s={};if("string"!=typeof t||0===t.length)return s;var a=/\+/g;t=t.split(e);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var h=t.length;u>0&&h>u&&(h=u);for(var l=0;l=0?(c=v.substr(0,y),d=v.substr(y+1)):(c=v,d=""),f=decodeURIComponent(c),p=decodeURIComponent(d),n(s,f)?i(s[f])?s[f].push(p):s[f]=[s[f],p]:s[f]=p}return s};var i=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],27:[function(t,e,r){"use strict";function n(t,e){if(t.map)return t.map(e);for(var r=[],n=0;n",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(f),v=["'"].concat(p),y=["%","/","?",";","#"].concat(v),g=["/","?","#"],m=/^[+a-z0-9A-Z_-]{0,63}$/,_=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,b={javascript:!0,"javascript:":!0},x={javascript:!0,"javascript:":!0},T={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},w=t("querystring");n.prototype.parse=function(t,e,r){if(!h.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var n=t.indexOf("?"),i=-1!==n&&n127?L+="x":L+=D[N];if(!L.match(m)){var B=A.slice(0,O),k=A.slice(O+1),j=D.match(_);j&&(B.push(j[1]),k.unshift(j[2])),k.length&&(a="/"+k.join(".")+a),this.hostname=B.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),R||(this.hostname=u.toASCII(this.hostname));var U=this.port?":"+this.port:"",X=this.hostname||"";this.host=X+U,this.href+=this.host,R&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==a[0]&&(a="/"+a))}if(!b[p])for(var O=0,I=v.length;O0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return r.search=t.search,r.query=t.query,h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!w.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var O=w.slice(-1)[0],P=(r.host||t.host||w.length>1)&&("."===O||".."===O)||""===O,M=0,C=w.length;C>=0;C--)O=w[C],"."===O?w.splice(C,1):".."===O?(w.splice(C,1),M++):M&&(w.splice(C,1),M--);if(!_&&!b)for(;M--;M)w.unshift("..");!_||""===w[0]||w[0]&&"/"===w[0].charAt(0)||w.unshift(""),P&&"/"!==w.join("/").substr(-1)&&w.push("");var R=""===w[0]||w[0]&&"/"===w[0].charAt(0);if(E){r.hostname=r.host=R?"":w.length?w.shift():"";var S=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return _=_||r.host&&w.length,_&&!R&&w.unshift(""),w.length?r.pathname=w.join("/"):(r.pathname=null,r.path=null),h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},n.prototype.parseHost=function(){var t=this.host,e=c.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":30,punycode:25,querystring:28}],30:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],31:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n,i=t.length;if(!(e>=i||0===r)){r=e+r>i?i-e:r;var o=i-r;for(n=e;n0&&void 0!==arguments[0]?arguments[0]:"",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10;i(this,t),this.baseUrl=r,this.progress=0,this.loading=!1,this.defaultQueryString="",this._beforeMiddleware=[],this._afterMiddleware=[],this._resourcesParsing=[],this._boundLoadResource=function(t,r){return e._loadResource(t,r)},this._queue=c.queue(this._boundLoadResource,n),this._queue.pause(),this.resources={},this.onProgress=new a.default,this.onError=new a.default,this.onLoad=new a.default,this.onStart=new a.default,this.onComplete=new a.default}return t.prototype.add=function(t,e,r,n){if(Array.isArray(t)){for(var i=0;i0?n=200:1223===n&&(n=204),2!=(n/100|0))return void this.abort("["+e.status+"] "+e.statusText+": "+e.responseURL);if(this.xhrType===t.XHR_RESPONSE_TYPE.TEXT)this.data=r,this.type=t.TYPE.TEXT;else if(this.xhrType===t.XHR_RESPONSE_TYPE.JSON)try{this.data=JSON.parse(r),this.type=t.TYPE.JSON}catch(t){return void this.abort("Error trying to parse loaded json: "+t)}else if(this.xhrType===t.XHR_RESPONSE_TYPE.DOCUMENT)try{if(window.DOMParser){var i=new DOMParser;this.data=i.parseFromString(r,"text/xml")}else{var o=document.createElement("div");o.innerHTML=r,this.data=o}this.type=t.TYPE.XML}catch(t){return void this.abort("Error trying to parse loaded xml: "+t)}else this.data=e.response||r;this.complete()},t.prototype._determineCrossOrigin=function(t,e){if(0===t.indexOf("data:"))return"";e=e||window.location,p||(p=document.createElement("a")),p.href=t,t=(0,l.default)(p.href,{strictMode:!0});var r=!t.port&&""===e.port||t.port===e.port,n=t.protocol?t.protocol+":":"";return t.host===e.hostname&&r&&n===e.protocol?"":"anonymous"},t.prototype._determineXhrType=function(){return t._xhrTypeMap[this.extension]||t.XHR_RESPONSE_TYPE.TEXT},t.prototype._determineLoadType=function(){return t._loadTypeMap[this.extension]||t.LOAD_TYPE.XHR},t.prototype._getExtension=function(){var t=this.url,e="";if(this.isDataUrl){var r=t.indexOf("/");e=t.substring(r+1,t.indexOf(";",r))}else{var n=t.indexOf("?"),i=t.indexOf("#"),o=Math.min(n>-1?n:t.length,i>-1?i:t.length);t=t.substring(0,o),e=t.substring(t.lastIndexOf(".")+1)}return e.toLowerCase()},t.prototype._getMimeFromXhrType=function(e){switch(e){case t.XHR_RESPONSE_TYPE.BUFFER:return"application/octet-binary";case t.XHR_RESPONSE_TYPE.BLOB:return"application/blob";case t.XHR_RESPONSE_TYPE.DOCUMENT:return"application/xml";case t.XHR_RESPONSE_TYPE.JSON:return"application/json";case t.XHR_RESPONSE_TYPE.DEFAULT:case t.XHR_RESPONSE_TYPE.TEXT:default:return"text/plain"}},u(t,[{key:"isDataUrl",get:function(){return this._hasFlag(t.STATUS_FLAGS.DATA_URL)}},{key:"isComplete",get:function(){return this._hasFlag(t.STATUS_FLAGS.COMPLETE)}},{key:"isLoading",get:function(){return this._hasFlag(t.STATUS_FLAGS.LOADING)}}]),t}();r.default=v,v.STATUS_FLAGS={NONE:0,DATA_URL:1,COMPLETE:2,LOADING:4},v.TYPE={UNKNOWN:0,JSON:1,XML:2,IMAGE:3,AUDIO:4,VIDEO:5,TEXT:6},v.LOAD_TYPE={XHR:1,IMAGE:2,AUDIO:3,VIDEO:4},v.XHR_RESPONSE_TYPE={DEFAULT:"text",BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"},v._loadTypeMap={gif:v.LOAD_TYPE.IMAGE,png:v.LOAD_TYPE.IMAGE,bmp:v.LOAD_TYPE.IMAGE,jpg:v.LOAD_TYPE.IMAGE,jpeg:v.LOAD_TYPE.IMAGE,tif:v.LOAD_TYPE.IMAGE,tiff:v.LOAD_TYPE.IMAGE,webp:v.LOAD_TYPE.IMAGE,tga:v.LOAD_TYPE.IMAGE,svg:v.LOAD_TYPE.IMAGE,"svg+xml":v.LOAD_TYPE.IMAGE,mp3:v.LOAD_TYPE.AUDIO,ogg:v.LOAD_TYPE.AUDIO,wav:v.LOAD_TYPE.AUDIO,mp4:v.LOAD_TYPE.VIDEO,webm:v.LOAD_TYPE.VIDEO},v._xhrTypeMap={xhtml:v.XHR_RESPONSE_TYPE.DOCUMENT,html:v.XHR_RESPONSE_TYPE.DOCUMENT,htm:v.XHR_RESPONSE_TYPE.DOCUMENT,xml:v.XHR_RESPONSE_TYPE.DOCUMENT,tmx:v.XHR_RESPONSE_TYPE.DOCUMENT,svg:v.XHR_RESPONSE_TYPE.DOCUMENT,tsx:v.XHR_RESPONSE_TYPE.DOCUMENT,gif:v.XHR_RESPONSE_TYPE.BLOB,png:v.XHR_RESPONSE_TYPE.BLOB,bmp:v.XHR_RESPONSE_TYPE.BLOB,jpg:v.XHR_RESPONSE_TYPE.BLOB,jpeg:v.XHR_RESPONSE_TYPE.BLOB,tif:v.XHR_RESPONSE_TYPE.BLOB,tiff:v.XHR_RESPONSE_TYPE.BLOB,webp:v.XHR_RESPONSE_TYPE.BLOB,tga:v.XHR_RESPONSE_TYPE.BLOB,json:v.XHR_RESPONSE_TYPE.JSON,text:v.XHR_RESPONSE_TYPE.TEXT,txt:v.XHR_RESPONSE_TYPE.TEXT,ttf:v.XHR_RESPONSE_TYPE.BUFFER,otf:v.XHR_RESPONSE_TYPE.BUFFER},v.EMPTY_GIF="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="},{"mini-signals":38,"parse-uri":39}],34:[function(t,e,r){"use strict";function n(){}function i(t,e,r,n){var i=0,o=t.length;!function s(a){if(a||i===o)return void(r&&r(a));n?setTimeout(function(){e(t[i++],s)},1):e(t[i++],s)}()}function o(t){return function(){if(null===t)throw new Error("Callback was already called.");var e=t;t=null,e.apply(this,arguments)}}function s(t,e){function r(t,e,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(a.started=!0,null==t&&a.idle())return void setTimeout(function(){return a.drain()},1);var i={data:t,callback:"function"==typeof r?r:n};e?a._tasks.unshift(i):a._tasks.push(i),setTimeout(function(){return a.process()},1)}function i(t){return function(){s-=1,t.callback.apply(t,arguments),null!=arguments[0]&&a.error(arguments[0],t.data),s<=a.concurrency-a.buffer&&a.unsaturated(),a.idle()&&a.drain(),a.process()}}if(null==e)e=1;else if(0===e)throw new Error("Concurrency must not be zero");var s=0,a={_tasks:[],concurrency:e,saturated:n,unsaturated:n,buffer:e/4,empty:n,drain:n,error:n,started:!1,paused:!1,push:function(t,e){r(t,!1,e)},kill:function(){s=0,a.drain=n,a.started=!1,a._tasks=[]},unshift:function(t,e){r(t,!0,e)},process:function(){for(;!a.paused&&s>2,o[1]=(3&n[0])<<4|n[1]>>4,o[2]=(15&n[1])<<2|n[2]>>6,o[3]=63&n[2];switch(r-(t.length-1)){case 2:o[3]=64,o[2]=64;break;case 1:o[3]=64}for(var a=0;a=0;r--)this.updateAccessibleObjects(e[r])}},t.prototype.update=function(){if(this.renderer.renderingToScreen){this.updateAccessibleObjects(this.renderer._lastObjectRendered);var t=this.renderer.view.getBoundingClientRect(),e=t.width/this.renderer.width,r=t.height/this.renderer.height,n=this.div;n.style.left=t.left+"px",n.style.top=t.top+"px",n.style.width=this.renderer.width+"px",n.style.height=this.renderer.height+"px";for(var i=0;ithis.renderer.width&&(t.width=this.renderer.width-t.x),t.y+t.height>this.renderer.height&&(t.height=this.renderer.height-t.y)},t.prototype.addChild=function(t){var e=this.pool.pop();e||(e=document.createElement("button"),e.style.width=c+"px",e.style.height=c+"px",e.style.backgroundColor=this.debug?"rgba(255,0,0,0.5)":"transparent",e.style.position="absolute",e.style.zIndex=p,e.style.borderStyle="none",e.addEventListener("click",this._onClick.bind(this)),e.addEventListener("focus",this._onFocus.bind(this)),e.addEventListener("focusout",this._onFocusOut.bind(this))),t.accessibleTitle?e.title=t.accessibleTitle:t.accessibleTitle||t.accessibleHint||(e.title="displayObject "+this.tabIndex),t.accessibleHint&&e.setAttribute("aria-label",t.accessibleHint),t._accessibleActive=!0,t._accessibleDiv=e,e.displayObject=t,this.children.push(t),this.div.appendChild(t._accessibleDiv),t._accessibleDiv.tabIndex=t.tabIndex},t.prototype._onClick=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"click",e.eventData)},t.prototype._onFocus=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseover",e.eventData)},t.prototype._onFocusOut=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseout",e.eventData)},t.prototype._onKeyDown=function(t){9===t.keyCode&&this.activate()},t.prototype._onMouseMove=function(){this.deactivate()},t.prototype.destroy=function(){this.div=null;for(var t=0;t]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i,r.SHAPES={POLY:0,RECT:1,CIRC:2,ELIP:3,RREC:4},r.PRECISION={LOW:"lowp",MEDIUM:"mediump",HIGH:"highp"},r.TRANSFORM_MODE={STATIC:0,DYNAMIC:1},r.TEXT_GRADIENT={LINEAR_VERTICAL:0,LINEAR_HORIZONTAL:1},r.UPDATE_PRIORITY={INTERACTION:50,HIGH:25,NORMAL:0,LOW:-25,UTILITY:-50}},{}],47:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../math"),o=function(){function t(){n(this,t),this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.rect=null}return t.prototype.isEmpty=function(){return this.minX>this.maxX||this.minY>this.maxY},t.prototype.clear=function(){this.updateID++,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0},t.prototype.getRectangle=function(t){return this.minX>this.maxX||this.minY>this.maxY?i.Rectangle.EMPTY:(t=t||new i.Rectangle(0,0,1,1),t.x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)},t.prototype.addPoint=function(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)},t.prototype.addQuad=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY,o=t[0],s=t[1];e=on?o:n,i=s>i?s:i,o=t[2],s=t[3],e=on?o:n,i=s>i?s:i,o=t[4],s=t[5],e=on?o:n,i=s>i?s:i,o=t[6],s=t[7],e=on?o:n,i=s>i?s:i,this.minX=e,this.minY=r,this.maxX=n,this.maxY=i},t.prototype.addFrame=function(t,e,r,n,i){var o=t.worldTransform,s=o.a,a=o.b,u=o.c,h=o.d,l=o.tx,c=o.ty,d=this.minX,f=this.minY,p=this.maxX,v=this.maxY,y=s*e+u*r+l,g=a*e+h*r+c;d=yp?y:p,v=g>v?g:v,y=s*n+u*r+l,g=a*n+h*r+c,d=yp?y:p,v=g>v?g:v,y=s*e+u*i+l,g=a*e+h*i+c,d=yp?y:p,v=g>v?g:v,y=s*n+u*i+l,g=a*n+h*i+c,d=yp?y:p,v=g>v?g:v,this.minX=d,this.minY=f,this.maxX=p,this.maxY=v},t.prototype.addVertices=function(t,e,r,n){for(var i=t.worldTransform,o=i.a,s=i.b,a=i.c,u=i.d,h=i.tx,l=i.ty,c=this.minX,d=this.minY,f=this.maxX,p=this.maxY,v=r;vf?m:f,p=_>p?_:p}this.minX=c,this.minY=d,this.maxX=f,this.maxY=p},t.prototype.addBounds=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY;this.minX=t.minXn?t.maxX:n,this.maxY=t.maxY>i?t.maxY:i},t.prototype.addBoundsMask=function(t,e){var r=t.minX>e.minX?t.minX:e.minX,n=t.minY>e.minY?t.minY:e.minY,i=t.maxXu?i:u,this.maxY=o>h?o:h}},t.prototype.addBoundsArea=function(t,e){var r=t.minX>e.x?t.minX:e.x,n=t.minY>e.y?t.minY:e.y,i=t.maxXu?i:u,this.maxY=o>h?o:h}},t}();r.default=o},{"../math":70}],48:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r1)for(var r=0;rthis.children.length)throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length);return t.parent&&t.parent.removeChild(t),t.parent=this,t.transform._parentID=-1,this.children.splice(e,0,t),this._boundsID++,this.onChildrenChange(e),t.emit("added",this),t},e.prototype.swapChildren=function(t,e){if(t!==e){var r=this.getChildIndex(t),n=this.getChildIndex(e);this.children[r]=e,this.children[n]=t,this.onChildrenChange(r=this.children.length)throw new Error("The supplied index is out of bounds");var r=this.getChildIndex(t);(0,a.removeItems)(this.children,r,1),this.children.splice(e,0,t),this.onChildrenChange(e)},e.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Index ("+t+") does not exist.");return this.children[t]},e.prototype.removeChild=function(t){var e=arguments.length;if(e>1)for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=t,n="number"==typeof e?e:this.children.length,i=n-r,o=void 0;if(i>0&&i<=n){o=this.children.splice(r,i);for(var s=0;s2&&void 0!==arguments[2]&&arguments[2]||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)},e.prototype.toLocal=function(t,e,r,n){return e&&(t=e.toGlobal(t,r,n)),n||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,r)},e.prototype.renderWebGL=function(t){},e.prototype.renderCanvas=function(t){},e.prototype.setParent=function(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t},e.prototype.setTransform=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0,u=arguments.length>8&&void 0!==arguments[8]?arguments[8]:0;return this.position.x=t,this.position.y=e,this.scale.x=r||1,this.scale.y=n||1,this.rotation=i,this.skew.x=o,this.skew.y=s,this.pivot.x=a,this.pivot.y=u,this},e.prototype.destroy=function(){this.removeAllListeners(),this.parent&&this.parent.removeChild(this),this.transform=null,this.parent=null,this._bounds=null,this._currentBounds=null,this._mask=null,this.filterArea=null,this.interactive=!1,this.interactiveChildren=!1,this._destroyed=!0},a(e,[{key:"_tempDisplayObjectParent",get:function(){return null===this.tempDisplayObjectParent&&(this.tempDisplayObjectParent=new e),this.tempDisplayObjectParent}},{key:"x",get:function(){return this.position.x},set:function(t){this.transform.position.x=t}},{key:"y",get:function(){return this.position.y},set:function(t){this.transform.position.y=t}},{key:"worldTransform",get:function(){return this.transform.worldTransform}},{key:"localTransform",get:function(){return this.transform.localTransform}},{key:"position",get:function(){return this.transform.position},set:function(t){this.transform.position.copy(t)}},{key:"scale",get:function(){return this.transform.scale},set:function(t){this.transform.scale.copy(t)}},{key:"pivot",get:function(){return this.transform.pivot},set:function(t){this.transform.pivot.copy(t)}},{key:"skew",get:function(){return this.transform.skew},set:function(t){this.transform.skew.copy(t)}},{key:"rotation",get:function(){return this.transform.rotation},set:function(t){this.transform.rotation=t}},{key:"worldVisible",get:function(){var t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask&&(this._mask.renderable=!0),this._mask=t,this._mask&&(this._mask.renderable=!1)}},{key:"filters",get:function(){return this._filters&&this._filters.slice()},set:function(t){this._filters=t&&t.slice()}}]),e}(h.default);r.default=b,b.prototype.displayObjectUpdateTransform=b.prototype.updateTransform},{"../const":46,"../math":70,"../settings":101,"./Bounds":47,"./Transform":50,"./TransformStatic":52,eventemitter3:3}],50:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]&&arguments[0];i(this,e);var n=o(this,t.call(this));return n.fillAlpha=1,n.lineWidth=0,n.nativeLines=r,n.lineColor=0,n.graphicsData=[],n.tint=16777215,n._prevTint=16777215,n.blendMode=_.BLEND_MODES.NORMAL,n.currentPath=null,n._webGL={},n.isMask=!1,n.boundsPadding=0,n._localBounds=new x.default,n.dirty=0,n.fastRectDirty=-1,n.clearDirty=0,n.boundsDirty=-1,n.cachedSpriteDirty=!1,n._spriteRect=null,n._fastRect=!1,n}return s(e,t),e.prototype.clone=function(){var t=new e;t.renderable=this.renderable,t.fillAlpha=this.fillAlpha,t.lineWidth=this.lineWidth,t.lineColor=this.lineColor,t.tint=this.tint,t.blendMode=this.blendMode,t.isMask=this.isMask,t.boundsPadding=this.boundsPadding,t.dirty=0,t.cachedSpriteDirty=this.cachedSpriteDirty;for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;if(this.lineWidth=t,this.lineColor=e,this.lineAlpha=r,this.currentPath)if(this.currentPath.shape.points.length){var n=new g.Polygon(this.currentPath.shape.points.slice(-2));n.closed=!1,this.drawShape(n)}else this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha;return this},e.prototype.moveTo=function(t,e){var r=new g.Polygon([t,e]);return r.closed=!1,this.drawShape(r),this},e.prototype.lineTo=function(t,e){return this.currentPath.shape.points.push(t,e),this.dirty++,this},e.prototype.quadraticCurveTo=function(t,e,r,n){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var i=this.currentPath.shape.points,o=0,s=0;0===i.length&&this.moveTo(0,0);for(var a=i[i.length-2],u=i[i.length-1],h=1;h<=20;++h){var l=h/20;o=a+(t-a)*l,s=u+(e-u)*l,i.push(o+(t+(r-t)*l-o)*l,s+(e+(n-e)*l-s)*l)}return this.dirty++,this},e.prototype.bezierCurveTo=function(t,e,r,n,i,o){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var s=this.currentPath.shape.points,a=s[s.length-2],u=s[s.length-1];return s.length-=2,(0,w.default)(a,u,t,e,r,n,i,o,s),this.dirty++,this},e.prototype.arcTo=function(t,e,r,n,i){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(t,e):this.moveTo(t,e);var o=this.currentPath.shape.points,s=o[o.length-2],a=o[o.length-1],u=a-e,h=s-t,l=n-e,c=r-t,d=Math.abs(u*c-h*l);if(d<1e-8||0===i)o[o.length-2]===t&&o[o.length-1]===e||o.push(t,e);else{var f=u*u+h*h,p=l*l+c*c,v=u*l+h*c,y=i*Math.sqrt(f)/d,g=i*Math.sqrt(p)/d,m=y*v/f,_=g*v/p,b=y*c+g*h,x=y*l+g*u,T=h*(g+m),w=u*(g+m),E=c*(y+_),S=l*(y+_),O=Math.atan2(w-x,T-b),P=Math.atan2(S-x,E-b);this.arc(b+t,x+e,i,O,P,h*l>c*u)}return this.dirty++,this},e.prototype.arc=function(t,e,r,n,i){var o=arguments.length>5&&void 0!==arguments[5]&&arguments[5];if(n===i)return this;!o&&i<=n?i+=2*Math.PI:o&&n<=i&&(n+=2*Math.PI);var s=i-n,a=40*Math.ceil(Math.abs(s)/(2*Math.PI));if(0===s)return this;var u=t+Math.cos(n)*r,h=e+Math.sin(n)*r,l=this.currentPath?this.currentPath.shape.points:null;l?l[l.length-2]===u&&l[l.length-1]===h||l.push(u,h):(this.moveTo(u,h),l=this.currentPath.shape.points);for(var c=s/(2*a),d=2*c,f=Math.cos(c),p=Math.sin(c),v=a-1,y=v%1/v,g=0;g<=v;++g){var m=g+y*g,_=c+n+d*m,b=Math.cos(_),x=-Math.sin(_);l.push((f*b+p*x)*r+t,(f*-x+p*b)*r+e)}return this.dirty++,this},e.prototype.beginFill=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this.filling=!0,this.fillColor=t,this.fillAlpha=e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},e.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},e.prototype.drawRect=function(t,e,r,n){return this.drawShape(new g.Rectangle(t,e,r,n)),this},e.prototype.drawRoundedRect=function(t,e,r,n,i){return this.drawShape(new g.RoundedRectangle(t,e,r,n,i)),this},e.prototype.drawCircle=function(t,e,r){return this.drawShape(new g.Circle(t,e,r)),this},e.prototype.drawEllipse=function(t,e,r,n){return this.drawShape(new g.Ellipse(t,e,r,n)),this},e.prototype.drawPolygon=function(t){var e=t,r=!0;if(e instanceof g.Polygon&&(r=e.closed,e=e.points),!Array.isArray(e)){e=new Array(arguments.length);for(var n=0;n0)&&(this.lineWidth=0,this.filling=!1,this.boundsDirty=-1,this.dirty++,this.clearDirty++,this.graphicsData.length=0),this.currentPath=null,this._spriteRect=null,this},e.prototype.isFastRect=function(){return 1===this.graphicsData.length&&this.graphicsData[0].shape.type===_.SHAPES.RECT&&!this.graphicsData[0].lineWidth},e.prototype._renderWebGL=function(t){this.dirty!==this.fastRectDirty&&(this.fastRectDirty=this.dirty,this._fastRect=this.isFastRect()),this._fastRect?this._renderSpriteRect(t):(t.setObjectRenderer(t.plugins.graphics),t.plugins.graphics.render(this))},e.prototype._renderSpriteRect=function(t){var e=this.graphicsData[0].shape;this._spriteRect||(this._spriteRect=new y.default(new d.default(d.default.WHITE)));var r=this._spriteRect;if(16777215===this.tint)r.tint=this.graphicsData[0].fillColor;else{var n=C,i=R;(0,m.hex2rgb)(this.graphicsData[0].fillColor,n),(0,m.hex2rgb)(this.tint,i),n[0]*=i[0],n[1]*=i[1],n[2]*=i[2],r.tint=(0,m.rgb2hex)(n)}r.alpha=this.graphicsData[0].fillAlpha,r.worldAlpha=this.worldAlpha*r.alpha,r.blendMode=this.blendMode,r._texture._frame.width=e.width,r._texture._frame.height=e.height,r.transform.worldTransform=this.transform.worldTransform,r.anchor.set(-e.x/e.width,-e.y/e.height),r._onAnchorUpdate(),r._renderWebGL(t)},e.prototype._renderCanvas=function(t){!0!==this.isMask&&t.plugins.graphics.render(this)},e.prototype._calculateBounds=function(){this.boundsDirty!==this.dirty&&(this.boundsDirty=this.dirty,this.updateLocalBounds(),this.cachedSpriteDirty=!0);var t=this._localBounds;this._bounds.addFrame(this.transform,t.minX,t.minY,t.maxX,t.maxY)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,M);for(var e=this.graphicsData,r=0;re?o+a:e,r=sn?s+u:n;else if(c===_.SHAPES.CIRC)o=i.x,s=i.y,a=i.radius+d/2,u=i.radius+d/2,t=o-ae?o+a:e,r=s-un?s+u:n;else if(c===_.SHAPES.ELIP)o=i.x,s=i.y,a=i.width+d/2,u=i.height+d/2,t=o-ae?o+a:e,r=s-un?s+u:n;else for(var f=i.points,p=0,v=0,y=0,g=0,m=0,b=0,x=0,T=0,w=0;w+2e?x+m:e,r=T-bn?T+b:n)}else t=0,e=0,r=0,n=0;var E=this.boundsPadding;this._localBounds.minX=t-E,this._localBounds.maxX=e+E,this._localBounds.minY=r-E,this._localBounds.maxY=n+E},e.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null;var e=new p.default(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,this.nativeLines,t);return this.graphicsData.push(e),e.type===_.SHAPES.POLY&&(e.shape.closed=e.shape.closed||this.filling,this.currentPath=e),this.dirty++,e},e.prototype.generateCanvasTexture=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=this.getLocalBounds(),n=l.default.create(r.width,r.height,t,e);O||(O=new S.default),this.transform.updateLocalTransform(),this.transform.localTransform.copy(P),P.invert(),P.tx-=r.x,P.ty-=r.y,O.render(this,n,!0,P);var i=d.default.fromCanvas(n.baseTexture._canvasRenderTarget.canvas,t,"graphics");return i.baseTexture.resolution=e,i.baseTexture.update(),i},e.prototype.closePath=function(){var t=this.currentPath;return t&&t.shape&&t.shape.close(),this},e.prototype.addHole=function(){var t=this.graphicsData.pop();return this.currentPath=this.graphicsData[this.graphicsData.length-1],this.currentPath.addHole(t.shape),this.currentPath=null,this},e.prototype.destroy=function(e){t.prototype.destroy.call(this,e);for(var r=0;rM?M:P,r.beginPath(),r.moveTo(w,E+P),r.lineTo(w,E+O-P),r.quadraticCurveTo(w,E+O,w+P,E+O),r.lineTo(w+S-P,E+O),r.quadraticCurveTo(w+S,E+O,w+S,E+O-P),r.lineTo(w+S,E+P),r.quadraticCurveTo(w+S,E,w+S-P,E),r.lineTo(w+P,E),r.quadraticCurveTo(w,E,w,E+P),r.closePath(),(u.fillColor||0===u.fillColor)&&(r.globalAlpha=u.fillAlpha*n,r.fillStyle="#"+("00000"+(0|l).toString(16)).substr(-6),r.fill()),u.lineWidth&&(r.globalAlpha=u.lineAlpha*n,r.strokeStyle="#"+("00000"+(0|c).toString(16)).substr(-6),r.stroke())}}},t.prototype.updateGraphicsTint=function(t){t._prevTint=t.tint;for(var e=(t.tint>>16&255)/255,r=(t.tint>>8&255)/255,n=(255&t.tint)/255,i=0;i>16&255)/255*e*255<<16)+((s>>8&255)/255*r*255<<8)+(255&s)/255*n*255,o._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*r*255<<8)+(255&a)/255*n*255}},t.prototype.renderPolygon=function(t,e,r){r.moveTo(t[0],t[1]);for(var n=1;n8&&void 0!==arguments[8]?arguments[8]:[],h=0,l=0,c=0,d=0,f=0;u.push(t,e);for(var p=1,v=0;p<=20;++p)v=p/20,h=1-v,l=h*h,c=l*h,d=v*v,f=d*v,u.push(c*t+3*l*v*r+3*h*d*i+f*s,c*e+3*l*v*n+3*h*d*o+f*a);return u}r.__esModule=!0,r.default=n},{}],57:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../utils"),u=t("../../const"),h=t("../../renderers/webgl/utils/ObjectRenderer"),l=n(h),c=t("../../renderers/webgl/WebGLRenderer"),d=n(c),f=t("./WebGLGraphicsData"),p=n(f),v=t("./shaders/PrimitiveShader"),y=n(v),g=t("./utils/buildPoly"),m=n(g),_=t("./utils/buildRectangle"),b=n(_),x=t("./utils/buildRoundedRectangle"),T=n(x),w=t("./utils/buildCircle"),E=n(w),S=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.graphicsDataPool=[],n.primitiveShader=null,n.gl=r.gl,n.CONTEXT_UID=0,n}return s(e,t),e.prototype.onContextChange=function(){this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.primitiveShader=new y.default(this.gl)},e.prototype.destroy=function(){l.default.prototype.destroy.call(this);for(var t=0;t32e4)&&(n=this.graphicsDataPool.pop()||new p.default(this.renderer.gl,this.primitiveShader,this.renderer.state.attribsState),n.nativeLines=r,n.reset(e),t.data.push(n)),n.dirty=!0,n},e}(l.default);r.default=S,d.default.registerPlugin("graphics",S)},{"../../const":46,"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../utils":124,"./WebGLGraphicsData":58,"./shaders/PrimitiveShader":59,"./utils/buildCircle":60,"./utils/buildPoly":62,"./utils/buildRectangle":63,"./utils/buildRoundedRectangle":64}],58:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("pixi-gl-core"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=function(){function t(e,r,i){n(this,t),this.gl=e,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=o.default.GLBuffer.createVertexBuffer(e),this.indexBuffer=o.default.GLBuffer.createIndexBuffer(e),this.dirty=!0,this.nativeLines=!1,this.glPoints=null,this.glIndices=null,this.shader=r,this.vao=new o.default.VertexArrayObject(e,i).addIndex(this.indexBuffer).addAttribute(this.buffer,r.attributes.aVertexPosition,e.FLOAT,!1,24,0).addAttribute(this.buffer,r.attributes.aColor,e.FLOAT,!1,24,8)}return t.prototype.reset=function(){this.points.length=0,this.indices.length=0},t.prototype.upload=function(){this.glPoints=new Float32Array(this.points),this.buffer.upload(this.glPoints),this.glIndices=new Uint16Array(this.indices),this.indexBuffer.upload(this.glIndices),this.dirty=!1},t.prototype.destroy=function(){this.color=null,this.points=null,this.indices=null,this.vao.destroy(),this.buffer.destroy(),this.indexBuffer.destroy(),this.gl=null,this.buffer=null,this.indexBuffer=null,this.glPoints=null,this.glIndices=null},t}();r.default=s},{"pixi-gl-core":12}],59:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=t("../../../Shader"),a=function(t){return t&&t.__esModule?t:{default:t}}(s),u=function(t){function e(r){return n(this,e),i(this,t.call(this,r,["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","uniform float alpha;","uniform vec3 tint;","varying vec4 vColor;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"].join("\n"),["varying vec4 vColor;","void main(void){"," gl_FragColor = vColor;","}"].join("\n")))}return o(e,t),e}(a.default);r.default=u},{"../../../Shader":44}],60:[function(t,e,r){"use strict";function n(t,e,r){var n=t.shape,i=n.x,u=n.y,h=void 0,l=void 0;if(t.type===s.SHAPES.CIRC?(h=n.radius,l=n.radius):(h=n.width,l=n.height),0!==h&&0!==l){var c=Math.floor(30*Math.sqrt(n.radius))||Math.floor(15*Math.sqrt(n.width+n.height)),d=2*Math.PI/c;if(t.fill){var f=(0,a.hex2rgb)(t.fillColor),p=t.fillAlpha,v=f[0]*p,y=f[1]*p,g=f[2]*p,m=e.points,_=e.indices,b=m.length/6;_.push(b);for(var x=0;x196*p*p?(R=O-M,A=P-C,I=Math.sqrt(R*R+A*A),R/=I,A/=I,R*=p,A*=p,h.push(T-R,w-A),h.push(g,m,_,y),h.push(T+R,w+A),h.push(g,m,_,y),h.push(T-R,w-A),h.push(g,m,_,y),d++):(h.push(X,G),h.push(g,m,_,y),h.push(T-(X-T),w-(G-w)),h.push(g,m,_,y))}}b=r[2*(c-2)],x=r[2*(c-2)+1],T=r[2*(c-1)],w=r[2*(c-1)+1],O=-(x-w),P=b-T,I=Math.sqrt(O*O+P*P),O/=I,P/=I,O*=p,P*=p,h.push(T-O,w-P),h.push(g,m,_,y),h.push(T+O,w+P),h.push(g,m,_,y),l.push(f);for(var W=0;W=6){for(var i=[],o=t.holes,u=0;u0&&(0,s.default)(t,e,r)}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils"),u=t("earcut"),h=n(u)},{"../../../utils":124,"./buildLine":61,earcut:2}],63:[function(t,e,r){"use strict";function n(t,e,r){var n=t.shape,i=n.x,a=n.y,u=n.width,h=n.height;if(t.fill){var l=(0,s.hex2rgb)(t.fillColor),c=t.fillAlpha,d=l[0]*c,f=l[1]*c,p=l[2]*c,v=e.points,y=e.indices,g=v.length/6;v.push(i,a),v.push(d,f,p,c),v.push(i+u,a),v.push(d,f,p,c),v.push(i,a+h),v.push(d,f,p,c),v.push(i+u,a+h),v.push(d,f,p,c),y.push(g,g,g+1,g+2,g+3,g+3)}if(t.lineWidth){var m=t.points;t.points=[i,a,i+u,a,i+u,a+h,i,a+h,i,a],(0,o.default)(t,e,r),t.points=m}}r.__esModule=!0,r.default=n;var i=t("./buildLine"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=t("../../../utils")},{"../../../utils":124,"./buildLine":61}],64:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e,r){var n=t.shape,i=n.x,o=n.y,a=n.width,h=n.height,d=n.radius,f=[];if(f.push(i,o+d),s(i,o+h-d,i,o+h,i+d,o+h,f),s(i+a-d,o+h,i+a,o+h,i+a,o+h-d,f),s(i+a,o+d,i+a,o,i+a-d,o,f),s(i+d,o,i,o,i,o+d+1e-10,f),t.fill){for(var p=(0,c.hex2rgb)(t.fillColor),v=t.fillAlpha,y=p[0]*v,g=p[1]*v,m=p[2]*v,_=e.points,b=e.indices,x=_.length/6,T=(0,u.default)(f,null,2),w=0,E=T.length;w6&&void 0!==arguments[6]?arguments[6]:[],u=a,h=0,l=0,c=0,d=0,f=0,p=0,v=0,y=0;v<=20;++v)y=v/20,h=o(t,r,y),l=o(e,n,y),c=o(r,i,y),d=o(n,s,y),f=o(h,c,y),p=o(l,d,y),u.push(f,p);return u}r.__esModule=!0,r.default=i;var a=t("earcut"),u=n(a),h=t("./buildLine"),l=n(h),c=t("../../../utils")},{"../../../utils":124,"./buildLine":61,earcut:2}],65:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.autoDetectRenderer=r.Application=r.Filter=r.SpriteMaskFilter=r.Quad=r.RenderTarget=r.ObjectRenderer=r.WebGLManager=r.Shader=r.CanvasRenderTarget=r.TextureUvs=r.VideoBaseTexture=r.BaseRenderTexture=r.RenderTexture=r.BaseTexture=r.Texture=r.Spritesheet=r.CanvasGraphicsRenderer=r.GraphicsRenderer=r.GraphicsData=r.Graphics=r.TextMetrics=r.TextStyle=r.Text=r.SpriteRenderer=r.CanvasTinter=r.CanvasSpriteRenderer=r.Sprite=r.TransformBase=r.TransformStatic=r.Transform=r.Container=r.DisplayObject=r.Bounds=r.glCore=r.WebGLRenderer=r.CanvasRenderer=r.ticker=r.utils=r.settings=void 0;var o=t("./const");Object.keys(o).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return o[t]}})});var s=t("./math");Object.keys(s).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return s[t]}})});var a=t("pixi-gl-core");Object.defineProperty(r,"glCore",{enumerable:!0,get:function(){return i(a).default}});var u=t("./display/Bounds");Object.defineProperty(r,"Bounds",{enumerable:!0,get:function(){return i(u).default}}) +;var h=t("./display/DisplayObject");Object.defineProperty(r,"DisplayObject",{enumerable:!0,get:function(){return i(h).default}});var l=t("./display/Container");Object.defineProperty(r,"Container",{enumerable:!0,get:function(){return i(l).default}});var c=t("./display/Transform");Object.defineProperty(r,"Transform",{enumerable:!0,get:function(){return i(c).default}});var d=t("./display/TransformStatic");Object.defineProperty(r,"TransformStatic",{enumerable:!0,get:function(){return i(d).default}});var f=t("./display/TransformBase");Object.defineProperty(r,"TransformBase",{enumerable:!0,get:function(){return i(f).default}});var p=t("./sprites/Sprite");Object.defineProperty(r,"Sprite",{enumerable:!0,get:function(){return i(p).default}});var v=t("./sprites/canvas/CanvasSpriteRenderer");Object.defineProperty(r,"CanvasSpriteRenderer",{enumerable:!0,get:function(){return i(v).default}});var y=t("./sprites/canvas/CanvasTinter");Object.defineProperty(r,"CanvasTinter",{enumerable:!0,get:function(){return i(y).default}});var g=t("./sprites/webgl/SpriteRenderer");Object.defineProperty(r,"SpriteRenderer",{enumerable:!0,get:function(){return i(g).default}});var m=t("./text/Text");Object.defineProperty(r,"Text",{enumerable:!0,get:function(){return i(m).default}});var _=t("./text/TextStyle");Object.defineProperty(r,"TextStyle",{enumerable:!0,get:function(){return i(_).default}});var b=t("./text/TextMetrics");Object.defineProperty(r,"TextMetrics",{enumerable:!0,get:function(){return i(b).default}});var x=t("./graphics/Graphics");Object.defineProperty(r,"Graphics",{enumerable:!0,get:function(){return i(x).default}});var T=t("./graphics/GraphicsData");Object.defineProperty(r,"GraphicsData",{enumerable:!0,get:function(){return i(T).default}});var w=t("./graphics/webgl/GraphicsRenderer");Object.defineProperty(r,"GraphicsRenderer",{enumerable:!0,get:function(){return i(w).default}});var E=t("./graphics/canvas/CanvasGraphicsRenderer");Object.defineProperty(r,"CanvasGraphicsRenderer",{enumerable:!0,get:function(){return i(E).default}});var S=t("./textures/Spritesheet");Object.defineProperty(r,"Spritesheet",{enumerable:!0,get:function(){return i(S).default}});var O=t("./textures/Texture");Object.defineProperty(r,"Texture",{enumerable:!0,get:function(){return i(O).default}});var P=t("./textures/BaseTexture");Object.defineProperty(r,"BaseTexture",{enumerable:!0,get:function(){return i(P).default}});var M=t("./textures/RenderTexture");Object.defineProperty(r,"RenderTexture",{enumerable:!0,get:function(){return i(M).default}});var C=t("./textures/BaseRenderTexture");Object.defineProperty(r,"BaseRenderTexture",{enumerable:!0,get:function(){return i(C).default}});var R=t("./textures/VideoBaseTexture");Object.defineProperty(r,"VideoBaseTexture",{enumerable:!0,get:function(){return i(R).default}});var A=t("./textures/TextureUvs");Object.defineProperty(r,"TextureUvs",{enumerable:!0,get:function(){return i(A).default}});var I=t("./renderers/canvas/utils/CanvasRenderTarget");Object.defineProperty(r,"CanvasRenderTarget",{enumerable:!0,get:function(){return i(I).default}});var D=t("./Shader");Object.defineProperty(r,"Shader",{enumerable:!0,get:function(){return i(D).default}});var L=t("./renderers/webgl/managers/WebGLManager");Object.defineProperty(r,"WebGLManager",{enumerable:!0,get:function(){return i(L).default}});var N=t("./renderers/webgl/utils/ObjectRenderer");Object.defineProperty(r,"ObjectRenderer",{enumerable:!0,get:function(){return i(N).default}});var F=t("./renderers/webgl/utils/RenderTarget");Object.defineProperty(r,"RenderTarget",{enumerable:!0,get:function(){return i(F).default}});var B=t("./renderers/webgl/utils/Quad");Object.defineProperty(r,"Quad",{enumerable:!0,get:function(){return i(B).default}});var k=t("./renderers/webgl/filters/spriteMask/SpriteMaskFilter");Object.defineProperty(r,"SpriteMaskFilter",{enumerable:!0,get:function(){return i(k).default}});var j=t("./renderers/webgl/filters/Filter");Object.defineProperty(r,"Filter",{enumerable:!0,get:function(){return i(j).default}});var U=t("./Application");Object.defineProperty(r,"Application",{enumerable:!0,get:function(){return i(U).default}});var X=t("./autoDetectRenderer");Object.defineProperty(r,"autoDetectRenderer",{enumerable:!0,get:function(){return X.autoDetectRenderer}});var G=t("./utils"),W=n(G),H=t("./ticker"),Y=n(H),V=t("./settings"),z=i(V),q=t("./renderers/canvas/CanvasRenderer"),K=i(q),Z=t("./renderers/webgl/WebGLRenderer"),J=i(Z);r.settings=z.default,r.utils=W,r.ticker=Y,r.CanvasRenderer=K.default,r.WebGLRenderer=J.default},{"./Application":43,"./Shader":44,"./autoDetectRenderer":45,"./const":46,"./display/Bounds":47,"./display/Container":48,"./display/DisplayObject":49,"./display/Transform":50,"./display/TransformBase":51,"./display/TransformStatic":52,"./graphics/Graphics":53,"./graphics/GraphicsData":54,"./graphics/canvas/CanvasGraphicsRenderer":55,"./graphics/webgl/GraphicsRenderer":57,"./math":70,"./renderers/canvas/CanvasRenderer":77,"./renderers/canvas/utils/CanvasRenderTarget":79,"./renderers/webgl/WebGLRenderer":84,"./renderers/webgl/filters/Filter":86,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":89,"./renderers/webgl/managers/WebGLManager":93,"./renderers/webgl/utils/ObjectRenderer":94,"./renderers/webgl/utils/Quad":95,"./renderers/webgl/utils/RenderTarget":96,"./settings":101,"./sprites/Sprite":102,"./sprites/canvas/CanvasSpriteRenderer":103,"./sprites/canvas/CanvasTinter":104,"./sprites/webgl/SpriteRenderer":106,"./text/Text":108,"./text/TextMetrics":109,"./text/TextStyle":110,"./textures/BaseRenderTexture":111,"./textures/BaseTexture":112,"./textures/RenderTexture":113,"./textures/Spritesheet":114,"./textures/Texture":115,"./textures/TextureUvs":116,"./textures/VideoBaseTexture":117,"./ticker":120,"./utils":124,"pixi-gl-core":12}],66:[function(t,e,r){"use strict";function n(t){return t<0?-1:t>0?1:0}r.__esModule=!0;var i=t("./Matrix"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],a=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],u=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],h=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],l=[],c=[];!function(){for(var t=0;t<16;t++){var e=[];c.push(e);for(var r=0;r<16;r++)for(var i=n(s[t]*s[r]+u[t]*a[r]),d=n(a[t]*s[r]+h[t]*a[r]),f=n(s[t]*u[r]+u[t]*h[r]),p=n(a[t]*u[r]+h[t]*h[r]),v=0;v<16;v++)if(s[v]===i&&a[v]===d&&u[v]===f&&h[v]===p){e.push(v);break}}for(var y=0;y<16;y++){var g=new o.default;g.set(s[y],a[y],u[y],h[y],0,0),l.push(g)}}();var d={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MIRROR_HORIZONTAL:12,uX:function(t){return s[t]},uY:function(t){return a[t]},vX:function(t){return u[t]},vY:function(t){return h[t]},inv:function(t){return 8&t?15&t:7&-t},add:function(t,e){return c[t][e]},sub:function(t,e){return c[t][d.inv(e)]},rotate180:function(t){return 4^t},isSwapWidthHeight:function(t){return 2==(3&t)},byDirection:function(t,e){return 2*Math.abs(t)<=Math.abs(e)?e>=0?d.S:d.N:2*Math.abs(e)<=Math.abs(t)?t>0?d.E:d.W:e>0?t>0?d.SE:d.SW:t>0?d.NE:d.NW},matrixAppendRotationInv:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=l[d.inv(e)];i.tx=r,i.ty=n,t.append(i)}};r.default=d},{"./Matrix":67}],67:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:1,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;n(this,t),this.a=e,this.b=r,this.c=i,this.d=o,this.tx=s,this.ty=a,this.array=null}return t.prototype.fromArray=function(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]},t.prototype.set=function(t,e,r,n,i,o){return this.a=t,this.b=e,this.c=r,this.d=n,this.tx=i,this.ty=o,this},t.prototype.toArray=function(t,e){this.array||(this.array=new Float32Array(9));var r=e||this.array;return t?(r[0]=this.a,r[1]=this.b,r[2]=0,r[3]=this.c,r[4]=this.d,r[5]=0,r[6]=this.tx,r[7]=this.ty,r[8]=1):(r[0]=this.a,r[1]=this.c,r[2]=this.tx,r[3]=this.b,r[4]=this.d,r[5]=this.ty,r[6]=0,r[7]=0,r[8]=1),r},t.prototype.apply=function(t,e){e=e||new s.default;var r=t.x,n=t.y;return e.x=this.a*r+this.c*n+this.tx,e.y=this.b*r+this.d*n+this.ty,e},t.prototype.applyInverse=function(t,e){e=e||new s.default;var r=1/(this.a*this.d+this.c*-this.b),n=t.x,i=t.y;return e.x=this.d*r*n+-this.c*r*i+(this.ty*this.c-this.tx*this.d)*r,e.y=this.a*r*i+-this.b*r*n+(-this.ty*this.a+this.tx*this.b)*r,e},t.prototype.translate=function(t,e){return this.tx+=t,this.ty+=e,this},t.prototype.scale=function(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this},t.prototype.rotate=function(t){var e=Math.cos(t),r=Math.sin(t),n=this.a,i=this.c,o=this.tx;return this.a=n*e-this.b*r,this.b=n*r+this.b*e,this.c=i*e-this.d*r,this.d=i*r+this.d*e,this.tx=o*e-this.ty*r,this.ty=o*r+this.ty*e,this},t.prototype.append=function(t){var e=this.a,r=this.b,n=this.c,i=this.d;return this.a=t.a*e+t.b*n,this.b=t.a*r+t.b*i,this.c=t.c*e+t.d*n,this.d=t.c*r+t.d*i,this.tx=t.tx*e+t.ty*n+this.tx,this.ty=t.tx*r+t.ty*i+this.ty,this},t.prototype.setTransform=function(t,e,r,n,i,o,s,a,u){var h=Math.sin(s),l=Math.cos(s),c=Math.cos(u),d=Math.sin(u),f=-Math.sin(a),p=Math.cos(a),v=l*i,y=h*i,g=-h*o,m=l*o;return this.a=c*v+d*g,this.b=c*y+d*m,this.c=f*v+p*g,this.d=f*y+p*m,this.tx=t+(r*v+n*g),this.ty=e+(r*y+n*m),this},t.prototype.prepend=function(t){var e=this.tx;if(1!==t.a||0!==t.b||0!==t.c||1!==t.d){var r=this.a,n=this.c;this.a=r*t.a+this.b*t.c,this.b=r*t.b+this.b*t.d,this.c=n*t.a+this.d*t.c,this.d=n*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this},t.prototype.decompose=function(t){var e=this.a,r=this.b,n=this.c,i=this.d,o=-Math.atan2(-n,i),s=Math.atan2(r,e);return Math.abs(o+s)<1e-5?(t.rotation=s,e<0&&i>=0&&(t.rotation+=t.rotation<=0?Math.PI:-Math.PI),t.skew.x=t.skew.y=0):(t.skew.x=o,t.skew.y=s),t.scale.x=Math.sqrt(e*e+r*r),t.scale.y=Math.sqrt(n*n+i*i),t.position.x=this.tx,t.position.y=this.ty,t},t.prototype.invert=function(){var t=this.a,e=this.b,r=this.c,n=this.d,i=this.tx,o=t*n-e*r;return this.a=n/o,this.b=-e/o,this.c=-r/o,this.d=t/o,this.tx=(r*this.ty-n*i)/o,this.ty=-(t*this.ty-e*i)/o,this},t.prototype.identity=function(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this},t.prototype.clone=function(){var e=new t;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e},t.prototype.copy=function(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t},i(t,null,[{key:"IDENTITY",get:function(){return new t}},{key:"TEMP_MATRIX",get:function(){return new t}}]),t}();r.default=a},{"./Point":69}],68:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this._x=i,this._y=o,this.cb=e,this.scope=r}return t.prototype.set=function(t,e){var r=t||0,n=e||(0!==e?r:0);this._x===r&&this._y===n||(this._x=r,this._y=n,this.cb.call(this.scope))},t.prototype.copy=function(t){this._x===t.x&&this._y===t.y||(this._x=t.x,this._y=t.y,this.cb.call(this.scope))},i(t,[{key:"x",get:function(){return this._x},set:function(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}},{key:"y",get:function(){return this._y},set:function(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}]),t}();r.default=o},{}],69:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;n(this,t),this.x=e,this.y=r}return t.prototype.clone=function(){return new t(this.x,this.y)},t.prototype.copy=function(t){this.set(t.x,t.y)},t.prototype.equals=function(t){return t.x===this.x&&t.y===this.y},t.prototype.set=function(t,e){this.x=t||0,this.y=e||(0!==e?this.x:0)},t}();r.default=i},{}],70:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./Point");Object.defineProperty(r,"Point",{enumerable:!0,get:function(){return n(i).default}});var o=t("./ObservablePoint");Object.defineProperty(r,"ObservablePoint",{enumerable:!0,get:function(){return n(o).default}});var s=t("./Matrix");Object.defineProperty(r,"Matrix",{enumerable:!0,get:function(){return n(s).default}});var a=t("./GroupD8");Object.defineProperty(r,"GroupD8",{enumerable:!0,get:function(){return n(a).default}});var u=t("./shapes/Circle");Object.defineProperty(r,"Circle",{enumerable:!0,get:function(){return n(u).default}});var h=t("./shapes/Ellipse");Object.defineProperty(r,"Ellipse",{enumerable:!0,get:function(){return n(h).default}});var l=t("./shapes/Polygon");Object.defineProperty(r,"Polygon",{enumerable:!0,get:function(){return n(l).default}});var c=t("./shapes/Rectangle");Object.defineProperty(r,"Rectangle",{enumerable:!0,get:function(){return n(c).default}});var d=t("./shapes/RoundedRectangle");Object.defineProperty(r,"RoundedRectangle",{enumerable:!0,get:function(){return n(d).default}})},{"./GroupD8":66,"./Matrix":67,"./ObservablePoint":68,"./Point":69,"./shapes/Circle":71,"./shapes/Ellipse":72,"./shapes/Polygon":73,"./shapes/Rectangle":74,"./shapes/RoundedRectangle":75}],71:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("./Rectangle"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=t("../../const"),a=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;n(this,t),this.x=e,this.y=r,this.radius=i,this.type=s.SHAPES.CIRC}return t.prototype.clone=function(){return new t(this.x,this.y,this.radius)},t.prototype.contains=function(t,e){if(this.radius<=0)return!1;var r=this.radius*this.radius,n=this.x-t,i=this.y-e;return n*=n,i*=i,n+i<=r},t.prototype.getBounds=function(){return new o.default(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)},t}();r.default=a},{"../../const":46,"./Rectangle":74}],72:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("./Rectangle"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=t("../../const"),a=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this.x=e,this.y=r,this.width=i,this.height=o,this.type=s.SHAPES.ELIP}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;var r=(t-this.x)/this.width,n=(e-this.y)/this.height;return r*=r,n*=n,r+n<=1},t.prototype.getBounds=function(){return new o.default(this.x-this.width,this.y-this.height,this.width,this.height)},t}();r.default=a},{"../../const":46,"./Rectangle":74}],73:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../Point"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=t("../../const"),a=function(){function t(){for(var e=arguments.length,r=Array(e),i=0;ie!=h>e&&t<(e-a)/(h-a)*(u-s)+s&&(r=!r)}return r},t}();r.default=a},{"../../const":46,"../Point":69}],74:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this.x=Number(e),this.y=Number(r),this.width=Number(i),this.height=Number(s),this.type=o.SHAPES.RECT}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this},t.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t=this.y&&et.x+t.width&&(this.width=t.width-this.x,this.width<0&&(this.width=0)),this.y+this.height>t.y+t.height&&(this.height=t.height-this.y,this.height<0&&(this.height=0))},t.prototype.enlarge=function(t){var e=Math.min(this.x,t.x),r=Math.max(this.x+this.width,t.x+t.width),n=Math.min(this.y,t.y),i=Math.max(this.y+this.height,t.y+t.height);this.x=e,this.width=r-e,this.y=n,this.height=i-n},i(t,[{key:"left",get:function(){return this.x}},{key:"right",get:function(){return this.x+this.width}},{key:"top",get:function(){return this.y}},{key:"bottom",get:function(){return this.y+this.height}}],[{key:"EMPTY",get:function(){return new t(0,0,0,0)}}]),t}();r.default=s},{"../../const":46}],75:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:20;n(this,t),this.x=e,this.y=r,this.width=o,this.height=s,this.radius=a,this.type=i.SHAPES.RREC}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height,this.radius)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){if(e>=this.y+this.radius&&e<=this.y+this.height-this.radius||t>=this.x+this.radius&&t<=this.x+this.width-this.radius)return!0;var r=t-(this.x+this.radius),n=e-(this.y+this.radius),i=this.radius*this.radius;if(r*r+n*n<=i)return!0;if((r=t-(this.x+this.width-this.radius))*r+n*n<=i)return!0;if(n=e-(this.y+this.height-this.radius),r*r+n*n<=i)return!0;if((r=t-(this.x+this.radius))*r+n*n<=i)return!0}return!1},t}();r.default=o},{"../../const":46}],76:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rE?E:w,e.moveTo(_,b+w),e.lineTo(_,b+T-w),e.quadraticCurveTo(_,b+T,_+w,b+T),e.lineTo(_+x-w,b+T),e.quadraticCurveTo(_+x,b+T,_+x,b+T-w),e.lineTo(_+x,b+w),e.quadraticCurveTo(_+x,b,_+x-w,b),e.lineTo(_+w,b),e.quadraticCurveTo(_,b,_,b+w),e.closePath()}}}},t.prototype.popMask=function(t){t.context.restore()},t.prototype.destroy=function(){},t}();r.default=o},{"../../../const":46}],79:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:[];return(0,s.default)()?(t[i.BLEND_MODES.NORMAL]="source-over",t[i.BLEND_MODES.ADD]="lighter",t[i.BLEND_MODES.MULTIPLY]="multiply",t[i.BLEND_MODES.SCREEN]="screen",t[i.BLEND_MODES.OVERLAY]="overlay",t[i.BLEND_MODES.DARKEN]="darken",t[i.BLEND_MODES.LIGHTEN]="lighten",t[i.BLEND_MODES.COLOR_DODGE]="color-dodge",t[i.BLEND_MODES.COLOR_BURN]="color-burn",t[i.BLEND_MODES.HARD_LIGHT]="hard-light",t[i.BLEND_MODES.SOFT_LIGHT]="soft-light",t[i.BLEND_MODES.DIFFERENCE]="difference",t[i.BLEND_MODES.EXCLUSION]="exclusion",t[i.BLEND_MODES.HUE]="hue", +t[i.BLEND_MODES.SATURATION]="saturate",t[i.BLEND_MODES.COLOR]="color",t[i.BLEND_MODES.LUMINOSITY]="luminosity"):(t[i.BLEND_MODES.NORMAL]="source-over",t[i.BLEND_MODES.ADD]="lighter",t[i.BLEND_MODES.MULTIPLY]="source-over",t[i.BLEND_MODES.SCREEN]="source-over",t[i.BLEND_MODES.OVERLAY]="source-over",t[i.BLEND_MODES.DARKEN]="source-over",t[i.BLEND_MODES.LIGHTEN]="source-over",t[i.BLEND_MODES.COLOR_DODGE]="source-over",t[i.BLEND_MODES.COLOR_BURN]="source-over",t[i.BLEND_MODES.HARD_LIGHT]="source-over",t[i.BLEND_MODES.SOFT_LIGHT]="source-over",t[i.BLEND_MODES.DIFFERENCE]="source-over",t[i.BLEND_MODES.EXCLUSION]="source-over",t[i.BLEND_MODES.HUE]="source-over",t[i.BLEND_MODES.SATURATION]="source-over",t[i.BLEND_MODES.COLOR]="source-over",t[i.BLEND_MODES.LUMINOSITY]="source-over"),t[i.BLEND_MODES.NORMAL_NPM]=t[i.BLEND_MODES.NORMAL],t[i.BLEND_MODES.ADD_NPM]=t[i.BLEND_MODES.ADD],t[i.BLEND_MODES.SCREEN_NPM]=t[i.BLEND_MODES.SCREEN],t}r.__esModule=!0,r.default=n;var i=t("../../../const"),o=t("./canUseNewCanvasBlendModes"),s=function(t){return t&&t.__esModule?t:{default:t}}(o)},{"../../../const":46,"./canUseNewCanvasBlendModes":80}],82:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=t("../../settings"),s=function(t){return t&&t.__esModule?t:{default:t}}(o),a=function(){function t(e){n(this,t),this.renderer=e,this.count=0,this.checkCount=0,this.maxIdle=s.default.GC_MAX_IDLE,this.checkCountMax=s.default.GC_MAX_CHECK_COUNT,this.mode=s.default.GC_MODE}return t.prototype.update=function(){this.count++,this.mode!==i.GC_MODES.MANUAL&&++this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run())},t.prototype.run=function(){for(var t=this.renderer.textureManager,e=t._managedTextures,r=!1,n=0;nthis.maxIdle&&(t.destroyTexture(i,!0),e[n]=null,r=!0)}if(r){for(var o=0,s=0;s=0;r--)this.unload(t.children[r])},t}();r.default=a},{"../../const":46,"../../settings":101}],83:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("pixi-gl-core"),o=t("../../const"),s=t("./utils/RenderTarget"),a=function(t){return t&&t.__esModule?t:{default:t}}(s),u=t("../../utils"),h=function(){function t(e){n(this,t),this.renderer=e,this.gl=e.gl,this._managedTextures=[]}return t.prototype.bindTexture=function(){},t.prototype.getTexture=function(){},t.prototype.updateTexture=function(t,e){var r=this.gl,n=!!t._glRenderTargets;if(!t.hasLoaded)return null;var s=this.renderer.boundTextures;if(void 0===e){e=0;for(var u=0;u 0.5)"," {"," color = vec4(1.0, 0.0, 0.0, 1.0);"," }"," else"," {"," color = vec4(0.0, 1.0, 0.0, 1.0);"," }"," gl_FragColor = mix(sample, masky, 0.5);"," gl_FragColor *= sample.a;","}"].join("\n")}}]),t}();r.default=f},{"../../../const":46,"../../../settings":101,"../../../utils":124,"./extractUniformsFromSrc":87}],87:[function(t,e,r){"use strict";function n(t,e,r){var n=i(t),o=i(e);return Object.assign(n,o)}function i(t){for(var e=new RegExp("^(projectionMatrix|uSampler|filterArea|filterClamp)$"),r={},n=void 0,i=t.replace(/\s+/g," ").split(/\s*;\s*/),o=0;o-1){var u=s.split(" "),h=u[1],l=u[2],c=1;l.indexOf("[")>-1&&(n=l.split(/\[|]/),l=n[0],c*=Number(n[1])),l.match(e)||(r[l]={value:a(h,c),name:l,type:h})}}return r}r.__esModule=!0,r.default=n;var o=t("pixi-gl-core"),s=function(t){return t&&t.__esModule?t:{default:t}}(o),a=s.default.shader.defaultValue},{"pixi-gl-core":12}],88:[function(t,e,r){"use strict";function n(t,e,r){var n=t.identity();return n.translate(e.x/r.width,e.y/r.height),n.scale(r.width,r.height),n}function i(t,e,r){var n=t.identity();n.translate(e.x/r.width,e.y/r.height);var i=r.width/e.width,o=r.height/e.height;return n.scale(i,o),n}function o(t,e,r,n){var i=n.worldTransform.copy(s.Matrix.TEMP_MATRIX),o=n._texture.baseTexture,a=t.identity(),u=r.height/r.width;a.translate(e.x/r.width,e.y/r.height),a.scale(1,u);var h=r.width/o.width,l=r.height/o.height;return i.tx/=o.width*h,i.ty/=o.width*h,i.invert(),a.prepend(i),a.scale(1,1/u),a.scale(h,l),a.translate(n.anchor.x,n.anchor.y),a}r.__esModule=!0,r.calculateScreenSpaceMatrix=n,r.calculateNormalizedScreenSpaceMatrix=i,r.calculateSpriteMatrix=o;var s=t("../../../math")},{"../../../math":70}],89:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=t("../Filter"),a=function(t){return t&&t.__esModule?t:{default:t}}(s),u=t("../../../../math"),h=(t("path"),function(t){function e(r){n(this,e);var o=new u.Matrix,s=i(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n","varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform sampler2D mask;\n\nvoid main(void)\n{\n // check clip! this will stop the mask bleeding out from the edges\n vec2 text = abs( vMaskCoord - 0.5 );\n text = step(0.5, text);\n\n float clip = 1.0 - max(text.y, text.x);\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n"));return r.renderable=!1,s.maskSprite=r,s.maskMatrix=o,s}return o(e,t),e.prototype.apply=function(t,e,r){var n=this.maskSprite;this.uniforms.mask=n._texture,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,n),this.uniforms.alpha=n.worldAlpha,t.applyFilter(this,e,r)},e}(a.default));r.default=h},{"../../../../math":70,"../Filter":86,path:23}],90:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var a=t("./WebGLManager"),u=n(a),h=t("../utils/RenderTarget"),l=n(h),c=t("../utils/Quad"),d=n(c),f=t("../../../math"),p=t("../../../Shader"),v=n(p),y=t("../filters/filterTransforms"),g=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(y),m=t("bit-twiddle"),_=n(m),b=function t(){s(this,t),this.renderTarget=null,this.sourceFrame=new f.Rectangle,this.destinationFrame=new f.Rectangle,this.filters=[],this.target=null,this.resolution=1},x=function(t){function e(r){s(this,e);var n=i(this,t.call(this,r));return n.gl=n.renderer.gl,n.quad=new d.default(n.gl,r.state.attribState),n.shaderCache={},n.pool={},n.filterData=null,n}return o(e,t),e.prototype.pushFilter=function(t,e){var r=this.renderer,n=this.filterData;if(!n){n=this.renderer._activeRenderTarget.filterStack;var i=new b;i.sourceFrame=i.destinationFrame=this.renderer._activeRenderTarget.size,i.renderTarget=r._activeRenderTarget,this.renderer._activeRenderTarget.filterData=n={index:0,stack:[i]},this.filterData=n}var o=n.stack[++n.index];o||(o=n.stack[n.index]=new b);var s=e[0].resolution,a=0|e[0].padding,u=t.filterArea||t.getBounds(!0),h=o.sourceFrame,l=o.destinationFrame;h.x=(u.x*s|0)/s,h.y=(u.y*s|0)/s,h.width=(u.width*s|0)/s,h.height=(u.height*s|0)/s,n.stack[0].renderTarget.transform||e[0].autoFit&&h.fit(n.stack[0].destinationFrame),h.pad(a),l.width=h.width,l.height=h.height;var c=this.getPotRenderTarget(r.gl,h.width,h.height,s);o.target=t,o.filters=e,o.resolution=s,o.renderTarget=c,c.setFrame(l,h),r.bindRenderTarget(c),c.clear()},e.prototype.popFilter=function(){var t=this.filterData,e=t.stack[t.index-1],r=t.stack[t.index];this.quad.map(r.renderTarget.size,r.sourceFrame).upload();var n=r.filters;if(1===n.length)n[0].apply(this,r.renderTarget,e.renderTarget,!1,r),this.freePotRenderTarget(r.renderTarget);else{var i=r.renderTarget,o=this.getPotRenderTarget(this.renderer.gl,r.sourceFrame.width,r.sourceFrame.height,r.resolution);o.setFrame(r.destinationFrame,r.sourceFrame),o.clear();var s=0;for(s=0;s0&&(e+="\nelse "),r1&&void 0!==arguments[1]?arguments[1]:[];return e[i.BLEND_MODES.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.ADD]=[t.ONE,t.DST_ALPHA],e[i.BLEND_MODES.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SCREEN]=[t.ONE,t.ONE_MINUS_SRC_COLOR],e[i.BLEND_MODES.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.NORMAL_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.ADD_NPM]=[t.SRC_ALPHA,t.DST_ALPHA,t.ONE,t.DST_ALPHA],e[i.BLEND_MODES.SCREEN_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_COLOR,t.ONE,t.ONE_MINUS_SRC_COLOR],e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":46}],99:[function(t,e,r){"use strict";function n(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e[i.DRAW_MODES.POINTS]=t.POINTS,e[i.DRAW_MODES.LINES]=t.LINES,e[i.DRAW_MODES.LINE_LOOP]=t.LINE_LOOP,e[i.DRAW_MODES.LINE_STRIP]=t.LINE_STRIP,e[i.DRAW_MODES.TRIANGLES]=t.TRIANGLES,e[i.DRAW_MODES.TRIANGLE_STRIP]=t.TRIANGLE_STRIP,e[i.DRAW_MODES.TRIANGLE_FAN]=t.TRIANGLE_FAN,e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":46}],100:[function(t,e,r){"use strict";function n(t){t.getContextAttributes().stencil||console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly")}r.__esModule=!0,r.default=n},{}],101:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./utils/maxRecommendedTextures"),o=n(i),s=t("./utils/canUploadSameBuffer"),a=n(s);r.default={TARGET_FPMS:.06,MIPMAP_TEXTURES:!0,RESOLUTION:1,FILTER_RESOLUTION:1,SPRITE_MAX_TEXTURES:(0,o.default)(32),SPRITE_BATCH_SIZE:4096,RETINA_PREFIX:/@([0-9\.]+)x/,RENDER_OPTIONS:{view:null,antialias:!1,forceFXAA:!1,autoResize:!1,transparent:!1,backgroundColor:0,clearBeforeRender:!0,preserveDrawingBuffer:!1,roundPixels:!1,width:800,height:600,legacy:!1},TRANSFORM_MODE:0,GC_MODE:0,GC_MAX_IDLE:3600,GC_MAX_CHECK_COUNT:600,WRAP_MODE:0,SCALE_MODE:0,PRECISION_VERTEX:"highp",PRECISION_FRAGMENT:"mediump",CAN_UPLOAD_SAME_BUFFER:(0,a.default)()}},{"./utils/canUploadSameBuffer":121,"./utils/maxRecommendedTextures":126}],102:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r=n&&v.x=i&&v.y>16)+(65280&t)+((255&t)<<16)}},{key:"texture",get:function(){return this._texture},set:function(t){this._texture!==t&&(this._texture=t,this.cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,t&&(t.baseTexture.hasLoaded?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}]),e}(p.default);r.default=y},{"../const":46,"../display/Container":48,"../math":70,"../textures/Texture":115,"../utils":124}],103:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../renderers/canvas/CanvasRenderer"),s=n(o),a=t("../../const"),u=t("../../math"),h=t("./CanvasTinter"),l=n(h),c=new u.Matrix,d=function(){function t(e){i(this,t),this.renderer=e}return t.prototype.render=function(t){var e=t._texture,r=this.renderer,n=e._frame.width,i=e._frame.height,o=t.transform.worldTransform,s=0,h=0;if(!(e.orig.width<=0||e.orig.height<=0)&&e.baseTexture.source&&(r.setBlendMode(t.blendMode),e.valid)){r.context.globalAlpha=t.worldAlpha;var d=e.baseTexture.scaleMode===a.SCALE_MODES.LINEAR;r.smoothProperty&&r.context[r.smoothProperty]!==d&&(r.context[r.smoothProperty]=d),e.trim?(s=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,h=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(s=(.5-t.anchor.x)*e.orig.width,h=(.5-t.anchor.y)*e.orig.height),e.rotate&&(o.copy(c),o=c,u.GroupD8.matrixAppendRotationInv(o,e.rotate,s,h),s=0,h=0),s-=n/2,h-=i/2,r.roundPixels?(r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution|0,o.ty*r.resolution|0),s|=0,h|=0):r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution,o.ty*r.resolution);var f=e.baseTexture.resolution;16777215!==t.tint?(t.cachedTint===t.tint&&t.tintedTexture.tintId===t._texture._updateID||(t.cachedTint=t.tint,t.tintedTexture=l.default.getTintedTexture(t,t.tint)),r.context.drawImage(t.tintedTexture,0,0,n*f,i*f,s*r.resolution,h*r.resolution,n*r.resolution,i*r.resolution)):r.context.drawImage(e.baseTexture.source,e._frame.x*f,e._frame.y*f,n*f,i*f,s*r.resolution,h*r.resolution,n*r.resolution,i*r.resolution)}},t.prototype.destroy=function(){this.renderer=null},t}();r.default=d,s.default.registerPlugin("sprite",d)},{"../../const":46,"../../math":70,"../../renderers/canvas/CanvasRenderer":77,"./CanvasTinter":104}],104:[function(t,e,r){"use strict";r.__esModule=!0;var n=t("../../utils"),i=t("../../renderers/canvas/utils/canUseNewCanvasBlendModes"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s={getTintedTexture:function(t,e){var r=t._texture;e=s.roundColor(e);var n="#"+("00000"+(0|e).toString(16)).substr(-6);r.tintCache=r.tintCache||{};var i=r.tintCache[n],o=void 0;if(i){if(i.tintId===r._updateID)return r.tintCache[n];o=r.tintCache[n]}else o=s.canvas||document.createElement("canvas");if(s.tintMethod(r,e,o),o.tintId=r._updateID,s.convertTintToImage){var a=new Image;a.src=o.toDataURL(),r.tintCache[n]=a}else r.tintCache[n]=o,s.canvas=null;return o},tintWithMultiply:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="multiply",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},tintWithOverlay:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.globalCompositeOperation="copy",n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height)},tintWithPerPixel:function(t,e,r){var i=r.getContext("2d"),o=t._frame.clone(),s=t.baseTexture.resolution;o.x*=s,o.y*=s,o.width*=s,o.height*=s,r.width=Math.ceil(o.width),r.height=Math.ceil(o.height),i.globalCompositeOperation="copy",i.drawImage(t.baseTexture.source,o.x,o.y,o.width,o.height,0,0,o.width,o.height);for(var a=(0,n.hex2rgb)(e),u=a[0],h=a[1],l=a[2],c=i.getImageData(0,0,o.width,o.height),d=c.data,f=0;f=this.size&&this.flush(),t._texture._uvs&&(this.sprites[this.currentIndex++]=t)},e.prototype.flush=function(){if(0!==this.currentIndex){var t=this.renderer.gl,e=this.MAX_TEXTURES,r=S.default.nextPow2(this.currentIndex),n=S.default.log2(r),i=this.buffers[n],o=this.sprites,s=this.groups,a=i.float32View,u=i.uint32View,h=this.boundTextures,l=this.renderer.boundTextures,c=this.renderer.textureGC.count,d=0,f=void 0,p=void 0,v=1,y=0,g=s[0],m=void 0,_=void 0,T=x.premultiplyBlendMode[o[0]._texture.baseTexture.premultipliedAlpha?1:0][o[0].blendMode];g.textureCount=0,g.start=0,g.blend=T,O++;var E=void 0;for(E=0;E0&&(e+="\nelse "),r0&&(r.shadowColor=e.dropShadowColor);for(var f=Math.cos(e.dropShadowAngle)*e.dropShadowDistance,p=Math.sin(e.dropShadowAngle)*e.dropShadowDistance,v=0;v3&&void 0!==arguments[3]&&arguments[3],i=this._style,o=i.letterSpacing;if(0===o)return void(n?this.context.strokeText(t,e,r):this.context.fillText(t,e,r));for(var s=String.prototype.split.call(t,""),a=e,u=0,h="";u3&&void 0!==arguments[3]?arguments[3]:t._canvas;n=n||r.wordWrap;var o=r.toFontString(),s=t.measureFont(o),a=i.getContext("2d");a.font=o;for(var u=n?t.wordWrap(e,r,i):e,h=u.split(/(?:\r\n|\r|\n)/),l=new Array(h.length),c=0,d=0;d2&&void 0!==arguments[2]?arguments[2]:t._canvas,i=n.getContext("2d"),o="",s=e.split("\n"),a=r.wordWrapWidth,u={},h=0;ha)for(var p=c[d].split(""),v=0;vl?(o+="\n"+y,l=a-g):(0===v&&(o+=" "),o+=y,l-=g)}else{var m=f+i.measureText(" ").width;0===d||m>l?(d>0&&(o+="\n"),o+=c[d],l=a-f):(l-=m,o+=" "+c[d])}}hs;--c){for(var v=0;v=0;r--){var n=e[r].trim();/([\"\'])[^\'\"]+\1/.test(n)||(n='"'+n+'"'),e[r]=n}return this.fontStyle+" "+this.fontVariant+" "+this.fontWeight+" "+t+" "+e.join(",")},a(t,[{key:"align",get:function(){return this._align},set:function(t){this._align!==t&&(this._align=t,this.styleID++)}},{key:"breakWords",get:function(){return this._breakWords},set:function(t){this._breakWords!==t&&(this._breakWords=t,this.styleID++)}},{key:"dropShadow",get:function(){return this._dropShadow},set:function(t){this._dropShadow!==t&&(this._dropShadow=t,this.styleID++)}},{key:"dropShadowAlpha",get:function(){return this._dropShadowAlpha},set:function(t){this._dropShadowAlpha!==t&&(this._dropShadowAlpha=t,this.styleID++)}},{key:"dropShadowAngle",get:function(){return this._dropShadowAngle},set:function(t){this._dropShadowAngle!==t&&(this._dropShadowAngle=t,this.styleID++)}},{key:"dropShadowBlur",get:function(){return this._dropShadowBlur},set:function(t){this._dropShadowBlur!==t&&(this._dropShadowBlur=t,this.styleID++)}},{key:"dropShadowColor",get:function(){return this._dropShadowColor},set:function(t){var e=o(t);this._dropShadowColor!==e&&(this._dropShadowColor=e,this.styleID++)}},{key:"dropShadowDistance",get:function(){return this._dropShadowDistance},set:function(t){this._dropShadowDistance!==t&&(this._dropShadowDistance=t,this.styleID++)}},{key:"fill",get:function(){return this._fill},set:function(t){var e=o(t);this._fill!==e&&(this._fill=e,this.styleID++)}},{key:"fillGradientType",get:function(){return this._fillGradientType},set:function(t){this._fillGradientType!==t&&(this._fillGradientType=t,this.styleID++)}},{key:"fillGradientStops",get:function(){return this._fillGradientStops},set:function(t){s(this._fillGradientStops,t)||(this._fillGradientStops=t,this.styleID++)}},{key:"fontFamily",get:function(){return this._fontFamily},set:function(t){this.fontFamily!==t&&(this._fontFamily=t,this.styleID++)}},{key:"fontSize",get:function(){return this._fontSize},set:function(t){this._fontSize!==t&&(this._fontSize=t,this.styleID++)}},{key:"fontStyle",get:function(){return this._fontStyle},set:function(t){this._fontStyle!==t&&(this._fontStyle=t,this.styleID++)}},{key:"fontVariant",get:function(){return this._fontVariant},set:function(t){this._fontVariant!==t&&(this._fontVariant=t,this.styleID++)}},{key:"fontWeight",get:function(){return this._fontWeight},set:function(t){this._fontWeight!==t&&(this._fontWeight=t,this.styleID++)}},{key:"letterSpacing",get:function(){return this._letterSpacing},set:function(t){this._letterSpacing!==t&&(this._letterSpacing=t,this.styleID++)}},{key:"lineHeight",get:function(){return this._lineHeight},set:function(t){this._lineHeight!==t&&(this._lineHeight=t,this.styleID++)}},{key:"lineJoin",get:function(){return this._lineJoin},set:function(t){this._lineJoin!==t&&(this._lineJoin=t,this.styleID++)}},{key:"miterLimit",get:function(){return this._miterLimit},set:function(t){this._miterLimit!==t&&(this._miterLimit=t,this.styleID++)}},{key:"padding",get:function(){return this._padding},set:function(t){this._padding!==t&&(this._padding=t,this.styleID++)}},{key:"stroke",get:function(){return this._stroke},set:function(t){var e=o(t);this._stroke!==e&&(this._stroke=e,this.styleID++)}},{key:"strokeThickness",get:function(){return this._strokeThickness},set:function(t){this._strokeThickness!==t&&(this._strokeThickness=t,this.styleID++)}},{key:"textBaseline",get:function(){return this._textBaseline},set:function(t){this._textBaseline!==t&&(this._textBaseline=t,this.styleID++)}},{key:"trim",get:function(){return this._trim},set:function(t){this._trim!==t&&(this._trim=t,this.styleID++)}},{key:"wordWrap",get:function(){return this._wordWrap},set:function(t){this._wordWrap!==t&&(this._wordWrap=t,this.styleID++)}},{key:"wordWrapWidth",get:function(){return this._wordWrapWidth},set:function(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this.styleID++)}}]),t}();r.default=c},{"../const":46,"../utils":124}],111:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("./BaseTexture"),u=n(a),h=t("../settings"),l=n(h),c=function(t){function e(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,s=arguments[2],a=arguments[3];i(this,e);var u=o(this,t.call(this,null,s));return u.resolution=a||l.default.RESOLUTION,u.width=r,u.height=n,u.realWidth=u.width*u.resolution,u.realHeight=u.height*u.resolution,u.scaleMode=void 0!==s?s:l.default.SCALE_MODE,u.hasLoaded=!0,u._glRenderTargets={},u._canvasRenderTarget=null,u.valid=!1,u}return s(e,t),e.prototype.resize=function(t,e){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.realWidth=this.width*this.resolution,this.realHeight=this.height*this.resolution,this.valid&&this.emit("update",this))},e.prototype.destroy=function(){t.prototype.destroy.call(this,!0),this.renderer=null},e}(u.default);r.default=c},{"../settings":101,"./BaseTexture":112}],112:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../utils"),u=t("../settings"),h=n(u),l=t("eventemitter3"),c=n(l),d=t("../utils/determineCrossOrigin"),f=n(d),p=t("bit-twiddle"),v=n(p),y=function(t){function e(r,n,s){i(this,e);var u=o(this,t.call(this));return u.uid=(0,a.uid)(),u.touched=0,u.resolution=s||h.default.RESOLUTION,u.width=100,u.height=100,u.realWidth=100,u.realHeight=100,u.scaleMode=void 0!==n?n:h.default.SCALE_MODE,u.hasLoaded=!1,u.isLoading=!1,u.source=null,u.origSource=null,u.imageType=null,u.sourceScale=1,u.premultipliedAlpha=!0,u.imageUrl=null,u.isPowerOfTwo=!1,u.mipmap=h.default.MIPMAP_TEXTURES,u.wrapMode=h.default.WRAP_MODE,u._glTextures={},u._enabled=0,u._virtalBoundId=-1,u._destroyed=!1,u.textureCacheIds=[],r&&u.loadSource(r),u}return s(e,t),e.prototype.update=function(){"svg"!==this.imageType&&(this.realWidth=this.source.naturalWidth||this.source.videoWidth||this.source.width,this.realHeight=this.source.naturalHeight||this.source.videoHeight||this.source.height,this._updateDimensions()),this.emit("update",this)},e.prototype._updateDimensions=function(){this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=v.default.isPow2(this.realWidth)&&v.default.isPow2(this.realHeight)},e.prototype.loadSource=function(t){var e=this.isLoading;this.hasLoaded=!1,this.isLoading=!1,e&&this.source&&(this.source.onload=null,this.source.onerror=null);var r=!this.source;if(this.source=t,(t.src&&t.complete||t.getContext)&&t.width&&t.height)this._updateImageType(),"svg"===this.imageType?this._loadSvgSource():this._sourceLoaded(),r&&this.emit("loaded",this);else if(!t.getContext){this.isLoading=!0;var n=this;if(t.onload=function(){if(n._updateImageType(),t.onload=null,t.onerror=null,n.isLoading){if(n.isLoading=!1,n._sourceLoaded(),"svg"===n.imageType)return void n._loadSvgSource();n.emit("loaded",n)}},t.onerror=function(){t.onload=null,t.onerror=null,n.isLoading&&(n.isLoading=!1,n.emit("error",n))},t.complete&&t.src){if(t.onload=null,t.onerror=null,"svg"===n.imageType)return void n._loadSvgSource();this.isLoading=!1,t.width&&t.height?(this._sourceLoaded(),e&&this.emit("loaded",this)):e&&this.emit("error",this)}}},e.prototype._updateImageType=function(){if(this.imageUrl){var t=(0,a.decomposeDataUri)(this.imageUrl),e=void 0;if(t&&"image"===t.mediaType){var r=t.subType.split("+")[0];if(!(e=(0,a.getUrlFileExtension)("."+r)))throw new Error("Invalid image type in data URI.")}else(e=(0,a.getUrlFileExtension)(this.imageUrl))||(e="png");this.imageType=e}},e.prototype._loadSvgSource=function(){if("svg"===this.imageType){var t=(0,a.decomposeDataUri)(this.imageUrl);t?this._loadSvgSourceUsingDataUri(t):this._loadSvgSourceUsingXhr()}},e.prototype._loadSvgSourceUsingDataUri=function(t){var e=void 0;if("base64"===t.encoding){if(!atob)throw new Error("Your browser doesn't support base64 conversions.");e=atob(t.data)}else e=t.data;this._loadSvgSourceUsingString(e)},e.prototype._loadSvgSourceUsingXhr=function(){var t=this,e=new XMLHttpRequest;e.onload=function(){if(e.readyState!==e.DONE||200!==e.status)throw new Error("Failed to load SVG using XHR.");t._loadSvgSourceUsingString(e.response)},e.onerror=function(){return t.emit("error",t)},e.open("GET",this.imageUrl,!0),e.send()},e.prototype._loadSvgSourceUsingString=function(t){var r=(0,a.getSvgSize)(t),n=r.width,i=r.height;if(!n||!i)throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them.");this.realWidth=Math.round(n*this.sourceScale),this.realHeight=Math.round(i*this.sourceScale),this._updateDimensions();var o=document.createElement("canvas");o.width=this.realWidth,o.height=this.realHeight,o._pixiId="canvas_"+(0,a.uid)(),o.getContext("2d").drawImage(this.source,0,0,n,i,0,0,this.realWidth,this.realHeight),this.origSource=this.source,this.source=o,e.addToCache(this,o._pixiId),this.isLoading=!1,this._sourceLoaded(),this.emit("loaded",this)},e.prototype._sourceLoaded=function(){this.hasLoaded=!0,this.update()},e.prototype.destroy=function(){this.imageUrl&&(delete a.TextureCache[this.imageUrl],this.imageUrl=null,navigator.isCocoonJS||(this.source.src="")),this.source=null,this.dispose(),e.removeFromCache(this),this.textureCacheIds=null,this._destroyed=!0},e.prototype.dispose=function(){this.emit("dispose",this)},e.prototype.updateSourceImage=function(t){this.source.src=t,this.loadSource(this.source)},e.fromImage=function(t,r,n,i){var o=a.BaseTextureCache[t];if(!o){var s=new Image;void 0===r&&0!==t.indexOf("data:")?s.crossOrigin=(0,f.default)(t):r&&(s.crossOrigin="string"==typeof r?r:"anonymous"),o=new e(s,n),o.imageUrl=t,i&&(o.sourceScale=i),o.resolution=(0,a.getResolutionOfUrl)(t),s.src=t,e.addToCache(o,t)}return o},e.fromCanvas=function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"canvas";t._pixiId||(t._pixiId=n+"_"+(0,a.uid)());var i=a.BaseTextureCache[t._pixiId];return i||(i=new e(t,r),e.addToCache(i,t._pixiId)),i},e.from=function(t,r,n){if("string"==typeof t)return e.fromImage(t,void 0,r,n);if(t instanceof HTMLImageElement){var i=t.src,o=a.BaseTextureCache[i];return o||(o=new e(t,r),o.imageUrl=i,n&&(o.sourceScale=n),o.resolution=(0,a.getResolutionOfUrl)(i),e.addToCache(o,i)),o}return t instanceof HTMLCanvasElement?e.fromCanvas(t,r):t},e.addToCache=function(t,e){e&&(-1===t.textureCacheIds.indexOf(e)&&t.textureCacheIds.push(e),a.BaseTextureCache[e]=t)},e.removeFromCache=function(t){if("string"==typeof t){var e=a.BaseTextureCache[t];if(e){var r=e.textureCacheIds.indexOf(t);return r>-1&&e.textureCacheIds.splice(r,1),delete a.BaseTextureCache[t],e}}else if(t&&t.textureCacheIds){for(var n=0;n0&&e>0,this._frame.width=this.orig.width=t,this._frame.height=this.orig.height=e,r||this.baseTexture.resize(t,e),this._updateUvs()},e.create=function(t,r,n,i){return new e(new u.default(t,r,n,i))},e}(l.default);r.default=c},{"./BaseRenderTexture":111,"./Texture":115}],114:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:null;n(this,t),this.baseTexture=e,this.textures={},this.data=r,this.resolution=this._updateResolution(i||this.baseTexture.imageUrl),this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}return i(t,null,[{key:"BATCH_SIZE",get:function(){return 1e3}}]),t.prototype._updateResolution=function(t){var e=this.data.meta.scale,r=(0,s.getResolutionOfUrl)(t,null);return null===r&&(r=void 0!==e?parseFloat(e):1),1!==r&&(this.baseTexture.resolution=r,this.baseTexture.update()),r},t.prototype.parse=function(e){this._batchIndex=0,this._callback=e,this._frameKeys.length<=t.BATCH_SIZE?(this._processFrames(0),this._parseComplete()):this._nextBatch()},t.prototype._processFrames=function(e){for(var r=e,n=t.BATCH_SIZE;r-e0&&void 0!==arguments[0]&&arguments[0];for(var e in this.textures)this.textures[e].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,t&&this.baseTexture.destroy(),this.baseTexture=null},t}();r.default=a},{"../":65,"../utils":124}],115:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t){t.destroy=function(){},t.on=function(){},t.once=function(){},t.emit=function(){}}r.__esModule=!0;var u=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:"canvas";return new e(l.default.fromCanvas(t,r,n))},e.fromVideo=function(t,r){return"string"==typeof t?e.fromVideoUrl(t,r):new e(d.default.fromVideo(t,r))},e.fromVideoUrl=function(t,r){return new e(d.default.fromUrl(t,r))},e.from=function(t){if("string"==typeof t){var r=m.TextureCache[t];if(!r){return null!==t.match(/\.(mp4|webm|ogg|h264|avi|mov)$/)?e.fromVideoUrl(t):e.fromImage(t)}return r}return t instanceof HTMLImageElement?new e(l.default.from(t)):t instanceof HTMLCanvasElement?e.fromCanvas(t,b.default.SCALE_MODE,"HTMLCanvasElement"):t instanceof HTMLVideoElement?e.fromVideo(t):t instanceof l.default?new e(t):t},e.fromLoader=function(t,r,n){var i=new l.default(t,void 0,(0,m.getResolutionOfUrl)(r)),o=new e(i);return i.imageUrl=r,n||(n=r),l.default.addToCache(o.baseTexture,n),e.addToCache(o,n),n!==r&&(l.default.addToCache(o.baseTexture,r),e.addToCache(o,r)),o},e.addToCache=function(t,e){e&&(-1===t.textureCacheIds.indexOf(e)&&t.textureCacheIds.push(e),m.TextureCache[e]=t)},e.removeFromCache=function(t){if("string"==typeof t){var e=m.TextureCache[t];if(e){var r=e.textureCacheIds.indexOf(t);return r>-1&&e.textureCacheIds.splice(r,1),delete m.TextureCache[t],e}}else if(t&&t.textureCacheIds){for(var n=0;nthis.baseTexture.width||t.y+t.height>this.baseTexture.height)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions: X: "+t.x+" + "+t.width+" = "+(t.x+t.width)+" > "+this.baseTexture.width+" Y: "+t.y+" + "+t.height+" = "+(t.y+t.height)+" > "+this.baseTexture.height);this.valid=t&&t.width&&t.height&&this.baseTexture.hasLoaded,this.trim||this.rotate||(this.orig=t),this.valid&&this._updateUvs()}},{key:"rotate",get:function(){return this._rotate},set:function(t){this._rotate=t,this.valid&&this._updateUvs()}},{key:"width",get:function(){return this.orig.width}},{key:"height",get:function(){return this.orig.height}}]),e}(y.default);r.default=x,x.EMPTY=new x(new l.default),a(x.EMPTY),a(x.EMPTY.baseTexture),x.WHITE=function(){var t=document.createElement("canvas");t.width=10,t.height=10;var e=t.getContext("2d");return e.fillStyle="white",e.fillRect(0,0,10,10),new x(new l.default(t))}(),a(x.WHITE),a(x.WHITE.baseTexture)},{"../math":70,"../settings":101,"../utils":124,"./BaseTexture":112,"./TextureUvs":116,"./VideoBaseTexture":117,eventemitter3:3}],116:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0 +;var i=t("../math/GroupD8"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=function(){function t(){n(this,t),this.x0=0,this.y0=0,this.x1=1,this.y1=0,this.x2=1,this.y2=1,this.x3=0,this.y3=1,this.uvsUint32=new Uint32Array(4)}return t.prototype.set=function(t,e,r){var n=e.width,i=e.height;if(r){var s=t.width/2/n,a=t.height/2/i,u=t.x/n+s,h=t.y/i+a;r=o.default.add(r,o.default.NW),this.x0=u+s*o.default.uX(r),this.y0=h+a*o.default.uY(r),r=o.default.add(r,2),this.x1=u+s*o.default.uX(r),this.y1=h+a*o.default.uY(r),r=o.default.add(r,2),this.x2=u+s*o.default.uX(r),this.y2=h+a*o.default.uY(r),r=o.default.add(r,2),this.x3=u+s*o.default.uX(r),this.y3=h+a*o.default.uY(r)}else this.x0=t.x/n,this.y0=t.y/i,this.x1=(t.x+t.width)/n,this.y1=t.y/i,this.x2=(t.x+t.width)/n,this.y2=(t.y+t.height)/i,this.x3=t.x/n,this.y3=(t.y+t.height)/i;this.uvsUint32[0]=(65535*this.y0&65535)<<16|65535*this.x0&65535,this.uvsUint32[1]=(65535*this.y1&65535)<<16|65535*this.x1&65535,this.uvsUint32[2]=(65535*this.y2&65535)<<16|65535*this.x2&65535,this.uvsUint32[3]=(65535*this.y3&65535)<<16|65535*this.x3&65535},t}();r.default=s},{"../math/GroupD8":66}],117:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function s(t,e){e||(e="video/"+t.substr(t.lastIndexOf(".")+1));var r=document.createElement("source");return r.src=t,r.type=e,r}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r0&&!1===t.paused&&!1===t.ended&&t.readyState>2},e.prototype._isSourceReady=function(){return 3===this.source.readyState||4===this.source.readyState},e.prototype._onPlayStart=function(){this.hasLoaded||this._onCanPlay(),!this._isAutoUpdating&&this.autoUpdate&&(c.shared.add(this.update,this,d.UPDATE_PRIORITY.HIGH),this._isAutoUpdating=!0)},e.prototype._onPlayStop=function(){this._isAutoUpdating&&(c.shared.remove(this.update,this),this._isAutoUpdating=!1)},e.prototype._onCanPlay=function(){this.hasLoaded=!0,this.source&&(this.source.removeEventListener("canplay",this._onCanPlay),this.source.removeEventListener("canplaythrough",this._onCanPlay),this.width=this.source.videoWidth,this.height=this.source.videoHeight,this.__loaded||(this.__loaded=!0,this.emit("loaded",this)),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.source.play())},e.prototype.destroy=function(){this._isAutoUpdating&&c.shared.remove(this.update,this),this.source&&this.source._pixiId&&(h.default.removeFromCache(this.source._pixiId),delete this.source._pixiId),t.prototype.destroy.call(this)},e.fromVideo=function(t,r){t._pixiId||(t._pixiId="video_"+(0,l.uid)());var n=l.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),h.default.addToCache(n,t._pixiId)),n},e.fromUrl=function(t,r){var n=document.createElement("video");if(n.setAttribute("webkit-playsinline",""),n.setAttribute("playsinline",""),Array.isArray(t))for(var i=0;i2&&void 0!==arguments[2]?arguments[2]:u.UPDATE_PRIORITY.NORMAL;return this._addListener(new l.default(t,e,r))},t.prototype.addOnce=function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:u.UPDATE_PRIORITY.NORMAL;return this._addListener(new l.default(t,e,r,!0))},t.prototype._addListener=function(t){var e=this._head.next,r=this._head;if(e){for(;e;){if(t.priority>e.priority){t.connect(r);break}r=e,e=e.next}t.previous||t.connect(r)}else t.connect(r);return this._startIfPossible(),this},t.prototype.remove=function(t,e){for(var r=this._head.next;r;)r=r.match(t,e)?r.destroy():r.next;return this._head.next||this._cancelIfNeeded(),this},t.prototype.start=function(){this.started||(this.started=!0,this._requestIfNeeded())},t.prototype.stop=function(){this.started&&(this.started=!1,this._cancelIfNeeded())},t.prototype.destroy=function(){this.stop();for(var t=this._head.next;t;)t=t.destroy(!0);this._head.destroy(),this._head=null},t.prototype.update=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:performance.now(),e=void 0;if(t>this.lastTime){e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),this.deltaTime=e*a.default.TARGET_FPMS*this.speed;for(var r=this._head,n=r.next;n;)n=n.emit(this.deltaTime);r.next||this._cancelIfNeeded()}else this.deltaTime=this.elapsedMS=0;this.lastTime=t},o(t,[{key:"FPS",get:function(){return 1e3/this.elapsedMS}},{key:"minFPS",get:function(){return 1e3/this._maxElapsedMS},set:function(t){var e=Math.min(Math.max(0,t)/1e3,a.default.TARGET_FPMS);this._maxElapsedMS=1/e}}]),t}();r.default=c},{"../const":46,"../settings":101,"./TickerListener":119}],119:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];n(this,t),this.fn=e,this.context=r,this.priority=i,this.once=o,this.next=null,this.previous=null,this._destroyed=!1}return t.prototype.match=function(t,e){return e=e||null,this.fn===t&&this.context===e},t.prototype.emit=function(t){this.fn&&(this.context?this.fn.call(this.context,t):this.fn(t));var e=this.next;return this.once&&this.destroy(!0),this._destroyed&&(this.next=null),e},t.prototype.connect=function(t){this.previous=t,t.next&&(t.next.previous=this),this.next=t.next,t.next=this},t.prototype.destroy=function(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._destroyed=!0,this.fn=null,this.context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);var e=this.previous;return this.next=t?null:e,this.previous=null,e},t}();r.default=i},{}],120:[function(t,e,r){"use strict";r.__esModule=!0,r.Ticker=r.shared=void 0;var n=t("./Ticker"),i=function(t){return t&&t.__esModule?t:{default:t}}(n),o=new i.default;o.autoStart=!0,o.destroy=function(){},r.shared=o,r.Ticker=i.default},{"./Ticker":118}],121:[function(t,e,r){"use strict";function n(){return!(!!navigator.platform&&/iPad|iPhone|iPod/.test(navigator.platform))}r.__esModule=!0,r.default=n},{}],122:[function(t,e,r){"use strict";function n(t){for(var e=6*t,r=new Uint16Array(e),n=0,i=0;n1&&void 0!==arguments[1]?arguments[1]:window.location;if(0===t.indexOf("data:"))return"";e=e||window.location,s||(s=document.createElement("a")),s.href=t,t=o.default.parse(s.href);var r=!t.port&&""===e.port||t.port===e.port;return t.hostname===e.hostname&&r&&t.protocol===e.protocol?"":"anonymous"}r.__esModule=!0,r.default=n;var i=t("url"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=void 0},{url:29}],124:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(){return++k}function s(t,e){return e=e||[],e[0]=(t>>16&255)/255,e[1]=(t>>8&255)/255,e[2]=(255&t)/255,e}function a(t){return t=t.toString(16),"#"+(t="000000".substr(0,6-t.length)+t)}function u(t){return(255*t[0]<<16)+(255*t[1]<<8)+(255*t[2]|0)}function h(t,e){var r=S.default.RETINA_PREFIX.exec(t);return r?parseFloat(r[1]):void 0!==e?e:1}function l(t){var e=w.DATA_URI.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,encoding:e[3]?e[3].toLowerCase():void 0,data:e[4]}}function c(t){var e=w.URL_FILE_EXTENSION.exec(t);if(e)return e[1].toLowerCase()}function d(t){var e=w.SVG_SIZE.exec(t),r={};return e&&(r[e[1]]=Math.round(parseFloat(e[3])),r[e[5]]=Math.round(parseFloat(e[7]))),r}function f(){j=!0}function p(t){if(!j){if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var e=["\n %c %c %c PixiJS "+w.VERSION+" - ✰ "+t+" ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n","background: #ff66a5; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff66a5; background: #030307; padding:5px 0;","background: #ff66a5; padding:5px 0;","background: #ffc3dc; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;"];window.console.log.apply(console,e)}else window.console&&window.console.log("PixiJS "+w.VERSION+" - "+t+" - http://www.pixijs.com/");j=!0}}function v(){var t={stencil:!0,failIfMajorPerformanceCaveat:!0};try{if(!window.WebGLRenderingContext)return!1;var e=document.createElement("canvas"),r=e.getContext("webgl",t)||e.getContext("experimental-webgl",t),n=!(!r||!r.getContextAttributes().stencil);if(r){var i=r.getExtension("WEBGL_lose_context");i&&i.loseContext()}return r=null,n}catch(t){return!1}}function y(t){return 0===t?0:t<0?-1:1}function g(){var t=void 0;for(t in U)U[t].destroy();for(t in X)X[t].destroy()}function m(){var t=void 0;for(t in U)delete U[t];for(t in X)delete X[t]}function _(t,e){return G[e?1:0][t]}function b(t,e){if(1===e)return(255*e<<24)+t;if(0===e)return 0;var r=t>>16&255,n=t>>8&255,i=255&t;return r=r*e+.5|0,n=n*e+.5|0,i=i*e+.5|0,(255*e<<24)+(r<<16)+(n<<8)+i}function x(t,e,r,n){return r=r||new Float32Array(4),n||void 0===n?(r[0]=t[0]*e,r[1]=t[1]*e,r[2]=t[2]*e):(r[0]=t[0],r[1]=t[1],r[2]=t[2]),r[3]=e,r}function T(t,e,r,n){return r=r||new Float32Array(4),r[0]=(t>>16&255)/255,r[1]=(t>>8&255)/255,r[2]=(255&t)/255,(n||void 0===n)&&(r[0]*=e,r[1]*=e,r[2]*=e),r[3]=e,r}r.__esModule=!0,r.premultiplyBlendMode=r.BaseTextureCache=r.TextureCache=r.mixins=r.pluginTarget=r.EventEmitter=r.removeItems=r.isMobile=void 0,r.uid=o,r.hex2rgb=s,r.hex2string=a,r.rgb2hex=u,r.getResolutionOfUrl=h,r.decomposeDataUri=l,r.getUrlFileExtension=c,r.getSvgSize=d,r.skipHello=f,r.sayHello=p,r.isWebGLSupported=v,r.sign=y,r.destroyTextureCache=g,r.clearTextureCache=m,r.correctBlendMode=_,r.premultiplyTint=b,r.premultiplyRgba=x,r.premultiplyTintToRgba=T;var w=t("../const"),E=t("../settings"),S=i(E),O=t("eventemitter3"),P=i(O),M=t("./pluginTarget"),C=i(M),R=t("./mixin"),A=n(R),I=t("ismobilejs"),D=n(I),L=t("remove-array-items"),N=i(L),F=t("./mapPremultipliedBlendModes"),B=i(F),k=0,j=!1;r.isMobile=D,r.removeItems=N.default,r.EventEmitter=P.default,r.pluginTarget=C.default,r.mixins=A;var U=r.TextureCache=Object.create(null),X=r.BaseTextureCache=Object.create(null),G=r.premultiplyBlendMode=(0,B.default)()},{"../const":46,"../settings":101,"./mapPremultipliedBlendModes":125,"./mixin":127,"./pluginTarget":128,eventemitter3:3,ismobilejs:4,"remove-array-items":31}],125:[function(t,e,r){"use strict";function n(){for(var t=[],e=[],r=0;r<32;r++)t[r]=r,e[r]=r;t[i.BLEND_MODES.NORMAL_NPM]=i.BLEND_MODES.NORMAL,t[i.BLEND_MODES.ADD_NPM]=i.BLEND_MODES.ADD,t[i.BLEND_MODES.SCREEN_NPM]=i.BLEND_MODES.SCREEN,e[i.BLEND_MODES.NORMAL]=i.BLEND_MODES.NORMAL_NPM,e[i.BLEND_MODES.ADD]=i.BLEND_MODES.ADD_NPM,e[i.BLEND_MODES.SCREEN]=i.BLEND_MODES.SCREEN_NPM;var n=[];return n.push(e),n.push(t),n}r.__esModule=!0,r.default=n;var i=t("../const")},{"../const":46}],126:[function(t,e,r){"use strict";function n(t){return o.default.tablet||o.default.phone?4:t}r.__esModule=!0,r.default=n;var i=t("ismobilejs"),o=function(t){return t&&t.__esModule?t:{default:t}}(i)},{ismobilejs:4}],127:[function(t,e,r){"use strict";function n(t,e){if(t&&e)for(var r=Object.keys(e),n=0;n1?this._fontStyle="italic":t.indexOf("oblique")>-1?this._fontStyle="oblique":this._fontStyle="normal",t.indexOf("small-caps")>-1?this._fontVariant="small-caps":this._fontVariant="normal";var e=t.split(" "),r=-1;this._fontSize=26;for(var i=0;i-1&&r=this._durations[this.currentFrame];)n-=this._durations[this.currentFrame]*i,this._currentTime+=i;this._currentTime+=n/this._durations[this.currentFrame]}else this._currentTime+=e;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):r!==this.currentFrame&&(this.loop&&this.onLoop&&(this.animationSpeed>0&&this.currentFramer&&this.onLoop()),this.updateTexture())},e.prototype.updateTexture=function(){this._texture=this._textures[this.currentFrame],this._textureID=-1,this.onFrameChange&&this.onFrameChange(this.currentFrame)},e.prototype.destroy=function(e){this.stop(),t.prototype.destroy.call(this,e)},e.fromFrames=function(t){for(var r=[],n=0;n1&&void 0!==arguments[1]?arguments[1]:{};i(this,e);var s=o(this,t.call(this));return s._textWidth=0,s._textHeight=0,s._glyphs=[],s._font={tint:void 0!==n.tint?n.tint:16777215,align:n.align||"left",name:null,size:0},s.font=n.font,s._text=r,s._maxWidth=0,s._maxLineHeight=0,s._anchor=new c.default(function(){s.dirty=!0},s,0,0),s.dirty=!1,s.updateText(),s}return s(e,t),e.prototype.updateText=function(){for(var t=e.fonts[this._font.name],r=this._font.size/t.size,n=new h.Point,i=[],o=[],s=null,a=0,u=0,l=0,c=-1,d=0,f=0,p=0,v=0;v0&&n.x*r>this._maxWidth)h.utils.removeItems(i,c-f,v-c),v=c,c=-1,++f,o.push(d),u=Math.max(u,d),l++,n.x=0,n.y+=t.lineHeight,s=null;else{var g=t.chars[y];g&&(s&&g.kerning[s]&&(n.x+=g.kerning[s]),i.push({texture:g.texture,line:l,charCode:y,position:new h.Point(n.x+g.xOffset,n.y+g.yOffset)}),a=n.x+(g.texture.width+g.xOffset),n.x+=g.xAdvance,p=Math.max(p,g.yOffset+g.texture.height),s=y)}}o.push(a),u=Math.max(u,a);for(var m=[],_=0;_<=l;_++){var b=0;"right"===this._font.align?b=u-o[_]:"center"===this._font.align&&(b=(u-o[_])/2),m.push(b)}for(var x=i.length,T=this.tint,w=0;w=0?t:16777215,this.dirty=!0}},{key:"align",get:function(){return this._font.align},set:function(t){this._font.align=t||"left",this.dirty=!0}},{key:"anchor",get:function(){return this._anchor},set:function(t){"number"==typeof t?this._anchor.set(t):this._anchor.copy(t)}},{key:"font",get:function(){return this._font},set:function(t){t&&("string"==typeof t?(t=t.split(" "),this._font.name=1===t.length?t[0]:t.slice(1).join(" "),this._font.size=t.length>=2?parseInt(t[0],10):e.fonts[this._font.name].size):(this._font.name=t.name,this._font.size="number"==typeof t.size?t.size:parseInt(t.size,10)),this.dirty=!0)}},{key:"text",get:function(){return this._text},set:function(t){t=t.toString()||" ",this._text!==t&&(this._text=t,this.dirty=!0)}},{key:"maxWidth",get:function(){return this._maxWidth},set:function(t){this._maxWidth!==t&&(this._maxWidth=t,this.dirty=!0)}},{key:"maxLineHeight",get:function(){return this.validate(),this._maxLineHeight}},{key:"textWidth",get:function(){return this.validate(),this._textWidth}},{key:"textHeight",get:function(){return this.validate(),this._textHeight}}]),e}(h.Container);r.default=p,p.fonts={}},{"../core":65,"../core/math/ObservablePoint":68,"../core/settings":101}],136:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:100,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:100;i(this,e);var a=o(this,t.call(this,r));return a.tileTransform=new h.TransformStatic,a._width=n,a._height=s,a._canvasPattern=null,a.uvTransform=r.transform||new f.default(r),a.pluginName="tilingSprite",a.uvRespectAnchor=!1,a}return s(e,t),e.prototype._onTextureUpdate=function(){this.uvTransform&&(this.uvTransform.texture=this._texture)},e.prototype._renderWebGL=function(t){var e=this._texture;e&&e.valid&&(this.tileTransform.updateLocalTransform(),this.uvTransform.update(),t.setObjectRenderer(t.plugins[this.pluginName]),t.plugins[this.pluginName].render(this))},e.prototype._renderCanvas=function(t){var e=this._texture;if(e.baseTexture.hasLoaded){var r=t.context,n=this.worldTransform,i=t.resolution,o=e.baseTexture,s=o.resolution,a=this.tilePosition.x/this.tileScale.x%e._frame.width*s,u=this.tilePosition.y/this.tileScale.y%e._frame.height*s;if(!this._canvasPattern){var l=new h.CanvasRenderTarget(e._frame.width,e._frame.height,s);16777215!==this.tint?(this.cachedTint!==this.tint&&(this.cachedTint=this.tint,this.tintedTexture=c.default.getTintedTexture(this,this.tint)),l.context.drawImage(this.tintedTexture,0,0)):l.context.drawImage(o.source,-e._frame.x*s,-e._frame.y*s),this._canvasPattern=l.context.createPattern(l.canvas,"repeat")}r.globalAlpha=this.worldAlpha,r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t.setBlendMode(this.blendMode),r.fillStyle=this._canvasPattern,r.scale(this.tileScale.x/s,this.tileScale.y/s);var d=this.anchor.x*-this._width,f=this.anchor.y*-this._height;this.uvRespectAnchor?(r.translate(a,u),r.fillRect(-a+d,-u+f,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s)):(r.translate(a+d,u+f),r.fillRect(-a,-u,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s))}},e.prototype._calculateBounds=function(){var t=this._width*-this._anchor._x,e=this._height*-this._anchor._y,r=this._width*(1-this._anchor._x),n=this._height*(1-this._anchor._y);this._bounds.addFrame(this.transform,t,e,r,n)},e.prototype.getLocalBounds=function(e){return 0===this.children.length?(this._bounds.minX=this._width*-this._anchor._x,this._bounds.minY=this._height*-this._anchor._y,this._bounds.maxX=this._width*(1-this._anchor._x),this._bounds.maxY=this._height*(1-this._anchor._x),e||(this._localBoundsRect||(this._localBoundsRect=new h.Rectangle),e=this._localBoundsRect),this._bounds.getRectangle(e)):t.prototype.getLocalBounds.call(this,e)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,p);var e=this._width,r=this._height,n=-e*this.anchor._x;if(p.x>=n&&p.x=i&&p.y0&&void 0!==arguments[0]?arguments[0]:new i.Point,e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.parent?this.parent.toGlobal(this.position,t,e):(t.x=this.position.x,t.y=this.position.y),t}},{"../core":65}],141:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.BitmapText=r.TilingSpriteRenderer=r.TilingSprite=r.TextureTransform=r.AnimatedSprite=void 0;var i=t("./AnimatedSprite");Object.defineProperty(r,"AnimatedSprite",{enumerable:!0,get:function(){return n(i).default}});var o=t("./TextureTransform");Object.defineProperty(r,"TextureTransform",{enumerable:!0,get:function(){return n(o).default}});var s=t("./TilingSprite");Object.defineProperty(r,"TilingSprite",{enumerable:!0,get:function(){return n(s).default}});var a=t("./webgl/TilingSpriteRenderer");Object.defineProperty(r,"TilingSpriteRenderer",{enumerable:!0,get:function(){return n(a).default}});var u=t("./BitmapText");Object.defineProperty(r,"BitmapText",{enumerable:!0,get:function(){return n(u).default}}),t("./cacheAsBitmap"),t("./getChildByName"),t("./getGlobalPosition")},{"./AnimatedSprite":134,"./BitmapText":135,"./TextureTransform":136,"./TilingSprite":137,"./cacheAsBitmap":138,"./getChildByName":139,"./getGlobalPosition":140,"./webgl/TilingSpriteRenderer":142}],142:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=t("../../core"),a=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(s),u=t("../../core/const"),h=(t("path"),new a.Matrix),l=function(t){function e(r){n(this,e);var o=i(this,t.call(this,r));return o.shader=null,o.simpleShader=null,o.quad=null,o}return o(e,t),e.prototype.onContextChange=function(){var t=this.renderer.gl;this.shader=new a.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n gl_FragColor = sample * uColor;\n}\n"),this.simpleShader=new a.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = sample * uColor;\n}\n"),this.renderer.bindVao(null),this.quad=new a.Quad(t,this.renderer.state.attribState),this.quad.initVao(this.shader)},e.prototype.render=function(t){var e=this.renderer,r=this.quad;e.bindVao(r.vao);var n=r.vertices;n[0]=n[6]=t._width*-t.anchor.x,n[1]=n[3]=t._height*-t.anchor.y,n[2]=n[4]=t._width*(1-t.anchor.x),n[5]=n[7]=t._height*(1-t.anchor.y),t.uvRespectAnchor&&(n=r.uvs,n[0]=n[6]=-t.anchor.x,n[1]=n[3]=-t.anchor.y,n[2]=n[4]=1-t.anchor.x,n[5]=n[7]=1-t.anchor.y),r.upload();var i=t._texture,o=i.baseTexture,s=t.tileTransform.localTransform,l=t.uvTransform,c=o.isPowerOfTwo&&i.frame.width===o.width&&i.frame.height===o.height;c&&(o._glTextures[e.CONTEXT_UID]?c=o.wrapMode!==u.WRAP_MODES.CLAMP:o.wrapMode===u.WRAP_MODES.CLAMP&&(o.wrapMode=u.WRAP_MODES.REPEAT));var d=c?this.simpleShader:this.shader;e.bindShader(d);var f=i.width,p=i.height,v=t._width,y=t._height;h.set(s.a*f/v,s.b*f/y,s.c*p/v,s.d*p/y,s.tx/v,s.ty/y),h.invert(),c?h.prepend(l.mapCoord):(d.uniforms.uMapCoord=l.mapCoord.toArray(!0),d.uniforms.uClampFrame=l.uClampFrame,d.uniforms.uClampOffset=l.uClampOffset),d.uniforms.uTransform=h.toArray(!0),d.uniforms.uColor=a.utils.premultiplyTintToRgba(t.tint,t.worldAlpha,d.uniforms.uColor,o.premultipliedAlpha),d.uniforms.translationMatrix=t.transform.worldTransform.toArray(!0),d.uniforms.uSampler=e.bindTexture(i),e.setBlendMode(a.utils.correctBlendMode(t.blendMode,o.premultipliedAlpha)),r.vao.draw(this.renderer.gl.TRIANGLES,6,0)},e}(a.ObjectRenderer);r.default=l,a.WebGLRenderer.registerPlugin("tilingSprite",l)},{"../../core":65,"../../core/const":46,path:23}],143:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r=r&&(u=t-h-1),l=l.replace("%value%",e[u]),s+=l,s+="\n"}return n=n.replace("%blur%",s),n=n.replace("%size%",t)}r.__esModule=!0,r.default=n;var i={5:[.153388,.221461,.250301],7:[.071303,.131514,.189879,.214607],9:[.028532,.067234,.124009,.179044,.20236],11:[.0093,.028002,.065984,.121703,.175713,.198596],13:[.002406,.009255,.027867,.065666,.121117,.174868,.197641],15:[489e-6,.002403,.009246,.02784,.065602,.120999,.174697,.197448]},o=["varying vec2 vBlurTexCoords[%size%];","uniform sampler2D uSampler;","void main(void)","{"," gl_FragColor = vec4(0.0);"," %blur%","}"].join("\n")},{}],147:[function(t,e,r){"use strict";function n(t,e){var r=Math.ceil(t/2),n=i,o="",s=void 0;s=e?"vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);":"vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);";for(var a=0;ae;)r-=2;return r}r.__esModule=!0,r.default=n},{}],149:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n"));return r.uniforms.m=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],r.alpha=1,r}return o(e,t),e.prototype._loadMatrix=function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t;e&&(this._multiply(r,this.uniforms.m,t),r=this._colorMatrix(r)),this.uniforms.m=r},e.prototype._multiply=function(t,e,r){return t[0]=e[0]*r[0]+e[1]*r[5]+e[2]*r[10]+e[3]*r[15],t[1]=e[0]*r[1]+e[1]*r[6]+e[2]*r[11]+e[3]*r[16],t[2]=e[0]*r[2]+e[1]*r[7]+e[2]*r[12]+e[3]*r[17],t[3]=e[0]*r[3]+e[1]*r[8]+e[2]*r[13]+e[3]*r[18],t[4]=e[0]*r[4]+e[1]*r[9]+e[2]*r[14]+e[3]*r[19]+e[4],t[5]=e[5]*r[0]+e[6]*r[5]+e[7]*r[10]+e[8]*r[15],t[6]=e[5]*r[1]+e[6]*r[6]+e[7]*r[11]+e[8]*r[16],t[7]=e[5]*r[2]+e[6]*r[7]+e[7]*r[12]+e[8]*r[17],t[8]=e[5]*r[3]+e[6]*r[8]+e[7]*r[13]+e[8]*r[18],t[9]=e[5]*r[4]+e[6]*r[9]+e[7]*r[14]+e[8]*r[19]+e[9],t[10]=e[10]*r[0]+e[11]*r[5]+e[12]*r[10]+e[13]*r[15],t[11]=e[10]*r[1]+e[11]*r[6]+e[12]*r[11]+e[13]*r[16],t[12]=e[10]*r[2]+e[11]*r[7]+e[12]*r[12]+e[13]*r[17],t[13]=e[10]*r[3]+e[11]*r[8]+e[12]*r[13]+e[13]*r[18],t[14]=e[10]*r[4]+e[11]*r[9]+e[12]*r[14]+e[13]*r[19]+e[14],t[15]=e[15]*r[0]+e[16]*r[5]+e[17]*r[10]+e[18]*r[15],t[16]=e[15]*r[1]+e[16]*r[6]+e[17]*r[11]+e[18]*r[16],t[17]=e[15]*r[2]+e[16]*r[7]+e[17]*r[12]+e[18]*r[17],t[18]=e[15]*r[3]+e[16]*r[8]+e[17]*r[13]+e[18]*r[18],t[19]=e[15]*r[4]+e[16]*r[9]+e[17]*r[14]+e[18]*r[19]+e[19],t},e.prototype._colorMatrix=function(t){var e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e},e.prototype.brightness=function(t,e){var r=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.greyscale=function(t,e){var r=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.blackAndWhite=function(t){var e=[.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.hue=function(t,e){t=(t||0)/180*Math.PI;var r=Math.cos(t),n=Math.sin(t),i=Math.sqrt,o=1/3,s=i(o),a=r+(1-r)*o,u=o*(1-r)-s*n,h=o*(1-r)+s*n,l=o*(1-r)+s*n,c=r+o*(1-r),d=o*(1-r)-s*n,f=o*(1-r)-s*n,p=o*(1-r)+s*n,v=r+o*(1-r),y=[a,u,h,0,0,l,c,d,0,0,f,p,v,0,0,0,0,0,1,0];this._loadMatrix(y,e)},e.prototype.contrast=function(t,e){var r=(t||0)+1,n=-.5*(r-1),i=[r,0,0,0,n,0,r,0,0,n,0,0,r,0,n,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.saturate=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=2*t/3+1,n=-.5*(r-1),i=[r,n,n,0,0,n,r,n,0,0,n,n,r,0,0,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.desaturate=function(){this.saturate(-1)},e.prototype.negative=function(t){var e=[0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.sepia=function(t){var e=[.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.technicolor=function(t){var e=[1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.polaroid=function(t){var e=[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.toBGR=function(t){var e=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.kodachrome=function(t){var e=[1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.browni=function(t){var e=[.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.vintage=function(t){var e=[.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.colorTone=function(t,e,r,n,i){t=t||.2,e=e||.15,r=r||16770432,n=n||3375104;var o=(r>>16&255)/255,s=(r>>8&255)/255,a=(255&r)/255,u=(n>>16&255)/255,h=(n>>8&255)/255,l=(255&n)/255,c=[.3,.59,.11,0,0,o,s,a,t,0,u,h,l,e,0,o-u,s-h,a-l,0,0];this._loadMatrix(c,i)},e.prototype.night=function(t,e){t=t||.1;var r=[-2*t,-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.predator=function(t,e){var r=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.lsd=function(t){var e=[2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.reset=function(){var t=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(t,!1)},s(e,[{key:"matrix",get:function(){return this.uniforms.m},set:function(t){this.uniforms.m=t}},{key:"alpha",get:function(){return this.uniforms.uAlpha},set:function(t){this.uniforms.uAlpha=t}}]),e}(u.Filter));r.default=h,h.prototype.grayscale=h.prototype.greyscale},{"../../core":65,path:23}],150:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n'))}return o(e,t),e}(a.Filter));r.default=u},{"../../core":65,path:23}],152:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./fxaa/FXAAFilter");Object.defineProperty(r,"FXAAFilter",{enumerable:!0,get:function(){return n(i).default}});var o=t("./noise/NoiseFilter");Object.defineProperty(r,"NoiseFilter",{enumerable:!0,get:function(){return n(o).default}});var s=t("./displacement/DisplacementFilter");Object.defineProperty(r,"DisplacementFilter",{enumerable:!0,get:function(){return n(s).default}});var a=t("./blur/BlurFilter");Object.defineProperty(r,"BlurFilter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./blur/BlurXFilter");Object.defineProperty(r,"BlurXFilter",{enumerable:!0,get:function(){return n(u).default}});var h=t("./blur/BlurYFilter");Object.defineProperty(r,"BlurYFilter",{enumerable:!0,get:function(){return n(h).default}});var l=t("./colormatrix/ColorMatrixFilter");Object.defineProperty(r,"ColorMatrixFilter",{enumerable:!0,get:function(){return n(l).default}});var c=t("./void/VoidFilter");Object.defineProperty(r,"VoidFilter",{enumerable:!0,get:function(){return n(c).default}})},{"./blur/BlurFilter":143,"./blur/BlurXFilter":144,"./blur/BlurYFilter":145,"./colormatrix/ColorMatrixFilter":149,"./displacement/DisplacementFilter":150,"./fxaa/FXAAFilter":151,"./noise/NoiseFilter":153,"./void/VoidFilter":154}],153:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:.5,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Math.random();n(this,e);var s=i(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n"));return s.noise=r,s.seed=o,s}return o(e,t),s(e,[{key:"noise",get:function(){return this.uniforms.uNoise},set:function(t){this.uniforms.uNoise=t}},{key:"seed",get:function(){return this.uniforms.uSeed},set:function(t){this.uniforms.uSeed=t}}]),e}(u.Filter));r.default=h},{"../../core":65,path:23}],154:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=t("../../core"),a=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(s),u=(t("path"),function(t){function e(){n(this,e);var r=i(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"));return r.glShaderKey="void",r}return o(e,t),e}(a.Filter));r.default=u},{"../../core":65,path:23}],155:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:1;this.removeEvents(),this.interactionDOMElement=t,this.resolution=e,this.addEvents()},e.prototype.addEvents=function(){this.interactionDOMElement&&(h.ticker.shared.add(this.update,this,h.UPDATE_PRIORITY.INTERACTION),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="none",this.interactionDOMElement.style["-ms-touch-action"]="none"):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]="none"),this.supportsPointerEvents?(window.document.addEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("pointerover",this.onPointerOver,!0),window.addEventListener("pointercancel",this.onPointerCancel,!0),window.addEventListener("pointerup",this.onPointerUp,!0)):(window.document.addEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onPointerOver,!0),window.addEventListener("mouseup",this.onPointerUp,!0)),this.supportsTouchEvents&&(this.interactionDOMElement.addEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.addEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.addEventListener("touchmove",this.onPointerMove,!0)),this.eventsAdded=!0)},e.prototype.removeEvents=function(){this.interactionDOMElement&&(h.ticker.shared.remove(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="",this.interactionDOMElement.style["-ms-touch-action"]=""):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]=""),this.supportsPointerEvents?(window.document.removeEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("pointerover",this.onPointerOver,!0),window.removeEventListener("pointercancel",this.onPointerCancel,!0),window.removeEventListener("pointerup",this.onPointerUp,!0)):(window.document.removeEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onPointerOver,!0),window.removeEventListener("mouseup",this.onPointerUp,!0)),this.supportsTouchEvents&&(this.interactionDOMElement.removeEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.removeEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onPointerMove,!0)),this.interactionDOMElement=null,this.eventsAdded=!1)},e.prototype.update=function(t){if(this._deltaTime+=t,!(this._deltaTime=0;h--){var l=u[h],c=this.processInteractive(t,l,r,n,a);if(c){if(!l.parent)continue;a=!1,c&&(t.target&&(n=!1),s=!0)}}return i&&(n&&!t.target&&(e.hitArea?(e.worldTransform.applyInverse(o,this._tempPoint),e.hitArea.contains(this._tempPoint.x,this._tempPoint.y)&&(s=!0)):e.containsPoint&&e.containsPoint(o)&&(s=!0)),e.interactive&&(s&&!t.target&&(t.target=e),r&&r(t,e,!!s))),s},e.prototype.onPointerDown=function(t){if(!this.supportsTouchEvents||"touch"!==t.pointerType){var e=this.normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&t.preventDefault();for(var r=e.length,n=0;n1&&(l=1);var c=Math.sqrt(n*n+i*i),d=this._texture.height/2;n/=c,i/=c,n*=d,i*=d,o[h]=u.x+n,o[h+1]=u.y+i,o[h+2]=u.x-n,o[h+3]=u.y-i,e=u}},e.prototype.updateTransform=function(){this.autoUpdate&&this.refreshVertices(),this.containerUpdateTransform()},e}(a.default);r.default=u},{"./Mesh":166}],170:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../core"),o=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(i),s=t("../Mesh"),a=function(t){return t&&t.__esModule?t:{default:t}}(s),u=function(){function t(e){n(this,t),this.renderer=e}return t.prototype.render=function(t){var e=this.renderer,r=e.context,n=t.worldTransform,i=e.resolution;e.roundPixels?r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i|0,n.ty*i|0):r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),e.setBlendMode(t.blendMode),t.drawMode===a.default.DRAW_MODES.TRIANGLE_MESH?this._renderTriangleMesh(t):this._renderTriangles(t)},t.prototype._renderTriangleMesh=function(t){for(var e=t.vertices.length/2,r=0;r0){var S=t.canvasPadding/t.worldTransform.a,O=t.canvasPadding/t.worldTransform.d,P=(_+b+x)/3,M=(T+w+E)/3,C=_-P,R=T-M,A=Math.sqrt(C*C+R*R);_=P+C/A*(A+S),T=M+R/A*(A+O),C=b-P,R=w-M,A=Math.sqrt(C*C+R*R),b=P+C/A*(A+S),w=M+R/A*(A+O),C=x-P,R=E-M,A=Math.sqrt(C*C+R*R),x=P+C/A*(A+S),E=M+R/A*(A+O)}i.save(),i.beginPath(),i.moveTo(_,T),i.lineTo(b,w),i.lineTo(x,E),i.closePath(),i.clip();var I=d*y+v*p+f*g-y*p-v*f-d*g,D=_*y+v*x+b*g-y*x-v*b-_*g,L=d*b+_*p+f*x-b*p-_*f-d*x,N=d*y*x+v*b*p+_*f*g-_*y*p-v*f*x-d*b*g,F=T*y+v*E+w*g-y*E-v*w-T*g,B=d*w+T*p+f*E-w*p-T*f-d*E,k=d*y*E+v*w*p+T*f*g-T*y*p-v*f*E-d*w*g;i.transform(D/I,F/I,L/I,B/I,N/I,k/I),i.drawImage(h,0,0,l*u.resolution,c*u.resolution,0,0,l,c),i.restore()}},t.prototype.renderMeshFlat=function(t){var e=this.renderer.context,r=t.vertices,n=r.length/2;e.beginPath();for(var i=1;i0&&void 0!==arguments[0]?arguments[0]:1500,o=arguments[1],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16384;n(this,e);var a=i(this,t.call(this));return s>16384&&(s=16384),s>r&&(s=r),a._properties=[!1,!0,!1,!1,!1],a._maxSize=r,a._batchSize=s,a._glBuffers={},a._bufferToUpdate=0,a.interactiveChildren=!1,a.blendMode=u.BLEND_MODES.NORMAL,a.roundPixels=!0,a.baseTexture=null,a.setProperties(o),a._tint=0,a.tintRgb=new Float32Array(4),a.tint=16777215,a}return o(e,t),e.prototype.setProperties=function(t){t&&(this._properties[0]="scale"in t?!!t.scale:this._properties[0],this._properties[1]="position"in t?!!t.position:this._properties[1],this._properties[2]="rotation"in t?!!t.rotation:this._properties[2],this._properties[3]="uvs"in t?!!t.uvs:this._properties[3],this._properties[4]="alpha"in t?!!t.alpha:this._properties[4])},e.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},e.prototype.renderWebGL=function(t){var e=this;this.visible&&!(this.worldAlpha<=0)&&this.children.length&&this.renderable&&(this.baseTexture||(this.baseTexture=this.children[0]._texture.baseTexture,this.baseTexture.hasLoaded||this.baseTexture.once("update",function(){return e.onChildrenChange(0)})),t.setObjectRenderer(t.plugins.particle),t.plugins.particle.render(this))},e.prototype.onChildrenChange=function(t){var e=Math.floor(t/this._batchSize);er&&(o=r);var s=t._glBuffers[i.CONTEXT_UID];s||(s=t._glBuffers[i.CONTEXT_UID]=this.generateBuffers(t));var a=e[0]._texture.baseTexture;this.renderer.setBlendMode(u.utils.correctBlendMode(t.blendMode,a.premultipliedAlpha));var h=i.gl,l=t.worldTransform.copy(this.tempMatrix);l.prepend(i._activeRenderTarget.projectionMatrix),this.shader.uniforms.projectionMatrix=l.toArray(!0),this.shader.uniforms.uColor=u.utils.premultiplyRgba(t.tintRgb,t.worldAlpha,this.shader.uniforms.uColor,a.premultipliedAlpha),this.shader.uniforms.uSampler=i.bindTexture(a);for(var c=0,d=0;cn&&(f=n);var p=s[d];p.uploadDynamic(e,c,f),t._bufferToUpdate===d&&(p.uploadStatic(e,c,f),t._bufferToUpdate=d+1),i.bindVao(p.vao),p.vao.draw(h.TRIANGLES,6*f)}}},e.prototype.generateBuffers=function(t){for(var e=this.renderer.gl,r=[],n=t._maxSize,i=t._batchSize,o=t._properties,s=0;s0?1:-1})},{}],179:[function(t,e,r){"use strict";var n=t("object-assign"),i=function(t){return t&&t.__esModule?t:{default:t}}(n);Object.assign||(Object.assign=i.default)},{"object-assign":5}],180:[function(t,e,r){"use strict";t("./Object.assign"),t("./requestAnimationFrame"),t("./Math.sign"),window.ArrayBuffer||(window.ArrayBuffer=Array),window.Float32Array||(window.Float32Array=Array),window.Uint32Array||(window.Uint32Array=Array),window.Uint16Array||(window.Uint16Array=Array)},{"./Math.sign":178,"./Object.assign":179,"./requestAnimationFrame":181}],181:[function(t,e,r){(function(t){"use strict";if(Date.now&&Date.prototype.getTime||(Date.now=function(){return(new Date).getTime()}),!t.performance||!t.performance.now){var e=Date.now();t.performance||(t.performance={}),t.performance.now=function(){return Date.now()-e}}for(var r=Date.now(),n=["ms","moz","webkit","o"],i=0;i=0;n--)this.add(t.children[n]);return this},t.prototype.destroy=function(){this.ticking&&v.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null,this.limiter=null,this.uploadHookHelper=null},t}();r.default=y},{"../core":65,"./limiters/CountLimiter":185}],183:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function s(t,e){if(e instanceof u.BaseTexture){var r=e.source,n=0===r.width?t.canvas.width:Math.min(t.canvas.width,r.width),i=0===r.height?t.canvas.height:Math.min(t.canvas.height,r.height);return t.ctx.drawImage(r,0,0,n,i,0,0,t.canvas.width,t.canvas.height),!0}return!1}r.__esModule=!0;var a=t("../../core"),u=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(a),h=t("../BasePrepare"),l=function(t){return t&&t.__esModule?t:{default:t}}(h),c=16,d=function(t){function e(r){n(this,e);var o=i(this,t.call(this,r));return o.uploadHookHelper=o,o.canvas=document.createElement("canvas"),o.canvas.width=c,o.canvas.height=c,o.ctx=o.canvas.getContext("2d"),o.registerUploadHook(s),o}return o(e,t),e.prototype.destroy=function(){t.prototype.destroy.call(this),this.ctx=null,this.canvas=null},e}(l.default);r.default=d,u.CanvasRenderer.registerPlugin("prepare",d)},{"../../core":65,"../BasePrepare":182}],184:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./webgl/WebGLPrepare");Object.defineProperty(r,"webgl",{enumerable:!0,get:function(){return n(i).default}});var o=t("./canvas/CanvasPrepare");Object.defineProperty(r,"canvas",{enumerable:!0,get:function(){return n(o).default}});var s=t("./BasePrepare");Object.defineProperty(r,"BasePrepare",{enumerable:!0,get:function(){return n(s).default}});var a=t("./limiters/CountLimiter") +;Object.defineProperty(r,"CountLimiter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./limiters/TimeLimiter");Object.defineProperty(r,"TimeLimiter",{enumerable:!0,get:function(){return n(u).default}})},{"./BasePrepare":182,"./canvas/CanvasPrepare":183,"./limiters/CountLimiter":185,"./limiters/TimeLimiter":186,"./webgl/WebGLPrepare":187}],185:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxItemsPerFrame=e,this.itemsLeft=0}return t.prototype.beginFrame=function(){this.itemsLeft=this.maxItemsPerFrame},t.prototype.allowedToUpload=function(){return this.itemsLeft-- >0},t}();r.default=i},{}],186:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxMilliseconds=e,this.frameStart=0}return t.prototype.beginFrame=function(){this.frameStart=Date.now()},t.prototype.allowedToUpload=function(){return Date.now()-this.frameStart 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],2:[function(require,module,exports){ +'use strict'; + +module.exports = earcut; +module.exports.default = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, invSize; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 1 / invSize : 0; + } + + earcutLinked(outerNode, triangles, dim, minX, minY, invSize); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, invSize) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, invSize), + maxZ = zOrder(maxTX, maxTY, minX, minY, invSize); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize); + earcutLinked(c, triangles, dim, minX, minY, invSize); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, invSize) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) * invSize; + y = 32767 * (y - minY) * invSize; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; + +},{}],3:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @api private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {Mixed} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @api public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @api public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Boolean} exists Only check if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Add a one-time listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Remove the listeners of a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {Mixed} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn + && (!once || listeners.once) + && (!context || listeners.context === context) + ) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {String|Symbol} [event] The event name. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],4:[function(require,module,exports){ +/** + * isMobile.js v0.4.1 + * + * A simple library to detect Apple phones and tablets, + * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone), + * and any kind of seven inch device, via user agent sniffing. + * + * @author: Kai Mallea (kmallea@gmail.com) + * + * @license: http://creativecommons.org/publicdomain/zero/1.0/ + */ +(function (global) { + + var apple_phone = /iPhone/i, + apple_ipod = /iPod/i, + apple_tablet = /iPad/i, + android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i, // Match 'Android' AND 'Mobile' + android_tablet = /Android/i, + amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i, + amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i, + windows_phone = /Windows Phone/i, + windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i, // Match 'Windows' AND 'ARM' + other_blackberry = /BlackBerry/i, + other_blackberry_10 = /BB10/i, + other_opera = /Opera Mini/i, + other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i, + other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i, // Match 'Firefox' AND 'Mobile' + seven_inch = new RegExp( + '(?:' + // Non-capturing group + + 'Nexus 7' + // Nexus 7 + + '|' + // OR + + 'BNTV250' + // B&N Nook Tablet 7 inch + + '|' + // OR + + 'Kindle Fire' + // Kindle Fire + + '|' + // OR + + 'Silk' + // Kindle Fire, Silk Accelerated + + '|' + // OR + + 'GT-P1000' + // Galaxy Tab 7 inch + + ')', // End non-capturing group + + 'i'); // Case-insensitive matching + + var match = function(regex, userAgent) { + return regex.test(userAgent); + }; + + var IsMobileClass = function(userAgent) { + var ua = userAgent || navigator.userAgent; + + // Facebook mobile app's integrated browser adds a bunch of strings that + // match everything. Strip it out if it exists. + var tmp = ua.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + // Twitter mobile app's integrated browser on iPad adds a "Twitter for + // iPhone" string. Same probable happens on other tablet platforms. + // This will confuse detection so strip it out if it exists. + tmp = ua.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + this.apple = { + phone: match(apple_phone, ua), + ipod: match(apple_ipod, ua), + tablet: !match(apple_phone, ua) && match(apple_tablet, ua), + device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua) + }; + this.amazon = { + phone: match(amazon_phone, ua), + tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) + }; + this.android = { + phone: match(amazon_phone, ua) || match(android_phone, ua), + tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua) + }; + this.windows = { + phone: match(windows_phone, ua), + tablet: match(windows_tablet, ua), + device: match(windows_phone, ua) || match(windows_tablet, ua) + }; + this.other = { + blackberry: match(other_blackberry, ua), + blackberry10: match(other_blackberry_10, ua), + opera: match(other_opera, ua), + firefox: match(other_firefox, ua), + chrome: match(other_chrome, ua), + device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua) + }; + this.seven_inch = match(seven_inch, ua); + this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch; + + // excludes 'other' devices and ipods, targeting touchscreen phones + this.phone = this.apple.phone || this.android.phone || this.windows.phone; + + // excludes 7 inch devices, classifying as phone or tablet is left to the user + this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet; + + if (typeof window === 'undefined') { + return this; + } + }; + + var instantiate = function() { + var IM = new IsMobileClass(); + IM.Class = IsMobileClass; + return IM; + }; + + if (typeof module !== 'undefined' && module.exports && typeof window === 'undefined') { + //node + module.exports = IsMobileClass; + } else if (typeof module !== 'undefined' && module.exports && typeof window !== 'undefined') { + //browserify + module.exports = instantiate(); + } else if (typeof define === 'function' && define.amd) { + //AMD + define('isMobile', [], global.isMobile = instantiate()); + } else { + global.isMobile = instantiate(); + } + +})(this); + +},{}],5:[function(require,module,exports){ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],6:[function(require,module,exports){ +var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); + +/** + * Helper class to create a webGL buffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ +var Buffer = function(gl, type, data, drawType) +{ + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The WebGL buffer, created upon instantiation + * + * @member {WebGLBuffer} + */ + this.buffer = gl.createBuffer(); + + /** + * The type of the buffer + * + * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} + */ + this.type = type || gl.ARRAY_BUFFER; + + /** + * The draw type of the buffer + * + * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ + this.drawType = drawType || gl.STATIC_DRAW; + + /** + * The data in the buffer, as a typed array + * + * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} + */ + this.data = EMPTY_ARRAY_BUFFER; + + if(data) + { + this.upload(data); + } + + this._updateID = 0; +}; + +/** + * Uploads the buffer to the GPU + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload + * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract + * @param dontBind {Boolean} whether to bind the buffer before uploading it + */ +Buffer.prototype.upload = function(data, offset, dontBind) +{ + // todo - needed? + if(!dontBind) this.bind(); + + var gl = this.gl; + + data = data || this.data; + offset = offset || 0; + + if(this.data.byteLength >= data.byteLength) + { + gl.bufferSubData(this.type, offset, data); + } + else + { + gl.bufferData(this.type, data, this.drawType); + } + + this.data = data; +}; +/** + * Binds the buffer + * + */ +Buffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindBuffer(this.type, this.buffer); +}; + +Buffer.createVertexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); +}; + +Buffer.createIndexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); +}; + +Buffer.create = function(gl, type, data, drawType) +{ + return new Buffer(gl, type, data, drawType); +}; + +/** + * Destroys the buffer + * + */ +Buffer.prototype.destroy = function(){ + this.gl.deleteBuffer(this.buffer); +}; + +module.exports = Buffer; + +},{}],7:[function(require,module,exports){ + +var Texture = require('./GLTexture'); + +/** + * Helper class to create a webGL Framebuffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + */ +var Framebuffer = function(gl, width, height) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The frame buffer + * + * @member {WebGLFramebuffer} + */ + this.framebuffer = gl.createFramebuffer(); + + /** + * The stencil buffer + * + * @member {WebGLRenderbuffer} + */ + this.stencil = null; + + /** + * The stencil buffer + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The width of the drawing area of the buffer + * + * @member {Number} + */ + this.width = width || 100; + /** + * The height of the drawing area of the buffer + * + * @member {Number} + */ + this.height = height || 100; +}; + +/** + * Adds a texture to the frame buffer + * @param texture {PIXI.glCore.GLTexture} + */ +Framebuffer.prototype.enableTexture = function(texture) +{ + var gl = this.gl; + + this.texture = texture || new Texture(gl); + + this.texture.bind(); + + //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + this.bind(); + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); +}; + +/** + * Initialises the stencil buffer + */ +Framebuffer.prototype.enableStencil = function() +{ + if(this.stencil)return; + + var gl = this.gl; + + this.stencil = gl.createRenderbuffer(); + + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + + // TODO.. this is depth AND stencil? + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width , this.height ); + + +}; + +/** + * Erases the drawing area and fills it with a colour + * @param r {Number} the red value of the clearing colour + * @param g {Number} the green value of the clearing colour + * @param b {Number} the blue value of the clearing colour + * @param a {Number} the alpha value of the clearing colour + */ +Framebuffer.prototype.clear = function( r, g, b, a ) +{ + this.bind(); + + var gl = this.gl; + + gl.clearColor(r, g, b, a); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); +}; + +/** + * Binds the frame buffer to the WebGL context + */ +Framebuffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); +}; + +/** + * Unbinds the frame buffer to the WebGL context + */ +Framebuffer.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, null ); +}; +/** + * Resizes the drawing area of the buffer to the given width and height + * @param width {Number} the new width + * @param height {Number} the new height + */ +Framebuffer.prototype.resize = function(width, height) +{ + var gl = this.gl; + + this.width = width; + this.height = height; + + if ( this.texture ) + { + this.texture.uploadData(null, width, height); + } + + if ( this.stencil ) + { + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + } +}; + +/** + * Destroys this buffer + */ +Framebuffer.prototype.destroy = function() +{ + var gl = this.gl; + + //TODO + if(this.texture) + { + this.texture.destroy(); + } + + gl.deleteFramebuffer(this.framebuffer); + + this.gl = null; + + this.stencil = null; + this.texture = null; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createRGBA = function(gl, width, height, data) +{ + var texture = Texture.fromData(gl, null, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + //fbo.enableStencil(); // get this back on soon! + + //fbo.enableStencil(); // get this back on soon! + + fbo.unbind(); + + return fbo; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createFloat32 = function(gl, width, height, data) +{ + // create a new texture.. + var texture = new Texture.fromData(gl, data, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +module.exports = Framebuffer; + +},{"./GLTexture":9}],8:[function(require,module,exports){ + +var compileProgram = require('./shader/compileProgram'), + extractAttributes = require('./shader/extractAttributes'), + extractUniforms = require('./shader/extractUniforms'), + setPrecision = require('./shader/setPrecision'), + generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + +/** + * Helper class to create a webGL Shader + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + */ +var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + if(precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } + + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); + + this.uniformData = extractUniforms(gl, this.program); + + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + +}; +/** + * Uses this shader + * + * @return {PIXI.glCore.GLShader} Returns itself. + */ +Shader.prototype.bind = function() +{ + this.gl.useProgram(this.program); + return this; +}; + +/** + * Destroys this shader + * TODO + */ +Shader.prototype.destroy = function() +{ + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + + var gl = this.gl; + gl.deleteProgram(this.program); +}; + + +module.exports = Shader; + +},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18,"./shader/setPrecision":22}],9:[function(require,module,exports){ + +/** + * Helper class to create a WebGL Texture + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL context + * @param width {number} the width of the texture + * @param height {number} the height of the texture + * @param format {number} the pixel format of the texture. defaults to gl.RGBA + * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE + */ +var Texture = function(gl, width, height, format, type) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); + + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; + + + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; + + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; + + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + + +}; + +/** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ +Texture.prototype.upload = function(source) +{ + this.bind(); + + var gl = this.gl; + + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + var newWidth = source.videoWidth || source.width; + var newHeight = source.videoHeight || source.height; + + if(newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } + + // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + +}; + +var FLOATING_POINT_AVAILABLE = false; + +/** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.prototype.uploadData = function(data, width, height) +{ + this.bind(); + + var gl = this.gl; + + + if(data instanceof Float32Array) + { + if(!FLOATING_POINT_AVAILABLE) + { + var ext = gl.getExtension("OES_texture_float"); + + if(ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } + + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } + + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + + if(width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } + + this.width = width; + this.height = height; + + +// texSubImage2D +}; + +/** + * Binds the texture + * @param location + */ +Texture.prototype.bind = function(location) +{ + var gl = this.gl; + + if(location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } + + gl.bindTexture(gl.TEXTURE_2D, this.texture); +}; + +/** + * Unbinds the texture + */ +Texture.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, null); +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.minFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + if(this.mipmap) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.magFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); +}; + +/** + * Enables mipmapping + */ +Texture.prototype.enableMipmap = function() +{ + var gl = this.gl; + + this.bind(); + + this.mipmap = true; + + gl.generateMipmap(gl.TEXTURE_2D); +}; + +/** + * Enables linear filtering + */ +Texture.prototype.enableLinearScaling = function() +{ + this.minFilter(true); + this.magFilter(true); +}; + +/** + * Enables nearest neighbour interpolation + */ +Texture.prototype.enableNearestScaling = function() +{ + this.minFilter(false); + this.magFilter(false); +}; + +/** + * Enables clamping on the texture so WebGL will not repeat it + */ +Texture.prototype.enableWrapClamp = function() +{ + var gl = this.gl; + + this.bind(); + + 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); +}; + +/** + * Enable tiling on the texture + */ +Texture.prototype.enableWrapRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); +}; + +Texture.prototype.enableWrapMirrorRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); +}; + + +/** + * Destroys this texture + */ +Texture.prototype.destroy = function() +{ + var gl = this.gl; + //TODO + gl.deleteTexture(this.texture); +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ +Texture.fromSource = function(gl, source, premultiplyAlpha) +{ + var texture = new Texture(gl); + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); + + return texture; +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.fromData = function(gl, data, width, height) +{ + //console.log(data, width, height); + var texture = new Texture(gl); + texture.uploadData(data, width, height); + + return texture; +}; + + +module.exports = Texture; + +},{}],10:[function(require,module,exports){ + +// state object// +var setVertexAttribArrays = require( './setVertexAttribArrays' ); + +/** + * Helper class to work with WebGL VertexArrayObjects (vaos) + * Only works if WebGL extensions are enabled (they usually are) + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function VertexArrayObject(gl, state) +{ + this.nativeVaoExtension = null; + + if(!VertexArrayObject.FORCE_NATIVE) + { + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + this.nativeState = state; + + if(this.nativeVaoExtension) + { + this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + + var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + // VAO - overwrite the state.. + this.nativeState = { + tempAttribState: new Array(maxAttribs), + attribState: new Array(maxAttribs) + }; + } + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of attributes + * + * @member {Array} + */ + this.attributes = []; + + /** + * @member {PIXI.glCore.GLBuffer} + */ + this.indexBuffer = null; + + /** + * A boolean flag + * + * @member {Boolean} + */ + this.dirty = false; +} + +VertexArrayObject.prototype.constructor = VertexArrayObject; +module.exports = VertexArrayObject; + +/** +* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) +* If you find on older devices that things have gone a bit weird then set this to true. +*/ +/** + * Lets the VAO know if you should use the WebGL extension or the native methods. + * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) + * If you find on older devices that things have gone a bit weird then set this to true. + * @static + * @property {Boolean} FORCE_NATIVE + */ +VertexArrayObject.FORCE_NATIVE = false; + +/** + * Binds the buffer + */ +VertexArrayObject.prototype.bind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + + if(this.dirty) + { + this.dirty = false; + this.activate(); + return this; + } + if (this.indexBuffer) + { + this.indexBuffer.bind(); + } + } + else + { + this.activate(); + } + + return this; +}; + +/** + * Unbinds the buffer + */ +VertexArrayObject.prototype.unbind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + return this; +}; + +/** + * Uses this vao + */ +VertexArrayObject.prototype.activate = function() +{ + + var gl = this.gl; + var lastBuffer = null; + + for (var i = 0; i < this.attributes.length; i++) + { + var attrib = this.attributes[i]; + + if(lastBuffer !== attrib.buffer) + { + attrib.buffer.bind(); + lastBuffer = attrib.buffer; + } + + gl.vertexAttribPointer(attrib.attribute.location, + attrib.attribute.size, + attrib.type || gl.FLOAT, + attrib.normalized || false, + attrib.stride || 0, + attrib.start || 0); + } + + setVertexAttribArrays(gl, this.attributes, this.nativeState); + + if(this.indexBuffer) + { + this.indexBuffer.bind(); + } + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + * @param attribute {*} + * @param type {String} + * @param normalized {Boolean} + * @param stride {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start) +{ + this.attributes.push({ + buffer: buffer, + attribute: attribute, + + location: attribute.location, + type: type || this.gl.FLOAT, + normalized: normalized || false, + stride: stride || 0, + start: start || 0 + }); + + this.dirty = true; + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + */ +VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) +{ + this.indexBuffer = buffer; + + this.dirty = true; + + return this; +}; + +/** + * Unbinds this vao and disables it + */ +VertexArrayObject.prototype.clear = function() +{ + // var gl = this.gl; + + // TODO - should this function unbind after clear? + // for now, no but lets see what happens in the real world! + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + } + + this.attributes.length = 0; + this.indexBuffer = null; + + return this; +}; + +/** + * @param type {Number} + * @param size {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.draw = function(type, size, start) +{ + var gl = this.gl; + + if(this.indexBuffer) + { + gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + } + else + { + // TODO need a better way to calculate size.. + gl.drawArrays(type, start, size || this.getSize()); + } + + return this; +}; + +/** + * Destroy this vao + */ +VertexArrayObject.prototype.destroy = function() +{ + // lose references + this.gl = null; + this.indexBuffer = null; + this.attributes = null; + this.nativeState = null; + + if(this.nativeVao) + { + this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); + } + + this.nativeVaoExtension = null; + this.nativeVao = null; +}; + +VertexArrayObject.prototype.getSize = function() +{ + var attrib = this.attributes[0]; + return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); +}; + +},{"./setVertexAttribArrays":13}],11:[function(require,module,exports){ + +/** + * Helper class to create a webGL Context + * + * @class + * @memberof PIXI.glCore + * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from + * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * @return {WebGLRenderingContext} the WebGL context + */ +var createContext = function(canvas, options) +{ + var gl = canvas.getContext('webgl', options) || + canvas.getContext('experimental-webgl', options); + + if (!gl) + { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + return gl; +}; + +module.exports = createContext; + +},{}],12:[function(require,module,exports){ +var gl = { + createContext: require('./createContext'), + setVertexAttribArrays: require('./setVertexAttribArrays'), + GLBuffer: require('./GLBuffer'), + GLFramebuffer: require('./GLFramebuffer'), + GLShader: require('./GLShader'), + GLTexture: require('./GLTexture'), + VertexArrayObject: require('./VertexArrayObject'), + shader: require('./shader') +}; + +// Export for Node-compatible environments +if (typeof module !== 'undefined' && module.exports) +{ + // Export the module + module.exports = gl; +} + +// Add to the browser window pixi.gl +if (typeof window !== 'undefined') +{ + // add the window object + window.PIXI = window.PIXI || {}; + window.PIXI.glCore = gl; +} + +},{"./GLBuffer":6,"./GLFramebuffer":7,"./GLShader":8,"./GLTexture":9,"./VertexArrayObject":10,"./createContext":11,"./setVertexAttribArrays":13,"./shader":19}],13:[function(require,module,exports){ +// var GL_MAP = {}; + +/** + * @param gl {WebGLRenderingContext} The current WebGL context + * @param attribs {*} + * @param state {*} + */ +var setVertexAttribArrays = function (gl, attribs, state) +{ + var i; + if(state) + { + var tempAttribState = state.tempAttribState, + attribState = state.attribState; + + for (i = 0; i < tempAttribState.length; i++) + { + tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + tempAttribState[attribs[i].attribute.location] = true; + } + + for (i = 0; i < attribState.length; i++) + { + if (attribState[i] !== tempAttribState[i]) + { + attribState[i] = tempAttribState[i]; + + if (state.attribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } + + } + else + { + for (i = 0; i < attribs.length; i++) + { + var attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); + } + } +}; + +module.exports = setVertexAttribArrays; + +},{}],14:[function(require,module,exports){ + +/** + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations + * @return {WebGLProgram} the shader program + */ +var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +{ + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + + var program = gl.createProgram(); + + gl.attachShader(program, glVertShader); + gl.attachShader(program, glFragShader); + + // optionally, set the attributes manually for the program rather than letting WebGL decide.. + if(attributeLocations) + { + for(var i in attributeLocations) + { + gl.bindAttribLocation(program, attributeLocations[i], i); + } + } + + + gl.linkProgram(program); + + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + console.error('Pixi.js Error: Could not initialize shader.'); + console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); + console.error('gl.getError()', gl.getError()); + + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') + { + console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + + gl.deleteProgram(program); + program = null; + } + + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + + return program; +}; + +/** + * @private + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @return {WebGLShader} the shader + */ +var compileShader = function (gl, type, src) +{ + var shader = gl.createShader(type); + + gl.shaderSource(shader, src); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + console.log(gl.getShaderInfoLog(shader)); + return null; + } + + return shader; +}; + +module.exports = compileProgram; + +},{}],15:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} Type of value + * @param size {Number} + */ +var defaultValue = function(type, size) +{ + switch (type) + { + case 'float': + return 0; + + case 'vec2': + return new Float32Array(2 * size); + + case 'vec3': + return new Float32Array(3 * size); + + case 'vec4': + return new Float32Array(4 * size); + + case 'int': + case 'sampler2D': + return 0; + + case 'ivec2': + return new Int32Array(2 * size); + + case 'ivec3': + return new Int32Array(3 * size); + + case 'ivec4': + return new Int32Array(4 * size); + + case 'bool': + return false; + + case 'bvec2': + + return booleanArray( 2 * size); + + case 'bvec3': + return booleanArray(3 * size); + + case 'bvec4': + return booleanArray(4 * size); + + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } +}; + +var booleanArray = function(size) +{ + var array = new Array(size); + + for (var i = 0; i < array.length; i++) + { + array[i] = false; + } + + return array; +}; + +module.exports = defaultValue; + +},{}],16:[function(require,module,exports){ + +var mapType = require('./mapType'); +var mapSize = require('./mapSize'); + +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the attributes from + * @return attributes {Object} + */ +var extractAttributes = function(gl, program) +{ + var attributes = {}; + + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + + for (var i = 0; i < totalAttributes; i++) + { + var attribData = gl.getActiveAttrib(program, i); + var type = mapType(gl, attribData.type); + + attributes[attribData.name] = { + type:type, + size:mapSize(type), + location:gl.getAttribLocation(program, attribData.name), + //TODO - make an attribute object + pointer: pointer + }; + } + + return attributes; +}; + +var pointer = function(type, normalized, stride, start){ + // console.log(this.location) + gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +}; + +module.exports = extractAttributes; + +},{"./mapSize":20,"./mapType":21}],17:[function(require,module,exports){ +var mapType = require('./mapType'); +var defaultValue = require('./defaultValue'); + +/** + * Extracts the uniforms + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the uniforms from + * @return uniforms {Object} + */ +var extractUniforms = function(gl, program) +{ + var uniforms = {}; + + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + + for (var i = 0; i < totalUniforms; i++) + { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]/, ""); + var type = mapType(gl, uniformData.type ); + + uniforms[name] = { + type:type, + size:uniformData.size, + location:gl.getUniformLocation(program, name), + value:defaultValue(type, uniformData.size) + }; + } + + return uniforms; +}; + +module.exports = extractUniforms; + +},{"./defaultValue":15,"./mapType":21}],18:[function(require,module,exports){ +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param uniforms {Array} @mat ? + * @return attributes {Object} + */ +var generateUniformAccessObject = function(gl, uniformData) +{ + // this is the object we will be sending back. + // an object hierachy will be created for structs + var uniforms = {data:{}}; + + uniforms.gl = gl; + + var uniformKeys= Object.keys(uniformData); + + for (var i = 0; i < uniformKeys.length; i++) + { + var fullName = uniformKeys[i]; + + var nameTokens = fullName.split('.'); + var name = nameTokens[nameTokens.length - 1]; + + + var uniformGroup = getUniformGroup(nameTokens, uniforms); + + var uniform = uniformData[fullName]; + uniformGroup.data[name] = uniform; + + uniformGroup.gl = gl; + + Object.defineProperty(uniformGroup, name, { + get: generateGetter(name), + set: generateSetter(name, uniform) + }); + } + + return uniforms; +}; + +var generateGetter = function(name) +{ + return function() { + return this.data[name].value; + }; +}; + +var GLSL_SINGLE_SETTERS = { + float: function setSingleFloat(gl, location, value) { gl.uniform1f(location, value); }, + vec2: function setSingleVec2(gl, location, value) { gl.uniform2f(location, value[0], value[1]); }, + vec3: function setSingleVec3(gl, location, value) { gl.uniform3f(location, value[0], value[1], value[2]); }, + vec4: function setSingleVec4(gl, location, value) { gl.uniform4f(location, value[0], value[1], value[2], value[3]); }, + + int: function setSingleInt(gl, location, value) { gl.uniform1i(location, value); }, + ivec2: function setSingleIvec2(gl, location, value) { gl.uniform2i(location, value[0], value[1]); }, + ivec3: function setSingleIvec3(gl, location, value) { gl.uniform3i(location, value[0], value[1], value[2]); }, + ivec4: function setSingleIvec4(gl, location, value) { gl.uniform4i(location, value[0], value[1], value[2], value[3]); }, + + bool: function setSingleBool(gl, location, value) { gl.uniform1i(location, value); }, + bvec2: function setSingleBvec2(gl, location, value) { gl.uniform2i(location, value[0], value[1]); }, + bvec3: function setSingleBvec3(gl, location, value) { gl.uniform3i(location, value[0], value[1], value[2]); }, + bvec4: function setSingleBvec4(gl, location, value) { gl.uniform4i(location, value[0], value[1], value[2], value[3]); }, + + mat2: function setSingleMat2(gl, location, value) { gl.uniformMatrix2fv(location, false, value); }, + mat3: function setSingleMat3(gl, location, value) { gl.uniformMatrix3fv(location, false, value); }, + mat4: function setSingleMat4(gl, location, value) { gl.uniformMatrix4fv(location, false, value); }, + + sampler2D: function setSingleSampler2D(gl, location, value) { gl.uniform1i(location, value); }, +}; + +var GLSL_ARRAY_SETTERS = { + float: function setFloatArray(gl, location, value) { gl.uniform1fv(location, value); }, + vec2: function setVec2Array(gl, location, value) { gl.uniform2fv(location, value); }, + vec3: function setVec3Array(gl, location, value) { gl.uniform3fv(location, value); }, + vec4: function setVec4Array(gl, location, value) { gl.uniform4fv(location, value); }, + int: function setIntArray(gl, location, value) { gl.uniform1iv(location, value); }, + ivec2: function setIvec2Array(gl, location, value) { gl.uniform2iv(location, value); }, + ivec3: function setIvec3Array(gl, location, value) { gl.uniform3iv(location, value); }, + ivec4: function setIvec4Array(gl, location, value) { gl.uniform4iv(location, value); }, + bool: function setBoolArray(gl, location, value) { gl.uniform1iv(location, value); }, + bvec2: function setBvec2Array(gl, location, value) { gl.uniform2iv(location, value); }, + bvec3: function setBvec3Array(gl, location, value) { gl.uniform3iv(location, value); }, + bvec4: function setBvec4Array(gl, location, value) { gl.uniform4iv(location, value); }, + sampler2D: function setSampler2DArray(gl, location, value) { gl.uniform1iv(location, value); }, +}; + +function generateSetter(name, uniform) +{ + return function(value) { + this.data[name].value = value; + var location = this.data[name].location; + if (uniform.size === 1) + { + GLSL_SINGLE_SETTERS[uniform.type](this.gl, location, value); + } + else + { + // glslSetArray(gl, location, type, value) { + GLSL_ARRAY_SETTERS[uniform.type](this.gl, location, value); + } + }; +} + +function getUniformGroup(nameTokens, uniform) +{ + var cur = uniform; + + for (var i = 0; i < nameTokens.length - 1; i++) + { + var o = cur[nameTokens[i]] || {data:{}}; + cur[nameTokens[i]] = o; + cur = o; + } + + return cur; +} + + +module.exports = generateUniformAccessObject; + +},{}],19:[function(require,module,exports){ +module.exports = { + compileProgram: require('./compileProgram'), + defaultValue: require('./defaultValue'), + extractAttributes: require('./extractAttributes'), + extractUniforms: require('./extractUniforms'), + generateUniformAccessObject: require('./generateUniformAccessObject'), + setPrecision: require('./setPrecision'), + mapSize: require('./mapSize'), + mapType: require('./mapType') +}; +},{"./compileProgram":14,"./defaultValue":15,"./extractAttributes":16,"./extractUniforms":17,"./generateUniformAccessObject":18,"./mapSize":20,"./mapType":21,"./setPrecision":22}],20:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} + * @return {Number} + */ +var mapSize = function(type) +{ + return GLSL_TO_SIZE[type]; +}; + + +var GLSL_TO_SIZE = { + 'float': 1, + 'vec2': 2, + 'vec3': 3, + 'vec4': 4, + + 'int': 1, + 'ivec2': 2, + 'ivec3': 3, + 'ivec4': 4, + + 'bool': 1, + 'bvec2': 2, + 'bvec3': 3, + 'bvec4': 4, + + 'mat2': 4, + 'mat3': 9, + 'mat4': 16, + + 'sampler2D': 1 +}; + +module.exports = mapSize; + +},{}],21:[function(require,module,exports){ + + +var mapType = function(gl, type) +{ + if(!GL_TABLE) + { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + + GL_TABLE = {}; + + for(var i = 0; i < typeNames.length; ++i) + { + var tn = typeNames[i]; + GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + } + } + + return GL_TABLE[type]; +}; + +var GL_TABLE = null; + +var GL_TO_GLSL_TYPES = { + 'FLOAT': 'float', + 'FLOAT_VEC2': 'vec2', + 'FLOAT_VEC3': 'vec3', + 'FLOAT_VEC4': 'vec4', + + 'INT': 'int', + 'INT_VEC2': 'ivec2', + 'INT_VEC3': 'ivec3', + 'INT_VEC4': 'ivec4', + + 'BOOL': 'bool', + 'BOOL_VEC2': 'bvec2', + 'BOOL_VEC3': 'bvec3', + 'BOOL_VEC4': 'bvec4', + + 'FLOAT_MAT2': 'mat2', + 'FLOAT_MAT3': 'mat3', + 'FLOAT_MAT4': 'mat4', + + 'SAMPLER_2D': 'sampler2D' +}; + +module.exports = mapType; + +},{}],22:[function(require,module,exports){ +/** + * Sets the float precision on the shader. If the precision is already present this function will do nothing + * @param {string} src the shader source + * @param {string} precision The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + * + * @return {string} modified shader source + */ +var setPrecision = function(src, precision) +{ + if(src.substring(0, 9) !== 'precision') + { + return 'precision ' + precision + ' float;\n' + src; + } + + return src; +}; + +module.exports = setPrecision; + +},{}],23:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) + +},{"_process":24}],24:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],25:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],26:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],27:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],28:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":26,"./encode":27}],29:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":30,"punycode":25,"querystring":28}],30:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],31:[function(require,module,exports){ +'use strict' + +/** + * Remove a range of items from an array + * + * @function removeItems + * @param {Array<*>} arr The target array + * @param {number} startIdx The index to begin removing from (inclusive) + * @param {number} removeCount How many items to remove + */ +module.exports = function removeItems(arr, startIdx, removeCount) +{ + var i, length = arr.length + + if (startIdx >= length || removeCount === 0) { + return + } + + removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount) + + var len = length - removeCount + + for (i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount] + } + + arr.length = len +} + +},{}],32:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _async = require('./async'); + +var async = _interopRequireWildcard(_async); + +var _Resource = require('./Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// some constants +var MAX_PROGRESS = 100; +var rgxExtractUrlHash = /(#[\w-]+)?$/; + +/** + * Manages the state and loading of multiple resources to load. + * + * @class + */ + +var Loader = function () { + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader() { + var _this = this; + + var baseUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var concurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; + + _classCallCheck(this, Loader); + + /** + * The base url for all resources loaded by this loader. + * + * @member {string} + */ + this.baseUrl = baseUrl; + + /** + * The progress percent of the loader going through the queue. + * + * @member {number} + */ + this.progress = 0; + + /** + * Loading state of the loader, true if it is currently loading resources. + * + * @member {boolean} + */ + this.loading = false; + + /** + * A querystring to append to every URL added to the loader. + * + * This should be a valid query string *without* the question-mark (`?`). The loader will + * also *not* escape values for you. Make sure to escape your parameters with + * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. + * + * @example + * const loader = new Loader(); + * + * loader.defaultQueryString = 'user=me&password=secret'; + * + * // This will request 'image.png?user=me&password=secret' + * loader.add('image.png').load(); + * + * loader.reset(); + * + * // This will request 'image.png?v=1&user=me&password=secret' + * loader.add('iamge.png?v=1').load(); + */ + this.defaultQueryString = ''; + + /** + * The middleware to run before loading each resource. + * + * @member {function[]} + */ + this._beforeMiddleware = []; + + /** + * The middleware to run after loading each resource. + * + * @member {function[]} + */ + this._afterMiddleware = []; + + /** + * The tracks the resources we are currently completing parsing for. + * + * @member {Resource[]} + */ + this._resourcesParsing = []; + + /** + * The `_loadResource` function bound with this object context. + * + * @private + * @member {function} + * @param {Resource} r - The resource to load + * @param {Function} d - The dequeue function + * @return {undefined} + */ + this._boundLoadResource = function (r, d) { + return _this._loadResource(r, d); + }; + + /** + * The resources waiting to be loaded. + * + * @private + * @member {Resource[]} + */ + this._queue = async.queue(this._boundLoadResource, concurrency); + + this._queue.pause(); + + /** + * All the resources for this loader keyed by name. + * + * @member {object} + */ + this.resources = {}; + + /** + * Dispatched once per loaded or errored resource. + * + * The callback looks like {@link Loader.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once per errored resource. + * + * The callback looks like {@link Loader.OnErrorSignal}. + * + * @member {Signal} + */ + this.onError = new _miniSignals2.default(); + + /** + * Dispatched once per loaded resource. + * + * The callback looks like {@link Loader.OnLoadSignal}. + * + * @member {Signal} + */ + this.onLoad = new _miniSignals2.default(); + + /** + * Dispatched when the loader begins to process the queue. + * + * The callback looks like {@link Loader.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched when the queued resources all load. + * + * The callback looks like {@link Loader.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * When the progress changes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnProgressSignal + * @param {Loader} loader - The loader the progress is advancing on. + * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance. + */ + + /** + * When an error occurrs the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnErrorSignal + * @param {Loader} loader - The loader the error happened in. + * @param {Resource} resource - The resource that caused the error. + */ + + /** + * When a load completes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnLoadSignal + * @param {Loader} loader - The loader that laoded the resource. + * @param {Resource} resource - The resource that has completed loading. + */ + + /** + * When the loader starts loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnStartSignal + * @param {Loader} loader - The loader that has started loading resources. + */ + + /** + * When the loader completes loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnCompleteSignal + * @param {Loader} loader - The loader that has finished loading resources. + */ + } + + /** + * Adds a resource (or multiple resources) to the loader queue. + * + * This function can take a wide variety of different parameters. The only thing that is always + * required the url to load. All the following will work: + * + * ```js + * loader + * // normal param syntax + * .add('key', 'http://...', function () {}) + * .add('http://...', function () {}) + * .add('http://...') + * + * // object syntax + * .add({ + * name: 'key2', + * url: 'http://...' + * }, function () {}) + * .add({ + * url: 'http://...' + * }, function () {}) + * .add({ + * name: 'key3', + * url: 'http://...' + * onComplete: function () {} + * }) + * .add({ + * url: 'https://...', + * onComplete: function () {}, + * crossOrigin: true + * }) + * + * // you can also pass an array of objects or urls or both + * .add([ + * { name: 'key4', url: 'http://...', onComplete: function () {} }, + * { url: 'http://...', onComplete: function () {} }, + * 'http://...' + * ]) + * + * // and you can use both params and options + * .add('key', 'http://...', { crossOrigin: true }, function () {}) + * .add('http://...', { crossOrigin: true }, function () {}); + * ``` + * + * @param {string} [name] - The name of the resource to load, if not passed the url is used. + * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @param {object} [options] - The options for the load. + * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should + * the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @param {function} [cb] - Function to call when this specific resource completes loading. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.add = function add(name, url, options, cb) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + + return this; + } + + // if an object is passed instead of params + if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') { + cb = url || name.callback || name.onComplete; + options = name; + url = name.url; + name = name.name || name.key || name.url; + } + + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + cb = options; + options = url; + url = name; + } + + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + cb = options; + options = null; + } + + // if loading already you can only add resources that have a parent. + if (this.loading && (!options || !options.parentResource)) { + throw new Error('Cannot add resources while the loader is running.'); + } + + // check if resource already exists. + if (this.resources[name]) { + throw new Error('Resource named "' + name + '" already exists.'); + } + + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + + // create the store the resource + this.resources[name] = new _Resource2.default(name, url, options); + + if (typeof cb === 'function') { + this.resources[name].onAfterMiddleware.once(cb); + } + + // if actively loading, make sure to adjust progress chunks for that parent and its children + if (this.loading) { + var parent = options.parentResource; + var incompleteChildren = []; + + for (var _i = 0; _i < parent.children.length; ++_i) { + if (!parent.children[_i].isComplete) { + incompleteChildren.push(parent.children[_i]); + } + } + + var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent + var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child + + parent.children.push(this.resources[name]); + parent.progressChunk = eachChunk; + + for (var _i2 = 0; _i2 < incompleteChildren.length; ++_i2) { + incompleteChildren[_i2].progressChunk = eachChunk; + } + + this.resources[name].progressChunk = eachChunk; + } + + // add the resource to the queue + this._queue.push(this.resources[name]); + + return this; + }; + + /** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * + * @method before + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.pre = function pre(fn) { + this._beforeMiddleware.push(fn); + + return this; + }; + + /** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * + * @alias use + * @method after + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.use = function use(fn) { + this._afterMiddleware.push(fn); + + return this; + }; + + /** + * Resets the queue of the loader to prepare for a new load. + * + * @return {Loader} Returns itself. + */ + + + Loader.prototype.reset = function reset() { + this.progress = 0; + this.loading = false; + + this._queue.kill(); + this._queue.pause(); + + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + + if (res._onLoadBinding) { + res._onLoadBinding.detach(); + } + + if (res.isLoading) { + res.abort(); + } + } + + this.resources = {}; + + return this; + }; + + /** + * Starts loading the queued resources. + * + * @param {function} [cb] - Optional callback that will be bound to the `complete` event. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.load = function load(cb) { + // register complete callback if they pass one + if (typeof cb === 'function') { + this.onComplete.once(cb); + } + + // if the queue has already started we are done here + if (this.loading) { + return this; + } + + // distribute progress chunks + var chunk = 100 / this._queue._tasks.length; + + for (var i = 0; i < this._queue._tasks.length; ++i) { + this._queue._tasks[i].data.progressChunk = chunk; + } + + // update loading state + this.loading = true; + + // notify of start + this.onStart.dispatch(this); + + // start loading + this._queue.resume(); + + return this; + }; + + /** + * Prepares a url for usage based on the configuration of this object + * + * @private + * @param {string} url - The url to prepare. + * @return {string} The prepared url. + */ + + + Loader.prototype._prepareUrl = function _prepareUrl(url) { + var parsedUrl = (0, _parseUri2.default)(url, { strictMode: true }); + var result = void 0; + + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { + result = url; + } + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + else if (this.baseUrl.length && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 && url.charAt(0) !== '/') { + result = this.baseUrl + '/' + url; + } else { + result = this.baseUrl + url; + } + + // if we need to add a default querystring, there is a bit more work + if (this.defaultQueryString) { + var hash = rgxExtractUrlHash.exec(result)[0]; + + result = result.substr(0, result.length - hash.length); + + if (result.indexOf('?') !== -1) { + result += '&' + this.defaultQueryString; + } else { + result += '?' + this.defaultQueryString; + } + + result += hash; + } + + return result; + }; + + /** + * Loads a single resource. + * + * @private + * @param {Resource} resource - The resource to load. + * @param {function} dequeue - The function to call when we need to dequeue this item. + */ + + + Loader.prototype._loadResource = function _loadResource(resource, dequeue) { + var _this2 = this; + + resource._dequeue = dequeue; + + // run before middleware + async.eachSeries(this._beforeMiddleware, function (fn, next) { + fn.call(_this2, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, function () { + if (resource.isComplete) { + _this2._onLoad(resource); + } else { + resource._onLoadBinding = resource.onComplete.once(_this2._onLoad, _this2); + resource.load(); + } + }, true); + }; + + /** + * Called once each resource has loaded. + * + * @private + */ + + + Loader.prototype._onComplete = function _onComplete() { + this.loading = false; + + this.onComplete.dispatch(this, this.resources); + }; + + /** + * Called each time a resources is loaded. + * + * @private + * @param {Resource} resource - The resource that was loaded + */ + + + Loader.prototype._onLoad = function _onLoad(resource) { + var _this3 = this; + + resource._onLoadBinding = null; + + // remove this resource from the async queue, and add it to our list of resources that are being parsed + this._resourcesParsing.push(resource); + resource._dequeue(); + + // run all the after middleware for this resource + async.eachSeries(this._afterMiddleware, function (fn, next) { + fn.call(_this3, resource, next); + }, function () { + resource.onAfterMiddleware.dispatch(resource); + + _this3.progress += resource.progressChunk; + _this3.onProgress.dispatch(_this3, resource); + + if (resource.error) { + _this3.onError.dispatch(resource.error, _this3, resource); + } else { + _this3.onLoad.dispatch(_this3, resource); + } + + _this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1); + + // do completion check + if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) { + _this3.progress = MAX_PROGRESS; + _this3._onComplete(); + } + }, true); + }; + + return Loader; +}(); + +exports.default = Loader; + +},{"./Resource":33,"./async":34,"mini-signals":38,"parse-uri":39}],33:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// tests is CORS is supported in XHR, if not we need to use XDR +var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest())); +var tempAnchor = null; + +// some status constants +var STATUS_NONE = 0; +var STATUS_OK = 200; +var STATUS_EMPTY = 204; +var STATUS_IE_BUG_EMPTY = 1223; +var STATUS_TYPE_OK = 2; + +// noop +function _noop() {} /* empty */ + +/** + * Manages the state and loading of a resource and all child resources. + * + * @class + */ + +var Resource = function () { + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. + */ + Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) { + setExtMap(Resource._loadTypeMap, extname, loadType); + }; + + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ + + + Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); + }; + + /** + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass + * an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @param {string|string[]} [options.metadata.mimeType] - The mime type to use for the source element of a video/audio + * elment. If the urls are an array, you can pass this as an array as well where each index is the mime type to + * use for the corresponding url index. + */ + + + function Resource(name, url, options) { + _classCallCheck(this, Resource); + + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + + options = options || {}; + + /** + * The state flags of this resource. + * + * @member {number} + */ + this._flags = 0; + + // set data url flag, needs to be set early for some _determineX checks to work. + this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); + + /** + * The name of this resource. + * + * @member {string} + * @readonly + */ + this.name = name; + + /** + * The url used to load this resource. + * + * @member {string} + * @readonly + */ + this.url = url; + + /** + * The extension used to load this resource. + * + * @member {string} + * @readonly + */ + this.extension = this._getExtension(); + + /** + * The data that was loaded by the resource. + * + * @member {any} + */ + this.data = null; + + /** + * Is this request cross-origin? If unset, determined automatically. + * + * @member {string} + */ + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + + /** + * The method of loading to use for this resource. + * + * @member {Resource.LOAD_TYPE} + */ + this.loadType = options.loadType || this._determineLoadType(); + + /** + * The type used to load the resource via XHR. If unset, determined automatically. + * + * @member {string} + */ + this.xhrType = options.xhrType; + + /** + * Extra info for middleware, and controlling specifics about how the resource loads. + * + * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + * Meaning it will modify it as it sees fit. + * + * @member {object} + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources + * to. + */ + this.metadata = options.metadata || {}; + + /** + * The error that occurred while loading (if any). + * + * @member {Error} + * @readonly + */ + this.error = null; + + /** + * The XHR object that was used to load this resource. This is only set + * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * + * @member {XMLHttpRequest} + * @readonly + */ + this.xhr = null; + + /** + * The child resources this resource owns. + * + * @member {Resource[]} + * @readonly + */ + this.children = []; + + /** + * The resource type. + * + * @member {Resource.TYPE} + * @readonly + */ + this.type = Resource.TYPE.UNKNOWN; + + /** + * The progress chunk owned by this resource. + * + * @member {number} + * @readonly + */ + this.progressChunk = 0; + + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * + * @private + * @member {function} + */ + this._dequeue = _noop; + + /** + * Used a storage place for the on load binding used privately by the loader. + * + * @private + * @member {function} + */ + this._onLoadBinding = null; + + /** + * The `complete` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundComplete = this.complete.bind(this); + + /** + * The `_onError` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnError = this._onError.bind(this); + + /** + * The `_onProgress` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnProgress = this._onProgress.bind(this); + + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + this._boundXdrOnTimeout = this._xdrOnTimeout.bind(this); + + /** + * Dispatched when the resource beings to load. + * + * The callback looks like {@link Resource.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched each time progress of this resource load updates. + * Not all resources types and loader systems can support this event + * so sometimes it may not be available. If the resource + * is being loaded on a modern browser, using XHR, and the remote server + * properly sets Content-Length headers, then this will be available. + * + * The callback looks like {@link Resource.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once this resource has loaded, if there was an error it will + * be in the `error` property. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * Dispatched after this resource has had all the *after* middleware run on it. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onAfterMiddleware = new _miniSignals2.default(); + + /** + * When the resource starts to load. + * + * @memberof Resource + * @callback OnStartSignal + * @param {Resource} resource - The resource that the event happened on. + */ + + /** + * When the resource reports loading progress. + * + * @memberof Resource + * @callback OnProgressSignal + * @param {Resource} resource - The resource that the event happened on. + * @param {number} percentage - The progress of the load in the range [0, 1]. + */ + + /** + * When the resource finishes loading. + * + * @memberof Resource + * @callback OnCompleteSignal + * @param {Resource} resource - The resource that the event happened on. + */ + } + + /** + * Stores whether or not this url is a data url. + * + * @member {boolean} + * @readonly + */ + + + /** + * Marks the resource as complete. + * + */ + Resource.prototype.complete = function complete() { + // TODO: Clean this up in a wrapper or something...gross.... + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + + this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true); + this._setFlag(Resource.STATUS_FLAGS.LOADING, false); + + this.onComplete.dispatch(this); + }; + + /** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ + + + Resource.prototype.abort = function abort(message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + + // store error + this.error = new Error(message); + + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } else if (this.xdr) { + this.xdr.abort(); + } else if (this.data) { + // single source + if (this.data.src) { + this.data.src = Resource.EMPTY_GIF; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + + // done now. + this.complete(); + }; + + /** + * Kicks off loading of this resource. This method is asynchronous. + * + * @param {function} [cb] - Optional callback to call once the resource is loaded. + */ + + + Resource.prototype.load = function load(cb) { + var _this = this; + + if (this.isLoading) { + return; + } + + if (this.isComplete) { + if (cb) { + setTimeout(function () { + return cb(_this); + }, 1); + } + + return; + } else if (cb) { + this.onComplete.once(cb); + } + + this._setFlag(Resource.STATUS_FLAGS.LOADING, true); + + this.onStart.dispatch(this); + + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + + switch (this.loadType) { + case Resource.LOAD_TYPE.IMAGE: + this.type = Resource.TYPE.IMAGE; + this._loadElement('image'); + break; + + case Resource.LOAD_TYPE.AUDIO: + this.type = Resource.TYPE.AUDIO; + this._loadSourceElement('audio'); + break; + + case Resource.LOAD_TYPE.VIDEO: + this.type = Resource.TYPE.VIDEO; + this._loadSourceElement('video'); + break; + + case Resource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } else { + this._loadXhr(); + } + break; + } + }; + + /** + * Checks if the flag is set. + * + * @private + * @param {number} flag - The flag to check. + * @return {boolean} True if the flag is set. + */ + + + Resource.prototype._hasFlag = function _hasFlag(flag) { + return !!(this._flags & flag); + }; + + /** + * (Un)Sets the flag. + * + * @private + * @param {number} flag - The flag to (un)set. + * @param {boolean} value - Whether to set or (un)set the flag. + */ + + + Resource.prototype._setFlag = function _setFlag(flag, value) { + this._flags = value ? this._flags | flag : this._flags & ~flag; + }; + + /** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadElement = function _loadElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'image' && typeof window.Image !== 'undefined') { + this.data = new Image(); + } else { + this.data = document.createElement(type); + } + + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + }; + + /** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadSourceElement = function _loadSourceElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'audio' && typeof window.Audio !== 'undefined') { + this.data = new Audio(); + } else { + this.data = document.createElement(type); + } + + if (this.data === null) { + this.abort('Unsupported element: ' + type); + + return; + } + + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } else if (Array.isArray(this.url)) { + var mimeTypes = this.metadata.mimeType; + + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes)); + } + } else { + var _mimeTypes = this.metadata.mimeType; + + this.data.appendChild(this._createSource(type, this.url, Array.isArray(_mimeTypes) ? _mimeTypes[0] : _mimeTypes)); + } + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + + this.data.load(); + }; + + /** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ + + + Resource.prototype._loadXhr = function _loadXhr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xhr = this.xhr = new XMLHttpRequest(); + + // set the request type and url + xhr.open('GET', this.url, true); + + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; + } else { + xhr.responseType = this.xhrType; + } + + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + + xhr.send(); + }; + + /** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ + + + Resource.prototype._loadXdr = function _loadXdr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xdr = this.xhr = new XDomainRequest(); + + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = 5000; + + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXdrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + + xdr.open('GET', this.url, true); + + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { + return xdr.send(); + }, 1); + }; + + /** + * Creates a source used in loading via an element. + * + * @private + * @param {string} type - The element type (video or audio). + * @param {string} url - The source URL to load from. + * @param {string} [mime] - The mime type of the video + * @return {HTMLSourceElement} The source element. + */ + + + Resource.prototype._createSource = function _createSource(type, url, mime) { + if (!mime) { + mime = type + '/' + this._getExtension(url); + } + + var source = document.createElement('source'); + + source.src = url; + source.type = mime; + + return source; + }; + + /** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ + + + Resource.prototype._onError = function _onError(event) { + this.abort('Failed to load element using: ' + event.target.nodeName); + }; + + /** + * Called if a load progress event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ + + + Resource.prototype._onProgress = function _onProgress(event) { + if (event && event.lengthComputable) { + this.onProgress.dispatch(this, event.loaded / event.total); + } + }; + + /** + * Called if an error event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestErrorEvent|Event} event - Error event. + */ + + + Resource.prototype._xhrOnError = function _xhrOnError() { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"'); + }; + + /** + * Called if an abort event fires for xhr. + * + * @private + * @param {XMLHttpRequestAbortEvent} event - Abort Event + */ + + + Resource.prototype._xhrOnAbort = function _xhrOnAbort() { + this.abort(reqType(this.xhr) + ' Request was aborted by the user.'); + }; + + /** + * Called if a timeout event fires for xdr. + * + * @private + * @param {Event} event - Timeout event. + */ + + + Resource.prototype._xdrOnTimeout = function _xdrOnTimeout() { + this.abort(reqType(this.xhr) + ' Request timed out.'); + }; + + /** + * Called when data successfully loads from an xhr/xdr request. + * + * @private + * @param {XMLHttpRequestLoadEvent|Event} event - Load event + */ + + + Resource.prototype._xhrOnLoad = function _xhrOnLoad() { + var xhr = this.xhr; + var text = ''; + var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200. + + // responseText is accessible only if responseType is '' or 'text' and on older browsers + if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') { + text = xhr.responseText; + } + + // status can be 0 when using the `file://` protocol so we also check if a response is set. + // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request. + if (status === STATUS_NONE && text.length > 0) { + status = STATUS_OK; + } + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + else if (status === STATUS_IE_BUG_EMPTY) { + status = STATUS_EMPTY; + } + + var statusType = status / 100 | 0; + + if (statusType === STATUS_TYPE_OK) { + // if text, just return it + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { + this.data = text; + this.type = Resource.TYPE.TEXT; + } + // if json, parse into json object + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(text); + this.type = Resource.TYPE.JSON; + } catch (e) { + this.abort('Error trying to parse loaded json: ' + e); + + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (window.DOMParser) { + var domparser = new DOMParser(); + + this.data = domparser.parseFromString(text, 'text/xml'); + } else { + var div = document.createElement('div'); + + div.innerHTML = text; + + this.data = div; + } + + this.type = Resource.TYPE.XML; + } catch (e) { + this.abort('Error trying to parse loaded xml: ' + e); + + return; + } + } + // other types just return the response + else { + this.data = xhr.response || text; + } + } else { + this.abort('[' + xhr.status + '] ' + xhr.statusText + ': ' + xhr.responseURL); + + return; + } + + this.complete(); + }; + + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * + * @private + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ + + + Resource.prototype._determineCrossOrigin = function _determineCrossOrigin(url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = (0, _parseUri2.default)(tempAnchor.href, { strictMode: true }); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + var protocol = url.protocol ? url.protocol + ':' : ''; + + // if cross origin + if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; + }; + + /** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. + */ + + + Resource.prototype._determineXhrType = function _determineXhrType() { + return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT; + }; + + /** + * Determines the loadType of a resource based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.LOAD_TYPE} The loadType to use. + */ + + + Resource.prototype._determineLoadType = function _determineLoadType() { + return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR; + }; + + /** + * Extracts the extension (sans '.') of the file being loaded by the resource. + * + * @private + * @return {string} The extension. + */ + + + Resource.prototype._getExtension = function _getExtension() { + var url = this.url; + var ext = ''; + + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } else { + var queryStart = url.indexOf('?'); + var hashStart = url.indexOf('#'); + var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length); + + url = url.substring(0, index); + ext = url.substring(url.lastIndexOf('.') + 1); + } + + return ext.toLowerCase(); + }; + + /** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * + * @private + * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. + * @return {string} The mime type to use. + */ + + + Resource.prototype._getMimeFromXhrType = function _getMimeFromXhrType(type) { + switch (type) { + case Resource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + + case Resource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + + case Resource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + + case Resource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + + case Resource.XHR_RESPONSE_TYPE.DEFAULT: + case Resource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + + } + }; + + _createClass(Resource, [{ + key: 'isDataUrl', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL); + } + + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isComplete', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE); + } + + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isLoading', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.LOADING); + } + }]); + + return Resource; +}(); + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ + + +exports.default = Resource; +Resource.STATUS_FLAGS = { + NONE: 0, + DATA_URL: 1 << 0, + COMPLETE: 1 << 1, + LOADING: 1 << 2 +}; + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ +Resource.TYPE = { + UNKNOWN: 0, + JSON: 1, + XML: 2, + IMAGE: 3, + AUDIO: 4, + VIDEO: 5, + TEXT: 6 +}; + +/** + * The types of loading a resource can use. + * + * @static + * @readonly + * @enum {number} + */ +Resource.LOAD_TYPE = { + /** Uses XMLHttpRequest to load the resource. */ + XHR: 1, + /** Uses an `Image` object to load the resource. */ + IMAGE: 2, + /** Uses an `Audio` object to load the resource. */ + AUDIO: 3, + /** Uses a `Video` object to load the resource. */ + VIDEO: 4 +}; + +/** + * The XHR ready states, used internally. + * + * @static + * @readonly + * @enum {string} + */ +Resource.XHR_RESPONSE_TYPE = { + /** string */ + DEFAULT: 'text', + /** ArrayBuffer */ + BUFFER: 'arraybuffer', + /** Blob */ + BLOB: 'blob', + /** Document */ + DOCUMENT: 'document', + /** Object */ + JSON: 'json', + /** String */ + TEXT: 'text' +}; + +Resource._loadTypeMap = { + // images + gif: Resource.LOAD_TYPE.IMAGE, + png: Resource.LOAD_TYPE.IMAGE, + bmp: Resource.LOAD_TYPE.IMAGE, + jpg: Resource.LOAD_TYPE.IMAGE, + jpeg: Resource.LOAD_TYPE.IMAGE, + tif: Resource.LOAD_TYPE.IMAGE, + tiff: Resource.LOAD_TYPE.IMAGE, + webp: Resource.LOAD_TYPE.IMAGE, + tga: Resource.LOAD_TYPE.IMAGE, + svg: Resource.LOAD_TYPE.IMAGE, + 'svg+xml': Resource.LOAD_TYPE.IMAGE, // for SVG data urls + + // audio + mp3: Resource.LOAD_TYPE.AUDIO, + ogg: Resource.LOAD_TYPE.AUDIO, + wav: Resource.LOAD_TYPE.AUDIO, + + // videos + mp4: Resource.LOAD_TYPE.VIDEO, + webm: Resource.LOAD_TYPE.VIDEO +}; + +Resource._xhrTypeMap = { + // xml + xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. + // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, + // this should probably be fine. + tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // images + gif: Resource.XHR_RESPONSE_TYPE.BLOB, + png: Resource.XHR_RESPONSE_TYPE.BLOB, + bmp: Resource.XHR_RESPONSE_TYPE.BLOB, + jpg: Resource.XHR_RESPONSE_TYPE.BLOB, + jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, + tif: Resource.XHR_RESPONSE_TYPE.BLOB, + tiff: Resource.XHR_RESPONSE_TYPE.BLOB, + webp: Resource.XHR_RESPONSE_TYPE.BLOB, + tga: Resource.XHR_RESPONSE_TYPE.BLOB, + + // json + json: Resource.XHR_RESPONSE_TYPE.JSON, + + // text + text: Resource.XHR_RESPONSE_TYPE.TEXT, + txt: Resource.XHR_RESPONSE_TYPE.TEXT, + + // fonts + ttf: Resource.XHR_RESPONSE_TYPE.BUFFER, + otf: Resource.XHR_RESPONSE_TYPE.BUFFER +}; + +// We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif +Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; + +/** + * Quick helper to set a value on one of the extension maps. Ensures there is no + * dot at the start of the extension. + * + * @ignore + * @param {object} map - The map to set on. + * @param {string} extname - The extension (or key) to set. + * @param {number} val - The value to set. + */ +function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + + if (!extname) { + return; + } + + map[extname] = val; +} + +/** + * Quick helper to get string xhr type. + * + * @ignore + * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. + * @return {string} The type. + */ +function reqType(xhr) { + return xhr.toString().replace('object ', ''); +} + +},{"mini-signals":38,"parse-uri":39}],34:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.eachSeries = eachSeries; +exports.queue = queue; +/** + * Smaller version of the async library constructs. + * + */ +function _noop() {} /* empty */ + +/** + * Iterates an array in series. + * + * @param {Array.<*>} array - Array to iterate. + * @param {function} iterator - Function to call for each element. + * @param {function} callback - Function to call when done, or on error. + * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1. + */ +function eachSeries(array, iterator, callback, deferNext) { + var i = 0; + var len = array.length; + + (function next(err) { + if (err || i === len) { + if (callback) { + callback(err); + } + + return; + } + + if (deferNext) { + setTimeout(function () { + iterator(array[i++], next); + }, 1); + } else { + iterator(array[i++], next); + } + })(); +} + +/** + * Ensures a function is only called once. + * + * @param {function} fn - The function to wrap. + * @return {function} The wrapping function. + */ +function onlyOnce(fn) { + return function onceWrapper() { + if (fn === null) { + throw new Error('Callback was already called.'); + } + + var callFn = fn; + + fn = null; + callFn.apply(this, arguments); + }; +} + +/** + * Async queue implementation, + * + * @param {function} worker - The worker function to call for each task. + * @param {number} concurrency - How many workers to run in parrallel. + * @return {*} The async queue object. + */ +function queue(worker, concurrency) { + if (concurrency == null) { + // eslint-disable-line no-eq-null,eqeqeq + concurrency = 1; + } else if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + + var workers = 0; + var q = { + _tasks: [], + concurrency: concurrency, + saturated: _noop, + unsaturated: _noop, + buffer: concurrency / 4, + empty: _noop, + drain: _noop, + error: _noop, + started: false, + paused: false, + push: function push(data, callback) { + _insert(data, false, callback); + }, + kill: function kill() { + workers = 0; + q.drain = _noop; + q.started = false; + q._tasks = []; + }, + unshift: function unshift(data, callback) { + _insert(data, true, callback); + }, + process: function process() { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var task = q._tasks.shift(); + + if (q._tasks.length === 0) { + q.empty(); + } + + workers += 1; + + if (workers === q.concurrency) { + q.saturated(); + } + + worker(task.data, onlyOnce(_next(task))); + } + }, + length: function length() { + return q._tasks.length; + }, + running: function running() { + return workers; + }, + idle: function idle() { + return q._tasks.length + workers === 0; + }, + pause: function pause() { + if (q.paused === true) { + return; + } + + q.paused = true; + }, + resume: function resume() { + if (q.paused === false) { + return; + } + + q.paused = false; + + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= q.concurrency; w++) { + q.process(); + } + } + }; + + function _insert(data, insertAtFront, callback) { + if (callback != null && typeof callback !== 'function') { + // eslint-disable-line no-eq-null,eqeqeq + throw new Error('task callback must be a function'); + } + + q.started = true; + + if (data == null && q.idle()) { + // eslint-disable-line no-eq-null,eqeqeq + // call drain immediately if there are no tasks + setTimeout(function () { + return q.drain(); + }, 1); + + return; + } + + var item = { + data: data, + callback: typeof callback === 'function' ? callback : _noop + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + setTimeout(function () { + return q.process(); + }, 1); + } + + function _next(task) { + return function next() { + workers -= 1; + + task.callback.apply(task, arguments); + + if (arguments[0] != null) { + // eslint-disable-line no-eq-null,eqeqeq + q.error(arguments[0], task.data); + } + + if (workers <= q.concurrency - q.buffer) { + q.unsaturated(); + } + + if (q.idle()) { + q.drain(); + } + + q.process(); + }; + } + + return q; +} + +},{}],35:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.encodeBinary = encodeBinary; +var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +function encodeBinary(input) { + var output = ''; + var inx = 0; + + while (inx < input.length) { + // Fill byte buffer array + var bytebuffer = [0, 0, 0]; + var encodedCharIndexes = [0, 0, 0, 0]; + + for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } else { + bytebuffer[jnx] = 0; + } + } + + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4; + + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6; + + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + + // Determine whether padding happened, and adjust accordingly + var paddingBytes = inx - (input.length - 1); + + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + + default: + break; // No padding - proceed + } + + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) { + output += _keyStr.charAt(encodedCharIndexes[_jnx]); + } + } + + return output; +} + +},{}],36:[function(require,module,exports){ +'use strict'; + +// import Loader from './Loader'; +// import Resource from './Resource'; +// import * as async from './async'; +// import * as b64 from './b64'; + +/* eslint-disable no-undef */ + +var Loader = require('./Loader').default; +var Resource = require('./Resource').default; +var async = require('./async'); +var b64 = require('./b64'); + +Loader.Resource = Resource; +Loader.async = async; +Loader.base64 = b64; + +// export manually, and also as default +module.exports = Loader; +// export default Loader; +module.exports.default = Loader; + +},{"./Loader":32,"./Resource":33,"./async":34,"./b64":35}],37:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +exports.blobMiddlewareFactory = blobMiddlewareFactory; + +var _Resource = require('../../Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +var _b = require('../../b64'); + +var _b2 = _interopRequireDefault(_b); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Url = window.URL || window.webkitURL; + +// a middleware for transforming XHR loaded Blobs into more useful objects +function blobMiddlewareFactory() { + return function blobMiddleware(resource, next) { + if (!resource.data) { + next(); + + return; + } + + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === _Resource2.default.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!window.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = 'data:' + type + ';base64,' + _b2.default.encodeBinary(resource.xhr.responseText); + + resource.type = _Resource2.default.TYPE.IMAGE; + + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + + next(); + }; + + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var _ret = function () { + var src = Url.createObjectURL(resource.data); + + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src; + + resource.type = _Resource2.default.TYPE.IMAGE; + + // cleanup the no longer used blob after the image loads + // TODO: Is this correct? Will the image be invalid after revoking? + resource.data.onload = function () { + Url.revokeObjectURL(src); + resource.data.onload = null; + + next(); + }; + + // next will be called on load. + return { + v: void 0 + }; + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + } + + next(); + }; +} + +},{"../../Resource":33,"../../b64":35}],38:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + +var MiniSignalBinding = (function () { + function MiniSignalBinding(fn, once, thisArg) { + if (once === undefined) once = false; + + _classCallCheck(this, MiniSignalBinding); + + this._fn = fn; + this._once = once; + this._thisArg = thisArg; + this._next = this._prev = this._owner = null; + } + + _createClass(MiniSignalBinding, [{ + key: 'detach', + value: function detach() { + if (this._owner === null) return false; + this._owner.detach(this); + return true; + } + }]); + + return MiniSignalBinding; +})(); + +function _addMiniSignalBinding(self, node) { + if (!self._head) { + self._head = node; + self._tail = node; + } else { + self._tail._next = node; + node._prev = self._tail; + self._tail = node; + } + + node._owner = self; + + return node; +} + +var MiniSignal = (function () { + function MiniSignal() { + _classCallCheck(this, MiniSignal); + + this._head = this._tail = undefined; + } + + _createClass(MiniSignal, [{ + key: 'handlers', + value: function handlers() { + var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; + + var node = this._head; + + if (exists) return !!node; + + var ee = []; + + while (node) { + ee.push(node); + node = node._next; + } + + return ee; + } + }, { + key: 'has', + value: function has(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.'); + } + + return node._owner === this; + } + }, { + key: 'dispatch', + value: function dispatch() { + var node = this._head; + + if (!node) return false; + + while (node) { + if (node._once) this.detach(node); + node._fn.apply(node._thisArg, arguments); + node = node._next; + } + + return true; + } + }, { + key: 'add', + value: function add(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#add(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg)); + } + }, { + key: 'once', + value: function once(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#once(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg)); + } + }, { + key: 'detach', + value: function detach(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.'); + } + if (node._owner !== this) return this; + + if (node._prev) node._prev._next = node._next; + if (node._next) node._next._prev = node._prev; + + if (node === this._head) { + this._head = node._next; + if (node._next === null) { + this._tail = null; + } + } else if (node === this._tail) { + this._tail = node._prev; + this._tail._next = null; + } + + node._owner = null; + return this; + } + }, { + key: 'detachAll', + value: function detachAll() { + var node = this._head; + if (!node) return this; + + this._head = this._tail = null; + + while (node) { + node._owner = null; + node = node._next; + } + return this; + } + }]); + + return MiniSignal; +})(); + +MiniSignal.MiniSignalBinding = MiniSignalBinding; + +exports['default'] = MiniSignal; +module.exports = exports['default']; + +},{}],39:[function(require,module,exports){ +'use strict' + +module.exports = function parseURI (str, opts) { + opts = opts || {} + + var o = { + key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], + q: { + name: 'queryKey', + parser: /(?:^|&)([^&=]*)=?([^&]*)/g + }, + parser: { + strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, + loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ + } + } + + var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str) + var uri = {} + var i = 14 + + while (i--) uri[o.key[i]] = m[i] || '' + + uri[o.q.name] = {} + uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { + if ($1) uri[o.q.name][$1] = $2 + }) + + return uri +} + +},{}],40:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +var _accessibleTarget = require('./accessibleTarget'); + +var _accessibleTarget2 = _interopRequireDefault(_accessibleTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// add some extra variables to the container.. +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _accessibleTarget2.default); + +var KEY_CODE_TAB = 9; + +var DIV_TOUCH_SIZE = 100; +var DIV_TOUCH_POS_X = 0; +var DIV_TOUCH_POS_Y = 0; +var DIV_TOUCH_ZINDEX = 2; + +var DIV_HOOK_SIZE = 1; +var DIV_HOOK_POS_X = -1000; +var DIV_HOOK_POS_Y = -1000; +var DIV_HOOK_ZINDEX = 2; + +/** + * The Accessibility manager recreates the ability to tab and have content read by screen + * readers. This is very important as it can possibly help people with disabilities access pixi + * content. + * + * Much like interaction any DisplayObject can be made accessible. This manager will map the + * events as if the mouse was being used, minimizing the effort required to implement. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.accessibility + * + * @class + * @memberof PIXI.accessibility + */ + +var AccessibilityManager = function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + _classCallCheck(this, AccessibilityManager); + + if ((_ismobilejs2.default.tablet || _ismobilejs2.default.phone) && !navigator.isCocoonJS) { + this.createTouchHook(); + } + + // first we create a div that will sit over the PixiJS element. This is where the div overlays will go. + var div = document.createElement('div'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + 'px'; + div.style.left = DIV_TOUCH_POS_Y + 'px'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + + /** + * This is the dom element that will sit over the PixiJS element. This is where the div overlays will go. + * + * @type {HTMLElement} + * @private + */ + this.div = div; + + /** + * A simple pool for storing divs. + * + * @type {*} + * @private + */ + this.pool = []; + + /** + * This is a tick used to check if an object is no longer being rendered. + * + * @type {Number} + * @private + */ + this.renderId = 0; + + /** + * Setting this to true will visually show the divs. + * + * @type {boolean} + */ + this.debug = false; + + /** + * The renderer this accessibility manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * The array of currently active accessible items. + * + * @member {Array<*>} + * @private + */ + this.children = []; + + /** + * pre-bind the functions + * + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + + /** + * stores the state of the manager. If there are no accessible objects or the mouse is moving, this will be false. + * + * @member {Array<*>} + * @private + */ + this.isActive = false; + this.isMobileAccessabillity = false; + + // let listen for tab.. once pressed we can fire up and show the accessibility layer + window.addEventListener('keydown', this._onKeyDown, false); + } + + /** + * Creates the touch hooks. + * + */ + + + AccessibilityManager.prototype.createTouchHook = function createTouchHook() { + var _this = this; + + var hookDiv = document.createElement('button'); + + hookDiv.style.width = DIV_HOOK_SIZE + 'px'; + hookDiv.style.height = DIV_HOOK_SIZE + 'px'; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + 'px'; + hookDiv.style.left = DIV_HOOK_POS_Y + 'px'; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX; + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'HOOK DIV'; + + hookDiv.addEventListener('focus', function () { + _this.isMobileAccessabillity = true; + _this.activate(); + document.body.removeChild(hookDiv); + }); + + document.body.appendChild(hookDiv); + }; + + /** + * Activating will cause the Accessibility layer to be shown. This is called when a user + * preses the tab key. + * + * @private + */ + + + AccessibilityManager.prototype.activate = function activate() { + if (this.isActive) { + return; + } + + this.isActive = true; + + window.document.addEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown, false); + + this.renderer.on('postrender', this.update, this); + + if (this.renderer.view.parentNode) { + this.renderer.view.parentNode.appendChild(this.div); + } + }; + + /** + * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves + * the mouse. + * + * @private + */ + + + AccessibilityManager.prototype.deactivate = function deactivate() { + if (!this.isActive || this.isMobileAccessabillity) { + return; + } + + this.isActive = false; + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.addEventListener('keydown', this._onKeyDown, false); + + this.renderer.off('postrender', this.update); + + if (this.div.parentNode) { + this.div.parentNode.removeChild(this.div); + } + }; + + /** + * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. + * + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + + + AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects(displayObject) { + if (!displayObject.visible) { + return; + } + + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + + displayObject.renderId = this.renderId; + } + + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + this.updateAccessibleObjects(children[i]); + } + }; + + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * + * @private + */ + + + AccessibilityManager.prototype.update = function update() { + if (!this.renderer.renderingToScreen) { + return; + } + + // update children... + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + + var rect = this.renderer.view.getBoundingClientRect(); + var sx = rect.width / this.renderer.width; + var sy = rect.height / this.renderer.height; + + var div = this.div; + + div.style.left = rect.left + 'px'; + div.style.top = rect.top + 'px'; + div.style.width = this.renderer.width + 'px'; + div.style.height = this.renderer.height + 'px'; + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + + core.utils.removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + + i--; + + if (this.children.length === 0) { + this.deactivate(); + } + } else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + + if (child.hitArea) { + div.style.left = (wt.tx + hitArea.x * wt.a) * sx + 'px'; + div.style.top = (wt.ty + hitArea.y * wt.d) * sy + 'px'; + + div.style.width = hitArea.width * wt.a * sx + 'px'; + div.style.height = hitArea.height * wt.d * sy + 'px'; + } else { + hitArea = child.getBounds(); + + this.capHitArea(hitArea); + + div.style.left = hitArea.x * sx + 'px'; + div.style.top = hitArea.y * sy + 'px'; + + div.style.width = hitArea.width * sx + 'px'; + div.style.height = hitArea.height * sy + 'px'; + } + } + } + + // increment the render id.. + this.renderId++; + }; + + /** + * TODO: docs. + * + * @param {Rectangle} hitArea - TODO docs + */ + + + AccessibilityManager.prototype.capHitArea = function capHitArea(hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + + if (hitArea.x + hitArea.width > this.renderer.width) { + hitArea.width = this.renderer.width - hitArea.x; + } + + if (hitArea.y + hitArea.height > this.renderer.height) { + hitArea.height = this.renderer.height - hitArea.y; + } + }; + + /** + * Adds a DisplayObject to the accessibility manager + * + * @private + * @param {DisplayObject} displayObject - The child to make accessible. + */ + + + AccessibilityManager.prototype.addChild = function addChild(displayObject) { + // this.activate(); + + var div = this.pool.pop(); + + if (!div) { + div = document.createElement('button'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + div.style.borderStyle = 'none'; + + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + + if (displayObject.accessibleTitle) { + div.title = displayObject.accessibleTitle; + } else if (!displayObject.accessibleTitle && !displayObject.accessibleHint) { + div.title = 'displayObject ' + this.tabIndex; + } + + if (displayObject.accessibleHint) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + + // + + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + + /** + * Maps the div button press to pixi's InteractionManager (click) + * + * @private + * @param {MouseEvent} e - The click event. + */ + + + AccessibilityManager.prototype._onClick = function _onClick(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixi's InteractionManager (mouseover) + * + * @private + * @param {FocusEvent} e - The focus event. + */ + + + AccessibilityManager.prototype._onFocus = function _onFocus(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixi's InteractionManager (mouseout) + * + * @private + * @param {FocusEvent} e - The focusout event. + */ + + + AccessibilityManager.prototype._onFocusOut = function _onFocusOut(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); + }; + + /** + * Is called when a key is pressed + * + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + + + AccessibilityManager.prototype._onKeyDown = function _onKeyDown(e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + + this.activate(); + }; + + /** + * Is called when the mouse moves across the renderer element + * + * @private + */ + + + AccessibilityManager.prototype._onMouseMove = function _onMouseMove() { + this.deactivate(); + }; + + /** + * Destroys the accessibility manager + * + */ + + + AccessibilityManager.prototype.destroy = function destroy() { + this.div = null; + + for (var i = 0; i < this.children.length; i++) { + this.children[i].div = null; + } + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.removeEventListener('keydown', this._onKeyDown); + + this.pool = null; + this.children = null; + this.renderer = null; + }; + + return AccessibilityManager; +}(); + +exports.default = AccessibilityManager; + + +core.WebGLRenderer.registerPlugin('accessibility', AccessibilityManager); +core.CanvasRenderer.registerPlugin('accessibility', AccessibilityManager); + +},{"../core":65,"./accessibleTarget":41,"ismobilejs":4}],41:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Default property values of accessible objects + * used by {@link PIXI.accessibility.AccessibilityManager}. + * + * @function accessibleTarget + * @memberof PIXI.accessibility + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibility.accessibleTarget + * ); + */ +exports.default = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * + * @member {boolean} + */ + accessible: false, + + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * + * @member {string} + */ + accessibleTitle: null, + + /** + * Sets the aria-label attribute of the shadow div + * + * @member {string} + */ + accessibleHint: null, + + /** + * @todo Needs docs. + */ + tabIndex: 0, + + /** + * @todo Needs docs. + */ + _accessibleActive: false, + + /** + * @todo Needs docs. + */ + _accessibleDiv: false +}; + +},{}],42:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _accessibleTarget = require('./accessibleTarget'); + +Object.defineProperty(exports, 'accessibleTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_accessibleTarget).default; + } +}); + +var _AccessibilityManager = require('./AccessibilityManager'); + +Object.defineProperty(exports, 'AccessibilityManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AccessibilityManager).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./AccessibilityManager":40,"./accessibleTarget":41}],43:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +var _Container = require('./display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _ticker = require('./ticker'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _const = require('./const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Convenience class to create a new PIXI application. + * This class automatically creates the renderer, ticker + * and root container. + * + * @example + * // Create the application + * const app = new PIXI.Application(); + * + * // Add the view to the DOM + * document.body.appendChild(app.view); + * + * // ex, add display objects + * app.stage.addChild(PIXI.Sprite.fromImage('something.png')); + * + * @class + * @memberof PIXI + */ +var Application = function () { + // eslint-disable-next-line valid-jsdoc + /** + * @param {object} [options] - The optional renderer parameters + * @param {boolean} [options.autoStart=true] - automatically starts the rendering after the construction. + * Note that setting this parameter to false does NOT stop the shared ticker even if you set + * options.sharedTicker to true in case that it is already started. Stop it by your own. + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great **webgl only** + * @param {boolean} [options.legacy=false] - `true` to ensure compatibility with older / less advanced devices. + * If you experience unexplained flickering try setting this to true. **webgl only** + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card **webgl only** + * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.ticker.shared, `false` to create new ticker. + * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.loaders.shared, `false` to create new Loader. + */ + function Application(options, arg2, arg3, arg4, arg5) { + _classCallCheck(this, Application); + + // Support for constructor(width, height, options, noWebGL, useSharedTicker) + if (typeof options === 'number') { + options = Object.assign({ + width: options, + height: arg2 || _settings2.default.RENDER_OPTIONS.height, + forceCanvas: !!arg4, + sharedTicker: !!arg5 + }, arg3); + } + + /** + * The default options, so we mixin functionality later. + * @member {object} + * @protected + */ + this._options = options = Object.assign({ + autoStart: true, + sharedTicker: false, + forceCanvas: false, + sharedLoader: false + }, options); + + /** + * WebGL renderer if available, otherwise CanvasRenderer + * @member {PIXI.WebGLRenderer|PIXI.CanvasRenderer} + */ + this.renderer = (0, _autoDetectRenderer.autoDetectRenderer)(options); + + /** + * The root display container that's rendered. + * @member {PIXI.Container} + */ + this.stage = new _Container2.default(); + + /** + * Internal reference to the ticker + * @member {PIXI.ticker.Ticker} + * @private + */ + this._ticker = null; + + /** + * Ticker for doing render updates. + * @member {PIXI.ticker.Ticker} + * @default PIXI.ticker.shared + */ + this.ticker = options.sharedTicker ? _ticker.shared : new _ticker.Ticker(); + + // Start the rendering + if (options.autoStart) { + this.start(); + } + } + + /** + * Render the current stage. + */ + Application.prototype.render = function render() { + this.renderer.render(this.stage); + }; + + /** + * Convenience method for stopping the render. + */ + + + Application.prototype.stop = function stop() { + this._ticker.stop(); + }; + + /** + * Convenience method for starting the render. + */ + + + Application.prototype.start = function start() { + this._ticker.start(); + }; + + /** + * Reference to the renderer's canvas element. + * @member {HTMLCanvasElement} + * @readonly + */ + + + /** + * Destroy and don't use after this. + * @param {Boolean} [removeView=false] Automatically remove canvas from DOM. + */ + Application.prototype.destroy = function destroy(removeView) { + var oldTicker = this._ticker; + + this.ticker = null; + + oldTicker.destroy(); + + this.stage.destroy(); + this.stage = null; + + this.renderer.destroy(removeView); + this.renderer = null; + + this._options = null; + }; + + _createClass(Application, [{ + key: 'ticker', + set: function set(ticker) // eslint-disable-line require-jsdoc + { + if (this._ticker) { + this._ticker.remove(this.render, this); + } + this._ticker = ticker; + if (ticker) { + ticker.add(this.render, this, _const.UPDATE_PRIORITY.LOW); + } + }, + get: function get() // eslint-disable-line require-jsdoc + { + return this._ticker; + } + }, { + key: 'view', + get: function get() { + return this.renderer.view; + } + + /** + * Reference to the renderer's screen rectangle. Its safe to use as filterArea or hitArea for whole screen + * @member {PIXI.Rectangle} + * @readonly + */ + + }, { + key: 'screen', + get: function get() { + return this.renderer.screen; + } + }]); + + return Application; +}(); + +exports.default = Application; + +},{"./autoDetectRenderer":45,"./const":46,"./display/Container":48,"./settings":101,"./ticker":121}],44:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function checkPrecision(src, def) { + if (src instanceof Array) { + if (src[0].substring(0, 9) !== 'precision') { + var copy = src.slice(0); + + copy.unshift('precision ' + def + ' float;'); + + return copy; + } + } else if (src.substring(0, 9) !== 'precision') { + return 'precision ' + def + ' float;\n' + src; + } + + return src; +} + +/** + * Wrapper class, webGL Shader for Pixi. + * Adds precision string if vertexSrc or fragmentSrc have no mention of it. + * + * @class + * @extends GLShader + * @memberof PIXI + */ + +var Shader = function (_GLShader) { + _inherits(Shader, _GLShader); + + /** + * + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + * @param {string|string[]} vertexSrc - The vertex shader source as an array of strings. + * @param {string|string[]} fragmentSrc - The fragment shader source as an array of strings. + */ + function Shader(gl, vertexSrc, fragmentSrc) { + _classCallCheck(this, Shader); + + return _possibleConstructorReturn(this, _GLShader.call(this, gl, checkPrecision(vertexSrc, _settings2.default.PRECISION_VERTEX), checkPrecision(fragmentSrc, _settings2.default.PRECISION_FRAGMENT))); + } + + return Shader; +}(_pixiGlCore.GLShader); + +exports.default = Shader; + +},{"./settings":101,"pixi-gl-core":12}],45:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = autoDetectRenderer; + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// eslint-disable-next-line valid-jsdoc +/** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by + * the browser then this function will return a canvas renderer + * + * @memberof PIXI + * @function autoDetectRenderer + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great **webgl only** + * @param {boolean} [options.legacy=false] - `true` to ensure compatibility with older / less advanced devices. + * If you experience unexplained flickering try setting this to true. **webgl only** + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card **webgl only** + * @return {PIXI.WebGLRenderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ +function autoDetectRenderer(options, arg1, arg2, arg3) { + // Backward-compatible support for noWebGL option + var forceCanvas = options && options.forceCanvas; + + if (arg3 !== undefined) { + forceCanvas = arg3; + } + + if (!forceCanvas && utils.isWebGLSupported()) { + return new _WebGLRenderer2.default(options, arg1, arg2); + } + + return new _CanvasRenderer2.default(options, arg1, arg2); +} + +},{"./renderers/canvas/CanvasRenderer":77,"./renderers/webgl/WebGLRenderer":84,"./utils":125}],46:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * String of the current PIXI version. + * + * @static + * @constant + * @memberof PIXI + * @name VERSION + * @type {string} + */ +var VERSION = exports.VERSION = '4.6.2'; + +/** + * Two Pi. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var PI_2 = exports.PI_2 = Math.PI * 2; + +/** + * Conversion factor for converting radians to degrees. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var RAD_TO_DEG = exports.RAD_TO_DEG = 180 / Math.PI; + +/** + * Conversion factor for converting degrees to radians. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var DEG_TO_RAD = exports.DEG_TO_RAD = Math.PI / 180; + +/** + * Constant to identify the Renderer Type. + * + * @static + * @constant + * @memberof PIXI + * @name RENDERER_TYPE + * @type {object} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ +var RENDERER_TYPE = exports.RENDERER_TYPE = { + UNKNOWN: 0, + WEBGL: 1, + CANVAS: 2 +}; + +/** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * + * @static + * @constant + * @memberof PIXI + * @name BLEND_MODES + * @type {object} + * @property {number} NORMAL + * @property {number} ADD + * @property {number} MULTIPLY + * @property {number} SCREEN + * @property {number} OVERLAY + * @property {number} DARKEN + * @property {number} LIGHTEN + * @property {number} COLOR_DODGE + * @property {number} COLOR_BURN + * @property {number} HARD_LIGHT + * @property {number} SOFT_LIGHT + * @property {number} DIFFERENCE + * @property {number} EXCLUSION + * @property {number} HUE + * @property {number} SATURATION + * @property {number} COLOR + * @property {number} LUMINOSITY + */ +var BLEND_MODES = exports.BLEND_MODES = { + NORMAL: 0, + ADD: 1, + MULTIPLY: 2, + SCREEN: 3, + OVERLAY: 4, + DARKEN: 5, + LIGHTEN: 6, + COLOR_DODGE: 7, + COLOR_BURN: 8, + HARD_LIGHT: 9, + SOFT_LIGHT: 10, + DIFFERENCE: 11, + EXCLUSION: 12, + HUE: 13, + SATURATION: 14, + COLOR: 15, + LUMINOSITY: 16, + NORMAL_NPM: 17, + ADD_NPM: 18, + SCREEN_NPM: 19 +}; + +/** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * + * @static + * @constant + * @memberof PIXI + * @name DRAW_MODES + * @type {object} + * @property {number} POINTS + * @property {number} LINES + * @property {number} LINE_LOOP + * @property {number} LINE_STRIP + * @property {number} TRIANGLES + * @property {number} TRIANGLE_STRIP + * @property {number} TRIANGLE_FAN + */ +var DRAW_MODES = exports.DRAW_MODES = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6 +}; + +/** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @static + * @constant + * @memberof PIXI + * @name SCALE_MODES + * @type {object} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ +var SCALE_MODES = exports.SCALE_MODES = { + LINEAR: 0, + NEAREST: 1 +}; + +/** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wraping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as webGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * + * @static + * @constant + * @name WRAP_MODES + * @memberof PIXI + * @type {object} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ +var WRAP_MODES = exports.WRAP_MODES = { + CLAMP: 0, + REPEAT: 1, + MIRRORED_REPEAT: 2 +}; + +/** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * + * @static + * @constant + * @name GC_MODES + * @memberof PIXI + * @type {object} + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ +var GC_MODES = exports.GC_MODES = { + AUTO: 0, + MANUAL: 1 +}; + +/** + * Regexp for image type by extension. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `image.png` + */ +var URL_FILE_EXTENSION = exports.URL_FILE_EXTENSION = /\.(\w{3,4})(?:$|\?|#)/i; + +/** + * Regexp for data URI. + * Based on: {@link https://github.com/ragingwind/data-uri-regex} + * + * @static + * @constant + * @name DATA_URI + * @memberof PIXI + * @type {RegExp|string} + * @example data:image/png;base64 + */ +var DATA_URI = exports.DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;(charset=[\w-]+|base64))?,(.*)/i; + +/** + * Regexp for SVG size. + * + * @static + * @constant + * @name SVG_SIZE + * @memberof PIXI + * @type {RegExp|string} + * @example <svg width="100" height="100"></svg> + */ +var SVG_SIZE = exports.SVG_SIZE = /]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len + +/** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * + * @static + * @constant + * @name SHAPES + * @memberof PIXI + * @type {object} + * @property {number} POLY Polygon + * @property {number} RECT Rectangle + * @property {number} CIRC Circle + * @property {number} ELIP Ellipse + * @property {number} RREC Rounded Rectangle + */ +var SHAPES = exports.SHAPES = { + POLY: 0, + RECT: 1, + CIRC: 2, + ELIP: 3, + RREC: 4 +}; + +/** + * Constants that specify float precision in shaders. + * + * @static + * @constant + * @name PRECISION + * @memberof PIXI + * @type {object} + * @property {string} LOW='lowp' + * @property {string} MEDIUM='mediump' + * @property {string} HIGH='highp' + */ +var PRECISION = exports.PRECISION = { + LOW: 'lowp', + MEDIUM: 'mediump', + HIGH: 'highp' +}; + +/** + * Constants that specify the transform type. + * + * @static + * @constant + * @name TRANSFORM_MODE + * @memberof PIXI + * @type {object} + * @property {number} STATIC + * @property {number} DYNAMIC + */ +var TRANSFORM_MODE = exports.TRANSFORM_MODE = { + STATIC: 0, + DYNAMIC: 1 +}; + +/** + * Constants that define the type of gradient on text. + * + * @static + * @constant + * @name TEXT_GRADIENT + * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL Vertical gradient + * @property {number} LINEAR_HORIZONTAL Linear gradient + */ +var TEXT_GRADIENT = exports.TEXT_GRADIENT = { + LINEAR_VERTICAL: 0, + LINEAR_HORIZONTAL: 1 +}; + +/** + * Represents the update priorities used by internal PIXI classes when registered with + * the {@link PIXI.ticker.Ticker} object. Higher priority items are updated first and lower + * priority items, such as render, should go later. + * + * @static + * @constant + * @name UPDATE_PRIORITY + * @memberof PIXI + * @type {object} + * @property {number} INTERACTION=50 Highest priority, used for {@link PIXI.interaction.InteractionManager} + * @property {number} HIGH=25 High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.extras.AnimatedSprite} + * @property {number} NORMAL=0 Default priority for ticker events, see {@link PIXI.ticker.Ticker#add}. + * @property {number} LOW=-25 Low priority used for {@link PIXI.Application} rendering. + * @property {number} UTILITY=-50 Lowest priority used for {@link PIXI.prepare.BasePrepare} utility. + */ +var UPDATE_PRIORITY = exports.UPDATE_PRIORITY = { + INTERACTION: 50, + HIGH: 25, + NORMAL: 0, + LOW: -25, + UTILITY: -50 +}; + +},{}],47:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * 'Builder' pattern for bounds rectangles + * Axis-Aligned Bounding Box + * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems + * + * @class + * @memberof PIXI + */ +var Bounds = function () { + /** + * + */ + function Bounds() { + _classCallCheck(this, Bounds); + + /** + * @member {number} + * @default 0 + */ + this.minX = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.minY = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxX = -Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxY = -Infinity; + + this.rect = null; + } + + /** + * Checks if bounds are empty. + * + * @return {boolean} True if empty. + */ + + + Bounds.prototype.isEmpty = function isEmpty() { + return this.minX > this.maxX || this.minY > this.maxY; + }; + + /** + * Clears the bounds and resets. + * + */ + + + Bounds.prototype.clear = function clear() { + this.updateID++; + + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * + * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty + * @returns {PIXI.Rectangle} A rectangle of the bounds + */ + + + Bounds.prototype.getRectangle = function getRectangle(rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return _math.Rectangle.EMPTY; + } + + rect = rect || new _math.Rectangle(0, 0, 1, 1); + + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + + return rect; + }; + + /** + * This function should be inlined when its possible. + * + * @param {PIXI.Point} point - The point to add. + */ + + + Bounds.prototype.addPoint = function addPoint(point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + }; + + /** + * Adds a quad, not transformed + * + * @param {Float32Array} vertices - The verts to add. + */ + + + Bounds.prototype.addQuad = function addQuad(vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = vertices[0]; + var y = vertices[1]; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds sprite frame, transformed. + * + * @param {PIXI.TransformBase} transform - TODO + * @param {number} x0 - TODO + * @param {number} y0 - TODO + * @param {number} x1 - TODO + * @param {number} y1 - TODO + */ + + + Bounds.prototype.addFrame = function addFrame(transform, x0, y0, x1, y1) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = a * x0 + c * y0 + tx; + var y = b * x0 + d * y0 + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y0 + tx; + y = b * x1 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x0 + c * y1 + tx; + y = b * x0 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y1 + tx; + y = b * x1 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Add an array of vertices + * + * @param {PIXI.TransformBase} transform - TODO + * @param {Float32Array} vertices - TODO + * @param {number} beginOffset - TODO + * @param {number} endOffset - TODO + */ + + + Bounds.prototype.addVertices = function addVertices(transform, vertices, beginOffset, endOffset) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = a * rawX + c * rawY + tx; + var y = d * rawY + b * rawX + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds other Bounds + * + * @param {PIXI.Bounds} bounds - TODO + */ + + + Bounds.prototype.addBounds = function addBounds(bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + }; + + /** + * Adds other Bounds, masked with Bounds + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Bounds} mask - TODO + */ + + + Bounds.prototype.addBoundsMask = function addBoundsMask(bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + /** + * Adds other Bounds, masked with Rectangle + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Rectangle} area - TODO + */ + + + Bounds.prototype.addBoundsArea = function addBoundsArea(bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : area.x + area.width; + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : area.y + area.height; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + return Bounds; +}(); + +exports.default = Bounds; + +},{"../math":70}],48:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _DisplayObject2 = require('./DisplayObject'); + +var _DisplayObject3 = _interopRequireDefault(_DisplayObject2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A Container represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + *```js + * let container = new PIXI.Container(); + * container.addChild(sprite); + * ``` + * + * @class + * @extends PIXI.DisplayObject + * @memberof PIXI + */ +var Container = function (_DisplayObject) { + _inherits(Container, _DisplayObject); + + /** + * + */ + function Container() { + _classCallCheck(this, Container); + + /** + * The array of children of this container. + * + * @member {PIXI.DisplayObject[]} + * @readonly + */ + var _this = _possibleConstructorReturn(this, _DisplayObject.call(this)); + + _this.children = []; + return _this; + } + + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified + * + * @private + */ + + + Container.prototype.onChildrenChange = function onChildrenChange() {} + /* empty */ + + + /** + * Adds one or more children to the container. + * + * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container + * @return {PIXI.DisplayObject} The first child that was added. + */ + ; + + Container.prototype.addChild = function addChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.addChild(arguments[i]); + } + } else { + // if the child has a parent then lets remove it as PixiJS objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.push(child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + child.emit('added', this); + } + + return child; + }; + + /** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @return {PIXI.DisplayObject} The child that was added. + */ + + + Container.prototype.addChildAt = function addChildAt(child, index) { + if (index < 0 || index > this.children.length) { + throw new Error(child + 'addChildAt: The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.splice(index, 0, child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + + return child; + }; + + /** + * Swaps the position of 2 Display Objects within this container. + * + * @param {PIXI.DisplayObject} child - First display object to swap + * @param {PIXI.DisplayObject} child2 - Second display object to swap + */ + + + Container.prototype.swapChildren = function swapChildren(child, child2) { + if (child === child2) { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; + + /** + * Returns the index position of a child DisplayObject instance + * + * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify + * @return {number} The index position of the child display object to identify + */ + + + Container.prototype.getChildIndex = function getChildIndex(child) { + var index = this.children.indexOf(child); + + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + }; + + /** + * Changes the position of an existing child in the display object container + * + * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number + * @param {number} index - The resulting index number for the child display object + */ + + + Container.prototype.setChildIndex = function setChildIndex(child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error('The supplied index is out of bounds'); + } + + var currentIndex = this.getChildIndex(child); + + (0, _utils.removeItems)(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + + this.onChildrenChange(index); + }; + + /** + * Returns the child at the specified index + * + * @param {number} index - The index to get the child at + * @return {PIXI.DisplayObject} The child at the given index, if any. + */ + + + Container.prototype.getChildAt = function getChildAt(index) { + if (index < 0 || index >= this.children.length) { + throw new Error('getChildAt: Index (' + index + ') does not exist.'); + } + + return this.children[index]; + }; + + /** + * Removes one or more children from the container. + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove + * @return {PIXI.DisplayObject} The first child that was removed. + */ + + + Container.prototype.removeChild = function removeChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.removeChild(arguments[i]); + } + } else { + var index = this.children.indexOf(child); + + if (index === -1) return null; + + child.parent = null; + // ensure child transform will be recalculated + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + } + + return child; + }; + + /** + * Removes a child from the specified index position. + * + * @param {number} index - The index to get the child from + * @return {PIXI.DisplayObject} The child that was removed. + */ + + + Container.prototype.removeChildAt = function removeChildAt(index) { + var child = this.getChildAt(index); + + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + + return child; + }; + + /** + * Removes all children from this container that are within the begin and end indexes. + * + * @param {number} [beginIndex=0] - The beginning position. + * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. + * @returns {DisplayObject[]} List of removed children + */ + + + Container.prototype.removeChildren = function removeChildren() { + var beginIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var endIndex = arguments[1]; + + var begin = beginIndex; + var end = typeof endIndex === 'number' ? endIndex : this.children.length; + var range = end - begin; + var removed = void 0; + + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } + + this._boundsID++; + + this.onChildrenChange(beginIndex); + + for (var _i = 0; _i < removed.length; ++_i) { + removed[_i].emit('removed', this); + } + + return removed; + } else if (range === 0 && this.children.length === 0) { + return []; + } + + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + }; + + /** + * Updates the transform on all children of this container for rendering + */ + + + Container.prototype.updateTransform = function updateTransform() { + this._boundsID++; + + this.transform.updateTransform(this.parent.transform); + + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + + if (child.visible) { + child.updateTransform(); + } + } + }; + + /** + * Recalculates the bounds of the container. + * + */ + + + Container.prototype.calculateBounds = function calculateBounds() { + this._bounds.clear(); + + this._calculateBounds(); + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (!child.visible || !child.renderable) { + continue; + } + + child.calculateBounds(); + + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + child._mask.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, child._mask._bounds); + } else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } else { + this._bounds.addBounds(child._bounds); + } + } + + this._lastBoundsID = this._boundsID; + }; + + /** + * Recalculates the bounds of the object. Override this to + * calculate the bounds of the specific object (not including children). + * + */ + + + Container.prototype._calculateBounds = function _calculateBounds() {} + // FILL IN// + + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderWebGL = function renderWebGL(renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + // do a quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) { + this.renderAdvancedWebGL(renderer); + } else { + this._renderWebGL(renderer); + + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderWebGL(renderer); + } + } + }; + + /** + * Render the object using the WebGL renderer and advanced features. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { + renderer.flush(); + + var filters = this._filters; + var mask = this._mask; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + + this._enabledFilters.length = 0; + + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + + if (this._enabledFilters.length) { + renderer.filterManager.pushFilter(this, this._enabledFilters); + } + } + + if (mask) { + renderer.maskManager.pushMask(this, this._mask); + } + + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); + + // now loop through the children and make sure they get rendered + for (var _i2 = 0, j = this.children.length; _i2 < j; _i2++) { + this.children[_i2].renderWebGL(renderer); + } + + renderer.flush(); + + if (mask) { + renderer.maskManager.popMask(this, this._mask); + } + + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filterManager.popFilter(); + } + }; + + /** + * To be overridden by the subclasses. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype._renderWebGL = function _renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * To be overridden by the subclass + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype._renderCanvas = function _renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderCanvas = function renderCanvas(renderer) { + // if not visible or the alpha is 0 then no need to render this + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + if (this._mask) { + renderer.maskManager.pushMask(this._mask); + } + + this._renderCanvas(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderCanvas(renderer); + } + + if (this._mask) { + renderer.maskManager.popMask(renderer); + } + }; + + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Container.prototype.destroy = function destroy(options) { + _DisplayObject.prototype.destroy.call(this); + + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + + var oldChildren = this.removeChildren(0, this.children.length); + + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + }; + + /** + * The width of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Container, [{ + key: 'width', + get: function get() { + return this.scale.x * this.getLocalBounds().width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var width = this.getLocalBounds().width; + + if (width !== 0) { + this.scale.x = value / width; + } else { + this.scale.x = 1; + } + + this._width = value; + } + + /** + * The height of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.scale.y * this.getLocalBounds().height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var height = this.getLocalBounds().height; + + if (height !== 0) { + this.scale.y = value / height; + } else { + this.scale.y = 1; + } + + this._height = value; + } + }]); + + return Container; +}(_DisplayObject3.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = Container; +Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + +},{"../utils":125,"./DisplayObject":49}],49:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TransformStatic = require('./TransformStatic'); + +var _TransformStatic2 = _interopRequireDefault(_TransformStatic); + +var _Transform = require('./Transform'); + +var _Transform2 = _interopRequireDefault(_Transform); + +var _Bounds = require('./Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _math = require('../math'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// _tempDisplayObjectParent = new DisplayObject(); + +/** + * The base class for all objects that are rendered on the screen. + * This is an abstract class and should not be used on its own rather it should be extended. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var DisplayObject = function (_EventEmitter) { + _inherits(DisplayObject, _EventEmitter); + + /** + * + */ + function DisplayObject() { + _classCallCheck(this, DisplayObject); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + var TransformClass = _settings2.default.TRANSFORM_MODE === _const.TRANSFORM_MODE.STATIC ? _TransformStatic2.default : _Transform2.default; + + _this.tempDisplayObjectParent = null; + + // TODO: need to create Transform from factory + /** + * World transform and local transform of this object. + * This will become read-only later, please do not assign anything there unless you know what are you doing + * + * @member {PIXI.TransformBase} + */ + _this.transform = new TransformClass(); + + /** + * The opacity of the object. + * + * @member {number} + */ + _this.alpha = 1; + + /** + * The visibility of the object. If false the object will not be drawn, and + * the updateTransform function will not be called. + * + * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually + * + * @member {boolean} + */ + _this.visible = true; + + /** + * Can this object be rendered, if false the object will not be drawn but the updateTransform + * methods will still be called. + * + * Only affects recursive calls from parent. You can ask for bounds manually + * + * @member {boolean} + */ + _this.renderable = true; + + /** + * The display object container that contains this display object. + * + * @member {PIXI.Container} + * @readonly + */ + _this.parent = null; + + /** + * The multiplied alpha of the displayObject + * + * @member {number} + * @readonly + */ + _this.worldAlpha = 1; + + /** + * The area the filter is applied to. This is used as more of an optimisation + * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle + * + * Also works as an interaction mask + * + * @member {PIXI.Rectangle} + */ + _this.filterArea = null; + + _this._filters = null; + _this._enabledFilters = null; + + /** + * The bounds object, this is used to calculate and store the bounds of the displayObject + * + * @member {PIXI.Rectangle} + * @private + */ + _this._bounds = new _Bounds2.default(); + _this._boundsID = 0; + _this._lastBoundsID = -1; + _this._boundsRect = null; + _this._localBoundsRect = null; + + /** + * The original, cached mask of the object + * + * @member {PIXI.Graphics|PIXI.Sprite} + * @private + */ + _this._mask = null; + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + + /** + * Fired when this DisplayObject is added to a Container. + * + * @event PIXI.DisplayObject#added + * @param {PIXI.Container} container - The container added to. + */ + + /** + * Fired when this DisplayObject is removed from a Container. + * + * @event PIXI.DisplayObject#removed + * @param {PIXI.Container} container - The container removed from. + */ + return _this; + } + + /** + * @private + * @member {PIXI.DisplayObject} + */ + + + /** + * Updates the object transform for rendering + * + * TODO - Optimization pass! + */ + DisplayObject.prototype.updateTransform = function updateTransform() { + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + this._bounds.updateID++; + }; + + /** + * recursively updates transform of all objects from the root to this one + * internal function for toLocal() + */ + + + DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform() { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + }; + + /** + * Retrieves the bounds of the displayObject as a rectangle object. + * + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @param {PIXI.Rectangle} rect - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getBounds = function getBounds(skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + + if (this._boundsID !== this._lastBoundsID) { + this.calculateBounds(); + } + + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new _math.Rectangle(); + } + + rect = this._boundsRect; + } + + return this._bounds.getRectangle(rect); + }; + + /** + * Retrieves the local bounds of the displayObject as a rectangle object + * + * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getLocalBounds = function getLocalBounds(rect) { + var transformRef = this.transform; + var parentRef = this.parent; + + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + var bounds = this.getBounds(false, rect); + + this.parent = parentRef; + this.transform = transformRef; + + return bounds; + }; + + /** + * Calculates the global position of the display object + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform. + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toGlobal = function toGlobal(position, point) { + var skipUpdate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; + + /** + * Calculates the local position of the display object relative to another point + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toLocal = function toLocal(position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + DisplayObject.prototype.renderCanvas = function renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Set the parent Container of this DisplayObject + * + * @param {PIXI.Container} container - The Container to add this DisplayObject to + * @return {PIXI.Container} The Container that this DisplayObject was added to + */ + ; + + DisplayObject.prototype.setParent = function setParent(container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); + } + + container.addChild(this); + + return container; + }; + + /** + * Convenience function to set the position, scale, skew and pivot at once. + * + * @param {number} [x=0] - The X position + * @param {number} [y=0] - The Y position + * @param {number} [scaleX=1] - The X scale value + * @param {number} [scaleY=1] - The Y scale value + * @param {number} [rotation=0] - The rotation + * @param {number} [skewX=0] - The X skew value + * @param {number} [skewY=0] - The Y skew value + * @param {number} [pivotX=0] - The X pivot value + * @param {number} [pivotY=0] - The Y pivot value + * @return {PIXI.DisplayObject} The DisplayObject instance + */ + + + DisplayObject.prototype.setTransform = function setTransform() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var scaleX = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var scaleY = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var rotation = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var skewX = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + var skewY = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + var pivotX = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; + var pivotY = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0; + + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + + return this; + }; + + /** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy`. + * + */ + + + DisplayObject.prototype.destroy = function destroy() { + this.removeAllListeners(); + if (this.parent) { + this.parent.removeChild(this); + } + this.transform = null; + + this.parent = null; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this.filterArea = null; + + this.interactive = false; + this.interactiveChildren = false; + + this._destroyed = true; + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + * + * @member {number} + */ + + + _createClass(DisplayObject, [{ + key: '_tempDisplayObjectParent', + get: function get() { + if (this.tempDisplayObjectParent === null) { + this.tempDisplayObjectParent = new DisplayObject(); + } + + return this.tempDisplayObjectParent; + } + }, { + key: 'x', + get: function get() { + return this.position.x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.x = value; + } + + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + * + * @member {number} + */ + + }, { + key: 'y', + get: function get() { + return this.position.y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.y = value; + } + + /** + * Current transform of the object based on world (parent) factors + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'worldTransform', + get: function get() { + return this.transform.worldTransform; + } + + /** + * Current transform of the object based on local factors: position, scale, other stuff + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'localTransform', + get: function get() { + return this.transform.localTransform; + } + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'position', + get: function get() { + return this.transform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.copy(value); + } + + /** + * The scale factor of the object. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'scale', + get: function get() { + return this.transform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.scale.copy(value); + } + + /** + * The pivot point of the displayObject that it rotates around + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'pivot', + get: function get() { + return this.transform.pivot; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.pivot.copy(value); + } + + /** + * The skew factor for the object in radians. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'skew', + get: function get() { + return this.transform.skew; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.skew.copy(value); + } + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + }, { + key: 'rotation', + get: function get() { + return this.transform.rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.rotation = value; + } + + /** + * Indicates if the object is globally visible. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'worldVisible', + get: function get() { + var item = this; + + do { + if (!item.visible) { + return false; + } + + item = item.parent; + } while (item); + + return true; + } + + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PIXI a regular mask must be a + * PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it + * utilises shape clipping. To remove a mask, set this property to null. + * + * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + * + * @member {PIXI.Graphics|PIXI.Sprite} + */ + + }, { + key: 'mask', + get: function get() { + return this._mask; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._mask) { + this._mask.renderable = true; + } + + this._mask = value; + + if (this._mask) { + this._mask.renderable = false; + } + } + + /** + * Sets the filters for the displayObject. + * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * To remove filters simply set this property to 'null' + * + * @member {PIXI.Filter[]} + */ + + }, { + key: 'filters', + get: function get() { + return this._filters && this._filters.slice(); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._filters = value && value.slice(); + } + }]); + + return DisplayObject; +}(_eventemitter2.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = DisplayObject; +DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + +},{"../const":46,"../math":70,"../settings":101,"./Bounds":47,"./Transform":50,"./TransformStatic":52,"eventemitter3":3}],50:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Generic class to deal with traditional 2D matrix transforms + * local transformation is calculated from position,scale,skew and rotation + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var Transform = function (_TransformBase) { + _inherits(Transform, _TransformBase); + + /** + * + */ + function Transform() { + _classCallCheck(this, Transform); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.Point} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.Point(0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.Point} + */ + _this.scale = new _math.Point(1, 1); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.Point} + */ + _this.pivot = new _math.Point(0, 0); + + /** + * The rotation value of the object, in radians + * + * @member {Number} + * @private + */ + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + return _this; + } + + /** + * Updates the skew values when the skew or rotation changes. + * + * @private + */ + + + Transform.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + }; + + /** + * Updates only local matrix + */ + + + Transform.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + Transform.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + Transform.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(Transform, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return Transform; +}(_TransformBase3.default); + +exports.default = Transform; + +},{"../math":70,"./TransformBase":51}],51:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Generic class to deal with traditional 2D matrix transforms + * + * @class + * @memberof PIXI + */ +var TransformBase = function () { + /** + * + */ + function TransformBase() { + _classCallCheck(this, TransformBase); + + /** + * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds() + * + * @member {PIXI.Matrix} + */ + this.worldTransform = new _math.Matrix(); + + /** + * The local matrix transform + * + * @member {PIXI.Matrix} + */ + this.localTransform = new _math.Matrix(); + + this._worldID = 0; + this._parentID = 0; + } + + /** + * TransformBase does not have decomposition, so this function wont do anything + */ + + + TransformBase.prototype.updateLocalTransform = function updateLocalTransform() {} + // empty + + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.TransformBase} parentTransform - The transform of the parent of this object + */ + ; + + TransformBase.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + return TransformBase; +}(); + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ + + +exports.default = TransformBase; +TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; + +TransformBase.IDENTITY = new TransformBase(); + +},{"../math":70}],52:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Transform that takes care about its versions + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var TransformStatic = function (_TransformBase) { + _inherits(TransformStatic, _TransformBase); + + /** + * + */ + function TransformStatic() { + _classCallCheck(this, TransformStatic); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.ObservablePoint} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.ObservablePoint} + */ + _this.scale = new _math.ObservablePoint(_this.onChange, _this, 1, 1); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.ObservablePoint} + */ + _this.pivot = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + + _this._localID = 0; + _this._currentLocalID = 0; + return _this; + } + + /** + * Called when a value changes. + * + * @private + */ + + + TransformStatic.prototype.onChange = function onChange() { + this._localID++; + }; + + /** + * Called when skew or rotation changes + * + * @private + */ + + + TransformStatic.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + + this._localID++; + }; + + /** + * Updates only local matrix + */ + + + TransformStatic.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + TransformStatic.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._parentID = parentTransform._worldID; + + // update the id of the transform.. + this._worldID++; + } + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + TransformStatic.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + this._localID++; + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(TransformStatic, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return TransformStatic; +}(_TransformBase3.default); + +exports.default = TransformStatic; + +},{"../math":70,"./TransformBase":51}],53:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _GraphicsData = require('./GraphicsData'); + +var _GraphicsData2 = _interopRequireDefault(_GraphicsData); + +var _Sprite = require('../sprites/Sprite'); + +var _Sprite2 = _interopRequireDefault(_Sprite); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Bounds = require('../display/Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _bezierCurveTo2 = require('./utils/bezierCurveTo'); + +var _bezierCurveTo3 = _interopRequireDefault(_bezierCurveTo2); + +var _CanvasRenderer = require('../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var canvasRenderer = void 0; +var tempMatrix = new _math.Matrix(); +var tempPoint = new _math.Point(); +var tempColor1 = new Float32Array(4); +var tempColor2 = new Float32Array(4); + +/** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Graphics = function (_Container) { + _inherits(Graphics, _Container); + + /** + * + * @param {boolean} [nativeLines=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + */ + function Graphics() { + var nativeLines = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + _classCallCheck(this, Graphics); + + /** + * The alpha value used when filling the Graphics object. + * + * @member {number} + * @default 1 + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @member {number} + * @default 0 + */ + _this.lineWidth = 0; + + /** + * If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * + * @member {boolean} + */ + _this.nativeLines = nativeLines; + + /** + * The color of any lines drawn. + * + * @member {string} + * @default 0 + */ + _this.lineColor = 0; + + /** + * Graphics data + * + * @member {PIXI.GraphicsData[]} + * @private + */ + _this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to + * reset the tint. + * + * @member {number} + * @default 0xFFFFFF + */ + _this.tint = 0xFFFFFF; + + /** + * The previous tint applied to the graphic shape. Used to compare to the current tint and + * check if theres change. + * + * @member {number} + * @private + * @default 0xFFFFFF + */ + _this._prevTint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * Current path + * + * @member {PIXI.GraphicsData} + * @private + */ + _this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @member {object} + * @private + */ + // TODO - _webgl should use a prototype object, not a random undocumented object... + _this._webGL = {}; + + /** + * Whether this shape is being used as a mask. + * + * @member {boolean} + */ + _this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @member {number} + */ + _this.boundsPadding = 0; + + /** + * A cache of the local bounds to prevent recalculation. + * + * @member {PIXI.Rectangle} + * @private + */ + _this._localBounds = new _Bounds2.default(); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics + * object will be recalculated. + * + * @member {boolean} + * @private + */ + _this.dirty = 0; + + /** + * Used to detect if we need to do a fast rect check using the id compare method + * @type {Number} + */ + _this.fastRectDirty = -1; + + /** + * Used to detect if we clear the graphics webGL data + * @type {Number} + */ + _this.clearDirty = 0; + + /** + * Used to detect if we we need to recalculate local bounds + * @type {Number} + */ + _this.boundsDirty = -1; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @member {boolean} + * @private + */ + _this.cachedSpriteDirty = false; + + _this._spriteRect = null; + _this._fastRect = false; + + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ + return _this; + } + + /** + * Creates a new Graphics object with the same values as this one. + * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) + * + * @return {PIXI.Graphics} A clone of the graphics object + */ + + + Graphics.prototype.clone = function clone() { + var clone = new Graphics(); + + clone.renderable = this.renderable; + clone.fillAlpha = this.fillAlpha; + clone.lineWidth = this.lineWidth; + clone.lineColor = this.lineColor; + clone.tint = this.tint; + clone.blendMode = this.blendMode; + clone.isMask = this.isMask; + clone.boundsPadding = this.boundsPadding; + clone.dirty = 0; + clone.cachedSpriteDirty = this.cachedSpriteDirty; + + // copy graphics data + for (var i = 0; i < this.graphicsData.length; ++i) { + clone.graphicsData.push(this.graphicsData[i].clone()); + } + + clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; + + clone.updateLocalBounds(); + + return clone; + }; + + /** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() + * method or the drawCircle() method. + * + * @param {number} [lineWidth=0] - width of the line to draw, will update the objects stored style + * @param {number} [color=0] - color of the line to draw, will update the objects stored style + * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineStyle = function lineStyle() { + var lineWidth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var alpha = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + + this.lineWidth = lineWidth; + this.lineColor = color; + this.lineAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length) { + // halfway through a line? start a new one! + var shape = new _math.Polygon(this.currentPath.shape.points.slice(-2)); + + shape.closed = false; + + this.drawShape(shape); + } else { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + } + } + + return this; + }; + + /** + * Moves the current drawing position to x, y. + * + * @param {number} x - the X coordinate to move to + * @param {number} y - the Y coordinate to move to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.moveTo = function moveTo(x, y) { + var shape = new _math.Polygon([x, y]); + + shape.closed = false; + this.drawShape(shape); + + return this; + }; + + /** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @param {number} x - the X coordinate to draw to + * @param {number} y - the Y coordinate to draw to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineTo = function lineTo(x, y) { + this.currentPath.shape.points.push(x, y); + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.quadraticCurveTo = function quadraticCurveTo(cpX, cpY, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var n = 20; + var points = this.currentPath.shape.points; + var xa = 0; + var ya = 0; + + if (points.length === 0) { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + for (var i = 1; i <= n; ++i) { + var j = i / n; + + xa = fromX + (cpX - fromX) * j; + ya = fromY + (cpY - fromY) * j; + + points.push(xa + (cpX + (toX - cpX) * j - xa) * j, ya + (cpY + (toY - cpY) * j - ya) * j); + } + + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a bezier curve and then draws it. + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.bezierCurveTo = function bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + points.length -= 2; + + (0, _bezierCurveTo3.default)(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, points); + + this.dirty++; + + return this; + }; + + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @param {number} x1 - The x-coordinate of the beginning of the arc + * @param {number} y1 - The y-coordinate of the beginning of the arc + * @param {number} x2 - The x-coordinate of the end of the arc + * @param {number} y2 - The y-coordinate of the end of the arc + * @param {number} radius - The radius of the arc + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arcTo = function arcTo(x1, y1, x2, y2, radius) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points.push(x1, y1); + } + } else { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + } else { + var dd = a1 * a1 + b1 * b1; + var cc = a2 * a2 + b2 * b2; + var tt = a1 * a2 + b1 * b2; + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = k1 * b2 + k2 * b1; + var cy = k1 * a2 + k2 * a1; + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty++; + + return this; + }; + + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @param {number} cx - The x-coordinate of the center of the circle + * @param {number} cy - The y-coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param {number} endAngle - The ending angle, in radians + * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arc = function arc(cx, cy, radius, startAngle, endAngle) { + var anticlockwise = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; + + if (startAngle === endAngle) { + return this; + } + + if (!anticlockwise && endAngle <= startAngle) { + endAngle += Math.PI * 2; + } else if (anticlockwise && startAngle <= endAngle) { + startAngle += Math.PI * 2; + } + + var sweep = endAngle - startAngle; + var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * 40; + + if (sweep === 0) { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. + var points = this.currentPath ? this.currentPath.shape.points : null; + + if (points) { + if (points[points.length - 2] !== startX || points[points.length - 1] !== startY) { + points.push(startX, startY); + } + } else { + this.moveTo(startX, startY); + points = this.currentPath.shape.points; + } + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = segMinus % 1 / segMinus; + + for (var i = 0; i <= segMinus; ++i) { + var real = i + remainder * i; + + var angle = theta + startAngle + theta2 * real; + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push((cTheta * c + sTheta * s) * radius + cx, (cTheta * -s + sTheta * c) * radius + cy); + } + + this.dirty++; + + return this; + }; + + /** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @param {number} [color=0] - the color of the fill + * @param {number} [alpha=1] - the alpha of the fill + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.beginFill = function beginFill() { + var color = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var alpha = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.filling = true; + this.fillColor = color; + this.fillAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length <= 2) { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + }; + + /** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.endFill = function endFill() { + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRect = function drawRect(x, y, width, height) { + this.drawShape(new _math.Rectangle(x, y, width, height)); + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @param {number} radius - Radius of the rectangle corners + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRoundedRect = function drawRoundedRect(x, y, width, height, radius) { + this.drawShape(new _math.RoundedRectangle(x, y, width, height, radius)); + + return this; + }; + + /** + * Draws a circle. + * + * @param {number} x - The X coordinate of the center of the circle + * @param {number} y - The Y coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawCircle = function drawCircle(x, y, radius) { + this.drawShape(new _math.Circle(x, y, radius)); + + return this; + }; + + /** + * Draws an ellipse. + * + * @param {number} x - The X coordinate of the center of the ellipse + * @param {number} y - The Y coordinate of the center of the ellipse + * @param {number} width - The half width of the ellipse + * @param {number} height - The half height of the ellipse + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawEllipse = function drawEllipse(x, y, width, height) { + this.drawShape(new _math.Ellipse(x, y, width, height)); + + return this; + }; + + /** + * Draws a polygon using the given path. + * + * @param {number[]|PIXI.Point[]|PIXI.Polygon} path - The path data used to construct the polygon. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawPolygon = function drawPolygon(path) { + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + var closed = true; + + if (points instanceof _math.Polygon) { + closed = points.closed; + points = points.points; + } + + if (!Array.isArray(points)) { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) { + points[i] = arguments[i]; // eslint-disable-line prefer-rest-params + } + } + + var shape = new _math.Polygon(points); + + shape.closed = closed; + + this.drawShape(shape); + + return this; + }; + + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.clear = function clear() { + if (this.lineWidth || this.filling || this.graphicsData.length > 0) { + this.lineWidth = 0; + this.filling = false; + + this.boundsDirty = -1; + this.dirty++; + this.clearDirty++; + this.graphicsData.length = 0; + } + + this.currentPath = null; + this._spriteRect = null; + + return this; + }; + + /** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. + * + * @returns {boolean} True if only 1 rect. + */ + + + Graphics.prototype.isFastRect = function isFastRect() { + return this.graphicsData.length === 1 && this.graphicsData[0].shape.type === _const.SHAPES.RECT && !this.graphicsData[0].lineWidth; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderWebGL = function _renderWebGL(renderer) { + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.dirty !== this.fastRectDirty) { + this.fastRectDirty = this.dirty; + this._fastRect = this.isFastRect(); + } + + // TODO this check can be moved to dirty? + if (this._fastRect) { + this._renderSpriteRect(renderer); + } else { + renderer.setObjectRenderer(renderer.plugins.graphics); + renderer.plugins.graphics.render(this); + } + }; + + /** + * Renders a sprite rectangle. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderSpriteRect = function _renderSpriteRect(renderer) { + var rect = this.graphicsData[0].shape; + + if (!this._spriteRect) { + this._spriteRect = new _Sprite2.default(new _Texture2.default(_Texture2.default.WHITE)); + } + + var sprite = this._spriteRect; + + if (this.tint === 0xffffff) { + sprite.tint = this.graphicsData[0].fillColor; + } else { + var t1 = tempColor1; + var t2 = tempColor2; + + (0, _utils.hex2rgb)(this.graphicsData[0].fillColor, t1); + (0, _utils.hex2rgb)(this.tint, t2); + + t1[0] *= t2[0]; + t1[1] *= t2[1]; + t1[2] *= t2[2]; + + sprite.tint = (0, _utils.rgb2hex)(t1); + } + sprite.alpha = this.graphicsData[0].fillAlpha; + sprite.worldAlpha = this.worldAlpha * sprite.alpha; + sprite.blendMode = this.blendMode; + + sprite._texture._frame.width = rect.width; + sprite._texture._frame.height = rect.height; + + sprite.transform.worldTransform = this.transform.worldTransform; + + sprite.anchor.set(-rect.x / rect.width, -rect.y / rect.height); + sprite._onAnchorUpdate(); + + sprite._renderWebGL(renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.isMask === true) { + return; + } + + renderer.plugins.graphics.render(this); + }; + + /** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @private + */ + + + Graphics.prototype._calculateBounds = function _calculateBounds() { + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.updateLocalBounds(); + + this.cachedSpriteDirty = true; + } + + var lb = this._localBounds; + + this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); + }; + + /** + * Tests if a point is inside this graphics object + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Graphics.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + + if (!data.fill) { + continue; + } + + // only deal with fills.. + if (data.shape) { + if (data.shape.contains(tempPoint.x, tempPoint.y)) { + if (data.holes) { + for (var _i = 0; _i < data.holes.length; _i++) { + var hole = data.holes[_i]; + + if (hole.contains(tempPoint.x, tempPoint.y)) { + return false; + } + } + } + + return true; + } + } + } + + return false; + }; + + /** + * Update the bounds of the object + * + */ + + + Graphics.prototype.updateLocalBounds = function updateLocalBounds() { + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) { + var shape = 0; + var x = 0; + var y = 0; + var w = 0; + var h = 0; + + for (var i = 0; i < this.graphicsData.length; i++) { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + + shape = data.shape; + + if (type === _const.SHAPES.RECT || type === _const.SHAPES.RREC) { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.CIRC) { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.ELIP) { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else { + // POLY + var points = shape.points; + var x2 = 0; + var y2 = 0; + var dx = 0; + var dy = 0; + var rw = 0; + var rh = 0; + var cx = 0; + var cy = 0; + + for (var j = 0; j + 2 < points.length; j += 2) { + x = points[j]; + y = points[j + 1]; + x2 = points[j + 2]; + y2 = points[j + 3]; + dx = Math.abs(x2 - x); + dy = Math.abs(y2 - y); + h = lineWidth; + w = Math.sqrt(dx * dx + dy * dy); + + if (w < 1e-9) { + continue; + } + + rw = (h / w * dy + dx) / 2; + rh = (h / w * dx + dy) / 2; + cx = (x2 + x) / 2; + cy = (y2 + y) / 2; + + minX = cx - rw < minX ? cx - rw : minX; + maxX = cx + rw > maxX ? cx + rw : maxX; + + minY = cy - rh < minY ? cy - rh : minY; + maxY = cy + rh > maxY ? cy + rh : maxY; + } + } + } + } else { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.minX = minX - padding; + this._localBounds.maxX = maxX + padding; + + this._localBounds.minY = minY - padding; + this._localBounds.maxY = maxY + padding; + }; + + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @return {PIXI.GraphicsData} The generated GraphicsData object. + */ + + + Graphics.prototype.drawShape = function drawShape(shape) { + if (this.currentPath) { + // check current path! + if (this.currentPath.shape.points.length <= 2) { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + var data = new _GraphicsData2.default(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, this.nativeLines, shape); + + this.graphicsData.push(data); + + if (data.type === _const.SHAPES.POLY) { + data.shape.closed = data.shape.closed || this.filling; + this.currentPath = data; + } + + this.dirty++; + + return data; + }; + + /** + * Generates a canvas texture. + * + * @param {number} scaleMode - The scale mode of the texture. + * @param {number} resolution - The resolution of the texture. + * @return {PIXI.Texture} The new texture. + */ + + + Graphics.prototype.generateCanvasTexture = function generateCanvasTexture(scaleMode) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + var bounds = this.getLocalBounds(); + + var canvasBuffer = _RenderTexture2.default.create(bounds.width, bounds.height, scaleMode, resolution); + + if (!canvasRenderer) { + canvasRenderer = new _CanvasRenderer2.default(); + } + + this.transform.updateLocalTransform(); + this.transform.localTransform.copy(tempMatrix); + + tempMatrix.invert(); + + tempMatrix.tx -= bounds.x; + tempMatrix.ty -= bounds.y; + + canvasRenderer.render(this, canvasBuffer, true, tempMatrix); + + var texture = _Texture2.default.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas, scaleMode, 'graphics'); + + texture.baseTexture.resolution = resolution; + texture.baseTexture.update(); + + return texture; + }; + + /** + * Closes the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.closePath = function closePath() { + // ok so close path assumes next one is a hole! + var currentPath = this.currentPath; + + if (currentPath && currentPath.shape) { + currentPath.shape.close(); + } + + return this; + }; + + /** + * Adds a hole in the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.addHole = function addHole() { + // this is a hole! + var hole = this.graphicsData.pop(); + + this.currentPath = this.graphicsData[this.graphicsData.length - 1]; + + this.currentPath.addHole(hole.shape); + this.currentPath = null; + + return this; + }; + + /** + * Destroys the Graphics object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Graphics.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._webgl) { + for (var j = 0; j < this._webgl[id].data.length; ++j) { + this._webgl[id].data[j].destroy(); + } + } + + if (this._spriteRect) { + this._spriteRect.destroy(); + } + + this.graphicsData = null; + + this.currentPath = null; + this._webgl = null; + this._localBounds = null; + }; + + return Graphics; +}(_Container3.default); + +exports.default = Graphics; + + +Graphics._SPRITE_TEXTURE = null; + +},{"../const":46,"../display/Bounds":47,"../display/Container":48,"../math":70,"../renderers/canvas/CanvasRenderer":77,"../sprites/Sprite":102,"../textures/RenderTexture":113,"../textures/Texture":115,"../utils":125,"./GraphicsData":54,"./utils/bezierCurveTo":56}],54:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + */ +var GraphicsData = function () { + /** + * + * @param {number} lineWidth - the width of the line to draw + * @param {number} lineColor - the color of the line to draw + * @param {number} lineAlpha - the alpha of the line to draw + * @param {number} fillColor - the color of the fill + * @param {number} fillAlpha - the alpha of the fill + * @param {boolean} fill - whether or not the shape is filled with a colour + * @param {boolean} nativeLines - the method for drawing lines + * @param {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} shape - The shape object to draw. + */ + function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, nativeLines, shape) { + _classCallCheck(this, GraphicsData); + + /** + * @member {number} the width of the line to draw + */ + this.lineWidth = lineWidth; + /** + * @member {boolean} if true the liens will be draw using LINES instead of TRIANGLE_STRIP + */ + this.nativeLines = nativeLines; + + /** + * @member {number} the color of the line to draw + */ + this.lineColor = lineColor; + + /** + * @member {number} the alpha of the line to draw + */ + this.lineAlpha = lineAlpha; + + /** + * @member {number} cached tint of the line to draw + */ + this._lineTint = lineColor; + + /** + * @member {number} the color of the fill + */ + this.fillColor = fillColor; + + /** + * @member {number} the alpha of the fill + */ + this.fillAlpha = fillAlpha; + + /** + * @member {number} cached tint of the fill + */ + this._fillTint = fillColor; + + /** + * @member {boolean} whether or not the shape is filled with a colour + */ + this.fill = fill; + + this.holes = []; + + /** + * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} The shape object to draw. + */ + this.shape = shape; + + /** + * @member {number} The type of the shape, see the Const.Shapes file for all the existing types, + */ + this.type = shape.type; + } + + /** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {PIXI.GraphicsData} Cloned GraphicsData object + */ + + + GraphicsData.prototype.clone = function clone() { + return new GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.fill, this.nativeLines, this.shape); + }; + + /** + * Adds a hole to the shape. + * + * @param {PIXI.Rectangle|PIXI.Circle} shape - The shape of the hole. + */ + + + GraphicsData.prototype.addHole = function addHole(shape) { + this.holes.push(shape); + }; + + /** + * Destroys the Graphics data. + */ + + + GraphicsData.prototype.destroy = function destroy() { + this.shape = null; + this.holes = null; + }; + + return GraphicsData; +}(); + +exports.default = GraphicsData; + +},{}],55:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they + * now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasGraphicsRenderer: + * https://github.com/libgdx/libgdx/blob/1.0.0/gdx/src/com/badlogic/gdx/graphics/glutils/ShapeRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching graphics objects. + * + * @class + * @private + * @memberof PIXI + */ +var CanvasGraphicsRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The current PIXI renderer. + */ + function CanvasGraphicsRenderer(renderer) { + _classCallCheck(this, CanvasGraphicsRenderer); + + this.renderer = renderer; + } + + /** + * Renders a Graphics object to a canvas. + * + * @param {PIXI.Graphics} graphics - the actual graphics object to render + */ + + + CanvasGraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var context = renderer.context; + var worldAlpha = graphics.worldAlpha; + var transform = graphics.transform.worldTransform; + var resolution = renderer.resolution; + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) { + this.dirty = true; + } + + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + if (graphics.dirty) { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + renderer.setBlendMode(graphics.blendMode); + + for (var i = 0; i < graphics.graphicsData.length; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === _const.SHAPES.POLY) { + context.beginPath(); + + this.renderPolygon(shape.points, shape.closed, context); + + for (var j = 0; j < data.holes.length; j++) { + this.renderPolygon(data.holes[j].points, true, context); + } + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RECT) { + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + context.beginPath(); + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + }; + + /** + * Updates the tint of a graphics object + * + * @private + * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated + */ + + + CanvasGraphicsRenderer.prototype.updateGraphicsTint = function updateGraphicsTint(graphics) { + graphics._prevTint = graphics.tint; + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF) / 255; + + for (var i = 0; i < graphics.graphicsData.length; ++i) { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + // super inline cos im an optimization NAZI :) + data._fillTint = ((fillColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (fillColor & 0xFF) / 255 * tintB * 255; + + data._lineTint = ((lineColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (lineColor & 0xFF) / 255 * tintB * 255; + } + }; + + /** + * Renders a polygon. + * + * @param {PIXI.Point[]} points - The points to render + * @param {boolean} close - Should the polygon be closed + * @param {CanvasRenderingContext2D} context - The rendering context to use + */ + + + CanvasGraphicsRenderer.prototype.renderPolygon = function renderPolygon(points, close, context) { + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; ++j) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (close) { + context.closePath(); + } + }; + + /** + * destroy graphics object + * + */ + + + CanvasGraphicsRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasGraphicsRenderer; +}(); + +exports.default = CanvasGraphicsRenderer; + + +_CanvasRenderer2.default.registerPlugin('graphics', CanvasGraphicsRenderer); + +},{"../../const":46,"../../renderers/canvas/CanvasRenderer":77}],56:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = bezierCurveTo; +/** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [path=[]] - Path array to push points into + * @return {number[]} Array of points of the curve + */ +function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var path = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : []; + + var n = 20; + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + + path.push(fromX, fromY); + + for (var i = 1, j = 0; i <= n; ++i) { + j = i / n; + + dt = 1 - j; + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + path.push(dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + return path; +} + +},{}],57:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _WebGLGraphicsData = require('./WebGLGraphicsData'); + +var _WebGLGraphicsData2 = _interopRequireDefault(_WebGLGraphicsData); + +var _PrimitiveShader = require('./shaders/PrimitiveShader'); + +var _PrimitiveShader2 = _interopRequireDefault(_PrimitiveShader); + +var _buildPoly = require('./utils/buildPoly'); + +var _buildPoly2 = _interopRequireDefault(_buildPoly); + +var _buildRectangle = require('./utils/buildRectangle'); + +var _buildRectangle2 = _interopRequireDefault(_buildRectangle); + +var _buildRoundedRectangle = require('./utils/buildRoundedRectangle'); + +var _buildRoundedRectangle2 = _interopRequireDefault(_buildRoundedRectangle); + +var _buildCircle = require('./utils/buildCircle'); + +var _buildCircle2 = _interopRequireDefault(_buildCircle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Renders the graphics object. + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var GraphicsRenderer = function (_ObjectRenderer) { + _inherits(GraphicsRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this object renderer works for. + */ + function GraphicsRenderer(renderer) { + _classCallCheck(this, GraphicsRenderer); + + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.graphicsDataPool = []; + + _this.primitiveShader = null; + + _this.gl = renderer.gl; + + // easy access! + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * Called when there is a WebGL context change + * + * @private + * + */ + + + GraphicsRenderer.prototype.onContextChange = function onContextChange() { + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.primitiveShader = new _PrimitiveShader2.default(this.gl); + }; + + /** + * Destroys this renderer. + * + */ + + + GraphicsRenderer.prototype.destroy = function destroy() { + _ObjectRenderer3.default.prototype.destroy.call(this); + + for (var i = 0; i < this.graphicsDataPool.length; ++i) { + this.graphicsDataPool[i].destroy(); + } + + this.graphicsDataPool = null; + }; + + /** + * Renders a graphics object. + * + * @param {PIXI.Graphics} graphics - The graphics object to render. + */ + + + GraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var gl = renderer.gl; + + var webGLData = void 0; + var webGL = graphics._webGL[this.CONTEXT_UID]; + + if (!webGL || graphics.dirty !== webGL.dirty) { + this.updateGraphics(graphics); + + webGL = graphics._webGL[this.CONTEXT_UID]; + } + + // This could be speeded up for sure! + var shader = this.primitiveShader; + + renderer.bindShader(shader); + renderer.state.setBlendMode(graphics.blendMode); + + for (var i = 0, n = webGL.data.length; i < n; i++) { + webGLData = webGL.data[i]; + var shaderTemp = webGLData.shader; + + renderer.bindShader(shaderTemp); + shaderTemp.uniforms.translationMatrix = graphics.transform.worldTransform.toArray(true); + shaderTemp.uniforms.tint = (0, _utils.hex2rgb)(graphics.tint); + shaderTemp.uniforms.alpha = graphics.worldAlpha; + + renderer.bindVao(webGLData.vao); + + if (webGLData.nativeLines) { + gl.drawArrays(gl.LINES, 0, webGLData.points.length / 6); + } else { + webGLData.vao.draw(gl.TRIANGLE_STRIP, webGLData.indices.length); + } + } + }; + + /** + * Updates the graphics object + * + * @private + * @param {PIXI.Graphics} graphics - The graphics object to update + */ + + + GraphicsRenderer.prototype.updateGraphics = function updateGraphics(graphics) { + var gl = this.renderer.gl; + + // get the contexts graphics object + var webGL = graphics._webGL[this.CONTEXT_UID]; + + // if the graphics object does not exist in the webGL context time to create it! + if (!webGL) { + webGL = graphics._webGL[this.CONTEXT_UID] = { lastIndex: 0, data: [], gl: gl, clearDirty: -1, dirty: -1 }; + } + + // flag the graphics as not dirty as we are about to update it... + webGL.dirty = graphics.dirty; + + // if the user cleared the graphics object we will need to clear every object + if (graphics.clearDirty !== webGL.clearDirty) { + webGL.clearDirty = graphics.clearDirty; + + // loop through and return all the webGLDatas to the object pool so than can be reused later on + for (var i = 0; i < webGL.data.length; i++) { + this.graphicsDataPool.push(webGL.data[i]); + } + + // clear the array and reset the index.. + webGL.data.length = 0; + webGL.lastIndex = 0; + } + + var webGLData = void 0; + var webGLDataNativeLines = void 0; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (var _i = webGL.lastIndex; _i < graphics.graphicsData.length; _i++) { + var data = graphics.graphicsData[_i]; + + // TODO - this can be simplified + webGLData = this.getWebGLData(webGL, 0); + + if (data.nativeLines && data.lineWidth) { + webGLDataNativeLines = this.getWebGLData(webGL, 0, true); + webGL.lastIndex++; + } + + if (data.type === _const.SHAPES.POLY) { + (0, _buildPoly2.default)(data, webGLData, webGLDataNativeLines); + } + if (data.type === _const.SHAPES.RECT) { + (0, _buildRectangle2.default)(data, webGLData, webGLDataNativeLines); + } else if (data.type === _const.SHAPES.CIRC || data.type === _const.SHAPES.ELIP) { + (0, _buildCircle2.default)(data, webGLData, webGLDataNativeLines); + } else if (data.type === _const.SHAPES.RREC) { + (0, _buildRoundedRectangle2.default)(data, webGLData, webGLDataNativeLines); + } + + webGL.lastIndex++; + } + + this.renderer.bindVao(null); + + // upload all the dirty data... + for (var _i2 = 0; _i2 < webGL.data.length; _i2++) { + webGLData = webGL.data[_i2]; + + if (webGLData.dirty) { + webGLData.upload(); + } + } + }; + + /** + * + * @private + * @param {WebGLRenderingContext} gl - the current WebGL drawing context + * @param {number} type - TODO @Alvin + * @param {number} nativeLines - indicate whether the webGLData use for nativeLines. + * @return {*} TODO + */ + + + GraphicsRenderer.prototype.getWebGLData = function getWebGLData(gl, type, nativeLines) { + var webGLData = gl.data[gl.data.length - 1]; + + if (!webGLData || webGLData.nativeLines !== nativeLines || webGLData.points.length > 320000) { + webGLData = this.graphicsDataPool.pop() || new _WebGLGraphicsData2.default(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData.nativeLines = nativeLines; + webGLData.reset(type); + gl.data.push(webGLData); + } + + webGLData.dirty = true; + + return webGLData; + }; + + return GraphicsRenderer; +}(_ObjectRenderer3.default); + +exports.default = GraphicsRenderer; + + +_WebGLRenderer2.default.registerPlugin('graphics', GraphicsRenderer); + +},{"../../const":46,"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../utils":125,"./WebGLGraphicsData":58,"./shaders/PrimitiveShader":59,"./utils/buildCircle":60,"./utils/buildPoly":62,"./utils/buildRectangle":63,"./utils/buildRoundedRectangle":64}],58:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * An object containing WebGL specific properties to be used by the WebGL renderer + * + * @class + * @private + * @memberof PIXI + */ +var WebGLGraphicsData = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {PIXI.Shader} shader - The shader + * @param {object} attribsState - The state for the VAO + */ + function WebGLGraphicsData(gl, shader, attribsState) { + _classCallCheck(this, WebGLGraphicsData); + + /** + * The current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // TODO does this need to be split before uploading?? + /** + * An array of color components (r,g,b) + * @member {number[]} + */ + this.color = [0, 0, 0]; // color split! + + /** + * An array of points to draw + * @member {PIXI.Point[]} + */ + this.points = []; + + /** + * The indices of the vertices + * @member {number[]} + */ + this.indices = []; + /** + * The main buffer + * @member {WebGLBuffer} + */ + this.buffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl); + + /** + * The index buffer + * @member {WebGLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl); + + /** + * Whether this graphics is dirty or not + * @member {boolean} + */ + this.dirty = true; + + /** + * Whether this graphics is nativeLines or not + * @member {boolean} + */ + this.nativeLines = false; + + this.glPoints = null; + this.glIndices = null; + + /** + * + * @member {PIXI.Shader} + */ + this.shader = shader; + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, attribsState).addIndex(this.indexBuffer).addAttribute(this.buffer, shader.attributes.aVertexPosition, gl.FLOAT, false, 4 * 6, 0).addAttribute(this.buffer, shader.attributes.aColor, gl.FLOAT, false, 4 * 6, 2 * 4); + } + + /** + * Resets the vertices and the indices + */ + + + WebGLGraphicsData.prototype.reset = function reset() { + this.points.length = 0; + this.indices.length = 0; + }; + + /** + * Binds the buffers and uploads the data + */ + + + WebGLGraphicsData.prototype.upload = function upload() { + this.glPoints = new Float32Array(this.points); + this.buffer.upload(this.glPoints); + + this.glIndices = new Uint16Array(this.indices); + this.indexBuffer.upload(this.glIndices); + + this.dirty = false; + }; + + /** + * Empties all the data + */ + + + WebGLGraphicsData.prototype.destroy = function destroy() { + this.color = null; + this.points = null; + this.indices = null; + + this.vao.destroy(); + this.buffer.destroy(); + this.indexBuffer.destroy(); + + this.gl = null; + + this.buffer = null; + this.indexBuffer = null; + + this.glPoints = null; + this.glIndices = null; + }; + + return WebGLGraphicsData; +}(); + +exports.default = WebGLGraphicsData; + +},{"pixi-gl-core":12}],59:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../../Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. + * + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ +var PrimitiveShader = function (_Shader) { + _inherits(PrimitiveShader, _Shader); + + /** + * @param {WebGLRenderingContext} gl - The webgl shader manager this shader works for. + */ + function PrimitiveShader(gl) { + _classCallCheck(this, PrimitiveShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec4 aColor;', 'uniform mat3 translationMatrix;', 'uniform mat3 projectionMatrix;', 'uniform float alpha;', 'uniform vec3 tint;', 'varying vec4 vColor;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vColor = aColor * vec4(tint * alpha, alpha);', '}'].join('\n'), + // fragment shader + ['varying vec4 vColor;', 'void main(void){', ' gl_FragColor = vColor;', '}'].join('\n'))); + } + + return PrimitiveShader; +}(_Shader3.default); + +exports.default = PrimitiveShader; + +},{"../../../Shader":44}],60:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildCircle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _const = require('../../../const'); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildCircle(graphicsData, webGLData, webGLDataNativeLines) { + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width = void 0; + var height = void 0; + + // TODO - bit hacky?? + if (graphicsData.type === _const.SHAPES.CIRC) { + width = circleData.radius; + height = circleData.radius; + } else { + width = circleData.width; + height = circleData.height; + } + + if (width === 0 || height === 0) { + return; + } + + var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); + + var seg = Math.PI * 2 / totalSegs; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + indices.push(vecPos); + + for (var i = 0; i < totalSegs + 1; i++) { + verts.push(x, y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos - 1); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (var _i = 0; _i < totalSegs + 1; _i++) { + graphicsData.points.push(x + Math.sin(seg * _i) * width, y + Math.cos(seg * _i) * height); + } + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +},{"../../../const":46,"../../../utils":125,"./buildLine":61}],61:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function (graphicsData, webGLData, webGLDataNativeLines) { + if (graphicsData.nativeLines) { + buildNativeLine(graphicsData, webGLDataNativeLines); + } else { + buildLine(graphicsData, webGLData); + } +}; + +var _math = require('../../../math'); + +var _utils = require('../../../utils'); + +/** + * Builds a line to draw using the poligon method. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildLine(graphicsData, webGLData) { + // TODO OPTIMISE! + var points = graphicsData.points; + + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + + // get first and last point.. figure out the middle! + var firstPoint = new _math.Point(points[0], points[1]); + var lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + // if the first point is the last point - gonna have issues :) + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var p1x = points[0]; + var p1y = points[1]; + var p2x = points[2]; + var p2y = points[3]; + var p3x = 0; + var p3y = 0; + + var perpx = -(p1y - p2y); + var perpy = p1x - p2x; + var perp2x = 0; + var perp2y = 0; + var perp3x = 0; + var perp3y = 0; + + var dist = Math.sqrt(perpx * perpx + perpy * perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + // start + verts.push(p1x - perpx, p1y - perpy, r, g, b, alpha); + + verts.push(p1x + perpx, p1y + perpy, r, g, b, alpha); + + for (var i = 1; i < length - 1; ++i) { + p1x = points[(i - 1) * 2]; + p1y = points[(i - 1) * 2 + 1]; + + p2x = points[i * 2]; + p2y = points[i * 2 + 1]; + + p3x = points[(i + 1) * 2]; + p3y = points[(i + 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + var a1 = -perpy + p1y - (-perpy + p2y); + var b1 = -perpx + p2x - (-perpx + p1x); + var c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + var a2 = -perp2y + p3y - (-perp2y + p2y); + var b2 = -perp2x + p2x - (-perp2x + p3x); + var c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + var denom = a1 * b2 - a2 * b1; + + if (Math.abs(denom) < 0.1) { + denom += 10.1; + verts.push(p2x - perpx, p2y - perpy, r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy, r, g, b, alpha); + + continue; + } + + var px = (b1 * c2 - b2 * c1) / denom; + var py = (a2 * c1 - a1 * c2) / denom; + var pdist = (px - p2x) * (px - p2x) + (py - p2y) * (py - p2y); + + if (pdist > 196 * width * width) { + perp3x = perpx - perp2x; + perp3y = perpy - perp2y; + + dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y); + perp3x /= dist; + perp3y /= dist; + perp3x *= width; + perp3y *= width; + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x + perp3x, p2y + perp3y); + verts.push(r, g, b, alpha); + + verts.push(p2x - perp3x, p2y - perp3y); + verts.push(r, g, b, alpha); + + indexCount++; + } else { + verts.push(px, py); + verts.push(r, g, b, alpha); + + verts.push(p2x - (px - p2x), p2y - (py - p2y)); + verts.push(r, g, b, alpha); + } + } + + p1x = points[(length - 2) * 2]; + p1y = points[(length - 2) * 2 + 1]; + + p2x = points[(length - 1) * 2]; + p2y = points[(length - 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + verts.push(p2x - perpx, p2y - perpy); + verts.push(r, g, b, alpha); + + verts.push(p2x + perpx, p2y + perpy); + verts.push(r, g, b, alpha); + + indices.push(indexStart); + + for (var _i = 0; _i < indexCount; ++_i) { + indices.push(indexStart++); + } + + indices.push(indexStart - 1); +} + +/** + * Builds a line to draw using the gl.drawArrays(gl.LINES) method + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ + + +/** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildNativeLine(graphicsData, webGLData) { + var i = 0; + var points = graphicsData.points; + + if (points.length === 0) return; + + var verts = webGLData.points; + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + for (i = 1; i < length; i++) { + var p1x = points[(i - 1) * 2]; + var p1y = points[(i - 1) * 2 + 1]; + + var p2x = points[i * 2]; + var p2y = points[i * 2 + 1]; + + verts.push(p1x, p1y); + verts.push(r, g, b, alpha); + + verts.push(p2x, p2y); + verts.push(r, g, b, alpha); + } +} + +},{"../../../math":70,"../../../utils":125}],62:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildPoly; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildPoly(graphicsData, webGLData, webGLDataNativeLines) { + graphicsData.points = graphicsData.shape.points.slice(); + + var points = graphicsData.points; + + if (graphicsData.fill && points.length >= 6) { + var holeArray = []; + // Process holes.. + var holes = graphicsData.holes; + + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + + holeArray.push(points.length / 2); + + points = points.concat(hole.points); + } + + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = (0, _earcut2.default)(points, holeArray, 2); + + if (!triangles) { + return; + } + + var vertPos = verts.length / 6; + + for (var _i = 0; _i < triangles.length; _i += 3) { + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i + 1] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + } + + for (var _i2 = 0; _i2 < length; _i2++) { + verts.push(points[_i2 * 2], points[_i2 * 2 + 1], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth > 0) { + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + } +} + +},{"../../../utils":125,"./buildLine":61,"earcut":2}],63:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRectangle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildRectangle(graphicsData, webGLData, webGLDataNativeLines) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vertPos = verts.length / 6; + + // start + verts.push(x, y); + verts.push(r, g, b, alpha); + + verts.push(x + width, y); + verts.push(r, g, b, alpha); + + verts.push(x, y + height); + verts.push(r, g, b, alpha); + + verts.push(x + width, y + height); + verts.push(r, g, b, alpha); + + // insert 2 dead triangles.. + indices.push(vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y]; + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +},{"../../../utils":125,"./buildLine":61}],64:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRoundedRectangle; + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildRoundedRectangle(graphicsData, webGLData, webGLDataNativeLines) { + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + + recPoints.push(x, y + radius); + quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height, recPoints); + quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius, recPoints); + quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y, recPoints); + quadraticBezierCurve(x + radius, y, x, y, x, y + radius + 0.0000000001, recPoints); + + // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. + // TODO - fix this properly, this is not very elegant.. but it works for now. + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + var triangles = (0, _earcut2.default)(recPoints, null, 2); + + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + + for (var _i = 0, _j = recPoints.length; _i < _j; _i++) { + verts.push(recPoints[_i], recPoints[++_i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +/** + * Calculate a single point for a quadratic bezier curve. + * Utility function used by quadraticBezierCurve. + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} n1 - first number + * @param {number} n2 - second number + * @param {number} perc - percentage + * @return {number} the result + * + */ +function getPt(n1, n2, perc) { + var diff = n2 - n1; + + return n1 + diff * perc; +} + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @return {number[]} an array of points + */ +function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY) { + var out = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : []; + + var n = 20; + var points = out; + + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + + points.push(x, y); + } + + return points; +} + +},{"../../../utils":125,"./buildLine":61,"earcut":2}],65:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = exports.Application = exports.Filter = exports.SpriteMaskFilter = exports.Quad = exports.RenderTarget = exports.ObjectRenderer = exports.WebGLManager = exports.Shader = exports.CanvasRenderTarget = exports.TextureUvs = exports.VideoBaseTexture = exports.BaseRenderTexture = exports.RenderTexture = exports.BaseTexture = exports.TextureMatrix = exports.Texture = exports.Spritesheet = exports.CanvasGraphicsRenderer = exports.GraphicsRenderer = exports.GraphicsData = exports.Graphics = exports.TextMetrics = exports.TextStyle = exports.Text = exports.SpriteRenderer = exports.CanvasTinter = exports.CanvasSpriteRenderer = exports.Sprite = exports.TransformBase = exports.TransformStatic = exports.Transform = exports.Container = exports.DisplayObject = exports.Bounds = exports.glCore = exports.WebGLRenderer = exports.CanvasRenderer = exports.ticker = exports.utils = exports.settings = undefined; + +var _const = require('./const'); + +Object.keys(_const).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _const[key]; + } + }); +}); + +var _math = require('./math'); + +Object.keys(_math).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _math[key]; + } + }); +}); + +var _pixiGlCore = require('pixi-gl-core'); + +Object.defineProperty(exports, 'glCore', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_pixiGlCore).default; + } +}); + +var _Bounds = require('./display/Bounds'); + +Object.defineProperty(exports, 'Bounds', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Bounds).default; + } +}); + +var _DisplayObject = require('./display/DisplayObject'); + +Object.defineProperty(exports, 'DisplayObject', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplayObject).default; + } +}); + +var _Container = require('./display/Container'); + +Object.defineProperty(exports, 'Container', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Container).default; + } +}); + +var _Transform = require('./display/Transform'); + +Object.defineProperty(exports, 'Transform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Transform).default; + } +}); + +var _TransformStatic = require('./display/TransformStatic'); + +Object.defineProperty(exports, 'TransformStatic', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformStatic).default; + } +}); + +var _TransformBase = require('./display/TransformBase'); + +Object.defineProperty(exports, 'TransformBase', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformBase).default; + } +}); + +var _Sprite = require('./sprites/Sprite'); + +Object.defineProperty(exports, 'Sprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Sprite).default; + } +}); + +var _CanvasSpriteRenderer = require('./sprites/canvas/CanvasSpriteRenderer'); + +Object.defineProperty(exports, 'CanvasSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasSpriteRenderer).default; + } +}); + +var _CanvasTinter = require('./sprites/canvas/CanvasTinter'); + +Object.defineProperty(exports, 'CanvasTinter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasTinter).default; + } +}); + +var _SpriteRenderer = require('./sprites/webgl/SpriteRenderer'); + +Object.defineProperty(exports, 'SpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteRenderer).default; + } +}); + +var _Text = require('./text/Text'); + +Object.defineProperty(exports, 'Text', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Text).default; + } +}); + +var _TextStyle = require('./text/TextStyle'); + +Object.defineProperty(exports, 'TextStyle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextStyle).default; + } +}); + +var _TextMetrics = require('./text/TextMetrics'); + +Object.defineProperty(exports, 'TextMetrics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextMetrics).default; + } +}); + +var _Graphics = require('./graphics/Graphics'); + +Object.defineProperty(exports, 'Graphics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Graphics).default; + } +}); + +var _GraphicsData = require('./graphics/GraphicsData'); + +Object.defineProperty(exports, 'GraphicsData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsData).default; + } +}); + +var _GraphicsRenderer = require('./graphics/webgl/GraphicsRenderer'); + +Object.defineProperty(exports, 'GraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsRenderer).default; + } +}); + +var _CanvasGraphicsRenderer = require('./graphics/canvas/CanvasGraphicsRenderer'); + +Object.defineProperty(exports, 'CanvasGraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasGraphicsRenderer).default; + } +}); + +var _Spritesheet = require('./textures/Spritesheet'); + +Object.defineProperty(exports, 'Spritesheet', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Spritesheet).default; + } +}); + +var _Texture = require('./textures/Texture'); + +Object.defineProperty(exports, 'Texture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Texture).default; + } +}); + +var _TextureMatrix = require('./textures/TextureMatrix'); + +Object.defineProperty(exports, 'TextureMatrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureMatrix).default; + } +}); + +var _BaseTexture = require('./textures/BaseTexture'); + +Object.defineProperty(exports, 'BaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseTexture).default; + } +}); + +var _RenderTexture = require('./textures/RenderTexture'); + +Object.defineProperty(exports, 'RenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTexture).default; + } +}); + +var _BaseRenderTexture = require('./textures/BaseRenderTexture'); + +Object.defineProperty(exports, 'BaseRenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseRenderTexture).default; + } +}); + +var _VideoBaseTexture = require('./textures/VideoBaseTexture'); + +Object.defineProperty(exports, 'VideoBaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VideoBaseTexture).default; + } +}); + +var _TextureUvs = require('./textures/TextureUvs'); + +Object.defineProperty(exports, 'TextureUvs', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureUvs).default; + } +}); + +var _CanvasRenderTarget = require('./renderers/canvas/utils/CanvasRenderTarget'); + +Object.defineProperty(exports, 'CanvasRenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasRenderTarget).default; + } +}); + +var _Shader = require('./Shader'); + +Object.defineProperty(exports, 'Shader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Shader).default; + } +}); + +var _WebGLManager = require('./renderers/webgl/managers/WebGLManager'); + +Object.defineProperty(exports, 'WebGLManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLManager).default; + } +}); + +var _ObjectRenderer = require('./renderers/webgl/utils/ObjectRenderer'); + +Object.defineProperty(exports, 'ObjectRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObjectRenderer).default; + } +}); + +var _RenderTarget = require('./renderers/webgl/utils/RenderTarget'); + +Object.defineProperty(exports, 'RenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTarget).default; + } +}); + +var _Quad = require('./renderers/webgl/utils/Quad'); + +Object.defineProperty(exports, 'Quad', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Quad).default; + } +}); + +var _SpriteMaskFilter = require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter'); + +Object.defineProperty(exports, 'SpriteMaskFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteMaskFilter).default; + } +}); + +var _Filter = require('./renderers/webgl/filters/Filter'); + +Object.defineProperty(exports, 'Filter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Filter).default; + } +}); + +var _Application = require('./Application'); + +Object.defineProperty(exports, 'Application', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Application).default; + } +}); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +Object.defineProperty(exports, 'autoDetectRenderer', { + enumerable: true, + get: function get() { + return _autoDetectRenderer.autoDetectRenderer; + } +}); + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _ticker = require('./ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.settings = _settings2.default; +exports.utils = utils; +exports.ticker = ticker; +exports.CanvasRenderer = _CanvasRenderer2.default; +exports.WebGLRenderer = _WebGLRenderer2.default; /** + * @namespace PIXI + */ + +},{"./Application":43,"./Shader":44,"./autoDetectRenderer":45,"./const":46,"./display/Bounds":47,"./display/Container":48,"./display/DisplayObject":49,"./display/Transform":50,"./display/TransformBase":51,"./display/TransformStatic":52,"./graphics/Graphics":53,"./graphics/GraphicsData":54,"./graphics/canvas/CanvasGraphicsRenderer":55,"./graphics/webgl/GraphicsRenderer":57,"./math":70,"./renderers/canvas/CanvasRenderer":77,"./renderers/canvas/utils/CanvasRenderTarget":79,"./renderers/webgl/WebGLRenderer":84,"./renderers/webgl/filters/Filter":86,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":89,"./renderers/webgl/managers/WebGLManager":93,"./renderers/webgl/utils/ObjectRenderer":94,"./renderers/webgl/utils/Quad":95,"./renderers/webgl/utils/RenderTarget":96,"./settings":101,"./sprites/Sprite":102,"./sprites/canvas/CanvasSpriteRenderer":103,"./sprites/canvas/CanvasTinter":104,"./sprites/webgl/SpriteRenderer":106,"./text/Text":108,"./text/TextMetrics":109,"./text/TextStyle":110,"./textures/BaseRenderTexture":111,"./textures/BaseTexture":112,"./textures/RenderTexture":113,"./textures/Spritesheet":114,"./textures/Texture":115,"./textures/TextureMatrix":116,"./textures/TextureUvs":117,"./textures/VideoBaseTexture":118,"./ticker":121,"./utils":125,"pixi-gl-core":12}],66:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Matrix = require('./Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16 + +var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; +var tempMatrices = []; + +var mul = []; + +function signum(x) { + if (x < 0) { + return -1; + } + if (x > 0) { + return 1; + } + + return 0; +} + +function init() { + for (var i = 0; i < 16; i++) { + var row = []; + + mul.push(row); + + for (var j = 0; j < 16; j++) { + var _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); + var _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); + var _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); + var _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); + + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + + for (var _i = 0; _i < 16; _i++) { + var mat = new _Matrix2.default(); + + mat.set(ux[_i], uy[_i], vx[_i], vy[_i], 0, 0); + tempMatrices.push(mat); + } +} + +init(); + +/** + * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, + * D8 is the same but with diagonals. Used for texture rotations. + * + * Vector xX(i), xY(i) is U-axis of sprite with rotation i + * Vector yY(i), yY(i) is V-axis of sprite with rotation i + * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) + * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) + * This is the small part of gameofbombs.com portal system. It works. + * + * @author Ivan @ivanpopelyshev + * @class + * @memberof PIXI + */ +var GroupD8 = { + E: 0, + SE: 1, + S: 2, + SW: 3, + W: 4, + NW: 5, + N: 6, + NE: 7, + MIRROR_VERTICAL: 8, + MIRROR_HORIZONTAL: 12, + uX: function uX(ind) { + return ux[ind]; + }, + uY: function uY(ind) { + return uy[ind]; + }, + vX: function vX(ind) { + return vx[ind]; + }, + vY: function vY(ind) { + return vy[ind]; + }, + inv: function inv(rotation) { + if (rotation & 8) { + return rotation & 15; + } + + return -rotation & 7; + }, + add: function add(rotationSecond, rotationFirst) { + return mul[rotationSecond][rotationFirst]; + }, + sub: function sub(rotationSecond, rotationFirst) { + return mul[rotationSecond][GroupD8.inv(rotationFirst)]; + }, + + /** + * Adds 180 degrees to rotation. Commutative operation. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to rotate. + * @returns {number} rotated number + */ + rotate180: function rotate180(rotation) { + return rotation ^ 4; + }, + + /** + * Direction of main vector can be horizontal, vertical or diagonal. + * Some objects work with vertical directions different. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the direction is vertical + */ + isVertical: function isVertical(rotation) { + return (rotation & 3) === 2; + }, + + /** + * @memberof PIXI.GroupD8 + * @param {number} dx - TODO + * @param {number} dy - TODO + * + * @return {number} TODO + */ + byDirection: function byDirection(dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return GroupD8.S; + } + + return GroupD8.N; + } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return GroupD8.E; + } + + return GroupD8.W; + } else if (dy > 0) { + if (dx > 0) { + return GroupD8.SE; + } + + return GroupD8.SW; + } else if (dx > 0) { + return GroupD8.NE; + } + + return GroupD8.NW; + }, + + /** + * Helps sprite to compensate texture packer rotation. + * + * @memberof PIXI.GroupD8 + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {number} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function matrixAppendRotationInv(matrix, rotation) { + var tx = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var ty = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + // Packer used "rotation", we use "inv(rotation)" + var mat = tempMatrices[GroupD8.inv(rotation)]; + + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + } +}; + +exports.default = GroupD8; + +},{"./Matrix":67}],67:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Point = require('./Point'); + +var _Point2 = _interopRequireDefault(_Point); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The PixiJS Matrix class as an object, which makes it a lot faster, + * here is a representation of it : + * | a | b | tx| + * | c | d | ty| + * | 0 | 0 | 1 | + * + * @class + * @memberof PIXI + */ +var Matrix = function () { + /** + * @param {number} [a=1] - x scale + * @param {number} [b=0] - y skew + * @param {number} [c=0] - x skew + * @param {number} [d=1] - y scale + * @param {number} [tx=0] - x translation + * @param {number} [ty=0] - y translation + */ + function Matrix() { + var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var d = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var tx = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var ty = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + + _classCallCheck(this, Matrix); + + /** + * @member {number} + * @default 1 + */ + this.a = a; + + /** + * @member {number} + * @default 0 + */ + this.b = b; + + /** + * @member {number} + * @default 0 + */ + this.c = c; + + /** + * @member {number} + * @default 1 + */ + this.d = d; + + /** + * @member {number} + * @default 0 + */ + this.tx = tx; + + /** + * @member {number} + * @default 0 + */ + this.ty = ty; + + this.array = null; + } + + /** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @param {number[]} array - The array that the matrix will be populated from. + */ + + + Matrix.prototype.fromArray = function fromArray(array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + }; + + /** + * sets the matrix properties + * + * @param {number} a - Matrix component + * @param {number} b - Matrix component + * @param {number} c - Matrix component + * @param {number} d - Matrix component + * @param {number} tx - Matrix component + * @param {number} ty - Matrix component + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.set = function set(a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + }; + + /** + * Creates an array from the current Matrix object. + * + * @param {boolean} transpose - Whether we need to transpose the matrix or not + * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out + * @return {number[]} the newly created array which contains the matrix + */ + + + Matrix.prototype.toArray = function toArray(transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + + var array = out || this.array; + + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + }; + + /** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, transformed through this matrix + */ + + + Matrix.prototype.apply = function apply(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; + + return newPos; + }; + + /** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, inverse-transformed through this matrix + */ + + + Matrix.prototype.applyInverse = function applyInverse(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var id = 1 / (this.a * this.d + this.c * -this.b); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + }; + + /** + * Translates the matrix on the x and y. + * + * @param {number} x How much to translate x by + * @param {number} y How much to translate y by + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.translate = function translate(x, y) { + this.tx += x; + this.ty += y; + + return this; + }; + + /** + * Applies a scale transformation to the matrix. + * + * @param {number} x The amount to scale horizontally + * @param {number} y The amount to scale vertically + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.scale = function scale(x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + }; + + /** + * Applies a rotation transformation to the matrix. + * + * @param {number} angle - The angle in radians. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.rotate = function rotate(angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos - this.b * sin; + this.b = a1 * sin + this.b * cos; + this.c = c1 * cos - this.d * sin; + this.d = c1 * sin + this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + }; + + /** + * Appends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to append. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.append = function append(matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + }; + + /** + * Sets the matrix based on all the available properties + * + * @param {number} x - Position on the x axis + * @param {number} y - Position on the y axis + * @param {number} pivotX - Pivot on the x axis + * @param {number} pivotY - Pivot on the y axis + * @param {number} scaleX - Scale on the x axis + * @param {number} scaleY - Scale on the y axis + * @param {number} rotation - Rotation in radians + * @param {number} skewX - Skew on the x axis + * @param {number} skewY - Skew on the y axis + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.setTransform = function setTransform(x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + var sr = Math.sin(rotation); + var cr = Math.cos(rotation); + var cy = Math.cos(skewY); + var sy = Math.sin(skewY); + var nsx = -Math.sin(skewX); + var cx = Math.cos(skewX); + + var a = cr * scaleX; + var b = sr * scaleX; + var c = -sr * scaleY; + var d = cr * scaleY; + + this.a = cy * a + sy * c; + this.b = cy * b + sy * d; + this.c = nsx * a + cx * c; + this.d = nsx * b + cx * d; + + this.tx = x + (pivotX * a + pivotY * c); + this.ty = y + (pivotX * b + pivotY * d); + + return this; + }; + + /** + * Prepends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to prepend + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.prepend = function prepend(matrix) { + var tx1 = this.tx; + + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + + this.a = a1 * matrix.a + this.b * matrix.c; + this.b = a1 * matrix.b + this.b * matrix.d; + this.c = c1 * matrix.a + this.d * matrix.c; + this.d = c1 * matrix.b + this.d * matrix.d; + } + + this.tx = tx1 * matrix.a + this.ty * matrix.c + matrix.tx; + this.ty = tx1 * matrix.b + this.ty * matrix.d + matrix.ty; + + return this; + }; + + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * + * @param {PIXI.Transform|PIXI.TransformStatic} transform - The transform to apply the properties to. + * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properties + */ + + + Matrix.prototype.decompose = function decompose(transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + + var skewX = -Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + + var delta = Math.abs(skewX + skewY); + + if (delta < 0.00001) { + transform.rotation = skewY; + + if (a < 0 && d >= 0) { + transform.rotation += transform.rotation <= 0 ? Math.PI : -Math.PI; + } + + transform.skew.x = transform.skew.y = 0; + } else { + transform.skew.x = skewX; + transform.skew.y = skewY; + } + + // next set scale + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); + + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; + + return transform; + }; + + /** + * Inverts this matrix + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.invert = function invert() { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1 * d1 - b1 * c1; + + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = (c1 * this.ty - d1 * tx1) / n; + this.ty = -(a1 * this.ty - b1 * tx1) / n; + + return this; + }; + + /** + * Resets this Matix to an identity (default) matrix. + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.identity = function identity() { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + + return this; + }; + + /** + * Creates a new Matrix object with the same values as this one. + * + * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. + */ + + + Matrix.prototype.clone = function clone() { + var matrix = new Matrix(); + + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * Changes the values of the given matrix to be the same as the ones in this matrix + * + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @return {PIXI.Matrix} The matrix given in parameter with its values updated. + */ + + + Matrix.prototype.copy = function copy(matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * A default (identity) matrix + * + * @static + * @const + */ + + + _createClass(Matrix, null, [{ + key: 'IDENTITY', + get: function get() { + return new Matrix(); + } + + /** + * A temp matrix + * + * @static + * @const + */ + + }, { + key: 'TEMP_MATRIX', + get: function get() { + return new Matrix(); + } + }]); + + return Matrix; +}(); + +exports.default = Matrix; + +},{"./Point":69}],68:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * An observable point is a point that triggers a callback when the point's position is changed. + * + * @class + * @memberof PIXI + */ +var ObservablePoint = function () { + /** + * @param {Function} cb - callback when changed + * @param {object} scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope) { + var x = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var y = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, ObservablePoint); + + this._x = x; + this._y = y; + + this.cb = cb; + this.scope = scope; + } + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + ObservablePoint.prototype.set = function set(x, y) { + var _x = x || 0; + var _y = y || (y !== 0 ? _x : 0); + + if (this._x !== _x || this._y !== _y) { + this._x = _x; + this._y = _y; + this.cb.call(this.scope); + } + }; + + /** + * Copies the data from another point + * + * @param {PIXI.Point|PIXI.ObservablePoint} point - point to copy from + */ + + + ObservablePoint.prototype.copy = function copy(point) { + if (this._x !== point.x || this._y !== point.y) { + this._x = point.x; + this._y = point.y; + this.cb.call(this.scope); + } + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + + _createClass(ObservablePoint, [{ + key: "x", + get: function get() { + return this._x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + } + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + }, { + key: "y", + get: function get() { + return this._y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + } + }]); + + return ObservablePoint; +}(); + +exports.default = ObservablePoint; + +},{}],69:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * + * @class + * @memberof PIXI + */ +var Point = function () { + /** + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function Point() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + + _classCallCheck(this, Point); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + } + + /** + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point + */ + + + Point.prototype.clone = function clone() { + return new Point(this.x, this.y); + }; + + /** + * Copies x and y from the given point + * + * @param {PIXI.Point} p - The point to copy. + */ + + + Point.prototype.copy = function copy(p) { + this.set(p.x, p.y); + }; + + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.Point} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + + + Point.prototype.equals = function equals(p) { + return p.x === this.x && p.y === this.y; + }; + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + Point.prototype.set = function set(x, y) { + this.x = x || 0; + this.y = y || (y !== 0 ? this.x : 0); + }; + + return Point; +}(); + +exports.default = Point; + +},{}],70:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('./Point'); + +Object.defineProperty(exports, 'Point', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Point).default; + } +}); + +var _ObservablePoint = require('./ObservablePoint'); + +Object.defineProperty(exports, 'ObservablePoint', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObservablePoint).default; + } +}); + +var _Matrix = require('./Matrix'); + +Object.defineProperty(exports, 'Matrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Matrix).default; + } +}); + +var _GroupD = require('./GroupD8'); + +Object.defineProperty(exports, 'GroupD8', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GroupD).default; + } +}); + +var _Circle = require('./shapes/Circle'); + +Object.defineProperty(exports, 'Circle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Circle).default; + } +}); + +var _Ellipse = require('./shapes/Ellipse'); + +Object.defineProperty(exports, 'Ellipse', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Ellipse).default; + } +}); + +var _Polygon = require('./shapes/Polygon'); + +Object.defineProperty(exports, 'Polygon', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Polygon).default; + } +}); + +var _Rectangle = require('./shapes/Rectangle'); + +Object.defineProperty(exports, 'Rectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rectangle).default; + } +}); + +var _RoundedRectangle = require('./shapes/RoundedRectangle'); + +Object.defineProperty(exports, 'RoundedRectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RoundedRectangle).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./GroupD8":66,"./Matrix":67,"./ObservablePoint":68,"./Point":69,"./shapes/Circle":71,"./shapes/Ellipse":72,"./shapes/Polygon":73,"./shapes/Rectangle":74,"./shapes/RoundedRectangle":75}],71:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Circle object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Circle = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [radius=0] - The radius of the circle + */ + function Circle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var radius = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + _classCallCheck(this, Circle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.CIRC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.CIRC; + } + + /** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ + + + Circle.prototype.clone = function clone() { + return new Circle(this.x, this.y, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this circle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Circle + */ + + + Circle.prototype.contains = function contains(x, y) { + if (this.radius <= 0) { + return false; + } + + var r2 = this.radius * this.radius; + var dx = this.x - x; + var dy = this.y - y; + + dx *= dx; + dy *= dy; + + return dx + dy <= r2; + }; + + /** + * Returns the framing rectangle of the circle as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Circle.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + + return Circle; +}(); + +exports.default = Circle; + +},{"../../const":46,"./Rectangle":74}],72:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Ellipse object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Ellipse = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [width=0] - The half width of this ellipse + * @param {number} [height=0] - The half height of this ellipse + */ + function Ellipse() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Ellipse); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.ELIP + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.ELIP; + } + + /** + * Creates a clone of this Ellipse instance + * + * @return {PIXI.Ellipse} a copy of the ellipse + */ + + + Ellipse.prototype.clone = function clone() { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coords are within this ellipse + */ + + + Ellipse.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + // normalize the coords to an ellipse with center 0,0 + var normx = (x - this.x) / this.width; + var normy = (y - this.y) / this.height; + + normx *= normx; + normy *= normy; + + return normx + normy <= 1; + }; + + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Ellipse.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.width, this.y - this.height, this.width, this.height); + }; + + return Ellipse; +}(); + +exports.default = Ellipse; + +},{"../../const":46,"./Rectangle":74}],73:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('../Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Polygon = function () { + /** + * @param {PIXI.Point[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + for (var _len = arguments.length, points = Array(_len), _key = 0; _key < _len; _key++) { + points[_key] = arguments[_key]; + } + + _classCallCheck(this, Polygon); + + if (Array.isArray(points[0])) { + points = points[0]; + } + + // if this is an array of points, convert it to a flat array of numbers + if (points[0] instanceof _Point2.default) { + var p = []; + + for (var i = 0, il = points.length; i < il; i++) { + p.push(points[i].x, points[i].y); + } + + points = p; + } + + this.closed = true; + + /** + * An array of the points of this polygon + * + * @member {number[]} + */ + this.points = points; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.POLY + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.POLY; + } + + /** + * Creates a clone of this polygon + * + * @return {PIXI.Polygon} a copy of the polygon + */ + + + Polygon.prototype.clone = function clone() { + return new Polygon(this.points.slice()); + }; + + /** + * Closes the polygon, adding points if necessary. + * + */ + + + Polygon.prototype.close = function close() { + var points = this.points; + + // close the poly if the value is true! + if (points[0] !== points[points.length - 2] || points[1] !== points[points.length - 1]) { + points.push(points[0], points[1]); + } + }; + + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this polygon + */ + + + Polygon.prototype.contains = function contains(x, y) { + var inside = false; + + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + + for (var i = 0, j = length - 1; i < length; j = i++) { + var xi = this.points[i * 2]; + var yi = this.points[i * 2 + 1]; + var xj = this.points[j * 2]; + var yj = this.points[j * 2 + 1]; + var intersect = yi > y !== yj > y && x < (xj - xi) * ((y - yi) / (yj - yi)) + xi; + + if (intersect) { + inside = !inside; + } + } + + return inside; + }; + + return Polygon; +}(); + +exports.default = Polygon; + +},{"../../const":46,"../Point":69}],74:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * + * @class + * @memberof PIXI + */ +var Rectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle + * @param {number} [width=0] - The overall width of this rectangle + * @param {number} [height=0] - The overall height of this rectangle + */ + function Rectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Rectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = Number(x); + + /** + * @member {number} + * @default 0 + */ + this.y = Number(y); + + /** + * @member {number} + * @default 0 + */ + this.width = Number(width); + + /** + * @member {number} + * @default 0 + */ + this.height = Number(height); + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.RECT + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RECT; + } + + /** + * returns the left edge of the rectangle + * + * @member {number} + */ + + + /** + * Creates a clone of this Rectangle + * + * @return {PIXI.Rectangle} a copy of the rectangle + */ + Rectangle.prototype.clone = function clone() { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + + /** + * Copies another rectangle to this one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to copy. + * @return {PIXI.Rectangle} Returns itself. + */ + + + Rectangle.prototype.copy = function copy(rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + + return this; + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rectangle + */ + + + Rectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + + return false; + }; + + /** + * Pads the rectangle making it grow in all directions. + * + * @param {number} paddingX - The horizontal padding amount. + * @param {number} paddingY - The vertical padding amount. + */ + + + Rectangle.prototype.pad = function pad(paddingX, paddingY) { + paddingX = paddingX || 0; + paddingY = paddingY || (paddingY !== 0 ? paddingX : 0); + + this.x -= paddingX; + this.y -= paddingY; + + this.width += paddingX * 2; + this.height += paddingY * 2; + }; + + /** + * Fits this rectangle around the passed one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to fit. + */ + + + Rectangle.prototype.fit = function fit(rectangle) { + if (this.x < rectangle.x) { + this.width += this.x; + if (this.width < 0) { + this.width = 0; + } + + this.x = rectangle.x; + } + + if (this.y < rectangle.y) { + this.height += this.y; + if (this.height < 0) { + this.height = 0; + } + this.y = rectangle.y; + } + + if (this.x + this.width > rectangle.x + rectangle.width) { + this.width = rectangle.width - this.x; + if (this.width < 0) { + this.width = 0; + } + } + + if (this.y + this.height > rectangle.y + rectangle.height) { + this.height = rectangle.height - this.y; + if (this.height < 0) { + this.height = 0; + } + } + }; + + /** + * Enlarges this rectangle to include the passed rectangle. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to include. + */ + + + Rectangle.prototype.enlarge = function enlarge(rectangle) { + var x1 = Math.min(this.x, rectangle.x); + var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.min(this.y, rectangle.y); + var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); + + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + }; + + _createClass(Rectangle, [{ + key: 'left', + get: function get() { + return this.x; + } + + /** + * returns the right edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'right', + get: function get() { + return this.x + this.width; + } + + /** + * returns the top edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'top', + get: function get() { + return this.y; + } + + /** + * returns the bottom edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'bottom', + get: function get() { + return this.y + this.height; + } + + /** + * A constant empty rectangle. + * + * @static + * @constant + */ + + }], [{ + key: 'EMPTY', + get: function get() { + return new Rectangle(0, 0, 0, 0); + } + }]); + + return Rectangle; +}(); + +exports.default = Rectangle; + +},{"../../const":46}],75:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. + * + * @class + * @memberof PIXI + */ +var RoundedRectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle + * @param {number} [width=0] - The overall width of this rounded rectangle + * @param {number} [height=0] - The overall height of this rounded rectangle + * @param {number} [radius=20] - Controls the radius of the rounded corners + */ + function RoundedRectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var radius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 20; + + _classCallCheck(this, RoundedRectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * @member {number} + * @default 20 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readonly + * @default PIXI.SHAPES.RREC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RREC; + } + + /** + * Creates a clone of this Rounded Rectangle + * + * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle + */ + + + RoundedRectangle.prototype.clone = function clone() { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + */ + + + RoundedRectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + if (y >= this.y + this.radius && y <= this.y + this.height - this.radius || x >= this.x + this.radius && x <= this.x + this.width - this.radius) { + return true; + } + var dx = x - (this.x + this.radius); + var dy = y - (this.y + this.radius); + var radius2 = this.radius * this.radius; + + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.width - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dy = y - (this.y + this.height - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + } + } + + return false; + }; + + return RoundedRectangle; +}(); + +exports.default = RoundedRectangle; + +},{"../../const":46}],76:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _math = require('../math'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _Container = require('../display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMatrix = new _math.Matrix(); + +/** + * The SystemRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.WebGLRenderer} which can be used for rendering a PixiJS scene. + * + * @abstract + * @class + * @extends EventEmitter + * @memberof PIXI + */ + +var SystemRenderer = function (_EventEmitter) { + _inherits(SystemRenderer, _EventEmitter); + + // eslint-disable-next-line valid-jsdoc + /** + * @param {string} system - The name of the system this renderer is for. + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function SystemRenderer(system, options, arg2, arg3) { + _classCallCheck(this, SystemRenderer); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + (0, _utils.sayHello)(system); + + // Support for constructor(system, screenWidth, screenHeight, options) + if (typeof options === 'number') { + options = Object.assign({ + width: options, + height: arg2 || _settings2.default.RENDER_OPTIONS.height + }, arg3); + } + + // Add the default render options + options = Object.assign({}, _settings2.default.RENDER_OPTIONS, options); + + /** + * The supplied constructor options. + * + * @member {Object} + * @readOnly + */ + _this.options = options; + + /** + * The type of the renderer. + * + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.UNKNOWN; + + /** + * Measurements of the screen. (0, 0, screenWidth, screenHeight) + * + * Its safe to use as filterArea or hitArea for whole stage + * + * @member {PIXI.Rectangle} + */ + _this.screen = new _math.Rectangle(0, 0, options.width, options.height); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.view = options.view || document.createElement('canvas'); + + /** + * The resolution / device pixel ratio of the renderer + * + * @member {number} + * @default 1 + */ + _this.resolution = options.resolution || _settings2.default.RESOLUTION; + + /** + * Whether the render view is transparent + * + * @member {boolean} + */ + _this.transparent = options.transparent; + + /** + * Whether css dimensions of canvas view should be resized to screen dimensions automatically + * + * @member {boolean} + */ + _this.autoResize = options.autoResize || false; + + /** + * Tracks the blend modes useful for this renderer. + * + * @member {object} + */ + _this.blendModes = null; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example if + * your game has a canvas filling background image you often don't need this set. + * + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + * + * @member {boolean} + */ + _this.roundPixels = options.roundPixels; + + /** + * The background color as a number. + * + * @member {number} + * @private + */ + _this._backgroundColor = 0x000000; + + /** + * The background color as an [R, G, B] array. + * + * @member {number[]} + * @private + */ + _this._backgroundColorRgba = [0, 0, 0, 0]; + + /** + * The background color as a string. + * + * @member {string} + * @private + */ + _this._backgroundColorString = '#000000'; + + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + + /** + * This temporary display object used as the parent of the currently being rendered item + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._tempDisplayObjectParent = new _Container2.default(); + + /** + * The last root object that the renderer tried to render. + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._lastObjectRendered = _this._tempDisplayObjectParent; + return _this; + } + + /** + * Same as view.width, actual number of pixels in the canvas by horizontal + * + * @member {number} + * @readonly + * @default 800 + */ + + + /** + * Resizes the screen and canvas to the specified width and height + * Canvas dimensions are multiplied by resolution + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + SystemRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + this.screen.width = screenWidth; + this.screen.height = screenHeight; + + this.view.width = screenWidth * this.resolution; + this.view.height = screenHeight * this.resolution; + + if (this.autoResize) { + this.view.style.width = screenWidth + 'px'; + this.view.style.height = screenHeight + 'px'; + } + }; + + /** + * Useful function that returns a texture of the display object that can then be used to create sprites + * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. + * + * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from + * @param {number} scaleMode - Should be one of the scaleMode consts + * @param {number} resolution - The resolution / device pixel ratio of the texture being generated + * @param {PIXI.Rectangle} [region] - The region of the displayObject, that shall be rendered, + * if no region is specified, defaults to the local bounds of the displayObject. + * @return {PIXI.Texture} a texture of the graphics object + */ + + + SystemRenderer.prototype.generateTexture = function generateTexture(displayObject, scaleMode, resolution, region) { + region = region || displayObject.getLocalBounds(); + + var renderTexture = _RenderTexture2.default.create(region.width | 0, region.height | 0, scaleMode, resolution); + + tempMatrix.tx = -region.x; + tempMatrix.ty = -region.y; + + this.render(displayObject, renderTexture, false, tempMatrix, true); + + return renderTexture; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + SystemRenderer.prototype.destroy = function destroy(removeView) { + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } + + this.type = _const.RENDERER_TYPE.UNKNOWN; + + this.view = null; + + this.screen = null; + + this.resolution = 0; + + this.transparent = false; + + this.autoResize = false; + + this.blendModes = null; + + this.options = null; + + this.preserveDrawingBuffer = false; + this.clearBeforeRender = false; + + this.roundPixels = false; + + this._backgroundColor = 0; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + + this._tempDisplayObjectParent = null; + this._lastObjectRendered = null; + }; + + /** + * The background color to fill if not transparent + * + * @member {number} + */ + + + _createClass(SystemRenderer, [{ + key: 'width', + get: function get() { + return this.view.width; + } + + /** + * Same as view.height, actual number of pixels in the canvas by vertical + * + * @member {number} + * @readonly + * @default 600 + */ + + }, { + key: 'height', + get: function get() { + return this.view.height; + } + }, { + key: 'backgroundColor', + get: function get() { + return this._backgroundColor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._backgroundColor = value; + this._backgroundColorString = (0, _utils.hex2string)(value); + (0, _utils.hex2rgb)(value, this._backgroundColorRgba); + } + }]); + + return SystemRenderer; +}(_eventemitter2.default); + +exports.default = SystemRenderer; + +},{"../const":46,"../display/Container":48,"../math":70,"../settings":101,"../textures/RenderTexture":113,"../utils":125,"eventemitter3":3}],77:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _CanvasMaskManager = require('./utils/CanvasMaskManager'); + +var _CanvasMaskManager2 = _interopRequireDefault(_CanvasMaskManager); + +var _CanvasRenderTarget = require('./utils/CanvasRenderTarget'); + +var _CanvasRenderTarget2 = _interopRequireDefault(_CanvasRenderTarget); + +var _mapCanvasBlendModesToPixi = require('./utils/mapCanvasBlendModesToPixi'); + +var _mapCanvasBlendModesToPixi2 = _interopRequireDefault(_mapCanvasBlendModesToPixi); + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should + * be used for browsers that do not support WebGL. Don't forget to add the CanvasRenderer.view to + * your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ +var CanvasRenderer = function (_SystemRenderer) { + _inherits(CanvasRenderer, _SystemRenderer); + + // eslint-disable-next-line valid-jsdoc + /** + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function CanvasRenderer(options, arg2, arg3) { + _classCallCheck(this, CanvasRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'Canvas', options, arg2, arg3)); + + _this.type = _const.RENDERER_TYPE.CANVAS; + + /** + * The root canvas 2d context that everything is drawn with. + * + * @member {CanvasRenderingContext2D} + */ + _this.rootContext = _this.view.getContext('2d', { alpha: _this.transparent }); + + /** + * The currently active canvas 2d context (could change with renderTextures) + * + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.rootContext; + + /** + * Boolean flag controlling canvas refresh. + * + * @member {boolean} + */ + _this.refresh = true; + + /** + * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. + * + * @member {PIXI.CanvasMaskManager} + */ + _this.maskManager = new _CanvasMaskManager2.default(_this); + + /** + * The canvas property used to set the canvas smoothing property. + * + * @member {string} + */ + _this.smoothProperty = 'imageSmoothingEnabled'; + + if (!_this.rootContext.imageSmoothingEnabled) { + if (_this.rootContext.webkitImageSmoothingEnabled) { + _this.smoothProperty = 'webkitImageSmoothingEnabled'; + } else if (_this.rootContext.mozImageSmoothingEnabled) { + _this.smoothProperty = 'mozImageSmoothingEnabled'; + } else if (_this.rootContext.oImageSmoothingEnabled) { + _this.smoothProperty = 'oImageSmoothingEnabled'; + } else if (_this.rootContext.msImageSmoothingEnabled) { + _this.smoothProperty = 'msImageSmoothingEnabled'; + } + } + + _this.initPlugins(); + + _this.blendModes = (0, _mapCanvasBlendModesToPixi2.default)(); + _this._activeBlendMode = null; + + _this.renderingToScreen = false; + + _this.resize(_this.options.width, _this.options.height); + + /** + * Fired after rendering finishes. + * + * @event PIXI.CanvasRenderer#postrender + */ + + /** + * Fired before rendering starts. + * + * @event PIXI.CanvasRenderer#prerender + */ + return _this; + } + + /** + * Renders the object to this canvas view + * + * @param {PIXI.DisplayObject} displayObject - The object to be rendered + * @param {PIXI.RenderTexture} [renderTexture] - A render texture to be rendered to. + * If unset, it will render to the root context. + * @param {boolean} [clear=false] - Whether to clear the canvas before drawing + * @param {PIXI.Transform} [transform] - A transformation to be applied + * @param {boolean} [skipUpdateTransform=false] - Whether to skip the update transform + */ + + + CanvasRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!this.view) { + return; + } + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + var rootResolution = this.resolution; + + if (renderTexture) { + renderTexture = renderTexture.baseTexture || renderTexture; + + if (!renderTexture._canvasRenderTarget) { + renderTexture._canvasRenderTarget = new _CanvasRenderTarget2.default(renderTexture.width, renderTexture.height, renderTexture.resolution); + renderTexture.source = renderTexture._canvasRenderTarget.canvas; + renderTexture.valid = true; + } + + this.context = renderTexture._canvasRenderTarget.context; + this.resolution = renderTexture._canvasRenderTarget.resolution; + } else { + this.context = this.rootContext; + } + + var context = this.context; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + var tempWt = this._tempDisplayObjectParent.transform.worldTransform; + + if (transform) { + transform.copy(tempWt); + + // lets not forget to flag the parent transform as dirty... + this._tempDisplayObjectParent.transform._worldID = -1; + } else { + tempWt.identity(); + } + + displayObject.parent = this._tempDisplayObjectParent; + + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + context.save(); + context.setTransform(1, 0, 0, 1, 0, 0); + context.globalAlpha = 1; + this._activeBlendMode = _const.BLEND_MODES.NORMAL; + context.globalCompositeOperation = this.blendModes[_const.BLEND_MODES.NORMAL]; + + if (navigator.isCocoonJS && this.view.screencanvas) { + context.fillStyle = 'black'; + context.clear(); + } + + if (clear !== undefined ? clear : this.clearBeforeRender) { + if (this.renderingToScreen) { + if (this.transparent) { + context.clearRect(0, 0, this.width, this.height); + } else { + context.fillStyle = this._backgroundColorString; + context.fillRect(0, 0, this.width, this.height); + } + } // else { + // TODO: implement background for CanvasRenderTarget or RenderTexture? + // } + } + + // TODO RENDER TARGET STUFF HERE.. + var tempContext = this.context; + + this.context = context; + displayObject.renderCanvas(this); + this.context = tempContext; + + context.restore(); + + this.resolution = rootResolution; + + this.emit('postrender'); + }; + + /** + * Clear the canvas of renderer. + * + * @param {string} [clearColor] - Clear the canvas with this color, except the canvas is transparent. + */ + + + CanvasRenderer.prototype.clear = function clear(clearColor) { + var context = this.context; + + clearColor = clearColor || this._backgroundColorString; + + if (!this.transparent && clearColor) { + context.fillStyle = clearColor; + context.fillRect(0, 0, this.width, this.height); + } else { + context.clearRect(0, 0, this.width, this.height); + } + }; + + /** + * Sets the blend mode of the renderer. + * + * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values. + */ + + + CanvasRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + if (this._activeBlendMode === blendMode) { + return; + } + + this._activeBlendMode = blendMode; + this.context.globalCompositeOperation = this.blendModes[blendMode]; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + CanvasRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // call the base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.context = null; + + this.refresh = true; + + this.maskManager.destroy(); + this.maskManager = null; + + this.smoothProperty = null; + }; + + /** + * Resizes the canvas view to the specified width and height. + * + * @extends PIXI.SystemRenderer#resize + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + CanvasRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + _SystemRenderer.prototype.resize.call(this, screenWidth, screenHeight); + + // reset the scale mode.. oddly this seems to be reset when the canvas is resized. + // surely a browser bug?? Let PixiJS fix that for you.. + if (this.smoothProperty) { + this.rootContext[this.smoothProperty] = _settings2.default.SCALE_MODE === _const.SCALE_MODES.LINEAR; + } + }; + + /** + * Checks if blend mode has changed. + */ + + + CanvasRenderer.prototype.invalidateBlendMode = function invalidateBlendMode() { + this._activeBlendMode = this.blendModes.indexOf(this.context.globalCompositeOperation); + }; + + return CanvasRenderer; +}(_SystemRenderer3.default); + +/** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @name PIXI.CanvasRenderer#plugins + * @type {object} + * @readonly + * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.extract.CanvasExtract} extract Extract image data from renderer. + * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.prepare.CanvasPrepare} prepare Pre-render display objects. + */ + +/** + * Adds a plugin to the renderer. + * + * @method PIXI.CanvasRenderer#registerPlugin + * @param {string} pluginName - The name of the plugin. + * @param {Function} ctor - The constructor function or class for the plugin. + */ + +exports.default = CanvasRenderer; +_utils.pluginTarget.mixin(CanvasRenderer); + +},{"../../const":46,"../../settings":101,"../../utils":125,"../SystemRenderer":76,"./utils/CanvasMaskManager":78,"./utils/CanvasRenderTarget":79,"./utils/mapCanvasBlendModesToPixi":81}],78:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A set of functions used to handle masking. + * + * @class + * @memberof PIXI + */ +var CanvasMaskManager = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + function CanvasMaskManager(renderer) { + _classCallCheck(this, CanvasMaskManager); + + this.renderer = renderer; + } + + /** + * This method adds it to the current stack of masks. + * + * @param {object} maskData - the maskData that will be pushed + */ + + + CanvasMaskManager.prototype.pushMask = function pushMask(maskData) { + var renderer = this.renderer; + + renderer.context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.transform.worldTransform; + var resolution = renderer.resolution; + + renderer.context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // TODO suport sprite alpha masks?? + // lots of effort required. If demand is great enough.. + if (!maskData._texture) { + this.renderGraphicsShape(maskData); + renderer.context.clip(); + } + + maskData.worldAlpha = cacheAlpha; + }; + + /** + * Renders a PIXI.Graphics shape. + * + * @param {PIXI.Graphics} graphics - The object to render. + */ + + + CanvasMaskManager.prototype.renderGraphicsShape = function renderGraphicsShape(graphics) { + var context = this.renderer.context; + var len = graphics.graphicsData.length; + + if (len === 0) { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === _const.SHAPES.POLY) { + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; j++) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) { + context.closePath(); + } + } else if (data.type === _const.SHAPES.RECT) { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } + }; + + /** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @param {PIXI.CanvasRenderer} renderer - The renderer context to use. + */ + + + CanvasMaskManager.prototype.popMask = function popMask(renderer) { + renderer.context.restore(); + renderer.invalidateBlendMode(); + }; + + /** + * Destroys this canvas mask manager. + * + */ + + + CanvasMaskManager.prototype.destroy = function destroy() { + /* empty */ + }; + + return CanvasMaskManager; +}(); + +exports.default = CanvasMaskManager; + +},{"../../../const":46}],79:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Creates a Canvas element of the given size. + * + * @class + * @memberof PIXI + */ +var CanvasRenderTarget = function () { + /** + * @param {number} width - the width for the newly created canvas + * @param {number} height - the height for the newly created canvas + * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + _classCallCheck(this, CanvasRenderTarget); + + /** + * The Canvas object that belongs to this CanvasRenderTarget. + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @member {CanvasRenderingContext2D} + */ + this.context = this.canvas.getContext('2d'); + + this.resolution = resolution || _settings2.default.RESOLUTION; + + this.resize(width, height); + } + + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * + * @private + */ + + + CanvasRenderTarget.prototype.clear = function clear() { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + + /** + * Resizes the canvas to the specified width and height. + * + * @param {number} width - the new width of the canvas + * @param {number} height - the new height of the canvas + */ + + + CanvasRenderTarget.prototype.resize = function resize(width, height) { + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; + }; + + /** + * Destroys this canvas. + * + */ + + + CanvasRenderTarget.prototype.destroy = function destroy() { + this.context = null; + this.canvas = null; + }; + + /** + * The width of the canvas buffer in pixels. + * + * @member {number} + */ + + + _createClass(CanvasRenderTarget, [{ + key: 'width', + get: function get() { + return this.canvas.width; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.width = val; + } + + /** + * The height of the canvas buffer in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.canvas.height; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.height = val; + } + }]); + + return CanvasRenderTarget; +}(); + +exports.default = CanvasRenderTarget; + +},{"../../../settings":101}],80:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = canUseNewCanvasBlendModes; +/** + * Creates a little colored canvas + * + * @ignore + * @param {string} color - The color to make the canvas + * @return {canvas} a small canvas element + */ +function createColoredCanvas(color) { + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.fillStyle = color; + context.fillRect(0, 0, 6, 1); + + return canvas; +} + +/** + * Checks whether the Canvas BlendModes are supported by the current browser + * + * @return {boolean} whether they are supported + */ +function canUseNewCanvasBlendModes() { + if (typeof document === 'undefined') { + return false; + } + + var magenta = createColoredCanvas('#ff00ff'); + var yellow = createColoredCanvas('#ffff00'); + + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.globalCompositeOperation = 'multiply'; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + var imageData = context.getImageData(2, 0, 1, 1); + + if (!imageData) { + return false; + } + + var data = imageData.data; + + return data[0] === 255 && data[1] === 0 && data[2] === 0; +} + +},{}],81:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapCanvasBlendModesToPixi; + +var _const = require('../../../const'); + +var _canUseNewCanvasBlendModes = require('./canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Maps blend combinations to Canvas. + * + * @memberof PIXI + * @function mapCanvasBlendModesToPixi + * @private + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapCanvasBlendModesToPixi() { + var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + + if ((0, _canUseNewCanvasBlendModes2.default)()) { + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'multiply'; + array[_const.BLEND_MODES.SCREEN] = 'screen'; + array[_const.BLEND_MODES.OVERLAY] = 'overlay'; + array[_const.BLEND_MODES.DARKEN] = 'darken'; + array[_const.BLEND_MODES.LIGHTEN] = 'lighten'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'color-dodge'; + array[_const.BLEND_MODES.COLOR_BURN] = 'color-burn'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'hard-light'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'soft-light'; + array[_const.BLEND_MODES.DIFFERENCE] = 'difference'; + array[_const.BLEND_MODES.EXCLUSION] = 'exclusion'; + array[_const.BLEND_MODES.HUE] = 'hue'; + array[_const.BLEND_MODES.SATURATION] = 'saturate'; + array[_const.BLEND_MODES.COLOR] = 'color'; + array[_const.BLEND_MODES.LUMINOSITY] = 'luminosity'; + } else { + // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'source-over'; + array[_const.BLEND_MODES.SCREEN] = 'source-over'; + array[_const.BLEND_MODES.OVERLAY] = 'source-over'; + array[_const.BLEND_MODES.DARKEN] = 'source-over'; + array[_const.BLEND_MODES.LIGHTEN] = 'source-over'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'source-over'; + array[_const.BLEND_MODES.COLOR_BURN] = 'source-over'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.DIFFERENCE] = 'source-over'; + array[_const.BLEND_MODES.EXCLUSION] = 'source-over'; + array[_const.BLEND_MODES.HUE] = 'source-over'; + array[_const.BLEND_MODES.SATURATION] = 'source-over'; + array[_const.BLEND_MODES.COLOR] = 'source-over'; + array[_const.BLEND_MODES.LUMINOSITY] = 'source-over'; + } + // not-premultiplied, only for webgl + array[_const.BLEND_MODES.NORMAL_NPM] = array[_const.BLEND_MODES.NORMAL]; + array[_const.BLEND_MODES.ADD_NPM] = array[_const.BLEND_MODES.ADD]; + array[_const.BLEND_MODES.SCREEN_NPM] = array[_const.BLEND_MODES.SCREEN]; + + return array; +} + +},{"../../../const":46,"./canUseNewCanvasBlendModes":80}],82:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged + * up with textures that are no longer being used. + * + * @class + * @memberof PIXI + */ +var TextureGarbageCollector = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function TextureGarbageCollector(renderer) { + _classCallCheck(this, TextureGarbageCollector); + + this.renderer = renderer; + + this.count = 0; + this.checkCount = 0; + this.maxIdle = _settings2.default.GC_MAX_IDLE; + this.checkCountMax = _settings2.default.GC_MAX_CHECK_COUNT; + this.mode = _settings2.default.GC_MODE; + } + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.update = function update() { + this.count++; + + if (this.mode === _const.GC_MODES.MANUAL) { + return; + } + + this.checkCount++; + + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + + this.run(); + } + }; + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.run = function run() { + var tm = this.renderer.textureManager; + var managedTextures = tm._managedTextures; + var wasRemoved = false; + + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + + // only supports non generated textures at the moment! + if (!texture._glRenderTargets && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + + if (wasRemoved) { + var j = 0; + + for (var _i = 0; _i < managedTextures.length; _i++) { + if (managedTextures[_i] !== null) { + managedTextures[j++] = managedTextures[_i]; + } + } + + managedTextures.length = j; + } + }; + + /** + * Removes all the textures within the specified displayObject and its children from the GPU + * + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + */ + + + TextureGarbageCollector.prototype.unload = function unload(displayObject) { + var tm = this.renderer.textureManager; + + // only destroy non generated textures + if (displayObject._texture && displayObject._texture._glRenderTargets) { + tm.destroyTexture(displayObject._texture, true); + } + + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + + return TextureGarbageCollector; +}(); + +exports.default = TextureGarbageCollector; + +},{"../../const":46,"../../settings":101}],83:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _const = require('../../const'); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _utils = require('../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a webGL Texture + * + * @class + * @memberof PIXI + */ +var TextureManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function TextureManager(renderer) { + _classCallCheck(this, TextureManager); + + /** + * A reference to the current renderer + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = renderer.gl; + + /** + * Track textures in the renderer so we can no longer listen to them on destruction. + * + * @member {Array<*>} + * @private + */ + this._managedTextures = []; + } + + /** + * Binds a texture. + * + */ + + + TextureManager.prototype.bindTexture = function bindTexture() {} + // empty + + + /** + * Gets a texture. + * + */ + ; + + TextureManager.prototype.getTexture = function getTexture() {} + // empty + + + /** + * Updates and/or Creates a WebGL texture for the renderer's context. + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update + * @param {number} location - the location the texture will be bound to. + * @return {GLTexture} The gl texture. + */ + ; + + TextureManager.prototype.updateTexture = function updateTexture(texture, location) { + // assume it good! + // texture = texture.baseTexture || texture; + + var gl = this.gl; + + var isRenderTexture = !!texture._glRenderTargets; + + if (!texture.hasLoaded) { + return null; + } + + var boundTextures = this.renderer.boundTextures; + + // if the location is undefined then this may have been called by n event. + // this being the case the texture may already be bound to a slot. As a texture can only be bound once + // we need to find its current location if it exists. + if (location === undefined) { + location = 0; + + // TODO maybe we can use texture bound ids later on... + // check if texture is already bound.. + for (var i = 0; i < boundTextures.length; ++i) { + if (boundTextures[i] === texture) { + location = i; + break; + } + } + } + + boundTextures[location] = texture; + + gl.activeTexture(gl.TEXTURE0 + location); + + var glTexture = texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!glTexture) { + if (isRenderTexture) { + var renderTarget = new _RenderTarget2.default(this.gl, texture.width, texture.height, texture.scaleMode, texture.resolution); + + renderTarget.resize(texture.width, texture.height); + texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget; + glTexture = renderTarget.texture; + } else { + glTexture = new _pixiGlCore.GLTexture(this.gl, null, null, null, null); + glTexture.bind(location); + glTexture.premultiplyAlpha = true; + glTexture.upload(texture.source); + } + + texture._glTextures[this.renderer.CONTEXT_UID] = glTexture; + + texture.on('update', this.updateTexture, this); + texture.on('dispose', this.destroyTexture, this); + + this._managedTextures.push(texture); + + if (texture.isPowerOfTwo) { + if (texture.mipmap) { + glTexture.enableMipmap(); + } + + if (texture.wrapMode === _const.WRAP_MODES.CLAMP) { + glTexture.enableWrapClamp(); + } else if (texture.wrapMode === _const.WRAP_MODES.REPEAT) { + glTexture.enableWrapRepeat(); + } else { + glTexture.enableWrapMirrorRepeat(); + } + } else { + glTexture.enableWrapClamp(); + } + + if (texture.scaleMode === _const.SCALE_MODES.NEAREST) { + glTexture.enableNearestScaling(); + } else { + glTexture.enableLinearScaling(); + } + } + // the texture already exists so we only need to update it.. + else if (isRenderTexture) { + texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height); + } else { + glTexture.upload(texture.source); + } + + return glTexture; + }; + + /** + * Deletes the texture from WebGL + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy + * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. + */ + + + TextureManager.prototype.destroyTexture = function destroyTexture(texture, skipRemove) { + texture = texture.baseTexture || texture; + + if (!texture.hasLoaded) { + return; + } + + var uid = this.renderer.CONTEXT_UID; + var glTextures = texture._glTextures; + var glRenderTargets = texture._glRenderTargets; + + if (glTextures[uid]) { + this.renderer.unbindTexture(texture); + + glTextures[uid].destroy(); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + + delete glTextures[uid]; + + if (!skipRemove) { + var i = this._managedTextures.indexOf(texture); + + if (i !== -1) { + (0, _utils.removeItems)(this._managedTextures, i, 1); + } + } + } + + if (glRenderTargets && glRenderTargets[uid]) { + glRenderTargets[uid].destroy(); + delete glRenderTargets[uid]; + } + }; + + /** + * Deletes all the textures from WebGL + */ + + + TextureManager.prototype.removeAll = function removeAll() { + // empty all the old gl textures as they are useless now + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + delete texture._glTextures[this.renderer.CONTEXT_UID]; + } + } + }; + + /** + * Destroys this manager and removes all its textures + */ + + + TextureManager.prototype.destroy = function destroy() { + // destroy managed textures + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + this.destroyTexture(texture, true); + + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + } + + this._managedTextures = null; + }; + + return TextureManager; +}(); + +exports.default = TextureManager; + +},{"../../const":46,"../../utils":125,"./utils/RenderTarget":96,"pixi-gl-core":12}],84:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _MaskManager = require('./managers/MaskManager'); + +var _MaskManager2 = _interopRequireDefault(_MaskManager); + +var _StencilManager = require('./managers/StencilManager'); + +var _StencilManager2 = _interopRequireDefault(_StencilManager); + +var _FilterManager = require('./managers/FilterManager'); + +var _FilterManager2 = _interopRequireDefault(_FilterManager); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _ObjectRenderer = require('./utils/ObjectRenderer'); + +var _ObjectRenderer2 = _interopRequireDefault(_ObjectRenderer); + +var _TextureManager = require('./TextureManager'); + +var _TextureManager2 = _interopRequireDefault(_TextureManager); + +var _BaseTexture = require('../../textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _TextureGarbageCollector = require('./TextureGarbageCollector'); + +var _TextureGarbageCollector2 = _interopRequireDefault(_TextureGarbageCollector); + +var _WebGLState = require('./WebGLState'); + +var _WebGLState2 = _interopRequireDefault(_WebGLState); + +var _mapWebGLDrawModesToPixi = require('./utils/mapWebGLDrawModesToPixi'); + +var _mapWebGLDrawModesToPixi2 = _interopRequireDefault(_mapWebGLDrawModesToPixi); + +var _validateContext = require('./utils/validateContext'); + +var _validateContext2 = _interopRequireDefault(_validateContext); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CONTEXT_UID = 0; + +/** + * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ + +var WebGLRenderer = function (_SystemRenderer) { + _inherits(WebGLRenderer, _SystemRenderer); + + // eslint-disable-next-line valid-jsdoc + /** + * + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias. If not available natively then FXAA + * antialiasing is used + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. + * The resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear + * the canvas or not before the new render pass. If you wish to set this to false, you *must* set + * preserveDrawingBuffer to `true`. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when + * rendering, stopping pixel interpolation. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.legacy=false] - If true PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experiance unexplained flickering try setting this to true. + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card + */ + function WebGLRenderer(options, arg2, arg3) { + _classCallCheck(this, WebGLRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'WebGL', options, arg2, arg3)); + + _this.legacy = _this.options.legacy; + + if (_this.legacy) { + _pixiGlCore2.default.VertexArrayObject.FORCE_NATIVE = true; + } + + /** + * The type of this renderer as a standardised const + * + * @member {number} + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.WEBGL; + + _this.handleContextLost = _this.handleContextLost.bind(_this); + _this.handleContextRestored = _this.handleContextRestored.bind(_this); + + _this.view.addEventListener('webglcontextlost', _this.handleContextLost, false); + _this.view.addEventListener('webglcontextrestored', _this.handleContextRestored, false); + + /** + * The options passed in to create a new webgl context. + * + * @member {object} + * @private + */ + _this._contextOptions = { + alpha: _this.transparent, + antialias: _this.options.antialias, + premultipliedAlpha: _this.transparent && _this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: _this.options.preserveDrawingBuffer, + powerPreference: _this.options.powerPreference + }; + + _this._backgroundColorRgba[3] = _this.transparent ? 0 : 1; + + /** + * Manages the masks using the stencil buffer. + * + * @member {PIXI.MaskManager} + */ + _this.maskManager = new _MaskManager2.default(_this); + + /** + * Manages the stencil buffer. + * + * @member {PIXI.StencilManager} + */ + _this.stencilManager = new _StencilManager2.default(_this); + + /** + * An empty renderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.emptyRenderer = new _ObjectRenderer2.default(_this); + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.currentRenderer = _this.emptyRenderer; + + /** + * Manages textures + * @member {PIXI.TextureManager} + */ + _this.textureManager = null; + + /** + * Manages the filters. + * + * @member {PIXI.FilterManager} + */ + _this.filterManager = null; + + _this.initPlugins(); + + /** + * The current WebGL rendering context, it is created here + * + * @member {WebGLRenderingContext} + */ + // initialize the context so it is ready for the managers. + if (_this.options.context) { + // checks to see if a context is valid.. + (0, _validateContext2.default)(_this.options.context); + } + + _this.gl = _this.options.context || _pixiGlCore2.default.createContext(_this.view, _this._contextOptions); + + _this.CONTEXT_UID = CONTEXT_UID++; + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.WebGLState} + */ + _this.state = new _WebGLState2.default(_this.gl); + + _this.renderingToScreen = true; + + /** + * Holds the current state of textures bound to the GPU. + * @type {Array} + */ + _this.boundTextures = null; + + /** + * Holds the current shader + * + * @member {PIXI.Shader} + */ + _this._activeShader = null; + + _this._activeVao = null; + + /** + * Holds the current render target + * + * @member {PIXI.RenderTarget} + */ + _this._activeRenderTarget = null; + + _this._initContext(); + + // map some webGL blend and drawmodes.. + _this.drawModes = (0, _mapWebGLDrawModesToPixi2.default)(_this.gl); + + _this._nextTextureLocation = 0; + + _this.setBlendMode(0); + + /** + * Fired after rendering finishes. + * + * @event PIXI.WebGLRenderer#postrender + */ + + /** + * Fired before rendering starts. + * + * @event PIXI.WebGLRenderer#prerender + */ + + /** + * Fired when the WebGL context is set. + * + * @event PIXI.WebGLRenderer#context + * @param {WebGLRenderingContext} gl - WebGL context. + */ + return _this; + } + + /** + * Creates the WebGL context + * + * @private + */ + + + WebGLRenderer.prototype._initContext = function _initContext() { + var gl = this.gl; + + // restore a context if it was previously lost + if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').restoreContext(); + } + + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + + this._activeShader = null; + this._activeVao = null; + + this.boundTextures = new Array(maxTextures); + this.emptyTextures = new Array(maxTextures); + + // create a texture manager... + this.textureManager = new _TextureManager2.default(this); + this.filterManager = new _FilterManager2.default(this); + this.textureGC = new _TextureGarbageCollector2.default(this); + + this.state.resetToDefault(); + + this.rootRenderTarget = new _RenderTarget2.default(gl, this.width, this.height, null, this.resolution, true); + this.rootRenderTarget.clearColor = this._backgroundColorRgba; + + this.bindRenderTarget(this.rootRenderTarget); + + // now lets fill up the textures with empty ones! + var emptyGLTexture = new _pixiGlCore2.default.GLTexture.fromData(gl, null, 1, 1); + + var tempObj = { _glTextures: {} }; + + tempObj._glTextures[this.CONTEXT_UID] = {}; + + for (var i = 0; i < maxTextures; i++) { + var empty = new _BaseTexture2.default(); + + empty._glTextures[this.CONTEXT_UID] = emptyGLTexture; + + this.boundTextures[i] = tempObj; + this.emptyTextures[i] = empty; + this.bindTexture(null, i); + } + + this.emit('context', gl); + + // setup the width/height properties and gl viewport + this.resize(this.screen.width, this.screen.height); + }; + + /** + * Renders the object to its webGL view + * + * @param {PIXI.DisplayObject} displayObject - the object to be rendered + * @param {PIXI.RenderTexture} renderTexture - The render texture to render to. + * @param {boolean} [clear] - Should the canvas be cleared before the new render + * @param {PIXI.Transform} [transform] - A transform to apply to the render texture before rendering. + * @param {boolean} [skipUpdateTransform] - Should we skip the update transform pass? + */ + + + WebGLRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + // no point rendering if our context has been blown up! + if (!this.gl || this.gl.isContextLost()) { + return; + } + + this._nextTextureLocation = 0; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + this.bindRenderTexture(renderTexture, transform); + + this.currentRenderer.start(); + + if (clear !== undefined ? clear : this.clearBeforeRender) { + this._activeRenderTarget.clear(); + } + + displayObject.renderWebGL(this); + + // apply transform.. + this.currentRenderer.flush(); + + // this.setObjectRenderer(this.emptyRenderer); + + this.textureGC.update(); + + this.emit('postrender'); + }; + + /** + * Changes the current renderer to the one given in parameter + * + * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. + */ + + + WebGLRenderer.prototype.setObjectRenderer = function setObjectRenderer(objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; + + /** + * This should be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + * + */ + + + WebGLRenderer.prototype.flush = function flush() { + this.setObjectRenderer(this.emptyRenderer); + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + WebGLRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + // if(width * this.resolution === this.width && height * this.resolution === this.height)return; + + _SystemRenderer3.default.prototype.resize.call(this, screenWidth, screenHeight); + + this.rootRenderTarget.resize(screenWidth, screenHeight); + + if (this._activeRenderTarget === this.rootRenderTarget) { + this.rootRenderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true); + } + } + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} blendMode - the desired blend mode + */ + + + WebGLRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + this.state.setBlendMode(blendMode); + }; + + /** + * Erases the active render target and fills the drawing area with a colour + * + * @param {number} [clearColor] - The colour + */ + + + WebGLRenderer.prototype.clear = function clear(clearColor) { + this._activeRenderTarget.clear(clearColor); + }; + + /** + * Sets the transform of the active render target to the given matrix + * + * @param {PIXI.Matrix} matrix - The transformation matrix + */ + + + WebGLRenderer.prototype.setTransform = function setTransform(matrix) { + this._activeRenderTarget.transform = matrix; + }; + + /** + * Erases the render texture and fills the drawing area with a colour + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to clear + * @param {number} [clearColor] - The colour + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.clearRenderTexture = function clearRenderTexture(renderTexture, clearColor) { + var baseTexture = renderTexture.baseTexture; + var renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + + if (renderTarget) { + renderTarget.clear(clearColor); + } + + return this; + }; + + /** + * Binds a render texture for rendering + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to render + * @param {PIXI.Transform} transform - The transform to be applied to the render texture + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTexture = function bindRenderTexture(renderTexture, transform) { + var renderTarget = void 0; + + if (renderTexture) { + var baseTexture = renderTexture.baseTexture; + + if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) { + // bind the current texture + this.textureManager.updateTexture(baseTexture, 0); + } + + this.unbindTexture(baseTexture); + + renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + renderTarget.setFrame(renderTexture.frame); + } else { + renderTarget = this.rootRenderTarget; + } + + renderTarget.transform = transform; + this.bindRenderTarget(renderTarget); + + return this; + }; + + /** + * Changes the current render target to the one given in parameter + * + * @param {PIXI.RenderTarget} renderTarget - the new render target + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTarget = function bindRenderTarget(renderTarget) { + if (renderTarget !== this._activeRenderTarget) { + this._activeRenderTarget = renderTarget; + renderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true); + } + + this.stencilManager.setMaskStack(renderTarget.stencilMaskStack); + } + + return this; + }; + + /** + * Changes the current shader to the one given in parameter + * + * @param {PIXI.Shader} shader - the new shader + * @param {boolean} [autoProject=true] - Whether automatically set the projection matrix + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindShader = function bindShader(shader, autoProject) { + // TODO cache + if (this._activeShader !== shader) { + this._activeShader = shader; + shader.bind(); + + // `autoProject` normally would be a default parameter set to true + // but because of how Babel transpiles default parameters + // it hinders the performance of this method. + if (autoProject !== false) { + // automatically set the projection matrix + shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(true); + } + } + + return this; + }; + + /** + * Binds the texture. This will return the location of the bound texture. + * It may not be the same as the one you pass in. This is due to optimisation that prevents + * needless binding of textures. For example if the texture is already bound it will return the + * current location of the texture instead of the one provided. To bypass this use force location + * + * @param {PIXI.Texture} texture - the new texture + * @param {number} location - the suggested texture location + * @param {boolean} forceLocation - force the location + * @return {number} bound texture location + */ + + + WebGLRenderer.prototype.bindTexture = function bindTexture(texture, location, forceLocation) { + texture = texture || this.emptyTextures[location]; + texture = texture.baseTexture || texture; + texture.touched = this.textureGC.count; + + if (!forceLocation) { + // TODO - maybe look into adding boundIds.. save us the loop? + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + return i; + } + } + + if (location === undefined) { + this._nextTextureLocation++; + this._nextTextureLocation %= this.boundTextures.length; + location = this.boundTextures.length - this._nextTextureLocation - 1; + } + } else { + location = location || 0; + } + + var gl = this.gl; + var glTexture = texture._glTextures[this.CONTEXT_UID]; + + if (!glTexture) { + // this will also bind the texture.. + this.textureManager.updateTexture(texture, location); + } else { + // bind the current texture + this.boundTextures[location] = texture; + gl.activeTexture(gl.TEXTURE0 + location); + gl.bindTexture(gl.TEXTURE_2D, glTexture.texture); + } + + return location; + }; + + /** + * unbinds the texture ... + * + * @param {PIXI.Texture} texture - the texture to unbind + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.unbindTexture = function unbindTexture(texture) { + var gl = this.gl; + + texture = texture.baseTexture || texture; + + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + this.boundTextures[i] = this.emptyTextures[i]; + + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[i]._glTextures[this.CONTEXT_UID].texture); + } + } + + return this; + }; + + /** + * Creates a new VAO from this renderer's context and state. + * + * @return {VertexArrayObject} The new VAO. + */ + + + WebGLRenderer.prototype.createVao = function createVao() { + return new _pixiGlCore2.default.VertexArrayObject(this.gl, this.state.attribState); + }; + + /** + * Changes the current Vao to the one given in parameter + * + * @param {PIXI.VertexArrayObject} vao - the new Vao + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindVao = function bindVao(vao) { + if (this._activeVao === vao) { + return this; + } + + if (vao) { + vao.bind(); + } else if (this._activeVao) { + // TODO this should always be true i think? + this._activeVao.unbind(); + } + + this._activeVao = vao; + + return this; + }; + + /** + * Resets the WebGL state so you can render things however you fancy! + * + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.reset = function reset() { + this.setObjectRenderer(this.emptyRenderer); + + this.bindVao(null); + this._activeShader = null; + this._activeRenderTarget = this.rootRenderTarget; + + for (var i = 0; i < this.boundTextures.length; i++) { + this.boundTextures[i] = this.emptyTextures[i]; + } + + // bind the main frame buffer (the screen); + this.rootRenderTarget.activate(); + + this.state.resetToDefault(); + + return this; + }; + + /** + * Handles a lost webgl context + * + * @private + * @param {WebGLContextEvent} event - The context lost event. + */ + + + WebGLRenderer.prototype.handleContextLost = function handleContextLost(event) { + event.preventDefault(); + }; + + /** + * Handles a restored webgl context + * + * @private + */ + + + WebGLRenderer.prototype.handleContextRestored = function handleContextRestored() { + this.textureManager.removeAll(); + this.filterManager.destroy(true); + this._initContext(); + }; + + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + + + WebGLRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // remove listeners + this.view.removeEventListener('webglcontextlost', this.handleContextLost); + this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); + + this.textureManager.destroy(); + + // call base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.uid = 0; + + // destroy the managers + this.maskManager.destroy(); + this.stencilManager.destroy(); + this.filterManager.destroy(); + + this.maskManager = null; + this.filterManager = null; + this.textureManager = null; + this.currentRenderer = null; + + this.handleContextLost = null; + this.handleContextRestored = null; + + this._contextOptions = null; + this.gl.useProgram(null); + + if (this.gl.getExtension('WEBGL_lose_context')) { + this.gl.getExtension('WEBGL_lose_context').loseContext(); + } + + this.gl = null; + + // this = null; + }; + + return WebGLRenderer; +}(_SystemRenderer3.default); + +/** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @name PIXI.WebGLRenderer#plugins + * @type {object} + * @readonly + * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.extract.WebGLExtract} extract Extract image data from renderer. + * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.prepare.WebGLPrepare} prepare Pre-render display objects. + */ + +/** + * Adds a plugin to the renderer. + * + * @method PIXI.WebGLRenderer#registerPlugin + * @param {string} pluginName - The name of the plugin. + * @param {Function} ctor - The constructor function or class for the plugin. + */ + +exports.default = WebGLRenderer; +_utils.pluginTarget.mixin(WebGLRenderer); + +},{"../../const":46,"../../textures/BaseTexture":112,"../../utils":125,"../SystemRenderer":76,"./TextureGarbageCollector":82,"./TextureManager":83,"./WebGLState":85,"./managers/FilterManager":90,"./managers/MaskManager":91,"./managers/StencilManager":92,"./utils/ObjectRenderer":94,"./utils/RenderTarget":96,"./utils/mapWebGLDrawModesToPixi":99,"./utils/validateContext":100,"pixi-gl-core":12}],85:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); + +var _mapWebGLBlendModesToPixi2 = _interopRequireDefault(_mapWebGLBlendModesToPixi); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var BLEND = 0; +var DEPTH_TEST = 1; +var FRONT_FACE = 2; +var CULL_FACE = 3; +var BLEND_FUNC = 4; + +/** + * A WebGL state machines + * + * @memberof PIXI + * @class + */ + +var WebGLState = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + */ + function WebGLState(gl) { + _classCallCheck(this, WebGLState); + + /** + * The current active state + * + * @member {Uint8Array} + */ + this.activeState = new Uint8Array(16); + + /** + * The default state + * + * @member {Uint8Array} + */ + this.defaultState = new Uint8Array(16); + + // default blend mode.. + this.defaultState[0] = 1; + + /** + * The current state index in the stack + * + * @member {number} + * @private + */ + this.stackIndex = 0; + + /** + * The stack holding all the different states + * + * @member {Array<*>} + * @private + */ + this.stack = []; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + this.attribState = { + tempAttribState: new Array(this.maxAttribs), + attribState: new Array(this.maxAttribs) + }; + + this.blendModes = (0, _mapWebGLBlendModesToPixi2.default)(gl); + + // check we have vao.. + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || gl.getExtension('MOZ_OES_vertex_array_object') || gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + /** + * Pushes a new active state + */ + + + WebGLState.prototype.push = function push() { + // next state.. + var state = this.stack[this.stackIndex]; + + if (!state) { + state = this.stack[this.stackIndex] = new Uint8Array(16); + } + + ++this.stackIndex; + + // copy state.. + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) { + state[i] = this.activeState[i]; + } + }; + + /** + * Pops a state out + */ + + + WebGLState.prototype.pop = function pop() { + var state = this.stack[--this.stackIndex]; + + this.setState(state); + }; + + /** + * Sets the current state + * + * @param {*} state - The state to set. + */ + + + WebGLState.prototype.setState = function setState(state) { + this.setBlend(state[BLEND]); + this.setDepthTest(state[DEPTH_TEST]); + this.setFrontFace(state[FRONT_FACE]); + this.setCullFace(state[CULL_FACE]); + this.setBlendMode(state[BLEND_FUNC]); + }; + + /** + * Enables or disabled blending. + * + * @param {boolean} value - Turn on or off webgl blending. + */ + + + WebGLState.prototype.setBlend = function setBlend(value) { + value = value ? 1 : 0; + + if (this.activeState[BLEND] === value) { + return; + } + + this.activeState[BLEND] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + }; + + /** + * Sets the blend mode. + * + * @param {number} value - The blend mode to set to. + */ + + + WebGLState.prototype.setBlendMode = function setBlendMode(value) { + if (value === this.activeState[BLEND_FUNC]) { + return; + } + + this.activeState[BLEND_FUNC] = value; + + var mode = this.blendModes[value]; + + if (mode.length === 2) { + this.gl.blendFunc(mode[0], mode[1]); + } else { + this.gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); + } + }; + + /** + * Sets whether to enable or disable depth test. + * + * @param {boolean} value - Turn on or off webgl depth testing. + */ + + + WebGLState.prototype.setDepthTest = function setDepthTest(value) { + value = value ? 1 : 0; + + if (this.activeState[DEPTH_TEST] === value) { + return; + } + + this.activeState[DEPTH_TEST] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + }; + + /** + * Sets whether to enable or disable cull face. + * + * @param {boolean} value - Turn on or off webgl cull face. + */ + + + WebGLState.prototype.setCullFace = function setCullFace(value) { + value = value ? 1 : 0; + + if (this.activeState[CULL_FACE] === value) { + return; + } + + this.activeState[CULL_FACE] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + }; + + /** + * Sets the gl front face. + * + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ + + + WebGLState.prototype.setFrontFace = function setFrontFace(value) { + value = value ? 1 : 0; + + if (this.activeState[FRONT_FACE] === value) { + return; + } + + this.activeState[FRONT_FACE] = value; + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); + }; + + /** + * Disables all the vaos in use + * + */ + + + WebGLState.prototype.resetAttributes = function resetAttributes() { + for (var i = 0; i < this.attribState.tempAttribState.length; i++) { + this.attribState.tempAttribState[i] = 0; + } + + for (var _i = 0; _i < this.attribState.attribState.length; _i++) { + this.attribState.attribState[_i] = 0; + } + + // im going to assume one is always active for performance reasons. + for (var _i2 = 1; _i2 < this.maxAttribs; _i2++) { + this.gl.disableVertexAttribArray(_i2); + } + }; + + // used + /** + * Resets all the logic and disables the vaos + */ + + + WebGLState.prototype.resetToDefault = function resetToDefault() { + // unbind any VAO if they exist.. + if (this.nativeVaoExtension) { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + // reset all attributes.. + this.resetAttributes(); + + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; ++i) { + this.activeState[i] = 32; + } + + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + + this.setState(this.defaultState); + }; + + return WebGLState; +}(); + +exports.default = WebGLState; + +},{"./utils/mapWebGLBlendModesToPixi":98}],86:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _extractUniformsFromSrc = require('./extractUniformsFromSrc'); + +var _extractUniformsFromSrc2 = _interopRequireDefault(_extractUniformsFromSrc); + +var _utils = require('../../../utils'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SOURCE_KEY_MAP = {}; + +// let math = require('../../../math'); +/** + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ + +var Filter = function () { + /** + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. + */ + function Filter(vertexSrc, fragmentSrc, uniforms) { + _classCallCheck(this, Filter); + + /** + * The vertex shader. + * + * @member {string} + */ + this.vertexSrc = vertexSrc || Filter.defaultVertexSrc; + + /** + * The fragment shader. + * + * @member {string} + */ + this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc; + + this._blendMode = _const.BLEND_MODES.NORMAL; + + this.uniformData = uniforms || (0, _extractUniformsFromSrc2.default)(this.vertexSrc, this.fragmentSrc, 'projectionMatrix|uSampler'); + + /** + * An object containing the current values of custom uniforms. + * @example Updating the value of a custom uniform + * filter.uniforms.time = performance.now(); + * + * @member {object} + */ + this.uniforms = {}; + + for (var i in this.uniformData) { + this.uniforms[i] = this.uniformData[i].value; + if (this.uniformData[i].type) { + this.uniformData[i].type = this.uniformData[i].type.toLowerCase(); + } + } + + // this is where we store shader references.. + // TODO we could cache this! + this.glShaders = {}; + + // used for cacheing.. sure there is a better way! + if (!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) { + SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = (0, _utils.uid)(); + } + + this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]; + + /** + * The padding of the filter. Some filters require extra space to breath such as a blur. + * Increasing this will add extra width and height to the bounds of the object that the + * filter is applied to. + * + * @member {number} + */ + this.padding = 4; + + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + * + * @member {number} + */ + this.resolution = _settings2.default.RESOLUTION; + + /** + * If enabled is true the filter is applied, if false it will not. + * + * @member {boolean} + */ + this.enabled = true; + + /** + * If enabled, PixiJS will fit the filter area into boundaries for better performance. + * Switch it off if it does not work for specific shader. + * + * @member {boolean} + */ + this.autoFit = true; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + * @param {object} [currentState] - It's current state of filter. + * There are some useful properties in the currentState : + * target, filters, sourceFrame, destinationFrame, renderTarget, resolution + */ + + + Filter.prototype.apply = function apply(filterManager, input, output, clear, currentState) // eslint-disable-line no-unused-vars + { + // --- // + // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); + + // do as you please! + + filterManager.applyFilter(this, input, output, clear); + + // or just do a regular render.. + }; + + /** + * Sets the blendmode of the filter + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + */ + + + _createClass(Filter, [{ + key: 'blendMode', + get: function get() { + return this._blendMode; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._blendMode = value; + } + + /** + * The default vertex shader source + * + * @static + * @constant + */ + + }], [{ + key: 'defaultVertexSrc', + get: function get() { + return ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform mat3 projectionMatrix;', 'uniform mat3 filterMatrix;', 'varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;', ' vTextureCoord = aTextureCoord ;', '}'].join('\n'); + } + + /** + * The default fragment shader source + * + * @static + * @constant + */ + + }, { + key: 'defaultFragmentSrc', + get: function get() { + return ['varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'uniform sampler2D uSampler;', 'uniform sampler2D filterSampler;', 'void main(void){', ' vec4 masky = texture2D(filterSampler, vFilterCoord);', ' vec4 sample = texture2D(uSampler, vTextureCoord);', ' vec4 color;', ' if(mod(vFilterCoord.x, 1.0) > 0.5)', ' {', ' color = vec4(1.0, 0.0, 0.0, 1.0);', ' }', ' else', ' {', ' color = vec4(0.0, 1.0, 0.0, 1.0);', ' }', + // ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', + ' gl_FragColor = mix(sample, masky, 0.5);', ' gl_FragColor *= sample.a;', '}'].join('\n'); + } + }]); + + return Filter; +}(); + +exports.default = Filter; + +},{"../../../const":46,"../../../settings":101,"../../../utils":125,"./extractUniformsFromSrc":87}],87:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = extractUniformsFromSrc; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var defaultValue = _pixiGlCore2.default.shader.defaultValue; + +function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) { + var vertUniforms = extractUniformsFromString(vertexSrc, mask); + var fragUniforms = extractUniformsFromString(fragmentSrc, mask); + + return Object.assign(vertUniforms, fragUniforms); +} + +function extractUniformsFromString(string) { + var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea|filterClamp)$'); + + var uniforms = {}; + var nameSplit = void 0; + + // clean the lines a little - remove extra spaces / tabs etc + // then split along ';' + var lines = string.replace(/\s+/g, ' ').split(/\s*;\s*/); + + // loop through.. + for (var i = 0; i < lines.length; i++) { + var line = lines[i].trim(); + + if (line.indexOf('uniform') > -1) { + var splitLine = line.split(' '); + var type = splitLine[1]; + + var name = splitLine[2]; + var size = 1; + + if (name.indexOf('[') > -1) { + // array! + nameSplit = name.split(/\[|]/); + name = nameSplit[0]; + size *= Number(nameSplit[1]); + } + + if (!name.match(maskRegex)) { + uniforms[name] = { + value: defaultValue(type, size), + name: name, + type: type + }; + } + } + } + + return uniforms; +} + +},{"pixi-gl-core":12}],88:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.calculateScreenSpaceMatrix = calculateScreenSpaceMatrix; +exports.calculateNormalizedScreenSpaceMatrix = calculateNormalizedScreenSpaceMatrix; +exports.calculateSpriteMatrix = calculateSpriteMatrix; + +var _math = require('../../../math'); + +/** + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// this returns a matrix that will normalise map filter cords in the filter to screen space +function calculateScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + // let worldTransform = sprite.worldTransform.copy(Matrix.TEMP_MATRIX), + // let texture = {width:1136, height:700};//sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(textureSize.width, textureSize.height); + + return mappedMatrix; +} + +function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + var translateScaleX = textureSize.width / filterArea.width; + var translateScaleY = textureSize.height / filterArea.height; + + mappedMatrix.scale(translateScaleX, translateScaleY); + + return mappedMatrix; +} + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +function calculateSpriteMatrix(outputMatrix, filterArea, textureSize, sprite) { + var orig = sprite._texture.orig; + var mappedMatrix = outputMatrix.set(textureSize.width, 0, 0, textureSize.height, filterArea.x, filterArea.y); + var worldTransform = sprite.worldTransform.copy(_math.Matrix.TEMP_MATRIX); + + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height); + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; +} + +},{"../../../math":70}],89:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Filter2 = require('../Filter'); + +var _Filter3 = _interopRequireDefault(_Filter2); + +var _math = require('../../../../math'); + +var _path = require('path'); + +var _TextureMatrix = require('../../../../textures/TextureMatrix'); + +var _TextureMatrix2 = _interopRequireDefault(_TextureMatrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The SpriteMaskFilter class + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + */ +var SpriteMaskFilter = function (_Filter) { + _inherits(SpriteMaskFilter, _Filter); + + /** + * @param {PIXI.Sprite} sprite - the target sprite + */ + function SpriteMaskFilter(sprite) { + _classCallCheck(this, SpriteMaskFilter); + + var maskMatrix = new _math.Matrix(); + + var _this = _possibleConstructorReturn(this, _Filter.call(this, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n', 'varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n')); + + sprite.renderable = false; + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + return _this; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + */ + + + SpriteMaskFilter.prototype.apply = function apply(filterManager, input, output) { + var maskSprite = this.maskSprite; + var tex = this.maskSprite.texture; + + if (!tex.valid) { + return; + } + if (!tex.transform) { + // margin = 0.0, let it bleed a bit, shader code becomes easier + // assuming that atlas textures were made with 1-pixel padding + tex.transform = new _TextureMatrix2.default(tex, 0.0); + } + tex.transform.update(); + + this.uniforms.mask = tex; + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite).prepend(tex.transform.mapCoord); + this.uniforms.alpha = maskSprite.worldAlpha; + this.uniforms.maskClamp = tex.transform.uClampFrame; + + filterManager.applyFilter(this, input, output); + }; + + return SpriteMaskFilter; +}(_Filter3.default); + +exports.default = SpriteMaskFilter; + +},{"../../../../math":70,"../../../../textures/TextureMatrix":116,"../Filter":86,"path":23}],90:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _RenderTarget = require('../utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _Quad = require('../utils/Quad'); + +var _Quad2 = _interopRequireDefault(_Quad); + +var _math = require('../../../math'); + +var _Shader = require('../../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _filterTransforms = require('../filters/filterTransforms'); + +var filterTransforms = _interopRequireWildcard(_filterTransforms); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @ignore + * @class + */ +var FilterState = +/** + * + */ +function FilterState() { + _classCallCheck(this, FilterState); + + this.renderTarget = null; + this.sourceFrame = new _math.Rectangle(); + this.destinationFrame = new _math.Rectangle(); + this.filters = []; + this.target = null; + this.resolution = 1; +}; + +/** + * @class + * @memberof PIXI + * @extends PIXI.WebGLManager + */ + + +var FilterManager = function (_WebGLManager) { + _inherits(FilterManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function FilterManager(renderer) { + _classCallCheck(this, FilterManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.gl = _this.renderer.gl; + // know about sprites! + _this.quad = new _Quad2.default(_this.gl, renderer.state.attribState); + + _this.shaderCache = {}; + // todo add default! + _this.pool = {}; + + _this.filterData = null; + + _this.managedFilters = []; + return _this; + } + + /** + * Adds a new filter to the manager. + * + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param {PIXI.Filter[]} filters - The filters to apply. + */ + + + FilterManager.prototype.pushFilter = function pushFilter(target, filters) { + var renderer = this.renderer; + + var filterData = this.filterData; + + if (!filterData) { + filterData = this.renderer._activeRenderTarget.filterStack; + + // add new stack + var filterState = new FilterState(); + + filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; + filterState.renderTarget = renderer._activeRenderTarget; + + this.renderer._activeRenderTarget.filterData = filterData = { + index: 0, + stack: [filterState] + }; + + this.filterData = filterData; + } + + // get the current filter state.. + var currentState = filterData.stack[++filterData.index]; + + if (!currentState) { + currentState = filterData.stack[filterData.index] = new FilterState(); + } + + // for now we go off the filter of the first resolution.. + var resolution = filters[0].resolution; + var padding = filters[0].padding | 0; + var targetBounds = target.filterArea || target.getBounds(true); + var sourceFrame = currentState.sourceFrame; + var destinationFrame = currentState.destinationFrame; + + sourceFrame.x = (targetBounds.x * resolution | 0) / resolution; + sourceFrame.y = (targetBounds.y * resolution | 0) / resolution; + sourceFrame.width = (targetBounds.width * resolution | 0) / resolution; + sourceFrame.height = (targetBounds.height * resolution | 0) / resolution; + + if (filterData.stack[0].renderTarget.transform) {// + + // TODO we should fit the rect around the transform.. + } else if (filters[0].autoFit) { + sourceFrame.fit(filterData.stack[0].destinationFrame); + } + + // lets apply the padding After we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + sourceFrame.pad(padding); + + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + + // lets play the padding after we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + + var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); + + currentState.target = target; + currentState.filters = filters; + currentState.resolution = resolution; + currentState.renderTarget = renderTarget; + + // bind the render target to draw the shape in the top corner.. + + renderTarget.setFrame(destinationFrame, sourceFrame); + + // bind the render target + renderer.bindRenderTarget(renderTarget); + renderTarget.clear(); + }; + + /** + * Pops off the filter and applies it. + * + */ + + + FilterManager.prototype.popFilter = function popFilter() { + var filterData = this.filterData; + + var lastState = filterData.stack[filterData.index - 1]; + var currentState = filterData.stack[filterData.index]; + + this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); + + var filters = currentState.filters; + + if (filters.length === 1) { + filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false, currentState); + this.freePotRenderTarget(currentState.renderTarget); + } else { + var flip = currentState.renderTarget; + var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, currentState.resolution); + + flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + // finally lets clear the render target before drawing to it.. + flop.clear(); + + var i = 0; + + for (i = 0; i < filters.length - 1; ++i) { + filters[i].apply(this, flip, flop, true, currentState); + + var t = flip; + + flip = flop; + flop = t; + } + + filters[i].apply(this, flip, lastState.renderTarget, false, currentState); + + this.freePotRenderTarget(flip); + this.freePotRenderTarget(flop); + } + + filterData.index--; + + if (filterData.index === 0) { + this.filterData = null; + } + }; + + /** + * Draws a filter. + * + * @param {PIXI.Filter} filter - The filter to draw. + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + FilterManager.prototype.applyFilter = function applyFilter(filter, input, output, clear) { + var renderer = this.renderer; + var gl = renderer.gl; + + var shader = filter.glShaders[renderer.CONTEXT_UID]; + + // cacheing.. + if (!shader) { + if (filter.glShaderKey) { + shader = this.shaderCache[filter.glShaderKey]; + + if (!shader) { + shader = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + + filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = shader; + this.managedFilters.push(filter); + } + } else { + shader = filter.glShaders[renderer.CONTEXT_UID] = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + this.managedFilters.push(filter); + } + + // TODO - this only needs to be done once? + renderer.bindVao(null); + + this.quad.initVao(shader); + } + + renderer.bindVao(this.quad.vao); + + renderer.bindRenderTarget(output); + + if (clear) { + gl.disable(gl.SCISSOR_TEST); + renderer.clear(); // [1, 1, 1, 1]); + gl.enable(gl.SCISSOR_TEST); + } + + // in case the render target is being masked using a scissor rect + if (output === renderer.maskManager.scissorRenderTarget) { + renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); + } + + renderer.bindShader(shader); + + // free unit 0 for us, doesn't matter what was there + // don't try to restore it, because syncUniforms can upload it to another slot + // and it'll be a problem + var tex = this.renderer.emptyTextures[0]; + + this.renderer.boundTextures[0] = tex; + // this syncs the PixiJS filters uniforms with glsl uniforms + this.syncUniforms(shader, filter); + + renderer.state.setBlendMode(filter.blendMode); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, input.texture.texture); + + this.quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + }; + + /** + * Uploads the uniforms of the filter. + * + * @param {GLShader} shader - The underlying gl shader. + * @param {PIXI.Filter} filter - The filter we are synchronizing. + */ + + + FilterManager.prototype.syncUniforms = function syncUniforms(shader, filter) { + var uniformData = filter.uniformData; + var uniforms = filter.uniforms; + + // 0 is reserved for the PixiJS texture so we start at 1! + var textureCount = 1; + var currentState = void 0; + + // filterArea and filterClamp that are handled by FilterManager directly + // they must not appear in uniformData + + if (shader.uniforms.filterArea) { + currentState = this.filterData.stack[this.filterData.index]; + + var filterArea = shader.uniforms.filterArea; + + filterArea[0] = currentState.renderTarget.size.width; + filterArea[1] = currentState.renderTarget.size.height; + filterArea[2] = currentState.sourceFrame.x; + filterArea[3] = currentState.sourceFrame.y; + + shader.uniforms.filterArea = filterArea; + } + + // use this to clamp displaced texture coords so they belong to filterArea + // see displacementFilter fragment shader for an example + if (shader.uniforms.filterClamp) { + currentState = currentState || this.filterData.stack[this.filterData.index]; + + var filterClamp = shader.uniforms.filterClamp; + + filterClamp[0] = 0; + filterClamp[1] = 0; + filterClamp[2] = (currentState.sourceFrame.width - 1) / currentState.renderTarget.size.width; + filterClamp[3] = (currentState.sourceFrame.height - 1) / currentState.renderTarget.size.height; + + shader.uniforms.filterClamp = filterClamp; + } + + // TODO Cacheing layer.. + for (var i in uniformData) { + var type = uniformData[i].type; + + if (type === 'sampler2d' && uniforms[i] !== 0) { + if (uniforms[i].baseTexture) { + shader.uniforms[i] = this.renderer.bindTexture(uniforms[i].baseTexture, textureCount); + } else { + shader.uniforms[i] = textureCount; + + // TODO + // this is helpful as renderTargets can also be set. + // Although thinking about it, we could probably + // make the filter texture cache return a RenderTexture + // rather than a renderTarget + var gl = this.renderer.gl; + + this.renderer.boundTextures[textureCount] = this.renderer.emptyTextures[textureCount]; + gl.activeTexture(gl.TEXTURE0 + textureCount); + + uniforms[i].texture.bind(); + } + + textureCount++; + } else if (type === 'mat3') { + // check if its PixiJS matrix.. + if (uniforms[i].a !== undefined) { + shader.uniforms[i] = uniforms[i].toArray(true); + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (type === 'vec2') { + // check if its a point.. + if (uniforms[i].x !== undefined) { + var val = shader.uniforms[i] || new Float32Array(2); + + val[0] = uniforms[i].x; + val[1] = uniforms[i].y; + shader.uniforms[i] = val; + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (type === 'float') { + if (shader.uniforms.data[i].value !== uniformData[i]) { + shader.uniforms[i] = uniforms[i]; + } + } else { + shader.uniforms[i] = uniforms[i]; + } + } + }; + + /** + * Gets a render target from the pool, or creates a new one. + * + * @param {boolean} clear - Should we clear the render texture when we get it? + * @param {number} resolution - The resolution of the target. + * @return {PIXI.RenderTarget} The new render target + */ + + + FilterManager.prototype.getRenderTarget = function getRenderTarget(clear, resolution) { + var currentState = this.filterData.stack[this.filterData.index]; + var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution); + + renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + return renderTarget; + }; + + /** + * Returns a render target to the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The render target to return. + */ + + + FilterManager.prototype.returnRenderTarget = function returnRenderTarget(renderTarget) { + this.freePotRenderTarget(renderTarget); + }; + + /** + * Calculates the mapped matrix. + * + * TODO playing around here.. this is temporary - (will end up in the shader) + * this returns a matrix that will normalise map filter cords in the filter to screen space + * + * @param {PIXI.Matrix} outputMatrix - the matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateScreenSpaceMatrix = function calculateScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); + }; + + /** + * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function calculateNormalizedScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); + }; + + /** + * This will map the filter coord so that a texture can be used based on the transform of a sprite + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateSpriteMatrix = function calculateSpriteMatrix(outputMatrix, sprite) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); + }; + + /** + * Destroys this Filter Manager. + * + * @param {boolean} [contextLost=false] context was lost, do not free shaders + * + */ + + + FilterManager.prototype.destroy = function destroy() { + var contextLost = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + var renderer = this.renderer; + var filters = this.managedFilters; + + for (var i = 0; i < filters.length; i++) { + if (!contextLost) { + filters[i].glShaders[renderer.CONTEXT_UID].destroy(); + } + delete filters[i].glShaders[renderer.CONTEXT_UID]; + } + + this.shaderCache = {}; + if (!contextLost) { + this.emptyPool(); + } else { + this.pool = {}; + } + }; + + /** + * Gets a Power-of-Two render texture. + * + * TODO move to a seperate class could be on renderer? + * also - could cause issue with multiple contexts? + * + * @private + * @param {WebGLRenderingContext} gl - The webgl rendering context + * @param {number} minWidth - The minimum width of the render target. + * @param {number} minHeight - The minimum height of the render target. + * @param {number} resolution - The resolution of the render target. + * @return {PIXI.RenderTarget} The new render target. + */ + + + FilterManager.prototype.getPotRenderTarget = function getPotRenderTarget(gl, minWidth, minHeight, resolution) { + // TODO you could return a bigger texture if there is not one in the pool? + minWidth = _bitTwiddle2.default.nextPow2(minWidth * resolution); + minHeight = _bitTwiddle2.default.nextPow2(minHeight * resolution); + + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + if (!this.pool[key]) { + this.pool[key] = []; + } + + var renderTarget = this.pool[key].pop(); + + // creating render target will cause texture to be bound! + if (!renderTarget) { + // temporary bypass cache.. + var tex = this.renderer.boundTextures[0]; + + gl.activeTexture(gl.TEXTURE0); + + // internally - this will cause a texture to be bound.. + renderTarget = new _RenderTarget2.default(gl, minWidth, minHeight, null, 1); + + // set the current one back + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + } + + // manually tweak the resolution... + // this will not modify the size of the frame buffer, just its resolution. + renderTarget.resolution = resolution; + renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution; + renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution; + + return renderTarget; + }; + + /** + * Empties the texture pool. + * + */ + + + FilterManager.prototype.emptyPool = function emptyPool() { + for (var i in this.pool) { + var textures = this.pool[i]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + + this.pool = {}; + }; + + /** + * Frees a render target back into the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free + */ + + + FilterManager.prototype.freePotRenderTarget = function freePotRenderTarget(renderTarget) { + var minWidth = renderTarget.size.width * renderTarget.resolution; + var minHeight = renderTarget.size.height * renderTarget.resolution; + var key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + + this.pool[key].push(renderTarget); + }; + + return FilterManager; +}(_WebGLManager3.default); + +exports.default = FilterManager; + +},{"../../../Shader":44,"../../../math":70,"../filters/filterTransforms":88,"../utils/Quad":95,"../utils/RenderTarget":96,"./WebGLManager":93,"bit-twiddle":1}],91:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _SpriteMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); + +var _SpriteMaskFilter2 = _interopRequireDefault(_SpriteMaskFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var MaskManager = function (_WebGLManager) { + _inherits(MaskManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function MaskManager(renderer) { + _classCallCheck(this, MaskManager); + + // TODO - we don't need both! + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.scissor = false; + _this.scissorData = null; + _this.scissorRenderTarget = null; + + _this.enableScissor = true; + + _this.alphaMaskPool = []; + _this.alphaMaskIndex = 0; + return _this; + } + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushMask = function pushMask(target, maskData) { + // TODO the root check means scissor rect will not + // be used on render textures more info here: + // https://github.com/pixijs/pixi.js/pull/3545 + + if (maskData.texture) { + this.pushSpriteMask(target, maskData); + } else if (this.enableScissor && !this.scissor && this.renderer._activeRenderTarget.root && !this.renderer.stencilManager.stencilMaskStack.length && maskData.isFastRect()) { + var matrix = maskData.worldTransform; + + var rot = Math.atan2(matrix.b, matrix.a); + + // use the nearest degree! + rot = Math.round(rot * (180 / Math.PI)); + + if (rot % 90) { + this.pushStencilMask(maskData); + } else { + this.pushScissorMask(target, maskData); + } + } else { + this.pushStencilMask(maskData); + } + }; + + /** + * Removes the last mask from the mask stack and doesn't return it. + * + * @param {PIXI.DisplayObject} target - Display Object to pop the mask from + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.popMask = function popMask(target, maskData) { + if (maskData.texture) { + this.popSpriteMask(target, maskData); + } else if (this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length) { + this.popScissorMask(target, maskData); + } else { + this.popStencilMask(target, maskData); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.RenderTarget} target - Display Object to push the sprite mask to + * @param {PIXI.Sprite} maskData - Sprite to be used as the mask + */ + + + MaskManager.prototype.pushSpriteMask = function pushSpriteMask(target, maskData) { + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new _SpriteMaskFilter2.default(maskData)]; + } + + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskData; + + // TODO - may cause issues! + target.filterArea = maskData.getBounds(true); + + this.renderer.filterManager.pushFilter(target, alphaMaskFilter); + + this.alphaMaskIndex++; + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popSpriteMask = function popSpriteMask() { + this.renderer.filterManager.popFilter(); + this.alphaMaskIndex--; + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushStencilMask = function pushStencilMask(maskData) { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.pushStencil(maskData); + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popStencilMask = function popStencilMask() { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.popStencil(); + }; + + /** + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushScissorMask = function pushScissorMask(target, maskData) { + maskData.renderable = true; + + var renderTarget = this.renderer._activeRenderTarget; + + var bounds = maskData.getBounds(); + + bounds.fit(renderTarget.size); + maskData.renderable = false; + + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + + var resolution = this.renderer.resolution; + + this.renderer.gl.scissor(bounds.x * resolution, (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution, bounds.width * resolution, bounds.height * resolution); + + this.scissorRenderTarget = renderTarget; + this.scissorData = maskData; + this.scissor = true; + }; + + /** + * + * + */ + + + MaskManager.prototype.popScissorMask = function popScissorMask() { + this.scissorRenderTarget = null; + this.scissorData = null; + this.scissor = false; + + // must be scissor! + var gl = this.renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + }; + + return MaskManager; +}(_WebGLManager3.default); + +exports.default = MaskManager; + +},{"../filters/spriteMask/SpriteMaskFilter":89,"./WebGLManager":93}],92:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var StencilManager = function (_WebGLManager) { + _inherits(StencilManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function StencilManager(renderer) { + _classCallCheck(this, StencilManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.stencilMaskStack = null; + return _this; + } + + /** + * Changes the mask stack that is used by this manager. + * + * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack + */ + + + StencilManager.prototype.setMaskStack = function setMaskStack(stencilMaskStack) { + this.stencilMaskStack = stencilMaskStack; + + var gl = this.renderer.gl; + + if (stencilMaskStack.length === 0) { + gl.disable(gl.STENCIL_TEST); + } else { + gl.enable(gl.STENCIL_TEST); + } + }; + + /** + * Applies the Mask and adds it to the current stencil stack. @alvin + * + * @param {PIXI.Graphics} graphics - The mask + */ + + + StencilManager.prototype.pushStencil = function pushStencil(graphics) { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + this.renderer._activeRenderTarget.attachStencilBuffer(); + + var gl = this.renderer.gl; + var prevMaskCount = this.stencilMaskStack.length; + + if (prevMaskCount === 0) { + gl.enable(gl.STENCIL_TEST); + } + + this.stencilMaskStack.push(graphics); + + // Increment the refference stencil value where the new mask overlaps with the old ones. + gl.colorMask(false, false, false, false); + gl.stencilFunc(gl.EQUAL, prevMaskCount, this._getBitwiseMask()); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + this.renderer.plugins.graphics.render(graphics); + + this._useCurrent(); + }; + + /** + * Removes the last mask from the stencil stack. @alvin + */ + + + StencilManager.prototype.popStencil = function popStencil() { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + var gl = this.renderer.gl; + var graphics = this.stencilMaskStack.pop(); + + if (this.stencilMaskStack.length === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.clearStencil(0); + } else { + // Decrement the refference stencil value where the popped mask overlaps with the other ones + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + this.renderer.plugins.graphics.render(graphics); + + this._useCurrent(); + } + }; + + /** + * Setup renderer to use the current stencil data. + */ + + + StencilManager.prototype._useCurrent = function _useCurrent() { + var gl = this.renderer.gl; + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.EQUAL, this.stencilMaskStack.length, this._getBitwiseMask()); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; + + /** + * Fill 1s equal to the number of acitve stencil masks. + * + * @return {number} The bitwise mask. + */ + + + StencilManager.prototype._getBitwiseMask = function _getBitwiseMask() { + return (1 << this.stencilMaskStack.length) - 1; + }; + + /** + * Destroys the mask stack. + * + */ + + + StencilManager.prototype.destroy = function destroy() { + _WebGLManager3.default.prototype.destroy.call(this); + + this.stencilMaskStack.stencilStack = null; + }; + + return StencilManager; +}(_WebGLManager3.default); + +exports.default = StencilManager; + +},{"./WebGLManager":93}],93:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var WebGLManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function WebGLManager(renderer) { + _classCallCheck(this, WebGLManager); + + /** + * The renderer this manager works for. + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + this.renderer.on('context', this.onContextChange, this); + } + + /** + * Generic method called when there is a WebGL context change. + * + */ + + + WebGLManager.prototype.onContextChange = function onContextChange() {} + // do some codes init! + + + /** + * Generic destroy methods to be overridden by the subclass + * + */ + ; + + WebGLManager.prototype.destroy = function destroy() { + this.renderer.off('context', this.onContextChange, this); + + this.renderer = null; + }; + + return WebGLManager; +}(); + +exports.default = WebGLManager; + +},{}],94:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('../managers/WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Base for a common object renderer that can be used as a system renderer plugin. + * + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var ObjectRenderer = function (_WebGLManager) { + _inherits(ObjectRenderer, _WebGLManager); + + function ObjectRenderer() { + _classCallCheck(this, ObjectRenderer); + + return _possibleConstructorReturn(this, _WebGLManager.apply(this, arguments)); + } + + /** + * Starts the renderer and sets the shader + * + */ + ObjectRenderer.prototype.start = function start() {} + // set the shader.. + + + /** + * Stops the renderer + * + */ + ; + + ObjectRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Stub method for rendering content and emptying the current batch. + * + */ + + + ObjectRenderer.prototype.flush = function flush() {} + // flush! + + + /** + * Renders an object + * + * @param {PIXI.DisplayObject} object - The object to render. + */ + ; + + ObjectRenderer.prototype.render = function render(object) // eslint-disable-line no-unused-vars + { + // render the object + }; + + return ObjectRenderer; +}(_WebGLManager3.default); + +exports.default = ObjectRenderer; + +},{"../managers/WebGLManager":93}],95:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a quad + * + * @class + * @memberof PIXI + */ +var Quad = function () { + /** + * @param {WebGLRenderingContext} gl - The gl context for this quad to use. + * @param {object} state - TODO: Description + */ + function Quad(gl, state) { + _classCallCheck(this, Quad); + + /** + * the current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]); + + /** + * The Uvs of the quad + * + * @member {Float32Array} + */ + this.uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + this.interleaved = new Float32Array(8 * 2); + + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(1); + + /** + * The vertex buffer + * + * @member {glCore.GLBuffer} + */ + this.vertexBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW); + + /** + * The index buffer + * + * @member {glCore.GLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + /** + * The vertex array object + * + * @member {glCore.VertexArrayObject} + */ + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, state); + } + + /** + * Initialises the vaos and uses the shader. + * + * @param {PIXI.Shader} shader - the shader to use + */ + + + Quad.prototype.initVao = function initVao(shader) { + this.vao.clear().addIndex(this.indexBuffer).addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0).addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4); + }; + + /** + * Maps two Rectangle to the quad. + * + * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle + * @param {PIXI.Rectangle} destinationFrame - the second rectangle + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.map = function map(targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + + this.uvs[0] = x; + this.uvs[1] = y; + + this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; + + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; + + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; + + x = destinationFrame.x; + y = destinationFrame.y; + + this.vertices[0] = x; + this.vertices[1] = y; + + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + + return this; + }; + + /** + * Binds the buffer and uploads the data + * + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.upload = function upload() { + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + this.vertexBuffer.upload(this.interleaved); + + return this; + }; + + /** + * Removes this quad from WebGL + */ + + + Quad.prototype.destroy = function destroy() { + var gl = this.gl; + + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.indexBuffer); + }; + + return Quad; +}(); + +exports.default = Quad; + +},{"../../../utils/createIndicesForQuads":123,"pixi-gl-core":12}],96:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../../../math'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _pixiGlCore = require('pixi-gl-core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var RenderTarget = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {number} [width=0] - the horizontal range of the filter + * @param {number} [height=0] - the vertical range of the filter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The current resolution / device pixel ratio + * @param {boolean} [root=false] - Whether this object is the root element or not + */ + function RenderTarget(gl, width, height, scaleMode, resolution, root) { + _classCallCheck(this, RenderTarget); + + // TODO Resolution could go here ( eg low res blurs ) + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // next time to create a frame buffer and texture + + /** + * A frame buffer + * + * @member {PIXI.glCore.GLFramebuffer} + */ + this.frameBuffer = null; + + /** + * The texture + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The background colour of this render target, as an array of [r,g,b,a] values + * + * @member {number[]} + */ + this.clearColor = [0, 0, 0, 0]; + + /** + * The size of the object as a rectangle + * + * @member {PIXI.Rectangle} + */ + this.size = new _math.Rectangle(0, 0, 1, 1); + + /** + * The current resolution / device pixel ratio + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The projection matrix + * + * @member {PIXI.Matrix} + */ + this.projectionMatrix = new _math.Matrix(); + + /** + * The object's transform + * + * @member {PIXI.Matrix} + */ + this.transform = null; + + /** + * The frame. + * + * @member {PIXI.Rectangle} + */ + this.frame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.defaultFrame = new _math.Rectangle(); + this.destinationFrame = null; + this.sourceFrame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.stencilBuffer = null; + + /** + * The data structure for the stencil masks + * + * @member {PIXI.Graphics[]} + */ + this.stencilMaskStack = []; + + /** + * Stores filter data for the render target + * + * @member {object[]} + */ + this.filterData = null; + + /** + * The scale mode. + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Whether this object is the root element or not + * + * @member {boolean} + */ + this.root = root; + + if (!this.root) { + this.frameBuffer = _pixiGlCore.GLFramebuffer.createRGBA(gl, 100, 100); + + if (this.scaleMode === _const.SCALE_MODES.NEAREST) { + this.frameBuffer.texture.enableNearestScaling(); + } else { + this.frameBuffer.texture.enableLinearScaling(); + } + /* + A frame buffer needs a target to render to.. + create a texture and bind it attach it to the framebuffer.. + */ + + // this is used by the base texture + this.texture = this.frameBuffer.texture; + } else { + // make it a null framebuffer.. + this.frameBuffer = new _pixiGlCore.GLFramebuffer(gl, 100, 100); + this.frameBuffer.framebuffer = null; + } + + this.setFrame(); + + this.resize(width, height); + } + + /** + * Clears the filter texture. + * + * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer + */ + + + RenderTarget.prototype.clear = function clear(clearColor) { + var cc = clearColor || this.clearColor; + + this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a); + }; + + /** + * Binds the stencil buffer. + * + */ + + + RenderTarget.prototype.attachStencilBuffer = function attachStencilBuffer() { + // TODO check if stencil is done? + /** + * The stencil buffer is used for masking in pixi + * lets create one and then add attach it to the framebuffer.. + */ + if (!this.root) { + this.frameBuffer.enableStencil(); + } + }; + + /** + * Sets the frame of the render target. + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.setFrame = function setFrame(destinationFrame, sourceFrame) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || this.destinationFrame; + }; + + /** + * Binds the buffers and initialises the viewport. + * + */ + + + RenderTarget.prototype.activate = function activate() { + // TOOD refactor usage of frame.. + var gl = this.gl; + + // make sure the texture is unbound! + this.frameBuffer.bind(); + + this.calculateProjection(this.destinationFrame, this.sourceFrame); + + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + + // TODO add a check as them may be the same! + if (this.destinationFrame !== this.sourceFrame) { + gl.enable(gl.SCISSOR_TEST); + gl.scissor(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + } else { + gl.disable(gl.SCISSOR_TEST); + } + + // TODO - does not need to be updated all the time?? + gl.viewport(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + }; + + /** + * Updates the projection matrix based on a projection frame (which is a rectangle) + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.calculateProjection = function calculateProjection(destinationFrame, sourceFrame) { + var pm = this.projectionMatrix; + + sourceFrame = sourceFrame || destinationFrame; + + pm.identity(); + + // TODO: make dest scale source + if (!this.root) { + pm.a = 1 / destinationFrame.width * 2; + pm.d = 1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = -1 - sourceFrame.y * pm.d; + } else { + pm.a = 1 / destinationFrame.width * 2; + pm.d = -1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = 1 - sourceFrame.y * pm.d; + } + }; + + /** + * Resizes the texture to the specified width and height + * + * @param {number} width - the new width of the texture + * @param {number} height - the new height of the texture + */ + + + RenderTarget.prototype.resize = function resize(width, height) { + width = width | 0; + height = height | 0; + + if (this.size.width === width && this.size.height === height) { + return; + } + + this.size.width = width; + this.size.height = height; + + this.defaultFrame.width = width; + this.defaultFrame.height = height; + + this.frameBuffer.resize(width * this.resolution, height * this.resolution); + + var projectionFrame = this.frame || this.size; + + this.calculateProjection(projectionFrame); + }; + + /** + * Destroys the render target. + * + */ + + + RenderTarget.prototype.destroy = function destroy() { + this.frameBuffer.destroy(); + + this.frameBuffer = null; + this.texture = null; + }; + + return RenderTarget; +}(); + +exports.default = RenderTarget; + +},{"../../../const":46,"../../../math":70,"../../../settings":101,"pixi-gl-core":12}],97:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = checkMaxIfStatmentsInShader; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['precision mediump float;', 'void main(void){', 'float test = 0.1;', '%forloop%', 'gl_FragColor = vec4(0.0);', '}'].join('\n'); + +function checkMaxIfStatmentsInShader(maxIfs, gl) { + var createTempContext = !gl; + + if (maxIfs === 0) { + throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); + } + + if (createTempContext) { + var tinyCanvas = document.createElement('canvas'); + + tinyCanvas.width = 1; + tinyCanvas.height = 1; + + gl = _pixiGlCore2.default.createContext(tinyCanvas); + } + + var shader = gl.createShader(gl.FRAGMENT_SHADER); + + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = maxIfs / 2 | 0; + } else { + // valid! + break; + } + } + + if (createTempContext) { + // get rid of context + if (gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').loseContext(); + } + } + + return maxIfs; +} + +function generateIfTestSrc(maxIfs) { + var src = ''; + + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxIfs - 1) { + src += 'if(test == ' + i + '.0){}'; + } + } + + return src; +} + +},{"pixi-gl-core":12}],98:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLBlendModesToPixi; + +var _const = require('../../../const'); + +/** + * Maps gl blend combinations to WebGL. + * + * @memberof PIXI + * @function mapWebGLBlendModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapWebGLBlendModesToPixi(gl) { + var array = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[_const.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD] = [gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + array[_const.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + // not-premultiplied blend modes + array[_const.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.DST_ALPHA, gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + + return array; +} + +},{"../../../const":46}],99:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLDrawModesToPixi; + +var _const = require('../../../const'); + +/** + * Generic Mask Stack data structure. + * + * @memberof PIXI + * @function mapWebGLDrawModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {object} [object={}] - The object to map into + * @return {object} The mapped draw modes. + */ +function mapWebGLDrawModesToPixi(gl) { + var object = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + object[_const.DRAW_MODES.POINTS] = gl.POINTS; + object[_const.DRAW_MODES.LINES] = gl.LINES; + object[_const.DRAW_MODES.LINE_LOOP] = gl.LINE_LOOP; + object[_const.DRAW_MODES.LINE_STRIP] = gl.LINE_STRIP; + object[_const.DRAW_MODES.TRIANGLES] = gl.TRIANGLES; + object[_const.DRAW_MODES.TRIANGLE_STRIP] = gl.TRIANGLE_STRIP; + object[_const.DRAW_MODES.TRIANGLE_FAN] = gl.TRIANGLE_FAN; + + return object; +} + +},{"../../../const":46}],100:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = validateContext; +function validateContext(gl) { + var attributes = gl.getContextAttributes(); + + // this is going to be fairly simple for now.. but at least we have room to grow! + if (!attributes.stencil) { + /* eslint-disable no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable no-console */ + } +} + +},{}],101:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _maxRecommendedTextures = require('./utils/maxRecommendedTextures'); + +var _maxRecommendedTextures2 = _interopRequireDefault(_maxRecommendedTextures); + +var _canUploadSameBuffer = require('./utils/canUploadSameBuffer'); + +var _canUploadSameBuffer2 = _interopRequireDefault(_canUploadSameBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * User's customizable globals for overriding the default PIXI settings, such + * as a renderer's default resolution, framerate, float percision, etc. + * @example + * // Use the native window resolution as the default resolution + * // will support high-density displays when rendering + * PIXI.settings.RESOLUTION = window.devicePixelRatio. + * + * // Disable interpolation when scaling, will make texture be pixelated + * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; + * @namespace PIXI.settings + */ +exports.default = { + + /** + * Target frames per millisecond. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 0.06 + */ + TARGET_FPMS: 0.06, + + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * + * @static + * @memberof PIXI.settings + * @type {boolean} + * @default true + */ + MIPMAP_TEXTURES: true, + + /** + * Default resolution / device pixel ratio of the renderer. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + RESOLUTION: 1, + + /** + * Default filter resolution. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + FILTER_RESOLUTION: 1, + + /** + * The maximum textures that this device supports. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 32 + */ + SPRITE_MAX_TEXTURES: (0, _maxRecommendedTextures2.default)(32), + + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + + /** + * The prefix that denotes a URL is for a retina asset. + * + * @static + * @memberof PIXI.settings + * @type {RegExp} + * @example `@2x` + * @default /@([0-9\.]+)x/ + */ + RETINA_PREFIX: /@([0-9\.]+)x/, + + /** + * The default render options if none are supplied to {@link PIXI.WebGLRenderer} + * or {@link PIXI.CanvasRenderer}. + * + * @static + * @constant + * @memberof PIXI.settings + * @type {object} + * @property {HTMLCanvasElement} view=null + * @property {number} resolution=1 + * @property {boolean} antialias=false + * @property {boolean} forceFXAA=false + * @property {boolean} autoResize=false + * @property {boolean} transparent=false + * @property {number} backgroundColor=0x000000 + * @property {boolean} clearBeforeRender=true + * @property {boolean} preserveDrawingBuffer=false + * @property {boolean} roundPixels=false + * @property {number} width=800 + * @property {number} height=600 + * @property {boolean} legacy=false + */ + RENDER_OPTIONS: { + view: null, + antialias: false, + forceFXAA: false, + autoResize: false, + transparent: false, + backgroundColor: 0x000000, + clearBeforeRender: true, + preserveDrawingBuffer: false, + roundPixels: false, + width: 800, + height: 600, + legacy: false + }, + + /** + * Default transform type. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.TRANSFORM_MODE} + * @default PIXI.TRANSFORM_MODE.STATIC + */ + TRANSFORM_MODE: 0, + + /** + * Default Garbage Collection mode. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO + */ + GC_MODE: 0, + + /** + * Default Garbage Collection max idle. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 3600 + */ + GC_MAX_IDLE: 60 * 60, + + /** + * Default Garbage Collection maximum check count. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 600 + */ + GC_MAX_CHECK_COUNT: 60 * 10, + + /** + * Default wrap modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP + */ + WRAP_MODE: 0, + + /** + * The scale modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR + */ + SCALE_MODE: 0, + + /** + * Default specify float precision in vertex shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.HIGH + */ + PRECISION_VERTEX: 'highp', + + /** + * Default specify float precision in fragment shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM + */ + PRECISION_FRAGMENT: 'mediump', + + /** + * Can we upload the same buffer in a single frame? + * + * @static + * @constant + * @memberof PIXI + * @type {boolean} + */ + CAN_UPLOAD_SAME_BUFFER: (0, _canUploadSameBuffer2.default)() + +}; + +},{"./utils/canUploadSameBuffer":122,"./utils/maxRecommendedTextures":127}],102:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new _math.Point(); + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = new PIXI.Sprite.fromImage('assets/image.png'); + * ``` + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Sprite = function (_Container) { + _inherits(Sprite, _Container); + + /** + * @param {PIXI.Texture} texture - The texture for this sprite + */ + function Sprite(texture) { + _classCallCheck(this, Sprite); + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + * @private + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this._anchor = new _math.ObservablePoint(_this._onAnchorUpdate, _this); + + /** + * The texture that the sprite is using + * + * @private + * @member {PIXI.Texture} + */ + _this._texture = null; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = null; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * The shader that will be used to render the sprite. Set to null to remove a current shader. + * + * @member {PIXI.Filter|PIXI.Shader} + */ + _this.shader = null; + + /** + * An internal cached value of the tint. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this.cachedTint = 0xFFFFFF; + + // call texture setter + _this.texture = texture || _Texture2.default.EMPTY; + + /** + * this is used to store the vertex data of the sprite (basically a quad) + * + * @private + * @member {Float32Array} + */ + _this.vertexData = new Float32Array(8); + + /** + * This is used to calculate the bounds of the object IF it is a trimmed sprite + * + * @private + * @member {Float32Array} + */ + _this.vertexTrimmedData = null; + + _this._transformID = -1; + _this._textureID = -1; + + _this._transformTrimmedID = -1; + _this._textureTrimmedID = -1; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * + * @member {string} + * @default 'sprite' + */ + _this.pluginName = 'sprite'; + return _this; + } + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Sprite.prototype._onTextureUpdate = function _onTextureUpdate() { + this._textureID = -1; + this._textureTrimmedID = -1; + this.cachedTint = 0xFFFFFF; + + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = (0, _utils.sign)(this.scale.x) * this._width / this._texture.orig.width; + } + + if (this._height) { + this.scale.y = (0, _utils.sign)(this.scale.y) * this._height / this._texture.orig.height; + } + }; + + /** + * Called when the anchor position updates. + * + * @private + */ + + + Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate() { + this._transformID = -1; + this._transformTrimmedID = -1; + }; + + /** + * calculates worldTransform * vertices, store it in vertexData + */ + + + Sprite.prototype.calculateVertices = function calculateVertices() { + if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) { + return; + } + + this._transformID = this.transform._worldID; + this._textureID = this._texture._updateID; + + // set the vertex data + + var texture = this._texture; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var anchor = this._anchor; + + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - anchor._x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - anchor._y * orig.height; + h0 = h1 + trim.height; + } else { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData + * This is used to ensure that the true width and height of a trimmed texture is respected + */ + + + Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices() { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { + return; + } + + this._transformTrimmedID = this.transform._worldID; + this._textureTrimmedID = this._texture._updateID; + + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + var anchor = this._anchor; + + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + + var w1 = -anchor._x * orig.width; + var w0 = w1 + orig.width; + + var h1 = -anchor._y * orig.height; + var h0 = h1 + orig.height; + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use. + */ + + + Sprite.prototype._renderWebGL = function _renderWebGL(renderer) { + this.calculateVertices(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Sprite.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Updates the bounds of the sprite. + * + * @private + */ + + + Sprite.prototype._calculateBounds = function _calculateBounds() { + var trim = this._texture.trim; + var orig = this._texture.orig; + + // First lets check to see if the current texture has a trim.. + if (!trim || trim.width === orig.width && trim.height === orig.height) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + Sprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._texture.orig.width * -this._anchor._x; + this._bounds.minY = this._texture.orig.height * -this._anchor._y; + this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x); + this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._y); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _Container.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Tests if a point is inside this sprite + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Sprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + y1 = -height * this.anchor.y; + + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + Sprite.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + this._anchor = null; + + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + + this._texture.destroy(!!destroyBaseTexture); + } + + this._texture = null; + this.shader = null; + }; + + // some helper functions.. + + /** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Sprite} The newly created sprite + */ + + + Sprite.from = function from(source) { + return new Sprite(_Texture2.default.from(source)); + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId + */ + + + Sprite.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return new Sprite(texture); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id + */ + + + Sprite.fromImage = function fromImage(imageId, crossorigin, scaleMode) { + return new Sprite(_Texture2.default.fromImage(imageId, crossorigin, scaleMode)); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Sprite, [{ + key: 'width', + get: function get() { + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._anchor.copy(value); + } + + /** + * The tint applied to the sprite. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + } + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + */ + + }, { + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + this.cachedTint = 0xFFFFFF; + + this._textureID = -1; + this._textureTrimmedID = -1; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + }]); + + return Sprite; +}(_Container3.default); + +exports.default = Sprite; + +},{"../const":46,"../display/Container":48,"../math":70,"../textures/Texture":115,"../utils":125}],103:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +var _math = require('../../math'); + +var _CanvasTinter = require('./CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var canvasRenderWorldTransform = new _math.Matrix(); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasSpriteRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + */ + +var CanvasSpriteRenderer = function () { + /** + * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for. + */ + function CanvasSpriteRenderer(renderer) { + _classCallCheck(this, CanvasSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + CanvasSpriteRenderer.prototype.render = function render(sprite) { + var texture = sprite._texture; + var renderer = this.renderer; + + var width = texture._frame.width; + var height = texture._frame.height; + + var wt = sprite.transform.worldTransform; + var dx = 0; + var dy = 0; + + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) { + return; + } + + renderer.setBlendMode(sprite.blendMode); + + // Ignore null sources + if (texture.valid) { + renderer.context.globalAlpha = sprite.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture + var smoothingEnabled = texture.baseTexture.scaleMode === _const.SCALE_MODES.LINEAR; + + if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) { + renderer.context[renderer.smoothProperty] = smoothingEnabled; + } + + if (texture.trim) { + dx = texture.trim.width / 2 + texture.trim.x - sprite.anchor.x * texture.orig.width; + dy = texture.trim.height / 2 + texture.trim.y - sprite.anchor.y * texture.orig.height; + } else { + dx = (0.5 - sprite.anchor.x) * texture.orig.width; + dy = (0.5 - sprite.anchor.y) * texture.orig.height; + } + + if (texture.rotate) { + wt.copy(canvasRenderWorldTransform); + wt = canvasRenderWorldTransform; + _math.GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); + // the anchor has already been applied above, so lets set it to zero + dx = 0; + dy = 0; + } + + dx -= width / 2; + dy -= height / 2; + + // Allow for pixel rounding + if (renderer.roundPixels) { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution | 0, wt.ty * renderer.resolution | 0); + + dx = dx | 0; + dy = dy | 0; + } else { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution, wt.ty * renderer.resolution); + } + + var resolution = texture.baseTexture.resolution; + + if (sprite.tint !== 0xFFFFFF) { + if (sprite.cachedTint !== sprite.tint || sprite.tintedTexture.tintId !== sprite._texture._updateID) { + sprite.cachedTint = sprite.tint; + + // TODO clean up caching - how to clean up the caches? + sprite.tintedTexture = _CanvasTinter2.default.getTintedTexture(sprite, sprite.tint); + } + + renderer.context.drawImage(sprite.tintedTexture, 0, 0, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } else { + renderer.context.drawImage(texture.baseTexture.source, texture._frame.x * resolution, texture._frame.y * resolution, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } + } + }; + + /** + * destroy the sprite object. + * + */ + + + CanvasSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasSpriteRenderer; +}(); + +exports.default = CanvasSpriteRenderer; + + +_CanvasRenderer2.default.registerPlugin('sprite', CanvasSpriteRenderer); + +},{"../../const":46,"../../math":70,"../../renderers/canvas/CanvasRenderer":77,"./CanvasTinter":104}],104:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class + * @memberof PIXI + */ +var CanvasTinter = { + /** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Sprite} sprite - the sprite to tint + * @param {number} color - the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ + getTintedTexture: function getTintedTexture(sprite, color) { + var texture = sprite._texture; + + color = CanvasTinter.roundColor(color); + + var stringColor = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + texture.tintCache = texture.tintCache || {}; + + var cachedTexture = texture.tintCache[stringColor]; + + var canvas = void 0; + + if (cachedTexture) { + if (cachedTexture.tintId === texture._updateID) { + return texture.tintCache[stringColor]; + } + + canvas = texture.tintCache[stringColor]; + } else { + canvas = CanvasTinter.canvas || document.createElement('canvas'); + } + + CanvasTinter.tintMethod(texture, color, canvas); + + canvas.tintId = texture._updateID; + + if (CanvasTinter.convertTintToImage) { + // is this better? + var tintImage = new Image(); + + tintImage.src = canvas.toDataURL(); + + texture.tintCache[stringColor] = tintImage; + } else { + texture.tintCache[stringColor] = canvas; + // if we are not converting the texture to an image then we need to lose the reference to the canvas + CanvasTinter.canvas = null; + } + + return canvas; + }, + + /** + * Tint a texture using the 'multiply' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithMultiply: function tintWithMultiply(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.save(); + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + context.restore(); + }, + + /** + * Tint a texture using the 'overlay' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithOverlay: function tintWithOverlay(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.save(); + context.globalCompositeOperation = 'copy'; + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + // context.globalCompositeOperation = 'copy'; + context.restore(); + }, + + + /** + * Tint a texture pixel per pixel. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithPerPixel: function tintWithPerPixel(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.save(); + context.globalCompositeOperation = 'copy'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + context.restore(); + + var rgbValues = (0, _utils.hex2rgb)(color); + var r = rgbValues[0]; + var g = rgbValues[1]; + var b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, crop.width, crop.height); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + } + + context.putImageData(pixelData, 0, 0); + }, + + /** + * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel. + * + * @memberof PIXI.CanvasTinter + * @param {number} color - the color to round, should be a hex color + * @return {number} The rounded color. + */ + roundColor: function roundColor(color) { + var step = CanvasTinter.cacheStepsPerColorChannel; + + var rgbValues = (0, _utils.hex2rgb)(color); + + rgbValues[0] = Math.min(255, rgbValues[0] / step * step); + rgbValues[1] = Math.min(255, rgbValues[1] / step * step); + rgbValues[2] = Math.min(255, rgbValues[2] / step * step); + + return (0, _utils.rgb2hex)(rgbValues); + }, + + /** + * Number of steps which will be used as a cap when rounding colors. + * + * @memberof PIXI.CanvasTinter + * @type {number} + */ + cacheStepsPerColorChannel: 8, + + /** + * Tint cache boolean flag. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + convertTintToImage: false, + + /** + * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + canUseMultiply: (0, _canUseNewCanvasBlendModes2.default)(), + + /** + * The tinting method that will be used. + * + * @memberof PIXI.CanvasTinter + * @type {tintMethodFunctionType} + */ + tintMethod: 0 +}; + +CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply : CanvasTinter.tintWithPerPixel; + +/** + * The tintMethod type. + * + * @memberof PIXI.CanvasTinter + * @callback tintMethodFunctionType + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + +exports.default = CanvasTinter; + +},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":80,"../../utils":125}],105:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Buffer = function () { + /** + * @param {number} size - The size of the buffer in bytes. + */ + function Buffer(size) { + _classCallCheck(this, Buffer); + + this.vertices = new ArrayBuffer(size); + + /** + * View on the vertices as a Float32Array for positions + * + * @member {Float32Array} + */ + this.float32View = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array for uvs + * + * @member {Float32Array} + */ + this.uint32View = new Uint32Array(this.vertices); + } + + /** + * Destroys the buffer. + * + */ + + + Buffer.prototype.destroy = function destroy() { + this.vertices = null; + this.positions = null; + this.uvs = null; + this.colors = null; + }; + + return Buffer; +}(); + +exports.default = Buffer; + +},{}],106:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _createIndicesForQuads = require('../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +var _generateMultiTextureShader = require('./generateMultiTextureShader'); + +var _generateMultiTextureShader2 = _interopRequireDefault(_generateMultiTextureShader); + +var _checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'); + +var _checkMaxIfStatmentsInShader2 = _interopRequireDefault(_checkMaxIfStatmentsInShader); + +var _BatchBuffer = require('./BatchBuffer'); + +var _BatchBuffer2 = _interopRequireDefault(_BatchBuffer); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var TICK = 0; +var TEXTURE_TICK = 0; + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var SpriteRenderer = function (_ObjectRenderer) { + _inherits(SpriteRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function SpriteRenderer(renderer) { + _classCallCheck(this, SpriteRenderer); + + /** + * Number of values sent in the vertex buffer. + * aVertexPosition(2), aTextureCoord(1), aColor(1), aTextureId(1) = 5 + * + * @member {number} + */ + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.vertSize = 5; + + /** + * The size of the vertex information in bytes. + * + * @member {number} + */ + _this.vertByteSize = _this.vertSize * 4; + + /** + * The number of images in the SpriteRenderer before it flushes. + * + * @member {number} + */ + _this.size = _settings2.default.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + + // the total number of bytes in our batch + // let numVerts = this.size * 4 * this.vertByteSize; + + _this.buffers = []; + for (var i = 1; i <= _bitTwiddle2.default.nextPow2(_this.size); i *= 2) { + _this.buffers.push(new _BatchBuffer2.default(i * 4 * _this.vertByteSize)); + } + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + _this.indices = (0, _createIndicesForQuads2.default)(_this.size); + + /** + * The default shaders that is used if a sprite doesn't have a more specific one. + * there is a shader for each number of textures that can be rendererd. + * These shaders will also be generated on the fly as required. + * @member {PIXI.Shader[]} + */ + _this.shader = null; + + _this.currentIndex = 0; + _this.groups = []; + + for (var k = 0; k < _this.size; k++) { + _this.groups[k] = { textures: [], textureCount: 0, ids: [], size: 0, start: 0, blend: 0 }; + } + + _this.sprites = []; + + _this.vertexBuffers = []; + _this.vaos = []; + + _this.vaoMax = 2; + _this.vertexCount = 0; + + _this.renderer.on('prerender', _this.onPrerender, _this); + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + SpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + if (this.renderer.legacy) { + this.MAX_TEXTURES = 1; + } else { + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), _settings2.default.SPRITE_MAX_TEXTURES); + + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = (0, _checkMaxIfStatmentsInShader2.default)(this.MAX_TEXTURES, gl); + } + + this.shader = (0, _generateMultiTextureShader2.default)(gl, this.MAX_TEXTURES); + + // create a couple of buffers + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + // we use the second shader as the first one depending on your browser may omit aTextureId + // as it is not used by the shader so is optimized out. + + this.renderer.bindVao(null); + + var attrs = this.shader.attributes; + + for (var i = 0; i < this.vaoMax; i++) { + /* eslint-disable max-len */ + var vertexBuffer = this.vertexBuffers[i] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + /* eslint-enable max-len */ + + // build the vao object that will render.. + var vao = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (attrs.aTextureId) { + vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vaos[i] = vao; + } + + this.vao = this.vaos[0]; + this.currentBlendMode = 99999; + + this.boundTextures = new Array(this.MAX_TEXTURES); + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + SpriteRenderer.prototype.onPrerender = function onPrerender() { + this.vertexCount = 0; + }; + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + SpriteRenderer.prototype.render = function render(sprite) { + // TODO set blend modes.. + // check texture.. + if (this.currentIndex >= this.size) { + this.flush(); + } + + // get the uvs for the texture + + // if the uvs have not updated then no point rendering just yet! + if (!sprite._texture._uvs) { + return; + } + + // push a texture. + // increment the batchsize + this.sprites[this.currentIndex++] = sprite; + }; + + /** + * Renders the content and empties the current batch. + * + */ + + + SpriteRenderer.prototype.flush = function flush() { + if (this.currentIndex === 0) { + return; + } + + var gl = this.renderer.gl; + var MAX_TEXTURES = this.MAX_TEXTURES; + + var np2 = _bitTwiddle2.default.nextPow2(this.currentIndex); + var log2 = _bitTwiddle2.default.log2(np2); + var buffer = this.buffers[log2]; + + var sprites = this.sprites; + var groups = this.groups; + + var float32View = buffer.float32View; + var uint32View = buffer.uint32View; + + var boundTextures = this.boundTextures; + var rendererBoundTextures = this.renderer.boundTextures; + var touch = this.renderer.textureGC.count; + + var index = 0; + var nextTexture = void 0; + var currentTexture = void 0; + var groupCount = 1; + var textureCount = 0; + var currentGroup = groups[0]; + var vertexData = void 0; + var uvs = void 0; + var blendMode = _utils.premultiplyBlendMode[sprites[0]._texture.baseTexture.premultipliedAlpha ? 1 : 0][sprites[0].blendMode]; + + currentGroup.textureCount = 0; + currentGroup.start = 0; + currentGroup.blend = blendMode; + + TICK++; + + var i = void 0; + + // copy textures.. + for (i = 0; i < MAX_TEXTURES; ++i) { + var bt = rendererBoundTextures[i]; + + if (bt._enabled === TICK) { + boundTextures[i] = this.renderer.emptyTextures[i]; + continue; + } + + boundTextures[i] = bt; + bt._virtalBoundId = i; + bt._enabled = TICK; + } + TICK++; + + for (i = 0; i < this.currentIndex; ++i) { + // upload the sprite elemetns... + // they have all ready been calculated so we just need to push them into the buffer. + var sprite = sprites[i]; + + nextTexture = sprite._texture.baseTexture; + + var spriteBlendMode = _utils.premultiplyBlendMode[Number(nextTexture.premultipliedAlpha)][sprite.blendMode]; + + if (blendMode !== spriteBlendMode) { + // finish a group.. + blendMode = spriteBlendMode; + + // force the batch to break! + currentTexture = null; + textureCount = MAX_TEXTURES; + TICK++; + } + + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + + if (nextTexture._enabled !== TICK) { + if (textureCount === MAX_TEXTURES) { + TICK++; + + currentGroup.size = i - currentGroup.start; + + textureCount = 0; + + currentGroup = groups[groupCount++]; + currentGroup.blend = blendMode; + currentGroup.textureCount = 0; + currentGroup.start = i; + } + + nextTexture.touched = touch; + + if (nextTexture._virtalBoundId === -1) { + for (var j = 0; j < MAX_TEXTURES; ++j) { + var tIndex = (j + TEXTURE_TICK) % MAX_TEXTURES; + + var t = boundTextures[tIndex]; + + if (t._enabled !== TICK) { + TEXTURE_TICK++; + + t._virtalBoundId = -1; + + nextTexture._virtalBoundId = tIndex; + + boundTextures[tIndex] = nextTexture; + break; + } + } + } + + nextTexture._enabled = TICK; + + currentGroup.textureCount++; + currentGroup.ids[textureCount] = nextTexture._virtalBoundId; + currentGroup.textures[textureCount++] = nextTexture; + } + } + + vertexData = sprite.vertexData; + + // TODO this sum does not need to be set each frame.. + uvs = sprite._texture._uvs.uvsUint32; + + if (this.renderer.roundPixels) { + var resolution = this.renderer.resolution; + + // xy + float32View[index] = (vertexData[0] * resolution | 0) / resolution; + float32View[index + 1] = (vertexData[1] * resolution | 0) / resolution; + + // xy + float32View[index + 5] = (vertexData[2] * resolution | 0) / resolution; + float32View[index + 6] = (vertexData[3] * resolution | 0) / resolution; + + // xy + float32View[index + 10] = (vertexData[4] * resolution | 0) / resolution; + float32View[index + 11] = (vertexData[5] * resolution | 0) / resolution; + + // xy + float32View[index + 15] = (vertexData[6] * resolution | 0) / resolution; + float32View[index + 16] = (vertexData[7] * resolution | 0) / resolution; + } else { + // xy + float32View[index] = vertexData[0]; + float32View[index + 1] = vertexData[1]; + + // xy + float32View[index + 5] = vertexData[2]; + float32View[index + 6] = vertexData[3]; + + // xy + float32View[index + 10] = vertexData[4]; + float32View[index + 11] = vertexData[5]; + + // xy + float32View[index + 15] = vertexData[6]; + float32View[index + 16] = vertexData[7]; + } + + uint32View[index + 2] = uvs[0]; + uint32View[index + 7] = uvs[1]; + uint32View[index + 12] = uvs[2]; + uint32View[index + 17] = uvs[3]; + /* eslint-disable max-len */ + var alpha = Math.min(sprite.worldAlpha, 1.0); + // we dont call extra function if alpha is 1.0, that's faster + var argb = alpha < 1.0 && nextTexture.premultipliedAlpha ? (0, _utils.premultiplyTint)(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); + + uint32View[index + 3] = uint32View[index + 8] = uint32View[index + 13] = uint32View[index + 18] = argb; + float32View[index + 4] = float32View[index + 9] = float32View[index + 14] = float32View[index + 19] = nextTexture._virtalBoundId; + /* eslint-enable max-len */ + + index += 20; + } + + currentGroup.size = i - currentGroup.start; + + if (!_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // this is still needed for IOS performance.. + // it really does not like uploading to the same buffer in a single frame! + if (this.vaoMax <= this.vertexCount) { + this.vaoMax++; + + var attrs = this.shader.attributes; + + /* eslint-disable max-len */ + var vertexBuffer = this.vertexBuffers[this.vertexCount] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + /* eslint-enable max-len */ + + // build the vao object that will render.. + var vao = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (attrs.aTextureId) { + vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vaos[this.vertexCount] = vao; + } + + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, false); + + this.vertexCount++; + } else { + // lets use the faster option, always use buffer number 0 + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, true); + } + + for (i = 0; i < MAX_TEXTURES; ++i) { + rendererBoundTextures[i]._virtalBoundId = -1; + } + + // render the groups.. + for (i = 0; i < groupCount; ++i) { + var group = groups[i]; + var groupTextureCount = group.textureCount; + + for (var _j = 0; _j < groupTextureCount; _j++) { + currentTexture = group.textures[_j]; + + // reset virtual ids.. + // lets do a quick check.. + if (rendererBoundTextures[group.ids[_j]] !== currentTexture) { + this.renderer.bindTexture(currentTexture, group.ids[_j], true); + } + + // reset the virtualId.. + currentTexture._virtalBoundId = -1; + } + + // set the blend mode.. + this.renderer.state.setBlendMode(group.blend); + + gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); + } + + // reset elements for the next flush + this.currentIndex = 0; + }; + + /** + * Starts a new sprite batch. + */ + + + SpriteRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + + if (_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // bind buffer #0, we don't need others + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].bind(); + } + }; + + /** + * Stops and flushes the current batch. + * + */ + + + SpriteRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Destroys the SpriteRenderer. + * + */ + + + SpriteRenderer.prototype.destroy = function destroy() { + for (var i = 0; i < this.vaoMax; i++) { + if (this.vertexBuffers[i]) { + this.vertexBuffers[i].destroy(); + } + if (this.vaos[i]) { + this.vaos[i].destroy(); + } + } + + if (this.indexBuffer) { + this.indexBuffer.destroy(); + } + + this.renderer.off('prerender', this.onPrerender, this); + + _ObjectRenderer.prototype.destroy.call(this); + + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } + + this.vertexBuffers = null; + this.vaos = null; + this.indexBuffer = null; + this.indices = null; + + this.sprites = null; + + for (var _i = 0; _i < this.buffers.length; ++_i) { + this.buffers[_i].destroy(); + } + }; + + return SpriteRenderer; +}(_ObjectRenderer3.default); + +exports.default = SpriteRenderer; + + +_WebGLRenderer2.default.registerPlugin('sprite', SpriteRenderer); + +},{"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":97,"../../settings":101,"../../utils":125,"../../utils/createIndicesForQuads":123,"./BatchBuffer":105,"./generateMultiTextureShader":107,"bit-twiddle":1,"pixi-gl-core":12}],107:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateMultiTextureShader; + +var _Shader = require('../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'varying float vTextureId;', 'uniform sampler2D uSamplers[%count%];', 'void main(void){', 'vec4 color;', 'float textureId = floor(vTextureId+0.5);', '%forloop%', 'gl_FragColor = color * vColor;', '}'].join('\n'); + +function generateMultiTextureShader(gl, maxTextures) { + var vertexSrc = 'precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor;\n}\n'; + var fragmentSrc = fragTemplate; + + fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); + + var shader = new _Shader2.default(gl, vertexSrc, fragmentSrc); + + var sampleValues = []; + + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + + shader.bind(); + shader.uniforms.uSamplers = sampleValues; + + return shader; +} + +function generateSampleSrc(maxTextures) { + var src = ''; + + src += '\n'; + src += '\n'; + + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxTextures - 1) { + src += 'if(textureId == ' + i + '.0)'; + } + + src += '\n{'; + src += '\n\tcolor = texture2D(uSamplers[' + i + '], vTextureCoord);'; + src += '\n}'; + } + + src += '\n'; + src += '\n'; + + return src; +} + +},{"../../Shader":44,"path":23}],108:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Sprite2 = require('../sprites/Sprite'); + +var _Sprite3 = _interopRequireDefault(_Sprite2); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TextStyle = require('./TextStyle'); + +var _TextStyle2 = _interopRequireDefault(_TextStyle); + +var _TextMetrics = require('./TextMetrics'); + +var _TextMetrics2 = _interopRequireDefault(_TextMetrics); + +var _trimCanvas = require('../utils/trimCanvas'); + +var _trimCanvas2 = _interopRequireDefault(_trimCanvas); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint max-depth: [2, 8] */ + + +var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true +}; + +/** + * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string, + * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object. + * + * A Text can be created directly from a string and a style object + * + * ```js + * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI + */ + +var Text = function (_Sprite) { + _inherits(Text, _Sprite); + + /** + * @param {string} text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + * @param {HTMLCanvasElement} [canvas] - The canvas element for drawing text + */ + function Text(text, style, canvas) { + _classCallCheck(this, Text); + + canvas = canvas || document.createElement('canvas'); + + canvas.width = 3; + canvas.height = 3; + + var texture = _Texture2.default.fromCanvas(canvas, _settings2.default.SCALE_MODE, 'text'); + + texture.orig = new _math.Rectangle(); + texture.trim = new _math.Rectangle(); + + // base texture is already automatically added to the cache, now adding the actual texture + var _this = _possibleConstructorReturn(this, _Sprite.call(this, texture)); + + _Texture2.default.addToCache(_this._texture, _this._texture.baseTexture.textureCacheIds[0]); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.canvas = canvas; + + /** + * The canvas 2d context that everything is drawn with + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.canvas.getContext('2d'); + + /** + * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. + * @member {number} + * @default 1 + */ + _this.resolution = _settings2.default.RESOLUTION; + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = null; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._style = null; + /** + * Private listener to track style changes. + * + * @member {Function} + * @private + */ + _this._styleListener = null; + + /** + * Private tracker for the current font. + * + * @member {string} + * @private + */ + _this._font = ''; + + _this.text = text; + _this.style = style; + + _this.localStyleID = -1; + return _this; + } + + /** + * Renders text and updates it when needed. + * + * @private + * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. + */ + + + Text.prototype.updateText = function updateText(respectDirty) { + var style = this._style; + + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + + if (!this.dirty && respectDirty) { + return; + } + + this._font = this._style.toFontString(); + + var context = this.context; + var measured = _TextMetrics2.default.measureText(this._text, this._style, this._style.wordWrap, this.canvas); + var width = measured.width; + var height = measured.height; + var lines = measured.lines; + var lineHeight = measured.lineHeight; + var lineWidths = measured.lineWidths; + var maxLineWidth = measured.maxLineWidth; + var fontProperties = measured.fontProperties; + + this.canvas.width = Math.ceil((width + style.padding * 2) * this.resolution); + this.canvas.height = Math.ceil((height + style.padding * 2) * this.resolution); + + context.scale(this.resolution, this.resolution); + + context.clearRect(0, 0, this.canvas.width, this.canvas.height); + + context.font = this._font; + context.strokeStyle = style.stroke; + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + + var linePositionX = void 0; + var linePositionY = void 0; + + if (style.dropShadow) { + context.fillStyle = style.dropShadowColor; + context.globalAlpha = style.dropShadowAlpha; + context.shadowBlur = style.dropShadowBlur; + + if (style.dropShadowBlur > 0) { + context.shadowColor = style.dropShadowColor; + } + + var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + + for (var i = 0; i < lines.length; i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (style.fill) { + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); + + if (style.stroke && style.strokeThickness) { + context.strokeStyle = style.dropShadowColor; + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding, true); + context.strokeStyle = style.stroke; + } + } + } + } + + // reset the shadow blur and alpha that was set by the drop shadow, for the regular text + context.shadowBlur = 0; + context.globalAlpha = 1; + + // set canvas text styles + context.fillStyle = this._generateFillStyle(style, lines); + + // draw lines line by line + for (var _i = 0; _i < lines.length; _i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i]) / 2; + } + + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding, true); + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding); + } + } + + this.updateTexture(); + }; + + /** + * Render the text with letter-spacing. + * @param {string} text - The text to draw + * @param {number} x - Horizontal position to draw the text + * @param {number} y - Vertical position to draw the text + * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + * @private + */ + + + Text.prototype.drawLetterSpacing = function drawLetterSpacing(text, x, y) { + var isStroke = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var style = this._style; + + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + + if (letterSpacing === 0) { + if (isStroke) { + this.context.strokeText(text, x, y); + } else { + this.context.fillText(text, x, y); + } + + return; + } + + var characters = String.prototype.split.call(text, ''); + var currentPosition = x; + var index = 0; + var current = ''; + + while (index < text.length) { + current = characters[index++]; + if (isStroke) { + this.context.strokeText(current, currentPosition, y); + } else { + this.context.fillText(current, currentPosition, y); + } + currentPosition += this.context.measureText(current).width + letterSpacing; + } + }; + + /** + * Updates texture size based on canvas size + * + * @private + */ + + + Text.prototype.updateTexture = function updateTexture() { + var canvas = this.canvas; + + if (this._style.trim) { + var trimmed = (0, _trimCanvas2.default)(canvas); + + canvas.width = trimmed.width; + canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } + + var texture = this._texture; + var style = this._style; + var padding = style.trim ? 0 : style.padding; + var baseTexture = texture.baseTexture; + + baseTexture.hasLoaded = true; + baseTexture.resolution = this.resolution; + + baseTexture.realWidth = canvas.width; + baseTexture.realHeight = canvas.height; + baseTexture.width = canvas.width / this.resolution; + baseTexture.height = canvas.height / this.resolution; + + texture.trim.width = texture._frame.width = canvas.width / this.resolution; + texture.trim.height = texture._frame.height = canvas.height / this.resolution; + texture.trim.x = -padding; + texture.trim.y = -padding; + + texture.orig.width = texture._frame.width - padding * 2; + texture.orig.height = texture._frame.height - padding * 2; + + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + + baseTexture.emit('update', baseTexture); + + this.dirty = false; + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Text.prototype.renderWebGL = function renderWebGL(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype.renderWebGL.call(this, renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Text.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype._renderCanvas.call(this, renderer); + }; + + /** + * Gets the local bounds of the text object. + * + * @param {Rectangle} rect - The output rectangle. + * @return {Rectangle} The bounds. + */ + + + Text.prototype.getLocalBounds = function getLocalBounds(rect) { + this.updateText(true); + + return _Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + */ + + + Text.prototype._calculateBounds = function _calculateBounds() { + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; + + /** + * Method to be called upon a TextStyle change. + * @private + */ + + + Text.prototype._onStyleChange = function _onStyleChange() { + this.dirty = true; + }; + + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * + * @private + * @param {object} style - The style. + * @param {string[]} lines - The lines of text. + * @return {string|number|CanvasGradient} The fill style + */ + + + Text.prototype._generateFillStyle = function _generateFillStyle(style, lines) { + if (!Array.isArray(style.fill)) { + return style.fill; + } + + // cocoon on canvas+ cannot generate textures, so use the first colour instead + if (navigator.isCocoonJS) { + return style.fill[0]; + } + + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient = void 0; + var totalIterations = void 0; + var currentIteration = void 0; + var stop = void 0; + + var width = this.canvas.width / this.resolution; + var height = this.canvas.height / this.resolution; + + // make a copy of the style settings, so we can manipulate them later + var fill = style.fill.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(style.fill[0]); + fillGradientStops.unshift(0); + + fill.push(style.fill[style.fill.length - 1]); + fillGradientStops.push(1); + + if (style.fillGradientType === _const.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); + + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + totalIterations = (fill.length + 1) * lines.length; + currentIteration = 0; + for (var _i2 = 0; _i2 < lines.length; _i2++) { + currentIteration += 1; + for (var j = 0; j < fill.length; j++) { + if (typeof fillGradientStops[j] === 'number') { + stop = fillGradientStops[j] / lines.length + _i2 / lines.length; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[j]); + currentIteration++; + } + } + } else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); + + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + totalIterations = fill.length + 1; + currentIteration = 1; + + for (var _i3 = 0; _i3 < fill.length; _i3++) { + if (typeof fillGradientStops[_i3] === 'number') { + stop = fillGradientStops[_i3]; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[_i3]); + currentIteration++; + } + } + + return gradient; + }; + + /** + * Destroys this text object. + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majority of the time the texture will not be shared with any other Sprites. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well + */ + + + Text.prototype.destroy = function destroy(options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + + options = Object.assign({}, defaultDestroyOptions, options); + + _Sprite.prototype.destroy.call(this, options); + + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + + this._style = null; + }; + + /** + * The width of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Text, [{ + key: 'width', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * Set the style of the text. Set up an event listener to listen for changes on the style + * object and mark the text as dirty. + * + * @member {object|PIXI.TextStyle} + */ + + }, { + key: 'style', + get: function get() { + return this._style; + }, + set: function set(style) // eslint-disable-line require-jsdoc + { + style = style || {}; + + if (style instanceof _TextStyle2.default) { + this._style = style; + } else { + this._style = new _TextStyle2.default(style); + } + + this.localStyleID = -1; + this.dirty = true; + } + + /** + * Set the copy for the text object. To split a line you can use '\n'. + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(text) // eslint-disable-line require-jsdoc + { + text = String(text === '' || text === null || text === undefined ? ' ' : text); + + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + } + }]); + + return Text; +}(_Sprite3.default); + +exports.default = Text; + +},{"../const":46,"../math":70,"../settings":101,"../sprites/Sprite":102,"../textures/Texture":115,"../utils":125,"../utils/trimCanvas":130,"./TextMetrics":109,"./TextStyle":110}],109:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The TextMetrics object represents the measurement of a block of text with a specified style. + * + * @class + * @memberOf PIXI + */ +var TextMetrics = function () { + /** + * @param {string} text - the text that was measured + * @param {PIXI.TextStyle} style - the style that was measured + * @param {number} width - the measured width of the text + * @param {number} height - the measured height of the text + * @param {array} lines - an array of the lines of text broken by new lines and wrapping if specified in style + * @param {array} lineWidths - an array of the line widths for each line matched to `lines` + * @param {number} lineHeight - the measured line height for this style + * @param {number} maxLineWidth - the maximum line width for all measured lines + * @param {Object} fontProperties - the font properties object from TextMetrics.measureFont + */ + function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) { + _classCallCheck(this, TextMetrics); + + this.text = text; + this.style = style; + this.width = width; + this.height = height; + this.lines = lines; + this.lineWidths = lineWidths; + this.lineHeight = lineHeight; + this.maxLineWidth = maxLineWidth; + this.fontProperties = fontProperties; + } + + /** + * Measures the supplied string of text and returns a Rectangle. + * + * @param {string} text - the text to measure. + * @param {PIXI.TextStyle} style - the text style to use for measuring + * @param {boolean} [wordWrap] - optional override for if word-wrap should be applied to the text. + * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. + * @return {PIXI.TextMetrics} measured width and height of the text. + */ + + + TextMetrics.measureText = function measureText(text, style, wordWrap) { + var canvas = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : TextMetrics._canvas; + + wordWrap = wordWrap || style.wordWrap; + var font = style.toFontString(); + var fontProperties = TextMetrics.measureFont(font); + var context = canvas.getContext('2d'); + + context.font = font; + + var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text; + var lines = outputText.split(/(?:\r\n|\r|\n)/); + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + + for (var i = 0; i < lines.length; i++) { + var lineWidth = context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing; + + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + var width = maxLineWidth + style.strokeThickness; + + if (style.dropShadow) { + width += style.dropShadowDistance; + } + + var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * (lineHeight + style.leading); + + if (style.dropShadow) { + height += style.dropShadowDistance; + } + + return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties); + }; + + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @private + * @param {string} text - String to apply word wrapping to + * @param {PIXI.TextStyle} style - the style to use when wrapping + * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. + * @return {string} New string with new lines applied where required + */ + + + TextMetrics.wordWrap = function wordWrap(text, style) { + var canvas = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : TextMetrics._canvas; + + var context = canvas.getContext('2d'); + + // Greedy wrapping algorithm that will wrap words as the line grows longer + // than its horizontal bounds. + var result = ''; + var firstChar = text.charAt(0); + var lines = text.split('\n'); + var wordWrapWidth = style.wordWrapWidth; + var characterCache = {}; + + for (var i = 0; i < lines.length; i++) { + var spaceLeft = wordWrapWidth; + var words = lines[i].split(' '); + + for (var j = 0; j < words.length; j++) { + var wordWidth = context.measureText(words[j]).width; + + if (style.breakWords && wordWidth > wordWrapWidth) { + // Word should be split in the middle + var characters = words[j].split(''); + + for (var c = 0; c < characters.length; c++) { + var character = characters[c]; + var characterWidth = characterCache[character]; + + if (characterWidth === undefined) { + characterWidth = context.measureText(character).width; + characterCache[character] = characterWidth; + } + + if (characterWidth > spaceLeft) { + result += '\n' + character; + spaceLeft = wordWrapWidth - characterWidth; + } else { + if (c === 0 && (j > 0 || firstChar === ' ')) { + result += ' '; + } + + result += character; + spaceLeft -= characterWidth; + } + } + } else { + var wordWidthWithSpace = wordWidth + context.measureText(' ').width; + + if (j === 0 || wordWidthWithSpace > spaceLeft) { + // Skip printing the newline if it's the first word of the line that is + // greater than the word wrap width. + if (j > 0) { + result += '\n'; + } + result += words[j]; + spaceLeft = wordWrapWidth - wordWidth; + } else { + spaceLeft -= wordWidthWithSpace; + result += ' ' + words[j]; + } + } + } + + if (i < lines.length - 1) { + result += '\n'; + } + } + + return result; + }; + + /** + * Calculates the ascent, descent and fontSize of a given font-style + * + * @static + * @param {string} font - String representing the style of the font + * @return {PIXI.TextMetrics~FontMetrics} Font properties object + */ + + + TextMetrics.measureFont = function measureFont(font) { + // as this method is used for preparing assets, don't recalculate things if we don't need to + if (TextMetrics._fonts[font]) { + return TextMetrics._fonts[font]; + } + + var properties = {}; + + var canvas = TextMetrics._canvas; + var context = TextMetrics._context; + + context.font = font; + + var width = Math.ceil(context.measureText('|MÉq').width); + var baseline = Math.ceil(context.measureText('M').width); + var height = 2 * baseline; + + baseline = baseline * 1.4 | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = font; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText('|MÉq', 0, baseline); + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i = 0; + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } else { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var _j = 0; _j < line; _j += 4) { + if (imagedata[idx + _j] !== 255) { + stop = true; + break; + } + } + + if (!stop) { + idx -= line; + } else { + break; + } + } + + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + + TextMetrics._fonts[font] = properties; + + return properties; + }; + + return TextMetrics; +}(); + +/** + * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}. + * @class FontMetrics + * @memberof PIXI.TextMetrics~ + * @property {number} ascent - The ascent distance + * @property {number} descent - The descent distance + * @property {number} fontSize - Font size from ascent to descent + */ + +exports.default = TextMetrics; +var canvas = document.createElement('canvas'); + +canvas.width = canvas.height = 10; + +/** + * Cached canvas element for measuring text + * @memberof PIXI.TextMetrics + * @type {HTMLCanvasElement} + * @private + */ +TextMetrics._canvas = canvas; + +/** + * Cache for context to use. + * @memberof PIXI.TextMetrics + * @type {CanvasRenderingContext2D} + * @private + */ +TextMetrics._context = canvas.getContext('2d'); + +/** + * Cache of PIXI.TextMetrics~FontMetrics objects. + * @memberof PIXI.TextMetrics + * @type {Object} + * @private + */ +TextMetrics._fonts = {}; + +},{}],110:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // disabling eslint for now, going to rewrite this in v5 +/* eslint-disable */ + +var _const = require('../const'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: 'black', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: _const.TEXT_GRADIENT.LINEAR_VERTICAL, + fillGradientStops: [], + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + trim: false, + wordWrap: false, + wordWrapWidth: 100, + leading: 0 +}; + +/** + * A TextStyle Object decorates a Text Object. It can be shared between + * multiple Text objects. Changing the style will update all text objects using it. + * + * @class + * @memberof PIXI + */ + +var TextStyle = function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string|number} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours + * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} + * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set + * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * @param {string|string[]} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', 800' or '900') + * @param {number} [style.leading=0] - The space between lines + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Possible values "miter" (creates a sharp corner), "round" (creates a round corner) or "bevel" + * (creates a squared corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {boolean} [style.trim=false] - Trim transparent borders + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + _classCallCheck(this, TextStyle); + + this.styleID = 0; + + this.reset(); + + deepCopyProperties(this, style, style); + } + + /** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return {PIXI.TextStyle} New cloned TextStyle object + */ + + + TextStyle.prototype.clone = function clone() { + var clonedProperties = {}; + + deepCopyProperties(clonedProperties, this, defaultStyle); + + return new TextStyle(clonedProperties); + }; + + /** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ + + + TextStyle.prototype.reset = function reset() { + deepCopyProperties(this, defaultStyle, defaultStyle); + }; + + /** + * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text + * + * @member {string} + */ + + + /** + * Generates a font style string to use for `TextMetrics.measureFont()`. + * + * @return {string} Font style string, for passing to `TextMetrics.measureFont()` + */ + TextStyle.prototype.toFontString = function toFontString() { + // build canvas api font setting from individual components. Convert a numeric this.fontSize to px + var fontSizeString = typeof this.fontSize === 'number' ? this.fontSize + 'px' : this.fontSize; + + // Clean-up fontFamily property by quoting each font name + // this will support font names with spaces + var fontFamilies = this.fontFamily; + + if (!Array.isArray(this.fontFamily)) { + fontFamilies = this.fontFamily.split(','); + } + + for (var i = fontFamilies.length - 1; i >= 0; i--) { + // Trim any extra white-space + var fontFamily = fontFamilies[i].trim(); + + // Check if font already contains strings + if (!/([\"\'])[^\'\"]+\1/.test(fontFamily)) { + fontFamily = '"' + fontFamily + '"'; + } + fontFamilies[i] = fontFamily; + } + + return this.fontStyle + ' ' + this.fontVariant + ' ' + this.fontWeight + ' ' + fontSizeString + ' ' + fontFamilies.join(','); + }; + + _createClass(TextStyle, [{ + key: 'align', + get: function get() { + return this._align; + }, + set: function set(align) // eslint-disable-line require-jsdoc + { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + } + + /** + * Indicates if lines can be wrapped within words, it needs wordWrap to be set to true + * + * @member {boolean} + */ + + }, { + key: 'breakWords', + get: function get() { + return this._breakWords; + }, + set: function set(breakWords) // eslint-disable-line require-jsdoc + { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + } + + /** + * Set a drop shadow for the text + * + * @member {boolean} + */ + + }, { + key: 'dropShadow', + get: function get() { + return this._dropShadow; + }, + set: function set(dropShadow) // eslint-disable-line require-jsdoc + { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + } + + /** + * Set alpha for the drop shadow + * + * @member {number} + */ + + }, { + key: 'dropShadowAlpha', + get: function get() { + return this._dropShadowAlpha; + }, + set: function set(dropShadowAlpha) // eslint-disable-line require-jsdoc + { + if (this._dropShadowAlpha !== dropShadowAlpha) { + this._dropShadowAlpha = dropShadowAlpha; + this.styleID++; + } + } + + /** + * Set a angle of the drop shadow + * + * @member {number} + */ + + }, { + key: 'dropShadowAngle', + get: function get() { + return this._dropShadowAngle; + }, + set: function set(dropShadowAngle) // eslint-disable-line require-jsdoc + { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + } + + /** + * Set a shadow blur radius + * + * @member {number} + */ + + }, { + key: 'dropShadowBlur', + get: function get() { + return this._dropShadowBlur; + }, + set: function set(dropShadowBlur) // eslint-disable-line require-jsdoc + { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + } + + /** + * A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * + * @member {string|number} + */ + + }, { + key: 'dropShadowColor', + get: function get() { + return this._dropShadowColor; + }, + set: function set(dropShadowColor) // eslint-disable-line require-jsdoc + { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + } + + /** + * Set a distance of the drop shadow + * + * @member {number} + */ + + }, { + key: 'dropShadowDistance', + get: function get() { + return this._dropShadowDistance; + }, + set: function set(dropShadowDistance) // eslint-disable-line require-jsdoc + { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + } + + /** + * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'. + * Can be an array to create a gradient eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * + * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern} + */ + + }, { + key: 'fill', + get: function get() { + return this._fill; + }, + set: function set(fill) // eslint-disable-line require-jsdoc + { + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + } + + /** + * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient. + * See {@link PIXI.TEXT_GRADIENT} + * + * @member {number} + */ + + }, { + key: 'fillGradientType', + get: function get() { + return this._fillGradientType; + }, + set: function set(fillGradientType) // eslint-disable-line require-jsdoc + { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + } + + /** + * If fill is an array of colours to create a gradient, this array can set the stop points + * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * + * @member {number[]} + */ + + }, { + key: 'fillGradientStops', + get: function get() { + return this._fillGradientStops; + }, + set: function set(fillGradientStops) // eslint-disable-line require-jsdoc + { + if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { + this._fillGradientStops = fillGradientStops; + this.styleID++; + } + } + + /** + * The font family + * + * @member {string|string[]} + */ + + }, { + key: 'fontFamily', + get: function get() { + return this._fontFamily; + }, + set: function set(fontFamily) // eslint-disable-line require-jsdoc + { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + } + + /** + * The font size + * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em') + * + * @member {number|string} + */ + + }, { + key: 'fontSize', + get: function get() { + return this._fontSize; + }, + set: function set(fontSize) // eslint-disable-line require-jsdoc + { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + } + + /** + * The font style + * ('normal', 'italic' or 'oblique') + * + * @member {string} + */ + + }, { + key: 'fontStyle', + get: function get() { + return this._fontStyle; + }, + set: function set(fontStyle) // eslint-disable-line require-jsdoc + { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + } + + /** + * The font variant + * ('normal' or 'small-caps') + * + * @member {string} + */ + + }, { + key: 'fontVariant', + get: function get() { + return this._fontVariant; + }, + set: function set(fontVariant) // eslint-disable-line require-jsdoc + { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + } + + /** + * The font weight + * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900') + * + * @member {string} + */ + + }, { + key: 'fontWeight', + get: function get() { + return this._fontWeight; + }, + set: function set(fontWeight) // eslint-disable-line require-jsdoc + { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + } + + /** + * The amount of spacing between letters, default is 0 + * + * @member {number} + */ + + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(letterSpacing) // eslint-disable-line require-jsdoc + { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + } + + /** + * The line height, a number that represents the vertical space that a letter uses + * + * @member {number} + */ + + }, { + key: 'lineHeight', + get: function get() { + return this._lineHeight; + }, + set: function set(lineHeight) // eslint-disable-line require-jsdoc + { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + } + + /** + * The space between lines + * + * @member {number} + */ + + }, { + key: 'leading', + get: function get() { + return this._leading; + }, + set: function set(leading) // eslint-disable-line require-jsdoc + { + if (this._leading !== leading) { + this._leading = leading; + this.styleID++; + } + } + + /** + * The lineJoin property sets the type of corner created, it can resolve spiked text issues. + * Default is 'miter' (creates a sharp corner). + * + * @member {string} + */ + + }, { + key: 'lineJoin', + get: function get() { + return this._lineJoin; + }, + set: function set(lineJoin) // eslint-disable-line require-jsdoc + { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + } + + /** + * The miter limit to use when using the 'miter' lineJoin mode + * This can reduce or increase the spikiness of rendered text. + * + * @member {number} + */ + + }, { + key: 'miterLimit', + get: function get() { + return this._miterLimit; + }, + set: function set(miterLimit) // eslint-disable-line require-jsdoc + { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + } + + /** + * Occasionally some fonts are cropped. Adding some padding will prevent this from happening + * by adding padding to all sides of the text. + * + * @member {number} + */ + + }, { + key: 'padding', + get: function get() { + return this._padding; + }, + set: function set(padding) // eslint-disable-line require-jsdoc + { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + } + + /** + * A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * + * @member {string|number} + */ + + }, { + key: 'stroke', + get: function get() { + return this._stroke; + }, + set: function set(stroke) // eslint-disable-line require-jsdoc + { + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + } + + /** + * A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * + * @member {number} + */ + + }, { + key: 'strokeThickness', + get: function get() { + return this._strokeThickness; + }, + set: function set(strokeThickness) // eslint-disable-line require-jsdoc + { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + } + + /** + * The baseline of the text that is rendered. + * + * @member {string} + */ + + }, { + key: 'textBaseline', + get: function get() { + return this._textBaseline; + }, + set: function set(textBaseline) // eslint-disable-line require-jsdoc + { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + } + + /** + * Trim transparent borders + * + * @member {boolean} + */ + + }, { + key: 'trim', + get: function get() { + return this._trim; + }, + set: function set(trim) // eslint-disable-line require-jsdoc + { + if (this._trim !== trim) { + this._trim = trim; + this.styleID++; + } + } + + /** + * Indicates if word wrap should be used + * + * @member {boolean} + */ + + }, { + key: 'wordWrap', + get: function get() { + return this._wordWrap; + }, + set: function set(wordWrap) // eslint-disable-line require-jsdoc + { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + } + + /** + * The width at which text will wrap, it needs wordWrap to be set to true + * + * @member {number} + */ + + }, { + key: 'wordWrapWidth', + get: function get() { + return this._wordWrapWidth; + }, + set: function set(wordWrapWidth) // eslint-disable-line require-jsdoc + { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + } + }]); + + return TextStyle; +}(); + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * + * @param {number|number[]} color + * @return {string} The color as a string. + */ + + +exports.default = TextStyle; +function getSingleColor(color) { + if (typeof color === 'number') { + return (0, _utils.hex2string)(color); + } else if (typeof color === 'string') { + if (color.indexOf('0x') === 0) { + color = color.replace('0x', '#'); + } + } + + return color; +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * + * @param {number|number[]} color + * @return {string} The color as a string. + */ +function getColor(color) { + if (!Array.isArray(color)) { + return getSingleColor(color); + } else { + for (var i = 0; i < color.length; ++i) { + color[i] = getSingleColor(color[i]); + } + + return color; + } +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * + * @param {Array} array1 First array to compare + * @param {Array} array2 Second array to compare + * @return {boolean} Do the arrays contain the same values in the same order + */ +function areArraysEqual(array1, array2) { + if (!Array.isArray(array1) || !Array.isArray(array2)) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } + + return true; +} + +/** + * Utility function to ensure that object properties are copied by value, and not by reference + * + * @param {Object} target Target object to copy properties into + * @param {Object} source Source object for the proporties to copy + * @param {string} propertyObj Object containing properties names we want to loop over + */ +function deepCopyProperties(target, source, propertyObj) { + for (var prop in propertyObj) { + if (Array.isArray(source[prop])) { + target[prop] = source[prop].slice(); + } else { + target[prop] = source[prop]; + } + } +} + +},{"../const":46,"../utils":125}],111:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let baseRenderTexture = new PIXI.BaseRenderTexture(renderer, 800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * baseRenderTexture.render(sprite); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let baseRenderTexture = new PIXI.BaseRenderTexture(100, 100); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var BaseRenderTexture = function (_BaseTexture) { + _inherits(BaseRenderTexture, _BaseTexture); + + /** + * @param {number} [width=100] - The width of the base render texture + * @param {number} [height=100] - The height of the base render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + */ + function BaseRenderTexture() { + var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + + _classCallCheck(this, BaseRenderTexture); + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, null, scaleMode)); + + _this.resolution = resolution || _settings2.default.RESOLUTION; + + _this.width = Math.ceil(width); + _this.height = Math.ceil(height); + + _this.realWidth = _this.width * _this.resolution; + _this.realHeight = _this.height * _this.resolution; + + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + _this.hasLoaded = true; + + /** + * A map of renderer IDs to webgl renderTargets + * + * @private + * @member {object} + */ + _this._glRenderTargets = {}; + + /** + * A reference to the canvas render target (we only need one as this can be shared across renderers) + * + * @private + * @member {object} + */ + _this._canvasRenderTarget = null; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + return _this; + } + + /** + * Resizes the BaseRenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + */ + + + BaseRenderTexture.prototype.resize = function resize(width, height) { + width = Math.ceil(width); + height = Math.ceil(height); + + if (width === this.width && height === this.height) { + return; + } + + this.valid = width > 0 && height > 0; + + this.width = width; + this.height = height; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + if (!this.valid) { + return; + } + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + */ + + + BaseRenderTexture.prototype.destroy = function destroy() { + _BaseTexture.prototype.destroy.call(this, true); + this.renderer = null; + }; + + return BaseRenderTexture; +}(_BaseTexture3.default); + +exports.default = BaseRenderTexture; + +},{"../settings":101,"./BaseTexture":112}],112:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var BaseTexture = function (_EventEmitter) { + _inherits(BaseTexture, _EventEmitter); + + /** + * @param {HTMLImageElement|HTMLCanvasElement} [source] - the source object of the texture. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture + */ + function BaseTexture(source, scaleMode, resolution) { + _classCallCheck(this, BaseTexture); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.uid = (0, _utils.uid)(); + + _this.touched = 0; + + /** + * The resolution / device pixel ratio of the texture + * + * @member {number} + * @default 1 + */ + _this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The width of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.width = 100; + + /** + * The height of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.height = 100; + + // TODO docs + // used to store the actual dimensions of the source + /** + * Used to store the actual width of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realWidth = 100; + /** + * Used to store the actual height of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realHeight = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Set to true once the base texture has successfully loaded. + * + * This is never true if the underlying source fails to load or has no texture data. + * + * @readonly + * @member {boolean} + */ + _this.hasLoaded = false; + + /** + * Set to true if the source is currently loading. + * + * If an Image source is loading the 'loaded' or 'error' event will be + * dispatched when the operation ends. An underyling source that is + * immediately-available bypasses loading entirely. + * + * @readonly + * @member {boolean} + */ + _this.isLoading = false; + + /** + * The image source that is used to create the texture. + * + * TODO: Make this a setter that calls loadSource(); + * + * @readonly + * @member {HTMLImageElement|HTMLCanvasElement} + */ + _this.source = null; // set in loadSource, if at all + + /** + * The image source that is used to create the texture. This is used to + * store the original Svg source when it is replaced with a canvas element. + * + * TODO: Currently not in use but could be used when re-scaling svg. + * + * @readonly + * @member {Image} + */ + _this.origSource = null; // set in loadSvg, if at all + + /** + * Type of image defined in source, eg. `png` or `svg` + * + * @readonly + * @member {string} + */ + _this.imageType = null; // set in updateImageType + + /** + * Scale for source image. Used with Svg images to scale them before rasterization. + * + * @readonly + * @member {number} + */ + _this.sourceScale = 1.0; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * All blend modes, and shaders written for default value. Change it on your own risk. + * + * @member {boolean} + * @default true + */ + _this.premultipliedAlpha = true; + + /** + * The image url of the texture + * + * @member {string} + */ + _this.imageUrl = null; + + /** + * Whether or not the texture is a power of two, try to use power of two textures as much + * as you can + * + * @private + * @member {boolean} + */ + _this.isPowerOfTwo = false; + + // used for webGL + + /** + * + * Set this to true if a mipmap of this texture needs to be generated. This value needs + * to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @member {boolean} + * @see PIXI.MIPMAP_TEXTURES + */ + _this.mipmap = _settings2.default.MIPMAP_TEXTURES; + + /** + * + * WebGL Texture wrap mode + * + * @member {number} + * @see PIXI.WRAP_MODES + */ + _this.wrapMode = _settings2.default.WRAP_MODE; + + /** + * A map of renderer IDs to webgl textures + * + * @private + * @member {object} + */ + _this._glTextures = {}; + + _this._enabled = 0; + _this._virtalBoundId = -1; + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + + /** + * The ids under which this BaseTexture has been added to the base texture cache. This is + * automatically set as long as BaseTexture.addToCache is used, but may not be set if a + * BaseTexture is added directly to the BaseTextureCache array. + * + * @member {string[]} + */ + _this.textureCacheIds = []; + + // if no source passed don't try to load + if (source) { + _this.loadSource(source); + } + + /** + * Fired when a not-immediately-available source finishes loading. + * + * @protected + * @event PIXI.BaseTexture#loaded + * @param {PIXI.BaseTexture} baseTexture - Resource loaded. + */ + + /** + * Fired when a not-immediately-available source fails to load. + * + * @protected + * @event PIXI.BaseTexture#error + * @param {PIXI.BaseTexture} baseTexture - Resource errored. + */ + + /** + * Fired when BaseTexture is updated. + * + * @protected + * @event PIXI.BaseTexture#update + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. + */ + + /** + * Fired when BaseTexture is destroyed. + * + * @protected + * @event PIXI.BaseTexture#dispose + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. + */ + return _this; + } + + /** + * Updates the texture on all the webgl renderers, this also assumes the src has changed. + * + * @fires PIXI.BaseTexture#update + */ + + + BaseTexture.prototype.update = function update() { + // Svg size is handled during load + if (this.imageType !== 'svg') { + this.realWidth = this.source.naturalWidth || this.source.videoWidth || this.source.width; + this.realHeight = this.source.naturalHeight || this.source.videoHeight || this.source.height; + + this._updateDimensions(); + } + + this.emit('update', this); + }; + + /** + * Update dimensions from real values + */ + + + BaseTexture.prototype._updateDimensions = function _updateDimensions() { + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + this.isPowerOfTwo = _bitTwiddle2.default.isPow2(this.realWidth) && _bitTwiddle2.default.isPow2(this.realHeight); + }; + + /** + * Load a source. + * + * If the source is not-immediately-available, such as an image that needs to be + * downloaded, then the 'loaded' or 'error' event will be dispatched in the future + * and `hasLoaded` will remain false after this call. + * + * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: + * + * if (texture.hasLoaded) { + * // texture ready for use + * } else if (texture.isLoading) { + * // listen to 'loaded' and/or 'error' events on texture + * } else { + * // not loading, not going to load UNLESS the source is reloaded + * // (it may still make sense to listen to the events) + * } + * + * @protected + * @param {HTMLImageElement|HTMLCanvasElement} source - the source object of the texture. + */ + + + BaseTexture.prototype.loadSource = function loadSource(source) { + var wasLoading = this.isLoading; + + this.hasLoaded = false; + this.isLoading = false; + + if (wasLoading && this.source) { + this.source.onload = null; + this.source.onerror = null; + } + + var firstSourceLoaded = !this.source; + + this.source = source; + + // Apply source if loaded. Otherwise setup appropriate loading monitors. + if ((source.src && source.complete || source.getContext) && source.width && source.height) { + this._updateImageType(); + + if (this.imageType === 'svg') { + this._loadSvgSource(); + } else { + this._sourceLoaded(); + } + + if (firstSourceLoaded) { + // send loaded event if previous source was null and we have been passed a pre-loaded IMG element + this.emit('loaded', this); + } + } else if (!source.getContext) { + // Image fail / not ready + this.isLoading = true; + + var scope = this; + + source.onload = function () { + scope._updateImageType(); + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope._sourceLoaded(); + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + scope.emit('loaded', scope); + }; + + source.onerror = function () { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope.emit('error', scope); + }; + + // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element + // "The value of `complete` can thus change while a script is executing." + // So complete needs to be re-checked after the callbacks have been added.. + // NOTE: complete will be true if the image has no src so best to check if the src is set. + if (source.complete && source.src) { + // ..and if we're complete now, no need for callbacks + source.onload = null; + source.onerror = null; + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + this.isLoading = false; + + if (source.width && source.height) { + this._sourceLoaded(); + + // If any previous subscribers possible + if (wasLoading) { + this.emit('loaded', this); + } + } + // If any previous subscribers possible + else if (wasLoading) { + this.emit('error', this); + } + } + } + }; + + /** + * Updates type of the source image. + */ + + + BaseTexture.prototype._updateImageType = function _updateImageType() { + if (!this.imageUrl) { + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + var imageType = void 0; + + if (dataUri && dataUri.mediaType === 'image') { + // Check for subType validity + var firstSubType = dataUri.subType.split('+')[0]; + + imageType = (0, _utils.getUrlFileExtension)('.' + firstSubType); + + if (!imageType) { + throw new Error('Invalid image type in data URI.'); + } + } else { + imageType = (0, _utils.getUrlFileExtension)(this.imageUrl); + + if (!imageType) { + imageType = 'png'; + } + } + + this.imageType = imageType; + }; + + /** + * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls + * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. + */ + + + BaseTexture.prototype._loadSvgSource = function _loadSvgSource() { + if (this.imageType !== 'svg') { + // Do nothing if source is not svg + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + + if (dataUri) { + this._loadSvgSourceUsingDataUri(dataUri); + } else { + // We got an URL, so we need to do an XHR to check the svg size + this._loadSvgSourceUsingXhr(); + } + }; + + /** + * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`. + * + * @param {string} dataUri - The data uri to load from. + */ + + + BaseTexture.prototype._loadSvgSourceUsingDataUri = function _loadSvgSourceUsingDataUri(dataUri) { + var svgString = void 0; + + if (dataUri.encoding === 'base64') { + if (!atob) { + throw new Error('Your browser doesn\'t support base64 conversions.'); + } + svgString = atob(dataUri.data); + } else { + svgString = dataUri.data; + } + + this._loadSvgSourceUsingString(svgString); + }; + + /** + * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. + */ + + + BaseTexture.prototype._loadSvgSourceUsingXhr = function _loadSvgSourceUsingXhr() { + var _this2 = this; + + var svgXhr = new XMLHttpRequest(); + + // This throws error on IE, so SVG Document can't be used + // svgXhr.responseType = 'document'; + + // This is not needed since we load the svg as string (breaks IE too) + // but overrideMimeType() can be used to force the response to be parsed as XML + // svgXhr.overrideMimeType('image/svg+xml'); + + svgXhr.onload = function () { + if (svgXhr.readyState !== svgXhr.DONE || svgXhr.status !== 200) { + throw new Error('Failed to load SVG using XHR.'); + } + + _this2._loadSvgSourceUsingString(svgXhr.response); + }; + + svgXhr.onerror = function () { + return _this2.emit('error', _this2); + }; + + svgXhr.open('GET', this.imageUrl, true); + svgXhr.send(); + }; + + /** + * Loads texture using an SVG string. The original SVG Image is stored as `origSource` and the + * created canvas is the new `source`. The SVG is scaled using `sourceScale`. Called by + * `_loadSvgSourceUsingXhr` or `_loadSvgSourceUsingDataUri`. + * + * @param {string} svgString SVG source as string + * + * @fires PIXI.BaseTexture#loaded + */ + + + BaseTexture.prototype._loadSvgSourceUsingString = function _loadSvgSourceUsingString(svgString) { + var svgSize = (0, _utils.getSvgSize)(svgString); + + var svgWidth = svgSize.width; + var svgHeight = svgSize.height; + + if (!svgWidth || !svgHeight) { + throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); + } + + // Scale realWidth and realHeight + this.realWidth = Math.round(svgWidth * this.sourceScale); + this.realHeight = Math.round(svgHeight * this.sourceScale); + + this._updateDimensions(); + + // Create a canvas element + var canvas = document.createElement('canvas'); + + canvas.width = this.realWidth; + canvas.height = this.realHeight; + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + + // Draw the Svg to the canvas + canvas.getContext('2d').drawImage(this.source, 0, 0, svgWidth, svgHeight, 0, 0, this.realWidth, this.realHeight); + + // Replace the original source image with the canvas + this.origSource = this.source; + this.source = canvas; + + // Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`) + BaseTexture.addToCache(this, canvas._pixiId); + + this.isLoading = false; + this._sourceLoaded(); + this.emit('loaded', this); + }; + + /** + * Used internally to update the width, height, and some other tracking vars once + * a source has successfully loaded. + * + * @private + */ + + + BaseTexture.prototype._sourceLoaded = function _sourceLoaded() { + this.hasLoaded = true; + this.update(); + }; + + /** + * Destroys this base texture + * + */ + + + BaseTexture.prototype.destroy = function destroy() { + if (this.imageUrl) { + delete _utils.TextureCache[this.imageUrl]; + + this.imageUrl = null; + + if (!navigator.isCocoonJS) { + this.source.src = ''; + } + } + + this.source = null; + + this.dispose(); + + BaseTexture.removeFromCache(this); + this.textureCacheIds = null; + + this._destroyed = true; + }; + + /** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + * @fires PIXI.BaseTexture#dispose + */ + + + BaseTexture.prototype.dispose = function dispose() { + this.emit('dispose', this); + }; + + /** + * Changes the source image of the texture. + * The original source must be an Image element. + * + * @param {string} newSrc - the path of the image + */ + + + BaseTexture.prototype.updateSourceImage = function updateSourceImage(newSrc) { + this.source.src = newSrc; + + this.loadSource(this.source); + }; + + /** + * Helper function that creates a base texture from the given image url. + * If the image is not in the base texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + // new Image() breaks tex loading in some versions of Chrome. + // See https://code.google.com/p/chromium/issues/detail?id=238071 + var image = new Image(); // document.createElement('img'); + + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + image.crossOrigin = (0, _determineCrossOrigin2.default)(imageUrl); + } else if (crossorigin) { + image.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; + } + + baseTexture = new BaseTexture(image, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + image.src = imageUrl; // Setting this triggers load + + BaseTexture.addToCache(baseTexture, imageUrl); + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @param {string} [origin='canvas'] - A string origin of who created the base texture + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode) { + var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; + + if (!canvas._pixiId) { + canvas._pixiId = origin + '_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[canvas._pixiId]; + + if (!baseTexture) { + baseTexture = new BaseTexture(canvas, scaleMode); + BaseTexture.addToCache(baseTexture, canvas._pixiId); + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture based on the source you provide. + * The source can be - image url, image element, canvas element. If the + * source is an image url or an image element and not in the base texture + * cache, it will be created and loaded. + * + * @static + * @param {string|HTMLImageElement|HTMLCanvasElement} source - The source to create base texture from. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.from = function from(source, scaleMode, sourceScale) { + if (typeof source === 'string') { + return BaseTexture.fromImage(source, undefined, scaleMode, sourceScale); + } else if (source instanceof HTMLImageElement) { + var imageUrl = source.src; + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + baseTexture = new BaseTexture(source, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + BaseTexture.addToCache(baseTexture, imageUrl); + } + + return baseTexture; + } else if (source instanceof HTMLCanvasElement) { + return BaseTexture.fromCanvas(source, scaleMode); + } + + // lets assume its a base texture! + return source; + }; + + /** + * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache. + * @param {string} id - The id that the BaseTexture will be stored against. + */ + + + BaseTexture.addToCache = function addToCache(baseTexture, id) { + if (id) { + if (baseTexture.textureCacheIds.indexOf(id) === -1) { + baseTexture.textureCacheIds.push(id); + } + + /* eslint-disable no-console */ + if (_utils.BaseTextureCache[id]) { + console.warn('BaseTexture added to the cache with an id [' + id + '] that already had an entry'); + } + /* eslint-enable no-console */ + + _utils.BaseTextureCache[id] = baseTexture; + } + }; + + /** + * Remove a BaseTexture from the global BaseTextureCache. + * + * @static + * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself. + * @return {PIXI.BaseTexture|null} The BaseTexture that was removed. + */ + + + BaseTexture.removeFromCache = function removeFromCache(baseTexture) { + if (typeof baseTexture === 'string') { + var baseTextureFromCache = _utils.BaseTextureCache[baseTexture]; + + if (baseTextureFromCache) { + var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); + + if (index > -1) { + baseTextureFromCache.textureCacheIds.splice(index, 1); + } + + delete _utils.BaseTextureCache[baseTexture]; + + return baseTextureFromCache; + } + } else if (baseTexture && baseTexture.textureCacheIds) { + for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { + delete _utils.BaseTextureCache[baseTexture.textureCacheIds[i]]; + } + + baseTexture.textureCacheIds.length = 0; + + return baseTexture; + } + + return null; + }; + + return BaseTexture; +}(_eventemitter2.default); + +exports.default = BaseTexture; + +},{"../settings":101,"../utils":125,"../utils/determineCrossOrigin":124,"bit-twiddle":1,"eventemitter3":3}],113:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseRenderTexture = require('./BaseRenderTexture'); + +var _BaseRenderTexture2 = _interopRequireDefault(_BaseRenderTexture); + +var _Texture2 = require('./Texture'); + +var _Texture3 = _interopRequireDefault(_Texture2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let renderTexture = PIXI.RenderTexture.create(800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let renderTexture = new PIXI.RenderTexture.create(100, 100); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.Texture + * @memberof PIXI + */ +var RenderTexture = function (_Texture) { + _inherits(RenderTexture, _Texture); + + /** + * @param {PIXI.BaseRenderTexture} baseRenderTexture - The renderer used for this RenderTexture + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + */ + function RenderTexture(baseRenderTexture, frame) { + _classCallCheck(this, RenderTexture); + + // support for legacy.. + var _legacyRenderer = null; + + if (!(baseRenderTexture instanceof _BaseRenderTexture2.default)) { + /* eslint-disable prefer-rest-params, no-console */ + var width = arguments[1]; + var height = arguments[2]; + var scaleMode = arguments[3]; + var resolution = arguments[4]; + + // we have an old render texture.. + console.warn('Please use RenderTexture.create(' + width + ', ' + height + ') instead of the ctor directly.'); + _legacyRenderer = arguments[0]; + /* eslint-enable prefer-rest-params, no-console */ + + frame = null; + baseRenderTexture = new _BaseRenderTexture2.default(width, height, scaleMode, resolution); + } + + /** + * The base texture object that this texture uses + * + * @member {BaseTexture} + */ + + var _this = _possibleConstructorReturn(this, _Texture.call(this, baseRenderTexture, frame)); + + _this.legacyRenderer = _legacyRenderer; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = true; + + _this._updateUvs(); + return _this; + } + + /** + * Resizes the RenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + * @param {boolean} doNotResizeBaseTexture - Should the baseTexture.width and height values be resized as well? + */ + + + RenderTexture.prototype.resize = function resize(width, height, doNotResizeBaseTexture) { + width = Math.ceil(width); + height = Math.ceil(height); + + // TODO - could be not required.. + this.valid = width > 0 && height > 0; + + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + + if (!doNotResizeBaseTexture) { + this.baseTexture.resize(width, height); + } + + this._updateUvs(); + }; + + /** + * A short hand way of creating a render texture. + * + * @param {number} [width=100] - The width of the render texture + * @param {number} [height=100] - The height of the render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.RenderTexture} The new render texture + */ + + + RenderTexture.create = function create(width, height, scaleMode, resolution) { + return new RenderTexture(new _BaseRenderTexture2.default(width, height, scaleMode, resolution)); + }; + + return RenderTexture; +}(_Texture3.default); + +exports.default = RenderTexture; + +},{"./BaseRenderTexture":111,"./Texture":115}],114:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _ = require('../'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Utility class for maintaining reference to a collection + * of Textures on a single Spritesheet. + * + * @class + * @memberof PIXI + */ +var Spritesheet = function () { + _createClass(Spritesheet, null, [{ + key: 'BATCH_SIZE', + + /** + * The maximum number of Textures to build per process. + * + * @type {number} + * @default 1000 + */ + get: function get() { + return 1000; + } + + /** + * @param {PIXI.BaseTexture} baseTexture Reference to the source BaseTexture object. + * @param {Object} data - Spritesheet image data. + * @param {string} [resolutionFilename] - The filename to consider when determining + * the resolution of the spritesheet. If not provided, the imageUrl will + * be used on the BaseTexture. + */ + + }]); + + function Spritesheet(baseTexture, data) { + var resolutionFilename = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + _classCallCheck(this, Spritesheet); + + /** + * Reference to ths source texture + * @type {PIXI.BaseTexture} + */ + this.baseTexture = baseTexture; + + /** + * Map of spritesheet textures. + * @type {Object} + */ + this.textures = {}; + + /** + * Reference to the original JSON data. + * @type {Object} + */ + this.data = data; + + /** + * The resolution of the spritesheet. + * @type {number} + */ + this.resolution = this._updateResolution(resolutionFilename || this.baseTexture.imageUrl); + + /** + * Map of spritesheet frames. + * @type {Object} + * @private + */ + this._frames = this.data.frames; + + /** + * Collection of frame names. + * @type {string[]} + * @private + */ + this._frameKeys = Object.keys(this._frames); + + /** + * Current batch index being processed. + * @type {number} + * @private + */ + this._batchIndex = 0; + + /** + * Callback when parse is completed. + * @type {Function} + * @private + */ + this._callback = null; + } + + /** + * Generate the resolution from the filename or fallback + * to the meta.scale field of the JSON data. + * + * @private + * @param {string} resolutionFilename - The filename to use for resolving + * the default resolution. + * @return {number} Resolution to use for spritesheet. + */ + + + Spritesheet.prototype._updateResolution = function _updateResolution(resolutionFilename) { + var scale = this.data.meta.scale; + + // Use a defaultValue of `null` to check if a url-based resolution is set + var resolution = (0, _utils.getResolutionOfUrl)(resolutionFilename, null); + + // No resolution found via URL + if (resolution === null) { + // Use the scale value or default to 1 + resolution = scale !== undefined ? parseFloat(scale) : 1; + } + + // For non-1 resolutions, update baseTexture + if (resolution !== 1) { + this.baseTexture.resolution = resolution; + this.baseTexture.update(); + } + + return resolution; + }; + + /** + * Parser spritesheet from loaded data. This is done asynchronously + * to prevent creating too many Texture within a single process. + * + * @param {Function} callback - Callback when complete returns + * a map of the Textures for this spritesheet. + */ + + + Spritesheet.prototype.parse = function parse(callback) { + this._batchIndex = 0; + this._callback = callback; + + if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) { + this._processFrames(0); + this._parseComplete(); + } else { + this._nextBatch(); + } + }; + + /** + * Process a batch of frames + * + * @private + * @param {number} initialFrameIndex - The index of frame to start. + */ + + + Spritesheet.prototype._processFrames = function _processFrames(initialFrameIndex) { + var frameIndex = initialFrameIndex; + var maxFrames = Spritesheet.BATCH_SIZE; + var sourceScale = this.baseTexture.sourceScale; + + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { + var i = this._frameKeys[frameIndex]; + var rect = this._frames[i].frame; + + if (rect) { + var frame = null; + var trim = null; + var orig = new _.Rectangle(0, 0, Math.floor(this._frames[i].sourceSize.w * sourceScale) / this.resolution, Math.floor(this._frames[i].sourceSize.h * sourceScale) / this.resolution); + + if (this._frames[i].rotated) { + frame = new _.Rectangle(Math.floor(rect.x * sourceScale) / this.resolution, Math.floor(rect.y * sourceScale) / this.resolution, Math.floor(rect.h * sourceScale) / this.resolution, Math.floor(rect.w * sourceScale) / this.resolution); + } else { + frame = new _.Rectangle(Math.floor(rect.x * sourceScale) / this.resolution, Math.floor(rect.y * sourceScale) / this.resolution, Math.floor(rect.w * sourceScale) / this.resolution, Math.floor(rect.h * sourceScale) / this.resolution); + } + + // Check to see if the sprite is trimmed + if (this._frames[i].trimmed) { + trim = new _.Rectangle(Math.floor(this._frames[i].spriteSourceSize.x * sourceScale) / this.resolution, Math.floor(this._frames[i].spriteSourceSize.y * sourceScale) / this.resolution, Math.floor(rect.w * sourceScale) / this.resolution, Math.floor(rect.h * sourceScale) / this.resolution); + } + + this.textures[i] = new _.Texture(this.baseTexture, frame, orig, trim, this._frames[i].rotated ? 2 : 0); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage functions + _.Texture.addToCache(this.textures[i], i); + } + + frameIndex++; + } + }; + + /** + * The parse has completed. + * + * @private + */ + + + Spritesheet.prototype._parseComplete = function _parseComplete() { + var callback = this._callback; + + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); + }; + + /** + * Begin the next batch of textures. + * + * @private + */ + + + Spritesheet.prototype._nextBatch = function _nextBatch() { + var _this = this; + + this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); + this._batchIndex++; + setTimeout(function () { + if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { + _this._nextBatch(); + } else { + _this._parseComplete(); + } + }, 0); + }; + + /** + * Destroy Spritesheet and don't use after this. + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Spritesheet.prototype.destroy = function destroy() { + var destroyBase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + for (var i in this.textures) { + this.textures[i].destroy(); + } + this._frames = null; + this._frameKeys = null; + this.data = null; + this.textures = null; + if (destroyBase) { + this.baseTexture.destroy(); + } + this.baseTexture = null; + }; + + return Spritesheet; +}(); + +exports.default = Spritesheet; + +},{"../":65,"../utils":125}],115:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture = require('./BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _VideoBaseTexture = require('./VideoBaseTexture'); + +var _VideoBaseTexture2 = _interopRequireDefault(_VideoBaseTexture); + +var _TextureUvs = require('./TextureUvs'); + +var _TextureUvs2 = _interopRequireDefault(_TextureUvs); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided + * then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * let texture = PIXI.Texture.fromImage('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` + * + * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. + * You can check for this by checking the sprite's _textureID property. + * ```js + * var texture = PIXI.Texture.fromImage('assets/image.svg'); + * var sprite1 = new PIXI.Sprite(texture); + * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file + * ``` + * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var Texture = function (_EventEmitter) { + _inherits(Texture, _EventEmitter); + + /** + * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + * @param {PIXI.Rectangle} [orig] - The area of original texture + * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture + * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8} + */ + function Texture(baseTexture, frame, orig, trim, rotate) { + _classCallCheck(this, Texture); + + /** + * Does this Texture have any frame data assigned to it? + * + * @member {boolean} + */ + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.noFrame = false; + + if (!frame) { + _this.noFrame = true; + frame = new _math.Rectangle(0, 0, 1, 1); + } + + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @member {PIXI.BaseTexture} + */ + _this.baseTexture = baseTexture; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @member {PIXI.Rectangle} + */ + _this._frame = frame; + + /** + * This is the trimmed area of original texture, before it was put in atlas + * Please call `_updateUvs()` after you change coordinates of `trim` manually. + * + * @member {PIXI.Rectangle} + */ + _this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @member {boolean} + */ + _this.requiresUpdate = false; + + /** + * The WebGL UV data cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + _this._uvs = null; + + /** + * This is the area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + + _this._rotate = Number(rotate || 0); + + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); + } + + if (baseTexture.hasLoaded) { + if (_this.noFrame) { + frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + + // if there is no frame we should monitor for any base texture changes.. + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + _this.frame = frame; + } else { + baseTexture.once('loaded', _this.onBaseTextureLoaded, _this); + } + + /** + * Fired when the texture is updated. This happens if the frame or the baseTexture is updated. + * + * @event PIXI.Texture#update + * @protected + * @param {PIXI.Texture} texture - Instance of texture being updated. + */ + + _this._updateID = 0; + + /** + * Contains data for uvs. May contain clamp settings and some matrices. + * Its a bit heavy, so by default that object is not created. + * @type {PIXI.TextureMatrix} + * @default null + */ + _this.transform = null; + + /** + * The ids under which this Texture has been added to the texture cache. This is + * automatically set as long as Texture.addToCache is used, but may not be set if a + * Texture is added directly to the TextureCache array. + * + * @member {string[]} + */ + _this.textureCacheIds = []; + return _this; + } + + /** + * Updates this texture on the gpu. + * + */ + + + Texture.prototype.update = function update() { + this.baseTexture.update(); + }; + + /** + * Called when the base texture is loaded + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureLoaded = function onBaseTextureLoaded(baseTexture) { + this._updateID++; + + // TODO this code looks confusing.. boo to abusing getters and setters! + if (this.noFrame) { + this.frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } else { + this.frame = this._frame; + } + + this.baseTexture.on('update', this.onBaseTextureUpdated, this); + this.emit('update', this); + }; + + /** + * Called when the base texture is updated + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated(baseTexture) { + this._updateID++; + + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Texture.prototype.destroy = function destroy(destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destroyed too.. + if (_utils.TextureCache[this.baseTexture.imageUrl]) { + Texture.removeFromCache(this.baseTexture.imageUrl); + } + + this.baseTexture.destroy(); + } + + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); + + this.baseTexture = null; + } + + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + + this.valid = false; + + Texture.removeFromCache(this); + this.textureCacheIds = null; + }; + + /** + * Creates a new texture object that acts the same as this one. + * + * @return {PIXI.Texture} The new texture + */ + + + Texture.prototype.clone = function clone() { + return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); + }; + + /** + * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture. + */ + + + Texture.prototype._updateUvs = function _updateUvs() { + if (!this._uvs) { + this._uvs = new _TextureUvs2.default(); + } + + this._uvs.set(this._frame, this.baseTexture, this.rotate); + + this._updateID++; + }; + + /** + * Helper function that creates a Texture object from the given image url. + * If the image is not in the texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var texture = _utils.TextureCache[imageUrl]; + + if (!texture) { + texture = new Texture(_BaseTexture2.default.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); + Texture.addToCache(texture, imageUrl); + } + + return texture; + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return texture; + }; + + /** + * Helper function that creates a new Texture based on the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {string} [origin='canvas'] - A string origin of who created the base texture + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromCanvas = function fromCanvas(canvas, scaleMode) { + var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; + + return new Texture(_BaseTexture2.default.fromCanvas(canvas, scaleMode, origin)); + }; + + /** + * Helper function that creates a new Texture based on the given video element. + * + * @static + * @param {HTMLVideoElement|string} video - The URL or actual element of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideo = function fromVideo(video, scaleMode) { + if (typeof video === 'string') { + return Texture.fromVideoUrl(video, scaleMode); + } + + return new Texture(_VideoBaseTexture2.default.fromVideo(video, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the video url. + * + * @static + * @param {string} videoUrl - URL of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideoUrl = function fromVideoUrl(videoUrl, scaleMode) { + return new Texture(_VideoBaseTexture2.default.fromUrl(videoUrl, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} + * source - Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.from = function from(source) { + // TODO auto detect cross origin.. + // TODO pass in scale mode? + if (typeof source === 'string') { + var texture = _utils.TextureCache[source]; + + if (!texture) { + // check if its a video.. + var isVideo = source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/) !== null; + + if (isVideo) { + return Texture.fromVideoUrl(source); + } + + return Texture.fromImage(source); + } + + return texture; + } else if (source instanceof HTMLImageElement) { + return new Texture(_BaseTexture2.default.from(source)); + } else if (source instanceof HTMLCanvasElement) { + return Texture.fromCanvas(source, _settings2.default.SCALE_MODE, 'HTMLCanvasElement'); + } else if (source instanceof HTMLVideoElement) { + return Texture.fromVideo(source); + } else if (source instanceof _BaseTexture2.default) { + return new Texture(source); + } + + // lets assume its a texture! + return source; + }; + + /** + * Create a texture from a source and add to the cache. + * + * @static + * @param {HTMLImageElement|HTMLCanvasElement} source - The input source. + * @param {String} imageUrl - File name of texture, for cache and resolving resolution. + * @param {String} [name] - Human readible name for the texture cache. If no name is + * specified, only `imageUrl` will be used as the cache ID. + * @return {PIXI.Texture} Output texture + */ + + + Texture.fromLoader = function fromLoader(source, imageUrl, name) { + var baseTexture = new _BaseTexture2.default(source, undefined, (0, _utils.getResolutionOfUrl)(imageUrl)); + var texture = new Texture(baseTexture); + + baseTexture.imageUrl = imageUrl; + + // No name, use imageUrl instead + if (!name) { + name = imageUrl; + } + + // lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions + _BaseTexture2.default.addToCache(texture.baseTexture, name); + Texture.addToCache(texture, name); + + // also add references by url if they are different. + if (name !== imageUrl) { + _BaseTexture2.default.addToCache(texture.baseTexture, imageUrl); + Texture.addToCache(texture, imageUrl); + } + + return texture; + }; + + /** + * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the Texture will be stored against. + */ + + + Texture.addToCache = function addToCache(texture, id) { + if (id) { + if (texture.textureCacheIds.indexOf(id) === -1) { + texture.textureCacheIds.push(id); + } + + /* eslint-disable no-console */ + if (_utils.TextureCache[id]) { + console.warn('Texture added to the cache with an id [' + id + '] that already had an entry'); + } + /* eslint-enable no-console */ + + _utils.TextureCache[id] = texture; + } + }; + + /** + * Remove a Texture from the global TextureCache. + * + * @static + * @param {string|PIXI.Texture} texture - id of a Texture to be removed, or a Texture instance itself + * @return {PIXI.Texture|null} The Texture that was removed + */ + + + Texture.removeFromCache = function removeFromCache(texture) { + if (typeof texture === 'string') { + var textureFromCache = _utils.TextureCache[texture]; + + if (textureFromCache) { + var index = textureFromCache.textureCacheIds.indexOf(texture); + + if (index > -1) { + textureFromCache.textureCacheIds.splice(index, 1); + } + + delete _utils.TextureCache[texture]; + + return textureFromCache; + } + } else if (texture && texture.textureCacheIds) { + for (var i = 0; i < texture.textureCacheIds.length; ++i) { + // Check that texture matches the one being passed in before deleting it from the cache. + if (_utils.TextureCache[texture.textureCacheIds[i]] === texture) { + delete _utils.TextureCache[texture.textureCacheIds[i]]; + } + } + + texture.textureCacheIds.length = 0; + + return texture; + } + + return null; + }; + + /** + * The frame specifies the region of the base texture that this texture uses. + * Please call `_updateUvs()` after you change coordinates of `frame` manually. + * + * @member {PIXI.Rectangle} + */ + + + _createClass(Texture, [{ + key: 'frame', + get: function get() { + return this._frame; + }, + set: function set(frame) // eslint-disable-line require-jsdoc + { + this._frame = frame; + + this.noFrame = false; + + var x = frame.x, + y = frame.y, + width = frame.width, + height = frame.height; + + var xNotFit = x + width > this.baseTexture.width; + var yNotFit = y + height > this.baseTexture.height; + + if (xNotFit || yNotFit) { + var relationship = xNotFit && yNotFit ? 'and' : 'or'; + var errorX = 'X: ' + x + ' + ' + width + ' = ' + (x + width) + ' > ' + this.baseTexture.width; + var errorY = 'Y: ' + y + ' + ' + height + ' = ' + (y + height) + ' > ' + this.baseTexture.height; + + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + (errorX + ' ' + relationship + ' ' + errorY)); + } + + // this.valid = width && height && this.baseTexture.source && this.baseTexture.hasLoaded; + this.valid = width && height && this.baseTexture.hasLoaded; + + if (!this.trim && !this.rotate) { + this.orig = frame; + } + + if (this.valid) { + this._updateUvs(); + } + } + + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.GroupD8} for explanation + * + * @member {number} + */ + + }, { + key: 'rotate', + get: function get() { + return this._rotate; + }, + set: function set(rotate) // eslint-disable-line require-jsdoc + { + this._rotate = rotate; + if (this.valid) { + this._updateUvs(); + } + } + + /** + * The width of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'width', + get: function get() { + return this.orig.width; + } + + /** + * The height of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.orig.height; + } + }]); + + return Texture; +}(_eventemitter2.default); + +exports.default = Texture; + + +function createWhiteTexture() { + var canvas = document.createElement('canvas'); + + canvas.width = 10; + canvas.height = 10; + + var context = canvas.getContext('2d'); + + context.fillStyle = 'white'; + context.fillRect(0, 0, 10, 10); + + return new Texture(new _BaseTexture2.default(canvas)); +} + +function removeAllHandlers(tex) { + tex.destroy = function _emptyDestroy() {/* empty */}; + tex.on = function _emptyOn() {/* empty */}; + tex.once = function _emptyOnce() {/* empty */}; + tex.emit = function _emptyEmit() {/* empty */}; +} + +/** + * An empty texture, used often to not have to create multiple empty textures. + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.EMPTY = new Texture(new _BaseTexture2.default()); +removeAllHandlers(Texture.EMPTY); +removeAllHandlers(Texture.EMPTY.baseTexture); + +/** + * A white texture of 10x10 size, used for graphics and other things + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.WHITE = createWhiteTexture(); +removeAllHandlers(Texture.WHITE); +removeAllHandlers(Texture.WHITE.baseTexture); + +},{"../math":70,"../settings":101,"../utils":125,"./BaseTexture":112,"./TextureUvs":117,"./VideoBaseTexture":118,"eventemitter3":3}],116:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Matrix = require('../math/Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var tempMat = new _Matrix2.default(); + +/** + * Class controls uv transform and frame clamp for texture + * Can be used in Texture "transform" field, or separately, you can use different clamp settings on the same texture. + * If you want to add support for texture region of certain feature or filter, that's what you're looking for. + * + * @see PIXI.Texture + * @see PIXI.mesh.Mesh + * @see PIXI.extras.TilingSprite + * @class + * @memberof PIXI + */ + +var TextureMatrix = function () { + /** + * + * @param {PIXI.Texture} texture observed texture + * @param {number} [clampMargin] Changes frame clamping, 0.5 by default. Use -0.5 for extra border. + * @constructor + */ + function TextureMatrix(texture, clampMargin) { + _classCallCheck(this, TextureMatrix); + + this._texture = texture; + + this.mapCoord = new _Matrix2.default(); + + this.uClampFrame = new Float32Array(4); + + this.uClampOffset = new Float32Array(2); + + this._lastTextureID = -1; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders + * + * @default 0 + * @member {number} + */ + this.clampOffset = 0; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + this.clampMargin = typeof clampMargin === 'undefined' ? 0.5 : clampMargin; + } + + /** + * texture property + * @member {PIXI.Texture} + */ + + + /** + * Multiplies uvs array to transform + * @param {Float32Array} uvs mesh uvs + * @param {Float32Array} [out=uvs] output + * @returns {Float32Array} output + */ + TextureMatrix.prototype.multiplyUvs = function multiplyUvs(uvs, out) { + if (out === undefined) { + out = uvs; + } + + var mat = this.mapCoord; + + for (var i = 0; i < uvs.length; i += 2) { + var x = uvs[i]; + var y = uvs[i + 1]; + + out[i] = x * mat.a + y * mat.c + mat.tx; + out[i + 1] = x * mat.b + y * mat.d + mat.ty; + } + + return out; + }; + + /** + * updates matrices if texture was changed + * @param {boolean} forceUpdate if true, matrices will be updated any case + * @returns {boolean} whether or not it was updated + */ + + + TextureMatrix.prototype.update = function update(forceUpdate) { + var tex = this._texture; + + if (!tex || !tex.valid) { + return false; + } + + if (!forceUpdate && this._lastTextureID === tex._updateID) { + return false; + } + + this._lastTextureID = tex._updateID; + + var uvs = tex._uvs; + + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + + var orig = tex.orig; + var trim = tex.trim; + + if (trim) { + tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat); + } + + var texBase = tex.baseTexture; + var frame = this.uClampFrame; + var margin = this.clampMargin / texBase.resolution; + var offset = this.clampOffset; + + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.uClampOffset[0] = offset / texBase.realWidth; + this.uClampOffset[1] = offset / texBase.realHeight; + + return true; + }; + + _createClass(TextureMatrix, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._texture = value; + this._lastTextureID = -1; + } + }]); + + return TextureMatrix; +}(); + +exports.default = TextureMatrix; + +},{"../math/Matrix":67}],117:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _GroupD = require('../math/GroupD8'); + +var _GroupD2 = _interopRequireDefault(_GroupD); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A standard object to store the Uvs of a texture + * + * @class + * @private + * @memberof PIXI + */ +var TextureUvs = function () { + /** + * + */ + function TextureUvs() { + _classCallCheck(this, TextureUvs); + + this.x0 = 0; + this.y0 = 0; + + this.x1 = 1; + this.y1 = 0; + + this.x2 = 1; + this.y2 = 1; + + this.x3 = 0; + this.y3 = 1; + + this.uvsUint32 = new Uint32Array(4); + } + + /** + * Sets the texture Uvs based on the given frame information. + * + * @private + * @param {PIXI.Rectangle} frame - The frame of the texture + * @param {PIXI.Rectangle} baseFrame - The base frame of the texture + * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8} + */ + + + TextureUvs.prototype.set = function set(frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + + // coordinates of center + var cX = frame.x / tw + w2; + var cY = frame.y / th + h2; + + rotate = _GroupD2.default.add(rotate, _GroupD2.default.NW); // NW is top-left corner + this.x0 = cX + w2 * _GroupD2.default.uX(rotate); + this.y0 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + w2 * _GroupD2.default.uX(rotate); + this.y1 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x2 = cX + w2 * _GroupD2.default.uX(rotate); + this.y2 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x3 = cX + w2 * _GroupD2.default.uX(rotate); + this.y3 = cY + h2 * _GroupD2.default.uY(rotate); + } else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + + this.uvsUint32[0] = (this.y0 * 65535 & 0xFFFF) << 16 | this.x0 * 65535 & 0xFFFF; + this.uvsUint32[1] = (this.y1 * 65535 & 0xFFFF) << 16 | this.x1 * 65535 & 0xFFFF; + this.uvsUint32[2] = (this.y2 * 65535 & 0xFFFF) << 16 | this.x2 * 65535 & 0xFFFF; + this.uvsUint32[3] = (this.y3 * 65535 & 0xFFFF) << 16 | this.x3 * 65535 & 0xFFFF; + }; + + return TextureUvs; +}(); + +exports.default = TextureUvs; + +},{"../math/GroupD8":66}],118:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _utils = require('../utils'); + +var _ticker = require('../ticker'); + +var _const = require('../const'); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture of a [playing] Video. + * + * Video base textures mimic PixiJS BaseTexture.from.... method in their creation process. + * + * This can be used in several ways, such as: + * + * ```js + * let texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4'); + * + * let texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' }); + * + * let texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']); + * + * let texture = PIXI.VideoBaseTexture.fromUrls([ + * { src: '/video.webm', mime: 'video/webm' }, + * { src: '/video.mp4', mime: 'video/mp4' } + * ]); + * ``` + * + * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/). + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var VideoBaseTexture = function (_BaseTexture) { + _inherits(VideoBaseTexture, _BaseTexture); + + /** + * @param {HTMLVideoElement} source - Video source + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + */ + function VideoBaseTexture(source, scaleMode) { + _classCallCheck(this, VideoBaseTexture); + + if (!source) { + throw new Error('No video source element specified.'); + } + + // hook in here to check if video is already available. + // BaseTexture looks for a source.complete boolean, plus width & height. + + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + source.complete = true; + } + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, source, scaleMode)); + + _this.width = source.videoWidth; + _this.height = source.videoHeight; + + _this._autoUpdate = true; + _this._isAutoUpdating = false; + + /** + * When set to true will automatically play videos used by this texture once + * they are loaded. If false, it will not modify the playing state. + * + * @member {boolean} + * @default true + */ + _this.autoPlay = true; + + _this.update = _this.update.bind(_this); + _this._onCanPlay = _this._onCanPlay.bind(_this); + + source.addEventListener('play', _this._onPlayStart.bind(_this)); + source.addEventListener('pause', _this._onPlayStop.bind(_this)); + _this.hasLoaded = false; + _this.__loaded = false; + + if (!_this._isSourceReady()) { + source.addEventListener('canplay', _this._onCanPlay); + source.addEventListener('canplaythrough', _this._onCanPlay); + } else { + _this._onCanPlay(); + } + return _this; + } + + /** + * Returns true if the underlying source is playing. + * + * @private + * @return {boolean} True if playing. + */ + + + VideoBaseTexture.prototype._isSourcePlaying = function _isSourcePlaying() { + var source = this.source; + + return source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2; + }; + + /** + * Returns true if the underlying source is ready for playing. + * + * @private + * @return {boolean} True if ready. + */ + + + VideoBaseTexture.prototype._isSourceReady = function _isSourceReady() { + return this.source.readyState === 3 || this.source.readyState === 4; + }; + + /** + * Runs the update loop when the video is ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStart = function _onPlayStart() { + // Just in case the video has not received its can play even yet.. + if (!this.hasLoaded) { + this._onCanPlay(); + } + + if (!this._isAutoUpdating && this.autoUpdate) { + _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); + this._isAutoUpdating = true; + } + }; + + /** + * Fired when a pause event is triggered, stops the update loop + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStop = function _onPlayStop() { + if (this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } + }; + + /** + * Fired when the video is loaded and ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onCanPlay = function _onCanPlay() { + this.hasLoaded = true; + + if (this.source) { + this.source.removeEventListener('canplay', this._onCanPlay); + this.source.removeEventListener('canplaythrough', this._onCanPlay); + + this.width = this.source.videoWidth; + this.height = this.source.videoHeight; + + // prevent multiple loaded dispatches.. + if (!this.__loaded) { + this.__loaded = true; + this.emit('loaded', this); + } + + if (this._isSourcePlaying()) { + this._onPlayStart(); + } else if (this.autoPlay) { + this.source.play(); + } + } + }; + + /** + * Destroys this texture + * + */ + + + VideoBaseTexture.prototype.destroy = function destroy() { + if (this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + } + + if (this.source && this.source._pixiId) { + _BaseTexture3.default.removeFromCache(this.source._pixiId); + delete this.source._pixiId; + + this.source.pause(); + this.source.src = ''; + this.source.load(); + } + + _BaseTexture.prototype.destroy.call(this); + }; + + /** + * Mimic PixiJS BaseTexture.from.... method. + * + * @static + * @param {HTMLVideoElement} video - Video to create texture from + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromVideo = function fromVideo(video, scaleMode) { + if (!video._pixiId) { + video._pixiId = 'video_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[video._pixiId]; + + if (!baseTexture) { + baseTexture = new VideoBaseTexture(video, scaleMode); + _BaseTexture3.default.addToCache(baseTexture, video._pixiId); + } + + return baseTexture; + }; + + /** + * Helper function that creates a new BaseTexture based on the given video element. + * This BaseTexture can then be used to create a texture + * + * @static + * @param {string|object|string[]|object[]} videoSrc - The URL(s) for the video. + * @param {string} [videoSrc.src] - One of the source urls for the video + * @param {string} [videoSrc.mime] - The mimetype of the video (e.g. 'video/mp4'). If not specified + * the url's extension will be used as the second part of the mime type. + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromUrl = function fromUrl(videoSrc, scaleMode, crossorigin) { + var video = document.createElement('video'); + + video.setAttribute('webkit-playsinline', ''); + video.setAttribute('playsinline', ''); + + var url = Array.isArray(videoSrc) ? videoSrc[0].src || videoSrc[0] : videoSrc.src || videoSrc; + + if (crossorigin === undefined && url.indexOf('data:') !== 0) { + video.crossOrigin = (0, _determineCrossOrigin2.default)(url); + } else if (crossorigin) { + video.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; + } + + // array of objects or strings + if (Array.isArray(videoSrc)) { + for (var i = 0; i < videoSrc.length; ++i) { + video.appendChild(createSource(videoSrc[i].src || videoSrc[i], videoSrc[i].mime)); + } + } + // single object or string + else { + video.appendChild(createSource(url, videoSrc.mime)); + } + + video.load(); + + return VideoBaseTexture.fromVideo(video, scaleMode); + }; + + /** + * Should the base texture automatically update itself, set to true by default + * + * @member {boolean} + */ + + + _createClass(VideoBaseTexture, [{ + key: 'autoUpdate', + get: function get() { + return this._autoUpdate; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + + if (!this._autoUpdate && this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } else if (this._autoUpdate && !this._isAutoUpdating) { + _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); + this._isAutoUpdating = true; + } + } + } + }]); + + return VideoBaseTexture; +}(_BaseTexture3.default); + +exports.default = VideoBaseTexture; + + +VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; + +function createSource(path, type) { + if (!type) { + type = 'video/' + path.substr(path.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = path; + source.type = type; + + return source; +} + +},{"../const":46,"../ticker":121,"../utils":125,"../utils/determineCrossOrigin":124,"./BaseTexture":112}],119:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _const = require('../const'); + +var _TickerListener = require('./TickerListener'); + +var _TickerListener2 = _interopRequireDefault(_TickerListener); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A Ticker class that runs an update loop that other objects listen to. + * This class is composed around listeners + * meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, + * e.g. When the ticker is started and the emitter has listeners. + * + * @class + * @memberof PIXI.ticker + */ +var Ticker = function () { + /** + * + */ + function Ticker() { + var _this = this; + + _classCallCheck(this, Ticker); + + /** + * The first listener. All new listeners added are chained on this. + * @private + * @type {TickerListener} + */ + this._head = new _TickerListener2.default(null, null, Infinity); + + /** + * Internal current frame request ID + * @private + */ + this._requestId = null; + + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + * @private + */ + this._maxElapsedMS = 100; + + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.ticker.Ticker#start} automatically + * when a listener is added. + * + * @member {boolean} + * @default false + */ + this.autoStart = false; + + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS} + * and is scaled with {@link PIXI.ticker.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * + * @member {number} + * @default 1 + */ + this.deltaTime = 1; + + /** + * Time elapsed in milliseconds from last frame to this frame. + * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime} + * is based, this value is neither capped nor scaled. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * Defaults to target frame time + * + * @member {number} + * @default 16.66 + */ + this.elapsedMS = 1 / _settings2.default.TARGET_FPMS; + + /** + * The last time {@link PIXI.ticker.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default -1 + */ + this.lastTime = -1; + + /** + * Factor of current {@link PIXI.ticker.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + * + * @member {number} + * @default 1 + */ + this.speed = 1; + + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.ticker.Ticker#start} has been called. + * `false` if {@link PIXI.ticker.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.ticker.Ticker#autoStart} being `true` + * and a listener is added. + * + * @member {boolean} + * @default false + */ + this.started = false; + + /** + * Internal tick method bound to ticker instance. + * This is because in early 2015, Function.bind + * is still 60% slower in high performance scenarios. + * Also separating frame requests from update method + * so listeners may be called at any time and with + * any animation API, just invoke ticker.update(time). + * + * @private + * @param {number} time - Time since last tick. + */ + this._tick = function (time) { + _this._requestId = null; + + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._head.next) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * + * @private + */ + + + Ticker.prototype._requestIfNeeded = function _requestIfNeeded() { + if (this._requestId === null && this._head.next) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._requestId = requestAnimationFrame(this._tick); + } + }; + + /** + * Conditionally cancels a pending animation frame. + * + * @private + */ + + + Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; + + /** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * + * @private + */ + + + Ticker.prototype._startIfPossible = function _startIfPossible() { + if (this.started) { + this._requestIfNeeded(); + } else if (this.autoStart) { + this.start(); + } + }; + + /** + * Register a handler for tick events. Calls continuously unless + * it is removed or the ticker is stopped. + * + * @param {Function} fn - The listener function to be added for updates + * @param {Function} [context] - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.add = function add(fn, context) { + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _const.UPDATE_PRIORITY.NORMAL; + + return this._addListener(new _TickerListener2.default(fn, context, priority)); + }; + + /** + * Add a handler for the tick event which is only execute once. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context] - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.addOnce = function addOnce(fn, context) { + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _const.UPDATE_PRIORITY.NORMAL; + + return this._addListener(new _TickerListener2.default(fn, context, priority, true)); + }; + + /** + * Internally adds the event handler so that it can be sorted by priority. + * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run + * before the rendering. + * + * @private + * @param {TickerListener} listener - Current listener being added. + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype._addListener = function _addListener(listener) { + // For attaching to head + var current = this._head.next; + var previous = this._head; + + // Add the first item + if (!current) { + listener.connect(previous); + } else { + // Go from highest to lowest priority + while (current) { + if (listener.priority > current.priority) { + listener.connect(previous); + break; + } + previous = current; + current = current.next; + } + + // Not yet connected + if (!listener.previous) { + listener.connect(previous); + } + } + + this._startIfPossible(); + + return this; + }; + + /** + * Removes any handlers matching the function and context parameters. + * If no handlers are left after removing, then it cancels the animation frame. + * + * @param {Function} fn - The listener function to be removed + * @param {Function} [context] - The listener context to be removed + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.remove = function remove(fn, context) { + var listener = this._head.next; + + while (listener) { + // We found a match, lets remove it + // no break to delete all possible matches + // incase a listener was added 2+ times + if (listener.match(fn, context)) { + listener = listener.destroy(); + } else { + listener = listener.next; + } + } + + if (!this._head.next) { + this._cancelIfNeeded(); + } + + return this; + }; + + /** + * Starts the ticker. If the ticker has listeners + * a new animation frame is requested at this point. + */ + + + Ticker.prototype.start = function start() { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + }; + + /** + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. + */ + + + Ticker.prototype.stop = function stop() { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; + + /** + * Destroy the ticker and don't use after this. Calling + * this method removes all references to internal events. + */ + + + Ticker.prototype.destroy = function destroy() { + this.stop(); + + var listener = this._head.next; + + while (listener) { + listener = listener.destroy(true); + } + + this._head.destroy(); + this._head = null; + }; + + /** + * Triggers an update. An update entails setting the + * current {@link PIXI.ticker.Ticker#elapsedMS}, + * the current {@link PIXI.ticker.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.ticker.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + + + Ticker.prototype.update = function update() { + var currentTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : performance.now(); + + var elapsedMS = void 0; + + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + + this.deltaTime = elapsedMS * _settings2.default.TARGET_FPMS * this.speed; + + // Cache a local reference, in-case ticker is destroyed + // during the emit, we can still check for head.next + var head = this._head; + + // Invoke listeners added to internal emitter + var listener = head.next; + + while (listener) { + listener = listener.emit(this.deltaTime); + } + + if (!head.next) { + this._cancelIfNeeded(); + } + } else { + this.deltaTime = this.elapsedMS = 0; + } + + this.lastTime = currentTime; + }; + + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.ticker.Ticker#speed}, which is specific + * to scaling {@link PIXI.ticker.Ticker#deltaTime}. + * + * @member {number} + * @readonly + */ + + + _createClass(Ticker, [{ + key: 'FPS', + get: function get() { + return 1000 / this.elapsedMS; + } + + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.ticker.Ticker#update}. + * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.settings.TARGET_FPMS * 1000`. + * + * @member {number} + * @default 10 + */ + + }, { + key: 'minFPS', + get: function get() { + return 1000 / this._maxElapsedMS; + }, + set: function set(fps) // eslint-disable-line require-jsdoc + { + // Clamp: 0 to TARGET_FPMS + var minFPMS = Math.min(Math.max(0, fps) / 1000, _settings2.default.TARGET_FPMS); + + this._maxElapsedMS = 1 / minFPMS; + } + }]); + + return Ticker; +}(); + +exports.default = Ticker; + +},{"../const":46,"../settings":101,"./TickerListener":120}],120:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Internal class for handling the priority sorting of ticker handlers. + * + * @private + * @class + * @memberof PIXI.ticker + */ +var TickerListener = function () { + /** + * Constructor + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context=null] - The listener context + * @param {number} [priority=0] - The priority for emitting + * @param {boolean} [once=false] - If the handler should fire once + */ + function TickerListener(fn) { + var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var once = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + _classCallCheck(this, TickerListener); + + /** + * The handler function to execute. + * @member {Function} + */ + this.fn = fn; + + /** + * The calling to execute. + * @member {Function} + */ + this.context = context; + + /** + * The current priority. + * @member {number} + */ + this.priority = priority; + + /** + * If this should only execute once. + * @member {boolean} + */ + this.once = once; + + /** + * The next item in chain. + * @member {TickerListener} + */ + this.next = null; + + /** + * The previous item in chain. + * @member {TickerListener} + */ + this.previous = null; + + /** + * `true` if this listener has been destroyed already. + * @member {boolean} + * @private + */ + this._destroyed = false; + } + + /** + * Simple compare function to figure out if a function and context match. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} context - The listener context + * @return {boolean} `true` if the listener match the arguments + */ + + + TickerListener.prototype.match = function match(fn, context) { + context = context || null; + + return this.fn === fn && this.context === context; + }; + + /** + * Emit by calling the current function. + * @param {number} deltaTime - time since the last emit. + * @return {TickerListener} Next ticker + */ + + + TickerListener.prototype.emit = function emit(deltaTime) { + if (this.fn) { + if (this.context) { + this.fn.call(this.context, deltaTime); + } else { + this.fn(deltaTime); + } + } + + var redirect = this.next; + + if (this.once) { + this.destroy(true); + } + + // Soft-destroying should remove + // the next reference + if (this._destroyed) { + this.next = null; + } + + return redirect; + }; + + /** + * Connect to the list. + * @param {TickerListener} previous - Input node, previous listener + */ + + + TickerListener.prototype.connect = function connect(previous) { + this.previous = previous; + if (previous.next) { + previous.next.previous = this; + } + this.next = previous.next; + previous.next = this; + }; + + /** + * Destroy and don't use after this. + * @param {boolean} [hard = false] `true` to remove the `next` reference, this + * is considered a hard destroy. Soft destroy maintains the next reference. + * @return {TickerListener} The listener to redirect while emitting or removing. + */ + + + TickerListener.prototype.destroy = function destroy() { + var hard = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + this._destroyed = true; + this.fn = null; + this.context = null; + + // Disconnect, hook up next and previous + if (this.previous) { + this.previous.next = this.next; + } + + if (this.next) { + this.next.previous = this.previous; + } + + // Redirect to the next item + var redirect = this.previous; + + // Remove references + this.next = hard ? null : redirect; + this.previous = null; + + return redirect; + }; + + return TickerListener; +}(); + +exports.default = TickerListener; + +},{}],121:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Ticker = exports.shared = undefined; + +var _Ticker = require('./Ticker'); + +var _Ticker2 = _interopRequireDefault(_Ticker); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The shared ticker instance used by {@link PIXI.extras.AnimatedSprite}. + * and by {@link PIXI.interaction.InteractionManager}. + * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` + * for this instance. Please follow the examples for usage, including + * how to opt-out of auto-starting the shared ticker. + * + * @example + * let ticker = PIXI.ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(800, 600); + * let stage = new PIXI.Container(); + * let interactionManager = PIXI.interaction.InteractionManager(renderer); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * + * @type {PIXI.ticker.Ticker} + * @memberof PIXI.ticker + */ +var shared = new _Ticker2.default(); + +shared.autoStart = true; +shared.destroy = function () { + // protect destroying shared ticker + // this is used by other internal systems + // like AnimatedSprite and InteractionManager +}; + +/** + * This namespace contains an API for interacting with PIXI's internal global update loop. + * + * This ticker is used for rendering, {@link PIXI.extras.AnimatedSprite AnimatedSprite}, + * {@link PIXI.interaction.InteractionManager InteractionManager} and many other time-based PIXI systems. + * @example + * const ticker = new PIXI.ticker.Ticker(); + * ticker.stop(); + * ticker.add((deltaTime) => { + * // do something every frame + * }); + * ticker.start(); + * @namespace PIXI.ticker + */ +exports.shared = shared; +exports.Ticker = _Ticker2.default; + +},{"./Ticker":119}],122:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = canUploadSameBuffer; +function canUploadSameBuffer() { + // Uploading the same buffer multiple times in a single frame can cause perf issues. + // Apparent on IOS so only check for that at the moment + // this check may become more complex if this issue pops up elsewhere. + var ios = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform); + + return !ios; +} + +},{}],123:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = createIndicesForQuads; +/** + * Generic Mask Stack data structure + * + * @memberof PIXI + * @function createIndicesForQuads + * @private + * @param {number} size - Number of quads + * @return {Uint16Array} indices + */ +function createIndicesForQuads(size) { + // the total number of indices in our array, there are 6 points per quad. + + var totalIndices = size * 6; + + var indices = new Uint16Array(totalIndices); + + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + indices[i + 0] = j + 0; + indices[i + 1] = j + 1; + indices[i + 2] = j + 2; + indices[i + 3] = j + 0; + indices[i + 4] = j + 2; + indices[i + 5] = j + 3; + } + + return indices; +} + +},{}],124:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = determineCrossOrigin; + +var _url2 = require('url'); + +var _url3 = _interopRequireDefault(_url2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var tempAnchor = void 0; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +function determineCrossOrigin(url) { + var loc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location; + + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url3.default.parse(tempAnchor.href); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +} + +},{"url":29}],125:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.premultiplyBlendMode = exports.BaseTextureCache = exports.TextureCache = exports.mixins = exports.pluginTarget = exports.EventEmitter = exports.removeItems = exports.isMobile = undefined; +exports.uid = uid; +exports.hex2rgb = hex2rgb; +exports.hex2string = hex2string; +exports.rgb2hex = rgb2hex; +exports.getResolutionOfUrl = getResolutionOfUrl; +exports.decomposeDataUri = decomposeDataUri; +exports.getUrlFileExtension = getUrlFileExtension; +exports.getSvgSize = getSvgSize; +exports.skipHello = skipHello; +exports.sayHello = sayHello; +exports.isWebGLSupported = isWebGLSupported; +exports.sign = sign; +exports.destroyTextureCache = destroyTextureCache; +exports.clearTextureCache = clearTextureCache; +exports.correctBlendMode = correctBlendMode; +exports.premultiplyTint = premultiplyTint; +exports.premultiplyRgba = premultiplyRgba; +exports.premultiplyTintToRgba = premultiplyTintToRgba; + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _pluginTarget = require('./pluginTarget'); + +var _pluginTarget2 = _interopRequireDefault(_pluginTarget); + +var _mixin = require('./mixin'); + +var mixins = _interopRequireWildcard(_mixin); + +var _ismobilejs = require('ismobilejs'); + +var isMobile = _interopRequireWildcard(_ismobilejs); + +var _removeArrayItems = require('remove-array-items'); + +var _removeArrayItems2 = _interopRequireDefault(_removeArrayItems); + +var _mapPremultipliedBlendModes = require('./mapPremultipliedBlendModes'); + +var _mapPremultipliedBlendModes2 = _interopRequireDefault(_mapPremultipliedBlendModes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var nextUid = 0; +var saidHello = false; + +/** + * Generalized convenience utilities for PIXI. + * @example + * // Extend PIXI's internal Event Emitter. + * class MyEmitter extends PIXI.utils.EventEmitter { + * constructor() { + * super(); + * console.log("Emitter created!"); + * } + * } + * + * // Get info on current device + * console.log(PIXI.utils.isMobile); + * + * // Convert hex color to string + * console.log(PIXI.utils.hex2string(0xff00ff)); // returns: "#ff00ff" + * @namespace PIXI.utils + */ +exports.isMobile = isMobile; +exports.removeItems = _removeArrayItems2.default; +exports.EventEmitter = _eventemitter2.default; +exports.pluginTarget = _pluginTarget2.default; +exports.mixins = mixins; + +/** + * Gets the next unique identifier + * + * @memberof PIXI.utils + * @function uid + * @return {number} The next unique identifier to use. + */ + +function uid() { + return ++nextUid; +} + +/** + * Converts a hex color number to an [R, G, B] array + * + * @memberof PIXI.utils + * @function hex2rgb + * @param {number} hex - The number to convert + * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one + * @return {number[]} An array representing the [R, G, B] of the color. + */ +function hex2rgb(hex, out) { + out = out || []; + + out[0] = (hex >> 16 & 0xFF) / 255; + out[1] = (hex >> 8 & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + + return out; +} + +/** + * Converts a hex color number to a string. + * + * @memberof PIXI.utils + * @function hex2string + * @param {number} hex - Number in hex + * @return {string} The string color. + */ +function hex2string(hex) { + hex = hex.toString(16); + hex = '000000'.substr(0, 6 - hex.length) + hex; + + return '#' + hex; +} + +/** + * Converts a color as an [R, G, B] array to a hex number + * + * @memberof PIXI.utils + * @function rgb2hex + * @param {number[]} rgb - rgb array + * @return {number} The color number + */ +function rgb2hex(rgb) { + return (rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + (rgb[2] * 255 | 0); +} + +/** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * + * @memberof PIXI.utils + * @function getResolutionOfUrl + * @param {string} url - the image path + * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. + * @return {number} resolution / device pixel ratio of an asset + */ +function getResolutionOfUrl(url, defaultValue) { + var resolution = _settings2.default.RETINA_PREFIX.exec(url); + + if (resolution) { + return parseFloat(resolution[1]); + } + + return defaultValue !== undefined ? defaultValue : 1; +} + +/** + * Typedef for decomposeDataUri return object. + * + * @typedef {object} DecomposedDataUri + * @property {mediaType} Media type, eg. `image` + * @property {subType} Sub type, eg. `png` + * @property {encoding} Data encoding, eg. `base64` + * @property {data} The actual data + */ + +/** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. + * + * @memberof PIXI.utils + * @function decomposeDataUri + * @param {string} dataUri - the data URI to check + * @return {DecomposedDataUri|undefined} The decomposed data uri or undefined + */ +function decomposeDataUri(dataUri) { + var dataUriMatch = _const.DATA_URI.exec(dataUri); + + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + encoding: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + data: dataUriMatch[4] + }; + } + + return undefined; +} + +/** + * Get type of the image by regexp for extension. Returns undefined for unknown extensions. + * + * @memberof PIXI.utils + * @function getUrlFileExtension + * @param {string} url - the image path + * @return {string|undefined} image extension + */ +function getUrlFileExtension(url) { + var extension = _const.URL_FILE_EXTENSION.exec(url); + + if (extension) { + return extension[1].toLowerCase(); + } + + return undefined; +} + +/** + * Typedef for Size object. + * + * @typedef {object} Size + * @property {width} Width component + * @property {height} Height component + */ + +/** + * Get size from an svg string using regexp. + * + * @memberof PIXI.utils + * @function getSvgSize + * @param {string} svgString - a serialized svg element + * @return {Size|undefined} image extension + */ +function getSvgSize(svgString) { + var sizeMatch = _const.SVG_SIZE.exec(svgString); + var size = {}; + + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); + size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); + } + + return size; +} + +/** + * Skips the hello message of renderers that are created after this is run. + * + * @function skipHello + * @memberof PIXI.utils + */ +function skipHello() { + saidHello = true; +} + +/** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever makes you a jerk face. + * + * @static + * @function sayHello + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ +function sayHello(type) { + if (saidHello) { + return; + } + + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = ['\n %c %c %c PixiJS ' + _const.VERSION + ' - \u2730 ' + type + ' \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n', 'background: #ff66a5; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff66a5; background: #030307; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'background: #ffc3dc; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;']; + + window.console.log.apply(console, args); + } else if (window.console) { + window.console.log('PixiJS ' + _const.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); + } + + saidHello = true; +} + +/** + * Helper for checking for webgl support + * + * @memberof PIXI.utils + * @function isWebGLSupported + * @return {boolean} is webgl supported + */ +function isWebGLSupported() { + var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; + + try { + if (!window.WebGLRenderingContext) { + return false; + } + + var canvas = document.createElement('canvas'); + var gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); + + var success = !!(gl && gl.getContextAttributes().stencil); + + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + + if (loseContext) { + loseContext.loseContext(); + } + } + + gl = null; + + return success; + } catch (e) { + return false; + } +} + +/** + * Returns sign of number + * + * @memberof PIXI.utils + * @function sign + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ +function sign(n) { + if (n === 0) return 0; + + return n < 0 ? -1 : 1; +} + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var TextureCache = exports.TextureCache = Object.create(null); + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var BaseTextureCache = exports.BaseTextureCache = Object.create(null); + +/** + * Destroys all texture in the cache + * + * @memberof PIXI.utils + * @function destroyTextureCache + */ +function destroyTextureCache() { + var key = void 0; + + for (key in TextureCache) { + TextureCache[key].destroy(); + } + for (key in BaseTextureCache) { + BaseTextureCache[key].destroy(); + } +} + +/** + * Removes all textures from cache, but does not destroy them + * + * @memberof PIXI.utils + * @function clearTextureCache + */ +function clearTextureCache() { + var key = void 0; + + for (key in TextureCache) { + delete TextureCache[key]; + } + for (key in BaseTextureCache) { + delete BaseTextureCache[key]; + } +} + +/** + * maps premultiply flag and blendMode to adjusted blendMode + * @memberof PIXI.utils + * @const premultiplyBlendMode + * @type {Array} + */ +var premultiplyBlendMode = exports.premultiplyBlendMode = (0, _mapPremultipliedBlendModes2.default)(); + +/** + * changes blendMode according to texture format + * + * @memberof PIXI.utils + * @function correctBlendMode + * @param {number} blendMode supposed blend mode + * @param {boolean} premultiplied whether source is premultiplied + * @returns {number} true blend mode for this texture + */ +function correctBlendMode(blendMode, premultiplied) { + return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; +} + +/** + * premultiplies tint + * + * @param {number} tint integet RGB + * @param {number} alpha floating point alpha (0.0-1.0) + * @returns {number} tint multiplied by alpha + */ +function premultiplyTint(tint, alpha) { + if (alpha === 1.0) { + return (alpha * 255 << 24) + tint; + } + if (alpha === 0.0) { + return 0; + } + var R = tint >> 16 & 0xFF; + var G = tint >> 8 & 0xFF; + var B = tint & 0xFF; + + R = R * alpha + 0.5 | 0; + G = G * alpha + 0.5 | 0; + B = B * alpha + 0.5 | 0; + + return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; +} + +/** + * combines rgb and alpha to out array + * + * @param {Float32Array|number[]} rgb input rgb + * @param {number} alpha alpha param + * @param {Float32Array} [out] output + * @param {boolean} [premultiply=true] do premultiply it + * @returns {Float32Array} vec4 rgba + */ +function premultiplyRgba(rgb, alpha, out, premultiply) { + out = out || new Float32Array(4); + if (premultiply || premultiply === undefined) { + out[0] = rgb[0] * alpha; + out[1] = rgb[1] * alpha; + out[2] = rgb[2] * alpha; + } else { + out[0] = rgb[0]; + out[1] = rgb[1]; + out[2] = rgb[2]; + } + out[3] = alpha; + + return out; +} + +/** + * converts integer tint and float alpha to vec4 form, premultiplies by default + * + * @param {number} tint input tint + * @param {number} alpha alpha param + * @param {Float32Array} [out] output + * @param {boolean} [premultiply=true] do premultiply it + * @returns {Float32Array} vec4 rgba + */ +function premultiplyTintToRgba(tint, alpha, out, premultiply) { + out = out || new Float32Array(4); + out[0] = (tint >> 16 & 0xFF) / 255.0; + out[1] = (tint >> 8 & 0xFF) / 255.0; + out[2] = (tint & 0xFF) / 255.0; + if (premultiply || premultiply === undefined) { + out[0] *= alpha; + out[1] *= alpha; + out[2] *= alpha; + } + out[3] = alpha; + + return out; +} + +},{"../const":46,"../settings":101,"./mapPremultipliedBlendModes":126,"./mixin":128,"./pluginTarget":129,"eventemitter3":3,"ismobilejs":4,"remove-array-items":31}],126:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapPremultipliedBlendModes; + +var _const = require('../const'); + +/** + * Corrects PixiJS blend, takes premultiplied alpha into account + * + * @memberof PIXI + * @function mapPremultipliedBlendModes + * @private + * @param {Array} [array] - The array to output into. + * @return {Array} Mapped modes. + */ + +function mapPremultipliedBlendModes() { + var pm = []; + var npm = []; + + for (var i = 0; i < 32; i++) { + pm[i] = i; + npm[i] = i; + } + + pm[_const.BLEND_MODES.NORMAL_NPM] = _const.BLEND_MODES.NORMAL; + pm[_const.BLEND_MODES.ADD_NPM] = _const.BLEND_MODES.ADD; + pm[_const.BLEND_MODES.SCREEN_NPM] = _const.BLEND_MODES.SCREEN; + + npm[_const.BLEND_MODES.NORMAL] = _const.BLEND_MODES.NORMAL_NPM; + npm[_const.BLEND_MODES.ADD] = _const.BLEND_MODES.ADD_NPM; + npm[_const.BLEND_MODES.SCREEN] = _const.BLEND_MODES.SCREEN_NPM; + + var array = []; + + array.push(npm); + array.push(pm); + + return array; +} + +},{"../const":46}],127:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = maxRecommendedTextures; + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function maxRecommendedTextures(max) { + if (_ismobilejs2.default.tablet || _ismobilejs2.default.phone) { + // check if the res is iphone 6 or higher.. + return 4; + } + + // desktop should be ok + return max; +} + +},{"ismobilejs":4}],128:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.mixin = mixin; +exports.delayMixin = delayMixin; +exports.performMixins = performMixins; +/** + * Mixes all enumerable properties and methods from a source object to a target object. + * + * @memberof PIXI.utils.mixins + * @function mixin + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function mixin(target, source) { + if (!target || !source) return; + // in ES8/ES2017, this would be really easy: + // Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + + // get all the enumerable property keys + var keys = Object.keys(source); + + // loop through properties + for (var i = 0; i < keys.length; ++i) { + var propertyName = keys[i]; + + // Set the property using the property descriptor - this works for accessors and normal value properties + Object.defineProperty(target, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); + } +} + +var mixins = []; + +/** + * Queues a mixin to be handled towards the end of the initialization of PIXI, so that deprecation + * can take effect. + * + * @memberof PIXI.utils.mixins + * @function delayMixin + * @private + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function delayMixin(target, source) { + mixins.push(target, source); +} + +/** + * Handles all mixins queued via delayMixin(). + * + * @memberof PIXI.utils.mixins + * @function performMixins + * @private + */ +function performMixins() { + for (var i = 0; i < mixins.length; i += 2) { + mixin(mixins[i], mixins[i + 1]); + } + mixins.length = 0; +} + +},{}],129:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Mixins functionality to make an object have "plugins". + * + * @example + * function MyObject() {} + * + * pluginTarget.mixin(MyObject); + * + * @mixin + * @memberof PIXI.utils + * @param {object} obj - The object to mix into. + */ +function pluginTarget(obj) { + obj.__plugins = {}; + + /** + * Adds a plugin to an object + * + * @param {string} pluginName - The events that should be listed. + * @param {Function} ctor - The constructor function for the plugin. + */ + obj.registerPlugin = function registerPlugin(pluginName, ctor) { + obj.__plugins[pluginName] = ctor; + }; + + /** + * Instantiates all the plugins of this object + * + */ + obj.prototype.initPlugins = function initPlugins() { + this.plugins = this.plugins || {}; + + for (var o in obj.__plugins) { + this.plugins[o] = new obj.__plugins[o](this); + } + }; + + /** + * Removes all the plugins of this object + * + */ + obj.prototype.destroyPlugins = function destroyPlugins() { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + + this.plugins = null; + }; +} + +exports.default = { + /** + * Mixes in the properties of the pluginTarget into another object + * + * @param {object} obj - The obj to mix into + */ + mixin: function mixin(obj) { + pluginTarget(obj); + } +}; + +},{}],130:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = trimCanvas; +/** + * Trim transparent borders from a canvas + * + * @memberof PIXI + * @function trimCanvas + * @private + * @param {HTMLCanvasElement} canvas - the canvas to trim + * @returns {object} Trim data + */ +function trimCanvas(canvas) { + // https://gist.github.com/remy/784508 + + var width = canvas.width; + var height = canvas.height; + + var context = canvas.getContext('2d'); + var imageData = context.getImageData(0, 0, width, height); + var pixels = imageData.data; + var len = pixels.length; + + var bound = { + top: null, + left: null, + right: null, + bottom: null + }; + var i = void 0; + var x = void 0; + var y = void 0; + + for (i = 0; i < len; i += 4) { + if (pixels[i + 3] !== 0) { + x = i / 4 % width; + y = ~~(i / 4 / width); + + if (bound.top === null) { + bound.top = y; + } + + if (bound.left === null) { + bound.left = x; + } else if (x < bound.left) { + bound.left = x; + } + + if (bound.right === null) { + bound.right = x + 1; + } else if (bound.right < x) { + bound.right = x + 1; + } + + if (bound.bottom === null) { + bound.bottom = y; + } else if (bound.bottom < y) { + bound.bottom = y; + } + } + } + + width = bound.right - bound.left; + height = bound.bottom - bound.top + 1; + + var data = context.getImageData(bound.left, bound.top, width, height); + + return { + height: height, + width: width, + data: data + }; +} + +},{}],131:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = deprecation; +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code +function warn(msg) { + /* eslint-disable no-console */ + var stack = new Error().stack; + + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('Deprecation Warning: ', msg); + } else { + // chop off the stack trace which includes pixi.js internal calls + stack = stack.split('\n').splice(3).join('\n'); + + if (console.groupCollapsed) { + console.groupCollapsed('%cDeprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', msg); + console.warn(stack); + console.groupEnd(); + } else { + console.warn('Deprecation Warning: ', msg); + console.warn(stack); + } + } + /* eslint-enable no-console */ +} + +function deprecation(core) { + var mesh = core.mesh, + particles = core.particles, + extras = core.extras, + filters = core.filters, + prepare = core.prepare, + loaders = core.loaders, + interaction = core.interaction; + + + Object.defineProperties(core, { + + /** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ + SpriteBatch: { + get: function get() { + throw new ReferenceError('SpriteBatch does not exist any more, ' + 'please use the new ParticleContainer instead.'); + } + }, + + /** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in PixiJS v3, + * please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ + AssetLoader: { + get: function get() { + throw new ReferenceError('The loader system was overhauled in PixiJS v3, ' + 'please see the new PIXI.loaders.Loader class.'); + } + }, + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + Stage: { + get: function get() { + warn('You do not need to use a PIXI Stage any more, you can simply render any container.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + DisplayObjectContainer: { + get: function get() { + warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + Strip: { + get: function get() { + warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.'); + + return mesh.Mesh; + } + }, + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + Rope: { + get: function get() { + warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.'); + + return mesh.Rope; + } + }, + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + ParticleContainer: { + get: function get() { + warn('The ParticleContainer class has been moved to particles.ParticleContainer, ' + 'please use particles.ParticleContainer from now on.'); + + return particles.ParticleContainer; + } + }, + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + MovieClip: { + get: function get() { + warn('The MovieClip class has been moved to extras.AnimatedSprite, please use extras.AnimatedSprite.'); + + return extras.AnimatedSprite; + } + }, + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + TilingSprite: { + get: function get() { + warn('The TilingSprite class has been moved to extras.TilingSprite, ' + 'please use extras.TilingSprite from now on.'); + + return extras.TilingSprite; + } + }, + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + BitmapText: { + get: function get() { + warn('The BitmapText class has been moved to extras.BitmapText, ' + 'please use extras.BitmapText from now on.'); + + return extras.BitmapText; + } + }, + + /** + * @class + * @private + * @name blendModes + * @memberof PIXI + * @see PIXI.BLEND_MODES + * @deprecated since version 3.0.0 + */ + blendModes: { + get: function get() { + warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.'); + + return core.BLEND_MODES; + } + }, + + /** + * @class + * @private + * @name scaleModes + * @memberof PIXI + * @see PIXI.SCALE_MODES + * @deprecated since version 3.0.0 + */ + scaleModes: { + get: function get() { + warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.'); + + return core.SCALE_MODES; + } + }, + + /** + * @class + * @private + * @name BaseTextureCache + * @memberof PIXI + * @see PIXI.utils.BaseTextureCache + * @deprecated since version 3.0.0 + */ + BaseTextureCache: { + get: function get() { + warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, ' + 'please use utils.BaseTextureCache from now on.'); + + return core.utils.BaseTextureCache; + } + }, + + /** + * @class + * @private + * @name TextureCache + * @memberof PIXI + * @see PIXI.utils.TextureCache + * @deprecated since version 3.0.0 + */ + TextureCache: { + get: function get() { + warn('The TextureCache class has been moved to utils.TextureCache, ' + 'please use utils.TextureCache from now on.'); + + return core.utils.TextureCache; + } + }, + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + math: { + get: function get() { + warn('The math namespace is deprecated, please access members already accessible on PIXI.'); + + return core; + } + }, + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.Filter; + } + }, + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + TransformManual: { + get: function get() { + warn('TransformManual has been renamed to TransformBase, please update your pixi-spine'); + + return core.TransformBase; + } + }, + + /** + * @static + * @constant + * @name PIXI.TARGET_FPMS + * @see PIXI.settings.TARGET_FPMS + * @deprecated since version 4.2.0 + */ + TARGET_FPMS: { + get: function get() { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + return core.settings.TARGET_FPMS; + }, + set: function set(value) { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + core.settings.TARGET_FPMS = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.FILTER_RESOLUTION + * @see PIXI.settings.FILTER_RESOLUTION + * @deprecated since version 4.2.0 + */ + FILTER_RESOLUTION: { + get: function get() { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + return core.settings.FILTER_RESOLUTION; + }, + set: function set(value) { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + core.settings.FILTER_RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RESOLUTION + * @see PIXI.settings.RESOLUTION + * @deprecated since version 4.2.0 + */ + RESOLUTION: { + get: function get() { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + return core.settings.RESOLUTION; + }, + set: function set(value) { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + core.settings.RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.MIPMAP_TEXTURES + * @see PIXI.settings.MIPMAP_TEXTURES + * @deprecated since version 4.2.0 + */ + MIPMAP_TEXTURES: { + get: function get() { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + return core.settings.MIPMAP_TEXTURES; + }, + set: function set(value) { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + core.settings.MIPMAP_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_BATCH_SIZE + * @see PIXI.settings.SPRITE_BATCH_SIZE + * @deprecated since version 4.2.0 + */ + SPRITE_BATCH_SIZE: { + get: function get() { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + return core.settings.SPRITE_BATCH_SIZE; + }, + set: function set(value) { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + core.settings.SPRITE_BATCH_SIZE = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_MAX_TEXTURES + * @see PIXI.settings.SPRITE_MAX_TEXTURES + * @deprecated since version 4.2.0 + */ + SPRITE_MAX_TEXTURES: { + get: function get() { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + return core.settings.SPRITE_MAX_TEXTURES; + }, + set: function set(value) { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + core.settings.SPRITE_MAX_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RETINA_PREFIX + * @see PIXI.settings.RETINA_PREFIX + * @deprecated since version 4.2.0 + */ + RETINA_PREFIX: { + get: function get() { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + return core.settings.RETINA_PREFIX; + }, + set: function set(value) { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + core.settings.RETINA_PREFIX = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.DEFAULT_RENDER_OPTIONS + * @see PIXI.settings.RENDER_OPTIONS + * @deprecated since version 4.2.0 + */ + DEFAULT_RENDER_OPTIONS: { + get: function get() { + warn('PIXI.DEFAULT_RENDER_OPTIONS has been deprecated, please use PIXI.settings.DEFAULT_RENDER_OPTIONS'); + + return core.settings.RENDER_OPTIONS; + } + } + }); + + // Move the default properties to settings + var defaults = [{ parent: 'TRANSFORM_MODE', target: 'TRANSFORM_MODE' }, { parent: 'GC_MODES', target: 'GC_MODE' }, { parent: 'WRAP_MODES', target: 'WRAP_MODE' }, { parent: 'SCALE_MODES', target: 'SCALE_MODE' }, { parent: 'PRECISION', target: 'PRECISION_FRAGMENT' }]; + + var _loop = function _loop(i) { + var deprecation = defaults[i]; + + Object.defineProperty(core[deprecation.parent], 'DEFAULT', { + get: function get() { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); + + return core.settings[deprecation.target]; + }, + set: function set(value) { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); + + core.settings[deprecation.target] = value; + } + }); + }; + + for (var i = 0; i < defaults.length; i++) { + _loop(i); + } + + Object.defineProperties(core.settings, { + + /** + * @static + * @name PRECISION + * @memberof PIXI.settings + * @see PIXI.PRECISION + * @deprecated since version 4.4.0 + */ + PRECISION: { + get: function get() { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + return core.settings.PRECISION_FRAGMENT; + }, + set: function set(value) { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + core.settings.PRECISION_FRAGMENT = value; + } + } + }); + + if (extras.AnimatedSprite) { + Object.defineProperties(extras, { + + /** + * @class + * @name MovieClip + * @memberof PIXI.extras + * @see PIXI.extras.AnimatedSprite + * @deprecated since version 4.2.0 + */ + MovieClip: { + get: function get() { + warn('The MovieClip class has been renamed to AnimatedSprite, please use AnimatedSprite from now on.'); + + return extras.AnimatedSprite; + } + } + }); + } + + if (extras) { + Object.defineProperties(extras, { + /** + * @class + * @name TextureTransform + * @memberof PIXI.extras + * @see PIXI.TextureMatrix + * @deprecated since version 4.6.0 + */ + TextureTransform: { + get: function get() { + warn('The TextureTransform class has been renamed to TextureMatrix, ' + 'please use PIXI.TextureMatrix from now on.'); + + return core.TextureMatrix; + } + } + }); + } + + core.DisplayObject.prototype.generateTexture = function generateTexture(renderer, scaleMode, resolution) { + warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); + + return renderer.generateTexture(this, scaleMode, resolution); + }; + + core.Graphics.prototype.generateTexture = function generateTexture(scaleMode, resolution) { + warn('graphics generate texture has moved to the renderer. ' + 'Or to render a graphics to a texture using canvas please use generateCanvasTexture'); + + return this.generateCanvasTexture(scaleMode, resolution); + }; + + /** + * @method + * @name PIXI.GroupD8.isSwapWidthHeight + * @see PIXI.GroupD8.isVertical + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the direction is vertical + * @deprecated since version 4.6.0 + */ + core.GroupD8.isSwapWidthHeight = function isSwapWidthHeight(rotation) { + warn('GroupD8.isSwapWidthHeight was renamed to GroupD8.isVertical'); + + return core.GroupD8.isVertical(rotation); + }; + + core.RenderTexture.prototype.render = function render(displayObject, matrix, clear, updateTransform) { + this.legacyRenderer.render(displayObject, this, clear, matrix, !updateTransform); + warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)'); + }; + + core.RenderTexture.prototype.getImage = function getImage(target) { + warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); + + return this.legacyRenderer.extract.image(target); + }; + + core.RenderTexture.prototype.getBase64 = function getBase64(target) { + warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); + + return this.legacyRenderer.extract.base64(target); + }; + + core.RenderTexture.prototype.getCanvas = function getCanvas(target) { + warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); + + return this.legacyRenderer.extract.canvas(target); + }; + + core.RenderTexture.prototype.getPixels = function getPixels(target) { + warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); + + return this.legacyRenderer.pixels(target); + }; + + /** + * @method + * @private + * @name PIXI.Sprite#setTexture + * @see PIXI.Sprite#texture + * @deprecated since version 3.0.0 + * @param {PIXI.Texture} texture - The texture to set to. + */ + core.Sprite.prototype.setTexture = function setTexture(texture) { + this.texture = texture; + warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;'); + }; + + if (extras.BitmapText) { + /** + * @method + * @name PIXI.extras.BitmapText#setText + * @see PIXI.extras.BitmapText#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ + extras.BitmapText.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';'); + }; + } + + /** + * @method + * @name PIXI.Text#setText + * @see PIXI.Text#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ + core.Text.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';'); + }; + + /** + * Calculates the ascent, descent and fontSize of a given fontStyle + * + * @name PIXI.Text.calculateFontProperties + * @see PIXI.TextMetrics.measureFont + * @deprecated since version 4.5.0 + * @param {string} font - String representing the style of the font + * @return {Object} Font properties object + */ + core.Text.calculateFontProperties = function calculateFontProperties(font) { + warn('Text.calculateFontProperties is now deprecated, please use the TextMetrics.measureFont'); + + return core.TextMetrics.measureFont(font); + }; + + Object.defineProperties(core.Text, { + fontPropertiesCache: { + get: function get() { + warn('Text.fontPropertiesCache is deprecated'); + + return core.TextMetrics._fonts; + } + }, + fontPropertiesCanvas: { + get: function get() { + warn('Text.fontPropertiesCanvas is deprecated'); + + return core.TextMetrics._canvas; + } + }, + fontPropertiesContext: { + get: function get() { + warn('Text.fontPropertiesContext is deprecated'); + + return core.TextMetrics._context; + } + } + }); + + /** + * @method + * @name PIXI.Text#setStyle + * @see PIXI.Text#style + * @deprecated since version 3.0.0 + * @param {*} style - The style to set to. + */ + core.Text.prototype.setStyle = function setStyle(style) { + this.style = style; + warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;'); + }; + + /** + * @method + * @name PIXI.Text#determineFontProperties + * @see PIXI.Text#measureFontProperties + * @deprecated since version 4.2.0 + * @private + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ + core.Text.prototype.determineFontProperties = function determineFontProperties(fontStyle) { + warn('determineFontProperties is now deprecated, please use TextMetrics.measureFont method'); + + return core.TextMetrics.measureFont(fontStyle); + }; + + /** + * @method + * @name PIXI.Text.getFontStyle + * @see PIXI.TextMetrics.getFontStyle + * @deprecated since version 4.5.0 + * @param {PIXI.TextStyle} style - The style to use. + * @return {string} Font string + */ + core.Text.getFontStyle = function getFontStyle(style) { + warn('getFontStyle is now deprecated, please use TextStyle.toFontString() instead'); + + style = style || {}; + + if (!(style instanceof core.TextStyle)) { + style = new core.TextStyle(style); + } + + return style.toFontString(); + }; + + Object.defineProperties(core.TextStyle.prototype, { + /** + * Set all properties of a font as a single string + * + * @name PIXI.TextStyle#font + * @deprecated since version 4.0.0 + */ + font: { + get: function get() { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\', \'fontSize\', \'fontStyle\', \'fontVariant\' and \'fontWeight\' properties from now on'); + + var fontSizeString = typeof this._fontSize === 'number' ? this._fontSize + 'px' : this._fontSize; + + return this._fontStyle + ' ' + this._fontVariant + ' ' + this._fontWeight + ' ' + fontSizeString + ' ' + this._fontFamily; + }, + set: function set(font) { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + + // can work out fontStyle from search of whole string + if (font.indexOf('italic') > 1) { + this._fontStyle = 'italic'; + } else if (font.indexOf('oblique') > -1) { + this._fontStyle = 'oblique'; + } else { + this._fontStyle = 'normal'; + } + + // can work out fontVariant from search of whole string + if (font.indexOf('small-caps') > -1) { + this._fontVariant = 'small-caps'; + } else { + this._fontVariant = 'normal'; + } + + // fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units + var splits = font.split(' '); + var fontSizeIndex = -1; + + this._fontSize = 26; + for (var i = 0; i < splits.length; ++i) { + if (splits[i].match(/(px|pt|em|%)/)) { + fontSizeIndex = i; + this._fontSize = splits[i]; + break; + } + } + + // we can now search for fontWeight as we know it must occur before the fontSize + this._fontWeight = 'normal'; + for (var _i = 0; _i < fontSizeIndex; ++_i) { + if (splits[_i].match(/(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/)) { + this._fontWeight = splits[_i]; + break; + } + } + + // and finally join everything together after the fontSize in case the font family has multiple words + if (fontSizeIndex > -1 && fontSizeIndex < splits.length - 1) { + this._fontFamily = ''; + for (var _i2 = fontSizeIndex + 1; _i2 < splits.length; ++_i2) { + this._fontFamily += splits[_i2] + ' '; + } + + this._fontFamily = this._fontFamily.slice(0, -1); + } else { + this._fontFamily = 'Arial'; + } + + this.styleID++; + } + } + }); + + /** + * @method + * @name PIXI.Texture#setFrame + * @see PIXI.Texture#setFrame + * @deprecated since version 3.0.0 + * @param {PIXI.Rectangle} frame - The frame to set. + */ + core.Texture.prototype.setFrame = function setFrame(frame) { + this.frame = frame; + warn('setFrame is now deprecated, please use the frame property, e.g: myTexture.frame = frame;'); + }; + + /** + * @static + * @function + * @name PIXI.Texture.addTextureToCache + * @see PIXI.Texture.addToCache + * @deprecated since 4.5.0 + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the texture will be stored against. + */ + core.Texture.addTextureToCache = function addTextureToCache(texture, id) { + core.Texture.addToCache(texture, id); + warn('Texture.addTextureToCache is deprecated, please use Texture.addToCache from now on.'); + }; + + /** + * @static + * @function + * @name PIXI.Texture.removeTextureFromCache + * @see PIXI.Texture.removeFromCache + * @deprecated since 4.5.0 + * @param {string} id - The id of the texture to be removed + * @return {PIXI.Texture|null} The texture that was removed + */ + core.Texture.removeTextureFromCache = function removeTextureFromCache(id) { + warn('Texture.removeTextureFromCache is deprecated, please use Texture.removeFromCache from now on. ' + 'Be aware that Texture.removeFromCache does not automatically its BaseTexture from the BaseTextureCache. ' + 'For that, use BaseTexture.removeFromCache'); + + core.BaseTexture.removeFromCache(id); + + return core.Texture.removeFromCache(id); + }; + + Object.defineProperties(filters, { + + /** + * @class + * @private + * @name PIXI.filters.AbstractFilter + * @see PIXI.AbstractFilter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.AbstractFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.SpriteMaskFilter + * @see PIXI.SpriteMaskFilter + * @deprecated since version 3.0.6 + */ + SpriteMaskFilter: { + get: function get() { + warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.'); + + return core.SpriteMaskFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.VoidFilter + * @see PIXI.filters.AlphaFilter + * @deprecated since version 4.5.7 + */ + VoidFilter: { + get: function get() { + warn('VoidFilter has been renamed to AlphaFilter, please use PIXI.filters.AlphaFilter'); + + return filters.AlphaFilter; + } + } + }); + + /** + * @method + * @name PIXI.utils.uuid + * @see PIXI.utils.uid + * @deprecated since version 3.0.6 + * @return {number} The uid + */ + core.utils.uuid = function () { + warn('utils.uuid() is deprecated, please use utils.uid() from now on.'); + + return core.utils.uid(); + }; + + /** + * @method + * @name PIXI.utils.canUseNewCanvasBlendModes + * @see PIXI.CanvasTinter + * @deprecated + * @return {boolean} Can use blend modes. + */ + core.utils.canUseNewCanvasBlendModes = function () { + warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on'); + + return core.CanvasTinter.canUseMultiply; + }; + + var saidHello = true; + + /** + * @name PIXI.utils._saidHello + * @type {boolean} + * @see PIXI.utils.skipHello + * @deprecated since 4.1.0 + */ + Object.defineProperty(core.utils, '_saidHello', { + set: function set(bool) { + if (bool) { + warn('PIXI.utils._saidHello is deprecated, please use PIXI.utils.skipHello()'); + this.skipHello(); + } + saidHello = bool; + }, + get: function get() { + return saidHello; + } + }); + + if (prepare.BasePrepare) { + /** + * @method + * @name PIXI.prepare.BasePrepare#register + * @see PIXI.prepare.BasePrepare#registerFindHook + * @deprecated since version 4.4.2 + * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + prepare.BasePrepare.prototype.register = function register(addHook, uploadHook) { + warn('renderer.plugins.prepare.register is now deprecated, ' + 'please use renderer.plugins.prepare.registerFindHook & renderer.plugins.prepare.registerUploadHook'); + + if (addHook) { + this.registerFindHook(addHook); + } + + if (uploadHook) { + this.registerUploadHook(uploadHook); + } + + return this; + }; + } + + if (prepare.canvas) { + /** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.canvas.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ + Object.defineProperty(prepare.canvas, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } + }); + } + + if (prepare.webgl) { + /** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.webgl.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ + Object.defineProperty(prepare.webgl, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } + }); + } + + if (loaders.Loader) { + var Resource = loaders.Resource; + var Loader = loaders.Loader; + + Object.defineProperties(Resource.prototype, { + isJson: { + get: function get() { + warn('The isJson property is deprecated, please use `resource.type === Resource.TYPE.JSON`.'); + + return this.type === Resource.TYPE.JSON; + } + }, + isXml: { + get: function get() { + warn('The isXml property is deprecated, please use `resource.type === Resource.TYPE.XML`.'); + + return this.type === Resource.TYPE.XML; + } + }, + isImage: { + get: function get() { + warn('The isImage property is deprecated, please use `resource.type === Resource.TYPE.IMAGE`.'); + + return this.type === Resource.TYPE.IMAGE; + } + }, + isAudio: { + get: function get() { + warn('The isAudio property is deprecated, please use `resource.type === Resource.TYPE.AUDIO`.'); + + return this.type === Resource.TYPE.AUDIO; + } + }, + isVideo: { + get: function get() { + warn('The isVideo property is deprecated, please use `resource.type === Resource.TYPE.VIDEO`.'); + + return this.type === Resource.TYPE.VIDEO; + } + } + }); + + Object.defineProperties(Loader.prototype, { + before: { + get: function get() { + warn('The before() method is deprecated, please use pre().'); + + return this.pre; + } + }, + after: { + get: function get() { + warn('The after() method is deprecated, please use use().'); + + return this.use; + } + } + }); + } + + if (interaction.interactiveTarget) { + /** + * @name PIXI.interaction.interactiveTarget#defaultCursor + * @static + * @type {number} + * @see PIXI.interaction.interactiveTarget#cursor + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.interactiveTarget, 'defaultCursor', { + set: function set(value) { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + this.cursor = value; + }, + get: function get() { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + + return this.cursor; + } + }); + } + + if (interaction.InteractionManager) { + /** + * @name PIXI.interaction.InteractionManager#defaultCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.InteractionManager, 'defaultCursorStyle', { + set: function set(value) { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + this.cursorStyles.default = value; + }, + get: function get() { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + + return this.cursorStyles.default; + } + }); + + /** + * @name PIXI.interaction.InteractionManager#currentCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.InteractionManager, 'currentCursorStyle', { + set: function set(value) { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + this.currentCursorMode = value; + }, + get: function get() { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + + return this.currentCursorMode; + } + }); + } +} + +},{}],132:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI.extract + */ + +var CanvasExtract = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasExtract(renderer) { + _classCallCheck(this, CanvasExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.extract.CanvasExtract} extract + * @memberof PIXI.CanvasRenderer# + * @see PIXI.extract.CanvasExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + CanvasExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `CanvasExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + CanvasExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + CanvasExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = this.renderer.width; + frame.height = this.renderer.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + CanvasExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + + return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; + }; + + /** + * Destroys the extract + * + */ + + + CanvasExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return CanvasExtract; +}(); + +exports.default = CanvasExtract; + + +core.CanvasRenderer.registerPlugin('extract', CanvasExtract); + +},{"../../core":65}],133:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLExtract = require('./webgl/WebGLExtract'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLExtract).default; + } +}); + +var _CanvasExtract = require('./canvas/CanvasExtract'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasExtract).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./canvas/CanvasExtract":132,"./webgl/WebGLExtract":134}],134:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); +var BYTES_PER_PIXEL = 4; + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI.extract + */ + +var WebGLExtract = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLExtract(renderer) { + _classCallCheck(this, WebGLExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.extract.WebGLExtract} extract + * @memberof PIXI.WebGLRenderer# + * @see PIXI.extract.WebGLExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + WebGLExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `WebGLExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + WebGLExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + WebGLExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var flipY = false; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + flipY = false; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + flipY = true; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + + // set up an array of pixels + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + + canvasData.data.set(webglPixels); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // pulling pixels + if (flipY) { + canvasBuffer.context.scale(1, -1); + canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); + } + } + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + WebGLExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + } + + return webglPixels; + }; + + /** + * Destroys the extract + * + */ + + + WebGLExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return WebGLExtract; +}(); + +exports.default = WebGLExtract; + + +core.WebGLRenderer.registerPlugin('extract', WebGLExtract); + +},{"../../core":65}],135:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @typedef FrameObject + * @type {object} + * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame + * @property {number} time - the duration of the frame in ms + */ + +/** + * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. + * + * ```js + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; + * + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.fromImage(alienImages[i]); + * textureArray.push(texture); + * }; + * + * let mc = new PIXI.AnimatedSprite(textureArray); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ +var AnimatedSprite = function (_core$Sprite) { + _inherits(AnimatedSprite, _core$Sprite); + + /** + * @param {PIXI.Texture[]|FrameObject[]} textures - an array of {@link PIXI.Texture} or frame + * objects that make up the animation + * @param {boolean} [autoUpdate=true] - Whether to use PIXI.ticker.shared to auto update animation time. + */ + function AnimatedSprite(textures, autoUpdate) { + _classCallCheck(this, AnimatedSprite); + + /** + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture)); + + _this._textures = null; + + /** + * @private + */ + _this._durations = null; + + _this.textures = textures; + + /** + * `true` uses PIXI.ticker.shared to auto update animation time. + * @type {boolean} + * @default true + * @private + */ + _this._autoUpdate = autoUpdate !== false; + + /** + * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower + * + * @member {number} + * @default 1 + */ + _this.animationSpeed = 1; + + /** + * Whether or not the animate sprite repeats after playing. + * + * @member {boolean} + * @default true + */ + _this.loop = true; + + /** + * Function to call when a AnimatedSprite finishes playing + * + * @member {Function} + */ + _this.onComplete = null; + + /** + * Function to call when a AnimatedSprite changes which texture is being rendered + * + * @member {Function} + */ + _this.onFrameChange = null; + + /** + * Function to call when 'loop' is true, and an AnimatedSprite is played and loops around to start again + * + * @member {Function} + */ + _this.onLoop = null; + + /** + * Elapsed time since animation has been started, used internally to display current texture + * + * @member {number} + * @private + */ + _this._currentTime = 0; + + /** + * Indicates if the AnimatedSprite is currently playing + * + * @member {boolean} + * @readonly + */ + _this.playing = false; + return _this; + } + + /** + * Stops the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.stop = function stop() { + if (!this.playing) { + return; + } + + this.playing = false; + if (this._autoUpdate) { + core.ticker.shared.remove(this.update, this); + } + }; + + /** + * Plays the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.play = function play() { + if (this.playing) { + return; + } + + this.playing = true; + if (this._autoUpdate) { + core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.HIGH); + } + }; + + /** + * Stops the AnimatedSprite and goes to a specific frame + * + * @param {number} frameNumber - frame index to stop at + */ + + + AnimatedSprite.prototype.gotoAndStop = function gotoAndStop(frameNumber) { + this.stop(); + + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + + /** + * Goes to a specific frame and begins playing the AnimatedSprite + * + * @param {number} frameNumber - frame index to start at + */ + + + AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay(frameNumber) { + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + + this.play(); + }; + + /** + * Updates the object transform for rendering. + * + * @private + * @param {number} deltaTime - Time since last tick. + */ + + + AnimatedSprite.prototype.update = function update(deltaTime) { + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + + lag += elapsed / 60 * 1000; + + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + + var sign = Math.sign(this.animationSpeed * deltaTime); + + this._currentTime = Math.floor(this._currentTime); + + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + + this._currentTime += lag / this._durations[this.currentFrame]; + } else { + this._currentTime += elapsed; + } + + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + + if (this.onComplete) { + this.onComplete(); + } + } else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + + if (this.onComplete) { + this.onComplete(); + } + } else if (previousFrame !== this.currentFrame) { + if (this.loop && this.onLoop) { + if (this.animationSpeed > 0 && this.currentFrame < previousFrame) { + this.onLoop(); + } else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) { + this.onLoop(); + } + } + + this.updateTexture(); + } + }; + + /** + * Updates the displayed texture to match the current frame index + * + * @private + */ + + + AnimatedSprite.prototype.updateTexture = function updateTexture() { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + this.cachedTint = 0xFFFFFF; + + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + }; + + /** + * Stops the AnimatedSprite and destroys it + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + AnimatedSprite.prototype.destroy = function destroy(options) { + this.stop(); + _core$Sprite.prototype.destroy.call(this, options); + }; + + /** + * A short hand way of creating a movieclip from an array of frame ids + * + * @static + * @param {string[]} frames - The array of frames ids the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animated sprite with the specified frames. + */ + + + AnimatedSprite.fromFrames = function fromFrames(frames) { + var textures = []; + + for (var i = 0; i < frames.length; ++i) { + textures.push(core.Texture.fromFrame(frames[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * A short hand way of creating a movieclip from an array of image ids + * + * @static + * @param {string[]} images - the array of image urls the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animate sprite with the specified images as frames. + */ + + + AnimatedSprite.fromImages = function fromImages(images) { + var textures = []; + + for (var i = 0; i < images.length; ++i) { + textures.push(core.Texture.fromImage(images[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * totalFrames is the total number of frames in the AnimatedSprite. This is the same as number of textures + * assigned to the AnimatedSprite. + * + * @readonly + * @member {number} + * @default 0 + */ + + + _createClass(AnimatedSprite, [{ + key: 'totalFrames', + get: function get() { + return this._textures.length; + } + + /** + * The array of textures used for this AnimatedSprite + * + * @member {PIXI.Texture[]} + */ + + }, { + key: 'textures', + get: function get() { + return this._textures; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value[0] instanceof core.Texture) { + this._textures = value; + this._durations = null; + } else { + this._textures = []; + this._durations = []; + + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + this.gotoAndStop(0); + this.updateTexture(); + } + + /** + * The AnimatedSprites current frame index + * + * @member {number} + * @readonly + */ + + }, { + key: 'currentFrame', + get: function get() { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + + return currentFrame; + } + }]); + + return AnimatedSprite; +}(core.Sprite); + +exports.default = AnimatedSprite; + +},{"../core":65}],136:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ObservablePoint = require('../core/math/ObservablePoint'); + +var _ObservablePoint2 = _interopRequireDefault(_ObservablePoint); + +var _utils = require('../core/utils'); + +var _settings = require('../core/settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BitmapText object will create a line or multiple lines of text using bitmap font. To + * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using: + * + * A BitmapText can only be created when the font is loaded + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); + * ``` + * + * http://www.angelcode.com/products/bmfont/ for windows or + * http://www.bmglyph.com/ for mac. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.extras + */ +var BitmapText = function (_core$Container) { + _inherits(BitmapText, _core$Container); + + /** + * @param {string} text - The copy that you would like the text to display + * @param {object} style - The style parameters + * @param {string|object} style.font - The font descriptor for the object, can be passed as a string of form + * "24px FontName" or "FontName" or as an object with explicit name/size properties. + * @param {string} [style.font.name] - The bitmap font id + * @param {number} [style.font.size] - The size of the font in pixels, e.g. 24 + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), does not affect + * single line text + * @param {number} [style.tint=0xFFFFFF] - The tint color + */ + function BitmapText(text) { + var style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _classCallCheck(this, BitmapText); + + /** + * Private tracker for the width of the overall text + * + * @member {number} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._textWidth = 0; + + /** + * Private tracker for the height of the overall text + * + * @member {number} + * @private + */ + _this._textHeight = 0; + + /** + * Private tracker for the letter sprite pool. + * + * @member {PIXI.Sprite[]} + * @private + */ + _this._glyphs = []; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._font = { + tint: style.tint !== undefined ? style.tint : 0xFFFFFF, + align: style.align || 'left', + name: null, + size: 0 + }; + + /** + * Private tracker for the current font. + * + * @member {object} + * @private + */ + _this.font = style.font; // run font setter + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = text; + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + * @private + */ + _this._maxWidth = 0; + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + * @private + */ + _this._maxLineHeight = 0; + + /** + * Text anchor. read-only + * + * @member {PIXI.ObservablePoint} + * @private + */ + _this._anchor = new _ObservablePoint2.default(function () { + _this.dirty = true; + }, _this, 0, 0); + + /** + * The dirty state of this object. + * + * @member {boolean} + */ + _this.dirty = false; + + _this.updateText(); + return _this; + } + + /** + * Renders text and updates it when needed + * + * @private + */ + + + BitmapText.prototype.updateText = function updateText() { + var data = BitmapText.fonts[this._font.name]; + var scale = this._font.size / data.size; + var pos = new core.Point(); + var chars = []; + var lineWidths = []; + + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastSpace = -1; + var lastSpaceWidth = 0; + var spacesRemoved = 0; + var maxLineHeight = 0; + + for (var i = 0; i < this.text.length; i++) { + var charCode = this.text.charCodeAt(i); + + if (/(\s)/.test(this.text.charAt(i))) { + lastSpace = i; + lastSpaceWidth = lastLineWidth; + } + + if (/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) { + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + if (lastSpace !== -1 && this._maxWidth > 0 && pos.x * scale > this._maxWidth) { + core.utils.removeItems(chars, lastSpace - spacesRemoved, i - lastSpace); + i = lastSpace; + lastSpace = -1; + ++spacesRemoved; + + lineWidths.push(lastSpaceWidth); + maxLineWidth = Math.max(maxLineWidth, lastSpaceWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + var charData = data.chars[charCode]; + + if (!charData) { + continue; + } + + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + + chars.push({ + texture: charData.texture, + line: line, + charCode: charCode, + position: new core.Point(pos.x + charData.xOffset, pos.y + charData.yOffset) + }); + lastLineWidth = pos.x + (charData.texture.width + charData.xOffset); + pos.x += charData.xAdvance; + maxLineHeight = Math.max(maxLineHeight, charData.yOffset + charData.texture.height); + prevCharCode = charCode; + } + + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + + var lineAlignOffsets = []; + + for (var _i = 0; _i <= line; _i++) { + var alignOffset = 0; + + if (this._font.align === 'right') { + alignOffset = maxLineWidth - lineWidths[_i]; + } else if (this._font.align === 'center') { + alignOffset = (maxLineWidth - lineWidths[_i]) / 2; + } + + lineAlignOffsets.push(alignOffset); + } + + var lenChars = chars.length; + var tint = this.tint; + + for (var _i2 = 0; _i2 < lenChars; _i2++) { + var c = this._glyphs[_i2]; // get the next glyph sprite + + if (c) { + c.texture = chars[_i2].texture; + } else { + c = new core.Sprite(chars[_i2].texture); + this._glyphs.push(c); + } + + c.position.x = (chars[_i2].position.x + lineAlignOffsets[chars[_i2].line]) * scale; + c.position.y = chars[_i2].position.y * scale; + c.scale.x = c.scale.y = scale; + c.tint = tint; + + if (!c.parent) { + this.addChild(c); + } + } + + // remove unnecessary children. + for (var _i3 = lenChars; _i3 < this._glyphs.length; ++_i3) { + this.removeChild(this._glyphs[_i3]); + } + + this._textWidth = maxLineWidth * scale; + this._textHeight = (pos.y + data.lineHeight) * scale; + + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + for (var _i4 = 0; _i4 < lenChars; _i4++) { + this._glyphs[_i4].x -= this._textWidth * this.anchor.x; + this._glyphs[_i4].y -= this._textHeight * this.anchor.y; + } + } + this._maxLineHeight = maxLineHeight * scale; + }; + + /** + * Updates the transform of this object + * + * @private + */ + + + BitmapText.prototype.updateTransform = function updateTransform() { + this.validate(); + this.containerUpdateTransform(); + }; + + /** + * Validates text before calling parent's getLocalBounds + * + * @return {PIXI.Rectangle} The rectangular bounding area + */ + + + BitmapText.prototype.getLocalBounds = function getLocalBounds() { + this.validate(); + + return _core$Container.prototype.getLocalBounds.call(this); + }; + + /** + * Updates text when needed + * + * @private + */ + + + BitmapText.prototype.validate = function validate() { + if (this.dirty) { + this.updateText(); + this.dirty = false; + } + }; + + /** + * The tint of the BitmapText object + * + * @member {number} + */ + + + /** + * Register a bitmap font with data and a texture. + * + * @static + * @param {XMLDocument} xml - The XML document data. + * @param {PIXI.Texture} texture - Texture with all symbols. + * @return {Object} Result font object with font, size, lineHeight and char fields. + */ + BitmapText.registerFont = function registerFont(xml, texture) { + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + var fileName = xml.getElementsByTagName('page')[0].getAttribute('file'); + var res = (0, _utils.getResolutionOfUrl)(fileName, _settings2.default.RESOLUTION); + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) / res; + data.chars = {}; + + // parse letters + var letters = xml.getElementsByTagName('char'); + + for (var i = 0; i < letters.length; i++) { + var letter = letters[i]; + var charCode = parseInt(letter.getAttribute('id'), 10); + + var textureRect = new core.Rectangle(parseInt(letter.getAttribute('x'), 10) / res + texture.frame.x / res, parseInt(letter.getAttribute('y'), 10) / res + texture.frame.y / res, parseInt(letter.getAttribute('width'), 10) / res, parseInt(letter.getAttribute('height'), 10) / res); + + data.chars[charCode] = { + xOffset: parseInt(letter.getAttribute('xoffset'), 10) / res, + yOffset: parseInt(letter.getAttribute('yoffset'), 10) / res, + xAdvance: parseInt(letter.getAttribute('xadvance'), 10) / res, + kerning: {}, + texture: new core.Texture(texture.baseTexture, textureRect) + + }; + } + + // parse kernings + var kernings = xml.getElementsByTagName('kerning'); + + for (var _i5 = 0; _i5 < kernings.length; _i5++) { + var kerning = kernings[_i5]; + var first = parseInt(kerning.getAttribute('first'), 10) / res; + var second = parseInt(kerning.getAttribute('second'), 10) / res; + var amount = parseInt(kerning.getAttribute('amount'), 10) / res; + + if (data.chars[second]) { + data.chars[second].kerning[first] = amount; + } + } + + // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 + // but it's very likely to change + BitmapText.fonts[data.font] = data; + + return data; + }; + + _createClass(BitmapText, [{ + key: 'tint', + get: function get() { + return this._font.tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.tint = typeof value === 'number' && value >= 0 ? value : 0xFFFFFF; + + this.dirty = true; + } + + /** + * The alignment of the BitmapText object + * + * @member {string} + * @default 'left' + */ + + }, { + key: 'align', + get: function get() { + return this._font.align; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.align = value || 'left'; + + this.dirty = true; + } + + /** + * The anchor sets the origin point of the text. + * The default is 0,0 this means the text's origin is the top left + * Setting the anchor to 0.5,0.5 means the text's origin is centered + * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner + * + * @member {PIXI.Point | number} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (typeof value === 'number') { + this._anchor.set(value); + } else { + this._anchor.copy(value); + } + } + + /** + * The font descriptor of the BitmapText object + * + * @member {string|object} + */ + + }, { + key: 'font', + get: function get() { + return this._font; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (!value) { + return; + } + + if (typeof value === 'string') { + value = value.split(' '); + + this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); + this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; + } else { + this._font.name = value.name; + this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); + } + + this.dirty = true; + } + + /** + * The text of the BitmapText object + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + value = value.toString() || ' '; + if (this._text === value) { + return; + } + this._text = value; + this.dirty = true; + } + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + */ + + }, { + key: 'maxWidth', + get: function get() { + return this._maxWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._maxWidth === value) { + return; + } + this._maxWidth = value; + this.dirty = true; + } + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + * @readonly + */ + + }, { + key: 'maxLineHeight', + get: function get() { + this.validate(); + + return this._maxLineHeight; + } + + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textWidth', + get: function get() { + this.validate(); + + return this._textWidth; + } + + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textHeight', + get: function get() { + this.validate(); + + return this._textHeight; + } + }]); + + return BitmapText; +}(core.Container); + +exports.default = BitmapText; + + +BitmapText.fonts = {}; + +},{"../core":65,"../core/math/ObservablePoint":68,"../core/settings":101,"../core/utils":125}],137:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CanvasTinter = require('../core/sprites/canvas/CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); + +/** + * A tiling sprite is a fast way of rendering a tiling image + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ + +var TilingSprite = function (_core$Sprite) { + _inherits(TilingSprite, _core$Sprite); + + /** + * @param {PIXI.Texture} texture - the texture of the tiling sprite + * @param {number} [width=100] - the width of the tiling sprite + * @param {number} [height=100] - the height of the tiling sprite + */ + function TilingSprite(texture) { + var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100; + + _classCallCheck(this, TilingSprite); + + /** + * Tile transform + * + * @member {PIXI.TransformStatic} + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, texture)); + + _this.tileTransform = new core.TransformStatic(); + + // /// private + + /** + * The with of the tiling sprite + * + * @member {number} + * @private + */ + _this._width = width; + + /** + * The height of the tiling sprite + * + * @member {number} + * @private + */ + _this._height = height; + + /** + * Canvas pattern + * + * @type {CanvasPattern} + * @private + */ + _this._canvasPattern = null; + + /** + * transform that is applied to UV to get the texture coords + * + * @member {PIXI.TextureMatrix} + */ + _this.uvTransform = texture.transform || new core.TextureMatrix(texture); + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' method. + * + * @member {string} + * @default 'tilingSprite' + */ + _this.pluginName = 'tilingSprite'; + + /** + * Whether or not anchor affects uvs + * + * @member {boolean} + * @default false + */ + _this.uvRespectAnchor = false; + return _this; + } + /** + * Changes frame clamping in corresponding textureTransform, shortcut + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + + + /** + * @private + */ + TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate() { + if (this.uvTransform) { + this.uvTransform.texture = this._texture; + } + this.cachedTint = 0xFFFFFF; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + TilingSprite.prototype._renderWebGL = function _renderWebGL(renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + + if (!texture || !texture.valid) { + return; + } + + this.tileTransform.updateLocalTransform(); + this.uvTransform.update(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer + */ + + + TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { + var texture = this._texture; + + if (!texture.baseTexture.hasLoaded) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var resolution = renderer.resolution; + var baseTexture = texture.baseTexture; + var baseTextureResolution = baseTexture.resolution; + var modX = this.tilePosition.x / this.tileScale.x % texture._frame.width * baseTextureResolution; + var modY = this.tilePosition.y / this.tileScale.y % texture._frame.height * baseTextureResolution; + + // create a nice shiny pattern! + if (this._textureID !== this._texture._updateID || this.cachedTint !== this.tint) { + this._textureID = this._texture._updateID; + // cut an object from a spritesheet.. + var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height, baseTextureResolution); + + // Tint the tiling sprite + if (this.tint !== 0xFFFFFF) { + this.tintedTexture = _CanvasTinter2.default.getTintedTexture(this, this.tint); + tempCanvas.context.drawImage(this.tintedTexture, 0, 0); + } else { + tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x * baseTextureResolution, -texture._frame.y * baseTextureResolution); + } + this.cachedTint = this.tint; + this._canvasPattern = tempCanvas.context.createPattern(tempCanvas.canvas, 'repeat'); + } + + // set context state.. + context.globalAlpha = this.worldAlpha; + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + renderer.setBlendMode(this.blendMode); + + // fill the pattern! + context.fillStyle = this._canvasPattern; + + // TODO - this should be rolled into the setTransform above.. + context.scale(this.tileScale.x / baseTextureResolution, this.tileScale.y / baseTextureResolution); + + var anchorX = this.anchor.x * -this._width; + var anchorY = this.anchor.y * -this._height; + + if (this.uvRespectAnchor) { + context.translate(modX, modY); + + context.fillRect(-modX + anchorX, -modY + anchorY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } else { + context.translate(modX + anchorX, modY + anchorY); + + context.fillRect(-modX, -modY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } + }; + + /** + * Updates the bounds of the tiling sprite. + * + * @private + */ + + + TilingSprite.prototype._calculateBounds = function _calculateBounds() { + var minX = this._width * -this._anchor._x; + var minY = this._height * -this._anchor._y; + var maxX = this._width * (1 - this._anchor._x); + var maxY = this._height * (1 - this._anchor._y); + + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + TilingSprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._width * -this._anchor._x; + this._bounds.minY = this._height * -this._anchor._y; + this._bounds.maxX = this._width * (1 - this._anchor._x); + this._bounds.maxY = this._height * (1 - this._anchor._x); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new core.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _core$Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Checks if a point is inside this tiling sprite. + * + * @param {PIXI.Point} point - the point to check + * @return {boolean} Whether or not the sprite contains the point. + */ + + + TilingSprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor._x; + + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + var y1 = -height * this.anchor._y; + + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + TilingSprite.prototype.destroy = function destroy(options) { + _core$Sprite.prototype.destroy.call(this, options); + + this.tileTransform = null; + this.uvTransform = null; + }; + + /** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.Texture} The newly created texture + */ + + + TilingSprite.from = function from(source, width, height) { + return new TilingSprite(core.Texture.from(source), width, height); + }; + + /** + * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId + */ + + + TilingSprite.fromFrame = function fromFrame(frameId, width, height) { + var texture = core.utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this); + } + + return new TilingSprite(texture, width, height); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @param {boolean} [crossorigin] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id + */ + + + TilingSprite.fromImage = function fromImage(imageId, width, height, crossorigin, scaleMode) { + return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode), width, height); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(TilingSprite, [{ + key: 'clampMargin', + get: function get() { + return this.uvTransform.clampMargin; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uvTransform.clampMargin = value; + this.uvTransform.update(true); + } + + /** + * The scaling of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tileScale', + get: function get() { + return this.tileTransform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.scale.copy(value); + } + + /** + * The offset of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tilePosition', + get: function get() { + return this.tileTransform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.position.copy(value); + } + }, { + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + } + + /** + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + } + }]); + + return TilingSprite; +}(core.Sprite); + +exports.default = TilingSprite; + +},{"../core":65,"../core/sprites/canvas/CanvasTinter":104}],138:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _BaseTexture = require('../core/textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _utils = require('../core/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DisplayObject = core.DisplayObject; +var _tempMatrix = new core.Matrix(); + +DisplayObject.prototype._cacheAsBitmap = false; +DisplayObject.prototype._cacheData = false; + +// figured theres no point adding ALL the extra variables to prototype. +// this model can hold the information needed. This can also be generated on demand as +// most objects are not cached as bitmaps. +/** + * @class + * @ignore + */ + +var CacheData = +/** + * + */ +function CacheData() { + _classCallCheck(this, CacheData); + + this.textureCacheId = null; + + this.originalRenderWebGL = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + + this.originalUpdateTransform = null; + this.originalHitTest = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.sprite = null; +}; + +Object.defineProperties(DisplayObject.prototype, { + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to 'false' + * + * IMPORTANT GOTCHA - make sure that all your textures are preloaded BEFORE setting this property to true + * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function get() { + return this._cacheAsBitmap; + }, + set: function set(value) { + if (this._cacheAsBitmap === value) { + return; + } + + this._cacheAsBitmap = value; + + var data = void 0; + + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + + data = this._cacheData; + + data.originalRenderWebGL = this.renderWebGL; + data.originalRenderCanvas = this.renderCanvas; + + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this._calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + + data.originalDestroy = this.destroy; + + data.originalContainsPoint = this.containsPoint; + + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + + this.renderWebGL = this._renderCachedWebGL; + this.renderCanvas = this._renderCachedCanvas; + + this.destroy = this._cacheAsBitmapDestroy; + } else { + data = this._cacheData; + + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + + this.renderWebGL = data.originalRenderWebGL; + this.renderCanvas = data.originalRenderCanvas; + this._calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + + this.destroy = data.originalDestroy; + + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + } + } +}); + +/** + * Renders a cached version of the sprite with WebGL + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedWebGL = function _renderCachedWebGL(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObject(renderer); + + this._cacheData.sprite._transformID = -1; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderWebGL(renderer); +}; + +/** + * Prepares the WebGL renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + + this.alpha = 1; + + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.currentRenderer.flush(); + // this.filters= []; + + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds().clone(); + + // add some padding! + if (this._filters) { + var padding = this._filters[0].padding; + + bounds.pad(padding); + } + + // for now we cache the current renderTarget that the webGL renderer is currently using. + // this could be more elegent.. + var cachedRenderTarget = renderer._activeRenderTarget; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + var stack = renderer.filterManager.filterStack; + + // this renderTexture will be used to store the cached DisplayObject + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); + + this._cacheData.textureCacheId = textureCacheId; + + _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); + _Texture2.default.addToCache(renderTexture, textureCacheId); + + // need to set // + var m = _tempMatrix; + + m.tx = -bounds.x; + m.ty = -bounds.y; + + // reset + this.transform.worldTransform.identity(); + + // set all properties to there original so we can render to a texture + this.renderWebGL = this._cacheData.originalRenderWebGL; + + renderer.render(this, renderTexture, true, m, true); + // now restore the state be setting the new properties + + renderer.bindRenderTarget(cachedRenderTarget); + + renderer.filterManager.filterStack = stack; + + this.renderWebGL = this._renderCachedWebGL; + this.updateTransform = this.displayObjectUpdateTransform; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + + // easy bounds.. + this._calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + + this._cacheData.sprite = cachedSprite; + + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this.updateTransform(); + } + + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Renders a cached version of the sprite with canvas + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObjectCanvas(renderer); + + this._cacheData.sprite.worldAlpha = this.worldAlpha; + + this._cacheData.sprite.renderCanvas(renderer); +}; + +// TODO this can be the same as the webGL verison.. will need to do a little tweaking first though.. +/** + * Prepares the Canvas renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(); + + var cacheAlpha = this.alpha; + + this.alpha = 1; + + var cachedRenderTarget = renderer.context; + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); + + this._cacheData.textureCacheId = textureCacheId; + + _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); + _Texture2.default.addToCache(renderTexture, textureCacheId); + + // need to set // + var m = _tempMatrix; + + this.transform.localTransform.copy(m); + m.invert(); + + m.tx -= bounds.x; + m.ty -= bounds.y; + + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + + // renderTexture.render(this, m, true); + renderer.render(this, renderTexture, true, m, false); + + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + + this.renderCanvas = this._renderCachedCanvas; + this._calculateBounds = this._calculateCachedBounds; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite._bounds = this._bounds; + cachedSprite.alpha = cacheAlpha; + + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this.updateTransform(); + } + + this.updateTransform = this.displayObjectUpdateTransform; + + this._cacheData.sprite = cachedSprite; + + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Calculates the bounds of the cached sprite + * + * @private + */ +DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._cacheData.sprite._calculateBounds(); +}; + +/** + * Gets the bounds of the cached sprite. + * + * @private + * @return {Rectangle} The local bounds. + */ +DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(); +}; + +/** + * Destroys the cached sprite. + * + * @private + */ +DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; + + _BaseTexture2.default.removeFromCache(this._cacheData.textureCacheId); + _Texture2.default.removeFromCache(this._cacheData.textureCacheId); + + this._cacheData.textureCacheId = null; +}; + +/** + * Destroys the cached object. + * + * @private + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * Used when destroying containers, see the Container.destroy method. + */ +DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { + this.cacheAsBitmap = false; + this.destroy(options); +}; + +},{"../core":65,"../core/textures/BaseTexture":112,"../core/textures/Texture":115,"../core/utils":125}],139:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * The instance name of the object. + * + * @memberof PIXI.DisplayObject# + * @member {string} + */ +core.DisplayObject.prototype.name = null; + +/** + * Returns the display object in the container + * + * @memberof PIXI.Container# + * @param {string} name - instance name + * @return {PIXI.DisplayObject} The child with the specified name. + */ +core.Container.prototype.getChildByName = function getChildByName(name) { + for (var i = 0; i < this.children.length; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + + return null; +}; + +},{"../core":65}],140:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. + * + * @memberof PIXI.DisplayObject# + * @param {Point} point - the point to write the global value to. If null a new point will be returned + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @return {Point} The updated point + */ +core.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition() { + var point = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new core.Point(); + var skipUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (this.parent) { + this.parent.toGlobal(this.position, point, skipUpdate); + } else { + point.x = this.position.x; + point.y = this.position.y; + } + + return point; +}; + +},{"../core":65}],141:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BitmapText = exports.TilingSpriteRenderer = exports.TilingSprite = exports.AnimatedSprite = undefined; + +var _AnimatedSprite = require('./AnimatedSprite'); + +Object.defineProperty(exports, 'AnimatedSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AnimatedSprite).default; + } +}); + +var _TilingSprite = require('./TilingSprite'); + +Object.defineProperty(exports, 'TilingSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSprite).default; + } +}); + +var _TilingSpriteRenderer = require('./webgl/TilingSpriteRenderer'); + +Object.defineProperty(exports, 'TilingSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSpriteRenderer).default; + } +}); + +var _BitmapText = require('./BitmapText'); + +Object.defineProperty(exports, 'BitmapText', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BitmapText).default; + } +}); + +require('./cacheAsBitmap'); + +require('./getChildByName'); + +require('./getGlobalPosition'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// imported for side effect of extending the prototype only, contains no exports + +},{"./AnimatedSprite":135,"./BitmapText":136,"./TilingSprite":137,"./cacheAsBitmap":138,"./getChildByName":139,"./getGlobalPosition":140,"./webgl/TilingSpriteRenderer":142}],142:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _const = require('../../core/const'); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMat = new core.Matrix(); + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI.extras + * @extends PIXI.ObjectRenderer + */ + +var TilingSpriteRenderer = function (_core$ObjectRenderer) { + _inherits(TilingSpriteRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function TilingSpriteRenderer(renderer) { + _classCallCheck(this, TilingSpriteRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + _this.simpleShader = null; + _this.quad = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + TilingSpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n gl_FragColor = sample * uColor;\n}\n'); + this.simpleShader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = sample * uColor;\n}\n'); + + this.renderer.bindVao(null); + this.quad = new core.Quad(gl, this.renderer.state.attribState); + this.quad.initVao(this.shader); + }; + + /** + * + * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered + */ + + + TilingSpriteRenderer.prototype.render = function render(ts) { + var renderer = this.renderer; + var quad = this.quad; + + renderer.bindVao(quad.vao); + + var vertices = quad.vertices; + + vertices[0] = vertices[6] = ts._width * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + + vertices[2] = vertices[4] = ts._width * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + + if (ts.uvRespectAnchor) { + vertices = quad.uvs; + + vertices[0] = vertices[6] = -ts.anchor.x; + vertices[1] = vertices[3] = -ts.anchor.y; + + vertices[2] = vertices[4] = 1.0 - ts.anchor.x; + vertices[5] = vertices[7] = 1.0 - ts.anchor.y; + } + + quad.upload(); + + var tex = ts._texture; + var baseTex = tex.baseTexture; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvTransform; + var isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === _const.WRAP_MODES.CLAMP) { + baseTex.wrapMode = _const.WRAP_MODES.REPEAT; + } + } else { + isSimple = baseTex.wrapMode !== _const.WRAP_MODES.CLAMP; + } + } + + var shader = isSimple ? this.simpleShader : this.shader; + + renderer.bindShader(shader); + + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + + tempMat.invert(); + if (isSimple) { + tempMat.prepend(uv.mapCoord); + } else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + + shader.uniforms.uTransform = tempMat.toArray(true); + shader.uniforms.uColor = core.utils.premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, baseTex.premultipliedAlpha); + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + + shader.uniforms.uSampler = renderer.bindTexture(tex); + + renderer.setBlendMode(core.utils.correctBlendMode(ts.blendMode, baseTex.premultipliedAlpha)); + + quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + }; + + return TilingSpriteRenderer; +}(core.ObjectRenderer); + +exports.default = TilingSpriteRenderer; + + +core.WebGLRenderer.registerPlugin('tilingSprite', TilingSpriteRenderer); + +},{"../../core":65,"../../core/const":46,"path":23}],143:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Simplest filter - applies alpha + * + * Use this instead of Container's alpha property to avoid visual layering of individual elements. + * AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains. + * If elements are not opaque, they will blend with each other anyway. + * + * Very handy if you want to use common features of all filters: + * + * 1. Assign a blendMode to this filter, blend all elements inside display object with background. + * + * 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var AlphaFilter = function (_core$Filter) { + _inherits(AlphaFilter, _core$Filter); + + /** + * @param {number} [alpha=1] Amount of alpha from 0 to 1, where 0 is transparent + */ + function AlphaFilter() { + var alpha = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1.0; + + _classCallCheck(this, AlphaFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n')); + + _this.alpha = alpha; + _this.glShaderKey = 'alpha'; + return _this; + } + + /** + * Coefficient for alpha multiplication + * + * @member {number} + * @default 1 + */ + + + _createClass(AlphaFilter, [{ + key: 'alpha', + get: function get() { + return this.uniforms.uAlpha; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uAlpha = value; + } + }]); + + return AlphaFilter; +}(core.Filter); + +exports.default = AlphaFilter; + +},{"../../core":65,"path":23}],144:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BlurXFilter = require('./BlurXFilter'); + +var _BlurXFilter2 = _interopRequireDefault(_BlurXFilter); + +var _BlurYFilter = require('./BlurYFilter'); + +var _BlurYFilter2 = _interopRequireDefault(_BlurYFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurFilter applies a Gaussian blur to an object. + * The strength of the blur can be set for x- and y-axis separately. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurFilter = function (_core$Filter) { + _inherits(BlurFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this)); + + _this.blurXFilter = new _BlurXFilter2.default(strength, quality, resolution, kernelSize); + _this.blurYFilter = new _BlurYFilter2.default(strength, quality, resolution, kernelSize); + + _this.padding = 0; + _this.resolution = resolution || core.settings.RESOLUTION; + _this.quality = quality || 4; + _this.blur = strength || 8; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + BlurFilter.prototype.apply = function apply(filterManager, input, output) { + var renderTarget = filterManager.getRenderTarget(true); + + this.blurXFilter.apply(filterManager, input, renderTarget, true); + this.blurYFilter.apply(filterManager, renderTarget, output, false); + + filterManager.returnRenderTarget(renderTarget); + }; + + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurFilter, [{ + key: 'blur', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the number of passes for blur. More passes means higher quaility bluring. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'quality', + get: function get() { + return this.blurXFilter.quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.quality = this.blurYFilter.quality = value; + } + + /** + * Sets the strength of the blurX property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurX', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the strength of the blurY property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurY', + get: function get() { + return this.blurYFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the blendmode of the filter + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + */ + + }, { + key: 'blendMode', + get: function get() { + return this.blurYFilter._blendMode; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter._blendMode = value; + } + }]); + + return BlurFilter; +}(core.Filter); + +exports.default = BlurFilter; + +},{"../../core":65,"./BlurXFilter":145,"./BlurYFilter":146}],145:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurXFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurXFilter = function (_core$Filter) { + _inherits(BlurXFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurXFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurXFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurXFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.width * (output.size.width / input.size.width); + + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; // / this.passes//Math.pow(1, this.passes); + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 16 + */ + + + _createClass(BlurXFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurXFilter; +}(core.Filter); + +exports.default = BlurXFilter; + +},{"../../core":65,"./generateBlurFragSource":147,"./generateBlurVertSource":148,"./getMaxBlurKernelSize":149}],146:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurYFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurYFilter = function (_core$Filter) { + _inherits(BlurYFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurYFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurYFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurYFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.height * (output.size.height / input.size.height); + + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurYFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurYFilter; +}(core.Filter); + +exports.default = BlurYFilter; + +},{"../../core":65,"./generateBlurFragSource":147,"./generateBlurVertSource":148,"./getMaxBlurKernelSize":149}],147:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateFragBlurSource; +var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] +}; + +var fragTemplate = ['varying vec2 vBlurTexCoords[%size%];', 'uniform sampler2D uSampler;', 'void main(void)', '{', ' gl_FragColor = vec4(0.0);', ' %blur%', '}'].join('\n'); + +function generateFragBlurSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + + var fragSource = fragTemplate; + + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value = void 0; + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + value = i; + + if (i >= halfLength) { + value = kernelSize - i - 1; + } + + blur = blur.replace('%value%', kernel[value]); + + blurLoop += blur; + blurLoop += '\n'; + } + + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize); + + return fragSource; +} + +},{}],148:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateVertBlurSource; +var vertTemplate = ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform float strength;', 'uniform mat3 projectionMatrix;', 'varying vec2 vBlurTexCoords[%size%];', 'void main(void)', '{', 'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);', '%blur%', '}'].join('\n'); + +function generateVertBlurSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + + var vertSource = vertTemplate; + + var blurLoop = ''; + var template = void 0; + // let value; + + if (x) { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } else { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + // value = i; + + // if(i >= halfLength) + // { + // value = kernelSize - i - 1; + // } + + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + '.0'); + + blurLoop += blur; + blurLoop += '\n'; + } + + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize); + + return vertSource; +} + +},{}],149:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = getMaxKernelSize; +function getMaxKernelSize(gl) { + var maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + var kernelSize = 15; + + while (kernelSize > maxVaryings) { + kernelSize -= 2; + } + + return kernelSize; +} + +},{}],150:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.filters.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var ColorMatrixFilter = function (_core$Filter) { + _inherits(ColorMatrixFilter, _core$Filter); + + /** + * + */ + function ColorMatrixFilter() { + _classCallCheck(this, ColorMatrixFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n')); + + _this.uniforms.m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + _this.alpha = 1; + return _this; + } + + /** + * Transforms current matrix and set the new one + * + * @param {number[]} matrix - 5x4 matrix + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix(matrix) { + var multiply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + var newMatrix = matrix; + + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + + // set the new matrix + this.uniforms.m = newMatrix; + }; + + /** + * Multiplies two mat5's + * + * @private + * @param {number[]} out - 5x4 matrix the receiving matrix + * @param {number[]} a - 5x4 matrix the first operand + * @param {number[]} b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix + */ + + + ColorMatrixFilter.prototype._multiply = function _multiply(out, a, b) { + // Red Channel + out[0] = a[0] * b[0] + a[1] * b[5] + a[2] * b[10] + a[3] * b[15]; + out[1] = a[0] * b[1] + a[1] * b[6] + a[2] * b[11] + a[3] * b[16]; + out[2] = a[0] * b[2] + a[1] * b[7] + a[2] * b[12] + a[3] * b[17]; + out[3] = a[0] * b[3] + a[1] * b[8] + a[2] * b[13] + a[3] * b[18]; + out[4] = a[0] * b[4] + a[1] * b[9] + a[2] * b[14] + a[3] * b[19] + a[4]; + + // Green Channel + out[5] = a[5] * b[0] + a[6] * b[5] + a[7] * b[10] + a[8] * b[15]; + out[6] = a[5] * b[1] + a[6] * b[6] + a[7] * b[11] + a[8] * b[16]; + out[7] = a[5] * b[2] + a[6] * b[7] + a[7] * b[12] + a[8] * b[17]; + out[8] = a[5] * b[3] + a[6] * b[8] + a[7] * b[13] + a[8] * b[18]; + out[9] = a[5] * b[4] + a[6] * b[9] + a[7] * b[14] + a[8] * b[19] + a[9]; + + // Blue Channel + out[10] = a[10] * b[0] + a[11] * b[5] + a[12] * b[10] + a[13] * b[15]; + out[11] = a[10] * b[1] + a[11] * b[6] + a[12] * b[11] + a[13] * b[16]; + out[12] = a[10] * b[2] + a[11] * b[7] + a[12] * b[12] + a[13] * b[17]; + out[13] = a[10] * b[3] + a[11] * b[8] + a[12] * b[13] + a[13] * b[18]; + out[14] = a[10] * b[4] + a[11] * b[9] + a[12] * b[14] + a[13] * b[19] + a[14]; + + // Alpha Channel + out[15] = a[15] * b[0] + a[16] * b[5] + a[17] * b[10] + a[18] * b[15]; + out[16] = a[15] * b[1] + a[16] * b[6] + a[17] * b[11] + a[18] * b[16]; + out[17] = a[15] * b[2] + a[16] * b[7] + a[17] * b[12] + a[18] * b[17]; + out[18] = a[15] * b[3] + a[16] * b[8] + a[17] * b[13] + a[18] * b[18]; + out[19] = a[15] * b[4] + a[16] * b[9] + a[17] * b[14] + a[18] * b[19] + a[19]; + + return out; + }; + + /** + * Create a Float32 Array and normalize the offset component to 0-1 + * + * @private + * @param {number[]} matrix - 5x4 matrix + * @return {number[]} 5x4 matrix with all values between 0-1 + */ + + + ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix(matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + + return m; + }; + + /** + * Adjusts brightness + * + * @param {number} b - value of the brigthness (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.brightness = function brightness(b, multiply) { + var matrix = [b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the matrices in grey scales + * + * @param {number} scale - value of the grey (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.greyscale = function greyscale(scale, multiply) { + var matrix = [scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the black and white matrice. + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite(multiply) { + var matrix = [0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the hue property of the color + * + * @param {number} rotation - in degrees + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.hue = function hue(rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + + var a00 = cosR + (1.0 - cosR) * w; + var a01 = w * (1.0 - cosR) - sqrW * sinR; + var a02 = w * (1.0 - cosR) + sqrW * sinR; + + var a10 = w * (1.0 - cosR) + sqrW * sinR; + var a11 = cosR + w * (1.0 - cosR); + var a12 = w * (1.0 - cosR) - sqrW * sinR; + + var a20 = w * (1.0 - cosR) - sqrW * sinR; + var a21 = w * (1.0 - cosR) + sqrW * sinR; + var a22 = cosR + w * (1.0 - cosR); + + var matrix = [a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * + * @param {number} amount - value of the contrast (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.contrast = function contrast(amount, multiply) { + var v = (amount || 0) + 1; + var o = -0.5 * (v - 1); + + var matrix = [v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * + * @param {number} amount - The saturation amount (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.saturate = function saturate() { + var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var multiply = arguments[1]; + + var x = amount * 2 / 3 + 1; + var y = (x - 1) * -0.5; + + var matrix = [x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Desaturate image (remove color) + * + * Call the saturate function + * + */ + + + ColorMatrixFilter.prototype.desaturate = function desaturate() // eslint-disable-line no-unused-vars + { + this.saturate(-1); + }; + + /** + * Negative image (inverse of classic rgb matrix) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.negative = function negative(multiply) { + var matrix = [0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Sepia image + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.sepia = function sepia(multiply) { + var matrix = [0.393, 0.7689999, 0.18899999, 0, 0, 0.349, 0.6859999, 0.16799999, 0, 0, 0.272, 0.5339999, 0.13099999, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.technicolor = function technicolor(multiply) { + var matrix = [1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Polaroid filter + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.polaroid = function polaroid(multiply) { + var matrix = [1.438, -0.062, -0.062, 0, 0, -0.122, 1.378, -0.122, 0, 0, -0.016, -0.016, 1.483, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Filter who transforms : Red -> Blue and Blue -> Red + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.toBGR = function toBGR(multiply) { + var matrix = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.kodachrome = function kodachrome(multiply) { + var matrix = [1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Brown delicious browni filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.browni = function browni(multiply) { + var matrix = [0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Vintage filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.vintage = function vintage(multiply) { + var matrix = [0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * + * @param {number} desaturation - Tone values. + * @param {number} toned - Tone values. + * @param {string} lightColor - Tone values, example: `0xFFE580` + * @param {string} darkColor - Tone values, example: `0xFFE580` + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.colorTone = function colorTone(desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + + var lR = (lightColor >> 16 & 0xFF) / 255; + var lG = (lightColor >> 8 & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + + var dR = (darkColor >> 16 & 0xFF) / 255; + var dG = (darkColor >> 8 & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + + var matrix = [0.3, 0.59, 0.11, 0, 0, lR, lG, lB, desaturation, 0, dR, dG, dB, toned, 0, lR - dR, lG - dG, lB - dB, 0, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Night effect + * + * @param {number} intensity - The intensity of the night effect. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.night = function night(intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [intensity * -2.0, -intensity, 0, 0, 0, -intensity, 0, intensity, 0, 0, 0, intensity, intensity * 2.0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * + * @param {number} amount - how much the predator feels his future victim + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.predator = function predator(amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * LSD effect + * + * Multiply the current matrix + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.lsd = function lsd(multiply) { + var matrix = [2, -0.4, 0.5, 0, 0, -0.5, 2, -0.4, 0, 0, -0.4, -0.5, 3, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Erase the current matrix by setting the default one + * + */ + + + ColorMatrixFilter.prototype.reset = function reset() { + var matrix = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, false); + }; + + /** + * The matrix of the color matrix filter + * + * @member {number[]} + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + + + _createClass(ColorMatrixFilter, [{ + key: 'matrix', + get: function get() { + return this.uniforms.m; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.m = value; + } + + /** + * The opacity value to use when mixing the original and resultant colors. + * + * When the value is 0, the original color is used without modification. + * When the value is 1, the result color is used. + * When in the range (0, 1) the color is interpolated between the original and result by this amount. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'alpha', + get: function get() { + return this.uniforms.uAlpha; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uAlpha = value; + } + }]); + + return ColorMatrixFilter; +}(core.Filter); + +// Americanized alias + + +exports.default = ColorMatrixFilter; +ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + +},{"../../core":65,"path":23}],151:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. You can + * use this filter to apply all manor of crazy warping effects. Currently the r + * property of the texture is used to offset the x and the g property of the texture + * is used to offset the y. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var DisplacementFilter = function (_core$Filter) { + _inherits(DisplacementFilter, _core$Filter); + + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param {number} scale - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + _classCallCheck(this, DisplacementFilter); + + var maskMatrix = new core.Matrix(); + + sprite.renderable = false; + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n')); + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + + _this.uniforms.mapSampler = sprite._texture; + _this.uniforms.filterMatrix = maskMatrix; + _this.uniforms.scale = { x: 1, y: 1 }; + + if (scale === null || scale === undefined) { + scale = 20; + } + + _this.scale = new core.Point(scale, scale); + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + DisplacementFilter.prototype.apply = function apply(filterManager, input, output) { + var ratio = 1 / output.destinationFrame.width * (output.size.width / input.size.width); + + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x * ratio; + this.uniforms.scale.y = this.scale.y * ratio; + + // draw the filter... + filterManager.applyFilter(this, input, output); + }; + + /** + * The texture used for the displacement map. Must be power of 2 sized texture. + * + * @member {PIXI.Texture} + */ + + + _createClass(DisplacementFilter, [{ + key: 'map', + get: function get() { + return this.uniforms.mapSampler; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.mapSampler = value; + } + }]); + + return DisplacementFilter; +}(core.Filter); + +exports.default = DisplacementFilter; + +},{"../../core":65,"path":23}],152:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * Basic FXAA implementation based on the code on geeks3d.com with the + * modification that the texture2DLod stuff was removed since it's + * unsupported by WebGL. + * + * @see https://github.com/mitsuhiko/webgl-meincraft + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + * + */ +var FXAAFilter = function (_core$Filter) { + _inherits(FXAAFilter, _core$Filter); + + /** + * + */ + function FXAAFilter() { + _classCallCheck(this, FXAAFilter); + + // TODO - needs work + return _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + '\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}', + // fragment shader + 'varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n')); + } + + return FXAAFilter; +}(core.Filter); + +exports.default = FXAAFilter; + +},{"../../core":65,"path":23}],153:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _FXAAFilter = require('./fxaa/FXAAFilter'); + +Object.defineProperty(exports, 'FXAAFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_FXAAFilter).default; + } +}); + +var _NoiseFilter = require('./noise/NoiseFilter'); + +Object.defineProperty(exports, 'NoiseFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NoiseFilter).default; + } +}); + +var _DisplacementFilter = require('./displacement/DisplacementFilter'); + +Object.defineProperty(exports, 'DisplacementFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplacementFilter).default; + } +}); + +var _BlurFilter = require('./blur/BlurFilter'); + +Object.defineProperty(exports, 'BlurFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurFilter).default; + } +}); + +var _BlurXFilter = require('./blur/BlurXFilter'); + +Object.defineProperty(exports, 'BlurXFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurXFilter).default; + } +}); + +var _BlurYFilter = require('./blur/BlurYFilter'); + +Object.defineProperty(exports, 'BlurYFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurYFilter).default; + } +}); + +var _ColorMatrixFilter = require('./colormatrix/ColorMatrixFilter'); + +Object.defineProperty(exports, 'ColorMatrixFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ColorMatrixFilter).default; + } +}); + +var _AlphaFilter = require('./alpha/AlphaFilter'); + +Object.defineProperty(exports, 'AlphaFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AlphaFilter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./alpha/AlphaFilter":143,"./blur/BlurFilter":144,"./blur/BlurXFilter":145,"./blur/BlurYFilter":146,"./colormatrix/ColorMatrixFilter":150,"./displacement/DisplacementFilter":151,"./fxaa/FXAAFilter":152,"./noise/NoiseFilter":154}],154:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Vico @vicocotea + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + */ + +/** + * A Noise effect filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var NoiseFilter = function (_core$Filter) { + _inherits(NoiseFilter, _core$Filter); + + /** + * @param {number} noise - The noise intensity, should be a normalized value in the range [0, 1]. + * @param {number} seed - A random seed for the noise generation. Default is `Math.random()`. + */ + function NoiseFilter() { + var noise = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0.5; + var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Math.random(); + + _classCallCheck(this, NoiseFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n')); + + _this.noise = noise; + _this.seed = seed; + return _this; + } + + /** + * The amount of noise to apply, this value should be in the range (0, 1]. + * + * @member {number} + * @default 0.5 + */ + + + _createClass(NoiseFilter, [{ + key: 'noise', + get: function get() { + return this.uniforms.uNoise; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uNoise = value; + } + + /** + * A seed value to apply to the random noise generation. `Math.random()` is a good value to use. + * + * @member {number} + */ + + }, { + key: 'seed', + get: function get() { + return this.uniforms.uSeed; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uSeed = value; + } + }]); + + return NoiseFilter; +}(core.Filter); + +exports.default = NoiseFilter; + +},{"../../core":65,"path":23}],155:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Holds all information related to an Interaction event + * + * @class + * @memberof PIXI.interaction + */ +var InteractionData = function () { + /** + * + */ + function InteractionData() { + _classCallCheck(this, InteractionData); + + /** + * This point stores the global coords of where the touch/mouse event happened + * + * @member {PIXI.Point} + */ + this.global = new core.Point(); + + /** + * The target DisplayObject that was interacted with + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * When passed to an event handler, this will be the original DOM Event that was captured + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent + * @see https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent + * @member {MouseEvent|TouchEvent|PointerEvent} + */ + this.originalEvent = null; + + /** + * Unique identifier for this interaction + * + * @member {number} + */ + this.identifier = null; + + /** + * Indicates whether or not the pointer device that created the event is the primary pointer. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary + * @type {Boolean} + */ + this.isPrimary = false; + + /** + * Indicates which button was pressed on the mouse or pointer device to trigger the event. + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button + * @type {number} + */ + this.button = 0; + + /** + * Indicates which buttons are pressed on the mouse or pointer device when the event is triggered. + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons + * @type {number} + */ + this.buttons = 0; + + /** + * The width of the pointer's contact along the x-axis, measured in CSS pixels. + * radiusX of TouchEvents will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width + * @type {number} + */ + this.width = 0; + + /** + * The height of the pointer's contact along the y-axis, measured in CSS pixels. + * radiusY of TouchEvents will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height + * @type {number} + */ + this.height = 0; + + /** + * The angle, in degrees, between the pointer device and the screen. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX + * @type {number} + */ + this.tiltX = 0; + + /** + * The angle, in degrees, between the pointer device and the screen. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY + * @type {number} + */ + this.tiltY = 0; + + /** + * The type of pointer that triggered the event. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType + * @type {string} + */ + this.pointerType = null; + + /** + * Pressure applied by the pointing device during the event. A Touch's force property + * will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure + * @type {number} + */ + this.pressure = 0; + + /** + * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch. + * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle + * @type {number} + */ + this.rotationAngle = 0; + + /** + * Twist of a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + * @type {number} + */ + this.twist = 0; + + /** + * Barrel pressure on a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + * @type {number} + */ + this.tangentialPressure = 0; + } + + /** + * The unique identifier of the pointer. It will be the same as `identifier`. + * @readonly + * @member {number} + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId + */ + + + /** + * This will return the local coordinates of the specified displayObject for this InteractionData + * + * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local + * coords off + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative + * to the DisplayObject + */ + InteractionData.prototype.getLocalPosition = function getLocalPosition(displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + + /** + * Copies properties from normalized event data. + * + * @param {Touch|MouseEvent|PointerEvent} event The normalized event data + * @private + */ + + + InteractionData.prototype._copyEvent = function _copyEvent(event) { + // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite + // it with "false" on later events when our shim for it on touch events might not be + // accurate + if (event.isPrimary) { + this.isPrimary = true; + } + this.button = event.button; + this.buttons = event.buttons; + this.width = event.width; + this.height = event.height; + this.tiltX = event.tiltX; + this.tiltY = event.tiltY; + this.pointerType = event.pointerType; + this.pressure = event.pressure; + this.rotationAngle = event.rotationAngle; + this.twist = event.twist || 0; + this.tangentialPressure = event.tangentialPressure || 0; + }; + + /** + * Resets the data for pooling. + * + * @private + */ + + + InteractionData.prototype._reset = function _reset() { + // isPrimary is the only property that we really need to reset - everything else is + // guaranteed to be overwritten + this.isPrimary = false; + }; + + _createClass(InteractionData, [{ + key: 'pointerId', + get: function get() { + return this.identifier; + } + }]); + + return InteractionData; +}(); + +exports.default = InteractionData; + +},{"../core":65}],156:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Event class that mimics native DOM events. + * + * @class + * @memberof PIXI.interaction + */ +var InteractionEvent = function () { + /** + * + */ + function InteractionEvent() { + _classCallCheck(this, InteractionEvent); + + /** + * Whether this event will continue propagating in the tree + * + * @member {boolean} + */ + this.stopped = false; + + /** + * The object which caused this event to be dispatched. + * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}. + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * The object whose event listener’s callback is currently being invoked. + * + * @member {PIXI.DisplayObject} + */ + this.currentTarget = null; + + /** + * Type of the event + * + * @member {string} + */ + this.type = null; + + /** + * InteractionData related to this event + * + * @member {PIXI.interaction.InteractionData} + */ + this.data = null; + } + + /** + * Prevents event from reaching any objects other than the current object. + * + */ + + + InteractionEvent.prototype.stopPropagation = function stopPropagation() { + this.stopped = true; + }; + + /** + * Resets the event. + * + * @private + */ + + + InteractionEvent.prototype._reset = function _reset() { + this.stopped = false; + this.currentTarget = null; + this.target = null; + }; + + return InteractionEvent; +}(); + +exports.default = InteractionEvent; + +},{}],157:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _InteractionData = require('./InteractionData'); + +var _InteractionData2 = _interopRequireDefault(_InteractionData); + +var _InteractionEvent = require('./InteractionEvent'); + +var _InteractionEvent2 = _interopRequireDefault(_InteractionEvent); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +var _InteractionTrackingData2 = _interopRequireDefault(_InteractionTrackingData); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _interactiveTarget = require('./interactiveTarget'); + +var _interactiveTarget2 = _interopRequireDefault(_interactiveTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// Mix interactiveTarget into core.DisplayObject.prototype, after deprecation has been handled +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _interactiveTarget2.default); + +var MOUSE_POINTER_ID = 'MOUSE'; + +// helpers for hitTest() - only used inside hitTest() +var hitTestEvent = { + target: null, + data: { + global: null + } +}; + +/** + * The interaction manager deals with mouse, touch and pointer events. Any DisplayObject can be interactive + * if its interactive parameter is set to true + * This manager also supports multitouch. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.interaction + * + * @class + * @extends EventEmitter + * @memberof PIXI.interaction + */ + +var InteractionManager = function (_EventEmitter) { + _inherits(InteractionManager, _EventEmitter); + + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + * @param {object} [options] - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Frequency increases the interaction events will be checked. + */ + function InteractionManager(renderer, options) { + _classCallCheck(this, InteractionManager); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + options = options || {}; + + /** + * The renderer this interaction manager works for. + * + * @member {PIXI.SystemRenderer} + */ + _this.renderer = renderer; + + /** + * Should default browser actions automatically be prevented. + * Does not apply to pointer events for backwards compatibility + * preventDefault on pointer events stops mouse events from firing + * Thus, for every pointer event, there will always be either a mouse of touch event alongside it. + * + * @member {boolean} + * @default true + */ + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + + /** + * Frequency in milliseconds that the mousemove, moveover & mouseout interaction events will be checked. + * + * @member {number} + * @default 10 + */ + _this.interactionFrequency = options.interactionFrequency || 10; + + /** + * The mouse data + * + * @member {PIXI.interaction.InteractionData} + */ + _this.mouse = new _InteractionData2.default(); + _this.mouse.identifier = MOUSE_POINTER_ID; + + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + + /** + * Actively tracked InteractionData + * + * @private + * @member {Object.} + */ + _this.activeInteractionData = {}; + _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; + + /** + * Pool of unused InteractionData + * + * @private + * @member {PIXI.interation.InteractionData[]} + */ + _this.interactionDataPool = []; + + /** + * An event data object to handle all the event tracking/dispatching + * + * @member {object} + */ + _this.eventData = new _InteractionEvent2.default(); + + /** + * The DOM element to bind to. + * + * @private + * @member {HTMLElement} + */ + _this.interactionDOMElement = null; + + /** + * This property determines if mousemove and touchmove events are fired only when the cursor + * is over the object. + * Setting to true will make things work more in line with how the DOM verison works. + * Setting to false can make things easier for things like dragging + * It is currently set to false as this is how PixiJS used to work. This will be set to true in + * future versions of pixi. + * + * @member {boolean} + * @default false + */ + _this.moveWhenInside = false; + + /** + * Have events been attached to the dom element? + * + * @private + * @member {boolean} + */ + _this.eventsAdded = false; + + /** + * Is the mouse hovering over the renderer? + * + * @private + * @member {boolean} + */ + _this.mouseOverRenderer = false; + + /** + * Does the device support touch events + * https://www.w3.org/TR/touch-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsTouchEvents = 'ontouchstart' in window; + + /** + * Does the device support pointer events + * https://www.w3.org/Submission/pointer-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsPointerEvents = !!window.PointerEvent; + + // this will make it so that you don't have to call bind all the time + + /** + * @private + * @member {Function} + */ + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerCancel = _this.onPointerCancel.bind(_this); + _this.processPointerCancel = _this.processPointerCancel.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOver = _this.onPointerOver.bind(_this); + + /** + * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor + * values, objects are handled as dictionaries of CSS values for interactionDOMElement, + * and functions are called instead of changing the CSS. + * Default CSS cursor values are provided for 'default' and 'pointer' modes. + * @member {Object.)>} + */ + _this.cursorStyles = { + default: 'inherit', + pointer: 'pointer' + }; + + /** + * The mode of the cursor that is being used. + * The value of this is a key from the cursorStyles dictionary. + * + * @member {string} + */ + _this.currentCursorMode = null; + + /** + * Internal cached let. + * + * @private + * @member {string} + */ + _this.cursor = null; + + /** + * Internal cached let. + * + * @private + * @member {PIXI.Point} + */ + _this._tempPoint = new core.Point(); + + /** + * The current resolution / device pixel ratio. + * + * @member {number} + * @default 1 + */ + _this.resolution = 1; + + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display + * object. + * + * @event PIXI.interaction.InteractionManager#mousedown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * + * @event PIXI.interaction.InteractionManager#rightdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. + * + * @event PIXI.interaction.InteractionManager#mouseup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * + * @event PIXI.interaction.InteractionManager#rightup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. + * + * @event PIXI.interaction.InteractionManager#click + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * + * @event PIXI.interaction.InteractionManager#rightclick + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. + * + * @event PIXI.interaction.InteractionManager#mouseupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. + * + * @event PIXI.interaction.InteractionManager#rightupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * + * @event PIXI.interaction.InteractionManager#mousemove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * + * @event PIXI.interaction.InteractionManager#mouseover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * + * @event PIXI.interaction.InteractionManager#mouseout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * + * @event PIXI.interaction.InteractionManager#pointerdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released over the display object. + * + * @event PIXI.interaction.InteractionManager#pointerup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a pointer event + * + * @event PIXI.interaction.InteractionManager#pointercancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * + * @event PIXI.interaction.InteractionManager#pointertap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}. + * + * @event PIXI.interaction.InteractionManager#pointerupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved while over the display object + * + * @event PIXI.interaction.InteractionManager#pointermove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved onto the display object + * + * @event PIXI.interaction.InteractionManager#pointerover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved off the display object + * + * @event PIXI.interaction.InteractionManager#pointerout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed on the display object. + * + * @event PIXI.interaction.InteractionManager#touchstart + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed from the display object. + * + * @event PIXI.interaction.InteractionManager#touchend + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a touch + * + * @event PIXI.interaction.InteractionManager#touchcancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * + * @event PIXI.interaction.InteractionManager#tap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. + * + * @event PIXI.interaction.InteractionManager#touchendoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is moved along the display object. + * + * @event PIXI.interaction.InteractionManager#touchmove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display. + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mousedown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#click + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightclick + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.DisplayObject#event:mousedown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.DisplayObject#event:rightdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mousemove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a pointer event. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointercancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointertap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointermove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchstart + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchend + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a touch. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchcancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#tap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchendoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is moved along the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchmove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + return _this; + } + + /** + * Hit tests a point against the display tree, returning the first interactive object that is hit. + * + * @param {PIXI.Point} globalPoint - A point to hit test with, in global space. + * @param {PIXI.Container} [root] - The root display object to start from. If omitted, defaults + * to the last rendered root of the associated renderer. + * @return {PIXI.DisplayObject} The hit display object, if any. + */ + + + InteractionManager.prototype.hitTest = function hitTest(globalPoint, root) { + // clear the target for our hit test + hitTestEvent.target = null; + // assign the global point + hitTestEvent.data.global = globalPoint; + // ensure safety of the root + if (!root) { + root = this.renderer._lastObjectRendered; + } + // run the hit test + this.processInteractive(hitTestEvent, root, null, true); + // return our found object - it'll be null if we didn't hit anything + + return hitTestEvent.target; + }; + + /** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate + * another DOM element to receive those events. + * + * @param {HTMLCanvasElement} element - the DOM element which will receive mouse and touch events. + * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). + */ + + + InteractionManager.prototype.setTargetElement = function setTargetElement(element) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.removeEvents(); + + this.interactionDOMElement = element; + + this.resolution = resolution; + + this.addEvents(); + }; + + /** + * Registers all the DOM events + * + * @private + */ + + + InteractionManager.prototype.addEvents = function addEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.INTERACTION); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; + this.interactionDOMElement.style['-ms-touch-action'] = 'none'; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = 'none'; + } + + /** + * These events are added first, so that if pointer events are normalised, they are fired + * in the same order as non-normalised events. ie. pointer event 1st, mouse / touch 2nd + */ + if (this.supportsPointerEvents) { + window.document.addEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); + // pointerout is fired in addition to pointerup (for touch events) and pointercancel + // we already handle those, so for the purposes of what we do in onPointerOut, we only + // care about the pointerleave event + this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); + window.addEventListener('pointercancel', this.onPointerCancel, true); + window.addEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.addEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); + window.addEventListener('mouseup', this.onPointerUp, true); + } + + // always look directly for touch events so that we can provide original data + // In a future version we should change this to being just a fallback and rely solely on + // PointerEvents whenever available + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); + } + + this.eventsAdded = true; + }; + + /** + * Removes all the DOM events that were previously registered + * + * @private + */ + + + InteractionManager.prototype.removeEvents = function removeEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.remove(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = ''; + this.interactionDOMElement.style['-ms-touch-action'] = ''; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = ''; + } + + if (this.supportsPointerEvents) { + window.document.removeEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); + window.removeEventListener('pointercancel', this.onPointerCancel, true); + window.removeEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.removeEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true); + window.removeEventListener('mouseup', this.onPointerUp, true); + } + + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); + } + + this.interactionDOMElement = null; + + this.eventsAdded = false; + }; + + /** + * Updates the state of interactive objects. + * Invoked by a throttled ticker update from {@link PIXI.ticker.shared}. + * + * @param {number} deltaTime - time delta since last tick + */ + + + InteractionManager.prototype.update = function update(deltaTime) { + this._deltaTime += deltaTime; + + if (this._deltaTime < this.interactionFrequency) { + return; + } + + this._deltaTime = 0; + + if (!this.interactionDOMElement) { + return; + } + + // if the user move the mouse this check has already been done using the mouse move! + if (this.didMove) { + this.didMove = false; + + return; + } + + this.cursor = null; + + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + for (var k in this.activeInteractionData) { + // eslint-disable-next-line no-prototype-builtins + if (this.activeInteractionData.hasOwnProperty(k)) { + var interactionData = this.activeInteractionData[k]; + + if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, true); + } + } + } + + this.setCursorMode(this.cursor); + + // TODO + }; + + /** + * Sets the current cursor mode, handling any callbacks or CSS style changes. + * + * @param {string} mode - cursor mode, a key from the cursorStyles dictionary + */ + + + InteractionManager.prototype.setCursorMode = function setCursorMode(mode) { + mode = mode || 'default'; + // if the mode didn't actually change, bail early + if (this.currentCursorMode === mode) { + return; + } + this.currentCursorMode = mode; + var style = this.cursorStyles[mode]; + + // only do things if there is a cursor style for it + if (style) { + switch (typeof style === 'undefined' ? 'undefined' : _typeof(style)) { + case 'string': + // string styles are handled as cursor CSS + this.interactionDOMElement.style.cursor = style; + break; + case 'function': + // functions are just called, and passed the cursor mode + style(mode); + break; + case 'object': + // if it is an object, assume that it is a dictionary of CSS styles, + // apply it to the interactionDOMElement + Object.assign(this.interactionDOMElement.style, style); + break; + } + } else if (typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) { + // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry + // for the mode, then assume that the dev wants it to be CSS for the cursor. + this.interactionDOMElement.style.cursor = mode; + } + }; + + /** + * Dispatches an event on the display object that was interacted with + * + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the display object in question + * @param {string} eventString - the name of the event (e.g, mousedown) + * @param {object} eventData - the event data object + * @private + */ + + + InteractionManager.prototype.dispatchEvent = function dispatchEvent(displayObject, eventString, eventData) { + if (!eventData.stopped) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + + displayObject.emit(eventString, eventData); + + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } + }; + + /** + * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. + * + * @param {PIXI.Point} point - the point that the result will be stored in + * @param {number} x - the x coord of the position to map + * @param {number} y - the y coord of the position to map + */ + + + InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint(point, x, y) { + var rect = void 0; + + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { x: 0, y: 0, width: 0, height: 0 }; + } else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + + var resolutionMultiplier = navigator.isCocoonJS ? this.resolution : 1.0 / this.resolution; + + point.x = (x - rect.left) * (this.interactionDOMElement.width / rect.width) * resolutionMultiplier; + point.y = (y - rect.top) * (this.interactionDOMElement.height / rect.height) * resolutionMultiplier; + }; + + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that + * is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param {Function} [func] - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point + * @param {boolean} [interactive] - Whether the displayObject is interactive + * @return {boolean} returns true if the displayObject hit the point + */ + + + InteractionManager.prototype.processInteractive = function processInteractive(interactionEvent, displayObject, func, hitTest, interactive) { + if (!displayObject || !displayObject.visible) { + return false; + } + + var point = interactionEvent.data.global; + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + interactive = displayObject.interactive || interactive; + + var hit = false; + var interactiveParent = interactive; + + // if the displayobject has a hitArea, then it does not need to hitTest children. + if (displayObject.hitArea) { + interactiveParent = false; + } + // it has a mask! Then lets hit test that before continuing + else if (hitTest && displayObject._mask) { + if (!displayObject._mask.containsPoint(point)) { + hitTest = false; + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow PixiJS to completely ignore and bypass checking the displayObjects children. + if (displayObject.interactiveChildren && displayObject.children) { + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + + // time to get recursive.. if this function will return if something is hit.. + var childHit = this.processInteractive(interactionEvent, child, func, hitTest, interactiveParent); + + if (childHit) { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if (!child.parent) { + continue; + } + + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + + if (childHit) { + if (interactionEvent.target) { + hitTest = false; + } + hit = true; + } + } + } + } + + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit - but only if it was interactive, otherwise we need to keep + // looking for an interactive child, just in case we hit one + if (hitTest && !interactionEvent.target) { + if (displayObject.hitArea) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hit = true; + } + } else if (displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = true; + } + } + } + + if (displayObject.interactive) { + if (hit && !interactionEvent.target) { + interactionEvent.target = displayObject; + } + + if (func) { + func(interactionEvent, displayObject, !!hit); + } + } + } + + return hit; + }; + + /** + * Is called when the pointer button is pressed down on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down + */ + + + InteractionManager.prototype.onPointerDown = function onPointerDown(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + /** + * No need to prevent default on natural pointer events, as there are no side effects + * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, + * so still need to be prevented. + */ + + // Guaranteed that there will be at least one event in events, and all events must have the same pointer type + + if (this.autoPreventDefault && events[0].isNormalized) { + originalEvent.preventDefault(); + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerDown, true); + + this.emit('pointerdown', interactionEvent); + if (event.pointerType === 'touch') { + this.emit('touchstart', interactionEvent); + } + // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event + else if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + } + }; + + /** + * Processes the result of the pointer down check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerDown = function processPointerDown(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + + if (hit) { + if (!displayObject.trackedPointers[id]) { + displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchstart', interactionEvent); + } else if (data.pointerType === 'mouse' || data.pointerType === 'pen') { + var isRightButton = data.button === 2; + + if (isRightButton) { + displayObject.trackedPointers[id].rightDown = true; + } else { + displayObject.trackedPointers[id].leftDown = true; + } + + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released + * @param {boolean} cancelled - true if the pointer is cancelled + * @param {Function} func - Function passed to {@link processInteractive} + */ + + + InteractionManager.prototype.onPointerComplete = function onPointerComplete(originalEvent, cancelled, func) { + var events = this.normalizeToPointerData(originalEvent); + + var eventLen = events.length; + + // if the event wasn't targeting our canvas, then consider it to be pointerupoutside + // in all cases (unless it was a pointercancel) + var eventAppend = originalEvent.target !== this.interactionDOMElement ? 'outside' : ''; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + // perform hit testing for events targeting our canvas or cancel events + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, func, cancelled || !eventAppend); + + this.emit(cancelled ? 'pointercancel' : 'pointerup' + eventAppend, interactionEvent); + + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + + this.emit(isRightButton ? 'rightup' + eventAppend : 'mouseup' + eventAppend, interactionEvent); + } else if (event.pointerType === 'touch') { + this.emit(cancelled ? 'touchcancel' : 'touchend' + eventAppend, interactionEvent); + this.releaseInteractionDataForPointerId(event.pointerId, interactionData); + } + } + }; + + /** + * Is called when the pointer button is cancelled + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerCancel = function onPointerCancel(event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') return; + + this.onPointerComplete(event, true, this.processPointerCancel); + }; + + /** + * Processes the result of the pointer cancel check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + */ + + + InteractionManager.prototype.processPointerCancel = function processPointerCancel(interactionEvent, displayObject) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + if (displayObject.trackedPointers[id] !== undefined) { + delete displayObject.trackedPointers[id]; + this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); + + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerUp = function onPointerUp(event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') return; + + this.onPointerComplete(event, false, this.processPointerUp); + }; + + /** + * Processes the result of the pointer up check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerUp = function processPointerUp(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + var trackingData = displayObject.trackedPointers[id]; + + var isTouch = data.pointerType === 'touch'; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + // Mouse only + if (isMouse) { + var isRightButton = data.button === 2; + + var flags = _InteractionTrackingData2.default.FLAGS; + + var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; + + var isDown = trackingData !== undefined && trackingData.flags & test; + + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); + + if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); + } + } else if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); + } + // update the down state of the tracking data + if (trackingData) { + if (isRightButton) { + trackingData.rightDown = false; + } else { + trackingData.leftDown = false; + } + } + } + + // Pointers and Touches, and Mouse + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchend', interactionEvent); + + if (trackingData) { + this.dispatchEvent(displayObject, 'pointertap', interactionEvent); + if (isTouch) { + this.dispatchEvent(displayObject, 'tap', interactionEvent); + // touches are no longer over (if they ever were) when we get the touchend + // so we should ensure that we don't keep pretending that they are + trackingData.over = false; + } + } + } else if (trackingData) { + this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); + } + // Only remove the tracking data if there is no over/down state still associated with it + if (trackingData && trackingData.none) { + delete displayObject.trackedPointers[id]; + } + }; + + /** + * Is called when the pointer moves across the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer moving + */ + + + InteractionManager.prototype.onPointerMove = function onPointerMove(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + if (events[0].pointerType === 'mouse') { + this.didMove = true; + + this.cursor = null; + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + var interactive = event.pointerType === 'touch' ? this.moveWhenInside : true; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerMove, interactive); + this.emit('pointermove', interactionEvent); + if (event.pointerType === 'touch') this.emit('touchmove', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') this.emit('mousemove', interactionEvent); + } + + if (events[0].pointerType === 'mouse') { + this.setCursorMode(this.cursor); + + // TODO BUG for parents interactive object (border order issue) + } + }; + + /** + * Processes the result of the pointer move check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerMove = function processPointerMove(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var isTouch = data.pointerType === 'touch'; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + if (isMouse) { + this.processPointerOverOut(interactionEvent, displayObject, hit); + } + + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchmove', interactionEvent); + if (isMouse) this.dispatchEvent(displayObject, 'mousemove', interactionEvent); + } + }; + + /** + * Is called when the pointer is moved out of the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out + */ + + + InteractionManager.prototype.onPointerOut = function onPointerOut(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOut, so events will always be length 1 + var event = events[0]; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = false; + this.setCursorMode(null); + } + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, false); + + this.emit('pointerout', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseout', interactionEvent); + } else { + // we can get touchleave events after touchend, so we want to make sure we don't + // introduce memory leaks + this.releaseInteractionDataForPointerId(interactionData.identifier); + } + }; + + /** + * Processes the result of the pointer over/out check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerOverOut = function processPointerOverOut(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + var trackingData = displayObject.trackedPointers[id]; + + // if we just moused over the display object, then we need to track that state + if (hit && !trackingData) { + trackingData = displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + + if (trackingData === undefined) return; + + if (hit && this.mouseOverRenderer) { + if (!trackingData.over) { + trackingData.over = true; + this.dispatchEvent(displayObject, 'pointerover', interactionEvent); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseover', interactionEvent); + } + } + + // only change the cursor if it has not already been changed (by something deeper in the + // display tree) + if (isMouse && this.cursor === null) { + this.cursor = displayObject.cursor; + } + } else if (trackingData.over) { + trackingData.over = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseout', interactionEvent); + } + // if there is no mouse down information for the pointer, then it is safe to delete + if (trackingData.none) { + delete displayObject.trackedPointers[id]; + } + } + }; + + /** + * Is called when the pointer is moved into the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view + */ + + + InteractionManager.prototype.onPointerOver = function onPointerOver(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOver, so events will always be length 1 + var event = events[0]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = true; + } + + this.emit('pointerover', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseover', interactionEvent); + } + }; + + /** + * Get InteractionData for a given pointerId. Store that data as well + * + * @private + * @param {PointerEvent} event - Normalized pointer event, output from normalizeToPointerData + * @return {PIXI.interaction.InteractionData} - Interaction data for the given pointer identifier + */ + + + InteractionManager.prototype.getInteractionDataForPointerId = function getInteractionDataForPointerId(event) { + var pointerId = event.pointerId; + + var interactionData = void 0; + + if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { + interactionData = this.mouse; + } else if (this.activeInteractionData[pointerId]) { + interactionData = this.activeInteractionData[pointerId]; + } else { + interactionData = this.interactionDataPool.pop() || new _InteractionData2.default(); + interactionData.identifier = pointerId; + this.activeInteractionData[pointerId] = interactionData; + } + // copy properties from the event, so that we can make sure that touch/pointer specific + // data is available + interactionData._copyEvent(event); + + return interactionData; + }; + + /** + * Return unused InteractionData to the pool, for a given pointerId + * + * @private + * @param {number} pointerId - Identifier from a pointer event + */ + + + InteractionManager.prototype.releaseInteractionDataForPointerId = function releaseInteractionDataForPointerId(pointerId) { + var interactionData = this.activeInteractionData[pointerId]; + + if (interactionData) { + delete this.activeInteractionData[pointerId]; + interactionData._reset(); + this.interactionDataPool.push(interactionData); + } + }; + + /** + * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The event to be configured + * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent + * @param {PIXI.interaction.InteractionData} interactionData - The InteractionData that will be paired + * with the InteractionEvent + * @return {PIXI.interaction.InteractionEvent} the interaction event that was passed in + */ + + + InteractionManager.prototype.configureInteractionEventForDOMEvent = function configureInteractionEventForDOMEvent(interactionEvent, pointerEvent, interactionData) { + interactionEvent.data = interactionData; + + this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); + + // This is the way InteractionManager processed touch events before the refactoring, so I've kept + // it here. But it doesn't make that much sense to me, since mapPositionToPoint already factors + // in this.resolution, so this just divides by this.resolution twice for touch events... + if (navigator.isCocoonJS && pointerEvent.pointerType === 'touch') { + interactionData.global.x = interactionData.global.x / this.resolution; + interactionData.global.y = interactionData.global.y / this.resolution; + } + + // Not really sure why this is happening, but it's how a previous version handled things + if (pointerEvent.pointerType === 'touch') { + pointerEvent.globalX = interactionData.global.x; + pointerEvent.globalY = interactionData.global.y; + } + + interactionData.originalEvent = pointerEvent; + interactionEvent._reset(); + + return interactionEvent; + }; + + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * + * @private + * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event + * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer + * or mouse event, or a multiple normalized pointer events if there are multiple changed touches + */ + + + InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData(event) { + var normalizedEvents = []; + + if (this.supportsTouchEvents && event instanceof TouchEvent) { + for (var i = 0, li = event.changedTouches.length; i < li; i++) { + var touch = event.changedTouches[i]; + + if (typeof touch.button === 'undefined') touch.button = event.touches.length ? 1 : 0; + if (typeof touch.buttons === 'undefined') touch.buttons = event.touches.length ? 1 : 0; + if (typeof touch.isPrimary === 'undefined') { + touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart'; + } + if (typeof touch.width === 'undefined') touch.width = touch.radiusX || 1; + if (typeof touch.height === 'undefined') touch.height = touch.radiusY || 1; + if (typeof touch.tiltX === 'undefined') touch.tiltX = 0; + if (typeof touch.tiltY === 'undefined') touch.tiltY = 0; + if (typeof touch.pointerType === 'undefined') touch.pointerType = 'touch'; + if (typeof touch.pointerId === 'undefined') touch.pointerId = touch.identifier || 0; + if (typeof touch.pressure === 'undefined') touch.pressure = touch.force || 0.5; + touch.twist = 0; + touch.tangentialPressure = 0; + // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven + // support, and the fill ins are not quite the same + // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top + // left is not 0,0 on the page + if (typeof touch.layerX === 'undefined') touch.layerX = touch.offsetX = touch.clientX; + if (typeof touch.layerY === 'undefined') touch.layerY = touch.offsetY = touch.clientY; + + // mark the touch as normalized, just so that we know we did it + touch.isNormalized = true; + + normalizedEvents.push(touch); + } + } + // apparently PointerEvent subclasses MouseEvent, so yay + else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent))) { + if (typeof event.isPrimary === 'undefined') event.isPrimary = true; + if (typeof event.width === 'undefined') event.width = 1; + if (typeof event.height === 'undefined') event.height = 1; + if (typeof event.tiltX === 'undefined') event.tiltX = 0; + if (typeof event.tiltY === 'undefined') event.tiltY = 0; + if (typeof event.pointerType === 'undefined') event.pointerType = 'mouse'; + if (typeof event.pointerId === 'undefined') event.pointerId = MOUSE_POINTER_ID; + if (typeof event.pressure === 'undefined') event.pressure = 0.5; + event.twist = 0; + event.tangentialPressure = 0; + + // mark the mouse event as normalized, just so that we know we did it + event.isNormalized = true; + + normalizedEvents.push(event); + } else { + normalizedEvents.push(event); + } + + return normalizedEvents; + }; + + /** + * Destroys the interaction manager + * + */ + + + InteractionManager.prototype.destroy = function destroy() { + this.removeEvents(); + + this.removeAllListeners(); + + this.renderer = null; + + this.mouse = null; + + this.eventData = null; + + this.interactionDOMElement = null; + + this.onPointerDown = null; + this.processPointerDown = null; + + this.onPointerUp = null; + this.processPointerUp = null; + + this.onPointerCancel = null; + this.processPointerCancel = null; + + this.onPointerMove = null; + this.processPointerMove = null; + + this.onPointerOut = null; + this.processPointerOverOut = null; + + this.onPointerOver = null; + + this._tempPoint = null; + }; + + return InteractionManager; +}(_eventemitter2.default); + +exports.default = InteractionManager; + + +core.WebGLRenderer.registerPlugin('interaction', InteractionManager); +core.CanvasRenderer.registerPlugin('interaction', InteractionManager); + +},{"../core":65,"./InteractionData":155,"./InteractionEvent":156,"./InteractionTrackingData":158,"./interactiveTarget":160,"eventemitter3":3}],158:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * DisplayObjects with the {@link PIXI.interaction.interactiveTarget} mixin use this class to track interactions + * + * @class + * @private + * @memberof PIXI.interaction + */ +var InteractionTrackingData = function () { + /** + * @param {number} pointerId - Unique pointer id of the event + */ + function InteractionTrackingData(pointerId) { + _classCallCheck(this, InteractionTrackingData); + + this._pointerId = pointerId; + this._flags = InteractionTrackingData.FLAGS.NONE; + } + + /** + * + * @private + * @param {number} flag - The interaction flag to set + * @param {boolean} yn - Should the flag be set or unset + */ + + + InteractionTrackingData.prototype._doSet = function _doSet(flag, yn) { + if (yn) { + this._flags = this._flags | flag; + } else { + this._flags = this._flags & ~flag; + } + }; + + /** + * Unique pointer id of the event + * + * @readonly + * @member {number} + */ + + + _createClass(InteractionTrackingData, [{ + key: "pointerId", + get: function get() { + return this._pointerId; + } + + /** + * State of the tracking data, expressed as bit flags + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "flags", + get: function get() { + return this._flags; + } + + /** + * Set the flags for the tracking data + * + * @param {number} flags - Flags to set + */ + , + set: function set(flags) { + this._flags = flags; + } + + /** + * Is the tracked event inactive (not over or down)? + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "none", + get: function get() { + return this._flags === this.constructor.FLAGS.NONE; + } + + /** + * Is the tracked event over the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "over", + get: function get() { + return (this._flags & this.constructor.FLAGS.OVER) !== 0; + } + + /** + * Set the over flag + * + * @param {boolean} yn - Is the event over? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.OVER, yn); + } + + /** + * Did the right mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "rightDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.RIGHT_DOWN) !== 0; + } + + /** + * Set the right down flag + * + * @param {boolean} yn - Is the right mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.RIGHT_DOWN, yn); + } + + /** + * Did the left mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "leftDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.LEFT_DOWN) !== 0; + } + + /** + * Set the left down flag + * + * @param {boolean} yn - Is the left mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.LEFT_DOWN, yn); + } + }]); + + return InteractionTrackingData; +}(); + +exports.default = InteractionTrackingData; + + +InteractionTrackingData.FLAGS = Object.freeze({ + NONE: 0, + OVER: 1 << 0, + LEFT_DOWN: 1 << 1, + RIGHT_DOWN: 1 << 2 +}); + +},{}],159:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _InteractionData = require('./InteractionData'); + +Object.defineProperty(exports, 'InteractionData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionData).default; + } +}); + +var _InteractionManager = require('./InteractionManager'); + +Object.defineProperty(exports, 'InteractionManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionManager).default; + } +}); + +var _interactiveTarget = require('./interactiveTarget'); + +Object.defineProperty(exports, 'interactiveTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_interactiveTarget).default; + } +}); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +Object.defineProperty(exports, 'InteractionTrackingData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionTrackingData).default; + } +}); + +var _InteractionEvent = require('./InteractionEvent'); + +Object.defineProperty(exports, 'InteractionEvent', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionEvent).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./InteractionData":155,"./InteractionEvent":156,"./InteractionManager":157,"./InteractionTrackingData":158,"./interactiveTarget":160}],160:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * Default property values of interactive objects + * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties + * + * @private + * @name interactiveTarget + * @memberof PIXI.interaction + * @example + * function MyObject() {} + * + * Object.assign( + * core.DisplayObject.prototype, + * PIXI.interaction.interactiveTarget + * ); + */ +exports.default = { + + /** + * Enable interaction events for the DisplayObject. Touch, pointer and mouse + * events will not be emitted unless `interactive` is set to `true`. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.on('tap', (event) => { + * //handle event + * }); + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + interactive: false, + + /** + * Determines if the children to the displayObject can be clicked/touched + * Setting this to false allows PixiJS to bypass a recursive `hitTest` function + * + * @member {boolean} + * @memberof PIXI.Container# + */ + interactiveChildren: true, + + /** + * Interaction shape. Children will be hit first, then this shape will be checked. + * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.hitArea = new PIXI.Rectangle(0, 0, 100, 100); + * @member {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle} + * @memberof PIXI.DisplayObject# + */ + hitArea: null, + + /** + * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive + * Setting this changes the 'cursor' property to `'pointer'`. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.buttonMode = true; + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + get buttonMode() { + return this.cursor === 'pointer'; + }, + set buttonMode(value) { + if (value) { + this.cursor = 'pointer'; + } else if (this.cursor === 'pointer') { + this.cursor = null; + } + }, + + /** + * This defines what cursor mode is used when the mouse cursor + * is hovered over the displayObject. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.cursor = 'wait'; + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * + * @member {string} + * @memberof PIXI.DisplayObject# + */ + cursor: null, + + /** + * Internal set of all active pointers, by identifier + * + * @member {Map} + * @memberof PIXI.DisplayObject# + * @private + */ + get trackedPointers() { + if (this._trackedPointers === undefined) this._trackedPointers = {}; + + return this._trackedPointers; + }, + + /** + * Map of all tracked pointers, by identifier. Use trackedPointers to access. + * + * @private + * @type {Map} + */ + _trackedPointers: undefined +}; + +},{}],161:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.parse = parse; + +exports.default = function () { + return function bitmapFontParser(resource, next) { + // skip if no data or not xml data + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.XML) { + next(); + + return; + } + + // skip if not bitmap font data, using some silly duck-typing + if (resource.data.getElementsByTagName('page').length === 0 || resource.data.getElementsByTagName('info').length === 0 || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null) { + next(); + + return; + } + + var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; + + if (resource.isDataUrl) { + if (xmlUrl === '.') { + xmlUrl = ''; + } + + if (this.baseUrl && xmlUrl) { + // if baseurl has a trailing slash then add one to xmlUrl so the replace works below + if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { + xmlUrl += '/'; + } + } + } + + // remove baseUrl from xmlUrl + xmlUrl = xmlUrl.replace(this.baseUrl, ''); + + // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { + xmlUrl += '/'; + } + + var textureUrl = xmlUrl + resource.data.getElementsByTagName('page')[0].getAttribute('file'); + + if (_core.utils.TextureCache[textureUrl]) { + // reuse existing texture + parse(resource, _core.utils.TextureCache[textureUrl]); + next(); + } else { + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + // load the texture for the font + this.add(resource.name + '_image', textureUrl, loadOptions, function (res) { + parse(resource, res.texture); + next(); + }); + } + }; +}; + +var _path = require('path'); + +var path = _interopRequireWildcard(_path); + +var _core = require('../core'); + +var _resourceLoader = require('resource-loader'); + +var _extras = require('../extras'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Register a BitmapText font from loader resource. + * + * @function parseBitmapFontData + * @memberof PIXI.loaders + * @param {PIXI.loaders.Resource} resource - Loader resource. + * @param {PIXI.Texture} texture - Reference to texture. + */ +function parse(resource, texture) { + resource.bitmapFont = _extras.BitmapText.registerFont(resource.data, texture); +} + +},{"../core":65,"../extras":141,"path":23,"resource-loader":36}],162:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.shared = exports.Resource = exports.textureParser = exports.getResourcePath = exports.spritesheetParser = exports.parseBitmapFontData = exports.bitmapFontParser = exports.Loader = undefined; + +var _bitmapFontParser = require('./bitmapFontParser'); + +Object.defineProperty(exports, 'bitmapFontParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_bitmapFontParser).default; + } +}); +Object.defineProperty(exports, 'parseBitmapFontData', { + enumerable: true, + get: function get() { + return _bitmapFontParser.parse; + } +}); + +var _spritesheetParser = require('./spritesheetParser'); + +Object.defineProperty(exports, 'spritesheetParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_spritesheetParser).default; + } +}); +Object.defineProperty(exports, 'getResourcePath', { + enumerable: true, + get: function get() { + return _spritesheetParser.getResourcePath; + } +}); + +var _textureParser = require('./textureParser'); + +Object.defineProperty(exports, 'textureParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_textureParser).default; + } +}); + +var _resourceLoader = require('resource-loader'); + +Object.defineProperty(exports, 'Resource', { + enumerable: true, + get: function get() { + return _resourceLoader.Resource; + } +}); + +var _Application = require('../core/Application'); + +var _Application2 = _interopRequireDefault(_Application); + +var _loader = require('./loader'); + +var _loader2 = _interopRequireDefault(_loader); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * This namespace contains APIs which extends the {@link https://github.com/englercj/resource-loader resource-loader} module + * for loading assets, data, and other resources dynamically. + * @example + * const loader = new PIXI.loaders.Loader(); + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.load((loader, resources) => { + * // resources.bunny + * // resources.spaceship + * }); + * @namespace PIXI.loaders + */ +exports.Loader = _loader2.default; + + +/** + * A premade instance of the loader that can be used to load resources. + * @name shared + * @memberof PIXI.loaders + * @type {PIXI.loaders.Loader} + */ +var shared = new _loader2.default(); + +shared.destroy = function () { + // protect destroying shared loader +}; + +exports.shared = shared; + +// Mixin the loader construction + +var AppPrototype = _Application2.default.prototype; + +AppPrototype._loader = null; + +/** + * Loader instance to help with asset loading. + * @name PIXI.Application#loader + * @type {PIXI.loaders.Loader} + */ +Object.defineProperty(AppPrototype, 'loader', { + get: function get() { + if (!this._loader) { + var sharedLoader = this._options.sharedLoader; + + this._loader = sharedLoader ? shared : new _loader2.default(); + } + + return this._loader; + } +}); + +// Override the destroy function +// making sure to destroy the current Loader +AppPrototype._parentDestroy = AppPrototype.destroy; +AppPrototype.destroy = function destroy(removeView) { + if (this._loader) { + this._loader.destroy(); + this._loader = null; + } + this._parentDestroy(removeView); +}; + +},{"../core/Application":43,"./bitmapFontParser":161,"./loader":163,"./spritesheetParser":164,"./textureParser":165,"resource-loader":36}],163:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _resourceLoader = require('resource-loader'); + +var _resourceLoader2 = _interopRequireDefault(_resourceLoader); + +var _blob = require('resource-loader/lib/middlewares/parsing/blob'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _textureParser = require('./textureParser'); + +var _textureParser2 = _interopRequireDefault(_textureParser); + +var _spritesheetParser = require('./spritesheetParser'); + +var _spritesheetParser2 = _interopRequireDefault(_spritesheetParser); + +var _bitmapFontParser = require('./bitmapFontParser'); + +var _bitmapFontParser2 = _interopRequireDefault(_bitmapFontParser); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader + * + * ```js + * const loader = PIXI.loader; // PixiJS exposes a premade instance for you to use. + * //or + * const loader = new PIXI.loaders.Loader(); // you can also create your own if you want + * + * const sprites = {}; + * + * // Chainable `add` to enqueue a resource + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.add('scoreFont', 'assets/score.fnt'); + * + * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. + * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). + * loader.pre(cachingMiddleware); + * + * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. + * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). + * loader.use(parsingMiddleware); + * + * // The `load` method loads the queue of resources, and calls the passed in callback called once all + * // resources have loaded. + * loader.load((loader, resources) => { + * // resources is an object where the key is the name of the resource loaded and the value is the resource object. + * // They have a couple default properties: + * // - `url`: The URL that the resource was loaded from + * // - `error`: The error that happened when trying to load (if any) + * // - `data`: The raw data that was loaded + * // also may contain other properties based on the middleware that runs. + * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); + * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); + * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); + * }); + * + * // throughout the process multiple signals can be dispatched. + * loader.onProgress.add(() => {}); // called once per loaded/errored file + * loader.onError.add(() => {}); // called once per errored file + * loader.onLoad.add(() => {}); // called once per loaded file + * loader.onComplete.add(() => {}); // called once when the queued resources all load. + * ``` + * + * @see https://github.com/englercj/resource-loader + * + * @class + * @extends module:resource-loader.ResourceLoader + * @memberof PIXI.loaders + */ +var Loader = function (_ResourceLoader) { + _inherits(Loader, _ResourceLoader); + + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + _classCallCheck(this, Loader); + + var _this = _possibleConstructorReturn(this, _ResourceLoader.call(this, baseUrl, concurrency)); + + _eventemitter2.default.call(_this); + + for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { + _this.use(Loader._pixiMiddleware[i]()); + } + + // Compat layer, translate the new v2 signals into old v1 events. + _this.onStart.add(function (l) { + return _this.emit('start', l); + }); + _this.onProgress.add(function (l, r) { + return _this.emit('progress', l, r); + }); + _this.onError.add(function (e, l, r) { + return _this.emit('error', e, l, r); + }); + _this.onLoad.add(function (l, r) { + return _this.emit('load', l, r); + }); + _this.onComplete.add(function (l, r) { + return _this.emit('complete', l, r); + }); + return _this; + } + + /** + * Adds a default middleware to the PixiJS loader. + * + * @static + * @param {Function} fn - The middleware to add. + */ + + + Loader.addPixiMiddleware = function addPixiMiddleware(fn) { + Loader._pixiMiddleware.push(fn); + }; + + /** + * Destroy the loader, removes references. + */ + + + Loader.prototype.destroy = function destroy() { + this.removeAllListeners(); + this.reset(); + }; + + return Loader; +}(_resourceLoader2.default); + +// Copy EE3 prototype (mixin) + + +exports.default = Loader; +for (var k in _eventemitter2.default.prototype) { + Loader.prototype[k] = _eventemitter2.default.prototype[k]; +} + +Loader._pixiMiddleware = [ +// parse any blob into more usable objects (e.g. Image) +_blob.blobMiddlewareFactory, +// parse any Image objects into textures +_textureParser2.default, +// parse any spritesheet data into multiple textures +_spritesheetParser2.default, +// parse bitmap font data into multiple textures +_bitmapFontParser2.default]; + +// Add custom extentions +var Resource = _resourceLoader2.default.Resource; + +Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); + +},{"./bitmapFontParser":161,"./spritesheetParser":164,"./textureParser":165,"eventemitter3":3,"resource-loader":36,"resource-loader/lib/middlewares/parsing/blob":37}],164:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function spritesheetParser(resource, next) { + var imageResourceName = resource.name + '_image'; + + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.JSON || !resource.data.frames || this.resources[imageResourceName]) { + next(); + + return; + } + + var loadOptions = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + var resourcePath = getResourcePath(resource, this.baseUrl); + + // load the image for this sheet + this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + var spritesheet = new _core.Spritesheet(res.texture.baseTexture, resource.data, resource.url); + + spritesheet.parse(function () { + resource.spritesheet = spritesheet; + resource.textures = spritesheet.textures; + next(); + }); + }); + }; +}; + +exports.getResourcePath = getResourcePath; + +var _resourceLoader = require('resource-loader'); + +var _url = require('url'); + +var _url2 = _interopRequireDefault(_url); + +var _core = require('../core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function getResourcePath(resource, baseUrl) { + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + return resource.data.meta.image; + } + + return _url2.default.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); +} + +},{"../core":65,"resource-loader":36,"url":29}],165:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function textureParser(resource, next) { + // create a new texture if the data is an Image object + if (resource.data && resource.type === _resourceLoader.Resource.TYPE.IMAGE) { + resource.texture = _Texture2.default.fromLoader(resource.data, resource.url, resource.name); + } + next(); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"../core/textures/Texture":115,"resource-loader":36}],166:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); +var tempPolygon = new core.Polygon(); + +/** + * Base mesh class + * @class + * @extends PIXI.Container + * @memberof PIXI.mesh + */ + +var Mesh = function (_core$Container) { + _inherits(Mesh, _core$Container); + + /** + * @param {PIXI.Texture} texture - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts + */ + function Mesh(texture, vertices, uvs, indices, drawMode) { + _classCallCheck(this, Mesh); + + /** + * The texture of the Mesh + * + * @member {PIXI.Texture} + * @default PIXI.Texture.EMPTY + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._texture = texture || _Texture2.default.EMPTY; + + /** + * The Uvs of the Mesh + * + * @member {Float32Array} + */ + _this.uvs = uvs || new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + /** + * An array of vertices + * + * @member {Float32Array} + */ + _this.vertices = vertices || new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]); + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + // TODO auto generate this based on draw mode! + _this.indices = indices || new Uint16Array([0, 1, 3, 2]); + + /** + * Version of mesh uvs are dirty or not + * + * @member {number} + */ + _this.dirty = 0; + + /** + * Version of mesh indices + * + * @member {number} + */ + _this.indexDirty = 0; + + /** + * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove + * any blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles + * to overlap a bit with each other. + * + * @member {number} + */ + _this.canvasPadding = 0; + + /** + * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts + * + * @member {number} + * @see PIXI.mesh.Mesh.DRAW_MODES + */ + _this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH; + + /** + * The default shader that is used if a mesh doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + _this.shader = null; + + /** + * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any + * tint effect. + * + * @member {number} + */ + _this.tintRgb = new Float32Array([1, 1, 1]); + + /** + * A map of renderer IDs to webgl render data + * + * @private + * @member {object} + */ + _this._glDatas = {}; + + /** + * transform that is applied to UV to get the texture coords + * its updated independently from texture uvTransform + * updates of uvs are tied to that thing + * + * @member {PIXI.TextureMatrix} + * @private + */ + _this._uvTransform = new core.TextureMatrix(_this._texture); + + /** + * whether or not upload uvTransform to shader + * if its false, then uvs should be pre-multiplied + * if you change it for generated mesh, please call 'refresh(true)' + * @member {boolean} + * @default false + */ + _this.uploadUvTransform = false; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * @member {string} + * @default 'mesh' + */ + _this.pluginName = 'mesh'; + return _this; + } + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - a reference to the WebGL renderer + */ + + + Mesh.prototype._renderWebGL = function _renderWebGL(renderer) { + this.refresh(); + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + + + Mesh.prototype._renderCanvas = function _renderCanvas(renderer) { + this.refresh(); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Mesh.prototype._onTextureUpdate = function _onTextureUpdate() { + this._uvTransform.texture = this._texture; + this.refresh(); + }; + + /** + * multiplies uvs only if uploadUvTransform is false + * call it after you change uvs manually + * make sure that texture is valid + */ + + + Mesh.prototype.multiplyUvs = function multiplyUvs() { + if (!this.uploadUvTransform) { + this._uvTransform.multiplyUvs(this.uvs); + } + }; + + /** + * Refreshes uvs for generated meshes (rope, plane) + * sometimes refreshes vertices too + * + * @param {boolean} [forceUpdate=false] if true, matrices will be updated any case + */ + + + Mesh.prototype.refresh = function refresh(forceUpdate) { + if (this._uvTransform.update(forceUpdate)) { + this._refresh(); + } + }; + + /** + * re-calculates mesh coords + * @protected + */ + + + Mesh.prototype._refresh = function _refresh() {} + /* empty */ + + + /** + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + */ + ; + + Mesh.prototype._calculateBounds = function _calculateBounds() { + // TODO - we can cache local bounds and use them if they are dirty (like graphics) + this._bounds.addVertices(this.transform, this.vertices, 0, this.vertices.length); + }; + + /** + * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Mesh.prototype.containsPoint = function containsPoint(point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + + this.worldTransform.applyInverse(point, tempPoint); + + var vertices = this.vertices; + var points = tempPolygon.points; + var indices = this.indices; + var len = this.indices.length; + var step = this.drawMode === Mesh.DRAW_MODES.TRIANGLES ? 3 : 1; + + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + + return false; + }; + + /** + * The texture that the mesh uses. + * + * @member {PIXI.Texture} + */ + + + _createClass(Mesh, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + + /** + * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return core.utils.rgb2hex(this.tintRgb); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tintRgb = core.utils.hex2rgb(value, this.tintRgb); + } + }]); + + return Mesh; +}(core.Container); + +/** + * Different drawing buffer modes supported + * + * @static + * @constant + * @type {object} + * @property {number} TRIANGLE_MESH + * @property {number} TRIANGLES + */ + + +exports.default = Mesh; +Mesh.DRAW_MODES = { + TRIANGLE_MESH: 0, + TRIANGLES: 1 +}; + +},{"../core":65,"../core/textures/Texture":115}],167:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Plane2 = require('./Plane'); + +var _Plane3 = _interopRequireDefault(_Plane2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DEFAULT_BORDER_SIZE = 10; + +/** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.fromImage('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
+ *      A                          B
+ *    +---+----------------------+---+
+ *  C | 1 |          2           | 3 |
+ *    +---+----------------------+---+
+ *    |   |                      |   |
+ *    | 4 |          5           | 6 |
+ *    |   |                      |   |
+ *    +---+----------------------+---+
+ *  D | 7 |          8           | 9 |
+ *    +---+----------------------+---+
+
+ *  When changing this objects width and/or height:
+ *     areas 1 3 7 and 9 will remain unscaled.
+ *     areas 2 and 8 will be stretched horizontally
+ *     areas 4 and 6 will be stretched vertically
+ *     area 5 will be stretched both horizontally and vertically
+ * 
+ * + * @class + * @extends PIXI.mesh.Plane + * @memberof PIXI.mesh + * + */ + +var NineSlicePlane = function (_Plane) { + _inherits(NineSlicePlane, _Plane); + + /** + * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. + * @param {int} [leftWidth=10] size of the left vertical bar (A) + * @param {int} [topHeight=10] size of the top horizontal bar (C) + * @param {int} [rightWidth=10] size of the right vertical bar (B) + * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) + */ + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + _classCallCheck(this, NineSlicePlane); + + var _this = _possibleConstructorReturn(this, _Plane.call(this, texture, 4, 4)); + + _this._origWidth = texture.orig.width; + _this._origHeight = texture.orig.height; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._width = _this._origWidth; + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._height = _this._origHeight; + + /** + * The width of the left column (a) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; + + /** + * The width of the right column (b) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; + + /** + * The height of the top row (c) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; + + /** + * The height of the bottom row (d) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this.bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; + + _this.refresh(true); + return _this; + } + + /** + * Updates the horizontal vertices. + * + */ + + + NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices() { + var vertices = this.vertices; + + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight; + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + }; + + /** + * Updates the vertical vertices. + * + */ + + + NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices() { + var vertices = this.vertices; + + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth; + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with. + */ + + + NineSlicePlane.prototype._renderCanvas = function _renderCanvas(renderer) { + var context = renderer.context; + + context.globalAlpha = this.worldAlpha; + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + var base = this._texture.baseTexture; + var textureSource = base.source; + var w = base.width * base.resolution; + var h = base.height * base.resolution; + + this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11); + this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13); + this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15); + this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19); + this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21); + this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23); + this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27); + this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29); + this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31); + }; + + /** + * Renders one segment of the plane. + * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure + * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used. + * + * @private + * @param {CanvasRenderingContext2D} context - The context to draw with. + * @param {CanvasImageSource} textureSource - The source to draw. + * @param {number} w - width of the texture + * @param {number} h - height of the texture + * @param {number} x1 - x index 1 + * @param {number} y1 - y index 1 + * @param {number} x2 - x index 2 + * @param {number} y2 - y index 2 + */ + + + NineSlicePlane.prototype.drawSegment = function drawSegment(context, textureSource, w, h, x1, y1, x2, y2) { + // otherwise you get weird results when using slices of that are 0 wide or high. + var uvs = this.uvs; + var vertices = this.vertices; + + var sw = (uvs[x2] - uvs[x1]) * w; + var sh = (uvs[y2] - uvs[y1]) * h; + var dw = vertices[x2] - vertices[x1]; + var dh = vertices[y2] - vertices[y1]; + + // make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn. + if (sw < 1) { + sw = 1; + } + + if (sh < 1) { + sh = 1; + } + + // make sure destination is at least 1 pixel wide and high, otherwise you get + // lines when rendering close to original size. + if (dw < 1) { + dw = 1; + } + + if (dh < 1) { + dh = 1; + } + + context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh); + }; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + + /** + * Refreshes NineSlicePlane coords. All of them. + */ + NineSlicePlane.prototype._refresh = function _refresh() { + _Plane.prototype._refresh.call(this); + + var uvs = this.uvs; + var texture = this._texture; + + this._origWidth = texture.orig.width; + this._origHeight = texture.orig.height; + + var _uvw = 1.0 / this._origWidth; + var _uvh = 1.0 / this._origHeight; + + uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; + uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - _uvw * this._rightWidth; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - _uvh * this._bottomHeight; + + this.updateHorizontalVertices(); + this.updateVerticalVertices(); + + this.dirty++; + + this.multiplyUvs(); + }; + + _createClass(NineSlicePlane, [{ + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + this._refresh(); + } + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + this._refresh(); + } + + /** + * The width of the left column + * + * @member {number} + */ + + }, { + key: 'leftWidth', + get: function get() { + return this._leftWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._leftWidth = value; + this._refresh(); + } + + /** + * The width of the right column + * + * @member {number} + */ + + }, { + key: 'rightWidth', + get: function get() { + return this._rightWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rightWidth = value; + this._refresh(); + } + + /** + * The height of the top row + * + * @member {number} + */ + + }, { + key: 'topHeight', + get: function get() { + return this._topHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._topHeight = value; + this._refresh(); + } + + /** + * The height of the bottom row + * + * @member {number} + */ + + }, { + key: 'bottomHeight', + get: function get() { + return this._bottomHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._bottomHeight = value; + this._refresh(); + } + }]); + + return NineSlicePlane; +}(_Plane3.default); + +exports.default = NineSlicePlane; + +},{"./Plane":168}],168:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The Plane allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Plane = function (_Mesh) { + _inherits(Plane, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the Plane. + * @param {number} verticesX - The number of vertices in the x-axis + * @param {number} verticesY - The number of vertices in the y-axis + */ + function Plane(texture, verticesX, verticesY) { + _classCallCheck(this, Plane); + + /** + * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this._ready = true; + + _this.verticesX = verticesX || 10; + _this.verticesY = verticesY || 10; + + _this.drawMode = _Mesh3.default.DRAW_MODES.TRIANGLES; + _this.refresh(); + return _this; + } + + /** + * Refreshes plane coordinates + * + */ + + + Plane.prototype._refresh = function _refresh() { + var texture = this._texture; + var total = this.verticesX * this.verticesY; + var verts = []; + var colors = []; + var uvs = []; + var indices = []; + + var segmentsX = this.verticesX - 1; + var segmentsY = this.verticesY - 1; + + var sizeX = texture.width / segmentsX; + var sizeY = texture.height / segmentsY; + + for (var i = 0; i < total; i++) { + var x = i % this.verticesX; + var y = i / this.verticesX | 0; + + verts.push(x * sizeX, y * sizeY); + + uvs.push(x / segmentsX, y / segmentsY); + } + + // cons + + var totalSub = segmentsX * segmentsY; + + for (var _i = 0; _i < totalSub; _i++) { + var xpos = _i % segmentsX; + var ypos = _i / segmentsX | 0; + + var value = ypos * this.verticesX + xpos; + var value2 = ypos * this.verticesX + xpos + 1; + var value3 = (ypos + 1) * this.verticesX + xpos; + var value4 = (ypos + 1) * this.verticesX + xpos + 1; + + indices.push(value, value2, value3); + indices.push(value2, value4, value3); + } + + // console.log(indices) + this.vertices = new Float32Array(verts); + this.uvs = new Float32Array(uvs); + this.colors = new Float32Array(colors); + this.indices = new Uint16Array(indices); + + this.dirty++; + this.indexDirty++; + + this.multiplyUvs(); + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Plane.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh3.default.prototype._onTextureUpdate.call(this); + + // wait for the Plane ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + return Plane; +}(_Mesh3.default); + +exports.default = Plane; + +},{"./Mesh":166}],169:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The rope allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Rope = function (_Mesh) { + _inherits(Rope, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the rope. + * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. + */ + function Rope(texture, points) { + _classCallCheck(this, Rope); + + /** + * An array of points that determine the rope + * + * @member {PIXI.Point[]} + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this.points = points; + + /** + * An array of vertices used to construct this rope. + * + * @member {Float32Array} + */ + _this.vertices = new Float32Array(points.length * 4); + + /** + * The WebGL Uvs of the rope. + * + * @member {Float32Array} + */ + _this.uvs = new Float32Array(points.length * 4); + + /** + * An array containing the color components + * + * @member {Float32Array} + */ + _this.colors = new Float32Array(points.length * 2); + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + _this.indices = new Uint16Array(points.length * 2); + + /** + * refreshes vertices on every updateTransform + * @member {boolean} + * @default true + */ + _this.autoUpdate = true; + + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Rope.prototype._refresh = function _refresh() { + var points = this.points; + + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1 || !this._texture._uvs) { + return; + } + + // if the number of points has changed we will need to recreate the arraybuffers + if (this.vertices.length / 4 !== points.length) { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + + for (var i = 1; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + var amount = i / (total - 1); + + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + + // ensure that the changes are uploaded + this.dirty++; + this.indexDirty++; + + this.multiplyUvs(); + this.refreshVertices(); + }; + + /** + * refreshes vertices of Rope mesh + */ + + + Rope.prototype.refreshVertices = function refreshVertices() { + var points = this.points; + + if (points.length < 1) { + return; + } + + var lastPoint = points[0]; + var nextPoint = void 0; + var perpX = 0; + var perpY = 0; + + // this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } else { + nextPoint = point; + } + + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + + var ratio = (1 - i / (total - 1)) * 10; + + if (ratio > 1) { + ratio = 1; + } + + var perpLength = Math.sqrt(perpX * perpX + perpY * perpY); + var num = this._texture.height / 2; // (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; + + perpX /= perpLength; + perpY /= perpLength; + + perpX *= num; + perpY *= num; + + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + + lastPoint = point; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + Rope.prototype.updateTransform = function updateTransform() { + if (this.autoUpdate) { + this.refreshVertices(); + } + this.containerUpdateTransform(); + }; + + return Rope; +}(_Mesh3.default); + +exports.default = Rope; + +},{"./Mesh":166}],170:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Renderer dedicated to meshes. + * + * @class + * @private + * @memberof PIXI + */ +var MeshSpriteRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The renderer this downport works for + */ + function MeshSpriteRenderer(renderer) { + _classCallCheck(this, MeshSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the Mesh + * + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var context = renderer.context; + + var transform = mesh.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + renderer.setBlendMode(mesh.blendMode); + + if (mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH) { + this._renderTriangleMesh(mesh); + } else { + this._renderTriangles(mesh); + } + }; + + /** + * Draws the object in Triangle Mesh mode + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype._renderTriangleMesh = function _renderTriangleMesh(mesh) { + // draw triangles!! + var length = mesh.vertices.length / 2; + + for (var i = 0; i < length - 2; i++) { + // draw some triangles! + var index = i * 2; + + this._renderDrawTriangle(mesh, index, index + 2, index + 4); + } + }; + + /** + * Draws the object in triangle mode using canvas + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + */ + + + MeshSpriteRenderer.prototype._renderTriangles = function _renderTriangles(mesh) { + // draw triangles!! + var indices = mesh.indices; + var length = indices.length; + + for (var i = 0; i < length; i += 3) { + // draw some triangles! + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderDrawTriangle(mesh, index0, index1, index2); + } + }; + + /** + * Draws one of the triangles that from the Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + * @param {number} index0 - the index of the first vertex + * @param {number} index1 - the index of the second vertex + * @param {number} index2 - the index of the third vertex + */ + + + MeshSpriteRenderer.prototype._renderDrawTriangle = function _renderDrawTriangle(mesh, index0, index1, index2) { + var context = this.renderer.context; + var uvs = mesh.uvs; + var vertices = mesh.vertices; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var base = texture.baseTexture; + var textureSource = base.source; + var textureWidth = base.width; + var textureHeight = base.height; + + var u0 = void 0; + var u1 = void 0; + var u2 = void 0; + var v0 = void 0; + var v1 = void 0; + var v2 = void 0; + + if (mesh.uploadUvTransform) { + var ut = mesh._uvTransform.mapCoord; + + u0 = (uvs[index0] * ut.a + uvs[index0 + 1] * ut.c + ut.tx) * base.width; + u1 = (uvs[index1] * ut.a + uvs[index1 + 1] * ut.c + ut.tx) * base.width; + u2 = (uvs[index2] * ut.a + uvs[index2 + 1] * ut.c + ut.tx) * base.width; + v0 = (uvs[index0] * ut.b + uvs[index0 + 1] * ut.d + ut.ty) * base.height; + v1 = (uvs[index1] * ut.b + uvs[index1 + 1] * ut.d + ut.ty) * base.height; + v2 = (uvs[index2] * ut.b + uvs[index2 + 1] * ut.d + ut.ty) * base.height; + } else { + u0 = uvs[index0] * base.width; + u1 = uvs[index1] * base.width; + u2 = uvs[index2] * base.width; + v0 = uvs[index0 + 1] * base.height; + v1 = uvs[index1 + 1] * base.height; + v2 = uvs[index2 + 1] * base.height; + } + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + if (mesh.canvasPadding > 0) { + var paddingX = mesh.canvasPadding / mesh.worldTransform.a; + var paddingY = mesh.canvasPadding / mesh.worldTransform.d; + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt(normX * normX + normY * normY); + + x0 = centerX + normX / dist * (dist + paddingX); + y0 = centerY + normY / dist * (dist + paddingY); + + // + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x1 = centerX + normX / dist * (dist + paddingX); + y1 = centerY + normY / dist * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x2 = centerX + normX / dist * (dist + paddingX); + y2 = centerY + normY / dist * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2; + var deltaA = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2; + var deltaB = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2; + var deltaC = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2; + var deltaD = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2; + var deltaE = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2; + var deltaF = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2; + + context.transform(deltaA / delta, deltaD / delta, deltaB / delta, deltaE / delta, deltaC / delta, deltaF / delta); + + context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + + context.restore(); + this.renderer.invalidateBlendMode(); + }; + + /** + * Renders a flat Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - The Mesh to render + */ + + + MeshSpriteRenderer.prototype.renderMeshFlat = function renderMeshFlat(mesh) { + var context = this.renderer.context; + var vertices = mesh.vertices; + var length = vertices.length / 2; + + // this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; ++i) { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var y0 = vertices[index + 1]; + + var x1 = vertices[index + 2]; + var y1 = vertices[index + 3]; + + var x2 = vertices[index + 4]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + }; + + /** + * destroy the the renderer. + * + */ + + + MeshSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return MeshSpriteRenderer; +}(); + +exports.default = MeshSpriteRenderer; + + +core.CanvasRenderer.registerPlugin('mesh', MeshSpriteRenderer); + +},{"../../core":65,"../Mesh":166}],171:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh = require('./Mesh'); + +Object.defineProperty(exports, 'Mesh', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Mesh).default; + } +}); + +var _MeshRenderer = require('./webgl/MeshRenderer'); + +Object.defineProperty(exports, 'MeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_MeshRenderer).default; + } +}); + +var _CanvasMeshRenderer = require('./canvas/CanvasMeshRenderer'); + +Object.defineProperty(exports, 'CanvasMeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasMeshRenderer).default; + } +}); + +var _Plane = require('./Plane'); + +Object.defineProperty(exports, 'Plane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Plane).default; + } +}); + +var _NineSlicePlane = require('./NineSlicePlane'); + +Object.defineProperty(exports, 'NineSlicePlane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NineSlicePlane).default; + } +}); + +var _Rope = require('./Rope'); + +Object.defineProperty(exports, 'Rope', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rope).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./Mesh":166,"./NineSlicePlane":167,"./Plane":168,"./Rope":169,"./canvas/CanvasMeshRenderer":170,"./webgl/MeshRenderer":172}],172:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var matrixIdentity = core.Matrix.IDENTITY; + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var MeshRenderer = function (_core$ObjectRenderer) { + _inherits(MeshRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function MeshRenderer(renderer) { + _classCallCheck(this, MeshRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + MeshRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n'); + }; + + /** + * renders mesh + * + * @param {PIXI.mesh.Mesh} mesh mesh instance + */ + + + MeshRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var gl = renderer.gl; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var glData = mesh._glDatas[renderer.CONTEXT_UID]; + + if (!glData) { + renderer.bindVao(null); + + glData = { + shader: this.shader, + vertexBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.vertices, gl.STREAM_DRAW), + uvBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.uvs, gl.STREAM_DRAW), + indexBuffer: _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, mesh.indices, gl.STATIC_DRAW), + // build the vao object that will render.. + vao: null, + dirty: mesh.dirty, + indexDirty: mesh.indexDirty + }; + + // build the vao object that will render.. + glData.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(glData.indexBuffer).addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0).addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); + + mesh._glDatas[renderer.CONTEXT_UID] = glData; + } + + renderer.bindVao(glData.vao); + + if (mesh.dirty !== glData.dirty) { + glData.dirty = mesh.dirty; + glData.uvBuffer.upload(mesh.uvs); + } + + if (mesh.indexDirty !== glData.indexDirty) { + glData.indexDirty = mesh.indexDirty; + glData.indexBuffer.upload(mesh.indices); + } + + glData.vertexBuffer.upload(mesh.vertices); + + renderer.bindShader(glData.shader); + + glData.shader.uniforms.uSampler = renderer.bindTexture(texture); + + renderer.state.setBlendMode(core.utils.correctBlendMode(mesh.blendMode, texture.baseTexture.premultipliedAlpha)); + + if (glData.shader.uniforms.uTransform) { + if (mesh.uploadUvTransform) { + glData.shader.uniforms.uTransform = mesh._uvTransform.mapCoord.toArray(true); + } else { + glData.shader.uniforms.uTransform = matrixIdentity.toArray(true); + } + } + glData.shader.uniforms.translationMatrix = mesh.worldTransform.toArray(true); + + glData.shader.uniforms.uColor = core.utils.premultiplyRgba(mesh.tintRgb, mesh.worldAlpha, glData.shader.uniforms.uColor, texture.baseTexture.premultipliedAlpha); + + var drawMode = mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + glData.vao.draw(drawMode, mesh.indices.length, 0); + }; + + return MeshRenderer; +}(core.ObjectRenderer); + +exports.default = MeshRenderer; + + +core.WebGLRenderer.registerPlugin('mesh', MeshRenderer); + +},{"../../core":65,"../Mesh":166,"path":23,"pixi-gl-core":12}],173:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _utils = require('../core/utils'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that most advanced + * functionality will not work. ParticleContainer implements the basic object transform (position, scale, rotation) + * and some advanced functionality like tint (as of v4.5.6). + * Other more advanced functionality like masking, children, filters, etc will not work on sprites in this batch. + * + * It's extremely easy to use : + * + * ```js + * let container = new ParticleContainer(); + * + * for (let i = 0; i < 100; ++i) + * { + * let sprite = new PIXI.Sprite.fromImage("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be rendered at the speed of light. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.particles + */ +var ParticleContainer = function (_core$Container) { + _inherits(ParticleContainer, _core$Container); + + /** + * @param {number} [maxSize=1500] - The maximum number of particles that can be rendered by the container. + * Affects size of allocated buffers. + * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.scale=false] - When true, scale be uploaded and applied. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.tint=false] - When true, alpha and tint be uploaded and applied. + * @param {number} [batchSize=16384] - Number of particles per batch. If less than maxSize, it uses maxSize instead. + * @param {boolean} [autoResize=true] If true, container allocates more batches in case + * there are more than `maxSize` particles. + */ + function ParticleContainer() { + var maxSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1500; + var properties = arguments[1]; + var batchSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 16384; + var autoResize = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + _classCallCheck(this, ParticleContainer); + + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + var maxBatchSize = 16384; + + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + + if (batchSize > maxSize) { + batchSize = maxSize; + } + + /** + * Set properties to be dynamic (true) / static (false) + * + * @member {boolean[]} + * @private + */ + _this._properties = [false, true, false, false, false]; + + /** + * @member {number} + * @private + */ + _this._maxSize = maxSize; + + /** + * @member {number} + * @private + */ + _this._batchSize = batchSize; + + /** + * @member {object} + * @private + */ + _this._glBuffers = {}; + + /** + * @member {number} + * @private + */ + _this._bufferToUpdate = 0; + + /** + * @member {boolean} + * + */ + _this.interactiveChildren = false; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` + * to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * If true, container allocates more batches in case there are more than `maxSize` particles. + * @member {boolean} + * @default false + */ + _this.autoResize = autoResize; + + /** + * Used for canvas renderering. If true then the elements will be positioned at the + * nearest pixel. This provides a nice speed boost. + * + * @member {boolean} + * @default true; + */ + _this.roundPixels = true; + + /** + * The texture used to render the children. + * + * @readonly + * @member {BaseTexture} + */ + _this.baseTexture = null; + + _this.setProperties(properties); + + /** + * The tint applied to the container. + * This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = 0; + _this.tintRgb = new Float32Array(4); + _this.tint = 0xFFFFFF; + return _this; + } + + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * + * @param {object} properties - The properties to be uploaded + */ + + + ParticleContainer.prototype.setProperties = function setProperties(properties) { + if (properties) { + this._properties[0] = 'scale' in properties ? !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'alpha' in properties || 'tint' in properties ? !!properties.alpha || !!properties.tint : this._properties[4]; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + ParticleContainer.prototype.updateTransform = function updateTransform() { + // TODO don't need to! + this.displayObjectUpdateTransform(); + // PIXI.Container.prototype.updateTransform.call( this ); + }; + + /** + * The tint applied to the container. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + ** IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * @member {number} + * @default 0xFFFFFF + */ + + + /** + * Renders the container using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer + */ + ParticleContainer.prototype.renderWebGL = function renderWebGL(renderer) { + var _this2 = this; + + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.hasLoaded) { + this.baseTexture.once('update', function () { + return _this2.onChildrenChange(0); + }); + } + } + + renderer.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + + /** + * Set the flag that static data should be updated to true + * + * @private + * @param {number} smallestChildIndex - The smallest child index + */ + + + ParticleContainer.prototype.onChildrenChange = function onChildrenChange(smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + + if (bufferIndex < this._bufferToUpdate) { + this._bufferToUpdate = bufferIndex; + } + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + + + ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var isRotated = true; + + var positionX = 0; + var positionY = 0; + + var finalWidth = 0; + var finalHeight = 0; + + renderer.setBlendMode(this.blendMode); + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i]; + + if (!child.visible) { + continue; + } + + var frame = child._texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) { + // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call + if (isRotated) { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx * renderer.resolution, transform.ty * renderer.resolution); + + isRotated = false; + } + + positionX = child.anchor.x * (-frame.width * child.scale.x) + child.position.x + 0.5; + positionY = child.anchor.y * (-frame.height * child.scale.y) + child.position.y + 0.5; + + finalWidth = frame.width * child.scale.x; + finalHeight = frame.height * child.scale.y; + } else { + if (!isRotated) { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + + if (renderer.roundPixels) { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution | 0, childTransform.ty * renderer.resolution | 0); + } else { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution, childTransform.ty * renderer.resolution); + } + + positionX = child.anchor.x * -frame.width + 0.5; + positionY = child.anchor.y * -frame.height + 0.5; + + finalWidth = frame.width; + finalHeight = frame.height; + } + + var resolution = child._texture.baseTexture.resolution; + + context.drawImage(child._texture.baseTexture.source, frame.x * resolution, frame.y * resolution, frame.width * resolution, frame.height * resolution, positionX * renderer.resolution, positionY * renderer.resolution, finalWidth * renderer.resolution, finalHeight * renderer.resolution); + } + }; + + /** + * Destroys the container + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + ParticleContainer.prototype.destroy = function destroy(options) { + _core$Container.prototype.destroy.call(this, options); + + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + } + + this._properties = null; + this._buffers = null; + }; + + _createClass(ParticleContainer, [{ + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + (0, _utils.hex2rgb)(value, this.tintRgb); + } + }]); + + return ParticleContainer; +}(core.Container); + +exports.default = ParticleContainer; + +},{"../core":65,"../core/utils":125}],174:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ParticleContainer = require('./ParticleContainer'); + +Object.defineProperty(exports, 'ParticleContainer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleContainer).default; + } +}); + +var _ParticleRenderer = require('./webgl/ParticleRenderer'); + +Object.defineProperty(exports, 'ParticleRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleRenderer).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./ParticleContainer":173,"./webgl/ParticleRenderer":176}],175:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + +/** + * The particle buffer manages the static and dynamic buffers for a particle container. + * + * @class + * @private + * @memberof PIXI + */ +var ParticleBuffer = function () { + /** + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(gl, properties, dynamicPropertyFlags, size) { + _classCallCheck(this, ParticleBuffer); + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The number of particles the buffer can hold + * + * @member {number} + */ + this.size = size; + + /** + * A list of the properties that are dynamic. + * + * @member {object[]} + */ + this.dynamicProperties = []; + + /** + * A list of the properties that are static. + * + * @member {object[]} + */ + this.staticProperties = []; + + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attribute: property.attribute, + size: property.size, + uploadFunction: property.uploadFunction, + unsignedByte: property.unsignedByte, + offset: property.offset + }; + + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } else { + this.staticProperties.push(property); + } + } + + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + + this.initBuffers(); + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + ParticleBuffer.prototype.initBuffers = function initBuffers() { + var gl = this.gl; + var dynamicOffset = 0; + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(this.size); + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + this.dynamicStride = 0; + + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + + var dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4); + + this.dynamicData = new Float32Array(dynBuffer); + this.dynamicDataUint32 = new Uint32Array(dynBuffer); + this.dynamicBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, dynBuffer, gl.STREAM_DRAW); + + // static // + var staticOffset = 0; + + this.staticStride = 0; + + for (var _i = 0; _i < this.staticProperties.length; ++_i) { + var _property = this.staticProperties[_i]; + + _property.offset = staticOffset; + staticOffset += _property.size; + this.staticStride += _property.size; + } + + var statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4); + + this.staticData = new Float32Array(statBuffer); + this.staticDataUint32 = new Uint32Array(statBuffer); + this.staticBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, statBuffer, gl.STATIC_DRAW); + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(this.indexBuffer); + + for (var _i2 = 0; _i2 < this.dynamicProperties.length; ++_i2) { + var _property2 = this.dynamicProperties[_i2]; + + if (_property2.unsignedByte) { + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.UNSIGNED_BYTE, true, this.dynamicStride * 4, _property2.offset * 4); + } else { + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.FLOAT, false, this.dynamicStride * 4, _property2.offset * 4); + } + } + + for (var _i3 = 0; _i3 < this.staticProperties.length; ++_i3) { + var _property3 = this.staticProperties[_i3]; + + if (_property3.unsignedByte) { + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.UNSIGNED_BYTE, true, this.staticStride * 4, _property3.offset * 4); + } else { + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.FLOAT, false, this.staticStride * 4, _property3.offset * 4); + } + } + }; + + /** + * Uploads the dynamic properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadDynamic = function uploadDynamic(children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + + property.uploadFunction(children, startIndex, amount, property.unsignedByte ? this.dynamicDataUint32 : this.dynamicData, this.dynamicStride, property.offset); + } + + this.dynamicBuffer.upload(); + }; + + /** + * Uploads the static properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadStatic = function uploadStatic(children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + + property.uploadFunction(children, startIndex, amount, property.unsignedByte ? this.staticDataUint32 : this.staticData, this.staticStride, property.offset); + } + + this.staticBuffer.upload(); + }; + + /** + * Destroys the ParticleBuffer. + * + */ + + + ParticleBuffer.prototype.destroy = function destroy() { + this.dynamicProperties = null; + this.dynamicBuffer.destroy(); + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + + this.staticProperties = null; + this.staticBuffer.destroy(); + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + }; + + return ParticleBuffer; +}(); + +exports.default = ParticleBuffer; + +},{"../../core/utils/createIndicesForQuads":123,"pixi-gl-core":12}],176:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _ParticleShader = require('./ParticleShader'); + +var _ParticleShader2 = _interopRequireDefault(_ParticleShader); + +var _ParticleBuffer = require('./ParticleBuffer'); + +var _ParticleBuffer2 = _interopRequireDefault(_ParticleBuffer); + +var _utils = require('../../core/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + +/** + * + * @class + * @private + * @memberof PIXI + */ +var ParticleRenderer = function (_core$ObjectRenderer) { + _inherits(ParticleRenderer, _core$ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + _classCallCheck(this, ParticleRenderer); + + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; + + /** + * The default shader that is used if a sprite doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + + _this.indexBuffer = null; + + _this.properties = null; + + _this.tempMatrix = new core.Matrix(); + + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * When there is a WebGL context change + * + * @private + */ + + + ParticleRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + + // setup default shader + this.shader = new _ParticleShader2.default(gl); + + this.properties = [ + // verticesData + { + attribute: this.shader.attributes.aVertexPosition, + size: 2, + uploadFunction: this.uploadVertices, + offset: 0 + }, + // positionData + { + attribute: this.shader.attributes.aPositionCoord, + size: 2, + uploadFunction: this.uploadPosition, + offset: 0 + }, + // rotationData + { + attribute: this.shader.attributes.aRotation, + size: 1, + uploadFunction: this.uploadRotation, + offset: 0 + }, + // uvsData + { + attribute: this.shader.attributes.aTextureCoord, + size: 2, + uploadFunction: this.uploadUvs, + offset: 0 + }, + // tintData + { + attribute: this.shader.attributes.aColor, + size: 1, + unsignedByte: true, + uploadFunction: this.uploadTint, + offset: 0 + }]; + }; + + /** + * Starts a new particle batch. + * + */ + + + ParticleRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + }; + + /** + * Renders the particle container object. + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + */ + + + ParticleRenderer.prototype.render = function render(container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var renderer = this.renderer; + var totalChildren = children.length; + + if (totalChildren === 0) { + return; + } else if (totalChildren > maxSize) { + totalChildren = maxSize; + } + + var buffers = container._glBuffers[renderer.CONTEXT_UID]; + + if (!buffers) { + buffers = container._glBuffers[renderer.CONTEXT_UID] = this.generateBuffers(container); + } + + var baseTexture = children[0]._texture.baseTexture; + + // if the uvs have not updated then no point rendering just yet! + this.renderer.setBlendMode(core.utils.correctBlendMode(container.blendMode, baseTexture.premultipliedAlpha)); + + var gl = renderer.gl; + + var m = container.worldTransform.copy(this.tempMatrix); + + m.prepend(renderer._activeRenderTarget.projectionMatrix); + + this.shader.uniforms.projectionMatrix = m.toArray(true); + + this.shader.uniforms.uColor = core.utils.premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, baseTexture.premultipliedAlpha); + + // make sure the texture is bound.. + this.shader.uniforms.uSampler = renderer.bindTexture(baseTexture); + + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = totalChildren - i; + + if (amount > batchSize) { + amount = batchSize; + } + + if (j >= buffers.length) { + if (!container.autoResize) { + break; + } + buffers.push(this._generateOneMoreBuffer(container)); + } + + var buffer = buffers[j]; + + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + + // we only upload the static content when we have to! + if (container._bufferToUpdate === j) { + buffer.uploadStatic(children, i, amount); + container._bufferToUpdate = j + 1; + } + + // bind the buffer + renderer.bindVao(buffer.vao); + buffer.vao.draw(gl.TRIANGLES, amount * 6); + } + }; + + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer[]} The buffers + */ + + + ParticleRenderer.prototype.generateBuffers = function generateBuffers(container) { + var gl = this.renderer.gl; + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + for (var i = 0; i < size; i += batchSize) { + buffers.push(new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize)); + } + + return buffers; + }; + + /** + * Creates one more particle buffer, because container has autoResize feature + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer} generated buffer + * @private + */ + + + ParticleRenderer.prototype._generateOneMoreBuffer = function _generateOneMoreBuffer(container) { + var gl = this.renderer.gl; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + return new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize); + }; + + /** + * Uploads the verticies. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their vertices uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadVertices = function uploadVertices(children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - sprite.anchor.x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - sprite.anchor.y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - sprite.anchor.x); + w1 = orig.width * -sprite.anchor.x; + + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + + array[offset + stride * 2] = w0 * sx; + array[offset + stride * 2 + 1] = h0 * sy; + + array[offset + stride * 3] = w1 * sx; + array[offset + stride * 3 + 1] = h0 * sy; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their positions uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadPosition = function uploadPosition(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + + array[offset + stride * 2] = spritePosition.x; + array[offset + stride * 2 + 1] = spritePosition.y; + + array[offset + stride * 3] = spritePosition.x; + array[offset + stride * 3 + 1] = spritePosition.y; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadRotation = function uploadRotation(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + stride * 2] = spriteRotation; + array[offset + stride * 3] = spriteRotation; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadUvs = function uploadUvs(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + + array[offset + stride * 2] = textureUvs.x2; + array[offset + stride * 2 + 1] = textureUvs.y2; + + array[offset + stride * 3] = textureUvs.x3; + array[offset + stride * 3 + 1] = textureUvs.y3; + + offset += stride * 4; + } else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + + array[offset + stride * 2] = 0; + array[offset + stride * 2 + 1] = 0; + + array[offset + stride * 3] = 0; + array[offset + stride * 3 + 1] = 0; + + offset += stride * 4; + } + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadTint = function uploadTint(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var premultiplied = sprite._texture.baseTexture.premultipliedAlpha; + var alpha = sprite.alpha; + // we dont call extra function if alpha is 1.0, that's faster + var argb = alpha < 1.0 && premultiplied ? (0, _utils.premultiplyTint)(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); + + array[offset] = argb; + array[offset + stride] = argb; + array[offset + stride * 2] = argb; + array[offset + stride * 3] = argb; + + offset += stride * 4; + } + }; + + /** + * Destroys the ParticleRenderer. + * + */ + + + ParticleRenderer.prototype.destroy = function destroy() { + if (this.renderer.gl) { + this.renderer.gl.deleteBuffer(this.indexBuffer); + } + + _core$ObjectRenderer.prototype.destroy.call(this); + + this.shader.destroy(); + + this.indices = null; + this.tempMatrix = null; + }; + + return ParticleRenderer; +}(core.ObjectRenderer); + +exports.default = ParticleRenderer; + + +core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + +},{"../../core":65,"../../core/utils":125,"./ParticleBuffer":175,"./ParticleShader":177}],177:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../core/Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI + */ +var ParticleShader = function (_Shader) { + _inherits(ParticleShader, _Shader); + + /** + * @param {PIXI.Shader} gl - The webgl shader manager this shader works for. + */ + function ParticleShader(gl) { + _classCallCheck(this, ParticleShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'attribute vec4 aColor;', 'attribute vec2 aPositionCoord;', 'attribute vec2 aScale;', 'attribute float aRotation;', 'uniform mat3 projectionMatrix;', 'uniform vec4 uColor;', 'varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'void main(void){', ' float x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);', ' float y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);', ' vec2 v = vec2(x, y);', ' v = v + aPositionCoord;', ' gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = aColor * uColor;', '}'].join('\n'), + // hello + ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'uniform sampler2D uSampler;', 'void main(void){', ' vec4 color = texture2D(uSampler, vTextureCoord) * vColor;', ' gl_FragColor = color;', '}'].join('\n'))); + } + + return ParticleShader; +}(_Shader3.default); + +exports.default = ParticleShader; + +},{"../../core/Shader":44}],178:[function(require,module,exports){ +"use strict"; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + +if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + + if (x === 0 || isNaN(x)) { + return x; + } + + return x > 0 ? 1 : -1; + }; +} + +},{}],179:[function(require,module,exports){ +'use strict'; + +var _objectAssign = require('object-assign'); + +var _objectAssign2 = _interopRequireDefault(_objectAssign); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +if (!Object.assign) { + Object.assign = _objectAssign2.default; +} // References: +// https://github.com/sindresorhus/object-assign +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + +},{"object-assign":5}],180:[function(require,module,exports){ +'use strict'; + +require('./Object.assign'); + +require('./requestAnimationFrame'); + +require('./Math.sign'); + +if (!window.ArrayBuffer) { + window.ArrayBuffer = Array; +} + +if (!window.Float32Array) { + window.Float32Array = Array; +} + +if (!window.Uint32Array) { + window.Uint32Array = Array; +} + +if (!window.Uint16Array) { + window.Uint16Array = Array; +} + +},{"./Math.sign":178,"./Object.assign":179,"./requestAnimationFrame":181}],181:[function(require,module,exports){ +(function (global){ +'use strict'; + +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + +// Expected to be used with Browserfiy +// Browserify automatically detects the use of `global` and passes the +// correct reference of `global`, `self`, and finally `window` + +var ONE_FRAME_TIME = 16; + +// Date.now +if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; +} + +// performance.now +if (!(global.performance && global.performance.now)) { + var startTime = Date.now(); + + if (!global.performance) { + global.performance = {}; + } + + global.performance.now = function () { + return Date.now() - startTime; + }; +} + +// requestAnimationFrame +var lastTime = Date.now(); +var vendors = ['ms', 'moz', 'webkit', 'o']; + +for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { + var p = vendors[x]; + + global.requestAnimationFrame = global[p + 'RequestAnimationFrame']; + global.cancelAnimationFrame = global[p + 'CancelAnimationFrame'] || global[p + 'CancelRequestAnimationFrame']; +} + +if (!global.requestAnimationFrame) { + global.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + 'is not a function'); + } + + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + + if (delay < 0) { + delay = 0; + } + + lastTime = currentTime; + + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} + +if (!global.cancelAnimationFrame) { + global.cancelAnimationFrame = function (id) { + return clearTimeout(id); + }; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],182:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CountLimiter = require('./limiters/CountLimiter'); + +var _CountLimiter2 = _interopRequireDefault(_CountLimiter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SharedTicker = core.ticker.shared; + +/** + * Default number of uploads per frame using prepare plugin. + * + * @static + * @memberof PIXI.settings + * @name UPLOADS_PER_FRAME + * @type {number} + * @default 4 + */ +core.settings.UPLOADS_PER_FRAME = 4; + +/** + * The prepare manager provides functionality to upload content to the GPU. BasePrepare handles + * basic queuing functionality and is extended by {@link PIXI.prepare.WebGLPrepare} and {@link PIXI.prepare.CanvasPrepare} + * to provide preparation capabilities specific to their respective renderers. + * + * @example + * // Create a sprite + * const sprite = new PIXI.Sprite.fromImage('something.png'); + * + * // Load object into GPU + * app.renderer.plugins.prepare.upload(sprite, () => { + * + * //Texture(s) has been uploaded to GPU + * app.stage.addChild(sprite); + * + * }) + * + * @abstract + * @class + * @memberof PIXI.prepare + */ + +var BasePrepare = function () { + /** + * @param {PIXI.SystemRenderer} renderer - A reference to the current renderer + */ + function BasePrepare(renderer) { + var _this = this; + + _classCallCheck(this, BasePrepare); + + /** + * The limiter to be used to control how quickly items are prepared. + * @type {PIXI.prepare.CountLimiter|PIXI.prepare.TimeLimiter} + */ + this.limiter = new _CountLimiter2.default(core.settings.UPLOADS_PER_FRAME); + + /** + * Reference to the renderer. + * @type {PIXI.SystemRenderer} + * @protected + */ + this.renderer = renderer; + + /** + * The only real difference between CanvasPrepare and WebGLPrepare is what they pass + * to upload hooks. That different parameter is stored here. + * @type {PIXI.prepare.CanvasPrepare|PIXI.WebGLRenderer} + * @protected + */ + this.uploadHookHelper = null; + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + /** + * 'bound' call for prepareItems(). + * @type {Function} + * @private + */ + this.delayedTick = function () { + // unlikely, but in case we were destroyed between tick() and delayedTick() + if (!_this.queue) { + return; + } + _this.prepareItems(); + }; + + // hooks to find the correct texture + this.registerFindHook(findText); + this.registerFindHook(findTextStyle); + this.registerFindHook(findMultipleBaseTextures); + this.registerFindHook(findBaseTexture); + this.registerFindHook(findTexture); + + // upload hooks + this.registerUploadHook(drawText); + this.registerUploadHook(calculateTextStyle); + } + + /** + * Upload all the textures and graphics to the GPU. + * + * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item - + * Either the container or display object to search for items to upload, the items to upload themselves, + * or the callback function, if items have been added using `prepare.add`. + * @param {Function} [done] - Optional callback when all queued uploads have completed + */ + + + BasePrepare.prototype.upload = function upload(item, done) { + if (typeof item === 'function') { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) { + if (done) { + this.completes.push(done); + } + + if (!this.ticking) { + this.ticking = true; + SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); + } + } else if (done) { + done(); + } + }; + + /** + * Handle tick update + * + * @private + */ + + + BasePrepare.prototype.tick = function tick() { + setTimeout(this.delayedTick, 0); + }; + + /** + * Actually prepare items. This is handled outside of the tick because it will take a while + * and we do NOT want to block the current animation frame from rendering. + * + * @private + */ + + + BasePrepare.prototype.prepareItems = function prepareItems() { + this.limiter.beginFrame(); + // Upload the graphics + while (this.queue.length && this.limiter.allowedToUpload()) { + var item = this.queue[0]; + var uploaded = false; + + if (item && !item._destroyed) { + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.uploadHookHelper, item)) { + this.queue.shift(); + uploaded = true; + break; + } + } + } + + if (!uploaded) { + this.queue.shift(); + } + } + + // We're finished + if (!this.queue.length) { + this.ticking = false; + + var completes = this.completes.slice(0); + + this.completes.length = 0; + + for (var _i = 0, _len = completes.length; _i < _len; _i++) { + completes[_i](); + } + } else { + // if we are not finished, on the next rAF do this again + SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); + } + }; + + /** + * Adds hooks for finding items. + * + * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.registerFindHook = function registerFindHook(addHook) { + if (addHook) { + this.addHooks.push(addHook); + } + + return this; + }; + + /** + * Adds hooks for uploading items. + * + * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.registerUploadHook = function registerUploadHook(uploadHook) { + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + + return this; + }; + + /** + * Manually add an item to the uploading queue. + * + * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to + * add to the queue + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.add = function add(item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) { + for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { + this.add(item.children[_i2]); + } + } + + return this; + }; + + /** + * Destroys the plugin, don't use after this. + * + */ + + + BasePrepare.prototype.destroy = function destroy() { + if (this.ticking) { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.limiter = null; + this.uploadHookHelper = null; + }; + + return BasePrepare; +}(); + +/** + * Built-in hook to find multiple textures from objects like AnimatedSprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ + + +exports.default = BasePrepare; +function findMultipleBaseTextures(item, queue) { + var result = false; + + // Objects with mutliple textures + if (item && item._textures && item._textures.length) { + for (var i = 0; i < item._textures.length; i++) { + if (item._textures[i] instanceof core.Texture) { + var baseTexture = item._textures[i].baseTexture; + + if (queue.indexOf(baseTexture) === -1) { + queue.push(baseTexture); + result = true; + } + } + } + } + + return result; +} + +/** + * Built-in hook to find BaseTextures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTexture(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findTexture(item, queue) { + if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to draw PIXI.Text to its texture. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function drawText(helper, item) { + if (item instanceof core.Text) { + // updating text will return early if it is not dirty + item.updateText(true); + + return true; + } + + return false; +} + +/** + * Built-in hook to calculate a text style for a PIXI.Text object. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function calculateTextStyle(helper, item) { + if (item instanceof core.TextStyle) { + var font = item.toFontString(); + + core.TextMetrics.measureFont(font); + + return true; + } + + return false; +} + +/** + * Built-in hook to find Text objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Text object was found. + */ +function findText(item, queue) { + if (item instanceof core.Text) { + // push the text style to prepare it - this can be really expensive + if (queue.indexOf(item.style) === -1) { + queue.push(item.style); + } + // also push the text object so that we can render it (to canvas/texture) if needed + if (queue.indexOf(item) === -1) { + queue.push(item); + } + // also push the Text's texture for upload to GPU + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find TextStyle objects. + * + * @private + * @param {PIXI.TextStyle} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.TextStyle object was found. + */ +function findTextStyle(item, queue) { + if (item instanceof core.TextStyle) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +},{"../core":65,"./limiters/CountLimiter":185}],183:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CANVAS_START_SIZE = 16; + +/** + * The prepare manager provides functionality to upload content to the GPU + * This cannot be done directly for Canvas like in WebGL, but the effect can be achieved by drawing + * textures to an offline canvas. + * This draw call will force the texture to be moved onto the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ + +var CanvasPrepare = function (_BasePrepare) { + _inherits(CanvasPrepare, _BasePrepare); + + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasPrepare(renderer) { + _classCallCheck(this, CanvasPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this; + + /** + * An offline canvas to render textures to + * @type {HTMLCanvasElement} + * @private + */ + _this.canvas = document.createElement('canvas'); + _this.canvas.width = CANVAS_START_SIZE; + _this.canvas.height = CANVAS_START_SIZE; + + /** + * The context to the canvas + * @type {CanvasRenderingContext2D} + * @private + */ + _this.ctx = _this.canvas.getContext('2d'); + + // Add textures to upload + _this.registerUploadHook(uploadBaseTextures); + return _this; + } + + /** + * Destroys the plugin, don't use after this. + * + */ + + + CanvasPrepare.prototype.destroy = function destroy() { + _BasePrepare.prototype.destroy.call(this); + this.ctx = null; + this.canvas = null; + }; + + return CanvasPrepare; +}(_BasePrepare3.default); + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {*} prepare - Instance of CanvasPrepare + * @param {*} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = CanvasPrepare; +function uploadBaseTextures(prepare, item) { + if (item instanceof core.BaseTexture) { + var image = item.source; + + // Sometimes images (like atlas images) report a size of zero, causing errors on windows phone. + // So if the width or height is equal to zero then use the canvas size + // Otherwise use whatever is smaller, the image dimensions or the canvas dimensions. + var imageWidth = image.width === 0 ? prepare.canvas.width : Math.min(prepare.canvas.width, image.width); + var imageHeight = image.height === 0 ? prepare.canvas.height : Math.min(prepare.canvas.height, image.height); + + // Only a small subsections is required to be drawn to have the whole texture uploaded to the GPU + // A smaller draw can be faster. + prepare.ctx.drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, prepare.canvas.width, prepare.canvas.height); + + return true; + } + + return false; +} + +core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); + +},{"../../core":65,"../BasePrepare":182}],184:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLPrepare = require('./webgl/WebGLPrepare'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLPrepare).default; + } +}); + +var _CanvasPrepare = require('./canvas/CanvasPrepare'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasPrepare).default; + } +}); + +var _BasePrepare = require('./BasePrepare'); + +Object.defineProperty(exports, 'BasePrepare', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BasePrepare).default; + } +}); + +var _CountLimiter = require('./limiters/CountLimiter'); + +Object.defineProperty(exports, 'CountLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CountLimiter).default; + } +}); + +var _TimeLimiter = require('./limiters/TimeLimiter'); + +Object.defineProperty(exports, 'TimeLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TimeLimiter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./BasePrepare":182,"./canvas/CanvasPrepare":183,"./limiters/CountLimiter":185,"./limiters/TimeLimiter":186,"./webgl/WebGLPrepare":187}],185:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * CountLimiter limits the number of items handled by a {@link PIXI.prepare.BasePrepare} to a specified + * number of items per frame. + * + * @class + * @memberof PIXI + */ +var CountLimiter = function () { + /** + * @param {number} maxItemsPerFrame - The maximum number of items that can be prepared each frame. + */ + function CountLimiter(maxItemsPerFrame) { + _classCallCheck(this, CountLimiter); + + /** + * The maximum number of items that can be prepared each frame. + * @private + */ + this.maxItemsPerFrame = maxItemsPerFrame; + /** + * The number of items that can be prepared in the current frame. + * @type {number} + * @private + */ + this.itemsLeft = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + CountLimiter.prototype.beginFrame = function beginFrame() { + this.itemsLeft = this.maxItemsPerFrame; + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + CountLimiter.prototype.allowedToUpload = function allowedToUpload() { + return this.itemsLeft-- > 0; + }; + + return CountLimiter; +}(); + +exports.default = CountLimiter; + +},{}],186:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of milliseconds per frame. + * + * @class + * @memberof PIXI + */ +var TimeLimiter = function () { + /** + * @param {number} maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. + */ + function TimeLimiter(maxMilliseconds) { + _classCallCheck(this, TimeLimiter); + + /** + * The maximum milliseconds that can be spent preparing items each frame. + * @private + */ + this.maxMilliseconds = maxMilliseconds; + /** + * The start time of the current frame. + * @type {number} + * @private + */ + this.frameStart = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + TimeLimiter.prototype.beginFrame = function beginFrame() { + this.frameStart = Date.now(); + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + TimeLimiter.prototype.allowedToUpload = function allowedToUpload() { + return Date.now() - this.frameStart < this.maxMilliseconds; + }; + + return TimeLimiter; +}(); + +exports.default = TimeLimiter; + +},{}],187:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The prepare manager provides functionality to upload content to the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ +var WebGLPrepare = function (_BasePrepare) { + _inherits(WebGLPrepare, _BasePrepare); + + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLPrepare(renderer) { + _classCallCheck(this, WebGLPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this.renderer; + + // Add textures and graphics to upload + _this.registerFindHook(findGraphics); + _this.registerUploadHook(uploadBaseTextures); + _this.registerUploadHook(uploadGraphics); + return _this; + } + + return WebGLPrepare; +}(_BasePrepare3.default); +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = WebGLPrepare; +function uploadBaseTextures(renderer, item) { + if (item instanceof core.BaseTexture) { + // if the texture already has a GL texture, then the texture has been prepared or rendered + // before now. If the texture changed, then the changer should be calling texture.update() which + // reuploads the texture without need for preparing it again + if (!item._glTextures[renderer.CONTEXT_UID]) { + renderer.textureManager.updateTexture(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to upload PIXI.Graphics to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadGraphics(renderer, item) { + if (item instanceof core.Graphics) { + // if the item is not dirty and already has webgl data, then it got prepared or rendered + // before now and we shouldn't waste time updating it again + if (item.dirty || item.clearDirty || !item._webGL[renderer.plugins.graphics.CONTEXT_UID]) { + renderer.plugins.graphics.updateGraphics(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find graphics. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Graphics object was found. + */ +function findGraphics(item, queue) { + if (item instanceof core.Graphics) { + queue.push(item); + + return true; + } + + return false; +} + +core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); + +},{"../../core":65,"../BasePrepare":182}],188:[function(require,module,exports){ +(function (global){ +'use strict'; + +exports.__esModule = true; +exports.loader = exports.prepare = exports.particles = exports.mesh = exports.loaders = exports.interaction = exports.filters = exports.extras = exports.extract = exports.accessibility = undefined; + +var _polyfill = require('./polyfill'); + +Object.keys(_polyfill).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _polyfill[key]; + } + }); +}); + +var _core = require('./core'); + +Object.keys(_core).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _core[key]; + } + }); +}); + +var _deprecation = require('./deprecation'); + +var _deprecation2 = _interopRequireDefault(_deprecation); + +var _accessibility = require('./accessibility'); + +var accessibility = _interopRequireWildcard(_accessibility); + +var _extract = require('./extract'); + +var extract = _interopRequireWildcard(_extract); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// export core +_core.utils.mixins.performMixins(); + +/** + * Alias for {@link PIXI.loaders.shared}. + * @name loader + * @memberof PIXI + * @type {PIXI.loader.Loader} + */ + + +// handle mixins now, after all code has been added, including deprecation + + +// export libs +// import polyfills. Done as an export to make sure polyfills are imported first +var loader = loaders.shared || null; + +exports.accessibility = accessibility; +exports.extract = extract; +exports.extras = extras; +exports.filters = filters; +exports.interaction = interaction; +exports.loaders = loaders; +exports.mesh = mesh; +exports.particles = particles; +exports.prepare = prepare; +exports.loader = loader; + +// Apply the deprecations + +if (typeof _deprecation2.default === 'function') { + (0, _deprecation2.default)(exports); +} + +// Always export PixiJS globally. +global.PIXI = exports; // eslint-disable-line + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"./accessibility":42,"./core":65,"./deprecation":131,"./extract":133,"./extras":141,"./filters":153,"./interaction":159,"./loaders":162,"./mesh":171,"./particles":174,"./polyfill":180,"./prepare":184}]},{},[188])(188) +}); + + +//# sourceMappingURL=pixi.js.map diff --git a/js/pixi/4.6.2/pixi.min.js b/js/pixi/4.6.2/pixi.min.js new file mode 100644 index 0000000..f55d876 --- /dev/null +++ b/js/pixi/4.6.2/pixi.min.js @@ -0,0 +1,22 @@ +/*! + * pixi.js - v4.6.2 + * Compiled Thu, 30 Nov 2017 15:24:52 UTC + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.PIXI=t()}}(function(){var t;return function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var h=new Error("Cannot find module '"+s+"'");throw h.code="MODULE_NOT_FOUND",h}var l=r[s]={exports:{}};e[s][0].call(l.exports,function(t){var r=e[s][1][t];return i(r||t)},l,l.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s0)-(t<0)},r.abs=function(t){var e=t>>31;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,(e|=r)|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,16843009*((t=(858993459&t)+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var i=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|i[t>>>16&255]<<8|i[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),(t=65535&(t|t>>>16))<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),(t=1023&(t|t>>>16))<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],2:[function(t,e,r){"use strict";function n(t,e,r){r=r||2;var n=e&&e.length,o=n?e[0]*r:t.length,a=i(t,0,o,r,!0),u=[];if(!a)return u;var h,l,d,f,p,v,y;if(n&&(a=c(t,e,a,r)),t.length>80*r){h=d=t[0],l=f=t[1];for(var g=r;gd&&(d=p),v>f&&(f=v);y=Math.max(d-h,f-l),y=0!==y?1/y:0}return s(a,u,r,h,l,y),u}function i(t,e,r,n,i){var o,s;if(i===A(t,e,r,n)>0)for(o=e;o=e;o-=n)s=P(o,t[o],t[o+1],s);return s&&T(s,s.next)&&(C(s),s=s.next),s}function o(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!T(n,n.next)&&0!==x(n.prev,n,n.next))n=n.next;else{if(C(n),(n=e=n.prev)===n.next)break;r=!0}}while(r||n!==e);return e}function s(t,e,r,n,i,c,d){if(t){!d&&c&&v(t,n,i,c);for(var f,p,y=t;t.prev!==t.next;)if(f=t.prev,p=t.next,c?u(t,n,i,c):a(t))e.push(f.i/r),e.push(t.i/r),e.push(p.i/r),C(t),t=p.next,y=p.next;else if((t=p)===y){d?1===d?(t=h(t,e,r),s(t,e,r,n,i,c,2)):2===d&&l(t,e,r,n,i,c):s(o(t),e,r,n,i,c,1);break}}}function a(t){var e=t.prev,r=t,n=t.next;if(x(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(_(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&x(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function u(t,e,r,n){var i=t.prev,o=t,s=t.next;if(x(i,o,s)>=0)return!1;for(var a=i.xo.x?i.x>s.x?i.x:s.x:o.x>s.x?o.x:s.x,l=i.y>o.y?i.y>s.y?i.y:s.y:o.y>s.y?o.y:s.y,c=g(a,u,e,r,n),d=g(h,l,e,r,n),f=t.nextZ;f&&f.z<=d;){if(f!==t.prev&&f!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,f.x,f.y)&&x(f.prev,f,f.next)>=0)return!1;f=f.nextZ}for(f=t.prevZ;f&&f.z>=c;){if(f!==t.prev&&f!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,f.x,f.y)&&x(f.prev,f,f.next)>=0)return!1;f=f.prevZ}return!0}function h(t,e,r){var n=t;do{var i=n.prev,o=n.next.next;!T(i,o)&&w(i,n,n.next,o)&&S(i,o)&&S(o,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(o.i/r),C(n),C(n.next),n=t=o),n=n.next}while(n!==t);return n}function l(t,e,r,n,i,a){var u=t;do{for(var h=u.next.next;h!==u.prev;){if(u.i!==h.i&&b(u,h)){var l=M(u,h);return u=o(u,u.next),l=o(l,l.next),s(u,e,r,n,i,a),void s(l,e,r,n,i,a)}h=h.next}u=u.next}while(u!==t)}function c(t,e,r,n){var s,a,u,h,l,c=[];for(s=0,a=e.length;s=n.next.y&&n.next.y!==n.y){var a=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=i&&a>s){if(s=a,a===i){if(o===n.y)return n;if(o===n.next.y)return n.next}r=n.x=n.x&&n.x>=l&&i!==n.x&&_(or.x)&&S(n,t)&&(r=n,d=u),n=n.next;return r}function v(t,e,r,n){var i=t;do{null===i.z&&(i.z=g(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,y(i)}function y(t){var e,r,n,i,o,s,a,u,h=1;do{for(r=t,t=null,o=null,s=0;r;){for(s++,n=r,a=0,e=0;e0||u>0&&n;)0!==a&&(0===u||!n||r.z<=n.z)?(i=r,r=r.nextZ,a--):(i=n,n=n.nextZ,u--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;r=n}o.nextZ=null,h*=2}while(s>1);return t}function g(t,e,r,n,i){return t=32767*(t-r)*i,e=32767*(e-n)*i,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1}function m(t){var e=t,r=t;do{e.x=0&&(t-s)*(n-a)-(r-s)*(e-a)>=0&&(r-s)*(o-a)-(i-s)*(n-a)>=0}function b(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!E(t,e)&&S(t,e)&&S(e,t)&&O(t,e)}function x(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function T(t,e){return t.x===e.x&&t.y===e.y}function w(t,e,r,n){return!!(T(t,e)&&T(r,n)||T(t,n)&&T(r,e))||x(t,e,r)>0!=x(t,e,n)>0&&x(r,n,t)>0!=x(r,n,e)>0}function E(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&w(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}function S(t,e){return x(t.prev,t,t.next)<0?x(t,e,t.next)>=0&&x(t,t.prev,e)>=0:x(t,e,t.prev)<0||x(t,t.next,e)<0}function O(t,e){var r=t,n=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{r.y>o!=r.next.y>o&&r.next.y!==r.y&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}function M(t,e){var r=new R(t.i,t.x,t.y),n=new R(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function P(t,e,r,n){var i=new R(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function C(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function R(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(t,e,r,n){for(var i=0,o=e,s=r-n;o0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],3:[function(t,e,r){"use strict";function n(){}function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function o(){this._events=new n,this._eventsCount=0}var s=Object.prototype.hasOwnProperty,a="~";Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(a=!1)),o.prototype.eventNames=function(){var t,e,r=[];if(0===this._eventsCount)return r;for(e in t=this._events)s.call(t,e)&&r.push(a?e.slice(1):e);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t,e){var r=a?a+t:t,n=this._events[r];if(e)return!!n;if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i=t.byteLength?n.bufferSubData(this.type,e,t):n.bufferData(this.type,t,this.drawType),this.data=t},i.prototype.bind=function(){this.gl.bindBuffer(this.type,this.buffer)},i.createVertexBuffer=function(t,e,r){return new i(t,t.ARRAY_BUFFER,e,r)},i.createIndexBuffer=function(t,e,r){return new i(t,t.ELEMENT_ARRAY_BUFFER,e,r)},i.create=function(t,e,r,n){return new i(t,e,r,n)},i.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer)},e.exports=i},{}],7:[function(t,e,r){var n=t("./GLTexture"),i=function(t,e,r){this.gl=t,this.framebuffer=t.createFramebuffer(),this.stencil=null,this.texture=null,this.width=e||100,this.height=r||100};i.prototype.enableTexture=function(t){var e=this.gl;this.texture=t||new n(e),this.texture.bind(),this.bind(),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0)},i.prototype.enableStencil=function(){if(!this.stencil){var t=this.gl;this.stencil=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.stencil),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.stencil),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,this.width,this.height)}},i.prototype.clear=function(t,e,r,n){this.bind();var i=this.gl;i.clearColor(t,e,r,n),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT)},i.prototype.bind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer)},i.prototype.unbind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)},i.prototype.resize=function(t,e){var r=this.gl;this.width=t,this.height=e,this.texture&&this.texture.uploadData(null,t,e),this.stencil&&(r.bindRenderbuffer(r.RENDERBUFFER,this.stencil),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e))},i.prototype.destroy=function(){var t=this.gl;this.texture&&this.texture.destroy(),t.deleteFramebuffer(this.framebuffer),this.gl=null,this.stencil=null,this.texture=null},i.createRGBA=function(t,e,r,o){var s=n.fromData(t,null,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},i.createFloat32=function(t,e,r,o){var s=new n.fromData(t,o,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},e.exports=i},{"./GLTexture":9}],8:[function(t,e,r){var n=t("./shader/compileProgram"),i=t("./shader/extractAttributes"),o=t("./shader/extractUniforms"),s=t("./shader/setPrecision"),a=t("./shader/generateUniformAccessObject"),u=function(t,e,r,u,h){this.gl=t,u&&(e=s(e,u),r=s(r,u)),this.program=n(t,e,r,h),this.attributes=i(t,this.program),this.uniformData=o(t,this.program),this.uniforms=a(t,this.uniformData)};u.prototype.bind=function(){return this.gl.useProgram(this.program),this},u.prototype.destroy=function(){this.attributes=null,this.uniformData=null,this.uniforms=null,this.gl.deleteProgram(this.program)},e.exports=u},{"./shader/compileProgram":14,"./shader/extractAttributes":16,"./shader/extractUniforms":17,"./shader/generateUniformAccessObject":18,"./shader/setPrecision":22}],9:[function(t,e,r){var n=function(t,e,r,n,i){this.gl=t,this.texture=t.createTexture(),this.mipmap=!1,this.premultiplyAlpha=!1,this.width=e||-1,this.height=r||-1,this.format=n||t.RGBA,this.type=i||t.UNSIGNED_BYTE};n.prototype.upload=function(t){this.bind();var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var r=t.videoWidth||t.width,n=t.videoHeight||t.height;n!==this.height||r!==this.width?e.texImage2D(e.TEXTURE_2D,0,this.format,this.format,this.type,t):e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.format,this.type,t),this.width=r,this.height=n};var i=!1;n.prototype.uploadData=function(t,e,r){this.bind();var n=this.gl;if(t instanceof Float32Array){if(!i){if(!n.getExtension("OES_texture_float"))throw new Error("floating point textures not available");i=!0}this.type=n.FLOAT}else this.type=this.type||n.UNSIGNED_BYTE;n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),e!==this.width||r!==this.height?n.texImage2D(n.TEXTURE_2D,0,this.format,e,r,0,this.format,this.type,t||null):n.texSubImage2D(n.TEXTURE_2D,0,0,0,e,r,this.format,this.type,t||null),this.width=e,this.height=r},n.prototype.bind=function(t){var e=this.gl;void 0!==t&&e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,this.texture)},n.prototype.unbind=function(){var t=this.gl;t.bindTexture(t.TEXTURE_2D,null)},n.prototype.minFilter=function(t){var e=this.gl;this.bind(),this.mipmap?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.magFilter=function(t){var e=this.gl;this.bind(),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.enableMipmap=function(){var t=this.gl;this.bind(),this.mipmap=!0,t.generateMipmap(t.TEXTURE_2D)},n.prototype.enableLinearScaling=function(){this.minFilter(!0),this.magFilter(!0)},n.prototype.enableNearestScaling=function(){this.minFilter(!1),this.magFilter(!1)},n.prototype.enableWrapClamp=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)},n.prototype.enableWrapRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT)},n.prototype.enableWrapMirrorRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.MIRRORED_REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.MIRRORED_REPEAT)},n.prototype.destroy=function(){this.gl.deleteTexture(this.texture)},n.fromSource=function(t,e,r){var i=new n(t);return i.premultiplyAlpha=r||!1,i.upload(e),i},n.fromData=function(t,e,r,i){var o=new n(t);return o.uploadData(e,r,i),o},e.exports=n},{}],10:[function(t,e,r){function n(t,e){if(this.nativeVaoExtension=null,n.FORCE_NATIVE||(this.nativeVaoExtension=t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object")),this.nativeState=e,this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var r=t.getParameter(t.MAX_VERTEX_ATTRIBS);this.nativeState={tempAttribState:new Array(r),attribState:new Array(r)}}this.gl=t,this.attributes=[],this.indexBuffer=null,this.dirty=!1}var i=t("./setVertexAttribArrays");n.prototype.constructor=n,e.exports=n,n.FORCE_NATIVE=!1,n.prototype.bind=function(){if(this.nativeVao){if(this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao),this.dirty)return this.dirty=!1,this.activate(),this;this.indexBuffer&&this.indexBuffer.bind()}else this.activate();return this},n.prototype.unbind=function(){return this.nativeVao&&this.nativeVaoExtension.bindVertexArrayOES(null),this},n.prototype.activate=function(){for(var t=this.gl,e=null,r=0;r=0;n--){var i=t[n];"."===i?t.splice(n,1):".."===i?(t.splice(n,1),r++):r&&(t.splice(n,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}function n(t,e){if(t.filter)return t.filter(e);for(var r=[],n=0;n=-1&&!i;o--){var s=o>=0?arguments[o]:t.cwd();if("string"!=typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(r=s+"/"+r,i="/"===s.charAt(0))}return r=e(n(r.split("/"),function(t){return!!t}),!i).join("/"),(i?"/":"")+r||"."},r.normalize=function(t){var i=r.isAbsolute(t),o="/"===s(t,-1);return t=e(n(t.split("/"),function(t){return!!t}),!i).join("/"),t||i||(t="."),t&&o&&(t+="/"),(i?"/":"")+t},r.isAbsolute=function(t){return"/"===t.charAt(0)},r.join=function(){var t=Array.prototype.slice.call(arguments,0);return r.normalize(n(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},r.relative=function(t,e){function n(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=r.resolve(t).substr(1),e=r.resolve(e).substr(1);for(var i=n(t.split("/")),o=n(e.split("/")),s=Math.min(i.length,o.length),a=s,u=0;u1)for(var r=1;r1&&(n=r[0]+"@",t=r[1]),t=t.replace(D,"."),n+s(t.split("."),e).join(".")}function u(t){for(var e,r,n=[],i=0,o=t.length;i=55296&&e<=56319&&i65535&&(t-=65536,e+=B(t>>>10&1023|55296),t=56320|1023&t),e+=B(t)}).join("")}function l(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:w}function c(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function d(t,e,r){var n=0;for(t=r?F(t/M):t>>1,t+=F(t/e);t>N*S>>1;n+=w)t=F(t/N);return F(n+(N+1)*t/(t+O))}function f(t){var e,r,n,i,s,a,u,c,f,p,v=[],y=t.length,g=0,m=C,_=P;for(r=t.lastIndexOf(R),r<0&&(r=0),n=0;n=128&&o("not-basic"),v.push(t.charCodeAt(n));for(i=r>0?r+1:0;i=y&&o("invalid-input"),c=l(t.charCodeAt(i++)),(c>=w||c>F((T-g)/a))&&o("overflow"),g+=c*a,f=u<=_?E:u>=_+S?S:u-_,!(cF(T/p)&&o("overflow"),a*=p;e=v.length+1,_=d(g-s,e,0==s),F(g/e)>T-m&&o("overflow"),m+=F(g/e),g%=e,v.splice(g++,0,m)}return h(v)}function p(t){var e,r,n,i,s,a,h,l,f,p,v,y,g,m,_,b=[];for(t=u(t),y=t.length,e=C,r=0,s=P,a=0;a=e&&vF((T-r)/g)&&o("overflow"),r+=(h-e)*g,e=h,a=0;aT&&o("overflow"),v==e){for(l=r,f=w;p=f<=s?E:f>=s+S?S:f-s,!(l= 0x80 (not a basic code point)","invalid-input":"Invalid input"},N=w-E,F=Math.floor,B=String.fromCharCode;if(b={version:"1.4.1",ucs2:{decode:u,encode:h},decode:f,encode:p,toASCII:y,toUnicode:v},"function"==typeof t&&"object"==typeof t.amd&&t.amd)t("punycode",function(){return b});else if(g&&m)if(r.exports==g)m.exports=b;else for(x in b)b.hasOwnProperty(x)&&(g[x]=b[x]);else i.punycode=b}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],26:[function(t,e,r){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,r,o){e=e||"&",r=r||"=";var s={};if("string"!=typeof t||0===t.length)return s;var a=/\+/g;t=t.split(e);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var h=t.length;u>0&&h>u&&(h=u);for(var l=0;l=0?(c=v.substr(0,y),d=v.substr(y+1)):(c=v,d=""),f=decodeURIComponent(c),p=decodeURIComponent(d),n(s,f)?i(s[f])?s[f].push(p):s[f]=[s[f],p]:s[f]=p}return s};var i=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],27:[function(t,e,r){"use strict";function n(t,e){if(t.map)return t.map(e);for(var r=[],n=0;n",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(f),v=["'"].concat(p),y=["%","/","?",";","#"].concat(v),g=["/","?","#"],m=/^[+a-z0-9A-Z_-]{0,63}$/,_=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,b={javascript:!0,"javascript:":!0},x={javascript:!0,"javascript:":!0},T={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},w=t("querystring");n.prototype.parse=function(t,e,r){if(!h.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var n=t.indexOf("?"),i=-1!==n&&n127?L+="x":L+=D[N];if(!L.match(m)){var B=A.slice(0,O),k=A.slice(O+1),j=D.match(_);j&&(B.push(j[1]),k.unshift(j[2])),k.length&&(a="/"+k.join(".")+a),this.hostname=B.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),R||(this.hostname=u.toASCII(this.hostname));var U=this.port?":"+this.port:"",X=this.hostname||"";this.host=X+U,this.href+=this.host,R&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==a[0]&&(a="/"+a))}if(!b[p])for(var O=0,I=v.length;O0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return r.search=t.search,r.query=t.query,h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!w.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var O=w.slice(-1)[0],M=(r.host||t.host||w.length>1)&&("."===O||".."===O)||""===O,P=0,C=w.length;C>=0;C--)O=w[C],"."===O?w.splice(C,1):".."===O?(w.splice(C,1),P++):P&&(w.splice(C,1),P--);if(!_&&!b)for(;P--;P)w.unshift("..");!_||""===w[0]||w[0]&&"/"===w[0].charAt(0)||w.unshift(""),M&&"/"!==w.join("/").substr(-1)&&w.push("");var R=""===w[0]||w[0]&&"/"===w[0].charAt(0);if(E){r.hostname=r.host=R?"":w.length?w.shift():"";var S=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return _=_||r.host&&w.length,_&&!R&&w.unshift(""),w.length?r.pathname=w.join("/"):(r.pathname=null,r.path=null),h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},n.prototype.parseHost=function(){var t=this.host,e=c.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":30,punycode:25,querystring:28}],30:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],31:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n,i=t.length;if(!(e>=i||0===r)){r=e+r>i?i-e:r;var o=i-r;for(n=e;n0&&void 0!==arguments[0]?arguments[0]:"",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10;i(this,t),this.baseUrl=r,this.progress=0,this.loading=!1,this.defaultQueryString="",this._beforeMiddleware=[],this._afterMiddleware=[],this._resourcesParsing=[],this._boundLoadResource=function(t,r){return e._loadResource(t,r)},this._queue=c.queue(this._boundLoadResource,n),this._queue.pause(),this.resources={},this.onProgress=new a.default,this.onError=new a.default,this.onLoad=new a.default,this.onStart=new a.default,this.onComplete=new a.default}return t.prototype.add=function(t,e,r,n){if(Array.isArray(t)){for(var i=0;i0?n=200:1223===n&&(n=204),2!=(n/100|0))return void this.abort("["+e.status+"] "+e.statusText+": "+e.responseURL);if(this.xhrType===t.XHR_RESPONSE_TYPE.TEXT)this.data=r,this.type=t.TYPE.TEXT;else if(this.xhrType===t.XHR_RESPONSE_TYPE.JSON)try{this.data=JSON.parse(r),this.type=t.TYPE.JSON}catch(t){return void this.abort("Error trying to parse loaded json: "+t)}else if(this.xhrType===t.XHR_RESPONSE_TYPE.DOCUMENT)try{if(window.DOMParser){var i=new DOMParser;this.data=i.parseFromString(r,"text/xml")}else{var o=document.createElement("div");o.innerHTML=r,this.data=o}this.type=t.TYPE.XML}catch(t){return void this.abort("Error trying to parse loaded xml: "+t)}else this.data=e.response||r;this.complete()},t.prototype._determineCrossOrigin=function(t,e){if(0===t.indexOf("data:"))return"";e=e||window.location,p||(p=document.createElement("a")),p.href=t,t=(0,l.default)(p.href,{strictMode:!0});var r=!t.port&&""===e.port||t.port===e.port,n=t.protocol?t.protocol+":":"";return t.host===e.hostname&&r&&n===e.protocol?"":"anonymous"},t.prototype._determineXhrType=function(){return t._xhrTypeMap[this.extension]||t.XHR_RESPONSE_TYPE.TEXT},t.prototype._determineLoadType=function(){return t._loadTypeMap[this.extension]||t.LOAD_TYPE.XHR},t.prototype._getExtension=function(){var t=this.url,e="";if(this.isDataUrl){var r=t.indexOf("/");e=t.substring(r+1,t.indexOf(";",r))}else{var n=t.indexOf("?"),i=t.indexOf("#"),o=Math.min(n>-1?n:t.length,i>-1?i:t.length);t=t.substring(0,o),e=t.substring(t.lastIndexOf(".")+1)}return e.toLowerCase()},t.prototype._getMimeFromXhrType=function(e){switch(e){case t.XHR_RESPONSE_TYPE.BUFFER:return"application/octet-binary";case t.XHR_RESPONSE_TYPE.BLOB:return"application/blob";case t.XHR_RESPONSE_TYPE.DOCUMENT:return"application/xml";case t.XHR_RESPONSE_TYPE.JSON:return"application/json";case t.XHR_RESPONSE_TYPE.DEFAULT:case t.XHR_RESPONSE_TYPE.TEXT:default:return"text/plain"}},u(t,[{key:"isDataUrl",get:function(){return this._hasFlag(t.STATUS_FLAGS.DATA_URL)}},{key:"isComplete",get:function(){return this._hasFlag(t.STATUS_FLAGS.COMPLETE)}},{key:"isLoading",get:function(){return this._hasFlag(t.STATUS_FLAGS.LOADING)}}]),t}();r.default=v,v.STATUS_FLAGS={NONE:0,DATA_URL:1,COMPLETE:2,LOADING:4},v.TYPE={UNKNOWN:0,JSON:1,XML:2,IMAGE:3,AUDIO:4,VIDEO:5,TEXT:6},v.LOAD_TYPE={XHR:1,IMAGE:2,AUDIO:3,VIDEO:4},v.XHR_RESPONSE_TYPE={DEFAULT:"text",BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"},v._loadTypeMap={gif:v.LOAD_TYPE.IMAGE,png:v.LOAD_TYPE.IMAGE,bmp:v.LOAD_TYPE.IMAGE,jpg:v.LOAD_TYPE.IMAGE,jpeg:v.LOAD_TYPE.IMAGE,tif:v.LOAD_TYPE.IMAGE,tiff:v.LOAD_TYPE.IMAGE,webp:v.LOAD_TYPE.IMAGE,tga:v.LOAD_TYPE.IMAGE,svg:v.LOAD_TYPE.IMAGE,"svg+xml":v.LOAD_TYPE.IMAGE,mp3:v.LOAD_TYPE.AUDIO,ogg:v.LOAD_TYPE.AUDIO,wav:v.LOAD_TYPE.AUDIO,mp4:v.LOAD_TYPE.VIDEO,webm:v.LOAD_TYPE.VIDEO},v._xhrTypeMap={xhtml:v.XHR_RESPONSE_TYPE.DOCUMENT,html:v.XHR_RESPONSE_TYPE.DOCUMENT,htm:v.XHR_RESPONSE_TYPE.DOCUMENT,xml:v.XHR_RESPONSE_TYPE.DOCUMENT,tmx:v.XHR_RESPONSE_TYPE.DOCUMENT,svg:v.XHR_RESPONSE_TYPE.DOCUMENT,tsx:v.XHR_RESPONSE_TYPE.DOCUMENT,gif:v.XHR_RESPONSE_TYPE.BLOB,png:v.XHR_RESPONSE_TYPE.BLOB,bmp:v.XHR_RESPONSE_TYPE.BLOB,jpg:v.XHR_RESPONSE_TYPE.BLOB,jpeg:v.XHR_RESPONSE_TYPE.BLOB,tif:v.XHR_RESPONSE_TYPE.BLOB,tiff:v.XHR_RESPONSE_TYPE.BLOB,webp:v.XHR_RESPONSE_TYPE.BLOB,tga:v.XHR_RESPONSE_TYPE.BLOB,json:v.XHR_RESPONSE_TYPE.JSON,text:v.XHR_RESPONSE_TYPE.TEXT,txt:v.XHR_RESPONSE_TYPE.TEXT,ttf:v.XHR_RESPONSE_TYPE.BUFFER,otf:v.XHR_RESPONSE_TYPE.BUFFER},v.EMPTY_GIF="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="},{"mini-signals":38,"parse-uri":39}],34:[function(t,e,r){"use strict";function n(){}function i(t,e,r,n){var i=0,o=t.length;!function s(a){if(a||i===o)return void(r&&r(a));n?setTimeout(function(){e(t[i++],s)},1):e(t[i++],s)}()}function o(t){return function(){if(null===t)throw new Error("Callback was already called.");var e=t;t=null,e.apply(this,arguments)}}function s(t,e){function r(t,e,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(a.started=!0,null==t&&a.idle())return void setTimeout(function(){return a.drain()},1);var i={data:t,callback:"function"==typeof r?r:n};e?a._tasks.unshift(i):a._tasks.push(i),setTimeout(function(){return a.process()},1)}function i(t){return function(){s-=1,t.callback.apply(t,arguments),null!=arguments[0]&&a.error(arguments[0],t.data),s<=a.concurrency-a.buffer&&a.unsaturated(),a.idle()&&a.drain(),a.process()}}if(null==e)e=1;else if(0===e)throw new Error("Concurrency must not be zero");var s=0,a={_tasks:[],concurrency:e,saturated:n,unsaturated:n,buffer:e/4,empty:n,drain:n,error:n,started:!1,paused:!1,push:function(t,e){r(t,!1,e)},kill:function(){s=0,a.drain=n,a.started=!1,a._tasks=[]},unshift:function(t,e){r(t,!0,e)},process:function(){for(;!a.paused&&s>2,o[1]=(3&n[0])<<4|n[1]>>4,o[2]=(15&n[1])<<2|n[2]>>6,o[3]=63&n[2];switch(r-(t.length-1)){case 2:o[3]=64,o[2]=64;break;case 1:o[3]=64}for(var a=0;a=0;r--)this.updateAccessibleObjects(e[r])}},t.prototype.update=function(){if(this.renderer.renderingToScreen){this.updateAccessibleObjects(this.renderer._lastObjectRendered);var t=this.renderer.view.getBoundingClientRect(),e=t.width/this.renderer.width,r=t.height/this.renderer.height,n=this.div;n.style.left=t.left+"px",n.style.top=t.top+"px",n.style.width=this.renderer.width+"px",n.style.height=this.renderer.height+"px";for(var i=0;ithis.renderer.width&&(t.width=this.renderer.width-t.x),t.y+t.height>this.renderer.height&&(t.height=this.renderer.height-t.y)},t.prototype.addChild=function(t){var e=this.pool.pop();e||(e=document.createElement("button"),e.style.width=c+"px",e.style.height=c+"px",e.style.backgroundColor=this.debug?"rgba(255,0,0,0.5)":"transparent",e.style.position="absolute",e.style.zIndex=p,e.style.borderStyle="none",e.addEventListener("click",this._onClick.bind(this)),e.addEventListener("focus",this._onFocus.bind(this)),e.addEventListener("focusout",this._onFocusOut.bind(this))),t.accessibleTitle?e.title=t.accessibleTitle:t.accessibleTitle||t.accessibleHint||(e.title="displayObject "+this.tabIndex),t.accessibleHint&&e.setAttribute("aria-label",t.accessibleHint),t._accessibleActive=!0,t._accessibleDiv=e,e.displayObject=t,this.children.push(t),this.div.appendChild(t._accessibleDiv),t._accessibleDiv.tabIndex=t.tabIndex},t.prototype._onClick=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"click",e.eventData)},t.prototype._onFocus=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseover",e.eventData)},t.prototype._onFocusOut=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseout",e.eventData)},t.prototype._onKeyDown=function(t){9===t.keyCode&&this.activate()},t.prototype._onMouseMove=function(){this.deactivate()},t.prototype.destroy=function(){this.div=null;for(var t=0;t]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i,r.SHAPES={POLY:0,RECT:1,CIRC:2,ELIP:3,RREC:4},r.PRECISION={LOW:"lowp",MEDIUM:"mediump",HIGH:"highp"},r.TRANSFORM_MODE={STATIC:0,DYNAMIC:1},r.TEXT_GRADIENT={LINEAR_VERTICAL:0,LINEAR_HORIZONTAL:1},r.UPDATE_PRIORITY={INTERACTION:50,HIGH:25,NORMAL:0,LOW:-25,UTILITY:-50}},{}],47:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../math"),o=function(){function t(){n(this,t),this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.rect=null}return t.prototype.isEmpty=function(){return this.minX>this.maxX||this.minY>this.maxY},t.prototype.clear=function(){this.updateID++,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0},t.prototype.getRectangle=function(t){return this.minX>this.maxX||this.minY>this.maxY?i.Rectangle.EMPTY:(t=t||new i.Rectangle(0,0,1,1),t.x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)},t.prototype.addPoint=function(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)},t.prototype.addQuad=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY,o=t[0],s=t[1];e=on?o:n,i=s>i?s:i,o=t[2],s=t[3],e=on?o:n,i=s>i?s:i,o=t[4],s=t[5],e=on?o:n,i=s>i?s:i,o=t[6],s=t[7],e=on?o:n,i=s>i?s:i,this.minX=e,this.minY=r,this.maxX=n,this.maxY=i},t.prototype.addFrame=function(t,e,r,n,i){var o=t.worldTransform,s=o.a,a=o.b,u=o.c,h=o.d,l=o.tx,c=o.ty,d=this.minX,f=this.minY,p=this.maxX,v=this.maxY,y=s*e+u*r+l,g=a*e+h*r+c;d=yp?y:p,v=g>v?g:v,y=s*n+u*r+l,g=a*n+h*r+c,d=yp?y:p,v=g>v?g:v,y=s*e+u*i+l,g=a*e+h*i+c,d=yp?y:p,v=g>v?g:v,y=s*n+u*i+l,g=a*n+h*i+c,d=yp?y:p,v=g>v?g:v,this.minX=d,this.minY=f,this.maxX=p,this.maxY=v},t.prototype.addVertices=function(t,e,r,n){for(var i=t.worldTransform,o=i.a,s=i.b,a=i.c,u=i.d,h=i.tx,l=i.ty,c=this.minX,d=this.minY,f=this.maxX,p=this.maxY,v=r;vf?m:f,p=_>p?_:p}this.minX=c,this.minY=d,this.maxX=f,this.maxY=p},t.prototype.addBounds=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY;this.minX=t.minXn?t.maxX:n,this.maxY=t.maxY>i?t.maxY:i},t.prototype.addBoundsMask=function(t,e){var r=t.minX>e.minX?t.minX:e.minX,n=t.minY>e.minY?t.minY:e.minY,i=t.maxXu?i:u,this.maxY=o>h?o:h}},t.prototype.addBoundsArea=function(t,e){var r=t.minX>e.x?t.minX:e.x,n=t.minY>e.y?t.minY:e.y,i=t.maxXu?i:u,this.maxY=o>h?o:h}},t}();r.default=o},{"../math":70}],48:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r1)for(var r=0;rthis.children.length)throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length);return t.parent&&t.parent.removeChild(t),t.parent=this,t.transform._parentID=-1,this.children.splice(e,0,t),this._boundsID++,this.onChildrenChange(e),t.emit("added",this),t},e.prototype.swapChildren=function(t,e){if(t!==e){var r=this.getChildIndex(t),n=this.getChildIndex(e);this.children[r]=e,this.children[n]=t,this.onChildrenChange(r=this.children.length)throw new Error("The supplied index is out of bounds");var r=this.getChildIndex(t);(0,a.removeItems)(this.children,r,1),this.children.splice(e,0,t),this.onChildrenChange(e)},e.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Index ("+t+") does not exist.");return this.children[t]},e.prototype.removeChild=function(t){var e=arguments.length;if(e>1)for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=t,n="number"==typeof e?e:this.children.length,i=n-r,o=void 0;if(i>0&&i<=n){o=this.children.splice(r,i);for(var s=0;s2&&void 0!==arguments[2]&&arguments[2]||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)},e.prototype.toLocal=function(t,e,r,n){return e&&(t=e.toGlobal(t,r,n)),n||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,r)},e.prototype.renderWebGL=function(t){},e.prototype.renderCanvas=function(t){},e.prototype.setParent=function(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t},e.prototype.setTransform=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0,u=arguments.length>8&&void 0!==arguments[8]?arguments[8]:0;return this.position.x=t,this.position.y=e,this.scale.x=r||1,this.scale.y=n||1,this.rotation=i,this.skew.x=o,this.skew.y=s,this.pivot.x=a,this.pivot.y=u,this},e.prototype.destroy=function(){this.removeAllListeners(),this.parent&&this.parent.removeChild(this),this.transform=null,this.parent=null,this._bounds=null,this._currentBounds=null,this._mask=null,this.filterArea=null,this.interactive=!1,this.interactiveChildren=!1,this._destroyed=!0},a(e,[{key:"_tempDisplayObjectParent",get:function(){return null===this.tempDisplayObjectParent&&(this.tempDisplayObjectParent=new e),this.tempDisplayObjectParent}},{key:"x",get:function(){return this.position.x},set:function(t){this.transform.position.x=t}},{key:"y",get:function(){return this.position.y},set:function(t){this.transform.position.y=t}},{key:"worldTransform",get:function(){return this.transform.worldTransform}},{key:"localTransform",get:function(){return this.transform.localTransform}},{key:"position",get:function(){return this.transform.position},set:function(t){this.transform.position.copy(t)}},{key:"scale",get:function(){return this.transform.scale},set:function(t){this.transform.scale.copy(t)}},{key:"pivot",get:function(){return this.transform.pivot},set:function(t){this.transform.pivot.copy(t)}},{key:"skew",get:function(){return this.transform.skew},set:function(t){this.transform.skew.copy(t)}},{key:"rotation",get:function(){return this.transform.rotation},set:function(t){this.transform.rotation=t}},{key:"worldVisible",get:function(){var t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask&&(this._mask.renderable=!0),this._mask=t,this._mask&&(this._mask.renderable=!1)}},{key:"filters",get:function(){return this._filters&&this._filters.slice()},set:function(t){this._filters=t&&t.slice()}}]),e}(h.default);r.default=b,b.prototype.displayObjectUpdateTransform=b.prototype.updateTransform},{"../const":46,"../math":70,"../settings":101,"./Bounds":47,"./Transform":50,"./TransformStatic":52,eventemitter3:3}],50:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]&&arguments[0];i(this,e);var n=o(this,t.call(this));return n.fillAlpha=1,n.lineWidth=0,n.nativeLines=r,n.lineColor=0,n.graphicsData=[],n.tint=16777215,n._prevTint=16777215,n.blendMode=_.BLEND_MODES.NORMAL,n.currentPath=null,n._webGL={},n.isMask=!1,n.boundsPadding=0,n._localBounds=new x.default,n.dirty=0,n.fastRectDirty=-1,n.clearDirty=0,n.boundsDirty=-1,n.cachedSpriteDirty=!1,n._spriteRect=null,n._fastRect=!1,n}return s(e,t),e.prototype.clone=function(){var t=new e;t.renderable=this.renderable,t.fillAlpha=this.fillAlpha,t.lineWidth=this.lineWidth,t.lineColor=this.lineColor,t.tint=this.tint,t.blendMode=this.blendMode,t.isMask=this.isMask,t.boundsPadding=this.boundsPadding,t.dirty=0,t.cachedSpriteDirty=this.cachedSpriteDirty;for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;if(this.lineWidth=t,this.lineColor=e,this.lineAlpha=r,this.currentPath)if(this.currentPath.shape.points.length){var n=new g.Polygon(this.currentPath.shape.points.slice(-2));n.closed=!1,this.drawShape(n)}else this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha;return this},e.prototype.moveTo=function(t,e){var r=new g.Polygon([t,e]);return r.closed=!1,this.drawShape(r),this},e.prototype.lineTo=function(t,e){return this.currentPath.shape.points.push(t,e),this.dirty++,this},e.prototype.quadraticCurveTo=function(t,e,r,n){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var i=this.currentPath.shape.points,o=0,s=0;0===i.length&&this.moveTo(0,0);for(var a=i[i.length-2],u=i[i.length-1],h=1;h<=20;++h){var l=h/20;o=a+(t-a)*l,s=u+(e-u)*l,i.push(o+(t+(r-t)*l-o)*l,s+(e+(n-e)*l-s)*l)}return this.dirty++,this},e.prototype.bezierCurveTo=function(t,e,r,n,i,o){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var s=this.currentPath.shape.points,a=s[s.length-2],u=s[s.length-1];return s.length-=2,(0,w.default)(a,u,t,e,r,n,i,o,s),this.dirty++,this},e.prototype.arcTo=function(t,e,r,n,i){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(t,e):this.moveTo(t,e);var o=this.currentPath.shape.points,s=o[o.length-2],a=o[o.length-1],u=a-e,h=s-t,l=n-e,c=r-t,d=Math.abs(u*c-h*l);if(d<1e-8||0===i)o[o.length-2]===t&&o[o.length-1]===e||o.push(t,e);else{var f=u*u+h*h,p=l*l+c*c,v=u*l+h*c,y=i*Math.sqrt(f)/d,g=i*Math.sqrt(p)/d,m=y*v/f,_=g*v/p,b=y*c+g*h,x=y*l+g*u,T=h*(g+m),w=u*(g+m),E=c*(y+_),S=l*(y+_),O=Math.atan2(w-x,T-b),M=Math.atan2(S-x,E-b);this.arc(b+t,x+e,i,O,M,h*l>c*u)}return this.dirty++,this},e.prototype.arc=function(t,e,r,n,i){var o=arguments.length>5&&void 0!==arguments[5]&&arguments[5];if(n===i)return this;!o&&i<=n?i+=2*Math.PI:o&&n<=i&&(n+=2*Math.PI);var s=i-n,a=40*Math.ceil(Math.abs(s)/(2*Math.PI));if(0===s)return this;var u=t+Math.cos(n)*r,h=e+Math.sin(n)*r,l=this.currentPath?this.currentPath.shape.points:null;l?l[l.length-2]===u&&l[l.length-1]===h||l.push(u,h):(this.moveTo(u,h),l=this.currentPath.shape.points);for(var c=s/(2*a),d=2*c,f=Math.cos(c),p=Math.sin(c),v=a-1,y=v%1/v,g=0;g<=v;++g){var m=g+y*g,_=c+n+d*m,b=Math.cos(_),x=-Math.sin(_);l.push((f*b+p*x)*r+t,(f*-x+p*b)*r+e)}return this.dirty++,this},e.prototype.beginFill=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this.filling=!0,this.fillColor=t,this.fillAlpha=e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},e.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},e.prototype.drawRect=function(t,e,r,n){return this.drawShape(new g.Rectangle(t,e,r,n)),this},e.prototype.drawRoundedRect=function(t,e,r,n,i){return this.drawShape(new g.RoundedRectangle(t,e,r,n,i)),this},e.prototype.drawCircle=function(t,e,r){return this.drawShape(new g.Circle(t,e,r)),this},e.prototype.drawEllipse=function(t,e,r,n){return this.drawShape(new g.Ellipse(t,e,r,n)),this},e.prototype.drawPolygon=function(t){var e=t,r=!0;if(e instanceof g.Polygon&&(r=e.closed,e=e.points),!Array.isArray(e)){e=new Array(arguments.length);for(var n=0;n0)&&(this.lineWidth=0,this.filling=!1,this.boundsDirty=-1,this.dirty++,this.clearDirty++,this.graphicsData.length=0),this.currentPath=null,this._spriteRect=null,this},e.prototype.isFastRect=function(){return 1===this.graphicsData.length&&this.graphicsData[0].shape.type===_.SHAPES.RECT&&!this.graphicsData[0].lineWidth},e.prototype._renderWebGL=function(t){this.dirty!==this.fastRectDirty&&(this.fastRectDirty=this.dirty,this._fastRect=this.isFastRect()),this._fastRect?this._renderSpriteRect(t):(t.setObjectRenderer(t.plugins.graphics),t.plugins.graphics.render(this))},e.prototype._renderSpriteRect=function(t){var e=this.graphicsData[0].shape;this._spriteRect||(this._spriteRect=new y.default(new d.default(d.default.WHITE)));var r=this._spriteRect;if(16777215===this.tint)r.tint=this.graphicsData[0].fillColor;else{var n=C,i=R;(0,m.hex2rgb)(this.graphicsData[0].fillColor,n),(0,m.hex2rgb)(this.tint,i),n[0]*=i[0],n[1]*=i[1],n[2]*=i[2],r.tint=(0,m.rgb2hex)(n)}r.alpha=this.graphicsData[0].fillAlpha,r.worldAlpha=this.worldAlpha*r.alpha,r.blendMode=this.blendMode,r._texture._frame.width=e.width,r._texture._frame.height=e.height,r.transform.worldTransform=this.transform.worldTransform,r.anchor.set(-e.x/e.width,-e.y/e.height),r._onAnchorUpdate(),r._renderWebGL(t)},e.prototype._renderCanvas=function(t){!0!==this.isMask&&t.plugins.graphics.render(this)},e.prototype._calculateBounds=function(){this.boundsDirty!==this.dirty&&(this.boundsDirty=this.dirty,this.updateLocalBounds(),this.cachedSpriteDirty=!0);var t=this._localBounds;this._bounds.addFrame(this.transform,t.minX,t.minY,t.maxX,t.maxY)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,P);for(var e=this.graphicsData,r=0;re?o+a:e,r=sn?s+u:n;else if(c===_.SHAPES.CIRC)o=i.x,s=i.y,a=i.radius+d/2,u=i.radius+d/2,t=o-ae?o+a:e,r=s-un?s+u:n;else if(c===_.SHAPES.ELIP)o=i.x,s=i.y,a=i.width+d/2,u=i.height+d/2,t=o-ae?o+a:e,r=s-un?s+u:n;else for(var f=i.points,p=0,v=0,y=0,g=0,m=0,b=0,x=0,T=0,w=0;w+2e?x+m:e,r=T-bn?T+b:n)}else t=0,e=0,r=0,n=0;var E=this.boundsPadding;this._localBounds.minX=t-E,this._localBounds.maxX=e+E,this._localBounds.minY=r-E,this._localBounds.maxY=n+E},e.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null;var e=new p.default(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,this.nativeLines,t);return this.graphicsData.push(e),e.type===_.SHAPES.POLY&&(e.shape.closed=e.shape.closed||this.filling,this.currentPath=e),this.dirty++,e},e.prototype.generateCanvasTexture=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=this.getLocalBounds(),n=l.default.create(r.width,r.height,t,e);O||(O=new S.default),this.transform.updateLocalTransform(),this.transform.localTransform.copy(M),M.invert(),M.tx-=r.x,M.ty-=r.y,O.render(this,n,!0,M);var i=d.default.fromCanvas(n.baseTexture._canvasRenderTarget.canvas,t,"graphics");return i.baseTexture.resolution=e,i.baseTexture.update(),i},e.prototype.closePath=function(){var t=this.currentPath;return t&&t.shape&&t.shape.close(),this},e.prototype.addHole=function(){var t=this.graphicsData.pop();return this.currentPath=this.graphicsData[this.graphicsData.length-1],this.currentPath.addHole(t.shape),this.currentPath=null,this},e.prototype.destroy=function(e){t.prototype.destroy.call(this,e);for(var r=0;rP?P:M,r.beginPath(),r.moveTo(w,E+M),r.lineTo(w,E+O-M),r.quadraticCurveTo(w,E+O,w+M,E+O),r.lineTo(w+S-M,E+O),r.quadraticCurveTo(w+S,E+O,w+S,E+O-M),r.lineTo(w+S,E+M),r.quadraticCurveTo(w+S,E,w+S-M,E),r.lineTo(w+M,E),r.quadraticCurveTo(w,E,w,E+M),r.closePath(),(u.fillColor||0===u.fillColor)&&(r.globalAlpha=u.fillAlpha*n,r.fillStyle="#"+("00000"+(0|l).toString(16)).substr(-6),r.fill()),u.lineWidth&&(r.globalAlpha=u.lineAlpha*n,r.strokeStyle="#"+("00000"+(0|c).toString(16)).substr(-6),r.stroke())}}},t.prototype.updateGraphicsTint=function(t){t._prevTint=t.tint;for(var e=(t.tint>>16&255)/255,r=(t.tint>>8&255)/255,n=(255&t.tint)/255,i=0;i>16&255)/255*e*255<<16)+((s>>8&255)/255*r*255<<8)+(255&s)/255*n*255,o._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*r*255<<8)+(255&a)/255*n*255}},t.prototype.renderPolygon=function(t,e,r){r.moveTo(t[0],t[1]);for(var n=1;n8&&void 0!==arguments[8]?arguments[8]:[],h=0,l=0,c=0,d=0,f=0;u.push(t,e);for(var p=1,v=0;p<=20;++p)v=p/20,h=1-v,l=h*h,c=l*h,d=v*v,f=d*v,u.push(c*t+3*l*v*r+3*h*d*i+f*s,c*e+3*l*v*n+3*h*d*o+f*a);return u}r.__esModule=!0,r.default=n},{}],57:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../utils"),u=t("../../const"),h=t("../../renderers/webgl/utils/ObjectRenderer"),l=n(h),c=t("../../renderers/webgl/WebGLRenderer"),d=n(c),f=t("./WebGLGraphicsData"),p=n(f),v=t("./shaders/PrimitiveShader"),y=n(v),g=t("./utils/buildPoly"),m=n(g),_=t("./utils/buildRectangle"),b=n(_),x=t("./utils/buildRoundedRectangle"),T=n(x),w=t("./utils/buildCircle"),E=n(w),S=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.graphicsDataPool=[],n.primitiveShader=null,n.gl=r.gl,n.CONTEXT_UID=0,n}return s(e,t),e.prototype.onContextChange=function(){this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.primitiveShader=new y.default(this.gl)},e.prototype.destroy=function(){l.default.prototype.destroy.call(this);for(var t=0;t32e4)&&(n=this.graphicsDataPool.pop()||new p.default(this.renderer.gl,this.primitiveShader,this.renderer.state.attribsState),n.nativeLines=r,n.reset(e),t.data.push(n)),n.dirty=!0,n},e}(l.default);r.default=S,d.default.registerPlugin("graphics",S)},{"../../const":46,"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../utils":125,"./WebGLGraphicsData":58,"./shaders/PrimitiveShader":59,"./utils/buildCircle":60,"./utils/buildPoly":62,"./utils/buildRectangle":63,"./utils/buildRoundedRectangle":64}],58:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("pixi-gl-core"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=function(){function t(e,r,i){n(this,t),this.gl=e,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=o.default.GLBuffer.createVertexBuffer(e),this.indexBuffer=o.default.GLBuffer.createIndexBuffer(e),this.dirty=!0,this.nativeLines=!1,this.glPoints=null,this.glIndices=null,this.shader=r,this.vao=new o.default.VertexArrayObject(e,i).addIndex(this.indexBuffer).addAttribute(this.buffer,r.attributes.aVertexPosition,e.FLOAT,!1,24,0).addAttribute(this.buffer,r.attributes.aColor,e.FLOAT,!1,24,8)}return t.prototype.reset=function(){this.points.length=0,this.indices.length=0},t.prototype.upload=function(){this.glPoints=new Float32Array(this.points),this.buffer.upload(this.glPoints),this.glIndices=new Uint16Array(this.indices),this.indexBuffer.upload(this.glIndices),this.dirty=!1},t.prototype.destroy=function(){this.color=null,this.points=null,this.indices=null,this.vao.destroy(),this.buffer.destroy(),this.indexBuffer.destroy(),this.gl=null,this.buffer=null,this.indexBuffer=null,this.glPoints=null,this.glIndices=null},t}();r.default=s},{"pixi-gl-core":12}],59:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=t("../../../Shader"),a=function(t){return t&&t.__esModule?t:{default:t}}(s),u=function(t){function e(r){return n(this,e),i(this,t.call(this,r,["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","uniform float alpha;","uniform vec3 tint;","varying vec4 vColor;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"].join("\n"),["varying vec4 vColor;","void main(void){"," gl_FragColor = vColor;","}"].join("\n")))}return o(e,t),e}(a.default);r.default=u},{"../../../Shader":44}],60:[function(t,e,r){"use strict";function n(t,e,r){var n=t.shape,i=n.x,u=n.y,h=void 0,l=void 0;if(t.type===s.SHAPES.CIRC?(h=n.radius,l=n.radius):(h=n.width,l=n.height),0!==h&&0!==l){var c=Math.floor(30*Math.sqrt(n.radius))||Math.floor(15*Math.sqrt(n.width+n.height)),d=2*Math.PI/c;if(t.fill){var f=(0,a.hex2rgb)(t.fillColor),p=t.fillAlpha,v=f[0]*p,y=f[1]*p,g=f[2]*p,m=e.points,_=e.indices,b=m.length/6;_.push(b);for(var x=0;x196*p*p?(R=O-P,A=M-C,I=Math.sqrt(R*R+A*A),R/=I,A/=I,R*=p,A*=p,h.push(T-R,w-A),h.push(g,m,_,y),h.push(T+R,w+A),h.push(g,m,_,y),h.push(T-R,w-A),h.push(g,m,_,y),d++):(h.push(X,G),h.push(g,m,_,y),h.push(T-(X-T),w-(G-w)),h.push(g,m,_,y))}}b=r[2*(c-2)],x=r[2*(c-2)+1],T=r[2*(c-1)],w=r[2*(c-1)+1],O=-(x-w),M=b-T,I=Math.sqrt(O*O+M*M),O/=I,M/=I,O*=p,M*=p,h.push(T-O,w-M),h.push(g,m,_,y),h.push(T+O,w+M),h.push(g,m,_,y),l.push(f);for(var W=0;W=6){for(var i=[],o=t.holes,u=0;u0&&(0,s.default)(t,e,r)}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils"),u=t("earcut"),h=n(u)},{"../../../utils":125,"./buildLine":61,earcut:2}],63:[function(t,e,r){"use strict";function n(t,e,r){var n=t.shape,i=n.x,a=n.y,u=n.width,h=n.height;if(t.fill){var l=(0,s.hex2rgb)(t.fillColor),c=t.fillAlpha,d=l[0]*c,f=l[1]*c,p=l[2]*c,v=e.points,y=e.indices,g=v.length/6;v.push(i,a),v.push(d,f,p,c),v.push(i+u,a),v.push(d,f,p,c),v.push(i,a+h),v.push(d,f,p,c),v.push(i+u,a+h),v.push(d,f,p,c),y.push(g,g,g+1,g+2,g+3,g+3)}if(t.lineWidth){var m=t.points;t.points=[i,a,i+u,a,i+u,a+h,i,a+h,i,a],(0,o.default)(t,e,r),t.points=m}}r.__esModule=!0,r.default=n;var i=t("./buildLine"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=t("../../../utils")},{"../../../utils":125,"./buildLine":61}],64:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e,r){var n=t.shape,i=n.x,o=n.y,a=n.width,h=n.height,d=n.radius,f=[];if(f.push(i,o+d),s(i,o+h-d,i,o+h,i+d,o+h,f),s(i+a-d,o+h,i+a,o+h,i+a,o+h-d,f),s(i+a,o+d,i+a,o,i+a-d,o,f),s(i+d,o,i,o,i,o+d+1e-10,f),t.fill){for(var p=(0,c.hex2rgb)(t.fillColor),v=t.fillAlpha,y=p[0]*v,g=p[1]*v,m=p[2]*v,_=e.points,b=e.indices,x=_.length/6,T=(0,u.default)(f,null,2),w=0,E=T.length;w6&&void 0!==arguments[6]?arguments[6]:[],u=a,h=0,l=0,c=0,d=0,f=0,p=0,v=0,y=0;v<=20;++v)y=v/20,h=o(t,r,y),l=o(e,n,y),c=o(r,i,y),d=o(n,s,y),f=o(h,c,y),p=o(l,d,y),u.push(f,p);return u}r.__esModule=!0,r.default=i;var a=t("earcut"),u=n(a),h=t("./buildLine"),l=n(h),c=t("../../../utils")},{"../../../utils":125,"./buildLine":61,earcut:2}],65:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.autoDetectRenderer=r.Application=r.Filter=r.SpriteMaskFilter=r.Quad=r.RenderTarget=r.ObjectRenderer=r.WebGLManager=r.Shader=r.CanvasRenderTarget=r.TextureUvs=r.VideoBaseTexture=r.BaseRenderTexture=r.RenderTexture=r.BaseTexture=r.TextureMatrix=r.Texture=r.Spritesheet=r.CanvasGraphicsRenderer=r.GraphicsRenderer=r.GraphicsData=r.Graphics=r.TextMetrics=r.TextStyle=r.Text=r.SpriteRenderer=r.CanvasTinter=r.CanvasSpriteRenderer=r.Sprite=r.TransformBase=r.TransformStatic=r.Transform=r.Container=r.DisplayObject=r.Bounds=r.glCore=r.WebGLRenderer=r.CanvasRenderer=r.ticker=r.utils=r.settings=void 0;var o=t("./const");Object.keys(o).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return o[t]}})});var s=t("./math");Object.keys(s).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return s[t]}})});var a=t("pixi-gl-core");Object.defineProperty(r,"glCore",{enumerable:!0,get:function(){return i(a).default}});var u=t("./display/Bounds");Object.defineProperty(r,"Bounds",{enumerable:!0,get:function(){return i(u).default}}) +;var h=t("./display/DisplayObject");Object.defineProperty(r,"DisplayObject",{enumerable:!0,get:function(){return i(h).default}});var l=t("./display/Container");Object.defineProperty(r,"Container",{enumerable:!0,get:function(){return i(l).default}});var c=t("./display/Transform");Object.defineProperty(r,"Transform",{enumerable:!0,get:function(){return i(c).default}});var d=t("./display/TransformStatic");Object.defineProperty(r,"TransformStatic",{enumerable:!0,get:function(){return i(d).default}});var f=t("./display/TransformBase");Object.defineProperty(r,"TransformBase",{enumerable:!0,get:function(){return i(f).default}});var p=t("./sprites/Sprite");Object.defineProperty(r,"Sprite",{enumerable:!0,get:function(){return i(p).default}});var v=t("./sprites/canvas/CanvasSpriteRenderer");Object.defineProperty(r,"CanvasSpriteRenderer",{enumerable:!0,get:function(){return i(v).default}});var y=t("./sprites/canvas/CanvasTinter");Object.defineProperty(r,"CanvasTinter",{enumerable:!0,get:function(){return i(y).default}});var g=t("./sprites/webgl/SpriteRenderer");Object.defineProperty(r,"SpriteRenderer",{enumerable:!0,get:function(){return i(g).default}});var m=t("./text/Text");Object.defineProperty(r,"Text",{enumerable:!0,get:function(){return i(m).default}});var _=t("./text/TextStyle");Object.defineProperty(r,"TextStyle",{enumerable:!0,get:function(){return i(_).default}});var b=t("./text/TextMetrics");Object.defineProperty(r,"TextMetrics",{enumerable:!0,get:function(){return i(b).default}});var x=t("./graphics/Graphics");Object.defineProperty(r,"Graphics",{enumerable:!0,get:function(){return i(x).default}});var T=t("./graphics/GraphicsData");Object.defineProperty(r,"GraphicsData",{enumerable:!0,get:function(){return i(T).default}});var w=t("./graphics/webgl/GraphicsRenderer");Object.defineProperty(r,"GraphicsRenderer",{enumerable:!0,get:function(){return i(w).default}});var E=t("./graphics/canvas/CanvasGraphicsRenderer");Object.defineProperty(r,"CanvasGraphicsRenderer",{enumerable:!0,get:function(){return i(E).default}});var S=t("./textures/Spritesheet");Object.defineProperty(r,"Spritesheet",{enumerable:!0,get:function(){return i(S).default}});var O=t("./textures/Texture");Object.defineProperty(r,"Texture",{enumerable:!0,get:function(){return i(O).default}});var M=t("./textures/TextureMatrix");Object.defineProperty(r,"TextureMatrix",{enumerable:!0,get:function(){return i(M).default}});var P=t("./textures/BaseTexture");Object.defineProperty(r,"BaseTexture",{enumerable:!0,get:function(){return i(P).default}});var C=t("./textures/RenderTexture");Object.defineProperty(r,"RenderTexture",{enumerable:!0,get:function(){return i(C).default}});var R=t("./textures/BaseRenderTexture");Object.defineProperty(r,"BaseRenderTexture",{enumerable:!0,get:function(){return i(R).default}});var A=t("./textures/VideoBaseTexture");Object.defineProperty(r,"VideoBaseTexture",{enumerable:!0,get:function(){return i(A).default}});var I=t("./textures/TextureUvs");Object.defineProperty(r,"TextureUvs",{enumerable:!0,get:function(){return i(I).default}});var D=t("./renderers/canvas/utils/CanvasRenderTarget");Object.defineProperty(r,"CanvasRenderTarget",{enumerable:!0,get:function(){return i(D).default}});var L=t("./Shader");Object.defineProperty(r,"Shader",{enumerable:!0,get:function(){return i(L).default}});var N=t("./renderers/webgl/managers/WebGLManager");Object.defineProperty(r,"WebGLManager",{enumerable:!0,get:function(){return i(N).default}});var F=t("./renderers/webgl/utils/ObjectRenderer");Object.defineProperty(r,"ObjectRenderer",{enumerable:!0,get:function(){return i(F).default}});var B=t("./renderers/webgl/utils/RenderTarget");Object.defineProperty(r,"RenderTarget",{enumerable:!0,get:function(){return i(B).default}});var k=t("./renderers/webgl/utils/Quad");Object.defineProperty(r,"Quad",{enumerable:!0,get:function(){return i(k).default}});var j=t("./renderers/webgl/filters/spriteMask/SpriteMaskFilter");Object.defineProperty(r,"SpriteMaskFilter",{enumerable:!0,get:function(){return i(j).default}});var U=t("./renderers/webgl/filters/Filter");Object.defineProperty(r,"Filter",{enumerable:!0,get:function(){return i(U).default}});var X=t("./Application");Object.defineProperty(r,"Application",{enumerable:!0,get:function(){return i(X).default}});var G=t("./autoDetectRenderer");Object.defineProperty(r,"autoDetectRenderer",{enumerable:!0,get:function(){return G.autoDetectRenderer}});var W=t("./utils"),H=n(W),Y=t("./ticker"),V=n(Y),z=t("./settings"),q=i(z),K=t("./renderers/canvas/CanvasRenderer"),Z=i(K),J=t("./renderers/webgl/WebGLRenderer"),Q=i(J);r.settings=q.default,r.utils=H,r.ticker=V,r.CanvasRenderer=Z.default,r.WebGLRenderer=Q.default},{"./Application":43,"./Shader":44,"./autoDetectRenderer":45,"./const":46,"./display/Bounds":47,"./display/Container":48,"./display/DisplayObject":49,"./display/Transform":50,"./display/TransformBase":51,"./display/TransformStatic":52,"./graphics/Graphics":53,"./graphics/GraphicsData":54,"./graphics/canvas/CanvasGraphicsRenderer":55,"./graphics/webgl/GraphicsRenderer":57,"./math":70,"./renderers/canvas/CanvasRenderer":77,"./renderers/canvas/utils/CanvasRenderTarget":79,"./renderers/webgl/WebGLRenderer":84,"./renderers/webgl/filters/Filter":86,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":89,"./renderers/webgl/managers/WebGLManager":93,"./renderers/webgl/utils/ObjectRenderer":94,"./renderers/webgl/utils/Quad":95,"./renderers/webgl/utils/RenderTarget":96,"./settings":101,"./sprites/Sprite":102,"./sprites/canvas/CanvasSpriteRenderer":103,"./sprites/canvas/CanvasTinter":104,"./sprites/webgl/SpriteRenderer":106,"./text/Text":108,"./text/TextMetrics":109,"./text/TextStyle":110,"./textures/BaseRenderTexture":111,"./textures/BaseTexture":112,"./textures/RenderTexture":113,"./textures/Spritesheet":114,"./textures/Texture":115,"./textures/TextureMatrix":116,"./textures/TextureUvs":117,"./textures/VideoBaseTexture":118,"./ticker":121,"./utils":125,"pixi-gl-core":12}],66:[function(t,e,r){"use strict";function n(t){return t<0?-1:t>0?1:0}r.__esModule=!0;var i=t("./Matrix"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],a=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],u=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],h=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],l=[],c=[];!function(){for(var t=0;t<16;t++){var e=[];c.push(e);for(var r=0;r<16;r++)for(var i=n(s[t]*s[r]+u[t]*a[r]),d=n(a[t]*s[r]+h[t]*a[r]),f=n(s[t]*u[r]+u[t]*h[r]),p=n(a[t]*u[r]+h[t]*h[r]),v=0;v<16;v++)if(s[v]===i&&a[v]===d&&u[v]===f&&h[v]===p){e.push(v);break}}for(var y=0;y<16;y++){var g=new o.default;g.set(s[y],a[y],u[y],h[y],0,0),l.push(g)}}();var d={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MIRROR_HORIZONTAL:12,uX:function(t){return s[t]},uY:function(t){return a[t]},vX:function(t){return u[t]},vY:function(t){return h[t]},inv:function(t){return 8&t?15&t:7&-t},add:function(t,e){return c[t][e]},sub:function(t,e){return c[t][d.inv(e)]},rotate180:function(t){return 4^t},isVertical:function(t){return 2==(3&t)},byDirection:function(t,e){return 2*Math.abs(t)<=Math.abs(e)?e>=0?d.S:d.N:2*Math.abs(e)<=Math.abs(t)?t>0?d.E:d.W:e>0?t>0?d.SE:d.SW:t>0?d.NE:d.NW},matrixAppendRotationInv:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=l[d.inv(e)];i.tx=r,i.ty=n,t.append(i)}};r.default=d},{"./Matrix":67}],67:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:1,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;n(this,t),this.a=e,this.b=r,this.c=i,this.d=o,this.tx=s,this.ty=a,this.array=null}return t.prototype.fromArray=function(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]},t.prototype.set=function(t,e,r,n,i,o){return this.a=t,this.b=e,this.c=r,this.d=n,this.tx=i,this.ty=o,this},t.prototype.toArray=function(t,e){this.array||(this.array=new Float32Array(9));var r=e||this.array;return t?(r[0]=this.a,r[1]=this.b,r[2]=0,r[3]=this.c,r[4]=this.d,r[5]=0,r[6]=this.tx,r[7]=this.ty,r[8]=1):(r[0]=this.a,r[1]=this.c,r[2]=this.tx,r[3]=this.b,r[4]=this.d,r[5]=this.ty,r[6]=0,r[7]=0,r[8]=1),r},t.prototype.apply=function(t,e){e=e||new s.default;var r=t.x,n=t.y;return e.x=this.a*r+this.c*n+this.tx,e.y=this.b*r+this.d*n+this.ty,e},t.prototype.applyInverse=function(t,e){e=e||new s.default;var r=1/(this.a*this.d+this.c*-this.b),n=t.x,i=t.y;return e.x=this.d*r*n+-this.c*r*i+(this.ty*this.c-this.tx*this.d)*r,e.y=this.a*r*i+-this.b*r*n+(-this.ty*this.a+this.tx*this.b)*r,e},t.prototype.translate=function(t,e){return this.tx+=t,this.ty+=e,this},t.prototype.scale=function(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this},t.prototype.rotate=function(t){var e=Math.cos(t),r=Math.sin(t),n=this.a,i=this.c,o=this.tx;return this.a=n*e-this.b*r,this.b=n*r+this.b*e,this.c=i*e-this.d*r,this.d=i*r+this.d*e,this.tx=o*e-this.ty*r,this.ty=o*r+this.ty*e,this},t.prototype.append=function(t){var e=this.a,r=this.b,n=this.c,i=this.d;return this.a=t.a*e+t.b*n,this.b=t.a*r+t.b*i,this.c=t.c*e+t.d*n,this.d=t.c*r+t.d*i,this.tx=t.tx*e+t.ty*n+this.tx,this.ty=t.tx*r+t.ty*i+this.ty,this},t.prototype.setTransform=function(t,e,r,n,i,o,s,a,u){var h=Math.sin(s),l=Math.cos(s),c=Math.cos(u),d=Math.sin(u),f=-Math.sin(a),p=Math.cos(a),v=l*i,y=h*i,g=-h*o,m=l*o;return this.a=c*v+d*g,this.b=c*y+d*m,this.c=f*v+p*g,this.d=f*y+p*m,this.tx=t+(r*v+n*g),this.ty=e+(r*y+n*m),this},t.prototype.prepend=function(t){var e=this.tx;if(1!==t.a||0!==t.b||0!==t.c||1!==t.d){var r=this.a,n=this.c;this.a=r*t.a+this.b*t.c,this.b=r*t.b+this.b*t.d,this.c=n*t.a+this.d*t.c,this.d=n*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this},t.prototype.decompose=function(t){var e=this.a,r=this.b,n=this.c,i=this.d,o=-Math.atan2(-n,i),s=Math.atan2(r,e);return Math.abs(o+s)<1e-5?(t.rotation=s,e<0&&i>=0&&(t.rotation+=t.rotation<=0?Math.PI:-Math.PI),t.skew.x=t.skew.y=0):(t.skew.x=o,t.skew.y=s),t.scale.x=Math.sqrt(e*e+r*r),t.scale.y=Math.sqrt(n*n+i*i),t.position.x=this.tx,t.position.y=this.ty,t},t.prototype.invert=function(){var t=this.a,e=this.b,r=this.c,n=this.d,i=this.tx,o=t*n-e*r;return this.a=n/o,this.b=-e/o,this.c=-r/o,this.d=t/o,this.tx=(r*this.ty-n*i)/o,this.ty=-(t*this.ty-e*i)/o,this},t.prototype.identity=function(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this},t.prototype.clone=function(){var e=new t;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e},t.prototype.copy=function(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t},i(t,null,[{key:"IDENTITY",get:function(){return new t}},{key:"TEMP_MATRIX",get:function(){return new t}}]),t}();r.default=a},{"./Point":69}],68:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this._x=i,this._y=o,this.cb=e,this.scope=r}return t.prototype.set=function(t,e){var r=t||0,n=e||(0!==e?r:0);this._x===r&&this._y===n||(this._x=r,this._y=n,this.cb.call(this.scope))},t.prototype.copy=function(t){this._x===t.x&&this._y===t.y||(this._x=t.x,this._y=t.y,this.cb.call(this.scope))},i(t,[{key:"x",get:function(){return this._x},set:function(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}},{key:"y",get:function(){return this._y},set:function(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}]),t}();r.default=o},{}],69:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;n(this,t),this.x=e,this.y=r}return t.prototype.clone=function(){return new t(this.x,this.y)},t.prototype.copy=function(t){this.set(t.x,t.y)},t.prototype.equals=function(t){return t.x===this.x&&t.y===this.y},t.prototype.set=function(t,e){this.x=t||0,this.y=e||(0!==e?this.x:0)},t}();r.default=i},{}],70:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./Point");Object.defineProperty(r,"Point",{enumerable:!0,get:function(){return n(i).default}});var o=t("./ObservablePoint");Object.defineProperty(r,"ObservablePoint",{enumerable:!0,get:function(){return n(o).default}});var s=t("./Matrix");Object.defineProperty(r,"Matrix",{enumerable:!0,get:function(){return n(s).default}});var a=t("./GroupD8");Object.defineProperty(r,"GroupD8",{enumerable:!0,get:function(){return n(a).default}});var u=t("./shapes/Circle");Object.defineProperty(r,"Circle",{enumerable:!0,get:function(){return n(u).default}});var h=t("./shapes/Ellipse");Object.defineProperty(r,"Ellipse",{enumerable:!0,get:function(){return n(h).default}});var l=t("./shapes/Polygon");Object.defineProperty(r,"Polygon",{enumerable:!0,get:function(){return n(l).default}});var c=t("./shapes/Rectangle");Object.defineProperty(r,"Rectangle",{enumerable:!0,get:function(){return n(c).default}});var d=t("./shapes/RoundedRectangle");Object.defineProperty(r,"RoundedRectangle",{enumerable:!0,get:function(){return n(d).default}})},{"./GroupD8":66,"./Matrix":67,"./ObservablePoint":68,"./Point":69,"./shapes/Circle":71,"./shapes/Ellipse":72,"./shapes/Polygon":73,"./shapes/Rectangle":74,"./shapes/RoundedRectangle":75}],71:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("./Rectangle"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=t("../../const"),a=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;n(this,t),this.x=e,this.y=r,this.radius=i,this.type=s.SHAPES.CIRC}return t.prototype.clone=function(){return new t(this.x,this.y,this.radius)},t.prototype.contains=function(t,e){if(this.radius<=0)return!1;var r=this.radius*this.radius,n=this.x-t,i=this.y-e;return n*=n,i*=i,n+i<=r},t.prototype.getBounds=function(){return new o.default(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)},t}();r.default=a},{"../../const":46,"./Rectangle":74}],72:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("./Rectangle"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=t("../../const"),a=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this.x=e,this.y=r,this.width=i,this.height=o,this.type=s.SHAPES.ELIP}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;var r=(t-this.x)/this.width,n=(e-this.y)/this.height;return r*=r,n*=n,r+n<=1},t.prototype.getBounds=function(){return new o.default(this.x-this.width,this.y-this.height,this.width,this.height)},t}();r.default=a},{"../../const":46,"./Rectangle":74}],73:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../Point"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=t("../../const"),a=function(){function t(){for(var e=arguments.length,r=Array(e),i=0;ie!=h>e&&t<(e-a)/(h-a)*(u-s)+s&&(r=!r)}return r},t}();r.default=a},{"../../const":46,"../Point":69}],74:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this.x=Number(e),this.y=Number(r),this.width=Number(i),this.height=Number(s),this.type=o.SHAPES.RECT}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this},t.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t=this.y&&et.x+t.width&&(this.width=t.width-this.x,this.width<0&&(this.width=0)),this.y+this.height>t.y+t.height&&(this.height=t.height-this.y,this.height<0&&(this.height=0))},t.prototype.enlarge=function(t){var e=Math.min(this.x,t.x),r=Math.max(this.x+this.width,t.x+t.width),n=Math.min(this.y,t.y),i=Math.max(this.y+this.height,t.y+t.height);this.x=e,this.width=r-e,this.y=n,this.height=i-n},i(t,[{key:"left",get:function(){return this.x}},{key:"right",get:function(){return this.x+this.width}},{key:"top",get:function(){return this.y}},{key:"bottom",get:function(){return this.y+this.height}}],[{key:"EMPTY",get:function(){return new t(0,0,0,0)}}]),t}();r.default=s},{"../../const":46}],75:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:20;n(this,t),this.x=e,this.y=r,this.width=o,this.height=s,this.radius=a,this.type=i.SHAPES.RREC}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height,this.radius)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){if(e>=this.y+this.radius&&e<=this.y+this.height-this.radius||t>=this.x+this.radius&&t<=this.x+this.width-this.radius)return!0;var r=t-(this.x+this.radius),n=e-(this.y+this.radius),i=this.radius*this.radius;if(r*r+n*n<=i)return!0;if((r=t-(this.x+this.width-this.radius))*r+n*n<=i)return!0;if(n=e-(this.y+this.height-this.radius),r*r+n*n<=i)return!0;if((r=t-(this.x+this.radius))*r+n*n<=i)return!0}return!1},t}();r.default=o},{"../../const":46}],76:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rE?E:w,e.moveTo(_,b+w),e.lineTo(_,b+T-w),e.quadraticCurveTo(_,b+T,_+w,b+T),e.lineTo(_+x-w,b+T),e.quadraticCurveTo(_+x,b+T,_+x,b+T-w),e.lineTo(_+x,b+w),e.quadraticCurveTo(_+x,b,_+x-w,b),e.lineTo(_+w,b),e.quadraticCurveTo(_,b,_,b+w),e.closePath()}}}},t.prototype.popMask=function(t){t.context.restore(),t.invalidateBlendMode()},t.prototype.destroy=function(){},t}();r.default=o},{"../../../const":46}],79:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:[];return(0,s.default)()?(t[i.BLEND_MODES.NORMAL]="source-over",t[i.BLEND_MODES.ADD]="lighter",t[i.BLEND_MODES.MULTIPLY]="multiply",t[i.BLEND_MODES.SCREEN]="screen", +t[i.BLEND_MODES.OVERLAY]="overlay",t[i.BLEND_MODES.DARKEN]="darken",t[i.BLEND_MODES.LIGHTEN]="lighten",t[i.BLEND_MODES.COLOR_DODGE]="color-dodge",t[i.BLEND_MODES.COLOR_BURN]="color-burn",t[i.BLEND_MODES.HARD_LIGHT]="hard-light",t[i.BLEND_MODES.SOFT_LIGHT]="soft-light",t[i.BLEND_MODES.DIFFERENCE]="difference",t[i.BLEND_MODES.EXCLUSION]="exclusion",t[i.BLEND_MODES.HUE]="hue",t[i.BLEND_MODES.SATURATION]="saturate",t[i.BLEND_MODES.COLOR]="color",t[i.BLEND_MODES.LUMINOSITY]="luminosity"):(t[i.BLEND_MODES.NORMAL]="source-over",t[i.BLEND_MODES.ADD]="lighter",t[i.BLEND_MODES.MULTIPLY]="source-over",t[i.BLEND_MODES.SCREEN]="source-over",t[i.BLEND_MODES.OVERLAY]="source-over",t[i.BLEND_MODES.DARKEN]="source-over",t[i.BLEND_MODES.LIGHTEN]="source-over",t[i.BLEND_MODES.COLOR_DODGE]="source-over",t[i.BLEND_MODES.COLOR_BURN]="source-over",t[i.BLEND_MODES.HARD_LIGHT]="source-over",t[i.BLEND_MODES.SOFT_LIGHT]="source-over",t[i.BLEND_MODES.DIFFERENCE]="source-over",t[i.BLEND_MODES.EXCLUSION]="source-over",t[i.BLEND_MODES.HUE]="source-over",t[i.BLEND_MODES.SATURATION]="source-over",t[i.BLEND_MODES.COLOR]="source-over",t[i.BLEND_MODES.LUMINOSITY]="source-over"),t[i.BLEND_MODES.NORMAL_NPM]=t[i.BLEND_MODES.NORMAL],t[i.BLEND_MODES.ADD_NPM]=t[i.BLEND_MODES.ADD],t[i.BLEND_MODES.SCREEN_NPM]=t[i.BLEND_MODES.SCREEN],t}r.__esModule=!0,r.default=n;var i=t("../../../const"),o=t("./canUseNewCanvasBlendModes"),s=function(t){return t&&t.__esModule?t:{default:t}}(o)},{"../../../const":46,"./canUseNewCanvasBlendModes":80}],82:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=t("../../settings"),s=function(t){return t&&t.__esModule?t:{default:t}}(o),a=function(){function t(e){n(this,t),this.renderer=e,this.count=0,this.checkCount=0,this.maxIdle=s.default.GC_MAX_IDLE,this.checkCountMax=s.default.GC_MAX_CHECK_COUNT,this.mode=s.default.GC_MODE}return t.prototype.update=function(){this.count++,this.mode!==i.GC_MODES.MANUAL&&++this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run())},t.prototype.run=function(){for(var t=this.renderer.textureManager,e=t._managedTextures,r=!1,n=0;nthis.maxIdle&&(t.destroyTexture(i,!0),e[n]=null,r=!0)}if(r){for(var o=0,s=0;s=0;r--)this.unload(t.children[r])},t}();r.default=a},{"../../const":46,"../../settings":101}],83:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("pixi-gl-core"),o=t("../../const"),s=t("./utils/RenderTarget"),a=function(t){return t&&t.__esModule?t:{default:t}}(s),u=t("../../utils"),h=function(){function t(e){n(this,t),this.renderer=e,this.gl=e.gl,this._managedTextures=[]}return t.prototype.bindTexture=function(){},t.prototype.getTexture=function(){},t.prototype.updateTexture=function(t,e){var r=this.gl,n=!!t._glRenderTargets;if(!t.hasLoaded)return null;var s=this.renderer.boundTextures;if(void 0===e){e=0;for(var u=0;u 0.5)"," {"," color = vec4(1.0, 0.0, 0.0, 1.0);"," }"," else"," {"," color = vec4(0.0, 1.0, 0.0, 1.0);"," }"," gl_FragColor = mix(sample, masky, 0.5);"," gl_FragColor *= sample.a;","}"].join("\n")}}]),t}();r.default=f},{"../../../const":46,"../../../settings":101,"../../../utils":125,"./extractUniformsFromSrc":87}],87:[function(t,e,r){"use strict";function n(t,e,r){var n=i(t),o=i(e);return Object.assign(n,o)}function i(t){for(var e=new RegExp("^(projectionMatrix|uSampler|filterArea|filterClamp)$"),r={},n=void 0,i=t.replace(/\s+/g," ").split(/\s*;\s*/),o=0;o-1){var u=s.split(" "),h=u[1],l=u[2],c=1;l.indexOf("[")>-1&&(n=l.split(/\[|]/),l=n[0],c*=Number(n[1])),l.match(e)||(r[l]={value:a(h,c),name:l,type:h})}}return r}r.__esModule=!0,r.default=n;var o=t("pixi-gl-core"),s=function(t){return t&&t.__esModule?t:{default:t}}(o),a=s.default.shader.defaultValue},{"pixi-gl-core":12}],88:[function(t,e,r){"use strict";function n(t,e,r){var n=t.identity();return n.translate(e.x/r.width,e.y/r.height),n.scale(r.width,r.height),n}function i(t,e,r){var n=t.identity();n.translate(e.x/r.width,e.y/r.height);var i=r.width/e.width,o=r.height/e.height;return n.scale(i,o),n}function o(t,e,r,n){var i=n._texture.orig,o=t.set(r.width,0,0,r.height,e.x,e.y),a=n.worldTransform.copy(s.Matrix.TEMP_MATRIX);return a.invert(),o.prepend(a),o.scale(1/i.width,1/i.height),o.translate(n.anchor.x,n.anchor.y),o}r.__esModule=!0,r.calculateScreenSpaceMatrix=n,r.calculateNormalizedScreenSpaceMatrix=i,r.calculateSpriteMatrix=o;var s=t("../../../math")},{"../../../math":70}],89:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../Filter"),u=n(a),h=t("../../../../math"),l=(t("path"),t("../../../../textures/TextureMatrix")),c=n(l),d=function(t){function e(r){i(this,e);var n=new h.Matrix,s=o(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n","varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n"));return r.renderable=!1,s.maskSprite=r,s.maskMatrix=n,s}return s(e,t),e.prototype.apply=function(t,e,r){var n=this.maskSprite,i=this.maskSprite.texture;i.valid&&(i.transform||(i.transform=new c.default(i,0)),i.transform.update(),this.uniforms.mask=i,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,n).prepend(i.transform.mapCoord),this.uniforms.alpha=n.worldAlpha,this.uniforms.maskClamp=i.transform.uClampFrame,t.applyFilter(this,e,r))},e}(u.default);r.default=d},{"../../../../math":70,"../../../../textures/TextureMatrix":116,"../Filter":86,path:23}],90:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var a=t("./WebGLManager"),u=n(a),h=t("../utils/RenderTarget"),l=n(h),c=t("../utils/Quad"),d=n(c),f=t("../../../math"),p=t("../../../Shader"),v=n(p),y=t("../filters/filterTransforms"),g=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(y),m=t("bit-twiddle"),_=n(m),b=function t(){s(this,t),this.renderTarget=null,this.sourceFrame=new f.Rectangle,this.destinationFrame=new f.Rectangle,this.filters=[],this.target=null,this.resolution=1},x=function(t){function e(r){s(this,e);var n=i(this,t.call(this,r));return n.gl=n.renderer.gl,n.quad=new d.default(n.gl,r.state.attribState),n.shaderCache={},n.pool={},n.filterData=null,n.managedFilters=[],n}return o(e,t),e.prototype.pushFilter=function(t,e){var r=this.renderer,n=this.filterData;if(!n){n=this.renderer._activeRenderTarget.filterStack;var i=new b;i.sourceFrame=i.destinationFrame=this.renderer._activeRenderTarget.size,i.renderTarget=r._activeRenderTarget,this.renderer._activeRenderTarget.filterData=n={index:0,stack:[i]},this.filterData=n}var o=n.stack[++n.index];o||(o=n.stack[n.index]=new b);var s=e[0].resolution,a=0|e[0].padding,u=t.filterArea||t.getBounds(!0),h=o.sourceFrame,l=o.destinationFrame;h.x=(u.x*s|0)/s,h.y=(u.y*s|0)/s,h.width=(u.width*s|0)/s,h.height=(u.height*s|0)/s,n.stack[0].renderTarget.transform||e[0].autoFit&&h.fit(n.stack[0].destinationFrame),h.pad(a),l.width=h.width,l.height=h.height;var c=this.getPotRenderTarget(r.gl,h.width,h.height,s);o.target=t,o.filters=e,o.resolution=s,o.renderTarget=c,c.setFrame(l,h),r.bindRenderTarget(c),c.clear()},e.prototype.popFilter=function(){var t=this.filterData,e=t.stack[t.index-1],r=t.stack[t.index];this.quad.map(r.renderTarget.size,r.sourceFrame).upload();var n=r.filters;if(1===n.length)n[0].apply(this,r.renderTarget,e.renderTarget,!1,r),this.freePotRenderTarget(r.renderTarget);else{var i=r.renderTarget,o=this.getPotRenderTarget(this.renderer.gl,r.sourceFrame.width,r.sourceFrame.height,r.resolution);o.setFrame(r.destinationFrame,r.sourceFrame),o.clear();var s=0;for(s=0;s0&&void 0!==arguments[0]&&arguments[0],e=this.renderer,r=this.managedFilters,n=0;n0&&(e+="\nelse "),r1&&void 0!==arguments[1]?arguments[1]:[];return e[i.BLEND_MODES.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.ADD]=[t.ONE,t.DST_ALPHA],e[i.BLEND_MODES.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SCREEN]=[t.ONE,t.ONE_MINUS_SRC_COLOR],e[i.BLEND_MODES.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.NORMAL_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.ADD_NPM]=[t.SRC_ALPHA,t.DST_ALPHA,t.ONE,t.DST_ALPHA],e[i.BLEND_MODES.SCREEN_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_COLOR,t.ONE,t.ONE_MINUS_SRC_COLOR],e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":46}],99:[function(t,e,r){"use strict";function n(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e[i.DRAW_MODES.POINTS]=t.POINTS,e[i.DRAW_MODES.LINES]=t.LINES,e[i.DRAW_MODES.LINE_LOOP]=t.LINE_LOOP,e[i.DRAW_MODES.LINE_STRIP]=t.LINE_STRIP,e[i.DRAW_MODES.TRIANGLES]=t.TRIANGLES,e[i.DRAW_MODES.TRIANGLE_STRIP]=t.TRIANGLE_STRIP,e[i.DRAW_MODES.TRIANGLE_FAN]=t.TRIANGLE_FAN,e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":46}],100:[function(t,e,r){"use strict";function n(t){t.getContextAttributes().stencil||console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly")}r.__esModule=!0,r.default=n},{}],101:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./utils/maxRecommendedTextures"),o=n(i),s=t("./utils/canUploadSameBuffer"),a=n(s);r.default={TARGET_FPMS:.06,MIPMAP_TEXTURES:!0,RESOLUTION:1,FILTER_RESOLUTION:1,SPRITE_MAX_TEXTURES:(0,o.default)(32),SPRITE_BATCH_SIZE:4096,RETINA_PREFIX:/@([0-9\.]+)x/,RENDER_OPTIONS:{view:null,antialias:!1,forceFXAA:!1,autoResize:!1,transparent:!1,backgroundColor:0,clearBeforeRender:!0,preserveDrawingBuffer:!1,roundPixels:!1,width:800,height:600,legacy:!1},TRANSFORM_MODE:0,GC_MODE:0,GC_MAX_IDLE:3600,GC_MAX_CHECK_COUNT:600,WRAP_MODE:0,SCALE_MODE:0,PRECISION_VERTEX:"highp",PRECISION_FRAGMENT:"mediump",CAN_UPLOAD_SAME_BUFFER:(0,a.default)()}},{"./utils/canUploadSameBuffer":122,"./utils/maxRecommendedTextures":127}],102:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r=n&&v.x=i&&v.y>16)+(65280&t)+((255&t)<<16)}},{key:"texture",get:function(){return this._texture},set:function(t){this._texture!==t&&(this._texture=t,this.cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,t&&(t.baseTexture.hasLoaded?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}]),e}(p.default);r.default=y},{"../const":46,"../display/Container":48,"../math":70,"../textures/Texture":115,"../utils":125}],103:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../renderers/canvas/CanvasRenderer"),s=n(o),a=t("../../const"),u=t("../../math"),h=t("./CanvasTinter"),l=n(h),c=new u.Matrix,d=function(){function t(e){i(this,t),this.renderer=e}return t.prototype.render=function(t){var e=t._texture,r=this.renderer,n=e._frame.width,i=e._frame.height,o=t.transform.worldTransform,s=0,h=0;if(!(e.orig.width<=0||e.orig.height<=0)&&e.baseTexture.source&&(r.setBlendMode(t.blendMode),e.valid)){r.context.globalAlpha=t.worldAlpha;var d=e.baseTexture.scaleMode===a.SCALE_MODES.LINEAR;r.smoothProperty&&r.context[r.smoothProperty]!==d&&(r.context[r.smoothProperty]=d),e.trim?(s=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,h=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(s=(.5-t.anchor.x)*e.orig.width,h=(.5-t.anchor.y)*e.orig.height),e.rotate&&(o.copy(c),o=c,u.GroupD8.matrixAppendRotationInv(o,e.rotate,s,h),s=0,h=0),s-=n/2,h-=i/2,r.roundPixels?(r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution|0,o.ty*r.resolution|0),s|=0,h|=0):r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution,o.ty*r.resolution);var f=e.baseTexture.resolution;16777215!==t.tint?(t.cachedTint===t.tint&&t.tintedTexture.tintId===t._texture._updateID||(t.cachedTint=t.tint,t.tintedTexture=l.default.getTintedTexture(t,t.tint)),r.context.drawImage(t.tintedTexture,0,0,n*f,i*f,s*r.resolution,h*r.resolution,n*r.resolution,i*r.resolution)):r.context.drawImage(e.baseTexture.source,e._frame.x*f,e._frame.y*f,n*f,i*f,s*r.resolution,h*r.resolution,n*r.resolution,i*r.resolution)}},t.prototype.destroy=function(){this.renderer=null},t}();r.default=d,s.default.registerPlugin("sprite",d)},{"../../const":46,"../../math":70,"../../renderers/canvas/CanvasRenderer":77,"./CanvasTinter":104}],104:[function(t,e,r){"use strict";r.__esModule=!0;var n=t("../../utils"),i=t("../../renderers/canvas/utils/canUseNewCanvasBlendModes"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s={getTintedTexture:function(t,e){var r=t._texture;e=s.roundColor(e);var n="#"+("00000"+(0|e).toString(16)).substr(-6);r.tintCache=r.tintCache||{};var i=r.tintCache[n],o=void 0;if(i){if(i.tintId===r._updateID)return r.tintCache[n];o=r.tintCache[n]}else o=s.canvas||document.createElement("canvas");if(s.tintMethod(r,e,o),o.tintId=r._updateID,s.convertTintToImage){var a=new Image;a.src=o.toDataURL(),r.tintCache[n]=a}else r.tintCache[n]=o,s.canvas=null;return o},tintWithMultiply:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.save(),n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="multiply",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.restore()},tintWithOverlay:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.save(),n.globalCompositeOperation="copy",n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.restore()},tintWithPerPixel:function(t,e,r){var i=r.getContext("2d"),o=t._frame.clone(),s=t.baseTexture.resolution;o.x*=s,o.y*=s,o.width*=s,o.height*=s,r.width=Math.ceil(o.width),r.height=Math.ceil(o.height),i.save(),i.globalCompositeOperation="copy",i.drawImage(t.baseTexture.source,o.x,o.y,o.width,o.height,0,0,o.width,o.height),i.restore();for(var a=(0,n.hex2rgb)(e),u=a[0],h=a[1],l=a[2],c=i.getImageData(0,0,o.width,o.height),d=c.data,f=0;f=this.size&&this.flush(),t._texture._uvs&&(this.sprites[this.currentIndex++]=t)},e.prototype.flush=function(){if(0!==this.currentIndex){var t=this.renderer.gl,e=this.MAX_TEXTURES,r=S.default.nextPow2(this.currentIndex),n=S.default.log2(r),i=this.buffers[n],o=this.sprites,s=this.groups,a=i.float32View,u=i.uint32View,h=this.boundTextures,l=this.renderer.boundTextures,c=this.renderer.textureGC.count,d=0,f=void 0,p=void 0,v=1,y=0,g=s[0],m=void 0,_=void 0,T=x.premultiplyBlendMode[o[0]._texture.baseTexture.premultipliedAlpha?1:0][o[0].blendMode];g.textureCount=0,g.start=0,g.blend=T,O++;var E=void 0;for(E=0;E0&&(e+="\nelse "),r0&&(r.shadowColor=e.dropShadowColor);for(var f=Math.cos(e.dropShadowAngle)*e.dropShadowDistance,p=Math.sin(e.dropShadowAngle)*e.dropShadowDistance,v=0;v3&&void 0!==arguments[3]&&arguments[3],i=this._style,o=i.letterSpacing;if(0===o)return void(n?this.context.strokeText(t,e,r):this.context.fillText(t,e,r));for(var s=String.prototype.split.call(t,""),a=e,u=0,h="";u3&&void 0!==arguments[3]?arguments[3]:t._canvas;n=n||r.wordWrap;var o=r.toFontString(),s=t.measureFont(o),a=i.getContext("2d");a.font=o;for(var u=n?t.wordWrap(e,r,i):e,h=u.split(/(?:\r\n|\r|\n)/),l=new Array(h.length),c=0,d=0;d2&&void 0!==arguments[2]?arguments[2]:t._canvas,i=n.getContext("2d"),o="",s=e.charAt(0),a=e.split("\n"),u=r.wordWrapWidth,h={},l=0;lu)for(var v=d[f].split(""),y=0;yc?(o+="\n"+g,c=u-m):(0===y&&(f>0||" "===s)&&(o+=" "),o+=g,c-=m)}else{var _=p+i.measureText(" ").width;0===f||_>c?(f>0&&(o+="\n"),o+=d[f],c=u-p):(c-=_,o+=" "+d[f])}}ls;--c){for(var v=0;v=0;r--){var n=e[r].trim();/([\"\'])[^\'\"]+\1/.test(n)||(n='"'+n+'"'),e[r]=n}return this.fontStyle+" "+this.fontVariant+" "+this.fontWeight+" "+t+" "+e.join(",")},u(t,[{key:"align",get:function(){return this._align},set:function(t){this._align!==t&&(this._align=t,this.styleID++)}},{key:"breakWords",get:function(){return this._breakWords},set:function(t){this._breakWords!==t&&(this._breakWords=t,this.styleID++)}},{key:"dropShadow",get:function(){return this._dropShadow},set:function(t){this._dropShadow!==t&&(this._dropShadow=t,this.styleID++)}},{key:"dropShadowAlpha",get:function(){return this._dropShadowAlpha},set:function(t){this._dropShadowAlpha!==t&&(this._dropShadowAlpha=t,this.styleID++)}},{key:"dropShadowAngle",get:function(){return this._dropShadowAngle},set:function(t){this._dropShadowAngle!==t&&(this._dropShadowAngle=t,this.styleID++)}},{key:"dropShadowBlur",get:function(){return this._dropShadowBlur},set:function(t){this._dropShadowBlur!==t&&(this._dropShadowBlur=t,this.styleID++)}},{key:"dropShadowColor",get:function(){return this._dropShadowColor},set:function(t){var e=o(t);this._dropShadowColor!==e&&(this._dropShadowColor=e,this.styleID++)}},{key:"dropShadowDistance",get:function(){return this._dropShadowDistance},set:function(t){this._dropShadowDistance!==t&&(this._dropShadowDistance=t,this.styleID++)}},{key:"fill",get:function(){return this._fill},set:function(t){var e=o(t);this._fill!==e&&(this._fill=e,this.styleID++)}},{key:"fillGradientType",get:function(){return this._fillGradientType},set:function(t){this._fillGradientType!==t&&(this._fillGradientType=t,this.styleID++)}},{key:"fillGradientStops",get:function(){return this._fillGradientStops},set:function(t){s(this._fillGradientStops,t)||(this._fillGradientStops=t,this.styleID++)}},{key:"fontFamily",get:function(){return this._fontFamily},set:function(t){this.fontFamily!==t&&(this._fontFamily=t,this.styleID++)}},{key:"fontSize",get:function(){return this._fontSize},set:function(t){this._fontSize!==t&&(this._fontSize=t,this.styleID++)}},{key:"fontStyle",get:function(){return this._fontStyle},set:function(t){this._fontStyle!==t&&(this._fontStyle=t,this.styleID++)}},{key:"fontVariant",get:function(){return this._fontVariant},set:function(t){this._fontVariant!==t&&(this._fontVariant=t,this.styleID++)}},{key:"fontWeight",get:function(){return this._fontWeight},set:function(t){this._fontWeight!==t&&(this._fontWeight=t,this.styleID++)}},{key:"letterSpacing",get:function(){return this._letterSpacing},set:function(t){this._letterSpacing!==t&&(this._letterSpacing=t,this.styleID++)}},{key:"lineHeight",get:function(){return this._lineHeight},set:function(t){this._lineHeight!==t&&(this._lineHeight=t,this.styleID++)}},{key:"leading",get:function(){return this._leading},set:function(t){this._leading!==t&&(this._leading=t,this.styleID++)}},{key:"lineJoin",get:function(){return this._lineJoin},set:function(t){this._lineJoin!==t&&(this._lineJoin=t,this.styleID++)}},{key:"miterLimit",get:function(){return this._miterLimit},set:function(t){this._miterLimit!==t&&(this._miterLimit=t,this.styleID++)}},{key:"padding",get:function(){return this._padding},set:function(t){this._padding!==t&&(this._padding=t,this.styleID++)}},{key:"stroke",get:function(){return this._stroke},set:function(t){var e=o(t);this._stroke!==e&&(this._stroke=e,this.styleID++)}},{key:"strokeThickness",get:function(){return this._strokeThickness},set:function(t){this._strokeThickness!==t&&(this._strokeThickness=t,this.styleID++)}},{key:"textBaseline",get:function(){return this._textBaseline},set:function(t){this._textBaseline!==t&&(this._textBaseline=t,this.styleID++)}},{key:"trim",get:function(){return this._trim},set:function(t){this._trim!==t&&(this._trim=t,this.styleID++)}},{key:"wordWrap",get:function(){return this._wordWrap},set:function(t){this._wordWrap!==t&&(this._wordWrap=t,this.styleID++)}},{key:"wordWrapWidth",get:function(){return this._wordWrapWidth},set:function(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this.styleID++)}}]),t}();r.default=d},{"../const":46,"../utils":125}],111:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("./BaseTexture"),u=n(a),h=t("../settings"),l=n(h),c=function(t){function e(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,s=arguments[2],a=arguments[3];i(this,e);var u=o(this,t.call(this,null,s));return u.resolution=a||l.default.RESOLUTION,u.width=Math.ceil(r),u.height=Math.ceil(n),u.realWidth=u.width*u.resolution,u.realHeight=u.height*u.resolution,u.scaleMode=void 0!==s?s:l.default.SCALE_MODE,u.hasLoaded=!0,u._glRenderTargets={},u._canvasRenderTarget=null,u.valid=!1,u}return s(e,t),e.prototype.resize=function(t,e){t=Math.ceil(t),e=Math.ceil(e),t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.realWidth=this.width*this.resolution,this.realHeight=this.height*this.resolution,this.valid&&this.emit("update",this))},e.prototype.destroy=function(){t.prototype.destroy.call(this,!0),this.renderer=null},e}(u.default);r.default=c},{"../settings":101,"./BaseTexture":112}],112:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../utils"),u=t("../settings"),h=n(u),l=t("eventemitter3"),c=n(l),d=t("../utils/determineCrossOrigin"),f=n(d),p=t("bit-twiddle"),v=n(p),y=function(t){function e(r,n,s){i(this,e);var u=o(this,t.call(this));return u.uid=(0,a.uid)(),u.touched=0,u.resolution=s||h.default.RESOLUTION,u.width=100,u.height=100,u.realWidth=100,u.realHeight=100,u.scaleMode=void 0!==n?n:h.default.SCALE_MODE,u.hasLoaded=!1,u.isLoading=!1,u.source=null,u.origSource=null,u.imageType=null,u.sourceScale=1,u.premultipliedAlpha=!0,u.imageUrl=null,u.isPowerOfTwo=!1,u.mipmap=h.default.MIPMAP_TEXTURES,u.wrapMode=h.default.WRAP_MODE,u._glTextures={},u._enabled=0,u._virtalBoundId=-1,u._destroyed=!1,u.textureCacheIds=[],r&&u.loadSource(r),u}return s(e,t),e.prototype.update=function(){"svg"!==this.imageType&&(this.realWidth=this.source.naturalWidth||this.source.videoWidth||this.source.width,this.realHeight=this.source.naturalHeight||this.source.videoHeight||this.source.height,this._updateDimensions()),this.emit("update",this)},e.prototype._updateDimensions=function(){this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=v.default.isPow2(this.realWidth)&&v.default.isPow2(this.realHeight)},e.prototype.loadSource=function(t){var e=this.isLoading;this.hasLoaded=!1,this.isLoading=!1,e&&this.source&&(this.source.onload=null,this.source.onerror=null);var r=!this.source;if(this.source=t,(t.src&&t.complete||t.getContext)&&t.width&&t.height)this._updateImageType(),"svg"===this.imageType?this._loadSvgSource():this._sourceLoaded(),r&&this.emit("loaded",this);else if(!t.getContext){this.isLoading=!0;var n=this;if(t.onload=function(){if(n._updateImageType(),t.onload=null,t.onerror=null,n.isLoading){if(n.isLoading=!1,n._sourceLoaded(),"svg"===n.imageType)return void n._loadSvgSource();n.emit("loaded",n)}},t.onerror=function(){t.onload=null,t.onerror=null,n.isLoading&&(n.isLoading=!1,n.emit("error",n))},t.complete&&t.src){if(t.onload=null,t.onerror=null,"svg"===n.imageType)return void n._loadSvgSource();this.isLoading=!1,t.width&&t.height?(this._sourceLoaded(),e&&this.emit("loaded",this)):e&&this.emit("error",this)}}},e.prototype._updateImageType=function(){if(this.imageUrl){var t=(0,a.decomposeDataUri)(this.imageUrl),e=void 0;if(t&&"image"===t.mediaType){var r=t.subType.split("+")[0];if(!(e=(0,a.getUrlFileExtension)("."+r)))throw new Error("Invalid image type in data URI.")}else(e=(0,a.getUrlFileExtension)(this.imageUrl))||(e="png");this.imageType=e}},e.prototype._loadSvgSource=function(){if("svg"===this.imageType){var t=(0,a.decomposeDataUri)(this.imageUrl);t?this._loadSvgSourceUsingDataUri(t):this._loadSvgSourceUsingXhr()}},e.prototype._loadSvgSourceUsingDataUri=function(t){var e=void 0;if("base64"===t.encoding){if(!atob)throw new Error("Your browser doesn't support base64 conversions.");e=atob(t.data)}else e=t.data;this._loadSvgSourceUsingString(e)},e.prototype._loadSvgSourceUsingXhr=function(){var t=this,e=new XMLHttpRequest;e.onload=function(){if(e.readyState!==e.DONE||200!==e.status)throw new Error("Failed to load SVG using XHR.");t._loadSvgSourceUsingString(e.response)},e.onerror=function(){return t.emit("error",t)},e.open("GET",this.imageUrl,!0),e.send()},e.prototype._loadSvgSourceUsingString=function(t){var r=(0,a.getSvgSize)(t),n=r.width,i=r.height;if(!n||!i)throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them.");this.realWidth=Math.round(n*this.sourceScale),this.realHeight=Math.round(i*this.sourceScale),this._updateDimensions();var o=document.createElement("canvas");o.width=this.realWidth,o.height=this.realHeight,o._pixiId="canvas_"+(0,a.uid)(),o.getContext("2d").drawImage(this.source,0,0,n,i,0,0,this.realWidth,this.realHeight),this.origSource=this.source,this.source=o,e.addToCache(this,o._pixiId),this.isLoading=!1,this._sourceLoaded(),this.emit("loaded",this)},e.prototype._sourceLoaded=function(){this.hasLoaded=!0,this.update()},e.prototype.destroy=function(){this.imageUrl&&(delete a.TextureCache[this.imageUrl],this.imageUrl=null,navigator.isCocoonJS||(this.source.src="")),this.source=null,this.dispose(),e.removeFromCache(this),this.textureCacheIds=null,this._destroyed=!0},e.prototype.dispose=function(){this.emit("dispose",this)},e.prototype.updateSourceImage=function(t){this.source.src=t,this.loadSource(this.source)},e.fromImage=function(t,r,n,i){var o=a.BaseTextureCache[t];if(!o){var s=new Image;void 0===r&&0!==t.indexOf("data:")?s.crossOrigin=(0,f.default)(t):r&&(s.crossOrigin="string"==typeof r?r:"anonymous"),o=new e(s,n),o.imageUrl=t,i&&(o.sourceScale=i),o.resolution=(0,a.getResolutionOfUrl)(t),s.src=t,e.addToCache(o,t)}return o},e.fromCanvas=function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"canvas";t._pixiId||(t._pixiId=n+"_"+(0,a.uid)());var i=a.BaseTextureCache[t._pixiId];return i||(i=new e(t,r),e.addToCache(i,t._pixiId)),i},e.from=function(t,r,n){if("string"==typeof t)return e.fromImage(t,void 0,r,n);if(t instanceof HTMLImageElement){var i=t.src,o=a.BaseTextureCache[i];return o||(o=new e(t,r),o.imageUrl=i,n&&(o.sourceScale=n),o.resolution=(0,a.getResolutionOfUrl)(i),e.addToCache(o,i)),o}return t instanceof HTMLCanvasElement?e.fromCanvas(t,r):t},e.addToCache=function(t,e){e&&(-1===t.textureCacheIds.indexOf(e)&&t.textureCacheIds.push(e),a.BaseTextureCache[e]=t)},e.removeFromCache=function(t){if("string"==typeof t){var e=a.BaseTextureCache[t];if(e){var r=e.textureCacheIds.indexOf(t);return r>-1&&e.textureCacheIds.splice(r,1),delete a.BaseTextureCache[t],e}}else if(t&&t.textureCacheIds){for(var n=0;n0&&e>0,this._frame.width=this.orig.width=t,this._frame.height=this.orig.height=e,r||this.baseTexture.resize(t,e),this._updateUvs()},e.create=function(t,r,n,i){return new e(new u.default(t,r,n,i))},e}(l.default);r.default=c},{"./BaseRenderTexture":111,"./Texture":115}],114:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:null;n(this,t),this.baseTexture=e,this.textures={},this.data=r,this.resolution=this._updateResolution(i||this.baseTexture.imageUrl),this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}return i(t,null,[{key:"BATCH_SIZE",get:function(){return 1e3}}]),t.prototype._updateResolution=function(t){var e=this.data.meta.scale,r=(0,s.getResolutionOfUrl)(t,null);return null===r&&(r=void 0!==e?parseFloat(e):1),1!==r&&(this.baseTexture.resolution=r,this.baseTexture.update()),r},t.prototype.parse=function(e){this._batchIndex=0,this._callback=e,this._frameKeys.length<=t.BATCH_SIZE?(this._processFrames(0),this._parseComplete()):this._nextBatch()},t.prototype._processFrames=function(e){for(var r=e,n=t.BATCH_SIZE,i=this.baseTexture.sourceScale;r-e0&&void 0!==arguments[0]&&arguments[0];for(var e in this.textures)this.textures[e].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,t&&this.baseTexture.destroy(),this.baseTexture=null},t}();r.default=a},{"../":65,"../utils":125}],115:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t){t.destroy=function(){},t.on=function(){},t.once=function(){},t.emit=function(){}}r.__esModule=!0;var u=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:"canvas";return new e(l.default.fromCanvas(t,r,n))},e.fromVideo=function(t,r){return"string"==typeof t?e.fromVideoUrl(t,r):new e(d.default.fromVideo(t,r))},e.fromVideoUrl=function(t,r){return new e(d.default.fromUrl(t,r))},e.from=function(t){if("string"==typeof t){var r=m.TextureCache[t];if(!r){return null!==t.match(/\.(mp4|webm|ogg|h264|avi|mov)$/)?e.fromVideoUrl(t):e.fromImage(t)}return r}return t instanceof HTMLImageElement?new e(l.default.from(t)):t instanceof HTMLCanvasElement?e.fromCanvas(t,b.default.SCALE_MODE,"HTMLCanvasElement"):t instanceof HTMLVideoElement?e.fromVideo(t):t instanceof l.default?new e(t):t},e.fromLoader=function(t,r,n){var i=new l.default(t,void 0,(0, +m.getResolutionOfUrl)(r)),o=new e(i);return i.imageUrl=r,n||(n=r),l.default.addToCache(o.baseTexture,n),e.addToCache(o,n),n!==r&&(l.default.addToCache(o.baseTexture,r),e.addToCache(o,r)),o},e.addToCache=function(t,e){e&&(-1===t.textureCacheIds.indexOf(e)&&t.textureCacheIds.push(e),m.TextureCache[e]=t)},e.removeFromCache=function(t){if("string"==typeof t){var e=m.TextureCache[t];if(e){var r=e.textureCacheIds.indexOf(t);return r>-1&&e.textureCacheIds.splice(r,1),delete m.TextureCache[t],e}}else if(t&&t.textureCacheIds){for(var n=0;nthis.baseTexture.width,s=r+i>this.baseTexture.height;if(o||s){var a=o&&s?"and":"or",u="X: "+e+" + "+n+" = "+(e+n)+" > "+this.baseTexture.width,h="Y: "+r+" + "+i+" = "+(r+i)+" > "+this.baseTexture.height;throw new Error("Texture Error: frame does not fit inside the base Texture dimensions: "+u+" "+a+" "+h)}this.valid=n&&i&&this.baseTexture.hasLoaded,this.trim||this.rotate||(this.orig=t),this.valid&&this._updateUvs()}},{key:"rotate",get:function(){return this._rotate},set:function(t){this._rotate=t,this.valid&&this._updateUvs()}},{key:"width",get:function(){return this.orig.width}},{key:"height",get:function(){return this.orig.height}}]),e}(y.default);r.default=x,x.EMPTY=new x(new l.default),a(x.EMPTY),a(x.EMPTY.baseTexture),x.WHITE=function(){var t=document.createElement("canvas");t.width=10,t.height=10;var e=t.getContext("2d");return e.fillStyle="white",e.fillRect(0,0,10,10),new x(new l.default(t))}(),a(x.WHITE),a(x.WHITE.baseTexture)},{"../math":70,"../settings":101,"../utils":125,"./BaseTexture":112,"./TextureUvs":117,"./VideoBaseTexture":118,eventemitter3:3}],116:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&!1===t.paused&&!1===t.ended&&t.readyState>2},e.prototype._isSourceReady=function(){return 3===this.source.readyState||4===this.source.readyState},e.prototype._onPlayStart=function(){this.hasLoaded||this._onCanPlay(),!this._isAutoUpdating&&this.autoUpdate&&(d.shared.add(this.update,this,f.UPDATE_PRIORITY.HIGH),this._isAutoUpdating=!0)},e.prototype._onPlayStop=function(){this._isAutoUpdating&&(d.shared.remove(this.update,this),this._isAutoUpdating=!1)},e.prototype._onCanPlay=function(){this.hasLoaded=!0,this.source&&(this.source.removeEventListener("canplay",this._onCanPlay),this.source.removeEventListener("canplaythrough",this._onCanPlay),this.width=this.source.videoWidth,this.height=this.source.videoHeight,this.__loaded||(this.__loaded=!0,this.emit("loaded",this)),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.source.play())},e.prototype.destroy=function(){this._isAutoUpdating&&d.shared.remove(this.update,this),this.source&&this.source._pixiId&&(l.default.removeFromCache(this.source._pixiId),delete this.source._pixiId,this.source.pause(),this.source.src="",this.source.load()),t.prototype.destroy.call(this)},e.fromVideo=function(t,r){t._pixiId||(t._pixiId="video_"+(0,c.uid)());var n=c.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),l.default.addToCache(n,t._pixiId)),n},e.fromUrl=function(t,r,n){var i=document.createElement("video");i.setAttribute("webkit-playsinline",""),i.setAttribute("playsinline","");var o=Array.isArray(t)?t[0].src||t[0]:t.src||t;if(void 0===n&&0!==o.indexOf("data:")?i.crossOrigin=(0,v.default)(o):n&&(i.crossOrigin="string"==typeof n?n:"anonymous"),Array.isArray(t))for(var s=0;s2&&void 0!==arguments[2]?arguments[2]:u.UPDATE_PRIORITY.NORMAL;return this._addListener(new l.default(t,e,r))},t.prototype.addOnce=function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:u.UPDATE_PRIORITY.NORMAL;return this._addListener(new l.default(t,e,r,!0))},t.prototype._addListener=function(t){var e=this._head.next,r=this._head;if(e){for(;e;){if(t.priority>e.priority){t.connect(r);break}r=e,e=e.next}t.previous||t.connect(r)}else t.connect(r);return this._startIfPossible(),this},t.prototype.remove=function(t,e){for(var r=this._head.next;r;)r=r.match(t,e)?r.destroy():r.next;return this._head.next||this._cancelIfNeeded(),this},t.prototype.start=function(){this.started||(this.started=!0,this._requestIfNeeded())},t.prototype.stop=function(){this.started&&(this.started=!1,this._cancelIfNeeded())},t.prototype.destroy=function(){this.stop();for(var t=this._head.next;t;)t=t.destroy(!0);this._head.destroy(),this._head=null},t.prototype.update=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:performance.now(),e=void 0;if(t>this.lastTime){e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),this.deltaTime=e*a.default.TARGET_FPMS*this.speed;for(var r=this._head,n=r.next;n;)n=n.emit(this.deltaTime);r.next||this._cancelIfNeeded()}else this.deltaTime=this.elapsedMS=0;this.lastTime=t},o(t,[{key:"FPS",get:function(){return 1e3/this.elapsedMS}},{key:"minFPS",get:function(){return 1e3/this._maxElapsedMS},set:function(t){var e=Math.min(Math.max(0,t)/1e3,a.default.TARGET_FPMS);this._maxElapsedMS=1/e}}]),t}();r.default=c},{"../const":46,"../settings":101,"./TickerListener":120}],120:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];n(this,t),this.fn=e,this.context=r,this.priority=i,this.once=o,this.next=null,this.previous=null,this._destroyed=!1}return t.prototype.match=function(t,e){return e=e||null,this.fn===t&&this.context===e},t.prototype.emit=function(t){this.fn&&(this.context?this.fn.call(this.context,t):this.fn(t));var e=this.next;return this.once&&this.destroy(!0),this._destroyed&&(this.next=null),e},t.prototype.connect=function(t){this.previous=t,t.next&&(t.next.previous=this),this.next=t.next,t.next=this},t.prototype.destroy=function(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._destroyed=!0,this.fn=null,this.context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);var e=this.previous;return this.next=t?null:e,this.previous=null,e},t}();r.default=i},{}],121:[function(t,e,r){"use strict";r.__esModule=!0,r.Ticker=r.shared=void 0;var n=t("./Ticker"),i=function(t){return t&&t.__esModule?t:{default:t}}(n),o=new i.default;o.autoStart=!0,o.destroy=function(){},r.shared=o,r.Ticker=i.default},{"./Ticker":119}],122:[function(t,e,r){"use strict";function n(){return!(!!navigator.platform&&/iPad|iPhone|iPod/.test(navigator.platform))}r.__esModule=!0,r.default=n},{}],123:[function(t,e,r){"use strict";function n(t){for(var e=6*t,r=new Uint16Array(e),n=0,i=0;n1&&void 0!==arguments[1]?arguments[1]:window.location;if(0===t.indexOf("data:"))return"";e=e||window.location,s||(s=document.createElement("a")),s.href=t,t=o.default.parse(s.href);var r=!t.port&&""===e.port||t.port===e.port;return t.hostname===e.hostname&&r&&t.protocol===e.protocol?"":"anonymous"}r.__esModule=!0,r.default=n;var i=t("url"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=void 0},{url:29}],125:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(){return++k}function s(t,e){return e=e||[],e[0]=(t>>16&255)/255,e[1]=(t>>8&255)/255,e[2]=(255&t)/255,e}function a(t){return t=t.toString(16),"#"+(t="000000".substr(0,6-t.length)+t)}function u(t){return(255*t[0]<<16)+(255*t[1]<<8)+(255*t[2]|0)}function h(t,e){var r=S.default.RETINA_PREFIX.exec(t);return r?parseFloat(r[1]):void 0!==e?e:1}function l(t){var e=w.DATA_URI.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,encoding:e[3]?e[3].toLowerCase():void 0,data:e[4]}}function c(t){var e=w.URL_FILE_EXTENSION.exec(t);if(e)return e[1].toLowerCase()}function d(t){var e=w.SVG_SIZE.exec(t),r={};return e&&(r[e[1]]=Math.round(parseFloat(e[3])),r[e[5]]=Math.round(parseFloat(e[7]))),r}function f(){j=!0}function p(t){if(!j){if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var e=["\n %c %c %c PixiJS "+w.VERSION+" - ✰ "+t+" ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n","background: #ff66a5; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff66a5; background: #030307; padding:5px 0;","background: #ff66a5; padding:5px 0;","background: #ffc3dc; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;"];window.console.log.apply(console,e)}else window.console&&window.console.log("PixiJS "+w.VERSION+" - "+t+" - http://www.pixijs.com/");j=!0}}function v(){var t={stencil:!0,failIfMajorPerformanceCaveat:!0};try{if(!window.WebGLRenderingContext)return!1;var e=document.createElement("canvas"),r=e.getContext("webgl",t)||e.getContext("experimental-webgl",t),n=!(!r||!r.getContextAttributes().stencil);if(r){var i=r.getExtension("WEBGL_lose_context");i&&i.loseContext()}return r=null,n}catch(t){return!1}}function y(t){return 0===t?0:t<0?-1:1}function g(){var t=void 0;for(t in U)U[t].destroy();for(t in X)X[t].destroy()}function m(){var t=void 0;for(t in U)delete U[t];for(t in X)delete X[t]}function _(t,e){return G[e?1:0][t]}function b(t,e){if(1===e)return(255*e<<24)+t;if(0===e)return 0;var r=t>>16&255,n=t>>8&255,i=255&t;return r=r*e+.5|0,n=n*e+.5|0,i=i*e+.5|0,(255*e<<24)+(r<<16)+(n<<8)+i}function x(t,e,r,n){return r=r||new Float32Array(4),n||void 0===n?(r[0]=t[0]*e,r[1]=t[1]*e,r[2]=t[2]*e):(r[0]=t[0],r[1]=t[1],r[2]=t[2]),r[3]=e,r}function T(t,e,r,n){return r=r||new Float32Array(4),r[0]=(t>>16&255)/255,r[1]=(t>>8&255)/255,r[2]=(255&t)/255,(n||void 0===n)&&(r[0]*=e,r[1]*=e,r[2]*=e),r[3]=e,r}r.__esModule=!0,r.premultiplyBlendMode=r.BaseTextureCache=r.TextureCache=r.mixins=r.pluginTarget=r.EventEmitter=r.removeItems=r.isMobile=void 0,r.uid=o,r.hex2rgb=s,r.hex2string=a,r.rgb2hex=u,r.getResolutionOfUrl=h,r.decomposeDataUri=l,r.getUrlFileExtension=c,r.getSvgSize=d,r.skipHello=f,r.sayHello=p,r.isWebGLSupported=v,r.sign=y,r.destroyTextureCache=g,r.clearTextureCache=m,r.correctBlendMode=_,r.premultiplyTint=b,r.premultiplyRgba=x,r.premultiplyTintToRgba=T;var w=t("../const"),E=t("../settings"),S=i(E),O=t("eventemitter3"),M=i(O),P=t("./pluginTarget"),C=i(P),R=t("./mixin"),A=n(R),I=t("ismobilejs"),D=n(I),L=t("remove-array-items"),N=i(L),F=t("./mapPremultipliedBlendModes"),B=i(F),k=0,j=!1;r.isMobile=D,r.removeItems=N.default,r.EventEmitter=M.default,r.pluginTarget=C.default,r.mixins=A;var U=r.TextureCache=Object.create(null),X=r.BaseTextureCache=Object.create(null),G=r.premultiplyBlendMode=(0,B.default)()},{"../const":46,"../settings":101,"./mapPremultipliedBlendModes":126,"./mixin":128,"./pluginTarget":129,eventemitter3:3,ismobilejs:4,"remove-array-items":31}],126:[function(t,e,r){"use strict";function n(){for(var t=[],e=[],r=0;r<32;r++)t[r]=r,e[r]=r;t[i.BLEND_MODES.NORMAL_NPM]=i.BLEND_MODES.NORMAL,t[i.BLEND_MODES.ADD_NPM]=i.BLEND_MODES.ADD,t[i.BLEND_MODES.SCREEN_NPM]=i.BLEND_MODES.SCREEN,e[i.BLEND_MODES.NORMAL]=i.BLEND_MODES.NORMAL_NPM,e[i.BLEND_MODES.ADD]=i.BLEND_MODES.ADD_NPM,e[i.BLEND_MODES.SCREEN]=i.BLEND_MODES.SCREEN_NPM;var n=[];return n.push(e),n.push(t),n}r.__esModule=!0,r.default=n;var i=t("../const")},{"../const":46}],127:[function(t,e,r){"use strict";function n(t){return o.default.tablet||o.default.phone?4:t}r.__esModule=!0,r.default=n;var i=t("ismobilejs"),o=function(t){return t&&t.__esModule?t:{default:t}}(i)},{ismobilejs:4}],128:[function(t,e,r){"use strict";function n(t,e){if(t&&e)for(var r=Object.keys(e),n=0;n1?this._fontStyle="italic":t.indexOf("oblique")>-1?this._fontStyle="oblique":this._fontStyle="normal",t.indexOf("small-caps")>-1?this._fontVariant="small-caps":this._fontVariant="normal";var e=t.split(" "),r=-1;this._fontSize=26;for(var i=0;i-1&&r=this._durations[this.currentFrame];)n-=this._durations[this.currentFrame]*i,this._currentTime+=i;this._currentTime+=n/this._durations[this.currentFrame]}else this._currentTime+=e;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):r!==this.currentFrame&&(this.loop&&this.onLoop&&(this.animationSpeed>0&&this.currentFramer&&this.onLoop()),this.updateTexture())},e.prototype.updateTexture=function(){this._texture=this._textures[this.currentFrame],this._textureID=-1,this.cachedTint=16777215,this.onFrameChange&&this.onFrameChange(this.currentFrame)},e.prototype.destroy=function(e){this.stop(),t.prototype.destroy.call(this,e)},e.fromFrames=function(t){for(var r=[],n=0;n1&&void 0!==arguments[1]?arguments[1]:{};i(this,e);var s=o(this,t.call(this));return s._textWidth=0,s._textHeight=0,s._glyphs=[],s._font={tint:void 0!==n.tint?n.tint:16777215,align:n.align||"left",name:null,size:0},s.font=n.font,s._text=r,s._maxWidth=0,s._maxLineHeight=0,s._anchor=new c.default(function(){s.dirty=!0},s,0,0),s.dirty=!1,s.updateText(),s}return s(e,t),e.prototype.updateText=function(){for(var t=e.fonts[this._font.name],r=this._font.size/t.size,n=new h.Point,i=[],o=[],s=null,a=0,u=0,l=0,c=-1,d=0,f=0,p=0,v=0;v0&&n.x*r>this._maxWidth)h.utils.removeItems(i,c-f,v-c),v=c,c=-1,++f,o.push(d),u=Math.max(u,d),l++,n.x=0,n.y+=t.lineHeight,s=null;else{var g=t.chars[y];g&&(s&&g.kerning[s]&&(n.x+=g.kerning[s]),i.push({texture:g.texture,line:l,charCode:y,position:new h.Point(n.x+g.xOffset,n.y+g.yOffset)}),a=n.x+(g.texture.width+g.xOffset),n.x+=g.xAdvance,p=Math.max(p,g.yOffset+g.texture.height),s=y)}}o.push(a),u=Math.max(u,a);for(var m=[],_=0;_<=l;_++){var b=0;"right"===this._font.align?b=u-o[_]:"center"===this._font.align&&(b=(u-o[_])/2),m.push(b)}for(var x=i.length,T=this.tint,w=0;w=0?t:16777215,this.dirty=!0}},{key:"align",get:function(){return this._font.align},set:function(t){this._font.align=t||"left",this.dirty=!0}},{key:"anchor",get:function(){return this._anchor},set:function(t){"number"==typeof t?this._anchor.set(t):this._anchor.copy(t)}},{key:"font",get:function(){return this._font},set:function(t){t&&("string"==typeof t?(t=t.split(" "),this._font.name=1===t.length?t[0]:t.slice(1).join(" "),this._font.size=t.length>=2?parseInt(t[0],10):e.fonts[this._font.name].size):(this._font.name=t.name,this._font.size="number"==typeof t.size?t.size:parseInt(t.size,10)),this.dirty=!0)}},{key:"text",get:function(){return this._text},set:function(t){t=t.toString()||" ",this._text!==t&&(this._text=t,this.dirty=!0)}},{key:"maxWidth",get:function(){return this._maxWidth},set:function(t){this._maxWidth!==t&&(this._maxWidth=t,this.dirty=!0)}},{key:"maxLineHeight",get:function(){return this.validate(),this._maxLineHeight}},{key:"textWidth",get:function(){return this.validate(),this._textWidth}},{key:"textHeight",get:function(){return this.validate(),this._textHeight}}]),e}(h.Container);r.default=v,v.fonts={}},{"../core":65,"../core/math/ObservablePoint":68,"../core/settings":101,"../core/utils":125}],137:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:100,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:100;n(this,e);var a=i(this,t.call(this,r));return a.tileTransform=new u.TransformStatic,a._width=o,a._height=s,a._canvasPattern=null,a.uvTransform=r.transform||new u.TextureMatrix(r),a.pluginName="tilingSprite",a.uvRespectAnchor=!1,a}return o(e,t),e.prototype._onTextureUpdate=function(){this.uvTransform&&(this.uvTransform.texture=this._texture),this.cachedTint=16777215},e.prototype._renderWebGL=function(t){var e=this._texture;e&&e.valid&&(this.tileTransform.updateLocalTransform(),this.uvTransform.update(),t.setObjectRenderer(t.plugins[this.pluginName]),t.plugins[this.pluginName].render(this))},e.prototype._renderCanvas=function(t){var e=this._texture;if(e.baseTexture.hasLoaded){var r=t.context,n=this.worldTransform,i=t.resolution,o=e.baseTexture,s=o.resolution,a=this.tilePosition.x/this.tileScale.x%e._frame.width*s,h=this.tilePosition.y/this.tileScale.y%e._frame.height*s;if(this._textureID!==this._texture._updateID||this.cachedTint!==this.tint){this._textureID=this._texture._updateID;var c=new u.CanvasRenderTarget(e._frame.width,e._frame.height,s);16777215!==this.tint?(this.tintedTexture=l.default.getTintedTexture(this,this.tint),c.context.drawImage(this.tintedTexture,0,0)):c.context.drawImage(o.source,-e._frame.x*s,-e._frame.y*s),this.cachedTint=this.tint,this._canvasPattern=c.context.createPattern(c.canvas,"repeat")}r.globalAlpha=this.worldAlpha,r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t.setBlendMode(this.blendMode),r.fillStyle=this._canvasPattern,r.scale(this.tileScale.x/s,this.tileScale.y/s);var d=this.anchor.x*-this._width,f=this.anchor.y*-this._height;this.uvRespectAnchor?(r.translate(a,h),r.fillRect(-a+d,-h+f,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s)):(r.translate(a+d,h+f),r.fillRect(-a,-h,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s))}},e.prototype._calculateBounds=function(){var t=this._width*-this._anchor._x,e=this._height*-this._anchor._y,r=this._width*(1-this._anchor._x),n=this._height*(1-this._anchor._y);this._bounds.addFrame(this.transform,t,e,r,n)},e.prototype.getLocalBounds=function(e){return 0===this.children.length?(this._bounds.minX=this._width*-this._anchor._x,this._bounds.minY=this._height*-this._anchor._y,this._bounds.maxX=this._width*(1-this._anchor._x),this._bounds.maxY=this._height*(1-this._anchor._x),e||(this._localBoundsRect||(this._localBoundsRect=new u.Rectangle),e=this._localBoundsRect),this._bounds.getRectangle(e)):t.prototype.getLocalBounds.call(this,e)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,c);var e=this._width,r=this._height,n=-e*this.anchor._x;if(c.x>=n&&c.x=i&&c.y0&&void 0!==arguments[0]?arguments[0]:new i.Point,e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.parent?this.parent.toGlobal(this.position,t,e):(t.x=this.position.x,t.y=this.position.y),t}},{"../core":65}],141:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.BitmapText=r.TilingSpriteRenderer=r.TilingSprite=r.AnimatedSprite=void 0;var i=t("./AnimatedSprite");Object.defineProperty(r,"AnimatedSprite",{enumerable:!0,get:function(){return n(i).default}});var o=t("./TilingSprite");Object.defineProperty(r,"TilingSprite",{enumerable:!0,get:function(){return n(o).default}});var s=t("./webgl/TilingSpriteRenderer");Object.defineProperty(r,"TilingSpriteRenderer",{enumerable:!0,get:function(){return n(s).default}});var a=t("./BitmapText");Object.defineProperty(r,"BitmapText",{enumerable:!0,get:function(){return n(a).default}}),t("./cacheAsBitmap"),t("./getChildByName"),t("./getGlobalPosition")},{"./AnimatedSprite":135,"./BitmapText":136,"./TilingSprite":137,"./cacheAsBitmap":138,"./getChildByName":139,"./getGlobalPosition":140,"./webgl/TilingSpriteRenderer":142}],142:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=t("../../core"),a=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(s),u=t("../../core/const"),h=(t("path"),new a.Matrix),l=function(t){function e(r){n(this,e);var o=i(this,t.call(this,r));return o.shader=null,o.simpleShader=null,o.quad=null,o}return o(e,t),e.prototype.onContextChange=function(){var t=this.renderer.gl;this.shader=new a.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n gl_FragColor = sample * uColor;\n}\n"), +this.simpleShader=new a.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = sample * uColor;\n}\n"),this.renderer.bindVao(null),this.quad=new a.Quad(t,this.renderer.state.attribState),this.quad.initVao(this.shader)},e.prototype.render=function(t){var e=this.renderer,r=this.quad;e.bindVao(r.vao);var n=r.vertices;n[0]=n[6]=t._width*-t.anchor.x,n[1]=n[3]=t._height*-t.anchor.y,n[2]=n[4]=t._width*(1-t.anchor.x),n[5]=n[7]=t._height*(1-t.anchor.y),t.uvRespectAnchor&&(n=r.uvs,n[0]=n[6]=-t.anchor.x,n[1]=n[3]=-t.anchor.y,n[2]=n[4]=1-t.anchor.x,n[5]=n[7]=1-t.anchor.y),r.upload();var i=t._texture,o=i.baseTexture,s=t.tileTransform.localTransform,l=t.uvTransform,c=o.isPowerOfTwo&&i.frame.width===o.width&&i.frame.height===o.height;c&&(o._glTextures[e.CONTEXT_UID]?c=o.wrapMode!==u.WRAP_MODES.CLAMP:o.wrapMode===u.WRAP_MODES.CLAMP&&(o.wrapMode=u.WRAP_MODES.REPEAT));var d=c?this.simpleShader:this.shader;e.bindShader(d);var f=i.width,p=i.height,v=t._width,y=t._height;h.set(s.a*f/v,s.b*f/y,s.c*p/v,s.d*p/y,s.tx/v,s.ty/y),h.invert(),c?h.prepend(l.mapCoord):(d.uniforms.uMapCoord=l.mapCoord.toArray(!0),d.uniforms.uClampFrame=l.uClampFrame,d.uniforms.uClampOffset=l.uClampOffset),d.uniforms.uTransform=h.toArray(!0),d.uniforms.uColor=a.utils.premultiplyTintToRgba(t.tint,t.worldAlpha,d.uniforms.uColor,o.premultipliedAlpha),d.uniforms.translationMatrix=t.transform.worldTransform.toArray(!0),d.uniforms.uSampler=e.bindTexture(i),e.setBlendMode(a.utils.correctBlendMode(t.blendMode,o.premultipliedAlpha)),r.vao.draw(this.renderer.gl.TRIANGLES,6,0)},e}(a.ObjectRenderer);r.default=l,a.WebGLRenderer.registerPlugin("tilingSprite",l)},{"../../core":65,"../../core/const":46,path:23}],143:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:1;n(this,e);var o=i(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n"));return o.alpha=r,o.glShaderKey="alpha",o}return o(e,t),s(e,[{key:"alpha",get:function(){return this.uniforms.uAlpha},set:function(t){this.uniforms.uAlpha=t}}]),e}(u.Filter));r.default=h},{"../../core":65,path:23}],144:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r=r&&(u=t-h-1),l=l.replace("%value%",e[u]),s+=l,s+="\n"}return n=n.replace("%blur%",s),n=n.replace("%size%",t)}r.__esModule=!0,r.default=n;var i={5:[.153388,.221461,.250301],7:[.071303,.131514,.189879,.214607],9:[.028532,.067234,.124009,.179044,.20236],11:[.0093,.028002,.065984,.121703,.175713,.198596],13:[.002406,.009255,.027867,.065666,.121117,.174868,.197641],15:[489e-6,.002403,.009246,.02784,.065602,.120999,.174697,.197448]},o=["varying vec2 vBlurTexCoords[%size%];","uniform sampler2D uSampler;","void main(void)","{"," gl_FragColor = vec4(0.0);"," %blur%","}"].join("\n")},{}],148:[function(t,e,r){"use strict";function n(t,e){var r=Math.ceil(t/2),n=i,o="",s=void 0;s=e?"vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);":"vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);";for(var a=0;ae;)r-=2;return r}r.__esModule=!0,r.default=n},{}],150:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n"));return r.uniforms.m=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],r.alpha=1,r}return o(e,t),e.prototype._loadMatrix=function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t;e&&(this._multiply(r,this.uniforms.m,t),r=this._colorMatrix(r)),this.uniforms.m=r},e.prototype._multiply=function(t,e,r){return t[0]=e[0]*r[0]+e[1]*r[5]+e[2]*r[10]+e[3]*r[15],t[1]=e[0]*r[1]+e[1]*r[6]+e[2]*r[11]+e[3]*r[16],t[2]=e[0]*r[2]+e[1]*r[7]+e[2]*r[12]+e[3]*r[17],t[3]=e[0]*r[3]+e[1]*r[8]+e[2]*r[13]+e[3]*r[18],t[4]=e[0]*r[4]+e[1]*r[9]+e[2]*r[14]+e[3]*r[19]+e[4],t[5]=e[5]*r[0]+e[6]*r[5]+e[7]*r[10]+e[8]*r[15],t[6]=e[5]*r[1]+e[6]*r[6]+e[7]*r[11]+e[8]*r[16],t[7]=e[5]*r[2]+e[6]*r[7]+e[7]*r[12]+e[8]*r[17],t[8]=e[5]*r[3]+e[6]*r[8]+e[7]*r[13]+e[8]*r[18],t[9]=e[5]*r[4]+e[6]*r[9]+e[7]*r[14]+e[8]*r[19]+e[9],t[10]=e[10]*r[0]+e[11]*r[5]+e[12]*r[10]+e[13]*r[15],t[11]=e[10]*r[1]+e[11]*r[6]+e[12]*r[11]+e[13]*r[16],t[12]=e[10]*r[2]+e[11]*r[7]+e[12]*r[12]+e[13]*r[17],t[13]=e[10]*r[3]+e[11]*r[8]+e[12]*r[13]+e[13]*r[18],t[14]=e[10]*r[4]+e[11]*r[9]+e[12]*r[14]+e[13]*r[19]+e[14],t[15]=e[15]*r[0]+e[16]*r[5]+e[17]*r[10]+e[18]*r[15],t[16]=e[15]*r[1]+e[16]*r[6]+e[17]*r[11]+e[18]*r[16],t[17]=e[15]*r[2]+e[16]*r[7]+e[17]*r[12]+e[18]*r[17],t[18]=e[15]*r[3]+e[16]*r[8]+e[17]*r[13]+e[18]*r[18],t[19]=e[15]*r[4]+e[16]*r[9]+e[17]*r[14]+e[18]*r[19]+e[19],t},e.prototype._colorMatrix=function(t){var e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e},e.prototype.brightness=function(t,e){var r=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.greyscale=function(t,e){var r=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.blackAndWhite=function(t){var e=[.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.hue=function(t,e){t=(t||0)/180*Math.PI;var r=Math.cos(t),n=Math.sin(t),i=Math.sqrt,o=1/3,s=i(o),a=r+(1-r)*o,u=o*(1-r)-s*n,h=o*(1-r)+s*n,l=o*(1-r)+s*n,c=r+o*(1-r),d=o*(1-r)-s*n,f=o*(1-r)-s*n,p=o*(1-r)+s*n,v=r+o*(1-r),y=[a,u,h,0,0,l,c,d,0,0,f,p,v,0,0,0,0,0,1,0];this._loadMatrix(y,e)},e.prototype.contrast=function(t,e){var r=(t||0)+1,n=-.5*(r-1),i=[r,0,0,0,n,0,r,0,0,n,0,0,r,0,n,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.saturate=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=2*t/3+1,n=-.5*(r-1),i=[r,n,n,0,0,n,r,n,0,0,n,n,r,0,0,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.desaturate=function(){this.saturate(-1)},e.prototype.negative=function(t){var e=[0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.sepia=function(t){var e=[.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.technicolor=function(t){var e=[1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.polaroid=function(t){var e=[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.toBGR=function(t){var e=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.kodachrome=function(t){var e=[1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.browni=function(t){var e=[.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.vintage=function(t){var e=[.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.colorTone=function(t,e,r,n,i){t=t||.2,e=e||.15,r=r||16770432,n=n||3375104;var o=(r>>16&255)/255,s=(r>>8&255)/255,a=(255&r)/255,u=(n>>16&255)/255,h=(n>>8&255)/255,l=(255&n)/255,c=[.3,.59,.11,0,0,o,s,a,t,0,u,h,l,e,0,o-u,s-h,a-l,0,0];this._loadMatrix(c,i)},e.prototype.night=function(t,e){t=t||.1;var r=[-2*t,-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.predator=function(t,e){var r=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.lsd=function(t){var e=[2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.reset=function(){var t=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(t,!1)},s(e,[{key:"matrix",get:function(){return this.uniforms.m},set:function(t){this.uniforms.m=t}},{key:"alpha",get:function(){return this.uniforms.uAlpha},set:function(t){this.uniforms.uAlpha=t}}]),e}(u.Filter));r.default=h,h.prototype.grayscale=h.prototype.greyscale},{"../../core":65,path:23}],151:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n'))}return o(e,t),e}(a.Filter));r.default=u},{"../../core":65,path:23}],153:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./fxaa/FXAAFilter");Object.defineProperty(r,"FXAAFilter",{enumerable:!0,get:function(){return n(i).default}});var o=t("./noise/NoiseFilter");Object.defineProperty(r,"NoiseFilter",{enumerable:!0,get:function(){return n(o).default}});var s=t("./displacement/DisplacementFilter");Object.defineProperty(r,"DisplacementFilter",{enumerable:!0,get:function(){return n(s).default}});var a=t("./blur/BlurFilter");Object.defineProperty(r,"BlurFilter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./blur/BlurXFilter");Object.defineProperty(r,"BlurXFilter",{enumerable:!0,get:function(){return n(u).default}});var h=t("./blur/BlurYFilter");Object.defineProperty(r,"BlurYFilter",{enumerable:!0,get:function(){return n(h).default}});var l=t("./colormatrix/ColorMatrixFilter");Object.defineProperty(r,"ColorMatrixFilter",{enumerable:!0,get:function(){return n(l).default}});var c=t("./alpha/AlphaFilter");Object.defineProperty(r,"AlphaFilter",{enumerable:!0,get:function(){return n(c).default}})},{"./alpha/AlphaFilter":143,"./blur/BlurFilter":144,"./blur/BlurXFilter":145,"./blur/BlurYFilter":146,"./colormatrix/ColorMatrixFilter":150,"./displacement/DisplacementFilter":151,"./fxaa/FXAAFilter":152,"./noise/NoiseFilter":154}],154:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called") +;return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:.5,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Math.random();n(this,e);var s=i(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n"));return s.noise=r,s.seed=o,s}return o(e,t),s(e,[{key:"noise",get:function(){return this.uniforms.uNoise},set:function(t){this.uniforms.uNoise=t}},{key:"seed",get:function(){return this.uniforms.uSeed},set:function(t){this.uniforms.uSeed=t}}]),e}(u.Filter));r.default=h},{"../../core":65,path:23}],155:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:1;this.removeEvents(),this.interactionDOMElement=t,this.resolution=e,this.addEvents()},e.prototype.addEvents=function(){this.interactionDOMElement&&(h.ticker.shared.add(this.update,this,h.UPDATE_PRIORITY.INTERACTION),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="none",this.interactionDOMElement.style["-ms-touch-action"]="none"):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]="none"),this.supportsPointerEvents?(window.document.addEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("pointerover",this.onPointerOver,!0),window.addEventListener("pointercancel",this.onPointerCancel,!0),window.addEventListener("pointerup",this.onPointerUp,!0)):(window.document.addEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onPointerOver,!0),window.addEventListener("mouseup",this.onPointerUp,!0)),this.supportsTouchEvents&&(this.interactionDOMElement.addEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.addEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.addEventListener("touchmove",this.onPointerMove,!0)),this.eventsAdded=!0)},e.prototype.removeEvents=function(){this.interactionDOMElement&&(h.ticker.shared.remove(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="",this.interactionDOMElement.style["-ms-touch-action"]=""):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]=""),this.supportsPointerEvents?(window.document.removeEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("pointerover",this.onPointerOver,!0),window.removeEventListener("pointercancel",this.onPointerCancel,!0),window.removeEventListener("pointerup",this.onPointerUp,!0)):(window.document.removeEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onPointerOver,!0),window.removeEventListener("mouseup",this.onPointerUp,!0)),this.supportsTouchEvents&&(this.interactionDOMElement.removeEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.removeEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onPointerMove,!0)),this.interactionDOMElement=null,this.eventsAdded=!1)},e.prototype.update=function(t){if(this._deltaTime+=t,!(this._deltaTime=0;h--){var l=u[h],c=this.processInteractive(t,l,r,n,a);if(c){if(!l.parent)continue;a=!1,c&&(t.target&&(n=!1),s=!0)}}return i&&(n&&!t.target&&(e.hitArea?(e.worldTransform.applyInverse(o,this._tempPoint),e.hitArea.contains(this._tempPoint.x,this._tempPoint.y)&&(s=!0)):e.containsPoint&&e.containsPoint(o)&&(s=!0)),e.interactive&&(s&&!t.target&&(t.target=e),r&&r(t,e,!!s))),s},e.prototype.onPointerDown=function(t){if(!this.supportsTouchEvents||"touch"!==t.pointerType){var e=this.normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&t.preventDefault();for(var r=e.length,n=0;n1&&(l=1);var c=Math.sqrt(n*n+i*i),d=this._texture.height/2;n/=c,i/=c,n*=d,i*=d,o[h]=u.x+n,o[h+1]=u.y+i,o[h+2]=u.x-n,o[h+3]=u.y-i,e=u}},e.prototype.updateTransform=function(){this.autoUpdate&&this.refreshVertices(),this.containerUpdateTransform()},e}(a.default);r.default=u},{"./Mesh":166}],170:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../core"),o=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(i),s=t("../Mesh"),a=function(t){return t&&t.__esModule?t:{default:t}}(s),u=function(){function t(e){n(this,t),this.renderer=e}return t.prototype.render=function(t){var e=this.renderer,r=e.context,n=t.worldTransform,i=e.resolution;e.roundPixels?r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i|0,n.ty*i|0):r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),e.setBlendMode(t.blendMode),t.drawMode===a.default.DRAW_MODES.TRIANGLE_MESH?this._renderTriangleMesh(t):this._renderTriangles(t)},t.prototype._renderTriangleMesh=function(t){for(var e=t.vertices.length/2,r=0;r0){var S=t.canvasPadding/t.worldTransform.a,O=t.canvasPadding/t.worldTransform.d,M=(_+b+x)/3,P=(T+w+E)/3,C=_-M,R=T-P,A=Math.sqrt(C*C+R*R);_=M+C/A*(A+S),T=P+R/A*(A+O),C=b-M,R=w-P,A=Math.sqrt(C*C+R*R),b=M+C/A*(A+S),w=P+R/A*(A+O),C=x-M,R=E-P,A=Math.sqrt(C*C+R*R),x=M+C/A*(A+S),E=P+R/A*(A+O)}i.save(),i.beginPath(),i.moveTo(_,T),i.lineTo(b,w),i.lineTo(x,E),i.closePath(),i.clip();var I=d*y+v*p+f*g-y*p-v*f-d*g,D=_*y+v*x+b*g-y*x-v*b-_*g,L=d*b+_*p+f*x-b*p-_*f-d*x,N=d*y*x+v*b*p+_*f*g-_*y*p-v*f*x-d*b*g,F=T*y+v*E+w*g-y*E-v*w-T*g,B=d*w+T*p+f*E-w*p-T*f-d*E,k=d*y*E+v*w*p+T*f*g-T*y*p-v*f*E-d*w*g;i.transform(D/I,F/I,L/I,B/I,N/I,k/I),i.drawImage(h,0,0,l*u.resolution,c*u.resolution,0,0,l,c),i.restore(),this.renderer.invalidateBlendMode()}},t.prototype.renderMeshFlat=function(t){var e=this.renderer.context,r=t.vertices,n=r.length/2;e.beginPath();for(var i=1;i0&&void 0!==arguments[0]?arguments[0]:1500,o=arguments[1],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16384,a=arguments.length>3&&void 0!==arguments[3]&&arguments[3];n(this,e);var h=i(this,t.call(this));return s>16384&&(s=16384),s>r&&(s=r),h._properties=[!1,!0,!1,!1,!1],h._maxSize=r,h._batchSize=s,h._glBuffers={},h._bufferToUpdate=0,h.interactiveChildren=!1,h.blendMode=u.BLEND_MODES.NORMAL,h.autoResize=a,h.roundPixels=!0,h.baseTexture=null,h.setProperties(o),h._tint=0,h.tintRgb=new Float32Array(4),h.tint=16777215,h}return o(e,t),e.prototype.setProperties=function(t){t&&(this._properties[0]="scale"in t?!!t.scale:this._properties[0],this._properties[1]="position"in t?!!t.position:this._properties[1],this._properties[2]="rotation"in t?!!t.rotation:this._properties[2],this._properties[3]="uvs"in t?!!t.uvs:this._properties[3],this._properties[4]="alpha"in t||"tint"in t?!!t.alpha||!!t.tint:this._properties[4])},e.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},e.prototype.renderWebGL=function(t){var e=this;this.visible&&!(this.worldAlpha<=0)&&this.children.length&&this.renderable&&(this.baseTexture||(this.baseTexture=this.children[0]._texture.baseTexture,this.baseTexture.hasLoaded||this.baseTexture.once("update",function(){return e.onChildrenChange(0)})),t.setObjectRenderer(t.plugins.particle),t.plugins.particle.render(this))},e.prototype.onChildrenChange=function(t){var e=Math.floor(t/this._batchSize);er&&(o=r);var s=t._glBuffers[i.CONTEXT_UID];s||(s=t._glBuffers[i.CONTEXT_UID]=this.generateBuffers(t));var a=e[0]._texture.baseTexture;this.renderer.setBlendMode(u.utils.correctBlendMode(t.blendMode,a.premultipliedAlpha));var h=i.gl,l=t.worldTransform.copy(this.tempMatrix);l.prepend(i._activeRenderTarget.projectionMatrix),this.shader.uniforms.projectionMatrix=l.toArray(!0),this.shader.uniforms.uColor=u.utils.premultiplyRgba(t.tintRgb,t.worldAlpha,this.shader.uniforms.uColor,a.premultipliedAlpha),this.shader.uniforms.uSampler=i.bindTexture(a);for(var c=0,d=0;cn&&(f=n),d>=s.length){if(!t.autoResize)break;s.push(this._generateOneMoreBuffer(t))}var p=s[d];p.uploadDynamic(e,c,f),t._bufferToUpdate===d&&(p.uploadStatic(e,c,f),t._bufferToUpdate=d+1),i.bindVao(p.vao),p.vao.draw(h.TRIANGLES,6*f)}}},e.prototype.generateBuffers=function(t){for(var e=this.renderer.gl,r=[],n=t._maxSize,i=t._batchSize,o=t._properties,s=0;s0?1:-1})},{}],179:[function(t,e,r){"use strict";var n=t("object-assign"),i=function(t){return t&&t.__esModule?t:{default:t}}(n);Object.assign||(Object.assign=i.default)},{"object-assign":5}],180:[function(t,e,r){"use strict";t("./Object.assign"),t("./requestAnimationFrame"),t("./Math.sign"),window.ArrayBuffer||(window.ArrayBuffer=Array),window.Float32Array||(window.Float32Array=Array),window.Uint32Array||(window.Uint32Array=Array),window.Uint16Array||(window.Uint16Array=Array)},{"./Math.sign":178,"./Object.assign":179,"./requestAnimationFrame":181}],181:[function(t,e,r){(function(t){"use strict";if(Date.now&&Date.prototype.getTime||(Date.now=function(){return(new Date).getTime()}),!t.performance||!t.performance.now){var e=Date.now();t.performance||(t.performance={}),t.performance.now=function(){return Date.now()-e}}for(var r=Date.now(),n=["ms","moz","webkit","o"],i=0;i=0;n--)this.add(t.children[n]);return this},t.prototype.destroy=function(){this.ticking&&v.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null,this.limiter=null,this.uploadHookHelper=null},t}();r.default=y},{"../core":65,"./limiters/CountLimiter":185}],183:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function s(t,e){if(e instanceof u.BaseTexture){var r=e.source,n=0===r.width?t.canvas.width:Math.min(t.canvas.width,r.width),i=0===r.height?t.canvas.height:Math.min(t.canvas.height,r.height);return t.ctx.drawImage(r,0,0,n,i,0,0,t.canvas.width,t.canvas.height),!0}return!1}r.__esModule=!0;var a=t("../../core"),u=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(a),h=t("../BasePrepare"),l=function(t){return t&&t.__esModule?t:{default:t}}(h),c=16,d=function(t){function e(r){n(this,e);var o=i(this,t.call(this,r));return o.uploadHookHelper=o,o.canvas=document.createElement("canvas"),o.canvas.width=c,o.canvas.height=c,o.ctx=o.canvas.getContext("2d"),o.registerUploadHook(s),o}return o(e,t),e.prototype.destroy=function(){t.prototype.destroy.call(this),this.ctx=null,this.canvas=null},e}(l.default);r.default=d,u.CanvasRenderer.registerPlugin("prepare",d)},{"../../core":65,"../BasePrepare":182}],184:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./webgl/WebGLPrepare");Object.defineProperty(r,"webgl",{enumerable:!0,get:function(){return n(i).default}});var o=t("./canvas/CanvasPrepare");Object.defineProperty(r,"canvas",{enumerable:!0,get:function(){return n(o).default}});var s=t("./BasePrepare");Object.defineProperty(r,"BasePrepare",{enumerable:!0,get:function(){return n(s).default}});var a=t("./limiters/CountLimiter");Object.defineProperty(r,"CountLimiter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./limiters/TimeLimiter");Object.defineProperty(r,"TimeLimiter",{enumerable:!0,get:function(){return n(u).default}})},{"./BasePrepare":182,"./canvas/CanvasPrepare":183,"./limiters/CountLimiter":185,"./limiters/TimeLimiter":186,"./webgl/WebGLPrepare":187}],185:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxItemsPerFrame=e,this.itemsLeft=0}return t.prototype.beginFrame=function(){this.itemsLeft=this.maxItemsPerFrame},t.prototype.allowedToUpload=function(){return this.itemsLeft-- >0},t}();r.default=i},{}],186:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxMilliseconds=e,this.frameStart=0}return t.prototype.beginFrame=function(){this.frameStart=Date.now()},t.prototype.allowedToUpload=function(){return Date.now()-this.frameStart 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],2:[function(require,module,exports){ +'use strict'; + +module.exports = earcut; +module.exports.default = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, invSize; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 1 / invSize : 0; + } + + earcutLinked(outerNode, triangles, dim, minX, minY, invSize); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, invSize) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, invSize), + maxZ = zOrder(maxTX, maxTY, minX, minY, invSize); + + var p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + + if (n !== ear.prev && n !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && + area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + // look for remaining points in decreasing z-order + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + // look for remaining points in increasing z-order + while (n && n.z <= maxZ) { + if (n !== ear.prev && n !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && + area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize); + earcutLinked(c, triangles, dim, minX, minY, invSize); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, invSize) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) * invSize; + y = 32767 * (y - minY) * invSize; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; + +},{}],3:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @api private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {Mixed} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @api public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @api public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Boolean} exists Only check if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Add a one-time listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Remove the listeners of a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {Mixed} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn + && (!once || listeners.once) + && (!context || listeners.context === context) + ) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {String|Symbol} [event] The event name. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],4:[function(require,module,exports){ +/** + * isMobile.js v0.4.1 + * + * A simple library to detect Apple phones and tablets, + * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone), + * and any kind of seven inch device, via user agent sniffing. + * + * @author: Kai Mallea (kmallea@gmail.com) + * + * @license: http://creativecommons.org/publicdomain/zero/1.0/ + */ +(function (global) { + + var apple_phone = /iPhone/i, + apple_ipod = /iPod/i, + apple_tablet = /iPad/i, + android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i, // Match 'Android' AND 'Mobile' + android_tablet = /Android/i, + amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i, + amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i, + windows_phone = /Windows Phone/i, + windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i, // Match 'Windows' AND 'ARM' + other_blackberry = /BlackBerry/i, + other_blackberry_10 = /BB10/i, + other_opera = /Opera Mini/i, + other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i, + other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i, // Match 'Firefox' AND 'Mobile' + seven_inch = new RegExp( + '(?:' + // Non-capturing group + + 'Nexus 7' + // Nexus 7 + + '|' + // OR + + 'BNTV250' + // B&N Nook Tablet 7 inch + + '|' + // OR + + 'Kindle Fire' + // Kindle Fire + + '|' + // OR + + 'Silk' + // Kindle Fire, Silk Accelerated + + '|' + // OR + + 'GT-P1000' + // Galaxy Tab 7 inch + + ')', // End non-capturing group + + 'i'); // Case-insensitive matching + + var match = function(regex, userAgent) { + return regex.test(userAgent); + }; + + var IsMobileClass = function(userAgent) { + var ua = userAgent || navigator.userAgent; + + // Facebook mobile app's integrated browser adds a bunch of strings that + // match everything. Strip it out if it exists. + var tmp = ua.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + // Twitter mobile app's integrated browser on iPad adds a "Twitter for + // iPhone" string. Same probable happens on other tablet platforms. + // This will confuse detection so strip it out if it exists. + tmp = ua.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + this.apple = { + phone: match(apple_phone, ua), + ipod: match(apple_ipod, ua), + tablet: !match(apple_phone, ua) && match(apple_tablet, ua), + device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua) + }; + this.amazon = { + phone: match(amazon_phone, ua), + tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) + }; + this.android = { + phone: match(amazon_phone, ua) || match(android_phone, ua), + tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua) + }; + this.windows = { + phone: match(windows_phone, ua), + tablet: match(windows_tablet, ua), + device: match(windows_phone, ua) || match(windows_tablet, ua) + }; + this.other = { + blackberry: match(other_blackberry, ua), + blackberry10: match(other_blackberry_10, ua), + opera: match(other_opera, ua), + firefox: match(other_firefox, ua), + chrome: match(other_chrome, ua), + device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua) + }; + this.seven_inch = match(seven_inch, ua); + this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch; + + // excludes 'other' devices and ipods, targeting touchscreen phones + this.phone = this.apple.phone || this.android.phone || this.windows.phone; + + // excludes 7 inch devices, classifying as phone or tablet is left to the user + this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet; + + if (typeof window === 'undefined') { + return this; + } + }; + + var instantiate = function() { + var IM = new IsMobileClass(); + IM.Class = IsMobileClass; + return IM; + }; + + if (typeof module !== 'undefined' && module.exports && typeof window === 'undefined') { + //node + module.exports = IsMobileClass; + } else if (typeof module !== 'undefined' && module.exports && typeof window !== 'undefined') { + //browserify + module.exports = instantiate(); + } else if (typeof define === 'function' && define.amd) { + //AMD + define('isMobile', [], global.isMobile = instantiate()); + } else { + global.isMobile = instantiate(); + } + +})(this); + +},{}],5:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + +var MiniSignalBinding = (function () { + function MiniSignalBinding(fn, once, thisArg) { + if (once === undefined) once = false; + + _classCallCheck(this, MiniSignalBinding); + + this._fn = fn; + this._once = once; + this._thisArg = thisArg; + this._next = this._prev = this._owner = null; + } + + _createClass(MiniSignalBinding, [{ + key: 'detach', + value: function detach() { + if (this._owner === null) return false; + this._owner.detach(this); + return true; + } + }]); + + return MiniSignalBinding; +})(); + +function _addMiniSignalBinding(self, node) { + if (!self._head) { + self._head = node; + self._tail = node; + } else { + self._tail._next = node; + node._prev = self._tail; + self._tail = node; + } + + node._owner = self; + + return node; +} + +var MiniSignal = (function () { + function MiniSignal() { + _classCallCheck(this, MiniSignal); + + this._head = this._tail = undefined; + } + + _createClass(MiniSignal, [{ + key: 'handlers', + value: function handlers() { + var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; + + var node = this._head; + + if (exists) return !!node; + + var ee = []; + + while (node) { + ee.push(node); + node = node._next; + } + + return ee; + } + }, { + key: 'has', + value: function has(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.'); + } + + return node._owner === this; + } + }, { + key: 'dispatch', + value: function dispatch() { + var node = this._head; + + if (!node) return false; + + while (node) { + if (node._once) this.detach(node); + node._fn.apply(node._thisArg, arguments); + node = node._next; + } + + return true; + } + }, { + key: 'add', + value: function add(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#add(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg)); + } + }, { + key: 'once', + value: function once(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#once(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg)); + } + }, { + key: 'detach', + value: function detach(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.'); + } + if (node._owner !== this) return this; + + if (node._prev) node._prev._next = node._next; + if (node._next) node._next._prev = node._prev; + + if (node === this._head) { + this._head = node._next; + if (node._next === null) { + this._tail = null; + } + } else if (node === this._tail) { + this._tail = node._prev; + this._tail._next = null; + } + + node._owner = null; + return this; + } + }, { + key: 'detachAll', + value: function detachAll() { + var node = this._head; + if (!node) return this; + + this._head = this._tail = null; + + while (node) { + node._owner = null; + node = node._next; + } + return this; + } + }]); + + return MiniSignal; +})(); + +MiniSignal.MiniSignalBinding = MiniSignalBinding; + +exports['default'] = MiniSignal; +module.exports = exports['default']; + +},{}],6:[function(require,module,exports){ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],7:[function(require,module,exports){ +'use strict' + +module.exports = function parseURI (str, opts) { + opts = opts || {} + + var o = { + key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], + q: { + name: 'queryKey', + parser: /(?:^|&)([^&=]*)=?([^&]*)/g + }, + parser: { + strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, + loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ + } + } + + var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str) + var uri = {} + var i = 14 + + while (i--) uri[o.key[i]] = m[i] || '' + + uri[o.q.name] = {} + uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { + if ($1) uri[o.q.name][$1] = $2 + }) + + return uri +} + +},{}],8:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) + +},{"_process":26}],9:[function(require,module,exports){ +var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); + +/** + * Helper class to create a webGL buffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ +var Buffer = function(gl, type, data, drawType) +{ + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The WebGL buffer, created upon instantiation + * + * @member {WebGLBuffer} + */ + this.buffer = gl.createBuffer(); + + /** + * The type of the buffer + * + * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} + */ + this.type = type || gl.ARRAY_BUFFER; + + /** + * The draw type of the buffer + * + * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ + this.drawType = drawType || gl.STATIC_DRAW; + + /** + * The data in the buffer, as a typed array + * + * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} + */ + this.data = EMPTY_ARRAY_BUFFER; + + if(data) + { + this.upload(data); + } + + this._updateID = 0; +}; + +/** + * Uploads the buffer to the GPU + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload + * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract + * @param dontBind {Boolean} whether to bind the buffer before uploading it + */ +Buffer.prototype.upload = function(data, offset, dontBind) +{ + // todo - needed? + if(!dontBind) this.bind(); + + var gl = this.gl; + + data = data || this.data; + offset = offset || 0; + + if(this.data.byteLength >= data.byteLength) + { + gl.bufferSubData(this.type, offset, data); + } + else + { + gl.bufferData(this.type, data, this.drawType); + } + + this.data = data; +}; +/** + * Binds the buffer + * + */ +Buffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindBuffer(this.type, this.buffer); +}; + +Buffer.createVertexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); +}; + +Buffer.createIndexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); +}; + +Buffer.create = function(gl, type, data, drawType) +{ + return new Buffer(gl, type, data, drawType); +}; + +/** + * Destroys the buffer + * + */ +Buffer.prototype.destroy = function(){ + this.gl.deleteBuffer(this.buffer); +}; + +module.exports = Buffer; + +},{}],10:[function(require,module,exports){ + +var Texture = require('./GLTexture'); + +/** + * Helper class to create a webGL Framebuffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + */ +var Framebuffer = function(gl, width, height) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The frame buffer + * + * @member {WebGLFramebuffer} + */ + this.framebuffer = gl.createFramebuffer(); + + /** + * The stencil buffer + * + * @member {WebGLRenderbuffer} + */ + this.stencil = null; + + /** + * The stencil buffer + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The width of the drawing area of the buffer + * + * @member {Number} + */ + this.width = width || 100; + /** + * The height of the drawing area of the buffer + * + * @member {Number} + */ + this.height = height || 100; +}; + +/** + * Adds a texture to the frame buffer + * @param texture {PIXI.glCore.GLTexture} + */ +Framebuffer.prototype.enableTexture = function(texture) +{ + var gl = this.gl; + + this.texture = texture || new Texture(gl); + + this.texture.bind(); + + //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + this.bind(); + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); +}; + +/** + * Initialises the stencil buffer + */ +Framebuffer.prototype.enableStencil = function() +{ + if(this.stencil)return; + + var gl = this.gl; + + this.stencil = gl.createRenderbuffer(); + + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + + // TODO.. this is depth AND stencil? + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width , this.height ); + + +}; + +/** + * Erases the drawing area and fills it with a colour + * @param r {Number} the red value of the clearing colour + * @param g {Number} the green value of the clearing colour + * @param b {Number} the blue value of the clearing colour + * @param a {Number} the alpha value of the clearing colour + */ +Framebuffer.prototype.clear = function( r, g, b, a ) +{ + this.bind(); + + var gl = this.gl; + + gl.clearColor(r, g, b, a); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); +}; + +/** + * Binds the frame buffer to the WebGL context + */ +Framebuffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); +}; + +/** + * Unbinds the frame buffer to the WebGL context + */ +Framebuffer.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, null ); +}; +/** + * Resizes the drawing area of the buffer to the given width and height + * @param width {Number} the new width + * @param height {Number} the new height + */ +Framebuffer.prototype.resize = function(width, height) +{ + var gl = this.gl; + + this.width = width; + this.height = height; + + if ( this.texture ) + { + this.texture.uploadData(null, width, height); + } + + if ( this.stencil ) + { + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + } +}; + +/** + * Destroys this buffer + */ +Framebuffer.prototype.destroy = function() +{ + var gl = this.gl; + + //TODO + if(this.texture) + { + this.texture.destroy(); + } + + gl.deleteFramebuffer(this.framebuffer); + + this.gl = null; + + this.stencil = null; + this.texture = null; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createRGBA = function(gl, width, height, data) +{ + var texture = Texture.fromData(gl, null, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + //fbo.enableStencil(); // get this back on soon! + + //fbo.enableStencil(); // get this back on soon! + + fbo.unbind(); + + return fbo; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createFloat32 = function(gl, width, height, data) +{ + // create a new texture.. + var texture = new Texture.fromData(gl, data, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +module.exports = Framebuffer; + +},{"./GLTexture":12}],11:[function(require,module,exports){ + +var compileProgram = require('./shader/compileProgram'), + extractAttributes = require('./shader/extractAttributes'), + extractUniforms = require('./shader/extractUniforms'), + setPrecision = require('./shader/setPrecision'), + generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + +/** + * Helper class to create a webGL Shader + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + */ +var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + if(precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } + + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); + + this.uniformData = extractUniforms(gl, this.program); + + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + +}; +/** + * Uses this shader + * + * @return {PIXI.glCore.GLShader} Returns itself. + */ +Shader.prototype.bind = function() +{ + this.gl.useProgram(this.program); + return this; +}; + +/** + * Destroys this shader + * TODO + */ +Shader.prototype.destroy = function() +{ + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + + var gl = this.gl; + gl.deleteProgram(this.program); +}; + + +module.exports = Shader; + +},{"./shader/compileProgram":17,"./shader/extractAttributes":19,"./shader/extractUniforms":20,"./shader/generateUniformAccessObject":21,"./shader/setPrecision":25}],12:[function(require,module,exports){ + +/** + * Helper class to create a WebGL Texture + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL context + * @param width {number} the width of the texture + * @param height {number} the height of the texture + * @param format {number} the pixel format of the texture. defaults to gl.RGBA + * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE + */ +var Texture = function(gl, width, height, format, type) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); + + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; + + + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; + + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; + + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + + +}; + +/** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ +Texture.prototype.upload = function(source) +{ + this.bind(); + + var gl = this.gl; + + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + var newWidth = source.videoWidth || source.width; + var newHeight = source.videoHeight || source.height; + + if(newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } + + // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + +}; + +var FLOATING_POINT_AVAILABLE = false; + +/** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.prototype.uploadData = function(data, width, height) +{ + this.bind(); + + var gl = this.gl; + + + if(data instanceof Float32Array) + { + if(!FLOATING_POINT_AVAILABLE) + { + var ext = gl.getExtension("OES_texture_float"); + + if(ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } + + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } + + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + + if(width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } + + this.width = width; + this.height = height; + + +// texSubImage2D +}; + +/** + * Binds the texture + * @param location + */ +Texture.prototype.bind = function(location) +{ + var gl = this.gl; + + if(location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } + + gl.bindTexture(gl.TEXTURE_2D, this.texture); +}; + +/** + * Unbinds the texture + */ +Texture.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, null); +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.minFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + if(this.mipmap) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.magFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); +}; + +/** + * Enables mipmapping + */ +Texture.prototype.enableMipmap = function() +{ + var gl = this.gl; + + this.bind(); + + this.mipmap = true; + + gl.generateMipmap(gl.TEXTURE_2D); +}; + +/** + * Enables linear filtering + */ +Texture.prototype.enableLinearScaling = function() +{ + this.minFilter(true); + this.magFilter(true); +}; + +/** + * Enables nearest neighbour interpolation + */ +Texture.prototype.enableNearestScaling = function() +{ + this.minFilter(false); + this.magFilter(false); +}; + +/** + * Enables clamping on the texture so WebGL will not repeat it + */ +Texture.prototype.enableWrapClamp = function() +{ + var gl = this.gl; + + this.bind(); + + 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); +}; + +/** + * Enable tiling on the texture + */ +Texture.prototype.enableWrapRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); +}; + +Texture.prototype.enableWrapMirrorRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); +}; + + +/** + * Destroys this texture + */ +Texture.prototype.destroy = function() +{ + var gl = this.gl; + //TODO + gl.deleteTexture(this.texture); +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ +Texture.fromSource = function(gl, source, premultiplyAlpha) +{ + var texture = new Texture(gl); + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); + + return texture; +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.fromData = function(gl, data, width, height) +{ + //console.log(data, width, height); + var texture = new Texture(gl); + texture.uploadData(data, width, height); + + return texture; +}; + + +module.exports = Texture; + +},{}],13:[function(require,module,exports){ + +// state object// +var setVertexAttribArrays = require( './setVertexAttribArrays' ); + +/** + * Helper class to work with WebGL VertexArrayObjects (vaos) + * Only works if WebGL extensions are enabled (they usually are) + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function VertexArrayObject(gl, state) +{ + this.nativeVaoExtension = null; + + if(!VertexArrayObject.FORCE_NATIVE) + { + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + this.nativeState = state; + + if(this.nativeVaoExtension) + { + this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + + var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + // VAO - overwrite the state.. + this.nativeState = { + tempAttribState: new Array(maxAttribs), + attribState: new Array(maxAttribs) + }; + } + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of attributes + * + * @member {Array} + */ + this.attributes = []; + + /** + * @member {PIXI.glCore.GLBuffer} + */ + this.indexBuffer = null; + + /** + * A boolean flag + * + * @member {Boolean} + */ + this.dirty = false; +} + +VertexArrayObject.prototype.constructor = VertexArrayObject; +module.exports = VertexArrayObject; + +/** +* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) +* If you find on older devices that things have gone a bit weird then set this to true. +*/ +/** + * Lets the VAO know if you should use the WebGL extension or the native methods. + * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) + * If you find on older devices that things have gone a bit weird then set this to true. + * @static + * @property {Boolean} FORCE_NATIVE + */ +VertexArrayObject.FORCE_NATIVE = false; + +/** + * Binds the buffer + */ +VertexArrayObject.prototype.bind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + + if(this.dirty) + { + this.dirty = false; + this.activate(); + return this; + } + if (this.indexBuffer) + { + this.indexBuffer.bind(); + } + } + else + { + this.activate(); + } + + return this; +}; + +/** + * Unbinds the buffer + */ +VertexArrayObject.prototype.unbind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + return this; +}; + +/** + * Uses this vao + */ +VertexArrayObject.prototype.activate = function() +{ + + var gl = this.gl; + var lastBuffer = null; + + for (var i = 0; i < this.attributes.length; i++) + { + var attrib = this.attributes[i]; + + if(lastBuffer !== attrib.buffer) + { + attrib.buffer.bind(); + lastBuffer = attrib.buffer; + } + + gl.vertexAttribPointer(attrib.attribute.location, + attrib.attribute.size, + attrib.type || gl.FLOAT, + attrib.normalized || false, + attrib.stride || 0, + attrib.start || 0); + } + + setVertexAttribArrays(gl, this.attributes, this.nativeState); + + if(this.indexBuffer) + { + this.indexBuffer.bind(); + } + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + * @param attribute {*} + * @param type {String} + * @param normalized {Boolean} + * @param stride {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start) +{ + this.attributes.push({ + buffer: buffer, + attribute: attribute, + + location: attribute.location, + type: type || this.gl.FLOAT, + normalized: normalized || false, + stride: stride || 0, + start: start || 0 + }); + + this.dirty = true; + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + */ +VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) +{ + this.indexBuffer = buffer; + + this.dirty = true; + + return this; +}; + +/** + * Unbinds this vao and disables it + */ +VertexArrayObject.prototype.clear = function() +{ + // var gl = this.gl; + + // TODO - should this function unbind after clear? + // for now, no but lets see what happens in the real world! + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + } + + this.attributes.length = 0; + this.indexBuffer = null; + + return this; +}; + +/** + * @param type {Number} + * @param size {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.draw = function(type, size, start) +{ + var gl = this.gl; + + if(this.indexBuffer) + { + gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + } + else + { + // TODO need a better way to calculate size.. + gl.drawArrays(type, start, size || this.getSize()); + } + + return this; +}; + +/** + * Destroy this vao + */ +VertexArrayObject.prototype.destroy = function() +{ + // lose references + this.gl = null; + this.indexBuffer = null; + this.attributes = null; + this.nativeState = null; + + if(this.nativeVao) + { + this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); + } + + this.nativeVaoExtension = null; + this.nativeVao = null; +}; + +VertexArrayObject.prototype.getSize = function() +{ + var attrib = this.attributes[0]; + return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); +}; + +},{"./setVertexAttribArrays":16}],14:[function(require,module,exports){ + +/** + * Helper class to create a webGL Context + * + * @class + * @memberof PIXI.glCore + * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from + * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * @return {WebGLRenderingContext} the WebGL context + */ +var createContext = function(canvas, options) +{ + var gl = canvas.getContext('webgl', options) || + canvas.getContext('experimental-webgl', options); + + if (!gl) + { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + return gl; +}; + +module.exports = createContext; + +},{}],15:[function(require,module,exports){ +var gl = { + createContext: require('./createContext'), + setVertexAttribArrays: require('./setVertexAttribArrays'), + GLBuffer: require('./GLBuffer'), + GLFramebuffer: require('./GLFramebuffer'), + GLShader: require('./GLShader'), + GLTexture: require('./GLTexture'), + VertexArrayObject: require('./VertexArrayObject'), + shader: require('./shader') +}; + +// Export for Node-compatible environments +if (typeof module !== 'undefined' && module.exports) +{ + // Export the module + module.exports = gl; +} + +// Add to the browser window pixi.gl +if (typeof window !== 'undefined') +{ + // add the window object + window.PIXI = window.PIXI || {}; + window.PIXI.glCore = gl; +} + +},{"./GLBuffer":9,"./GLFramebuffer":10,"./GLShader":11,"./GLTexture":12,"./VertexArrayObject":13,"./createContext":14,"./setVertexAttribArrays":16,"./shader":22}],16:[function(require,module,exports){ +// var GL_MAP = {}; + +/** + * @param gl {WebGLRenderingContext} The current WebGL context + * @param attribs {*} + * @param state {*} + */ +var setVertexAttribArrays = function (gl, attribs, state) +{ + var i; + if(state) + { + var tempAttribState = state.tempAttribState, + attribState = state.attribState; + + for (i = 0; i < tempAttribState.length; i++) + { + tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + tempAttribState[attribs[i].attribute.location] = true; + } + + for (i = 0; i < attribState.length; i++) + { + if (attribState[i] !== tempAttribState[i]) + { + attribState[i] = tempAttribState[i]; + + if (state.attribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } + + } + else + { + for (i = 0; i < attribs.length; i++) + { + var attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); + } + } +}; + +module.exports = setVertexAttribArrays; + +},{}],17:[function(require,module,exports){ + +/** + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations + * @return {WebGLProgram} the shader program + */ +var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +{ + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + + var program = gl.createProgram(); + + gl.attachShader(program, glVertShader); + gl.attachShader(program, glFragShader); + + // optionally, set the attributes manually for the program rather than letting WebGL decide.. + if(attributeLocations) + { + for(var i in attributeLocations) + { + gl.bindAttribLocation(program, attributeLocations[i], i); + } + } + + + gl.linkProgram(program); + + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + console.error('Pixi.js Error: Could not initialize shader.'); + console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); + console.error('gl.getError()', gl.getError()); + + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') + { + console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + + gl.deleteProgram(program); + program = null; + } + + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + + return program; +}; + +/** + * @private + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @return {WebGLShader} the shader + */ +var compileShader = function (gl, type, src) +{ + var shader = gl.createShader(type); + + gl.shaderSource(shader, src); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + console.log(gl.getShaderInfoLog(shader)); + return null; + } + + return shader; +}; + +module.exports = compileProgram; + +},{}],18:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} Type of value + * @param size {Number} + */ +var defaultValue = function(type, size) +{ + switch (type) + { + case 'float': + return 0; + + case 'vec2': + return new Float32Array(2 * size); + + case 'vec3': + return new Float32Array(3 * size); + + case 'vec4': + return new Float32Array(4 * size); + + case 'int': + case 'sampler2D': + return 0; + + case 'ivec2': + return new Int32Array(2 * size); + + case 'ivec3': + return new Int32Array(3 * size); + + case 'ivec4': + return new Int32Array(4 * size); + + case 'bool': + return false; + + case 'bvec2': + + return booleanArray( 2 * size); + + case 'bvec3': + return booleanArray(3 * size); + + case 'bvec4': + return booleanArray(4 * size); + + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } +}; + +var booleanArray = function(size) +{ + var array = new Array(size); + + for (var i = 0; i < array.length; i++) + { + array[i] = false; + } + + return array; +}; + +module.exports = defaultValue; + +},{}],19:[function(require,module,exports){ + +var mapType = require('./mapType'); +var mapSize = require('./mapSize'); + +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the attributes from + * @return attributes {Object} + */ +var extractAttributes = function(gl, program) +{ + var attributes = {}; + + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + + for (var i = 0; i < totalAttributes; i++) + { + var attribData = gl.getActiveAttrib(program, i); + var type = mapType(gl, attribData.type); + + attributes[attribData.name] = { + type:type, + size:mapSize(type), + location:gl.getAttribLocation(program, attribData.name), + //TODO - make an attribute object + pointer: pointer + }; + } + + return attributes; +}; + +var pointer = function(type, normalized, stride, start){ + // console.log(this.location) + gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +}; + +module.exports = extractAttributes; + +},{"./mapSize":23,"./mapType":24}],20:[function(require,module,exports){ +var mapType = require('./mapType'); +var defaultValue = require('./defaultValue'); + +/** + * Extracts the uniforms + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the uniforms from + * @return uniforms {Object} + */ +var extractUniforms = function(gl, program) +{ + var uniforms = {}; + + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + + for (var i = 0; i < totalUniforms; i++) + { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]/, ""); + var type = mapType(gl, uniformData.type ); + + uniforms[name] = { + type:type, + size:uniformData.size, + location:gl.getUniformLocation(program, name), + value:defaultValue(type, uniformData.size) + }; + } + + return uniforms; +}; + +module.exports = extractUniforms; + +},{"./defaultValue":18,"./mapType":24}],21:[function(require,module,exports){ +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param uniforms {Array} @mat ? + * @return attributes {Object} + */ +var generateUniformAccessObject = function(gl, uniformData) +{ + // this is the object we will be sending back. + // an object hierachy will be created for structs + var uniforms = {data:{}}; + + uniforms.gl = gl; + + var uniformKeys= Object.keys(uniformData); + + for (var i = 0; i < uniformKeys.length; i++) + { + var fullName = uniformKeys[i]; + + var nameTokens = fullName.split('.'); + var name = nameTokens[nameTokens.length - 1]; + + + var uniformGroup = getUniformGroup(nameTokens, uniforms); + + var uniform = uniformData[fullName]; + uniformGroup.data[name] = uniform; + + uniformGroup.gl = gl; + + Object.defineProperty(uniformGroup, name, { + get: generateGetter(name), + set: generateSetter(name, uniform) + }); + } + + return uniforms; +}; + +var generateGetter = function(name) +{ + return function() { + return this.data[name].value; + }; +}; + +var GLSL_SINGLE_SETTERS = { + float: function setSingleFloat(gl, location, value) { gl.uniform1f(location, value); }, + vec2: function setSingleVec2(gl, location, value) { gl.uniform2f(location, value[0], value[1]); }, + vec3: function setSingleVec3(gl, location, value) { gl.uniform3f(location, value[0], value[1], value[2]); }, + vec4: function setSingleVec4(gl, location, value) { gl.uniform4f(location, value[0], value[1], value[2], value[3]); }, + + int: function setSingleInt(gl, location, value) { gl.uniform1i(location, value); }, + ivec2: function setSingleIvec2(gl, location, value) { gl.uniform2i(location, value[0], value[1]); }, + ivec3: function setSingleIvec3(gl, location, value) { gl.uniform3i(location, value[0], value[1], value[2]); }, + ivec4: function setSingleIvec4(gl, location, value) { gl.uniform4i(location, value[0], value[1], value[2], value[3]); }, + + bool: function setSingleBool(gl, location, value) { gl.uniform1i(location, value); }, + bvec2: function setSingleBvec2(gl, location, value) { gl.uniform2i(location, value[0], value[1]); }, + bvec3: function setSingleBvec3(gl, location, value) { gl.uniform3i(location, value[0], value[1], value[2]); }, + bvec4: function setSingleBvec4(gl, location, value) { gl.uniform4i(location, value[0], value[1], value[2], value[3]); }, + + mat2: function setSingleMat2(gl, location, value) { gl.uniformMatrix2fv(location, false, value); }, + mat3: function setSingleMat3(gl, location, value) { gl.uniformMatrix3fv(location, false, value); }, + mat4: function setSingleMat4(gl, location, value) { gl.uniformMatrix4fv(location, false, value); }, + + sampler2D: function setSingleSampler2D(gl, location, value) { gl.uniform1i(location, value); }, +}; + +var GLSL_ARRAY_SETTERS = { + float: function setFloatArray(gl, location, value) { gl.uniform1fv(location, value); }, + vec2: function setVec2Array(gl, location, value) { gl.uniform2fv(location, value); }, + vec3: function setVec3Array(gl, location, value) { gl.uniform3fv(location, value); }, + vec4: function setVec4Array(gl, location, value) { gl.uniform4fv(location, value); }, + int: function setIntArray(gl, location, value) { gl.uniform1iv(location, value); }, + ivec2: function setIvec2Array(gl, location, value) { gl.uniform2iv(location, value); }, + ivec3: function setIvec3Array(gl, location, value) { gl.uniform3iv(location, value); }, + ivec4: function setIvec4Array(gl, location, value) { gl.uniform4iv(location, value); }, + bool: function setBoolArray(gl, location, value) { gl.uniform1iv(location, value); }, + bvec2: function setBvec2Array(gl, location, value) { gl.uniform2iv(location, value); }, + bvec3: function setBvec3Array(gl, location, value) { gl.uniform3iv(location, value); }, + bvec4: function setBvec4Array(gl, location, value) { gl.uniform4iv(location, value); }, + sampler2D: function setSampler2DArray(gl, location, value) { gl.uniform1iv(location, value); }, +}; + +function generateSetter(name, uniform) +{ + return function(value) { + this.data[name].value = value; + var location = this.data[name].location; + if (uniform.size === 1) + { + GLSL_SINGLE_SETTERS[uniform.type](this.gl, location, value); + } + else + { + // glslSetArray(gl, location, type, value) { + GLSL_ARRAY_SETTERS[uniform.type](this.gl, location, value); + } + }; +} + +function getUniformGroup(nameTokens, uniform) +{ + var cur = uniform; + + for (var i = 0; i < nameTokens.length - 1; i++) + { + var o = cur[nameTokens[i]] || {data:{}}; + cur[nameTokens[i]] = o; + cur = o; + } + + return cur; +} + + +module.exports = generateUniformAccessObject; + +},{}],22:[function(require,module,exports){ +module.exports = { + compileProgram: require('./compileProgram'), + defaultValue: require('./defaultValue'), + extractAttributes: require('./extractAttributes'), + extractUniforms: require('./extractUniforms'), + generateUniformAccessObject: require('./generateUniformAccessObject'), + setPrecision: require('./setPrecision'), + mapSize: require('./mapSize'), + mapType: require('./mapType') +}; +},{"./compileProgram":17,"./defaultValue":18,"./extractAttributes":19,"./extractUniforms":20,"./generateUniformAccessObject":21,"./mapSize":23,"./mapType":24,"./setPrecision":25}],23:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} + * @return {Number} + */ +var mapSize = function(type) +{ + return GLSL_TO_SIZE[type]; +}; + + +var GLSL_TO_SIZE = { + 'float': 1, + 'vec2': 2, + 'vec3': 3, + 'vec4': 4, + + 'int': 1, + 'ivec2': 2, + 'ivec3': 3, + 'ivec4': 4, + + 'bool': 1, + 'bvec2': 2, + 'bvec3': 3, + 'bvec4': 4, + + 'mat2': 4, + 'mat3': 9, + 'mat4': 16, + + 'sampler2D': 1 +}; + +module.exports = mapSize; + +},{}],24:[function(require,module,exports){ + + +var mapType = function(gl, type) +{ + if(!GL_TABLE) + { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + + GL_TABLE = {}; + + for(var i = 0; i < typeNames.length; ++i) + { + var tn = typeNames[i]; + GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + } + } + + return GL_TABLE[type]; +}; + +var GL_TABLE = null; + +var GL_TO_GLSL_TYPES = { + 'FLOAT': 'float', + 'FLOAT_VEC2': 'vec2', + 'FLOAT_VEC3': 'vec3', + 'FLOAT_VEC4': 'vec4', + + 'INT': 'int', + 'INT_VEC2': 'ivec2', + 'INT_VEC3': 'ivec3', + 'INT_VEC4': 'ivec4', + + 'BOOL': 'bool', + 'BOOL_VEC2': 'bvec2', + 'BOOL_VEC3': 'bvec3', + 'BOOL_VEC4': 'bvec4', + + 'FLOAT_MAT2': 'mat2', + 'FLOAT_MAT3': 'mat3', + 'FLOAT_MAT4': 'mat4', + + 'SAMPLER_2D': 'sampler2D' +}; + +module.exports = mapType; + +},{}],25:[function(require,module,exports){ +/** + * Sets the float precision on the shader. If the precision is already present this function will do nothing + * @param {string} src the shader source + * @param {string} precision The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + * + * @return {string} modified shader source + */ +var setPrecision = function(src, precision) +{ + if(src.substring(0, 9) !== 'precision') + { + return 'precision ' + precision + ' float;\n' + src; + } + + return src; +}; + +module.exports = setPrecision; + +},{}],26:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],27:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],28:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],29:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],30:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":28,"./encode":29}],31:[function(require,module,exports){ +'use strict' + +/** + * Remove a range of items from an array + * + * @function removeItems + * @param {Array<*>} arr The target array + * @param {number} startIdx The index to begin removing from (inclusive) + * @param {number} removeCount How many items to remove + */ +module.exports = function removeItems(arr, startIdx, removeCount) +{ + var i, length = arr.length + + if (startIdx >= length || removeCount === 0) { + return + } + + removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount) + + var len = length - removeCount + + for (i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount] + } + + arr.length = len +} + +},{}],32:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _async = require('./async'); + +var async = _interopRequireWildcard(_async); + +var _Resource = require('./Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// some constants +var MAX_PROGRESS = 100; +var rgxExtractUrlHash = /(#[\w-]+)?$/; + +/** + * Manages the state and loading of multiple resources to load. + * + * @class + */ + +var Loader = function () { + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader() { + var _this = this; + + var baseUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var concurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; + + _classCallCheck(this, Loader); + + /** + * The base url for all resources loaded by this loader. + * + * @member {string} + */ + this.baseUrl = baseUrl; + + /** + * The progress percent of the loader going through the queue. + * + * @member {number} + */ + this.progress = 0; + + /** + * Loading state of the loader, true if it is currently loading resources. + * + * @member {boolean} + */ + this.loading = false; + + /** + * A querystring to append to every URL added to the loader. + * + * This should be a valid query string *without* the question-mark (`?`). The loader will + * also *not* escape values for you. Make sure to escape your parameters with + * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. + * + * @example + * const loader = new Loader(); + * + * loader.defaultQueryString = 'user=me&password=secret'; + * + * // This will request 'image.png?user=me&password=secret' + * loader.add('image.png').load(); + * + * loader.reset(); + * + * // This will request 'image.png?v=1&user=me&password=secret' + * loader.add('iamge.png?v=1').load(); + */ + this.defaultQueryString = ''; + + /** + * The middleware to run before loading each resource. + * + * @member {function[]} + */ + this._beforeMiddleware = []; + + /** + * The middleware to run after loading each resource. + * + * @member {function[]} + */ + this._afterMiddleware = []; + + /** + * The tracks the resources we are currently completing parsing for. + * + * @member {Resource[]} + */ + this._resourcesParsing = []; + + /** + * The `_loadResource` function bound with this object context. + * + * @private + * @member {function} + * @param {Resource} r - The resource to load + * @param {Function} d - The dequeue function + * @return {undefined} + */ + this._boundLoadResource = function (r, d) { + return _this._loadResource(r, d); + }; + + /** + * The resources waiting to be loaded. + * + * @private + * @member {Resource[]} + */ + this._queue = async.queue(this._boundLoadResource, concurrency); + + this._queue.pause(); + + /** + * All the resources for this loader keyed by name. + * + * @member {object} + */ + this.resources = {}; + + /** + * Dispatched once per loaded or errored resource. + * + * The callback looks like {@link Loader.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once per errored resource. + * + * The callback looks like {@link Loader.OnErrorSignal}. + * + * @member {Signal} + */ + this.onError = new _miniSignals2.default(); + + /** + * Dispatched once per loaded resource. + * + * The callback looks like {@link Loader.OnLoadSignal}. + * + * @member {Signal} + */ + this.onLoad = new _miniSignals2.default(); + + /** + * Dispatched when the loader begins to process the queue. + * + * The callback looks like {@link Loader.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched when the queued resources all load. + * + * The callback looks like {@link Loader.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * When the progress changes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnProgressSignal + * @param {Loader} loader - The loader the progress is advancing on. + * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance. + */ + + /** + * When an error occurrs the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnErrorSignal + * @param {Loader} loader - The loader the error happened in. + * @param {Resource} resource - The resource that caused the error. + */ + + /** + * When a load completes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnLoadSignal + * @param {Loader} loader - The loader that laoded the resource. + * @param {Resource} resource - The resource that has completed loading. + */ + + /** + * When the loader starts loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnStartSignal + * @param {Loader} loader - The loader that has started loading resources. + */ + + /** + * When the loader completes loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnCompleteSignal + * @param {Loader} loader - The loader that has finished loading resources. + */ + } + + /** + * Adds a resource (or multiple resources) to the loader queue. + * + * This function can take a wide variety of different parameters. The only thing that is always + * required the url to load. All the following will work: + * + * ```js + * loader + * // normal param syntax + * .add('key', 'http://...', function () {}) + * .add('http://...', function () {}) + * .add('http://...') + * + * // object syntax + * .add({ + * name: 'key2', + * url: 'http://...' + * }, function () {}) + * .add({ + * url: 'http://...' + * }, function () {}) + * .add({ + * name: 'key3', + * url: 'http://...' + * onComplete: function () {} + * }) + * .add({ + * url: 'https://...', + * onComplete: function () {}, + * crossOrigin: true + * }) + * + * // you can also pass an array of objects or urls or both + * .add([ + * { name: 'key4', url: 'http://...', onComplete: function () {} }, + * { url: 'http://...', onComplete: function () {} }, + * 'http://...' + * ]) + * + * // and you can use both params and options + * .add('key', 'http://...', { crossOrigin: true }, function () {}) + * .add('http://...', { crossOrigin: true }, function () {}); + * ``` + * + * @param {string} [name] - The name of the resource to load, if not passed the url is used. + * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @param {object} [options] - The options for the load. + * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should + * the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @param {function} [cb] - Function to call when this specific resource completes loading. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.add = function add(name, url, options, cb) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + + return this; + } + + // if an object is passed instead of params + if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') { + cb = url || name.callback || name.onComplete; + options = name; + url = name.url; + name = name.name || name.key || name.url; + } + + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + cb = options; + options = url; + url = name; + } + + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + cb = options; + options = null; + } + + // if loading already you can only add resources that have a parent. + if (this.loading && (!options || !options.parentResource)) { + throw new Error('Cannot add resources while the loader is running.'); + } + + // check if resource already exists. + if (this.resources[name]) { + throw new Error('Resource named "' + name + '" already exists.'); + } + + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + + // create the store the resource + this.resources[name] = new _Resource2.default(name, url, options); + + if (typeof cb === 'function') { + this.resources[name].onAfterMiddleware.once(cb); + } + + // if actively loading, make sure to adjust progress chunks for that parent and its children + if (this.loading) { + var parent = options.parentResource; + var incompleteChildren = []; + + for (var _i = 0; _i < parent.children.length; ++_i) { + if (!parent.children[_i].isComplete) { + incompleteChildren.push(parent.children[_i]); + } + } + + var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent + var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child + + parent.children.push(this.resources[name]); + parent.progressChunk = eachChunk; + + for (var _i2 = 0; _i2 < incompleteChildren.length; ++_i2) { + incompleteChildren[_i2].progressChunk = eachChunk; + } + + this.resources[name].progressChunk = eachChunk; + } + + // add the resource to the queue + this._queue.push(this.resources[name]); + + return this; + }; + + /** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * + * @method before + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.pre = function pre(fn) { + this._beforeMiddleware.push(fn); + + return this; + }; + + /** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * + * @alias use + * @method after + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.use = function use(fn) { + this._afterMiddleware.push(fn); + + return this; + }; + + /** + * Resets the queue of the loader to prepare for a new load. + * + * @return {Loader} Returns itself. + */ + + + Loader.prototype.reset = function reset() { + this.progress = 0; + this.loading = false; + + this._queue.kill(); + this._queue.pause(); + + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + + if (res._onLoadBinding) { + res._onLoadBinding.detach(); + } + + if (res.isLoading) { + res.abort(); + } + } + + this.resources = {}; + + return this; + }; + + /** + * Starts loading the queued resources. + * + * @param {function} [cb] - Optional callback that will be bound to the `complete` event. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.load = function load(cb) { + // register complete callback if they pass one + if (typeof cb === 'function') { + this.onComplete.once(cb); + } + + // if the queue has already started we are done here + if (this.loading) { + return this; + } + + if (this._queue.idle()) { + this._onStart(); + this._onComplete(); + } else { + // distribute progress chunks + var numTasks = this._queue._tasks.length; + var chunk = 100 / numTasks; + + for (var i = 0; i < this._queue._tasks.length; ++i) { + this._queue._tasks[i].data.progressChunk = chunk; + } + + // notify we are starting + this._onStart(); + + // start loading + this._queue.resume(); + } + + return this; + }; + + /** + * The number of resources to load concurrently. + * + * @member {number} + * @default 10 + */ + + + /** + * Prepares a url for usage based on the configuration of this object + * + * @private + * @param {string} url - The url to prepare. + * @return {string} The prepared url. + */ + Loader.prototype._prepareUrl = function _prepareUrl(url) { + var parsedUrl = (0, _parseUri2.default)(url, { strictMode: true }); + var result = void 0; + + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { + result = url; + } + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + else if (this.baseUrl.length && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 && url.charAt(0) !== '/') { + result = this.baseUrl + '/' + url; + } else { + result = this.baseUrl + url; + } + + // if we need to add a default querystring, there is a bit more work + if (this.defaultQueryString) { + var hash = rgxExtractUrlHash.exec(result)[0]; + + result = result.substr(0, result.length - hash.length); + + if (result.indexOf('?') !== -1) { + result += '&' + this.defaultQueryString; + } else { + result += '?' + this.defaultQueryString; + } + + result += hash; + } + + return result; + }; + + /** + * Loads a single resource. + * + * @private + * @param {Resource} resource - The resource to load. + * @param {function} dequeue - The function to call when we need to dequeue this item. + */ + + + Loader.prototype._loadResource = function _loadResource(resource, dequeue) { + var _this2 = this; + + resource._dequeue = dequeue; + + // run before middleware + async.eachSeries(this._beforeMiddleware, function (fn, next) { + fn.call(_this2, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, function () { + if (resource.isComplete) { + _this2._onLoad(resource); + } else { + resource._onLoadBinding = resource.onComplete.once(_this2._onLoad, _this2); + resource.load(); + } + }, true); + }; + + /** + * Called once loading has started. + * + * @private + */ + + + Loader.prototype._onStart = function _onStart() { + this.progress = 0; + this.loading = true; + this.onStart.dispatch(this); + }; + + /** + * Called once each resource has loaded. + * + * @private + */ + + + Loader.prototype._onComplete = function _onComplete() { + this.progress = MAX_PROGRESS; + this.loading = false; + this.onComplete.dispatch(this, this.resources); + }; + + /** + * Called each time a resources is loaded. + * + * @private + * @param {Resource} resource - The resource that was loaded + */ + + + Loader.prototype._onLoad = function _onLoad(resource) { + var _this3 = this; + + resource._onLoadBinding = null; + + // remove this resource from the async queue, and add it to our list of resources that are being parsed + this._resourcesParsing.push(resource); + resource._dequeue(); + + // run all the after middleware for this resource + async.eachSeries(this._afterMiddleware, function (fn, next) { + fn.call(_this3, resource, next); + }, function () { + resource.onAfterMiddleware.dispatch(resource); + + _this3.progress += resource.progressChunk; + _this3.onProgress.dispatch(_this3, resource); + + if (resource.error) { + _this3.onError.dispatch(resource.error, _this3, resource); + } else { + _this3.onLoad.dispatch(_this3, resource); + } + + _this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1); + + // do completion check + if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) { + _this3._onComplete(); + } + }, true); + }; + + _createClass(Loader, [{ + key: 'concurrency', + get: function get() { + return this._queue.concurrency; + } + // eslint-disable-next-line require-jsdoc + , + set: function set(concurrency) { + this._queue.concurrency = concurrency; + } + }]); + + return Loader; +}(); + +exports.default = Loader; + +},{"./Resource":33,"./async":34,"mini-signals":5,"parse-uri":7}],33:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// tests is CORS is supported in XHR, if not we need to use XDR +var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest())); +var tempAnchor = null; + +// some status constants +var STATUS_NONE = 0; +var STATUS_OK = 200; +var STATUS_EMPTY = 204; +var STATUS_IE_BUG_EMPTY = 1223; +var STATUS_TYPE_OK = 2; + +// noop +function _noop() {} /* empty */ + +/** + * Manages the state and loading of a resource and all child resources. + * + * @class + */ + +var Resource = function () { + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. + */ + Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) { + setExtMap(Resource._loadTypeMap, extname, loadType); + }; + + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ + + + Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); + }; + + /** + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass + * an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @param {string|string[]} [options.metadata.mimeType] - The mime type to use for the source element of a video/audio + * elment. If the urls are an array, you can pass this as an array as well where each index is the mime type to + * use for the corresponding url index. + */ + + + function Resource(name, url, options) { + _classCallCheck(this, Resource); + + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + + options = options || {}; + + /** + * The state flags of this resource. + * + * @member {number} + */ + this._flags = 0; + + // set data url flag, needs to be set early for some _determineX checks to work. + this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); + + /** + * The name of this resource. + * + * @member {string} + * @readonly + */ + this.name = name; + + /** + * The url used to load this resource. + * + * @member {string} + * @readonly + */ + this.url = url; + + /** + * The extension used to load this resource. + * + * @member {string} + * @readonly + */ + this.extension = this._getExtension(); + + /** + * The data that was loaded by the resource. + * + * @member {any} + */ + this.data = null; + + /** + * Is this request cross-origin? If unset, determined automatically. + * + * @member {string} + */ + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + + /** + * The method of loading to use for this resource. + * + * @member {Resource.LOAD_TYPE} + */ + this.loadType = options.loadType || this._determineLoadType(); + + /** + * The type used to load the resource via XHR. If unset, determined automatically. + * + * @member {string} + */ + this.xhrType = options.xhrType; + + /** + * Extra info for middleware, and controlling specifics about how the resource loads. + * + * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + * Meaning it will modify it as it sees fit. + * + * @member {object} + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources + * to. + */ + this.metadata = options.metadata || {}; + + /** + * The error that occurred while loading (if any). + * + * @member {Error} + * @readonly + */ + this.error = null; + + /** + * The XHR object that was used to load this resource. This is only set + * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * + * @member {XMLHttpRequest} + * @readonly + */ + this.xhr = null; + + /** + * The child resources this resource owns. + * + * @member {Resource[]} + * @readonly + */ + this.children = []; + + /** + * The resource type. + * + * @member {Resource.TYPE} + * @readonly + */ + this.type = Resource.TYPE.UNKNOWN; + + /** + * The progress chunk owned by this resource. + * + * @member {number} + * @readonly + */ + this.progressChunk = 0; + + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * + * @private + * @member {function} + */ + this._dequeue = _noop; + + /** + * Used a storage place for the on load binding used privately by the loader. + * + * @private + * @member {function} + */ + this._onLoadBinding = null; + + /** + * The `complete` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundComplete = this.complete.bind(this); + + /** + * The `_onError` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnError = this._onError.bind(this); + + /** + * The `_onProgress` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnProgress = this._onProgress.bind(this); + + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + this._boundXdrOnTimeout = this._xdrOnTimeout.bind(this); + + /** + * Dispatched when the resource beings to load. + * + * The callback looks like {@link Resource.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched each time progress of this resource load updates. + * Not all resources types and loader systems can support this event + * so sometimes it may not be available. If the resource + * is being loaded on a modern browser, using XHR, and the remote server + * properly sets Content-Length headers, then this will be available. + * + * The callback looks like {@link Resource.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once this resource has loaded, if there was an error it will + * be in the `error` property. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * Dispatched after this resource has had all the *after* middleware run on it. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onAfterMiddleware = new _miniSignals2.default(); + + /** + * When the resource starts to load. + * + * @memberof Resource + * @callback OnStartSignal + * @param {Resource} resource - The resource that the event happened on. + */ + + /** + * When the resource reports loading progress. + * + * @memberof Resource + * @callback OnProgressSignal + * @param {Resource} resource - The resource that the event happened on. + * @param {number} percentage - The progress of the load in the range [0, 1]. + */ + + /** + * When the resource finishes loading. + * + * @memberof Resource + * @callback OnCompleteSignal + * @param {Resource} resource - The resource that the event happened on. + */ + } + + /** + * Stores whether or not this url is a data url. + * + * @member {boolean} + * @readonly + */ + + + /** + * Marks the resource as complete. + * + */ + Resource.prototype.complete = function complete() { + // TODO: Clean this up in a wrapper or something...gross.... + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + + this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true); + this._setFlag(Resource.STATUS_FLAGS.LOADING, false); + + this.onComplete.dispatch(this); + }; + + /** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ + + + Resource.prototype.abort = function abort(message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + + // store error + this.error = new Error(message); + + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } else if (this.xdr) { + this.xdr.abort(); + } else if (this.data) { + // single source + if (this.data.src) { + this.data.src = Resource.EMPTY_GIF; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + + // done now. + this.complete(); + }; + + /** + * Kicks off loading of this resource. This method is asynchronous. + * + * @param {function} [cb] - Optional callback to call once the resource is loaded. + */ + + + Resource.prototype.load = function load(cb) { + var _this = this; + + if (this.isLoading) { + return; + } + + if (this.isComplete) { + if (cb) { + setTimeout(function () { + return cb(_this); + }, 1); + } + + return; + } else if (cb) { + this.onComplete.once(cb); + } + + this._setFlag(Resource.STATUS_FLAGS.LOADING, true); + + this.onStart.dispatch(this); + + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + + switch (this.loadType) { + case Resource.LOAD_TYPE.IMAGE: + this.type = Resource.TYPE.IMAGE; + this._loadElement('image'); + break; + + case Resource.LOAD_TYPE.AUDIO: + this.type = Resource.TYPE.AUDIO; + this._loadSourceElement('audio'); + break; + + case Resource.LOAD_TYPE.VIDEO: + this.type = Resource.TYPE.VIDEO; + this._loadSourceElement('video'); + break; + + case Resource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } else { + this._loadXhr(); + } + break; + } + }; + + /** + * Checks if the flag is set. + * + * @private + * @param {number} flag - The flag to check. + * @return {boolean} True if the flag is set. + */ + + + Resource.prototype._hasFlag = function _hasFlag(flag) { + return !!(this._flags & flag); + }; + + /** + * (Un)Sets the flag. + * + * @private + * @param {number} flag - The flag to (un)set. + * @param {boolean} value - Whether to set or (un)set the flag. + */ + + + Resource.prototype._setFlag = function _setFlag(flag, value) { + this._flags = value ? this._flags | flag : this._flags & ~flag; + }; + + /** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadElement = function _loadElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'image' && typeof window.Image !== 'undefined') { + this.data = new Image(); + } else { + this.data = document.createElement(type); + } + + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + }; + + /** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadSourceElement = function _loadSourceElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'audio' && typeof window.Audio !== 'undefined') { + this.data = new Audio(); + } else { + this.data = document.createElement(type); + } + + if (this.data === null) { + this.abort('Unsupported element: ' + type); + + return; + } + + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } else if (Array.isArray(this.url)) { + var mimeTypes = this.metadata.mimeType; + + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes)); + } + } else { + var _mimeTypes = this.metadata.mimeType; + + this.data.appendChild(this._createSource(type, this.url, Array.isArray(_mimeTypes) ? _mimeTypes[0] : _mimeTypes)); + } + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + + this.data.load(); + }; + + /** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ + + + Resource.prototype._loadXhr = function _loadXhr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xhr = this.xhr = new XMLHttpRequest(); + + // set the request type and url + xhr.open('GET', this.url, true); + + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; + } else { + xhr.responseType = this.xhrType; + } + + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + + xhr.send(); + }; + + /** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ + + + Resource.prototype._loadXdr = function _loadXdr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xdr = this.xhr = new XDomainRequest(); + + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = 5000; + + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXdrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + + xdr.open('GET', this.url, true); + + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { + return xdr.send(); + }, 1); + }; + + /** + * Creates a source used in loading via an element. + * + * @private + * @param {string} type - The element type (video or audio). + * @param {string} url - The source URL to load from. + * @param {string} [mime] - The mime type of the video + * @return {HTMLSourceElement} The source element. + */ + + + Resource.prototype._createSource = function _createSource(type, url, mime) { + if (!mime) { + mime = type + '/' + this._getExtension(url); + } + + var source = document.createElement('source'); + + source.src = url; + source.type = mime; + + return source; + }; + + /** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ + + + Resource.prototype._onError = function _onError(event) { + this.abort('Failed to load element using: ' + event.target.nodeName); + }; + + /** + * Called if a load progress event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ + + + Resource.prototype._onProgress = function _onProgress(event) { + if (event && event.lengthComputable) { + this.onProgress.dispatch(this, event.loaded / event.total); + } + }; + + /** + * Called if an error event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestErrorEvent|Event} event - Error event. + */ + + + Resource.prototype._xhrOnError = function _xhrOnError() { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"'); + }; + + /** + * Called if an abort event fires for xhr. + * + * @private + * @param {XMLHttpRequestAbortEvent} event - Abort Event + */ + + + Resource.prototype._xhrOnAbort = function _xhrOnAbort() { + this.abort(reqType(this.xhr) + ' Request was aborted by the user.'); + }; + + /** + * Called if a timeout event fires for xdr. + * + * @private + * @param {Event} event - Timeout event. + */ + + + Resource.prototype._xdrOnTimeout = function _xdrOnTimeout() { + this.abort(reqType(this.xhr) + ' Request timed out.'); + }; + + /** + * Called when data successfully loads from an xhr/xdr request. + * + * @private + * @param {XMLHttpRequestLoadEvent|Event} event - Load event + */ + + + Resource.prototype._xhrOnLoad = function _xhrOnLoad() { + var xhr = this.xhr; + var text = ''; + var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200. + + // responseText is accessible only if responseType is '' or 'text' and on older browsers + if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') { + text = xhr.responseText; + } + + // status can be 0 when using the `file://` protocol so we also check if a response is set. + // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request. + if (status === STATUS_NONE && (text.length > 0 || xhr.responseType === Resource.XHR_RESPONSE_TYPE.BUFFER)) { + status = STATUS_OK; + } + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + else if (status === STATUS_IE_BUG_EMPTY) { + status = STATUS_EMPTY; + } + + var statusType = status / 100 | 0; + + if (statusType === STATUS_TYPE_OK) { + // if text, just return it + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { + this.data = text; + this.type = Resource.TYPE.TEXT; + } + // if json, parse into json object + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(text); + this.type = Resource.TYPE.JSON; + } catch (e) { + this.abort('Error trying to parse loaded json: ' + e); + + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (window.DOMParser) { + var domparser = new DOMParser(); + + this.data = domparser.parseFromString(text, 'text/xml'); + } else { + var div = document.createElement('div'); + + div.innerHTML = text; + + this.data = div; + } + + this.type = Resource.TYPE.XML; + } catch (e) { + this.abort('Error trying to parse loaded xml: ' + e); + + return; + } + } + // other types just return the response + else { + this.data = xhr.response || text; + } + } else { + this.abort('[' + xhr.status + '] ' + xhr.statusText + ': ' + xhr.responseURL); + + return; + } + + this.complete(); + }; + + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * + * @private + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ + + + Resource.prototype._determineCrossOrigin = function _determineCrossOrigin(url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = (0, _parseUri2.default)(tempAnchor.href, { strictMode: true }); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + var protocol = url.protocol ? url.protocol + ':' : ''; + + // if cross origin + if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; + }; + + /** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. + */ + + + Resource.prototype._determineXhrType = function _determineXhrType() { + return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT; + }; + + /** + * Determines the loadType of a resource based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.LOAD_TYPE} The loadType to use. + */ + + + Resource.prototype._determineLoadType = function _determineLoadType() { + return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR; + }; + + /** + * Extracts the extension (sans '.') of the file being loaded by the resource. + * + * @private + * @return {string} The extension. + */ + + + Resource.prototype._getExtension = function _getExtension() { + var url = this.url; + var ext = ''; + + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } else { + var queryStart = url.indexOf('?'); + var hashStart = url.indexOf('#'); + var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length); + + url = url.substring(0, index); + ext = url.substring(url.lastIndexOf('.') + 1); + } + + return ext.toLowerCase(); + }; + + /** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * + * @private + * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. + * @return {string} The mime type to use. + */ + + + Resource.prototype._getMimeFromXhrType = function _getMimeFromXhrType(type) { + switch (type) { + case Resource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + + case Resource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + + case Resource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + + case Resource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + + case Resource.XHR_RESPONSE_TYPE.DEFAULT: + case Resource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + + } + }; + + _createClass(Resource, [{ + key: 'isDataUrl', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL); + } + + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isComplete', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE); + } + + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isLoading', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.LOADING); + } + }]); + + return Resource; +}(); + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ + + +exports.default = Resource; +Resource.STATUS_FLAGS = { + NONE: 0, + DATA_URL: 1 << 0, + COMPLETE: 1 << 1, + LOADING: 1 << 2 +}; + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ +Resource.TYPE = { + UNKNOWN: 0, + JSON: 1, + XML: 2, + IMAGE: 3, + AUDIO: 4, + VIDEO: 5, + TEXT: 6 +}; + +/** + * The types of loading a resource can use. + * + * @static + * @readonly + * @enum {number} + */ +Resource.LOAD_TYPE = { + /** Uses XMLHttpRequest to load the resource. */ + XHR: 1, + /** Uses an `Image` object to load the resource. */ + IMAGE: 2, + /** Uses an `Audio` object to load the resource. */ + AUDIO: 3, + /** Uses a `Video` object to load the resource. */ + VIDEO: 4 +}; + +/** + * The XHR ready states, used internally. + * + * @static + * @readonly + * @enum {string} + */ +Resource.XHR_RESPONSE_TYPE = { + /** string */ + DEFAULT: 'text', + /** ArrayBuffer */ + BUFFER: 'arraybuffer', + /** Blob */ + BLOB: 'blob', + /** Document */ + DOCUMENT: 'document', + /** Object */ + JSON: 'json', + /** String */ + TEXT: 'text' +}; + +Resource._loadTypeMap = { + // images + gif: Resource.LOAD_TYPE.IMAGE, + png: Resource.LOAD_TYPE.IMAGE, + bmp: Resource.LOAD_TYPE.IMAGE, + jpg: Resource.LOAD_TYPE.IMAGE, + jpeg: Resource.LOAD_TYPE.IMAGE, + tif: Resource.LOAD_TYPE.IMAGE, + tiff: Resource.LOAD_TYPE.IMAGE, + webp: Resource.LOAD_TYPE.IMAGE, + tga: Resource.LOAD_TYPE.IMAGE, + svg: Resource.LOAD_TYPE.IMAGE, + 'svg+xml': Resource.LOAD_TYPE.IMAGE, // for SVG data urls + + // audio + mp3: Resource.LOAD_TYPE.AUDIO, + ogg: Resource.LOAD_TYPE.AUDIO, + wav: Resource.LOAD_TYPE.AUDIO, + + // videos + mp4: Resource.LOAD_TYPE.VIDEO, + webm: Resource.LOAD_TYPE.VIDEO +}; + +Resource._xhrTypeMap = { + // xml + xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. + // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, + // this should probably be fine. + tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // images + gif: Resource.XHR_RESPONSE_TYPE.BLOB, + png: Resource.XHR_RESPONSE_TYPE.BLOB, + bmp: Resource.XHR_RESPONSE_TYPE.BLOB, + jpg: Resource.XHR_RESPONSE_TYPE.BLOB, + jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, + tif: Resource.XHR_RESPONSE_TYPE.BLOB, + tiff: Resource.XHR_RESPONSE_TYPE.BLOB, + webp: Resource.XHR_RESPONSE_TYPE.BLOB, + tga: Resource.XHR_RESPONSE_TYPE.BLOB, + + // json + json: Resource.XHR_RESPONSE_TYPE.JSON, + + // text + text: Resource.XHR_RESPONSE_TYPE.TEXT, + txt: Resource.XHR_RESPONSE_TYPE.TEXT, + + // fonts + ttf: Resource.XHR_RESPONSE_TYPE.BUFFER, + otf: Resource.XHR_RESPONSE_TYPE.BUFFER +}; + +// We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif +Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; + +/** + * Quick helper to set a value on one of the extension maps. Ensures there is no + * dot at the start of the extension. + * + * @ignore + * @param {object} map - The map to set on. + * @param {string} extname - The extension (or key) to set. + * @param {number} val - The value to set. + */ +function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + + if (!extname) { + return; + } + + map[extname] = val; +} + +/** + * Quick helper to get string xhr type. + * + * @ignore + * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. + * @return {string} The type. + */ +function reqType(xhr) { + return xhr.toString().replace('object ', ''); +} + +},{"mini-signals":5,"parse-uri":7}],34:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.eachSeries = eachSeries; +exports.queue = queue; +/** + * Smaller version of the async library constructs. + * + */ +function _noop() {} /* empty */ + +/** + * Iterates an array in series. + * + * @param {Array.<*>} array - Array to iterate. + * @param {function} iterator - Function to call for each element. + * @param {function} callback - Function to call when done, or on error. + * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1. + */ +function eachSeries(array, iterator, callback, deferNext) { + var i = 0; + var len = array.length; + + (function next(err) { + if (err || i === len) { + if (callback) { + callback(err); + } + + return; + } + + if (deferNext) { + setTimeout(function () { + iterator(array[i++], next); + }, 1); + } else { + iterator(array[i++], next); + } + })(); +} + +/** + * Ensures a function is only called once. + * + * @param {function} fn - The function to wrap. + * @return {function} The wrapping function. + */ +function onlyOnce(fn) { + return function onceWrapper() { + if (fn === null) { + throw new Error('Callback was already called.'); + } + + var callFn = fn; + + fn = null; + callFn.apply(this, arguments); + }; +} + +/** + * Async queue implementation, + * + * @param {function} worker - The worker function to call for each task. + * @param {number} concurrency - How many workers to run in parrallel. + * @return {*} The async queue object. + */ +function queue(worker, concurrency) { + if (concurrency == null) { + // eslint-disable-line no-eq-null,eqeqeq + concurrency = 1; + } else if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + + var workers = 0; + var q = { + _tasks: [], + concurrency: concurrency, + saturated: _noop, + unsaturated: _noop, + buffer: concurrency / 4, + empty: _noop, + drain: _noop, + error: _noop, + started: false, + paused: false, + push: function push(data, callback) { + _insert(data, false, callback); + }, + kill: function kill() { + workers = 0; + q.drain = _noop; + q.started = false; + q._tasks = []; + }, + unshift: function unshift(data, callback) { + _insert(data, true, callback); + }, + process: function process() { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var task = q._tasks.shift(); + + if (q._tasks.length === 0) { + q.empty(); + } + + workers += 1; + + if (workers === q.concurrency) { + q.saturated(); + } + + worker(task.data, onlyOnce(_next(task))); + } + }, + length: function length() { + return q._tasks.length; + }, + running: function running() { + return workers; + }, + idle: function idle() { + return q._tasks.length + workers === 0; + }, + pause: function pause() { + if (q.paused === true) { + return; + } + + q.paused = true; + }, + resume: function resume() { + if (q.paused === false) { + return; + } + + q.paused = false; + + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= q.concurrency; w++) { + q.process(); + } + } + }; + + function _insert(data, insertAtFront, callback) { + if (callback != null && typeof callback !== 'function') { + // eslint-disable-line no-eq-null,eqeqeq + throw new Error('task callback must be a function'); + } + + q.started = true; + + if (data == null && q.idle()) { + // eslint-disable-line no-eq-null,eqeqeq + // call drain immediately if there are no tasks + setTimeout(function () { + return q.drain(); + }, 1); + + return; + } + + var item = { + data: data, + callback: typeof callback === 'function' ? callback : _noop + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + setTimeout(function () { + return q.process(); + }, 1); + } + + function _next(task) { + return function next() { + workers -= 1; + + task.callback.apply(task, arguments); + + if (arguments[0] != null) { + // eslint-disable-line no-eq-null,eqeqeq + q.error(arguments[0], task.data); + } + + if (workers <= q.concurrency - q.buffer) { + q.unsaturated(); + } + + if (q.idle()) { + q.drain(); + } + + q.process(); + }; + } + + return q; +} + +},{}],35:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.encodeBinary = encodeBinary; +var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +function encodeBinary(input) { + var output = ''; + var inx = 0; + + while (inx < input.length) { + // Fill byte buffer array + var bytebuffer = [0, 0, 0]; + var encodedCharIndexes = [0, 0, 0, 0]; + + for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } else { + bytebuffer[jnx] = 0; + } + } + + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4; + + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6; + + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + + // Determine whether padding happened, and adjust accordingly + var paddingBytes = inx - (input.length - 1); + + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + + default: + break; // No padding - proceed + } + + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) { + output += _keyStr.charAt(encodedCharIndexes[_jnx]); + } + } + + return output; +} + +},{}],36:[function(require,module,exports){ +'use strict'; + +// import Loader from './Loader'; +// import Resource from './Resource'; +// import * as async from './async'; +// import * as b64 from './b64'; + +/* eslint-disable no-undef */ + +var Loader = require('./Loader').default; +var Resource = require('./Resource').default; +var async = require('./async'); +var b64 = require('./b64'); + +Loader.Resource = Resource; +Loader.async = async; +Loader.base64 = b64; + +// export manually, and also as default +module.exports = Loader; +// export default Loader; +module.exports.default = Loader; + +},{"./Loader":32,"./Resource":33,"./async":34,"./b64":35}],37:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +exports.blobMiddlewareFactory = blobMiddlewareFactory; + +var _Resource = require('../../Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +var _b = require('../../b64'); + +var _b2 = _interopRequireDefault(_b); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Url = window.URL || window.webkitURL; + +// a middleware for transforming XHR loaded Blobs into more useful objects +function blobMiddlewareFactory() { + return function blobMiddleware(resource, next) { + if (!resource.data) { + next(); + + return; + } + + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === _Resource2.default.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!window.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = 'data:' + type + ';base64,' + _b2.default.encodeBinary(resource.xhr.responseText); + + resource.type = _Resource2.default.TYPE.IMAGE; + + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + + next(); + }; + + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var _ret = function () { + var src = Url.createObjectURL(resource.data); + + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src; + + resource.type = _Resource2.default.TYPE.IMAGE; + + // cleanup the no longer used blob after the image loads + // TODO: Is this correct? Will the image be invalid after revoking? + resource.data.onload = function () { + Url.revokeObjectURL(src); + resource.data.onload = null; + + next(); + }; + + // next will be called on load. + return { + v: void 0 + }; + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + } + + next(); + }; +} + +},{"../../Resource":33,"../../b64":35}],38:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":39,"punycode":27,"querystring":30}],39:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],40:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +var _accessibleTarget = require('./accessibleTarget'); + +var _accessibleTarget2 = _interopRequireDefault(_accessibleTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// add some extra variables to the container.. +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _accessibleTarget2.default); + +var KEY_CODE_TAB = 9; + +var DIV_TOUCH_SIZE = 100; +var DIV_TOUCH_POS_X = 0; +var DIV_TOUCH_POS_Y = 0; +var DIV_TOUCH_ZINDEX = 2; + +var DIV_HOOK_SIZE = 1; +var DIV_HOOK_POS_X = -1000; +var DIV_HOOK_POS_Y = -1000; +var DIV_HOOK_ZINDEX = 2; + +/** + * The Accessibility manager recreates the ability to tab and have content read by screen + * readers. This is very important as it can possibly help people with disabilities access pixi + * content. + * + * Much like interaction any DisplayObject can be made accessible. This manager will map the + * events as if the mouse was being used, minimizing the effort required to implement. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.accessibility + * + * @class + * @memberof PIXI.accessibility + */ + +var AccessibilityManager = function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + _classCallCheck(this, AccessibilityManager); + + if ((_ismobilejs2.default.tablet || _ismobilejs2.default.phone) && !navigator.isCocoonJS) { + this.createTouchHook(); + } + + // first we create a div that will sit over the PixiJS element. This is where the div overlays will go. + var div = document.createElement('div'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + 'px'; + div.style.left = DIV_TOUCH_POS_Y + 'px'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + + /** + * This is the dom element that will sit over the PixiJS element. This is where the div overlays will go. + * + * @type {HTMLElement} + * @private + */ + this.div = div; + + /** + * A simple pool for storing divs. + * + * @type {*} + * @private + */ + this.pool = []; + + /** + * This is a tick used to check if an object is no longer being rendered. + * + * @type {Number} + * @private + */ + this.renderId = 0; + + /** + * Setting this to true will visually show the divs. + * + * @type {boolean} + */ + this.debug = false; + + /** + * The renderer this accessibility manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * The array of currently active accessible items. + * + * @member {Array<*>} + * @private + */ + this.children = []; + + /** + * pre-bind the functions + * + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + + /** + * stores the state of the manager. If there are no accessible objects or the mouse is moving, this will be false. + * + * @member {Array<*>} + * @private + */ + this.isActive = false; + this.isMobileAccessabillity = false; + + // let listen for tab.. once pressed we can fire up and show the accessibility layer + window.addEventListener('keydown', this._onKeyDown, false); + } + + /** + * Creates the touch hooks. + * + */ + + + AccessibilityManager.prototype.createTouchHook = function createTouchHook() { + var _this = this; + + var hookDiv = document.createElement('button'); + + hookDiv.style.width = DIV_HOOK_SIZE + 'px'; + hookDiv.style.height = DIV_HOOK_SIZE + 'px'; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + 'px'; + hookDiv.style.left = DIV_HOOK_POS_Y + 'px'; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX; + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'HOOK DIV'; + + hookDiv.addEventListener('focus', function () { + _this.isMobileAccessabillity = true; + _this.activate(); + document.body.removeChild(hookDiv); + }); + + document.body.appendChild(hookDiv); + }; + + /** + * Activating will cause the Accessibility layer to be shown. This is called when a user + * preses the tab key. + * + * @private + */ + + + AccessibilityManager.prototype.activate = function activate() { + if (this.isActive) { + return; + } + + this.isActive = true; + + window.document.addEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown, false); + + this.renderer.on('postrender', this.update, this); + + if (this.renderer.view.parentNode) { + this.renderer.view.parentNode.appendChild(this.div); + } + }; + + /** + * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves + * the mouse. + * + * @private + */ + + + AccessibilityManager.prototype.deactivate = function deactivate() { + if (!this.isActive || this.isMobileAccessabillity) { + return; + } + + this.isActive = false; + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.addEventListener('keydown', this._onKeyDown, false); + + this.renderer.off('postrender', this.update); + + if (this.div.parentNode) { + this.div.parentNode.removeChild(this.div); + } + }; + + /** + * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. + * + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + + + AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects(displayObject) { + if (!displayObject.visible) { + return; + } + + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + + displayObject.renderId = this.renderId; + } + + var children = displayObject.children; + + for (var i = 0; i < children.length; i++) { + this.updateAccessibleObjects(children[i]); + } + }; + + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * + * @private + */ + + + AccessibilityManager.prototype.update = function update() { + if (!this.renderer.renderingToScreen) { + return; + } + + // update children... + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + + var rect = this.renderer.view.getBoundingClientRect(); + var sx = rect.width / this.renderer.width; + var sy = rect.height / this.renderer.height; + + var div = this.div; + + div.style.left = rect.left + 'px'; + div.style.top = rect.top + 'px'; + div.style.width = this.renderer.width + 'px'; + div.style.height = this.renderer.height + 'px'; + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + + core.utils.removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + + i--; + + if (this.children.length === 0) { + this.deactivate(); + } + } else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + + if (child.hitArea) { + div.style.left = (wt.tx + hitArea.x * wt.a) * sx + 'px'; + div.style.top = (wt.ty + hitArea.y * wt.d) * sy + 'px'; + + div.style.width = hitArea.width * wt.a * sx + 'px'; + div.style.height = hitArea.height * wt.d * sy + 'px'; + } else { + hitArea = child.getBounds(); + + this.capHitArea(hitArea); + + div.style.left = hitArea.x * sx + 'px'; + div.style.top = hitArea.y * sy + 'px'; + + div.style.width = hitArea.width * sx + 'px'; + div.style.height = hitArea.height * sy + 'px'; + + // update button titles and hints if they exist and they've changed + if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) { + div.title = child.accessibleTitle; + } + if (div.getAttribute('aria-label') !== child.accessibleHint && child.accessibleHint !== null) { + div.setAttribute('aria-label', child.accessibleHint); + } + } + } + } + + // increment the render id.. + this.renderId++; + }; + + /** + * TODO: docs. + * + * @param {Rectangle} hitArea - TODO docs + */ + + + AccessibilityManager.prototype.capHitArea = function capHitArea(hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + + if (hitArea.x + hitArea.width > this.renderer.width) { + hitArea.width = this.renderer.width - hitArea.x; + } + + if (hitArea.y + hitArea.height > this.renderer.height) { + hitArea.height = this.renderer.height - hitArea.y; + } + }; + + /** + * Adds a DisplayObject to the accessibility manager + * + * @private + * @param {DisplayObject} displayObject - The child to make accessible. + */ + + + AccessibilityManager.prototype.addChild = function addChild(displayObject) { + // this.activate(); + + var div = this.pool.pop(); + + if (!div) { + div = document.createElement('button'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + div.style.borderStyle = 'none'; + + // ARIA attributes ensure that button title and hint updates are announced properly + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + // Chrome doesn't need aria-live to work as intended; in fact it just gets more confused. + div.setAttribute('aria-live', 'off'); + } else { + div.setAttribute('aria-live', 'polite'); + } + + if (navigator.userAgent.match(/rv:.*Gecko\//)) { + // FireFox needs this to announce only the new button name + div.setAttribute('aria-relevant', 'additions'); + } else { + // required by IE, other browsers don't much care + div.setAttribute('aria-relevant', 'text'); + } + + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + + if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) { + div.title = displayObject.accessibleTitle; + } else if (!displayObject.accessibleHint || displayObject.accessibleHint === null) { + div.title = 'displayObject ' + displayObject.tabIndex; + } + + if (displayObject.accessibleHint && displayObject.accessibleHint !== null) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + + // + + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + + /** + * Maps the div button press to pixi's InteractionManager (click) + * + * @private + * @param {MouseEvent} e - The click event. + */ + + + AccessibilityManager.prototype._onClick = function _onClick(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixi's InteractionManager (mouseover) + * + * @private + * @param {FocusEvent} e - The focus event. + */ + + + AccessibilityManager.prototype._onFocus = function _onFocus(e) { + if (!e.target.getAttribute('aria-live', 'off')) { + e.target.setAttribute('aria-live', 'assertive'); + } + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixi's InteractionManager (mouseout) + * + * @private + * @param {FocusEvent} e - The focusout event. + */ + + + AccessibilityManager.prototype._onFocusOut = function _onFocusOut(e) { + if (!e.target.getAttribute('aria-live', 'off')) { + e.target.setAttribute('aria-live', 'polite'); + } + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); + }; + + /** + * Is called when a key is pressed + * + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + + + AccessibilityManager.prototype._onKeyDown = function _onKeyDown(e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + + this.activate(); + }; + + /** + * Is called when the mouse moves across the renderer element + * + * @private + * @param {MouseEvent} e - The mouse event. + */ + + + AccessibilityManager.prototype._onMouseMove = function _onMouseMove(e) { + if (e.movementX === 0 && e.movementY === 0) { + return; + } + + this.deactivate(); + }; + + /** + * Destroys the accessibility manager + * + */ + + + AccessibilityManager.prototype.destroy = function destroy() { + this.div = null; + + for (var i = 0; i < this.children.length; i++) { + this.children[i].div = null; + } + + window.document.removeEventListener('mousemove', this._onMouseMove); + window.removeEventListener('keydown', this._onKeyDown); + + this.pool = null; + this.children = null; + this.renderer = null; + }; + + return AccessibilityManager; +}(); + +exports.default = AccessibilityManager; + + +core.WebGLRenderer.registerPlugin('accessibility', AccessibilityManager); +core.CanvasRenderer.registerPlugin('accessibility', AccessibilityManager); + +},{"../core":65,"./accessibleTarget":41,"ismobilejs":4}],41:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Default property values of accessible objects + * used by {@link PIXI.accessibility.AccessibilityManager}. + * + * @function accessibleTarget + * @memberof PIXI.accessibility + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibility.accessibleTarget + * ); + */ +exports.default = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * + * @member {boolean} + */ + accessible: false, + + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * + * @member {string} + */ + accessibleTitle: null, + + /** + * Sets the aria-label attribute of the shadow div + * + * @member {string} + */ + accessibleHint: null, + + /** + * @todo Needs docs. + */ + tabIndex: 0, + + /** + * @todo Needs docs. + */ + _accessibleActive: false, + + /** + * @todo Needs docs. + */ + _accessibleDiv: false +}; + +},{}],42:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _accessibleTarget = require('./accessibleTarget'); + +Object.defineProperty(exports, 'accessibleTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_accessibleTarget).default; + } +}); + +var _AccessibilityManager = require('./AccessibilityManager'); + +Object.defineProperty(exports, 'AccessibilityManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AccessibilityManager).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./AccessibilityManager":40,"./accessibleTarget":41}],43:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +var _Container = require('./display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _ticker = require('./ticker'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _const = require('./const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Convenience class to create a new PIXI application. + * This class automatically creates the renderer, ticker + * and root container. + * + * @example + * // Create the application + * const app = new PIXI.Application(); + * + * // Add the view to the DOM + * document.body.appendChild(app.view); + * + * // ex, add display objects + * app.stage.addChild(PIXI.Sprite.fromImage('something.png')); + * + * @class + * @memberof PIXI + */ +var Application = function () { + // eslint-disable-next-line valid-jsdoc + /** + * @param {object} [options] - The optional renderer parameters + * @param {boolean} [options.autoStart=true] - automatically starts the rendering after the construction. + * Note that setting this parameter to false does NOT stop the shared ticker even if you set + * options.sharedTicker to true in case that it is already started. Stop it by your own. + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great **webgl only** + * @param {boolean} [options.legacy=false] - `true` to ensure compatibility with older / less advanced devices. + * If you experience unexplained flickering try setting this to true. **webgl only** + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card **webgl only** + * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.ticker.shared, `false` to create new ticker. + * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.loaders.shared, `false` to create new Loader. + */ + function Application(options, arg2, arg3, arg4, arg5) { + _classCallCheck(this, Application); + + // Support for constructor(width, height, options, noWebGL, useSharedTicker) + if (typeof options === 'number') { + options = Object.assign({ + width: options, + height: arg2 || _settings2.default.RENDER_OPTIONS.height, + forceCanvas: !!arg4, + sharedTicker: !!arg5 + }, arg3); + } + + /** + * The default options, so we mixin functionality later. + * @member {object} + * @protected + */ + this._options = options = Object.assign({ + autoStart: true, + sharedTicker: false, + forceCanvas: false, + sharedLoader: false + }, options); + + /** + * WebGL renderer if available, otherwise CanvasRenderer + * @member {PIXI.WebGLRenderer|PIXI.CanvasRenderer} + */ + this.renderer = (0, _autoDetectRenderer.autoDetectRenderer)(options); + + /** + * The root display container that's rendered. + * @member {PIXI.Container} + */ + this.stage = new _Container2.default(); + + /** + * Internal reference to the ticker + * @member {PIXI.ticker.Ticker} + * @private + */ + this._ticker = null; + + /** + * Ticker for doing render updates. + * @member {PIXI.ticker.Ticker} + * @default PIXI.ticker.shared + */ + this.ticker = options.sharedTicker ? _ticker.shared : new _ticker.Ticker(); + + // Start the rendering + if (options.autoStart) { + this.start(); + } + } + + /** + * Render the current stage. + */ + Application.prototype.render = function render() { + this.renderer.render(this.stage); + }; + + /** + * Convenience method for stopping the render. + */ + + + Application.prototype.stop = function stop() { + this._ticker.stop(); + }; + + /** + * Convenience method for starting the render. + */ + + + Application.prototype.start = function start() { + this._ticker.start(); + }; + + /** + * Reference to the renderer's canvas element. + * @member {HTMLCanvasElement} + * @readonly + */ + + + /** + * Destroy and don't use after this. + * @param {Boolean} [removeView=false] Automatically remove canvas from DOM. + * @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy + * method called as well. 'stageOptions' will be passed on to those calls. + * @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set + * to true. Should it destroy the texture of the child sprite + * @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set + * to true. Should it destroy the base texture of the child sprite + */ + Application.prototype.destroy = function destroy(removeView, stageOptions) { + if (this._ticker) { + var oldTicker = this._ticker; + + this.ticker = null; + oldTicker.destroy(); + } + + this.stage.destroy(stageOptions); + this.stage = null; + + this.renderer.destroy(removeView); + this.renderer = null; + + this._options = null; + }; + + _createClass(Application, [{ + key: 'ticker', + set: function set(ticker) // eslint-disable-line require-jsdoc + { + if (this._ticker) { + this._ticker.remove(this.render, this); + } + this._ticker = ticker; + if (ticker) { + ticker.add(this.render, this, _const.UPDATE_PRIORITY.LOW); + } + }, + get: function get() // eslint-disable-line require-jsdoc + { + return this._ticker; + } + }, { + key: 'view', + get: function get() { + return this.renderer.view; + } + + /** + * Reference to the renderer's screen rectangle. Its safe to use as filterArea or hitArea for whole screen + * @member {PIXI.Rectangle} + * @readonly + */ + + }, { + key: 'screen', + get: function get() { + return this.renderer.screen; + } + }]); + + return Application; +}(); + +exports.default = Application; + +},{"./autoDetectRenderer":45,"./const":46,"./display/Container":48,"./settings":101,"./ticker":121}],44:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function checkPrecision(src, def) { + if (src instanceof Array) { + if (src[0].substring(0, 9) !== 'precision') { + var copy = src.slice(0); + + copy.unshift('precision ' + def + ' float;'); + + return copy; + } + } else if (src.trim().substring(0, 9) !== 'precision') { + return 'precision ' + def + ' float;\n' + src; + } + + return src; +} + +/** + * Wrapper class, webGL Shader for Pixi. + * Adds precision string if vertexSrc or fragmentSrc have no mention of it. + * + * @class + * @extends GLShader + * @memberof PIXI + */ + +var Shader = function (_GLShader) { + _inherits(Shader, _GLShader); + + /** + * + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + * @param {string|string[]} vertexSrc - The vertex shader source as an array of strings. + * @param {string|string[]} fragmentSrc - The fragment shader source as an array of strings. + * @param {object} [attributeLocations] - A key value pair showing which location eact attribute should sit. + e.g. {position:0, uvs:1}. + * @param {string} [precision] - The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + */ + function Shader(gl, vertexSrc, fragmentSrc, attributeLocations, precision) { + _classCallCheck(this, Shader); + + return _possibleConstructorReturn(this, _GLShader.call(this, gl, checkPrecision(vertexSrc, precision || _settings2.default.PRECISION_VERTEX), checkPrecision(fragmentSrc, precision || _settings2.default.PRECISION_FRAGMENT), undefined, attributeLocations)); + } + + return Shader; +}(_pixiGlCore.GLShader); + +exports.default = Shader; + +},{"./settings":101,"pixi-gl-core":15}],45:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = autoDetectRenderer; + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// eslint-disable-next-line valid-jsdoc +/** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by + * the browser then this function will return a canvas renderer + * + * @memberof PIXI + * @function autoDetectRenderer + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great **webgl only** + * @param {boolean} [options.legacy=false] - `true` to ensure compatibility with older / less advanced devices. + * If you experience unexplained flickering try setting this to true. **webgl only** + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card **webgl only** + * @return {PIXI.WebGLRenderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ +function autoDetectRenderer(options, arg1, arg2, arg3) { + // Backward-compatible support for noWebGL option + var forceCanvas = options && options.forceCanvas; + + if (arg3 !== undefined) { + forceCanvas = arg3; + } + + if (!forceCanvas && utils.isWebGLSupported()) { + return new _WebGLRenderer2.default(options, arg1, arg2); + } + + return new _CanvasRenderer2.default(options, arg1, arg2); +} + +},{"./renderers/canvas/CanvasRenderer":77,"./renderers/webgl/WebGLRenderer":84,"./utils":125}],46:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * String of the current PIXI version. + * + * @static + * @constant + * @memberof PIXI + * @name VERSION + * @type {string} + */ +var VERSION = exports.VERSION = '4.8.1'; + +/** + * Two Pi. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var PI_2 = exports.PI_2 = Math.PI * 2; + +/** + * Conversion factor for converting radians to degrees. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var RAD_TO_DEG = exports.RAD_TO_DEG = 180 / Math.PI; + +/** + * Conversion factor for converting degrees to radians. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var DEG_TO_RAD = exports.DEG_TO_RAD = Math.PI / 180; + +/** + * Constant to identify the Renderer Type. + * + * @static + * @constant + * @memberof PIXI + * @name RENDERER_TYPE + * @type {object} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ +var RENDERER_TYPE = exports.RENDERER_TYPE = { + UNKNOWN: 0, + WEBGL: 1, + CANVAS: 2 +}; + +/** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * + * @static + * @constant + * @memberof PIXI + * @name BLEND_MODES + * @type {object} + * @property {number} NORMAL + * @property {number} ADD + * @property {number} MULTIPLY + * @property {number} SCREEN + * @property {number} OVERLAY + * @property {number} DARKEN + * @property {number} LIGHTEN + * @property {number} COLOR_DODGE + * @property {number} COLOR_BURN + * @property {number} HARD_LIGHT + * @property {number} SOFT_LIGHT + * @property {number} DIFFERENCE + * @property {number} EXCLUSION + * @property {number} HUE + * @property {number} SATURATION + * @property {number} COLOR + * @property {number} LUMINOSITY + */ +var BLEND_MODES = exports.BLEND_MODES = { + NORMAL: 0, + ADD: 1, + MULTIPLY: 2, + SCREEN: 3, + OVERLAY: 4, + DARKEN: 5, + LIGHTEN: 6, + COLOR_DODGE: 7, + COLOR_BURN: 8, + HARD_LIGHT: 9, + SOFT_LIGHT: 10, + DIFFERENCE: 11, + EXCLUSION: 12, + HUE: 13, + SATURATION: 14, + COLOR: 15, + LUMINOSITY: 16, + NORMAL_NPM: 17, + ADD_NPM: 18, + SCREEN_NPM: 19 +}; + +/** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * + * @static + * @constant + * @memberof PIXI + * @name DRAW_MODES + * @type {object} + * @property {number} POINTS + * @property {number} LINES + * @property {number} LINE_LOOP + * @property {number} LINE_STRIP + * @property {number} TRIANGLES + * @property {number} TRIANGLE_STRIP + * @property {number} TRIANGLE_FAN + */ +var DRAW_MODES = exports.DRAW_MODES = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6 +}; + +/** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @static + * @constant + * @memberof PIXI + * @name SCALE_MODES + * @type {object} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ +var SCALE_MODES = exports.SCALE_MODES = { + LINEAR: 0, + NEAREST: 1 +}; + +/** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as webGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * + * @static + * @constant + * @name WRAP_MODES + * @memberof PIXI + * @type {object} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ +var WRAP_MODES = exports.WRAP_MODES = { + CLAMP: 0, + REPEAT: 1, + MIRRORED_REPEAT: 2 +}; + +/** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * + * @static + * @constant + * @name GC_MODES + * @memberof PIXI + * @type {object} + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ +var GC_MODES = exports.GC_MODES = { + AUTO: 0, + MANUAL: 1 +}; + +/** + * Regexp for image type by extension. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `image.png` + */ +var URL_FILE_EXTENSION = exports.URL_FILE_EXTENSION = /\.(\w{3,4})(?:$|\?|#)/i; + +/** + * Regexp for data URI. + * Based on: {@link https://github.com/ragingwind/data-uri-regex} + * + * @static + * @constant + * @name DATA_URI + * @memberof PIXI + * @type {RegExp|string} + * @example data:image/png;base64 + */ +var DATA_URI = exports.DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i; + +/** + * Regexp for SVG size. + * + * @static + * @constant + * @name SVG_SIZE + * @memberof PIXI + * @type {RegExp|string} + * @example <svg width="100" height="100"></svg> + */ +var SVG_SIZE = exports.SVG_SIZE = /]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len + +/** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * + * @static + * @constant + * @name SHAPES + * @memberof PIXI + * @type {object} + * @property {number} POLY Polygon + * @property {number} RECT Rectangle + * @property {number} CIRC Circle + * @property {number} ELIP Ellipse + * @property {number} RREC Rounded Rectangle + */ +var SHAPES = exports.SHAPES = { + POLY: 0, + RECT: 1, + CIRC: 2, + ELIP: 3, + RREC: 4 +}; + +/** + * Constants that specify float precision in shaders. + * + * @static + * @constant + * @name PRECISION + * @memberof PIXI + * @type {object} + * @property {string} LOW='lowp' + * @property {string} MEDIUM='mediump' + * @property {string} HIGH='highp' + */ +var PRECISION = exports.PRECISION = { + LOW: 'lowp', + MEDIUM: 'mediump', + HIGH: 'highp' +}; + +/** + * Constants that specify the transform type. + * + * @static + * @constant + * @name TRANSFORM_MODE + * @memberof PIXI + * @type {object} + * @property {number} STATIC + * @property {number} DYNAMIC + */ +var TRANSFORM_MODE = exports.TRANSFORM_MODE = { + STATIC: 0, + DYNAMIC: 1 +}; + +/** + * Constants that define the type of gradient on text. + * + * @static + * @constant + * @name TEXT_GRADIENT + * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL Vertical gradient + * @property {number} LINEAR_HORIZONTAL Linear gradient + */ +var TEXT_GRADIENT = exports.TEXT_GRADIENT = { + LINEAR_VERTICAL: 0, + LINEAR_HORIZONTAL: 1 +}; + +/** + * Represents the update priorities used by internal PIXI classes when registered with + * the {@link PIXI.ticker.Ticker} object. Higher priority items are updated first and lower + * priority items, such as render, should go later. + * + * @static + * @constant + * @name UPDATE_PRIORITY + * @memberof PIXI + * @type {object} + * @property {number} INTERACTION=50 Highest priority, used for {@link PIXI.interaction.InteractionManager} + * @property {number} HIGH=25 High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.extras.AnimatedSprite} + * @property {number} NORMAL=0 Default priority for ticker events, see {@link PIXI.ticker.Ticker#add}. + * @property {number} LOW=-25 Low priority used for {@link PIXI.Application} rendering. + * @property {number} UTILITY=-50 Lowest priority used for {@link PIXI.prepare.BasePrepare} utility. + */ +var UPDATE_PRIORITY = exports.UPDATE_PRIORITY = { + INTERACTION: 50, + HIGH: 25, + NORMAL: 0, + LOW: -25, + UTILITY: -50 +}; + +},{}],47:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * 'Builder' pattern for bounds rectangles + * Axis-Aligned Bounding Box + * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems + * + * @class + * @memberof PIXI + */ +var Bounds = function () { + /** + * + */ + function Bounds() { + _classCallCheck(this, Bounds); + + /** + * @member {number} + * @default 0 + */ + this.minX = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.minY = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxX = -Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxY = -Infinity; + + this.rect = null; + } + + /** + * Checks if bounds are empty. + * + * @return {boolean} True if empty. + */ + + + Bounds.prototype.isEmpty = function isEmpty() { + return this.minX > this.maxX || this.minY > this.maxY; + }; + + /** + * Clears the bounds and resets. + * + */ + + + Bounds.prototype.clear = function clear() { + this.updateID++; + + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * + * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty + * @returns {PIXI.Rectangle} A rectangle of the bounds + */ + + + Bounds.prototype.getRectangle = function getRectangle(rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return _math.Rectangle.EMPTY; + } + + rect = rect || new _math.Rectangle(0, 0, 1, 1); + + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + + return rect; + }; + + /** + * This function should be inlined when its possible. + * + * @param {PIXI.Point} point - The point to add. + */ + + + Bounds.prototype.addPoint = function addPoint(point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + }; + + /** + * Adds a quad, not transformed + * + * @param {Float32Array} vertices - The verts to add. + */ + + + Bounds.prototype.addQuad = function addQuad(vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = vertices[0]; + var y = vertices[1]; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds sprite frame, transformed. + * + * @param {PIXI.TransformBase} transform - TODO + * @param {number} x0 - TODO + * @param {number} y0 - TODO + * @param {number} x1 - TODO + * @param {number} y1 - TODO + */ + + + Bounds.prototype.addFrame = function addFrame(transform, x0, y0, x1, y1) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = a * x0 + c * y0 + tx; + var y = b * x0 + d * y0 + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y0 + tx; + y = b * x1 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x0 + c * y1 + tx; + y = b * x0 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y1 + tx; + y = b * x1 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Add an array of vertices + * + * @param {PIXI.TransformBase} transform - TODO + * @param {Float32Array} vertices - TODO + * @param {number} beginOffset - TODO + * @param {number} endOffset - TODO + */ + + + Bounds.prototype.addVertices = function addVertices(transform, vertices, beginOffset, endOffset) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = a * rawX + c * rawY + tx; + var y = d * rawY + b * rawX + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds other Bounds + * + * @param {PIXI.Bounds} bounds - TODO + */ + + + Bounds.prototype.addBounds = function addBounds(bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + }; + + /** + * Adds other Bounds, masked with Bounds + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Bounds} mask - TODO + */ + + + Bounds.prototype.addBoundsMask = function addBoundsMask(bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + /** + * Adds other Bounds, masked with Rectangle + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Rectangle} area - TODO + */ + + + Bounds.prototype.addBoundsArea = function addBoundsArea(bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : area.x + area.width; + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : area.y + area.height; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + return Bounds; +}(); + +exports.default = Bounds; + +},{"../math":70}],48:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _DisplayObject2 = require('./DisplayObject'); + +var _DisplayObject3 = _interopRequireDefault(_DisplayObject2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A Container represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + *```js + * let container = new PIXI.Container(); + * container.addChild(sprite); + * ``` + * + * @class + * @extends PIXI.DisplayObject + * @memberof PIXI + */ +var Container = function (_DisplayObject) { + _inherits(Container, _DisplayObject); + + /** + * + */ + function Container() { + _classCallCheck(this, Container); + + /** + * The array of children of this container. + * + * @member {PIXI.DisplayObject[]} + * @readonly + */ + var _this = _possibleConstructorReturn(this, _DisplayObject.call(this)); + + _this.children = []; + return _this; + } + + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified + * + * @private + */ + + + Container.prototype.onChildrenChange = function onChildrenChange() {} + /* empty */ + + + /** + * Adds one or more children to the container. + * + * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container + * @return {PIXI.DisplayObject} The first child that was added. + */ + ; + + Container.prototype.addChild = function addChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.addChild(arguments[i]); + } + } else { + // if the child has a parent then lets remove it as PixiJS objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.push(child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + child.emit('added', this); + } + + return child; + }; + + /** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @return {PIXI.DisplayObject} The child that was added. + */ + + + Container.prototype.addChildAt = function addChildAt(child, index) { + if (index < 0 || index > this.children.length) { + throw new Error(child + 'addChildAt: The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.splice(index, 0, child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + + return child; + }; + + /** + * Swaps the position of 2 Display Objects within this container. + * + * @param {PIXI.DisplayObject} child - First display object to swap + * @param {PIXI.DisplayObject} child2 - Second display object to swap + */ + + + Container.prototype.swapChildren = function swapChildren(child, child2) { + if (child === child2) { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; + + /** + * Returns the index position of a child DisplayObject instance + * + * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify + * @return {number} The index position of the child display object to identify + */ + + + Container.prototype.getChildIndex = function getChildIndex(child) { + var index = this.children.indexOf(child); + + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + }; + + /** + * Changes the position of an existing child in the display object container + * + * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number + * @param {number} index - The resulting index number for the child display object + */ + + + Container.prototype.setChildIndex = function setChildIndex(child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error('The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + var currentIndex = this.getChildIndex(child); + + (0, _utils.removeItems)(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + + this.onChildrenChange(index); + }; + + /** + * Returns the child at the specified index + * + * @param {number} index - The index to get the child at + * @return {PIXI.DisplayObject} The child at the given index, if any. + */ + + + Container.prototype.getChildAt = function getChildAt(index) { + if (index < 0 || index >= this.children.length) { + throw new Error('getChildAt: Index (' + index + ') does not exist.'); + } + + return this.children[index]; + }; + + /** + * Removes one or more children from the container. + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove + * @return {PIXI.DisplayObject} The first child that was removed. + */ + + + Container.prototype.removeChild = function removeChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.removeChild(arguments[i]); + } + } else { + var index = this.children.indexOf(child); + + if (index === -1) return null; + + child.parent = null; + // ensure child transform will be recalculated + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + } + + return child; + }; + + /** + * Removes a child from the specified index position. + * + * @param {number} index - The index to get the child from + * @return {PIXI.DisplayObject} The child that was removed. + */ + + + Container.prototype.removeChildAt = function removeChildAt(index) { + var child = this.getChildAt(index); + + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + + return child; + }; + + /** + * Removes all children from this container that are within the begin and end indexes. + * + * @param {number} [beginIndex=0] - The beginning position. + * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. + * @returns {DisplayObject[]} List of removed children + */ + + + Container.prototype.removeChildren = function removeChildren() { + var beginIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var endIndex = arguments[1]; + + var begin = beginIndex; + var end = typeof endIndex === 'number' ? endIndex : this.children.length; + var range = end - begin; + var removed = void 0; + + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } + + this._boundsID++; + + this.onChildrenChange(beginIndex); + + for (var _i = 0; _i < removed.length; ++_i) { + removed[_i].emit('removed', this); + } + + return removed; + } else if (range === 0 && this.children.length === 0) { + return []; + } + + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + }; + + /** + * Updates the transform on all children of this container for rendering + */ + + + Container.prototype.updateTransform = function updateTransform() { + this._boundsID++; + + this.transform.updateTransform(this.parent.transform); + + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + + if (child.visible) { + child.updateTransform(); + } + } + }; + + /** + * Recalculates the bounds of the container. + * + */ + + + Container.prototype.calculateBounds = function calculateBounds() { + this._bounds.clear(); + + this._calculateBounds(); + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (!child.visible || !child.renderable) { + continue; + } + + child.calculateBounds(); + + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + child._mask.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, child._mask._bounds); + } else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } else { + this._bounds.addBounds(child._bounds); + } + } + + this._lastBoundsID = this._boundsID; + }; + + /** + * Recalculates the bounds of the object. Override this to + * calculate the bounds of the specific object (not including children). + * + */ + + + Container.prototype._calculateBounds = function _calculateBounds() {} + // FILL IN// + + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderWebGL = function renderWebGL(renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + // do a quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) { + this.renderAdvancedWebGL(renderer); + } else { + this._renderWebGL(renderer); + + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderWebGL(renderer); + } + } + }; + + /** + * Render the object using the WebGL renderer and advanced features. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { + renderer.flush(); + + var filters = this._filters; + var mask = this._mask; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + + this._enabledFilters.length = 0; + + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + + if (this._enabledFilters.length) { + renderer.filterManager.pushFilter(this, this._enabledFilters); + } + } + + if (mask) { + renderer.maskManager.pushMask(this, this._mask); + } + + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); + + // now loop through the children and make sure they get rendered + for (var _i2 = 0, j = this.children.length; _i2 < j; _i2++) { + this.children[_i2].renderWebGL(renderer); + } + + renderer.flush(); + + if (mask) { + renderer.maskManager.popMask(this, this._mask); + } + + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filterManager.popFilter(); + } + }; + + /** + * To be overridden by the subclasses. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype._renderWebGL = function _renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * To be overridden by the subclass + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype._renderCanvas = function _renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderCanvas = function renderCanvas(renderer) { + // if not visible or the alpha is 0 then no need to render this + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + if (this._mask) { + renderer.maskManager.pushMask(this._mask); + } + + this._renderCanvas(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderCanvas(renderer); + } + + if (this._mask) { + renderer.maskManager.popMask(renderer); + } + }; + + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Container.prototype.destroy = function destroy(options) { + _DisplayObject.prototype.destroy.call(this); + + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + + var oldChildren = this.removeChildren(0, this.children.length); + + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + }; + + /** + * The width of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Container, [{ + key: 'width', + get: function get() { + return this.scale.x * this.getLocalBounds().width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var width = this.getLocalBounds().width; + + if (width !== 0) { + this.scale.x = value / width; + } else { + this.scale.x = 1; + } + + this._width = value; + } + + /** + * The height of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.scale.y * this.getLocalBounds().height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var height = this.getLocalBounds().height; + + if (height !== 0) { + this.scale.y = value / height; + } else { + this.scale.y = 1; + } + + this._height = value; + } + }]); + + return Container; +}(_DisplayObject3.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = Container; +Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + +},{"../utils":125,"./DisplayObject":49}],49:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TransformStatic = require('./TransformStatic'); + +var _TransformStatic2 = _interopRequireDefault(_TransformStatic); + +var _Transform = require('./Transform'); + +var _Transform2 = _interopRequireDefault(_Transform); + +var _Bounds = require('./Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _math = require('../math'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// _tempDisplayObjectParent = new DisplayObject(); + +/** + * The base class for all objects that are rendered on the screen. + * This is an abstract class and should not be used on its own rather it should be extended. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var DisplayObject = function (_EventEmitter) { + _inherits(DisplayObject, _EventEmitter); + + /** + * + */ + function DisplayObject() { + _classCallCheck(this, DisplayObject); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + var TransformClass = _settings2.default.TRANSFORM_MODE === _const.TRANSFORM_MODE.STATIC ? _TransformStatic2.default : _Transform2.default; + + _this.tempDisplayObjectParent = null; + + // TODO: need to create Transform from factory + /** + * World transform and local transform of this object. + * This will become read-only later, please do not assign anything there unless you know what are you doing + * + * @member {PIXI.TransformBase} + */ + _this.transform = new TransformClass(); + + /** + * The opacity of the object. + * + * @member {number} + */ + _this.alpha = 1; + + /** + * The visibility of the object. If false the object will not be drawn, and + * the updateTransform function will not be called. + * + * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually + * + * @member {boolean} + */ + _this.visible = true; + + /** + * Can this object be rendered, if false the object will not be drawn but the updateTransform + * methods will still be called. + * + * Only affects recursive calls from parent. You can ask for bounds manually + * + * @member {boolean} + */ + _this.renderable = true; + + /** + * The display object container that contains this display object. + * + * @member {PIXI.Container} + * @readonly + */ + _this.parent = null; + + /** + * The multiplied alpha of the displayObject + * + * @member {number} + * @readonly + */ + _this.worldAlpha = 1; + + /** + * The area the filter is applied to. This is used as more of an optimisation + * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle + * + * Also works as an interaction mask + * + * @member {PIXI.Rectangle} + */ + _this.filterArea = null; + + _this._filters = null; + _this._enabledFilters = null; + + /** + * The bounds object, this is used to calculate and store the bounds of the displayObject + * + * @member {PIXI.Rectangle} + * @private + */ + _this._bounds = new _Bounds2.default(); + _this._boundsID = 0; + _this._lastBoundsID = -1; + _this._boundsRect = null; + _this._localBoundsRect = null; + + /** + * The original, cached mask of the object + * + * @member {PIXI.Graphics|PIXI.Sprite} + * @private + */ + _this._mask = null; + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + + /** + * Fired when this DisplayObject is added to a Container. + * + * @event PIXI.DisplayObject#added + * @param {PIXI.Container} container - The container added to. + */ + + /** + * Fired when this DisplayObject is removed from a Container. + * + * @event PIXI.DisplayObject#removed + * @param {PIXI.Container} container - The container removed from. + */ + return _this; + } + + /** + * @private + * @member {PIXI.DisplayObject} + */ + + + /** + * Updates the object transform for rendering + * + * TODO - Optimization pass! + */ + DisplayObject.prototype.updateTransform = function updateTransform() { + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + this._bounds.updateID++; + }; + + /** + * recursively updates transform of all objects from the root to this one + * internal function for toLocal() + */ + + + DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform() { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + }; + + /** + * Retrieves the bounds of the displayObject as a rectangle object. + * + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @param {PIXI.Rectangle} rect - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getBounds = function getBounds(skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + + if (this._boundsID !== this._lastBoundsID) { + this.calculateBounds(); + } + + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new _math.Rectangle(); + } + + rect = this._boundsRect; + } + + return this._bounds.getRectangle(rect); + }; + + /** + * Retrieves the local bounds of the displayObject as a rectangle object + * + * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getLocalBounds = function getLocalBounds(rect) { + var transformRef = this.transform; + var parentRef = this.parent; + + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + var bounds = this.getBounds(false, rect); + + this.parent = parentRef; + this.transform = transformRef; + + return bounds; + }; + + /** + * Calculates the global position of the display object + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform. + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toGlobal = function toGlobal(position, point) { + var skipUpdate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; + + /** + * Calculates the local position of the display object relative to another point + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toLocal = function toLocal(position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + DisplayObject.prototype.renderCanvas = function renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Set the parent Container of this DisplayObject + * + * @param {PIXI.Container} container - The Container to add this DisplayObject to + * @return {PIXI.Container} The Container that this DisplayObject was added to + */ + ; + + DisplayObject.prototype.setParent = function setParent(container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); + } + + container.addChild(this); + + return container; + }; + + /** + * Convenience function to set the position, scale, skew and pivot at once. + * + * @param {number} [x=0] - The X position + * @param {number} [y=0] - The Y position + * @param {number} [scaleX=1] - The X scale value + * @param {number} [scaleY=1] - The Y scale value + * @param {number} [rotation=0] - The rotation + * @param {number} [skewX=0] - The X skew value + * @param {number} [skewY=0] - The Y skew value + * @param {number} [pivotX=0] - The X pivot value + * @param {number} [pivotY=0] - The Y pivot value + * @return {PIXI.DisplayObject} The DisplayObject instance + */ + + + DisplayObject.prototype.setTransform = function setTransform() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var scaleX = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var scaleY = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var rotation = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var skewX = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + var skewY = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + var pivotX = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; + var pivotY = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0; + + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + + return this; + }; + + /** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy`. + * + */ + + + DisplayObject.prototype.destroy = function destroy() { + this.removeAllListeners(); + if (this.parent) { + this.parent.removeChild(this); + } + this.transform = null; + + this.parent = null; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this.filterArea = null; + + this.interactive = false; + this.interactiveChildren = false; + + this._destroyed = true; + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + * + * @member {number} + */ + + + _createClass(DisplayObject, [{ + key: '_tempDisplayObjectParent', + get: function get() { + if (this.tempDisplayObjectParent === null) { + this.tempDisplayObjectParent = new DisplayObject(); + } + + return this.tempDisplayObjectParent; + } + }, { + key: 'x', + get: function get() { + return this.position.x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.x = value; + } + + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + * + * @member {number} + */ + + }, { + key: 'y', + get: function get() { + return this.position.y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.y = value; + } + + /** + * Current transform of the object based on world (parent) factors + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'worldTransform', + get: function get() { + return this.transform.worldTransform; + } + + /** + * Current transform of the object based on local factors: position, scale, other stuff + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'localTransform', + get: function get() { + return this.transform.localTransform; + } + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'position', + get: function get() { + return this.transform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.copy(value); + } + + /** + * The scale factor of the object. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'scale', + get: function get() { + return this.transform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.scale.copy(value); + } + + /** + * The pivot point of the displayObject that it rotates around + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'pivot', + get: function get() { + return this.transform.pivot; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.pivot.copy(value); + } + + /** + * The skew factor for the object in radians. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'skew', + get: function get() { + return this.transform.skew; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.skew.copy(value); + } + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + }, { + key: 'rotation', + get: function get() { + return this.transform.rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.rotation = value; + } + + /** + * Indicates if the object is globally visible. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'worldVisible', + get: function get() { + var item = this; + + do { + if (!item.visible) { + return false; + } + + item = item.parent; + } while (item); + + return true; + } + + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PIXI a regular mask must be a + * PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it + * utilises shape clipping. To remove a mask, set this property to null. + * + * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + * + * @member {PIXI.Graphics|PIXI.Sprite} + */ + + }, { + key: 'mask', + get: function get() { + return this._mask; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._mask) { + this._mask.renderable = true; + this._mask.isMask = false; + } + + this._mask = value; + + if (this._mask) { + this._mask.renderable = false; + this._mask.isMask = true; + } + } + + /** + * Sets the filters for the displayObject. + * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * To remove filters simply set this property to 'null' + * + * @member {PIXI.Filter[]} + */ + + }, { + key: 'filters', + get: function get() { + return this._filters && this._filters.slice(); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._filters = value && value.slice(); + } + }]); + + return DisplayObject; +}(_eventemitter2.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = DisplayObject; +DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + +},{"../const":46,"../math":70,"../settings":101,"./Bounds":47,"./Transform":50,"./TransformStatic":52,"eventemitter3":3}],50:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Generic class to deal with traditional 2D matrix transforms + * local transformation is calculated from position,scale,skew and rotation + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var Transform = function (_TransformBase) { + _inherits(Transform, _TransformBase); + + /** + * + */ + function Transform() { + _classCallCheck(this, Transform); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.Point} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.Point(0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.Point} + */ + _this.scale = new _math.Point(1, 1); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.Point} + */ + _this.pivot = new _math.Point(0, 0); + + /** + * The rotation value of the object, in radians + * + * @member {Number} + * @private + */ + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + return _this; + } + + /** + * Updates the skew values when the skew or rotation changes. + * + * @private + */ + + + Transform.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + }; + + /** + * Updates only local matrix + */ + + + Transform.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + Transform.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + Transform.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(Transform, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return Transform; +}(_TransformBase3.default); + +exports.default = Transform; + +},{"../math":70,"./TransformBase":51}],51:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Generic class to deal with traditional 2D matrix transforms + * + * @class + * @memberof PIXI + */ +var TransformBase = function () { + /** + * + */ + function TransformBase() { + _classCallCheck(this, TransformBase); + + /** + * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds() + * + * @member {PIXI.Matrix} + */ + this.worldTransform = new _math.Matrix(); + + /** + * The local matrix transform + * + * @member {PIXI.Matrix} + */ + this.localTransform = new _math.Matrix(); + + this._worldID = 0; + this._parentID = 0; + } + + /** + * TransformBase does not have decomposition, so this function wont do anything + */ + + + TransformBase.prototype.updateLocalTransform = function updateLocalTransform() {} + // empty + + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.TransformBase} parentTransform - The transform of the parent of this object + */ + ; + + TransformBase.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + return TransformBase; +}(); + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ + + +exports.default = TransformBase; +TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; + +TransformBase.IDENTITY = new TransformBase(); + +},{"../math":70}],52:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Transform that takes care about its versions + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var TransformStatic = function (_TransformBase) { + _inherits(TransformStatic, _TransformBase); + + /** + * + */ + function TransformStatic() { + _classCallCheck(this, TransformStatic); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.ObservablePoint} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.ObservablePoint} + */ + _this.scale = new _math.ObservablePoint(_this.onChange, _this, 1, 1); + + /** + * The pivot point of the displayObject that it rotates around + * + * @member {PIXI.ObservablePoint} + */ + _this.pivot = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + + _this._localID = 0; + _this._currentLocalID = 0; + return _this; + } + + /** + * Called when a value changes. + * + * @private + */ + + + TransformStatic.prototype.onChange = function onChange() { + this._localID++; + }; + + /** + * Called when skew or rotation changes + * + * @private + */ + + + TransformStatic.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + + this._localID++; + }; + + /** + * Updates only local matrix + */ + + + TransformStatic.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + TransformStatic.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._parentID = parentTransform._worldID; + + // update the id of the transform.. + this._worldID++; + } + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + TransformStatic.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + this._localID++; + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(TransformStatic, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return TransformStatic; +}(_TransformBase3.default); + +exports.default = TransformStatic; + +},{"../math":70,"./TransformBase":51}],53:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _GraphicsData = require('./GraphicsData'); + +var _GraphicsData2 = _interopRequireDefault(_GraphicsData); + +var _Sprite = require('../sprites/Sprite'); + +var _Sprite2 = _interopRequireDefault(_Sprite); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Bounds = require('../display/Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _bezierCurveTo2 = require('./utils/bezierCurveTo'); + +var _bezierCurveTo3 = _interopRequireDefault(_bezierCurveTo2); + +var _CanvasRenderer = require('../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var canvasRenderer = void 0; +var tempMatrix = new _math.Matrix(); +var tempPoint = new _math.Point(); +var tempColor1 = new Float32Array(4); +var tempColor2 = new Float32Array(4); + +/** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Graphics = function (_Container) { + _inherits(Graphics, _Container); + + /** + * + * @param {boolean} [nativeLines=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + */ + function Graphics() { + var nativeLines = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + _classCallCheck(this, Graphics); + + /** + * The alpha value used when filling the Graphics object. + * + * @member {number} + * @default 1 + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @member {number} + * @default 0 + */ + _this.lineWidth = 0; + + /** + * If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * + * @member {boolean} + */ + _this.nativeLines = nativeLines; + + /** + * The color of any lines drawn. + * + * @member {string} + * @default 0 + */ + _this.lineColor = 0; + + /** + * The alignment of any lines drawn (0.5 = middle, 1 = outter, 0 = inner). + * + * @member {number} + * @default 0 + */ + _this.lineAlignment = 0.5; + + /** + * Graphics data + * + * @member {PIXI.GraphicsData[]} + * @private + */ + _this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to + * reset the tint. + * + * @member {number} + * @default 0xFFFFFF + */ + _this.tint = 0xFFFFFF; + + /** + * The previous tint applied to the graphic shape. Used to compare to the current tint and + * check if theres change. + * + * @member {number} + * @private + * @default 0xFFFFFF + */ + _this._prevTint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * Current path + * + * @member {PIXI.GraphicsData} + * @private + */ + _this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @member {object} + * @private + */ + // TODO - _webgl should use a prototype object, not a random undocumented object... + _this._webGL = {}; + + /** + * Whether this shape is being used as a mask. + * + * @member {boolean} + */ + _this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @member {number} + */ + _this.boundsPadding = 0; + + /** + * A cache of the local bounds to prevent recalculation. + * + * @member {PIXI.Rectangle} + * @private + */ + _this._localBounds = new _Bounds2.default(); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics + * object will be recalculated. + * + * @member {boolean} + * @private + */ + _this.dirty = 0; + + /** + * Used to detect if we need to do a fast rect check using the id compare method + * @type {Number} + */ + _this.fastRectDirty = -1; + + /** + * Used to detect if we clear the graphics webGL data + * @type {Number} + */ + _this.clearDirty = 0; + + /** + * Used to detect if we we need to recalculate local bounds + * @type {Number} + */ + _this.boundsDirty = -1; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @member {boolean} + * @private + */ + _this.cachedSpriteDirty = false; + + _this._spriteRect = null; + _this._fastRect = false; + + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ + return _this; + } + + /** + * Creates a new Graphics object with the same values as this one. + * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) + * + * @return {PIXI.Graphics} A clone of the graphics object + */ + + + Graphics.prototype.clone = function clone() { + var clone = new Graphics(); + + clone.renderable = this.renderable; + clone.fillAlpha = this.fillAlpha; + clone.lineWidth = this.lineWidth; + clone.lineColor = this.lineColor; + clone.lineAlignment = this.lineAlignment; + clone.tint = this.tint; + clone.blendMode = this.blendMode; + clone.isMask = this.isMask; + clone.boundsPadding = this.boundsPadding; + clone.dirty = 0; + clone.cachedSpriteDirty = this.cachedSpriteDirty; + + // copy graphics data + for (var i = 0; i < this.graphicsData.length; ++i) { + clone.graphicsData.push(this.graphicsData[i].clone()); + } + + clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; + + clone.updateLocalBounds(); + + return clone; + }; + + /** + * Calculate length of quadratic curve + * @see {@link http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/} + * for the detailed explanation of math behind this. + * + * @private + * @param {number} fromX - x-coordinate of curve start point + * @param {number} fromY - y-coordinate of curve start point + * @param {number} cpX - x-coordinate of curve control point + * @param {number} cpY - y-coordinate of curve control point + * @param {number} toX - x-coordinate of curve end point + * @param {number} toY - y-coordinate of curve end point + * @return {number} Length of quadratic curve + */ + + + Graphics.prototype._quadraticCurveLength = function _quadraticCurveLength(fromX, fromY, cpX, cpY, toX, toY) { + var ax = fromX - (2.0 * cpX + toX); + var ay = fromY - (2.0 * cpY + toY); + var bx = 2.0 * ((cpX - 2.0) * fromX); + var by = 2.0 * ((cpY - 2.0) * fromY); + var a = 4.0 * (ax * ax + ay * ay); + var b = 4.0 * (ax * bx + ay * by); + var c = bx * bx + by * by; + + var s = 2.0 * Math.sqrt(a + b + c); + var a2 = Math.sqrt(a); + var a32 = 2.0 * a * a2; + var c2 = 2.0 * Math.sqrt(c); + var ba = b / a2; + + return (a32 * s + a2 * b * (s - c2) + (4.0 * c * a - b * b) * Math.log((2.0 * a2 + ba + s) / (ba + c2))) / (4.0 * a32); + }; + + /** + * Calculate length of bezier curve. + * Analytical solution is impossible, since it involves an integral that does not integrate in general. + * Therefore numerical solution is used. + * + * @private + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {number} Length of bezier curve + */ + + + Graphics.prototype._bezierCurveLength = function _bezierCurveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var n = 10; + var result = 0.0; + var t = 0.0; + var t2 = 0.0; + var t3 = 0.0; + var nt = 0.0; + var nt2 = 0.0; + var nt3 = 0.0; + var x = 0.0; + var y = 0.0; + var dx = 0.0; + var dy = 0.0; + var prevX = fromX; + var prevY = fromY; + + for (var i = 1; i <= n; ++i) { + t = i / n; + t2 = t * t; + t3 = t2 * t; + nt = 1.0 - t; + nt2 = nt * nt; + nt3 = nt2 * nt; + + x = nt3 * fromX + 3.0 * nt2 * t * cpX + 3.0 * nt * t2 * cpX2 + t3 * toX; + y = nt3 * fromY + 3.0 * nt2 * t * cpY + 3 * nt * t2 * cpY2 + t3 * toY; + dx = prevX - x; + dy = prevY - y; + prevX = x; + prevY = y; + + result += Math.sqrt(dx * dx + dy * dy); + } + + return result; + }; + + /** + * Calculate number of segments for the curve based on its length to ensure its smoothness. + * + * @private + * @param {number} length - length of curve + * @return {number} Number of segments + */ + + + Graphics.prototype._segmentsCount = function _segmentsCount(length) { + var result = Math.ceil(length / Graphics.CURVES.maxLength); + + if (result < Graphics.CURVES.minSegments) { + result = Graphics.CURVES.minSegments; + } else if (result > Graphics.CURVES.maxSegments) { + result = Graphics.CURVES.maxSegments; + } + + return result; + }; + + /** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() + * method or the drawCircle() method. + * + * @param {number} [lineWidth=0] - width of the line to draw, will update the objects stored style + * @param {number} [color=0] - color of the line to draw, will update the objects stored style + * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style + * @param {number} [alignment=1] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineStyle = function lineStyle() { + var lineWidth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var alpha = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var alignment = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0.5; + + this.lineWidth = lineWidth; + this.lineColor = color; + this.lineAlpha = alpha; + this.lineAlignment = alignment; + + if (this.currentPath) { + if (this.currentPath.shape.points.length) { + // halfway through a line? start a new one! + var shape = new _math.Polygon(this.currentPath.shape.points.slice(-2)); + + shape.closed = false; + + this.drawShape(shape); + } else { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + this.currentPath.lineAlignment = this.lineAlignment; + } + } + + return this; + }; + + /** + * Moves the current drawing position to x, y. + * + * @param {number} x - the X coordinate to move to + * @param {number} y - the Y coordinate to move to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.moveTo = function moveTo(x, y) { + var shape = new _math.Polygon([x, y]); + + shape.closed = false; + this.drawShape(shape); + + return this; + }; + + /** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @param {number} x - the X coordinate to draw to + * @param {number} y - the Y coordinate to draw to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineTo = function lineTo(x, y) { + this.currentPath.shape.points.push(x, y); + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.quadraticCurveTo = function quadraticCurveTo(cpX, cpY, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + var xa = 0; + var ya = 0; + + if (points.length === 0) { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var n = Graphics.CURVES.adaptive ? this._segmentsCount(this._quadraticCurveLength(fromX, fromY, cpX, cpY, toX, toY)) : 20; + + for (var i = 1; i <= n; ++i) { + var j = i / n; + + xa = fromX + (cpX - fromX) * j; + ya = fromY + (cpY - fromY) * j; + + points.push(xa + (cpX + (toX - cpX) * j - xa) * j, ya + (cpY + (toY - cpY) * j - ya) * j); + } + + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a bezier curve and then draws it. + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.bezierCurveTo = function bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + points.length -= 2; + + var n = Graphics.CURVES.adaptive ? this._segmentsCount(this._bezierCurveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY)) : 20; + + (0, _bezierCurveTo3.default)(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, n, points); + + this.dirty++; + + return this; + }; + + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @param {number} x1 - The x-coordinate of the beginning of the arc + * @param {number} y1 - The y-coordinate of the beginning of the arc + * @param {number} x2 - The x-coordinate of the end of the arc + * @param {number} y2 - The y-coordinate of the end of the arc + * @param {number} radius - The radius of the arc + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arcTo = function arcTo(x1, y1, x2, y2, radius) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points.push(x1, y1); + } + } else { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + } else { + var dd = a1 * a1 + b1 * b1; + var cc = a2 * a2 + b2 * b2; + var tt = a1 * a2 + b1 * b2; + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = k1 * b2 + k2 * b1; + var cy = k1 * a2 + k2 * a1; + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty++; + + return this; + }; + + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @param {number} cx - The x-coordinate of the center of the circle + * @param {number} cy - The y-coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param {number} endAngle - The ending angle, in radians + * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arc = function arc(cx, cy, radius, startAngle, endAngle) { + var anticlockwise = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; + + if (startAngle === endAngle) { + return this; + } + + if (!anticlockwise && endAngle <= startAngle) { + endAngle += _const.PI_2; + } else if (anticlockwise && startAngle <= endAngle) { + startAngle += _const.PI_2; + } + + var sweep = endAngle - startAngle; + var segs = Graphics.CURVES.adaptive ? this._segmentsCount(Math.abs(sweep) * radius) : Math.ceil(Math.abs(sweep) / _const.PI_2) * 40; + + if (sweep === 0) { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. + var points = this.currentPath ? this.currentPath.shape.points : null; + + if (points) { + if (points[points.length - 2] !== startX || points[points.length - 1] !== startY) { + points.push(startX, startY); + } + } else { + this.moveTo(startX, startY); + points = this.currentPath.shape.points; + } + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = segMinus % 1 / segMinus; + + for (var i = 0; i <= segMinus; ++i) { + var real = i + remainder * i; + + var angle = theta + startAngle + theta2 * real; + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push((cTheta * c + sTheta * s) * radius + cx, (cTheta * -s + sTheta * c) * radius + cy); + } + + this.dirty++; + + return this; + }; + + /** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @param {number} [color=0] - the color of the fill + * @param {number} [alpha=1] - the alpha of the fill + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.beginFill = function beginFill() { + var color = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var alpha = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.filling = true; + this.fillColor = color; + this.fillAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length <= 2) { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + }; + + /** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.endFill = function endFill() { + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRect = function drawRect(x, y, width, height) { + this.drawShape(new _math.Rectangle(x, y, width, height)); + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @param {number} radius - Radius of the rectangle corners + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRoundedRect = function drawRoundedRect(x, y, width, height, radius) { + this.drawShape(new _math.RoundedRectangle(x, y, width, height, radius)); + + return this; + }; + + /** + * Draws a circle. + * + * @param {number} x - The X coordinate of the center of the circle + * @param {number} y - The Y coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawCircle = function drawCircle(x, y, radius) { + this.drawShape(new _math.Circle(x, y, radius)); + + return this; + }; + + /** + * Draws an ellipse. + * + * @param {number} x - The X coordinate of the center of the ellipse + * @param {number} y - The Y coordinate of the center of the ellipse + * @param {number} width - The half width of the ellipse + * @param {number} height - The half height of the ellipse + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawEllipse = function drawEllipse(x, y, width, height) { + this.drawShape(new _math.Ellipse(x, y, width, height)); + + return this; + }; + + /** + * Draws a polygon using the given path. + * + * @param {number[]|PIXI.Point[]|PIXI.Polygon} path - The path data used to construct the polygon. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawPolygon = function drawPolygon(path) { + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + var closed = true; + + if (points instanceof _math.Polygon) { + closed = points.closed; + points = points.points; + } + + if (!Array.isArray(points)) { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) { + points[i] = arguments[i]; // eslint-disable-line prefer-rest-params + } + } + + var shape = new _math.Polygon(points); + + shape.closed = closed; + + this.drawShape(shape); + + return this; + }; + + /** + * Draw a star shape with an abitrary number of points. + * + * @param {number} x - Center X position of the star + * @param {number} y - Center Y position of the star + * @param {number} points - The number of points of the star, must be > 1 + * @param {number} radius - The outer radius of the star + * @param {number} [innerRadius] - The inner radius between points, default half `radius` + * @param {number} [rotation=0] - The rotation of the star in radians, where 0 is vertical + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawStar = function drawStar(x, y, points, radius, innerRadius) { + var rotation = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + + innerRadius = innerRadius || radius / 2; + + var startAngle = -1 * Math.PI / 2 + rotation; + var len = points * 2; + var delta = _const.PI_2 / len; + var polygon = []; + + for (var i = 0; i < len; i++) { + var r = i % 2 ? innerRadius : radius; + var angle = i * delta + startAngle; + + polygon.push(x + r * Math.cos(angle), y + r * Math.sin(angle)); + } + + return this.drawPolygon(polygon); + }; + + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.clear = function clear() { + if (this.lineWidth || this.filling || this.graphicsData.length > 0) { + this.lineWidth = 0; + this.lineAlignment = 0.5; + + this.filling = false; + + this.boundsDirty = -1; + this.dirty++; + this.clearDirty++; + this.graphicsData.length = 0; + } + + this.currentPath = null; + this._spriteRect = null; + + return this; + }; + + /** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. + * + * @returns {boolean} True if only 1 rect. + */ + + + Graphics.prototype.isFastRect = function isFastRect() { + return this.graphicsData.length === 1 && this.graphicsData[0].shape.type === _const.SHAPES.RECT && !this.graphicsData[0].lineWidth; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderWebGL = function _renderWebGL(renderer) { + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.dirty !== this.fastRectDirty) { + this.fastRectDirty = this.dirty; + this._fastRect = this.isFastRect(); + } + + // TODO this check can be moved to dirty? + if (this._fastRect) { + this._renderSpriteRect(renderer); + } else { + renderer.setObjectRenderer(renderer.plugins.graphics); + renderer.plugins.graphics.render(this); + } + }; + + /** + * Renders a sprite rectangle. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderSpriteRect = function _renderSpriteRect(renderer) { + var rect = this.graphicsData[0].shape; + + if (!this._spriteRect) { + this._spriteRect = new _Sprite2.default(new _Texture2.default(_Texture2.default.WHITE)); + } + + var sprite = this._spriteRect; + + if (this.tint === 0xffffff) { + sprite.tint = this.graphicsData[0].fillColor; + } else { + var t1 = tempColor1; + var t2 = tempColor2; + + (0, _utils.hex2rgb)(this.graphicsData[0].fillColor, t1); + (0, _utils.hex2rgb)(this.tint, t2); + + t1[0] *= t2[0]; + t1[1] *= t2[1]; + t1[2] *= t2[2]; + + sprite.tint = (0, _utils.rgb2hex)(t1); + } + sprite.alpha = this.graphicsData[0].fillAlpha; + sprite.worldAlpha = this.worldAlpha * sprite.alpha; + sprite.blendMode = this.blendMode; + + sprite._texture._frame.width = rect.width; + sprite._texture._frame.height = rect.height; + + sprite.transform.worldTransform = this.transform.worldTransform; + + sprite.anchor.set(-rect.x / rect.width, -rect.y / rect.height); + sprite._onAnchorUpdate(); + + sprite._renderWebGL(renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.isMask === true) { + return; + } + + renderer.plugins.graphics.render(this); + }; + + /** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @private + */ + + + Graphics.prototype._calculateBounds = function _calculateBounds() { + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.updateLocalBounds(); + + this.cachedSpriteDirty = true; + } + + var lb = this._localBounds; + + this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); + }; + + /** + * Tests if a point is inside this graphics object + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Graphics.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + + if (!data.fill) { + continue; + } + + // only deal with fills.. + if (data.shape) { + if (data.shape.contains(tempPoint.x, tempPoint.y)) { + if (data.holes) { + for (var _i = 0; _i < data.holes.length; _i++) { + var hole = data.holes[_i]; + + if (hole.contains(tempPoint.x, tempPoint.y)) { + return false; + } + } + } + + return true; + } + } + } + + return false; + }; + + /** + * Update the bounds of the object + * + */ + + + Graphics.prototype.updateLocalBounds = function updateLocalBounds() { + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) { + var shape = 0; + var x = 0; + var y = 0; + var w = 0; + var h = 0; + + for (var i = 0; i < this.graphicsData.length; i++) { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + + shape = data.shape; + + if (type === _const.SHAPES.RECT || type === _const.SHAPES.RREC) { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.CIRC) { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.ELIP) { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else { + // POLY + var points = shape.points; + var x2 = 0; + var y2 = 0; + var dx = 0; + var dy = 0; + var rw = 0; + var rh = 0; + var cx = 0; + var cy = 0; + + for (var j = 0; j + 2 < points.length; j += 2) { + x = points[j]; + y = points[j + 1]; + x2 = points[j + 2]; + y2 = points[j + 3]; + dx = Math.abs(x2 - x); + dy = Math.abs(y2 - y); + h = lineWidth; + w = Math.sqrt(dx * dx + dy * dy); + + if (w < 1e-9) { + continue; + } + + rw = (h / w * dy + dx) / 2; + rh = (h / w * dx + dy) / 2; + cx = (x2 + x) / 2; + cy = (y2 + y) / 2; + + minX = cx - rw < minX ? cx - rw : minX; + maxX = cx + rw > maxX ? cx + rw : maxX; + + minY = cy - rh < minY ? cy - rh : minY; + maxY = cy + rh > maxY ? cy + rh : maxY; + } + } + } + } else { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.minX = minX - padding; + this._localBounds.maxX = maxX + padding; + + this._localBounds.minY = minY - padding; + this._localBounds.maxY = maxY + padding; + }; + + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @return {PIXI.GraphicsData} The generated GraphicsData object. + */ + + + Graphics.prototype.drawShape = function drawShape(shape) { + if (this.currentPath) { + // check current path! + if (this.currentPath.shape.points.length <= 2) { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + var data = new _GraphicsData2.default(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, this.nativeLines, shape, this.lineAlignment); + + this.graphicsData.push(data); + + if (data.type === _const.SHAPES.POLY) { + data.shape.closed = data.shape.closed || this.filling; + this.currentPath = data; + } + + this.dirty++; + + return data; + }; + + /** + * Generates a canvas texture. + * + * @param {number} scaleMode - The scale mode of the texture. + * @param {number} resolution - The resolution of the texture. + * @return {PIXI.Texture} The new texture. + */ + + + Graphics.prototype.generateCanvasTexture = function generateCanvasTexture(scaleMode) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + var bounds = this.getLocalBounds(); + + var canvasBuffer = _RenderTexture2.default.create(bounds.width, bounds.height, scaleMode, resolution); + + if (!canvasRenderer) { + canvasRenderer = new _CanvasRenderer2.default(); + } + + this.transform.updateLocalTransform(); + this.transform.localTransform.copy(tempMatrix); + + tempMatrix.invert(); + + tempMatrix.tx -= bounds.x; + tempMatrix.ty -= bounds.y; + + canvasRenderer.render(this, canvasBuffer, true, tempMatrix); + + var texture = _Texture2.default.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas, scaleMode, 'graphics'); + + texture.baseTexture.resolution = resolution; + texture.baseTexture.update(); + + return texture; + }; + + /** + * Closes the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.closePath = function closePath() { + // ok so close path assumes next one is a hole! + var currentPath = this.currentPath; + + if (currentPath && currentPath.shape) { + currentPath.shape.close(); + } + + return this; + }; + + /** + * Adds a hole in the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.addHole = function addHole() { + // this is a hole! + var hole = this.graphicsData.pop(); + + this.currentPath = this.graphicsData[this.graphicsData.length - 1]; + + this.currentPath.addHole(hole.shape); + this.currentPath = null; + + return this; + }; + + /** + * Destroys the Graphics object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Graphics.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._webGL) { + for (var j = 0; j < this._webGL[id].data.length; ++j) { + this._webGL[id].data[j].destroy(); + } + } + + if (this._spriteRect) { + this._spriteRect.destroy(); + } + + this.graphicsData = null; + + this.currentPath = null; + this._webGL = null; + this._localBounds = null; + }; + + return Graphics; +}(_Container3.default); + +exports.default = Graphics; + + +Graphics._SPRITE_TEXTURE = null; + +/** + * Graphics curves resolution settings. If `adaptive` flag is set to `true`, + * the resolution is calculated based on the curve's length to ensure better visual quality. + * Adaptive draw works with `bezierCurveTo` and `quadraticCurveTo`. + * + * @static + * @constant + * @memberof PIXI.Graphics + * @name CURVES + * @type {object} + * @property {boolean} adaptive=false - flag indicating if the resolution should be adaptive + * @property {number} maxLength=10 - maximal length of a single segment of the curve (if adaptive = false, ignored) + * @property {number} minSegments=8 - minimal number of segments in the curve (if adaptive = false, ignored) + * @property {number} maxSegments=2048 - maximal number of segments in the curve (if adaptive = false, ignored) + */ +Graphics.CURVES = { + adaptive: false, + maxLength: 10, + minSegments: 8, + maxSegments: 2048 +}; + +},{"../const":46,"../display/Bounds":47,"../display/Container":48,"../math":70,"../renderers/canvas/CanvasRenderer":77,"../sprites/Sprite":102,"../textures/RenderTexture":113,"../textures/Texture":115,"../utils":125,"./GraphicsData":54,"./utils/bezierCurveTo":56}],54:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + */ +var GraphicsData = function () { + /** + * + * @param {number} lineWidth - the width of the line to draw + * @param {number} lineColor - the color of the line to draw + * @param {number} lineAlpha - the alpha of the line to draw + * @param {number} fillColor - the color of the fill + * @param {number} fillAlpha - the alpha of the fill + * @param {boolean} fill - whether or not the shape is filled with a colour + * @param {boolean} nativeLines - the method for drawing lines + * @param {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} shape - The shape object to draw. + * @param {number} lineAlignment - the alignment of the line. + */ + function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, nativeLines, shape, lineAlignment) { + _classCallCheck(this, GraphicsData); + + /** + * the width of the line to draw + * @member {number} + */ + this.lineWidth = lineWidth; + + /** + * The alignment of any lines drawn (0.5 = middle, 1 = outter, 0 = inner). + * + * @member {number} + * @default 0 + */ + this.lineAlignment = lineAlignment; + + /** + * if true the liens will be draw using LINES instead of TRIANGLE_STRIP + * @member {boolean} + */ + this.nativeLines = nativeLines; + + /** + * the color of the line to draw + * @member {number} + */ + this.lineColor = lineColor; + + /** + * the alpha of the line to draw + * @member {number} + */ + this.lineAlpha = lineAlpha; + + /** + * cached tint of the line to draw + * @member {number} + * @private + */ + this._lineTint = lineColor; + + /** + * the color of the fill + * @member {number} + */ + this.fillColor = fillColor; + + /** + * the alpha of the fill + * @member {number} + */ + this.fillAlpha = fillAlpha; + + /** + * cached tint of the fill + * @member {number} + * @private + */ + this._fillTint = fillColor; + + /** + * whether or not the shape is filled with a colour + * @member {boolean} + */ + this.fill = fill; + + this.holes = []; + + /** + * The shape object to draw. + * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} + */ + this.shape = shape; + + /** + * The type of the shape, see the Const.Shapes file for all the existing types, + * @member {number} + */ + this.type = shape.type; + } + + /** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {PIXI.GraphicsData} Cloned GraphicsData object + */ + + + GraphicsData.prototype.clone = function clone() { + return new GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.fill, this.nativeLines, this.shape); + }; + + /** + * Adds a hole to the shape. + * + * @param {PIXI.Rectangle|PIXI.Circle} shape - The shape of the hole. + */ + + + GraphicsData.prototype.addHole = function addHole(shape) { + this.holes.push(shape); + }; + + /** + * Destroys the Graphics data. + */ + + + GraphicsData.prototype.destroy = function destroy() { + this.shape = null; + this.holes = null; + }; + + return GraphicsData; +}(); + +exports.default = GraphicsData; + +},{}],55:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they + * now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasGraphicsRenderer: + * https://github.com/libgdx/libgdx/blob/1.0.0/gdx/src/com/badlogic/gdx/graphics/glutils/ShapeRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching graphics objects. + * + * @class + * @private + * @memberof PIXI + */ +var CanvasGraphicsRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The current PIXI renderer. + */ + function CanvasGraphicsRenderer(renderer) { + _classCallCheck(this, CanvasGraphicsRenderer); + + this.renderer = renderer; + } + + /** + * Renders a Graphics object to a canvas. + * + * @param {PIXI.Graphics} graphics - the actual graphics object to render + */ + + + CanvasGraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var context = renderer.context; + var worldAlpha = graphics.worldAlpha; + var transform = graphics.transform.worldTransform; + var resolution = renderer.resolution; + + // if the tint has changed, set the graphics object to dirty. + if (this._prevTint !== this.tint) { + this.dirty = true; + } + + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + if (graphics.dirty) { + this.updateGraphicsTint(graphics); + graphics.dirty = false; + } + + renderer.setBlendMode(graphics.blendMode); + + for (var i = 0; i < graphics.graphicsData.length; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === _const.SHAPES.POLY) { + context.beginPath(); + + this.renderPolygon(shape.points, shape.closed, context); + + for (var j = 0; j < data.holes.length; j++) { + this.renderPolygon(data.holes[j].points, true, context); + } + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RECT) { + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + context.beginPath(); + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + }; + + /** + * Updates the tint of a graphics object + * + * @private + * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated + */ + + + CanvasGraphicsRenderer.prototype.updateGraphicsTint = function updateGraphicsTint(graphics) { + graphics._prevTint = graphics.tint; + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF) / 255; + + for (var i = 0; i < graphics.graphicsData.length; ++i) { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + // super inline, cos optimization :) + data._fillTint = ((fillColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (fillColor & 0xFF) / 255 * tintB * 255; + + data._lineTint = ((lineColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (lineColor & 0xFF) / 255 * tintB * 255; + } + }; + + /** + * Renders a polygon. + * + * @param {PIXI.Point[]} points - The points to render + * @param {boolean} close - Should the polygon be closed + * @param {CanvasRenderingContext2D} context - The rendering context to use + */ + + + CanvasGraphicsRenderer.prototype.renderPolygon = function renderPolygon(points, close, context) { + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; ++j) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (close) { + context.closePath(); + } + }; + + /** + * destroy graphics object + * + */ + + + CanvasGraphicsRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasGraphicsRenderer; +}(); + +exports.default = CanvasGraphicsRenderer; + + +_CanvasRenderer2.default.registerPlugin('graphics', CanvasGraphicsRenderer); + +},{"../../const":46,"../../renderers/canvas/CanvasRenderer":77}],56:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = bezierCurveTo; +/** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number} n - Number of segments approximating the bezier curve + * @param {number[]} [path=[]] - Path array to push points into + * @return {number[]} Array of points of the curve + */ +function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, n) { + var path = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : []; + + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + + path.push(fromX, fromY); + + for (var i = 1, j = 0; i <= n; ++i) { + j = i / n; + + dt = 1 - j; + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + path.push(dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + return path; +} + +},{}],57:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _WebGLGraphicsData = require('./WebGLGraphicsData'); + +var _WebGLGraphicsData2 = _interopRequireDefault(_WebGLGraphicsData); + +var _PrimitiveShader = require('./shaders/PrimitiveShader'); + +var _PrimitiveShader2 = _interopRequireDefault(_PrimitiveShader); + +var _buildPoly = require('./utils/buildPoly'); + +var _buildPoly2 = _interopRequireDefault(_buildPoly); + +var _buildRectangle = require('./utils/buildRectangle'); + +var _buildRectangle2 = _interopRequireDefault(_buildRectangle); + +var _buildRoundedRectangle = require('./utils/buildRoundedRectangle'); + +var _buildRoundedRectangle2 = _interopRequireDefault(_buildRoundedRectangle); + +var _buildCircle = require('./utils/buildCircle'); + +var _buildCircle2 = _interopRequireDefault(_buildCircle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Renders the graphics object. + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var GraphicsRenderer = function (_ObjectRenderer) { + _inherits(GraphicsRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this object renderer works for. + */ + function GraphicsRenderer(renderer) { + _classCallCheck(this, GraphicsRenderer); + + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.graphicsDataPool = []; + + _this.primitiveShader = null; + + _this.gl = renderer.gl; + + // easy access! + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * Called when there is a WebGL context change + * + * @private + * + */ + + + GraphicsRenderer.prototype.onContextChange = function onContextChange() { + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.primitiveShader = new _PrimitiveShader2.default(this.gl); + }; + + /** + * Destroys this renderer. + * + */ + + + GraphicsRenderer.prototype.destroy = function destroy() { + _ObjectRenderer3.default.prototype.destroy.call(this); + + for (var i = 0; i < this.graphicsDataPool.length; ++i) { + this.graphicsDataPool[i].destroy(); + } + + this.graphicsDataPool = null; + }; + + /** + * Renders a graphics object. + * + * @param {PIXI.Graphics} graphics - The graphics object to render. + */ + + + GraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var gl = renderer.gl; + + var webGLData = void 0; + var webGL = graphics._webGL[this.CONTEXT_UID]; + + if (!webGL || graphics.dirty !== webGL.dirty) { + this.updateGraphics(graphics); + + webGL = graphics._webGL[this.CONTEXT_UID]; + } + + // This could be speeded up for sure! + var shader = this.primitiveShader; + + renderer.bindShader(shader); + renderer.state.setBlendMode(graphics.blendMode); + + for (var i = 0, n = webGL.data.length; i < n; i++) { + webGLData = webGL.data[i]; + var shaderTemp = webGLData.shader; + + renderer.bindShader(shaderTemp); + shaderTemp.uniforms.translationMatrix = graphics.transform.worldTransform.toArray(true); + shaderTemp.uniforms.tint = (0, _utils.hex2rgb)(graphics.tint); + shaderTemp.uniforms.alpha = graphics.worldAlpha; + + renderer.bindVao(webGLData.vao); + + if (webGLData.nativeLines) { + gl.drawArrays(gl.LINES, 0, webGLData.points.length / 6); + } else { + webGLData.vao.draw(gl.TRIANGLE_STRIP, webGLData.indices.length); + } + } + }; + + /** + * Updates the graphics object + * + * @private + * @param {PIXI.Graphics} graphics - The graphics object to update + */ + + + GraphicsRenderer.prototype.updateGraphics = function updateGraphics(graphics) { + var gl = this.renderer.gl; + + // get the contexts graphics object + var webGL = graphics._webGL[this.CONTEXT_UID]; + + // if the graphics object does not exist in the webGL context time to create it! + if (!webGL) { + webGL = graphics._webGL[this.CONTEXT_UID] = { lastIndex: 0, data: [], gl: gl, clearDirty: -1, dirty: -1 }; + } + + // flag the graphics as not dirty as we are about to update it... + webGL.dirty = graphics.dirty; + + // if the user cleared the graphics object we will need to clear every object + if (graphics.clearDirty !== webGL.clearDirty) { + webGL.clearDirty = graphics.clearDirty; + + // loop through and return all the webGLDatas to the object pool so than can be reused later on + for (var i = 0; i < webGL.data.length; i++) { + this.graphicsDataPool.push(webGL.data[i]); + } + + // clear the array and reset the index.. + webGL.data.length = 0; + webGL.lastIndex = 0; + } + + var webGLData = void 0; + var webGLDataNativeLines = void 0; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (var _i = webGL.lastIndex; _i < graphics.graphicsData.length; _i++) { + var data = graphics.graphicsData[_i]; + + // TODO - this can be simplified + webGLData = this.getWebGLData(webGL, 0); + + if (data.nativeLines && data.lineWidth) { + webGLDataNativeLines = this.getWebGLData(webGL, 0, true); + webGL.lastIndex++; + } + + if (data.type === _const.SHAPES.POLY) { + (0, _buildPoly2.default)(data, webGLData, webGLDataNativeLines); + } + if (data.type === _const.SHAPES.RECT) { + (0, _buildRectangle2.default)(data, webGLData, webGLDataNativeLines); + } else if (data.type === _const.SHAPES.CIRC || data.type === _const.SHAPES.ELIP) { + (0, _buildCircle2.default)(data, webGLData, webGLDataNativeLines); + } else if (data.type === _const.SHAPES.RREC) { + (0, _buildRoundedRectangle2.default)(data, webGLData, webGLDataNativeLines); + } + + webGL.lastIndex++; + } + + this.renderer.bindVao(null); + + // upload all the dirty data... + for (var _i2 = 0; _i2 < webGL.data.length; _i2++) { + webGLData = webGL.data[_i2]; + + if (webGLData.dirty) { + webGLData.upload(); + } + } + }; + + /** + * + * @private + * @param {WebGLRenderingContext} gl - the current WebGL drawing context + * @param {number} type - TODO @Alvin + * @param {number} nativeLines - indicate whether the webGLData use for nativeLines. + * @return {*} TODO + */ + + + GraphicsRenderer.prototype.getWebGLData = function getWebGLData(gl, type, nativeLines) { + var webGLData = gl.data[gl.data.length - 1]; + + if (!webGLData || webGLData.nativeLines !== nativeLines || webGLData.points.length > 320000) { + webGLData = this.graphicsDataPool.pop() || new _WebGLGraphicsData2.default(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData.nativeLines = nativeLines; + webGLData.reset(type); + gl.data.push(webGLData); + } + + webGLData.dirty = true; + + return webGLData; + }; + + return GraphicsRenderer; +}(_ObjectRenderer3.default); + +exports.default = GraphicsRenderer; + + +_WebGLRenderer2.default.registerPlugin('graphics', GraphicsRenderer); + +},{"../../const":46,"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../utils":125,"./WebGLGraphicsData":58,"./shaders/PrimitiveShader":59,"./utils/buildCircle":60,"./utils/buildPoly":62,"./utils/buildRectangle":63,"./utils/buildRoundedRectangle":64}],58:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * An object containing WebGL specific properties to be used by the WebGL renderer + * + * @class + * @private + * @memberof PIXI + */ +var WebGLGraphicsData = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {PIXI.Shader} shader - The shader + * @param {object} attribsState - The state for the VAO + */ + function WebGLGraphicsData(gl, shader, attribsState) { + _classCallCheck(this, WebGLGraphicsData); + + /** + * The current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // TODO does this need to be split before uploading?? + /** + * An array of color components (r,g,b) + * @member {number[]} + */ + this.color = [0, 0, 0]; // color split! + + /** + * An array of points to draw + * @member {PIXI.Point[]} + */ + this.points = []; + + /** + * The indices of the vertices + * @member {number[]} + */ + this.indices = []; + /** + * The main buffer + * @member {WebGLBuffer} + */ + this.buffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl); + + /** + * The index buffer + * @member {WebGLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl); + + /** + * Whether this graphics is dirty or not + * @member {boolean} + */ + this.dirty = true; + + /** + * Whether this graphics is nativeLines or not + * @member {boolean} + */ + this.nativeLines = false; + + this.glPoints = null; + this.glIndices = null; + + /** + * + * @member {PIXI.Shader} + */ + this.shader = shader; + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, attribsState).addIndex(this.indexBuffer).addAttribute(this.buffer, shader.attributes.aVertexPosition, gl.FLOAT, false, 4 * 6, 0).addAttribute(this.buffer, shader.attributes.aColor, gl.FLOAT, false, 4 * 6, 2 * 4); + } + + /** + * Resets the vertices and the indices + */ + + + WebGLGraphicsData.prototype.reset = function reset() { + this.points.length = 0; + this.indices.length = 0; + }; + + /** + * Binds the buffers and uploads the data + */ + + + WebGLGraphicsData.prototype.upload = function upload() { + this.glPoints = new Float32Array(this.points); + this.buffer.upload(this.glPoints); + + this.glIndices = new Uint16Array(this.indices); + this.indexBuffer.upload(this.glIndices); + + this.dirty = false; + }; + + /** + * Empties all the data + */ + + + WebGLGraphicsData.prototype.destroy = function destroy() { + this.color = null; + this.points = null; + this.indices = null; + + this.vao.destroy(); + this.buffer.destroy(); + this.indexBuffer.destroy(); + + this.gl = null; + + this.buffer = null; + this.indexBuffer = null; + + this.glPoints = null; + this.glIndices = null; + }; + + return WebGLGraphicsData; +}(); + +exports.default = WebGLGraphicsData; + +},{"pixi-gl-core":15}],59:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../../Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. + * + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ +var PrimitiveShader = function (_Shader) { + _inherits(PrimitiveShader, _Shader); + + /** + * @param {WebGLRenderingContext} gl - The webgl shader manager this shader works for. + */ + function PrimitiveShader(gl) { + _classCallCheck(this, PrimitiveShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec4 aColor;', 'uniform mat3 translationMatrix;', 'uniform mat3 projectionMatrix;', 'uniform float alpha;', 'uniform vec3 tint;', 'varying vec4 vColor;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vColor = aColor * vec4(tint * alpha, alpha);', '}'].join('\n'), + // fragment shader + ['varying vec4 vColor;', 'void main(void){', ' gl_FragColor = vColor;', '}'].join('\n'))); + } + + return PrimitiveShader; +}(_Shader3.default); + +exports.default = PrimitiveShader; + +},{"../../../Shader":44}],60:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildCircle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _const = require('../../../const'); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildCircle(graphicsData, webGLData, webGLDataNativeLines) { + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width = void 0; + var height = void 0; + + // TODO - bit hacky?? + if (graphicsData.type === _const.SHAPES.CIRC) { + width = circleData.radius; + height = circleData.radius; + } else { + width = circleData.width; + height = circleData.height; + } + + if (width === 0 || height === 0) { + return; + } + + var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); + + var seg = Math.PI * 2 / totalSegs; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + indices.push(vecPos); + + for (var i = 0; i < totalSegs + 1; i++) { + verts.push(x, y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos - 1); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (var _i = 0; _i < totalSegs + 1; _i++) { + graphicsData.points.push(x + Math.sin(seg * -_i) * width, y + Math.cos(seg * -_i) * height); + } + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +},{"../../../const":46,"../../../utils":125,"./buildLine":61}],61:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function (graphicsData, webGLData, webGLDataNativeLines) { + if (graphicsData.nativeLines) { + buildNativeLine(graphicsData, webGLDataNativeLines); + } else { + buildLine(graphicsData, webGLData); + } +}; + +var _math = require('../../../math'); + +var _utils = require('../../../utils'); + +/** + * Builds a line to draw using the poligon method. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildLine(graphicsData, webGLData) { + // TODO OPTIMISE! + var points = graphicsData.points; + + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + + // get first and last point.. figure out the middle! + var firstPoint = new _math.Point(points[0], points[1]); + var lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + // if the first point is the last point - gonna have issues :) + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var p1x = points[0]; + var p1y = points[1]; + var p2x = points[2]; + var p2y = points[3]; + var p3x = 0; + var p3y = 0; + + var perpx = -(p1y - p2y); + var perpy = p1x - p2x; + var perp2x = 0; + var perp2y = 0; + var perp3x = 0; + var perp3y = 0; + + var dist = Math.sqrt(perpx * perpx + perpy * perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + var ratio = graphicsData.lineAlignment; // 0.5; + var r1 = (1 - ratio) * 2; + var r2 = ratio * 2; + + // start + verts.push(p1x - perpx * r1, p1y - perpy * r1, r, g, b, alpha); + + verts.push(p1x + perpx * r2, p1y + perpy * r2, r, g, b, alpha); + + for (var i = 1; i < length - 1; ++i) { + p1x = points[(i - 1) * 2]; + p1y = points[(i - 1) * 2 + 1]; + + p2x = points[i * 2]; + p2y = points[i * 2 + 1]; + + p3x = points[(i + 1) * 2]; + p3y = points[(i + 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + var a1 = -perpy + p1y - (-perpy + p2y); + var b1 = -perpx + p2x - (-perpx + p1x); + var c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + var a2 = -perp2y + p3y - (-perp2y + p2y); + var b2 = -perp2x + p2x - (-perp2x + p3x); + var c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + var denom = a1 * b2 - a2 * b1; + + if (Math.abs(denom) < 0.1) { + denom += 10.1; + verts.push(p2x - perpx * r1, p2y - perpy * r1, r, g, b, alpha); + + verts.push(p2x + perpx * r2, p2y + perpy * r2, r, g, b, alpha); + + continue; + } + + var px = (b1 * c2 - b2 * c1) / denom; + var py = (a2 * c1 - a1 * c2) / denom; + var pdist = (px - p2x) * (px - p2x) + (py - p2y) * (py - p2y); + + if (pdist > 196 * width * width) { + perp3x = perpx - perp2x; + perp3y = perpy - perp2y; + + dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y); + perp3x /= dist; + perp3y /= dist; + perp3x *= width; + perp3y *= width; + + verts.push(p2x - perp3x * r1, p2y - perp3y * r1); + verts.push(r, g, b, alpha); + + verts.push(p2x + perp3x * r2, p2y + perp3y * r2); + verts.push(r, g, b, alpha); + + verts.push(p2x - perp3x * r2 * r1, p2y - perp3y * r1); + verts.push(r, g, b, alpha); + + indexCount++; + } else { + verts.push(p2x + (px - p2x) * r1, p2y + (py - p2y) * r1); + verts.push(r, g, b, alpha); + + verts.push(p2x - (px - p2x) * r2, p2y - (py - p2y) * r2); + verts.push(r, g, b, alpha); + } + } + + p1x = points[(length - 2) * 2]; + p1y = points[(length - 2) * 2 + 1]; + + p2x = points[(length - 1) * 2]; + p2y = points[(length - 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + verts.push(p2x - perpx * r1, p2y - perpy * r1); + verts.push(r, g, b, alpha); + + verts.push(p2x + perpx * r2, p2y + perpy * r2); + verts.push(r, g, b, alpha); + + indices.push(indexStart); + + for (var _i = 0; _i < indexCount; ++_i) { + indices.push(indexStart++); + } + + indices.push(indexStart - 1); +} + +/** + * Builds a line to draw using the gl.drawArrays(gl.LINES) method + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ + + +/** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildNativeLine(graphicsData, webGLData) { + var i = 0; + var points = graphicsData.points; + + if (points.length === 0) return; + + var verts = webGLData.points; + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + for (i = 1; i < length; i++) { + var p1x = points[(i - 1) * 2]; + var p1y = points[(i - 1) * 2 + 1]; + + var p2x = points[i * 2]; + var p2y = points[i * 2 + 1]; + + verts.push(p1x, p1y); + verts.push(r, g, b, alpha); + + verts.push(p2x, p2y); + verts.push(r, g, b, alpha); + } +} + +},{"../../../math":70,"../../../utils":125}],62:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildPoly; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildPoly(graphicsData, webGLData, webGLDataNativeLines) { + graphicsData.points = graphicsData.shape.points.slice(); + + var points = graphicsData.points; + + if (graphicsData.fill && points.length >= 6) { + var holeArray = []; + // Process holes.. + var holes = graphicsData.holes; + + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + + holeArray.push(points.length / 2); + + points = points.concat(hole.points); + } + + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = (0, _earcut2.default)(points, holeArray, 2); + + if (!triangles) { + return; + } + + var vertPos = verts.length / 6; + + for (var _i = 0; _i < triangles.length; _i += 3) { + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i + 1] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + } + + for (var _i2 = 0; _i2 < length; _i2++) { + verts.push(points[_i2 * 2], points[_i2 * 2 + 1], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth > 0) { + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + } +} + +},{"../../../utils":125,"./buildLine":61,"earcut":2}],63:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRectangle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildRectangle(graphicsData, webGLData, webGLDataNativeLines) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vertPos = verts.length / 6; + + // start + verts.push(x, y); + verts.push(r, g, b, alpha); + + verts.push(x + width, y); + verts.push(r, g, b, alpha); + + verts.push(x, y + height); + verts.push(r, g, b, alpha); + + verts.push(x + width, y + height); + verts.push(r, g, b, alpha); + + // insert 2 dead triangles.. + indices.push(vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y]; + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +},{"../../../utils":125,"./buildLine":61}],64:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRoundedRectangle; + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildRoundedRectangle(graphicsData, webGLData, webGLDataNativeLines) { + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + + recPoints.push(x, y + radius); + quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height, recPoints); + quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius, recPoints); + quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y, recPoints); + quadraticBezierCurve(x + radius, y, x, y, x, y + radius + 0.0000000001, recPoints); + + // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. + // TODO - fix this properly, this is not very elegant.. but it works for now. + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + var triangles = (0, _earcut2.default)(recPoints, null, 2); + + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + + for (var _i = 0, _j = recPoints.length; _i < _j; _i++) { + verts.push(recPoints[_i], recPoints[++_i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +/** + * Calculate a single point for a quadratic bezier curve. + * Utility function used by quadraticBezierCurve. + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} n1 - first number + * @param {number} n2 - second number + * @param {number} perc - percentage + * @return {number} the result + * + */ +function getPt(n1, n2, perc) { + var diff = n2 - n1; + + return n1 + diff * perc; +} + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @return {number[]} an array of points + */ +function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY) { + var out = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : []; + + var n = 20; + var points = out; + + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + + points.push(x, y); + } + + return points; +} + +},{"../../../utils":125,"./buildLine":61,"earcut":2}],65:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = exports.Application = exports.Filter = exports.SpriteMaskFilter = exports.Quad = exports.RenderTarget = exports.ObjectRenderer = exports.WebGLManager = exports.Shader = exports.CanvasRenderTarget = exports.TextureUvs = exports.VideoBaseTexture = exports.BaseRenderTexture = exports.RenderTexture = exports.BaseTexture = exports.TextureMatrix = exports.Texture = exports.Spritesheet = exports.CanvasGraphicsRenderer = exports.GraphicsRenderer = exports.GraphicsData = exports.Graphics = exports.TextMetrics = exports.TextStyle = exports.Text = exports.SpriteRenderer = exports.CanvasTinter = exports.CanvasSpriteRenderer = exports.Sprite = exports.TransformBase = exports.TransformStatic = exports.Transform = exports.Container = exports.DisplayObject = exports.Bounds = exports.glCore = exports.WebGLRenderer = exports.CanvasRenderer = exports.ticker = exports.utils = exports.settings = undefined; + +var _const = require('./const'); + +Object.keys(_const).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _const[key]; + } + }); +}); + +var _math = require('./math'); + +Object.keys(_math).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _math[key]; + } + }); +}); + +var _pixiGlCore = require('pixi-gl-core'); + +Object.defineProperty(exports, 'glCore', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_pixiGlCore).default; + } +}); + +var _Bounds = require('./display/Bounds'); + +Object.defineProperty(exports, 'Bounds', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Bounds).default; + } +}); + +var _DisplayObject = require('./display/DisplayObject'); + +Object.defineProperty(exports, 'DisplayObject', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplayObject).default; + } +}); + +var _Container = require('./display/Container'); + +Object.defineProperty(exports, 'Container', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Container).default; + } +}); + +var _Transform = require('./display/Transform'); + +Object.defineProperty(exports, 'Transform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Transform).default; + } +}); + +var _TransformStatic = require('./display/TransformStatic'); + +Object.defineProperty(exports, 'TransformStatic', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformStatic).default; + } +}); + +var _TransformBase = require('./display/TransformBase'); + +Object.defineProperty(exports, 'TransformBase', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformBase).default; + } +}); + +var _Sprite = require('./sprites/Sprite'); + +Object.defineProperty(exports, 'Sprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Sprite).default; + } +}); + +var _CanvasSpriteRenderer = require('./sprites/canvas/CanvasSpriteRenderer'); + +Object.defineProperty(exports, 'CanvasSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasSpriteRenderer).default; + } +}); + +var _CanvasTinter = require('./sprites/canvas/CanvasTinter'); + +Object.defineProperty(exports, 'CanvasTinter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasTinter).default; + } +}); + +var _SpriteRenderer = require('./sprites/webgl/SpriteRenderer'); + +Object.defineProperty(exports, 'SpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteRenderer).default; + } +}); + +var _Text = require('./text/Text'); + +Object.defineProperty(exports, 'Text', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Text).default; + } +}); + +var _TextStyle = require('./text/TextStyle'); + +Object.defineProperty(exports, 'TextStyle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextStyle).default; + } +}); + +var _TextMetrics = require('./text/TextMetrics'); + +Object.defineProperty(exports, 'TextMetrics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextMetrics).default; + } +}); + +var _Graphics = require('./graphics/Graphics'); + +Object.defineProperty(exports, 'Graphics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Graphics).default; + } +}); + +var _GraphicsData = require('./graphics/GraphicsData'); + +Object.defineProperty(exports, 'GraphicsData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsData).default; + } +}); + +var _GraphicsRenderer = require('./graphics/webgl/GraphicsRenderer'); + +Object.defineProperty(exports, 'GraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsRenderer).default; + } +}); + +var _CanvasGraphicsRenderer = require('./graphics/canvas/CanvasGraphicsRenderer'); + +Object.defineProperty(exports, 'CanvasGraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasGraphicsRenderer).default; + } +}); + +var _Spritesheet = require('./textures/Spritesheet'); + +Object.defineProperty(exports, 'Spritesheet', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Spritesheet).default; + } +}); + +var _Texture = require('./textures/Texture'); + +Object.defineProperty(exports, 'Texture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Texture).default; + } +}); + +var _TextureMatrix = require('./textures/TextureMatrix'); + +Object.defineProperty(exports, 'TextureMatrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureMatrix).default; + } +}); + +var _BaseTexture = require('./textures/BaseTexture'); + +Object.defineProperty(exports, 'BaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseTexture).default; + } +}); + +var _RenderTexture = require('./textures/RenderTexture'); + +Object.defineProperty(exports, 'RenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTexture).default; + } +}); + +var _BaseRenderTexture = require('./textures/BaseRenderTexture'); + +Object.defineProperty(exports, 'BaseRenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseRenderTexture).default; + } +}); + +var _VideoBaseTexture = require('./textures/VideoBaseTexture'); + +Object.defineProperty(exports, 'VideoBaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VideoBaseTexture).default; + } +}); + +var _TextureUvs = require('./textures/TextureUvs'); + +Object.defineProperty(exports, 'TextureUvs', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureUvs).default; + } +}); + +var _CanvasRenderTarget = require('./renderers/canvas/utils/CanvasRenderTarget'); + +Object.defineProperty(exports, 'CanvasRenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasRenderTarget).default; + } +}); + +var _Shader = require('./Shader'); + +Object.defineProperty(exports, 'Shader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Shader).default; + } +}); + +var _WebGLManager = require('./renderers/webgl/managers/WebGLManager'); + +Object.defineProperty(exports, 'WebGLManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLManager).default; + } +}); + +var _ObjectRenderer = require('./renderers/webgl/utils/ObjectRenderer'); + +Object.defineProperty(exports, 'ObjectRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObjectRenderer).default; + } +}); + +var _RenderTarget = require('./renderers/webgl/utils/RenderTarget'); + +Object.defineProperty(exports, 'RenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTarget).default; + } +}); + +var _Quad = require('./renderers/webgl/utils/Quad'); + +Object.defineProperty(exports, 'Quad', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Quad).default; + } +}); + +var _SpriteMaskFilter = require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter'); + +Object.defineProperty(exports, 'SpriteMaskFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteMaskFilter).default; + } +}); + +var _Filter = require('./renderers/webgl/filters/Filter'); + +Object.defineProperty(exports, 'Filter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Filter).default; + } +}); + +var _Application = require('./Application'); + +Object.defineProperty(exports, 'Application', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Application).default; + } +}); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +Object.defineProperty(exports, 'autoDetectRenderer', { + enumerable: true, + get: function get() { + return _autoDetectRenderer.autoDetectRenderer; + } +}); + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _ticker = require('./ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.settings = _settings2.default; +exports.utils = utils; +exports.ticker = ticker; +exports.CanvasRenderer = _CanvasRenderer2.default; +exports.WebGLRenderer = _WebGLRenderer2.default; /** + * @namespace PIXI + */ + +},{"./Application":43,"./Shader":44,"./autoDetectRenderer":45,"./const":46,"./display/Bounds":47,"./display/Container":48,"./display/DisplayObject":49,"./display/Transform":50,"./display/TransformBase":51,"./display/TransformStatic":52,"./graphics/Graphics":53,"./graphics/GraphicsData":54,"./graphics/canvas/CanvasGraphicsRenderer":55,"./graphics/webgl/GraphicsRenderer":57,"./math":70,"./renderers/canvas/CanvasRenderer":77,"./renderers/canvas/utils/CanvasRenderTarget":79,"./renderers/webgl/WebGLRenderer":84,"./renderers/webgl/filters/Filter":86,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":89,"./renderers/webgl/managers/WebGLManager":93,"./renderers/webgl/utils/ObjectRenderer":94,"./renderers/webgl/utils/Quad":95,"./renderers/webgl/utils/RenderTarget":96,"./settings":101,"./sprites/Sprite":102,"./sprites/canvas/CanvasSpriteRenderer":103,"./sprites/canvas/CanvasTinter":104,"./sprites/webgl/SpriteRenderer":106,"./text/Text":108,"./text/TextMetrics":109,"./text/TextStyle":110,"./textures/BaseRenderTexture":111,"./textures/BaseTexture":112,"./textures/RenderTexture":113,"./textures/Spritesheet":114,"./textures/Texture":115,"./textures/TextureMatrix":116,"./textures/TextureUvs":117,"./textures/VideoBaseTexture":118,"./ticker":121,"./utils":125,"pixi-gl-core":15}],66:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Matrix = require('./Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16 + +var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; +var tempMatrices = []; + +var mul = []; + +function signum(x) { + if (x < 0) { + return -1; + } + if (x > 0) { + return 1; + } + + return 0; +} + +function init() { + for (var i = 0; i < 16; i++) { + var row = []; + + mul.push(row); + + for (var j = 0; j < 16; j++) { + var _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); + var _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); + var _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); + var _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); + + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + + for (var _i = 0; _i < 16; _i++) { + var mat = new _Matrix2.default(); + + mat.set(ux[_i], uy[_i], vx[_i], vy[_i], 0, 0); + tempMatrices.push(mat); + } +} + +init(); + +/** + * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, + * D8 is the same but with diagonals. Used for texture rotations. + * + * Vector xX(i), xY(i) is U-axis of sprite with rotation i + * Vector yY(i), yY(i) is V-axis of sprite with rotation i + * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) + * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) + * This is the small part of gameofbombs.com portal system. It works. + * + * @author Ivan @ivanpopelyshev + * @class + * @memberof PIXI + */ +var GroupD8 = { + E: 0, + SE: 1, + S: 2, + SW: 3, + W: 4, + NW: 5, + N: 6, + NE: 7, + MIRROR_VERTICAL: 8, + MIRROR_HORIZONTAL: 12, + uX: function uX(ind) { + return ux[ind]; + }, + uY: function uY(ind) { + return uy[ind]; + }, + vX: function vX(ind) { + return vx[ind]; + }, + vY: function vY(ind) { + return vy[ind]; + }, + inv: function inv(rotation) { + if (rotation & 8) { + return rotation & 15; + } + + return -rotation & 7; + }, + add: function add(rotationSecond, rotationFirst) { + return mul[rotationSecond][rotationFirst]; + }, + sub: function sub(rotationSecond, rotationFirst) { + return mul[rotationSecond][GroupD8.inv(rotationFirst)]; + }, + + /** + * Adds 180 degrees to rotation. Commutative operation. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to rotate. + * @returns {number} rotated number + */ + rotate180: function rotate180(rotation) { + return rotation ^ 4; + }, + + /** + * Direction of main vector can be horizontal, vertical or diagonal. + * Some objects work with vertical directions different. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the direction is vertical + */ + isVertical: function isVertical(rotation) { + return (rotation & 3) === 2; + }, + + /** + * @memberof PIXI.GroupD8 + * @param {number} dx - TODO + * @param {number} dy - TODO + * + * @return {number} TODO + */ + byDirection: function byDirection(dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return GroupD8.S; + } + + return GroupD8.N; + } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return GroupD8.E; + } + + return GroupD8.W; + } else if (dy > 0) { + if (dx > 0) { + return GroupD8.SE; + } + + return GroupD8.SW; + } else if (dx > 0) { + return GroupD8.NE; + } + + return GroupD8.NW; + }, + + /** + * Helps sprite to compensate texture packer rotation. + * + * @memberof PIXI.GroupD8 + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {number} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function matrixAppendRotationInv(matrix, rotation) { + var tx = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var ty = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + // Packer used "rotation", we use "inv(rotation)" + var mat = tempMatrices[GroupD8.inv(rotation)]; + + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + } +}; + +exports.default = GroupD8; + +},{"./Matrix":67}],67:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Point = require('./Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The PixiJS Matrix class as an object, which makes it a lot faster, + * here is a representation of it : + * | a | c | tx| + * | b | d | ty| + * | 0 | 0 | 1 | + * + * @class + * @memberof PIXI + */ +var Matrix = function () { + /** + * @param {number} [a=1] - x scale + * @param {number} [b=0] - x skew + * @param {number} [c=0] - y skew + * @param {number} [d=1] - y scale + * @param {number} [tx=0] - x translation + * @param {number} [ty=0] - y translation + */ + function Matrix() { + var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var d = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var tx = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var ty = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + + _classCallCheck(this, Matrix); + + /** + * @member {number} + * @default 1 + */ + this.a = a; + + /** + * @member {number} + * @default 0 + */ + this.b = b; + + /** + * @member {number} + * @default 0 + */ + this.c = c; + + /** + * @member {number} + * @default 1 + */ + this.d = d; + + /** + * @member {number} + * @default 0 + */ + this.tx = tx; + + /** + * @member {number} + * @default 0 + */ + this.ty = ty; + + this.array = null; + } + + /** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @param {number[]} array - The array that the matrix will be populated from. + */ + + + Matrix.prototype.fromArray = function fromArray(array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + }; + + /** + * sets the matrix properties + * + * @param {number} a - Matrix component + * @param {number} b - Matrix component + * @param {number} c - Matrix component + * @param {number} d - Matrix component + * @param {number} tx - Matrix component + * @param {number} ty - Matrix component + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.set = function set(a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + }; + + /** + * Creates an array from the current Matrix object. + * + * @param {boolean} transpose - Whether we need to transpose the matrix or not + * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out + * @return {number[]} the newly created array which contains the matrix + */ + + + Matrix.prototype.toArray = function toArray(transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + + var array = out || this.array; + + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + }; + + /** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, transformed through this matrix + */ + + + Matrix.prototype.apply = function apply(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; + + return newPos; + }; + + /** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, inverse-transformed through this matrix + */ + + + Matrix.prototype.applyInverse = function applyInverse(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var id = 1 / (this.a * this.d + this.c * -this.b); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + }; + + /** + * Translates the matrix on the x and y. + * + * @param {number} x How much to translate x by + * @param {number} y How much to translate y by + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.translate = function translate(x, y) { + this.tx += x; + this.ty += y; + + return this; + }; + + /** + * Applies a scale transformation to the matrix. + * + * @param {number} x The amount to scale horizontally + * @param {number} y The amount to scale vertically + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.scale = function scale(x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + }; + + /** + * Applies a rotation transformation to the matrix. + * + * @param {number} angle - The angle in radians. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.rotate = function rotate(angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos - this.b * sin; + this.b = a1 * sin + this.b * cos; + this.c = c1 * cos - this.d * sin; + this.d = c1 * sin + this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + }; + + /** + * Appends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to append. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.append = function append(matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + }; + + /** + * Sets the matrix based on all the available properties + * + * @param {number} x - Position on the x axis + * @param {number} y - Position on the y axis + * @param {number} pivotX - Pivot on the x axis + * @param {number} pivotY - Pivot on the y axis + * @param {number} scaleX - Scale on the x axis + * @param {number} scaleY - Scale on the y axis + * @param {number} rotation - Rotation in radians + * @param {number} skewX - Skew on the x axis + * @param {number} skewY - Skew on the y axis + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.setTransform = function setTransform(x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + this.a = Math.cos(rotation + skewY) * scaleX; + this.b = Math.sin(rotation + skewY) * scaleX; + this.c = -Math.sin(rotation - skewX) * scaleY; + this.d = Math.cos(rotation - skewX) * scaleY; + + this.tx = x - (pivotX * this.a + pivotY * this.c); + this.ty = y - (pivotX * this.b + pivotY * this.d); + + return this; + }; + + /** + * Prepends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to prepend + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.prepend = function prepend(matrix) { + var tx1 = this.tx; + + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + + this.a = a1 * matrix.a + this.b * matrix.c; + this.b = a1 * matrix.b + this.b * matrix.d; + this.c = c1 * matrix.a + this.d * matrix.c; + this.d = c1 * matrix.b + this.d * matrix.d; + } + + this.tx = tx1 * matrix.a + this.ty * matrix.c + matrix.tx; + this.ty = tx1 * matrix.b + this.ty * matrix.d + matrix.ty; + + return this; + }; + + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * + * @param {PIXI.Transform|PIXI.TransformStatic} transform - The transform to apply the properties to. + * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properties + */ + + + Matrix.prototype.decompose = function decompose(transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + + var skewX = -Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + + var delta = Math.abs(skewX + skewY); + + if (delta < 0.00001 || Math.abs(_const.PI_2 - delta) < 0.00001) { + transform.rotation = skewY; + + if (a < 0 && d >= 0) { + transform.rotation += transform.rotation <= 0 ? Math.PI : -Math.PI; + } + + transform.skew.x = transform.skew.y = 0; + } else { + transform.rotation = 0; + transform.skew.x = skewX; + transform.skew.y = skewY; + } + + // next set scale + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); + + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; + + return transform; + }; + + /** + * Inverts this matrix + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.invert = function invert() { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1 * d1 - b1 * c1; + + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = (c1 * this.ty - d1 * tx1) / n; + this.ty = -(a1 * this.ty - b1 * tx1) / n; + + return this; + }; + + /** + * Resets this Matix to an identity (default) matrix. + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.identity = function identity() { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + + return this; + }; + + /** + * Creates a new Matrix object with the same values as this one. + * + * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. + */ + + + Matrix.prototype.clone = function clone() { + var matrix = new Matrix(); + + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * Changes the values of the given matrix to be the same as the ones in this matrix + * + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @return {PIXI.Matrix} The matrix given in parameter with its values updated. + */ + + + Matrix.prototype.copy = function copy(matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * A default (identity) matrix + * + * @static + * @const + */ + + + _createClass(Matrix, null, [{ + key: 'IDENTITY', + get: function get() { + return new Matrix(); + } + + /** + * A temp matrix + * + * @static + * @const + */ + + }, { + key: 'TEMP_MATRIX', + get: function get() { + return new Matrix(); + } + }]); + + return Matrix; +}(); + +exports.default = Matrix; + +},{"../const":46,"./Point":69}],68:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * An observable point is a point that triggers a callback when the point's position is changed. + * + * @class + * @memberof PIXI + */ +var ObservablePoint = function () { + /** + * @param {Function} cb - callback when changed + * @param {object} scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope) { + var x = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var y = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, ObservablePoint); + + this._x = x; + this._y = y; + + this.cb = cb; + this.scope = scope; + } + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + ObservablePoint.prototype.set = function set(x, y) { + var _x = x || 0; + var _y = y || (y !== 0 ? _x : 0); + + if (this._x !== _x || this._y !== _y) { + this._x = _x; + this._y = _y; + this.cb.call(this.scope); + } + }; + + /** + * Copies the data from another point + * + * @param {PIXI.Point|PIXI.ObservablePoint} point - point to copy from + */ + + + ObservablePoint.prototype.copy = function copy(point) { + if (this._x !== point.x || this._y !== point.y) { + this._x = point.x; + this._y = point.y; + this.cb.call(this.scope); + } + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + + _createClass(ObservablePoint, [{ + key: "x", + get: function get() { + return this._x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + } + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + }, { + key: "y", + get: function get() { + return this._y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + } + }]); + + return ObservablePoint; +}(); + +exports.default = ObservablePoint; + +},{}],69:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * + * @class + * @memberof PIXI + */ +var Point = function () { + /** + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function Point() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + + _classCallCheck(this, Point); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + } + + /** + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point + */ + + + Point.prototype.clone = function clone() { + return new Point(this.x, this.y); + }; + + /** + * Copies x and y from the given point + * + * @param {PIXI.Point} p - The point to copy. + */ + + + Point.prototype.copy = function copy(p) { + this.set(p.x, p.y); + }; + + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.Point} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + + + Point.prototype.equals = function equals(p) { + return p.x === this.x && p.y === this.y; + }; + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + Point.prototype.set = function set(x, y) { + this.x = x || 0; + this.y = y || (y !== 0 ? this.x : 0); + }; + + return Point; +}(); + +exports.default = Point; + +},{}],70:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('./Point'); + +Object.defineProperty(exports, 'Point', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Point).default; + } +}); + +var _ObservablePoint = require('./ObservablePoint'); + +Object.defineProperty(exports, 'ObservablePoint', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObservablePoint).default; + } +}); + +var _Matrix = require('./Matrix'); + +Object.defineProperty(exports, 'Matrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Matrix).default; + } +}); + +var _GroupD = require('./GroupD8'); + +Object.defineProperty(exports, 'GroupD8', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GroupD).default; + } +}); + +var _Circle = require('./shapes/Circle'); + +Object.defineProperty(exports, 'Circle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Circle).default; + } +}); + +var _Ellipse = require('./shapes/Ellipse'); + +Object.defineProperty(exports, 'Ellipse', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Ellipse).default; + } +}); + +var _Polygon = require('./shapes/Polygon'); + +Object.defineProperty(exports, 'Polygon', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Polygon).default; + } +}); + +var _Rectangle = require('./shapes/Rectangle'); + +Object.defineProperty(exports, 'Rectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rectangle).default; + } +}); + +var _RoundedRectangle = require('./shapes/RoundedRectangle'); + +Object.defineProperty(exports, 'RoundedRectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RoundedRectangle).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./GroupD8":66,"./Matrix":67,"./ObservablePoint":68,"./Point":69,"./shapes/Circle":71,"./shapes/Ellipse":72,"./shapes/Polygon":73,"./shapes/Rectangle":74,"./shapes/RoundedRectangle":75}],71:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Circle object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Circle = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [radius=0] - The radius of the circle + */ + function Circle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var radius = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + _classCallCheck(this, Circle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.CIRC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.CIRC; + } + + /** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ + + + Circle.prototype.clone = function clone() { + return new Circle(this.x, this.y, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this circle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Circle + */ + + + Circle.prototype.contains = function contains(x, y) { + if (this.radius <= 0) { + return false; + } + + var r2 = this.radius * this.radius; + var dx = this.x - x; + var dy = this.y - y; + + dx *= dx; + dy *= dy; + + return dx + dy <= r2; + }; + + /** + * Returns the framing rectangle of the circle as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Circle.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + + return Circle; +}(); + +exports.default = Circle; + +},{"../../const":46,"./Rectangle":74}],72:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Ellipse object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Ellipse = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [width=0] - The half width of this ellipse + * @param {number} [height=0] - The half height of this ellipse + */ + function Ellipse() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Ellipse); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.ELIP + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.ELIP; + } + + /** + * Creates a clone of this Ellipse instance + * + * @return {PIXI.Ellipse} a copy of the ellipse + */ + + + Ellipse.prototype.clone = function clone() { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coords are within this ellipse + */ + + + Ellipse.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + // normalize the coords to an ellipse with center 0,0 + var normx = (x - this.x) / this.width; + var normy = (y - this.y) / this.height; + + normx *= normx; + normy *= normy; + + return normx + normy <= 1; + }; + + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Ellipse.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.width, this.y - this.height, this.width, this.height); + }; + + return Ellipse; +}(); + +exports.default = Ellipse; + +},{"../../const":46,"./Rectangle":74}],73:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('../Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Polygon = function () { + /** + * @param {PIXI.Point[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + for (var _len = arguments.length, points = Array(_len), _key = 0; _key < _len; _key++) { + points[_key] = arguments[_key]; + } + + _classCallCheck(this, Polygon); + + if (Array.isArray(points[0])) { + points = points[0]; + } + + // if this is an array of points, convert it to a flat array of numbers + if (points[0] instanceof _Point2.default) { + var p = []; + + for (var i = 0, il = points.length; i < il; i++) { + p.push(points[i].x, points[i].y); + } + + points = p; + } + + this.closed = true; + + /** + * An array of the points of this polygon + * + * @member {number[]} + */ + this.points = points; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.POLY + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.POLY; + } + + /** + * Creates a clone of this polygon + * + * @return {PIXI.Polygon} a copy of the polygon + */ + + + Polygon.prototype.clone = function clone() { + return new Polygon(this.points.slice()); + }; + + /** + * Closes the polygon, adding points if necessary. + * + */ + + + Polygon.prototype.close = function close() { + var points = this.points; + + // close the poly if the value is true! + if (points[0] !== points[points.length - 2] || points[1] !== points[points.length - 1]) { + points.push(points[0], points[1]); + } + }; + + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this polygon + */ + + + Polygon.prototype.contains = function contains(x, y) { + var inside = false; + + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + + for (var i = 0, j = length - 1; i < length; j = i++) { + var xi = this.points[i * 2]; + var yi = this.points[i * 2 + 1]; + var xj = this.points[j * 2]; + var yj = this.points[j * 2 + 1]; + var intersect = yi > y !== yj > y && x < (xj - xi) * ((y - yi) / (yj - yi)) + xi; + + if (intersect) { + inside = !inside; + } + } + + return inside; + }; + + return Polygon; +}(); + +exports.default = Polygon; + +},{"../../const":46,"../Point":69}],74:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * + * @class + * @memberof PIXI + */ +var Rectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle + * @param {number} [width=0] - The overall width of this rectangle + * @param {number} [height=0] - The overall height of this rectangle + */ + function Rectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Rectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = Number(x); + + /** + * @member {number} + * @default 0 + */ + this.y = Number(y); + + /** + * @member {number} + * @default 0 + */ + this.width = Number(width); + + /** + * @member {number} + * @default 0 + */ + this.height = Number(height); + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.RECT + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RECT; + } + + /** + * returns the left edge of the rectangle + * + * @member {number} + */ + + + /** + * Creates a clone of this Rectangle + * + * @return {PIXI.Rectangle} a copy of the rectangle + */ + Rectangle.prototype.clone = function clone() { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + + /** + * Copies another rectangle to this one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to copy. + * @return {PIXI.Rectangle} Returns itself. + */ + + + Rectangle.prototype.copy = function copy(rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + + return this; + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rectangle + */ + + + Rectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + + return false; + }; + + /** + * Pads the rectangle making it grow in all directions. + * + * @param {number} paddingX - The horizontal padding amount. + * @param {number} [paddingY] - The vertical padding amount. + */ + + + Rectangle.prototype.pad = function pad(paddingX, paddingY) { + paddingX = paddingX || 0; + paddingY = paddingY || (paddingY !== 0 ? paddingX : 0); + + this.x -= paddingX; + this.y -= paddingY; + + this.width += paddingX * 2; + this.height += paddingY * 2; + }; + + /** + * Fits this rectangle around the passed one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to fit. + */ + + + Rectangle.prototype.fit = function fit(rectangle) { + if (this.x < rectangle.x) { + this.width += this.x; + if (this.width < 0) { + this.width = 0; + } + + this.x = rectangle.x; + } + + if (this.y < rectangle.y) { + this.height += this.y; + if (this.height < 0) { + this.height = 0; + } + this.y = rectangle.y; + } + + if (this.x + this.width > rectangle.x + rectangle.width) { + this.width = rectangle.width - this.x; + if (this.width < 0) { + this.width = 0; + } + } + + if (this.y + this.height > rectangle.y + rectangle.height) { + this.height = rectangle.height - this.y; + if (this.height < 0) { + this.height = 0; + } + } + }; + + /** + * Enlarges this rectangle to include the passed rectangle. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to include. + */ + + + Rectangle.prototype.enlarge = function enlarge(rectangle) { + var x1 = Math.min(this.x, rectangle.x); + var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.min(this.y, rectangle.y); + var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); + + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + }; + + _createClass(Rectangle, [{ + key: 'left', + get: function get() { + return this.x; + } + + /** + * returns the right edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'right', + get: function get() { + return this.x + this.width; + } + + /** + * returns the top edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'top', + get: function get() { + return this.y; + } + + /** + * returns the bottom edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'bottom', + get: function get() { + return this.y + this.height; + } + + /** + * A constant empty rectangle. + * + * @static + * @constant + */ + + }], [{ + key: 'EMPTY', + get: function get() { + return new Rectangle(0, 0, 0, 0); + } + }]); + + return Rectangle; +}(); + +exports.default = Rectangle; + +},{"../../const":46}],75:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. + * + * @class + * @memberof PIXI + */ +var RoundedRectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle + * @param {number} [width=0] - The overall width of this rounded rectangle + * @param {number} [height=0] - The overall height of this rounded rectangle + * @param {number} [radius=20] - Controls the radius of the rounded corners + */ + function RoundedRectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var radius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 20; + + _classCallCheck(this, RoundedRectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * @member {number} + * @default 20 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readonly + * @default PIXI.SHAPES.RREC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RREC; + } + + /** + * Creates a clone of this Rounded Rectangle + * + * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle + */ + + + RoundedRectangle.prototype.clone = function clone() { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + */ + + + RoundedRectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + if (y >= this.y + this.radius && y <= this.y + this.height - this.radius || x >= this.x + this.radius && x <= this.x + this.width - this.radius) { + return true; + } + var dx = x - (this.x + this.radius); + var dy = y - (this.y + this.radius); + var radius2 = this.radius * this.radius; + + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.width - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dy = y - (this.y + this.height - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + } + } + + return false; + }; + + return RoundedRectangle; +}(); + +exports.default = RoundedRectangle; + +},{"../../const":46}],76:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _math = require('../math'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _Container = require('../display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMatrix = new _math.Matrix(); + +/** + * The SystemRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.WebGLRenderer} which can be used for rendering a PixiJS scene. + * + * @abstract + * @class + * @extends EventEmitter + * @memberof PIXI + */ + +var SystemRenderer = function (_EventEmitter) { + _inherits(SystemRenderer, _EventEmitter); + + // eslint-disable-next-line valid-jsdoc + /** + * @param {string} system - The name of the system this renderer is for. + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function SystemRenderer(system, options, arg2, arg3) { + _classCallCheck(this, SystemRenderer); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + (0, _utils.sayHello)(system); + + // Support for constructor(system, screenWidth, screenHeight, options) + if (typeof options === 'number') { + options = Object.assign({ + width: options, + height: arg2 || _settings2.default.RENDER_OPTIONS.height + }, arg3); + } + + // Add the default render options + options = Object.assign({}, _settings2.default.RENDER_OPTIONS, options); + + /** + * The supplied constructor options. + * + * @member {Object} + * @readOnly + */ + _this.options = options; + + /** + * The type of the renderer. + * + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.UNKNOWN; + + /** + * Measurements of the screen. (0, 0, screenWidth, screenHeight) + * + * Its safe to use as filterArea or hitArea for whole stage + * + * @member {PIXI.Rectangle} + */ + _this.screen = new _math.Rectangle(0, 0, options.width, options.height); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.view = options.view || document.createElement('canvas'); + + /** + * The resolution / device pixel ratio of the renderer + * + * @member {number} + * @default 1 + */ + _this.resolution = options.resolution || _settings2.default.RESOLUTION; + + /** + * Whether the render view is transparent + * + * @member {boolean} + */ + _this.transparent = options.transparent; + + /** + * Whether css dimensions of canvas view should be resized to screen dimensions automatically + * + * @member {boolean} + */ + _this.autoResize = options.autoResize || false; + + /** + * Tracks the blend modes useful for this renderer. + * + * @member {object} + */ + _this.blendModes = null; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example if + * your game has a canvas filling background image you often don't need this set. + * + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + * + * @member {boolean} + */ + _this.roundPixels = options.roundPixels; + + /** + * The background color as a number. + * + * @member {number} + * @private + */ + _this._backgroundColor = 0x000000; + + /** + * The background color as an [R, G, B] array. + * + * @member {number[]} + * @private + */ + _this._backgroundColorRgba = [0, 0, 0, 0]; + + /** + * The background color as a string. + * + * @member {string} + * @private + */ + _this._backgroundColorString = '#000000'; + + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + + /** + * This temporary display object used as the parent of the currently being rendered item + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._tempDisplayObjectParent = new _Container2.default(); + + /** + * The last root object that the renderer tried to render. + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._lastObjectRendered = _this._tempDisplayObjectParent; + return _this; + } + + /** + * Same as view.width, actual number of pixels in the canvas by horizontal + * + * @member {number} + * @readonly + * @default 800 + */ + + + /** + * Resizes the screen and canvas to the specified width and height + * Canvas dimensions are multiplied by resolution + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + SystemRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + this.screen.width = screenWidth; + this.screen.height = screenHeight; + + this.view.width = screenWidth * this.resolution; + this.view.height = screenHeight * this.resolution; + + if (this.autoResize) { + this.view.style.width = screenWidth + 'px'; + this.view.style.height = screenHeight + 'px'; + } + }; + + /** + * Useful function that returns a texture of the display object that can then be used to create sprites + * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. + * + * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from + * @param {number} scaleMode - Should be one of the scaleMode consts + * @param {number} resolution - The resolution / device pixel ratio of the texture being generated + * @param {PIXI.Rectangle} [region] - The region of the displayObject, that shall be rendered, + * if no region is specified, defaults to the local bounds of the displayObject. + * @return {PIXI.Texture} a texture of the graphics object + */ + + + SystemRenderer.prototype.generateTexture = function generateTexture(displayObject, scaleMode, resolution, region) { + region = region || displayObject.getLocalBounds(); + + var renderTexture = _RenderTexture2.default.create(region.width | 0, region.height | 0, scaleMode, resolution); + + tempMatrix.tx = -region.x; + tempMatrix.ty = -region.y; + + this.render(displayObject, renderTexture, false, tempMatrix, true); + + return renderTexture; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + SystemRenderer.prototype.destroy = function destroy(removeView) { + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } + + this.type = _const.RENDERER_TYPE.UNKNOWN; + + this.view = null; + + this.screen = null; + + this.resolution = 0; + + this.transparent = false; + + this.autoResize = false; + + this.blendModes = null; + + this.options = null; + + this.preserveDrawingBuffer = false; + this.clearBeforeRender = false; + + this.roundPixels = false; + + this._backgroundColor = 0; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + + this._tempDisplayObjectParent = null; + this._lastObjectRendered = null; + }; + + /** + * The background color to fill if not transparent + * + * @member {number} + */ + + + _createClass(SystemRenderer, [{ + key: 'width', + get: function get() { + return this.view.width; + } + + /** + * Same as view.height, actual number of pixels in the canvas by vertical + * + * @member {number} + * @readonly + * @default 600 + */ + + }, { + key: 'height', + get: function get() { + return this.view.height; + } + }, { + key: 'backgroundColor', + get: function get() { + return this._backgroundColor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._backgroundColor = value; + this._backgroundColorString = (0, _utils.hex2string)(value); + (0, _utils.hex2rgb)(value, this._backgroundColorRgba); + } + }]); + + return SystemRenderer; +}(_eventemitter2.default); + +exports.default = SystemRenderer; + +},{"../const":46,"../display/Container":48,"../math":70,"../settings":101,"../textures/RenderTexture":113,"../utils":125,"eventemitter3":3}],77:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _CanvasMaskManager = require('./utils/CanvasMaskManager'); + +var _CanvasMaskManager2 = _interopRequireDefault(_CanvasMaskManager); + +var _CanvasRenderTarget = require('./utils/CanvasRenderTarget'); + +var _CanvasRenderTarget2 = _interopRequireDefault(_CanvasRenderTarget); + +var _mapCanvasBlendModesToPixi = require('./utils/mapCanvasBlendModesToPixi'); + +var _mapCanvasBlendModesToPixi2 = _interopRequireDefault(_mapCanvasBlendModesToPixi); + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should + * be used for browsers that do not support WebGL. Don't forget to add the CanvasRenderer.view to + * your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ +var CanvasRenderer = function (_SystemRenderer) { + _inherits(CanvasRenderer, _SystemRenderer); + + // eslint-disable-next-line valid-jsdoc + /** + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function CanvasRenderer(options, arg2, arg3) { + _classCallCheck(this, CanvasRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'Canvas', options, arg2, arg3)); + + _this.type = _const.RENDERER_TYPE.CANVAS; + + /** + * The root canvas 2d context that everything is drawn with. + * + * @member {CanvasRenderingContext2D} + */ + _this.rootContext = _this.view.getContext('2d', { alpha: _this.transparent }); + + /** + * The currently active canvas 2d context (could change with renderTextures) + * + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.rootContext; + + /** + * Boolean flag controlling canvas refresh. + * + * @member {boolean} + */ + _this.refresh = true; + + /** + * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. + * + * @member {PIXI.CanvasMaskManager} + */ + _this.maskManager = new _CanvasMaskManager2.default(_this); + + /** + * The canvas property used to set the canvas smoothing property. + * + * @member {string} + */ + _this.smoothProperty = 'imageSmoothingEnabled'; + + if (!_this.rootContext.imageSmoothingEnabled) { + if (_this.rootContext.webkitImageSmoothingEnabled) { + _this.smoothProperty = 'webkitImageSmoothingEnabled'; + } else if (_this.rootContext.mozImageSmoothingEnabled) { + _this.smoothProperty = 'mozImageSmoothingEnabled'; + } else if (_this.rootContext.oImageSmoothingEnabled) { + _this.smoothProperty = 'oImageSmoothingEnabled'; + } else if (_this.rootContext.msImageSmoothingEnabled) { + _this.smoothProperty = 'msImageSmoothingEnabled'; + } + } + + _this.initPlugins(); + + _this.blendModes = (0, _mapCanvasBlendModesToPixi2.default)(); + _this._activeBlendMode = null; + + _this.renderingToScreen = false; + + _this.resize(_this.options.width, _this.options.height); + + /** + * Fired after rendering finishes. + * + * @event PIXI.CanvasRenderer#postrender + */ + + /** + * Fired before rendering starts. + * + * @event PIXI.CanvasRenderer#prerender + */ + return _this; + } + + /** + * Renders the object to this canvas view + * + * @param {PIXI.DisplayObject} displayObject - The object to be rendered + * @param {PIXI.RenderTexture} [renderTexture] - A render texture to be rendered to. + * If unset, it will render to the root context. + * @param {boolean} [clear=false] - Whether to clear the canvas before drawing + * @param {PIXI.Transform} [transform] - A transformation to be applied + * @param {boolean} [skipUpdateTransform=false] - Whether to skip the update transform + */ + + + CanvasRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!this.view) { + return; + } + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + var rootResolution = this.resolution; + + if (renderTexture) { + renderTexture = renderTexture.baseTexture || renderTexture; + + if (!renderTexture._canvasRenderTarget) { + renderTexture._canvasRenderTarget = new _CanvasRenderTarget2.default(renderTexture.width, renderTexture.height, renderTexture.resolution); + renderTexture.source = renderTexture._canvasRenderTarget.canvas; + renderTexture.valid = true; + } + + this.context = renderTexture._canvasRenderTarget.context; + this.resolution = renderTexture._canvasRenderTarget.resolution; + } else { + this.context = this.rootContext; + } + + var context = this.context; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + var tempWt = this._tempDisplayObjectParent.transform.worldTransform; + + if (transform) { + transform.copy(tempWt); + + // lets not forget to flag the parent transform as dirty... + this._tempDisplayObjectParent.transform._worldID = -1; + } else { + tempWt.identity(); + } + + displayObject.parent = this._tempDisplayObjectParent; + + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + context.save(); + context.setTransform(1, 0, 0, 1, 0, 0); + context.globalAlpha = 1; + this._activeBlendMode = _const.BLEND_MODES.NORMAL; + context.globalCompositeOperation = this.blendModes[_const.BLEND_MODES.NORMAL]; + + if (navigator.isCocoonJS && this.view.screencanvas) { + context.fillStyle = 'black'; + context.clear(); + } + + if (clear !== undefined ? clear : this.clearBeforeRender) { + if (this.renderingToScreen) { + if (this.transparent) { + context.clearRect(0, 0, this.width, this.height); + } else { + context.fillStyle = this._backgroundColorString; + context.fillRect(0, 0, this.width, this.height); + } + } // else { + // TODO: implement background for CanvasRenderTarget or RenderTexture? + // } + } + + // TODO RENDER TARGET STUFF HERE.. + var tempContext = this.context; + + this.context = context; + displayObject.renderCanvas(this); + this.context = tempContext; + + context.restore(); + + this.resolution = rootResolution; + + this.emit('postrender'); + }; + + /** + * Clear the canvas of renderer. + * + * @param {string} [clearColor] - Clear the canvas with this color, except the canvas is transparent. + */ + + + CanvasRenderer.prototype.clear = function clear(clearColor) { + var context = this.context; + + clearColor = clearColor || this._backgroundColorString; + + if (!this.transparent && clearColor) { + context.fillStyle = clearColor; + context.fillRect(0, 0, this.width, this.height); + } else { + context.clearRect(0, 0, this.width, this.height); + } + }; + + /** + * Sets the blend mode of the renderer. + * + * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values. + */ + + + CanvasRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + if (this._activeBlendMode === blendMode) { + return; + } + + this._activeBlendMode = blendMode; + this.context.globalCompositeOperation = this.blendModes[blendMode]; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + CanvasRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // call the base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.context = null; + + this.refresh = true; + + this.maskManager.destroy(); + this.maskManager = null; + + this.smoothProperty = null; + }; + + /** + * Resizes the canvas view to the specified width and height. + * + * @extends PIXI.SystemRenderer#resize + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + CanvasRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + _SystemRenderer.prototype.resize.call(this, screenWidth, screenHeight); + + // reset the scale mode.. oddly this seems to be reset when the canvas is resized. + // surely a browser bug?? Let PixiJS fix that for you.. + if (this.smoothProperty) { + this.rootContext[this.smoothProperty] = _settings2.default.SCALE_MODE === _const.SCALE_MODES.LINEAR; + } + }; + + /** + * Checks if blend mode has changed. + */ + + + CanvasRenderer.prototype.invalidateBlendMode = function invalidateBlendMode() { + this._activeBlendMode = this.blendModes.indexOf(this.context.globalCompositeOperation); + }; + + return CanvasRenderer; +}(_SystemRenderer3.default); + +/** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @name PIXI.CanvasRenderer#plugins + * @type {object} + * @readonly + * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.extract.CanvasExtract} extract Extract image data from renderer. + * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.prepare.CanvasPrepare} prepare Pre-render display objects. + */ + +/** + * Adds a plugin to the renderer. + * + * @method PIXI.CanvasRenderer#registerPlugin + * @param {string} pluginName - The name of the plugin. + * @param {Function} ctor - The constructor function or class for the plugin. + */ + +exports.default = CanvasRenderer; +_utils.pluginTarget.mixin(CanvasRenderer); + +},{"../../const":46,"../../settings":101,"../../utils":125,"../SystemRenderer":76,"./utils/CanvasMaskManager":78,"./utils/CanvasRenderTarget":79,"./utils/mapCanvasBlendModesToPixi":81}],78:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A set of functions used to handle masking. + * + * @class + * @memberof PIXI + */ +var CanvasMaskManager = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + function CanvasMaskManager(renderer) { + _classCallCheck(this, CanvasMaskManager); + + this.renderer = renderer; + } + + /** + * This method adds it to the current stack of masks. + * + * @param {object} maskData - the maskData that will be pushed + */ + + + CanvasMaskManager.prototype.pushMask = function pushMask(maskData) { + var renderer = this.renderer; + + renderer.context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.transform.worldTransform; + var resolution = renderer.resolution; + + renderer.context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // TODO suport sprite alpha masks?? + // lots of effort required. If demand is great enough.. + if (!maskData._texture) { + this.renderGraphicsShape(maskData); + renderer.context.clip(); + } + + maskData.worldAlpha = cacheAlpha; + }; + + /** + * Renders a PIXI.Graphics shape. + * + * @param {PIXI.Graphics} graphics - The object to render. + */ + + + CanvasMaskManager.prototype.renderGraphicsShape = function renderGraphicsShape(graphics) { + var context = this.renderer.context; + var len = graphics.graphicsData.length; + + if (len === 0) { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === _const.SHAPES.POLY) { + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; j++) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) { + context.closePath(); + } + } else if (data.type === _const.SHAPES.RECT) { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } + }; + + /** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @param {PIXI.CanvasRenderer} renderer - The renderer context to use. + */ + + + CanvasMaskManager.prototype.popMask = function popMask(renderer) { + renderer.context.restore(); + renderer.invalidateBlendMode(); + }; + + /** + * Destroys this canvas mask manager. + * + */ + + + CanvasMaskManager.prototype.destroy = function destroy() { + /* empty */ + }; + + return CanvasMaskManager; +}(); + +exports.default = CanvasMaskManager; + +},{"../../../const":46}],79:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Creates a Canvas element of the given size. + * + * @class + * @memberof PIXI + */ +var CanvasRenderTarget = function () { + /** + * @param {number} width - the width for the newly created canvas + * @param {number} height - the height for the newly created canvas + * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + _classCallCheck(this, CanvasRenderTarget); + + /** + * The Canvas object that belongs to this CanvasRenderTarget. + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @member {CanvasRenderingContext2D} + */ + this.context = this.canvas.getContext('2d'); + + this.resolution = resolution || _settings2.default.RESOLUTION; + + this.resize(width, height); + } + + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * + * @private + */ + + + CanvasRenderTarget.prototype.clear = function clear() { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + + /** + * Resizes the canvas to the specified width and height. + * + * @param {number} width - the new width of the canvas + * @param {number} height - the new height of the canvas + */ + + + CanvasRenderTarget.prototype.resize = function resize(width, height) { + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; + }; + + /** + * Destroys this canvas. + * + */ + + + CanvasRenderTarget.prototype.destroy = function destroy() { + this.context = null; + this.canvas = null; + }; + + /** + * The width of the canvas buffer in pixels. + * + * @member {number} + */ + + + _createClass(CanvasRenderTarget, [{ + key: 'width', + get: function get() { + return this.canvas.width; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.width = val; + } + + /** + * The height of the canvas buffer in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.canvas.height; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.height = val; + } + }]); + + return CanvasRenderTarget; +}(); + +exports.default = CanvasRenderTarget; + +},{"../../../settings":101}],80:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = canUseNewCanvasBlendModes; +/** + * Creates a little colored canvas + * + * @ignore + * @param {string} color - The color to make the canvas + * @return {canvas} a small canvas element + */ +function createColoredCanvas(color) { + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.fillStyle = color; + context.fillRect(0, 0, 6, 1); + + return canvas; +} + +/** + * Checks whether the Canvas BlendModes are supported by the current browser + * + * @return {boolean} whether they are supported + */ +function canUseNewCanvasBlendModes() { + if (typeof document === 'undefined') { + return false; + } + + var magenta = createColoredCanvas('#ff00ff'); + var yellow = createColoredCanvas('#ffff00'); + + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.globalCompositeOperation = 'multiply'; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + var imageData = context.getImageData(2, 0, 1, 1); + + if (!imageData) { + return false; + } + + var data = imageData.data; + + return data[0] === 255 && data[1] === 0 && data[2] === 0; +} + +},{}],81:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapCanvasBlendModesToPixi; + +var _const = require('../../../const'); + +var _canUseNewCanvasBlendModes = require('./canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Maps blend combinations to Canvas. + * + * @memberof PIXI + * @function mapCanvasBlendModesToPixi + * @private + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapCanvasBlendModesToPixi() { + var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + + if ((0, _canUseNewCanvasBlendModes2.default)()) { + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'multiply'; + array[_const.BLEND_MODES.SCREEN] = 'screen'; + array[_const.BLEND_MODES.OVERLAY] = 'overlay'; + array[_const.BLEND_MODES.DARKEN] = 'darken'; + array[_const.BLEND_MODES.LIGHTEN] = 'lighten'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'color-dodge'; + array[_const.BLEND_MODES.COLOR_BURN] = 'color-burn'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'hard-light'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'soft-light'; + array[_const.BLEND_MODES.DIFFERENCE] = 'difference'; + array[_const.BLEND_MODES.EXCLUSION] = 'exclusion'; + array[_const.BLEND_MODES.HUE] = 'hue'; + array[_const.BLEND_MODES.SATURATION] = 'saturate'; + array[_const.BLEND_MODES.COLOR] = 'color'; + array[_const.BLEND_MODES.LUMINOSITY] = 'luminosity'; + } else { + // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'source-over'; + array[_const.BLEND_MODES.SCREEN] = 'source-over'; + array[_const.BLEND_MODES.OVERLAY] = 'source-over'; + array[_const.BLEND_MODES.DARKEN] = 'source-over'; + array[_const.BLEND_MODES.LIGHTEN] = 'source-over'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'source-over'; + array[_const.BLEND_MODES.COLOR_BURN] = 'source-over'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.DIFFERENCE] = 'source-over'; + array[_const.BLEND_MODES.EXCLUSION] = 'source-over'; + array[_const.BLEND_MODES.HUE] = 'source-over'; + array[_const.BLEND_MODES.SATURATION] = 'source-over'; + array[_const.BLEND_MODES.COLOR] = 'source-over'; + array[_const.BLEND_MODES.LUMINOSITY] = 'source-over'; + } + // not-premultiplied, only for webgl + array[_const.BLEND_MODES.NORMAL_NPM] = array[_const.BLEND_MODES.NORMAL]; + array[_const.BLEND_MODES.ADD_NPM] = array[_const.BLEND_MODES.ADD]; + array[_const.BLEND_MODES.SCREEN_NPM] = array[_const.BLEND_MODES.SCREEN]; + + return array; +} + +},{"../../../const":46,"./canUseNewCanvasBlendModes":80}],82:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged + * up with textures that are no longer being used. + * + * @class + * @memberof PIXI + */ +var TextureGarbageCollector = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function TextureGarbageCollector(renderer) { + _classCallCheck(this, TextureGarbageCollector); + + this.renderer = renderer; + + this.count = 0; + this.checkCount = 0; + this.maxIdle = _settings2.default.GC_MAX_IDLE; + this.checkCountMax = _settings2.default.GC_MAX_CHECK_COUNT; + this.mode = _settings2.default.GC_MODE; + } + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.update = function update() { + this.count++; + + if (this.mode === _const.GC_MODES.MANUAL) { + return; + } + + this.checkCount++; + + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + + this.run(); + } + }; + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.run = function run() { + var tm = this.renderer.textureManager; + var managedTextures = tm._managedTextures; + var wasRemoved = false; + + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + + // only supports non generated textures at the moment! + if (!texture._glRenderTargets && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + + if (wasRemoved) { + var j = 0; + + for (var _i = 0; _i < managedTextures.length; _i++) { + if (managedTextures[_i] !== null) { + managedTextures[j++] = managedTextures[_i]; + } + } + + managedTextures.length = j; + } + }; + + /** + * Removes all the textures within the specified displayObject and its children from the GPU + * + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + */ + + + TextureGarbageCollector.prototype.unload = function unload(displayObject) { + var tm = this.renderer.textureManager; + + // only destroy non generated textures + if (displayObject._texture && displayObject._texture._glRenderTargets) { + tm.destroyTexture(displayObject._texture, true); + } + + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + + return TextureGarbageCollector; +}(); + +exports.default = TextureGarbageCollector; + +},{"../../const":46,"../../settings":101}],83:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _const = require('../../const'); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _utils = require('../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a webGL Texture + * + * @class + * @memberof PIXI + */ +var TextureManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function TextureManager(renderer) { + _classCallCheck(this, TextureManager); + + /** + * A reference to the current renderer + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = renderer.gl; + + /** + * Track textures in the renderer so we can no longer listen to them on destruction. + * + * @member {Array<*>} + * @private + */ + this._managedTextures = []; + } + + /** + * Binds a texture. + * + */ + + + TextureManager.prototype.bindTexture = function bindTexture() {} + // empty + + + /** + * Gets a texture. + * + */ + ; + + TextureManager.prototype.getTexture = function getTexture() {} + // empty + + + /** + * Updates and/or Creates a WebGL texture for the renderer's context. + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update + * @param {number} location - the location the texture will be bound to. + * @return {GLTexture} The gl texture. + */ + ; + + TextureManager.prototype.updateTexture = function updateTexture(texture, location) { + // assume it good! + // texture = texture.baseTexture || texture; + + var gl = this.gl; + + var isRenderTexture = !!texture._glRenderTargets; + + if (!texture.hasLoaded) { + return null; + } + + var boundTextures = this.renderer.boundTextures; + + // if the location is undefined then this may have been called by n event. + // this being the case the texture may already be bound to a slot. As a texture can only be bound once + // we need to find its current location if it exists. + if (location === undefined) { + location = 0; + + // TODO maybe we can use texture bound ids later on... + // check if texture is already bound.. + for (var i = 0; i < boundTextures.length; ++i) { + if (boundTextures[i] === texture) { + location = i; + break; + } + } + } + + boundTextures[location] = texture; + + gl.activeTexture(gl.TEXTURE0 + location); + + var glTexture = texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!glTexture) { + if (isRenderTexture) { + var renderTarget = new _RenderTarget2.default(this.gl, texture.width, texture.height, texture.scaleMode, texture.resolution); + + renderTarget.resize(texture.width, texture.height); + texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget; + glTexture = renderTarget.texture; + } else { + glTexture = new _pixiGlCore.GLTexture(this.gl, null, null, null, null); + glTexture.bind(location); + glTexture.premultiplyAlpha = true; + glTexture.upload(texture.source); + } + + texture._glTextures[this.renderer.CONTEXT_UID] = glTexture; + + texture.on('update', this.updateTexture, this); + texture.on('dispose', this.destroyTexture, this); + + this._managedTextures.push(texture); + + if (texture.isPowerOfTwo) { + if (texture.mipmap) { + glTexture.enableMipmap(); + } + + if (texture.wrapMode === _const.WRAP_MODES.CLAMP) { + glTexture.enableWrapClamp(); + } else if (texture.wrapMode === _const.WRAP_MODES.REPEAT) { + glTexture.enableWrapRepeat(); + } else { + glTexture.enableWrapMirrorRepeat(); + } + } else { + glTexture.enableWrapClamp(); + } + + if (texture.scaleMode === _const.SCALE_MODES.NEAREST) { + glTexture.enableNearestScaling(); + } else { + glTexture.enableLinearScaling(); + } + } + // the texture already exists so we only need to update it.. + else if (isRenderTexture) { + texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height); + } else { + glTexture.upload(texture.source); + } + + return glTexture; + }; + + /** + * Deletes the texture from WebGL + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy + * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. + */ + + + TextureManager.prototype.destroyTexture = function destroyTexture(texture, skipRemove) { + texture = texture.baseTexture || texture; + + if (!texture.hasLoaded) { + return; + } + + var uid = this.renderer.CONTEXT_UID; + var glTextures = texture._glTextures; + var glRenderTargets = texture._glRenderTargets; + + if (glTextures[uid]) { + this.renderer.unbindTexture(texture); + + glTextures[uid].destroy(); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + + delete glTextures[uid]; + + if (!skipRemove) { + var i = this._managedTextures.indexOf(texture); + + if (i !== -1) { + (0, _utils.removeItems)(this._managedTextures, i, 1); + } + } + } + + if (glRenderTargets && glRenderTargets[uid]) { + glRenderTargets[uid].destroy(); + delete glRenderTargets[uid]; + } + }; + + /** + * Deletes all the textures from WebGL + */ + + + TextureManager.prototype.removeAll = function removeAll() { + // empty all the old gl textures as they are useless now + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + delete texture._glTextures[this.renderer.CONTEXT_UID]; + } + } + }; + + /** + * Destroys this manager and removes all its textures + */ + + + TextureManager.prototype.destroy = function destroy() { + // destroy managed textures + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + this.destroyTexture(texture, true); + + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + } + + this._managedTextures = null; + }; + + return TextureManager; +}(); + +exports.default = TextureManager; + +},{"../../const":46,"../../utils":125,"./utils/RenderTarget":96,"pixi-gl-core":15}],84:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _MaskManager = require('./managers/MaskManager'); + +var _MaskManager2 = _interopRequireDefault(_MaskManager); + +var _StencilManager = require('./managers/StencilManager'); + +var _StencilManager2 = _interopRequireDefault(_StencilManager); + +var _FilterManager = require('./managers/FilterManager'); + +var _FilterManager2 = _interopRequireDefault(_FilterManager); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _ObjectRenderer = require('./utils/ObjectRenderer'); + +var _ObjectRenderer2 = _interopRequireDefault(_ObjectRenderer); + +var _TextureManager = require('./TextureManager'); + +var _TextureManager2 = _interopRequireDefault(_TextureManager); + +var _BaseTexture = require('../../textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _TextureGarbageCollector = require('./TextureGarbageCollector'); + +var _TextureGarbageCollector2 = _interopRequireDefault(_TextureGarbageCollector); + +var _WebGLState = require('./WebGLState'); + +var _WebGLState2 = _interopRequireDefault(_WebGLState); + +var _mapWebGLDrawModesToPixi = require('./utils/mapWebGLDrawModesToPixi'); + +var _mapWebGLDrawModesToPixi2 = _interopRequireDefault(_mapWebGLDrawModesToPixi); + +var _validateContext = require('./utils/validateContext'); + +var _validateContext2 = _interopRequireDefault(_validateContext); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CONTEXT_UID = 0; + +/** + * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ + +var WebGLRenderer = function (_SystemRenderer) { + _inherits(WebGLRenderer, _SystemRenderer); + + // eslint-disable-next-line valid-jsdoc + /** + * + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias. If not available natively then FXAA + * antialiasing is used + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. + * The resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear + * the canvas or not before the new render pass. If you wish to set this to false, you *must* set + * preserveDrawingBuffer to `true`. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when + * rendering, stopping pixel interpolation. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.legacy=false] - If true PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experiance unexplained flickering try setting this to true. + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card + */ + function WebGLRenderer(options, arg2, arg3) { + _classCallCheck(this, WebGLRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'WebGL', options, arg2, arg3)); + + _this.legacy = _this.options.legacy; + + if (_this.legacy) { + _pixiGlCore2.default.VertexArrayObject.FORCE_NATIVE = true; + } + + /** + * The type of this renderer as a standardised const + * + * @member {number} + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.WEBGL; + + _this.handleContextLost = _this.handleContextLost.bind(_this); + _this.handleContextRestored = _this.handleContextRestored.bind(_this); + + _this.view.addEventListener('webglcontextlost', _this.handleContextLost, false); + _this.view.addEventListener('webglcontextrestored', _this.handleContextRestored, false); + + /** + * The options passed in to create a new webgl context. + * + * @member {object} + * @private + */ + _this._contextOptions = { + alpha: _this.transparent, + antialias: _this.options.antialias, + premultipliedAlpha: _this.transparent && _this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: _this.options.preserveDrawingBuffer, + powerPreference: _this.options.powerPreference + }; + + _this._backgroundColorRgba[3] = _this.transparent ? 0 : 1; + + /** + * Manages the masks using the stencil buffer. + * + * @member {PIXI.MaskManager} + */ + _this.maskManager = new _MaskManager2.default(_this); + + /** + * Manages the stencil buffer. + * + * @member {PIXI.StencilManager} + */ + _this.stencilManager = new _StencilManager2.default(_this); + + /** + * An empty renderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.emptyRenderer = new _ObjectRenderer2.default(_this); + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.currentRenderer = _this.emptyRenderer; + + /** + * Manages textures + * @member {PIXI.TextureManager} + */ + _this.textureManager = null; + + /** + * Manages the filters. + * + * @member {PIXI.FilterManager} + */ + _this.filterManager = null; + + _this.initPlugins(); + + /** + * The current WebGL rendering context, it is created here + * + * @member {WebGLRenderingContext} + */ + // initialize the context so it is ready for the managers. + if (_this.options.context) { + // checks to see if a context is valid.. + (0, _validateContext2.default)(_this.options.context); + } + + _this.gl = _this.options.context || _pixiGlCore2.default.createContext(_this.view, _this._contextOptions); + + _this.CONTEXT_UID = CONTEXT_UID++; + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.WebGLState} + */ + _this.state = new _WebGLState2.default(_this.gl); + + _this.renderingToScreen = true; + + /** + * Holds the current state of textures bound to the GPU. + * @type {Array} + */ + _this.boundTextures = null; + + /** + * Holds the current shader + * + * @member {PIXI.Shader} + */ + _this._activeShader = null; + + _this._activeVao = null; + + /** + * Holds the current render target + * + * @member {PIXI.RenderTarget} + */ + _this._activeRenderTarget = null; + + _this._initContext(); + + // map some webGL blend and drawmodes.. + _this.drawModes = (0, _mapWebGLDrawModesToPixi2.default)(_this.gl); + + _this._nextTextureLocation = 0; + + _this.setBlendMode(0); + + /** + * Fired after rendering finishes. + * + * @event PIXI.WebGLRenderer#postrender + */ + + /** + * Fired before rendering starts. + * + * @event PIXI.WebGLRenderer#prerender + */ + + /** + * Fired when the WebGL context is set. + * + * @event PIXI.WebGLRenderer#context + * @param {WebGLRenderingContext} gl - WebGL context. + */ + return _this; + } + + /** + * Creates the WebGL context + * + * @private + */ + + + WebGLRenderer.prototype._initContext = function _initContext() { + var gl = this.gl; + + // restore a context if it was previously lost + if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').restoreContext(); + } + + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + + this._activeShader = null; + this._activeVao = null; + + this.boundTextures = new Array(maxTextures); + this.emptyTextures = new Array(maxTextures); + + // create a texture manager... + this.textureManager = new _TextureManager2.default(this); + this.filterManager = new _FilterManager2.default(this); + this.textureGC = new _TextureGarbageCollector2.default(this); + + this.state.resetToDefault(); + + this.rootRenderTarget = new _RenderTarget2.default(gl, this.width, this.height, null, this.resolution, true); + this.rootRenderTarget.clearColor = this._backgroundColorRgba; + + this.bindRenderTarget(this.rootRenderTarget); + + // now lets fill up the textures with empty ones! + var emptyGLTexture = new _pixiGlCore2.default.GLTexture.fromData(gl, null, 1, 1); + + var tempObj = { _glTextures: {} }; + + tempObj._glTextures[this.CONTEXT_UID] = {}; + + for (var i = 0; i < maxTextures; i++) { + var empty = new _BaseTexture2.default(); + + empty._glTextures[this.CONTEXT_UID] = emptyGLTexture; + + this.boundTextures[i] = tempObj; + this.emptyTextures[i] = empty; + this.bindTexture(null, i); + } + + this.emit('context', gl); + + // setup the width/height properties and gl viewport + this.resize(this.screen.width, this.screen.height); + }; + + /** + * Renders the object to its webGL view + * + * @param {PIXI.DisplayObject} displayObject - the object to be rendered + * @param {PIXI.RenderTexture} renderTexture - The render texture to render to. + * @param {boolean} [clear] - Should the canvas be cleared before the new render + * @param {PIXI.Transform} [transform] - A transform to apply to the render texture before rendering. + * @param {boolean} [skipUpdateTransform] - Should we skip the update transform pass? + */ + + + WebGLRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + // no point rendering if our context has been blown up! + if (!this.gl || this.gl.isContextLost()) { + return; + } + + this._nextTextureLocation = 0; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + this.bindRenderTexture(renderTexture, transform); + + this.currentRenderer.start(); + + if (clear !== undefined ? clear : this.clearBeforeRender) { + this._activeRenderTarget.clear(); + } + + displayObject.renderWebGL(this); + + // apply transform.. + this.currentRenderer.flush(); + + // this.setObjectRenderer(this.emptyRenderer); + + this.textureGC.update(); + + this.emit('postrender'); + }; + + /** + * Changes the current renderer to the one given in parameter + * + * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. + */ + + + WebGLRenderer.prototype.setObjectRenderer = function setObjectRenderer(objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; + + /** + * This should be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + * + */ + + + WebGLRenderer.prototype.flush = function flush() { + this.setObjectRenderer(this.emptyRenderer); + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + WebGLRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + // if(width * this.resolution === this.width && height * this.resolution === this.height)return; + + _SystemRenderer3.default.prototype.resize.call(this, screenWidth, screenHeight); + + this.rootRenderTarget.resize(screenWidth, screenHeight); + + if (this._activeRenderTarget === this.rootRenderTarget) { + this.rootRenderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true); + } + } + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} blendMode - the desired blend mode + */ + + + WebGLRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + this.state.setBlendMode(blendMode); + }; + + /** + * Erases the active render target and fills the drawing area with a colour + * + * @param {number} [clearColor] - The colour + */ + + + WebGLRenderer.prototype.clear = function clear(clearColor) { + this._activeRenderTarget.clear(clearColor); + }; + + /** + * Sets the transform of the active render target to the given matrix + * + * @param {PIXI.Matrix} matrix - The transformation matrix + */ + + + WebGLRenderer.prototype.setTransform = function setTransform(matrix) { + this._activeRenderTarget.transform = matrix; + }; + + /** + * Erases the render texture and fills the drawing area with a colour + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to clear + * @param {number} [clearColor] - The colour + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.clearRenderTexture = function clearRenderTexture(renderTexture, clearColor) { + var baseTexture = renderTexture.baseTexture; + var renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + + if (renderTarget) { + renderTarget.clear(clearColor); + } + + return this; + }; + + /** + * Binds a render texture for rendering + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to render + * @param {PIXI.Transform} transform - The transform to be applied to the render texture + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTexture = function bindRenderTexture(renderTexture, transform) { + var renderTarget = void 0; + + if (renderTexture) { + var baseTexture = renderTexture.baseTexture; + + if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) { + // bind the current texture + this.textureManager.updateTexture(baseTexture, 0); + } + + this.unbindTexture(baseTexture); + + renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + renderTarget.setFrame(renderTexture.frame); + } else { + renderTarget = this.rootRenderTarget; + } + + renderTarget.transform = transform; + this.bindRenderTarget(renderTarget); + + return this; + }; + + /** + * Changes the current render target to the one given in parameter + * + * @param {PIXI.RenderTarget} renderTarget - the new render target + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTarget = function bindRenderTarget(renderTarget) { + if (renderTarget !== this._activeRenderTarget) { + this._activeRenderTarget = renderTarget; + renderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true); + } + + this.stencilManager.setMaskStack(renderTarget.stencilMaskStack); + } + + return this; + }; + + /** + * Changes the current shader to the one given in parameter + * + * @param {PIXI.Shader} shader - the new shader + * @param {boolean} [autoProject=true] - Whether automatically set the projection matrix + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindShader = function bindShader(shader, autoProject) { + // TODO cache + if (this._activeShader !== shader) { + this._activeShader = shader; + shader.bind(); + + // `autoProject` normally would be a default parameter set to true + // but because of how Babel transpiles default parameters + // it hinders the performance of this method. + if (autoProject !== false) { + // automatically set the projection matrix + shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(true); + } + } + + return this; + }; + + /** + * Binds the texture. This will return the location of the bound texture. + * It may not be the same as the one you pass in. This is due to optimisation that prevents + * needless binding of textures. For example if the texture is already bound it will return the + * current location of the texture instead of the one provided. To bypass this use force location + * + * @param {PIXI.Texture} texture - the new texture + * @param {number} location - the suggested texture location + * @param {boolean} forceLocation - force the location + * @return {number} bound texture location + */ + + + WebGLRenderer.prototype.bindTexture = function bindTexture(texture, location, forceLocation) { + texture = texture || this.emptyTextures[location]; + texture = texture.baseTexture || texture; + texture.touched = this.textureGC.count; + + if (!forceLocation) { + // TODO - maybe look into adding boundIds.. save us the loop? + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + return i; + } + } + + if (location === undefined) { + this._nextTextureLocation++; + this._nextTextureLocation %= this.boundTextures.length; + location = this.boundTextures.length - this._nextTextureLocation - 1; + } + } else { + location = location || 0; + } + + var gl = this.gl; + var glTexture = texture._glTextures[this.CONTEXT_UID]; + + if (!glTexture) { + // this will also bind the texture.. + this.textureManager.updateTexture(texture, location); + } else { + // bind the current texture + this.boundTextures[location] = texture; + gl.activeTexture(gl.TEXTURE0 + location); + gl.bindTexture(gl.TEXTURE_2D, glTexture.texture); + } + + return location; + }; + + /** + * unbinds the texture ... + * + * @param {PIXI.Texture} texture - the texture to unbind + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.unbindTexture = function unbindTexture(texture) { + var gl = this.gl; + + texture = texture.baseTexture || texture; + + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + this.boundTextures[i] = this.emptyTextures[i]; + + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[i]._glTextures[this.CONTEXT_UID].texture); + } + } + + return this; + }; + + /** + * Creates a new VAO from this renderer's context and state. + * + * @return {VertexArrayObject} The new VAO. + */ + + + WebGLRenderer.prototype.createVao = function createVao() { + return new _pixiGlCore2.default.VertexArrayObject(this.gl, this.state.attribState); + }; + + /** + * Changes the current Vao to the one given in parameter + * + * @param {PIXI.VertexArrayObject} vao - the new Vao + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindVao = function bindVao(vao) { + if (this._activeVao === vao) { + return this; + } + + if (vao) { + vao.bind(); + } else if (this._activeVao) { + // TODO this should always be true i think? + this._activeVao.unbind(); + } + + this._activeVao = vao; + + return this; + }; + + /** + * Resets the WebGL state so you can render things however you fancy! + * + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.reset = function reset() { + this.setObjectRenderer(this.emptyRenderer); + + this.bindVao(null); + this._activeShader = null; + this._activeRenderTarget = this.rootRenderTarget; + + for (var i = 0; i < this.boundTextures.length; i++) { + this.boundTextures[i] = this.emptyTextures[i]; + } + + // bind the main frame buffer (the screen); + this.rootRenderTarget.activate(); + + this.state.resetToDefault(); + + return this; + }; + + /** + * Handles a lost webgl context + * + * @private + * @param {WebGLContextEvent} event - The context lost event. + */ + + + WebGLRenderer.prototype.handleContextLost = function handleContextLost(event) { + event.preventDefault(); + }; + + /** + * Handles a restored webgl context + * + * @private + */ + + + WebGLRenderer.prototype.handleContextRestored = function handleContextRestored() { + this.textureManager.removeAll(); + this.filterManager.destroy(true); + this._initContext(); + }; + + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + + + WebGLRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // remove listeners + this.view.removeEventListener('webglcontextlost', this.handleContextLost); + this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); + + this.textureManager.destroy(); + + // call base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.uid = 0; + + // destroy the managers + this.maskManager.destroy(); + this.stencilManager.destroy(); + this.filterManager.destroy(); + + this.maskManager = null; + this.filterManager = null; + this.textureManager = null; + this.currentRenderer = null; + + this.handleContextLost = null; + this.handleContextRestored = null; + + this._contextOptions = null; + this.gl.useProgram(null); + + if (this.gl.getExtension('WEBGL_lose_context')) { + this.gl.getExtension('WEBGL_lose_context').loseContext(); + } + + this.gl = null; + + // this = null; + }; + + return WebGLRenderer; +}(_SystemRenderer3.default); + +/** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @name PIXI.WebGLRenderer#plugins + * @type {object} + * @readonly + * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.extract.WebGLExtract} extract Extract image data from renderer. + * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.prepare.WebGLPrepare} prepare Pre-render display objects. + */ + +/** + * Adds a plugin to the renderer. + * + * @method PIXI.WebGLRenderer#registerPlugin + * @param {string} pluginName - The name of the plugin. + * @param {Function} ctor - The constructor function or class for the plugin. + */ + +exports.default = WebGLRenderer; +_utils.pluginTarget.mixin(WebGLRenderer); + +},{"../../const":46,"../../textures/BaseTexture":112,"../../utils":125,"../SystemRenderer":76,"./TextureGarbageCollector":82,"./TextureManager":83,"./WebGLState":85,"./managers/FilterManager":90,"./managers/MaskManager":91,"./managers/StencilManager":92,"./utils/ObjectRenderer":94,"./utils/RenderTarget":96,"./utils/mapWebGLDrawModesToPixi":99,"./utils/validateContext":100,"pixi-gl-core":15}],85:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); + +var _mapWebGLBlendModesToPixi2 = _interopRequireDefault(_mapWebGLBlendModesToPixi); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var BLEND = 0; +var DEPTH_TEST = 1; +var FRONT_FACE = 2; +var CULL_FACE = 3; +var BLEND_FUNC = 4; + +/** + * A WebGL state machines + * + * @memberof PIXI + * @class + */ + +var WebGLState = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + */ + function WebGLState(gl) { + _classCallCheck(this, WebGLState); + + /** + * The current active state + * + * @member {Uint8Array} + */ + this.activeState = new Uint8Array(16); + + /** + * The default state + * + * @member {Uint8Array} + */ + this.defaultState = new Uint8Array(16); + + // default blend mode.. + this.defaultState[0] = 1; + + /** + * The current state index in the stack + * + * @member {number} + * @private + */ + this.stackIndex = 0; + + /** + * The stack holding all the different states + * + * @member {Array<*>} + * @private + */ + this.stack = []; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + this.attribState = { + tempAttribState: new Array(this.maxAttribs), + attribState: new Array(this.maxAttribs) + }; + + this.blendModes = (0, _mapWebGLBlendModesToPixi2.default)(gl); + + // check we have vao.. + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || gl.getExtension('MOZ_OES_vertex_array_object') || gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + /** + * Pushes a new active state + */ + + + WebGLState.prototype.push = function push() { + // next state.. + var state = this.stack[this.stackIndex]; + + if (!state) { + state = this.stack[this.stackIndex] = new Uint8Array(16); + } + + ++this.stackIndex; + + // copy state.. + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) { + state[i] = this.activeState[i]; + } + }; + + /** + * Pops a state out + */ + + + WebGLState.prototype.pop = function pop() { + var state = this.stack[--this.stackIndex]; + + this.setState(state); + }; + + /** + * Sets the current state + * + * @param {*} state - The state to set. + */ + + + WebGLState.prototype.setState = function setState(state) { + this.setBlend(state[BLEND]); + this.setDepthTest(state[DEPTH_TEST]); + this.setFrontFace(state[FRONT_FACE]); + this.setCullFace(state[CULL_FACE]); + this.setBlendMode(state[BLEND_FUNC]); + }; + + /** + * Enables or disabled blending. + * + * @param {boolean} value - Turn on or off webgl blending. + */ + + + WebGLState.prototype.setBlend = function setBlend(value) { + value = value ? 1 : 0; + + if (this.activeState[BLEND] === value) { + return; + } + + this.activeState[BLEND] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + }; + + /** + * Sets the blend mode. + * + * @param {number} value - The blend mode to set to. + */ + + + WebGLState.prototype.setBlendMode = function setBlendMode(value) { + if (value === this.activeState[BLEND_FUNC]) { + return; + } + + this.activeState[BLEND_FUNC] = value; + + var mode = this.blendModes[value]; + + if (mode.length === 2) { + this.gl.blendFunc(mode[0], mode[1]); + } else { + this.gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); + } + }; + + /** + * Sets whether to enable or disable depth test. + * + * @param {boolean} value - Turn on or off webgl depth testing. + */ + + + WebGLState.prototype.setDepthTest = function setDepthTest(value) { + value = value ? 1 : 0; + + if (this.activeState[DEPTH_TEST] === value) { + return; + } + + this.activeState[DEPTH_TEST] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + }; + + /** + * Sets whether to enable or disable cull face. + * + * @param {boolean} value - Turn on or off webgl cull face. + */ + + + WebGLState.prototype.setCullFace = function setCullFace(value) { + value = value ? 1 : 0; + + if (this.activeState[CULL_FACE] === value) { + return; + } + + this.activeState[CULL_FACE] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + }; + + /** + * Sets the gl front face. + * + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ + + + WebGLState.prototype.setFrontFace = function setFrontFace(value) { + value = value ? 1 : 0; + + if (this.activeState[FRONT_FACE] === value) { + return; + } + + this.activeState[FRONT_FACE] = value; + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); + }; + + /** + * Disables all the vaos in use + * + */ + + + WebGLState.prototype.resetAttributes = function resetAttributes() { + for (var i = 0; i < this.attribState.tempAttribState.length; i++) { + this.attribState.tempAttribState[i] = 0; + } + + for (var _i = 0; _i < this.attribState.attribState.length; _i++) { + this.attribState.attribState[_i] = 0; + } + + // im going to assume one is always active for performance reasons. + for (var _i2 = 1; _i2 < this.maxAttribs; _i2++) { + this.gl.disableVertexAttribArray(_i2); + } + }; + + // used + /** + * Resets all the logic and disables the vaos + */ + + + WebGLState.prototype.resetToDefault = function resetToDefault() { + // unbind any VAO if they exist.. + if (this.nativeVaoExtension) { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + // reset all attributes.. + this.resetAttributes(); + + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; ++i) { + this.activeState[i] = 32; + } + + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + + this.setState(this.defaultState); + }; + + return WebGLState; +}(); + +exports.default = WebGLState; + +},{"./utils/mapWebGLBlendModesToPixi":98}],86:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _extractUniformsFromSrc = require('./extractUniformsFromSrc'); + +var _extractUniformsFromSrc2 = _interopRequireDefault(_extractUniformsFromSrc); + +var _utils = require('../../../utils'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SOURCE_KEY_MAP = {}; + +// let math = require('../../../math'); +/** + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ + +var Filter = function () { + /** + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. + */ + function Filter(vertexSrc, fragmentSrc, uniforms) { + _classCallCheck(this, Filter); + + /** + * The vertex shader. + * + * @member {string} + */ + this.vertexSrc = vertexSrc || Filter.defaultVertexSrc; + + /** + * The fragment shader. + * + * @member {string} + */ + this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc; + + this._blendMode = _const.BLEND_MODES.NORMAL; + + this.uniformData = uniforms || (0, _extractUniformsFromSrc2.default)(this.vertexSrc, this.fragmentSrc, 'projectionMatrix|uSampler'); + + /** + * An object containing the current values of custom uniforms. + * @example Updating the value of a custom uniform + * filter.uniforms.time = performance.now(); + * + * @member {object} + */ + this.uniforms = {}; + + for (var i in this.uniformData) { + this.uniforms[i] = this.uniformData[i].value; + if (this.uniformData[i].type) { + this.uniformData[i].type = this.uniformData[i].type.toLowerCase(); + } + } + + // this is where we store shader references.. + // TODO we could cache this! + this.glShaders = {}; + + // used for cacheing.. sure there is a better way! + if (!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) { + SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = (0, _utils.uid)(); + } + + this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]; + + /** + * The padding of the filter. Some filters require extra space to breath such as a blur. + * Increasing this will add extra width and height to the bounds of the object that the + * filter is applied to. + * + * @member {number} + */ + this.padding = 4; + + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + * + * @member {number} + */ + this.resolution = _settings2.default.FILTER_RESOLUTION; + + /** + * If enabled is true the filter is applied, if false it will not. + * + * @member {boolean} + */ + this.enabled = true; + + /** + * If enabled, PixiJS will fit the filter area into boundaries for better performance. + * Switch it off if it does not work for specific shader. + * + * @member {boolean} + */ + this.autoFit = true; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + * @param {object} [currentState] - It's current state of filter. + * There are some useful properties in the currentState : + * target, filters, sourceFrame, destinationFrame, renderTarget, resolution + */ + + + Filter.prototype.apply = function apply(filterManager, input, output, clear, currentState) // eslint-disable-line no-unused-vars + { + // --- // + // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); + + // do as you please! + + filterManager.applyFilter(this, input, output, clear); + + // or just do a regular render.. + }; + + /** + * Sets the blendmode of the filter + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + */ + + + _createClass(Filter, [{ + key: 'blendMode', + get: function get() { + return this._blendMode; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._blendMode = value; + } + + /** + * The default vertex shader source + * + * @static + * @constant + */ + + }], [{ + key: 'defaultVertexSrc', + get: function get() { + return ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform mat3 projectionMatrix;', 'uniform mat3 filterMatrix;', 'varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;', ' vTextureCoord = aTextureCoord ;', '}'].join('\n'); + } + + /** + * The default fragment shader source + * + * @static + * @constant + */ + + }, { + key: 'defaultFragmentSrc', + get: function get() { + return ['varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'uniform sampler2D uSampler;', 'uniform sampler2D filterSampler;', 'void main(void){', ' vec4 masky = texture2D(filterSampler, vFilterCoord);', ' vec4 sample = texture2D(uSampler, vTextureCoord);', ' vec4 color;', ' if(mod(vFilterCoord.x, 1.0) > 0.5)', ' {', ' color = vec4(1.0, 0.0, 0.0, 1.0);', ' }', ' else', ' {', ' color = vec4(0.0, 1.0, 0.0, 1.0);', ' }', + // ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', + ' gl_FragColor = mix(sample, masky, 0.5);', ' gl_FragColor *= sample.a;', '}'].join('\n'); + } + }]); + + return Filter; +}(); + +exports.default = Filter; + +},{"../../../const":46,"../../../settings":101,"../../../utils":125,"./extractUniformsFromSrc":87}],87:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = extractUniformsFromSrc; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var defaultValue = _pixiGlCore2.default.shader.defaultValue; + +function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) { + var vertUniforms = extractUniformsFromString(vertexSrc, mask); + var fragUniforms = extractUniformsFromString(fragmentSrc, mask); + + return Object.assign(vertUniforms, fragUniforms); +} + +function extractUniformsFromString(string) { + var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea|filterClamp)$'); + + var uniforms = {}; + var nameSplit = void 0; + + // clean the lines a little - remove extra spaces / tabs etc + // then split along ';' + var lines = string.replace(/\s+/g, ' ').split(/\s*;\s*/); + + // loop through.. + for (var i = 0; i < lines.length; i++) { + var line = lines[i].trim(); + + if (line.indexOf('uniform') > -1) { + var splitLine = line.split(' '); + var type = splitLine[1]; + + var name = splitLine[2]; + var size = 1; + + if (name.indexOf('[') > -1) { + // array! + nameSplit = name.split(/\[|]/); + name = nameSplit[0]; + size *= Number(nameSplit[1]); + } + + if (!name.match(maskRegex)) { + uniforms[name] = { + value: defaultValue(type, size), + name: name, + type: type + }; + } + } + } + + return uniforms; +} + +},{"pixi-gl-core":15}],88:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.calculateScreenSpaceMatrix = calculateScreenSpaceMatrix; +exports.calculateNormalizedScreenSpaceMatrix = calculateNormalizedScreenSpaceMatrix; +exports.calculateSpriteMatrix = calculateSpriteMatrix; + +var _math = require('../../../math'); + +/** + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + * @private + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// this returns a matrix that will normalise map filter cords in the filter to screen space +function calculateScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + // let worldTransform = sprite.worldTransform.copy(Matrix.TEMP_MATRIX), + // let texture = {width:1136, height:700};//sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(textureSize.width, textureSize.height); + + return mappedMatrix; +} + +function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + var translateScaleX = textureSize.width / filterArea.width; + var translateScaleY = textureSize.height / filterArea.height; + + mappedMatrix.scale(translateScaleX, translateScaleY); + + return mappedMatrix; +} + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +function calculateSpriteMatrix(outputMatrix, filterArea, textureSize, sprite) { + var orig = sprite._texture.orig; + var mappedMatrix = outputMatrix.set(textureSize.width, 0, 0, textureSize.height, filterArea.x, filterArea.y); + var worldTransform = sprite.worldTransform.copy(_math.Matrix.TEMP_MATRIX); + + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height); + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; +} + +},{"../../../math":70}],89:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Filter2 = require('../Filter'); + +var _Filter3 = _interopRequireDefault(_Filter2); + +var _math = require('../../../../math'); + +var _path = require('path'); + +var _TextureMatrix = require('../../../../textures/TextureMatrix'); + +var _TextureMatrix2 = _interopRequireDefault(_TextureMatrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The SpriteMaskFilter class + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + */ +var SpriteMaskFilter = function (_Filter) { + _inherits(SpriteMaskFilter, _Filter); + + /** + * @param {PIXI.Sprite} sprite - the target sprite + */ + function SpriteMaskFilter(sprite) { + _classCallCheck(this, SpriteMaskFilter); + + var maskMatrix = new _math.Matrix(); + + var _this = _possibleConstructorReturn(this, _Filter.call(this, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n', 'varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n')); + + sprite.renderable = false; + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + return _this; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + */ + + + SpriteMaskFilter.prototype.apply = function apply(filterManager, input, output) { + var maskSprite = this.maskSprite; + var tex = this.maskSprite.texture; + + if (!tex.valid) { + return; + } + if (!tex.transform) { + // margin = 0.0, let it bleed a bit, shader code becomes easier + // assuming that atlas textures were made with 1-pixel padding + tex.transform = new _TextureMatrix2.default(tex, 0.0); + } + tex.transform.update(); + + this.uniforms.mask = tex; + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite).prepend(tex.transform.mapCoord); + this.uniforms.alpha = maskSprite.worldAlpha; + this.uniforms.maskClamp = tex.transform.uClampFrame; + + filterManager.applyFilter(this, input, output); + }; + + return SpriteMaskFilter; +}(_Filter3.default); + +exports.default = SpriteMaskFilter; + +},{"../../../../math":70,"../../../../textures/TextureMatrix":116,"../Filter":86,"path":8}],90:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _RenderTarget = require('../utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _Quad = require('../utils/Quad'); + +var _Quad2 = _interopRequireDefault(_Quad); + +var _math = require('../../../math'); + +var _Shader = require('../../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _filterTransforms = require('../filters/filterTransforms'); + +var filterTransforms = _interopRequireWildcard(_filterTransforms); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @ignore + * @class + */ +var FilterState = function () { + /** + * + */ + function FilterState() { + _classCallCheck(this, FilterState); + + this.renderTarget = null; + this.target = null; + this.resolution = 1; + + // those three objects are used only for root + // re-assigned for everything else + this.sourceFrame = new _math.Rectangle(); + this.destinationFrame = new _math.Rectangle(); + this.filters = []; + } + + /** + * clears the state + */ + + + FilterState.prototype.clear = function clear() { + this.filters = null; + this.target = null; + this.renderTarget = null; + }; + + return FilterState; +}(); + +var screenKey = 'screen'; + +/** + * @class + * @memberof PIXI + * @extends PIXI.WebGLManager + */ + +var FilterManager = function (_WebGLManager) { + _inherits(FilterManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function FilterManager(renderer) { + _classCallCheck(this, FilterManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.gl = _this.renderer.gl; + // know about sprites! + _this.quad = new _Quad2.default(_this.gl, renderer.state.attribState); + + _this.shaderCache = {}; + // todo add default! + _this.pool = {}; + + _this.filterData = null; + + _this.managedFilters = []; + + _this.renderer.on('prerender', _this.onPrerender, _this); + + _this._screenWidth = renderer.view.width; + _this._screenHeight = renderer.view.height; + return _this; + } + + /** + * Adds a new filter to the manager. + * + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param {PIXI.Filter[]} filters - The filters to apply. + */ + + + FilterManager.prototype.pushFilter = function pushFilter(target, filters) { + var renderer = this.renderer; + + var filterData = this.filterData; + + if (!filterData) { + filterData = this.renderer._activeRenderTarget.filterStack; + + // add new stack + var filterState = new FilterState(); + + filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; + filterState.renderTarget = renderer._activeRenderTarget; + + this.renderer._activeRenderTarget.filterData = filterData = { + index: 0, + stack: [filterState] + }; + + this.filterData = filterData; + } + + // get the current filter state.. + var currentState = filterData.stack[++filterData.index]; + var renderTargetFrame = filterData.stack[0].destinationFrame; + + if (!currentState) { + currentState = filterData.stack[filterData.index] = new FilterState(); + } + + var fullScreen = target.filterArea && target.filterArea.x === 0 && target.filterArea.y === 0 && target.filterArea.width === renderer.screen.width && target.filterArea.height === renderer.screen.height; + + // for now we go off the filter of the first resolution.. + var resolution = filters[0].resolution; + var padding = filters[0].padding | 0; + var targetBounds = fullScreen ? renderer.screen : target.filterArea || target.getBounds(true); + var sourceFrame = currentState.sourceFrame; + var destinationFrame = currentState.destinationFrame; + + sourceFrame.x = (targetBounds.x * resolution | 0) / resolution; + sourceFrame.y = (targetBounds.y * resolution | 0) / resolution; + sourceFrame.width = (targetBounds.width * resolution | 0) / resolution; + sourceFrame.height = (targetBounds.height * resolution | 0) / resolution; + + if (!fullScreen) { + if (filterData.stack[0].renderTarget.transform) {// + + // TODO we should fit the rect around the transform.. + } else if (filters[0].autoFit) { + sourceFrame.fit(renderTargetFrame); + } + + // lets apply the padding After we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + sourceFrame.pad(padding); + } + + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + + // lets play the padding after we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + + var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); + + currentState.target = target; + currentState.filters = filters; + currentState.resolution = resolution; + currentState.renderTarget = renderTarget; + + // bind the render target to draw the shape in the top corner.. + + renderTarget.setFrame(destinationFrame, sourceFrame); + + // bind the render target + renderer.bindRenderTarget(renderTarget); + renderTarget.clear(); + }; + + /** + * Pops off the filter and applies it. + * + */ + + + FilterManager.prototype.popFilter = function popFilter() { + var filterData = this.filterData; + + var lastState = filterData.stack[filterData.index - 1]; + var currentState = filterData.stack[filterData.index]; + + this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); + + var filters = currentState.filters; + + if (filters.length === 1) { + filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false, currentState); + this.freePotRenderTarget(currentState.renderTarget); + } else { + var flip = currentState.renderTarget; + var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, currentState.resolution); + + flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + // finally lets clear the render target before drawing to it.. + flop.clear(); + + var i = 0; + + for (i = 0; i < filters.length - 1; ++i) { + filters[i].apply(this, flip, flop, true, currentState); + + var t = flip; + + flip = flop; + flop = t; + } + + filters[i].apply(this, flip, lastState.renderTarget, false, currentState); + + this.freePotRenderTarget(flip); + this.freePotRenderTarget(flop); + } + + currentState.clear(); + filterData.index--; + + if (filterData.index === 0) { + this.filterData = null; + } + }; + + /** + * Draws a filter. + * + * @param {PIXI.Filter} filter - The filter to draw. + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + FilterManager.prototype.applyFilter = function applyFilter(filter, input, output, clear) { + var renderer = this.renderer; + var gl = renderer.gl; + + var shader = filter.glShaders[renderer.CONTEXT_UID]; + + // cacheing.. + if (!shader) { + if (filter.glShaderKey) { + shader = this.shaderCache[filter.glShaderKey]; + + if (!shader) { + shader = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + + filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = shader; + this.managedFilters.push(filter); + } + } else { + shader = filter.glShaders[renderer.CONTEXT_UID] = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + this.managedFilters.push(filter); + } + + // TODO - this only needs to be done once? + renderer.bindVao(null); + + this.quad.initVao(shader); + } + + renderer.bindVao(this.quad.vao); + + renderer.bindRenderTarget(output); + + if (clear) { + gl.disable(gl.SCISSOR_TEST); + renderer.clear(); // [1, 1, 1, 1]); + gl.enable(gl.SCISSOR_TEST); + } + + // in case the render target is being masked using a scissor rect + if (output === renderer.maskManager.scissorRenderTarget) { + renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); + } + + renderer.bindShader(shader); + + // free unit 0 for us, doesn't matter what was there + // don't try to restore it, because syncUniforms can upload it to another slot + // and it'll be a problem + var tex = this.renderer.emptyTextures[0]; + + this.renderer.boundTextures[0] = tex; + // this syncs the PixiJS filters uniforms with glsl uniforms + this.syncUniforms(shader, filter); + + renderer.state.setBlendMode(filter.blendMode); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, input.texture.texture); + + this.quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + }; + + /** + * Uploads the uniforms of the filter. + * + * @param {GLShader} shader - The underlying gl shader. + * @param {PIXI.Filter} filter - The filter we are synchronizing. + */ + + + FilterManager.prototype.syncUniforms = function syncUniforms(shader, filter) { + var uniformData = filter.uniformData; + var uniforms = filter.uniforms; + + // 0 is reserved for the PixiJS texture so we start at 1! + var textureCount = 1; + var currentState = void 0; + + // filterArea and filterClamp that are handled by FilterManager directly + // they must not appear in uniformData + + if (shader.uniforms.filterArea) { + currentState = this.filterData.stack[this.filterData.index]; + + var filterArea = shader.uniforms.filterArea; + + filterArea[0] = currentState.renderTarget.size.width; + filterArea[1] = currentState.renderTarget.size.height; + filterArea[2] = currentState.sourceFrame.x; + filterArea[3] = currentState.sourceFrame.y; + + shader.uniforms.filterArea = filterArea; + } + + // use this to clamp displaced texture coords so they belong to filterArea + // see displacementFilter fragment shader for an example + if (shader.uniforms.filterClamp) { + currentState = currentState || this.filterData.stack[this.filterData.index]; + + var filterClamp = shader.uniforms.filterClamp; + + filterClamp[0] = 0; + filterClamp[1] = 0; + filterClamp[2] = (currentState.sourceFrame.width - 1) / currentState.renderTarget.size.width; + filterClamp[3] = (currentState.sourceFrame.height - 1) / currentState.renderTarget.size.height; + + shader.uniforms.filterClamp = filterClamp; + } + + // TODO Cacheing layer.. + for (var i in uniformData) { + var type = uniformData[i].type; + + if (type === 'sampler2d' && uniforms[i] !== 0) { + if (uniforms[i].baseTexture) { + shader.uniforms[i] = this.renderer.bindTexture(uniforms[i].baseTexture, textureCount); + } else { + shader.uniforms[i] = textureCount; + + // TODO + // this is helpful as renderTargets can also be set. + // Although thinking about it, we could probably + // make the filter texture cache return a RenderTexture + // rather than a renderTarget + var gl = this.renderer.gl; + + this.renderer.boundTextures[textureCount] = this.renderer.emptyTextures[textureCount]; + gl.activeTexture(gl.TEXTURE0 + textureCount); + + uniforms[i].texture.bind(); + } + + textureCount++; + } else if (type === 'mat3') { + // check if its PixiJS matrix.. + if (uniforms[i].a !== undefined) { + shader.uniforms[i] = uniforms[i].toArray(true); + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (type === 'vec2') { + // check if its a point.. + if (uniforms[i].x !== undefined) { + var val = shader.uniforms[i] || new Float32Array(2); + + val[0] = uniforms[i].x; + val[1] = uniforms[i].y; + shader.uniforms[i] = val; + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (type === 'float') { + if (shader.uniforms.data[i].value !== uniformData[i]) { + shader.uniforms[i] = uniforms[i]; + } + } else { + shader.uniforms[i] = uniforms[i]; + } + } + }; + + /** + * Gets a render target from the pool, or creates a new one. + * + * @param {boolean} clear - Should we clear the render texture when we get it? + * @param {number} resolution - The resolution of the target. + * @return {PIXI.RenderTarget} The new render target + */ + + + FilterManager.prototype.getRenderTarget = function getRenderTarget(clear, resolution) { + var currentState = this.filterData.stack[this.filterData.index]; + var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution); + + renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + return renderTarget; + }; + + /** + * Returns a render target to the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The render target to return. + */ + + + FilterManager.prototype.returnRenderTarget = function returnRenderTarget(renderTarget) { + this.freePotRenderTarget(renderTarget); + }; + + /** + * Calculates the mapped matrix. + * + * TODO playing around here.. this is temporary - (will end up in the shader) + * this returns a matrix that will normalise map filter cords in the filter to screen space + * + * @param {PIXI.Matrix} outputMatrix - the matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateScreenSpaceMatrix = function calculateScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); + }; + + /** + * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function calculateNormalizedScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); + }; + + /** + * This will map the filter coord so that a texture can be used based on the transform of a sprite + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateSpriteMatrix = function calculateSpriteMatrix(outputMatrix, sprite) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); + }; + + /** + * Destroys this Filter Manager. + * + * @param {boolean} [contextLost=false] context was lost, do not free shaders + * + */ + + + FilterManager.prototype.destroy = function destroy() { + var contextLost = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + var renderer = this.renderer; + var filters = this.managedFilters; + + renderer.off('prerender', this.onPrerender, this); + + for (var i = 0; i < filters.length; i++) { + if (!contextLost) { + filters[i].glShaders[renderer.CONTEXT_UID].destroy(); + } + delete filters[i].glShaders[renderer.CONTEXT_UID]; + } + + this.shaderCache = {}; + if (!contextLost) { + this.emptyPool(); + } else { + this.pool = {}; + } + }; + + /** + * Gets a Power-of-Two render texture. + * + * TODO move to a seperate class could be on renderer? + * also - could cause issue with multiple contexts? + * + * @private + * @param {WebGLRenderingContext} gl - The webgl rendering context + * @param {number} minWidth - The minimum width of the render target. + * @param {number} minHeight - The minimum height of the render target. + * @param {number} resolution - The resolution of the render target. + * @return {PIXI.RenderTarget} The new render target. + */ + + + FilterManager.prototype.getPotRenderTarget = function getPotRenderTarget(gl, minWidth, minHeight, resolution) { + var key = screenKey; + + minWidth *= resolution; + minHeight *= resolution; + + if (minWidth !== this._screenWidth || minHeight !== this._screenHeight) { + // TODO you could return a bigger texture if there is not one in the pool? + minWidth = _bitTwiddle2.default.nextPow2(minWidth); + minHeight = _bitTwiddle2.default.nextPow2(minHeight); + key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + } + + if (!this.pool[key]) { + this.pool[key] = []; + } + + var renderTarget = this.pool[key].pop(); + + // creating render target will cause texture to be bound! + if (!renderTarget) { + // temporary bypass cache.. + var tex = this.renderer.boundTextures[0]; + + gl.activeTexture(gl.TEXTURE0); + + // internally - this will cause a texture to be bound.. + renderTarget = new _RenderTarget2.default(gl, minWidth, minHeight, null, 1); + + // set the current one back + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + } + + // manually tweak the resolution... + // this will not modify the size of the frame buffer, just its resolution. + renderTarget.resolution = resolution; + renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution; + renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution; + renderTarget.filterPoolKey = key; + + return renderTarget; + }; + + /** + * Empties the texture pool. + * + */ + + + FilterManager.prototype.emptyPool = function emptyPool() { + for (var i in this.pool) { + var textures = this.pool[i]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + + this.pool = {}; + }; + + /** + * Frees a render target back into the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free + */ + + + FilterManager.prototype.freePotRenderTarget = function freePotRenderTarget(renderTarget) { + this.pool[renderTarget.filterPoolKey].push(renderTarget); + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + FilterManager.prototype.onPrerender = function onPrerender() { + if (this._screenWidth !== this.renderer.view.width || this._screenHeight !== this.renderer.view.height) { + this._screenWidth = this.renderer.view.width; + this._screenHeight = this.renderer.view.height; + + var textures = this.pool[screenKey]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + this.pool[screenKey] = []; + } + }; + + return FilterManager; +}(_WebGLManager3.default); + +exports.default = FilterManager; + +},{"../../../Shader":44,"../../../math":70,"../filters/filterTransforms":88,"../utils/Quad":95,"../utils/RenderTarget":96,"./WebGLManager":93,"bit-twiddle":1}],91:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _SpriteMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); + +var _SpriteMaskFilter2 = _interopRequireDefault(_SpriteMaskFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var MaskManager = function (_WebGLManager) { + _inherits(MaskManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function MaskManager(renderer) { + _classCallCheck(this, MaskManager); + + // TODO - we don't need both! + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.scissor = false; + _this.scissorData = null; + _this.scissorRenderTarget = null; + + _this.enableScissor = true; + + _this.alphaMaskPool = []; + _this.alphaMaskIndex = 0; + return _this; + } + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushMask = function pushMask(target, maskData) { + // TODO the root check means scissor rect will not + // be used on render textures more info here: + // https://github.com/pixijs/pixi.js/pull/3545 + + if (maskData.texture) { + this.pushSpriteMask(target, maskData); + } else if (this.enableScissor && !this.scissor && this.renderer._activeRenderTarget.root && !this.renderer.stencilManager.stencilMaskStack.length && maskData.isFastRect()) { + var matrix = maskData.worldTransform; + + var rot = Math.atan2(matrix.b, matrix.a); + + // use the nearest degree! + rot = Math.round(rot * (180 / Math.PI)); + + if (rot % 90) { + this.pushStencilMask(maskData); + } else { + this.pushScissorMask(target, maskData); + } + } else { + this.pushStencilMask(maskData); + } + }; + + /** + * Removes the last mask from the mask stack and doesn't return it. + * + * @param {PIXI.DisplayObject} target - Display Object to pop the mask from + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.popMask = function popMask(target, maskData) { + if (maskData.texture) { + this.popSpriteMask(target, maskData); + } else if (this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length) { + this.popScissorMask(target, maskData); + } else { + this.popStencilMask(target, maskData); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.RenderTarget} target - Display Object to push the sprite mask to + * @param {PIXI.Sprite} maskData - Sprite to be used as the mask + */ + + + MaskManager.prototype.pushSpriteMask = function pushSpriteMask(target, maskData) { + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new _SpriteMaskFilter2.default(maskData)]; + } + + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskData; + + // TODO - may cause issues! + target.filterArea = maskData.getBounds(true); + + this.renderer.filterManager.pushFilter(target, alphaMaskFilter); + + this.alphaMaskIndex++; + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popSpriteMask = function popSpriteMask() { + this.renderer.filterManager.popFilter(); + this.alphaMaskIndex--; + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushStencilMask = function pushStencilMask(maskData) { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.pushStencil(maskData); + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popStencilMask = function popStencilMask() { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.popStencil(); + }; + + /** + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushScissorMask = function pushScissorMask(target, maskData) { + maskData.renderable = true; + + var renderTarget = this.renderer._activeRenderTarget; + + var bounds = maskData.getBounds(); + + bounds.fit(renderTarget.size); + maskData.renderable = false; + + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + + var resolution = this.renderer.resolution; + + this.renderer.gl.scissor(bounds.x * resolution, (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution, bounds.width * resolution, bounds.height * resolution); + + this.scissorRenderTarget = renderTarget; + this.scissorData = maskData; + this.scissor = true; + }; + + /** + * + * + */ + + + MaskManager.prototype.popScissorMask = function popScissorMask() { + this.scissorRenderTarget = null; + this.scissorData = null; + this.scissor = false; + + // must be scissor! + var gl = this.renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + }; + + return MaskManager; +}(_WebGLManager3.default); + +exports.default = MaskManager; + +},{"../filters/spriteMask/SpriteMaskFilter":89,"./WebGLManager":93}],92:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var StencilManager = function (_WebGLManager) { + _inherits(StencilManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function StencilManager(renderer) { + _classCallCheck(this, StencilManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.stencilMaskStack = null; + return _this; + } + + /** + * Changes the mask stack that is used by this manager. + * + * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack + */ + + + StencilManager.prototype.setMaskStack = function setMaskStack(stencilMaskStack) { + this.stencilMaskStack = stencilMaskStack; + + var gl = this.renderer.gl; + + if (stencilMaskStack.length === 0) { + gl.disable(gl.STENCIL_TEST); + } else { + gl.enable(gl.STENCIL_TEST); + } + }; + + /** + * Applies the Mask and adds it to the current stencil stack. @alvin + * + * @param {PIXI.Graphics} graphics - The mask + */ + + + StencilManager.prototype.pushStencil = function pushStencil(graphics) { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + this.renderer._activeRenderTarget.attachStencilBuffer(); + + var gl = this.renderer.gl; + var prevMaskCount = this.stencilMaskStack.length; + + if (prevMaskCount === 0) { + gl.enable(gl.STENCIL_TEST); + } + + this.stencilMaskStack.push(graphics); + + // Increment the refference stencil value where the new mask overlaps with the old ones. + gl.colorMask(false, false, false, false); + gl.stencilFunc(gl.EQUAL, prevMaskCount, this._getBitwiseMask()); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + this.renderer.plugins.graphics.render(graphics); + + this._useCurrent(); + }; + + /** + * Removes the last mask from the stencil stack. @alvin + */ + + + StencilManager.prototype.popStencil = function popStencil() { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + var gl = this.renderer.gl; + var graphics = this.stencilMaskStack.pop(); + + if (this.stencilMaskStack.length === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.clearStencil(0); + } else { + // Decrement the refference stencil value where the popped mask overlaps with the other ones + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + this.renderer.plugins.graphics.render(graphics); + + this._useCurrent(); + } + }; + + /** + * Setup renderer to use the current stencil data. + */ + + + StencilManager.prototype._useCurrent = function _useCurrent() { + var gl = this.renderer.gl; + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.EQUAL, this.stencilMaskStack.length, this._getBitwiseMask()); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; + + /** + * Fill 1s equal to the number of acitve stencil masks. + * + * @return {number} The bitwise mask. + */ + + + StencilManager.prototype._getBitwiseMask = function _getBitwiseMask() { + return (1 << this.stencilMaskStack.length) - 1; + }; + + /** + * Destroys the mask stack. + * + */ + + + StencilManager.prototype.destroy = function destroy() { + _WebGLManager3.default.prototype.destroy.call(this); + + this.stencilMaskStack.stencilStack = null; + }; + + return StencilManager; +}(_WebGLManager3.default); + +exports.default = StencilManager; + +},{"./WebGLManager":93}],93:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var WebGLManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function WebGLManager(renderer) { + _classCallCheck(this, WebGLManager); + + /** + * The renderer this manager works for. + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + this.renderer.on('context', this.onContextChange, this); + } + + /** + * Generic method called when there is a WebGL context change. + * + */ + + + WebGLManager.prototype.onContextChange = function onContextChange() {} + // do some codes init! + + + /** + * Generic destroy methods to be overridden by the subclass + * + */ + ; + + WebGLManager.prototype.destroy = function destroy() { + this.renderer.off('context', this.onContextChange, this); + + this.renderer = null; + }; + + return WebGLManager; +}(); + +exports.default = WebGLManager; + +},{}],94:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('../managers/WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Base for a common object renderer that can be used as a system renderer plugin. + * + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var ObjectRenderer = function (_WebGLManager) { + _inherits(ObjectRenderer, _WebGLManager); + + function ObjectRenderer() { + _classCallCheck(this, ObjectRenderer); + + return _possibleConstructorReturn(this, _WebGLManager.apply(this, arguments)); + } + + /** + * Starts the renderer and sets the shader + * + */ + ObjectRenderer.prototype.start = function start() {} + // set the shader.. + + + /** + * Stops the renderer + * + */ + ; + + ObjectRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Stub method for rendering content and emptying the current batch. + * + */ + + + ObjectRenderer.prototype.flush = function flush() {} + // flush! + + + /** + * Renders an object + * + * @param {PIXI.DisplayObject} object - The object to render. + */ + ; + + ObjectRenderer.prototype.render = function render(object) // eslint-disable-line no-unused-vars + { + // render the object + }; + + return ObjectRenderer; +}(_WebGLManager3.default); + +exports.default = ObjectRenderer; + +},{"../managers/WebGLManager":93}],95:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a quad + * + * @class + * @memberof PIXI + */ +var Quad = function () { + /** + * @param {WebGLRenderingContext} gl - The gl context for this quad to use. + * @param {object} state - TODO: Description + */ + function Quad(gl, state) { + _classCallCheck(this, Quad); + + /** + * the current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]); + + /** + * The Uvs of the quad + * + * @member {Float32Array} + */ + this.uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + this.interleaved = new Float32Array(8 * 2); + + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(1); + + /** + * The vertex buffer + * + * @member {glCore.GLBuffer} + */ + this.vertexBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW); + + /** + * The index buffer + * + * @member {glCore.GLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + /** + * The vertex array object + * + * @member {glCore.VertexArrayObject} + */ + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, state); + } + + /** + * Initialises the vaos and uses the shader. + * + * @param {PIXI.Shader} shader - the shader to use + */ + + + Quad.prototype.initVao = function initVao(shader) { + this.vao.clear().addIndex(this.indexBuffer).addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0).addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4); + }; + + /** + * Maps two Rectangle to the quad. + * + * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle + * @param {PIXI.Rectangle} destinationFrame - the second rectangle + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.map = function map(targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + + this.uvs[0] = x; + this.uvs[1] = y; + + this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; + + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; + + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; + + x = destinationFrame.x; + y = destinationFrame.y; + + this.vertices[0] = x; + this.vertices[1] = y; + + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + + return this; + }; + + /** + * Binds the buffer and uploads the data + * + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.upload = function upload() { + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + this.vertexBuffer.upload(this.interleaved); + + return this; + }; + + /** + * Removes this quad from WebGL + */ + + + Quad.prototype.destroy = function destroy() { + var gl = this.gl; + + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.indexBuffer); + }; + + return Quad; +}(); + +exports.default = Quad; + +},{"../../../utils/createIndicesForQuads":123,"pixi-gl-core":15}],96:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../../../math'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _pixiGlCore = require('pixi-gl-core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var RenderTarget = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {number} [width=0] - the horizontal range of the filter + * @param {number} [height=0] - the vertical range of the filter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The current resolution / device pixel ratio + * @param {boolean} [root=false] - Whether this object is the root element or not + */ + function RenderTarget(gl, width, height, scaleMode, resolution, root) { + _classCallCheck(this, RenderTarget); + + // TODO Resolution could go here ( eg low res blurs ) + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // next time to create a frame buffer and texture + + /** + * A frame buffer + * + * @member {PIXI.glCore.GLFramebuffer} + */ + this.frameBuffer = null; + + /** + * The texture + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The background colour of this render target, as an array of [r,g,b,a] values + * + * @member {number[]} + */ + this.clearColor = [0, 0, 0, 0]; + + /** + * The size of the object as a rectangle + * + * @member {PIXI.Rectangle} + */ + this.size = new _math.Rectangle(0, 0, 1, 1); + + /** + * The current resolution / device pixel ratio + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The projection matrix + * + * @member {PIXI.Matrix} + */ + this.projectionMatrix = new _math.Matrix(); + + /** + * The object's transform + * + * @member {PIXI.Matrix} + */ + this.transform = null; + + /** + * The frame. + * + * @member {PIXI.Rectangle} + */ + this.frame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.defaultFrame = new _math.Rectangle(); + this.destinationFrame = null; + this.sourceFrame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.stencilBuffer = null; + + /** + * The data structure for the stencil masks + * + * @member {PIXI.Graphics[]} + */ + this.stencilMaskStack = []; + + /** + * Stores filter data for the render target + * + * @member {object[]} + */ + this.filterData = null; + + /** + * The key for pooled texture of FilterSystem + * @private + * @member {string} + */ + this.filterPoolKey = ''; + + /** + * The scale mode. + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Whether this object is the root element or not + * + * @member {boolean} + */ + this.root = root; + + if (!this.root) { + this.frameBuffer = _pixiGlCore.GLFramebuffer.createRGBA(gl, 100, 100); + + if (this.scaleMode === _const.SCALE_MODES.NEAREST) { + this.frameBuffer.texture.enableNearestScaling(); + } else { + this.frameBuffer.texture.enableLinearScaling(); + } + /* + A frame buffer needs a target to render to.. + create a texture and bind it attach it to the framebuffer.. + */ + + // this is used by the base texture + this.texture = this.frameBuffer.texture; + } else { + // make it a null framebuffer.. + this.frameBuffer = new _pixiGlCore.GLFramebuffer(gl, 100, 100); + this.frameBuffer.framebuffer = null; + } + + this.setFrame(); + + this.resize(width, height); + } + + /** + * Clears the filter texture. + * + * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer + */ + + + RenderTarget.prototype.clear = function clear(clearColor) { + var cc = clearColor || this.clearColor; + + this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a); + }; + + /** + * Binds the stencil buffer. + * + */ + + + RenderTarget.prototype.attachStencilBuffer = function attachStencilBuffer() { + // TODO check if stencil is done? + /** + * The stencil buffer is used for masking in pixi + * lets create one and then add attach it to the framebuffer.. + */ + if (!this.root) { + this.frameBuffer.enableStencil(); + } + }; + + /** + * Sets the frame of the render target. + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.setFrame = function setFrame(destinationFrame, sourceFrame) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || this.destinationFrame; + }; + + /** + * Binds the buffers and initialises the viewport. + * + */ + + + RenderTarget.prototype.activate = function activate() { + // TOOD refactor usage of frame.. + var gl = this.gl; + + // make sure the texture is unbound! + this.frameBuffer.bind(); + + this.calculateProjection(this.destinationFrame, this.sourceFrame); + + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + + // TODO add a check as them may be the same! + if (this.destinationFrame !== this.sourceFrame) { + gl.enable(gl.SCISSOR_TEST); + gl.scissor(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + } else { + gl.disable(gl.SCISSOR_TEST); + } + + // TODO - does not need to be updated all the time?? + gl.viewport(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + }; + + /** + * Updates the projection matrix based on a projection frame (which is a rectangle) + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.calculateProjection = function calculateProjection(destinationFrame, sourceFrame) { + var pm = this.projectionMatrix; + + sourceFrame = sourceFrame || destinationFrame; + + pm.identity(); + + // TODO: make dest scale source + if (!this.root) { + pm.a = 1 / destinationFrame.width * 2; + pm.d = 1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = -1 - sourceFrame.y * pm.d; + } else { + pm.a = 1 / destinationFrame.width * 2; + pm.d = -1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = 1 - sourceFrame.y * pm.d; + } + }; + + /** + * Resizes the texture to the specified width and height + * + * @param {number} width - the new width of the texture + * @param {number} height - the new height of the texture + */ + + + RenderTarget.prototype.resize = function resize(width, height) { + width = width | 0; + height = height | 0; + + if (this.size.width === width && this.size.height === height) { + return; + } + + this.size.width = width; + this.size.height = height; + + this.defaultFrame.width = width; + this.defaultFrame.height = height; + + this.frameBuffer.resize(width * this.resolution, height * this.resolution); + + var projectionFrame = this.frame || this.size; + + this.calculateProjection(projectionFrame); + }; + + /** + * Destroys the render target. + * + */ + + + RenderTarget.prototype.destroy = function destroy() { + this.frameBuffer.destroy(); + + this.frameBuffer = null; + this.texture = null; + }; + + return RenderTarget; +}(); + +exports.default = RenderTarget; + +},{"../../../const":46,"../../../math":70,"../../../settings":101,"pixi-gl-core":15}],97:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = checkMaxIfStatmentsInShader; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['precision mediump float;', 'void main(void){', 'float test = 0.1;', '%forloop%', 'gl_FragColor = vec4(0.0);', '}'].join('\n'); + +function checkMaxIfStatmentsInShader(maxIfs, gl) { + var createTempContext = !gl; + + if (maxIfs === 0) { + throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); + } + + if (createTempContext) { + var tinyCanvas = document.createElement('canvas'); + + tinyCanvas.width = 1; + tinyCanvas.height = 1; + + gl = _pixiGlCore2.default.createContext(tinyCanvas); + } + + var shader = gl.createShader(gl.FRAGMENT_SHADER); + + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = maxIfs / 2 | 0; + } else { + // valid! + break; + } + } + + if (createTempContext) { + // get rid of context + if (gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').loseContext(); + } + } + + return maxIfs; +} + +function generateIfTestSrc(maxIfs) { + var src = ''; + + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxIfs - 1) { + src += 'if(test == ' + i + '.0){}'; + } + } + + return src; +} + +},{"pixi-gl-core":15}],98:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLBlendModesToPixi; + +var _const = require('../../../const'); + +/** + * Maps gl blend combinations to WebGL. + * + * @memberof PIXI + * @function mapWebGLBlendModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapWebGLBlendModesToPixi(gl) { + var array = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[_const.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD] = [gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + array[_const.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + // not-premultiplied blend modes + array[_const.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.DST_ALPHA, gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + + return array; +} + +},{"../../../const":46}],99:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLDrawModesToPixi; + +var _const = require('../../../const'); + +/** + * Generic Mask Stack data structure. + * + * @memberof PIXI + * @function mapWebGLDrawModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {object} [object={}] - The object to map into + * @return {object} The mapped draw modes. + */ +function mapWebGLDrawModesToPixi(gl) { + var object = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + object[_const.DRAW_MODES.POINTS] = gl.POINTS; + object[_const.DRAW_MODES.LINES] = gl.LINES; + object[_const.DRAW_MODES.LINE_LOOP] = gl.LINE_LOOP; + object[_const.DRAW_MODES.LINE_STRIP] = gl.LINE_STRIP; + object[_const.DRAW_MODES.TRIANGLES] = gl.TRIANGLES; + object[_const.DRAW_MODES.TRIANGLE_STRIP] = gl.TRIANGLE_STRIP; + object[_const.DRAW_MODES.TRIANGLE_FAN] = gl.TRIANGLE_FAN; + + return object; +} + +},{"../../../const":46}],100:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = validateContext; +function validateContext(gl) { + var attributes = gl.getContextAttributes(); + + // this is going to be fairly simple for now.. but at least we have room to grow! + if (!attributes.stencil) { + /* eslint-disable no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable no-console */ + } +} + +},{}],101:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _maxRecommendedTextures = require('./utils/maxRecommendedTextures'); + +var _maxRecommendedTextures2 = _interopRequireDefault(_maxRecommendedTextures); + +var _canUploadSameBuffer = require('./utils/canUploadSameBuffer'); + +var _canUploadSameBuffer2 = _interopRequireDefault(_canUploadSameBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * User's customizable globals for overriding the default PIXI settings, such + * as a renderer's default resolution, framerate, float percision, etc. + * @example + * // Use the native window resolution as the default resolution + * // will support high-density displays when rendering + * PIXI.settings.RESOLUTION = window.devicePixelRatio. + * + * // Disable interpolation when scaling, will make texture be pixelated + * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; + * @namespace PIXI.settings + */ +exports.default = { + + /** + * Target frames per millisecond. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 0.06 + */ + TARGET_FPMS: 0.06, + + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * + * @static + * @memberof PIXI.settings + * @type {boolean} + * @default true + */ + MIPMAP_TEXTURES: true, + + /** + * Default resolution / device pixel ratio of the renderer. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + RESOLUTION: 1, + + /** + * Default filter resolution. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + FILTER_RESOLUTION: 1, + + /** + * The maximum textures that this device supports. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 32 + */ + SPRITE_MAX_TEXTURES: (0, _maxRecommendedTextures2.default)(32), + + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + + /** + * The prefix that denotes a URL is for a retina asset. + * + * @static + * @memberof PIXI.settings + * @type {RegExp} + * @example `@2x` + * @default /@([0-9\.]+)x/ + */ + RETINA_PREFIX: /@([0-9\.]+)x/, + + /** + * The default render options if none are supplied to {@link PIXI.WebGLRenderer} + * or {@link PIXI.CanvasRenderer}. + * + * @static + * @constant + * @memberof PIXI.settings + * @type {object} + * @property {HTMLCanvasElement} view=null + * @property {number} resolution=1 + * @property {boolean} antialias=false + * @property {boolean} forceFXAA=false + * @property {boolean} autoResize=false + * @property {boolean} transparent=false + * @property {number} backgroundColor=0x000000 + * @property {boolean} clearBeforeRender=true + * @property {boolean} preserveDrawingBuffer=false + * @property {boolean} roundPixels=false + * @property {number} width=800 + * @property {number} height=600 + * @property {boolean} legacy=false + */ + RENDER_OPTIONS: { + view: null, + antialias: false, + forceFXAA: false, + autoResize: false, + transparent: false, + backgroundColor: 0x000000, + clearBeforeRender: true, + preserveDrawingBuffer: false, + roundPixels: false, + width: 800, + height: 600, + legacy: false + }, + + /** + * Default transform type. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.TRANSFORM_MODE} + * @default PIXI.TRANSFORM_MODE.STATIC + */ + TRANSFORM_MODE: 0, + + /** + * Default Garbage Collection mode. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO + */ + GC_MODE: 0, + + /** + * Default Garbage Collection max idle. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 3600 + */ + GC_MAX_IDLE: 60 * 60, + + /** + * Default Garbage Collection maximum check count. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 600 + */ + GC_MAX_CHECK_COUNT: 60 * 10, + + /** + * Default wrap modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP + */ + WRAP_MODE: 0, + + /** + * The scale modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR + */ + SCALE_MODE: 0, + + /** + * Default specify float precision in vertex shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.HIGH + */ + PRECISION_VERTEX: 'highp', + + /** + * Default specify float precision in fragment shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM + */ + PRECISION_FRAGMENT: 'mediump', + + /** + * Can we upload the same buffer in a single frame? + * + * @static + * @constant + * @memberof PIXI.settings + * @type {boolean} + */ + CAN_UPLOAD_SAME_BUFFER: (0, _canUploadSameBuffer2.default)(), + + /** + * Default Mesh `canvasPadding`. + * + * @see PIXI.mesh.Mesh#canvasPadding + * @static + * @constant + * @memberof PIXI.settings + * @type {number} + */ + MESH_CANVAS_PADDING: 0 +}; + +},{"./utils/canUploadSameBuffer":122,"./utils/maxRecommendedTextures":127}],102:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new _math.Point(); + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = new PIXI.Sprite.fromImage('assets/image.png'); + * ``` + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Sprite = function (_Container) { + _inherits(Sprite, _Container); + + /** + * @param {PIXI.Texture} texture - The texture for this sprite + */ + function Sprite(texture) { + _classCallCheck(this, Sprite); + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + * @private + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this._anchor = new _math.ObservablePoint(_this._onAnchorUpdate, _this); + + /** + * The texture that the sprite is using + * + * @private + * @member {PIXI.Texture} + */ + _this._texture = null; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = null; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * The shader that will be used to render the sprite. Set to null to remove a current shader. + * + * @member {PIXI.Filter|PIXI.Shader} + */ + _this.shader = null; + + /** + * An internal cached value of the tint. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this.cachedTint = 0xFFFFFF; + + // call texture setter + _this.texture = texture || _Texture2.default.EMPTY; + + /** + * this is used to store the vertex data of the sprite (basically a quad) + * + * @private + * @member {Float32Array} + */ + _this.vertexData = new Float32Array(8); + + /** + * This is used to calculate the bounds of the object IF it is a trimmed sprite + * + * @private + * @member {Float32Array} + */ + _this.vertexTrimmedData = null; + + _this._transformID = -1; + _this._textureID = -1; + + _this._transformTrimmedID = -1; + _this._textureTrimmedID = -1; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * + * @member {string} + * @default 'sprite' + */ + _this.pluginName = 'sprite'; + return _this; + } + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Sprite.prototype._onTextureUpdate = function _onTextureUpdate() { + this._textureID = -1; + this._textureTrimmedID = -1; + this.cachedTint = 0xFFFFFF; + + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = (0, _utils.sign)(this.scale.x) * this._width / this._texture.orig.width; + } + + if (this._height) { + this.scale.y = (0, _utils.sign)(this.scale.y) * this._height / this._texture.orig.height; + } + }; + + /** + * Called when the anchor position updates. + * + * @private + */ + + + Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate() { + this._transformID = -1; + this._transformTrimmedID = -1; + }; + + /** + * calculates worldTransform * vertices, store it in vertexData + */ + + + Sprite.prototype.calculateVertices = function calculateVertices() { + if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) { + return; + } + + this._transformID = this.transform._worldID; + this._textureID = this._texture._updateID; + + // set the vertex data + + var texture = this._texture; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var anchor = this._anchor; + + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - anchor._x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - anchor._y * orig.height; + h0 = h1 + trim.height; + } else { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData + * This is used to ensure that the true width and height of a trimmed texture is respected + */ + + + Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices() { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { + return; + } + + this._transformTrimmedID = this.transform._worldID; + this._textureTrimmedID = this._texture._updateID; + + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + var anchor = this._anchor; + + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + + var w1 = -anchor._x * orig.width; + var w0 = w1 + orig.width; + + var h1 = -anchor._y * orig.height; + var h0 = h1 + orig.height; + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use. + */ + + + Sprite.prototype._renderWebGL = function _renderWebGL(renderer) { + this.calculateVertices(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Sprite.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Updates the bounds of the sprite. + * + * @private + */ + + + Sprite.prototype._calculateBounds = function _calculateBounds() { + var trim = this._texture.trim; + var orig = this._texture.orig; + + // First lets check to see if the current texture has a trim.. + if (!trim || trim.width === orig.width && trim.height === orig.height) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + Sprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._texture.orig.width * -this._anchor._x; + this._bounds.minY = this._texture.orig.height * -this._anchor._y; + this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x); + this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._y); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _Container.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Tests if a point is inside this sprite + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Sprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + y1 = -height * this.anchor.y; + + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + Sprite.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + this._texture.off('update', this._onTextureUpdate, this); + + this._anchor = null; + + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + + this._texture.destroy(!!destroyBaseTexture); + } + + this._texture = null; + this.shader = null; + }; + + // some helper functions.. + + /** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Sprite} The newly created sprite + */ + + + Sprite.from = function from(source) { + return new Sprite(_Texture2.default.from(source)); + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId + */ + + + Sprite.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return new Sprite(texture); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id + */ + + + Sprite.fromImage = function fromImage(imageId, crossorigin, scaleMode) { + return new Sprite(_Texture2.default.fromImage(imageId, crossorigin, scaleMode)); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Sprite, [{ + key: 'width', + get: function get() { + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 this means the texture's origin is the top left + * Setting the anchor to 0.5,0.5 means the texture's origin is centered + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._anchor.copy(value); + } + + /** + * The tint applied to the sprite. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + } + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + */ + + }, { + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + this.cachedTint = 0xFFFFFF; + + this._textureID = -1; + this._textureTrimmedID = -1; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + }]); + + return Sprite; +}(_Container3.default); + +exports.default = Sprite; + +},{"../const":46,"../display/Container":48,"../math":70,"../textures/Texture":115,"../utils":125}],103:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +var _math = require('../../math'); + +var _CanvasTinter = require('./CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var canvasRenderWorldTransform = new _math.Matrix(); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasSpriteRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + */ + +var CanvasSpriteRenderer = function () { + /** + * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for. + */ + function CanvasSpriteRenderer(renderer) { + _classCallCheck(this, CanvasSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + CanvasSpriteRenderer.prototype.render = function render(sprite) { + var texture = sprite._texture; + var renderer = this.renderer; + + var width = texture._frame.width; + var height = texture._frame.height; + + var wt = sprite.transform.worldTransform; + var dx = 0; + var dy = 0; + + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) { + return; + } + + renderer.setBlendMode(sprite.blendMode); + + // Ignore null sources + if (texture.valid) { + renderer.context.globalAlpha = sprite.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture + var smoothingEnabled = texture.baseTexture.scaleMode === _const.SCALE_MODES.LINEAR; + + if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) { + renderer.context[renderer.smoothProperty] = smoothingEnabled; + } + + if (texture.trim) { + dx = texture.trim.width / 2 + texture.trim.x - sprite.anchor.x * texture.orig.width; + dy = texture.trim.height / 2 + texture.trim.y - sprite.anchor.y * texture.orig.height; + } else { + dx = (0.5 - sprite.anchor.x) * texture.orig.width; + dy = (0.5 - sprite.anchor.y) * texture.orig.height; + } + + if (texture.rotate) { + wt.copy(canvasRenderWorldTransform); + wt = canvasRenderWorldTransform; + _math.GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); + // the anchor has already been applied above, so lets set it to zero + dx = 0; + dy = 0; + } + + dx -= width / 2; + dy -= height / 2; + + // Allow for pixel rounding + if (renderer.roundPixels) { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution | 0, wt.ty * renderer.resolution | 0); + + dx = dx | 0; + dy = dy | 0; + } else { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution, wt.ty * renderer.resolution); + } + + var resolution = texture.baseTexture.resolution; + + if (sprite.tint !== 0xFFFFFF) { + if (sprite.cachedTint !== sprite.tint || sprite.tintedTexture.tintId !== sprite._texture._updateID) { + sprite.cachedTint = sprite.tint; + + // TODO clean up caching - how to clean up the caches? + sprite.tintedTexture = _CanvasTinter2.default.getTintedTexture(sprite, sprite.tint); + } + + renderer.context.drawImage(sprite.tintedTexture, 0, 0, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } else { + renderer.context.drawImage(texture.baseTexture.source, texture._frame.x * resolution, texture._frame.y * resolution, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } + } + }; + + /** + * destroy the sprite object. + * + */ + + + CanvasSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasSpriteRenderer; +}(); + +exports.default = CanvasSpriteRenderer; + + +_CanvasRenderer2.default.registerPlugin('sprite', CanvasSpriteRenderer); + +},{"../../const":46,"../../math":70,"../../renderers/canvas/CanvasRenderer":77,"./CanvasTinter":104}],104:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class + * @memberof PIXI + */ +var CanvasTinter = { + /** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Sprite} sprite - the sprite to tint + * @param {number} color - the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ + getTintedTexture: function getTintedTexture(sprite, color) { + var texture = sprite._texture; + + color = CanvasTinter.roundColor(color); + + var stringColor = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + texture.tintCache = texture.tintCache || {}; + + var cachedTexture = texture.tintCache[stringColor]; + + var canvas = void 0; + + if (cachedTexture) { + if (cachedTexture.tintId === texture._updateID) { + return texture.tintCache[stringColor]; + } + + canvas = texture.tintCache[stringColor]; + } else { + canvas = CanvasTinter.canvas || document.createElement('canvas'); + } + + CanvasTinter.tintMethod(texture, color, canvas); + + canvas.tintId = texture._updateID; + + if (CanvasTinter.convertTintToImage) { + // is this better? + var tintImage = new Image(); + + tintImage.src = canvas.toDataURL(); + + texture.tintCache[stringColor] = tintImage; + } else { + texture.tintCache[stringColor] = canvas; + // if we are not converting the texture to an image then we need to lose the reference to the canvas + CanvasTinter.canvas = null; + } + + return canvas; + }, + + /** + * Tint a texture using the 'multiply' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithMultiply: function tintWithMultiply(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.save(); + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + context.restore(); + }, + + /** + * Tint a texture using the 'overlay' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithOverlay: function tintWithOverlay(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.save(); + context.globalCompositeOperation = 'copy'; + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + // context.globalCompositeOperation = 'copy'; + context.restore(); + }, + + + /** + * Tint a texture pixel per pixel. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithPerPixel: function tintWithPerPixel(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.save(); + context.globalCompositeOperation = 'copy'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + context.restore(); + + var rgbValues = (0, _utils.hex2rgb)(color); + var r = rgbValues[0]; + var g = rgbValues[1]; + var b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, crop.width, crop.height); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + } + + context.putImageData(pixelData, 0, 0); + }, + + /** + * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel. + * + * @memberof PIXI.CanvasTinter + * @param {number} color - the color to round, should be a hex color + * @return {number} The rounded color. + */ + roundColor: function roundColor(color) { + var step = CanvasTinter.cacheStepsPerColorChannel; + + var rgbValues = (0, _utils.hex2rgb)(color); + + rgbValues[0] = Math.min(255, rgbValues[0] / step * step); + rgbValues[1] = Math.min(255, rgbValues[1] / step * step); + rgbValues[2] = Math.min(255, rgbValues[2] / step * step); + + return (0, _utils.rgb2hex)(rgbValues); + }, + + /** + * Number of steps which will be used as a cap when rounding colors. + * + * @memberof PIXI.CanvasTinter + * @type {number} + */ + cacheStepsPerColorChannel: 8, + + /** + * Tint cache boolean flag. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + convertTintToImage: false, + + /** + * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + canUseMultiply: (0, _canUseNewCanvasBlendModes2.default)(), + + /** + * The tinting method that will be used. + * + * @memberof PIXI.CanvasTinter + * @type {tintMethodFunctionType} + */ + tintMethod: 0 +}; + +CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply : CanvasTinter.tintWithPerPixel; + +/** + * The tintMethod type. + * + * @memberof PIXI.CanvasTinter + * @callback tintMethodFunctionType + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + +exports.default = CanvasTinter; + +},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":80,"../../utils":125}],105:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Buffer = function () { + /** + * @param {number} size - The size of the buffer in bytes. + */ + function Buffer(size) { + _classCallCheck(this, Buffer); + + this.vertices = new ArrayBuffer(size); + + /** + * View on the vertices as a Float32Array for positions + * + * @member {Float32Array} + */ + this.float32View = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array for uvs + * + * @member {Float32Array} + */ + this.uint32View = new Uint32Array(this.vertices); + } + + /** + * Destroys the buffer. + * + */ + + + Buffer.prototype.destroy = function destroy() { + this.vertices = null; + this.positions = null; + this.uvs = null; + this.colors = null; + }; + + return Buffer; +}(); + +exports.default = Buffer; + +},{}],106:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _createIndicesForQuads = require('../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +var _generateMultiTextureShader = require('./generateMultiTextureShader'); + +var _generateMultiTextureShader2 = _interopRequireDefault(_generateMultiTextureShader); + +var _checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'); + +var _checkMaxIfStatmentsInShader2 = _interopRequireDefault(_checkMaxIfStatmentsInShader); + +var _BatchBuffer = require('./BatchBuffer'); + +var _BatchBuffer2 = _interopRequireDefault(_BatchBuffer); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var TICK = 0; +var TEXTURE_TICK = 0; + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var SpriteRenderer = function (_ObjectRenderer) { + _inherits(SpriteRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function SpriteRenderer(renderer) { + _classCallCheck(this, SpriteRenderer); + + /** + * Number of values sent in the vertex buffer. + * aVertexPosition(2), aTextureCoord(1), aColor(1), aTextureId(1) = 5 + * + * @member {number} + */ + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.vertSize = 5; + + /** + * The size of the vertex information in bytes. + * + * @member {number} + */ + _this.vertByteSize = _this.vertSize * 4; + + /** + * The number of images in the SpriteRenderer before it flushes. + * + * @member {number} + */ + _this.size = _settings2.default.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + + // the total number of bytes in our batch + // let numVerts = this.size * 4 * this.vertByteSize; + + _this.buffers = []; + for (var i = 1; i <= _bitTwiddle2.default.nextPow2(_this.size); i *= 2) { + _this.buffers.push(new _BatchBuffer2.default(i * 4 * _this.vertByteSize)); + } + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + _this.indices = (0, _createIndicesForQuads2.default)(_this.size); + + /** + * The default shaders that is used if a sprite doesn't have a more specific one. + * there is a shader for each number of textures that can be rendererd. + * These shaders will also be generated on the fly as required. + * @member {PIXI.Shader[]} + */ + _this.shader = null; + + _this.currentIndex = 0; + _this.groups = []; + + for (var k = 0; k < _this.size; k++) { + _this.groups[k] = { textures: [], textureCount: 0, ids: [], size: 0, start: 0, blend: 0 }; + } + + _this.sprites = []; + + _this.vertexBuffers = []; + _this.vaos = []; + + _this.vaoMax = 2; + _this.vertexCount = 0; + + _this.renderer.on('prerender', _this.onPrerender, _this); + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + SpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + if (this.renderer.legacy) { + this.MAX_TEXTURES = 1; + } else { + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), _settings2.default.SPRITE_MAX_TEXTURES); + + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = (0, _checkMaxIfStatmentsInShader2.default)(this.MAX_TEXTURES, gl); + } + + this.shader = (0, _generateMultiTextureShader2.default)(gl, this.MAX_TEXTURES); + + // create a couple of buffers + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + // we use the second shader as the first one depending on your browser may omit aTextureId + // as it is not used by the shader so is optimized out. + + this.renderer.bindVao(null); + + var attrs = this.shader.attributes; + + for (var i = 0; i < this.vaoMax; i++) { + /* eslint-disable max-len */ + var vertexBuffer = this.vertexBuffers[i] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + /* eslint-enable max-len */ + + // build the vao object that will render.. + var vao = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (attrs.aTextureId) { + vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vaos[i] = vao; + } + + this.vao = this.vaos[0]; + this.currentBlendMode = 99999; + + this.boundTextures = new Array(this.MAX_TEXTURES); + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + SpriteRenderer.prototype.onPrerender = function onPrerender() { + this.vertexCount = 0; + }; + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + SpriteRenderer.prototype.render = function render(sprite) { + // TODO set blend modes.. + // check texture.. + if (this.currentIndex >= this.size) { + this.flush(); + } + + // get the uvs for the texture + + // if the uvs have not updated then no point rendering just yet! + if (!sprite._texture._uvs) { + return; + } + + // push a texture. + // increment the batchsize + this.sprites[this.currentIndex++] = sprite; + }; + + /** + * Renders the content and empties the current batch. + * + */ + + + SpriteRenderer.prototype.flush = function flush() { + if (this.currentIndex === 0) { + return; + } + + var gl = this.renderer.gl; + var MAX_TEXTURES = this.MAX_TEXTURES; + + var np2 = _bitTwiddle2.default.nextPow2(this.currentIndex); + var log2 = _bitTwiddle2.default.log2(np2); + var buffer = this.buffers[log2]; + + var sprites = this.sprites; + var groups = this.groups; + + var float32View = buffer.float32View; + var uint32View = buffer.uint32View; + + var boundTextures = this.boundTextures; + var rendererBoundTextures = this.renderer.boundTextures; + var touch = this.renderer.textureGC.count; + + var index = 0; + var nextTexture = void 0; + var currentTexture = void 0; + var groupCount = 1; + var textureCount = 0; + var currentGroup = groups[0]; + var vertexData = void 0; + var uvs = void 0; + var blendMode = _utils.premultiplyBlendMode[sprites[0]._texture.baseTexture.premultipliedAlpha ? 1 : 0][sprites[0].blendMode]; + + currentGroup.textureCount = 0; + currentGroup.start = 0; + currentGroup.blend = blendMode; + + TICK++; + + var i = void 0; + + // copy textures.. + for (i = 0; i < MAX_TEXTURES; ++i) { + var bt = rendererBoundTextures[i]; + + if (bt._enabled === TICK) { + boundTextures[i] = this.renderer.emptyTextures[i]; + continue; + } + + boundTextures[i] = bt; + bt._virtalBoundId = i; + bt._enabled = TICK; + } + TICK++; + + for (i = 0; i < this.currentIndex; ++i) { + // upload the sprite elemetns... + // they have all ready been calculated so we just need to push them into the buffer. + var sprite = sprites[i]; + + sprites[i] = null; + + nextTexture = sprite._texture.baseTexture; + + var spriteBlendMode = _utils.premultiplyBlendMode[Number(nextTexture.premultipliedAlpha)][sprite.blendMode]; + + if (blendMode !== spriteBlendMode) { + // finish a group.. + blendMode = spriteBlendMode; + + // force the batch to break! + currentTexture = null; + textureCount = MAX_TEXTURES; + TICK++; + } + + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + + if (nextTexture._enabled !== TICK) { + if (textureCount === MAX_TEXTURES) { + TICK++; + + currentGroup.size = i - currentGroup.start; + + textureCount = 0; + + currentGroup = groups[groupCount++]; + currentGroup.blend = blendMode; + currentGroup.textureCount = 0; + currentGroup.start = i; + } + + nextTexture.touched = touch; + + if (nextTexture._virtalBoundId === -1) { + for (var j = 0; j < MAX_TEXTURES; ++j) { + var tIndex = (j + TEXTURE_TICK) % MAX_TEXTURES; + + var t = boundTextures[tIndex]; + + if (t._enabled !== TICK) { + TEXTURE_TICK++; + + t._virtalBoundId = -1; + + nextTexture._virtalBoundId = tIndex; + + boundTextures[tIndex] = nextTexture; + break; + } + } + } + + nextTexture._enabled = TICK; + + currentGroup.textureCount++; + currentGroup.ids[textureCount] = nextTexture._virtalBoundId; + currentGroup.textures[textureCount++] = nextTexture; + } + } + + vertexData = sprite.vertexData; + + // TODO this sum does not need to be set each frame.. + uvs = sprite._texture._uvs.uvsUint32; + + if (this.renderer.roundPixels) { + var resolution = this.renderer.resolution; + + // xy + float32View[index] = (vertexData[0] * resolution | 0) / resolution; + float32View[index + 1] = (vertexData[1] * resolution | 0) / resolution; + + // xy + float32View[index + 5] = (vertexData[2] * resolution | 0) / resolution; + float32View[index + 6] = (vertexData[3] * resolution | 0) / resolution; + + // xy + float32View[index + 10] = (vertexData[4] * resolution | 0) / resolution; + float32View[index + 11] = (vertexData[5] * resolution | 0) / resolution; + + // xy + float32View[index + 15] = (vertexData[6] * resolution | 0) / resolution; + float32View[index + 16] = (vertexData[7] * resolution | 0) / resolution; + } else { + // xy + float32View[index] = vertexData[0]; + float32View[index + 1] = vertexData[1]; + + // xy + float32View[index + 5] = vertexData[2]; + float32View[index + 6] = vertexData[3]; + + // xy + float32View[index + 10] = vertexData[4]; + float32View[index + 11] = vertexData[5]; + + // xy + float32View[index + 15] = vertexData[6]; + float32View[index + 16] = vertexData[7]; + } + + uint32View[index + 2] = uvs[0]; + uint32View[index + 7] = uvs[1]; + uint32View[index + 12] = uvs[2]; + uint32View[index + 17] = uvs[3]; + /* eslint-disable max-len */ + var alpha = Math.min(sprite.worldAlpha, 1.0); + // we dont call extra function if alpha is 1.0, that's faster + var argb = alpha < 1.0 && nextTexture.premultipliedAlpha ? (0, _utils.premultiplyTint)(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); + + uint32View[index + 3] = uint32View[index + 8] = uint32View[index + 13] = uint32View[index + 18] = argb; + float32View[index + 4] = float32View[index + 9] = float32View[index + 14] = float32View[index + 19] = nextTexture._virtalBoundId; + /* eslint-enable max-len */ + + index += 20; + } + + currentGroup.size = i - currentGroup.start; + + if (!_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // this is still needed for IOS performance.. + // it really does not like uploading to the same buffer in a single frame! + if (this.vaoMax <= this.vertexCount) { + this.vaoMax++; + + var attrs = this.shader.attributes; + + /* eslint-disable max-len */ + var vertexBuffer = this.vertexBuffers[this.vertexCount] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + /* eslint-enable max-len */ + + // build the vao object that will render.. + var vao = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (attrs.aTextureId) { + vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vaos[this.vertexCount] = vao; + } + + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, false); + + this.vertexCount++; + } else { + // lets use the faster option, always use buffer number 0 + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, true); + } + + for (i = 0; i < MAX_TEXTURES; ++i) { + rendererBoundTextures[i]._virtalBoundId = -1; + } + + // render the groups.. + for (i = 0; i < groupCount; ++i) { + var group = groups[i]; + var groupTextureCount = group.textureCount; + + for (var _j = 0; _j < groupTextureCount; _j++) { + currentTexture = group.textures[_j]; + + // reset virtual ids.. + // lets do a quick check.. + if (rendererBoundTextures[group.ids[_j]] !== currentTexture) { + this.renderer.bindTexture(currentTexture, group.ids[_j], true); + } + + // reset the virtualId.. + currentTexture._virtalBoundId = -1; + } + + // set the blend mode.. + this.renderer.state.setBlendMode(group.blend); + + gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); + } + + // reset elements for the next flush + this.currentIndex = 0; + }; + + /** + * Starts a new sprite batch. + */ + + + SpriteRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + + if (_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // bind buffer #0, we don't need others + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].bind(); + } + }; + + /** + * Stops and flushes the current batch. + * + */ + + + SpriteRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Destroys the SpriteRenderer. + * + */ + + + SpriteRenderer.prototype.destroy = function destroy() { + for (var i = 0; i < this.vaoMax; i++) { + if (this.vertexBuffers[i]) { + this.vertexBuffers[i].destroy(); + } + if (this.vaos[i]) { + this.vaos[i].destroy(); + } + } + + if (this.indexBuffer) { + this.indexBuffer.destroy(); + } + + this.renderer.off('prerender', this.onPrerender, this); + + _ObjectRenderer.prototype.destroy.call(this); + + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } + + this.vertexBuffers = null; + this.vaos = null; + this.indexBuffer = null; + this.indices = null; + + this.sprites = null; + + for (var _i = 0; _i < this.buffers.length; ++_i) { + this.buffers[_i].destroy(); + } + }; + + return SpriteRenderer; +}(_ObjectRenderer3.default); + +exports.default = SpriteRenderer; + + +_WebGLRenderer2.default.registerPlugin('sprite', SpriteRenderer); + +},{"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":97,"../../settings":101,"../../utils":125,"../../utils/createIndicesForQuads":123,"./BatchBuffer":105,"./generateMultiTextureShader":107,"bit-twiddle":1,"pixi-gl-core":15}],107:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateMultiTextureShader; + +var _Shader = require('../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'varying float vTextureId;', 'uniform sampler2D uSamplers[%count%];', 'void main(void){', 'vec4 color;', 'float textureId = floor(vTextureId+0.5);', '%forloop%', 'gl_FragColor = color * vColor;', '}'].join('\n'); + +function generateMultiTextureShader(gl, maxTextures) { + var vertexSrc = 'precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor;\n}\n'; + var fragmentSrc = fragTemplate; + + fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); + + var shader = new _Shader2.default(gl, vertexSrc, fragmentSrc); + + var sampleValues = []; + + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + + shader.bind(); + shader.uniforms.uSamplers = sampleValues; + + return shader; +} + +function generateSampleSrc(maxTextures) { + var src = ''; + + src += '\n'; + src += '\n'; + + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxTextures - 1) { + src += 'if(textureId == ' + i + '.0)'; + } + + src += '\n{'; + src += '\n\tcolor = texture2D(uSamplers[' + i + '], vTextureCoord);'; + src += '\n}'; + } + + src += '\n'; + src += '\n'; + + return src; +} + +},{"../../Shader":44,"path":8}],108:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Sprite2 = require('../sprites/Sprite'); + +var _Sprite3 = _interopRequireDefault(_Sprite2); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TextStyle = require('./TextStyle'); + +var _TextStyle2 = _interopRequireDefault(_TextStyle); + +var _TextMetrics = require('./TextMetrics'); + +var _TextMetrics2 = _interopRequireDefault(_TextMetrics); + +var _trimCanvas = require('../utils/trimCanvas'); + +var _trimCanvas2 = _interopRequireDefault(_trimCanvas); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint max-depth: [2, 8] */ + + +var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true +}; + +/** + * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string, + * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object. + * + * A Text can be created directly from a string and a style object + * + * ```js + * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI + */ + +var Text = function (_Sprite) { + _inherits(Text, _Sprite); + + /** + * @param {string} text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + * @param {HTMLCanvasElement} [canvas] - The canvas element for drawing text + */ + function Text(text, style, canvas) { + _classCallCheck(this, Text); + + canvas = canvas || document.createElement('canvas'); + + canvas.width = 3; + canvas.height = 3; + + var texture = _Texture2.default.fromCanvas(canvas, _settings2.default.SCALE_MODE, 'text'); + + texture.orig = new _math.Rectangle(); + texture.trim = new _math.Rectangle(); + + // base texture is already automatically added to the cache, now adding the actual texture + var _this = _possibleConstructorReturn(this, _Sprite.call(this, texture)); + + _Texture2.default.addToCache(_this._texture, _this._texture.baseTexture.textureCacheIds[0]); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.canvas = canvas; + + /** + * The canvas 2d context that everything is drawn with + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.canvas.getContext('2d'); + + /** + * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. + * @member {number} + * @default 1 + */ + _this.resolution = _settings2.default.RESOLUTION; + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = null; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._style = null; + /** + * Private listener to track style changes. + * + * @member {Function} + * @private + */ + _this._styleListener = null; + + /** + * Private tracker for the current font. + * + * @member {string} + * @private + */ + _this._font = ''; + + _this.text = text; + _this.style = style; + + _this.localStyleID = -1; + return _this; + } + + /** + * Renders text and updates it when needed. + * + * @private + * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. + */ + + + Text.prototype.updateText = function updateText(respectDirty) { + var style = this._style; + + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + + if (!this.dirty && respectDirty) { + return; + } + + this._font = this._style.toFontString(); + + var context = this.context; + var measured = _TextMetrics2.default.measureText(this._text, this._style, this._style.wordWrap, this.canvas); + var width = measured.width; + var height = measured.height; + var lines = measured.lines; + var lineHeight = measured.lineHeight; + var lineWidths = measured.lineWidths; + var maxLineWidth = measured.maxLineWidth; + var fontProperties = measured.fontProperties; + + this.canvas.width = Math.ceil((Math.max(1, width) + style.padding * 2) * this.resolution); + this.canvas.height = Math.ceil((Math.max(1, height) + style.padding * 2) * this.resolution); + + context.scale(this.resolution, this.resolution); + + context.clearRect(0, 0, this.canvas.width, this.canvas.height); + + context.font = this._font; + context.strokeStyle = style.stroke; + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + + var linePositionX = void 0; + var linePositionY = void 0; + + if (style.dropShadow) { + context.fillStyle = style.dropShadowColor; + context.globalAlpha = style.dropShadowAlpha; + context.shadowBlur = style.dropShadowBlur; + + if (style.dropShadowBlur > 0) { + context.shadowColor = style.dropShadowColor; + } + + var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + + for (var i = 0; i < lines.length; i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (style.fill) { + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); + + if (style.stroke && style.strokeThickness) { + context.strokeStyle = style.dropShadowColor; + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding, true); + context.strokeStyle = style.stroke; + } + } + } + } + + // reset the shadow blur and alpha that was set by the drop shadow, for the regular text + context.shadowBlur = 0; + context.globalAlpha = 1; + + // set canvas text styles + context.fillStyle = this._generateFillStyle(style, lines); + + // draw lines line by line + for (var _i = 0; _i < lines.length; _i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i]) / 2; + } + + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding, true); + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding); + } + } + + this.updateTexture(); + }; + + /** + * Render the text with letter-spacing. + * @param {string} text - The text to draw + * @param {number} x - Horizontal position to draw the text + * @param {number} y - Vertical position to draw the text + * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + * @private + */ + + + Text.prototype.drawLetterSpacing = function drawLetterSpacing(text, x, y) { + var isStroke = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var style = this._style; + + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + + if (letterSpacing === 0) { + if (isStroke) { + this.context.strokeText(text, x, y); + } else { + this.context.fillText(text, x, y); + } + + return; + } + + var characters = String.prototype.split.call(text, ''); + var currentPosition = x; + var index = 0; + var current = ''; + + while (index < text.length) { + current = characters[index++]; + if (isStroke) { + this.context.strokeText(current, currentPosition, y); + } else { + this.context.fillText(current, currentPosition, y); + } + currentPosition += this.context.measureText(current).width + letterSpacing; + } + }; + + /** + * Updates texture size based on canvas size + * + * @private + */ + + + Text.prototype.updateTexture = function updateTexture() { + var canvas = this.canvas; + + if (this._style.trim) { + var trimmed = (0, _trimCanvas2.default)(canvas); + + canvas.width = trimmed.width; + canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } + + var texture = this._texture; + var style = this._style; + var padding = style.trim ? 0 : style.padding; + var baseTexture = texture.baseTexture; + + baseTexture.hasLoaded = true; + baseTexture.resolution = this.resolution; + + baseTexture.realWidth = canvas.width; + baseTexture.realHeight = canvas.height; + baseTexture.width = canvas.width / this.resolution; + baseTexture.height = canvas.height / this.resolution; + + texture.trim.width = texture._frame.width = canvas.width / this.resolution; + texture.trim.height = texture._frame.height = canvas.height / this.resolution; + texture.trim.x = -padding; + texture.trim.y = -padding; + + texture.orig.width = texture._frame.width - padding * 2; + texture.orig.height = texture._frame.height - padding * 2; + + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + + baseTexture.emit('update', baseTexture); + + this.dirty = false; + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Text.prototype.renderWebGL = function renderWebGL(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype.renderWebGL.call(this, renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Text.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype._renderCanvas.call(this, renderer); + }; + + /** + * Gets the local bounds of the text object. + * + * @param {Rectangle} rect - The output rectangle. + * @return {Rectangle} The bounds. + */ + + + Text.prototype.getLocalBounds = function getLocalBounds(rect) { + this.updateText(true); + + return _Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + */ + + + Text.prototype._calculateBounds = function _calculateBounds() { + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; + + /** + * Method to be called upon a TextStyle change. + * @private + */ + + + Text.prototype._onStyleChange = function _onStyleChange() { + this.dirty = true; + }; + + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * + * @private + * @param {object} style - The style. + * @param {string[]} lines - The lines of text. + * @return {string|number|CanvasGradient} The fill style + */ + + + Text.prototype._generateFillStyle = function _generateFillStyle(style, lines) { + if (!Array.isArray(style.fill)) { + return style.fill; + } + + // cocoon on canvas+ cannot generate textures, so use the first colour instead + if (navigator.isCocoonJS) { + return style.fill[0]; + } + + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient = void 0; + var totalIterations = void 0; + var currentIteration = void 0; + var stop = void 0; + + var width = this.canvas.width / this.resolution; + var height = this.canvas.height / this.resolution; + + // make a copy of the style settings, so we can manipulate them later + var fill = style.fill.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(style.fill[0]); + fillGradientStops.unshift(0); + + fill.push(style.fill[style.fill.length - 1]); + fillGradientStops.push(1); + + if (style.fillGradientType === _const.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); + + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + totalIterations = (fill.length + 1) * lines.length; + currentIteration = 0; + for (var _i2 = 0; _i2 < lines.length; _i2++) { + currentIteration += 1; + for (var j = 0; j < fill.length; j++) { + if (typeof fillGradientStops[j] === 'number') { + stop = fillGradientStops[j] / lines.length + _i2 / lines.length; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[j]); + currentIteration++; + } + } + } else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); + + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + totalIterations = fill.length + 1; + currentIteration = 1; + + for (var _i3 = 0; _i3 < fill.length; _i3++) { + if (typeof fillGradientStops[_i3] === 'number') { + stop = fillGradientStops[_i3]; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[_i3]); + currentIteration++; + } + } + + return gradient; + }; + + /** + * Destroys this text object. + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majority of the time the texture will not be shared with any other Sprites. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well + */ + + + Text.prototype.destroy = function destroy(options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + + options = Object.assign({}, defaultDestroyOptions, options); + + _Sprite.prototype.destroy.call(this, options); + + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + + this._style = null; + }; + + /** + * The width of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Text, [{ + key: 'width', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * Set the style of the text. Set up an event listener to listen for changes on the style + * object and mark the text as dirty. + * + * @member {object|PIXI.TextStyle} + */ + + }, { + key: 'style', + get: function get() { + return this._style; + }, + set: function set(style) // eslint-disable-line require-jsdoc + { + style = style || {}; + + if (style instanceof _TextStyle2.default) { + this._style = style; + } else { + this._style = new _TextStyle2.default(style); + } + + this.localStyleID = -1; + this.dirty = true; + } + + /** + * Set the copy for the text object. To split a line you can use '\n'. + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(text) // eslint-disable-line require-jsdoc + { + text = String(text === '' || text === null || text === undefined ? ' ' : text); + + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + } + }]); + + return Text; +}(_Sprite3.default); + +exports.default = Text; + +},{"../const":46,"../math":70,"../settings":101,"../sprites/Sprite":102,"../textures/Texture":115,"../utils":125,"../utils/trimCanvas":130,"./TextMetrics":109,"./TextStyle":110}],109:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The TextMetrics object represents the measurement of a block of text with a specified style. + * + * ```js + * let style = new PIXI.TextStyle({fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}) + * let textMetrics = PIXI.TextMetrics.measureText('Your text', style) + * ``` + * + * @class + * @memberOf PIXI + */ +var TextMetrics = function () { + /** + * @param {string} text - the text that was measured + * @param {PIXI.TextStyle} style - the style that was measured + * @param {number} width - the measured width of the text + * @param {number} height - the measured height of the text + * @param {array} lines - an array of the lines of text broken by new lines and wrapping if specified in style + * @param {array} lineWidths - an array of the line widths for each line matched to `lines` + * @param {number} lineHeight - the measured line height for this style + * @param {number} maxLineWidth - the maximum line width for all measured lines + * @param {Object} fontProperties - the font properties object from TextMetrics.measureFont + */ + function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) { + _classCallCheck(this, TextMetrics); + + this.text = text; + this.style = style; + this.width = width; + this.height = height; + this.lines = lines; + this.lineWidths = lineWidths; + this.lineHeight = lineHeight; + this.maxLineWidth = maxLineWidth; + this.fontProperties = fontProperties; + } + + /** + * Measures the supplied string of text and returns a Rectangle. + * + * @param {string} text - the text to measure. + * @param {PIXI.TextStyle} style - the text style to use for measuring + * @param {boolean} [wordWrap] - optional override for if word-wrap should be applied to the text. + * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. + * @return {PIXI.TextMetrics} measured width and height of the text. + */ + + + TextMetrics.measureText = function measureText(text, style, wordWrap) { + var canvas = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : TextMetrics._canvas; + + wordWrap = wordWrap || style.wordWrap; + var font = style.toFontString(); + var fontProperties = TextMetrics.measureFont(font); + var context = canvas.getContext('2d'); + + context.font = font; + + var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text; + var lines = outputText.split(/(?:\r\n|\r|\n)/); + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + + for (var i = 0; i < lines.length; i++) { + var lineWidth = context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing; + + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + var width = maxLineWidth + style.strokeThickness; + + if (style.dropShadow) { + width += style.dropShadowDistance; + } + + var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * (lineHeight + style.leading); + + if (style.dropShadow) { + height += style.dropShadowDistance; + } + + return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties); + }; + + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @private + * @param {string} text - String to apply word wrapping to + * @param {PIXI.TextStyle} style - the style to use when wrapping + * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. + * @return {string} New string with new lines applied where required + */ + + + TextMetrics.wordWrap = function wordWrap(text, style) { + var canvas = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : TextMetrics._canvas; + + var context = canvas.getContext('2d'); + + var width = 0; + var line = ''; + var lines = ''; + + var cache = {}; + var letterSpacing = style.letterSpacing, + whiteSpace = style.whiteSpace; + + // How to handle whitespaces + + var collapseSpaces = TextMetrics.collapseSpaces(whiteSpace); + var collapseNewlines = TextMetrics.collapseNewlines(whiteSpace); + + // whether or not spaces may be added to the beginning of lines + var canPrependSpaces = !collapseSpaces; + + // There is letterSpacing after every char except the last one + // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_! + // so for convenience the above needs to be compared to width + 1 extra letterSpace + // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_ + // ________________________________________________ + // And then the final space is simply no appended to each line + var wordWrapWidth = style.wordWrapWidth + letterSpacing; + + // break text into words, spaces and newline chars + var tokens = TextMetrics.tokenize(text); + + for (var i = 0; i < tokens.length; i++) { + // get the word, space or newlineChar + var token = tokens[i]; + + // if word is a new line + if (TextMetrics.isNewline(token)) { + // keep the new line + if (!collapseNewlines) { + lines += TextMetrics.addLine(line); + canPrependSpaces = !collapseSpaces; + line = ''; + width = 0; + continue; + } + + // if we should collapse new lines + // we simply convert it into a space + token = ' '; + } + + // if we should collapse repeated whitespaces + if (collapseSpaces) { + // check both this and the last tokens for spaces + var currIsBreakingSpace = TextMetrics.isBreakingSpace(token); + var lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]); + + if (currIsBreakingSpace && lastIsBreakingSpace) { + continue; + } + } + + // get word width from cache if possible + var tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context); + + // word is longer than desired bounds + if (tokenWidth > wordWrapWidth) { + // if we are not already at the beginning of a line + if (line !== '') { + // start newlines for overflow words + lines += TextMetrics.addLine(line); + line = ''; + width = 0; + } + + // break large word over multiple lines + if (TextMetrics.canBreakWords(token, style.breakWords)) { + // break word into characters + var characters = token.split(''); + + // loop the characters + for (var j = 0; j < characters.length; j++) { + var char = characters[j]; + + var k = 1; + // we are not at the end of the token + + while (characters[j + k]) { + var nextChar = characters[j + k]; + var lastChar = char[char.length - 1]; + + // should not split chars + if (!TextMetrics.canBreakChars(lastChar, nextChar, token, j, style.breakWords)) { + // combine chars & move forward one + char += nextChar; + } else { + break; + } + + k++; + } + + j += char.length - 1; + + var characterWidth = TextMetrics.getFromCache(char, letterSpacing, cache, context); + + if (characterWidth + width > wordWrapWidth) { + lines += TextMetrics.addLine(line); + canPrependSpaces = false; + line = ''; + width = 0; + } + + line += char; + width += characterWidth; + } + } + + // run word out of the bounds + else { + // if there are words in this line already + // finish that line and start a new one + if (line.length > 0) { + lines += TextMetrics.addLine(line); + line = ''; + width = 0; + } + + var isLastToken = i === tokens.length - 1; + + // give it its own line if it's not the end + lines += TextMetrics.addLine(token, !isLastToken); + canPrependSpaces = false; + line = ''; + width = 0; + } + } + + // word could fit + else { + // word won't fit because of existing words + // start a new line + if (tokenWidth + width > wordWrapWidth) { + // if its a space we don't want it + canPrependSpaces = false; + + // add a new line + lines += TextMetrics.addLine(line); + + // start a new line + line = ''; + width = 0; + } + + // don't add spaces to the beginning of lines + if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces) { + // add the word to the current line + line += token; + + // update width counter + width += tokenWidth; + } + } + } + + lines += TextMetrics.addLine(line, false); + + return lines; + }; + + /** + * Convienience function for logging each line added during the wordWrap + * method + * + * @private + * @param {string} line - The line of text to add + * @param {boolean} newLine - Add new line character to end + * @return {string} A formatted line + */ + + + TextMetrics.addLine = function addLine(line) { + var newLine = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + + line = TextMetrics.trimRight(line); + + line = newLine ? line + '\n' : line; + + return line; + }; + + /** + * Gets & sets the widths of calculated characters in a cache object + * + * @private + * @param {string} key The key + * @param {number} letterSpacing The letter spacing + * @param {object} cache The cache + * @param {CanvasRenderingContext2D} context The canvas context + * @return {number} The from cache. + */ + + + TextMetrics.getFromCache = function getFromCache(key, letterSpacing, cache, context) { + var width = cache[key]; + + if (width === undefined) { + var spacing = key.length * letterSpacing; + + width = context.measureText(key).width + spacing; + cache[key] = width; + } + + return width; + }; + + /** + * Determines whether we should collapse breaking spaces + * + * @private + * @param {string} whiteSpace The TextStyle property whiteSpace + * @return {boolean} should collapse + */ + + + TextMetrics.collapseSpaces = function collapseSpaces(whiteSpace) { + return whiteSpace === 'normal' || whiteSpace === 'pre-line'; + }; + + /** + * Determines whether we should collapse newLine chars + * + * @private + * @param {string} whiteSpace The white space + * @return {boolean} should collapse + */ + + + TextMetrics.collapseNewlines = function collapseNewlines(whiteSpace) { + return whiteSpace === 'normal'; + }; + + /** + * trims breaking whitespaces from string + * + * @private + * @param {string} text The text + * @return {string} trimmed string + */ + + + TextMetrics.trimRight = function trimRight(text) { + if (typeof text !== 'string') { + return ''; + } + + for (var i = text.length - 1; i >= 0; i--) { + var char = text[i]; + + if (!TextMetrics.isBreakingSpace(char)) { + break; + } + + text = text.slice(0, -1); + } + + return text; + }; + + /** + * Determines if char is a newline. + * + * @private + * @param {string} char The character + * @return {boolean} True if newline, False otherwise. + */ + + + TextMetrics.isNewline = function isNewline(char) { + if (typeof char !== 'string') { + return false; + } + + return TextMetrics._newlines.indexOf(char.charCodeAt(0)) >= 0; + }; + + /** + * Determines if char is a breaking whitespace. + * + * @private + * @param {string} char The character + * @return {boolean} True if whitespace, False otherwise. + */ + + + TextMetrics.isBreakingSpace = function isBreakingSpace(char) { + if (typeof char !== 'string') { + return false; + } + + return TextMetrics._breakingSpaces.indexOf(char.charCodeAt(0)) >= 0; + }; + + /** + * Splits a string into words, breaking-spaces and newLine characters + * + * @private + * @param {string} text The text + * @return {array} A tokenized array + */ + + + TextMetrics.tokenize = function tokenize(text) { + var tokens = []; + var token = ''; + + if (typeof text !== 'string') { + return tokens; + } + + for (var i = 0; i < text.length; i++) { + var char = text[i]; + + if (TextMetrics.isBreakingSpace(char) || TextMetrics.isNewline(char)) { + if (token !== '') { + tokens.push(token); + token = ''; + } + + tokens.push(char); + + continue; + } + + token += char; + } + + if (token !== '') { + tokens.push(token); + } + + return tokens; + }; + + /** + * This method exists to be easily overridden + * It allows one to customise which words should break + * Examples are if the token is CJK or numbers. + * It must return a boolean. + * + * @private + * @param {string} token The token + * @param {boolean} breakWords The style attr break words + * @return {boolean} whether to break word or not + */ + + + TextMetrics.canBreakWords = function canBreakWords(token, breakWords) { + return breakWords; + }; + + /** + * This method exists to be easily overridden + * It allows one to determine whether a pair of characters + * should be broken by newlines + * For example certain characters in CJK langs or numbers. + * It must return a boolean. + * + * @private + * @param {string} char The character + * @param {string} nextChar The next character + * @param {string} token The token/word the characters are from + * @param {number} index The index in the token of the char + * @param {boolean} breakWords The style attr break words + * @return {boolean} whether to break word or not + */ + + + TextMetrics.canBreakChars = function canBreakChars(char, nextChar, token, index, breakWords) // eslint-disable-line no-unused-vars + { + return true; + }; + + /** + * Calculates the ascent, descent and fontSize of a given font-style + * + * @static + * @param {string} font - String representing the style of the font + * @return {PIXI.TextMetrics~FontMetrics} Font properties object + */ + + + TextMetrics.measureFont = function measureFont(font) { + // as this method is used for preparing assets, don't recalculate things if we don't need to + if (TextMetrics._fonts[font]) { + return TextMetrics._fonts[font]; + } + + var properties = {}; + + var canvas = TextMetrics._canvas; + var context = TextMetrics._context; + + context.font = font; + + var metricsString = TextMetrics.METRICS_STRING + TextMetrics.BASELINE_SYMBOL; + var width = Math.ceil(context.measureText(metricsString).width); + var baseline = Math.ceil(context.measureText(TextMetrics.BASELINE_SYMBOL).width); + var height = 2 * baseline; + + baseline = baseline * TextMetrics.BASELINE_MULTIPLIER | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = font; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText(metricsString, 0, baseline); + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i = 0; + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } else { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var _j = 0; _j < line; _j += 4) { + if (imagedata[idx + _j] !== 255) { + stop = true; + break; + } + } + + if (!stop) { + idx -= line; + } else { + break; + } + } + + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + + TextMetrics._fonts[font] = properties; + + return properties; + }; + + /** + * Clear font metrics in metrics cache. + * + * @static + * @param {string} [font] - font name. If font name not set then clear cache for all fonts. + */ + + + TextMetrics.clearMetrics = function clearMetrics() { + var font = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + + if (font) { + delete TextMetrics._fonts[font]; + } else { + TextMetrics._fonts = {}; + } + }; + + return TextMetrics; +}(); + +/** + * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}. + * @class FontMetrics + * @memberof PIXI.TextMetrics~ + * @property {number} ascent - The ascent distance + * @property {number} descent - The descent distance + * @property {number} fontSize - Font size from ascent to descent + */ + +exports.default = TextMetrics; +var canvas = document.createElement('canvas'); + +canvas.width = canvas.height = 10; + +/** + * Cached canvas element for measuring text + * @memberof PIXI.TextMetrics + * @type {HTMLCanvasElement} + * @private + */ +TextMetrics._canvas = canvas; + +/** + * Cache for context to use. + * @memberof PIXI.TextMetrics + * @type {CanvasRenderingContext2D} + * @private + */ +TextMetrics._context = canvas.getContext('2d'); + +/** + * Cache of PIXI.TextMetrics~FontMetrics objects. + * @memberof PIXI.TextMetrics + * @type {Object} + * @private + */ +TextMetrics._fonts = {}; + +/** + * String used for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name METRICS_STRING + * @type {string} + * @default |Éq + */ +TextMetrics.METRICS_STRING = '|Éq'; + +/** + * Baseline symbol for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name BASELINE_SYMBOL + * @type {string} + * @default M + */ +TextMetrics.BASELINE_SYMBOL = 'M'; + +/** + * Baseline multiplier for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name BASELINE_MULTIPLIER + * @type {number} + * @default 1.4 + */ +TextMetrics.BASELINE_MULTIPLIER = 1.4; + +/** + * Cache of new line chars. + * @memberof PIXI.TextMetrics + * @type {number[]} + * @private + */ +TextMetrics._newlines = [0x000A, // line feed +0x000D]; + +/** + * Cache of breaking spaces. + * @memberof PIXI.TextMetrics + * @type {number[]} + * @private + */ +TextMetrics._breakingSpaces = [0x0009, // character tabulation +0x0020, // space +0x2000, // en quad +0x2001, // em quad +0x2002, // en space +0x2003, // em space +0x2004, // three-per-em space +0x2005, // four-per-em space +0x2006, // six-per-em space +0x2008, // punctuation space +0x2009, // thin space +0x200A, // hair space +0x205F, // medium mathematical space +0x3000]; + +},{}],110:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // disabling eslint for now, going to rewrite this in v5 +/* eslint-disable */ + +var _const = require('../const'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: 'black', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: _const.TEXT_GRADIENT.LINEAR_VERTICAL, + fillGradientStops: [], + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + trim: false, + whiteSpace: 'pre', + wordWrap: false, + wordWrapWidth: 100, + leading: 0 +}; + +/** + * A TextStyle Object decorates a Text Object. It can be shared between + * multiple Text objects. Changing the style will update all text objects using it. + * + * @class + * @memberof PIXI + */ + +var TextStyle = function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string|number} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours + * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} + * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set + * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * @param {string|string[]} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', 800' or '900') + * @param {number} [style.leading=0] - The space between lines + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Possible values "miter" (creates a sharp corner), "round" (creates a round corner) or "bevel" + * (creates a squared corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {boolean} [style.trim=false] - Trim transparent borders + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {boolean} [style.whiteSpace='pre'] - Determines whether newlines & spaces are collapsed or preserved "normal" + * (collapse, collapse), "pre" (preserve, preserve) | "pre-line" (preserve, collapse). It needs wordWrap to be set to true + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + _classCallCheck(this, TextStyle); + + this.styleID = 0; + + this.reset(); + + deepCopyProperties(this, style, style); + } + + /** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return {PIXI.TextStyle} New cloned TextStyle object + */ + + + TextStyle.prototype.clone = function clone() { + var clonedProperties = {}; + + deepCopyProperties(clonedProperties, this, defaultStyle); + + return new TextStyle(clonedProperties); + }; + + /** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ + + + TextStyle.prototype.reset = function reset() { + deepCopyProperties(this, defaultStyle, defaultStyle); + }; + + /** + * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text + * + * @member {string} + */ + + + /** + * Generates a font style string to use for `TextMetrics.measureFont()`. + * + * @return {string} Font style string, for passing to `TextMetrics.measureFont()` + */ + TextStyle.prototype.toFontString = function toFontString() { + // build canvas api font setting from individual components. Convert a numeric this.fontSize to px + var fontSizeString = typeof this.fontSize === 'number' ? this.fontSize + 'px' : this.fontSize; + + // Clean-up fontFamily property by quoting each font name + // this will support font names with spaces + var fontFamilies = this.fontFamily; + + if (!Array.isArray(this.fontFamily)) { + fontFamilies = this.fontFamily.split(','); + } + + for (var i = fontFamilies.length - 1; i >= 0; i--) { + // Trim any extra white-space + var fontFamily = fontFamilies[i].trim(); + + // Check if font already contains strings + if (!/([\"\'])[^\'\"]+\1/.test(fontFamily)) { + fontFamily = '"' + fontFamily + '"'; + } + fontFamilies[i] = fontFamily; + } + + return this.fontStyle + ' ' + this.fontVariant + ' ' + this.fontWeight + ' ' + fontSizeString + ' ' + fontFamilies.join(','); + }; + + _createClass(TextStyle, [{ + key: 'align', + get: function get() { + return this._align; + }, + set: function set(align) // eslint-disable-line require-jsdoc + { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + } + + /** + * Indicates if lines can be wrapped within words, it needs wordWrap to be set to true + * + * @member {boolean} + */ + + }, { + key: 'breakWords', + get: function get() { + return this._breakWords; + }, + set: function set(breakWords) // eslint-disable-line require-jsdoc + { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + } + + /** + * Set a drop shadow for the text + * + * @member {boolean} + */ + + }, { + key: 'dropShadow', + get: function get() { + return this._dropShadow; + }, + set: function set(dropShadow) // eslint-disable-line require-jsdoc + { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + } + + /** + * Set alpha for the drop shadow + * + * @member {number} + */ + + }, { + key: 'dropShadowAlpha', + get: function get() { + return this._dropShadowAlpha; + }, + set: function set(dropShadowAlpha) // eslint-disable-line require-jsdoc + { + if (this._dropShadowAlpha !== dropShadowAlpha) { + this._dropShadowAlpha = dropShadowAlpha; + this.styleID++; + } + } + + /** + * Set a angle of the drop shadow + * + * @member {number} + */ + + }, { + key: 'dropShadowAngle', + get: function get() { + return this._dropShadowAngle; + }, + set: function set(dropShadowAngle) // eslint-disable-line require-jsdoc + { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + } + + /** + * Set a shadow blur radius + * + * @member {number} + */ + + }, { + key: 'dropShadowBlur', + get: function get() { + return this._dropShadowBlur; + }, + set: function set(dropShadowBlur) // eslint-disable-line require-jsdoc + { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + } + + /** + * A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * + * @member {string|number} + */ + + }, { + key: 'dropShadowColor', + get: function get() { + return this._dropShadowColor; + }, + set: function set(dropShadowColor) // eslint-disable-line require-jsdoc + { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + } + + /** + * Set a distance of the drop shadow + * + * @member {number} + */ + + }, { + key: 'dropShadowDistance', + get: function get() { + return this._dropShadowDistance; + }, + set: function set(dropShadowDistance) // eslint-disable-line require-jsdoc + { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + } + + /** + * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'. + * Can be an array to create a gradient eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * + * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern} + */ + + }, { + key: 'fill', + get: function get() { + return this._fill; + }, + set: function set(fill) // eslint-disable-line require-jsdoc + { + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + } + + /** + * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient. + * See {@link PIXI.TEXT_GRADIENT} + * + * @member {number} + */ + + }, { + key: 'fillGradientType', + get: function get() { + return this._fillGradientType; + }, + set: function set(fillGradientType) // eslint-disable-line require-jsdoc + { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + } + + /** + * If fill is an array of colours to create a gradient, this array can set the stop points + * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * + * @member {number[]} + */ + + }, { + key: 'fillGradientStops', + get: function get() { + return this._fillGradientStops; + }, + set: function set(fillGradientStops) // eslint-disable-line require-jsdoc + { + if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { + this._fillGradientStops = fillGradientStops; + this.styleID++; + } + } + + /** + * The font family + * + * @member {string|string[]} + */ + + }, { + key: 'fontFamily', + get: function get() { + return this._fontFamily; + }, + set: function set(fontFamily) // eslint-disable-line require-jsdoc + { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + } + + /** + * The font size + * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em') + * + * @member {number|string} + */ + + }, { + key: 'fontSize', + get: function get() { + return this._fontSize; + }, + set: function set(fontSize) // eslint-disable-line require-jsdoc + { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + } + + /** + * The font style + * ('normal', 'italic' or 'oblique') + * + * @member {string} + */ + + }, { + key: 'fontStyle', + get: function get() { + return this._fontStyle; + }, + set: function set(fontStyle) // eslint-disable-line require-jsdoc + { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + } + + /** + * The font variant + * ('normal' or 'small-caps') + * + * @member {string} + */ + + }, { + key: 'fontVariant', + get: function get() { + return this._fontVariant; + }, + set: function set(fontVariant) // eslint-disable-line require-jsdoc + { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + } + + /** + * The font weight + * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900') + * + * @member {string} + */ + + }, { + key: 'fontWeight', + get: function get() { + return this._fontWeight; + }, + set: function set(fontWeight) // eslint-disable-line require-jsdoc + { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + } + + /** + * The amount of spacing between letters, default is 0 + * + * @member {number} + */ + + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(letterSpacing) // eslint-disable-line require-jsdoc + { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + } + + /** + * The line height, a number that represents the vertical space that a letter uses + * + * @member {number} + */ + + }, { + key: 'lineHeight', + get: function get() { + return this._lineHeight; + }, + set: function set(lineHeight) // eslint-disable-line require-jsdoc + { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + } + + /** + * The space between lines + * + * @member {number} + */ + + }, { + key: 'leading', + get: function get() { + return this._leading; + }, + set: function set(leading) // eslint-disable-line require-jsdoc + { + if (this._leading !== leading) { + this._leading = leading; + this.styleID++; + } + } + + /** + * The lineJoin property sets the type of corner created, it can resolve spiked text issues. + * Default is 'miter' (creates a sharp corner). + * + * @member {string} + */ + + }, { + key: 'lineJoin', + get: function get() { + return this._lineJoin; + }, + set: function set(lineJoin) // eslint-disable-line require-jsdoc + { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + } + + /** + * The miter limit to use when using the 'miter' lineJoin mode + * This can reduce or increase the spikiness of rendered text. + * + * @member {number} + */ + + }, { + key: 'miterLimit', + get: function get() { + return this._miterLimit; + }, + set: function set(miterLimit) // eslint-disable-line require-jsdoc + { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + } + + /** + * Occasionally some fonts are cropped. Adding some padding will prevent this from happening + * by adding padding to all sides of the text. + * + * @member {number} + */ + + }, { + key: 'padding', + get: function get() { + return this._padding; + }, + set: function set(padding) // eslint-disable-line require-jsdoc + { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + } + + /** + * A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * + * @member {string|number} + */ + + }, { + key: 'stroke', + get: function get() { + return this._stroke; + }, + set: function set(stroke) // eslint-disable-line require-jsdoc + { + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + } + + /** + * A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * + * @member {number} + */ + + }, { + key: 'strokeThickness', + get: function get() { + return this._strokeThickness; + }, + set: function set(strokeThickness) // eslint-disable-line require-jsdoc + { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + } + + /** + * The baseline of the text that is rendered. + * + * @member {string} + */ + + }, { + key: 'textBaseline', + get: function get() { + return this._textBaseline; + }, + set: function set(textBaseline) // eslint-disable-line require-jsdoc + { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + } + + /** + * Trim transparent borders + * + * @member {boolean} + */ + + }, { + key: 'trim', + get: function get() { + return this._trim; + }, + set: function set(trim) // eslint-disable-line require-jsdoc + { + if (this._trim !== trim) { + this._trim = trim; + this.styleID++; + } + } + + /** + * How newlines and spaces should be handled. + * Default is 'pre' (preserve, preserve). + * + * value | New lines | Spaces + * --- | --- | --- + * 'normal' | Collapse | Collapse + * 'pre' | Preserve | Preserve + * 'pre-line' | Preserve | Collapse + * + * @member {string} + */ + + }, { + key: 'whiteSpace', + get: function get() { + return this._whiteSpace; + }, + set: function set(whiteSpace) // eslint-disable-line require-jsdoc + { + if (this._whiteSpace !== whiteSpace) { + this._whiteSpace = whiteSpace; + this.styleID++; + } + } + + /** + * Indicates if word wrap should be used + * + * @member {boolean} + */ + + }, { + key: 'wordWrap', + get: function get() { + return this._wordWrap; + }, + set: function set(wordWrap) // eslint-disable-line require-jsdoc + { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + } + + /** + * The width at which text will wrap, it needs wordWrap to be set to true + * + * @member {number} + */ + + }, { + key: 'wordWrapWidth', + get: function get() { + return this._wordWrapWidth; + }, + set: function set(wordWrapWidth) // eslint-disable-line require-jsdoc + { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + } + }]); + + return TextStyle; +}(); + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * @private + * @param {number|number[]} color + * @return {string} The color as a string. + */ + + +exports.default = TextStyle; +function getSingleColor(color) { + if (typeof color === 'number') { + return (0, _utils.hex2string)(color); + } else if (typeof color === 'string') { + if (color.indexOf('0x') === 0) { + color = color.replace('0x', '#'); + } + } + + return color; +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * @private + * @param {number|number[]} color + * @return {string} The color as a string. + */ +function getColor(color) { + if (!Array.isArray(color)) { + return getSingleColor(color); + } else { + for (var i = 0; i < color.length; ++i) { + color[i] = getSingleColor(color[i]); + } + + return color; + } +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * @private + * @param {Array} array1 First array to compare + * @param {Array} array2 Second array to compare + * @return {boolean} Do the arrays contain the same values in the same order + */ +function areArraysEqual(array1, array2) { + if (!Array.isArray(array1) || !Array.isArray(array2)) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } + + return true; +} + +/** + * Utility function to ensure that object properties are copied by value, and not by reference + * @private + * @param {Object} target Target object to copy properties into + * @param {Object} source Source object for the proporties to copy + * @param {string} propertyObj Object containing properties names we want to loop over + */ +function deepCopyProperties(target, source, propertyObj) { + for (var prop in propertyObj) { + if (Array.isArray(source[prop])) { + target[prop] = source[prop].slice(); + } else { + target[prop] = source[prop]; + } + } +} + +},{"../const":46,"../utils":125}],111:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let baseRenderTexture = new PIXI.BaseRenderTexture(renderer, 800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * baseRenderTexture.render(sprite); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let baseRenderTexture = new PIXI.BaseRenderTexture(100, 100); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var BaseRenderTexture = function (_BaseTexture) { + _inherits(BaseRenderTexture, _BaseTexture); + + /** + * @param {number} [width=100] - The width of the base render texture + * @param {number} [height=100] - The height of the base render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + */ + function BaseRenderTexture() { + var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + + _classCallCheck(this, BaseRenderTexture); + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, null, scaleMode)); + + _this.resolution = resolution || _settings2.default.RESOLUTION; + + _this.width = Math.ceil(width); + _this.height = Math.ceil(height); + + _this.realWidth = _this.width * _this.resolution; + _this.realHeight = _this.height * _this.resolution; + + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + _this.hasLoaded = true; + + /** + * A map of renderer IDs to webgl renderTargets + * + * @private + * @member {object} + */ + _this._glRenderTargets = {}; + + /** + * A reference to the canvas render target (we only need one as this can be shared across renderers) + * + * @private + * @member {object} + */ + _this._canvasRenderTarget = null; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + return _this; + } + + /** + * Resizes the BaseRenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + */ + + + BaseRenderTexture.prototype.resize = function resize(width, height) { + width = Math.ceil(width); + height = Math.ceil(height); + + if (width === this.width && height === this.height) { + return; + } + + this.valid = width > 0 && height > 0; + + this.width = width; + this.height = height; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + if (!this.valid) { + return; + } + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + */ + + + BaseRenderTexture.prototype.destroy = function destroy() { + _BaseTexture.prototype.destroy.call(this, true); + this.renderer = null; + }; + + return BaseRenderTexture; +}(_BaseTexture3.default); + +exports.default = BaseRenderTexture; + +},{"../settings":101,"./BaseTexture":112}],112:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var BaseTexture = function (_EventEmitter) { + _inherits(BaseTexture, _EventEmitter); + + /** + * @param {HTMLImageElement|HTMLCanvasElement} [source] - the source object of the texture. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture + */ + function BaseTexture(source, scaleMode, resolution) { + _classCallCheck(this, BaseTexture); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.uid = (0, _utils.uid)(); + + _this.touched = 0; + + /** + * The resolution / device pixel ratio of the texture + * + * @member {number} + * @default 1 + */ + _this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The width of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.width = 100; + + /** + * The height of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.height = 100; + + // TODO docs + // used to store the actual dimensions of the source + /** + * Used to store the actual width of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realWidth = 100; + /** + * Used to store the actual height of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realHeight = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Set to true once the base texture has successfully loaded. + * + * This is never true if the underlying source fails to load or has no texture data. + * + * @readonly + * @member {boolean} + */ + _this.hasLoaded = false; + + /** + * Set to true if the source is currently loading. + * + * If an Image source is loading the 'loaded' or 'error' event will be + * dispatched when the operation ends. An underyling source that is + * immediately-available bypasses loading entirely. + * + * @readonly + * @member {boolean} + */ + _this.isLoading = false; + + /** + * The image source that is used to create the texture. + * + * TODO: Make this a setter that calls loadSource(); + * + * @readonly + * @member {HTMLImageElement|HTMLCanvasElement} + */ + _this.source = null; // set in loadSource, if at all + + /** + * The image source that is used to create the texture. This is used to + * store the original Svg source when it is replaced with a canvas element. + * + * TODO: Currently not in use but could be used when re-scaling svg. + * + * @readonly + * @member {Image} + */ + _this.origSource = null; // set in loadSvg, if at all + + /** + * Type of image defined in source, eg. `png` or `svg` + * + * @readonly + * @member {string} + */ + _this.imageType = null; // set in updateImageType + + /** + * Scale for source image. Used with Svg images to scale them before rasterization. + * + * @readonly + * @member {number} + */ + _this.sourceScale = 1.0; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * All blend modes, and shaders written for default value. Change it on your own risk. + * + * @member {boolean} + * @default true + */ + _this.premultipliedAlpha = true; + + /** + * The image url of the texture + * + * @member {string} + */ + _this.imageUrl = null; + + /** + * Whether or not the texture is a power of two, try to use power of two textures as much + * as you can + * + * @private + * @member {boolean} + */ + _this.isPowerOfTwo = false; + + // used for webGL + + /** + * + * Set this to true if a mipmap of this texture needs to be generated. This value needs + * to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @member {boolean} + * @see PIXI.MIPMAP_TEXTURES + */ + _this.mipmap = _settings2.default.MIPMAP_TEXTURES; + + /** + * + * WebGL Texture wrap mode + * + * @member {number} + * @see PIXI.WRAP_MODES + */ + _this.wrapMode = _settings2.default.WRAP_MODE; + + /** + * A map of renderer IDs to webgl textures + * + * @private + * @member {object} + */ + _this._glTextures = {}; + + _this._enabled = 0; + _this._virtalBoundId = -1; + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + + /** + * The ids under which this BaseTexture has been added to the base texture cache. This is + * automatically set as long as BaseTexture.addToCache is used, but may not be set if a + * BaseTexture is added directly to the BaseTextureCache array. + * + * @member {string[]} + */ + _this.textureCacheIds = []; + + // if no source passed don't try to load + if (source) { + _this.loadSource(source); + } + + /** + * Fired when a not-immediately-available source finishes loading. + * + * @protected + * @event PIXI.BaseTexture#loaded + * @param {PIXI.BaseTexture} baseTexture - Resource loaded. + */ + + /** + * Fired when a not-immediately-available source fails to load. + * + * @protected + * @event PIXI.BaseTexture#error + * @param {PIXI.BaseTexture} baseTexture - Resource errored. + */ + + /** + * Fired when BaseTexture is updated. + * + * @protected + * @event PIXI.BaseTexture#update + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. + */ + + /** + * Fired when BaseTexture is destroyed. + * + * @protected + * @event PIXI.BaseTexture#dispose + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. + */ + return _this; + } + + /** + * Updates the texture on all the webgl renderers, this also assumes the src has changed. + * + * @fires PIXI.BaseTexture#update + */ + + + BaseTexture.prototype.update = function update() { + // Svg size is handled during load + if (this.imageType !== 'svg') { + this.realWidth = this.source.naturalWidth || this.source.videoWidth || this.source.width; + this.realHeight = this.source.naturalHeight || this.source.videoHeight || this.source.height; + + this._updateDimensions(); + } + + this.emit('update', this); + }; + + /** + * Update dimensions from real values + */ + + + BaseTexture.prototype._updateDimensions = function _updateDimensions() { + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + this.isPowerOfTwo = _bitTwiddle2.default.isPow2(this.realWidth) && _bitTwiddle2.default.isPow2(this.realHeight); + }; + + /** + * Load a source. + * + * If the source is not-immediately-available, such as an image that needs to be + * downloaded, then the 'loaded' or 'error' event will be dispatched in the future + * and `hasLoaded` will remain false after this call. + * + * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: + * + * if (texture.hasLoaded) { + * // texture ready for use + * } else if (texture.isLoading) { + * // listen to 'loaded' and/or 'error' events on texture + * } else { + * // not loading, not going to load UNLESS the source is reloaded + * // (it may still make sense to listen to the events) + * } + * + * @protected + * @param {HTMLImageElement|HTMLCanvasElement} source - the source object of the texture. + */ + + + BaseTexture.prototype.loadSource = function loadSource(source) { + var wasLoading = this.isLoading; + + this.hasLoaded = false; + this.isLoading = false; + + if (wasLoading && this.source) { + this.source.onload = null; + this.source.onerror = null; + } + + var firstSourceLoaded = !this.source; + + this.source = source; + + // Apply source if loaded. Otherwise setup appropriate loading monitors. + if ((source.src && source.complete || source.getContext) && source.width && source.height) { + this._updateImageType(); + + if (this.imageType === 'svg') { + this._loadSvgSource(); + } else { + this._sourceLoaded(); + } + + if (firstSourceLoaded) { + // send loaded event if previous source was null and we have been passed a pre-loaded IMG element + this.emit('loaded', this); + } + } else if (!source.getContext) { + // Image fail / not ready + this.isLoading = true; + + var scope = this; + + source.onload = function () { + scope._updateImageType(); + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope._sourceLoaded(); + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + scope.emit('loaded', scope); + }; + + source.onerror = function () { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope.emit('error', scope); + }; + + // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element + // "The value of `complete` can thus change while a script is executing." + // So complete needs to be re-checked after the callbacks have been added.. + // NOTE: complete will be true if the image has no src so best to check if the src is set. + if (source.complete && source.src) { + // ..and if we're complete now, no need for callbacks + source.onload = null; + source.onerror = null; + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + this.isLoading = false; + + if (source.width && source.height) { + this._sourceLoaded(); + + // If any previous subscribers possible + if (wasLoading) { + this.emit('loaded', this); + } + } + // If any previous subscribers possible + else if (wasLoading) { + this.emit('error', this); + } + } + } + }; + + /** + * Updates type of the source image. + */ + + + BaseTexture.prototype._updateImageType = function _updateImageType() { + if (!this.imageUrl) { + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + var imageType = void 0; + + if (dataUri && dataUri.mediaType === 'image') { + // Check for subType validity + var firstSubType = dataUri.subType.split('+')[0]; + + imageType = (0, _utils.getUrlFileExtension)('.' + firstSubType); + + if (!imageType) { + throw new Error('Invalid image type in data URI.'); + } + } else { + imageType = (0, _utils.getUrlFileExtension)(this.imageUrl); + + if (!imageType) { + imageType = 'png'; + } + } + + this.imageType = imageType; + }; + + /** + * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls + * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. + */ + + + BaseTexture.prototype._loadSvgSource = function _loadSvgSource() { + if (this.imageType !== 'svg') { + // Do nothing if source is not svg + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + + if (dataUri) { + this._loadSvgSourceUsingDataUri(dataUri); + } else { + // We got an URL, so we need to do an XHR to check the svg size + this._loadSvgSourceUsingXhr(); + } + }; + + /** + * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`. + * + * @param {string} dataUri - The data uri to load from. + */ + + + BaseTexture.prototype._loadSvgSourceUsingDataUri = function _loadSvgSourceUsingDataUri(dataUri) { + var svgString = void 0; + + if (dataUri.encoding === 'base64') { + if (!atob) { + throw new Error('Your browser doesn\'t support base64 conversions.'); + } + svgString = atob(dataUri.data); + } else { + svgString = dataUri.data; + } + + this._loadSvgSourceUsingString(svgString); + }; + + /** + * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. + */ + + + BaseTexture.prototype._loadSvgSourceUsingXhr = function _loadSvgSourceUsingXhr() { + var _this2 = this; + + var svgXhr = new XMLHttpRequest(); + + // This throws error on IE, so SVG Document can't be used + // svgXhr.responseType = 'document'; + + // This is not needed since we load the svg as string (breaks IE too) + // but overrideMimeType() can be used to force the response to be parsed as XML + // svgXhr.overrideMimeType('image/svg+xml'); + + svgXhr.onload = function () { + if (svgXhr.readyState !== svgXhr.DONE || svgXhr.status !== 200) { + throw new Error('Failed to load SVG using XHR.'); + } + + _this2._loadSvgSourceUsingString(svgXhr.response); + }; + + svgXhr.onerror = function () { + return _this2.emit('error', _this2); + }; + + svgXhr.open('GET', this.imageUrl, true); + svgXhr.send(); + }; + + /** + * Loads texture using an SVG string. The original SVG Image is stored as `origSource` and the + * created canvas is the new `source`. The SVG is scaled using `sourceScale`. Called by + * `_loadSvgSourceUsingXhr` or `_loadSvgSourceUsingDataUri`. + * + * @param {string} svgString SVG source as string + * + * @fires PIXI.BaseTexture#loaded + */ + + + BaseTexture.prototype._loadSvgSourceUsingString = function _loadSvgSourceUsingString(svgString) { + var svgSize = (0, _utils.getSvgSize)(svgString); + + var svgWidth = svgSize.width; + var svgHeight = svgSize.height; + + if (!svgWidth || !svgHeight) { + throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); + } + + // Scale realWidth and realHeight + this.realWidth = Math.round(svgWidth * this.sourceScale); + this.realHeight = Math.round(svgHeight * this.sourceScale); + + this._updateDimensions(); + + // Create a canvas element + var canvas = document.createElement('canvas'); + + canvas.width = this.realWidth; + canvas.height = this.realHeight; + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + + // Draw the Svg to the canvas + canvas.getContext('2d').drawImage(this.source, 0, 0, svgWidth, svgHeight, 0, 0, this.realWidth, this.realHeight); + + // Replace the original source image with the canvas + this.origSource = this.source; + this.source = canvas; + + // Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`) + BaseTexture.addToCache(this, canvas._pixiId); + + this.isLoading = false; + this._sourceLoaded(); + this.emit('loaded', this); + }; + + /** + * Used internally to update the width, height, and some other tracking vars once + * a source has successfully loaded. + * + * @private + */ + + + BaseTexture.prototype._sourceLoaded = function _sourceLoaded() { + this.hasLoaded = true; + this.update(); + }; + + /** + * Destroys this base texture + * + */ + + + BaseTexture.prototype.destroy = function destroy() { + if (this.imageUrl) { + delete _utils.TextureCache[this.imageUrl]; + + this.imageUrl = null; + + if (!navigator.isCocoonJS) { + this.source.src = ''; + } + } + + this.source = null; + + this.dispose(); + + BaseTexture.removeFromCache(this); + this.textureCacheIds = null; + + this._destroyed = true; + }; + + /** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + * @fires PIXI.BaseTexture#dispose + */ + + + BaseTexture.prototype.dispose = function dispose() { + this.emit('dispose', this); + }; + + /** + * Changes the source image of the texture. + * The original source must be an Image element. + * + * @param {string} newSrc - the path of the image + */ + + + BaseTexture.prototype.updateSourceImage = function updateSourceImage(newSrc) { + this.source.src = newSrc; + + this.loadSource(this.source); + }; + + /** + * Helper function that creates a base texture from the given image url. + * If the image is not in the base texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + // new Image() breaks tex loading in some versions of Chrome. + // See https://code.google.com/p/chromium/issues/detail?id=238071 + var image = new Image(); // document.createElement('img'); + + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + image.crossOrigin = (0, _determineCrossOrigin2.default)(imageUrl); + } else if (crossorigin) { + image.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; + } + + baseTexture = new BaseTexture(image, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + image.src = imageUrl; // Setting this triggers load + + BaseTexture.addToCache(baseTexture, imageUrl); + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @param {string} [origin='canvas'] - A string origin of who created the base texture + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode) { + var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; + + if (!canvas._pixiId) { + canvas._pixiId = origin + '_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[canvas._pixiId]; + + if (!baseTexture) { + baseTexture = new BaseTexture(canvas, scaleMode); + BaseTexture.addToCache(baseTexture, canvas._pixiId); + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture based on the source you provide. + * The source can be - image url, image element, canvas element. If the + * source is an image url or an image element and not in the base texture + * cache, it will be created and loaded. + * + * @static + * @param {string|HTMLImageElement|HTMLCanvasElement} source - The source to create base texture from. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.from = function from(source, scaleMode, sourceScale) { + if (typeof source === 'string') { + return BaseTexture.fromImage(source, undefined, scaleMode, sourceScale); + } else if (source instanceof HTMLImageElement) { + var imageUrl = source.src; + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + baseTexture = new BaseTexture(source, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + BaseTexture.addToCache(baseTexture, imageUrl); + } + + return baseTexture; + } else if (source instanceof HTMLCanvasElement) { + return BaseTexture.fromCanvas(source, scaleMode); + } + + // lets assume its a base texture! + return source; + }; + + /** + * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache. + * @param {string} id - The id that the BaseTexture will be stored against. + */ + + + BaseTexture.addToCache = function addToCache(baseTexture, id) { + if (id) { + if (baseTexture.textureCacheIds.indexOf(id) === -1) { + baseTexture.textureCacheIds.push(id); + } + + /* eslint-disable no-console */ + if (_utils.BaseTextureCache[id]) { + console.warn('BaseTexture added to the cache with an id [' + id + '] that already had an entry'); + } + /* eslint-enable no-console */ + + _utils.BaseTextureCache[id] = baseTexture; + } + }; + + /** + * Remove a BaseTexture from the global BaseTextureCache. + * + * @static + * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself. + * @return {PIXI.BaseTexture|null} The BaseTexture that was removed. + */ + + + BaseTexture.removeFromCache = function removeFromCache(baseTexture) { + if (typeof baseTexture === 'string') { + var baseTextureFromCache = _utils.BaseTextureCache[baseTexture]; + + if (baseTextureFromCache) { + var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); + + if (index > -1) { + baseTextureFromCache.textureCacheIds.splice(index, 1); + } + + delete _utils.BaseTextureCache[baseTexture]; + + return baseTextureFromCache; + } + } else if (baseTexture && baseTexture.textureCacheIds) { + for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { + delete _utils.BaseTextureCache[baseTexture.textureCacheIds[i]]; + } + + baseTexture.textureCacheIds.length = 0; + + return baseTexture; + } + + return null; + }; + + return BaseTexture; +}(_eventemitter2.default); + +exports.default = BaseTexture; + +},{"../settings":101,"../utils":125,"../utils/determineCrossOrigin":124,"bit-twiddle":1,"eventemitter3":3}],113:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseRenderTexture = require('./BaseRenderTexture'); + +var _BaseRenderTexture2 = _interopRequireDefault(_BaseRenderTexture); + +var _Texture2 = require('./Texture'); + +var _Texture3 = _interopRequireDefault(_Texture2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let renderTexture = PIXI.RenderTexture.create(800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let renderTexture = new PIXI.RenderTexture.create(100, 100); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.Texture + * @memberof PIXI + */ +var RenderTexture = function (_Texture) { + _inherits(RenderTexture, _Texture); + + /** + * @param {PIXI.BaseRenderTexture} baseRenderTexture - The renderer used for this RenderTexture + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + */ + function RenderTexture(baseRenderTexture, frame) { + _classCallCheck(this, RenderTexture); + + // support for legacy.. + var _legacyRenderer = null; + + if (!(baseRenderTexture instanceof _BaseRenderTexture2.default)) { + /* eslint-disable prefer-rest-params, no-console */ + var width = arguments[1]; + var height = arguments[2]; + var scaleMode = arguments[3]; + var resolution = arguments[4]; + + // we have an old render texture.. + console.warn('Please use RenderTexture.create(' + width + ', ' + height + ') instead of the ctor directly.'); + _legacyRenderer = arguments[0]; + /* eslint-enable prefer-rest-params, no-console */ + + frame = null; + baseRenderTexture = new _BaseRenderTexture2.default(width, height, scaleMode, resolution); + } + + /** + * The base texture object that this texture uses + * + * @member {BaseTexture} + */ + + var _this = _possibleConstructorReturn(this, _Texture.call(this, baseRenderTexture, frame)); + + _this.legacyRenderer = _legacyRenderer; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = true; + + _this._updateUvs(); + return _this; + } + + /** + * Resizes the RenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + * @param {boolean} doNotResizeBaseTexture - Should the baseTexture.width and height values be resized as well? + */ + + + RenderTexture.prototype.resize = function resize(width, height, doNotResizeBaseTexture) { + width = Math.ceil(width); + height = Math.ceil(height); + + // TODO - could be not required.. + this.valid = width > 0 && height > 0; + + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + + if (!doNotResizeBaseTexture) { + this.baseTexture.resize(width, height); + } + + this._updateUvs(); + }; + + /** + * A short hand way of creating a render texture. + * + * @param {number} [width=100] - The width of the render texture + * @param {number} [height=100] - The height of the render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.RenderTexture} The new render texture + */ + + + RenderTexture.create = function create(width, height, scaleMode, resolution) { + return new RenderTexture(new _BaseRenderTexture2.default(width, height, scaleMode, resolution)); + }; + + return RenderTexture; +}(_Texture3.default); + +exports.default = RenderTexture; + +},{"./BaseRenderTexture":111,"./Texture":115}],114:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _ = require('../'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Utility class for maintaining reference to a collection + * of Textures on a single Spritesheet. + * + * @class + * @memberof PIXI + */ +var Spritesheet = function () { + _createClass(Spritesheet, null, [{ + key: 'BATCH_SIZE', + + /** + * The maximum number of Textures to build per process. + * + * @type {number} + * @default 1000 + */ + get: function get() { + return 1000; + } + + /** + * @param {PIXI.BaseTexture} baseTexture Reference to the source BaseTexture object. + * @param {Object} data - Spritesheet image data. + * @param {string} [resolutionFilename] - The filename to consider when determining + * the resolution of the spritesheet. If not provided, the imageUrl will + * be used on the BaseTexture. + */ + + }]); + + function Spritesheet(baseTexture, data) { + var resolutionFilename = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + _classCallCheck(this, Spritesheet); + + /** + * Reference to ths source texture + * @type {PIXI.BaseTexture} + */ + this.baseTexture = baseTexture; + + /** + * Map of spritesheet textures. + * @type {Object} + */ + this.textures = {}; + + /** + * Reference to the original JSON data. + * @type {Object} + */ + this.data = data; + + /** + * The resolution of the spritesheet. + * @type {number} + */ + this.resolution = this._updateResolution(resolutionFilename || this.baseTexture.imageUrl); + + /** + * Map of spritesheet frames. + * @type {Object} + * @private + */ + this._frames = this.data.frames; + + /** + * Collection of frame names. + * @type {string[]} + * @private + */ + this._frameKeys = Object.keys(this._frames); + + /** + * Current batch index being processed. + * @type {number} + * @private + */ + this._batchIndex = 0; + + /** + * Callback when parse is completed. + * @type {Function} + * @private + */ + this._callback = null; + } + + /** + * Generate the resolution from the filename or fallback + * to the meta.scale field of the JSON data. + * + * @private + * @param {string} resolutionFilename - The filename to use for resolving + * the default resolution. + * @return {number} Resolution to use for spritesheet. + */ + + + Spritesheet.prototype._updateResolution = function _updateResolution(resolutionFilename) { + var scale = this.data.meta.scale; + + // Use a defaultValue of `null` to check if a url-based resolution is set + var resolution = (0, _utils.getResolutionOfUrl)(resolutionFilename, null); + + // No resolution found via URL + if (resolution === null) { + // Use the scale value or default to 1 + resolution = scale !== undefined ? parseFloat(scale) : 1; + } + + // For non-1 resolutions, update baseTexture + if (resolution !== 1) { + this.baseTexture.resolution = resolution; + this.baseTexture.update(); + } + + return resolution; + }; + + /** + * Parser spritesheet from loaded data. This is done asynchronously + * to prevent creating too many Texture within a single process. + * + * @param {Function} callback - Callback when complete returns + * a map of the Textures for this spritesheet. + */ + + + Spritesheet.prototype.parse = function parse(callback) { + this._batchIndex = 0; + this._callback = callback; + + if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) { + this._processFrames(0); + this._parseComplete(); + } else { + this._nextBatch(); + } + }; + + /** + * Process a batch of frames + * + * @private + * @param {number} initialFrameIndex - The index of frame to start. + */ + + + Spritesheet.prototype._processFrames = function _processFrames(initialFrameIndex) { + var frameIndex = initialFrameIndex; + var maxFrames = Spritesheet.BATCH_SIZE; + var sourceScale = this.baseTexture.sourceScale; + + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { + var i = this._frameKeys[frameIndex]; + var data = this._frames[i]; + var rect = data.frame; + + if (rect) { + var frame = null; + var trim = null; + var sourceSize = data.trimmed !== false && data.sourceSize ? data.sourceSize : data.frame; + + var orig = new _.Rectangle(0, 0, Math.floor(sourceSize.w * sourceScale) / this.resolution, Math.floor(sourceSize.h * sourceScale) / this.resolution); + + if (data.rotated) { + frame = new _.Rectangle(Math.floor(rect.x * sourceScale) / this.resolution, Math.floor(rect.y * sourceScale) / this.resolution, Math.floor(rect.h * sourceScale) / this.resolution, Math.floor(rect.w * sourceScale) / this.resolution); + } else { + frame = new _.Rectangle(Math.floor(rect.x * sourceScale) / this.resolution, Math.floor(rect.y * sourceScale) / this.resolution, Math.floor(rect.w * sourceScale) / this.resolution, Math.floor(rect.h * sourceScale) / this.resolution); + } + + // Check to see if the sprite is trimmed + if (data.trimmed !== false && data.spriteSourceSize) { + trim = new _.Rectangle(Math.floor(data.spriteSourceSize.x * sourceScale) / this.resolution, Math.floor(data.spriteSourceSize.y * sourceScale) / this.resolution, Math.floor(rect.w * sourceScale) / this.resolution, Math.floor(rect.h * sourceScale) / this.resolution); + } + + this.textures[i] = new _.Texture(this.baseTexture, frame, orig, trim, data.rotated ? 2 : 0); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage functions + _.Texture.addToCache(this.textures[i], i); + } + + frameIndex++; + } + }; + + /** + * The parse has completed. + * + * @private + */ + + + Spritesheet.prototype._parseComplete = function _parseComplete() { + var callback = this._callback; + + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); + }; + + /** + * Begin the next batch of textures. + * + * @private + */ + + + Spritesheet.prototype._nextBatch = function _nextBatch() { + var _this = this; + + this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); + this._batchIndex++; + setTimeout(function () { + if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { + _this._nextBatch(); + } else { + _this._parseComplete(); + } + }, 0); + }; + + /** + * Destroy Spritesheet and don't use after this. + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Spritesheet.prototype.destroy = function destroy() { + var destroyBase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + for (var i in this.textures) { + this.textures[i].destroy(); + } + this._frames = null; + this._frameKeys = null; + this.data = null; + this.textures = null; + if (destroyBase) { + this.baseTexture.destroy(); + } + this.baseTexture = null; + }; + + return Spritesheet; +}(); + +exports.default = Spritesheet; + +},{"../":65,"../utils":125}],115:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture = require('./BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _VideoBaseTexture = require('./VideoBaseTexture'); + +var _VideoBaseTexture2 = _interopRequireDefault(_VideoBaseTexture); + +var _TextureUvs = require('./TextureUvs'); + +var _TextureUvs2 = _interopRequireDefault(_TextureUvs); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided + * then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * let texture = PIXI.Texture.fromImage('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` + * + * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. + * You can check for this by checking the sprite's _textureID property. + * ```js + * var texture = PIXI.Texture.fromImage('assets/image.svg'); + * var sprite1 = new PIXI.Sprite(texture); + * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file + * ``` + * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var Texture = function (_EventEmitter) { + _inherits(Texture, _EventEmitter); + + /** + * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + * @param {PIXI.Rectangle} [orig] - The area of original texture + * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture + * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8} + */ + function Texture(baseTexture, frame, orig, trim, rotate) { + _classCallCheck(this, Texture); + + /** + * Does this Texture have any frame data assigned to it? + * + * @member {boolean} + */ + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.noFrame = false; + + if (!frame) { + _this.noFrame = true; + frame = new _math.Rectangle(0, 0, 1, 1); + } + + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @member {PIXI.BaseTexture} + */ + _this.baseTexture = baseTexture; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @member {PIXI.Rectangle} + */ + _this._frame = frame; + + /** + * This is the trimmed area of original texture, before it was put in atlas + * Please call `_updateUvs()` after you change coordinates of `trim` manually. + * + * @member {PIXI.Rectangle} + */ + _this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @member {boolean} + */ + _this.requiresUpdate = false; + + /** + * The WebGL UV data cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + _this._uvs = null; + + /** + * This is the area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + + _this._rotate = Number(rotate || 0); + + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); + } + + if (baseTexture.hasLoaded) { + if (_this.noFrame) { + frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + + // if there is no frame we should monitor for any base texture changes.. + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + _this.frame = frame; + } else { + baseTexture.once('loaded', _this.onBaseTextureLoaded, _this); + } + + /** + * Fired when the texture is updated. This happens if the frame or the baseTexture is updated. + * + * @event PIXI.Texture#update + * @protected + * @param {PIXI.Texture} texture - Instance of texture being updated. + */ + + _this._updateID = 0; + + /** + * Contains data for uvs. May contain clamp settings and some matrices. + * Its a bit heavy, so by default that object is not created. + * @type {PIXI.TextureMatrix} + * @default null + */ + _this.transform = null; + + /** + * The ids under which this Texture has been added to the texture cache. This is + * automatically set as long as Texture.addToCache is used, but may not be set if a + * Texture is added directly to the TextureCache array. + * + * @member {string[]} + */ + _this.textureCacheIds = []; + return _this; + } + + /** + * Updates this texture on the gpu. + * + */ + + + Texture.prototype.update = function update() { + this.baseTexture.update(); + }; + + /** + * Called when the base texture is loaded + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureLoaded = function onBaseTextureLoaded(baseTexture) { + this._updateID++; + + // TODO this code looks confusing.. boo to abusing getters and setters! + if (this.noFrame) { + this.frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } else { + this.frame = this._frame; + } + + this.baseTexture.on('update', this.onBaseTextureUpdated, this); + this.emit('update', this); + }; + + /** + * Called when the base texture is updated + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated(baseTexture) { + this._updateID++; + + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Texture.prototype.destroy = function destroy(destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destroyed too.. + if (_utils.TextureCache[this.baseTexture.imageUrl]) { + Texture.removeFromCache(this.baseTexture.imageUrl); + } + + this.baseTexture.destroy(); + } + + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); + + this.baseTexture = null; + } + + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + + this.valid = false; + + Texture.removeFromCache(this); + this.textureCacheIds = null; + }; + + /** + * Creates a new texture object that acts the same as this one. + * + * @return {PIXI.Texture} The new texture + */ + + + Texture.prototype.clone = function clone() { + return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); + }; + + /** + * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture. + */ + + + Texture.prototype._updateUvs = function _updateUvs() { + if (!this._uvs) { + this._uvs = new _TextureUvs2.default(); + } + + this._uvs.set(this._frame, this.baseTexture, this.rotate); + + this._updateID++; + }; + + /** + * Helper function that creates a Texture object from the given image url. + * If the image is not in the texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var texture = _utils.TextureCache[imageUrl]; + + if (!texture) { + texture = new Texture(_BaseTexture2.default.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); + Texture.addToCache(texture, imageUrl); + } + + return texture; + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return texture; + }; + + /** + * Helper function that creates a new Texture based on the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {string} [origin='canvas'] - A string origin of who created the base texture + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromCanvas = function fromCanvas(canvas, scaleMode) { + var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; + + return new Texture(_BaseTexture2.default.fromCanvas(canvas, scaleMode, origin)); + }; + + /** + * Helper function that creates a new Texture based on the given video element. + * + * @static + * @param {HTMLVideoElement|string} video - The URL or actual element of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideo = function fromVideo(video, scaleMode) { + if (typeof video === 'string') { + return Texture.fromVideoUrl(video, scaleMode); + } + + return new Texture(_VideoBaseTexture2.default.fromVideo(video, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the video url. + * + * @static + * @param {string} videoUrl - URL of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideoUrl = function fromVideoUrl(videoUrl, scaleMode) { + return new Texture(_VideoBaseTexture2.default.fromUrl(videoUrl, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} + * source - Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.from = function from(source) { + // TODO auto detect cross origin.. + // TODO pass in scale mode? + if (typeof source === 'string') { + var texture = _utils.TextureCache[source]; + + if (!texture) { + // check if its a video.. + var isVideo = source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/) !== null; + + if (isVideo) { + return Texture.fromVideoUrl(source); + } + + return Texture.fromImage(source); + } + + return texture; + } else if (source instanceof HTMLImageElement) { + return new Texture(_BaseTexture2.default.from(source)); + } else if (source instanceof HTMLCanvasElement) { + return Texture.fromCanvas(source, _settings2.default.SCALE_MODE, 'HTMLCanvasElement'); + } else if (source instanceof HTMLVideoElement) { + return Texture.fromVideo(source); + } else if (source instanceof _BaseTexture2.default) { + return new Texture(source); + } + + // lets assume its a texture! + return source; + }; + + /** + * Create a texture from a source and add to the cache. + * + * @static + * @param {HTMLImageElement|HTMLCanvasElement} source - The input source. + * @param {String} imageUrl - File name of texture, for cache and resolving resolution. + * @param {String} [name] - Human readible name for the texture cache. If no name is + * specified, only `imageUrl` will be used as the cache ID. + * @return {PIXI.Texture} Output texture + */ + + + Texture.fromLoader = function fromLoader(source, imageUrl, name) { + var baseTexture = new _BaseTexture2.default(source, undefined, (0, _utils.getResolutionOfUrl)(imageUrl)); + var texture = new Texture(baseTexture); + + baseTexture.imageUrl = imageUrl; + + // No name, use imageUrl instead + if (!name) { + name = imageUrl; + } + + // lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions + _BaseTexture2.default.addToCache(texture.baseTexture, name); + Texture.addToCache(texture, name); + + // also add references by url if they are different. + if (name !== imageUrl) { + _BaseTexture2.default.addToCache(texture.baseTexture, imageUrl); + Texture.addToCache(texture, imageUrl); + } + + return texture; + }; + + /** + * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the Texture will be stored against. + */ + + + Texture.addToCache = function addToCache(texture, id) { + if (id) { + if (texture.textureCacheIds.indexOf(id) === -1) { + texture.textureCacheIds.push(id); + } + + /* eslint-disable no-console */ + if (_utils.TextureCache[id]) { + console.warn('Texture added to the cache with an id [' + id + '] that already had an entry'); + } + /* eslint-enable no-console */ + + _utils.TextureCache[id] = texture; + } + }; + + /** + * Remove a Texture from the global TextureCache. + * + * @static + * @param {string|PIXI.Texture} texture - id of a Texture to be removed, or a Texture instance itself + * @return {PIXI.Texture|null} The Texture that was removed + */ + + + Texture.removeFromCache = function removeFromCache(texture) { + if (typeof texture === 'string') { + var textureFromCache = _utils.TextureCache[texture]; + + if (textureFromCache) { + var index = textureFromCache.textureCacheIds.indexOf(texture); + + if (index > -1) { + textureFromCache.textureCacheIds.splice(index, 1); + } + + delete _utils.TextureCache[texture]; + + return textureFromCache; + } + } else if (texture && texture.textureCacheIds) { + for (var i = 0; i < texture.textureCacheIds.length; ++i) { + // Check that texture matches the one being passed in before deleting it from the cache. + if (_utils.TextureCache[texture.textureCacheIds[i]] === texture) { + delete _utils.TextureCache[texture.textureCacheIds[i]]; + } + } + + texture.textureCacheIds.length = 0; + + return texture; + } + + return null; + }; + + /** + * The frame specifies the region of the base texture that this texture uses. + * Please call `_updateUvs()` after you change coordinates of `frame` manually. + * + * @member {PIXI.Rectangle} + */ + + + _createClass(Texture, [{ + key: 'frame', + get: function get() { + return this._frame; + }, + set: function set(frame) // eslint-disable-line require-jsdoc + { + this._frame = frame; + + this.noFrame = false; + + var x = frame.x, + y = frame.y, + width = frame.width, + height = frame.height; + + var xNotFit = x + width > this.baseTexture.width; + var yNotFit = y + height > this.baseTexture.height; + + if (xNotFit || yNotFit) { + var relationship = xNotFit && yNotFit ? 'and' : 'or'; + var errorX = 'X: ' + x + ' + ' + width + ' = ' + (x + width) + ' > ' + this.baseTexture.width; + var errorY = 'Y: ' + y + ' + ' + height + ' = ' + (y + height) + ' > ' + this.baseTexture.height; + + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + (errorX + ' ' + relationship + ' ' + errorY)); + } + + // this.valid = width && height && this.baseTexture.source && this.baseTexture.hasLoaded; + this.valid = width && height && this.baseTexture.hasLoaded; + + if (!this.trim && !this.rotate) { + this.orig = frame; + } + + if (this.valid) { + this._updateUvs(); + } + } + + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.GroupD8} for explanation + * + * @member {number} + */ + + }, { + key: 'rotate', + get: function get() { + return this._rotate; + }, + set: function set(rotate) // eslint-disable-line require-jsdoc + { + this._rotate = rotate; + if (this.valid) { + this._updateUvs(); + } + } + + /** + * The width of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'width', + get: function get() { + return this.orig.width; + } + + /** + * The height of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.orig.height; + } + }]); + + return Texture; +}(_eventemitter2.default); + +exports.default = Texture; + + +function createWhiteTexture() { + var canvas = document.createElement('canvas'); + + canvas.width = 10; + canvas.height = 10; + + var context = canvas.getContext('2d'); + + context.fillStyle = 'white'; + context.fillRect(0, 0, 10, 10); + + return new Texture(new _BaseTexture2.default(canvas)); +} + +function removeAllHandlers(tex) { + tex.destroy = function _emptyDestroy() {/* empty */}; + tex.on = function _emptyOn() {/* empty */}; + tex.once = function _emptyOnce() {/* empty */}; + tex.emit = function _emptyEmit() {/* empty */}; +} + +/** + * An empty texture, used often to not have to create multiple empty textures. + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.EMPTY = new Texture(new _BaseTexture2.default()); +removeAllHandlers(Texture.EMPTY); +removeAllHandlers(Texture.EMPTY.baseTexture); + +/** + * A white texture of 10x10 size, used for graphics and other things + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.WHITE = createWhiteTexture(); +removeAllHandlers(Texture.WHITE); +removeAllHandlers(Texture.WHITE.baseTexture); + +},{"../math":70,"../settings":101,"../utils":125,"./BaseTexture":112,"./TextureUvs":117,"./VideoBaseTexture":118,"eventemitter3":3}],116:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Matrix = require('../math/Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var tempMat = new _Matrix2.default(); + +/** + * Class controls uv transform and frame clamp for texture + * Can be used in Texture "transform" field, or separately, you can use different clamp settings on the same texture. + * If you want to add support for texture region of certain feature or filter, that's what you're looking for. + * + * @see PIXI.Texture + * @see PIXI.mesh.Mesh + * @see PIXI.extras.TilingSprite + * @class + * @memberof PIXI + */ + +var TextureMatrix = function () { + /** + * + * @param {PIXI.Texture} texture observed texture + * @param {number} [clampMargin] Changes frame clamping, 0.5 by default. Use -0.5 for extra border. + * @constructor + */ + function TextureMatrix(texture, clampMargin) { + _classCallCheck(this, TextureMatrix); + + this._texture = texture; + + this.mapCoord = new _Matrix2.default(); + + this.uClampFrame = new Float32Array(4); + + this.uClampOffset = new Float32Array(2); + + this._lastTextureID = -1; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders + * + * @default 0 + * @member {number} + */ + this.clampOffset = 0; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + this.clampMargin = typeof clampMargin === 'undefined' ? 0.5 : clampMargin; + } + + /** + * texture property + * @member {PIXI.Texture} + */ + + + /** + * Multiplies uvs array to transform + * @param {Float32Array} uvs mesh uvs + * @param {Float32Array} [out=uvs] output + * @returns {Float32Array} output + */ + TextureMatrix.prototype.multiplyUvs = function multiplyUvs(uvs, out) { + if (out === undefined) { + out = uvs; + } + + var mat = this.mapCoord; + + for (var i = 0; i < uvs.length; i += 2) { + var x = uvs[i]; + var y = uvs[i + 1]; + + out[i] = x * mat.a + y * mat.c + mat.tx; + out[i + 1] = x * mat.b + y * mat.d + mat.ty; + } + + return out; + }; + + /** + * updates matrices if texture was changed + * @param {boolean} forceUpdate if true, matrices will be updated any case + * @returns {boolean} whether or not it was updated + */ + + + TextureMatrix.prototype.update = function update(forceUpdate) { + var tex = this._texture; + + if (!tex || !tex.valid) { + return false; + } + + if (!forceUpdate && this._lastTextureID === tex._updateID) { + return false; + } + + this._lastTextureID = tex._updateID; + + var uvs = tex._uvs; + + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + + var orig = tex.orig; + var trim = tex.trim; + + if (trim) { + tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat); + } + + var texBase = tex.baseTexture; + var frame = this.uClampFrame; + var margin = this.clampMargin / texBase.resolution; + var offset = this.clampOffset; + + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.uClampOffset[0] = offset / texBase.realWidth; + this.uClampOffset[1] = offset / texBase.realHeight; + + return true; + }; + + _createClass(TextureMatrix, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._texture = value; + this._lastTextureID = -1; + } + }]); + + return TextureMatrix; +}(); + +exports.default = TextureMatrix; + +},{"../math/Matrix":67}],117:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _GroupD = require('../math/GroupD8'); + +var _GroupD2 = _interopRequireDefault(_GroupD); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A standard object to store the Uvs of a texture + * + * @class + * @private + * @memberof PIXI + */ +var TextureUvs = function () { + /** + * + */ + function TextureUvs() { + _classCallCheck(this, TextureUvs); + + this.x0 = 0; + this.y0 = 0; + + this.x1 = 1; + this.y1 = 0; + + this.x2 = 1; + this.y2 = 1; + + this.x3 = 0; + this.y3 = 1; + + this.uvsUint32 = new Uint32Array(4); + } + + /** + * Sets the texture Uvs based on the given frame information. + * + * @private + * @param {PIXI.Rectangle} frame - The frame of the texture + * @param {PIXI.Rectangle} baseFrame - The base frame of the texture + * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8} + */ + + + TextureUvs.prototype.set = function set(frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + + // coordinates of center + var cX = frame.x / tw + w2; + var cY = frame.y / th + h2; + + rotate = _GroupD2.default.add(rotate, _GroupD2.default.NW); // NW is top-left corner + this.x0 = cX + w2 * _GroupD2.default.uX(rotate); + this.y0 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + w2 * _GroupD2.default.uX(rotate); + this.y1 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x2 = cX + w2 * _GroupD2.default.uX(rotate); + this.y2 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x3 = cX + w2 * _GroupD2.default.uX(rotate); + this.y3 = cY + h2 * _GroupD2.default.uY(rotate); + } else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + + this.uvsUint32[0] = (this.y0 * 65535 & 0xFFFF) << 16 | this.x0 * 65535 & 0xFFFF; + this.uvsUint32[1] = (this.y1 * 65535 & 0xFFFF) << 16 | this.x1 * 65535 & 0xFFFF; + this.uvsUint32[2] = (this.y2 * 65535 & 0xFFFF) << 16 | this.x2 * 65535 & 0xFFFF; + this.uvsUint32[3] = (this.y3 * 65535 & 0xFFFF) << 16 | this.x3 * 65535 & 0xFFFF; + }; + + return TextureUvs; +}(); + +exports.default = TextureUvs; + +},{"../math/GroupD8":66}],118:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _utils = require('../utils'); + +var _ticker = require('../ticker'); + +var _const = require('../const'); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture of a [playing] Video. + * + * Video base textures mimic PixiJS BaseTexture.from.... method in their creation process. + * + * This can be used in several ways, such as: + * + * ```js + * let texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4'); + * + * let texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' }); + * + * let texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']); + * + * let texture = PIXI.VideoBaseTexture.fromUrls([ + * { src: '/video.webm', mime: 'video/webm' }, + * { src: '/video.mp4', mime: 'video/mp4' } + * ]); + * ``` + * + * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/). + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var VideoBaseTexture = function (_BaseTexture) { + _inherits(VideoBaseTexture, _BaseTexture); + + /** + * @param {HTMLVideoElement} source - Video source + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + */ + function VideoBaseTexture(source, scaleMode) { + _classCallCheck(this, VideoBaseTexture); + + if (!source) { + throw new Error('No video source element specified.'); + } + + // hook in here to check if video is already available. + // BaseTexture looks for a source.complete boolean, plus width & height. + + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + source.complete = true; + } + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, source, scaleMode)); + + _this.width = source.videoWidth; + _this.height = source.videoHeight; + + _this._autoUpdate = true; + _this._isAutoUpdating = false; + + /** + * When set to true will automatically play videos used by this texture once + * they are loaded. If false, it will not modify the playing state. + * + * @member {boolean} + * @default true + */ + _this.autoPlay = true; + + _this.update = _this.update.bind(_this); + _this._onCanPlay = _this._onCanPlay.bind(_this); + + source.addEventListener('play', _this._onPlayStart.bind(_this)); + source.addEventListener('pause', _this._onPlayStop.bind(_this)); + _this.hasLoaded = false; + _this.__loaded = false; + + if (!_this._isSourceReady()) { + source.addEventListener('canplay', _this._onCanPlay); + source.addEventListener('canplaythrough', _this._onCanPlay); + } else { + _this._onCanPlay(); + } + return _this; + } + + /** + * Returns true if the underlying source is playing. + * + * @private + * @return {boolean} True if playing. + */ + + + VideoBaseTexture.prototype._isSourcePlaying = function _isSourcePlaying() { + var source = this.source; + + return source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2; + }; + + /** + * Returns true if the underlying source is ready for playing. + * + * @private + * @return {boolean} True if ready. + */ + + + VideoBaseTexture.prototype._isSourceReady = function _isSourceReady() { + return this.source.readyState === 3 || this.source.readyState === 4; + }; + + /** + * Runs the update loop when the video is ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStart = function _onPlayStart() { + // Just in case the video has not received its can play even yet.. + if (!this.hasLoaded) { + this._onCanPlay(); + } + + if (!this._isAutoUpdating && this.autoUpdate) { + _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); + this._isAutoUpdating = true; + } + }; + + /** + * Fired when a pause event is triggered, stops the update loop + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStop = function _onPlayStop() { + if (this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } + }; + + /** + * Fired when the video is loaded and ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onCanPlay = function _onCanPlay() { + this.hasLoaded = true; + + if (this.source) { + this.source.removeEventListener('canplay', this._onCanPlay); + this.source.removeEventListener('canplaythrough', this._onCanPlay); + + this.width = this.source.videoWidth; + this.height = this.source.videoHeight; + + // prevent multiple loaded dispatches.. + if (!this.__loaded) { + this.__loaded = true; + this.emit('loaded', this); + } + + if (this._isSourcePlaying()) { + this._onPlayStart(); + } else if (this.autoPlay) { + this.source.play(); + } + } + }; + + /** + * Destroys this texture + * + */ + + + VideoBaseTexture.prototype.destroy = function destroy() { + if (this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + } + + if (this.source && this.source._pixiId) { + _BaseTexture3.default.removeFromCache(this.source._pixiId); + delete this.source._pixiId; + + this.source.pause(); + this.source.src = ''; + this.source.load(); + } + + _BaseTexture.prototype.destroy.call(this); + }; + + /** + * Mimic PixiJS BaseTexture.from.... method. + * + * @static + * @param {HTMLVideoElement} video - Video to create texture from + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromVideo = function fromVideo(video, scaleMode) { + if (!video._pixiId) { + video._pixiId = 'video_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[video._pixiId]; + + if (!baseTexture) { + baseTexture = new VideoBaseTexture(video, scaleMode); + _BaseTexture3.default.addToCache(baseTexture, video._pixiId); + } + + return baseTexture; + }; + + /** + * Helper function that creates a new BaseTexture based on the given video element. + * This BaseTexture can then be used to create a texture + * + * @static + * @param {string|object|string[]|object[]} videoSrc - The URL(s) for the video. + * @param {string} [videoSrc.src] - One of the source urls for the video + * @param {string} [videoSrc.mime] - The mimetype of the video (e.g. 'video/mp4'). If not specified + * the url's extension will be used as the second part of the mime type. + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromUrl = function fromUrl(videoSrc, scaleMode, crossorigin) { + var video = document.createElement('video'); + + video.setAttribute('webkit-playsinline', ''); + video.setAttribute('playsinline', ''); + + var url = Array.isArray(videoSrc) ? videoSrc[0].src || videoSrc[0] : videoSrc.src || videoSrc; + + if (crossorigin === undefined && url.indexOf('data:') !== 0) { + video.crossOrigin = (0, _determineCrossOrigin2.default)(url); + } else if (crossorigin) { + video.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; + } + + // array of objects or strings + if (Array.isArray(videoSrc)) { + for (var i = 0; i < videoSrc.length; ++i) { + video.appendChild(createSource(videoSrc[i].src || videoSrc[i], videoSrc[i].mime)); + } + } + // single object or string + else { + video.appendChild(createSource(url, videoSrc.mime)); + } + + video.load(); + + return VideoBaseTexture.fromVideo(video, scaleMode); + }; + + /** + * Should the base texture automatically update itself, set to true by default + * + * @member {boolean} + */ + + + _createClass(VideoBaseTexture, [{ + key: 'autoUpdate', + get: function get() { + return this._autoUpdate; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + + if (!this._autoUpdate && this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } else if (this._autoUpdate && !this._isAutoUpdating) { + _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); + this._isAutoUpdating = true; + } + } + } + }]); + + return VideoBaseTexture; +}(_BaseTexture3.default); + +exports.default = VideoBaseTexture; + + +VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; + +function createSource(path, type) { + if (!type) { + type = 'video/' + path.substr(path.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = path; + source.type = type; + + return source; +} + +},{"../const":46,"../ticker":121,"../utils":125,"../utils/determineCrossOrigin":124,"./BaseTexture":112}],119:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _const = require('../const'); + +var _TickerListener = require('./TickerListener'); + +var _TickerListener2 = _interopRequireDefault(_TickerListener); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A Ticker class that runs an update loop that other objects listen to. + * This class is composed around listeners + * meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, + * e.g. When the ticker is started and the emitter has listeners. + * + * @class + * @memberof PIXI.ticker + */ +var Ticker = function () { + /** + * + */ + function Ticker() { + var _this = this; + + _classCallCheck(this, Ticker); + + /** + * The first listener. All new listeners added are chained on this. + * @private + * @type {TickerListener} + */ + this._head = new _TickerListener2.default(null, null, Infinity); + + /** + * Internal current frame request ID + * @private + */ + this._requestId = null; + + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + * @private + */ + this._maxElapsedMS = 100; + + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.ticker.Ticker#start} automatically + * when a listener is added. + * + * @member {boolean} + * @default false + */ + this.autoStart = false; + + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS} + * and is scaled with {@link PIXI.ticker.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * + * @member {number} + * @default 1 + */ + this.deltaTime = 1; + + /** + * Time elapsed in milliseconds from last frame to this frame. + * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime} + * is based, this value is neither capped nor scaled. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * Defaults to target frame time + * + * @member {number} + * @default 16.66 + */ + this.elapsedMS = 1 / _settings2.default.TARGET_FPMS; + + /** + * The last time {@link PIXI.ticker.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default -1 + */ + this.lastTime = -1; + + /** + * Factor of current {@link PIXI.ticker.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + * + * @member {number} + * @default 1 + */ + this.speed = 1; + + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.ticker.Ticker#start} has been called. + * `false` if {@link PIXI.ticker.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.ticker.Ticker#autoStart} being `true` + * and a listener is added. + * + * @member {boolean} + * @default false + */ + this.started = false; + + /** + * Internal tick method bound to ticker instance. + * This is because in early 2015, Function.bind + * is still 60% slower in high performance scenarios. + * Also separating frame requests from update method + * so listeners may be called at any time and with + * any animation API, just invoke ticker.update(time). + * + * @private + * @param {number} time - Time since last tick. + */ + this._tick = function (time) { + _this._requestId = null; + + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._head.next) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * + * @private + */ + + + Ticker.prototype._requestIfNeeded = function _requestIfNeeded() { + if (this._requestId === null && this._head.next) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._requestId = requestAnimationFrame(this._tick); + } + }; + + /** + * Conditionally cancels a pending animation frame. + * + * @private + */ + + + Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; + + /** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * + * @private + */ + + + Ticker.prototype._startIfPossible = function _startIfPossible() { + if (this.started) { + this._requestIfNeeded(); + } else if (this.autoStart) { + this.start(); + } + }; + + /** + * Register a handler for tick events. Calls continuously unless + * it is removed or the ticker is stopped. + * + * @param {Function} fn - The listener function to be added for updates + * @param {Function} [context] - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.add = function add(fn, context) { + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _const.UPDATE_PRIORITY.NORMAL; + + return this._addListener(new _TickerListener2.default(fn, context, priority)); + }; + + /** + * Add a handler for the tick event which is only execute once. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context] - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.addOnce = function addOnce(fn, context) { + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _const.UPDATE_PRIORITY.NORMAL; + + return this._addListener(new _TickerListener2.default(fn, context, priority, true)); + }; + + /** + * Internally adds the event handler so that it can be sorted by priority. + * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run + * before the rendering. + * + * @private + * @param {TickerListener} listener - Current listener being added. + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype._addListener = function _addListener(listener) { + // For attaching to head + var current = this._head.next; + var previous = this._head; + + // Add the first item + if (!current) { + listener.connect(previous); + } else { + // Go from highest to lowest priority + while (current) { + if (listener.priority > current.priority) { + listener.connect(previous); + break; + } + previous = current; + current = current.next; + } + + // Not yet connected + if (!listener.previous) { + listener.connect(previous); + } + } + + this._startIfPossible(); + + return this; + }; + + /** + * Removes any handlers matching the function and context parameters. + * If no handlers are left after removing, then it cancels the animation frame. + * + * @param {Function} fn - The listener function to be removed + * @param {Function} [context] - The listener context to be removed + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.remove = function remove(fn, context) { + var listener = this._head.next; + + while (listener) { + // We found a match, lets remove it + // no break to delete all possible matches + // incase a listener was added 2+ times + if (listener.match(fn, context)) { + listener = listener.destroy(); + } else { + listener = listener.next; + } + } + + if (!this._head.next) { + this._cancelIfNeeded(); + } + + return this; + }; + + /** + * Starts the ticker. If the ticker has listeners + * a new animation frame is requested at this point. + */ + + + Ticker.prototype.start = function start() { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + }; + + /** + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. + */ + + + Ticker.prototype.stop = function stop() { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; + + /** + * Destroy the ticker and don't use after this. Calling + * this method removes all references to internal events. + */ + + + Ticker.prototype.destroy = function destroy() { + this.stop(); + + var listener = this._head.next; + + while (listener) { + listener = listener.destroy(true); + } + + this._head.destroy(); + this._head = null; + }; + + /** + * Triggers an update. An update entails setting the + * current {@link PIXI.ticker.Ticker#elapsedMS}, + * the current {@link PIXI.ticker.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.ticker.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + + + Ticker.prototype.update = function update() { + var currentTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : performance.now(); + + var elapsedMS = void 0; + + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + + this.deltaTime = elapsedMS * _settings2.default.TARGET_FPMS * this.speed; + + // Cache a local reference, in-case ticker is destroyed + // during the emit, we can still check for head.next + var head = this._head; + + // Invoke listeners added to internal emitter + var listener = head.next; + + while (listener) { + listener = listener.emit(this.deltaTime); + } + + if (!head.next) { + this._cancelIfNeeded(); + } + } else { + this.deltaTime = this.elapsedMS = 0; + } + + this.lastTime = currentTime; + }; + + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.ticker.Ticker#speed}, which is specific + * to scaling {@link PIXI.ticker.Ticker#deltaTime}. + * + * @member {number} + * @readonly + */ + + + _createClass(Ticker, [{ + key: 'FPS', + get: function get() { + return 1000 / this.elapsedMS; + } + + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.ticker.Ticker#update}. + * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.settings.TARGET_FPMS * 1000`. + * + * @member {number} + * @default 10 + */ + + }, { + key: 'minFPS', + get: function get() { + return 1000 / this._maxElapsedMS; + }, + set: function set(fps) // eslint-disable-line require-jsdoc + { + // Clamp: 0 to TARGET_FPMS + var minFPMS = Math.min(Math.max(0, fps) / 1000, _settings2.default.TARGET_FPMS); + + this._maxElapsedMS = 1 / minFPMS; + } + }]); + + return Ticker; +}(); + +exports.default = Ticker; + +},{"../const":46,"../settings":101,"./TickerListener":120}],120:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Internal class for handling the priority sorting of ticker handlers. + * + * @private + * @class + * @memberof PIXI.ticker + */ +var TickerListener = function () { + /** + * Constructor + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context=null] - The listener context + * @param {number} [priority=0] - The priority for emitting + * @param {boolean} [once=false] - If the handler should fire once + */ + function TickerListener(fn) { + var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var once = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + _classCallCheck(this, TickerListener); + + /** + * The handler function to execute. + * @member {Function} + */ + this.fn = fn; + + /** + * The calling to execute. + * @member {Function} + */ + this.context = context; + + /** + * The current priority. + * @member {number} + */ + this.priority = priority; + + /** + * If this should only execute once. + * @member {boolean} + */ + this.once = once; + + /** + * The next item in chain. + * @member {TickerListener} + */ + this.next = null; + + /** + * The previous item in chain. + * @member {TickerListener} + */ + this.previous = null; + + /** + * `true` if this listener has been destroyed already. + * @member {boolean} + * @private + */ + this._destroyed = false; + } + + /** + * Simple compare function to figure out if a function and context match. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} context - The listener context + * @return {boolean} `true` if the listener match the arguments + */ + + + TickerListener.prototype.match = function match(fn, context) { + context = context || null; + + return this.fn === fn && this.context === context; + }; + + /** + * Emit by calling the current function. + * @param {number} deltaTime - time since the last emit. + * @return {TickerListener} Next ticker + */ + + + TickerListener.prototype.emit = function emit(deltaTime) { + if (this.fn) { + if (this.context) { + this.fn.call(this.context, deltaTime); + } else { + this.fn(deltaTime); + } + } + + var redirect = this.next; + + if (this.once) { + this.destroy(true); + } + + // Soft-destroying should remove + // the next reference + if (this._destroyed) { + this.next = null; + } + + return redirect; + }; + + /** + * Connect to the list. + * @param {TickerListener} previous - Input node, previous listener + */ + + + TickerListener.prototype.connect = function connect(previous) { + this.previous = previous; + if (previous.next) { + previous.next.previous = this; + } + this.next = previous.next; + previous.next = this; + }; + + /** + * Destroy and don't use after this. + * @param {boolean} [hard = false] `true` to remove the `next` reference, this + * is considered a hard destroy. Soft destroy maintains the next reference. + * @return {TickerListener} The listener to redirect while emitting or removing. + */ + + + TickerListener.prototype.destroy = function destroy() { + var hard = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + this._destroyed = true; + this.fn = null; + this.context = null; + + // Disconnect, hook up next and previous + if (this.previous) { + this.previous.next = this.next; + } + + if (this.next) { + this.next.previous = this.previous; + } + + // Redirect to the next item + var redirect = this.next; + + // Remove references + this.next = hard ? null : redirect; + this.previous = null; + + return redirect; + }; + + return TickerListener; +}(); + +exports.default = TickerListener; + +},{}],121:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Ticker = exports.shared = undefined; + +var _Ticker = require('./Ticker'); + +var _Ticker2 = _interopRequireDefault(_Ticker); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The shared ticker instance used by {@link PIXI.extras.AnimatedSprite}. + * and by {@link PIXI.interaction.InteractionManager}. + * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` + * for this instance. Please follow the examples for usage, including + * how to opt-out of auto-starting the shared ticker. + * + * @example + * let ticker = PIXI.ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(800, 600); + * let stage = new PIXI.Container(); + * let interactionManager = PIXI.interaction.InteractionManager(renderer); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * + * @type {PIXI.ticker.Ticker} + * @memberof PIXI.ticker + */ +var shared = new _Ticker2.default(); + +shared.autoStart = true; +shared.destroy = function () { + // protect destroying shared ticker + // this is used by other internal systems + // like AnimatedSprite and InteractionManager +}; + +/** + * This namespace contains an API for interacting with PIXI's internal global update loop. + * + * This ticker is used for rendering, {@link PIXI.extras.AnimatedSprite AnimatedSprite}, + * {@link PIXI.interaction.InteractionManager InteractionManager} and many other time-based PIXI systems. + * @example + * const ticker = new PIXI.ticker.Ticker(); + * ticker.stop(); + * ticker.add((deltaTime) => { + * // do something every frame + * }); + * ticker.start(); + * @namespace PIXI.ticker + */ +exports.shared = shared; +exports.Ticker = _Ticker2.default; + +},{"./Ticker":119}],122:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = canUploadSameBuffer; +function canUploadSameBuffer() { + // Uploading the same buffer multiple times in a single frame can cause perf issues. + // Apparent on IOS so only check for that at the moment + // this check may become more complex if this issue pops up elsewhere. + var ios = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform); + + return !ios; +} + +},{}],123:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = createIndicesForQuads; +/** + * Generic Mask Stack data structure + * + * @memberof PIXI + * @function createIndicesForQuads + * @private + * @param {number} size - Number of quads + * @return {Uint16Array} indices + */ +function createIndicesForQuads(size) { + // the total number of indices in our array, there are 6 points per quad. + + var totalIndices = size * 6; + + var indices = new Uint16Array(totalIndices); + + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + indices[i + 0] = j + 0; + indices[i + 1] = j + 1; + indices[i + 2] = j + 2; + indices[i + 3] = j + 0; + indices[i + 4] = j + 2; + indices[i + 5] = j + 3; + } + + return indices; +} + +},{}],124:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = determineCrossOrigin; + +var _url2 = require('url'); + +var _url3 = _interopRequireDefault(_url2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var tempAnchor = void 0; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +function determineCrossOrigin(url) { + var loc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location; + + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url3.default.parse(tempAnchor.href); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +} + +},{"url":38}],125:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.premultiplyBlendMode = exports.BaseTextureCache = exports.TextureCache = exports.earcut = exports.mixins = exports.pluginTarget = exports.EventEmitter = exports.removeItems = exports.isMobile = undefined; +exports.uid = uid; +exports.hex2rgb = hex2rgb; +exports.hex2string = hex2string; +exports.rgb2hex = rgb2hex; +exports.getResolutionOfUrl = getResolutionOfUrl; +exports.decomposeDataUri = decomposeDataUri; +exports.getUrlFileExtension = getUrlFileExtension; +exports.getSvgSize = getSvgSize; +exports.skipHello = skipHello; +exports.sayHello = sayHello; +exports.isWebGLSupported = isWebGLSupported; +exports.sign = sign; +exports.destroyTextureCache = destroyTextureCache; +exports.clearTextureCache = clearTextureCache; +exports.correctBlendMode = correctBlendMode; +exports.premultiplyTint = premultiplyTint; +exports.premultiplyRgba = premultiplyRgba; +exports.premultiplyTintToRgba = premultiplyTintToRgba; + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _pluginTarget = require('./pluginTarget'); + +var _pluginTarget2 = _interopRequireDefault(_pluginTarget); + +var _mixin = require('./mixin'); + +var mixins = _interopRequireWildcard(_mixin); + +var _ismobilejs = require('ismobilejs'); + +var isMobile = _interopRequireWildcard(_ismobilejs); + +var _removeArrayItems = require('remove-array-items'); + +var _removeArrayItems2 = _interopRequireDefault(_removeArrayItems); + +var _mapPremultipliedBlendModes = require('./mapPremultipliedBlendModes'); + +var _mapPremultipliedBlendModes2 = _interopRequireDefault(_mapPremultipliedBlendModes); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var nextUid = 0; +var saidHello = false; + +/** + * Generalized convenience utilities for PIXI. + * @example + * // Extend PIXI's internal Event Emitter. + * class MyEmitter extends PIXI.utils.EventEmitter { + * constructor() { + * super(); + * console.log("Emitter created!"); + * } + * } + * + * // Get info on current device + * console.log(PIXI.utils.isMobile); + * + * // Convert hex color to string + * console.log(PIXI.utils.hex2string(0xff00ff)); // returns: "#ff00ff" + * @namespace PIXI.utils + */ +exports.isMobile = isMobile; +exports.removeItems = _removeArrayItems2.default; +exports.EventEmitter = _eventemitter2.default; +exports.pluginTarget = _pluginTarget2.default; +exports.mixins = mixins; +exports.earcut = _earcut2.default; + +/** + * Gets the next unique identifier + * + * @memberof PIXI.utils + * @function uid + * @return {number} The next unique identifier to use. + */ + +function uid() { + return ++nextUid; +} + +/** + * Converts a hex color number to an [R, G, B] array + * + * @memberof PIXI.utils + * @function hex2rgb + * @param {number} hex - The number to convert + * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one + * @return {number[]} An array representing the [R, G, B] of the color. + */ +function hex2rgb(hex, out) { + out = out || []; + + out[0] = (hex >> 16 & 0xFF) / 255; + out[1] = (hex >> 8 & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + + return out; +} + +/** + * Converts a hex color number to a string. + * + * @memberof PIXI.utils + * @function hex2string + * @param {number} hex - Number in hex + * @return {string} The string color. + */ +function hex2string(hex) { + hex = hex.toString(16); + hex = '000000'.substr(0, 6 - hex.length) + hex; + + return '#' + hex; +} + +/** + * Converts a color as an [R, G, B] array to a hex number + * + * @memberof PIXI.utils + * @function rgb2hex + * @param {number[]} rgb - rgb array + * @return {number} The color number + */ +function rgb2hex(rgb) { + return (rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + (rgb[2] * 255 | 0); +} + +/** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * + * @memberof PIXI.utils + * @function getResolutionOfUrl + * @param {string} url - the image path + * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. + * @return {number} resolution / device pixel ratio of an asset + */ +function getResolutionOfUrl(url, defaultValue) { + var resolution = _settings2.default.RETINA_PREFIX.exec(url); + + if (resolution) { + return parseFloat(resolution[1]); + } + + return defaultValue !== undefined ? defaultValue : 1; +} + +/** + * Typedef for decomposeDataUri return object. + * + * @typedef {object} PIXI.utils~DecomposedDataUri + * @property {mediaType} Media type, eg. `image` + * @property {subType} Sub type, eg. `png` + * @property {encoding} Data encoding, eg. `base64` + * @property {data} The actual data + */ + +/** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. + * + * @memberof PIXI.utils + * @function decomposeDataUri + * @param {string} dataUri - the data URI to check + * @return {PIXI.utils~DecomposedDataUri|undefined} The decomposed data uri or undefined + */ +function decomposeDataUri(dataUri) { + var dataUriMatch = _const.DATA_URI.exec(dataUri); + + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : undefined, + data: dataUriMatch[5] + }; + } + + return undefined; +} + +/** + * Get type of the image by regexp for extension. Returns undefined for unknown extensions. + * + * @memberof PIXI.utils + * @function getUrlFileExtension + * @param {string} url - the image path + * @return {string|undefined} image extension + */ +function getUrlFileExtension(url) { + var extension = _const.URL_FILE_EXTENSION.exec(url); + + if (extension) { + return extension[1].toLowerCase(); + } + + return undefined; +} + +/** + * Typedef for Size object. + * + * @typedef {object} PIXI.utils~Size + * @property {width} Width component + * @property {height} Height component + */ + +/** + * Get size from an svg string using regexp. + * + * @memberof PIXI.utils + * @function getSvgSize + * @param {string} svgString - a serialized svg element + * @return {PIXI.utils~Size|undefined} image extension + */ +function getSvgSize(svgString) { + var sizeMatch = _const.SVG_SIZE.exec(svgString); + var size = {}; + + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); + size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); + } + + return size; +} + +/** + * Skips the hello message of renderers that are created after this is run. + * + * @function skipHello + * @memberof PIXI.utils + */ +function skipHello() { + saidHello = true; +} + +/** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever makes you a jerk face. + * + * @static + * @function sayHello + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ +function sayHello(type) { + if (saidHello) { + return; + } + + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = ['\n %c %c %c PixiJS ' + _const.VERSION + ' - \u2730 ' + type + ' \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n', 'background: #ff66a5; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff66a5; background: #030307; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'background: #ffc3dc; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;']; + + window.console.log.apply(console, args); + } else if (window.console) { + window.console.log('PixiJS ' + _const.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); + } + + saidHello = true; +} + +/** + * Helper for checking for webgl support + * + * @memberof PIXI.utils + * @function isWebGLSupported + * @return {boolean} is webgl supported + */ +function isWebGLSupported() { + var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; + + try { + if (!window.WebGLRenderingContext) { + return false; + } + + var canvas = document.createElement('canvas'); + var gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); + + var success = !!(gl && gl.getContextAttributes().stencil); + + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + + if (loseContext) { + loseContext.loseContext(); + } + } + + gl = null; + + return success; + } catch (e) { + return false; + } +} + +/** + * Returns sign of number + * + * @memberof PIXI.utils + * @function sign + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ +function sign(n) { + if (n === 0) return 0; + + return n < 0 ? -1 : 1; +} + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var TextureCache = exports.TextureCache = Object.create(null); + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var BaseTextureCache = exports.BaseTextureCache = Object.create(null); + +/** + * Destroys all texture in the cache + * + * @memberof PIXI.utils + * @function destroyTextureCache + */ +function destroyTextureCache() { + var key = void 0; + + for (key in TextureCache) { + TextureCache[key].destroy(); + } + for (key in BaseTextureCache) { + BaseTextureCache[key].destroy(); + } +} + +/** + * Removes all textures from cache, but does not destroy them + * + * @memberof PIXI.utils + * @function clearTextureCache + */ +function clearTextureCache() { + var key = void 0; + + for (key in TextureCache) { + delete TextureCache[key]; + } + for (key in BaseTextureCache) { + delete BaseTextureCache[key]; + } +} + +/** + * maps premultiply flag and blendMode to adjusted blendMode + * @memberof PIXI.utils + * @const premultiplyBlendMode + * @type {Array} + */ +var premultiplyBlendMode = exports.premultiplyBlendMode = (0, _mapPremultipliedBlendModes2.default)(); + +/** + * changes blendMode according to texture format + * + * @memberof PIXI.utils + * @function correctBlendMode + * @param {number} blendMode supposed blend mode + * @param {boolean} premultiplied whether source is premultiplied + * @returns {number} true blend mode for this texture + */ +function correctBlendMode(blendMode, premultiplied) { + return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; +} + +/** + * premultiplies tint + * + * @memberof PIXI.utils + * @param {number} tint integet RGB + * @param {number} alpha floating point alpha (0.0-1.0) + * @returns {number} tint multiplied by alpha + */ +function premultiplyTint(tint, alpha) { + if (alpha === 1.0) { + return (alpha * 255 << 24) + tint; + } + if (alpha === 0.0) { + return 0; + } + var R = tint >> 16 & 0xFF; + var G = tint >> 8 & 0xFF; + var B = tint & 0xFF; + + R = R * alpha + 0.5 | 0; + G = G * alpha + 0.5 | 0; + B = B * alpha + 0.5 | 0; + + return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; +} + +/** + * combines rgb and alpha to out array + * + * @memberof PIXI.utils + * @param {Float32Array|number[]} rgb input rgb + * @param {number} alpha alpha param + * @param {Float32Array} [out] output + * @param {boolean} [premultiply=true] do premultiply it + * @returns {Float32Array} vec4 rgba + */ +function premultiplyRgba(rgb, alpha, out, premultiply) { + out = out || new Float32Array(4); + if (premultiply || premultiply === undefined) { + out[0] = rgb[0] * alpha; + out[1] = rgb[1] * alpha; + out[2] = rgb[2] * alpha; + } else { + out[0] = rgb[0]; + out[1] = rgb[1]; + out[2] = rgb[2]; + } + out[3] = alpha; + + return out; +} + +/** + * converts integer tint and float alpha to vec4 form, premultiplies by default + * + * @memberof PIXI.utils + * @param {number} tint input tint + * @param {number} alpha alpha param + * @param {Float32Array} [out] output + * @param {boolean} [premultiply=true] do premultiply it + * @returns {Float32Array} vec4 rgba + */ +function premultiplyTintToRgba(tint, alpha, out, premultiply) { + out = out || new Float32Array(4); + out[0] = (tint >> 16 & 0xFF) / 255.0; + out[1] = (tint >> 8 & 0xFF) / 255.0; + out[2] = (tint & 0xFF) / 255.0; + if (premultiply || premultiply === undefined) { + out[0] *= alpha; + out[1] *= alpha; + out[2] *= alpha; + } + out[3] = alpha; + + return out; +} + +},{"../const":46,"../settings":101,"./mapPremultipliedBlendModes":126,"./mixin":128,"./pluginTarget":129,"earcut":2,"eventemitter3":3,"ismobilejs":4,"remove-array-items":31}],126:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapPremultipliedBlendModes; + +var _const = require('../const'); + +/** + * Corrects PixiJS blend, takes premultiplied alpha into account + * + * @memberof PIXI + * @function mapPremultipliedBlendModes + * @private + * @param {Array} [array] - The array to output into. + * @return {Array} Mapped modes. + */ + +function mapPremultipliedBlendModes() { + var pm = []; + var npm = []; + + for (var i = 0; i < 32; i++) { + pm[i] = i; + npm[i] = i; + } + + pm[_const.BLEND_MODES.NORMAL_NPM] = _const.BLEND_MODES.NORMAL; + pm[_const.BLEND_MODES.ADD_NPM] = _const.BLEND_MODES.ADD; + pm[_const.BLEND_MODES.SCREEN_NPM] = _const.BLEND_MODES.SCREEN; + + npm[_const.BLEND_MODES.NORMAL] = _const.BLEND_MODES.NORMAL_NPM; + npm[_const.BLEND_MODES.ADD] = _const.BLEND_MODES.ADD_NPM; + npm[_const.BLEND_MODES.SCREEN] = _const.BLEND_MODES.SCREEN_NPM; + + var array = []; + + array.push(npm); + array.push(pm); + + return array; +} + +},{"../const":46}],127:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = maxRecommendedTextures; + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function maxRecommendedTextures(max) { + if (_ismobilejs2.default.tablet || _ismobilejs2.default.phone) { + // check if the res is iphone 6 or higher.. + return 4; + } + + // desktop should be ok + return max; +} + +},{"ismobilejs":4}],128:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.mixin = mixin; +exports.delayMixin = delayMixin; +exports.performMixins = performMixins; +/** + * Mixes all enumerable properties and methods from a source object to a target object. + * + * @memberof PIXI.utils.mixins + * @function mixin + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function mixin(target, source) { + if (!target || !source) return; + // in ES8/ES2017, this would be really easy: + // Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + + // get all the enumerable property keys + var keys = Object.keys(source); + + // loop through properties + for (var i = 0; i < keys.length; ++i) { + var propertyName = keys[i]; + + // Set the property using the property descriptor - this works for accessors and normal value properties + Object.defineProperty(target, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); + } +} + +var mixins = []; + +/** + * Queues a mixin to be handled towards the end of the initialization of PIXI, so that deprecation + * can take effect. + * + * @memberof PIXI.utils.mixins + * @function delayMixin + * @private + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function delayMixin(target, source) { + mixins.push(target, source); +} + +/** + * Handles all mixins queued via delayMixin(). + * + * @memberof PIXI.utils.mixins + * @function performMixins + * @private + */ +function performMixins() { + for (var i = 0; i < mixins.length; i += 2) { + mixin(mixins[i], mixins[i + 1]); + } + mixins.length = 0; +} + +},{}],129:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Mixins functionality to make an object have "plugins". + * + * @example + * function MyObject() {} + * + * pluginTarget.mixin(MyObject); + * + * @mixin + * @memberof PIXI.utils + * @param {object} obj - The object to mix into. + */ +function pluginTarget(obj) { + obj.__plugins = {}; + + /** + * Adds a plugin to an object + * + * @param {string} pluginName - The events that should be listed. + * @param {Function} ctor - The constructor function for the plugin. + */ + obj.registerPlugin = function registerPlugin(pluginName, ctor) { + obj.__plugins[pluginName] = ctor; + }; + + /** + * Instantiates all the plugins of this object + * + */ + obj.prototype.initPlugins = function initPlugins() { + this.plugins = this.plugins || {}; + + for (var o in obj.__plugins) { + this.plugins[o] = new obj.__plugins[o](this); + } + }; + + /** + * Removes all the plugins of this object + * + */ + obj.prototype.destroyPlugins = function destroyPlugins() { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + + this.plugins = null; + }; +} + +exports.default = { + /** + * Mixes in the properties of the pluginTarget into another object + * + * @param {object} obj - The obj to mix into + */ + mixin: function mixin(obj) { + pluginTarget(obj); + } +}; + +},{}],130:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = trimCanvas; +/** + * Trim transparent borders from a canvas + * + * @memberof PIXI + * @function trimCanvas + * @private + * @param {HTMLCanvasElement} canvas - the canvas to trim + * @returns {object} Trim data + */ +function trimCanvas(canvas) { + // https://gist.github.com/remy/784508 + + var width = canvas.width; + var height = canvas.height; + + var context = canvas.getContext('2d'); + var imageData = context.getImageData(0, 0, width, height); + var pixels = imageData.data; + var len = pixels.length; + + var bound = { + top: null, + left: null, + right: null, + bottom: null + }; + var i = void 0; + var x = void 0; + var y = void 0; + + for (i = 0; i < len; i += 4) { + if (pixels[i + 3] !== 0) { + x = i / 4 % width; + y = ~~(i / 4 / width); + + if (bound.top === null) { + bound.top = y; + } + + if (bound.left === null) { + bound.left = x; + } else if (x < bound.left) { + bound.left = x; + } + + if (bound.right === null) { + bound.right = x + 1; + } else if (bound.right < x) { + bound.right = x + 1; + } + + if (bound.bottom === null) { + bound.bottom = y; + } else if (bound.bottom < y) { + bound.bottom = y; + } + } + } + + width = bound.right - bound.left; + height = bound.bottom - bound.top + 1; + + var data = context.getImageData(bound.left, bound.top, width, height); + + return { + height: height, + width: width, + data: data + }; +} + +},{}],131:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = deprecation; +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code + +// A map of warning messages already fired +var warnings = {}; + +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code +function warn(msg) { + // Ignore duplicat + if (warnings[msg]) { + return; + } + + /* eslint-disable no-console */ + var stack = new Error().stack; + + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('Deprecation Warning: ', msg); + } else { + // chop off the stack trace which includes pixi.js internal calls + stack = stack.split('\n').splice(3).join('\n'); + + if (console.groupCollapsed) { + console.groupCollapsed('%cDeprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', msg); + console.warn(stack); + console.groupEnd(); + } else { + console.warn('Deprecation Warning: ', msg); + console.warn(stack); + } + } + /* eslint-enable no-console */ + + warnings[msg] = true; +} + +function deprecation(core) { + var mesh = core.mesh, + particles = core.particles, + extras = core.extras, + filters = core.filters, + prepare = core.prepare, + loaders = core.loaders, + interaction = core.interaction; + + + Object.defineProperties(core, { + + /** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ + SpriteBatch: { + get: function get() { + throw new ReferenceError('SpriteBatch does not exist any more, ' + 'please use the new ParticleContainer instead.'); + } + }, + + /** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in PixiJS v3, + * please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ + AssetLoader: { + get: function get() { + throw new ReferenceError('The loader system was overhauled in PixiJS v3, ' + 'please see the new PIXI.loaders.Loader class.'); + } + }, + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + Stage: { + get: function get() { + warn('You do not need to use a PIXI Stage any more, you can simply render any container.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + DisplayObjectContainer: { + get: function get() { + warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + Strip: { + get: function get() { + warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.'); + + return mesh.Mesh; + } + }, + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + Rope: { + get: function get() { + warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.'); + + return mesh.Rope; + } + }, + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + ParticleContainer: { + get: function get() { + warn('The ParticleContainer class has been moved to particles.ParticleContainer, ' + 'please use particles.ParticleContainer from now on.'); + + return particles.ParticleContainer; + } + }, + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + MovieClip: { + get: function get() { + warn('The MovieClip class has been moved to extras.AnimatedSprite, please use extras.AnimatedSprite.'); + + return extras.AnimatedSprite; + } + }, + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + TilingSprite: { + get: function get() { + warn('The TilingSprite class has been moved to extras.TilingSprite, ' + 'please use extras.TilingSprite from now on.'); + + return extras.TilingSprite; + } + }, + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + BitmapText: { + get: function get() { + warn('The BitmapText class has been moved to extras.BitmapText, ' + 'please use extras.BitmapText from now on.'); + + return extras.BitmapText; + } + }, + + /** + * @class + * @private + * @name blendModes + * @memberof PIXI + * @see PIXI.BLEND_MODES + * @deprecated since version 3.0.0 + */ + blendModes: { + get: function get() { + warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.'); + + return core.BLEND_MODES; + } + }, + + /** + * @class + * @private + * @name scaleModes + * @memberof PIXI + * @see PIXI.SCALE_MODES + * @deprecated since version 3.0.0 + */ + scaleModes: { + get: function get() { + warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.'); + + return core.SCALE_MODES; + } + }, + + /** + * @class + * @private + * @name BaseTextureCache + * @memberof PIXI + * @see PIXI.utils.BaseTextureCache + * @deprecated since version 3.0.0 + */ + BaseTextureCache: { + get: function get() { + warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, ' + 'please use utils.BaseTextureCache from now on.'); + + return core.utils.BaseTextureCache; + } + }, + + /** + * @class + * @private + * @name TextureCache + * @memberof PIXI + * @see PIXI.utils.TextureCache + * @deprecated since version 3.0.0 + */ + TextureCache: { + get: function get() { + warn('The TextureCache class has been moved to utils.TextureCache, ' + 'please use utils.TextureCache from now on.'); + + return core.utils.TextureCache; + } + }, + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + math: { + get: function get() { + warn('The math namespace is deprecated, please access members already accessible on PIXI.'); + + return core; + } + }, + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.Filter; + } + }, + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + TransformManual: { + get: function get() { + warn('TransformManual has been renamed to TransformBase, please update your pixi-spine'); + + return core.TransformBase; + } + }, + + /** + * @static + * @constant + * @name PIXI.TARGET_FPMS + * @see PIXI.settings.TARGET_FPMS + * @deprecated since version 4.2.0 + */ + TARGET_FPMS: { + get: function get() { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + return core.settings.TARGET_FPMS; + }, + set: function set(value) { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + core.settings.TARGET_FPMS = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.FILTER_RESOLUTION + * @see PIXI.settings.FILTER_RESOLUTION + * @deprecated since version 4.2.0 + */ + FILTER_RESOLUTION: { + get: function get() { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + return core.settings.FILTER_RESOLUTION; + }, + set: function set(value) { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + core.settings.FILTER_RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RESOLUTION + * @see PIXI.settings.RESOLUTION + * @deprecated since version 4.2.0 + */ + RESOLUTION: { + get: function get() { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + return core.settings.RESOLUTION; + }, + set: function set(value) { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + core.settings.RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.MIPMAP_TEXTURES + * @see PIXI.settings.MIPMAP_TEXTURES + * @deprecated since version 4.2.0 + */ + MIPMAP_TEXTURES: { + get: function get() { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + return core.settings.MIPMAP_TEXTURES; + }, + set: function set(value) { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + core.settings.MIPMAP_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_BATCH_SIZE + * @see PIXI.settings.SPRITE_BATCH_SIZE + * @deprecated since version 4.2.0 + */ + SPRITE_BATCH_SIZE: { + get: function get() { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + return core.settings.SPRITE_BATCH_SIZE; + }, + set: function set(value) { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + core.settings.SPRITE_BATCH_SIZE = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_MAX_TEXTURES + * @see PIXI.settings.SPRITE_MAX_TEXTURES + * @deprecated since version 4.2.0 + */ + SPRITE_MAX_TEXTURES: { + get: function get() { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + return core.settings.SPRITE_MAX_TEXTURES; + }, + set: function set(value) { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + core.settings.SPRITE_MAX_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RETINA_PREFIX + * @see PIXI.settings.RETINA_PREFIX + * @deprecated since version 4.2.0 + */ + RETINA_PREFIX: { + get: function get() { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + return core.settings.RETINA_PREFIX; + }, + set: function set(value) { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + core.settings.RETINA_PREFIX = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.DEFAULT_RENDER_OPTIONS + * @see PIXI.settings.RENDER_OPTIONS + * @deprecated since version 4.2.0 + */ + DEFAULT_RENDER_OPTIONS: { + get: function get() { + warn('PIXI.DEFAULT_RENDER_OPTIONS has been deprecated, please use PIXI.settings.DEFAULT_RENDER_OPTIONS'); + + return core.settings.RENDER_OPTIONS; + } + } + }); + + // Move the default properties to settings + var defaults = [{ parent: 'TRANSFORM_MODE', target: 'TRANSFORM_MODE' }, { parent: 'GC_MODES', target: 'GC_MODE' }, { parent: 'WRAP_MODES', target: 'WRAP_MODE' }, { parent: 'SCALE_MODES', target: 'SCALE_MODE' }, { parent: 'PRECISION', target: 'PRECISION_FRAGMENT' }]; + + var _loop = function _loop(i) { + var deprecation = defaults[i]; + + Object.defineProperty(core[deprecation.parent], 'DEFAULT', { + get: function get() { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); + + return core.settings[deprecation.target]; + }, + set: function set(value) { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); + + core.settings[deprecation.target] = value; + } + }); + }; + + for (var i = 0; i < defaults.length; i++) { + _loop(i); + } + + Object.defineProperties(core.settings, { + + /** + * @static + * @name PRECISION + * @memberof PIXI.settings + * @see PIXI.PRECISION + * @deprecated since version 4.4.0 + */ + PRECISION: { + get: function get() { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + return core.settings.PRECISION_FRAGMENT; + }, + set: function set(value) { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + core.settings.PRECISION_FRAGMENT = value; + } + } + }); + + if (extras.AnimatedSprite) { + Object.defineProperties(extras, { + + /** + * @class + * @name MovieClip + * @memberof PIXI.extras + * @see PIXI.extras.AnimatedSprite + * @deprecated since version 4.2.0 + */ + MovieClip: { + get: function get() { + warn('The MovieClip class has been renamed to AnimatedSprite, please use AnimatedSprite from now on.'); + + return extras.AnimatedSprite; + } + } + }); + } + + if (extras) { + Object.defineProperties(extras, { + /** + * @class + * @name TextureTransform + * @memberof PIXI.extras + * @see PIXI.TextureMatrix + * @deprecated since version 4.6.0 + */ + TextureTransform: { + get: function get() { + warn('The TextureTransform class has been renamed to TextureMatrix, ' + 'please use PIXI.TextureMatrix from now on.'); + + return core.TextureMatrix; + } + } + }); + } + + core.DisplayObject.prototype.generateTexture = function generateTexture(renderer, scaleMode, resolution) { + warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); + + return renderer.generateTexture(this, scaleMode, resolution); + }; + + core.Graphics.prototype.generateTexture = function generateTexture(scaleMode, resolution) { + warn('graphics generate texture has moved to the renderer. ' + 'Or to render a graphics to a texture using canvas please use generateCanvasTexture'); + + return this.generateCanvasTexture(scaleMode, resolution); + }; + + /** + * @method + * @name PIXI.GroupD8.isSwapWidthHeight + * @see PIXI.GroupD8.isVertical + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the direction is vertical + * @deprecated since version 4.6.0 + */ + core.GroupD8.isSwapWidthHeight = function isSwapWidthHeight(rotation) { + warn('GroupD8.isSwapWidthHeight was renamed to GroupD8.isVertical'); + + return core.GroupD8.isVertical(rotation); + }; + + core.RenderTexture.prototype.render = function render(displayObject, matrix, clear, updateTransform) { + this.legacyRenderer.render(displayObject, this, clear, matrix, !updateTransform); + warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)'); + }; + + core.RenderTexture.prototype.getImage = function getImage(target) { + warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); + + return this.legacyRenderer.extract.image(target); + }; + + core.RenderTexture.prototype.getBase64 = function getBase64(target) { + warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); + + return this.legacyRenderer.extract.base64(target); + }; + + core.RenderTexture.prototype.getCanvas = function getCanvas(target) { + warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); + + return this.legacyRenderer.extract.canvas(target); + }; + + core.RenderTexture.prototype.getPixels = function getPixels(target) { + warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); + + return this.legacyRenderer.pixels(target); + }; + + /** + * @method + * @private + * @name PIXI.Sprite#setTexture + * @see PIXI.Sprite#texture + * @deprecated since version 3.0.0 + * @param {PIXI.Texture} texture - The texture to set to. + */ + core.Sprite.prototype.setTexture = function setTexture(texture) { + this.texture = texture; + warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;'); + }; + + if (extras.BitmapText) { + /** + * @method + * @name PIXI.extras.BitmapText#setText + * @see PIXI.extras.BitmapText#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ + extras.BitmapText.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';'); + }; + } + + /** + * @method + * @name PIXI.Text#setText + * @see PIXI.Text#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ + core.Text.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';'); + }; + + /** + * Calculates the ascent, descent and fontSize of a given fontStyle + * + * @name PIXI.Text.calculateFontProperties + * @see PIXI.TextMetrics.measureFont + * @deprecated since version 4.5.0 + * @param {string} font - String representing the style of the font + * @return {Object} Font properties object + */ + core.Text.calculateFontProperties = function calculateFontProperties(font) { + warn('Text.calculateFontProperties is now deprecated, please use the TextMetrics.measureFont'); + + return core.TextMetrics.measureFont(font); + }; + + Object.defineProperties(core.Text, { + fontPropertiesCache: { + get: function get() { + warn('Text.fontPropertiesCache is deprecated'); + + return core.TextMetrics._fonts; + } + }, + fontPropertiesCanvas: { + get: function get() { + warn('Text.fontPropertiesCanvas is deprecated'); + + return core.TextMetrics._canvas; + } + }, + fontPropertiesContext: { + get: function get() { + warn('Text.fontPropertiesContext is deprecated'); + + return core.TextMetrics._context; + } + } + }); + + /** + * @method + * @name PIXI.Text#setStyle + * @see PIXI.Text#style + * @deprecated since version 3.0.0 + * @param {*} style - The style to set to. + */ + core.Text.prototype.setStyle = function setStyle(style) { + this.style = style; + warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;'); + }; + + /** + * @method + * @name PIXI.Text#determineFontProperties + * @see PIXI.Text#measureFontProperties + * @deprecated since version 4.2.0 + * @private + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ + core.Text.prototype.determineFontProperties = function determineFontProperties(fontStyle) { + warn('determineFontProperties is now deprecated, please use TextMetrics.measureFont method'); + + return core.TextMetrics.measureFont(fontStyle); + }; + + /** + * @method + * @name PIXI.Text.getFontStyle + * @see PIXI.TextMetrics.getFontStyle + * @deprecated since version 4.5.0 + * @param {PIXI.TextStyle} style - The style to use. + * @return {string} Font string + */ + core.Text.getFontStyle = function getFontStyle(style) { + warn('getFontStyle is now deprecated, please use TextStyle.toFontString() instead'); + + style = style || {}; + + if (!(style instanceof core.TextStyle)) { + style = new core.TextStyle(style); + } + + return style.toFontString(); + }; + + Object.defineProperties(core.TextStyle.prototype, { + /** + * Set all properties of a font as a single string + * + * @name PIXI.TextStyle#font + * @deprecated since version 4.0.0 + */ + font: { + get: function get() { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\', \'fontSize\', \'fontStyle\', \'fontVariant\' and \'fontWeight\' properties from now on'); + + var fontSizeString = typeof this._fontSize === 'number' ? this._fontSize + 'px' : this._fontSize; + + return this._fontStyle + ' ' + this._fontVariant + ' ' + this._fontWeight + ' ' + fontSizeString + ' ' + this._fontFamily; + }, + set: function set(font) { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + + // can work out fontStyle from search of whole string + if (font.indexOf('italic') > 1) { + this._fontStyle = 'italic'; + } else if (font.indexOf('oblique') > -1) { + this._fontStyle = 'oblique'; + } else { + this._fontStyle = 'normal'; + } + + // can work out fontVariant from search of whole string + if (font.indexOf('small-caps') > -1) { + this._fontVariant = 'small-caps'; + } else { + this._fontVariant = 'normal'; + } + + // fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units + var splits = font.split(' '); + var fontSizeIndex = -1; + + this._fontSize = 26; + for (var i = 0; i < splits.length; ++i) { + if (splits[i].match(/(px|pt|em|%)/)) { + fontSizeIndex = i; + this._fontSize = splits[i]; + break; + } + } + + // we can now search for fontWeight as we know it must occur before the fontSize + this._fontWeight = 'normal'; + for (var _i = 0; _i < fontSizeIndex; ++_i) { + if (splits[_i].match(/(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/)) { + this._fontWeight = splits[_i]; + break; + } + } + + // and finally join everything together after the fontSize in case the font family has multiple words + if (fontSizeIndex > -1 && fontSizeIndex < splits.length - 1) { + this._fontFamily = ''; + for (var _i2 = fontSizeIndex + 1; _i2 < splits.length; ++_i2) { + this._fontFamily += splits[_i2] + ' '; + } + + this._fontFamily = this._fontFamily.slice(0, -1); + } else { + this._fontFamily = 'Arial'; + } + + this.styleID++; + } + } + }); + + /** + * @method + * @name PIXI.Texture#setFrame + * @see PIXI.Texture#setFrame + * @deprecated since version 3.0.0 + * @param {PIXI.Rectangle} frame - The frame to set. + */ + core.Texture.prototype.setFrame = function setFrame(frame) { + this.frame = frame; + warn('setFrame is now deprecated, please use the frame property, e.g: myTexture.frame = frame;'); + }; + + /** + * @static + * @function + * @name PIXI.Texture.addTextureToCache + * @see PIXI.Texture.addToCache + * @deprecated since 4.5.0 + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the texture will be stored against. + */ + core.Texture.addTextureToCache = function addTextureToCache(texture, id) { + core.Texture.addToCache(texture, id); + warn('Texture.addTextureToCache is deprecated, please use Texture.addToCache from now on.'); + }; + + /** + * @static + * @function + * @name PIXI.Texture.removeTextureFromCache + * @see PIXI.Texture.removeFromCache + * @deprecated since 4.5.0 + * @param {string} id - The id of the texture to be removed + * @return {PIXI.Texture|null} The texture that was removed + */ + core.Texture.removeTextureFromCache = function removeTextureFromCache(id) { + warn('Texture.removeTextureFromCache is deprecated, please use Texture.removeFromCache from now on. ' + 'Be aware that Texture.removeFromCache does not automatically its BaseTexture from the BaseTextureCache. ' + 'For that, use BaseTexture.removeFromCache'); + + core.BaseTexture.removeFromCache(id); + + return core.Texture.removeFromCache(id); + }; + + Object.defineProperties(filters, { + + /** + * @class + * @private + * @name PIXI.filters.AbstractFilter + * @see PIXI.AbstractFilter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.AbstractFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.SpriteMaskFilter + * @see PIXI.SpriteMaskFilter + * @deprecated since version 3.0.6 + */ + SpriteMaskFilter: { + get: function get() { + warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.'); + + return core.SpriteMaskFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.VoidFilter + * @see PIXI.filters.AlphaFilter + * @deprecated since version 4.5.7 + */ + VoidFilter: { + get: function get() { + warn('VoidFilter has been renamed to AlphaFilter, please use PIXI.filters.AlphaFilter'); + + return filters.AlphaFilter; + } + } + }); + + /** + * @method + * @name PIXI.utils.uuid + * @see PIXI.utils.uid + * @deprecated since version 3.0.6 + * @return {number} The uid + */ + core.utils.uuid = function () { + warn('utils.uuid() is deprecated, please use utils.uid() from now on.'); + + return core.utils.uid(); + }; + + /** + * @method + * @name PIXI.utils.canUseNewCanvasBlendModes + * @see PIXI.CanvasTinter + * @deprecated + * @return {boolean} Can use blend modes. + */ + core.utils.canUseNewCanvasBlendModes = function () { + warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on'); + + return core.CanvasTinter.canUseMultiply; + }; + + var saidHello = true; + + /** + * @name PIXI.utils._saidHello + * @type {boolean} + * @see PIXI.utils.skipHello + * @deprecated since 4.1.0 + */ + Object.defineProperty(core.utils, '_saidHello', { + set: function set(bool) { + if (bool) { + warn('PIXI.utils._saidHello is deprecated, please use PIXI.utils.skipHello()'); + this.skipHello(); + } + saidHello = bool; + }, + get: function get() { + return saidHello; + } + }); + + if (prepare.BasePrepare) { + /** + * @method + * @name PIXI.prepare.BasePrepare#register + * @see PIXI.prepare.BasePrepare#registerFindHook + * @deprecated since version 4.4.2 + * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + prepare.BasePrepare.prototype.register = function register(addHook, uploadHook) { + warn('renderer.plugins.prepare.register is now deprecated, ' + 'please use renderer.plugins.prepare.registerFindHook & renderer.plugins.prepare.registerUploadHook'); + + if (addHook) { + this.registerFindHook(addHook); + } + + if (uploadHook) { + this.registerUploadHook(uploadHook); + } + + return this; + }; + } + + if (prepare.canvas) { + /** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.canvas.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ + Object.defineProperty(prepare.canvas, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } + }); + } + + if (prepare.webgl) { + /** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.webgl.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ + Object.defineProperty(prepare.webgl, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } + }); + } + + if (loaders.Loader) { + var Resource = loaders.Resource; + var Loader = loaders.Loader; + + Object.defineProperties(Resource.prototype, { + isJson: { + get: function get() { + warn('The isJson property is deprecated, please use `resource.type === Resource.TYPE.JSON`.'); + + return this.type === Resource.TYPE.JSON; + } + }, + isXml: { + get: function get() { + warn('The isXml property is deprecated, please use `resource.type === Resource.TYPE.XML`.'); + + return this.type === Resource.TYPE.XML; + } + }, + isImage: { + get: function get() { + warn('The isImage property is deprecated, please use `resource.type === Resource.TYPE.IMAGE`.'); + + return this.type === Resource.TYPE.IMAGE; + } + }, + isAudio: { + get: function get() { + warn('The isAudio property is deprecated, please use `resource.type === Resource.TYPE.AUDIO`.'); + + return this.type === Resource.TYPE.AUDIO; + } + }, + isVideo: { + get: function get() { + warn('The isVideo property is deprecated, please use `resource.type === Resource.TYPE.VIDEO`.'); + + return this.type === Resource.TYPE.VIDEO; + } + } + }); + + Object.defineProperties(Loader.prototype, { + before: { + get: function get() { + warn('The before() method is deprecated, please use pre().'); + + return this.pre; + } + }, + after: { + get: function get() { + warn('The after() method is deprecated, please use use().'); + + return this.use; + } + } + }); + } + + if (interaction.interactiveTarget) { + /** + * @name PIXI.interaction.interactiveTarget#defaultCursor + * @static + * @type {number} + * @see PIXI.interaction.interactiveTarget#cursor + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.interactiveTarget, 'defaultCursor', { + set: function set(value) { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + this.cursor = value; + }, + get: function get() { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + + return this.cursor; + } + }); + } + + if (interaction.InteractionManager) { + /** + * @name PIXI.interaction.InteractionManager#defaultCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.InteractionManager, 'defaultCursorStyle', { + set: function set(value) { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + this.cursorStyles.default = value; + }, + get: function get() { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + + return this.cursorStyles.default; + } + }); + + /** + * @name PIXI.interaction.InteractionManager#currentCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.InteractionManager, 'currentCursorStyle', { + set: function set(value) { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + this.currentCursorMode = value; + }, + get: function get() { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + + return this.currentCursorMode; + } + }); + } +} + +},{}],132:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI.extract + */ + +var CanvasExtract = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasExtract(renderer) { + _classCallCheck(this, CanvasExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.extract.CanvasExtract} extract + * @memberof PIXI.CanvasRenderer# + * @see PIXI.extract.CanvasExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + CanvasExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `CanvasExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + CanvasExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + CanvasExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = this.renderer.width; + frame.height = this.renderer.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + CanvasExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + + return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; + }; + + /** + * Destroys the extract + * + */ + + + CanvasExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return CanvasExtract; +}(); + +exports.default = CanvasExtract; + + +core.CanvasRenderer.registerPlugin('extract', CanvasExtract); + +},{"../../core":65}],133:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLExtract = require('./webgl/WebGLExtract'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLExtract).default; + } +}); + +var _CanvasExtract = require('./canvas/CanvasExtract'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasExtract).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./canvas/CanvasExtract":132,"./webgl/WebGLExtract":134}],134:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); +var BYTES_PER_PIXEL = 4; + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI.extract + */ + +var WebGLExtract = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLExtract(renderer) { + _classCallCheck(this, WebGLExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.extract.WebGLExtract} extract + * @memberof PIXI.WebGLRenderer# + * @see PIXI.extract.WebGLExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + WebGLExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `WebGLExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + WebGLExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + WebGLExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var flipY = false; + var renderTexture = void 0; + var generated = false; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + generated = true; + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + flipY = false; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + flipY = true; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + + // set up an array of pixels + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + + canvasData.data.set(webglPixels); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // pulling pixels + if (flipY) { + canvasBuffer.context.scale(1, -1); + canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); + } + } + + if (generated) { + renderTexture.destroy(true); + } + // send the canvas back.. + + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + WebGLExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + var generated = false; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + generated = true; + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + } + + if (generated) { + renderTexture.destroy(true); + } + + return webglPixels; + }; + + /** + * Destroys the extract + * + */ + + + WebGLExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return WebGLExtract; +}(); + +exports.default = WebGLExtract; + + +core.WebGLRenderer.registerPlugin('extract', WebGLExtract); + +},{"../../core":65}],135:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @typedef PIXI.extras.AnimatedSprite~FrameObject + * @type {object} + * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame + * @property {number} time - the duration of the frame in ms + */ + +/** + * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. + * + * ```js + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; + * + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.fromImage(alienImages[i]); + * textureArray.push(texture); + * }; + * + * let mc = new PIXI.AnimatedSprite(textureArray); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ +var AnimatedSprite = function (_core$Sprite) { + _inherits(AnimatedSprite, _core$Sprite); + + /** + * @param {PIXI.Texture[]|PIXI.extras.AnimatedSprite~FrameObject[]} textures - an array of {@link PIXI.Texture} or frame + * objects that make up the animation + * @param {boolean} [autoUpdate=true] - Whether to use PIXI.ticker.shared to auto update animation time. + */ + function AnimatedSprite(textures, autoUpdate) { + _classCallCheck(this, AnimatedSprite); + + /** + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture)); + + _this._textures = null; + + /** + * @private + */ + _this._durations = null; + + _this.textures = textures; + + /** + * `true` uses PIXI.ticker.shared to auto update animation time. + * @type {boolean} + * @default true + * @private + */ + _this._autoUpdate = autoUpdate !== false; + + /** + * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower + * + * @member {number} + * @default 1 + */ + _this.animationSpeed = 1; + + /** + * Whether or not the animate sprite repeats after playing. + * + * @member {boolean} + * @default true + */ + _this.loop = true; + + /** + * Function to call when a AnimatedSprite finishes playing + * + * @member {Function} + */ + _this.onComplete = null; + + /** + * Function to call when a AnimatedSprite changes which texture is being rendered + * + * @member {Function} + */ + _this.onFrameChange = null; + + /** + * Function to call when 'loop' is true, and an AnimatedSprite is played and loops around to start again + * + * @member {Function} + */ + _this.onLoop = null; + + /** + * Elapsed time since animation has been started, used internally to display current texture + * + * @member {number} + * @private + */ + _this._currentTime = 0; + + /** + * Indicates if the AnimatedSprite is currently playing + * + * @member {boolean} + * @readonly + */ + _this.playing = false; + return _this; + } + + /** + * Stops the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.stop = function stop() { + if (!this.playing) { + return; + } + + this.playing = false; + if (this._autoUpdate) { + core.ticker.shared.remove(this.update, this); + } + }; + + /** + * Plays the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.play = function play() { + if (this.playing) { + return; + } + + this.playing = true; + if (this._autoUpdate) { + core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.HIGH); + } + }; + + /** + * Stops the AnimatedSprite and goes to a specific frame + * + * @param {number} frameNumber - frame index to stop at + */ + + + AnimatedSprite.prototype.gotoAndStop = function gotoAndStop(frameNumber) { + this.stop(); + + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + + /** + * Goes to a specific frame and begins playing the AnimatedSprite + * + * @param {number} frameNumber - frame index to start at + */ + + + AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay(frameNumber) { + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + + this.play(); + }; + + /** + * Updates the object transform for rendering. + * + * @private + * @param {number} deltaTime - Time since last tick. + */ + + + AnimatedSprite.prototype.update = function update(deltaTime) { + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + + lag += elapsed / 60 * 1000; + + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + + var sign = Math.sign(this.animationSpeed * deltaTime); + + this._currentTime = Math.floor(this._currentTime); + + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + + this._currentTime += lag / this._durations[this.currentFrame]; + } else { + this._currentTime += elapsed; + } + + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + + if (this.onComplete) { + this.onComplete(); + } + } else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + + if (this.onComplete) { + this.onComplete(); + } + } else if (previousFrame !== this.currentFrame) { + if (this.loop && this.onLoop) { + if (this.animationSpeed > 0 && this.currentFrame < previousFrame) { + this.onLoop(); + } else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) { + this.onLoop(); + } + } + + this.updateTexture(); + } + }; + + /** + * Updates the displayed texture to match the current frame index + * + * @private + */ + + + AnimatedSprite.prototype.updateTexture = function updateTexture() { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + this.cachedTint = 0xFFFFFF; + + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + }; + + /** + * Stops the AnimatedSprite and destroys it + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + AnimatedSprite.prototype.destroy = function destroy(options) { + this.stop(); + _core$Sprite.prototype.destroy.call(this, options); + }; + + /** + * A short hand way of creating a movieclip from an array of frame ids + * + * @static + * @param {string[]} frames - The array of frames ids the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animated sprite with the specified frames. + */ + + + AnimatedSprite.fromFrames = function fromFrames(frames) { + var textures = []; + + for (var i = 0; i < frames.length; ++i) { + textures.push(core.Texture.fromFrame(frames[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * A short hand way of creating a movieclip from an array of image ids + * + * @static + * @param {string[]} images - the array of image urls the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animate sprite with the specified images as frames. + */ + + + AnimatedSprite.fromImages = function fromImages(images) { + var textures = []; + + for (var i = 0; i < images.length; ++i) { + textures.push(core.Texture.fromImage(images[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * totalFrames is the total number of frames in the AnimatedSprite. This is the same as number of textures + * assigned to the AnimatedSprite. + * + * @readonly + * @member {number} + * @default 0 + */ + + + _createClass(AnimatedSprite, [{ + key: 'totalFrames', + get: function get() { + return this._textures.length; + } + + /** + * The array of textures used for this AnimatedSprite + * + * @member {PIXI.Texture[]} + */ + + }, { + key: 'textures', + get: function get() { + return this._textures; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value[0] instanceof core.Texture) { + this._textures = value; + this._durations = null; + } else { + this._textures = []; + this._durations = []; + + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + this.gotoAndStop(0); + this.updateTexture(); + } + + /** + * The AnimatedSprites current frame index + * + * @member {number} + * @readonly + */ + + }, { + key: 'currentFrame', + get: function get() { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + + return currentFrame; + } + }]); + + return AnimatedSprite; +}(core.Sprite); + +exports.default = AnimatedSprite; + +},{"../core":65}],136:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ObservablePoint = require('../core/math/ObservablePoint'); + +var _ObservablePoint2 = _interopRequireDefault(_ObservablePoint); + +var _utils = require('../core/utils'); + +var _settings = require('../core/settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BitmapText object will create a line or multiple lines of text using bitmap font. To + * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using: + * + * A BitmapText can only be created when the font is loaded + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); + * ``` + * + * http://www.angelcode.com/products/bmfont/ for windows or + * http://www.bmglyph.com/ for mac. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.extras + */ +var BitmapText = function (_core$Container) { + _inherits(BitmapText, _core$Container); + + /** + * @param {string} text - The copy that you would like the text to display + * @param {object} style - The style parameters + * @param {string|object} style.font - The font descriptor for the object, can be passed as a string of form + * "24px FontName" or "FontName" or as an object with explicit name/size properties. + * @param {string} [style.font.name] - The bitmap font id + * @param {number} [style.font.size] - The size of the font in pixels, e.g. 24 + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), does not affect + * single line text + * @param {number} [style.tint=0xFFFFFF] - The tint color + */ + function BitmapText(text) { + var style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _classCallCheck(this, BitmapText); + + /** + * Private tracker for the width of the overall text + * + * @member {number} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._textWidth = 0; + + /** + * Private tracker for the height of the overall text + * + * @member {number} + * @private + */ + _this._textHeight = 0; + + /** + * Private tracker for the letter sprite pool. + * + * @member {PIXI.Sprite[]} + * @private + */ + _this._glyphs = []; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._font = { + tint: style.tint !== undefined ? style.tint : 0xFFFFFF, + align: style.align || 'left', + name: null, + size: 0 + }; + + /** + * Private tracker for the current font. + * + * @member {object} + * @private + */ + _this.font = style.font; // run font setter + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = text; + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + * @private + */ + _this._maxWidth = 0; + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + * @private + */ + _this._maxLineHeight = 0; + + /** + * Letter spacing. This is useful for setting the space between characters. + * @member {number} + * @private + */ + _this._letterSpacing = 0; + + /** + * Text anchor. read-only + * + * @member {PIXI.ObservablePoint} + * @private + */ + _this._anchor = new _ObservablePoint2.default(function () { + _this.dirty = true; + }, _this, 0, 0); + + /** + * The dirty state of this object. + * + * @member {boolean} + */ + _this.dirty = false; + + _this.updateText(); + return _this; + } + + /** + * Renders text and updates it when needed + * + * @private + */ + + + BitmapText.prototype.updateText = function updateText() { + var data = BitmapText.fonts[this._font.name]; + var scale = this._font.size / data.size; + var pos = new core.Point(); + var chars = []; + var lineWidths = []; + var text = this.text.replace(/(?:\r\n|\r)/g, '\n'); + var textLength = text.length; + var maxWidth = this._maxWidth * data.size / this._font.size; + + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastBreakPos = -1; + var lastBreakWidth = 0; + var spacesRemoved = 0; + var maxLineHeight = 0; + + for (var i = 0; i < textLength; i++) { + var charCode = text.charCodeAt(i); + var char = text.charAt(i); + + if (/(?:\s)/.test(char)) { + lastBreakPos = i; + lastBreakWidth = lastLineWidth; + } + + if (char === '\r' || char === '\n') { + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + ++line; + ++spacesRemoved; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + var charData = data.chars[charCode]; + + if (!charData) { + continue; + } + + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + + chars.push({ + texture: charData.texture, + line: line, + charCode: charCode, + position: new core.Point(pos.x + charData.xOffset + this._letterSpacing / 2, pos.y + charData.yOffset) + }); + pos.x += charData.xAdvance + this._letterSpacing; + lastLineWidth = pos.x; + maxLineHeight = Math.max(maxLineHeight, charData.yOffset + charData.texture.height); + prevCharCode = charCode; + + if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth) { + ++spacesRemoved; + core.utils.removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos); + i = lastBreakPos; + lastBreakPos = -1; + + lineWidths.push(lastBreakWidth); + maxLineWidth = Math.max(maxLineWidth, lastBreakWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + } + } + + var lastChar = text.charAt(text.length - 1); + + if (lastChar !== '\r' && lastChar !== '\n') { + if (/(?:\s)/.test(lastChar)) { + lastLineWidth = lastBreakWidth; + } + + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + } + + var lineAlignOffsets = []; + + for (var _i = 0; _i <= line; _i++) { + var alignOffset = 0; + + if (this._font.align === 'right') { + alignOffset = maxLineWidth - lineWidths[_i]; + } else if (this._font.align === 'center') { + alignOffset = (maxLineWidth - lineWidths[_i]) / 2; + } + + lineAlignOffsets.push(alignOffset); + } + + var lenChars = chars.length; + var tint = this.tint; + + for (var _i2 = 0; _i2 < lenChars; _i2++) { + var c = this._glyphs[_i2]; // get the next glyph sprite + + if (c) { + c.texture = chars[_i2].texture; + } else { + c = new core.Sprite(chars[_i2].texture); + this._glyphs.push(c); + } + + c.position.x = (chars[_i2].position.x + lineAlignOffsets[chars[_i2].line]) * scale; + c.position.y = chars[_i2].position.y * scale; + c.scale.x = c.scale.y = scale; + c.tint = tint; + + if (!c.parent) { + this.addChild(c); + } + } + + // remove unnecessary children. + for (var _i3 = lenChars; _i3 < this._glyphs.length; ++_i3) { + this.removeChild(this._glyphs[_i3]); + } + + this._textWidth = maxLineWidth * scale; + this._textHeight = (pos.y + data.lineHeight) * scale; + + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + for (var _i4 = 0; _i4 < lenChars; _i4++) { + this._glyphs[_i4].x -= this._textWidth * this.anchor.x; + this._glyphs[_i4].y -= this._textHeight * this.anchor.y; + } + } + this._maxLineHeight = maxLineHeight * scale; + }; + + /** + * Updates the transform of this object + * + * @private + */ + + + BitmapText.prototype.updateTransform = function updateTransform() { + this.validate(); + this.containerUpdateTransform(); + }; + + /** + * Validates text before calling parent's getLocalBounds + * + * @return {PIXI.Rectangle} The rectangular bounding area + */ + + + BitmapText.prototype.getLocalBounds = function getLocalBounds() { + this.validate(); + + return _core$Container.prototype.getLocalBounds.call(this); + }; + + /** + * Updates text when needed + * + * @private + */ + + + BitmapText.prototype.validate = function validate() { + if (this.dirty) { + this.updateText(); + this.dirty = false; + } + }; + + /** + * The tint of the BitmapText object + * + * @member {number} + */ + + + /** + * Register a bitmap font with data and a texture. + * + * @static + * @param {XMLDocument} xml - The XML document data. + * @param {Object.|PIXI.Texture|PIXI.Texture[]} textures - List of textures for each page. + * If providing an object, the key is the `` element's `file` attribute in the FNT file. + * @return {Object} Result font object with font, size, lineHeight and char fields. + */ + BitmapText.registerFont = function registerFont(xml, textures) { + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + var pages = xml.getElementsByTagName('page'); + var res = (0, _utils.getResolutionOfUrl)(pages[0].getAttribute('file'), _settings2.default.RESOLUTION); + var pagesTextures = {}; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) / res; + data.chars = {}; + + // Single texture, convert to list + if (textures instanceof core.Texture) { + textures = [textures]; + } + + // Convert the input Texture, Textures or object + // into a page Texture lookup by "id" + for (var i = 0; i < pages.length; i++) { + var id = pages[i].getAttribute('id'); + var file = pages[i].getAttribute('file'); + + pagesTextures[id] = textures instanceof Array ? textures[i] : textures[file]; + } + + // parse letters + var letters = xml.getElementsByTagName('char'); + + for (var _i5 = 0; _i5 < letters.length; _i5++) { + var letter = letters[_i5]; + var charCode = parseInt(letter.getAttribute('id'), 10); + var page = letter.getAttribute('page') || 0; + var textureRect = new core.Rectangle(parseInt(letter.getAttribute('x'), 10) / res + pagesTextures[page].frame.x / res, parseInt(letter.getAttribute('y'), 10) / res + pagesTextures[page].frame.y / res, parseInt(letter.getAttribute('width'), 10) / res, parseInt(letter.getAttribute('height'), 10) / res); + + data.chars[charCode] = { + xOffset: parseInt(letter.getAttribute('xoffset'), 10) / res, + yOffset: parseInt(letter.getAttribute('yoffset'), 10) / res, + xAdvance: parseInt(letter.getAttribute('xadvance'), 10) / res, + kerning: {}, + texture: new core.Texture(pagesTextures[page].baseTexture, textureRect), + page: page + }; + } + + // parse kernings + var kernings = xml.getElementsByTagName('kerning'); + + for (var _i6 = 0; _i6 < kernings.length; _i6++) { + var kerning = kernings[_i6]; + var first = parseInt(kerning.getAttribute('first'), 10) / res; + var second = parseInt(kerning.getAttribute('second'), 10) / res; + var amount = parseInt(kerning.getAttribute('amount'), 10) / res; + + if (data.chars[second]) { + data.chars[second].kerning[first] = amount; + } + } + + // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 + // but it's very likely to change + BitmapText.fonts[data.font] = data; + + return data; + }; + + _createClass(BitmapText, [{ + key: 'tint', + get: function get() { + return this._font.tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.tint = typeof value === 'number' && value >= 0 ? value : 0xFFFFFF; + + this.dirty = true; + } + + /** + * The alignment of the BitmapText object + * + * @member {string} + * @default 'left' + */ + + }, { + key: 'align', + get: function get() { + return this._font.align; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.align = value || 'left'; + + this.dirty = true; + } + + /** + * The anchor sets the origin point of the text. + * The default is 0,0 this means the text's origin is the top left + * Setting the anchor to 0.5,0.5 means the text's origin is centered + * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner + * + * @member {PIXI.Point | number} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (typeof value === 'number') { + this._anchor.set(value); + } else { + this._anchor.copy(value); + } + } + + /** + * The font descriptor of the BitmapText object + * + * @member {string|object} + */ + + }, { + key: 'font', + get: function get() { + return this._font; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (!value) { + return; + } + + if (typeof value === 'string') { + value = value.split(' '); + + this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); + this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; + } else { + this._font.name = value.name; + this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); + } + + this.dirty = true; + } + + /** + * The text of the BitmapText object + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + value = value.toString() || ' '; + if (this._text === value) { + return; + } + this._text = value; + this.dirty = true; + } + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + */ + + }, { + key: 'maxWidth', + get: function get() { + return this._maxWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._maxWidth === value) { + return; + } + this._maxWidth = value; + this.dirty = true; + } + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + * @readonly + */ + + }, { + key: 'maxLineHeight', + get: function get() { + this.validate(); + + return this._maxLineHeight; + } + + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textWidth', + get: function get() { + this.validate(); + + return this._textWidth; + } + + /** + * Additional space between characters. + * + * @member {number} + */ + + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._letterSpacing !== value) { + this._letterSpacing = value; + this.dirty = true; + } + } + + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textHeight', + get: function get() { + this.validate(); + + return this._textHeight; + } + }]); + + return BitmapText; +}(core.Container); + +exports.default = BitmapText; + + +BitmapText.fonts = {}; + +},{"../core":65,"../core/math/ObservablePoint":68,"../core/settings":101,"../core/utils":125}],137:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CanvasTinter = require('../core/sprites/canvas/CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); + +/** + * A tiling sprite is a fast way of rendering a tiling image + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ + +var TilingSprite = function (_core$Sprite) { + _inherits(TilingSprite, _core$Sprite); + + /** + * @param {PIXI.Texture} texture - the texture of the tiling sprite + * @param {number} [width=100] - the width of the tiling sprite + * @param {number} [height=100] - the height of the tiling sprite + */ + function TilingSprite(texture) { + var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100; + + _classCallCheck(this, TilingSprite); + + /** + * Tile transform + * + * @member {PIXI.TransformStatic} + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, texture)); + + _this.tileTransform = new core.TransformStatic(); + + // /// private + + /** + * The with of the tiling sprite + * + * @member {number} + * @private + */ + _this._width = width; + + /** + * The height of the tiling sprite + * + * @member {number} + * @private + */ + _this._height = height; + + /** + * Canvas pattern + * + * @type {CanvasPattern} + * @private + */ + _this._canvasPattern = null; + + /** + * transform that is applied to UV to get the texture coords + * + * @member {PIXI.TextureMatrix} + */ + _this.uvTransform = texture.transform || new core.TextureMatrix(texture); + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' method. + * + * @member {string} + * @default 'tilingSprite' + */ + _this.pluginName = 'tilingSprite'; + + /** + * Whether or not anchor affects uvs + * + * @member {boolean} + * @default false + */ + _this.uvRespectAnchor = false; + return _this; + } + /** + * Changes frame clamping in corresponding textureTransform, shortcut + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + + + /** + * @private + */ + TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate() { + if (this.uvTransform) { + this.uvTransform.texture = this._texture; + } + this.cachedTint = 0xFFFFFF; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + TilingSprite.prototype._renderWebGL = function _renderWebGL(renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + + if (!texture || !texture.valid) { + return; + } + + this.tileTransform.updateLocalTransform(); + this.uvTransform.update(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer + */ + + + TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { + var texture = this._texture; + + if (!texture.baseTexture.hasLoaded) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var resolution = renderer.resolution; + var baseTexture = texture.baseTexture; + var baseTextureResolution = baseTexture.resolution; + var modX = this.tilePosition.x / this.tileScale.x % texture._frame.width * baseTextureResolution; + var modY = this.tilePosition.y / this.tileScale.y % texture._frame.height * baseTextureResolution; + + // create a nice shiny pattern! + if (this._textureID !== this._texture._updateID || this.cachedTint !== this.tint) { + this._textureID = this._texture._updateID; + // cut an object from a spritesheet.. + var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height, baseTextureResolution); + + // Tint the tiling sprite + if (this.tint !== 0xFFFFFF) { + this.tintedTexture = _CanvasTinter2.default.getTintedTexture(this, this.tint); + tempCanvas.context.drawImage(this.tintedTexture, 0, 0); + } else { + tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x * baseTextureResolution, -texture._frame.y * baseTextureResolution); + } + this.cachedTint = this.tint; + this._canvasPattern = tempCanvas.context.createPattern(tempCanvas.canvas, 'repeat'); + } + + // set context state.. + context.globalAlpha = this.worldAlpha; + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + renderer.setBlendMode(this.blendMode); + + // fill the pattern! + context.fillStyle = this._canvasPattern; + + // TODO - this should be rolled into the setTransform above.. + context.scale(this.tileScale.x / baseTextureResolution, this.tileScale.y / baseTextureResolution); + + var anchorX = this.anchor.x * -this._width; + var anchorY = this.anchor.y * -this._height; + + if (this.uvRespectAnchor) { + context.translate(modX, modY); + + context.fillRect(-modX + anchorX, -modY + anchorY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } else { + context.translate(modX + anchorX, modY + anchorY); + + context.fillRect(-modX, -modY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } + }; + + /** + * Updates the bounds of the tiling sprite. + * + * @private + */ + + + TilingSprite.prototype._calculateBounds = function _calculateBounds() { + var minX = this._width * -this._anchor._x; + var minY = this._height * -this._anchor._y; + var maxX = this._width * (1 - this._anchor._x); + var maxY = this._height * (1 - this._anchor._y); + + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + TilingSprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._width * -this._anchor._x; + this._bounds.minY = this._height * -this._anchor._y; + this._bounds.maxX = this._width * (1 - this._anchor._x); + this._bounds.maxY = this._height * (1 - this._anchor._y); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new core.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _core$Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Checks if a point is inside this tiling sprite. + * + * @param {PIXI.Point} point - the point to check + * @return {boolean} Whether or not the sprite contains the point. + */ + + + TilingSprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor._x; + + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + var y1 = -height * this.anchor._y; + + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + TilingSprite.prototype.destroy = function destroy(options) { + _core$Sprite.prototype.destroy.call(this, options); + + this.tileTransform = null; + this.uvTransform = null; + }; + + /** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.Texture} The newly created texture + */ + + + TilingSprite.from = function from(source, width, height) { + return new TilingSprite(core.Texture.from(source), width, height); + }; + + /** + * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId + */ + + + TilingSprite.fromFrame = function fromFrame(frameId, width, height) { + var texture = core.utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this); + } + + return new TilingSprite(texture, width, height); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @param {boolean} [crossorigin] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id + */ + + + TilingSprite.fromImage = function fromImage(imageId, width, height, crossorigin, scaleMode) { + return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode), width, height); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(TilingSprite, [{ + key: 'clampMargin', + get: function get() { + return this.uvTransform.clampMargin; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uvTransform.clampMargin = value; + this.uvTransform.update(true); + } + + /** + * The scaling of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tileScale', + get: function get() { + return this.tileTransform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.scale.copy(value); + } + + /** + * The offset of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tilePosition', + get: function get() { + return this.tileTransform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.position.copy(value); + } + }, { + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + } + + /** + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + } + }]); + + return TilingSprite; +}(core.Sprite); + +exports.default = TilingSprite; + +},{"../core":65,"../core/sprites/canvas/CanvasTinter":104}],138:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _BaseTexture = require('../core/textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _utils = require('../core/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DisplayObject = core.DisplayObject; +var _tempMatrix = new core.Matrix(); + +DisplayObject.prototype._cacheAsBitmap = false; +DisplayObject.prototype._cacheData = false; + +// figured theres no point adding ALL the extra variables to prototype. +// this model can hold the information needed. This can also be generated on demand as +// most objects are not cached as bitmaps. +/** + * @class + * @ignore + */ + +var CacheData = +/** + * + */ +function CacheData() { + _classCallCheck(this, CacheData); + + this.textureCacheId = null; + + this.originalRenderWebGL = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + + this.originalUpdateTransform = null; + this.originalHitTest = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.sprite = null; +}; + +Object.defineProperties(DisplayObject.prototype, { + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to 'false' + * + * IMPORTANT GOTCHA - make sure that all your textures are preloaded BEFORE setting this property to true + * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function get() { + return this._cacheAsBitmap; + }, + set: function set(value) { + if (this._cacheAsBitmap === value) { + return; + } + + this._cacheAsBitmap = value; + + var data = void 0; + + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + + data = this._cacheData; + + data.originalRenderWebGL = this.renderWebGL; + data.originalRenderCanvas = this.renderCanvas; + + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this._calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + + data.originalDestroy = this.destroy; + + data.originalContainsPoint = this.containsPoint; + + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + + this.renderWebGL = this._renderCachedWebGL; + this.renderCanvas = this._renderCachedCanvas; + + this.destroy = this._cacheAsBitmapDestroy; + } else { + data = this._cacheData; + + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + + this.renderWebGL = data.originalRenderWebGL; + this.renderCanvas = data.originalRenderCanvas; + this._calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + + this.destroy = data.originalDestroy; + + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + } + } +}); + +/** + * Renders a cached version of the sprite with WebGL + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedWebGL = function _renderCachedWebGL(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObject(renderer); + + this._cacheData.sprite._transformID = -1; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderWebGL(renderer); +}; + +/** + * Prepares the WebGL renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + + this.alpha = 1; + + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.currentRenderer.flush(); + // this.filters= []; + + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds().clone(); + + // add some padding! + if (this._filters) { + var padding = this._filters[0].padding; + + bounds.pad(padding); + } + + // for now we cache the current renderTarget that the webGL renderer is currently using. + // this could be more elegent.. + var cachedRenderTarget = renderer._activeRenderTarget; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + var stack = renderer.filterManager.filterStack; + + // this renderTexture will be used to store the cached DisplayObject + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); + + this._cacheData.textureCacheId = textureCacheId; + + _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); + _Texture2.default.addToCache(renderTexture, textureCacheId); + + // need to set // + var m = _tempMatrix; + + m.tx = -bounds.x; + m.ty = -bounds.y; + + // reset + this.transform.worldTransform.identity(); + + // set all properties to there original so we can render to a texture + this.renderWebGL = this._cacheData.originalRenderWebGL; + + renderer.render(this, renderTexture, true, m, true); + // now restore the state be setting the new properties + + renderer.bindRenderTarget(cachedRenderTarget); + + renderer.filterManager.filterStack = stack; + + this.renderWebGL = this._renderCachedWebGL; + this.updateTransform = this.displayObjectUpdateTransform; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + + // easy bounds.. + this._calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + + this._cacheData.sprite = cachedSprite; + + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this.updateTransform(); + } + + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Renders a cached version of the sprite with canvas + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObjectCanvas(renderer); + + this._cacheData.sprite.worldAlpha = this.worldAlpha; + + this._cacheData.sprite.renderCanvas(renderer); +}; + +// TODO this can be the same as the webGL verison.. will need to do a little tweaking first though.. +/** + * Prepares the Canvas renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(); + + var cacheAlpha = this.alpha; + + this.alpha = 1; + + var cachedRenderTarget = renderer.context; + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); + + this._cacheData.textureCacheId = textureCacheId; + + _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); + _Texture2.default.addToCache(renderTexture, textureCacheId); + + // need to set // + var m = _tempMatrix; + + this.transform.localTransform.copy(m); + m.invert(); + + m.tx -= bounds.x; + m.ty -= bounds.y; + + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + + // renderTexture.render(this, m, true); + renderer.render(this, renderTexture, true, m, false); + + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + + this.renderCanvas = this._renderCachedCanvas; + this._calculateBounds = this._calculateCachedBounds; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite._bounds = this._bounds; + cachedSprite.alpha = cacheAlpha; + + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this.updateTransform(); + } + + this.updateTransform = this.displayObjectUpdateTransform; + + this._cacheData.sprite = cachedSprite; + + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Calculates the bounds of the cached sprite + * + * @private + */ +DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._cacheData.sprite._calculateBounds(); +}; + +/** + * Gets the bounds of the cached sprite. + * + * @private + * @return {Rectangle} The local bounds. + */ +DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(); +}; + +/** + * Destroys the cached sprite. + * + * @private + */ +DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; + + _BaseTexture2.default.removeFromCache(this._cacheData.textureCacheId); + _Texture2.default.removeFromCache(this._cacheData.textureCacheId); + + this._cacheData.textureCacheId = null; +}; + +/** + * Destroys the cached object. + * + * @private + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * Used when destroying containers, see the Container.destroy method. + */ +DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { + this.cacheAsBitmap = false; + this.destroy(options); +}; + +},{"../core":65,"../core/textures/BaseTexture":112,"../core/textures/Texture":115,"../core/utils":125}],139:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * The instance name of the object. + * + * @memberof PIXI.DisplayObject# + * @member {string} name + */ +core.DisplayObject.prototype.name = null; + +/** + * Returns the display object in the container + * + * @method getChildByName + * @memberof PIXI.Container# + * @param {string} name - instance name + * @return {PIXI.DisplayObject} The child with the specified name. + */ +core.Container.prototype.getChildByName = function getChildByName(name) { + for (var i = 0; i < this.children.length; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + + return null; +}; + +},{"../core":65}],140:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. + * + * @method getGlobalPosition + * @memberof PIXI.DisplayObject# + * @param {Point} point - the point to write the global value to. If null a new point will be returned + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @return {Point} The updated point + */ +core.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition() { + var point = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new core.Point(); + var skipUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (this.parent) { + this.parent.toGlobal(this.position, point, skipUpdate); + } else { + point.x = this.position.x; + point.y = this.position.y; + } + + return point; +}; + +},{"../core":65}],141:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BitmapText = exports.TilingSpriteRenderer = exports.TilingSprite = exports.AnimatedSprite = undefined; + +var _AnimatedSprite = require('./AnimatedSprite'); + +Object.defineProperty(exports, 'AnimatedSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AnimatedSprite).default; + } +}); + +var _TilingSprite = require('./TilingSprite'); + +Object.defineProperty(exports, 'TilingSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSprite).default; + } +}); + +var _TilingSpriteRenderer = require('./webgl/TilingSpriteRenderer'); + +Object.defineProperty(exports, 'TilingSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSpriteRenderer).default; + } +}); + +var _BitmapText = require('./BitmapText'); + +Object.defineProperty(exports, 'BitmapText', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BitmapText).default; + } +}); + +require('./cacheAsBitmap'); + +require('./getChildByName'); + +require('./getGlobalPosition'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// imported for side effect of extending the prototype only, contains no exports + +},{"./AnimatedSprite":135,"./BitmapText":136,"./TilingSprite":137,"./cacheAsBitmap":138,"./getChildByName":139,"./getGlobalPosition":140,"./webgl/TilingSpriteRenderer":142}],142:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _const = require('../../core/const'); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMat = new core.Matrix(); + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI.extras + * @extends PIXI.ObjectRenderer + */ + +var TilingSpriteRenderer = function (_core$ObjectRenderer) { + _inherits(TilingSpriteRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function TilingSpriteRenderer(renderer) { + _classCallCheck(this, TilingSpriteRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + _this.simpleShader = null; + _this.quad = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + TilingSpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n gl_FragColor = sample * uColor;\n}\n'); + this.simpleShader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = sample * uColor;\n}\n'); + + this.renderer.bindVao(null); + this.quad = new core.Quad(gl, this.renderer.state.attribState); + this.quad.initVao(this.shader); + }; + + /** + * + * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered + */ + + + TilingSpriteRenderer.prototype.render = function render(ts) { + var renderer = this.renderer; + var quad = this.quad; + + renderer.bindVao(quad.vao); + + var vertices = quad.vertices; + + vertices[0] = vertices[6] = ts._width * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + + vertices[2] = vertices[4] = ts._width * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + + if (ts.uvRespectAnchor) { + vertices = quad.uvs; + + vertices[0] = vertices[6] = -ts.anchor.x; + vertices[1] = vertices[3] = -ts.anchor.y; + + vertices[2] = vertices[4] = 1.0 - ts.anchor.x; + vertices[5] = vertices[7] = 1.0 - ts.anchor.y; + } + + quad.upload(); + + var tex = ts._texture; + var baseTex = tex.baseTexture; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvTransform; + var isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === _const.WRAP_MODES.CLAMP) { + baseTex.wrapMode = _const.WRAP_MODES.REPEAT; + } + } else { + isSimple = baseTex.wrapMode !== _const.WRAP_MODES.CLAMP; + } + } + + var shader = isSimple ? this.simpleShader : this.shader; + + renderer.bindShader(shader); + + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + + tempMat.invert(); + if (isSimple) { + tempMat.prepend(uv.mapCoord); + } else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + + shader.uniforms.uTransform = tempMat.toArray(true); + shader.uniforms.uColor = core.utils.premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, baseTex.premultipliedAlpha); + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + + shader.uniforms.uSampler = renderer.bindTexture(tex); + + renderer.setBlendMode(core.utils.correctBlendMode(ts.blendMode, baseTex.premultipliedAlpha)); + + quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + }; + + return TilingSpriteRenderer; +}(core.ObjectRenderer); + +exports.default = TilingSpriteRenderer; + + +core.WebGLRenderer.registerPlugin('tilingSprite', TilingSpriteRenderer); + +},{"../../core":65,"../../core/const":46,"path":8}],143:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Simplest filter - applies alpha + * + * Use this instead of Container's alpha property to avoid visual layering of individual elements. + * AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains. + * If elements are not opaque, they will blend with each other anyway. + * + * Very handy if you want to use common features of all filters: + * + * 1. Assign a blendMode to this filter, blend all elements inside display object with background. + * + * 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var AlphaFilter = function (_core$Filter) { + _inherits(AlphaFilter, _core$Filter); + + /** + * @param {number} [alpha=1] Amount of alpha from 0 to 1, where 0 is transparent + */ + function AlphaFilter() { + var alpha = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1.0; + + _classCallCheck(this, AlphaFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n')); + + _this.alpha = alpha; + _this.glShaderKey = 'alpha'; + return _this; + } + + /** + * Coefficient for alpha multiplication + * + * @member {number} + * @default 1 + */ + + + _createClass(AlphaFilter, [{ + key: 'alpha', + get: function get() { + return this.uniforms.uAlpha; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uAlpha = value; + } + }]); + + return AlphaFilter; +}(core.Filter); + +exports.default = AlphaFilter; + +},{"../../core":65,"path":8}],144:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BlurXFilter = require('./BlurXFilter'); + +var _BlurXFilter2 = _interopRequireDefault(_BlurXFilter); + +var _BlurYFilter = require('./BlurYFilter'); + +var _BlurYFilter2 = _interopRequireDefault(_BlurYFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurFilter applies a Gaussian blur to an object. + * The strength of the blur can be set for x- and y-axis separately. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurFilter = function (_core$Filter) { + _inherits(BlurFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this)); + + _this.blurXFilter = new _BlurXFilter2.default(strength, quality, resolution, kernelSize); + _this.blurYFilter = new _BlurYFilter2.default(strength, quality, resolution, kernelSize); + + _this.padding = 0; + _this.resolution = resolution || core.settings.RESOLUTION; + _this.quality = quality || 4; + _this.blur = strength || 8; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + BlurFilter.prototype.apply = function apply(filterManager, input, output) { + var renderTarget = filterManager.getRenderTarget(true); + + this.blurXFilter.apply(filterManager, input, renderTarget, true); + this.blurYFilter.apply(filterManager, renderTarget, output, false); + + filterManager.returnRenderTarget(renderTarget); + }; + + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurFilter, [{ + key: 'blur', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the number of passes for blur. More passes means higher quaility bluring. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'quality', + get: function get() { + return this.blurXFilter.quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.quality = this.blurYFilter.quality = value; + } + + /** + * Sets the strength of the blurX property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurX', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the strength of the blurY property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurY', + get: function get() { + return this.blurYFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the blendmode of the filter + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + */ + + }, { + key: 'blendMode', + get: function get() { + return this.blurYFilter._blendMode; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter._blendMode = value; + } + }]); + + return BlurFilter; +}(core.Filter); + +exports.default = BlurFilter; + +},{"../../core":65,"./BlurXFilter":145,"./BlurYFilter":146}],145:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurXFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurXFilter = function (_core$Filter) { + _inherits(BlurXFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurXFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurXFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurXFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.width * (output.size.width / input.size.width); + + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; // / this.passes//Math.pow(1, this.passes); + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 16 + */ + + + _createClass(BlurXFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurXFilter; +}(core.Filter); + +exports.default = BlurXFilter; + +},{"../../core":65,"./generateBlurFragSource":147,"./generateBlurVertSource":148,"./getMaxBlurKernelSize":149}],146:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurYFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurYFilter = function (_core$Filter) { + _inherits(BlurYFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurYFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurYFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurYFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.height * (output.size.height / input.size.height); + + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurYFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurYFilter; +}(core.Filter); + +exports.default = BlurYFilter; + +},{"../../core":65,"./generateBlurFragSource":147,"./generateBlurVertSource":148,"./getMaxBlurKernelSize":149}],147:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateFragBlurSource; +var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] +}; + +var fragTemplate = ['varying vec2 vBlurTexCoords[%size%];', 'uniform sampler2D uSampler;', 'void main(void)', '{', ' gl_FragColor = vec4(0.0);', ' %blur%', '}'].join('\n'); + +function generateFragBlurSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + + var fragSource = fragTemplate; + + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value = void 0; + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + value = i; + + if (i >= halfLength) { + value = kernelSize - i - 1; + } + + blur = blur.replace('%value%', kernel[value]); + + blurLoop += blur; + blurLoop += '\n'; + } + + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize); + + return fragSource; +} + +},{}],148:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateVertBlurSource; +var vertTemplate = ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform float strength;', 'uniform mat3 projectionMatrix;', 'varying vec2 vBlurTexCoords[%size%];', 'void main(void)', '{', 'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);', '%blur%', '}'].join('\n'); + +function generateVertBlurSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + + var vertSource = vertTemplate; + + var blurLoop = ''; + var template = void 0; + // let value; + + if (x) { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } else { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + // value = i; + + // if(i >= halfLength) + // { + // value = kernelSize - i - 1; + // } + + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + '.0'); + + blurLoop += blur; + blurLoop += '\n'; + } + + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize); + + return vertSource; +} + +},{}],149:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = getMaxKernelSize; +function getMaxKernelSize(gl) { + var maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + var kernelSize = 15; + + while (kernelSize > maxVaryings) { + kernelSize -= 2; + } + + return kernelSize; +} + +},{}],150:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.filters.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var ColorMatrixFilter = function (_core$Filter) { + _inherits(ColorMatrixFilter, _core$Filter); + + /** + * + */ + function ColorMatrixFilter() { + _classCallCheck(this, ColorMatrixFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n')); + + _this.uniforms.m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + _this.alpha = 1; + return _this; + } + + /** + * Transforms current matrix and set the new one + * + * @param {number[]} matrix - 5x4 matrix + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix(matrix) { + var multiply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + var newMatrix = matrix; + + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + + // set the new matrix + this.uniforms.m = newMatrix; + }; + + /** + * Multiplies two mat5's + * + * @private + * @param {number[]} out - 5x4 matrix the receiving matrix + * @param {number[]} a - 5x4 matrix the first operand + * @param {number[]} b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix + */ + + + ColorMatrixFilter.prototype._multiply = function _multiply(out, a, b) { + // Red Channel + out[0] = a[0] * b[0] + a[1] * b[5] + a[2] * b[10] + a[3] * b[15]; + out[1] = a[0] * b[1] + a[1] * b[6] + a[2] * b[11] + a[3] * b[16]; + out[2] = a[0] * b[2] + a[1] * b[7] + a[2] * b[12] + a[3] * b[17]; + out[3] = a[0] * b[3] + a[1] * b[8] + a[2] * b[13] + a[3] * b[18]; + out[4] = a[0] * b[4] + a[1] * b[9] + a[2] * b[14] + a[3] * b[19] + a[4]; + + // Green Channel + out[5] = a[5] * b[0] + a[6] * b[5] + a[7] * b[10] + a[8] * b[15]; + out[6] = a[5] * b[1] + a[6] * b[6] + a[7] * b[11] + a[8] * b[16]; + out[7] = a[5] * b[2] + a[6] * b[7] + a[7] * b[12] + a[8] * b[17]; + out[8] = a[5] * b[3] + a[6] * b[8] + a[7] * b[13] + a[8] * b[18]; + out[9] = a[5] * b[4] + a[6] * b[9] + a[7] * b[14] + a[8] * b[19] + a[9]; + + // Blue Channel + out[10] = a[10] * b[0] + a[11] * b[5] + a[12] * b[10] + a[13] * b[15]; + out[11] = a[10] * b[1] + a[11] * b[6] + a[12] * b[11] + a[13] * b[16]; + out[12] = a[10] * b[2] + a[11] * b[7] + a[12] * b[12] + a[13] * b[17]; + out[13] = a[10] * b[3] + a[11] * b[8] + a[12] * b[13] + a[13] * b[18]; + out[14] = a[10] * b[4] + a[11] * b[9] + a[12] * b[14] + a[13] * b[19] + a[14]; + + // Alpha Channel + out[15] = a[15] * b[0] + a[16] * b[5] + a[17] * b[10] + a[18] * b[15]; + out[16] = a[15] * b[1] + a[16] * b[6] + a[17] * b[11] + a[18] * b[16]; + out[17] = a[15] * b[2] + a[16] * b[7] + a[17] * b[12] + a[18] * b[17]; + out[18] = a[15] * b[3] + a[16] * b[8] + a[17] * b[13] + a[18] * b[18]; + out[19] = a[15] * b[4] + a[16] * b[9] + a[17] * b[14] + a[18] * b[19] + a[19]; + + return out; + }; + + /** + * Create a Float32 Array and normalize the offset component to 0-1 + * + * @private + * @param {number[]} matrix - 5x4 matrix + * @return {number[]} 5x4 matrix with all values between 0-1 + */ + + + ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix(matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + + return m; + }; + + /** + * Adjusts brightness + * + * @param {number} b - value of the brigthness (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.brightness = function brightness(b, multiply) { + var matrix = [b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the matrices in grey scales + * + * @param {number} scale - value of the grey (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.greyscale = function greyscale(scale, multiply) { + var matrix = [scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the black and white matrice. + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite(multiply) { + var matrix = [0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the hue property of the color + * + * @param {number} rotation - in degrees + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.hue = function hue(rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + + var a00 = cosR + (1.0 - cosR) * w; + var a01 = w * (1.0 - cosR) - sqrW * sinR; + var a02 = w * (1.0 - cosR) + sqrW * sinR; + + var a10 = w * (1.0 - cosR) + sqrW * sinR; + var a11 = cosR + w * (1.0 - cosR); + var a12 = w * (1.0 - cosR) - sqrW * sinR; + + var a20 = w * (1.0 - cosR) - sqrW * sinR; + var a21 = w * (1.0 - cosR) + sqrW * sinR; + var a22 = cosR + w * (1.0 - cosR); + + var matrix = [a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * + * @param {number} amount - value of the contrast (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.contrast = function contrast(amount, multiply) { + var v = (amount || 0) + 1; + var o = -0.5 * (v - 1); + + var matrix = [v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * + * @param {number} amount - The saturation amount (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.saturate = function saturate() { + var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var multiply = arguments[1]; + + var x = amount * 2 / 3 + 1; + var y = (x - 1) * -0.5; + + var matrix = [x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Desaturate image (remove color) + * + * Call the saturate function + * + */ + + + ColorMatrixFilter.prototype.desaturate = function desaturate() // eslint-disable-line no-unused-vars + { + this.saturate(-1); + }; + + /** + * Negative image (inverse of classic rgb matrix) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.negative = function negative(multiply) { + var matrix = [-1, 0, 0, 1, 0, 0, -1, 0, 1, 0, 0, 0, -1, 1, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Sepia image + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.sepia = function sepia(multiply) { + var matrix = [0.393, 0.7689999, 0.18899999, 0, 0, 0.349, 0.6859999, 0.16799999, 0, 0, 0.272, 0.5339999, 0.13099999, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.technicolor = function technicolor(multiply) { + var matrix = [1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Polaroid filter + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.polaroid = function polaroid(multiply) { + var matrix = [1.438, -0.062, -0.062, 0, 0, -0.122, 1.378, -0.122, 0, 0, -0.016, -0.016, 1.483, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Filter who transforms : Red -> Blue and Blue -> Red + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.toBGR = function toBGR(multiply) { + var matrix = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.kodachrome = function kodachrome(multiply) { + var matrix = [1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Brown delicious browni filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.browni = function browni(multiply) { + var matrix = [0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Vintage filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.vintage = function vintage(multiply) { + var matrix = [0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * + * @param {number} desaturation - Tone values. + * @param {number} toned - Tone values. + * @param {string} lightColor - Tone values, example: `0xFFE580` + * @param {string} darkColor - Tone values, example: `0xFFE580` + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.colorTone = function colorTone(desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + + var lR = (lightColor >> 16 & 0xFF) / 255; + var lG = (lightColor >> 8 & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + + var dR = (darkColor >> 16 & 0xFF) / 255; + var dG = (darkColor >> 8 & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + + var matrix = [0.3, 0.59, 0.11, 0, 0, lR, lG, lB, desaturation, 0, dR, dG, dB, toned, 0, lR - dR, lG - dG, lB - dB, 0, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Night effect + * + * @param {number} intensity - The intensity of the night effect. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.night = function night(intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [intensity * -2.0, -intensity, 0, 0, 0, -intensity, 0, intensity, 0, 0, 0, intensity, intensity * 2.0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * + * @param {number} amount - how much the predator feels his future victim + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.predator = function predator(amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * LSD effect + * + * Multiply the current matrix + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.lsd = function lsd(multiply) { + var matrix = [2, -0.4, 0.5, 0, 0, -0.5, 2, -0.4, 0, 0, -0.4, -0.5, 3, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Erase the current matrix by setting the default one + * + */ + + + ColorMatrixFilter.prototype.reset = function reset() { + var matrix = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, false); + }; + + /** + * The matrix of the color matrix filter + * + * @member {number[]} + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + + + _createClass(ColorMatrixFilter, [{ + key: 'matrix', + get: function get() { + return this.uniforms.m; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.m = value; + } + + /** + * The opacity value to use when mixing the original and resultant colors. + * + * When the value is 0, the original color is used without modification. + * When the value is 1, the result color is used. + * When in the range (0, 1) the color is interpolated between the original and result by this amount. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'alpha', + get: function get() { + return this.uniforms.uAlpha; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uAlpha = value; + } + }]); + + return ColorMatrixFilter; +}(core.Filter); + +// Americanized alias + + +exports.default = ColorMatrixFilter; +ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + +},{"../../core":65,"path":8}],151:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. You can + * use this filter to apply all manor of crazy warping effects. Currently the r + * property of the texture is used to offset the x and the g property of the texture + * is used to offset the y. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var DisplacementFilter = function (_core$Filter) { + _inherits(DisplacementFilter, _core$Filter); + + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param {number} scale - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + _classCallCheck(this, DisplacementFilter); + + var maskMatrix = new core.Matrix(); + + sprite.renderable = false; + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale / filterArea.xy;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n')); + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + + _this.uniforms.mapSampler = sprite._texture; + _this.uniforms.filterMatrix = maskMatrix; + _this.uniforms.scale = { x: 1, y: 1 }; + + if (scale === null || scale === undefined) { + scale = 20; + } + + _this.scale = new core.Point(scale, scale); + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + DisplacementFilter.prototype.apply = function apply(filterManager, input, output) { + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x; + this.uniforms.scale.y = this.scale.y; + + // draw the filter... + filterManager.applyFilter(this, input, output); + }; + + /** + * The texture used for the displacement map. Must be power of 2 sized texture. + * + * @member {PIXI.Texture} + */ + + + _createClass(DisplacementFilter, [{ + key: 'map', + get: function get() { + return this.uniforms.mapSampler; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.mapSampler = value; + } + }]); + + return DisplacementFilter; +}(core.Filter); + +exports.default = DisplacementFilter; + +},{"../../core":65,"path":8}],152:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * Basic FXAA implementation based on the code on geeks3d.com with the + * modification that the texture2DLod stuff was removed since it's + * unsupported by WebGL. + * + * @see https://github.com/mitsuhiko/webgl-meincraft + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + * + */ +var FXAAFilter = function (_core$Filter) { + _inherits(FXAAFilter, _core$Filter); + + /** + * + */ + function FXAAFilter() { + _classCallCheck(this, FXAAFilter); + + // TODO - needs work + return _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + '\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}', + // fragment shader + 'varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n')); + } + + return FXAAFilter; +}(core.Filter); + +exports.default = FXAAFilter; + +},{"../../core":65,"path":8}],153:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _FXAAFilter = require('./fxaa/FXAAFilter'); + +Object.defineProperty(exports, 'FXAAFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_FXAAFilter).default; + } +}); + +var _NoiseFilter = require('./noise/NoiseFilter'); + +Object.defineProperty(exports, 'NoiseFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NoiseFilter).default; + } +}); + +var _DisplacementFilter = require('./displacement/DisplacementFilter'); + +Object.defineProperty(exports, 'DisplacementFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplacementFilter).default; + } +}); + +var _BlurFilter = require('./blur/BlurFilter'); + +Object.defineProperty(exports, 'BlurFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurFilter).default; + } +}); + +var _BlurXFilter = require('./blur/BlurXFilter'); + +Object.defineProperty(exports, 'BlurXFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurXFilter).default; + } +}); + +var _BlurYFilter = require('./blur/BlurYFilter'); + +Object.defineProperty(exports, 'BlurYFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurYFilter).default; + } +}); + +var _ColorMatrixFilter = require('./colormatrix/ColorMatrixFilter'); + +Object.defineProperty(exports, 'ColorMatrixFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ColorMatrixFilter).default; + } +}); + +var _AlphaFilter = require('./alpha/AlphaFilter'); + +Object.defineProperty(exports, 'AlphaFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AlphaFilter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./alpha/AlphaFilter":143,"./blur/BlurFilter":144,"./blur/BlurXFilter":145,"./blur/BlurYFilter":146,"./colormatrix/ColorMatrixFilter":150,"./displacement/DisplacementFilter":151,"./fxaa/FXAAFilter":152,"./noise/NoiseFilter":154}],154:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Vico @vicocotea + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + */ + +/** + * A Noise effect filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var NoiseFilter = function (_core$Filter) { + _inherits(NoiseFilter, _core$Filter); + + /** + * @param {number} noise - The noise intensity, should be a normalized value in the range [0, 1]. + * @param {number} seed - A random seed for the noise generation. Default is `Math.random()`. + */ + function NoiseFilter() { + var noise = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0.5; + var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Math.random(); + + _classCallCheck(this, NoiseFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n')); + + _this.noise = noise; + _this.seed = seed; + return _this; + } + + /** + * The amount of noise to apply, this value should be in the range (0, 1]. + * + * @member {number} + * @default 0.5 + */ + + + _createClass(NoiseFilter, [{ + key: 'noise', + get: function get() { + return this.uniforms.uNoise; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uNoise = value; + } + + /** + * A seed value to apply to the random noise generation. `Math.random()` is a good value to use. + * + * @member {number} + */ + + }, { + key: 'seed', + get: function get() { + return this.uniforms.uSeed; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uSeed = value; + } + }]); + + return NoiseFilter; +}(core.Filter); + +exports.default = NoiseFilter; + +},{"../../core":65,"path":8}],155:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Holds all information related to an Interaction event + * + * @class + * @memberof PIXI.interaction + */ +var InteractionData = function () { + /** + * + */ + function InteractionData() { + _classCallCheck(this, InteractionData); + + /** + * This point stores the global coords of where the touch/mouse event happened + * + * @member {PIXI.Point} + */ + this.global = new core.Point(); + + /** + * The target DisplayObject that was interacted with + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * When passed to an event handler, this will be the original DOM Event that was captured + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent + * @see https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent + * @member {MouseEvent|TouchEvent|PointerEvent} + */ + this.originalEvent = null; + + /** + * Unique identifier for this interaction + * + * @member {number} + */ + this.identifier = null; + + /** + * Indicates whether or not the pointer device that created the event is the primary pointer. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary + * @type {Boolean} + */ + this.isPrimary = false; + + /** + * Indicates which button was pressed on the mouse or pointer device to trigger the event. + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button + * @type {number} + */ + this.button = 0; + + /** + * Indicates which buttons are pressed on the mouse or pointer device when the event is triggered. + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons + * @type {number} + */ + this.buttons = 0; + + /** + * The width of the pointer's contact along the x-axis, measured in CSS pixels. + * radiusX of TouchEvents will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width + * @type {number} + */ + this.width = 0; + + /** + * The height of the pointer's contact along the y-axis, measured in CSS pixels. + * radiusY of TouchEvents will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height + * @type {number} + */ + this.height = 0; + + /** + * The angle, in degrees, between the pointer device and the screen. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX + * @type {number} + */ + this.tiltX = 0; + + /** + * The angle, in degrees, between the pointer device and the screen. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY + * @type {number} + */ + this.tiltY = 0; + + /** + * The type of pointer that triggered the event. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType + * @type {string} + */ + this.pointerType = null; + + /** + * Pressure applied by the pointing device during the event. A Touch's force property + * will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure + * @type {number} + */ + this.pressure = 0; + + /** + * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch. + * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle + * @type {number} + */ + this.rotationAngle = 0; + + /** + * Twist of a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + * @type {number} + */ + this.twist = 0; + + /** + * Barrel pressure on a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + * @type {number} + */ + this.tangentialPressure = 0; + } + + /** + * The unique identifier of the pointer. It will be the same as `identifier`. + * @readonly + * @member {number} + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId + */ + + + /** + * This will return the local coordinates of the specified displayObject for this InteractionData + * + * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local + * coords off + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative + * to the DisplayObject + */ + InteractionData.prototype.getLocalPosition = function getLocalPosition(displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + + /** + * Copies properties from normalized event data. + * + * @param {Touch|MouseEvent|PointerEvent} event The normalized event data + */ + + + InteractionData.prototype.copyEvent = function copyEvent(event) { + // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite + // it with "false" on later events when our shim for it on touch events might not be + // accurate + if (event.isPrimary) { + this.isPrimary = true; + } + this.button = event.button; + // event.buttons is not available in all browsers (ie. Safari), but it does have a non-standard + // event.which property instead, which conveys the same information. + this.buttons = Number.isInteger(event.buttons) ? event.buttons : event.which; + this.width = event.width; + this.height = event.height; + this.tiltX = event.tiltX; + this.tiltY = event.tiltY; + this.pointerType = event.pointerType; + this.pressure = event.pressure; + this.rotationAngle = event.rotationAngle; + this.twist = event.twist || 0; + this.tangentialPressure = event.tangentialPressure || 0; + }; + + /** + * Resets the data for pooling. + */ + + + InteractionData.prototype.reset = function reset() { + // isPrimary is the only property that we really need to reset - everything else is + // guaranteed to be overwritten + this.isPrimary = false; + }; + + _createClass(InteractionData, [{ + key: 'pointerId', + get: function get() { + return this.identifier; + } + }]); + + return InteractionData; +}(); + +exports.default = InteractionData; + +},{"../core":65}],156:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Event class that mimics native DOM events. + * + * @class + * @memberof PIXI.interaction + */ +var InteractionEvent = function () { + /** + * + */ + function InteractionEvent() { + _classCallCheck(this, InteractionEvent); + + /** + * Whether this event will continue propagating in the tree + * + * @member {boolean} + */ + this.stopped = false; + + /** + * The object which caused this event to be dispatched. + * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}. + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * The object whose event listener’s callback is currently being invoked. + * + * @member {PIXI.DisplayObject} + */ + this.currentTarget = null; + + /** + * Type of the event + * + * @member {string} + */ + this.type = null; + + /** + * InteractionData related to this event + * + * @member {PIXI.interaction.InteractionData} + */ + this.data = null; + } + + /** + * Prevents event from reaching any objects other than the current object. + * + */ + + + InteractionEvent.prototype.stopPropagation = function stopPropagation() { + this.stopped = true; + }; + + /** + * Resets the event. + */ + + + InteractionEvent.prototype.reset = function reset() { + this.stopped = false; + this.currentTarget = null; + this.target = null; + }; + + return InteractionEvent; +}(); + +exports.default = InteractionEvent; + +},{}],157:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _InteractionData = require('./InteractionData'); + +var _InteractionData2 = _interopRequireDefault(_InteractionData); + +var _InteractionEvent = require('./InteractionEvent'); + +var _InteractionEvent2 = _interopRequireDefault(_InteractionEvent); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +var _InteractionTrackingData2 = _interopRequireDefault(_InteractionTrackingData); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _interactiveTarget = require('./interactiveTarget'); + +var _interactiveTarget2 = _interopRequireDefault(_interactiveTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// Mix interactiveTarget into core.DisplayObject.prototype, after deprecation has been handled +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _interactiveTarget2.default); + +var MOUSE_POINTER_ID = 1; + +// helpers for hitTest() - only used inside hitTest() +var hitTestEvent = { + target: null, + data: { + global: null + } +}; + +/** + * The interaction manager deals with mouse, touch and pointer events. Any DisplayObject can be interactive + * if its interactive parameter is set to true + * This manager also supports multitouch. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.interaction + * + * @class + * @extends EventEmitter + * @memberof PIXI.interaction + */ + +var InteractionManager = function (_EventEmitter) { + _inherits(InteractionManager, _EventEmitter); + + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + * @param {object} [options] - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Frequency increases the interaction events will be checked. + */ + function InteractionManager(renderer, options) { + _classCallCheck(this, InteractionManager); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + options = options || {}; + + /** + * The renderer this interaction manager works for. + * + * @member {PIXI.SystemRenderer} + */ + _this.renderer = renderer; + + /** + * Should default browser actions automatically be prevented. + * Does not apply to pointer events for backwards compatibility + * preventDefault on pointer events stops mouse events from firing + * Thus, for every pointer event, there will always be either a mouse of touch event alongside it. + * + * @member {boolean} + * @default true + */ + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + + /** + * Frequency in milliseconds that the mousemove, moveover & mouseout interaction events will be checked. + * + * @member {number} + * @default 10 + */ + _this.interactionFrequency = options.interactionFrequency || 10; + + /** + * The mouse data + * + * @member {PIXI.interaction.InteractionData} + */ + _this.mouse = new _InteractionData2.default(); + _this.mouse.identifier = MOUSE_POINTER_ID; + + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + + /** + * Actively tracked InteractionData + * + * @private + * @member {Object.} + */ + _this.activeInteractionData = {}; + _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; + + /** + * Pool of unused InteractionData + * + * @private + * @member {PIXI.interation.InteractionData[]} + */ + _this.interactionDataPool = []; + + /** + * An event data object to handle all the event tracking/dispatching + * + * @member {object} + */ + _this.eventData = new _InteractionEvent2.default(); + + /** + * The DOM element to bind to. + * + * @private + * @member {HTMLElement} + */ + _this.interactionDOMElement = null; + + /** + * This property determines if mousemove and touchmove events are fired only when the cursor + * is over the object. + * Setting to true will make things work more in line with how the DOM verison works. + * Setting to false can make things easier for things like dragging + * It is currently set to false as this is how PixiJS used to work. This will be set to true in + * future versions of pixi. + * + * @member {boolean} + * @default false + */ + _this.moveWhenInside = false; + + /** + * Have events been attached to the dom element? + * + * @private + * @member {boolean} + */ + _this.eventsAdded = false; + + /** + * Is the mouse hovering over the renderer? + * + * @private + * @member {boolean} + */ + _this.mouseOverRenderer = false; + + /** + * Does the device support touch events + * https://www.w3.org/TR/touch-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsTouchEvents = 'ontouchstart' in window; + + /** + * Does the device support pointer events + * https://www.w3.org/Submission/pointer-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsPointerEvents = !!window.PointerEvent; + + // this will make it so that you don't have to call bind all the time + + /** + * @private + * @member {Function} + */ + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerCancel = _this.onPointerCancel.bind(_this); + _this.processPointerCancel = _this.processPointerCancel.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOver = _this.onPointerOver.bind(_this); + + /** + * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor + * values, objects are handled as dictionaries of CSS values for interactionDOMElement, + * and functions are called instead of changing the CSS. + * Default CSS cursor values are provided for 'default' and 'pointer' modes. + * @member {Object.)>} + */ + _this.cursorStyles = { + default: 'inherit', + pointer: 'pointer' + }; + + /** + * The mode of the cursor that is being used. + * The value of this is a key from the cursorStyles dictionary. + * + * @member {string} + */ + _this.currentCursorMode = null; + + /** + * Internal cached let. + * + * @private + * @member {string} + */ + _this.cursor = null; + + /** + * Internal cached let. + * + * @private + * @member {PIXI.Point} + */ + _this._tempPoint = new core.Point(); + + /** + * The current resolution / device pixel ratio. + * + * @member {number} + * @default 1 + */ + _this.resolution = 1; + + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display + * object. + * + * @event PIXI.interaction.InteractionManager#mousedown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * + * @event PIXI.interaction.InteractionManager#rightdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. + * + * @event PIXI.interaction.InteractionManager#mouseup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * + * @event PIXI.interaction.InteractionManager#rightup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. + * + * @event PIXI.interaction.InteractionManager#click + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * + * @event PIXI.interaction.InteractionManager#rightclick + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. + * + * @event PIXI.interaction.InteractionManager#mouseupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. + * + * @event PIXI.interaction.InteractionManager#rightupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * + * @event PIXI.interaction.InteractionManager#mousemove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * + * @event PIXI.interaction.InteractionManager#mouseover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * + * @event PIXI.interaction.InteractionManager#mouseout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * + * @event PIXI.interaction.InteractionManager#pointerdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released over the display object. + * + * @event PIXI.interaction.InteractionManager#pointerup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a pointer event + * + * @event PIXI.interaction.InteractionManager#pointercancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * + * @event PIXI.interaction.InteractionManager#pointertap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}. + * + * @event PIXI.interaction.InteractionManager#pointerupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved while over the display object + * + * @event PIXI.interaction.InteractionManager#pointermove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved onto the display object + * + * @event PIXI.interaction.InteractionManager#pointerover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved off the display object + * + * @event PIXI.interaction.InteractionManager#pointerout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed on the display object. + * + * @event PIXI.interaction.InteractionManager#touchstart + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed from the display object. + * + * @event PIXI.interaction.InteractionManager#touchend + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a touch + * + * @event PIXI.interaction.InteractionManager#touchcancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * + * @event PIXI.interaction.InteractionManager#tap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. + * + * @event PIXI.interaction.InteractionManager#touchendoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is moved along the display object. + * + * @event PIXI.interaction.InteractionManager#touchmove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display. + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mousedown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#click + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightclick + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.DisplayObject#event:mousedown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.DisplayObject#event:rightdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mousemove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a pointer event. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointercancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointertap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointermove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchstart + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchend + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a touch. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchcancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#tap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchendoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is moved along the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchmove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + return _this; + } + + /** + * Hit tests a point against the display tree, returning the first interactive object that is hit. + * + * @param {PIXI.Point} globalPoint - A point to hit test with, in global space. + * @param {PIXI.Container} [root] - The root display object to start from. If omitted, defaults + * to the last rendered root of the associated renderer. + * @return {PIXI.DisplayObject} The hit display object, if any. + */ + + + InteractionManager.prototype.hitTest = function hitTest(globalPoint, root) { + // clear the target for our hit test + hitTestEvent.target = null; + // assign the global point + hitTestEvent.data.global = globalPoint; + // ensure safety of the root + if (!root) { + root = this.renderer._lastObjectRendered; + } + // run the hit test + this.processInteractive(hitTestEvent, root, null, true); + // return our found object - it'll be null if we didn't hit anything + + return hitTestEvent.target; + }; + + /** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate + * another DOM element to receive those events. + * + * @param {HTMLCanvasElement} element - the DOM element which will receive mouse and touch events. + * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). + */ + + + InteractionManager.prototype.setTargetElement = function setTargetElement(element) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.removeEvents(); + + this.interactionDOMElement = element; + + this.resolution = resolution; + + this.addEvents(); + }; + + /** + * Registers all the DOM events + * + * @private + */ + + + InteractionManager.prototype.addEvents = function addEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.INTERACTION); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; + this.interactionDOMElement.style['-ms-touch-action'] = 'none'; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = 'none'; + } + + /** + * These events are added first, so that if pointer events are normalised, they are fired + * in the same order as non-normalised events. ie. pointer event 1st, mouse / touch 2nd + */ + if (this.supportsPointerEvents) { + window.document.addEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); + // pointerout is fired in addition to pointerup (for touch events) and pointercancel + // we already handle those, so for the purposes of what we do in onPointerOut, we only + // care about the pointerleave event + this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); + window.addEventListener('pointercancel', this.onPointerCancel, true); + window.addEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.addEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); + window.addEventListener('mouseup', this.onPointerUp, true); + } + + // always look directly for touch events so that we can provide original data + // In a future version we should change this to being just a fallback and rely solely on + // PointerEvents whenever available + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); + } + + this.eventsAdded = true; + }; + + /** + * Removes all the DOM events that were previously registered + * + * @private + */ + + + InteractionManager.prototype.removeEvents = function removeEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.remove(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = ''; + this.interactionDOMElement.style['-ms-touch-action'] = ''; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = ''; + } + + if (this.supportsPointerEvents) { + window.document.removeEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); + window.removeEventListener('pointercancel', this.onPointerCancel, true); + window.removeEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.removeEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true); + window.removeEventListener('mouseup', this.onPointerUp, true); + } + + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); + } + + this.interactionDOMElement = null; + + this.eventsAdded = false; + }; + + /** + * Updates the state of interactive objects. + * Invoked by a throttled ticker update from {@link PIXI.ticker.shared}. + * + * @param {number} deltaTime - time delta since last tick + */ + + + InteractionManager.prototype.update = function update(deltaTime) { + this._deltaTime += deltaTime; + + if (this._deltaTime < this.interactionFrequency) { + return; + } + + this._deltaTime = 0; + + if (!this.interactionDOMElement) { + return; + } + + // if the user move the mouse this check has already been done using the mouse move! + if (this.didMove) { + this.didMove = false; + + return; + } + + this.cursor = null; + + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + for (var k in this.activeInteractionData) { + // eslint-disable-next-line no-prototype-builtins + if (this.activeInteractionData.hasOwnProperty(k)) { + var interactionData = this.activeInteractionData[k]; + + if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, true); + } + } + } + + this.setCursorMode(this.cursor); + + // TODO + }; + + /** + * Sets the current cursor mode, handling any callbacks or CSS style changes. + * + * @param {string} mode - cursor mode, a key from the cursorStyles dictionary + */ + + + InteractionManager.prototype.setCursorMode = function setCursorMode(mode) { + mode = mode || 'default'; + // if the mode didn't actually change, bail early + if (this.currentCursorMode === mode) { + return; + } + this.currentCursorMode = mode; + var style = this.cursorStyles[mode]; + + // only do things if there is a cursor style for it + if (style) { + switch (typeof style === 'undefined' ? 'undefined' : _typeof(style)) { + case 'string': + // string styles are handled as cursor CSS + this.interactionDOMElement.style.cursor = style; + break; + case 'function': + // functions are just called, and passed the cursor mode + style(mode); + break; + case 'object': + // if it is an object, assume that it is a dictionary of CSS styles, + // apply it to the interactionDOMElement + Object.assign(this.interactionDOMElement.style, style); + break; + } + } else if (typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) { + // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry + // for the mode, then assume that the dev wants it to be CSS for the cursor. + this.interactionDOMElement.style.cursor = mode; + } + }; + + /** + * Dispatches an event on the display object that was interacted with + * + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the display object in question + * @param {string} eventString - the name of the event (e.g, mousedown) + * @param {object} eventData - the event data object + * @private + */ + + + InteractionManager.prototype.dispatchEvent = function dispatchEvent(displayObject, eventString, eventData) { + if (!eventData.stopped) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + + displayObject.emit(eventString, eventData); + + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } + }; + + /** + * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. + * + * @param {PIXI.Point} point - the point that the result will be stored in + * @param {number} x - the x coord of the position to map + * @param {number} y - the y coord of the position to map + */ + + + InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint(point, x, y) { + var rect = void 0; + + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { x: 0, y: 0, width: 0, height: 0 }; + } else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + + var resolutionMultiplier = navigator.isCocoonJS ? this.resolution : 1.0 / this.resolution; + + point.x = (x - rect.left) * (this.interactionDOMElement.width / rect.width) * resolutionMultiplier; + point.y = (y - rect.top) * (this.interactionDOMElement.height / rect.height) * resolutionMultiplier; + }; + + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that + * is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param {Function} [func] - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point + * @param {boolean} [interactive] - Whether the displayObject is interactive + * @return {boolean} returns true if the displayObject hit the point + */ + + + InteractionManager.prototype.processInteractive = function processInteractive(interactionEvent, displayObject, func, hitTest, interactive) { + if (!displayObject || !displayObject.visible) { + return false; + } + + var point = interactionEvent.data.global; + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + interactive = displayObject.interactive || interactive; + + var hit = false; + var interactiveParent = interactive; + + // Flag here can set to false if the event is outside the parents hitArea or mask + var hitTestChildren = true; + + // If there is a hitArea, no need to test against anything else if the pointer is not within the hitArea + // There is also no longer a need to hitTest children. + if (displayObject.hitArea) { + if (hitTest) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (!displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hitTest = false; + hitTestChildren = false; + } else { + hit = true; + } + } + interactiveParent = false; + } + // If there is a mask, no need to test against anything else if the pointer is not within the mask + else if (displayObject._mask) { + if (hitTest) { + if (!displayObject._mask.containsPoint(point)) { + hitTest = false; + hitTestChildren = false; + } + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow PixiJS to completely ignore and bypass checking the displayObjects children. + if (hitTestChildren && displayObject.interactiveChildren && displayObject.children) { + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + + // time to get recursive.. if this function will return if something is hit.. + var childHit = this.processInteractive(interactionEvent, child, func, hitTest, interactiveParent); + + if (childHit) { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if (!child.parent) { + continue; + } + + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + + if (childHit) { + if (interactionEvent.target) { + hitTest = false; + } + hit = true; + } + } + } + } + + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit - but only if it was interactive, otherwise we need to keep + // looking for an interactive child, just in case we hit one + if (hitTest && !interactionEvent.target) { + // already tested against hitArea if it is defined + if (!displayObject.hitArea && displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = true; + } + } + } + + if (displayObject.interactive) { + if (hit && !interactionEvent.target) { + interactionEvent.target = displayObject; + } + + if (func) { + func(interactionEvent, displayObject, !!hit); + } + } + } + + return hit; + }; + + /** + * Is called when the pointer button is pressed down on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down + */ + + + InteractionManager.prototype.onPointerDown = function onPointerDown(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + /** + * No need to prevent default on natural pointer events, as there are no side effects + * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, + * so still need to be prevented. + */ + + // Guaranteed that there will be at least one event in events, and all events must have the same pointer type + + if (this.autoPreventDefault && events[0].isNormalized) { + originalEvent.preventDefault(); + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerDown, true); + + this.emit('pointerdown', interactionEvent); + if (event.pointerType === 'touch') { + this.emit('touchstart', interactionEvent); + } + // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event + else if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + } + }; + + /** + * Processes the result of the pointer down check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerDown = function processPointerDown(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + + if (hit) { + if (!displayObject.trackedPointers[id]) { + displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchstart', interactionEvent); + } else if (data.pointerType === 'mouse' || data.pointerType === 'pen') { + var isRightButton = data.button === 2; + + if (isRightButton) { + displayObject.trackedPointers[id].rightDown = true; + } else { + displayObject.trackedPointers[id].leftDown = true; + } + + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released + * @param {boolean} cancelled - true if the pointer is cancelled + * @param {Function} func - Function passed to {@link processInteractive} + */ + + + InteractionManager.prototype.onPointerComplete = function onPointerComplete(originalEvent, cancelled, func) { + var events = this.normalizeToPointerData(originalEvent); + + var eventLen = events.length; + + // if the event wasn't targeting our canvas, then consider it to be pointerupoutside + // in all cases (unless it was a pointercancel) + var eventAppend = originalEvent.target !== this.interactionDOMElement ? 'outside' : ''; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + // perform hit testing for events targeting our canvas or cancel events + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, func, cancelled || !eventAppend); + + this.emit(cancelled ? 'pointercancel' : 'pointerup' + eventAppend, interactionEvent); + + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + + this.emit(isRightButton ? 'rightup' + eventAppend : 'mouseup' + eventAppend, interactionEvent); + } else if (event.pointerType === 'touch') { + this.emit(cancelled ? 'touchcancel' : 'touchend' + eventAppend, interactionEvent); + this.releaseInteractionDataForPointerId(event.pointerId, interactionData); + } + } + }; + + /** + * Is called when the pointer button is cancelled + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerCancel = function onPointerCancel(event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') return; + + this.onPointerComplete(event, true, this.processPointerCancel); + }; + + /** + * Processes the result of the pointer cancel check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + */ + + + InteractionManager.prototype.processPointerCancel = function processPointerCancel(interactionEvent, displayObject) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + if (displayObject.trackedPointers[id] !== undefined) { + delete displayObject.trackedPointers[id]; + this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); + + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerUp = function onPointerUp(event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') return; + + this.onPointerComplete(event, false, this.processPointerUp); + }; + + /** + * Processes the result of the pointer up check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerUp = function processPointerUp(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + var trackingData = displayObject.trackedPointers[id]; + + var isTouch = data.pointerType === 'touch'; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + // need to track mouse down status in the mouse block so that we can emit + // event in a later block + var isMouseTap = false; + + // Mouse only + if (isMouse) { + var isRightButton = data.button === 2; + + var flags = _InteractionTrackingData2.default.FLAGS; + + var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; + + var isDown = trackingData !== undefined && trackingData.flags & test; + + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); + + if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); + // because we can confirm that the mousedown happened on this object, flag for later emit of pointertap + isMouseTap = true; + } + } else if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); + } + // update the down state of the tracking data + if (trackingData) { + if (isRightButton) { + trackingData.rightDown = false; + } else { + trackingData.leftDown = false; + } + } + } + + // Pointers and Touches, and Mouse + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchend', interactionEvent); + + if (trackingData) { + // emit pointertap if not a mouse, or if the mouse block decided it was a tap + if (!isMouse || isMouseTap) { + this.dispatchEvent(displayObject, 'pointertap', interactionEvent); + } + if (isTouch) { + this.dispatchEvent(displayObject, 'tap', interactionEvent); + // touches are no longer over (if they ever were) when we get the touchend + // so we should ensure that we don't keep pretending that they are + trackingData.over = false; + } + } + } else if (trackingData) { + this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); + } + // Only remove the tracking data if there is no over/down state still associated with it + if (trackingData && trackingData.none) { + delete displayObject.trackedPointers[id]; + } + }; + + /** + * Is called when the pointer moves across the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer moving + */ + + + InteractionManager.prototype.onPointerMove = function onPointerMove(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + if (events[0].pointerType === 'mouse' || events[0].pointerType === 'pen') { + this.didMove = true; + + this.cursor = null; + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + var interactive = event.pointerType === 'touch' ? this.moveWhenInside : true; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerMove, interactive); + this.emit('pointermove', interactionEvent); + if (event.pointerType === 'touch') this.emit('touchmove', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') this.emit('mousemove', interactionEvent); + } + + if (events[0].pointerType === 'mouse') { + this.setCursorMode(this.cursor); + + // TODO BUG for parents interactive object (border order issue) + } + }; + + /** + * Processes the result of the pointer move check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerMove = function processPointerMove(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var isTouch = data.pointerType === 'touch'; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + if (isMouse) { + this.processPointerOverOut(interactionEvent, displayObject, hit); + } + + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchmove', interactionEvent); + if (isMouse) this.dispatchEvent(displayObject, 'mousemove', interactionEvent); + } + }; + + /** + * Is called when the pointer is moved out of the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out + */ + + + InteractionManager.prototype.onPointerOut = function onPointerOut(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOut, so events will always be length 1 + var event = events[0]; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = false; + this.setCursorMode(null); + } + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, false); + + this.emit('pointerout', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseout', interactionEvent); + } else { + // we can get touchleave events after touchend, so we want to make sure we don't + // introduce memory leaks + this.releaseInteractionDataForPointerId(interactionData.identifier); + } + }; + + /** + * Processes the result of the pointer over/out check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerOverOut = function processPointerOverOut(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + var trackingData = displayObject.trackedPointers[id]; + + // if we just moused over the display object, then we need to track that state + if (hit && !trackingData) { + trackingData = displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + + if (trackingData === undefined) return; + + if (hit && this.mouseOverRenderer) { + if (!trackingData.over) { + trackingData.over = true; + this.dispatchEvent(displayObject, 'pointerover', interactionEvent); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseover', interactionEvent); + } + } + + // only change the cursor if it has not already been changed (by something deeper in the + // display tree) + if (isMouse && this.cursor === null) { + this.cursor = displayObject.cursor; + } + } else if (trackingData.over) { + trackingData.over = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseout', interactionEvent); + } + // if there is no mouse down information for the pointer, then it is safe to delete + if (trackingData.none) { + delete displayObject.trackedPointers[id]; + } + } + }; + + /** + * Is called when the pointer is moved into the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view + */ + + + InteractionManager.prototype.onPointerOver = function onPointerOver(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOver, so events will always be length 1 + var event = events[0]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = true; + } + + this.emit('pointerover', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseover', interactionEvent); + } + }; + + /** + * Get InteractionData for a given pointerId. Store that data as well + * + * @private + * @param {PointerEvent} event - Normalized pointer event, output from normalizeToPointerData + * @return {PIXI.interaction.InteractionData} - Interaction data for the given pointer identifier + */ + + + InteractionManager.prototype.getInteractionDataForPointerId = function getInteractionDataForPointerId(event) { + var pointerId = event.pointerId; + + var interactionData = void 0; + + if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { + interactionData = this.mouse; + } else if (this.activeInteractionData[pointerId]) { + interactionData = this.activeInteractionData[pointerId]; + } else { + interactionData = this.interactionDataPool.pop() || new _InteractionData2.default(); + interactionData.identifier = pointerId; + this.activeInteractionData[pointerId] = interactionData; + } + // copy properties from the event, so that we can make sure that touch/pointer specific + // data is available + interactionData.copyEvent(event); + + return interactionData; + }; + + /** + * Return unused InteractionData to the pool, for a given pointerId + * + * @private + * @param {number} pointerId - Identifier from a pointer event + */ + + + InteractionManager.prototype.releaseInteractionDataForPointerId = function releaseInteractionDataForPointerId(pointerId) { + var interactionData = this.activeInteractionData[pointerId]; + + if (interactionData) { + delete this.activeInteractionData[pointerId]; + interactionData.reset(); + this.interactionDataPool.push(interactionData); + } + }; + + /** + * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The event to be configured + * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent + * @param {PIXI.interaction.InteractionData} interactionData - The InteractionData that will be paired + * with the InteractionEvent + * @return {PIXI.interaction.InteractionEvent} the interaction event that was passed in + */ + + + InteractionManager.prototype.configureInteractionEventForDOMEvent = function configureInteractionEventForDOMEvent(interactionEvent, pointerEvent, interactionData) { + interactionEvent.data = interactionData; + + this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); + + // This is the way InteractionManager processed touch events before the refactoring, so I've kept + // it here. But it doesn't make that much sense to me, since mapPositionToPoint already factors + // in this.resolution, so this just divides by this.resolution twice for touch events... + if (navigator.isCocoonJS && pointerEvent.pointerType === 'touch') { + interactionData.global.x = interactionData.global.x / this.resolution; + interactionData.global.y = interactionData.global.y / this.resolution; + } + + // Not really sure why this is happening, but it's how a previous version handled things + if (pointerEvent.pointerType === 'touch') { + pointerEvent.globalX = interactionData.global.x; + pointerEvent.globalY = interactionData.global.y; + } + + interactionData.originalEvent = pointerEvent; + interactionEvent.reset(); + + return interactionEvent; + }; + + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * + * @private + * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event + * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer + * or mouse event, or a multiple normalized pointer events if there are multiple changed touches + */ + + + InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData(event) { + var normalizedEvents = []; + + if (this.supportsTouchEvents && event instanceof TouchEvent) { + for (var i = 0, li = event.changedTouches.length; i < li; i++) { + var touch = event.changedTouches[i]; + + if (typeof touch.button === 'undefined') touch.button = event.touches.length ? 1 : 0; + if (typeof touch.buttons === 'undefined') touch.buttons = event.touches.length ? 1 : 0; + if (typeof touch.isPrimary === 'undefined') { + touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart'; + } + if (typeof touch.width === 'undefined') touch.width = touch.radiusX || 1; + if (typeof touch.height === 'undefined') touch.height = touch.radiusY || 1; + if (typeof touch.tiltX === 'undefined') touch.tiltX = 0; + if (typeof touch.tiltY === 'undefined') touch.tiltY = 0; + if (typeof touch.pointerType === 'undefined') touch.pointerType = 'touch'; + if (typeof touch.pointerId === 'undefined') touch.pointerId = touch.identifier || 0; + if (typeof touch.pressure === 'undefined') touch.pressure = touch.force || 0.5; + touch.twist = 0; + touch.tangentialPressure = 0; + // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven + // support, and the fill ins are not quite the same + // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top + // left is not 0,0 on the page + if (typeof touch.layerX === 'undefined') touch.layerX = touch.offsetX = touch.clientX; + if (typeof touch.layerY === 'undefined') touch.layerY = touch.offsetY = touch.clientY; + + // mark the touch as normalized, just so that we know we did it + touch.isNormalized = true; + + normalizedEvents.push(touch); + } + } + // apparently PointerEvent subclasses MouseEvent, so yay + else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent))) { + if (typeof event.isPrimary === 'undefined') event.isPrimary = true; + if (typeof event.width === 'undefined') event.width = 1; + if (typeof event.height === 'undefined') event.height = 1; + if (typeof event.tiltX === 'undefined') event.tiltX = 0; + if (typeof event.tiltY === 'undefined') event.tiltY = 0; + if (typeof event.pointerType === 'undefined') event.pointerType = 'mouse'; + if (typeof event.pointerId === 'undefined') event.pointerId = MOUSE_POINTER_ID; + if (typeof event.pressure === 'undefined') event.pressure = 0.5; + event.twist = 0; + event.tangentialPressure = 0; + + // mark the mouse event as normalized, just so that we know we did it + event.isNormalized = true; + + normalizedEvents.push(event); + } else { + normalizedEvents.push(event); + } + + return normalizedEvents; + }; + + /** + * Destroys the interaction manager + * + */ + + + InteractionManager.prototype.destroy = function destroy() { + this.removeEvents(); + + this.removeAllListeners(); + + this.renderer = null; + + this.mouse = null; + + this.eventData = null; + + this.interactionDOMElement = null; + + this.onPointerDown = null; + this.processPointerDown = null; + + this.onPointerUp = null; + this.processPointerUp = null; + + this.onPointerCancel = null; + this.processPointerCancel = null; + + this.onPointerMove = null; + this.processPointerMove = null; + + this.onPointerOut = null; + this.processPointerOverOut = null; + + this.onPointerOver = null; + + this._tempPoint = null; + }; + + return InteractionManager; +}(_eventemitter2.default); + +exports.default = InteractionManager; + + +core.WebGLRenderer.registerPlugin('interaction', InteractionManager); +core.CanvasRenderer.registerPlugin('interaction', InteractionManager); + +},{"../core":65,"./InteractionData":155,"./InteractionEvent":156,"./InteractionTrackingData":158,"./interactiveTarget":160,"eventemitter3":3}],158:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * DisplayObjects with the {@link PIXI.interaction.interactiveTarget} mixin use this class to track interactions + * + * @class + * @private + * @memberof PIXI.interaction + */ +var InteractionTrackingData = function () { + /** + * @param {number} pointerId - Unique pointer id of the event + */ + function InteractionTrackingData(pointerId) { + _classCallCheck(this, InteractionTrackingData); + + this._pointerId = pointerId; + this._flags = InteractionTrackingData.FLAGS.NONE; + } + + /** + * + * @private + * @param {number} flag - The interaction flag to set + * @param {boolean} yn - Should the flag be set or unset + */ + + + InteractionTrackingData.prototype._doSet = function _doSet(flag, yn) { + if (yn) { + this._flags = this._flags | flag; + } else { + this._flags = this._flags & ~flag; + } + }; + + /** + * Unique pointer id of the event + * + * @readonly + * @member {number} + */ + + + _createClass(InteractionTrackingData, [{ + key: "pointerId", + get: function get() { + return this._pointerId; + } + + /** + * State of the tracking data, expressed as bit flags + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "flags", + get: function get() { + return this._flags; + } + + /** + * Set the flags for the tracking data + * + * @param {number} flags - Flags to set + */ + , + set: function set(flags) { + this._flags = flags; + } + + /** + * Is the tracked event inactive (not over or down)? + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "none", + get: function get() { + return this._flags === this.constructor.FLAGS.NONE; + } + + /** + * Is the tracked event over the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "over", + get: function get() { + return (this._flags & this.constructor.FLAGS.OVER) !== 0; + } + + /** + * Set the over flag + * + * @param {boolean} yn - Is the event over? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.OVER, yn); + } + + /** + * Did the right mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "rightDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.RIGHT_DOWN) !== 0; + } + + /** + * Set the right down flag + * + * @param {boolean} yn - Is the right mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.RIGHT_DOWN, yn); + } + + /** + * Did the left mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "leftDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.LEFT_DOWN) !== 0; + } + + /** + * Set the left down flag + * + * @param {boolean} yn - Is the left mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.LEFT_DOWN, yn); + } + }]); + + return InteractionTrackingData; +}(); + +exports.default = InteractionTrackingData; + + +InteractionTrackingData.FLAGS = Object.freeze({ + NONE: 0, + OVER: 1 << 0, + LEFT_DOWN: 1 << 1, + RIGHT_DOWN: 1 << 2 +}); + +},{}],159:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _InteractionData = require('./InteractionData'); + +Object.defineProperty(exports, 'InteractionData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionData).default; + } +}); + +var _InteractionManager = require('./InteractionManager'); + +Object.defineProperty(exports, 'InteractionManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionManager).default; + } +}); + +var _interactiveTarget = require('./interactiveTarget'); + +Object.defineProperty(exports, 'interactiveTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_interactiveTarget).default; + } +}); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +Object.defineProperty(exports, 'InteractionTrackingData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionTrackingData).default; + } +}); + +var _InteractionEvent = require('./InteractionEvent'); + +Object.defineProperty(exports, 'InteractionEvent', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionEvent).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./InteractionData":155,"./InteractionEvent":156,"./InteractionManager":157,"./InteractionTrackingData":158,"./interactiveTarget":160}],160:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * Default property values of interactive objects + * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties + * + * @private + * @name interactiveTarget + * @memberof PIXI.interaction + * @example + * function MyObject() {} + * + * Object.assign( + * core.DisplayObject.prototype, + * PIXI.interaction.interactiveTarget + * ); + */ +exports.default = { + + /** + * Enable interaction events for the DisplayObject. Touch, pointer and mouse + * events will not be emitted unless `interactive` is set to `true`. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.on('tap', (event) => { + * //handle event + * }); + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + interactive: false, + + /** + * Determines if the children to the displayObject can be clicked/touched + * Setting this to false allows PixiJS to bypass a recursive `hitTest` function + * + * @member {boolean} + * @memberof PIXI.Container# + */ + interactiveChildren: true, + + /** + * Interaction shape. Children will be hit first, then this shape will be checked. + * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.hitArea = new PIXI.Rectangle(0, 0, 100, 100); + * @member {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle} + * @memberof PIXI.DisplayObject# + */ + hitArea: null, + + /** + * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive + * Setting this changes the 'cursor' property to `'pointer'`. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.buttonMode = true; + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + get buttonMode() { + return this.cursor === 'pointer'; + }, + set buttonMode(value) { + if (value) { + this.cursor = 'pointer'; + } else if (this.cursor === 'pointer') { + this.cursor = null; + } + }, + + /** + * This defines what cursor mode is used when the mouse cursor + * is hovered over the displayObject. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.cursor = 'wait'; + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * + * @member {string} + * @memberof PIXI.DisplayObject# + */ + cursor: null, + + /** + * Internal set of all active pointers, by identifier + * + * @member {Map} + * @memberof PIXI.DisplayObject# + * @private + */ + get trackedPointers() { + if (this._trackedPointers === undefined) this._trackedPointers = {}; + + return this._trackedPointers; + }, + + /** + * Map of all tracked pointers, by identifier. Use trackedPointers to access. + * + * @private + * @type {Map} + */ + _trackedPointers: undefined +}; + +},{}],161:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.parse = parse; + +exports.default = function () { + return function bitmapFontParser(resource, next) { + // skip if no data or not xml data + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.XML) { + next(); + + return; + } + + // skip if not bitmap font data, using some silly duck-typing + if (resource.data.getElementsByTagName('page').length === 0 || resource.data.getElementsByTagName('info').length === 0 || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null) { + next(); + + return; + } + + var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; + + if (resource.isDataUrl) { + if (xmlUrl === '.') { + xmlUrl = ''; + } + + if (this.baseUrl && xmlUrl) { + // if baseurl has a trailing slash then add one to xmlUrl so the replace works below + if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { + xmlUrl += '/'; + } + } + } + + // remove baseUrl from xmlUrl + xmlUrl = xmlUrl.replace(this.baseUrl, ''); + + // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { + xmlUrl += '/'; + } + + var pages = resource.data.getElementsByTagName('page'); + var textures = {}; + + // Handle completed, when the number of textures + // load is the same number as references in the fnt file + var completed = function completed(page) { + textures[page.metadata.pageFile] = page.texture; + + if (Object.keys(textures).length === pages.length) { + parse(resource, textures); + next(); + } + }; + + for (var i = 0; i < pages.length; ++i) { + var pageFile = pages[i].getAttribute('file'); + var url = xmlUrl + pageFile; + var exists = false; + + // incase the image is loaded outside + // using the same loader, resource will be available + for (var name in this.resources) { + if (this.resources[name].url === url) { + this.resources[name].metadata.pageFile = pageFile; + completed(this.resources[name]); + exists = true; + break; + } + } + + // texture is not loaded, we'll attempt to add + // it to the load and add the texture to the list + if (!exists) { + // Standard loading options for images + var options = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: Object.assign({ pageFile: pageFile }, resource.metadata.imageMetadata), + parentResource: resource + }; + + this.add(url, options, completed); + } + } + }; +}; + +var _path = require('path'); + +var path = _interopRequireWildcard(_path); + +var _resourceLoader = require('resource-loader'); + +var _extras = require('../extras'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Register a BitmapText font from loader resource. + * + * @function parseBitmapFontData + * @memberof PIXI.loaders + * @param {PIXI.loaders.Resource} resource - Loader resource. + * @param {PIXI.Texture|PIXI.Texture[]} textures - List of textures for each page. + */ +function parse(resource, textures) { + resource.bitmapFont = _extras.BitmapText.registerFont(resource.data, textures); +} + +},{"../extras":141,"path":8,"resource-loader":36}],162:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.shared = exports.Resource = exports.textureParser = exports.getResourcePath = exports.spritesheetParser = exports.parseBitmapFontData = exports.bitmapFontParser = exports.Loader = undefined; + +var _bitmapFontParser = require('./bitmapFontParser'); + +Object.defineProperty(exports, 'bitmapFontParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_bitmapFontParser).default; + } +}); +Object.defineProperty(exports, 'parseBitmapFontData', { + enumerable: true, + get: function get() { + return _bitmapFontParser.parse; + } +}); + +var _spritesheetParser = require('./spritesheetParser'); + +Object.defineProperty(exports, 'spritesheetParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_spritesheetParser).default; + } +}); +Object.defineProperty(exports, 'getResourcePath', { + enumerable: true, + get: function get() { + return _spritesheetParser.getResourcePath; + } +}); + +var _textureParser = require('./textureParser'); + +Object.defineProperty(exports, 'textureParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_textureParser).default; + } +}); + +var _resourceLoader = require('resource-loader'); + +Object.defineProperty(exports, 'Resource', { + enumerable: true, + get: function get() { + return _resourceLoader.Resource; + } +}); + +var _Application = require('../core/Application'); + +var _Application2 = _interopRequireDefault(_Application); + +var _loader = require('./loader'); + +var _loader2 = _interopRequireDefault(_loader); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * This namespace contains APIs which extends the {@link https://github.com/englercj/resource-loader resource-loader} module + * for loading assets, data, and other resources dynamically. + * @example + * const loader = new PIXI.loaders.Loader(); + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.load((loader, resources) => { + * // resources.bunny + * // resources.spaceship + * }); + * @namespace PIXI.loaders + */ +exports.Loader = _loader2.default; + + +/** + * A premade instance of the loader that can be used to load resources. + * @name shared + * @memberof PIXI.loaders + * @type {PIXI.loaders.Loader} + */ +var shared = new _loader2.default(); + +shared.destroy = function () { + // protect destroying shared loader +}; + +exports.shared = shared; + +// Mixin the loader construction + +var AppPrototype = _Application2.default.prototype; + +AppPrototype._loader = null; + +/** + * Loader instance to help with asset loading. + * @name PIXI.Application#loader + * @type {PIXI.loaders.Loader} + */ +Object.defineProperty(AppPrototype, 'loader', { + get: function get() { + if (!this._loader) { + var sharedLoader = this._options.sharedLoader; + + this._loader = sharedLoader ? shared : new _loader2.default(); + } + + return this._loader; + } +}); + +// Override the destroy function +// making sure to destroy the current Loader +AppPrototype._parentDestroy = AppPrototype.destroy; +AppPrototype.destroy = function destroy(removeView, stageOptions) { + if (this._loader) { + this._loader.destroy(); + this._loader = null; + } + this._parentDestroy(removeView, stageOptions); +}; + +},{"../core/Application":43,"./bitmapFontParser":161,"./loader":163,"./spritesheetParser":164,"./textureParser":165,"resource-loader":36}],163:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _resourceLoader = require('resource-loader'); + +var _resourceLoader2 = _interopRequireDefault(_resourceLoader); + +var _blob = require('resource-loader/lib/middlewares/parsing/blob'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _textureParser = require('./textureParser'); + +var _textureParser2 = _interopRequireDefault(_textureParser); + +var _spritesheetParser = require('./spritesheetParser'); + +var _spritesheetParser2 = _interopRequireDefault(_spritesheetParser); + +var _bitmapFontParser = require('./bitmapFontParser'); + +var _bitmapFontParser2 = _interopRequireDefault(_bitmapFontParser); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader + * + * ```js + * const loader = PIXI.loader; // PixiJS exposes a premade instance for you to use. + * //or + * const loader = new PIXI.loaders.Loader(); // you can also create your own if you want + * + * const sprites = {}; + * + * // Chainable `add` to enqueue a resource + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.add('scoreFont', 'assets/score.fnt'); + * + * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. + * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). + * loader.pre(cachingMiddleware); + * + * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. + * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). + * loader.use(parsingMiddleware); + * + * // The `load` method loads the queue of resources, and calls the passed in callback called once all + * // resources have loaded. + * loader.load((loader, resources) => { + * // resources is an object where the key is the name of the resource loaded and the value is the resource object. + * // They have a couple default properties: + * // - `url`: The URL that the resource was loaded from + * // - `error`: The error that happened when trying to load (if any) + * // - `data`: The raw data that was loaded + * // also may contain other properties based on the middleware that runs. + * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); + * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); + * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); + * }); + * + * // throughout the process multiple signals can be dispatched. + * loader.onProgress.add(() => {}); // called once per loaded/errored file + * loader.onError.add(() => {}); // called once per errored file + * loader.onLoad.add(() => {}); // called once per loaded file + * loader.onComplete.add(() => {}); // called once when the queued resources all load. + * ``` + * + * @see https://github.com/englercj/resource-loader + * + * @class + * @extends module:resource-loader.ResourceLoader + * @memberof PIXI.loaders + */ +var Loader = function (_ResourceLoader) { + _inherits(Loader, _ResourceLoader); + + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + _classCallCheck(this, Loader); + + var _this = _possibleConstructorReturn(this, _ResourceLoader.call(this, baseUrl, concurrency)); + + _eventemitter2.default.call(_this); + + for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { + _this.use(Loader._pixiMiddleware[i]()); + } + + // Compat layer, translate the new v2 signals into old v1 events. + _this.onStart.add(function (l) { + return _this.emit('start', l); + }); + _this.onProgress.add(function (l, r) { + return _this.emit('progress', l, r); + }); + _this.onError.add(function (e, l, r) { + return _this.emit('error', e, l, r); + }); + _this.onLoad.add(function (l, r) { + return _this.emit('load', l, r); + }); + _this.onComplete.add(function (l, r) { + return _this.emit('complete', l, r); + }); + return _this; + } + + /** + * Adds a default middleware to the PixiJS loader. + * + * @static + * @param {Function} fn - The middleware to add. + */ + + + Loader.addPixiMiddleware = function addPixiMiddleware(fn) { + Loader._pixiMiddleware.push(fn); + }; + + /** + * Destroy the loader, removes references. + */ + + + Loader.prototype.destroy = function destroy() { + this.removeAllListeners(); + this.reset(); + }; + + return Loader; +}(_resourceLoader2.default); + +// Copy EE3 prototype (mixin) + + +exports.default = Loader; +for (var k in _eventemitter2.default.prototype) { + Loader.prototype[k] = _eventemitter2.default.prototype[k]; +} + +Loader._pixiMiddleware = [ +// parse any blob into more usable objects (e.g. Image) +_blob.blobMiddlewareFactory, +// parse any Image objects into textures +_textureParser2.default, +// parse any spritesheet data into multiple textures +_spritesheetParser2.default, +// parse bitmap font data into multiple textures +_bitmapFontParser2.default]; + +// Add custom extentions +var Resource = _resourceLoader2.default.Resource; + +Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); + +},{"./bitmapFontParser":161,"./spritesheetParser":164,"./textureParser":165,"eventemitter3":3,"resource-loader":36,"resource-loader/lib/middlewares/parsing/blob":37}],164:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function spritesheetParser(resource, next) { + var imageResourceName = resource.name + '_image'; + + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.JSON || !resource.data.frames || this.resources[imageResourceName]) { + next(); + + return; + } + + var loadOptions = { + crossOrigin: resource.crossOrigin, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + var resourcePath = getResourcePath(resource, this.baseUrl); + + // load the image for this sheet + this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + if (res.error) { + next(res.error); + + return; + } + + var spritesheet = new _core.Spritesheet(res.texture.baseTexture, resource.data, resource.url); + + spritesheet.parse(function () { + resource.spritesheet = spritesheet; + resource.textures = spritesheet.textures; + next(); + }); + }); + }; +}; + +exports.getResourcePath = getResourcePath; + +var _resourceLoader = require('resource-loader'); + +var _url = require('url'); + +var _url2 = _interopRequireDefault(_url); + +var _core = require('../core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function getResourcePath(resource, baseUrl) { + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + return resource.data.meta.image; + } + + return _url2.default.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); +} + +},{"../core":65,"resource-loader":36,"url":38}],165:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function textureParser(resource, next) { + // create a new texture if the data is an Image object + if (resource.data && resource.type === _resourceLoader.Resource.TYPE.IMAGE) { + resource.texture = _Texture2.default.fromLoader(resource.data, resource.url, resource.name); + } + next(); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"../core/textures/Texture":115,"resource-loader":36}],166:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); +var tempPolygon = new core.Polygon(); + +/** + * Base mesh class + * @class + * @extends PIXI.Container + * @memberof PIXI.mesh + */ + +var Mesh = function (_core$Container) { + _inherits(Mesh, _core$Container); + + /** + * @param {PIXI.Texture} texture - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts + */ + function Mesh(texture, vertices, uvs, indices, drawMode) { + _classCallCheck(this, Mesh); + + /** + * The texture of the Mesh + * + * @member {PIXI.Texture} + * @default PIXI.Texture.EMPTY + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._texture = texture || _Texture2.default.EMPTY; + + /** + * The Uvs of the Mesh + * + * @member {Float32Array} + */ + _this.uvs = uvs || new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + /** + * An array of vertices + * + * @member {Float32Array} + */ + _this.vertices = vertices || new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]); + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + // TODO auto generate this based on draw mode! + _this.indices = indices || new Uint16Array([0, 1, 3, 2]); + + /** + * Version of mesh uvs are dirty or not + * + * @member {number} + */ + _this.dirty = 0; + + /** + * Version of mesh indices + * + * @member {number} + */ + _this.indexDirty = 0; + + /** + * Version of mesh verticies array + * + * @member {number} + */ + _this.vertexDirty = 0; + + /** + * For backwards compatibility the default is to re-upload verticies each render call. + * Set this to `false` and increase `vertexDirty` to manually re-upload the buffer. + * + * @member {boolean} + */ + _this.autoUpdate = true; + + /** + * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove + * any blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles + * to overlap a bit with each other. + * + * @member {number} + */ + _this.canvasPadding = core.settings.MESH_CANVAS_PADDING; + + /** + * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts + * + * @member {number} + * @see PIXI.mesh.Mesh.DRAW_MODES + */ + _this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH; + + /** + * The default shader that is used if a mesh doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + _this.shader = null; + + /** + * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any + * tint effect. + * + * @member {number} + */ + _this.tintRgb = new Float32Array([1, 1, 1]); + + /** + * A map of renderer IDs to webgl render data + * + * @private + * @member {object} + */ + _this._glDatas = {}; + + /** + * transform that is applied to UV to get the texture coords + * its updated independently from texture uvTransform + * updates of uvs are tied to that thing + * + * @member {PIXI.TextureMatrix} + * @private + */ + _this._uvTransform = new core.TextureMatrix(_this._texture); + + /** + * whether or not upload uvTransform to shader + * if its false, then uvs should be pre-multiplied + * if you change it for generated mesh, please call 'refresh(true)' + * @member {boolean} + * @default false + */ + _this.uploadUvTransform = false; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * @member {string} + * @default 'mesh' + */ + _this.pluginName = 'mesh'; + return _this; + } + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - a reference to the WebGL renderer + */ + + + Mesh.prototype._renderWebGL = function _renderWebGL(renderer) { + this.refresh(); + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + + + Mesh.prototype._renderCanvas = function _renderCanvas(renderer) { + this.refresh(); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Mesh.prototype._onTextureUpdate = function _onTextureUpdate() { + this._uvTransform.texture = this._texture; + this.refresh(); + }; + + /** + * multiplies uvs only if uploadUvTransform is false + * call it after you change uvs manually + * make sure that texture is valid + */ + + + Mesh.prototype.multiplyUvs = function multiplyUvs() { + if (!this.uploadUvTransform) { + this._uvTransform.multiplyUvs(this.uvs); + } + }; + + /** + * Refreshes uvs for generated meshes (rope, plane) + * sometimes refreshes vertices too + * + * @param {boolean} [forceUpdate=false] if true, matrices will be updated any case + */ + + + Mesh.prototype.refresh = function refresh(forceUpdate) { + if (this.autoUpdate) { + this.vertexDirty++; + } + if (this._uvTransform.update(forceUpdate)) { + this._refresh(); + } + }; + + /** + * re-calculates mesh coords + * @protected + */ + + + Mesh.prototype._refresh = function _refresh() {} + /* empty */ + + + /** + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + */ + ; + + Mesh.prototype._calculateBounds = function _calculateBounds() { + // TODO - we can cache local bounds and use them if they are dirty (like graphics) + this._bounds.addVertices(this.transform, this.vertices, 0, this.vertices.length); + }; + + /** + * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Mesh.prototype.containsPoint = function containsPoint(point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + + this.worldTransform.applyInverse(point, tempPoint); + + var vertices = this.vertices; + var points = tempPolygon.points; + var indices = this.indices; + var len = this.indices.length; + var step = this.drawMode === Mesh.DRAW_MODES.TRIANGLES ? 3 : 1; + + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + + return false; + }; + + /** + * The texture that the mesh uses. + * + * @member {PIXI.Texture} + */ + + + /** + * Destroys the Mesh object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + Mesh.prototype.destroy = function destroy(options) { + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._glDatas) { + var data = this._glDatas[id]; + + if (data.destroy) { + data.destroy(); + } else { + if (data.vertexBuffer) { + data.vertexBuffer.destroy(); + data.vertexBuffer = null; + } + if (data.indexBuffer) { + data.indexBuffer.destroy(); + data.indexBuffer = null; + } + if (data.uvBuffer) { + data.uvBuffer.destroy(); + data.uvBuffer = null; + } + if (data.vao) { + data.vao.destroy(); + data.vao = null; + } + } + } + + this._glDatas = null; + + _core$Container.prototype.destroy.call(this, options); + }; + + _createClass(Mesh, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + + /** + * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return core.utils.rgb2hex(this.tintRgb); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tintRgb = core.utils.hex2rgb(value, this.tintRgb); + } + }]); + + return Mesh; +}(core.Container); + +/** + * Different drawing buffer modes supported + * + * @static + * @constant + * @type {object} + * @property {number} TRIANGLE_MESH + * @property {number} TRIANGLES + */ + + +exports.default = Mesh; +Mesh.DRAW_MODES = { + TRIANGLE_MESH: 0, + TRIANGLES: 1 +}; + +},{"../core":65,"../core/textures/Texture":115}],167:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Plane2 = require('./Plane'); + +var _Plane3 = _interopRequireDefault(_Plane2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DEFAULT_BORDER_SIZE = 10; + +/** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.fromImage('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
+ *      A                          B
+ *    +---+----------------------+---+
+ *  C | 1 |          2           | 3 |
+ *    +---+----------------------+---+
+ *    |   |                      |   |
+ *    | 4 |          5           | 6 |
+ *    |   |                      |   |
+ *    +---+----------------------+---+
+ *  D | 7 |          8           | 9 |
+ *    +---+----------------------+---+
+
+ *  When changing this objects width and/or height:
+ *     areas 1 3 7 and 9 will remain unscaled.
+ *     areas 2 and 8 will be stretched horizontally
+ *     areas 4 and 6 will be stretched vertically
+ *     area 5 will be stretched both horizontally and vertically
+ * 
+ * + * @class + * @extends PIXI.mesh.Plane + * @memberof PIXI.mesh + * + */ + +var NineSlicePlane = function (_Plane) { + _inherits(NineSlicePlane, _Plane); + + /** + * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. + * @param {int} [leftWidth=10] size of the left vertical bar (A) + * @param {int} [topHeight=10] size of the top horizontal bar (C) + * @param {int} [rightWidth=10] size of the right vertical bar (B) + * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) + */ + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + _classCallCheck(this, NineSlicePlane); + + var _this = _possibleConstructorReturn(this, _Plane.call(this, texture, 4, 4)); + + _this._origWidth = texture.orig.width; + _this._origHeight = texture.orig.height; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._width = _this._origWidth; + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._height = _this._origHeight; + + /** + * The width of the left column (a) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; + + /** + * The width of the right column (b) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; + + /** + * The height of the top row (c) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; + + /** + * The height of the bottom row (d) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; + + _this.refresh(true); + return _this; + } + + /** + * Updates the horizontal vertices. + * + */ + + + NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices() { + var vertices = this.vertices; + + var h = this._topHeight + this._bottomHeight; + var scale = this._height > h ? 1.0 : this._height / h; + + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight * scale; + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + }; + + /** + * Updates the vertical vertices. + * + */ + + + NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices() { + var vertices = this.vertices; + + var w = this._leftWidth + this._rightWidth; + var scale = this._width > w ? 1.0 : this._width / w; + + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth * scale; + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with. + */ + + + NineSlicePlane.prototype._renderCanvas = function _renderCanvas(renderer) { + var context = renderer.context; + + context.globalAlpha = this.worldAlpha; + renderer.setBlendMode(this.blendMode); + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + var base = this._texture.baseTexture; + var textureSource = base.source; + var w = base.width * base.resolution; + var h = base.height * base.resolution; + + this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11); + this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13); + this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15); + this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19); + this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21); + this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23); + this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27); + this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29); + this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31); + }; + + /** + * Renders one segment of the plane. + * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure + * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used. + * + * @private + * @param {CanvasRenderingContext2D} context - The context to draw with. + * @param {CanvasImageSource} textureSource - The source to draw. + * @param {number} w - width of the texture + * @param {number} h - height of the texture + * @param {number} x1 - x index 1 + * @param {number} y1 - y index 1 + * @param {number} x2 - x index 2 + * @param {number} y2 - y index 2 + */ + + + NineSlicePlane.prototype.drawSegment = function drawSegment(context, textureSource, w, h, x1, y1, x2, y2) { + // otherwise you get weird results when using slices of that are 0 wide or high. + var uvs = this.uvs; + var vertices = this.vertices; + + var sw = (uvs[x2] - uvs[x1]) * w; + var sh = (uvs[y2] - uvs[y1]) * h; + var dw = vertices[x2] - vertices[x1]; + var dh = vertices[y2] - vertices[y1]; + + // make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn. + if (sw < 1) { + sw = 1; + } + + if (sh < 1) { + sh = 1; + } + + // make sure destination is at least 1 pixel wide and high, otherwise you get + // lines when rendering close to original size. + if (dw < 1) { + dw = 1; + } + + if (dh < 1) { + dh = 1; + } + + context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh); + }; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + + /** + * Refreshes NineSlicePlane coords. All of them. + */ + NineSlicePlane.prototype._refresh = function _refresh() { + _Plane.prototype._refresh.call(this); + + var uvs = this.uvs; + var texture = this._texture; + + this._origWidth = texture.orig.width; + this._origHeight = texture.orig.height; + + var _uvw = 1.0 / this._origWidth; + var _uvh = 1.0 / this._origHeight; + + uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; + uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - _uvw * this._rightWidth; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - _uvh * this._bottomHeight; + + this.updateHorizontalVertices(); + this.updateVerticalVertices(); + + this.dirty++; + + this.multiplyUvs(); + }; + + _createClass(NineSlicePlane, [{ + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + this._refresh(); + } + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + this._refresh(); + } + + /** + * The width of the left column + * + * @member {number} + */ + + }, { + key: 'leftWidth', + get: function get() { + return this._leftWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._leftWidth = value; + this._refresh(); + } + + /** + * The width of the right column + * + * @member {number} + */ + + }, { + key: 'rightWidth', + get: function get() { + return this._rightWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rightWidth = value; + this._refresh(); + } + + /** + * The height of the top row + * + * @member {number} + */ + + }, { + key: 'topHeight', + get: function get() { + return this._topHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._topHeight = value; + this._refresh(); + } + + /** + * The height of the bottom row + * + * @member {number} + */ + + }, { + key: 'bottomHeight', + get: function get() { + return this._bottomHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._bottomHeight = value; + this._refresh(); + } + }]); + + return NineSlicePlane; +}(_Plane3.default); + +exports.default = NineSlicePlane; + +},{"./Plane":168}],168:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The Plane allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Plane = function (_Mesh) { + _inherits(Plane, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the Plane. + * @param {number} verticesX - The number of vertices in the x-axis + * @param {number} verticesY - The number of vertices in the y-axis + */ + function Plane(texture, verticesX, verticesY) { + _classCallCheck(this, Plane); + + /** + * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this._ready = true; + + _this.verticesX = verticesX || 10; + _this.verticesY = verticesY || 10; + + _this.drawMode = _Mesh3.default.DRAW_MODES.TRIANGLES; + _this.refresh(); + return _this; + } + + /** + * Refreshes plane coordinates + * + */ + + + Plane.prototype._refresh = function _refresh() { + var texture = this._texture; + var total = this.verticesX * this.verticesY; + var verts = []; + var colors = []; + var uvs = []; + var indices = []; + + var segmentsX = this.verticesX - 1; + var segmentsY = this.verticesY - 1; + + var sizeX = texture.width / segmentsX; + var sizeY = texture.height / segmentsY; + + for (var i = 0; i < total; i++) { + var x = i % this.verticesX; + var y = i / this.verticesX | 0; + + verts.push(x * sizeX, y * sizeY); + + uvs.push(x / segmentsX, y / segmentsY); + } + + // cons + + var totalSub = segmentsX * segmentsY; + + for (var _i = 0; _i < totalSub; _i++) { + var xpos = _i % segmentsX; + var ypos = _i / segmentsX | 0; + + var value = ypos * this.verticesX + xpos; + var value2 = ypos * this.verticesX + xpos + 1; + var value3 = (ypos + 1) * this.verticesX + xpos; + var value4 = (ypos + 1) * this.verticesX + xpos + 1; + + indices.push(value, value2, value3); + indices.push(value2, value4, value3); + } + + // console.log(indices) + this.vertices = new Float32Array(verts); + this.uvs = new Float32Array(uvs); + this.colors = new Float32Array(colors); + this.indices = new Uint16Array(indices); + + this.dirty++; + this.indexDirty++; + + this.multiplyUvs(); + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Plane.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh3.default.prototype._onTextureUpdate.call(this); + + // wait for the Plane ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + return Plane; +}(_Mesh3.default); + +exports.default = Plane; + +},{"./Mesh":166}],169:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The rope allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Rope = function (_Mesh) { + _inherits(Rope, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the rope. + * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. + */ + function Rope(texture, points) { + _classCallCheck(this, Rope); + + /** + * An array of points that determine the rope + * + * @member {PIXI.Point[]} + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this.points = points; + + /** + * An array of vertices used to construct this rope. + * + * @member {Float32Array} + */ + _this.vertices = new Float32Array(points.length * 4); + + /** + * The WebGL Uvs of the rope. + * + * @member {Float32Array} + */ + _this.uvs = new Float32Array(points.length * 4); + + /** + * An array containing the color components + * + * @member {Float32Array} + */ + _this.colors = new Float32Array(points.length * 2); + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + _this.indices = new Uint16Array(points.length * 2); + + /** + * refreshes vertices on every updateTransform + * @member {boolean} + * @default true + */ + _this.autoUpdate = true; + + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Rope.prototype._refresh = function _refresh() { + var points = this.points; + + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1 || !this._texture._uvs) { + return; + } + + // if the number of points has changed we will need to recreate the arraybuffers + if (this.vertices.length / 4 !== points.length) { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + + for (var i = 1; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + var amount = i / (total - 1); + + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + + // ensure that the changes are uploaded + this.dirty++; + this.indexDirty++; + + this.multiplyUvs(); + this.refreshVertices(); + }; + + /** + * refreshes vertices of Rope mesh + */ + + + Rope.prototype.refreshVertices = function refreshVertices() { + var points = this.points; + + if (points.length < 1) { + return; + } + + var lastPoint = points[0]; + var nextPoint = void 0; + var perpX = 0; + var perpY = 0; + + // this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } else { + nextPoint = point; + } + + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + + var ratio = (1 - i / (total - 1)) * 10; + + if (ratio > 1) { + ratio = 1; + } + + var perpLength = Math.sqrt(perpX * perpX + perpY * perpY); + var num = this._texture.height / 2; // (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; + + perpX /= perpLength; + perpY /= perpLength; + + perpX *= num; + perpY *= num; + + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + + lastPoint = point; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + Rope.prototype.updateTransform = function updateTransform() { + if (this.autoUpdate) { + this.refreshVertices(); + } + this.containerUpdateTransform(); + }; + + return Rope; +}(_Mesh3.default); + +exports.default = Rope; + +},{"./Mesh":166}],170:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Renderer dedicated to meshes. + * + * @class + * @private + * @memberof PIXI + */ +var MeshSpriteRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The renderer this downport works for + */ + function MeshSpriteRenderer(renderer) { + _classCallCheck(this, MeshSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the Mesh + * + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var context = renderer.context; + + var transform = mesh.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + renderer.context.globalAlpha = mesh.worldAlpha; + renderer.setBlendMode(mesh.blendMode); + + if (mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH) { + this._renderTriangleMesh(mesh); + } else { + this._renderTriangles(mesh); + } + }; + + /** + * Draws the object in Triangle Mesh mode + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype._renderTriangleMesh = function _renderTriangleMesh(mesh) { + // draw triangles!! + var length = mesh.vertices.length / 2; + + for (var i = 0; i < length - 2; i++) { + // draw some triangles! + var index = i * 2; + + this._renderDrawTriangle(mesh, index, index + 2, index + 4); + } + }; + + /** + * Draws the object in triangle mode using canvas + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + */ + + + MeshSpriteRenderer.prototype._renderTriangles = function _renderTriangles(mesh) { + // draw triangles!! + var indices = mesh.indices; + var length = indices.length; + + for (var i = 0; i < length; i += 3) { + // draw some triangles! + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderDrawTriangle(mesh, index0, index1, index2); + } + }; + + /** + * Draws one of the triangles that from the Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + * @param {number} index0 - the index of the first vertex + * @param {number} index1 - the index of the second vertex + * @param {number} index2 - the index of the third vertex + */ + + + MeshSpriteRenderer.prototype._renderDrawTriangle = function _renderDrawTriangle(mesh, index0, index1, index2) { + var context = this.renderer.context; + var uvs = mesh.uvs; + var vertices = mesh.vertices; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var base = texture.baseTexture; + var textureSource = base.source; + var textureWidth = base.width; + var textureHeight = base.height; + + var u0 = void 0; + var u1 = void 0; + var u2 = void 0; + var v0 = void 0; + var v1 = void 0; + var v2 = void 0; + + if (mesh.uploadUvTransform) { + var ut = mesh._uvTransform.mapCoord; + + u0 = (uvs[index0] * ut.a + uvs[index0 + 1] * ut.c + ut.tx) * base.width; + u1 = (uvs[index1] * ut.a + uvs[index1 + 1] * ut.c + ut.tx) * base.width; + u2 = (uvs[index2] * ut.a + uvs[index2 + 1] * ut.c + ut.tx) * base.width; + v0 = (uvs[index0] * ut.b + uvs[index0 + 1] * ut.d + ut.ty) * base.height; + v1 = (uvs[index1] * ut.b + uvs[index1 + 1] * ut.d + ut.ty) * base.height; + v2 = (uvs[index2] * ut.b + uvs[index2 + 1] * ut.d + ut.ty) * base.height; + } else { + u0 = uvs[index0] * base.width; + u1 = uvs[index1] * base.width; + u2 = uvs[index2] * base.width; + v0 = uvs[index0 + 1] * base.height; + v1 = uvs[index1 + 1] * base.height; + v2 = uvs[index2 + 1] * base.height; + } + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + var canvasPadding = mesh.canvasPadding / this.renderer.resolution; + + if (canvasPadding > 0) { + var paddingX = canvasPadding / Math.abs(mesh.worldTransform.a); + var paddingY = canvasPadding / Math.abs(mesh.worldTransform.d); + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt(normX * normX + normY * normY); + + x0 = centerX + normX / dist * (dist + paddingX); + y0 = centerY + normY / dist * (dist + paddingY); + + // + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x1 = centerX + normX / dist * (dist + paddingX); + y1 = centerY + normY / dist * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x2 = centerX + normX / dist * (dist + paddingX); + y2 = centerY + normY / dist * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2; + var deltaA = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2; + var deltaB = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2; + var deltaC = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2; + var deltaD = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2; + var deltaE = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2; + var deltaF = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2; + + context.transform(deltaA / delta, deltaD / delta, deltaB / delta, deltaE / delta, deltaC / delta, deltaF / delta); + + context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + + context.restore(); + this.renderer.invalidateBlendMode(); + }; + + /** + * Renders a flat Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - The Mesh to render + */ + + + MeshSpriteRenderer.prototype.renderMeshFlat = function renderMeshFlat(mesh) { + var context = this.renderer.context; + var vertices = mesh.vertices; + var length = vertices.length / 2; + + // this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; ++i) { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var y0 = vertices[index + 1]; + + var x1 = vertices[index + 2]; + var y1 = vertices[index + 3]; + + var x2 = vertices[index + 4]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + }; + + /** + * destroy the the renderer. + * + */ + + + MeshSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return MeshSpriteRenderer; +}(); + +exports.default = MeshSpriteRenderer; + + +core.CanvasRenderer.registerPlugin('mesh', MeshSpriteRenderer); + +},{"../../core":65,"../Mesh":166}],171:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh = require('./Mesh'); + +Object.defineProperty(exports, 'Mesh', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Mesh).default; + } +}); + +var _MeshRenderer = require('./webgl/MeshRenderer'); + +Object.defineProperty(exports, 'MeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_MeshRenderer).default; + } +}); + +var _CanvasMeshRenderer = require('./canvas/CanvasMeshRenderer'); + +Object.defineProperty(exports, 'CanvasMeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasMeshRenderer).default; + } +}); + +var _Plane = require('./Plane'); + +Object.defineProperty(exports, 'Plane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Plane).default; + } +}); + +var _NineSlicePlane = require('./NineSlicePlane'); + +Object.defineProperty(exports, 'NineSlicePlane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NineSlicePlane).default; + } +}); + +var _Rope = require('./Rope'); + +Object.defineProperty(exports, 'Rope', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rope).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./Mesh":166,"./NineSlicePlane":167,"./Plane":168,"./Rope":169,"./canvas/CanvasMeshRenderer":170,"./webgl/MeshRenderer":172}],172:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var matrixIdentity = core.Matrix.IDENTITY; + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var MeshRenderer = function (_core$ObjectRenderer) { + _inherits(MeshRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function MeshRenderer(renderer) { + _classCallCheck(this, MeshRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + MeshRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n'); + }; + + /** + * renders mesh + * + * @param {PIXI.mesh.Mesh} mesh mesh instance + */ + + + MeshRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var gl = renderer.gl; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var glData = mesh._glDatas[renderer.CONTEXT_UID]; + + if (!glData) { + renderer.bindVao(null); + + glData = { + shader: this.shader, + vertexBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.vertices, gl.STREAM_DRAW), + uvBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.uvs, gl.STREAM_DRAW), + indexBuffer: _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, mesh.indices, gl.STATIC_DRAW), + // build the vao object that will render.. + vao: null, + dirty: mesh.dirty, + indexDirty: mesh.indexDirty, + vertexDirty: mesh.vertexDirty + }; + + // build the vao object that will render.. + glData.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(glData.indexBuffer).addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0).addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); + + mesh._glDatas[renderer.CONTEXT_UID] = glData; + } + + renderer.bindVao(glData.vao); + + if (mesh.dirty !== glData.dirty) { + glData.dirty = mesh.dirty; + glData.uvBuffer.upload(mesh.uvs); + } + + if (mesh.indexDirty !== glData.indexDirty) { + glData.indexDirty = mesh.indexDirty; + glData.indexBuffer.upload(mesh.indices); + } + + if (mesh.vertexDirty !== glData.vertexDirty) { + glData.vertexDirty = mesh.vertexDirty; + glData.vertexBuffer.upload(mesh.vertices); + } + + renderer.bindShader(glData.shader); + + glData.shader.uniforms.uSampler = renderer.bindTexture(texture); + + renderer.state.setBlendMode(core.utils.correctBlendMode(mesh.blendMode, texture.baseTexture.premultipliedAlpha)); + + if (glData.shader.uniforms.uTransform) { + if (mesh.uploadUvTransform) { + glData.shader.uniforms.uTransform = mesh._uvTransform.mapCoord.toArray(true); + } else { + glData.shader.uniforms.uTransform = matrixIdentity.toArray(true); + } + } + glData.shader.uniforms.translationMatrix = mesh.worldTransform.toArray(true); + + glData.shader.uniforms.uColor = core.utils.premultiplyRgba(mesh.tintRgb, mesh.worldAlpha, glData.shader.uniforms.uColor, texture.baseTexture.premultipliedAlpha); + + var drawMode = mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + glData.vao.draw(drawMode, mesh.indices.length, 0); + }; + + return MeshRenderer; +}(core.ObjectRenderer); + +exports.default = MeshRenderer; + + +core.WebGLRenderer.registerPlugin('mesh', MeshRenderer); + +},{"../../core":65,"../Mesh":166,"path":8,"pixi-gl-core":15}],173:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _utils = require('../core/utils'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that most advanced + * functionality will not work. ParticleContainer implements the basic object transform (position, scale, rotation) + * and some advanced functionality like tint (as of v4.5.6). + * Other more advanced functionality like masking, children, filters, etc will not work on sprites in this batch. + * + * It's extremely easy to use : + * + * ```js + * let container = new ParticleContainer(); + * + * for (let i = 0; i < 100; ++i) + * { + * let sprite = new PIXI.Sprite.fromImage("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be rendered at the speed of light. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.particles + */ +var ParticleContainer = function (_core$Container) { + _inherits(ParticleContainer, _core$Container); + + /** + * @param {number} [maxSize=1500] - The maximum number of particles that can be rendered by the container. + * Affects size of allocated buffers. + * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.vertices=false] - When true, vertices be uploaded and applied. + * if sprite's ` scale/anchor/trim/frame/orig` is dynamic, please set `true`. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.tint=false] - When true, alpha and tint be uploaded and applied. + * @param {number} [batchSize=16384] - Number of particles per batch. If less than maxSize, it uses maxSize instead. + * @param {boolean} [autoResize=false] If true, container allocates more batches in case + * there are more than `maxSize` particles. + */ + function ParticleContainer() { + var maxSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1500; + var properties = arguments[1]; + var batchSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 16384; + var autoResize = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + _classCallCheck(this, ParticleContainer); + + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + var maxBatchSize = 16384; + + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + + if (batchSize > maxSize) { + batchSize = maxSize; + } + + /** + * Set properties to be dynamic (true) / static (false) + * + * @member {boolean[]} + * @private + */ + _this._properties = [false, true, false, false, false]; + + /** + * @member {number} + * @private + */ + _this._maxSize = maxSize; + + /** + * @member {number} + * @private + */ + _this._batchSize = batchSize; + + /** + * @member {object} + * @private + */ + _this._glBuffers = {}; + + /** + * for every batch stores _updateID corresponding to the last change in that batch + * @member {number[]} + * @private + */ + _this._bufferUpdateIDs = []; + + /** + * when child inserted, removed or changes position this number goes up + * @member {number[]} + * @private + */ + _this._updateID = 0; + + /** + * @member {boolean} + * + */ + _this.interactiveChildren = false; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` + * to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * If true, container allocates more batches in case there are more than `maxSize` particles. + * @member {boolean} + * @default false + */ + _this.autoResize = autoResize; + + /** + * Used for canvas renderering. If true then the elements will be positioned at the + * nearest pixel. This provides a nice speed boost. + * + * @member {boolean} + * @default true; + */ + _this.roundPixels = true; + + /** + * The texture used to render the children. + * + * @readonly + * @member {BaseTexture} + */ + _this.baseTexture = null; + + _this.setProperties(properties); + + /** + * The tint applied to the container. + * This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = 0; + _this.tintRgb = new Float32Array(4); + _this.tint = 0xFFFFFF; + return _this; + } + + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * + * @param {object} properties - The properties to be uploaded + */ + + + ParticleContainer.prototype.setProperties = function setProperties(properties) { + if (properties) { + this._properties[0] = 'vertices' in properties || 'scale' in properties ? !!properties.vertices || !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'tint' in properties || 'alpha' in properties ? !!properties.tint || !!properties.alpha : this._properties[4]; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + ParticleContainer.prototype.updateTransform = function updateTransform() { + // TODO don't need to! + this.displayObjectUpdateTransform(); + // PIXI.Container.prototype.updateTransform.call( this ); + }; + + /** + * The tint applied to the container. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + ** IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * @member {number} + * @default 0xFFFFFF + */ + + + /** + * Renders the container using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer + */ + ParticleContainer.prototype.renderWebGL = function renderWebGL(renderer) { + var _this2 = this; + + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.hasLoaded) { + this.baseTexture.once('update', function () { + return _this2.onChildrenChange(0); + }); + } + } + + renderer.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + + /** + * Set the flag that static data should be updated to true + * + * @private + * @param {number} smallestChildIndex - The smallest child index + */ + + + ParticleContainer.prototype.onChildrenChange = function onChildrenChange(smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + + while (this._bufferUpdateIDs.length < bufferIndex) { + this._bufferUpdateIDs.push(0); + } + this._bufferUpdateIDs[bufferIndex] = ++this._updateID; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + + + ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var isRotated = true; + + var positionX = 0; + var positionY = 0; + + var finalWidth = 0; + var finalHeight = 0; + + renderer.setBlendMode(this.blendMode); + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i]; + + if (!child.visible) { + continue; + } + + var frame = child._texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) { + // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call + if (isRotated) { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx * renderer.resolution, transform.ty * renderer.resolution); + + isRotated = false; + } + + positionX = child.anchor.x * (-frame.width * child.scale.x) + child.position.x + 0.5; + positionY = child.anchor.y * (-frame.height * child.scale.y) + child.position.y + 0.5; + + finalWidth = frame.width * child.scale.x; + finalHeight = frame.height * child.scale.y; + } else { + if (!isRotated) { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + + if (renderer.roundPixels) { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution | 0, childTransform.ty * renderer.resolution | 0); + } else { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution, childTransform.ty * renderer.resolution); + } + + positionX = child.anchor.x * -frame.width + 0.5; + positionY = child.anchor.y * -frame.height + 0.5; + + finalWidth = frame.width; + finalHeight = frame.height; + } + + var resolution = child._texture.baseTexture.resolution; + + context.drawImage(child._texture.baseTexture.source, frame.x * resolution, frame.y * resolution, frame.width * resolution, frame.height * resolution, positionX * renderer.resolution, positionY * renderer.resolution, finalWidth * renderer.resolution, finalHeight * renderer.resolution); + } + }; + + /** + * Destroys the container + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + ParticleContainer.prototype.destroy = function destroy(options) { + _core$Container.prototype.destroy.call(this, options); + + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + } + + this._properties = null; + this._buffers = null; + this._bufferUpdateIDs = null; + }; + + _createClass(ParticleContainer, [{ + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + (0, _utils.hex2rgb)(value, this.tintRgb); + } + }]); + + return ParticleContainer; +}(core.Container); + +exports.default = ParticleContainer; + +},{"../core":65,"../core/utils":125}],174:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ParticleContainer = require('./ParticleContainer'); + +Object.defineProperty(exports, 'ParticleContainer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleContainer).default; + } +}); + +var _ParticleRenderer = require('./webgl/ParticleRenderer'); + +Object.defineProperty(exports, 'ParticleRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleRenderer).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./ParticleContainer":173,"./webgl/ParticleRenderer":176}],175:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + +/** + * The particle buffer manages the static and dynamic buffers for a particle container. + * + * @class + * @private + * @memberof PIXI + */ +var ParticleBuffer = function () { + /** + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(gl, properties, dynamicPropertyFlags, size) { + _classCallCheck(this, ParticleBuffer); + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The number of particles the buffer can hold + * + * @member {number} + */ + this.size = size; + + /** + * A list of the properties that are dynamic. + * + * @member {object[]} + */ + this.dynamicProperties = []; + + /** + * A list of the properties that are static. + * + * @member {object[]} + */ + this.staticProperties = []; + + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attribute: property.attribute, + size: property.size, + uploadFunction: property.uploadFunction, + unsignedByte: property.unsignedByte, + offset: property.offset + }; + + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } else { + this.staticProperties.push(property); + } + } + + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + + this._updateID = 0; + + this.initBuffers(); + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + ParticleBuffer.prototype.initBuffers = function initBuffers() { + var gl = this.gl; + var dynamicOffset = 0; + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(this.size); + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + this.dynamicStride = 0; + + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + + var dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4); + + this.dynamicData = new Float32Array(dynBuffer); + this.dynamicDataUint32 = new Uint32Array(dynBuffer); + this.dynamicBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, dynBuffer, gl.STREAM_DRAW); + + // static // + var staticOffset = 0; + + this.staticStride = 0; + + for (var _i = 0; _i < this.staticProperties.length; ++_i) { + var _property = this.staticProperties[_i]; + + _property.offset = staticOffset; + staticOffset += _property.size; + this.staticStride += _property.size; + } + + var statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4); + + this.staticData = new Float32Array(statBuffer); + this.staticDataUint32 = new Uint32Array(statBuffer); + this.staticBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, statBuffer, gl.STATIC_DRAW); + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(this.indexBuffer); + + for (var _i2 = 0; _i2 < this.dynamicProperties.length; ++_i2) { + var _property2 = this.dynamicProperties[_i2]; + + if (_property2.unsignedByte) { + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.UNSIGNED_BYTE, true, this.dynamicStride * 4, _property2.offset * 4); + } else { + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.FLOAT, false, this.dynamicStride * 4, _property2.offset * 4); + } + } + + for (var _i3 = 0; _i3 < this.staticProperties.length; ++_i3) { + var _property3 = this.staticProperties[_i3]; + + if (_property3.unsignedByte) { + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.UNSIGNED_BYTE, true, this.staticStride * 4, _property3.offset * 4); + } else { + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.FLOAT, false, this.staticStride * 4, _property3.offset * 4); + } + } + }; + + /** + * Uploads the dynamic properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadDynamic = function uploadDynamic(children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + + property.uploadFunction(children, startIndex, amount, property.unsignedByte ? this.dynamicDataUint32 : this.dynamicData, this.dynamicStride, property.offset); + } + + this.dynamicBuffer.upload(); + }; + + /** + * Uploads the static properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadStatic = function uploadStatic(children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + + property.uploadFunction(children, startIndex, amount, property.unsignedByte ? this.staticDataUint32 : this.staticData, this.staticStride, property.offset); + } + + this.staticBuffer.upload(); + }; + + /** + * Destroys the ParticleBuffer. + * + */ + + + ParticleBuffer.prototype.destroy = function destroy() { + this.dynamicProperties = null; + this.dynamicBuffer.destroy(); + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + + this.staticProperties = null; + this.staticBuffer.destroy(); + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + }; + + return ParticleBuffer; +}(); + +exports.default = ParticleBuffer; + +},{"../../core/utils/createIndicesForQuads":123,"pixi-gl-core":15}],176:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _ParticleShader = require('./ParticleShader'); + +var _ParticleShader2 = _interopRequireDefault(_ParticleShader); + +var _ParticleBuffer = require('./ParticleBuffer'); + +var _ParticleBuffer2 = _interopRequireDefault(_ParticleBuffer); + +var _utils = require('../../core/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + +/** + * + * @class + * @private + * @memberof PIXI + */ +var ParticleRenderer = function (_core$ObjectRenderer) { + _inherits(ParticleRenderer, _core$ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + _classCallCheck(this, ParticleRenderer); + + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; + + /** + * The default shader that is used if a sprite doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + + _this.indexBuffer = null; + + _this.properties = null; + + _this.tempMatrix = new core.Matrix(); + + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * When there is a WebGL context change + * + * @private + */ + + + ParticleRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + + // setup default shader + this.shader = new _ParticleShader2.default(gl); + + this.properties = [ + // verticesData + { + attribute: this.shader.attributes.aVertexPosition, + size: 2, + uploadFunction: this.uploadVertices, + offset: 0 + }, + // positionData + { + attribute: this.shader.attributes.aPositionCoord, + size: 2, + uploadFunction: this.uploadPosition, + offset: 0 + }, + // rotationData + { + attribute: this.shader.attributes.aRotation, + size: 1, + uploadFunction: this.uploadRotation, + offset: 0 + }, + // uvsData + { + attribute: this.shader.attributes.aTextureCoord, + size: 2, + uploadFunction: this.uploadUvs, + offset: 0 + }, + // tintData + { + attribute: this.shader.attributes.aColor, + size: 1, + unsignedByte: true, + uploadFunction: this.uploadTint, + offset: 0 + }]; + }; + + /** + * Starts a new particle batch. + * + */ + + + ParticleRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + }; + + /** + * Renders the particle container object. + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + */ + + + ParticleRenderer.prototype.render = function render(container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var renderer = this.renderer; + var totalChildren = children.length; + + if (totalChildren === 0) { + return; + } else if (totalChildren > maxSize) { + totalChildren = maxSize; + } + + var buffers = container._glBuffers[renderer.CONTEXT_UID]; + + if (!buffers) { + buffers = container._glBuffers[renderer.CONTEXT_UID] = this.generateBuffers(container); + } + + var baseTexture = children[0]._texture.baseTexture; + + // if the uvs have not updated then no point rendering just yet! + this.renderer.setBlendMode(core.utils.correctBlendMode(container.blendMode, baseTexture.premultipliedAlpha)); + + var gl = renderer.gl; + + var m = container.worldTransform.copy(this.tempMatrix); + + m.prepend(renderer._activeRenderTarget.projectionMatrix); + + this.shader.uniforms.projectionMatrix = m.toArray(true); + + this.shader.uniforms.uColor = core.utils.premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, baseTexture.premultipliedAlpha); + + // make sure the texture is bound.. + this.shader.uniforms.uSampler = renderer.bindTexture(baseTexture); + + var updateStatic = false; + + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = totalChildren - i; + + if (amount > batchSize) { + amount = batchSize; + } + + if (j >= buffers.length) { + if (!container.autoResize) { + break; + } + buffers.push(this._generateOneMoreBuffer(container)); + } + + var buffer = buffers[j]; + + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + + var bid = container._bufferUpdateIDs[j] || 0; + + updateStatic = updateStatic || buffer._updateID < bid; + // we only upload the static content when we have to! + if (updateStatic) { + buffer._updateID = container._updateID; + buffer.uploadStatic(children, i, amount); + } + + // bind the buffer + renderer.bindVao(buffer.vao); + buffer.vao.draw(gl.TRIANGLES, amount * 6); + } + }; + + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer[]} The buffers + */ + + + ParticleRenderer.prototype.generateBuffers = function generateBuffers(container) { + var gl = this.renderer.gl; + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + for (var i = 0; i < size; i += batchSize) { + buffers.push(new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize)); + } + + return buffers; + }; + + /** + * Creates one more particle buffer, because container has autoResize feature + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer} generated buffer + * @private + */ + + + ParticleRenderer.prototype._generateOneMoreBuffer = function _generateOneMoreBuffer(container) { + var gl = this.renderer.gl; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + return new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize); + }; + + /** + * Uploads the verticies. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their vertices uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadVertices = function uploadVertices(children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - sprite.anchor.x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - sprite.anchor.y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - sprite.anchor.x); + w1 = orig.width * -sprite.anchor.x; + + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + + array[offset + stride * 2] = w0 * sx; + array[offset + stride * 2 + 1] = h0 * sy; + + array[offset + stride * 3] = w1 * sx; + array[offset + stride * 3 + 1] = h0 * sy; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their positions uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadPosition = function uploadPosition(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + + array[offset + stride * 2] = spritePosition.x; + array[offset + stride * 2 + 1] = spritePosition.y; + + array[offset + stride * 3] = spritePosition.x; + array[offset + stride * 3 + 1] = spritePosition.y; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadRotation = function uploadRotation(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + stride * 2] = spriteRotation; + array[offset + stride * 3] = spriteRotation; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadUvs = function uploadUvs(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + + array[offset + stride * 2] = textureUvs.x2; + array[offset + stride * 2 + 1] = textureUvs.y2; + + array[offset + stride * 3] = textureUvs.x3; + array[offset + stride * 3 + 1] = textureUvs.y3; + + offset += stride * 4; + } else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + + array[offset + stride * 2] = 0; + array[offset + stride * 2 + 1] = 0; + + array[offset + stride * 3] = 0; + array[offset + stride * 3 + 1] = 0; + + offset += stride * 4; + } + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadTint = function uploadTint(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var premultiplied = sprite._texture.baseTexture.premultipliedAlpha; + var alpha = sprite.alpha; + // we dont call extra function if alpha is 1.0, that's faster + var argb = alpha < 1.0 && premultiplied ? (0, _utils.premultiplyTint)(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); + + array[offset] = argb; + array[offset + stride] = argb; + array[offset + stride * 2] = argb; + array[offset + stride * 3] = argb; + + offset += stride * 4; + } + }; + + /** + * Destroys the ParticleRenderer. + * + */ + + + ParticleRenderer.prototype.destroy = function destroy() { + if (this.renderer.gl) { + this.renderer.gl.deleteBuffer(this.indexBuffer); + } + + _core$ObjectRenderer.prototype.destroy.call(this); + + this.shader.destroy(); + + this.indices = null; + this.tempMatrix = null; + }; + + return ParticleRenderer; +}(core.ObjectRenderer); + +exports.default = ParticleRenderer; + + +core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + +},{"../../core":65,"../../core/utils":125,"./ParticleBuffer":175,"./ParticleShader":177}],177:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../core/Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI + */ +var ParticleShader = function (_Shader) { + _inherits(ParticleShader, _Shader); + + /** + * @param {PIXI.Shader} gl - The webgl shader manager this shader works for. + */ + function ParticleShader(gl) { + _classCallCheck(this, ParticleShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'attribute vec4 aColor;', 'attribute vec2 aPositionCoord;', 'attribute float aRotation;', 'uniform mat3 projectionMatrix;', 'uniform vec4 uColor;', 'varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'void main(void){', ' float x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);', ' float y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);', ' vec2 v = vec2(x, y);', ' v = v + aPositionCoord;', ' gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = aColor * uColor;', '}'].join('\n'), + // hello + ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'uniform sampler2D uSampler;', 'void main(void){', ' vec4 color = texture2D(uSampler, vTextureCoord) * vColor;', ' gl_FragColor = color;', '}'].join('\n'))); + } + + return ParticleShader; +}(_Shader3.default); + +exports.default = ParticleShader; + +},{"../../core/Shader":44}],178:[function(require,module,exports){ +"use strict"; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + +if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + + if (x === 0 || isNaN(x)) { + return x; + } + + return x > 0 ? 1 : -1; + }; +} + +},{}],179:[function(require,module,exports){ +'use strict'; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger + +if (!Number.isInteger) { + Number.isInteger = function numberIsInteger(value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; + }; +} + +},{}],180:[function(require,module,exports){ +'use strict'; + +var _objectAssign = require('object-assign'); + +var _objectAssign2 = _interopRequireDefault(_objectAssign); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +if (!Object.assign) { + Object.assign = _objectAssign2.default; +} // References: +// https://github.com/sindresorhus/object-assign +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + +},{"object-assign":6}],181:[function(require,module,exports){ +'use strict'; + +require('./Object.assign'); + +require('./requestAnimationFrame'); + +require('./Math.sign'); + +require('./Number.isInteger'); + +if (!window.ArrayBuffer) { + window.ArrayBuffer = Array; +} + +if (!window.Float32Array) { + window.Float32Array = Array; +} + +if (!window.Uint32Array) { + window.Uint32Array = Array; +} + +if (!window.Uint16Array) { + window.Uint16Array = Array; +} + +},{"./Math.sign":178,"./Number.isInteger":179,"./Object.assign":180,"./requestAnimationFrame":182}],182:[function(require,module,exports){ +(function (global){ +'use strict'; + +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + +// Expected to be used with Browserfiy +// Browserify automatically detects the use of `global` and passes the +// correct reference of `global`, `self`, and finally `window` + +var ONE_FRAME_TIME = 16; + +// Date.now +if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; +} + +// performance.now +if (!(global.performance && global.performance.now)) { + var startTime = Date.now(); + + if (!global.performance) { + global.performance = {}; + } + + global.performance.now = function () { + return Date.now() - startTime; + }; +} + +// requestAnimationFrame +var lastTime = Date.now(); +var vendors = ['ms', 'moz', 'webkit', 'o']; + +for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { + var p = vendors[x]; + + global.requestAnimationFrame = global[p + 'RequestAnimationFrame']; + global.cancelAnimationFrame = global[p + 'CancelAnimationFrame'] || global[p + 'CancelRequestAnimationFrame']; +} + +if (!global.requestAnimationFrame) { + global.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + 'is not a function'); + } + + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + + if (delay < 0) { + delay = 0; + } + + lastTime = currentTime; + + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} + +if (!global.cancelAnimationFrame) { + global.cancelAnimationFrame = function (id) { + return clearTimeout(id); + }; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],183:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CountLimiter = require('./limiters/CountLimiter'); + +var _CountLimiter2 = _interopRequireDefault(_CountLimiter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SharedTicker = core.ticker.shared; + +/** + * Default number of uploads per frame using prepare plugin. + * + * @static + * @memberof PIXI.settings + * @name UPLOADS_PER_FRAME + * @type {number} + * @default 4 + */ +core.settings.UPLOADS_PER_FRAME = 4; + +/** + * The prepare manager provides functionality to upload content to the GPU. BasePrepare handles + * basic queuing functionality and is extended by {@link PIXI.prepare.WebGLPrepare} and {@link PIXI.prepare.CanvasPrepare} + * to provide preparation capabilities specific to their respective renderers. + * + * @example + * // Create a sprite + * const sprite = new PIXI.Sprite.fromImage('something.png'); + * + * // Load object into GPU + * app.renderer.plugins.prepare.upload(sprite, () => { + * + * //Texture(s) has been uploaded to GPU + * app.stage.addChild(sprite); + * + * }) + * + * @abstract + * @class + * @memberof PIXI.prepare + */ + +var BasePrepare = function () { + /** + * @param {PIXI.SystemRenderer} renderer - A reference to the current renderer + */ + function BasePrepare(renderer) { + var _this = this; + + _classCallCheck(this, BasePrepare); + + /** + * The limiter to be used to control how quickly items are prepared. + * @type {PIXI.prepare.CountLimiter|PIXI.prepare.TimeLimiter} + */ + this.limiter = new _CountLimiter2.default(core.settings.UPLOADS_PER_FRAME); + + /** + * Reference to the renderer. + * @type {PIXI.SystemRenderer} + * @protected + */ + this.renderer = renderer; + + /** + * The only real difference between CanvasPrepare and WebGLPrepare is what they pass + * to upload hooks. That different parameter is stored here. + * @type {PIXI.prepare.CanvasPrepare|PIXI.WebGLRenderer} + * @protected + */ + this.uploadHookHelper = null; + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + /** + * 'bound' call for prepareItems(). + * @type {Function} + * @private + */ + this.delayedTick = function () { + // unlikely, but in case we were destroyed between tick() and delayedTick() + if (!_this.queue) { + return; + } + _this.prepareItems(); + }; + + // hooks to find the correct texture + this.registerFindHook(findText); + this.registerFindHook(findTextStyle); + this.registerFindHook(findMultipleBaseTextures); + this.registerFindHook(findBaseTexture); + this.registerFindHook(findTexture); + + // upload hooks + this.registerUploadHook(drawText); + this.registerUploadHook(calculateTextStyle); + } + + /** + * Upload all the textures and graphics to the GPU. + * + * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item - + * Either the container or display object to search for items to upload, the items to upload themselves, + * or the callback function, if items have been added using `prepare.add`. + * @param {Function} [done] - Optional callback when all queued uploads have completed + */ + + + BasePrepare.prototype.upload = function upload(item, done) { + if (typeof item === 'function') { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) { + if (done) { + this.completes.push(done); + } + + if (!this.ticking) { + this.ticking = true; + SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); + } + } else if (done) { + done(); + } + }; + + /** + * Handle tick update + * + * @private + */ + + + BasePrepare.prototype.tick = function tick() { + setTimeout(this.delayedTick, 0); + }; + + /** + * Actually prepare items. This is handled outside of the tick because it will take a while + * and we do NOT want to block the current animation frame from rendering. + * + * @private + */ + + + BasePrepare.prototype.prepareItems = function prepareItems() { + this.limiter.beginFrame(); + // Upload the graphics + while (this.queue.length && this.limiter.allowedToUpload()) { + var item = this.queue[0]; + var uploaded = false; + + if (item && !item._destroyed) { + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.uploadHookHelper, item)) { + this.queue.shift(); + uploaded = true; + break; + } + } + } + + if (!uploaded) { + this.queue.shift(); + } + } + + // We're finished + if (!this.queue.length) { + this.ticking = false; + + var completes = this.completes.slice(0); + + this.completes.length = 0; + + for (var _i = 0, _len = completes.length; _i < _len; _i++) { + completes[_i](); + } + } else { + // if we are not finished, on the next rAF do this again + SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); + } + }; + + /** + * Adds hooks for finding items. + * + * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.registerFindHook = function registerFindHook(addHook) { + if (addHook) { + this.addHooks.push(addHook); + } + + return this; + }; + + /** + * Adds hooks for uploading items. + * + * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.registerUploadHook = function registerUploadHook(uploadHook) { + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + + return this; + }; + + /** + * Manually add an item to the uploading queue. + * + * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to + * add to the queue + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.add = function add(item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) { + for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { + this.add(item.children[_i2]); + } + } + + return this; + }; + + /** + * Destroys the plugin, don't use after this. + * + */ + + + BasePrepare.prototype.destroy = function destroy() { + if (this.ticking) { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.limiter = null; + this.uploadHookHelper = null; + }; + + return BasePrepare; +}(); + +/** + * Built-in hook to find multiple textures from objects like AnimatedSprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ + + +exports.default = BasePrepare; +function findMultipleBaseTextures(item, queue) { + var result = false; + + // Objects with mutliple textures + if (item && item._textures && item._textures.length) { + for (var i = 0; i < item._textures.length; i++) { + if (item._textures[i] instanceof core.Texture) { + var baseTexture = item._textures[i].baseTexture; + + if (queue.indexOf(baseTexture) === -1) { + queue.push(baseTexture); + result = true; + } + } + } + } + + return result; +} + +/** + * Built-in hook to find BaseTextures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTexture(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findTexture(item, queue) { + if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to draw PIXI.Text to its texture. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function drawText(helper, item) { + if (item instanceof core.Text) { + // updating text will return early if it is not dirty + item.updateText(true); + + return true; + } + + return false; +} + +/** + * Built-in hook to calculate a text style for a PIXI.Text object. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function calculateTextStyle(helper, item) { + if (item instanceof core.TextStyle) { + var font = item.toFontString(); + + core.TextMetrics.measureFont(font); + + return true; + } + + return false; +} + +/** + * Built-in hook to find Text objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Text object was found. + */ +function findText(item, queue) { + if (item instanceof core.Text) { + // push the text style to prepare it - this can be really expensive + if (queue.indexOf(item.style) === -1) { + queue.push(item.style); + } + // also push the text object so that we can render it (to canvas/texture) if needed + if (queue.indexOf(item) === -1) { + queue.push(item); + } + // also push the Text's texture for upload to GPU + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find TextStyle objects. + * + * @private + * @param {PIXI.TextStyle} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.TextStyle object was found. + */ +function findTextStyle(item, queue) { + if (item instanceof core.TextStyle) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +},{"../core":65,"./limiters/CountLimiter":186}],184:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CANVAS_START_SIZE = 16; + +/** + * The prepare manager provides functionality to upload content to the GPU + * This cannot be done directly for Canvas like in WebGL, but the effect can be achieved by drawing + * textures to an offline canvas. + * This draw call will force the texture to be moved onto the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ + +var CanvasPrepare = function (_BasePrepare) { + _inherits(CanvasPrepare, _BasePrepare); + + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasPrepare(renderer) { + _classCallCheck(this, CanvasPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this; + + /** + * An offline canvas to render textures to + * @type {HTMLCanvasElement} + * @private + */ + _this.canvas = document.createElement('canvas'); + _this.canvas.width = CANVAS_START_SIZE; + _this.canvas.height = CANVAS_START_SIZE; + + /** + * The context to the canvas + * @type {CanvasRenderingContext2D} + * @private + */ + _this.ctx = _this.canvas.getContext('2d'); + + // Add textures to upload + _this.registerUploadHook(uploadBaseTextures); + return _this; + } + + /** + * Destroys the plugin, don't use after this. + * + */ + + + CanvasPrepare.prototype.destroy = function destroy() { + _BasePrepare.prototype.destroy.call(this); + this.ctx = null; + this.canvas = null; + }; + + return CanvasPrepare; +}(_BasePrepare3.default); + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {*} prepare - Instance of CanvasPrepare + * @param {*} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = CanvasPrepare; +function uploadBaseTextures(prepare, item) { + if (item instanceof core.BaseTexture) { + var image = item.source; + + // Sometimes images (like atlas images) report a size of zero, causing errors on windows phone. + // So if the width or height is equal to zero then use the canvas size + // Otherwise use whatever is smaller, the image dimensions or the canvas dimensions. + var imageWidth = image.width === 0 ? prepare.canvas.width : Math.min(prepare.canvas.width, image.width); + var imageHeight = image.height === 0 ? prepare.canvas.height : Math.min(prepare.canvas.height, image.height); + + // Only a small subsections is required to be drawn to have the whole texture uploaded to the GPU + // A smaller draw can be faster. + prepare.ctx.drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, prepare.canvas.width, prepare.canvas.height); + + return true; + } + + return false; +} + +core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); + +},{"../../core":65,"../BasePrepare":183}],185:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLPrepare = require('./webgl/WebGLPrepare'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLPrepare).default; + } +}); + +var _CanvasPrepare = require('./canvas/CanvasPrepare'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasPrepare).default; + } +}); + +var _BasePrepare = require('./BasePrepare'); + +Object.defineProperty(exports, 'BasePrepare', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BasePrepare).default; + } +}); + +var _CountLimiter = require('./limiters/CountLimiter'); + +Object.defineProperty(exports, 'CountLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CountLimiter).default; + } +}); + +var _TimeLimiter = require('./limiters/TimeLimiter'); + +Object.defineProperty(exports, 'TimeLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TimeLimiter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./BasePrepare":183,"./canvas/CanvasPrepare":184,"./limiters/CountLimiter":186,"./limiters/TimeLimiter":187,"./webgl/WebGLPrepare":188}],186:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * CountLimiter limits the number of items handled by a {@link PIXI.prepare.BasePrepare} to a specified + * number of items per frame. + * + * @class + * @memberof PIXI + */ +var CountLimiter = function () { + /** + * @param {number} maxItemsPerFrame - The maximum number of items that can be prepared each frame. + */ + function CountLimiter(maxItemsPerFrame) { + _classCallCheck(this, CountLimiter); + + /** + * The maximum number of items that can be prepared each frame. + * @private + */ + this.maxItemsPerFrame = maxItemsPerFrame; + /** + * The number of items that can be prepared in the current frame. + * @type {number} + * @private + */ + this.itemsLeft = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + CountLimiter.prototype.beginFrame = function beginFrame() { + this.itemsLeft = this.maxItemsPerFrame; + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + CountLimiter.prototype.allowedToUpload = function allowedToUpload() { + return this.itemsLeft-- > 0; + }; + + return CountLimiter; +}(); + +exports.default = CountLimiter; + +},{}],187:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of milliseconds per frame. + * + * @class + * @memberof PIXI + */ +var TimeLimiter = function () { + /** + * @param {number} maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. + */ + function TimeLimiter(maxMilliseconds) { + _classCallCheck(this, TimeLimiter); + + /** + * The maximum milliseconds that can be spent preparing items each frame. + * @private + */ + this.maxMilliseconds = maxMilliseconds; + /** + * The start time of the current frame. + * @type {number} + * @private + */ + this.frameStart = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + TimeLimiter.prototype.beginFrame = function beginFrame() { + this.frameStart = Date.now(); + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + TimeLimiter.prototype.allowedToUpload = function allowedToUpload() { + return Date.now() - this.frameStart < this.maxMilliseconds; + }; + + return TimeLimiter; +}(); + +exports.default = TimeLimiter; + +},{}],188:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The prepare manager provides functionality to upload content to the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ +var WebGLPrepare = function (_BasePrepare) { + _inherits(WebGLPrepare, _BasePrepare); + + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLPrepare(renderer) { + _classCallCheck(this, WebGLPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this.renderer; + + // Add textures and graphics to upload + _this.registerFindHook(findGraphics); + _this.registerUploadHook(uploadBaseTextures); + _this.registerUploadHook(uploadGraphics); + return _this; + } + + return WebGLPrepare; +}(_BasePrepare3.default); +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = WebGLPrepare; +function uploadBaseTextures(renderer, item) { + if (item instanceof core.BaseTexture) { + // if the texture already has a GL texture, then the texture has been prepared or rendered + // before now. If the texture changed, then the changer should be calling texture.update() which + // reuploads the texture without need for preparing it again + if (!item._glTextures[renderer.CONTEXT_UID]) { + renderer.textureManager.updateTexture(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to upload PIXI.Graphics to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadGraphics(renderer, item) { + if (item instanceof core.Graphics) { + // if the item is not dirty and already has webgl data, then it got prepared or rendered + // before now and we shouldn't waste time updating it again + if (item.dirty || item.clearDirty || !item._webGL[renderer.plugins.graphics.CONTEXT_UID]) { + renderer.plugins.graphics.updateGraphics(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find graphics. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Graphics object was found. + */ +function findGraphics(item, queue) { + if (item instanceof core.Graphics) { + queue.push(item); + + return true; + } + + return false; +} + +core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); + +},{"../../core":65,"../BasePrepare":183}],189:[function(require,module,exports){ +(function (global){ +'use strict'; + +exports.__esModule = true; +exports.loader = exports.prepare = exports.particles = exports.mesh = exports.loaders = exports.interaction = exports.filters = exports.extras = exports.extract = exports.accessibility = undefined; + +var _polyfill = require('./polyfill'); + +Object.keys(_polyfill).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _polyfill[key]; + } + }); +}); + +var _core = require('./core'); + +Object.keys(_core).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _core[key]; + } + }); +}); + +var _deprecation = require('./deprecation'); + +var _deprecation2 = _interopRequireDefault(_deprecation); + +var _accessibility = require('./accessibility'); + +var accessibility = _interopRequireWildcard(_accessibility); + +var _extract = require('./extract'); + +var extract = _interopRequireWildcard(_extract); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// export core +_core.utils.mixins.performMixins(); + +/** + * Alias for {@link PIXI.loaders.shared}. + * @name loader + * @memberof PIXI + * @type {PIXI.loader.Loader} + */ + + +// handle mixins now, after all code has been added, including deprecation + + +// export libs +// import polyfills. Done as an export to make sure polyfills are imported first +var loader = loaders.shared || null; + +exports.accessibility = accessibility; +exports.extract = extract; +exports.extras = extras; +exports.filters = filters; +exports.interaction = interaction; +exports.loaders = loaders; +exports.mesh = mesh; +exports.particles = particles; +exports.prepare = prepare; +exports.loader = loader; + +// Apply the deprecations + +if (typeof _deprecation2.default === 'function') { + (0, _deprecation2.default)(exports); +} + +// Always export PixiJS globally. +global.PIXI = exports; // eslint-disable-line + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"./accessibility":42,"./core":65,"./deprecation":131,"./extract":133,"./extras":141,"./filters":153,"./interaction":159,"./loaders":162,"./mesh":171,"./particles":174,"./polyfill":181,"./prepare":185}]},{},[189])(189) +}); + + +//# sourceMappingURL=pixi.js.map diff --git a/js/pixi/4.8.1/pixi.min.js b/js/pixi/4.8.1/pixi.min.js new file mode 100644 index 0000000..b79f556 --- /dev/null +++ b/js/pixi/4.8.1/pixi.min.js @@ -0,0 +1,22 @@ +/*! + * pixi.js - v4.8.1 + * Compiled Wed, 06 Jun 2018 15:42:31 UTC + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.PIXI=t()}}(function(){var t;return function(){function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var h=new Error("Cannot find module '"+s+"'");throw h.code="MODULE_NOT_FOUND",h}var l=r[s]={exports:{}};e[s][0].call(l.exports,function(t){var r=e[s][1][t];return i(r||t)},l,l.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s0)-(t<0)},r.abs=function(t){var e=t>>31;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,(e|=r)|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,16843009*((t=(858993459&t)+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var i=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|i[t>>>16&255]<<8|i[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),(t=65535&(t|t>>>16))<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),(t=1023&(t|t>>>16))<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],2:[function(t,e,r){"use strict";function n(t,e,r){r=r||2;var n=e&&e.length,o=n?e[0]*r:t.length,a=i(t,0,o,r,!0),u=[];if(!a)return u;var h,l,d,f,p,v,g;if(n&&(a=c(t,e,a,r)),t.length>80*r){h=d=t[0],l=f=t[1];for(var y=r;yd&&(d=p),v>f&&(f=v);g=Math.max(d-h,f-l),g=0!==g?1/g:0}return s(a,u,r,h,l,g),u}function i(t,e,r,n,i){var o,s;if(i===A(t,e,r,n)>0)for(o=e;o=e;o-=n)s=P(o,t[o],t[o+1],s);return s&&T(s,s.next)&&(C(s),s=s.next),s}function o(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!T(n,n.next)&&0!==x(n.prev,n,n.next))n=n.next;else{if(C(n),(n=e=n.prev)===n.next)break;r=!0}}while(r||n!==e);return e}function s(t,e,r,n,i,c,d){if(t){!d&&c&&v(t,n,i,c);for(var f,p,g=t;t.prev!==t.next;)if(f=t.prev,p=t.next,c?u(t,n,i,c):a(t))e.push(f.i/r),e.push(t.i/r),e.push(p.i/r),C(t),t=p.next,g=p.next;else if((t=p)===g){d?1===d?(t=h(t,e,r),s(t,e,r,n,i,c,2)):2===d&&l(t,e,r,n,i,c):s(o(t),e,r,n,i,c,1);break}}}function a(t){var e=t.prev,r=t,n=t.next;if(x(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(_(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&x(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function u(t,e,r,n){var i=t.prev,o=t,s=t.next;if(x(i,o,s)>=0)return!1;for(var a=i.xo.x?i.x>s.x?i.x:s.x:o.x>s.x?o.x:s.x,l=i.y>o.y?i.y>s.y?i.y:s.y:o.y>s.y?o.y:s.y,c=y(a,u,e,r,n),d=y(h,l,e,r,n),f=t.prevZ,p=t.nextZ;f&&f.z>=c&&p&&p.z<=d;){if(f!==t.prev&&f!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,f.x,f.y)&&x(f.prev,f,f.next)>=0)return!1;if(f=f.prevZ,p!==t.prev&&p!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,p.x,p.y)&&x(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(;f&&f.z>=c;){if(f!==t.prev&&f!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,f.x,f.y)&&x(f.prev,f,f.next)>=0)return!1;f=f.prevZ}for(;p&&p.z<=d;){if(p!==t.prev&&p!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,p.x,p.y)&&x(p.prev,p,p.next)>=0)return!1;p=p.nextZ}return!0}function h(t,e,r){var n=t;do{var i=n.prev,o=n.next.next;!T(i,o)&&w(i,n,n.next,o)&&S(i,o)&&S(o,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(o.i/r),C(n),C(n.next),n=t=o),n=n.next}while(n!==t);return n}function l(t,e,r,n,i,a){var u=t;do{for(var h=u.next.next;h!==u.prev;){if(u.i!==h.i&&b(u,h)){var l=M(u,h);return u=o(u,u.next),l=o(l,l.next),s(u,e,r,n,i,a),void s(l,e,r,n,i,a)}h=h.next}u=u.next}while(u!==t)}function c(t,e,r,n){var s,a,u,h,l,c=[];for(s=0,a=e.length;s=n.next.y&&n.next.y!==n.y){var a=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=i&&a>s){if(s=a,a===i){if(o===n.y)return n;if(o===n.next.y)return n.next}r=n.x=n.x&&n.x>=l&&i!==n.x&&_(or.x)&&S(n,t)&&(r=n,d=u),n=n.next;return r}function v(t,e,r,n){var i=t;do{null===i.z&&(i.z=y(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,g(i)}function g(t){var e,r,n,i,o,s,a,u,h=1;do{for(r=t,t=null,o=null,s=0;r;){for(s++,n=r,a=0,e=0;e0||u>0&&n;)0!==a&&(0===u||!n||r.z<=n.z)?(i=r,r=r.nextZ,a--):(i=n,n=n.nextZ,u--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;r=n}o.nextZ=null,h*=2}while(s>1);return t}function y(t,e,r,n,i){return t=32767*(t-r)*i,e=32767*(e-n)*i,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1}function m(t){var e=t,r=t;do{e.x=0&&(t-s)*(n-a)-(r-s)*(e-a)>=0&&(r-s)*(o-a)-(i-s)*(n-a)>=0}function b(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!E(t,e)&&S(t,e)&&S(e,t)&&O(t,e)}function x(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function T(t,e){return t.x===e.x&&t.y===e.y}function w(t,e,r,n){return!!(T(t,e)&&T(r,n)||T(t,n)&&T(r,e))||x(t,e,r)>0!=x(t,e,n)>0&&x(r,n,t)>0!=x(r,n,e)>0}function E(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&w(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}function S(t,e){return x(t.prev,t,t.next)<0?x(t,e,t.next)>=0&&x(t,t.prev,e)>=0:x(t,e,t.prev)<0||x(t,t.next,e)<0}function O(t,e){var r=t,n=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{r.y>o!=r.next.y>o&&r.next.y!==r.y&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}function M(t,e){var r=new R(t.i,t.x,t.y),n=new R(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function P(t,e,r,n){var i=new R(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function C(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function R(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(t,e,r,n){for(var i=0,o=e,s=r-n;o0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],3:[function(t,e,r){"use strict";function n(){}function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function o(){this._events=new n,this._eventsCount=0}var s=Object.prototype.hasOwnProperty,a="~";Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(a=!1)),o.prototype.eventNames=function(){var t,e,r=[];if(0===this._eventsCount)return r;for(e in t=this._events)s.call(t,e)&&r.push(a?e.slice(1):e);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t,e){var r=a?a+t:t,n=this._events[r];if(e)return!!n;if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i=0;n--){var i=t[n];"."===i?t.splice(n,1):".."===i?(t.splice(n,1),r++):r&&(t.splice(n,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}function n(t,e){if(t.filter)return t.filter(e);for(var r=[],n=0;n=-1&&!i;o--){var s=o>=0?arguments[o]:t.cwd();if("string"!=typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(r=s+"/"+r,i="/"===s.charAt(0))}return r=e(n(r.split("/"),function(t){return!!t}),!i).join("/"),(i?"/":"")+r||"."},r.normalize=function(t){var i=r.isAbsolute(t),o="/"===s(t,-1);return t=e(n(t.split("/"),function(t){return!!t}),!i).join("/"),t||i||(t="."),t&&o&&(t+="/"),(i?"/":"")+t},r.isAbsolute=function(t){return"/"===t.charAt(0)},r.join=function(){var t=Array.prototype.slice.call(arguments,0);return r.normalize(n(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},r.relative=function(t,e){function n(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=r.resolve(t).substr(1),e=r.resolve(e).substr(1);for(var i=n(t.split("/")),o=n(e.split("/")),s=Math.min(i.length,o.length),a=s,u=0;u=t.byteLength?n.bufferSubData(this.type,e,t):n.bufferData(this.type,t,this.drawType),this.data=t},i.prototype.bind=function(){this.gl.bindBuffer(this.type,this.buffer)},i.createVertexBuffer=function(t,e,r){return new i(t,t.ARRAY_BUFFER,e,r)},i.createIndexBuffer=function(t,e,r){return new i(t,t.ELEMENT_ARRAY_BUFFER,e,r)},i.create=function(t,e,r,n){return new i(t,e,r,n)},i.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer)},e.exports=i},{}],10:[function(t,e,r){var n=t("./GLTexture"),i=function(t,e,r){this.gl=t,this.framebuffer=t.createFramebuffer(),this.stencil=null,this.texture=null,this.width=e||100,this.height=r||100};i.prototype.enableTexture=function(t){var e=this.gl;this.texture=t||new n(e),this.texture.bind(),this.bind(),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0)},i.prototype.enableStencil=function(){if(!this.stencil){var t=this.gl;this.stencil=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.stencil),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.stencil),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,this.width,this.height)}},i.prototype.clear=function(t,e,r,n){this.bind();var i=this.gl;i.clearColor(t,e,r,n),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT)},i.prototype.bind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer)},i.prototype.unbind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)},i.prototype.resize=function(t,e){var r=this.gl;this.width=t,this.height=e,this.texture&&this.texture.uploadData(null,t,e),this.stencil&&(r.bindRenderbuffer(r.RENDERBUFFER,this.stencil),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e))},i.prototype.destroy=function(){var t=this.gl;this.texture&&this.texture.destroy(),t.deleteFramebuffer(this.framebuffer),this.gl=null,this.stencil=null,this.texture=null},i.createRGBA=function(t,e,r,o){var s=n.fromData(t,null,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},i.createFloat32=function(t,e,r,o){var s=new n.fromData(t,o,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},e.exports=i},{"./GLTexture":12}],11:[function(t,e,r){var n=t("./shader/compileProgram"),i=t("./shader/extractAttributes"),o=t("./shader/extractUniforms"),s=t("./shader/setPrecision"),a=t("./shader/generateUniformAccessObject"),u=function(t,e,r,u,h){this.gl=t,u&&(e=s(e,u),r=s(r,u)),this.program=n(t,e,r,h),this.attributes=i(t,this.program),this.uniformData=o(t,this.program),this.uniforms=a(t,this.uniformData)};u.prototype.bind=function(){return this.gl.useProgram(this.program),this},u.prototype.destroy=function(){this.attributes=null,this.uniformData=null,this.uniforms=null,this.gl.deleteProgram(this.program)},e.exports=u},{"./shader/compileProgram":17,"./shader/extractAttributes":19,"./shader/extractUniforms":20,"./shader/generateUniformAccessObject":21,"./shader/setPrecision":25}],12:[function(t,e,r){var n=function(t,e,r,n,i){this.gl=t,this.texture=t.createTexture(),this.mipmap=!1,this.premultiplyAlpha=!1,this.width=e||-1,this.height=r||-1,this.format=n||t.RGBA,this.type=i||t.UNSIGNED_BYTE};n.prototype.upload=function(t){this.bind();var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var r=t.videoWidth||t.width,n=t.videoHeight||t.height;n!==this.height||r!==this.width?e.texImage2D(e.TEXTURE_2D,0,this.format,this.format,this.type,t):e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.format,this.type,t),this.width=r,this.height=n};var i=!1;n.prototype.uploadData=function(t,e,r){this.bind();var n=this.gl;if(t instanceof Float32Array){if(!i){if(!n.getExtension("OES_texture_float"))throw new Error("floating point textures not available");i=!0}this.type=n.FLOAT}else this.type=this.type||n.UNSIGNED_BYTE;n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),e!==this.width||r!==this.height?n.texImage2D(n.TEXTURE_2D,0,this.format,e,r,0,this.format,this.type,t||null):n.texSubImage2D(n.TEXTURE_2D,0,0,0,e,r,this.format,this.type,t||null),this.width=e,this.height=r},n.prototype.bind=function(t){var e=this.gl;void 0!==t&&e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,this.texture)},n.prototype.unbind=function(){var t=this.gl;t.bindTexture(t.TEXTURE_2D,null)},n.prototype.minFilter=function(t){var e=this.gl;this.bind(),this.mipmap?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.magFilter=function(t){var e=this.gl;this.bind(),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.enableMipmap=function(){var t=this.gl;this.bind(),this.mipmap=!0,t.generateMipmap(t.TEXTURE_2D)},n.prototype.enableLinearScaling=function(){this.minFilter(!0),this.magFilter(!0)},n.prototype.enableNearestScaling=function(){this.minFilter(!1),this.magFilter(!1)},n.prototype.enableWrapClamp=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)},n.prototype.enableWrapRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT)},n.prototype.enableWrapMirrorRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.MIRRORED_REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.MIRRORED_REPEAT)},n.prototype.destroy=function(){this.gl.deleteTexture(this.texture)},n.fromSource=function(t,e,r){var i=new n(t);return i.premultiplyAlpha=r||!1,i.upload(e),i},n.fromData=function(t,e,r,i){var o=new n(t);return o.uploadData(e,r,i),o},e.exports=n},{}],13:[function(t,e,r){function n(t,e){if(this.nativeVaoExtension=null,n.FORCE_NATIVE||(this.nativeVaoExtension=t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object")),this.nativeState=e,this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var r=t.getParameter(t.MAX_VERTEX_ATTRIBS);this.nativeState={tempAttribState:new Array(r),attribState:new Array(r)}}this.gl=t,this.attributes=[],this.indexBuffer=null,this.dirty=!1}var i=t("./setVertexAttribArrays");n.prototype.constructor=n,e.exports=n,n.FORCE_NATIVE=!1,n.prototype.bind=function(){if(this.nativeVao){if(this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao),this.dirty)return this.dirty=!1,this.activate(),this;this.indexBuffer&&this.indexBuffer.bind()}else this.activate();return this},n.prototype.unbind=function(){return this.nativeVao&&this.nativeVaoExtension.bindVertexArrayOES(null),this},n.prototype.activate=function(){for(var t=this.gl,e=null,r=0;r1)for(var r=1;r1&&(n=r[0]+"@",t=r[1]),t=t.replace(D,"."),n+s(t.split("."),e).join(".")}function u(t){for(var e,r,n=[],i=0,o=t.length;i=55296&&e<=56319&&i65535&&(t-=65536,e+=F(t>>>10&1023|55296),t=56320|1023&t),e+=F(t)}).join("")}function l(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:w}function c(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function d(t,e,r){var n=0;for(t=r?B(t/M):t>>1,t+=B(t/e);t>N*S>>1;n+=w)t=B(t/N);return B(n+(N+1)*t/(t+O))}function f(t){var e,r,n,i,s,a,u,c,f,p,v=[],g=t.length,y=0,m=C,_=P;for(r=t.lastIndexOf(R),r<0&&(r=0),n=0;n=128&&o("not-basic"),v.push(t.charCodeAt(n));for(i=r>0?r+1:0;i=g&&o("invalid-input"),c=l(t.charCodeAt(i++)),(c>=w||c>B((T-y)/a))&&o("overflow"),y+=c*a,f=u<=_?E:u>=_+S?S:u-_,!(cB(T/p)&&o("overflow"),a*=p;e=v.length+1,_=d(y-s,e,0==s),B(y/e)>T-m&&o("overflow"),m+=B(y/e),y%=e,v.splice(y++,0,m)}return h(v)}function p(t){var e,r,n,i,s,a,h,l,f,p,v,g,y,m,_,b=[];for(t=u(t),g=t.length,e=C,r=0,s=P,a=0;a=e&&vB((T-r)/y)&&o("overflow"),r+=(h-e)*y,e=h,a=0;aT&&o("overflow"),v==e){for(l=r,f=w;p=f<=s?E:f>=s+S?S:f-s,!(l= 0x80 (not a basic code point)","invalid-input":"Invalid input"},N=w-E,B=Math.floor,F=String.fromCharCode;if(b={version:"1.4.1",ucs2:{decode:u,encode:h},decode:f,encode:p,toASCII:g,toUnicode:v},"function"==typeof t&&"object"==typeof t.amd&&t.amd)t("punycode",function(){return b});else if(y&&m)if(r.exports==y)m.exports=b;else for(x in b)b.hasOwnProperty(x)&&(y[x]=b[x]);else i.punycode=b}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],28:[function(t,e,r){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,r,o){e=e||"&",r=r||"=";var s={};if("string"!=typeof t||0===t.length)return s;var a=/\+/g;t=t.split(e);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var h=t.length;u>0&&h>u&&(h=u);for(var l=0;l=0?(c=v.substr(0,g),d=v.substr(g+1)):(c=v,d=""),f=decodeURIComponent(c),p=decodeURIComponent(d),n(s,f)?i(s[f])?s[f].push(p):s[f]=[s[f],p]:s[f]=p}return s};var i=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],29:[function(t,e,r){"use strict";function n(t,e){if(t.map)return t.map(e);for(var r=[],n=0;n=i||0===r)){r=e+r>i?i-e:r;var o=i-r;for(n=e;n0&&void 0!==arguments[0]?arguments[0]:"",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10;i(this,t),this.baseUrl=r,this.progress=0,this.loading=!1,this.defaultQueryString="",this._beforeMiddleware=[],this._afterMiddleware=[],this._resourcesParsing=[],this._boundLoadResource=function(t,r){return e._loadResource(t,r)},this._queue=d.queue(this._boundLoadResource,n),this._queue.pause(),this.resources={},this.onProgress=new u.default,this.onError=new u.default,this.onLoad=new u.default,this.onStart=new u.default,this.onComplete=new u.default}return t.prototype.add=function(t,e,r,n){if(Array.isArray(t)){for(var i=0;i0||e.responseType===t.XHR_RESPONSE_TYPE.BUFFER)?n=200:1223===n&&(n=204),2!=(n/100|0))return void this.abort("["+e.status+"] "+e.statusText+": "+e.responseURL);if(this.xhrType===t.XHR_RESPONSE_TYPE.TEXT)this.data=r,this.type=t.TYPE.TEXT;else if(this.xhrType===t.XHR_RESPONSE_TYPE.JSON)try{this.data=JSON.parse(r),this.type=t.TYPE.JSON}catch(t){return void this.abort("Error trying to parse loaded json: "+t)}else if(this.xhrType===t.XHR_RESPONSE_TYPE.DOCUMENT)try{if(window.DOMParser){var i=new DOMParser;this.data=i.parseFromString(r,"text/xml")}else{var o=document.createElement("div");o.innerHTML=r,this.data=o}this.type=t.TYPE.XML}catch(t){return void this.abort("Error trying to parse loaded xml: "+t)}else this.data=e.response||r;this.complete()},t.prototype._determineCrossOrigin=function(t,e){if(0===t.indexOf("data:"))return"";e=e||window.location,p||(p=document.createElement("a")),p.href=t,t=(0,l.default)(p.href,{strictMode:!0});var r=!t.port&&""===e.port||t.port===e.port,n=t.protocol?t.protocol+":":"";return t.host===e.hostname&&r&&n===e.protocol?"":"anonymous"},t.prototype._determineXhrType=function(){return t._xhrTypeMap[this.extension]||t.XHR_RESPONSE_TYPE.TEXT},t.prototype._determineLoadType=function(){return t._loadTypeMap[this.extension]||t.LOAD_TYPE.XHR},t.prototype._getExtension=function(){var t=this.url,e="";if(this.isDataUrl){var r=t.indexOf("/");e=t.substring(r+1,t.indexOf(";",r))}else{var n=t.indexOf("?"),i=t.indexOf("#"),o=Math.min(n>-1?n:t.length,i>-1?i:t.length);t=t.substring(0,o),e=t.substring(t.lastIndexOf(".")+1)}return e.toLowerCase()},t.prototype._getMimeFromXhrType=function(e){switch(e){case t.XHR_RESPONSE_TYPE.BUFFER:return"application/octet-binary";case t.XHR_RESPONSE_TYPE.BLOB:return"application/blob";case t.XHR_RESPONSE_TYPE.DOCUMENT:return"application/xml";case t.XHR_RESPONSE_TYPE.JSON:return"application/json";case t.XHR_RESPONSE_TYPE.DEFAULT:case t.XHR_RESPONSE_TYPE.TEXT:default:return"text/plain"}},u(t,[{key:"isDataUrl",get:function(){return this._hasFlag(t.STATUS_FLAGS.DATA_URL)}},{key:"isComplete",get:function(){return this._hasFlag(t.STATUS_FLAGS.COMPLETE)}},{key:"isLoading",get:function(){return this._hasFlag(t.STATUS_FLAGS.LOADING)}}]),t}();r.default=v,v.STATUS_FLAGS={NONE:0,DATA_URL:1,COMPLETE:2,LOADING:4},v.TYPE={UNKNOWN:0,JSON:1,XML:2,IMAGE:3,AUDIO:4,VIDEO:5,TEXT:6},v.LOAD_TYPE={XHR:1,IMAGE:2,AUDIO:3,VIDEO:4},v.XHR_RESPONSE_TYPE={DEFAULT:"text",BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"},v._loadTypeMap={gif:v.LOAD_TYPE.IMAGE,png:v.LOAD_TYPE.IMAGE,bmp:v.LOAD_TYPE.IMAGE,jpg:v.LOAD_TYPE.IMAGE,jpeg:v.LOAD_TYPE.IMAGE,tif:v.LOAD_TYPE.IMAGE,tiff:v.LOAD_TYPE.IMAGE,webp:v.LOAD_TYPE.IMAGE,tga:v.LOAD_TYPE.IMAGE,svg:v.LOAD_TYPE.IMAGE,"svg+xml":v.LOAD_TYPE.IMAGE,mp3:v.LOAD_TYPE.AUDIO,ogg:v.LOAD_TYPE.AUDIO,wav:v.LOAD_TYPE.AUDIO,mp4:v.LOAD_TYPE.VIDEO,webm:v.LOAD_TYPE.VIDEO},v._xhrTypeMap={xhtml:v.XHR_RESPONSE_TYPE.DOCUMENT,html:v.XHR_RESPONSE_TYPE.DOCUMENT,htm:v.XHR_RESPONSE_TYPE.DOCUMENT,xml:v.XHR_RESPONSE_TYPE.DOCUMENT,tmx:v.XHR_RESPONSE_TYPE.DOCUMENT,svg:v.XHR_RESPONSE_TYPE.DOCUMENT,tsx:v.XHR_RESPONSE_TYPE.DOCUMENT,gif:v.XHR_RESPONSE_TYPE.BLOB,png:v.XHR_RESPONSE_TYPE.BLOB,bmp:v.XHR_RESPONSE_TYPE.BLOB,jpg:v.XHR_RESPONSE_TYPE.BLOB,jpeg:v.XHR_RESPONSE_TYPE.BLOB,tif:v.XHR_RESPONSE_TYPE.BLOB,tiff:v.XHR_RESPONSE_TYPE.BLOB,webp:v.XHR_RESPONSE_TYPE.BLOB,tga:v.XHR_RESPONSE_TYPE.BLOB,json:v.XHR_RESPONSE_TYPE.JSON,text:v.XHR_RESPONSE_TYPE.TEXT,txt:v.XHR_RESPONSE_TYPE.TEXT,ttf:v.XHR_RESPONSE_TYPE.BUFFER,otf:v.XHR_RESPONSE_TYPE.BUFFER},v.EMPTY_GIF="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="},{"mini-signals":5,"parse-uri":7}],34:[function(t,e,r){"use strict";function n(){}function i(t,e,r,n){var i=0,o=t.length;!function s(a){if(a||i===o)return void(r&&r(a));n?setTimeout(function(){e(t[i++],s)},1):e(t[i++],s)}()}function o(t){return function(){if(null===t)throw new Error("Callback was already called.");var e=t;t=null,e.apply(this,arguments)}}function s(t,e){function r(t,e,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(a.started=!0,null==t&&a.idle())return void setTimeout(function(){return a.drain()},1);var i={data:t,callback:"function"==typeof r?r:n};e?a._tasks.unshift(i):a._tasks.push(i),setTimeout(function(){return a.process()},1)}function i(t){return function(){s-=1,t.callback.apply(t,arguments),null!=arguments[0]&&a.error(arguments[0],t.data),s<=a.concurrency-a.buffer&&a.unsaturated(),a.idle()&&a.drain(),a.process()}}if(null==e)e=1;else if(0===e)throw new Error("Concurrency must not be zero");var s=0,a={_tasks:[],concurrency:e,saturated:n,unsaturated:n,buffer:e/4,empty:n,drain:n,error:n,started:!1,paused:!1,push:function(t,e){r(t,!1,e)},kill:function(){s=0,a.drain=n,a.started=!1,a._tasks=[]},unshift:function(t,e){r(t,!0,e)},process:function(){for(;!a.paused&&s>2,o[1]=(3&n[0])<<4|n[1]>>4,o[2]=(15&n[1])<<2|n[2]>>6,o[3]=63&n[2];switch(r-(t.length-1)){case 2:o[3]=64,o[2]=64;break;case 1:o[3]=64}for(var a=0;a",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(f),v=["'"].concat(p),g=["%","/","?",";","#"].concat(v),y=["/","?","#"],m=/^[+a-z0-9A-Z_-]{0,63}$/,_=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,b={javascript:!0,"javascript:":!0},x={javascript:!0,"javascript:":!0},T={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},w=t("querystring");n.prototype.parse=function(t,e,r){if(!h.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var n=t.indexOf("?"),i=-1!==n&&n127?L+="x":L+=D[N];if(!L.match(m)){var F=A.slice(0,O),k=A.slice(O+1),j=D.match(_);j&&(F.push(j[1]),k.unshift(j[2])),k.length&&(a="/"+k.join(".")+a),this.hostname=F.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),R||(this.hostname=u.toASCII(this.hostname));var U=this.port?":"+this.port:"",X=this.hostname||"";this.host=X+U,this.href+=this.host,R&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==a[0]&&(a="/"+a))}if(!b[p])for(var O=0,I=v.length;O0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return r.search=t.search,r.query=t.query,h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!w.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var O=w.slice(-1)[0],M=(r.host||t.host||w.length>1)&&("."===O||".."===O)||""===O,P=0,C=w.length;C>=0;C--)O=w[C],"."===O?w.splice(C,1):".."===O?(w.splice(C,1),P++):P&&(w.splice(C,1),P--);if(!_&&!b)for(;P--;P)w.unshift("..");!_||""===w[0]||w[0]&&"/"===w[0].charAt(0)||w.unshift(""),M&&"/"!==w.join("/").substr(-1)&&w.push("");var R=""===w[0]||w[0]&&"/"===w[0].charAt(0);if(E){r.hostname=r.host=R?"":w.length?w.shift():"";var S=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return _=_||r.host&&w.length,_&&!R&&w.unshift(""),w.length?r.pathname=w.join("/"):(r.pathname=null,r.path=null),h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},n.prototype.parseHost=function(){var t=this.host,e=c.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":39,punycode:27,querystring:30}],39:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],40:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../core"),s=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(o),a=t("ismobilejs"),u=n(a),h=t("./accessibleTarget"),l=n(h);s.utils.mixins.delayMixin(s.DisplayObject.prototype,l.default);var c=100,d=0,f=0,p=2,v=function(){function t(e){i(this,t),!u.default.tablet&&!u.default.phone||navigator.isCocoonJS||this.createTouchHook();var r=document.createElement("div");r.style.width=c+"px",r.style.height=c+"px",r.style.position="absolute",r.style.top=d+"px",r.style.left=f+"px",r.style.zIndex=p,this.div=r,this.pool=[],this.renderId=0,this.debug=!1,this.renderer=e,this.children=[],this._onKeyDown=this._onKeyDown.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this.isActive=!1,this.isMobileAccessabillity=!1,window.addEventListener("keydown",this._onKeyDown,!1)}return t.prototype.createTouchHook=function(){var t=this,e=document.createElement("button");e.style.width="1px",e.style.height="1px",e.style.position="absolute",e.style.top="-1000px",e.style.left="-1000px",e.style.zIndex=2,e.style.backgroundColor="#FF0000",e.title="HOOK DIV",e.addEventListener("focus",function(){t.isMobileAccessabillity=!0,t.activate(),document.body.removeChild(e)}),document.body.appendChild(e)},t.prototype.activate=function(){this.isActive||(this.isActive=!0,window.document.addEventListener("mousemove",this._onMouseMove,!0),window.removeEventListener("keydown",this._onKeyDown,!1),this.renderer.on("postrender",this.update,this),this.renderer.view.parentNode&&this.renderer.view.parentNode.appendChild(this.div))},t.prototype.deactivate=function(){this.isActive&&!this.isMobileAccessabillity&&(this.isActive=!1,window.document.removeEventListener("mousemove",this._onMouseMove),window.addEventListener("keydown",this._onKeyDown,!1),this.renderer.off("postrender",this.update),this.div.parentNode&&this.div.parentNode.removeChild(this.div))},t.prototype.updateAccessibleObjects=function(t){if(t.visible){t.accessible&&t.interactive&&(t._accessibleActive||this.addChild(t),t.renderId=this.renderId);for(var e=t.children,r=0;rthis.renderer.width&&(t.width=this.renderer.width-t.x),t.y+t.height>this.renderer.height&&(t.height=this.renderer.height-t.y)},t.prototype.addChild=function(t){var e=this.pool.pop();e||(e=document.createElement("button"),e.style.width=c+"px",e.style.height=c+"px",e.style.backgroundColor=this.debug?"rgba(255,0,0,0.5)":"transparent",e.style.position="absolute",e.style.zIndex=p,e.style.borderStyle="none",navigator.userAgent.toLowerCase().indexOf("chrome")>-1?e.setAttribute("aria-live","off"):e.setAttribute("aria-live","polite"),navigator.userAgent.match(/rv:.*Gecko\//)?e.setAttribute("aria-relevant","additions"):e.setAttribute("aria-relevant","text"),e.addEventListener("click",this._onClick.bind(this)),e.addEventListener("focus",this._onFocus.bind(this)),e.addEventListener("focusout",this._onFocusOut.bind(this))),t.accessibleTitle&&null!==t.accessibleTitle?e.title=t.accessibleTitle:t.accessibleHint&&null!==t.accessibleHint||(e.title="displayObject "+t.tabIndex),t.accessibleHint&&null!==t.accessibleHint&&e.setAttribute("aria-label",t.accessibleHint),t._accessibleActive=!0,t._accessibleDiv=e,e.displayObject=t,this.children.push(t),this.div.appendChild(t._accessibleDiv),t._accessibleDiv.tabIndex=t.tabIndex},t.prototype._onClick=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"click",e.eventData)},t.prototype._onFocus=function(t){t.target.getAttribute("aria-live","off")||t.target.setAttribute("aria-live","assertive");var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseover",e.eventData)},t.prototype._onFocusOut=function(t){t.target.getAttribute("aria-live","off")||t.target.setAttribute("aria-live","polite");var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseout",e.eventData)},t.prototype._onKeyDown=function(t){9===t.keyCode&&this.activate()},t.prototype._onMouseMove=function(t){0===t.movementX&&0===t.movementY||this.deactivate()},t.prototype.destroy=function(){this.div=null;for(var t=0;t]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i,r.SHAPES={POLY:0,RECT:1,CIRC:2,ELIP:3,RREC:4},r.PRECISION={LOW:"lowp",MEDIUM:"mediump",HIGH:"highp"},r.TRANSFORM_MODE={STATIC:0,DYNAMIC:1},r.TEXT_GRADIENT={LINEAR_VERTICAL:0,LINEAR_HORIZONTAL:1},r.UPDATE_PRIORITY={INTERACTION:50,HIGH:25,NORMAL:0,LOW:-25,UTILITY:-50}},{}],47:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../math"),o=function(){function t(){n(this,t),this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.rect=null}return t.prototype.isEmpty=function(){return this.minX>this.maxX||this.minY>this.maxY},t.prototype.clear=function(){this.updateID++,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0},t.prototype.getRectangle=function(t){return this.minX>this.maxX||this.minY>this.maxY?i.Rectangle.EMPTY:(t=t||new i.Rectangle(0,0,1,1),t.x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)},t.prototype.addPoint=function(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)},t.prototype.addQuad=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY,o=t[0],s=t[1];e=on?o:n,i=s>i?s:i,o=t[2],s=t[3],e=on?o:n,i=s>i?s:i,o=t[4],s=t[5],e=on?o:n,i=s>i?s:i,o=t[6],s=t[7],e=on?o:n,i=s>i?s:i,this.minX=e,this.minY=r,this.maxX=n,this.maxY=i},t.prototype.addFrame=function(t,e,r,n,i){var o=t.worldTransform,s=o.a,a=o.b,u=o.c,h=o.d,l=o.tx,c=o.ty,d=this.minX,f=this.minY,p=this.maxX,v=this.maxY,g=s*e+u*r+l,y=a*e+h*r+c;d=gp?g:p,v=y>v?y:v,g=s*n+u*r+l,y=a*n+h*r+c,d=gp?g:p,v=y>v?y:v,g=s*e+u*i+l,y=a*e+h*i+c,d=gp?g:p,v=y>v?y:v,g=s*n+u*i+l,y=a*n+h*i+c,d=gp?g:p,v=y>v?y:v,this.minX=d,this.minY=f,this.maxX=p,this.maxY=v},t.prototype.addVertices=function(t,e,r,n){for(var i=t.worldTransform,o=i.a,s=i.b,a=i.c,u=i.d,h=i.tx,l=i.ty,c=this.minX,d=this.minY,f=this.maxX,p=this.maxY,v=r;vf?m:f,p=_>p?_:p}this.minX=c,this.minY=d,this.maxX=f,this.maxY=p},t.prototype.addBounds=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY;this.minX=t.minXn?t.maxX:n,this.maxY=t.maxY>i?t.maxY:i},t.prototype.addBoundsMask=function(t,e){var r=t.minX>e.minX?t.minX:e.minX,n=t.minY>e.minY?t.minY:e.minY,i=t.maxXu?i:u,this.maxY=o>h?o:h}},t.prototype.addBoundsArea=function(t,e){var r=t.minX>e.x?t.minX:e.x,n=t.minY>e.y?t.minY:e.y,i=t.maxXu?i:u,this.maxY=o>h?o:h}},t}();r.default=o},{"../math":70}],48:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r1)for(var r=0;rthis.children.length)throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length);return t.parent&&t.parent.removeChild(t),t.parent=this,t.transform._parentID=-1,this.children.splice(e,0,t),this._boundsID++,this.onChildrenChange(e),t.emit("added",this),t},e.prototype.swapChildren=function(t,e){if(t!==e){var r=this.getChildIndex(t),n=this.getChildIndex(e);this.children[r]=e,this.children[n]=t,this.onChildrenChange(r=this.children.length)throw new Error("The index "+e+" supplied is out of bounds "+this.children.length);var r=this.getChildIndex(t);(0,a.removeItems)(this.children,r,1),this.children.splice(e,0,t),this.onChildrenChange(e)},e.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Index ("+t+") does not exist.");return this.children[t]},e.prototype.removeChild=function(t){var e=arguments.length;if(e>1)for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=t,n="number"==typeof e?e:this.children.length,i=n-r,o=void 0;if(i>0&&i<=n){o=this.children.splice(r,i);for(var s=0;s2&&void 0!==arguments[2]&&arguments[2]||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)},e.prototype.toLocal=function(t,e,r,n){return e&&(t=e.toGlobal(t,r,n)),n||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,r)},e.prototype.renderWebGL=function(t){},e.prototype.renderCanvas=function(t){},e.prototype.setParent=function(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t},e.prototype.setTransform=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0,u=arguments.length>8&&void 0!==arguments[8]?arguments[8]:0;return this.position.x=t,this.position.y=e,this.scale.x=r||1,this.scale.y=n||1,this.rotation=i,this.skew.x=o,this.skew.y=s,this.pivot.x=a,this.pivot.y=u,this},e.prototype.destroy=function(){this.removeAllListeners(),this.parent&&this.parent.removeChild(this),this.transform=null,this.parent=null,this._bounds=null,this._currentBounds=null,this._mask=null,this.filterArea=null,this.interactive=!1,this.interactiveChildren=!1,this._destroyed=!0},a(e,[{key:"_tempDisplayObjectParent",get:function(){return null===this.tempDisplayObjectParent&&(this.tempDisplayObjectParent=new e),this.tempDisplayObjectParent}},{key:"x",get:function(){return this.position.x},set:function(t){this.transform.position.x=t}},{key:"y",get:function(){return this.position.y},set:function(t){this.transform.position.y=t}},{key:"worldTransform",get:function(){return this.transform.worldTransform}},{key:"localTransform",get:function(){return this.transform.localTransform}},{key:"position",get:function(){return this.transform.position},set:function(t){this.transform.position.copy(t)}},{key:"scale",get:function(){return this.transform.scale},set:function(t){this.transform.scale.copy(t)}},{key:"pivot",get:function(){return this.transform.pivot},set:function(t){this.transform.pivot.copy(t)}},{key:"skew",get:function(){return this.transform.skew},set:function(t){this.transform.skew.copy(t)}},{key:"rotation",get:function(){return this.transform.rotation},set:function(t){this.transform.rotation=t}},{key:"worldVisible",get:function(){var t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask&&(this._mask.renderable=!0,this._mask.isMask=!1),this._mask=t,this._mask&&(this._mask.renderable=!1,this._mask.isMask=!0)}},{key:"filters",get:function(){return this._filters&&this._filters.slice()},set:function(t){this._filters=t&&t.slice()}}]),e}(h.default);r.default=b,b.prototype.displayObjectUpdateTransform=b.prototype.updateTransform},{"../const":46,"../math":70,"../settings":101,"./Bounds":47,"./Transform":50,"./TransformStatic":52,eventemitter3:3}],50:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]&&arguments[0];i(this,e);var n=o(this,t.call(this));return n.fillAlpha=1,n.lineWidth=0,n.nativeLines=r,n.lineColor=0,n.lineAlignment=.5,n.graphicsData=[],n.tint=16777215,n._prevTint=16777215,n.blendMode=_.BLEND_MODES.NORMAL,n.currentPath=null,n._webGL={},n.isMask=!1,n.boundsPadding=0,n._localBounds=new x.default,n.dirty=0,n.fastRectDirty=-1,n.clearDirty=0,n.boundsDirty=-1,n.cachedSpriteDirty=!1,n._spriteRect=null,n._fastRect=!1,n}return s(e,t),e.prototype.clone=function(){var t=new e;t.renderable=this.renderable,t.fillAlpha=this.fillAlpha,t.lineWidth=this.lineWidth,t.lineColor=this.lineColor,t.lineAlignment=this.lineAlignment,t.tint=this.tint,t.blendMode=this.blendMode,t.isMask=this.isMask,t.boundsPadding=this.boundsPadding,t.dirty=0,t.cachedSpriteDirty=this.cachedSpriteDirty;for(var r=0;re.CURVES.maxSegments&&(r=e.CURVES.maxSegments),r},e.prototype.lineStyle=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:.5;if(this.lineWidth=t,this.lineColor=e,this.lineAlpha=r,this.lineAlignment=n,this.currentPath)if(this.currentPath.shape.points.length){var i=new y.Polygon(this.currentPath.shape.points.slice(-2));i.closed=!1,this.drawShape(i)}else this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha,this.currentPath.lineAlignment=this.lineAlignment;return this},e.prototype.moveTo=function(t,e){var r=new y.Polygon([t,e]);return r.closed=!1,this.drawShape(r),this},e.prototype.lineTo=function(t,e){return this.currentPath.shape.points.push(t,e),this.dirty++,this},e.prototype.quadraticCurveTo=function(t,r,n,i){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var o=this.currentPath.shape.points,s=0,a=0;0===o.length&&this.moveTo(0,0);for(var u=o[o.length-2],h=o[o.length-1],l=e.CURVES.adaptive?this._segmentsCount(this._quadraticCurveLength(u,h,t,r,n,i)):20,c=1;c<=l;++c){var d=c/l;s=u+(t-u)*d,a=h+(r-h)*d,o.push(s+(t+(n-t)*d-s)*d,a+(r+(i-r)*d-a)*d)}return this.dirty++,this},e.prototype.bezierCurveTo=function(t,r,n,i,o,s){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var a=this.currentPath.shape.points,u=a[a.length-2],h=a[a.length-1];a.length-=2;var l=e.CURVES.adaptive?this._segmentsCount(this._bezierCurveLength(u,h,t,r,n,i,o,s)):20;return(0,w.default)(u,h,t,r,n,i,o,s,l,a),this.dirty++,this},e.prototype.arcTo=function(t,e,r,n,i){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(t,e):this.moveTo(t,e);var o=this.currentPath.shape.points,s=o[o.length-2],a=o[o.length-1],u=a-e,h=s-t,l=n-e,c=r-t,d=Math.abs(u*c-h*l);if(d<1e-8||0===i)o[o.length-2]===t&&o[o.length-1]===e||o.push(t,e);else{var f=u*u+h*h,p=l*l+c*c,v=u*l+h*c,g=i*Math.sqrt(f)/d,y=i*Math.sqrt(p)/d,m=g*v/f,_=y*v/p,b=g*c+y*h,x=g*l+y*u,T=h*(y+m),w=u*(y+m),E=c*(g+_),S=l*(g+_),O=Math.atan2(w-x,T-b),M=Math.atan2(S-x,E-b);this.arc(b+t,x+e,i,O,M,h*l>c*u)}return this.dirty++,this},e.prototype.arc=function(t,r,n,i,o){var s=arguments.length>5&&void 0!==arguments[5]&&arguments[5];if(i===o)return this;!s&&o<=i?o+=_.PI_2:s&&i<=o&&(i+=_.PI_2);var a=o-i,u=e.CURVES.adaptive?this._segmentsCount(Math.abs(a)*n):40*Math.ceil(Math.abs(a)/_.PI_2);if(0===a)return this;var h=t+Math.cos(i)*n,l=r+Math.sin(i)*n,c=this.currentPath?this.currentPath.shape.points:null;c?c[c.length-2]===h&&c[c.length-1]===l||c.push(h,l):(this.moveTo(h,l),c=this.currentPath.shape.points);for(var d=a/(2*u),f=2*d,p=Math.cos(d),v=Math.sin(d),g=u-1,y=g%1/g,m=0;m<=g;++m){var b=m+y*m,x=d+i+f*b,T=Math.cos(x),w=-Math.sin(x);c.push((p*T+v*w)*n+t,(p*-w+v*T)*n+r)}return this.dirty++,this},e.prototype.beginFill=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this.filling=!0,this.fillColor=t,this.fillAlpha=e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},e.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},e.prototype.drawRect=function(t,e,r,n){return this.drawShape(new y.Rectangle(t,e,r,n)),this},e.prototype.drawRoundedRect=function(t,e,r,n,i){return this.drawShape(new y.RoundedRectangle(t,e,r,n,i)),this},e.prototype.drawCircle=function(t,e,r){return this.drawShape(new y.Circle(t,e,r)),this},e.prototype.drawEllipse=function(t,e,r,n){return this.drawShape(new y.Ellipse(t,e,r,n)),this},e.prototype.drawPolygon=function(t){var e=t,r=!0;if(e instanceof y.Polygon&&(r=e.closed,e=e.points),!Array.isArray(e)){e=new Array(arguments.length);for(var n=0;n5&&void 0!==arguments[5]?arguments[5]:0;i=i||n/2;for(var s=-1*Math.PI/2+o,a=2*r,u=_.PI_2/a,h=[],l=0;l0)&&(this.lineWidth=0,this.lineAlignment=.5,this.filling=!1,this.boundsDirty=-1,this.dirty++,this.clearDirty++,this.graphicsData.length=0),this.currentPath=null,this._spriteRect=null,this},e.prototype.isFastRect=function(){return 1===this.graphicsData.length&&this.graphicsData[0].shape.type===_.SHAPES.RECT&&!this.graphicsData[0].lineWidth},e.prototype._renderWebGL=function(t){this.dirty!==this.fastRectDirty&&(this.fastRectDirty=this.dirty,this._fastRect=this.isFastRect()),this._fastRect?this._renderSpriteRect(t):(t.setObjectRenderer(t.plugins.graphics),t.plugins.graphics.render(this))},e.prototype._renderSpriteRect=function(t){var e=this.graphicsData[0].shape;this._spriteRect||(this._spriteRect=new g.default(new d.default(d.default.WHITE)));var r=this._spriteRect;if(16777215===this.tint)r.tint=this.graphicsData[0].fillColor;else{var n=C,i=R;(0,m.hex2rgb)(this.graphicsData[0].fillColor,n),(0,m.hex2rgb)(this.tint,i),n[0]*=i[0],n[1]*=i[1],n[2]*=i[2],r.tint=(0,m.rgb2hex)(n)}r.alpha=this.graphicsData[0].fillAlpha,r.worldAlpha=this.worldAlpha*r.alpha,r.blendMode=this.blendMode,r._texture._frame.width=e.width,r._texture._frame.height=e.height,r.transform.worldTransform=this.transform.worldTransform,r.anchor.set(-e.x/e.width,-e.y/e.height),r._onAnchorUpdate(),r._renderWebGL(t)},e.prototype._renderCanvas=function(t){!0!==this.isMask&&t.plugins.graphics.render(this)},e.prototype._calculateBounds=function(){this.boundsDirty!==this.dirty&&(this.boundsDirty=this.dirty,this.updateLocalBounds(),this.cachedSpriteDirty=!0);var t=this._localBounds;this._bounds.addFrame(this.transform,t.minX,t.minY,t.maxX,t.maxY)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,P);for(var e=this.graphicsData,r=0;re?o+a:e,r=sn?s+u:n;else if(c===_.SHAPES.CIRC)o=i.x,s=i.y,a=i.radius+d/2,u=i.radius+d/2,t=o-ae?o+a:e,r=s-un?s+u:n;else if(c===_.SHAPES.ELIP)o=i.x,s=i.y,a=i.width+d/2,u=i.height+d/2,t=o-ae?o+a:e,r=s-un?s+u:n;else for(var f=i.points,p=0,v=0,g=0,y=0,m=0,b=0,x=0,T=0,w=0;w+2e?x+m:e,r=T-bn?T+b:n)}else t=0,e=0,r=0,n=0;var E=this.boundsPadding;this._localBounds.minX=t-E,this._localBounds.maxX=e+E,this._localBounds.minY=r-E,this._localBounds.maxY=n+E},e.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null;var e=new p.default(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,this.nativeLines,t,this.lineAlignment);return this.graphicsData.push(e),e.type===_.SHAPES.POLY&&(e.shape.closed=e.shape.closed||this.filling,this.currentPath=e),this.dirty++,e},e.prototype.generateCanvasTexture=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=this.getLocalBounds(),n=l.default.create(r.width,r.height,t,e);O||(O=new S.default),this.transform.updateLocalTransform(),this.transform.localTransform.copy(M),M.invert(),M.tx-=r.x,M.ty-=r.y,O.render(this,n,!0,M);var i=d.default.fromCanvas(n.baseTexture._canvasRenderTarget.canvas,t,"graphics");return i.baseTexture.resolution=e,i.baseTexture.update(),i},e.prototype.closePath=function(){var t=this.currentPath;return t&&t.shape&&t.shape.close(),this},e.prototype.addHole=function(){var t=this.graphicsData.pop();return this.currentPath=this.graphicsData[this.graphicsData.length-1],this.currentPath.addHole(t.shape),this.currentPath=null,this},e.prototype.destroy=function(e){t.prototype.destroy.call(this,e);for(var r=0;rP?P:M,r.beginPath(),r.moveTo(w,E+M),r.lineTo(w,E+O-M),r.quadraticCurveTo(w,E+O,w+M,E+O),r.lineTo(w+S-M,E+O),r.quadraticCurveTo(w+S,E+O,w+S,E+O-M),r.lineTo(w+S,E+M),r.quadraticCurveTo(w+S,E,w+S-M,E),r.lineTo(w+M,E),r.quadraticCurveTo(w,E,w,E+M),r.closePath(),(u.fillColor||0===u.fillColor)&&(r.globalAlpha=u.fillAlpha*n,r.fillStyle="#"+("00000"+(0|l).toString(16)).substr(-6),r.fill()),u.lineWidth&&(r.globalAlpha=u.lineAlpha*n,r.strokeStyle="#"+("00000"+(0|c).toString(16)).substr(-6),r.stroke())}}},t.prototype.updateGraphicsTint=function(t){t._prevTint=t.tint;for(var e=(t.tint>>16&255)/255,r=(t.tint>>8&255)/255,n=(255&t.tint)/255,i=0;i>16&255)/255*e*255<<16)+((s>>8&255)/255*r*255<<8)+(255&s)/255*n*255,o._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*r*255<<8)+(255&a)/255*n*255}},t.prototype.renderPolygon=function(t,e,r){r.moveTo(t[0],t[1]);for(var n=1;n9&&void 0!==arguments[9]?arguments[9]:[],l=0,c=0,d=0,f=0,p=0;h.push(t,e);for(var v=1,g=0;v<=u;++v)g=v/u,l=1-g,c=l*l,d=c*l,f=g*g,p=f*g,h.push(d*t+3*c*g*r+3*l*f*i+p*s,d*e+3*c*g*n+3*l*f*o+p*a);return h}r.__esModule=!0,r.default=n},{}],57:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../utils"),u=t("../../const"),h=t("../../renderers/webgl/utils/ObjectRenderer"),l=n(h),c=t("../../renderers/webgl/WebGLRenderer"),d=n(c),f=t("./WebGLGraphicsData"),p=n(f),v=t("./shaders/PrimitiveShader"),g=n(v),y=t("./utils/buildPoly"),m=n(y),_=t("./utils/buildRectangle"),b=n(_),x=t("./utils/buildRoundedRectangle"),T=n(x),w=t("./utils/buildCircle"),E=n(w),S=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.graphicsDataPool=[],n.primitiveShader=null,n.gl=r.gl,n.CONTEXT_UID=0,n}return s(e,t),e.prototype.onContextChange=function(){this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.primitiveShader=new g.default(this.gl)},e.prototype.destroy=function(){l.default.prototype.destroy.call(this);for(var t=0;t32e4)&&(n=this.graphicsDataPool.pop()||new p.default(this.renderer.gl,this.primitiveShader,this.renderer.state.attribsState),n.nativeLines=r,n.reset(e),t.data.push(n)),n.dirty=!0,n},e}(l.default);r.default=S,d.default.registerPlugin("graphics",S)},{"../../const":46,"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../utils":125,"./WebGLGraphicsData":58,"./shaders/PrimitiveShader":59,"./utils/buildCircle":60,"./utils/buildPoly":62,"./utils/buildRectangle":63,"./utils/buildRoundedRectangle":64}],58:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("pixi-gl-core"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=function(){function t(e,r,i){n(this,t),this.gl=e,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=o.default.GLBuffer.createVertexBuffer(e),this.indexBuffer=o.default.GLBuffer.createIndexBuffer(e),this.dirty=!0,this.nativeLines=!1,this.glPoints=null,this.glIndices=null,this.shader=r,this.vao=new o.default.VertexArrayObject(e,i).addIndex(this.indexBuffer).addAttribute(this.buffer,r.attributes.aVertexPosition,e.FLOAT,!1,24,0).addAttribute(this.buffer,r.attributes.aColor,e.FLOAT,!1,24,8)}return t.prototype.reset=function(){this.points.length=0,this.indices.length=0},t.prototype.upload=function(){this.glPoints=new Float32Array(this.points),this.buffer.upload(this.glPoints),this.glIndices=new Uint16Array(this.indices),this.indexBuffer.upload(this.glIndices),this.dirty=!1},t.prototype.destroy=function(){this.color=null,this.points=null,this.indices=null,this.vao.destroy(),this.buffer.destroy(),this.indexBuffer.destroy(),this.gl=null,this.buffer=null,this.indexBuffer=null,this.glPoints=null,this.glIndices=null},t}();r.default=s},{"pixi-gl-core":15}],59:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=t("../../../Shader"),a=function(t){return t&&t.__esModule?t:{default:t}}(s),u=function(t){function e(r){return n(this,e),i(this,t.call(this,r,["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","uniform float alpha;","uniform vec3 tint;","varying vec4 vColor;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"].join("\n"),["varying vec4 vColor;","void main(void){"," gl_FragColor = vColor;","}"].join("\n")))}return o(e,t),e}(a.default);r.default=u},{"../../../Shader":44}],60:[function(t,e,r){"use strict";function n(t,e,r){var n=t.shape,i=n.x,u=n.y,h=void 0,l=void 0;if(t.type===s.SHAPES.CIRC?(h=n.radius,l=n.radius):(h=n.width,l=n.height),0!==h&&0!==l){var c=Math.floor(30*Math.sqrt(n.radius))||Math.floor(15*Math.sqrt(n.width+n.height)),d=2*Math.PI/c;if(t.fill){var f=(0,a.hex2rgb)(t.fillColor),p=t.fillAlpha,v=f[0]*p,g=f[1]*p,y=f[2]*p,m=e.points,_=e.indices,b=m.length/6;_.push(b);for(var x=0;x196*p*p?(R=O-P,A=M-C,I=Math.sqrt(R*R+A*A),R/=I,A/=I,R*=p,A*=p,h.push(T-R*L,w-A*L),h.push(y,m,_,g),h.push(T+R*N,w+A*N),h.push(y,m,_,g),h.push(T-R*N*L,w-A*L),h.push(y,m,_,g),d++):(h.push(T+(H-T)*L,w+(V-w)*L),h.push(y,m,_,g),h.push(T-(H-T)*N,w-(V-w)*N),h.push(y,m,_,g))}}b=r[2*(c-2)],x=r[2*(c-2)+1],T=r[2*(c-1)],w=r[2*(c-1)+1],O=-(x-w),M=b-T,I=Math.sqrt(O*O+M*M),O/=I,M/=I,O*=p,M*=p,h.push(T-O*L,w-M*L),h.push(y,m,_,g),h.push(T+O*N,w+M*N),h.push(y,m,_,g),l.push(f);for(var Y=0;Y=6){for(var i=[],o=t.holes,u=0;u0&&(0, +s.default)(t,e,r)}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils"),u=t("earcut"),h=n(u)},{"../../../utils":125,"./buildLine":61,earcut:2}],63:[function(t,e,r){"use strict";function n(t,e,r){var n=t.shape,i=n.x,a=n.y,u=n.width,h=n.height;if(t.fill){var l=(0,s.hex2rgb)(t.fillColor),c=t.fillAlpha,d=l[0]*c,f=l[1]*c,p=l[2]*c,v=e.points,g=e.indices,y=v.length/6;v.push(i,a),v.push(d,f,p,c),v.push(i+u,a),v.push(d,f,p,c),v.push(i,a+h),v.push(d,f,p,c),v.push(i+u,a+h),v.push(d,f,p,c),g.push(y,y,y+1,y+2,y+3,y+3)}if(t.lineWidth){var m=t.points;t.points=[i,a,i+u,a,i+u,a+h,i,a+h,i,a],(0,o.default)(t,e,r),t.points=m}}r.__esModule=!0,r.default=n;var i=t("./buildLine"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=t("../../../utils")},{"../../../utils":125,"./buildLine":61}],64:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e,r){var n=t.shape,i=n.x,o=n.y,a=n.width,h=n.height,d=n.radius,f=[];if(f.push(i,o+d),s(i,o+h-d,i,o+h,i+d,o+h,f),s(i+a-d,o+h,i+a,o+h,i+a,o+h-d,f),s(i+a,o+d,i+a,o,i+a-d,o,f),s(i+d,o,i,o,i,o+d+1e-10,f),t.fill){for(var p=(0,c.hex2rgb)(t.fillColor),v=t.fillAlpha,g=p[0]*v,y=p[1]*v,m=p[2]*v,_=e.points,b=e.indices,x=_.length/6,T=(0,u.default)(f,null,2),w=0,E=T.length;w6&&void 0!==arguments[6]?arguments[6]:[],u=a,h=0,l=0,c=0,d=0,f=0,p=0,v=0,g=0;v<=20;++v)g=v/20,h=o(t,r,g),l=o(e,n,g),c=o(r,i,g),d=o(n,s,g),f=o(h,c,g),p=o(l,d,g),u.push(f,p);return u}r.__esModule=!0,r.default=i;var a=t("earcut"),u=n(a),h=t("./buildLine"),l=n(h),c=t("../../../utils")},{"../../../utils":125,"./buildLine":61,earcut:2}],65:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.autoDetectRenderer=r.Application=r.Filter=r.SpriteMaskFilter=r.Quad=r.RenderTarget=r.ObjectRenderer=r.WebGLManager=r.Shader=r.CanvasRenderTarget=r.TextureUvs=r.VideoBaseTexture=r.BaseRenderTexture=r.RenderTexture=r.BaseTexture=r.TextureMatrix=r.Texture=r.Spritesheet=r.CanvasGraphicsRenderer=r.GraphicsRenderer=r.GraphicsData=r.Graphics=r.TextMetrics=r.TextStyle=r.Text=r.SpriteRenderer=r.CanvasTinter=r.CanvasSpriteRenderer=r.Sprite=r.TransformBase=r.TransformStatic=r.Transform=r.Container=r.DisplayObject=r.Bounds=r.glCore=r.WebGLRenderer=r.CanvasRenderer=r.ticker=r.utils=r.settings=void 0;var o=t("./const");Object.keys(o).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return o[t]}})});var s=t("./math");Object.keys(s).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return s[t]}})});var a=t("pixi-gl-core");Object.defineProperty(r,"glCore",{enumerable:!0,get:function(){return i(a).default}});var u=t("./display/Bounds");Object.defineProperty(r,"Bounds",{enumerable:!0,get:function(){return i(u).default}});var h=t("./display/DisplayObject");Object.defineProperty(r,"DisplayObject",{enumerable:!0,get:function(){return i(h).default}});var l=t("./display/Container");Object.defineProperty(r,"Container",{enumerable:!0,get:function(){return i(l).default}});var c=t("./display/Transform");Object.defineProperty(r,"Transform",{enumerable:!0,get:function(){return i(c).default}});var d=t("./display/TransformStatic");Object.defineProperty(r,"TransformStatic",{enumerable:!0,get:function(){return i(d).default}});var f=t("./display/TransformBase");Object.defineProperty(r,"TransformBase",{enumerable:!0,get:function(){return i(f).default}});var p=t("./sprites/Sprite");Object.defineProperty(r,"Sprite",{enumerable:!0,get:function(){return i(p).default}});var v=t("./sprites/canvas/CanvasSpriteRenderer");Object.defineProperty(r,"CanvasSpriteRenderer",{enumerable:!0,get:function(){return i(v).default}});var g=t("./sprites/canvas/CanvasTinter");Object.defineProperty(r,"CanvasTinter",{enumerable:!0,get:function(){return i(g).default}});var y=t("./sprites/webgl/SpriteRenderer");Object.defineProperty(r,"SpriteRenderer",{enumerable:!0,get:function(){return i(y).default}});var m=t("./text/Text");Object.defineProperty(r,"Text",{enumerable:!0,get:function(){return i(m).default}});var _=t("./text/TextStyle");Object.defineProperty(r,"TextStyle",{enumerable:!0,get:function(){return i(_).default}});var b=t("./text/TextMetrics");Object.defineProperty(r,"TextMetrics",{enumerable:!0,get:function(){return i(b).default}});var x=t("./graphics/Graphics");Object.defineProperty(r,"Graphics",{enumerable:!0,get:function(){return i(x).default}});var T=t("./graphics/GraphicsData");Object.defineProperty(r,"GraphicsData",{enumerable:!0,get:function(){return i(T).default}});var w=t("./graphics/webgl/GraphicsRenderer");Object.defineProperty(r,"GraphicsRenderer",{enumerable:!0,get:function(){return i(w).default}});var E=t("./graphics/canvas/CanvasGraphicsRenderer");Object.defineProperty(r,"CanvasGraphicsRenderer",{enumerable:!0,get:function(){return i(E).default}});var S=t("./textures/Spritesheet");Object.defineProperty(r,"Spritesheet",{enumerable:!0,get:function(){return i(S).default}});var O=t("./textures/Texture");Object.defineProperty(r,"Texture",{enumerable:!0,get:function(){return i(O).default}});var M=t("./textures/TextureMatrix");Object.defineProperty(r,"TextureMatrix",{enumerable:!0,get:function(){return i(M).default}});var P=t("./textures/BaseTexture");Object.defineProperty(r,"BaseTexture",{enumerable:!0,get:function(){return i(P).default}});var C=t("./textures/RenderTexture");Object.defineProperty(r,"RenderTexture",{enumerable:!0,get:function(){return i(C).default}});var R=t("./textures/BaseRenderTexture");Object.defineProperty(r,"BaseRenderTexture",{enumerable:!0,get:function(){return i(R).default}});var A=t("./textures/VideoBaseTexture");Object.defineProperty(r,"VideoBaseTexture",{enumerable:!0,get:function(){return i(A).default}});var I=t("./textures/TextureUvs");Object.defineProperty(r,"TextureUvs",{enumerable:!0,get:function(){return i(I).default}});var D=t("./renderers/canvas/utils/CanvasRenderTarget");Object.defineProperty(r,"CanvasRenderTarget",{enumerable:!0,get:function(){return i(D).default}});var L=t("./Shader");Object.defineProperty(r,"Shader",{enumerable:!0,get:function(){return i(L).default}});var N=t("./renderers/webgl/managers/WebGLManager");Object.defineProperty(r,"WebGLManager",{enumerable:!0,get:function(){return i(N).default}});var B=t("./renderers/webgl/utils/ObjectRenderer");Object.defineProperty(r,"ObjectRenderer",{enumerable:!0,get:function(){return i(B).default}});var F=t("./renderers/webgl/utils/RenderTarget");Object.defineProperty(r,"RenderTarget",{enumerable:!0,get:function(){return i(F).default}});var k=t("./renderers/webgl/utils/Quad");Object.defineProperty(r,"Quad",{enumerable:!0,get:function(){return i(k).default}});var j=t("./renderers/webgl/filters/spriteMask/SpriteMaskFilter");Object.defineProperty(r,"SpriteMaskFilter",{enumerable:!0,get:function(){return i(j).default}});var U=t("./renderers/webgl/filters/Filter");Object.defineProperty(r,"Filter",{enumerable:!0,get:function(){return i(U).default}});var X=t("./Application");Object.defineProperty(r,"Application",{enumerable:!0,get:function(){return i(X).default}});var G=t("./autoDetectRenderer");Object.defineProperty(r,"autoDetectRenderer",{enumerable:!0,get:function(){return G.autoDetectRenderer}});var W=t("./utils"),H=n(W),V=t("./ticker"),Y=n(V),z=t("./settings"),q=i(z),K=t("./renderers/canvas/CanvasRenderer"),Z=i(K),J=t("./renderers/webgl/WebGLRenderer"),Q=i(J);r.settings=q.default,r.utils=H,r.ticker=Y,r.CanvasRenderer=Z.default,r.WebGLRenderer=Q.default},{"./Application":43,"./Shader":44,"./autoDetectRenderer":45,"./const":46,"./display/Bounds":47,"./display/Container":48,"./display/DisplayObject":49,"./display/Transform":50,"./display/TransformBase":51,"./display/TransformStatic":52,"./graphics/Graphics":53,"./graphics/GraphicsData":54,"./graphics/canvas/CanvasGraphicsRenderer":55,"./graphics/webgl/GraphicsRenderer":57,"./math":70,"./renderers/canvas/CanvasRenderer":77,"./renderers/canvas/utils/CanvasRenderTarget":79,"./renderers/webgl/WebGLRenderer":84,"./renderers/webgl/filters/Filter":86,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":89,"./renderers/webgl/managers/WebGLManager":93,"./renderers/webgl/utils/ObjectRenderer":94,"./renderers/webgl/utils/Quad":95,"./renderers/webgl/utils/RenderTarget":96,"./settings":101,"./sprites/Sprite":102,"./sprites/canvas/CanvasSpriteRenderer":103,"./sprites/canvas/CanvasTinter":104,"./sprites/webgl/SpriteRenderer":106,"./text/Text":108,"./text/TextMetrics":109,"./text/TextStyle":110,"./textures/BaseRenderTexture":111,"./textures/BaseTexture":112,"./textures/RenderTexture":113,"./textures/Spritesheet":114,"./textures/Texture":115,"./textures/TextureMatrix":116,"./textures/TextureUvs":117,"./textures/VideoBaseTexture":118,"./ticker":121,"./utils":125,"pixi-gl-core":15}],66:[function(t,e,r){"use strict";function n(t){return t<0?-1:t>0?1:0}r.__esModule=!0;var i=t("./Matrix"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],a=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],u=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],h=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],l=[],c=[];!function(){for(var t=0;t<16;t++){var e=[];c.push(e);for(var r=0;r<16;r++)for(var i=n(s[t]*s[r]+u[t]*a[r]),d=n(a[t]*s[r]+h[t]*a[r]),f=n(s[t]*u[r]+u[t]*h[r]),p=n(a[t]*u[r]+h[t]*h[r]),v=0;v<16;v++)if(s[v]===i&&a[v]===d&&u[v]===f&&h[v]===p){e.push(v);break}}for(var g=0;g<16;g++){var y=new o.default;y.set(s[g],a[g],u[g],h[g],0,0),l.push(y)}}();var d={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MIRROR_HORIZONTAL:12,uX:function(t){return s[t]},uY:function(t){return a[t]},vX:function(t){return u[t]},vY:function(t){return h[t]},inv:function(t){return 8&t?15&t:7&-t},add:function(t,e){return c[t][e]},sub:function(t,e){return c[t][d.inv(e)]},rotate180:function(t){return 4^t},isVertical:function(t){return 2==(3&t)},byDirection:function(t,e){return 2*Math.abs(t)<=Math.abs(e)?e>=0?d.S:d.N:2*Math.abs(e)<=Math.abs(t)?t>0?d.E:d.W:e>0?t>0?d.SE:d.SW:t>0?d.NE:d.NW},matrixAppendRotationInv:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=l[d.inv(e)];i.tx=r,i.ty=n,t.append(i)}};r.default=d},{"./Matrix":67}],67:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:1,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;n(this,t),this.a=e,this.b=r,this.c=i,this.d=o,this.tx=s,this.ty=a,this.array=null}return t.prototype.fromArray=function(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]},t.prototype.set=function(t,e,r,n,i,o){return this.a=t,this.b=e,this.c=r,this.d=n,this.tx=i,this.ty=o,this},t.prototype.toArray=function(t,e){this.array||(this.array=new Float32Array(9));var r=e||this.array;return t?(r[0]=this.a,r[1]=this.b,r[2]=0,r[3]=this.c,r[4]=this.d,r[5]=0,r[6]=this.tx,r[7]=this.ty,r[8]=1):(r[0]=this.a,r[1]=this.c,r[2]=this.tx,r[3]=this.b,r[4]=this.d,r[5]=this.ty,r[6]=0,r[7]=0,r[8]=1),r},t.prototype.apply=function(t,e){e=e||new s.default;var r=t.x,n=t.y;return e.x=this.a*r+this.c*n+this.tx,e.y=this.b*r+this.d*n+this.ty,e},t.prototype.applyInverse=function(t,e){e=e||new s.default;var r=1/(this.a*this.d+this.c*-this.b),n=t.x,i=t.y;return e.x=this.d*r*n+-this.c*r*i+(this.ty*this.c-this.tx*this.d)*r,e.y=this.a*r*i+-this.b*r*n+(-this.ty*this.a+this.tx*this.b)*r,e},t.prototype.translate=function(t,e){return this.tx+=t,this.ty+=e,this},t.prototype.scale=function(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this},t.prototype.rotate=function(t){var e=Math.cos(t),r=Math.sin(t),n=this.a,i=this.c,o=this.tx;return this.a=n*e-this.b*r,this.b=n*r+this.b*e,this.c=i*e-this.d*r,this.d=i*r+this.d*e,this.tx=o*e-this.ty*r,this.ty=o*r+this.ty*e,this},t.prototype.append=function(t){var e=this.a,r=this.b,n=this.c,i=this.d;return this.a=t.a*e+t.b*n,this.b=t.a*r+t.b*i,this.c=t.c*e+t.d*n,this.d=t.c*r+t.d*i,this.tx=t.tx*e+t.ty*n+this.tx,this.ty=t.tx*r+t.ty*i+this.ty,this},t.prototype.setTransform=function(t,e,r,n,i,o,s,a,u){return this.a=Math.cos(s+u)*i,this.b=Math.sin(s+u)*i,this.c=-Math.sin(s-a)*o,this.d=Math.cos(s-a)*o,this.tx=t-(r*this.a+n*this.c),this.ty=e-(r*this.b+n*this.d),this},t.prototype.prepend=function(t){var e=this.tx;if(1!==t.a||0!==t.b||0!==t.c||1!==t.d){var r=this.a,n=this.c;this.a=r*t.a+this.b*t.c,this.b=r*t.b+this.b*t.d,this.c=n*t.a+this.d*t.c,this.d=n*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this},t.prototype.decompose=function(t){var e=this.a,r=this.b,n=this.c,i=this.d,o=-Math.atan2(-n,i),s=Math.atan2(r,e),u=Math.abs(o+s);return u<1e-5||Math.abs(a.PI_2-u)<1e-5?(t.rotation=s,e<0&&i>=0&&(t.rotation+=t.rotation<=0?Math.PI:-Math.PI),t.skew.x=t.skew.y=0):(t.rotation=0,t.skew.x=o,t.skew.y=s),t.scale.x=Math.sqrt(e*e+r*r),t.scale.y=Math.sqrt(n*n+i*i),t.position.x=this.tx,t.position.y=this.ty,t},t.prototype.invert=function(){var t=this.a,e=this.b,r=this.c,n=this.d,i=this.tx,o=t*n-e*r;return this.a=n/o,this.b=-e/o,this.c=-r/o,this.d=t/o,this.tx=(r*this.ty-n*i)/o,this.ty=-(t*this.ty-e*i)/o,this},t.prototype.identity=function(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this},t.prototype.clone=function(){var e=new t;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e},t.prototype.copy=function(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t},i(t,null,[{key:"IDENTITY",get:function(){return new t}},{key:"TEMP_MATRIX",get:function(){return new t}}]),t}();r.default=u},{"../const":46,"./Point":69}],68:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this._x=i,this._y=o,this.cb=e,this.scope=r}return t.prototype.set=function(t,e){var r=t||0,n=e||(0!==e?r:0);this._x===r&&this._y===n||(this._x=r,this._y=n,this.cb.call(this.scope))},t.prototype.copy=function(t){this._x===t.x&&this._y===t.y||(this._x=t.x,this._y=t.y,this.cb.call(this.scope))},i(t,[{key:"x",get:function(){return this._x},set:function(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}},{key:"y",get:function(){return this._y},set:function(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}]),t}();r.default=o},{}],69:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;n(this,t),this.x=e,this.y=r}return t.prototype.clone=function(){return new t(this.x,this.y)},t.prototype.copy=function(t){this.set(t.x,t.y)},t.prototype.equals=function(t){return t.x===this.x&&t.y===this.y},t.prototype.set=function(t,e){this.x=t||0,this.y=e||(0!==e?this.x:0)},t}();r.default=i},{}],70:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./Point");Object.defineProperty(r,"Point",{enumerable:!0,get:function(){return n(i).default}});var o=t("./ObservablePoint");Object.defineProperty(r,"ObservablePoint",{enumerable:!0,get:function(){return n(o).default}});var s=t("./Matrix");Object.defineProperty(r,"Matrix",{enumerable:!0,get:function(){return n(s).default}});var a=t("./GroupD8");Object.defineProperty(r,"GroupD8",{enumerable:!0,get:function(){return n(a).default}});var u=t("./shapes/Circle");Object.defineProperty(r,"Circle",{enumerable:!0,get:function(){return n(u).default}});var h=t("./shapes/Ellipse");Object.defineProperty(r,"Ellipse",{enumerable:!0,get:function(){return n(h).default}});var l=t("./shapes/Polygon");Object.defineProperty(r,"Polygon",{enumerable:!0,get:function(){return n(l).default}});var c=t("./shapes/Rectangle");Object.defineProperty(r,"Rectangle",{enumerable:!0,get:function(){return n(c).default}});var d=t("./shapes/RoundedRectangle");Object.defineProperty(r,"RoundedRectangle",{enumerable:!0,get:function(){return n(d).default}})},{"./GroupD8":66,"./Matrix":67,"./ObservablePoint":68,"./Point":69,"./shapes/Circle":71,"./shapes/Ellipse":72,"./shapes/Polygon":73,"./shapes/Rectangle":74,"./shapes/RoundedRectangle":75}],71:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("./Rectangle"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=t("../../const"),a=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;n(this,t),this.x=e,this.y=r,this.radius=i,this.type=s.SHAPES.CIRC}return t.prototype.clone=function(){return new t(this.x,this.y,this.radius)},t.prototype.contains=function(t,e){if(this.radius<=0)return!1;var r=this.radius*this.radius,n=this.x-t,i=this.y-e;return n*=n,i*=i,n+i<=r},t.prototype.getBounds=function(){return new o.default(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)},t}();r.default=a},{"../../const":46,"./Rectangle":74}],72:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("./Rectangle"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=t("../../const"),a=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this.x=e,this.y=r,this.width=i,this.height=o,this.type=s.SHAPES.ELIP}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;var r=(t-this.x)/this.width,n=(e-this.y)/this.height;return r*=r,n*=n,r+n<=1},t.prototype.getBounds=function(){return new o.default(this.x-this.width,this.y-this.height,this.width,this.height)},t}();r.default=a},{"../../const":46,"./Rectangle":74}],73:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../Point"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=t("../../const"),a=function(){function t(){for(var e=arguments.length,r=Array(e),i=0;ie!=h>e&&t<(e-a)/(h-a)*(u-s)+s&&(r=!r)}return r},t}();r.default=a},{"../../const":46,"../Point":69}],74:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this.x=Number(e),this.y=Number(r),this.width=Number(i),this.height=Number(s),this.type=o.SHAPES.RECT}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this},t.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t=this.y&&et.x+t.width&&(this.width=t.width-this.x,this.width<0&&(this.width=0)),this.y+this.height>t.y+t.height&&(this.height=t.height-this.y,this.height<0&&(this.height=0))},t.prototype.enlarge=function(t){var e=Math.min(this.x,t.x),r=Math.max(this.x+this.width,t.x+t.width),n=Math.min(this.y,t.y),i=Math.max(this.y+this.height,t.y+t.height);this.x=e,this.width=r-e,this.y=n,this.height=i-n},i(t,[{key:"left",get:function(){return this.x}},{key:"right",get:function(){return this.x+this.width}},{key:"top",get:function(){return this.y}},{key:"bottom",get:function(){return this.y+this.height}}],[{key:"EMPTY",get:function(){return new t(0,0,0,0)}}]),t}();r.default=s},{"../../const":46}],75:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:20;n(this,t),this.x=e,this.y=r,this.width=o,this.height=s,this.radius=a,this.type=i.SHAPES.RREC}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height,this.radius)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){if(e>=this.y+this.radius&&e<=this.y+this.height-this.radius||t>=this.x+this.radius&&t<=this.x+this.width-this.radius)return!0;var r=t-(this.x+this.radius),n=e-(this.y+this.radius),i=this.radius*this.radius;if(r*r+n*n<=i)return!0;if((r=t-(this.x+this.width-this.radius))*r+n*n<=i)return!0;if(n=e-(this.y+this.height-this.radius),r*r+n*n<=i)return!0;if((r=t-(this.x+this.radius))*r+n*n<=i)return!0}return!1},t}();r.default=o},{"../../const":46}],76:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rE?E:w,e.moveTo(_,b+w),e.lineTo(_,b+T-w),e.quadraticCurveTo(_,b+T,_+w,b+T),e.lineTo(_+x-w,b+T),e.quadraticCurveTo(_+x,b+T,_+x,b+T-w),e.lineTo(_+x,b+w),e.quadraticCurveTo(_+x,b,_+x-w,b),e.lineTo(_+w,b),e.quadraticCurveTo(_,b,_,b+w),e.closePath()}}}},t.prototype.popMask=function(t){t.context.restore(),t.invalidateBlendMode()},t.prototype.destroy=function(){},t}();r.default=o},{"../../../const":46}],79:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:[];return(0,s.default)()?(t[i.BLEND_MODES.NORMAL]="source-over",t[i.BLEND_MODES.ADD]="lighter",t[i.BLEND_MODES.MULTIPLY]="multiply",t[i.BLEND_MODES.SCREEN]="screen",t[i.BLEND_MODES.OVERLAY]="overlay",t[i.BLEND_MODES.DARKEN]="darken",t[i.BLEND_MODES.LIGHTEN]="lighten",t[i.BLEND_MODES.COLOR_DODGE]="color-dodge",t[i.BLEND_MODES.COLOR_BURN]="color-burn",t[i.BLEND_MODES.HARD_LIGHT]="hard-light",t[i.BLEND_MODES.SOFT_LIGHT]="soft-light",t[i.BLEND_MODES.DIFFERENCE]="difference",t[i.BLEND_MODES.EXCLUSION]="exclusion",t[i.BLEND_MODES.HUE]="hue",t[i.BLEND_MODES.SATURATION]="saturate",t[i.BLEND_MODES.COLOR]="color",t[i.BLEND_MODES.LUMINOSITY]="luminosity"):(t[i.BLEND_MODES.NORMAL]="source-over",t[i.BLEND_MODES.ADD]="lighter",t[i.BLEND_MODES.MULTIPLY]="source-over",t[i.BLEND_MODES.SCREEN]="source-over",t[i.BLEND_MODES.OVERLAY]="source-over",t[i.BLEND_MODES.DARKEN]="source-over",t[i.BLEND_MODES.LIGHTEN]="source-over",t[i.BLEND_MODES.COLOR_DODGE]="source-over",t[i.BLEND_MODES.COLOR_BURN]="source-over",t[i.BLEND_MODES.HARD_LIGHT]="source-over",t[i.BLEND_MODES.SOFT_LIGHT]="source-over",t[i.BLEND_MODES.DIFFERENCE]="source-over",t[i.BLEND_MODES.EXCLUSION]="source-over",t[i.BLEND_MODES.HUE]="source-over",t[i.BLEND_MODES.SATURATION]="source-over",t[i.BLEND_MODES.COLOR]="source-over",t[i.BLEND_MODES.LUMINOSITY]="source-over"),t[i.BLEND_MODES.NORMAL_NPM]=t[i.BLEND_MODES.NORMAL],t[i.BLEND_MODES.ADD_NPM]=t[i.BLEND_MODES.ADD],t[i.BLEND_MODES.SCREEN_NPM]=t[i.BLEND_MODES.SCREEN],t}r.__esModule=!0,r.default=n;var i=t("../../../const"),o=t("./canUseNewCanvasBlendModes"),s=function(t){return t&&t.__esModule?t:{default:t}}(o)},{"../../../const":46,"./canUseNewCanvasBlendModes":80}],82:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=t("../../settings"),s=function(t){return t&&t.__esModule?t:{default:t}}(o),a=function(){function t(e){n(this,t),this.renderer=e,this.count=0,this.checkCount=0,this.maxIdle=s.default.GC_MAX_IDLE,this.checkCountMax=s.default.GC_MAX_CHECK_COUNT,this.mode=s.default.GC_MODE}return t.prototype.update=function(){this.count++,this.mode!==i.GC_MODES.MANUAL&&++this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run())},t.prototype.run=function(){for(var t=this.renderer.textureManager,e=t._managedTextures,r=!1,n=0;nthis.maxIdle&&(t.destroyTexture(i,!0),e[n]=null,r=!0)}if(r){for(var o=0,s=0;s=0;r--)this.unload(t.children[r])},t}();r.default=a},{"../../const":46,"../../settings":101}],83:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("pixi-gl-core"),o=t("../../const"),s=t("./utils/RenderTarget"),a=function(t){return t&&t.__esModule?t:{default:t}}(s),u=t("../../utils"),h=function(){function t(e){n(this,t),this.renderer=e,this.gl=e.gl,this._managedTextures=[]}return t.prototype.bindTexture=function(){},t.prototype.getTexture=function(){},t.prototype.updateTexture=function(t,e){var r=this.gl,n=!!t._glRenderTargets;if(!t.hasLoaded)return null;var s=this.renderer.boundTextures;if(void 0===e){e=0;for(var u=0;u 0.5)"," {"," color = vec4(1.0, 0.0, 0.0, 1.0);"," }"," else"," {"," color = vec4(0.0, 1.0, 0.0, 1.0);"," }"," gl_FragColor = mix(sample, masky, 0.5);"," gl_FragColor *= sample.a;","}"].join("\n")}}]),t}();r.default=f},{"../../../const":46,"../../../settings":101,"../../../utils":125,"./extractUniformsFromSrc":87}],87:[function(t,e,r){"use strict";function n(t,e,r){var n=i(t),o=i(e);return Object.assign(n,o)}function i(t){for(var e=new RegExp("^(projectionMatrix|uSampler|filterArea|filterClamp)$"),r={},n=void 0,i=t.replace(/\s+/g," ").split(/\s*;\s*/),o=0;o-1){var u=s.split(" "),h=u[1],l=u[2],c=1;l.indexOf("[")>-1&&(n=l.split(/\[|]/),l=n[0],c*=Number(n[1])),l.match(e)||(r[l]={value:a(h,c),name:l,type:h})}}return r}r.__esModule=!0,r.default=n;var o=t("pixi-gl-core"),s=function(t){return t&&t.__esModule?t:{default:t}}(o),a=s.default.shader.defaultValue},{"pixi-gl-core":15}],88:[function(t,e,r){"use strict";function n(t,e,r){var n=t.identity();return n.translate(e.x/r.width,e.y/r.height),n.scale(r.width,r.height),n}function i(t,e,r){var n=t.identity();n.translate(e.x/r.width,e.y/r.height);var i=r.width/e.width,o=r.height/e.height;return n.scale(i,o),n}function o(t,e,r,n){var i=n._texture.orig,o=t.set(r.width,0,0,r.height,e.x,e.y),a=n.worldTransform.copy(s.Matrix.TEMP_MATRIX);return a.invert(),o.prepend(a),o.scale(1/i.width,1/i.height),o.translate(n.anchor.x,n.anchor.y),o}r.__esModule=!0,r.calculateScreenSpaceMatrix=n,r.calculateNormalizedScreenSpaceMatrix=i,r.calculateSpriteMatrix=o;var s=t("../../../math")},{"../../../math":70}],89:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../Filter"),u=n(a),h=t("../../../../math"),l=(t("path"),t("../../../../textures/TextureMatrix")),c=n(l),d=function(t){function e(r){i(this,e);var n=new h.Matrix,s=o(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n","varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n"));return r.renderable=!1,s.maskSprite=r,s.maskMatrix=n,s}return s(e,t),e.prototype.apply=function(t,e,r){var n=this.maskSprite,i=this.maskSprite.texture;i.valid&&(i.transform||(i.transform=new c.default(i,0)),i.transform.update(),this.uniforms.mask=i,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,n).prepend(i.transform.mapCoord),this.uniforms.alpha=n.worldAlpha,this.uniforms.maskClamp=i.transform.uClampFrame,t.applyFilter(this,e,r))},e}(u.default);r.default=d},{"../../../../math":70,"../../../../textures/TextureMatrix":116,"../Filter":86,path:8}],90:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var a=t("./WebGLManager"),u=n(a),h=t("../utils/RenderTarget"),l=n(h),c=t("../utils/Quad"),d=n(c),f=t("../../../math"),p=t("../../../Shader"),v=n(p),g=t("../filters/filterTransforms"),y=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(g),m=t("bit-twiddle"),_=n(m),b=function(){function t(){s(this,t),this.renderTarget=null,this.target=null,this.resolution=1,this.sourceFrame=new f.Rectangle,this.destinationFrame=new f.Rectangle,this.filters=[]}return t.prototype.clear=function(){this.filters=null,this.target=null,this.renderTarget=null},t}(),x=function(t){function e(r){s(this,e);var n=i(this,t.call(this,r));return n.gl=n.renderer.gl,n.quad=new d.default(n.gl,r.state.attribState),n.shaderCache={},n.pool={},n.filterData=null,n.managedFilters=[],n.renderer.on("prerender",n.onPrerender,n),n._screenWidth=r.view.width,n._screenHeight=r.view.height,n}return o(e,t),e.prototype.pushFilter=function(t,e){var r=this.renderer,n=this.filterData;if(!n){n=this.renderer._activeRenderTarget.filterStack;var i=new b;i.sourceFrame=i.destinationFrame=this.renderer._activeRenderTarget.size,i.renderTarget=r._activeRenderTarget,this.renderer._activeRenderTarget.filterData=n={index:0,stack:[i]},this.filterData=n}var o=n.stack[++n.index],s=n.stack[0].destinationFrame;o||(o=n.stack[n.index]=new b);var a=t.filterArea&&0===t.filterArea.x&&0===t.filterArea.y&&t.filterArea.width===r.screen.width&&t.filterArea.height===r.screen.height,u=e[0].resolution,h=0|e[0].padding,l=a?r.screen:t.filterArea||t.getBounds(!0),c=o.sourceFrame,d=o.destinationFrame;c.x=(l.x*u|0)/u,c.y=(l.y*u|0)/u,c.width=(l.width*u|0)/u,c.height=(l.height*u|0)/u,a||(n.stack[0].renderTarget.transform||e[0].autoFit&&c.fit(s),c.pad(h)),d.width=c.width,d.height=c.height;var f=this.getPotRenderTarget(r.gl,c.width,c.height,u);o.target=t,o.filters=e,o.resolution=u,o.renderTarget=f,f.setFrame(d,c),r.bindRenderTarget(f),f.clear()},e.prototype.popFilter=function(){var t=this.filterData,e=t.stack[t.index-1],r=t.stack[t.index];this.quad.map(r.renderTarget.size,r.sourceFrame).upload();var n=r.filters;if(1===n.length)n[0].apply(this,r.renderTarget,e.renderTarget,!1,r),this.freePotRenderTarget(r.renderTarget);else{var i=r.renderTarget,o=this.getPotRenderTarget(this.renderer.gl,r.sourceFrame.width,r.sourceFrame.height,r.resolution);o.setFrame(r.destinationFrame,r.sourceFrame),o.clear();var s=0;for(s=0;s0&&void 0!==arguments[0]&&arguments[0],e=this.renderer,r=this.managedFilters;e.off("prerender",this.onPrerender,this);for(var n=0;n0&&(e+="\nelse "),r1&&void 0!==arguments[1]?arguments[1]:[];return e[i.BLEND_MODES.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.ADD]=[t.ONE,t.DST_ALPHA],e[i.BLEND_MODES.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SCREEN]=[t.ONE,t.ONE_MINUS_SRC_COLOR],e[i.BLEND_MODES.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.NORMAL_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.ADD_NPM]=[t.SRC_ALPHA,t.DST_ALPHA,t.ONE,t.DST_ALPHA],e[i.BLEND_MODES.SCREEN_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_COLOR,t.ONE,t.ONE_MINUS_SRC_COLOR],e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":46}],99:[function(t,e,r){"use strict";function n(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e[i.DRAW_MODES.POINTS]=t.POINTS,e[i.DRAW_MODES.LINES]=t.LINES,e[i.DRAW_MODES.LINE_LOOP]=t.LINE_LOOP,e[i.DRAW_MODES.LINE_STRIP]=t.LINE_STRIP,e[i.DRAW_MODES.TRIANGLES]=t.TRIANGLES,e[i.DRAW_MODES.TRIANGLE_STRIP]=t.TRIANGLE_STRIP,e[i.DRAW_MODES.TRIANGLE_FAN]=t.TRIANGLE_FAN,e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":46}],100:[function(t,e,r){"use strict";function n(t){t.getContextAttributes().stencil||console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly")}r.__esModule=!0,r.default=n},{}],101:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./utils/maxRecommendedTextures"),o=n(i),s=t("./utils/canUploadSameBuffer"),a=n(s);r.default={TARGET_FPMS:.06,MIPMAP_TEXTURES:!0,RESOLUTION:1,FILTER_RESOLUTION:1,SPRITE_MAX_TEXTURES:(0,o.default)(32),SPRITE_BATCH_SIZE:4096,RETINA_PREFIX:/@([0-9\.]+)x/,RENDER_OPTIONS:{view:null,antialias:!1,forceFXAA:!1,autoResize:!1,transparent:!1,backgroundColor:0,clearBeforeRender:!0,preserveDrawingBuffer:!1,roundPixels:!1,width:800,height:600,legacy:!1},TRANSFORM_MODE:0,GC_MODE:0,GC_MAX_IDLE:3600,GC_MAX_CHECK_COUNT:600,WRAP_MODE:0,SCALE_MODE:0,PRECISION_VERTEX:"highp",PRECISION_FRAGMENT:"mediump",CAN_UPLOAD_SAME_BUFFER:(0,a.default)(),MESH_CANVAS_PADDING:0}},{"./utils/canUploadSameBuffer":122,"./utils/maxRecommendedTextures":127}],102:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r=n&&v.x=i&&v.y>16)+(65280&t)+((255&t)<<16)}},{key:"texture",get:function(){return this._texture},set:function(t){this._texture!==t&&(this._texture=t,this.cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,t&&(t.baseTexture.hasLoaded?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}]),e}(p.default);r.default=g},{"../const":46,"../display/Container":48,"../math":70,"../textures/Texture":115,"../utils":125}],103:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../renderers/canvas/CanvasRenderer"),s=n(o),a=t("../../const"),u=t("../../math"),h=t("./CanvasTinter"),l=n(h),c=new u.Matrix,d=function(){function t(e){i(this,t),this.renderer=e}return t.prototype.render=function(t){var e=t._texture,r=this.renderer,n=e._frame.width,i=e._frame.height,o=t.transform.worldTransform,s=0,h=0;if(!(e.orig.width<=0||e.orig.height<=0)&&e.baseTexture.source&&(r.setBlendMode(t.blendMode),e.valid)){r.context.globalAlpha=t.worldAlpha;var d=e.baseTexture.scaleMode===a.SCALE_MODES.LINEAR;r.smoothProperty&&r.context[r.smoothProperty]!==d&&(r.context[r.smoothProperty]=d),e.trim?(s=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,h=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(s=(.5-t.anchor.x)*e.orig.width,h=(.5-t.anchor.y)*e.orig.height),e.rotate&&(o.copy(c),o=c,u.GroupD8.matrixAppendRotationInv(o,e.rotate,s,h),s=0,h=0),s-=n/2,h-=i/2,r.roundPixels?(r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution|0,o.ty*r.resolution|0),s|=0,h|=0):r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution,o.ty*r.resolution);var f=e.baseTexture.resolution;16777215!==t.tint?(t.cachedTint===t.tint&&t.tintedTexture.tintId===t._texture._updateID||(t.cachedTint=t.tint,t.tintedTexture=l.default.getTintedTexture(t,t.tint)),r.context.drawImage(t.tintedTexture,0,0,n*f,i*f,s*r.resolution,h*r.resolution,n*r.resolution,i*r.resolution)):r.context.drawImage(e.baseTexture.source,e._frame.x*f,e._frame.y*f,n*f,i*f,s*r.resolution,h*r.resolution,n*r.resolution,i*r.resolution)}},t.prototype.destroy=function(){this.renderer=null},t}();r.default=d,s.default.registerPlugin("sprite",d)},{"../../const":46,"../../math":70,"../../renderers/canvas/CanvasRenderer":77,"./CanvasTinter":104}],104:[function(t,e,r){"use strict";r.__esModule=!0;var n=t("../../utils"),i=t("../../renderers/canvas/utils/canUseNewCanvasBlendModes"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s={getTintedTexture:function(t,e){var r=t._texture;e=s.roundColor(e);var n="#"+("00000"+(0|e).toString(16)).substr(-6);r.tintCache=r.tintCache||{};var i=r.tintCache[n],o=void 0;if(i){if(i.tintId===r._updateID)return r.tintCache[n];o=r.tintCache[n]}else o=s.canvas||document.createElement("canvas");if(s.tintMethod(r,e,o),o.tintId=r._updateID,s.convertTintToImage){var a=new Image;a.src=o.toDataURL(),r.tintCache[n]=a}else r.tintCache[n]=o,s.canvas=null;return o},tintWithMultiply:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.save(),n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="multiply",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.restore()},tintWithOverlay:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.save(),n.globalCompositeOperation="copy",n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.restore()},tintWithPerPixel:function(t,e,r){var i=r.getContext("2d"),o=t._frame.clone(),s=t.baseTexture.resolution;o.x*=s,o.y*=s,o.width*=s,o.height*=s,r.width=Math.ceil(o.width),r.height=Math.ceil(o.height),i.save(),i.globalCompositeOperation="copy",i.drawImage(t.baseTexture.source,o.x,o.y,o.width,o.height,0,0,o.width,o.height),i.restore();for(var a=(0,n.hex2rgb)(e),u=a[0],h=a[1],l=a[2],c=i.getImageData(0,0,o.width,o.height),d=c.data,f=0;f=this.size&&this.flush(),t._texture._uvs&&(this.sprites[this.currentIndex++]=t)},e.prototype.flush=function(){if(0!==this.currentIndex){var t=this.renderer.gl,e=this.MAX_TEXTURES,r=S.default.nextPow2(this.currentIndex),n=S.default.log2(r),i=this.buffers[n],o=this.sprites,s=this.groups,a=i.float32View,u=i.uint32View,h=this.boundTextures,l=this.renderer.boundTextures,c=this.renderer.textureGC.count,d=0,f=void 0,p=void 0,v=1,g=0,y=s[0],m=void 0,_=void 0,T=x.premultiplyBlendMode[o[0]._texture.baseTexture.premultipliedAlpha?1:0][o[0].blendMode];y.textureCount=0,y.start=0,y.blend=T,O++;var E=void 0;for(E=0;E0&&(e+="\nelse "),r0&&(r.shadowColor=e.dropShadowColor);for(var f=Math.cos(e.dropShadowAngle)*e.dropShadowDistance,p=Math.sin(e.dropShadowAngle)*e.dropShadowDistance,v=0;v3&&void 0!==arguments[3]&&arguments[3],i=this._style,o=i.letterSpacing;if(0===o)return void(n?this.context.strokeText(t,e,r):this.context.fillText(t,e,r));for(var s=String.prototype.split.call(t,""),a=e,u=0,h="";u3&&void 0!==arguments[3]?arguments[3]:t._canvas;n=n||r.wordWrap;var o=r.toFontString(),s=t.measureFont(o),a=i.getContext("2d");a.font=o;for(var u=n?t.wordWrap(e,r,i):e,h=u.split(/(?:\r\n|\r|\n)/),l=new Array(h.length),c=0,d=0;d2&&void 0!==arguments[2]?arguments[2]:t._canvas,i=n.getContext("2d"),o=0,s="",a="",u={},h=r.letterSpacing,l=r.whiteSpace,c=t.collapseSpaces(l),d=t.collapseNewlines(l),f=!c,p=r.wordWrapWidth+h,v=t.tokenize(e),g=0;gp)if(""!==s&&(a+=t.addLine(s),s="",o=0),t.canBreakWords(y,r.breakWords))for(var x=y.split(""),T=0;Tp&&(a+=t.addLine(s),f=!1,s="",o=0),s+=w,o+=M}else{s.length>0&&(a+=t.addLine(s),s="",o=0);var P=g===v.length-1;a+=t.addLine(y,!P),f=!1,s="",o=0}else b+o>p&&(f=!1,a+=t.addLine(s),s="",o=0),(s.length>0||!t.isBreakingSpace(y)||f)&&(s+=y,o+=b)}return a+=t.addLine(s,!1)},t.addLine=function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return e=t.trimRight(e),e=r?e+"\n":e},t.getFromCache=function(t,e,r,n){var i=r[t];if(void 0===i){var o=t.length*e;i=n.measureText(t).width+o,r[t]=i}return i},t.collapseSpaces=function(t){return"normal"===t||"pre-line"===t},t.collapseNewlines=function(t){return"normal"===t},t.trimRight=function(e){if("string"!=typeof e)return"";for(var r=e.length-1;r>=0;r--){var n=e[r];if(!t.isBreakingSpace(n))break;e=e.slice(0,-1)}return e},t.isNewline=function(e){return"string"==typeof e&&t._newlines.indexOf(e.charCodeAt(0))>=0},t.isBreakingSpace=function(e){return"string"==typeof e&&t._breakingSpaces.indexOf(e.charCodeAt(0))>=0},t.tokenize=function(e){var r=[],n="";if("string"!=typeof e)return r;for(var i=0;ia;--d){for(var g=0;g0&&void 0!==arguments[0]?arguments[0]:"";e?delete t._fonts[e]:t._fonts={}},t}();r.default=i;var o=document.createElement("canvas");o.width=o.height=10,i._canvas=o,i._context=o.getContext("2d"),i._fonts={},i.METRICS_STRING="|Éq",i.BASELINE_SYMBOL="M",i.BASELINE_MULTIPLIER=1.4,i._newlines=[10,13],i._breakingSpaces=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288]},{}],110:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t){return"number"==typeof t?(0,l.hex2string)(t):("string"==typeof t&&0===t.indexOf("0x")&&(t=t.replace("0x","#")),t)}function o(t){if(Array.isArray(t)){for(var e=0;e=0;r--){var n=e[r].trim();/([\"\'])[^\'\"]+\1/.test(n)||(n='"'+n+'"'),e[r]=n}return this.fontStyle+" "+this.fontVariant+" "+this.fontWeight+" "+t+" "+e.join(",")},u(t,[{key:"align",get:function(){return this._align},set:function(t){this._align!==t&&(this._align=t,this.styleID++)}},{key:"breakWords",get:function(){return this._breakWords},set:function(t){this._breakWords!==t&&(this._breakWords=t,this.styleID++)}},{key:"dropShadow",get:function(){return this._dropShadow},set:function(t){this._dropShadow!==t&&(this._dropShadow=t,this.styleID++)}},{key:"dropShadowAlpha",get:function(){return this._dropShadowAlpha},set:function(t){this._dropShadowAlpha!==t&&(this._dropShadowAlpha=t,this.styleID++)}},{key:"dropShadowAngle",get:function(){return this._dropShadowAngle},set:function(t){this._dropShadowAngle!==t&&(this._dropShadowAngle=t,this.styleID++)}},{key:"dropShadowBlur",get:function(){return this._dropShadowBlur},set:function(t){this._dropShadowBlur!==t&&(this._dropShadowBlur=t,this.styleID++)}},{key:"dropShadowColor",get:function(){return this._dropShadowColor},set:function(t){var e=o(t);this._dropShadowColor!==e&&(this._dropShadowColor=e,this.styleID++)}},{key:"dropShadowDistance",get:function(){return this._dropShadowDistance},set:function(t){this._dropShadowDistance!==t&&(this._dropShadowDistance=t,this.styleID++)}},{key:"fill",get:function(){return this._fill},set:function(t){var e=o(t);this._fill!==e&&(this._fill=e,this.styleID++)}},{key:"fillGradientType",get:function(){return this._fillGradientType},set:function(t){this._fillGradientType!==t&&(this._fillGradientType=t,this.styleID++)}},{key:"fillGradientStops",get:function(){return this._fillGradientStops},set:function(t){s(this._fillGradientStops,t)||(this._fillGradientStops=t,this.styleID++)}},{key:"fontFamily",get:function(){return this._fontFamily},set:function(t){this.fontFamily!==t&&(this._fontFamily=t,this.styleID++)}},{key:"fontSize",get:function(){return this._fontSize},set:function(t){this._fontSize!==t&&(this._fontSize=t,this.styleID++)}},{key:"fontStyle",get:function(){return this._fontStyle},set:function(t){this._fontStyle!==t&&(this._fontStyle=t,this.styleID++)}},{key:"fontVariant",get:function(){return this._fontVariant},set:function(t){this._fontVariant!==t&&(this._fontVariant=t,this.styleID++)}},{key:"fontWeight",get:function(){return this._fontWeight},set:function(t){this._fontWeight!==t&&(this._fontWeight=t,this.styleID++)}},{key:"letterSpacing",get:function(){return this._letterSpacing},set:function(t){this._letterSpacing!==t&&(this._letterSpacing=t,this.styleID++)}},{key:"lineHeight",get:function(){return this._lineHeight},set:function(t){this._lineHeight!==t&&(this._lineHeight=t,this.styleID++)}},{key:"leading",get:function(){return this._leading},set:function(t){this._leading!==t&&(this._leading=t,this.styleID++)}},{key:"lineJoin",get:function(){return this._lineJoin},set:function(t){this._lineJoin!==t&&(this._lineJoin=t,this.styleID++)}},{key:"miterLimit",get:function(){return this._miterLimit},set:function(t){this._miterLimit!==t&&(this._miterLimit=t,this.styleID++)}},{key:"padding",get:function(){return this._padding},set:function(t){this._padding!==t&&(this._padding=t,this.styleID++)}},{key:"stroke",get:function(){return this._stroke},set:function(t){var e=o(t);this._stroke!==e&&(this._stroke=e,this.styleID++)}},{key:"strokeThickness",get:function(){return this._strokeThickness},set:function(t){this._strokeThickness!==t&&(this._strokeThickness=t,this.styleID++)}},{key:"textBaseline",get:function(){return this._textBaseline},set:function(t){this._textBaseline!==t&&(this._textBaseline=t,this.styleID++)}},{key:"trim",get:function(){return this._trim},set:function(t){this._trim!==t&&(this._trim=t,this.styleID++)}},{key:"whiteSpace",get:function(){return this._whiteSpace},set:function(t){this._whiteSpace!==t&&(this._whiteSpace=t,this.styleID++)}},{key:"wordWrap",get:function(){return this._wordWrap},set:function(t){this._wordWrap!==t&&(this._wordWrap=t,this.styleID++)}},{key:"wordWrapWidth",get:function(){return this._wordWrapWidth},set:function(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this.styleID++)}}]),t}();r.default=d},{"../const":46,"../utils":125}],111:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("./BaseTexture"),u=n(a),h=t("../settings"),l=n(h),c=function(t){function e(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,s=arguments[2],a=arguments[3];i(this,e);var u=o(this,t.call(this,null,s));return u.resolution=a||l.default.RESOLUTION,u.width=Math.ceil(r),u.height=Math.ceil(n),u.realWidth=u.width*u.resolution,u.realHeight=u.height*u.resolution,u.scaleMode=void 0!==s?s:l.default.SCALE_MODE,u.hasLoaded=!0,u._glRenderTargets={},u._canvasRenderTarget=null,u.valid=!1,u}return s(e,t),e.prototype.resize=function(t,e){t=Math.ceil(t),e=Math.ceil(e),t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.realWidth=this.width*this.resolution,this.realHeight=this.height*this.resolution,this.valid&&this.emit("update",this))},e.prototype.destroy=function(){t.prototype.destroy.call(this,!0),this.renderer=null},e}(u.default);r.default=c},{"../settings":101,"./BaseTexture":112}],112:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../utils"),u=t("../settings"),h=n(u),l=t("eventemitter3"),c=n(l),d=t("../utils/determineCrossOrigin"),f=n(d),p=t("bit-twiddle"),v=n(p),g=function(t){function e(r,n,s){i(this,e);var u=o(this,t.call(this));return u.uid=(0,a.uid)(),u.touched=0,u.resolution=s||h.default.RESOLUTION,u.width=100,u.height=100,u.realWidth=100,u.realHeight=100,u.scaleMode=void 0!==n?n:h.default.SCALE_MODE,u.hasLoaded=!1,u.isLoading=!1,u.source=null,u.origSource=null,u.imageType=null,u.sourceScale=1,u.premultipliedAlpha=!0,u.imageUrl=null,u.isPowerOfTwo=!1,u.mipmap=h.default.MIPMAP_TEXTURES,u.wrapMode=h.default.WRAP_MODE,u._glTextures={},u._enabled=0,u._virtalBoundId=-1,u._destroyed=!1,u.textureCacheIds=[],r&&u.loadSource(r),u}return s(e,t),e.prototype.update=function(){"svg"!==this.imageType&&(this.realWidth=this.source.naturalWidth||this.source.videoWidth||this.source.width,this.realHeight=this.source.naturalHeight||this.source.videoHeight||this.source.height,this._updateDimensions()),this.emit("update",this)},e.prototype._updateDimensions=function(){this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=v.default.isPow2(this.realWidth)&&v.default.isPow2(this.realHeight)},e.prototype.loadSource=function(t){var e=this.isLoading;this.hasLoaded=!1,this.isLoading=!1,e&&this.source&&(this.source.onload=null,this.source.onerror=null);var r=!this.source;if(this.source=t,(t.src&&t.complete||t.getContext)&&t.width&&t.height)this._updateImageType(),"svg"===this.imageType?this._loadSvgSource():this._sourceLoaded(),r&&this.emit("loaded",this);else if(!t.getContext){this.isLoading=!0;var n=this;if(t.onload=function(){if(n._updateImageType(),t.onload=null,t.onerror=null,n.isLoading){if(n.isLoading=!1,n._sourceLoaded(),"svg"===n.imageType)return void n._loadSvgSource();n.emit("loaded",n)}},t.onerror=function(){t.onload=null,t.onerror=null,n.isLoading&&(n.isLoading=!1,n.emit("error",n))},t.complete&&t.src){if(t.onload=null,t.onerror=null,"svg"===n.imageType)return void n._loadSvgSource();this.isLoading=!1,t.width&&t.height?(this._sourceLoaded(),e&&this.emit("loaded",this)):e&&this.emit("error",this)}}},e.prototype._updateImageType=function(){if(this.imageUrl){var t=(0,a.decomposeDataUri)(this.imageUrl),e=void 0;if(t&&"image"===t.mediaType){var r=t.subType.split("+")[0];if(!(e=(0,a.getUrlFileExtension)("."+r)))throw new Error("Invalid image type in data URI.")}else(e=(0,a.getUrlFileExtension)(this.imageUrl))||(e="png");this.imageType=e}},e.prototype._loadSvgSource=function(){if("svg"===this.imageType){var t=(0,a.decomposeDataUri)(this.imageUrl);t?this._loadSvgSourceUsingDataUri(t):this._loadSvgSourceUsingXhr()}},e.prototype._loadSvgSourceUsingDataUri=function(t){var e=void 0;if("base64"===t.encoding){if(!atob)throw new Error("Your browser doesn't support base64 conversions.");e=atob(t.data)}else e=t.data;this._loadSvgSourceUsingString(e)},e.prototype._loadSvgSourceUsingXhr=function(){var t=this,e=new XMLHttpRequest;e.onload=function(){if(e.readyState!==e.DONE||200!==e.status)throw new Error("Failed to load SVG using XHR.");t._loadSvgSourceUsingString(e.response)},e.onerror=function(){return t.emit("error",t)},e.open("GET",this.imageUrl,!0),e.send()},e.prototype._loadSvgSourceUsingString=function(t){var r=(0,a.getSvgSize)(t),n=r.width,i=r.height;if(!n||!i)throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them.");this.realWidth=Math.round(n*this.sourceScale),this.realHeight=Math.round(i*this.sourceScale),this._updateDimensions();var o=document.createElement("canvas");o.width=this.realWidth,o.height=this.realHeight,o._pixiId="canvas_"+(0,a.uid)(),o.getContext("2d").drawImage(this.source,0,0,n,i,0,0,this.realWidth,this.realHeight),this.origSource=this.source,this.source=o,e.addToCache(this,o._pixiId),this.isLoading=!1,this._sourceLoaded(),this.emit("loaded",this)},e.prototype._sourceLoaded=function(){this.hasLoaded=!0,this.update()},e.prototype.destroy=function(){this.imageUrl&&(delete a.TextureCache[this.imageUrl],this.imageUrl=null,navigator.isCocoonJS||(this.source.src="")),this.source=null,this.dispose(),e.removeFromCache(this),this.textureCacheIds=null,this._destroyed=!0},e.prototype.dispose=function(){this.emit("dispose",this)},e.prototype.updateSourceImage=function(t){this.source.src=t,this.loadSource(this.source)},e.fromImage=function(t,r,n,i){var o=a.BaseTextureCache[t];if(!o){var s=new Image;void 0===r&&0!==t.indexOf("data:")?s.crossOrigin=(0,f.default)(t):r&&(s.crossOrigin="string"==typeof r?r:"anonymous"),o=new e(s,n),o.imageUrl=t,i&&(o.sourceScale=i),o.resolution=(0,a.getResolutionOfUrl)(t),s.src=t,e.addToCache(o,t)}return o},e.fromCanvas=function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"canvas";t._pixiId||(t._pixiId=n+"_"+(0,a.uid)());var i=a.BaseTextureCache[t._pixiId];return i||(i=new e(t,r),e.addToCache(i,t._pixiId)),i},e.from=function(t,r,n){if("string"==typeof t)return e.fromImage(t,void 0,r,n);if(t instanceof HTMLImageElement){var i=t.src,o=a.BaseTextureCache[i];return o||(o=new e(t,r),o.imageUrl=i,n&&(o.sourceScale=n),o.resolution=(0,a.getResolutionOfUrl)(i),e.addToCache(o,i)),o}return t instanceof HTMLCanvasElement?e.fromCanvas(t,r):t},e.addToCache=function(t,e){e&&(-1===t.textureCacheIds.indexOf(e)&&t.textureCacheIds.push(e),a.BaseTextureCache[e]=t)},e.removeFromCache=function(t){if("string"==typeof t){var e=a.BaseTextureCache[t];if(e){var r=e.textureCacheIds.indexOf(t);return r>-1&&e.textureCacheIds.splice(r,1),delete a.BaseTextureCache[t],e}}else if(t&&t.textureCacheIds){for(var n=0;n0&&e>0,this._frame.width=this.orig.width=t,this._frame.height=this.orig.height=e,r||this.baseTexture.resize(t,e),this._updateUvs()},e.create=function(t,r,n,i){return new e(new u.default(t,r,n,i))},e}(l.default);r.default=c},{"./BaseRenderTexture":111,"./Texture":115}],114:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:null;n(this,t),this.baseTexture=e,this.textures={},this.data=r,this.resolution=this._updateResolution(i||this.baseTexture.imageUrl),this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}return i(t,null,[{key:"BATCH_SIZE",get:function(){return 1e3}}]), +t.prototype._updateResolution=function(t){var e=this.data.meta.scale,r=(0,s.getResolutionOfUrl)(t,null);return null===r&&(r=void 0!==e?parseFloat(e):1),1!==r&&(this.baseTexture.resolution=r,this.baseTexture.update()),r},t.prototype.parse=function(e){this._batchIndex=0,this._callback=e,this._frameKeys.length<=t.BATCH_SIZE?(this._processFrames(0),this._parseComplete()):this._nextBatch()},t.prototype._processFrames=function(e){for(var r=e,n=t.BATCH_SIZE,i=this.baseTexture.sourceScale;r-e0&&void 0!==arguments[0]&&arguments[0];for(var e in this.textures)this.textures[e].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,t&&this.baseTexture.destroy(),this.baseTexture=null},t}();r.default=a},{"../":65,"../utils":125}],115:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t){t.destroy=function(){},t.on=function(){},t.once=function(){},t.emit=function(){}}r.__esModule=!0;var u=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:"canvas";return new e(l.default.fromCanvas(t,r,n))},e.fromVideo=function(t,r){return"string"==typeof t?e.fromVideoUrl(t,r):new e(d.default.fromVideo(t,r))},e.fromVideoUrl=function(t,r){return new e(d.default.fromUrl(t,r))},e.from=function(t){if("string"==typeof t){var r=m.TextureCache[t];if(!r){return null!==t.match(/\.(mp4|webm|ogg|h264|avi|mov)$/)?e.fromVideoUrl(t):e.fromImage(t)}return r}return t instanceof HTMLImageElement?new e(l.default.from(t)):t instanceof HTMLCanvasElement?e.fromCanvas(t,b.default.SCALE_MODE,"HTMLCanvasElement"):t instanceof HTMLVideoElement?e.fromVideo(t):t instanceof l.default?new e(t):t},e.fromLoader=function(t,r,n){var i=new l.default(t,void 0,(0,m.getResolutionOfUrl)(r)),o=new e(i);return i.imageUrl=r,n||(n=r),l.default.addToCache(o.baseTexture,n),e.addToCache(o,n),n!==r&&(l.default.addToCache(o.baseTexture,r),e.addToCache(o,r)),o},e.addToCache=function(t,e){e&&(-1===t.textureCacheIds.indexOf(e)&&t.textureCacheIds.push(e),m.TextureCache[e]=t)},e.removeFromCache=function(t){if("string"==typeof t){var e=m.TextureCache[t];if(e){var r=e.textureCacheIds.indexOf(t);return r>-1&&e.textureCacheIds.splice(r,1),delete m.TextureCache[t],e}}else if(t&&t.textureCacheIds){for(var n=0;nthis.baseTexture.width,s=r+i>this.baseTexture.height;if(o||s){var a=o&&s?"and":"or",u="X: "+e+" + "+n+" = "+(e+n)+" > "+this.baseTexture.width,h="Y: "+r+" + "+i+" = "+(r+i)+" > "+this.baseTexture.height;throw new Error("Texture Error: frame does not fit inside the base Texture dimensions: "+u+" "+a+" "+h)}this.valid=n&&i&&this.baseTexture.hasLoaded,this.trim||this.rotate||(this.orig=t),this.valid&&this._updateUvs()}},{key:"rotate",get:function(){return this._rotate},set:function(t){this._rotate=t,this.valid&&this._updateUvs()}},{key:"width",get:function(){return this.orig.width}},{key:"height",get:function(){return this.orig.height}}]),e}(g.default);r.default=x,x.EMPTY=new x(new l.default),a(x.EMPTY),a(x.EMPTY.baseTexture),x.WHITE=function(){var t=document.createElement("canvas");t.width=10,t.height=10;var e=t.getContext("2d");return e.fillStyle="white",e.fillRect(0,0,10,10),new x(new l.default(t))}(),a(x.WHITE),a(x.WHITE.baseTexture)},{"../math":70,"../settings":101,"../utils":125,"./BaseTexture":112,"./TextureUvs":117,"./VideoBaseTexture":118,eventemitter3:3}],116:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&!1===t.paused&&!1===t.ended&&t.readyState>2},e.prototype._isSourceReady=function(){return 3===this.source.readyState||4===this.source.readyState},e.prototype._onPlayStart=function(){this.hasLoaded||this._onCanPlay(),!this._isAutoUpdating&&this.autoUpdate&&(d.shared.add(this.update,this,f.UPDATE_PRIORITY.HIGH),this._isAutoUpdating=!0)},e.prototype._onPlayStop=function(){this._isAutoUpdating&&(d.shared.remove(this.update,this),this._isAutoUpdating=!1)},e.prototype._onCanPlay=function(){this.hasLoaded=!0,this.source&&(this.source.removeEventListener("canplay",this._onCanPlay),this.source.removeEventListener("canplaythrough",this._onCanPlay),this.width=this.source.videoWidth,this.height=this.source.videoHeight,this.__loaded||(this.__loaded=!0,this.emit("loaded",this)),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.source.play())},e.prototype.destroy=function(){this._isAutoUpdating&&d.shared.remove(this.update,this),this.source&&this.source._pixiId&&(l.default.removeFromCache(this.source._pixiId),delete this.source._pixiId,this.source.pause(),this.source.src="",this.source.load()),t.prototype.destroy.call(this)},e.fromVideo=function(t,r){t._pixiId||(t._pixiId="video_"+(0,c.uid)());var n=c.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),l.default.addToCache(n,t._pixiId)),n},e.fromUrl=function(t,r,n){var i=document.createElement("video");i.setAttribute("webkit-playsinline",""),i.setAttribute("playsinline","");var o=Array.isArray(t)?t[0].src||t[0]:t.src||t;if(void 0===n&&0!==o.indexOf("data:")?i.crossOrigin=(0,v.default)(o):n&&(i.crossOrigin="string"==typeof n?n:"anonymous"),Array.isArray(t))for(var s=0;s2&&void 0!==arguments[2]?arguments[2]:u.UPDATE_PRIORITY.NORMAL;return this._addListener(new l.default(t,e,r))},t.prototype.addOnce=function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:u.UPDATE_PRIORITY.NORMAL;return this._addListener(new l.default(t,e,r,!0))},t.prototype._addListener=function(t){var e=this._head.next,r=this._head;if(e){for(;e;){if(t.priority>e.priority){t.connect(r);break}r=e,e=e.next}t.previous||t.connect(r)}else t.connect(r);return this._startIfPossible(),this},t.prototype.remove=function(t,e){for(var r=this._head.next;r;)r=r.match(t,e)?r.destroy():r.next;return this._head.next||this._cancelIfNeeded(),this},t.prototype.start=function(){this.started||(this.started=!0,this._requestIfNeeded())},t.prototype.stop=function(){this.started&&(this.started=!1,this._cancelIfNeeded())},t.prototype.destroy=function(){this.stop();for(var t=this._head.next;t;)t=t.destroy(!0);this._head.destroy(),this._head=null},t.prototype.update=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:performance.now(),e=void 0;if(t>this.lastTime){e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),this.deltaTime=e*a.default.TARGET_FPMS*this.speed;for(var r=this._head,n=r.next;n;)n=n.emit(this.deltaTime);r.next||this._cancelIfNeeded()}else this.deltaTime=this.elapsedMS=0;this.lastTime=t},o(t,[{key:"FPS",get:function(){return 1e3/this.elapsedMS}},{key:"minFPS",get:function(){return 1e3/this._maxElapsedMS},set:function(t){var e=Math.min(Math.max(0,t)/1e3,a.default.TARGET_FPMS);this._maxElapsedMS=1/e}}]),t}();r.default=c},{"../const":46,"../settings":101,"./TickerListener":120}],120:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];n(this,t),this.fn=e,this.context=r,this.priority=i,this.once=o,this.next=null,this.previous=null,this._destroyed=!1}return t.prototype.match=function(t,e){return e=e||null,this.fn===t&&this.context===e},t.prototype.emit=function(t){this.fn&&(this.context?this.fn.call(this.context,t):this.fn(t));var e=this.next;return this.once&&this.destroy(!0),this._destroyed&&(this.next=null),e},t.prototype.connect=function(t){this.previous=t,t.next&&(t.next.previous=this),this.next=t.next,t.next=this},t.prototype.destroy=function(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._destroyed=!0,this.fn=null,this.context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);var e=this.next;return this.next=t?null:e,this.previous=null,e},t}();r.default=i},{}],121:[function(t,e,r){"use strict";r.__esModule=!0,r.Ticker=r.shared=void 0;var n=t("./Ticker"),i=function(t){return t&&t.__esModule?t:{default:t}}(n),o=new i.default;o.autoStart=!0,o.destroy=function(){},r.shared=o,r.Ticker=i.default},{"./Ticker":119}],122:[function(t,e,r){"use strict";function n(){return!(!!navigator.platform&&/iPad|iPhone|iPod/.test(navigator.platform))}r.__esModule=!0,r.default=n},{}],123:[function(t,e,r){"use strict";function n(t){for(var e=6*t,r=new Uint16Array(e),n=0,i=0;n1&&void 0!==arguments[1]?arguments[1]:window.location;if(0===t.indexOf("data:"))return"";e=e||window.location,s||(s=document.createElement("a")),s.href=t,t=o.default.parse(s.href);var r=!t.port&&""===e.port||t.port===e.port;return t.hostname===e.hostname&&r&&t.protocol===e.protocol?"":"anonymous"}r.__esModule=!0,r.default=n;var i=t("url"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=void 0},{url:38}],125:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(){return++U}function s(t,e){return e=e||[],e[0]=(t>>16&255)/255,e[1]=(t>>8&255)/255,e[2]=(255&t)/255,e}function a(t){return t=t.toString(16),"#"+(t="000000".substr(0,6-t.length)+t)}function u(t){return(255*t[0]<<16)+(255*t[1]<<8)+(255*t[2]|0)}function h(t,e){var r=S.default.RETINA_PREFIX.exec(t);return r?parseFloat(r[1]):void 0!==e?e:1}function l(t){var e=w.DATA_URI.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,charset:e[3]?e[3].toLowerCase():void 0,encoding:e[4]?e[4].toLowerCase():void 0,data:e[5]}}function c(t){var e=w.URL_FILE_EXTENSION.exec(t);if(e)return e[1].toLowerCase()}function d(t){var e=w.SVG_SIZE.exec(t),r={};return e&&(r[e[1]]=Math.round(parseFloat(e[3])),r[e[5]]=Math.round(parseFloat(e[7]))),r}function f(){X=!0}function p(t){if(!X){if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var e=["\n %c %c %c PixiJS "+w.VERSION+" - ✰ "+t+" ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n","background: #ff66a5; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff66a5; background: #030307; padding:5px 0;","background: #ff66a5; padding:5px 0;","background: #ffc3dc; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;"];window.console.log.apply(console,e)}else window.console&&window.console.log("PixiJS "+w.VERSION+" - "+t+" - http://www.pixijs.com/");X=!0}}function v(){var t={stencil:!0,failIfMajorPerformanceCaveat:!0};try{if(!window.WebGLRenderingContext)return!1;var e=document.createElement("canvas"),r=e.getContext("webgl",t)||e.getContext("experimental-webgl",t),n=!(!r||!r.getContextAttributes().stencil);if(r){var i=r.getExtension("WEBGL_lose_context");i&&i.loseContext()}return r=null,n}catch(t){return!1}}function g(t){return 0===t?0:t<0?-1:1}function y(){var t=void 0;for(t in G)G[t].destroy();for(t in W)W[t].destroy()}function m(){var t=void 0;for(t in G)delete G[t];for(t in W)delete W[t]}function _(t,e){return H[e?1:0][t]}function b(t,e){if(1===e)return(255*e<<24)+t;if(0===e)return 0;var r=t>>16&255,n=t>>8&255,i=255&t;return r=r*e+.5|0,n=n*e+.5|0,i=i*e+.5|0,(255*e<<24)+(r<<16)+(n<<8)+i}function x(t,e,r,n){return r=r||new Float32Array(4),n||void 0===n?(r[0]=t[0]*e,r[1]=t[1]*e,r[2]=t[2]*e):(r[0]=t[0],r[1]=t[1],r[2]=t[2]),r[3]=e,r}function T(t,e,r,n){return r=r||new Float32Array(4),r[0]=(t>>16&255)/255,r[1]=(t>>8&255)/255,r[2]=(255&t)/255,(n||void 0===n)&&(r[0]*=e,r[1]*=e,r[2]*=e),r[3]=e,r}r.__esModule=!0,r.premultiplyBlendMode=r.BaseTextureCache=r.TextureCache=r.earcut=r.mixins=r.pluginTarget=r.EventEmitter=r.removeItems=r.isMobile=void 0,r.uid=o,r.hex2rgb=s,r.hex2string=a,r.rgb2hex=u,r.getResolutionOfUrl=h,r.decomposeDataUri=l,r.getUrlFileExtension=c,r.getSvgSize=d,r.skipHello=f,r.sayHello=p,r.isWebGLSupported=v,r.sign=g,r.destroyTextureCache=y,r.clearTextureCache=m,r.correctBlendMode=_,r.premultiplyTint=b,r.premultiplyRgba=x,r.premultiplyTintToRgba=T;var w=t("../const"),E=t("../settings"),S=i(E),O=t("eventemitter3"),M=i(O),P=t("./pluginTarget"),C=i(P),R=t("./mixin"),A=n(R),I=t("ismobilejs"),D=n(I),L=t("remove-array-items"),N=i(L),B=t("./mapPremultipliedBlendModes"),F=i(B),k=t("earcut"),j=i(k),U=0,X=!1;r.isMobile=D,r.removeItems=N.default,r.EventEmitter=M.default,r.pluginTarget=C.default,r.mixins=A,r.earcut=j.default;var G=r.TextureCache=Object.create(null),W=r.BaseTextureCache=Object.create(null),H=r.premultiplyBlendMode=(0,F.default)()},{"../const":46,"../settings":101,"./mapPremultipliedBlendModes":126,"./mixin":128,"./pluginTarget":129,earcut:2,eventemitter3:3,ismobilejs:4,"remove-array-items":31}],126:[function(t,e,r){"use strict";function n(){for(var t=[],e=[],r=0;r<32;r++)t[r]=r,e[r]=r;t[i.BLEND_MODES.NORMAL_NPM]=i.BLEND_MODES.NORMAL,t[i.BLEND_MODES.ADD_NPM]=i.BLEND_MODES.ADD,t[i.BLEND_MODES.SCREEN_NPM]=i.BLEND_MODES.SCREEN,e[i.BLEND_MODES.NORMAL]=i.BLEND_MODES.NORMAL_NPM,e[i.BLEND_MODES.ADD]=i.BLEND_MODES.ADD_NPM,e[i.BLEND_MODES.SCREEN]=i.BLEND_MODES.SCREEN_NPM;var n=[];return n.push(e),n.push(t),n}r.__esModule=!0,r.default=n;var i=t("../const")},{"../const":46}],127:[function(t,e,r){"use strict";function n(t){return o.default.tablet||o.default.phone?4:t}r.__esModule=!0,r.default=n;var i=t("ismobilejs"),o=function(t){return t&&t.__esModule?t:{default:t}}(i)},{ismobilejs:4}],128:[function(t,e,r){"use strict";function n(t,e){if(t&&e)for(var r=Object.keys(e),n=0;n1?this._fontStyle="italic":t.indexOf("oblique")>-1?this._fontStyle="oblique":this._fontStyle="normal",t.indexOf("small-caps")>-1?this._fontVariant="small-caps":this._fontVariant="normal";var e=t.split(" "),r=-1;this._fontSize=26;for(var i=0;i-1&&r=this._durations[this.currentFrame];)n-=this._durations[this.currentFrame]*i,this._currentTime+=i;this._currentTime+=n/this._durations[this.currentFrame]}else this._currentTime+=e;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):r!==this.currentFrame&&(this.loop&&this.onLoop&&(this.animationSpeed>0&&this.currentFramer&&this.onLoop()),this.updateTexture())},e.prototype.updateTexture=function(){this._texture=this._textures[this.currentFrame],this._textureID=-1,this.cachedTint=16777215,this.onFrameChange&&this.onFrameChange(this.currentFrame)},e.prototype.destroy=function(e){this.stop(),t.prototype.destroy.call(this,e)},e.fromFrames=function(t){for(var r=[],n=0;n1&&void 0!==arguments[1]?arguments[1]:{};i(this,e);var s=o(this,t.call(this));return s._textWidth=0,s._textHeight=0,s._glyphs=[],s._font={tint:void 0!==n.tint?n.tint:16777215,align:n.align||"left",name:null,size:0},s.font=n.font,s._text=r,s._maxWidth=0,s._maxLineHeight=0,s._letterSpacing=0,s._anchor=new c.default(function(){s.dirty=!0},s,0,0),s.dirty=!1,s.updateText(),s}return s(e,t),e.prototype.updateText=function(){for(var t=e.fonts[this._font.name],r=this._font.size/t.size,n=new h.Point,i=[],o=[],s=this.text.replace(/(?:\r\n|\r)/g,"\n"),a=s.length,u=this._maxWidth*t.size/this._font.size,l=null,c=0,d=0,f=0,p=-1,v=0,g=0,y=0,m=0;m0&&n.x>u&&(++g,h.utils.removeItems(i,1+p-g,1+m-p),m=p,p=-1,o.push(v),d=Math.max(d,v),f++,n.x=0,n.y+=t.lineHeight,l=null))}else o.push(c),d=Math.max(d,c),++f,++g,n.x=0,n.y+=t.lineHeight,l=null}var T=s.charAt(s.length-1);"\r"!==T&&"\n"!==T&&(/(?:\s)/.test(T)&&(c=v),o.push(c),d=Math.max(d,c));for(var w=[],E=0;E<=f;E++){var S=0;"right"===this._font.align?S=d-o[E]:"center"===this._font.align&&(S=(d-o[E])/2),w.push(S)}for(var O=i.length,M=this.tint,P=0;P=0?t:16777215,this.dirty=!0}},{key:"align",get:function(){return this._font.align},set:function(t){this._font.align=t||"left",this.dirty=!0}},{key:"anchor",get:function(){return this._anchor},set:function(t){"number"==typeof t?this._anchor.set(t):this._anchor.copy(t)}},{key:"font",get:function(){return this._font},set:function(t){t&&("string"==typeof t?(t=t.split(" "),this._font.name=1===t.length?t[0]:t.slice(1).join(" "),this._font.size=t.length>=2?parseInt(t[0],10):e.fonts[this._font.name].size):(this._font.name=t.name,this._font.size="number"==typeof t.size?t.size:parseInt(t.size,10)),this.dirty=!0)}},{key:"text",get:function(){return this._text},set:function(t){t=t.toString()||" ",this._text!==t&&(this._text=t,this.dirty=!0)}},{key:"maxWidth",get:function(){return this._maxWidth},set:function(t){this._maxWidth!==t&&(this._maxWidth=t,this.dirty=!0)}},{key:"maxLineHeight",get:function(){return this.validate(),this._maxLineHeight}},{key:"textWidth",get:function(){return this.validate(),this._textWidth}},{key:"letterSpacing",get:function(){return this._letterSpacing},set:function(t){this._letterSpacing!==t&&(this._letterSpacing=t,this.dirty=!0)}},{key:"textHeight",get:function(){return this.validate(),this._textHeight}}]),e}(h.Container);r.default=v,v.fonts={}},{"../core":65,"../core/math/ObservablePoint":68,"../core/settings":101,"../core/utils":125}],137:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:100,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:100;n(this,e);var a=i(this,t.call(this,r));return a.tileTransform=new u.TransformStatic,a._width=o,a._height=s,a._canvasPattern=null,a.uvTransform=r.transform||new u.TextureMatrix(r),a.pluginName="tilingSprite",a.uvRespectAnchor=!1,a}return o(e,t),e.prototype._onTextureUpdate=function(){this.uvTransform&&(this.uvTransform.texture=this._texture),this.cachedTint=16777215},e.prototype._renderWebGL=function(t){var e=this._texture;e&&e.valid&&(this.tileTransform.updateLocalTransform(),this.uvTransform.update(),t.setObjectRenderer(t.plugins[this.pluginName]),t.plugins[this.pluginName].render(this))},e.prototype._renderCanvas=function(t){var e=this._texture;if(e.baseTexture.hasLoaded){var r=t.context,n=this.worldTransform,i=t.resolution,o=e.baseTexture,s=o.resolution,a=this.tilePosition.x/this.tileScale.x%e._frame.width*s,h=this.tilePosition.y/this.tileScale.y%e._frame.height*s;if(this._textureID!==this._texture._updateID||this.cachedTint!==this.tint){this._textureID=this._texture._updateID;var c=new u.CanvasRenderTarget(e._frame.width,e._frame.height,s);16777215!==this.tint?(this.tintedTexture=l.default.getTintedTexture(this,this.tint),c.context.drawImage(this.tintedTexture,0,0)):c.context.drawImage(o.source,-e._frame.x*s,-e._frame.y*s),this.cachedTint=this.tint,this._canvasPattern=c.context.createPattern(c.canvas,"repeat")}r.globalAlpha=this.worldAlpha,r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t.setBlendMode(this.blendMode),r.fillStyle=this._canvasPattern,r.scale(this.tileScale.x/s,this.tileScale.y/s);var d=this.anchor.x*-this._width,f=this.anchor.y*-this._height;this.uvRespectAnchor?(r.translate(a,h),r.fillRect(-a+d,-h+f,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s)):(r.translate(a+d,h+f),r.fillRect(-a,-h,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s))}},e.prototype._calculateBounds=function(){var t=this._width*-this._anchor._x,e=this._height*-this._anchor._y,r=this._width*(1-this._anchor._x),n=this._height*(1-this._anchor._y);this._bounds.addFrame(this.transform,t,e,r,n)},e.prototype.getLocalBounds=function(e){return 0===this.children.length?(this._bounds.minX=this._width*-this._anchor._x,this._bounds.minY=this._height*-this._anchor._y,this._bounds.maxX=this._width*(1-this._anchor._x),this._bounds.maxY=this._height*(1-this._anchor._y),e||(this._localBoundsRect||(this._localBoundsRect=new u.Rectangle),e=this._localBoundsRect),this._bounds.getRectangle(e)):t.prototype.getLocalBounds.call(this,e)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,c);var e=this._width,r=this._height,n=-e*this.anchor._x;if(c.x>=n&&c.x=i&&c.y0&&void 0!==arguments[0]?arguments[0]:new i.Point,e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.parent?this.parent.toGlobal(this.position,t,e):(t.x=this.position.x,t.y=this.position.y),t}},{"../core":65}],141:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.BitmapText=r.TilingSpriteRenderer=r.TilingSprite=r.AnimatedSprite=void 0;var i=t("./AnimatedSprite");Object.defineProperty(r,"AnimatedSprite",{enumerable:!0,get:function(){return n(i).default}});var o=t("./TilingSprite");Object.defineProperty(r,"TilingSprite",{enumerable:!0,get:function(){return n(o).default}});var s=t("./webgl/TilingSpriteRenderer");Object.defineProperty(r,"TilingSpriteRenderer",{enumerable:!0,get:function(){return n(s).default}});var a=t("./BitmapText");Object.defineProperty(r,"BitmapText",{enumerable:!0,get:function(){return n(a).default}}),t("./cacheAsBitmap"),t("./getChildByName"),t("./getGlobalPosition")},{"./AnimatedSprite":135,"./BitmapText":136,"./TilingSprite":137,"./cacheAsBitmap":138,"./getChildByName":139,"./getGlobalPosition":140,"./webgl/TilingSpriteRenderer":142}],142:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=t("../../core"),a=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(s),u=t("../../core/const"),h=(t("path"),new a.Matrix),l=function(t){function e(r){n(this,e);var o=i(this,t.call(this,r));return o.shader=null,o.simpleShader=null,o.quad=null,o}return o(e,t),e.prototype.onContextChange=function(){var t=this.renderer.gl;this.shader=new a.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n gl_FragColor = sample * uColor;\n}\n"),this.simpleShader=new a.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = sample * uColor;\n}\n"),this.renderer.bindVao(null),this.quad=new a.Quad(t,this.renderer.state.attribState),this.quad.initVao(this.shader)},e.prototype.render=function(t){var e=this.renderer,r=this.quad;e.bindVao(r.vao);var n=r.vertices;n[0]=n[6]=t._width*-t.anchor.x,n[1]=n[3]=t._height*-t.anchor.y,n[2]=n[4]=t._width*(1-t.anchor.x),n[5]=n[7]=t._height*(1-t.anchor.y),t.uvRespectAnchor&&(n=r.uvs,n[0]=n[6]=-t.anchor.x,n[1]=n[3]=-t.anchor.y,n[2]=n[4]=1-t.anchor.x,n[5]=n[7]=1-t.anchor.y),r.upload();var i=t._texture,o=i.baseTexture,s=t.tileTransform.localTransform,l=t.uvTransform,c=o.isPowerOfTwo&&i.frame.width===o.width&&i.frame.height===o.height;c&&(o._glTextures[e.CONTEXT_UID]?c=o.wrapMode!==u.WRAP_MODES.CLAMP:o.wrapMode===u.WRAP_MODES.CLAMP&&(o.wrapMode=u.WRAP_MODES.REPEAT));var d=c?this.simpleShader:this.shader;e.bindShader(d);var f=i.width,p=i.height,v=t._width,g=t._height;h.set(s.a*f/v,s.b*f/g,s.c*p/v,s.d*p/g,s.tx/v,s.ty/g),h.invert(),c?h.prepend(l.mapCoord):(d.uniforms.uMapCoord=l.mapCoord.toArray(!0),d.uniforms.uClampFrame=l.uClampFrame,d.uniforms.uClampOffset=l.uClampOffset),d.uniforms.uTransform=h.toArray(!0),d.uniforms.uColor=a.utils.premultiplyTintToRgba(t.tint,t.worldAlpha,d.uniforms.uColor,o.premultipliedAlpha),d.uniforms.translationMatrix=t.transform.worldTransform.toArray(!0),d.uniforms.uSampler=e.bindTexture(i),e.setBlendMode(a.utils.correctBlendMode(t.blendMode,o.premultipliedAlpha)),r.vao.draw(this.renderer.gl.TRIANGLES,6,0)},e}(a.ObjectRenderer);r.default=l,a.WebGLRenderer.registerPlugin("tilingSprite",l)},{"../../core":65,"../../core/const":46,path:8}],143:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:1;n(this,e);var o=i(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n"));return o.alpha=r,o.glShaderKey="alpha",o}return o(e,t),s(e,[{key:"alpha",get:function(){return this.uniforms.uAlpha},set:function(t){this.uniforms.uAlpha=t}}]),e}(u.Filter));r.default=h},{"../../core":65,path:8}],144:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r=r&&(u=t-h-1),l=l.replace("%value%",e[u]),s+=l,s+="\n"}return n=n.replace("%blur%",s),n=n.replace("%size%",t)}r.__esModule=!0,r.default=n;var i={5:[.153388,.221461,.250301],7:[.071303,.131514,.189879,.214607],9:[.028532,.067234,.124009,.179044,.20236],11:[.0093,.028002,.065984,.121703,.175713,.198596],13:[.002406,.009255,.027867,.065666,.121117,.174868,.197641],15:[489e-6,.002403,.009246,.02784,.065602,.120999,.174697,.197448]},o=["varying vec2 vBlurTexCoords[%size%];","uniform sampler2D uSampler;","void main(void)","{"," gl_FragColor = vec4(0.0);"," %blur%","}"].join("\n")},{}],148:[function(t,e,r){"use strict";function n(t,e){var r=Math.ceil(t/2),n=i,o="",s=void 0;s=e?"vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);":"vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);";for(var a=0;ae;)r-=2;return r}r.__esModule=!0,r.default=n},{}],150:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n"));return r.uniforms.m=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],r.alpha=1,r}return o(e,t),e.prototype._loadMatrix=function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t;e&&(this._multiply(r,this.uniforms.m,t),r=this._colorMatrix(r)),this.uniforms.m=r},e.prototype._multiply=function(t,e,r){return t[0]=e[0]*r[0]+e[1]*r[5]+e[2]*r[10]+e[3]*r[15],t[1]=e[0]*r[1]+e[1]*r[6]+e[2]*r[11]+e[3]*r[16],t[2]=e[0]*r[2]+e[1]*r[7]+e[2]*r[12]+e[3]*r[17],t[3]=e[0]*r[3]+e[1]*r[8]+e[2]*r[13]+e[3]*r[18],t[4]=e[0]*r[4]+e[1]*r[9]+e[2]*r[14]+e[3]*r[19]+e[4],t[5]=e[5]*r[0]+e[6]*r[5]+e[7]*r[10]+e[8]*r[15],t[6]=e[5]*r[1]+e[6]*r[6]+e[7]*r[11]+e[8]*r[16],t[7]=e[5]*r[2]+e[6]*r[7]+e[7]*r[12]+e[8]*r[17],t[8]=e[5]*r[3]+e[6]*r[8]+e[7]*r[13]+e[8]*r[18],t[9]=e[5]*r[4]+e[6]*r[9]+e[7]*r[14]+e[8]*r[19]+e[9],t[10]=e[10]*r[0]+e[11]*r[5]+e[12]*r[10]+e[13]*r[15],t[11]=e[10]*r[1]+e[11]*r[6]+e[12]*r[11]+e[13]*r[16],t[12]=e[10]*r[2]+e[11]*r[7]+e[12]*r[12]+e[13]*r[17],t[13]=e[10]*r[3]+e[11]*r[8]+e[12]*r[13]+e[13]*r[18],t[14]=e[10]*r[4]+e[11]*r[9]+e[12]*r[14]+e[13]*r[19]+e[14],t[15]=e[15]*r[0]+e[16]*r[5]+e[17]*r[10]+e[18]*r[15],t[16]=e[15]*r[1]+e[16]*r[6]+e[17]*r[11]+e[18]*r[16],t[17]=e[15]*r[2]+e[16]*r[7]+e[17]*r[12]+e[18]*r[17],t[18]=e[15]*r[3]+e[16]*r[8]+e[17]*r[13]+e[18]*r[18],t[19]=e[15]*r[4]+e[16]*r[9]+e[17]*r[14]+e[18]*r[19]+e[19],t},e.prototype._colorMatrix=function(t){var e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e},e.prototype.brightness=function(t,e){var r=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.greyscale=function(t,e){var r=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.blackAndWhite=function(t){var e=[.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.hue=function(t,e){t=(t||0)/180*Math.PI;var r=Math.cos(t),n=Math.sin(t),i=Math.sqrt,o=1/3,s=i(o),a=r+(1-r)*o,u=o*(1-r)-s*n,h=o*(1-r)+s*n,l=o*(1-r)+s*n,c=r+o*(1-r),d=o*(1-r)-s*n,f=o*(1-r)-s*n,p=o*(1-r)+s*n,v=r+o*(1-r),g=[a,u,h,0,0,l,c,d,0,0,f,p,v,0,0,0,0,0,1,0];this._loadMatrix(g,e)},e.prototype.contrast=function(t,e){var r=(t||0)+1,n=-.5*(r-1),i=[r,0,0,0,n,0,r,0,0,n,0,0,r,0,n,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.saturate=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=2*t/3+1,n=-.5*(r-1),i=[r,n,n,0,0,n,r,n,0,0,n,n,r,0,0,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.desaturate=function(){this.saturate(-1)},e.prototype.negative=function(t){var e=[-1,0,0,1,0,0,-1,0,1,0,0,0,-1,1,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.sepia=function(t){var e=[.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.technicolor=function(t){var e=[1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.polaroid=function(t){var e=[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.toBGR=function(t){var e=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.kodachrome=function(t){var e=[1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.browni=function(t){var e=[.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.vintage=function(t){var e=[.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.colorTone=function(t,e,r,n,i){t=t||.2,e=e||.15,r=r||16770432,n=n||3375104;var o=(r>>16&255)/255,s=(r>>8&255)/255,a=(255&r)/255,u=(n>>16&255)/255,h=(n>>8&255)/255,l=(255&n)/255,c=[.3,.59,.11,0,0,o,s,a,t,0,u,h,l,e,0,o-u,s-h,a-l,0,0];this._loadMatrix(c,i)},e.prototype.night=function(t,e){t=t||.1;var r=[-2*t,-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.predator=function(t,e){var r=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.lsd=function(t){var e=[2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.reset=function(){var t=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(t,!1)},s(e,[{key:"matrix",get:function(){return this.uniforms.m},set:function(t){this.uniforms.m=t}},{key:"alpha",get:function(){return this.uniforms.uAlpha},set:function(t){this.uniforms.uAlpha=t}}]),e}(u.Filter));r.default=h,h.prototype.grayscale=h.prototype.greyscale},{"../../core":65,path:8}],151:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n'))}return o(e,t),e}(a.Filter));r.default=u},{"../../core":65,path:8}],153:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./fxaa/FXAAFilter");Object.defineProperty(r,"FXAAFilter",{enumerable:!0,get:function(){return n(i).default}});var o=t("./noise/NoiseFilter");Object.defineProperty(r,"NoiseFilter",{enumerable:!0,get:function(){return n(o).default}});var s=t("./displacement/DisplacementFilter");Object.defineProperty(r,"DisplacementFilter",{enumerable:!0,get:function(){return n(s).default}});var a=t("./blur/BlurFilter");Object.defineProperty(r,"BlurFilter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./blur/BlurXFilter");Object.defineProperty(r,"BlurXFilter",{enumerable:!0,get:function(){return n(u).default}});var h=t("./blur/BlurYFilter");Object.defineProperty(r,"BlurYFilter",{enumerable:!0,get:function(){return n(h).default}});var l=t("./colormatrix/ColorMatrixFilter");Object.defineProperty(r,"ColorMatrixFilter",{enumerable:!0,get:function(){return n(l).default}});var c=t("./alpha/AlphaFilter");Object.defineProperty(r,"AlphaFilter",{enumerable:!0,get:function(){return n(c).default}})},{"./alpha/AlphaFilter":143,"./blur/BlurFilter":144,"./blur/BlurXFilter":145,"./blur/BlurYFilter":146,"./colormatrix/ColorMatrixFilter":150,"./displacement/DisplacementFilter":151,"./fxaa/FXAAFilter":152,"./noise/NoiseFilter":154}],154:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:.5,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Math.random();n(this,e);var s=i(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n"));return s.noise=r,s.seed=o,s}return o(e,t),s(e,[{key:"noise",get:function(){return this.uniforms.uNoise},set:function(t){this.uniforms.uNoise=t}},{key:"seed",get:function(){return this.uniforms.uSeed},set:function(t){this.uniforms.uSeed=t}}]),e}(u.Filter));r.default=h},{"../../core":65,path:8}],155:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:1;this.removeEvents(),this.interactionDOMElement=t,this.resolution=e,this.addEvents()},e.prototype.addEvents=function(){this.interactionDOMElement&&(h.ticker.shared.add(this.update,this,h.UPDATE_PRIORITY.INTERACTION),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="none",this.interactionDOMElement.style["-ms-touch-action"]="none"):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]="none"),this.supportsPointerEvents?(window.document.addEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("pointerover",this.onPointerOver,!0),window.addEventListener("pointercancel",this.onPointerCancel,!0),window.addEventListener("pointerup",this.onPointerUp,!0)):(window.document.addEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onPointerOver,!0),window.addEventListener("mouseup",this.onPointerUp,!0)),this.supportsTouchEvents&&(this.interactionDOMElement.addEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.addEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.addEventListener("touchmove",this.onPointerMove,!0)),this.eventsAdded=!0)},e.prototype.removeEvents=function(){this.interactionDOMElement&&(h.ticker.shared.remove(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="",this.interactionDOMElement.style["-ms-touch-action"]=""):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]=""),this.supportsPointerEvents?(window.document.removeEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("pointerover",this.onPointerOver,!0),window.removeEventListener("pointercancel",this.onPointerCancel,!0),window.removeEventListener("pointerup",this.onPointerUp,!0)):(window.document.removeEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onPointerOver,!0),window.removeEventListener("mouseup",this.onPointerUp,!0)),this.supportsTouchEvents&&(this.interactionDOMElement.removeEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.removeEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onPointerMove,!0)),this.interactionDOMElement=null,this.eventsAdded=!1)},e.prototype.update=function(t){if(this._deltaTime+=t,!(this._deltaTime=0;l--){var c=h[l],d=this.processInteractive(t,c,r,n,a);if(d){if(!c.parent)continue;a=!1,d&&(t.target&&(n=!1),s=!0)}}return i&&(n&&!t.target&&!e.hitArea&&e.containsPoint&&e.containsPoint(o)&&(s=!0),e.interactive&&(s&&!t.target&&(t.target=e),r&&r(t,e,!!s))),s},e.prototype.onPointerDown=function(t){if(!this.supportsTouchEvents||"touch"!==t.pointerType){var e=this.normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&t.preventDefault();for(var r=e.length,n=0;ne?1:this._height/e;t[9]=t[11]=t[13]=t[15]=this._topHeight*r,t[17]=t[19]=t[21]=t[23]=this._height-this._bottomHeight*r,t[25]=t[27]=t[29]=t[31]=this._height},e.prototype.updateVerticalVertices=function(){var t=this.vertices,e=this._leftWidth+this._rightWidth,r=this._width>e?1:this._width/e;t[2]=t[10]=t[18]=t[26]=this._leftWidth*r,t[4]=t[12]=t[20]=t[28]=this._width-this._rightWidth*r,t[6]=t[14]=t[22]=t[30]=this._width},e.prototype._renderCanvas=function(t){var e=t.context;e.globalAlpha=this.worldAlpha,t.setBlendMode(this.blendMode);var r=this.worldTransform,n=t.resolution;t.roundPixels?e.setTransform(r.a*n,r.b*n,r.c*n,r.d*n,r.tx*n|0,r.ty*n|0):e.setTransform(r.a*n,r.b*n,r.c*n,r.d*n,r.tx*n,r.ty*n);var i=this._texture.baseTexture,o=i.source,s=i.width*i.resolution,a=i.height*i.resolution;this.drawSegment(e,o,s,a,0,1,10,11),this.drawSegment(e,o,s,a,2,3,12,13),this.drawSegment(e,o,s,a,4,5,14,15),this.drawSegment(e,o,s,a,8,9,18,19),this.drawSegment(e,o,s,a,10,11,20,21),this.drawSegment(e,o,s,a,12,13,22,23),this.drawSegment(e,o,s,a,16,17,26,27),this.drawSegment(e,o,s,a,18,19,28,29),this.drawSegment(e,o,s,a,20,21,30,31)},e.prototype.drawSegment=function(t,e,r,n,i,o,s,a){var u=this.uvs,h=this.vertices,l=(u[s]-u[i])*r,c=(u[a]-u[o])*n,d=h[s]-h[i],f=h[a]-h[o];l<1&&(l=1),c<1&&(c=1),d<1&&(d=1),f<1&&(f=1),t.drawImage(e,u[i]*r,u[o]*n,l,c,h[i],h[o],d,f)},e.prototype._refresh=function(){t.prototype._refresh.call(this);var e=this.uvs,r=this._texture;this._origWidth=r.orig.width,this._origHeight=r.orig.height;var n=1/this._origWidth,i=1/this._origHeight;e[0]=e[8]=e[16]=e[24]=0,e[1]=e[3]=e[5]=e[7]=0,e[6]=e[14]=e[22]=e[30]=1,e[25]=e[27]=e[29]=e[31]=1,e[2]=e[10]=e[18]=e[26]=n*this._leftWidth,e[4]=e[12]=e[20]=e[28]=1-n*this._rightWidth,e[9]=e[11]=e[13]=e[15]=i*this._topHeight,e[17]=e[19]=e[21]=e[23]=1-i*this._bottomHeight,this.updateHorizontalVertices(),this.updateVerticalVertices(),this.dirty++,this.multiplyUvs()},s(e,[{key:"width",get:function(){return this._width},set:function(t){this._width=t,this._refresh()}},{key:"height",get:function(){return this._height},set:function(t){this._height=t,this._refresh()}},{key:"leftWidth",get:function(){return this._leftWidth},set:function(t){this._leftWidth=t,this._refresh()}},{key:"rightWidth",get:function(){return this._rightWidth},set:function(t){this._rightWidth=t,this._refresh()}},{key:"topHeight",get:function(){return this._topHeight},set:function(t){this._topHeight=t,this._refresh()}},{key:"bottomHeight",get:function(){return this._bottomHeight},set:function(t){this._bottomHeight=t,this._refresh()}}]),e}(u.default);r.default=l},{"./Plane":168}],168:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=t("./Mesh"),a=function(t){return t&&t.__esModule?t:{default:t}}(s),u=function(t){function e(r,o,s){n(this,e);var u=i(this,t.call(this,r));return u._ready=!0,u.verticesX=o||10,u.verticesY=s||10,u.drawMode=a.default.DRAW_MODES.TRIANGLES,u.refresh(),u}return o(e,t),e.prototype._refresh=function(){for(var t=this._texture,e=this.verticesX*this.verticesY,r=[],n=[],i=[],o=[],s=this.verticesX-1,a=this.verticesY-1,u=t.width/s,h=t.height/a,l=0;l1&&(l=1);var c=Math.sqrt(n*n+i*i),d=this._texture.height/2;n/=c,i/=c,n*=d,i*=d,o[h]=u.x+n,o[h+1]=u.y+i,o[h+2]=u.x-n,o[h+3]=u.y-i,e=u}},e.prototype.updateTransform=function(){this.autoUpdate&&this.refreshVertices(),this.containerUpdateTransform()},e}(a.default);r.default=u},{"./Mesh":166}],170:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../core"),o=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(i),s=t("../Mesh"),a=function(t){return t&&t.__esModule?t:{default:t}}(s),u=function(){function t(e){n(this,t),this.renderer=e}return t.prototype.render=function(t){var e=this.renderer,r=e.context,n=t.worldTransform,i=e.resolution;e.roundPixels?r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i|0,n.ty*i|0):r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),e.context.globalAlpha=t.worldAlpha,e.setBlendMode(t.blendMode),t.drawMode===a.default.DRAW_MODES.TRIANGLE_MESH?this._renderTriangleMesh(t):this._renderTriangles(t)},t.prototype._renderTriangleMesh=function(t){for(var e=t.vertices.length/2,r=0;r0){var O=S/Math.abs(t.worldTransform.a),M=S/Math.abs(t.worldTransform.d),P=(_+b+x)/3,C=(T+w+E)/3,R=_-P,A=T-C,I=Math.sqrt(R*R+A*A);_=P+R/I*(I+O),T=C+A/I*(I+M),R=b-P,A=w-C,I=Math.sqrt(R*R+A*A),b=P+R/I*(I+O),w=C+A/I*(I+M),R=x-P,A=E-C,I=Math.sqrt(R*R+A*A),x=P+R/I*(I+O),E=C+A/I*(I+M)}i.save(),i.beginPath(),i.moveTo(_,T),i.lineTo(b,w),i.lineTo(x,E),i.closePath(),i.clip();var D=d*g+v*p+f*y-g*p-v*f-d*y,L=_*g+v*x+b*y-g*x-v*b-_*y,N=d*b+_*p+f*x-b*p-_*f-d*x,B=d*g*x+v*b*p+_*f*y-_*g*p-v*f*x-d*b*y,F=T*g+v*E+w*y-g*E-v*w-T*y,k=d*w+T*p+f*E-w*p-T*f-d*E,j=d*g*E+v*w*p+T*f*y-T*g*p-v*f*E-d*w*y;i.transform(L/D,F/D,N/D,k/D,B/D,j/D),i.drawImage(h,0,0,l*u.resolution,c*u.resolution,0,0,l,c),i.restore(),this.renderer.invalidateBlendMode()}},t.prototype.renderMeshFlat=function(t){var e=this.renderer.context,r=t.vertices,n=r.length/2;e.beginPath();for(var i=1;i0&&void 0!==arguments[0]?arguments[0]:1500,o=arguments[1],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16384,a=arguments.length>3&&void 0!==arguments[3]&&arguments[3];n(this,e);var h=i(this,t.call(this));return s>16384&&(s=16384),s>r&&(s=r),h._properties=[!1,!0,!1,!1,!1],h._maxSize=r,h._batchSize=s,h._glBuffers={},h._bufferUpdateIDs=[],h._updateID=0,h.interactiveChildren=!1,h.blendMode=u.BLEND_MODES.NORMAL,h.autoResize=a,h.roundPixels=!0,h.baseTexture=null,h.setProperties(o),h._tint=0,h.tintRgb=new Float32Array(4),h.tint=16777215,h}return o(e,t),e.prototype.setProperties=function(t){t&&(this._properties[0]="vertices"in t||"scale"in t?!!t.vertices||!!t.scale:this._properties[0],this._properties[1]="position"in t?!!t.position:this._properties[1],this._properties[2]="rotation"in t?!!t.rotation:this._properties[2],this._properties[3]="uvs"in t?!!t.uvs:this._properties[3],this._properties[4]="tint"in t||"alpha"in t?!!t.tint||!!t.alpha:this._properties[4])},e.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},e.prototype.renderWebGL=function(t){var e=this;this.visible&&!(this.worldAlpha<=0)&&this.children.length&&this.renderable&&(this.baseTexture||(this.baseTexture=this.children[0]._texture.baseTexture,this.baseTexture.hasLoaded||this.baseTexture.once("update",function(){return e.onChildrenChange(0)})),t.setObjectRenderer(t.plugins.particle),t.plugins.particle.render(this))},e.prototype.onChildrenChange=function(t){for(var e=Math.floor(t/this._batchSize);this._bufferUpdateIDs.lengthr&&(o=r);var s=t._glBuffers[i.CONTEXT_UID];s||(s=t._glBuffers[i.CONTEXT_UID]=this.generateBuffers(t));var a=e[0]._texture.baseTexture;this.renderer.setBlendMode(u.utils.correctBlendMode(t.blendMode,a.premultipliedAlpha));var h=i.gl,l=t.worldTransform.copy(this.tempMatrix);l.prepend(i._activeRenderTarget.projectionMatrix),this.shader.uniforms.projectionMatrix=l.toArray(!0),this.shader.uniforms.uColor=u.utils.premultiplyRgba(t.tintRgb,t.worldAlpha,this.shader.uniforms.uColor,a.premultipliedAlpha),this.shader.uniforms.uSampler=i.bindTexture(a);for(var c=!1,d=0,f=0;dn&&(p=n),f>=s.length){if(!t.autoResize)break;s.push(this._generateOneMoreBuffer(t))}var v=s[f];v.uploadDynamic(e,d,p);var g=t._bufferUpdateIDs[f]||0;c=c||v._updateID0?1:-1})},{}],179:[function(t,e,r){"use strict";Number.isInteger||(Number.isInteger=function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t})},{}],180:[function(t,e,r){"use strict";var n=t("object-assign"),i=function(t){return t&&t.__esModule?t:{default:t}}(n);Object.assign||(Object.assign=i.default)},{"object-assign":6}],181:[function(t,e,r){"use strict";t("./Object.assign"),t("./requestAnimationFrame"),t("./Math.sign"),t("./Number.isInteger"),window.ArrayBuffer||(window.ArrayBuffer=Array),window.Float32Array||(window.Float32Array=Array),window.Uint32Array||(window.Uint32Array=Array),window.Uint16Array||(window.Uint16Array=Array)},{"./Math.sign":178,"./Number.isInteger":179,"./Object.assign":180,"./requestAnimationFrame":182}],182:[function(t,e,r){(function(t){"use strict";if(Date.now&&Date.prototype.getTime||(Date.now=function(){return(new Date).getTime()}),!t.performance||!t.performance.now){var e=Date.now();t.performance||(t.performance={}),t.performance.now=function(){return Date.now()-e}}for(var r=Date.now(),n=["ms","moz","webkit","o"],i=0;i=0;n--)this.add(t.children[n]);return this},t.prototype.destroy=function(){this.ticking&&v.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null,this.limiter=null,this.uploadHookHelper=null},t}();r.default=g},{"../core":65,"./limiters/CountLimiter":186}],184:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function s(t,e){if(e instanceof u.BaseTexture){var r=e.source,n=0===r.width?t.canvas.width:Math.min(t.canvas.width,r.width),i=0===r.height?t.canvas.height:Math.min(t.canvas.height,r.height);return t.ctx.drawImage(r,0,0,n,i,0,0,t.canvas.width,t.canvas.height),!0}return!1}r.__esModule=!0;var a=t("../../core"),u=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(a),h=t("../BasePrepare"),l=function(t){return t&&t.__esModule?t:{default:t}}(h),c=16,d=function(t){function e(r){n(this,e);var o=i(this,t.call(this,r));return o.uploadHookHelper=o,o.canvas=document.createElement("canvas"),o.canvas.width=c,o.canvas.height=c,o.ctx=o.canvas.getContext("2d"),o.registerUploadHook(s),o}return o(e,t),e.prototype.destroy=function(){t.prototype.destroy.call(this),this.ctx=null,this.canvas=null},e}(l.default);r.default=d,u.CanvasRenderer.registerPlugin("prepare",d)},{"../../core":65,"../BasePrepare":183}],185:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./webgl/WebGLPrepare");Object.defineProperty(r,"webgl",{enumerable:!0,get:function(){return n(i).default}});var o=t("./canvas/CanvasPrepare");Object.defineProperty(r,"canvas",{enumerable:!0,get:function(){return n(o).default}});var s=t("./BasePrepare");Object.defineProperty(r,"BasePrepare",{enumerable:!0,get:function(){return n(s).default}});var a=t("./limiters/CountLimiter");Object.defineProperty(r,"CountLimiter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./limiters/TimeLimiter");Object.defineProperty(r,"TimeLimiter",{enumerable:!0,get:function(){return n(u).default}})},{"./BasePrepare":183,"./canvas/CanvasPrepare":184,"./limiters/CountLimiter":186,"./limiters/TimeLimiter":187,"./webgl/WebGLPrepare":188}],186:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxItemsPerFrame=e,this.itemsLeft=0}return t.prototype.beginFrame=function(){this.itemsLeft=this.maxItemsPerFrame},t.prototype.allowedToUpload=function(){return this.itemsLeft-- >0},t}();r.default=i},{}],187:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxMilliseconds=e,this.frameStart=0}return t.prototype.beginFrame=function(){this.frameStart=Date.now()},t.prototype.allowedToUpload=function(){return Date.now()-this.frameStart 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],2:[function(require,module,exports){ +'use strict'; + +module.exports = earcut; +module.exports.default = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, invSize; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 1 / invSize : 0; + } + + earcutLinked(outerNode, triangles, dim, minX, minY, invSize); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, invSize) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, invSize), + maxZ = zOrder(maxTX, maxTY, minX, minY, invSize); + + var p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + + if (n !== ear.prev && n !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && + area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + // look for remaining points in decreasing z-order + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + // look for remaining points in increasing z-order + while (n && n.z <= maxZ) { + if (n !== ear.prev && n !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && + area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize); + earcutLinked(c, triangles, dim, minX, minY, invSize); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, invSize) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) * invSize; + y = 32767 * (y - minY) * invSize; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; + +},{}],3:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @api private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {Mixed} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @api public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @api public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Boolean} exists Only check if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Add a one-time listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Remove the listeners of a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {Mixed} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn + && (!once || listeners.once) + && (!context || listeners.context === context) + ) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {String|Symbol} [event] The event name. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],4:[function(require,module,exports){ +/** + * isMobile.js v0.4.1 + * + * A simple library to detect Apple phones and tablets, + * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone), + * and any kind of seven inch device, via user agent sniffing. + * + * @author: Kai Mallea (kmallea@gmail.com) + * + * @license: http://creativecommons.org/publicdomain/zero/1.0/ + */ +(function (global) { + + var apple_phone = /iPhone/i, + apple_ipod = /iPod/i, + apple_tablet = /iPad/i, + android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i, // Match 'Android' AND 'Mobile' + android_tablet = /Android/i, + amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i, + amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i, + windows_phone = /Windows Phone/i, + windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i, // Match 'Windows' AND 'ARM' + other_blackberry = /BlackBerry/i, + other_blackberry_10 = /BB10/i, + other_opera = /Opera Mini/i, + other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i, + other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i, // Match 'Firefox' AND 'Mobile' + seven_inch = new RegExp( + '(?:' + // Non-capturing group + + 'Nexus 7' + // Nexus 7 + + '|' + // OR + + 'BNTV250' + // B&N Nook Tablet 7 inch + + '|' + // OR + + 'Kindle Fire' + // Kindle Fire + + '|' + // OR + + 'Silk' + // Kindle Fire, Silk Accelerated + + '|' + // OR + + 'GT-P1000' + // Galaxy Tab 7 inch + + ')', // End non-capturing group + + 'i'); // Case-insensitive matching + + var match = function(regex, userAgent) { + return regex.test(userAgent); + }; + + var IsMobileClass = function(userAgent) { + var ua = userAgent || navigator.userAgent; + + // Facebook mobile app's integrated browser adds a bunch of strings that + // match everything. Strip it out if it exists. + var tmp = ua.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + // Twitter mobile app's integrated browser on iPad adds a "Twitter for + // iPhone" string. Same probable happens on other tablet platforms. + // This will confuse detection so strip it out if it exists. + tmp = ua.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + this.apple = { + phone: match(apple_phone, ua), + ipod: match(apple_ipod, ua), + tablet: !match(apple_phone, ua) && match(apple_tablet, ua), + device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua) + }; + this.amazon = { + phone: match(amazon_phone, ua), + tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) + }; + this.android = { + phone: match(amazon_phone, ua) || match(android_phone, ua), + tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua) + }; + this.windows = { + phone: match(windows_phone, ua), + tablet: match(windows_tablet, ua), + device: match(windows_phone, ua) || match(windows_tablet, ua) + }; + this.other = { + blackberry: match(other_blackberry, ua), + blackberry10: match(other_blackberry_10, ua), + opera: match(other_opera, ua), + firefox: match(other_firefox, ua), + chrome: match(other_chrome, ua), + device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua) + }; + this.seven_inch = match(seven_inch, ua); + this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch; + + // excludes 'other' devices and ipods, targeting touchscreen phones + this.phone = this.apple.phone || this.android.phone || this.windows.phone; + + // excludes 7 inch devices, classifying as phone or tablet is left to the user + this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet; + + if (typeof window === 'undefined') { + return this; + } + }; + + var instantiate = function() { + var IM = new IsMobileClass(); + IM.Class = IsMobileClass; + return IM; + }; + + if (typeof module !== 'undefined' && module.exports && typeof window === 'undefined') { + //node + module.exports = IsMobileClass; + } else if (typeof module !== 'undefined' && module.exports && typeof window !== 'undefined') { + //browserify + module.exports = instantiate(); + } else if (typeof define === 'function' && define.amd) { + //AMD + define('isMobile', [], global.isMobile = instantiate()); + } else { + global.isMobile = instantiate(); + } + +})(this); + +},{}],5:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + +var MiniSignalBinding = (function () { + function MiniSignalBinding(fn, once, thisArg) { + if (once === undefined) once = false; + + _classCallCheck(this, MiniSignalBinding); + + this._fn = fn; + this._once = once; + this._thisArg = thisArg; + this._next = this._prev = this._owner = null; + } + + _createClass(MiniSignalBinding, [{ + key: 'detach', + value: function detach() { + if (this._owner === null) return false; + this._owner.detach(this); + return true; + } + }]); + + return MiniSignalBinding; +})(); + +function _addMiniSignalBinding(self, node) { + if (!self._head) { + self._head = node; + self._tail = node; + } else { + self._tail._next = node; + node._prev = self._tail; + self._tail = node; + } + + node._owner = self; + + return node; +} + +var MiniSignal = (function () { + function MiniSignal() { + _classCallCheck(this, MiniSignal); + + this._head = this._tail = undefined; + } + + _createClass(MiniSignal, [{ + key: 'handlers', + value: function handlers() { + var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; + + var node = this._head; + + if (exists) return !!node; + + var ee = []; + + while (node) { + ee.push(node); + node = node._next; + } + + return ee; + } + }, { + key: 'has', + value: function has(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.'); + } + + return node._owner === this; + } + }, { + key: 'dispatch', + value: function dispatch() { + var node = this._head; + + if (!node) return false; + + while (node) { + if (node._once) this.detach(node); + node._fn.apply(node._thisArg, arguments); + node = node._next; + } + + return true; + } + }, { + key: 'add', + value: function add(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#add(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg)); + } + }, { + key: 'once', + value: function once(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#once(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg)); + } + }, { + key: 'detach', + value: function detach(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.'); + } + if (node._owner !== this) return this; + + if (node._prev) node._prev._next = node._next; + if (node._next) node._next._prev = node._prev; + + if (node === this._head) { + this._head = node._next; + if (node._next === null) { + this._tail = null; + } + } else if (node === this._tail) { + this._tail = node._prev; + this._tail._next = null; + } + + node._owner = null; + return this; + } + }, { + key: 'detachAll', + value: function detachAll() { + var node = this._head; + if (!node) return this; + + this._head = this._tail = null; + + while (node) { + node._owner = null; + node = node._next; + } + return this; + } + }]); + + return MiniSignal; +})(); + +MiniSignal.MiniSignalBinding = MiniSignalBinding; + +exports['default'] = MiniSignal; +module.exports = exports['default']; + +},{}],6:[function(require,module,exports){ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],7:[function(require,module,exports){ +'use strict' + +module.exports = function parseURI (str, opts) { + opts = opts || {} + + var o = { + key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], + q: { + name: 'queryKey', + parser: /(?:^|&)([^&=]*)=?([^&]*)/g + }, + parser: { + strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, + loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ + } + } + + var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str) + var uri = {} + var i = 14 + + while (i--) uri[o.key[i]] = m[i] || '' + + uri[o.q.name] = {} + uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { + if ($1) uri[o.q.name][$1] = $2 + }) + + return uri +} + +},{}],8:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) + +},{"_process":26}],9:[function(require,module,exports){ +var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); + +/** + * Helper class to create a webGL buffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ +var Buffer = function(gl, type, data, drawType) +{ + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The WebGL buffer, created upon instantiation + * + * @member {WebGLBuffer} + */ + this.buffer = gl.createBuffer(); + + /** + * The type of the buffer + * + * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} + */ + this.type = type || gl.ARRAY_BUFFER; + + /** + * The draw type of the buffer + * + * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ + this.drawType = drawType || gl.STATIC_DRAW; + + /** + * The data in the buffer, as a typed array + * + * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} + */ + this.data = EMPTY_ARRAY_BUFFER; + + if(data) + { + this.upload(data); + } + + this._updateID = 0; +}; + +/** + * Uploads the buffer to the GPU + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload + * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract + * @param dontBind {Boolean} whether to bind the buffer before uploading it + */ +Buffer.prototype.upload = function(data, offset, dontBind) +{ + // todo - needed? + if(!dontBind) this.bind(); + + var gl = this.gl; + + data = data || this.data; + offset = offset || 0; + + if(this.data.byteLength >= data.byteLength) + { + gl.bufferSubData(this.type, offset, data); + } + else + { + gl.bufferData(this.type, data, this.drawType); + } + + this.data = data; +}; +/** + * Binds the buffer + * + */ +Buffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindBuffer(this.type, this.buffer); +}; + +Buffer.createVertexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); +}; + +Buffer.createIndexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); +}; + +Buffer.create = function(gl, type, data, drawType) +{ + return new Buffer(gl, type, data, drawType); +}; + +/** + * Destroys the buffer + * + */ +Buffer.prototype.destroy = function(){ + this.gl.deleteBuffer(this.buffer); +}; + +module.exports = Buffer; + +},{}],10:[function(require,module,exports){ + +var Texture = require('./GLTexture'); + +/** + * Helper class to create a webGL Framebuffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + */ +var Framebuffer = function(gl, width, height) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The frame buffer + * + * @member {WebGLFramebuffer} + */ + this.framebuffer = gl.createFramebuffer(); + + /** + * The stencil buffer + * + * @member {WebGLRenderbuffer} + */ + this.stencil = null; + + /** + * The stencil buffer + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The width of the drawing area of the buffer + * + * @member {Number} + */ + this.width = width || 100; + /** + * The height of the drawing area of the buffer + * + * @member {Number} + */ + this.height = height || 100; +}; + +/** + * Adds a texture to the frame buffer + * @param texture {PIXI.glCore.GLTexture} + */ +Framebuffer.prototype.enableTexture = function(texture) +{ + var gl = this.gl; + + this.texture = texture || new Texture(gl); + + this.texture.bind(); + + //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + this.bind(); + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); +}; + +/** + * Initialises the stencil buffer + */ +Framebuffer.prototype.enableStencil = function() +{ + if(this.stencil)return; + + var gl = this.gl; + + this.stencil = gl.createRenderbuffer(); + + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + + // TODO.. this is depth AND stencil? + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width , this.height ); + + +}; + +/** + * Erases the drawing area and fills it with a colour + * @param r {Number} the red value of the clearing colour + * @param g {Number} the green value of the clearing colour + * @param b {Number} the blue value of the clearing colour + * @param a {Number} the alpha value of the clearing colour + */ +Framebuffer.prototype.clear = function( r, g, b, a ) +{ + this.bind(); + + var gl = this.gl; + + gl.clearColor(r, g, b, a); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); +}; + +/** + * Binds the frame buffer to the WebGL context + */ +Framebuffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); +}; + +/** + * Unbinds the frame buffer to the WebGL context + */ +Framebuffer.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, null ); +}; +/** + * Resizes the drawing area of the buffer to the given width and height + * @param width {Number} the new width + * @param height {Number} the new height + */ +Framebuffer.prototype.resize = function(width, height) +{ + var gl = this.gl; + + this.width = width; + this.height = height; + + if ( this.texture ) + { + this.texture.uploadData(null, width, height); + } + + if ( this.stencil ) + { + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + } +}; + +/** + * Destroys this buffer + */ +Framebuffer.prototype.destroy = function() +{ + var gl = this.gl; + + //TODO + if(this.texture) + { + this.texture.destroy(); + } + + gl.deleteFramebuffer(this.framebuffer); + + this.gl = null; + + this.stencil = null; + this.texture = null; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createRGBA = function(gl, width, height, data) +{ + var texture = Texture.fromData(gl, null, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + //fbo.enableStencil(); // get this back on soon! + + //fbo.enableStencil(); // get this back on soon! + + fbo.unbind(); + + return fbo; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createFloat32 = function(gl, width, height, data) +{ + // create a new texture.. + var texture = new Texture.fromData(gl, data, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +module.exports = Framebuffer; + +},{"./GLTexture":12}],11:[function(require,module,exports){ + +var compileProgram = require('./shader/compileProgram'), + extractAttributes = require('./shader/extractAttributes'), + extractUniforms = require('./shader/extractUniforms'), + setPrecision = require('./shader/setPrecision'), + generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + +/** + * Helper class to create a webGL Shader + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + */ +var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + if(precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } + + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); + + this.uniformData = extractUniforms(gl, this.program); + + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + +}; +/** + * Uses this shader + * + * @return {PIXI.glCore.GLShader} Returns itself. + */ +Shader.prototype.bind = function() +{ + this.gl.useProgram(this.program); + return this; +}; + +/** + * Destroys this shader + * TODO + */ +Shader.prototype.destroy = function() +{ + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + + var gl = this.gl; + gl.deleteProgram(this.program); +}; + + +module.exports = Shader; + +},{"./shader/compileProgram":17,"./shader/extractAttributes":19,"./shader/extractUniforms":20,"./shader/generateUniformAccessObject":21,"./shader/setPrecision":25}],12:[function(require,module,exports){ + +/** + * Helper class to create a WebGL Texture + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL context + * @param width {number} the width of the texture + * @param height {number} the height of the texture + * @param format {number} the pixel format of the texture. defaults to gl.RGBA + * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE + */ +var Texture = function(gl, width, height, format, type) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); + + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; + + + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; + + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; + + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + + +}; + +/** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ +Texture.prototype.upload = function(source) +{ + this.bind(); + + var gl = this.gl; + + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + var newWidth = source.videoWidth || source.width; + var newHeight = source.videoHeight || source.height; + + if(newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } + + // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + +}; + +var FLOATING_POINT_AVAILABLE = false; + +/** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.prototype.uploadData = function(data, width, height) +{ + this.bind(); + + var gl = this.gl; + + + if(data instanceof Float32Array) + { + if(!FLOATING_POINT_AVAILABLE) + { + var ext = gl.getExtension("OES_texture_float"); + + if(ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } + + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } + + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + + if(width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } + + this.width = width; + this.height = height; + + +// texSubImage2D +}; + +/** + * Binds the texture + * @param location + */ +Texture.prototype.bind = function(location) +{ + var gl = this.gl; + + if(location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } + + gl.bindTexture(gl.TEXTURE_2D, this.texture); +}; + +/** + * Unbinds the texture + */ +Texture.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, null); +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.minFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + if(this.mipmap) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.magFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); +}; + +/** + * Enables mipmapping + */ +Texture.prototype.enableMipmap = function() +{ + var gl = this.gl; + + this.bind(); + + this.mipmap = true; + + gl.generateMipmap(gl.TEXTURE_2D); +}; + +/** + * Enables linear filtering + */ +Texture.prototype.enableLinearScaling = function() +{ + this.minFilter(true); + this.magFilter(true); +}; + +/** + * Enables nearest neighbour interpolation + */ +Texture.prototype.enableNearestScaling = function() +{ + this.minFilter(false); + this.magFilter(false); +}; + +/** + * Enables clamping on the texture so WebGL will not repeat it + */ +Texture.prototype.enableWrapClamp = function() +{ + var gl = this.gl; + + this.bind(); + + 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); +}; + +/** + * Enable tiling on the texture + */ +Texture.prototype.enableWrapRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); +}; + +Texture.prototype.enableWrapMirrorRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); +}; + + +/** + * Destroys this texture + */ +Texture.prototype.destroy = function() +{ + var gl = this.gl; + //TODO + gl.deleteTexture(this.texture); +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ +Texture.fromSource = function(gl, source, premultiplyAlpha) +{ + var texture = new Texture(gl); + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); + + return texture; +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.fromData = function(gl, data, width, height) +{ + //console.log(data, width, height); + var texture = new Texture(gl); + texture.uploadData(data, width, height); + + return texture; +}; + + +module.exports = Texture; + +},{}],13:[function(require,module,exports){ + +// state object// +var setVertexAttribArrays = require( './setVertexAttribArrays' ); + +/** + * Helper class to work with WebGL VertexArrayObjects (vaos) + * Only works if WebGL extensions are enabled (they usually are) + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function VertexArrayObject(gl, state) +{ + this.nativeVaoExtension = null; + + if(!VertexArrayObject.FORCE_NATIVE) + { + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + this.nativeState = state; + + if(this.nativeVaoExtension) + { + this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + + var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + // VAO - overwrite the state.. + this.nativeState = { + tempAttribState: new Array(maxAttribs), + attribState: new Array(maxAttribs) + }; + } + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of attributes + * + * @member {Array} + */ + this.attributes = []; + + /** + * @member {PIXI.glCore.GLBuffer} + */ + this.indexBuffer = null; + + /** + * A boolean flag + * + * @member {Boolean} + */ + this.dirty = false; +} + +VertexArrayObject.prototype.constructor = VertexArrayObject; +module.exports = VertexArrayObject; + +/** +* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) +* If you find on older devices that things have gone a bit weird then set this to true. +*/ +/** + * Lets the VAO know if you should use the WebGL extension or the native methods. + * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) + * If you find on older devices that things have gone a bit weird then set this to true. + * @static + * @property {Boolean} FORCE_NATIVE + */ +VertexArrayObject.FORCE_NATIVE = false; + +/** + * Binds the buffer + */ +VertexArrayObject.prototype.bind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + + if(this.dirty) + { + this.dirty = false; + this.activate(); + return this; + } + if (this.indexBuffer) + { + this.indexBuffer.bind(); + } + } + else + { + this.activate(); + } + + return this; +}; + +/** + * Unbinds the buffer + */ +VertexArrayObject.prototype.unbind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + return this; +}; + +/** + * Uses this vao + */ +VertexArrayObject.prototype.activate = function() +{ + + var gl = this.gl; + var lastBuffer = null; + + for (var i = 0; i < this.attributes.length; i++) + { + var attrib = this.attributes[i]; + + if(lastBuffer !== attrib.buffer) + { + attrib.buffer.bind(); + lastBuffer = attrib.buffer; + } + + gl.vertexAttribPointer(attrib.attribute.location, + attrib.attribute.size, + attrib.type || gl.FLOAT, + attrib.normalized || false, + attrib.stride || 0, + attrib.start || 0); + } + + setVertexAttribArrays(gl, this.attributes, this.nativeState); + + if(this.indexBuffer) + { + this.indexBuffer.bind(); + } + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + * @param attribute {*} + * @param type {String} + * @param normalized {Boolean} + * @param stride {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start) +{ + this.attributes.push({ + buffer: buffer, + attribute: attribute, + + location: attribute.location, + type: type || this.gl.FLOAT, + normalized: normalized || false, + stride: stride || 0, + start: start || 0 + }); + + this.dirty = true; + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + */ +VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) +{ + this.indexBuffer = buffer; + + this.dirty = true; + + return this; +}; + +/** + * Unbinds this vao and disables it + */ +VertexArrayObject.prototype.clear = function() +{ + // var gl = this.gl; + + // TODO - should this function unbind after clear? + // for now, no but lets see what happens in the real world! + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + } + + this.attributes.length = 0; + this.indexBuffer = null; + + return this; +}; + +/** + * @param type {Number} + * @param size {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.draw = function(type, size, start) +{ + var gl = this.gl; + + if(this.indexBuffer) + { + gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + } + else + { + // TODO need a better way to calculate size.. + gl.drawArrays(type, start, size || this.getSize()); + } + + return this; +}; + +/** + * Destroy this vao + */ +VertexArrayObject.prototype.destroy = function() +{ + // lose references + this.gl = null; + this.indexBuffer = null; + this.attributes = null; + this.nativeState = null; + + if(this.nativeVao) + { + this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); + } + + this.nativeVaoExtension = null; + this.nativeVao = null; +}; + +VertexArrayObject.prototype.getSize = function() +{ + var attrib = this.attributes[0]; + return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); +}; + +},{"./setVertexAttribArrays":16}],14:[function(require,module,exports){ + +/** + * Helper class to create a webGL Context + * + * @class + * @memberof PIXI.glCore + * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from + * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * @return {WebGLRenderingContext} the WebGL context + */ +var createContext = function(canvas, options) +{ + var gl = canvas.getContext('webgl', options) || + canvas.getContext('experimental-webgl', options); + + if (!gl) + { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + return gl; +}; + +module.exports = createContext; + +},{}],15:[function(require,module,exports){ +var gl = { + createContext: require('./createContext'), + setVertexAttribArrays: require('./setVertexAttribArrays'), + GLBuffer: require('./GLBuffer'), + GLFramebuffer: require('./GLFramebuffer'), + GLShader: require('./GLShader'), + GLTexture: require('./GLTexture'), + VertexArrayObject: require('./VertexArrayObject'), + shader: require('./shader') +}; + +// Export for Node-compatible environments +if (typeof module !== 'undefined' && module.exports) +{ + // Export the module + module.exports = gl; +} + +// Add to the browser window pixi.gl +if (typeof window !== 'undefined') +{ + // add the window object + window.PIXI = window.PIXI || {}; + window.PIXI.glCore = gl; +} + +},{"./GLBuffer":9,"./GLFramebuffer":10,"./GLShader":11,"./GLTexture":12,"./VertexArrayObject":13,"./createContext":14,"./setVertexAttribArrays":16,"./shader":22}],16:[function(require,module,exports){ +// var GL_MAP = {}; + +/** + * @param gl {WebGLRenderingContext} The current WebGL context + * @param attribs {*} + * @param state {*} + */ +var setVertexAttribArrays = function (gl, attribs, state) +{ + var i; + if(state) + { + var tempAttribState = state.tempAttribState, + attribState = state.attribState; + + for (i = 0; i < tempAttribState.length; i++) + { + tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + tempAttribState[attribs[i].attribute.location] = true; + } + + for (i = 0; i < attribState.length; i++) + { + if (attribState[i] !== tempAttribState[i]) + { + attribState[i] = tempAttribState[i]; + + if (state.attribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } + + } + else + { + for (i = 0; i < attribs.length; i++) + { + var attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); + } + } +}; + +module.exports = setVertexAttribArrays; + +},{}],17:[function(require,module,exports){ + +/** + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations + * @return {WebGLProgram} the shader program + */ +var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +{ + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + + var program = gl.createProgram(); + + gl.attachShader(program, glVertShader); + gl.attachShader(program, glFragShader); + + // optionally, set the attributes manually for the program rather than letting WebGL decide.. + if(attributeLocations) + { + for(var i in attributeLocations) + { + gl.bindAttribLocation(program, attributeLocations[i], i); + } + } + + + gl.linkProgram(program); + + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + console.error('Pixi.js Error: Could not initialize shader.'); + console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); + console.error('gl.getError()', gl.getError()); + + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') + { + console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + + gl.deleteProgram(program); + program = null; + } + + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + + return program; +}; + +/** + * @private + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @return {WebGLShader} the shader + */ +var compileShader = function (gl, type, src) +{ + var shader = gl.createShader(type); + + gl.shaderSource(shader, src); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + console.log(gl.getShaderInfoLog(shader)); + return null; + } + + return shader; +}; + +module.exports = compileProgram; + +},{}],18:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} Type of value + * @param size {Number} + */ +var defaultValue = function(type, size) +{ + switch (type) + { + case 'float': + return 0; + + case 'vec2': + return new Float32Array(2 * size); + + case 'vec3': + return new Float32Array(3 * size); + + case 'vec4': + return new Float32Array(4 * size); + + case 'int': + case 'sampler2D': + return 0; + + case 'ivec2': + return new Int32Array(2 * size); + + case 'ivec3': + return new Int32Array(3 * size); + + case 'ivec4': + return new Int32Array(4 * size); + + case 'bool': + return false; + + case 'bvec2': + + return booleanArray( 2 * size); + + case 'bvec3': + return booleanArray(3 * size); + + case 'bvec4': + return booleanArray(4 * size); + + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } +}; + +var booleanArray = function(size) +{ + var array = new Array(size); + + for (var i = 0; i < array.length; i++) + { + array[i] = false; + } + + return array; +}; + +module.exports = defaultValue; + +},{}],19:[function(require,module,exports){ + +var mapType = require('./mapType'); +var mapSize = require('./mapSize'); + +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the attributes from + * @return attributes {Object} + */ +var extractAttributes = function(gl, program) +{ + var attributes = {}; + + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + + for (var i = 0; i < totalAttributes; i++) + { + var attribData = gl.getActiveAttrib(program, i); + var type = mapType(gl, attribData.type); + + attributes[attribData.name] = { + type:type, + size:mapSize(type), + location:gl.getAttribLocation(program, attribData.name), + //TODO - make an attribute object + pointer: pointer + }; + } + + return attributes; +}; + +var pointer = function(type, normalized, stride, start){ + // console.log(this.location) + gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +}; + +module.exports = extractAttributes; + +},{"./mapSize":23,"./mapType":24}],20:[function(require,module,exports){ +var mapType = require('./mapType'); +var defaultValue = require('./defaultValue'); + +/** + * Extracts the uniforms + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the uniforms from + * @return uniforms {Object} + */ +var extractUniforms = function(gl, program) +{ + var uniforms = {}; + + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + + for (var i = 0; i < totalUniforms; i++) + { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]/, ""); + var type = mapType(gl, uniformData.type ); + + uniforms[name] = { + type:type, + size:uniformData.size, + location:gl.getUniformLocation(program, name), + value:defaultValue(type, uniformData.size) + }; + } + + return uniforms; +}; + +module.exports = extractUniforms; + +},{"./defaultValue":18,"./mapType":24}],21:[function(require,module,exports){ +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param uniforms {Array} @mat ? + * @return attributes {Object} + */ +var generateUniformAccessObject = function(gl, uniformData) +{ + // this is the object we will be sending back. + // an object hierachy will be created for structs + var uniforms = {data:{}}; + + uniforms.gl = gl; + + var uniformKeys= Object.keys(uniformData); + + for (var i = 0; i < uniformKeys.length; i++) + { + var fullName = uniformKeys[i]; + + var nameTokens = fullName.split('.'); + var name = nameTokens[nameTokens.length - 1]; + + + var uniformGroup = getUniformGroup(nameTokens, uniforms); + + var uniform = uniformData[fullName]; + uniformGroup.data[name] = uniform; + + uniformGroup.gl = gl; + + Object.defineProperty(uniformGroup, name, { + get: generateGetter(name), + set: generateSetter(name, uniform) + }); + } + + return uniforms; +}; + +var generateGetter = function(name) +{ + return function() { + return this.data[name].value; + }; +}; + +var GLSL_SINGLE_SETTERS = { + float: function setSingleFloat(gl, location, value) { gl.uniform1f(location, value); }, + vec2: function setSingleVec2(gl, location, value) { gl.uniform2f(location, value[0], value[1]); }, + vec3: function setSingleVec3(gl, location, value) { gl.uniform3f(location, value[0], value[1], value[2]); }, + vec4: function setSingleVec4(gl, location, value) { gl.uniform4f(location, value[0], value[1], value[2], value[3]); }, + + int: function setSingleInt(gl, location, value) { gl.uniform1i(location, value); }, + ivec2: function setSingleIvec2(gl, location, value) { gl.uniform2i(location, value[0], value[1]); }, + ivec3: function setSingleIvec3(gl, location, value) { gl.uniform3i(location, value[0], value[1], value[2]); }, + ivec4: function setSingleIvec4(gl, location, value) { gl.uniform4i(location, value[0], value[1], value[2], value[3]); }, + + bool: function setSingleBool(gl, location, value) { gl.uniform1i(location, value); }, + bvec2: function setSingleBvec2(gl, location, value) { gl.uniform2i(location, value[0], value[1]); }, + bvec3: function setSingleBvec3(gl, location, value) { gl.uniform3i(location, value[0], value[1], value[2]); }, + bvec4: function setSingleBvec4(gl, location, value) { gl.uniform4i(location, value[0], value[1], value[2], value[3]); }, + + mat2: function setSingleMat2(gl, location, value) { gl.uniformMatrix2fv(location, false, value); }, + mat3: function setSingleMat3(gl, location, value) { gl.uniformMatrix3fv(location, false, value); }, + mat4: function setSingleMat4(gl, location, value) { gl.uniformMatrix4fv(location, false, value); }, + + sampler2D: function setSingleSampler2D(gl, location, value) { gl.uniform1i(location, value); }, +}; + +var GLSL_ARRAY_SETTERS = { + float: function setFloatArray(gl, location, value) { gl.uniform1fv(location, value); }, + vec2: function setVec2Array(gl, location, value) { gl.uniform2fv(location, value); }, + vec3: function setVec3Array(gl, location, value) { gl.uniform3fv(location, value); }, + vec4: function setVec4Array(gl, location, value) { gl.uniform4fv(location, value); }, + int: function setIntArray(gl, location, value) { gl.uniform1iv(location, value); }, + ivec2: function setIvec2Array(gl, location, value) { gl.uniform2iv(location, value); }, + ivec3: function setIvec3Array(gl, location, value) { gl.uniform3iv(location, value); }, + ivec4: function setIvec4Array(gl, location, value) { gl.uniform4iv(location, value); }, + bool: function setBoolArray(gl, location, value) { gl.uniform1iv(location, value); }, + bvec2: function setBvec2Array(gl, location, value) { gl.uniform2iv(location, value); }, + bvec3: function setBvec3Array(gl, location, value) { gl.uniform3iv(location, value); }, + bvec4: function setBvec4Array(gl, location, value) { gl.uniform4iv(location, value); }, + sampler2D: function setSampler2DArray(gl, location, value) { gl.uniform1iv(location, value); }, +}; + +function generateSetter(name, uniform) +{ + return function(value) { + this.data[name].value = value; + var location = this.data[name].location; + if (uniform.size === 1) + { + GLSL_SINGLE_SETTERS[uniform.type](this.gl, location, value); + } + else + { + // glslSetArray(gl, location, type, value) { + GLSL_ARRAY_SETTERS[uniform.type](this.gl, location, value); + } + }; +} + +function getUniformGroup(nameTokens, uniform) +{ + var cur = uniform; + + for (var i = 0; i < nameTokens.length - 1; i++) + { + var o = cur[nameTokens[i]] || {data:{}}; + cur[nameTokens[i]] = o; + cur = o; + } + + return cur; +} + + +module.exports = generateUniformAccessObject; + +},{}],22:[function(require,module,exports){ +module.exports = { + compileProgram: require('./compileProgram'), + defaultValue: require('./defaultValue'), + extractAttributes: require('./extractAttributes'), + extractUniforms: require('./extractUniforms'), + generateUniformAccessObject: require('./generateUniformAccessObject'), + setPrecision: require('./setPrecision'), + mapSize: require('./mapSize'), + mapType: require('./mapType') +}; +},{"./compileProgram":17,"./defaultValue":18,"./extractAttributes":19,"./extractUniforms":20,"./generateUniformAccessObject":21,"./mapSize":23,"./mapType":24,"./setPrecision":25}],23:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} + * @return {Number} + */ +var mapSize = function(type) +{ + return GLSL_TO_SIZE[type]; +}; + + +var GLSL_TO_SIZE = { + 'float': 1, + 'vec2': 2, + 'vec3': 3, + 'vec4': 4, + + 'int': 1, + 'ivec2': 2, + 'ivec3': 3, + 'ivec4': 4, + + 'bool': 1, + 'bvec2': 2, + 'bvec3': 3, + 'bvec4': 4, + + 'mat2': 4, + 'mat3': 9, + 'mat4': 16, + + 'sampler2D': 1 +}; + +module.exports = mapSize; + +},{}],24:[function(require,module,exports){ + + +var mapType = function(gl, type) +{ + if(!GL_TABLE) + { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + + GL_TABLE = {}; + + for(var i = 0; i < typeNames.length; ++i) + { + var tn = typeNames[i]; + GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + } + } + + return GL_TABLE[type]; +}; + +var GL_TABLE = null; + +var GL_TO_GLSL_TYPES = { + 'FLOAT': 'float', + 'FLOAT_VEC2': 'vec2', + 'FLOAT_VEC3': 'vec3', + 'FLOAT_VEC4': 'vec4', + + 'INT': 'int', + 'INT_VEC2': 'ivec2', + 'INT_VEC3': 'ivec3', + 'INT_VEC4': 'ivec4', + + 'BOOL': 'bool', + 'BOOL_VEC2': 'bvec2', + 'BOOL_VEC3': 'bvec3', + 'BOOL_VEC4': 'bvec4', + + 'FLOAT_MAT2': 'mat2', + 'FLOAT_MAT3': 'mat3', + 'FLOAT_MAT4': 'mat4', + + 'SAMPLER_2D': 'sampler2D' +}; + +module.exports = mapType; + +},{}],25:[function(require,module,exports){ +/** + * Sets the float precision on the shader. If the precision is already present this function will do nothing + * @param {string} src the shader source + * @param {string} precision The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + * + * @return {string} modified shader source + */ +var setPrecision = function(src, precision) +{ + if(src.substring(0, 9) !== 'precision') + { + return 'precision ' + precision + ' float;\n' + src; + } + + return src; +}; + +module.exports = setPrecision; + +},{}],26:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],27:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],28:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],29:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],30:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":28,"./encode":29}],31:[function(require,module,exports){ +'use strict' + +/** + * Remove a range of items from an array + * + * @function removeItems + * @param {Array<*>} arr The target array + * @param {number} startIdx The index to begin removing from (inclusive) + * @param {number} removeCount How many items to remove + */ +module.exports = function removeItems(arr, startIdx, removeCount) +{ + var i, length = arr.length + + if (startIdx >= length || removeCount === 0) { + return + } + + removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount) + + var len = length - removeCount + + for (i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount] + } + + arr.length = len +} + +},{}],32:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _async = require('./async'); + +var async = _interopRequireWildcard(_async); + +var _Resource = require('./Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// some constants +var MAX_PROGRESS = 100; +var rgxExtractUrlHash = /(#[\w-]+)?$/; + +/** + * Manages the state and loading of multiple resources to load. + * + * @class + */ + +var Loader = function () { + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader() { + var _this = this; + + var baseUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var concurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; + + _classCallCheck(this, Loader); + + /** + * The base url for all resources loaded by this loader. + * + * @member {string} + */ + this.baseUrl = baseUrl; + + /** + * The progress percent of the loader going through the queue. + * + * @member {number} + */ + this.progress = 0; + + /** + * Loading state of the loader, true if it is currently loading resources. + * + * @member {boolean} + */ + this.loading = false; + + /** + * A querystring to append to every URL added to the loader. + * + * This should be a valid query string *without* the question-mark (`?`). The loader will + * also *not* escape values for you. Make sure to escape your parameters with + * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. + * + * @example + * const loader = new Loader(); + * + * loader.defaultQueryString = 'user=me&password=secret'; + * + * // This will request 'image.png?user=me&password=secret' + * loader.add('image.png').load(); + * + * loader.reset(); + * + * // This will request 'image.png?v=1&user=me&password=secret' + * loader.add('iamge.png?v=1').load(); + */ + this.defaultQueryString = ''; + + /** + * The middleware to run before loading each resource. + * + * @member {function[]} + */ + this._beforeMiddleware = []; + + /** + * The middleware to run after loading each resource. + * + * @member {function[]} + */ + this._afterMiddleware = []; + + /** + * The tracks the resources we are currently completing parsing for. + * + * @member {Resource[]} + */ + this._resourcesParsing = []; + + /** + * The `_loadResource` function bound with this object context. + * + * @private + * @member {function} + * @param {Resource} r - The resource to load + * @param {Function} d - The dequeue function + * @return {undefined} + */ + this._boundLoadResource = function (r, d) { + return _this._loadResource(r, d); + }; + + /** + * The resources waiting to be loaded. + * + * @private + * @member {Resource[]} + */ + this._queue = async.queue(this._boundLoadResource, concurrency); + + this._queue.pause(); + + /** + * All the resources for this loader keyed by name. + * + * @member {object} + */ + this.resources = {}; + + /** + * Dispatched once per loaded or errored resource. + * + * The callback looks like {@link Loader.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once per errored resource. + * + * The callback looks like {@link Loader.OnErrorSignal}. + * + * @member {Signal} + */ + this.onError = new _miniSignals2.default(); + + /** + * Dispatched once per loaded resource. + * + * The callback looks like {@link Loader.OnLoadSignal}. + * + * @member {Signal} + */ + this.onLoad = new _miniSignals2.default(); + + /** + * Dispatched when the loader begins to process the queue. + * + * The callback looks like {@link Loader.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched when the queued resources all load. + * + * The callback looks like {@link Loader.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * When the progress changes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnProgressSignal + * @param {Loader} loader - The loader the progress is advancing on. + * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance. + */ + + /** + * When an error occurrs the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnErrorSignal + * @param {Loader} loader - The loader the error happened in. + * @param {Resource} resource - The resource that caused the error. + */ + + /** + * When a load completes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnLoadSignal + * @param {Loader} loader - The loader that laoded the resource. + * @param {Resource} resource - The resource that has completed loading. + */ + + /** + * When the loader starts loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnStartSignal + * @param {Loader} loader - The loader that has started loading resources. + */ + + /** + * When the loader completes loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnCompleteSignal + * @param {Loader} loader - The loader that has finished loading resources. + */ + } + + /** + * Adds a resource (or multiple resources) to the loader queue. + * + * This function can take a wide variety of different parameters. The only thing that is always + * required the url to load. All the following will work: + * + * ```js + * loader + * // normal param syntax + * .add('key', 'http://...', function () {}) + * .add('http://...', function () {}) + * .add('http://...') + * + * // object syntax + * .add({ + * name: 'key2', + * url: 'http://...' + * }, function () {}) + * .add({ + * url: 'http://...' + * }, function () {}) + * .add({ + * name: 'key3', + * url: 'http://...' + * onComplete: function () {} + * }) + * .add({ + * url: 'https://...', + * onComplete: function () {}, + * crossOrigin: true + * }) + * + * // you can also pass an array of objects or urls or both + * .add([ + * { name: 'key4', url: 'http://...', onComplete: function () {} }, + * { url: 'http://...', onComplete: function () {} }, + * 'http://...' + * ]) + * + * // and you can use both params and options + * .add('key', 'http://...', { crossOrigin: true }, function () {}) + * .add('http://...', { crossOrigin: true }, function () {}); + * ``` + * + * @param {string} [name] - The name of the resource to load, if not passed the url is used. + * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @param {object} [options] - The options for the load. + * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should + * the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @param {function} [cb] - Function to call when this specific resource completes loading. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.add = function add(name, url, options, cb) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + + return this; + } + + // if an object is passed instead of params + if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') { + cb = url || name.callback || name.onComplete; + options = name; + url = name.url; + name = name.name || name.key || name.url; + } + + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + cb = options; + options = url; + url = name; + } + + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + cb = options; + options = null; + } + + // if loading already you can only add resources that have a parent. + if (this.loading && (!options || !options.parentResource)) { + throw new Error('Cannot add resources while the loader is running.'); + } + + // check if resource already exists. + if (this.resources[name]) { + throw new Error('Resource named "' + name + '" already exists.'); + } + + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + + // create the store the resource + this.resources[name] = new _Resource2.default(name, url, options); + + if (typeof cb === 'function') { + this.resources[name].onAfterMiddleware.once(cb); + } + + // if actively loading, make sure to adjust progress chunks for that parent and its children + if (this.loading) { + var parent = options.parentResource; + var incompleteChildren = []; + + for (var _i = 0; _i < parent.children.length; ++_i) { + if (!parent.children[_i].isComplete) { + incompleteChildren.push(parent.children[_i]); + } + } + + var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent + var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child + + parent.children.push(this.resources[name]); + parent.progressChunk = eachChunk; + + for (var _i2 = 0; _i2 < incompleteChildren.length; ++_i2) { + incompleteChildren[_i2].progressChunk = eachChunk; + } + + this.resources[name].progressChunk = eachChunk; + } + + // add the resource to the queue + this._queue.push(this.resources[name]); + + return this; + }; + + /** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * + * @method before + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.pre = function pre(fn) { + this._beforeMiddleware.push(fn); + + return this; + }; + + /** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * + * @alias use + * @method after + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.use = function use(fn) { + this._afterMiddleware.push(fn); + + return this; + }; + + /** + * Resets the queue of the loader to prepare for a new load. + * + * @return {Loader} Returns itself. + */ + + + Loader.prototype.reset = function reset() { + this.progress = 0; + this.loading = false; + + this._queue.kill(); + this._queue.pause(); + + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + + if (res._onLoadBinding) { + res._onLoadBinding.detach(); + } + + if (res.isLoading) { + res.abort(); + } + } + + this.resources = {}; + + return this; + }; + + /** + * Starts loading the queued resources. + * + * @param {function} [cb] - Optional callback that will be bound to the `complete` event. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.load = function load(cb) { + // register complete callback if they pass one + if (typeof cb === 'function') { + this.onComplete.once(cb); + } + + // if the queue has already started we are done here + if (this.loading) { + return this; + } + + if (this._queue.idle()) { + this._onStart(); + this._onComplete(); + } else { + // distribute progress chunks + var numTasks = this._queue._tasks.length; + var chunk = 100 / numTasks; + + for (var i = 0; i < this._queue._tasks.length; ++i) { + this._queue._tasks[i].data.progressChunk = chunk; + } + + // notify we are starting + this._onStart(); + + // start loading + this._queue.resume(); + } + + return this; + }; + + /** + * The number of resources to load concurrently. + * + * @member {number} + * @default 10 + */ + + + /** + * Prepares a url for usage based on the configuration of this object + * + * @private + * @param {string} url - The url to prepare. + * @return {string} The prepared url. + */ + Loader.prototype._prepareUrl = function _prepareUrl(url) { + var parsedUrl = (0, _parseUri2.default)(url, { strictMode: true }); + var result = void 0; + + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { + result = url; + } + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + else if (this.baseUrl.length && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 && url.charAt(0) !== '/') { + result = this.baseUrl + '/' + url; + } else { + result = this.baseUrl + url; + } + + // if we need to add a default querystring, there is a bit more work + if (this.defaultQueryString) { + var hash = rgxExtractUrlHash.exec(result)[0]; + + result = result.substr(0, result.length - hash.length); + + if (result.indexOf('?') !== -1) { + result += '&' + this.defaultQueryString; + } else { + result += '?' + this.defaultQueryString; + } + + result += hash; + } + + return result; + }; + + /** + * Loads a single resource. + * + * @private + * @param {Resource} resource - The resource to load. + * @param {function} dequeue - The function to call when we need to dequeue this item. + */ + + + Loader.prototype._loadResource = function _loadResource(resource, dequeue) { + var _this2 = this; + + resource._dequeue = dequeue; + + // run before middleware + async.eachSeries(this._beforeMiddleware, function (fn, next) { + fn.call(_this2, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, function () { + if (resource.isComplete) { + _this2._onLoad(resource); + } else { + resource._onLoadBinding = resource.onComplete.once(_this2._onLoad, _this2); + resource.load(); + } + }, true); + }; + + /** + * Called once loading has started. + * + * @private + */ + + + Loader.prototype._onStart = function _onStart() { + this.progress = 0; + this.loading = true; + this.onStart.dispatch(this); + }; + + /** + * Called once each resource has loaded. + * + * @private + */ + + + Loader.prototype._onComplete = function _onComplete() { + this.progress = MAX_PROGRESS; + this.loading = false; + this.onComplete.dispatch(this, this.resources); + }; + + /** + * Called each time a resources is loaded. + * + * @private + * @param {Resource} resource - The resource that was loaded + */ + + + Loader.prototype._onLoad = function _onLoad(resource) { + var _this3 = this; + + resource._onLoadBinding = null; + + // remove this resource from the async queue, and add it to our list of resources that are being parsed + this._resourcesParsing.push(resource); + resource._dequeue(); + + // run all the after middleware for this resource + async.eachSeries(this._afterMiddleware, function (fn, next) { + fn.call(_this3, resource, next); + }, function () { + resource.onAfterMiddleware.dispatch(resource); + + _this3.progress += resource.progressChunk; + _this3.onProgress.dispatch(_this3, resource); + + if (resource.error) { + _this3.onError.dispatch(resource.error, _this3, resource); + } else { + _this3.onLoad.dispatch(_this3, resource); + } + + _this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1); + + // do completion check + if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) { + _this3._onComplete(); + } + }, true); + }; + + _createClass(Loader, [{ + key: 'concurrency', + get: function get() { + return this._queue.concurrency; + } + // eslint-disable-next-line require-jsdoc + , + set: function set(concurrency) { + this._queue.concurrency = concurrency; + } + }]); + + return Loader; +}(); + +exports.default = Loader; + +},{"./Resource":33,"./async":34,"mini-signals":5,"parse-uri":7}],33:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// tests is CORS is supported in XHR, if not we need to use XDR +var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest())); +var tempAnchor = null; + +// some status constants +var STATUS_NONE = 0; +var STATUS_OK = 200; +var STATUS_EMPTY = 204; +var STATUS_IE_BUG_EMPTY = 1223; +var STATUS_TYPE_OK = 2; + +// noop +function _noop() {} /* empty */ + +/** + * Manages the state and loading of a resource and all child resources. + * + * @class + */ + +var Resource = function () { + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. + */ + Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) { + setExtMap(Resource._loadTypeMap, extname, loadType); + }; + + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ + + + Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); + }; + + /** + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass + * an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @param {string|string[]} [options.metadata.mimeType] - The mime type to use for the source element of a video/audio + * elment. If the urls are an array, you can pass this as an array as well where each index is the mime type to + * use for the corresponding url index. + */ + + + function Resource(name, url, options) { + _classCallCheck(this, Resource); + + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + + options = options || {}; + + /** + * The state flags of this resource. + * + * @member {number} + */ + this._flags = 0; + + // set data url flag, needs to be set early for some _determineX checks to work. + this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); + + /** + * The name of this resource. + * + * @member {string} + * @readonly + */ + this.name = name; + + /** + * The url used to load this resource. + * + * @member {string} + * @readonly + */ + this.url = url; + + /** + * The extension used to load this resource. + * + * @member {string} + * @readonly + */ + this.extension = this._getExtension(); + + /** + * The data that was loaded by the resource. + * + * @member {any} + */ + this.data = null; + + /** + * Is this request cross-origin? If unset, determined automatically. + * + * @member {string} + */ + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + + /** + * The method of loading to use for this resource. + * + * @member {Resource.LOAD_TYPE} + */ + this.loadType = options.loadType || this._determineLoadType(); + + /** + * The type used to load the resource via XHR. If unset, determined automatically. + * + * @member {string} + */ + this.xhrType = options.xhrType; + + /** + * Extra info for middleware, and controlling specifics about how the resource loads. + * + * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + * Meaning it will modify it as it sees fit. + * + * @member {object} + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources + * to. + */ + this.metadata = options.metadata || {}; + + /** + * The error that occurred while loading (if any). + * + * @member {Error} + * @readonly + */ + this.error = null; + + /** + * The XHR object that was used to load this resource. This is only set + * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * + * @member {XMLHttpRequest} + * @readonly + */ + this.xhr = null; + + /** + * The child resources this resource owns. + * + * @member {Resource[]} + * @readonly + */ + this.children = []; + + /** + * The resource type. + * + * @member {Resource.TYPE} + * @readonly + */ + this.type = Resource.TYPE.UNKNOWN; + + /** + * The progress chunk owned by this resource. + * + * @member {number} + * @readonly + */ + this.progressChunk = 0; + + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * + * @private + * @member {function} + */ + this._dequeue = _noop; + + /** + * Used a storage place for the on load binding used privately by the loader. + * + * @private + * @member {function} + */ + this._onLoadBinding = null; + + /** + * The `complete` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundComplete = this.complete.bind(this); + + /** + * The `_onError` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnError = this._onError.bind(this); + + /** + * The `_onProgress` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnProgress = this._onProgress.bind(this); + + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + this._boundXdrOnTimeout = this._xdrOnTimeout.bind(this); + + /** + * Dispatched when the resource beings to load. + * + * The callback looks like {@link Resource.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched each time progress of this resource load updates. + * Not all resources types and loader systems can support this event + * so sometimes it may not be available. If the resource + * is being loaded on a modern browser, using XHR, and the remote server + * properly sets Content-Length headers, then this will be available. + * + * The callback looks like {@link Resource.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once this resource has loaded, if there was an error it will + * be in the `error` property. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * Dispatched after this resource has had all the *after* middleware run on it. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onAfterMiddleware = new _miniSignals2.default(); + + /** + * When the resource starts to load. + * + * @memberof Resource + * @callback OnStartSignal + * @param {Resource} resource - The resource that the event happened on. + */ + + /** + * When the resource reports loading progress. + * + * @memberof Resource + * @callback OnProgressSignal + * @param {Resource} resource - The resource that the event happened on. + * @param {number} percentage - The progress of the load in the range [0, 1]. + */ + + /** + * When the resource finishes loading. + * + * @memberof Resource + * @callback OnCompleteSignal + * @param {Resource} resource - The resource that the event happened on. + */ + } + + /** + * Stores whether or not this url is a data url. + * + * @member {boolean} + * @readonly + */ + + + /** + * Marks the resource as complete. + * + */ + Resource.prototype.complete = function complete() { + // TODO: Clean this up in a wrapper or something...gross.... + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + + this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true); + this._setFlag(Resource.STATUS_FLAGS.LOADING, false); + + this.onComplete.dispatch(this); + }; + + /** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ + + + Resource.prototype.abort = function abort(message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + + // store error + this.error = new Error(message); + + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } else if (this.xdr) { + this.xdr.abort(); + } else if (this.data) { + // single source + if (this.data.src) { + this.data.src = Resource.EMPTY_GIF; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + + // done now. + this.complete(); + }; + + /** + * Kicks off loading of this resource. This method is asynchronous. + * + * @param {function} [cb] - Optional callback to call once the resource is loaded. + */ + + + Resource.prototype.load = function load(cb) { + var _this = this; + + if (this.isLoading) { + return; + } + + if (this.isComplete) { + if (cb) { + setTimeout(function () { + return cb(_this); + }, 1); + } + + return; + } else if (cb) { + this.onComplete.once(cb); + } + + this._setFlag(Resource.STATUS_FLAGS.LOADING, true); + + this.onStart.dispatch(this); + + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + + switch (this.loadType) { + case Resource.LOAD_TYPE.IMAGE: + this.type = Resource.TYPE.IMAGE; + this._loadElement('image'); + break; + + case Resource.LOAD_TYPE.AUDIO: + this.type = Resource.TYPE.AUDIO; + this._loadSourceElement('audio'); + break; + + case Resource.LOAD_TYPE.VIDEO: + this.type = Resource.TYPE.VIDEO; + this._loadSourceElement('video'); + break; + + case Resource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } else { + this._loadXhr(); + } + break; + } + }; + + /** + * Checks if the flag is set. + * + * @private + * @param {number} flag - The flag to check. + * @return {boolean} True if the flag is set. + */ + + + Resource.prototype._hasFlag = function _hasFlag(flag) { + return !!(this._flags & flag); + }; + + /** + * (Un)Sets the flag. + * + * @private + * @param {number} flag - The flag to (un)set. + * @param {boolean} value - Whether to set or (un)set the flag. + */ + + + Resource.prototype._setFlag = function _setFlag(flag, value) { + this._flags = value ? this._flags | flag : this._flags & ~flag; + }; + + /** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadElement = function _loadElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'image' && typeof window.Image !== 'undefined') { + this.data = new Image(); + } else { + this.data = document.createElement(type); + } + + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + }; + + /** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadSourceElement = function _loadSourceElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'audio' && typeof window.Audio !== 'undefined') { + this.data = new Audio(); + } else { + this.data = document.createElement(type); + } + + if (this.data === null) { + this.abort('Unsupported element: ' + type); + + return; + } + + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } else if (Array.isArray(this.url)) { + var mimeTypes = this.metadata.mimeType; + + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes)); + } + } else { + var _mimeTypes = this.metadata.mimeType; + + this.data.appendChild(this._createSource(type, this.url, Array.isArray(_mimeTypes) ? _mimeTypes[0] : _mimeTypes)); + } + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + + this.data.load(); + }; + + /** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ + + + Resource.prototype._loadXhr = function _loadXhr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xhr = this.xhr = new XMLHttpRequest(); + + // set the request type and url + xhr.open('GET', this.url, true); + + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; + } else { + xhr.responseType = this.xhrType; + } + + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + + xhr.send(); + }; + + /** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ + + + Resource.prototype._loadXdr = function _loadXdr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xdr = this.xhr = new XDomainRequest(); + + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = 5000; + + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXdrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + + xdr.open('GET', this.url, true); + + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { + return xdr.send(); + }, 1); + }; + + /** + * Creates a source used in loading via an element. + * + * @private + * @param {string} type - The element type (video or audio). + * @param {string} url - The source URL to load from. + * @param {string} [mime] - The mime type of the video + * @return {HTMLSourceElement} The source element. + */ + + + Resource.prototype._createSource = function _createSource(type, url, mime) { + if (!mime) { + mime = type + '/' + this._getExtension(url); + } + + var source = document.createElement('source'); + + source.src = url; + source.type = mime; + + return source; + }; + + /** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ + + + Resource.prototype._onError = function _onError(event) { + this.abort('Failed to load element using: ' + event.target.nodeName); + }; + + /** + * Called if a load progress event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ + + + Resource.prototype._onProgress = function _onProgress(event) { + if (event && event.lengthComputable) { + this.onProgress.dispatch(this, event.loaded / event.total); + } + }; + + /** + * Called if an error event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestErrorEvent|Event} event - Error event. + */ + + + Resource.prototype._xhrOnError = function _xhrOnError() { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"'); + }; + + /** + * Called if an abort event fires for xhr. + * + * @private + * @param {XMLHttpRequestAbortEvent} event - Abort Event + */ + + + Resource.prototype._xhrOnAbort = function _xhrOnAbort() { + this.abort(reqType(this.xhr) + ' Request was aborted by the user.'); + }; + + /** + * Called if a timeout event fires for xdr. + * + * @private + * @param {Event} event - Timeout event. + */ + + + Resource.prototype._xdrOnTimeout = function _xdrOnTimeout() { + this.abort(reqType(this.xhr) + ' Request timed out.'); + }; + + /** + * Called when data successfully loads from an xhr/xdr request. + * + * @private + * @param {XMLHttpRequestLoadEvent|Event} event - Load event + */ + + + Resource.prototype._xhrOnLoad = function _xhrOnLoad() { + var xhr = this.xhr; + var text = ''; + var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200. + + // responseText is accessible only if responseType is '' or 'text' and on older browsers + if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') { + text = xhr.responseText; + } + + // status can be 0 when using the `file://` protocol so we also check if a response is set. + // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request. + if (status === STATUS_NONE && (text.length > 0 || xhr.responseType === Resource.XHR_RESPONSE_TYPE.BUFFER)) { + status = STATUS_OK; + } + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + else if (status === STATUS_IE_BUG_EMPTY) { + status = STATUS_EMPTY; + } + + var statusType = status / 100 | 0; + + if (statusType === STATUS_TYPE_OK) { + // if text, just return it + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { + this.data = text; + this.type = Resource.TYPE.TEXT; + } + // if json, parse into json object + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(text); + this.type = Resource.TYPE.JSON; + } catch (e) { + this.abort('Error trying to parse loaded json: ' + e); + + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (window.DOMParser) { + var domparser = new DOMParser(); + + this.data = domparser.parseFromString(text, 'text/xml'); + } else { + var div = document.createElement('div'); + + div.innerHTML = text; + + this.data = div; + } + + this.type = Resource.TYPE.XML; + } catch (e) { + this.abort('Error trying to parse loaded xml: ' + e); + + return; + } + } + // other types just return the response + else { + this.data = xhr.response || text; + } + } else { + this.abort('[' + xhr.status + '] ' + xhr.statusText + ': ' + xhr.responseURL); + + return; + } + + this.complete(); + }; + + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * + * @private + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ + + + Resource.prototype._determineCrossOrigin = function _determineCrossOrigin(url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = (0, _parseUri2.default)(tempAnchor.href, { strictMode: true }); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + var protocol = url.protocol ? url.protocol + ':' : ''; + + // if cross origin + if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; + }; + + /** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. + */ + + + Resource.prototype._determineXhrType = function _determineXhrType() { + return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT; + }; + + /** + * Determines the loadType of a resource based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.LOAD_TYPE} The loadType to use. + */ + + + Resource.prototype._determineLoadType = function _determineLoadType() { + return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR; + }; + + /** + * Extracts the extension (sans '.') of the file being loaded by the resource. + * + * @private + * @return {string} The extension. + */ + + + Resource.prototype._getExtension = function _getExtension() { + var url = this.url; + var ext = ''; + + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } else { + var queryStart = url.indexOf('?'); + var hashStart = url.indexOf('#'); + var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length); + + url = url.substring(0, index); + ext = url.substring(url.lastIndexOf('.') + 1); + } + + return ext.toLowerCase(); + }; + + /** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * + * @private + * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. + * @return {string} The mime type to use. + */ + + + Resource.prototype._getMimeFromXhrType = function _getMimeFromXhrType(type) { + switch (type) { + case Resource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + + case Resource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + + case Resource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + + case Resource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + + case Resource.XHR_RESPONSE_TYPE.DEFAULT: + case Resource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + + } + }; + + _createClass(Resource, [{ + key: 'isDataUrl', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL); + } + + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isComplete', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE); + } + + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isLoading', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.LOADING); + } + }]); + + return Resource; +}(); + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ + + +exports.default = Resource; +Resource.STATUS_FLAGS = { + NONE: 0, + DATA_URL: 1 << 0, + COMPLETE: 1 << 1, + LOADING: 1 << 2 +}; + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ +Resource.TYPE = { + UNKNOWN: 0, + JSON: 1, + XML: 2, + IMAGE: 3, + AUDIO: 4, + VIDEO: 5, + TEXT: 6 +}; + +/** + * The types of loading a resource can use. + * + * @static + * @readonly + * @enum {number} + */ +Resource.LOAD_TYPE = { + /** Uses XMLHttpRequest to load the resource. */ + XHR: 1, + /** Uses an `Image` object to load the resource. */ + IMAGE: 2, + /** Uses an `Audio` object to load the resource. */ + AUDIO: 3, + /** Uses a `Video` object to load the resource. */ + VIDEO: 4 +}; + +/** + * The XHR ready states, used internally. + * + * @static + * @readonly + * @enum {string} + */ +Resource.XHR_RESPONSE_TYPE = { + /** string */ + DEFAULT: 'text', + /** ArrayBuffer */ + BUFFER: 'arraybuffer', + /** Blob */ + BLOB: 'blob', + /** Document */ + DOCUMENT: 'document', + /** Object */ + JSON: 'json', + /** String */ + TEXT: 'text' +}; + +Resource._loadTypeMap = { + // images + gif: Resource.LOAD_TYPE.IMAGE, + png: Resource.LOAD_TYPE.IMAGE, + bmp: Resource.LOAD_TYPE.IMAGE, + jpg: Resource.LOAD_TYPE.IMAGE, + jpeg: Resource.LOAD_TYPE.IMAGE, + tif: Resource.LOAD_TYPE.IMAGE, + tiff: Resource.LOAD_TYPE.IMAGE, + webp: Resource.LOAD_TYPE.IMAGE, + tga: Resource.LOAD_TYPE.IMAGE, + svg: Resource.LOAD_TYPE.IMAGE, + 'svg+xml': Resource.LOAD_TYPE.IMAGE, // for SVG data urls + + // audio + mp3: Resource.LOAD_TYPE.AUDIO, + ogg: Resource.LOAD_TYPE.AUDIO, + wav: Resource.LOAD_TYPE.AUDIO, + + // videos + mp4: Resource.LOAD_TYPE.VIDEO, + webm: Resource.LOAD_TYPE.VIDEO +}; + +Resource._xhrTypeMap = { + // xml + xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. + // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, + // this should probably be fine. + tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // images + gif: Resource.XHR_RESPONSE_TYPE.BLOB, + png: Resource.XHR_RESPONSE_TYPE.BLOB, + bmp: Resource.XHR_RESPONSE_TYPE.BLOB, + jpg: Resource.XHR_RESPONSE_TYPE.BLOB, + jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, + tif: Resource.XHR_RESPONSE_TYPE.BLOB, + tiff: Resource.XHR_RESPONSE_TYPE.BLOB, + webp: Resource.XHR_RESPONSE_TYPE.BLOB, + tga: Resource.XHR_RESPONSE_TYPE.BLOB, + + // json + json: Resource.XHR_RESPONSE_TYPE.JSON, + + // text + text: Resource.XHR_RESPONSE_TYPE.TEXT, + txt: Resource.XHR_RESPONSE_TYPE.TEXT, + + // fonts + ttf: Resource.XHR_RESPONSE_TYPE.BUFFER, + otf: Resource.XHR_RESPONSE_TYPE.BUFFER +}; + +// We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif +Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; + +/** + * Quick helper to set a value on one of the extension maps. Ensures there is no + * dot at the start of the extension. + * + * @ignore + * @param {object} map - The map to set on. + * @param {string} extname - The extension (or key) to set. + * @param {number} val - The value to set. + */ +function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + + if (!extname) { + return; + } + + map[extname] = val; +} + +/** + * Quick helper to get string xhr type. + * + * @ignore + * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. + * @return {string} The type. + */ +function reqType(xhr) { + return xhr.toString().replace('object ', ''); +} + +},{"mini-signals":5,"parse-uri":7}],34:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.eachSeries = eachSeries; +exports.queue = queue; +/** + * Smaller version of the async library constructs. + * + */ +function _noop() {} /* empty */ + +/** + * Iterates an array in series. + * + * @param {Array.<*>} array - Array to iterate. + * @param {function} iterator - Function to call for each element. + * @param {function} callback - Function to call when done, or on error. + * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1. + */ +function eachSeries(array, iterator, callback, deferNext) { + var i = 0; + var len = array.length; + + (function next(err) { + if (err || i === len) { + if (callback) { + callback(err); + } + + return; + } + + if (deferNext) { + setTimeout(function () { + iterator(array[i++], next); + }, 1); + } else { + iterator(array[i++], next); + } + })(); +} + +/** + * Ensures a function is only called once. + * + * @param {function} fn - The function to wrap. + * @return {function} The wrapping function. + */ +function onlyOnce(fn) { + return function onceWrapper() { + if (fn === null) { + throw new Error('Callback was already called.'); + } + + var callFn = fn; + + fn = null; + callFn.apply(this, arguments); + }; +} + +/** + * Async queue implementation, + * + * @param {function} worker - The worker function to call for each task. + * @param {number} concurrency - How many workers to run in parrallel. + * @return {*} The async queue object. + */ +function queue(worker, concurrency) { + if (concurrency == null) { + // eslint-disable-line no-eq-null,eqeqeq + concurrency = 1; + } else if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + + var workers = 0; + var q = { + _tasks: [], + concurrency: concurrency, + saturated: _noop, + unsaturated: _noop, + buffer: concurrency / 4, + empty: _noop, + drain: _noop, + error: _noop, + started: false, + paused: false, + push: function push(data, callback) { + _insert(data, false, callback); + }, + kill: function kill() { + workers = 0; + q.drain = _noop; + q.started = false; + q._tasks = []; + }, + unshift: function unshift(data, callback) { + _insert(data, true, callback); + }, + process: function process() { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var task = q._tasks.shift(); + + if (q._tasks.length === 0) { + q.empty(); + } + + workers += 1; + + if (workers === q.concurrency) { + q.saturated(); + } + + worker(task.data, onlyOnce(_next(task))); + } + }, + length: function length() { + return q._tasks.length; + }, + running: function running() { + return workers; + }, + idle: function idle() { + return q._tasks.length + workers === 0; + }, + pause: function pause() { + if (q.paused === true) { + return; + } + + q.paused = true; + }, + resume: function resume() { + if (q.paused === false) { + return; + } + + q.paused = false; + + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= q.concurrency; w++) { + q.process(); + } + } + }; + + function _insert(data, insertAtFront, callback) { + if (callback != null && typeof callback !== 'function') { + // eslint-disable-line no-eq-null,eqeqeq + throw new Error('task callback must be a function'); + } + + q.started = true; + + if (data == null && q.idle()) { + // eslint-disable-line no-eq-null,eqeqeq + // call drain immediately if there are no tasks + setTimeout(function () { + return q.drain(); + }, 1); + + return; + } + + var item = { + data: data, + callback: typeof callback === 'function' ? callback : _noop + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + setTimeout(function () { + return q.process(); + }, 1); + } + + function _next(task) { + return function next() { + workers -= 1; + + task.callback.apply(task, arguments); + + if (arguments[0] != null) { + // eslint-disable-line no-eq-null,eqeqeq + q.error(arguments[0], task.data); + } + + if (workers <= q.concurrency - q.buffer) { + q.unsaturated(); + } + + if (q.idle()) { + q.drain(); + } + + q.process(); + }; + } + + return q; +} + +},{}],35:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.encodeBinary = encodeBinary; +var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +function encodeBinary(input) { + var output = ''; + var inx = 0; + + while (inx < input.length) { + // Fill byte buffer array + var bytebuffer = [0, 0, 0]; + var encodedCharIndexes = [0, 0, 0, 0]; + + for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } else { + bytebuffer[jnx] = 0; + } + } + + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4; + + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6; + + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + + // Determine whether padding happened, and adjust accordingly + var paddingBytes = inx - (input.length - 1); + + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + + default: + break; // No padding - proceed + } + + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) { + output += _keyStr.charAt(encodedCharIndexes[_jnx]); + } + } + + return output; +} + +},{}],36:[function(require,module,exports){ +'use strict'; + +// import Loader from './Loader'; +// import Resource from './Resource'; +// import * as async from './async'; +// import * as b64 from './b64'; + +/* eslint-disable no-undef */ + +var Loader = require('./Loader').default; +var Resource = require('./Resource').default; +var async = require('./async'); +var b64 = require('./b64'); + +Loader.Resource = Resource; +Loader.async = async; +Loader.base64 = b64; + +// export manually, and also as default +module.exports = Loader; +// export default Loader; +module.exports.default = Loader; + +},{"./Loader":32,"./Resource":33,"./async":34,"./b64":35}],37:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +exports.blobMiddlewareFactory = blobMiddlewareFactory; + +var _Resource = require('../../Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +var _b = require('../../b64'); + +var _b2 = _interopRequireDefault(_b); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Url = window.URL || window.webkitURL; + +// a middleware for transforming XHR loaded Blobs into more useful objects +function blobMiddlewareFactory() { + return function blobMiddleware(resource, next) { + if (!resource.data) { + next(); + + return; + } + + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === _Resource2.default.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!window.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = 'data:' + type + ';base64,' + _b2.default.encodeBinary(resource.xhr.responseText); + + resource.type = _Resource2.default.TYPE.IMAGE; + + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + + next(); + }; + + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var _ret = function () { + var src = Url.createObjectURL(resource.data); + + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src; + + resource.type = _Resource2.default.TYPE.IMAGE; + + // cleanup the no longer used blob after the image loads + // TODO: Is this correct? Will the image be invalid after revoking? + resource.data.onload = function () { + Url.revokeObjectURL(src); + resource.data.onload = null; + + next(); + }; + + // next will be called on load. + return { + v: void 0 + }; + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + } + + next(); + }; +} + +},{"../../Resource":33,"../../b64":35}],38:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":39,"punycode":27,"querystring":30}],39:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],40:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +var _accessibleTarget = require('./accessibleTarget'); + +var _accessibleTarget2 = _interopRequireDefault(_accessibleTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// add some extra variables to the container.. +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _accessibleTarget2.default); + +var KEY_CODE_TAB = 9; + +var DIV_TOUCH_SIZE = 100; +var DIV_TOUCH_POS_X = 0; +var DIV_TOUCH_POS_Y = 0; +var DIV_TOUCH_ZINDEX = 2; + +var DIV_HOOK_SIZE = 1; +var DIV_HOOK_POS_X = -1000; +var DIV_HOOK_POS_Y = -1000; +var DIV_HOOK_ZINDEX = 2; + +/** + * The Accessibility manager recreates the ability to tab and have content read by screen + * readers. This is very important as it can possibly help people with disabilities access pixi + * content. + * + * Much like interaction any DisplayObject can be made accessible. This manager will map the + * events as if the mouse was being used, minimizing the effort required to implement. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.accessibility + * + * @class + * @memberof PIXI.accessibility + */ + +var AccessibilityManager = function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + _classCallCheck(this, AccessibilityManager); + + if ((_ismobilejs2.default.tablet || _ismobilejs2.default.phone) && !navigator.isCocoonJS) { + this.createTouchHook(); + } + + // first we create a div that will sit over the PixiJS element. This is where the div overlays will go. + var div = document.createElement('div'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + 'px'; + div.style.left = DIV_TOUCH_POS_Y + 'px'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + + /** + * This is the dom element that will sit over the PixiJS element. This is where the div overlays will go. + * + * @type {HTMLElement} + * @private + */ + this.div = div; + + /** + * A simple pool for storing divs. + * + * @type {*} + * @private + */ + this.pool = []; + + /** + * This is a tick used to check if an object is no longer being rendered. + * + * @type {Number} + * @private + */ + this.renderId = 0; + + /** + * Setting this to true will visually show the divs. + * + * @type {boolean} + */ + this.debug = false; + + /** + * The renderer this accessibility manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * The array of currently active accessible items. + * + * @member {Array<*>} + * @private + */ + this.children = []; + + /** + * pre-bind the functions + * + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + + /** + * stores the state of the manager. If there are no accessible objects or the mouse is moving, this will be false. + * + * @member {Array<*>} + * @private + */ + this.isActive = false; + this.isMobileAccessabillity = false; + + // let listen for tab.. once pressed we can fire up and show the accessibility layer + window.addEventListener('keydown', this._onKeyDown, false); + } + + /** + * Creates the touch hooks. + * + */ + + + AccessibilityManager.prototype.createTouchHook = function createTouchHook() { + var _this = this; + + var hookDiv = document.createElement('button'); + + hookDiv.style.width = DIV_HOOK_SIZE + 'px'; + hookDiv.style.height = DIV_HOOK_SIZE + 'px'; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + 'px'; + hookDiv.style.left = DIV_HOOK_POS_Y + 'px'; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX; + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'HOOK DIV'; + + hookDiv.addEventListener('focus', function () { + _this.isMobileAccessabillity = true; + _this.activate(); + document.body.removeChild(hookDiv); + }); + + document.body.appendChild(hookDiv); + }; + + /** + * Activating will cause the Accessibility layer to be shown. This is called when a user + * preses the tab key. + * + * @private + */ + + + AccessibilityManager.prototype.activate = function activate() { + if (this.isActive) { + return; + } + + this.isActive = true; + + window.document.addEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown, false); + + this.renderer.on('postrender', this.update, this); + + if (this.renderer.view.parentNode) { + this.renderer.view.parentNode.appendChild(this.div); + } + }; + + /** + * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves + * the mouse. + * + * @private + */ + + + AccessibilityManager.prototype.deactivate = function deactivate() { + if (!this.isActive || this.isMobileAccessabillity) { + return; + } + + this.isActive = false; + + window.document.removeEventListener('mousemove', this._onMouseMove, true); + window.addEventListener('keydown', this._onKeyDown, false); + + this.renderer.off('postrender', this.update); + + if (this.div.parentNode) { + this.div.parentNode.removeChild(this.div); + } + }; + + /** + * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. + * + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + + + AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects(displayObject) { + if (!displayObject.visible) { + return; + } + + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + + displayObject.renderId = this.renderId; + } + + var children = displayObject.children; + + for (var i = 0; i < children.length; i++) { + this.updateAccessibleObjects(children[i]); + } + }; + + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * + * @private + */ + + + AccessibilityManager.prototype.update = function update() { + if (!this.renderer.renderingToScreen) { + return; + } + + // update children... + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + + var rect = this.renderer.view.getBoundingClientRect(); + var sx = rect.width / this.renderer.width; + var sy = rect.height / this.renderer.height; + + var div = this.div; + + div.style.left = rect.left + 'px'; + div.style.top = rect.top + 'px'; + div.style.width = this.renderer.width + 'px'; + div.style.height = this.renderer.height + 'px'; + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + + core.utils.removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + + i--; + + if (this.children.length === 0) { + this.deactivate(); + } + } else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + + if (child.hitArea) { + div.style.left = (wt.tx + hitArea.x * wt.a) * sx + 'px'; + div.style.top = (wt.ty + hitArea.y * wt.d) * sy + 'px'; + + div.style.width = hitArea.width * wt.a * sx + 'px'; + div.style.height = hitArea.height * wt.d * sy + 'px'; + } else { + hitArea = child.getBounds(); + + this.capHitArea(hitArea); + + div.style.left = hitArea.x * sx + 'px'; + div.style.top = hitArea.y * sy + 'px'; + + div.style.width = hitArea.width * sx + 'px'; + div.style.height = hitArea.height * sy + 'px'; + + // update button titles and hints if they exist and they've changed + if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) { + div.title = child.accessibleTitle; + } + if (div.getAttribute('aria-label') !== child.accessibleHint && child.accessibleHint !== null) { + div.setAttribute('aria-label', child.accessibleHint); + } + } + } + } + + // increment the render id.. + this.renderId++; + }; + + /** + * TODO: docs. + * + * @param {Rectangle} hitArea - TODO docs + */ + + + AccessibilityManager.prototype.capHitArea = function capHitArea(hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + + if (hitArea.x + hitArea.width > this.renderer.width) { + hitArea.width = this.renderer.width - hitArea.x; + } + + if (hitArea.y + hitArea.height > this.renderer.height) { + hitArea.height = this.renderer.height - hitArea.y; + } + }; + + /** + * Adds a DisplayObject to the accessibility manager + * + * @private + * @param {DisplayObject} displayObject - The child to make accessible. + */ + + + AccessibilityManager.prototype.addChild = function addChild(displayObject) { + // this.activate(); + + var div = this.pool.pop(); + + if (!div) { + div = document.createElement('button'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + div.style.borderStyle = 'none'; + + // ARIA attributes ensure that button title and hint updates are announced properly + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + // Chrome doesn't need aria-live to work as intended; in fact it just gets more confused. + div.setAttribute('aria-live', 'off'); + } else { + div.setAttribute('aria-live', 'polite'); + } + + if (navigator.userAgent.match(/rv:.*Gecko\//)) { + // FireFox needs this to announce only the new button name + div.setAttribute('aria-relevant', 'additions'); + } else { + // required by IE, other browsers don't much care + div.setAttribute('aria-relevant', 'text'); + } + + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + + if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) { + div.title = displayObject.accessibleTitle; + } else if (!displayObject.accessibleHint || displayObject.accessibleHint === null) { + div.title = 'displayObject ' + displayObject.tabIndex; + } + + if (displayObject.accessibleHint && displayObject.accessibleHint !== null) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + + // + + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + + /** + * Maps the div button press to pixi's InteractionManager (click) + * + * @private + * @param {MouseEvent} e - The click event. + */ + + + AccessibilityManager.prototype._onClick = function _onClick(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixi's InteractionManager (mouseover) + * + * @private + * @param {FocusEvent} e - The focus event. + */ + + + AccessibilityManager.prototype._onFocus = function _onFocus(e) { + if (!e.target.getAttribute('aria-live', 'off')) { + e.target.setAttribute('aria-live', 'assertive'); + } + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixi's InteractionManager (mouseout) + * + * @private + * @param {FocusEvent} e - The focusout event. + */ + + + AccessibilityManager.prototype._onFocusOut = function _onFocusOut(e) { + if (!e.target.getAttribute('aria-live', 'off')) { + e.target.setAttribute('aria-live', 'polite'); + } + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); + }; + + /** + * Is called when a key is pressed + * + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + + + AccessibilityManager.prototype._onKeyDown = function _onKeyDown(e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + + this.activate(); + }; + + /** + * Is called when the mouse moves across the renderer element + * + * @private + * @param {MouseEvent} e - The mouse event. + */ + + + AccessibilityManager.prototype._onMouseMove = function _onMouseMove(e) { + if (e.movementX === 0 && e.movementY === 0) { + return; + } + + this.deactivate(); + }; + + /** + * Destroys the accessibility manager + * + */ + + + AccessibilityManager.prototype.destroy = function destroy() { + this.div = null; + + for (var i = 0; i < this.children.length; i++) { + this.children[i].div = null; + } + + window.document.removeEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown); + + this.pool = null; + this.children = null; + this.renderer = null; + }; + + return AccessibilityManager; +}(); + +exports.default = AccessibilityManager; + + +core.WebGLRenderer.registerPlugin('accessibility', AccessibilityManager); +core.CanvasRenderer.registerPlugin('accessibility', AccessibilityManager); + +},{"../core":65,"./accessibleTarget":41,"ismobilejs":4}],41:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Default property values of accessible objects + * used by {@link PIXI.accessibility.AccessibilityManager}. + * + * @function accessibleTarget + * @memberof PIXI.accessibility + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibility.accessibleTarget + * ); + */ +exports.default = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * + * @member {boolean} + */ + accessible: false, + + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * + * @member {string} + */ + accessibleTitle: null, + + /** + * Sets the aria-label attribute of the shadow div + * + * @member {string} + */ + accessibleHint: null, + + /** + * @todo Needs docs. + */ + tabIndex: 0, + + /** + * @todo Needs docs. + */ + _accessibleActive: false, + + /** + * @todo Needs docs. + */ + _accessibleDiv: false +}; + +},{}],42:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _accessibleTarget = require('./accessibleTarget'); + +Object.defineProperty(exports, 'accessibleTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_accessibleTarget).default; + } +}); + +var _AccessibilityManager = require('./AccessibilityManager'); + +Object.defineProperty(exports, 'AccessibilityManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AccessibilityManager).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./AccessibilityManager":40,"./accessibleTarget":41}],43:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +var _Container = require('./display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _ticker = require('./ticker'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _const = require('./const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Convenience class to create a new PIXI application. + * This class automatically creates the renderer, ticker + * and root container. + * + * @example + * // Create the application + * const app = new PIXI.Application(); + * + * // Add the view to the DOM + * document.body.appendChild(app.view); + * + * // ex, add display objects + * app.stage.addChild(PIXI.Sprite.fromImage('something.png')); + * + * @class + * @memberof PIXI + */ +var Application = function () { + // eslint-disable-next-line valid-jsdoc + /** + * @param {object} [options] - The optional renderer parameters + * @param {boolean} [options.autoStart=true] - automatically starts the rendering after the construction. + * Note that setting this parameter to false does NOT stop the shared ticker even if you set + * options.sharedTicker to true in case that it is already started. Stop it by your own. + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great **webgl only** + * @param {boolean} [options.legacy=false] - `true` to ensure compatibility with older / less advanced devices. + * If you experience unexplained flickering try setting this to true. **webgl only** + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card **webgl only** + * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.ticker.shared, `false` to create new ticker. + * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.loaders.shared, `false` to create new Loader. + */ + function Application(options, arg2, arg3, arg4, arg5) { + _classCallCheck(this, Application); + + // Support for constructor(width, height, options, noWebGL, useSharedTicker) + if (typeof options === 'number') { + options = Object.assign({ + width: options, + height: arg2 || _settings2.default.RENDER_OPTIONS.height, + forceCanvas: !!arg4, + sharedTicker: !!arg5 + }, arg3); + } + + /** + * The default options, so we mixin functionality later. + * @member {object} + * @protected + */ + this._options = options = Object.assign({ + autoStart: true, + sharedTicker: false, + forceCanvas: false, + sharedLoader: false + }, options); + + /** + * WebGL renderer if available, otherwise CanvasRenderer + * @member {PIXI.WebGLRenderer|PIXI.CanvasRenderer} + */ + this.renderer = (0, _autoDetectRenderer.autoDetectRenderer)(options); + + /** + * The root display container that's rendered. + * @member {PIXI.Container} + */ + this.stage = new _Container2.default(); + + /** + * Internal reference to the ticker + * @member {PIXI.ticker.Ticker} + * @private + */ + this._ticker = null; + + /** + * Ticker for doing render updates. + * @member {PIXI.ticker.Ticker} + * @default PIXI.ticker.shared + */ + this.ticker = options.sharedTicker ? _ticker.shared : new _ticker.Ticker(); + + // Start the rendering + if (options.autoStart) { + this.start(); + } + } + + /** + * Render the current stage. + */ + Application.prototype.render = function render() { + this.renderer.render(this.stage); + }; + + /** + * Convenience method for stopping the render. + */ + + + Application.prototype.stop = function stop() { + this._ticker.stop(); + }; + + /** + * Convenience method for starting the render. + */ + + + Application.prototype.start = function start() { + this._ticker.start(); + }; + + /** + * Reference to the renderer's canvas element. + * @member {HTMLCanvasElement} + * @readonly + */ + + + /** + * Destroy and don't use after this. + * @param {Boolean} [removeView=false] Automatically remove canvas from DOM. + * @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy + * method called as well. 'stageOptions' will be passed on to those calls. + * @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set + * to true. Should it destroy the texture of the child sprite + * @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set + * to true. Should it destroy the base texture of the child sprite + */ + Application.prototype.destroy = function destroy(removeView, stageOptions) { + if (this._ticker) { + var oldTicker = this._ticker; + + this.ticker = null; + oldTicker.destroy(); + } + + this.stage.destroy(stageOptions); + this.stage = null; + + this.renderer.destroy(removeView); + this.renderer = null; + + this._options = null; + }; + + _createClass(Application, [{ + key: 'ticker', + set: function set(ticker) // eslint-disable-line require-jsdoc + { + if (this._ticker) { + this._ticker.remove(this.render, this); + } + this._ticker = ticker; + if (ticker) { + ticker.add(this.render, this, _const.UPDATE_PRIORITY.LOW); + } + }, + get: function get() // eslint-disable-line require-jsdoc + { + return this._ticker; + } + }, { + key: 'view', + get: function get() { + return this.renderer.view; + } + + /** + * Reference to the renderer's screen rectangle. Its safe to use as filterArea or hitArea for whole screen + * @member {PIXI.Rectangle} + * @readonly + */ + + }, { + key: 'screen', + get: function get() { + return this.renderer.screen; + } + }]); + + return Application; +}(); + +exports.default = Application; + +},{"./autoDetectRenderer":45,"./const":46,"./display/Container":48,"./settings":101,"./ticker":121}],44:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function checkPrecision(src, def) { + if (src instanceof Array) { + if (src[0].substring(0, 9) !== 'precision') { + var copy = src.slice(0); + + copy.unshift('precision ' + def + ' float;'); + + return copy; + } + } else if (src.trim().substring(0, 9) !== 'precision') { + return 'precision ' + def + ' float;\n' + src; + } + + return src; +} + +/** + * Wrapper class, webGL Shader for Pixi. + * Adds precision string if vertexSrc or fragmentSrc have no mention of it. + * + * @class + * @extends GLShader + * @memberof PIXI + */ + +var Shader = function (_GLShader) { + _inherits(Shader, _GLShader); + + /** + * + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + * @param {string|string[]} vertexSrc - The vertex shader source as an array of strings. + * @param {string|string[]} fragmentSrc - The fragment shader source as an array of strings. + * @param {object} [attributeLocations] - A key value pair showing which location eact attribute should sit. + e.g. {position:0, uvs:1}. + * @param {string} [precision] - The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + */ + function Shader(gl, vertexSrc, fragmentSrc, attributeLocations, precision) { + _classCallCheck(this, Shader); + + return _possibleConstructorReturn(this, _GLShader.call(this, gl, checkPrecision(vertexSrc, precision || _settings2.default.PRECISION_VERTEX), checkPrecision(fragmentSrc, precision || _settings2.default.PRECISION_FRAGMENT), undefined, attributeLocations)); + } + + return Shader; +}(_pixiGlCore.GLShader); + +exports.default = Shader; + +},{"./settings":101,"pixi-gl-core":15}],45:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = autoDetectRenderer; + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// eslint-disable-next-line valid-jsdoc +/** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by + * the browser then this function will return a canvas renderer + * + * @memberof PIXI + * @function autoDetectRenderer + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great **webgl only** + * @param {boolean} [options.legacy=false] - `true` to ensure compatibility with older / less advanced devices. + * If you experience unexplained flickering try setting this to true. **webgl only** + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card **webgl only** + * @return {PIXI.WebGLRenderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ +function autoDetectRenderer(options, arg1, arg2, arg3) { + // Backward-compatible support for noWebGL option + var forceCanvas = options && options.forceCanvas; + + if (arg3 !== undefined) { + forceCanvas = arg3; + } + + if (!forceCanvas && utils.isWebGLSupported()) { + return new _WebGLRenderer2.default(options, arg1, arg2); + } + + return new _CanvasRenderer2.default(options, arg1, arg2); +} + +},{"./renderers/canvas/CanvasRenderer":77,"./renderers/webgl/WebGLRenderer":84,"./utils":125}],46:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * String of the current PIXI version. + * + * @static + * @constant + * @memberof PIXI + * @name VERSION + * @type {string} + */ +var VERSION = exports.VERSION = '4.8.2'; + +/** + * Two Pi. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var PI_2 = exports.PI_2 = Math.PI * 2; + +/** + * Conversion factor for converting radians to degrees. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var RAD_TO_DEG = exports.RAD_TO_DEG = 180 / Math.PI; + +/** + * Conversion factor for converting degrees to radians. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var DEG_TO_RAD = exports.DEG_TO_RAD = Math.PI / 180; + +/** + * Constant to identify the Renderer Type. + * + * @static + * @constant + * @memberof PIXI + * @name RENDERER_TYPE + * @type {object} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ +var RENDERER_TYPE = exports.RENDERER_TYPE = { + UNKNOWN: 0, + WEBGL: 1, + CANVAS: 2 +}; + +/** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * + * @static + * @constant + * @memberof PIXI + * @name BLEND_MODES + * @type {object} + * @property {number} NORMAL + * @property {number} ADD + * @property {number} MULTIPLY + * @property {number} SCREEN + * @property {number} OVERLAY + * @property {number} DARKEN + * @property {number} LIGHTEN + * @property {number} COLOR_DODGE + * @property {number} COLOR_BURN + * @property {number} HARD_LIGHT + * @property {number} SOFT_LIGHT + * @property {number} DIFFERENCE + * @property {number} EXCLUSION + * @property {number} HUE + * @property {number} SATURATION + * @property {number} COLOR + * @property {number} LUMINOSITY + */ +var BLEND_MODES = exports.BLEND_MODES = { + NORMAL: 0, + ADD: 1, + MULTIPLY: 2, + SCREEN: 3, + OVERLAY: 4, + DARKEN: 5, + LIGHTEN: 6, + COLOR_DODGE: 7, + COLOR_BURN: 8, + HARD_LIGHT: 9, + SOFT_LIGHT: 10, + DIFFERENCE: 11, + EXCLUSION: 12, + HUE: 13, + SATURATION: 14, + COLOR: 15, + LUMINOSITY: 16, + NORMAL_NPM: 17, + ADD_NPM: 18, + SCREEN_NPM: 19 +}; + +/** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * + * @static + * @constant + * @memberof PIXI + * @name DRAW_MODES + * @type {object} + * @property {number} POINTS + * @property {number} LINES + * @property {number} LINE_LOOP + * @property {number} LINE_STRIP + * @property {number} TRIANGLES + * @property {number} TRIANGLE_STRIP + * @property {number} TRIANGLE_FAN + */ +var DRAW_MODES = exports.DRAW_MODES = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6 +}; + +/** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @static + * @constant + * @memberof PIXI + * @name SCALE_MODES + * @type {object} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ +var SCALE_MODES = exports.SCALE_MODES = { + LINEAR: 0, + NEAREST: 1 +}; + +/** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as webGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * + * @static + * @constant + * @name WRAP_MODES + * @memberof PIXI + * @type {object} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ +var WRAP_MODES = exports.WRAP_MODES = { + CLAMP: 0, + REPEAT: 1, + MIRRORED_REPEAT: 2 +}; + +/** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * + * @static + * @constant + * @name GC_MODES + * @memberof PIXI + * @type {object} + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ +var GC_MODES = exports.GC_MODES = { + AUTO: 0, + MANUAL: 1 +}; + +/** + * Regexp for image type by extension. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `image.png` + */ +var URL_FILE_EXTENSION = exports.URL_FILE_EXTENSION = /\.(\w{3,4})(?:$|\?|#)/i; + +/** + * Regexp for data URI. + * Based on: {@link https://github.com/ragingwind/data-uri-regex} + * + * @static + * @constant + * @name DATA_URI + * @memberof PIXI + * @type {RegExp|string} + * @example data:image/png;base64 + */ +var DATA_URI = exports.DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i; + +/** + * Regexp for SVG size. + * + * @static + * @constant + * @name SVG_SIZE + * @memberof PIXI + * @type {RegExp|string} + * @example <svg width="100" height="100"></svg> + */ +var SVG_SIZE = exports.SVG_SIZE = /]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len + +/** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * + * @static + * @constant + * @name SHAPES + * @memberof PIXI + * @type {object} + * @property {number} POLY Polygon + * @property {number} RECT Rectangle + * @property {number} CIRC Circle + * @property {number} ELIP Ellipse + * @property {number} RREC Rounded Rectangle + */ +var SHAPES = exports.SHAPES = { + POLY: 0, + RECT: 1, + CIRC: 2, + ELIP: 3, + RREC: 4 +}; + +/** + * Constants that specify float precision in shaders. + * + * @static + * @constant + * @name PRECISION + * @memberof PIXI + * @type {object} + * @property {string} LOW='lowp' + * @property {string} MEDIUM='mediump' + * @property {string} HIGH='highp' + */ +var PRECISION = exports.PRECISION = { + LOW: 'lowp', + MEDIUM: 'mediump', + HIGH: 'highp' +}; + +/** + * Constants that specify the transform type. + * + * @static + * @constant + * @name TRANSFORM_MODE + * @memberof PIXI + * @type {object} + * @property {number} STATIC + * @property {number} DYNAMIC + */ +var TRANSFORM_MODE = exports.TRANSFORM_MODE = { + STATIC: 0, + DYNAMIC: 1 +}; + +/** + * Constants that define the type of gradient on text. + * + * @static + * @constant + * @name TEXT_GRADIENT + * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL Vertical gradient + * @property {number} LINEAR_HORIZONTAL Linear gradient + */ +var TEXT_GRADIENT = exports.TEXT_GRADIENT = { + LINEAR_VERTICAL: 0, + LINEAR_HORIZONTAL: 1 +}; + +/** + * Represents the update priorities used by internal PIXI classes when registered with + * the {@link PIXI.ticker.Ticker} object. Higher priority items are updated first and lower + * priority items, such as render, should go later. + * + * @static + * @constant + * @name UPDATE_PRIORITY + * @memberof PIXI + * @type {object} + * @property {number} INTERACTION=50 Highest priority, used for {@link PIXI.interaction.InteractionManager} + * @property {number} HIGH=25 High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.extras.AnimatedSprite} + * @property {number} NORMAL=0 Default priority for ticker events, see {@link PIXI.ticker.Ticker#add}. + * @property {number} LOW=-25 Low priority used for {@link PIXI.Application} rendering. + * @property {number} UTILITY=-50 Lowest priority used for {@link PIXI.prepare.BasePrepare} utility. + */ +var UPDATE_PRIORITY = exports.UPDATE_PRIORITY = { + INTERACTION: 50, + HIGH: 25, + NORMAL: 0, + LOW: -25, + UTILITY: -50 +}; + +},{}],47:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * 'Builder' pattern for bounds rectangles + * Axis-Aligned Bounding Box + * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems + * + * @class + * @memberof PIXI + */ +var Bounds = function () { + /** + * + */ + function Bounds() { + _classCallCheck(this, Bounds); + + /** + * @member {number} + * @default 0 + */ + this.minX = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.minY = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxX = -Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxY = -Infinity; + + this.rect = null; + } + + /** + * Checks if bounds are empty. + * + * @return {boolean} True if empty. + */ + + + Bounds.prototype.isEmpty = function isEmpty() { + return this.minX > this.maxX || this.minY > this.maxY; + }; + + /** + * Clears the bounds and resets. + * + */ + + + Bounds.prototype.clear = function clear() { + this.updateID++; + + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * + * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty + * @returns {PIXI.Rectangle} A rectangle of the bounds + */ + + + Bounds.prototype.getRectangle = function getRectangle(rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return _math.Rectangle.EMPTY; + } + + rect = rect || new _math.Rectangle(0, 0, 1, 1); + + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + + return rect; + }; + + /** + * This function should be inlined when its possible. + * + * @param {PIXI.Point} point - The point to add. + */ + + + Bounds.prototype.addPoint = function addPoint(point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + }; + + /** + * Adds a quad, not transformed + * + * @param {Float32Array} vertices - The verts to add. + */ + + + Bounds.prototype.addQuad = function addQuad(vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = vertices[0]; + var y = vertices[1]; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds sprite frame, transformed. + * + * @param {PIXI.TransformBase} transform - TODO + * @param {number} x0 - TODO + * @param {number} y0 - TODO + * @param {number} x1 - TODO + * @param {number} y1 - TODO + */ + + + Bounds.prototype.addFrame = function addFrame(transform, x0, y0, x1, y1) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = a * x0 + c * y0 + tx; + var y = b * x0 + d * y0 + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y0 + tx; + y = b * x1 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x0 + c * y1 + tx; + y = b * x0 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y1 + tx; + y = b * x1 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Add an array of vertices + * + * @param {PIXI.TransformBase} transform - TODO + * @param {Float32Array} vertices - TODO + * @param {number} beginOffset - TODO + * @param {number} endOffset - TODO + */ + + + Bounds.prototype.addVertices = function addVertices(transform, vertices, beginOffset, endOffset) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = a * rawX + c * rawY + tx; + var y = d * rawY + b * rawX + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds other Bounds + * + * @param {PIXI.Bounds} bounds - TODO + */ + + + Bounds.prototype.addBounds = function addBounds(bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + }; + + /** + * Adds other Bounds, masked with Bounds + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Bounds} mask - TODO + */ + + + Bounds.prototype.addBoundsMask = function addBoundsMask(bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + /** + * Adds other Bounds, masked with Rectangle + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Rectangle} area - TODO + */ + + + Bounds.prototype.addBoundsArea = function addBoundsArea(bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : area.x + area.width; + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : area.y + area.height; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + return Bounds; +}(); + +exports.default = Bounds; + +},{"../math":70}],48:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _DisplayObject2 = require('./DisplayObject'); + +var _DisplayObject3 = _interopRequireDefault(_DisplayObject2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A Container represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + *```js + * let container = new PIXI.Container(); + * container.addChild(sprite); + * ``` + * + * @class + * @extends PIXI.DisplayObject + * @memberof PIXI + */ +var Container = function (_DisplayObject) { + _inherits(Container, _DisplayObject); + + /** + * + */ + function Container() { + _classCallCheck(this, Container); + + /** + * The array of children of this container. + * + * @member {PIXI.DisplayObject[]} + * @readonly + */ + var _this = _possibleConstructorReturn(this, _DisplayObject.call(this)); + + _this.children = []; + return _this; + } + + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified + * + * @private + */ + + + Container.prototype.onChildrenChange = function onChildrenChange() {} + /* empty */ + + + /** + * Adds one or more children to the container. + * + * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container + * @return {PIXI.DisplayObject} The first child that was added. + */ + ; + + Container.prototype.addChild = function addChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.addChild(arguments[i]); + } + } else { + // if the child has a parent then lets remove it as PixiJS objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.push(child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + child.emit('added', this); + } + + return child; + }; + + /** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @return {PIXI.DisplayObject} The child that was added. + */ + + + Container.prototype.addChildAt = function addChildAt(child, index) { + if (index < 0 || index > this.children.length) { + throw new Error(child + 'addChildAt: The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.splice(index, 0, child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + + return child; + }; + + /** + * Swaps the position of 2 Display Objects within this container. + * + * @param {PIXI.DisplayObject} child - First display object to swap + * @param {PIXI.DisplayObject} child2 - Second display object to swap + */ + + + Container.prototype.swapChildren = function swapChildren(child, child2) { + if (child === child2) { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; + + /** + * Returns the index position of a child DisplayObject instance + * + * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify + * @return {number} The index position of the child display object to identify + */ + + + Container.prototype.getChildIndex = function getChildIndex(child) { + var index = this.children.indexOf(child); + + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + }; + + /** + * Changes the position of an existing child in the display object container + * + * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number + * @param {number} index - The resulting index number for the child display object + */ + + + Container.prototype.setChildIndex = function setChildIndex(child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error('The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + var currentIndex = this.getChildIndex(child); + + (0, _utils.removeItems)(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + + this.onChildrenChange(index); + }; + + /** + * Returns the child at the specified index + * + * @param {number} index - The index to get the child at + * @return {PIXI.DisplayObject} The child at the given index, if any. + */ + + + Container.prototype.getChildAt = function getChildAt(index) { + if (index < 0 || index >= this.children.length) { + throw new Error('getChildAt: Index (' + index + ') does not exist.'); + } + + return this.children[index]; + }; + + /** + * Removes one or more children from the container. + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove + * @return {PIXI.DisplayObject} The first child that was removed. + */ + + + Container.prototype.removeChild = function removeChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.removeChild(arguments[i]); + } + } else { + var index = this.children.indexOf(child); + + if (index === -1) return null; + + child.parent = null; + // ensure child transform will be recalculated + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + } + + return child; + }; + + /** + * Removes a child from the specified index position. + * + * @param {number} index - The index to get the child from + * @return {PIXI.DisplayObject} The child that was removed. + */ + + + Container.prototype.removeChildAt = function removeChildAt(index) { + var child = this.getChildAt(index); + + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + + return child; + }; + + /** + * Removes all children from this container that are within the begin and end indexes. + * + * @param {number} [beginIndex=0] - The beginning position. + * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. + * @returns {DisplayObject[]} List of removed children + */ + + + Container.prototype.removeChildren = function removeChildren() { + var beginIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var endIndex = arguments[1]; + + var begin = beginIndex; + var end = typeof endIndex === 'number' ? endIndex : this.children.length; + var range = end - begin; + var removed = void 0; + + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } + + this._boundsID++; + + this.onChildrenChange(beginIndex); + + for (var _i = 0; _i < removed.length; ++_i) { + removed[_i].emit('removed', this); + } + + return removed; + } else if (range === 0 && this.children.length === 0) { + return []; + } + + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + }; + + /** + * Updates the transform on all children of this container for rendering + */ + + + Container.prototype.updateTransform = function updateTransform() { + this._boundsID++; + + this.transform.updateTransform(this.parent.transform); + + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + + if (child.visible) { + child.updateTransform(); + } + } + }; + + /** + * Recalculates the bounds of the container. + * + */ + + + Container.prototype.calculateBounds = function calculateBounds() { + this._bounds.clear(); + + this._calculateBounds(); + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (!child.visible || !child.renderable) { + continue; + } + + child.calculateBounds(); + + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + child._mask.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, child._mask._bounds); + } else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } else { + this._bounds.addBounds(child._bounds); + } + } + + this._lastBoundsID = this._boundsID; + }; + + /** + * Recalculates the bounds of the object. Override this to + * calculate the bounds of the specific object (not including children). + * + */ + + + Container.prototype._calculateBounds = function _calculateBounds() {} + // FILL IN// + + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderWebGL = function renderWebGL(renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + // do a quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) { + this.renderAdvancedWebGL(renderer); + } else { + this._renderWebGL(renderer); + + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderWebGL(renderer); + } + } + }; + + /** + * Render the object using the WebGL renderer and advanced features. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { + renderer.flush(); + + var filters = this._filters; + var mask = this._mask; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + + this._enabledFilters.length = 0; + + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + + if (this._enabledFilters.length) { + renderer.filterManager.pushFilter(this, this._enabledFilters); + } + } + + if (mask) { + renderer.maskManager.pushMask(this, this._mask); + } + + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); + + // now loop through the children and make sure they get rendered + for (var _i2 = 0, j = this.children.length; _i2 < j; _i2++) { + this.children[_i2].renderWebGL(renderer); + } + + renderer.flush(); + + if (mask) { + renderer.maskManager.popMask(this, this._mask); + } + + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filterManager.popFilter(); + } + }; + + /** + * To be overridden by the subclasses. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype._renderWebGL = function _renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * To be overridden by the subclass + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype._renderCanvas = function _renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderCanvas = function renderCanvas(renderer) { + // if not visible or the alpha is 0 then no need to render this + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + if (this._mask) { + renderer.maskManager.pushMask(this._mask); + } + + this._renderCanvas(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderCanvas(renderer); + } + + if (this._mask) { + renderer.maskManager.popMask(renderer); + } + }; + + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Container.prototype.destroy = function destroy(options) { + _DisplayObject.prototype.destroy.call(this); + + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + + var oldChildren = this.removeChildren(0, this.children.length); + + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + }; + + /** + * The width of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Container, [{ + key: 'width', + get: function get() { + return this.scale.x * this.getLocalBounds().width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var width = this.getLocalBounds().width; + + if (width !== 0) { + this.scale.x = value / width; + } else { + this.scale.x = 1; + } + + this._width = value; + } + + /** + * The height of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.scale.y * this.getLocalBounds().height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var height = this.getLocalBounds().height; + + if (height !== 0) { + this.scale.y = value / height; + } else { + this.scale.y = 1; + } + + this._height = value; + } + }]); + + return Container; +}(_DisplayObject3.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = Container; +Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + +},{"../utils":125,"./DisplayObject":49}],49:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TransformStatic = require('./TransformStatic'); + +var _TransformStatic2 = _interopRequireDefault(_TransformStatic); + +var _Transform = require('./Transform'); + +var _Transform2 = _interopRequireDefault(_Transform); + +var _Bounds = require('./Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _math = require('../math'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// _tempDisplayObjectParent = new DisplayObject(); + +/** + * The base class for all objects that are rendered on the screen. + * This is an abstract class and should not be used on its own rather it should be extended. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var DisplayObject = function (_EventEmitter) { + _inherits(DisplayObject, _EventEmitter); + + /** + * + */ + function DisplayObject() { + _classCallCheck(this, DisplayObject); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + var TransformClass = _settings2.default.TRANSFORM_MODE === _const.TRANSFORM_MODE.STATIC ? _TransformStatic2.default : _Transform2.default; + + _this.tempDisplayObjectParent = null; + + // TODO: need to create Transform from factory + /** + * World transform and local transform of this object. + * This will become read-only later, please do not assign anything there unless you know what are you doing + * + * @member {PIXI.TransformBase} + */ + _this.transform = new TransformClass(); + + /** + * The opacity of the object. + * + * @member {number} + */ + _this.alpha = 1; + + /** + * The visibility of the object. If false the object will not be drawn, and + * the updateTransform function will not be called. + * + * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually + * + * @member {boolean} + */ + _this.visible = true; + + /** + * Can this object be rendered, if false the object will not be drawn but the updateTransform + * methods will still be called. + * + * Only affects recursive calls from parent. You can ask for bounds manually + * + * @member {boolean} + */ + _this.renderable = true; + + /** + * The display object container that contains this display object. + * + * @member {PIXI.Container} + * @readonly + */ + _this.parent = null; + + /** + * The multiplied alpha of the displayObject + * + * @member {number} + * @readonly + */ + _this.worldAlpha = 1; + + /** + * The area the filter is applied to. This is used as more of an optimisation + * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle + * + * Also works as an interaction mask + * + * @member {PIXI.Rectangle} + */ + _this.filterArea = null; + + _this._filters = null; + _this._enabledFilters = null; + + /** + * The bounds object, this is used to calculate and store the bounds of the displayObject + * + * @member {PIXI.Rectangle} + * @private + */ + _this._bounds = new _Bounds2.default(); + _this._boundsID = 0; + _this._lastBoundsID = -1; + _this._boundsRect = null; + _this._localBoundsRect = null; + + /** + * The original, cached mask of the object + * + * @member {PIXI.Graphics|PIXI.Sprite} + * @private + */ + _this._mask = null; + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + + /** + * Fired when this DisplayObject is added to a Container. + * + * @event PIXI.DisplayObject#added + * @param {PIXI.Container} container - The container added to. + */ + + /** + * Fired when this DisplayObject is removed from a Container. + * + * @event PIXI.DisplayObject#removed + * @param {PIXI.Container} container - The container removed from. + */ + return _this; + } + + /** + * @private + * @member {PIXI.DisplayObject} + */ + + + /** + * Updates the object transform for rendering + * + * TODO - Optimization pass! + */ + DisplayObject.prototype.updateTransform = function updateTransform() { + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + this._bounds.updateID++; + }; + + /** + * recursively updates transform of all objects from the root to this one + * internal function for toLocal() + */ + + + DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform() { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + }; + + /** + * Retrieves the bounds of the displayObject as a rectangle object. + * + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @param {PIXI.Rectangle} rect - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getBounds = function getBounds(skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + + if (this._boundsID !== this._lastBoundsID) { + this.calculateBounds(); + } + + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new _math.Rectangle(); + } + + rect = this._boundsRect; + } + + return this._bounds.getRectangle(rect); + }; + + /** + * Retrieves the local bounds of the displayObject as a rectangle object + * + * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getLocalBounds = function getLocalBounds(rect) { + var transformRef = this.transform; + var parentRef = this.parent; + + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + var bounds = this.getBounds(false, rect); + + this.parent = parentRef; + this.transform = transformRef; + + return bounds; + }; + + /** + * Calculates the global position of the display object + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform. + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toGlobal = function toGlobal(position, point) { + var skipUpdate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; + + /** + * Calculates the local position of the display object relative to another point + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toLocal = function toLocal(position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + DisplayObject.prototype.renderCanvas = function renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Set the parent Container of this DisplayObject + * + * @param {PIXI.Container} container - The Container to add this DisplayObject to + * @return {PIXI.Container} The Container that this DisplayObject was added to + */ + ; + + DisplayObject.prototype.setParent = function setParent(container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); + } + + container.addChild(this); + + return container; + }; + + /** + * Convenience function to set the position, scale, skew and pivot at once. + * + * @param {number} [x=0] - The X position + * @param {number} [y=0] - The Y position + * @param {number} [scaleX=1] - The X scale value + * @param {number} [scaleY=1] - The Y scale value + * @param {number} [rotation=0] - The rotation + * @param {number} [skewX=0] - The X skew value + * @param {number} [skewY=0] - The Y skew value + * @param {number} [pivotX=0] - The X pivot value + * @param {number} [pivotY=0] - The Y pivot value + * @return {PIXI.DisplayObject} The DisplayObject instance + */ + + + DisplayObject.prototype.setTransform = function setTransform() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var scaleX = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var scaleY = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var rotation = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var skewX = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + var skewY = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + var pivotX = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; + var pivotY = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0; + + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + + return this; + }; + + /** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy`. + * + */ + + + DisplayObject.prototype.destroy = function destroy() { + this.removeAllListeners(); + if (this.parent) { + this.parent.removeChild(this); + } + this.transform = null; + + this.parent = null; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this.filterArea = null; + + this.interactive = false; + this.interactiveChildren = false; + + this._destroyed = true; + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + * + * @member {number} + */ + + + _createClass(DisplayObject, [{ + key: '_tempDisplayObjectParent', + get: function get() { + if (this.tempDisplayObjectParent === null) { + this.tempDisplayObjectParent = new DisplayObject(); + } + + return this.tempDisplayObjectParent; + } + }, { + key: 'x', + get: function get() { + return this.position.x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.x = value; + } + + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + * + * @member {number} + */ + + }, { + key: 'y', + get: function get() { + return this.position.y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.y = value; + } + + /** + * Current transform of the object based on world (parent) factors + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'worldTransform', + get: function get() { + return this.transform.worldTransform; + } + + /** + * Current transform of the object based on local factors: position, scale, other stuff + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'localTransform', + get: function get() { + return this.transform.localTransform; + } + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'position', + get: function get() { + return this.transform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.copy(value); + } + + /** + * The scale factor of the object. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'scale', + get: function get() { + return this.transform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.scale.copy(value); + } + + /** + * The pivot point of the displayObject that it rotates around. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'pivot', + get: function get() { + return this.transform.pivot; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.pivot.copy(value); + } + + /** + * The skew factor for the object in radians. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'skew', + get: function get() { + return this.transform.skew; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.skew.copy(value); + } + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + }, { + key: 'rotation', + get: function get() { + return this.transform.rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.rotation = value; + } + + /** + * Indicates if the object is globally visible. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'worldVisible', + get: function get() { + var item = this; + + do { + if (!item.visible) { + return false; + } + + item = item.parent; + } while (item); + + return true; + } + + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PIXI a regular mask must be a + * PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it + * utilises shape clipping. To remove a mask, set this property to null. + * + * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + * + * @member {PIXI.Graphics|PIXI.Sprite} + */ + + }, { + key: 'mask', + get: function get() { + return this._mask; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._mask) { + this._mask.renderable = true; + this._mask.isMask = false; + } + + this._mask = value; + + if (this._mask) { + this._mask.renderable = false; + this._mask.isMask = true; + } + } + + /** + * Sets the filters for the displayObject. + * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * To remove filters simply set this property to 'null' + * + * @member {PIXI.Filter[]} + */ + + }, { + key: 'filters', + get: function get() { + return this._filters && this._filters.slice(); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._filters = value && value.slice(); + } + }]); + + return DisplayObject; +}(_eventemitter2.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = DisplayObject; +DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + +},{"../const":46,"../math":70,"../settings":101,"./Bounds":47,"./Transform":50,"./TransformStatic":52,"eventemitter3":3}],50:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Generic class to deal with traditional 2D matrix transforms + * local transformation is calculated from position,scale,skew and rotation + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var Transform = function (_TransformBase) { + _inherits(Transform, _TransformBase); + + /** + * + */ + function Transform() { + _classCallCheck(this, Transform); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.Point} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.Point(0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.Point} + */ + _this.scale = new _math.Point(1, 1); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + /** + * The pivot point of the displayObject that it rotates around. + * + * @member {PIXI.Point} + */ + _this.pivot = new _math.Point(0, 0); + + /** + * The rotation value of the object, in radians + * + * @member {Number} + * @private + */ + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + return _this; + } + + /** + * Updates the skew values when the skew or rotation changes. + * + * @private + */ + + + Transform.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + }; + + /** + * Updates only local matrix + */ + + + Transform.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + Transform.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + Transform.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(Transform, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return Transform; +}(_TransformBase3.default); + +exports.default = Transform; + +},{"../math":70,"./TransformBase":51}],51:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Generic class to deal with traditional 2D matrix transforms + * + * @class + * @memberof PIXI + */ +var TransformBase = function () { + /** + * + */ + function TransformBase() { + _classCallCheck(this, TransformBase); + + /** + * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds() + * + * @member {PIXI.Matrix} + */ + this.worldTransform = new _math.Matrix(); + + /** + * The local matrix transform + * + * @member {PIXI.Matrix} + */ + this.localTransform = new _math.Matrix(); + + this._worldID = 0; + this._parentID = 0; + } + + /** + * TransformBase does not have decomposition, so this function wont do anything + */ + + + TransformBase.prototype.updateLocalTransform = function updateLocalTransform() {} + // empty + + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.TransformBase} parentTransform - The transform of the parent of this object + */ + ; + + TransformBase.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + return TransformBase; +}(); + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ + + +exports.default = TransformBase; +TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; + +TransformBase.IDENTITY = new TransformBase(); + +},{"../math":70}],52:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Transform that takes care about its versions + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var TransformStatic = function (_TransformBase) { + _inherits(TransformStatic, _TransformBase); + + /** + * + */ + function TransformStatic() { + _classCallCheck(this, TransformStatic); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.ObservablePoint} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.ObservablePoint} + */ + _this.scale = new _math.ObservablePoint(_this.onChange, _this, 1, 1); + + /** + * The pivot point of the displayObject that it rotates around. + * + * @member {PIXI.ObservablePoint} + */ + _this.pivot = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + + _this._localID = 0; + _this._currentLocalID = 0; + return _this; + } + + /** + * Called when a value changes. + * + * @private + */ + + + TransformStatic.prototype.onChange = function onChange() { + this._localID++; + }; + + /** + * Called when skew or rotation changes + * + * @private + */ + + + TransformStatic.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + + this._localID++; + }; + + /** + * Updates only local matrix + */ + + + TransformStatic.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + TransformStatic.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._parentID = parentTransform._worldID; + + // update the id of the transform.. + this._worldID++; + } + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + TransformStatic.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + this._localID++; + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(TransformStatic, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return TransformStatic; +}(_TransformBase3.default); + +exports.default = TransformStatic; + +},{"../math":70,"./TransformBase":51}],53:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _GraphicsData = require('./GraphicsData'); + +var _GraphicsData2 = _interopRequireDefault(_GraphicsData); + +var _Sprite = require('../sprites/Sprite'); + +var _Sprite2 = _interopRequireDefault(_Sprite); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Bounds = require('../display/Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _bezierCurveTo2 = require('./utils/bezierCurveTo'); + +var _bezierCurveTo3 = _interopRequireDefault(_bezierCurveTo2); + +var _CanvasRenderer = require('../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var canvasRenderer = void 0; +var tempMatrix = new _math.Matrix(); +var tempPoint = new _math.Point(); +var tempColor1 = new Float32Array(4); +var tempColor2 = new Float32Array(4); + +/** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Graphics = function (_Container) { + _inherits(Graphics, _Container); + + /** + * + * @param {boolean} [nativeLines=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + */ + function Graphics() { + var nativeLines = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + _classCallCheck(this, Graphics); + + /** + * The alpha value used when filling the Graphics object. + * + * @member {number} + * @default 1 + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @member {number} + * @default 0 + */ + _this.lineWidth = 0; + + /** + * If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * + * @member {boolean} + */ + _this.nativeLines = nativeLines; + + /** + * The color of any lines drawn. + * + * @member {string} + * @default 0 + */ + _this.lineColor = 0; + + /** + * The alignment of any lines drawn (0.5 = middle, 1 = outter, 0 = inner). + * + * @member {number} + * @default 0 + */ + _this.lineAlignment = 0.5; + + /** + * Graphics data + * + * @member {PIXI.GraphicsData[]} + * @private + */ + _this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to + * reset the tint. + * + * @member {number} + * @default 0xFFFFFF + */ + _this.tint = 0xFFFFFF; + + /** + * The previous tint applied to the graphic shape. Used to compare to the current tint and + * check if theres change. + * + * @member {number} + * @private + * @default 0xFFFFFF + */ + _this._prevTint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * Current path + * + * @member {PIXI.GraphicsData} + * @private + */ + _this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @member {object} + * @private + */ + // TODO - _webgl should use a prototype object, not a random undocumented object... + _this._webGL = {}; + + /** + * Whether this shape is being used as a mask. + * + * @member {boolean} + */ + _this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @member {number} + */ + _this.boundsPadding = 0; + + /** + * A cache of the local bounds to prevent recalculation. + * + * @member {PIXI.Rectangle} + * @private + */ + _this._localBounds = new _Bounds2.default(); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics + * object will be recalculated. + * + * @member {boolean} + * @private + */ + _this.dirty = 0; + + /** + * Used to detect if we need to do a fast rect check using the id compare method + * @type {Number} + */ + _this.fastRectDirty = -1; + + /** + * Used to detect if we clear the graphics webGL data + * @type {Number} + */ + _this.clearDirty = 0; + + /** + * Used to detect if we we need to recalculate local bounds + * @type {Number} + */ + _this.boundsDirty = -1; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @member {boolean} + * @private + */ + _this.cachedSpriteDirty = false; + + _this._spriteRect = null; + _this._fastRect = false; + + _this._prevRectTint = null; + _this._prevRectFillColor = null; + + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ + return _this; + } + + /** + * Creates a new Graphics object with the same values as this one. + * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) + * + * @return {PIXI.Graphics} A clone of the graphics object + */ + + + Graphics.prototype.clone = function clone() { + var clone = new Graphics(); + + clone.renderable = this.renderable; + clone.fillAlpha = this.fillAlpha; + clone.lineWidth = this.lineWidth; + clone.lineColor = this.lineColor; + clone.lineAlignment = this.lineAlignment; + clone.tint = this.tint; + clone.blendMode = this.blendMode; + clone.isMask = this.isMask; + clone.boundsPadding = this.boundsPadding; + clone.dirty = 0; + clone.cachedSpriteDirty = this.cachedSpriteDirty; + + // copy graphics data + for (var i = 0; i < this.graphicsData.length; ++i) { + clone.graphicsData.push(this.graphicsData[i].clone()); + } + + clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; + + clone.updateLocalBounds(); + + return clone; + }; + + /** + * Calculate length of quadratic curve + * @see {@link http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/} + * for the detailed explanation of math behind this. + * + * @private + * @param {number} fromX - x-coordinate of curve start point + * @param {number} fromY - y-coordinate of curve start point + * @param {number} cpX - x-coordinate of curve control point + * @param {number} cpY - y-coordinate of curve control point + * @param {number} toX - x-coordinate of curve end point + * @param {number} toY - y-coordinate of curve end point + * @return {number} Length of quadratic curve + */ + + + Graphics.prototype._quadraticCurveLength = function _quadraticCurveLength(fromX, fromY, cpX, cpY, toX, toY) { + var ax = fromX - (2.0 * cpX + toX); + var ay = fromY - (2.0 * cpY + toY); + var bx = 2.0 * ((cpX - 2.0) * fromX); + var by = 2.0 * ((cpY - 2.0) * fromY); + var a = 4.0 * (ax * ax + ay * ay); + var b = 4.0 * (ax * bx + ay * by); + var c = bx * bx + by * by; + + var s = 2.0 * Math.sqrt(a + b + c); + var a2 = Math.sqrt(a); + var a32 = 2.0 * a * a2; + var c2 = 2.0 * Math.sqrt(c); + var ba = b / a2; + + return (a32 * s + a2 * b * (s - c2) + (4.0 * c * a - b * b) * Math.log((2.0 * a2 + ba + s) / (ba + c2))) / (4.0 * a32); + }; + + /** + * Calculate length of bezier curve. + * Analytical solution is impossible, since it involves an integral that does not integrate in general. + * Therefore numerical solution is used. + * + * @private + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {number} Length of bezier curve + */ + + + Graphics.prototype._bezierCurveLength = function _bezierCurveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var n = 10; + var result = 0.0; + var t = 0.0; + var t2 = 0.0; + var t3 = 0.0; + var nt = 0.0; + var nt2 = 0.0; + var nt3 = 0.0; + var x = 0.0; + var y = 0.0; + var dx = 0.0; + var dy = 0.0; + var prevX = fromX; + var prevY = fromY; + + for (var i = 1; i <= n; ++i) { + t = i / n; + t2 = t * t; + t3 = t2 * t; + nt = 1.0 - t; + nt2 = nt * nt; + nt3 = nt2 * nt; + + x = nt3 * fromX + 3.0 * nt2 * t * cpX + 3.0 * nt * t2 * cpX2 + t3 * toX; + y = nt3 * fromY + 3.0 * nt2 * t * cpY + 3 * nt * t2 * cpY2 + t3 * toY; + dx = prevX - x; + dy = prevY - y; + prevX = x; + prevY = y; + + result += Math.sqrt(dx * dx + dy * dy); + } + + return result; + }; + + /** + * Calculate number of segments for the curve based on its length to ensure its smoothness. + * + * @private + * @param {number} length - length of curve + * @return {number} Number of segments + */ + + + Graphics.prototype._segmentsCount = function _segmentsCount(length) { + var result = Math.ceil(length / Graphics.CURVES.maxLength); + + if (result < Graphics.CURVES.minSegments) { + result = Graphics.CURVES.minSegments; + } else if (result > Graphics.CURVES.maxSegments) { + result = Graphics.CURVES.maxSegments; + } + + return result; + }; + + /** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() + * method or the drawCircle() method. + * + * @param {number} [lineWidth=0] - width of the line to draw, will update the objects stored style + * @param {number} [color=0] - color of the line to draw, will update the objects stored style + * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style + * @param {number} [alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineStyle = function lineStyle() { + var lineWidth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var alpha = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var alignment = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0.5; + + this.lineWidth = lineWidth; + this.lineColor = color; + this.lineAlpha = alpha; + this.lineAlignment = alignment; + + if (this.currentPath) { + if (this.currentPath.shape.points.length) { + // halfway through a line? start a new one! + var shape = new _math.Polygon(this.currentPath.shape.points.slice(-2)); + + shape.closed = false; + + this.drawShape(shape); + } else { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + this.currentPath.lineAlignment = this.lineAlignment; + } + } + + return this; + }; + + /** + * Moves the current drawing position to x, y. + * + * @param {number} x - the X coordinate to move to + * @param {number} y - the Y coordinate to move to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.moveTo = function moveTo(x, y) { + var shape = new _math.Polygon([x, y]); + + shape.closed = false; + this.drawShape(shape); + + return this; + }; + + /** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @param {number} x - the X coordinate to draw to + * @param {number} y - the Y coordinate to draw to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineTo = function lineTo(x, y) { + var points = this.currentPath.shape.points; + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + if (fromX !== x || fromY !== y) { + points.push(x, y); + this.dirty++; + } + + return this; + }; + + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.quadraticCurveTo = function quadraticCurveTo(cpX, cpY, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + var xa = 0; + var ya = 0; + + if (points.length === 0) { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var n = Graphics.CURVES.adaptive ? this._segmentsCount(this._quadraticCurveLength(fromX, fromY, cpX, cpY, toX, toY)) : 20; + + for (var i = 1; i <= n; ++i) { + var j = i / n; + + xa = fromX + (cpX - fromX) * j; + ya = fromY + (cpY - fromY) * j; + + points.push(xa + (cpX + (toX - cpX) * j - xa) * j, ya + (cpY + (toY - cpY) * j - ya) * j); + } + + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a bezier curve and then draws it. + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.bezierCurveTo = function bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + points.length -= 2; + + var n = Graphics.CURVES.adaptive ? this._segmentsCount(this._bezierCurveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY)) : 20; + + (0, _bezierCurveTo3.default)(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, n, points); + + this.dirty++; + + return this; + }; + + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @param {number} x1 - The x-coordinate of the beginning of the arc + * @param {number} y1 - The y-coordinate of the beginning of the arc + * @param {number} x2 - The x-coordinate of the end of the arc + * @param {number} y2 - The y-coordinate of the end of the arc + * @param {number} radius - The radius of the arc + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arcTo = function arcTo(x1, y1, x2, y2, radius) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points.push(x1, y1); + } + } else { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + } else { + var dd = a1 * a1 + b1 * b1; + var cc = a2 * a2 + b2 * b2; + var tt = a1 * a2 + b1 * b2; + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = k1 * b2 + k2 * b1; + var cy = k1 * a2 + k2 * a1; + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty++; + + return this; + }; + + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @param {number} cx - The x-coordinate of the center of the circle + * @param {number} cy - The y-coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param {number} endAngle - The ending angle, in radians + * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arc = function arc(cx, cy, radius, startAngle, endAngle) { + var anticlockwise = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; + + if (startAngle === endAngle) { + return this; + } + + if (!anticlockwise && endAngle <= startAngle) { + endAngle += _const.PI_2; + } else if (anticlockwise && startAngle <= endAngle) { + startAngle += _const.PI_2; + } + + var sweep = endAngle - startAngle; + var segs = Graphics.CURVES.adaptive ? this._segmentsCount(Math.abs(sweep) * radius) : Math.ceil(Math.abs(sweep) / _const.PI_2) * 40; + + if (sweep === 0) { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. + var points = this.currentPath ? this.currentPath.shape.points : null; + + if (points) { + // We check how far our start is from the last existing point + var xDiff = Math.abs(points[points.length - 2] - startX); + var yDiff = Math.abs(points[points.length - 1] - startY); + + if (xDiff < 0.001 && yDiff < 0.001) { + // If the point is very close, we don't add it, since this would lead to artifacts + // during tesselation due to floating point imprecision. + } else { + points.push(startX, startY); + } + } else { + this.moveTo(startX, startY); + points = this.currentPath.shape.points; + } + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = segMinus % 1 / segMinus; + + for (var i = 0; i <= segMinus; ++i) { + var real = i + remainder * i; + + var angle = theta + startAngle + theta2 * real; + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push((cTheta * c + sTheta * s) * radius + cx, (cTheta * -s + sTheta * c) * radius + cy); + } + + this.dirty++; + + return this; + }; + + /** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @param {number} [color=0] - the color of the fill + * @param {number} [alpha=1] - the alpha of the fill + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.beginFill = function beginFill() { + var color = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var alpha = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.filling = true; + this.fillColor = color; + this.fillAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length <= 2) { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + }; + + /** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.endFill = function endFill() { + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRect = function drawRect(x, y, width, height) { + this.drawShape(new _math.Rectangle(x, y, width, height)); + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @param {number} radius - Radius of the rectangle corners + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRoundedRect = function drawRoundedRect(x, y, width, height, radius) { + this.drawShape(new _math.RoundedRectangle(x, y, width, height, radius)); + + return this; + }; + + /** + * Draws a circle. + * + * @param {number} x - The X coordinate of the center of the circle + * @param {number} y - The Y coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawCircle = function drawCircle(x, y, radius) { + this.drawShape(new _math.Circle(x, y, radius)); + + return this; + }; + + /** + * Draws an ellipse. + * + * @param {number} x - The X coordinate of the center of the ellipse + * @param {number} y - The Y coordinate of the center of the ellipse + * @param {number} width - The half width of the ellipse + * @param {number} height - The half height of the ellipse + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawEllipse = function drawEllipse(x, y, width, height) { + this.drawShape(new _math.Ellipse(x, y, width, height)); + + return this; + }; + + /** + * Draws a polygon using the given path. + * + * @param {number[]|PIXI.Point[]|PIXI.Polygon} path - The path data used to construct the polygon. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawPolygon = function drawPolygon(path) { + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + var closed = true; + + if (points instanceof _math.Polygon) { + closed = points.closed; + points = points.points; + } + + if (!Array.isArray(points)) { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) { + points[i] = arguments[i]; // eslint-disable-line prefer-rest-params + } + } + + var shape = new _math.Polygon(points); + + shape.closed = closed; + + this.drawShape(shape); + + return this; + }; + + /** + * Draw a star shape with an abitrary number of points. + * + * @param {number} x - Center X position of the star + * @param {number} y - Center Y position of the star + * @param {number} points - The number of points of the star, must be > 1 + * @param {number} radius - The outer radius of the star + * @param {number} [innerRadius] - The inner radius between points, default half `radius` + * @param {number} [rotation=0] - The rotation of the star in radians, where 0 is vertical + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawStar = function drawStar(x, y, points, radius, innerRadius) { + var rotation = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + + innerRadius = innerRadius || radius / 2; + + var startAngle = -1 * Math.PI / 2 + rotation; + var len = points * 2; + var delta = _const.PI_2 / len; + var polygon = []; + + for (var i = 0; i < len; i++) { + var r = i % 2 ? innerRadius : radius; + var angle = i * delta + startAngle; + + polygon.push(x + r * Math.cos(angle), y + r * Math.sin(angle)); + } + + return this.drawPolygon(polygon); + }; + + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.clear = function clear() { + if (this.lineWidth || this.filling || this.graphicsData.length > 0) { + this.lineWidth = 0; + this.lineAlignment = 0.5; + + this.filling = false; + + this.boundsDirty = -1; + this.canvasTintDirty = -1; + this.dirty++; + this.clearDirty++; + this.graphicsData.length = 0; + } + + this.currentPath = null; + this._spriteRect = null; + + return this; + }; + + /** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. + * + * @returns {boolean} True if only 1 rect. + */ + + + Graphics.prototype.isFastRect = function isFastRect() { + return this.graphicsData.length === 1 && this.graphicsData[0].shape.type === _const.SHAPES.RECT && !this.graphicsData[0].lineWidth; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderWebGL = function _renderWebGL(renderer) { + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.dirty !== this.fastRectDirty) { + this.fastRectDirty = this.dirty; + this._fastRect = this.isFastRect(); + } + + // TODO this check can be moved to dirty? + if (this._fastRect) { + this._renderSpriteRect(renderer); + } else { + renderer.setObjectRenderer(renderer.plugins.graphics); + renderer.plugins.graphics.render(this); + } + }; + + /** + * Renders a sprite rectangle. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderSpriteRect = function _renderSpriteRect(renderer) { + var rect = this.graphicsData[0].shape; + + if (!this._spriteRect) { + this._spriteRect = new _Sprite2.default(new _Texture2.default(_Texture2.default.WHITE)); + } + + var sprite = this._spriteRect; + var fillColor = this.graphicsData[0].fillColor; + + if (this.tint === 0xffffff) { + sprite.tint = fillColor; + } else if (this.tint !== this._prevRectTint || fillColor !== this._prevRectFillColor) { + var t1 = tempColor1; + var t2 = tempColor2; + + (0, _utils.hex2rgb)(fillColor, t1); + (0, _utils.hex2rgb)(this.tint, t2); + + t1[0] *= t2[0]; + t1[1] *= t2[1]; + t1[2] *= t2[2]; + + sprite.tint = (0, _utils.rgb2hex)(t1); + + this._prevRectTint = this.tint; + this._prevRectFillColor = fillColor; + } + + sprite.alpha = this.graphicsData[0].fillAlpha; + sprite.worldAlpha = this.worldAlpha * sprite.alpha; + sprite.blendMode = this.blendMode; + + sprite._texture._frame.width = rect.width; + sprite._texture._frame.height = rect.height; + + sprite.transform.worldTransform = this.transform.worldTransform; + + sprite.anchor.set(-rect.x / rect.width, -rect.y / rect.height); + sprite._onAnchorUpdate(); + + sprite._renderWebGL(renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.isMask === true) { + return; + } + + renderer.plugins.graphics.render(this); + }; + + /** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @private + */ + + + Graphics.prototype._calculateBounds = function _calculateBounds() { + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.updateLocalBounds(); + + this.cachedSpriteDirty = true; + } + + var lb = this._localBounds; + + this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); + }; + + /** + * Tests if a point is inside this graphics object + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Graphics.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + + if (!data.fill) { + continue; + } + + // only deal with fills.. + if (data.shape) { + if (data.shape.contains(tempPoint.x, tempPoint.y)) { + if (data.holes) { + for (var _i = 0; _i < data.holes.length; _i++) { + var hole = data.holes[_i]; + + if (hole.contains(tempPoint.x, tempPoint.y)) { + return false; + } + } + } + + return true; + } + } + } + + return false; + }; + + /** + * Update the bounds of the object + * + */ + + + Graphics.prototype.updateLocalBounds = function updateLocalBounds() { + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) { + var shape = 0; + var x = 0; + var y = 0; + var w = 0; + var h = 0; + + for (var i = 0; i < this.graphicsData.length; i++) { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + + shape = data.shape; + + if (type === _const.SHAPES.RECT || type === _const.SHAPES.RREC) { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.CIRC) { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.ELIP) { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else { + // POLY + var points = shape.points; + var x2 = 0; + var y2 = 0; + var dx = 0; + var dy = 0; + var rw = 0; + var rh = 0; + var cx = 0; + var cy = 0; + + for (var j = 0; j + 2 < points.length; j += 2) { + x = points[j]; + y = points[j + 1]; + x2 = points[j + 2]; + y2 = points[j + 3]; + dx = Math.abs(x2 - x); + dy = Math.abs(y2 - y); + h = lineWidth; + w = Math.sqrt(dx * dx + dy * dy); + + if (w < 1e-9) { + continue; + } + + rw = (h / w * dy + dx) / 2; + rh = (h / w * dx + dy) / 2; + cx = (x2 + x) / 2; + cy = (y2 + y) / 2; + + minX = cx - rw < minX ? cx - rw : minX; + maxX = cx + rw > maxX ? cx + rw : maxX; + + minY = cy - rh < minY ? cy - rh : minY; + maxY = cy + rh > maxY ? cy + rh : maxY; + } + } + } + } else { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.minX = minX - padding; + this._localBounds.maxX = maxX + padding; + + this._localBounds.minY = minY - padding; + this._localBounds.maxY = maxY + padding; + }; + + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @return {PIXI.GraphicsData} The generated GraphicsData object. + */ + + + Graphics.prototype.drawShape = function drawShape(shape) { + if (this.currentPath) { + // check current path! + if (this.currentPath.shape.points.length <= 2) { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + var data = new _GraphicsData2.default(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, this.nativeLines, shape, this.lineAlignment); + + this.graphicsData.push(data); + + if (data.type === _const.SHAPES.POLY) { + data.shape.closed = data.shape.closed; + this.currentPath = data; + } + + this.dirty++; + + return data; + }; + + /** + * Generates a canvas texture. + * + * @param {number} scaleMode - The scale mode of the texture. + * @param {number} resolution - The resolution of the texture. + * @return {PIXI.Texture} The new texture. + */ + + + Graphics.prototype.generateCanvasTexture = function generateCanvasTexture(scaleMode) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + var bounds = this.getLocalBounds(); + + var canvasBuffer = _RenderTexture2.default.create(bounds.width, bounds.height, scaleMode, resolution); + + if (!canvasRenderer) { + canvasRenderer = new _CanvasRenderer2.default(); + } + + this.transform.updateLocalTransform(); + this.transform.localTransform.copy(tempMatrix); + + tempMatrix.invert(); + + tempMatrix.tx -= bounds.x; + tempMatrix.ty -= bounds.y; + + canvasRenderer.render(this, canvasBuffer, true, tempMatrix); + + var texture = _Texture2.default.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas, scaleMode, 'graphics'); + + texture.baseTexture.resolution = resolution; + texture.baseTexture.update(); + + return texture; + }; + + /** + * Closes the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.closePath = function closePath() { + // ok so close path assumes next one is a hole! + var currentPath = this.currentPath; + + if (currentPath && currentPath.shape) { + currentPath.shape.close(); + } + + return this; + }; + + /** + * Adds a hole in the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.addHole = function addHole() { + // this is a hole! + var hole = this.graphicsData.pop(); + + this.currentPath = this.graphicsData[this.graphicsData.length - 1]; + + this.currentPath.addHole(hole.shape); + this.currentPath = null; + + return this; + }; + + /** + * Destroys the Graphics object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Graphics.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._webGL) { + for (var j = 0; j < this._webGL[id].data.length; ++j) { + this._webGL[id].data[j].destroy(); + } + } + + if (this._spriteRect) { + this._spriteRect.destroy(); + } + + this.graphicsData = null; + + this.currentPath = null; + this._webGL = null; + this._localBounds = null; + }; + + return Graphics; +}(_Container3.default); + +exports.default = Graphics; + + +Graphics._SPRITE_TEXTURE = null; + +/** + * Graphics curves resolution settings. If `adaptive` flag is set to `true`, + * the resolution is calculated based on the curve's length to ensure better visual quality. + * Adaptive draw works with `bezierCurveTo` and `quadraticCurveTo`. + * + * @static + * @constant + * @memberof PIXI.Graphics + * @name CURVES + * @type {object} + * @property {boolean} adaptive=false - flag indicating if the resolution should be adaptive + * @property {number} maxLength=10 - maximal length of a single segment of the curve (if adaptive = false, ignored) + * @property {number} minSegments=8 - minimal number of segments in the curve (if adaptive = false, ignored) + * @property {number} maxSegments=2048 - maximal number of segments in the curve (if adaptive = false, ignored) + */ +Graphics.CURVES = { + adaptive: false, + maxLength: 10, + minSegments: 8, + maxSegments: 2048 +}; + +},{"../const":46,"../display/Bounds":47,"../display/Container":48,"../math":70,"../renderers/canvas/CanvasRenderer":77,"../sprites/Sprite":102,"../textures/RenderTexture":113,"../textures/Texture":115,"../utils":125,"./GraphicsData":54,"./utils/bezierCurveTo":56}],54:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + */ +var GraphicsData = function () { + /** + * + * @param {number} lineWidth - the width of the line to draw + * @param {number} lineColor - the color of the line to draw + * @param {number} lineAlpha - the alpha of the line to draw + * @param {number} fillColor - the color of the fill + * @param {number} fillAlpha - the alpha of the fill + * @param {boolean} fill - whether or not the shape is filled with a colour + * @param {boolean} nativeLines - the method for drawing lines + * @param {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} shape - The shape object to draw. + * @param {number} lineAlignment - the alignment of the line. + */ + function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, nativeLines, shape, lineAlignment) { + _classCallCheck(this, GraphicsData); + + /** + * the width of the line to draw + * @member {number} + */ + this.lineWidth = lineWidth; + + /** + * The alignment of any lines drawn (0.5 = middle, 1 = outter, 0 = inner). + * + * @member {number} + * @default 0 + */ + this.lineAlignment = lineAlignment; + + /** + * if true the liens will be draw using LINES instead of TRIANGLE_STRIP + * @member {boolean} + */ + this.nativeLines = nativeLines; + + /** + * the color of the line to draw + * @member {number} + */ + this.lineColor = lineColor; + + /** + * the alpha of the line to draw + * @member {number} + */ + this.lineAlpha = lineAlpha; + + /** + * cached tint of the line to draw + * @member {number} + * @private + */ + this._lineTint = lineColor; + + /** + * the color of the fill + * @member {number} + */ + this.fillColor = fillColor; + + /** + * the alpha of the fill + * @member {number} + */ + this.fillAlpha = fillAlpha; + + /** + * cached tint of the fill + * @member {number} + * @private + */ + this._fillTint = fillColor; + + /** + * whether or not the shape is filled with a colour + * @member {boolean} + */ + this.fill = fill; + + this.holes = []; + + /** + * The shape object to draw. + * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} + */ + this.shape = shape; + + /** + * The type of the shape, see the Const.Shapes file for all the existing types, + * @member {number} + */ + this.type = shape.type; + } + + /** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {PIXI.GraphicsData} Cloned GraphicsData object + */ + + + GraphicsData.prototype.clone = function clone() { + return new GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.fill, this.nativeLines, this.shape); + }; + + /** + * Adds a hole to the shape. + * + * @param {PIXI.Rectangle|PIXI.Circle} shape - The shape of the hole. + */ + + + GraphicsData.prototype.addHole = function addHole(shape) { + this.holes.push(shape); + }; + + /** + * Destroys the Graphics data. + */ + + + GraphicsData.prototype.destroy = function destroy() { + this.shape = null; + this.holes = null; + }; + + return GraphicsData; +}(); + +exports.default = GraphicsData; + +},{}],55:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they + * now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasGraphicsRenderer: + * https://github.com/libgdx/libgdx/blob/1.0.0/gdx/src/com/badlogic/gdx/graphics/glutils/ShapeRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching graphics objects. + * + * @class + * @private + * @memberof PIXI + */ +var CanvasGraphicsRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The current PIXI renderer. + */ + function CanvasGraphicsRenderer(renderer) { + _classCallCheck(this, CanvasGraphicsRenderer); + + this.renderer = renderer; + } + + /** + * Renders a Graphics object to a canvas. + * + * @param {PIXI.Graphics} graphics - the actual graphics object to render + */ + + + CanvasGraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var context = renderer.context; + var worldAlpha = graphics.worldAlpha; + var transform = graphics.transform.worldTransform; + var resolution = renderer.resolution; + + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // update tint if graphics was dirty + if (graphics.canvasTintDirty !== graphics.dirty || graphics._prevTint !== graphics.tint) { + this.updateGraphicsTint(graphics); + } + + renderer.setBlendMode(graphics.blendMode); + + for (var i = 0; i < graphics.graphicsData.length; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === _const.SHAPES.POLY) { + context.beginPath(); + + this.renderPolygon(shape.points, shape.closed, context); + + for (var j = 0; j < data.holes.length; j++) { + this.renderPolygon(data.holes[j].points, true, context); + } + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RECT) { + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + context.beginPath(); + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + }; + + /** + * Updates the tint of a graphics object + * + * @private + * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated + */ + + + CanvasGraphicsRenderer.prototype.updateGraphicsTint = function updateGraphicsTint(graphics) { + graphics._prevTint = graphics.tint; + graphics.canvasTintDirty = graphics.dirty; + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF) / 255; + + for (var i = 0; i < graphics.graphicsData.length; ++i) { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + // super inline, cos optimization :) + data._fillTint = ((fillColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (fillColor & 0xFF) / 255 * tintB * 255; + + data._lineTint = ((lineColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (lineColor & 0xFF) / 255 * tintB * 255; + } + }; + + /** + * Renders a polygon. + * + * @param {PIXI.Point[]} points - The points to render + * @param {boolean} close - Should the polygon be closed + * @param {CanvasRenderingContext2D} context - The rendering context to use + */ + + + CanvasGraphicsRenderer.prototype.renderPolygon = function renderPolygon(points, close, context) { + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; ++j) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (close) { + context.closePath(); + } + }; + + /** + * destroy graphics object + * + */ + + + CanvasGraphicsRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasGraphicsRenderer; +}(); + +exports.default = CanvasGraphicsRenderer; + + +_CanvasRenderer2.default.registerPlugin('graphics', CanvasGraphicsRenderer); + +},{"../../const":46,"../../renderers/canvas/CanvasRenderer":77}],56:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = bezierCurveTo; +/** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number} n - Number of segments approximating the bezier curve + * @param {number[]} [path=[]] - Path array to push points into + * @return {number[]} Array of points of the curve + */ +function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, n) { + var path = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : []; + + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + + path.push(fromX, fromY); + + for (var i = 1, j = 0; i <= n; ++i) { + j = i / n; + + dt = 1 - j; + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + path.push(dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + return path; +} + +},{}],57:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _WebGLGraphicsData = require('./WebGLGraphicsData'); + +var _WebGLGraphicsData2 = _interopRequireDefault(_WebGLGraphicsData); + +var _PrimitiveShader = require('./shaders/PrimitiveShader'); + +var _PrimitiveShader2 = _interopRequireDefault(_PrimitiveShader); + +var _buildPoly = require('./utils/buildPoly'); + +var _buildPoly2 = _interopRequireDefault(_buildPoly); + +var _buildRectangle = require('./utils/buildRectangle'); + +var _buildRectangle2 = _interopRequireDefault(_buildRectangle); + +var _buildRoundedRectangle = require('./utils/buildRoundedRectangle'); + +var _buildRoundedRectangle2 = _interopRequireDefault(_buildRoundedRectangle); + +var _buildCircle = require('./utils/buildCircle'); + +var _buildCircle2 = _interopRequireDefault(_buildCircle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Renders the graphics object. + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var GraphicsRenderer = function (_ObjectRenderer) { + _inherits(GraphicsRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this object renderer works for. + */ + function GraphicsRenderer(renderer) { + _classCallCheck(this, GraphicsRenderer); + + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.graphicsDataPool = []; + + _this.primitiveShader = null; + + _this.gl = renderer.gl; + + // easy access! + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * Called when there is a WebGL context change + * + * @private + * + */ + + + GraphicsRenderer.prototype.onContextChange = function onContextChange() { + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.primitiveShader = new _PrimitiveShader2.default(this.gl); + }; + + /** + * Destroys this renderer. + * + */ + + + GraphicsRenderer.prototype.destroy = function destroy() { + _ObjectRenderer3.default.prototype.destroy.call(this); + + for (var i = 0; i < this.graphicsDataPool.length; ++i) { + this.graphicsDataPool[i].destroy(); + } + + this.graphicsDataPool = null; + }; + + /** + * Renders a graphics object. + * + * @param {PIXI.Graphics} graphics - The graphics object to render. + */ + + + GraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var gl = renderer.gl; + + var webGLData = void 0; + var webGL = graphics._webGL[this.CONTEXT_UID]; + + if (!webGL || graphics.dirty !== webGL.dirty) { + this.updateGraphics(graphics); + + webGL = graphics._webGL[this.CONTEXT_UID]; + } + + // This could be speeded up for sure! + var shader = this.primitiveShader; + + renderer.bindShader(shader); + renderer.state.setBlendMode(graphics.blendMode); + + for (var i = 0, n = webGL.data.length; i < n; i++) { + webGLData = webGL.data[i]; + var shaderTemp = webGLData.shader; + + renderer.bindShader(shaderTemp); + shaderTemp.uniforms.translationMatrix = graphics.transform.worldTransform.toArray(true); + shaderTemp.uniforms.tint = (0, _utils.hex2rgb)(graphics.tint); + shaderTemp.uniforms.alpha = graphics.worldAlpha; + + renderer.bindVao(webGLData.vao); + + if (webGLData.nativeLines) { + gl.drawArrays(gl.LINES, 0, webGLData.points.length / 6); + } else { + webGLData.vao.draw(gl.TRIANGLE_STRIP, webGLData.indices.length); + } + } + }; + + /** + * Updates the graphics object + * + * @private + * @param {PIXI.Graphics} graphics - The graphics object to update + */ + + + GraphicsRenderer.prototype.updateGraphics = function updateGraphics(graphics) { + var gl = this.renderer.gl; + + // get the contexts graphics object + var webGL = graphics._webGL[this.CONTEXT_UID]; + + // if the graphics object does not exist in the webGL context time to create it! + if (!webGL) { + webGL = graphics._webGL[this.CONTEXT_UID] = { lastIndex: 0, data: [], gl: gl, clearDirty: -1, dirty: -1 }; + } + + // flag the graphics as not dirty as we are about to update it... + webGL.dirty = graphics.dirty; + + // if the user cleared the graphics object we will need to clear every object + if (graphics.clearDirty !== webGL.clearDirty) { + webGL.clearDirty = graphics.clearDirty; + + // loop through and return all the webGLDatas to the object pool so than can be reused later on + for (var i = 0; i < webGL.data.length; i++) { + this.graphicsDataPool.push(webGL.data[i]); + } + + // clear the array and reset the index.. + webGL.data.length = 0; + webGL.lastIndex = 0; + } + + var webGLData = void 0; + var webGLDataNativeLines = void 0; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (var _i = webGL.lastIndex; _i < graphics.graphicsData.length; _i++) { + var data = graphics.graphicsData[_i]; + + // TODO - this can be simplified + webGLData = this.getWebGLData(webGL, 0); + + if (data.nativeLines && data.lineWidth) { + webGLDataNativeLines = this.getWebGLData(webGL, 0, true); + webGL.lastIndex++; + } + + if (data.type === _const.SHAPES.POLY) { + (0, _buildPoly2.default)(data, webGLData, webGLDataNativeLines); + } + if (data.type === _const.SHAPES.RECT) { + (0, _buildRectangle2.default)(data, webGLData, webGLDataNativeLines); + } else if (data.type === _const.SHAPES.CIRC || data.type === _const.SHAPES.ELIP) { + (0, _buildCircle2.default)(data, webGLData, webGLDataNativeLines); + } else if (data.type === _const.SHAPES.RREC) { + (0, _buildRoundedRectangle2.default)(data, webGLData, webGLDataNativeLines); + } + + webGL.lastIndex++; + } + + this.renderer.bindVao(null); + + // upload all the dirty data... + for (var _i2 = 0; _i2 < webGL.data.length; _i2++) { + webGLData = webGL.data[_i2]; + + if (webGLData.dirty) { + webGLData.upload(); + } + } + }; + + /** + * + * @private + * @param {WebGLRenderingContext} gl - the current WebGL drawing context + * @param {number} type - TODO @Alvin + * @param {number} nativeLines - indicate whether the webGLData use for nativeLines. + * @return {*} TODO + */ + + + GraphicsRenderer.prototype.getWebGLData = function getWebGLData(gl, type, nativeLines) { + var webGLData = gl.data[gl.data.length - 1]; + + if (!webGLData || webGLData.nativeLines !== nativeLines || webGLData.points.length > 320000) { + webGLData = this.graphicsDataPool.pop() || new _WebGLGraphicsData2.default(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData.nativeLines = nativeLines; + webGLData.reset(type); + gl.data.push(webGLData); + } + + webGLData.dirty = true; + + return webGLData; + }; + + return GraphicsRenderer; +}(_ObjectRenderer3.default); + +exports.default = GraphicsRenderer; + + +_WebGLRenderer2.default.registerPlugin('graphics', GraphicsRenderer); + +},{"../../const":46,"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../utils":125,"./WebGLGraphicsData":58,"./shaders/PrimitiveShader":59,"./utils/buildCircle":60,"./utils/buildPoly":62,"./utils/buildRectangle":63,"./utils/buildRoundedRectangle":64}],58:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * An object containing WebGL specific properties to be used by the WebGL renderer + * + * @class + * @private + * @memberof PIXI + */ +var WebGLGraphicsData = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {PIXI.Shader} shader - The shader + * @param {object} attribsState - The state for the VAO + */ + function WebGLGraphicsData(gl, shader, attribsState) { + _classCallCheck(this, WebGLGraphicsData); + + /** + * The current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // TODO does this need to be split before uploading?? + /** + * An array of color components (r,g,b) + * @member {number[]} + */ + this.color = [0, 0, 0]; // color split! + + /** + * An array of points to draw + * @member {PIXI.Point[]} + */ + this.points = []; + + /** + * The indices of the vertices + * @member {number[]} + */ + this.indices = []; + /** + * The main buffer + * @member {WebGLBuffer} + */ + this.buffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl); + + /** + * The index buffer + * @member {WebGLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl); + + /** + * Whether this graphics is dirty or not + * @member {boolean} + */ + this.dirty = true; + + /** + * Whether this graphics is nativeLines or not + * @member {boolean} + */ + this.nativeLines = false; + + this.glPoints = null; + this.glIndices = null; + + /** + * + * @member {PIXI.Shader} + */ + this.shader = shader; + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, attribsState).addIndex(this.indexBuffer).addAttribute(this.buffer, shader.attributes.aVertexPosition, gl.FLOAT, false, 4 * 6, 0).addAttribute(this.buffer, shader.attributes.aColor, gl.FLOAT, false, 4 * 6, 2 * 4); + } + + /** + * Resets the vertices and the indices + */ + + + WebGLGraphicsData.prototype.reset = function reset() { + this.points.length = 0; + this.indices.length = 0; + }; + + /** + * Binds the buffers and uploads the data + */ + + + WebGLGraphicsData.prototype.upload = function upload() { + this.glPoints = new Float32Array(this.points); + this.buffer.upload(this.glPoints); + + this.glIndices = new Uint16Array(this.indices); + this.indexBuffer.upload(this.glIndices); + + this.dirty = false; + }; + + /** + * Empties all the data + */ + + + WebGLGraphicsData.prototype.destroy = function destroy() { + this.color = null; + this.points = null; + this.indices = null; + + this.vao.destroy(); + this.buffer.destroy(); + this.indexBuffer.destroy(); + + this.gl = null; + + this.buffer = null; + this.indexBuffer = null; + + this.glPoints = null; + this.glIndices = null; + }; + + return WebGLGraphicsData; +}(); + +exports.default = WebGLGraphicsData; + +},{"pixi-gl-core":15}],59:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../../Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. + * + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ +var PrimitiveShader = function (_Shader) { + _inherits(PrimitiveShader, _Shader); + + /** + * @param {WebGLRenderingContext} gl - The webgl shader manager this shader works for. + */ + function PrimitiveShader(gl) { + _classCallCheck(this, PrimitiveShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec4 aColor;', 'uniform mat3 translationMatrix;', 'uniform mat3 projectionMatrix;', 'uniform float alpha;', 'uniform vec3 tint;', 'varying vec4 vColor;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vColor = aColor * vec4(tint * alpha, alpha);', '}'].join('\n'), + // fragment shader + ['varying vec4 vColor;', 'void main(void){', ' gl_FragColor = vColor;', '}'].join('\n'))); + } + + return PrimitiveShader; +}(_Shader3.default); + +exports.default = PrimitiveShader; + +},{"../../../Shader":44}],60:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildCircle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _const = require('../../../const'); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildCircle(graphicsData, webGLData, webGLDataNativeLines) { + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width = void 0; + var height = void 0; + + // TODO - bit hacky?? + if (graphicsData.type === _const.SHAPES.CIRC) { + width = circleData.radius; + height = circleData.radius; + } else { + width = circleData.width; + height = circleData.height; + } + + if (width === 0 || height === 0) { + return; + } + + var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); + + var seg = Math.PI * 2 / totalSegs; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + indices.push(vecPos); + + for (var i = 0; i < totalSegs + 1; i++) { + verts.push(x, y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos - 1); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (var _i = 0; _i < totalSegs; _i++) { + graphicsData.points.push(x + Math.sin(seg * -_i) * width, y + Math.cos(seg * -_i) * height); + } + + graphicsData.points.push(graphicsData.points[0], graphicsData.points[1]); + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +},{"../../../const":46,"../../../utils":125,"./buildLine":61}],61:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function (graphicsData, webGLData, webGLDataNativeLines) { + if (graphicsData.nativeLines) { + buildNativeLine(graphicsData, webGLDataNativeLines); + } else { + buildLine(graphicsData, webGLData); + } +}; + +var _math = require('../../../math'); + +var _utils = require('../../../utils'); + +/** + * Builds a line to draw using the poligon method. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildLine(graphicsData, webGLData) { + // TODO OPTIMISE! + var points = graphicsData.points; + + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + + // get first and last point.. figure out the middle! + var firstPoint = new _math.Point(points[0], points[1]); + var lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + // if the first point is the last point - gonna have issues :) + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var p1x = points[0]; + var p1y = points[1]; + var p2x = points[2]; + var p2y = points[3]; + var p3x = 0; + var p3y = 0; + + var perpx = -(p1y - p2y); + var perpy = p1x - p2x; + var perp2x = 0; + var perp2y = 0; + var perp3x = 0; + var perp3y = 0; + + var dist = Math.sqrt(perpx * perpx + perpy * perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + var ratio = graphicsData.lineAlignment; // 0.5; + var r1 = (1 - ratio) * 2; + var r2 = ratio * 2; + + // start + verts.push(p1x - perpx * r1, p1y - perpy * r1, r, g, b, alpha); + + verts.push(p1x + perpx * r2, p1y + perpy * r2, r, g, b, alpha); + + for (var i = 1; i < length - 1; ++i) { + p1x = points[(i - 1) * 2]; + p1y = points[(i - 1) * 2 + 1]; + + p2x = points[i * 2]; + p2y = points[i * 2 + 1]; + + p3x = points[(i + 1) * 2]; + p3y = points[(i + 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + var a1 = -perpy + p1y - (-perpy + p2y); + var b1 = -perpx + p2x - (-perpx + p1x); + var c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + var a2 = -perp2y + p3y - (-perp2y + p2y); + var b2 = -perp2x + p2x - (-perp2x + p3x); + var c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + var denom = a1 * b2 - a2 * b1; + + if (Math.abs(denom) < 0.1) { + denom += 10.1; + verts.push(p2x - perpx * r1, p2y - perpy * r1, r, g, b, alpha); + + verts.push(p2x + perpx * r2, p2y + perpy * r2, r, g, b, alpha); + + continue; + } + + var px = (b1 * c2 - b2 * c1) / denom; + var py = (a2 * c1 - a1 * c2) / denom; + var pdist = (px - p2x) * (px - p2x) + (py - p2y) * (py - p2y); + + if (pdist > 196 * width * width) { + perp3x = perpx - perp2x; + perp3y = perpy - perp2y; + + dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y); + perp3x /= dist; + perp3y /= dist; + perp3x *= width; + perp3y *= width; + + verts.push(p2x - perp3x * r1, p2y - perp3y * r1); + verts.push(r, g, b, alpha); + + verts.push(p2x + perp3x * r2, p2y + perp3y * r2); + verts.push(r, g, b, alpha); + + verts.push(p2x - perp3x * r2 * r1, p2y - perp3y * r1); + verts.push(r, g, b, alpha); + + indexCount++; + } else { + verts.push(p2x + (px - p2x) * r1, p2y + (py - p2y) * r1); + verts.push(r, g, b, alpha); + + verts.push(p2x - (px - p2x) * r2, p2y - (py - p2y) * r2); + verts.push(r, g, b, alpha); + } + } + + p1x = points[(length - 2) * 2]; + p1y = points[(length - 2) * 2 + 1]; + + p2x = points[(length - 1) * 2]; + p2y = points[(length - 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + verts.push(p2x - perpx * r1, p2y - perpy * r1); + verts.push(r, g, b, alpha); + + verts.push(p2x + perpx * r2, p2y + perpy * r2); + verts.push(r, g, b, alpha); + + indices.push(indexStart); + + for (var _i = 0; _i < indexCount; ++_i) { + indices.push(indexStart++); + } + + indices.push(indexStart - 1); +} + +/** + * Builds a line to draw using the gl.drawArrays(gl.LINES) method + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ + + +/** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildNativeLine(graphicsData, webGLData) { + var i = 0; + var points = graphicsData.points; + + if (points.length === 0) return; + + var verts = webGLData.points; + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + for (i = 1; i < length; i++) { + var p1x = points[(i - 1) * 2]; + var p1y = points[(i - 1) * 2 + 1]; + + var p2x = points[i * 2]; + var p2y = points[i * 2 + 1]; + + verts.push(p1x, p1y); + verts.push(r, g, b, alpha); + + verts.push(p2x, p2y); + verts.push(r, g, b, alpha); + } +} + +},{"../../../math":70,"../../../utils":125}],62:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildPoly; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildPoly(graphicsData, webGLData, webGLDataNativeLines) { + graphicsData.points = graphicsData.shape.points.slice(); + + var points = graphicsData.points; + + if (graphicsData.fill && points.length >= 6) { + var holeArray = []; + // Process holes.. + var holes = graphicsData.holes; + + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + + holeArray.push(points.length / 2); + + points = points.concat(hole.points); + } + + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = (0, _earcut2.default)(points, holeArray, 2); + + if (!triangles) { + return; + } + + var vertPos = verts.length / 6; + + for (var _i = 0; _i < triangles.length; _i += 3) { + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i + 1] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + } + + for (var _i2 = 0; _i2 < length; _i2++) { + verts.push(points[_i2 * 2], points[_i2 * 2 + 1], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth > 0) { + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + } +} + +},{"../../../utils":125,"./buildLine":61,"earcut":2}],63:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRectangle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildRectangle(graphicsData, webGLData, webGLDataNativeLines) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vertPos = verts.length / 6; + + // start + verts.push(x, y); + verts.push(r, g, b, alpha); + + verts.push(x + width, y); + verts.push(r, g, b, alpha); + + verts.push(x, y + height); + verts.push(r, g, b, alpha); + + verts.push(x + width, y + height); + verts.push(r, g, b, alpha); + + // insert 2 dead triangles.. + indices.push(vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y]; + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +},{"../../../utils":125,"./buildLine":61}],64:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRoundedRectangle; + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildRoundedRectangle(graphicsData, webGLData, webGLDataNativeLines) { + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + + recPoints.push(x, y + radius); + quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height, recPoints); + quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius, recPoints); + quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y, recPoints); + quadraticBezierCurve(x + radius, y, x, y, x, y + radius + 0.0000000001, recPoints); + + // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. + // TODO - fix this properly, this is not very elegant.. but it works for now. + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + var triangles = (0, _earcut2.default)(recPoints, null, 2); + + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + + for (var _i = 0, _j = recPoints.length; _i < _j; _i++) { + verts.push(recPoints[_i], recPoints[++_i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +/** + * Calculate a single point for a quadratic bezier curve. + * Utility function used by quadraticBezierCurve. + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} n1 - first number + * @param {number} n2 - second number + * @param {number} perc - percentage + * @return {number} the result + * + */ +function getPt(n1, n2, perc) { + var diff = n2 - n1; + + return n1 + diff * perc; +} + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @return {number[]} an array of points + */ +function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY) { + var out = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : []; + + var n = 20; + var points = out; + + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + + points.push(x, y); + } + + return points; +} + +},{"../../../utils":125,"./buildLine":61,"earcut":2}],65:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = exports.Application = exports.Filter = exports.SpriteMaskFilter = exports.Quad = exports.RenderTarget = exports.ObjectRenderer = exports.WebGLManager = exports.Shader = exports.CanvasRenderTarget = exports.TextureUvs = exports.VideoBaseTexture = exports.BaseRenderTexture = exports.RenderTexture = exports.BaseTexture = exports.TextureMatrix = exports.Texture = exports.Spritesheet = exports.CanvasGraphicsRenderer = exports.GraphicsRenderer = exports.GraphicsData = exports.Graphics = exports.TextMetrics = exports.TextStyle = exports.Text = exports.SpriteRenderer = exports.CanvasTinter = exports.CanvasSpriteRenderer = exports.Sprite = exports.TransformBase = exports.TransformStatic = exports.Transform = exports.Container = exports.DisplayObject = exports.Bounds = exports.glCore = exports.WebGLRenderer = exports.CanvasRenderer = exports.ticker = exports.utils = exports.settings = undefined; + +var _const = require('./const'); + +Object.keys(_const).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _const[key]; + } + }); +}); + +var _math = require('./math'); + +Object.keys(_math).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _math[key]; + } + }); +}); + +var _pixiGlCore = require('pixi-gl-core'); + +Object.defineProperty(exports, 'glCore', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_pixiGlCore).default; + } +}); + +var _Bounds = require('./display/Bounds'); + +Object.defineProperty(exports, 'Bounds', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Bounds).default; + } +}); + +var _DisplayObject = require('./display/DisplayObject'); + +Object.defineProperty(exports, 'DisplayObject', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplayObject).default; + } +}); + +var _Container = require('./display/Container'); + +Object.defineProperty(exports, 'Container', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Container).default; + } +}); + +var _Transform = require('./display/Transform'); + +Object.defineProperty(exports, 'Transform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Transform).default; + } +}); + +var _TransformStatic = require('./display/TransformStatic'); + +Object.defineProperty(exports, 'TransformStatic', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformStatic).default; + } +}); + +var _TransformBase = require('./display/TransformBase'); + +Object.defineProperty(exports, 'TransformBase', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformBase).default; + } +}); + +var _Sprite = require('./sprites/Sprite'); + +Object.defineProperty(exports, 'Sprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Sprite).default; + } +}); + +var _CanvasSpriteRenderer = require('./sprites/canvas/CanvasSpriteRenderer'); + +Object.defineProperty(exports, 'CanvasSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasSpriteRenderer).default; + } +}); + +var _CanvasTinter = require('./sprites/canvas/CanvasTinter'); + +Object.defineProperty(exports, 'CanvasTinter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasTinter).default; + } +}); + +var _SpriteRenderer = require('./sprites/webgl/SpriteRenderer'); + +Object.defineProperty(exports, 'SpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteRenderer).default; + } +}); + +var _Text = require('./text/Text'); + +Object.defineProperty(exports, 'Text', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Text).default; + } +}); + +var _TextStyle = require('./text/TextStyle'); + +Object.defineProperty(exports, 'TextStyle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextStyle).default; + } +}); + +var _TextMetrics = require('./text/TextMetrics'); + +Object.defineProperty(exports, 'TextMetrics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextMetrics).default; + } +}); + +var _Graphics = require('./graphics/Graphics'); + +Object.defineProperty(exports, 'Graphics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Graphics).default; + } +}); + +var _GraphicsData = require('./graphics/GraphicsData'); + +Object.defineProperty(exports, 'GraphicsData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsData).default; + } +}); + +var _GraphicsRenderer = require('./graphics/webgl/GraphicsRenderer'); + +Object.defineProperty(exports, 'GraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsRenderer).default; + } +}); + +var _CanvasGraphicsRenderer = require('./graphics/canvas/CanvasGraphicsRenderer'); + +Object.defineProperty(exports, 'CanvasGraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasGraphicsRenderer).default; + } +}); + +var _Spritesheet = require('./textures/Spritesheet'); + +Object.defineProperty(exports, 'Spritesheet', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Spritesheet).default; + } +}); + +var _Texture = require('./textures/Texture'); + +Object.defineProperty(exports, 'Texture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Texture).default; + } +}); + +var _TextureMatrix = require('./textures/TextureMatrix'); + +Object.defineProperty(exports, 'TextureMatrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureMatrix).default; + } +}); + +var _BaseTexture = require('./textures/BaseTexture'); + +Object.defineProperty(exports, 'BaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseTexture).default; + } +}); + +var _RenderTexture = require('./textures/RenderTexture'); + +Object.defineProperty(exports, 'RenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTexture).default; + } +}); + +var _BaseRenderTexture = require('./textures/BaseRenderTexture'); + +Object.defineProperty(exports, 'BaseRenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseRenderTexture).default; + } +}); + +var _VideoBaseTexture = require('./textures/VideoBaseTexture'); + +Object.defineProperty(exports, 'VideoBaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VideoBaseTexture).default; + } +}); + +var _TextureUvs = require('./textures/TextureUvs'); + +Object.defineProperty(exports, 'TextureUvs', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureUvs).default; + } +}); + +var _CanvasRenderTarget = require('./renderers/canvas/utils/CanvasRenderTarget'); + +Object.defineProperty(exports, 'CanvasRenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasRenderTarget).default; + } +}); + +var _Shader = require('./Shader'); + +Object.defineProperty(exports, 'Shader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Shader).default; + } +}); + +var _WebGLManager = require('./renderers/webgl/managers/WebGLManager'); + +Object.defineProperty(exports, 'WebGLManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLManager).default; + } +}); + +var _ObjectRenderer = require('./renderers/webgl/utils/ObjectRenderer'); + +Object.defineProperty(exports, 'ObjectRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObjectRenderer).default; + } +}); + +var _RenderTarget = require('./renderers/webgl/utils/RenderTarget'); + +Object.defineProperty(exports, 'RenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTarget).default; + } +}); + +var _Quad = require('./renderers/webgl/utils/Quad'); + +Object.defineProperty(exports, 'Quad', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Quad).default; + } +}); + +var _SpriteMaskFilter = require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter'); + +Object.defineProperty(exports, 'SpriteMaskFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteMaskFilter).default; + } +}); + +var _Filter = require('./renderers/webgl/filters/Filter'); + +Object.defineProperty(exports, 'Filter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Filter).default; + } +}); + +var _Application = require('./Application'); + +Object.defineProperty(exports, 'Application', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Application).default; + } +}); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +Object.defineProperty(exports, 'autoDetectRenderer', { + enumerable: true, + get: function get() { + return _autoDetectRenderer.autoDetectRenderer; + } +}); + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _ticker = require('./ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.settings = _settings2.default; +exports.utils = utils; +exports.ticker = ticker; +exports.CanvasRenderer = _CanvasRenderer2.default; +exports.WebGLRenderer = _WebGLRenderer2.default; /** + * @namespace PIXI + */ + +},{"./Application":43,"./Shader":44,"./autoDetectRenderer":45,"./const":46,"./display/Bounds":47,"./display/Container":48,"./display/DisplayObject":49,"./display/Transform":50,"./display/TransformBase":51,"./display/TransformStatic":52,"./graphics/Graphics":53,"./graphics/GraphicsData":54,"./graphics/canvas/CanvasGraphicsRenderer":55,"./graphics/webgl/GraphicsRenderer":57,"./math":70,"./renderers/canvas/CanvasRenderer":77,"./renderers/canvas/utils/CanvasRenderTarget":79,"./renderers/webgl/WebGLRenderer":84,"./renderers/webgl/filters/Filter":86,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":89,"./renderers/webgl/managers/WebGLManager":93,"./renderers/webgl/utils/ObjectRenderer":94,"./renderers/webgl/utils/Quad":95,"./renderers/webgl/utils/RenderTarget":96,"./settings":101,"./sprites/Sprite":102,"./sprites/canvas/CanvasSpriteRenderer":103,"./sprites/canvas/CanvasTinter":104,"./sprites/webgl/SpriteRenderer":106,"./text/Text":108,"./text/TextMetrics":109,"./text/TextStyle":110,"./textures/BaseRenderTexture":111,"./textures/BaseTexture":112,"./textures/RenderTexture":113,"./textures/Spritesheet":114,"./textures/Texture":115,"./textures/TextureMatrix":116,"./textures/TextureUvs":117,"./textures/VideoBaseTexture":118,"./ticker":121,"./utils":125,"pixi-gl-core":15}],66:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Matrix = require('./Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16 + +var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; +var tempMatrices = []; + +var mul = []; + +function signum(x) { + if (x < 0) { + return -1; + } + if (x > 0) { + return 1; + } + + return 0; +} + +function init() { + for (var i = 0; i < 16; i++) { + var row = []; + + mul.push(row); + + for (var j = 0; j < 16; j++) { + var _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); + var _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); + var _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); + var _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); + + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + + for (var _i = 0; _i < 16; _i++) { + var mat = new _Matrix2.default(); + + mat.set(ux[_i], uy[_i], vx[_i], vy[_i], 0, 0); + tempMatrices.push(mat); + } +} + +init(); + +/** + * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, + * D8 is the same but with diagonals. Used for texture rotations. + * + * Vector xX(i), xY(i) is U-axis of sprite with rotation i + * Vector yY(i), yY(i) is V-axis of sprite with rotation i + * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) + * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) + * This is the small part of gameofbombs.com portal system. It works. + * + * @author Ivan @ivanpopelyshev + * @class + * @memberof PIXI + */ +var GroupD8 = { + E: 0, + SE: 1, + S: 2, + SW: 3, + W: 4, + NW: 5, + N: 6, + NE: 7, + MIRROR_VERTICAL: 8, + MIRROR_HORIZONTAL: 12, + uX: function uX(ind) { + return ux[ind]; + }, + uY: function uY(ind) { + return uy[ind]; + }, + vX: function vX(ind) { + return vx[ind]; + }, + vY: function vY(ind) { + return vy[ind]; + }, + inv: function inv(rotation) { + if (rotation & 8) { + return rotation & 15; + } + + return -rotation & 7; + }, + add: function add(rotationSecond, rotationFirst) { + return mul[rotationSecond][rotationFirst]; + }, + sub: function sub(rotationSecond, rotationFirst) { + return mul[rotationSecond][GroupD8.inv(rotationFirst)]; + }, + + /** + * Adds 180 degrees to rotation. Commutative operation. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to rotate. + * @returns {number} rotated number + */ + rotate180: function rotate180(rotation) { + return rotation ^ 4; + }, + + /** + * Direction of main vector can be horizontal, vertical or diagonal. + * Some objects work with vertical directions different. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the direction is vertical + */ + isVertical: function isVertical(rotation) { + return (rotation & 3) === 2; + }, + + /** + * @memberof PIXI.GroupD8 + * @param {number} dx - TODO + * @param {number} dy - TODO + * + * @return {number} TODO + */ + byDirection: function byDirection(dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return GroupD8.S; + } + + return GroupD8.N; + } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return GroupD8.E; + } + + return GroupD8.W; + } else if (dy > 0) { + if (dx > 0) { + return GroupD8.SE; + } + + return GroupD8.SW; + } else if (dx > 0) { + return GroupD8.NE; + } + + return GroupD8.NW; + }, + + /** + * Helps sprite to compensate texture packer rotation. + * + * @memberof PIXI.GroupD8 + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {number} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function matrixAppendRotationInv(matrix, rotation) { + var tx = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var ty = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + // Packer used "rotation", we use "inv(rotation)" + var mat = tempMatrices[GroupD8.inv(rotation)]; + + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + } +}; + +exports.default = GroupD8; + +},{"./Matrix":67}],67:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Point = require('./Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The PixiJS Matrix class as an object, which makes it a lot faster, + * here is a representation of it : + * | a | c | tx| + * | b | d | ty| + * | 0 | 0 | 1 | + * + * @class + * @memberof PIXI + */ +var Matrix = function () { + /** + * @param {number} [a=1] - x scale + * @param {number} [b=0] - x skew + * @param {number} [c=0] - y skew + * @param {number} [d=1] - y scale + * @param {number} [tx=0] - x translation + * @param {number} [ty=0] - y translation + */ + function Matrix() { + var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var d = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var tx = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var ty = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + + _classCallCheck(this, Matrix); + + /** + * @member {number} + * @default 1 + */ + this.a = a; + + /** + * @member {number} + * @default 0 + */ + this.b = b; + + /** + * @member {number} + * @default 0 + */ + this.c = c; + + /** + * @member {number} + * @default 1 + */ + this.d = d; + + /** + * @member {number} + * @default 0 + */ + this.tx = tx; + + /** + * @member {number} + * @default 0 + */ + this.ty = ty; + + this.array = null; + } + + /** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @param {number[]} array - The array that the matrix will be populated from. + */ + + + Matrix.prototype.fromArray = function fromArray(array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + }; + + /** + * sets the matrix properties + * + * @param {number} a - Matrix component + * @param {number} b - Matrix component + * @param {number} c - Matrix component + * @param {number} d - Matrix component + * @param {number} tx - Matrix component + * @param {number} ty - Matrix component + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.set = function set(a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + }; + + /** + * Creates an array from the current Matrix object. + * + * @param {boolean} transpose - Whether we need to transpose the matrix or not + * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out + * @return {number[]} the newly created array which contains the matrix + */ + + + Matrix.prototype.toArray = function toArray(transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + + var array = out || this.array; + + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + }; + + /** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, transformed through this matrix + */ + + + Matrix.prototype.apply = function apply(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; + + return newPos; + }; + + /** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, inverse-transformed through this matrix + */ + + + Matrix.prototype.applyInverse = function applyInverse(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var id = 1 / (this.a * this.d + this.c * -this.b); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + }; + + /** + * Translates the matrix on the x and y. + * + * @param {number} x How much to translate x by + * @param {number} y How much to translate y by + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.translate = function translate(x, y) { + this.tx += x; + this.ty += y; + + return this; + }; + + /** + * Applies a scale transformation to the matrix. + * + * @param {number} x The amount to scale horizontally + * @param {number} y The amount to scale vertically + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.scale = function scale(x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + }; + + /** + * Applies a rotation transformation to the matrix. + * + * @param {number} angle - The angle in radians. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.rotate = function rotate(angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos - this.b * sin; + this.b = a1 * sin + this.b * cos; + this.c = c1 * cos - this.d * sin; + this.d = c1 * sin + this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + }; + + /** + * Appends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to append. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.append = function append(matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + }; + + /** + * Sets the matrix based on all the available properties + * + * @param {number} x - Position on the x axis + * @param {number} y - Position on the y axis + * @param {number} pivotX - Pivot on the x axis + * @param {number} pivotY - Pivot on the y axis + * @param {number} scaleX - Scale on the x axis + * @param {number} scaleY - Scale on the y axis + * @param {number} rotation - Rotation in radians + * @param {number} skewX - Skew on the x axis + * @param {number} skewY - Skew on the y axis + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.setTransform = function setTransform(x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + this.a = Math.cos(rotation + skewY) * scaleX; + this.b = Math.sin(rotation + skewY) * scaleX; + this.c = -Math.sin(rotation - skewX) * scaleY; + this.d = Math.cos(rotation - skewX) * scaleY; + + this.tx = x - (pivotX * this.a + pivotY * this.c); + this.ty = y - (pivotX * this.b + pivotY * this.d); + + return this; + }; + + /** + * Prepends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to prepend + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.prepend = function prepend(matrix) { + var tx1 = this.tx; + + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + + this.a = a1 * matrix.a + this.b * matrix.c; + this.b = a1 * matrix.b + this.b * matrix.d; + this.c = c1 * matrix.a + this.d * matrix.c; + this.d = c1 * matrix.b + this.d * matrix.d; + } + + this.tx = tx1 * matrix.a + this.ty * matrix.c + matrix.tx; + this.ty = tx1 * matrix.b + this.ty * matrix.d + matrix.ty; + + return this; + }; + + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * + * @param {PIXI.Transform|PIXI.TransformStatic} transform - The transform to apply the properties to. + * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properties + */ + + + Matrix.prototype.decompose = function decompose(transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + + var skewX = -Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + + var delta = Math.abs(skewX + skewY); + + if (delta < 0.00001 || Math.abs(_const.PI_2 - delta) < 0.00001) { + transform.rotation = skewY; + + if (a < 0 && d >= 0) { + transform.rotation += transform.rotation <= 0 ? Math.PI : -Math.PI; + } + + transform.skew.x = transform.skew.y = 0; + } else { + transform.rotation = 0; + transform.skew.x = skewX; + transform.skew.y = skewY; + } + + // next set scale + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); + + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; + + return transform; + }; + + /** + * Inverts this matrix + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.invert = function invert() { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1 * d1 - b1 * c1; + + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = (c1 * this.ty - d1 * tx1) / n; + this.ty = -(a1 * this.ty - b1 * tx1) / n; + + return this; + }; + + /** + * Resets this Matix to an identity (default) matrix. + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.identity = function identity() { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + + return this; + }; + + /** + * Creates a new Matrix object with the same values as this one. + * + * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. + */ + + + Matrix.prototype.clone = function clone() { + var matrix = new Matrix(); + + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * Changes the values of the given matrix to be the same as the ones in this matrix + * + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @return {PIXI.Matrix} The matrix given in parameter with its values updated. + */ + + + Matrix.prototype.copy = function copy(matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * A default (identity) matrix + * + * @static + * @const + */ + + + _createClass(Matrix, null, [{ + key: 'IDENTITY', + get: function get() { + return new Matrix(); + } + + /** + * A temp matrix + * + * @static + * @const + */ + + }, { + key: 'TEMP_MATRIX', + get: function get() { + return new Matrix(); + } + }]); + + return Matrix; +}(); + +exports.default = Matrix; + +},{"../const":46,"./Point":69}],68:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * An observable point is a point that triggers a callback when the point's position is changed. + * + * @class + * @memberof PIXI + */ +var ObservablePoint = function () { + /** + * @param {Function} cb - callback when changed + * @param {object} scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope) { + var x = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var y = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, ObservablePoint); + + this._x = x; + this._y = y; + + this.cb = cb; + this.scope = scope; + } + + /** + * Creates a clone of this point. + * The callback and scope params can be overidden otherwise they will default + * to the clone object's values. + * + * @override + * @param {Function} [cb=null] - callback when changed + * @param {object} [scope=null] - owner of callback + * @return {PIXI.ObservablePoint} a copy of the point + */ + + + ObservablePoint.prototype.clone = function clone() { + var cb = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + + var _cb = cb || this.cb; + var _scope = scope || this.scope; + + return new ObservablePoint(_cb, _scope, this._x, this._y); + }; + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + ObservablePoint.prototype.set = function set(x, y) { + var _x = x || 0; + var _y = y || (y !== 0 ? _x : 0); + + if (this._x !== _x || this._y !== _y) { + this._x = _x; + this._y = _y; + this.cb.call(this.scope); + } + }; + + /** + * Copies the data from another point + * + * @param {PIXI.Point|PIXI.ObservablePoint} point - point to copy from + */ + + + ObservablePoint.prototype.copy = function copy(point) { + if (this._x !== point.x || this._y !== point.y) { + this._x = point.x; + this._y = point.y; + this.cb.call(this.scope); + } + }; + + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.Point|PIXI.ObservablePoint} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + + + ObservablePoint.prototype.equals = function equals(p) { + return p.x === this._x && p.y === this._y; + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + + _createClass(ObservablePoint, [{ + key: "x", + get: function get() { + return this._x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + } + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + }, { + key: "y", + get: function get() { + return this._y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + } + }]); + + return ObservablePoint; +}(); + +exports.default = ObservablePoint; + +},{}],69:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * + * @class + * @memberof PIXI + */ +var Point = function () { + /** + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function Point() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + + _classCallCheck(this, Point); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + } + + /** + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point + */ + + + Point.prototype.clone = function clone() { + return new Point(this.x, this.y); + }; + + /** + * Copies x and y from the given point + * + * @param {PIXI.Point} p - The point to copy. + */ + + + Point.prototype.copy = function copy(p) { + this.set(p.x, p.y); + }; + + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.Point} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + + + Point.prototype.equals = function equals(p) { + return p.x === this.x && p.y === this.y; + }; + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + Point.prototype.set = function set(x, y) { + this.x = x || 0; + this.y = y || (y !== 0 ? this.x : 0); + }; + + return Point; +}(); + +exports.default = Point; + +},{}],70:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('./Point'); + +Object.defineProperty(exports, 'Point', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Point).default; + } +}); + +var _ObservablePoint = require('./ObservablePoint'); + +Object.defineProperty(exports, 'ObservablePoint', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObservablePoint).default; + } +}); + +var _Matrix = require('./Matrix'); + +Object.defineProperty(exports, 'Matrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Matrix).default; + } +}); + +var _GroupD = require('./GroupD8'); + +Object.defineProperty(exports, 'GroupD8', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GroupD).default; + } +}); + +var _Circle = require('./shapes/Circle'); + +Object.defineProperty(exports, 'Circle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Circle).default; + } +}); + +var _Ellipse = require('./shapes/Ellipse'); + +Object.defineProperty(exports, 'Ellipse', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Ellipse).default; + } +}); + +var _Polygon = require('./shapes/Polygon'); + +Object.defineProperty(exports, 'Polygon', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Polygon).default; + } +}); + +var _Rectangle = require('./shapes/Rectangle'); + +Object.defineProperty(exports, 'Rectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rectangle).default; + } +}); + +var _RoundedRectangle = require('./shapes/RoundedRectangle'); + +Object.defineProperty(exports, 'RoundedRectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RoundedRectangle).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./GroupD8":66,"./Matrix":67,"./ObservablePoint":68,"./Point":69,"./shapes/Circle":71,"./shapes/Ellipse":72,"./shapes/Polygon":73,"./shapes/Rectangle":74,"./shapes/RoundedRectangle":75}],71:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Circle object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Circle = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [radius=0] - The radius of the circle + */ + function Circle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var radius = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + _classCallCheck(this, Circle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.CIRC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.CIRC; + } + + /** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ + + + Circle.prototype.clone = function clone() { + return new Circle(this.x, this.y, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this circle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Circle + */ + + + Circle.prototype.contains = function contains(x, y) { + if (this.radius <= 0) { + return false; + } + + var r2 = this.radius * this.radius; + var dx = this.x - x; + var dy = this.y - y; + + dx *= dx; + dy *= dy; + + return dx + dy <= r2; + }; + + /** + * Returns the framing rectangle of the circle as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Circle.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + + return Circle; +}(); + +exports.default = Circle; + +},{"../../const":46,"./Rectangle":74}],72:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Ellipse object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Ellipse = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [width=0] - The half width of this ellipse + * @param {number} [height=0] - The half height of this ellipse + */ + function Ellipse() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Ellipse); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.ELIP + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.ELIP; + } + + /** + * Creates a clone of this Ellipse instance + * + * @return {PIXI.Ellipse} a copy of the ellipse + */ + + + Ellipse.prototype.clone = function clone() { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coords are within this ellipse + */ + + + Ellipse.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + // normalize the coords to an ellipse with center 0,0 + var normx = (x - this.x) / this.width; + var normy = (y - this.y) / this.height; + + normx *= normx; + normy *= normy; + + return normx + normy <= 1; + }; + + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Ellipse.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.width, this.y - this.height, this.width, this.height); + }; + + return Ellipse; +}(); + +exports.default = Ellipse; + +},{"../../const":46,"./Rectangle":74}],73:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('../Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Polygon = function () { + /** + * @param {PIXI.Point[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + for (var _len = arguments.length, points = Array(_len), _key = 0; _key < _len; _key++) { + points[_key] = arguments[_key]; + } + + _classCallCheck(this, Polygon); + + if (Array.isArray(points[0])) { + points = points[0]; + } + + // if this is an array of points, convert it to a flat array of numbers + if (points[0] instanceof _Point2.default) { + var p = []; + + for (var i = 0, il = points.length; i < il; i++) { + p.push(points[i].x, points[i].y); + } + + points = p; + } + + this.closed = true; + + /** + * An array of the points of this polygon + * + * @member {number[]} + */ + this.points = points; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.POLY + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.POLY; + } + + /** + * Creates a clone of this polygon + * + * @return {PIXI.Polygon} a copy of the polygon + */ + + + Polygon.prototype.clone = function clone() { + return new Polygon(this.points.slice()); + }; + + /** + * Closes the polygon, adding points if necessary. + * + */ + + + Polygon.prototype.close = function close() { + var points = this.points; + + // close the poly if the value is true! + if (points[0] !== points[points.length - 2] || points[1] !== points[points.length - 1]) { + points.push(points[0], points[1]); + } + }; + + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this polygon + */ + + + Polygon.prototype.contains = function contains(x, y) { + var inside = false; + + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + + for (var i = 0, j = length - 1; i < length; j = i++) { + var xi = this.points[i * 2]; + var yi = this.points[i * 2 + 1]; + var xj = this.points[j * 2]; + var yj = this.points[j * 2 + 1]; + var intersect = yi > y !== yj > y && x < (xj - xi) * ((y - yi) / (yj - yi)) + xi; + + if (intersect) { + inside = !inside; + } + } + + return inside; + }; + + return Polygon; +}(); + +exports.default = Polygon; + +},{"../../const":46,"../Point":69}],74:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * + * @class + * @memberof PIXI + */ +var Rectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle + * @param {number} [width=0] - The overall width of this rectangle + * @param {number} [height=0] - The overall height of this rectangle + */ + function Rectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Rectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = Number(x); + + /** + * @member {number} + * @default 0 + */ + this.y = Number(y); + + /** + * @member {number} + * @default 0 + */ + this.width = Number(width); + + /** + * @member {number} + * @default 0 + */ + this.height = Number(height); + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.RECT + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RECT; + } + + /** + * returns the left edge of the rectangle + * + * @member {number} + */ + + + /** + * Creates a clone of this Rectangle + * + * @return {PIXI.Rectangle} a copy of the rectangle + */ + Rectangle.prototype.clone = function clone() { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + + /** + * Copies another rectangle to this one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to copy. + * @return {PIXI.Rectangle} Returns itself. + */ + + + Rectangle.prototype.copy = function copy(rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + + return this; + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rectangle + */ + + + Rectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + + return false; + }; + + /** + * Pads the rectangle making it grow in all directions. + * + * @param {number} paddingX - The horizontal padding amount. + * @param {number} [paddingY] - The vertical padding amount. + */ + + + Rectangle.prototype.pad = function pad(paddingX, paddingY) { + paddingX = paddingX || 0; + paddingY = paddingY || (paddingY !== 0 ? paddingX : 0); + + this.x -= paddingX; + this.y -= paddingY; + + this.width += paddingX * 2; + this.height += paddingY * 2; + }; + + /** + * Fits this rectangle around the passed one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to fit. + */ + + + Rectangle.prototype.fit = function fit(rectangle) { + if (this.x < rectangle.x) { + this.width += this.x; + if (this.width < 0) { + this.width = 0; + } + + this.x = rectangle.x; + } + + if (this.y < rectangle.y) { + this.height += this.y; + if (this.height < 0) { + this.height = 0; + } + this.y = rectangle.y; + } + + if (this.x + this.width > rectangle.x + rectangle.width) { + this.width = rectangle.width - this.x; + if (this.width < 0) { + this.width = 0; + } + } + + if (this.y + this.height > rectangle.y + rectangle.height) { + this.height = rectangle.height - this.y; + if (this.height < 0) { + this.height = 0; + } + } + }; + + /** + * Enlarges this rectangle to include the passed rectangle. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to include. + */ + + + Rectangle.prototype.enlarge = function enlarge(rectangle) { + var x1 = Math.min(this.x, rectangle.x); + var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.min(this.y, rectangle.y); + var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); + + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + }; + + _createClass(Rectangle, [{ + key: 'left', + get: function get() { + return this.x; + } + + /** + * returns the right edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'right', + get: function get() { + return this.x + this.width; + } + + /** + * returns the top edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'top', + get: function get() { + return this.y; + } + + /** + * returns the bottom edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'bottom', + get: function get() { + return this.y + this.height; + } + + /** + * A constant empty rectangle. + * + * @static + * @constant + */ + + }], [{ + key: 'EMPTY', + get: function get() { + return new Rectangle(0, 0, 0, 0); + } + }]); + + return Rectangle; +}(); + +exports.default = Rectangle; + +},{"../../const":46}],75:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. + * + * @class + * @memberof PIXI + */ +var RoundedRectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle + * @param {number} [width=0] - The overall width of this rounded rectangle + * @param {number} [height=0] - The overall height of this rounded rectangle + * @param {number} [radius=20] - Controls the radius of the rounded corners + */ + function RoundedRectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var radius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 20; + + _classCallCheck(this, RoundedRectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * @member {number} + * @default 20 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readonly + * @default PIXI.SHAPES.RREC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RREC; + } + + /** + * Creates a clone of this Rounded Rectangle + * + * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle + */ + + + RoundedRectangle.prototype.clone = function clone() { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + */ + + + RoundedRectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + if (y >= this.y + this.radius && y <= this.y + this.height - this.radius || x >= this.x + this.radius && x <= this.x + this.width - this.radius) { + return true; + } + var dx = x - (this.x + this.radius); + var dy = y - (this.y + this.radius); + var radius2 = this.radius * this.radius; + + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.width - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dy = y - (this.y + this.height - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + } + } + + return false; + }; + + return RoundedRectangle; +}(); + +exports.default = RoundedRectangle; + +},{"../../const":46}],76:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _math = require('../math'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _Container = require('../display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMatrix = new _math.Matrix(); + +/** + * The SystemRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.WebGLRenderer} which can be used for rendering a PixiJS scene. + * + * @abstract + * @class + * @extends EventEmitter + * @memberof PIXI + */ + +var SystemRenderer = function (_EventEmitter) { + _inherits(SystemRenderer, _EventEmitter); + + // eslint-disable-next-line valid-jsdoc + /** + * @param {string} system - The name of the system this renderer is for. + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function SystemRenderer(system, options, arg2, arg3) { + _classCallCheck(this, SystemRenderer); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + (0, _utils.sayHello)(system); + + // Support for constructor(system, screenWidth, screenHeight, options) + if (typeof options === 'number') { + options = Object.assign({ + width: options, + height: arg2 || _settings2.default.RENDER_OPTIONS.height + }, arg3); + } + + // Add the default render options + options = Object.assign({}, _settings2.default.RENDER_OPTIONS, options); + + /** + * The supplied constructor options. + * + * @member {Object} + * @readOnly + */ + _this.options = options; + + /** + * The type of the renderer. + * + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.UNKNOWN; + + /** + * Measurements of the screen. (0, 0, screenWidth, screenHeight) + * + * Its safe to use as filterArea or hitArea for whole stage + * + * @member {PIXI.Rectangle} + */ + _this.screen = new _math.Rectangle(0, 0, options.width, options.height); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.view = options.view || document.createElement('canvas'); + + /** + * The resolution / device pixel ratio of the renderer + * + * @member {number} + * @default 1 + */ + _this.resolution = options.resolution || _settings2.default.RESOLUTION; + + /** + * Whether the render view is transparent + * + * @member {boolean} + */ + _this.transparent = options.transparent; + + /** + * Whether css dimensions of canvas view should be resized to screen dimensions automatically + * + * @member {boolean} + */ + _this.autoResize = options.autoResize || false; + + /** + * Tracks the blend modes useful for this renderer. + * + * @member {object} + */ + _this.blendModes = null; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example if + * your game has a canvas filling background image you often don't need this set. + * + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + * + * @member {boolean} + */ + _this.roundPixels = options.roundPixels; + + /** + * The background color as a number. + * + * @member {number} + * @private + */ + _this._backgroundColor = 0x000000; + + /** + * The background color as an [R, G, B] array. + * + * @member {number[]} + * @private + */ + _this._backgroundColorRgba = [0, 0, 0, 0]; + + /** + * The background color as a string. + * + * @member {string} + * @private + */ + _this._backgroundColorString = '#000000'; + + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + + /** + * This temporary display object used as the parent of the currently being rendered item + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._tempDisplayObjectParent = new _Container2.default(); + + /** + * The last root object that the renderer tried to render. + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._lastObjectRendered = _this._tempDisplayObjectParent; + return _this; + } + + /** + * Same as view.width, actual number of pixels in the canvas by horizontal + * + * @member {number} + * @readonly + * @default 800 + */ + + + /** + * Resizes the screen and canvas to the specified width and height + * Canvas dimensions are multiplied by resolution + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + SystemRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + this.screen.width = screenWidth; + this.screen.height = screenHeight; + + this.view.width = screenWidth * this.resolution; + this.view.height = screenHeight * this.resolution; + + if (this.autoResize) { + this.view.style.width = screenWidth + 'px'; + this.view.style.height = screenHeight + 'px'; + } + }; + + /** + * Useful function that returns a texture of the display object that can then be used to create sprites + * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. + * + * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from + * @param {number} scaleMode - Should be one of the scaleMode consts + * @param {number} resolution - The resolution / device pixel ratio of the texture being generated + * @param {PIXI.Rectangle} [region] - The region of the displayObject, that shall be rendered, + * if no region is specified, defaults to the local bounds of the displayObject. + * @return {PIXI.Texture} a texture of the graphics object + */ + + + SystemRenderer.prototype.generateTexture = function generateTexture(displayObject, scaleMode, resolution, region) { + region = region || displayObject.getLocalBounds(); + + var renderTexture = _RenderTexture2.default.create(region.width | 0, region.height | 0, scaleMode, resolution); + + tempMatrix.tx = -region.x; + tempMatrix.ty = -region.y; + + this.render(displayObject, renderTexture, false, tempMatrix, !!displayObject.parent); + + return renderTexture; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + SystemRenderer.prototype.destroy = function destroy(removeView) { + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } + + this.type = _const.RENDERER_TYPE.UNKNOWN; + + this.view = null; + + this.screen = null; + + this.resolution = 0; + + this.transparent = false; + + this.autoResize = false; + + this.blendModes = null; + + this.options = null; + + this.preserveDrawingBuffer = false; + this.clearBeforeRender = false; + + this.roundPixels = false; + + this._backgroundColor = 0; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + + this._tempDisplayObjectParent = null; + this._lastObjectRendered = null; + }; + + /** + * The background color to fill if not transparent + * + * @member {number} + */ + + + _createClass(SystemRenderer, [{ + key: 'width', + get: function get() { + return this.view.width; + } + + /** + * Same as view.height, actual number of pixels in the canvas by vertical + * + * @member {number} + * @readonly + * @default 600 + */ + + }, { + key: 'height', + get: function get() { + return this.view.height; + } + }, { + key: 'backgroundColor', + get: function get() { + return this._backgroundColor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._backgroundColor = value; + this._backgroundColorString = (0, _utils.hex2string)(value); + (0, _utils.hex2rgb)(value, this._backgroundColorRgba); + } + }]); + + return SystemRenderer; +}(_eventemitter2.default); + +exports.default = SystemRenderer; + +},{"../const":46,"../display/Container":48,"../math":70,"../settings":101,"../textures/RenderTexture":113,"../utils":125,"eventemitter3":3}],77:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _CanvasMaskManager = require('./utils/CanvasMaskManager'); + +var _CanvasMaskManager2 = _interopRequireDefault(_CanvasMaskManager); + +var _CanvasRenderTarget = require('./utils/CanvasRenderTarget'); + +var _CanvasRenderTarget2 = _interopRequireDefault(_CanvasRenderTarget); + +var _mapCanvasBlendModesToPixi = require('./utils/mapCanvasBlendModesToPixi'); + +var _mapCanvasBlendModesToPixi2 = _interopRequireDefault(_mapCanvasBlendModesToPixi); + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should + * be used for browsers that do not support WebGL. Don't forget to add the CanvasRenderer.view to + * your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ +var CanvasRenderer = function (_SystemRenderer) { + _inherits(CanvasRenderer, _SystemRenderer); + + // eslint-disable-next-line valid-jsdoc + /** + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function CanvasRenderer(options, arg2, arg3) { + _classCallCheck(this, CanvasRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'Canvas', options, arg2, arg3)); + + _this.type = _const.RENDERER_TYPE.CANVAS; + + /** + * The root canvas 2d context that everything is drawn with. + * + * @member {CanvasRenderingContext2D} + */ + _this.rootContext = _this.view.getContext('2d', { alpha: _this.transparent }); + + /** + * The currently active canvas 2d context (could change with renderTextures) + * + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.rootContext; + + /** + * Boolean flag controlling canvas refresh. + * + * @member {boolean} + */ + _this.refresh = true; + + /** + * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. + * + * @member {PIXI.CanvasMaskManager} + */ + _this.maskManager = new _CanvasMaskManager2.default(_this); + + /** + * The canvas property used to set the canvas smoothing property. + * + * @member {string} + */ + _this.smoothProperty = 'imageSmoothingEnabled'; + + if (!_this.rootContext.imageSmoothingEnabled) { + if (_this.rootContext.webkitImageSmoothingEnabled) { + _this.smoothProperty = 'webkitImageSmoothingEnabled'; + } else if (_this.rootContext.mozImageSmoothingEnabled) { + _this.smoothProperty = 'mozImageSmoothingEnabled'; + } else if (_this.rootContext.oImageSmoothingEnabled) { + _this.smoothProperty = 'oImageSmoothingEnabled'; + } else if (_this.rootContext.msImageSmoothingEnabled) { + _this.smoothProperty = 'msImageSmoothingEnabled'; + } + } + + _this.initPlugins(); + + _this.blendModes = (0, _mapCanvasBlendModesToPixi2.default)(); + _this._activeBlendMode = null; + + _this.renderingToScreen = false; + + _this.resize(_this.options.width, _this.options.height); + + /** + * Fired after rendering finishes. + * + * @event PIXI.CanvasRenderer#postrender + */ + + /** + * Fired before rendering starts. + * + * @event PIXI.CanvasRenderer#prerender + */ + return _this; + } + + /** + * Renders the object to this canvas view + * + * @param {PIXI.DisplayObject} displayObject - The object to be rendered + * @param {PIXI.RenderTexture} [renderTexture] - A render texture to be rendered to. + * If unset, it will render to the root context. + * @param {boolean} [clear=false] - Whether to clear the canvas before drawing + * @param {PIXI.Matrix} [transform] - A transformation to be applied + * @param {boolean} [skipUpdateTransform=false] - Whether to skip the update transform + */ + + + CanvasRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!this.view) { + return; + } + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + var rootResolution = this.resolution; + + if (renderTexture) { + renderTexture = renderTexture.baseTexture || renderTexture; + + if (!renderTexture._canvasRenderTarget) { + renderTexture._canvasRenderTarget = new _CanvasRenderTarget2.default(renderTexture.width, renderTexture.height, renderTexture.resolution); + renderTexture.source = renderTexture._canvasRenderTarget.canvas; + renderTexture.valid = true; + } + + this.context = renderTexture._canvasRenderTarget.context; + this.resolution = renderTexture._canvasRenderTarget.resolution; + } else { + this.context = this.rootContext; + } + + var context = this.context; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + var tempWt = this._tempDisplayObjectParent.transform.worldTransform; + + if (transform) { + transform.copy(tempWt); + + // lets not forget to flag the parent transform as dirty... + this._tempDisplayObjectParent.transform._worldID = -1; + } else { + tempWt.identity(); + } + + displayObject.parent = this._tempDisplayObjectParent; + + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + context.save(); + context.setTransform(1, 0, 0, 1, 0, 0); + context.globalAlpha = 1; + this._activeBlendMode = _const.BLEND_MODES.NORMAL; + context.globalCompositeOperation = this.blendModes[_const.BLEND_MODES.NORMAL]; + + if (navigator.isCocoonJS && this.view.screencanvas) { + context.fillStyle = 'black'; + context.clear(); + } + + if (clear !== undefined ? clear : this.clearBeforeRender) { + if (this.renderingToScreen) { + if (this.transparent) { + context.clearRect(0, 0, this.width, this.height); + } else { + context.fillStyle = this._backgroundColorString; + context.fillRect(0, 0, this.width, this.height); + } + } // else { + // TODO: implement background for CanvasRenderTarget or RenderTexture? + // } + } + + // TODO RENDER TARGET STUFF HERE.. + var tempContext = this.context; + + this.context = context; + displayObject.renderCanvas(this); + this.context = tempContext; + + context.restore(); + + this.resolution = rootResolution; + + this.emit('postrender'); + }; + + /** + * Clear the canvas of renderer. + * + * @param {string} [clearColor] - Clear the canvas with this color, except the canvas is transparent. + */ + + + CanvasRenderer.prototype.clear = function clear(clearColor) { + var context = this.context; + + clearColor = clearColor || this._backgroundColorString; + + if (!this.transparent && clearColor) { + context.fillStyle = clearColor; + context.fillRect(0, 0, this.width, this.height); + } else { + context.clearRect(0, 0, this.width, this.height); + } + }; + + /** + * Sets the blend mode of the renderer. + * + * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values. + */ + + + CanvasRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + if (this._activeBlendMode === blendMode) { + return; + } + + this._activeBlendMode = blendMode; + this.context.globalCompositeOperation = this.blendModes[blendMode]; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + CanvasRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // call the base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.context = null; + + this.refresh = true; + + this.maskManager.destroy(); + this.maskManager = null; + + this.smoothProperty = null; + }; + + /** + * Resizes the canvas view to the specified width and height. + * + * @extends PIXI.SystemRenderer#resize + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + CanvasRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + _SystemRenderer.prototype.resize.call(this, screenWidth, screenHeight); + + // reset the scale mode.. oddly this seems to be reset when the canvas is resized. + // surely a browser bug?? Let PixiJS fix that for you.. + if (this.smoothProperty) { + this.rootContext[this.smoothProperty] = _settings2.default.SCALE_MODE === _const.SCALE_MODES.LINEAR; + } + }; + + /** + * Checks if blend mode has changed. + */ + + + CanvasRenderer.prototype.invalidateBlendMode = function invalidateBlendMode() { + this._activeBlendMode = this.blendModes.indexOf(this.context.globalCompositeOperation); + }; + + return CanvasRenderer; +}(_SystemRenderer3.default); + +/** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @name PIXI.CanvasRenderer#plugins + * @type {object} + * @readonly + * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.extract.CanvasExtract} extract Extract image data from renderer. + * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.prepare.CanvasPrepare} prepare Pre-render display objects. + */ + +/** + * Adds a plugin to the renderer. + * + * @method PIXI.CanvasRenderer#registerPlugin + * @param {string} pluginName - The name of the plugin. + * @param {Function} ctor - The constructor function or class for the plugin. + */ + +exports.default = CanvasRenderer; +_utils.pluginTarget.mixin(CanvasRenderer); + +},{"../../const":46,"../../settings":101,"../../utils":125,"../SystemRenderer":76,"./utils/CanvasMaskManager":78,"./utils/CanvasRenderTarget":79,"./utils/mapCanvasBlendModesToPixi":81}],78:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A set of functions used to handle masking. + * + * @class + * @memberof PIXI + */ +var CanvasMaskManager = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + function CanvasMaskManager(renderer) { + _classCallCheck(this, CanvasMaskManager); + + this.renderer = renderer; + } + + /** + * This method adds it to the current stack of masks. + * + * @param {object} maskData - the maskData that will be pushed + */ + + + CanvasMaskManager.prototype.pushMask = function pushMask(maskData) { + var renderer = this.renderer; + + renderer.context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.transform.worldTransform; + var resolution = renderer.resolution; + + renderer.context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // TODO suport sprite alpha masks?? + // lots of effort required. If demand is great enough.. + if (!maskData._texture) { + this.renderGraphicsShape(maskData); + renderer.context.clip(); + } + + maskData.worldAlpha = cacheAlpha; + }; + + /** + * Renders a PIXI.Graphics shape. + * + * @param {PIXI.Graphics} graphics - The object to render. + */ + + + CanvasMaskManager.prototype.renderGraphicsShape = function renderGraphicsShape(graphics) { + var context = this.renderer.context; + var len = graphics.graphicsData.length; + + if (len === 0) { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === _const.SHAPES.POLY) { + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; j++) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) { + context.closePath(); + } + } else if (data.type === _const.SHAPES.RECT) { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } + }; + + /** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @param {PIXI.CanvasRenderer} renderer - The renderer context to use. + */ + + + CanvasMaskManager.prototype.popMask = function popMask(renderer) { + renderer.context.restore(); + renderer.invalidateBlendMode(); + }; + + /** + * Destroys this canvas mask manager. + * + */ + + + CanvasMaskManager.prototype.destroy = function destroy() { + /* empty */ + }; + + return CanvasMaskManager; +}(); + +exports.default = CanvasMaskManager; + +},{"../../../const":46}],79:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Creates a Canvas element of the given size. + * + * @class + * @memberof PIXI + */ +var CanvasRenderTarget = function () { + /** + * @param {number} width - the width for the newly created canvas + * @param {number} height - the height for the newly created canvas + * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + _classCallCheck(this, CanvasRenderTarget); + + /** + * The Canvas object that belongs to this CanvasRenderTarget. + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @member {CanvasRenderingContext2D} + */ + this.context = this.canvas.getContext('2d'); + + this.resolution = resolution || _settings2.default.RESOLUTION; + + this.resize(width, height); + } + + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * + * @private + */ + + + CanvasRenderTarget.prototype.clear = function clear() { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + + /** + * Resizes the canvas to the specified width and height. + * + * @param {number} width - the new width of the canvas + * @param {number} height - the new height of the canvas + */ + + + CanvasRenderTarget.prototype.resize = function resize(width, height) { + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; + }; + + /** + * Destroys this canvas. + * + */ + + + CanvasRenderTarget.prototype.destroy = function destroy() { + this.context = null; + this.canvas = null; + }; + + /** + * The width of the canvas buffer in pixels. + * + * @member {number} + */ + + + _createClass(CanvasRenderTarget, [{ + key: 'width', + get: function get() { + return this.canvas.width; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.width = val; + } + + /** + * The height of the canvas buffer in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.canvas.height; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.height = val; + } + }]); + + return CanvasRenderTarget; +}(); + +exports.default = CanvasRenderTarget; + +},{"../../../settings":101}],80:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = canUseNewCanvasBlendModes; +/** + * Creates a little colored canvas + * + * @ignore + * @param {string} color - The color to make the canvas + * @return {canvas} a small canvas element + */ +function createColoredCanvas(color) { + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.fillStyle = color; + context.fillRect(0, 0, 6, 1); + + return canvas; +} + +/** + * Checks whether the Canvas BlendModes are supported by the current browser + * + * @return {boolean} whether they are supported + */ +function canUseNewCanvasBlendModes() { + if (typeof document === 'undefined') { + return false; + } + + var magenta = createColoredCanvas('#ff00ff'); + var yellow = createColoredCanvas('#ffff00'); + + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.globalCompositeOperation = 'multiply'; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + var imageData = context.getImageData(2, 0, 1, 1); + + if (!imageData) { + return false; + } + + var data = imageData.data; + + return data[0] === 255 && data[1] === 0 && data[2] === 0; +} + +},{}],81:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapCanvasBlendModesToPixi; + +var _const = require('../../../const'); + +var _canUseNewCanvasBlendModes = require('./canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Maps blend combinations to Canvas. + * + * @memberof PIXI + * @function mapCanvasBlendModesToPixi + * @private + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapCanvasBlendModesToPixi() { + var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + + if ((0, _canUseNewCanvasBlendModes2.default)()) { + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'multiply'; + array[_const.BLEND_MODES.SCREEN] = 'screen'; + array[_const.BLEND_MODES.OVERLAY] = 'overlay'; + array[_const.BLEND_MODES.DARKEN] = 'darken'; + array[_const.BLEND_MODES.LIGHTEN] = 'lighten'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'color-dodge'; + array[_const.BLEND_MODES.COLOR_BURN] = 'color-burn'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'hard-light'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'soft-light'; + array[_const.BLEND_MODES.DIFFERENCE] = 'difference'; + array[_const.BLEND_MODES.EXCLUSION] = 'exclusion'; + array[_const.BLEND_MODES.HUE] = 'hue'; + array[_const.BLEND_MODES.SATURATION] = 'saturate'; + array[_const.BLEND_MODES.COLOR] = 'color'; + array[_const.BLEND_MODES.LUMINOSITY] = 'luminosity'; + } else { + // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'source-over'; + array[_const.BLEND_MODES.SCREEN] = 'source-over'; + array[_const.BLEND_MODES.OVERLAY] = 'source-over'; + array[_const.BLEND_MODES.DARKEN] = 'source-over'; + array[_const.BLEND_MODES.LIGHTEN] = 'source-over'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'source-over'; + array[_const.BLEND_MODES.COLOR_BURN] = 'source-over'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.DIFFERENCE] = 'source-over'; + array[_const.BLEND_MODES.EXCLUSION] = 'source-over'; + array[_const.BLEND_MODES.HUE] = 'source-over'; + array[_const.BLEND_MODES.SATURATION] = 'source-over'; + array[_const.BLEND_MODES.COLOR] = 'source-over'; + array[_const.BLEND_MODES.LUMINOSITY] = 'source-over'; + } + // not-premultiplied, only for webgl + array[_const.BLEND_MODES.NORMAL_NPM] = array[_const.BLEND_MODES.NORMAL]; + array[_const.BLEND_MODES.ADD_NPM] = array[_const.BLEND_MODES.ADD]; + array[_const.BLEND_MODES.SCREEN_NPM] = array[_const.BLEND_MODES.SCREEN]; + + return array; +} + +},{"../../../const":46,"./canUseNewCanvasBlendModes":80}],82:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged + * up with textures that are no longer being used. + * + * @class + * @memberof PIXI + */ +var TextureGarbageCollector = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function TextureGarbageCollector(renderer) { + _classCallCheck(this, TextureGarbageCollector); + + this.renderer = renderer; + + this.count = 0; + this.checkCount = 0; + this.maxIdle = _settings2.default.GC_MAX_IDLE; + this.checkCountMax = _settings2.default.GC_MAX_CHECK_COUNT; + this.mode = _settings2.default.GC_MODE; + } + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.update = function update() { + this.count++; + + if (this.mode === _const.GC_MODES.MANUAL) { + return; + } + + this.checkCount++; + + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + + this.run(); + } + }; + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.run = function run() { + var tm = this.renderer.textureManager; + var managedTextures = tm._managedTextures; + var wasRemoved = false; + + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + + // only supports non generated textures at the moment! + if (!texture._glRenderTargets && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + + if (wasRemoved) { + var j = 0; + + for (var _i = 0; _i < managedTextures.length; _i++) { + if (managedTextures[_i] !== null) { + managedTextures[j++] = managedTextures[_i]; + } + } + + managedTextures.length = j; + } + }; + + /** + * Removes all the textures within the specified displayObject and its children from the GPU + * + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + */ + + + TextureGarbageCollector.prototype.unload = function unload(displayObject) { + var tm = this.renderer.textureManager; + + // only destroy non generated textures + if (displayObject._texture && displayObject._texture._glRenderTargets) { + tm.destroyTexture(displayObject._texture, true); + } + + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + + return TextureGarbageCollector; +}(); + +exports.default = TextureGarbageCollector; + +},{"../../const":46,"../../settings":101}],83:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _const = require('../../const'); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _utils = require('../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a webGL Texture + * + * @class + * @memberof PIXI + */ +var TextureManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function TextureManager(renderer) { + _classCallCheck(this, TextureManager); + + /** + * A reference to the current renderer + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = renderer.gl; + + /** + * Track textures in the renderer so we can no longer listen to them on destruction. + * + * @member {Array<*>} + * @private + */ + this._managedTextures = []; + } + + /** + * Binds a texture. + * + */ + + + TextureManager.prototype.bindTexture = function bindTexture() {} + // empty + + + /** + * Gets a texture. + * + */ + ; + + TextureManager.prototype.getTexture = function getTexture() {} + // empty + + + /** + * Updates and/or Creates a WebGL texture for the renderer's context. + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update + * @param {number} location - the location the texture will be bound to. + * @return {GLTexture} The gl texture. + */ + ; + + TextureManager.prototype.updateTexture = function updateTexture(texture, location) { + // assume it good! + // texture = texture.baseTexture || texture; + + var gl = this.gl; + + var isRenderTexture = !!texture._glRenderTargets; + + if (!texture.hasLoaded) { + return null; + } + + var boundTextures = this.renderer.boundTextures; + + // if the location is undefined then this may have been called by n event. + // this being the case the texture may already be bound to a slot. As a texture can only be bound once + // we need to find its current location if it exists. + if (location === undefined) { + location = 0; + + // TODO maybe we can use texture bound ids later on... + // check if texture is already bound.. + for (var i = 0; i < boundTextures.length; ++i) { + if (boundTextures[i] === texture) { + location = i; + break; + } + } + } + + boundTextures[location] = texture; + + gl.activeTexture(gl.TEXTURE0 + location); + + var glTexture = texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!glTexture) { + if (isRenderTexture) { + var renderTarget = new _RenderTarget2.default(this.gl, texture.width, texture.height, texture.scaleMode, texture.resolution); + + renderTarget.resize(texture.width, texture.height); + texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget; + glTexture = renderTarget.texture; + } else { + glTexture = new _pixiGlCore.GLTexture(this.gl, null, null, null, null); + glTexture.bind(location); + glTexture.premultiplyAlpha = true; + glTexture.upload(texture.source); + } + + texture._glTextures[this.renderer.CONTEXT_UID] = glTexture; + + texture.on('update', this.updateTexture, this); + texture.on('dispose', this.destroyTexture, this); + + this._managedTextures.push(texture); + + if (texture.isPowerOfTwo) { + if (texture.mipmap) { + glTexture.enableMipmap(); + } + + if (texture.wrapMode === _const.WRAP_MODES.CLAMP) { + glTexture.enableWrapClamp(); + } else if (texture.wrapMode === _const.WRAP_MODES.REPEAT) { + glTexture.enableWrapRepeat(); + } else { + glTexture.enableWrapMirrorRepeat(); + } + } else { + glTexture.enableWrapClamp(); + } + + if (texture.scaleMode === _const.SCALE_MODES.NEAREST) { + glTexture.enableNearestScaling(); + } else { + glTexture.enableLinearScaling(); + } + } + // the texture already exists so we only need to update it.. + else if (isRenderTexture) { + texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height); + } else { + glTexture.upload(texture.source); + } + + return glTexture; + }; + + /** + * Deletes the texture from WebGL + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy + * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. + */ + + + TextureManager.prototype.destroyTexture = function destroyTexture(texture, skipRemove) { + texture = texture.baseTexture || texture; + + if (!texture.hasLoaded) { + return; + } + + var uid = this.renderer.CONTEXT_UID; + var glTextures = texture._glTextures; + var glRenderTargets = texture._glRenderTargets; + + if (glTextures[uid]) { + this.renderer.unbindTexture(texture); + + glTextures[uid].destroy(); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + + delete glTextures[uid]; + + if (!skipRemove) { + var i = this._managedTextures.indexOf(texture); + + if (i !== -1) { + (0, _utils.removeItems)(this._managedTextures, i, 1); + } + } + } + + if (glRenderTargets && glRenderTargets[uid]) { + glRenderTargets[uid].destroy(); + delete glRenderTargets[uid]; + } + }; + + /** + * Deletes all the textures from WebGL + */ + + + TextureManager.prototype.removeAll = function removeAll() { + // empty all the old gl textures as they are useless now + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + delete texture._glTextures[this.renderer.CONTEXT_UID]; + } + } + }; + + /** + * Destroys this manager and removes all its textures + */ + + + TextureManager.prototype.destroy = function destroy() { + // destroy managed textures + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + this.destroyTexture(texture, true); + + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + } + + this._managedTextures = null; + }; + + return TextureManager; +}(); + +exports.default = TextureManager; + +},{"../../const":46,"../../utils":125,"./utils/RenderTarget":96,"pixi-gl-core":15}],84:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _MaskManager = require('./managers/MaskManager'); + +var _MaskManager2 = _interopRequireDefault(_MaskManager); + +var _StencilManager = require('./managers/StencilManager'); + +var _StencilManager2 = _interopRequireDefault(_StencilManager); + +var _FilterManager = require('./managers/FilterManager'); + +var _FilterManager2 = _interopRequireDefault(_FilterManager); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _ObjectRenderer = require('./utils/ObjectRenderer'); + +var _ObjectRenderer2 = _interopRequireDefault(_ObjectRenderer); + +var _TextureManager = require('./TextureManager'); + +var _TextureManager2 = _interopRequireDefault(_TextureManager); + +var _BaseTexture = require('../../textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _TextureGarbageCollector = require('./TextureGarbageCollector'); + +var _TextureGarbageCollector2 = _interopRequireDefault(_TextureGarbageCollector); + +var _WebGLState = require('./WebGLState'); + +var _WebGLState2 = _interopRequireDefault(_WebGLState); + +var _mapWebGLDrawModesToPixi = require('./utils/mapWebGLDrawModesToPixi'); + +var _mapWebGLDrawModesToPixi2 = _interopRequireDefault(_mapWebGLDrawModesToPixi); + +var _validateContext = require('./utils/validateContext'); + +var _validateContext2 = _interopRequireDefault(_validateContext); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CONTEXT_UID = 0; + +/** + * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ + +var WebGLRenderer = function (_SystemRenderer) { + _inherits(WebGLRenderer, _SystemRenderer); + + // eslint-disable-next-line valid-jsdoc + /** + * + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias. If not available natively then FXAA + * antialiasing is used + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. + * The resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear + * the canvas or not before the new render pass. If you wish to set this to false, you *must* set + * preserveDrawingBuffer to `true`. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when + * rendering, stopping pixel interpolation. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.legacy=false] - If true PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering try setting this to true. + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card + */ + function WebGLRenderer(options, arg2, arg3) { + _classCallCheck(this, WebGLRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'WebGL', options, arg2, arg3)); + + _this.legacy = _this.options.legacy; + + if (_this.legacy) { + _pixiGlCore2.default.VertexArrayObject.FORCE_NATIVE = true; + } + + /** + * The type of this renderer as a standardised const + * + * @member {number} + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.WEBGL; + + _this.handleContextLost = _this.handleContextLost.bind(_this); + _this.handleContextRestored = _this.handleContextRestored.bind(_this); + + _this.view.addEventListener('webglcontextlost', _this.handleContextLost, false); + _this.view.addEventListener('webglcontextrestored', _this.handleContextRestored, false); + + /** + * The options passed in to create a new webgl context. + * + * @member {object} + * @private + */ + _this._contextOptions = { + alpha: _this.transparent, + antialias: _this.options.antialias, + premultipliedAlpha: _this.transparent && _this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: _this.options.preserveDrawingBuffer, + powerPreference: _this.options.powerPreference + }; + + _this._backgroundColorRgba[3] = _this.transparent ? 0 : 1; + + /** + * Manages the masks using the stencil buffer. + * + * @member {PIXI.MaskManager} + */ + _this.maskManager = new _MaskManager2.default(_this); + + /** + * Manages the stencil buffer. + * + * @member {PIXI.StencilManager} + */ + _this.stencilManager = new _StencilManager2.default(_this); + + /** + * An empty renderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.emptyRenderer = new _ObjectRenderer2.default(_this); + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.currentRenderer = _this.emptyRenderer; + + /** + * Manages textures + * @member {PIXI.TextureManager} + */ + _this.textureManager = null; + + /** + * Manages the filters. + * + * @member {PIXI.FilterManager} + */ + _this.filterManager = null; + + _this.initPlugins(); + + /** + * The current WebGL rendering context, it is created here + * + * @member {WebGLRenderingContext} + */ + // initialize the context so it is ready for the managers. + if (_this.options.context) { + // checks to see if a context is valid.. + (0, _validateContext2.default)(_this.options.context); + } + + _this.gl = _this.options.context || _pixiGlCore2.default.createContext(_this.view, _this._contextOptions); + + _this.CONTEXT_UID = CONTEXT_UID++; + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.WebGLState} + */ + _this.state = new _WebGLState2.default(_this.gl); + + _this.renderingToScreen = true; + + /** + * Holds the current state of textures bound to the GPU. + * @type {Array} + */ + _this.boundTextures = null; + + /** + * Holds the current shader + * + * @member {PIXI.Shader} + */ + _this._activeShader = null; + + _this._activeVao = null; + + /** + * Holds the current render target + * + * @member {PIXI.RenderTarget} + */ + _this._activeRenderTarget = null; + + _this._initContext(); + + // map some webGL blend and drawmodes.. + _this.drawModes = (0, _mapWebGLDrawModesToPixi2.default)(_this.gl); + + _this._nextTextureLocation = 0; + + _this.setBlendMode(0); + + /** + * Fired after rendering finishes. + * + * @event PIXI.WebGLRenderer#postrender + */ + + /** + * Fired before rendering starts. + * + * @event PIXI.WebGLRenderer#prerender + */ + + /** + * Fired when the WebGL context is set. + * + * @event PIXI.WebGLRenderer#context + * @param {WebGLRenderingContext} gl - WebGL context. + */ + return _this; + } + + /** + * Creates the WebGL context + * + * @private + */ + + + WebGLRenderer.prototype._initContext = function _initContext() { + var gl = this.gl; + + // restore a context if it was previously lost + if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').restoreContext(); + } + + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + + this._activeShader = null; + this._activeVao = null; + + this.boundTextures = new Array(maxTextures); + this.emptyTextures = new Array(maxTextures); + + // create a texture manager... + this.textureManager = new _TextureManager2.default(this); + this.filterManager = new _FilterManager2.default(this); + this.textureGC = new _TextureGarbageCollector2.default(this); + + this.state.resetToDefault(); + + this.rootRenderTarget = new _RenderTarget2.default(gl, this.width, this.height, null, this.resolution, true); + this.rootRenderTarget.clearColor = this._backgroundColorRgba; + + this.bindRenderTarget(this.rootRenderTarget); + + // now lets fill up the textures with empty ones! + var emptyGLTexture = new _pixiGlCore2.default.GLTexture.fromData(gl, null, 1, 1); + + var tempObj = { _glTextures: {} }; + + tempObj._glTextures[this.CONTEXT_UID] = {}; + + for (var i = 0; i < maxTextures; i++) { + var empty = new _BaseTexture2.default(); + + empty._glTextures[this.CONTEXT_UID] = emptyGLTexture; + + this.boundTextures[i] = tempObj; + this.emptyTextures[i] = empty; + this.bindTexture(null, i); + } + + this.emit('context', gl); + + // setup the width/height properties and gl viewport + this.resize(this.screen.width, this.screen.height); + }; + + /** + * Renders the object to its webGL view + * + * @param {PIXI.DisplayObject} displayObject - the object to be rendered + * @param {PIXI.RenderTexture} renderTexture - The render texture to render to. + * @param {boolean} [clear] - Should the canvas be cleared before the new render + * @param {PIXI.Matrix} [transform] - A transform to apply to the render texture before rendering. + * @param {boolean} [skipUpdateTransform] - Should we skip the update transform pass? + */ + + + WebGLRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + // no point rendering if our context has been blown up! + if (!this.gl || this.gl.isContextLost()) { + return; + } + + this._nextTextureLocation = 0; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + this.bindRenderTexture(renderTexture, transform); + + this.currentRenderer.start(); + + if (clear !== undefined ? clear : this.clearBeforeRender) { + this._activeRenderTarget.clear(); + } + + displayObject.renderWebGL(this); + + // apply transform.. + this.currentRenderer.flush(); + + // this.setObjectRenderer(this.emptyRenderer); + + this.textureGC.update(); + + this.emit('postrender'); + }; + + /** + * Changes the current renderer to the one given in parameter + * + * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. + */ + + + WebGLRenderer.prototype.setObjectRenderer = function setObjectRenderer(objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; + + /** + * This should be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + * + */ + + + WebGLRenderer.prototype.flush = function flush() { + this.setObjectRenderer(this.emptyRenderer); + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + WebGLRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + // if(width * this.resolution === this.width && height * this.resolution === this.height)return; + + _SystemRenderer3.default.prototype.resize.call(this, screenWidth, screenHeight); + + this.rootRenderTarget.resize(screenWidth, screenHeight); + + if (this._activeRenderTarget === this.rootRenderTarget) { + this.rootRenderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true); + } + } + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} blendMode - the desired blend mode + */ + + + WebGLRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + this.state.setBlendMode(blendMode); + }; + + /** + * Erases the active render target and fills the drawing area with a colour + * + * @param {number} [clearColor] - The colour + */ + + + WebGLRenderer.prototype.clear = function clear(clearColor) { + this._activeRenderTarget.clear(clearColor); + }; + + /** + * Sets the transform of the active render target to the given matrix + * + * @param {PIXI.Matrix} matrix - The transformation matrix + */ + + + WebGLRenderer.prototype.setTransform = function setTransform(matrix) { + this._activeRenderTarget.transform = matrix; + }; + + /** + * Erases the render texture and fills the drawing area with a colour + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to clear + * @param {number} [clearColor] - The colour + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.clearRenderTexture = function clearRenderTexture(renderTexture, clearColor) { + var baseTexture = renderTexture.baseTexture; + var renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + + if (renderTarget) { + renderTarget.clear(clearColor); + } + + return this; + }; + + /** + * Binds a render texture for rendering + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to render + * @param {PIXI.Matrix} transform - The transform to be applied to the render texture + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTexture = function bindRenderTexture(renderTexture, transform) { + var renderTarget = void 0; + + if (renderTexture) { + var baseTexture = renderTexture.baseTexture; + + if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) { + // bind the current texture + this.textureManager.updateTexture(baseTexture, 0); + } + + this.unbindTexture(baseTexture); + + renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + renderTarget.setFrame(renderTexture.frame); + } else { + renderTarget = this.rootRenderTarget; + } + + renderTarget.transform = transform; + this.bindRenderTarget(renderTarget); + + return this; + }; + + /** + * Changes the current render target to the one given in parameter + * + * @param {PIXI.RenderTarget} renderTarget - the new render target + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTarget = function bindRenderTarget(renderTarget) { + if (renderTarget !== this._activeRenderTarget) { + this._activeRenderTarget = renderTarget; + renderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true); + } + + this.stencilManager.setMaskStack(renderTarget.stencilMaskStack); + } + + return this; + }; + + /** + * Changes the current shader to the one given in parameter + * + * @param {PIXI.Shader} shader - the new shader + * @param {boolean} [autoProject=true] - Whether automatically set the projection matrix + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindShader = function bindShader(shader, autoProject) { + // TODO cache + if (this._activeShader !== shader) { + this._activeShader = shader; + shader.bind(); + + // `autoProject` normally would be a default parameter set to true + // but because of how Babel transpiles default parameters + // it hinders the performance of this method. + if (autoProject !== false) { + // automatically set the projection matrix + shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(true); + } + } + + return this; + }; + + /** + * Binds the texture. This will return the location of the bound texture. + * It may not be the same as the one you pass in. This is due to optimisation that prevents + * needless binding of textures. For example if the texture is already bound it will return the + * current location of the texture instead of the one provided. To bypass this use force location + * + * @param {PIXI.Texture} texture - the new texture + * @param {number} location - the suggested texture location + * @param {boolean} forceLocation - force the location + * @return {number} bound texture location + */ + + + WebGLRenderer.prototype.bindTexture = function bindTexture(texture, location, forceLocation) { + texture = texture || this.emptyTextures[location]; + texture = texture.baseTexture || texture; + texture.touched = this.textureGC.count; + + if (!forceLocation) { + // TODO - maybe look into adding boundIds.. save us the loop? + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + return i; + } + } + + if (location === undefined) { + this._nextTextureLocation++; + this._nextTextureLocation %= this.boundTextures.length; + location = this.boundTextures.length - this._nextTextureLocation - 1; + } + } else { + location = location || 0; + } + + var gl = this.gl; + var glTexture = texture._glTextures[this.CONTEXT_UID]; + + if (!glTexture) { + // this will also bind the texture.. + this.textureManager.updateTexture(texture, location); + } else { + // bind the current texture + this.boundTextures[location] = texture; + gl.activeTexture(gl.TEXTURE0 + location); + gl.bindTexture(gl.TEXTURE_2D, glTexture.texture); + } + + return location; + }; + + /** + * unbinds the texture ... + * + * @param {PIXI.Texture} texture - the texture to unbind + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.unbindTexture = function unbindTexture(texture) { + var gl = this.gl; + + texture = texture.baseTexture || texture; + + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + this.boundTextures[i] = this.emptyTextures[i]; + + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[i]._glTextures[this.CONTEXT_UID].texture); + } + } + + return this; + }; + + /** + * Creates a new VAO from this renderer's context and state. + * + * @return {VertexArrayObject} The new VAO. + */ + + + WebGLRenderer.prototype.createVao = function createVao() { + return new _pixiGlCore2.default.VertexArrayObject(this.gl, this.state.attribState); + }; + + /** + * Changes the current Vao to the one given in parameter + * + * @param {PIXI.VertexArrayObject} vao - the new Vao + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindVao = function bindVao(vao) { + if (this._activeVao === vao) { + return this; + } + + if (vao) { + vao.bind(); + } else if (this._activeVao) { + // TODO this should always be true i think? + this._activeVao.unbind(); + } + + this._activeVao = vao; + + return this; + }; + + /** + * Resets the WebGL state so you can render things however you fancy! + * + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.reset = function reset() { + this.setObjectRenderer(this.emptyRenderer); + + this.bindVao(null); + this._activeShader = null; + this._activeRenderTarget = this.rootRenderTarget; + + for (var i = 0; i < this.boundTextures.length; i++) { + this.boundTextures[i] = this.emptyTextures[i]; + } + + // bind the main frame buffer (the screen); + this.rootRenderTarget.activate(); + + this.state.resetToDefault(); + + return this; + }; + + /** + * Handles a lost webgl context + * + * @private + * @param {WebGLContextEvent} event - The context lost event. + */ + + + WebGLRenderer.prototype.handleContextLost = function handleContextLost(event) { + event.preventDefault(); + }; + + /** + * Handles a restored webgl context + * + * @private + */ + + + WebGLRenderer.prototype.handleContextRestored = function handleContextRestored() { + this.textureManager.removeAll(); + this.filterManager.destroy(true); + this._initContext(); + }; + + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + + + WebGLRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // remove listeners + this.view.removeEventListener('webglcontextlost', this.handleContextLost); + this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); + + this.textureManager.destroy(); + + // call base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.uid = 0; + + // destroy the managers + this.maskManager.destroy(); + this.stencilManager.destroy(); + this.filterManager.destroy(); + + this.maskManager = null; + this.filterManager = null; + this.textureManager = null; + this.currentRenderer = null; + + this.handleContextLost = null; + this.handleContextRestored = null; + + this._contextOptions = null; + this.gl.useProgram(null); + + if (this.gl.getExtension('WEBGL_lose_context')) { + this.gl.getExtension('WEBGL_lose_context').loseContext(); + } + + this.gl = null; + + // this = null; + }; + + return WebGLRenderer; +}(_SystemRenderer3.default); + +/** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @name PIXI.WebGLRenderer#plugins + * @type {object} + * @readonly + * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.extract.WebGLExtract} extract Extract image data from renderer. + * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.prepare.WebGLPrepare} prepare Pre-render display objects. + */ + +/** + * Adds a plugin to the renderer. + * + * @method PIXI.WebGLRenderer#registerPlugin + * @param {string} pluginName - The name of the plugin. + * @param {Function} ctor - The constructor function or class for the plugin. + */ + +exports.default = WebGLRenderer; +_utils.pluginTarget.mixin(WebGLRenderer); + +},{"../../const":46,"../../textures/BaseTexture":112,"../../utils":125,"../SystemRenderer":76,"./TextureGarbageCollector":82,"./TextureManager":83,"./WebGLState":85,"./managers/FilterManager":90,"./managers/MaskManager":91,"./managers/StencilManager":92,"./utils/ObjectRenderer":94,"./utils/RenderTarget":96,"./utils/mapWebGLDrawModesToPixi":99,"./utils/validateContext":100,"pixi-gl-core":15}],85:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); + +var _mapWebGLBlendModesToPixi2 = _interopRequireDefault(_mapWebGLBlendModesToPixi); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var BLEND = 0; +var DEPTH_TEST = 1; +var FRONT_FACE = 2; +var CULL_FACE = 3; +var BLEND_FUNC = 4; + +/** + * A WebGL state machines + * + * @memberof PIXI + * @class + */ + +var WebGLState = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + */ + function WebGLState(gl) { + _classCallCheck(this, WebGLState); + + /** + * The current active state + * + * @member {Uint8Array} + */ + this.activeState = new Uint8Array(16); + + /** + * The default state + * + * @member {Uint8Array} + */ + this.defaultState = new Uint8Array(16); + + // default blend mode.. + this.defaultState[0] = 1; + + /** + * The current state index in the stack + * + * @member {number} + * @private + */ + this.stackIndex = 0; + + /** + * The stack holding all the different states + * + * @member {Array<*>} + * @private + */ + this.stack = []; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + this.attribState = { + tempAttribState: new Array(this.maxAttribs), + attribState: new Array(this.maxAttribs) + }; + + this.blendModes = (0, _mapWebGLBlendModesToPixi2.default)(gl); + + // check we have vao.. + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || gl.getExtension('MOZ_OES_vertex_array_object') || gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + /** + * Pushes a new active state + */ + + + WebGLState.prototype.push = function push() { + // next state.. + var state = this.stack[this.stackIndex]; + + if (!state) { + state = this.stack[this.stackIndex] = new Uint8Array(16); + } + + ++this.stackIndex; + + // copy state.. + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) { + state[i] = this.activeState[i]; + } + }; + + /** + * Pops a state out + */ + + + WebGLState.prototype.pop = function pop() { + var state = this.stack[--this.stackIndex]; + + this.setState(state); + }; + + /** + * Sets the current state + * + * @param {*} state - The state to set. + */ + + + WebGLState.prototype.setState = function setState(state) { + this.setBlend(state[BLEND]); + this.setDepthTest(state[DEPTH_TEST]); + this.setFrontFace(state[FRONT_FACE]); + this.setCullFace(state[CULL_FACE]); + this.setBlendMode(state[BLEND_FUNC]); + }; + + /** + * Enables or disabled blending. + * + * @param {boolean} value - Turn on or off webgl blending. + */ + + + WebGLState.prototype.setBlend = function setBlend(value) { + value = value ? 1 : 0; + + if (this.activeState[BLEND] === value) { + return; + } + + this.activeState[BLEND] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + }; + + /** + * Sets the blend mode. + * + * @param {number} value - The blend mode to set to. + */ + + + WebGLState.prototype.setBlendMode = function setBlendMode(value) { + if (value === this.activeState[BLEND_FUNC]) { + return; + } + + this.activeState[BLEND_FUNC] = value; + + var mode = this.blendModes[value]; + + if (mode.length === 2) { + this.gl.blendFunc(mode[0], mode[1]); + } else { + this.gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); + } + }; + + /** + * Sets whether to enable or disable depth test. + * + * @param {boolean} value - Turn on or off webgl depth testing. + */ + + + WebGLState.prototype.setDepthTest = function setDepthTest(value) { + value = value ? 1 : 0; + + if (this.activeState[DEPTH_TEST] === value) { + return; + } + + this.activeState[DEPTH_TEST] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + }; + + /** + * Sets whether to enable or disable cull face. + * + * @param {boolean} value - Turn on or off webgl cull face. + */ + + + WebGLState.prototype.setCullFace = function setCullFace(value) { + value = value ? 1 : 0; + + if (this.activeState[CULL_FACE] === value) { + return; + } + + this.activeState[CULL_FACE] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + }; + + /** + * Sets the gl front face. + * + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ + + + WebGLState.prototype.setFrontFace = function setFrontFace(value) { + value = value ? 1 : 0; + + if (this.activeState[FRONT_FACE] === value) { + return; + } + + this.activeState[FRONT_FACE] = value; + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); + }; + + /** + * Disables all the vaos in use + * + */ + + + WebGLState.prototype.resetAttributes = function resetAttributes() { + for (var i = 0; i < this.attribState.tempAttribState.length; i++) { + this.attribState.tempAttribState[i] = 0; + } + + for (var _i = 0; _i < this.attribState.attribState.length; _i++) { + this.attribState.attribState[_i] = 0; + } + + // im going to assume one is always active for performance reasons. + for (var _i2 = 1; _i2 < this.maxAttribs; _i2++) { + this.gl.disableVertexAttribArray(_i2); + } + }; + + // used + /** + * Resets all the logic and disables the vaos + */ + + + WebGLState.prototype.resetToDefault = function resetToDefault() { + // unbind any VAO if they exist.. + if (this.nativeVaoExtension) { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + // reset all attributes.. + this.resetAttributes(); + + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; ++i) { + this.activeState[i] = 32; + } + + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + + this.setState(this.defaultState); + }; + + return WebGLState; +}(); + +exports.default = WebGLState; + +},{"./utils/mapWebGLBlendModesToPixi":98}],86:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _extractUniformsFromSrc = require('./extractUniformsFromSrc'); + +var _extractUniformsFromSrc2 = _interopRequireDefault(_extractUniformsFromSrc); + +var _utils = require('../../../utils'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SOURCE_KEY_MAP = {}; + +// let math = require('../../../math'); +/** + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ + +var Filter = function () { + /** + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. + */ + function Filter(vertexSrc, fragmentSrc, uniforms) { + _classCallCheck(this, Filter); + + /** + * The vertex shader. + * + * @member {string} + */ + this.vertexSrc = vertexSrc || Filter.defaultVertexSrc; + + /** + * The fragment shader. + * + * @member {string} + */ + this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc; + + this._blendMode = _const.BLEND_MODES.NORMAL; + + this.uniformData = uniforms || (0, _extractUniformsFromSrc2.default)(this.vertexSrc, this.fragmentSrc, 'projectionMatrix|uSampler'); + + /** + * An object containing the current values of custom uniforms. + * @example Updating the value of a custom uniform + * filter.uniforms.time = performance.now(); + * + * @member {object} + */ + this.uniforms = {}; + + for (var i in this.uniformData) { + this.uniforms[i] = this.uniformData[i].value; + if (this.uniformData[i].type) { + this.uniformData[i].type = this.uniformData[i].type.toLowerCase(); + } + } + + // this is where we store shader references.. + // TODO we could cache this! + this.glShaders = {}; + + // used for caching.. sure there is a better way! + if (!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) { + SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = (0, _utils.uid)(); + } + + this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]; + + /** + * The padding of the filter. Some filters require extra space to breath such as a blur. + * Increasing this will add extra width and height to the bounds of the object that the + * filter is applied to. + * + * @member {number} + */ + this.padding = 4; + + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + * + * @member {number} + */ + this.resolution = _settings2.default.FILTER_RESOLUTION; + + /** + * If enabled is true the filter is applied, if false it will not. + * + * @member {boolean} + */ + this.enabled = true; + + /** + * If enabled, PixiJS will fit the filter area into boundaries for better performance. + * Switch it off if it does not work for specific shader. + * + * @member {boolean} + */ + this.autoFit = true; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + * @param {object} [currentState] - It's current state of filter. + * There are some useful properties in the currentState : + * target, filters, sourceFrame, destinationFrame, renderTarget, resolution + */ + + + Filter.prototype.apply = function apply(filterManager, input, output, clear, currentState) // eslint-disable-line no-unused-vars + { + // --- // + // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); + + // do as you please! + + filterManager.applyFilter(this, input, output, clear); + + // or just do a regular render.. + }; + + /** + * Sets the blendmode of the filter + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + */ + + + _createClass(Filter, [{ + key: 'blendMode', + get: function get() { + return this._blendMode; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._blendMode = value; + } + + /** + * The default vertex shader source + * + * @static + * @constant + */ + + }], [{ + key: 'defaultVertexSrc', + get: function get() { + return ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform mat3 projectionMatrix;', 'uniform mat3 filterMatrix;', 'varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;', ' vTextureCoord = aTextureCoord ;', '}'].join('\n'); + } + + /** + * The default fragment shader source + * + * @static + * @constant + */ + + }, { + key: 'defaultFragmentSrc', + get: function get() { + return ['varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'uniform sampler2D uSampler;', 'uniform sampler2D filterSampler;', 'void main(void){', ' vec4 masky = texture2D(filterSampler, vFilterCoord);', ' vec4 sample = texture2D(uSampler, vTextureCoord);', ' vec4 color;', ' if(mod(vFilterCoord.x, 1.0) > 0.5)', ' {', ' color = vec4(1.0, 0.0, 0.0, 1.0);', ' }', ' else', ' {', ' color = vec4(0.0, 1.0, 0.0, 1.0);', ' }', + // ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', + ' gl_FragColor = mix(sample, masky, 0.5);', ' gl_FragColor *= sample.a;', '}'].join('\n'); + } + }]); + + return Filter; +}(); + +exports.default = Filter; + +},{"../../../const":46,"../../../settings":101,"../../../utils":125,"./extractUniformsFromSrc":87}],87:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = extractUniformsFromSrc; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var defaultValue = _pixiGlCore2.default.shader.defaultValue; + +function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) { + var vertUniforms = extractUniformsFromString(vertexSrc, mask); + var fragUniforms = extractUniformsFromString(fragmentSrc, mask); + + return Object.assign(vertUniforms, fragUniforms); +} + +function extractUniformsFromString(string) { + var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea|filterClamp)$'); + + var uniforms = {}; + var nameSplit = void 0; + + // clean the lines a little - remove extra spaces / tabs etc + // then split along ';' + var lines = string.replace(/\s+/g, ' ').split(/\s*;\s*/); + + // loop through.. + for (var i = 0; i < lines.length; i++) { + var line = lines[i].trim(); + + if (line.indexOf('uniform') > -1) { + var splitLine = line.split(' '); + var type = splitLine[1]; + + var name = splitLine[2]; + var size = 1; + + if (name.indexOf('[') > -1) { + // array! + nameSplit = name.split(/\[|]/); + name = nameSplit[0]; + size *= Number(nameSplit[1]); + } + + if (!name.match(maskRegex)) { + uniforms[name] = { + value: defaultValue(type, size), + name: name, + type: type + }; + } + } + } + + return uniforms; +} + +},{"pixi-gl-core":15}],88:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.calculateScreenSpaceMatrix = calculateScreenSpaceMatrix; +exports.calculateNormalizedScreenSpaceMatrix = calculateNormalizedScreenSpaceMatrix; +exports.calculateSpriteMatrix = calculateSpriteMatrix; + +var _math = require('../../../math'); + +/** + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + * @private + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// this returns a matrix that will normalise map filter cords in the filter to screen space +function calculateScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + // let worldTransform = sprite.worldTransform.copy(Matrix.TEMP_MATRIX), + // let texture = {width:1136, height:700};//sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(textureSize.width, textureSize.height); + + return mappedMatrix; +} + +function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + var translateScaleX = textureSize.width / filterArea.width; + var translateScaleY = textureSize.height / filterArea.height; + + mappedMatrix.scale(translateScaleX, translateScaleY); + + return mappedMatrix; +} + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +function calculateSpriteMatrix(outputMatrix, filterArea, textureSize, sprite) { + var orig = sprite._texture.orig; + var mappedMatrix = outputMatrix.set(textureSize.width, 0, 0, textureSize.height, filterArea.x, filterArea.y); + var worldTransform = sprite.worldTransform.copy(_math.Matrix.TEMP_MATRIX); + + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height); + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; +} + +},{"../../../math":70}],89:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Filter2 = require('../Filter'); + +var _Filter3 = _interopRequireDefault(_Filter2); + +var _math = require('../../../../math'); + +var _path = require('path'); + +var _TextureMatrix = require('../../../../textures/TextureMatrix'); + +var _TextureMatrix2 = _interopRequireDefault(_TextureMatrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The SpriteMaskFilter class + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + */ +var SpriteMaskFilter = function (_Filter) { + _inherits(SpriteMaskFilter, _Filter); + + /** + * @param {PIXI.Sprite} sprite - the target sprite + */ + function SpriteMaskFilter(sprite) { + _classCallCheck(this, SpriteMaskFilter); + + var maskMatrix = new _math.Matrix(); + + var _this = _possibleConstructorReturn(this, _Filter.call(this, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n', 'varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n')); + + sprite.renderable = false; + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + return _this; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + */ + + + SpriteMaskFilter.prototype.apply = function apply(filterManager, input, output) { + var maskSprite = this.maskSprite; + var tex = this.maskSprite.texture; + + if (!tex.valid) { + return; + } + if (!tex.transform) { + // margin = 0.0, let it bleed a bit, shader code becomes easier + // assuming that atlas textures were made with 1-pixel padding + tex.transform = new _TextureMatrix2.default(tex, 0.0); + } + tex.transform.update(); + + this.uniforms.mask = tex; + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite).prepend(tex.transform.mapCoord); + this.uniforms.alpha = maskSprite.worldAlpha; + this.uniforms.maskClamp = tex.transform.uClampFrame; + + filterManager.applyFilter(this, input, output); + }; + + return SpriteMaskFilter; +}(_Filter3.default); + +exports.default = SpriteMaskFilter; + +},{"../../../../math":70,"../../../../textures/TextureMatrix":116,"../Filter":86,"path":8}],90:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _RenderTarget = require('../utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _Quad = require('../utils/Quad'); + +var _Quad2 = _interopRequireDefault(_Quad); + +var _math = require('../../../math'); + +var _Shader = require('../../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _filterTransforms = require('../filters/filterTransforms'); + +var filterTransforms = _interopRequireWildcard(_filterTransforms); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @ignore + * @class + */ +var FilterState = function () { + /** + * + */ + function FilterState() { + _classCallCheck(this, FilterState); + + this.renderTarget = null; + this.target = null; + this.resolution = 1; + + // those three objects are used only for root + // re-assigned for everything else + this.sourceFrame = new _math.Rectangle(); + this.destinationFrame = new _math.Rectangle(); + this.filters = []; + } + + /** + * clears the state + */ + + + FilterState.prototype.clear = function clear() { + this.filters = null; + this.target = null; + this.renderTarget = null; + }; + + return FilterState; +}(); + +var screenKey = 'screen'; + +/** + * @class + * @memberof PIXI + * @extends PIXI.WebGLManager + */ + +var FilterManager = function (_WebGLManager) { + _inherits(FilterManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function FilterManager(renderer) { + _classCallCheck(this, FilterManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.gl = _this.renderer.gl; + // know about sprites! + _this.quad = new _Quad2.default(_this.gl, renderer.state.attribState); + + _this.shaderCache = {}; + // todo add default! + _this.pool = {}; + + _this.filterData = null; + + _this.managedFilters = []; + + _this.renderer.on('prerender', _this.onPrerender, _this); + + _this._screenWidth = renderer.view.width; + _this._screenHeight = renderer.view.height; + return _this; + } + + /** + * Adds a new filter to the manager. + * + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param {PIXI.Filter[]} filters - The filters to apply. + */ + + + FilterManager.prototype.pushFilter = function pushFilter(target, filters) { + var renderer = this.renderer; + + var filterData = this.filterData; + + if (!filterData) { + filterData = this.renderer._activeRenderTarget.filterStack; + + // add new stack + var filterState = new FilterState(); + + filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; + filterState.renderTarget = renderer._activeRenderTarget; + + this.renderer._activeRenderTarget.filterData = filterData = { + index: 0, + stack: [filterState] + }; + + this.filterData = filterData; + } + + // get the current filter state.. + var currentState = filterData.stack[++filterData.index]; + var renderTargetFrame = filterData.stack[0].destinationFrame; + + if (!currentState) { + currentState = filterData.stack[filterData.index] = new FilterState(); + } + + var fullScreen = target.filterArea && target.filterArea.x === 0 && target.filterArea.y === 0 && target.filterArea.width === renderer.screen.width && target.filterArea.height === renderer.screen.height; + + // for now we go off the filter of the first resolution.. + var resolution = filters[0].resolution; + var padding = filters[0].padding | 0; + var targetBounds = fullScreen ? renderer.screen : target.filterArea || target.getBounds(true); + var sourceFrame = currentState.sourceFrame; + var destinationFrame = currentState.destinationFrame; + + sourceFrame.x = (targetBounds.x * resolution | 0) / resolution; + sourceFrame.y = (targetBounds.y * resolution | 0) / resolution; + sourceFrame.width = (targetBounds.width * resolution | 0) / resolution; + sourceFrame.height = (targetBounds.height * resolution | 0) / resolution; + + if (!fullScreen) { + if (filterData.stack[0].renderTarget.transform) {// + + // TODO we should fit the rect around the transform.. + } else if (filters[0].autoFit) { + sourceFrame.fit(renderTargetFrame); + } + + // lets apply the padding After we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + sourceFrame.pad(padding); + } + + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + + // lets play the padding after we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + + var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); + + currentState.target = target; + currentState.filters = filters; + currentState.resolution = resolution; + currentState.renderTarget = renderTarget; + + // bind the render target to draw the shape in the top corner.. + + renderTarget.setFrame(destinationFrame, sourceFrame); + + // bind the render target + renderer.bindRenderTarget(renderTarget); + renderTarget.clear(); + }; + + /** + * Pops off the filter and applies it. + * + */ + + + FilterManager.prototype.popFilter = function popFilter() { + var filterData = this.filterData; + + var lastState = filterData.stack[filterData.index - 1]; + var currentState = filterData.stack[filterData.index]; + + this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); + + var filters = currentState.filters; + + if (filters.length === 1) { + filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false, currentState); + this.freePotRenderTarget(currentState.renderTarget); + } else { + var flip = currentState.renderTarget; + var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, currentState.resolution); + + flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + // finally lets clear the render target before drawing to it.. + flop.clear(); + + var i = 0; + + for (i = 0; i < filters.length - 1; ++i) { + filters[i].apply(this, flip, flop, true, currentState); + + var t = flip; + + flip = flop; + flop = t; + } + + filters[i].apply(this, flip, lastState.renderTarget, false, currentState); + + this.freePotRenderTarget(flip); + this.freePotRenderTarget(flop); + } + + currentState.clear(); + filterData.index--; + + if (filterData.index === 0) { + this.filterData = null; + } + }; + + /** + * Draws a filter. + * + * @param {PIXI.Filter} filter - The filter to draw. + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + FilterManager.prototype.applyFilter = function applyFilter(filter, input, output, clear) { + var renderer = this.renderer; + var gl = renderer.gl; + + var shader = filter.glShaders[renderer.CONTEXT_UID]; + + // caching.. + if (!shader) { + if (filter.glShaderKey) { + shader = this.shaderCache[filter.glShaderKey]; + + if (!shader) { + shader = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + + filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = shader; + this.managedFilters.push(filter); + } + } else { + shader = filter.glShaders[renderer.CONTEXT_UID] = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + this.managedFilters.push(filter); + } + + // TODO - this only needs to be done once? + renderer.bindVao(null); + + this.quad.initVao(shader); + } + + renderer.bindVao(this.quad.vao); + + renderer.bindRenderTarget(output); + + if (clear) { + gl.disable(gl.SCISSOR_TEST); + renderer.clear(); // [1, 1, 1, 1]); + gl.enable(gl.SCISSOR_TEST); + } + + // in case the render target is being masked using a scissor rect + if (output === renderer.maskManager.scissorRenderTarget) { + renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); + } + + renderer.bindShader(shader); + + // free unit 0 for us, doesn't matter what was there + // don't try to restore it, because syncUniforms can upload it to another slot + // and it'll be a problem + var tex = this.renderer.emptyTextures[0]; + + this.renderer.boundTextures[0] = tex; + // this syncs the PixiJS filters uniforms with glsl uniforms + this.syncUniforms(shader, filter); + + renderer.state.setBlendMode(filter.blendMode); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, input.texture.texture); + + this.quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + }; + + /** + * Uploads the uniforms of the filter. + * + * @param {GLShader} shader - The underlying gl shader. + * @param {PIXI.Filter} filter - The filter we are synchronizing. + */ + + + FilterManager.prototype.syncUniforms = function syncUniforms(shader, filter) { + var uniformData = filter.uniformData; + var uniforms = filter.uniforms; + + // 0 is reserved for the PixiJS texture so we start at 1! + var textureCount = 1; + var currentState = void 0; + + // filterArea and filterClamp that are handled by FilterManager directly + // they must not appear in uniformData + + if (shader.uniforms.filterArea) { + currentState = this.filterData.stack[this.filterData.index]; + + var filterArea = shader.uniforms.filterArea; + + filterArea[0] = currentState.renderTarget.size.width; + filterArea[1] = currentState.renderTarget.size.height; + filterArea[2] = currentState.sourceFrame.x; + filterArea[3] = currentState.sourceFrame.y; + + shader.uniforms.filterArea = filterArea; + } + + // use this to clamp displaced texture coords so they belong to filterArea + // see displacementFilter fragment shader for an example + if (shader.uniforms.filterClamp) { + currentState = currentState || this.filterData.stack[this.filterData.index]; + + var filterClamp = shader.uniforms.filterClamp; + + filterClamp[0] = 0; + filterClamp[1] = 0; + filterClamp[2] = (currentState.sourceFrame.width - 1) / currentState.renderTarget.size.width; + filterClamp[3] = (currentState.sourceFrame.height - 1) / currentState.renderTarget.size.height; + + shader.uniforms.filterClamp = filterClamp; + } + + // TODO Caching layer.. + for (var i in uniformData) { + var type = uniformData[i].type; + + if (type === 'sampler2d' && uniforms[i] !== 0) { + if (uniforms[i].baseTexture) { + shader.uniforms[i] = this.renderer.bindTexture(uniforms[i].baseTexture, textureCount); + } else { + shader.uniforms[i] = textureCount; + + // TODO + // this is helpful as renderTargets can also be set. + // Although thinking about it, we could probably + // make the filter texture cache return a RenderTexture + // rather than a renderTarget + var gl = this.renderer.gl; + + this.renderer.boundTextures[textureCount] = this.renderer.emptyTextures[textureCount]; + gl.activeTexture(gl.TEXTURE0 + textureCount); + + uniforms[i].texture.bind(); + } + + textureCount++; + } else if (type === 'mat3') { + // check if its PixiJS matrix.. + if (uniforms[i].a !== undefined) { + shader.uniforms[i] = uniforms[i].toArray(true); + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (type === 'vec2') { + // check if its a point.. + if (uniforms[i].x !== undefined) { + var val = shader.uniforms[i] || new Float32Array(2); + + val[0] = uniforms[i].x; + val[1] = uniforms[i].y; + shader.uniforms[i] = val; + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (type === 'float') { + if (shader.uniforms.data[i].value !== uniformData[i]) { + shader.uniforms[i] = uniforms[i]; + } + } else { + shader.uniforms[i] = uniforms[i]; + } + } + }; + + /** + * Gets a render target from the pool, or creates a new one. + * + * @param {boolean} clear - Should we clear the render texture when we get it? + * @param {number} resolution - The resolution of the target. + * @return {PIXI.RenderTarget} The new render target + */ + + + FilterManager.prototype.getRenderTarget = function getRenderTarget(clear, resolution) { + var currentState = this.filterData.stack[this.filterData.index]; + var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution); + + renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + return renderTarget; + }; + + /** + * Returns a render target to the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The render target to return. + */ + + + FilterManager.prototype.returnRenderTarget = function returnRenderTarget(renderTarget) { + this.freePotRenderTarget(renderTarget); + }; + + /** + * Calculates the mapped matrix. + * + * TODO playing around here.. this is temporary - (will end up in the shader) + * this returns a matrix that will normalise map filter cords in the filter to screen space + * + * @param {PIXI.Matrix} outputMatrix - the matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateScreenSpaceMatrix = function calculateScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); + }; + + /** + * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function calculateNormalizedScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); + }; + + /** + * This will map the filter coord so that a texture can be used based on the transform of a sprite + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateSpriteMatrix = function calculateSpriteMatrix(outputMatrix, sprite) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); + }; + + /** + * Destroys this Filter Manager. + * + * @param {boolean} [contextLost=false] context was lost, do not free shaders + * + */ + + + FilterManager.prototype.destroy = function destroy() { + var contextLost = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + var renderer = this.renderer; + var filters = this.managedFilters; + + renderer.off('prerender', this.onPrerender, this); + + for (var i = 0; i < filters.length; i++) { + if (!contextLost) { + filters[i].glShaders[renderer.CONTEXT_UID].destroy(); + } + delete filters[i].glShaders[renderer.CONTEXT_UID]; + } + + this.shaderCache = {}; + if (!contextLost) { + this.emptyPool(); + } else { + this.pool = {}; + } + }; + + /** + * Gets a Power-of-Two render texture. + * + * TODO move to a separate class could be on renderer? + * also - could cause issue with multiple contexts? + * + * @private + * @param {WebGLRenderingContext} gl - The webgl rendering context + * @param {number} minWidth - The minimum width of the render target. + * @param {number} minHeight - The minimum height of the render target. + * @param {number} resolution - The resolution of the render target. + * @return {PIXI.RenderTarget} The new render target. + */ + + + FilterManager.prototype.getPotRenderTarget = function getPotRenderTarget(gl, minWidth, minHeight, resolution) { + var key = screenKey; + + minWidth *= resolution; + minHeight *= resolution; + + if (minWidth !== this._screenWidth || minHeight !== this._screenHeight) { + // TODO you could return a bigger texture if there is not one in the pool? + minWidth = _bitTwiddle2.default.nextPow2(minWidth); + minHeight = _bitTwiddle2.default.nextPow2(minHeight); + key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + } + + if (!this.pool[key]) { + this.pool[key] = []; + } + + var renderTarget = this.pool[key].pop(); + + // creating render target will cause texture to be bound! + if (!renderTarget) { + // temporary bypass cache.. + var tex = this.renderer.boundTextures[0]; + + gl.activeTexture(gl.TEXTURE0); + + // internally - this will cause a texture to be bound.. + renderTarget = new _RenderTarget2.default(gl, minWidth, minHeight, null, 1); + + // set the current one back + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + } + + // manually tweak the resolution... + // this will not modify the size of the frame buffer, just its resolution. + renderTarget.resolution = resolution; + renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution; + renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution; + renderTarget.filterPoolKey = key; + + return renderTarget; + }; + + /** + * Empties the texture pool. + * + */ + + + FilterManager.prototype.emptyPool = function emptyPool() { + for (var i in this.pool) { + var textures = this.pool[i]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + + this.pool = {}; + }; + + /** + * Frees a render target back into the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free + */ + + + FilterManager.prototype.freePotRenderTarget = function freePotRenderTarget(renderTarget) { + this.pool[renderTarget.filterPoolKey].push(renderTarget); + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + FilterManager.prototype.onPrerender = function onPrerender() { + if (this._screenWidth !== this.renderer.view.width || this._screenHeight !== this.renderer.view.height) { + this._screenWidth = this.renderer.view.width; + this._screenHeight = this.renderer.view.height; + + var textures = this.pool[screenKey]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + this.pool[screenKey] = []; + } + }; + + return FilterManager; +}(_WebGLManager3.default); + +exports.default = FilterManager; + +},{"../../../Shader":44,"../../../math":70,"../filters/filterTransforms":88,"../utils/Quad":95,"../utils/RenderTarget":96,"./WebGLManager":93,"bit-twiddle":1}],91:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _SpriteMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); + +var _SpriteMaskFilter2 = _interopRequireDefault(_SpriteMaskFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var MaskManager = function (_WebGLManager) { + _inherits(MaskManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function MaskManager(renderer) { + _classCallCheck(this, MaskManager); + + // TODO - we don't need both! + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.scissor = false; + _this.scissorData = null; + _this.scissorRenderTarget = null; + + _this.enableScissor = true; + + _this.alphaMaskPool = []; + _this.alphaMaskIndex = 0; + return _this; + } + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushMask = function pushMask(target, maskData) { + // TODO the root check means scissor rect will not + // be used on render textures more info here: + // https://github.com/pixijs/pixi.js/pull/3545 + + if (maskData.texture) { + this.pushSpriteMask(target, maskData); + } else if (this.enableScissor && !this.scissor && this.renderer._activeRenderTarget.root && !this.renderer.stencilManager.stencilMaskStack.length && maskData.isFastRect()) { + var matrix = maskData.worldTransform; + + var rot = Math.atan2(matrix.b, matrix.a); + + // use the nearest degree! + rot = Math.round(rot * (180 / Math.PI)); + + if (rot % 90) { + this.pushStencilMask(maskData); + } else { + this.pushScissorMask(target, maskData); + } + } else { + this.pushStencilMask(maskData); + } + }; + + /** + * Removes the last mask from the mask stack and doesn't return it. + * + * @param {PIXI.DisplayObject} target - Display Object to pop the mask from + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.popMask = function popMask(target, maskData) { + if (maskData.texture) { + this.popSpriteMask(target, maskData); + } else if (this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length) { + this.popScissorMask(target, maskData); + } else { + this.popStencilMask(target, maskData); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.RenderTarget} target - Display Object to push the sprite mask to + * @param {PIXI.Sprite} maskData - Sprite to be used as the mask + */ + + + MaskManager.prototype.pushSpriteMask = function pushSpriteMask(target, maskData) { + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new _SpriteMaskFilter2.default(maskData)]; + } + + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskData; + + // TODO - may cause issues! + target.filterArea = maskData.getBounds(true); + + this.renderer.filterManager.pushFilter(target, alphaMaskFilter); + + this.alphaMaskIndex++; + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popSpriteMask = function popSpriteMask() { + this.renderer.filterManager.popFilter(); + this.alphaMaskIndex--; + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushStencilMask = function pushStencilMask(maskData) { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.pushStencil(maskData); + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popStencilMask = function popStencilMask() { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.popStencil(); + }; + + /** + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushScissorMask = function pushScissorMask(target, maskData) { + maskData.renderable = true; + + var renderTarget = this.renderer._activeRenderTarget; + + var bounds = maskData.getBounds(); + + bounds.fit(renderTarget.size); + maskData.renderable = false; + + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + + var resolution = this.renderer.resolution; + + this.renderer.gl.scissor(bounds.x * resolution, (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution, bounds.width * resolution, bounds.height * resolution); + + this.scissorRenderTarget = renderTarget; + this.scissorData = maskData; + this.scissor = true; + }; + + /** + * + * + */ + + + MaskManager.prototype.popScissorMask = function popScissorMask() { + this.scissorRenderTarget = null; + this.scissorData = null; + this.scissor = false; + + // must be scissor! + var gl = this.renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + }; + + return MaskManager; +}(_WebGLManager3.default); + +exports.default = MaskManager; + +},{"../filters/spriteMask/SpriteMaskFilter":89,"./WebGLManager":93}],92:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var StencilManager = function (_WebGLManager) { + _inherits(StencilManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function StencilManager(renderer) { + _classCallCheck(this, StencilManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.stencilMaskStack = null; + return _this; + } + + /** + * Changes the mask stack that is used by this manager. + * + * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack + */ + + + StencilManager.prototype.setMaskStack = function setMaskStack(stencilMaskStack) { + this.stencilMaskStack = stencilMaskStack; + + var gl = this.renderer.gl; + + if (stencilMaskStack.length === 0) { + gl.disable(gl.STENCIL_TEST); + } else { + gl.enable(gl.STENCIL_TEST); + } + }; + + /** + * Applies the Mask and adds it to the current stencil stack. @alvin + * + * @param {PIXI.Graphics} graphics - The mask + */ + + + StencilManager.prototype.pushStencil = function pushStencil(graphics) { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + this.renderer._activeRenderTarget.attachStencilBuffer(); + + var gl = this.renderer.gl; + var prevMaskCount = this.stencilMaskStack.length; + + if (prevMaskCount === 0) { + gl.enable(gl.STENCIL_TEST); + } + + this.stencilMaskStack.push(graphics); + + // Increment the reference stencil value where the new mask overlaps with the old ones. + gl.colorMask(false, false, false, false); + gl.stencilFunc(gl.EQUAL, prevMaskCount, this._getBitwiseMask()); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + this.renderer.plugins.graphics.render(graphics); + + this._useCurrent(); + }; + + /** + * Removes the last mask from the stencil stack. @alvin + */ + + + StencilManager.prototype.popStencil = function popStencil() { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + var gl = this.renderer.gl; + var graphics = this.stencilMaskStack.pop(); + + if (this.stencilMaskStack.length === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.clearStencil(0); + } else { + // Decrement the reference stencil value where the popped mask overlaps with the other ones + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + this.renderer.plugins.graphics.render(graphics); + + this._useCurrent(); + } + }; + + /** + * Setup renderer to use the current stencil data. + */ + + + StencilManager.prototype._useCurrent = function _useCurrent() { + var gl = this.renderer.gl; + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.EQUAL, this.stencilMaskStack.length, this._getBitwiseMask()); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; + + /** + * Fill 1s equal to the number of acitve stencil masks. + * + * @return {number} The bitwise mask. + */ + + + StencilManager.prototype._getBitwiseMask = function _getBitwiseMask() { + return (1 << this.stencilMaskStack.length) - 1; + }; + + /** + * Destroys the mask stack. + * + */ + + + StencilManager.prototype.destroy = function destroy() { + _WebGLManager3.default.prototype.destroy.call(this); + + this.stencilMaskStack.stencilStack = null; + }; + + return StencilManager; +}(_WebGLManager3.default); + +exports.default = StencilManager; + +},{"./WebGLManager":93}],93:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var WebGLManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function WebGLManager(renderer) { + _classCallCheck(this, WebGLManager); + + /** + * The renderer this manager works for. + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + this.renderer.on('context', this.onContextChange, this); + } + + /** + * Generic method called when there is a WebGL context change. + * + */ + + + WebGLManager.prototype.onContextChange = function onContextChange() {} + // do some codes init! + + + /** + * Generic destroy methods to be overridden by the subclass + * + */ + ; + + WebGLManager.prototype.destroy = function destroy() { + this.renderer.off('context', this.onContextChange, this); + + this.renderer = null; + }; + + return WebGLManager; +}(); + +exports.default = WebGLManager; + +},{}],94:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('../managers/WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Base for a common object renderer that can be used as a system renderer plugin. + * + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var ObjectRenderer = function (_WebGLManager) { + _inherits(ObjectRenderer, _WebGLManager); + + function ObjectRenderer() { + _classCallCheck(this, ObjectRenderer); + + return _possibleConstructorReturn(this, _WebGLManager.apply(this, arguments)); + } + + /** + * Starts the renderer and sets the shader + * + */ + ObjectRenderer.prototype.start = function start() {} + // set the shader.. + + + /** + * Stops the renderer + * + */ + ; + + ObjectRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Stub method for rendering content and emptying the current batch. + * + */ + + + ObjectRenderer.prototype.flush = function flush() {} + // flush! + + + /** + * Renders an object + * + * @param {PIXI.DisplayObject} object - The object to render. + */ + ; + + ObjectRenderer.prototype.render = function render(object) // eslint-disable-line no-unused-vars + { + // render the object + }; + + return ObjectRenderer; +}(_WebGLManager3.default); + +exports.default = ObjectRenderer; + +},{"../managers/WebGLManager":93}],95:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a quad + * + * @class + * @memberof PIXI + */ +var Quad = function () { + /** + * @param {WebGLRenderingContext} gl - The gl context for this quad to use. + * @param {object} state - TODO: Description + */ + function Quad(gl, state) { + _classCallCheck(this, Quad); + + /** + * the current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]); + + /** + * The Uvs of the quad + * + * @member {Float32Array} + */ + this.uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + this.interleaved = new Float32Array(8 * 2); + + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(1); + + /** + * The vertex buffer + * + * @member {glCore.GLBuffer} + */ + this.vertexBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW); + + /** + * The index buffer + * + * @member {glCore.GLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + /** + * The vertex array object + * + * @member {glCore.VertexArrayObject} + */ + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, state); + } + + /** + * Initialises the vaos and uses the shader. + * + * @param {PIXI.Shader} shader - the shader to use + */ + + + Quad.prototype.initVao = function initVao(shader) { + this.vao.clear().addIndex(this.indexBuffer).addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0).addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4); + }; + + /** + * Maps two Rectangle to the quad. + * + * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle + * @param {PIXI.Rectangle} destinationFrame - the second rectangle + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.map = function map(targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + + this.uvs[0] = x; + this.uvs[1] = y; + + this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; + + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; + + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; + + x = destinationFrame.x; + y = destinationFrame.y; + + this.vertices[0] = x; + this.vertices[1] = y; + + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + + return this; + }; + + /** + * Binds the buffer and uploads the data + * + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.upload = function upload() { + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + this.vertexBuffer.upload(this.interleaved); + + return this; + }; + + /** + * Removes this quad from WebGL + */ + + + Quad.prototype.destroy = function destroy() { + var gl = this.gl; + + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.indexBuffer); + }; + + return Quad; +}(); + +exports.default = Quad; + +},{"../../../utils/createIndicesForQuads":123,"pixi-gl-core":15}],96:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../../../math'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _pixiGlCore = require('pixi-gl-core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var RenderTarget = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {number} [width=0] - the horizontal range of the filter + * @param {number} [height=0] - the vertical range of the filter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The current resolution / device pixel ratio + * @param {boolean} [root=false] - Whether this object is the root element or not + */ + function RenderTarget(gl, width, height, scaleMode, resolution, root) { + _classCallCheck(this, RenderTarget); + + // TODO Resolution could go here ( eg low res blurs ) + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // next time to create a frame buffer and texture + + /** + * A frame buffer + * + * @member {PIXI.glCore.GLFramebuffer} + */ + this.frameBuffer = null; + + /** + * The texture + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The background colour of this render target, as an array of [r,g,b,a] values + * + * @member {number[]} + */ + this.clearColor = [0, 0, 0, 0]; + + /** + * The size of the object as a rectangle + * + * @member {PIXI.Rectangle} + */ + this.size = new _math.Rectangle(0, 0, 1, 1); + + /** + * The current resolution / device pixel ratio + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The projection matrix + * + * @member {PIXI.Matrix} + */ + this.projectionMatrix = new _math.Matrix(); + + /** + * The object's transform + * + * @member {PIXI.Matrix} + */ + this.transform = null; + + /** + * The frame. + * + * @member {PIXI.Rectangle} + */ + this.frame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.defaultFrame = new _math.Rectangle(); + this.destinationFrame = null; + this.sourceFrame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.stencilBuffer = null; + + /** + * The data structure for the stencil masks + * + * @member {PIXI.Graphics[]} + */ + this.stencilMaskStack = []; + + /** + * Stores filter data for the render target + * + * @member {object[]} + */ + this.filterData = null; + + /** + * The key for pooled texture of FilterSystem + * @private + * @member {string} + */ + this.filterPoolKey = ''; + + /** + * The scale mode. + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Whether this object is the root element or not + * + * @member {boolean} + */ + this.root = root; + + if (!this.root) { + this.frameBuffer = _pixiGlCore.GLFramebuffer.createRGBA(gl, 100, 100); + + if (this.scaleMode === _const.SCALE_MODES.NEAREST) { + this.frameBuffer.texture.enableNearestScaling(); + } else { + this.frameBuffer.texture.enableLinearScaling(); + } + /* + A frame buffer needs a target to render to.. + create a texture and bind it attach it to the framebuffer.. + */ + + // this is used by the base texture + this.texture = this.frameBuffer.texture; + } else { + // make it a null framebuffer.. + this.frameBuffer = new _pixiGlCore.GLFramebuffer(gl, 100, 100); + this.frameBuffer.framebuffer = null; + } + + this.setFrame(); + + this.resize(width, height); + } + + /** + * Clears the filter texture. + * + * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer + */ + + + RenderTarget.prototype.clear = function clear(clearColor) { + var cc = clearColor || this.clearColor; + + this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a); + }; + + /** + * Binds the stencil buffer. + * + */ + + + RenderTarget.prototype.attachStencilBuffer = function attachStencilBuffer() { + // TODO check if stencil is done? + /** + * The stencil buffer is used for masking in pixi + * lets create one and then add attach it to the framebuffer.. + */ + if (!this.root) { + this.frameBuffer.enableStencil(); + } + }; + + /** + * Sets the frame of the render target. + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.setFrame = function setFrame(destinationFrame, sourceFrame) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || this.destinationFrame; + }; + + /** + * Binds the buffers and initialises the viewport. + * + */ + + + RenderTarget.prototype.activate = function activate() { + // TODO refactor usage of frame.. + var gl = this.gl; + + // make sure the texture is unbound! + this.frameBuffer.bind(); + + this.calculateProjection(this.destinationFrame, this.sourceFrame); + + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + + // TODO add a check as them may be the same! + if (this.destinationFrame !== this.sourceFrame) { + gl.enable(gl.SCISSOR_TEST); + gl.scissor(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + } else { + gl.disable(gl.SCISSOR_TEST); + } + + // TODO - does not need to be updated all the time?? + gl.viewport(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + }; + + /** + * Updates the projection matrix based on a projection frame (which is a rectangle) + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.calculateProjection = function calculateProjection(destinationFrame, sourceFrame) { + var pm = this.projectionMatrix; + + sourceFrame = sourceFrame || destinationFrame; + + pm.identity(); + + // TODO: make dest scale source + if (!this.root) { + pm.a = 1 / destinationFrame.width * 2; + pm.d = 1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = -1 - sourceFrame.y * pm.d; + } else { + pm.a = 1 / destinationFrame.width * 2; + pm.d = -1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = 1 - sourceFrame.y * pm.d; + } + }; + + /** + * Resizes the texture to the specified width and height + * + * @param {number} width - the new width of the texture + * @param {number} height - the new height of the texture + */ + + + RenderTarget.prototype.resize = function resize(width, height) { + width = width | 0; + height = height | 0; + + if (this.size.width === width && this.size.height === height) { + return; + } + + this.size.width = width; + this.size.height = height; + + this.defaultFrame.width = width; + this.defaultFrame.height = height; + + this.frameBuffer.resize(width * this.resolution, height * this.resolution); + + var projectionFrame = this.frame || this.size; + + this.calculateProjection(projectionFrame); + }; + + /** + * Destroys the render target. + * + */ + + + RenderTarget.prototype.destroy = function destroy() { + this.frameBuffer.destroy(); + + this.frameBuffer = null; + this.texture = null; + }; + + return RenderTarget; +}(); + +exports.default = RenderTarget; + +},{"../../../const":46,"../../../math":70,"../../../settings":101,"pixi-gl-core":15}],97:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = checkMaxIfStatmentsInShader; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['precision mediump float;', 'void main(void){', 'float test = 0.1;', '%forloop%', 'gl_FragColor = vec4(0.0);', '}'].join('\n'); + +function checkMaxIfStatmentsInShader(maxIfs, gl) { + var createTempContext = !gl; + + if (maxIfs === 0) { + throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); + } + + if (createTempContext) { + var tinyCanvas = document.createElement('canvas'); + + tinyCanvas.width = 1; + tinyCanvas.height = 1; + + gl = _pixiGlCore2.default.createContext(tinyCanvas); + } + + var shader = gl.createShader(gl.FRAGMENT_SHADER); + + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = maxIfs / 2 | 0; + } else { + // valid! + break; + } + } + + if (createTempContext) { + // get rid of context + if (gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').loseContext(); + } + } + + return maxIfs; +} + +function generateIfTestSrc(maxIfs) { + var src = ''; + + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxIfs - 1) { + src += 'if(test == ' + i + '.0){}'; + } + } + + return src; +} + +},{"pixi-gl-core":15}],98:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLBlendModesToPixi; + +var _const = require('../../../const'); + +/** + * Maps gl blend combinations to WebGL. + * + * @memberof PIXI + * @function mapWebGLBlendModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapWebGLBlendModesToPixi(gl) { + var array = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[_const.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD] = [gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + array[_const.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + // not-premultiplied blend modes + array[_const.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.DST_ALPHA, gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + + return array; +} + +},{"../../../const":46}],99:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLDrawModesToPixi; + +var _const = require('../../../const'); + +/** + * Generic Mask Stack data structure. + * + * @memberof PIXI + * @function mapWebGLDrawModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {object} [object={}] - The object to map into + * @return {object} The mapped draw modes. + */ +function mapWebGLDrawModesToPixi(gl) { + var object = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + object[_const.DRAW_MODES.POINTS] = gl.POINTS; + object[_const.DRAW_MODES.LINES] = gl.LINES; + object[_const.DRAW_MODES.LINE_LOOP] = gl.LINE_LOOP; + object[_const.DRAW_MODES.LINE_STRIP] = gl.LINE_STRIP; + object[_const.DRAW_MODES.TRIANGLES] = gl.TRIANGLES; + object[_const.DRAW_MODES.TRIANGLE_STRIP] = gl.TRIANGLE_STRIP; + object[_const.DRAW_MODES.TRIANGLE_FAN] = gl.TRIANGLE_FAN; + + return object; +} + +},{"../../../const":46}],100:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = validateContext; +function validateContext(gl) { + var attributes = gl.getContextAttributes(); + + // this is going to be fairly simple for now.. but at least we have room to grow! + if (!attributes.stencil) { + /* eslint-disable no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable no-console */ + } +} + +},{}],101:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _maxRecommendedTextures = require('./utils/maxRecommendedTextures'); + +var _maxRecommendedTextures2 = _interopRequireDefault(_maxRecommendedTextures); + +var _canUploadSameBuffer = require('./utils/canUploadSameBuffer'); + +var _canUploadSameBuffer2 = _interopRequireDefault(_canUploadSameBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * User's customizable globals for overriding the default PIXI settings, such + * as a renderer's default resolution, framerate, float percision, etc. + * @example + * // Use the native window resolution as the default resolution + * // will support high-density displays when rendering + * PIXI.settings.RESOLUTION = window.devicePixelRatio. + * + * // Disable interpolation when scaling, will make texture be pixelated + * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; + * @namespace PIXI.settings + */ +exports.default = { + + /** + * Target frames per millisecond. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 0.06 + */ + TARGET_FPMS: 0.06, + + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * + * @static + * @memberof PIXI.settings + * @type {boolean} + * @default true + */ + MIPMAP_TEXTURES: true, + + /** + * Default resolution / device pixel ratio of the renderer. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + RESOLUTION: 1, + + /** + * Default filter resolution. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + FILTER_RESOLUTION: 1, + + /** + * The maximum textures that this device supports. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 32 + */ + SPRITE_MAX_TEXTURES: (0, _maxRecommendedTextures2.default)(32), + + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + + /** + * The prefix that denotes a URL is for a retina asset. + * + * @static + * @memberof PIXI.settings + * @type {RegExp} + * @example `@2x` + * @default /@([0-9\.]+)x/ + */ + RETINA_PREFIX: /@([0-9\.]+)x/, + + /** + * The default render options if none are supplied to {@link PIXI.WebGLRenderer} + * or {@link PIXI.CanvasRenderer}. + * + * @static + * @constant + * @memberof PIXI.settings + * @type {object} + * @property {HTMLCanvasElement} view=null + * @property {number} resolution=1 + * @property {boolean} antialias=false + * @property {boolean} forceFXAA=false + * @property {boolean} autoResize=false + * @property {boolean} transparent=false + * @property {number} backgroundColor=0x000000 + * @property {boolean} clearBeforeRender=true + * @property {boolean} preserveDrawingBuffer=false + * @property {boolean} roundPixels=false + * @property {number} width=800 + * @property {number} height=600 + * @property {boolean} legacy=false + */ + RENDER_OPTIONS: { + view: null, + antialias: false, + forceFXAA: false, + autoResize: false, + transparent: false, + backgroundColor: 0x000000, + clearBeforeRender: true, + preserveDrawingBuffer: false, + roundPixels: false, + width: 800, + height: 600, + legacy: false + }, + + /** + * Default transform type. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.TRANSFORM_MODE} + * @default PIXI.TRANSFORM_MODE.STATIC + */ + TRANSFORM_MODE: 0, + + /** + * Default Garbage Collection mode. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO + */ + GC_MODE: 0, + + /** + * Default Garbage Collection max idle. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 3600 + */ + GC_MAX_IDLE: 60 * 60, + + /** + * Default Garbage Collection maximum check count. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 600 + */ + GC_MAX_CHECK_COUNT: 60 * 10, + + /** + * Default wrap modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP + */ + WRAP_MODE: 0, + + /** + * The scale modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR + */ + SCALE_MODE: 0, + + /** + * Default specify float precision in vertex shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.HIGH + */ + PRECISION_VERTEX: 'highp', + + /** + * Default specify float precision in fragment shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM + */ + PRECISION_FRAGMENT: 'mediump', + + /** + * Can we upload the same buffer in a single frame? + * + * @static + * @constant + * @memberof PIXI.settings + * @type {boolean} + */ + CAN_UPLOAD_SAME_BUFFER: (0, _canUploadSameBuffer2.default)(), + + /** + * Default Mesh `canvasPadding`. + * + * @see PIXI.mesh.Mesh#canvasPadding + * @static + * @constant + * @memberof PIXI.settings + * @type {number} + */ + MESH_CANVAS_PADDING: 0 +}; + +},{"./utils/canUploadSameBuffer":122,"./utils/maxRecommendedTextures":127}],102:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new _math.Point(); + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = new PIXI.Sprite.fromImage('assets/image.png'); + * ``` + * + * The more efficient way to create sprites is using a {@link PIXI.Spritesheet}: + * + * ```js + * PIXI.loader.add("assets/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.loader.resources["assets/spritesheet.json"].spritesheet; + * let sprite = new PIXI.Sprite(sheet.textures["image.png"]); + * ... + * } + * ``` + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Sprite = function (_Container) { + _inherits(Sprite, _Container); + + /** + * @param {PIXI.Texture} texture - The texture for this sprite + */ + function Sprite(texture) { + _classCallCheck(this, Sprite); + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 or taken from the {@link PIXI.Texture#defaultAnchor|Texture} + * passed to the constructor. A value of 0,0 means the texture's origin is the top left. + * Setting the anchor to 0.5,0.5 means the texture's origin is centered. + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner. + * Note: Updating the {@link PIXI.Texture#defaultAnchor} after a Texture is + * created does _not_ update the Sprite's anchor values. + * + * @member {PIXI.ObservablePoint} + * @private + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this._anchor = new _math.ObservablePoint(_this._onAnchorUpdate, _this, texture ? texture.defaultAnchor.x : 0, texture ? texture.defaultAnchor.y : 0); + + /** + * The texture that the sprite is using + * + * @private + * @member {PIXI.Texture} + */ + _this._texture = null; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = null; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * The shader that will be used to render the sprite. Set to null to remove a current shader. + * + * @member {PIXI.Filter|PIXI.Shader} + */ + _this.shader = null; + + /** + * An internal cached value of the tint. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this.cachedTint = 0xFFFFFF; + + // call texture setter + _this.texture = texture || _Texture2.default.EMPTY; + + /** + * this is used to store the vertex data of the sprite (basically a quad) + * + * @private + * @member {Float32Array} + */ + _this.vertexData = new Float32Array(8); + + /** + * This is used to calculate the bounds of the object IF it is a trimmed sprite + * + * @private + * @member {Float32Array} + */ + _this.vertexTrimmedData = null; + + _this._transformID = -1; + _this._textureID = -1; + + _this._transformTrimmedID = -1; + _this._textureTrimmedID = -1; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * + * @member {string} + * @default 'sprite' + */ + _this.pluginName = 'sprite'; + _this.roundPixels = false; + return _this; + } + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Sprite.prototype._onTextureUpdate = function _onTextureUpdate() { + this._textureID = -1; + this._textureTrimmedID = -1; + this.cachedTint = 0xFFFFFF; + + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = (0, _utils.sign)(this.scale.x) * this._width / this._texture.orig.width; + } + + if (this._height) { + this.scale.y = (0, _utils.sign)(this.scale.y) * this._height / this._texture.orig.height; + } + }; + + /** + * Called when the anchor position updates. + * + * @private + */ + + + Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate() { + this._transformID = -1; + this._transformTrimmedID = -1; + }; + + /** + * calculates worldTransform * vertices, store it in vertexData + */ + + + Sprite.prototype.calculateVertices = function calculateVertices() { + if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) { + return; + } + + this._transformID = this.transform._worldID; + this._textureID = this._texture._updateID; + + // set the vertex data + + var texture = this._texture; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var anchor = this._anchor; + + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - anchor._x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - anchor._y * orig.height; + h0 = h1 + trim.height; + } else { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData + * This is used to ensure that the true width and height of a trimmed texture is respected + */ + + + Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices() { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { + return; + } + + this._transformTrimmedID = this.transform._worldID; + this._textureTrimmedID = this._texture._updateID; + + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + var anchor = this._anchor; + + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + + var w1 = -anchor._x * orig.width; + var w0 = w1 + orig.width; + + var h1 = -anchor._y * orig.height; + var h0 = h1 + orig.height; + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use. + */ + + + Sprite.prototype._renderWebGL = function _renderWebGL(renderer) { + this.calculateVertices(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Sprite.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Updates the bounds of the sprite. + * + * @private + */ + + + Sprite.prototype._calculateBounds = function _calculateBounds() { + var trim = this._texture.trim; + var orig = this._texture.orig; + + // First lets check to see if the current texture has a trim.. + if (!trim || trim.width === orig.width && trim.height === orig.height) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + Sprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._texture.orig.width * -this._anchor._x; + this._bounds.minY = this._texture.orig.height * -this._anchor._y; + this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x); + this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._y); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _Container.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Tests if a point is inside this sprite + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Sprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + y1 = -height * this.anchor.y; + + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + Sprite.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + this._texture.off('update', this._onTextureUpdate, this); + + this._anchor = null; + + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + + this._texture.destroy(!!destroyBaseTexture); + } + + this._texture = null; + this.shader = null; + }; + + // some helper functions.. + + /** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Sprite} The newly created sprite + */ + + + Sprite.from = function from(source) { + return new Sprite(_Texture2.default.from(source)); + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId + */ + + + Sprite.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return new Sprite(texture); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id + */ + + + Sprite.fromImage = function fromImage(imageId, crossorigin, scaleMode) { + return new Sprite(_Texture2.default.fromImage(imageId, crossorigin, scaleMode)); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Sprite, [{ + key: 'width', + get: function get() { + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 or taken from the {@link PIXI.Texture|Texture} passed to the constructor. + * Setting the texture at a later point of time does not change the anchor. + * + * 0,0 means the texture's origin is the top left, 0.5,0.5 is the center, 1,1 the bottom right corner. + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._anchor.copy(value); + } + + /** + * The tint applied to the sprite. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + } + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + */ + + }, { + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value || _Texture2.default.EMPTY; + this.cachedTint = 0xFFFFFF; + + this._textureID = -1; + this._textureTrimmedID = -1; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + }]); + + return Sprite; +}(_Container3.default); + +exports.default = Sprite; + +},{"../const":46,"../display/Container":48,"../math":70,"../textures/Texture":115,"../utils":125}],103:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +var _math = require('../../math'); + +var _CanvasTinter = require('./CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var canvasRenderWorldTransform = new _math.Matrix(); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasSpriteRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + */ + +var CanvasSpriteRenderer = function () { + /** + * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for. + */ + function CanvasSpriteRenderer(renderer) { + _classCallCheck(this, CanvasSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + CanvasSpriteRenderer.prototype.render = function render(sprite) { + var texture = sprite._texture; + var renderer = this.renderer; + + var width = texture._frame.width; + var height = texture._frame.height; + + var wt = sprite.transform.worldTransform; + var dx = 0; + var dy = 0; + + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) { + return; + } + + renderer.setBlendMode(sprite.blendMode); + + // Ignore null sources + if (texture.valid) { + renderer.context.globalAlpha = sprite.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture + var smoothingEnabled = texture.baseTexture.scaleMode === _const.SCALE_MODES.LINEAR; + + if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) { + renderer.context[renderer.smoothProperty] = smoothingEnabled; + } + + if (texture.trim) { + dx = texture.trim.width / 2 + texture.trim.x - sprite.anchor.x * texture.orig.width; + dy = texture.trim.height / 2 + texture.trim.y - sprite.anchor.y * texture.orig.height; + } else { + dx = (0.5 - sprite.anchor.x) * texture.orig.width; + dy = (0.5 - sprite.anchor.y) * texture.orig.height; + } + + if (texture.rotate) { + wt.copy(canvasRenderWorldTransform); + wt = canvasRenderWorldTransform; + _math.GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); + // the anchor has already been applied above, so lets set it to zero + dx = 0; + dy = 0; + } + + dx -= width / 2; + dy -= height / 2; + + // Allow for pixel rounding + if (renderer.roundPixels || sprite.roundPixels) { // #CUSTOM + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution | 0, wt.ty * renderer.resolution | 0); + + dx = dx | 0; + dy = dy | 0; + } else { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution, wt.ty * renderer.resolution); + } + + var resolution = texture.baseTexture.resolution; + + if (sprite.tint !== 0xFFFFFF) { + if (sprite.cachedTint !== sprite.tint || sprite.tintedTexture.tintId !== sprite._texture._updateID) { + sprite.cachedTint = sprite.tint; + + // TODO clean up caching - how to clean up the caches? + sprite.tintedTexture = _CanvasTinter2.default.getTintedTexture(sprite, sprite.tint); + } + + renderer.context.drawImage(sprite.tintedTexture, 0, 0, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } else { + renderer.context.drawImage(texture.baseTexture.source, texture._frame.x * resolution, texture._frame.y * resolution, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } + } + }; + + /** + * destroy the sprite object. + * + */ + + + CanvasSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasSpriteRenderer; +}(); + +exports.default = CanvasSpriteRenderer; + + +_CanvasRenderer2.default.registerPlugin('sprite', CanvasSpriteRenderer); + +},{"../../const":46,"../../math":70,"../../renderers/canvas/CanvasRenderer":77,"./CanvasTinter":104}],104:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class + * @memberof PIXI + */ +var CanvasTinter = { + /** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Sprite} sprite - the sprite to tint + * @param {number} color - the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ + getTintedTexture: function getTintedTexture(sprite, color) { + var texture = sprite._texture; + + color = CanvasTinter.roundColor(color); + + var stringColor = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + texture.tintCache = texture.tintCache || {}; + + var cachedTexture = texture.tintCache[stringColor]; + + var canvas = void 0; + + if (cachedTexture) { + if (cachedTexture.tintId === texture._updateID) { + return texture.tintCache[stringColor]; + } + + canvas = texture.tintCache[stringColor]; + } else { + canvas = CanvasTinter.canvas || document.createElement('canvas'); + } + + CanvasTinter.tintMethod(texture, color, canvas); + + canvas.tintId = texture._updateID; + + if (CanvasTinter.convertTintToImage) { + // is this better? + var tintImage = new Image(); + + tintImage.src = canvas.toDataURL(); + + texture.tintCache[stringColor] = tintImage; + } else { + texture.tintCache[stringColor] = canvas; + // if we are not converting the texture to an image then we need to lose the reference to the canvas + CanvasTinter.canvas = null; + } + + return canvas; + }, + + /** + * Tint a texture using the 'multiply' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithMultiply: function tintWithMultiply(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.save(); + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + context.restore(); + }, + + /** + * Tint a texture using the 'overlay' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithOverlay: function tintWithOverlay(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.save(); + context.globalCompositeOperation = 'copy'; + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + // context.globalCompositeOperation = 'copy'; + context.restore(); + }, + + + /** + * Tint a texture pixel per pixel. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithPerPixel: function tintWithPerPixel(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.save(); + context.globalCompositeOperation = 'copy'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + context.restore(); + + var rgbValues = (0, _utils.hex2rgb)(color); + var r = rgbValues[0]; + var g = rgbValues[1]; + var b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, crop.width, crop.height); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + } + + context.putImageData(pixelData, 0, 0); + }, + + /** + * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel. + * + * @memberof PIXI.CanvasTinter + * @param {number} color - the color to round, should be a hex color + * @return {number} The rounded color. + */ + roundColor: function roundColor(color) { + var step = CanvasTinter.cacheStepsPerColorChannel; + + var rgbValues = (0, _utils.hex2rgb)(color); + + rgbValues[0] = Math.min(255, rgbValues[0] / step * step); + rgbValues[1] = Math.min(255, rgbValues[1] / step * step); + rgbValues[2] = Math.min(255, rgbValues[2] / step * step); + + return (0, _utils.rgb2hex)(rgbValues); + }, + + /** + * Number of steps which will be used as a cap when rounding colors. + * + * @memberof PIXI.CanvasTinter + * @type {number} + */ + cacheStepsPerColorChannel: 8, + + /** + * Tint cache boolean flag. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + convertTintToImage: false, + + /** + * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + canUseMultiply: (0, _canUseNewCanvasBlendModes2.default)(), + + /** + * The tinting method that will be used. + * + * @memberof PIXI.CanvasTinter + * @type {tintMethodFunctionType} + */ + tintMethod: 0 +}; + +CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply : CanvasTinter.tintWithPerPixel; + +/** + * The tintMethod type. + * + * @memberof PIXI.CanvasTinter + * @callback tintMethodFunctionType + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + +exports.default = CanvasTinter; + +},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":80,"../../utils":125}],105:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Buffer = function () { + /** + * @param {number} size - The size of the buffer in bytes. + */ + function Buffer(size) { + _classCallCheck(this, Buffer); + + this.vertices = new ArrayBuffer(size); + + /** + * View on the vertices as a Float32Array for positions + * + * @member {Float32Array} + */ + this.float32View = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array for uvs + * + * @member {Float32Array} + */ + this.uint32View = new Uint32Array(this.vertices); + } + + /** + * Destroys the buffer. + * + */ + + + Buffer.prototype.destroy = function destroy() { + this.vertices = null; + this.positions = null; + this.uvs = null; + this.colors = null; + }; + + return Buffer; +}(); + +exports.default = Buffer; + +},{}],106:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _createIndicesForQuads = require('../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +var _generateMultiTextureShader = require('./generateMultiTextureShader'); + +var _generateMultiTextureShader2 = _interopRequireDefault(_generateMultiTextureShader); + +var _checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'); + +var _checkMaxIfStatmentsInShader2 = _interopRequireDefault(_checkMaxIfStatmentsInShader); + +var _BatchBuffer = require('./BatchBuffer'); + +var _BatchBuffer2 = _interopRequireDefault(_BatchBuffer); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var TICK = 0; +var TEXTURE_TICK = 0; + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var SpriteRenderer = function (_ObjectRenderer) { + _inherits(SpriteRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function SpriteRenderer(renderer) { + _classCallCheck(this, SpriteRenderer); + + /** + * Number of values sent in the vertex buffer. + * aVertexPosition(2), aTextureCoord(1), aColor(1), aTextureId(1) = 5 + * + * @member {number} + */ + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.vertSize = 5; + + /** + * The size of the vertex information in bytes. + * + * @member {number} + */ + _this.vertByteSize = _this.vertSize * 4; + + /** + * The number of images in the SpriteRenderer before it flushes. + * + * @member {number} + */ + _this.size = _settings2.default.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + + // the total number of bytes in our batch + // let numVerts = this.size * 4 * this.vertByteSize; + + _this.buffers = []; + for (var i = 1; i <= _bitTwiddle2.default.nextPow2(_this.size); i *= 2) { + _this.buffers.push(new _BatchBuffer2.default(i * 4 * _this.vertByteSize)); + } + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + _this.indices = (0, _createIndicesForQuads2.default)(_this.size); + + /** + * The default shaders that is used if a sprite doesn't have a more specific one. + * there is a shader for each number of textures that can be rendererd. + * These shaders will also be generated on the fly as required. + * @member {PIXI.Shader[]} + */ + _this.shader = null; + + _this.currentIndex = 0; + _this.groups = []; + + for (var k = 0; k < _this.size; k++) { + _this.groups[k] = { textures: [], textureCount: 0, ids: [], size: 0, start: 0, blend: 0 }; + } + + _this.sprites = []; + + _this.vertexBuffers = []; + _this.vaos = []; + + _this.vaoMax = 2; + _this.vertexCount = 0; + + _this.renderer.on('prerender', _this.onPrerender, _this); + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + SpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + if (this.renderer.legacy) { + this.MAX_TEXTURES = 1; + } else { + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), _settings2.default.SPRITE_MAX_TEXTURES); + + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = (0, _checkMaxIfStatmentsInShader2.default)(this.MAX_TEXTURES, gl); + } + + this.shader = (0, _generateMultiTextureShader2.default)(gl, this.MAX_TEXTURES); + + // create a couple of buffers + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + // we use the second shader as the first one depending on your browser may omit aTextureId + // as it is not used by the shader so is optimized out. + + this.renderer.bindVao(null); + + var attrs = this.shader.attributes; + + for (var i = 0; i < this.vaoMax; i++) { + /* eslint-disable max-len */ + var vertexBuffer = this.vertexBuffers[i] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + /* eslint-enable max-len */ + + // build the vao object that will render.. + var vao = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (attrs.aTextureId) { + vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vaos[i] = vao; + } + + this.vao = this.vaos[0]; + this.currentBlendMode = 99999; + + this.boundTextures = new Array(this.MAX_TEXTURES); + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + SpriteRenderer.prototype.onPrerender = function onPrerender() { + this.vertexCount = 0; + }; + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + SpriteRenderer.prototype.render = function render(sprite) { + // TODO set blend modes.. + // check texture.. + if (this.currentIndex >= this.size) { + this.flush(); + } + + // get the uvs for the texture + + // if the uvs have not updated then no point rendering just yet! + if (!sprite._texture._uvs) { + return; + } + + // push a texture. + // increment the batchsize + this.sprites[this.currentIndex++] = sprite; + }; + + /** + * Renders the content and empties the current batch. + * + */ + + + SpriteRenderer.prototype.flush = function flush() { + if (this.currentIndex === 0) { + return; + } + + var gl = this.renderer.gl; + var MAX_TEXTURES = this.MAX_TEXTURES; + + var np2 = _bitTwiddle2.default.nextPow2(this.currentIndex); + var log2 = _bitTwiddle2.default.log2(np2); + var buffer = this.buffers[log2]; + + var sprites = this.sprites; + var groups = this.groups; + + var float32View = buffer.float32View; + var uint32View = buffer.uint32View; + + var boundTextures = this.boundTextures; + var rendererBoundTextures = this.renderer.boundTextures; + var touch = this.renderer.textureGC.count; + + var index = 0; + var nextTexture = void 0; + var currentTexture = void 0; + var groupCount = 1; + var textureCount = 0; + var currentGroup = groups[0]; + var vertexData = void 0; + var uvs = void 0; + var blendMode = _utils.premultiplyBlendMode[sprites[0]._texture.baseTexture.premultipliedAlpha ? 1 : 0][sprites[0].blendMode]; + + currentGroup.textureCount = 0; + currentGroup.start = 0; + currentGroup.blend = blendMode; + + TICK++; + + var i = void 0; + + // copy textures.. + for (i = 0; i < MAX_TEXTURES; ++i) { + var bt = rendererBoundTextures[i]; + + if (bt._enabled === TICK) { + boundTextures[i] = this.renderer.emptyTextures[i]; + continue; + } + + boundTextures[i] = bt; + bt._virtalBoundId = i; + bt._enabled = TICK; + } + TICK++; + + for (i = 0; i < this.currentIndex; ++i) { + // upload the sprite elemetns... + // they have all ready been calculated so we just need to push them into the buffer. + var sprite = sprites[i]; + + sprites[i] = null; + + nextTexture = sprite._texture.baseTexture; + + var spriteBlendMode = _utils.premultiplyBlendMode[Number(nextTexture.premultipliedAlpha)][sprite.blendMode]; + + if (blendMode !== spriteBlendMode) { + // finish a group.. + blendMode = spriteBlendMode; + + // force the batch to break! + currentTexture = null; + textureCount = MAX_TEXTURES; + TICK++; + } + + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + + if (nextTexture._enabled !== TICK) { + if (textureCount === MAX_TEXTURES) { + TICK++; + + currentGroup.size = i - currentGroup.start; + + textureCount = 0; + + currentGroup = groups[groupCount++]; + currentGroup.blend = blendMode; + currentGroup.textureCount = 0; + currentGroup.start = i; + } + + nextTexture.touched = touch; + + if (nextTexture._virtalBoundId === -1) { + for (var j = 0; j < MAX_TEXTURES; ++j) { + var tIndex = (j + TEXTURE_TICK) % MAX_TEXTURES; + + var t = boundTextures[tIndex]; + + if (t._enabled !== TICK) { + TEXTURE_TICK++; + + t._virtalBoundId = -1; + + nextTexture._virtalBoundId = tIndex; + + boundTextures[tIndex] = nextTexture; + break; + } + } + } + + nextTexture._enabled = TICK; + + currentGroup.textureCount++; + currentGroup.ids[textureCount] = nextTexture._virtalBoundId; + currentGroup.textures[textureCount++] = nextTexture; + } + } + + vertexData = sprite.vertexData; + + // TODO this sum does not need to be set each frame.. + uvs = sprite._texture._uvs.uvsUint32; + + if (this.renderer.roundPixels || sprite.roundPixels) { // #CUSTOM + var resolution = this.renderer.resolution; + + // xy + float32View[index] = (vertexData[0] * resolution | 0) / resolution; + float32View[index + 1] = (vertexData[1] * resolution | 0) / resolution; + + // xy + float32View[index + 5] = (vertexData[2] * resolution | 0) / resolution; + float32View[index + 6] = (vertexData[3] * resolution | 0) / resolution; + + // xy + float32View[index + 10] = (vertexData[4] * resolution | 0) / resolution; + float32View[index + 11] = (vertexData[5] * resolution | 0) / resolution; + + // xy + float32View[index + 15] = (vertexData[6] * resolution | 0) / resolution; + float32View[index + 16] = (vertexData[7] * resolution | 0) / resolution; + } else { + // xy + float32View[index] = vertexData[0]; + float32View[index + 1] = vertexData[1]; + + // xy + float32View[index + 5] = vertexData[2]; + float32View[index + 6] = vertexData[3]; + + // xy + float32View[index + 10] = vertexData[4]; + float32View[index + 11] = vertexData[5]; + + // xy + float32View[index + 15] = vertexData[6]; + float32View[index + 16] = vertexData[7]; + } + + uint32View[index + 2] = uvs[0]; + uint32View[index + 7] = uvs[1]; + uint32View[index + 12] = uvs[2]; + uint32View[index + 17] = uvs[3]; + /* eslint-disable max-len */ + var alpha = Math.min(sprite.worldAlpha, 1.0); + // we dont call extra function if alpha is 1.0, that's faster + var argb = alpha < 1.0 && nextTexture.premultipliedAlpha ? (0, _utils.premultiplyTint)(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); + + uint32View[index + 3] = uint32View[index + 8] = uint32View[index + 13] = uint32View[index + 18] = argb; + float32View[index + 4] = float32View[index + 9] = float32View[index + 14] = float32View[index + 19] = nextTexture._virtalBoundId; + /* eslint-enable max-len */ + + index += 20; + } + + currentGroup.size = i - currentGroup.start; + + if (!_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // this is still needed for IOS performance.. + // it really does not like uploading to the same buffer in a single frame! + if (this.vaoMax <= this.vertexCount) { + this.vaoMax++; + + var attrs = this.shader.attributes; + + /* eslint-disable max-len */ + var vertexBuffer = this.vertexBuffers[this.vertexCount] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + /* eslint-enable max-len */ + + // build the vao object that will render.. + var vao = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (attrs.aTextureId) { + vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vaos[this.vertexCount] = vao; + } + + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, false); + + this.vertexCount++; + } else { + // lets use the faster option, always use buffer number 0 + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, true); + } + + for (i = 0; i < MAX_TEXTURES; ++i) { + rendererBoundTextures[i]._virtalBoundId = -1; + } + + // render the groups.. + for (i = 0; i < groupCount; ++i) { + var group = groups[i]; + var groupTextureCount = group.textureCount; + + for (var _j = 0; _j < groupTextureCount; _j++) { + currentTexture = group.textures[_j]; + + // reset virtual ids.. + // lets do a quick check.. + if (rendererBoundTextures[group.ids[_j]] !== currentTexture) { + this.renderer.bindTexture(currentTexture, group.ids[_j], true); + } + + // reset the virtualId.. + currentTexture._virtalBoundId = -1; + } + + // set the blend mode.. + this.renderer.state.setBlendMode(group.blend); + + gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); + } + + // reset elements for the next flush + this.currentIndex = 0; + }; + + /** + * Starts a new sprite batch. + */ + + + SpriteRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + + if (_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // bind buffer #0, we don't need others + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].bind(); + } + }; + + /** + * Stops and flushes the current batch. + * + */ + + + SpriteRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Destroys the SpriteRenderer. + * + */ + + + SpriteRenderer.prototype.destroy = function destroy() { + for (var i = 0; i < this.vaoMax; i++) { + if (this.vertexBuffers[i]) { + this.vertexBuffers[i].destroy(); + } + if (this.vaos[i]) { + this.vaos[i].destroy(); + } + } + + if (this.indexBuffer) { + this.indexBuffer.destroy(); + } + + this.renderer.off('prerender', this.onPrerender, this); + + _ObjectRenderer.prototype.destroy.call(this); + + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } + + this.vertexBuffers = null; + this.vaos = null; + this.indexBuffer = null; + this.indices = null; + + this.sprites = null; + + for (var _i = 0; _i < this.buffers.length; ++_i) { + this.buffers[_i].destroy(); + } + }; + + return SpriteRenderer; +}(_ObjectRenderer3.default); + +exports.default = SpriteRenderer; + + +_WebGLRenderer2.default.registerPlugin('sprite', SpriteRenderer); + +},{"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":97,"../../settings":101,"../../utils":125,"../../utils/createIndicesForQuads":123,"./BatchBuffer":105,"./generateMultiTextureShader":107,"bit-twiddle":1,"pixi-gl-core":15}],107:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateMultiTextureShader; + +var _Shader = require('../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'varying float vTextureId;', 'uniform sampler2D uSamplers[%count%];', 'void main(void){', 'vec4 color;', 'float textureId = floor(vTextureId+0.5);', '%forloop%', 'gl_FragColor = color * vColor;', '}'].join('\n'); + +function generateMultiTextureShader(gl, maxTextures) { + var vertexSrc = 'precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor;\n}\n'; + var fragmentSrc = fragTemplate; + + fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); + + var shader = new _Shader2.default(gl, vertexSrc, fragmentSrc); + + var sampleValues = []; + + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + + shader.bind(); + shader.uniforms.uSamplers = sampleValues; + + return shader; +} + +function generateSampleSrc(maxTextures) { + var src = ''; + + src += '\n'; + src += '\n'; + + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxTextures - 1) { + src += 'if(textureId == ' + i + '.0)'; + } + + src += '\n{'; + src += '\n\tcolor = texture2D(uSamplers[' + i + '], vTextureCoord);'; + src += '\n}'; + } + + src += '\n'; + src += '\n'; + + return src; +} + +},{"../../Shader":44,"path":8}],108:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Sprite2 = require('../sprites/Sprite'); + +var _Sprite3 = _interopRequireDefault(_Sprite2); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TextStyle = require('./TextStyle'); + +var _TextStyle2 = _interopRequireDefault(_TextStyle); + +var _TextMetrics = require('./TextMetrics'); + +var _TextMetrics2 = _interopRequireDefault(_TextMetrics); + +var _trimCanvas = require('../utils/trimCanvas'); + +var _trimCanvas2 = _interopRequireDefault(_trimCanvas); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint max-depth: [2, 8] */ + + +var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true +}; + +/** + * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string, + * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object. + * + * A Text can be created directly from a string and a style object, + * which can be generated [here](https://pixijs.io/pixi-text-style). + * + * ```js + * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI + */ + +var Text = function (_Sprite) { + _inherits(Text, _Sprite); + + /** + * @param {string} text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + * @param {HTMLCanvasElement} [canvas] - The canvas element for drawing text + */ + function Text(text, style, canvas) { + _classCallCheck(this, Text); + + canvas = canvas || document.createElement('canvas'); + + canvas.width = 3; + canvas.height = 3; + + var texture = _Texture2.default.fromCanvas(canvas, _settings2.default.SCALE_MODE, 'text'); + + texture.orig = new _math.Rectangle(); + texture.trim = new _math.Rectangle(); + + // base texture is already automatically added to the cache, now adding the actual texture + var _this = _possibleConstructorReturn(this, _Sprite.call(this, texture)); + + _Texture2.default.addToCache(_this._texture, _this._texture.baseTexture.textureCacheIds[0]); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.canvas = canvas; + + /** + * The canvas 2d context that everything is drawn with + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.canvas.getContext('2d'); + + /** + * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. + * @member {number} + * @default 1 + */ + _this.resolution = _settings2.default.RESOLUTION; + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = null; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._style = null; + /** + * Private listener to track style changes. + * + * @member {Function} + * @private + */ + _this._styleListener = null; + + /** + * Private tracker for the current font. + * + * @member {string} + * @private + */ + _this._font = ''; + + _this.text = text; + _this.style = style; + + _this.localStyleID = -1; + return _this; + } + + /** + * Renders text and updates it when needed. + * + * @private + * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. + */ + + + Text.prototype.updateText = function updateText(respectDirty) { + var style = this._style; + + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + + if (!this.dirty && respectDirty) { + return; + } + + this._font = this._style.toFontString(); + + var context = this.context; + var measured = _TextMetrics2.default.measureText(this._text, this._style, this._style.wordWrap, this.canvas); + var width = measured.width; + var height = measured.height; + var lines = measured.lines; + var lineHeight = measured.lineHeight; + var lineWidths = measured.lineWidths; + var maxLineWidth = measured.maxLineWidth; + var fontProperties = measured.fontProperties; + + this.canvas.width = Math.ceil((Math.max(1, width) + style.padding * 2) * this.resolution); + this.canvas.height = Math.ceil((Math.max(1, height) + style.padding * 2) * this.resolution); + + context.scale(this.resolution, this.resolution); + + context.clearRect(0, 0, this.canvas.width, this.canvas.height); + + context.font = this._font; + context.strokeStyle = style.stroke; + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + + var linePositionX = void 0; + var linePositionY = void 0; + + if (style.dropShadow) { + context.fillStyle = style.dropShadowColor; + context.globalAlpha = style.dropShadowAlpha; + context.shadowBlur = style.dropShadowBlur; + + if (style.dropShadowBlur > 0) { + context.shadowColor = style.dropShadowColor; + } + + var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + + for (var i = 0; i < lines.length; i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (style.fill) { + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); + + if (style.stroke && style.strokeThickness) { + context.strokeStyle = style.dropShadowColor; + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding, true); + context.strokeStyle = style.stroke; + } + } + } + } + + // reset the shadow blur and alpha that was set by the drop shadow, for the regular text + context.shadowBlur = 0; + context.globalAlpha = 1; + + // set canvas text styles + context.fillStyle = this._generateFillStyle(style, lines); + + // draw lines line by line + for (var _i = 0; _i < lines.length; _i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i]) / 2; + } + + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding, true); + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding); + } + } + + this.updateTexture(); + }; + + /** + * Render the text with letter-spacing. + * @param {string} text - The text to draw + * @param {number} x - Horizontal position to draw the text + * @param {number} y - Vertical position to draw the text + * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + * @private + */ + + + Text.prototype.drawLetterSpacing = function drawLetterSpacing(text, x, y) { + var isStroke = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var style = this._style; + + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + + if (letterSpacing === 0) { + if (isStroke) { + this.context.strokeText(text, x, y); + } else { + this.context.fillText(text, x, y); + } + + return; + } + + var characters = String.prototype.split.call(text, ''); + var currentPosition = x; + var index = 0; + var current = ''; + + while (index < text.length) { + current = characters[index++]; + if (isStroke) { + this.context.strokeText(current, currentPosition, y); + } else { + this.context.fillText(current, currentPosition, y); + } + currentPosition += this.context.measureText(current).width + letterSpacing; + } + }; + + /** + * Updates texture size based on canvas size + * + * @private + */ + + + Text.prototype.updateTexture = function updateTexture() { + var canvas = this.canvas; + + if (this._style.trim) { + var trimmed = (0, _trimCanvas2.default)(canvas); + + if (trimmed.data) { + canvas.width = trimmed.width; + canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } + } + + var texture = this._texture; + var style = this._style; + var padding = style.trim ? 0 : style.padding; + var baseTexture = texture.baseTexture; + + baseTexture.hasLoaded = true; + baseTexture.resolution = this.resolution; + + baseTexture.realWidth = canvas.width; + baseTexture.realHeight = canvas.height; + baseTexture.width = canvas.width / this.resolution; + baseTexture.height = canvas.height / this.resolution; + + texture.trim.width = texture._frame.width = canvas.width / this.resolution; + texture.trim.height = texture._frame.height = canvas.height / this.resolution; + texture.trim.x = -padding; + texture.trim.y = -padding; + + texture.orig.width = texture._frame.width - padding * 2; + texture.orig.height = texture._frame.height - padding * 2; + + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + + baseTexture.emit('update', baseTexture); + + this.dirty = false; + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Text.prototype.renderWebGL = function renderWebGL(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype.renderWebGL.call(this, renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Text.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype._renderCanvas.call(this, renderer); + }; + + /** + * Gets the local bounds of the text object. + * + * @param {Rectangle} rect - The output rectangle. + * @return {Rectangle} The bounds. + */ + + + Text.prototype.getLocalBounds = function getLocalBounds(rect) { + this.updateText(true); + + return _Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + */ + + + Text.prototype._calculateBounds = function _calculateBounds() { + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; + + /** + * Method to be called upon a TextStyle change. + * @private + */ + + + Text.prototype._onStyleChange = function _onStyleChange() { + this.dirty = true; + }; + + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * + * @private + * @param {object} style - The style. + * @param {string[]} lines - The lines of text. + * @return {string|number|CanvasGradient} The fill style + */ + + + Text.prototype._generateFillStyle = function _generateFillStyle(style, lines) { + if (!Array.isArray(style.fill)) { + return style.fill; + } + + // cocoon on canvas+ cannot generate textures, so use the first colour instead + if (navigator.isCocoonJS) { + return style.fill[0]; + } + + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient = void 0; + var totalIterations = void 0; + var currentIteration = void 0; + var stop = void 0; + + var width = this.canvas.width / this.resolution; + var height = this.canvas.height / this.resolution; + + // make a copy of the style settings, so we can manipulate them later + var fill = style.fill.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(style.fill[0]); + fillGradientStops.unshift(0); + + fill.push(style.fill[style.fill.length - 1]); + fillGradientStops.push(1); + + if (style.fillGradientType === _const.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); + + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + totalIterations = (fill.length + 1) * lines.length; + currentIteration = 0; + for (var _i2 = 0; _i2 < lines.length; _i2++) { + currentIteration += 1; + for (var j = 0; j < fill.length; j++) { + if (typeof fillGradientStops[j] === 'number') { + stop = fillGradientStops[j] / lines.length + _i2 / lines.length; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[j]); + currentIteration++; + } + } + } else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); + + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + totalIterations = fill.length + 1; + currentIteration = 1; + + for (var _i3 = 0; _i3 < fill.length; _i3++) { + if (typeof fillGradientStops[_i3] === 'number') { + stop = fillGradientStops[_i3]; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[_i3]); + currentIteration++; + } + } + + return gradient; + }; + + /** + * Destroys this text object. + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majority of the time the texture will not be shared with any other Sprites. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well + */ + + + Text.prototype.destroy = function destroy(options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + + options = Object.assign({}, defaultDestroyOptions, options); + + _Sprite.prototype.destroy.call(this, options); + + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + + this._style = null; + }; + + /** + * The width of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Text, [{ + key: 'width', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * Set the style of the text. Set up an event listener to listen for changes on the style + * object and mark the text as dirty. + * + * @member {object|PIXI.TextStyle} + */ + + }, { + key: 'style', + get: function get() { + return this._style; + }, + set: function set(style) // eslint-disable-line require-jsdoc + { + style = style || {}; + + if (style instanceof _TextStyle2.default) { + this._style = style; + } else { + this._style = new _TextStyle2.default(style); + } + + this.localStyleID = -1; + this.dirty = true; + } + + /** + * Set the copy for the text object. To split a line you can use '\n'. + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(text) // eslint-disable-line require-jsdoc + { + text = String(text === '' || text === null || text === undefined ? ' ' : text); + + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + } + }]); + + return Text; +}(_Sprite3.default); + +exports.default = Text; + +},{"../const":46,"../math":70,"../settings":101,"../sprites/Sprite":102,"../textures/Texture":115,"../utils":125,"../utils/trimCanvas":130,"./TextMetrics":109,"./TextStyle":110}],109:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The TextMetrics object represents the measurement of a block of text with a specified style. + * + * ```js + * let style = new PIXI.TextStyle({fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}) + * let textMetrics = PIXI.TextMetrics.measureText('Your text', style) + * ``` + * + * @class + * @memberOf PIXI + */ +var TextMetrics = function () { + /** + * @param {string} text - the text that was measured + * @param {PIXI.TextStyle} style - the style that was measured + * @param {number} width - the measured width of the text + * @param {number} height - the measured height of the text + * @param {array} lines - an array of the lines of text broken by new lines and wrapping if specified in style + * @param {array} lineWidths - an array of the line widths for each line matched to `lines` + * @param {number} lineHeight - the measured line height for this style + * @param {number} maxLineWidth - the maximum line width for all measured lines + * @param {Object} fontProperties - the font properties object from TextMetrics.measureFont + */ + function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) { + _classCallCheck(this, TextMetrics); + + this.text = text; + this.style = style; + this.width = width; + this.height = height; + this.lines = lines; + this.lineWidths = lineWidths; + this.lineHeight = lineHeight; + this.maxLineWidth = maxLineWidth; + this.fontProperties = fontProperties; + } + + /** + * Measures the supplied string of text and returns a Rectangle. + * + * @param {string} text - the text to measure. + * @param {PIXI.TextStyle} style - the text style to use for measuring + * @param {boolean} [wordWrap] - optional override for if word-wrap should be applied to the text. + * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. + * @return {PIXI.TextMetrics} measured width and height of the text. + */ + + + TextMetrics.measureText = function measureText(text, style, wordWrap) { + var canvas = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : TextMetrics._canvas; + + wordWrap = wordWrap === undefined || wordWrap === null ? style.wordWrap : wordWrap; + var font = style.toFontString(); + var fontProperties = TextMetrics.measureFont(font); + var context = canvas.getContext('2d'); + + context.font = font; + + var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text; + var lines = outputText.split(/(?:\r\n|\r|\n)/); + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + + for (var i = 0; i < lines.length; i++) { + var lineWidth = context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing; + + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + var width = maxLineWidth + style.strokeThickness; + + if (style.dropShadow) { + width += style.dropShadowDistance; + } + + var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * (lineHeight + style.leading); + + if (style.dropShadow) { + height += style.dropShadowDistance; + } + + return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties); + }; + + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @private + * @param {string} text - String to apply word wrapping to + * @param {PIXI.TextStyle} style - the style to use when wrapping + * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. + * @return {string} New string with new lines applied where required + */ + + + TextMetrics.wordWrap = function wordWrap(text, style) { + var canvas = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : TextMetrics._canvas; + + var context = canvas.getContext('2d'); + + var width = 0; + var line = ''; + var lines = ''; + + var cache = {}; + var letterSpacing = style.letterSpacing, + whiteSpace = style.whiteSpace; + + // How to handle whitespaces + + var collapseSpaces = TextMetrics.collapseSpaces(whiteSpace); + var collapseNewlines = TextMetrics.collapseNewlines(whiteSpace); + + // whether or not spaces may be added to the beginning of lines + var canPrependSpaces = !collapseSpaces; + + // There is letterSpacing after every char except the last one + // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_! + // so for convenience the above needs to be compared to width + 1 extra letterSpace + // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_ + // ________________________________________________ + // And then the final space is simply no appended to each line + var wordWrapWidth = style.wordWrapWidth + letterSpacing; + + // break text into words, spaces and newline chars + var tokens = TextMetrics.tokenize(text); + + for (var i = 0; i < tokens.length; i++) { + // get the word, space or newlineChar + var token = tokens[i]; + + // if word is a new line + if (TextMetrics.isNewline(token)) { + // keep the new line + if (!collapseNewlines) { + lines += TextMetrics.addLine(line); + canPrependSpaces = !collapseSpaces; + line = ''; + width = 0; + continue; + } + + // if we should collapse new lines + // we simply convert it into a space + token = ' '; + } + + // if we should collapse repeated whitespaces + if (collapseSpaces) { + // check both this and the last tokens for spaces + var currIsBreakingSpace = TextMetrics.isBreakingSpace(token); + var lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]); + + if (currIsBreakingSpace && lastIsBreakingSpace) { + continue; + } + } + + // get word width from cache if possible + var tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context); + + // word is longer than desired bounds + if (tokenWidth > wordWrapWidth) { + // if we are not already at the beginning of a line + if (line !== '') { + // start newlines for overflow words + lines += TextMetrics.addLine(line); + line = ''; + width = 0; + } + + // break large word over multiple lines + if (TextMetrics.canBreakWords(token, style.breakWords)) { + // break word into characters + var characters = token.split(''); + + // loop the characters + for (var j = 0; j < characters.length; j++) { + var char = characters[j]; + + var k = 1; + // we are not at the end of the token + + while (characters[j + k]) { + var nextChar = characters[j + k]; + var lastChar = char[char.length - 1]; + + // should not split chars + if (!TextMetrics.canBreakChars(lastChar, nextChar, token, j, style.breakWords)) { + // combine chars & move forward one + char += nextChar; + } else { + break; + } + + k++; + } + + j += char.length - 1; + + var characterWidth = TextMetrics.getFromCache(char, letterSpacing, cache, context); + + if (characterWidth + width > wordWrapWidth) { + lines += TextMetrics.addLine(line); + canPrependSpaces = false; + line = ''; + width = 0; + } + + line += char; + width += characterWidth; + } + } + + // run word out of the bounds + else { + // if there are words in this line already + // finish that line and start a new one + if (line.length > 0) { + lines += TextMetrics.addLine(line); + line = ''; + width = 0; + } + + var isLastToken = i === tokens.length - 1; + + // give it its own line if it's not the end + lines += TextMetrics.addLine(token, !isLastToken); + canPrependSpaces = false; + line = ''; + width = 0; + } + } + + // word could fit + else { + // word won't fit because of existing words + // start a new line + if (tokenWidth + width > wordWrapWidth) { + // if its a space we don't want it + canPrependSpaces = false; + + // add a new line + lines += TextMetrics.addLine(line); + + // start a new line + line = ''; + width = 0; + } + + // don't add spaces to the beginning of lines + if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces) { + // add the word to the current line + line += token; + + // update width counter + width += tokenWidth; + } + } + } + + lines += TextMetrics.addLine(line, false); + + return lines; + }; + + /** + * Convienience function for logging each line added during the wordWrap + * method + * + * @private + * @param {string} line - The line of text to add + * @param {boolean} newLine - Add new line character to end + * @return {string} A formatted line + */ + + + TextMetrics.addLine = function addLine(line) { + var newLine = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + + line = TextMetrics.trimRight(line); + + line = newLine ? line + '\n' : line; + + return line; + }; + + /** + * Gets & sets the widths of calculated characters in a cache object + * + * @private + * @param {string} key The key + * @param {number} letterSpacing The letter spacing + * @param {object} cache The cache + * @param {CanvasRenderingContext2D} context The canvas context + * @return {number} The from cache. + */ + + + TextMetrics.getFromCache = function getFromCache(key, letterSpacing, cache, context) { + var width = cache[key]; + + if (width === undefined) { + var spacing = key.length * letterSpacing; + + width = context.measureText(key).width + spacing; + cache[key] = width; + } + + return width; + }; + + /** + * Determines whether we should collapse breaking spaces + * + * @private + * @param {string} whiteSpace The TextStyle property whiteSpace + * @return {boolean} should collapse + */ + + + TextMetrics.collapseSpaces = function collapseSpaces(whiteSpace) { + return whiteSpace === 'normal' || whiteSpace === 'pre-line'; + }; + + /** + * Determines whether we should collapse newLine chars + * + * @private + * @param {string} whiteSpace The white space + * @return {boolean} should collapse + */ + + + TextMetrics.collapseNewlines = function collapseNewlines(whiteSpace) { + return whiteSpace === 'normal'; + }; + + /** + * trims breaking whitespaces from string + * + * @private + * @param {string} text The text + * @return {string} trimmed string + */ + + + TextMetrics.trimRight = function trimRight(text) { + if (typeof text !== 'string') { + return ''; + } + + for (var i = text.length - 1; i >= 0; i--) { + var char = text[i]; + + if (!TextMetrics.isBreakingSpace(char)) { + break; + } + + text = text.slice(0, -1); + } + + return text; + }; + + /** + * Determines if char is a newline. + * + * @private + * @param {string} char The character + * @return {boolean} True if newline, False otherwise. + */ + + + TextMetrics.isNewline = function isNewline(char) { + if (typeof char !== 'string') { + return false; + } + + return TextMetrics._newlines.indexOf(char.charCodeAt(0)) >= 0; + }; + + /** + * Determines if char is a breaking whitespace. + * + * @private + * @param {string} char The character + * @return {boolean} True if whitespace, False otherwise. + */ + + + TextMetrics.isBreakingSpace = function isBreakingSpace(char) { + if (typeof char !== 'string') { + return false; + } + + return TextMetrics._breakingSpaces.indexOf(char.charCodeAt(0)) >= 0; + }; + + /** + * Splits a string into words, breaking-spaces and newLine characters + * + * @private + * @param {string} text The text + * @return {array} A tokenized array + */ + + + TextMetrics.tokenize = function tokenize(text) { + var tokens = []; + var token = ''; + + if (typeof text !== 'string') { + return tokens; + } + + for (var i = 0; i < text.length; i++) { + var char = text[i]; + + if (TextMetrics.isBreakingSpace(char) || TextMetrics.isNewline(char)) { + if (token !== '') { + tokens.push(token); + token = ''; + } + + tokens.push(char); + + continue; + } + + token += char; + } + + if (token !== '') { + tokens.push(token); + } + + return tokens; + }; + + /** + * This method exists to be easily overridden + * It allows one to customise which words should break + * Examples are if the token is CJK or numbers. + * It must return a boolean. + * + * @private + * @param {string} token The token + * @param {boolean} breakWords The style attr break words + * @return {boolean} whether to break word or not + */ + + + TextMetrics.canBreakWords = function canBreakWords(token, breakWords) { + return breakWords; + }; + + /** + * This method exists to be easily overridden + * It allows one to determine whether a pair of characters + * should be broken by newlines + * For example certain characters in CJK langs or numbers. + * It must return a boolean. + * + * @private + * @param {string} char The character + * @param {string} nextChar The next character + * @param {string} token The token/word the characters are from + * @param {number} index The index in the token of the char + * @param {boolean} breakWords The style attr break words + * @return {boolean} whether to break word or not + */ + + + TextMetrics.canBreakChars = function canBreakChars(char, nextChar, token, index, breakWords) // eslint-disable-line no-unused-vars + { + return true; + }; + + /** + * Calculates the ascent, descent and fontSize of a given font-style + * + * @static + * @param {string} font - String representing the style of the font + * @return {PIXI.TextMetrics~FontMetrics} Font properties object + */ + + + TextMetrics.measureFont = function measureFont(font) { + // as this method is used for preparing assets, don't recalculate things if we don't need to + if (TextMetrics._fonts[font]) { + return TextMetrics._fonts[font]; + } + + var properties = {}; + + var canvas = TextMetrics._canvas; + var context = TextMetrics._context; + + context.font = font; + + var metricsString = TextMetrics.METRICS_STRING + TextMetrics.BASELINE_SYMBOL; + var width = Math.ceil(context.measureText(metricsString).width); + var baseline = Math.ceil(context.measureText(TextMetrics.BASELINE_SYMBOL).width); + var height = 2 * baseline; + + baseline = baseline * TextMetrics.BASELINE_MULTIPLIER | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = font; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText(metricsString, 0, baseline); + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i = 0; + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } else { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var _j = 0; _j < line; _j += 4) { + if (imagedata[idx + _j] !== 255) { + stop = true; + break; + } + } + + if (!stop) { + idx -= line; + } else { + break; + } + } + + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + + TextMetrics._fonts[font] = properties; + + return properties; + }; + + /** + * Clear font metrics in metrics cache. + * + * @static + * @param {string} [font] - font name. If font name not set then clear cache for all fonts. + */ + + + TextMetrics.clearMetrics = function clearMetrics() { + var font = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + + if (font) { + delete TextMetrics._fonts[font]; + } else { + TextMetrics._fonts = {}; + } + }; + + return TextMetrics; +}(); + +/** + * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}. + * @class FontMetrics + * @memberof PIXI.TextMetrics~ + * @property {number} ascent - The ascent distance + * @property {number} descent - The descent distance + * @property {number} fontSize - Font size from ascent to descent + */ + +exports.default = TextMetrics; +var canvas = document.createElement('canvas'); + +canvas.width = canvas.height = 10; + +/** + * Cached canvas element for measuring text + * @memberof PIXI.TextMetrics + * @type {HTMLCanvasElement} + * @private + */ +TextMetrics._canvas = canvas; + +/** + * Cache for context to use. + * @memberof PIXI.TextMetrics + * @type {CanvasRenderingContext2D} + * @private + */ +TextMetrics._context = canvas.getContext('2d'); + +/** + * Cache of PIXI.TextMetrics~FontMetrics objects. + * @memberof PIXI.TextMetrics + * @type {Object} + * @private + */ +TextMetrics._fonts = {}; + +/** + * String used for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name METRICS_STRING + * @type {string} + * @default |Éq + */ +TextMetrics.METRICS_STRING = '|Éq'; + +/** + * Baseline symbol for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name BASELINE_SYMBOL + * @type {string} + * @default M + */ +TextMetrics.BASELINE_SYMBOL = 'M'; + +/** + * Baseline multiplier for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name BASELINE_MULTIPLIER + * @type {number} + * @default 1.4 + */ +TextMetrics.BASELINE_MULTIPLIER = 1.4; + +/** + * Cache of new line chars. + * @memberof PIXI.TextMetrics + * @type {number[]} + * @private + */ +TextMetrics._newlines = [0x000A, // line feed +0x000D]; + +/** + * Cache of breaking spaces. + * @memberof PIXI.TextMetrics + * @type {number[]} + * @private + */ +TextMetrics._breakingSpaces = [0x0009, // character tabulation +0x0020, // space +0x2000, // en quad +0x2001, // em quad +0x2002, // en space +0x2003, // em space +0x2004, // three-per-em space +0x2005, // four-per-em space +0x2006, // six-per-em space +0x2008, // punctuation space +0x2009, // thin space +0x200A, // hair space +0x205F, // medium mathematical space +0x3000]; + +},{}],110:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // disabling eslint for now, going to rewrite this in v5 +/* eslint-disable */ + +var _const = require('../const'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: 'black', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: _const.TEXT_GRADIENT.LINEAR_VERTICAL, + fillGradientStops: [], + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + trim: false, + whiteSpace: 'pre', + wordWrap: false, + wordWrapWidth: 100, + leading: 0 +}; + +var genericFontFamilies = ['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui']; + +/** + * A TextStyle Object decorates a Text Object. It can be shared between + * multiple Text objects. Changing the style will update all text objects using it. + * It can be generated [here](https://pixijs.io/pixi-text-style). + * + * @class + * @memberof PIXI + */ + +var TextStyle = function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string|number} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours + * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} + * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set + * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * @param {string|string[]} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', 800' or '900') + * @param {number} [style.leading=0] - The space between lines + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Possible values "miter" (creates a sharp corner), "round" (creates a round corner) or "bevel" + * (creates a squared corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {boolean} [style.trim=false] - Trim transparent borders + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {boolean} [style.whiteSpace='pre'] - Determines whether newlines & spaces are collapsed or preserved "normal" + * (collapse, collapse), "pre" (preserve, preserve) | "pre-line" (preserve, collapse). It needs wordWrap to be set to true + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + _classCallCheck(this, TextStyle); + + this.styleID = 0; + + this.reset(); + + deepCopyProperties(this, style, style); + } + + /** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return {PIXI.TextStyle} New cloned TextStyle object + */ + + + TextStyle.prototype.clone = function clone() { + var clonedProperties = {}; + + deepCopyProperties(clonedProperties, this, defaultStyle); + + return new TextStyle(clonedProperties); + }; + + /** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ + + + TextStyle.prototype.reset = function reset() { + deepCopyProperties(this, defaultStyle, defaultStyle); + }; + + /** + * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text + * + * @member {string} + */ + + + /** + * Generates a font style string to use for `TextMetrics.measureFont()`. + * + * @return {string} Font style string, for passing to `TextMetrics.measureFont()` + */ + TextStyle.prototype.toFontString = function toFontString() { + // build canvas api font setting from individual components. Convert a numeric this.fontSize to px + var fontSizeString = typeof this.fontSize === 'number' ? this.fontSize + 'px' : this.fontSize; + + // Clean-up fontFamily property by quoting each font name + // this will support font names with spaces + var fontFamilies = this.fontFamily; + + if (!Array.isArray(this.fontFamily)) { + fontFamilies = this.fontFamily.split(','); + } + + for (var i = fontFamilies.length - 1; i >= 0; i--) { + // Trim any extra white-space + var fontFamily = fontFamilies[i].trim(); + + // Check if font is already escaped in quotes except for CSS generic fonts + if (!/([\"\'])[^\'\"]+\1/.test(fontFamily) && genericFontFamilies.indexOf(fontFamily) < 0) { + fontFamily = '"' + fontFamily + '"'; + } + fontFamilies[i] = fontFamily; + } + + return this.fontStyle + ' ' + this.fontVariant + ' ' + this.fontWeight + ' ' + fontSizeString + ' ' + fontFamilies.join(','); + }; + + _createClass(TextStyle, [{ + key: 'align', + get: function get() { + return this._align; + }, + set: function set(align) // eslint-disable-line require-jsdoc + { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + } + + /** + * Indicates if lines can be wrapped within words, it needs wordWrap to be set to true + * + * @member {boolean} + */ + + }, { + key: 'breakWords', + get: function get() { + return this._breakWords; + }, + set: function set(breakWords) // eslint-disable-line require-jsdoc + { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + } + + /** + * Set a drop shadow for the text + * + * @member {boolean} + */ + + }, { + key: 'dropShadow', + get: function get() { + return this._dropShadow; + }, + set: function set(dropShadow) // eslint-disable-line require-jsdoc + { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + } + + /** + * Set alpha for the drop shadow + * + * @member {number} + */ + + }, { + key: 'dropShadowAlpha', + get: function get() { + return this._dropShadowAlpha; + }, + set: function set(dropShadowAlpha) // eslint-disable-line require-jsdoc + { + if (this._dropShadowAlpha !== dropShadowAlpha) { + this._dropShadowAlpha = dropShadowAlpha; + this.styleID++; + } + } + + /** + * Set a angle of the drop shadow + * + * @member {number} + */ + + }, { + key: 'dropShadowAngle', + get: function get() { + return this._dropShadowAngle; + }, + set: function set(dropShadowAngle) // eslint-disable-line require-jsdoc + { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + } + + /** + * Set a shadow blur radius + * + * @member {number} + */ + + }, { + key: 'dropShadowBlur', + get: function get() { + return this._dropShadowBlur; + }, + set: function set(dropShadowBlur) // eslint-disable-line require-jsdoc + { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + } + + /** + * A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * + * @member {string|number} + */ + + }, { + key: 'dropShadowColor', + get: function get() { + return this._dropShadowColor; + }, + set: function set(dropShadowColor) // eslint-disable-line require-jsdoc + { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + } + + /** + * Set a distance of the drop shadow + * + * @member {number} + */ + + }, { + key: 'dropShadowDistance', + get: function get() { + return this._dropShadowDistance; + }, + set: function set(dropShadowDistance) // eslint-disable-line require-jsdoc + { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + } + + /** + * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'. + * Can be an array to create a gradient eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * + * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern} + */ + + }, { + key: 'fill', + get: function get() { + return this._fill; + }, + set: function set(fill) // eslint-disable-line require-jsdoc + { + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + } + + /** + * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient. + * See {@link PIXI.TEXT_GRADIENT} + * + * @member {number} + */ + + }, { + key: 'fillGradientType', + get: function get() { + return this._fillGradientType; + }, + set: function set(fillGradientType) // eslint-disable-line require-jsdoc + { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + } + + /** + * If fill is an array of colours to create a gradient, this array can set the stop points + * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * + * @member {number[]} + */ + + }, { + key: 'fillGradientStops', + get: function get() { + return this._fillGradientStops; + }, + set: function set(fillGradientStops) // eslint-disable-line require-jsdoc + { + if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { + this._fillGradientStops = fillGradientStops; + this.styleID++; + } + } + + /** + * The font family + * + * @member {string|string[]} + */ + + }, { + key: 'fontFamily', + get: function get() { + return this._fontFamily; + }, + set: function set(fontFamily) // eslint-disable-line require-jsdoc + { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + } + + /** + * The font size + * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em') + * + * @member {number|string} + */ + + }, { + key: 'fontSize', + get: function get() { + return this._fontSize; + }, + set: function set(fontSize) // eslint-disable-line require-jsdoc + { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + } + + /** + * The font style + * ('normal', 'italic' or 'oblique') + * + * @member {string} + */ + + }, { + key: 'fontStyle', + get: function get() { + return this._fontStyle; + }, + set: function set(fontStyle) // eslint-disable-line require-jsdoc + { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + } + + /** + * The font variant + * ('normal' or 'small-caps') + * + * @member {string} + */ + + }, { + key: 'fontVariant', + get: function get() { + return this._fontVariant; + }, + set: function set(fontVariant) // eslint-disable-line require-jsdoc + { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + } + + /** + * The font weight + * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900') + * + * @member {string} + */ + + }, { + key: 'fontWeight', + get: function get() { + return this._fontWeight; + }, + set: function set(fontWeight) // eslint-disable-line require-jsdoc + { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + } + + /** + * The amount of spacing between letters, default is 0 + * + * @member {number} + */ + + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(letterSpacing) // eslint-disable-line require-jsdoc + { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + } + + /** + * The line height, a number that represents the vertical space that a letter uses + * + * @member {number} + */ + + }, { + key: 'lineHeight', + get: function get() { + return this._lineHeight; + }, + set: function set(lineHeight) // eslint-disable-line require-jsdoc + { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + } + + /** + * The space between lines + * + * @member {number} + */ + + }, { + key: 'leading', + get: function get() { + return this._leading; + }, + set: function set(leading) // eslint-disable-line require-jsdoc + { + if (this._leading !== leading) { + this._leading = leading; + this.styleID++; + } + } + + /** + * The lineJoin property sets the type of corner created, it can resolve spiked text issues. + * Default is 'miter' (creates a sharp corner). + * + * @member {string} + */ + + }, { + key: 'lineJoin', + get: function get() { + return this._lineJoin; + }, + set: function set(lineJoin) // eslint-disable-line require-jsdoc + { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + } + + /** + * The miter limit to use when using the 'miter' lineJoin mode + * This can reduce or increase the spikiness of rendered text. + * + * @member {number} + */ + + }, { + key: 'miterLimit', + get: function get() { + return this._miterLimit; + }, + set: function set(miterLimit) // eslint-disable-line require-jsdoc + { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + } + + /** + * Occasionally some fonts are cropped. Adding some padding will prevent this from happening + * by adding padding to all sides of the text. + * + * @member {number} + */ + + }, { + key: 'padding', + get: function get() { + return this._padding; + }, + set: function set(padding) // eslint-disable-line require-jsdoc + { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + } + + /** + * A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * + * @member {string|number} + */ + + }, { + key: 'stroke', + get: function get() { + return this._stroke; + }, + set: function set(stroke) // eslint-disable-line require-jsdoc + { + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + } + + /** + * A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * + * @member {number} + */ + + }, { + key: 'strokeThickness', + get: function get() { + return this._strokeThickness; + }, + set: function set(strokeThickness) // eslint-disable-line require-jsdoc + { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + } + + /** + * The baseline of the text that is rendered. + * + * @member {string} + */ + + }, { + key: 'textBaseline', + get: function get() { + return this._textBaseline; + }, + set: function set(textBaseline) // eslint-disable-line require-jsdoc + { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + } + + /** + * Trim transparent borders + * + * @member {boolean} + */ + + }, { + key: 'trim', + get: function get() { + return this._trim; + }, + set: function set(trim) // eslint-disable-line require-jsdoc + { + if (this._trim !== trim) { + this._trim = trim; + this.styleID++; + } + } + + /** + * How newlines and spaces should be handled. + * Default is 'pre' (preserve, preserve). + * + * value | New lines | Spaces + * --- | --- | --- + * 'normal' | Collapse | Collapse + * 'pre' | Preserve | Preserve + * 'pre-line' | Preserve | Collapse + * + * @member {string} + */ + + }, { + key: 'whiteSpace', + get: function get() { + return this._whiteSpace; + }, + set: function set(whiteSpace) // eslint-disable-line require-jsdoc + { + if (this._whiteSpace !== whiteSpace) { + this._whiteSpace = whiteSpace; + this.styleID++; + } + } + + /** + * Indicates if word wrap should be used + * + * @member {boolean} + */ + + }, { + key: 'wordWrap', + get: function get() { + return this._wordWrap; + }, + set: function set(wordWrap) // eslint-disable-line require-jsdoc + { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + } + + /** + * The width at which text will wrap, it needs wordWrap to be set to true + * + * @member {number} + */ + + }, { + key: 'wordWrapWidth', + get: function get() { + return this._wordWrapWidth; + }, + set: function set(wordWrapWidth) // eslint-disable-line require-jsdoc + { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + } + }]); + + return TextStyle; +}(); + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * @private + * @param {number|number[]} color + * @return {string} The color as a string. + */ + + +exports.default = TextStyle; +function getSingleColor(color) { + if (typeof color === 'number') { + return (0, _utils.hex2string)(color); + } else if (typeof color === 'string') { + if (color.indexOf('0x') === 0) { + color = color.replace('0x', '#'); + } + } + + return color; +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * @private + * @param {number|number[]} color + * @return {string} The color as a string. + */ +function getColor(color) { + if (!Array.isArray(color)) { + return getSingleColor(color); + } else { + for (var i = 0; i < color.length; ++i) { + color[i] = getSingleColor(color[i]); + } + + return color; + } +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * @private + * @param {Array} array1 First array to compare + * @param {Array} array2 Second array to compare + * @return {boolean} Do the arrays contain the same values in the same order + */ +function areArraysEqual(array1, array2) { + if (!Array.isArray(array1) || !Array.isArray(array2)) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } + + return true; +} + +/** + * Utility function to ensure that object properties are copied by value, and not by reference + * @private + * @param {Object} target Target object to copy properties into + * @param {Object} source Source object for the proporties to copy + * @param {string} propertyObj Object containing properties names we want to loop over + */ +function deepCopyProperties(target, source, propertyObj) { + for (var prop in propertyObj) { + if (Array.isArray(source[prop])) { + target[prop] = source[prop].slice(); + } else { + target[prop] = source[prop]; + } + } +} + +},{"../const":46,"../utils":125}],111:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let baseRenderTexture = new PIXI.BaseRenderTexture(renderer, 800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * baseRenderTexture.render(sprite); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let baseRenderTexture = new PIXI.BaseRenderTexture(100, 100); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var BaseRenderTexture = function (_BaseTexture) { + _inherits(BaseRenderTexture, _BaseTexture); + + /** + * @param {number} [width=100] - The width of the base render texture + * @param {number} [height=100] - The height of the base render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + */ + function BaseRenderTexture() { + var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + + _classCallCheck(this, BaseRenderTexture); + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, null, scaleMode)); + + _this.resolution = resolution || _settings2.default.RESOLUTION; + + _this.width = Math.ceil(width); + _this.height = Math.ceil(height); + + _this.realWidth = _this.width * _this.resolution; + _this.realHeight = _this.height * _this.resolution; + + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + _this.hasLoaded = true; + + /** + * A map of renderer IDs to webgl renderTargets + * + * @private + * @member {object} + */ + _this._glRenderTargets = {}; + + /** + * A reference to the canvas render target (we only need one as this can be shared across renderers) + * + * @private + * @member {object} + */ + _this._canvasRenderTarget = null; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + return _this; + } + + /** + * Resizes the BaseRenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + */ + + + BaseRenderTexture.prototype.resize = function resize(width, height) { + width = Math.ceil(width); + height = Math.ceil(height); + + if (width === this.width && height === this.height) { + return; + } + + this.valid = width > 0 && height > 0; + + this.width = width; + this.height = height; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + if (!this.valid) { + return; + } + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + */ + + + BaseRenderTexture.prototype.destroy = function destroy() { + _BaseTexture.prototype.destroy.call(this, true); + this.renderer = null; + }; + + return BaseRenderTexture; +}(_BaseTexture3.default); + +exports.default = BaseRenderTexture; + +},{"../settings":101,"./BaseTexture":112}],112:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var BaseTexture = function (_EventEmitter) { + _inherits(BaseTexture, _EventEmitter); + + /** + * @param {HTMLImageElement|HTMLCanvasElement} [source] - the source object of the texture. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture + */ + function BaseTexture(source, scaleMode, resolution) { + _classCallCheck(this, BaseTexture); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.uid = (0, _utils.uid)(); + + _this.touched = 0; + + /** + * The resolution / device pixel ratio of the texture + * + * @member {number} + * @default 1 + */ + _this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The width of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.width = 100; + + /** + * The height of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.height = 100; + + // TODO docs + // used to store the actual dimensions of the source + /** + * Used to store the actual width of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realWidth = 100; + /** + * Used to store the actual height of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realHeight = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Set to true once the base texture has successfully loaded. + * + * This is never true if the underlying source fails to load or has no texture data. + * + * @readonly + * @member {boolean} + */ + _this.hasLoaded = false; + + /** + * Set to true if the source is currently loading. + * + * If an Image source is loading the 'loaded' or 'error' event will be + * dispatched when the operation ends. An underyling source that is + * immediately-available bypasses loading entirely. + * + * @readonly + * @member {boolean} + */ + _this.isLoading = false; + + /** + * The image source that is used to create the texture. + * + * TODO: Make this a setter that calls loadSource(); + * + * @readonly + * @member {HTMLImageElement|HTMLCanvasElement} + */ + _this.source = null; // set in loadSource, if at all + + /** + * The image source that is used to create the texture. This is used to + * store the original Svg source when it is replaced with a canvas element. + * + * TODO: Currently not in use but could be used when re-scaling svg. + * + * @readonly + * @member {Image} + */ + _this.origSource = null; // set in loadSvg, if at all + + /** + * Type of image defined in source, eg. `png` or `svg` + * + * @readonly + * @member {string} + */ + _this.imageType = null; // set in updateImageType + + /** + * Scale for source image. Used with Svg images to scale them before rasterization. + * + * @readonly + * @member {number} + */ + _this.sourceScale = 1.0; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * All blend modes, and shaders written for default value. Change it on your own risk. + * + * @member {boolean} + * @default true + */ + _this.premultipliedAlpha = true; + + /** + * The image url of the texture + * + * @member {string} + */ + _this.imageUrl = null; + + /** + * Whether or not the texture is a power of two, try to use power of two textures as much + * as you can + * + * @private + * @member {boolean} + */ + _this.isPowerOfTwo = false; + + // used for webGL + + /** + * + * Set this to true if a mipmap of this texture needs to be generated. This value needs + * to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @member {boolean} + * @see PIXI.MIPMAP_TEXTURES + */ + _this.mipmap = _settings2.default.MIPMAP_TEXTURES; + + /** + * + * WebGL Texture wrap mode + * + * @member {number} + * @see PIXI.WRAP_MODES + */ + _this.wrapMode = _settings2.default.WRAP_MODE; + + /** + * A map of renderer IDs to webgl textures + * + * @private + * @member {object} + */ + _this._glTextures = {}; + + _this._enabled = 0; + _this._virtalBoundId = -1; + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + + /** + * The ids under which this BaseTexture has been added to the base texture cache. This is + * automatically set as long as BaseTexture.addToCache is used, but may not be set if a + * BaseTexture is added directly to the BaseTextureCache array. + * + * @member {string[]} + */ + _this.textureCacheIds = []; + + // if no source passed don't try to load + if (source) { + _this.loadSource(source); + } + + /** + * Fired when a not-immediately-available source finishes loading. + * + * @protected + * @event PIXI.BaseTexture#loaded + * @param {PIXI.BaseTexture} baseTexture - Resource loaded. + */ + + /** + * Fired when a not-immediately-available source fails to load. + * + * @protected + * @event PIXI.BaseTexture#error + * @param {PIXI.BaseTexture} baseTexture - Resource errored. + */ + + /** + * Fired when BaseTexture is updated. + * + * @protected + * @event PIXI.BaseTexture#update + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. + */ + + /** + * Fired when BaseTexture is destroyed. + * + * @protected + * @event PIXI.BaseTexture#dispose + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. + */ + return _this; + } + + /** + * Updates the texture on all the webgl renderers, this also assumes the src has changed. + * + * @fires PIXI.BaseTexture#update + */ + + + BaseTexture.prototype.update = function update() { + // Svg size is handled during load + if (this.imageType !== 'svg') { + this.realWidth = this.source.naturalWidth || this.source.videoWidth || this.source.width; + this.realHeight = this.source.naturalHeight || this.source.videoHeight || this.source.height; + + this._updateDimensions(); + } + + this.emit('update', this); + }; + + /** + * Update dimensions from real values + */ + + + BaseTexture.prototype._updateDimensions = function _updateDimensions() { + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + this.isPowerOfTwo = _bitTwiddle2.default.isPow2(this.realWidth) && _bitTwiddle2.default.isPow2(this.realHeight); + }; + + /** + * Load a source. + * + * If the source is not-immediately-available, such as an image that needs to be + * downloaded, then the 'loaded' or 'error' event will be dispatched in the future + * and `hasLoaded` will remain false after this call. + * + * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: + * + * if (texture.hasLoaded) { + * // texture ready for use + * } else if (texture.isLoading) { + * // listen to 'loaded' and/or 'error' events on texture + * } else { + * // not loading, not going to load UNLESS the source is reloaded + * // (it may still make sense to listen to the events) + * } + * + * @protected + * @param {HTMLImageElement|HTMLCanvasElement} source - the source object of the texture. + */ + + + BaseTexture.prototype.loadSource = function loadSource(source) { + var wasLoading = this.isLoading; + + this.hasLoaded = false; + this.isLoading = false; + + if (wasLoading && this.source) { + this.source.onload = null; + this.source.onerror = null; + } + + var firstSourceLoaded = !this.source; + + this.source = source; + + // Apply source if loaded. Otherwise setup appropriate loading monitors. + if ((source.src && source.complete || source.getContext) && source.width && source.height) { + this._updateImageType(); + + if (this.imageType === 'svg') { + this._loadSvgSource(); + } else { + this._sourceLoaded(); + } + + if (firstSourceLoaded) { + // send loaded event if previous source was null and we have been passed a pre-loaded IMG element + this.emit('loaded', this); + } + } else if (!source.getContext) { + // Image fail / not ready + this.isLoading = true; + + var scope = this; + + source.onload = function () { + scope._updateImageType(); + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope._sourceLoaded(); + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + scope.emit('loaded', scope); + }; + + source.onerror = function () { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope.emit('error', scope); + }; + + // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element + // "The value of `complete` can thus change while a script is executing." + // So complete needs to be re-checked after the callbacks have been added.. + // NOTE: complete will be true if the image has no src so best to check if the src is set. + if (source.complete && source.src) { + // ..and if we're complete now, no need for callbacks + source.onload = null; + source.onerror = null; + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + this.isLoading = false; + + if (source.width && source.height) { + this._sourceLoaded(); + + // If any previous subscribers possible + if (wasLoading) { + this.emit('loaded', this); + } + } + // If any previous subscribers possible + else if (wasLoading) { + this.emit('error', this); + } + } + } + }; + + /** + * Updates type of the source image. + */ + + + BaseTexture.prototype._updateImageType = function _updateImageType() { + if (!this.imageUrl) { + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + var imageType = void 0; + + if (dataUri && dataUri.mediaType === 'image') { + // Check for subType validity + var firstSubType = dataUri.subType.split('+')[0]; + + imageType = (0, _utils.getUrlFileExtension)('.' + firstSubType); + + if (!imageType) { + throw new Error('Invalid image type in data URI.'); + } + } else { + imageType = (0, _utils.getUrlFileExtension)(this.imageUrl); + + if (!imageType) { + imageType = 'png'; + } + } + + this.imageType = imageType; + }; + + /** + * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls + * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. + */ + + + BaseTexture.prototype._loadSvgSource = function _loadSvgSource() { + if (this.imageType !== 'svg') { + // Do nothing if source is not svg + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + + if (dataUri) { + this._loadSvgSourceUsingDataUri(dataUri); + } else { + // We got an URL, so we need to do an XHR to check the svg size + this._loadSvgSourceUsingXhr(); + } + }; + + /** + * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`. + * + * @param {string} dataUri - The data uri to load from. + */ + + + BaseTexture.prototype._loadSvgSourceUsingDataUri = function _loadSvgSourceUsingDataUri(dataUri) { + var svgString = void 0; + + if (dataUri.encoding === 'base64') { + if (!atob) { + throw new Error('Your browser doesn\'t support base64 conversions.'); + } + svgString = atob(dataUri.data); + } else { + svgString = dataUri.data; + } + + this._loadSvgSourceUsingString(svgString); + }; + + /** + * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. + */ + + + BaseTexture.prototype._loadSvgSourceUsingXhr = function _loadSvgSourceUsingXhr() { + var _this2 = this; + + var svgXhr = new XMLHttpRequest(); + + // This throws error on IE, so SVG Document can't be used + // svgXhr.responseType = 'document'; + + // This is not needed since we load the svg as string (breaks IE too) + // but overrideMimeType() can be used to force the response to be parsed as XML + // svgXhr.overrideMimeType('image/svg+xml'); + + svgXhr.onload = function () { + if (svgXhr.readyState !== svgXhr.DONE || svgXhr.status !== 200) { + throw new Error('Failed to load SVG using XHR.'); + } + + _this2._loadSvgSourceUsingString(svgXhr.response); + }; + + svgXhr.onerror = function () { + return _this2.emit('error', _this2); + }; + + svgXhr.open('GET', this.imageUrl, true); + svgXhr.send(); + }; + + /** + * Loads texture using an SVG string. The original SVG Image is stored as `origSource` and the + * created canvas is the new `source`. The SVG is scaled using `sourceScale`. Called by + * `_loadSvgSourceUsingXhr` or `_loadSvgSourceUsingDataUri`. + * + * @param {string} svgString SVG source as string + * + * @fires PIXI.BaseTexture#loaded + */ + + + BaseTexture.prototype._loadSvgSourceUsingString = function _loadSvgSourceUsingString(svgString) { + var svgSize = (0, _utils.getSvgSize)(svgString); + + var svgWidth = svgSize.width; + var svgHeight = svgSize.height; + + if (!svgWidth || !svgHeight) { + throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); + } + + // Scale realWidth and realHeight + this.realWidth = Math.round(svgWidth * this.sourceScale); + this.realHeight = Math.round(svgHeight * this.sourceScale); + + this._updateDimensions(); + + // Create a canvas element + var canvas = document.createElement('canvas'); + + canvas.width = this.realWidth; + canvas.height = this.realHeight; + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + + // Draw the Svg to the canvas + canvas.getContext('2d').drawImage(this.source, 0, 0, svgWidth, svgHeight, 0, 0, this.realWidth, this.realHeight); + + // Replace the original source image with the canvas + this.origSource = this.source; + this.source = canvas; + + // Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`) + BaseTexture.addToCache(this, canvas._pixiId); + + this.isLoading = false; + this._sourceLoaded(); + this.emit('loaded', this); + }; + + /** + * Used internally to update the width, height, and some other tracking vars once + * a source has successfully loaded. + * + * @private + */ + + + BaseTexture.prototype._sourceLoaded = function _sourceLoaded() { + this.hasLoaded = true; + this.update(); + }; + + /** + * Destroys this base texture + * + */ + + + BaseTexture.prototype.destroy = function destroy() { + if (this.imageUrl) { + delete _utils.TextureCache[this.imageUrl]; + + this.imageUrl = null; + + if (!navigator.isCocoonJS) { + this.source.src = ''; + } + } + + this.source = null; + + this.dispose(); + + BaseTexture.removeFromCache(this); + this.textureCacheIds = null; + + this._destroyed = true; + }; + + /** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + * @fires PIXI.BaseTexture#dispose + */ + + + BaseTexture.prototype.dispose = function dispose() { + this.emit('dispose', this); + }; + + /** + * Changes the source image of the texture. + * The original source must be an Image element. + * + * @param {string} newSrc - the path of the image + */ + + + BaseTexture.prototype.updateSourceImage = function updateSourceImage(newSrc) { + this.source.src = newSrc; + + this.loadSource(this.source); + }; + + /** + * Helper function that creates a base texture from the given image url. + * If the image is not in the base texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + // new Image() breaks tex loading in some versions of Chrome. + // See https://code.google.com/p/chromium/issues/detail?id=238071 + var image = new Image(); // document.createElement('img'); + + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + image.crossOrigin = (0, _determineCrossOrigin2.default)(imageUrl); + } else if (crossorigin) { + image.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; + } + + baseTexture = new BaseTexture(image, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + image.src = imageUrl; // Setting this triggers load + + BaseTexture.addToCache(baseTexture, imageUrl); + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @param {string} [origin='canvas'] - A string origin of who created the base texture + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode) { + var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; + + if (!canvas._pixiId) { + canvas._pixiId = origin + '_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[canvas._pixiId]; + + if (!baseTexture) { + baseTexture = new BaseTexture(canvas, scaleMode); + BaseTexture.addToCache(baseTexture, canvas._pixiId); + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture based on the source you provide. + * The source can be - image url, image element, canvas element. If the + * source is an image url or an image element and not in the base texture + * cache, it will be created and loaded. + * + * @static + * @param {string|HTMLImageElement|HTMLCanvasElement} source - The source to create base texture from. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.from = function from(source, scaleMode, sourceScale) { + if (typeof source === 'string') { + return BaseTexture.fromImage(source, undefined, scaleMode, sourceScale); + } else if (source instanceof HTMLImageElement) { + var imageUrl = source.src; + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + baseTexture = new BaseTexture(source, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + BaseTexture.addToCache(baseTexture, imageUrl); + } + + return baseTexture; + } else if (source instanceof HTMLCanvasElement) { + return BaseTexture.fromCanvas(source, scaleMode); + } + + // lets assume its a base texture! + return source; + }; + + /** + * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache. + * @param {string} id - The id that the BaseTexture will be stored against. + */ + + + BaseTexture.addToCache = function addToCache(baseTexture, id) { + if (id) { + if (baseTexture.textureCacheIds.indexOf(id) === -1) { + baseTexture.textureCacheIds.push(id); + } + + /* eslint-disable no-console */ + if (_utils.BaseTextureCache[id]) { + console.warn('BaseTexture added to the cache with an id [' + id + '] that already had an entry'); + } + /* eslint-enable no-console */ + + _utils.BaseTextureCache[id] = baseTexture; + } + }; + + /** + * Remove a BaseTexture from the global BaseTextureCache. + * + * @static + * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself. + * @return {PIXI.BaseTexture|null} The BaseTexture that was removed. + */ + + + BaseTexture.removeFromCache = function removeFromCache(baseTexture) { + if (typeof baseTexture === 'string') { + var baseTextureFromCache = _utils.BaseTextureCache[baseTexture]; + + if (baseTextureFromCache) { + var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); + + if (index > -1) { + baseTextureFromCache.textureCacheIds.splice(index, 1); + } + + delete _utils.BaseTextureCache[baseTexture]; + + return baseTextureFromCache; + } + } else if (baseTexture && baseTexture.textureCacheIds) { + for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { + delete _utils.BaseTextureCache[baseTexture.textureCacheIds[i]]; + } + + baseTexture.textureCacheIds.length = 0; + + return baseTexture; + } + + return null; + }; + + return BaseTexture; +}(_eventemitter2.default); + +exports.default = BaseTexture; + +},{"../settings":101,"../utils":125,"../utils/determineCrossOrigin":124,"bit-twiddle":1,"eventemitter3":3}],113:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseRenderTexture = require('./BaseRenderTexture'); + +var _BaseRenderTexture2 = _interopRequireDefault(_BaseRenderTexture); + +var _Texture2 = require('./Texture'); + +var _Texture3 = _interopRequireDefault(_Texture2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let renderTexture = PIXI.RenderTexture.create(800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let renderTexture = new PIXI.RenderTexture.create(100, 100); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.Texture + * @memberof PIXI + */ +var RenderTexture = function (_Texture) { + _inherits(RenderTexture, _Texture); + + /** + * @param {PIXI.BaseRenderTexture} baseRenderTexture - The renderer used for this RenderTexture + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + */ + function RenderTexture(baseRenderTexture, frame) { + _classCallCheck(this, RenderTexture); + + // support for legacy.. + var _legacyRenderer = null; + + if (!(baseRenderTexture instanceof _BaseRenderTexture2.default)) { + /* eslint-disable prefer-rest-params, no-console */ + var width = arguments[1]; + var height = arguments[2]; + var scaleMode = arguments[3]; + var resolution = arguments[4]; + + // we have an old render texture.. + console.warn('Please use RenderTexture.create(' + width + ', ' + height + ') instead of the ctor directly.'); + _legacyRenderer = arguments[0]; + /* eslint-enable prefer-rest-params, no-console */ + + frame = null; + baseRenderTexture = new _BaseRenderTexture2.default(width, height, scaleMode, resolution); + } + + /** + * The base texture object that this texture uses + * + * @member {BaseTexture} + */ + + var _this = _possibleConstructorReturn(this, _Texture.call(this, baseRenderTexture, frame)); + + _this.legacyRenderer = _legacyRenderer; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = true; + + _this._updateUvs(); + return _this; + } + + /** + * Resizes the RenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + * @param {boolean} doNotResizeBaseTexture - Should the baseTexture.width and height values be resized as well? + */ + + + RenderTexture.prototype.resize = function resize(width, height, doNotResizeBaseTexture) { + width = Math.ceil(width); + height = Math.ceil(height); + + // TODO - could be not required.. + this.valid = width > 0 && height > 0; + + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + + if (!doNotResizeBaseTexture) { + this.baseTexture.resize(width, height); + } + + this._updateUvs(); + }; + + /** + * A short hand way of creating a render texture. + * + * @param {number} [width=100] - The width of the render texture + * @param {number} [height=100] - The height of the render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.RenderTexture} The new render texture + */ + + + RenderTexture.create = function create(width, height, scaleMode, resolution) { + return new RenderTexture(new _BaseRenderTexture2.default(width, height, scaleMode, resolution)); + }; + + return RenderTexture; +}(_Texture3.default); + +exports.default = RenderTexture; + +},{"./BaseRenderTexture":111,"./Texture":115}],114:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _ = require('../'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Utility class for maintaining reference to a collection + * of Textures on a single Spritesheet. + * + * To access a sprite sheet from your code pass its JSON data file to Pixi's loader: + * + * ```js + * PIXI.loader.add("images/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.loader.resources["images/spritesheet.json"].spritesheet; + * ... + * } + * ``` + * With the `sheet.textures` you can create Sprite objects,`sheet.animations` can be used to create an AnimatedSprite. + * + * Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker}, + * {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}. + * Default anchor points (see {@link PIXI.Texture#defaultAnchor}) and grouping of animation sprites are currently only + * supported by TexturePacker. + * + * @class + * @memberof PIXI + */ +var Spritesheet = function () { + _createClass(Spritesheet, null, [{ + key: 'BATCH_SIZE', + + /** + * The maximum number of Textures to build per process. + * + * @type {number} + * @default 1000 + */ + get: function get() { + return 1000; + } + + /** + * @param {PIXI.BaseTexture} baseTexture Reference to the source BaseTexture object. + * @param {Object} data - Spritesheet image data. + * @param {string} [resolutionFilename] - The filename to consider when determining + * the resolution of the spritesheet. If not provided, the imageUrl will + * be used on the BaseTexture. + */ + + }]); + + function Spritesheet(baseTexture, data) { + var resolutionFilename = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + _classCallCheck(this, Spritesheet); + + /** + * Reference to ths source texture + * @type {PIXI.BaseTexture} + */ + this.baseTexture = baseTexture; + + /** + * A map containing all textures of the sprite sheet. + * Can be used to create a {@link PIXI.Sprite|Sprite}: + * ```js + * new PIXI.Sprite(sheet.textures["image.png"]); + * ``` + * @member {Object} + */ + this.textures = {}; + + /** + * A map containing the textures for each animation. + * Can be used to create an {@link PIXI.extras.AnimatedSprite|AnimatedSprite}: + * ```js + * new PIXI.extras.AnimatedSprite(sheet.animations["anim_name"]) + * ``` + * @member {Object} + */ + this.animations = {}; + + /** + * Reference to the original JSON data. + * @type {Object} + */ + this.data = data; + + /** + * The resolution of the spritesheet. + * @type {number} + */ + this.resolution = this._updateResolution(resolutionFilename || this.baseTexture.imageUrl); + + /** + * Map of spritesheet frames. + * @type {Object} + * @private + */ + this._frames = this.data.frames; + + /** + * Collection of frame names. + * @type {string[]} + * @private + */ + this._frameKeys = Object.keys(this._frames); + + /** + * Current batch index being processed. + * @type {number} + * @private + */ + this._batchIndex = 0; + + /** + * Callback when parse is completed. + * @type {Function} + * @private + */ + this._callback = null; + } + + /** + * Generate the resolution from the filename or fallback + * to the meta.scale field of the JSON data. + * + * @private + * @param {string} resolutionFilename - The filename to use for resolving + * the default resolution. + * @return {number} Resolution to use for spritesheet. + */ + + + Spritesheet.prototype._updateResolution = function _updateResolution(resolutionFilename) { + var scale = this.data.meta.scale; + + // Use a defaultValue of `null` to check if a url-based resolution is set + var resolution = (0, _utils.getResolutionOfUrl)(resolutionFilename, null); + + // No resolution found via URL + if (resolution === null) { + // Use the scale value or default to 1 + resolution = scale !== undefined ? parseFloat(scale) : 1; + } + + // For non-1 resolutions, update baseTexture + if (resolution !== 1) { + this.baseTexture.resolution = resolution; + this.baseTexture.update(); + } + + return resolution; + }; + + /** + * Parser spritesheet from loaded data. This is done asynchronously + * to prevent creating too many Texture within a single process. + * + * @param {Function} callback - Callback when complete returns + * a map of the Textures for this spritesheet. + */ + + + Spritesheet.prototype.parse = function parse(callback) { + this._batchIndex = 0; + this._callback = callback; + + if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) { + this._processFrames(0); + this._processAnimations(); + this._parseComplete(); + } else { + this._nextBatch(); + } + }; + + /** + * Process a batch of frames + * + * @private + * @param {number} initialFrameIndex - The index of frame to start. + */ + + + Spritesheet.prototype._processFrames = function _processFrames(initialFrameIndex) { + var frameIndex = initialFrameIndex; + var maxFrames = Spritesheet.BATCH_SIZE; + var sourceScale = this.baseTexture.sourceScale; + + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { + var i = this._frameKeys[frameIndex]; + var data = this._frames[i]; + var rect = data.frame; + + if (rect) { + var frame = null; + var trim = null; + var sourceSize = data.trimmed !== false && data.sourceSize ? data.sourceSize : data.frame; + + var orig = new _.Rectangle(0, 0, Math.floor(sourceSize.w * sourceScale) / this.resolution, Math.floor(sourceSize.h * sourceScale) / this.resolution); + + if (data.rotated) { + frame = new _.Rectangle(Math.floor(rect.x * sourceScale) / this.resolution, Math.floor(rect.y * sourceScale) / this.resolution, Math.floor(rect.h * sourceScale) / this.resolution, Math.floor(rect.w * sourceScale) / this.resolution); + } else { + frame = new _.Rectangle(Math.floor(rect.x * sourceScale) / this.resolution, Math.floor(rect.y * sourceScale) / this.resolution, Math.floor(rect.w * sourceScale) / this.resolution, Math.floor(rect.h * sourceScale) / this.resolution); + } + + // Check to see if the sprite is trimmed + if (data.trimmed !== false && data.spriteSourceSize) { + trim = new _.Rectangle(Math.floor(data.spriteSourceSize.x * sourceScale) / this.resolution, Math.floor(data.spriteSourceSize.y * sourceScale) / this.resolution, Math.floor(rect.w * sourceScale) / this.resolution, Math.floor(rect.h * sourceScale) / this.resolution); + } + + this.textures[i] = new _.Texture(this.baseTexture, frame, orig, trim, data.rotated ? 2 : 0, data.anchor); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage functions + _.Texture.addToCache(this.textures[i], i); + } + + frameIndex++; + } + }; + + /** + * Parse animations config + * + * @private + */ + + + Spritesheet.prototype._processAnimations = function _processAnimations() { + var animations = this.data.animations || {}; + + for (var animName in animations) { + this.animations[animName] = []; + for (var _iterator = animations[animName], _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var frameName = _ref; + + this.animations[animName].push(this.textures[frameName]); + } + } + }; + + /** + * The parse has completed. + * + * @private + */ + + + Spritesheet.prototype._parseComplete = function _parseComplete() { + var callback = this._callback; + + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); + }; + + /** + * Begin the next batch of textures. + * + * @private + */ + + + Spritesheet.prototype._nextBatch = function _nextBatch() { + var _this = this; + + this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); + this._batchIndex++; + setTimeout(function () { + if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { + _this._nextBatch(); + } else { + _this._processAnimations(); + _this._parseComplete(); + } + }, 0); + }; + + /** + * Destroy Spritesheet and don't use after this. + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Spritesheet.prototype.destroy = function destroy() { + var destroyBase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + for (var i in this.textures) { + this.textures[i].destroy(); + } + this._frames = null; + this._frameKeys = null; + this.data = null; + this.textures = null; + if (destroyBase) { + this.baseTexture.destroy(); + } + this.baseTexture = null; + }; + + return Spritesheet; +}(); + +exports.default = Spritesheet; + +},{"../":65,"../utils":125}],115:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture = require('./BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _VideoBaseTexture = require('./VideoBaseTexture'); + +var _VideoBaseTexture2 = _interopRequireDefault(_VideoBaseTexture); + +var _TextureUvs = require('./TextureUvs'); + +var _TextureUvs2 = _interopRequireDefault(_TextureUvs); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided + * then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * let texture = PIXI.Texture.fromImage('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` + * + * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. + * You can check for this by checking the sprite's _textureID property. + * ```js + * var texture = PIXI.Texture.fromImage('assets/image.svg'); + * var sprite1 = new PIXI.Sprite(texture); + * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file + * ``` + * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var Texture = function (_EventEmitter) { + _inherits(Texture, _EventEmitter); + + /** + * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + * @param {PIXI.Rectangle} [orig] - The area of original texture + * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture + * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8} + * @param {PIXI.Point} [anchor] - Default anchor point used for sprite placement / rotation + */ + function Texture(baseTexture, frame, orig, trim, rotate, anchor) { + _classCallCheck(this, Texture); + + /** + * Does this Texture have any frame data assigned to it? + * + * @member {boolean} + */ + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.noFrame = false; + + if (!frame) { + _this.noFrame = true; + frame = new _math.Rectangle(0, 0, 1, 1); + } + + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @member {PIXI.BaseTexture} + */ + _this.baseTexture = baseTexture; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @member {PIXI.Rectangle} + */ + _this._frame = frame; + + /** + * This is the trimmed area of original texture, before it was put in atlas + * Please call `_updateUvs()` after you change coordinates of `trim` manually. + * + * @member {PIXI.Rectangle} + */ + _this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @member {boolean} + */ + _this.requiresUpdate = false; + + /** + * The WebGL UV data cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + _this._uvs = null; + + /** + * This is the area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + + _this._rotate = Number(rotate || 0); + + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); + } + + if (baseTexture.hasLoaded) { + if (_this.noFrame) { + frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + + // if there is no frame we should monitor for any base texture changes.. + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + _this.frame = frame; + } else { + baseTexture.once('loaded', _this.onBaseTextureLoaded, _this); + } + + /** + * Anchor point that is used as default if sprite is created with this texture. + * Changing the `defaultAnchor` at a later point of time will not update Sprite's anchor point. + * @member {PIXI.Point} + * @default {0,0} + */ + _this.defaultAnchor = anchor ? new _math.Point(anchor.x, anchor.y) : new _math.Point(0, 0); + + /** + * Fired when the texture is updated. This happens if the frame or the baseTexture is updated. + * + * @event PIXI.Texture#update + * @protected + * @param {PIXI.Texture} texture - Instance of texture being updated. + */ + + _this._updateID = 0; + + /** + * Contains data for uvs. May contain clamp settings and some matrices. + * Its a bit heavy, so by default that object is not created. + * @member {PIXI.TextureMatrix} + * @default null + */ + _this.transform = null; + + /** + * The ids under which this Texture has been added to the texture cache. This is + * automatically set as long as Texture.addToCache is used, but may not be set if a + * Texture is added directly to the TextureCache array. + * + * @member {string[]} + */ + _this.textureCacheIds = []; + return _this; + } + + /** + * Updates this texture on the gpu. + * + */ + + + Texture.prototype.update = function update() { + this.baseTexture.update(); + }; + + /** + * Called when the base texture is loaded + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureLoaded = function onBaseTextureLoaded(baseTexture) { + this._updateID++; + + // TODO this code looks confusing.. boo to abusing getters and setters! + if (this.noFrame) { + this.frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } else { + this.frame = this._frame; + } + + this.baseTexture.on('update', this.onBaseTextureUpdated, this); + this.emit('update', this); + }; + + /** + * Called when the base texture is updated + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated(baseTexture) { + this._updateID++; + + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Texture.prototype.destroy = function destroy(destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destroyed too.. + if (_utils.TextureCache[this.baseTexture.imageUrl]) { + Texture.removeFromCache(this.baseTexture.imageUrl); + } + + this.baseTexture.destroy(); + } + + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); + + this.baseTexture = null; + } + + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + + this.valid = false; + + Texture.removeFromCache(this); + this.textureCacheIds = null; + }; + + /** + * Creates a new texture object that acts the same as this one. + * + * @return {PIXI.Texture} The new texture + */ + + + Texture.prototype.clone = function clone() { + return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); + }; + + /** + * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture. + */ + + + Texture.prototype._updateUvs = function _updateUvs() { + if (!this._uvs) { + this._uvs = new _TextureUvs2.default(); + } + + this._uvs.set(this._frame, this.baseTexture, this.rotate); + + this._updateID++; + }; + + /** + * Helper function that creates a Texture object from the given image url. + * If the image is not in the texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var texture = _utils.TextureCache[imageUrl]; + + if (!texture) { + texture = new Texture(_BaseTexture2.default.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); + Texture.addToCache(texture, imageUrl); + } + + return texture; + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return texture; + }; + + /** + * Helper function that creates a new Texture based on the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {string} [origin='canvas'] - A string origin of who created the base texture + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromCanvas = function fromCanvas(canvas, scaleMode) { + var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; + + return new Texture(_BaseTexture2.default.fromCanvas(canvas, scaleMode, origin)); + }; + + /** + * Helper function that creates a new Texture based on the given video element. + * + * @static + * @param {HTMLVideoElement|string} video - The URL or actual element of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideo = function fromVideo(video, scaleMode) { + if (typeof video === 'string') { + return Texture.fromVideoUrl(video, scaleMode); + } + + return new Texture(_VideoBaseTexture2.default.fromVideo(video, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the video url. + * + * @static + * @param {string} videoUrl - URL of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideoUrl = function fromVideoUrl(videoUrl, scaleMode) { + return new Texture(_VideoBaseTexture2.default.fromUrl(videoUrl, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} + * source - Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.from = function from(source) { + // TODO auto detect cross origin.. + // TODO pass in scale mode? + if (typeof source === 'string') { + var texture = _utils.TextureCache[source]; + + if (!texture) { + // check if its a video.. + var isVideo = source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/) !== null; + + if (isVideo) { + return Texture.fromVideoUrl(source); + } + + return Texture.fromImage(source); + } + + return texture; + } else if (source instanceof HTMLImageElement) { + return new Texture(_BaseTexture2.default.from(source)); + } else if (source instanceof HTMLCanvasElement) { + return Texture.fromCanvas(source, _settings2.default.SCALE_MODE, 'HTMLCanvasElement'); + } else if (source instanceof HTMLVideoElement) { + return Texture.fromVideo(source); + } else if (source instanceof _BaseTexture2.default) { + return new Texture(source); + } + + // lets assume its a texture! + return source; + }; + + /** + * Create a texture from a source and add to the cache. + * + * @static + * @param {HTMLImageElement|HTMLCanvasElement} source - The input source. + * @param {String} imageUrl - File name of texture, for cache and resolving resolution. + * @param {String} [name] - Human readible name for the texture cache. If no name is + * specified, only `imageUrl` will be used as the cache ID. + * @return {PIXI.Texture} Output texture + */ + + + Texture.fromLoader = function fromLoader(source, imageUrl, name) { + var baseTexture = new _BaseTexture2.default(source, undefined, (0, _utils.getResolutionOfUrl)(imageUrl)); + var texture = new Texture(baseTexture); + + baseTexture.imageUrl = imageUrl; + + // No name, use imageUrl instead + if (!name) { + name = imageUrl; + } + + // lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions + _BaseTexture2.default.addToCache(texture.baseTexture, name); + Texture.addToCache(texture, name); + + // also add references by url if they are different. + if (name !== imageUrl) { + _BaseTexture2.default.addToCache(texture.baseTexture, imageUrl); + Texture.addToCache(texture, imageUrl); + } + + return texture; + }; + + /** + * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the Texture will be stored against. + */ + + + Texture.addToCache = function addToCache(texture, id) { + if (id) { + if (texture.textureCacheIds.indexOf(id) === -1) { + texture.textureCacheIds.push(id); + } + + /* eslint-disable no-console */ + if (_utils.TextureCache[id]) { + console.warn('Texture added to the cache with an id [' + id + '] that already had an entry'); + } + /* eslint-enable no-console */ + + _utils.TextureCache[id] = texture; + } + }; + + /** + * Remove a Texture from the global TextureCache. + * + * @static + * @param {string|PIXI.Texture} texture - id of a Texture to be removed, or a Texture instance itself + * @return {PIXI.Texture|null} The Texture that was removed + */ + + + Texture.removeFromCache = function removeFromCache(texture) { + if (typeof texture === 'string') { + var textureFromCache = _utils.TextureCache[texture]; + + if (textureFromCache) { + var index = textureFromCache.textureCacheIds.indexOf(texture); + + if (index > -1) { + textureFromCache.textureCacheIds.splice(index, 1); + } + + delete _utils.TextureCache[texture]; + + return textureFromCache; + } + } else if (texture && texture.textureCacheIds) { + for (var i = 0; i < texture.textureCacheIds.length; ++i) { + // Check that texture matches the one being passed in before deleting it from the cache. + if (_utils.TextureCache[texture.textureCacheIds[i]] === texture) { + delete _utils.TextureCache[texture.textureCacheIds[i]]; + } + } + + texture.textureCacheIds.length = 0; + + return texture; + } + + return null; + }; + + /** + * The frame specifies the region of the base texture that this texture uses. + * Please call `_updateUvs()` after you change coordinates of `frame` manually. + * + * @member {PIXI.Rectangle} + */ + + + _createClass(Texture, [{ + key: 'frame', + get: function get() { + return this._frame; + }, + set: function set(frame) // eslint-disable-line require-jsdoc + { + this._frame = frame; + + this.noFrame = false; + + var x = frame.x, + y = frame.y, + width = frame.width, + height = frame.height; + + var xNotFit = x + width > this.baseTexture.width; + var yNotFit = y + height > this.baseTexture.height; + + if (xNotFit || yNotFit) { + var relationship = xNotFit && yNotFit ? 'and' : 'or'; + var errorX = 'X: ' + x + ' + ' + width + ' = ' + (x + width) + ' > ' + this.baseTexture.width; + var errorY = 'Y: ' + y + ' + ' + height + ' = ' + (y + height) + ' > ' + this.baseTexture.height; + + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + (errorX + ' ' + relationship + ' ' + errorY)); + } + + // this.valid = width && height && this.baseTexture.source && this.baseTexture.hasLoaded; + this.valid = width && height && this.baseTexture.hasLoaded; + + if (!this.trim && !this.rotate) { + this.orig = frame; + } + + if (this.valid) { + this._updateUvs(); + } + } + + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.GroupD8} for explanation + * + * @member {number} + */ + + }, { + key: 'rotate', + get: function get() { + return this._rotate; + }, + set: function set(rotate) // eslint-disable-line require-jsdoc + { + this._rotate = rotate; + if (this.valid) { + this._updateUvs(); + } + } + + /** + * The width of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'width', + get: function get() { + return this.orig.width; + } + + /** + * The height of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.orig.height; + } + }]); + + return Texture; +}(_eventemitter2.default); + +exports.default = Texture; + + +function createWhiteTexture() { + var canvas = document.createElement('canvas'); + + canvas.width = 10; + canvas.height = 10; + + var context = canvas.getContext('2d'); + + context.fillStyle = 'white'; + context.fillRect(0, 0, 10, 10); + + return new Texture(new _BaseTexture2.default(canvas)); +} + +function removeAllHandlers(tex) { + tex.destroy = function _emptyDestroy() {/* empty */}; + tex.on = function _emptyOn() {/* empty */}; + tex.once = function _emptyOnce() {/* empty */}; + tex.emit = function _emptyEmit() {/* empty */}; +} + +/** + * An empty texture, used often to not have to create multiple empty textures. + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.EMPTY = new Texture(new _BaseTexture2.default()); +removeAllHandlers(Texture.EMPTY); +removeAllHandlers(Texture.EMPTY.baseTexture); + +/** + * A white texture of 10x10 size, used for graphics and other things + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.WHITE = createWhiteTexture(); +removeAllHandlers(Texture.WHITE); +removeAllHandlers(Texture.WHITE.baseTexture); + +},{"../math":70,"../settings":101,"../utils":125,"./BaseTexture":112,"./TextureUvs":117,"./VideoBaseTexture":118,"eventemitter3":3}],116:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Matrix = require('../math/Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var tempMat = new _Matrix2.default(); + +/** + * Class controls uv transform and frame clamp for texture + * Can be used in Texture "transform" field, or separately, you can use different clamp settings on the same texture. + * If you want to add support for texture region of certain feature or filter, that's what you're looking for. + * + * @see PIXI.Texture + * @see PIXI.mesh.Mesh + * @see PIXI.extras.TilingSprite + * @class + * @memberof PIXI + */ + +var TextureMatrix = function () { + /** + * + * @param {PIXI.Texture} texture observed texture + * @param {number} [clampMargin] Changes frame clamping, 0.5 by default. Use -0.5 for extra border. + * @constructor + */ + function TextureMatrix(texture, clampMargin) { + _classCallCheck(this, TextureMatrix); + + this._texture = texture; + + this.mapCoord = new _Matrix2.default(); + + this.uClampFrame = new Float32Array(4); + + this.uClampOffset = new Float32Array(2); + + this._lastTextureID = -1; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders + * + * @default 0 + * @member {number} + */ + this.clampOffset = 0; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + this.clampMargin = typeof clampMargin === 'undefined' ? 0.5 : clampMargin; + } + + /** + * texture property + * @member {PIXI.Texture} + */ + + + /** + * Multiplies uvs array to transform + * @param {Float32Array} uvs mesh uvs + * @param {Float32Array} [out=uvs] output + * @returns {Float32Array} output + */ + TextureMatrix.prototype.multiplyUvs = function multiplyUvs(uvs, out) { + if (out === undefined) { + out = uvs; + } + + var mat = this.mapCoord; + + for (var i = 0; i < uvs.length; i += 2) { + var x = uvs[i]; + var y = uvs[i + 1]; + + out[i] = x * mat.a + y * mat.c + mat.tx; + out[i + 1] = x * mat.b + y * mat.d + mat.ty; + } + + return out; + }; + + /** + * updates matrices if texture was changed + * @param {boolean} forceUpdate if true, matrices will be updated any case + * @returns {boolean} whether or not it was updated + */ + + + TextureMatrix.prototype.update = function update(forceUpdate) { + var tex = this._texture; + + if (!tex || !tex.valid) { + return false; + } + + if (!forceUpdate && this._lastTextureID === tex._updateID) { + return false; + } + + this._lastTextureID = tex._updateID; + + var uvs = tex._uvs; + + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + + var orig = tex.orig; + var trim = tex.trim; + + if (trim) { + tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat); + } + + var texBase = tex.baseTexture; + var frame = this.uClampFrame; + var margin = this.clampMargin / texBase.resolution; + var offset = this.clampOffset; + + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.uClampOffset[0] = offset / texBase.realWidth; + this.uClampOffset[1] = offset / texBase.realHeight; + + return true; + }; + + _createClass(TextureMatrix, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._texture = value; + this._lastTextureID = -1; + } + }]); + + return TextureMatrix; +}(); + +exports.default = TextureMatrix; + +},{"../math/Matrix":67}],117:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _GroupD = require('../math/GroupD8'); + +var _GroupD2 = _interopRequireDefault(_GroupD); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A standard object to store the Uvs of a texture + * + * @class + * @private + * @memberof PIXI + */ +var TextureUvs = function () { + /** + * + */ + function TextureUvs() { + _classCallCheck(this, TextureUvs); + + this.x0 = 0; + this.y0 = 0; + + this.x1 = 1; + this.y1 = 0; + + this.x2 = 1; + this.y2 = 1; + + this.x3 = 0; + this.y3 = 1; + + this.uvsUint32 = new Uint32Array(4); + } + + /** + * Sets the texture Uvs based on the given frame information. + * + * @private + * @param {PIXI.Rectangle} frame - The frame of the texture + * @param {PIXI.Rectangle} baseFrame - The base frame of the texture + * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8} + */ + + + TextureUvs.prototype.set = function set(frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + + // coordinates of center + var cX = frame.x / tw + w2; + var cY = frame.y / th + h2; + + rotate = _GroupD2.default.add(rotate, _GroupD2.default.NW); // NW is top-left corner + this.x0 = cX + w2 * _GroupD2.default.uX(rotate); + this.y0 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + w2 * _GroupD2.default.uX(rotate); + this.y1 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x2 = cX + w2 * _GroupD2.default.uX(rotate); + this.y2 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x3 = cX + w2 * _GroupD2.default.uX(rotate); + this.y3 = cY + h2 * _GroupD2.default.uY(rotate); + } else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + + this.uvsUint32[0] = (this.y0 * 65535 & 0xFFFF) << 16 | this.x0 * 65535 & 0xFFFF; + this.uvsUint32[1] = (this.y1 * 65535 & 0xFFFF) << 16 | this.x1 * 65535 & 0xFFFF; + this.uvsUint32[2] = (this.y2 * 65535 & 0xFFFF) << 16 | this.x2 * 65535 & 0xFFFF; + this.uvsUint32[3] = (this.y3 * 65535 & 0xFFFF) << 16 | this.x3 * 65535 & 0xFFFF; + }; + + return TextureUvs; +}(); + +exports.default = TextureUvs; + +},{"../math/GroupD8":66}],118:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _utils = require('../utils'); + +var _ticker = require('../ticker'); + +var _const = require('../const'); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture of a [playing] Video. + * + * Video base textures mimic PixiJS BaseTexture.from.... method in their creation process. + * + * This can be used in several ways, such as: + * + * ```js + * let texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4'); + * + * let texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' }); + * + * let texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']); + * + * let texture = PIXI.VideoBaseTexture.fromUrls([ + * { src: '/video.webm', mime: 'video/webm' }, + * { src: '/video.mp4', mime: 'video/mp4' } + * ]); + * ``` + * + * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/). + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var VideoBaseTexture = function (_BaseTexture) { + _inherits(VideoBaseTexture, _BaseTexture); + + /** + * @param {HTMLVideoElement} source - Video source + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + */ + function VideoBaseTexture(source, scaleMode) { + _classCallCheck(this, VideoBaseTexture); + + if (!source) { + throw new Error('No video source element specified.'); + } + + // hook in here to check if video is already available. + // BaseTexture looks for a source.complete boolean, plus width & height. + + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + source.complete = true; + } + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, source, scaleMode)); + + _this.width = source.videoWidth; + _this.height = source.videoHeight; + + _this._autoUpdate = true; + _this._isAutoUpdating = false; + + /** + * When set to true will automatically play videos used by this texture once + * they are loaded. If false, it will not modify the playing state. + * + * @member {boolean} + * @default true + */ + _this.autoPlay = true; + + _this.update = _this.update.bind(_this); + _this._onCanPlay = _this._onCanPlay.bind(_this); + + source.addEventListener('play', _this._onPlayStart.bind(_this)); + source.addEventListener('pause', _this._onPlayStop.bind(_this)); + _this.hasLoaded = false; + _this.__loaded = false; + + if (!_this._isSourceReady()) { + source.addEventListener('canplay', _this._onCanPlay); + source.addEventListener('canplaythrough', _this._onCanPlay); + } else { + _this._onCanPlay(); + } + return _this; + } + + /** + * Returns true if the underlying source is playing. + * + * @private + * @return {boolean} True if playing. + */ + + + VideoBaseTexture.prototype._isSourcePlaying = function _isSourcePlaying() { + var source = this.source; + + return source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2; + }; + + /** + * Returns true if the underlying source is ready for playing. + * + * @private + * @return {boolean} True if ready. + */ + + + VideoBaseTexture.prototype._isSourceReady = function _isSourceReady() { + return this.source.readyState === 3 || this.source.readyState === 4; + }; + + /** + * Runs the update loop when the video is ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStart = function _onPlayStart() { + // Just in case the video has not received its can play even yet.. + if (!this.hasLoaded) { + this._onCanPlay(); + } + + if (!this._isAutoUpdating && this.autoUpdate) { + _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); + this._isAutoUpdating = true; + } + }; + + /** + * Fired when a pause event is triggered, stops the update loop + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStop = function _onPlayStop() { + if (this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } + }; + + /** + * Fired when the video is loaded and ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onCanPlay = function _onCanPlay() { + this.hasLoaded = true; + + if (this.source) { + this.source.removeEventListener('canplay', this._onCanPlay); + this.source.removeEventListener('canplaythrough', this._onCanPlay); + + this.width = this.source.videoWidth; + this.height = this.source.videoHeight; + + // prevent multiple loaded dispatches.. + if (!this.__loaded) { + this.__loaded = true; + this.emit('loaded', this); + } + + if (this._isSourcePlaying()) { + this._onPlayStart(); + } else if (this.autoPlay) { + this.source.play(); + } + } + }; + + /** + * Destroys this texture + * + */ + + + VideoBaseTexture.prototype.destroy = function destroy() { + if (this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + } + + if (this.source && this.source._pixiId) { + _BaseTexture3.default.removeFromCache(this.source._pixiId); + delete this.source._pixiId; + + this.source.pause(); + this.source.src = ''; + this.source.load(); + } + + _BaseTexture.prototype.destroy.call(this); + }; + + /** + * Mimic PixiJS BaseTexture.from.... method. + * + * @static + * @param {HTMLVideoElement} video - Video to create texture from + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromVideo = function fromVideo(video, scaleMode) { + if (!video._pixiId) { + video._pixiId = 'video_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[video._pixiId]; + + if (!baseTexture) { + baseTexture = new VideoBaseTexture(video, scaleMode); + _BaseTexture3.default.addToCache(baseTexture, video._pixiId); + } + + return baseTexture; + }; + + /** + * Helper function that creates a new BaseTexture based on the given video element. + * This BaseTexture can then be used to create a texture + * + * @static + * @param {string|object|string[]|object[]} videoSrc - The URL(s) for the video. + * @param {string} [videoSrc.src] - One of the source urls for the video + * @param {string} [videoSrc.mime] - The mimetype of the video (e.g. 'video/mp4'). If not specified + * the url's extension will be used as the second part of the mime type. + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromUrl = function fromUrl(videoSrc, scaleMode, crossorigin) { + var video = document.createElement('video'); + + video.setAttribute('webkit-playsinline', ''); + video.setAttribute('playsinline', ''); + + var url = Array.isArray(videoSrc) ? videoSrc[0].src || videoSrc[0] : videoSrc.src || videoSrc; + + if (crossorigin === undefined && url.indexOf('data:') !== 0) { + video.crossOrigin = (0, _determineCrossOrigin2.default)(url); + } else if (crossorigin) { + video.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; + } + + // array of objects or strings + if (Array.isArray(videoSrc)) { + for (var i = 0; i < videoSrc.length; ++i) { + video.appendChild(createSource(videoSrc[i].src || videoSrc[i], videoSrc[i].mime)); + } + } + // single object or string + else { + video.appendChild(createSource(url, videoSrc.mime)); + } + + video.load(); + + return VideoBaseTexture.fromVideo(video, scaleMode); + }; + + /** + * Should the base texture automatically update itself, set to true by default + * + * @member {boolean} + */ + + + _createClass(VideoBaseTexture, [{ + key: 'autoUpdate', + get: function get() { + return this._autoUpdate; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + + if (!this._autoUpdate && this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } else if (this._autoUpdate && !this._isAutoUpdating) { + _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); + this._isAutoUpdating = true; + } + } + } + }]); + + return VideoBaseTexture; +}(_BaseTexture3.default); + +exports.default = VideoBaseTexture; + + +VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; + +function createSource(path, type) { + if (!type) { + path = path.split('?').shift().toLowerCase(); + type = 'video/' + path.substr(path.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = path; + source.type = type; + + return source; +} + +},{"../const":46,"../ticker":121,"../utils":125,"../utils/determineCrossOrigin":124,"./BaseTexture":112}],119:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _const = require('../const'); + +var _TickerListener = require('./TickerListener'); + +var _TickerListener2 = _interopRequireDefault(_TickerListener); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A Ticker class that runs an update loop that other objects listen to. + * This class is composed around listeners + * meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, + * e.g. When the ticker is started and the emitter has listeners. + * + * @class + * @memberof PIXI.ticker + */ +var Ticker = function () { + /** + * + */ + function Ticker() { + var _this = this; + + _classCallCheck(this, Ticker); + + /** + * The first listener. All new listeners added are chained on this. + * @private + * @type {TickerListener} + */ + this._head = new _TickerListener2.default(null, null, Infinity); + + /** + * Internal current frame request ID + * @private + */ + this._requestId = null; + + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + * @private + */ + this._maxElapsedMS = 100; + + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.ticker.Ticker#start} automatically + * when a listener is added. + * + * @member {boolean} + * @default false + */ + this.autoStart = false; + + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS} + * and is scaled with {@link PIXI.ticker.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * + * @member {number} + * @default 1 + */ + this.deltaTime = 1; + + /** + * Time elapsed in milliseconds from last frame to this frame. + * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime} + * is based, this value is neither capped nor scaled. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * Defaults to target frame time + * + * @member {number} + * @default 16.66 + */ + this.elapsedMS = 1 / _settings2.default.TARGET_FPMS; + + /** + * The last time {@link PIXI.ticker.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default -1 + */ + this.lastTime = -1; + + /** + * Factor of current {@link PIXI.ticker.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + * + * @member {number} + * @default 1 + */ + this.speed = 1; + + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.ticker.Ticker#start} has been called. + * `false` if {@link PIXI.ticker.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.ticker.Ticker#autoStart} being `true` + * and a listener is added. + * + * @member {boolean} + * @default false + */ + this.started = false; + + /** + * Internal tick method bound to ticker instance. + * This is because in early 2015, Function.bind + * is still 60% slower in high performance scenarios. + * Also separating frame requests from update method + * so listeners may be called at any time and with + * any animation API, just invoke ticker.update(time). + * + * @private + * @param {number} time - Time since last tick. + */ + this._tick = function (time) { + _this._requestId = null; + + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._head.next) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * + * @private + */ + + + Ticker.prototype._requestIfNeeded = function _requestIfNeeded() { + if (this._requestId === null && this._head.next) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._requestId = requestAnimationFrame(this._tick); + } + }; + + /** + * Conditionally cancels a pending animation frame. + * + * @private + */ + + + Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; + + /** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * + * @private + */ + + + Ticker.prototype._startIfPossible = function _startIfPossible() { + if (this.started) { + this._requestIfNeeded(); + } else if (this.autoStart) { + this.start(); + } + }; + + /** + * Register a handler for tick events. Calls continuously unless + * it is removed or the ticker is stopped. + * + * @param {Function} fn - The listener function to be added for updates + * @param {Function} [context] - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.add = function add(fn, context) { + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _const.UPDATE_PRIORITY.NORMAL; + + return this._addListener(new _TickerListener2.default(fn, context, priority)); + }; + + /** + * Add a handler for the tick event which is only execute once. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context] - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.addOnce = function addOnce(fn, context) { + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _const.UPDATE_PRIORITY.NORMAL; + + return this._addListener(new _TickerListener2.default(fn, context, priority, true)); + }; + + /** + * Internally adds the event handler so that it can be sorted by priority. + * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run + * before the rendering. + * + * @private + * @param {TickerListener} listener - Current listener being added. + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype._addListener = function _addListener(listener) { + // For attaching to head + var current = this._head.next; + var previous = this._head; + + // Add the first item + if (!current) { + listener.connect(previous); + } else { + // Go from highest to lowest priority + while (current) { + if (listener.priority > current.priority) { + listener.connect(previous); + break; + } + previous = current; + current = current.next; + } + + // Not yet connected + if (!listener.previous) { + listener.connect(previous); + } + } + + this._startIfPossible(); + + return this; + }; + + /** + * Removes any handlers matching the function and context parameters. + * If no handlers are left after removing, then it cancels the animation frame. + * + * @param {Function} fn - The listener function to be removed + * @param {Function} [context] - The listener context to be removed + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.remove = function remove(fn, context) { + var listener = this._head.next; + + while (listener) { + // We found a match, lets remove it + // no break to delete all possible matches + // incase a listener was added 2+ times + if (listener.match(fn, context)) { + listener = listener.destroy(); + } else { + listener = listener.next; + } + } + + if (!this._head.next) { + this._cancelIfNeeded(); + } + + return this; + }; + + /** + * Starts the ticker. If the ticker has listeners + * a new animation frame is requested at this point. + */ + + + Ticker.prototype.start = function start() { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + }; + + /** + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. + */ + + + Ticker.prototype.stop = function stop() { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; + + /** + * Destroy the ticker and don't use after this. Calling + * this method removes all references to internal events. + */ + + + Ticker.prototype.destroy = function destroy() { + this.stop(); + + var listener = this._head.next; + + while (listener) { + listener = listener.destroy(true); + } + + this._head.destroy(); + this._head = null; + }; + + /** + * Triggers an update. An update entails setting the + * current {@link PIXI.ticker.Ticker#elapsedMS}, + * the current {@link PIXI.ticker.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.ticker.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + + + Ticker.prototype.update = function update() { + var currentTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : performance.now(); + + var elapsedMS = void 0; + + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + + this.deltaTime = elapsedMS * _settings2.default.TARGET_FPMS * this.speed; + + // Cache a local reference, in-case ticker is destroyed + // during the emit, we can still check for head.next + var head = this._head; + + // Invoke listeners added to internal emitter + var listener = head.next; + + while (listener) { + listener = listener.emit(this.deltaTime); + } + + if (!head.next) { + this._cancelIfNeeded(); + } + } else { + this.deltaTime = this.elapsedMS = 0; + } + + this.lastTime = currentTime; + }; + + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.ticker.Ticker#speed}, which is specific + * to scaling {@link PIXI.ticker.Ticker#deltaTime}. + * + * @member {number} + * @readonly + */ + + + _createClass(Ticker, [{ + key: 'FPS', + get: function get() { + return 1000 / this.elapsedMS; + } + + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.ticker.Ticker#update}. + * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.settings.TARGET_FPMS * 1000`. + * + * @member {number} + * @default 10 + */ + + }, { + key: 'minFPS', + get: function get() { + return 1000 / this._maxElapsedMS; + }, + set: function set(fps) // eslint-disable-line require-jsdoc + { + // Clamp: 0 to TARGET_FPMS + var minFPMS = Math.min(Math.max(0, fps) / 1000, _settings2.default.TARGET_FPMS); + + this._maxElapsedMS = 1 / minFPMS; + } + }]); + + return Ticker; +}(); + +exports.default = Ticker; + +},{"../const":46,"../settings":101,"./TickerListener":120}],120:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Internal class for handling the priority sorting of ticker handlers. + * + * @private + * @class + * @memberof PIXI.ticker + */ +var TickerListener = function () { + /** + * Constructor + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context=null] - The listener context + * @param {number} [priority=0] - The priority for emitting + * @param {boolean} [once=false] - If the handler should fire once + */ + function TickerListener(fn) { + var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var once = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + _classCallCheck(this, TickerListener); + + /** + * The handler function to execute. + * @member {Function} + */ + this.fn = fn; + + /** + * The calling to execute. + * @member {Function} + */ + this.context = context; + + /** + * The current priority. + * @member {number} + */ + this.priority = priority; + + /** + * If this should only execute once. + * @member {boolean} + */ + this.once = once; + + /** + * The next item in chain. + * @member {TickerListener} + */ + this.next = null; + + /** + * The previous item in chain. + * @member {TickerListener} + */ + this.previous = null; + + /** + * `true` if this listener has been destroyed already. + * @member {boolean} + * @private + */ + this._destroyed = false; + } + + /** + * Simple compare function to figure out if a function and context match. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} context - The listener context + * @return {boolean} `true` if the listener match the arguments + */ + + + TickerListener.prototype.match = function match(fn, context) { + context = context || null; + + return this.fn === fn && this.context === context; + }; + + /** + * Emit by calling the current function. + * @param {number} deltaTime - time since the last emit. + * @return {TickerListener} Next ticker + */ + + + TickerListener.prototype.emit = function emit(deltaTime) { + if (this.fn) { + if (this.context) { + this.fn.call(this.context, deltaTime); + } else { + this.fn(deltaTime); + } + } + + var redirect = this.next; + + if (this.once) { + this.destroy(true); + } + + // Soft-destroying should remove + // the next reference + if (this._destroyed) { + this.next = null; + } + + return redirect; + }; + + /** + * Connect to the list. + * @param {TickerListener} previous - Input node, previous listener + */ + + + TickerListener.prototype.connect = function connect(previous) { + this.previous = previous; + if (previous.next) { + previous.next.previous = this; + } + this.next = previous.next; + previous.next = this; + }; + + /** + * Destroy and don't use after this. + * @param {boolean} [hard = false] `true` to remove the `next` reference, this + * is considered a hard destroy. Soft destroy maintains the next reference. + * @return {TickerListener} The listener to redirect while emitting or removing. + */ + + + TickerListener.prototype.destroy = function destroy() { + var hard = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + this._destroyed = true; + this.fn = null; + this.context = null; + + // Disconnect, hook up next and previous + if (this.previous) { + this.previous.next = this.next; + } + + if (this.next) { + this.next.previous = this.previous; + } + + // Redirect to the next item + var redirect = this.next; + + // Remove references + this.next = hard ? null : redirect; + this.previous = null; + + return redirect; + }; + + return TickerListener; +}(); + +exports.default = TickerListener; + +},{}],121:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Ticker = exports.shared = undefined; + +var _Ticker = require('./Ticker'); + +var _Ticker2 = _interopRequireDefault(_Ticker); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The shared ticker instance used by {@link PIXI.extras.AnimatedSprite}. + * and by {@link PIXI.interaction.InteractionManager}. + * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` + * for this instance. Please follow the examples for usage, including + * how to opt-out of auto-starting the shared ticker. + * + * @example + * let ticker = PIXI.ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(800, 600); + * let stage = new PIXI.Container(); + * let interactionManager = PIXI.interaction.InteractionManager(renderer); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * + * @type {PIXI.ticker.Ticker} + * @memberof PIXI.ticker + */ +var shared = new _Ticker2.default(); + +shared.autoStart = true; +shared.destroy = function () { + // protect destroying shared ticker + // this is used by other internal systems + // like AnimatedSprite and InteractionManager +}; + +/** + * This namespace contains an API for interacting with PIXI's internal global update loop. + * + * This ticker is used for rendering, {@link PIXI.extras.AnimatedSprite AnimatedSprite}, + * {@link PIXI.interaction.InteractionManager InteractionManager} and many other time-based PIXI systems. + * @example + * const ticker = new PIXI.ticker.Ticker(); + * ticker.stop(); + * ticker.add((deltaTime) => { + * // do something every frame + * }); + * ticker.start(); + * @namespace PIXI.ticker + */ +exports.shared = shared; +exports.Ticker = _Ticker2.default; + +},{"./Ticker":119}],122:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = canUploadSameBuffer; +function canUploadSameBuffer() { + // Uploading the same buffer multiple times in a single frame can cause perf issues. + // Apparent on IOS so only check for that at the moment + // this check may become more complex if this issue pops up elsewhere. + var ios = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform); + + return !ios; +} + +},{}],123:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = createIndicesForQuads; +/** + * Generic Mask Stack data structure + * + * @memberof PIXI + * @function createIndicesForQuads + * @private + * @param {number} size - Number of quads + * @return {Uint16Array} indices + */ +function createIndicesForQuads(size) { + // the total number of indices in our array, there are 6 points per quad. + + var totalIndices = size * 6; + + var indices = new Uint16Array(totalIndices); + + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + indices[i + 0] = j + 0; + indices[i + 1] = j + 1; + indices[i + 2] = j + 2; + indices[i + 3] = j + 0; + indices[i + 4] = j + 2; + indices[i + 5] = j + 3; + } + + return indices; +} + +},{}],124:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = determineCrossOrigin; + +var _url2 = require('url'); + +var _url3 = _interopRequireDefault(_url2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var tempAnchor = void 0; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +function determineCrossOrigin(url) { + var loc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location; + + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url3.default.parse(tempAnchor.href); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +} + +},{"url":38}],125:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.premultiplyBlendMode = exports.BaseTextureCache = exports.TextureCache = exports.earcut = exports.mixins = exports.pluginTarget = exports.EventEmitter = exports.removeItems = exports.isMobile = undefined; +exports.uid = uid; +exports.hex2rgb = hex2rgb; +exports.hex2string = hex2string; +exports.rgb2hex = rgb2hex; +exports.getResolutionOfUrl = getResolutionOfUrl; +exports.decomposeDataUri = decomposeDataUri; +exports.getUrlFileExtension = getUrlFileExtension; +exports.getSvgSize = getSvgSize; +exports.skipHello = skipHello; +exports.sayHello = sayHello; +exports.isWebGLSupported = isWebGLSupported; +exports.sign = sign; +exports.destroyTextureCache = destroyTextureCache; +exports.clearTextureCache = clearTextureCache; +exports.correctBlendMode = correctBlendMode; +exports.premultiplyTint = premultiplyTint; +exports.premultiplyRgba = premultiplyRgba; +exports.premultiplyTintToRgba = premultiplyTintToRgba; + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _pluginTarget = require('./pluginTarget'); + +var _pluginTarget2 = _interopRequireDefault(_pluginTarget); + +var _mixin = require('./mixin'); + +var mixins = _interopRequireWildcard(_mixin); + +var _ismobilejs = require('ismobilejs'); + +var isMobile = _interopRequireWildcard(_ismobilejs); + +var _removeArrayItems = require('remove-array-items'); + +var _removeArrayItems2 = _interopRequireDefault(_removeArrayItems); + +var _mapPremultipliedBlendModes = require('./mapPremultipliedBlendModes'); + +var _mapPremultipliedBlendModes2 = _interopRequireDefault(_mapPremultipliedBlendModes); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var nextUid = 0; +var saidHello = false; + +/** + * Generalized convenience utilities for PIXI. + * @example + * // Extend PIXI's internal Event Emitter. + * class MyEmitter extends PIXI.utils.EventEmitter { + * constructor() { + * super(); + * console.log("Emitter created!"); + * } + * } + * + * // Get info on current device + * console.log(PIXI.utils.isMobile); + * + * // Convert hex color to string + * console.log(PIXI.utils.hex2string(0xff00ff)); // returns: "#ff00ff" + * @namespace PIXI.utils + */ +exports.isMobile = isMobile; +exports.removeItems = _removeArrayItems2.default; +exports.EventEmitter = _eventemitter2.default; +exports.pluginTarget = _pluginTarget2.default; +exports.mixins = mixins; +exports.earcut = _earcut2.default; + +/** + * Gets the next unique identifier + * + * @memberof PIXI.utils + * @function uid + * @return {number} The next unique identifier to use. + */ + +function uid() { + return ++nextUid; +} + +/** + * Converts a hex color number to an [R, G, B] array + * + * @memberof PIXI.utils + * @function hex2rgb + * @param {number} hex - The number to convert + * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one + * @return {number[]} An array representing the [R, G, B] of the color. + */ +function hex2rgb(hex, out) { + out = out || []; + + out[0] = (hex >> 16 & 0xFF) / 255; + out[1] = (hex >> 8 & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + + return out; +} + +/** + * Converts a hex color number to a string. + * + * @memberof PIXI.utils + * @function hex2string + * @param {number} hex - Number in hex + * @return {string} The string color. + */ +function hex2string(hex) { + hex = hex.toString(16); + hex = '000000'.substr(0, 6 - hex.length) + hex; + + return '#' + hex; +} + +/** + * Converts a color as an [R, G, B] array to a hex number + * + * @memberof PIXI.utils + * @function rgb2hex + * @param {number[]} rgb - rgb array + * @return {number} The color number + */ +function rgb2hex(rgb) { + return (rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + (rgb[2] * 255 | 0); +} + +/** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * + * @memberof PIXI.utils + * @function getResolutionOfUrl + * @param {string} url - the image path + * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. + * @return {number} resolution / device pixel ratio of an asset + */ +function getResolutionOfUrl(url, defaultValue) { + var resolution = _settings2.default.RETINA_PREFIX.exec(url); + + if (resolution) { + return parseFloat(resolution[1]); + } + + return defaultValue !== undefined ? defaultValue : 1; +} + +/** + * Typedef for decomposeDataUri return object. + * + * @typedef {object} PIXI.utils~DecomposedDataUri + * @property {mediaType} Media type, eg. `image` + * @property {subType} Sub type, eg. `png` + * @property {encoding} Data encoding, eg. `base64` + * @property {data} The actual data + */ + +/** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. + * + * @memberof PIXI.utils + * @function decomposeDataUri + * @param {string} dataUri - the data URI to check + * @return {PIXI.utils~DecomposedDataUri|undefined} The decomposed data uri or undefined + */ +function decomposeDataUri(dataUri) { + var dataUriMatch = _const.DATA_URI.exec(dataUri); + + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : undefined, + data: dataUriMatch[5] + }; + } + + return undefined; +} + +/** + * Get type of the image by regexp for extension. Returns undefined for unknown extensions. + * + * @memberof PIXI.utils + * @function getUrlFileExtension + * @param {string} url - the image path + * @return {string|undefined} image extension + */ +function getUrlFileExtension(url) { + var extension = _const.URL_FILE_EXTENSION.exec(url); + + if (extension) { + return extension[1].toLowerCase(); + } + + return undefined; +} + +/** + * Typedef for Size object. + * + * @typedef {object} PIXI.utils~Size + * @property {width} Width component + * @property {height} Height component + */ + +/** + * Get size from an svg string using regexp. + * + * @memberof PIXI.utils + * @function getSvgSize + * @param {string} svgString - a serialized svg element + * @return {PIXI.utils~Size|undefined} image extension + */ +function getSvgSize(svgString) { + var sizeMatch = _const.SVG_SIZE.exec(svgString); + var size = {}; + + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); + size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); + } + + return size; +} + +/** + * Skips the hello message of renderers that are created after this is run. + * + * @function skipHello + * @memberof PIXI.utils + */ +function skipHello() { + saidHello = true; +} + +/** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever makes you a jerk face. + * + * @static + * @function sayHello + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ +function sayHello(type) { + if (saidHello) { + return; + } + + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = ['\n %c %c %c PixiJS ' + _const.VERSION + ' - \u2730 ' + type + ' \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n', 'background: #ff66a5; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff66a5; background: #030307; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'background: #ffc3dc; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;']; + + window.console.log.apply(console, args); + } else if (window.console) { + window.console.log('PixiJS ' + _const.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); + } + + saidHello = true; +} + +/** + * Helper for checking for webgl support + * + * @memberof PIXI.utils + * @function isWebGLSupported + * @return {boolean} is webgl supported + */ +function isWebGLSupported() { + var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; + + try { + if (!window.WebGLRenderingContext) { + return false; + } + + var canvas = document.createElement('canvas'); + var gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); + + var success = !!(gl && gl.getContextAttributes().stencil); + + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + + if (loseContext) { + loseContext.loseContext(); + } + } + + gl = null; + + return success; + } catch (e) { + return false; + } +} + +/** + * Returns sign of number + * + * @memberof PIXI.utils + * @function sign + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ +function sign(n) { + if (n === 0) return 0; + + return n < 0 ? -1 : 1; +} + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var TextureCache = exports.TextureCache = Object.create(null); + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var BaseTextureCache = exports.BaseTextureCache = Object.create(null); + +/** + * Destroys all texture in the cache + * + * @memberof PIXI.utils + * @function destroyTextureCache + */ +function destroyTextureCache() { + var key = void 0; + + for (key in TextureCache) { + TextureCache[key].destroy(); + } + for (key in BaseTextureCache) { + BaseTextureCache[key].destroy(); + } +} + +/** + * Removes all textures from cache, but does not destroy them + * + * @memberof PIXI.utils + * @function clearTextureCache + */ +function clearTextureCache() { + var key = void 0; + + for (key in TextureCache) { + delete TextureCache[key]; + } + for (key in BaseTextureCache) { + delete BaseTextureCache[key]; + } +} + +/** + * maps premultiply flag and blendMode to adjusted blendMode + * @memberof PIXI.utils + * @const premultiplyBlendMode + * @type {Array} + */ +var premultiplyBlendMode = exports.premultiplyBlendMode = (0, _mapPremultipliedBlendModes2.default)(); + +/** + * changes blendMode according to texture format + * + * @memberof PIXI.utils + * @function correctBlendMode + * @param {number} blendMode supposed blend mode + * @param {boolean} premultiplied whether source is premultiplied + * @returns {number} true blend mode for this texture + */ +function correctBlendMode(blendMode, premultiplied) { + return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; +} + +/** + * premultiplies tint + * + * @memberof PIXI.utils + * @param {number} tint integet RGB + * @param {number} alpha floating point alpha (0.0-1.0) + * @returns {number} tint multiplied by alpha + */ +function premultiplyTint(tint, alpha) { + if (alpha === 1.0) { + return (alpha * 255 << 24) + tint; + } + if (alpha === 0.0) { + return 0; + } + var R = tint >> 16 & 0xFF; + var G = tint >> 8 & 0xFF; + var B = tint & 0xFF; + + R = R * alpha + 0.5 | 0; + G = G * alpha + 0.5 | 0; + B = B * alpha + 0.5 | 0; + + return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; +} + +/** + * combines rgb and alpha to out array + * + * @memberof PIXI.utils + * @param {Float32Array|number[]} rgb input rgb + * @param {number} alpha alpha param + * @param {Float32Array} [out] output + * @param {boolean} [premultiply=true] do premultiply it + * @returns {Float32Array} vec4 rgba + */ +function premultiplyRgba(rgb, alpha, out, premultiply) { + out = out || new Float32Array(4); + if (premultiply || premultiply === undefined) { + out[0] = rgb[0] * alpha; + out[1] = rgb[1] * alpha; + out[2] = rgb[2] * alpha; + } else { + out[0] = rgb[0]; + out[1] = rgb[1]; + out[2] = rgb[2]; + } + out[3] = alpha; + + return out; +} + +/** + * converts integer tint and float alpha to vec4 form, premultiplies by default + * + * @memberof PIXI.utils + * @param {number} tint input tint + * @param {number} alpha alpha param + * @param {Float32Array} [out] output + * @param {boolean} [premultiply=true] do premultiply it + * @returns {Float32Array} vec4 rgba + */ +function premultiplyTintToRgba(tint, alpha, out, premultiply) { + out = out || new Float32Array(4); + out[0] = (tint >> 16 & 0xFF) / 255.0; + out[1] = (tint >> 8 & 0xFF) / 255.0; + out[2] = (tint & 0xFF) / 255.0; + if (premultiply || premultiply === undefined) { + out[0] *= alpha; + out[1] *= alpha; + out[2] *= alpha; + } + out[3] = alpha; + + return out; +} + +},{"../const":46,"../settings":101,"./mapPremultipliedBlendModes":126,"./mixin":128,"./pluginTarget":129,"earcut":2,"eventemitter3":3,"ismobilejs":4,"remove-array-items":31}],126:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapPremultipliedBlendModes; + +var _const = require('../const'); + +/** + * Corrects PixiJS blend, takes premultiplied alpha into account + * + * @memberof PIXI + * @function mapPremultipliedBlendModes + * @private + * @param {Array} [array] - The array to output into. + * @return {Array} Mapped modes. + */ + +function mapPremultipliedBlendModes() { + var pm = []; + var npm = []; + + for (var i = 0; i < 32; i++) { + pm[i] = i; + npm[i] = i; + } + + pm[_const.BLEND_MODES.NORMAL_NPM] = _const.BLEND_MODES.NORMAL; + pm[_const.BLEND_MODES.ADD_NPM] = _const.BLEND_MODES.ADD; + pm[_const.BLEND_MODES.SCREEN_NPM] = _const.BLEND_MODES.SCREEN; + + npm[_const.BLEND_MODES.NORMAL] = _const.BLEND_MODES.NORMAL_NPM; + npm[_const.BLEND_MODES.ADD] = _const.BLEND_MODES.ADD_NPM; + npm[_const.BLEND_MODES.SCREEN] = _const.BLEND_MODES.SCREEN_NPM; + + var array = []; + + array.push(npm); + array.push(pm); + + return array; +} + +},{"../const":46}],127:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = maxRecommendedTextures; + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function maxRecommendedTextures(max) { + if (_ismobilejs2.default.tablet || _ismobilejs2.default.phone) { + // check if the res is iphone 6 or higher.. + return 4; + } + + // desktop should be ok + return max; +} + +},{"ismobilejs":4}],128:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.mixin = mixin; +exports.delayMixin = delayMixin; +exports.performMixins = performMixins; +/** + * Mixes all enumerable properties and methods from a source object to a target object. + * + * @memberof PIXI.utils.mixins + * @function mixin + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function mixin(target, source) { + if (!target || !source) return; + // in ES8/ES2017, this would be really easy: + // Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + + // get all the enumerable property keys + var keys = Object.keys(source); + + // loop through properties + for (var i = 0; i < keys.length; ++i) { + var propertyName = keys[i]; + + // Set the property using the property descriptor - this works for accessors and normal value properties + Object.defineProperty(target, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); + } +} + +var mixins = []; + +/** + * Queues a mixin to be handled towards the end of the initialization of PIXI, so that deprecation + * can take effect. + * + * @memberof PIXI.utils.mixins + * @function delayMixin + * @private + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function delayMixin(target, source) { + mixins.push(target, source); +} + +/** + * Handles all mixins queued via delayMixin(). + * + * @memberof PIXI.utils.mixins + * @function performMixins + * @private + */ +function performMixins() { + for (var i = 0; i < mixins.length; i += 2) { + mixin(mixins[i], mixins[i + 1]); + } + mixins.length = 0; +} + +},{}],129:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Mixins functionality to make an object have "plugins". + * + * @example + * function MyObject() {} + * + * pluginTarget.mixin(MyObject); + * + * @mixin + * @memberof PIXI.utils + * @param {object} obj - The object to mix into. + */ +function pluginTarget(obj) { + obj.__plugins = {}; + + /** + * Adds a plugin to an object + * + * @param {string} pluginName - The events that should be listed. + * @param {Function} ctor - The constructor function for the plugin. + */ + obj.registerPlugin = function registerPlugin(pluginName, ctor) { + obj.__plugins[pluginName] = ctor; + }; + + /** + * Instantiates all the plugins of this object + * + */ + obj.prototype.initPlugins = function initPlugins() { + this.plugins = this.plugins || {}; + + for (var o in obj.__plugins) { + this.plugins[o] = new obj.__plugins[o](this); + } + }; + + /** + * Removes all the plugins of this object + * + */ + obj.prototype.destroyPlugins = function destroyPlugins() { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + + this.plugins = null; + }; +} + +exports.default = { + /** + * Mixes in the properties of the pluginTarget into another object + * + * @param {object} obj - The obj to mix into + */ + mixin: function mixin(obj) { + pluginTarget(obj); + } +}; + +},{}],130:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = trimCanvas; +/** + * Trim transparent borders from a canvas + * + * @memberof PIXI + * @function trimCanvas + * @private + * @param {HTMLCanvasElement} canvas - the canvas to trim + * @returns {object} Trim data + */ +function trimCanvas(canvas) { + // https://gist.github.com/remy/784508 + + var width = canvas.width; + var height = canvas.height; + + var context = canvas.getContext('2d'); + var imageData = context.getImageData(0, 0, width, height); + var pixels = imageData.data; + var len = pixels.length; + + var bound = { + top: null, + left: null, + right: null, + bottom: null + }; + var data = null; + var i = void 0; + var x = void 0; + var y = void 0; + + for (i = 0; i < len; i += 4) { + if (pixels[i + 3] !== 0) { + x = i / 4 % width; + y = ~~(i / 4 / width); + + if (bound.top === null) { + bound.top = y; + } + + if (bound.left === null) { + bound.left = x; + } else if (x < bound.left) { + bound.left = x; + } + + if (bound.right === null) { + bound.right = x + 1; + } else if (bound.right < x) { + bound.right = x + 1; + } + + if (bound.bottom === null) { + bound.bottom = y; + } else if (bound.bottom < y) { + bound.bottom = y; + } + } + } + + if (bound.top !== null) { + width = bound.right - bound.left; + height = bound.bottom - bound.top + 1; + data = context.getImageData(bound.left, bound.top, width, height); + } + + return { + height: height, + width: width, + data: data + }; +} + +},{}],131:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = deprecation; +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code + +// A map of warning messages already fired +var warnings = {}; + +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code +function warn(msg) { + // Ignore duplicat + if (warnings[msg]) { + return; + } + + /* eslint-disable no-console */ + var stack = new Error().stack; + + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('Deprecation Warning: ', msg); + } else { + // chop off the stack trace which includes pixi.js internal calls + stack = stack.split('\n').splice(3).join('\n'); + + if (console.groupCollapsed) { + console.groupCollapsed('%cDeprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', msg); + console.warn(stack); + console.groupEnd(); + } else { + console.warn('Deprecation Warning: ', msg); + console.warn(stack); + } + } + /* eslint-enable no-console */ + + warnings[msg] = true; +} + +function deprecation(core) { + var mesh = core.mesh, + particles = core.particles, + extras = core.extras, + filters = core.filters, + prepare = core.prepare, + loaders = core.loaders, + interaction = core.interaction; + + + Object.defineProperties(core, { + + /** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ + SpriteBatch: { + get: function get() { + throw new ReferenceError('SpriteBatch does not exist any more, ' + 'please use the new ParticleContainer instead.'); + } + }, + + /** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in PixiJS v3, + * please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ + AssetLoader: { + get: function get() { + throw new ReferenceError('The loader system was overhauled in PixiJS v3, ' + 'please see the new PIXI.loaders.Loader class.'); + } + }, + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + Stage: { + get: function get() { + warn('You do not need to use a PIXI Stage any more, you can simply render any container.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + DisplayObjectContainer: { + get: function get() { + warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + Strip: { + get: function get() { + warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.'); + + return mesh.Mesh; + } + }, + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + Rope: { + get: function get() { + warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.'); + + return mesh.Rope; + } + }, + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + ParticleContainer: { + get: function get() { + warn('The ParticleContainer class has been moved to particles.ParticleContainer, ' + 'please use particles.ParticleContainer from now on.'); + + return particles.ParticleContainer; + } + }, + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + MovieClip: { + get: function get() { + warn('The MovieClip class has been moved to extras.AnimatedSprite, please use extras.AnimatedSprite.'); + + return extras.AnimatedSprite; + } + }, + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + TilingSprite: { + get: function get() { + warn('The TilingSprite class has been moved to extras.TilingSprite, ' + 'please use extras.TilingSprite from now on.'); + + return extras.TilingSprite; + } + }, + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + BitmapText: { + get: function get() { + warn('The BitmapText class has been moved to extras.BitmapText, ' + 'please use extras.BitmapText from now on.'); + + return extras.BitmapText; + } + }, + + /** + * @class + * @private + * @name blendModes + * @memberof PIXI + * @see PIXI.BLEND_MODES + * @deprecated since version 3.0.0 + */ + blendModes: { + get: function get() { + warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.'); + + return core.BLEND_MODES; + } + }, + + /** + * @class + * @private + * @name scaleModes + * @memberof PIXI + * @see PIXI.SCALE_MODES + * @deprecated since version 3.0.0 + */ + scaleModes: { + get: function get() { + warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.'); + + return core.SCALE_MODES; + } + }, + + /** + * @class + * @private + * @name BaseTextureCache + * @memberof PIXI + * @see PIXI.utils.BaseTextureCache + * @deprecated since version 3.0.0 + */ + BaseTextureCache: { + get: function get() { + warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, ' + 'please use utils.BaseTextureCache from now on.'); + + return core.utils.BaseTextureCache; + } + }, + + /** + * @class + * @private + * @name TextureCache + * @memberof PIXI + * @see PIXI.utils.TextureCache + * @deprecated since version 3.0.0 + */ + TextureCache: { + get: function get() { + warn('The TextureCache class has been moved to utils.TextureCache, ' + 'please use utils.TextureCache from now on.'); + + return core.utils.TextureCache; + } + }, + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + math: { + get: function get() { + warn('The math namespace is deprecated, please access members already accessible on PIXI.'); + + return core; + } + }, + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.Filter; + } + }, + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + TransformManual: { + get: function get() { + warn('TransformManual has been renamed to TransformBase, please update your pixi-spine'); + + return core.TransformBase; + } + }, + + /** + * @static + * @constant + * @name PIXI.TARGET_FPMS + * @see PIXI.settings.TARGET_FPMS + * @deprecated since version 4.2.0 + */ + TARGET_FPMS: { + get: function get() { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + return core.settings.TARGET_FPMS; + }, + set: function set(value) { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + core.settings.TARGET_FPMS = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.FILTER_RESOLUTION + * @see PIXI.settings.FILTER_RESOLUTION + * @deprecated since version 4.2.0 + */ + FILTER_RESOLUTION: { + get: function get() { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + return core.settings.FILTER_RESOLUTION; + }, + set: function set(value) { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + core.settings.FILTER_RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RESOLUTION + * @see PIXI.settings.RESOLUTION + * @deprecated since version 4.2.0 + */ + RESOLUTION: { + get: function get() { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + return core.settings.RESOLUTION; + }, + set: function set(value) { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + core.settings.RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.MIPMAP_TEXTURES + * @see PIXI.settings.MIPMAP_TEXTURES + * @deprecated since version 4.2.0 + */ + MIPMAP_TEXTURES: { + get: function get() { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + return core.settings.MIPMAP_TEXTURES; + }, + set: function set(value) { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + core.settings.MIPMAP_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_BATCH_SIZE + * @see PIXI.settings.SPRITE_BATCH_SIZE + * @deprecated since version 4.2.0 + */ + SPRITE_BATCH_SIZE: { + get: function get() { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + return core.settings.SPRITE_BATCH_SIZE; + }, + set: function set(value) { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + core.settings.SPRITE_BATCH_SIZE = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_MAX_TEXTURES + * @see PIXI.settings.SPRITE_MAX_TEXTURES + * @deprecated since version 4.2.0 + */ + SPRITE_MAX_TEXTURES: { + get: function get() { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + return core.settings.SPRITE_MAX_TEXTURES; + }, + set: function set(value) { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + core.settings.SPRITE_MAX_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RETINA_PREFIX + * @see PIXI.settings.RETINA_PREFIX + * @deprecated since version 4.2.0 + */ + RETINA_PREFIX: { + get: function get() { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + return core.settings.RETINA_PREFIX; + }, + set: function set(value) { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + core.settings.RETINA_PREFIX = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.DEFAULT_RENDER_OPTIONS + * @see PIXI.settings.RENDER_OPTIONS + * @deprecated since version 4.2.0 + */ + DEFAULT_RENDER_OPTIONS: { + get: function get() { + warn('PIXI.DEFAULT_RENDER_OPTIONS has been deprecated, please use PIXI.settings.DEFAULT_RENDER_OPTIONS'); + + return core.settings.RENDER_OPTIONS; + } + } + }); + + // Move the default properties to settings + var defaults = [{ parent: 'TRANSFORM_MODE', target: 'TRANSFORM_MODE' }, { parent: 'GC_MODES', target: 'GC_MODE' }, { parent: 'WRAP_MODES', target: 'WRAP_MODE' }, { parent: 'SCALE_MODES', target: 'SCALE_MODE' }, { parent: 'PRECISION', target: 'PRECISION_FRAGMENT' }]; + + var _loop = function _loop(i) { + var deprecation = defaults[i]; + + Object.defineProperty(core[deprecation.parent], 'DEFAULT', { + get: function get() { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); + + return core.settings[deprecation.target]; + }, + set: function set(value) { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); + + core.settings[deprecation.target] = value; + } + }); + }; + + for (var i = 0; i < defaults.length; i++) { + _loop(i); + } + + Object.defineProperties(core.settings, { + + /** + * @static + * @name PRECISION + * @memberof PIXI.settings + * @see PIXI.PRECISION + * @deprecated since version 4.4.0 + */ + PRECISION: { + get: function get() { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + return core.settings.PRECISION_FRAGMENT; + }, + set: function set(value) { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + core.settings.PRECISION_FRAGMENT = value; + } + } + }); + + if (extras.AnimatedSprite) { + Object.defineProperties(extras, { + + /** + * @class + * @name MovieClip + * @memberof PIXI.extras + * @see PIXI.extras.AnimatedSprite + * @deprecated since version 4.2.0 + */ + MovieClip: { + get: function get() { + warn('The MovieClip class has been renamed to AnimatedSprite, please use AnimatedSprite from now on.'); + + return extras.AnimatedSprite; + } + } + }); + } + + if (extras) { + Object.defineProperties(extras, { + /** + * @class + * @name TextureTransform + * @memberof PIXI.extras + * @see PIXI.TextureMatrix + * @deprecated since version 4.6.0 + */ + TextureTransform: { + get: function get() { + warn('The TextureTransform class has been renamed to TextureMatrix, ' + 'please use PIXI.TextureMatrix from now on.'); + + return core.TextureMatrix; + } + } + }); + } + + core.DisplayObject.prototype.generateTexture = function generateTexture(renderer, scaleMode, resolution) { + warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); + + return renderer.generateTexture(this, scaleMode, resolution); + }; + + core.Graphics.prototype.generateTexture = function generateTexture(scaleMode, resolution) { + warn('graphics generate texture has moved to the renderer. ' + 'Or to render a graphics to a texture using canvas please use generateCanvasTexture'); + + return this.generateCanvasTexture(scaleMode, resolution); + }; + + /** + * @method + * @name PIXI.GroupD8.isSwapWidthHeight + * @see PIXI.GroupD8.isVertical + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the direction is vertical + * @deprecated since version 4.6.0 + */ + core.GroupD8.isSwapWidthHeight = function isSwapWidthHeight(rotation) { + warn('GroupD8.isSwapWidthHeight was renamed to GroupD8.isVertical'); + + return core.GroupD8.isVertical(rotation); + }; + + core.RenderTexture.prototype.render = function render(displayObject, matrix, clear, updateTransform) { + this.legacyRenderer.render(displayObject, this, clear, matrix, !updateTransform); + warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)'); + }; + + core.RenderTexture.prototype.getImage = function getImage(target) { + warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); + + return this.legacyRenderer.extract.image(target); + }; + + core.RenderTexture.prototype.getBase64 = function getBase64(target) { + warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); + + return this.legacyRenderer.extract.base64(target); + }; + + core.RenderTexture.prototype.getCanvas = function getCanvas(target) { + warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); + + return this.legacyRenderer.extract.canvas(target); + }; + + core.RenderTexture.prototype.getPixels = function getPixels(target) { + warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); + + return this.legacyRenderer.pixels(target); + }; + + /** + * @method + * @private + * @name PIXI.Sprite#setTexture + * @see PIXI.Sprite#texture + * @deprecated since version 3.0.0 + * @param {PIXI.Texture} texture - The texture to set to. + */ + core.Sprite.prototype.setTexture = function setTexture(texture) { + this.texture = texture; + warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;'); + }; + + if (extras.BitmapText) { + /** + * @method + * @name PIXI.extras.BitmapText#setText + * @see PIXI.extras.BitmapText#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ + extras.BitmapText.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';'); + }; + } + + /** + * @method + * @name PIXI.Text#setText + * @see PIXI.Text#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ + core.Text.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';'); + }; + + /** + * Calculates the ascent, descent and fontSize of a given fontStyle + * + * @name PIXI.Text.calculateFontProperties + * @see PIXI.TextMetrics.measureFont + * @deprecated since version 4.5.0 + * @param {string} font - String representing the style of the font + * @return {Object} Font properties object + */ + core.Text.calculateFontProperties = function calculateFontProperties(font) { + warn('Text.calculateFontProperties is now deprecated, please use the TextMetrics.measureFont'); + + return core.TextMetrics.measureFont(font); + }; + + Object.defineProperties(core.Text, { + fontPropertiesCache: { + get: function get() { + warn('Text.fontPropertiesCache is deprecated'); + + return core.TextMetrics._fonts; + } + }, + fontPropertiesCanvas: { + get: function get() { + warn('Text.fontPropertiesCanvas is deprecated'); + + return core.TextMetrics._canvas; + } + }, + fontPropertiesContext: { + get: function get() { + warn('Text.fontPropertiesContext is deprecated'); + + return core.TextMetrics._context; + } + } + }); + + /** + * @method + * @name PIXI.Text#setStyle + * @see PIXI.Text#style + * @deprecated since version 3.0.0 + * @param {*} style - The style to set to. + */ + core.Text.prototype.setStyle = function setStyle(style) { + this.style = style; + warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;'); + }; + + /** + * @method + * @name PIXI.Text#determineFontProperties + * @see PIXI.Text#measureFontProperties + * @deprecated since version 4.2.0 + * @private + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ + core.Text.prototype.determineFontProperties = function determineFontProperties(fontStyle) { + warn('determineFontProperties is now deprecated, please use TextMetrics.measureFont method'); + + return core.TextMetrics.measureFont(fontStyle); + }; + + /** + * @method + * @name PIXI.Text.getFontStyle + * @see PIXI.TextMetrics.getFontStyle + * @deprecated since version 4.5.0 + * @param {PIXI.TextStyle} style - The style to use. + * @return {string} Font string + */ + core.Text.getFontStyle = function getFontStyle(style) { + warn('getFontStyle is now deprecated, please use TextStyle.toFontString() instead'); + + style = style || {}; + + if (!(style instanceof core.TextStyle)) { + style = new core.TextStyle(style); + } + + return style.toFontString(); + }; + + Object.defineProperties(core.TextStyle.prototype, { + /** + * Set all properties of a font as a single string + * + * @name PIXI.TextStyle#font + * @deprecated since version 4.0.0 + */ + font: { + get: function get() { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\', \'fontSize\', \'fontStyle\', \'fontVariant\' and \'fontWeight\' properties from now on'); + + var fontSizeString = typeof this._fontSize === 'number' ? this._fontSize + 'px' : this._fontSize; + + return this._fontStyle + ' ' + this._fontVariant + ' ' + this._fontWeight + ' ' + fontSizeString + ' ' + this._fontFamily; + }, + set: function set(font) { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + + // can work out fontStyle from search of whole string + if (font.indexOf('italic') > 1) { + this._fontStyle = 'italic'; + } else if (font.indexOf('oblique') > -1) { + this._fontStyle = 'oblique'; + } else { + this._fontStyle = 'normal'; + } + + // can work out fontVariant from search of whole string + if (font.indexOf('small-caps') > -1) { + this._fontVariant = 'small-caps'; + } else { + this._fontVariant = 'normal'; + } + + // fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units + var splits = font.split(' '); + var fontSizeIndex = -1; + + this._fontSize = 26; + for (var i = 0; i < splits.length; ++i) { + if (splits[i].match(/(px|pt|em|%)/)) { + fontSizeIndex = i; + this._fontSize = splits[i]; + break; + } + } + + // we can now search for fontWeight as we know it must occur before the fontSize + this._fontWeight = 'normal'; + for (var _i = 0; _i < fontSizeIndex; ++_i) { + if (splits[_i].match(/(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/)) { + this._fontWeight = splits[_i]; + break; + } + } + + // and finally join everything together after the fontSize in case the font family has multiple words + if (fontSizeIndex > -1 && fontSizeIndex < splits.length - 1) { + this._fontFamily = ''; + for (var _i2 = fontSizeIndex + 1; _i2 < splits.length; ++_i2) { + this._fontFamily += splits[_i2] + ' '; + } + + this._fontFamily = this._fontFamily.slice(0, -1); + } else { + this._fontFamily = 'Arial'; + } + + this.styleID++; + } + } + }); + + /** + * @method + * @name PIXI.Texture#setFrame + * @see PIXI.Texture#setFrame + * @deprecated since version 3.0.0 + * @param {PIXI.Rectangle} frame - The frame to set. + */ + core.Texture.prototype.setFrame = function setFrame(frame) { + this.frame = frame; + warn('setFrame is now deprecated, please use the frame property, e.g: myTexture.frame = frame;'); + }; + + /** + * @static + * @function + * @name PIXI.Texture.addTextureToCache + * @see PIXI.Texture.addToCache + * @deprecated since 4.5.0 + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the texture will be stored against. + */ + core.Texture.addTextureToCache = function addTextureToCache(texture, id) { + core.Texture.addToCache(texture, id); + warn('Texture.addTextureToCache is deprecated, please use Texture.addToCache from now on.'); + }; + + /** + * @static + * @function + * @name PIXI.Texture.removeTextureFromCache + * @see PIXI.Texture.removeFromCache + * @deprecated since 4.5.0 + * @param {string} id - The id of the texture to be removed + * @return {PIXI.Texture|null} The texture that was removed + */ + core.Texture.removeTextureFromCache = function removeTextureFromCache(id) { + warn('Texture.removeTextureFromCache is deprecated, please use Texture.removeFromCache from now on. ' + 'Be aware that Texture.removeFromCache does not automatically its BaseTexture from the BaseTextureCache. ' + 'For that, use BaseTexture.removeFromCache'); + + core.BaseTexture.removeFromCache(id); + + return core.Texture.removeFromCache(id); + }; + + Object.defineProperties(filters, { + + /** + * @class + * @private + * @name PIXI.filters.AbstractFilter + * @see PIXI.AbstractFilter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.AbstractFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.SpriteMaskFilter + * @see PIXI.SpriteMaskFilter + * @deprecated since version 3.0.6 + */ + SpriteMaskFilter: { + get: function get() { + warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.'); + + return core.SpriteMaskFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.VoidFilter + * @see PIXI.filters.AlphaFilter + * @deprecated since version 4.5.7 + */ + VoidFilter: { + get: function get() { + warn('VoidFilter has been renamed to AlphaFilter, please use PIXI.filters.AlphaFilter'); + + return filters.AlphaFilter; + } + } + }); + + /** + * @method + * @name PIXI.utils.uuid + * @see PIXI.utils.uid + * @deprecated since version 3.0.6 + * @return {number} The uid + */ + core.utils.uuid = function () { + warn('utils.uuid() is deprecated, please use utils.uid() from now on.'); + + return core.utils.uid(); + }; + + /** + * @method + * @name PIXI.utils.canUseNewCanvasBlendModes + * @see PIXI.CanvasTinter + * @deprecated + * @return {boolean} Can use blend modes. + */ + core.utils.canUseNewCanvasBlendModes = function () { + warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on'); + + return core.CanvasTinter.canUseMultiply; + }; + + var saidHello = true; + + /** + * @name PIXI.utils._saidHello + * @type {boolean} + * @see PIXI.utils.skipHello + * @deprecated since 4.1.0 + */ + Object.defineProperty(core.utils, '_saidHello', { + set: function set(bool) { + if (bool) { + warn('PIXI.utils._saidHello is deprecated, please use PIXI.utils.skipHello()'); + this.skipHello(); + } + saidHello = bool; + }, + get: function get() { + return saidHello; + } + }); + + if (prepare.BasePrepare) { + /** + * @method + * @name PIXI.prepare.BasePrepare#register + * @see PIXI.prepare.BasePrepare#registerFindHook + * @deprecated since version 4.4.2 + * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + prepare.BasePrepare.prototype.register = function register(addHook, uploadHook) { + warn('renderer.plugins.prepare.register is now deprecated, ' + 'please use renderer.plugins.prepare.registerFindHook & renderer.plugins.prepare.registerUploadHook'); + + if (addHook) { + this.registerFindHook(addHook); + } + + if (uploadHook) { + this.registerUploadHook(uploadHook); + } + + return this; + }; + } + + if (prepare.canvas) { + /** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.canvas.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ + Object.defineProperty(prepare.canvas, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } + }); + } + + if (prepare.webgl) { + /** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.webgl.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ + Object.defineProperty(prepare.webgl, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } + }); + } + + if (loaders.Loader) { + var Resource = loaders.Resource; + var Loader = loaders.Loader; + + Object.defineProperties(Resource.prototype, { + isJson: { + get: function get() { + warn('The isJson property is deprecated, please use `resource.type === Resource.TYPE.JSON`.'); + + return this.type === Resource.TYPE.JSON; + } + }, + isXml: { + get: function get() { + warn('The isXml property is deprecated, please use `resource.type === Resource.TYPE.XML`.'); + + return this.type === Resource.TYPE.XML; + } + }, + isImage: { + get: function get() { + warn('The isImage property is deprecated, please use `resource.type === Resource.TYPE.IMAGE`.'); + + return this.type === Resource.TYPE.IMAGE; + } + }, + isAudio: { + get: function get() { + warn('The isAudio property is deprecated, please use `resource.type === Resource.TYPE.AUDIO`.'); + + return this.type === Resource.TYPE.AUDIO; + } + }, + isVideo: { + get: function get() { + warn('The isVideo property is deprecated, please use `resource.type === Resource.TYPE.VIDEO`.'); + + return this.type === Resource.TYPE.VIDEO; + } + } + }); + + Object.defineProperties(Loader.prototype, { + before: { + get: function get() { + warn('The before() method is deprecated, please use pre().'); + + return this.pre; + } + }, + after: { + get: function get() { + warn('The after() method is deprecated, please use use().'); + + return this.use; + } + } + }); + } + + if (interaction.interactiveTarget) { + /** + * @name PIXI.interaction.interactiveTarget#defaultCursor + * @static + * @type {number} + * @see PIXI.interaction.interactiveTarget#cursor + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.interactiveTarget, 'defaultCursor', { + set: function set(value) { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + this.cursor = value; + }, + get: function get() { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + + return this.cursor; + } + }); + } + + if (interaction.InteractionManager) { + /** + * @name PIXI.interaction.InteractionManager#defaultCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.InteractionManager, 'defaultCursorStyle', { + set: function set(value) { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + this.cursorStyles.default = value; + }, + get: function get() { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + + return this.cursorStyles.default; + } + }); + + /** + * @name PIXI.interaction.InteractionManager#currentCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.InteractionManager, 'currentCursorStyle', { + set: function set(value) { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + this.currentCursorMode = value; + }, + get: function get() { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + + return this.currentCursorMode; + } + }); + } +} + +},{}],132:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI.extract + */ + +var CanvasExtract = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasExtract(renderer) { + _classCallCheck(this, CanvasExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.extract.CanvasExtract} extract + * @memberof PIXI.CanvasRenderer# + * @see PIXI.extract.CanvasExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + CanvasExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `CanvasExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + CanvasExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + CanvasExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = this.renderer.width; + frame.height = this.renderer.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height, 1); + var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + CanvasExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + + return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; + }; + + /** + * Destroys the extract + * + */ + + + CanvasExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return CanvasExtract; +}(); + +exports.default = CanvasExtract; + + +core.CanvasRenderer.registerPlugin('extract', CanvasExtract); + +},{"../../core":65}],133:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLExtract = require('./webgl/WebGLExtract'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLExtract).default; + } +}); + +var _CanvasExtract = require('./canvas/CanvasExtract'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasExtract).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./canvas/CanvasExtract":132,"./webgl/WebGLExtract":134}],134:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); +var BYTES_PER_PIXEL = 4; + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI.extract + */ + +var WebGLExtract = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLExtract(renderer) { + _classCallCheck(this, WebGLExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.extract.WebGLExtract} extract + * @memberof PIXI.WebGLRenderer# + * @see PIXI.extract.WebGLExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + WebGLExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `WebGLExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + WebGLExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + WebGLExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var flipY = false; + var renderTexture = void 0; + var generated = false; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + generated = true; + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + flipY = false; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + flipY = true; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height, 1); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + + // set up an array of pixels + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + + canvasData.data.set(webglPixels); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // pulling pixels + if (flipY) { + canvasBuffer.context.scale(1, -1); + canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); + } + } + + if (generated) { + renderTexture.destroy(true); + } + // send the canvas back.. + + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + WebGLExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + var generated = false; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + generated = true; + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + } + + if (generated) { + renderTexture.destroy(true); + } + + return webglPixels; + }; + + /** + * Destroys the extract + * + */ + + + WebGLExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return WebGLExtract; +}(); + +exports.default = WebGLExtract; + + +core.WebGLRenderer.registerPlugin('extract', WebGLExtract); + +},{"../../core":65}],135:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @typedef PIXI.extras.AnimatedSprite~FrameObject + * @type {object} + * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame + * @property {number} time - the duration of the frame in ms + */ + +/** + * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. + * + * ```js + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; + * + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.fromImage(alienImages[i]); + * textureArray.push(texture); + * }; + * + * let animatedSprite = new PIXI.extras.AnimatedSprite(textureArray); + * ``` + * + * The more efficient and simpler way to create an animated sprite is using a {@link PIXI.Spritesheet} + * containing the animation definitions: + * + * ```js + * PIXI.loader.add("assets/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.loader.resources["assets/spritesheet.json"].spritesheet; + * animatedSprite = new PIXI.extras.AnimatedSprite(sheet.animations["image_sequence"]); + * ... + * } + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ +var AnimatedSprite = function (_core$Sprite) { + _inherits(AnimatedSprite, _core$Sprite); + + /** + * @param {PIXI.Texture[]|PIXI.extras.AnimatedSprite~FrameObject[]} textures - an array of {@link PIXI.Texture} or frame + * objects that make up the animation + * @param {boolean} [autoUpdate=true] - Whether to use PIXI.ticker.shared to auto update animation time. + */ + function AnimatedSprite(textures, autoUpdate) { + _classCallCheck(this, AnimatedSprite); + + /** + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture)); + + _this._textures = null; + + /** + * @private + */ + _this._durations = null; + + _this.textures = textures; + + /** + * `true` uses PIXI.ticker.shared to auto update animation time. + * @type {boolean} + * @default true + * @private + */ + _this._autoUpdate = autoUpdate !== false; + + /** + * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower + * + * @member {number} + * @default 1 + */ + _this.animationSpeed = 1; + + /** + * Whether or not the animate sprite repeats after playing. + * + * @member {boolean} + * @default true + */ + _this.loop = true; + + /** + * Function to call when a AnimatedSprite finishes playing + * + * @member {Function} + */ + _this.onComplete = null; + + /** + * Function to call when a AnimatedSprite changes which texture is being rendered + * + * @member {Function} + */ + _this.onFrameChange = null; + + /** + * Function to call when 'loop' is true, and an AnimatedSprite is played and loops around to start again + * + * @member {Function} + */ + _this.onLoop = null; + + /** + * Elapsed time since animation has been started, used internally to display current texture + * + * @member {number} + * @private + */ + _this._currentTime = 0; + + /** + * Indicates if the AnimatedSprite is currently playing + * + * @member {boolean} + * @readonly + */ + _this.playing = false; + return _this; + } + + /** + * Stops the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.stop = function stop() { + if (!this.playing) { + return; + } + + this.playing = false; + if (this._autoUpdate) { + core.ticker.shared.remove(this.update, this); + } + }; + + /** + * Plays the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.play = function play() { + if (this.playing) { + return; + } + + this.playing = true; + if (this._autoUpdate) { + core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.HIGH); + } + }; + + /** + * Stops the AnimatedSprite and goes to a specific frame + * + * @param {number} frameNumber - frame index to stop at + */ + + + AnimatedSprite.prototype.gotoAndStop = function gotoAndStop(frameNumber) { + this.stop(); + + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + + /** + * Goes to a specific frame and begins playing the AnimatedSprite + * + * @param {number} frameNumber - frame index to start at + */ + + + AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay(frameNumber) { + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + + this.play(); + }; + + /** + * Updates the object transform for rendering. + * + * @private + * @param {number} deltaTime - Time since last tick. + */ + + + AnimatedSprite.prototype.update = function update(deltaTime) { + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + + lag += elapsed / 60 * 1000; + + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + + var sign = Math.sign(this.animationSpeed * deltaTime); + + this._currentTime = Math.floor(this._currentTime); + + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + + this._currentTime += lag / this._durations[this.currentFrame]; + } else { + this._currentTime += elapsed; + } + + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + + if (this.onComplete) { + this.onComplete(); + } + } else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + + if (this.onComplete) { + this.onComplete(); + } + } else if (previousFrame !== this.currentFrame) { + if (this.loop && this.onLoop) { + if (this.animationSpeed > 0 && this.currentFrame < previousFrame) { + this.onLoop(); + } else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) { + this.onLoop(); + } + } + + this.updateTexture(); + } + }; + + /** + * Updates the displayed texture to match the current frame index + * + * @private + */ + + + AnimatedSprite.prototype.updateTexture = function updateTexture() { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + this.cachedTint = 0xFFFFFF; + + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + }; + + /** + * Stops the AnimatedSprite and destroys it + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + AnimatedSprite.prototype.destroy = function destroy(options) { + this.stop(); + _core$Sprite.prototype.destroy.call(this, options); + }; + + /** + * A short hand way of creating a movieclip from an array of frame ids + * + * @static + * @param {string[]} frames - The array of frames ids the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animated sprite with the specified frames. + */ + + + AnimatedSprite.fromFrames = function fromFrames(frames) { + var textures = []; + + for (var i = 0; i < frames.length; ++i) { + textures.push(core.Texture.fromFrame(frames[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * A short hand way of creating a movieclip from an array of image ids + * + * @static + * @param {string[]} images - the array of image urls the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animate sprite with the specified images as frames. + */ + + + AnimatedSprite.fromImages = function fromImages(images) { + var textures = []; + + for (var i = 0; i < images.length; ++i) { + textures.push(core.Texture.fromImage(images[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * totalFrames is the total number of frames in the AnimatedSprite. This is the same as number of textures + * assigned to the AnimatedSprite. + * + * @readonly + * @member {number} + * @default 0 + */ + + + _createClass(AnimatedSprite, [{ + key: 'totalFrames', + get: function get() { + return this._textures.length; + } + + /** + * The array of textures used for this AnimatedSprite + * + * @member {PIXI.Texture[]} + */ + + }, { + key: 'textures', + get: function get() { + return this._textures; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value[0] instanceof core.Texture) { + this._textures = value; + this._durations = null; + } else { + this._textures = []; + this._durations = []; + + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + this.gotoAndStop(0); + this.updateTexture(); + } + + /** + * The AnimatedSprites current frame index + * + * @member {number} + * @readonly + */ + + }, { + key: 'currentFrame', + get: function get() { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + + return currentFrame; + } + }]); + + return AnimatedSprite; +}(core.Sprite); + +exports.default = AnimatedSprite; + +},{"../core":65}],136:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ObservablePoint = require('../core/math/ObservablePoint'); + +var _ObservablePoint2 = _interopRequireDefault(_ObservablePoint); + +var _utils = require('../core/utils'); + +var _settings = require('../core/settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BitmapText object will create a line or multiple lines of text using bitmap font. To + * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using: + * + * A BitmapText can only be created when the font is loaded + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); + * ``` + * + * http://www.angelcode.com/products/bmfont/ for windows or + * http://www.bmglyph.com/ for mac. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.extras + */ +var BitmapText = function (_core$Container) { + _inherits(BitmapText, _core$Container); + + /** + * @param {string} text - The copy that you would like the text to display + * @param {object} style - The style parameters + * @param {string|object} style.font - The font descriptor for the object, can be passed as a string of form + * "24px FontName" or "FontName" or as an object with explicit name/size properties. + * @param {string} [style.font.name] - The bitmap font id + * @param {number} [style.font.size] - The size of the font in pixels, e.g. 24 + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), does not affect + * single line text + * @param {number} [style.tint=0xFFFFFF] - The tint color + */ + function BitmapText(text) { + var style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _classCallCheck(this, BitmapText); + + /** + * Private tracker for the width of the overall text + * + * @member {number} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._textWidth = 0; + + /** + * Private tracker for the height of the overall text + * + * @member {number} + * @private + */ + _this._textHeight = 0; + + /** + * Private tracker for the letter sprite pool. + * + * @member {PIXI.Sprite[]} + * @private + */ + _this._glyphs = []; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._font = { + tint: style.tint !== undefined ? style.tint : 0xFFFFFF, + align: style.align || 'left', + name: null, + size: 0 + }; + + /** + * Private tracker for the current font. + * + * @member {object} + * @private + */ + _this.font = style.font; // run font setter + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = text; + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + * @private + */ + _this._maxWidth = 0; + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + * @private + */ + _this._maxLineHeight = 0; + + /** + * Letter spacing. This is useful for setting the space between characters. + * @member {number} + * @private + */ + _this._letterSpacing = 0; + + /** + * Text anchor. read-only + * + * @member {PIXI.ObservablePoint} + * @private + */ + _this._anchor = new _ObservablePoint2.default(function () { + _this.dirty = true; + }, _this, 0, 0); + + /** + * The dirty state of this object. + * + * @member {boolean} + */ + _this.dirty = false; + + _this.updateText(); + return _this; + } + + /** + * Renders text and updates it when needed + * + * @private + */ + + + BitmapText.prototype.updateText = function updateText() { + var data = BitmapText.fonts[this._font.name]; + var scale = this._font.size / data.size; + var pos = new core.Point(); + var chars = []; + var lineWidths = []; + var text = this.text.replace(/(?:\r\n|\r)/g, '\n'); + var textLength = text.length; + var maxWidth = this._maxWidth * data.size / this._font.size; + + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastBreakPos = -1; + var lastBreakWidth = 0; + var spacesRemoved = 0; + var maxLineHeight = 0; + + for (var i = 0; i < textLength; i++) { + var charCode = text.charCodeAt(i); + var char = text.charAt(i); + + if (/(?:\s)/.test(char)) { + lastBreakPos = i; + lastBreakWidth = lastLineWidth; + } + + if (char === '\r' || char === '\n') { + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + ++line; + ++spacesRemoved; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + var charData = data.chars[charCode]; + + if (!charData) { + continue; + } + + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + + chars.push({ + texture: charData.texture, + line: line, + charCode: charCode, + position: new core.Point(pos.x + charData.xOffset + this._letterSpacing / 2, pos.y + charData.yOffset) + }); + pos.x += charData.xAdvance + this._letterSpacing; + lastLineWidth = pos.x; + maxLineHeight = Math.max(maxLineHeight, charData.yOffset + charData.texture.height); + prevCharCode = charCode; + + if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth) { + ++spacesRemoved; + core.utils.removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos); + i = lastBreakPos; + lastBreakPos = -1; + + lineWidths.push(lastBreakWidth); + maxLineWidth = Math.max(maxLineWidth, lastBreakWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + } + } + + var lastChar = text.charAt(text.length - 1); + + if (lastChar !== '\r' && lastChar !== '\n') { + if (/(?:\s)/.test(lastChar)) { + lastLineWidth = lastBreakWidth; + } + + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + } + + var lineAlignOffsets = []; + + for (var _i = 0; _i <= line; _i++) { + var alignOffset = 0; + + if (this._font.align === 'right') { + alignOffset = maxLineWidth - lineWidths[_i]; + } else if (this._font.align === 'center') { + alignOffset = (maxLineWidth - lineWidths[_i]) / 2; + } + + lineAlignOffsets.push(alignOffset); + } + + var lenChars = chars.length; + var tint = this.tint; + + for (var _i2 = 0; _i2 < lenChars; _i2++) { + var c = this._glyphs[_i2]; // get the next glyph sprite + + if (c) { + c.texture = chars[_i2].texture; + } else { + c = new core.Sprite(chars[_i2].texture); + this._glyphs.push(c); + } + + c.position.x = (chars[_i2].position.x + lineAlignOffsets[chars[_i2].line]) * scale; + c.position.y = chars[_i2].position.y * scale; + c.scale.x = c.scale.y = scale; + c.tint = tint; + + if (!c.parent) { + this.addChild(c); + } + } + + // remove unnecessary children. + for (var _i3 = lenChars; _i3 < this._glyphs.length; ++_i3) { + this.removeChild(this._glyphs[_i3]); + } + + this._textWidth = maxLineWidth * scale; + this._textHeight = (pos.y + data.lineHeight) * scale; + + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + for (var _i4 = 0; _i4 < lenChars; _i4++) { + this._glyphs[_i4].x -= this._textWidth * this.anchor.x; + this._glyphs[_i4].y -= this._textHeight * this.anchor.y; + } + } + this._maxLineHeight = maxLineHeight * scale; + }; + + /** + * Updates the transform of this object + * + * @private + */ + + + BitmapText.prototype.updateTransform = function updateTransform() { + this.validate(); + this.containerUpdateTransform(); + }; + + /** + * Validates text before calling parent's getLocalBounds + * + * @return {PIXI.Rectangle} The rectangular bounding area + */ + + + BitmapText.prototype.getLocalBounds = function getLocalBounds() { + this.validate(); + + return _core$Container.prototype.getLocalBounds.call(this); + }; + + /** + * Updates text when needed + * + * @private + */ + + + BitmapText.prototype.validate = function validate() { + if (this.dirty) { + this.updateText(); + this.dirty = false; + } + }; + + /** + * The tint of the BitmapText object + * + * @member {number} + */ + + + /** + * Register a bitmap font with data and a texture. + * + * @static + * @param {XMLDocument} xml - The XML document data. + * @param {Object.|PIXI.Texture|PIXI.Texture[]} textures - List of textures for each page. + * If providing an object, the key is the `` element's `file` attribute in the FNT file. + * @return {Object} Result font object with font, size, lineHeight and char fields. + */ + BitmapText.registerFont = function registerFont(xml, textures) { + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + var pages = xml.getElementsByTagName('page'); + var res = (0, _utils.getResolutionOfUrl)(pages[0].getAttribute('file'), _settings2.default.RESOLUTION); + var pagesTextures = {}; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) / res; + data.chars = {}; + + // Single texture, convert to list + if (textures instanceof core.Texture) { + textures = [textures]; + } + + // Convert the input Texture, Textures or object + // into a page Texture lookup by "id" + for (var i = 0; i < pages.length; i++) { + var id = pages[i].getAttribute('id'); + var file = pages[i].getAttribute('file'); + + pagesTextures[id] = textures instanceof Array ? textures[i] : textures[file]; + } + + // parse letters + var letters = xml.getElementsByTagName('char'); + + for (var _i5 = 0; _i5 < letters.length; _i5++) { + var letter = letters[_i5]; + var charCode = parseInt(letter.getAttribute('id'), 10); + var page = letter.getAttribute('page') || 0; + var textureRect = new core.Rectangle(parseInt(letter.getAttribute('x'), 10) / res + pagesTextures[page].frame.x / res, parseInt(letter.getAttribute('y'), 10) / res + pagesTextures[page].frame.y / res, parseInt(letter.getAttribute('width'), 10) / res, parseInt(letter.getAttribute('height'), 10) / res); + + data.chars[charCode] = { + xOffset: parseInt(letter.getAttribute('xoffset'), 10) / res, + yOffset: parseInt(letter.getAttribute('yoffset'), 10) / res, + xAdvance: parseInt(letter.getAttribute('xadvance'), 10) / res, + kerning: {}, + texture: new core.Texture(pagesTextures[page].baseTexture, textureRect), + page: page + }; + } + + // parse kernings + var kernings = xml.getElementsByTagName('kerning'); + + for (var _i6 = 0; _i6 < kernings.length; _i6++) { + var kerning = kernings[_i6]; + var first = parseInt(kerning.getAttribute('first'), 10) / res; + var second = parseInt(kerning.getAttribute('second'), 10) / res; + var amount = parseInt(kerning.getAttribute('amount'), 10) / res; + + if (data.chars[second]) { + data.chars[second].kerning[first] = amount; + } + } + + // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 + // but it's very likely to change + BitmapText.fonts[data.font] = data; + + return data; + }; + + _createClass(BitmapText, [{ + key: 'tint', + get: function get() { + return this._font.tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.tint = typeof value === 'number' && value >= 0 ? value : 0xFFFFFF; + + this.dirty = true; + } + + /** + * The alignment of the BitmapText object + * + * @member {string} + * @default 'left' + */ + + }, { + key: 'align', + get: function get() { + return this._font.align; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.align = value || 'left'; + + this.dirty = true; + } + + /** + * The anchor sets the origin point of the text. + * The default is 0,0 this means the text's origin is the top left + * Setting the anchor to 0.5,0.5 means the text's origin is centered + * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner + * + * @member {PIXI.Point | number} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (typeof value === 'number') { + this._anchor.set(value); + } else { + this._anchor.copy(value); + } + } + + /** + * The font descriptor of the BitmapText object + * + * @member {string|object} + */ + + }, { + key: 'font', + get: function get() { + return this._font; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (!value) { + return; + } + + if (typeof value === 'string') { + value = value.split(' '); + + this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); + this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; + } else { + this._font.name = value.name; + this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); + } + + this.dirty = true; + } + + /** + * The text of the BitmapText object + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + value = value.toString() || ' '; + if (this._text === value) { + return; + } + this._text = value; + this.dirty = true; + } + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + */ + + }, { + key: 'maxWidth', + get: function get() { + return this._maxWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._maxWidth === value) { + return; + } + this._maxWidth = value; + this.dirty = true; + } + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + * @readonly + */ + + }, { + key: 'maxLineHeight', + get: function get() { + this.validate(); + + return this._maxLineHeight; + } + + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textWidth', + get: function get() { + this.validate(); + + return this._textWidth; + } + + /** + * Additional space between characters. + * + * @member {number} + */ + + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._letterSpacing !== value) { + this._letterSpacing = value; + this.dirty = true; + } + } + + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textHeight', + get: function get() { + this.validate(); + + return this._textHeight; + } + }]); + + return BitmapText; +}(core.Container); + +exports.default = BitmapText; + + +BitmapText.fonts = {}; + +},{"../core":65,"../core/math/ObservablePoint":68,"../core/settings":101,"../core/utils":125}],137:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CanvasTinter = require('../core/sprites/canvas/CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); + +/** + * A tiling sprite is a fast way of rendering a tiling image + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ + +var TilingSprite = function (_core$Sprite) { + _inherits(TilingSprite, _core$Sprite); + + /** + * @param {PIXI.Texture} texture - the texture of the tiling sprite + * @param {number} [width=100] - the width of the tiling sprite + * @param {number} [height=100] - the height of the tiling sprite + */ + function TilingSprite(texture) { + var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100; + + _classCallCheck(this, TilingSprite); + + /** + * Tile transform + * + * @member {PIXI.TransformStatic} + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, texture)); + + _this.tileTransform = new core.TransformStatic(); + + // /// private + + /** + * The with of the tiling sprite + * + * @member {number} + * @private + */ + _this._width = width; + + /** + * The height of the tiling sprite + * + * @member {number} + * @private + */ + _this._height = height; + + /** + * Canvas pattern + * + * @type {CanvasPattern} + * @private + */ + _this._canvasPattern = null; + + /** + * transform that is applied to UV to get the texture coords + * + * @member {PIXI.TextureMatrix} + */ + _this.uvTransform = texture.transform || new core.TextureMatrix(texture); + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' method. + * + * @member {string} + * @default 'tilingSprite' + */ + _this.pluginName = 'tilingSprite'; + + /** + * Whether or not anchor affects uvs + * + * @member {boolean} + * @default false + */ + _this.uvRespectAnchor = false; + return _this; + } + /** + * Changes frame clamping in corresponding textureTransform, shortcut + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + + + /** + * @private + */ + TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate() { + if (this.uvTransform) { + this.uvTransform.texture = this._texture; + } + this.cachedTint = 0xFFFFFF; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + TilingSprite.prototype._renderWebGL = function _renderWebGL(renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + + if (!texture || !texture.valid) { + return; + } + + this.tileTransform.updateLocalTransform(); + this.uvTransform.update(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer + */ + + + TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { + var texture = this._texture; + + if (!texture.baseTexture.hasLoaded) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var resolution = renderer.resolution; + var baseTexture = texture.baseTexture; + var baseTextureResolution = baseTexture.resolution; + var modX = this.tilePosition.x / this.tileScale.x % texture._frame.width * baseTextureResolution; + var modY = this.tilePosition.y / this.tileScale.y % texture._frame.height * baseTextureResolution; + + // create a nice shiny pattern! + if (this._textureID !== this._texture._updateID || this.cachedTint !== this.tint) { + this._textureID = this._texture._updateID; + // cut an object from a spritesheet.. + var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height, baseTextureResolution); + + // Tint the tiling sprite + if (this.tint !== 0xFFFFFF) { + this.tintedTexture = _CanvasTinter2.default.getTintedTexture(this, this.tint); + tempCanvas.context.drawImage(this.tintedTexture, 0, 0); + } else { + tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x * baseTextureResolution, -texture._frame.y * baseTextureResolution); + } + this.cachedTint = this.tint; + this._canvasPattern = tempCanvas.context.createPattern(tempCanvas.canvas, 'repeat'); + } + + // set context state.. + context.globalAlpha = this.worldAlpha; + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + renderer.setBlendMode(this.blendMode); + + // fill the pattern! + context.fillStyle = this._canvasPattern; + + // TODO - this should be rolled into the setTransform above.. + context.scale(this.tileScale.x / baseTextureResolution, this.tileScale.y / baseTextureResolution); + + var anchorX = this.anchor.x * -this._width; + var anchorY = this.anchor.y * -this._height; + + if (this.uvRespectAnchor) { + context.translate(modX, modY); + + context.fillRect(-modX + anchorX, -modY + anchorY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } else { + context.translate(modX + anchorX, modY + anchorY); + + context.fillRect(-modX, -modY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } + }; + + /** + * Updates the bounds of the tiling sprite. + * + * @private + */ + + + TilingSprite.prototype._calculateBounds = function _calculateBounds() { + var minX = this._width * -this._anchor._x; + var minY = this._height * -this._anchor._y; + var maxX = this._width * (1 - this._anchor._x); + var maxY = this._height * (1 - this._anchor._y); + + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + TilingSprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._width * -this._anchor._x; + this._bounds.minY = this._height * -this._anchor._y; + this._bounds.maxX = this._width * (1 - this._anchor._x); + this._bounds.maxY = this._height * (1 - this._anchor._y); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new core.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _core$Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Checks if a point is inside this tiling sprite. + * + * @param {PIXI.Point} point - the point to check + * @return {boolean} Whether or not the sprite contains the point. + */ + + + TilingSprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor._x; + + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + var y1 = -height * this.anchor._y; + + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + TilingSprite.prototype.destroy = function destroy(options) { + _core$Sprite.prototype.destroy.call(this, options); + + this.tileTransform = null; + this.uvTransform = null; + }; + + /** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.Texture} The newly created texture + */ + + + TilingSprite.from = function from(source, width, height) { + return new TilingSprite(core.Texture.from(source), width, height); + }; + + /** + * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId + */ + + + TilingSprite.fromFrame = function fromFrame(frameId, width, height) { + var texture = core.utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this); + } + + return new TilingSprite(texture, width, height); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @param {boolean} [crossorigin] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id + */ + + + TilingSprite.fromImage = function fromImage(imageId, width, height, crossorigin, scaleMode) { + return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode), width, height); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(TilingSprite, [{ + key: 'clampMargin', + get: function get() { + return this.uvTransform.clampMargin; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uvTransform.clampMargin = value; + this.uvTransform.update(true); + } + + /** + * The scaling of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tileScale', + get: function get() { + return this.tileTransform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.scale.copy(value); + } + + /** + * The offset of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tilePosition', + get: function get() { + return this.tileTransform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.position.copy(value); + } + }, { + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + } + + /** + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + } + }]); + + return TilingSprite; +}(core.Sprite); + +exports.default = TilingSprite; + +},{"../core":65,"../core/sprites/canvas/CanvasTinter":104}],138:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _BaseTexture = require('../core/textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _utils = require('../core/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DisplayObject = core.DisplayObject; +var _tempMatrix = new core.Matrix(); + +DisplayObject.prototype._cacheAsBitmap = false; +DisplayObject.prototype._cacheData = false; + +// figured theres no point adding ALL the extra variables to prototype. +// this model can hold the information needed. This can also be generated on demand as +// most objects are not cached as bitmaps. +/** + * @class + * @ignore + */ + +var CacheData = +/** + * + */ +function CacheData() { + _classCallCheck(this, CacheData); + + this.textureCacheId = null; + + this.originalRenderWebGL = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + + this.originalUpdateTransform = null; + this.originalHitTest = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.sprite = null; +}; + +Object.defineProperties(DisplayObject.prototype, { + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to 'false' + * + * IMPORTANT GOTCHA - make sure that all your textures are preloaded BEFORE setting this property to true + * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function get() { + return this._cacheAsBitmap; + }, + set: function set(value) { + if (this._cacheAsBitmap === value) { + return; + } + + this._cacheAsBitmap = value; + + var data = void 0; + + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + + data = this._cacheData; + + data.originalRenderWebGL = this.renderWebGL; + data.originalRenderCanvas = this.renderCanvas; + + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this._calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + + data.originalDestroy = this.destroy; + + data.originalContainsPoint = this.containsPoint; + + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + + this.renderWebGL = this._renderCachedWebGL; + this.renderCanvas = this._renderCachedCanvas; + + this.destroy = this._cacheAsBitmapDestroy; + } else { + data = this._cacheData; + + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + + this.renderWebGL = data.originalRenderWebGL; + this.renderCanvas = data.originalRenderCanvas; + this._calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + + this.destroy = data.originalDestroy; + + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + } + } +}); + +/** + * Renders a cached version of the sprite with WebGL + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedWebGL = function _renderCachedWebGL(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObject(renderer); + + this._cacheData.sprite._transformID = -1; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderWebGL(renderer); +}; + +/** + * Prepares the WebGL renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + + this.alpha = 1; + + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.currentRenderer.flush(); + // this.filters= []; + + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds().clone(); + + // add some padding! + if (this._filters) { + var padding = this._filters[0].padding; + + bounds.pad(padding); + } + + // for now we cache the current renderTarget that the webGL renderer is currently using. + // this could be more elegent.. + var cachedRenderTarget = renderer._activeRenderTarget; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + var stack = renderer.filterManager.filterStack; + + // this renderTexture will be used to store the cached DisplayObject + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); + + this._cacheData.textureCacheId = textureCacheId; + + _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); + _Texture2.default.addToCache(renderTexture, textureCacheId); + + // need to set // + var m = _tempMatrix; + + m.tx = -bounds.x; + m.ty = -bounds.y; + + // reset + this.transform.worldTransform.identity(); + + // set all properties to there original so we can render to a texture + this.renderWebGL = this._cacheData.originalRenderWebGL; + + renderer.render(this, renderTexture, true, m, true); + // now restore the state be setting the new properties + + renderer.bindRenderTarget(cachedRenderTarget); + + renderer.filterManager.filterStack = stack; + + this.renderWebGL = this._renderCachedWebGL; + this.updateTransform = this.displayObjectUpdateTransform; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + + // easy bounds.. + this._calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + + this._cacheData.sprite = cachedSprite; + + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this.updateTransform(); + } + + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Renders a cached version of the sprite with canvas + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObjectCanvas(renderer); + + this._cacheData.sprite.worldAlpha = this.worldAlpha; + + this._cacheData.sprite.renderCanvas(renderer); +}; + +// TODO this can be the same as the webGL verison.. will need to do a little tweaking first though.. +/** + * Prepares the Canvas renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(); + + var cacheAlpha = this.alpha; + + this.alpha = 1; + + var cachedRenderTarget = renderer.context; + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); + + this._cacheData.textureCacheId = textureCacheId; + + _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); + _Texture2.default.addToCache(renderTexture, textureCacheId); + + // need to set // + var m = _tempMatrix; + + this.transform.localTransform.copy(m); + m.invert(); + + m.tx -= bounds.x; + m.ty -= bounds.y; + + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + + // renderTexture.render(this, m, true); + renderer.render(this, renderTexture, true, m, false); + + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + + this.renderCanvas = this._renderCachedCanvas; + this._calculateBounds = this._calculateCachedBounds; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite._bounds = this._bounds; + cachedSprite.alpha = cacheAlpha; + + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this.updateTransform(); + } + + this.updateTransform = this.displayObjectUpdateTransform; + + this._cacheData.sprite = cachedSprite; + + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Calculates the bounds of the cached sprite + * + * @private + */ +DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._cacheData.sprite._calculateBounds(); +}; + +/** + * Gets the bounds of the cached sprite. + * + * @private + * @return {Rectangle} The local bounds. + */ +DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(); +}; + +/** + * Destroys the cached sprite. + * + * @private + */ +DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; + + _BaseTexture2.default.removeFromCache(this._cacheData.textureCacheId); + _Texture2.default.removeFromCache(this._cacheData.textureCacheId); + + this._cacheData.textureCacheId = null; +}; + +/** + * Destroys the cached object. + * + * @private + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * Used when destroying containers, see the Container.destroy method. + */ +DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { + this.cacheAsBitmap = false; + this.destroy(options); +}; + +},{"../core":65,"../core/textures/BaseTexture":112,"../core/textures/Texture":115,"../core/utils":125}],139:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * The instance name of the object. + * + * @memberof PIXI.DisplayObject# + * @member {string} name + */ +core.DisplayObject.prototype.name = null; + +/** + * Returns the display object in the container + * + * @method getChildByName + * @memberof PIXI.Container# + * @param {string} name - instance name + * @return {PIXI.DisplayObject} The child with the specified name. + */ +core.Container.prototype.getChildByName = function getChildByName(name) { + for (var i = 0; i < this.children.length; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + + return null; +}; + +},{"../core":65}],140:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. + * + * @method getGlobalPosition + * @memberof PIXI.DisplayObject# + * @param {Point} point - the point to write the global value to. If null a new point will be returned + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @return {Point} The updated point + */ +core.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition() { + var point = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new core.Point(); + var skipUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (this.parent) { + this.parent.toGlobal(this.position, point, skipUpdate); + } else { + point.x = this.position.x; + point.y = this.position.y; + } + + return point; +}; + +},{"../core":65}],141:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BitmapText = exports.TilingSpriteRenderer = exports.TilingSprite = exports.AnimatedSprite = undefined; + +var _AnimatedSprite = require('./AnimatedSprite'); + +Object.defineProperty(exports, 'AnimatedSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AnimatedSprite).default; + } +}); + +var _TilingSprite = require('./TilingSprite'); + +Object.defineProperty(exports, 'TilingSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSprite).default; + } +}); + +var _TilingSpriteRenderer = require('./webgl/TilingSpriteRenderer'); + +Object.defineProperty(exports, 'TilingSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSpriteRenderer).default; + } +}); + +var _BitmapText = require('./BitmapText'); + +Object.defineProperty(exports, 'BitmapText', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BitmapText).default; + } +}); + +require('./cacheAsBitmap'); + +require('./getChildByName'); + +require('./getGlobalPosition'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// imported for side effect of extending the prototype only, contains no exports + +},{"./AnimatedSprite":135,"./BitmapText":136,"./TilingSprite":137,"./cacheAsBitmap":138,"./getChildByName":139,"./getGlobalPosition":140,"./webgl/TilingSpriteRenderer":142}],142:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _const = require('../../core/const'); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMat = new core.Matrix(); + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI.extras + * @extends PIXI.ObjectRenderer + */ + +var TilingSpriteRenderer = function (_core$ObjectRenderer) { + _inherits(TilingSpriteRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function TilingSpriteRenderer(renderer) { + _classCallCheck(this, TilingSpriteRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + _this.simpleShader = null; + _this.quad = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + TilingSpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n gl_FragColor = sample * uColor;\n}\n'); + this.simpleShader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = sample * uColor;\n}\n'); + + this.renderer.bindVao(null); + this.quad = new core.Quad(gl, this.renderer.state.attribState); + this.quad.initVao(this.shader); + }; + + /** + * + * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered + */ + + + TilingSpriteRenderer.prototype.render = function render(ts) { + var renderer = this.renderer; + var quad = this.quad; + + renderer.bindVao(quad.vao); + + var vertices = quad.vertices; + + vertices[0] = vertices[6] = ts._width * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + + vertices[2] = vertices[4] = ts._width * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + + if (ts.uvRespectAnchor) { + vertices = quad.uvs; + + vertices[0] = vertices[6] = -ts.anchor.x; + vertices[1] = vertices[3] = -ts.anchor.y; + + vertices[2] = vertices[4] = 1.0 - ts.anchor.x; + vertices[5] = vertices[7] = 1.0 - ts.anchor.y; + } + + quad.upload(); + + var tex = ts._texture; + var baseTex = tex.baseTexture; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvTransform; + var isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === _const.WRAP_MODES.CLAMP) { + baseTex.wrapMode = _const.WRAP_MODES.REPEAT; + } + } else { + isSimple = baseTex.wrapMode !== _const.WRAP_MODES.CLAMP; + } + } + + var shader = isSimple ? this.simpleShader : this.shader; + + renderer.bindShader(shader); + + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + + tempMat.invert(); + if (isSimple) { + tempMat.prepend(uv.mapCoord); + } else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + + shader.uniforms.uTransform = tempMat.toArray(true); + shader.uniforms.uColor = core.utils.premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, baseTex.premultipliedAlpha); + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + + shader.uniforms.uSampler = renderer.bindTexture(tex); + + renderer.setBlendMode(core.utils.correctBlendMode(ts.blendMode, baseTex.premultipliedAlpha)); + + quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + }; + + return TilingSpriteRenderer; +}(core.ObjectRenderer); + +exports.default = TilingSpriteRenderer; + + +core.WebGLRenderer.registerPlugin('tilingSprite', TilingSpriteRenderer); + +},{"../../core":65,"../../core/const":46,"path":8}],143:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Simplest filter - applies alpha + * + * Use this instead of Container's alpha property to avoid visual layering of individual elements. + * AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains. + * If elements are not opaque, they will blend with each other anyway. + * + * Very handy if you want to use common features of all filters: + * + * 1. Assign a blendMode to this filter, blend all elements inside display object with background. + * + * 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var AlphaFilter = function (_core$Filter) { + _inherits(AlphaFilter, _core$Filter); + + /** + * @param {number} [alpha=1] Amount of alpha from 0 to 1, where 0 is transparent + */ + function AlphaFilter() { + var alpha = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1.0; + + _classCallCheck(this, AlphaFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n')); + + _this.alpha = alpha; + _this.glShaderKey = 'alpha'; + return _this; + } + + /** + * Coefficient for alpha multiplication + * + * @member {number} + * @default 1 + */ + + + _createClass(AlphaFilter, [{ + key: 'alpha', + get: function get() { + return this.uniforms.uAlpha; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uAlpha = value; + } + }]); + + return AlphaFilter; +}(core.Filter); + +exports.default = AlphaFilter; + +},{"../../core":65,"path":8}],144:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BlurXFilter = require('./BlurXFilter'); + +var _BlurXFilter2 = _interopRequireDefault(_BlurXFilter); + +var _BlurYFilter = require('./BlurYFilter'); + +var _BlurYFilter2 = _interopRequireDefault(_BlurYFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurFilter applies a Gaussian blur to an object. + * The strength of the blur can be set for x- and y-axis separately. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurFilter = function (_core$Filter) { + _inherits(BlurFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this)); + + _this.blurXFilter = new _BlurXFilter2.default(strength, quality, resolution, kernelSize); + _this.blurYFilter = new _BlurYFilter2.default(strength, quality, resolution, kernelSize); + + _this.padding = 0; + _this.resolution = resolution || core.settings.RESOLUTION; + _this.quality = quality || 4; + _this.blur = strength || 8; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + BlurFilter.prototype.apply = function apply(filterManager, input, output) { + var renderTarget = filterManager.getRenderTarget(true); + + this.blurXFilter.apply(filterManager, input, renderTarget, true); + this.blurYFilter.apply(filterManager, renderTarget, output, false); + + filterManager.returnRenderTarget(renderTarget); + }; + + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurFilter, [{ + key: 'blur', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the number of passes for blur. More passes means higher quaility bluring. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'quality', + get: function get() { + return this.blurXFilter.quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.quality = this.blurYFilter.quality = value; + } + + /** + * Sets the strength of the blurX property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurX', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the strength of the blurY property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurY', + get: function get() { + return this.blurYFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the blendmode of the filter + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + */ + + }, { + key: 'blendMode', + get: function get() { + return this.blurYFilter._blendMode; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter._blendMode = value; + } + }]); + + return BlurFilter; +}(core.Filter); + +exports.default = BlurFilter; + +},{"../../core":65,"./BlurXFilter":145,"./BlurYFilter":146}],145:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurXFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurXFilter = function (_core$Filter) { + _inherits(BlurXFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurXFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurXFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurXFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.width * (output.size.width / input.size.width); + + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; // / this.passes//Math.pow(1, this.passes); + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 16 + */ + + + _createClass(BlurXFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurXFilter; +}(core.Filter); + +exports.default = BlurXFilter; + +},{"../../core":65,"./generateBlurFragSource":147,"./generateBlurVertSource":148,"./getMaxBlurKernelSize":149}],146:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurYFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurYFilter = function (_core$Filter) { + _inherits(BlurYFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurYFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurYFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurYFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.height * (output.size.height / input.size.height); + + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurYFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurYFilter; +}(core.Filter); + +exports.default = BlurYFilter; + +},{"../../core":65,"./generateBlurFragSource":147,"./generateBlurVertSource":148,"./getMaxBlurKernelSize":149}],147:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateFragBlurSource; +var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] +}; + +var fragTemplate = ['varying vec2 vBlurTexCoords[%size%];', 'uniform sampler2D uSampler;', 'void main(void)', '{', ' gl_FragColor = vec4(0.0);', ' %blur%', '}'].join('\n'); + +function generateFragBlurSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + + var fragSource = fragTemplate; + + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value = void 0; + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + value = i; + + if (i >= halfLength) { + value = kernelSize - i - 1; + } + + blur = blur.replace('%value%', kernel[value]); + + blurLoop += blur; + blurLoop += '\n'; + } + + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize); + + return fragSource; +} + +},{}],148:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateVertBlurSource; +var vertTemplate = ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform float strength;', 'uniform mat3 projectionMatrix;', 'varying vec2 vBlurTexCoords[%size%];', 'void main(void)', '{', 'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);', '%blur%', '}'].join('\n'); + +function generateVertBlurSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + + var vertSource = vertTemplate; + + var blurLoop = ''; + var template = void 0; + // let value; + + if (x) { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } else { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + // value = i; + + // if(i >= halfLength) + // { + // value = kernelSize - i - 1; + // } + + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + '.0'); + + blurLoop += blur; + blurLoop += '\n'; + } + + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize); + + return vertSource; +} + +},{}],149:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = getMaxKernelSize; +function getMaxKernelSize(gl) { + var maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + var kernelSize = 15; + + while (kernelSize > maxVaryings) { + kernelSize -= 2; + } + + return kernelSize; +} + +},{}],150:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.filters.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var ColorMatrixFilter = function (_core$Filter) { + _inherits(ColorMatrixFilter, _core$Filter); + + /** + * + */ + function ColorMatrixFilter() { + _classCallCheck(this, ColorMatrixFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n')); + + _this.uniforms.m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + _this.alpha = 1; + return _this; + } + + /** + * Transforms current matrix and set the new one + * + * @param {number[]} matrix - 5x4 matrix + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix(matrix) { + var multiply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + var newMatrix = matrix; + + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + + // set the new matrix + this.uniforms.m = newMatrix; + }; + + /** + * Multiplies two mat5's + * + * @private + * @param {number[]} out - 5x4 matrix the receiving matrix + * @param {number[]} a - 5x4 matrix the first operand + * @param {number[]} b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix + */ + + + ColorMatrixFilter.prototype._multiply = function _multiply(out, a, b) { + // Red Channel + out[0] = a[0] * b[0] + a[1] * b[5] + a[2] * b[10] + a[3] * b[15]; + out[1] = a[0] * b[1] + a[1] * b[6] + a[2] * b[11] + a[3] * b[16]; + out[2] = a[0] * b[2] + a[1] * b[7] + a[2] * b[12] + a[3] * b[17]; + out[3] = a[0] * b[3] + a[1] * b[8] + a[2] * b[13] + a[3] * b[18]; + out[4] = a[0] * b[4] + a[1] * b[9] + a[2] * b[14] + a[3] * b[19] + a[4]; + + // Green Channel + out[5] = a[5] * b[0] + a[6] * b[5] + a[7] * b[10] + a[8] * b[15]; + out[6] = a[5] * b[1] + a[6] * b[6] + a[7] * b[11] + a[8] * b[16]; + out[7] = a[5] * b[2] + a[6] * b[7] + a[7] * b[12] + a[8] * b[17]; + out[8] = a[5] * b[3] + a[6] * b[8] + a[7] * b[13] + a[8] * b[18]; + out[9] = a[5] * b[4] + a[6] * b[9] + a[7] * b[14] + a[8] * b[19] + a[9]; + + // Blue Channel + out[10] = a[10] * b[0] + a[11] * b[5] + a[12] * b[10] + a[13] * b[15]; + out[11] = a[10] * b[1] + a[11] * b[6] + a[12] * b[11] + a[13] * b[16]; + out[12] = a[10] * b[2] + a[11] * b[7] + a[12] * b[12] + a[13] * b[17]; + out[13] = a[10] * b[3] + a[11] * b[8] + a[12] * b[13] + a[13] * b[18]; + out[14] = a[10] * b[4] + a[11] * b[9] + a[12] * b[14] + a[13] * b[19] + a[14]; + + // Alpha Channel + out[15] = a[15] * b[0] + a[16] * b[5] + a[17] * b[10] + a[18] * b[15]; + out[16] = a[15] * b[1] + a[16] * b[6] + a[17] * b[11] + a[18] * b[16]; + out[17] = a[15] * b[2] + a[16] * b[7] + a[17] * b[12] + a[18] * b[17]; + out[18] = a[15] * b[3] + a[16] * b[8] + a[17] * b[13] + a[18] * b[18]; + out[19] = a[15] * b[4] + a[16] * b[9] + a[17] * b[14] + a[18] * b[19] + a[19]; + + return out; + }; + + /** + * Create a Float32 Array and normalize the offset component to 0-1 + * + * @private + * @param {number[]} matrix - 5x4 matrix + * @return {number[]} 5x4 matrix with all values between 0-1 + */ + + + ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix(matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + + return m; + }; + + /** + * Adjusts brightness + * + * @param {number} b - value of the brigthness (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.brightness = function brightness(b, multiply) { + var matrix = [b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the matrices in grey scales + * + * @param {number} scale - value of the grey (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.greyscale = function greyscale(scale, multiply) { + var matrix = [scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the black and white matrice. + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite(multiply) { + var matrix = [0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the hue property of the color + * + * @param {number} rotation - in degrees + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.hue = function hue(rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + + var a00 = cosR + (1.0 - cosR) * w; + var a01 = w * (1.0 - cosR) - sqrW * sinR; + var a02 = w * (1.0 - cosR) + sqrW * sinR; + + var a10 = w * (1.0 - cosR) + sqrW * sinR; + var a11 = cosR + w * (1.0 - cosR); + var a12 = w * (1.0 - cosR) - sqrW * sinR; + + var a20 = w * (1.0 - cosR) - sqrW * sinR; + var a21 = w * (1.0 - cosR) + sqrW * sinR; + var a22 = cosR + w * (1.0 - cosR); + + var matrix = [a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * + * @param {number} amount - value of the contrast (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.contrast = function contrast(amount, multiply) { + var v = (amount || 0) + 1; + var o = -0.5 * (v - 1); + + var matrix = [v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * + * @param {number} amount - The saturation amount (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.saturate = function saturate() { + var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var multiply = arguments[1]; + + var x = amount * 2 / 3 + 1; + var y = (x - 1) * -0.5; + + var matrix = [x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Desaturate image (remove color) + * + * Call the saturate function + * + */ + + + ColorMatrixFilter.prototype.desaturate = function desaturate() // eslint-disable-line no-unused-vars + { + this.saturate(-1); + }; + + /** + * Negative image (inverse of classic rgb matrix) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.negative = function negative(multiply) { + var matrix = [-1, 0, 0, 1, 0, 0, -1, 0, 1, 0, 0, 0, -1, 1, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Sepia image + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.sepia = function sepia(multiply) { + var matrix = [0.393, 0.7689999, 0.18899999, 0, 0, 0.349, 0.6859999, 0.16799999, 0, 0, 0.272, 0.5339999, 0.13099999, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.technicolor = function technicolor(multiply) { + var matrix = [1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Polaroid filter + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.polaroid = function polaroid(multiply) { + var matrix = [1.438, -0.062, -0.062, 0, 0, -0.122, 1.378, -0.122, 0, 0, -0.016, -0.016, 1.483, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Filter who transforms : Red -> Blue and Blue -> Red + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.toBGR = function toBGR(multiply) { + var matrix = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.kodachrome = function kodachrome(multiply) { + var matrix = [1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Brown delicious browni filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.browni = function browni(multiply) { + var matrix = [0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Vintage filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.vintage = function vintage(multiply) { + var matrix = [0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * + * @param {number} desaturation - Tone values. + * @param {number} toned - Tone values. + * @param {string} lightColor - Tone values, example: `0xFFE580` + * @param {string} darkColor - Tone values, example: `0xFFE580` + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.colorTone = function colorTone(desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + + var lR = (lightColor >> 16 & 0xFF) / 255; + var lG = (lightColor >> 8 & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + + var dR = (darkColor >> 16 & 0xFF) / 255; + var dG = (darkColor >> 8 & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + + var matrix = [0.3, 0.59, 0.11, 0, 0, lR, lG, lB, desaturation, 0, dR, dG, dB, toned, 0, lR - dR, lG - dG, lB - dB, 0, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Night effect + * + * @param {number} intensity - The intensity of the night effect. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.night = function night(intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [intensity * -2.0, -intensity, 0, 0, 0, -intensity, 0, intensity, 0, 0, 0, intensity, intensity * 2.0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * + * @param {number} amount - how much the predator feels his future victim + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.predator = function predator(amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * LSD effect + * + * Multiply the current matrix + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.lsd = function lsd(multiply) { + var matrix = [2, -0.4, 0.5, 0, 0, -0.5, 2, -0.4, 0, 0, -0.4, -0.5, 3, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Erase the current matrix by setting the default one + * + */ + + + ColorMatrixFilter.prototype.reset = function reset() { + var matrix = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, false); + }; + + /** + * The matrix of the color matrix filter + * + * @member {number[]} + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + + + _createClass(ColorMatrixFilter, [{ + key: 'matrix', + get: function get() { + return this.uniforms.m; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.m = value; + } + + /** + * The opacity value to use when mixing the original and resultant colors. + * + * When the value is 0, the original color is used without modification. + * When the value is 1, the result color is used. + * When in the range (0, 1) the color is interpolated between the original and result by this amount. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'alpha', + get: function get() { + return this.uniforms.uAlpha; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uAlpha = value; + } + }]); + + return ColorMatrixFilter; +}(core.Filter); + +// Americanized alias + + +exports.default = ColorMatrixFilter; +ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + +},{"../../core":65,"path":8}],151:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. You can + * use this filter to apply all manor of crazy warping effects. Currently the r + * property of the texture is used to offset the x and the g property of the texture + * is used to offset the y. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var DisplacementFilter = function (_core$Filter) { + _inherits(DisplacementFilter, _core$Filter); + + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param {number} scale - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + _classCallCheck(this, DisplacementFilter); + + var maskMatrix = new core.Matrix(); + + sprite.renderable = false; + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale / filterArea.xy;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n')); + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + + _this.uniforms.mapSampler = sprite._texture; + _this.uniforms.filterMatrix = maskMatrix; + _this.uniforms.scale = { x: 1, y: 1 }; + + if (scale === null || scale === undefined) { + scale = 20; + } + + _this.scale = new core.Point(scale, scale); + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + DisplacementFilter.prototype.apply = function apply(filterManager, input, output) { + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x; + this.uniforms.scale.y = this.scale.y; + + // draw the filter... + filterManager.applyFilter(this, input, output); + }; + + /** + * The texture used for the displacement map. Must be power of 2 sized texture. + * + * @member {PIXI.Texture} + */ + + + _createClass(DisplacementFilter, [{ + key: 'map', + get: function get() { + return this.uniforms.mapSampler; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.mapSampler = value; + } + }]); + + return DisplacementFilter; +}(core.Filter); + +exports.default = DisplacementFilter; + +},{"../../core":65,"path":8}],152:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * Basic FXAA implementation based on the code on geeks3d.com with the + * modification that the texture2DLod stuff was removed since it's + * unsupported by WebGL. + * + * @see https://github.com/mitsuhiko/webgl-meincraft + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + * + */ +var FXAAFilter = function (_core$Filter) { + _inherits(FXAAFilter, _core$Filter); + + /** + * + */ + function FXAAFilter() { + _classCallCheck(this, FXAAFilter); + + // TODO - needs work + return _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + '\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}', + // fragment shader + 'varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n')); + } + + return FXAAFilter; +}(core.Filter); + +exports.default = FXAAFilter; + +},{"../../core":65,"path":8}],153:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _FXAAFilter = require('./fxaa/FXAAFilter'); + +Object.defineProperty(exports, 'FXAAFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_FXAAFilter).default; + } +}); + +var _NoiseFilter = require('./noise/NoiseFilter'); + +Object.defineProperty(exports, 'NoiseFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NoiseFilter).default; + } +}); + +var _DisplacementFilter = require('./displacement/DisplacementFilter'); + +Object.defineProperty(exports, 'DisplacementFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplacementFilter).default; + } +}); + +var _BlurFilter = require('./blur/BlurFilter'); + +Object.defineProperty(exports, 'BlurFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurFilter).default; + } +}); + +var _BlurXFilter = require('./blur/BlurXFilter'); + +Object.defineProperty(exports, 'BlurXFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurXFilter).default; + } +}); + +var _BlurYFilter = require('./blur/BlurYFilter'); + +Object.defineProperty(exports, 'BlurYFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurYFilter).default; + } +}); + +var _ColorMatrixFilter = require('./colormatrix/ColorMatrixFilter'); + +Object.defineProperty(exports, 'ColorMatrixFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ColorMatrixFilter).default; + } +}); + +var _AlphaFilter = require('./alpha/AlphaFilter'); + +Object.defineProperty(exports, 'AlphaFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AlphaFilter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./alpha/AlphaFilter":143,"./blur/BlurFilter":144,"./blur/BlurXFilter":145,"./blur/BlurYFilter":146,"./colormatrix/ColorMatrixFilter":150,"./displacement/DisplacementFilter":151,"./fxaa/FXAAFilter":152,"./noise/NoiseFilter":154}],154:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Vico @vicocotea + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + */ + +/** + * A Noise effect filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var NoiseFilter = function (_core$Filter) { + _inherits(NoiseFilter, _core$Filter); + + /** + * @param {number} noise - The noise intensity, should be a normalized value in the range [0, 1]. + * @param {number} seed - A random seed for the noise generation. Default is `Math.random()`. + */ + function NoiseFilter() { + var noise = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0.5; + var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Math.random(); + + _classCallCheck(this, NoiseFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n')); + + _this.noise = noise; + _this.seed = seed; + return _this; + } + + /** + * The amount of noise to apply, this value should be in the range (0, 1]. + * + * @member {number} + * @default 0.5 + */ + + + _createClass(NoiseFilter, [{ + key: 'noise', + get: function get() { + return this.uniforms.uNoise; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uNoise = value; + } + + /** + * A seed value to apply to the random noise generation. `Math.random()` is a good value to use. + * + * @member {number} + */ + + }, { + key: 'seed', + get: function get() { + return this.uniforms.uSeed; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uSeed = value; + } + }]); + + return NoiseFilter; +}(core.Filter); + +exports.default = NoiseFilter; + +},{"../../core":65,"path":8}],155:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Holds all information related to an Interaction event + * + * @class + * @memberof PIXI.interaction + */ +var InteractionData = function () { + /** + * + */ + function InteractionData() { + _classCallCheck(this, InteractionData); + + /** + * This point stores the global coords of where the touch/mouse event happened + * + * @member {PIXI.Point} + */ + this.global = new core.Point(); + + /** + * The target DisplayObject that was interacted with + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * When passed to an event handler, this will be the original DOM Event that was captured + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent + * @see https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent + * @member {MouseEvent|TouchEvent|PointerEvent} + */ + this.originalEvent = null; + + /** + * Unique identifier for this interaction + * + * @member {number} + */ + this.identifier = null; + + /** + * Indicates whether or not the pointer device that created the event is the primary pointer. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary + * @type {Boolean} + */ + this.isPrimary = false; + + /** + * Indicates which button was pressed on the mouse or pointer device to trigger the event. + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button + * @type {number} + */ + this.button = 0; + + /** + * Indicates which buttons are pressed on the mouse or pointer device when the event is triggered. + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons + * @type {number} + */ + this.buttons = 0; + + /** + * The width of the pointer's contact along the x-axis, measured in CSS pixels. + * radiusX of TouchEvents will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width + * @type {number} + */ + this.width = 0; + + /** + * The height of the pointer's contact along the y-axis, measured in CSS pixels. + * radiusY of TouchEvents will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height + * @type {number} + */ + this.height = 0; + + /** + * The angle, in degrees, between the pointer device and the screen. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX + * @type {number} + */ + this.tiltX = 0; + + /** + * The angle, in degrees, between the pointer device and the screen. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY + * @type {number} + */ + this.tiltY = 0; + + /** + * The type of pointer that triggered the event. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType + * @type {string} + */ + this.pointerType = null; + + /** + * Pressure applied by the pointing device during the event. A Touch's force property + * will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure + * @type {number} + */ + this.pressure = 0; + + /** + * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch. + * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle + * @type {number} + */ + this.rotationAngle = 0; + + /** + * Twist of a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + * @type {number} + */ + this.twist = 0; + + /** + * Barrel pressure on a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + * @type {number} + */ + this.tangentialPressure = 0; + } + + /** + * The unique identifier of the pointer. It will be the same as `identifier`. + * @readonly + * @member {number} + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId + */ + + + /** + * This will return the local coordinates of the specified displayObject for this InteractionData + * + * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local + * coords off + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative + * to the DisplayObject + */ + InteractionData.prototype.getLocalPosition = function getLocalPosition(displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + + /** + * Copies properties from normalized event data. + * + * @param {Touch|MouseEvent|PointerEvent} event The normalized event data + */ + + + InteractionData.prototype.copyEvent = function copyEvent(event) { + // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite + // it with "false" on later events when our shim for it on touch events might not be + // accurate + if (event.isPrimary) { + this.isPrimary = true; + } + this.button = event.button; + // event.buttons is not available in all browsers (ie. Safari), but it does have a non-standard + // event.which property instead, which conveys the same information. + this.buttons = Number.isInteger(event.buttons) ? event.buttons : event.which; + this.width = event.width; + this.height = event.height; + this.tiltX = event.tiltX; + this.tiltY = event.tiltY; + this.pointerType = event.pointerType; + this.pressure = event.pressure; + this.rotationAngle = event.rotationAngle; + this.twist = event.twist || 0; + this.tangentialPressure = event.tangentialPressure || 0; + }; + + /** + * Resets the data for pooling. + */ + + + InteractionData.prototype.reset = function reset() { + // isPrimary is the only property that we really need to reset - everything else is + // guaranteed to be overwritten + this.isPrimary = false; + }; + + _createClass(InteractionData, [{ + key: 'pointerId', + get: function get() { + return this.identifier; + } + }]); + + return InteractionData; +}(); + +exports.default = InteractionData; + +},{"../core":65}],156:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Event class that mimics native DOM events. + * + * @class + * @memberof PIXI.interaction + */ +var InteractionEvent = function () { + /** + * + */ + function InteractionEvent() { + _classCallCheck(this, InteractionEvent); + + /** + * Whether this event will continue propagating in the tree + * + * @member {boolean} + */ + this.stopped = false; + + /** + * The object which caused this event to be dispatched. + * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}. + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * The object whose event listener’s callback is currently being invoked. + * + * @member {PIXI.DisplayObject} + */ + this.currentTarget = null; + + /** + * Type of the event + * + * @member {string} + */ + this.type = null; + + /** + * InteractionData related to this event + * + * @member {PIXI.interaction.InteractionData} + */ + this.data = null; + } + + /** + * Prevents event from reaching any objects other than the current object. + * + */ + + + InteractionEvent.prototype.stopPropagation = function stopPropagation() { + this.stopped = true; + }; + + /** + * Resets the event. + */ + + + InteractionEvent.prototype.reset = function reset() { + this.stopped = false; + this.currentTarget = null; + this.target = null; + }; + + return InteractionEvent; +}(); + +exports.default = InteractionEvent; + +},{}],157:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _InteractionData = require('./InteractionData'); + +var _InteractionData2 = _interopRequireDefault(_InteractionData); + +var _InteractionEvent = require('./InteractionEvent'); + +var _InteractionEvent2 = _interopRequireDefault(_InteractionEvent); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +var _InteractionTrackingData2 = _interopRequireDefault(_InteractionTrackingData); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _interactiveTarget = require('./interactiveTarget'); + +var _interactiveTarget2 = _interopRequireDefault(_interactiveTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// Mix interactiveTarget into core.DisplayObject.prototype, after deprecation has been handled +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _interactiveTarget2.default); + +var MOUSE_POINTER_ID = 1; + +// helpers for hitTest() - only used inside hitTest() +var hitTestEvent = { + target: null, + data: { + global: null + } +}; + +/** + * The interaction manager deals with mouse, touch and pointer events. Any DisplayObject can be interactive + * if its interactive parameter is set to true + * This manager also supports multitouch. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.interaction + * + * @class + * @extends EventEmitter + * @memberof PIXI.interaction + */ + +var InteractionManager = function (_EventEmitter) { + _inherits(InteractionManager, _EventEmitter); + + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + * @param {object} [options] - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Frequency increases the interaction events will be checked. + */ + function InteractionManager(renderer, options) { + _classCallCheck(this, InteractionManager); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + options = options || {}; + + /** + * The renderer this interaction manager works for. + * + * @member {PIXI.SystemRenderer} + */ + _this.renderer = renderer; + + /** + * Should default browser actions automatically be prevented. + * Does not apply to pointer events for backwards compatibility + * preventDefault on pointer events stops mouse events from firing + * Thus, for every pointer event, there will always be either a mouse of touch event alongside it. + * + * @member {boolean} + * @default true + */ + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + + /** + * Frequency in milliseconds that the mousemove, moveover & mouseout interaction events will be checked. + * + * @member {number} + * @default 10 + */ + _this.interactionFrequency = options.interactionFrequency || 10; + + /** + * The mouse data + * + * @member {PIXI.interaction.InteractionData} + */ + _this.mouse = new _InteractionData2.default(); + _this.mouse.identifier = MOUSE_POINTER_ID; + + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + + /** + * Actively tracked InteractionData + * + * @private + * @member {Object.} + */ + _this.activeInteractionData = {}; + _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; + + /** + * Pool of unused InteractionData + * + * @private + * @member {PIXI.interation.InteractionData[]} + */ + _this.interactionDataPool = []; + + /** + * An event data object to handle all the event tracking/dispatching + * + * @member {object} + */ + _this.eventData = new _InteractionEvent2.default(); + + /** + * The DOM element to bind to. + * + * @private + * @member {HTMLElement} + */ + _this.interactionDOMElement = null; + + /** + * This property determines if mousemove and touchmove events are fired only when the cursor + * is over the object. + * Setting to true will make things work more in line with how the DOM verison works. + * Setting to false can make things easier for things like dragging + * It is currently set to false as this is how PixiJS used to work. This will be set to true in + * future versions of pixi. + * + * @member {boolean} + * @default false + */ + _this.moveWhenInside = false; + + /** + * Have events been attached to the dom element? + * + * @private + * @member {boolean} + */ + _this.eventsAdded = false; + + /** + * Is the mouse hovering over the renderer? + * + * @private + * @member {boolean} + */ + _this.mouseOverRenderer = false; + + /** + * Does the device support touch events + * https://www.w3.org/TR/touch-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsTouchEvents = 'ontouchstart' in window; + + /** + * Does the device support pointer events + * https://www.w3.org/Submission/pointer-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsPointerEvents = !!window.PointerEvent; + + // this will make it so that you don't have to call bind all the time + + /** + * @private + * @member {Function} + */ + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerCancel = _this.onPointerCancel.bind(_this); + _this.processPointerCancel = _this.processPointerCancel.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOver = _this.onPointerOver.bind(_this); + + /** + * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor + * values, objects are handled as dictionaries of CSS values for interactionDOMElement, + * and functions are called instead of changing the CSS. + * Default CSS cursor values are provided for 'default' and 'pointer' modes. + * @member {Object.)>} + */ + _this.cursorStyles = { + default: 'inherit', + pointer: 'pointer' + }; + + /** + * The mode of the cursor that is being used. + * The value of this is a key from the cursorStyles dictionary. + * + * @member {string} + */ + _this.currentCursorMode = null; + + /** + * Internal cached let. + * + * @private + * @member {string} + */ + _this.cursor = null; + + /** + * Internal cached let. + * + * @private + * @member {PIXI.Point} + */ + _this._tempPoint = new core.Point(); + + /** + * The current resolution / device pixel ratio. + * + * @member {number} + * @default 1 + */ + _this.resolution = 1; + + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display + * object. + * + * @event PIXI.interaction.InteractionManager#mousedown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * + * @event PIXI.interaction.InteractionManager#rightdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. + * + * @event PIXI.interaction.InteractionManager#mouseup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * + * @event PIXI.interaction.InteractionManager#rightup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. + * + * @event PIXI.interaction.InteractionManager#click + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * + * @event PIXI.interaction.InteractionManager#rightclick + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. + * + * @event PIXI.interaction.InteractionManager#mouseupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. + * + * @event PIXI.interaction.InteractionManager#rightupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * + * @event PIXI.interaction.InteractionManager#mousemove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * + * @event PIXI.interaction.InteractionManager#mouseover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * + * @event PIXI.interaction.InteractionManager#mouseout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * + * @event PIXI.interaction.InteractionManager#pointerdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released over the display object. + * Not always fired when some buttons are held down while others are released. In those cases, + * use [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown} and + * [mouseup]{@link PIXI.interaction.InteractionManager#event:mouseup} instead. + * + * @event PIXI.interaction.InteractionManager#pointerup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a pointer event + * + * @event PIXI.interaction.InteractionManager#pointercancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * + * @event PIXI.interaction.InteractionManager#pointertap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}. + * + * @event PIXI.interaction.InteractionManager#pointerupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved while over the display object + * + * @event PIXI.interaction.InteractionManager#pointermove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved onto the display object + * + * @event PIXI.interaction.InteractionManager#pointerover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved off the display object + * + * @event PIXI.interaction.InteractionManager#pointerout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed on the display object. + * + * @event PIXI.interaction.InteractionManager#touchstart + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed from the display object. + * + * @event PIXI.interaction.InteractionManager#touchend + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a touch + * + * @event PIXI.interaction.InteractionManager#touchcancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * + * @event PIXI.interaction.InteractionManager#tap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. + * + * @event PIXI.interaction.InteractionManager#touchendoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is moved along the display object. + * + * @event PIXI.interaction.InteractionManager#touchmove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display. + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mousedown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#click + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightclick + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.DisplayObject#event:mousedown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.DisplayObject#event:rightdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mousemove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a pointer event. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointercancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointertap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointermove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchstart + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchend + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a touch. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchcancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#tap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchendoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is moved along the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchmove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + return _this; + } + + /** + * Hit tests a point against the display tree, returning the first interactive object that is hit. + * + * @param {PIXI.Point} globalPoint - A point to hit test with, in global space. + * @param {PIXI.Container} [root] - The root display object to start from. If omitted, defaults + * to the last rendered root of the associated renderer. + * @return {PIXI.DisplayObject} The hit display object, if any. + */ + + + InteractionManager.prototype.hitTest = function hitTest(globalPoint, root) { + // clear the target for our hit test + hitTestEvent.target = null; + // assign the global point + hitTestEvent.data.global = globalPoint; + // ensure safety of the root + if (!root) { + root = this.renderer._lastObjectRendered; + } + // run the hit test + this.processInteractive(hitTestEvent, root, null, true); + // return our found object - it'll be null if we didn't hit anything + + return hitTestEvent.target; + }; + + /** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate + * another DOM element to receive those events. + * + * @param {HTMLCanvasElement} element - the DOM element which will receive mouse and touch events. + * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). + */ + + + InteractionManager.prototype.setTargetElement = function setTargetElement(element) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.removeEvents(); + + this.interactionDOMElement = element; + + this.resolution = resolution; + + this.addEvents(); + }; + + /** + * Registers all the DOM events + * + * @private + */ + + + InteractionManager.prototype.addEvents = function addEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.INTERACTION); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; + this.interactionDOMElement.style['-ms-touch-action'] = 'none'; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = 'none'; + } + + /** + * These events are added first, so that if pointer events are normalised, they are fired + * in the same order as non-normalised events. ie. pointer event 1st, mouse / touch 2nd + */ + if (this.supportsPointerEvents) { + window.document.addEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); + // pointerout is fired in addition to pointerup (for touch events) and pointercancel + // we already handle those, so for the purposes of what we do in onPointerOut, we only + // care about the pointerleave event + this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); + window.addEventListener('pointercancel', this.onPointerCancel, true); + window.addEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.addEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); + window.addEventListener('mouseup', this.onPointerUp, true); + } + + // always look directly for touch events so that we can provide original data + // In a future version we should change this to being just a fallback and rely solely on + // PointerEvents whenever available + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); + } + + this.eventsAdded = true; + }; + + /** + * Removes all the DOM events that were previously registered + * + * @private + */ + + + InteractionManager.prototype.removeEvents = function removeEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.remove(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = ''; + this.interactionDOMElement.style['-ms-touch-action'] = ''; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = ''; + } + + if (this.supportsPointerEvents) { + window.document.removeEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); + window.removeEventListener('pointercancel', this.onPointerCancel, true); + window.removeEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.removeEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true); + window.removeEventListener('mouseup', this.onPointerUp, true); + } + + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); + } + + this.interactionDOMElement = null; + + this.eventsAdded = false; + }; + + /** + * Updates the state of interactive objects. + * Invoked by a throttled ticker update from {@link PIXI.ticker.shared}. + * + * @param {number} deltaTime - time delta since last tick + */ + + + InteractionManager.prototype.update = function update(deltaTime) { + this._deltaTime += deltaTime; + + if (this._deltaTime < this.interactionFrequency) { + return; + } + + this._deltaTime = 0; + + if (!this.interactionDOMElement) { + return; + } + + // if the user move the mouse this check has already been done using the mouse move! + if (this.didMove) { + this.didMove = false; + + return; + } + + this.cursor = null; + + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + for (var k in this.activeInteractionData) { + // eslint-disable-next-line no-prototype-builtins + if (this.activeInteractionData.hasOwnProperty(k)) { + var interactionData = this.activeInteractionData[k]; + + if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, true); + } + } + } + + this.setCursorMode(this.cursor); + + // TODO + }; + + /** + * Sets the current cursor mode, handling any callbacks or CSS style changes. + * + * @param {string} mode - cursor mode, a key from the cursorStyles dictionary + */ + + + InteractionManager.prototype.setCursorMode = function setCursorMode(mode) { + mode = mode || 'default'; + // if the mode didn't actually change, bail early + if (this.currentCursorMode === mode) { + return; + } + this.currentCursorMode = mode; + var style = this.cursorStyles[mode]; + + // only do things if there is a cursor style for it + if (style) { + switch (typeof style === 'undefined' ? 'undefined' : _typeof(style)) { + case 'string': + // string styles are handled as cursor CSS + this.interactionDOMElement.style.cursor = style; + break; + case 'function': + // functions are just called, and passed the cursor mode + style(mode); + break; + case 'object': + // if it is an object, assume that it is a dictionary of CSS styles, + // apply it to the interactionDOMElement + Object.assign(this.interactionDOMElement.style, style); + break; + } + } else if (typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) { + // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry + // for the mode, then assume that the dev wants it to be CSS for the cursor. + this.interactionDOMElement.style.cursor = mode; + } + }; + + /** + * Dispatches an event on the display object that was interacted with + * + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the display object in question + * @param {string} eventString - the name of the event (e.g, mousedown) + * @param {object} eventData - the event data object + * @private + */ + + + InteractionManager.prototype.dispatchEvent = function dispatchEvent(displayObject, eventString, eventData) { + if (!eventData.stopped) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + + displayObject.emit(eventString, eventData); + + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } + }; + + /** + * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. + * + * @param {PIXI.Point} point - the point that the result will be stored in + * @param {number} x - the x coord of the position to map + * @param {number} y - the y coord of the position to map + */ + + + InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint(point, x, y) { + var rect = void 0; + + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { x: 0, y: 0, width: 0, height: 0 }; + } else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + + var resolutionMultiplier = navigator.isCocoonJS ? this.resolution : 1.0 / this.resolution; + + point.x = (x - rect.left) * (this.interactionDOMElement.width / rect.width) * resolutionMultiplier; + point.y = (y - rect.top) * (this.interactionDOMElement.height / rect.height) * resolutionMultiplier; + }; + + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that + * is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param {Function} [func] - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point + * @param {boolean} [interactive] - Whether the displayObject is interactive + * @return {boolean} returns true if the displayObject hit the point + */ + + + InteractionManager.prototype.processInteractive = function processInteractive(interactionEvent, displayObject, func, hitTest, interactive) { + if (!displayObject || !displayObject.visible) { + return false; + } + + var point = interactionEvent.data.global; + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + interactive = displayObject.interactive || interactive; + + var hit = false; + var interactiveParent = interactive; + + // Flag here can set to false if the event is outside the parents hitArea or mask + var hitTestChildren = true; + + // If there is a hitArea, no need to test against anything else if the pointer is not within the hitArea + // There is also no longer a need to hitTest children. + if (displayObject.hitArea) { + if (hitTest) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (!displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hitTest = false; + hitTestChildren = false; + } else { + hit = true; + } + } + interactiveParent = false; + } + // If there is a mask, no need to test against anything else if the pointer is not within the mask + else if (displayObject._mask) { + if (hitTest) { + if (!displayObject._mask.containsPoint(point)) { + hitTest = false; + hitTestChildren = false; + } + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow PixiJS to completely ignore and bypass checking the displayObjects children. + if (hitTestChildren && displayObject.interactiveChildren && displayObject.children) { + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + + // time to get recursive.. if this function will return if something is hit.. + var childHit = this.processInteractive(interactionEvent, child, func, hitTest, interactiveParent); + + if (childHit) { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if (!child.parent) { + continue; + } + + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + + if (childHit) { + if (interactionEvent.target) { + hitTest = false; + } + hit = true; + } + } + } + } + + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit - but only if it was interactive, otherwise we need to keep + // looking for an interactive child, just in case we hit one + if (hitTest && !interactionEvent.target) { + // already tested against hitArea if it is defined + if (!displayObject.hitArea && displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = true; + } + } + } + + if (displayObject.interactive) { + if (hit && !interactionEvent.target) { + interactionEvent.target = displayObject; + } + + if (func) { + func(interactionEvent, displayObject, !!hit); + } + } + } + + return hit; + }; + + /** + * Is called when the pointer button is pressed down on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down + */ + + + InteractionManager.prototype.onPointerDown = function onPointerDown(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + /** + * No need to prevent default on natural pointer events, as there are no side effects + * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, + * so still need to be prevented. + */ + + // Guaranteed that there will be at least one event in events, and all events must have the same pointer type + + if (this.autoPreventDefault && events[0].isNormalized) { + originalEvent.preventDefault(); + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerDown, true); + + this.emit('pointerdown', interactionEvent); + if (event.pointerType === 'touch') { + this.emit('touchstart', interactionEvent); + } + // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event + else if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + } + }; + + /** + * Processes the result of the pointer down check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerDown = function processPointerDown(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + + if (hit) { + if (!displayObject.trackedPointers[id]) { + displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchstart', interactionEvent); + } else if (data.pointerType === 'mouse' || data.pointerType === 'pen') { + var isRightButton = data.button === 2; + + if (isRightButton) { + displayObject.trackedPointers[id].rightDown = true; + } else { + displayObject.trackedPointers[id].leftDown = true; + } + + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released + * @param {boolean} cancelled - true if the pointer is cancelled + * @param {Function} func - Function passed to {@link processInteractive} + */ + + + InteractionManager.prototype.onPointerComplete = function onPointerComplete(originalEvent, cancelled, func) { + var events = this.normalizeToPointerData(originalEvent); + + var eventLen = events.length; + + // if the event wasn't targeting our canvas, then consider it to be pointerupoutside + // in all cases (unless it was a pointercancel) + var eventAppend = originalEvent.target !== this.interactionDOMElement ? 'outside' : ''; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + // perform hit testing for events targeting our canvas or cancel events + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, func, cancelled || !eventAppend); + + this.emit(cancelled ? 'pointercancel' : 'pointerup' + eventAppend, interactionEvent); + + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + + this.emit(isRightButton ? 'rightup' + eventAppend : 'mouseup' + eventAppend, interactionEvent); + } else if (event.pointerType === 'touch') { + this.emit(cancelled ? 'touchcancel' : 'touchend' + eventAppend, interactionEvent); + this.releaseInteractionDataForPointerId(event.pointerId, interactionData); + } + } + }; + + /** + * Is called when the pointer button is cancelled + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerCancel = function onPointerCancel(event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') return; + + this.onPointerComplete(event, true, this.processPointerCancel); + }; + + /** + * Processes the result of the pointer cancel check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + */ + + + InteractionManager.prototype.processPointerCancel = function processPointerCancel(interactionEvent, displayObject) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + if (displayObject.trackedPointers[id] !== undefined) { + delete displayObject.trackedPointers[id]; + this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); + + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerUp = function onPointerUp(event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') return; + + this.onPointerComplete(event, false, this.processPointerUp); + }; + + /** + * Processes the result of the pointer up check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerUp = function processPointerUp(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + var trackingData = displayObject.trackedPointers[id]; + + var isTouch = data.pointerType === 'touch'; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + // need to track mouse down status in the mouse block so that we can emit + // event in a later block + var isMouseTap = false; + + // Mouse only + if (isMouse) { + var isRightButton = data.button === 2; + + var flags = _InteractionTrackingData2.default.FLAGS; + + var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; + + var isDown = trackingData !== undefined && trackingData.flags & test; + + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); + + if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); + // because we can confirm that the mousedown happened on this object, flag for later emit of pointertap + isMouseTap = true; + } + } else if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); + } + // update the down state of the tracking data + if (trackingData) { + if (isRightButton) { + trackingData.rightDown = false; + } else { + trackingData.leftDown = false; + } + } + } + + // Pointers and Touches, and Mouse + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchend', interactionEvent); + + if (trackingData) { + // emit pointertap if not a mouse, or if the mouse block decided it was a tap + if (!isMouse || isMouseTap) { + this.dispatchEvent(displayObject, 'pointertap', interactionEvent); + } + if (isTouch) { + this.dispatchEvent(displayObject, 'tap', interactionEvent); + // touches are no longer over (if they ever were) when we get the touchend + // so we should ensure that we don't keep pretending that they are + trackingData.over = false; + } + } + } else if (trackingData) { + this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); + } + // Only remove the tracking data if there is no over/down state still associated with it + if (trackingData && trackingData.none) { + delete displayObject.trackedPointers[id]; + } + }; + + /** + * Is called when the pointer moves across the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer moving + */ + + + InteractionManager.prototype.onPointerMove = function onPointerMove(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + if (events[0].pointerType === 'mouse' || events[0].pointerType === 'pen') { + this.didMove = true; + + this.cursor = null; + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + var interactive = event.pointerType === 'touch' ? this.moveWhenInside : true; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerMove, interactive); + this.emit('pointermove', interactionEvent); + if (event.pointerType === 'touch') this.emit('touchmove', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') this.emit('mousemove', interactionEvent); + } + + if (events[0].pointerType === 'mouse') { + this.setCursorMode(this.cursor); + + // TODO BUG for parents interactive object (border order issue) + } + }; + + /** + * Processes the result of the pointer move check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerMove = function processPointerMove(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var isTouch = data.pointerType === 'touch'; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + if (isMouse) { + this.processPointerOverOut(interactionEvent, displayObject, hit); + } + + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchmove', interactionEvent); + if (isMouse) this.dispatchEvent(displayObject, 'mousemove', interactionEvent); + } + }; + + /** + * Is called when the pointer is moved out of the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out + */ + + + InteractionManager.prototype.onPointerOut = function onPointerOut(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOut, so events will always be length 1 + var event = events[0]; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = false; + this.setCursorMode(null); + } + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, false); + + this.emit('pointerout', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseout', interactionEvent); + } else { + // we can get touchleave events after touchend, so we want to make sure we don't + // introduce memory leaks + this.releaseInteractionDataForPointerId(interactionData.identifier); + } + }; + + /** + * Processes the result of the pointer over/out check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerOverOut = function processPointerOverOut(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + var trackingData = displayObject.trackedPointers[id]; + + // if we just moused over the display object, then we need to track that state + if (hit && !trackingData) { + trackingData = displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + + if (trackingData === undefined) return; + + if (hit && this.mouseOverRenderer) { + if (!trackingData.over) { + trackingData.over = true; + this.dispatchEvent(displayObject, 'pointerover', interactionEvent); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseover', interactionEvent); + } + } + + // only change the cursor if it has not already been changed (by something deeper in the + // display tree) + if (isMouse && this.cursor === null) { + this.cursor = displayObject.cursor; + } + } else if (trackingData.over) { + trackingData.over = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseout', interactionEvent); + } + // if there is no mouse down information for the pointer, then it is safe to delete + if (trackingData.none) { + delete displayObject.trackedPointers[id]; + } + } + }; + + /** + * Is called when the pointer is moved into the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view + */ + + + InteractionManager.prototype.onPointerOver = function onPointerOver(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOver, so events will always be length 1 + var event = events[0]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = true; + } + + this.emit('pointerover', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseover', interactionEvent); + } + }; + + /** + * Get InteractionData for a given pointerId. Store that data as well + * + * @private + * @param {PointerEvent} event - Normalized pointer event, output from normalizeToPointerData + * @return {PIXI.interaction.InteractionData} - Interaction data for the given pointer identifier + */ + + + InteractionManager.prototype.getInteractionDataForPointerId = function getInteractionDataForPointerId(event) { + var pointerId = event.pointerId; + + var interactionData = void 0; + + if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { + interactionData = this.mouse; + } else if (this.activeInteractionData[pointerId]) { + interactionData = this.activeInteractionData[pointerId]; + } else { + interactionData = this.interactionDataPool.pop() || new _InteractionData2.default(); + interactionData.identifier = pointerId; + this.activeInteractionData[pointerId] = interactionData; + } + // copy properties from the event, so that we can make sure that touch/pointer specific + // data is available + interactionData.copyEvent(event); + + return interactionData; + }; + + /** + * Return unused InteractionData to the pool, for a given pointerId + * + * @private + * @param {number} pointerId - Identifier from a pointer event + */ + + + InteractionManager.prototype.releaseInteractionDataForPointerId = function releaseInteractionDataForPointerId(pointerId) { + var interactionData = this.activeInteractionData[pointerId]; + + if (interactionData) { + delete this.activeInteractionData[pointerId]; + interactionData.reset(); + this.interactionDataPool.push(interactionData); + } + }; + + /** + * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The event to be configured + * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent + * @param {PIXI.interaction.InteractionData} interactionData - The InteractionData that will be paired + * with the InteractionEvent + * @return {PIXI.interaction.InteractionEvent} the interaction event that was passed in + */ + + + InteractionManager.prototype.configureInteractionEventForDOMEvent = function configureInteractionEventForDOMEvent(interactionEvent, pointerEvent, interactionData) { + interactionEvent.data = interactionData; + + this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); + + // This is the way InteractionManager processed touch events before the refactoring, so I've kept + // it here. But it doesn't make that much sense to me, since mapPositionToPoint already factors + // in this.resolution, so this just divides by this.resolution twice for touch events... + if (navigator.isCocoonJS && pointerEvent.pointerType === 'touch') { + interactionData.global.x = interactionData.global.x / this.resolution; + interactionData.global.y = interactionData.global.y / this.resolution; + } + + // Not really sure why this is happening, but it's how a previous version handled things + if (pointerEvent.pointerType === 'touch') { + pointerEvent.globalX = interactionData.global.x; + pointerEvent.globalY = interactionData.global.y; + } + + interactionData.originalEvent = pointerEvent; + interactionEvent.reset(); + + return interactionEvent; + }; + + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * + * @private + * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event + * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer + * or mouse event, or a multiple normalized pointer events if there are multiple changed touches + */ + + + InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData(event) { + var normalizedEvents = []; + + if (this.supportsTouchEvents && event instanceof TouchEvent) { + for (var i = 0, li = event.changedTouches.length; i < li; i++) { + var touch = event.changedTouches[i]; + + if (typeof touch.button === 'undefined') touch.button = event.touches.length ? 1 : 0; + if (typeof touch.buttons === 'undefined') touch.buttons = event.touches.length ? 1 : 0; + if (typeof touch.isPrimary === 'undefined') { + touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart'; + } + if (typeof touch.width === 'undefined') touch.width = touch.radiusX || 1; + if (typeof touch.height === 'undefined') touch.height = touch.radiusY || 1; + if (typeof touch.tiltX === 'undefined') touch.tiltX = 0; + if (typeof touch.tiltY === 'undefined') touch.tiltY = 0; + if (typeof touch.pointerType === 'undefined') touch.pointerType = 'touch'; + if (typeof touch.pointerId === 'undefined') touch.pointerId = touch.identifier || 0; + if (typeof touch.pressure === 'undefined') touch.pressure = touch.force || 0.5; + touch.twist = 0; + touch.tangentialPressure = 0; + // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven + // support, and the fill ins are not quite the same + // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top + // left is not 0,0 on the page + if (typeof touch.layerX === 'undefined') touch.layerX = touch.offsetX = touch.clientX; + if (typeof touch.layerY === 'undefined') touch.layerY = touch.offsetY = touch.clientY; + + // mark the touch as normalized, just so that we know we did it + touch.isNormalized = true; + + normalizedEvents.push(touch); + } + } + // apparently PointerEvent subclasses MouseEvent, so yay + else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent))) { + if (typeof event.isPrimary === 'undefined') event.isPrimary = true; + if (typeof event.width === 'undefined') event.width = 1; + if (typeof event.height === 'undefined') event.height = 1; + if (typeof event.tiltX === 'undefined') event.tiltX = 0; + if (typeof event.tiltY === 'undefined') event.tiltY = 0; + if (typeof event.pointerType === 'undefined') event.pointerType = 'mouse'; + if (typeof event.pointerId === 'undefined') event.pointerId = MOUSE_POINTER_ID; + if (typeof event.pressure === 'undefined') event.pressure = 0.5; + event.twist = 0; + event.tangentialPressure = 0; + + // mark the mouse event as normalized, just so that we know we did it + event.isNormalized = true; + + normalizedEvents.push(event); + } else { + normalizedEvents.push(event); + } + + return normalizedEvents; + }; + + /** + * Destroys the interaction manager + * + */ + + + InteractionManager.prototype.destroy = function destroy() { + this.removeEvents(); + + this.removeAllListeners(); + + this.renderer = null; + + this.mouse = null; + + this.eventData = null; + + this.interactionDOMElement = null; + + this.onPointerDown = null; + this.processPointerDown = null; + + this.onPointerUp = null; + this.processPointerUp = null; + + this.onPointerCancel = null; + this.processPointerCancel = null; + + this.onPointerMove = null; + this.processPointerMove = null; + + this.onPointerOut = null; + this.processPointerOverOut = null; + + this.onPointerOver = null; + + this._tempPoint = null; + }; + + return InteractionManager; +}(_eventemitter2.default); + +exports.default = InteractionManager; + + +core.WebGLRenderer.registerPlugin('interaction', InteractionManager); +core.CanvasRenderer.registerPlugin('interaction', InteractionManager); + +},{"../core":65,"./InteractionData":155,"./InteractionEvent":156,"./InteractionTrackingData":158,"./interactiveTarget":160,"eventemitter3":3}],158:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * DisplayObjects with the {@link PIXI.interaction.interactiveTarget} mixin use this class to track interactions + * + * @class + * @private + * @memberof PIXI.interaction + */ +var InteractionTrackingData = function () { + /** + * @param {number} pointerId - Unique pointer id of the event + */ + function InteractionTrackingData(pointerId) { + _classCallCheck(this, InteractionTrackingData); + + this._pointerId = pointerId; + this._flags = InteractionTrackingData.FLAGS.NONE; + } + + /** + * + * @private + * @param {number} flag - The interaction flag to set + * @param {boolean} yn - Should the flag be set or unset + */ + + + InteractionTrackingData.prototype._doSet = function _doSet(flag, yn) { + if (yn) { + this._flags = this._flags | flag; + } else { + this._flags = this._flags & ~flag; + } + }; + + /** + * Unique pointer id of the event + * + * @readonly + * @member {number} + */ + + + _createClass(InteractionTrackingData, [{ + key: "pointerId", + get: function get() { + return this._pointerId; + } + + /** + * State of the tracking data, expressed as bit flags + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "flags", + get: function get() { + return this._flags; + } + + /** + * Set the flags for the tracking data + * + * @param {number} flags - Flags to set + */ + , + set: function set(flags) { + this._flags = flags; + } + + /** + * Is the tracked event inactive (not over or down)? + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "none", + get: function get() { + return this._flags === this.constructor.FLAGS.NONE; + } + + /** + * Is the tracked event over the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "over", + get: function get() { + return (this._flags & this.constructor.FLAGS.OVER) !== 0; + } + + /** + * Set the over flag + * + * @param {boolean} yn - Is the event over? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.OVER, yn); + } + + /** + * Did the right mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "rightDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.RIGHT_DOWN) !== 0; + } + + /** + * Set the right down flag + * + * @param {boolean} yn - Is the right mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.RIGHT_DOWN, yn); + } + + /** + * Did the left mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "leftDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.LEFT_DOWN) !== 0; + } + + /** + * Set the left down flag + * + * @param {boolean} yn - Is the left mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.LEFT_DOWN, yn); + } + }]); + + return InteractionTrackingData; +}(); + +exports.default = InteractionTrackingData; + + +InteractionTrackingData.FLAGS = Object.freeze({ + NONE: 0, + OVER: 1 << 0, + LEFT_DOWN: 1 << 1, + RIGHT_DOWN: 1 << 2 +}); + +},{}],159:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _InteractionData = require('./InteractionData'); + +Object.defineProperty(exports, 'InteractionData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionData).default; + } +}); + +var _InteractionManager = require('./InteractionManager'); + +Object.defineProperty(exports, 'InteractionManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionManager).default; + } +}); + +var _interactiveTarget = require('./interactiveTarget'); + +Object.defineProperty(exports, 'interactiveTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_interactiveTarget).default; + } +}); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +Object.defineProperty(exports, 'InteractionTrackingData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionTrackingData).default; + } +}); + +var _InteractionEvent = require('./InteractionEvent'); + +Object.defineProperty(exports, 'InteractionEvent', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionEvent).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./InteractionData":155,"./InteractionEvent":156,"./InteractionManager":157,"./InteractionTrackingData":158,"./interactiveTarget":160}],160:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * Default property values of interactive objects + * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties + * + * @private + * @name interactiveTarget + * @memberof PIXI.interaction + * @example + * function MyObject() {} + * + * Object.assign( + * core.DisplayObject.prototype, + * PIXI.interaction.interactiveTarget + * ); + */ +exports.default = { + + /** + * Enable interaction events for the DisplayObject. Touch, pointer and mouse + * events will not be emitted unless `interactive` is set to `true`. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.on('tap', (event) => { + * //handle event + * }); + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + interactive: false, + + /** + * Determines if the children to the displayObject can be clicked/touched + * Setting this to false allows PixiJS to bypass a recursive `hitTest` function + * + * @member {boolean} + * @memberof PIXI.Container# + */ + interactiveChildren: true, + + /** + * Interaction shape. Children will be hit first, then this shape will be checked. + * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.hitArea = new PIXI.Rectangle(0, 0, 100, 100); + * @member {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle} + * @memberof PIXI.DisplayObject# + */ + hitArea: null, + + /** + * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive + * Setting this changes the 'cursor' property to `'pointer'`. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.buttonMode = true; + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + get buttonMode() { + return this.cursor === 'pointer'; + }, + set buttonMode(value) { + if (value) { + this.cursor = 'pointer'; + } else if (this.cursor === 'pointer') { + this.cursor = null; + } + }, + + /** + * This defines what cursor mode is used when the mouse cursor + * is hovered over the displayObject. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.cursor = 'wait'; + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * + * @member {string} + * @memberof PIXI.DisplayObject# + */ + cursor: null, + + /** + * Internal set of all active pointers, by identifier + * + * @member {Map} + * @memberof PIXI.DisplayObject# + * @private + */ + get trackedPointers() { + if (this._trackedPointers === undefined) this._trackedPointers = {}; + + return this._trackedPointers; + }, + + /** + * Map of all tracked pointers, by identifier. Use trackedPointers to access. + * + * @private + * @type {Map} + */ + _trackedPointers: undefined +}; + +},{}],161:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.parse = parse; + +exports.default = function () { + return function bitmapFontParser(resource, next) { + // skip if no data or not xml data + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.XML) { + next(); + + return; + } + + // skip if not bitmap font data, using some silly duck-typing + if (resource.data.getElementsByTagName('page').length === 0 || resource.data.getElementsByTagName('info').length === 0 || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null) { + next(); + + return; + } + + var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; + + if (resource.isDataUrl) { + if (xmlUrl === '.') { + xmlUrl = ''; + } + + if (this.baseUrl && xmlUrl) { + // if baseurl has a trailing slash then add one to xmlUrl so the replace works below + if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { + xmlUrl += '/'; + } + } + } + + // remove baseUrl from xmlUrl + xmlUrl = xmlUrl.replace(this.baseUrl, ''); + + // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { + xmlUrl += '/'; + } + + var pages = resource.data.getElementsByTagName('page'); + var textures = {}; + + // Handle completed, when the number of textures + // load is the same number as references in the fnt file + var completed = function completed(page) { + textures[page.metadata.pageFile] = page.texture; + + if (Object.keys(textures).length === pages.length) { + parse(resource, textures); + next(); + } + }; + + for (var i = 0; i < pages.length; ++i) { + var pageFile = pages[i].getAttribute('file'); + var url = xmlUrl + pageFile; + var exists = false; + + // incase the image is loaded outside + // using the same loader, resource will be available + for (var name in this.resources) { + var bitmapResource = this.resources[name]; + + if (bitmapResource.url === url) { + bitmapResource.metadata.pageFile = pageFile; + if (bitmapResource.texture) { + completed(bitmapResource); + } else { + bitmapResource.onAfterMiddleware.add(completed); + } + exists = true; + break; + } + } + + // texture is not loaded, we'll attempt to add + // it to the load and add the texture to the list + if (!exists) { + // Standard loading options for images + var options = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: Object.assign({ pageFile: pageFile }, resource.metadata.imageMetadata), + parentResource: resource + }; + + this.add(url, options, completed); + } + } + }; +}; + +var _path = require('path'); + +var path = _interopRequireWildcard(_path); + +var _resourceLoader = require('resource-loader'); + +var _extras = require('../extras'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Register a BitmapText font from loader resource. + * + * @function parseBitmapFontData + * @memberof PIXI.loaders + * @param {PIXI.loaders.Resource} resource - Loader resource. + * @param {PIXI.Texture|PIXI.Texture[]} textures - List of textures for each page. + */ +function parse(resource, textures) { + resource.bitmapFont = _extras.BitmapText.registerFont(resource.data, textures); +} + +},{"../extras":141,"path":8,"resource-loader":36}],162:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.shared = exports.Resource = exports.textureParser = exports.getResourcePath = exports.spritesheetParser = exports.parseBitmapFontData = exports.bitmapFontParser = exports.Loader = undefined; + +var _bitmapFontParser = require('./bitmapFontParser'); + +Object.defineProperty(exports, 'bitmapFontParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_bitmapFontParser).default; + } +}); +Object.defineProperty(exports, 'parseBitmapFontData', { + enumerable: true, + get: function get() { + return _bitmapFontParser.parse; + } +}); + +var _spritesheetParser = require('./spritesheetParser'); + +Object.defineProperty(exports, 'spritesheetParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_spritesheetParser).default; + } +}); +Object.defineProperty(exports, 'getResourcePath', { + enumerable: true, + get: function get() { + return _spritesheetParser.getResourcePath; + } +}); + +var _textureParser = require('./textureParser'); + +Object.defineProperty(exports, 'textureParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_textureParser).default; + } +}); + +var _resourceLoader = require('resource-loader'); + +Object.defineProperty(exports, 'Resource', { + enumerable: true, + get: function get() { + return _resourceLoader.Resource; + } +}); + +var _Application = require('../core/Application'); + +var _Application2 = _interopRequireDefault(_Application); + +var _loader = require('./loader'); + +var _loader2 = _interopRequireDefault(_loader); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * This namespace contains APIs which extends the {@link https://github.com/englercj/resource-loader resource-loader} module + * for loading assets, data, and other resources dynamically. + * @example + * const loader = new PIXI.loaders.Loader(); + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.load((loader, resources) => { + * // resources.bunny + * // resources.spaceship + * }); + * @namespace PIXI.loaders + */ +exports.Loader = _loader2.default; + + +/** + * A premade instance of the loader that can be used to load resources. + * @name shared + * @memberof PIXI.loaders + * @type {PIXI.loaders.Loader} + */ +var shared = new _loader2.default(); + +shared.destroy = function () { + // protect destroying shared loader +}; + +exports.shared = shared; + +// Mixin the loader construction + +var AppPrototype = _Application2.default.prototype; + +AppPrototype._loader = null; + +/** + * Loader instance to help with asset loading. + * @name PIXI.Application#loader + * @type {PIXI.loaders.Loader} + */ +Object.defineProperty(AppPrototype, 'loader', { + get: function get() { + if (!this._loader) { + var sharedLoader = this._options.sharedLoader; + + this._loader = sharedLoader ? shared : new _loader2.default(); + } + + return this._loader; + } +}); + +// Override the destroy function +// making sure to destroy the current Loader +AppPrototype._parentDestroy = AppPrototype.destroy; +AppPrototype.destroy = function destroy(removeView, stageOptions) { + if (this._loader) { + this._loader.destroy(); + this._loader = null; + } + this._parentDestroy(removeView, stageOptions); +}; + +},{"../core/Application":43,"./bitmapFontParser":161,"./loader":163,"./spritesheetParser":164,"./textureParser":165,"resource-loader":36}],163:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _resourceLoader = require('resource-loader'); + +var _resourceLoader2 = _interopRequireDefault(_resourceLoader); + +var _blob = require('resource-loader/lib/middlewares/parsing/blob'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _textureParser = require('./textureParser'); + +var _textureParser2 = _interopRequireDefault(_textureParser); + +var _spritesheetParser = require('./spritesheetParser'); + +var _spritesheetParser2 = _interopRequireDefault(_spritesheetParser); + +var _bitmapFontParser = require('./bitmapFontParser'); + +var _bitmapFontParser2 = _interopRequireDefault(_bitmapFontParser); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader + * + * ```js + * const loader = PIXI.loader; // PixiJS exposes a premade instance for you to use. + * //or + * const loader = new PIXI.loaders.Loader(); // you can also create your own if you want + * + * const sprites = {}; + * + * // Chainable `add` to enqueue a resource + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.add('scoreFont', 'assets/score.fnt'); + * + * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. + * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). + * loader.pre(cachingMiddleware); + * + * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. + * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). + * loader.use(parsingMiddleware); + * + * // The `load` method loads the queue of resources, and calls the passed in callback called once all + * // resources have loaded. + * loader.load((loader, resources) => { + * // resources is an object where the key is the name of the resource loaded and the value is the resource object. + * // They have a couple default properties: + * // - `url`: The URL that the resource was loaded from + * // - `error`: The error that happened when trying to load (if any) + * // - `data`: The raw data that was loaded + * // also may contain other properties based on the middleware that runs. + * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); + * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); + * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); + * }); + * + * // throughout the process multiple signals can be dispatched. + * loader.onProgress.add(() => {}); // called once per loaded/errored file + * loader.onError.add(() => {}); // called once per errored file + * loader.onLoad.add(() => {}); // called once per loaded file + * loader.onComplete.add(() => {}); // called once when the queued resources all load. + * ``` + * + * @see https://github.com/englercj/resource-loader + * + * @class + * @extends module:resource-loader.ResourceLoader + * @memberof PIXI.loaders + */ +var Loader = function (_ResourceLoader) { + _inherits(Loader, _ResourceLoader); + + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + _classCallCheck(this, Loader); + + var _this = _possibleConstructorReturn(this, _ResourceLoader.call(this, baseUrl, concurrency)); + + _eventemitter2.default.call(_this); + + for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { + _this.use(Loader._pixiMiddleware[i]()); + } + + // Compat layer, translate the new v2 signals into old v1 events. + _this.onStart.add(function (l) { + return _this.emit('start', l); + }); + _this.onProgress.add(function (l, r) { + return _this.emit('progress', l, r); + }); + _this.onError.add(function (e, l, r) { + return _this.emit('error', e, l, r); + }); + _this.onLoad.add(function (l, r) { + return _this.emit('load', l, r); + }); + _this.onComplete.add(function (l, r) { + return _this.emit('complete', l, r); + }); + return _this; + } + + /** + * Adds a default middleware to the PixiJS loader. + * + * @static + * @param {Function} fn - The middleware to add. + */ + + + Loader.addPixiMiddleware = function addPixiMiddleware(fn) { + Loader._pixiMiddleware.push(fn); + }; + + /** + * Destroy the loader, removes references. + */ + + + Loader.prototype.destroy = function destroy() { + this.removeAllListeners(); + this.reset(); + }; + + return Loader; +}(_resourceLoader2.default); + +// Copy EE3 prototype (mixin) + + +exports.default = Loader; +for (var k in _eventemitter2.default.prototype) { + Loader.prototype[k] = _eventemitter2.default.prototype[k]; +} + +Loader._pixiMiddleware = [ +// parse any blob into more usable objects (e.g. Image) +_blob.blobMiddlewareFactory, +// parse any Image objects into textures +_textureParser2.default, +// parse any spritesheet data into multiple textures +_spritesheetParser2.default, +// parse bitmap font data into multiple textures +_bitmapFontParser2.default]; + +// Add custom extentions +var Resource = _resourceLoader2.default.Resource; + +Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); + +},{"./bitmapFontParser":161,"./spritesheetParser":164,"./textureParser":165,"eventemitter3":3,"resource-loader":36,"resource-loader/lib/middlewares/parsing/blob":37}],164:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function spritesheetParser(resource, next) { + var imageResourceName = resource.name + '_image'; + + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.JSON || !resource.data.frames || this.resources[imageResourceName]) { + next(); + + return; + } + + var loadOptions = { + crossOrigin: resource.crossOrigin, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + var resourcePath = getResourcePath(resource, this.baseUrl); + + // load the image for this sheet + this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + if (res.error) { + next(res.error); + + return; + } + + var spritesheet = new _core.Spritesheet(res.texture.baseTexture, resource.data, resource.url); + + spritesheet.parse(function () { + resource.spritesheet = spritesheet; + resource.textures = spritesheet.textures; + next(); + }); + }); + }; +}; + +exports.getResourcePath = getResourcePath; + +var _resourceLoader = require('resource-loader'); + +var _url = require('url'); + +var _url2 = _interopRequireDefault(_url); + +var _core = require('../core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function getResourcePath(resource, baseUrl) { + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + return resource.data.meta.image; + } + + return _url2.default.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); +} + +},{"../core":65,"resource-loader":36,"url":38}],165:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function textureParser(resource, next) { + // create a new texture if the data is an Image object + if (resource.data && resource.type === _resourceLoader.Resource.TYPE.IMAGE) { + resource.texture = _Texture2.default.fromLoader(resource.data, resource.url, resource.name); + } + next(); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"../core/textures/Texture":115,"resource-loader":36}],166:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); +var tempPolygon = new core.Polygon(); + +/** + * Base mesh class + * @class + * @extends PIXI.Container + * @memberof PIXI.mesh + */ + +var Mesh = function (_core$Container) { + _inherits(Mesh, _core$Container); + + /** + * @param {PIXI.Texture} texture - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts + */ + function Mesh(texture, vertices, uvs, indices, drawMode) { + _classCallCheck(this, Mesh); + + /** + * The texture of the Mesh + * + * @member {PIXI.Texture} + * @default PIXI.Texture.EMPTY + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._texture = texture || _Texture2.default.EMPTY; + + /** + * The Uvs of the Mesh + * + * @member {Float32Array} + */ + _this.uvs = uvs || new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + /** + * An array of vertices + * + * @member {Float32Array} + */ + _this.vertices = vertices || new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]); + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + // TODO auto generate this based on draw mode! + _this.indices = indices || new Uint16Array([0, 1, 3, 2]); + + /** + * Version of mesh uvs are dirty or not + * + * @member {number} + */ + _this.dirty = 0; + + /** + * Version of mesh indices + * + * @member {number} + */ + _this.indexDirty = 0; + + /** + * Version of mesh verticies array + * + * @member {number} + */ + _this.vertexDirty = 0; + + /** + * For backwards compatibility the default is to re-upload verticies each render call. + * Set this to `false` and increase `vertexDirty` to manually re-upload the buffer. + * + * @member {boolean} + */ + _this.autoUpdate = true; + + /** + * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove + * any blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles + * to overlap a bit with each other. + * + * @member {number} + */ + _this.canvasPadding = core.settings.MESH_CANVAS_PADDING; + + /** + * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts + * + * @member {number} + * @see PIXI.mesh.Mesh.DRAW_MODES + */ + _this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH; + + /** + * The default shader that is used if a mesh doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + _this.shader = null; + + /** + * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any + * tint effect. + * + * @member {number} + */ + _this.tintRgb = new Float32Array([1, 1, 1]); + + /** + * A map of renderer IDs to webgl render data + * + * @private + * @member {object} + */ + _this._glDatas = {}; + + /** + * transform that is applied to UV to get the texture coords + * its updated independently from texture uvTransform + * updates of uvs are tied to that thing + * + * @member {PIXI.TextureMatrix} + * @private + */ + _this._uvTransform = new core.TextureMatrix(_this._texture); + + /** + * whether or not upload uvTransform to shader + * if its false, then uvs should be pre-multiplied + * if you change it for generated mesh, please call 'refresh(true)' + * @member {boolean} + * @default false + */ + _this.uploadUvTransform = false; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * @member {string} + * @default 'mesh' + */ + _this.pluginName = 'mesh'; + return _this; + } + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - a reference to the WebGL renderer + */ + + + Mesh.prototype._renderWebGL = function _renderWebGL(renderer) { + this.refresh(); + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + + + Mesh.prototype._renderCanvas = function _renderCanvas(renderer) { + this.refresh(); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Mesh.prototype._onTextureUpdate = function _onTextureUpdate() { + this._uvTransform.texture = this._texture; + this.refresh(); + }; + + /** + * multiplies uvs only if uploadUvTransform is false + * call it after you change uvs manually + * make sure that texture is valid + */ + + + Mesh.prototype.multiplyUvs = function multiplyUvs() { + if (!this.uploadUvTransform) { + this._uvTransform.multiplyUvs(this.uvs); + } + }; + + /** + * Refreshes uvs for generated meshes (rope, plane) + * sometimes refreshes vertices too + * + * @param {boolean} [forceUpdate=false] if true, matrices will be updated any case + */ + + + Mesh.prototype.refresh = function refresh(forceUpdate) { + if (this.autoUpdate) { + this.vertexDirty++; + } + if (this._uvTransform.update(forceUpdate)) { + this._refresh(); + } + }; + + /** + * re-calculates mesh coords + * @protected + */ + + + Mesh.prototype._refresh = function _refresh() {} + /* empty */ + + + /** + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + */ + ; + + Mesh.prototype._calculateBounds = function _calculateBounds() { + // TODO - we can cache local bounds and use them if they are dirty (like graphics) + this._bounds.addVertices(this.transform, this.vertices, 0, this.vertices.length); + }; + + /** + * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Mesh.prototype.containsPoint = function containsPoint(point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + + this.worldTransform.applyInverse(point, tempPoint); + + var vertices = this.vertices; + var points = tempPolygon.points; + var indices = this.indices; + var len = this.indices.length; + var step = this.drawMode === Mesh.DRAW_MODES.TRIANGLES ? 3 : 1; + + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + + return false; + }; + + /** + * The texture that the mesh uses. + * + * @member {PIXI.Texture} + */ + + + /** + * Destroys the Mesh object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + Mesh.prototype.destroy = function destroy(options) { + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._glDatas) { + var data = this._glDatas[id]; + + if (data.destroy) { + data.destroy(); + } else { + if (data.vertexBuffer) { + data.vertexBuffer.destroy(); + data.vertexBuffer = null; + } + if (data.indexBuffer) { + data.indexBuffer.destroy(); + data.indexBuffer = null; + } + if (data.uvBuffer) { + data.uvBuffer.destroy(); + data.uvBuffer = null; + } + if (data.vao) { + data.vao.destroy(); + data.vao = null; + } + } + } + + this._glDatas = null; + + _core$Container.prototype.destroy.call(this, options); + }; + + _createClass(Mesh, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + + /** + * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return core.utils.rgb2hex(this.tintRgb); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tintRgb = core.utils.hex2rgb(value, this.tintRgb); + } + }]); + + return Mesh; +}(core.Container); + +/** + * Different drawing buffer modes supported + * + * @static + * @constant + * @type {object} + * @property {number} TRIANGLE_MESH + * @property {number} TRIANGLES + */ + + +exports.default = Mesh; +Mesh.DRAW_MODES = { + TRIANGLE_MESH: 0, + TRIANGLES: 1 +}; + +},{"../core":65,"../core/textures/Texture":115}],167:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Plane2 = require('./Plane'); + +var _Plane3 = _interopRequireDefault(_Plane2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DEFAULT_BORDER_SIZE = 10; + +/** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.fromImage('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
+ *      A                          B
+ *    +---+----------------------+---+
+ *  C | 1 |          2           | 3 |
+ *    +---+----------------------+---+
+ *    |   |                      |   |
+ *    | 4 |          5           | 6 |
+ *    |   |                      |   |
+ *    +---+----------------------+---+
+ *  D | 7 |          8           | 9 |
+ *    +---+----------------------+---+
+
+ *  When changing this objects width and/or height:
+ *     areas 1 3 7 and 9 will remain unscaled.
+ *     areas 2 and 8 will be stretched horizontally
+ *     areas 4 and 6 will be stretched vertically
+ *     area 5 will be stretched both horizontally and vertically
+ * 
+ * + * @class + * @extends PIXI.mesh.Plane + * @memberof PIXI.mesh + * + */ + +var NineSlicePlane = function (_Plane) { + _inherits(NineSlicePlane, _Plane); + + /** + * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. + * @param {int} [leftWidth=10] size of the left vertical bar (A) + * @param {int} [topHeight=10] size of the top horizontal bar (C) + * @param {int} [rightWidth=10] size of the right vertical bar (B) + * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) + */ + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + _classCallCheck(this, NineSlicePlane); + + var _this = _possibleConstructorReturn(this, _Plane.call(this, texture, 4, 4)); + + _this._origWidth = texture.orig.width; + _this._origHeight = texture.orig.height; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._width = _this._origWidth; + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._height = _this._origHeight; + + /** + * The width of the left column (a) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; + + /** + * The width of the right column (b) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; + + /** + * The height of the top row (c) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; + + /** + * The height of the bottom row (d) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; + + _this.refresh(true); + return _this; + } + + /** + * Updates the horizontal vertices. + * + */ + + + NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices() { + var vertices = this.vertices; + + var h = this._topHeight + this._bottomHeight; + var scale = this._height > h ? 1.0 : this._height / h; + + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight * scale; + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + }; + + /** + * Updates the vertical vertices. + * + */ + + + NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices() { + var vertices = this.vertices; + + var w = this._leftWidth + this._rightWidth; + var scale = this._width > w ? 1.0 : this._width / w; + + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth * scale; + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with. + */ + + + NineSlicePlane.prototype._renderCanvas = function _renderCanvas(renderer) { + var context = renderer.context; + + context.globalAlpha = this.worldAlpha; + renderer.setBlendMode(this.blendMode); + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels || this.roundPixels) { // #CUSTOM + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + var base = this._texture.baseTexture; + var textureSource = base.source; + var w = base.width * base.resolution; + var h = base.height * base.resolution; + + this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11); + this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13); + this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15); + this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19); + this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21); + this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23); + this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27); + this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29); + this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31); + }; + + /** + * Renders one segment of the plane. + * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure + * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used. + * + * @private + * @param {CanvasRenderingContext2D} context - The context to draw with. + * @param {CanvasImageSource} textureSource - The source to draw. + * @param {number} w - width of the texture + * @param {number} h - height of the texture + * @param {number} x1 - x index 1 + * @param {number} y1 - y index 1 + * @param {number} x2 - x index 2 + * @param {number} y2 - y index 2 + */ + + + NineSlicePlane.prototype.drawSegment = function drawSegment(context, textureSource, w, h, x1, y1, x2, y2) { + // otherwise you get weird results when using slices of that are 0 wide or high. + var uvs = this.uvs; + var vertices = this.vertices; + + var sw = (uvs[x2] - uvs[x1]) * w; + var sh = (uvs[y2] - uvs[y1]) * h; + var dw = vertices[x2] - vertices[x1]; + var dh = vertices[y2] - vertices[y1]; + + // make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn. + if (sw < 1) { + sw = 1; + } + + if (sh < 1) { + sh = 1; + } + + // make sure destination is at least 1 pixel wide and high, otherwise you get + // lines when rendering close to original size. + if (dw < 1) { + dw = 1; + } + + if (dh < 1) { + dh = 1; + } + + context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh); + }; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + + /** + * Refreshes NineSlicePlane coords. All of them. + */ + NineSlicePlane.prototype._refresh = function _refresh() { + _Plane.prototype._refresh.call(this); + + var uvs = this.uvs; + var texture = this._texture; + + this._origWidth = texture.orig.width; + this._origHeight = texture.orig.height; + + var _uvw = 1.0 / this._origWidth; + var _uvh = 1.0 / this._origHeight; + + uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; + uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - _uvw * this._rightWidth; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - _uvh * this._bottomHeight; + + this.updateHorizontalVertices(); + this.updateVerticalVertices(); + + this.dirty++; + + this.multiplyUvs(); + }; + + _createClass(NineSlicePlane, [{ + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + this._refresh(); + } + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + this._refresh(); + } + + /** + * The width of the left column + * + * @member {number} + */ + + }, { + key: 'leftWidth', + get: function get() { + return this._leftWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._leftWidth = value; + this._refresh(); + } + + /** + * The width of the right column + * + * @member {number} + */ + + }, { + key: 'rightWidth', + get: function get() { + return this._rightWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rightWidth = value; + this._refresh(); + } + + /** + * The height of the top row + * + * @member {number} + */ + + }, { + key: 'topHeight', + get: function get() { + return this._topHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._topHeight = value; + this._refresh(); + } + + /** + * The height of the bottom row + * + * @member {number} + */ + + }, { + key: 'bottomHeight', + get: function get() { + return this._bottomHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._bottomHeight = value; + this._refresh(); + } + }]); + + return NineSlicePlane; +}(_Plane3.default); + +exports.default = NineSlicePlane; + +},{"./Plane":168}],168:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The Plane allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Plane = function (_Mesh) { + _inherits(Plane, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the Plane. + * @param {number} [verticesX=10] - The number of vertices in the x-axis + * @param {number} [verticesY=10] - The number of vertices in the y-axis + */ + function Plane(texture, verticesX, verticesY) { + _classCallCheck(this, Plane); + + /** + * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this._ready = true; + + _this.verticesX = verticesX || 10; + _this.verticesY = verticesY || 10; + + _this.drawMode = _Mesh3.default.DRAW_MODES.TRIANGLES; + _this.refresh(); + return _this; + } + + /** + * Refreshes plane coordinates + * + */ + + + Plane.prototype._refresh = function _refresh() { + var texture = this._texture; + var total = this.verticesX * this.verticesY; + var verts = []; + var colors = []; + var uvs = []; + var indices = []; + + var segmentsX = this.verticesX - 1; + var segmentsY = this.verticesY - 1; + + var sizeX = texture.width / segmentsX; + var sizeY = texture.height / segmentsY; + + for (var i = 0; i < total; i++) { + var x = i % this.verticesX; + var y = i / this.verticesX | 0; + + verts.push(x * sizeX, y * sizeY); + + uvs.push(x / segmentsX, y / segmentsY); + } + + // cons + + var totalSub = segmentsX * segmentsY; + + for (var _i = 0; _i < totalSub; _i++) { + var xpos = _i % segmentsX; + var ypos = _i / segmentsX | 0; + + var value = ypos * this.verticesX + xpos; + var value2 = ypos * this.verticesX + xpos + 1; + var value3 = (ypos + 1) * this.verticesX + xpos; + var value4 = (ypos + 1) * this.verticesX + xpos + 1; + + indices.push(value, value2, value3); + indices.push(value2, value4, value3); + } + + // console.log(indices) + this.vertices = new Float32Array(verts); + this.uvs = new Float32Array(uvs); + this.colors = new Float32Array(colors); + this.indices = new Uint16Array(indices); + + this.dirty++; + this.indexDirty++; + + this.multiplyUvs(); + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Plane.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh3.default.prototype._onTextureUpdate.call(this); + + // wait for the Plane ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + return Plane; +}(_Mesh3.default); + +exports.default = Plane; + +},{"./Mesh":166}],169:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The rope allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Rope = function (_Mesh) { + _inherits(Rope, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the rope. + * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. + */ + function Rope(texture, points) { + _classCallCheck(this, Rope); + + /** + * An array of points that determine the rope + * + * @member {PIXI.Point[]} + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this.points = points; + + /** + * An array of vertices used to construct this rope. + * + * @member {Float32Array} + */ + _this.vertices = new Float32Array(points.length * 4); + + /** + * The WebGL Uvs of the rope. + * + * @member {Float32Array} + */ + _this.uvs = new Float32Array(points.length * 4); + + /** + * An array containing the color components + * + * @member {Float32Array} + */ + _this.colors = new Float32Array(points.length * 2); + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + _this.indices = new Uint16Array(points.length * 2); + + /** + * refreshes vertices on every updateTransform + * @member {boolean} + * @default true + */ + _this.autoUpdate = true; + + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Rope.prototype._refresh = function _refresh() { + var points = this.points; + + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1 || !this._texture._uvs) { + return; + } + + // if the number of points has changed we will need to recreate the arraybuffers + if (this.vertices.length / 4 !== points.length) { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + + for (var i = 1; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + var amount = i / (total - 1); + + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + + // ensure that the changes are uploaded + this.dirty++; + this.indexDirty++; + + this.multiplyUvs(); + this.refreshVertices(); + }; + + /** + * refreshes vertices of Rope mesh + */ + + + Rope.prototype.refreshVertices = function refreshVertices() { + var points = this.points; + + if (points.length < 1) { + return; + } + + var lastPoint = points[0]; + var nextPoint = void 0; + var perpX = 0; + var perpY = 0; + + // this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } else { + nextPoint = point; + } + + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + + var ratio = (1 - i / (total - 1)) * 10; + + if (ratio > 1) { + ratio = 1; + } + + var perpLength = Math.sqrt(perpX * perpX + perpY * perpY); + var num = this._texture.height / 2; // (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; + + perpX /= perpLength; + perpY /= perpLength; + + perpX *= num; + perpY *= num; + + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + + lastPoint = point; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + Rope.prototype.updateTransform = function updateTransform() { + if (this.autoUpdate) { + this.refreshVertices(); + } + this.containerUpdateTransform(); + }; + + return Rope; +}(_Mesh3.default); + +exports.default = Rope; + +},{"./Mesh":166}],170:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Renderer dedicated to meshes. + * + * @class + * @private + * @memberof PIXI + */ +var MeshSpriteRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The renderer this downport works for + */ + function MeshSpriteRenderer(renderer) { + _classCallCheck(this, MeshSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the Mesh + * + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var context = renderer.context; + + var transform = mesh.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels || this.roundPixels) { // #CUSTOM + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + renderer.context.globalAlpha = mesh.worldAlpha; + renderer.setBlendMode(mesh.blendMode); + + if (mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH) { + this._renderTriangleMesh(mesh); + } else { + this._renderTriangles(mesh); + } + }; + + /** + * Draws the object in Triangle Mesh mode + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype._renderTriangleMesh = function _renderTriangleMesh(mesh) { + // draw triangles!! + var length = mesh.vertices.length / 2; + + for (var i = 0; i < length - 2; i++) { + // draw some triangles! + var index = i * 2; + + this._renderDrawTriangle(mesh, index, index + 2, index + 4); + } + }; + + /** + * Draws the object in triangle mode using canvas + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + */ + + + MeshSpriteRenderer.prototype._renderTriangles = function _renderTriangles(mesh) { + // draw triangles!! + var indices = mesh.indices; + var length = indices.length; + + for (var i = 0; i < length; i += 3) { + // draw some triangles! + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderDrawTriangle(mesh, index0, index1, index2); + } + }; + + /** + * Draws one of the triangles that from the Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + * @param {number} index0 - the index of the first vertex + * @param {number} index1 - the index of the second vertex + * @param {number} index2 - the index of the third vertex + */ + + + MeshSpriteRenderer.prototype._renderDrawTriangle = function _renderDrawTriangle(mesh, index0, index1, index2) { + var context = this.renderer.context; + var uvs = mesh.uvs; + var vertices = mesh.vertices; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var base = texture.baseTexture; + var textureSource = base.source; + var textureWidth = base.width; + var textureHeight = base.height; + + var u0 = void 0; + var u1 = void 0; + var u2 = void 0; + var v0 = void 0; + var v1 = void 0; + var v2 = void 0; + + if (mesh.uploadUvTransform) { + var ut = mesh._uvTransform.mapCoord; + + u0 = (uvs[index0] * ut.a + uvs[index0 + 1] * ut.c + ut.tx) * base.width; + u1 = (uvs[index1] * ut.a + uvs[index1 + 1] * ut.c + ut.tx) * base.width; + u2 = (uvs[index2] * ut.a + uvs[index2 + 1] * ut.c + ut.tx) * base.width; + v0 = (uvs[index0] * ut.b + uvs[index0 + 1] * ut.d + ut.ty) * base.height; + v1 = (uvs[index1] * ut.b + uvs[index1 + 1] * ut.d + ut.ty) * base.height; + v2 = (uvs[index2] * ut.b + uvs[index2 + 1] * ut.d + ut.ty) * base.height; + } else { + u0 = uvs[index0] * base.width; + u1 = uvs[index1] * base.width; + u2 = uvs[index2] * base.width; + v0 = uvs[index0 + 1] * base.height; + v1 = uvs[index1 + 1] * base.height; + v2 = uvs[index2 + 1] * base.height; + } + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + var canvasPadding = mesh.canvasPadding / this.renderer.resolution; + + if (canvasPadding > 0) { + var paddingX = canvasPadding / Math.abs(mesh.worldTransform.a); + var paddingY = canvasPadding / Math.abs(mesh.worldTransform.d); + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt(normX * normX + normY * normY); + + x0 = centerX + normX / dist * (dist + paddingX); + y0 = centerY + normY / dist * (dist + paddingY); + + // + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x1 = centerX + normX / dist * (dist + paddingX); + y1 = centerY + normY / dist * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x2 = centerX + normX / dist * (dist + paddingX); + y2 = centerY + normY / dist * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2; + var deltaA = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2; + var deltaB = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2; + var deltaC = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2; + var deltaD = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2; + var deltaE = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2; + var deltaF = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2; + + context.transform(deltaA / delta, deltaD / delta, deltaB / delta, deltaE / delta, deltaC / delta, deltaF / delta); + + context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + + context.restore(); + this.renderer.invalidateBlendMode(); + }; + + /** + * Renders a flat Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - The Mesh to render + */ + + + MeshSpriteRenderer.prototype.renderMeshFlat = function renderMeshFlat(mesh) { + var context = this.renderer.context; + var vertices = mesh.vertices; + var length = vertices.length / 2; + + // this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; ++i) { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var y0 = vertices[index + 1]; + + var x1 = vertices[index + 2]; + var y1 = vertices[index + 3]; + + var x2 = vertices[index + 4]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + }; + + /** + * destroy the the renderer. + * + */ + + + MeshSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return MeshSpriteRenderer; +}(); + +exports.default = MeshSpriteRenderer; + + +core.CanvasRenderer.registerPlugin('mesh', MeshSpriteRenderer); + +},{"../../core":65,"../Mesh":166}],171:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh = require('./Mesh'); + +Object.defineProperty(exports, 'Mesh', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Mesh).default; + } +}); + +var _MeshRenderer = require('./webgl/MeshRenderer'); + +Object.defineProperty(exports, 'MeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_MeshRenderer).default; + } +}); + +var _CanvasMeshRenderer = require('./canvas/CanvasMeshRenderer'); + +Object.defineProperty(exports, 'CanvasMeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasMeshRenderer).default; + } +}); + +var _Plane = require('./Plane'); + +Object.defineProperty(exports, 'Plane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Plane).default; + } +}); + +var _NineSlicePlane = require('./NineSlicePlane'); + +Object.defineProperty(exports, 'NineSlicePlane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NineSlicePlane).default; + } +}); + +var _Rope = require('./Rope'); + +Object.defineProperty(exports, 'Rope', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rope).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./Mesh":166,"./NineSlicePlane":167,"./Plane":168,"./Rope":169,"./canvas/CanvasMeshRenderer":170,"./webgl/MeshRenderer":172}],172:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var matrixIdentity = core.Matrix.IDENTITY; + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var MeshRenderer = function (_core$ObjectRenderer) { + _inherits(MeshRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function MeshRenderer(renderer) { + _classCallCheck(this, MeshRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + MeshRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n'); + }; + + /** + * renders mesh + * + * @param {PIXI.mesh.Mesh} mesh mesh instance + */ + + + MeshRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var gl = renderer.gl; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var glData = mesh._glDatas[renderer.CONTEXT_UID]; + + if (!glData) { + renderer.bindVao(null); + + glData = { + shader: this.shader, + vertexBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.vertices, gl.STREAM_DRAW), + uvBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.uvs, gl.STREAM_DRAW), + indexBuffer: _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, mesh.indices, gl.STATIC_DRAW), + // build the vao object that will render.. + vao: null, + dirty: mesh.dirty, + indexDirty: mesh.indexDirty, + vertexDirty: mesh.vertexDirty + }; + + // build the vao object that will render.. + glData.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(glData.indexBuffer).addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0).addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); + + mesh._glDatas[renderer.CONTEXT_UID] = glData; + } + + renderer.bindVao(glData.vao); + + if (mesh.dirty !== glData.dirty) { + glData.dirty = mesh.dirty; + glData.uvBuffer.upload(mesh.uvs); + } + + if (mesh.indexDirty !== glData.indexDirty) { + glData.indexDirty = mesh.indexDirty; + glData.indexBuffer.upload(mesh.indices); + } + + if (mesh.vertexDirty !== glData.vertexDirty) { + glData.vertexDirty = mesh.vertexDirty; + glData.vertexBuffer.upload(mesh.vertices); + } + + renderer.bindShader(glData.shader); + + glData.shader.uniforms.uSampler = renderer.bindTexture(texture); + + renderer.state.setBlendMode(core.utils.correctBlendMode(mesh.blendMode, texture.baseTexture.premultipliedAlpha)); + + if (glData.shader.uniforms.uTransform) { + if (mesh.uploadUvTransform) { + glData.shader.uniforms.uTransform = mesh._uvTransform.mapCoord.toArray(true); + } else { + glData.shader.uniforms.uTransform = matrixIdentity.toArray(true); + } + } + glData.shader.uniforms.translationMatrix = mesh.worldTransform.toArray(true); + + glData.shader.uniforms.uColor = core.utils.premultiplyRgba(mesh.tintRgb, mesh.worldAlpha, glData.shader.uniforms.uColor, texture.baseTexture.premultipliedAlpha); + + var drawMode = mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + glData.vao.draw(drawMode, mesh.indices.length, 0); + }; + + return MeshRenderer; +}(core.ObjectRenderer); + +exports.default = MeshRenderer; + + +core.WebGLRenderer.registerPlugin('mesh', MeshRenderer); + +},{"../../core":65,"../Mesh":166,"path":8,"pixi-gl-core":15}],173:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _utils = require('../core/utils'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that most advanced + * functionality will not work. ParticleContainer implements the basic object transform (position, scale, rotation) + * and some advanced functionality like tint (as of v4.5.6). + * Other more advanced functionality like masking, children, filters, etc will not work on sprites in this batch. + * + * It's extremely easy to use : + * + * ```js + * let container = new ParticleContainer(); + * + * for (let i = 0; i < 100; ++i) + * { + * let sprite = new PIXI.Sprite.fromImage("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be rendered at the speed of light. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.particles + */ +var ParticleContainer = function (_core$Container) { + _inherits(ParticleContainer, _core$Container); + + /** + * @param {number} [maxSize=1500] - The maximum number of particles that can be rendered by the container. + * Affects size of allocated buffers. + * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.vertices=false] - When true, vertices be uploaded and applied. + * if sprite's ` scale/anchor/trim/frame/orig` is dynamic, please set `true`. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.tint=false] - When true, alpha and tint be uploaded and applied. + * @param {number} [batchSize=16384] - Number of particles per batch. If less than maxSize, it uses maxSize instead. + * @param {boolean} [autoResize=false] If true, container allocates more batches in case + * there are more than `maxSize` particles. + */ + function ParticleContainer() { + var maxSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1500; + var properties = arguments[1]; + var batchSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 16384; + var autoResize = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + _classCallCheck(this, ParticleContainer); + + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + var maxBatchSize = 16384; + + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + + if (batchSize > maxSize) { + batchSize = maxSize; + } + + /** + * Set properties to be dynamic (true) / static (false) + * + * @member {boolean[]} + * @private + */ + _this._properties = [false, true, false, false, false]; + + /** + * @member {number} + * @private + */ + _this._maxSize = maxSize; + + /** + * @member {number} + * @private + */ + _this._batchSize = batchSize; + + /** + * @member {object} + * @private + */ + _this._glBuffers = {}; + + /** + * for every batch stores _updateID corresponding to the last change in that batch + * @member {number[]} + * @private + */ + _this._bufferUpdateIDs = []; + + /** + * when child inserted, removed or changes position this number goes up + * @member {number[]} + * @private + */ + _this._updateID = 0; + + /** + * @member {boolean} + * + */ + _this.interactiveChildren = false; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` + * to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * If true, container allocates more batches in case there are more than `maxSize` particles. + * @member {boolean} + * @default false + */ + _this.autoResize = autoResize; + + /** + * Used for canvas renderering. If true then the elements will be positioned at the + * nearest pixel. This provides a nice speed boost. + * + * @member {boolean} + * @default true; + */ + _this.roundPixels = true; + + /** + * The texture used to render the children. + * + * @readonly + * @member {BaseTexture} + */ + _this.baseTexture = null; + + _this.setProperties(properties); + + /** + * The tint applied to the container. + * This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = 0; + _this.tintRgb = new Float32Array(4); + _this.tint = 0xFFFFFF; + return _this; + } + + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * + * @param {object} properties - The properties to be uploaded + */ + + + ParticleContainer.prototype.setProperties = function setProperties(properties) { + if (properties) { + this._properties[0] = 'vertices' in properties || 'scale' in properties ? !!properties.vertices || !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'tint' in properties || 'alpha' in properties ? !!properties.tint || !!properties.alpha : this._properties[4]; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + ParticleContainer.prototype.updateTransform = function updateTransform() { + // TODO don't need to! + this.displayObjectUpdateTransform(); + // PIXI.Container.prototype.updateTransform.call( this ); + }; + + /** + * The tint applied to the container. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + ** IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * @member {number} + * @default 0xFFFFFF + */ + + + /** + * Renders the container using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer + */ + ParticleContainer.prototype.renderWebGL = function renderWebGL(renderer) { + var _this2 = this; + + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.hasLoaded) { + this.baseTexture.once('update', function () { + return _this2.onChildrenChange(0); + }); + } + } + + renderer.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + + /** + * Set the flag that static data should be updated to true + * + * @private + * @param {number} smallestChildIndex - The smallest child index + */ + + + ParticleContainer.prototype.onChildrenChange = function onChildrenChange(smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + + while (this._bufferUpdateIDs.length < bufferIndex) { + this._bufferUpdateIDs.push(0); + } + this._bufferUpdateIDs[bufferIndex] = ++this._updateID; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + + + ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var isRotated = true; + + var positionX = 0; + var positionY = 0; + + var finalWidth = 0; + var finalHeight = 0; + + renderer.setBlendMode(this.blendMode); + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i]; + + if (!child.visible) { + continue; + } + + var frame = child._texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) { + // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call + if (isRotated) { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx * renderer.resolution, transform.ty * renderer.resolution); + + isRotated = false; + } + + positionX = child.anchor.x * (-frame.width * child.scale.x) + child.position.x + 0.5; + positionY = child.anchor.y * (-frame.height * child.scale.y) + child.position.y + 0.5; + + finalWidth = frame.width * child.scale.x; + finalHeight = frame.height * child.scale.y; + } else { + if (!isRotated) { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + + if (renderer.roundPixels || this.roundPixels) { // #CUSTOM + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution | 0, childTransform.ty * renderer.resolution | 0); + } else { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution, childTransform.ty * renderer.resolution); + } + + positionX = child.anchor.x * -frame.width + 0.5; + positionY = child.anchor.y * -frame.height + 0.5; + + finalWidth = frame.width; + finalHeight = frame.height; + } + + var resolution = child._texture.baseTexture.resolution; + + context.drawImage(child._texture.baseTexture.source, frame.x * resolution, frame.y * resolution, frame.width * resolution, frame.height * resolution, positionX * renderer.resolution, positionY * renderer.resolution, finalWidth * renderer.resolution, finalHeight * renderer.resolution); + } + }; + + /** + * Destroys the container + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + ParticleContainer.prototype.destroy = function destroy(options) { + _core$Container.prototype.destroy.call(this, options); + + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + } + + this._properties = null; + this._buffers = null; + this._bufferUpdateIDs = null; + }; + + _createClass(ParticleContainer, [{ + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + (0, _utils.hex2rgb)(value, this.tintRgb); + } + }]); + + return ParticleContainer; +}(core.Container); + +exports.default = ParticleContainer; + +},{"../core":65,"../core/utils":125}],174:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ParticleContainer = require('./ParticleContainer'); + +Object.defineProperty(exports, 'ParticleContainer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleContainer).default; + } +}); + +var _ParticleRenderer = require('./webgl/ParticleRenderer'); + +Object.defineProperty(exports, 'ParticleRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleRenderer).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./ParticleContainer":173,"./webgl/ParticleRenderer":176}],175:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + +/** + * The particle buffer manages the static and dynamic buffers for a particle container. + * + * @class + * @private + * @memberof PIXI + */ +var ParticleBuffer = function () { + /** + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(gl, properties, dynamicPropertyFlags, size) { + _classCallCheck(this, ParticleBuffer); + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The number of particles the buffer can hold + * + * @member {number} + */ + this.size = size; + + /** + * A list of the properties that are dynamic. + * + * @member {object[]} + */ + this.dynamicProperties = []; + + /** + * A list of the properties that are static. + * + * @member {object[]} + */ + this.staticProperties = []; + + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attribute: property.attribute, + size: property.size, + uploadFunction: property.uploadFunction, + unsignedByte: property.unsignedByte, + offset: property.offset + }; + + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } else { + this.staticProperties.push(property); + } + } + + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + + this._updateID = 0; + + this.initBuffers(); + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + ParticleBuffer.prototype.initBuffers = function initBuffers() { + var gl = this.gl; + var dynamicOffset = 0; + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(this.size); + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + this.dynamicStride = 0; + + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + + var dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4); + + this.dynamicData = new Float32Array(dynBuffer); + this.dynamicDataUint32 = new Uint32Array(dynBuffer); + this.dynamicBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, dynBuffer, gl.STREAM_DRAW); + + // static // + var staticOffset = 0; + + this.staticStride = 0; + + for (var _i = 0; _i < this.staticProperties.length; ++_i) { + var _property = this.staticProperties[_i]; + + _property.offset = staticOffset; + staticOffset += _property.size; + this.staticStride += _property.size; + } + + var statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4); + + this.staticData = new Float32Array(statBuffer); + this.staticDataUint32 = new Uint32Array(statBuffer); + this.staticBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, statBuffer, gl.STATIC_DRAW); + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(this.indexBuffer); + + for (var _i2 = 0; _i2 < this.dynamicProperties.length; ++_i2) { + var _property2 = this.dynamicProperties[_i2]; + + if (_property2.unsignedByte) { + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.UNSIGNED_BYTE, true, this.dynamicStride * 4, _property2.offset * 4); + } else { + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.FLOAT, false, this.dynamicStride * 4, _property2.offset * 4); + } + } + + for (var _i3 = 0; _i3 < this.staticProperties.length; ++_i3) { + var _property3 = this.staticProperties[_i3]; + + if (_property3.unsignedByte) { + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.UNSIGNED_BYTE, true, this.staticStride * 4, _property3.offset * 4); + } else { + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.FLOAT, false, this.staticStride * 4, _property3.offset * 4); + } + } + }; + + /** + * Uploads the dynamic properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadDynamic = function uploadDynamic(children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + + property.uploadFunction(children, startIndex, amount, property.unsignedByte ? this.dynamicDataUint32 : this.dynamicData, this.dynamicStride, property.offset); + } + + this.dynamicBuffer.upload(); + }; + + /** + * Uploads the static properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadStatic = function uploadStatic(children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + + property.uploadFunction(children, startIndex, amount, property.unsignedByte ? this.staticDataUint32 : this.staticData, this.staticStride, property.offset); + } + + this.staticBuffer.upload(); + }; + + /** + * Destroys the ParticleBuffer. + * + */ + + + ParticleBuffer.prototype.destroy = function destroy() { + this.dynamicProperties = null; + this.dynamicBuffer.destroy(); + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + + this.staticProperties = null; + this.staticBuffer.destroy(); + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + }; + + return ParticleBuffer; +}(); + +exports.default = ParticleBuffer; + +},{"../../core/utils/createIndicesForQuads":123,"pixi-gl-core":15}],176:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _ParticleShader = require('./ParticleShader'); + +var _ParticleShader2 = _interopRequireDefault(_ParticleShader); + +var _ParticleBuffer = require('./ParticleBuffer'); + +var _ParticleBuffer2 = _interopRequireDefault(_ParticleBuffer); + +var _utils = require('../../core/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + +/** + * + * @class + * @private + * @memberof PIXI + */ +var ParticleRenderer = function (_core$ObjectRenderer) { + _inherits(ParticleRenderer, _core$ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + _classCallCheck(this, ParticleRenderer); + + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; + + /** + * The default shader that is used if a sprite doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + + _this.indexBuffer = null; + + _this.properties = null; + + _this.tempMatrix = new core.Matrix(); + + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * When there is a WebGL context change + * + * @private + */ + + + ParticleRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + + // setup default shader + this.shader = new _ParticleShader2.default(gl); + + this.properties = [ + // verticesData + { + attribute: this.shader.attributes.aVertexPosition, + size: 2, + uploadFunction: this.uploadVertices, + offset: 0 + }, + // positionData + { + attribute: this.shader.attributes.aPositionCoord, + size: 2, + uploadFunction: this.uploadPosition, + offset: 0 + }, + // rotationData + { + attribute: this.shader.attributes.aRotation, + size: 1, + uploadFunction: this.uploadRotation, + offset: 0 + }, + // uvsData + { + attribute: this.shader.attributes.aTextureCoord, + size: 2, + uploadFunction: this.uploadUvs, + offset: 0 + }, + // tintData + { + attribute: this.shader.attributes.aColor, + size: 1, + unsignedByte: true, + uploadFunction: this.uploadTint, + offset: 0 + }]; + }; + + /** + * Starts a new particle batch. + * + */ + + + ParticleRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + }; + + /** + * Renders the particle container object. + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + */ + + + ParticleRenderer.prototype.render = function render(container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var renderer = this.renderer; + var totalChildren = children.length; + + if (totalChildren === 0) { + return; + } else if (totalChildren > maxSize) { + totalChildren = maxSize; + } + + var buffers = container._glBuffers[renderer.CONTEXT_UID]; + + if (!buffers) { + buffers = container._glBuffers[renderer.CONTEXT_UID] = this.generateBuffers(container); + } + + var baseTexture = children[0]._texture.baseTexture; + + // if the uvs have not updated then no point rendering just yet! + this.renderer.setBlendMode(core.utils.correctBlendMode(container.blendMode, baseTexture.premultipliedAlpha)); + + var gl = renderer.gl; + + var m = container.worldTransform.copy(this.tempMatrix); + + m.prepend(renderer._activeRenderTarget.projectionMatrix); + + this.shader.uniforms.projectionMatrix = m.toArray(true); + + this.shader.uniforms.uColor = core.utils.premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, baseTexture.premultipliedAlpha); + + // make sure the texture is bound.. + this.shader.uniforms.uSampler = renderer.bindTexture(baseTexture); + + var updateStatic = false; + + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = totalChildren - i; + + if (amount > batchSize) { + amount = batchSize; + } + + if (j >= buffers.length) { + if (!container.autoResize) { + break; + } + buffers.push(this._generateOneMoreBuffer(container)); + } + + var buffer = buffers[j]; + + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + + var bid = container._bufferUpdateIDs[j] || 0; + + updateStatic = updateStatic || buffer._updateID < bid; + // we only upload the static content when we have to! + if (updateStatic) { + buffer._updateID = container._updateID; + buffer.uploadStatic(children, i, amount); + } + + // bind the buffer + renderer.bindVao(buffer.vao); + buffer.vao.draw(gl.TRIANGLES, amount * 6); + } + }; + + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer[]} The buffers + */ + + + ParticleRenderer.prototype.generateBuffers = function generateBuffers(container) { + var gl = this.renderer.gl; + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + for (var i = 0; i < size; i += batchSize) { + buffers.push(new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize)); + } + + return buffers; + }; + + /** + * Creates one more particle buffer, because container has autoResize feature + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer} generated buffer + * @private + */ + + + ParticleRenderer.prototype._generateOneMoreBuffer = function _generateOneMoreBuffer(container) { + var gl = this.renderer.gl; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + return new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize); + }; + + /** + * Uploads the verticies. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their vertices uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadVertices = function uploadVertices(children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - sprite.anchor.x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - sprite.anchor.y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - sprite.anchor.x); + w1 = orig.width * -sprite.anchor.x; + + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + + array[offset + stride * 2] = w0 * sx; + array[offset + stride * 2 + 1] = h0 * sy; + + array[offset + stride * 3] = w1 * sx; + array[offset + stride * 3 + 1] = h0 * sy; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their positions uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadPosition = function uploadPosition(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + + array[offset + stride * 2] = spritePosition.x; + array[offset + stride * 2 + 1] = spritePosition.y; + + array[offset + stride * 3] = spritePosition.x; + array[offset + stride * 3 + 1] = spritePosition.y; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadRotation = function uploadRotation(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + stride * 2] = spriteRotation; + array[offset + stride * 3] = spriteRotation; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadUvs = function uploadUvs(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + + array[offset + stride * 2] = textureUvs.x2; + array[offset + stride * 2 + 1] = textureUvs.y2; + + array[offset + stride * 3] = textureUvs.x3; + array[offset + stride * 3 + 1] = textureUvs.y3; + + offset += stride * 4; + } else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + + array[offset + stride * 2] = 0; + array[offset + stride * 2 + 1] = 0; + + array[offset + stride * 3] = 0; + array[offset + stride * 3 + 1] = 0; + + offset += stride * 4; + } + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadTint = function uploadTint(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var premultiplied = sprite._texture.baseTexture.premultipliedAlpha; + var alpha = sprite.alpha; + // we dont call extra function if alpha is 1.0, that's faster + var argb = alpha < 1.0 && premultiplied ? (0, _utils.premultiplyTint)(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); + + array[offset] = argb; + array[offset + stride] = argb; + array[offset + stride * 2] = argb; + array[offset + stride * 3] = argb; + + offset += stride * 4; + } + }; + + /** + * Destroys the ParticleRenderer. + * + */ + + + ParticleRenderer.prototype.destroy = function destroy() { + if (this.renderer.gl) { + this.renderer.gl.deleteBuffer(this.indexBuffer); + } + + _core$ObjectRenderer.prototype.destroy.call(this); + + this.shader.destroy(); + + this.indices = null; + this.tempMatrix = null; + }; + + return ParticleRenderer; +}(core.ObjectRenderer); + +exports.default = ParticleRenderer; + + +core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + +},{"../../core":65,"../../core/utils":125,"./ParticleBuffer":175,"./ParticleShader":177}],177:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../core/Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI + */ +var ParticleShader = function (_Shader) { + _inherits(ParticleShader, _Shader); + + /** + * @param {PIXI.Shader} gl - The webgl shader manager this shader works for. + */ + function ParticleShader(gl) { + _classCallCheck(this, ParticleShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'attribute vec4 aColor;', 'attribute vec2 aPositionCoord;', 'attribute float aRotation;', 'uniform mat3 projectionMatrix;', 'uniform vec4 uColor;', 'varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'void main(void){', ' float x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);', ' float y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);', ' vec2 v = vec2(x, y);', ' v = v + aPositionCoord;', ' gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = aColor * uColor;', '}'].join('\n'), + // hello + ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'uniform sampler2D uSampler;', 'void main(void){', ' vec4 color = texture2D(uSampler, vTextureCoord) * vColor;', ' gl_FragColor = color;', '}'].join('\n'))); + } + + return ParticleShader; +}(_Shader3.default); + +exports.default = ParticleShader; + +},{"../../core/Shader":44}],178:[function(require,module,exports){ +"use strict"; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + +if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + + if (x === 0 || isNaN(x)) { + return x; + } + + return x > 0 ? 1 : -1; + }; +} + +},{}],179:[function(require,module,exports){ +'use strict'; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger + +if (!Number.isInteger) { + Number.isInteger = function numberIsInteger(value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; + }; +} + +},{}],180:[function(require,module,exports){ +'use strict'; + +var _objectAssign = require('object-assign'); + +var _objectAssign2 = _interopRequireDefault(_objectAssign); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +if (!Object.assign) { + Object.assign = _objectAssign2.default; +} // References: +// https://github.com/sindresorhus/object-assign +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + +},{"object-assign":6}],181:[function(require,module,exports){ +'use strict'; + +require('./Object.assign'); + +require('./requestAnimationFrame'); + +require('./Math.sign'); + +require('./Number.isInteger'); + +if (!window.ArrayBuffer) { + window.ArrayBuffer = Array; +} + +if (!window.Float32Array) { + window.Float32Array = Array; +} + +if (!window.Uint32Array) { + window.Uint32Array = Array; +} + +if (!window.Uint16Array) { + window.Uint16Array = Array; +} + +},{"./Math.sign":178,"./Number.isInteger":179,"./Object.assign":180,"./requestAnimationFrame":182}],182:[function(require,module,exports){ +(function (global){ +'use strict'; + +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + +// Expected to be used with Browserfiy +// Browserify automatically detects the use of `global` and passes the +// correct reference of `global`, `self`, and finally `window` + +var ONE_FRAME_TIME = 16; + +// Date.now +if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; +} + +// performance.now +if (!(global.performance && global.performance.now)) { + var startTime = Date.now(); + + if (!global.performance) { + global.performance = {}; + } + + global.performance.now = function () { + return Date.now() - startTime; + }; +} + +// requestAnimationFrame +var lastTime = Date.now(); +var vendors = ['ms', 'moz', 'webkit', 'o']; + +for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { + var p = vendors[x]; + + global.requestAnimationFrame = global[p + 'RequestAnimationFrame']; + global.cancelAnimationFrame = global[p + 'CancelAnimationFrame'] || global[p + 'CancelRequestAnimationFrame']; +} + +if (!global.requestAnimationFrame) { + global.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + 'is not a function'); + } + + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + + if (delay < 0) { + delay = 0; + } + + lastTime = currentTime; + + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} + +if (!global.cancelAnimationFrame) { + global.cancelAnimationFrame = function (id) { + return clearTimeout(id); + }; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],183:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CountLimiter = require('./limiters/CountLimiter'); + +var _CountLimiter2 = _interopRequireDefault(_CountLimiter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SharedTicker = core.ticker.shared; + +/** + * Default number of uploads per frame using prepare plugin. + * + * @static + * @memberof PIXI.settings + * @name UPLOADS_PER_FRAME + * @type {number} + * @default 4 + */ +core.settings.UPLOADS_PER_FRAME = 4; + +/** + * The prepare manager provides functionality to upload content to the GPU. BasePrepare handles + * basic queuing functionality and is extended by {@link PIXI.prepare.WebGLPrepare} and {@link PIXI.prepare.CanvasPrepare} + * to provide preparation capabilities specific to their respective renderers. + * + * @example + * // Create a sprite + * const sprite = new PIXI.Sprite.fromImage('something.png'); + * + * // Load object into GPU + * app.renderer.plugins.prepare.upload(sprite, () => { + * + * //Texture(s) has been uploaded to GPU + * app.stage.addChild(sprite); + * + * }) + * + * @abstract + * @class + * @memberof PIXI.prepare + */ + +var BasePrepare = function () { + /** + * @param {PIXI.SystemRenderer} renderer - A reference to the current renderer + */ + function BasePrepare(renderer) { + var _this = this; + + _classCallCheck(this, BasePrepare); + + /** + * The limiter to be used to control how quickly items are prepared. + * @type {PIXI.prepare.CountLimiter|PIXI.prepare.TimeLimiter} + */ + this.limiter = new _CountLimiter2.default(core.settings.UPLOADS_PER_FRAME); + + /** + * Reference to the renderer. + * @type {PIXI.SystemRenderer} + * @protected + */ + this.renderer = renderer; + + /** + * The only real difference between CanvasPrepare and WebGLPrepare is what they pass + * to upload hooks. That different parameter is stored here. + * @type {PIXI.prepare.CanvasPrepare|PIXI.WebGLRenderer} + * @protected + */ + this.uploadHookHelper = null; + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + /** + * 'bound' call for prepareItems(). + * @type {Function} + * @private + */ + this.delayedTick = function () { + // unlikely, but in case we were destroyed between tick() and delayedTick() + if (!_this.queue) { + return; + } + _this.prepareItems(); + }; + + // hooks to find the correct texture + this.registerFindHook(findText); + this.registerFindHook(findTextStyle); + this.registerFindHook(findMultipleBaseTextures); + this.registerFindHook(findBaseTexture); + this.registerFindHook(findTexture); + + // upload hooks + this.registerUploadHook(drawText); + this.registerUploadHook(calculateTextStyle); + } + + /** + * Upload all the textures and graphics to the GPU. + * + * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item - + * Either the container or display object to search for items to upload, the items to upload themselves, + * or the callback function, if items have been added using `prepare.add`. + * @param {Function} [done] - Optional callback when all queued uploads have completed + */ + + + BasePrepare.prototype.upload = function upload(item, done) { + if (typeof item === 'function') { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) { + if (done) { + this.completes.push(done); + } + + if (!this.ticking) { + this.ticking = true; + SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); + } + } else if (done) { + done(); + } + }; + + /** + * Handle tick update + * + * @private + */ + + + BasePrepare.prototype.tick = function tick() { + setTimeout(this.delayedTick, 0); + }; + + /** + * Actually prepare items. This is handled outside of the tick because it will take a while + * and we do NOT want to block the current animation frame from rendering. + * + * @private + */ + + + BasePrepare.prototype.prepareItems = function prepareItems() { + this.limiter.beginFrame(); + // Upload the graphics + while (this.queue.length && this.limiter.allowedToUpload()) { + var item = this.queue[0]; + var uploaded = false; + + if (item && !item._destroyed) { + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.uploadHookHelper, item)) { + this.queue.shift(); + uploaded = true; + break; + } + } + } + + if (!uploaded) { + this.queue.shift(); + } + } + + // We're finished + if (!this.queue.length) { + this.ticking = false; + + var completes = this.completes.slice(0); + + this.completes.length = 0; + + for (var _i = 0, _len = completes.length; _i < _len; _i++) { + completes[_i](); + } + } else { + // if we are not finished, on the next rAF do this again + SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); + } + }; + + /** + * Adds hooks for finding items. + * + * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.registerFindHook = function registerFindHook(addHook) { + if (addHook) { + this.addHooks.push(addHook); + } + + return this; + }; + + /** + * Adds hooks for uploading items. + * + * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.registerUploadHook = function registerUploadHook(uploadHook) { + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + + return this; + }; + + /** + * Manually add an item to the uploading queue. + * + * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to + * add to the queue + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.add = function add(item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) { + for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { + this.add(item.children[_i2]); + } + } + + return this; + }; + + /** + * Destroys the plugin, don't use after this. + * + */ + + + BasePrepare.prototype.destroy = function destroy() { + if (this.ticking) { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.limiter = null; + this.uploadHookHelper = null; + }; + + return BasePrepare; +}(); + +/** + * Built-in hook to find multiple textures from objects like AnimatedSprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ + + +exports.default = BasePrepare; +function findMultipleBaseTextures(item, queue) { + var result = false; + + // Objects with mutliple textures + if (item && item._textures && item._textures.length) { + for (var i = 0; i < item._textures.length; i++) { + if (item._textures[i] instanceof core.Texture) { + var baseTexture = item._textures[i].baseTexture; + + if (queue.indexOf(baseTexture) === -1) { + queue.push(baseTexture); + result = true; + } + } + } + } + + return result; +} + +/** + * Built-in hook to find BaseTextures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTexture(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findTexture(item, queue) { + if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to draw PIXI.Text to its texture. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function drawText(helper, item) { + if (item instanceof core.Text) { + // updating text will return early if it is not dirty + item.updateText(true); + + return true; + } + + return false; +} + +/** + * Built-in hook to calculate a text style for a PIXI.Text object. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function calculateTextStyle(helper, item) { + if (item instanceof core.TextStyle) { + var font = item.toFontString(); + + core.TextMetrics.measureFont(font); + + return true; + } + + return false; +} + +/** + * Built-in hook to find Text objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Text object was found. + */ +function findText(item, queue) { + if (item instanceof core.Text) { + // push the text style to prepare it - this can be really expensive + if (queue.indexOf(item.style) === -1) { + queue.push(item.style); + } + // also push the text object so that we can render it (to canvas/texture) if needed + if (queue.indexOf(item) === -1) { + queue.push(item); + } + // also push the Text's texture for upload to GPU + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find TextStyle objects. + * + * @private + * @param {PIXI.TextStyle} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.TextStyle object was found. + */ +function findTextStyle(item, queue) { + if (item instanceof core.TextStyle) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +},{"../core":65,"./limiters/CountLimiter":186}],184:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CANVAS_START_SIZE = 16; + +/** + * The prepare manager provides functionality to upload content to the GPU + * This cannot be done directly for Canvas like in WebGL, but the effect can be achieved by drawing + * textures to an offline canvas. + * This draw call will force the texture to be moved onto the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ + +var CanvasPrepare = function (_BasePrepare) { + _inherits(CanvasPrepare, _BasePrepare); + + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasPrepare(renderer) { + _classCallCheck(this, CanvasPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this; + + /** + * An offline canvas to render textures to + * @type {HTMLCanvasElement} + * @private + */ + _this.canvas = document.createElement('canvas'); + _this.canvas.width = CANVAS_START_SIZE; + _this.canvas.height = CANVAS_START_SIZE; + + /** + * The context to the canvas + * @type {CanvasRenderingContext2D} + * @private + */ + _this.ctx = _this.canvas.getContext('2d'); + + // Add textures to upload + _this.registerUploadHook(uploadBaseTextures); + return _this; + } + + /** + * Destroys the plugin, don't use after this. + * + */ + + + CanvasPrepare.prototype.destroy = function destroy() { + _BasePrepare.prototype.destroy.call(this); + this.ctx = null; + this.canvas = null; + }; + + return CanvasPrepare; +}(_BasePrepare3.default); + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {*} prepare - Instance of CanvasPrepare + * @param {*} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = CanvasPrepare; +function uploadBaseTextures(prepare, item) { + if (item instanceof core.BaseTexture) { + var image = item.source; + + // Sometimes images (like atlas images) report a size of zero, causing errors on windows phone. + // So if the width or height is equal to zero then use the canvas size + // Otherwise use whatever is smaller, the image dimensions or the canvas dimensions. + var imageWidth = image.width === 0 ? prepare.canvas.width : Math.min(prepare.canvas.width, image.width); + var imageHeight = image.height === 0 ? prepare.canvas.height : Math.min(prepare.canvas.height, image.height); + + // Only a small subsections is required to be drawn to have the whole texture uploaded to the GPU + // A smaller draw can be faster. + prepare.ctx.drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, prepare.canvas.width, prepare.canvas.height); + + return true; + } + + return false; +} + +core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); + +},{"../../core":65,"../BasePrepare":183}],185:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLPrepare = require('./webgl/WebGLPrepare'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLPrepare).default; + } +}); + +var _CanvasPrepare = require('./canvas/CanvasPrepare'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasPrepare).default; + } +}); + +var _BasePrepare = require('./BasePrepare'); + +Object.defineProperty(exports, 'BasePrepare', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BasePrepare).default; + } +}); + +var _CountLimiter = require('./limiters/CountLimiter'); + +Object.defineProperty(exports, 'CountLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CountLimiter).default; + } +}); + +var _TimeLimiter = require('./limiters/TimeLimiter'); + +Object.defineProperty(exports, 'TimeLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TimeLimiter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./BasePrepare":183,"./canvas/CanvasPrepare":184,"./limiters/CountLimiter":186,"./limiters/TimeLimiter":187,"./webgl/WebGLPrepare":188}],186:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * CountLimiter limits the number of items handled by a {@link PIXI.prepare.BasePrepare} to a specified + * number of items per frame. + * + * @class + * @memberof PIXI + */ +var CountLimiter = function () { + /** + * @param {number} maxItemsPerFrame - The maximum number of items that can be prepared each frame. + */ + function CountLimiter(maxItemsPerFrame) { + _classCallCheck(this, CountLimiter); + + /** + * The maximum number of items that can be prepared each frame. + * @private + */ + this.maxItemsPerFrame = maxItemsPerFrame; + /** + * The number of items that can be prepared in the current frame. + * @type {number} + * @private + */ + this.itemsLeft = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + CountLimiter.prototype.beginFrame = function beginFrame() { + this.itemsLeft = this.maxItemsPerFrame; + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + CountLimiter.prototype.allowedToUpload = function allowedToUpload() { + return this.itemsLeft-- > 0; + }; + + return CountLimiter; +}(); + +exports.default = CountLimiter; + +},{}],187:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of milliseconds per frame. + * + * @class + * @memberof PIXI + */ +var TimeLimiter = function () { + /** + * @param {number} maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. + */ + function TimeLimiter(maxMilliseconds) { + _classCallCheck(this, TimeLimiter); + + /** + * The maximum milliseconds that can be spent preparing items each frame. + * @private + */ + this.maxMilliseconds = maxMilliseconds; + /** + * The start time of the current frame. + * @type {number} + * @private + */ + this.frameStart = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + TimeLimiter.prototype.beginFrame = function beginFrame() { + this.frameStart = Date.now(); + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + TimeLimiter.prototype.allowedToUpload = function allowedToUpload() { + return Date.now() - this.frameStart < this.maxMilliseconds; + }; + + return TimeLimiter; +}(); + +exports.default = TimeLimiter; + +},{}],188:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The prepare manager provides functionality to upload content to the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ +var WebGLPrepare = function (_BasePrepare) { + _inherits(WebGLPrepare, _BasePrepare); + + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLPrepare(renderer) { + _classCallCheck(this, WebGLPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this.renderer; + + // Add textures and graphics to upload + _this.registerFindHook(findGraphics); + _this.registerUploadHook(uploadBaseTextures); + _this.registerUploadHook(uploadGraphics); + return _this; + } + + return WebGLPrepare; +}(_BasePrepare3.default); +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = WebGLPrepare; +function uploadBaseTextures(renderer, item) { + if (item instanceof core.BaseTexture) { + // if the texture already has a GL texture, then the texture has been prepared or rendered + // before now. If the texture changed, then the changer should be calling texture.update() which + // reuploads the texture without need for preparing it again + if (!item._glTextures[renderer.CONTEXT_UID]) { + renderer.textureManager.updateTexture(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to upload PIXI.Graphics to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadGraphics(renderer, item) { + if (item instanceof core.Graphics) { + // if the item is not dirty and already has webgl data, then it got prepared or rendered + // before now and we shouldn't waste time updating it again + if (item.dirty || item.clearDirty || !item._webGL[renderer.plugins.graphics.CONTEXT_UID]) { + renderer.plugins.graphics.updateGraphics(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find graphics. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Graphics object was found. + */ +function findGraphics(item, queue) { + if (item instanceof core.Graphics) { + queue.push(item); + + return true; + } + + return false; +} + +core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); + +},{"../../core":65,"../BasePrepare":183}],189:[function(require,module,exports){ +(function (global){ +'use strict'; + +exports.__esModule = true; +exports.loader = exports.prepare = exports.particles = exports.mesh = exports.loaders = exports.interaction = exports.filters = exports.extras = exports.extract = exports.accessibility = undefined; + +var _polyfill = require('./polyfill'); + +Object.keys(_polyfill).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _polyfill[key]; + } + }); +}); + +var _core = require('./core'); + +Object.keys(_core).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _core[key]; + } + }); +}); + +var _deprecation = require('./deprecation'); + +var _deprecation2 = _interopRequireDefault(_deprecation); + +var _accessibility = require('./accessibility'); + +var accessibility = _interopRequireWildcard(_accessibility); + +var _extract = require('./extract'); + +var extract = _interopRequireWildcard(_extract); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// export core +_core.utils.mixins.performMixins(); + +/** + * Alias for {@link PIXI.loaders.shared}. + * @name loader + * @memberof PIXI + * @type {PIXI.loader.Loader} + */ + + +// handle mixins now, after all code has been added, including deprecation + + +// export libs +// import polyfills. Done as an export to make sure polyfills are imported first +var loader = loaders.shared || null; + +exports.accessibility = accessibility; +exports.extract = extract; +exports.extras = extras; +exports.filters = filters; +exports.interaction = interaction; +exports.loaders = loaders; +exports.mesh = mesh; +exports.particles = particles; +exports.prepare = prepare; +exports.loader = loader; + +// Apply the deprecations + +if (typeof _deprecation2.default === 'function') { + (0, _deprecation2.default)(exports); +} + +// Always export PixiJS globally. +global.PIXI = exports; // eslint-disable-line + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"./accessibility":42,"./core":65,"./deprecation":131,"./extract":133,"./extras":141,"./filters":153,"./interaction":159,"./loaders":162,"./mesh":171,"./particles":174,"./polyfill":181,"./prepare":185}]},{},[189])(189) +}); + + +//# sourceMappingURL=pixi.js.map diff --git a/js/pixi/4.8.2-roundpixels/pixi.min.js b/js/pixi/4.8.2-roundpixels/pixi.min.js new file mode 100755 index 0000000..5121c49 --- /dev/null +++ b/js/pixi/4.8.2-roundpixels/pixi.min.js @@ -0,0 +1 @@ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).PIXI=t()}}(function(){return function o(s,a,u){function h(r,t){if(!a[r]){if(!s[r]){var e="function"==typeof require&&require;if(!t&&e)return e(r,!0);if(l)return l(r,!0);var n=new Error("Cannot find module '"+r+"'");throw n.code="MODULE_NOT_FOUND",n}var i=a[r]={exports:{}};s[r][0].call(i.exports,function(t){var e=s[r][1][t];return h(e||t)},i,i.exports,o,s,a,u)}return a[r].exports}for(var l="function"==typeof require&&require,t=0;t>31;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t>>=e))<<3,e|=r=(15<(t>>>=r))<<2,(e|=r=(3<(t>>>=r))<<1)|(t>>>=r)>>1},r.log10=function(t){return 1e9<=t?9:1e8<=t?8:1e7<=t?7:1e6<=t?6:1e5<=t?5:1e4<=t?4:1e3<=t?3:100<=t?2:10<=t?1:0},r.popCount=function(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var i=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|i[t>>>16&255]<<8|i[t>>>24&255]},r.interleave2=function(t,e){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t&=65535)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e&=65535)|e<<8))|e<<4))|e<<2))|e<<1))<<1},r.deinterleave2=function(t,e){return(t=65535&((t=16711935&((t=252645135&((t=858993459&((t=t>>>e&1431655765)|t>>>1))|t>>>2))|t>>>4))|t>>>16))<<16>>16},r.interleave3=function(t,e,r){return t=1227133513&((t=3272356035&((t=251719695&((t=4278190335&((t&=1023)|t<<16))|t<<8))|t<<4))|t<<2),(t|=(e=1227133513&((e=3272356035&((e=251719695&((e=4278190335&((e&=1023)|e<<16))|e<<8))|e<<4))|e<<2))<<1)|(r=1227133513&((r=3272356035&((r=251719695&((r=4278190335&((r&=1023)|r<<16))|r<<8))|r<<4))|r<<2))<<2},r.deinterleave3=function(t,e){return(t=1023&((t=4278190335&((t=251719695&((t=3272356035&((t=t>>>e&1227133513)|t>>>2))|t>>>4))|t>>>8))|t>>>16))<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],2:[function(t,e,r){"use strict";function n(t,e,r){r=r||2;var n,i,o,s,a,u,h,l=e&&e.length,c=l?e[0]*r:t.length,d=v(t,0,c,r,!0),f=[];if(!d)return f;if(l&&(d=function(t,e,r,n){var i,o,s,a,u,h=[];for(i=0,o=e.length;i80*r){n=o=t[0],i=s=t[1];for(var p=r;po.x?i.x>s.x?i.x:s.x:o.x>s.x?o.x:s.x,l=i.y>o.y?i.y>s.y?i.y:s.y:o.y>s.y?o.y:s.y,c=b(a,u,e,r,n),d=b(h,l,e,r,n),f=t.prevZ,p=t.nextZ;f&&f.z>=c&&p&&p.z<=d;){if(f!==t.prev&&f!==t.next&&T(i.x,i.y,o.x,o.y,s.x,s.y,f.x,f.y)&&0<=w(f.prev,f,f.next))return!1;if(f=f.prevZ,p!==t.prev&&p!==t.next&&T(i.x,i.y,o.x,o.y,s.x,s.y,p.x,p.y)&&0<=w(p.prev,p,p.next))return!1;p=p.nextZ}for(;f&&f.z>=c;){if(f!==t.prev&&f!==t.next&&T(i.x,i.y,o.x,o.y,s.x,s.y,f.x,f.y)&&0<=w(f.prev,f,f.next))return!1;f=f.prevZ}for(;p&&p.z<=d;){if(p!==t.prev&&p!==t.next&&T(i.x,i.y,o.x,o.y,s.x,s.y,p.x,p.y)&&0<=w(p.prev,p,p.next))return!1;p=p.nextZ}return!0}function d(t,e,r){var n=t;do{var i=n.prev,o=n.next.next;!a(i,o)&&p(i,n,n.next,o)&&E(i,o)&&E(o,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(o.i/r),O(n),O(n.next),n=t=o),n=n.next}while(n!==t);return n}function f(t,e,r,n,i,o){var s,a,u=t;do{for(var h=u.next.next;h!==u.prev;){if(u.i!==h.i&&(a=h,(s=u).next.i!==a.i&&s.prev.i!==a.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&p(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}(s,a)&&E(s,a)&&E(a,s)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;for(;r.y>o!=r.next.y>o&&r.next.y!==r.y&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next,r!==t;);return n}(s,a))){var l=S(u,h);return u=g(u,u.next),l=g(l,l.next),y(u,e,r,n,i,o),void y(l,e,r,n,i,o)}h=h.next}u=u.next}while(u!==t)}function m(t,e){return t.x-e.x}function _(t,e){if(e=function(t,e){var r,n=e,i=t.x,o=t.y,s=-1/0;do{if(o<=n.y&&o>=n.next.y&&n.next.y!==n.y){var a=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=i&&s=n.x&&n.x>=l&&i!==n.x&&T(or.x)&&E(n,t)&&(r=n,d=u),n=n.next;return r}(t,e)){var r=S(e,t);g(r,r.next)}}function b(t,e,r,n,i){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function x(t){for(var e=t,r=t;e.x=t.byteLength?n.bufferSubData(this.type,e,t):n.bufferData(this.type,t,this.drawType),this.data=t},o.prototype.bind=function(){this.gl.bindBuffer(this.type,this.buffer)},o.createVertexBuffer=function(t,e,r){return new o(t,t.ARRAY_BUFFER,e,r)},o.createIndexBuffer=function(t,e,r){return new o(t,t.ELEMENT_ARRAY_BUFFER,e,r)},o.create=function(t,e,r,n){return new o(t,e,r,n)},o.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer)},e.exports=o},{}],10:[function(t,e,r){var s=t("./GLTexture"),a=function(t,e,r){this.gl=t,this.framebuffer=t.createFramebuffer(),this.stencil=null,this.texture=null,this.width=e||100,this.height=r||100};a.prototype.enableTexture=function(t){var e=this.gl;this.texture=t||new s(e),this.texture.bind(),this.bind(),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0)},a.prototype.enableStencil=function(){if(!this.stencil){var t=this.gl;this.stencil=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.stencil),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.stencil),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,this.width,this.height)}},a.prototype.clear=function(t,e,r,n){this.bind();var i=this.gl;i.clearColor(t,e,r,n),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT)},a.prototype.bind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer)},a.prototype.unbind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)},a.prototype.resize=function(t,e){var r=this.gl;this.width=t,this.height=e,this.texture&&this.texture.uploadData(null,t,e),this.stencil&&(r.bindRenderbuffer(r.RENDERBUFFER,this.stencil),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e))},a.prototype.destroy=function(){var t=this.gl;this.texture&&this.texture.destroy(),t.deleteFramebuffer(this.framebuffer),this.gl=null,this.stencil=null,this.texture=null},a.createRGBA=function(t,e,r,n){var i=s.fromData(t,null,e,r);i.enableNearestScaling(),i.enableWrapClamp();var o=new a(t,e,r);return o.enableTexture(i),o.unbind(),o},a.createFloat32=function(t,e,r,n){var i=new s.fromData(t,n,e,r);i.enableNearestScaling(),i.enableWrapClamp();var o=new a(t,e,r);return o.enableTexture(i),o.unbind(),o},e.exports=a},{"./GLTexture":12}],11:[function(t,e,r){var o=t("./shader/compileProgram"),s=t("./shader/extractAttributes"),a=t("./shader/extractUniforms"),u=t("./shader/setPrecision"),h=t("./shader/generateUniformAccessObject"),n=function(t,e,r,n,i){this.gl=t,n&&(e=u(e,n),r=u(r,n)),this.program=o(t,e,r,i),this.attributes=s(t,this.program),this.uniformData=a(t,this.program),this.uniforms=h(t,this.uniformData)};n.prototype.bind=function(){return this.gl.useProgram(this.program),this},n.prototype.destroy=function(){this.attributes=null,this.uniformData=null,this.uniforms=null,this.gl.deleteProgram(this.program)},e.exports=n},{"./shader/compileProgram":17,"./shader/extractAttributes":19,"./shader/extractUniforms":20,"./shader/generateUniformAccessObject":21,"./shader/setPrecision":25}],12:[function(t,e,r){var o=function(t,e,r,n,i){this.gl=t,this.texture=t.createTexture(),this.mipmap=!1,this.premultiplyAlpha=!1,this.width=e||-1,this.height=r||-1,this.format=n||t.RGBA,this.type=i||t.UNSIGNED_BYTE},i=!(o.prototype.upload=function(t){this.bind();var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var r=t.videoWidth||t.width,n=t.videoHeight||t.height;n!==this.height||r!==this.width?e.texImage2D(e.TEXTURE_2D,0,this.format,this.format,this.type,t):e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.format,this.type,t),this.width=r,this.height=n});o.prototype.uploadData=function(t,e,r){this.bind();var n=this.gl;if(t instanceof Float32Array){if(!i){if(!n.getExtension("OES_texture_float"))throw new Error("floating point textures not available");i=!0}this.type=n.FLOAT}else this.type=this.type||n.UNSIGNED_BYTE;n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),e!==this.width||r!==this.height?n.texImage2D(n.TEXTURE_2D,0,this.format,e,r,0,this.format,this.type,t||null):n.texSubImage2D(n.TEXTURE_2D,0,0,0,e,r,this.format,this.type,t||null),this.width=e,this.height=r},o.prototype.bind=function(t){var e=this.gl;void 0!==t&&e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,this.texture)},o.prototype.unbind=function(){var t=this.gl;t.bindTexture(t.TEXTURE_2D,null)},o.prototype.minFilter=function(t){var e=this.gl;this.bind(),this.mipmap?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR:e.NEAREST)},o.prototype.magFilter=function(t){var e=this.gl;this.bind(),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t?e.LINEAR:e.NEAREST)},o.prototype.enableMipmap=function(){var t=this.gl;this.bind(),this.mipmap=!0,t.generateMipmap(t.TEXTURE_2D)},o.prototype.enableLinearScaling=function(){this.minFilter(!0),this.magFilter(!0)},o.prototype.enableNearestScaling=function(){this.minFilter(!1),this.magFilter(!1)},o.prototype.enableWrapClamp=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)},o.prototype.enableWrapRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT)},o.prototype.enableWrapMirrorRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.MIRRORED_REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.MIRRORED_REPEAT)},o.prototype.destroy=function(){this.gl.deleteTexture(this.texture)},o.fromSource=function(t,e,r){var n=new o(t);return n.premultiplyAlpha=r||!1,n.upload(e),n},o.fromData=function(t,e,r,n){var i=new o(t);return i.uploadData(e,r,n),i},e.exports=o},{}],13:[function(t,e,r){var i=t("./setVertexAttribArrays");function n(t,e){if(this.nativeVaoExtension=null,n.FORCE_NATIVE||(this.nativeVaoExtension=t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object")),this.nativeState=e,this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var r=t.getParameter(t.MAX_VERTEX_ATTRIBS);this.nativeState={tempAttribState:new Array(r),attribState:new Array(r)}}this.gl=t,this.attributes=[],this.indexBuffer=null,this.dirty=!1}n.prototype.constructor=n,(e.exports=n).FORCE_NATIVE=!1,n.prototype.bind=function(){if(this.nativeVao){if(this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao),this.dirty)return this.dirty=!1,this.activate(),this;this.indexBuffer&&this.indexBuffer.bind()}else this.activate();return this},n.prototype.unbind=function(){return this.nativeVao&&this.nativeVaoExtension.bindVertexArrayOES(null),this},n.prototype.activate=function(){for(var t=this.gl,e=null,r=0;r= 0x80 (not a basic code point)","invalid-input":"Invalid input"},d=m-_,E=Math.floor,S=String.fromCharCode;function O(t){throw new RangeError(c[t])}function f(t,e){for(var r=t.length,n=[];r--;)n[r]=e(t[r]);return n}function p(t,e){var r=t.split("@"),n="";return 1>>10&1023|55296),t=56320|1023&t),e+=S(t)}).join("")}function C(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function R(t,e,r){var n=0;for(t=r?E(t/a):t>>1,t+=E(t/e);d*b>>1E((y-p)/s))&&O("overflow"),p+=u*s,!(u<(h=a<=g?_:g+b<=a?b:a-g));a+=m)s>E(y/(l=m-h))&&O("overflow"),s*=l;g=R(p-o,e=d.length+1,0==o),E(p/e)>y-v&&O("overflow"),v+=E(p/e),p%=e,d.splice(p++,0,v)}return P(d)}function g(t){var e,r,n,i,o,s,a,u,h,l,c,d,f,p,v,g=[];for(d=(t=M(t)).length,e=T,o=x,s=r=0;sE((y-r)/(f=n+1))&&O("overflow"),r+=(a-e)*f,e=a,s=0;sy&&O("overflow"),c==e){for(u=r,h=m;!(u<(l=h<=o?_:o+b<=h?b:h-o));h+=m)v=u-l,p=m-l,g.push(S(C(l+v%p,0))),u=E(v/p);g.push(S(C(u,0))),o=R(r,f,n==i),r=0,++n}++r,++e}return g.join("")}if(i={version:"1.4.1",ucs2:{decode:M,encode:P},decode:v,encode:g,toASCII:function(t){return p(t,function(t){return h.test(t)?"xn--"+g(t):t})},toUnicode:function(t){return p(t,function(t){return u.test(t)?v(t.slice(4).toLowerCase()):t})}},e&&r)if(I.exports==e)r.exports=i;else for(o in i)i.hasOwnProperty(o)&&(e[o]=i[o]);else t.punycode=i}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],28:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){e=e||"&",r=r||"=";var i={};if("string"!=typeof t||0===t.length)return i;var o=/\+/g;t=t.split(e);var s=1e3;n&&"number"==typeof n.maxKeys&&(s=n.maxKeys);var a,u,h=t.length;0>2,i[1]=(3&n[0])<<4|n[1]>>4,i[2]=(15&n[1])<<2|n[2]>>6,i[3]=63&n[2];var s=r-(t.length-1);switch(s){case 2:i[3]=64,i[2]=64;break;case 1:i[3]=64}for(var a=0;a",'"',"`"," ","\r","\n","\t"]),k=["'"].concat(i),F=["%","/","?",";","#"].concat(k),j=["/","?","#"],U=/^[+a-z0-9A-Z_-]{0,63}$/,X=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,G={javascript:!0,"javascript:":!0},W={javascript:!0,"javascript:":!0},H={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},V=t("querystring");function o(t,e,r){if(t&&L.isObject(t)&&t instanceof M)return t;var n=new M;return n.parse(t,e,r),n}M.prototype.parse=function(t,e,r){if(!L.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var n=t.indexOf("?"),i=-1!==n&&nthis.renderer.width&&(t.width=this.renderer.width-t.x),t.y+t.height>this.renderer.height&&(t.height=this.renderer.height-t.y)},r.prototype.addChild=function(t){var e=this.pool.pop();e||((e=document.createElement("button")).style.width="100px",e.style.height="100px",e.style.backgroundColor=this.debug?"rgba(255,0,0,0.5)":"transparent",e.style.position="absolute",e.style.zIndex=2,e.style.borderStyle="none",-1]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i,r.SHAPES={POLY:0,RECT:1,CIRC:2,ELIP:3,RREC:4},r.PRECISION={LOW:"lowp",MEDIUM:"mediump",HIGH:"highp"},r.TRANSFORM_MODE={STATIC:0,DYNAMIC:1},r.TEXT_GRADIENT={LINEAR_VERTICAL:0,LINEAR_HORIZONTAL:1},r.UPDATE_PRIORITY={INTERACTION:50,HIGH:25,NORMAL:0,LOW:-25,UTILITY:-50}},{}],47:[function(t,e,r){"use strict";r.__esModule=!0;var n=t("../math");var i=function(){function t(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.rect=null}return t.prototype.isEmpty=function(){return this.minX>this.maxX||this.minY>this.maxY},t.prototype.clear=function(){this.updateID++,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0},t.prototype.getRectangle=function(t){return this.minX>this.maxX||this.minY>this.maxY?n.Rectangle.EMPTY:((t=t||new n.Rectangle(0,0,1,1)).x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)},t.prototype.addPoint=function(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)},t.prototype.addQuad=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY,o=t[0],s=t[1];e=on?t.maxX:n,this.maxY=t.maxY>i?t.maxY:i},t.prototype.addBoundsMask=function(t,e){var r=t.minX>e.minX?t.minX:e.minX,n=t.minY>e.minY?t.minY:e.minY,i=t.maxXe.x?t.minX:e.x,n=t.minY>e.y?t.minY:e.y,i=t.maxXthis.children.length)throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length);return t.parent&&t.parent.removeChild(t),t.parent=this,t.transform._parentID=-1,this.children.splice(e,0,t),this._boundsID++,this.onChildrenChange(e),t.emit("added",this),t},e.prototype.swapChildren=function(t,e){if(t!==e){var r=this.getChildIndex(t),n=this.getChildIndex(e);this.children[r]=e,this.children[n]=t,this.onChildrenChange(r=this.children.length)throw new Error("The index "+e+" supplied is out of bounds "+this.children.length);var r=this.getChildIndex(t);(0,s.removeItems)(this.children,r,1),this.children.splice(e,0,t),this.onChildrenChange(e)},e.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Index ("+t+") does not exist.");return this.children[t]},e.prototype.removeChild=function(t){var e=arguments.length;if(1w.CURVES.maxSegments&&(e=w.CURVES.maxSegments),e},w.prototype.lineStyle=function(){var t=0>16&255)/255,r=(t.tint>>8&255)/255,n=(255&t.tint)/255,i=0;i>16&255)/255*e*255<<16)+((s>>8&255)/255*r*255<<8)+(255&s)/255*n*255,o._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*r*255<<8)+(255&a)/255*n*255}},e.prototype.renderPolygon=function(t,e,r){r.moveTo(t[0],t[1]);for(var n=1;n=this.x&&t=this.y&&et.x+t.width&&(this.width=t.width-this.x,this.width<0&&(this.width=0)),this.y+this.height>t.y+t.height&&(this.height=t.height-this.y,this.height<0&&(this.height=0))},i.prototype.enlarge=function(t){var e=Math.min(this.x,t.x),r=Math.max(this.x+this.width,t.x+t.width),n=Math.min(this.y,t.y),i=Math.max(this.y+this.height,t.y+t.height);this.x=e,this.width=r-e,this.y=n,this.height=i-n},n(i,[{key:"left",get:function(){return this.x}},{key:"right",get:function(){return this.x+this.width}},{key:"top",get:function(){return this.y}},{key:"bottom",get:function(){return this.y+this.height}}],[{key:"EMPTY",get:function(){return new i(0,0,0,0)}}]),i}();r.default=i},{"../../const":46}],75:[function(t,e,r){"use strict";r.__esModule=!0;var s=t("../../const");var n=function(){function o(){var t=0=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){if(e>=this.y+this.radius&&e<=this.y+this.height-this.radius||t>=this.x+this.radius&&t<=this.x+this.width-this.radius)return!0;var r=t-(this.x+this.radius),n=e-(this.y+this.radius),i=this.radius*this.radius;if(r*r+n*n<=i)return!0;if((r=t-(this.x+this.width-this.radius))*r+n*n<=i)return!0;if(r*r+(n=e-(this.y+this.height-this.radius))*n<=i)return!0;if((r=t-(this.x+this.radius))*r+n*n<=i)return!0}return!1},o}();r.default=n},{"../../const":46}],76:[function(t,e,r){"use strict";r.__esModule=!0;var n=function(){function n(t,e){for(var r=0;rthis.checkCountMax&&(this.checkCount=0,this.run()))},e.prototype.run=function(){for(var t=this.renderer.textureManager,e=t._managedTextures,r=!1,n=0;nthis.maxIdle&&(t.destroyTexture(i,!0),r=!(e[n]=null))}if(r){for(var o=0,s=0;s 0.5)"," {"," color = vec4(1.0, 0.0, 0.0, 1.0);"," }"," else"," {"," color = vec4(0.0, 1.0, 0.0, 1.0);"," }"," gl_FragColor = mix(sample, masky, 0.5);"," gl_FragColor *= sample.a;","}"].join("\n")}}]),i}();r.default=l},{"../../../const":46,"../../../settings":101,"../../../utils":125,"./extractUniformsFromSrc":87}],87:[function(t,e,r){"use strict";r.__esModule=!0,r.default=function(t,e,r){var n=o(t),i=o(e);return Object.assign(n,i)};var n,i=t("pixi-gl-core");var c=((n=i)&&n.__esModule?n:{default:n}).default.shader.defaultValue;function o(t){for(var e=new RegExp("^(projectionMatrix|uSampler|filterArea|filterClamp)$"),r={},n=void 0,i=t.replace(/\s+/g," ").split(/\s*;\s*/),o=0;o=n&&l.x=i&&l.y>16)+(65280&t)+((255&t)<<16)}},{key:"texture",get:function(){return this._texture},set:function(t){this._texture!==t&&(this._texture=t||u.default.EMPTY,this.cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,t&&(t.baseTexture.hasLoaded?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}]),n}(n.default);r.default=c},{"../const":46,"../display/Container":48,"../math":70,"../textures/Texture":115,"../utils":125}],103:[function(t,e,r){"use strict";r.__esModule=!0;var n=i(t("../../renderers/canvas/CanvasRenderer")),l=t("../../const"),c=t("../../math"),d=i(t("./CanvasTinter"));function i(t){return t&&t.__esModule?t:{default:t}}var f=new c.Matrix,o=function(){function e(t){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),this.renderer=t}return e.prototype.render=function(t){var e=t._texture,r=this.renderer,n=e._frame.width,i=e._frame.height,o=t.transform.worldTransform,s=0,a=0;if(!(e.orig.width<=0||e.orig.height<=0)&&e.baseTexture.source&&(r.setBlendMode(t.blendMode),e.valid)){r.context.globalAlpha=t.worldAlpha;var u=e.baseTexture.scaleMode===l.SCALE_MODES.LINEAR;r.smoothProperty&&r.context[r.smoothProperty]!==u&&(r.context[r.smoothProperty]=u),e.trim?(s=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,a=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(s=(.5-t.anchor.x)*e.orig.width,a=(.5-t.anchor.y)*e.orig.height),e.rotate&&(o.copy(f),o=f,c.GroupD8.matrixAppendRotationInv(o,e.rotate,s,a),a=s=0),s-=n/2,a-=i/2,r.roundPixels||t.roundPixels?(r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution|0,o.ty*r.resolution|0),s|=0,a|=0):r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution,o.ty*r.resolution);var h=e.baseTexture.resolution;16777215!==t.tint?(t.cachedTint===t.tint&&t.tintedTexture.tintId===t._texture._updateID||(t.cachedTint=t.tint,t.tintedTexture=d.default.getTintedTexture(t,t.tint)),r.context.drawImage(t.tintedTexture,0,0,n*h,i*h,s*r.resolution,a*r.resolution,n*r.resolution,i*r.resolution)):r.context.drawImage(e.baseTexture.source,e._frame.x*h,e._frame.y*h,n*h,i*h,s*r.resolution,a*r.resolution,n*r.resolution,i*r.resolution)}},e.prototype.destroy=function(){this.renderer=null},e}();r.default=o,n.default.registerPlugin("sprite",o)},{"../../const":46,"../../math":70,"../../renderers/canvas/CanvasRenderer":77,"./CanvasTinter":104}],104:[function(t,e,r){"use strict";r.__esModule=!0;var n,f=t("../../utils"),i=t("../../renderers/canvas/utils/canUseNewCanvasBlendModes");var a={getTintedTexture:function(t,e){var r=t._texture,n="#"+("00000"+(0|(e=a.roundColor(e))).toString(16)).substr(-6);r.tintCache=r.tintCache||{};var i=r.tintCache[n],o=void 0;if(i){if(i.tintId===r._updateID)return r.tintCache[n];o=r.tintCache[n]}else o=a.canvas||document.createElement("canvas");if(a.tintMethod(r,e,o),o.tintId=r._updateID,a.convertTintToImage){var s=new Image;s.src=o.toDataURL(),r.tintCache[n]=s}else r.tintCache[n]=o,a.canvas=null;return o},tintWithMultiply:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.save(),n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="multiply",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.restore()},tintWithOverlay:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.save(),n.globalCompositeOperation="copy",n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.restore()},tintWithPerPixel:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.save(),n.globalCompositeOperation="copy",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.restore();for(var s=(0,f.hex2rgb)(e),a=s[0],u=s[1],h=s[2],l=n.getImageData(0,0,i.width,i.height),c=l.data,d=0;d=this.size&&this.flush(),t._texture._uvs&&(this.sprites[this.currentIndex++]=t)},o.prototype.flush=function(){if(0!==this.currentIndex){var t=this.renderer.gl,e=this.MAX_TEXTURES,r=U.default.nextPow2(this.currentIndex),n=U.default.log2(r),i=this.buffers[n],o=this.sprites,s=this.groups,a=i.float32View,u=i.uint32View,h=this.boundTextures,l=this.renderer.boundTextures,c=this.renderer.textureGC.count,d=0,f=void 0,p=void 0,v=1,g=0,y=s[0],m=void 0,_=void 0,b=F.premultiplyBlendMode[o[0]._texture.baseTexture.premultipliedAlpha?1:0][o[0].blendMode];y.textureCount=0,y.start=0,y.blend=b,X++;var x=void 0;for(x=0;x=r.length)break;o=r[i++]}else{if((i=r.next()).done)break;o=i.value}var s=o;this.animations[e].push(this.textures[s])}}},c.prototype._parseComplete=function(){var t=this._callback;this._callback=null,this._batchIndex=0,t.call(this,this.textures)},c.prototype._nextBatch=function(){var t=this;this._processFrames(this._batchIndex*c.BATCH_SIZE),this._batchIndex++,setTimeout(function(){t._batchIndex*c.BATCH_SIZEthis.baseTexture.width,s=r+i>this.baseTexture.height;if(o||s){var a=o&&s?"and":"or",u="X: "+e+" + "+n+" = "+(e+n)+" > "+this.baseTexture.width,h="Y: "+r+" + "+i+" = "+(r+i)+" > "+this.baseTexture.height;throw new Error("Texture Error: frame does not fit inside the base Texture dimensions: "+u+" "+a+" "+h)}this.valid=n&&i&&this.baseTexture.hasLoaded,this.trim||this.rotate||(this.orig=t),this.valid&&this._updateUvs()}},{key:"rotate",get:function(){return this._rotate},set:function(t){this._rotate=t,this.valid&&this._updateUvs()}},{key:"width",get:function(){return this.orig.width}},{key:"height",get:function(){return this.orig.height}}]),u}(a.default);function f(t){t.destroy=function(){},t.on=function(){},t.once=function(){},t.emit=function(){}}(r.default=d).EMPTY=new d(new o.default),f(d.EMPTY),f(d.EMPTY.baseTexture),d.WHITE=function(){var t=document.createElement("canvas");t.width=10,t.height=10;var e=t.getContext("2d");return e.fillStyle="white",e.fillRect(0,0,10,10),new d(new o.default(t))}(),f(d.WHITE),f(d.WHITE.baseTexture)},{"../math":70,"../settings":101,"../utils":125,"./BaseTexture":112,"./TextureUvs":117,"./VideoBaseTexture":118,eventemitter3:3}],116:[function(t,e,r){"use strict";r.__esModule=!0;var n,i=function(){function n(t,e){for(var r=0;re.priority){t.connect(r);break}e=(r=e).next}t.previous||t.connect(r)}else t.connect(r);return this._startIfPossible(),this},t.prototype.remove=function(t,e){for(var r=this._head.next;r;)r=r.match(t,e)?r.destroy():r.next;return this._head.next||this._cancelIfNeeded(),this},t.prototype.start=function(){this.started||(this.started=!0,this._requestIfNeeded())},t.prototype.stop=function(){this.started&&(this.started=!1,this._cancelIfNeeded())},t.prototype.destroy=function(){this.stop();for(var t=this._head.next;t;)t=t.destroy(!0);this._head.destroy(),this._head=null},t.prototype.update=function(){var t=0this.lastTime){(e=this.elapsedMS=t-this.lastTime)>this._maxElapsedMS&&(e=this._maxElapsedMS),this.deltaTime=e*i.default.TARGET_FPMS*this.speed;for(var r=this._head,n=r.next;n;)n=n.emit(this.deltaTime);r.next||this._cancelIfNeeded()}else this.deltaTime=this.elapsedMS=0;this.lastTime=t},n(t,[{key:"FPS",get:function(){return 1e3/this.elapsedMS}},{key:"minFPS",get:function(){return 1e3/this._maxElapsedMS},set:function(t){var e=Math.min(Math.max(0,t)/1e3,i.default.TARGET_FPMS);this._maxElapsedMS=1/e}}]),t}();r.default=u},{"../const":46,"../settings":101,"./TickerListener":120}],120:[function(t,e,r){"use strict";r.__esModule=!0;var n=function(){function i(t){var e=1>16&255)/255,e[1]=(t>>8&255)/255,e[2]=(255&t)/255,e},r.hex2string=function(t){return t=t.toString(16),"#"+(t="000000".substr(0,6-t.length)+t)},r.rgb2hex=function(t){return(255*t[0]<<16)+(255*t[1]<<8)+(255*t[2]|0)},r.getResolutionOfUrl=function(t,e){var r=i.default.RETINA_PREFIX.exec(t);if(r)return parseFloat(r[1]);return void 0!==e?e:1},r.decomposeDataUri=function(t){var e=n.DATA_URI.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,charset:e[3]?e[3].toLowerCase():void 0,encoding:e[4]?e[4].toLowerCase():void 0,data:e[5]};return},r.getUrlFileExtension=function(t){var e=n.URL_FILE_EXTENSION.exec(t);if(e)return e[1].toLowerCase();return},r.getSvgSize=function(t){var e=n.SVG_SIZE.exec(t),r={};e&&(r[e[1]]=Math.round(parseFloat(e[3])),r[e[5]]=Math.round(parseFloat(e[7])));return r},r.skipHello=function(){v=!0},r.sayHello=function(t){if(v)return;if(-1>16&255,n=t>>8&255,i=255&t;return(255*e<<24)+((r=r*e+.5|0)<<16)+((n=n*e+.5|0)<<8)+(i=i*e+.5|0)},r.premultiplyRgba=function(t,e,r,n){r=r||new Float32Array(4),n||void 0===n?(r[0]=t[0]*e,r[1]=t[1]*e,r[2]=t[2]*e):(r[0]=t[0],r[1]=t[1],r[2]=t[2]);return r[3]=e,r},r.premultiplyTintToRgba=function(t,e,r,n){(r=r||new Float32Array(4))[0]=(t>>16&255)/255,r[1]=(t>>8&255)/255,r[2]=(255&t)/255,(n||void 0===n)&&(r[0]*=e,r[1]*=e,r[2]*=e);return r[3]=e,r};var n=t("../const"),i=f(t("../settings")),o=f(t("eventemitter3")),s=f(t("./pluginTarget")),a=d(t("./mixin")),u=d(t("ismobilejs")),h=f(t("remove-array-items")),l=f(t("./mapPremultipliedBlendModes")),c=f(t("earcut"));function d(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function f(t){return t&&t.__esModule?t:{default:t}}var p=0,v=!1;r.isMobile=u,r.removeItems=h.default,r.EventEmitter=o.default,r.pluginTarget=s.default,r.mixins=a,r.earcut=c.default;var g=r.TextureCache=Object.create(null),y=r.BaseTextureCache=Object.create(null);var m=r.premultiplyBlendMode=(0,l.default)()},{"../const":46,"../settings":101,"./mapPremultipliedBlendModes":126,"./mixin":128,"./pluginTarget":129,earcut:2,eventemitter3:3,ismobilejs:4,"remove-array-items":31}],126:[function(t,e,r){"use strict";r.__esModule=!0,r.default=function(){for(var t=[],e=[],r=0;r<32;r++)t[r]=r,e[r]=r;t[i.BLEND_MODES.NORMAL_NPM]=i.BLEND_MODES.NORMAL,t[i.BLEND_MODES.ADD_NPM]=i.BLEND_MODES.ADD,t[i.BLEND_MODES.SCREEN_NPM]=i.BLEND_MODES.SCREEN,e[i.BLEND_MODES.NORMAL]=i.BLEND_MODES.NORMAL_NPM,e[i.BLEND_MODES.ADD]=i.BLEND_MODES.ADD_NPM,e[i.BLEND_MODES.SCREEN]=i.BLEND_MODES.SCREEN_NPM;var n=[];return n.push(e),n.push(t),n};var i=t("../const")},{"../const":46}],127:[function(t,e,r){"use strict";r.__esModule=!0,r.default=function(t){if(o.default.tablet||o.default.phone)return 4;return t};var n,i=t("ismobilejs"),o=(n=i)&&n.__esModule?n:{default:n}},{ismobilejs:4}],128:[function(t,e,r){"use strict";function n(t,e){if(t&&e)for(var r=Object.keys(e),n=0;n=this._durations[this.currentFrame];)n-=this._durations[this.currentFrame]*i,this._currentTime+=i;this._currentTime+=n/this._durations[this.currentFrame]}else this._currentTime+=e;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):r!==this.currentFrame&&(this.loop&&this.onLoop&&(0r&&this.onLoop()),this.updateTexture())},i.prototype.updateTexture=function(){this._texture=this._textures[this.currentFrame],this._textureID=-1,this.cachedTint=16777215,this.onFrameChange&&this.onFrameChange(this.currentFrame)},i.prototype.destroy=function(t){this.stop(),n.prototype.destroy.call(this,t)},i.fromFrames=function(t){for(var e=[],r=0;ra&&(++p,A.utils.removeItems(n,1+d-p,1+g-d),g=d,d=-1,i.push(f),l=Math.max(l,f),c++,r.x=0,r.y+=t.lineHeight,u=null))}else i.push(h),l=Math.max(l,h),++c,++p,r.x=0,r.y+=t.lineHeight,u=null}var b=o.charAt(o.length-1);"\r"!==b&&"\n"!==b&&(/(?:\s)/.test(b)&&(h=f),i.push(h),l=Math.max(l,h));for(var x=[],T=0;T<=c;T++){var w=0;"right"===this._font.align?w=l-i[T]:"center"===this._font.align&&(w=(l-i[T])/2),x.push(w)}for(var E=n.length,S=this.tint,O=0;O=n&&a.x=i&&a.y 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n"));return t.uniforms.m=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],t.alpha=1,t}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(r,e),r.prototype._loadMatrix=function(t){var e=t;1>16&255)/255,s=(r>>8&255)/255,a=(255&r)/255,u=((n=n||3375104)>>16&255)/255,h=(n>>8&255)/255,l=(255&n)/255,c=[.3,.59,.11,0,0,o,s,a,t=t||.2,0,u,h,l,e=e||.15,0,o-u,s-h,a-l,0,0];this._loadMatrix(c,i)},r.prototype.night=function(t,e){var r=[-2*(t=t||.1),-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},r.prototype.predator=function(t,e){var r=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(r,e)},r.prototype.lsd=function(t){this._loadMatrix([2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0],t)},r.prototype.reset=function(){this._loadMatrix([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],!1)},n(r,[{key:"matrix",get:function(){return this.uniforms.m},set:function(t){this.uniforms.m=t}},{key:"alpha",get:function(){return this.uniforms.uAlpha},set:function(t){this.uniforms.uAlpha=t}}]),r}(i.Filter);(r.default=o).prototype.grayscale=o.prototype.greyscale},{"../../core":65,path:8}],151:[function(t,e,r){"use strict";r.__esModule=!0;var n=function(){function n(t,e){for(var r=0;r lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n'))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,t),e}(n.Filter);r.default=i},{"../../core":65,path:8}],153:[function(t,e,r){"use strict";r.__esModule=!0;var n=t("./fxaa/FXAAFilter");Object.defineProperty(r,"FXAAFilter",{enumerable:!0,get:function(){return c(n).default}});var i=t("./noise/NoiseFilter");Object.defineProperty(r,"NoiseFilter",{enumerable:!0,get:function(){return c(i).default}});var o=t("./displacement/DisplacementFilter");Object.defineProperty(r,"DisplacementFilter",{enumerable:!0,get:function(){return c(o).default}});var s=t("./blur/BlurFilter");Object.defineProperty(r,"BlurFilter",{enumerable:!0,get:function(){return c(s).default}});var a=t("./blur/BlurXFilter");Object.defineProperty(r,"BlurXFilter",{enumerable:!0,get:function(){return c(a).default}});var u=t("./blur/BlurYFilter");Object.defineProperty(r,"BlurYFilter",{enumerable:!0,get:function(){return c(u).default}});var h=t("./colormatrix/ColorMatrixFilter");Object.defineProperty(r,"ColorMatrixFilter",{enumerable:!0,get:function(){return c(h).default}});var l=t("./alpha/AlphaFilter");function c(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(r,"AlphaFilter",{enumerable:!0,get:function(){return c(l).default}})},{"./alpha/AlphaFilter":143,"./blur/BlurFilter":144,"./blur/BlurXFilter":145,"./blur/BlurYFilter":146,"./colormatrix/ColorMatrixFilter":150,"./displacement/DisplacementFilter":151,"./fxaa/FXAAFilter":152,"./noise/NoiseFilter":154}],154:[function(t,e,r){"use strict";r.__esModule=!0;var o=function(){function n(t,e){for(var r=0;r 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n"));return r.noise=t,r.seed=e,r}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(i,n),o(i,[{key:"noise",get:function(){return this.uniforms.uNoise},set:function(t){this.uniforms.uNoise=t}},{key:"seed",get:function(){return this.uniforms.uSeed},set:function(t){this.uniforms.uSeed=t}}]),i}(n.Filter);r.default=i},{"../../core":65,path:8}],155:[function(t,e,r){"use strict";r.__esModule=!0;var n=function(){function n(t,e){for(var r=0;re?1:this._height/e;t[9]=t[11]=t[13]=t[15]=this._topHeight*r,t[17]=t[19]=t[21]=t[23]=this._height-this._bottomHeight*r,t[25]=t[27]=t[29]=t[31]=this._height},a.prototype.updateVerticalVertices=function(){var t=this.vertices,e=this._leftWidth+this._rightWidth,r=this._width>e?1:this._width/e;t[2]=t[10]=t[18]=t[26]=this._leftWidth*r,t[4]=t[12]=t[20]=t[28]=this._width-this._rightWidth*r,t[6]=t[14]=t[22]=t[30]=this._width},a.prototype._renderCanvas=function(t){var e=t.context;e.globalAlpha=this.worldAlpha,t.setBlendMode(this.blendMode);var r=this.worldTransform,n=t.resolution;t.roundPixels||this.roundPixels?e.setTransform(r.a*n,r.b*n,r.c*n,r.d*n,r.tx*n|0,r.ty*n|0):e.setTransform(r.a*n,r.b*n,r.c*n,r.d*n,r.tx*n,r.ty*n);var i=this._texture.baseTexture,o=i.source,s=i.width*i.resolution,a=i.height*i.resolution;this.drawSegment(e,o,s,a,0,1,10,11),this.drawSegment(e,o,s,a,2,3,12,13),this.drawSegment(e,o,s,a,4,5,14,15),this.drawSegment(e,o,s,a,8,9,18,19),this.drawSegment(e,o,s,a,10,11,20,21),this.drawSegment(e,o,s,a,12,13,22,23),this.drawSegment(e,o,s,a,16,17,26,27),this.drawSegment(e,o,s,a,18,19,28,29),this.drawSegment(e,o,s,a,20,21,30,31)},a.prototype.drawSegment=function(t,e,r,n,i,o,s,a){var u=this.uvs,h=this.vertices,l=(u[s]-u[i])*r,c=(u[a]-u[o])*n,d=h[s]-h[i],f=h[a]-h[o];l<1&&(l=1),c<1&&(c=1),d<1&&(d=1),f<1&&(f=1),t.drawImage(e,u[i]*r,u[o]*n,l,c,h[i],h[o],d,f)},a.prototype._refresh=function(){s.prototype._refresh.call(this);var t=this.uvs,e=this._texture;this._origWidth=e.orig.width,this._origHeight=e.orig.height;var r=1/this._origWidth,n=1/this._origHeight;t[0]=t[8]=t[16]=t[24]=0,t[1]=t[3]=t[5]=t[7]=0,t[6]=t[14]=t[22]=t[30]=1,t[25]=t[27]=t[29]=t[31]=1,t[2]=t[10]=t[18]=t[26]=r*this._leftWidth,t[4]=t[12]=t[20]=t[28]=1-r*this._rightWidth,t[9]=t[11]=t[13]=t[15]=n*this._topHeight,t[17]=t[19]=t[21]=t[23]=1-n*this._bottomHeight,this.updateHorizontalVertices(),this.updateVerticalVertices(),this.dirty++,this.multiplyUvs()},i(a,[{key:"width",get:function(){return this._width},set:function(t){this._width=t,this._refresh()}},{key:"height",get:function(){return this._height},set:function(t){this._height=t,this._refresh()}},{key:"leftWidth",get:function(){return this._leftWidth},set:function(t){this._leftWidth=t,this._refresh()}},{key:"rightWidth",get:function(){return this._rightWidth},set:function(t){this._rightWidth=t,this._refresh()}},{key:"topHeight",get:function(){return this._topHeight},set:function(t){this._topHeight=t,this._refresh()}},{key:"bottomHeight",get:function(){return this._bottomHeight},set:function(t){this._bottomHeight=t,this._refresh()}}]),a}(s.default);r.default=a},{"./Plane":168}],168:[function(t,e,r){"use strict";r.__esModule=!0;var n,i=t("./Mesh"),s=(n=i)&&n.__esModule?n:{default:n};var o=function(i){function o(t,e,r){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,o);var n=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,i.call(this,t));return n._ready=!0,n.verticesX=e||10,n.verticesY=r||10,n.drawMode=s.default.DRAW_MODES.TRIANGLES,n.refresh(),n}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(o,i),o.prototype._refresh=function(){for(var t=this._texture,e=this.verticesX*this.verticesY,r=[],n=[],i=[],o=this.verticesX-1,s=this.verticesY-1,a=t.width/o,u=t.height/s,h=0;h=s.length){if(!t.autoResize)break;s.push(this._generateOneMoreBuffer(t))}var p=s[d];p.uploadDynamic(e,c,f);var v=t._bufferUpdateIDs[d]||0;(l=l||p._updateID 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],2:[function(require,module,exports){ +'use strict'; + +module.exports = earcut; +module.exports.default = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, invSize; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 1 / invSize : 0; + } + + earcutLinked(outerNode, triangles, dim, minX, minY, invSize); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, invSize) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, invSize), + maxZ = zOrder(maxTX, maxTY, minX, minY, invSize); + + var p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + + if (n !== ear.prev && n !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && + area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + // look for remaining points in decreasing z-order + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + // look for remaining points in increasing z-order + while (n && n.z <= maxZ) { + if (n !== ear.prev && n !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && + area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize); + earcutLinked(c, triangles, dim, minX, minY, invSize); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, invSize) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) * invSize; + y = 32767 * (y - minY) * invSize; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; + +},{}],3:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @api private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {Mixed} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @api public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @api public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Boolean} exists Only check if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Add a one-time listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Remove the listeners of a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {Mixed} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn + && (!once || listeners.once) + && (!context || listeners.context === context) + ) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {String|Symbol} [event] The event name. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],4:[function(require,module,exports){ +/** + * isMobile.js v0.4.1 + * + * A simple library to detect Apple phones and tablets, + * Android phones and tablets, other mobile devices (like blackberry, mini-opera and windows phone), + * and any kind of seven inch device, via user agent sniffing. + * + * @author: Kai Mallea (kmallea@gmail.com) + * + * @license: http://creativecommons.org/publicdomain/zero/1.0/ + */ +(function (global) { + + var apple_phone = /iPhone/i, + apple_ipod = /iPod/i, + apple_tablet = /iPad/i, + android_phone = /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i, // Match 'Android' AND 'Mobile' + android_tablet = /Android/i, + amazon_phone = /(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i, + amazon_tablet = /(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i, + windows_phone = /Windows Phone/i, + windows_tablet = /(?=.*\bWindows\b)(?=.*\bARM\b)/i, // Match 'Windows' AND 'ARM' + other_blackberry = /BlackBerry/i, + other_blackberry_10 = /BB10/i, + other_opera = /Opera Mini/i, + other_chrome = /(CriOS|Chrome)(?=.*\bMobile\b)/i, + other_firefox = /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i, // Match 'Firefox' AND 'Mobile' + seven_inch = new RegExp( + '(?:' + // Non-capturing group + + 'Nexus 7' + // Nexus 7 + + '|' + // OR + + 'BNTV250' + // B&N Nook Tablet 7 inch + + '|' + // OR + + 'Kindle Fire' + // Kindle Fire + + '|' + // OR + + 'Silk' + // Kindle Fire, Silk Accelerated + + '|' + // OR + + 'GT-P1000' + // Galaxy Tab 7 inch + + ')', // End non-capturing group + + 'i'); // Case-insensitive matching + + var match = function(regex, userAgent) { + return regex.test(userAgent); + }; + + var IsMobileClass = function(userAgent) { + var ua = userAgent || navigator.userAgent; + + // Facebook mobile app's integrated browser adds a bunch of strings that + // match everything. Strip it out if it exists. + var tmp = ua.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + // Twitter mobile app's integrated browser on iPad adds a "Twitter for + // iPhone" string. Same probable happens on other tablet platforms. + // This will confuse detection so strip it out if it exists. + tmp = ua.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + ua = tmp[0]; + } + + this.apple = { + phone: match(apple_phone, ua), + ipod: match(apple_ipod, ua), + tablet: !match(apple_phone, ua) && match(apple_tablet, ua), + device: match(apple_phone, ua) || match(apple_ipod, ua) || match(apple_tablet, ua) + }; + this.amazon = { + phone: match(amazon_phone, ua), + tablet: !match(amazon_phone, ua) && match(amazon_tablet, ua), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) + }; + this.android = { + phone: match(amazon_phone, ua) || match(android_phone, ua), + tablet: !match(amazon_phone, ua) && !match(android_phone, ua) && (match(amazon_tablet, ua) || match(android_tablet, ua)), + device: match(amazon_phone, ua) || match(amazon_tablet, ua) || match(android_phone, ua) || match(android_tablet, ua) + }; + this.windows = { + phone: match(windows_phone, ua), + tablet: match(windows_tablet, ua), + device: match(windows_phone, ua) || match(windows_tablet, ua) + }; + this.other = { + blackberry: match(other_blackberry, ua), + blackberry10: match(other_blackberry_10, ua), + opera: match(other_opera, ua), + firefox: match(other_firefox, ua), + chrome: match(other_chrome, ua), + device: match(other_blackberry, ua) || match(other_blackberry_10, ua) || match(other_opera, ua) || match(other_firefox, ua) || match(other_chrome, ua) + }; + this.seven_inch = match(seven_inch, ua); + this.any = this.apple.device || this.android.device || this.windows.device || this.other.device || this.seven_inch; + + // excludes 'other' devices and ipods, targeting touchscreen phones + this.phone = this.apple.phone || this.android.phone || this.windows.phone; + + // excludes 7 inch devices, classifying as phone or tablet is left to the user + this.tablet = this.apple.tablet || this.android.tablet || this.windows.tablet; + + if (typeof window === 'undefined') { + return this; + } + }; + + var instantiate = function() { + var IM = new IsMobileClass(); + IM.Class = IsMobileClass; + return IM; + }; + + if (typeof module !== 'undefined' && module.exports && typeof window === 'undefined') { + //node + module.exports = IsMobileClass; + } else if (typeof module !== 'undefined' && module.exports && typeof window !== 'undefined') { + //browserify + module.exports = instantiate(); + } else if (typeof define === 'function' && define.amd) { + //AMD + define('isMobile', [], global.isMobile = instantiate()); + } else { + global.isMobile = instantiate(); + } + +})(this); + +},{}],5:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + +var MiniSignalBinding = (function () { + function MiniSignalBinding(fn, once, thisArg) { + if (once === undefined) once = false; + + _classCallCheck(this, MiniSignalBinding); + + this._fn = fn; + this._once = once; + this._thisArg = thisArg; + this._next = this._prev = this._owner = null; + } + + _createClass(MiniSignalBinding, [{ + key: 'detach', + value: function detach() { + if (this._owner === null) return false; + this._owner.detach(this); + return true; + } + }]); + + return MiniSignalBinding; +})(); + +function _addMiniSignalBinding(self, node) { + if (!self._head) { + self._head = node; + self._tail = node; + } else { + self._tail._next = node; + node._prev = self._tail; + self._tail = node; + } + + node._owner = self; + + return node; +} + +var MiniSignal = (function () { + function MiniSignal() { + _classCallCheck(this, MiniSignal); + + this._head = this._tail = undefined; + } + + _createClass(MiniSignal, [{ + key: 'handlers', + value: function handlers() { + var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; + + var node = this._head; + + if (exists) return !!node; + + var ee = []; + + while (node) { + ee.push(node); + node = node._next; + } + + return ee; + } + }, { + key: 'has', + value: function has(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.'); + } + + return node._owner === this; + } + }, { + key: 'dispatch', + value: function dispatch() { + var node = this._head; + + if (!node) return false; + + while (node) { + if (node._once) this.detach(node); + node._fn.apply(node._thisArg, arguments); + node = node._next; + } + + return true; + } + }, { + key: 'add', + value: function add(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#add(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg)); + } + }, { + key: 'once', + value: function once(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#once(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg)); + } + }, { + key: 'detach', + value: function detach(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.'); + } + if (node._owner !== this) return this; + + if (node._prev) node._prev._next = node._next; + if (node._next) node._next._prev = node._prev; + + if (node === this._head) { + this._head = node._next; + if (node._next === null) { + this._tail = null; + } + } else if (node === this._tail) { + this._tail = node._prev; + this._tail._next = null; + } + + node._owner = null; + return this; + } + }, { + key: 'detachAll', + value: function detachAll() { + var node = this._head; + if (!node) return this; + + this._head = this._tail = null; + + while (node) { + node._owner = null; + node = node._next; + } + return this; + } + }]); + + return MiniSignal; +})(); + +MiniSignal.MiniSignalBinding = MiniSignalBinding; + +exports['default'] = MiniSignal; +module.exports = exports['default']; + +},{}],6:[function(require,module,exports){ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],7:[function(require,module,exports){ +'use strict' + +module.exports = function parseURI (str, opts) { + opts = opts || {} + + var o = { + key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], + q: { + name: 'queryKey', + parser: /(?:^|&)([^&=]*)=?([^&]*)/g + }, + parser: { + strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, + loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ + } + } + + var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str) + var uri = {} + var i = 14 + + while (i--) uri[o.key[i]] = m[i] || '' + + uri[o.q.name] = {} + uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { + if ($1) uri[o.q.name][$1] = $2 + }) + + return uri +} + +},{}],8:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) + +},{"_process":26}],9:[function(require,module,exports){ +var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); + +/** + * Helper class to create a webGL buffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ +var Buffer = function(gl, type, data, drawType) +{ + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The WebGL buffer, created upon instantiation + * + * @member {WebGLBuffer} + */ + this.buffer = gl.createBuffer(); + + /** + * The type of the buffer + * + * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} + */ + this.type = type || gl.ARRAY_BUFFER; + + /** + * The draw type of the buffer + * + * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ + this.drawType = drawType || gl.STATIC_DRAW; + + /** + * The data in the buffer, as a typed array + * + * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} + */ + this.data = EMPTY_ARRAY_BUFFER; + + if(data) + { + this.upload(data); + } + + this._updateID = 0; +}; + +/** + * Uploads the buffer to the GPU + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload + * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract + * @param dontBind {Boolean} whether to bind the buffer before uploading it + */ +Buffer.prototype.upload = function(data, offset, dontBind) +{ + // todo - needed? + if(!dontBind) this.bind(); + + var gl = this.gl; + + data = data || this.data; + offset = offset || 0; + + if(this.data.byteLength >= data.byteLength) + { + gl.bufferSubData(this.type, offset, data); + } + else + { + gl.bufferData(this.type, data, this.drawType); + } + + this.data = data; +}; +/** + * Binds the buffer + * + */ +Buffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindBuffer(this.type, this.buffer); +}; + +Buffer.createVertexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); +}; + +Buffer.createIndexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); +}; + +Buffer.create = function(gl, type, data, drawType) +{ + return new Buffer(gl, type, data, drawType); +}; + +/** + * Destroys the buffer + * + */ +Buffer.prototype.destroy = function(){ + this.gl.deleteBuffer(this.buffer); +}; + +module.exports = Buffer; + +},{}],10:[function(require,module,exports){ + +var Texture = require('./GLTexture'); + +/** + * Helper class to create a webGL Framebuffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + */ +var Framebuffer = function(gl, width, height) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The frame buffer + * + * @member {WebGLFramebuffer} + */ + this.framebuffer = gl.createFramebuffer(); + + /** + * The stencil buffer + * + * @member {WebGLRenderbuffer} + */ + this.stencil = null; + + /** + * The stencil buffer + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The width of the drawing area of the buffer + * + * @member {Number} + */ + this.width = width || 100; + /** + * The height of the drawing area of the buffer + * + * @member {Number} + */ + this.height = height || 100; +}; + +/** + * Adds a texture to the frame buffer + * @param texture {PIXI.glCore.GLTexture} + */ +Framebuffer.prototype.enableTexture = function(texture) +{ + var gl = this.gl; + + this.texture = texture || new Texture(gl); + + this.texture.bind(); + + //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + this.bind(); + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); +}; + +/** + * Initialises the stencil buffer + */ +Framebuffer.prototype.enableStencil = function() +{ + if(this.stencil)return; + + var gl = this.gl; + + this.stencil = gl.createRenderbuffer(); + + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + + // TODO.. this is depth AND stencil? + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width , this.height ); + + +}; + +/** + * Erases the drawing area and fills it with a colour + * @param r {Number} the red value of the clearing colour + * @param g {Number} the green value of the clearing colour + * @param b {Number} the blue value of the clearing colour + * @param a {Number} the alpha value of the clearing colour + */ +Framebuffer.prototype.clear = function( r, g, b, a ) +{ + this.bind(); + + var gl = this.gl; + + gl.clearColor(r, g, b, a); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); +}; + +/** + * Binds the frame buffer to the WebGL context + */ +Framebuffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); +}; + +/** + * Unbinds the frame buffer to the WebGL context + */ +Framebuffer.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, null ); +}; +/** + * Resizes the drawing area of the buffer to the given width and height + * @param width {Number} the new width + * @param height {Number} the new height + */ +Framebuffer.prototype.resize = function(width, height) +{ + var gl = this.gl; + + this.width = width; + this.height = height; + + if ( this.texture ) + { + this.texture.uploadData(null, width, height); + } + + if ( this.stencil ) + { + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + } +}; + +/** + * Destroys this buffer + */ +Framebuffer.prototype.destroy = function() +{ + var gl = this.gl; + + //TODO + if(this.texture) + { + this.texture.destroy(); + } + + gl.deleteFramebuffer(this.framebuffer); + + this.gl = null; + + this.stencil = null; + this.texture = null; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createRGBA = function(gl, width, height, data) +{ + var texture = Texture.fromData(gl, null, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + //fbo.enableStencil(); // get this back on soon! + + //fbo.enableStencil(); // get this back on soon! + + fbo.unbind(); + + return fbo; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createFloat32 = function(gl, width, height, data) +{ + // create a new texture.. + var texture = new Texture.fromData(gl, data, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +module.exports = Framebuffer; + +},{"./GLTexture":12}],11:[function(require,module,exports){ + +var compileProgram = require('./shader/compileProgram'), + extractAttributes = require('./shader/extractAttributes'), + extractUniforms = require('./shader/extractUniforms'), + setPrecision = require('./shader/setPrecision'), + generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + +/** + * Helper class to create a webGL Shader + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + */ +var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + if(precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } + + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); + + this.uniformData = extractUniforms(gl, this.program); + + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + +}; +/** + * Uses this shader + * + * @return {PIXI.glCore.GLShader} Returns itself. + */ +Shader.prototype.bind = function() +{ + this.gl.useProgram(this.program); + return this; +}; + +/** + * Destroys this shader + * TODO + */ +Shader.prototype.destroy = function() +{ + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + + var gl = this.gl; + gl.deleteProgram(this.program); +}; + + +module.exports = Shader; + +},{"./shader/compileProgram":17,"./shader/extractAttributes":19,"./shader/extractUniforms":20,"./shader/generateUniformAccessObject":21,"./shader/setPrecision":25}],12:[function(require,module,exports){ + +/** + * Helper class to create a WebGL Texture + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL context + * @param width {number} the width of the texture + * @param height {number} the height of the texture + * @param format {number} the pixel format of the texture. defaults to gl.RGBA + * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE + */ +var Texture = function(gl, width, height, format, type) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); + + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; + + + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; + + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; + + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + + +}; + +/** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ +Texture.prototype.upload = function(source) +{ + this.bind(); + + var gl = this.gl; + + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + var newWidth = source.videoWidth || source.width; + var newHeight = source.videoHeight || source.height; + + if(newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } + + // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + +}; + +var FLOATING_POINT_AVAILABLE = false; + +/** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.prototype.uploadData = function(data, width, height) +{ + this.bind(); + + var gl = this.gl; + + + if(data instanceof Float32Array) + { + if(!FLOATING_POINT_AVAILABLE) + { + var ext = gl.getExtension("OES_texture_float"); + + if(ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } + + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } + + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + + if(width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } + + this.width = width; + this.height = height; + + +// texSubImage2D +}; + +/** + * Binds the texture + * @param location + */ +Texture.prototype.bind = function(location) +{ + var gl = this.gl; + + if(location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } + + gl.bindTexture(gl.TEXTURE_2D, this.texture); +}; + +/** + * Unbinds the texture + */ +Texture.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, null); +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.minFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + if(this.mipmap) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.magFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); +}; + +/** + * Enables mipmapping + */ +Texture.prototype.enableMipmap = function() +{ + var gl = this.gl; + + this.bind(); + + this.mipmap = true; + + gl.generateMipmap(gl.TEXTURE_2D); +}; + +/** + * Enables linear filtering + */ +Texture.prototype.enableLinearScaling = function() +{ + this.minFilter(true); + this.magFilter(true); +}; + +/** + * Enables nearest neighbour interpolation + */ +Texture.prototype.enableNearestScaling = function() +{ + this.minFilter(false); + this.magFilter(false); +}; + +/** + * Enables clamping on the texture so WebGL will not repeat it + */ +Texture.prototype.enableWrapClamp = function() +{ + var gl = this.gl; + + this.bind(); + + 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); +}; + +/** + * Enable tiling on the texture + */ +Texture.prototype.enableWrapRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); +}; + +Texture.prototype.enableWrapMirrorRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); +}; + + +/** + * Destroys this texture + */ +Texture.prototype.destroy = function() +{ + var gl = this.gl; + //TODO + gl.deleteTexture(this.texture); +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ +Texture.fromSource = function(gl, source, premultiplyAlpha) +{ + var texture = new Texture(gl); + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); + + return texture; +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.fromData = function(gl, data, width, height) +{ + //console.log(data, width, height); + var texture = new Texture(gl); + texture.uploadData(data, width, height); + + return texture; +}; + + +module.exports = Texture; + +},{}],13:[function(require,module,exports){ + +// state object// +var setVertexAttribArrays = require( './setVertexAttribArrays' ); + +/** + * Helper class to work with WebGL VertexArrayObjects (vaos) + * Only works if WebGL extensions are enabled (they usually are) + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function VertexArrayObject(gl, state) +{ + this.nativeVaoExtension = null; + + if(!VertexArrayObject.FORCE_NATIVE) + { + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + this.nativeState = state; + + if(this.nativeVaoExtension) + { + this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + + var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + // VAO - overwrite the state.. + this.nativeState = { + tempAttribState: new Array(maxAttribs), + attribState: new Array(maxAttribs) + }; + } + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of attributes + * + * @member {Array} + */ + this.attributes = []; + + /** + * @member {PIXI.glCore.GLBuffer} + */ + this.indexBuffer = null; + + /** + * A boolean flag + * + * @member {Boolean} + */ + this.dirty = false; +} + +VertexArrayObject.prototype.constructor = VertexArrayObject; +module.exports = VertexArrayObject; + +/** +* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) +* If you find on older devices that things have gone a bit weird then set this to true. +*/ +/** + * Lets the VAO know if you should use the WebGL extension or the native methods. + * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) + * If you find on older devices that things have gone a bit weird then set this to true. + * @static + * @property {Boolean} FORCE_NATIVE + */ +VertexArrayObject.FORCE_NATIVE = false; + +/** + * Binds the buffer + */ +VertexArrayObject.prototype.bind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + + if(this.dirty) + { + this.dirty = false; + this.activate(); + return this; + } + if (this.indexBuffer) + { + this.indexBuffer.bind(); + } + } + else + { + this.activate(); + } + + return this; +}; + +/** + * Unbinds the buffer + */ +VertexArrayObject.prototype.unbind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + return this; +}; + +/** + * Uses this vao + */ +VertexArrayObject.prototype.activate = function() +{ + + var gl = this.gl; + var lastBuffer = null; + + for (var i = 0; i < this.attributes.length; i++) + { + var attrib = this.attributes[i]; + + if(lastBuffer !== attrib.buffer) + { + attrib.buffer.bind(); + lastBuffer = attrib.buffer; + } + + gl.vertexAttribPointer(attrib.attribute.location, + attrib.attribute.size, + attrib.type || gl.FLOAT, + attrib.normalized || false, + attrib.stride || 0, + attrib.start || 0); + } + + setVertexAttribArrays(gl, this.attributes, this.nativeState); + + if(this.indexBuffer) + { + this.indexBuffer.bind(); + } + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + * @param attribute {*} + * @param type {String} + * @param normalized {Boolean} + * @param stride {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start) +{ + this.attributes.push({ + buffer: buffer, + attribute: attribute, + + location: attribute.location, + type: type || this.gl.FLOAT, + normalized: normalized || false, + stride: stride || 0, + start: start || 0 + }); + + this.dirty = true; + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + */ +VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) +{ + this.indexBuffer = buffer; + + this.dirty = true; + + return this; +}; + +/** + * Unbinds this vao and disables it + */ +VertexArrayObject.prototype.clear = function() +{ + // var gl = this.gl; + + // TODO - should this function unbind after clear? + // for now, no but lets see what happens in the real world! + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + } + + this.attributes.length = 0; + this.indexBuffer = null; + + return this; +}; + +/** + * @param type {Number} + * @param size {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.draw = function(type, size, start) +{ + var gl = this.gl; + + if(this.indexBuffer) + { + gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + } + else + { + // TODO need a better way to calculate size.. + gl.drawArrays(type, start, size || this.getSize()); + } + + return this; +}; + +/** + * Destroy this vao + */ +VertexArrayObject.prototype.destroy = function() +{ + // lose references + this.gl = null; + this.indexBuffer = null; + this.attributes = null; + this.nativeState = null; + + if(this.nativeVao) + { + this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); + } + + this.nativeVaoExtension = null; + this.nativeVao = null; +}; + +VertexArrayObject.prototype.getSize = function() +{ + var attrib = this.attributes[0]; + return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); +}; + +},{"./setVertexAttribArrays":16}],14:[function(require,module,exports){ + +/** + * Helper class to create a webGL Context + * + * @class + * @memberof PIXI.glCore + * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from + * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * @return {WebGLRenderingContext} the WebGL context + */ +var createContext = function(canvas, options) +{ + var gl = canvas.getContext('webgl', options) || + canvas.getContext('experimental-webgl', options); + + if (!gl) + { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + return gl; +}; + +module.exports = createContext; + +},{}],15:[function(require,module,exports){ +var gl = { + createContext: require('./createContext'), + setVertexAttribArrays: require('./setVertexAttribArrays'), + GLBuffer: require('./GLBuffer'), + GLFramebuffer: require('./GLFramebuffer'), + GLShader: require('./GLShader'), + GLTexture: require('./GLTexture'), + VertexArrayObject: require('./VertexArrayObject'), + shader: require('./shader') +}; + +// Export for Node-compatible environments +if (typeof module !== 'undefined' && module.exports) +{ + // Export the module + module.exports = gl; +} + +// Add to the browser window pixi.gl +if (typeof window !== 'undefined') +{ + // add the window object + window.PIXI = window.PIXI || {}; + window.PIXI.glCore = gl; +} + +},{"./GLBuffer":9,"./GLFramebuffer":10,"./GLShader":11,"./GLTexture":12,"./VertexArrayObject":13,"./createContext":14,"./setVertexAttribArrays":16,"./shader":22}],16:[function(require,module,exports){ +// var GL_MAP = {}; + +/** + * @param gl {WebGLRenderingContext} The current WebGL context + * @param attribs {*} + * @param state {*} + */ +var setVertexAttribArrays = function (gl, attribs, state) +{ + var i; + if(state) + { + var tempAttribState = state.tempAttribState, + attribState = state.attribState; + + for (i = 0; i < tempAttribState.length; i++) + { + tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + tempAttribState[attribs[i].attribute.location] = true; + } + + for (i = 0; i < attribState.length; i++) + { + if (attribState[i] !== tempAttribState[i]) + { + attribState[i] = tempAttribState[i]; + + if (state.attribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } + + } + else + { + for (i = 0; i < attribs.length; i++) + { + var attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); + } + } +}; + +module.exports = setVertexAttribArrays; + +},{}],17:[function(require,module,exports){ + +/** + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations + * @return {WebGLProgram} the shader program + */ +var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +{ + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + + var program = gl.createProgram(); + + gl.attachShader(program, glVertShader); + gl.attachShader(program, glFragShader); + + // optionally, set the attributes manually for the program rather than letting WebGL decide.. + if(attributeLocations) + { + for(var i in attributeLocations) + { + gl.bindAttribLocation(program, attributeLocations[i], i); + } + } + + + gl.linkProgram(program); + + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + console.error('Pixi.js Error: Could not initialize shader.'); + console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); + console.error('gl.getError()', gl.getError()); + + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') + { + console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + + gl.deleteProgram(program); + program = null; + } + + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + + return program; +}; + +/** + * @private + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @return {WebGLShader} the shader + */ +var compileShader = function (gl, type, src) +{ + var shader = gl.createShader(type); + + gl.shaderSource(shader, src); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + console.log(gl.getShaderInfoLog(shader)); + return null; + } + + return shader; +}; + +module.exports = compileProgram; + +},{}],18:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} Type of value + * @param size {Number} + */ +var defaultValue = function(type, size) +{ + switch (type) + { + case 'float': + return 0; + + case 'vec2': + return new Float32Array(2 * size); + + case 'vec3': + return new Float32Array(3 * size); + + case 'vec4': + return new Float32Array(4 * size); + + case 'int': + case 'sampler2D': + return 0; + + case 'ivec2': + return new Int32Array(2 * size); + + case 'ivec3': + return new Int32Array(3 * size); + + case 'ivec4': + return new Int32Array(4 * size); + + case 'bool': + return false; + + case 'bvec2': + + return booleanArray( 2 * size); + + case 'bvec3': + return booleanArray(3 * size); + + case 'bvec4': + return booleanArray(4 * size); + + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } +}; + +var booleanArray = function(size) +{ + var array = new Array(size); + + for (var i = 0; i < array.length; i++) + { + array[i] = false; + } + + return array; +}; + +module.exports = defaultValue; + +},{}],19:[function(require,module,exports){ + +var mapType = require('./mapType'); +var mapSize = require('./mapSize'); + +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the attributes from + * @return attributes {Object} + */ +var extractAttributes = function(gl, program) +{ + var attributes = {}; + + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + + for (var i = 0; i < totalAttributes; i++) + { + var attribData = gl.getActiveAttrib(program, i); + var type = mapType(gl, attribData.type); + + attributes[attribData.name] = { + type:type, + size:mapSize(type), + location:gl.getAttribLocation(program, attribData.name), + //TODO - make an attribute object + pointer: pointer + }; + } + + return attributes; +}; + +var pointer = function(type, normalized, stride, start){ + // console.log(this.location) + gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +}; + +module.exports = extractAttributes; + +},{"./mapSize":23,"./mapType":24}],20:[function(require,module,exports){ +var mapType = require('./mapType'); +var defaultValue = require('./defaultValue'); + +/** + * Extracts the uniforms + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the uniforms from + * @return uniforms {Object} + */ +var extractUniforms = function(gl, program) +{ + var uniforms = {}; + + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + + for (var i = 0; i < totalUniforms; i++) + { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]/, ""); + var type = mapType(gl, uniformData.type ); + + uniforms[name] = { + type:type, + size:uniformData.size, + location:gl.getUniformLocation(program, name), + value:defaultValue(type, uniformData.size) + }; + } + + return uniforms; +}; + +module.exports = extractUniforms; + +},{"./defaultValue":18,"./mapType":24}],21:[function(require,module,exports){ +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param uniforms {Array} @mat ? + * @return attributes {Object} + */ +var generateUniformAccessObject = function(gl, uniformData) +{ + // this is the object we will be sending back. + // an object hierachy will be created for structs + var uniforms = {data:{}}; + + uniforms.gl = gl; + + var uniformKeys= Object.keys(uniformData); + + for (var i = 0; i < uniformKeys.length; i++) + { + var fullName = uniformKeys[i]; + + var nameTokens = fullName.split('.'); + var name = nameTokens[nameTokens.length - 1]; + + + var uniformGroup = getUniformGroup(nameTokens, uniforms); + + var uniform = uniformData[fullName]; + uniformGroup.data[name] = uniform; + + uniformGroup.gl = gl; + + Object.defineProperty(uniformGroup, name, { + get: generateGetter(name), + set: generateSetter(name, uniform) + }); + } + + return uniforms; +}; + +var generateGetter = function(name) +{ + return function() { + return this.data[name].value; + }; +}; + +var GLSL_SINGLE_SETTERS = { + float: function setSingleFloat(gl, location, value) { gl.uniform1f(location, value); }, + vec2: function setSingleVec2(gl, location, value) { gl.uniform2f(location, value[0], value[1]); }, + vec3: function setSingleVec3(gl, location, value) { gl.uniform3f(location, value[0], value[1], value[2]); }, + vec4: function setSingleVec4(gl, location, value) { gl.uniform4f(location, value[0], value[1], value[2], value[3]); }, + + int: function setSingleInt(gl, location, value) { gl.uniform1i(location, value); }, + ivec2: function setSingleIvec2(gl, location, value) { gl.uniform2i(location, value[0], value[1]); }, + ivec3: function setSingleIvec3(gl, location, value) { gl.uniform3i(location, value[0], value[1], value[2]); }, + ivec4: function setSingleIvec4(gl, location, value) { gl.uniform4i(location, value[0], value[1], value[2], value[3]); }, + + bool: function setSingleBool(gl, location, value) { gl.uniform1i(location, value); }, + bvec2: function setSingleBvec2(gl, location, value) { gl.uniform2i(location, value[0], value[1]); }, + bvec3: function setSingleBvec3(gl, location, value) { gl.uniform3i(location, value[0], value[1], value[2]); }, + bvec4: function setSingleBvec4(gl, location, value) { gl.uniform4i(location, value[0], value[1], value[2], value[3]); }, + + mat2: function setSingleMat2(gl, location, value) { gl.uniformMatrix2fv(location, false, value); }, + mat3: function setSingleMat3(gl, location, value) { gl.uniformMatrix3fv(location, false, value); }, + mat4: function setSingleMat4(gl, location, value) { gl.uniformMatrix4fv(location, false, value); }, + + sampler2D: function setSingleSampler2D(gl, location, value) { gl.uniform1i(location, value); }, +}; + +var GLSL_ARRAY_SETTERS = { + float: function setFloatArray(gl, location, value) { gl.uniform1fv(location, value); }, + vec2: function setVec2Array(gl, location, value) { gl.uniform2fv(location, value); }, + vec3: function setVec3Array(gl, location, value) { gl.uniform3fv(location, value); }, + vec4: function setVec4Array(gl, location, value) { gl.uniform4fv(location, value); }, + int: function setIntArray(gl, location, value) { gl.uniform1iv(location, value); }, + ivec2: function setIvec2Array(gl, location, value) { gl.uniform2iv(location, value); }, + ivec3: function setIvec3Array(gl, location, value) { gl.uniform3iv(location, value); }, + ivec4: function setIvec4Array(gl, location, value) { gl.uniform4iv(location, value); }, + bool: function setBoolArray(gl, location, value) { gl.uniform1iv(location, value); }, + bvec2: function setBvec2Array(gl, location, value) { gl.uniform2iv(location, value); }, + bvec3: function setBvec3Array(gl, location, value) { gl.uniform3iv(location, value); }, + bvec4: function setBvec4Array(gl, location, value) { gl.uniform4iv(location, value); }, + sampler2D: function setSampler2DArray(gl, location, value) { gl.uniform1iv(location, value); }, +}; + +function generateSetter(name, uniform) +{ + return function(value) { + this.data[name].value = value; + var location = this.data[name].location; + if (uniform.size === 1) + { + GLSL_SINGLE_SETTERS[uniform.type](this.gl, location, value); + } + else + { + // glslSetArray(gl, location, type, value) { + GLSL_ARRAY_SETTERS[uniform.type](this.gl, location, value); + } + }; +} + +function getUniformGroup(nameTokens, uniform) +{ + var cur = uniform; + + for (var i = 0; i < nameTokens.length - 1; i++) + { + var o = cur[nameTokens[i]] || {data:{}}; + cur[nameTokens[i]] = o; + cur = o; + } + + return cur; +} + + +module.exports = generateUniformAccessObject; + +},{}],22:[function(require,module,exports){ +module.exports = { + compileProgram: require('./compileProgram'), + defaultValue: require('./defaultValue'), + extractAttributes: require('./extractAttributes'), + extractUniforms: require('./extractUniforms'), + generateUniformAccessObject: require('./generateUniformAccessObject'), + setPrecision: require('./setPrecision'), + mapSize: require('./mapSize'), + mapType: require('./mapType') +}; +},{"./compileProgram":17,"./defaultValue":18,"./extractAttributes":19,"./extractUniforms":20,"./generateUniformAccessObject":21,"./mapSize":23,"./mapType":24,"./setPrecision":25}],23:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} + * @return {Number} + */ +var mapSize = function(type) +{ + return GLSL_TO_SIZE[type]; +}; + + +var GLSL_TO_SIZE = { + 'float': 1, + 'vec2': 2, + 'vec3': 3, + 'vec4': 4, + + 'int': 1, + 'ivec2': 2, + 'ivec3': 3, + 'ivec4': 4, + + 'bool': 1, + 'bvec2': 2, + 'bvec3': 3, + 'bvec4': 4, + + 'mat2': 4, + 'mat3': 9, + 'mat4': 16, + + 'sampler2D': 1 +}; + +module.exports = mapSize; + +},{}],24:[function(require,module,exports){ + + +var mapType = function(gl, type) +{ + if(!GL_TABLE) + { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + + GL_TABLE = {}; + + for(var i = 0; i < typeNames.length; ++i) + { + var tn = typeNames[i]; + GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + } + } + + return GL_TABLE[type]; +}; + +var GL_TABLE = null; + +var GL_TO_GLSL_TYPES = { + 'FLOAT': 'float', + 'FLOAT_VEC2': 'vec2', + 'FLOAT_VEC3': 'vec3', + 'FLOAT_VEC4': 'vec4', + + 'INT': 'int', + 'INT_VEC2': 'ivec2', + 'INT_VEC3': 'ivec3', + 'INT_VEC4': 'ivec4', + + 'BOOL': 'bool', + 'BOOL_VEC2': 'bvec2', + 'BOOL_VEC3': 'bvec3', + 'BOOL_VEC4': 'bvec4', + + 'FLOAT_MAT2': 'mat2', + 'FLOAT_MAT3': 'mat3', + 'FLOAT_MAT4': 'mat4', + + 'SAMPLER_2D': 'sampler2D' +}; + +module.exports = mapType; + +},{}],25:[function(require,module,exports){ +/** + * Sets the float precision on the shader. If the precision is already present this function will do nothing + * @param {string} src the shader source + * @param {string} precision The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + * + * @return {string} modified shader source + */ +var setPrecision = function(src, precision) +{ + if(src.substring(0, 9) !== 'precision') + { + return 'precision ' + precision + ' float;\n' + src; + } + + return src; +}; + +module.exports = setPrecision; + +},{}],26:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],27:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],28:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],29:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],30:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":28,"./encode":29}],31:[function(require,module,exports){ +'use strict' + +/** + * Remove a range of items from an array + * + * @function removeItems + * @param {Array<*>} arr The target array + * @param {number} startIdx The index to begin removing from (inclusive) + * @param {number} removeCount How many items to remove + */ +module.exports = function removeItems(arr, startIdx, removeCount) +{ + var i, length = arr.length + + if (startIdx >= length || removeCount === 0) { + return + } + + removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount) + + var len = length - removeCount + + for (i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount] + } + + arr.length = len +} + +},{}],32:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _async = require('./async'); + +var async = _interopRequireWildcard(_async); + +var _Resource = require('./Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// some constants +var MAX_PROGRESS = 100; +var rgxExtractUrlHash = /(#[\w-]+)?$/; + +/** + * Manages the state and loading of multiple resources to load. + * + * @class + */ + +var Loader = function () { + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader() { + var _this = this; + + var baseUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var concurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; + + _classCallCheck(this, Loader); + + /** + * The base url for all resources loaded by this loader. + * + * @member {string} + */ + this.baseUrl = baseUrl; + + /** + * The progress percent of the loader going through the queue. + * + * @member {number} + */ + this.progress = 0; + + /** + * Loading state of the loader, true if it is currently loading resources. + * + * @member {boolean} + */ + this.loading = false; + + /** + * A querystring to append to every URL added to the loader. + * + * This should be a valid query string *without* the question-mark (`?`). The loader will + * also *not* escape values for you. Make sure to escape your parameters with + * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. + * + * @example + * const loader = new Loader(); + * + * loader.defaultQueryString = 'user=me&password=secret'; + * + * // This will request 'image.png?user=me&password=secret' + * loader.add('image.png').load(); + * + * loader.reset(); + * + * // This will request 'image.png?v=1&user=me&password=secret' + * loader.add('iamge.png?v=1').load(); + */ + this.defaultQueryString = ''; + + /** + * The middleware to run before loading each resource. + * + * @member {function[]} + */ + this._beforeMiddleware = []; + + /** + * The middleware to run after loading each resource. + * + * @member {function[]} + */ + this._afterMiddleware = []; + + /** + * The tracks the resources we are currently completing parsing for. + * + * @member {Resource[]} + */ + this._resourcesParsing = []; + + /** + * The `_loadResource` function bound with this object context. + * + * @private + * @member {function} + * @param {Resource} r - The resource to load + * @param {Function} d - The dequeue function + * @return {undefined} + */ + this._boundLoadResource = function (r, d) { + return _this._loadResource(r, d); + }; + + /** + * The resources waiting to be loaded. + * + * @private + * @member {Resource[]} + */ + this._queue = async.queue(this._boundLoadResource, concurrency); + + this._queue.pause(); + + /** + * All the resources for this loader keyed by name. + * + * @member {object} + */ + this.resources = {}; + + /** + * Dispatched once per loaded or errored resource. + * + * The callback looks like {@link Loader.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once per errored resource. + * + * The callback looks like {@link Loader.OnErrorSignal}. + * + * @member {Signal} + */ + this.onError = new _miniSignals2.default(); + + /** + * Dispatched once per loaded resource. + * + * The callback looks like {@link Loader.OnLoadSignal}. + * + * @member {Signal} + */ + this.onLoad = new _miniSignals2.default(); + + /** + * Dispatched when the loader begins to process the queue. + * + * The callback looks like {@link Loader.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched when the queued resources all load. + * + * The callback looks like {@link Loader.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * When the progress changes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnProgressSignal + * @param {Loader} loader - The loader the progress is advancing on. + * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance. + */ + + /** + * When an error occurrs the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnErrorSignal + * @param {Loader} loader - The loader the error happened in. + * @param {Resource} resource - The resource that caused the error. + */ + + /** + * When a load completes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnLoadSignal + * @param {Loader} loader - The loader that laoded the resource. + * @param {Resource} resource - The resource that has completed loading. + */ + + /** + * When the loader starts loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnStartSignal + * @param {Loader} loader - The loader that has started loading resources. + */ + + /** + * When the loader completes loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnCompleteSignal + * @param {Loader} loader - The loader that has finished loading resources. + */ + } + + /** + * Adds a resource (or multiple resources) to the loader queue. + * + * This function can take a wide variety of different parameters. The only thing that is always + * required the url to load. All the following will work: + * + * ```js + * loader + * // normal param syntax + * .add('key', 'http://...', function () {}) + * .add('http://...', function () {}) + * .add('http://...') + * + * // object syntax + * .add({ + * name: 'key2', + * url: 'http://...' + * }, function () {}) + * .add({ + * url: 'http://...' + * }, function () {}) + * .add({ + * name: 'key3', + * url: 'http://...' + * onComplete: function () {} + * }) + * .add({ + * url: 'https://...', + * onComplete: function () {}, + * crossOrigin: true + * }) + * + * // you can also pass an array of objects or urls or both + * .add([ + * { name: 'key4', url: 'http://...', onComplete: function () {} }, + * { url: 'http://...', onComplete: function () {} }, + * 'http://...' + * ]) + * + * // and you can use both params and options + * .add('key', 'http://...', { crossOrigin: true }, function () {}) + * .add('http://...', { crossOrigin: true }, function () {}); + * ``` + * + * @param {string} [name] - The name of the resource to load, if not passed the url is used. + * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @param {object} [options] - The options for the load. + * @param {boolean} [options.crossOrigin] - Is this request cross-origin? Default is to determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How should + * the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @param {function} [cb] - Function to call when this specific resource completes loading. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.add = function add(name, url, options, cb) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + + return this; + } + + // if an object is passed instead of params + if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') { + cb = url || name.callback || name.onComplete; + options = name; + url = name.url; + name = name.name || name.key || name.url; + } + + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + cb = options; + options = url; + url = name; + } + + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + cb = options; + options = null; + } + + // if loading already you can only add resources that have a parent. + if (this.loading && (!options || !options.parentResource)) { + throw new Error('Cannot add resources while the loader is running.'); + } + + // check if resource already exists. + if (this.resources[name]) { + throw new Error('Resource named "' + name + '" already exists.'); + } + + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + + // create the store the resource + this.resources[name] = new _Resource2.default(name, url, options); + + if (typeof cb === 'function') { + this.resources[name].onAfterMiddleware.once(cb); + } + + // if actively loading, make sure to adjust progress chunks for that parent and its children + if (this.loading) { + var parent = options.parentResource; + var incompleteChildren = []; + + for (var _i = 0; _i < parent.children.length; ++_i) { + if (!parent.children[_i].isComplete) { + incompleteChildren.push(parent.children[_i]); + } + } + + var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent + var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child + + parent.children.push(this.resources[name]); + parent.progressChunk = eachChunk; + + for (var _i2 = 0; _i2 < incompleteChildren.length; ++_i2) { + incompleteChildren[_i2].progressChunk = eachChunk; + } + + this.resources[name].progressChunk = eachChunk; + } + + // add the resource to the queue + this._queue.push(this.resources[name]); + + return this; + }; + + /** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * + * @method before + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.pre = function pre(fn) { + this._beforeMiddleware.push(fn); + + return this; + }; + + /** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * + * @alias use + * @method after + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.use = function use(fn) { + this._afterMiddleware.push(fn); + + return this; + }; + + /** + * Resets the queue of the loader to prepare for a new load. + * + * @return {Loader} Returns itself. + */ + + + Loader.prototype.reset = function reset() { + this.progress = 0; + this.loading = false; + + this._queue.kill(); + this._queue.pause(); + + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + + if (res._onLoadBinding) { + res._onLoadBinding.detach(); + } + + if (res.isLoading) { + res.abort(); + } + } + + this.resources = {}; + + return this; + }; + + /** + * Starts loading the queued resources. + * + * @param {function} [cb] - Optional callback that will be bound to the `complete` event. + * @return {Loader} Returns itself. + */ + + + Loader.prototype.load = function load(cb) { + // register complete callback if they pass one + if (typeof cb === 'function') { + this.onComplete.once(cb); + } + + // if the queue has already started we are done here + if (this.loading) { + return this; + } + + if (this._queue.idle()) { + this._onStart(); + this._onComplete(); + } else { + // distribute progress chunks + var numTasks = this._queue._tasks.length; + var chunk = 100 / numTasks; + + for (var i = 0; i < this._queue._tasks.length; ++i) { + this._queue._tasks[i].data.progressChunk = chunk; + } + + // notify we are starting + this._onStart(); + + // start loading + this._queue.resume(); + } + + return this; + }; + + /** + * The number of resources to load concurrently. + * + * @member {number} + * @default 10 + */ + + + /** + * Prepares a url for usage based on the configuration of this object + * + * @private + * @param {string} url - The url to prepare. + * @return {string} The prepared url. + */ + Loader.prototype._prepareUrl = function _prepareUrl(url) { + var parsedUrl = (0, _parseUri2.default)(url, { strictMode: true }); + var result = void 0; + + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { + result = url; + } + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + else if (this.baseUrl.length && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 && url.charAt(0) !== '/') { + result = this.baseUrl + '/' + url; + } else { + result = this.baseUrl + url; + } + + // if we need to add a default querystring, there is a bit more work + if (this.defaultQueryString) { + var hash = rgxExtractUrlHash.exec(result)[0]; + + result = result.substr(0, result.length - hash.length); + + if (result.indexOf('?') !== -1) { + result += '&' + this.defaultQueryString; + } else { + result += '?' + this.defaultQueryString; + } + + result += hash; + } + + return result; + }; + + /** + * Loads a single resource. + * + * @private + * @param {Resource} resource - The resource to load. + * @param {function} dequeue - The function to call when we need to dequeue this item. + */ + + + Loader.prototype._loadResource = function _loadResource(resource, dequeue) { + var _this2 = this; + + resource._dequeue = dequeue; + + // run before middleware + async.eachSeries(this._beforeMiddleware, function (fn, next) { + fn.call(_this2, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, function () { + if (resource.isComplete) { + _this2._onLoad(resource); + } else { + resource._onLoadBinding = resource.onComplete.once(_this2._onLoad, _this2); + resource.load(); + } + }, true); + }; + + /** + * Called once loading has started. + * + * @private + */ + + + Loader.prototype._onStart = function _onStart() { + this.progress = 0; + this.loading = true; + this.onStart.dispatch(this); + }; + + /** + * Called once each resource has loaded. + * + * @private + */ + + + Loader.prototype._onComplete = function _onComplete() { + this.progress = MAX_PROGRESS; + this.loading = false; + this.onComplete.dispatch(this, this.resources); + }; + + /** + * Called each time a resources is loaded. + * + * @private + * @param {Resource} resource - The resource that was loaded + */ + + + Loader.prototype._onLoad = function _onLoad(resource) { + var _this3 = this; + + resource._onLoadBinding = null; + + // remove this resource from the async queue, and add it to our list of resources that are being parsed + this._resourcesParsing.push(resource); + resource._dequeue(); + + // run all the after middleware for this resource + async.eachSeries(this._afterMiddleware, function (fn, next) { + fn.call(_this3, resource, next); + }, function () { + resource.onAfterMiddleware.dispatch(resource); + + _this3.progress += resource.progressChunk; + _this3.onProgress.dispatch(_this3, resource); + + if (resource.error) { + _this3.onError.dispatch(resource.error, _this3, resource); + } else { + _this3.onLoad.dispatch(_this3, resource); + } + + _this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1); + + // do completion check + if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) { + _this3._onComplete(); + } + }, true); + }; + + _createClass(Loader, [{ + key: 'concurrency', + get: function get() { + return this._queue.concurrency; + } + // eslint-disable-next-line require-jsdoc + , + set: function set(concurrency) { + this._queue.concurrency = concurrency; + } + }]); + + return Loader; +}(); + +exports.default = Loader; + +},{"./Resource":33,"./async":34,"mini-signals":5,"parse-uri":7}],33:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// tests is CORS is supported in XHR, if not we need to use XDR +var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest())); +var tempAnchor = null; + +// some status constants +var STATUS_NONE = 0; +var STATUS_OK = 200; +var STATUS_EMPTY = 204; +var STATUS_IE_BUG_EMPTY = 1223; +var STATUS_TYPE_OK = 2; + +// noop +function _noop() {} /* empty */ + +/** + * Manages the state and loading of a resource and all child resources. + * + * @class + */ + +var Resource = function () { + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. + */ + Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) { + setExtMap(Resource._loadTypeMap, extname, loadType); + }; + + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ + + + Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); + }; + + /** + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass + * an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @param {object} [options.metadata] - Extra configuration for middleware and the Resource object. + * @param {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [options.metadata.loadElement=null] - The + * element to use for loading, instead of creating one. + * @param {boolean} [options.metadata.skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @param {string|string[]} [options.metadata.mimeType] - The mime type to use for the source element of a video/audio + * elment. If the urls are an array, you can pass this as an array as well where each index is the mime type to + * use for the corresponding url index. + */ + + + function Resource(name, url, options) { + _classCallCheck(this, Resource); + + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + + options = options || {}; + + /** + * The state flags of this resource. + * + * @member {number} + */ + this._flags = 0; + + // set data url flag, needs to be set early for some _determineX checks to work. + this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); + + /** + * The name of this resource. + * + * @member {string} + * @readonly + */ + this.name = name; + + /** + * The url used to load this resource. + * + * @member {string} + * @readonly + */ + this.url = url; + + /** + * The extension used to load this resource. + * + * @member {string} + * @readonly + */ + this.extension = this._getExtension(); + + /** + * The data that was loaded by the resource. + * + * @member {any} + */ + this.data = null; + + /** + * Is this request cross-origin? If unset, determined automatically. + * + * @member {string} + */ + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + + /** + * The method of loading to use for this resource. + * + * @member {Resource.LOAD_TYPE} + */ + this.loadType = options.loadType || this._determineLoadType(); + + /** + * The type used to load the resource via XHR. If unset, determined automatically. + * + * @member {string} + */ + this.xhrType = options.xhrType; + + /** + * Extra info for middleware, and controlling specifics about how the resource loads. + * + * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + * Meaning it will modify it as it sees fit. + * + * @member {object} + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources + * to. + */ + this.metadata = options.metadata || {}; + + /** + * The error that occurred while loading (if any). + * + * @member {Error} + * @readonly + */ + this.error = null; + + /** + * The XHR object that was used to load this resource. This is only set + * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * + * @member {XMLHttpRequest} + * @readonly + */ + this.xhr = null; + + /** + * The child resources this resource owns. + * + * @member {Resource[]} + * @readonly + */ + this.children = []; + + /** + * The resource type. + * + * @member {Resource.TYPE} + * @readonly + */ + this.type = Resource.TYPE.UNKNOWN; + + /** + * The progress chunk owned by this resource. + * + * @member {number} + * @readonly + */ + this.progressChunk = 0; + + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * + * @private + * @member {function} + */ + this._dequeue = _noop; + + /** + * Used a storage place for the on load binding used privately by the loader. + * + * @private + * @member {function} + */ + this._onLoadBinding = null; + + /** + * The `complete` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundComplete = this.complete.bind(this); + + /** + * The `_onError` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnError = this._onError.bind(this); + + /** + * The `_onProgress` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnProgress = this._onProgress.bind(this); + + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + this._boundXdrOnTimeout = this._xdrOnTimeout.bind(this); + + /** + * Dispatched when the resource beings to load. + * + * The callback looks like {@link Resource.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched each time progress of this resource load updates. + * Not all resources types and loader systems can support this event + * so sometimes it may not be available. If the resource + * is being loaded on a modern browser, using XHR, and the remote server + * properly sets Content-Length headers, then this will be available. + * + * The callback looks like {@link Resource.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once this resource has loaded, if there was an error it will + * be in the `error` property. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * Dispatched after this resource has had all the *after* middleware run on it. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onAfterMiddleware = new _miniSignals2.default(); + + /** + * When the resource starts to load. + * + * @memberof Resource + * @callback OnStartSignal + * @param {Resource} resource - The resource that the event happened on. + */ + + /** + * When the resource reports loading progress. + * + * @memberof Resource + * @callback OnProgressSignal + * @param {Resource} resource - The resource that the event happened on. + * @param {number} percentage - The progress of the load in the range [0, 1]. + */ + + /** + * When the resource finishes loading. + * + * @memberof Resource + * @callback OnCompleteSignal + * @param {Resource} resource - The resource that the event happened on. + */ + } + + /** + * Stores whether or not this url is a data url. + * + * @member {boolean} + * @readonly + */ + + + /** + * Marks the resource as complete. + * + */ + Resource.prototype.complete = function complete() { + // TODO: Clean this up in a wrapper or something...gross.... + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + + this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true); + this._setFlag(Resource.STATUS_FLAGS.LOADING, false); + + this.onComplete.dispatch(this); + }; + + /** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ + + + Resource.prototype.abort = function abort(message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + + // store error + this.error = new Error(message); + + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } else if (this.xdr) { + this.xdr.abort(); + } else if (this.data) { + // single source + if (this.data.src) { + this.data.src = Resource.EMPTY_GIF; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + + // done now. + this.complete(); + }; + + /** + * Kicks off loading of this resource. This method is asynchronous. + * + * @param {function} [cb] - Optional callback to call once the resource is loaded. + */ + + + Resource.prototype.load = function load(cb) { + var _this = this; + + if (this.isLoading) { + return; + } + + if (this.isComplete) { + if (cb) { + setTimeout(function () { + return cb(_this); + }, 1); + } + + return; + } else if (cb) { + this.onComplete.once(cb); + } + + this._setFlag(Resource.STATUS_FLAGS.LOADING, true); + + this.onStart.dispatch(this); + + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + + switch (this.loadType) { + case Resource.LOAD_TYPE.IMAGE: + this.type = Resource.TYPE.IMAGE; + this._loadElement('image'); + break; + + case Resource.LOAD_TYPE.AUDIO: + this.type = Resource.TYPE.AUDIO; + this._loadSourceElement('audio'); + break; + + case Resource.LOAD_TYPE.VIDEO: + this.type = Resource.TYPE.VIDEO; + this._loadSourceElement('video'); + break; + + case Resource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } else { + this._loadXhr(); + } + break; + } + }; + + /** + * Checks if the flag is set. + * + * @private + * @param {number} flag - The flag to check. + * @return {boolean} True if the flag is set. + */ + + + Resource.prototype._hasFlag = function _hasFlag(flag) { + return !!(this._flags & flag); + }; + + /** + * (Un)Sets the flag. + * + * @private + * @param {number} flag - The flag to (un)set. + * @param {boolean} value - Whether to set or (un)set the flag. + */ + + + Resource.prototype._setFlag = function _setFlag(flag, value) { + this._flags = value ? this._flags | flag : this._flags & ~flag; + }; + + /** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadElement = function _loadElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'image' && typeof window.Image !== 'undefined') { + this.data = new Image(); + } else { + this.data = document.createElement(type); + } + + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + }; + + /** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadSourceElement = function _loadSourceElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'audio' && typeof window.Audio !== 'undefined') { + this.data = new Audio(); + } else { + this.data = document.createElement(type); + } + + if (this.data === null) { + this.abort('Unsupported element: ' + type); + + return; + } + + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } else if (Array.isArray(this.url)) { + var mimeTypes = this.metadata.mimeType; + + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes)); + } + } else { + var _mimeTypes = this.metadata.mimeType; + + this.data.appendChild(this._createSource(type, this.url, Array.isArray(_mimeTypes) ? _mimeTypes[0] : _mimeTypes)); + } + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + + this.data.load(); + }; + + /** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ + + + Resource.prototype._loadXhr = function _loadXhr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xhr = this.xhr = new XMLHttpRequest(); + + // set the request type and url + xhr.open('GET', this.url, true); + + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; + } else { + xhr.responseType = this.xhrType; + } + + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + + xhr.send(); + }; + + /** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ + + + Resource.prototype._loadXdr = function _loadXdr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xdr = this.xhr = new XDomainRequest(); + + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = 5000; + + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXdrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + + xdr.open('GET', this.url, true); + + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { + return xdr.send(); + }, 1); + }; + + /** + * Creates a source used in loading via an element. + * + * @private + * @param {string} type - The element type (video or audio). + * @param {string} url - The source URL to load from. + * @param {string} [mime] - The mime type of the video + * @return {HTMLSourceElement} The source element. + */ + + + Resource.prototype._createSource = function _createSource(type, url, mime) { + if (!mime) { + mime = type + '/' + this._getExtension(url); + } + + var source = document.createElement('source'); + + source.src = url; + source.type = mime; + + return source; + }; + + /** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ + + + Resource.prototype._onError = function _onError(event) { + this.abort('Failed to load element using: ' + event.target.nodeName); + }; + + /** + * Called if a load progress event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ + + + Resource.prototype._onProgress = function _onProgress(event) { + if (event && event.lengthComputable) { + this.onProgress.dispatch(this, event.loaded / event.total); + } + }; + + /** + * Called if an error event fires for xhr/xdr. + * + * @private + * @param {XMLHttpRequestErrorEvent|Event} event - Error event. + */ + + + Resource.prototype._xhrOnError = function _xhrOnError() { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"'); + }; + + /** + * Called if an abort event fires for xhr. + * + * @private + * @param {XMLHttpRequestAbortEvent} event - Abort Event + */ + + + Resource.prototype._xhrOnAbort = function _xhrOnAbort() { + this.abort(reqType(this.xhr) + ' Request was aborted by the user.'); + }; + + /** + * Called if a timeout event fires for xdr. + * + * @private + * @param {Event} event - Timeout event. + */ + + + Resource.prototype._xdrOnTimeout = function _xdrOnTimeout() { + this.abort(reqType(this.xhr) + ' Request timed out.'); + }; + + /** + * Called when data successfully loads from an xhr/xdr request. + * + * @private + * @param {XMLHttpRequestLoadEvent|Event} event - Load event + */ + + + Resource.prototype._xhrOnLoad = function _xhrOnLoad() { + var xhr = this.xhr; + var text = ''; + var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200. + + // responseText is accessible only if responseType is '' or 'text' and on older browsers + if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') { + text = xhr.responseText; + } + + // status can be 0 when using the `file://` protocol so we also check if a response is set. + // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request. + if (status === STATUS_NONE && (text.length > 0 || xhr.responseType === Resource.XHR_RESPONSE_TYPE.BUFFER)) { + status = STATUS_OK; + } + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + else if (status === STATUS_IE_BUG_EMPTY) { + status = STATUS_EMPTY; + } + + var statusType = status / 100 | 0; + + if (statusType === STATUS_TYPE_OK) { + // if text, just return it + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { + this.data = text; + this.type = Resource.TYPE.TEXT; + } + // if json, parse into json object + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(text); + this.type = Resource.TYPE.JSON; + } catch (e) { + this.abort('Error trying to parse loaded json: ' + e); + + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (window.DOMParser) { + var domparser = new DOMParser(); + + this.data = domparser.parseFromString(text, 'text/xml'); + } else { + var div = document.createElement('div'); + + div.innerHTML = text; + + this.data = div; + } + + this.type = Resource.TYPE.XML; + } catch (e) { + this.abort('Error trying to parse loaded xml: ' + e); + + return; + } + } + // other types just return the response + else { + this.data = xhr.response || text; + } + } else { + this.abort('[' + xhr.status + '] ' + xhr.statusText + ': ' + xhr.responseURL); + + return; + } + + this.complete(); + }; + + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * + * @private + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ + + + Resource.prototype._determineCrossOrigin = function _determineCrossOrigin(url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = (0, _parseUri2.default)(tempAnchor.href, { strictMode: true }); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + var protocol = url.protocol ? url.protocol + ':' : ''; + + // if cross origin + if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; + }; + + /** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. + */ + + + Resource.prototype._determineXhrType = function _determineXhrType() { + return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT; + }; + + /** + * Determines the loadType of a resource based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.LOAD_TYPE} The loadType to use. + */ + + + Resource.prototype._determineLoadType = function _determineLoadType() { + return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR; + }; + + /** + * Extracts the extension (sans '.') of the file being loaded by the resource. + * + * @private + * @return {string} The extension. + */ + + + Resource.prototype._getExtension = function _getExtension() { + var url = this.url; + var ext = ''; + + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } else { + var queryStart = url.indexOf('?'); + var hashStart = url.indexOf('#'); + var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length); + + url = url.substring(0, index); + ext = url.substring(url.lastIndexOf('.') + 1); + } + + return ext.toLowerCase(); + }; + + /** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * + * @private + * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. + * @return {string} The mime type to use. + */ + + + Resource.prototype._getMimeFromXhrType = function _getMimeFromXhrType(type) { + switch (type) { + case Resource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + + case Resource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + + case Resource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + + case Resource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + + case Resource.XHR_RESPONSE_TYPE.DEFAULT: + case Resource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + + } + }; + + _createClass(Resource, [{ + key: 'isDataUrl', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL); + } + + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isComplete', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE); + } + + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'isLoading', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.LOADING); + } + }]); + + return Resource; +}(); + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ + + +exports.default = Resource; +Resource.STATUS_FLAGS = { + NONE: 0, + DATA_URL: 1 << 0, + COMPLETE: 1 << 1, + LOADING: 1 << 2 +}; + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ +Resource.TYPE = { + UNKNOWN: 0, + JSON: 1, + XML: 2, + IMAGE: 3, + AUDIO: 4, + VIDEO: 5, + TEXT: 6 +}; + +/** + * The types of loading a resource can use. + * + * @static + * @readonly + * @enum {number} + */ +Resource.LOAD_TYPE = { + /** Uses XMLHttpRequest to load the resource. */ + XHR: 1, + /** Uses an `Image` object to load the resource. */ + IMAGE: 2, + /** Uses an `Audio` object to load the resource. */ + AUDIO: 3, + /** Uses a `Video` object to load the resource. */ + VIDEO: 4 +}; + +/** + * The XHR ready states, used internally. + * + * @static + * @readonly + * @enum {string} + */ +Resource.XHR_RESPONSE_TYPE = { + /** string */ + DEFAULT: 'text', + /** ArrayBuffer */ + BUFFER: 'arraybuffer', + /** Blob */ + BLOB: 'blob', + /** Document */ + DOCUMENT: 'document', + /** Object */ + JSON: 'json', + /** String */ + TEXT: 'text' +}; + +Resource._loadTypeMap = { + // images + gif: Resource.LOAD_TYPE.IMAGE, + png: Resource.LOAD_TYPE.IMAGE, + bmp: Resource.LOAD_TYPE.IMAGE, + jpg: Resource.LOAD_TYPE.IMAGE, + jpeg: Resource.LOAD_TYPE.IMAGE, + tif: Resource.LOAD_TYPE.IMAGE, + tiff: Resource.LOAD_TYPE.IMAGE, + webp: Resource.LOAD_TYPE.IMAGE, + tga: Resource.LOAD_TYPE.IMAGE, + svg: Resource.LOAD_TYPE.IMAGE, + 'svg+xml': Resource.LOAD_TYPE.IMAGE, // for SVG data urls + + // audio + mp3: Resource.LOAD_TYPE.AUDIO, + ogg: Resource.LOAD_TYPE.AUDIO, + wav: Resource.LOAD_TYPE.AUDIO, + + // videos + mp4: Resource.LOAD_TYPE.VIDEO, + webm: Resource.LOAD_TYPE.VIDEO +}; + +Resource._xhrTypeMap = { + // xml + xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. + // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, + // this should probably be fine. + tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // images + gif: Resource.XHR_RESPONSE_TYPE.BLOB, + png: Resource.XHR_RESPONSE_TYPE.BLOB, + bmp: Resource.XHR_RESPONSE_TYPE.BLOB, + jpg: Resource.XHR_RESPONSE_TYPE.BLOB, + jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, + tif: Resource.XHR_RESPONSE_TYPE.BLOB, + tiff: Resource.XHR_RESPONSE_TYPE.BLOB, + webp: Resource.XHR_RESPONSE_TYPE.BLOB, + tga: Resource.XHR_RESPONSE_TYPE.BLOB, + + // json + json: Resource.XHR_RESPONSE_TYPE.JSON, + + // text + text: Resource.XHR_RESPONSE_TYPE.TEXT, + txt: Resource.XHR_RESPONSE_TYPE.TEXT, + + // fonts + ttf: Resource.XHR_RESPONSE_TYPE.BUFFER, + otf: Resource.XHR_RESPONSE_TYPE.BUFFER +}; + +// We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif +Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; + +/** + * Quick helper to set a value on one of the extension maps. Ensures there is no + * dot at the start of the extension. + * + * @ignore + * @param {object} map - The map to set on. + * @param {string} extname - The extension (or key) to set. + * @param {number} val - The value to set. + */ +function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + + if (!extname) { + return; + } + + map[extname] = val; +} + +/** + * Quick helper to get string xhr type. + * + * @ignore + * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. + * @return {string} The type. + */ +function reqType(xhr) { + return xhr.toString().replace('object ', ''); +} + +},{"mini-signals":5,"parse-uri":7}],34:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.eachSeries = eachSeries; +exports.queue = queue; +/** + * Smaller version of the async library constructs. + * + */ +function _noop() {} /* empty */ + +/** + * Iterates an array in series. + * + * @param {Array.<*>} array - Array to iterate. + * @param {function} iterator - Function to call for each element. + * @param {function} callback - Function to call when done, or on error. + * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1. + */ +function eachSeries(array, iterator, callback, deferNext) { + var i = 0; + var len = array.length; + + (function next(err) { + if (err || i === len) { + if (callback) { + callback(err); + } + + return; + } + + if (deferNext) { + setTimeout(function () { + iterator(array[i++], next); + }, 1); + } else { + iterator(array[i++], next); + } + })(); +} + +/** + * Ensures a function is only called once. + * + * @param {function} fn - The function to wrap. + * @return {function} The wrapping function. + */ +function onlyOnce(fn) { + return function onceWrapper() { + if (fn === null) { + throw new Error('Callback was already called.'); + } + + var callFn = fn; + + fn = null; + callFn.apply(this, arguments); + }; +} + +/** + * Async queue implementation, + * + * @param {function} worker - The worker function to call for each task. + * @param {number} concurrency - How many workers to run in parrallel. + * @return {*} The async queue object. + */ +function queue(worker, concurrency) { + if (concurrency == null) { + // eslint-disable-line no-eq-null,eqeqeq + concurrency = 1; + } else if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + + var workers = 0; + var q = { + _tasks: [], + concurrency: concurrency, + saturated: _noop, + unsaturated: _noop, + buffer: concurrency / 4, + empty: _noop, + drain: _noop, + error: _noop, + started: false, + paused: false, + push: function push(data, callback) { + _insert(data, false, callback); + }, + kill: function kill() { + workers = 0; + q.drain = _noop; + q.started = false; + q._tasks = []; + }, + unshift: function unshift(data, callback) { + _insert(data, true, callback); + }, + process: function process() { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var task = q._tasks.shift(); + + if (q._tasks.length === 0) { + q.empty(); + } + + workers += 1; + + if (workers === q.concurrency) { + q.saturated(); + } + + worker(task.data, onlyOnce(_next(task))); + } + }, + length: function length() { + return q._tasks.length; + }, + running: function running() { + return workers; + }, + idle: function idle() { + return q._tasks.length + workers === 0; + }, + pause: function pause() { + if (q.paused === true) { + return; + } + + q.paused = true; + }, + resume: function resume() { + if (q.paused === false) { + return; + } + + q.paused = false; + + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= q.concurrency; w++) { + q.process(); + } + } + }; + + function _insert(data, insertAtFront, callback) { + if (callback != null && typeof callback !== 'function') { + // eslint-disable-line no-eq-null,eqeqeq + throw new Error('task callback must be a function'); + } + + q.started = true; + + if (data == null && q.idle()) { + // eslint-disable-line no-eq-null,eqeqeq + // call drain immediately if there are no tasks + setTimeout(function () { + return q.drain(); + }, 1); + + return; + } + + var item = { + data: data, + callback: typeof callback === 'function' ? callback : _noop + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + setTimeout(function () { + return q.process(); + }, 1); + } + + function _next(task) { + return function next() { + workers -= 1; + + task.callback.apply(task, arguments); + + if (arguments[0] != null) { + // eslint-disable-line no-eq-null,eqeqeq + q.error(arguments[0], task.data); + } + + if (workers <= q.concurrency - q.buffer) { + q.unsaturated(); + } + + if (q.idle()) { + q.drain(); + } + + q.process(); + }; + } + + return q; +} + +},{}],35:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.encodeBinary = encodeBinary; +var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +function encodeBinary(input) { + var output = ''; + var inx = 0; + + while (inx < input.length) { + // Fill byte buffer array + var bytebuffer = [0, 0, 0]; + var encodedCharIndexes = [0, 0, 0, 0]; + + for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } else { + bytebuffer[jnx] = 0; + } + } + + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4; + + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6; + + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + + // Determine whether padding happened, and adjust accordingly + var paddingBytes = inx - (input.length - 1); + + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + + default: + break; // No padding - proceed + } + + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) { + output += _keyStr.charAt(encodedCharIndexes[_jnx]); + } + } + + return output; +} + +},{}],36:[function(require,module,exports){ +'use strict'; + +// import Loader from './Loader'; +// import Resource from './Resource'; +// import * as async from './async'; +// import * as b64 from './b64'; + +/* eslint-disable no-undef */ + +var Loader = require('./Loader').default; +var Resource = require('./Resource').default; +var async = require('./async'); +var b64 = require('./b64'); + +Loader.Resource = Resource; +Loader.async = async; +Loader.base64 = b64; + +// export manually, and also as default +module.exports = Loader; +// export default Loader; +module.exports.default = Loader; + +},{"./Loader":32,"./Resource":33,"./async":34,"./b64":35}],37:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +exports.blobMiddlewareFactory = blobMiddlewareFactory; + +var _Resource = require('../../Resource'); + +var _Resource2 = _interopRequireDefault(_Resource); + +var _b = require('../../b64'); + +var _b2 = _interopRequireDefault(_b); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Url = window.URL || window.webkitURL; + +// a middleware for transforming XHR loaded Blobs into more useful objects +function blobMiddlewareFactory() { + return function blobMiddleware(resource, next) { + if (!resource.data) { + next(); + + return; + } + + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === _Resource2.default.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!window.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = 'data:' + type + ';base64,' + _b2.default.encodeBinary(resource.xhr.responseText); + + resource.type = _Resource2.default.TYPE.IMAGE; + + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + + next(); + }; + + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var _ret = function () { + var src = Url.createObjectURL(resource.data); + + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src; + + resource.type = _Resource2.default.TYPE.IMAGE; + + // cleanup the no longer used blob after the image loads + // TODO: Is this correct? Will the image be invalid after revoking? + resource.data.onload = function () { + Url.revokeObjectURL(src); + resource.data.onload = null; + + next(); + }; + + // next will be called on load. + return { + v: void 0 + }; + }(); + + if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; + } + } + + next(); + }; +} + +},{"../../Resource":33,"../../b64":35}],38:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":39,"punycode":27,"querystring":30}],39:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],40:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +var _accessibleTarget = require('./accessibleTarget'); + +var _accessibleTarget2 = _interopRequireDefault(_accessibleTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// add some extra variables to the container.. +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _accessibleTarget2.default); + +var KEY_CODE_TAB = 9; + +var DIV_TOUCH_SIZE = 100; +var DIV_TOUCH_POS_X = 0; +var DIV_TOUCH_POS_Y = 0; +var DIV_TOUCH_ZINDEX = 2; + +var DIV_HOOK_SIZE = 1; +var DIV_HOOK_POS_X = -1000; +var DIV_HOOK_POS_Y = -1000; +var DIV_HOOK_ZINDEX = 2; + +/** + * The Accessibility manager recreates the ability to tab and have content read by screen + * readers. This is very important as it can possibly help people with disabilities access pixi + * content. + * + * Much like interaction any DisplayObject can be made accessible. This manager will map the + * events as if the mouse was being used, minimizing the effort required to implement. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.accessibility + * + * @class + * @memberof PIXI.accessibility + */ + +var AccessibilityManager = function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + _classCallCheck(this, AccessibilityManager); + + if ((_ismobilejs2.default.tablet || _ismobilejs2.default.phone) && !navigator.isCocoonJS) { + this.createTouchHook(); + } + + // first we create a div that will sit over the PixiJS element. This is where the div overlays will go. + var div = document.createElement('div'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + 'px'; + div.style.left = DIV_TOUCH_POS_Y + 'px'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + + /** + * This is the dom element that will sit over the PixiJS element. This is where the div overlays will go. + * + * @type {HTMLElement} + * @private + */ + this.div = div; + + /** + * A simple pool for storing divs. + * + * @type {*} + * @private + */ + this.pool = []; + + /** + * This is a tick used to check if an object is no longer being rendered. + * + * @type {Number} + * @private + */ + this.renderId = 0; + + /** + * Setting this to true will visually show the divs. + * + * @type {boolean} + */ + this.debug = false; + + /** + * The renderer this accessibility manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * The array of currently active accessible items. + * + * @member {Array<*>} + * @private + */ + this.children = []; + + /** + * pre-bind the functions + * + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + + /** + * stores the state of the manager. If there are no accessible objects or the mouse is moving, this will be false. + * + * @member {Array<*>} + * @private + */ + this.isActive = false; + this.isMobileAccessabillity = false; + + // let listen for tab.. once pressed we can fire up and show the accessibility layer + window.addEventListener('keydown', this._onKeyDown, false); + } + + /** + * Creates the touch hooks. + * + */ + + + AccessibilityManager.prototype.createTouchHook = function createTouchHook() { + var _this = this; + + var hookDiv = document.createElement('button'); + + hookDiv.style.width = DIV_HOOK_SIZE + 'px'; + hookDiv.style.height = DIV_HOOK_SIZE + 'px'; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + 'px'; + hookDiv.style.left = DIV_HOOK_POS_Y + 'px'; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX; + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'HOOK DIV'; + + hookDiv.addEventListener('focus', function () { + _this.isMobileAccessabillity = true; + _this.activate(); + document.body.removeChild(hookDiv); + }); + + document.body.appendChild(hookDiv); + }; + + /** + * Activating will cause the Accessibility layer to be shown. This is called when a user + * preses the tab key. + * + * @private + */ + + + AccessibilityManager.prototype.activate = function activate() { + if (this.isActive) { + return; + } + + this.isActive = true; + + window.document.addEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown, false); + + this.renderer.on('postrender', this.update, this); + + if (this.renderer.view.parentNode) { + this.renderer.view.parentNode.appendChild(this.div); + } + }; + + /** + * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves + * the mouse. + * + * @private + */ + + + AccessibilityManager.prototype.deactivate = function deactivate() { + if (!this.isActive || this.isMobileAccessabillity) { + return; + } + + this.isActive = false; + + window.document.removeEventListener('mousemove', this._onMouseMove, true); + window.addEventListener('keydown', this._onKeyDown, false); + + this.renderer.off('postrender', this.update); + + if (this.div.parentNode) { + this.div.parentNode.removeChild(this.div); + } + }; + + /** + * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. + * + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + + + AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects(displayObject) { + if (!displayObject.visible) { + return; + } + + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + + displayObject.renderId = this.renderId; + } + + var children = displayObject.children; + + for (var i = 0; i < children.length; i++) { + this.updateAccessibleObjects(children[i]); + } + }; + + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * + * @private + */ + + + AccessibilityManager.prototype.update = function update() { + if (!this.renderer.renderingToScreen) { + return; + } + + // update children... + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + + var rect = this.renderer.view.getBoundingClientRect(); + var sx = rect.width / this.renderer.width; + var sy = rect.height / this.renderer.height; + + var div = this.div; + + div.style.left = rect.left + 'px'; + div.style.top = rect.top + 'px'; + div.style.width = this.renderer.width + 'px'; + div.style.height = this.renderer.height + 'px'; + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + + core.utils.removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + + i--; + + if (this.children.length === 0) { + this.deactivate(); + } + } else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + + if (child.hitArea) { + div.style.left = (wt.tx + hitArea.x * wt.a) * sx + 'px'; + div.style.top = (wt.ty + hitArea.y * wt.d) * sy + 'px'; + + div.style.width = hitArea.width * wt.a * sx + 'px'; + div.style.height = hitArea.height * wt.d * sy + 'px'; + } else { + hitArea = child.getBounds(); + + this.capHitArea(hitArea); + + div.style.left = hitArea.x * sx + 'px'; + div.style.top = hitArea.y * sy + 'px'; + + div.style.width = hitArea.width * sx + 'px'; + div.style.height = hitArea.height * sy + 'px'; + + // update button titles and hints if they exist and they've changed + if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) { + div.title = child.accessibleTitle; + } + if (div.getAttribute('aria-label') !== child.accessibleHint && child.accessibleHint !== null) { + div.setAttribute('aria-label', child.accessibleHint); + } + } + } + } + + // increment the render id.. + this.renderId++; + }; + + /** + * TODO: docs. + * + * @param {Rectangle} hitArea - TODO docs + */ + + + AccessibilityManager.prototype.capHitArea = function capHitArea(hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + + if (hitArea.x + hitArea.width > this.renderer.width) { + hitArea.width = this.renderer.width - hitArea.x; + } + + if (hitArea.y + hitArea.height > this.renderer.height) { + hitArea.height = this.renderer.height - hitArea.y; + } + }; + + /** + * Adds a DisplayObject to the accessibility manager + * + * @private + * @param {DisplayObject} displayObject - The child to make accessible. + */ + + + AccessibilityManager.prototype.addChild = function addChild(displayObject) { + // this.activate(); + + var div = this.pool.pop(); + + if (!div) { + div = document.createElement('button'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + div.style.borderStyle = 'none'; + + // ARIA attributes ensure that button title and hint updates are announced properly + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + // Chrome doesn't need aria-live to work as intended; in fact it just gets more confused. + div.setAttribute('aria-live', 'off'); + } else { + div.setAttribute('aria-live', 'polite'); + } + + if (navigator.userAgent.match(/rv:.*Gecko\//)) { + // FireFox needs this to announce only the new button name + div.setAttribute('aria-relevant', 'additions'); + } else { + // required by IE, other browsers don't much care + div.setAttribute('aria-relevant', 'text'); + } + + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + + if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) { + div.title = displayObject.accessibleTitle; + } else if (!displayObject.accessibleHint || displayObject.accessibleHint === null) { + div.title = 'displayObject ' + displayObject.tabIndex; + } + + if (displayObject.accessibleHint && displayObject.accessibleHint !== null) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + + // + + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + + /** + * Maps the div button press to pixi's InteractionManager (click) + * + * @private + * @param {MouseEvent} e - The click event. + */ + + + AccessibilityManager.prototype._onClick = function _onClick(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixi's InteractionManager (mouseover) + * + * @private + * @param {FocusEvent} e - The focus event. + */ + + + AccessibilityManager.prototype._onFocus = function _onFocus(e) { + if (!e.target.getAttribute('aria-live', 'off')) { + e.target.setAttribute('aria-live', 'assertive'); + } + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixi's InteractionManager (mouseout) + * + * @private + * @param {FocusEvent} e - The focusout event. + */ + + + AccessibilityManager.prototype._onFocusOut = function _onFocusOut(e) { + if (!e.target.getAttribute('aria-live', 'off')) { + e.target.setAttribute('aria-live', 'polite'); + } + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); + }; + + /** + * Is called when a key is pressed + * + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + + + AccessibilityManager.prototype._onKeyDown = function _onKeyDown(e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + + this.activate(); + }; + + /** + * Is called when the mouse moves across the renderer element + * + * @private + * @param {MouseEvent} e - The mouse event. + */ + + + AccessibilityManager.prototype._onMouseMove = function _onMouseMove(e) { + if (e.movementX === 0 && e.movementY === 0) { + return; + } + + this.deactivate(); + }; + + /** + * Destroys the accessibility manager + * + */ + + + AccessibilityManager.prototype.destroy = function destroy() { + this.div = null; + + for (var i = 0; i < this.children.length; i++) { + this.children[i].div = null; + } + + window.document.removeEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown); + + this.pool = null; + this.children = null; + this.renderer = null; + }; + + return AccessibilityManager; +}(); + +exports.default = AccessibilityManager; + + +core.WebGLRenderer.registerPlugin('accessibility', AccessibilityManager); +core.CanvasRenderer.registerPlugin('accessibility', AccessibilityManager); + +},{"../core":65,"./accessibleTarget":41,"ismobilejs":4}],41:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Default property values of accessible objects + * used by {@link PIXI.accessibility.AccessibilityManager}. + * + * @function accessibleTarget + * @memberof PIXI.accessibility + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibility.accessibleTarget + * ); + */ +exports.default = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * + * @member {boolean} + */ + accessible: false, + + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * + * @member {string} + */ + accessibleTitle: null, + + /** + * Sets the aria-label attribute of the shadow div + * + * @member {string} + */ + accessibleHint: null, + + /** + * @todo Needs docs. + */ + tabIndex: 0, + + /** + * @todo Needs docs. + */ + _accessibleActive: false, + + /** + * @todo Needs docs. + */ + _accessibleDiv: false +}; + +},{}],42:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _accessibleTarget = require('./accessibleTarget'); + +Object.defineProperty(exports, 'accessibleTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_accessibleTarget).default; + } +}); + +var _AccessibilityManager = require('./AccessibilityManager'); + +Object.defineProperty(exports, 'AccessibilityManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AccessibilityManager).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./AccessibilityManager":40,"./accessibleTarget":41}],43:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +var _Container = require('./display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _ticker = require('./ticker'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _const = require('./const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Convenience class to create a new PIXI application. + * This class automatically creates the renderer, ticker + * and root container. + * + * @example + * // Create the application + * const app = new PIXI.Application(); + * + * // Add the view to the DOM + * document.body.appendChild(app.view); + * + * // ex, add display objects + * app.stage.addChild(PIXI.Sprite.fromImage('something.png')); + * + * @class + * @memberof PIXI + */ +var Application = function () { + // eslint-disable-next-line valid-jsdoc + /** + * @param {object} [options] - The optional renderer parameters + * @param {boolean} [options.autoStart=true] - automatically starts the rendering after the construction. + * Note that setting this parameter to false does NOT stop the shared ticker even if you set + * options.sharedTicker to true in case that it is already started. Stop it by your own. + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great **webgl only** + * @param {boolean} [options.legacy=false] - `true` to ensure compatibility with older / less advanced devices. + * If you experience unexplained flickering try setting this to true. **webgl only** + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card **webgl only** + * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.ticker.shared, `false` to create new ticker. + * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.loaders.shared, `false` to create new Loader. + */ + function Application(options, arg2, arg3, arg4, arg5) { + _classCallCheck(this, Application); + + // Support for constructor(width, height, options, noWebGL, useSharedTicker) + if (typeof options === 'number') { + options = Object.assign({ + width: options, + height: arg2 || _settings2.default.RENDER_OPTIONS.height, + forceCanvas: !!arg4, + sharedTicker: !!arg5 + }, arg3); + } + + /** + * The default options, so we mixin functionality later. + * @member {object} + * @protected + */ + this._options = options = Object.assign({ + autoStart: true, + sharedTicker: false, + forceCanvas: false, + sharedLoader: false + }, options); + + /** + * WebGL renderer if available, otherwise CanvasRenderer + * @member {PIXI.WebGLRenderer|PIXI.CanvasRenderer} + */ + this.renderer = (0, _autoDetectRenderer.autoDetectRenderer)(options); + + /** + * The root display container that's rendered. + * @member {PIXI.Container} + */ + this.stage = new _Container2.default(); + + /** + * Internal reference to the ticker + * @member {PIXI.ticker.Ticker} + * @private + */ + this._ticker = null; + + /** + * Ticker for doing render updates. + * @member {PIXI.ticker.Ticker} + * @default PIXI.ticker.shared + */ + this.ticker = options.sharedTicker ? _ticker.shared : new _ticker.Ticker(); + + // Start the rendering + if (options.autoStart) { + this.start(); + } + } + + /** + * Render the current stage. + */ + Application.prototype.render = function render() { + this.renderer.render(this.stage); + }; + + /** + * Convenience method for stopping the render. + */ + + + Application.prototype.stop = function stop() { + this._ticker.stop(); + }; + + /** + * Convenience method for starting the render. + */ + + + Application.prototype.start = function start() { + this._ticker.start(); + }; + + /** + * Reference to the renderer's canvas element. + * @member {HTMLCanvasElement} + * @readonly + */ + + + /** + * Destroy and don't use after this. + * @param {Boolean} [removeView=false] Automatically remove canvas from DOM. + * @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy + * method called as well. 'stageOptions' will be passed on to those calls. + * @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set + * to true. Should it destroy the texture of the child sprite + * @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set + * to true. Should it destroy the base texture of the child sprite + */ + Application.prototype.destroy = function destroy(removeView, stageOptions) { + if (this._ticker) { + var oldTicker = this._ticker; + + this.ticker = null; + oldTicker.destroy(); + } + + this.stage.destroy(stageOptions); + this.stage = null; + + this.renderer.destroy(removeView); + this.renderer = null; + + this._options = null; + }; + + _createClass(Application, [{ + key: 'ticker', + set: function set(ticker) // eslint-disable-line require-jsdoc + { + if (this._ticker) { + this._ticker.remove(this.render, this); + } + this._ticker = ticker; + if (ticker) { + ticker.add(this.render, this, _const.UPDATE_PRIORITY.LOW); + } + }, + get: function get() // eslint-disable-line require-jsdoc + { + return this._ticker; + } + }, { + key: 'view', + get: function get() { + return this.renderer.view; + } + + /** + * Reference to the renderer's screen rectangle. Its safe to use as filterArea or hitArea for whole screen + * @member {PIXI.Rectangle} + * @readonly + */ + + }, { + key: 'screen', + get: function get() { + return this.renderer.screen; + } + }]); + + return Application; +}(); + +exports.default = Application; + +},{"./autoDetectRenderer":45,"./const":46,"./display/Container":48,"./settings":101,"./ticker":121}],44:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function checkPrecision(src, def) { + if (src instanceof Array) { + if (src[0].substring(0, 9) !== 'precision') { + var copy = src.slice(0); + + copy.unshift('precision ' + def + ' float;'); + + return copy; + } + } else if (src.trim().substring(0, 9) !== 'precision') { + return 'precision ' + def + ' float;\n' + src; + } + + return src; +} + +/** + * Wrapper class, webGL Shader for Pixi. + * Adds precision string if vertexSrc or fragmentSrc have no mention of it. + * + * @class + * @extends GLShader + * @memberof PIXI + */ + +var Shader = function (_GLShader) { + _inherits(Shader, _GLShader); + + /** + * + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + * @param {string|string[]} vertexSrc - The vertex shader source as an array of strings. + * @param {string|string[]} fragmentSrc - The fragment shader source as an array of strings. + * @param {object} [attributeLocations] - A key value pair showing which location eact attribute should sit. + e.g. {position:0, uvs:1}. + * @param {string} [precision] - The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + */ + function Shader(gl, vertexSrc, fragmentSrc, attributeLocations, precision) { + _classCallCheck(this, Shader); + + return _possibleConstructorReturn(this, _GLShader.call(this, gl, checkPrecision(vertexSrc, precision || _settings2.default.PRECISION_VERTEX), checkPrecision(fragmentSrc, precision || _settings2.default.PRECISION_FRAGMENT), undefined, attributeLocations)); + } + + return Shader; +}(_pixiGlCore.GLShader); + +exports.default = Shader; + +},{"./settings":101,"pixi-gl-core":15}],45:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = autoDetectRenderer; + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// eslint-disable-next-line valid-jsdoc +/** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by + * the browser then this function will return a canvas renderer + * + * @memberof PIXI + * @function autoDetectRenderer + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great **webgl only** + * @param {boolean} [options.legacy=false] - `true` to ensure compatibility with older / less advanced devices. + * If you experience unexplained flickering try setting this to true. **webgl only** + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card **webgl only** + * @return {PIXI.WebGLRenderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ +function autoDetectRenderer(options, arg1, arg2, arg3) { + // Backward-compatible support for noWebGL option + var forceCanvas = options && options.forceCanvas; + + if (arg3 !== undefined) { + forceCanvas = arg3; + } + + if (!forceCanvas && utils.isWebGLSupported()) { + return new _WebGLRenderer2.default(options, arg1, arg2); + } + + return new _CanvasRenderer2.default(options, arg1, arg2); +} + +},{"./renderers/canvas/CanvasRenderer":77,"./renderers/webgl/WebGLRenderer":84,"./utils":125}],46:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * String of the current PIXI version. + * + * @static + * @constant + * @memberof PIXI + * @name VERSION + * @type {string} + */ +var VERSION = exports.VERSION = '4.8.2'; + +/** + * Two Pi. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var PI_2 = exports.PI_2 = Math.PI * 2; + +/** + * Conversion factor for converting radians to degrees. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var RAD_TO_DEG = exports.RAD_TO_DEG = 180 / Math.PI; + +/** + * Conversion factor for converting degrees to radians. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var DEG_TO_RAD = exports.DEG_TO_RAD = Math.PI / 180; + +/** + * Constant to identify the Renderer Type. + * + * @static + * @constant + * @memberof PIXI + * @name RENDERER_TYPE + * @type {object} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ +var RENDERER_TYPE = exports.RENDERER_TYPE = { + UNKNOWN: 0, + WEBGL: 1, + CANVAS: 2 +}; + +/** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * + * @static + * @constant + * @memberof PIXI + * @name BLEND_MODES + * @type {object} + * @property {number} NORMAL + * @property {number} ADD + * @property {number} MULTIPLY + * @property {number} SCREEN + * @property {number} OVERLAY + * @property {number} DARKEN + * @property {number} LIGHTEN + * @property {number} COLOR_DODGE + * @property {number} COLOR_BURN + * @property {number} HARD_LIGHT + * @property {number} SOFT_LIGHT + * @property {number} DIFFERENCE + * @property {number} EXCLUSION + * @property {number} HUE + * @property {number} SATURATION + * @property {number} COLOR + * @property {number} LUMINOSITY + */ +var BLEND_MODES = exports.BLEND_MODES = { + NORMAL: 0, + ADD: 1, + MULTIPLY: 2, + SCREEN: 3, + OVERLAY: 4, + DARKEN: 5, + LIGHTEN: 6, + COLOR_DODGE: 7, + COLOR_BURN: 8, + HARD_LIGHT: 9, + SOFT_LIGHT: 10, + DIFFERENCE: 11, + EXCLUSION: 12, + HUE: 13, + SATURATION: 14, + COLOR: 15, + LUMINOSITY: 16, + NORMAL_NPM: 17, + ADD_NPM: 18, + SCREEN_NPM: 19 +}; + +/** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * + * @static + * @constant + * @memberof PIXI + * @name DRAW_MODES + * @type {object} + * @property {number} POINTS + * @property {number} LINES + * @property {number} LINE_LOOP + * @property {number} LINE_STRIP + * @property {number} TRIANGLES + * @property {number} TRIANGLE_STRIP + * @property {number} TRIANGLE_FAN + */ +var DRAW_MODES = exports.DRAW_MODES = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6 +}; + +/** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @static + * @constant + * @memberof PIXI + * @name SCALE_MODES + * @type {object} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ +var SCALE_MODES = exports.SCALE_MODES = { + LINEAR: 0, + NEAREST: 1 +}; + +/** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as webGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * + * @static + * @constant + * @name WRAP_MODES + * @memberof PIXI + * @type {object} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ +var WRAP_MODES = exports.WRAP_MODES = { + CLAMP: 0, + REPEAT: 1, + MIRRORED_REPEAT: 2 +}; + +/** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * + * @static + * @constant + * @name GC_MODES + * @memberof PIXI + * @type {object} + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ +var GC_MODES = exports.GC_MODES = { + AUTO: 0, + MANUAL: 1 +}; + +/** + * Regexp for image type by extension. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `image.png` + */ +var URL_FILE_EXTENSION = exports.URL_FILE_EXTENSION = /\.(\w{3,4})(?:$|\?|#)/i; + +/** + * Regexp for data URI. + * Based on: {@link https://github.com/ragingwind/data-uri-regex} + * + * @static + * @constant + * @name DATA_URI + * @memberof PIXI + * @type {RegExp|string} + * @example data:image/png;base64 + */ +var DATA_URI = exports.DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i; + +/** + * Regexp for SVG size. + * + * @static + * @constant + * @name SVG_SIZE + * @memberof PIXI + * @type {RegExp|string} + * @example <svg width="100" height="100"></svg> + */ +var SVG_SIZE = exports.SVG_SIZE = /]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len + +/** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * + * @static + * @constant + * @name SHAPES + * @memberof PIXI + * @type {object} + * @property {number} POLY Polygon + * @property {number} RECT Rectangle + * @property {number} CIRC Circle + * @property {number} ELIP Ellipse + * @property {number} RREC Rounded Rectangle + */ +var SHAPES = exports.SHAPES = { + POLY: 0, + RECT: 1, + CIRC: 2, + ELIP: 3, + RREC: 4 +}; + +/** + * Constants that specify float precision in shaders. + * + * @static + * @constant + * @name PRECISION + * @memberof PIXI + * @type {object} + * @property {string} LOW='lowp' + * @property {string} MEDIUM='mediump' + * @property {string} HIGH='highp' + */ +var PRECISION = exports.PRECISION = { + LOW: 'lowp', + MEDIUM: 'mediump', + HIGH: 'highp' +}; + +/** + * Constants that specify the transform type. + * + * @static + * @constant + * @name TRANSFORM_MODE + * @memberof PIXI + * @type {object} + * @property {number} STATIC + * @property {number} DYNAMIC + */ +var TRANSFORM_MODE = exports.TRANSFORM_MODE = { + STATIC: 0, + DYNAMIC: 1 +}; + +/** + * Constants that define the type of gradient on text. + * + * @static + * @constant + * @name TEXT_GRADIENT + * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL Vertical gradient + * @property {number} LINEAR_HORIZONTAL Linear gradient + */ +var TEXT_GRADIENT = exports.TEXT_GRADIENT = { + LINEAR_VERTICAL: 0, + LINEAR_HORIZONTAL: 1 +}; + +/** + * Represents the update priorities used by internal PIXI classes when registered with + * the {@link PIXI.ticker.Ticker} object. Higher priority items are updated first and lower + * priority items, such as render, should go later. + * + * @static + * @constant + * @name UPDATE_PRIORITY + * @memberof PIXI + * @type {object} + * @property {number} INTERACTION=50 Highest priority, used for {@link PIXI.interaction.InteractionManager} + * @property {number} HIGH=25 High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.extras.AnimatedSprite} + * @property {number} NORMAL=0 Default priority for ticker events, see {@link PIXI.ticker.Ticker#add}. + * @property {number} LOW=-25 Low priority used for {@link PIXI.Application} rendering. + * @property {number} UTILITY=-50 Lowest priority used for {@link PIXI.prepare.BasePrepare} utility. + */ +var UPDATE_PRIORITY = exports.UPDATE_PRIORITY = { + INTERACTION: 50, + HIGH: 25, + NORMAL: 0, + LOW: -25, + UTILITY: -50 +}; + +},{}],47:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * 'Builder' pattern for bounds rectangles + * Axis-Aligned Bounding Box + * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems + * + * @class + * @memberof PIXI + */ +var Bounds = function () { + /** + * + */ + function Bounds() { + _classCallCheck(this, Bounds); + + /** + * @member {number} + * @default 0 + */ + this.minX = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.minY = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxX = -Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxY = -Infinity; + + this.rect = null; + } + + /** + * Checks if bounds are empty. + * + * @return {boolean} True if empty. + */ + + + Bounds.prototype.isEmpty = function isEmpty() { + return this.minX > this.maxX || this.minY > this.maxY; + }; + + /** + * Clears the bounds and resets. + * + */ + + + Bounds.prototype.clear = function clear() { + this.updateID++; + + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * + * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty + * @returns {PIXI.Rectangle} A rectangle of the bounds + */ + + + Bounds.prototype.getRectangle = function getRectangle(rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return _math.Rectangle.EMPTY; + } + + rect = rect || new _math.Rectangle(0, 0, 1, 1); + + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + + return rect; + }; + + /** + * This function should be inlined when its possible. + * + * @param {PIXI.Point} point - The point to add. + */ + + + Bounds.prototype.addPoint = function addPoint(point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + }; + + /** + * Adds a quad, not transformed + * + * @param {Float32Array} vertices - The verts to add. + */ + + + Bounds.prototype.addQuad = function addQuad(vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = vertices[0]; + var y = vertices[1]; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds sprite frame, transformed. + * + * @param {PIXI.TransformBase} transform - TODO + * @param {number} x0 - TODO + * @param {number} y0 - TODO + * @param {number} x1 - TODO + * @param {number} y1 - TODO + */ + + + Bounds.prototype.addFrame = function addFrame(transform, x0, y0, x1, y1) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = a * x0 + c * y0 + tx; + var y = b * x0 + d * y0 + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y0 + tx; + y = b * x1 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x0 + c * y1 + tx; + y = b * x0 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y1 + tx; + y = b * x1 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Add an array of vertices + * + * @param {PIXI.TransformBase} transform - TODO + * @param {Float32Array} vertices - TODO + * @param {number} beginOffset - TODO + * @param {number} endOffset - TODO + */ + + + Bounds.prototype.addVertices = function addVertices(transform, vertices, beginOffset, endOffset) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = a * rawX + c * rawY + tx; + var y = d * rawY + b * rawX + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds other Bounds + * + * @param {PIXI.Bounds} bounds - TODO + */ + + + Bounds.prototype.addBounds = function addBounds(bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + }; + + /** + * Adds other Bounds, masked with Bounds + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Bounds} mask - TODO + */ + + + Bounds.prototype.addBoundsMask = function addBoundsMask(bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + /** + * Adds other Bounds, masked with Rectangle + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Rectangle} area - TODO + */ + + + Bounds.prototype.addBoundsArea = function addBoundsArea(bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : area.x + area.width; + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : area.y + area.height; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + return Bounds; +}(); + +exports.default = Bounds; + +},{"../math":70}],48:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _DisplayObject2 = require('./DisplayObject'); + +var _DisplayObject3 = _interopRequireDefault(_DisplayObject2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A Container represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + *```js + * let container = new PIXI.Container(); + * container.addChild(sprite); + * ``` + * + * @class + * @extends PIXI.DisplayObject + * @memberof PIXI + */ +var Container = function (_DisplayObject) { + _inherits(Container, _DisplayObject); + + /** + * + */ + function Container() { + _classCallCheck(this, Container); + + /** + * The array of children of this container. + * + * @member {PIXI.DisplayObject[]} + * @readonly + */ + var _this = _possibleConstructorReturn(this, _DisplayObject.call(this)); + + _this.children = []; + return _this; + } + + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified + * + * @private + */ + + + Container.prototype.onChildrenChange = function onChildrenChange() {} + /* empty */ + + + /** + * Adds one or more children to the container. + * + * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container + * @return {PIXI.DisplayObject} The first child that was added. + */ + ; + + Container.prototype.addChild = function addChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.addChild(arguments[i]); + } + } else { + // if the child has a parent then lets remove it as PixiJS objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.push(child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + child.emit('added', this); + } + + return child; + }; + + /** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @return {PIXI.DisplayObject} The child that was added. + */ + + + Container.prototype.addChildAt = function addChildAt(child, index) { + if (index < 0 || index > this.children.length) { + throw new Error(child + 'addChildAt: The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.splice(index, 0, child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + + return child; + }; + + /** + * Swaps the position of 2 Display Objects within this container. + * + * @param {PIXI.DisplayObject} child - First display object to swap + * @param {PIXI.DisplayObject} child2 - Second display object to swap + */ + + + Container.prototype.swapChildren = function swapChildren(child, child2) { + if (child === child2) { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; + + /** + * Returns the index position of a child DisplayObject instance + * + * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify + * @return {number} The index position of the child display object to identify + */ + + + Container.prototype.getChildIndex = function getChildIndex(child) { + var index = this.children.indexOf(child); + + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + }; + + /** + * Changes the position of an existing child in the display object container + * + * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number + * @param {number} index - The resulting index number for the child display object + */ + + + Container.prototype.setChildIndex = function setChildIndex(child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error('The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + var currentIndex = this.getChildIndex(child); + + (0, _utils.removeItems)(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + + this.onChildrenChange(index); + }; + + /** + * Returns the child at the specified index + * + * @param {number} index - The index to get the child at + * @return {PIXI.DisplayObject} The child at the given index, if any. + */ + + + Container.prototype.getChildAt = function getChildAt(index) { + if (index < 0 || index >= this.children.length) { + throw new Error('getChildAt: Index (' + index + ') does not exist.'); + } + + return this.children[index]; + }; + + /** + * Removes one or more children from the container. + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove + * @return {PIXI.DisplayObject} The first child that was removed. + */ + + + Container.prototype.removeChild = function removeChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.removeChild(arguments[i]); + } + } else { + var index = this.children.indexOf(child); + + if (index === -1) return null; + + child.parent = null; + // ensure child transform will be recalculated + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + } + + return child; + }; + + /** + * Removes a child from the specified index position. + * + * @param {number} index - The index to get the child from + * @return {PIXI.DisplayObject} The child that was removed. + */ + + + Container.prototype.removeChildAt = function removeChildAt(index) { + var child = this.getChildAt(index); + + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + + return child; + }; + + /** + * Removes all children from this container that are within the begin and end indexes. + * + * @param {number} [beginIndex=0] - The beginning position. + * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. + * @returns {DisplayObject[]} List of removed children + */ + + + Container.prototype.removeChildren = function removeChildren() { + var beginIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var endIndex = arguments[1]; + + var begin = beginIndex; + var end = typeof endIndex === 'number' ? endIndex : this.children.length; + var range = end - begin; + var removed = void 0; + + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } + + this._boundsID++; + + this.onChildrenChange(beginIndex); + + for (var _i = 0; _i < removed.length; ++_i) { + removed[_i].emit('removed', this); + } + + return removed; + } else if (range === 0 && this.children.length === 0) { + return []; + } + + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + }; + + /** + * Updates the transform on all children of this container for rendering + */ + + + Container.prototype.updateTransform = function updateTransform() { + this._boundsID++; + + this.transform.updateTransform(this.parent.transform); + + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + + if (child.visible) { + child.updateTransform(); + } + } + }; + + /** + * Recalculates the bounds of the container. + * + */ + + + Container.prototype.calculateBounds = function calculateBounds() { + this._bounds.clear(); + + this._calculateBounds(); + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (!child.visible || !child.renderable) { + continue; + } + + child.calculateBounds(); + + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + child._mask.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, child._mask._bounds); + } else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } else { + this._bounds.addBounds(child._bounds); + } + } + + this._lastBoundsID = this._boundsID; + }; + + /** + * Recalculates the bounds of the object. Override this to + * calculate the bounds of the specific object (not including children). + * + */ + + + Container.prototype._calculateBounds = function _calculateBounds() {} + // FILL IN// + + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderWebGL = function renderWebGL(renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + // do a quick check to see if this element has a mask or a filter. + if (this._mask || this._filters) { + this.renderAdvancedWebGL(renderer); + } else { + this._renderWebGL(renderer); + + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderWebGL(renderer); + } + } + }; + + /** + * Render the object using the WebGL renderer and advanced features. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { + renderer.flush(); + + var filters = this._filters; + var mask = this._mask; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + + this._enabledFilters.length = 0; + + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + + if (this._enabledFilters.length) { + renderer.filterManager.pushFilter(this, this._enabledFilters); + } + } + + if (mask) { + renderer.maskManager.pushMask(this, this._mask); + } + + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); + + // now loop through the children and make sure they get rendered + for (var _i2 = 0, j = this.children.length; _i2 < j; _i2++) { + this.children[_i2].renderWebGL(renderer); + } + + renderer.flush(); + + if (mask) { + renderer.maskManager.popMask(this, this._mask); + } + + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filterManager.popFilter(); + } + }; + + /** + * To be overridden by the subclasses. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype._renderWebGL = function _renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * To be overridden by the subclass + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype._renderCanvas = function _renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderCanvas = function renderCanvas(renderer) { + // if not visible or the alpha is 0 then no need to render this + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + if (this._mask) { + renderer.maskManager.pushMask(this._mask); + } + + this._renderCanvas(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderCanvas(renderer); + } + + if (this._mask) { + renderer.maskManager.popMask(renderer); + } + }; + + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Container.prototype.destroy = function destroy(options) { + _DisplayObject.prototype.destroy.call(this); + + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + + var oldChildren = this.removeChildren(0, this.children.length); + + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + }; + + /** + * The width of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Container, [{ + key: 'width', + get: function get() { + return this.scale.x * this.getLocalBounds().width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var width = this.getLocalBounds().width; + + if (width !== 0) { + this.scale.x = value / width; + } else { + this.scale.x = 1; + } + + this._width = value; + } + + /** + * The height of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.scale.y * this.getLocalBounds().height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var height = this.getLocalBounds().height; + + if (height !== 0) { + this.scale.y = value / height; + } else { + this.scale.y = 1; + } + + this._height = value; + } + }]); + + return Container; +}(_DisplayObject3.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = Container; +Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + +},{"../utils":125,"./DisplayObject":49}],49:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TransformStatic = require('./TransformStatic'); + +var _TransformStatic2 = _interopRequireDefault(_TransformStatic); + +var _Transform = require('./Transform'); + +var _Transform2 = _interopRequireDefault(_Transform); + +var _Bounds = require('./Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _math = require('../math'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// _tempDisplayObjectParent = new DisplayObject(); + +/** + * The base class for all objects that are rendered on the screen. + * This is an abstract class and should not be used on its own rather it should be extended. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var DisplayObject = function (_EventEmitter) { + _inherits(DisplayObject, _EventEmitter); + + /** + * + */ + function DisplayObject() { + _classCallCheck(this, DisplayObject); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + var TransformClass = _settings2.default.TRANSFORM_MODE === _const.TRANSFORM_MODE.STATIC ? _TransformStatic2.default : _Transform2.default; + + _this.tempDisplayObjectParent = null; + + // TODO: need to create Transform from factory + /** + * World transform and local transform of this object. + * This will become read-only later, please do not assign anything there unless you know what are you doing + * + * @member {PIXI.TransformBase} + */ + _this.transform = new TransformClass(); + + /** + * The opacity of the object. + * + * @member {number} + */ + _this.alpha = 1; + + /** + * The visibility of the object. If false the object will not be drawn, and + * the updateTransform function will not be called. + * + * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually + * + * @member {boolean} + */ + _this.visible = true; + + /** + * Can this object be rendered, if false the object will not be drawn but the updateTransform + * methods will still be called. + * + * Only affects recursive calls from parent. You can ask for bounds manually + * + * @member {boolean} + */ + _this.renderable = true; + + /** + * The display object container that contains this display object. + * + * @member {PIXI.Container} + * @readonly + */ + _this.parent = null; + + /** + * The multiplied alpha of the displayObject + * + * @member {number} + * @readonly + */ + _this.worldAlpha = 1; + + /** + * The area the filter is applied to. This is used as more of an optimisation + * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle + * + * Also works as an interaction mask + * + * @member {PIXI.Rectangle} + */ + _this.filterArea = null; + + _this._filters = null; + _this._enabledFilters = null; + + /** + * The bounds object, this is used to calculate and store the bounds of the displayObject + * + * @member {PIXI.Rectangle} + * @private + */ + _this._bounds = new _Bounds2.default(); + _this._boundsID = 0; + _this._lastBoundsID = -1; + _this._boundsRect = null; + _this._localBoundsRect = null; + + /** + * The original, cached mask of the object + * + * @member {PIXI.Graphics|PIXI.Sprite} + * @private + */ + _this._mask = null; + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + + /** + * Fired when this DisplayObject is added to a Container. + * + * @event PIXI.DisplayObject#added + * @param {PIXI.Container} container - The container added to. + */ + + /** + * Fired when this DisplayObject is removed from a Container. + * + * @event PIXI.DisplayObject#removed + * @param {PIXI.Container} container - The container removed from. + */ + return _this; + } + + /** + * @private + * @member {PIXI.DisplayObject} + */ + + + /** + * Updates the object transform for rendering + * + * TODO - Optimization pass! + */ + DisplayObject.prototype.updateTransform = function updateTransform() { + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + this._bounds.updateID++; + }; + + /** + * recursively updates transform of all objects from the root to this one + * internal function for toLocal() + */ + + + DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform() { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + }; + + /** + * Retrieves the bounds of the displayObject as a rectangle object. + * + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @param {PIXI.Rectangle} rect - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getBounds = function getBounds(skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + + if (this._boundsID !== this._lastBoundsID) { + this.calculateBounds(); + } + + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new _math.Rectangle(); + } + + rect = this._boundsRect; + } + + return this._bounds.getRectangle(rect); + }; + + /** + * Retrieves the local bounds of the displayObject as a rectangle object + * + * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getLocalBounds = function getLocalBounds(rect) { + var transformRef = this.transform; + var parentRef = this.parent; + + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + var bounds = this.getBounds(false, rect); + + this.parent = parentRef; + this.transform = transformRef; + + return bounds; + }; + + /** + * Calculates the global position of the display object + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform. + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toGlobal = function toGlobal(position, point) { + var skipUpdate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; + + /** + * Calculates the local position of the display object relative to another point + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toLocal = function toLocal(position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + DisplayObject.prototype.renderCanvas = function renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Set the parent Container of this DisplayObject + * + * @param {PIXI.Container} container - The Container to add this DisplayObject to + * @return {PIXI.Container} The Container that this DisplayObject was added to + */ + ; + + DisplayObject.prototype.setParent = function setParent(container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); + } + + container.addChild(this); + + return container; + }; + + /** + * Convenience function to set the position, scale, skew and pivot at once. + * + * @param {number} [x=0] - The X position + * @param {number} [y=0] - The Y position + * @param {number} [scaleX=1] - The X scale value + * @param {number} [scaleY=1] - The Y scale value + * @param {number} [rotation=0] - The rotation + * @param {number} [skewX=0] - The X skew value + * @param {number} [skewY=0] - The Y skew value + * @param {number} [pivotX=0] - The X pivot value + * @param {number} [pivotY=0] - The Y pivot value + * @return {PIXI.DisplayObject} The DisplayObject instance + */ + + + DisplayObject.prototype.setTransform = function setTransform() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var scaleX = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var scaleY = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var rotation = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var skewX = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + var skewY = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + var pivotX = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; + var pivotY = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0; + + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + + return this; + }; + + /** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy`. + * + */ + + + DisplayObject.prototype.destroy = function destroy() { + this.removeAllListeners(); + if (this.parent) { + this.parent.removeChild(this); + } + this.transform = null; + + this.parent = null; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this.filterArea = null; + + this.interactive = false; + this.interactiveChildren = false; + + this._destroyed = true; + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + * + * @member {number} + */ + + + _createClass(DisplayObject, [{ + key: '_tempDisplayObjectParent', + get: function get() { + if (this.tempDisplayObjectParent === null) { + this.tempDisplayObjectParent = new DisplayObject(); + } + + return this.tempDisplayObjectParent; + } + }, { + key: 'x', + get: function get() { + return this.position.x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.x = value; + } + + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + * + * @member {number} + */ + + }, { + key: 'y', + get: function get() { + return this.position.y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.y = value; + } + + /** + * Current transform of the object based on world (parent) factors + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'worldTransform', + get: function get() { + return this.transform.worldTransform; + } + + /** + * Current transform of the object based on local factors: position, scale, other stuff + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'localTransform', + get: function get() { + return this.transform.localTransform; + } + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'position', + get: function get() { + return this.transform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.copy(value); + } + + /** + * The scale factor of the object. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'scale', + get: function get() { + return this.transform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.scale.copy(value); + } + + /** + * The pivot point of the displayObject that it rotates around. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'pivot', + get: function get() { + return this.transform.pivot; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.pivot.copy(value); + } + + /** + * The skew factor for the object in radians. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'skew', + get: function get() { + return this.transform.skew; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.skew.copy(value); + } + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + }, { + key: 'rotation', + get: function get() { + return this.transform.rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.rotation = value; + } + + /** + * Indicates if the object is globally visible. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'worldVisible', + get: function get() { + var item = this; + + do { + if (!item.visible) { + return false; + } + + item = item.parent; + } while (item); + + return true; + } + + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PIXI a regular mask must be a + * PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it + * utilises shape clipping. To remove a mask, set this property to null. + * + * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + * + * @member {PIXI.Graphics|PIXI.Sprite} + */ + + }, { + key: 'mask', + get: function get() { + return this._mask; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._mask) { + this._mask.renderable = true; + this._mask.isMask = false; + } + + this._mask = value; + + if (this._mask) { + this._mask.renderable = false; + this._mask.isMask = true; + } + } + + /** + * Sets the filters for the displayObject. + * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * To remove filters simply set this property to 'null' + * + * @member {PIXI.Filter[]} + */ + + }, { + key: 'filters', + get: function get() { + return this._filters && this._filters.slice(); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._filters = value && value.slice(); + } + }]); + + return DisplayObject; +}(_eventemitter2.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = DisplayObject; +DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + +},{"../const":46,"../math":70,"../settings":101,"./Bounds":47,"./Transform":50,"./TransformStatic":52,"eventemitter3":3}],50:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Generic class to deal with traditional 2D matrix transforms + * local transformation is calculated from position,scale,skew and rotation + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var Transform = function (_TransformBase) { + _inherits(Transform, _TransformBase); + + /** + * + */ + function Transform() { + _classCallCheck(this, Transform); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.Point} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.Point(0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.Point} + */ + _this.scale = new _math.Point(1, 1); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + /** + * The pivot point of the displayObject that it rotates around. + * + * @member {PIXI.Point} + */ + _this.pivot = new _math.Point(0, 0); + + /** + * The rotation value of the object, in radians + * + * @member {Number} + * @private + */ + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + return _this; + } + + /** + * Updates the skew values when the skew or rotation changes. + * + * @private + */ + + + Transform.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + }; + + /** + * Updates only local matrix + */ + + + Transform.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + Transform.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + Transform.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(Transform, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return Transform; +}(_TransformBase3.default); + +exports.default = Transform; + +},{"../math":70,"./TransformBase":51}],51:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Generic class to deal with traditional 2D matrix transforms + * + * @class + * @memberof PIXI + */ +var TransformBase = function () { + /** + * + */ + function TransformBase() { + _classCallCheck(this, TransformBase); + + /** + * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds() + * + * @member {PIXI.Matrix} + */ + this.worldTransform = new _math.Matrix(); + + /** + * The local matrix transform + * + * @member {PIXI.Matrix} + */ + this.localTransform = new _math.Matrix(); + + this._worldID = 0; + this._parentID = 0; + } + + /** + * TransformBase does not have decomposition, so this function wont do anything + */ + + + TransformBase.prototype.updateLocalTransform = function updateLocalTransform() {} + // empty + + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.TransformBase} parentTransform - The transform of the parent of this object + */ + ; + + TransformBase.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + return TransformBase; +}(); + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ + + +exports.default = TransformBase; +TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; + +TransformBase.IDENTITY = new TransformBase(); + +},{"../math":70}],52:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Transform that takes care about its versions + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var TransformStatic = function (_TransformBase) { + _inherits(TransformStatic, _TransformBase); + + /** + * + */ + function TransformStatic() { + _classCallCheck(this, TransformStatic); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.ObservablePoint} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.ObservablePoint} + */ + _this.scale = new _math.ObservablePoint(_this.onChange, _this, 1, 1); + + /** + * The pivot point of the displayObject that it rotates around. + * + * @member {PIXI.ObservablePoint} + */ + _this.pivot = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + + _this._localID = 0; + _this._currentLocalID = 0; + return _this; + } + + /** + * Called when a value changes. + * + * @private + */ + + + TransformStatic.prototype.onChange = function onChange() { + this._localID++; + }; + + /** + * Called when skew or rotation changes + * + * @private + */ + + + TransformStatic.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + + this._localID++; + }; + + /** + * Updates only local matrix + */ + + + TransformStatic.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + TransformStatic.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._parentID = parentTransform._worldID; + + // update the id of the transform.. + this._worldID++; + } + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + TransformStatic.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + this._localID++; + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(TransformStatic, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return TransformStatic; +}(_TransformBase3.default); + +exports.default = TransformStatic; + +},{"../math":70,"./TransformBase":51}],53:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _GraphicsData = require('./GraphicsData'); + +var _GraphicsData2 = _interopRequireDefault(_GraphicsData); + +var _Sprite = require('../sprites/Sprite'); + +var _Sprite2 = _interopRequireDefault(_Sprite); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Bounds = require('../display/Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _bezierCurveTo2 = require('./utils/bezierCurveTo'); + +var _bezierCurveTo3 = _interopRequireDefault(_bezierCurveTo2); + +var _CanvasRenderer = require('../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var canvasRenderer = void 0; +var tempMatrix = new _math.Matrix(); +var tempPoint = new _math.Point(); +var tempColor1 = new Float32Array(4); +var tempColor2 = new Float32Array(4); + +/** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Graphics = function (_Container) { + _inherits(Graphics, _Container); + + /** + * + * @param {boolean} [nativeLines=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + */ + function Graphics() { + var nativeLines = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + _classCallCheck(this, Graphics); + + /** + * The alpha value used when filling the Graphics object. + * + * @member {number} + * @default 1 + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @member {number} + * @default 0 + */ + _this.lineWidth = 0; + + /** + * If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * + * @member {boolean} + */ + _this.nativeLines = nativeLines; + + /** + * The color of any lines drawn. + * + * @member {string} + * @default 0 + */ + _this.lineColor = 0; + + /** + * The alignment of any lines drawn (0.5 = middle, 1 = outter, 0 = inner). + * + * @member {number} + * @default 0 + */ + _this.lineAlignment = 0.5; + + /** + * Graphics data + * + * @member {PIXI.GraphicsData[]} + * @private + */ + _this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to + * reset the tint. + * + * @member {number} + * @default 0xFFFFFF + */ + _this.tint = 0xFFFFFF; + + /** + * The previous tint applied to the graphic shape. Used to compare to the current tint and + * check if theres change. + * + * @member {number} + * @private + * @default 0xFFFFFF + */ + _this._prevTint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * Current path + * + * @member {PIXI.GraphicsData} + * @private + */ + _this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @member {object} + * @private + */ + // TODO - _webgl should use a prototype object, not a random undocumented object... + _this._webGL = {}; + + /** + * Whether this shape is being used as a mask. + * + * @member {boolean} + */ + _this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @member {number} + */ + _this.boundsPadding = 0; + + /** + * A cache of the local bounds to prevent recalculation. + * + * @member {PIXI.Rectangle} + * @private + */ + _this._localBounds = new _Bounds2.default(); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics + * object will be recalculated. + * + * @member {boolean} + * @private + */ + _this.dirty = 0; + + /** + * Used to detect if we need to do a fast rect check using the id compare method + * @type {Number} + */ + _this.fastRectDirty = -1; + + /** + * Used to detect if we clear the graphics webGL data + * @type {Number} + */ + _this.clearDirty = 0; + + /** + * Used to detect if we we need to recalculate local bounds + * @type {Number} + */ + _this.boundsDirty = -1; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @member {boolean} + * @private + */ + _this.cachedSpriteDirty = false; + + _this._spriteRect = null; + _this._fastRect = false; + + _this._prevRectTint = null; + _this._prevRectFillColor = null; + + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ + return _this; + } + + /** + * Creates a new Graphics object with the same values as this one. + * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) + * + * @return {PIXI.Graphics} A clone of the graphics object + */ + + + Graphics.prototype.clone = function clone() { + var clone = new Graphics(); + + clone.renderable = this.renderable; + clone.fillAlpha = this.fillAlpha; + clone.lineWidth = this.lineWidth; + clone.lineColor = this.lineColor; + clone.lineAlignment = this.lineAlignment; + clone.tint = this.tint; + clone.blendMode = this.blendMode; + clone.isMask = this.isMask; + clone.boundsPadding = this.boundsPadding; + clone.dirty = 0; + clone.cachedSpriteDirty = this.cachedSpriteDirty; + + // copy graphics data + for (var i = 0; i < this.graphicsData.length; ++i) { + clone.graphicsData.push(this.graphicsData[i].clone()); + } + + clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; + + clone.updateLocalBounds(); + + return clone; + }; + + /** + * Calculate length of quadratic curve + * @see {@link http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/} + * for the detailed explanation of math behind this. + * + * @private + * @param {number} fromX - x-coordinate of curve start point + * @param {number} fromY - y-coordinate of curve start point + * @param {number} cpX - x-coordinate of curve control point + * @param {number} cpY - y-coordinate of curve control point + * @param {number} toX - x-coordinate of curve end point + * @param {number} toY - y-coordinate of curve end point + * @return {number} Length of quadratic curve + */ + + + Graphics.prototype._quadraticCurveLength = function _quadraticCurveLength(fromX, fromY, cpX, cpY, toX, toY) { + var ax = fromX - (2.0 * cpX + toX); + var ay = fromY - (2.0 * cpY + toY); + var bx = 2.0 * ((cpX - 2.0) * fromX); + var by = 2.0 * ((cpY - 2.0) * fromY); + var a = 4.0 * (ax * ax + ay * ay); + var b = 4.0 * (ax * bx + ay * by); + var c = bx * bx + by * by; + + var s = 2.0 * Math.sqrt(a + b + c); + var a2 = Math.sqrt(a); + var a32 = 2.0 * a * a2; + var c2 = 2.0 * Math.sqrt(c); + var ba = b / a2; + + return (a32 * s + a2 * b * (s - c2) + (4.0 * c * a - b * b) * Math.log((2.0 * a2 + ba + s) / (ba + c2))) / (4.0 * a32); + }; + + /** + * Calculate length of bezier curve. + * Analytical solution is impossible, since it involves an integral that does not integrate in general. + * Therefore numerical solution is used. + * + * @private + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {number} Length of bezier curve + */ + + + Graphics.prototype._bezierCurveLength = function _bezierCurveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var n = 10; + var result = 0.0; + var t = 0.0; + var t2 = 0.0; + var t3 = 0.0; + var nt = 0.0; + var nt2 = 0.0; + var nt3 = 0.0; + var x = 0.0; + var y = 0.0; + var dx = 0.0; + var dy = 0.0; + var prevX = fromX; + var prevY = fromY; + + for (var i = 1; i <= n; ++i) { + t = i / n; + t2 = t * t; + t3 = t2 * t; + nt = 1.0 - t; + nt2 = nt * nt; + nt3 = nt2 * nt; + + x = nt3 * fromX + 3.0 * nt2 * t * cpX + 3.0 * nt * t2 * cpX2 + t3 * toX; + y = nt3 * fromY + 3.0 * nt2 * t * cpY + 3 * nt * t2 * cpY2 + t3 * toY; + dx = prevX - x; + dy = prevY - y; + prevX = x; + prevY = y; + + result += Math.sqrt(dx * dx + dy * dy); + } + + return result; + }; + + /** + * Calculate number of segments for the curve based on its length to ensure its smoothness. + * + * @private + * @param {number} length - length of curve + * @return {number} Number of segments + */ + + + Graphics.prototype._segmentsCount = function _segmentsCount(length) { + var result = Math.ceil(length / Graphics.CURVES.maxLength); + + if (result < Graphics.CURVES.minSegments) { + result = Graphics.CURVES.minSegments; + } else if (result > Graphics.CURVES.maxSegments) { + result = Graphics.CURVES.maxSegments; + } + + return result; + }; + + /** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() + * method or the drawCircle() method. + * + * @param {number} [lineWidth=0] - width of the line to draw, will update the objects stored style + * @param {number} [color=0] - color of the line to draw, will update the objects stored style + * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style + * @param {number} [alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineStyle = function lineStyle() { + var lineWidth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var alpha = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var alignment = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0.5; + + this.lineWidth = lineWidth; + this.lineColor = color; + this.lineAlpha = alpha; + this.lineAlignment = alignment; + + if (this.currentPath) { + if (this.currentPath.shape.points.length) { + // halfway through a line? start a new one! + var shape = new _math.Polygon(this.currentPath.shape.points.slice(-2)); + + shape.closed = false; + + this.drawShape(shape); + } else { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + this.currentPath.lineAlignment = this.lineAlignment; + } + } + + return this; + }; + + /** + * Moves the current drawing position to x, y. + * + * @param {number} x - the X coordinate to move to + * @param {number} y - the Y coordinate to move to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.moveTo = function moveTo(x, y) { + var shape = new _math.Polygon([x, y]); + + shape.closed = false; + this.drawShape(shape); + + return this; + }; + + /** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @param {number} x - the X coordinate to draw to + * @param {number} y - the Y coordinate to draw to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineTo = function lineTo(x, y) { + var points = this.currentPath.shape.points; + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + if (fromX !== x || fromY !== y) { + points.push(x, y); + this.dirty++; + } + + return this; + }; + + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.quadraticCurveTo = function quadraticCurveTo(cpX, cpY, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + var xa = 0; + var ya = 0; + + if (points.length === 0) { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var n = Graphics.CURVES.adaptive ? this._segmentsCount(this._quadraticCurveLength(fromX, fromY, cpX, cpY, toX, toY)) : 20; + + for (var i = 1; i <= n; ++i) { + var j = i / n; + + xa = fromX + (cpX - fromX) * j; + ya = fromY + (cpY - fromY) * j; + + points.push(xa + (cpX + (toX - cpX) * j - xa) * j, ya + (cpY + (toY - cpY) * j - ya) * j); + } + + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a bezier curve and then draws it. + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.bezierCurveTo = function bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + points.length -= 2; + + var n = Graphics.CURVES.adaptive ? this._segmentsCount(this._bezierCurveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY)) : 20; + + (0, _bezierCurveTo3.default)(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, n, points); + + this.dirty++; + + return this; + }; + + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @param {number} x1 - The x-coordinate of the beginning of the arc + * @param {number} y1 - The y-coordinate of the beginning of the arc + * @param {number} x2 - The x-coordinate of the end of the arc + * @param {number} y2 - The y-coordinate of the end of the arc + * @param {number} radius - The radius of the arc + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arcTo = function arcTo(x1, y1, x2, y2, radius) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points.push(x1, y1); + } + } else { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + } else { + var dd = a1 * a1 + b1 * b1; + var cc = a2 * a2 + b2 * b2; + var tt = a1 * a2 + b1 * b2; + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = k1 * b2 + k2 * b1; + var cy = k1 * a2 + k2 * a1; + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty++; + + return this; + }; + + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @param {number} cx - The x-coordinate of the center of the circle + * @param {number} cy - The y-coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param {number} endAngle - The ending angle, in radians + * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arc = function arc(cx, cy, radius, startAngle, endAngle) { + var anticlockwise = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; + + if (startAngle === endAngle) { + return this; + } + + if (!anticlockwise && endAngle <= startAngle) { + endAngle += _const.PI_2; + } else if (anticlockwise && startAngle <= endAngle) { + startAngle += _const.PI_2; + } + + var sweep = endAngle - startAngle; + var segs = Graphics.CURVES.adaptive ? this._segmentsCount(Math.abs(sweep) * radius) : Math.ceil(Math.abs(sweep) / _const.PI_2) * 40; + + if (sweep === 0) { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. + var points = this.currentPath ? this.currentPath.shape.points : null; + + if (points) { + // We check how far our start is from the last existing point + var xDiff = Math.abs(points[points.length - 2] - startX); + var yDiff = Math.abs(points[points.length - 1] - startY); + + if (xDiff < 0.001 && yDiff < 0.001) { + // If the point is very close, we don't add it, since this would lead to artifacts + // during tesselation due to floating point imprecision. + } else { + points.push(startX, startY); + } + } else { + this.moveTo(startX, startY); + points = this.currentPath.shape.points; + } + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = segMinus % 1 / segMinus; + + for (var i = 0; i <= segMinus; ++i) { + var real = i + remainder * i; + + var angle = theta + startAngle + theta2 * real; + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push((cTheta * c + sTheta * s) * radius + cx, (cTheta * -s + sTheta * c) * radius + cy); + } + + this.dirty++; + + return this; + }; + + /** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @param {number} [color=0] - the color of the fill + * @param {number} [alpha=1] - the alpha of the fill + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.beginFill = function beginFill() { + var color = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var alpha = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.filling = true; + this.fillColor = color; + this.fillAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length <= 2) { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + }; + + /** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.endFill = function endFill() { + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRect = function drawRect(x, y, width, height) { + this.drawShape(new _math.Rectangle(x, y, width, height)); + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @param {number} radius - Radius of the rectangle corners + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRoundedRect = function drawRoundedRect(x, y, width, height, radius) { + this.drawShape(new _math.RoundedRectangle(x, y, width, height, radius)); + + return this; + }; + + /** + * Draws a circle. + * + * @param {number} x - The X coordinate of the center of the circle + * @param {number} y - The Y coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawCircle = function drawCircle(x, y, radius) { + this.drawShape(new _math.Circle(x, y, radius)); + + return this; + }; + + /** + * Draws an ellipse. + * + * @param {number} x - The X coordinate of the center of the ellipse + * @param {number} y - The Y coordinate of the center of the ellipse + * @param {number} width - The half width of the ellipse + * @param {number} height - The half height of the ellipse + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawEllipse = function drawEllipse(x, y, width, height) { + this.drawShape(new _math.Ellipse(x, y, width, height)); + + return this; + }; + + /** + * Draws a polygon using the given path. + * + * @param {number[]|PIXI.Point[]|PIXI.Polygon} path - The path data used to construct the polygon. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawPolygon = function drawPolygon(path) { + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + var closed = true; + + if (points instanceof _math.Polygon) { + closed = points.closed; + points = points.points; + } + + if (!Array.isArray(points)) { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) { + points[i] = arguments[i]; // eslint-disable-line prefer-rest-params + } + } + + var shape = new _math.Polygon(points); + + shape.closed = closed; + + this.drawShape(shape); + + return this; + }; + + /** + * Draw a star shape with an abitrary number of points. + * + * @param {number} x - Center X position of the star + * @param {number} y - Center Y position of the star + * @param {number} points - The number of points of the star, must be > 1 + * @param {number} radius - The outer radius of the star + * @param {number} [innerRadius] - The inner radius between points, default half `radius` + * @param {number} [rotation=0] - The rotation of the star in radians, where 0 is vertical + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawStar = function drawStar(x, y, points, radius, innerRadius) { + var rotation = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + + innerRadius = innerRadius || radius / 2; + + var startAngle = -1 * Math.PI / 2 + rotation; + var len = points * 2; + var delta = _const.PI_2 / len; + var polygon = []; + + for (var i = 0; i < len; i++) { + var r = i % 2 ? innerRadius : radius; + var angle = i * delta + startAngle; + + polygon.push(x + r * Math.cos(angle), y + r * Math.sin(angle)); + } + + return this.drawPolygon(polygon); + }; + + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.clear = function clear() { + if (this.lineWidth || this.filling || this.graphicsData.length > 0) { + this.lineWidth = 0; + this.lineAlignment = 0.5; + + this.filling = false; + + this.boundsDirty = -1; + this.canvasTintDirty = -1; + this.dirty++; + this.clearDirty++; + this.graphicsData.length = 0; + } + + this.currentPath = null; + this._spriteRect = null; + + return this; + }; + + /** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. + * + * @returns {boolean} True if only 1 rect. + */ + + + Graphics.prototype.isFastRect = function isFastRect() { + return this.graphicsData.length === 1 && this.graphicsData[0].shape.type === _const.SHAPES.RECT && !this.graphicsData[0].lineWidth; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderWebGL = function _renderWebGL(renderer) { + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.dirty !== this.fastRectDirty) { + this.fastRectDirty = this.dirty; + this._fastRect = this.isFastRect(); + } + + // TODO this check can be moved to dirty? + if (this._fastRect) { + this._renderSpriteRect(renderer); + } else { + renderer.setObjectRenderer(renderer.plugins.graphics); + renderer.plugins.graphics.render(this); + } + }; + + /** + * Renders a sprite rectangle. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderSpriteRect = function _renderSpriteRect(renderer) { + var rect = this.graphicsData[0].shape; + + if (!this._spriteRect) { + this._spriteRect = new _Sprite2.default(new _Texture2.default(_Texture2.default.WHITE)); + } + + var sprite = this._spriteRect; + var fillColor = this.graphicsData[0].fillColor; + + if (this.tint === 0xffffff) { + sprite.tint = fillColor; + } else if (this.tint !== this._prevRectTint || fillColor !== this._prevRectFillColor) { + var t1 = tempColor1; + var t2 = tempColor2; + + (0, _utils.hex2rgb)(fillColor, t1); + (0, _utils.hex2rgb)(this.tint, t2); + + t1[0] *= t2[0]; + t1[1] *= t2[1]; + t1[2] *= t2[2]; + + sprite.tint = (0, _utils.rgb2hex)(t1); + + this._prevRectTint = this.tint; + this._prevRectFillColor = fillColor; + } + + sprite.alpha = this.graphicsData[0].fillAlpha; + sprite.worldAlpha = this.worldAlpha * sprite.alpha; + sprite.blendMode = this.blendMode; + + sprite._texture._frame.width = rect.width; + sprite._texture._frame.height = rect.height; + + sprite.transform.worldTransform = this.transform.worldTransform; + + sprite.anchor.set(-rect.x / rect.width, -rect.y / rect.height); + sprite._onAnchorUpdate(); + + sprite._renderWebGL(renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.isMask === true) { + return; + } + + renderer.plugins.graphics.render(this); + }; + + /** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @private + */ + + + Graphics.prototype._calculateBounds = function _calculateBounds() { + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.updateLocalBounds(); + + this.cachedSpriteDirty = true; + } + + var lb = this._localBounds; + + this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); + }; + + /** + * Tests if a point is inside this graphics object + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Graphics.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + + if (!data.fill) { + continue; + } + + // only deal with fills.. + if (data.shape) { + if (data.shape.contains(tempPoint.x, tempPoint.y)) { + if (data.holes) { + for (var _i = 0; _i < data.holes.length; _i++) { + var hole = data.holes[_i]; + + if (hole.contains(tempPoint.x, tempPoint.y)) { + return false; + } + } + } + + return true; + } + } + } + + return false; + }; + + /** + * Update the bounds of the object + * + */ + + + Graphics.prototype.updateLocalBounds = function updateLocalBounds() { + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) { + var shape = 0; + var x = 0; + var y = 0; + var w = 0; + var h = 0; + + for (var i = 0; i < this.graphicsData.length; i++) { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + + shape = data.shape; + + if (type === _const.SHAPES.RECT || type === _const.SHAPES.RREC) { + x = shape.x - lineWidth / 2; + y = shape.y - lineWidth / 2; + w = shape.width + lineWidth; + h = shape.height + lineWidth; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.CIRC) { + x = shape.x; + y = shape.y; + w = shape.radius + lineWidth / 2; + h = shape.radius + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.ELIP) { + x = shape.x; + y = shape.y; + w = shape.width + lineWidth / 2; + h = shape.height + lineWidth / 2; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else { + // POLY + var points = shape.points; + var x2 = 0; + var y2 = 0; + var dx = 0; + var dy = 0; + var rw = 0; + var rh = 0; + var cx = 0; + var cy = 0; + + for (var j = 0; j + 2 < points.length; j += 2) { + x = points[j]; + y = points[j + 1]; + x2 = points[j + 2]; + y2 = points[j + 3]; + dx = Math.abs(x2 - x); + dy = Math.abs(y2 - y); + h = lineWidth; + w = Math.sqrt(dx * dx + dy * dy); + + if (w < 1e-9) { + continue; + } + + rw = (h / w * dy + dx) / 2; + rh = (h / w * dx + dy) / 2; + cx = (x2 + x) / 2; + cy = (y2 + y) / 2; + + minX = cx - rw < minX ? cx - rw : minX; + maxX = cx + rw > maxX ? cx + rw : maxX; + + minY = cy - rh < minY ? cy - rh : minY; + maxY = cy + rh > maxY ? cy + rh : maxY; + } + } + } + } else { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.minX = minX - padding; + this._localBounds.maxX = maxX + padding; + + this._localBounds.minY = minY - padding; + this._localBounds.maxY = maxY + padding; + }; + + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @return {PIXI.GraphicsData} The generated GraphicsData object. + */ + + + Graphics.prototype.drawShape = function drawShape(shape) { + if (this.currentPath) { + // check current path! + if (this.currentPath.shape.points.length <= 2) { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + var data = new _GraphicsData2.default(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, this.nativeLines, shape, this.lineAlignment); + + this.graphicsData.push(data); + + if (data.type === _const.SHAPES.POLY) { + data.shape.closed = data.shape.closed; + this.currentPath = data; + } + + this.dirty++; + + return data; + }; + + /** + * Generates a canvas texture. + * + * @param {number} scaleMode - The scale mode of the texture. + * @param {number} resolution - The resolution of the texture. + * @return {PIXI.Texture} The new texture. + */ + + + Graphics.prototype.generateCanvasTexture = function generateCanvasTexture(scaleMode) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + var bounds = this.getLocalBounds(); + + var canvasBuffer = _RenderTexture2.default.create(bounds.width, bounds.height, scaleMode, resolution); + + if (!canvasRenderer) { + canvasRenderer = new _CanvasRenderer2.default(); + } + + this.transform.updateLocalTransform(); + this.transform.localTransform.copy(tempMatrix); + + tempMatrix.invert(); + + tempMatrix.tx -= bounds.x; + tempMatrix.ty -= bounds.y; + + canvasRenderer.render(this, canvasBuffer, true, tempMatrix); + + var texture = _Texture2.default.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas, scaleMode, 'graphics'); + + texture.baseTexture.resolution = resolution; + texture.baseTexture.update(); + + return texture; + }; + + /** + * Closes the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.closePath = function closePath() { + // ok so close path assumes next one is a hole! + var currentPath = this.currentPath; + + if (currentPath && currentPath.shape) { + currentPath.shape.close(); + } + + return this; + }; + + /** + * Adds a hole in the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.addHole = function addHole() { + // this is a hole! + var hole = this.graphicsData.pop(); + + this.currentPath = this.graphicsData[this.graphicsData.length - 1]; + + this.currentPath.addHole(hole.shape); + this.currentPath = null; + + return this; + }; + + /** + * Destroys the Graphics object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Graphics.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._webGL) { + for (var j = 0; j < this._webGL[id].data.length; ++j) { + this._webGL[id].data[j].destroy(); + } + } + + if (this._spriteRect) { + this._spriteRect.destroy(); + } + + this.graphicsData = null; + + this.currentPath = null; + this._webGL = null; + this._localBounds = null; + }; + + return Graphics; +}(_Container3.default); + +exports.default = Graphics; + + +Graphics._SPRITE_TEXTURE = null; + +/** + * Graphics curves resolution settings. If `adaptive` flag is set to `true`, + * the resolution is calculated based on the curve's length to ensure better visual quality. + * Adaptive draw works with `bezierCurveTo` and `quadraticCurveTo`. + * + * @static + * @constant + * @memberof PIXI.Graphics + * @name CURVES + * @type {object} + * @property {boolean} adaptive=false - flag indicating if the resolution should be adaptive + * @property {number} maxLength=10 - maximal length of a single segment of the curve (if adaptive = false, ignored) + * @property {number} minSegments=8 - minimal number of segments in the curve (if adaptive = false, ignored) + * @property {number} maxSegments=2048 - maximal number of segments in the curve (if adaptive = false, ignored) + */ +Graphics.CURVES = { + adaptive: false, + maxLength: 10, + minSegments: 8, + maxSegments: 2048 +}; + +},{"../const":46,"../display/Bounds":47,"../display/Container":48,"../math":70,"../renderers/canvas/CanvasRenderer":77,"../sprites/Sprite":102,"../textures/RenderTexture":113,"../textures/Texture":115,"../utils":125,"./GraphicsData":54,"./utils/bezierCurveTo":56}],54:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + */ +var GraphicsData = function () { + /** + * + * @param {number} lineWidth - the width of the line to draw + * @param {number} lineColor - the color of the line to draw + * @param {number} lineAlpha - the alpha of the line to draw + * @param {number} fillColor - the color of the fill + * @param {number} fillAlpha - the alpha of the fill + * @param {boolean} fill - whether or not the shape is filled with a colour + * @param {boolean} nativeLines - the method for drawing lines + * @param {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} shape - The shape object to draw. + * @param {number} lineAlignment - the alignment of the line. + */ + function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, nativeLines, shape, lineAlignment) { + _classCallCheck(this, GraphicsData); + + /** + * the width of the line to draw + * @member {number} + */ + this.lineWidth = lineWidth; + + /** + * The alignment of any lines drawn (0.5 = middle, 1 = outter, 0 = inner). + * + * @member {number} + * @default 0 + */ + this.lineAlignment = lineAlignment; + + /** + * if true the liens will be draw using LINES instead of TRIANGLE_STRIP + * @member {boolean} + */ + this.nativeLines = nativeLines; + + /** + * the color of the line to draw + * @member {number} + */ + this.lineColor = lineColor; + + /** + * the alpha of the line to draw + * @member {number} + */ + this.lineAlpha = lineAlpha; + + /** + * cached tint of the line to draw + * @member {number} + * @private + */ + this._lineTint = lineColor; + + /** + * the color of the fill + * @member {number} + */ + this.fillColor = fillColor; + + /** + * the alpha of the fill + * @member {number} + */ + this.fillAlpha = fillAlpha; + + /** + * cached tint of the fill + * @member {number} + * @private + */ + this._fillTint = fillColor; + + /** + * whether or not the shape is filled with a colour + * @member {boolean} + */ + this.fill = fill; + + this.holes = []; + + /** + * The shape object to draw. + * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} + */ + this.shape = shape; + + /** + * The type of the shape, see the Const.Shapes file for all the existing types, + * @member {number} + */ + this.type = shape.type; + } + + /** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {PIXI.GraphicsData} Cloned GraphicsData object + */ + + + GraphicsData.prototype.clone = function clone() { + return new GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.fill, this.nativeLines, this.shape); + }; + + /** + * Adds a hole to the shape. + * + * @param {PIXI.Rectangle|PIXI.Circle} shape - The shape of the hole. + */ + + + GraphicsData.prototype.addHole = function addHole(shape) { + this.holes.push(shape); + }; + + /** + * Destroys the Graphics data. + */ + + + GraphicsData.prototype.destroy = function destroy() { + this.shape = null; + this.holes = null; + }; + + return GraphicsData; +}(); + +exports.default = GraphicsData; + +},{}],55:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they + * now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasGraphicsRenderer: + * https://github.com/libgdx/libgdx/blob/1.0.0/gdx/src/com/badlogic/gdx/graphics/glutils/ShapeRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching graphics objects. + * + * @class + * @private + * @memberof PIXI + */ +var CanvasGraphicsRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The current PIXI renderer. + */ + function CanvasGraphicsRenderer(renderer) { + _classCallCheck(this, CanvasGraphicsRenderer); + + this.renderer = renderer; + } + + /** + * Renders a Graphics object to a canvas. + * + * @param {PIXI.Graphics} graphics - the actual graphics object to render + */ + + + CanvasGraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var context = renderer.context; + var worldAlpha = graphics.worldAlpha; + var transform = graphics.transform.worldTransform; + var resolution = renderer.resolution; + + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // update tint if graphics was dirty + if (graphics.canvasTintDirty !== graphics.dirty || graphics._prevTint !== graphics.tint) { + this.updateGraphicsTint(graphics); + } + + renderer.setBlendMode(graphics.blendMode); + + for (var i = 0; i < graphics.graphicsData.length; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === _const.SHAPES.POLY) { + context.beginPath(); + + this.renderPolygon(shape.points, shape.closed, context); + + for (var j = 0; j < data.holes.length; j++) { + this.renderPolygon(data.holes[j].points, true, context); + } + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RECT) { + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + context.beginPath(); + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + }; + + /** + * Updates the tint of a graphics object + * + * @private + * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated + */ + + + CanvasGraphicsRenderer.prototype.updateGraphicsTint = function updateGraphicsTint(graphics) { + graphics._prevTint = graphics.tint; + graphics.canvasTintDirty = graphics.dirty; + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF) / 255; + + for (var i = 0; i < graphics.graphicsData.length; ++i) { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + // super inline, cos optimization :) + data._fillTint = ((fillColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (fillColor & 0xFF) / 255 * tintB * 255; + + data._lineTint = ((lineColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (lineColor & 0xFF) / 255 * tintB * 255; + } + }; + + /** + * Renders a polygon. + * + * @param {PIXI.Point[]} points - The points to render + * @param {boolean} close - Should the polygon be closed + * @param {CanvasRenderingContext2D} context - The rendering context to use + */ + + + CanvasGraphicsRenderer.prototype.renderPolygon = function renderPolygon(points, close, context) { + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; ++j) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (close) { + context.closePath(); + } + }; + + /** + * destroy graphics object + * + */ + + + CanvasGraphicsRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasGraphicsRenderer; +}(); + +exports.default = CanvasGraphicsRenderer; + + +_CanvasRenderer2.default.registerPlugin('graphics', CanvasGraphicsRenderer); + +},{"../../const":46,"../../renderers/canvas/CanvasRenderer":77}],56:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = bezierCurveTo; +/** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number} n - Number of segments approximating the bezier curve + * @param {number[]} [path=[]] - Path array to push points into + * @return {number[]} Array of points of the curve + */ +function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, n) { + var path = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : []; + + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + + path.push(fromX, fromY); + + for (var i = 1, j = 0; i <= n; ++i) { + j = i / n; + + dt = 1 - j; + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + path.push(dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + return path; +} + +},{}],57:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _WebGLGraphicsData = require('./WebGLGraphicsData'); + +var _WebGLGraphicsData2 = _interopRequireDefault(_WebGLGraphicsData); + +var _PrimitiveShader = require('./shaders/PrimitiveShader'); + +var _PrimitiveShader2 = _interopRequireDefault(_PrimitiveShader); + +var _buildPoly = require('./utils/buildPoly'); + +var _buildPoly2 = _interopRequireDefault(_buildPoly); + +var _buildRectangle = require('./utils/buildRectangle'); + +var _buildRectangle2 = _interopRequireDefault(_buildRectangle); + +var _buildRoundedRectangle = require('./utils/buildRoundedRectangle'); + +var _buildRoundedRectangle2 = _interopRequireDefault(_buildRoundedRectangle); + +var _buildCircle = require('./utils/buildCircle'); + +var _buildCircle2 = _interopRequireDefault(_buildCircle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Renders the graphics object. + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var GraphicsRenderer = function (_ObjectRenderer) { + _inherits(GraphicsRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this object renderer works for. + */ + function GraphicsRenderer(renderer) { + _classCallCheck(this, GraphicsRenderer); + + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.graphicsDataPool = []; + + _this.primitiveShader = null; + + _this.gl = renderer.gl; + + // easy access! + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * Called when there is a WebGL context change + * + * @private + * + */ + + + GraphicsRenderer.prototype.onContextChange = function onContextChange() { + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.primitiveShader = new _PrimitiveShader2.default(this.gl); + }; + + /** + * Destroys this renderer. + * + */ + + + GraphicsRenderer.prototype.destroy = function destroy() { + _ObjectRenderer3.default.prototype.destroy.call(this); + + for (var i = 0; i < this.graphicsDataPool.length; ++i) { + this.graphicsDataPool[i].destroy(); + } + + this.graphicsDataPool = null; + }; + + /** + * Renders a graphics object. + * + * @param {PIXI.Graphics} graphics - The graphics object to render. + */ + + + GraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var gl = renderer.gl; + + var webGLData = void 0; + var webGL = graphics._webGL[this.CONTEXT_UID]; + + if (!webGL || graphics.dirty !== webGL.dirty) { + this.updateGraphics(graphics); + + webGL = graphics._webGL[this.CONTEXT_UID]; + } + + // This could be speeded up for sure! + var shader = this.primitiveShader; + + renderer.bindShader(shader); + renderer.state.setBlendMode(graphics.blendMode); + + for (var i = 0, n = webGL.data.length; i < n; i++) { + webGLData = webGL.data[i]; + var shaderTemp = webGLData.shader; + + renderer.bindShader(shaderTemp); + shaderTemp.uniforms.translationMatrix = graphics.transform.worldTransform.toArray(true); + shaderTemp.uniforms.tint = (0, _utils.hex2rgb)(graphics.tint); + shaderTemp.uniforms.alpha = graphics.worldAlpha; + + renderer.bindVao(webGLData.vao); + + if (webGLData.nativeLines) { + gl.drawArrays(gl.LINES, 0, webGLData.points.length / 6); + } else { + webGLData.vao.draw(gl.TRIANGLE_STRIP, webGLData.indices.length); + } + } + }; + + /** + * Updates the graphics object + * + * @private + * @param {PIXI.Graphics} graphics - The graphics object to update + */ + + + GraphicsRenderer.prototype.updateGraphics = function updateGraphics(graphics) { + var gl = this.renderer.gl; + + // get the contexts graphics object + var webGL = graphics._webGL[this.CONTEXT_UID]; + + // if the graphics object does not exist in the webGL context time to create it! + if (!webGL) { + webGL = graphics._webGL[this.CONTEXT_UID] = { lastIndex: 0, data: [], gl: gl, clearDirty: -1, dirty: -1 }; + } + + // flag the graphics as not dirty as we are about to update it... + webGL.dirty = graphics.dirty; + + // if the user cleared the graphics object we will need to clear every object + if (graphics.clearDirty !== webGL.clearDirty) { + webGL.clearDirty = graphics.clearDirty; + + // loop through and return all the webGLDatas to the object pool so than can be reused later on + for (var i = 0; i < webGL.data.length; i++) { + this.graphicsDataPool.push(webGL.data[i]); + } + + // clear the array and reset the index.. + webGL.data.length = 0; + webGL.lastIndex = 0; + } + + var webGLData = void 0; + var webGLDataNativeLines = void 0; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (var _i = webGL.lastIndex; _i < graphics.graphicsData.length; _i++) { + var data = graphics.graphicsData[_i]; + + // TODO - this can be simplified + webGLData = this.getWebGLData(webGL, 0); + + if (data.nativeLines && data.lineWidth) { + webGLDataNativeLines = this.getWebGLData(webGL, 0, true); + webGL.lastIndex++; + } + + if (data.type === _const.SHAPES.POLY) { + (0, _buildPoly2.default)(data, webGLData, webGLDataNativeLines); + } + if (data.type === _const.SHAPES.RECT) { + (0, _buildRectangle2.default)(data, webGLData, webGLDataNativeLines); + } else if (data.type === _const.SHAPES.CIRC || data.type === _const.SHAPES.ELIP) { + (0, _buildCircle2.default)(data, webGLData, webGLDataNativeLines); + } else if (data.type === _const.SHAPES.RREC) { + (0, _buildRoundedRectangle2.default)(data, webGLData, webGLDataNativeLines); + } + + webGL.lastIndex++; + } + + this.renderer.bindVao(null); + + // upload all the dirty data... + for (var _i2 = 0; _i2 < webGL.data.length; _i2++) { + webGLData = webGL.data[_i2]; + + if (webGLData.dirty) { + webGLData.upload(); + } + } + }; + + /** + * + * @private + * @param {WebGLRenderingContext} gl - the current WebGL drawing context + * @param {number} type - TODO @Alvin + * @param {number} nativeLines - indicate whether the webGLData use for nativeLines. + * @return {*} TODO + */ + + + GraphicsRenderer.prototype.getWebGLData = function getWebGLData(gl, type, nativeLines) { + var webGLData = gl.data[gl.data.length - 1]; + + if (!webGLData || webGLData.nativeLines !== nativeLines || webGLData.points.length > 320000) { + webGLData = this.graphicsDataPool.pop() || new _WebGLGraphicsData2.default(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData.nativeLines = nativeLines; + webGLData.reset(type); + gl.data.push(webGLData); + } + + webGLData.dirty = true; + + return webGLData; + }; + + return GraphicsRenderer; +}(_ObjectRenderer3.default); + +exports.default = GraphicsRenderer; + + +_WebGLRenderer2.default.registerPlugin('graphics', GraphicsRenderer); + +},{"../../const":46,"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../utils":125,"./WebGLGraphicsData":58,"./shaders/PrimitiveShader":59,"./utils/buildCircle":60,"./utils/buildPoly":62,"./utils/buildRectangle":63,"./utils/buildRoundedRectangle":64}],58:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * An object containing WebGL specific properties to be used by the WebGL renderer + * + * @class + * @private + * @memberof PIXI + */ +var WebGLGraphicsData = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {PIXI.Shader} shader - The shader + * @param {object} attribsState - The state for the VAO + */ + function WebGLGraphicsData(gl, shader, attribsState) { + _classCallCheck(this, WebGLGraphicsData); + + /** + * The current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // TODO does this need to be split before uploading?? + /** + * An array of color components (r,g,b) + * @member {number[]} + */ + this.color = [0, 0, 0]; // color split! + + /** + * An array of points to draw + * @member {PIXI.Point[]} + */ + this.points = []; + + /** + * The indices of the vertices + * @member {number[]} + */ + this.indices = []; + /** + * The main buffer + * @member {WebGLBuffer} + */ + this.buffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl); + + /** + * The index buffer + * @member {WebGLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl); + + /** + * Whether this graphics is dirty or not + * @member {boolean} + */ + this.dirty = true; + + /** + * Whether this graphics is nativeLines or not + * @member {boolean} + */ + this.nativeLines = false; + + this.glPoints = null; + this.glIndices = null; + + /** + * + * @member {PIXI.Shader} + */ + this.shader = shader; + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, attribsState).addIndex(this.indexBuffer).addAttribute(this.buffer, shader.attributes.aVertexPosition, gl.FLOAT, false, 4 * 6, 0).addAttribute(this.buffer, shader.attributes.aColor, gl.FLOAT, false, 4 * 6, 2 * 4); + } + + /** + * Resets the vertices and the indices + */ + + + WebGLGraphicsData.prototype.reset = function reset() { + this.points.length = 0; + this.indices.length = 0; + }; + + /** + * Binds the buffers and uploads the data + */ + + + WebGLGraphicsData.prototype.upload = function upload() { + this.glPoints = new Float32Array(this.points); + this.buffer.upload(this.glPoints); + + this.glIndices = new Uint16Array(this.indices); + this.indexBuffer.upload(this.glIndices); + + this.dirty = false; + }; + + /** + * Empties all the data + */ + + + WebGLGraphicsData.prototype.destroy = function destroy() { + this.color = null; + this.points = null; + this.indices = null; + + this.vao.destroy(); + this.buffer.destroy(); + this.indexBuffer.destroy(); + + this.gl = null; + + this.buffer = null; + this.indexBuffer = null; + + this.glPoints = null; + this.glIndices = null; + }; + + return WebGLGraphicsData; +}(); + +exports.default = WebGLGraphicsData; + +},{"pixi-gl-core":15}],59:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../../Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. + * + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ +var PrimitiveShader = function (_Shader) { + _inherits(PrimitiveShader, _Shader); + + /** + * @param {WebGLRenderingContext} gl - The webgl shader manager this shader works for. + */ + function PrimitiveShader(gl) { + _classCallCheck(this, PrimitiveShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec4 aColor;', 'uniform mat3 translationMatrix;', 'uniform mat3 projectionMatrix;', 'uniform float alpha;', 'uniform vec3 tint;', 'varying vec4 vColor;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vColor = aColor * vec4(tint * alpha, alpha);', '}'].join('\n'), + // fragment shader + ['varying vec4 vColor;', 'void main(void){', ' gl_FragColor = vColor;', '}'].join('\n'))); + } + + return PrimitiveShader; +}(_Shader3.default); + +exports.default = PrimitiveShader; + +},{"../../../Shader":44}],60:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildCircle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _const = require('../../../const'); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildCircle(graphicsData, webGLData, webGLDataNativeLines) { + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width = void 0; + var height = void 0; + + // TODO - bit hacky?? + if (graphicsData.type === _const.SHAPES.CIRC) { + width = circleData.radius; + height = circleData.radius; + } else { + width = circleData.width; + height = circleData.height; + } + + if (width === 0 || height === 0) { + return; + } + + var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); + + var seg = Math.PI * 2 / totalSegs; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + indices.push(vecPos); + + for (var i = 0; i < totalSegs + 1; i++) { + verts.push(x, y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos - 1); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (var _i = 0; _i < totalSegs; _i++) { + graphicsData.points.push(x + Math.sin(seg * -_i) * width, y + Math.cos(seg * -_i) * height); + } + + graphicsData.points.push(graphicsData.points[0], graphicsData.points[1]); + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +},{"../../../const":46,"../../../utils":125,"./buildLine":61}],61:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function (graphicsData, webGLData, webGLDataNativeLines) { + if (graphicsData.nativeLines) { + buildNativeLine(graphicsData, webGLDataNativeLines); + } else { + buildLine(graphicsData, webGLData); + } +}; + +var _math = require('../../../math'); + +var _utils = require('../../../utils'); + +/** + * Builds a line to draw using the poligon method. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildLine(graphicsData, webGLData) { + // TODO OPTIMISE! + var points = graphicsData.points; + + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + + // get first and last point.. figure out the middle! + var firstPoint = new _math.Point(points[0], points[1]); + var lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + // if the first point is the last point - gonna have issues :) + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var p1x = points[0]; + var p1y = points[1]; + var p2x = points[2]; + var p2y = points[3]; + var p3x = 0; + var p3y = 0; + + var perpx = -(p1y - p2y); + var perpy = p1x - p2x; + var perp2x = 0; + var perp2y = 0; + var perp3x = 0; + var perp3y = 0; + + var dist = Math.sqrt(perpx * perpx + perpy * perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + var ratio = graphicsData.lineAlignment; // 0.5; + var r1 = (1 - ratio) * 2; + var r2 = ratio * 2; + + // start + verts.push(p1x - perpx * r1, p1y - perpy * r1, r, g, b, alpha); + + verts.push(p1x + perpx * r2, p1y + perpy * r2, r, g, b, alpha); + + for (var i = 1; i < length - 1; ++i) { + p1x = points[(i - 1) * 2]; + p1y = points[(i - 1) * 2 + 1]; + + p2x = points[i * 2]; + p2y = points[i * 2 + 1]; + + p3x = points[(i + 1) * 2]; + p3y = points[(i + 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + var a1 = -perpy + p1y - (-perpy + p2y); + var b1 = -perpx + p2x - (-perpx + p1x); + var c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + var a2 = -perp2y + p3y - (-perp2y + p2y); + var b2 = -perp2x + p2x - (-perp2x + p3x); + var c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + var denom = a1 * b2 - a2 * b1; + + if (Math.abs(denom) < 0.1) { + denom += 10.1; + verts.push(p2x - perpx * r1, p2y - perpy * r1, r, g, b, alpha); + + verts.push(p2x + perpx * r2, p2y + perpy * r2, r, g, b, alpha); + + continue; + } + + var px = (b1 * c2 - b2 * c1) / denom; + var py = (a2 * c1 - a1 * c2) / denom; + var pdist = (px - p2x) * (px - p2x) + (py - p2y) * (py - p2y); + + if (pdist > 196 * width * width) { + perp3x = perpx - perp2x; + perp3y = perpy - perp2y; + + dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y); + perp3x /= dist; + perp3y /= dist; + perp3x *= width; + perp3y *= width; + + verts.push(p2x - perp3x * r1, p2y - perp3y * r1); + verts.push(r, g, b, alpha); + + verts.push(p2x + perp3x * r2, p2y + perp3y * r2); + verts.push(r, g, b, alpha); + + verts.push(p2x - perp3x * r2 * r1, p2y - perp3y * r1); + verts.push(r, g, b, alpha); + + indexCount++; + } else { + verts.push(p2x + (px - p2x) * r1, p2y + (py - p2y) * r1); + verts.push(r, g, b, alpha); + + verts.push(p2x - (px - p2x) * r2, p2y - (py - p2y) * r2); + verts.push(r, g, b, alpha); + } + } + + p1x = points[(length - 2) * 2]; + p1y = points[(length - 2) * 2 + 1]; + + p2x = points[(length - 1) * 2]; + p2y = points[(length - 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + verts.push(p2x - perpx * r1, p2y - perpy * r1); + verts.push(r, g, b, alpha); + + verts.push(p2x + perpx * r2, p2y + perpy * r2); + verts.push(r, g, b, alpha); + + indices.push(indexStart); + + for (var _i = 0; _i < indexCount; ++_i) { + indices.push(indexStart++); + } + + indices.push(indexStart - 1); +} + +/** + * Builds a line to draw using the gl.drawArrays(gl.LINES) method + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ + + +/** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildNativeLine(graphicsData, webGLData) { + var i = 0; + var points = graphicsData.points; + + if (points.length === 0) return; + + var verts = webGLData.points; + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + for (i = 1; i < length; i++) { + var p1x = points[(i - 1) * 2]; + var p1y = points[(i - 1) * 2 + 1]; + + var p2x = points[i * 2]; + var p2y = points[i * 2 + 1]; + + verts.push(p1x, p1y); + verts.push(r, g, b, alpha); + + verts.push(p2x, p2y); + verts.push(r, g, b, alpha); + } +} + +},{"../../../math":70,"../../../utils":125}],62:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildPoly; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildPoly(graphicsData, webGLData, webGLDataNativeLines) { + graphicsData.points = graphicsData.shape.points.slice(); + + var points = graphicsData.points; + + if (graphicsData.fill && points.length >= 6) { + var holeArray = []; + // Process holes.. + var holes = graphicsData.holes; + + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + + holeArray.push(points.length / 2); + + points = points.concat(hole.points); + } + + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = (0, _earcut2.default)(points, holeArray, 2); + + if (!triangles) { + return; + } + + var vertPos = verts.length / 6; + + for (var _i = 0; _i < triangles.length; _i += 3) { + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i + 1] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + } + + for (var _i2 = 0; _i2 < length; _i2++) { + verts.push(points[_i2 * 2], points[_i2 * 2 + 1], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth > 0) { + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + } +} + +},{"../../../utils":125,"./buildLine":61,"earcut":2}],63:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRectangle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildRectangle(graphicsData, webGLData, webGLDataNativeLines) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vertPos = verts.length / 6; + + // start + verts.push(x, y); + verts.push(r, g, b, alpha); + + verts.push(x + width, y); + verts.push(r, g, b, alpha); + + verts.push(x, y + height); + verts.push(r, g, b, alpha); + + verts.push(x + width, y + height); + verts.push(r, g, b, alpha); + + // insert 2 dead triangles.. + indices.push(vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y]; + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +},{"../../../utils":125,"./buildLine":61}],64:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRoundedRectangle; + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildRoundedRectangle(graphicsData, webGLData, webGLDataNativeLines) { + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + + recPoints.push(x, y + radius); + quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height, recPoints); + quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius, recPoints); + quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y, recPoints); + quadraticBezierCurve(x + radius, y, x, y, x, y + radius + 0.0000000001, recPoints); + + // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. + // TODO - fix this properly, this is not very elegant.. but it works for now. + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + var triangles = (0, _earcut2.default)(recPoints, null, 2); + + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + + for (var _i = 0, _j = recPoints.length; _i < _j; _i++) { + verts.push(recPoints[_i], recPoints[++_i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +/** + * Calculate a single point for a quadratic bezier curve. + * Utility function used by quadraticBezierCurve. + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} n1 - first number + * @param {number} n2 - second number + * @param {number} perc - percentage + * @return {number} the result + * + */ +function getPt(n1, n2, perc) { + var diff = n2 - n1; + + return n1 + diff * perc; +} + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @return {number[]} an array of points + */ +function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY) { + var out = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : []; + + var n = 20; + var points = out; + + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + + points.push(x, y); + } + + return points; +} + +},{"../../../utils":125,"./buildLine":61,"earcut":2}],65:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = exports.Application = exports.Filter = exports.SpriteMaskFilter = exports.Quad = exports.RenderTarget = exports.ObjectRenderer = exports.WebGLManager = exports.Shader = exports.CanvasRenderTarget = exports.TextureUvs = exports.VideoBaseTexture = exports.BaseRenderTexture = exports.RenderTexture = exports.BaseTexture = exports.TextureMatrix = exports.Texture = exports.Spritesheet = exports.CanvasGraphicsRenderer = exports.GraphicsRenderer = exports.GraphicsData = exports.Graphics = exports.TextMetrics = exports.TextStyle = exports.Text = exports.SpriteRenderer = exports.CanvasTinter = exports.CanvasSpriteRenderer = exports.Sprite = exports.TransformBase = exports.TransformStatic = exports.Transform = exports.Container = exports.DisplayObject = exports.Bounds = exports.glCore = exports.WebGLRenderer = exports.CanvasRenderer = exports.ticker = exports.utils = exports.settings = undefined; + +var _const = require('./const'); + +Object.keys(_const).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _const[key]; + } + }); +}); + +var _math = require('./math'); + +Object.keys(_math).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _math[key]; + } + }); +}); + +var _pixiGlCore = require('pixi-gl-core'); + +Object.defineProperty(exports, 'glCore', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_pixiGlCore).default; + } +}); + +var _Bounds = require('./display/Bounds'); + +Object.defineProperty(exports, 'Bounds', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Bounds).default; + } +}); + +var _DisplayObject = require('./display/DisplayObject'); + +Object.defineProperty(exports, 'DisplayObject', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplayObject).default; + } +}); + +var _Container = require('./display/Container'); + +Object.defineProperty(exports, 'Container', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Container).default; + } +}); + +var _Transform = require('./display/Transform'); + +Object.defineProperty(exports, 'Transform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Transform).default; + } +}); + +var _TransformStatic = require('./display/TransformStatic'); + +Object.defineProperty(exports, 'TransformStatic', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformStatic).default; + } +}); + +var _TransformBase = require('./display/TransformBase'); + +Object.defineProperty(exports, 'TransformBase', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformBase).default; + } +}); + +var _Sprite = require('./sprites/Sprite'); + +Object.defineProperty(exports, 'Sprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Sprite).default; + } +}); + +var _CanvasSpriteRenderer = require('./sprites/canvas/CanvasSpriteRenderer'); + +Object.defineProperty(exports, 'CanvasSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasSpriteRenderer).default; + } +}); + +var _CanvasTinter = require('./sprites/canvas/CanvasTinter'); + +Object.defineProperty(exports, 'CanvasTinter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasTinter).default; + } +}); + +var _SpriteRenderer = require('./sprites/webgl/SpriteRenderer'); + +Object.defineProperty(exports, 'SpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteRenderer).default; + } +}); + +var _Text = require('./text/Text'); + +Object.defineProperty(exports, 'Text', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Text).default; + } +}); + +var _TextStyle = require('./text/TextStyle'); + +Object.defineProperty(exports, 'TextStyle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextStyle).default; + } +}); + +var _TextMetrics = require('./text/TextMetrics'); + +Object.defineProperty(exports, 'TextMetrics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextMetrics).default; + } +}); + +var _Graphics = require('./graphics/Graphics'); + +Object.defineProperty(exports, 'Graphics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Graphics).default; + } +}); + +var _GraphicsData = require('./graphics/GraphicsData'); + +Object.defineProperty(exports, 'GraphicsData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsData).default; + } +}); + +var _GraphicsRenderer = require('./graphics/webgl/GraphicsRenderer'); + +Object.defineProperty(exports, 'GraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsRenderer).default; + } +}); + +var _CanvasGraphicsRenderer = require('./graphics/canvas/CanvasGraphicsRenderer'); + +Object.defineProperty(exports, 'CanvasGraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasGraphicsRenderer).default; + } +}); + +var _Spritesheet = require('./textures/Spritesheet'); + +Object.defineProperty(exports, 'Spritesheet', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Spritesheet).default; + } +}); + +var _Texture = require('./textures/Texture'); + +Object.defineProperty(exports, 'Texture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Texture).default; + } +}); + +var _TextureMatrix = require('./textures/TextureMatrix'); + +Object.defineProperty(exports, 'TextureMatrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureMatrix).default; + } +}); + +var _BaseTexture = require('./textures/BaseTexture'); + +Object.defineProperty(exports, 'BaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseTexture).default; + } +}); + +var _RenderTexture = require('./textures/RenderTexture'); + +Object.defineProperty(exports, 'RenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTexture).default; + } +}); + +var _BaseRenderTexture = require('./textures/BaseRenderTexture'); + +Object.defineProperty(exports, 'BaseRenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseRenderTexture).default; + } +}); + +var _VideoBaseTexture = require('./textures/VideoBaseTexture'); + +Object.defineProperty(exports, 'VideoBaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VideoBaseTexture).default; + } +}); + +var _TextureUvs = require('./textures/TextureUvs'); + +Object.defineProperty(exports, 'TextureUvs', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureUvs).default; + } +}); + +var _CanvasRenderTarget = require('./renderers/canvas/utils/CanvasRenderTarget'); + +Object.defineProperty(exports, 'CanvasRenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasRenderTarget).default; + } +}); + +var _Shader = require('./Shader'); + +Object.defineProperty(exports, 'Shader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Shader).default; + } +}); + +var _WebGLManager = require('./renderers/webgl/managers/WebGLManager'); + +Object.defineProperty(exports, 'WebGLManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLManager).default; + } +}); + +var _ObjectRenderer = require('./renderers/webgl/utils/ObjectRenderer'); + +Object.defineProperty(exports, 'ObjectRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObjectRenderer).default; + } +}); + +var _RenderTarget = require('./renderers/webgl/utils/RenderTarget'); + +Object.defineProperty(exports, 'RenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTarget).default; + } +}); + +var _Quad = require('./renderers/webgl/utils/Quad'); + +Object.defineProperty(exports, 'Quad', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Quad).default; + } +}); + +var _SpriteMaskFilter = require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter'); + +Object.defineProperty(exports, 'SpriteMaskFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteMaskFilter).default; + } +}); + +var _Filter = require('./renderers/webgl/filters/Filter'); + +Object.defineProperty(exports, 'Filter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Filter).default; + } +}); + +var _Application = require('./Application'); + +Object.defineProperty(exports, 'Application', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Application).default; + } +}); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +Object.defineProperty(exports, 'autoDetectRenderer', { + enumerable: true, + get: function get() { + return _autoDetectRenderer.autoDetectRenderer; + } +}); + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _ticker = require('./ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.settings = _settings2.default; +exports.utils = utils; +exports.ticker = ticker; +exports.CanvasRenderer = _CanvasRenderer2.default; +exports.WebGLRenderer = _WebGLRenderer2.default; /** + * @namespace PIXI + */ + +},{"./Application":43,"./Shader":44,"./autoDetectRenderer":45,"./const":46,"./display/Bounds":47,"./display/Container":48,"./display/DisplayObject":49,"./display/Transform":50,"./display/TransformBase":51,"./display/TransformStatic":52,"./graphics/Graphics":53,"./graphics/GraphicsData":54,"./graphics/canvas/CanvasGraphicsRenderer":55,"./graphics/webgl/GraphicsRenderer":57,"./math":70,"./renderers/canvas/CanvasRenderer":77,"./renderers/canvas/utils/CanvasRenderTarget":79,"./renderers/webgl/WebGLRenderer":84,"./renderers/webgl/filters/Filter":86,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":89,"./renderers/webgl/managers/WebGLManager":93,"./renderers/webgl/utils/ObjectRenderer":94,"./renderers/webgl/utils/Quad":95,"./renderers/webgl/utils/RenderTarget":96,"./settings":101,"./sprites/Sprite":102,"./sprites/canvas/CanvasSpriteRenderer":103,"./sprites/canvas/CanvasTinter":104,"./sprites/webgl/SpriteRenderer":106,"./text/Text":108,"./text/TextMetrics":109,"./text/TextStyle":110,"./textures/BaseRenderTexture":111,"./textures/BaseTexture":112,"./textures/RenderTexture":113,"./textures/Spritesheet":114,"./textures/Texture":115,"./textures/TextureMatrix":116,"./textures/TextureUvs":117,"./textures/VideoBaseTexture":118,"./ticker":121,"./utils":125,"pixi-gl-core":15}],66:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Matrix = require('./Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16 + +var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; +var tempMatrices = []; + +var mul = []; + +function signum(x) { + if (x < 0) { + return -1; + } + if (x > 0) { + return 1; + } + + return 0; +} + +function init() { + for (var i = 0; i < 16; i++) { + var row = []; + + mul.push(row); + + for (var j = 0; j < 16; j++) { + var _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); + var _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); + var _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); + var _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); + + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + + for (var _i = 0; _i < 16; _i++) { + var mat = new _Matrix2.default(); + + mat.set(ux[_i], uy[_i], vx[_i], vy[_i], 0, 0); + tempMatrices.push(mat); + } +} + +init(); + +/** + * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, + * D8 is the same but with diagonals. Used for texture rotations. + * + * Vector xX(i), xY(i) is U-axis of sprite with rotation i + * Vector yY(i), yY(i) is V-axis of sprite with rotation i + * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) + * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) + * This is the small part of gameofbombs.com portal system. It works. + * + * @author Ivan @ivanpopelyshev + * @class + * @memberof PIXI + */ +var GroupD8 = { + E: 0, + SE: 1, + S: 2, + SW: 3, + W: 4, + NW: 5, + N: 6, + NE: 7, + MIRROR_VERTICAL: 8, + MIRROR_HORIZONTAL: 12, + uX: function uX(ind) { + return ux[ind]; + }, + uY: function uY(ind) { + return uy[ind]; + }, + vX: function vX(ind) { + return vx[ind]; + }, + vY: function vY(ind) { + return vy[ind]; + }, + inv: function inv(rotation) { + if (rotation & 8) { + return rotation & 15; + } + + return -rotation & 7; + }, + add: function add(rotationSecond, rotationFirst) { + return mul[rotationSecond][rotationFirst]; + }, + sub: function sub(rotationSecond, rotationFirst) { + return mul[rotationSecond][GroupD8.inv(rotationFirst)]; + }, + + /** + * Adds 180 degrees to rotation. Commutative operation. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to rotate. + * @returns {number} rotated number + */ + rotate180: function rotate180(rotation) { + return rotation ^ 4; + }, + + /** + * Direction of main vector can be horizontal, vertical or diagonal. + * Some objects work with vertical directions different. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the direction is vertical + */ + isVertical: function isVertical(rotation) { + return (rotation & 3) === 2; + }, + + /** + * @memberof PIXI.GroupD8 + * @param {number} dx - TODO + * @param {number} dy - TODO + * + * @return {number} TODO + */ + byDirection: function byDirection(dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return GroupD8.S; + } + + return GroupD8.N; + } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return GroupD8.E; + } + + return GroupD8.W; + } else if (dy > 0) { + if (dx > 0) { + return GroupD8.SE; + } + + return GroupD8.SW; + } else if (dx > 0) { + return GroupD8.NE; + } + + return GroupD8.NW; + }, + + /** + * Helps sprite to compensate texture packer rotation. + * + * @memberof PIXI.GroupD8 + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {number} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function matrixAppendRotationInv(matrix, rotation) { + var tx = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var ty = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + // Packer used "rotation", we use "inv(rotation)" + var mat = tempMatrices[GroupD8.inv(rotation)]; + + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + } +}; + +exports.default = GroupD8; + +},{"./Matrix":67}],67:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Point = require('./Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The PixiJS Matrix class as an object, which makes it a lot faster, + * here is a representation of it : + * | a | c | tx| + * | b | d | ty| + * | 0 | 0 | 1 | + * + * @class + * @memberof PIXI + */ +var Matrix = function () { + /** + * @param {number} [a=1] - x scale + * @param {number} [b=0] - x skew + * @param {number} [c=0] - y skew + * @param {number} [d=1] - y scale + * @param {number} [tx=0] - x translation + * @param {number} [ty=0] - y translation + */ + function Matrix() { + var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var d = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var tx = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var ty = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + + _classCallCheck(this, Matrix); + + /** + * @member {number} + * @default 1 + */ + this.a = a; + + /** + * @member {number} + * @default 0 + */ + this.b = b; + + /** + * @member {number} + * @default 0 + */ + this.c = c; + + /** + * @member {number} + * @default 1 + */ + this.d = d; + + /** + * @member {number} + * @default 0 + */ + this.tx = tx; + + /** + * @member {number} + * @default 0 + */ + this.ty = ty; + + this.array = null; + } + + /** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @param {number[]} array - The array that the matrix will be populated from. + */ + + + Matrix.prototype.fromArray = function fromArray(array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + }; + + /** + * sets the matrix properties + * + * @param {number} a - Matrix component + * @param {number} b - Matrix component + * @param {number} c - Matrix component + * @param {number} d - Matrix component + * @param {number} tx - Matrix component + * @param {number} ty - Matrix component + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.set = function set(a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + }; + + /** + * Creates an array from the current Matrix object. + * + * @param {boolean} transpose - Whether we need to transpose the matrix or not + * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out + * @return {number[]} the newly created array which contains the matrix + */ + + + Matrix.prototype.toArray = function toArray(transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + + var array = out || this.array; + + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + }; + + /** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, transformed through this matrix + */ + + + Matrix.prototype.apply = function apply(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; + + return newPos; + }; + + /** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, inverse-transformed through this matrix + */ + + + Matrix.prototype.applyInverse = function applyInverse(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var id = 1 / (this.a * this.d + this.c * -this.b); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + }; + + /** + * Translates the matrix on the x and y. + * + * @param {number} x How much to translate x by + * @param {number} y How much to translate y by + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.translate = function translate(x, y) { + this.tx += x; + this.ty += y; + + return this; + }; + + /** + * Applies a scale transformation to the matrix. + * + * @param {number} x The amount to scale horizontally + * @param {number} y The amount to scale vertically + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.scale = function scale(x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + }; + + /** + * Applies a rotation transformation to the matrix. + * + * @param {number} angle - The angle in radians. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.rotate = function rotate(angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos - this.b * sin; + this.b = a1 * sin + this.b * cos; + this.c = c1 * cos - this.d * sin; + this.d = c1 * sin + this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + }; + + /** + * Appends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to append. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.append = function append(matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + }; + + /** + * Sets the matrix based on all the available properties + * + * @param {number} x - Position on the x axis + * @param {number} y - Position on the y axis + * @param {number} pivotX - Pivot on the x axis + * @param {number} pivotY - Pivot on the y axis + * @param {number} scaleX - Scale on the x axis + * @param {number} scaleY - Scale on the y axis + * @param {number} rotation - Rotation in radians + * @param {number} skewX - Skew on the x axis + * @param {number} skewY - Skew on the y axis + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.setTransform = function setTransform(x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + this.a = Math.cos(rotation + skewY) * scaleX; + this.b = Math.sin(rotation + skewY) * scaleX; + this.c = -Math.sin(rotation - skewX) * scaleY; + this.d = Math.cos(rotation - skewX) * scaleY; + + this.tx = x - (pivotX * this.a + pivotY * this.c); + this.ty = y - (pivotX * this.b + pivotY * this.d); + + return this; + }; + + /** + * Prepends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to prepend + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.prepend = function prepend(matrix) { + var tx1 = this.tx; + + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + + this.a = a1 * matrix.a + this.b * matrix.c; + this.b = a1 * matrix.b + this.b * matrix.d; + this.c = c1 * matrix.a + this.d * matrix.c; + this.d = c1 * matrix.b + this.d * matrix.d; + } + + this.tx = tx1 * matrix.a + this.ty * matrix.c + matrix.tx; + this.ty = tx1 * matrix.b + this.ty * matrix.d + matrix.ty; + + return this; + }; + + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * + * @param {PIXI.Transform|PIXI.TransformStatic} transform - The transform to apply the properties to. + * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properties + */ + + + Matrix.prototype.decompose = function decompose(transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + + var skewX = -Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + + var delta = Math.abs(skewX + skewY); + + if (delta < 0.00001 || Math.abs(_const.PI_2 - delta) < 0.00001) { + transform.rotation = skewY; + + if (a < 0 && d >= 0) { + transform.rotation += transform.rotation <= 0 ? Math.PI : -Math.PI; + } + + transform.skew.x = transform.skew.y = 0; + } else { + transform.rotation = 0; + transform.skew.x = skewX; + transform.skew.y = skewY; + } + + // next set scale + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); + + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; + + return transform; + }; + + /** + * Inverts this matrix + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.invert = function invert() { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1 * d1 - b1 * c1; + + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = (c1 * this.ty - d1 * tx1) / n; + this.ty = -(a1 * this.ty - b1 * tx1) / n; + + return this; + }; + + /** + * Resets this Matix to an identity (default) matrix. + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.identity = function identity() { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + + return this; + }; + + /** + * Creates a new Matrix object with the same values as this one. + * + * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. + */ + + + Matrix.prototype.clone = function clone() { + var matrix = new Matrix(); + + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * Changes the values of the given matrix to be the same as the ones in this matrix + * + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @return {PIXI.Matrix} The matrix given in parameter with its values updated. + */ + + + Matrix.prototype.copy = function copy(matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * A default (identity) matrix + * + * @static + * @const + */ + + + _createClass(Matrix, null, [{ + key: 'IDENTITY', + get: function get() { + return new Matrix(); + } + + /** + * A temp matrix + * + * @static + * @const + */ + + }, { + key: 'TEMP_MATRIX', + get: function get() { + return new Matrix(); + } + }]); + + return Matrix; +}(); + +exports.default = Matrix; + +},{"../const":46,"./Point":69}],68:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * An observable point is a point that triggers a callback when the point's position is changed. + * + * @class + * @memberof PIXI + */ +var ObservablePoint = function () { + /** + * @param {Function} cb - callback when changed + * @param {object} scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope) { + var x = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var y = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, ObservablePoint); + + this._x = x; + this._y = y; + + this.cb = cb; + this.scope = scope; + } + + /** + * Creates a clone of this point. + * The callback and scope params can be overidden otherwise they will default + * to the clone object's values. + * + * @override + * @param {Function} [cb=null] - callback when changed + * @param {object} [scope=null] - owner of callback + * @return {PIXI.ObservablePoint} a copy of the point + */ + + + ObservablePoint.prototype.clone = function clone() { + var cb = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + + var _cb = cb || this.cb; + var _scope = scope || this.scope; + + return new ObservablePoint(_cb, _scope, this._x, this._y); + }; + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + ObservablePoint.prototype.set = function set(x, y) { + var _x = x || 0; + var _y = y || (y !== 0 ? _x : 0); + + if (this._x !== _x || this._y !== _y) { + this._x = _x; + this._y = _y; + this.cb.call(this.scope); + } + }; + + /** + * Copies the data from another point + * + * @param {PIXI.Point|PIXI.ObservablePoint} point - point to copy from + */ + + + ObservablePoint.prototype.copy = function copy(point) { + if (this._x !== point.x || this._y !== point.y) { + this._x = point.x; + this._y = point.y; + this.cb.call(this.scope); + } + }; + + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.Point|PIXI.ObservablePoint} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + + + ObservablePoint.prototype.equals = function equals(p) { + return p.x === this._x && p.y === this._y; + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + + _createClass(ObservablePoint, [{ + key: "x", + get: function get() { + return this._x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + } + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + }, { + key: "y", + get: function get() { + return this._y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + } + }]); + + return ObservablePoint; +}(); + +exports.default = ObservablePoint; + +},{}],69:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * + * @class + * @memberof PIXI + */ +var Point = function () { + /** + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function Point() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + + _classCallCheck(this, Point); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + } + + /** + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point + */ + + + Point.prototype.clone = function clone() { + return new Point(this.x, this.y); + }; + + /** + * Copies x and y from the given point + * + * @param {PIXI.Point} p - The point to copy. + */ + + + Point.prototype.copy = function copy(p) { + this.set(p.x, p.y); + }; + + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.Point} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + + + Point.prototype.equals = function equals(p) { + return p.x === this.x && p.y === this.y; + }; + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + Point.prototype.set = function set(x, y) { + this.x = x || 0; + this.y = y || (y !== 0 ? this.x : 0); + }; + + return Point; +}(); + +exports.default = Point; + +},{}],70:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('./Point'); + +Object.defineProperty(exports, 'Point', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Point).default; + } +}); + +var _ObservablePoint = require('./ObservablePoint'); + +Object.defineProperty(exports, 'ObservablePoint', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObservablePoint).default; + } +}); + +var _Matrix = require('./Matrix'); + +Object.defineProperty(exports, 'Matrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Matrix).default; + } +}); + +var _GroupD = require('./GroupD8'); + +Object.defineProperty(exports, 'GroupD8', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GroupD).default; + } +}); + +var _Circle = require('./shapes/Circle'); + +Object.defineProperty(exports, 'Circle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Circle).default; + } +}); + +var _Ellipse = require('./shapes/Ellipse'); + +Object.defineProperty(exports, 'Ellipse', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Ellipse).default; + } +}); + +var _Polygon = require('./shapes/Polygon'); + +Object.defineProperty(exports, 'Polygon', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Polygon).default; + } +}); + +var _Rectangle = require('./shapes/Rectangle'); + +Object.defineProperty(exports, 'Rectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rectangle).default; + } +}); + +var _RoundedRectangle = require('./shapes/RoundedRectangle'); + +Object.defineProperty(exports, 'RoundedRectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RoundedRectangle).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./GroupD8":66,"./Matrix":67,"./ObservablePoint":68,"./Point":69,"./shapes/Circle":71,"./shapes/Ellipse":72,"./shapes/Polygon":73,"./shapes/Rectangle":74,"./shapes/RoundedRectangle":75}],71:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Circle object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Circle = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [radius=0] - The radius of the circle + */ + function Circle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var radius = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + _classCallCheck(this, Circle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.CIRC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.CIRC; + } + + /** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ + + + Circle.prototype.clone = function clone() { + return new Circle(this.x, this.y, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this circle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Circle + */ + + + Circle.prototype.contains = function contains(x, y) { + if (this.radius <= 0) { + return false; + } + + var r2 = this.radius * this.radius; + var dx = this.x - x; + var dy = this.y - y; + + dx *= dx; + dy *= dy; + + return dx + dy <= r2; + }; + + /** + * Returns the framing rectangle of the circle as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Circle.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + + return Circle; +}(); + +exports.default = Circle; + +},{"../../const":46,"./Rectangle":74}],72:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Ellipse object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Ellipse = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [width=0] - The half width of this ellipse + * @param {number} [height=0] - The half height of this ellipse + */ + function Ellipse() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Ellipse); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.ELIP + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.ELIP; + } + + /** + * Creates a clone of this Ellipse instance + * + * @return {PIXI.Ellipse} a copy of the ellipse + */ + + + Ellipse.prototype.clone = function clone() { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coords are within this ellipse + */ + + + Ellipse.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + // normalize the coords to an ellipse with center 0,0 + var normx = (x - this.x) / this.width; + var normy = (y - this.y) / this.height; + + normx *= normx; + normy *= normy; + + return normx + normy <= 1; + }; + + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Ellipse.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.width, this.y - this.height, this.width, this.height); + }; + + return Ellipse; +}(); + +exports.default = Ellipse; + +},{"../../const":46,"./Rectangle":74}],73:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('../Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Polygon = function () { + /** + * @param {PIXI.Point[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + for (var _len = arguments.length, points = Array(_len), _key = 0; _key < _len; _key++) { + points[_key] = arguments[_key]; + } + + _classCallCheck(this, Polygon); + + if (Array.isArray(points[0])) { + points = points[0]; + } + + // if this is an array of points, convert it to a flat array of numbers + if (points[0] instanceof _Point2.default) { + var p = []; + + for (var i = 0, il = points.length; i < il; i++) { + p.push(points[i].x, points[i].y); + } + + points = p; + } + + this.closed = true; + + /** + * An array of the points of this polygon + * + * @member {number[]} + */ + this.points = points; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.POLY + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.POLY; + } + + /** + * Creates a clone of this polygon + * + * @return {PIXI.Polygon} a copy of the polygon + */ + + + Polygon.prototype.clone = function clone() { + return new Polygon(this.points.slice()); + }; + + /** + * Closes the polygon, adding points if necessary. + * + */ + + + Polygon.prototype.close = function close() { + var points = this.points; + + // close the poly if the value is true! + if (points[0] !== points[points.length - 2] || points[1] !== points[points.length - 1]) { + points.push(points[0], points[1]); + } + }; + + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this polygon + */ + + + Polygon.prototype.contains = function contains(x, y) { + var inside = false; + + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + + for (var i = 0, j = length - 1; i < length; j = i++) { + var xi = this.points[i * 2]; + var yi = this.points[i * 2 + 1]; + var xj = this.points[j * 2]; + var yj = this.points[j * 2 + 1]; + var intersect = yi > y !== yj > y && x < (xj - xi) * ((y - yi) / (yj - yi)) + xi; + + if (intersect) { + inside = !inside; + } + } + + return inside; + }; + + return Polygon; +}(); + +exports.default = Polygon; + +},{"../../const":46,"../Point":69}],74:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * + * @class + * @memberof PIXI + */ +var Rectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle + * @param {number} [width=0] - The overall width of this rectangle + * @param {number} [height=0] - The overall height of this rectangle + */ + function Rectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Rectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = Number(x); + + /** + * @member {number} + * @default 0 + */ + this.y = Number(y); + + /** + * @member {number} + * @default 0 + */ + this.width = Number(width); + + /** + * @member {number} + * @default 0 + */ + this.height = Number(height); + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.RECT + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RECT; + } + + /** + * returns the left edge of the rectangle + * + * @member {number} + */ + + + /** + * Creates a clone of this Rectangle + * + * @return {PIXI.Rectangle} a copy of the rectangle + */ + Rectangle.prototype.clone = function clone() { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + + /** + * Copies another rectangle to this one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to copy. + * @return {PIXI.Rectangle} Returns itself. + */ + + + Rectangle.prototype.copy = function copy(rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + + return this; + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rectangle + */ + + + Rectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + + return false; + }; + + /** + * Pads the rectangle making it grow in all directions. + * + * @param {number} paddingX - The horizontal padding amount. + * @param {number} [paddingY] - The vertical padding amount. + */ + + + Rectangle.prototype.pad = function pad(paddingX, paddingY) { + paddingX = paddingX || 0; + paddingY = paddingY || (paddingY !== 0 ? paddingX : 0); + + this.x -= paddingX; + this.y -= paddingY; + + this.width += paddingX * 2; + this.height += paddingY * 2; + }; + + /** + * Fits this rectangle around the passed one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to fit. + */ + + + Rectangle.prototype.fit = function fit(rectangle) { + if (this.x < rectangle.x) { + this.width += this.x; + if (this.width < 0) { + this.width = 0; + } + + this.x = rectangle.x; + } + + if (this.y < rectangle.y) { + this.height += this.y; + if (this.height < 0) { + this.height = 0; + } + this.y = rectangle.y; + } + + if (this.x + this.width > rectangle.x + rectangle.width) { + this.width = rectangle.width - this.x; + if (this.width < 0) { + this.width = 0; + } + } + + if (this.y + this.height > rectangle.y + rectangle.height) { + this.height = rectangle.height - this.y; + if (this.height < 0) { + this.height = 0; + } + } + }; + + /** + * Enlarges this rectangle to include the passed rectangle. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to include. + */ + + + Rectangle.prototype.enlarge = function enlarge(rectangle) { + var x1 = Math.min(this.x, rectangle.x); + var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.min(this.y, rectangle.y); + var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); + + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + }; + + _createClass(Rectangle, [{ + key: 'left', + get: function get() { + return this.x; + } + + /** + * returns the right edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'right', + get: function get() { + return this.x + this.width; + } + + /** + * returns the top edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'top', + get: function get() { + return this.y; + } + + /** + * returns the bottom edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'bottom', + get: function get() { + return this.y + this.height; + } + + /** + * A constant empty rectangle. + * + * @static + * @constant + */ + + }], [{ + key: 'EMPTY', + get: function get() { + return new Rectangle(0, 0, 0, 0); + } + }]); + + return Rectangle; +}(); + +exports.default = Rectangle; + +},{"../../const":46}],75:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. + * + * @class + * @memberof PIXI + */ +var RoundedRectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle + * @param {number} [width=0] - The overall width of this rounded rectangle + * @param {number} [height=0] - The overall height of this rounded rectangle + * @param {number} [radius=20] - Controls the radius of the rounded corners + */ + function RoundedRectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var radius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 20; + + _classCallCheck(this, RoundedRectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * @member {number} + * @default 20 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readonly + * @default PIXI.SHAPES.RREC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RREC; + } + + /** + * Creates a clone of this Rounded Rectangle + * + * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle + */ + + + RoundedRectangle.prototype.clone = function clone() { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + */ + + + RoundedRectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + if (y >= this.y + this.radius && y <= this.y + this.height - this.radius || x >= this.x + this.radius && x <= this.x + this.width - this.radius) { + return true; + } + var dx = x - (this.x + this.radius); + var dy = y - (this.y + this.radius); + var radius2 = this.radius * this.radius; + + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.width - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dy = y - (this.y + this.height - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + } + } + + return false; + }; + + return RoundedRectangle; +}(); + +exports.default = RoundedRectangle; + +},{"../../const":46}],76:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _math = require('../math'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _Container = require('../display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMatrix = new _math.Matrix(); + +/** + * The SystemRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.WebGLRenderer} which can be used for rendering a PixiJS scene. + * + * @abstract + * @class + * @extends EventEmitter + * @memberof PIXI + */ + +var SystemRenderer = function (_EventEmitter) { + _inherits(SystemRenderer, _EventEmitter); + + // eslint-disable-next-line valid-jsdoc + /** + * @param {string} system - The name of the system this renderer is for. + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function SystemRenderer(system, options, arg2, arg3) { + _classCallCheck(this, SystemRenderer); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + (0, _utils.sayHello)(system); + + // Support for constructor(system, screenWidth, screenHeight, options) + if (typeof options === 'number') { + options = Object.assign({ + width: options, + height: arg2 || _settings2.default.RENDER_OPTIONS.height + }, arg3); + } + + // Add the default render options + options = Object.assign({}, _settings2.default.RENDER_OPTIONS, options); + + /** + * The supplied constructor options. + * + * @member {Object} + * @readOnly + */ + _this.options = options; + + /** + * The type of the renderer. + * + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.UNKNOWN; + + /** + * Measurements of the screen. (0, 0, screenWidth, screenHeight) + * + * Its safe to use as filterArea or hitArea for whole stage + * + * @member {PIXI.Rectangle} + */ + _this.screen = new _math.Rectangle(0, 0, options.width, options.height); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.view = options.view || document.createElement('canvas'); + + /** + * The resolution / device pixel ratio of the renderer + * + * @member {number} + * @default 1 + */ + _this.resolution = options.resolution || _settings2.default.RESOLUTION; + + /** + * Whether the render view is transparent + * + * @member {boolean} + */ + _this.transparent = options.transparent; + + /** + * Whether css dimensions of canvas view should be resized to screen dimensions automatically + * + * @member {boolean} + */ + _this.autoResize = options.autoResize || false; + + /** + * Tracks the blend modes useful for this renderer. + * + * @member {object} + */ + _this.blendModes = null; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example if + * your game has a canvas filling background image you often don't need this set. + * + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + * + * @member {boolean} + */ + _this.roundPixels = options.roundPixels; + + /** + * The background color as a number. + * + * @member {number} + * @private + */ + _this._backgroundColor = 0x000000; + + /** + * The background color as an [R, G, B] array. + * + * @member {number[]} + * @private + */ + _this._backgroundColorRgba = [0, 0, 0, 0]; + + /** + * The background color as a string. + * + * @member {string} + * @private + */ + _this._backgroundColorString = '#000000'; + + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + + /** + * This temporary display object used as the parent of the currently being rendered item + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._tempDisplayObjectParent = new _Container2.default(); + + /** + * The last root object that the renderer tried to render. + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._lastObjectRendered = _this._tempDisplayObjectParent; + return _this; + } + + /** + * Same as view.width, actual number of pixels in the canvas by horizontal + * + * @member {number} + * @readonly + * @default 800 + */ + + + /** + * Resizes the screen and canvas to the specified width and height + * Canvas dimensions are multiplied by resolution + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + SystemRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + this.screen.width = screenWidth; + this.screen.height = screenHeight; + + this.view.width = screenWidth * this.resolution; + this.view.height = screenHeight * this.resolution; + + if (this.autoResize) { + this.view.style.width = screenWidth + 'px'; + this.view.style.height = screenHeight + 'px'; + } + }; + + /** + * Useful function that returns a texture of the display object that can then be used to create sprites + * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. + * + * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from + * @param {number} scaleMode - Should be one of the scaleMode consts + * @param {number} resolution - The resolution / device pixel ratio of the texture being generated + * @param {PIXI.Rectangle} [region] - The region of the displayObject, that shall be rendered, + * if no region is specified, defaults to the local bounds of the displayObject. + * @return {PIXI.Texture} a texture of the graphics object + */ + + + SystemRenderer.prototype.generateTexture = function generateTexture(displayObject, scaleMode, resolution, region) { + region = region || displayObject.getLocalBounds(); + + var renderTexture = _RenderTexture2.default.create(region.width | 0, region.height | 0, scaleMode, resolution); + + tempMatrix.tx = -region.x; + tempMatrix.ty = -region.y; + + this.render(displayObject, renderTexture, false, tempMatrix, !!displayObject.parent); + + return renderTexture; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + SystemRenderer.prototype.destroy = function destroy(removeView) { + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } + + this.type = _const.RENDERER_TYPE.UNKNOWN; + + this.view = null; + + this.screen = null; + + this.resolution = 0; + + this.transparent = false; + + this.autoResize = false; + + this.blendModes = null; + + this.options = null; + + this.preserveDrawingBuffer = false; + this.clearBeforeRender = false; + + this.roundPixels = false; + + this._backgroundColor = 0; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + + this._tempDisplayObjectParent = null; + this._lastObjectRendered = null; + }; + + /** + * The background color to fill if not transparent + * + * @member {number} + */ + + + _createClass(SystemRenderer, [{ + key: 'width', + get: function get() { + return this.view.width; + } + + /** + * Same as view.height, actual number of pixels in the canvas by vertical + * + * @member {number} + * @readonly + * @default 600 + */ + + }, { + key: 'height', + get: function get() { + return this.view.height; + } + }, { + key: 'backgroundColor', + get: function get() { + return this._backgroundColor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._backgroundColor = value; + this._backgroundColorString = (0, _utils.hex2string)(value); + (0, _utils.hex2rgb)(value, this._backgroundColorRgba); + } + }]); + + return SystemRenderer; +}(_eventemitter2.default); + +exports.default = SystemRenderer; + +},{"../const":46,"../display/Container":48,"../math":70,"../settings":101,"../textures/RenderTexture":113,"../utils":125,"eventemitter3":3}],77:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _CanvasMaskManager = require('./utils/CanvasMaskManager'); + +var _CanvasMaskManager2 = _interopRequireDefault(_CanvasMaskManager); + +var _CanvasRenderTarget = require('./utils/CanvasRenderTarget'); + +var _CanvasRenderTarget2 = _interopRequireDefault(_CanvasRenderTarget); + +var _mapCanvasBlendModesToPixi = require('./utils/mapCanvasBlendModesToPixi'); + +var _mapCanvasBlendModesToPixi2 = _interopRequireDefault(_mapCanvasBlendModesToPixi); + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should + * be used for browsers that do not support WebGL. Don't forget to add the CanvasRenderer.view to + * your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ +var CanvasRenderer = function (_SystemRenderer) { + _inherits(CanvasRenderer, _SystemRenderer); + + // eslint-disable-next-line valid-jsdoc + /** + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function CanvasRenderer(options, arg2, arg3) { + _classCallCheck(this, CanvasRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'Canvas', options, arg2, arg3)); + + _this.type = _const.RENDERER_TYPE.CANVAS; + + /** + * The root canvas 2d context that everything is drawn with. + * + * @member {CanvasRenderingContext2D} + */ + _this.rootContext = _this.view.getContext('2d', { alpha: _this.transparent }); + + /** + * The currently active canvas 2d context (could change with renderTextures) + * + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.rootContext; + + /** + * Boolean flag controlling canvas refresh. + * + * @member {boolean} + */ + _this.refresh = true; + + /** + * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. + * + * @member {PIXI.CanvasMaskManager} + */ + _this.maskManager = new _CanvasMaskManager2.default(_this); + + /** + * The canvas property used to set the canvas smoothing property. + * + * @member {string} + */ + _this.smoothProperty = 'imageSmoothingEnabled'; + + if (!_this.rootContext.imageSmoothingEnabled) { + if (_this.rootContext.webkitImageSmoothingEnabled) { + _this.smoothProperty = 'webkitImageSmoothingEnabled'; + } else if (_this.rootContext.mozImageSmoothingEnabled) { + _this.smoothProperty = 'mozImageSmoothingEnabled'; + } else if (_this.rootContext.oImageSmoothingEnabled) { + _this.smoothProperty = 'oImageSmoothingEnabled'; + } else if (_this.rootContext.msImageSmoothingEnabled) { + _this.smoothProperty = 'msImageSmoothingEnabled'; + } + } + + _this.initPlugins(); + + _this.blendModes = (0, _mapCanvasBlendModesToPixi2.default)(); + _this._activeBlendMode = null; + + _this.renderingToScreen = false; + + _this.resize(_this.options.width, _this.options.height); + + /** + * Fired after rendering finishes. + * + * @event PIXI.CanvasRenderer#postrender + */ + + /** + * Fired before rendering starts. + * + * @event PIXI.CanvasRenderer#prerender + */ + return _this; + } + + /** + * Renders the object to this canvas view + * + * @param {PIXI.DisplayObject} displayObject - The object to be rendered + * @param {PIXI.RenderTexture} [renderTexture] - A render texture to be rendered to. + * If unset, it will render to the root context. + * @param {boolean} [clear=false] - Whether to clear the canvas before drawing + * @param {PIXI.Matrix} [transform] - A transformation to be applied + * @param {boolean} [skipUpdateTransform=false] - Whether to skip the update transform + */ + + + CanvasRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!this.view) { + return; + } + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + var rootResolution = this.resolution; + + if (renderTexture) { + renderTexture = renderTexture.baseTexture || renderTexture; + + if (!renderTexture._canvasRenderTarget) { + renderTexture._canvasRenderTarget = new _CanvasRenderTarget2.default(renderTexture.width, renderTexture.height, renderTexture.resolution); + renderTexture.source = renderTexture._canvasRenderTarget.canvas; + renderTexture.valid = true; + } + + this.context = renderTexture._canvasRenderTarget.context; + this.resolution = renderTexture._canvasRenderTarget.resolution; + } else { + this.context = this.rootContext; + } + + var context = this.context; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + var tempWt = this._tempDisplayObjectParent.transform.worldTransform; + + if (transform) { + transform.copy(tempWt); + + // lets not forget to flag the parent transform as dirty... + this._tempDisplayObjectParent.transform._worldID = -1; + } else { + tempWt.identity(); + } + + displayObject.parent = this._tempDisplayObjectParent; + + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + context.save(); + context.setTransform(1, 0, 0, 1, 0, 0); + context.globalAlpha = 1; + this._activeBlendMode = _const.BLEND_MODES.NORMAL; + context.globalCompositeOperation = this.blendModes[_const.BLEND_MODES.NORMAL]; + + if (navigator.isCocoonJS && this.view.screencanvas) { + context.fillStyle = 'black'; + context.clear(); + } + + if (clear !== undefined ? clear : this.clearBeforeRender) { + if (this.renderingToScreen) { + if (this.transparent) { + context.clearRect(0, 0, this.width, this.height); + } else { + context.fillStyle = this._backgroundColorString; + context.fillRect(0, 0, this.width, this.height); + } + } // else { + // TODO: implement background for CanvasRenderTarget or RenderTexture? + // } + } + + // TODO RENDER TARGET STUFF HERE.. + var tempContext = this.context; + + this.context = context; + displayObject.renderCanvas(this); + this.context = tempContext; + + context.restore(); + + this.resolution = rootResolution; + + this.emit('postrender'); + }; + + /** + * Clear the canvas of renderer. + * + * @param {string} [clearColor] - Clear the canvas with this color, except the canvas is transparent. + */ + + + CanvasRenderer.prototype.clear = function clear(clearColor) { + var context = this.context; + + clearColor = clearColor || this._backgroundColorString; + + if (!this.transparent && clearColor) { + context.fillStyle = clearColor; + context.fillRect(0, 0, this.width, this.height); + } else { + context.clearRect(0, 0, this.width, this.height); + } + }; + + /** + * Sets the blend mode of the renderer. + * + * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values. + */ + + + CanvasRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + if (this._activeBlendMode === blendMode) { + return; + } + + this._activeBlendMode = blendMode; + this.context.globalCompositeOperation = this.blendModes[blendMode]; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + CanvasRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // call the base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.context = null; + + this.refresh = true; + + this.maskManager.destroy(); + this.maskManager = null; + + this.smoothProperty = null; + }; + + /** + * Resizes the canvas view to the specified width and height. + * + * @extends PIXI.SystemRenderer#resize + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + CanvasRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + _SystemRenderer.prototype.resize.call(this, screenWidth, screenHeight); + + // reset the scale mode.. oddly this seems to be reset when the canvas is resized. + // surely a browser bug?? Let PixiJS fix that for you.. + if (this.smoothProperty) { + this.rootContext[this.smoothProperty] = _settings2.default.SCALE_MODE === _const.SCALE_MODES.LINEAR; + } + }; + + /** + * Checks if blend mode has changed. + */ + + + CanvasRenderer.prototype.invalidateBlendMode = function invalidateBlendMode() { + this._activeBlendMode = this.blendModes.indexOf(this.context.globalCompositeOperation); + }; + + return CanvasRenderer; +}(_SystemRenderer3.default); + +/** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @name PIXI.CanvasRenderer#plugins + * @type {object} + * @readonly + * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.extract.CanvasExtract} extract Extract image data from renderer. + * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.prepare.CanvasPrepare} prepare Pre-render display objects. + */ + +/** + * Adds a plugin to the renderer. + * + * @method PIXI.CanvasRenderer#registerPlugin + * @param {string} pluginName - The name of the plugin. + * @param {Function} ctor - The constructor function or class for the plugin. + */ + +exports.default = CanvasRenderer; +_utils.pluginTarget.mixin(CanvasRenderer); + +},{"../../const":46,"../../settings":101,"../../utils":125,"../SystemRenderer":76,"./utils/CanvasMaskManager":78,"./utils/CanvasRenderTarget":79,"./utils/mapCanvasBlendModesToPixi":81}],78:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A set of functions used to handle masking. + * + * @class + * @memberof PIXI + */ +var CanvasMaskManager = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + function CanvasMaskManager(renderer) { + _classCallCheck(this, CanvasMaskManager); + + this.renderer = renderer; + } + + /** + * This method adds it to the current stack of masks. + * + * @param {object} maskData - the maskData that will be pushed + */ + + + CanvasMaskManager.prototype.pushMask = function pushMask(maskData) { + var renderer = this.renderer; + + renderer.context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.transform.worldTransform; + var resolution = renderer.resolution; + + renderer.context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // TODO suport sprite alpha masks?? + // lots of effort required. If demand is great enough.. + if (!maskData._texture) { + this.renderGraphicsShape(maskData); + renderer.context.clip(); + } + + maskData.worldAlpha = cacheAlpha; + }; + + /** + * Renders a PIXI.Graphics shape. + * + * @param {PIXI.Graphics} graphics - The object to render. + */ + + + CanvasMaskManager.prototype.renderGraphicsShape = function renderGraphicsShape(graphics) { + var context = this.renderer.context; + var len = graphics.graphicsData.length; + + if (len === 0) { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === _const.SHAPES.POLY) { + var points = shape.points; + + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; j++) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) { + context.closePath(); + } + } else if (data.type === _const.SHAPES.RECT) { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } + }; + + /** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @param {PIXI.CanvasRenderer} renderer - The renderer context to use. + */ + + + CanvasMaskManager.prototype.popMask = function popMask(renderer) { + renderer.context.restore(); + renderer.invalidateBlendMode(); + }; + + /** + * Destroys this canvas mask manager. + * + */ + + + CanvasMaskManager.prototype.destroy = function destroy() { + /* empty */ + }; + + return CanvasMaskManager; +}(); + +exports.default = CanvasMaskManager; + +},{"../../../const":46}],79:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Creates a Canvas element of the given size. + * + * @class + * @memberof PIXI + */ +var CanvasRenderTarget = function () { + /** + * @param {number} width - the width for the newly created canvas + * @param {number} height - the height for the newly created canvas + * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + _classCallCheck(this, CanvasRenderTarget); + + /** + * The Canvas object that belongs to this CanvasRenderTarget. + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @member {CanvasRenderingContext2D} + */ + this.context = this.canvas.getContext('2d'); + + this.resolution = resolution || _settings2.default.RESOLUTION; + + this.resize(width, height); + } + + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * + * @private + */ + + + CanvasRenderTarget.prototype.clear = function clear() { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + + /** + * Resizes the canvas to the specified width and height. + * + * @param {number} width - the new width of the canvas + * @param {number} height - the new height of the canvas + */ + + + CanvasRenderTarget.prototype.resize = function resize(width, height) { + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; + }; + + /** + * Destroys this canvas. + * + */ + + + CanvasRenderTarget.prototype.destroy = function destroy() { + this.context = null; + this.canvas = null; + }; + + /** + * The width of the canvas buffer in pixels. + * + * @member {number} + */ + + + _createClass(CanvasRenderTarget, [{ + key: 'width', + get: function get() { + return this.canvas.width; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.width = val; + } + + /** + * The height of the canvas buffer in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.canvas.height; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.height = val; + } + }]); + + return CanvasRenderTarget; +}(); + +exports.default = CanvasRenderTarget; + +},{"../../../settings":101}],80:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = canUseNewCanvasBlendModes; +/** + * Creates a little colored canvas + * + * @ignore + * @param {string} color - The color to make the canvas + * @return {canvas} a small canvas element + */ +function createColoredCanvas(color) { + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.fillStyle = color; + context.fillRect(0, 0, 6, 1); + + return canvas; +} + +/** + * Checks whether the Canvas BlendModes are supported by the current browser + * + * @return {boolean} whether they are supported + */ +function canUseNewCanvasBlendModes() { + if (typeof document === 'undefined') { + return false; + } + + var magenta = createColoredCanvas('#ff00ff'); + var yellow = createColoredCanvas('#ffff00'); + + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.globalCompositeOperation = 'multiply'; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + var imageData = context.getImageData(2, 0, 1, 1); + + if (!imageData) { + return false; + } + + var data = imageData.data; + + return data[0] === 255 && data[1] === 0 && data[2] === 0; +} + +},{}],81:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapCanvasBlendModesToPixi; + +var _const = require('../../../const'); + +var _canUseNewCanvasBlendModes = require('./canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Maps blend combinations to Canvas. + * + * @memberof PIXI + * @function mapCanvasBlendModesToPixi + * @private + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapCanvasBlendModesToPixi() { + var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + + if ((0, _canUseNewCanvasBlendModes2.default)()) { + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'multiply'; + array[_const.BLEND_MODES.SCREEN] = 'screen'; + array[_const.BLEND_MODES.OVERLAY] = 'overlay'; + array[_const.BLEND_MODES.DARKEN] = 'darken'; + array[_const.BLEND_MODES.LIGHTEN] = 'lighten'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'color-dodge'; + array[_const.BLEND_MODES.COLOR_BURN] = 'color-burn'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'hard-light'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'soft-light'; + array[_const.BLEND_MODES.DIFFERENCE] = 'difference'; + array[_const.BLEND_MODES.EXCLUSION] = 'exclusion'; + array[_const.BLEND_MODES.HUE] = 'hue'; + array[_const.BLEND_MODES.SATURATION] = 'saturate'; + array[_const.BLEND_MODES.COLOR] = 'color'; + array[_const.BLEND_MODES.LUMINOSITY] = 'luminosity'; + } else { + // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'source-over'; + array[_const.BLEND_MODES.SCREEN] = 'source-over'; + array[_const.BLEND_MODES.OVERLAY] = 'source-over'; + array[_const.BLEND_MODES.DARKEN] = 'source-over'; + array[_const.BLEND_MODES.LIGHTEN] = 'source-over'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'source-over'; + array[_const.BLEND_MODES.COLOR_BURN] = 'source-over'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.DIFFERENCE] = 'source-over'; + array[_const.BLEND_MODES.EXCLUSION] = 'source-over'; + array[_const.BLEND_MODES.HUE] = 'source-over'; + array[_const.BLEND_MODES.SATURATION] = 'source-over'; + array[_const.BLEND_MODES.COLOR] = 'source-over'; + array[_const.BLEND_MODES.LUMINOSITY] = 'source-over'; + } + // not-premultiplied, only for webgl + array[_const.BLEND_MODES.NORMAL_NPM] = array[_const.BLEND_MODES.NORMAL]; + array[_const.BLEND_MODES.ADD_NPM] = array[_const.BLEND_MODES.ADD]; + array[_const.BLEND_MODES.SCREEN_NPM] = array[_const.BLEND_MODES.SCREEN]; + + return array; +} + +},{"../../../const":46,"./canUseNewCanvasBlendModes":80}],82:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged + * up with textures that are no longer being used. + * + * @class + * @memberof PIXI + */ +var TextureGarbageCollector = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function TextureGarbageCollector(renderer) { + _classCallCheck(this, TextureGarbageCollector); + + this.renderer = renderer; + + this.count = 0; + this.checkCount = 0; + this.maxIdle = _settings2.default.GC_MAX_IDLE; + this.checkCountMax = _settings2.default.GC_MAX_CHECK_COUNT; + this.mode = _settings2.default.GC_MODE; + } + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.update = function update() { + this.count++; + + if (this.mode === _const.GC_MODES.MANUAL) { + return; + } + + this.checkCount++; + + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + + this.run(); + } + }; + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.run = function run() { + var tm = this.renderer.textureManager; + var managedTextures = tm._managedTextures; + var wasRemoved = false; + + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + + // only supports non generated textures at the moment! + if (!texture._glRenderTargets && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + + if (wasRemoved) { + var j = 0; + + for (var _i = 0; _i < managedTextures.length; _i++) { + if (managedTextures[_i] !== null) { + managedTextures[j++] = managedTextures[_i]; + } + } + + managedTextures.length = j; + } + }; + + /** + * Removes all the textures within the specified displayObject and its children from the GPU + * + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + */ + + + TextureGarbageCollector.prototype.unload = function unload(displayObject) { + var tm = this.renderer.textureManager; + + // only destroy non generated textures + if (displayObject._texture && displayObject._texture._glRenderTargets) { + tm.destroyTexture(displayObject._texture, true); + } + + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + + return TextureGarbageCollector; +}(); + +exports.default = TextureGarbageCollector; + +},{"../../const":46,"../../settings":101}],83:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _const = require('../../const'); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _utils = require('../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a webGL Texture + * + * @class + * @memberof PIXI + */ +var TextureManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function TextureManager(renderer) { + _classCallCheck(this, TextureManager); + + /** + * A reference to the current renderer + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = renderer.gl; + + /** + * Track textures in the renderer so we can no longer listen to them on destruction. + * + * @member {Array<*>} + * @private + */ + this._managedTextures = []; + } + + /** + * Binds a texture. + * + */ + + + TextureManager.prototype.bindTexture = function bindTexture() {} + // empty + + + /** + * Gets a texture. + * + */ + ; + + TextureManager.prototype.getTexture = function getTexture() {} + // empty + + + /** + * Updates and/or Creates a WebGL texture for the renderer's context. + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update + * @param {number} location - the location the texture will be bound to. + * @return {GLTexture} The gl texture. + */ + ; + + TextureManager.prototype.updateTexture = function updateTexture(texture, location) { + // assume it good! + // texture = texture.baseTexture || texture; + + var gl = this.gl; + + var isRenderTexture = !!texture._glRenderTargets; + + if (!texture.hasLoaded) { + return null; + } + + var boundTextures = this.renderer.boundTextures; + + // if the location is undefined then this may have been called by n event. + // this being the case the texture may already be bound to a slot. As a texture can only be bound once + // we need to find its current location if it exists. + if (location === undefined) { + location = 0; + + // TODO maybe we can use texture bound ids later on... + // check if texture is already bound.. + for (var i = 0; i < boundTextures.length; ++i) { + if (boundTextures[i] === texture) { + location = i; + break; + } + } + } + + boundTextures[location] = texture; + + gl.activeTexture(gl.TEXTURE0 + location); + + var glTexture = texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!glTexture) { + if (isRenderTexture) { + var renderTarget = new _RenderTarget2.default(this.gl, texture.width, texture.height, texture.scaleMode, texture.resolution); + + renderTarget.resize(texture.width, texture.height); + texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget; + glTexture = renderTarget.texture; + } else { + glTexture = new _pixiGlCore.GLTexture(this.gl, null, null, null, null); + glTexture.bind(location); + glTexture.premultiplyAlpha = true; + glTexture.upload(texture.source); + } + + texture._glTextures[this.renderer.CONTEXT_UID] = glTexture; + + texture.on('update', this.updateTexture, this); + texture.on('dispose', this.destroyTexture, this); + + this._managedTextures.push(texture); + + if (texture.isPowerOfTwo) { + if (texture.mipmap) { + glTexture.enableMipmap(); + } + + if (texture.wrapMode === _const.WRAP_MODES.CLAMP) { + glTexture.enableWrapClamp(); + } else if (texture.wrapMode === _const.WRAP_MODES.REPEAT) { + glTexture.enableWrapRepeat(); + } else { + glTexture.enableWrapMirrorRepeat(); + } + } else { + glTexture.enableWrapClamp(); + } + + if (texture.scaleMode === _const.SCALE_MODES.NEAREST) { + glTexture.enableNearestScaling(); + } else { + glTexture.enableLinearScaling(); + } + } + // the texture already exists so we only need to update it.. + else if (isRenderTexture) { + texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height); + } else { + glTexture.upload(texture.source); + } + + return glTexture; + }; + + /** + * Deletes the texture from WebGL + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy + * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. + */ + + + TextureManager.prototype.destroyTexture = function destroyTexture(texture, skipRemove) { + texture = texture.baseTexture || texture; + + if (!texture.hasLoaded) { + return; + } + + var uid = this.renderer.CONTEXT_UID; + var glTextures = texture._glTextures; + var glRenderTargets = texture._glRenderTargets; + + if (glTextures[uid]) { + this.renderer.unbindTexture(texture); + + glTextures[uid].destroy(); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + + delete glTextures[uid]; + + if (!skipRemove) { + var i = this._managedTextures.indexOf(texture); + + if (i !== -1) { + (0, _utils.removeItems)(this._managedTextures, i, 1); + } + } + } + + if (glRenderTargets && glRenderTargets[uid]) { + glRenderTargets[uid].destroy(); + delete glRenderTargets[uid]; + } + }; + + /** + * Deletes all the textures from WebGL + */ + + + TextureManager.prototype.removeAll = function removeAll() { + // empty all the old gl textures as they are useless now + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + delete texture._glTextures[this.renderer.CONTEXT_UID]; + } + } + }; + + /** + * Destroys this manager and removes all its textures + */ + + + TextureManager.prototype.destroy = function destroy() { + // destroy managed textures + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + this.destroyTexture(texture, true); + + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + } + + this._managedTextures = null; + }; + + return TextureManager; +}(); + +exports.default = TextureManager; + +},{"../../const":46,"../../utils":125,"./utils/RenderTarget":96,"pixi-gl-core":15}],84:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _MaskManager = require('./managers/MaskManager'); + +var _MaskManager2 = _interopRequireDefault(_MaskManager); + +var _StencilManager = require('./managers/StencilManager'); + +var _StencilManager2 = _interopRequireDefault(_StencilManager); + +var _FilterManager = require('./managers/FilterManager'); + +var _FilterManager2 = _interopRequireDefault(_FilterManager); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _ObjectRenderer = require('./utils/ObjectRenderer'); + +var _ObjectRenderer2 = _interopRequireDefault(_ObjectRenderer); + +var _TextureManager = require('./TextureManager'); + +var _TextureManager2 = _interopRequireDefault(_TextureManager); + +var _BaseTexture = require('../../textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _TextureGarbageCollector = require('./TextureGarbageCollector'); + +var _TextureGarbageCollector2 = _interopRequireDefault(_TextureGarbageCollector); + +var _WebGLState = require('./WebGLState'); + +var _WebGLState2 = _interopRequireDefault(_WebGLState); + +var _mapWebGLDrawModesToPixi = require('./utils/mapWebGLDrawModesToPixi'); + +var _mapWebGLDrawModesToPixi2 = _interopRequireDefault(_mapWebGLDrawModesToPixi); + +var _validateContext = require('./utils/validateContext'); + +var _validateContext2 = _interopRequireDefault(_validateContext); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CONTEXT_UID = 0; + +/** + * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ + +var WebGLRenderer = function (_SystemRenderer) { + _inherits(WebGLRenderer, _SystemRenderer); + + // eslint-disable-next-line valid-jsdoc + /** + * + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias. If not available natively then FXAA + * antialiasing is used + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. + * The resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear + * the canvas or not before the new render pass. If you wish to set this to false, you *must* set + * preserveDrawingBuffer to `true`. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when + * rendering, stopping pixel interpolation. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.legacy=false] - If true PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering try setting this to true. + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card + */ + function WebGLRenderer(options, arg2, arg3) { + _classCallCheck(this, WebGLRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'WebGL', options, arg2, arg3)); + + _this.legacy = _this.options.legacy; + + if (_this.legacy) { + _pixiGlCore2.default.VertexArrayObject.FORCE_NATIVE = true; + } + + /** + * The type of this renderer as a standardised const + * + * @member {number} + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.WEBGL; + + _this.handleContextLost = _this.handleContextLost.bind(_this); + _this.handleContextRestored = _this.handleContextRestored.bind(_this); + + _this.view.addEventListener('webglcontextlost', _this.handleContextLost, false); + _this.view.addEventListener('webglcontextrestored', _this.handleContextRestored, false); + + /** + * The options passed in to create a new webgl context. + * + * @member {object} + * @private + */ + _this._contextOptions = { + alpha: _this.transparent, + antialias: _this.options.antialias, + premultipliedAlpha: _this.transparent && _this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: _this.options.preserveDrawingBuffer, + powerPreference: _this.options.powerPreference + }; + + _this._backgroundColorRgba[3] = _this.transparent ? 0 : 1; + + /** + * Manages the masks using the stencil buffer. + * + * @member {PIXI.MaskManager} + */ + _this.maskManager = new _MaskManager2.default(_this); + + /** + * Manages the stencil buffer. + * + * @member {PIXI.StencilManager} + */ + _this.stencilManager = new _StencilManager2.default(_this); + + /** + * An empty renderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.emptyRenderer = new _ObjectRenderer2.default(_this); + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.currentRenderer = _this.emptyRenderer; + + /** + * Manages textures + * @member {PIXI.TextureManager} + */ + _this.textureManager = null; + + /** + * Manages the filters. + * + * @member {PIXI.FilterManager} + */ + _this.filterManager = null; + + _this.initPlugins(); + + /** + * The current WebGL rendering context, it is created here + * + * @member {WebGLRenderingContext} + */ + // initialize the context so it is ready for the managers. + if (_this.options.context) { + // checks to see if a context is valid.. + (0, _validateContext2.default)(_this.options.context); + } + + _this.gl = _this.options.context || _pixiGlCore2.default.createContext(_this.view, _this._contextOptions); + + _this.CONTEXT_UID = CONTEXT_UID++; + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.WebGLState} + */ + _this.state = new _WebGLState2.default(_this.gl); + + _this.renderingToScreen = true; + + /** + * Holds the current state of textures bound to the GPU. + * @type {Array} + */ + _this.boundTextures = null; + + /** + * Holds the current shader + * + * @member {PIXI.Shader} + */ + _this._activeShader = null; + + _this._activeVao = null; + + /** + * Holds the current render target + * + * @member {PIXI.RenderTarget} + */ + _this._activeRenderTarget = null; + + _this._initContext(); + + // map some webGL blend and drawmodes.. + _this.drawModes = (0, _mapWebGLDrawModesToPixi2.default)(_this.gl); + + _this._nextTextureLocation = 0; + + _this.setBlendMode(0); + + /** + * Fired after rendering finishes. + * + * @event PIXI.WebGLRenderer#postrender + */ + + /** + * Fired before rendering starts. + * + * @event PIXI.WebGLRenderer#prerender + */ + + /** + * Fired when the WebGL context is set. + * + * @event PIXI.WebGLRenderer#context + * @param {WebGLRenderingContext} gl - WebGL context. + */ + return _this; + } + + /** + * Creates the WebGL context + * + * @private + */ + + + WebGLRenderer.prototype._initContext = function _initContext() { + var gl = this.gl; + + // restore a context if it was previously lost + if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').restoreContext(); + } + + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + + this._activeShader = null; + this._activeVao = null; + + this.boundTextures = new Array(maxTextures); + this.emptyTextures = new Array(maxTextures); + + // create a texture manager... + this.textureManager = new _TextureManager2.default(this); + this.filterManager = new _FilterManager2.default(this); + this.textureGC = new _TextureGarbageCollector2.default(this); + + this.state.resetToDefault(); + + this.rootRenderTarget = new _RenderTarget2.default(gl, this.width, this.height, null, this.resolution, true); + this.rootRenderTarget.clearColor = this._backgroundColorRgba; + + this.bindRenderTarget(this.rootRenderTarget); + + // now lets fill up the textures with empty ones! + var emptyGLTexture = new _pixiGlCore2.default.GLTexture.fromData(gl, null, 1, 1); + + var tempObj = { _glTextures: {} }; + + tempObj._glTextures[this.CONTEXT_UID] = {}; + + for (var i = 0; i < maxTextures; i++) { + var empty = new _BaseTexture2.default(); + + empty._glTextures[this.CONTEXT_UID] = emptyGLTexture; + + this.boundTextures[i] = tempObj; + this.emptyTextures[i] = empty; + this.bindTexture(null, i); + } + + this.emit('context', gl); + + // setup the width/height properties and gl viewport + this.resize(this.screen.width, this.screen.height); + }; + + /** + * Renders the object to its webGL view + * + * @param {PIXI.DisplayObject} displayObject - the object to be rendered + * @param {PIXI.RenderTexture} renderTexture - The render texture to render to. + * @param {boolean} [clear] - Should the canvas be cleared before the new render + * @param {PIXI.Matrix} [transform] - A transform to apply to the render texture before rendering. + * @param {boolean} [skipUpdateTransform] - Should we skip the update transform pass? + */ + + + WebGLRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + // no point rendering if our context has been blown up! + if (!this.gl || this.gl.isContextLost()) { + return; + } + + this._nextTextureLocation = 0; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + this.bindRenderTexture(renderTexture, transform); + + this.currentRenderer.start(); + + if (clear !== undefined ? clear : this.clearBeforeRender) { + this._activeRenderTarget.clear(); + } + + displayObject.renderWebGL(this); + + // apply transform.. + this.currentRenderer.flush(); + + // this.setObjectRenderer(this.emptyRenderer); + + this.textureGC.update(); + + this.emit('postrender'); + }; + + /** + * Changes the current renderer to the one given in parameter + * + * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. + */ + + + WebGLRenderer.prototype.setObjectRenderer = function setObjectRenderer(objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; + + /** + * This should be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + * + */ + + + WebGLRenderer.prototype.flush = function flush() { + this.setObjectRenderer(this.emptyRenderer); + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + WebGLRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + // if(width * this.resolution === this.width && height * this.resolution === this.height)return; + + _SystemRenderer3.default.prototype.resize.call(this, screenWidth, screenHeight); + + this.rootRenderTarget.resize(screenWidth, screenHeight); + + if (this._activeRenderTarget === this.rootRenderTarget) { + this.rootRenderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true); + } + } + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} blendMode - the desired blend mode + */ + + + WebGLRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + this.state.setBlendMode(blendMode); + }; + + /** + * Erases the active render target and fills the drawing area with a colour + * + * @param {number} [clearColor] - The colour + */ + + + WebGLRenderer.prototype.clear = function clear(clearColor) { + this._activeRenderTarget.clear(clearColor); + }; + + /** + * Sets the transform of the active render target to the given matrix + * + * @param {PIXI.Matrix} matrix - The transformation matrix + */ + + + WebGLRenderer.prototype.setTransform = function setTransform(matrix) { + this._activeRenderTarget.transform = matrix; + }; + + /** + * Erases the render texture and fills the drawing area with a colour + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to clear + * @param {number} [clearColor] - The colour + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.clearRenderTexture = function clearRenderTexture(renderTexture, clearColor) { + var baseTexture = renderTexture.baseTexture; + var renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + + if (renderTarget) { + renderTarget.clear(clearColor); + } + + return this; + }; + + /** + * Binds a render texture for rendering + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to render + * @param {PIXI.Matrix} transform - The transform to be applied to the render texture + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTexture = function bindRenderTexture(renderTexture, transform) { + var renderTarget = void 0; + + if (renderTexture) { + var baseTexture = renderTexture.baseTexture; + + if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) { + // bind the current texture + this.textureManager.updateTexture(baseTexture, 0); + } + + this.unbindTexture(baseTexture); + + renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + renderTarget.setFrame(renderTexture.frame); + } else { + renderTarget = this.rootRenderTarget; + } + + renderTarget.transform = transform; + this.bindRenderTarget(renderTarget); + + return this; + }; + + /** + * Changes the current render target to the one given in parameter + * + * @param {PIXI.RenderTarget} renderTarget - the new render target + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTarget = function bindRenderTarget(renderTarget) { + if (renderTarget !== this._activeRenderTarget) { + this._activeRenderTarget = renderTarget; + renderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true); + } + + this.stencilManager.setMaskStack(renderTarget.stencilMaskStack); + } + + return this; + }; + + /** + * Changes the current shader to the one given in parameter + * + * @param {PIXI.Shader} shader - the new shader + * @param {boolean} [autoProject=true] - Whether automatically set the projection matrix + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindShader = function bindShader(shader, autoProject) { + // TODO cache + if (this._activeShader !== shader) { + this._activeShader = shader; + shader.bind(); + + // `autoProject` normally would be a default parameter set to true + // but because of how Babel transpiles default parameters + // it hinders the performance of this method. + if (autoProject !== false) { + // automatically set the projection matrix + shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(true); + } + } + + return this; + }; + + /** + * Binds the texture. This will return the location of the bound texture. + * It may not be the same as the one you pass in. This is due to optimisation that prevents + * needless binding of textures. For example if the texture is already bound it will return the + * current location of the texture instead of the one provided. To bypass this use force location + * + * @param {PIXI.Texture} texture - the new texture + * @param {number} location - the suggested texture location + * @param {boolean} forceLocation - force the location + * @return {number} bound texture location + */ + + + WebGLRenderer.prototype.bindTexture = function bindTexture(texture, location, forceLocation) { + texture = texture || this.emptyTextures[location]; + texture = texture.baseTexture || texture; + texture.touched = this.textureGC.count; + + if (!forceLocation) { + // TODO - maybe look into adding boundIds.. save us the loop? + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + return i; + } + } + + if (location === undefined) { + this._nextTextureLocation++; + this._nextTextureLocation %= this.boundTextures.length; + location = this.boundTextures.length - this._nextTextureLocation - 1; + } + } else { + location = location || 0; + } + + var gl = this.gl; + var glTexture = texture._glTextures[this.CONTEXT_UID]; + + if (!glTexture) { + // this will also bind the texture.. + this.textureManager.updateTexture(texture, location); + } else { + // bind the current texture + this.boundTextures[location] = texture; + gl.activeTexture(gl.TEXTURE0 + location); + gl.bindTexture(gl.TEXTURE_2D, glTexture.texture); + } + + return location; + }; + + /** + * unbinds the texture ... + * + * @param {PIXI.Texture} texture - the texture to unbind + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.unbindTexture = function unbindTexture(texture) { + var gl = this.gl; + + texture = texture.baseTexture || texture; + + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + this.boundTextures[i] = this.emptyTextures[i]; + + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[i]._glTextures[this.CONTEXT_UID].texture); + } + } + + return this; + }; + + /** + * Creates a new VAO from this renderer's context and state. + * + * @return {VertexArrayObject} The new VAO. + */ + + + WebGLRenderer.prototype.createVao = function createVao() { + return new _pixiGlCore2.default.VertexArrayObject(this.gl, this.state.attribState); + }; + + /** + * Changes the current Vao to the one given in parameter + * + * @param {PIXI.VertexArrayObject} vao - the new Vao + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindVao = function bindVao(vao) { + if (this._activeVao === vao) { + return this; + } + + if (vao) { + vao.bind(); + } else if (this._activeVao) { + // TODO this should always be true i think? + this._activeVao.unbind(); + } + + this._activeVao = vao; + + return this; + }; + + /** + * Resets the WebGL state so you can render things however you fancy! + * + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.reset = function reset() { + this.setObjectRenderer(this.emptyRenderer); + + this.bindVao(null); + this._activeShader = null; + this._activeRenderTarget = this.rootRenderTarget; + + for (var i = 0; i < this.boundTextures.length; i++) { + this.boundTextures[i] = this.emptyTextures[i]; + } + + // bind the main frame buffer (the screen); + this.rootRenderTarget.activate(); + + this.state.resetToDefault(); + + return this; + }; + + /** + * Handles a lost webgl context + * + * @private + * @param {WebGLContextEvent} event - The context lost event. + */ + + + WebGLRenderer.prototype.handleContextLost = function handleContextLost(event) { + event.preventDefault(); + }; + + /** + * Handles a restored webgl context + * + * @private + */ + + + WebGLRenderer.prototype.handleContextRestored = function handleContextRestored() { + this.textureManager.removeAll(); + this.filterManager.destroy(true); + this._initContext(); + }; + + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + + + WebGLRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // remove listeners + this.view.removeEventListener('webglcontextlost', this.handleContextLost); + this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); + + this.textureManager.destroy(); + + // call base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.uid = 0; + + // destroy the managers + this.maskManager.destroy(); + this.stencilManager.destroy(); + this.filterManager.destroy(); + + this.maskManager = null; + this.filterManager = null; + this.textureManager = null; + this.currentRenderer = null; + + this.handleContextLost = null; + this.handleContextRestored = null; + + this._contextOptions = null; + this.gl.useProgram(null); + + if (this.gl.getExtension('WEBGL_lose_context')) { + this.gl.getExtension('WEBGL_lose_context').loseContext(); + } + + this.gl = null; + + // this = null; + }; + + return WebGLRenderer; +}(_SystemRenderer3.default); + +/** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @name PIXI.WebGLRenderer#plugins + * @type {object} + * @readonly + * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.extract.WebGLExtract} extract Extract image data from renderer. + * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.prepare.WebGLPrepare} prepare Pre-render display objects. + */ + +/** + * Adds a plugin to the renderer. + * + * @method PIXI.WebGLRenderer#registerPlugin + * @param {string} pluginName - The name of the plugin. + * @param {Function} ctor - The constructor function or class for the plugin. + */ + +exports.default = WebGLRenderer; +_utils.pluginTarget.mixin(WebGLRenderer); + +},{"../../const":46,"../../textures/BaseTexture":112,"../../utils":125,"../SystemRenderer":76,"./TextureGarbageCollector":82,"./TextureManager":83,"./WebGLState":85,"./managers/FilterManager":90,"./managers/MaskManager":91,"./managers/StencilManager":92,"./utils/ObjectRenderer":94,"./utils/RenderTarget":96,"./utils/mapWebGLDrawModesToPixi":99,"./utils/validateContext":100,"pixi-gl-core":15}],85:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); + +var _mapWebGLBlendModesToPixi2 = _interopRequireDefault(_mapWebGLBlendModesToPixi); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var BLEND = 0; +var DEPTH_TEST = 1; +var FRONT_FACE = 2; +var CULL_FACE = 3; +var BLEND_FUNC = 4; + +/** + * A WebGL state machines + * + * @memberof PIXI + * @class + */ + +var WebGLState = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + */ + function WebGLState(gl) { + _classCallCheck(this, WebGLState); + + /** + * The current active state + * + * @member {Uint8Array} + */ + this.activeState = new Uint8Array(16); + + /** + * The default state + * + * @member {Uint8Array} + */ + this.defaultState = new Uint8Array(16); + + // default blend mode.. + this.defaultState[0] = 1; + + /** + * The current state index in the stack + * + * @member {number} + * @private + */ + this.stackIndex = 0; + + /** + * The stack holding all the different states + * + * @member {Array<*>} + * @private + */ + this.stack = []; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + this.attribState = { + tempAttribState: new Array(this.maxAttribs), + attribState: new Array(this.maxAttribs) + }; + + this.blendModes = (0, _mapWebGLBlendModesToPixi2.default)(gl); + + // check we have vao.. + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || gl.getExtension('MOZ_OES_vertex_array_object') || gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + /** + * Pushes a new active state + */ + + + WebGLState.prototype.push = function push() { + // next state.. + var state = this.stack[this.stackIndex]; + + if (!state) { + state = this.stack[this.stackIndex] = new Uint8Array(16); + } + + ++this.stackIndex; + + // copy state.. + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) { + state[i] = this.activeState[i]; + } + }; + + /** + * Pops a state out + */ + + + WebGLState.prototype.pop = function pop() { + var state = this.stack[--this.stackIndex]; + + this.setState(state); + }; + + /** + * Sets the current state + * + * @param {*} state - The state to set. + */ + + + WebGLState.prototype.setState = function setState(state) { + this.setBlend(state[BLEND]); + this.setDepthTest(state[DEPTH_TEST]); + this.setFrontFace(state[FRONT_FACE]); + this.setCullFace(state[CULL_FACE]); + this.setBlendMode(state[BLEND_FUNC]); + }; + + /** + * Enables or disabled blending. + * + * @param {boolean} value - Turn on or off webgl blending. + */ + + + WebGLState.prototype.setBlend = function setBlend(value) { + value = value ? 1 : 0; + + if (this.activeState[BLEND] === value) { + return; + } + + this.activeState[BLEND] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + }; + + /** + * Sets the blend mode. + * + * @param {number} value - The blend mode to set to. + */ + + + WebGLState.prototype.setBlendMode = function setBlendMode(value) { + if (value === this.activeState[BLEND_FUNC]) { + return; + } + + this.activeState[BLEND_FUNC] = value; + + var mode = this.blendModes[value]; + + if (mode.length === 2) { + this.gl.blendFunc(mode[0], mode[1]); + } else { + this.gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); + } + }; + + /** + * Sets whether to enable or disable depth test. + * + * @param {boolean} value - Turn on or off webgl depth testing. + */ + + + WebGLState.prototype.setDepthTest = function setDepthTest(value) { + value = value ? 1 : 0; + + if (this.activeState[DEPTH_TEST] === value) { + return; + } + + this.activeState[DEPTH_TEST] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + }; + + /** + * Sets whether to enable or disable cull face. + * + * @param {boolean} value - Turn on or off webgl cull face. + */ + + + WebGLState.prototype.setCullFace = function setCullFace(value) { + value = value ? 1 : 0; + + if (this.activeState[CULL_FACE] === value) { + return; + } + + this.activeState[CULL_FACE] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + }; + + /** + * Sets the gl front face. + * + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ + + + WebGLState.prototype.setFrontFace = function setFrontFace(value) { + value = value ? 1 : 0; + + if (this.activeState[FRONT_FACE] === value) { + return; + } + + this.activeState[FRONT_FACE] = value; + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); + }; + + /** + * Disables all the vaos in use + * + */ + + + WebGLState.prototype.resetAttributes = function resetAttributes() { + for (var i = 0; i < this.attribState.tempAttribState.length; i++) { + this.attribState.tempAttribState[i] = 0; + } + + for (var _i = 0; _i < this.attribState.attribState.length; _i++) { + this.attribState.attribState[_i] = 0; + } + + // im going to assume one is always active for performance reasons. + for (var _i2 = 1; _i2 < this.maxAttribs; _i2++) { + this.gl.disableVertexAttribArray(_i2); + } + }; + + // used + /** + * Resets all the logic and disables the vaos + */ + + + WebGLState.prototype.resetToDefault = function resetToDefault() { + // unbind any VAO if they exist.. + if (this.nativeVaoExtension) { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + // reset all attributes.. + this.resetAttributes(); + + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; ++i) { + this.activeState[i] = 32; + } + + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + + this.setState(this.defaultState); + }; + + return WebGLState; +}(); + +exports.default = WebGLState; + +},{"./utils/mapWebGLBlendModesToPixi":98}],86:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _extractUniformsFromSrc = require('./extractUniformsFromSrc'); + +var _extractUniformsFromSrc2 = _interopRequireDefault(_extractUniformsFromSrc); + +var _utils = require('../../../utils'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SOURCE_KEY_MAP = {}; + +// let math = require('../../../math'); +/** + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ + +var Filter = function () { + /** + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. + */ + function Filter(vertexSrc, fragmentSrc, uniforms) { + _classCallCheck(this, Filter); + + /** + * The vertex shader. + * + * @member {string} + */ + this.vertexSrc = vertexSrc || Filter.defaultVertexSrc; + + /** + * The fragment shader. + * + * @member {string} + */ + this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc; + + this._blendMode = _const.BLEND_MODES.NORMAL; + + this.uniformData = uniforms || (0, _extractUniformsFromSrc2.default)(this.vertexSrc, this.fragmentSrc, 'projectionMatrix|uSampler'); + + /** + * An object containing the current values of custom uniforms. + * @example Updating the value of a custom uniform + * filter.uniforms.time = performance.now(); + * + * @member {object} + */ + this.uniforms = {}; + + for (var i in this.uniformData) { + this.uniforms[i] = this.uniformData[i].value; + if (this.uniformData[i].type) { + this.uniformData[i].type = this.uniformData[i].type.toLowerCase(); + } + } + + // this is where we store shader references.. + // TODO we could cache this! + this.glShaders = {}; + + // used for caching.. sure there is a better way! + if (!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) { + SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = (0, _utils.uid)(); + } + + this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]; + + /** + * The padding of the filter. Some filters require extra space to breath such as a blur. + * Increasing this will add extra width and height to the bounds of the object that the + * filter is applied to. + * + * @member {number} + */ + this.padding = 4; + + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + * + * @member {number} + */ + this.resolution = _settings2.default.FILTER_RESOLUTION; + + /** + * If enabled is true the filter is applied, if false it will not. + * + * @member {boolean} + */ + this.enabled = true; + + /** + * If enabled, PixiJS will fit the filter area into boundaries for better performance. + * Switch it off if it does not work for specific shader. + * + * @member {boolean} + */ + this.autoFit = true; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + * @param {object} [currentState] - It's current state of filter. + * There are some useful properties in the currentState : + * target, filters, sourceFrame, destinationFrame, renderTarget, resolution + */ + + + Filter.prototype.apply = function apply(filterManager, input, output, clear, currentState) // eslint-disable-line no-unused-vars + { + // --- // + // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); + + // do as you please! + + filterManager.applyFilter(this, input, output, clear); + + // or just do a regular render.. + }; + + /** + * Sets the blendmode of the filter + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + */ + + + _createClass(Filter, [{ + key: 'blendMode', + get: function get() { + return this._blendMode; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._blendMode = value; + } + + /** + * The default vertex shader source + * + * @static + * @constant + */ + + }], [{ + key: 'defaultVertexSrc', + get: function get() { + return ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform mat3 projectionMatrix;', 'uniform mat3 filterMatrix;', 'varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;', ' vTextureCoord = aTextureCoord ;', '}'].join('\n'); + } + + /** + * The default fragment shader source + * + * @static + * @constant + */ + + }, { + key: 'defaultFragmentSrc', + get: function get() { + return ['varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'uniform sampler2D uSampler;', 'uniform sampler2D filterSampler;', 'void main(void){', ' vec4 masky = texture2D(filterSampler, vFilterCoord);', ' vec4 sample = texture2D(uSampler, vTextureCoord);', ' vec4 color;', ' if(mod(vFilterCoord.x, 1.0) > 0.5)', ' {', ' color = vec4(1.0, 0.0, 0.0, 1.0);', ' }', ' else', ' {', ' color = vec4(0.0, 1.0, 0.0, 1.0);', ' }', + // ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', + ' gl_FragColor = mix(sample, masky, 0.5);', ' gl_FragColor *= sample.a;', '}'].join('\n'); + } + }]); + + return Filter; +}(); + +exports.default = Filter; + +},{"../../../const":46,"../../../settings":101,"../../../utils":125,"./extractUniformsFromSrc":87}],87:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = extractUniformsFromSrc; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var defaultValue = _pixiGlCore2.default.shader.defaultValue; + +function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) { + var vertUniforms = extractUniformsFromString(vertexSrc, mask); + var fragUniforms = extractUniformsFromString(fragmentSrc, mask); + + return Object.assign(vertUniforms, fragUniforms); +} + +function extractUniformsFromString(string) { + var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea|filterClamp)$'); + + var uniforms = {}; + var nameSplit = void 0; + + // clean the lines a little - remove extra spaces / tabs etc + // then split along ';' + var lines = string.replace(/\s+/g, ' ').split(/\s*;\s*/); + + // loop through.. + for (var i = 0; i < lines.length; i++) { + var line = lines[i].trim(); + + if (line.indexOf('uniform') > -1) { + var splitLine = line.split(' '); + var type = splitLine[1]; + + var name = splitLine[2]; + var size = 1; + + if (name.indexOf('[') > -1) { + // array! + nameSplit = name.split(/\[|]/); + name = nameSplit[0]; + size *= Number(nameSplit[1]); + } + + if (!name.match(maskRegex)) { + uniforms[name] = { + value: defaultValue(type, size), + name: name, + type: type + }; + } + } + } + + return uniforms; +} + +},{"pixi-gl-core":15}],88:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.calculateScreenSpaceMatrix = calculateScreenSpaceMatrix; +exports.calculateNormalizedScreenSpaceMatrix = calculateNormalizedScreenSpaceMatrix; +exports.calculateSpriteMatrix = calculateSpriteMatrix; + +var _math = require('../../../math'); + +/** + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + * @private + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// this returns a matrix that will normalise map filter cords in the filter to screen space +function calculateScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + // let worldTransform = sprite.worldTransform.copy(Matrix.TEMP_MATRIX), + // let texture = {width:1136, height:700};//sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(textureSize.width, textureSize.height); + + return mappedMatrix; +} + +function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + var translateScaleX = textureSize.width / filterArea.width; + var translateScaleY = textureSize.height / filterArea.height; + + mappedMatrix.scale(translateScaleX, translateScaleY); + + return mappedMatrix; +} + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +function calculateSpriteMatrix(outputMatrix, filterArea, textureSize, sprite) { + var orig = sprite._texture.orig; + var mappedMatrix = outputMatrix.set(textureSize.width, 0, 0, textureSize.height, filterArea.x, filterArea.y); + var worldTransform = sprite.worldTransform.copy(_math.Matrix.TEMP_MATRIX); + + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height); + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; +} + +},{"../../../math":70}],89:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Filter2 = require('../Filter'); + +var _Filter3 = _interopRequireDefault(_Filter2); + +var _math = require('../../../../math'); + +var _path = require('path'); + +var _TextureMatrix = require('../../../../textures/TextureMatrix'); + +var _TextureMatrix2 = _interopRequireDefault(_TextureMatrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The SpriteMaskFilter class + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + */ +var SpriteMaskFilter = function (_Filter) { + _inherits(SpriteMaskFilter, _Filter); + + /** + * @param {PIXI.Sprite} sprite - the target sprite + */ + function SpriteMaskFilter(sprite) { + _classCallCheck(this, SpriteMaskFilter); + + var maskMatrix = new _math.Matrix(); + + var _this = _possibleConstructorReturn(this, _Filter.call(this, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n', 'varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n')); + + sprite.renderable = false; + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + return _this; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + */ + + + SpriteMaskFilter.prototype.apply = function apply(filterManager, input, output) { + var maskSprite = this.maskSprite; + var tex = this.maskSprite.texture; + + if (!tex.valid) { + return; + } + if (!tex.transform) { + // margin = 0.0, let it bleed a bit, shader code becomes easier + // assuming that atlas textures were made with 1-pixel padding + tex.transform = new _TextureMatrix2.default(tex, 0.0); + } + tex.transform.update(); + + this.uniforms.mask = tex; + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite).prepend(tex.transform.mapCoord); + this.uniforms.alpha = maskSprite.worldAlpha; + this.uniforms.maskClamp = tex.transform.uClampFrame; + + filterManager.applyFilter(this, input, output); + }; + + return SpriteMaskFilter; +}(_Filter3.default); + +exports.default = SpriteMaskFilter; + +},{"../../../../math":70,"../../../../textures/TextureMatrix":116,"../Filter":86,"path":8}],90:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _RenderTarget = require('../utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _Quad = require('../utils/Quad'); + +var _Quad2 = _interopRequireDefault(_Quad); + +var _math = require('../../../math'); + +var _Shader = require('../../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _filterTransforms = require('../filters/filterTransforms'); + +var filterTransforms = _interopRequireWildcard(_filterTransforms); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @ignore + * @class + */ +var FilterState = function () { + /** + * + */ + function FilterState() { + _classCallCheck(this, FilterState); + + this.renderTarget = null; + this.target = null; + this.resolution = 1; + + // those three objects are used only for root + // re-assigned for everything else + this.sourceFrame = new _math.Rectangle(); + this.destinationFrame = new _math.Rectangle(); + this.filters = []; + } + + /** + * clears the state + */ + + + FilterState.prototype.clear = function clear() { + this.filters = null; + this.target = null; + this.renderTarget = null; + }; + + return FilterState; +}(); + +var screenKey = 'screen'; + +/** + * @class + * @memberof PIXI + * @extends PIXI.WebGLManager + */ + +var FilterManager = function (_WebGLManager) { + _inherits(FilterManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function FilterManager(renderer) { + _classCallCheck(this, FilterManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.gl = _this.renderer.gl; + // know about sprites! + _this.quad = new _Quad2.default(_this.gl, renderer.state.attribState); + + _this.shaderCache = {}; + // todo add default! + _this.pool = {}; + + _this.filterData = null; + + _this.managedFilters = []; + + _this.renderer.on('prerender', _this.onPrerender, _this); + + _this._screenWidth = renderer.view.width; + _this._screenHeight = renderer.view.height; + return _this; + } + + /** + * Adds a new filter to the manager. + * + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param {PIXI.Filter[]} filters - The filters to apply. + */ + + + FilterManager.prototype.pushFilter = function pushFilter(target, filters) { + var renderer = this.renderer; + + var filterData = this.filterData; + + if (!filterData) { + filterData = this.renderer._activeRenderTarget.filterStack; + + // add new stack + var filterState = new FilterState(); + + filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; + filterState.renderTarget = renderer._activeRenderTarget; + + this.renderer._activeRenderTarget.filterData = filterData = { + index: 0, + stack: [filterState] + }; + + this.filterData = filterData; + } + + // get the current filter state.. + var currentState = filterData.stack[++filterData.index]; + var renderTargetFrame = filterData.stack[0].destinationFrame; + + if (!currentState) { + currentState = filterData.stack[filterData.index] = new FilterState(); + } + + var fullScreen = target.filterArea && target.filterArea.x === 0 && target.filterArea.y === 0 && target.filterArea.width === renderer.screen.width && target.filterArea.height === renderer.screen.height; + + // for now we go off the filter of the first resolution.. + var resolution = filters[0].resolution; + var padding = filters[0].padding | 0; + var targetBounds = fullScreen ? renderer.screen : target.filterArea || target.getBounds(true); + var sourceFrame = currentState.sourceFrame; + var destinationFrame = currentState.destinationFrame; + + sourceFrame.x = (targetBounds.x * resolution | 0) / resolution; + sourceFrame.y = (targetBounds.y * resolution | 0) / resolution; + sourceFrame.width = (targetBounds.width * resolution | 0) / resolution; + sourceFrame.height = (targetBounds.height * resolution | 0) / resolution; + + if (!fullScreen) { + if (filterData.stack[0].renderTarget.transform) {// + + // TODO we should fit the rect around the transform.. + } else if (filters[0].autoFit) { + sourceFrame.fit(renderTargetFrame); + } + + // lets apply the padding After we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + sourceFrame.pad(padding); + } + + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + + // lets play the padding after we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + + var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); + + currentState.target = target; + currentState.filters = filters; + currentState.resolution = resolution; + currentState.renderTarget = renderTarget; + + // bind the render target to draw the shape in the top corner.. + + renderTarget.setFrame(destinationFrame, sourceFrame); + + // bind the render target + renderer.bindRenderTarget(renderTarget); + renderTarget.clear(); + }; + + /** + * Pops off the filter and applies it. + * + */ + + + FilterManager.prototype.popFilter = function popFilter() { + var filterData = this.filterData; + + var lastState = filterData.stack[filterData.index - 1]; + var currentState = filterData.stack[filterData.index]; + + this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); + + var filters = currentState.filters; + + if (filters.length === 1) { + filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false, currentState); + this.freePotRenderTarget(currentState.renderTarget); + } else { + var flip = currentState.renderTarget; + var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, currentState.resolution); + + flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + // finally lets clear the render target before drawing to it.. + flop.clear(); + + var i = 0; + + for (i = 0; i < filters.length - 1; ++i) { + filters[i].apply(this, flip, flop, true, currentState); + + var t = flip; + + flip = flop; + flop = t; + } + + filters[i].apply(this, flip, lastState.renderTarget, false, currentState); + + this.freePotRenderTarget(flip); + this.freePotRenderTarget(flop); + } + + currentState.clear(); + filterData.index--; + + if (filterData.index === 0) { + this.filterData = null; + } + }; + + /** + * Draws a filter. + * + * @param {PIXI.Filter} filter - The filter to draw. + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + FilterManager.prototype.applyFilter = function applyFilter(filter, input, output, clear) { + var renderer = this.renderer; + var gl = renderer.gl; + + var shader = filter.glShaders[renderer.CONTEXT_UID]; + + // caching.. + if (!shader) { + if (filter.glShaderKey) { + shader = this.shaderCache[filter.glShaderKey]; + + if (!shader) { + shader = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + + filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = shader; + this.managedFilters.push(filter); + } + } else { + shader = filter.glShaders[renderer.CONTEXT_UID] = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + this.managedFilters.push(filter); + } + + // TODO - this only needs to be done once? + renderer.bindVao(null); + + this.quad.initVao(shader); + } + + renderer.bindVao(this.quad.vao); + + renderer.bindRenderTarget(output); + + if (clear) { + gl.disable(gl.SCISSOR_TEST); + renderer.clear(); // [1, 1, 1, 1]); + gl.enable(gl.SCISSOR_TEST); + } + + // in case the render target is being masked using a scissor rect + if (output === renderer.maskManager.scissorRenderTarget) { + renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); + } + + renderer.bindShader(shader); + + // free unit 0 for us, doesn't matter what was there + // don't try to restore it, because syncUniforms can upload it to another slot + // and it'll be a problem + var tex = this.renderer.emptyTextures[0]; + + this.renderer.boundTextures[0] = tex; + // this syncs the PixiJS filters uniforms with glsl uniforms + this.syncUniforms(shader, filter); + + renderer.state.setBlendMode(filter.blendMode); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, input.texture.texture); + + this.quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + }; + + /** + * Uploads the uniforms of the filter. + * + * @param {GLShader} shader - The underlying gl shader. + * @param {PIXI.Filter} filter - The filter we are synchronizing. + */ + + + FilterManager.prototype.syncUniforms = function syncUniforms(shader, filter) { + var uniformData = filter.uniformData; + var uniforms = filter.uniforms; + + // 0 is reserved for the PixiJS texture so we start at 1! + var textureCount = 1; + var currentState = void 0; + + // filterArea and filterClamp that are handled by FilterManager directly + // they must not appear in uniformData + + if (shader.uniforms.filterArea) { + currentState = this.filterData.stack[this.filterData.index]; + + var filterArea = shader.uniforms.filterArea; + + filterArea[0] = currentState.renderTarget.size.width; + filterArea[1] = currentState.renderTarget.size.height; + filterArea[2] = currentState.sourceFrame.x; + filterArea[3] = currentState.sourceFrame.y; + + shader.uniforms.filterArea = filterArea; + } + + // use this to clamp displaced texture coords so they belong to filterArea + // see displacementFilter fragment shader for an example + if (shader.uniforms.filterClamp) { + currentState = currentState || this.filterData.stack[this.filterData.index]; + + var filterClamp = shader.uniforms.filterClamp; + + filterClamp[0] = 0; + filterClamp[1] = 0; + filterClamp[2] = (currentState.sourceFrame.width - 1) / currentState.renderTarget.size.width; + filterClamp[3] = (currentState.sourceFrame.height - 1) / currentState.renderTarget.size.height; + + shader.uniforms.filterClamp = filterClamp; + } + + // TODO Caching layer.. + for (var i in uniformData) { + var type = uniformData[i].type; + + if (type === 'sampler2d' && uniforms[i] !== 0) { + if (uniforms[i].baseTexture) { + shader.uniforms[i] = this.renderer.bindTexture(uniforms[i].baseTexture, textureCount); + } else { + shader.uniforms[i] = textureCount; + + // TODO + // this is helpful as renderTargets can also be set. + // Although thinking about it, we could probably + // make the filter texture cache return a RenderTexture + // rather than a renderTarget + var gl = this.renderer.gl; + + this.renderer.boundTextures[textureCount] = this.renderer.emptyTextures[textureCount]; + gl.activeTexture(gl.TEXTURE0 + textureCount); + + uniforms[i].texture.bind(); + } + + textureCount++; + } else if (type === 'mat3') { + // check if its PixiJS matrix.. + if (uniforms[i].a !== undefined) { + shader.uniforms[i] = uniforms[i].toArray(true); + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (type === 'vec2') { + // check if its a point.. + if (uniforms[i].x !== undefined) { + var val = shader.uniforms[i] || new Float32Array(2); + + val[0] = uniforms[i].x; + val[1] = uniforms[i].y; + shader.uniforms[i] = val; + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (type === 'float') { + if (shader.uniforms.data[i].value !== uniformData[i]) { + shader.uniforms[i] = uniforms[i]; + } + } else { + shader.uniforms[i] = uniforms[i]; + } + } + }; + + /** + * Gets a render target from the pool, or creates a new one. + * + * @param {boolean} clear - Should we clear the render texture when we get it? + * @param {number} resolution - The resolution of the target. + * @return {PIXI.RenderTarget} The new render target + */ + + + FilterManager.prototype.getRenderTarget = function getRenderTarget(clear, resolution) { + var currentState = this.filterData.stack[this.filterData.index]; + var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution); + + renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + return renderTarget; + }; + + /** + * Returns a render target to the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The render target to return. + */ + + + FilterManager.prototype.returnRenderTarget = function returnRenderTarget(renderTarget) { + this.freePotRenderTarget(renderTarget); + }; + + /** + * Calculates the mapped matrix. + * + * TODO playing around here.. this is temporary - (will end up in the shader) + * this returns a matrix that will normalise map filter cords in the filter to screen space + * + * @param {PIXI.Matrix} outputMatrix - the matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateScreenSpaceMatrix = function calculateScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); + }; + + /** + * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function calculateNormalizedScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); + }; + + /** + * This will map the filter coord so that a texture can be used based on the transform of a sprite + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateSpriteMatrix = function calculateSpriteMatrix(outputMatrix, sprite) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); + }; + + /** + * Destroys this Filter Manager. + * + * @param {boolean} [contextLost=false] context was lost, do not free shaders + * + */ + + + FilterManager.prototype.destroy = function destroy() { + var contextLost = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + var renderer = this.renderer; + var filters = this.managedFilters; + + renderer.off('prerender', this.onPrerender, this); + + for (var i = 0; i < filters.length; i++) { + if (!contextLost) { + filters[i].glShaders[renderer.CONTEXT_UID].destroy(); + } + delete filters[i].glShaders[renderer.CONTEXT_UID]; + } + + this.shaderCache = {}; + if (!contextLost) { + this.emptyPool(); + } else { + this.pool = {}; + } + }; + + /** + * Gets a Power-of-Two render texture. + * + * TODO move to a separate class could be on renderer? + * also - could cause issue with multiple contexts? + * + * @private + * @param {WebGLRenderingContext} gl - The webgl rendering context + * @param {number} minWidth - The minimum width of the render target. + * @param {number} minHeight - The minimum height of the render target. + * @param {number} resolution - The resolution of the render target. + * @return {PIXI.RenderTarget} The new render target. + */ + + + FilterManager.prototype.getPotRenderTarget = function getPotRenderTarget(gl, minWidth, minHeight, resolution) { + var key = screenKey; + + minWidth *= resolution; + minHeight *= resolution; + + if (minWidth !== this._screenWidth || minHeight !== this._screenHeight) { + // TODO you could return a bigger texture if there is not one in the pool? + minWidth = _bitTwiddle2.default.nextPow2(minWidth); + minHeight = _bitTwiddle2.default.nextPow2(minHeight); + key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + } + + if (!this.pool[key]) { + this.pool[key] = []; + } + + var renderTarget = this.pool[key].pop(); + + // creating render target will cause texture to be bound! + if (!renderTarget) { + // temporary bypass cache.. + var tex = this.renderer.boundTextures[0]; + + gl.activeTexture(gl.TEXTURE0); + + // internally - this will cause a texture to be bound.. + renderTarget = new _RenderTarget2.default(gl, minWidth, minHeight, null, 1); + + // set the current one back + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + } + + // manually tweak the resolution... + // this will not modify the size of the frame buffer, just its resolution. + renderTarget.resolution = resolution; + renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution; + renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution; + renderTarget.filterPoolKey = key; + + return renderTarget; + }; + + /** + * Empties the texture pool. + * + */ + + + FilterManager.prototype.emptyPool = function emptyPool() { + for (var i in this.pool) { + var textures = this.pool[i]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + + this.pool = {}; + }; + + /** + * Frees a render target back into the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free + */ + + + FilterManager.prototype.freePotRenderTarget = function freePotRenderTarget(renderTarget) { + this.pool[renderTarget.filterPoolKey].push(renderTarget); + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + FilterManager.prototype.onPrerender = function onPrerender() { + if (this._screenWidth !== this.renderer.view.width || this._screenHeight !== this.renderer.view.height) { + this._screenWidth = this.renderer.view.width; + this._screenHeight = this.renderer.view.height; + + var textures = this.pool[screenKey]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + this.pool[screenKey] = []; + } + }; + + return FilterManager; +}(_WebGLManager3.default); + +exports.default = FilterManager; + +},{"../../../Shader":44,"../../../math":70,"../filters/filterTransforms":88,"../utils/Quad":95,"../utils/RenderTarget":96,"./WebGLManager":93,"bit-twiddle":1}],91:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _SpriteMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); + +var _SpriteMaskFilter2 = _interopRequireDefault(_SpriteMaskFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var MaskManager = function (_WebGLManager) { + _inherits(MaskManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function MaskManager(renderer) { + _classCallCheck(this, MaskManager); + + // TODO - we don't need both! + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.scissor = false; + _this.scissorData = null; + _this.scissorRenderTarget = null; + + _this.enableScissor = true; + + _this.alphaMaskPool = []; + _this.alphaMaskIndex = 0; + return _this; + } + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushMask = function pushMask(target, maskData) { + // TODO the root check means scissor rect will not + // be used on render textures more info here: + // https://github.com/pixijs/pixi.js/pull/3545 + + if (maskData.texture) { + this.pushSpriteMask(target, maskData); + } else if (this.enableScissor && !this.scissor && this.renderer._activeRenderTarget.root && !this.renderer.stencilManager.stencilMaskStack.length && maskData.isFastRect()) { + var matrix = maskData.worldTransform; + + var rot = Math.atan2(matrix.b, matrix.a); + + // use the nearest degree! + rot = Math.round(rot * (180 / Math.PI)); + + if (rot % 90) { + this.pushStencilMask(maskData); + } else { + this.pushScissorMask(target, maskData); + } + } else { + this.pushStencilMask(maskData); + } + }; + + /** + * Removes the last mask from the mask stack and doesn't return it. + * + * @param {PIXI.DisplayObject} target - Display Object to pop the mask from + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.popMask = function popMask(target, maskData) { + if (maskData.texture) { + this.popSpriteMask(target, maskData); + } else if (this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length) { + this.popScissorMask(target, maskData); + } else { + this.popStencilMask(target, maskData); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.RenderTarget} target - Display Object to push the sprite mask to + * @param {PIXI.Sprite} maskData - Sprite to be used as the mask + */ + + + MaskManager.prototype.pushSpriteMask = function pushSpriteMask(target, maskData) { + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new _SpriteMaskFilter2.default(maskData)]; + } + + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskData; + + // TODO - may cause issues! + target.filterArea = maskData.getBounds(true); + + this.renderer.filterManager.pushFilter(target, alphaMaskFilter); + + this.alphaMaskIndex++; + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popSpriteMask = function popSpriteMask() { + this.renderer.filterManager.popFilter(); + this.alphaMaskIndex--; + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushStencilMask = function pushStencilMask(maskData) { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.pushStencil(maskData); + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popStencilMask = function popStencilMask() { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.popStencil(); + }; + + /** + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushScissorMask = function pushScissorMask(target, maskData) { + maskData.renderable = true; + + var renderTarget = this.renderer._activeRenderTarget; + + var bounds = maskData.getBounds(); + + bounds.fit(renderTarget.size); + maskData.renderable = false; + + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + + var resolution = this.renderer.resolution; + + this.renderer.gl.scissor(bounds.x * resolution, (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution, bounds.width * resolution, bounds.height * resolution); + + this.scissorRenderTarget = renderTarget; + this.scissorData = maskData; + this.scissor = true; + }; + + /** + * + * + */ + + + MaskManager.prototype.popScissorMask = function popScissorMask() { + this.scissorRenderTarget = null; + this.scissorData = null; + this.scissor = false; + + // must be scissor! + var gl = this.renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + }; + + return MaskManager; +}(_WebGLManager3.default); + +exports.default = MaskManager; + +},{"../filters/spriteMask/SpriteMaskFilter":89,"./WebGLManager":93}],92:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var StencilManager = function (_WebGLManager) { + _inherits(StencilManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function StencilManager(renderer) { + _classCallCheck(this, StencilManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.stencilMaskStack = null; + return _this; + } + + /** + * Changes the mask stack that is used by this manager. + * + * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack + */ + + + StencilManager.prototype.setMaskStack = function setMaskStack(stencilMaskStack) { + this.stencilMaskStack = stencilMaskStack; + + var gl = this.renderer.gl; + + if (stencilMaskStack.length === 0) { + gl.disable(gl.STENCIL_TEST); + } else { + gl.enable(gl.STENCIL_TEST); + } + }; + + /** + * Applies the Mask and adds it to the current stencil stack. @alvin + * + * @param {PIXI.Graphics} graphics - The mask + */ + + + StencilManager.prototype.pushStencil = function pushStencil(graphics) { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + this.renderer._activeRenderTarget.attachStencilBuffer(); + + var gl = this.renderer.gl; + var prevMaskCount = this.stencilMaskStack.length; + + if (prevMaskCount === 0) { + gl.enable(gl.STENCIL_TEST); + } + + this.stencilMaskStack.push(graphics); + + // Increment the reference stencil value where the new mask overlaps with the old ones. + gl.colorMask(false, false, false, false); + gl.stencilFunc(gl.EQUAL, prevMaskCount, this._getBitwiseMask()); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + this.renderer.plugins.graphics.render(graphics); + + this._useCurrent(); + }; + + /** + * Removes the last mask from the stencil stack. @alvin + */ + + + StencilManager.prototype.popStencil = function popStencil() { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + var gl = this.renderer.gl; + var graphics = this.stencilMaskStack.pop(); + + if (this.stencilMaskStack.length === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.clearStencil(0); + } else { + // Decrement the reference stencil value where the popped mask overlaps with the other ones + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + this.renderer.plugins.graphics.render(graphics); + + this._useCurrent(); + } + }; + + /** + * Setup renderer to use the current stencil data. + */ + + + StencilManager.prototype._useCurrent = function _useCurrent() { + var gl = this.renderer.gl; + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.EQUAL, this.stencilMaskStack.length, this._getBitwiseMask()); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; + + /** + * Fill 1s equal to the number of acitve stencil masks. + * + * @return {number} The bitwise mask. + */ + + + StencilManager.prototype._getBitwiseMask = function _getBitwiseMask() { + return (1 << this.stencilMaskStack.length) - 1; + }; + + /** + * Destroys the mask stack. + * + */ + + + StencilManager.prototype.destroy = function destroy() { + _WebGLManager3.default.prototype.destroy.call(this); + + this.stencilMaskStack.stencilStack = null; + }; + + return StencilManager; +}(_WebGLManager3.default); + +exports.default = StencilManager; + +},{"./WebGLManager":93}],93:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var WebGLManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function WebGLManager(renderer) { + _classCallCheck(this, WebGLManager); + + /** + * The renderer this manager works for. + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + this.renderer.on('context', this.onContextChange, this); + } + + /** + * Generic method called when there is a WebGL context change. + * + */ + + + WebGLManager.prototype.onContextChange = function onContextChange() {} + // do some codes init! + + + /** + * Generic destroy methods to be overridden by the subclass + * + */ + ; + + WebGLManager.prototype.destroy = function destroy() { + this.renderer.off('context', this.onContextChange, this); + + this.renderer = null; + }; + + return WebGLManager; +}(); + +exports.default = WebGLManager; + +},{}],94:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('../managers/WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Base for a common object renderer that can be used as a system renderer plugin. + * + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var ObjectRenderer = function (_WebGLManager) { + _inherits(ObjectRenderer, _WebGLManager); + + function ObjectRenderer() { + _classCallCheck(this, ObjectRenderer); + + return _possibleConstructorReturn(this, _WebGLManager.apply(this, arguments)); + } + + /** + * Starts the renderer and sets the shader + * + */ + ObjectRenderer.prototype.start = function start() {} + // set the shader.. + + + /** + * Stops the renderer + * + */ + ; + + ObjectRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Stub method for rendering content and emptying the current batch. + * + */ + + + ObjectRenderer.prototype.flush = function flush() {} + // flush! + + + /** + * Renders an object + * + * @param {PIXI.DisplayObject} object - The object to render. + */ + ; + + ObjectRenderer.prototype.render = function render(object) // eslint-disable-line no-unused-vars + { + // render the object + }; + + return ObjectRenderer; +}(_WebGLManager3.default); + +exports.default = ObjectRenderer; + +},{"../managers/WebGLManager":93}],95:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a quad + * + * @class + * @memberof PIXI + */ +var Quad = function () { + /** + * @param {WebGLRenderingContext} gl - The gl context for this quad to use. + * @param {object} state - TODO: Description + */ + function Quad(gl, state) { + _classCallCheck(this, Quad); + + /** + * the current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]); + + /** + * The Uvs of the quad + * + * @member {Float32Array} + */ + this.uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + this.interleaved = new Float32Array(8 * 2); + + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(1); + + /** + * The vertex buffer + * + * @member {glCore.GLBuffer} + */ + this.vertexBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW); + + /** + * The index buffer + * + * @member {glCore.GLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + /** + * The vertex array object + * + * @member {glCore.VertexArrayObject} + */ + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, state); + } + + /** + * Initialises the vaos and uses the shader. + * + * @param {PIXI.Shader} shader - the shader to use + */ + + + Quad.prototype.initVao = function initVao(shader) { + this.vao.clear().addIndex(this.indexBuffer).addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0).addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4); + }; + + /** + * Maps two Rectangle to the quad. + * + * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle + * @param {PIXI.Rectangle} destinationFrame - the second rectangle + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.map = function map(targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + + this.uvs[0] = x; + this.uvs[1] = y; + + this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; + + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; + + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; + + x = destinationFrame.x; + y = destinationFrame.y; + + this.vertices[0] = x; + this.vertices[1] = y; + + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + + return this; + }; + + /** + * Binds the buffer and uploads the data + * + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.upload = function upload() { + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + this.vertexBuffer.upload(this.interleaved); + + return this; + }; + + /** + * Removes this quad from WebGL + */ + + + Quad.prototype.destroy = function destroy() { + var gl = this.gl; + + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.indexBuffer); + }; + + return Quad; +}(); + +exports.default = Quad; + +},{"../../../utils/createIndicesForQuads":123,"pixi-gl-core":15}],96:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../../../math'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _pixiGlCore = require('pixi-gl-core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var RenderTarget = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {number} [width=0] - the horizontal range of the filter + * @param {number} [height=0] - the vertical range of the filter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The current resolution / device pixel ratio + * @param {boolean} [root=false] - Whether this object is the root element or not + */ + function RenderTarget(gl, width, height, scaleMode, resolution, root) { + _classCallCheck(this, RenderTarget); + + // TODO Resolution could go here ( eg low res blurs ) + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // next time to create a frame buffer and texture + + /** + * A frame buffer + * + * @member {PIXI.glCore.GLFramebuffer} + */ + this.frameBuffer = null; + + /** + * The texture + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The background colour of this render target, as an array of [r,g,b,a] values + * + * @member {number[]} + */ + this.clearColor = [0, 0, 0, 0]; + + /** + * The size of the object as a rectangle + * + * @member {PIXI.Rectangle} + */ + this.size = new _math.Rectangle(0, 0, 1, 1); + + /** + * The current resolution / device pixel ratio + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The projection matrix + * + * @member {PIXI.Matrix} + */ + this.projectionMatrix = new _math.Matrix(); + + /** + * The object's transform + * + * @member {PIXI.Matrix} + */ + this.transform = null; + + /** + * The frame. + * + * @member {PIXI.Rectangle} + */ + this.frame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.defaultFrame = new _math.Rectangle(); + this.destinationFrame = null; + this.sourceFrame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.stencilBuffer = null; + + /** + * The data structure for the stencil masks + * + * @member {PIXI.Graphics[]} + */ + this.stencilMaskStack = []; + + /** + * Stores filter data for the render target + * + * @member {object[]} + */ + this.filterData = null; + + /** + * The key for pooled texture of FilterSystem + * @private + * @member {string} + */ + this.filterPoolKey = ''; + + /** + * The scale mode. + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Whether this object is the root element or not + * + * @member {boolean} + */ + this.root = root; + + if (!this.root) { + this.frameBuffer = _pixiGlCore.GLFramebuffer.createRGBA(gl, 100, 100); + + if (this.scaleMode === _const.SCALE_MODES.NEAREST) { + this.frameBuffer.texture.enableNearestScaling(); + } else { + this.frameBuffer.texture.enableLinearScaling(); + } + /* + A frame buffer needs a target to render to.. + create a texture and bind it attach it to the framebuffer.. + */ + + // this is used by the base texture + this.texture = this.frameBuffer.texture; + } else { + // make it a null framebuffer.. + this.frameBuffer = new _pixiGlCore.GLFramebuffer(gl, 100, 100); + this.frameBuffer.framebuffer = null; + } + + this.setFrame(); + + this.resize(width, height); + } + + /** + * Clears the filter texture. + * + * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer + */ + + + RenderTarget.prototype.clear = function clear(clearColor) { + var cc = clearColor || this.clearColor; + + this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a); + }; + + /** + * Binds the stencil buffer. + * + */ + + + RenderTarget.prototype.attachStencilBuffer = function attachStencilBuffer() { + // TODO check if stencil is done? + /** + * The stencil buffer is used for masking in pixi + * lets create one and then add attach it to the framebuffer.. + */ + if (!this.root) { + this.frameBuffer.enableStencil(); + } + }; + + /** + * Sets the frame of the render target. + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.setFrame = function setFrame(destinationFrame, sourceFrame) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || this.destinationFrame; + }; + + /** + * Binds the buffers and initialises the viewport. + * + */ + + + RenderTarget.prototype.activate = function activate() { + // TODO refactor usage of frame.. + var gl = this.gl; + + // make sure the texture is unbound! + this.frameBuffer.bind(); + + this.calculateProjection(this.destinationFrame, this.sourceFrame); + + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + + // TODO add a check as them may be the same! + if (this.destinationFrame !== this.sourceFrame) { + gl.enable(gl.SCISSOR_TEST); + gl.scissor(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + } else { + gl.disable(gl.SCISSOR_TEST); + } + + // TODO - does not need to be updated all the time?? + gl.viewport(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + }; + + /** + * Updates the projection matrix based on a projection frame (which is a rectangle) + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.calculateProjection = function calculateProjection(destinationFrame, sourceFrame) { + var pm = this.projectionMatrix; + + sourceFrame = sourceFrame || destinationFrame; + + pm.identity(); + + // TODO: make dest scale source + if (!this.root) { + pm.a = 1 / destinationFrame.width * 2; + pm.d = 1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = -1 - sourceFrame.y * pm.d; + } else { + pm.a = 1 / destinationFrame.width * 2; + pm.d = -1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = 1 - sourceFrame.y * pm.d; + } + }; + + /** + * Resizes the texture to the specified width and height + * + * @param {number} width - the new width of the texture + * @param {number} height - the new height of the texture + */ + + + RenderTarget.prototype.resize = function resize(width, height) { + width = width | 0; + height = height | 0; + + if (this.size.width === width && this.size.height === height) { + return; + } + + this.size.width = width; + this.size.height = height; + + this.defaultFrame.width = width; + this.defaultFrame.height = height; + + this.frameBuffer.resize(width * this.resolution, height * this.resolution); + + var projectionFrame = this.frame || this.size; + + this.calculateProjection(projectionFrame); + }; + + /** + * Destroys the render target. + * + */ + + + RenderTarget.prototype.destroy = function destroy() { + this.frameBuffer.destroy(); + + this.frameBuffer = null; + this.texture = null; + }; + + return RenderTarget; +}(); + +exports.default = RenderTarget; + +},{"../../../const":46,"../../../math":70,"../../../settings":101,"pixi-gl-core":15}],97:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = checkMaxIfStatmentsInShader; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['precision mediump float;', 'void main(void){', 'float test = 0.1;', '%forloop%', 'gl_FragColor = vec4(0.0);', '}'].join('\n'); + +function checkMaxIfStatmentsInShader(maxIfs, gl) { + var createTempContext = !gl; + + if (maxIfs === 0) { + throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); + } + + if (createTempContext) { + var tinyCanvas = document.createElement('canvas'); + + tinyCanvas.width = 1; + tinyCanvas.height = 1; + + gl = _pixiGlCore2.default.createContext(tinyCanvas); + } + + var shader = gl.createShader(gl.FRAGMENT_SHADER); + + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = maxIfs / 2 | 0; + } else { + // valid! + break; + } + } + + if (createTempContext) { + // get rid of context + if (gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').loseContext(); + } + } + + return maxIfs; +} + +function generateIfTestSrc(maxIfs) { + var src = ''; + + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxIfs - 1) { + src += 'if(test == ' + i + '.0){}'; + } + } + + return src; +} + +},{"pixi-gl-core":15}],98:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLBlendModesToPixi; + +var _const = require('../../../const'); + +/** + * Maps gl blend combinations to WebGL. + * + * @memberof PIXI + * @function mapWebGLBlendModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapWebGLBlendModesToPixi(gl) { + var array = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[_const.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD] = [gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + array[_const.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + // not-premultiplied blend modes + array[_const.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.DST_ALPHA, gl.ONE, gl.DST_ALPHA]; + array[_const.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_COLOR]; + + return array; +} + +},{"../../../const":46}],99:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLDrawModesToPixi; + +var _const = require('../../../const'); + +/** + * Generic Mask Stack data structure. + * + * @memberof PIXI + * @function mapWebGLDrawModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {object} [object={}] - The object to map into + * @return {object} The mapped draw modes. + */ +function mapWebGLDrawModesToPixi(gl) { + var object = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + object[_const.DRAW_MODES.POINTS] = gl.POINTS; + object[_const.DRAW_MODES.LINES] = gl.LINES; + object[_const.DRAW_MODES.LINE_LOOP] = gl.LINE_LOOP; + object[_const.DRAW_MODES.LINE_STRIP] = gl.LINE_STRIP; + object[_const.DRAW_MODES.TRIANGLES] = gl.TRIANGLES; + object[_const.DRAW_MODES.TRIANGLE_STRIP] = gl.TRIANGLE_STRIP; + object[_const.DRAW_MODES.TRIANGLE_FAN] = gl.TRIANGLE_FAN; + + return object; +} + +},{"../../../const":46}],100:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = validateContext; +function validateContext(gl) { + var attributes = gl.getContextAttributes(); + + // this is going to be fairly simple for now.. but at least we have room to grow! + if (!attributes.stencil) { + /* eslint-disable no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable no-console */ + } +} + +},{}],101:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _maxRecommendedTextures = require('./utils/maxRecommendedTextures'); + +var _maxRecommendedTextures2 = _interopRequireDefault(_maxRecommendedTextures); + +var _canUploadSameBuffer = require('./utils/canUploadSameBuffer'); + +var _canUploadSameBuffer2 = _interopRequireDefault(_canUploadSameBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * User's customizable globals for overriding the default PIXI settings, such + * as a renderer's default resolution, framerate, float percision, etc. + * @example + * // Use the native window resolution as the default resolution + * // will support high-density displays when rendering + * PIXI.settings.RESOLUTION = window.devicePixelRatio. + * + * // Disable interpolation when scaling, will make texture be pixelated + * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; + * @namespace PIXI.settings + */ +exports.default = { + + /** + * Target frames per millisecond. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 0.06 + */ + TARGET_FPMS: 0.06, + + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * + * @static + * @memberof PIXI.settings + * @type {boolean} + * @default true + */ + MIPMAP_TEXTURES: true, + + /** + * Default resolution / device pixel ratio of the renderer. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + RESOLUTION: 1, + + /** + * Default filter resolution. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + FILTER_RESOLUTION: 1, + + /** + * The maximum textures that this device supports. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 32 + */ + SPRITE_MAX_TEXTURES: (0, _maxRecommendedTextures2.default)(32), + + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + + /** + * The prefix that denotes a URL is for a retina asset. + * + * @static + * @memberof PIXI.settings + * @type {RegExp} + * @example `@2x` + * @default /@([0-9\.]+)x/ + */ + RETINA_PREFIX: /@([0-9\.]+)x/, + + /** + * The default render options if none are supplied to {@link PIXI.WebGLRenderer} + * or {@link PIXI.CanvasRenderer}. + * + * @static + * @constant + * @memberof PIXI.settings + * @type {object} + * @property {HTMLCanvasElement} view=null + * @property {number} resolution=1 + * @property {boolean} antialias=false + * @property {boolean} forceFXAA=false + * @property {boolean} autoResize=false + * @property {boolean} transparent=false + * @property {number} backgroundColor=0x000000 + * @property {boolean} clearBeforeRender=true + * @property {boolean} preserveDrawingBuffer=false + * @property {boolean} roundPixels=false + * @property {number} width=800 + * @property {number} height=600 + * @property {boolean} legacy=false + */ + RENDER_OPTIONS: { + view: null, + antialias: false, + forceFXAA: false, + autoResize: false, + transparent: false, + backgroundColor: 0x000000, + clearBeforeRender: true, + preserveDrawingBuffer: false, + roundPixels: false, + width: 800, + height: 600, + legacy: false + }, + + /** + * Default transform type. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.TRANSFORM_MODE} + * @default PIXI.TRANSFORM_MODE.STATIC + */ + TRANSFORM_MODE: 0, + + /** + * Default Garbage Collection mode. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO + */ + GC_MODE: 0, + + /** + * Default Garbage Collection max idle. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 3600 + */ + GC_MAX_IDLE: 60 * 60, + + /** + * Default Garbage Collection maximum check count. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 600 + */ + GC_MAX_CHECK_COUNT: 60 * 10, + + /** + * Default wrap modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP + */ + WRAP_MODE: 0, + + /** + * The scale modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR + */ + SCALE_MODE: 0, + + /** + * Default specify float precision in vertex shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.HIGH + */ + PRECISION_VERTEX: 'highp', + + /** + * Default specify float precision in fragment shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM + */ + PRECISION_FRAGMENT: 'mediump', + + /** + * Can we upload the same buffer in a single frame? + * + * @static + * @constant + * @memberof PIXI.settings + * @type {boolean} + */ + CAN_UPLOAD_SAME_BUFFER: (0, _canUploadSameBuffer2.default)(), + + /** + * Default Mesh `canvasPadding`. + * + * @see PIXI.mesh.Mesh#canvasPadding + * @static + * @constant + * @memberof PIXI.settings + * @type {number} + */ + MESH_CANVAS_PADDING: 0 +}; + +},{"./utils/canUploadSameBuffer":122,"./utils/maxRecommendedTextures":127}],102:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new _math.Point(); + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = new PIXI.Sprite.fromImage('assets/image.png'); + * ``` + * + * The more efficient way to create sprites is using a {@link PIXI.Spritesheet}: + * + * ```js + * PIXI.loader.add("assets/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.loader.resources["assets/spritesheet.json"].spritesheet; + * let sprite = new PIXI.Sprite(sheet.textures["image.png"]); + * ... + * } + * ``` + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Sprite = function (_Container) { + _inherits(Sprite, _Container); + + /** + * @param {PIXI.Texture} texture - The texture for this sprite + */ + function Sprite(texture) { + _classCallCheck(this, Sprite); + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 or taken from the {@link PIXI.Texture#defaultAnchor|Texture} + * passed to the constructor. A value of 0,0 means the texture's origin is the top left. + * Setting the anchor to 0.5,0.5 means the texture's origin is centered. + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner. + * Note: Updating the {@link PIXI.Texture#defaultAnchor} after a Texture is + * created does _not_ update the Sprite's anchor values. + * + * @member {PIXI.ObservablePoint} + * @private + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this._anchor = new _math.ObservablePoint(_this._onAnchorUpdate, _this, texture ? texture.defaultAnchor.x : 0, texture ? texture.defaultAnchor.y : 0); + + /** + * The texture that the sprite is using + * + * @private + * @member {PIXI.Texture} + */ + _this._texture = null; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = null; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * The shader that will be used to render the sprite. Set to null to remove a current shader. + * + * @member {PIXI.Filter|PIXI.Shader} + */ + _this.shader = null; + + /** + * An internal cached value of the tint. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this.cachedTint = 0xFFFFFF; + + // call texture setter + _this.texture = texture || _Texture2.default.EMPTY; + + /** + * this is used to store the vertex data of the sprite (basically a quad) + * + * @private + * @member {Float32Array} + */ + _this.vertexData = new Float32Array(8); + + /** + * This is used to calculate the bounds of the object IF it is a trimmed sprite + * + * @private + * @member {Float32Array} + */ + _this.vertexTrimmedData = null; + + _this._transformID = -1; + _this._textureID = -1; + + _this._transformTrimmedID = -1; + _this._textureTrimmedID = -1; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * + * @member {string} + * @default 'sprite' + */ + _this.pluginName = 'sprite'; + _this.roundPixels = false; + return _this; + } + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Sprite.prototype._onTextureUpdate = function _onTextureUpdate() { + this._textureID = -1; + this._textureTrimmedID = -1; + this.cachedTint = 0xFFFFFF; + + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = (0, _utils.sign)(this.scale.x) * this._width / this._texture.orig.width; + } + + if (this._height) { + this.scale.y = (0, _utils.sign)(this.scale.y) * this._height / this._texture.orig.height; + } + }; + + /** + * Called when the anchor position updates. + * + * @private + */ + + + Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate() { + this._transformID = -1; + this._transformTrimmedID = -1; + }; + + /** + * calculates worldTransform * vertices, store it in vertexData + */ + + + Sprite.prototype.calculateVertices = function calculateVertices() { + if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) { + return; + } + + this._transformID = this.transform._worldID; + this._textureID = this._texture._updateID; + + // set the vertex data + + var texture = this._texture; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var anchor = this._anchor; + + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - anchor._x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - anchor._y * orig.height; + h0 = h1 + trim.height; + } else { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData + * This is used to ensure that the true width and height of a trimmed texture is respected + */ + + + Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices() { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { + return; + } + + this._transformTrimmedID = this.transform._worldID; + this._textureTrimmedID = this._texture._updateID; + + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + var anchor = this._anchor; + + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + + var w1 = -anchor._x * orig.width; + var w0 = w1 + orig.width; + + var h1 = -anchor._y * orig.height; + var h0 = h1 + orig.height; + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use. + */ + + + Sprite.prototype._renderWebGL = function _renderWebGL(renderer) { + this.calculateVertices(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Sprite.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Updates the bounds of the sprite. + * + * @private + */ + + + Sprite.prototype._calculateBounds = function _calculateBounds() { + var trim = this._texture.trim; + var orig = this._texture.orig; + + // First lets check to see if the current texture has a trim.. + if (!trim || trim.width === orig.width && trim.height === orig.height) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + Sprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._texture.orig.width * -this._anchor._x; + this._bounds.minY = this._texture.orig.height * -this._anchor._y; + this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x); + this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._y); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _Container.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Tests if a point is inside this sprite + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Sprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + y1 = -height * this.anchor.y; + + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + Sprite.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + this._texture.off('update', this._onTextureUpdate, this); + + this._anchor = null; + + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + + this._texture.destroy(!!destroyBaseTexture); + } + + this._texture = null; + this.shader = null; + }; + + // some helper functions.. + + /** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Sprite} The newly created sprite + */ + + + Sprite.from = function from(source) { + return new Sprite(_Texture2.default.from(source)); + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId + */ + + + Sprite.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return new Sprite(texture); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id + */ + + + Sprite.fromImage = function fromImage(imageId, crossorigin, scaleMode) { + return new Sprite(_Texture2.default.fromImage(imageId, crossorigin, scaleMode)); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Sprite, [{ + key: 'width', + get: function get() { + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 or taken from the {@link PIXI.Texture|Texture} passed to the constructor. + * Setting the texture at a later point of time does not change the anchor. + * + * 0,0 means the texture's origin is the top left, 0.5,0.5 is the center, 1,1 the bottom right corner. + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._anchor.copy(value); + } + + /** + * The tint applied to the sprite. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + } + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + */ + + }, { + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value || _Texture2.default.EMPTY; + this.cachedTint = 0xFFFFFF; + + this._textureID = -1; + this._textureTrimmedID = -1; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + }]); + + return Sprite; +}(_Container3.default); + +exports.default = Sprite; + +},{"../const":46,"../display/Container":48,"../math":70,"../textures/Texture":115,"../utils":125}],103:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +var _math = require('../../math'); + +var _CanvasTinter = require('./CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var canvasRenderWorldTransform = new _math.Matrix(); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasSpriteRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + */ + +var CanvasSpriteRenderer = function () { + /** + * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for. + */ + function CanvasSpriteRenderer(renderer) { + _classCallCheck(this, CanvasSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + CanvasSpriteRenderer.prototype.render = function render(sprite) { + var texture = sprite._texture; + var renderer = this.renderer; + + var width = texture._frame.width; + var height = texture._frame.height; + + var wt = sprite.transform.worldTransform; + var dx = 0; + var dy = 0; + + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) { + return; + } + + renderer.setBlendMode(sprite.blendMode); + + // Ignore null sources + if (texture.valid) { + renderer.context.globalAlpha = sprite.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture + var smoothingEnabled = texture.baseTexture.scaleMode === _const.SCALE_MODES.LINEAR; + + if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) { + renderer.context[renderer.smoothProperty] = smoothingEnabled; + } + + if (texture.trim) { + dx = texture.trim.width / 2 + texture.trim.x - sprite.anchor.x * texture.orig.width; + dy = texture.trim.height / 2 + texture.trim.y - sprite.anchor.y * texture.orig.height; + } else { + dx = (0.5 - sprite.anchor.x) * texture.orig.width; + dy = (0.5 - sprite.anchor.y) * texture.orig.height; + } + + if (texture.rotate) { + wt.copy(canvasRenderWorldTransform); + wt = canvasRenderWorldTransform; + _math.GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); + // the anchor has already been applied above, so lets set it to zero + dx = 0; + dy = 0; + } + + dx -= width / 2; + dy -= height / 2; + + // Allow for pixel rounding + if (renderer.roundPixels || sprite.roundPixels) { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution | 0, wt.ty * renderer.resolution | 0); + + dx = dx | 0; + dy = dy | 0; + } else { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution, wt.ty * renderer.resolution); + } + + var resolution = texture.baseTexture.resolution; + + if (sprite.tint !== 0xFFFFFF) { + if (sprite.cachedTint !== sprite.tint || sprite.tintedTexture.tintId !== sprite._texture._updateID) { + sprite.cachedTint = sprite.tint; + + // TODO clean up caching - how to clean up the caches? + sprite.tintedTexture = _CanvasTinter2.default.getTintedTexture(sprite, sprite.tint); + } + + renderer.context.drawImage(sprite.tintedTexture, 0, 0, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } else { + renderer.context.drawImage(texture.baseTexture.source, texture._frame.x * resolution, texture._frame.y * resolution, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } + } + }; + + /** + * destroy the sprite object. + * + */ + + + CanvasSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasSpriteRenderer; +}(); + +exports.default = CanvasSpriteRenderer; + + +_CanvasRenderer2.default.registerPlugin('sprite', CanvasSpriteRenderer); + +},{"../../const":46,"../../math":70,"../../renderers/canvas/CanvasRenderer":77,"./CanvasTinter":104}],104:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class + * @memberof PIXI + */ +var CanvasTinter = { + /** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Sprite} sprite - the sprite to tint + * @param {number} color - the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ + getTintedTexture: function getTintedTexture(sprite, color) { + var texture = sprite._texture; + + color = CanvasTinter.roundColor(color); + + var stringColor = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + texture.tintCache = texture.tintCache || {}; + + var cachedTexture = texture.tintCache[stringColor]; + + var canvas = void 0; + + if (cachedTexture) { + if (cachedTexture.tintId === texture._updateID) { + return texture.tintCache[stringColor]; + } + + canvas = texture.tintCache[stringColor]; + } else { + canvas = CanvasTinter.canvas || document.createElement('canvas'); + } + + CanvasTinter.tintMethod(texture, color, canvas); + + canvas.tintId = texture._updateID; + + if (CanvasTinter.convertTintToImage) { + // is this better? + var tintImage = new Image(); + + tintImage.src = canvas.toDataURL(); + + texture.tintCache[stringColor] = tintImage; + } else { + texture.tintCache[stringColor] = canvas; + // if we are not converting the texture to an image then we need to lose the reference to the canvas + CanvasTinter.canvas = null; + } + + return canvas; + }, + + /** + * Tint a texture using the 'multiply' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithMultiply: function tintWithMultiply(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.save(); + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + context.restore(); + }, + + /** + * Tint a texture using the 'overlay' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithOverlay: function tintWithOverlay(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.save(); + context.globalCompositeOperation = 'copy'; + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + // context.globalCompositeOperation = 'copy'; + context.restore(); + }, + + + /** + * Tint a texture pixel per pixel. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithPerPixel: function tintWithPerPixel(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.save(); + context.globalCompositeOperation = 'copy'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + context.restore(); + + var rgbValues = (0, _utils.hex2rgb)(color); + var r = rgbValues[0]; + var g = rgbValues[1]; + var b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, crop.width, crop.height); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + } + + context.putImageData(pixelData, 0, 0); + }, + + /** + * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel. + * + * @memberof PIXI.CanvasTinter + * @param {number} color - the color to round, should be a hex color + * @return {number} The rounded color. + */ + roundColor: function roundColor(color) { + var step = CanvasTinter.cacheStepsPerColorChannel; + + var rgbValues = (0, _utils.hex2rgb)(color); + + rgbValues[0] = Math.min(255, rgbValues[0] / step * step); + rgbValues[1] = Math.min(255, rgbValues[1] / step * step); + rgbValues[2] = Math.min(255, rgbValues[2] / step * step); + + return (0, _utils.rgb2hex)(rgbValues); + }, + + /** + * Number of steps which will be used as a cap when rounding colors. + * + * @memberof PIXI.CanvasTinter + * @type {number} + */ + cacheStepsPerColorChannel: 8, + + /** + * Tint cache boolean flag. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + convertTintToImage: false, + + /** + * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + canUseMultiply: (0, _canUseNewCanvasBlendModes2.default)(), + + /** + * The tinting method that will be used. + * + * @memberof PIXI.CanvasTinter + * @type {tintMethodFunctionType} + */ + tintMethod: 0 +}; + +CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply : CanvasTinter.tintWithPerPixel; + +/** + * The tintMethod type. + * + * @memberof PIXI.CanvasTinter + * @callback tintMethodFunctionType + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + +exports.default = CanvasTinter; + +},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":80,"../../utils":125}],105:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Buffer = function () { + /** + * @param {number} size - The size of the buffer in bytes. + */ + function Buffer(size) { + _classCallCheck(this, Buffer); + + this.vertices = new ArrayBuffer(size); + + /** + * View on the vertices as a Float32Array for positions + * + * @member {Float32Array} + */ + this.float32View = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array for uvs + * + * @member {Float32Array} + */ + this.uint32View = new Uint32Array(this.vertices); + } + + /** + * Destroys the buffer. + * + */ + + + Buffer.prototype.destroy = function destroy() { + this.vertices = null; + this.positions = null; + this.uvs = null; + this.colors = null; + }; + + return Buffer; +}(); + +exports.default = Buffer; + +},{}],106:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _createIndicesForQuads = require('../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +var _generateMultiTextureShader = require('./generateMultiTextureShader'); + +var _generateMultiTextureShader2 = _interopRequireDefault(_generateMultiTextureShader); + +var _checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'); + +var _checkMaxIfStatmentsInShader2 = _interopRequireDefault(_checkMaxIfStatmentsInShader); + +var _BatchBuffer = require('./BatchBuffer'); + +var _BatchBuffer2 = _interopRequireDefault(_BatchBuffer); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var TICK = 0; +var TEXTURE_TICK = 0; + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var SpriteRenderer = function (_ObjectRenderer) { + _inherits(SpriteRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function SpriteRenderer(renderer) { + _classCallCheck(this, SpriteRenderer); + + /** + * Number of values sent in the vertex buffer. + * aVertexPosition(2), aTextureCoord(1), aColor(1), aTextureId(1) = 5 + * + * @member {number} + */ + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.vertSize = 5; + + /** + * The size of the vertex information in bytes. + * + * @member {number} + */ + _this.vertByteSize = _this.vertSize * 4; + + /** + * The number of images in the SpriteRenderer before it flushes. + * + * @member {number} + */ + _this.size = _settings2.default.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + + // the total number of bytes in our batch + // let numVerts = this.size * 4 * this.vertByteSize; + + _this.buffers = []; + for (var i = 1; i <= _bitTwiddle2.default.nextPow2(_this.size); i *= 2) { + _this.buffers.push(new _BatchBuffer2.default(i * 4 * _this.vertByteSize)); + } + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + _this.indices = (0, _createIndicesForQuads2.default)(_this.size); + + /** + * The default shaders that is used if a sprite doesn't have a more specific one. + * there is a shader for each number of textures that can be rendererd. + * These shaders will also be generated on the fly as required. + * @member {PIXI.Shader[]} + */ + _this.shader = null; + + _this.currentIndex = 0; + _this.groups = []; + + for (var k = 0; k < _this.size; k++) { + _this.groups[k] = { textures: [], textureCount: 0, ids: [], size: 0, start: 0, blend: 0 }; + } + + _this.sprites = []; + + _this.vertexBuffers = []; + _this.vaos = []; + + _this.vaoMax = 2; + _this.vertexCount = 0; + + _this.renderer.on('prerender', _this.onPrerender, _this); + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + SpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + if (this.renderer.legacy) { + this.MAX_TEXTURES = 1; + } else { + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), _settings2.default.SPRITE_MAX_TEXTURES); + + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = (0, _checkMaxIfStatmentsInShader2.default)(this.MAX_TEXTURES, gl); + } + + this.shader = (0, _generateMultiTextureShader2.default)(gl, this.MAX_TEXTURES); + + // create a couple of buffers + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + // we use the second shader as the first one depending on your browser may omit aTextureId + // as it is not used by the shader so is optimized out. + + this.renderer.bindVao(null); + + var attrs = this.shader.attributes; + + for (var i = 0; i < this.vaoMax; i++) { + /* eslint-disable max-len */ + var vertexBuffer = this.vertexBuffers[i] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + /* eslint-enable max-len */ + + // build the vao object that will render.. + var vao = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (attrs.aTextureId) { + vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vaos[i] = vao; + } + + this.vao = this.vaos[0]; + this.currentBlendMode = 99999; + + this.boundTextures = new Array(this.MAX_TEXTURES); + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + SpriteRenderer.prototype.onPrerender = function onPrerender() { + this.vertexCount = 0; + }; + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + SpriteRenderer.prototype.render = function render(sprite) { + // TODO set blend modes.. + // check texture.. + if (this.currentIndex >= this.size) { + this.flush(); + } + + // get the uvs for the texture + + // if the uvs have not updated then no point rendering just yet! + if (!sprite._texture._uvs) { + return; + } + + // push a texture. + // increment the batchsize + this.sprites[this.currentIndex++] = sprite; + }; + + /** + * Renders the content and empties the current batch. + * + */ + + + SpriteRenderer.prototype.flush = function flush() { + if (this.currentIndex === 0) { + return; + } + + var gl = this.renderer.gl; + var MAX_TEXTURES = this.MAX_TEXTURES; + + var np2 = _bitTwiddle2.default.nextPow2(this.currentIndex); + var log2 = _bitTwiddle2.default.log2(np2); + var buffer = this.buffers[log2]; + + var sprites = this.sprites; + var groups = this.groups; + + var float32View = buffer.float32View; + var uint32View = buffer.uint32View; + + var boundTextures = this.boundTextures; + var rendererBoundTextures = this.renderer.boundTextures; + var touch = this.renderer.textureGC.count; + + var index = 0; + var nextTexture = void 0; + var currentTexture = void 0; + var groupCount = 1; + var textureCount = 0; + var currentGroup = groups[0]; + var vertexData = void 0; + var uvs = void 0; + var blendMode = _utils.premultiplyBlendMode[sprites[0]._texture.baseTexture.premultipliedAlpha ? 1 : 0][sprites[0].blendMode]; + + currentGroup.textureCount = 0; + currentGroup.start = 0; + currentGroup.blend = blendMode; + + TICK++; + + var i = void 0; + + // copy textures.. + for (i = 0; i < MAX_TEXTURES; ++i) { + var bt = rendererBoundTextures[i]; + + if (bt._enabled === TICK) { + boundTextures[i] = this.renderer.emptyTextures[i]; + continue; + } + + boundTextures[i] = bt; + bt._virtalBoundId = i; + bt._enabled = TICK; + } + TICK++; + + for (i = 0; i < this.currentIndex; ++i) { + // upload the sprite elemetns... + // they have all ready been calculated so we just need to push them into the buffer. + var sprite = sprites[i]; + + sprites[i] = null; + + nextTexture = sprite._texture.baseTexture; + + var spriteBlendMode = _utils.premultiplyBlendMode[Number(nextTexture.premultipliedAlpha)][sprite.blendMode]; + + if (blendMode !== spriteBlendMode) { + // finish a group.. + blendMode = spriteBlendMode; + + // force the batch to break! + currentTexture = null; + textureCount = MAX_TEXTURES; + TICK++; + } + + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + + if (nextTexture._enabled !== TICK) { + if (textureCount === MAX_TEXTURES) { + TICK++; + + currentGroup.size = i - currentGroup.start; + + textureCount = 0; + + currentGroup = groups[groupCount++]; + currentGroup.blend = blendMode; + currentGroup.textureCount = 0; + currentGroup.start = i; + } + + nextTexture.touched = touch; + + if (nextTexture._virtalBoundId === -1) { + for (var j = 0; j < MAX_TEXTURES; ++j) { + var tIndex = (j + TEXTURE_TICK) % MAX_TEXTURES; + + var t = boundTextures[tIndex]; + + if (t._enabled !== TICK) { + TEXTURE_TICK++; + + t._virtalBoundId = -1; + + nextTexture._virtalBoundId = tIndex; + + boundTextures[tIndex] = nextTexture; + break; + } + } + } + + nextTexture._enabled = TICK; + + currentGroup.textureCount++; + currentGroup.ids[textureCount] = nextTexture._virtalBoundId; + currentGroup.textures[textureCount++] = nextTexture; + } + } + + vertexData = sprite.vertexData; + + // TODO this sum does not need to be set each frame.. + uvs = sprite._texture._uvs.uvsUint32; + + if (this.renderer.roundPixels || sprite.roundPixels) { + var resolution = this.renderer.resolution; + + // xy + float32View[index] = (vertexData[0] * resolution | 0) / resolution; + float32View[index + 1] = (vertexData[1] * resolution | 0) / resolution; + + // xy + float32View[index + 5] = (vertexData[2] * resolution | 0) / resolution; + float32View[index + 6] = (vertexData[3] * resolution | 0) / resolution; + + // xy + float32View[index + 10] = (vertexData[4] * resolution | 0) / resolution; + float32View[index + 11] = (vertexData[5] * resolution | 0) / resolution; + + // xy + float32View[index + 15] = (vertexData[6] * resolution | 0) / resolution; + float32View[index + 16] = (vertexData[7] * resolution | 0) / resolution; + } else { + // xy + float32View[index] = vertexData[0]; + float32View[index + 1] = vertexData[1]; + + // xy + float32View[index + 5] = vertexData[2]; + float32View[index + 6] = vertexData[3]; + + // xy + float32View[index + 10] = vertexData[4]; + float32View[index + 11] = vertexData[5]; + + // xy + float32View[index + 15] = vertexData[6]; + float32View[index + 16] = vertexData[7]; + } + + uint32View[index + 2] = uvs[0]; + uint32View[index + 7] = uvs[1]; + uint32View[index + 12] = uvs[2]; + uint32View[index + 17] = uvs[3]; + /* eslint-disable max-len */ + var alpha = Math.min(sprite.worldAlpha, 1.0); + // we dont call extra function if alpha is 1.0, that's faster + var argb = alpha < 1.0 && nextTexture.premultipliedAlpha ? (0, _utils.premultiplyTint)(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); + + uint32View[index + 3] = uint32View[index + 8] = uint32View[index + 13] = uint32View[index + 18] = argb; + float32View[index + 4] = float32View[index + 9] = float32View[index + 14] = float32View[index + 19] = nextTexture._virtalBoundId; + /* eslint-enable max-len */ + + index += 20; + } + + currentGroup.size = i - currentGroup.start; + + if (!_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // this is still needed for IOS performance.. + // it really does not like uploading to the same buffer in a single frame! + if (this.vaoMax <= this.vertexCount) { + this.vaoMax++; + + var attrs = this.shader.attributes; + + /* eslint-disable max-len */ + var vertexBuffer = this.vertexBuffers[this.vertexCount] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + /* eslint-enable max-len */ + + // build the vao object that will render.. + var vao = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (attrs.aTextureId) { + vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vaos[this.vertexCount] = vao; + } + + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, false); + + this.vertexCount++; + } else { + // lets use the faster option, always use buffer number 0 + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, true); + } + + for (i = 0; i < MAX_TEXTURES; ++i) { + rendererBoundTextures[i]._virtalBoundId = -1; + } + + // render the groups.. + for (i = 0; i < groupCount; ++i) { + var group = groups[i]; + var groupTextureCount = group.textureCount; + + for (var _j = 0; _j < groupTextureCount; _j++) { + currentTexture = group.textures[_j]; + + // reset virtual ids.. + // lets do a quick check.. + if (rendererBoundTextures[group.ids[_j]] !== currentTexture) { + this.renderer.bindTexture(currentTexture, group.ids[_j], true); + } + + // reset the virtualId.. + currentTexture._virtalBoundId = -1; + } + + // set the blend mode.. + this.renderer.state.setBlendMode(group.blend); + + gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); + } + + // reset elements for the next flush + this.currentIndex = 0; + }; + + /** + * Starts a new sprite batch. + */ + + + SpriteRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + + if (_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // bind buffer #0, we don't need others + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].bind(); + } + }; + + /** + * Stops and flushes the current batch. + * + */ + + + SpriteRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Destroys the SpriteRenderer. + * + */ + + + SpriteRenderer.prototype.destroy = function destroy() { + for (var i = 0; i < this.vaoMax; i++) { + if (this.vertexBuffers[i]) { + this.vertexBuffers[i].destroy(); + } + if (this.vaos[i]) { + this.vaos[i].destroy(); + } + } + + if (this.indexBuffer) { + this.indexBuffer.destroy(); + } + + this.renderer.off('prerender', this.onPrerender, this); + + _ObjectRenderer.prototype.destroy.call(this); + + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } + + this.vertexBuffers = null; + this.vaos = null; + this.indexBuffer = null; + this.indices = null; + + this.sprites = null; + + for (var _i = 0; _i < this.buffers.length; ++_i) { + this.buffers[_i].destroy(); + } + }; + + return SpriteRenderer; +}(_ObjectRenderer3.default); + +exports.default = SpriteRenderer; + + +_WebGLRenderer2.default.registerPlugin('sprite', SpriteRenderer); + +},{"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":97,"../../settings":101,"../../utils":125,"../../utils/createIndicesForQuads":123,"./BatchBuffer":105,"./generateMultiTextureShader":107,"bit-twiddle":1,"pixi-gl-core":15}],107:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateMultiTextureShader; + +var _Shader = require('../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'varying float vTextureId;', 'uniform sampler2D uSamplers[%count%];', 'void main(void){', 'vec4 color;', 'float textureId = floor(vTextureId+0.5);', '%forloop%', 'gl_FragColor = color * vColor;', '}'].join('\n'); + +function generateMultiTextureShader(gl, maxTextures) { + var vertexSrc = 'precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor;\n}\n'; + var fragmentSrc = fragTemplate; + + fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); + + var shader = new _Shader2.default(gl, vertexSrc, fragmentSrc); + + var sampleValues = []; + + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + + shader.bind(); + shader.uniforms.uSamplers = sampleValues; + + return shader; +} + +function generateSampleSrc(maxTextures) { + var src = ''; + + src += '\n'; + src += '\n'; + + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxTextures - 1) { + src += 'if(textureId == ' + i + '.0)'; + } + + src += '\n{'; + src += '\n\tcolor = texture2D(uSamplers[' + i + '], vTextureCoord);'; + src += '\n}'; + } + + src += '\n'; + src += '\n'; + + return src; +} + +},{"../../Shader":44,"path":8}],108:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Sprite2 = require('../sprites/Sprite'); + +var _Sprite3 = _interopRequireDefault(_Sprite2); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TextStyle = require('./TextStyle'); + +var _TextStyle2 = _interopRequireDefault(_TextStyle); + +var _TextMetrics = require('./TextMetrics'); + +var _TextMetrics2 = _interopRequireDefault(_TextMetrics); + +var _trimCanvas = require('../utils/trimCanvas'); + +var _trimCanvas2 = _interopRequireDefault(_trimCanvas); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint max-depth: [2, 8] */ + + +var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true +}; + +/** + * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string, + * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object. + * + * A Text can be created directly from a string and a style object, + * which can be generated [here](https://pixijs.io/pixi-text-style). + * + * ```js + * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI + */ + +var Text = function (_Sprite) { + _inherits(Text, _Sprite); + + /** + * @param {string} text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + * @param {HTMLCanvasElement} [canvas] - The canvas element for drawing text + */ + function Text(text, style, canvas) { + _classCallCheck(this, Text); + + canvas = canvas || document.createElement('canvas'); + + canvas.width = 3; + canvas.height = 3; + + var texture = _Texture2.default.fromCanvas(canvas, _settings2.default.SCALE_MODE, 'text'); + + texture.orig = new _math.Rectangle(); + texture.trim = new _math.Rectangle(); + + // base texture is already automatically added to the cache, now adding the actual texture + var _this = _possibleConstructorReturn(this, _Sprite.call(this, texture)); + + _Texture2.default.addToCache(_this._texture, _this._texture.baseTexture.textureCacheIds[0]); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.canvas = canvas; + + /** + * The canvas 2d context that everything is drawn with + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.canvas.getContext('2d'); + + /** + * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. + * @member {number} + * @default 1 + */ + _this.resolution = _settings2.default.RESOLUTION; + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = null; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._style = null; + /** + * Private listener to track style changes. + * + * @member {Function} + * @private + */ + _this._styleListener = null; + + /** + * Private tracker for the current font. + * + * @member {string} + * @private + */ + _this._font = ''; + + _this.text = text; + _this.style = style; + + _this.localStyleID = -1; + return _this; + } + + /** + * Renders text and updates it when needed. + * + * @private + * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. + */ + + + Text.prototype.updateText = function updateText(respectDirty) { + var style = this._style; + + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + + if (!this.dirty && respectDirty) { + return; + } + + this._font = this._style.toFontString(); + + var context = this.context; + var measured = _TextMetrics2.default.measureText(this._text, this._style, this._style.wordWrap, this.canvas); + var width = measured.width; + var height = measured.height; + var lines = measured.lines; + var lineHeight = measured.lineHeight; + var lineWidths = measured.lineWidths; + var maxLineWidth = measured.maxLineWidth; + var fontProperties = measured.fontProperties; + + this.canvas.width = Math.ceil((Math.max(1, width) + style.padding * 2) * this.resolution); + this.canvas.height = Math.ceil((Math.max(1, height) + style.padding * 2) * this.resolution); + + context.scale(this.resolution, this.resolution); + + context.clearRect(0, 0, this.canvas.width, this.canvas.height); + + context.font = this._font; + context.strokeStyle = style.stroke; + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + + var linePositionX = void 0; + var linePositionY = void 0; + + if (style.dropShadow) { + context.fillStyle = style.dropShadowColor; + context.globalAlpha = style.dropShadowAlpha; + context.shadowBlur = style.dropShadowBlur; + + if (style.dropShadowBlur > 0) { + context.shadowColor = style.dropShadowColor; + } + + var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + + for (var i = 0; i < lines.length; i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (style.fill) { + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); + + if (style.stroke && style.strokeThickness) { + context.strokeStyle = style.dropShadowColor; + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding, true); + context.strokeStyle = style.stroke; + } + } + } + } + + // reset the shadow blur and alpha that was set by the drop shadow, for the regular text + context.shadowBlur = 0; + context.globalAlpha = 1; + + // set canvas text styles + context.fillStyle = this._generateFillStyle(style, lines); + + // draw lines line by line + for (var _i = 0; _i < lines.length; _i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i]) / 2; + } + + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding, true); + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding); + } + } + + this.updateTexture(); + }; + + /** + * Render the text with letter-spacing. + * @param {string} text - The text to draw + * @param {number} x - Horizontal position to draw the text + * @param {number} y - Vertical position to draw the text + * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + * @private + */ + + + Text.prototype.drawLetterSpacing = function drawLetterSpacing(text, x, y) { + var isStroke = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var style = this._style; + + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + + if (letterSpacing === 0) { + if (isStroke) { + this.context.strokeText(text, x, y); + } else { + this.context.fillText(text, x, y); + } + + return; + } + + var characters = String.prototype.split.call(text, ''); + var currentPosition = x; + var index = 0; + var current = ''; + + while (index < text.length) { + current = characters[index++]; + if (isStroke) { + this.context.strokeText(current, currentPosition, y); + } else { + this.context.fillText(current, currentPosition, y); + } + currentPosition += this.context.measureText(current).width + letterSpacing; + } + }; + + /** + * Updates texture size based on canvas size + * + * @private + */ + + + Text.prototype.updateTexture = function updateTexture() { + var canvas = this.canvas; + + if (this._style.trim) { + var trimmed = (0, _trimCanvas2.default)(canvas); + + if (trimmed.data) { + canvas.width = trimmed.width; + canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } + } + + var texture = this._texture; + var style = this._style; + var padding = style.trim ? 0 : style.padding; + var baseTexture = texture.baseTexture; + + baseTexture.hasLoaded = true; + baseTexture.resolution = this.resolution; + + baseTexture.realWidth = canvas.width; + baseTexture.realHeight = canvas.height; + baseTexture.width = canvas.width / this.resolution; + baseTexture.height = canvas.height / this.resolution; + + texture.trim.width = texture._frame.width = canvas.width / this.resolution; + texture.trim.height = texture._frame.height = canvas.height / this.resolution; + texture.trim.x = -padding; + texture.trim.y = -padding; + + texture.orig.width = texture._frame.width - padding * 2; + texture.orig.height = texture._frame.height - padding * 2; + + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + + baseTexture.emit('update', baseTexture); + + this.dirty = false; + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Text.prototype.renderWebGL = function renderWebGL(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype.renderWebGL.call(this, renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Text.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype._renderCanvas.call(this, renderer); + }; + + /** + * Gets the local bounds of the text object. + * + * @param {Rectangle} rect - The output rectangle. + * @return {Rectangle} The bounds. + */ + + + Text.prototype.getLocalBounds = function getLocalBounds(rect) { + this.updateText(true); + + return _Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + */ + + + Text.prototype._calculateBounds = function _calculateBounds() { + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; + + /** + * Method to be called upon a TextStyle change. + * @private + */ + + + Text.prototype._onStyleChange = function _onStyleChange() { + this.dirty = true; + }; + + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * + * @private + * @param {object} style - The style. + * @param {string[]} lines - The lines of text. + * @return {string|number|CanvasGradient} The fill style + */ + + + Text.prototype._generateFillStyle = function _generateFillStyle(style, lines) { + if (!Array.isArray(style.fill)) { + return style.fill; + } + + // cocoon on canvas+ cannot generate textures, so use the first colour instead + if (navigator.isCocoonJS) { + return style.fill[0]; + } + + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient = void 0; + var totalIterations = void 0; + var currentIteration = void 0; + var stop = void 0; + + var width = this.canvas.width / this.resolution; + var height = this.canvas.height / this.resolution; + + // make a copy of the style settings, so we can manipulate them later + var fill = style.fill.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(style.fill[0]); + fillGradientStops.unshift(0); + + fill.push(style.fill[style.fill.length - 1]); + fillGradientStops.push(1); + + if (style.fillGradientType === _const.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); + + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + totalIterations = (fill.length + 1) * lines.length; + currentIteration = 0; + for (var _i2 = 0; _i2 < lines.length; _i2++) { + currentIteration += 1; + for (var j = 0; j < fill.length; j++) { + if (typeof fillGradientStops[j] === 'number') { + stop = fillGradientStops[j] / lines.length + _i2 / lines.length; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[j]); + currentIteration++; + } + } + } else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); + + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + totalIterations = fill.length + 1; + currentIteration = 1; + + for (var _i3 = 0; _i3 < fill.length; _i3++) { + if (typeof fillGradientStops[_i3] === 'number') { + stop = fillGradientStops[_i3]; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[_i3]); + currentIteration++; + } + } + + return gradient; + }; + + /** + * Destroys this text object. + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majority of the time the texture will not be shared with any other Sprites. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well + */ + + + Text.prototype.destroy = function destroy(options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + + options = Object.assign({}, defaultDestroyOptions, options); + + _Sprite.prototype.destroy.call(this, options); + + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + + this._style = null; + }; + + /** + * The width of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Text, [{ + key: 'width', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * Set the style of the text. Set up an event listener to listen for changes on the style + * object and mark the text as dirty. + * + * @member {object|PIXI.TextStyle} + */ + + }, { + key: 'style', + get: function get() { + return this._style; + }, + set: function set(style) // eslint-disable-line require-jsdoc + { + style = style || {}; + + if (style instanceof _TextStyle2.default) { + this._style = style; + } else { + this._style = new _TextStyle2.default(style); + } + + this.localStyleID = -1; + this.dirty = true; + } + + /** + * Set the copy for the text object. To split a line you can use '\n'. + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(text) // eslint-disable-line require-jsdoc + { + text = String(text === '' || text === null || text === undefined ? ' ' : text); + + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + } + }]); + + return Text; +}(_Sprite3.default); + +exports.default = Text; + +},{"../const":46,"../math":70,"../settings":101,"../sprites/Sprite":102,"../textures/Texture":115,"../utils":125,"../utils/trimCanvas":130,"./TextMetrics":109,"./TextStyle":110}],109:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The TextMetrics object represents the measurement of a block of text with a specified style. + * + * ```js + * let style = new PIXI.TextStyle({fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}) + * let textMetrics = PIXI.TextMetrics.measureText('Your text', style) + * ``` + * + * @class + * @memberOf PIXI + */ +var TextMetrics = function () { + /** + * @param {string} text - the text that was measured + * @param {PIXI.TextStyle} style - the style that was measured + * @param {number} width - the measured width of the text + * @param {number} height - the measured height of the text + * @param {array} lines - an array of the lines of text broken by new lines and wrapping if specified in style + * @param {array} lineWidths - an array of the line widths for each line matched to `lines` + * @param {number} lineHeight - the measured line height for this style + * @param {number} maxLineWidth - the maximum line width for all measured lines + * @param {Object} fontProperties - the font properties object from TextMetrics.measureFont + */ + function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) { + _classCallCheck(this, TextMetrics); + + this.text = text; + this.style = style; + this.width = width; + this.height = height; + this.lines = lines; + this.lineWidths = lineWidths; + this.lineHeight = lineHeight; + this.maxLineWidth = maxLineWidth; + this.fontProperties = fontProperties; + } + + /** + * Measures the supplied string of text and returns a Rectangle. + * + * @param {string} text - the text to measure. + * @param {PIXI.TextStyle} style - the text style to use for measuring + * @param {boolean} [wordWrap] - optional override for if word-wrap should be applied to the text. + * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. + * @return {PIXI.TextMetrics} measured width and height of the text. + */ + + + TextMetrics.measureText = function measureText(text, style, wordWrap) { + var canvas = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : TextMetrics._canvas; + + wordWrap = wordWrap === undefined || wordWrap === null ? style.wordWrap : wordWrap; + var font = style.toFontString(); + var fontProperties = TextMetrics.measureFont(font); + var context = canvas.getContext('2d'); + + context.font = font; + + var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text; + var lines = outputText.split(/(?:\r\n|\r|\n)/); + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + + for (var i = 0; i < lines.length; i++) { + var lineWidth = context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing; + + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + var width = maxLineWidth + style.strokeThickness; + + if (style.dropShadow) { + width += style.dropShadowDistance; + } + + var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * (lineHeight + style.leading); + + if (style.dropShadow) { + height += style.dropShadowDistance; + } + + return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties); + }; + + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @private + * @param {string} text - String to apply word wrapping to + * @param {PIXI.TextStyle} style - the style to use when wrapping + * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. + * @return {string} New string with new lines applied where required + */ + + + TextMetrics.wordWrap = function wordWrap(text, style) { + var canvas = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : TextMetrics._canvas; + + var context = canvas.getContext('2d'); + + var width = 0; + var line = ''; + var lines = ''; + + var cache = {}; + var letterSpacing = style.letterSpacing, + whiteSpace = style.whiteSpace; + + // How to handle whitespaces + + var collapseSpaces = TextMetrics.collapseSpaces(whiteSpace); + var collapseNewlines = TextMetrics.collapseNewlines(whiteSpace); + + // whether or not spaces may be added to the beginning of lines + var canPrependSpaces = !collapseSpaces; + + // There is letterSpacing after every char except the last one + // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_! + // so for convenience the above needs to be compared to width + 1 extra letterSpace + // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_ + // ________________________________________________ + // And then the final space is simply no appended to each line + var wordWrapWidth = style.wordWrapWidth + letterSpacing; + + // break text into words, spaces and newline chars + var tokens = TextMetrics.tokenize(text); + + for (var i = 0; i < tokens.length; i++) { + // get the word, space or newlineChar + var token = tokens[i]; + + // if word is a new line + if (TextMetrics.isNewline(token)) { + // keep the new line + if (!collapseNewlines) { + lines += TextMetrics.addLine(line); + canPrependSpaces = !collapseSpaces; + line = ''; + width = 0; + continue; + } + + // if we should collapse new lines + // we simply convert it into a space + token = ' '; + } + + // if we should collapse repeated whitespaces + if (collapseSpaces) { + // check both this and the last tokens for spaces + var currIsBreakingSpace = TextMetrics.isBreakingSpace(token); + var lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]); + + if (currIsBreakingSpace && lastIsBreakingSpace) { + continue; + } + } + + // get word width from cache if possible + var tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context); + + // word is longer than desired bounds + if (tokenWidth > wordWrapWidth) { + // if we are not already at the beginning of a line + if (line !== '') { + // start newlines for overflow words + lines += TextMetrics.addLine(line); + line = ''; + width = 0; + } + + // break large word over multiple lines + if (TextMetrics.canBreakWords(token, style.breakWords)) { + // break word into characters + var characters = token.split(''); + + // loop the characters + for (var j = 0; j < characters.length; j++) { + var char = characters[j]; + + var k = 1; + // we are not at the end of the token + + while (characters[j + k]) { + var nextChar = characters[j + k]; + var lastChar = char[char.length - 1]; + + // should not split chars + if (!TextMetrics.canBreakChars(lastChar, nextChar, token, j, style.breakWords)) { + // combine chars & move forward one + char += nextChar; + } else { + break; + } + + k++; + } + + j += char.length - 1; + + var characterWidth = TextMetrics.getFromCache(char, letterSpacing, cache, context); + + if (characterWidth + width > wordWrapWidth) { + lines += TextMetrics.addLine(line); + canPrependSpaces = false; + line = ''; + width = 0; + } + + line += char; + width += characterWidth; + } + } + + // run word out of the bounds + else { + // if there are words in this line already + // finish that line and start a new one + if (line.length > 0) { + lines += TextMetrics.addLine(line); + line = ''; + width = 0; + } + + var isLastToken = i === tokens.length - 1; + + // give it its own line if it's not the end + lines += TextMetrics.addLine(token, !isLastToken); + canPrependSpaces = false; + line = ''; + width = 0; + } + } + + // word could fit + else { + // word won't fit because of existing words + // start a new line + if (tokenWidth + width > wordWrapWidth) { + // if its a space we don't want it + canPrependSpaces = false; + + // add a new line + lines += TextMetrics.addLine(line); + + // start a new line + line = ''; + width = 0; + } + + // don't add spaces to the beginning of lines + if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces) { + // add the word to the current line + line += token; + + // update width counter + width += tokenWidth; + } + } + } + + lines += TextMetrics.addLine(line, false); + + return lines; + }; + + /** + * Convienience function for logging each line added during the wordWrap + * method + * + * @private + * @param {string} line - The line of text to add + * @param {boolean} newLine - Add new line character to end + * @return {string} A formatted line + */ + + + TextMetrics.addLine = function addLine(line) { + var newLine = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + + line = TextMetrics.trimRight(line); + + line = newLine ? line + '\n' : line; + + return line; + }; + + /** + * Gets & sets the widths of calculated characters in a cache object + * + * @private + * @param {string} key The key + * @param {number} letterSpacing The letter spacing + * @param {object} cache The cache + * @param {CanvasRenderingContext2D} context The canvas context + * @return {number} The from cache. + */ + + + TextMetrics.getFromCache = function getFromCache(key, letterSpacing, cache, context) { + var width = cache[key]; + + if (width === undefined) { + var spacing = key.length * letterSpacing; + + width = context.measureText(key).width + spacing; + cache[key] = width; + } + + return width; + }; + + /** + * Determines whether we should collapse breaking spaces + * + * @private + * @param {string} whiteSpace The TextStyle property whiteSpace + * @return {boolean} should collapse + */ + + + TextMetrics.collapseSpaces = function collapseSpaces(whiteSpace) { + return whiteSpace === 'normal' || whiteSpace === 'pre-line'; + }; + + /** + * Determines whether we should collapse newLine chars + * + * @private + * @param {string} whiteSpace The white space + * @return {boolean} should collapse + */ + + + TextMetrics.collapseNewlines = function collapseNewlines(whiteSpace) { + return whiteSpace === 'normal'; + }; + + /** + * trims breaking whitespaces from string + * + * @private + * @param {string} text The text + * @return {string} trimmed string + */ + + + TextMetrics.trimRight = function trimRight(text) { + if (typeof text !== 'string') { + return ''; + } + + for (var i = text.length - 1; i >= 0; i--) { + var char = text[i]; + + if (!TextMetrics.isBreakingSpace(char)) { + break; + } + + text = text.slice(0, -1); + } + + return text; + }; + + /** + * Determines if char is a newline. + * + * @private + * @param {string} char The character + * @return {boolean} True if newline, False otherwise. + */ + + + TextMetrics.isNewline = function isNewline(char) { + if (typeof char !== 'string') { + return false; + } + + return TextMetrics._newlines.indexOf(char.charCodeAt(0)) >= 0; + }; + + /** + * Determines if char is a breaking whitespace. + * + * @private + * @param {string} char The character + * @return {boolean} True if whitespace, False otherwise. + */ + + + TextMetrics.isBreakingSpace = function isBreakingSpace(char) { + if (typeof char !== 'string') { + return false; + } + + return TextMetrics._breakingSpaces.indexOf(char.charCodeAt(0)) >= 0; + }; + + /** + * Splits a string into words, breaking-spaces and newLine characters + * + * @private + * @param {string} text The text + * @return {array} A tokenized array + */ + + + TextMetrics.tokenize = function tokenize(text) { + var tokens = []; + var token = ''; + + if (typeof text !== 'string') { + return tokens; + } + + for (var i = 0; i < text.length; i++) { + var char = text[i]; + + if (TextMetrics.isBreakingSpace(char) || TextMetrics.isNewline(char)) { + if (token !== '') { + tokens.push(token); + token = ''; + } + + tokens.push(char); + + continue; + } + + token += char; + } + + if (token !== '') { + tokens.push(token); + } + + return tokens; + }; + + /** + * This method exists to be easily overridden + * It allows one to customise which words should break + * Examples are if the token is CJK or numbers. + * It must return a boolean. + * + * @private + * @param {string} token The token + * @param {boolean} breakWords The style attr break words + * @return {boolean} whether to break word or not + */ + + + TextMetrics.canBreakWords = function canBreakWords(token, breakWords) { + return breakWords; + }; + + /** + * This method exists to be easily overridden + * It allows one to determine whether a pair of characters + * should be broken by newlines + * For example certain characters in CJK langs or numbers. + * It must return a boolean. + * + * @private + * @param {string} char The character + * @param {string} nextChar The next character + * @param {string} token The token/word the characters are from + * @param {number} index The index in the token of the char + * @param {boolean} breakWords The style attr break words + * @return {boolean} whether to break word or not + */ + + + TextMetrics.canBreakChars = function canBreakChars(char, nextChar, token, index, breakWords) // eslint-disable-line no-unused-vars + { + return true; + }; + + /** + * Calculates the ascent, descent and fontSize of a given font-style + * + * @static + * @param {string} font - String representing the style of the font + * @return {PIXI.TextMetrics~FontMetrics} Font properties object + */ + + + TextMetrics.measureFont = function measureFont(font) { + // as this method is used for preparing assets, don't recalculate things if we don't need to + if (TextMetrics._fonts[font]) { + return TextMetrics._fonts[font]; + } + + var properties = {}; + + var canvas = TextMetrics._canvas; + var context = TextMetrics._context; + + context.font = font; + + var metricsString = TextMetrics.METRICS_STRING + TextMetrics.BASELINE_SYMBOL; + var width = Math.ceil(context.measureText(metricsString).width); + var baseline = Math.ceil(context.measureText(TextMetrics.BASELINE_SYMBOL).width); + var height = 2 * baseline; + + baseline = baseline * TextMetrics.BASELINE_MULTIPLIER | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = font; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText(metricsString, 0, baseline); + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i = 0; + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } else { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var _j = 0; _j < line; _j += 4) { + if (imagedata[idx + _j] !== 255) { + stop = true; + break; + } + } + + if (!stop) { + idx -= line; + } else { + break; + } + } + + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + + TextMetrics._fonts[font] = properties; + + return properties; + }; + + /** + * Clear font metrics in metrics cache. + * + * @static + * @param {string} [font] - font name. If font name not set then clear cache for all fonts. + */ + + + TextMetrics.clearMetrics = function clearMetrics() { + var font = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + + if (font) { + delete TextMetrics._fonts[font]; + } else { + TextMetrics._fonts = {}; + } + }; + + return TextMetrics; +}(); + +/** + * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}. + * @class FontMetrics + * @memberof PIXI.TextMetrics~ + * @property {number} ascent - The ascent distance + * @property {number} descent - The descent distance + * @property {number} fontSize - Font size from ascent to descent + */ + +exports.default = TextMetrics; +var canvas = document.createElement('canvas'); + +canvas.width = canvas.height = 10; + +/** + * Cached canvas element for measuring text + * @memberof PIXI.TextMetrics + * @type {HTMLCanvasElement} + * @private + */ +TextMetrics._canvas = canvas; + +/** + * Cache for context to use. + * @memberof PIXI.TextMetrics + * @type {CanvasRenderingContext2D} + * @private + */ +TextMetrics._context = canvas.getContext('2d'); + +/** + * Cache of PIXI.TextMetrics~FontMetrics objects. + * @memberof PIXI.TextMetrics + * @type {Object} + * @private + */ +TextMetrics._fonts = {}; + +/** + * String used for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name METRICS_STRING + * @type {string} + * @default |Éq + */ +TextMetrics.METRICS_STRING = '|Éq'; + +/** + * Baseline symbol for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name BASELINE_SYMBOL + * @type {string} + * @default M + */ +TextMetrics.BASELINE_SYMBOL = 'M'; + +/** + * Baseline multiplier for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name BASELINE_MULTIPLIER + * @type {number} + * @default 1.4 + */ +TextMetrics.BASELINE_MULTIPLIER = 1.4; + +/** + * Cache of new line chars. + * @memberof PIXI.TextMetrics + * @type {number[]} + * @private + */ +TextMetrics._newlines = [0x000A, // line feed +0x000D]; + +/** + * Cache of breaking spaces. + * @memberof PIXI.TextMetrics + * @type {number[]} + * @private + */ +TextMetrics._breakingSpaces = [0x0009, // character tabulation +0x0020, // space +0x2000, // en quad +0x2001, // em quad +0x2002, // en space +0x2003, // em space +0x2004, // three-per-em space +0x2005, // four-per-em space +0x2006, // six-per-em space +0x2008, // punctuation space +0x2009, // thin space +0x200A, // hair space +0x205F, // medium mathematical space +0x3000]; + +},{}],110:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // disabling eslint for now, going to rewrite this in v5 +/* eslint-disable */ + +var _const = require('../const'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: 'black', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: _const.TEXT_GRADIENT.LINEAR_VERTICAL, + fillGradientStops: [], + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + trim: false, + whiteSpace: 'pre', + wordWrap: false, + wordWrapWidth: 100, + leading: 0 +}; + +var genericFontFamilies = ['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui']; + +/** + * A TextStyle Object decorates a Text Object. It can be shared between + * multiple Text objects. Changing the style will update all text objects using it. + * It can be generated [here](https://pixijs.io/pixi-text-style). + * + * @class + * @memberof PIXI + */ + +var TextStyle = function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string|number} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours + * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} + * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set + * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * @param {string|string[]} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', 800' or '900') + * @param {number} [style.leading=0] - The space between lines + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Possible values "miter" (creates a sharp corner), "round" (creates a round corner) or "bevel" + * (creates a squared corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {boolean} [style.trim=false] - Trim transparent borders + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {boolean} [style.whiteSpace='pre'] - Determines whether newlines & spaces are collapsed or preserved "normal" + * (collapse, collapse), "pre" (preserve, preserve) | "pre-line" (preserve, collapse). It needs wordWrap to be set to true + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + _classCallCheck(this, TextStyle); + + this.styleID = 0; + + this.reset(); + + deepCopyProperties(this, style, style); + } + + /** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return {PIXI.TextStyle} New cloned TextStyle object + */ + + + TextStyle.prototype.clone = function clone() { + var clonedProperties = {}; + + deepCopyProperties(clonedProperties, this, defaultStyle); + + return new TextStyle(clonedProperties); + }; + + /** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ + + + TextStyle.prototype.reset = function reset() { + deepCopyProperties(this, defaultStyle, defaultStyle); + }; + + /** + * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text + * + * @member {string} + */ + + + /** + * Generates a font style string to use for `TextMetrics.measureFont()`. + * + * @return {string} Font style string, for passing to `TextMetrics.measureFont()` + */ + TextStyle.prototype.toFontString = function toFontString() { + // build canvas api font setting from individual components. Convert a numeric this.fontSize to px + var fontSizeString = typeof this.fontSize === 'number' ? this.fontSize + 'px' : this.fontSize; + + // Clean-up fontFamily property by quoting each font name + // this will support font names with spaces + var fontFamilies = this.fontFamily; + + if (!Array.isArray(this.fontFamily)) { + fontFamilies = this.fontFamily.split(','); + } + + for (var i = fontFamilies.length - 1; i >= 0; i--) { + // Trim any extra white-space + var fontFamily = fontFamilies[i].trim(); + + // Check if font is already escaped in quotes except for CSS generic fonts + if (!/([\"\'])[^\'\"]+\1/.test(fontFamily) && genericFontFamilies.indexOf(fontFamily) < 0) { + fontFamily = '"' + fontFamily + '"'; + } + fontFamilies[i] = fontFamily; + } + + return this.fontStyle + ' ' + this.fontVariant + ' ' + this.fontWeight + ' ' + fontSizeString + ' ' + fontFamilies.join(','); + }; + + _createClass(TextStyle, [{ + key: 'align', + get: function get() { + return this._align; + }, + set: function set(align) // eslint-disable-line require-jsdoc + { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + } + + /** + * Indicates if lines can be wrapped within words, it needs wordWrap to be set to true + * + * @member {boolean} + */ + + }, { + key: 'breakWords', + get: function get() { + return this._breakWords; + }, + set: function set(breakWords) // eslint-disable-line require-jsdoc + { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + } + + /** + * Set a drop shadow for the text + * + * @member {boolean} + */ + + }, { + key: 'dropShadow', + get: function get() { + return this._dropShadow; + }, + set: function set(dropShadow) // eslint-disable-line require-jsdoc + { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + } + + /** + * Set alpha for the drop shadow + * + * @member {number} + */ + + }, { + key: 'dropShadowAlpha', + get: function get() { + return this._dropShadowAlpha; + }, + set: function set(dropShadowAlpha) // eslint-disable-line require-jsdoc + { + if (this._dropShadowAlpha !== dropShadowAlpha) { + this._dropShadowAlpha = dropShadowAlpha; + this.styleID++; + } + } + + /** + * Set a angle of the drop shadow + * + * @member {number} + */ + + }, { + key: 'dropShadowAngle', + get: function get() { + return this._dropShadowAngle; + }, + set: function set(dropShadowAngle) // eslint-disable-line require-jsdoc + { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + } + + /** + * Set a shadow blur radius + * + * @member {number} + */ + + }, { + key: 'dropShadowBlur', + get: function get() { + return this._dropShadowBlur; + }, + set: function set(dropShadowBlur) // eslint-disable-line require-jsdoc + { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + } + + /** + * A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * + * @member {string|number} + */ + + }, { + key: 'dropShadowColor', + get: function get() { + return this._dropShadowColor; + }, + set: function set(dropShadowColor) // eslint-disable-line require-jsdoc + { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + } + + /** + * Set a distance of the drop shadow + * + * @member {number} + */ + + }, { + key: 'dropShadowDistance', + get: function get() { + return this._dropShadowDistance; + }, + set: function set(dropShadowDistance) // eslint-disable-line require-jsdoc + { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + } + + /** + * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'. + * Can be an array to create a gradient eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * + * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern} + */ + + }, { + key: 'fill', + get: function get() { + return this._fill; + }, + set: function set(fill) // eslint-disable-line require-jsdoc + { + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + } + + /** + * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient. + * See {@link PIXI.TEXT_GRADIENT} + * + * @member {number} + */ + + }, { + key: 'fillGradientType', + get: function get() { + return this._fillGradientType; + }, + set: function set(fillGradientType) // eslint-disable-line require-jsdoc + { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + } + + /** + * If fill is an array of colours to create a gradient, this array can set the stop points + * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * + * @member {number[]} + */ + + }, { + key: 'fillGradientStops', + get: function get() { + return this._fillGradientStops; + }, + set: function set(fillGradientStops) // eslint-disable-line require-jsdoc + { + if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { + this._fillGradientStops = fillGradientStops; + this.styleID++; + } + } + + /** + * The font family + * + * @member {string|string[]} + */ + + }, { + key: 'fontFamily', + get: function get() { + return this._fontFamily; + }, + set: function set(fontFamily) // eslint-disable-line require-jsdoc + { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + } + + /** + * The font size + * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em') + * + * @member {number|string} + */ + + }, { + key: 'fontSize', + get: function get() { + return this._fontSize; + }, + set: function set(fontSize) // eslint-disable-line require-jsdoc + { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + } + + /** + * The font style + * ('normal', 'italic' or 'oblique') + * + * @member {string} + */ + + }, { + key: 'fontStyle', + get: function get() { + return this._fontStyle; + }, + set: function set(fontStyle) // eslint-disable-line require-jsdoc + { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + } + + /** + * The font variant + * ('normal' or 'small-caps') + * + * @member {string} + */ + + }, { + key: 'fontVariant', + get: function get() { + return this._fontVariant; + }, + set: function set(fontVariant) // eslint-disable-line require-jsdoc + { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + } + + /** + * The font weight + * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900') + * + * @member {string} + */ + + }, { + key: 'fontWeight', + get: function get() { + return this._fontWeight; + }, + set: function set(fontWeight) // eslint-disable-line require-jsdoc + { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + } + + /** + * The amount of spacing between letters, default is 0 + * + * @member {number} + */ + + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(letterSpacing) // eslint-disable-line require-jsdoc + { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + } + + /** + * The line height, a number that represents the vertical space that a letter uses + * + * @member {number} + */ + + }, { + key: 'lineHeight', + get: function get() { + return this._lineHeight; + }, + set: function set(lineHeight) // eslint-disable-line require-jsdoc + { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + } + + /** + * The space between lines + * + * @member {number} + */ + + }, { + key: 'leading', + get: function get() { + return this._leading; + }, + set: function set(leading) // eslint-disable-line require-jsdoc + { + if (this._leading !== leading) { + this._leading = leading; + this.styleID++; + } + } + + /** + * The lineJoin property sets the type of corner created, it can resolve spiked text issues. + * Default is 'miter' (creates a sharp corner). + * + * @member {string} + */ + + }, { + key: 'lineJoin', + get: function get() { + return this._lineJoin; + }, + set: function set(lineJoin) // eslint-disable-line require-jsdoc + { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + } + + /** + * The miter limit to use when using the 'miter' lineJoin mode + * This can reduce or increase the spikiness of rendered text. + * + * @member {number} + */ + + }, { + key: 'miterLimit', + get: function get() { + return this._miterLimit; + }, + set: function set(miterLimit) // eslint-disable-line require-jsdoc + { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + } + + /** + * Occasionally some fonts are cropped. Adding some padding will prevent this from happening + * by adding padding to all sides of the text. + * + * @member {number} + */ + + }, { + key: 'padding', + get: function get() { + return this._padding; + }, + set: function set(padding) // eslint-disable-line require-jsdoc + { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + } + + /** + * A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * + * @member {string|number} + */ + + }, { + key: 'stroke', + get: function get() { + return this._stroke; + }, + set: function set(stroke) // eslint-disable-line require-jsdoc + { + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + } + + /** + * A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * + * @member {number} + */ + + }, { + key: 'strokeThickness', + get: function get() { + return this._strokeThickness; + }, + set: function set(strokeThickness) // eslint-disable-line require-jsdoc + { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + } + + /** + * The baseline of the text that is rendered. + * + * @member {string} + */ + + }, { + key: 'textBaseline', + get: function get() { + return this._textBaseline; + }, + set: function set(textBaseline) // eslint-disable-line require-jsdoc + { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + } + + /** + * Trim transparent borders + * + * @member {boolean} + */ + + }, { + key: 'trim', + get: function get() { + return this._trim; + }, + set: function set(trim) // eslint-disable-line require-jsdoc + { + if (this._trim !== trim) { + this._trim = trim; + this.styleID++; + } + } + + /** + * How newlines and spaces should be handled. + * Default is 'pre' (preserve, preserve). + * + * value | New lines | Spaces + * --- | --- | --- + * 'normal' | Collapse | Collapse + * 'pre' | Preserve | Preserve + * 'pre-line' | Preserve | Collapse + * + * @member {string} + */ + + }, { + key: 'whiteSpace', + get: function get() { + return this._whiteSpace; + }, + set: function set(whiteSpace) // eslint-disable-line require-jsdoc + { + if (this._whiteSpace !== whiteSpace) { + this._whiteSpace = whiteSpace; + this.styleID++; + } + } + + /** + * Indicates if word wrap should be used + * + * @member {boolean} + */ + + }, { + key: 'wordWrap', + get: function get() { + return this._wordWrap; + }, + set: function set(wordWrap) // eslint-disable-line require-jsdoc + { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + } + + /** + * The width at which text will wrap, it needs wordWrap to be set to true + * + * @member {number} + */ + + }, { + key: 'wordWrapWidth', + get: function get() { + return this._wordWrapWidth; + }, + set: function set(wordWrapWidth) // eslint-disable-line require-jsdoc + { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + } + }]); + + return TextStyle; +}(); + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * @private + * @param {number|number[]} color + * @return {string} The color as a string. + */ + + +exports.default = TextStyle; +function getSingleColor(color) { + if (typeof color === 'number') { + return (0, _utils.hex2string)(color); + } else if (typeof color === 'string') { + if (color.indexOf('0x') === 0) { + color = color.replace('0x', '#'); + } + } + + return color; +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * @private + * @param {number|number[]} color + * @return {string} The color as a string. + */ +function getColor(color) { + if (!Array.isArray(color)) { + return getSingleColor(color); + } else { + for (var i = 0; i < color.length; ++i) { + color[i] = getSingleColor(color[i]); + } + + return color; + } +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * @private + * @param {Array} array1 First array to compare + * @param {Array} array2 Second array to compare + * @return {boolean} Do the arrays contain the same values in the same order + */ +function areArraysEqual(array1, array2) { + if (!Array.isArray(array1) || !Array.isArray(array2)) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } + + return true; +} + +/** + * Utility function to ensure that object properties are copied by value, and not by reference + * @private + * @param {Object} target Target object to copy properties into + * @param {Object} source Source object for the proporties to copy + * @param {string} propertyObj Object containing properties names we want to loop over + */ +function deepCopyProperties(target, source, propertyObj) { + for (var prop in propertyObj) { + if (Array.isArray(source[prop])) { + target[prop] = source[prop].slice(); + } else { + target[prop] = source[prop]; + } + } +} + +},{"../const":46,"../utils":125}],111:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let baseRenderTexture = new PIXI.BaseRenderTexture(renderer, 800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * baseRenderTexture.render(sprite); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let baseRenderTexture = new PIXI.BaseRenderTexture(100, 100); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var BaseRenderTexture = function (_BaseTexture) { + _inherits(BaseRenderTexture, _BaseTexture); + + /** + * @param {number} [width=100] - The width of the base render texture + * @param {number} [height=100] - The height of the base render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + */ + function BaseRenderTexture() { + var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + + _classCallCheck(this, BaseRenderTexture); + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, null, scaleMode)); + + _this.resolution = resolution || _settings2.default.RESOLUTION; + + _this.width = Math.ceil(width); + _this.height = Math.ceil(height); + + _this.realWidth = _this.width * _this.resolution; + _this.realHeight = _this.height * _this.resolution; + + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + _this.hasLoaded = true; + + /** + * A map of renderer IDs to webgl renderTargets + * + * @private + * @member {object} + */ + _this._glRenderTargets = {}; + + /** + * A reference to the canvas render target (we only need one as this can be shared across renderers) + * + * @private + * @member {object} + */ + _this._canvasRenderTarget = null; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + return _this; + } + + /** + * Resizes the BaseRenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + */ + + + BaseRenderTexture.prototype.resize = function resize(width, height) { + width = Math.ceil(width); + height = Math.ceil(height); + + if (width === this.width && height === this.height) { + return; + } + + this.valid = width > 0 && height > 0; + + this.width = width; + this.height = height; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + if (!this.valid) { + return; + } + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + */ + + + BaseRenderTexture.prototype.destroy = function destroy() { + _BaseTexture.prototype.destroy.call(this, true); + this.renderer = null; + }; + + return BaseRenderTexture; +}(_BaseTexture3.default); + +exports.default = BaseRenderTexture; + +},{"../settings":101,"./BaseTexture":112}],112:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var BaseTexture = function (_EventEmitter) { + _inherits(BaseTexture, _EventEmitter); + + /** + * @param {HTMLImageElement|HTMLCanvasElement} [source] - the source object of the texture. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture + */ + function BaseTexture(source, scaleMode, resolution) { + _classCallCheck(this, BaseTexture); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.uid = (0, _utils.uid)(); + + _this.touched = 0; + + /** + * The resolution / device pixel ratio of the texture + * + * @member {number} + * @default 1 + */ + _this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The width of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.width = 100; + + /** + * The height of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.height = 100; + + // TODO docs + // used to store the actual dimensions of the source + /** + * Used to store the actual width of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realWidth = 100; + /** + * Used to store the actual height of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realHeight = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Set to true once the base texture has successfully loaded. + * + * This is never true if the underlying source fails to load or has no texture data. + * + * @readonly + * @member {boolean} + */ + _this.hasLoaded = false; + + /** + * Set to true if the source is currently loading. + * + * If an Image source is loading the 'loaded' or 'error' event will be + * dispatched when the operation ends. An underyling source that is + * immediately-available bypasses loading entirely. + * + * @readonly + * @member {boolean} + */ + _this.isLoading = false; + + /** + * The image source that is used to create the texture. + * + * TODO: Make this a setter that calls loadSource(); + * + * @readonly + * @member {HTMLImageElement|HTMLCanvasElement} + */ + _this.source = null; // set in loadSource, if at all + + /** + * The image source that is used to create the texture. This is used to + * store the original Svg source when it is replaced with a canvas element. + * + * TODO: Currently not in use but could be used when re-scaling svg. + * + * @readonly + * @member {Image} + */ + _this.origSource = null; // set in loadSvg, if at all + + /** + * Type of image defined in source, eg. `png` or `svg` + * + * @readonly + * @member {string} + */ + _this.imageType = null; // set in updateImageType + + /** + * Scale for source image. Used with Svg images to scale them before rasterization. + * + * @readonly + * @member {number} + */ + _this.sourceScale = 1.0; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * All blend modes, and shaders written for default value. Change it on your own risk. + * + * @member {boolean} + * @default true + */ + _this.premultipliedAlpha = true; + + /** + * The image url of the texture + * + * @member {string} + */ + _this.imageUrl = null; + + /** + * Whether or not the texture is a power of two, try to use power of two textures as much + * as you can + * + * @private + * @member {boolean} + */ + _this.isPowerOfTwo = false; + + // used for webGL + + /** + * + * Set this to true if a mipmap of this texture needs to be generated. This value needs + * to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @member {boolean} + * @see PIXI.MIPMAP_TEXTURES + */ + _this.mipmap = _settings2.default.MIPMAP_TEXTURES; + + /** + * + * WebGL Texture wrap mode + * + * @member {number} + * @see PIXI.WRAP_MODES + */ + _this.wrapMode = _settings2.default.WRAP_MODE; + + /** + * A map of renderer IDs to webgl textures + * + * @private + * @member {object} + */ + _this._glTextures = {}; + + _this._enabled = 0; + _this._virtalBoundId = -1; + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + + /** + * The ids under which this BaseTexture has been added to the base texture cache. This is + * automatically set as long as BaseTexture.addToCache is used, but may not be set if a + * BaseTexture is added directly to the BaseTextureCache array. + * + * @member {string[]} + */ + _this.textureCacheIds = []; + + // if no source passed don't try to load + if (source) { + _this.loadSource(source); + } + + /** + * Fired when a not-immediately-available source finishes loading. + * + * @protected + * @event PIXI.BaseTexture#loaded + * @param {PIXI.BaseTexture} baseTexture - Resource loaded. + */ + + /** + * Fired when a not-immediately-available source fails to load. + * + * @protected + * @event PIXI.BaseTexture#error + * @param {PIXI.BaseTexture} baseTexture - Resource errored. + */ + + /** + * Fired when BaseTexture is updated. + * + * @protected + * @event PIXI.BaseTexture#update + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. + */ + + /** + * Fired when BaseTexture is destroyed. + * + * @protected + * @event PIXI.BaseTexture#dispose + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. + */ + return _this; + } + + /** + * Updates the texture on all the webgl renderers, this also assumes the src has changed. + * + * @fires PIXI.BaseTexture#update + */ + + + BaseTexture.prototype.update = function update() { + // Svg size is handled during load + if (this.imageType !== 'svg') { + this.realWidth = this.source.naturalWidth || this.source.videoWidth || this.source.width; + this.realHeight = this.source.naturalHeight || this.source.videoHeight || this.source.height; + + this._updateDimensions(); + } + + this.emit('update', this); + }; + + /** + * Update dimensions from real values + */ + + + BaseTexture.prototype._updateDimensions = function _updateDimensions() { + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + this.isPowerOfTwo = _bitTwiddle2.default.isPow2(this.realWidth) && _bitTwiddle2.default.isPow2(this.realHeight); + }; + + /** + * Load a source. + * + * If the source is not-immediately-available, such as an image that needs to be + * downloaded, then the 'loaded' or 'error' event will be dispatched in the future + * and `hasLoaded` will remain false after this call. + * + * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: + * + * if (texture.hasLoaded) { + * // texture ready for use + * } else if (texture.isLoading) { + * // listen to 'loaded' and/or 'error' events on texture + * } else { + * // not loading, not going to load UNLESS the source is reloaded + * // (it may still make sense to listen to the events) + * } + * + * @protected + * @param {HTMLImageElement|HTMLCanvasElement} source - the source object of the texture. + */ + + + BaseTexture.prototype.loadSource = function loadSource(source) { + var wasLoading = this.isLoading; + + this.hasLoaded = false; + this.isLoading = false; + + if (wasLoading && this.source) { + this.source.onload = null; + this.source.onerror = null; + } + + var firstSourceLoaded = !this.source; + + this.source = source; + + // Apply source if loaded. Otherwise setup appropriate loading monitors. + if ((source.src && source.complete || source.getContext) && source.width && source.height) { + this._updateImageType(); + + if (this.imageType === 'svg') { + this._loadSvgSource(); + } else { + this._sourceLoaded(); + } + + if (firstSourceLoaded) { + // send loaded event if previous source was null and we have been passed a pre-loaded IMG element + this.emit('loaded', this); + } + } else if (!source.getContext) { + // Image fail / not ready + this.isLoading = true; + + var scope = this; + + source.onload = function () { + scope._updateImageType(); + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope._sourceLoaded(); + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + scope.emit('loaded', scope); + }; + + source.onerror = function () { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope.emit('error', scope); + }; + + // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element + // "The value of `complete` can thus change while a script is executing." + // So complete needs to be re-checked after the callbacks have been added.. + // NOTE: complete will be true if the image has no src so best to check if the src is set. + if (source.complete && source.src) { + // ..and if we're complete now, no need for callbacks + source.onload = null; + source.onerror = null; + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + this.isLoading = false; + + if (source.width && source.height) { + this._sourceLoaded(); + + // If any previous subscribers possible + if (wasLoading) { + this.emit('loaded', this); + } + } + // If any previous subscribers possible + else if (wasLoading) { + this.emit('error', this); + } + } + } + }; + + /** + * Updates type of the source image. + */ + + + BaseTexture.prototype._updateImageType = function _updateImageType() { + if (!this.imageUrl) { + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + var imageType = void 0; + + if (dataUri && dataUri.mediaType === 'image') { + // Check for subType validity + var firstSubType = dataUri.subType.split('+')[0]; + + imageType = (0, _utils.getUrlFileExtension)('.' + firstSubType); + + if (!imageType) { + throw new Error('Invalid image type in data URI.'); + } + } else { + imageType = (0, _utils.getUrlFileExtension)(this.imageUrl); + + if (!imageType) { + imageType = 'png'; + } + } + + this.imageType = imageType; + }; + + /** + * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls + * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. + */ + + + BaseTexture.prototype._loadSvgSource = function _loadSvgSource() { + if (this.imageType !== 'svg') { + // Do nothing if source is not svg + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + + if (dataUri) { + this._loadSvgSourceUsingDataUri(dataUri); + } else { + // We got an URL, so we need to do an XHR to check the svg size + this._loadSvgSourceUsingXhr(); + } + }; + + /** + * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`. + * + * @param {string} dataUri - The data uri to load from. + */ + + + BaseTexture.prototype._loadSvgSourceUsingDataUri = function _loadSvgSourceUsingDataUri(dataUri) { + var svgString = void 0; + + if (dataUri.encoding === 'base64') { + if (!atob) { + throw new Error('Your browser doesn\'t support base64 conversions.'); + } + svgString = atob(dataUri.data); + } else { + svgString = dataUri.data; + } + + this._loadSvgSourceUsingString(svgString); + }; + + /** + * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. + */ + + + BaseTexture.prototype._loadSvgSourceUsingXhr = function _loadSvgSourceUsingXhr() { + var _this2 = this; + + var svgXhr = new XMLHttpRequest(); + + // This throws error on IE, so SVG Document can't be used + // svgXhr.responseType = 'document'; + + // This is not needed since we load the svg as string (breaks IE too) + // but overrideMimeType() can be used to force the response to be parsed as XML + // svgXhr.overrideMimeType('image/svg+xml'); + + svgXhr.onload = function () { + if (svgXhr.readyState !== svgXhr.DONE || svgXhr.status !== 200) { + throw new Error('Failed to load SVG using XHR.'); + } + + _this2._loadSvgSourceUsingString(svgXhr.response); + }; + + svgXhr.onerror = function () { + return _this2.emit('error', _this2); + }; + + svgXhr.open('GET', this.imageUrl, true); + svgXhr.send(); + }; + + /** + * Loads texture using an SVG string. The original SVG Image is stored as `origSource` and the + * created canvas is the new `source`. The SVG is scaled using `sourceScale`. Called by + * `_loadSvgSourceUsingXhr` or `_loadSvgSourceUsingDataUri`. + * + * @param {string} svgString SVG source as string + * + * @fires PIXI.BaseTexture#loaded + */ + + + BaseTexture.prototype._loadSvgSourceUsingString = function _loadSvgSourceUsingString(svgString) { + var svgSize = (0, _utils.getSvgSize)(svgString); + + var svgWidth = svgSize.width; + var svgHeight = svgSize.height; + + if (!svgWidth || !svgHeight) { + throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); + } + + // Scale realWidth and realHeight + this.realWidth = Math.round(svgWidth * this.sourceScale); + this.realHeight = Math.round(svgHeight * this.sourceScale); + + this._updateDimensions(); + + // Create a canvas element + var canvas = document.createElement('canvas'); + + canvas.width = this.realWidth; + canvas.height = this.realHeight; + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + + // Draw the Svg to the canvas + canvas.getContext('2d').drawImage(this.source, 0, 0, svgWidth, svgHeight, 0, 0, this.realWidth, this.realHeight); + + // Replace the original source image with the canvas + this.origSource = this.source; + this.source = canvas; + + // Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`) + BaseTexture.addToCache(this, canvas._pixiId); + + this.isLoading = false; + this._sourceLoaded(); + this.emit('loaded', this); + }; + + /** + * Used internally to update the width, height, and some other tracking vars once + * a source has successfully loaded. + * + * @private + */ + + + BaseTexture.prototype._sourceLoaded = function _sourceLoaded() { + this.hasLoaded = true; + this.update(); + }; + + /** + * Destroys this base texture + * + */ + + + BaseTexture.prototype.destroy = function destroy() { + if (this.imageUrl) { + delete _utils.TextureCache[this.imageUrl]; + + this.imageUrl = null; + + if (!navigator.isCocoonJS) { + this.source.src = ''; + } + } + + this.source = null; + + this.dispose(); + + BaseTexture.removeFromCache(this); + this.textureCacheIds = null; + + this._destroyed = true; + }; + + /** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + * @fires PIXI.BaseTexture#dispose + */ + + + BaseTexture.prototype.dispose = function dispose() { + this.emit('dispose', this); + }; + + /** + * Changes the source image of the texture. + * The original source must be an Image element. + * + * @param {string} newSrc - the path of the image + */ + + + BaseTexture.prototype.updateSourceImage = function updateSourceImage(newSrc) { + this.source.src = newSrc; + + this.loadSource(this.source); + }; + + /** + * Helper function that creates a base texture from the given image url. + * If the image is not in the base texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + // new Image() breaks tex loading in some versions of Chrome. + // See https://code.google.com/p/chromium/issues/detail?id=238071 + var image = new Image(); // document.createElement('img'); + + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + image.crossOrigin = (0, _determineCrossOrigin2.default)(imageUrl); + } else if (crossorigin) { + image.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; + } + + baseTexture = new BaseTexture(image, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + image.src = imageUrl; // Setting this triggers load + + BaseTexture.addToCache(baseTexture, imageUrl); + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @param {string} [origin='canvas'] - A string origin of who created the base texture + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode) { + var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; + + if (!canvas._pixiId) { + canvas._pixiId = origin + '_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[canvas._pixiId]; + + if (!baseTexture) { + baseTexture = new BaseTexture(canvas, scaleMode); + BaseTexture.addToCache(baseTexture, canvas._pixiId); + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture based on the source you provide. + * The source can be - image url, image element, canvas element. If the + * source is an image url or an image element and not in the base texture + * cache, it will be created and loaded. + * + * @static + * @param {string|HTMLImageElement|HTMLCanvasElement} source - The source to create base texture from. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.from = function from(source, scaleMode, sourceScale) { + if (typeof source === 'string') { + return BaseTexture.fromImage(source, undefined, scaleMode, sourceScale); + } else if (source instanceof HTMLImageElement) { + var imageUrl = source.src; + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + baseTexture = new BaseTexture(source, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + BaseTexture.addToCache(baseTexture, imageUrl); + } + + return baseTexture; + } else if (source instanceof HTMLCanvasElement) { + return BaseTexture.fromCanvas(source, scaleMode); + } + + // lets assume its a base texture! + return source; + }; + + /** + * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache. + * @param {string} id - The id that the BaseTexture will be stored against. + */ + + + BaseTexture.addToCache = function addToCache(baseTexture, id) { + if (id) { + if (baseTexture.textureCacheIds.indexOf(id) === -1) { + baseTexture.textureCacheIds.push(id); + } + + /* eslint-disable no-console */ + if (_utils.BaseTextureCache[id]) { + console.warn('BaseTexture added to the cache with an id [' + id + '] that already had an entry'); + } + /* eslint-enable no-console */ + + _utils.BaseTextureCache[id] = baseTexture; + } + }; + + /** + * Remove a BaseTexture from the global BaseTextureCache. + * + * @static + * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself. + * @return {PIXI.BaseTexture|null} The BaseTexture that was removed. + */ + + + BaseTexture.removeFromCache = function removeFromCache(baseTexture) { + if (typeof baseTexture === 'string') { + var baseTextureFromCache = _utils.BaseTextureCache[baseTexture]; + + if (baseTextureFromCache) { + var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); + + if (index > -1) { + baseTextureFromCache.textureCacheIds.splice(index, 1); + } + + delete _utils.BaseTextureCache[baseTexture]; + + return baseTextureFromCache; + } + } else if (baseTexture && baseTexture.textureCacheIds) { + for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { + delete _utils.BaseTextureCache[baseTexture.textureCacheIds[i]]; + } + + baseTexture.textureCacheIds.length = 0; + + return baseTexture; + } + + return null; + }; + + return BaseTexture; +}(_eventemitter2.default); + +exports.default = BaseTexture; + +},{"../settings":101,"../utils":125,"../utils/determineCrossOrigin":124,"bit-twiddle":1,"eventemitter3":3}],113:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseRenderTexture = require('./BaseRenderTexture'); + +var _BaseRenderTexture2 = _interopRequireDefault(_BaseRenderTexture); + +var _Texture2 = require('./Texture'); + +var _Texture3 = _interopRequireDefault(_Texture2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024, { view: canvas, ratio: 1 }); + * let renderTexture = PIXI.RenderTexture.create(800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let renderTexture = new PIXI.RenderTexture.create(100, 100); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.Texture + * @memberof PIXI + */ +var RenderTexture = function (_Texture) { + _inherits(RenderTexture, _Texture); + + /** + * @param {PIXI.BaseRenderTexture} baseRenderTexture - The renderer used for this RenderTexture + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + */ + function RenderTexture(baseRenderTexture, frame) { + _classCallCheck(this, RenderTexture); + + // support for legacy.. + var _legacyRenderer = null; + + if (!(baseRenderTexture instanceof _BaseRenderTexture2.default)) { + /* eslint-disable prefer-rest-params, no-console */ + var width = arguments[1]; + var height = arguments[2]; + var scaleMode = arguments[3]; + var resolution = arguments[4]; + + // we have an old render texture.. + console.warn('Please use RenderTexture.create(' + width + ', ' + height + ') instead of the ctor directly.'); + _legacyRenderer = arguments[0]; + /* eslint-enable prefer-rest-params, no-console */ + + frame = null; + baseRenderTexture = new _BaseRenderTexture2.default(width, height, scaleMode, resolution); + } + + /** + * The base texture object that this texture uses + * + * @member {BaseTexture} + */ + + var _this = _possibleConstructorReturn(this, _Texture.call(this, baseRenderTexture, frame)); + + _this.legacyRenderer = _legacyRenderer; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = true; + + _this._updateUvs(); + return _this; + } + + /** + * Resizes the RenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + * @param {boolean} doNotResizeBaseTexture - Should the baseTexture.width and height values be resized as well? + */ + + + RenderTexture.prototype.resize = function resize(width, height, doNotResizeBaseTexture) { + width = Math.ceil(width); + height = Math.ceil(height); + + // TODO - could be not required.. + this.valid = width > 0 && height > 0; + + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + + if (!doNotResizeBaseTexture) { + this.baseTexture.resize(width, height); + } + + this._updateUvs(); + }; + + /** + * A short hand way of creating a render texture. + * + * @param {number} [width=100] - The width of the render texture + * @param {number} [height=100] - The height of the render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.RenderTexture} The new render texture + */ + + + RenderTexture.create = function create(width, height, scaleMode, resolution) { + return new RenderTexture(new _BaseRenderTexture2.default(width, height, scaleMode, resolution)); + }; + + return RenderTexture; +}(_Texture3.default); + +exports.default = RenderTexture; + +},{"./BaseRenderTexture":111,"./Texture":115}],114:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _ = require('../'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Utility class for maintaining reference to a collection + * of Textures on a single Spritesheet. + * + * To access a sprite sheet from your code pass its JSON data file to Pixi's loader: + * + * ```js + * PIXI.loader.add("images/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.loader.resources["images/spritesheet.json"].spritesheet; + * ... + * } + * ``` + * With the `sheet.textures` you can create Sprite objects,`sheet.animations` can be used to create an AnimatedSprite. + * + * Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker}, + * {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}. + * Default anchor points (see {@link PIXI.Texture#defaultAnchor}) and grouping of animation sprites are currently only + * supported by TexturePacker. + * + * @class + * @memberof PIXI + */ +var Spritesheet = function () { + _createClass(Spritesheet, null, [{ + key: 'BATCH_SIZE', + + /** + * The maximum number of Textures to build per process. + * + * @type {number} + * @default 1000 + */ + get: function get() { + return 1000; + } + + /** + * @param {PIXI.BaseTexture} baseTexture Reference to the source BaseTexture object. + * @param {Object} data - Spritesheet image data. + * @param {string} [resolutionFilename] - The filename to consider when determining + * the resolution of the spritesheet. If not provided, the imageUrl will + * be used on the BaseTexture. + */ + + }]); + + function Spritesheet(baseTexture, data) { + var resolutionFilename = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + _classCallCheck(this, Spritesheet); + + /** + * Reference to ths source texture + * @type {PIXI.BaseTexture} + */ + this.baseTexture = baseTexture; + + /** + * A map containing all textures of the sprite sheet. + * Can be used to create a {@link PIXI.Sprite|Sprite}: + * ```js + * new PIXI.Sprite(sheet.textures["image.png"]); + * ``` + * @member {Object} + */ + this.textures = {}; + + /** + * A map containing the textures for each animation. + * Can be used to create an {@link PIXI.extras.AnimatedSprite|AnimatedSprite}: + * ```js + * new PIXI.extras.AnimatedSprite(sheet.animations["anim_name"]) + * ``` + * @member {Object} + */ + this.animations = {}; + + /** + * Reference to the original JSON data. + * @type {Object} + */ + this.data = data; + + /** + * The resolution of the spritesheet. + * @type {number} + */ + this.resolution = this._updateResolution(resolutionFilename || this.baseTexture.imageUrl); + + /** + * Map of spritesheet frames. + * @type {Object} + * @private + */ + this._frames = this.data.frames; + + /** + * Collection of frame names. + * @type {string[]} + * @private + */ + this._frameKeys = Object.keys(this._frames); + + /** + * Current batch index being processed. + * @type {number} + * @private + */ + this._batchIndex = 0; + + /** + * Callback when parse is completed. + * @type {Function} + * @private + */ + this._callback = null; + } + + /** + * Generate the resolution from the filename or fallback + * to the meta.scale field of the JSON data. + * + * @private + * @param {string} resolutionFilename - The filename to use for resolving + * the default resolution. + * @return {number} Resolution to use for spritesheet. + */ + + + Spritesheet.prototype._updateResolution = function _updateResolution(resolutionFilename) { + var scale = this.data.meta.scale; + + // Use a defaultValue of `null` to check if a url-based resolution is set + var resolution = (0, _utils.getResolutionOfUrl)(resolutionFilename, null); + + // No resolution found via URL + if (resolution === null) { + // Use the scale value or default to 1 + resolution = scale !== undefined ? parseFloat(scale) : 1; + } + + // For non-1 resolutions, update baseTexture + if (resolution !== 1) { + this.baseTexture.resolution = resolution; + this.baseTexture.update(); + } + + return resolution; + }; + + /** + * Parser spritesheet from loaded data. This is done asynchronously + * to prevent creating too many Texture within a single process. + * + * @param {Function} callback - Callback when complete returns + * a map of the Textures for this spritesheet. + */ + + + Spritesheet.prototype.parse = function parse(callback) { + this._batchIndex = 0; + this._callback = callback; + + if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) { + this._processFrames(0); + this._processAnimations(); + this._parseComplete(); + } else { + this._nextBatch(); + } + }; + + /** + * Process a batch of frames + * + * @private + * @param {number} initialFrameIndex - The index of frame to start. + */ + + + Spritesheet.prototype._processFrames = function _processFrames(initialFrameIndex) { + var frameIndex = initialFrameIndex; + var maxFrames = Spritesheet.BATCH_SIZE; + var sourceScale = this.baseTexture.sourceScale; + + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { + var i = this._frameKeys[frameIndex]; + var data = this._frames[i]; + var rect = data.frame; + + if (rect) { + var frame = null; + var trim = null; + var sourceSize = data.trimmed !== false && data.sourceSize ? data.sourceSize : data.frame; + + var orig = new _.Rectangle(0, 0, Math.floor(sourceSize.w * sourceScale) / this.resolution, Math.floor(sourceSize.h * sourceScale) / this.resolution); + + if (data.rotated) { + frame = new _.Rectangle(Math.floor(rect.x * sourceScale) / this.resolution, Math.floor(rect.y * sourceScale) / this.resolution, Math.floor(rect.h * sourceScale) / this.resolution, Math.floor(rect.w * sourceScale) / this.resolution); + } else { + frame = new _.Rectangle(Math.floor(rect.x * sourceScale) / this.resolution, Math.floor(rect.y * sourceScale) / this.resolution, Math.floor(rect.w * sourceScale) / this.resolution, Math.floor(rect.h * sourceScale) / this.resolution); + } + + // Check to see if the sprite is trimmed + if (data.trimmed !== false && data.spriteSourceSize) { + trim = new _.Rectangle(Math.floor(data.spriteSourceSize.x * sourceScale) / this.resolution, Math.floor(data.spriteSourceSize.y * sourceScale) / this.resolution, Math.floor(rect.w * sourceScale) / this.resolution, Math.floor(rect.h * sourceScale) / this.resolution); + } + + this.textures[i] = new _.Texture(this.baseTexture, frame, orig, trim, data.rotated ? 2 : 0, data.anchor); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage functions + _.Texture.addToCache(this.textures[i], i); + } + + frameIndex++; + } + }; + + /** + * Parse animations config + * + * @private + */ + + + Spritesheet.prototype._processAnimations = function _processAnimations() { + var animations = this.data.animations || {}; + + for (var animName in animations) { + this.animations[animName] = []; + for (var _iterator = animations[animName], _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var frameName = _ref; + + this.animations[animName].push(this.textures[frameName]); + } + } + }; + + /** + * The parse has completed. + * + * @private + */ + + + Spritesheet.prototype._parseComplete = function _parseComplete() { + var callback = this._callback; + + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); + }; + + /** + * Begin the next batch of textures. + * + * @private + */ + + + Spritesheet.prototype._nextBatch = function _nextBatch() { + var _this = this; + + this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); + this._batchIndex++; + setTimeout(function () { + if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { + _this._nextBatch(); + } else { + _this._processAnimations(); + _this._parseComplete(); + } + }, 0); + }; + + /** + * Destroy Spritesheet and don't use after this. + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Spritesheet.prototype.destroy = function destroy() { + var destroyBase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + for (var i in this.textures) { + this.textures[i].destroy(); + } + this._frames = null; + this._frameKeys = null; + this.data = null; + this.textures = null; + if (destroyBase) { + this.baseTexture.destroy(); + } + this.baseTexture = null; + }; + + return Spritesheet; +}(); + +exports.default = Spritesheet; + +},{"../":65,"../utils":125}],115:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture = require('./BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _VideoBaseTexture = require('./VideoBaseTexture'); + +var _VideoBaseTexture2 = _interopRequireDefault(_VideoBaseTexture); + +var _TextureUvs = require('./TextureUvs'); + +var _TextureUvs2 = _interopRequireDefault(_TextureUvs); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided + * then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * let texture = PIXI.Texture.fromImage('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` + * + * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. + * You can check for this by checking the sprite's _textureID property. + * ```js + * var texture = PIXI.Texture.fromImage('assets/image.svg'); + * var sprite1 = new PIXI.Sprite(texture); + * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file + * ``` + * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var Texture = function (_EventEmitter) { + _inherits(Texture, _EventEmitter); + + /** + * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + * @param {PIXI.Rectangle} [orig] - The area of original texture + * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture + * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8} + * @param {PIXI.Point} [anchor] - Default anchor point used for sprite placement / rotation + */ + function Texture(baseTexture, frame, orig, trim, rotate, anchor) { + _classCallCheck(this, Texture); + + /** + * Does this Texture have any frame data assigned to it? + * + * @member {boolean} + */ + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.noFrame = false; + + if (!frame) { + _this.noFrame = true; + frame = new _math.Rectangle(0, 0, 1, 1); + } + + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @member {PIXI.BaseTexture} + */ + _this.baseTexture = baseTexture; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @member {PIXI.Rectangle} + */ + _this._frame = frame; + + /** + * This is the trimmed area of original texture, before it was put in atlas + * Please call `_updateUvs()` after you change coordinates of `trim` manually. + * + * @member {PIXI.Rectangle} + */ + _this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @member {boolean} + */ + _this.requiresUpdate = false; + + /** + * The WebGL UV data cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + _this._uvs = null; + + /** + * This is the area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + + _this._rotate = Number(rotate || 0); + + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); + } + + if (baseTexture.hasLoaded) { + if (_this.noFrame) { + frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + + // if there is no frame we should monitor for any base texture changes.. + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + _this.frame = frame; + } else { + baseTexture.once('loaded', _this.onBaseTextureLoaded, _this); + } + + /** + * Anchor point that is used as default if sprite is created with this texture. + * Changing the `defaultAnchor` at a later point of time will not update Sprite's anchor point. + * @member {PIXI.Point} + * @default {0,0} + */ + _this.defaultAnchor = anchor ? new _math.Point(anchor.x, anchor.y) : new _math.Point(0, 0); + + /** + * Fired when the texture is updated. This happens if the frame or the baseTexture is updated. + * + * @event PIXI.Texture#update + * @protected + * @param {PIXI.Texture} texture - Instance of texture being updated. + */ + + _this._updateID = 0; + + /** + * Contains data for uvs. May contain clamp settings and some matrices. + * Its a bit heavy, so by default that object is not created. + * @member {PIXI.TextureMatrix} + * @default null + */ + _this.transform = null; + + /** + * The ids under which this Texture has been added to the texture cache. This is + * automatically set as long as Texture.addToCache is used, but may not be set if a + * Texture is added directly to the TextureCache array. + * + * @member {string[]} + */ + _this.textureCacheIds = []; + return _this; + } + + /** + * Updates this texture on the gpu. + * + */ + + + Texture.prototype.update = function update() { + this.baseTexture.update(); + }; + + /** + * Called when the base texture is loaded + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureLoaded = function onBaseTextureLoaded(baseTexture) { + this._updateID++; + + // TODO this code looks confusing.. boo to abusing getters and setters! + if (this.noFrame) { + this.frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } else { + this.frame = this._frame; + } + + this.baseTexture.on('update', this.onBaseTextureUpdated, this); + this.emit('update', this); + }; + + /** + * Called when the base texture is updated + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated(baseTexture) { + this._updateID++; + + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Texture.prototype.destroy = function destroy(destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destroyed too.. + if (_utils.TextureCache[this.baseTexture.imageUrl]) { + Texture.removeFromCache(this.baseTexture.imageUrl); + } + + this.baseTexture.destroy(); + } + + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); + + this.baseTexture = null; + } + + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + + this.valid = false; + + Texture.removeFromCache(this); + this.textureCacheIds = null; + }; + + /** + * Creates a new texture object that acts the same as this one. + * + * @return {PIXI.Texture} The new texture + */ + + + Texture.prototype.clone = function clone() { + return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate); + }; + + /** + * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture. + */ + + + Texture.prototype._updateUvs = function _updateUvs() { + if (!this._uvs) { + this._uvs = new _TextureUvs2.default(); + } + + this._uvs.set(this._frame, this.baseTexture, this.rotate); + + this._updateID++; + }; + + /** + * Helper function that creates a Texture object from the given image url. + * If the image is not in the texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var texture = _utils.TextureCache[imageUrl]; + + if (!texture) { + texture = new Texture(_BaseTexture2.default.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); + Texture.addToCache(texture, imageUrl); + } + + return texture; + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return texture; + }; + + /** + * Helper function that creates a new Texture based on the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {string} [origin='canvas'] - A string origin of who created the base texture + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromCanvas = function fromCanvas(canvas, scaleMode) { + var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; + + return new Texture(_BaseTexture2.default.fromCanvas(canvas, scaleMode, origin)); + }; + + /** + * Helper function that creates a new Texture based on the given video element. + * + * @static + * @param {HTMLVideoElement|string} video - The URL or actual element of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideo = function fromVideo(video, scaleMode) { + if (typeof video === 'string') { + return Texture.fromVideoUrl(video, scaleMode); + } + + return new Texture(_VideoBaseTexture2.default.fromVideo(video, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the video url. + * + * @static + * @param {string} videoUrl - URL of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideoUrl = function fromVideoUrl(videoUrl, scaleMode) { + return new Texture(_VideoBaseTexture2.default.fromUrl(videoUrl, scaleMode)); + }; + + /** + * Helper function that creates a new Texture based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} + * source - Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.from = function from(source) { + // TODO auto detect cross origin.. + // TODO pass in scale mode? + if (typeof source === 'string') { + var texture = _utils.TextureCache[source]; + + if (!texture) { + // check if its a video.. + var isVideo = source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/) !== null; + + if (isVideo) { + return Texture.fromVideoUrl(source); + } + + return Texture.fromImage(source); + } + + return texture; + } else if (source instanceof HTMLImageElement) { + return new Texture(_BaseTexture2.default.from(source)); + } else if (source instanceof HTMLCanvasElement) { + return Texture.fromCanvas(source, _settings2.default.SCALE_MODE, 'HTMLCanvasElement'); + } else if (source instanceof HTMLVideoElement) { + return Texture.fromVideo(source); + } else if (source instanceof _BaseTexture2.default) { + return new Texture(source); + } + + // lets assume its a texture! + return source; + }; + + /** + * Create a texture from a source and add to the cache. + * + * @static + * @param {HTMLImageElement|HTMLCanvasElement} source - The input source. + * @param {String} imageUrl - File name of texture, for cache and resolving resolution. + * @param {String} [name] - Human readible name for the texture cache. If no name is + * specified, only `imageUrl` will be used as the cache ID. + * @return {PIXI.Texture} Output texture + */ + + + Texture.fromLoader = function fromLoader(source, imageUrl, name) { + var baseTexture = new _BaseTexture2.default(source, undefined, (0, _utils.getResolutionOfUrl)(imageUrl)); + var texture = new Texture(baseTexture); + + baseTexture.imageUrl = imageUrl; + + // No name, use imageUrl instead + if (!name) { + name = imageUrl; + } + + // lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions + _BaseTexture2.default.addToCache(texture.baseTexture, name); + Texture.addToCache(texture, name); + + // also add references by url if they are different. + if (name !== imageUrl) { + _BaseTexture2.default.addToCache(texture.baseTexture, imageUrl); + Texture.addToCache(texture, imageUrl); + } + + return texture; + }; + + /** + * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the Texture will be stored against. + */ + + + Texture.addToCache = function addToCache(texture, id) { + if (id) { + if (texture.textureCacheIds.indexOf(id) === -1) { + texture.textureCacheIds.push(id); + } + + /* eslint-disable no-console */ + if (_utils.TextureCache[id]) { + console.warn('Texture added to the cache with an id [' + id + '] that already had an entry'); + } + /* eslint-enable no-console */ + + _utils.TextureCache[id] = texture; + } + }; + + /** + * Remove a Texture from the global TextureCache. + * + * @static + * @param {string|PIXI.Texture} texture - id of a Texture to be removed, or a Texture instance itself + * @return {PIXI.Texture|null} The Texture that was removed + */ + + + Texture.removeFromCache = function removeFromCache(texture) { + if (typeof texture === 'string') { + var textureFromCache = _utils.TextureCache[texture]; + + if (textureFromCache) { + var index = textureFromCache.textureCacheIds.indexOf(texture); + + if (index > -1) { + textureFromCache.textureCacheIds.splice(index, 1); + } + + delete _utils.TextureCache[texture]; + + return textureFromCache; + } + } else if (texture && texture.textureCacheIds) { + for (var i = 0; i < texture.textureCacheIds.length; ++i) { + // Check that texture matches the one being passed in before deleting it from the cache. + if (_utils.TextureCache[texture.textureCacheIds[i]] === texture) { + delete _utils.TextureCache[texture.textureCacheIds[i]]; + } + } + + texture.textureCacheIds.length = 0; + + return texture; + } + + return null; + }; + + /** + * The frame specifies the region of the base texture that this texture uses. + * Please call `_updateUvs()` after you change coordinates of `frame` manually. + * + * @member {PIXI.Rectangle} + */ + + + _createClass(Texture, [{ + key: 'frame', + get: function get() { + return this._frame; + }, + set: function set(frame) // eslint-disable-line require-jsdoc + { + this._frame = frame; + + this.noFrame = false; + + var x = frame.x, + y = frame.y, + width = frame.width, + height = frame.height; + + var xNotFit = x + width > this.baseTexture.width; + var yNotFit = y + height > this.baseTexture.height; + + if (xNotFit || yNotFit) { + var relationship = xNotFit && yNotFit ? 'and' : 'or'; + var errorX = 'X: ' + x + ' + ' + width + ' = ' + (x + width) + ' > ' + this.baseTexture.width; + var errorY = 'Y: ' + y + ' + ' + height + ' = ' + (y + height) + ' > ' + this.baseTexture.height; + + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + (errorX + ' ' + relationship + ' ' + errorY)); + } + + // this.valid = width && height && this.baseTexture.source && this.baseTexture.hasLoaded; + this.valid = width && height && this.baseTexture.hasLoaded; + + if (!this.trim && !this.rotate) { + this.orig = frame; + } + + if (this.valid) { + this._updateUvs(); + } + } + + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.GroupD8} for explanation + * + * @member {number} + */ + + }, { + key: 'rotate', + get: function get() { + return this._rotate; + }, + set: function set(rotate) // eslint-disable-line require-jsdoc + { + this._rotate = rotate; + if (this.valid) { + this._updateUvs(); + } + } + + /** + * The width of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'width', + get: function get() { + return this.orig.width; + } + + /** + * The height of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.orig.height; + } + }]); + + return Texture; +}(_eventemitter2.default); + +exports.default = Texture; + + +function createWhiteTexture() { + var canvas = document.createElement('canvas'); + + canvas.width = 10; + canvas.height = 10; + + var context = canvas.getContext('2d'); + + context.fillStyle = 'white'; + context.fillRect(0, 0, 10, 10); + + return new Texture(new _BaseTexture2.default(canvas)); +} + +function removeAllHandlers(tex) { + tex.destroy = function _emptyDestroy() {/* empty */}; + tex.on = function _emptyOn() {/* empty */}; + tex.once = function _emptyOnce() {/* empty */}; + tex.emit = function _emptyEmit() {/* empty */}; +} + +/** + * An empty texture, used often to not have to create multiple empty textures. + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.EMPTY = new Texture(new _BaseTexture2.default()); +removeAllHandlers(Texture.EMPTY); +removeAllHandlers(Texture.EMPTY.baseTexture); + +/** + * A white texture of 10x10 size, used for graphics and other things + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.WHITE = createWhiteTexture(); +removeAllHandlers(Texture.WHITE); +removeAllHandlers(Texture.WHITE.baseTexture); + +},{"../math":70,"../settings":101,"../utils":125,"./BaseTexture":112,"./TextureUvs":117,"./VideoBaseTexture":118,"eventemitter3":3}],116:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Matrix = require('../math/Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var tempMat = new _Matrix2.default(); + +/** + * Class controls uv transform and frame clamp for texture + * Can be used in Texture "transform" field, or separately, you can use different clamp settings on the same texture. + * If you want to add support for texture region of certain feature or filter, that's what you're looking for. + * + * @see PIXI.Texture + * @see PIXI.mesh.Mesh + * @see PIXI.extras.TilingSprite + * @class + * @memberof PIXI + */ + +var TextureMatrix = function () { + /** + * + * @param {PIXI.Texture} texture observed texture + * @param {number} [clampMargin] Changes frame clamping, 0.5 by default. Use -0.5 for extra border. + * @constructor + */ + function TextureMatrix(texture, clampMargin) { + _classCallCheck(this, TextureMatrix); + + this._texture = texture; + + this.mapCoord = new _Matrix2.default(); + + this.uClampFrame = new Float32Array(4); + + this.uClampOffset = new Float32Array(2); + + this._lastTextureID = -1; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders + * + * @default 0 + * @member {number} + */ + this.clampOffset = 0; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + this.clampMargin = typeof clampMargin === 'undefined' ? 0.5 : clampMargin; + } + + /** + * texture property + * @member {PIXI.Texture} + */ + + + /** + * Multiplies uvs array to transform + * @param {Float32Array} uvs mesh uvs + * @param {Float32Array} [out=uvs] output + * @returns {Float32Array} output + */ + TextureMatrix.prototype.multiplyUvs = function multiplyUvs(uvs, out) { + if (out === undefined) { + out = uvs; + } + + var mat = this.mapCoord; + + for (var i = 0; i < uvs.length; i += 2) { + var x = uvs[i]; + var y = uvs[i + 1]; + + out[i] = x * mat.a + y * mat.c + mat.tx; + out[i + 1] = x * mat.b + y * mat.d + mat.ty; + } + + return out; + }; + + /** + * updates matrices if texture was changed + * @param {boolean} forceUpdate if true, matrices will be updated any case + * @returns {boolean} whether or not it was updated + */ + + + TextureMatrix.prototype.update = function update(forceUpdate) { + var tex = this._texture; + + if (!tex || !tex.valid) { + return false; + } + + if (!forceUpdate && this._lastTextureID === tex._updateID) { + return false; + } + + this._lastTextureID = tex._updateID; + + var uvs = tex._uvs; + + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + + var orig = tex.orig; + var trim = tex.trim; + + if (trim) { + tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat); + } + + var texBase = tex.baseTexture; + var frame = this.uClampFrame; + var margin = this.clampMargin / texBase.resolution; + var offset = this.clampOffset; + + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.uClampOffset[0] = offset / texBase.realWidth; + this.uClampOffset[1] = offset / texBase.realHeight; + + return true; + }; + + _createClass(TextureMatrix, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._texture = value; + this._lastTextureID = -1; + } + }]); + + return TextureMatrix; +}(); + +exports.default = TextureMatrix; + +},{"../math/Matrix":67}],117:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _GroupD = require('../math/GroupD8'); + +var _GroupD2 = _interopRequireDefault(_GroupD); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A standard object to store the Uvs of a texture + * + * @class + * @private + * @memberof PIXI + */ +var TextureUvs = function () { + /** + * + */ + function TextureUvs() { + _classCallCheck(this, TextureUvs); + + this.x0 = 0; + this.y0 = 0; + + this.x1 = 1; + this.y1 = 0; + + this.x2 = 1; + this.y2 = 1; + + this.x3 = 0; + this.y3 = 1; + + this.uvsUint32 = new Uint32Array(4); + } + + /** + * Sets the texture Uvs based on the given frame information. + * + * @private + * @param {PIXI.Rectangle} frame - The frame of the texture + * @param {PIXI.Rectangle} baseFrame - The base frame of the texture + * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8} + */ + + + TextureUvs.prototype.set = function set(frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + + // coordinates of center + var cX = frame.x / tw + w2; + var cY = frame.y / th + h2; + + rotate = _GroupD2.default.add(rotate, _GroupD2.default.NW); // NW is top-left corner + this.x0 = cX + w2 * _GroupD2.default.uX(rotate); + this.y0 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + w2 * _GroupD2.default.uX(rotate); + this.y1 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x2 = cX + w2 * _GroupD2.default.uX(rotate); + this.y2 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x3 = cX + w2 * _GroupD2.default.uX(rotate); + this.y3 = cY + h2 * _GroupD2.default.uY(rotate); + } else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + + this.uvsUint32[0] = (this.y0 * 65535 & 0xFFFF) << 16 | this.x0 * 65535 & 0xFFFF; + this.uvsUint32[1] = (this.y1 * 65535 & 0xFFFF) << 16 | this.x1 * 65535 & 0xFFFF; + this.uvsUint32[2] = (this.y2 * 65535 & 0xFFFF) << 16 | this.x2 * 65535 & 0xFFFF; + this.uvsUint32[3] = (this.y3 * 65535 & 0xFFFF) << 16 | this.x3 * 65535 & 0xFFFF; + }; + + return TextureUvs; +}(); + +exports.default = TextureUvs; + +},{"../math/GroupD8":66}],118:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _utils = require('../utils'); + +var _ticker = require('../ticker'); + +var _const = require('../const'); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture of a [playing] Video. + * + * Video base textures mimic PixiJS BaseTexture.from.... method in their creation process. + * + * This can be used in several ways, such as: + * + * ```js + * let texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4'); + * + * let texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' }); + * + * let texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']); + * + * let texture = PIXI.VideoBaseTexture.fromUrls([ + * { src: '/video.webm', mime: 'video/webm' }, + * { src: '/video.mp4', mime: 'video/mp4' } + * ]); + * ``` + * + * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/). + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var VideoBaseTexture = function (_BaseTexture) { + _inherits(VideoBaseTexture, _BaseTexture); + + /** + * @param {HTMLVideoElement} source - Video source + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + */ + function VideoBaseTexture(source, scaleMode) { + _classCallCheck(this, VideoBaseTexture); + + if (!source) { + throw new Error('No video source element specified.'); + } + + // hook in here to check if video is already available. + // BaseTexture looks for a source.complete boolean, plus width & height. + + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + source.complete = true; + } + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, source, scaleMode)); + + _this.width = source.videoWidth; + _this.height = source.videoHeight; + + _this._autoUpdate = true; + _this._isAutoUpdating = false; + + /** + * When set to true will automatically play videos used by this texture once + * they are loaded. If false, it will not modify the playing state. + * + * @member {boolean} + * @default true + */ + _this.autoPlay = true; + + _this.update = _this.update.bind(_this); + _this._onCanPlay = _this._onCanPlay.bind(_this); + + source.addEventListener('play', _this._onPlayStart.bind(_this)); + source.addEventListener('pause', _this._onPlayStop.bind(_this)); + _this.hasLoaded = false; + _this.__loaded = false; + + if (!_this._isSourceReady()) { + source.addEventListener('canplay', _this._onCanPlay); + source.addEventListener('canplaythrough', _this._onCanPlay); + } else { + _this._onCanPlay(); + } + return _this; + } + + /** + * Returns true if the underlying source is playing. + * + * @private + * @return {boolean} True if playing. + */ + + + VideoBaseTexture.prototype._isSourcePlaying = function _isSourcePlaying() { + var source = this.source; + + return source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2; + }; + + /** + * Returns true if the underlying source is ready for playing. + * + * @private + * @return {boolean} True if ready. + */ + + + VideoBaseTexture.prototype._isSourceReady = function _isSourceReady() { + return this.source.readyState === 3 || this.source.readyState === 4; + }; + + /** + * Runs the update loop when the video is ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStart = function _onPlayStart() { + // Just in case the video has not received its can play even yet.. + if (!this.hasLoaded) { + this._onCanPlay(); + } + + if (!this._isAutoUpdating && this.autoUpdate) { + _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); + this._isAutoUpdating = true; + } + }; + + /** + * Fired when a pause event is triggered, stops the update loop + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStop = function _onPlayStop() { + if (this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } + }; + + /** + * Fired when the video is loaded and ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onCanPlay = function _onCanPlay() { + this.hasLoaded = true; + + if (this.source) { + this.source.removeEventListener('canplay', this._onCanPlay); + this.source.removeEventListener('canplaythrough', this._onCanPlay); + + this.width = this.source.videoWidth; + this.height = this.source.videoHeight; + + // prevent multiple loaded dispatches.. + if (!this.__loaded) { + this.__loaded = true; + this.emit('loaded', this); + } + + if (this._isSourcePlaying()) { + this._onPlayStart(); + } else if (this.autoPlay) { + this.source.play(); + } + } + }; + + /** + * Destroys this texture + * + */ + + + VideoBaseTexture.prototype.destroy = function destroy() { + if (this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + } + + if (this.source && this.source._pixiId) { + _BaseTexture3.default.removeFromCache(this.source._pixiId); + delete this.source._pixiId; + + this.source.pause(); + this.source.src = ''; + this.source.load(); + } + + _BaseTexture.prototype.destroy.call(this); + }; + + /** + * Mimic PixiJS BaseTexture.from.... method. + * + * @static + * @param {HTMLVideoElement} video - Video to create texture from + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromVideo = function fromVideo(video, scaleMode) { + if (!video._pixiId) { + video._pixiId = 'video_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[video._pixiId]; + + if (!baseTexture) { + baseTexture = new VideoBaseTexture(video, scaleMode); + _BaseTexture3.default.addToCache(baseTexture, video._pixiId); + } + + return baseTexture; + }; + + /** + * Helper function that creates a new BaseTexture based on the given video element. + * This BaseTexture can then be used to create a texture + * + * @static + * @param {string|object|string[]|object[]} videoSrc - The URL(s) for the video. + * @param {string} [videoSrc.src] - One of the source urls for the video + * @param {string} [videoSrc.mime] - The mimetype of the video (e.g. 'video/mp4'). If not specified + * the url's extension will be used as the second part of the mime type. + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromUrl = function fromUrl(videoSrc, scaleMode, crossorigin) { + var video = document.createElement('video'); + + video.setAttribute('webkit-playsinline', ''); + video.setAttribute('playsinline', ''); + + var url = Array.isArray(videoSrc) ? videoSrc[0].src || videoSrc[0] : videoSrc.src || videoSrc; + + if (crossorigin === undefined && url.indexOf('data:') !== 0) { + video.crossOrigin = (0, _determineCrossOrigin2.default)(url); + } else if (crossorigin) { + video.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; + } + + // array of objects or strings + if (Array.isArray(videoSrc)) { + for (var i = 0; i < videoSrc.length; ++i) { + video.appendChild(createSource(videoSrc[i].src || videoSrc[i], videoSrc[i].mime)); + } + } + // single object or string + else { + video.appendChild(createSource(url, videoSrc.mime)); + } + + video.load(); + + return VideoBaseTexture.fromVideo(video, scaleMode); + }; + + /** + * Should the base texture automatically update itself, set to true by default + * + * @member {boolean} + */ + + + _createClass(VideoBaseTexture, [{ + key: 'autoUpdate', + get: function get() { + return this._autoUpdate; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + + if (!this._autoUpdate && this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } else if (this._autoUpdate && !this._isAutoUpdating) { + _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); + this._isAutoUpdating = true; + } + } + } + }]); + + return VideoBaseTexture; +}(_BaseTexture3.default); + +exports.default = VideoBaseTexture; + + +VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; + +function createSource(path, type) { + if (!type) { + path = path.split('?').shift().toLowerCase(); + type = 'video/' + path.substr(path.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = path; + source.type = type; + + return source; +} + +},{"../const":46,"../ticker":121,"../utils":125,"../utils/determineCrossOrigin":124,"./BaseTexture":112}],119:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _const = require('../const'); + +var _TickerListener = require('./TickerListener'); + +var _TickerListener2 = _interopRequireDefault(_TickerListener); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A Ticker class that runs an update loop that other objects listen to. + * This class is composed around listeners + * meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, + * e.g. When the ticker is started and the emitter has listeners. + * + * @class + * @memberof PIXI.ticker + */ +var Ticker = function () { + /** + * + */ + function Ticker() { + var _this = this; + + _classCallCheck(this, Ticker); + + /** + * The first listener. All new listeners added are chained on this. + * @private + * @type {TickerListener} + */ + this._head = new _TickerListener2.default(null, null, Infinity); + + /** + * Internal current frame request ID + * @private + */ + this._requestId = null; + + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + * @private + */ + this._maxElapsedMS = 100; + + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.ticker.Ticker#start} automatically + * when a listener is added. + * + * @member {boolean} + * @default false + */ + this.autoStart = false; + + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS} + * and is scaled with {@link PIXI.ticker.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * + * @member {number} + * @default 1 + */ + this.deltaTime = 1; + + /** + * Time elapsed in milliseconds from last frame to this frame. + * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime} + * is based, this value is neither capped nor scaled. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * Defaults to target frame time + * + * @member {number} + * @default 16.66 + */ + this.elapsedMS = 1 / _settings2.default.TARGET_FPMS; + + /** + * The last time {@link PIXI.ticker.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default -1 + */ + this.lastTime = -1; + + /** + * Factor of current {@link PIXI.ticker.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + * + * @member {number} + * @default 1 + */ + this.speed = 1; + + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.ticker.Ticker#start} has been called. + * `false` if {@link PIXI.ticker.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.ticker.Ticker#autoStart} being `true` + * and a listener is added. + * + * @member {boolean} + * @default false + */ + this.started = false; + + /** + * Internal tick method bound to ticker instance. + * This is because in early 2015, Function.bind + * is still 60% slower in high performance scenarios. + * Also separating frame requests from update method + * so listeners may be called at any time and with + * any animation API, just invoke ticker.update(time). + * + * @private + * @param {number} time - Time since last tick. + */ + this._tick = function (time) { + _this._requestId = null; + + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._head.next) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * + * @private + */ + + + Ticker.prototype._requestIfNeeded = function _requestIfNeeded() { + if (this._requestId === null && this._head.next) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._requestId = requestAnimationFrame(this._tick); + } + }; + + /** + * Conditionally cancels a pending animation frame. + * + * @private + */ + + + Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; + + /** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * + * @private + */ + + + Ticker.prototype._startIfPossible = function _startIfPossible() { + if (this.started) { + this._requestIfNeeded(); + } else if (this.autoStart) { + this.start(); + } + }; + + /** + * Register a handler for tick events. Calls continuously unless + * it is removed or the ticker is stopped. + * + * @param {Function} fn - The listener function to be added for updates + * @param {Function} [context] - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.add = function add(fn, context) { + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _const.UPDATE_PRIORITY.NORMAL; + + return this._addListener(new _TickerListener2.default(fn, context, priority)); + }; + + /** + * Add a handler for the tick event which is only execute once. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context] - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.addOnce = function addOnce(fn, context) { + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _const.UPDATE_PRIORITY.NORMAL; + + return this._addListener(new _TickerListener2.default(fn, context, priority, true)); + }; + + /** + * Internally adds the event handler so that it can be sorted by priority. + * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run + * before the rendering. + * + * @private + * @param {TickerListener} listener - Current listener being added. + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype._addListener = function _addListener(listener) { + // For attaching to head + var current = this._head.next; + var previous = this._head; + + // Add the first item + if (!current) { + listener.connect(previous); + } else { + // Go from highest to lowest priority + while (current) { + if (listener.priority > current.priority) { + listener.connect(previous); + break; + } + previous = current; + current = current.next; + } + + // Not yet connected + if (!listener.previous) { + listener.connect(previous); + } + } + + this._startIfPossible(); + + return this; + }; + + /** + * Removes any handlers matching the function and context parameters. + * If no handlers are left after removing, then it cancels the animation frame. + * + * @param {Function} fn - The listener function to be removed + * @param {Function} [context] - The listener context to be removed + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.remove = function remove(fn, context) { + var listener = this._head.next; + + while (listener) { + // We found a match, lets remove it + // no break to delete all possible matches + // incase a listener was added 2+ times + if (listener.match(fn, context)) { + listener = listener.destroy(); + } else { + listener = listener.next; + } + } + + if (!this._head.next) { + this._cancelIfNeeded(); + } + + return this; + }; + + /** + * Starts the ticker. If the ticker has listeners + * a new animation frame is requested at this point. + */ + + + Ticker.prototype.start = function start() { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + }; + + /** + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. + */ + + + Ticker.prototype.stop = function stop() { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; + + /** + * Destroy the ticker and don't use after this. Calling + * this method removes all references to internal events. + */ + + + Ticker.prototype.destroy = function destroy() { + this.stop(); + + var listener = this._head.next; + + while (listener) { + listener = listener.destroy(true); + } + + this._head.destroy(); + this._head = null; + }; + + /** + * Triggers an update. An update entails setting the + * current {@link PIXI.ticker.Ticker#elapsedMS}, + * the current {@link PIXI.ticker.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.ticker.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + + + Ticker.prototype.update = function update() { + var currentTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : performance.now(); + + var elapsedMS = void 0; + + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + + this.deltaTime = elapsedMS * _settings2.default.TARGET_FPMS * this.speed; + + // Cache a local reference, in-case ticker is destroyed + // during the emit, we can still check for head.next + var head = this._head; + + // Invoke listeners added to internal emitter + var listener = head.next; + + while (listener) { + listener = listener.emit(this.deltaTime); + } + + if (!head.next) { + this._cancelIfNeeded(); + } + } else { + this.deltaTime = this.elapsedMS = 0; + } + + this.lastTime = currentTime; + }; + + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.ticker.Ticker#speed}, which is specific + * to scaling {@link PIXI.ticker.Ticker#deltaTime}. + * + * @member {number} + * @readonly + */ + + + _createClass(Ticker, [{ + key: 'FPS', + get: function get() { + return 1000 / this.elapsedMS; + } + + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.ticker.Ticker#update}. + * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.settings.TARGET_FPMS * 1000`. + * + * @member {number} + * @default 10 + */ + + }, { + key: 'minFPS', + get: function get() { + return 1000 / this._maxElapsedMS; + }, + set: function set(fps) // eslint-disable-line require-jsdoc + { + // Clamp: 0 to TARGET_FPMS + var minFPMS = Math.min(Math.max(0, fps) / 1000, _settings2.default.TARGET_FPMS); + + this._maxElapsedMS = 1 / minFPMS; + } + }]); + + return Ticker; +}(); + +exports.default = Ticker; + +},{"../const":46,"../settings":101,"./TickerListener":120}],120:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Internal class for handling the priority sorting of ticker handlers. + * + * @private + * @class + * @memberof PIXI.ticker + */ +var TickerListener = function () { + /** + * Constructor + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context=null] - The listener context + * @param {number} [priority=0] - The priority for emitting + * @param {boolean} [once=false] - If the handler should fire once + */ + function TickerListener(fn) { + var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var once = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + _classCallCheck(this, TickerListener); + + /** + * The handler function to execute. + * @member {Function} + */ + this.fn = fn; + + /** + * The calling to execute. + * @member {Function} + */ + this.context = context; + + /** + * The current priority. + * @member {number} + */ + this.priority = priority; + + /** + * If this should only execute once. + * @member {boolean} + */ + this.once = once; + + /** + * The next item in chain. + * @member {TickerListener} + */ + this.next = null; + + /** + * The previous item in chain. + * @member {TickerListener} + */ + this.previous = null; + + /** + * `true` if this listener has been destroyed already. + * @member {boolean} + * @private + */ + this._destroyed = false; + } + + /** + * Simple compare function to figure out if a function and context match. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} context - The listener context + * @return {boolean} `true` if the listener match the arguments + */ + + + TickerListener.prototype.match = function match(fn, context) { + context = context || null; + + return this.fn === fn && this.context === context; + }; + + /** + * Emit by calling the current function. + * @param {number} deltaTime - time since the last emit. + * @return {TickerListener} Next ticker + */ + + + TickerListener.prototype.emit = function emit(deltaTime) { + if (this.fn) { + if (this.context) { + this.fn.call(this.context, deltaTime); + } else { + this.fn(deltaTime); + } + } + + var redirect = this.next; + + if (this.once) { + this.destroy(true); + } + + // Soft-destroying should remove + // the next reference + if (this._destroyed) { + this.next = null; + } + + return redirect; + }; + + /** + * Connect to the list. + * @param {TickerListener} previous - Input node, previous listener + */ + + + TickerListener.prototype.connect = function connect(previous) { + this.previous = previous; + if (previous.next) { + previous.next.previous = this; + } + this.next = previous.next; + previous.next = this; + }; + + /** + * Destroy and don't use after this. + * @param {boolean} [hard = false] `true` to remove the `next` reference, this + * is considered a hard destroy. Soft destroy maintains the next reference. + * @return {TickerListener} The listener to redirect while emitting or removing. + */ + + + TickerListener.prototype.destroy = function destroy() { + var hard = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + this._destroyed = true; + this.fn = null; + this.context = null; + + // Disconnect, hook up next and previous + if (this.previous) { + this.previous.next = this.next; + } + + if (this.next) { + this.next.previous = this.previous; + } + + // Redirect to the next item + var redirect = this.next; + + // Remove references + this.next = hard ? null : redirect; + this.previous = null; + + return redirect; + }; + + return TickerListener; +}(); + +exports.default = TickerListener; + +},{}],121:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Ticker = exports.shared = undefined; + +var _Ticker = require('./Ticker'); + +var _Ticker2 = _interopRequireDefault(_Ticker); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The shared ticker instance used by {@link PIXI.extras.AnimatedSprite}. + * and by {@link PIXI.interaction.InteractionManager}. + * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` + * for this instance. Please follow the examples for usage, including + * how to opt-out of auto-starting the shared ticker. + * + * @example + * let ticker = PIXI.ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(800, 600); + * let stage = new PIXI.Container(); + * let interactionManager = PIXI.interaction.InteractionManager(renderer); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * + * @type {PIXI.ticker.Ticker} + * @memberof PIXI.ticker + */ +var shared = new _Ticker2.default(); + +shared.autoStart = true; +shared.destroy = function () { + // protect destroying shared ticker + // this is used by other internal systems + // like AnimatedSprite and InteractionManager +}; + +/** + * This namespace contains an API for interacting with PIXI's internal global update loop. + * + * This ticker is used for rendering, {@link PIXI.extras.AnimatedSprite AnimatedSprite}, + * {@link PIXI.interaction.InteractionManager InteractionManager} and many other time-based PIXI systems. + * @example + * const ticker = new PIXI.ticker.Ticker(); + * ticker.stop(); + * ticker.add((deltaTime) => { + * // do something every frame + * }); + * ticker.start(); + * @namespace PIXI.ticker + */ +exports.shared = shared; +exports.Ticker = _Ticker2.default; + +},{"./Ticker":119}],122:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = canUploadSameBuffer; +function canUploadSameBuffer() { + // Uploading the same buffer multiple times in a single frame can cause perf issues. + // Apparent on IOS so only check for that at the moment + // this check may become more complex if this issue pops up elsewhere. + var ios = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform); + + return !ios; +} + +},{}],123:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = createIndicesForQuads; +/** + * Generic Mask Stack data structure + * + * @memberof PIXI + * @function createIndicesForQuads + * @private + * @param {number} size - Number of quads + * @return {Uint16Array} indices + */ +function createIndicesForQuads(size) { + // the total number of indices in our array, there are 6 points per quad. + + var totalIndices = size * 6; + + var indices = new Uint16Array(totalIndices); + + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + indices[i + 0] = j + 0; + indices[i + 1] = j + 1; + indices[i + 2] = j + 2; + indices[i + 3] = j + 0; + indices[i + 4] = j + 2; + indices[i + 5] = j + 3; + } + + return indices; +} + +},{}],124:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = determineCrossOrigin; + +var _url2 = require('url'); + +var _url3 = _interopRequireDefault(_url2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var tempAnchor = void 0; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +function determineCrossOrigin(url) { + var loc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location; + + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url3.default.parse(tempAnchor.href); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +} + +},{"url":38}],125:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.premultiplyBlendMode = exports.BaseTextureCache = exports.TextureCache = exports.earcut = exports.mixins = exports.pluginTarget = exports.EventEmitter = exports.removeItems = exports.isMobile = undefined; +exports.uid = uid; +exports.hex2rgb = hex2rgb; +exports.hex2string = hex2string; +exports.rgb2hex = rgb2hex; +exports.getResolutionOfUrl = getResolutionOfUrl; +exports.decomposeDataUri = decomposeDataUri; +exports.getUrlFileExtension = getUrlFileExtension; +exports.getSvgSize = getSvgSize; +exports.skipHello = skipHello; +exports.sayHello = sayHello; +exports.isWebGLSupported = isWebGLSupported; +exports.sign = sign; +exports.destroyTextureCache = destroyTextureCache; +exports.clearTextureCache = clearTextureCache; +exports.correctBlendMode = correctBlendMode; +exports.premultiplyTint = premultiplyTint; +exports.premultiplyRgba = premultiplyRgba; +exports.premultiplyTintToRgba = premultiplyTintToRgba; + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _pluginTarget = require('./pluginTarget'); + +var _pluginTarget2 = _interopRequireDefault(_pluginTarget); + +var _mixin = require('./mixin'); + +var mixins = _interopRequireWildcard(_mixin); + +var _ismobilejs = require('ismobilejs'); + +var isMobile = _interopRequireWildcard(_ismobilejs); + +var _removeArrayItems = require('remove-array-items'); + +var _removeArrayItems2 = _interopRequireDefault(_removeArrayItems); + +var _mapPremultipliedBlendModes = require('./mapPremultipliedBlendModes'); + +var _mapPremultipliedBlendModes2 = _interopRequireDefault(_mapPremultipliedBlendModes); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var nextUid = 0; +var saidHello = false; + +/** + * Generalized convenience utilities for PIXI. + * @example + * // Extend PIXI's internal Event Emitter. + * class MyEmitter extends PIXI.utils.EventEmitter { + * constructor() { + * super(); + * console.log("Emitter created!"); + * } + * } + * + * // Get info on current device + * console.log(PIXI.utils.isMobile); + * + * // Convert hex color to string + * console.log(PIXI.utils.hex2string(0xff00ff)); // returns: "#ff00ff" + * @namespace PIXI.utils + */ +exports.isMobile = isMobile; +exports.removeItems = _removeArrayItems2.default; +exports.EventEmitter = _eventemitter2.default; +exports.pluginTarget = _pluginTarget2.default; +exports.mixins = mixins; +exports.earcut = _earcut2.default; + +/** + * Gets the next unique identifier + * + * @memberof PIXI.utils + * @function uid + * @return {number} The next unique identifier to use. + */ + +function uid() { + return ++nextUid; +} + +/** + * Converts a hex color number to an [R, G, B] array + * + * @memberof PIXI.utils + * @function hex2rgb + * @param {number} hex - The number to convert + * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one + * @return {number[]} An array representing the [R, G, B] of the color. + */ +function hex2rgb(hex, out) { + out = out || []; + + out[0] = (hex >> 16 & 0xFF) / 255; + out[1] = (hex >> 8 & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + + return out; +} + +/** + * Converts a hex color number to a string. + * + * @memberof PIXI.utils + * @function hex2string + * @param {number} hex - Number in hex + * @return {string} The string color. + */ +function hex2string(hex) { + hex = hex.toString(16); + hex = '000000'.substr(0, 6 - hex.length) + hex; + + return '#' + hex; +} + +/** + * Converts a color as an [R, G, B] array to a hex number + * + * @memberof PIXI.utils + * @function rgb2hex + * @param {number[]} rgb - rgb array + * @return {number} The color number + */ +function rgb2hex(rgb) { + return (rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + (rgb[2] * 255 | 0); +} + +/** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * + * @memberof PIXI.utils + * @function getResolutionOfUrl + * @param {string} url - the image path + * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. + * @return {number} resolution / device pixel ratio of an asset + */ +function getResolutionOfUrl(url, defaultValue) { + var resolution = _settings2.default.RETINA_PREFIX.exec(url); + + if (resolution) { + return parseFloat(resolution[1]); + } + + return defaultValue !== undefined ? defaultValue : 1; +} + +/** + * Typedef for decomposeDataUri return object. + * + * @typedef {object} PIXI.utils~DecomposedDataUri + * @property {mediaType} Media type, eg. `image` + * @property {subType} Sub type, eg. `png` + * @property {encoding} Data encoding, eg. `base64` + * @property {data} The actual data + */ + +/** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. + * + * @memberof PIXI.utils + * @function decomposeDataUri + * @param {string} dataUri - the data URI to check + * @return {PIXI.utils~DecomposedDataUri|undefined} The decomposed data uri or undefined + */ +function decomposeDataUri(dataUri) { + var dataUriMatch = _const.DATA_URI.exec(dataUri); + + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : undefined, + data: dataUriMatch[5] + }; + } + + return undefined; +} + +/** + * Get type of the image by regexp for extension. Returns undefined for unknown extensions. + * + * @memberof PIXI.utils + * @function getUrlFileExtension + * @param {string} url - the image path + * @return {string|undefined} image extension + */ +function getUrlFileExtension(url) { + var extension = _const.URL_FILE_EXTENSION.exec(url); + + if (extension) { + return extension[1].toLowerCase(); + } + + return undefined; +} + +/** + * Typedef for Size object. + * + * @typedef {object} PIXI.utils~Size + * @property {width} Width component + * @property {height} Height component + */ + +/** + * Get size from an svg string using regexp. + * + * @memberof PIXI.utils + * @function getSvgSize + * @param {string} svgString - a serialized svg element + * @return {PIXI.utils~Size|undefined} image extension + */ +function getSvgSize(svgString) { + var sizeMatch = _const.SVG_SIZE.exec(svgString); + var size = {}; + + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); + size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); + } + + return size; +} + +/** + * Skips the hello message of renderers that are created after this is run. + * + * @function skipHello + * @memberof PIXI.utils + */ +function skipHello() { + saidHello = true; +} + +/** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever makes you a jerk face. + * + * @static + * @function sayHello + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ +function sayHello(type) { + if (saidHello) { + return; + } + + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = ['\n %c %c %c PixiJS ' + _const.VERSION + ' - \u2730 ' + type + ' \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n', 'background: #ff66a5; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff66a5; background: #030307; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'background: #ffc3dc; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;']; + + window.console.log.apply(console, args); + } else if (window.console) { + window.console.log('PixiJS ' + _const.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); + } + + saidHello = true; +} + +/** + * Helper for checking for webgl support + * + * @memberof PIXI.utils + * @function isWebGLSupported + * @return {boolean} is webgl supported + */ +function isWebGLSupported() { + var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; + + try { + if (!window.WebGLRenderingContext) { + return false; + } + + var canvas = document.createElement('canvas'); + var gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); + + var success = !!(gl && gl.getContextAttributes().stencil); + + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + + if (loseContext) { + loseContext.loseContext(); + } + } + + gl = null; + + return success; + } catch (e) { + return false; + } +} + +/** + * Returns sign of number + * + * @memberof PIXI.utils + * @function sign + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ +function sign(n) { + if (n === 0) return 0; + + return n < 0 ? -1 : 1; +} + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var TextureCache = exports.TextureCache = Object.create(null); + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var BaseTextureCache = exports.BaseTextureCache = Object.create(null); + +/** + * Destroys all texture in the cache + * + * @memberof PIXI.utils + * @function destroyTextureCache + */ +function destroyTextureCache() { + var key = void 0; + + for (key in TextureCache) { + TextureCache[key].destroy(); + } + for (key in BaseTextureCache) { + BaseTextureCache[key].destroy(); + } +} + +/** + * Removes all textures from cache, but does not destroy them + * + * @memberof PIXI.utils + * @function clearTextureCache + */ +function clearTextureCache() { + var key = void 0; + + for (key in TextureCache) { + delete TextureCache[key]; + } + for (key in BaseTextureCache) { + delete BaseTextureCache[key]; + } +} + +/** + * maps premultiply flag and blendMode to adjusted blendMode + * @memberof PIXI.utils + * @const premultiplyBlendMode + * @type {Array} + */ +var premultiplyBlendMode = exports.premultiplyBlendMode = (0, _mapPremultipliedBlendModes2.default)(); + +/** + * changes blendMode according to texture format + * + * @memberof PIXI.utils + * @function correctBlendMode + * @param {number} blendMode supposed blend mode + * @param {boolean} premultiplied whether source is premultiplied + * @returns {number} true blend mode for this texture + */ +function correctBlendMode(blendMode, premultiplied) { + return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; +} + +/** + * premultiplies tint + * + * @memberof PIXI.utils + * @param {number} tint integet RGB + * @param {number} alpha floating point alpha (0.0-1.0) + * @returns {number} tint multiplied by alpha + */ +function premultiplyTint(tint, alpha) { + if (alpha === 1.0) { + return (alpha * 255 << 24) + tint; + } + if (alpha === 0.0) { + return 0; + } + var R = tint >> 16 & 0xFF; + var G = tint >> 8 & 0xFF; + var B = tint & 0xFF; + + R = R * alpha + 0.5 | 0; + G = G * alpha + 0.5 | 0; + B = B * alpha + 0.5 | 0; + + return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; +} + +/** + * combines rgb and alpha to out array + * + * @memberof PIXI.utils + * @param {Float32Array|number[]} rgb input rgb + * @param {number} alpha alpha param + * @param {Float32Array} [out] output + * @param {boolean} [premultiply=true] do premultiply it + * @returns {Float32Array} vec4 rgba + */ +function premultiplyRgba(rgb, alpha, out, premultiply) { + out = out || new Float32Array(4); + if (premultiply || premultiply === undefined) { + out[0] = rgb[0] * alpha; + out[1] = rgb[1] * alpha; + out[2] = rgb[2] * alpha; + } else { + out[0] = rgb[0]; + out[1] = rgb[1]; + out[2] = rgb[2]; + } + out[3] = alpha; + + return out; +} + +/** + * converts integer tint and float alpha to vec4 form, premultiplies by default + * + * @memberof PIXI.utils + * @param {number} tint input tint + * @param {number} alpha alpha param + * @param {Float32Array} [out] output + * @param {boolean} [premultiply=true] do premultiply it + * @returns {Float32Array} vec4 rgba + */ +function premultiplyTintToRgba(tint, alpha, out, premultiply) { + out = out || new Float32Array(4); + out[0] = (tint >> 16 & 0xFF) / 255.0; + out[1] = (tint >> 8 & 0xFF) / 255.0; + out[2] = (tint & 0xFF) / 255.0; + if (premultiply || premultiply === undefined) { + out[0] *= alpha; + out[1] *= alpha; + out[2] *= alpha; + } + out[3] = alpha; + + return out; +} + +},{"../const":46,"../settings":101,"./mapPremultipliedBlendModes":126,"./mixin":128,"./pluginTarget":129,"earcut":2,"eventemitter3":3,"ismobilejs":4,"remove-array-items":31}],126:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapPremultipliedBlendModes; + +var _const = require('../const'); + +/** + * Corrects PixiJS blend, takes premultiplied alpha into account + * + * @memberof PIXI + * @function mapPremultipliedBlendModes + * @private + * @param {Array} [array] - The array to output into. + * @return {Array} Mapped modes. + */ + +function mapPremultipliedBlendModes() { + var pm = []; + var npm = []; + + for (var i = 0; i < 32; i++) { + pm[i] = i; + npm[i] = i; + } + + pm[_const.BLEND_MODES.NORMAL_NPM] = _const.BLEND_MODES.NORMAL; + pm[_const.BLEND_MODES.ADD_NPM] = _const.BLEND_MODES.ADD; + pm[_const.BLEND_MODES.SCREEN_NPM] = _const.BLEND_MODES.SCREEN; + + npm[_const.BLEND_MODES.NORMAL] = _const.BLEND_MODES.NORMAL_NPM; + npm[_const.BLEND_MODES.ADD] = _const.BLEND_MODES.ADD_NPM; + npm[_const.BLEND_MODES.SCREEN] = _const.BLEND_MODES.SCREEN_NPM; + + var array = []; + + array.push(npm); + array.push(pm); + + return array; +} + +},{"../const":46}],127:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = maxRecommendedTextures; + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function maxRecommendedTextures(max) { + if (_ismobilejs2.default.tablet || _ismobilejs2.default.phone) { + // check if the res is iphone 6 or higher.. + return 4; + } + + // desktop should be ok + return max; +} + +},{"ismobilejs":4}],128:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.mixin = mixin; +exports.delayMixin = delayMixin; +exports.performMixins = performMixins; +/** + * Mixes all enumerable properties and methods from a source object to a target object. + * + * @memberof PIXI.utils.mixins + * @function mixin + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function mixin(target, source) { + if (!target || !source) return; + // in ES8/ES2017, this would be really easy: + // Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + + // get all the enumerable property keys + var keys = Object.keys(source); + + // loop through properties + for (var i = 0; i < keys.length; ++i) { + var propertyName = keys[i]; + + // Set the property using the property descriptor - this works for accessors and normal value properties + Object.defineProperty(target, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); + } +} + +var mixins = []; + +/** + * Queues a mixin to be handled towards the end of the initialization of PIXI, so that deprecation + * can take effect. + * + * @memberof PIXI.utils.mixins + * @function delayMixin + * @private + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function delayMixin(target, source) { + mixins.push(target, source); +} + +/** + * Handles all mixins queued via delayMixin(). + * + * @memberof PIXI.utils.mixins + * @function performMixins + * @private + */ +function performMixins() { + for (var i = 0; i < mixins.length; i += 2) { + mixin(mixins[i], mixins[i + 1]); + } + mixins.length = 0; +} + +},{}],129:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Mixins functionality to make an object have "plugins". + * + * @example + * function MyObject() {} + * + * pluginTarget.mixin(MyObject); + * + * @mixin + * @memberof PIXI.utils + * @param {object} obj - The object to mix into. + */ +function pluginTarget(obj) { + obj.__plugins = {}; + + /** + * Adds a plugin to an object + * + * @param {string} pluginName - The events that should be listed. + * @param {Function} ctor - The constructor function for the plugin. + */ + obj.registerPlugin = function registerPlugin(pluginName, ctor) { + obj.__plugins[pluginName] = ctor; + }; + + /** + * Instantiates all the plugins of this object + * + */ + obj.prototype.initPlugins = function initPlugins() { + this.plugins = this.plugins || {}; + + for (var o in obj.__plugins) { + this.plugins[o] = new obj.__plugins[o](this); + } + }; + + /** + * Removes all the plugins of this object + * + */ + obj.prototype.destroyPlugins = function destroyPlugins() { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + + this.plugins = null; + }; +} + +exports.default = { + /** + * Mixes in the properties of the pluginTarget into another object + * + * @param {object} obj - The obj to mix into + */ + mixin: function mixin(obj) { + pluginTarget(obj); + } +}; + +},{}],130:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = trimCanvas; +/** + * Trim transparent borders from a canvas + * + * @memberof PIXI + * @function trimCanvas + * @private + * @param {HTMLCanvasElement} canvas - the canvas to trim + * @returns {object} Trim data + */ +function trimCanvas(canvas) { + // https://gist.github.com/remy/784508 + + var width = canvas.width; + var height = canvas.height; + + var context = canvas.getContext('2d'); + var imageData = context.getImageData(0, 0, width, height); + var pixels = imageData.data; + var len = pixels.length; + + var bound = { + top: null, + left: null, + right: null, + bottom: null + }; + var data = null; + var i = void 0; + var x = void 0; + var y = void 0; + + for (i = 0; i < len; i += 4) { + if (pixels[i + 3] !== 0) { + x = i / 4 % width; + y = ~~(i / 4 / width); + + if (bound.top === null) { + bound.top = y; + } + + if (bound.left === null) { + bound.left = x; + } else if (x < bound.left) { + bound.left = x; + } + + if (bound.right === null) { + bound.right = x + 1; + } else if (bound.right < x) { + bound.right = x + 1; + } + + if (bound.bottom === null) { + bound.bottom = y; + } else if (bound.bottom < y) { + bound.bottom = y; + } + } + } + + if (bound.top !== null) { + width = bound.right - bound.left; + height = bound.bottom - bound.top + 1; + data = context.getImageData(bound.left, bound.top, width, height); + } + + return { + height: height, + width: width, + data: data + }; +} + +},{}],131:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = deprecation; +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code + +// A map of warning messages already fired +var warnings = {}; + +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code +function warn(msg) { + // Ignore duplicat + if (warnings[msg]) { + return; + } + + /* eslint-disable no-console */ + var stack = new Error().stack; + + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('Deprecation Warning: ', msg); + } else { + // chop off the stack trace which includes pixi.js internal calls + stack = stack.split('\n').splice(3).join('\n'); + + if (console.groupCollapsed) { + console.groupCollapsed('%cDeprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', msg); + console.warn(stack); + console.groupEnd(); + } else { + console.warn('Deprecation Warning: ', msg); + console.warn(stack); + } + } + /* eslint-enable no-console */ + + warnings[msg] = true; +} + +function deprecation(core) { + var mesh = core.mesh, + particles = core.particles, + extras = core.extras, + filters = core.filters, + prepare = core.prepare, + loaders = core.loaders, + interaction = core.interaction; + + + Object.defineProperties(core, { + + /** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ + SpriteBatch: { + get: function get() { + throw new ReferenceError('SpriteBatch does not exist any more, ' + 'please use the new ParticleContainer instead.'); + } + }, + + /** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in PixiJS v3, + * please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ + AssetLoader: { + get: function get() { + throw new ReferenceError('The loader system was overhauled in PixiJS v3, ' + 'please see the new PIXI.loaders.Loader class.'); + } + }, + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + Stage: { + get: function get() { + warn('You do not need to use a PIXI Stage any more, you can simply render any container.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + DisplayObjectContainer: { + get: function get() { + warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + Strip: { + get: function get() { + warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.'); + + return mesh.Mesh; + } + }, + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + Rope: { + get: function get() { + warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.'); + + return mesh.Rope; + } + }, + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + ParticleContainer: { + get: function get() { + warn('The ParticleContainer class has been moved to particles.ParticleContainer, ' + 'please use particles.ParticleContainer from now on.'); + + return particles.ParticleContainer; + } + }, + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + MovieClip: { + get: function get() { + warn('The MovieClip class has been moved to extras.AnimatedSprite, please use extras.AnimatedSprite.'); + + return extras.AnimatedSprite; + } + }, + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + TilingSprite: { + get: function get() { + warn('The TilingSprite class has been moved to extras.TilingSprite, ' + 'please use extras.TilingSprite from now on.'); + + return extras.TilingSprite; + } + }, + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + BitmapText: { + get: function get() { + warn('The BitmapText class has been moved to extras.BitmapText, ' + 'please use extras.BitmapText from now on.'); + + return extras.BitmapText; + } + }, + + /** + * @class + * @private + * @name blendModes + * @memberof PIXI + * @see PIXI.BLEND_MODES + * @deprecated since version 3.0.0 + */ + blendModes: { + get: function get() { + warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.'); + + return core.BLEND_MODES; + } + }, + + /** + * @class + * @private + * @name scaleModes + * @memberof PIXI + * @see PIXI.SCALE_MODES + * @deprecated since version 3.0.0 + */ + scaleModes: { + get: function get() { + warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.'); + + return core.SCALE_MODES; + } + }, + + /** + * @class + * @private + * @name BaseTextureCache + * @memberof PIXI + * @see PIXI.utils.BaseTextureCache + * @deprecated since version 3.0.0 + */ + BaseTextureCache: { + get: function get() { + warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, ' + 'please use utils.BaseTextureCache from now on.'); + + return core.utils.BaseTextureCache; + } + }, + + /** + * @class + * @private + * @name TextureCache + * @memberof PIXI + * @see PIXI.utils.TextureCache + * @deprecated since version 3.0.0 + */ + TextureCache: { + get: function get() { + warn('The TextureCache class has been moved to utils.TextureCache, ' + 'please use utils.TextureCache from now on.'); + + return core.utils.TextureCache; + } + }, + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + math: { + get: function get() { + warn('The math namespace is deprecated, please access members already accessible on PIXI.'); + + return core; + } + }, + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.Filter; + } + }, + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + TransformManual: { + get: function get() { + warn('TransformManual has been renamed to TransformBase, please update your pixi-spine'); + + return core.TransformBase; + } + }, + + /** + * @static + * @constant + * @name PIXI.TARGET_FPMS + * @see PIXI.settings.TARGET_FPMS + * @deprecated since version 4.2.0 + */ + TARGET_FPMS: { + get: function get() { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + return core.settings.TARGET_FPMS; + }, + set: function set(value) { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + core.settings.TARGET_FPMS = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.FILTER_RESOLUTION + * @see PIXI.settings.FILTER_RESOLUTION + * @deprecated since version 4.2.0 + */ + FILTER_RESOLUTION: { + get: function get() { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + return core.settings.FILTER_RESOLUTION; + }, + set: function set(value) { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + core.settings.FILTER_RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RESOLUTION + * @see PIXI.settings.RESOLUTION + * @deprecated since version 4.2.0 + */ + RESOLUTION: { + get: function get() { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + return core.settings.RESOLUTION; + }, + set: function set(value) { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + core.settings.RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.MIPMAP_TEXTURES + * @see PIXI.settings.MIPMAP_TEXTURES + * @deprecated since version 4.2.0 + */ + MIPMAP_TEXTURES: { + get: function get() { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + return core.settings.MIPMAP_TEXTURES; + }, + set: function set(value) { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + core.settings.MIPMAP_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_BATCH_SIZE + * @see PIXI.settings.SPRITE_BATCH_SIZE + * @deprecated since version 4.2.0 + */ + SPRITE_BATCH_SIZE: { + get: function get() { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + return core.settings.SPRITE_BATCH_SIZE; + }, + set: function set(value) { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + core.settings.SPRITE_BATCH_SIZE = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_MAX_TEXTURES + * @see PIXI.settings.SPRITE_MAX_TEXTURES + * @deprecated since version 4.2.0 + */ + SPRITE_MAX_TEXTURES: { + get: function get() { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + return core.settings.SPRITE_MAX_TEXTURES; + }, + set: function set(value) { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + core.settings.SPRITE_MAX_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RETINA_PREFIX + * @see PIXI.settings.RETINA_PREFIX + * @deprecated since version 4.2.0 + */ + RETINA_PREFIX: { + get: function get() { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + return core.settings.RETINA_PREFIX; + }, + set: function set(value) { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + core.settings.RETINA_PREFIX = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.DEFAULT_RENDER_OPTIONS + * @see PIXI.settings.RENDER_OPTIONS + * @deprecated since version 4.2.0 + */ + DEFAULT_RENDER_OPTIONS: { + get: function get() { + warn('PIXI.DEFAULT_RENDER_OPTIONS has been deprecated, please use PIXI.settings.DEFAULT_RENDER_OPTIONS'); + + return core.settings.RENDER_OPTIONS; + } + } + }); + + // Move the default properties to settings + var defaults = [{ parent: 'TRANSFORM_MODE', target: 'TRANSFORM_MODE' }, { parent: 'GC_MODES', target: 'GC_MODE' }, { parent: 'WRAP_MODES', target: 'WRAP_MODE' }, { parent: 'SCALE_MODES', target: 'SCALE_MODE' }, { parent: 'PRECISION', target: 'PRECISION_FRAGMENT' }]; + + var _loop = function _loop(i) { + var deprecation = defaults[i]; + + Object.defineProperty(core[deprecation.parent], 'DEFAULT', { + get: function get() { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); + + return core.settings[deprecation.target]; + }, + set: function set(value) { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); + + core.settings[deprecation.target] = value; + } + }); + }; + + for (var i = 0; i < defaults.length; i++) { + _loop(i); + } + + Object.defineProperties(core.settings, { + + /** + * @static + * @name PRECISION + * @memberof PIXI.settings + * @see PIXI.PRECISION + * @deprecated since version 4.4.0 + */ + PRECISION: { + get: function get() { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + return core.settings.PRECISION_FRAGMENT; + }, + set: function set(value) { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + core.settings.PRECISION_FRAGMENT = value; + } + } + }); + + if (extras.AnimatedSprite) { + Object.defineProperties(extras, { + + /** + * @class + * @name MovieClip + * @memberof PIXI.extras + * @see PIXI.extras.AnimatedSprite + * @deprecated since version 4.2.0 + */ + MovieClip: { + get: function get() { + warn('The MovieClip class has been renamed to AnimatedSprite, please use AnimatedSprite from now on.'); + + return extras.AnimatedSprite; + } + } + }); + } + + if (extras) { + Object.defineProperties(extras, { + /** + * @class + * @name TextureTransform + * @memberof PIXI.extras + * @see PIXI.TextureMatrix + * @deprecated since version 4.6.0 + */ + TextureTransform: { + get: function get() { + warn('The TextureTransform class has been renamed to TextureMatrix, ' + 'please use PIXI.TextureMatrix from now on.'); + + return core.TextureMatrix; + } + } + }); + } + + core.DisplayObject.prototype.generateTexture = function generateTexture(renderer, scaleMode, resolution) { + warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); + + return renderer.generateTexture(this, scaleMode, resolution); + }; + + core.Graphics.prototype.generateTexture = function generateTexture(scaleMode, resolution) { + warn('graphics generate texture has moved to the renderer. ' + 'Or to render a graphics to a texture using canvas please use generateCanvasTexture'); + + return this.generateCanvasTexture(scaleMode, resolution); + }; + + /** + * @method + * @name PIXI.GroupD8.isSwapWidthHeight + * @see PIXI.GroupD8.isVertical + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the direction is vertical + * @deprecated since version 4.6.0 + */ + core.GroupD8.isSwapWidthHeight = function isSwapWidthHeight(rotation) { + warn('GroupD8.isSwapWidthHeight was renamed to GroupD8.isVertical'); + + return core.GroupD8.isVertical(rotation); + }; + + core.RenderTexture.prototype.render = function render(displayObject, matrix, clear, updateTransform) { + this.legacyRenderer.render(displayObject, this, clear, matrix, !updateTransform); + warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)'); + }; + + core.RenderTexture.prototype.getImage = function getImage(target) { + warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); + + return this.legacyRenderer.extract.image(target); + }; + + core.RenderTexture.prototype.getBase64 = function getBase64(target) { + warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); + + return this.legacyRenderer.extract.base64(target); + }; + + core.RenderTexture.prototype.getCanvas = function getCanvas(target) { + warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); + + return this.legacyRenderer.extract.canvas(target); + }; + + core.RenderTexture.prototype.getPixels = function getPixels(target) { + warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); + + return this.legacyRenderer.pixels(target); + }; + + /** + * @method + * @private + * @name PIXI.Sprite#setTexture + * @see PIXI.Sprite#texture + * @deprecated since version 3.0.0 + * @param {PIXI.Texture} texture - The texture to set to. + */ + core.Sprite.prototype.setTexture = function setTexture(texture) { + this.texture = texture; + warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;'); + }; + + if (extras.BitmapText) { + /** + * @method + * @name PIXI.extras.BitmapText#setText + * @see PIXI.extras.BitmapText#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ + extras.BitmapText.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';'); + }; + } + + /** + * @method + * @name PIXI.Text#setText + * @see PIXI.Text#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ + core.Text.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';'); + }; + + /** + * Calculates the ascent, descent and fontSize of a given fontStyle + * + * @name PIXI.Text.calculateFontProperties + * @see PIXI.TextMetrics.measureFont + * @deprecated since version 4.5.0 + * @param {string} font - String representing the style of the font + * @return {Object} Font properties object + */ + core.Text.calculateFontProperties = function calculateFontProperties(font) { + warn('Text.calculateFontProperties is now deprecated, please use the TextMetrics.measureFont'); + + return core.TextMetrics.measureFont(font); + }; + + Object.defineProperties(core.Text, { + fontPropertiesCache: { + get: function get() { + warn('Text.fontPropertiesCache is deprecated'); + + return core.TextMetrics._fonts; + } + }, + fontPropertiesCanvas: { + get: function get() { + warn('Text.fontPropertiesCanvas is deprecated'); + + return core.TextMetrics._canvas; + } + }, + fontPropertiesContext: { + get: function get() { + warn('Text.fontPropertiesContext is deprecated'); + + return core.TextMetrics._context; + } + } + }); + + /** + * @method + * @name PIXI.Text#setStyle + * @see PIXI.Text#style + * @deprecated since version 3.0.0 + * @param {*} style - The style to set to. + */ + core.Text.prototype.setStyle = function setStyle(style) { + this.style = style; + warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;'); + }; + + /** + * @method + * @name PIXI.Text#determineFontProperties + * @see PIXI.Text#measureFontProperties + * @deprecated since version 4.2.0 + * @private + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ + core.Text.prototype.determineFontProperties = function determineFontProperties(fontStyle) { + warn('determineFontProperties is now deprecated, please use TextMetrics.measureFont method'); + + return core.TextMetrics.measureFont(fontStyle); + }; + + /** + * @method + * @name PIXI.Text.getFontStyle + * @see PIXI.TextMetrics.getFontStyle + * @deprecated since version 4.5.0 + * @param {PIXI.TextStyle} style - The style to use. + * @return {string} Font string + */ + core.Text.getFontStyle = function getFontStyle(style) { + warn('getFontStyle is now deprecated, please use TextStyle.toFontString() instead'); + + style = style || {}; + + if (!(style instanceof core.TextStyle)) { + style = new core.TextStyle(style); + } + + return style.toFontString(); + }; + + Object.defineProperties(core.TextStyle.prototype, { + /** + * Set all properties of a font as a single string + * + * @name PIXI.TextStyle#font + * @deprecated since version 4.0.0 + */ + font: { + get: function get() { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\', \'fontSize\', \'fontStyle\', \'fontVariant\' and \'fontWeight\' properties from now on'); + + var fontSizeString = typeof this._fontSize === 'number' ? this._fontSize + 'px' : this._fontSize; + + return this._fontStyle + ' ' + this._fontVariant + ' ' + this._fontWeight + ' ' + fontSizeString + ' ' + this._fontFamily; + }, + set: function set(font) { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + + // can work out fontStyle from search of whole string + if (font.indexOf('italic') > 1) { + this._fontStyle = 'italic'; + } else if (font.indexOf('oblique') > -1) { + this._fontStyle = 'oblique'; + } else { + this._fontStyle = 'normal'; + } + + // can work out fontVariant from search of whole string + if (font.indexOf('small-caps') > -1) { + this._fontVariant = 'small-caps'; + } else { + this._fontVariant = 'normal'; + } + + // fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units + var splits = font.split(' '); + var fontSizeIndex = -1; + + this._fontSize = 26; + for (var i = 0; i < splits.length; ++i) { + if (splits[i].match(/(px|pt|em|%)/)) { + fontSizeIndex = i; + this._fontSize = splits[i]; + break; + } + } + + // we can now search for fontWeight as we know it must occur before the fontSize + this._fontWeight = 'normal'; + for (var _i = 0; _i < fontSizeIndex; ++_i) { + if (splits[_i].match(/(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/)) { + this._fontWeight = splits[_i]; + break; + } + } + + // and finally join everything together after the fontSize in case the font family has multiple words + if (fontSizeIndex > -1 && fontSizeIndex < splits.length - 1) { + this._fontFamily = ''; + for (var _i2 = fontSizeIndex + 1; _i2 < splits.length; ++_i2) { + this._fontFamily += splits[_i2] + ' '; + } + + this._fontFamily = this._fontFamily.slice(0, -1); + } else { + this._fontFamily = 'Arial'; + } + + this.styleID++; + } + } + }); + + /** + * @method + * @name PIXI.Texture#setFrame + * @see PIXI.Texture#setFrame + * @deprecated since version 3.0.0 + * @param {PIXI.Rectangle} frame - The frame to set. + */ + core.Texture.prototype.setFrame = function setFrame(frame) { + this.frame = frame; + warn('setFrame is now deprecated, please use the frame property, e.g: myTexture.frame = frame;'); + }; + + /** + * @static + * @function + * @name PIXI.Texture.addTextureToCache + * @see PIXI.Texture.addToCache + * @deprecated since 4.5.0 + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the texture will be stored against. + */ + core.Texture.addTextureToCache = function addTextureToCache(texture, id) { + core.Texture.addToCache(texture, id); + warn('Texture.addTextureToCache is deprecated, please use Texture.addToCache from now on.'); + }; + + /** + * @static + * @function + * @name PIXI.Texture.removeTextureFromCache + * @see PIXI.Texture.removeFromCache + * @deprecated since 4.5.0 + * @param {string} id - The id of the texture to be removed + * @return {PIXI.Texture|null} The texture that was removed + */ + core.Texture.removeTextureFromCache = function removeTextureFromCache(id) { + warn('Texture.removeTextureFromCache is deprecated, please use Texture.removeFromCache from now on. ' + 'Be aware that Texture.removeFromCache does not automatically its BaseTexture from the BaseTextureCache. ' + 'For that, use BaseTexture.removeFromCache'); + + core.BaseTexture.removeFromCache(id); + + return core.Texture.removeFromCache(id); + }; + + Object.defineProperties(filters, { + + /** + * @class + * @private + * @name PIXI.filters.AbstractFilter + * @see PIXI.AbstractFilter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.AbstractFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.SpriteMaskFilter + * @see PIXI.SpriteMaskFilter + * @deprecated since version 3.0.6 + */ + SpriteMaskFilter: { + get: function get() { + warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.'); + + return core.SpriteMaskFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.VoidFilter + * @see PIXI.filters.AlphaFilter + * @deprecated since version 4.5.7 + */ + VoidFilter: { + get: function get() { + warn('VoidFilter has been renamed to AlphaFilter, please use PIXI.filters.AlphaFilter'); + + return filters.AlphaFilter; + } + } + }); + + /** + * @method + * @name PIXI.utils.uuid + * @see PIXI.utils.uid + * @deprecated since version 3.0.6 + * @return {number} The uid + */ + core.utils.uuid = function () { + warn('utils.uuid() is deprecated, please use utils.uid() from now on.'); + + return core.utils.uid(); + }; + + /** + * @method + * @name PIXI.utils.canUseNewCanvasBlendModes + * @see PIXI.CanvasTinter + * @deprecated + * @return {boolean} Can use blend modes. + */ + core.utils.canUseNewCanvasBlendModes = function () { + warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on'); + + return core.CanvasTinter.canUseMultiply; + }; + + var saidHello = true; + + /** + * @name PIXI.utils._saidHello + * @type {boolean} + * @see PIXI.utils.skipHello + * @deprecated since 4.1.0 + */ + Object.defineProperty(core.utils, '_saidHello', { + set: function set(bool) { + if (bool) { + warn('PIXI.utils._saidHello is deprecated, please use PIXI.utils.skipHello()'); + this.skipHello(); + } + saidHello = bool; + }, + get: function get() { + return saidHello; + } + }); + + if (prepare.BasePrepare) { + /** + * @method + * @name PIXI.prepare.BasePrepare#register + * @see PIXI.prepare.BasePrepare#registerFindHook + * @deprecated since version 4.4.2 + * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + prepare.BasePrepare.prototype.register = function register(addHook, uploadHook) { + warn('renderer.plugins.prepare.register is now deprecated, ' + 'please use renderer.plugins.prepare.registerFindHook & renderer.plugins.prepare.registerUploadHook'); + + if (addHook) { + this.registerFindHook(addHook); + } + + if (uploadHook) { + this.registerUploadHook(uploadHook); + } + + return this; + }; + } + + if (prepare.canvas) { + /** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.canvas.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ + Object.defineProperty(prepare.canvas, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } + }); + } + + if (prepare.webgl) { + /** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.webgl.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ + Object.defineProperty(prepare.webgl, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } + }); + } + + if (loaders.Loader) { + var Resource = loaders.Resource; + var Loader = loaders.Loader; + + Object.defineProperties(Resource.prototype, { + isJson: { + get: function get() { + warn('The isJson property is deprecated, please use `resource.type === Resource.TYPE.JSON`.'); + + return this.type === Resource.TYPE.JSON; + } + }, + isXml: { + get: function get() { + warn('The isXml property is deprecated, please use `resource.type === Resource.TYPE.XML`.'); + + return this.type === Resource.TYPE.XML; + } + }, + isImage: { + get: function get() { + warn('The isImage property is deprecated, please use `resource.type === Resource.TYPE.IMAGE`.'); + + return this.type === Resource.TYPE.IMAGE; + } + }, + isAudio: { + get: function get() { + warn('The isAudio property is deprecated, please use `resource.type === Resource.TYPE.AUDIO`.'); + + return this.type === Resource.TYPE.AUDIO; + } + }, + isVideo: { + get: function get() { + warn('The isVideo property is deprecated, please use `resource.type === Resource.TYPE.VIDEO`.'); + + return this.type === Resource.TYPE.VIDEO; + } + } + }); + + Object.defineProperties(Loader.prototype, { + before: { + get: function get() { + warn('The before() method is deprecated, please use pre().'); + + return this.pre; + } + }, + after: { + get: function get() { + warn('The after() method is deprecated, please use use().'); + + return this.use; + } + } + }); + } + + if (interaction.interactiveTarget) { + /** + * @name PIXI.interaction.interactiveTarget#defaultCursor + * @static + * @type {number} + * @see PIXI.interaction.interactiveTarget#cursor + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.interactiveTarget, 'defaultCursor', { + set: function set(value) { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + this.cursor = value; + }, + get: function get() { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + + return this.cursor; + } + }); + } + + if (interaction.InteractionManager) { + /** + * @name PIXI.interaction.InteractionManager#defaultCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.InteractionManager, 'defaultCursorStyle', { + set: function set(value) { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + this.cursorStyles.default = value; + }, + get: function get() { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + + return this.cursorStyles.default; + } + }); + + /** + * @name PIXI.interaction.InteractionManager#currentCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.InteractionManager, 'currentCursorStyle', { + set: function set(value) { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + this.currentCursorMode = value; + }, + get: function get() { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + + return this.currentCursorMode; + } + }); + } +} + +},{}],132:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI.extract + */ + +var CanvasExtract = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasExtract(renderer) { + _classCallCheck(this, CanvasExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.extract.CanvasExtract} extract + * @memberof PIXI.CanvasRenderer# + * @see PIXI.extract.CanvasExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + CanvasExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `CanvasExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + CanvasExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + CanvasExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = this.renderer.width; + frame.height = this.renderer.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height, 1); + var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + CanvasExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + + return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; + }; + + /** + * Destroys the extract + * + */ + + + CanvasExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return CanvasExtract; +}(); + +exports.default = CanvasExtract; + + +core.CanvasRenderer.registerPlugin('extract', CanvasExtract); + +},{"../../core":65}],133:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLExtract = require('./webgl/WebGLExtract'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLExtract).default; + } +}); + +var _CanvasExtract = require('./canvas/CanvasExtract'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasExtract).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./canvas/CanvasExtract":132,"./webgl/WebGLExtract":134}],134:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); +var BYTES_PER_PIXEL = 4; + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI.extract + */ + +var WebGLExtract = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLExtract(renderer) { + _classCallCheck(this, WebGLExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.extract.WebGLExtract} extract + * @memberof PIXI.WebGLRenderer# + * @see PIXI.extract.WebGLExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + WebGLExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `WebGLExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + WebGLExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + WebGLExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var flipY = false; + var renderTexture = void 0; + var generated = false; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + generated = true; + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + flipY = false; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + flipY = true; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var canvasBuffer = new core.CanvasRenderTarget(width, height, 1); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + + // set up an array of pixels + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + + canvasData.data.set(webglPixels); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // pulling pixels + if (flipY) { + canvasBuffer.context.scale(1, -1); + canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); + } + } + + if (generated) { + renderTexture.destroy(true); + } + // send the canvas back.. + + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + WebGLExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + var generated = false; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + generated = true; + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + } + + if (generated) { + renderTexture.destroy(true); + } + + return webglPixels; + }; + + /** + * Destroys the extract + * + */ + + + WebGLExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return WebGLExtract; +}(); + +exports.default = WebGLExtract; + + +core.WebGLRenderer.registerPlugin('extract', WebGLExtract); + +},{"../../core":65}],135:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @typedef PIXI.extras.AnimatedSprite~FrameObject + * @type {object} + * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame + * @property {number} time - the duration of the frame in ms + */ + +/** + * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. + * + * ```js + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; + * + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.fromImage(alienImages[i]); + * textureArray.push(texture); + * }; + * + * let animatedSprite = new PIXI.extras.AnimatedSprite(textureArray); + * ``` + * + * The more efficient and simpler way to create an animated sprite is using a {@link PIXI.Spritesheet} + * containing the animation definitions: + * + * ```js + * PIXI.loader.add("assets/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.loader.resources["assets/spritesheet.json"].spritesheet; + * animatedSprite = new PIXI.extras.AnimatedSprite(sheet.animations["image_sequence"]); + * ... + * } + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ +var AnimatedSprite = function (_core$Sprite) { + _inherits(AnimatedSprite, _core$Sprite); + + /** + * @param {PIXI.Texture[]|PIXI.extras.AnimatedSprite~FrameObject[]} textures - an array of {@link PIXI.Texture} or frame + * objects that make up the animation + * @param {boolean} [autoUpdate=true] - Whether to use PIXI.ticker.shared to auto update animation time. + */ + function AnimatedSprite(textures, autoUpdate) { + _classCallCheck(this, AnimatedSprite); + + /** + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture)); + + _this._textures = null; + + /** + * @private + */ + _this._durations = null; + + _this.textures = textures; + + /** + * `true` uses PIXI.ticker.shared to auto update animation time. + * @type {boolean} + * @default true + * @private + */ + _this._autoUpdate = autoUpdate !== false; + + /** + * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower + * + * @member {number} + * @default 1 + */ + _this.animationSpeed = 1; + + /** + * Whether or not the animate sprite repeats after playing. + * + * @member {boolean} + * @default true + */ + _this.loop = true; + + /** + * Function to call when a AnimatedSprite finishes playing + * + * @member {Function} + */ + _this.onComplete = null; + + /** + * Function to call when a AnimatedSprite changes which texture is being rendered + * + * @member {Function} + */ + _this.onFrameChange = null; + + /** + * Function to call when 'loop' is true, and an AnimatedSprite is played and loops around to start again + * + * @member {Function} + */ + _this.onLoop = null; + + /** + * Elapsed time since animation has been started, used internally to display current texture + * + * @member {number} + * @private + */ + _this._currentTime = 0; + + /** + * Indicates if the AnimatedSprite is currently playing + * + * @member {boolean} + * @readonly + */ + _this.playing = false; + return _this; + } + + /** + * Stops the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.stop = function stop() { + if (!this.playing) { + return; + } + + this.playing = false; + if (this._autoUpdate) { + core.ticker.shared.remove(this.update, this); + } + }; + + /** + * Plays the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.play = function play() { + if (this.playing) { + return; + } + + this.playing = true; + if (this._autoUpdate) { + core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.HIGH); + } + }; + + /** + * Stops the AnimatedSprite and goes to a specific frame + * + * @param {number} frameNumber - frame index to stop at + */ + + + AnimatedSprite.prototype.gotoAndStop = function gotoAndStop(frameNumber) { + this.stop(); + + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + + /** + * Goes to a specific frame and begins playing the AnimatedSprite + * + * @param {number} frameNumber - frame index to start at + */ + + + AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay(frameNumber) { + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + + this.play(); + }; + + /** + * Updates the object transform for rendering. + * + * @private + * @param {number} deltaTime - Time since last tick. + */ + + + AnimatedSprite.prototype.update = function update(deltaTime) { + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + + lag += elapsed / 60 * 1000; + + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + + var sign = Math.sign(this.animationSpeed * deltaTime); + + this._currentTime = Math.floor(this._currentTime); + + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + + this._currentTime += lag / this._durations[this.currentFrame]; + } else { + this._currentTime += elapsed; + } + + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + + if (this.onComplete) { + this.onComplete(); + } + } else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + + if (this.onComplete) { + this.onComplete(); + } + } else if (previousFrame !== this.currentFrame) { + if (this.loop && this.onLoop) { + if (this.animationSpeed > 0 && this.currentFrame < previousFrame) { + this.onLoop(); + } else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) { + this.onLoop(); + } + } + + this.updateTexture(); + } + }; + + /** + * Updates the displayed texture to match the current frame index + * + * @private + */ + + + AnimatedSprite.prototype.updateTexture = function updateTexture() { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + this.cachedTint = 0xFFFFFF; + + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + }; + + /** + * Stops the AnimatedSprite and destroys it + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + AnimatedSprite.prototype.destroy = function destroy(options) { + this.stop(); + _core$Sprite.prototype.destroy.call(this, options); + }; + + /** + * A short hand way of creating a movieclip from an array of frame ids + * + * @static + * @param {string[]} frames - The array of frames ids the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animated sprite with the specified frames. + */ + + + AnimatedSprite.fromFrames = function fromFrames(frames) { + var textures = []; + + for (var i = 0; i < frames.length; ++i) { + textures.push(core.Texture.fromFrame(frames[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * A short hand way of creating a movieclip from an array of image ids + * + * @static + * @param {string[]} images - the array of image urls the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animate sprite with the specified images as frames. + */ + + + AnimatedSprite.fromImages = function fromImages(images) { + var textures = []; + + for (var i = 0; i < images.length; ++i) { + textures.push(core.Texture.fromImage(images[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * totalFrames is the total number of frames in the AnimatedSprite. This is the same as number of textures + * assigned to the AnimatedSprite. + * + * @readonly + * @member {number} + * @default 0 + */ + + + _createClass(AnimatedSprite, [{ + key: 'totalFrames', + get: function get() { + return this._textures.length; + } + + /** + * The array of textures used for this AnimatedSprite + * + * @member {PIXI.Texture[]} + */ + + }, { + key: 'textures', + get: function get() { + return this._textures; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value[0] instanceof core.Texture) { + this._textures = value; + this._durations = null; + } else { + this._textures = []; + this._durations = []; + + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + this.gotoAndStop(0); + this.updateTexture(); + } + + /** + * The AnimatedSprites current frame index + * + * @member {number} + * @readonly + */ + + }, { + key: 'currentFrame', + get: function get() { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + + return currentFrame; + } + }]); + + return AnimatedSprite; +}(core.Sprite); + +exports.default = AnimatedSprite; + +},{"../core":65}],136:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ObservablePoint = require('../core/math/ObservablePoint'); + +var _ObservablePoint2 = _interopRequireDefault(_ObservablePoint); + +var _utils = require('../core/utils'); + +var _settings = require('../core/settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BitmapText object will create a line or multiple lines of text using bitmap font. To + * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using: + * + * A BitmapText can only be created when the font is loaded + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); + * ``` + * + * http://www.angelcode.com/products/bmfont/ for windows or + * http://www.bmglyph.com/ for mac. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.extras + */ +var BitmapText = function (_core$Container) { + _inherits(BitmapText, _core$Container); + + /** + * @param {string} text - The copy that you would like the text to display + * @param {object} style - The style parameters + * @param {string|object} style.font - The font descriptor for the object, can be passed as a string of form + * "24px FontName" or "FontName" or as an object with explicit name/size properties. + * @param {string} [style.font.name] - The bitmap font id + * @param {number} [style.font.size] - The size of the font in pixels, e.g. 24 + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), does not affect + * single line text + * @param {number} [style.tint=0xFFFFFF] - The tint color + */ + function BitmapText(text) { + var style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _classCallCheck(this, BitmapText); + + /** + * Private tracker for the width of the overall text + * + * @member {number} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._textWidth = 0; + + /** + * Private tracker for the height of the overall text + * + * @member {number} + * @private + */ + _this._textHeight = 0; + + /** + * Private tracker for the letter sprite pool. + * + * @member {PIXI.Sprite[]} + * @private + */ + _this._glyphs = []; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._font = { + tint: style.tint !== undefined ? style.tint : 0xFFFFFF, + align: style.align || 'left', + name: null, + size: 0 + }; + + /** + * Private tracker for the current font. + * + * @member {object} + * @private + */ + _this.font = style.font; // run font setter + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = text; + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + * @private + */ + _this._maxWidth = 0; + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + * @private + */ + _this._maxLineHeight = 0; + + /** + * Letter spacing. This is useful for setting the space between characters. + * @member {number} + * @private + */ + _this._letterSpacing = 0; + + /** + * Text anchor. read-only + * + * @member {PIXI.ObservablePoint} + * @private + */ + _this._anchor = new _ObservablePoint2.default(function () { + _this.dirty = true; + }, _this, 0, 0); + + /** + * The dirty state of this object. + * + * @member {boolean} + */ + _this.dirty = false; + + _this.updateText(); + return _this; + } + + /** + * Renders text and updates it when needed + * + * @private + */ + + + BitmapText.prototype.updateText = function updateText() { + var data = BitmapText.fonts[this._font.name]; + var scale = this._font.size / data.size; + var pos = new core.Point(); + var chars = []; + var lineWidths = []; + var text = this.text.replace(/(?:\r\n|\r)/g, '\n'); + var textLength = text.length; + var maxWidth = this._maxWidth * data.size / this._font.size; + + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastBreakPos = -1; + var lastBreakWidth = 0; + var spacesRemoved = 0; + var maxLineHeight = 0; + + for (var i = 0; i < textLength; i++) { + var charCode = text.charCodeAt(i); + var char = text.charAt(i); + + if (/(?:\s)/.test(char)) { + lastBreakPos = i; + lastBreakWidth = lastLineWidth; + } + + if (char === '\r' || char === '\n') { + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + ++line; + ++spacesRemoved; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + var charData = data.chars[charCode]; + + if (!charData) { + continue; + } + + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + + chars.push({ + texture: charData.texture, + line: line, + charCode: charCode, + position: new core.Point(pos.x + charData.xOffset + this._letterSpacing / 2, pos.y + charData.yOffset) + }); + pos.x += charData.xAdvance + this._letterSpacing; + lastLineWidth = pos.x; + maxLineHeight = Math.max(maxLineHeight, charData.yOffset + charData.texture.height); + prevCharCode = charCode; + + if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth) { + ++spacesRemoved; + core.utils.removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos); + i = lastBreakPos; + lastBreakPos = -1; + + lineWidths.push(lastBreakWidth); + maxLineWidth = Math.max(maxLineWidth, lastBreakWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + } + } + + var lastChar = text.charAt(text.length - 1); + + if (lastChar !== '\r' && lastChar !== '\n') { + if (/(?:\s)/.test(lastChar)) { + lastLineWidth = lastBreakWidth; + } + + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + } + + var lineAlignOffsets = []; + + for (var _i = 0; _i <= line; _i++) { + var alignOffset = 0; + + if (this._font.align === 'right') { + alignOffset = maxLineWidth - lineWidths[_i]; + } else if (this._font.align === 'center') { + alignOffset = (maxLineWidth - lineWidths[_i]) / 2; + } + + lineAlignOffsets.push(alignOffset); + } + + var lenChars = chars.length; + var tint = this.tint; + + for (var _i2 = 0; _i2 < lenChars; _i2++) { + var c = this._glyphs[_i2]; // get the next glyph sprite + + if (c) { + c.texture = chars[_i2].texture; + } else { + c = new core.Sprite(chars[_i2].texture); + this._glyphs.push(c); + } + + c.position.x = (chars[_i2].position.x + lineAlignOffsets[chars[_i2].line]) * scale; + c.position.y = chars[_i2].position.y * scale; + c.scale.x = c.scale.y = scale; + c.tint = tint; + + if (!c.parent) { + this.addChild(c); + } + } + + // remove unnecessary children. + for (var _i3 = lenChars; _i3 < this._glyphs.length; ++_i3) { + this.removeChild(this._glyphs[_i3]); + } + + this._textWidth = maxLineWidth * scale; + this._textHeight = (pos.y + data.lineHeight) * scale; + + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + for (var _i4 = 0; _i4 < lenChars; _i4++) { + this._glyphs[_i4].x -= this._textWidth * this.anchor.x; + this._glyphs[_i4].y -= this._textHeight * this.anchor.y; + } + } + this._maxLineHeight = maxLineHeight * scale; + }; + + /** + * Updates the transform of this object + * + * @private + */ + + + BitmapText.prototype.updateTransform = function updateTransform() { + this.validate(); + this.containerUpdateTransform(); + }; + + /** + * Validates text before calling parent's getLocalBounds + * + * @return {PIXI.Rectangle} The rectangular bounding area + */ + + + BitmapText.prototype.getLocalBounds = function getLocalBounds() { + this.validate(); + + return _core$Container.prototype.getLocalBounds.call(this); + }; + + /** + * Updates text when needed + * + * @private + */ + + + BitmapText.prototype.validate = function validate() { + if (this.dirty) { + this.updateText(); + this.dirty = false; + } + }; + + /** + * The tint of the BitmapText object + * + * @member {number} + */ + + + /** + * Register a bitmap font with data and a texture. + * + * @static + * @param {XMLDocument} xml - The XML document data. + * @param {Object.|PIXI.Texture|PIXI.Texture[]} textures - List of textures for each page. + * If providing an object, the key is the `` element's `file` attribute in the FNT file. + * @return {Object} Result font object with font, size, lineHeight and char fields. + */ + BitmapText.registerFont = function registerFont(xml, textures) { + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + var pages = xml.getElementsByTagName('page'); + var res = (0, _utils.getResolutionOfUrl)(pages[0].getAttribute('file'), _settings2.default.RESOLUTION); + var pagesTextures = {}; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) / res; + data.chars = {}; + + // Single texture, convert to list + if (textures instanceof core.Texture) { + textures = [textures]; + } + + // Convert the input Texture, Textures or object + // into a page Texture lookup by "id" + for (var i = 0; i < pages.length; i++) { + var id = pages[i].getAttribute('id'); + var file = pages[i].getAttribute('file'); + + pagesTextures[id] = textures instanceof Array ? textures[i] : textures[file]; + } + + // parse letters + var letters = xml.getElementsByTagName('char'); + + for (var _i5 = 0; _i5 < letters.length; _i5++) { + var letter = letters[_i5]; + var charCode = parseInt(letter.getAttribute('id'), 10); + var page = letter.getAttribute('page') || 0; + var textureRect = new core.Rectangle(parseInt(letter.getAttribute('x'), 10) / res + pagesTextures[page].frame.x / res, parseInt(letter.getAttribute('y'), 10) / res + pagesTextures[page].frame.y / res, parseInt(letter.getAttribute('width'), 10) / res, parseInt(letter.getAttribute('height'), 10) / res); + + data.chars[charCode] = { + xOffset: parseInt(letter.getAttribute('xoffset'), 10) / res, + yOffset: parseInt(letter.getAttribute('yoffset'), 10) / res, + xAdvance: parseInt(letter.getAttribute('xadvance'), 10) / res, + kerning: {}, + texture: new core.Texture(pagesTextures[page].baseTexture, textureRect), + page: page + }; + } + + // parse kernings + var kernings = xml.getElementsByTagName('kerning'); + + for (var _i6 = 0; _i6 < kernings.length; _i6++) { + var kerning = kernings[_i6]; + var first = parseInt(kerning.getAttribute('first'), 10) / res; + var second = parseInt(kerning.getAttribute('second'), 10) / res; + var amount = parseInt(kerning.getAttribute('amount'), 10) / res; + + if (data.chars[second]) { + data.chars[second].kerning[first] = amount; + } + } + + // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 + // but it's very likely to change + BitmapText.fonts[data.font] = data; + + return data; + }; + + _createClass(BitmapText, [{ + key: 'tint', + get: function get() { + return this._font.tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.tint = typeof value === 'number' && value >= 0 ? value : 0xFFFFFF; + + this.dirty = true; + } + + /** + * The alignment of the BitmapText object + * + * @member {string} + * @default 'left' + */ + + }, { + key: 'align', + get: function get() { + return this._font.align; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.align = value || 'left'; + + this.dirty = true; + } + + /** + * The anchor sets the origin point of the text. + * The default is 0,0 this means the text's origin is the top left + * Setting the anchor to 0.5,0.5 means the text's origin is centered + * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner + * + * @member {PIXI.Point | number} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (typeof value === 'number') { + this._anchor.set(value); + } else { + this._anchor.copy(value); + } + } + + /** + * The font descriptor of the BitmapText object + * + * @member {string|object} + */ + + }, { + key: 'font', + get: function get() { + return this._font; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (!value) { + return; + } + + if (typeof value === 'string') { + value = value.split(' '); + + this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); + this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; + } else { + this._font.name = value.name; + this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); + } + + this.dirty = true; + } + + /** + * The text of the BitmapText object + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + value = value.toString() || ' '; + if (this._text === value) { + return; + } + this._text = value; + this.dirty = true; + } + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + */ + + }, { + key: 'maxWidth', + get: function get() { + return this._maxWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._maxWidth === value) { + return; + } + this._maxWidth = value; + this.dirty = true; + } + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + * @readonly + */ + + }, { + key: 'maxLineHeight', + get: function get() { + this.validate(); + + return this._maxLineHeight; + } + + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textWidth', + get: function get() { + this.validate(); + + return this._textWidth; + } + + /** + * Additional space between characters. + * + * @member {number} + */ + + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._letterSpacing !== value) { + this._letterSpacing = value; + this.dirty = true; + } + } + + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textHeight', + get: function get() { + this.validate(); + + return this._textHeight; + } + }]); + + return BitmapText; +}(core.Container); + +exports.default = BitmapText; + + +BitmapText.fonts = {}; + +},{"../core":65,"../core/math/ObservablePoint":68,"../core/settings":101,"../core/utils":125}],137:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CanvasTinter = require('../core/sprites/canvas/CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); + +/** + * A tiling sprite is a fast way of rendering a tiling image + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ + +var TilingSprite = function (_core$Sprite) { + _inherits(TilingSprite, _core$Sprite); + + /** + * @param {PIXI.Texture} texture - the texture of the tiling sprite + * @param {number} [width=100] - the width of the tiling sprite + * @param {number} [height=100] - the height of the tiling sprite + */ + function TilingSprite(texture) { + var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100; + + _classCallCheck(this, TilingSprite); + + /** + * Tile transform + * + * @member {PIXI.TransformStatic} + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, texture)); + + _this.tileTransform = new core.TransformStatic(); + + // /// private + + /** + * The with of the tiling sprite + * + * @member {number} + * @private + */ + _this._width = width; + + /** + * The height of the tiling sprite + * + * @member {number} + * @private + */ + _this._height = height; + + /** + * Canvas pattern + * + * @type {CanvasPattern} + * @private + */ + _this._canvasPattern = null; + + /** + * transform that is applied to UV to get the texture coords + * + * @member {PIXI.TextureMatrix} + */ + _this.uvTransform = texture.transform || new core.TextureMatrix(texture); + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' method. + * + * @member {string} + * @default 'tilingSprite' + */ + _this.pluginName = 'tilingSprite'; + + /** + * Whether or not anchor affects uvs + * + * @member {boolean} + * @default false + */ + _this.uvRespectAnchor = false; + return _this; + } + /** + * Changes frame clamping in corresponding textureTransform, shortcut + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + + + /** + * @private + */ + TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate() { + if (this.uvTransform) { + this.uvTransform.texture = this._texture; + } + this.cachedTint = 0xFFFFFF; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + TilingSprite.prototype._renderWebGL = function _renderWebGL(renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + + if (!texture || !texture.valid) { + return; + } + + this.tileTransform.updateLocalTransform(); + this.uvTransform.update(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer + */ + + + TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { + var texture = this._texture; + + if (!texture.baseTexture.hasLoaded) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var resolution = renderer.resolution; + var baseTexture = texture.baseTexture; + var baseTextureResolution = baseTexture.resolution; + var modX = this.tilePosition.x / this.tileScale.x % texture._frame.width * baseTextureResolution; + var modY = this.tilePosition.y / this.tileScale.y % texture._frame.height * baseTextureResolution; + + // create a nice shiny pattern! + if (this._textureID !== this._texture._updateID || this.cachedTint !== this.tint) { + this._textureID = this._texture._updateID; + // cut an object from a spritesheet.. + var tempCanvas = new core.CanvasRenderTarget(texture._frame.width, texture._frame.height, baseTextureResolution); + + // Tint the tiling sprite + if (this.tint !== 0xFFFFFF) { + this.tintedTexture = _CanvasTinter2.default.getTintedTexture(this, this.tint); + tempCanvas.context.drawImage(this.tintedTexture, 0, 0); + } else { + tempCanvas.context.drawImage(baseTexture.source, -texture._frame.x * baseTextureResolution, -texture._frame.y * baseTextureResolution); + } + this.cachedTint = this.tint; + this._canvasPattern = tempCanvas.context.createPattern(tempCanvas.canvas, 'repeat'); + } + + // set context state.. + context.globalAlpha = this.worldAlpha; + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + renderer.setBlendMode(this.blendMode); + + // fill the pattern! + context.fillStyle = this._canvasPattern; + + // TODO - this should be rolled into the setTransform above.. + context.scale(this.tileScale.x / baseTextureResolution, this.tileScale.y / baseTextureResolution); + + var anchorX = this.anchor.x * -this._width; + var anchorY = this.anchor.y * -this._height; + + if (this.uvRespectAnchor) { + context.translate(modX, modY); + + context.fillRect(-modX + anchorX, -modY + anchorY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } else { + context.translate(modX + anchorX, modY + anchorY); + + context.fillRect(-modX, -modY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } + }; + + /** + * Updates the bounds of the tiling sprite. + * + * @private + */ + + + TilingSprite.prototype._calculateBounds = function _calculateBounds() { + var minX = this._width * -this._anchor._x; + var minY = this._height * -this._anchor._y; + var maxX = this._width * (1 - this._anchor._x); + var maxY = this._height * (1 - this._anchor._y); + + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + TilingSprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._width * -this._anchor._x; + this._bounds.minY = this._height * -this._anchor._y; + this._bounds.maxX = this._width * (1 - this._anchor._x); + this._bounds.maxY = this._height * (1 - this._anchor._y); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new core.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _core$Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Checks if a point is inside this tiling sprite. + * + * @param {PIXI.Point} point - the point to check + * @return {boolean} Whether or not the sprite contains the point. + */ + + + TilingSprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor._x; + + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + var y1 = -height * this.anchor._y; + + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + TilingSprite.prototype.destroy = function destroy(options) { + _core$Sprite.prototype.destroy.call(this, options); + + this.tileTransform = null; + this.uvTransform = null; + }; + + /** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.Texture} The newly created texture + */ + + + TilingSprite.from = function from(source, width, height) { + return new TilingSprite(core.Texture.from(source), width, height); + }; + + /** + * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId + */ + + + TilingSprite.fromFrame = function fromFrame(frameId, width, height) { + var texture = core.utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this); + } + + return new TilingSprite(texture, width, height); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @param {boolean} [crossorigin] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id + */ + + + TilingSprite.fromImage = function fromImage(imageId, width, height, crossorigin, scaleMode) { + return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode), width, height); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(TilingSprite, [{ + key: 'clampMargin', + get: function get() { + return this.uvTransform.clampMargin; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uvTransform.clampMargin = value; + this.uvTransform.update(true); + } + + /** + * The scaling of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tileScale', + get: function get() { + return this.tileTransform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.scale.copy(value); + } + + /** + * The offset of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tilePosition', + get: function get() { + return this.tileTransform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.position.copy(value); + } + }, { + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + } + + /** + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + } + }]); + + return TilingSprite; +}(core.Sprite); + +exports.default = TilingSprite; + +},{"../core":65,"../core/sprites/canvas/CanvasTinter":104}],138:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _BaseTexture = require('../core/textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _utils = require('../core/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DisplayObject = core.DisplayObject; +var _tempMatrix = new core.Matrix(); + +DisplayObject.prototype._cacheAsBitmap = false; +DisplayObject.prototype._cacheData = false; + +// figured theres no point adding ALL the extra variables to prototype. +// this model can hold the information needed. This can also be generated on demand as +// most objects are not cached as bitmaps. +/** + * @class + * @ignore + */ + +var CacheData = +/** + * + */ +function CacheData() { + _classCallCheck(this, CacheData); + + this.textureCacheId = null; + + this.originalRenderWebGL = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + + this.originalUpdateTransform = null; + this.originalHitTest = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.sprite = null; +}; + +Object.defineProperties(DisplayObject.prototype, { + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to 'false' + * + * IMPORTANT GOTCHA - make sure that all your textures are preloaded BEFORE setting this property to true + * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function get() { + return this._cacheAsBitmap; + }, + set: function set(value) { + if (this._cacheAsBitmap === value) { + return; + } + + this._cacheAsBitmap = value; + + var data = void 0; + + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + + data = this._cacheData; + + data.originalRenderWebGL = this.renderWebGL; + data.originalRenderCanvas = this.renderCanvas; + + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this._calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + + data.originalDestroy = this.destroy; + + data.originalContainsPoint = this.containsPoint; + + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + + this.renderWebGL = this._renderCachedWebGL; + this.renderCanvas = this._renderCachedCanvas; + + this.destroy = this._cacheAsBitmapDestroy; + } else { + data = this._cacheData; + + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + + this.renderWebGL = data.originalRenderWebGL; + this.renderCanvas = data.originalRenderCanvas; + this._calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + + this.destroy = data.originalDestroy; + + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + } + } +}); + +/** + * Renders a cached version of the sprite with WebGL + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedWebGL = function _renderCachedWebGL(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObject(renderer); + + this._cacheData.sprite._transformID = -1; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderWebGL(renderer); +}; + +/** + * Prepares the WebGL renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + + this.alpha = 1; + + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.currentRenderer.flush(); + // this.filters= []; + + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds().clone(); + + // add some padding! + if (this._filters) { + var padding = this._filters[0].padding; + + bounds.pad(padding); + } + + // for now we cache the current renderTarget that the webGL renderer is currently using. + // this could be more elegent.. + var cachedRenderTarget = renderer._activeRenderTarget; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + var stack = renderer.filterManager.filterStack; + + // this renderTexture will be used to store the cached DisplayObject + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); + + this._cacheData.textureCacheId = textureCacheId; + + _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); + _Texture2.default.addToCache(renderTexture, textureCacheId); + + // need to set // + var m = _tempMatrix; + + m.tx = -bounds.x; + m.ty = -bounds.y; + + // reset + this.transform.worldTransform.identity(); + + // set all properties to there original so we can render to a texture + this.renderWebGL = this._cacheData.originalRenderWebGL; + + renderer.render(this, renderTexture, true, m, true); + // now restore the state be setting the new properties + + renderer.bindRenderTarget(cachedRenderTarget); + + renderer.filterManager.filterStack = stack; + + this.renderWebGL = this._renderCachedWebGL; + this.updateTransform = this.displayObjectUpdateTransform; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + + // easy bounds.. + this._calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + + this._cacheData.sprite = cachedSprite; + + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this.updateTransform(); + } + + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Renders a cached version of the sprite with canvas + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObjectCanvas(renderer); + + this._cacheData.sprite.worldAlpha = this.worldAlpha; + + this._cacheData.sprite.renderCanvas(renderer); +}; + +// TODO this can be the same as the webGL verison.. will need to do a little tweaking first though.. +/** + * Prepares the Canvas renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(); + + var cacheAlpha = this.alpha; + + this.alpha = 1; + + var cachedRenderTarget = renderer.context; + + var renderTexture = core.RenderTexture.create(bounds.width | 0, bounds.height | 0); + + var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); + + this._cacheData.textureCacheId = textureCacheId; + + _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); + _Texture2.default.addToCache(renderTexture, textureCacheId); + + // need to set // + var m = _tempMatrix; + + this.transform.localTransform.copy(m); + m.invert(); + + m.tx -= bounds.x; + m.ty -= bounds.y; + + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + + // renderTexture.render(this, m, true); + renderer.render(this, renderTexture, true, m, false); + + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + + this.renderCanvas = this._renderCachedCanvas; + this._calculateBounds = this._calculateCachedBounds; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite._bounds = this._bounds; + cachedSprite.alpha = cacheAlpha; + + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this.updateTransform(); + } + + this.updateTransform = this.displayObjectUpdateTransform; + + this._cacheData.sprite = cachedSprite; + + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Calculates the bounds of the cached sprite + * + * @private + */ +DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._cacheData.sprite._calculateBounds(); +}; + +/** + * Gets the bounds of the cached sprite. + * + * @private + * @return {Rectangle} The local bounds. + */ +DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(); +}; + +/** + * Destroys the cached sprite. + * + * @private + */ +DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; + + _BaseTexture2.default.removeFromCache(this._cacheData.textureCacheId); + _Texture2.default.removeFromCache(this._cacheData.textureCacheId); + + this._cacheData.textureCacheId = null; +}; + +/** + * Destroys the cached object. + * + * @private + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * Used when destroying containers, see the Container.destroy method. + */ +DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { + this.cacheAsBitmap = false; + this.destroy(options); +}; + +},{"../core":65,"../core/textures/BaseTexture":112,"../core/textures/Texture":115,"../core/utils":125}],139:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * The instance name of the object. + * + * @memberof PIXI.DisplayObject# + * @member {string} name + */ +core.DisplayObject.prototype.name = null; + +/** + * Returns the display object in the container + * + * @method getChildByName + * @memberof PIXI.Container# + * @param {string} name - instance name + * @return {PIXI.DisplayObject} The child with the specified name. + */ +core.Container.prototype.getChildByName = function getChildByName(name) { + for (var i = 0; i < this.children.length; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + + return null; +}; + +},{"../core":65}],140:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. + * + * @method getGlobalPosition + * @memberof PIXI.DisplayObject# + * @param {Point} point - the point to write the global value to. If null a new point will be returned + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @return {Point} The updated point + */ +core.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition() { + var point = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new core.Point(); + var skipUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (this.parent) { + this.parent.toGlobal(this.position, point, skipUpdate); + } else { + point.x = this.position.x; + point.y = this.position.y; + } + + return point; +}; + +},{"../core":65}],141:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BitmapText = exports.TilingSpriteRenderer = exports.TilingSprite = exports.AnimatedSprite = undefined; + +var _AnimatedSprite = require('./AnimatedSprite'); + +Object.defineProperty(exports, 'AnimatedSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AnimatedSprite).default; + } +}); + +var _TilingSprite = require('./TilingSprite'); + +Object.defineProperty(exports, 'TilingSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSprite).default; + } +}); + +var _TilingSpriteRenderer = require('./webgl/TilingSpriteRenderer'); + +Object.defineProperty(exports, 'TilingSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSpriteRenderer).default; + } +}); + +var _BitmapText = require('./BitmapText'); + +Object.defineProperty(exports, 'BitmapText', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BitmapText).default; + } +}); + +require('./cacheAsBitmap'); + +require('./getChildByName'); + +require('./getGlobalPosition'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// imported for side effect of extending the prototype only, contains no exports + +},{"./AnimatedSprite":135,"./BitmapText":136,"./TilingSprite":137,"./cacheAsBitmap":138,"./getChildByName":139,"./getGlobalPosition":140,"./webgl/TilingSpriteRenderer":142}],142:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _const = require('../../core/const'); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMat = new core.Matrix(); + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI.extras + * @extends PIXI.ObjectRenderer + */ + +var TilingSpriteRenderer = function (_core$ObjectRenderer) { + _inherits(TilingSpriteRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function TilingSpriteRenderer(renderer) { + _classCallCheck(this, TilingSpriteRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + _this.simpleShader = null; + _this.quad = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + TilingSpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n gl_FragColor = sample * uColor;\n}\n'); + this.simpleShader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = sample * uColor;\n}\n'); + + this.renderer.bindVao(null); + this.quad = new core.Quad(gl, this.renderer.state.attribState); + this.quad.initVao(this.shader); + }; + + /** + * + * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered + */ + + + TilingSpriteRenderer.prototype.render = function render(ts) { + var renderer = this.renderer; + var quad = this.quad; + + renderer.bindVao(quad.vao); + + var vertices = quad.vertices; + + vertices[0] = vertices[6] = ts._width * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + + vertices[2] = vertices[4] = ts._width * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + + if (ts.uvRespectAnchor) { + vertices = quad.uvs; + + vertices[0] = vertices[6] = -ts.anchor.x; + vertices[1] = vertices[3] = -ts.anchor.y; + + vertices[2] = vertices[4] = 1.0 - ts.anchor.x; + vertices[5] = vertices[7] = 1.0 - ts.anchor.y; + } + + quad.upload(); + + var tex = ts._texture; + var baseTex = tex.baseTexture; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvTransform; + var isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === _const.WRAP_MODES.CLAMP) { + baseTex.wrapMode = _const.WRAP_MODES.REPEAT; + } + } else { + isSimple = baseTex.wrapMode !== _const.WRAP_MODES.CLAMP; + } + } + + var shader = isSimple ? this.simpleShader : this.shader; + + renderer.bindShader(shader); + + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + + tempMat.invert(); + if (isSimple) { + tempMat.prepend(uv.mapCoord); + } else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + + shader.uniforms.uTransform = tempMat.toArray(true); + shader.uniforms.uColor = core.utils.premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, baseTex.premultipliedAlpha); + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + + shader.uniforms.uSampler = renderer.bindTexture(tex); + + renderer.setBlendMode(core.utils.correctBlendMode(ts.blendMode, baseTex.premultipliedAlpha)); + + quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + }; + + return TilingSpriteRenderer; +}(core.ObjectRenderer); + +exports.default = TilingSpriteRenderer; + + +core.WebGLRenderer.registerPlugin('tilingSprite', TilingSpriteRenderer); + +},{"../../core":65,"../../core/const":46,"path":8}],143:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Simplest filter - applies alpha + * + * Use this instead of Container's alpha property to avoid visual layering of individual elements. + * AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains. + * If elements are not opaque, they will blend with each other anyway. + * + * Very handy if you want to use common features of all filters: + * + * 1. Assign a blendMode to this filter, blend all elements inside display object with background. + * + * 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var AlphaFilter = function (_core$Filter) { + _inherits(AlphaFilter, _core$Filter); + + /** + * @param {number} [alpha=1] Amount of alpha from 0 to 1, where 0 is transparent + */ + function AlphaFilter() { + var alpha = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1.0; + + _classCallCheck(this, AlphaFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n')); + + _this.alpha = alpha; + _this.glShaderKey = 'alpha'; + return _this; + } + + /** + * Coefficient for alpha multiplication + * + * @member {number} + * @default 1 + */ + + + _createClass(AlphaFilter, [{ + key: 'alpha', + get: function get() { + return this.uniforms.uAlpha; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uAlpha = value; + } + }]); + + return AlphaFilter; +}(core.Filter); + +exports.default = AlphaFilter; + +},{"../../core":65,"path":8}],144:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BlurXFilter = require('./BlurXFilter'); + +var _BlurXFilter2 = _interopRequireDefault(_BlurXFilter); + +var _BlurYFilter = require('./BlurYFilter'); + +var _BlurYFilter2 = _interopRequireDefault(_BlurYFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurFilter applies a Gaussian blur to an object. + * The strength of the blur can be set for x- and y-axis separately. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurFilter = function (_core$Filter) { + _inherits(BlurFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this)); + + _this.blurXFilter = new _BlurXFilter2.default(strength, quality, resolution, kernelSize); + _this.blurYFilter = new _BlurYFilter2.default(strength, quality, resolution, kernelSize); + + _this.padding = 0; + _this.resolution = resolution || core.settings.RESOLUTION; + _this.quality = quality || 4; + _this.blur = strength || 8; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + BlurFilter.prototype.apply = function apply(filterManager, input, output) { + var renderTarget = filterManager.getRenderTarget(true); + + this.blurXFilter.apply(filterManager, input, renderTarget, true); + this.blurYFilter.apply(filterManager, renderTarget, output, false); + + filterManager.returnRenderTarget(renderTarget); + }; + + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurFilter, [{ + key: 'blur', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the number of passes for blur. More passes means higher quaility bluring. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'quality', + get: function get() { + return this.blurXFilter.quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.quality = this.blurYFilter.quality = value; + } + + /** + * Sets the strength of the blurX property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurX', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the strength of the blurY property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurY', + get: function get() { + return this.blurYFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the blendmode of the filter + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + */ + + }, { + key: 'blendMode', + get: function get() { + return this.blurYFilter._blendMode; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter._blendMode = value; + } + }]); + + return BlurFilter; +}(core.Filter); + +exports.default = BlurFilter; + +},{"../../core":65,"./BlurXFilter":145,"./BlurYFilter":146}],145:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurXFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurXFilter = function (_core$Filter) { + _inherits(BlurXFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurXFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurXFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurXFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.width * (output.size.width / input.size.width); + + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; // / this.passes//Math.pow(1, this.passes); + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 16 + */ + + + _createClass(BlurXFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurXFilter; +}(core.Filter); + +exports.default = BlurXFilter; + +},{"../../core":65,"./generateBlurFragSource":147,"./generateBlurVertSource":148,"./getMaxBlurKernelSize":149}],146:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurYFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurYFilter = function (_core$Filter) { + _inherits(BlurYFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurYFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurYFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurYFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.height * (output.size.height / input.size.height); + + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurYFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurYFilter; +}(core.Filter); + +exports.default = BlurYFilter; + +},{"../../core":65,"./generateBlurFragSource":147,"./generateBlurVertSource":148,"./getMaxBlurKernelSize":149}],147:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateFragBlurSource; +var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] +}; + +var fragTemplate = ['varying vec2 vBlurTexCoords[%size%];', 'uniform sampler2D uSampler;', 'void main(void)', '{', ' gl_FragColor = vec4(0.0);', ' %blur%', '}'].join('\n'); + +function generateFragBlurSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + + var fragSource = fragTemplate; + + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value = void 0; + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + value = i; + + if (i >= halfLength) { + value = kernelSize - i - 1; + } + + blur = blur.replace('%value%', kernel[value]); + + blurLoop += blur; + blurLoop += '\n'; + } + + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize); + + return fragSource; +} + +},{}],148:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateVertBlurSource; +var vertTemplate = ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform float strength;', 'uniform mat3 projectionMatrix;', 'varying vec2 vBlurTexCoords[%size%];', 'void main(void)', '{', 'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);', '%blur%', '}'].join('\n'); + +function generateVertBlurSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + + var vertSource = vertTemplate; + + var blurLoop = ''; + var template = void 0; + // let value; + + if (x) { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } else { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + // value = i; + + // if(i >= halfLength) + // { + // value = kernelSize - i - 1; + // } + + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + '.0'); + + blurLoop += blur; + blurLoop += '\n'; + } + + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize); + + return vertSource; +} + +},{}],149:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = getMaxKernelSize; +function getMaxKernelSize(gl) { + var maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + var kernelSize = 15; + + while (kernelSize > maxVaryings) { + kernelSize -= 2; + } + + return kernelSize; +} + +},{}],150:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.filters.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var ColorMatrixFilter = function (_core$Filter) { + _inherits(ColorMatrixFilter, _core$Filter); + + /** + * + */ + function ColorMatrixFilter() { + _classCallCheck(this, ColorMatrixFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n')); + + _this.uniforms.m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + _this.alpha = 1; + return _this; + } + + /** + * Transforms current matrix and set the new one + * + * @param {number[]} matrix - 5x4 matrix + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix(matrix) { + var multiply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + var newMatrix = matrix; + + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + + // set the new matrix + this.uniforms.m = newMatrix; + }; + + /** + * Multiplies two mat5's + * + * @private + * @param {number[]} out - 5x4 matrix the receiving matrix + * @param {number[]} a - 5x4 matrix the first operand + * @param {number[]} b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix + */ + + + ColorMatrixFilter.prototype._multiply = function _multiply(out, a, b) { + // Red Channel + out[0] = a[0] * b[0] + a[1] * b[5] + a[2] * b[10] + a[3] * b[15]; + out[1] = a[0] * b[1] + a[1] * b[6] + a[2] * b[11] + a[3] * b[16]; + out[2] = a[0] * b[2] + a[1] * b[7] + a[2] * b[12] + a[3] * b[17]; + out[3] = a[0] * b[3] + a[1] * b[8] + a[2] * b[13] + a[3] * b[18]; + out[4] = a[0] * b[4] + a[1] * b[9] + a[2] * b[14] + a[3] * b[19] + a[4]; + + // Green Channel + out[5] = a[5] * b[0] + a[6] * b[5] + a[7] * b[10] + a[8] * b[15]; + out[6] = a[5] * b[1] + a[6] * b[6] + a[7] * b[11] + a[8] * b[16]; + out[7] = a[5] * b[2] + a[6] * b[7] + a[7] * b[12] + a[8] * b[17]; + out[8] = a[5] * b[3] + a[6] * b[8] + a[7] * b[13] + a[8] * b[18]; + out[9] = a[5] * b[4] + a[6] * b[9] + a[7] * b[14] + a[8] * b[19] + a[9]; + + // Blue Channel + out[10] = a[10] * b[0] + a[11] * b[5] + a[12] * b[10] + a[13] * b[15]; + out[11] = a[10] * b[1] + a[11] * b[6] + a[12] * b[11] + a[13] * b[16]; + out[12] = a[10] * b[2] + a[11] * b[7] + a[12] * b[12] + a[13] * b[17]; + out[13] = a[10] * b[3] + a[11] * b[8] + a[12] * b[13] + a[13] * b[18]; + out[14] = a[10] * b[4] + a[11] * b[9] + a[12] * b[14] + a[13] * b[19] + a[14]; + + // Alpha Channel + out[15] = a[15] * b[0] + a[16] * b[5] + a[17] * b[10] + a[18] * b[15]; + out[16] = a[15] * b[1] + a[16] * b[6] + a[17] * b[11] + a[18] * b[16]; + out[17] = a[15] * b[2] + a[16] * b[7] + a[17] * b[12] + a[18] * b[17]; + out[18] = a[15] * b[3] + a[16] * b[8] + a[17] * b[13] + a[18] * b[18]; + out[19] = a[15] * b[4] + a[16] * b[9] + a[17] * b[14] + a[18] * b[19] + a[19]; + + return out; + }; + + /** + * Create a Float32 Array and normalize the offset component to 0-1 + * + * @private + * @param {number[]} matrix - 5x4 matrix + * @return {number[]} 5x4 matrix with all values between 0-1 + */ + + + ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix(matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + + return m; + }; + + /** + * Adjusts brightness + * + * @param {number} b - value of the brigthness (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.brightness = function brightness(b, multiply) { + var matrix = [b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the matrices in grey scales + * + * @param {number} scale - value of the grey (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.greyscale = function greyscale(scale, multiply) { + var matrix = [scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the black and white matrice. + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite(multiply) { + var matrix = [0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the hue property of the color + * + * @param {number} rotation - in degrees + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.hue = function hue(rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + + var a00 = cosR + (1.0 - cosR) * w; + var a01 = w * (1.0 - cosR) - sqrW * sinR; + var a02 = w * (1.0 - cosR) + sqrW * sinR; + + var a10 = w * (1.0 - cosR) + sqrW * sinR; + var a11 = cosR + w * (1.0 - cosR); + var a12 = w * (1.0 - cosR) - sqrW * sinR; + + var a20 = w * (1.0 - cosR) - sqrW * sinR; + var a21 = w * (1.0 - cosR) + sqrW * sinR; + var a22 = cosR + w * (1.0 - cosR); + + var matrix = [a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * + * @param {number} amount - value of the contrast (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.contrast = function contrast(amount, multiply) { + var v = (amount || 0) + 1; + var o = -0.5 * (v - 1); + + var matrix = [v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * + * @param {number} amount - The saturation amount (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.saturate = function saturate() { + var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var multiply = arguments[1]; + + var x = amount * 2 / 3 + 1; + var y = (x - 1) * -0.5; + + var matrix = [x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Desaturate image (remove color) + * + * Call the saturate function + * + */ + + + ColorMatrixFilter.prototype.desaturate = function desaturate() // eslint-disable-line no-unused-vars + { + this.saturate(-1); + }; + + /** + * Negative image (inverse of classic rgb matrix) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.negative = function negative(multiply) { + var matrix = [-1, 0, 0, 1, 0, 0, -1, 0, 1, 0, 0, 0, -1, 1, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Sepia image + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.sepia = function sepia(multiply) { + var matrix = [0.393, 0.7689999, 0.18899999, 0, 0, 0.349, 0.6859999, 0.16799999, 0, 0, 0.272, 0.5339999, 0.13099999, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.technicolor = function technicolor(multiply) { + var matrix = [1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Polaroid filter + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.polaroid = function polaroid(multiply) { + var matrix = [1.438, -0.062, -0.062, 0, 0, -0.122, 1.378, -0.122, 0, 0, -0.016, -0.016, 1.483, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Filter who transforms : Red -> Blue and Blue -> Red + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.toBGR = function toBGR(multiply) { + var matrix = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.kodachrome = function kodachrome(multiply) { + var matrix = [1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Brown delicious browni filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.browni = function browni(multiply) { + var matrix = [0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Vintage filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.vintage = function vintage(multiply) { + var matrix = [0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * + * @param {number} desaturation - Tone values. + * @param {number} toned - Tone values. + * @param {string} lightColor - Tone values, example: `0xFFE580` + * @param {string} darkColor - Tone values, example: `0xFFE580` + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.colorTone = function colorTone(desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + + var lR = (lightColor >> 16 & 0xFF) / 255; + var lG = (lightColor >> 8 & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + + var dR = (darkColor >> 16 & 0xFF) / 255; + var dG = (darkColor >> 8 & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + + var matrix = [0.3, 0.59, 0.11, 0, 0, lR, lG, lB, desaturation, 0, dR, dG, dB, toned, 0, lR - dR, lG - dG, lB - dB, 0, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Night effect + * + * @param {number} intensity - The intensity of the night effect. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.night = function night(intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [intensity * -2.0, -intensity, 0, 0, 0, -intensity, 0, intensity, 0, 0, 0, intensity, intensity * 2.0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * + * @param {number} amount - how much the predator feels his future victim + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.predator = function predator(amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * LSD effect + * + * Multiply the current matrix + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.lsd = function lsd(multiply) { + var matrix = [2, -0.4, 0.5, 0, 0, -0.5, 2, -0.4, 0, 0, -0.4, -0.5, 3, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Erase the current matrix by setting the default one + * + */ + + + ColorMatrixFilter.prototype.reset = function reset() { + var matrix = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, false); + }; + + /** + * The matrix of the color matrix filter + * + * @member {number[]} + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + + + _createClass(ColorMatrixFilter, [{ + key: 'matrix', + get: function get() { + return this.uniforms.m; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.m = value; + } + + /** + * The opacity value to use when mixing the original and resultant colors. + * + * When the value is 0, the original color is used without modification. + * When the value is 1, the result color is used. + * When in the range (0, 1) the color is interpolated between the original and result by this amount. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'alpha', + get: function get() { + return this.uniforms.uAlpha; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uAlpha = value; + } + }]); + + return ColorMatrixFilter; +}(core.Filter); + +// Americanized alias + + +exports.default = ColorMatrixFilter; +ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + +},{"../../core":65,"path":8}],151:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. You can + * use this filter to apply all manor of crazy warping effects. Currently the r + * property of the texture is used to offset the x and the g property of the texture + * is used to offset the y. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var DisplacementFilter = function (_core$Filter) { + _inherits(DisplacementFilter, _core$Filter); + + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param {number} scale - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + _classCallCheck(this, DisplacementFilter); + + var maskMatrix = new core.Matrix(); + + sprite.renderable = false; + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale / filterArea.xy;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n')); + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + + _this.uniforms.mapSampler = sprite._texture; + _this.uniforms.filterMatrix = maskMatrix; + _this.uniforms.scale = { x: 1, y: 1 }; + + if (scale === null || scale === undefined) { + scale = 20; + } + + _this.scale = new core.Point(scale, scale); + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + DisplacementFilter.prototype.apply = function apply(filterManager, input, output) { + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x; + this.uniforms.scale.y = this.scale.y; + + // draw the filter... + filterManager.applyFilter(this, input, output); + }; + + /** + * The texture used for the displacement map. Must be power of 2 sized texture. + * + * @member {PIXI.Texture} + */ + + + _createClass(DisplacementFilter, [{ + key: 'map', + get: function get() { + return this.uniforms.mapSampler; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.mapSampler = value; + } + }]); + + return DisplacementFilter; +}(core.Filter); + +exports.default = DisplacementFilter; + +},{"../../core":65,"path":8}],152:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * Basic FXAA implementation based on the code on geeks3d.com with the + * modification that the texture2DLod stuff was removed since it's + * unsupported by WebGL. + * + * @see https://github.com/mitsuhiko/webgl-meincraft + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + * + */ +var FXAAFilter = function (_core$Filter) { + _inherits(FXAAFilter, _core$Filter); + + /** + * + */ + function FXAAFilter() { + _classCallCheck(this, FXAAFilter); + + // TODO - needs work + return _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + '\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}', + // fragment shader + 'varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n')); + } + + return FXAAFilter; +}(core.Filter); + +exports.default = FXAAFilter; + +},{"../../core":65,"path":8}],153:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _FXAAFilter = require('./fxaa/FXAAFilter'); + +Object.defineProperty(exports, 'FXAAFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_FXAAFilter).default; + } +}); + +var _NoiseFilter = require('./noise/NoiseFilter'); + +Object.defineProperty(exports, 'NoiseFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NoiseFilter).default; + } +}); + +var _DisplacementFilter = require('./displacement/DisplacementFilter'); + +Object.defineProperty(exports, 'DisplacementFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplacementFilter).default; + } +}); + +var _BlurFilter = require('./blur/BlurFilter'); + +Object.defineProperty(exports, 'BlurFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurFilter).default; + } +}); + +var _BlurXFilter = require('./blur/BlurXFilter'); + +Object.defineProperty(exports, 'BlurXFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurXFilter).default; + } +}); + +var _BlurYFilter = require('./blur/BlurYFilter'); + +Object.defineProperty(exports, 'BlurYFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurYFilter).default; + } +}); + +var _ColorMatrixFilter = require('./colormatrix/ColorMatrixFilter'); + +Object.defineProperty(exports, 'ColorMatrixFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ColorMatrixFilter).default; + } +}); + +var _AlphaFilter = require('./alpha/AlphaFilter'); + +Object.defineProperty(exports, 'AlphaFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AlphaFilter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./alpha/AlphaFilter":143,"./blur/BlurFilter":144,"./blur/BlurXFilter":145,"./blur/BlurYFilter":146,"./colormatrix/ColorMatrixFilter":150,"./displacement/DisplacementFilter":151,"./fxaa/FXAAFilter":152,"./noise/NoiseFilter":154}],154:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Vico @vicocotea + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + */ + +/** + * A Noise effect filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var NoiseFilter = function (_core$Filter) { + _inherits(NoiseFilter, _core$Filter); + + /** + * @param {number} noise - The noise intensity, should be a normalized value in the range [0, 1]. + * @param {number} seed - A random seed for the noise generation. Default is `Math.random()`. + */ + function NoiseFilter() { + var noise = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0.5; + var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Math.random(); + + _classCallCheck(this, NoiseFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n')); + + _this.noise = noise; + _this.seed = seed; + return _this; + } + + /** + * The amount of noise to apply, this value should be in the range (0, 1]. + * + * @member {number} + * @default 0.5 + */ + + + _createClass(NoiseFilter, [{ + key: 'noise', + get: function get() { + return this.uniforms.uNoise; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uNoise = value; + } + + /** + * A seed value to apply to the random noise generation. `Math.random()` is a good value to use. + * + * @member {number} + */ + + }, { + key: 'seed', + get: function get() { + return this.uniforms.uSeed; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uSeed = value; + } + }]); + + return NoiseFilter; +}(core.Filter); + +exports.default = NoiseFilter; + +},{"../../core":65,"path":8}],155:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Holds all information related to an Interaction event + * + * @class + * @memberof PIXI.interaction + */ +var InteractionData = function () { + /** + * + */ + function InteractionData() { + _classCallCheck(this, InteractionData); + + /** + * This point stores the global coords of where the touch/mouse event happened + * + * @member {PIXI.Point} + */ + this.global = new core.Point(); + + /** + * The target DisplayObject that was interacted with + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * When passed to an event handler, this will be the original DOM Event that was captured + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent + * @see https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent + * @member {MouseEvent|TouchEvent|PointerEvent} + */ + this.originalEvent = null; + + /** + * Unique identifier for this interaction + * + * @member {number} + */ + this.identifier = null; + + /** + * Indicates whether or not the pointer device that created the event is the primary pointer. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary + * @type {Boolean} + */ + this.isPrimary = false; + + /** + * Indicates which button was pressed on the mouse or pointer device to trigger the event. + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button + * @type {number} + */ + this.button = 0; + + /** + * Indicates which buttons are pressed on the mouse or pointer device when the event is triggered. + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons + * @type {number} + */ + this.buttons = 0; + + /** + * The width of the pointer's contact along the x-axis, measured in CSS pixels. + * radiusX of TouchEvents will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width + * @type {number} + */ + this.width = 0; + + /** + * The height of the pointer's contact along the y-axis, measured in CSS pixels. + * radiusY of TouchEvents will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height + * @type {number} + */ + this.height = 0; + + /** + * The angle, in degrees, between the pointer device and the screen. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX + * @type {number} + */ + this.tiltX = 0; + + /** + * The angle, in degrees, between the pointer device and the screen. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY + * @type {number} + */ + this.tiltY = 0; + + /** + * The type of pointer that triggered the event. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType + * @type {string} + */ + this.pointerType = null; + + /** + * Pressure applied by the pointing device during the event. A Touch's force property + * will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure + * @type {number} + */ + this.pressure = 0; + + /** + * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch. + * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle + * @type {number} + */ + this.rotationAngle = 0; + + /** + * Twist of a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + * @type {number} + */ + this.twist = 0; + + /** + * Barrel pressure on a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + * @type {number} + */ + this.tangentialPressure = 0; + } + + /** + * The unique identifier of the pointer. It will be the same as `identifier`. + * @readonly + * @member {number} + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId + */ + + + /** + * This will return the local coordinates of the specified displayObject for this InteractionData + * + * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local + * coords off + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative + * to the DisplayObject + */ + InteractionData.prototype.getLocalPosition = function getLocalPosition(displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + + /** + * Copies properties from normalized event data. + * + * @param {Touch|MouseEvent|PointerEvent} event The normalized event data + */ + + + InteractionData.prototype.copyEvent = function copyEvent(event) { + // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite + // it with "false" on later events when our shim for it on touch events might not be + // accurate + if (event.isPrimary) { + this.isPrimary = true; + } + this.button = event.button; + // event.buttons is not available in all browsers (ie. Safari), but it does have a non-standard + // event.which property instead, which conveys the same information. + this.buttons = Number.isInteger(event.buttons) ? event.buttons : event.which; + this.width = event.width; + this.height = event.height; + this.tiltX = event.tiltX; + this.tiltY = event.tiltY; + this.pointerType = event.pointerType; + this.pressure = event.pressure; + this.rotationAngle = event.rotationAngle; + this.twist = event.twist || 0; + this.tangentialPressure = event.tangentialPressure || 0; + }; + + /** + * Resets the data for pooling. + */ + + + InteractionData.prototype.reset = function reset() { + // isPrimary is the only property that we really need to reset - everything else is + // guaranteed to be overwritten + this.isPrimary = false; + }; + + _createClass(InteractionData, [{ + key: 'pointerId', + get: function get() { + return this.identifier; + } + }]); + + return InteractionData; +}(); + +exports.default = InteractionData; + +},{"../core":65}],156:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Event class that mimics native DOM events. + * + * @class + * @memberof PIXI.interaction + */ +var InteractionEvent = function () { + /** + * + */ + function InteractionEvent() { + _classCallCheck(this, InteractionEvent); + + /** + * Whether this event will continue propagating in the tree + * + * @member {boolean} + */ + this.stopped = false; + + /** + * The object which caused this event to be dispatched. + * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}. + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * The object whose event listener’s callback is currently being invoked. + * + * @member {PIXI.DisplayObject} + */ + this.currentTarget = null; + + /** + * Type of the event + * + * @member {string} + */ + this.type = null; + + /** + * InteractionData related to this event + * + * @member {PIXI.interaction.InteractionData} + */ + this.data = null; + } + + /** + * Prevents event from reaching any objects other than the current object. + * + */ + + + InteractionEvent.prototype.stopPropagation = function stopPropagation() { + this.stopped = true; + }; + + /** + * Resets the event. + */ + + + InteractionEvent.prototype.reset = function reset() { + this.stopped = false; + this.currentTarget = null; + this.target = null; + }; + + return InteractionEvent; +}(); + +exports.default = InteractionEvent; + +},{}],157:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _InteractionData = require('./InteractionData'); + +var _InteractionData2 = _interopRequireDefault(_InteractionData); + +var _InteractionEvent = require('./InteractionEvent'); + +var _InteractionEvent2 = _interopRequireDefault(_InteractionEvent); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +var _InteractionTrackingData2 = _interopRequireDefault(_InteractionTrackingData); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _interactiveTarget = require('./interactiveTarget'); + +var _interactiveTarget2 = _interopRequireDefault(_interactiveTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// Mix interactiveTarget into core.DisplayObject.prototype, after deprecation has been handled +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _interactiveTarget2.default); + +var MOUSE_POINTER_ID = 1; + +// helpers for hitTest() - only used inside hitTest() +var hitTestEvent = { + target: null, + data: { + global: null + } +}; + +/** + * The interaction manager deals with mouse, touch and pointer events. Any DisplayObject can be interactive + * if its interactive parameter is set to true + * This manager also supports multitouch. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.interaction + * + * @class + * @extends EventEmitter + * @memberof PIXI.interaction + */ + +var InteractionManager = function (_EventEmitter) { + _inherits(InteractionManager, _EventEmitter); + + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + * @param {object} [options] - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Frequency increases the interaction events will be checked. + */ + function InteractionManager(renderer, options) { + _classCallCheck(this, InteractionManager); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + options = options || {}; + + /** + * The renderer this interaction manager works for. + * + * @member {PIXI.SystemRenderer} + */ + _this.renderer = renderer; + + /** + * Should default browser actions automatically be prevented. + * Does not apply to pointer events for backwards compatibility + * preventDefault on pointer events stops mouse events from firing + * Thus, for every pointer event, there will always be either a mouse of touch event alongside it. + * + * @member {boolean} + * @default true + */ + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + + /** + * Frequency in milliseconds that the mousemove, moveover & mouseout interaction events will be checked. + * + * @member {number} + * @default 10 + */ + _this.interactionFrequency = options.interactionFrequency || 10; + + /** + * The mouse data + * + * @member {PIXI.interaction.InteractionData} + */ + _this.mouse = new _InteractionData2.default(); + _this.mouse.identifier = MOUSE_POINTER_ID; + + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + + /** + * Actively tracked InteractionData + * + * @private + * @member {Object.} + */ + _this.activeInteractionData = {}; + _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; + + /** + * Pool of unused InteractionData + * + * @private + * @member {PIXI.interation.InteractionData[]} + */ + _this.interactionDataPool = []; + + /** + * An event data object to handle all the event tracking/dispatching + * + * @member {object} + */ + _this.eventData = new _InteractionEvent2.default(); + + /** + * The DOM element to bind to. + * + * @private + * @member {HTMLElement} + */ + _this.interactionDOMElement = null; + + /** + * This property determines if mousemove and touchmove events are fired only when the cursor + * is over the object. + * Setting to true will make things work more in line with how the DOM verison works. + * Setting to false can make things easier for things like dragging + * It is currently set to false as this is how PixiJS used to work. This will be set to true in + * future versions of pixi. + * + * @member {boolean} + * @default false + */ + _this.moveWhenInside = false; + + /** + * Have events been attached to the dom element? + * + * @private + * @member {boolean} + */ + _this.eventsAdded = false; + + /** + * Is the mouse hovering over the renderer? + * + * @private + * @member {boolean} + */ + _this.mouseOverRenderer = false; + + /** + * Does the device support touch events + * https://www.w3.org/TR/touch-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsTouchEvents = 'ontouchstart' in window; + + /** + * Does the device support pointer events + * https://www.w3.org/Submission/pointer-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsPointerEvents = !!window.PointerEvent; + + // this will make it so that you don't have to call bind all the time + + /** + * @private + * @member {Function} + */ + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerCancel = _this.onPointerCancel.bind(_this); + _this.processPointerCancel = _this.processPointerCancel.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOver = _this.onPointerOver.bind(_this); + + /** + * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor + * values, objects are handled as dictionaries of CSS values for interactionDOMElement, + * and functions are called instead of changing the CSS. + * Default CSS cursor values are provided for 'default' and 'pointer' modes. + * @member {Object.)>} + */ + _this.cursorStyles = { + default: 'inherit', + pointer: 'pointer' + }; + + /** + * The mode of the cursor that is being used. + * The value of this is a key from the cursorStyles dictionary. + * + * @member {string} + */ + _this.currentCursorMode = null; + + /** + * Internal cached let. + * + * @private + * @member {string} + */ + _this.cursor = null; + + /** + * Internal cached let. + * + * @private + * @member {PIXI.Point} + */ + _this._tempPoint = new core.Point(); + + /** + * The current resolution / device pixel ratio. + * + * @member {number} + * @default 1 + */ + _this.resolution = 1; + + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display + * object. + * + * @event PIXI.interaction.InteractionManager#mousedown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * + * @event PIXI.interaction.InteractionManager#rightdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. + * + * @event PIXI.interaction.InteractionManager#mouseup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * + * @event PIXI.interaction.InteractionManager#rightup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. + * + * @event PIXI.interaction.InteractionManager#click + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * + * @event PIXI.interaction.InteractionManager#rightclick + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. + * + * @event PIXI.interaction.InteractionManager#mouseupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. + * + * @event PIXI.interaction.InteractionManager#rightupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * + * @event PIXI.interaction.InteractionManager#mousemove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * + * @event PIXI.interaction.InteractionManager#mouseover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * + * @event PIXI.interaction.InteractionManager#mouseout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * + * @event PIXI.interaction.InteractionManager#pointerdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released over the display object. + * Not always fired when some buttons are held down while others are released. In those cases, + * use [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown} and + * [mouseup]{@link PIXI.interaction.InteractionManager#event:mouseup} instead. + * + * @event PIXI.interaction.InteractionManager#pointerup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a pointer event + * + * @event PIXI.interaction.InteractionManager#pointercancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * + * @event PIXI.interaction.InteractionManager#pointertap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}. + * + * @event PIXI.interaction.InteractionManager#pointerupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved while over the display object + * + * @event PIXI.interaction.InteractionManager#pointermove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved onto the display object + * + * @event PIXI.interaction.InteractionManager#pointerover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved off the display object + * + * @event PIXI.interaction.InteractionManager#pointerout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed on the display object. + * + * @event PIXI.interaction.InteractionManager#touchstart + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed from the display object. + * + * @event PIXI.interaction.InteractionManager#touchend + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a touch + * + * @event PIXI.interaction.InteractionManager#touchcancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * + * @event PIXI.interaction.InteractionManager#tap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. + * + * @event PIXI.interaction.InteractionManager#touchendoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is moved along the display object. + * + * @event PIXI.interaction.InteractionManager#touchmove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display. + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mousedown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#click + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightclick + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.DisplayObject#event:mousedown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.DisplayObject#event:rightdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mousemove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a pointer event. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointercancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointertap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointermove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchstart + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchend + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a touch. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchcancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#tap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchendoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is moved along the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchmove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + return _this; + } + + /** + * Hit tests a point against the display tree, returning the first interactive object that is hit. + * + * @param {PIXI.Point} globalPoint - A point to hit test with, in global space. + * @param {PIXI.Container} [root] - The root display object to start from. If omitted, defaults + * to the last rendered root of the associated renderer. + * @return {PIXI.DisplayObject} The hit display object, if any. + */ + + + InteractionManager.prototype.hitTest = function hitTest(globalPoint, root) { + // clear the target for our hit test + hitTestEvent.target = null; + // assign the global point + hitTestEvent.data.global = globalPoint; + // ensure safety of the root + if (!root) { + root = this.renderer._lastObjectRendered; + } + // run the hit test + this.processInteractive(hitTestEvent, root, null, true); + // return our found object - it'll be null if we didn't hit anything + + return hitTestEvent.target; + }; + + /** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate + * another DOM element to receive those events. + * + * @param {HTMLCanvasElement} element - the DOM element which will receive mouse and touch events. + * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). + */ + + + InteractionManager.prototype.setTargetElement = function setTargetElement(element) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.removeEvents(); + + this.interactionDOMElement = element; + + this.resolution = resolution; + + this.addEvents(); + }; + + /** + * Registers all the DOM events + * + * @private + */ + + + InteractionManager.prototype.addEvents = function addEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.INTERACTION); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; + this.interactionDOMElement.style['-ms-touch-action'] = 'none'; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = 'none'; + } + + /** + * These events are added first, so that if pointer events are normalised, they are fired + * in the same order as non-normalised events. ie. pointer event 1st, mouse / touch 2nd + */ + if (this.supportsPointerEvents) { + window.document.addEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); + // pointerout is fired in addition to pointerup (for touch events) and pointercancel + // we already handle those, so for the purposes of what we do in onPointerOut, we only + // care about the pointerleave event + this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); + window.addEventListener('pointercancel', this.onPointerCancel, true); + window.addEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.addEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); + window.addEventListener('mouseup', this.onPointerUp, true); + } + + // always look directly for touch events so that we can provide original data + // In a future version we should change this to being just a fallback and rely solely on + // PointerEvents whenever available + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); + } + + this.eventsAdded = true; + }; + + /** + * Removes all the DOM events that were previously registered + * + * @private + */ + + + InteractionManager.prototype.removeEvents = function removeEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.remove(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = ''; + this.interactionDOMElement.style['-ms-touch-action'] = ''; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = ''; + } + + if (this.supportsPointerEvents) { + window.document.removeEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); + window.removeEventListener('pointercancel', this.onPointerCancel, true); + window.removeEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.removeEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true); + window.removeEventListener('mouseup', this.onPointerUp, true); + } + + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); + } + + this.interactionDOMElement = null; + + this.eventsAdded = false; + }; + + /** + * Updates the state of interactive objects. + * Invoked by a throttled ticker update from {@link PIXI.ticker.shared}. + * + * @param {number} deltaTime - time delta since last tick + */ + + + InteractionManager.prototype.update = function update(deltaTime) { + this._deltaTime += deltaTime; + + if (this._deltaTime < this.interactionFrequency) { + return; + } + + this._deltaTime = 0; + + if (!this.interactionDOMElement) { + return; + } + + // if the user move the mouse this check has already been done using the mouse move! + if (this.didMove) { + this.didMove = false; + + return; + } + + this.cursor = null; + + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + for (var k in this.activeInteractionData) { + // eslint-disable-next-line no-prototype-builtins + if (this.activeInteractionData.hasOwnProperty(k)) { + var interactionData = this.activeInteractionData[k]; + + if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, true); + } + } + } + + this.setCursorMode(this.cursor); + + // TODO + }; + + /** + * Sets the current cursor mode, handling any callbacks or CSS style changes. + * + * @param {string} mode - cursor mode, a key from the cursorStyles dictionary + */ + + + InteractionManager.prototype.setCursorMode = function setCursorMode(mode) { + mode = mode || 'default'; + // if the mode didn't actually change, bail early + if (this.currentCursorMode === mode) { + return; + } + this.currentCursorMode = mode; + var style = this.cursorStyles[mode]; + + // only do things if there is a cursor style for it + if (style) { + switch (typeof style === 'undefined' ? 'undefined' : _typeof(style)) { + case 'string': + // string styles are handled as cursor CSS + this.interactionDOMElement.style.cursor = style; + break; + case 'function': + // functions are just called, and passed the cursor mode + style(mode); + break; + case 'object': + // if it is an object, assume that it is a dictionary of CSS styles, + // apply it to the interactionDOMElement + Object.assign(this.interactionDOMElement.style, style); + break; + } + } else if (typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) { + // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry + // for the mode, then assume that the dev wants it to be CSS for the cursor. + this.interactionDOMElement.style.cursor = mode; + } + }; + + /** + * Dispatches an event on the display object that was interacted with + * + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the display object in question + * @param {string} eventString - the name of the event (e.g, mousedown) + * @param {object} eventData - the event data object + * @private + */ + + + InteractionManager.prototype.dispatchEvent = function dispatchEvent(displayObject, eventString, eventData) { + if (!eventData.stopped) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + + displayObject.emit(eventString, eventData); + + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } + }; + + /** + * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. + * + * @param {PIXI.Point} point - the point that the result will be stored in + * @param {number} x - the x coord of the position to map + * @param {number} y - the y coord of the position to map + */ + + + InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint(point, x, y) { + var rect = void 0; + + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { x: 0, y: 0, width: 0, height: 0 }; + } else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + + var resolutionMultiplier = navigator.isCocoonJS ? this.resolution : 1.0 / this.resolution; + + point.x = (x - rect.left) * (this.interactionDOMElement.width / rect.width) * resolutionMultiplier; + point.y = (y - rect.top) * (this.interactionDOMElement.height / rect.height) * resolutionMultiplier; + }; + + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that + * is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param {Function} [func] - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point + * @param {boolean} [interactive] - Whether the displayObject is interactive + * @return {boolean} returns true if the displayObject hit the point + */ + + + InteractionManager.prototype.processInteractive = function processInteractive(interactionEvent, displayObject, func, hitTest, interactive) { + if (!displayObject || !displayObject.visible) { + return false; + } + + var point = interactionEvent.data.global; + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + interactive = displayObject.interactive || interactive; + + var hit = false; + var interactiveParent = interactive; + + // Flag here can set to false if the event is outside the parents hitArea or mask + var hitTestChildren = true; + + // If there is a hitArea, no need to test against anything else if the pointer is not within the hitArea + // There is also no longer a need to hitTest children. + if (displayObject.hitArea) { + if (hitTest) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (!displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hitTest = false; + hitTestChildren = false; + } else { + hit = true; + } + } + interactiveParent = false; + } + // If there is a mask, no need to test against anything else if the pointer is not within the mask + else if (displayObject._mask) { + if (hitTest) { + if (!displayObject._mask.containsPoint(point)) { + hitTest = false; + hitTestChildren = false; + } + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow PixiJS to completely ignore and bypass checking the displayObjects children. + if (hitTestChildren && displayObject.interactiveChildren && displayObject.children) { + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + + // time to get recursive.. if this function will return if something is hit.. + var childHit = this.processInteractive(interactionEvent, child, func, hitTest, interactiveParent); + + if (childHit) { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if (!child.parent) { + continue; + } + + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + + if (childHit) { + if (interactionEvent.target) { + hitTest = false; + } + hit = true; + } + } + } + } + + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit - but only if it was interactive, otherwise we need to keep + // looking for an interactive child, just in case we hit one + if (hitTest && !interactionEvent.target) { + // already tested against hitArea if it is defined + if (!displayObject.hitArea && displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = true; + } + } + } + + if (displayObject.interactive) { + if (hit && !interactionEvent.target) { + interactionEvent.target = displayObject; + } + + if (func) { + func(interactionEvent, displayObject, !!hit); + } + } + } + + return hit; + }; + + /** + * Is called when the pointer button is pressed down on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down + */ + + + InteractionManager.prototype.onPointerDown = function onPointerDown(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + /** + * No need to prevent default on natural pointer events, as there are no side effects + * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, + * so still need to be prevented. + */ + + // Guaranteed that there will be at least one event in events, and all events must have the same pointer type + + if (this.autoPreventDefault && events[0].isNormalized) { + originalEvent.preventDefault(); + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerDown, true); + + this.emit('pointerdown', interactionEvent); + if (event.pointerType === 'touch') { + this.emit('touchstart', interactionEvent); + } + // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event + else if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + } + }; + + /** + * Processes the result of the pointer down check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerDown = function processPointerDown(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + + if (hit) { + if (!displayObject.trackedPointers[id]) { + displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchstart', interactionEvent); + } else if (data.pointerType === 'mouse' || data.pointerType === 'pen') { + var isRightButton = data.button === 2; + + if (isRightButton) { + displayObject.trackedPointers[id].rightDown = true; + } else { + displayObject.trackedPointers[id].leftDown = true; + } + + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released + * @param {boolean} cancelled - true if the pointer is cancelled + * @param {Function} func - Function passed to {@link processInteractive} + */ + + + InteractionManager.prototype.onPointerComplete = function onPointerComplete(originalEvent, cancelled, func) { + var events = this.normalizeToPointerData(originalEvent); + + var eventLen = events.length; + + // if the event wasn't targeting our canvas, then consider it to be pointerupoutside + // in all cases (unless it was a pointercancel) + var eventAppend = originalEvent.target !== this.interactionDOMElement ? 'outside' : ''; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + // perform hit testing for events targeting our canvas or cancel events + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, func, cancelled || !eventAppend); + + this.emit(cancelled ? 'pointercancel' : 'pointerup' + eventAppend, interactionEvent); + + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + + this.emit(isRightButton ? 'rightup' + eventAppend : 'mouseup' + eventAppend, interactionEvent); + } else if (event.pointerType === 'touch') { + this.emit(cancelled ? 'touchcancel' : 'touchend' + eventAppend, interactionEvent); + this.releaseInteractionDataForPointerId(event.pointerId, interactionData); + } + } + }; + + /** + * Is called when the pointer button is cancelled + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerCancel = function onPointerCancel(event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') return; + + this.onPointerComplete(event, true, this.processPointerCancel); + }; + + /** + * Processes the result of the pointer cancel check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + */ + + + InteractionManager.prototype.processPointerCancel = function processPointerCancel(interactionEvent, displayObject) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + if (displayObject.trackedPointers[id] !== undefined) { + delete displayObject.trackedPointers[id]; + this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); + + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerUp = function onPointerUp(event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') return; + + this.onPointerComplete(event, false, this.processPointerUp); + }; + + /** + * Processes the result of the pointer up check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerUp = function processPointerUp(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + var trackingData = displayObject.trackedPointers[id]; + + var isTouch = data.pointerType === 'touch'; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + // need to track mouse down status in the mouse block so that we can emit + // event in a later block + var isMouseTap = false; + + // Mouse only + if (isMouse) { + var isRightButton = data.button === 2; + + var flags = _InteractionTrackingData2.default.FLAGS; + + var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; + + var isDown = trackingData !== undefined && trackingData.flags & test; + + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); + + if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); + // because we can confirm that the mousedown happened on this object, flag for later emit of pointertap + isMouseTap = true; + } + } else if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); + } + // update the down state of the tracking data + if (trackingData) { + if (isRightButton) { + trackingData.rightDown = false; + } else { + trackingData.leftDown = false; + } + } + } + + // Pointers and Touches, and Mouse + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchend', interactionEvent); + + if (trackingData) { + // emit pointertap if not a mouse, or if the mouse block decided it was a tap + if (!isMouse || isMouseTap) { + this.dispatchEvent(displayObject, 'pointertap', interactionEvent); + } + if (isTouch) { + this.dispatchEvent(displayObject, 'tap', interactionEvent); + // touches are no longer over (if they ever were) when we get the touchend + // so we should ensure that we don't keep pretending that they are + trackingData.over = false; + } + } + } else if (trackingData) { + this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); + } + // Only remove the tracking data if there is no over/down state still associated with it + if (trackingData && trackingData.none) { + delete displayObject.trackedPointers[id]; + } + }; + + /** + * Is called when the pointer moves across the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer moving + */ + + + InteractionManager.prototype.onPointerMove = function onPointerMove(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + if (events[0].pointerType === 'mouse' || events[0].pointerType === 'pen') { + this.didMove = true; + + this.cursor = null; + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + var interactive = event.pointerType === 'touch' ? this.moveWhenInside : true; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerMove, interactive); + this.emit('pointermove', interactionEvent); + if (event.pointerType === 'touch') this.emit('touchmove', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') this.emit('mousemove', interactionEvent); + } + + if (events[0].pointerType === 'mouse') { + this.setCursorMode(this.cursor); + + // TODO BUG for parents interactive object (border order issue) + } + }; + + /** + * Processes the result of the pointer move check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerMove = function processPointerMove(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var isTouch = data.pointerType === 'touch'; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + if (isMouse) { + this.processPointerOverOut(interactionEvent, displayObject, hit); + } + + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchmove', interactionEvent); + if (isMouse) this.dispatchEvent(displayObject, 'mousemove', interactionEvent); + } + }; + + /** + * Is called when the pointer is moved out of the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out + */ + + + InteractionManager.prototype.onPointerOut = function onPointerOut(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOut, so events will always be length 1 + var event = events[0]; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = false; + this.setCursorMode(null); + } + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, false); + + this.emit('pointerout', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseout', interactionEvent); + } else { + // we can get touchleave events after touchend, so we want to make sure we don't + // introduce memory leaks + this.releaseInteractionDataForPointerId(interactionData.identifier); + } + }; + + /** + * Processes the result of the pointer over/out check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerOverOut = function processPointerOverOut(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + var trackingData = displayObject.trackedPointers[id]; + + // if we just moused over the display object, then we need to track that state + if (hit && !trackingData) { + trackingData = displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + + if (trackingData === undefined) return; + + if (hit && this.mouseOverRenderer) { + if (!trackingData.over) { + trackingData.over = true; + this.dispatchEvent(displayObject, 'pointerover', interactionEvent); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseover', interactionEvent); + } + } + + // only change the cursor if it has not already been changed (by something deeper in the + // display tree) + if (isMouse && this.cursor === null) { + this.cursor = displayObject.cursor; + } + } else if (trackingData.over) { + trackingData.over = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseout', interactionEvent); + } + // if there is no mouse down information for the pointer, then it is safe to delete + if (trackingData.none) { + delete displayObject.trackedPointers[id]; + } + } + }; + + /** + * Is called when the pointer is moved into the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view + */ + + + InteractionManager.prototype.onPointerOver = function onPointerOver(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOver, so events will always be length 1 + var event = events[0]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = true; + } + + this.emit('pointerover', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseover', interactionEvent); + } + }; + + /** + * Get InteractionData for a given pointerId. Store that data as well + * + * @private + * @param {PointerEvent} event - Normalized pointer event, output from normalizeToPointerData + * @return {PIXI.interaction.InteractionData} - Interaction data for the given pointer identifier + */ + + + InteractionManager.prototype.getInteractionDataForPointerId = function getInteractionDataForPointerId(event) { + var pointerId = event.pointerId; + + var interactionData = void 0; + + if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { + interactionData = this.mouse; + } else if (this.activeInteractionData[pointerId]) { + interactionData = this.activeInteractionData[pointerId]; + } else { + interactionData = this.interactionDataPool.pop() || new _InteractionData2.default(); + interactionData.identifier = pointerId; + this.activeInteractionData[pointerId] = interactionData; + } + // copy properties from the event, so that we can make sure that touch/pointer specific + // data is available + interactionData.copyEvent(event); + + return interactionData; + }; + + /** + * Return unused InteractionData to the pool, for a given pointerId + * + * @private + * @param {number} pointerId - Identifier from a pointer event + */ + + + InteractionManager.prototype.releaseInteractionDataForPointerId = function releaseInteractionDataForPointerId(pointerId) { + var interactionData = this.activeInteractionData[pointerId]; + + if (interactionData) { + delete this.activeInteractionData[pointerId]; + interactionData.reset(); + this.interactionDataPool.push(interactionData); + } + }; + + /** + * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The event to be configured + * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent + * @param {PIXI.interaction.InteractionData} interactionData - The InteractionData that will be paired + * with the InteractionEvent + * @return {PIXI.interaction.InteractionEvent} the interaction event that was passed in + */ + + + InteractionManager.prototype.configureInteractionEventForDOMEvent = function configureInteractionEventForDOMEvent(interactionEvent, pointerEvent, interactionData) { + interactionEvent.data = interactionData; + + this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); + + // This is the way InteractionManager processed touch events before the refactoring, so I've kept + // it here. But it doesn't make that much sense to me, since mapPositionToPoint already factors + // in this.resolution, so this just divides by this.resolution twice for touch events... + if (navigator.isCocoonJS && pointerEvent.pointerType === 'touch') { + interactionData.global.x = interactionData.global.x / this.resolution; + interactionData.global.y = interactionData.global.y / this.resolution; + } + + // Not really sure why this is happening, but it's how a previous version handled things + if (pointerEvent.pointerType === 'touch') { + pointerEvent.globalX = interactionData.global.x; + pointerEvent.globalY = interactionData.global.y; + } + + interactionData.originalEvent = pointerEvent; + interactionEvent.reset(); + + return interactionEvent; + }; + + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * + * @private + * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event + * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer + * or mouse event, or a multiple normalized pointer events if there are multiple changed touches + */ + + + InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData(event) { + var normalizedEvents = []; + + if (this.supportsTouchEvents && event instanceof TouchEvent) { + for (var i = 0, li = event.changedTouches.length; i < li; i++) { + var touch = event.changedTouches[i]; + + if (typeof touch.button === 'undefined') touch.button = event.touches.length ? 1 : 0; + if (typeof touch.buttons === 'undefined') touch.buttons = event.touches.length ? 1 : 0; + if (typeof touch.isPrimary === 'undefined') { + touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart'; + } + if (typeof touch.width === 'undefined') touch.width = touch.radiusX || 1; + if (typeof touch.height === 'undefined') touch.height = touch.radiusY || 1; + if (typeof touch.tiltX === 'undefined') touch.tiltX = 0; + if (typeof touch.tiltY === 'undefined') touch.tiltY = 0; + if (typeof touch.pointerType === 'undefined') touch.pointerType = 'touch'; + if (typeof touch.pointerId === 'undefined') touch.pointerId = touch.identifier || 0; + if (typeof touch.pressure === 'undefined') touch.pressure = touch.force || 0.5; + touch.twist = 0; + touch.tangentialPressure = 0; + // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven + // support, and the fill ins are not quite the same + // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top + // left is not 0,0 on the page + if (typeof touch.layerX === 'undefined') touch.layerX = touch.offsetX = touch.clientX; + if (typeof touch.layerY === 'undefined') touch.layerY = touch.offsetY = touch.clientY; + + // mark the touch as normalized, just so that we know we did it + touch.isNormalized = true; + + normalizedEvents.push(touch); + } + } + // apparently PointerEvent subclasses MouseEvent, so yay + else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent))) { + if (typeof event.isPrimary === 'undefined') event.isPrimary = true; + if (typeof event.width === 'undefined') event.width = 1; + if (typeof event.height === 'undefined') event.height = 1; + if (typeof event.tiltX === 'undefined') event.tiltX = 0; + if (typeof event.tiltY === 'undefined') event.tiltY = 0; + if (typeof event.pointerType === 'undefined') event.pointerType = 'mouse'; + if (typeof event.pointerId === 'undefined') event.pointerId = MOUSE_POINTER_ID; + if (typeof event.pressure === 'undefined') event.pressure = 0.5; + event.twist = 0; + event.tangentialPressure = 0; + + // mark the mouse event as normalized, just so that we know we did it + event.isNormalized = true; + + normalizedEvents.push(event); + } else { + normalizedEvents.push(event); + } + + return normalizedEvents; + }; + + /** + * Destroys the interaction manager + * + */ + + + InteractionManager.prototype.destroy = function destroy() { + this.removeEvents(); + + this.removeAllListeners(); + + this.renderer = null; + + this.mouse = null; + + this.eventData = null; + + this.interactionDOMElement = null; + + this.onPointerDown = null; + this.processPointerDown = null; + + this.onPointerUp = null; + this.processPointerUp = null; + + this.onPointerCancel = null; + this.processPointerCancel = null; + + this.onPointerMove = null; + this.processPointerMove = null; + + this.onPointerOut = null; + this.processPointerOverOut = null; + + this.onPointerOver = null; + + this._tempPoint = null; + }; + + return InteractionManager; +}(_eventemitter2.default); + +exports.default = InteractionManager; + + +core.WebGLRenderer.registerPlugin('interaction', InteractionManager); +core.CanvasRenderer.registerPlugin('interaction', InteractionManager); + +},{"../core":65,"./InteractionData":155,"./InteractionEvent":156,"./InteractionTrackingData":158,"./interactiveTarget":160,"eventemitter3":3}],158:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * DisplayObjects with the {@link PIXI.interaction.interactiveTarget} mixin use this class to track interactions + * + * @class + * @private + * @memberof PIXI.interaction + */ +var InteractionTrackingData = function () { + /** + * @param {number} pointerId - Unique pointer id of the event + */ + function InteractionTrackingData(pointerId) { + _classCallCheck(this, InteractionTrackingData); + + this._pointerId = pointerId; + this._flags = InteractionTrackingData.FLAGS.NONE; + } + + /** + * + * @private + * @param {number} flag - The interaction flag to set + * @param {boolean} yn - Should the flag be set or unset + */ + + + InteractionTrackingData.prototype._doSet = function _doSet(flag, yn) { + if (yn) { + this._flags = this._flags | flag; + } else { + this._flags = this._flags & ~flag; + } + }; + + /** + * Unique pointer id of the event + * + * @readonly + * @member {number} + */ + + + _createClass(InteractionTrackingData, [{ + key: "pointerId", + get: function get() { + return this._pointerId; + } + + /** + * State of the tracking data, expressed as bit flags + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "flags", + get: function get() { + return this._flags; + } + + /** + * Set the flags for the tracking data + * + * @param {number} flags - Flags to set + */ + , + set: function set(flags) { + this._flags = flags; + } + + /** + * Is the tracked event inactive (not over or down)? + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "none", + get: function get() { + return this._flags === this.constructor.FLAGS.NONE; + } + + /** + * Is the tracked event over the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "over", + get: function get() { + return (this._flags & this.constructor.FLAGS.OVER) !== 0; + } + + /** + * Set the over flag + * + * @param {boolean} yn - Is the event over? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.OVER, yn); + } + + /** + * Did the right mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "rightDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.RIGHT_DOWN) !== 0; + } + + /** + * Set the right down flag + * + * @param {boolean} yn - Is the right mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.RIGHT_DOWN, yn); + } + + /** + * Did the left mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "leftDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.LEFT_DOWN) !== 0; + } + + /** + * Set the left down flag + * + * @param {boolean} yn - Is the left mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.LEFT_DOWN, yn); + } + }]); + + return InteractionTrackingData; +}(); + +exports.default = InteractionTrackingData; + + +InteractionTrackingData.FLAGS = Object.freeze({ + NONE: 0, + OVER: 1 << 0, + LEFT_DOWN: 1 << 1, + RIGHT_DOWN: 1 << 2 +}); + +},{}],159:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _InteractionData = require('./InteractionData'); + +Object.defineProperty(exports, 'InteractionData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionData).default; + } +}); + +var _InteractionManager = require('./InteractionManager'); + +Object.defineProperty(exports, 'InteractionManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionManager).default; + } +}); + +var _interactiveTarget = require('./interactiveTarget'); + +Object.defineProperty(exports, 'interactiveTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_interactiveTarget).default; + } +}); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +Object.defineProperty(exports, 'InteractionTrackingData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionTrackingData).default; + } +}); + +var _InteractionEvent = require('./InteractionEvent'); + +Object.defineProperty(exports, 'InteractionEvent', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionEvent).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./InteractionData":155,"./InteractionEvent":156,"./InteractionManager":157,"./InteractionTrackingData":158,"./interactiveTarget":160}],160:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * Default property values of interactive objects + * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties + * + * @private + * @name interactiveTarget + * @memberof PIXI.interaction + * @example + * function MyObject() {} + * + * Object.assign( + * core.DisplayObject.prototype, + * PIXI.interaction.interactiveTarget + * ); + */ +exports.default = { + + /** + * Enable interaction events for the DisplayObject. Touch, pointer and mouse + * events will not be emitted unless `interactive` is set to `true`. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.on('tap', (event) => { + * //handle event + * }); + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + interactive: false, + + /** + * Determines if the children to the displayObject can be clicked/touched + * Setting this to false allows PixiJS to bypass a recursive `hitTest` function + * + * @member {boolean} + * @memberof PIXI.Container# + */ + interactiveChildren: true, + + /** + * Interaction shape. Children will be hit first, then this shape will be checked. + * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.hitArea = new PIXI.Rectangle(0, 0, 100, 100); + * @member {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle} + * @memberof PIXI.DisplayObject# + */ + hitArea: null, + + /** + * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive + * Setting this changes the 'cursor' property to `'pointer'`. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.buttonMode = true; + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + get buttonMode() { + return this.cursor === 'pointer'; + }, + set buttonMode(value) { + if (value) { + this.cursor = 'pointer'; + } else if (this.cursor === 'pointer') { + this.cursor = null; + } + }, + + /** + * This defines what cursor mode is used when the mouse cursor + * is hovered over the displayObject. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.cursor = 'wait'; + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * + * @member {string} + * @memberof PIXI.DisplayObject# + */ + cursor: null, + + /** + * Internal set of all active pointers, by identifier + * + * @member {Map} + * @memberof PIXI.DisplayObject# + * @private + */ + get trackedPointers() { + if (this._trackedPointers === undefined) this._trackedPointers = {}; + + return this._trackedPointers; + }, + + /** + * Map of all tracked pointers, by identifier. Use trackedPointers to access. + * + * @private + * @type {Map} + */ + _trackedPointers: undefined +}; + +},{}],161:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.parse = parse; + +exports.default = function () { + return function bitmapFontParser(resource, next) { + // skip if no data or not xml data + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.XML) { + next(); + + return; + } + + // skip if not bitmap font data, using some silly duck-typing + if (resource.data.getElementsByTagName('page').length === 0 || resource.data.getElementsByTagName('info').length === 0 || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null) { + next(); + + return; + } + + var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; + + if (resource.isDataUrl) { + if (xmlUrl === '.') { + xmlUrl = ''; + } + + if (this.baseUrl && xmlUrl) { + // if baseurl has a trailing slash then add one to xmlUrl so the replace works below + if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { + xmlUrl += '/'; + } + } + } + + // remove baseUrl from xmlUrl + xmlUrl = xmlUrl.replace(this.baseUrl, ''); + + // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { + xmlUrl += '/'; + } + + var pages = resource.data.getElementsByTagName('page'); + var textures = {}; + + // Handle completed, when the number of textures + // load is the same number as references in the fnt file + var completed = function completed(page) { + textures[page.metadata.pageFile] = page.texture; + + if (Object.keys(textures).length === pages.length) { + parse(resource, textures); + next(); + } + }; + + for (var i = 0; i < pages.length; ++i) { + var pageFile = pages[i].getAttribute('file'); + var url = xmlUrl + pageFile; + var exists = false; + + // incase the image is loaded outside + // using the same loader, resource will be available + for (var name in this.resources) { + var bitmapResource = this.resources[name]; + + if (bitmapResource.url === url) { + bitmapResource.metadata.pageFile = pageFile; + if (bitmapResource.texture) { + completed(bitmapResource); + } else { + bitmapResource.onAfterMiddleware.add(completed); + } + exists = true; + break; + } + } + + // texture is not loaded, we'll attempt to add + // it to the load and add the texture to the list + if (!exists) { + // Standard loading options for images + var options = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: Object.assign({ pageFile: pageFile }, resource.metadata.imageMetadata), + parentResource: resource + }; + + this.add(url, options, completed); + } + } + }; +}; + +var _path = require('path'); + +var path = _interopRequireWildcard(_path); + +var _resourceLoader = require('resource-loader'); + +var _extras = require('../extras'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Register a BitmapText font from loader resource. + * + * @function parseBitmapFontData + * @memberof PIXI.loaders + * @param {PIXI.loaders.Resource} resource - Loader resource. + * @param {PIXI.Texture|PIXI.Texture[]} textures - List of textures for each page. + */ +function parse(resource, textures) { + resource.bitmapFont = _extras.BitmapText.registerFont(resource.data, textures); +} + +},{"../extras":141,"path":8,"resource-loader":36}],162:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.shared = exports.Resource = exports.textureParser = exports.getResourcePath = exports.spritesheetParser = exports.parseBitmapFontData = exports.bitmapFontParser = exports.Loader = undefined; + +var _bitmapFontParser = require('./bitmapFontParser'); + +Object.defineProperty(exports, 'bitmapFontParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_bitmapFontParser).default; + } +}); +Object.defineProperty(exports, 'parseBitmapFontData', { + enumerable: true, + get: function get() { + return _bitmapFontParser.parse; + } +}); + +var _spritesheetParser = require('./spritesheetParser'); + +Object.defineProperty(exports, 'spritesheetParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_spritesheetParser).default; + } +}); +Object.defineProperty(exports, 'getResourcePath', { + enumerable: true, + get: function get() { + return _spritesheetParser.getResourcePath; + } +}); + +var _textureParser = require('./textureParser'); + +Object.defineProperty(exports, 'textureParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_textureParser).default; + } +}); + +var _resourceLoader = require('resource-loader'); + +Object.defineProperty(exports, 'Resource', { + enumerable: true, + get: function get() { + return _resourceLoader.Resource; + } +}); + +var _Application = require('../core/Application'); + +var _Application2 = _interopRequireDefault(_Application); + +var _loader = require('./loader'); + +var _loader2 = _interopRequireDefault(_loader); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * This namespace contains APIs which extends the {@link https://github.com/englercj/resource-loader resource-loader} module + * for loading assets, data, and other resources dynamically. + * @example + * const loader = new PIXI.loaders.Loader(); + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.load((loader, resources) => { + * // resources.bunny + * // resources.spaceship + * }); + * @namespace PIXI.loaders + */ +exports.Loader = _loader2.default; + + +/** + * A premade instance of the loader that can be used to load resources. + * @name shared + * @memberof PIXI.loaders + * @type {PIXI.loaders.Loader} + */ +var shared = new _loader2.default(); + +shared.destroy = function () { + // protect destroying shared loader +}; + +exports.shared = shared; + +// Mixin the loader construction + +var AppPrototype = _Application2.default.prototype; + +AppPrototype._loader = null; + +/** + * Loader instance to help with asset loading. + * @name PIXI.Application#loader + * @type {PIXI.loaders.Loader} + */ +Object.defineProperty(AppPrototype, 'loader', { + get: function get() { + if (!this._loader) { + var sharedLoader = this._options.sharedLoader; + + this._loader = sharedLoader ? shared : new _loader2.default(); + } + + return this._loader; + } +}); + +// Override the destroy function +// making sure to destroy the current Loader +AppPrototype._parentDestroy = AppPrototype.destroy; +AppPrototype.destroy = function destroy(removeView, stageOptions) { + if (this._loader) { + this._loader.destroy(); + this._loader = null; + } + this._parentDestroy(removeView, stageOptions); +}; + +},{"../core/Application":43,"./bitmapFontParser":161,"./loader":163,"./spritesheetParser":164,"./textureParser":165,"resource-loader":36}],163:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _resourceLoader = require('resource-loader'); + +var _resourceLoader2 = _interopRequireDefault(_resourceLoader); + +var _blob = require('resource-loader/lib/middlewares/parsing/blob'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _textureParser = require('./textureParser'); + +var _textureParser2 = _interopRequireDefault(_textureParser); + +var _spritesheetParser = require('./spritesheetParser'); + +var _spritesheetParser2 = _interopRequireDefault(_spritesheetParser); + +var _bitmapFontParser = require('./bitmapFontParser'); + +var _bitmapFontParser2 = _interopRequireDefault(_bitmapFontParser); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader + * + * ```js + * const loader = PIXI.loader; // PixiJS exposes a premade instance for you to use. + * //or + * const loader = new PIXI.loaders.Loader(); // you can also create your own if you want + * + * const sprites = {}; + * + * // Chainable `add` to enqueue a resource + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.add('scoreFont', 'assets/score.fnt'); + * + * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. + * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). + * loader.pre(cachingMiddleware); + * + * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. + * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). + * loader.use(parsingMiddleware); + * + * // The `load` method loads the queue of resources, and calls the passed in callback called once all + * // resources have loaded. + * loader.load((loader, resources) => { + * // resources is an object where the key is the name of the resource loaded and the value is the resource object. + * // They have a couple default properties: + * // - `url`: The URL that the resource was loaded from + * // - `error`: The error that happened when trying to load (if any) + * // - `data`: The raw data that was loaded + * // also may contain other properties based on the middleware that runs. + * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); + * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); + * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); + * }); + * + * // throughout the process multiple signals can be dispatched. + * loader.onProgress.add(() => {}); // called once per loaded/errored file + * loader.onError.add(() => {}); // called once per errored file + * loader.onLoad.add(() => {}); // called once per loaded file + * loader.onComplete.add(() => {}); // called once when the queued resources all load. + * ``` + * + * @see https://github.com/englercj/resource-loader + * + * @class + * @extends module:resource-loader.ResourceLoader + * @memberof PIXI.loaders + */ +var Loader = function (_ResourceLoader) { + _inherits(Loader, _ResourceLoader); + + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + _classCallCheck(this, Loader); + + var _this = _possibleConstructorReturn(this, _ResourceLoader.call(this, baseUrl, concurrency)); + + _eventemitter2.default.call(_this); + + for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { + _this.use(Loader._pixiMiddleware[i]()); + } + + // Compat layer, translate the new v2 signals into old v1 events. + _this.onStart.add(function (l) { + return _this.emit('start', l); + }); + _this.onProgress.add(function (l, r) { + return _this.emit('progress', l, r); + }); + _this.onError.add(function (e, l, r) { + return _this.emit('error', e, l, r); + }); + _this.onLoad.add(function (l, r) { + return _this.emit('load', l, r); + }); + _this.onComplete.add(function (l, r) { + return _this.emit('complete', l, r); + }); + return _this; + } + + /** + * Adds a default middleware to the PixiJS loader. + * + * @static + * @param {Function} fn - The middleware to add. + */ + + + Loader.addPixiMiddleware = function addPixiMiddleware(fn) { + Loader._pixiMiddleware.push(fn); + }; + + /** + * Destroy the loader, removes references. + */ + + + Loader.prototype.destroy = function destroy() { + this.removeAllListeners(); + this.reset(); + }; + + return Loader; +}(_resourceLoader2.default); + +// Copy EE3 prototype (mixin) + + +exports.default = Loader; +for (var k in _eventemitter2.default.prototype) { + Loader.prototype[k] = _eventemitter2.default.prototype[k]; +} + +Loader._pixiMiddleware = [ +// parse any blob into more usable objects (e.g. Image) +_blob.blobMiddlewareFactory, +// parse any Image objects into textures +_textureParser2.default, +// parse any spritesheet data into multiple textures +_spritesheetParser2.default, +// parse bitmap font data into multiple textures +_bitmapFontParser2.default]; + +// Add custom extentions +var Resource = _resourceLoader2.default.Resource; + +Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); + +},{"./bitmapFontParser":161,"./spritesheetParser":164,"./textureParser":165,"eventemitter3":3,"resource-loader":36,"resource-loader/lib/middlewares/parsing/blob":37}],164:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function spritesheetParser(resource, next) { + var imageResourceName = resource.name + '_image'; + + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.JSON || !resource.data.frames || this.resources[imageResourceName]) { + next(); + + return; + } + + var loadOptions = { + crossOrigin: resource.crossOrigin, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + var resourcePath = getResourcePath(resource, this.baseUrl); + + // load the image for this sheet + this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + if (res.error) { + next(res.error); + + return; + } + + var spritesheet = new _core.Spritesheet(res.texture.baseTexture, resource.data, resource.url); + + spritesheet.parse(function () { + resource.spritesheet = spritesheet; + resource.textures = spritesheet.textures; + next(); + }); + }); + }; +}; + +exports.getResourcePath = getResourcePath; + +var _resourceLoader = require('resource-loader'); + +var _url = require('url'); + +var _url2 = _interopRequireDefault(_url); + +var _core = require('../core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function getResourcePath(resource, baseUrl) { + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + return resource.data.meta.image; + } + + return _url2.default.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); +} + +},{"../core":65,"resource-loader":36,"url":38}],165:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function textureParser(resource, next) { + // create a new texture if the data is an Image object + if (resource.data && resource.type === _resourceLoader.Resource.TYPE.IMAGE) { + resource.texture = _Texture2.default.fromLoader(resource.data, resource.url, resource.name); + } + next(); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"../core/textures/Texture":115,"resource-loader":36}],166:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); +var tempPolygon = new core.Polygon(); + +/** + * Base mesh class + * @class + * @extends PIXI.Container + * @memberof PIXI.mesh + */ + +var Mesh = function (_core$Container) { + _inherits(Mesh, _core$Container); + + /** + * @param {PIXI.Texture} texture - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts + */ + function Mesh(texture, vertices, uvs, indices, drawMode) { + _classCallCheck(this, Mesh); + + /** + * The texture of the Mesh + * + * @member {PIXI.Texture} + * @default PIXI.Texture.EMPTY + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._texture = texture || _Texture2.default.EMPTY; + + /** + * The Uvs of the Mesh + * + * @member {Float32Array} + */ + _this.uvs = uvs || new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + /** + * An array of vertices + * + * @member {Float32Array} + */ + _this.vertices = vertices || new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]); + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + // TODO auto generate this based on draw mode! + _this.indices = indices || new Uint16Array([0, 1, 3, 2]); + + /** + * Version of mesh uvs are dirty or not + * + * @member {number} + */ + _this.dirty = 0; + + /** + * Version of mesh indices + * + * @member {number} + */ + _this.indexDirty = 0; + + /** + * Version of mesh verticies array + * + * @member {number} + */ + _this.vertexDirty = 0; + + /** + * For backwards compatibility the default is to re-upload verticies each render call. + * Set this to `false` and increase `vertexDirty` to manually re-upload the buffer. + * + * @member {boolean} + */ + _this.autoUpdate = true; + + /** + * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove + * any blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles + * to overlap a bit with each other. + * + * @member {number} + */ + _this.canvasPadding = core.settings.MESH_CANVAS_PADDING; + + /** + * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts + * + * @member {number} + * @see PIXI.mesh.Mesh.DRAW_MODES + */ + _this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH; + + /** + * The default shader that is used if a mesh doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + _this.shader = null; + + /** + * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any + * tint effect. + * + * @member {number} + */ + _this.tintRgb = new Float32Array([1, 1, 1]); + + /** + * A map of renderer IDs to webgl render data + * + * @private + * @member {object} + */ + _this._glDatas = {}; + + /** + * transform that is applied to UV to get the texture coords + * its updated independently from texture uvTransform + * updates of uvs are tied to that thing + * + * @member {PIXI.TextureMatrix} + * @private + */ + _this._uvTransform = new core.TextureMatrix(_this._texture); + + /** + * whether or not upload uvTransform to shader + * if its false, then uvs should be pre-multiplied + * if you change it for generated mesh, please call 'refresh(true)' + * @member {boolean} + * @default false + */ + _this.uploadUvTransform = false; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * @member {string} + * @default 'mesh' + */ + _this.pluginName = 'mesh'; + return _this; + } + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - a reference to the WebGL renderer + */ + + + Mesh.prototype._renderWebGL = function _renderWebGL(renderer) { + this.refresh(); + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + + + Mesh.prototype._renderCanvas = function _renderCanvas(renderer) { + this.refresh(); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Mesh.prototype._onTextureUpdate = function _onTextureUpdate() { + this._uvTransform.texture = this._texture; + this.refresh(); + }; + + /** + * multiplies uvs only if uploadUvTransform is false + * call it after you change uvs manually + * make sure that texture is valid + */ + + + Mesh.prototype.multiplyUvs = function multiplyUvs() { + if (!this.uploadUvTransform) { + this._uvTransform.multiplyUvs(this.uvs); + } + }; + + /** + * Refreshes uvs for generated meshes (rope, plane) + * sometimes refreshes vertices too + * + * @param {boolean} [forceUpdate=false] if true, matrices will be updated any case + */ + + + Mesh.prototype.refresh = function refresh(forceUpdate) { + if (this.autoUpdate) { + this.vertexDirty++; + } + if (this._uvTransform.update(forceUpdate)) { + this._refresh(); + } + }; + + /** + * re-calculates mesh coords + * @protected + */ + + + Mesh.prototype._refresh = function _refresh() {} + /* empty */ + + + /** + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + */ + ; + + Mesh.prototype._calculateBounds = function _calculateBounds() { + // TODO - we can cache local bounds and use them if they are dirty (like graphics) + this._bounds.addVertices(this.transform, this.vertices, 0, this.vertices.length); + }; + + /** + * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Mesh.prototype.containsPoint = function containsPoint(point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + + this.worldTransform.applyInverse(point, tempPoint); + + var vertices = this.vertices; + var points = tempPolygon.points; + var indices = this.indices; + var len = this.indices.length; + var step = this.drawMode === Mesh.DRAW_MODES.TRIANGLES ? 3 : 1; + + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + + return false; + }; + + /** + * The texture that the mesh uses. + * + * @member {PIXI.Texture} + */ + + + /** + * Destroys the Mesh object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + Mesh.prototype.destroy = function destroy(options) { + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._glDatas) { + var data = this._glDatas[id]; + + if (data.destroy) { + data.destroy(); + } else { + if (data.vertexBuffer) { + data.vertexBuffer.destroy(); + data.vertexBuffer = null; + } + if (data.indexBuffer) { + data.indexBuffer.destroy(); + data.indexBuffer = null; + } + if (data.uvBuffer) { + data.uvBuffer.destroy(); + data.uvBuffer = null; + } + if (data.vao) { + data.vao.destroy(); + data.vao = null; + } + } + } + + this._glDatas = null; + + _core$Container.prototype.destroy.call(this, options); + }; + + _createClass(Mesh, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + + /** + * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return core.utils.rgb2hex(this.tintRgb); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tintRgb = core.utils.hex2rgb(value, this.tintRgb); + } + }]); + + return Mesh; +}(core.Container); + +/** + * Different drawing buffer modes supported + * + * @static + * @constant + * @type {object} + * @property {number} TRIANGLE_MESH + * @property {number} TRIANGLES + */ + + +exports.default = Mesh; +Mesh.DRAW_MODES = { + TRIANGLE_MESH: 0, + TRIANGLES: 1 +}; + +},{"../core":65,"../core/textures/Texture":115}],167:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Plane2 = require('./Plane'); + +var _Plane3 = _interopRequireDefault(_Plane2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DEFAULT_BORDER_SIZE = 10; + +/** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.fromImage('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
+ *      A                          B
+ *    +---+----------------------+---+
+ *  C | 1 |          2           | 3 |
+ *    +---+----------------------+---+
+ *    |   |                      |   |
+ *    | 4 |          5           | 6 |
+ *    |   |                      |   |
+ *    +---+----------------------+---+
+ *  D | 7 |          8           | 9 |
+ *    +---+----------------------+---+
+
+ *  When changing this objects width and/or height:
+ *     areas 1 3 7 and 9 will remain unscaled.
+ *     areas 2 and 8 will be stretched horizontally
+ *     areas 4 and 6 will be stretched vertically
+ *     area 5 will be stretched both horizontally and vertically
+ * 
+ * + * @class + * @extends PIXI.mesh.Plane + * @memberof PIXI.mesh + * + */ + +var NineSlicePlane = function (_Plane) { + _inherits(NineSlicePlane, _Plane); + + /** + * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. + * @param {int} [leftWidth=10] size of the left vertical bar (A) + * @param {int} [topHeight=10] size of the top horizontal bar (C) + * @param {int} [rightWidth=10] size of the right vertical bar (B) + * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) + */ + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + _classCallCheck(this, NineSlicePlane); + + var _this = _possibleConstructorReturn(this, _Plane.call(this, texture, 4, 4)); + + _this._origWidth = texture.orig.width; + _this._origHeight = texture.orig.height; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._width = _this._origWidth; + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._height = _this._origHeight; + + /** + * The width of the left column (a) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; + + /** + * The width of the right column (b) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; + + /** + * The height of the top row (c) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; + + /** + * The height of the bottom row (d) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; + + _this.refresh(true); + return _this; + } + + /** + * Updates the horizontal vertices. + * + */ + + + NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices() { + var vertices = this.vertices; + + var h = this._topHeight + this._bottomHeight; + var scale = this._height > h ? 1.0 : this._height / h; + + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight * scale; + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + }; + + /** + * Updates the vertical vertices. + * + */ + + + NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices() { + var vertices = this.vertices; + + var w = this._leftWidth + this._rightWidth; + var scale = this._width > w ? 1.0 : this._width / w; + + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth * scale; + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with. + */ + + + NineSlicePlane.prototype._renderCanvas = function _renderCanvas(renderer) { + var context = renderer.context; + + context.globalAlpha = this.worldAlpha; + renderer.setBlendMode(this.blendMode); + + var transform = this.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels || this.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + var base = this._texture.baseTexture; + var textureSource = base.source; + var w = base.width * base.resolution; + var h = base.height * base.resolution; + + this.drawSegment(context, textureSource, w, h, 0, 1, 10, 11); + this.drawSegment(context, textureSource, w, h, 2, 3, 12, 13); + this.drawSegment(context, textureSource, w, h, 4, 5, 14, 15); + this.drawSegment(context, textureSource, w, h, 8, 9, 18, 19); + this.drawSegment(context, textureSource, w, h, 10, 11, 20, 21); + this.drawSegment(context, textureSource, w, h, 12, 13, 22, 23); + this.drawSegment(context, textureSource, w, h, 16, 17, 26, 27); + this.drawSegment(context, textureSource, w, h, 18, 19, 28, 29); + this.drawSegment(context, textureSource, w, h, 20, 21, 30, 31); + }; + + /** + * Renders one segment of the plane. + * to mimic the exact drawing behavior of stretching the image like WebGL does, we need to make sure + * that the source area is at least 1 pixel in size, otherwise nothing gets drawn when a slice size of 0 is used. + * + * @private + * @param {CanvasRenderingContext2D} context - The context to draw with. + * @param {CanvasImageSource} textureSource - The source to draw. + * @param {number} w - width of the texture + * @param {number} h - height of the texture + * @param {number} x1 - x index 1 + * @param {number} y1 - y index 1 + * @param {number} x2 - x index 2 + * @param {number} y2 - y index 2 + */ + + + NineSlicePlane.prototype.drawSegment = function drawSegment(context, textureSource, w, h, x1, y1, x2, y2) { + // otherwise you get weird results when using slices of that are 0 wide or high. + var uvs = this.uvs; + var vertices = this.vertices; + + var sw = (uvs[x2] - uvs[x1]) * w; + var sh = (uvs[y2] - uvs[y1]) * h; + var dw = vertices[x2] - vertices[x1]; + var dh = vertices[y2] - vertices[y1]; + + // make sure the source is at least 1 pixel wide and high, otherwise nothing will be drawn. + if (sw < 1) { + sw = 1; + } + + if (sh < 1) { + sh = 1; + } + + // make sure destination is at least 1 pixel wide and high, otherwise you get + // lines when rendering close to original size. + if (dw < 1) { + dw = 1; + } + + if (dh < 1) { + dh = 1; + } + + context.drawImage(textureSource, uvs[x1] * w, uvs[y1] * h, sw, sh, vertices[x1], vertices[y1], dw, dh); + }; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + + /** + * Refreshes NineSlicePlane coords. All of them. + */ + NineSlicePlane.prototype._refresh = function _refresh() { + _Plane.prototype._refresh.call(this); + + var uvs = this.uvs; + var texture = this._texture; + + this._origWidth = texture.orig.width; + this._origHeight = texture.orig.height; + + var _uvw = 1.0 / this._origWidth; + var _uvh = 1.0 / this._origHeight; + + uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; + uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - _uvw * this._rightWidth; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - _uvh * this._bottomHeight; + + this.updateHorizontalVertices(); + this.updateVerticalVertices(); + + this.dirty++; + + this.multiplyUvs(); + }; + + _createClass(NineSlicePlane, [{ + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + this._refresh(); + } + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + this._refresh(); + } + + /** + * The width of the left column + * + * @member {number} + */ + + }, { + key: 'leftWidth', + get: function get() { + return this._leftWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._leftWidth = value; + this._refresh(); + } + + /** + * The width of the right column + * + * @member {number} + */ + + }, { + key: 'rightWidth', + get: function get() { + return this._rightWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rightWidth = value; + this._refresh(); + } + + /** + * The height of the top row + * + * @member {number} + */ + + }, { + key: 'topHeight', + get: function get() { + return this._topHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._topHeight = value; + this._refresh(); + } + + /** + * The height of the bottom row + * + * @member {number} + */ + + }, { + key: 'bottomHeight', + get: function get() { + return this._bottomHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._bottomHeight = value; + this._refresh(); + } + }]); + + return NineSlicePlane; +}(_Plane3.default); + +exports.default = NineSlicePlane; + +},{"./Plane":168}],168:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The Plane allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Plane = function (_Mesh) { + _inherits(Plane, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the Plane. + * @param {number} [verticesX=10] - The number of vertices in the x-axis + * @param {number} [verticesY=10] - The number of vertices in the y-axis + */ + function Plane(texture, verticesX, verticesY) { + _classCallCheck(this, Plane); + + /** + * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this._ready = true; + + _this.verticesX = verticesX || 10; + _this.verticesY = verticesY || 10; + + _this.drawMode = _Mesh3.default.DRAW_MODES.TRIANGLES; + _this.refresh(); + return _this; + } + + /** + * Refreshes plane coordinates + * + */ + + + Plane.prototype._refresh = function _refresh() { + var texture = this._texture; + var total = this.verticesX * this.verticesY; + var verts = []; + var colors = []; + var uvs = []; + var indices = []; + + var segmentsX = this.verticesX - 1; + var segmentsY = this.verticesY - 1; + + var sizeX = texture.width / segmentsX; + var sizeY = texture.height / segmentsY; + + for (var i = 0; i < total; i++) { + var x = i % this.verticesX; + var y = i / this.verticesX | 0; + + verts.push(x * sizeX, y * sizeY); + + uvs.push(x / segmentsX, y / segmentsY); + } + + // cons + + var totalSub = segmentsX * segmentsY; + + for (var _i = 0; _i < totalSub; _i++) { + var xpos = _i % segmentsX; + var ypos = _i / segmentsX | 0; + + var value = ypos * this.verticesX + xpos; + var value2 = ypos * this.verticesX + xpos + 1; + var value3 = (ypos + 1) * this.verticesX + xpos; + var value4 = (ypos + 1) * this.verticesX + xpos + 1; + + indices.push(value, value2, value3); + indices.push(value2, value4, value3); + } + + // console.log(indices) + this.vertices = new Float32Array(verts); + this.uvs = new Float32Array(uvs); + this.colors = new Float32Array(colors); + this.indices = new Uint16Array(indices); + + this.dirty++; + this.indexDirty++; + + this.multiplyUvs(); + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Plane.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh3.default.prototype._onTextureUpdate.call(this); + + // wait for the Plane ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + return Plane; +}(_Mesh3.default); + +exports.default = Plane; + +},{"./Mesh":166}],169:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The rope allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Rope = function (_Mesh) { + _inherits(Rope, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the rope. + * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. + */ + function Rope(texture, points) { + _classCallCheck(this, Rope); + + /** + * An array of points that determine the rope + * + * @member {PIXI.Point[]} + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this.points = points; + + /** + * An array of vertices used to construct this rope. + * + * @member {Float32Array} + */ + _this.vertices = new Float32Array(points.length * 4); + + /** + * The WebGL Uvs of the rope. + * + * @member {Float32Array} + */ + _this.uvs = new Float32Array(points.length * 4); + + /** + * An array containing the color components + * + * @member {Float32Array} + */ + _this.colors = new Float32Array(points.length * 2); + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + _this.indices = new Uint16Array(points.length * 2); + + /** + * refreshes vertices on every updateTransform + * @member {boolean} + * @default true + */ + _this.autoUpdate = true; + + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Rope.prototype._refresh = function _refresh() { + var points = this.points; + + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1 || !this._texture._uvs) { + return; + } + + // if the number of points has changed we will need to recreate the arraybuffers + if (this.vertices.length / 4 !== points.length) { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + + for (var i = 1; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + var amount = i / (total - 1); + + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + + // ensure that the changes are uploaded + this.dirty++; + this.indexDirty++; + + this.multiplyUvs(); + this.refreshVertices(); + }; + + /** + * refreshes vertices of Rope mesh + */ + + + Rope.prototype.refreshVertices = function refreshVertices() { + var points = this.points; + + if (points.length < 1) { + return; + } + + var lastPoint = points[0]; + var nextPoint = void 0; + var perpX = 0; + var perpY = 0; + + // this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } else { + nextPoint = point; + } + + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + + var ratio = (1 - i / (total - 1)) * 10; + + if (ratio > 1) { + ratio = 1; + } + + var perpLength = Math.sqrt(perpX * perpX + perpY * perpY); + var num = this._texture.height / 2; // (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; + + perpX /= perpLength; + perpY /= perpLength; + + perpX *= num; + perpY *= num; + + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + + lastPoint = point; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + Rope.prototype.updateTransform = function updateTransform() { + if (this.autoUpdate) { + this.refreshVertices(); + } + this.containerUpdateTransform(); + }; + + return Rope; +}(_Mesh3.default); + +exports.default = Rope; + +},{"./Mesh":166}],170:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Renderer dedicated to meshes. + * + * @class + * @private + * @memberof PIXI + */ +var MeshSpriteRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The renderer this downport works for + */ + function MeshSpriteRenderer(renderer) { + _classCallCheck(this, MeshSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the Mesh + * + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var context = renderer.context; + + var transform = mesh.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels || this.roundPixels) { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + renderer.context.globalAlpha = mesh.worldAlpha; + renderer.setBlendMode(mesh.blendMode); + + if (mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH) { + this._renderTriangleMesh(mesh); + } else { + this._renderTriangles(mesh); + } + }; + + /** + * Draws the object in Triangle Mesh mode + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype._renderTriangleMesh = function _renderTriangleMesh(mesh) { + // draw triangles!! + var length = mesh.vertices.length / 2; + + for (var i = 0; i < length - 2; i++) { + // draw some triangles! + var index = i * 2; + + this._renderDrawTriangle(mesh, index, index + 2, index + 4); + } + }; + + /** + * Draws the object in triangle mode using canvas + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + */ + + + MeshSpriteRenderer.prototype._renderTriangles = function _renderTriangles(mesh) { + // draw triangles!! + var indices = mesh.indices; + var length = indices.length; + + for (var i = 0; i < length; i += 3) { + // draw some triangles! + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderDrawTriangle(mesh, index0, index1, index2); + } + }; + + /** + * Draws one of the triangles that from the Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + * @param {number} index0 - the index of the first vertex + * @param {number} index1 - the index of the second vertex + * @param {number} index2 - the index of the third vertex + */ + + + MeshSpriteRenderer.prototype._renderDrawTriangle = function _renderDrawTriangle(mesh, index0, index1, index2) { + var context = this.renderer.context; + var uvs = mesh.uvs; + var vertices = mesh.vertices; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var base = texture.baseTexture; + var textureSource = base.source; + var textureWidth = base.width; + var textureHeight = base.height; + + var u0 = void 0; + var u1 = void 0; + var u2 = void 0; + var v0 = void 0; + var v1 = void 0; + var v2 = void 0; + + if (mesh.uploadUvTransform) { + var ut = mesh._uvTransform.mapCoord; + + u0 = (uvs[index0] * ut.a + uvs[index0 + 1] * ut.c + ut.tx) * base.width; + u1 = (uvs[index1] * ut.a + uvs[index1 + 1] * ut.c + ut.tx) * base.width; + u2 = (uvs[index2] * ut.a + uvs[index2 + 1] * ut.c + ut.tx) * base.width; + v0 = (uvs[index0] * ut.b + uvs[index0 + 1] * ut.d + ut.ty) * base.height; + v1 = (uvs[index1] * ut.b + uvs[index1 + 1] * ut.d + ut.ty) * base.height; + v2 = (uvs[index2] * ut.b + uvs[index2 + 1] * ut.d + ut.ty) * base.height; + } else { + u0 = uvs[index0] * base.width; + u1 = uvs[index1] * base.width; + u2 = uvs[index2] * base.width; + v0 = uvs[index0 + 1] * base.height; + v1 = uvs[index1 + 1] * base.height; + v2 = uvs[index2 + 1] * base.height; + } + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + var canvasPadding = mesh.canvasPadding / this.renderer.resolution; + + if (canvasPadding > 0) { + var paddingX = canvasPadding / Math.abs(mesh.worldTransform.a); + var paddingY = canvasPadding / Math.abs(mesh.worldTransform.d); + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt(normX * normX + normY * normY); + + x0 = centerX + normX / dist * (dist + paddingX); + y0 = centerY + normY / dist * (dist + paddingY); + + // + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x1 = centerX + normX / dist * (dist + paddingX); + y1 = centerY + normY / dist * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x2 = centerX + normX / dist * (dist + paddingX); + y2 = centerY + normY / dist * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2; + var deltaA = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2; + var deltaB = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2; + var deltaC = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2; + var deltaD = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2; + var deltaE = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2; + var deltaF = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2; + + context.transform(deltaA / delta, deltaD / delta, deltaB / delta, deltaE / delta, deltaC / delta, deltaF / delta); + + context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + + context.restore(); + this.renderer.invalidateBlendMode(); + }; + + /** + * Renders a flat Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - The Mesh to render + */ + + + MeshSpriteRenderer.prototype.renderMeshFlat = function renderMeshFlat(mesh) { + var context = this.renderer.context; + var vertices = mesh.vertices; + var length = vertices.length / 2; + + // this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; ++i) { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var y0 = vertices[index + 1]; + + var x1 = vertices[index + 2]; + var y1 = vertices[index + 3]; + + var x2 = vertices[index + 4]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + }; + + /** + * destroy the the renderer. + * + */ + + + MeshSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return MeshSpriteRenderer; +}(); + +exports.default = MeshSpriteRenderer; + + +core.CanvasRenderer.registerPlugin('mesh', MeshSpriteRenderer); + +},{"../../core":65,"../Mesh":166}],171:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh = require('./Mesh'); + +Object.defineProperty(exports, 'Mesh', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Mesh).default; + } +}); + +var _MeshRenderer = require('./webgl/MeshRenderer'); + +Object.defineProperty(exports, 'MeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_MeshRenderer).default; + } +}); + +var _CanvasMeshRenderer = require('./canvas/CanvasMeshRenderer'); + +Object.defineProperty(exports, 'CanvasMeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasMeshRenderer).default; + } +}); + +var _Plane = require('./Plane'); + +Object.defineProperty(exports, 'Plane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Plane).default; + } +}); + +var _NineSlicePlane = require('./NineSlicePlane'); + +Object.defineProperty(exports, 'NineSlicePlane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NineSlicePlane).default; + } +}); + +var _Rope = require('./Rope'); + +Object.defineProperty(exports, 'Rope', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rope).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./Mesh":166,"./NineSlicePlane":167,"./Plane":168,"./Rope":169,"./canvas/CanvasMeshRenderer":170,"./webgl/MeshRenderer":172}],172:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var matrixIdentity = core.Matrix.IDENTITY; + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var MeshRenderer = function (_core$ObjectRenderer) { + _inherits(MeshRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function MeshRenderer(renderer) { + _classCallCheck(this, MeshRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + MeshRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n'); + }; + + /** + * renders mesh + * + * @param {PIXI.mesh.Mesh} mesh mesh instance + */ + + + MeshRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var gl = renderer.gl; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var glData = mesh._glDatas[renderer.CONTEXT_UID]; + + if (!glData) { + renderer.bindVao(null); + + glData = { + shader: this.shader, + vertexBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.vertices, gl.STREAM_DRAW), + uvBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.uvs, gl.STREAM_DRAW), + indexBuffer: _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, mesh.indices, gl.STATIC_DRAW), + // build the vao object that will render.. + vao: null, + dirty: mesh.dirty, + indexDirty: mesh.indexDirty, + vertexDirty: mesh.vertexDirty + }; + + // build the vao object that will render.. + glData.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(glData.indexBuffer).addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0).addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); + + mesh._glDatas[renderer.CONTEXT_UID] = glData; + } + + renderer.bindVao(glData.vao); + + if (mesh.dirty !== glData.dirty) { + glData.dirty = mesh.dirty; + glData.uvBuffer.upload(mesh.uvs); + } + + if (mesh.indexDirty !== glData.indexDirty) { + glData.indexDirty = mesh.indexDirty; + glData.indexBuffer.upload(mesh.indices); + } + + if (mesh.vertexDirty !== glData.vertexDirty) { + glData.vertexDirty = mesh.vertexDirty; + glData.vertexBuffer.upload(mesh.vertices); + } + + renderer.bindShader(glData.shader); + + glData.shader.uniforms.uSampler = renderer.bindTexture(texture); + + renderer.state.setBlendMode(core.utils.correctBlendMode(mesh.blendMode, texture.baseTexture.premultipliedAlpha)); + + if (glData.shader.uniforms.uTransform) { + if (mesh.uploadUvTransform) { + glData.shader.uniforms.uTransform = mesh._uvTransform.mapCoord.toArray(true); + } else { + glData.shader.uniforms.uTransform = matrixIdentity.toArray(true); + } + } + glData.shader.uniforms.translationMatrix = mesh.worldTransform.toArray(true); + + glData.shader.uniforms.uColor = core.utils.premultiplyRgba(mesh.tintRgb, mesh.worldAlpha, glData.shader.uniforms.uColor, texture.baseTexture.premultipliedAlpha); + + var drawMode = mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + glData.vao.draw(drawMode, mesh.indices.length, 0); + }; + + return MeshRenderer; +}(core.ObjectRenderer); + +exports.default = MeshRenderer; + + +core.WebGLRenderer.registerPlugin('mesh', MeshRenderer); + +},{"../../core":65,"../Mesh":166,"path":8,"pixi-gl-core":15}],173:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _utils = require('../core/utils'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that most advanced + * functionality will not work. ParticleContainer implements the basic object transform (position, scale, rotation) + * and some advanced functionality like tint (as of v4.5.6). + * Other more advanced functionality like masking, children, filters, etc will not work on sprites in this batch. + * + * It's extremely easy to use : + * + * ```js + * let container = new ParticleContainer(); + * + * for (let i = 0; i < 100; ++i) + * { + * let sprite = new PIXI.Sprite.fromImage("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be rendered at the speed of light. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.particles + */ +var ParticleContainer = function (_core$Container) { + _inherits(ParticleContainer, _core$Container); + + /** + * @param {number} [maxSize=1500] - The maximum number of particles that can be rendered by the container. + * Affects size of allocated buffers. + * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.vertices=false] - When true, vertices be uploaded and applied. + * if sprite's ` scale/anchor/trim/frame/orig` is dynamic, please set `true`. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.tint=false] - When true, alpha and tint be uploaded and applied. + * @param {number} [batchSize=16384] - Number of particles per batch. If less than maxSize, it uses maxSize instead. + * @param {boolean} [autoResize=false] If true, container allocates more batches in case + * there are more than `maxSize` particles. + */ + function ParticleContainer() { + var maxSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1500; + var properties = arguments[1]; + var batchSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 16384; + var autoResize = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + _classCallCheck(this, ParticleContainer); + + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + var maxBatchSize = 16384; + + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + + if (batchSize > maxSize) { + batchSize = maxSize; + } + + /** + * Set properties to be dynamic (true) / static (false) + * + * @member {boolean[]} + * @private + */ + _this._properties = [false, true, false, false, false]; + + /** + * @member {number} + * @private + */ + _this._maxSize = maxSize; + + /** + * @member {number} + * @private + */ + _this._batchSize = batchSize; + + /** + * @member {object} + * @private + */ + _this._glBuffers = {}; + + /** + * for every batch stores _updateID corresponding to the last change in that batch + * @member {number[]} + * @private + */ + _this._bufferUpdateIDs = []; + + /** + * when child inserted, removed or changes position this number goes up + * @member {number[]} + * @private + */ + _this._updateID = 0; + + /** + * @member {boolean} + * + */ + _this.interactiveChildren = false; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` + * to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * If true, container allocates more batches in case there are more than `maxSize` particles. + * @member {boolean} + * @default false + */ + _this.autoResize = autoResize; + + /** + * Used for canvas renderering. If true then the elements will be positioned at the + * nearest pixel. This provides a nice speed boost. + * + * @member {boolean} + * @default true; + */ + _this.roundPixels = true; + + /** + * The texture used to render the children. + * + * @readonly + * @member {BaseTexture} + */ + _this.baseTexture = null; + + _this.setProperties(properties); + + /** + * The tint applied to the container. + * This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = 0; + _this.tintRgb = new Float32Array(4); + _this.tint = 0xFFFFFF; + return _this; + } + + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * + * @param {object} properties - The properties to be uploaded + */ + + + ParticleContainer.prototype.setProperties = function setProperties(properties) { + if (properties) { + this._properties[0] = 'vertices' in properties || 'scale' in properties ? !!properties.vertices || !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'tint' in properties || 'alpha' in properties ? !!properties.tint || !!properties.alpha : this._properties[4]; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + ParticleContainer.prototype.updateTransform = function updateTransform() { + // TODO don't need to! + this.displayObjectUpdateTransform(); + // PIXI.Container.prototype.updateTransform.call( this ); + }; + + /** + * The tint applied to the container. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + ** IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * @member {number} + * @default 0xFFFFFF + */ + + + /** + * Renders the container using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer + */ + ParticleContainer.prototype.renderWebGL = function renderWebGL(renderer) { + var _this2 = this; + + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.hasLoaded) { + this.baseTexture.once('update', function () { + return _this2.onChildrenChange(0); + }); + } + } + + renderer.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + + /** + * Set the flag that static data should be updated to true + * + * @private + * @param {number} smallestChildIndex - The smallest child index + */ + + + ParticleContainer.prototype.onChildrenChange = function onChildrenChange(smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + + while (this._bufferUpdateIDs.length < bufferIndex) { + this._bufferUpdateIDs.push(0); + } + this._bufferUpdateIDs[bufferIndex] = ++this._updateID; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + + + ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var isRotated = true; + + var positionX = 0; + var positionY = 0; + + var finalWidth = 0; + var finalHeight = 0; + + renderer.setBlendMode(this.blendMode); + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i]; + + if (!child.visible) { + continue; + } + + var frame = child._texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) { + // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call + if (isRotated) { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx * renderer.resolution, transform.ty * renderer.resolution); + + isRotated = false; + } + + positionX = child.anchor.x * (-frame.width * child.scale.x) + child.position.x + 0.5; + positionY = child.anchor.y * (-frame.height * child.scale.y) + child.position.y + 0.5; + + finalWidth = frame.width * child.scale.x; + finalHeight = frame.height * child.scale.y; + } else { + if (!isRotated) { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + + if (renderer.roundPixels || this.roundPixels) { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution | 0, childTransform.ty * renderer.resolution | 0); + } else { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution, childTransform.ty * renderer.resolution); + } + + positionX = child.anchor.x * -frame.width + 0.5; + positionY = child.anchor.y * -frame.height + 0.5; + + finalWidth = frame.width; + finalHeight = frame.height; + } + + var resolution = child._texture.baseTexture.resolution; + + context.drawImage(child._texture.baseTexture.source, frame.x * resolution, frame.y * resolution, frame.width * resolution, frame.height * resolution, positionX * renderer.resolution, positionY * renderer.resolution, finalWidth * renderer.resolution, finalHeight * renderer.resolution); + } + }; + + /** + * Destroys the container + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + ParticleContainer.prototype.destroy = function destroy(options) { + _core$Container.prototype.destroy.call(this, options); + + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + } + + this._properties = null; + this._buffers = null; + this._bufferUpdateIDs = null; + }; + + _createClass(ParticleContainer, [{ + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + (0, _utils.hex2rgb)(value, this.tintRgb); + } + }]); + + return ParticleContainer; +}(core.Container); + +exports.default = ParticleContainer; + +},{"../core":65,"../core/utils":125}],174:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ParticleContainer = require('./ParticleContainer'); + +Object.defineProperty(exports, 'ParticleContainer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleContainer).default; + } +}); + +var _ParticleRenderer = require('./webgl/ParticleRenderer'); + +Object.defineProperty(exports, 'ParticleRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleRenderer).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./ParticleContainer":173,"./webgl/ParticleRenderer":176}],175:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + +/** + * The particle buffer manages the static and dynamic buffers for a particle container. + * + * @class + * @private + * @memberof PIXI + */ +var ParticleBuffer = function () { + /** + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(gl, properties, dynamicPropertyFlags, size) { + _classCallCheck(this, ParticleBuffer); + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The number of particles the buffer can hold + * + * @member {number} + */ + this.size = size; + + /** + * A list of the properties that are dynamic. + * + * @member {object[]} + */ + this.dynamicProperties = []; + + /** + * A list of the properties that are static. + * + * @member {object[]} + */ + this.staticProperties = []; + + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attribute: property.attribute, + size: property.size, + uploadFunction: property.uploadFunction, + unsignedByte: property.unsignedByte, + offset: property.offset + }; + + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } else { + this.staticProperties.push(property); + } + } + + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + + this._updateID = 0; + + this.initBuffers(); + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + ParticleBuffer.prototype.initBuffers = function initBuffers() { + var gl = this.gl; + var dynamicOffset = 0; + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(this.size); + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + this.dynamicStride = 0; + + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + + var dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4); + + this.dynamicData = new Float32Array(dynBuffer); + this.dynamicDataUint32 = new Uint32Array(dynBuffer); + this.dynamicBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, dynBuffer, gl.STREAM_DRAW); + + // static // + var staticOffset = 0; + + this.staticStride = 0; + + for (var _i = 0; _i < this.staticProperties.length; ++_i) { + var _property = this.staticProperties[_i]; + + _property.offset = staticOffset; + staticOffset += _property.size; + this.staticStride += _property.size; + } + + var statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4); + + this.staticData = new Float32Array(statBuffer); + this.staticDataUint32 = new Uint32Array(statBuffer); + this.staticBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, statBuffer, gl.STATIC_DRAW); + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(this.indexBuffer); + + for (var _i2 = 0; _i2 < this.dynamicProperties.length; ++_i2) { + var _property2 = this.dynamicProperties[_i2]; + + if (_property2.unsignedByte) { + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.UNSIGNED_BYTE, true, this.dynamicStride * 4, _property2.offset * 4); + } else { + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.FLOAT, false, this.dynamicStride * 4, _property2.offset * 4); + } + } + + for (var _i3 = 0; _i3 < this.staticProperties.length; ++_i3) { + var _property3 = this.staticProperties[_i3]; + + if (_property3.unsignedByte) { + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.UNSIGNED_BYTE, true, this.staticStride * 4, _property3.offset * 4); + } else { + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.FLOAT, false, this.staticStride * 4, _property3.offset * 4); + } + } + }; + + /** + * Uploads the dynamic properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadDynamic = function uploadDynamic(children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + + property.uploadFunction(children, startIndex, amount, property.unsignedByte ? this.dynamicDataUint32 : this.dynamicData, this.dynamicStride, property.offset); + } + + this.dynamicBuffer.upload(); + }; + + /** + * Uploads the static properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadStatic = function uploadStatic(children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + + property.uploadFunction(children, startIndex, amount, property.unsignedByte ? this.staticDataUint32 : this.staticData, this.staticStride, property.offset); + } + + this.staticBuffer.upload(); + }; + + /** + * Destroys the ParticleBuffer. + * + */ + + + ParticleBuffer.prototype.destroy = function destroy() { + this.dynamicProperties = null; + this.dynamicBuffer.destroy(); + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + + this.staticProperties = null; + this.staticBuffer.destroy(); + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + }; + + return ParticleBuffer; +}(); + +exports.default = ParticleBuffer; + +},{"../../core/utils/createIndicesForQuads":123,"pixi-gl-core":15}],176:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _ParticleShader = require('./ParticleShader'); + +var _ParticleShader2 = _interopRequireDefault(_ParticleShader); + +var _ParticleBuffer = require('./ParticleBuffer'); + +var _ParticleBuffer2 = _interopRequireDefault(_ParticleBuffer); + +var _utils = require('../../core/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + +/** + * + * @class + * @private + * @memberof PIXI + */ +var ParticleRenderer = function (_core$ObjectRenderer) { + _inherits(ParticleRenderer, _core$ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + _classCallCheck(this, ParticleRenderer); + + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; + + /** + * The default shader that is used if a sprite doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + + _this.indexBuffer = null; + + _this.properties = null; + + _this.tempMatrix = new core.Matrix(); + + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * When there is a WebGL context change + * + * @private + */ + + + ParticleRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + + // setup default shader + this.shader = new _ParticleShader2.default(gl); + + this.properties = [ + // verticesData + { + attribute: this.shader.attributes.aVertexPosition, + size: 2, + uploadFunction: this.uploadVertices, + offset: 0 + }, + // positionData + { + attribute: this.shader.attributes.aPositionCoord, + size: 2, + uploadFunction: this.uploadPosition, + offset: 0 + }, + // rotationData + { + attribute: this.shader.attributes.aRotation, + size: 1, + uploadFunction: this.uploadRotation, + offset: 0 + }, + // uvsData + { + attribute: this.shader.attributes.aTextureCoord, + size: 2, + uploadFunction: this.uploadUvs, + offset: 0 + }, + // tintData + { + attribute: this.shader.attributes.aColor, + size: 1, + unsignedByte: true, + uploadFunction: this.uploadTint, + offset: 0 + }]; + }; + + /** + * Starts a new particle batch. + * + */ + + + ParticleRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + }; + + /** + * Renders the particle container object. + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + */ + + + ParticleRenderer.prototype.render = function render(container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var renderer = this.renderer; + var totalChildren = children.length; + + if (totalChildren === 0) { + return; + } else if (totalChildren > maxSize) { + totalChildren = maxSize; + } + + var buffers = container._glBuffers[renderer.CONTEXT_UID]; + + if (!buffers) { + buffers = container._glBuffers[renderer.CONTEXT_UID] = this.generateBuffers(container); + } + + var baseTexture = children[0]._texture.baseTexture; + + // if the uvs have not updated then no point rendering just yet! + this.renderer.setBlendMode(core.utils.correctBlendMode(container.blendMode, baseTexture.premultipliedAlpha)); + + var gl = renderer.gl; + + var m = container.worldTransform.copy(this.tempMatrix); + + m.prepend(renderer._activeRenderTarget.projectionMatrix); + + this.shader.uniforms.projectionMatrix = m.toArray(true); + + this.shader.uniforms.uColor = core.utils.premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, baseTexture.premultipliedAlpha); + + // make sure the texture is bound.. + this.shader.uniforms.uSampler = renderer.bindTexture(baseTexture); + + var updateStatic = false; + + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = totalChildren - i; + + if (amount > batchSize) { + amount = batchSize; + } + + if (j >= buffers.length) { + if (!container.autoResize) { + break; + } + buffers.push(this._generateOneMoreBuffer(container)); + } + + var buffer = buffers[j]; + + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + + var bid = container._bufferUpdateIDs[j] || 0; + + updateStatic = updateStatic || buffer._updateID < bid; + // we only upload the static content when we have to! + if (updateStatic) { + buffer._updateID = container._updateID; + buffer.uploadStatic(children, i, amount); + } + + // bind the buffer + renderer.bindVao(buffer.vao); + buffer.vao.draw(gl.TRIANGLES, amount * 6); + } + }; + + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer[]} The buffers + */ + + + ParticleRenderer.prototype.generateBuffers = function generateBuffers(container) { + var gl = this.renderer.gl; + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + for (var i = 0; i < size; i += batchSize) { + buffers.push(new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize)); + } + + return buffers; + }; + + /** + * Creates one more particle buffer, because container has autoResize feature + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer} generated buffer + * @private + */ + + + ParticleRenderer.prototype._generateOneMoreBuffer = function _generateOneMoreBuffer(container) { + var gl = this.renderer.gl; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + return new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize); + }; + + /** + * Uploads the verticies. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their vertices uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadVertices = function uploadVertices(children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - sprite.anchor.x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - sprite.anchor.y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - sprite.anchor.x); + w1 = orig.width * -sprite.anchor.x; + + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + + array[offset + stride * 2] = w0 * sx; + array[offset + stride * 2 + 1] = h0 * sy; + + array[offset + stride * 3] = w1 * sx; + array[offset + stride * 3 + 1] = h0 * sy; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their positions uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadPosition = function uploadPosition(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + + array[offset + stride * 2] = spritePosition.x; + array[offset + stride * 2 + 1] = spritePosition.y; + + array[offset + stride * 3] = spritePosition.x; + array[offset + stride * 3 + 1] = spritePosition.y; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadRotation = function uploadRotation(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + stride * 2] = spriteRotation; + array[offset + stride * 3] = spriteRotation; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadUvs = function uploadUvs(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + + array[offset + stride * 2] = textureUvs.x2; + array[offset + stride * 2 + 1] = textureUvs.y2; + + array[offset + stride * 3] = textureUvs.x3; + array[offset + stride * 3 + 1] = textureUvs.y3; + + offset += stride * 4; + } else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + + array[offset + stride * 2] = 0; + array[offset + stride * 2 + 1] = 0; + + array[offset + stride * 3] = 0; + array[offset + stride * 3 + 1] = 0; + + offset += stride * 4; + } + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadTint = function uploadTint(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var premultiplied = sprite._texture.baseTexture.premultipliedAlpha; + var alpha = sprite.alpha; + // we dont call extra function if alpha is 1.0, that's faster + var argb = alpha < 1.0 && premultiplied ? (0, _utils.premultiplyTint)(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); + + array[offset] = argb; + array[offset + stride] = argb; + array[offset + stride * 2] = argb; + array[offset + stride * 3] = argb; + + offset += stride * 4; + } + }; + + /** + * Destroys the ParticleRenderer. + * + */ + + + ParticleRenderer.prototype.destroy = function destroy() { + if (this.renderer.gl) { + this.renderer.gl.deleteBuffer(this.indexBuffer); + } + + _core$ObjectRenderer.prototype.destroy.call(this); + + this.shader.destroy(); + + this.indices = null; + this.tempMatrix = null; + }; + + return ParticleRenderer; +}(core.ObjectRenderer); + +exports.default = ParticleRenderer; + + +core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + +},{"../../core":65,"../../core/utils":125,"./ParticleBuffer":175,"./ParticleShader":177}],177:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../core/Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI + */ +var ParticleShader = function (_Shader) { + _inherits(ParticleShader, _Shader); + + /** + * @param {PIXI.Shader} gl - The webgl shader manager this shader works for. + */ + function ParticleShader(gl) { + _classCallCheck(this, ParticleShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'attribute vec4 aColor;', 'attribute vec2 aPositionCoord;', 'attribute float aRotation;', 'uniform mat3 projectionMatrix;', 'uniform vec4 uColor;', 'varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'void main(void){', ' float x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);', ' float y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);', ' vec2 v = vec2(x, y);', ' v = v + aPositionCoord;', ' gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = aColor * uColor;', '}'].join('\n'), + // hello + ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'uniform sampler2D uSampler;', 'void main(void){', ' vec4 color = texture2D(uSampler, vTextureCoord) * vColor;', ' gl_FragColor = color;', '}'].join('\n'))); + } + + return ParticleShader; +}(_Shader3.default); + +exports.default = ParticleShader; + +},{"../../core/Shader":44}],178:[function(require,module,exports){ +"use strict"; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + +if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + + if (x === 0 || isNaN(x)) { + return x; + } + + return x > 0 ? 1 : -1; + }; +} + +},{}],179:[function(require,module,exports){ +'use strict'; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger + +if (!Number.isInteger) { + Number.isInteger = function numberIsInteger(value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; + }; +} + +},{}],180:[function(require,module,exports){ +'use strict'; + +var _objectAssign = require('object-assign'); + +var _objectAssign2 = _interopRequireDefault(_objectAssign); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +if (!Object.assign) { + Object.assign = _objectAssign2.default; +} // References: +// https://github.com/sindresorhus/object-assign +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + +},{"object-assign":6}],181:[function(require,module,exports){ +'use strict'; + +require('./Object.assign'); + +require('./requestAnimationFrame'); + +require('./Math.sign'); + +require('./Number.isInteger'); + +if (!window.ArrayBuffer) { + window.ArrayBuffer = Array; +} + +if (!window.Float32Array) { + window.Float32Array = Array; +} + +if (!window.Uint32Array) { + window.Uint32Array = Array; +} + +if (!window.Uint16Array) { + window.Uint16Array = Array; +} + +},{"./Math.sign":178,"./Number.isInteger":179,"./Object.assign":180,"./requestAnimationFrame":182}],182:[function(require,module,exports){ +(function (global){ +'use strict'; + +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + +// Expected to be used with Browserfiy +// Browserify automatically detects the use of `global` and passes the +// correct reference of `global`, `self`, and finally `window` + +var ONE_FRAME_TIME = 16; + +// Date.now +if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; +} + +// performance.now +if (!(global.performance && global.performance.now)) { + var startTime = Date.now(); + + if (!global.performance) { + global.performance = {}; + } + + global.performance.now = function () { + return Date.now() - startTime; + }; +} + +// requestAnimationFrame +var lastTime = Date.now(); +var vendors = ['ms', 'moz', 'webkit', 'o']; + +for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { + var p = vendors[x]; + + global.requestAnimationFrame = global[p + 'RequestAnimationFrame']; + global.cancelAnimationFrame = global[p + 'CancelAnimationFrame'] || global[p + 'CancelRequestAnimationFrame']; +} + +if (!global.requestAnimationFrame) { + global.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + 'is not a function'); + } + + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + + if (delay < 0) { + delay = 0; + } + + lastTime = currentTime; + + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} + +if (!global.cancelAnimationFrame) { + global.cancelAnimationFrame = function (id) { + return clearTimeout(id); + }; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],183:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CountLimiter = require('./limiters/CountLimiter'); + +var _CountLimiter2 = _interopRequireDefault(_CountLimiter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SharedTicker = core.ticker.shared; + +/** + * Default number of uploads per frame using prepare plugin. + * + * @static + * @memberof PIXI.settings + * @name UPLOADS_PER_FRAME + * @type {number} + * @default 4 + */ +core.settings.UPLOADS_PER_FRAME = 4; + +/** + * The prepare manager provides functionality to upload content to the GPU. BasePrepare handles + * basic queuing functionality and is extended by {@link PIXI.prepare.WebGLPrepare} and {@link PIXI.prepare.CanvasPrepare} + * to provide preparation capabilities specific to their respective renderers. + * + * @example + * // Create a sprite + * const sprite = new PIXI.Sprite.fromImage('something.png'); + * + * // Load object into GPU + * app.renderer.plugins.prepare.upload(sprite, () => { + * + * //Texture(s) has been uploaded to GPU + * app.stage.addChild(sprite); + * + * }) + * + * @abstract + * @class + * @memberof PIXI.prepare + */ + +var BasePrepare = function () { + /** + * @param {PIXI.SystemRenderer} renderer - A reference to the current renderer + */ + function BasePrepare(renderer) { + var _this = this; + + _classCallCheck(this, BasePrepare); + + /** + * The limiter to be used to control how quickly items are prepared. + * @type {PIXI.prepare.CountLimiter|PIXI.prepare.TimeLimiter} + */ + this.limiter = new _CountLimiter2.default(core.settings.UPLOADS_PER_FRAME); + + /** + * Reference to the renderer. + * @type {PIXI.SystemRenderer} + * @protected + */ + this.renderer = renderer; + + /** + * The only real difference between CanvasPrepare and WebGLPrepare is what they pass + * to upload hooks. That different parameter is stored here. + * @type {PIXI.prepare.CanvasPrepare|PIXI.WebGLRenderer} + * @protected + */ + this.uploadHookHelper = null; + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + /** + * 'bound' call for prepareItems(). + * @type {Function} + * @private + */ + this.delayedTick = function () { + // unlikely, but in case we were destroyed between tick() and delayedTick() + if (!_this.queue) { + return; + } + _this.prepareItems(); + }; + + // hooks to find the correct texture + this.registerFindHook(findText); + this.registerFindHook(findTextStyle); + this.registerFindHook(findMultipleBaseTextures); + this.registerFindHook(findBaseTexture); + this.registerFindHook(findTexture); + + // upload hooks + this.registerUploadHook(drawText); + this.registerUploadHook(calculateTextStyle); + } + + /** + * Upload all the textures and graphics to the GPU. + * + * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item - + * Either the container or display object to search for items to upload, the items to upload themselves, + * or the callback function, if items have been added using `prepare.add`. + * @param {Function} [done] - Optional callback when all queued uploads have completed + */ + + + BasePrepare.prototype.upload = function upload(item, done) { + if (typeof item === 'function') { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) { + if (done) { + this.completes.push(done); + } + + if (!this.ticking) { + this.ticking = true; + SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); + } + } else if (done) { + done(); + } + }; + + /** + * Handle tick update + * + * @private + */ + + + BasePrepare.prototype.tick = function tick() { + setTimeout(this.delayedTick, 0); + }; + + /** + * Actually prepare items. This is handled outside of the tick because it will take a while + * and we do NOT want to block the current animation frame from rendering. + * + * @private + */ + + + BasePrepare.prototype.prepareItems = function prepareItems() { + this.limiter.beginFrame(); + // Upload the graphics + while (this.queue.length && this.limiter.allowedToUpload()) { + var item = this.queue[0]; + var uploaded = false; + + if (item && !item._destroyed) { + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.uploadHookHelper, item)) { + this.queue.shift(); + uploaded = true; + break; + } + } + } + + if (!uploaded) { + this.queue.shift(); + } + } + + // We're finished + if (!this.queue.length) { + this.ticking = false; + + var completes = this.completes.slice(0); + + this.completes.length = 0; + + for (var _i = 0, _len = completes.length; _i < _len; _i++) { + completes[_i](); + } + } else { + // if we are not finished, on the next rAF do this again + SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); + } + }; + + /** + * Adds hooks for finding items. + * + * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.registerFindHook = function registerFindHook(addHook) { + if (addHook) { + this.addHooks.push(addHook); + } + + return this; + }; + + /** + * Adds hooks for uploading items. + * + * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.registerUploadHook = function registerUploadHook(uploadHook) { + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + + return this; + }; + + /** + * Manually add an item to the uploading queue. + * + * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to + * add to the queue + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.add = function add(item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) { + for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { + this.add(item.children[_i2]); + } + } + + return this; + }; + + /** + * Destroys the plugin, don't use after this. + * + */ + + + BasePrepare.prototype.destroy = function destroy() { + if (this.ticking) { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.limiter = null; + this.uploadHookHelper = null; + }; + + return BasePrepare; +}(); + +/** + * Built-in hook to find multiple textures from objects like AnimatedSprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ + + +exports.default = BasePrepare; +function findMultipleBaseTextures(item, queue) { + var result = false; + + // Objects with mutliple textures + if (item && item._textures && item._textures.length) { + for (var i = 0; i < item._textures.length; i++) { + if (item._textures[i] instanceof core.Texture) { + var baseTexture = item._textures[i].baseTexture; + + if (queue.indexOf(baseTexture) === -1) { + queue.push(baseTexture); + result = true; + } + } + } + } + + return result; +} + +/** + * Built-in hook to find BaseTextures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTexture(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findTexture(item, queue) { + if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to draw PIXI.Text to its texture. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function drawText(helper, item) { + if (item instanceof core.Text) { + // updating text will return early if it is not dirty + item.updateText(true); + + return true; + } + + return false; +} + +/** + * Built-in hook to calculate a text style for a PIXI.Text object. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function calculateTextStyle(helper, item) { + if (item instanceof core.TextStyle) { + var font = item.toFontString(); + + core.TextMetrics.measureFont(font); + + return true; + } + + return false; +} + +/** + * Built-in hook to find Text objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Text object was found. + */ +function findText(item, queue) { + if (item instanceof core.Text) { + // push the text style to prepare it - this can be really expensive + if (queue.indexOf(item.style) === -1) { + queue.push(item.style); + } + // also push the text object so that we can render it (to canvas/texture) if needed + if (queue.indexOf(item) === -1) { + queue.push(item); + } + // also push the Text's texture for upload to GPU + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find TextStyle objects. + * + * @private + * @param {PIXI.TextStyle} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.TextStyle object was found. + */ +function findTextStyle(item, queue) { + if (item instanceof core.TextStyle) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +},{"../core":65,"./limiters/CountLimiter":186}],184:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CANVAS_START_SIZE = 16; + +/** + * The prepare manager provides functionality to upload content to the GPU + * This cannot be done directly for Canvas like in WebGL, but the effect can be achieved by drawing + * textures to an offline canvas. + * This draw call will force the texture to be moved onto the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ + +var CanvasPrepare = function (_BasePrepare) { + _inherits(CanvasPrepare, _BasePrepare); + + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasPrepare(renderer) { + _classCallCheck(this, CanvasPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this; + + /** + * An offline canvas to render textures to + * @type {HTMLCanvasElement} + * @private + */ + _this.canvas = document.createElement('canvas'); + _this.canvas.width = CANVAS_START_SIZE; + _this.canvas.height = CANVAS_START_SIZE; + + /** + * The context to the canvas + * @type {CanvasRenderingContext2D} + * @private + */ + _this.ctx = _this.canvas.getContext('2d'); + + // Add textures to upload + _this.registerUploadHook(uploadBaseTextures); + return _this; + } + + /** + * Destroys the plugin, don't use after this. + * + */ + + + CanvasPrepare.prototype.destroy = function destroy() { + _BasePrepare.prototype.destroy.call(this); + this.ctx = null; + this.canvas = null; + }; + + return CanvasPrepare; +}(_BasePrepare3.default); + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {*} prepare - Instance of CanvasPrepare + * @param {*} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = CanvasPrepare; +function uploadBaseTextures(prepare, item) { + if (item instanceof core.BaseTexture) { + var image = item.source; + + // Sometimes images (like atlas images) report a size of zero, causing errors on windows phone. + // So if the width or height is equal to zero then use the canvas size + // Otherwise use whatever is smaller, the image dimensions or the canvas dimensions. + var imageWidth = image.width === 0 ? prepare.canvas.width : Math.min(prepare.canvas.width, image.width); + var imageHeight = image.height === 0 ? prepare.canvas.height : Math.min(prepare.canvas.height, image.height); + + // Only a small subsections is required to be drawn to have the whole texture uploaded to the GPU + // A smaller draw can be faster. + prepare.ctx.drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, prepare.canvas.width, prepare.canvas.height); + + return true; + } + + return false; +} + +core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); + +},{"../../core":65,"../BasePrepare":183}],185:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLPrepare = require('./webgl/WebGLPrepare'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLPrepare).default; + } +}); + +var _CanvasPrepare = require('./canvas/CanvasPrepare'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasPrepare).default; + } +}); + +var _BasePrepare = require('./BasePrepare'); + +Object.defineProperty(exports, 'BasePrepare', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BasePrepare).default; + } +}); + +var _CountLimiter = require('./limiters/CountLimiter'); + +Object.defineProperty(exports, 'CountLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CountLimiter).default; + } +}); + +var _TimeLimiter = require('./limiters/TimeLimiter'); + +Object.defineProperty(exports, 'TimeLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TimeLimiter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./BasePrepare":183,"./canvas/CanvasPrepare":184,"./limiters/CountLimiter":186,"./limiters/TimeLimiter":187,"./webgl/WebGLPrepare":188}],186:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * CountLimiter limits the number of items handled by a {@link PIXI.prepare.BasePrepare} to a specified + * number of items per frame. + * + * @class + * @memberof PIXI + */ +var CountLimiter = function () { + /** + * @param {number} maxItemsPerFrame - The maximum number of items that can be prepared each frame. + */ + function CountLimiter(maxItemsPerFrame) { + _classCallCheck(this, CountLimiter); + + /** + * The maximum number of items that can be prepared each frame. + * @private + */ + this.maxItemsPerFrame = maxItemsPerFrame; + /** + * The number of items that can be prepared in the current frame. + * @type {number} + * @private + */ + this.itemsLeft = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + CountLimiter.prototype.beginFrame = function beginFrame() { + this.itemsLeft = this.maxItemsPerFrame; + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + CountLimiter.prototype.allowedToUpload = function allowedToUpload() { + return this.itemsLeft-- > 0; + }; + + return CountLimiter; +}(); + +exports.default = CountLimiter; + +},{}],187:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of milliseconds per frame. + * + * @class + * @memberof PIXI + */ +var TimeLimiter = function () { + /** + * @param {number} maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. + */ + function TimeLimiter(maxMilliseconds) { + _classCallCheck(this, TimeLimiter); + + /** + * The maximum milliseconds that can be spent preparing items each frame. + * @private + */ + this.maxMilliseconds = maxMilliseconds; + /** + * The start time of the current frame. + * @type {number} + * @private + */ + this.frameStart = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + TimeLimiter.prototype.beginFrame = function beginFrame() { + this.frameStart = Date.now(); + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + TimeLimiter.prototype.allowedToUpload = function allowedToUpload() { + return Date.now() - this.frameStart < this.maxMilliseconds; + }; + + return TimeLimiter; +}(); + +exports.default = TimeLimiter; + +},{}],188:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The prepare manager provides functionality to upload content to the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ +var WebGLPrepare = function (_BasePrepare) { + _inherits(WebGLPrepare, _BasePrepare); + + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLPrepare(renderer) { + _classCallCheck(this, WebGLPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this.renderer; + + // Add textures and graphics to upload + _this.registerFindHook(findGraphics); + _this.registerUploadHook(uploadBaseTextures); + _this.registerUploadHook(uploadGraphics); + return _this; + } + + return WebGLPrepare; +}(_BasePrepare3.default); +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = WebGLPrepare; +function uploadBaseTextures(renderer, item) { + if (item instanceof core.BaseTexture) { + // if the texture already has a GL texture, then the texture has been prepared or rendered + // before now. If the texture changed, then the changer should be calling texture.update() which + // reuploads the texture without need for preparing it again + if (!item._glTextures[renderer.CONTEXT_UID]) { + renderer.textureManager.updateTexture(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to upload PIXI.Graphics to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadGraphics(renderer, item) { + if (item instanceof core.Graphics) { + // if the item is not dirty and already has webgl data, then it got prepared or rendered + // before now and we shouldn't waste time updating it again + if (item.dirty || item.clearDirty || !item._webGL[renderer.plugins.graphics.CONTEXT_UID]) { + renderer.plugins.graphics.updateGraphics(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find graphics. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Graphics object was found. + */ +function findGraphics(item, queue) { + if (item instanceof core.Graphics) { + queue.push(item); + + return true; + } + + return false; +} + +core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); + +},{"../../core":65,"../BasePrepare":183}],189:[function(require,module,exports){ +(function (global){ +'use strict'; + +exports.__esModule = true; +exports.loader = exports.prepare = exports.particles = exports.mesh = exports.loaders = exports.interaction = exports.filters = exports.extras = exports.extract = exports.accessibility = undefined; + +var _polyfill = require('./polyfill'); + +Object.keys(_polyfill).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _polyfill[key]; + } + }); +}); + +var _core = require('./core'); + +Object.keys(_core).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _core[key]; + } + }); +}); + +var _deprecation = require('./deprecation'); + +var _deprecation2 = _interopRequireDefault(_deprecation); + +var _accessibility = require('./accessibility'); + +var accessibility = _interopRequireWildcard(_accessibility); + +var _extract = require('./extract'); + +var extract = _interopRequireWildcard(_extract); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// export core +_core.utils.mixins.performMixins(); + +/** + * Alias for {@link PIXI.loaders.shared}. + * @name loader + * @memberof PIXI + * @type {PIXI.loader.Loader} + */ + + +// handle mixins now, after all code has been added, including deprecation + + +// export libs +// import polyfills. Done as an export to make sure polyfills are imported first +var loader = loaders.shared || null; + +exports.accessibility = accessibility; +exports.extract = extract; +exports.extras = extras; +exports.filters = filters; +exports.interaction = interaction; +exports.loaders = loaders; +exports.mesh = mesh; +exports.particles = particles; +exports.prepare = prepare; +exports.loader = loader; + +// Apply the deprecations + +if (typeof _deprecation2.default === 'function') { + (0, _deprecation2.default)(exports); +} + +// Always export PixiJS globally. +global.PIXI = exports; // eslint-disable-line + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"./accessibility":42,"./core":65,"./deprecation":131,"./extract":133,"./extras":141,"./filters":153,"./interaction":159,"./loaders":162,"./mesh":171,"./particles":174,"./polyfill":181,"./prepare":185}]},{},[189])(189) +}); + + +//# sourceMappingURL=pixi.js.map diff --git a/js/pixi/4.8.2/pixi.min.js b/js/pixi/4.8.2/pixi.min.js new file mode 100644 index 0000000..162de70 --- /dev/null +++ b/js/pixi/4.8.2/pixi.min.js @@ -0,0 +1,22 @@ +/*! + * pixi.js - v4.8.2 + * Compiled Mon, 03 Sep 2018 16:07:42 UTC + * + * pixi.js is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.PIXI=t()}}(function(){var t;return function(){function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var h=new Error("Cannot find module '"+s+"'");throw h.code="MODULE_NOT_FOUND",h}var l=r[s]={exports:{}};e[s][0].call(l.exports,function(t){var r=e[s][1][t];return i(r||t)},l,l.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s0)-(t<0)},r.abs=function(t){var e=t>>31;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,(e|=r)|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,16843009*((t=(858993459&t)+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var i=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<>>8&255]<<16|i[t>>>16&255]<<8|i[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),(t=65535&(t|t>>>16))<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),(t=1023&(t|t>>>16))<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],2:[function(t,e,r){"use strict";function n(t,e,r){r=r||2;var n=e&&e.length,o=n?e[0]*r:t.length,a=i(t,0,o,r,!0),u=[];if(!a)return u;var h,l,d,f,p,v,g;if(n&&(a=c(t,e,a,r)),t.length>80*r){h=d=t[0],l=f=t[1];for(var y=r;yd&&(d=p),v>f&&(f=v);g=Math.max(d-h,f-l),g=0!==g?1/g:0}return s(a,u,r,h,l,g),u}function i(t,e,r,n,i){var o,s;if(i===A(t,e,r,n)>0)for(o=e;o=e;o-=n)s=P(o,t[o],t[o+1],s);return s&&T(s,s.next)&&(C(s),s=s.next),s}function o(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!T(n,n.next)&&0!==x(n.prev,n,n.next))n=n.next;else{if(C(n),(n=e=n.prev)===n.next)break;r=!0}}while(r||n!==e);return e}function s(t,e,r,n,i,c,d){if(t){!d&&c&&v(t,n,i,c);for(var f,p,g=t;t.prev!==t.next;)if(f=t.prev,p=t.next,c?u(t,n,i,c):a(t))e.push(f.i/r),e.push(t.i/r),e.push(p.i/r),C(t),t=p.next,g=p.next;else if((t=p)===g){d?1===d?(t=h(t,e,r),s(t,e,r,n,i,c,2)):2===d&&l(t,e,r,n,i,c):s(o(t),e,r,n,i,c,1);break}}}function a(t){var e=t.prev,r=t,n=t.next;if(x(e,r,n)>=0)return!1;for(var i=t.next.next;i!==t.prev;){if(_(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&x(i.prev,i,i.next)>=0)return!1;i=i.next}return!0}function u(t,e,r,n){var i=t.prev,o=t,s=t.next;if(x(i,o,s)>=0)return!1;for(var a=i.xo.x?i.x>s.x?i.x:s.x:o.x>s.x?o.x:s.x,l=i.y>o.y?i.y>s.y?i.y:s.y:o.y>s.y?o.y:s.y,c=y(a,u,e,r,n),d=y(h,l,e,r,n),f=t.prevZ,p=t.nextZ;f&&f.z>=c&&p&&p.z<=d;){if(f!==t.prev&&f!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,f.x,f.y)&&x(f.prev,f,f.next)>=0)return!1;if(f=f.prevZ,p!==t.prev&&p!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,p.x,p.y)&&x(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(;f&&f.z>=c;){if(f!==t.prev&&f!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,f.x,f.y)&&x(f.prev,f,f.next)>=0)return!1;f=f.prevZ}for(;p&&p.z<=d;){if(p!==t.prev&&p!==t.next&&_(i.x,i.y,o.x,o.y,s.x,s.y,p.x,p.y)&&x(p.prev,p,p.next)>=0)return!1;p=p.nextZ}return!0}function h(t,e,r){var n=t;do{var i=n.prev,o=n.next.next;!T(i,o)&&w(i,n,n.next,o)&&S(i,o)&&S(o,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(o.i/r),C(n),C(n.next),n=t=o),n=n.next}while(n!==t);return n}function l(t,e,r,n,i,a){var u=t;do{for(var h=u.next.next;h!==u.prev;){if(u.i!==h.i&&b(u,h)){var l=M(u,h);return u=o(u,u.next),l=o(l,l.next),s(u,e,r,n,i,a),void s(l,e,r,n,i,a)}h=h.next}u=u.next}while(u!==t)}function c(t,e,r,n){var s,a,u,h,l,c=[];for(s=0,a=e.length;s=n.next.y&&n.next.y!==n.y){var a=n.x+(o-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=i&&a>s){if(s=a,a===i){if(o===n.y)return n;if(o===n.next.y)return n.next}r=n.x=n.x&&n.x>=l&&i!==n.x&&_(or.x)&&S(n,t)&&(r=n,d=u),n=n.next;return r}function v(t,e,r,n){var i=t;do{null===i.z&&(i.z=y(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,g(i)}function g(t){var e,r,n,i,o,s,a,u,h=1;do{for(r=t,t=null,o=null,s=0;r;){for(s++,n=r,a=0,e=0;e0||u>0&&n;)0!==a&&(0===u||!n||r.z<=n.z)?(i=r,r=r.nextZ,a--):(i=n,n=n.nextZ,u--),o?o.nextZ=i:t=i,i.prevZ=o,o=i;r=n}o.nextZ=null,h*=2}while(s>1);return t}function y(t,e,r,n,i){return t=32767*(t-r)*i,e=32767*(e-n)*i,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1}function m(t){var e=t,r=t;do{e.x=0&&(t-s)*(n-a)-(r-s)*(e-a)>=0&&(r-s)*(o-a)-(i-s)*(n-a)>=0}function b(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!E(t,e)&&S(t,e)&&S(e,t)&&O(t,e)}function x(t,e,r){return(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function T(t,e){return t.x===e.x&&t.y===e.y}function w(t,e,r,n){return!!(T(t,e)&&T(r,n)||T(t,n)&&T(r,e))||x(t,e,r)>0!=x(t,e,n)>0&&x(r,n,t)>0!=x(r,n,e)>0}function E(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&w(r,r.next,t,e))return!0;r=r.next}while(r!==t);return!1}function S(t,e){return x(t.prev,t,t.next)<0?x(t,e,t.next)>=0&&x(t,t.prev,e)>=0:x(t,e,t.prev)<0||x(t,t.next,e)<0}function O(t,e){var r=t,n=!1,i=(t.x+e.x)/2,o=(t.y+e.y)/2;do{r.y>o!=r.next.y>o&&r.next.y!==r.y&&i<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next}while(r!==t);return n}function M(t,e){var r=new R(t.i,t.x,t.y),n=new R(e.i,e.x,e.y),i=t.next,o=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,o.next=n,n.prev=o,n}function P(t,e,r,n){var i=new R(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function C(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function R(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function A(t,e,r,n){for(var i=0,o=e,s=r-n;o0&&(n+=t[i-1].length,r.holes.push(n))}return r}},{}],3:[function(t,e,r){"use strict";function n(){}function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function o(){this._events=new n,this._eventsCount=0}var s=Object.prototype.hasOwnProperty,a="~";Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(a=!1)),o.prototype.eventNames=function(){var t,e,r=[];if(0===this._eventsCount)return r;for(e in t=this._events)s.call(t,e)&&r.push(a?e.slice(1):e);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t,e){var r=a?a+t:t,n=this._events[r];if(e)return!!n;if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i=0;n--){var i=t[n];"."===i?t.splice(n,1):".."===i?(t.splice(n,1),r++):r&&(t.splice(n,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}function n(t,e){if(t.filter)return t.filter(e);for(var r=[],n=0;n=-1&&!i;o--){var s=o>=0?arguments[o]:t.cwd();if("string"!=typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(r=s+"/"+r,i="/"===s.charAt(0))}return r=e(n(r.split("/"),function(t){return!!t}),!i).join("/"),(i?"/":"")+r||"."},r.normalize=function(t){var i=r.isAbsolute(t),o="/"===s(t,-1);return t=e(n(t.split("/"),function(t){return!!t}),!i).join("/"),t||i||(t="."),t&&o&&(t+="/"),(i?"/":"")+t},r.isAbsolute=function(t){return"/"===t.charAt(0)},r.join=function(){var t=Array.prototype.slice.call(arguments,0);return r.normalize(n(t,function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))},r.relative=function(t,e){function n(t){for(var e=0;e=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=r.resolve(t).substr(1),e=r.resolve(e).substr(1);for(var i=n(t.split("/")),o=n(e.split("/")),s=Math.min(i.length,o.length),a=s,u=0;u=t.byteLength?n.bufferSubData(this.type,e,t):n.bufferData(this.type,t,this.drawType),this.data=t},i.prototype.bind=function(){this.gl.bindBuffer(this.type,this.buffer)},i.createVertexBuffer=function(t,e,r){return new i(t,t.ARRAY_BUFFER,e,r)},i.createIndexBuffer=function(t,e,r){return new i(t,t.ELEMENT_ARRAY_BUFFER,e,r)},i.create=function(t,e,r,n){return new i(t,e,r,n)},i.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer)},e.exports=i},{}],10:[function(t,e,r){var n=t("./GLTexture"),i=function(t,e,r){this.gl=t,this.framebuffer=t.createFramebuffer(),this.stencil=null,this.texture=null,this.width=e||100,this.height=r||100};i.prototype.enableTexture=function(t){var e=this.gl;this.texture=t||new n(e),this.texture.bind(),this.bind(),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0)},i.prototype.enableStencil=function(){if(!this.stencil){var t=this.gl;this.stencil=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.stencil),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.stencil),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,this.width,this.height)}},i.prototype.clear=function(t,e,r,n){this.bind();var i=this.gl;i.clearColor(t,e,r,n),i.clear(i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT)},i.prototype.bind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer)},i.prototype.unbind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)},i.prototype.resize=function(t,e){var r=this.gl;this.width=t,this.height=e,this.texture&&this.texture.uploadData(null,t,e),this.stencil&&(r.bindRenderbuffer(r.RENDERBUFFER,this.stencil),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e))},i.prototype.destroy=function(){var t=this.gl;this.texture&&this.texture.destroy(),t.deleteFramebuffer(this.framebuffer),this.gl=null,this.stencil=null,this.texture=null},i.createRGBA=function(t,e,r,o){var s=n.fromData(t,null,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},i.createFloat32=function(t,e,r,o){var s=new n.fromData(t,o,e,r);s.enableNearestScaling(),s.enableWrapClamp();var a=new i(t,e,r);return a.enableTexture(s),a.unbind(),a},e.exports=i},{"./GLTexture":12}],11:[function(t,e,r){var n=t("./shader/compileProgram"),i=t("./shader/extractAttributes"),o=t("./shader/extractUniforms"),s=t("./shader/setPrecision"),a=t("./shader/generateUniformAccessObject"),u=function(t,e,r,u,h){this.gl=t,u&&(e=s(e,u),r=s(r,u)),this.program=n(t,e,r,h),this.attributes=i(t,this.program),this.uniformData=o(t,this.program),this.uniforms=a(t,this.uniformData)};u.prototype.bind=function(){return this.gl.useProgram(this.program),this},u.prototype.destroy=function(){this.attributes=null,this.uniformData=null,this.uniforms=null,this.gl.deleteProgram(this.program)},e.exports=u},{"./shader/compileProgram":17,"./shader/extractAttributes":19,"./shader/extractUniforms":20,"./shader/generateUniformAccessObject":21,"./shader/setPrecision":25}],12:[function(t,e,r){var n=function(t,e,r,n,i){this.gl=t,this.texture=t.createTexture(),this.mipmap=!1,this.premultiplyAlpha=!1,this.width=e||-1,this.height=r||-1,this.format=n||t.RGBA,this.type=i||t.UNSIGNED_BYTE};n.prototype.upload=function(t){this.bind();var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var r=t.videoWidth||t.width,n=t.videoHeight||t.height;n!==this.height||r!==this.width?e.texImage2D(e.TEXTURE_2D,0,this.format,this.format,this.type,t):e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.format,this.type,t),this.width=r,this.height=n};var i=!1;n.prototype.uploadData=function(t,e,r){this.bind();var n=this.gl;if(t instanceof Float32Array){if(!i){if(!n.getExtension("OES_texture_float"))throw new Error("floating point textures not available");i=!0}this.type=n.FLOAT}else this.type=this.type||n.UNSIGNED_BYTE;n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),e!==this.width||r!==this.height?n.texImage2D(n.TEXTURE_2D,0,this.format,e,r,0,this.format,this.type,t||null):n.texSubImage2D(n.TEXTURE_2D,0,0,0,e,r,this.format,this.type,t||null),this.width=e,this.height=r},n.prototype.bind=function(t){var e=this.gl;void 0!==t&&e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,this.texture)},n.prototype.unbind=function(){var t=this.gl;t.bindTexture(t.TEXTURE_2D,null)},n.prototype.minFilter=function(t){var e=this.gl;this.bind(),this.mipmap?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.magFilter=function(t){var e=this.gl;this.bind(),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t?e.LINEAR:e.NEAREST)},n.prototype.enableMipmap=function(){var t=this.gl;this.bind(),this.mipmap=!0,t.generateMipmap(t.TEXTURE_2D)},n.prototype.enableLinearScaling=function(){this.minFilter(!0),this.magFilter(!0)},n.prototype.enableNearestScaling=function(){this.minFilter(!1),this.magFilter(!1)},n.prototype.enableWrapClamp=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)},n.prototype.enableWrapRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT)},n.prototype.enableWrapMirrorRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.MIRRORED_REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.MIRRORED_REPEAT)},n.prototype.destroy=function(){this.gl.deleteTexture(this.texture)},n.fromSource=function(t,e,r){var i=new n(t);return i.premultiplyAlpha=r||!1,i.upload(e),i},n.fromData=function(t,e,r,i){var o=new n(t);return o.uploadData(e,r,i),o},e.exports=n},{}],13:[function(t,e,r){function n(t,e){if(this.nativeVaoExtension=null,n.FORCE_NATIVE||(this.nativeVaoExtension=t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object")),this.nativeState=e,this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var r=t.getParameter(t.MAX_VERTEX_ATTRIBS);this.nativeState={tempAttribState:new Array(r),attribState:new Array(r)}}this.gl=t,this.attributes=[],this.indexBuffer=null,this.dirty=!1}var i=t("./setVertexAttribArrays");n.prototype.constructor=n,e.exports=n,n.FORCE_NATIVE=!1,n.prototype.bind=function(){if(this.nativeVao){if(this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao),this.dirty)return this.dirty=!1,this.activate(),this;this.indexBuffer&&this.indexBuffer.bind()}else this.activate();return this},n.prototype.unbind=function(){return this.nativeVao&&this.nativeVaoExtension.bindVertexArrayOES(null),this},n.prototype.activate=function(){for(var t=this.gl,e=null,r=0;r1)for(var r=1;r1&&(n=r[0]+"@",t=r[1]),t=t.replace(D,"."),n+s(t.split("."),e).join(".")}function u(t){for(var e,r,n=[],i=0,o=t.length;i=55296&&e<=56319&&i65535&&(t-=65536,e+=F(t>>>10&1023|55296),t=56320|1023&t),e+=F(t)}).join("")}function l(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:w}function c(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function d(t,e,r){var n=0;for(t=r?B(t/M):t>>1,t+=B(t/e);t>N*S>>1;n+=w)t=B(t/N);return B(n+(N+1)*t/(t+O))}function f(t){var e,r,n,i,s,a,u,c,f,p,v=[],g=t.length,y=0,m=C,_=P;for(r=t.lastIndexOf(R),r<0&&(r=0),n=0;n=128&&o("not-basic"),v.push(t.charCodeAt(n));for(i=r>0?r+1:0;i=g&&o("invalid-input"),c=l(t.charCodeAt(i++)),(c>=w||c>B((T-y)/a))&&o("overflow"),y+=c*a,f=u<=_?E:u>=_+S?S:u-_,!(cB(T/p)&&o("overflow"),a*=p;e=v.length+1,_=d(y-s,e,0==s),B(y/e)>T-m&&o("overflow"),m+=B(y/e),y%=e,v.splice(y++,0,m)}return h(v)}function p(t){var e,r,n,i,s,a,h,l,f,p,v,g,y,m,_,b=[];for(t=u(t),g=t.length,e=C,r=0,s=P,a=0;a=e&&vB((T-r)/y)&&o("overflow"),r+=(h-e)*y,e=h,a=0;aT&&o("overflow"),v==e){for(l=r,f=w;p=f<=s?E:f>=s+S?S:f-s,!(l= 0x80 (not a basic code point)","invalid-input":"Invalid input"},N=w-E,B=Math.floor,F=String.fromCharCode;if(b={version:"1.4.1",ucs2:{decode:u,encode:h},decode:f,encode:p,toASCII:g,toUnicode:v},"function"==typeof t&&"object"==typeof t.amd&&t.amd)t("punycode",function(){return b});else if(y&&m)if(r.exports==y)m.exports=b;else for(x in b)b.hasOwnProperty(x)&&(y[x]=b[x]);else i.punycode=b}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],28:[function(t,e,r){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}e.exports=function(t,e,r,o){e=e||"&",r=r||"=";var s={};if("string"!=typeof t||0===t.length)return s;var a=/\+/g;t=t.split(e);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var h=t.length;u>0&&h>u&&(h=u);for(var l=0;l=0?(c=v.substr(0,g),d=v.substr(g+1)):(c=v,d=""),f=decodeURIComponent(c),p=decodeURIComponent(d),n(s,f)?i(s[f])?s[f].push(p):s[f]=[s[f],p]:s[f]=p}return s};var i=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},{}],29:[function(t,e,r){"use strict";function n(t,e){if(t.map)return t.map(e);for(var r=[],n=0;n=i||0===r)){r=e+r>i?i-e:r;var o=i-r;for(n=e;n0&&void 0!==arguments[0]?arguments[0]:"",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10;i(this,t),this.baseUrl=r,this.progress=0,this.loading=!1,this.defaultQueryString="",this._beforeMiddleware=[],this._afterMiddleware=[],this._resourcesParsing=[],this._boundLoadResource=function(t,r){return e._loadResource(t,r)},this._queue=d.queue(this._boundLoadResource,n),this._queue.pause(),this.resources={},this.onProgress=new u.default,this.onError=new u.default,this.onLoad=new u.default,this.onStart=new u.default,this.onComplete=new u.default}return t.prototype.add=function(t,e,r,n){if(Array.isArray(t)){for(var i=0;i0||e.responseType===t.XHR_RESPONSE_TYPE.BUFFER)?n=200:1223===n&&(n=204),2!=(n/100|0))return void this.abort("["+e.status+"] "+e.statusText+": "+e.responseURL);if(this.xhrType===t.XHR_RESPONSE_TYPE.TEXT)this.data=r,this.type=t.TYPE.TEXT;else if(this.xhrType===t.XHR_RESPONSE_TYPE.JSON)try{this.data=JSON.parse(r),this.type=t.TYPE.JSON}catch(t){return void this.abort("Error trying to parse loaded json: "+t)}else if(this.xhrType===t.XHR_RESPONSE_TYPE.DOCUMENT)try{if(window.DOMParser){var i=new DOMParser;this.data=i.parseFromString(r,"text/xml")}else{var o=document.createElement("div");o.innerHTML=r,this.data=o}this.type=t.TYPE.XML}catch(t){return void this.abort("Error trying to parse loaded xml: "+t)}else this.data=e.response||r;this.complete()},t.prototype._determineCrossOrigin=function(t,e){if(0===t.indexOf("data:"))return"";e=e||window.location,p||(p=document.createElement("a")),p.href=t,t=(0,l.default)(p.href,{strictMode:!0});var r=!t.port&&""===e.port||t.port===e.port,n=t.protocol?t.protocol+":":"";return t.host===e.hostname&&r&&n===e.protocol?"":"anonymous"},t.prototype._determineXhrType=function(){return t._xhrTypeMap[this.extension]||t.XHR_RESPONSE_TYPE.TEXT},t.prototype._determineLoadType=function(){return t._loadTypeMap[this.extension]||t.LOAD_TYPE.XHR},t.prototype._getExtension=function(){var t=this.url,e="";if(this.isDataUrl){var r=t.indexOf("/");e=t.substring(r+1,t.indexOf(";",r))}else{var n=t.indexOf("?"),i=t.indexOf("#"),o=Math.min(n>-1?n:t.length,i>-1?i:t.length);t=t.substring(0,o),e=t.substring(t.lastIndexOf(".")+1)}return e.toLowerCase()},t.prototype._getMimeFromXhrType=function(e){switch(e){case t.XHR_RESPONSE_TYPE.BUFFER:return"application/octet-binary";case t.XHR_RESPONSE_TYPE.BLOB:return"application/blob";case t.XHR_RESPONSE_TYPE.DOCUMENT:return"application/xml";case t.XHR_RESPONSE_TYPE.JSON:return"application/json";case t.XHR_RESPONSE_TYPE.DEFAULT:case t.XHR_RESPONSE_TYPE.TEXT:default:return"text/plain"}},u(t,[{key:"isDataUrl",get:function(){return this._hasFlag(t.STATUS_FLAGS.DATA_URL)}},{key:"isComplete",get:function(){return this._hasFlag(t.STATUS_FLAGS.COMPLETE)}},{key:"isLoading",get:function(){return this._hasFlag(t.STATUS_FLAGS.LOADING)}}]),t}();r.default=v,v.STATUS_FLAGS={NONE:0,DATA_URL:1,COMPLETE:2,LOADING:4},v.TYPE={UNKNOWN:0,JSON:1,XML:2,IMAGE:3,AUDIO:4,VIDEO:5,TEXT:6},v.LOAD_TYPE={XHR:1,IMAGE:2,AUDIO:3,VIDEO:4},v.XHR_RESPONSE_TYPE={DEFAULT:"text",BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"},v._loadTypeMap={gif:v.LOAD_TYPE.IMAGE,png:v.LOAD_TYPE.IMAGE,bmp:v.LOAD_TYPE.IMAGE,jpg:v.LOAD_TYPE.IMAGE,jpeg:v.LOAD_TYPE.IMAGE,tif:v.LOAD_TYPE.IMAGE,tiff:v.LOAD_TYPE.IMAGE,webp:v.LOAD_TYPE.IMAGE,tga:v.LOAD_TYPE.IMAGE,svg:v.LOAD_TYPE.IMAGE,"svg+xml":v.LOAD_TYPE.IMAGE,mp3:v.LOAD_TYPE.AUDIO,ogg:v.LOAD_TYPE.AUDIO,wav:v.LOAD_TYPE.AUDIO,mp4:v.LOAD_TYPE.VIDEO,webm:v.LOAD_TYPE.VIDEO},v._xhrTypeMap={xhtml:v.XHR_RESPONSE_TYPE.DOCUMENT,html:v.XHR_RESPONSE_TYPE.DOCUMENT,htm:v.XHR_RESPONSE_TYPE.DOCUMENT,xml:v.XHR_RESPONSE_TYPE.DOCUMENT,tmx:v.XHR_RESPONSE_TYPE.DOCUMENT,svg:v.XHR_RESPONSE_TYPE.DOCUMENT,tsx:v.XHR_RESPONSE_TYPE.DOCUMENT,gif:v.XHR_RESPONSE_TYPE.BLOB,png:v.XHR_RESPONSE_TYPE.BLOB,bmp:v.XHR_RESPONSE_TYPE.BLOB,jpg:v.XHR_RESPONSE_TYPE.BLOB,jpeg:v.XHR_RESPONSE_TYPE.BLOB,tif:v.XHR_RESPONSE_TYPE.BLOB,tiff:v.XHR_RESPONSE_TYPE.BLOB,webp:v.XHR_RESPONSE_TYPE.BLOB,tga:v.XHR_RESPONSE_TYPE.BLOB,json:v.XHR_RESPONSE_TYPE.JSON,text:v.XHR_RESPONSE_TYPE.TEXT,txt:v.XHR_RESPONSE_TYPE.TEXT,ttf:v.XHR_RESPONSE_TYPE.BUFFER,otf:v.XHR_RESPONSE_TYPE.BUFFER},v.EMPTY_GIF="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="},{"mini-signals":5,"parse-uri":7}],34:[function(t,e,r){"use strict";function n(){}function i(t,e,r,n){var i=0,o=t.length;!function s(a){if(a||i===o)return void(r&&r(a));n?setTimeout(function(){e(t[i++],s)},1):e(t[i++],s)}()}function o(t){return function(){if(null===t)throw new Error("Callback was already called.");var e=t;t=null,e.apply(this,arguments)}}function s(t,e){function r(t,e,r){if(null!=r&&"function"!=typeof r)throw new Error("task callback must be a function");if(a.started=!0,null==t&&a.idle())return void setTimeout(function(){return a.drain()},1);var i={data:t,callback:"function"==typeof r?r:n};e?a._tasks.unshift(i):a._tasks.push(i),setTimeout(function(){return a.process()},1)}function i(t){return function(){s-=1,t.callback.apply(t,arguments),null!=arguments[0]&&a.error(arguments[0],t.data),s<=a.concurrency-a.buffer&&a.unsaturated(),a.idle()&&a.drain(),a.process()}}if(null==e)e=1;else if(0===e)throw new Error("Concurrency must not be zero");var s=0,a={_tasks:[],concurrency:e,saturated:n,unsaturated:n,buffer:e/4,empty:n,drain:n,error:n,started:!1,paused:!1,push:function(t,e){r(t,!1,e)},kill:function(){s=0,a.drain=n,a.started=!1,a._tasks=[]},unshift:function(t,e){r(t,!0,e)},process:function(){for(;!a.paused&&s>2,o[1]=(3&n[0])<<4|n[1]>>4,o[2]=(15&n[1])<<2|n[2]>>6,o[3]=63&n[2];switch(r-(t.length-1)){case 2:o[3]=64,o[2]=64;break;case 1:o[3]=64}for(var a=0;a",'"',"`"," ","\r","\n","\t"],p=["{","}","|","\\","^","`"].concat(f),v=["'"].concat(p),g=["%","/","?",";","#"].concat(v),y=["/","?","#"],m=/^[+a-z0-9A-Z_-]{0,63}$/,_=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,b={javascript:!0,"javascript:":!0},x={javascript:!0,"javascript:":!0},T={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},w=t("querystring");n.prototype.parse=function(t,e,r){if(!h.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var n=t.indexOf("?"),i=-1!==n&&n127?L+="x":L+=D[N];if(!L.match(m)){var F=A.slice(0,O),k=A.slice(O+1),j=D.match(_);j&&(F.push(j[1]),k.unshift(j[2])),k.length&&(a="/"+k.join(".")+a),this.hostname=F.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),R||(this.hostname=u.toASCII(this.hostname));var U=this.port?":"+this.port:"",X=this.hostname||"";this.host=X+U,this.href+=this.host,R&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==a[0]&&(a="/"+a))}if(!b[p])for(var O=0,I=v.length;O0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return r.search=t.search,r.query=t.query,h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!w.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var O=w.slice(-1)[0],M=(r.host||t.host||w.length>1)&&("."===O||".."===O)||""===O,P=0,C=w.length;C>=0;C--)O=w[C],"."===O?w.splice(C,1):".."===O?(w.splice(C,1),P++):P&&(w.splice(C,1),P--);if(!_&&!b)for(;P--;P)w.unshift("..");!_||""===w[0]||w[0]&&"/"===w[0].charAt(0)||w.unshift(""),M&&"/"!==w.join("/").substr(-1)&&w.push("");var R=""===w[0]||w[0]&&"/"===w[0].charAt(0);if(E){r.hostname=r.host=R?"":w.length?w.shift():"";var S=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@");S&&(r.auth=S.shift(),r.host=r.hostname=S.shift())}return _=_||r.host&&w.length,_&&!R&&w.unshift(""),w.length?r.pathname=w.join("/"):(r.pathname=null,r.path=null),h.isNull(r.pathname)&&h.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},n.prototype.parseHost=function(){var t=this.host,e=c.exec(t);e&&(e=e[0],":"!==e&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)}},{"./util":39,punycode:27,querystring:30}],39:[function(t,e,r){"use strict";e.exports={isString:function(t){return"string"==typeof t},isObject:function(t){return"object"==typeof t&&null!==t},isNull:function(t){return null===t},isNullOrUndefined:function(t){return null==t}}},{}],40:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../core"),s=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(o),a=t("ismobilejs"),u=n(a),h=t("./accessibleTarget"),l=n(h);s.utils.mixins.delayMixin(s.DisplayObject.prototype,l.default);var c=100,d=0,f=0,p=2,v=function(){function t(e){i(this,t),!u.default.tablet&&!u.default.phone||navigator.isCocoonJS||this.createTouchHook();var r=document.createElement("div");r.style.width=c+"px",r.style.height=c+"px",r.style.position="absolute",r.style.top=d+"px",r.style.left=f+"px",r.style.zIndex=p,this.div=r,this.pool=[],this.renderId=0,this.debug=!1,this.renderer=e,this.children=[],this._onKeyDown=this._onKeyDown.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this.isActive=!1,this.isMobileAccessabillity=!1,window.addEventListener("keydown",this._onKeyDown,!1)}return t.prototype.createTouchHook=function(){var t=this,e=document.createElement("button");e.style.width="1px",e.style.height="1px",e.style.position="absolute",e.style.top="-1000px",e.style.left="-1000px",e.style.zIndex=2,e.style.backgroundColor="#FF0000",e.title="HOOK DIV",e.addEventListener("focus",function(){t.isMobileAccessabillity=!0,t.activate(),document.body.removeChild(e)}),document.body.appendChild(e)},t.prototype.activate=function(){this.isActive||(this.isActive=!0,window.document.addEventListener("mousemove",this._onMouseMove,!0),window.removeEventListener("keydown",this._onKeyDown,!1),this.renderer.on("postrender",this.update,this),this.renderer.view.parentNode&&this.renderer.view.parentNode.appendChild(this.div))},t.prototype.deactivate=function(){this.isActive&&!this.isMobileAccessabillity&&(this.isActive=!1,window.document.removeEventListener("mousemove",this._onMouseMove,!0),window.addEventListener("keydown",this._onKeyDown,!1),this.renderer.off("postrender",this.update),this.div.parentNode&&this.div.parentNode.removeChild(this.div))},t.prototype.updateAccessibleObjects=function(t){if(t.visible){t.accessible&&t.interactive&&(t._accessibleActive||this.addChild(t),t.renderId=this.renderId);for(var e=t.children,r=0;rthis.renderer.width&&(t.width=this.renderer.width-t.x),t.y+t.height>this.renderer.height&&(t.height=this.renderer.height-t.y)},t.prototype.addChild=function(t){var e=this.pool.pop();e||(e=document.createElement("button"),e.style.width=c+"px",e.style.height=c+"px",e.style.backgroundColor=this.debug?"rgba(255,0,0,0.5)":"transparent",e.style.position="absolute",e.style.zIndex=p,e.style.borderStyle="none",navigator.userAgent.toLowerCase().indexOf("chrome")>-1?e.setAttribute("aria-live","off"):e.setAttribute("aria-live","polite"),navigator.userAgent.match(/rv:.*Gecko\//)?e.setAttribute("aria-relevant","additions"):e.setAttribute("aria-relevant","text"),e.addEventListener("click",this._onClick.bind(this)),e.addEventListener("focus",this._onFocus.bind(this)),e.addEventListener("focusout",this._onFocusOut.bind(this))),t.accessibleTitle&&null!==t.accessibleTitle?e.title=t.accessibleTitle:t.accessibleHint&&null!==t.accessibleHint||(e.title="displayObject "+t.tabIndex),t.accessibleHint&&null!==t.accessibleHint&&e.setAttribute("aria-label",t.accessibleHint),t._accessibleActive=!0,t._accessibleDiv=e,e.displayObject=t,this.children.push(t),this.div.appendChild(t._accessibleDiv),t._accessibleDiv.tabIndex=t.tabIndex},t.prototype._onClick=function(t){var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"click",e.eventData)},t.prototype._onFocus=function(t){t.target.getAttribute("aria-live","off")||t.target.setAttribute("aria-live","assertive");var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseover",e.eventData)},t.prototype._onFocusOut=function(t){t.target.getAttribute("aria-live","off")||t.target.setAttribute("aria-live","polite");var e=this.renderer.plugins.interaction;e.dispatchEvent(t.target.displayObject,"mouseout",e.eventData)},t.prototype._onKeyDown=function(t){9===t.keyCode&&this.activate()},t.prototype._onMouseMove=function(t){0===t.movementX&&0===t.movementY||this.deactivate()},t.prototype.destroy=function(){this.div=null;for(var t=0;t]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i,r.SHAPES={POLY:0,RECT:1,CIRC:2,ELIP:3,RREC:4},r.PRECISION={LOW:"lowp",MEDIUM:"mediump",HIGH:"highp"},r.TRANSFORM_MODE={STATIC:0,DYNAMIC:1},r.TEXT_GRADIENT={LINEAR_VERTICAL:0,LINEAR_HORIZONTAL:1},r.UPDATE_PRIORITY={INTERACTION:50,HIGH:25,NORMAL:0,LOW:-25,UTILITY:-50}},{}],47:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../math"),o=function(){function t(){n(this,t),this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.rect=null}return t.prototype.isEmpty=function(){return this.minX>this.maxX||this.minY>this.maxY},t.prototype.clear=function(){this.updateID++,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0},t.prototype.getRectangle=function(t){return this.minX>this.maxX||this.minY>this.maxY?i.Rectangle.EMPTY:(t=t||new i.Rectangle(0,0,1,1),t.x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)},t.prototype.addPoint=function(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)},t.prototype.addQuad=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY,o=t[0],s=t[1];e=on?o:n,i=s>i?s:i,o=t[2],s=t[3],e=on?o:n,i=s>i?s:i,o=t[4],s=t[5],e=on?o:n,i=s>i?s:i,o=t[6],s=t[7],e=on?o:n,i=s>i?s:i,this.minX=e,this.minY=r,this.maxX=n,this.maxY=i},t.prototype.addFrame=function(t,e,r,n,i){var o=t.worldTransform,s=o.a,a=o.b,u=o.c,h=o.d,l=o.tx,c=o.ty,d=this.minX,f=this.minY,p=this.maxX,v=this.maxY,g=s*e+u*r+l,y=a*e+h*r+c;d=gp?g:p,v=y>v?y:v,g=s*n+u*r+l,y=a*n+h*r+c,d=gp?g:p,v=y>v?y:v,g=s*e+u*i+l,y=a*e+h*i+c,d=gp?g:p,v=y>v?y:v,g=s*n+u*i+l,y=a*n+h*i+c,d=gp?g:p,v=y>v?y:v,this.minX=d,this.minY=f,this.maxX=p,this.maxY=v},t.prototype.addVertices=function(t,e,r,n){for(var i=t.worldTransform,o=i.a,s=i.b,a=i.c,u=i.d,h=i.tx,l=i.ty,c=this.minX,d=this.minY,f=this.maxX,p=this.maxY,v=r;vf?m:f,p=_>p?_:p}this.minX=c,this.minY=d,this.maxX=f,this.maxY=p},t.prototype.addBounds=function(t){var e=this.minX,r=this.minY,n=this.maxX,i=this.maxY;this.minX=t.minXn?t.maxX:n,this.maxY=t.maxY>i?t.maxY:i},t.prototype.addBoundsMask=function(t,e){var r=t.minX>e.minX?t.minX:e.minX,n=t.minY>e.minY?t.minY:e.minY,i=t.maxXu?i:u,this.maxY=o>h?o:h}},t.prototype.addBoundsArea=function(t,e){var r=t.minX>e.x?t.minX:e.x,n=t.minY>e.y?t.minY:e.y,i=t.maxXu?i:u,this.maxY=o>h?o:h}},t}();r.default=o},{"../math":70}],48:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r1)for(var r=0;rthis.children.length)throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length);return t.parent&&t.parent.removeChild(t),t.parent=this,t.transform._parentID=-1,this.children.splice(e,0,t),this._boundsID++,this.onChildrenChange(e),t.emit("added",this),t},e.prototype.swapChildren=function(t,e){if(t!==e){var r=this.getChildIndex(t),n=this.getChildIndex(e);this.children[r]=e,this.children[n]=t,this.onChildrenChange(r=this.children.length)throw new Error("The index "+e+" supplied is out of bounds "+this.children.length);var r=this.getChildIndex(t);(0,a.removeItems)(this.children,r,1),this.children.splice(e,0,t),this.onChildrenChange(e)},e.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Index ("+t+") does not exist.");return this.children[t]},e.prototype.removeChild=function(t){var e=arguments.length;if(e>1)for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=t,n="number"==typeof e?e:this.children.length,i=n-r,o=void 0;if(i>0&&i<=n){o=this.children.splice(r,i);for(var s=0;s2&&void 0!==arguments[2]&&arguments[2]||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)},e.prototype.toLocal=function(t,e,r,n){return e&&(t=e.toGlobal(t,r,n)),n||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,r)},e.prototype.renderWebGL=function(t){},e.prototype.renderCanvas=function(t){},e.prototype.setParent=function(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t},e.prototype.setTransform=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0,u=arguments.length>8&&void 0!==arguments[8]?arguments[8]:0;return this.position.x=t,this.position.y=e,this.scale.x=r||1,this.scale.y=n||1,this.rotation=i,this.skew.x=o,this.skew.y=s,this.pivot.x=a,this.pivot.y=u,this},e.prototype.destroy=function(){this.removeAllListeners(),this.parent&&this.parent.removeChild(this),this.transform=null,this.parent=null,this._bounds=null,this._currentBounds=null,this._mask=null,this.filterArea=null,this.interactive=!1,this.interactiveChildren=!1,this._destroyed=!0},a(e,[{key:"_tempDisplayObjectParent",get:function(){return null===this.tempDisplayObjectParent&&(this.tempDisplayObjectParent=new e),this.tempDisplayObjectParent}},{key:"x",get:function(){return this.position.x},set:function(t){this.transform.position.x=t}},{key:"y",get:function(){return this.position.y},set:function(t){this.transform.position.y=t}},{key:"worldTransform",get:function(){return this.transform.worldTransform}},{key:"localTransform",get:function(){return this.transform.localTransform}},{key:"position",get:function(){return this.transform.position},set:function(t){this.transform.position.copy(t)}},{key:"scale",get:function(){return this.transform.scale},set:function(t){this.transform.scale.copy(t)}},{key:"pivot",get:function(){return this.transform.pivot},set:function(t){this.transform.pivot.copy(t)}},{key:"skew",get:function(){return this.transform.skew},set:function(t){this.transform.skew.copy(t)}},{key:"rotation",get:function(){return this.transform.rotation},set:function(t){this.transform.rotation=t}},{key:"worldVisible",get:function(){var t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}},{key:"mask",get:function(){return this._mask},set:function(t){this._mask&&(this._mask.renderable=!0,this._mask.isMask=!1),this._mask=t,this._mask&&(this._mask.renderable=!1,this._mask.isMask=!0)}},{key:"filters",get:function(){return this._filters&&this._filters.slice()},set:function(t){this._filters=t&&t.slice()}}]),e}(h.default);r.default=b,b.prototype.displayObjectUpdateTransform=b.prototype.updateTransform},{"../const":46,"../math":70,"../settings":101,"./Bounds":47,"./Transform":50,"./TransformStatic":52,eventemitter3:3}],50:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]&&arguments[0];i(this,e);var n=o(this,t.call(this));return n.fillAlpha=1,n.lineWidth=0,n.nativeLines=r,n.lineColor=0,n.lineAlignment=.5,n.graphicsData=[],n.tint=16777215,n._prevTint=16777215,n.blendMode=_.BLEND_MODES.NORMAL,n.currentPath=null,n._webGL={},n.isMask=!1,n.boundsPadding=0,n._localBounds=new x.default,n.dirty=0,n.fastRectDirty=-1,n.clearDirty=0,n.boundsDirty=-1,n.cachedSpriteDirty=!1,n._spriteRect=null,n._fastRect=!1,n._prevRectTint=null,n._prevRectFillColor=null,n}return s(e,t),e.prototype.clone=function(){var t=new e;t.renderable=this.renderable,t.fillAlpha=this.fillAlpha,t.lineWidth=this.lineWidth,t.lineColor=this.lineColor,t.lineAlignment=this.lineAlignment,t.tint=this.tint,t.blendMode=this.blendMode,t.isMask=this.isMask,t.boundsPadding=this.boundsPadding,t.dirty=0,t.cachedSpriteDirty=this.cachedSpriteDirty;for(var r=0;re.CURVES.maxSegments&&(r=e.CURVES.maxSegments),r},e.prototype.lineStyle=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:.5;if(this.lineWidth=t,this.lineColor=e,this.lineAlpha=r,this.lineAlignment=n,this.currentPath)if(this.currentPath.shape.points.length){var i=new y.Polygon(this.currentPath.shape.points.slice(-2));i.closed=!1,this.drawShape(i)}else this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha,this.currentPath.lineAlignment=this.lineAlignment;return this},e.prototype.moveTo=function(t,e){var r=new y.Polygon([t,e]);return r.closed=!1,this.drawShape(r),this},e.prototype.lineTo=function(t,e){var r=this.currentPath.shape.points,n=r[r.length-2],i=r[r.length-1];return n===t&&i===e||(r.push(t,e),this.dirty++),this},e.prototype.quadraticCurveTo=function(t,r,n,i){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var o=this.currentPath.shape.points,s=0,a=0;0===o.length&&this.moveTo(0,0);for(var u=o[o.length-2],h=o[o.length-1],l=e.CURVES.adaptive?this._segmentsCount(this._quadraticCurveLength(u,h,t,r,n,i)):20,c=1;c<=l;++c){var d=c/l;s=u+(t-u)*d,a=h+(r-h)*d,o.push(s+(t+(n-t)*d-s)*d,a+(r+(i-r)*d-a)*d)}return this.dirty++,this},e.prototype.bezierCurveTo=function(t,r,n,i,o,s){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var a=this.currentPath.shape.points,u=a[a.length-2],h=a[a.length-1];a.length-=2;var l=e.CURVES.adaptive?this._segmentsCount(this._bezierCurveLength(u,h,t,r,n,i,o,s)):20;return(0,w.default)(u,h,t,r,n,i,o,s,l,a),this.dirty++,this},e.prototype.arcTo=function(t,e,r,n,i){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(t,e):this.moveTo(t,e);var o=this.currentPath.shape.points,s=o[o.length-2],a=o[o.length-1],u=a-e,h=s-t,l=n-e,c=r-t,d=Math.abs(u*c-h*l);if(d<1e-8||0===i)o[o.length-2]===t&&o[o.length-1]===e||o.push(t,e);else{var f=u*u+h*h,p=l*l+c*c,v=u*l+h*c,g=i*Math.sqrt(f)/d,y=i*Math.sqrt(p)/d,m=g*v/f,_=y*v/p,b=g*c+y*h,x=g*l+y*u,T=h*(y+m),w=u*(y+m),E=c*(g+_),S=l*(g+_),O=Math.atan2(w-x,T-b),M=Math.atan2(S-x,E-b);this.arc(b+t,x+e,i,O,M,h*l>c*u)}return this.dirty++,this},e.prototype.arc=function(t,r,n,i,o){var s=arguments.length>5&&void 0!==arguments[5]&&arguments[5];if(i===o)return this;!s&&o<=i?o+=_.PI_2:s&&i<=o&&(i+=_.PI_2);var a=o-i,u=e.CURVES.adaptive?this._segmentsCount(Math.abs(a)*n):40*Math.ceil(Math.abs(a)/_.PI_2);if(0===a)return this;var h=t+Math.cos(i)*n,l=r+Math.sin(i)*n,c=this.currentPath?this.currentPath.shape.points:null;if(c){var d=Math.abs(c[c.length-2]-h),f=Math.abs(c[c.length-1]-l);d<.001&&f<.001||c.push(h,l)}else this.moveTo(h,l),c=this.currentPath.shape.points;for(var p=a/(2*u),v=2*p,g=Math.cos(p),y=Math.sin(p),m=u-1,b=m%1/m,x=0;x<=m;++x){var T=x+b*x,w=p+i+v*T,E=Math.cos(w),S=-Math.sin(w);c.push((g*E+y*S)*n+t,(g*-S+y*E)*n+r)}return this.dirty++,this},e.prototype.beginFill=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this.filling=!0,this.fillColor=t,this.fillAlpha=e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},e.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},e.prototype.drawRect=function(t,e,r,n){return this.drawShape(new y.Rectangle(t,e,r,n)),this},e.prototype.drawRoundedRect=function(t,e,r,n,i){return this.drawShape(new y.RoundedRectangle(t,e,r,n,i)),this},e.prototype.drawCircle=function(t,e,r){return this.drawShape(new y.Circle(t,e,r)),this},e.prototype.drawEllipse=function(t,e,r,n){return this.drawShape(new y.Ellipse(t,e,r,n)),this},e.prototype.drawPolygon=function(t){var e=t,r=!0;if(e instanceof y.Polygon&&(r=e.closed,e=e.points),!Array.isArray(e)){e=new Array(arguments.length);for(var n=0;n5&&void 0!==arguments[5]?arguments[5]:0;i=i||n/2;for(var s=-1*Math.PI/2+o,a=2*r,u=_.PI_2/a,h=[],l=0;l0)&&(this.lineWidth=0,this.lineAlignment=.5,this.filling=!1,this.boundsDirty=-1,this.canvasTintDirty=-1,this.dirty++,this.clearDirty++,this.graphicsData.length=0),this.currentPath=null,this._spriteRect=null,this},e.prototype.isFastRect=function(){return 1===this.graphicsData.length&&this.graphicsData[0].shape.type===_.SHAPES.RECT&&!this.graphicsData[0].lineWidth},e.prototype._renderWebGL=function(t){this.dirty!==this.fastRectDirty&&(this.fastRectDirty=this.dirty,this._fastRect=this.isFastRect()),this._fastRect?this._renderSpriteRect(t):(t.setObjectRenderer(t.plugins.graphics),t.plugins.graphics.render(this))},e.prototype._renderSpriteRect=function(t){var e=this.graphicsData[0].shape;this._spriteRect||(this._spriteRect=new g.default(new d.default(d.default.WHITE)));var r=this._spriteRect,n=this.graphicsData[0].fillColor;if(16777215===this.tint)r.tint=n;else if(this.tint!==this._prevRectTint||n!==this._prevRectFillColor){var i=C,o=R;(0,m.hex2rgb)(n,i),(0,m.hex2rgb)(this.tint,o),i[0]*=o[0],i[1]*=o[1],i[2]*=o[2],r.tint=(0,m.rgb2hex)(i),this._prevRectTint=this.tint,this._prevRectFillColor=n}r.alpha=this.graphicsData[0].fillAlpha,r.worldAlpha=this.worldAlpha*r.alpha,r.blendMode=this.blendMode,r._texture._frame.width=e.width,r._texture._frame.height=e.height,r.transform.worldTransform=this.transform.worldTransform,r.anchor.set(-e.x/e.width,-e.y/e.height),r._onAnchorUpdate(),r._renderWebGL(t)},e.prototype._renderCanvas=function(t){!0!==this.isMask&&t.plugins.graphics.render(this)},e.prototype._calculateBounds=function(){this.boundsDirty!==this.dirty&&(this.boundsDirty=this.dirty,this.updateLocalBounds(),this.cachedSpriteDirty=!0);var t=this._localBounds;this._bounds.addFrame(this.transform,t.minX,t.minY,t.maxX,t.maxY)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,P);for(var e=this.graphicsData,r=0;re?o+a:e,r=sn?s+u:n;else if(c===_.SHAPES.CIRC)o=i.x,s=i.y,a=i.radius+d/2,u=i.radius+d/2,t=o-ae?o+a:e,r=s-un?s+u:n;else if(c===_.SHAPES.ELIP)o=i.x,s=i.y,a=i.width+d/2,u=i.height+d/2,t=o-ae?o+a:e,r=s-un?s+u:n;else for(var f=i.points,p=0,v=0,g=0,y=0,m=0,b=0,x=0,T=0,w=0;w+2e?x+m:e,r=T-bn?T+b:n)}else t=0,e=0,r=0,n=0;var E=this.boundsPadding;this._localBounds.minX=t-E,this._localBounds.maxX=e+E,this._localBounds.minY=r-E,this._localBounds.maxY=n+E},e.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null;var e=new p.default(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,this.nativeLines,t,this.lineAlignment);return this.graphicsData.push(e),e.type===_.SHAPES.POLY&&(e.shape.closed=e.shape.closed,this.currentPath=e),this.dirty++,e},e.prototype.generateCanvasTexture=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=this.getLocalBounds(),n=l.default.create(r.width,r.height,t,e);O||(O=new S.default),this.transform.updateLocalTransform(),this.transform.localTransform.copy(M),M.invert(),M.tx-=r.x,M.ty-=r.y,O.render(this,n,!0,M);var i=d.default.fromCanvas(n.baseTexture._canvasRenderTarget.canvas,t,"graphics");return i.baseTexture.resolution=e,i.baseTexture.update(),i},e.prototype.closePath=function(){var t=this.currentPath;return t&&t.shape&&t.shape.close(),this},e.prototype.addHole=function(){var t=this.graphicsData.pop();return this.currentPath=this.graphicsData[this.graphicsData.length-1],this.currentPath.addHole(t.shape),this.currentPath=null,this},e.prototype.destroy=function(e){t.prototype.destroy.call(this,e);for(var r=0;rP?P:M,r.beginPath(),r.moveTo(w,E+M),r.lineTo(w,E+O-M),r.quadraticCurveTo(w,E+O,w+M,E+O),r.lineTo(w+S-M,E+O),r.quadraticCurveTo(w+S,E+O,w+S,E+O-M),r.lineTo(w+S,E+M),r.quadraticCurveTo(w+S,E,w+S-M,E),r.lineTo(w+M,E),r.quadraticCurveTo(w,E,w,E+M),r.closePath(),(u.fillColor||0===u.fillColor)&&(r.globalAlpha=u.fillAlpha*n,r.fillStyle="#"+("00000"+(0|l).toString(16)).substr(-6),r.fill()),u.lineWidth&&(r.globalAlpha=u.lineAlpha*n,r.strokeStyle="#"+("00000"+(0|c).toString(16)).substr(-6),r.stroke())}}},t.prototype.updateGraphicsTint=function(t){t._prevTint=t.tint,t.canvasTintDirty=t.dirty;for(var e=(t.tint>>16&255)/255,r=(t.tint>>8&255)/255,n=(255&t.tint)/255,i=0;i>16&255)/255*e*255<<16)+((s>>8&255)/255*r*255<<8)+(255&s)/255*n*255,o._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*r*255<<8)+(255&a)/255*n*255}},t.prototype.renderPolygon=function(t,e,r){r.moveTo(t[0],t[1]);for(var n=1;n9&&void 0!==arguments[9]?arguments[9]:[],l=0,c=0,d=0,f=0,p=0;h.push(t,e);for(var v=1,g=0;v<=u;++v)g=v/u,l=1-g,c=l*l,d=c*l,f=g*g,p=f*g,h.push(d*t+3*c*g*r+3*l*f*i+p*s,d*e+3*c*g*n+3*l*f*o+p*a);return h}r.__esModule=!0,r.default=n},{}],57:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../../utils"),u=t("../../const"),h=t("../../renderers/webgl/utils/ObjectRenderer"),l=n(h),c=t("../../renderers/webgl/WebGLRenderer"),d=n(c),f=t("./WebGLGraphicsData"),p=n(f),v=t("./shaders/PrimitiveShader"),g=n(v),y=t("./utils/buildPoly"),m=n(y),_=t("./utils/buildRectangle"),b=n(_),x=t("./utils/buildRoundedRectangle"),T=n(x),w=t("./utils/buildCircle"),E=n(w),S=function(t){function e(r){i(this,e);var n=o(this,t.call(this,r));return n.graphicsDataPool=[],n.primitiveShader=null,n.gl=r.gl,n.CONTEXT_UID=0,n}return s(e,t),e.prototype.onContextChange=function(){this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.primitiveShader=new g.default(this.gl)},e.prototype.destroy=function(){l.default.prototype.destroy.call(this);for(var t=0;t32e4)&&(n=this.graphicsDataPool.pop()||new p.default(this.renderer.gl,this.primitiveShader,this.renderer.state.attribsState),n.nativeLines=r,n.reset(e),t.data.push(n)),n.dirty=!0,n},e}(l.default);r.default=S,d.default.registerPlugin("graphics",S)},{"../../const":46,"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../utils":125,"./WebGLGraphicsData":58,"./shaders/PrimitiveShader":59,"./utils/buildCircle":60,"./utils/buildPoly":62,"./utils/buildRectangle":63,"./utils/buildRoundedRectangle":64}],58:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("pixi-gl-core"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=function(){function t(e,r,i){n(this,t),this.gl=e,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=o.default.GLBuffer.createVertexBuffer(e),this.indexBuffer=o.default.GLBuffer.createIndexBuffer(e),this.dirty=!0,this.nativeLines=!1,this.glPoints=null,this.glIndices=null,this.shader=r,this.vao=new o.default.VertexArrayObject(e,i).addIndex(this.indexBuffer).addAttribute(this.buffer,r.attributes.aVertexPosition,e.FLOAT,!1,24,0).addAttribute(this.buffer,r.attributes.aColor,e.FLOAT,!1,24,8)}return t.prototype.reset=function(){this.points.length=0,this.indices.length=0},t.prototype.upload=function(){this.glPoints=new Float32Array(this.points),this.buffer.upload(this.glPoints),this.glIndices=new Uint16Array(this.indices),this.indexBuffer.upload(this.glIndices),this.dirty=!1},t.prototype.destroy=function(){this.color=null,this.points=null,this.indices=null,this.vao.destroy(),this.buffer.destroy(),this.indexBuffer.destroy(),this.gl=null,this.buffer=null,this.indexBuffer=null,this.glPoints=null,this.glIndices=null},t}();r.default=s},{"pixi-gl-core":15}],59:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=t("../../../Shader"),a=function(t){return t&&t.__esModule?t:{default:t}}(s),u=function(t){function e(r){return n(this,e),i(this,t.call(this,r,["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform mat3 projectionMatrix;","uniform float alpha;","uniform vec3 tint;","varying vec4 vColor;","void main(void){"," gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"].join("\n"),["varying vec4 vColor;","void main(void){"," gl_FragColor = vColor;","}"].join("\n")))}return o(e,t),e}(a.default);r.default=u},{"../../../Shader":44}],60:[function(t,e,r){"use strict";function n(t,e,r){var n=t.shape,i=n.x,u=n.y,h=void 0,l=void 0;if(t.type===s.SHAPES.CIRC?(h=n.radius,l=n.radius):(h=n.width,l=n.height),0!==h&&0!==l){var c=Math.floor(30*Math.sqrt(n.radius))||Math.floor(15*Math.sqrt(n.width+n.height)),d=2*Math.PI/c;if(t.fill){var f=(0,a.hex2rgb)(t.fillColor),p=t.fillAlpha,v=f[0]*p,g=f[1]*p,y=f[2]*p,m=e.points,_=e.indices,b=m.length/6;_.push(b);for(var x=0;x196*p*p?(R=O-P,A=M-C,I=Math.sqrt(R*R+A*A),R/=I,A/=I,R*=p,A*=p,h.push(T-R*L,w-A*L),h.push(y,m,_,g),h.push(T+R*N,w+A*N),h.push(y,m,_,g),h.push(T-R*N*L,w-A*L),h.push(y,m,_,g),d++):(h.push(T+(H-T)*L,w+(V-w)*L),h.push(y,m,_,g),h.push(T-(H-T)*N,w-(V-w)*N),h.push(y,m,_,g))}}b=r[2*(c-2)],x=r[2*(c-2)+1],T=r[2*(c-1)],w=r[2*(c-1)+1],O=-(x-w),M=b-T,I=Math.sqrt(O*O+M*M),O/=I,M/=I,O*=p,M*=p,h.push(T-O*L,w-M*L),h.push(y,m,_,g),h.push(T+O*N,w+M*N),h.push(y,m,_,g),l.push(f);for(var Y=0;Y=6){for(var i=[],o=t.holes,u=0;u0&&(0,s.default)(t,e,r)}r.__esModule=!0,r.default=i;var o=t("./buildLine"),s=n(o),a=t("../../../utils"),u=t("earcut"),h=n(u)},{"../../../utils":125,"./buildLine":61,earcut:2}],63:[function(t,e,r){"use strict";function n(t,e,r){var n=t.shape,i=n.x,a=n.y,u=n.width,h=n.height;if(t.fill){var l=(0,s.hex2rgb)(t.fillColor),c=t.fillAlpha,d=l[0]*c,f=l[1]*c,p=l[2]*c,v=e.points,g=e.indices,y=v.length/6;v.push(i,a),v.push(d,f,p,c),v.push(i+u,a),v.push(d,f,p,c),v.push(i,a+h),v.push(d,f,p,c),v.push(i+u,a+h),v.push(d,f,p,c),g.push(y,y,y+1,y+2,y+3,y+3)}if(t.lineWidth){var m=t.points;t.points=[i,a,i+u,a,i+u,a+h,i,a+h,i,a],(0,o.default)(t,e,r),t.points=m}}r.__esModule=!0,r.default=n;var i=t("./buildLine"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=t("../../../utils")},{"../../../utils":125,"./buildLine":61}],64:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e,r){var n=t.shape,i=n.x,o=n.y,a=n.width,h=n.height,d=n.radius,f=[];if(f.push(i,o+d),s(i,o+h-d,i,o+h,i+d,o+h,f),s(i+a-d,o+h,i+a,o+h,i+a,o+h-d,f),s(i+a,o+d,i+a,o,i+a-d,o,f),s(i+d,o,i,o,i,o+d+1e-10,f),t.fill){for(var p=(0,c.hex2rgb)(t.fillColor),v=t.fillAlpha,g=p[0]*v,y=p[1]*v,m=p[2]*v,_=e.points,b=e.indices,x=_.length/6,T=(0,u.default)(f,null,2),w=0,E=T.length;w6&&void 0!==arguments[6]?arguments[6]:[],u=a,h=0,l=0,c=0,d=0,f=0,p=0,v=0,g=0;v<=20;++v)g=v/20,h=o(t,r,g),l=o(e,n,g),c=o(r,i,g),d=o(n,s,g),f=o(h,c,g),p=o(l,d,g),u.push(f,p);return u}r.__esModule=!0,r.default=i;var a=t("earcut"),u=n(a),h=t("./buildLine"),l=n(h),c=t("../../../utils")},{"../../../utils":125,"./buildLine":61,earcut:2}],65:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.autoDetectRenderer=r.Application=r.Filter=r.SpriteMaskFilter=r.Quad=r.RenderTarget=r.ObjectRenderer=r.WebGLManager=r.Shader=r.CanvasRenderTarget=r.TextureUvs=r.VideoBaseTexture=r.BaseRenderTexture=r.RenderTexture=r.BaseTexture=r.TextureMatrix=r.Texture=r.Spritesheet=r.CanvasGraphicsRenderer=r.GraphicsRenderer=r.GraphicsData=r.Graphics=r.TextMetrics=r.TextStyle=r.Text=r.SpriteRenderer=r.CanvasTinter=r.CanvasSpriteRenderer=r.Sprite=r.TransformBase=r.TransformStatic=r.Transform=r.Container=r.DisplayObject=r.Bounds=r.glCore=r.WebGLRenderer=r.CanvasRenderer=r.ticker=r.utils=r.settings=void 0;var o=t("./const");Object.keys(o).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return o[t]}})});var s=t("./math");Object.keys(s).forEach(function(t){"default"!==t&&"__esModule"!==t&&Object.defineProperty(r,t,{enumerable:!0,get:function(){return s[t]}})});var a=t("pixi-gl-core");Object.defineProperty(r,"glCore",{enumerable:!0,get:function(){return i(a).default}});var u=t("./display/Bounds");Object.defineProperty(r,"Bounds",{enumerable:!0,get:function(){return i(u).default}});var h=t("./display/DisplayObject");Object.defineProperty(r,"DisplayObject",{enumerable:!0,get:function(){return i(h).default}});var l=t("./display/Container");Object.defineProperty(r,"Container",{enumerable:!0,get:function(){return i(l).default}});var c=t("./display/Transform");Object.defineProperty(r,"Transform",{enumerable:!0,get:function(){return i(c).default}});var d=t("./display/TransformStatic");Object.defineProperty(r,"TransformStatic",{enumerable:!0,get:function(){return i(d).default}});var f=t("./display/TransformBase");Object.defineProperty(r,"TransformBase",{enumerable:!0,get:function(){return i(f).default}});var p=t("./sprites/Sprite");Object.defineProperty(r,"Sprite",{enumerable:!0,get:function(){return i(p).default}});var v=t("./sprites/canvas/CanvasSpriteRenderer");Object.defineProperty(r,"CanvasSpriteRenderer",{enumerable:!0,get:function(){return i(v).default}});var g=t("./sprites/canvas/CanvasTinter");Object.defineProperty(r,"CanvasTinter",{enumerable:!0,get:function(){return i(g).default}});var y=t("./sprites/webgl/SpriteRenderer");Object.defineProperty(r,"SpriteRenderer",{enumerable:!0,get:function(){return i(y).default}});var m=t("./text/Text");Object.defineProperty(r,"Text",{enumerable:!0,get:function(){return i(m).default}});var _=t("./text/TextStyle");Object.defineProperty(r,"TextStyle",{enumerable:!0,get:function(){return i(_).default}});var b=t("./text/TextMetrics");Object.defineProperty(r,"TextMetrics",{enumerable:!0,get:function(){return i(b).default}});var x=t("./graphics/Graphics");Object.defineProperty(r,"Graphics",{enumerable:!0,get:function(){return i(x).default}});var T=t("./graphics/GraphicsData");Object.defineProperty(r,"GraphicsData",{enumerable:!0,get:function(){return i(T).default}});var w=t("./graphics/webgl/GraphicsRenderer");Object.defineProperty(r,"GraphicsRenderer",{enumerable:!0,get:function(){return i(w).default}});var E=t("./graphics/canvas/CanvasGraphicsRenderer");Object.defineProperty(r,"CanvasGraphicsRenderer",{enumerable:!0,get:function(){return i(E).default}});var S=t("./textures/Spritesheet");Object.defineProperty(r,"Spritesheet",{enumerable:!0,get:function(){return i(S).default}});var O=t("./textures/Texture");Object.defineProperty(r,"Texture",{enumerable:!0,get:function(){return i(O).default}});var M=t("./textures/TextureMatrix");Object.defineProperty(r,"TextureMatrix",{enumerable:!0,get:function(){return i(M).default}});var P=t("./textures/BaseTexture");Object.defineProperty(r,"BaseTexture",{enumerable:!0,get:function(){return i(P).default}});var C=t("./textures/RenderTexture");Object.defineProperty(r,"RenderTexture",{enumerable:!0,get:function(){return i(C).default}});var R=t("./textures/BaseRenderTexture");Object.defineProperty(r,"BaseRenderTexture",{enumerable:!0,get:function(){return i(R).default}});var A=t("./textures/VideoBaseTexture");Object.defineProperty(r,"VideoBaseTexture",{enumerable:!0,get:function(){return i(A).default}});var I=t("./textures/TextureUvs");Object.defineProperty(r,"TextureUvs",{enumerable:!0,get:function(){return i(I).default}});var D=t("./renderers/canvas/utils/CanvasRenderTarget");Object.defineProperty(r,"CanvasRenderTarget",{enumerable:!0,get:function(){return i(D).default}});var L=t("./Shader");Object.defineProperty(r,"Shader",{enumerable:!0,get:function(){return i(L).default}});var N=t("./renderers/webgl/managers/WebGLManager");Object.defineProperty(r,"WebGLManager",{enumerable:!0,get:function(){return i(N).default}});var B=t("./renderers/webgl/utils/ObjectRenderer");Object.defineProperty(r,"ObjectRenderer",{enumerable:!0,get:function(){return i(B).default}});var F=t("./renderers/webgl/utils/RenderTarget");Object.defineProperty(r,"RenderTarget",{enumerable:!0,get:function(){return i(F).default}});var k=t("./renderers/webgl/utils/Quad");Object.defineProperty(r,"Quad",{enumerable:!0,get:function(){return i(k).default}});var j=t("./renderers/webgl/filters/spriteMask/SpriteMaskFilter");Object.defineProperty(r,"SpriteMaskFilter",{enumerable:!0,get:function(){return i(j).default}});var U=t("./renderers/webgl/filters/Filter");Object.defineProperty(r,"Filter",{enumerable:!0,get:function(){return i(U).default}});var X=t("./Application");Object.defineProperty(r,"Application",{enumerable:!0,get:function(){return i(X).default}});var G=t("./autoDetectRenderer");Object.defineProperty(r,"autoDetectRenderer",{enumerable:!0,get:function(){return G.autoDetectRenderer}});var W=t("./utils"),H=n(W),V=t("./ticker"),Y=n(V),z=t("./settings"),q=i(z),K=t("./renderers/canvas/CanvasRenderer"),Z=i(K),J=t("./renderers/webgl/WebGLRenderer"),Q=i(J);r.settings=q.default,r.utils=H,r.ticker=Y,r.CanvasRenderer=Z.default,r.WebGLRenderer=Q.default},{"./Application":43,"./Shader":44,"./autoDetectRenderer":45,"./const":46,"./display/Bounds":47,"./display/Container":48,"./display/DisplayObject":49,"./display/Transform":50,"./display/TransformBase":51,"./display/TransformStatic":52,"./graphics/Graphics":53,"./graphics/GraphicsData":54,"./graphics/canvas/CanvasGraphicsRenderer":55,"./graphics/webgl/GraphicsRenderer":57,"./math":70,"./renderers/canvas/CanvasRenderer":77,"./renderers/canvas/utils/CanvasRenderTarget":79,"./renderers/webgl/WebGLRenderer":84,"./renderers/webgl/filters/Filter":86,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":89,"./renderers/webgl/managers/WebGLManager":93,"./renderers/webgl/utils/ObjectRenderer":94,"./renderers/webgl/utils/Quad":95,"./renderers/webgl/utils/RenderTarget":96,"./settings":101,"./sprites/Sprite":102,"./sprites/canvas/CanvasSpriteRenderer":103,"./sprites/canvas/CanvasTinter":104,"./sprites/webgl/SpriteRenderer":106,"./text/Text":108,"./text/TextMetrics":109,"./text/TextStyle":110,"./textures/BaseRenderTexture":111,"./textures/BaseTexture":112,"./textures/RenderTexture":113,"./textures/Spritesheet":114,"./textures/Texture":115,"./textures/TextureMatrix":116,"./textures/TextureUvs":117,"./textures/VideoBaseTexture":118,"./ticker":121,"./utils":125,"pixi-gl-core":15}],66:[function(t,e,r){"use strict";function n(t){return t<0?-1:t>0?1:0}r.__esModule=!0;var i=t("./Matrix"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],a=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],u=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],h=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],l=[],c=[];!function(){for(var t=0;t<16;t++){var e=[];c.push(e);for(var r=0;r<16;r++)for(var i=n(s[t]*s[r]+u[t]*a[r]),d=n(a[t]*s[r]+h[t]*a[r]),f=n(s[t]*u[r]+u[t]*h[r]),p=n(a[t]*u[r]+h[t]*h[r]),v=0;v<16;v++)if(s[v]===i&&a[v]===d&&u[v]===f&&h[v]===p){e.push(v);break}}for(var g=0;g<16;g++){var y=new o.default;y.set(s[g],a[g],u[g],h[g],0,0),l.push(y)}}();var d={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MIRROR_HORIZONTAL:12,uX:function(t){return s[t]},uY:function(t){return a[t]},vX:function(t){return u[t]},vY:function(t){return h[t]},inv:function(t){return 8&t?15&t:7&-t},add:function(t,e){return c[t][e]},sub:function(t,e){return c[t][d.inv(e)]},rotate180:function(t){return 4^t},isVertical:function(t){return 2==(3&t)},byDirection:function(t,e){return 2*Math.abs(t)<=Math.abs(e)?e>=0?d.S:d.N:2*Math.abs(e)<=Math.abs(t)?t>0?d.E:d.W:e>0?t>0?d.SE:d.SW:t>0?d.NE:d.NW},matrixAppendRotationInv:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=l[d.inv(e)];i.tx=r,i.ty=n,t.append(i)}};r.default=d},{"./Matrix":67}],67:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:1,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;n(this,t),this.a=e,this.b=r,this.c=i,this.d=o,this.tx=s,this.ty=a,this.array=null}return t.prototype.fromArray=function(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]},t.prototype.set=function(t,e,r,n,i,o){return this.a=t,this.b=e,this.c=r,this.d=n,this.tx=i,this.ty=o,this},t.prototype.toArray=function(t,e){this.array||(this.array=new Float32Array(9));var r=e||this.array;return t?(r[0]=this.a,r[1]=this.b,r[2]=0,r[3]=this.c,r[4]=this.d,r[5]=0,r[6]=this.tx,r[7]=this.ty,r[8]=1):(r[0]=this.a,r[1]=this.c,r[2]=this.tx,r[3]=this.b,r[4]=this.d,r[5]=this.ty,r[6]=0,r[7]=0,r[8]=1),r},t.prototype.apply=function(t,e){e=e||new s.default;var r=t.x,n=t.y;return e.x=this.a*r+this.c*n+this.tx,e.y=this.b*r+this.d*n+this.ty,e},t.prototype.applyInverse=function(t,e){e=e||new s.default;var r=1/(this.a*this.d+this.c*-this.b),n=t.x,i=t.y;return e.x=this.d*r*n+-this.c*r*i+(this.ty*this.c-this.tx*this.d)*r,e.y=this.a*r*i+-this.b*r*n+(-this.ty*this.a+this.tx*this.b)*r,e},t.prototype.translate=function(t,e){return this.tx+=t,this.ty+=e,this},t.prototype.scale=function(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this},t.prototype.rotate=function(t){var e=Math.cos(t),r=Math.sin(t),n=this.a,i=this.c,o=this.tx;return this.a=n*e-this.b*r,this.b=n*r+this.b*e,this.c=i*e-this.d*r,this.d=i*r+this.d*e,this.tx=o*e-this.ty*r,this.ty=o*r+this.ty*e,this},t.prototype.append=function(t){var e=this.a,r=this.b,n=this.c,i=this.d;return this.a=t.a*e+t.b*n,this.b=t.a*r+t.b*i,this.c=t.c*e+t.d*n,this.d=t.c*r+t.d*i,this.tx=t.tx*e+t.ty*n+this.tx,this.ty=t.tx*r+t.ty*i+this.ty,this},t.prototype.setTransform=function(t,e,r,n,i,o,s,a,u){return this.a=Math.cos(s+u)*i,this.b=Math.sin(s+u)*i,this.c=-Math.sin(s-a)*o,this.d=Math.cos(s-a)*o,this.tx=t-(r*this.a+n*this.c),this.ty=e-(r*this.b+n*this.d),this},t.prototype.prepend=function(t){var e=this.tx;if(1!==t.a||0!==t.b||0!==t.c||1!==t.d){var r=this.a,n=this.c;this.a=r*t.a+this.b*t.c,this.b=r*t.b+this.b*t.d,this.c=n*t.a+this.d*t.c,this.d=n*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this},t.prototype.decompose=function(t){var e=this.a,r=this.b,n=this.c,i=this.d,o=-Math.atan2(-n,i),s=Math.atan2(r,e),u=Math.abs(o+s);return u<1e-5||Math.abs(a.PI_2-u)<1e-5?(t.rotation=s,e<0&&i>=0&&(t.rotation+=t.rotation<=0?Math.PI:-Math.PI),t.skew.x=t.skew.y=0):(t.rotation=0,t.skew.x=o,t.skew.y=s),t.scale.x=Math.sqrt(e*e+r*r),t.scale.y=Math.sqrt(n*n+i*i),t.position.x=this.tx,t.position.y=this.ty,t},t.prototype.invert=function(){var t=this.a,e=this.b,r=this.c,n=this.d,i=this.tx,o=t*n-e*r;return this.a=n/o,this.b=-e/o,this.c=-r/o,this.d=t/o,this.tx=(r*this.ty-n*i)/o,this.ty=-(t*this.ty-e*i)/o,this},t.prototype.identity=function(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this},t.prototype.clone=function(){var e=new t;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e},t.prototype.copy=function(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t},i(t,null,[{key:"IDENTITY",get:function(){return new t}},{key:"TEMP_MATRIX",get:function(){return new t}}]),t}();r.default=u},{"../const":46,"./Point":69}],68:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this._x=i,this._y=o,this.cb=e,this.scope=r}return t.prototype.clone=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return new t(e||this.cb,r||this.scope,this._x,this._y)},t.prototype.set=function(t,e){var r=t||0,n=e||(0!==e?r:0);this._x===r&&this._y===n||(this._x=r,this._y=n,this.cb.call(this.scope))},t.prototype.copy=function(t){this._x===t.x&&this._y===t.y||(this._x=t.x,this._y=t.y,this.cb.call(this.scope))},t.prototype.equals=function(t){return t.x===this._x&&t.y===this._y},i(t,[{key:"x",get:function(){return this._x},set:function(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}},{key:"y",get:function(){return this._y},set:function(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}]),t}();r.default=o},{}],69:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;n(this,t),this.x=e,this.y=r}return t.prototype.clone=function(){return new t(this.x,this.y)},t.prototype.copy=function(t){this.set(t.x,t.y)},t.prototype.equals=function(t){return t.x===this.x&&t.y===this.y},t.prototype.set=function(t,e){this.x=t||0,this.y=e||(0!==e?this.x:0)},t}();r.default=i},{}],70:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./Point");Object.defineProperty(r,"Point",{enumerable:!0,get:function(){return n(i).default}});var o=t("./ObservablePoint");Object.defineProperty(r,"ObservablePoint",{enumerable:!0,get:function(){return n(o).default}});var s=t("./Matrix");Object.defineProperty(r,"Matrix",{enumerable:!0,get:function(){return n(s).default}});var a=t("./GroupD8");Object.defineProperty(r,"GroupD8",{enumerable:!0,get:function(){return n(a).default}});var u=t("./shapes/Circle");Object.defineProperty(r,"Circle",{enumerable:!0,get:function(){return n(u).default}});var h=t("./shapes/Ellipse");Object.defineProperty(r,"Ellipse",{enumerable:!0,get:function(){return n(h).default}});var l=t("./shapes/Polygon");Object.defineProperty(r,"Polygon",{enumerable:!0,get:function(){return n(l).default}});var c=t("./shapes/Rectangle");Object.defineProperty(r,"Rectangle",{enumerable:!0,get:function(){return n(c).default}});var d=t("./shapes/RoundedRectangle");Object.defineProperty(r,"RoundedRectangle",{enumerable:!0,get:function(){return n(d).default}})},{"./GroupD8":66,"./Matrix":67,"./ObservablePoint":68,"./Point":69,"./shapes/Circle":71,"./shapes/Ellipse":72,"./shapes/Polygon":73,"./shapes/Rectangle":74,"./shapes/RoundedRectangle":75}],71:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("./Rectangle"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=t("../../const"),a=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;n(this,t),this.x=e,this.y=r,this.radius=i,this.type=s.SHAPES.CIRC}return t.prototype.clone=function(){return new t(this.x,this.y,this.radius)},t.prototype.contains=function(t,e){if(this.radius<=0)return!1;var r=this.radius*this.radius,n=this.x-t,i=this.y-e;return n*=n,i*=i,n+i<=r},t.prototype.getBounds=function(){return new o.default(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)},t}();r.default=a},{"../../const":46,"./Rectangle":74}],72:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("./Rectangle"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=t("../../const"),a=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this.x=e,this.y=r,this.width=i,this.height=o,this.type=s.SHAPES.ELIP}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;var r=(t-this.x)/this.width,n=(e-this.y)/this.height;return r*=r,n*=n,r+n<=1},t.prototype.getBounds=function(){return new o.default(this.x-this.width,this.y-this.height,this.width,this.height)},t}();r.default=a},{"../../const":46,"./Rectangle":74}],73:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../Point"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=t("../../const"),a=function(){function t(){for(var e=arguments.length,r=Array(e),i=0;ie!=h>e&&t<(e-a)/(h-a)*(u-s)+s&&(r=!r)}return r},t}();r.default=a},{"../../const":46,"../Point":69}],74:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;n(this,t),this.x=Number(e),this.y=Number(r),this.width=Number(i),this.height=Number(s),this.type=o.SHAPES.RECT}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this},t.prototype.contains=function(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t=this.y&&et.x+t.width&&(this.width=t.width-this.x,this.width<0&&(this.width=0)),this.y+this.height>t.y+t.height&&(this.height=t.height-this.y,this.height<0&&(this.height=0))},t.prototype.enlarge=function(t){var e=Math.min(this.x,t.x),r=Math.max(this.x+this.width,t.x+t.width),n=Math.min(this.y,t.y),i=Math.max(this.y+this.height,t.y+t.height);this.x=e,this.width=r-e,this.y=n,this.height=i-n},i(t,[{key:"left",get:function(){return this.x}},{key:"right",get:function(){return this.x+this.width}},{key:"top",get:function(){return this.y}},{key:"bottom",get:function(){return this.y+this.height}}],[{key:"EMPTY",get:function(){return new t(0,0,0,0)}}]),t}();r.default=s},{"../../const":46}],75:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:20;n(this,t),this.x=e,this.y=r,this.width=o,this.height=s,this.radius=a,this.type=i.SHAPES.RREC}return t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height,this.radius)},t.prototype.contains=function(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){if(e>=this.y+this.radius&&e<=this.y+this.height-this.radius||t>=this.x+this.radius&&t<=this.x+this.width-this.radius)return!0;var r=t-(this.x+this.radius),n=e-(this.y+this.radius),i=this.radius*this.radius;if(r*r+n*n<=i)return!0;if((r=t-(this.x+this.width-this.radius))*r+n*n<=i)return!0;if(n=e-(this.y+this.height-this.radius),r*r+n*n<=i)return!0;if((r=t-(this.x+this.radius))*r+n*n<=i)return!0}return!1},t}();r.default=o},{"../../const":46}],76:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;rE?E:w,e.moveTo(_,b+w),e.lineTo(_,b+T-w),e.quadraticCurveTo(_,b+T,_+w,b+T),e.lineTo(_+x-w,b+T),e.quadraticCurveTo(_+x,b+T,_+x,b+T-w),e.lineTo(_+x,b+w),e.quadraticCurveTo(_+x,b,_+x-w,b),e.lineTo(_+w,b),e.quadraticCurveTo(_,b,_,b+w),e.closePath()}}}},t.prototype.popMask=function(t){t.context.restore(),t.invalidateBlendMode()},t.prototype.destroy=function(){},t}();r.default=o},{"../../../const":46}],79:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:[];return(0,s.default)()?(t[i.BLEND_MODES.NORMAL]="source-over",t[i.BLEND_MODES.ADD]="lighter",t[i.BLEND_MODES.MULTIPLY]="multiply",t[i.BLEND_MODES.SCREEN]="screen",t[i.BLEND_MODES.OVERLAY]="overlay",t[i.BLEND_MODES.DARKEN]="darken",t[i.BLEND_MODES.LIGHTEN]="lighten",t[i.BLEND_MODES.COLOR_DODGE]="color-dodge",t[i.BLEND_MODES.COLOR_BURN]="color-burn",t[i.BLEND_MODES.HARD_LIGHT]="hard-light",t[i.BLEND_MODES.SOFT_LIGHT]="soft-light",t[i.BLEND_MODES.DIFFERENCE]="difference",t[i.BLEND_MODES.EXCLUSION]="exclusion",t[i.BLEND_MODES.HUE]="hue",t[i.BLEND_MODES.SATURATION]="saturate",t[i.BLEND_MODES.COLOR]="color",t[i.BLEND_MODES.LUMINOSITY]="luminosity"):(t[i.BLEND_MODES.NORMAL]="source-over",t[i.BLEND_MODES.ADD]="lighter",t[i.BLEND_MODES.MULTIPLY]="source-over",t[i.BLEND_MODES.SCREEN]="source-over",t[i.BLEND_MODES.OVERLAY]="source-over",t[i.BLEND_MODES.DARKEN]="source-over",t[i.BLEND_MODES.LIGHTEN]="source-over",t[i.BLEND_MODES.COLOR_DODGE]="source-over",t[i.BLEND_MODES.COLOR_BURN]="source-over",t[i.BLEND_MODES.HARD_LIGHT]="source-over",t[i.BLEND_MODES.SOFT_LIGHT]="source-over",t[i.BLEND_MODES.DIFFERENCE]="source-over",t[i.BLEND_MODES.EXCLUSION]="source-over",t[i.BLEND_MODES.HUE]="source-over",t[i.BLEND_MODES.SATURATION]="source-over",t[i.BLEND_MODES.COLOR]="source-over",t[i.BLEND_MODES.LUMINOSITY]="source-over"),t[i.BLEND_MODES.NORMAL_NPM]=t[i.BLEND_MODES.NORMAL],t[i.BLEND_MODES.ADD_NPM]=t[i.BLEND_MODES.ADD],t[i.BLEND_MODES.SCREEN_NPM]=t[i.BLEND_MODES.SCREEN],t}r.__esModule=!0,r.default=n;var i=t("../../../const"),o=t("./canUseNewCanvasBlendModes"),s=function(t){return t&&t.__esModule?t:{default:t}}(o)},{"../../../const":46,"./canUseNewCanvasBlendModes":80}],82:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../const"),o=t("../../settings"),s=function(t){return t&&t.__esModule?t:{default:t}}(o),a=function(){function t(e){n(this,t),this.renderer=e,this.count=0,this.checkCount=0,this.maxIdle=s.default.GC_MAX_IDLE,this.checkCountMax=s.default.GC_MAX_CHECK_COUNT,this.mode=s.default.GC_MODE}return t.prototype.update=function(){this.count++,this.mode!==i.GC_MODES.MANUAL&&++this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run())},t.prototype.run=function(){for(var t=this.renderer.textureManager,e=t._managedTextures,r=!1,n=0;nthis.maxIdle&&(t.destroyTexture(i,!0),e[n]=null,r=!0)}if(r){for(var o=0,s=0;s=0;r--)this.unload(t.children[r])},t}();r.default=a},{"../../const":46,"../../settings":101}],83:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("pixi-gl-core"),o=t("../../const"),s=t("./utils/RenderTarget"),a=function(t){return t&&t.__esModule?t:{default:t}}(s),u=t("../../utils"),h=function(){function t(e){n(this,t),this.renderer=e,this.gl=e.gl,this._managedTextures=[]}return t.prototype.bindTexture=function(){},t.prototype.getTexture=function(){},t.prototype.updateTexture=function(t,e){var r=this.gl,n=!!t._glRenderTargets;if(!t.hasLoaded)return null;var s=this.renderer.boundTextures;if(void 0===e){e=0;for(var u=0;u 0.5)"," {"," color = vec4(1.0, 0.0, 0.0, 1.0);"," }"," else"," {"," color = vec4(0.0, 1.0, 0.0, 1.0);"," }"," gl_FragColor = mix(sample, masky, 0.5);"," gl_FragColor *= sample.a;","}"].join("\n")}}]),t}();r.default=f},{"../../../const":46,"../../../settings":101,"../../../utils":125,"./extractUniformsFromSrc":87}],87:[function(t,e,r){"use strict";function n(t,e,r){var n=i(t),o=i(e);return Object.assign(n,o)}function i(t){for(var e=new RegExp("^(projectionMatrix|uSampler|filterArea|filterClamp)$"),r={},n=void 0,i=t.replace(/\s+/g," ").split(/\s*;\s*/),o=0;o-1){var u=s.split(" "),h=u[1],l=u[2],c=1;l.indexOf("[")>-1&&(n=l.split(/\[|]/),l=n[0],c*=Number(n[1])),l.match(e)||(r[l]={value:a(h,c),name:l,type:h})}}return r}r.__esModule=!0,r.default=n;var o=t("pixi-gl-core"),s=function(t){return t&&t.__esModule?t:{default:t}}(o),a=s.default.shader.defaultValue},{"pixi-gl-core":15}],88:[function(t,e,r){"use strict";function n(t,e,r){var n=t.identity();return n.translate(e.x/r.width,e.y/r.height),n.scale(r.width,r.height),n}function i(t,e,r){var n=t.identity();n.translate(e.x/r.width,e.y/r.height);var i=r.width/e.width,o=r.height/e.height;return n.scale(i,o),n}function o(t,e,r,n){var i=n._texture.orig,o=t.set(r.width,0,0,r.height,e.x,e.y),a=n.worldTransform.copy(s.Matrix.TEMP_MATRIX);return a.invert(),o.prepend(a),o.scale(1/i.width,1/i.height),o.translate(n.anchor.x,n.anchor.y),o}r.__esModule=!0,r.calculateScreenSpaceMatrix=n,r.calculateNormalizedScreenSpaceMatrix=i,r.calculateSpriteMatrix=o;var s=t("../../../math")},{"../../../math":70}],89:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../Filter"),u=n(a),h=t("../../../../math"),l=(t("path"),t("../../../../textures/TextureMatrix")),c=n(l),d=function(t){function e(r){i(this,e);var n=new h.Matrix,s=o(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n","varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n"));return r.renderable=!1,s.maskSprite=r,s.maskMatrix=n,s}return s(e,t),e.prototype.apply=function(t,e,r){var n=this.maskSprite,i=this.maskSprite.texture;i.valid&&(i.transform||(i.transform=new c.default(i,0)),i.transform.update(),this.uniforms.mask=i,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,n).prepend(i.transform.mapCoord),this.uniforms.alpha=n.worldAlpha,this.uniforms.maskClamp=i.transform.uClampFrame,t.applyFilter(this,e,r))},e}(u.default);r.default=d},{"../../../../math":70,"../../../../textures/TextureMatrix":116,"../Filter":86,path:8}],90:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var a=t("./WebGLManager"),u=n(a),h=t("../utils/RenderTarget"),l=n(h),c=t("../utils/Quad"),d=n(c),f=t("../../../math"),p=t("../../../Shader"),v=n(p),g=t("../filters/filterTransforms"),y=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(g),m=t("bit-twiddle"),_=n(m),b=function(){function t(){s(this,t),this.renderTarget=null,this.target=null,this.resolution=1,this.sourceFrame=new f.Rectangle,this.destinationFrame=new f.Rectangle,this.filters=[]}return t.prototype.clear=function(){this.filters=null,this.target=null,this.renderTarget=null},t}(),x=function(t){function e(r){s(this,e);var n=i(this,t.call(this,r));return n.gl=n.renderer.gl,n.quad=new d.default(n.gl,r.state.attribState),n.shaderCache={},n.pool={},n.filterData=null,n.managedFilters=[],n.renderer.on("prerender",n.onPrerender,n),n._screenWidth=r.view.width,n._screenHeight=r.view.height,n}return o(e,t),e.prototype.pushFilter=function(t,e){var r=this.renderer,n=this.filterData;if(!n){n=this.renderer._activeRenderTarget.filterStack;var i=new b;i.sourceFrame=i.destinationFrame=this.renderer._activeRenderTarget.size,i.renderTarget=r._activeRenderTarget,this.renderer._activeRenderTarget.filterData=n={index:0,stack:[i]},this.filterData=n}var o=n.stack[++n.index],s=n.stack[0].destinationFrame;o||(o=n.stack[n.index]=new b);var a=t.filterArea&&0===t.filterArea.x&&0===t.filterArea.y&&t.filterArea.width===r.screen.width&&t.filterArea.height===r.screen.height,u=e[0].resolution,h=0|e[0].padding,l=a?r.screen:t.filterArea||t.getBounds(!0),c=o.sourceFrame,d=o.destinationFrame;c.x=(l.x*u|0)/u,c.y=(l.y*u|0)/u,c.width=(l.width*u|0)/u,c.height=(l.height*u|0)/u,a||(n.stack[0].renderTarget.transform||e[0].autoFit&&c.fit(s),c.pad(h)),d.width=c.width,d.height=c.height;var f=this.getPotRenderTarget(r.gl,c.width,c.height,u);o.target=t,o.filters=e,o.resolution=u,o.renderTarget=f,f.setFrame(d,c),r.bindRenderTarget(f),f.clear()},e.prototype.popFilter=function(){var t=this.filterData,e=t.stack[t.index-1],r=t.stack[t.index];this.quad.map(r.renderTarget.size,r.sourceFrame).upload();var n=r.filters;if(1===n.length)n[0].apply(this,r.renderTarget,e.renderTarget,!1,r),this.freePotRenderTarget(r.renderTarget);else{var i=r.renderTarget,o=this.getPotRenderTarget(this.renderer.gl,r.sourceFrame.width,r.sourceFrame.height,r.resolution);o.setFrame(r.destinationFrame,r.sourceFrame),o.clear();var s=0;for(s=0;s0&&void 0!==arguments[0]&&arguments[0],e=this.renderer,r=this.managedFilters;e.off("prerender",this.onPrerender,this);for(var n=0;n0&&(e+="\nelse "),r1&&void 0!==arguments[1]?arguments[1]:[];return e[i.BLEND_MODES.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.ADD]=[t.ONE,t.DST_ALPHA],e[i.BLEND_MODES.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SCREEN]=[t.ONE,t.ONE_MINUS_SRC_COLOR],e[i.BLEND_MODES.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.NORMAL_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[i.BLEND_MODES.ADD_NPM]=[t.SRC_ALPHA,t.DST_ALPHA,t.ONE,t.DST_ALPHA],e[i.BLEND_MODES.SCREEN_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_COLOR,t.ONE,t.ONE_MINUS_SRC_COLOR],e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":46}],99:[function(t,e,r){"use strict";function n(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e[i.DRAW_MODES.POINTS]=t.POINTS,e[i.DRAW_MODES.LINES]=t.LINES,e[i.DRAW_MODES.LINE_LOOP]=t.LINE_LOOP,e[i.DRAW_MODES.LINE_STRIP]=t.LINE_STRIP,e[i.DRAW_MODES.TRIANGLES]=t.TRIANGLES,e[i.DRAW_MODES.TRIANGLE_STRIP]=t.TRIANGLE_STRIP,e[i.DRAW_MODES.TRIANGLE_FAN]=t.TRIANGLE_FAN,e}r.__esModule=!0,r.default=n;var i=t("../../../const")},{"../../../const":46}],100:[function(t,e,r){"use strict";function n(t){t.getContextAttributes().stencil||console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly")}r.__esModule=!0,r.default=n},{}],101:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./utils/maxRecommendedTextures"),o=n(i),s=t("./utils/canUploadSameBuffer"),a=n(s);r.default={TARGET_FPMS:.06,MIPMAP_TEXTURES:!0,RESOLUTION:1,FILTER_RESOLUTION:1,SPRITE_MAX_TEXTURES:(0,o.default)(32),SPRITE_BATCH_SIZE:4096,RETINA_PREFIX:/@([0-9\.]+)x/,RENDER_OPTIONS:{view:null,antialias:!1,forceFXAA:!1,autoResize:!1,transparent:!1,backgroundColor:0,clearBeforeRender:!0,preserveDrawingBuffer:!1,roundPixels:!1,width:800,height:600,legacy:!1},TRANSFORM_MODE:0,GC_MODE:0,GC_MAX_IDLE:3600,GC_MAX_CHECK_COUNT:600,WRAP_MODE:0,SCALE_MODE:0,PRECISION_VERTEX:"highp",PRECISION_FRAGMENT:"mediump",CAN_UPLOAD_SAME_BUFFER:(0,a.default)(),MESH_CANVAS_PADDING:0}},{"./utils/canUploadSameBuffer":122,"./utils/maxRecommendedTextures":127}],102:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r=n&&v.x=i&&v.y>16)+(65280&t)+((255&t)<<16)}},{key:"texture",get:function(){return this._texture},set:function(t){this._texture!==t&&(this._texture=t||d.default.EMPTY,this.cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,t&&(t.baseTexture.hasLoaded?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}]),e}(p.default);r.default=g},{"../const":46,"../display/Container":48,"../math":70,"../textures/Texture":115,"../utils":125}],103:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var o=t("../../renderers/canvas/CanvasRenderer"),s=n(o),a=t("../../const"),u=t("../../math"),h=t("./CanvasTinter"),l=n(h),c=new u.Matrix,d=function(){function t(e){i(this,t),this.renderer=e}return t.prototype.render=function(t){var e=t._texture,r=this.renderer,n=e._frame.width,i=e._frame.height,o=t.transform.worldTransform,s=0,h=0;if(!(e.orig.width<=0||e.orig.height<=0)&&e.baseTexture.source&&(r.setBlendMode(t.blendMode),e.valid)){r.context.globalAlpha=t.worldAlpha;var d=e.baseTexture.scaleMode===a.SCALE_MODES.LINEAR;r.smoothProperty&&r.context[r.smoothProperty]!==d&&(r.context[r.smoothProperty]=d),e.trim?(s=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,h=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(s=(.5-t.anchor.x)*e.orig.width,h=(.5-t.anchor.y)*e.orig.height),e.rotate&&(o.copy(c),o=c,u.GroupD8.matrixAppendRotationInv(o,e.rotate,s,h),s=0,h=0),s-=n/2,h-=i/2,r.roundPixels?(r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution|0,o.ty*r.resolution|0),s|=0,h|=0):r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution,o.ty*r.resolution);var f=e.baseTexture.resolution;16777215!==t.tint?(t.cachedTint===t.tint&&t.tintedTexture.tintId===t._texture._updateID||(t.cachedTint=t.tint,t.tintedTexture=l.default.getTintedTexture(t,t.tint)),r.context.drawImage(t.tintedTexture,0,0,n*f,i*f,s*r.resolution,h*r.resolution,n*r.resolution,i*r.resolution)):r.context.drawImage(e.baseTexture.source,e._frame.x*f,e._frame.y*f,n*f,i*f,s*r.resolution,h*r.resolution,n*r.resolution,i*r.resolution)}},t.prototype.destroy=function(){this.renderer=null},t}();r.default=d,s.default.registerPlugin("sprite",d)},{"../../const":46,"../../math":70,"../../renderers/canvas/CanvasRenderer":77,"./CanvasTinter":104}],104:[function(t,e,r){"use strict";r.__esModule=!0;var n=t("../../utils"),i=t("../../renderers/canvas/utils/canUseNewCanvasBlendModes"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s={getTintedTexture:function(t,e){var r=t._texture;e=s.roundColor(e);var n="#"+("00000"+(0|e).toString(16)).substr(-6);r.tintCache=r.tintCache||{};var i=r.tintCache[n],o=void 0;if(i){if(i.tintId===r._updateID)return r.tintCache[n];o=r.tintCache[n]}else o=s.canvas||document.createElement("canvas");if(s.tintMethod(r,e,o),o.tintId=r._updateID,s.convertTintToImage){var a=new Image;a.src=o.toDataURL(),r.tintCache[n]=a}else r.tintCache[n]=o,s.canvas=null;return o},tintWithMultiply:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.save(),n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="multiply",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.restore()},tintWithOverlay:function(t,e,r){var n=r.getContext("2d"),i=t._frame.clone(),o=t.baseTexture.resolution;i.x*=o,i.y*=o,i.width*=o,i.height*=o,r.width=Math.ceil(i.width),r.height=Math.ceil(i.height),n.save(),n.globalCompositeOperation="copy",n.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),n.fillRect(0,0,i.width,i.height),n.globalCompositeOperation="destination-atop",n.drawImage(t.baseTexture.source,i.x,i.y,i.width,i.height,0,0,i.width,i.height),n.restore()},tintWithPerPixel:function(t,e,r){var i=r.getContext("2d"),o=t._frame.clone(),s=t.baseTexture.resolution;o.x*=s,o.y*=s,o.width*=s,o.height*=s,r.width=Math.ceil(o.width),r.height=Math.ceil(o.height),i.save(),i.globalCompositeOperation="copy",i.drawImage(t.baseTexture.source,o.x,o.y,o.width,o.height,0,0,o.width,o.height),i.restore();for(var a=(0,n.hex2rgb)(e),u=a[0],h=a[1],l=a[2],c=i.getImageData(0,0,o.width,o.height),d=c.data,f=0;f=this.size&&this.flush(),t._texture._uvs&&(this.sprites[this.currentIndex++]=t)},e.prototype.flush=function(){if(0!==this.currentIndex){var t=this.renderer.gl,e=this.MAX_TEXTURES,r=S.default.nextPow2(this.currentIndex),n=S.default.log2(r),i=this.buffers[n],o=this.sprites,s=this.groups,a=i.float32View,u=i.uint32View,h=this.boundTextures,l=this.renderer.boundTextures,c=this.renderer.textureGC.count,d=0,f=void 0,p=void 0,v=1,g=0,y=s[0],m=void 0,_=void 0,T=x.premultiplyBlendMode[o[0]._texture.baseTexture.premultipliedAlpha?1:0][o[0].blendMode];y.textureCount=0,y.start=0,y.blend=T,O++;var E=void 0;for(E=0;E0&&(e+="\nelse "),r0&&(r.shadowColor=e.dropShadowColor);for(var f=Math.cos(e.dropShadowAngle)*e.dropShadowDistance,p=Math.sin(e.dropShadowAngle)*e.dropShadowDistance,v=0;v3&&void 0!==arguments[3]&&arguments[3],i=this._style,o=i.letterSpacing;if(0===o)return void(n?this.context.strokeText(t,e,r):this.context.fillText(t,e,r));for(var s=String.prototype.split.call(t,""),a=e,u=0,h="";u3&&void 0!==arguments[3]?arguments[3]:t._canvas;n=void 0===n||null===n?r.wordWrap:n;var o=r.toFontString(),s=t.measureFont(o),a=i.getContext("2d");a.font=o;for(var u=n?t.wordWrap(e,r,i):e,h=u.split(/(?:\r\n|\r|\n)/),l=new Array(h.length),c=0,d=0;d2&&void 0!==arguments[2]?arguments[2]:t._canvas,i=n.getContext("2d"),o=0,s="",a="",u={},h=r.letterSpacing,l=r.whiteSpace,c=t.collapseSpaces(l),d=t.collapseNewlines(l),f=!c,p=r.wordWrapWidth+h,v=t.tokenize(e),g=0;gp)if(""!==s&&(a+=t.addLine(s),s="",o=0),t.canBreakWords(y,r.breakWords))for(var x=y.split(""),T=0;Tp&&(a+=t.addLine(s),f=!1,s="",o=0),s+=w,o+=M}else{s.length>0&&(a+=t.addLine(s),s="",o=0);var P=g===v.length-1;a+=t.addLine(y,!P),f=!1,s="",o=0}else b+o>p&&(f=!1,a+=t.addLine(s),s="",o=0),(s.length>0||!t.isBreakingSpace(y)||f)&&(s+=y,o+=b)}return a+=t.addLine(s,!1)},t.addLine=function(e){var r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return e=t.trimRight(e),e=r?e+"\n":e},t.getFromCache=function(t,e,r,n){var i=r[t];if(void 0===i){var o=t.length*e;i=n.measureText(t).width+o,r[t]=i}return i},t.collapseSpaces=function(t){return"normal"===t||"pre-line"===t},t.collapseNewlines=function(t){return"normal"===t},t.trimRight=function(e){if("string"!=typeof e)return"";for(var r=e.length-1;r>=0;r--){var n=e[r];if(!t.isBreakingSpace(n))break;e=e.slice(0,-1)}return e},t.isNewline=function(e){return"string"==typeof e&&t._newlines.indexOf(e.charCodeAt(0))>=0},t.isBreakingSpace=function(e){return"string"==typeof e&&t._breakingSpaces.indexOf(e.charCodeAt(0))>=0},t.tokenize=function(e){var r=[],n="";if("string"!=typeof e)return r;for(var i=0;ia;--d){for(var g=0;g0&&void 0!==arguments[0]?arguments[0]:"";e?delete t._fonts[e]:t._fonts={}},t}();r.default=i;var o=document.createElement("canvas");o.width=o.height=10,i._canvas=o,i._context=o.getContext("2d"),i._fonts={},i.METRICS_STRING="|Éq",i.BASELINE_SYMBOL="M",i.BASELINE_MULTIPLIER=1.4,i._newlines=[10,13],i._breakingSpaces=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288]},{}],110:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t){return"number"==typeof t?(0,l.hex2string)(t):("string"==typeof t&&0===t.indexOf("0x")&&(t=t.replace("0x","#")),t)}function o(t){if(Array.isArray(t)){for(var e=0;e=0;r--){var n=e[r].trim();!/([\"\'])[^\'\"]+\1/.test(n)&&d.indexOf(n)<0&&(n='"'+n+'"'),e[r]=n}return this.fontStyle+" "+this.fontVariant+" "+this.fontWeight+" "+t+" "+e.join(",")},u(t,[{key:"align",get:function(){return this._align},set:function(t){this._align!==t&&(this._align=t,this.styleID++)}},{key:"breakWords",get:function(){return this._breakWords},set:function(t){this._breakWords!==t&&(this._breakWords=t,this.styleID++)}},{key:"dropShadow",get:function(){return this._dropShadow},set:function(t){this._dropShadow!==t&&(this._dropShadow=t,this.styleID++)}},{key:"dropShadowAlpha",get:function(){return this._dropShadowAlpha},set:function(t){this._dropShadowAlpha!==t&&(this._dropShadowAlpha=t,this.styleID++)}},{key:"dropShadowAngle",get:function(){return this._dropShadowAngle},set:function(t){this._dropShadowAngle!==t&&(this._dropShadowAngle=t,this.styleID++)}},{key:"dropShadowBlur",get:function(){return this._dropShadowBlur},set:function(t){this._dropShadowBlur!==t&&(this._dropShadowBlur=t,this.styleID++)}},{key:"dropShadowColor",get:function(){return this._dropShadowColor},set:function(t){var e=o(t);this._dropShadowColor!==e&&(this._dropShadowColor=e,this.styleID++)}},{key:"dropShadowDistance",get:function(){return this._dropShadowDistance},set:function(t){this._dropShadowDistance!==t&&(this._dropShadowDistance=t,this.styleID++)}},{key:"fill",get:function(){return this._fill},set:function(t){var e=o(t);this._fill!==e&&(this._fill=e,this.styleID++)}},{key:"fillGradientType",get:function(){return this._fillGradientType},set:function(t){this._fillGradientType!==t&&(this._fillGradientType=t,this.styleID++)}},{key:"fillGradientStops",get:function(){return this._fillGradientStops},set:function(t){s(this._fillGradientStops,t)||(this._fillGradientStops=t,this.styleID++)}},{key:"fontFamily",get:function(){return this._fontFamily},set:function(t){this.fontFamily!==t&&(this._fontFamily=t,this.styleID++)}},{key:"fontSize",get:function(){return this._fontSize},set:function(t){this._fontSize!==t&&(this._fontSize=t,this.styleID++)}},{key:"fontStyle",get:function(){return this._fontStyle},set:function(t){this._fontStyle!==t&&(this._fontStyle=t,this.styleID++)}},{key:"fontVariant",get:function(){return this._fontVariant},set:function(t){this._fontVariant!==t&&(this._fontVariant=t,this.styleID++)}},{key:"fontWeight",get:function(){return this._fontWeight},set:function(t){this._fontWeight!==t&&(this._fontWeight=t,this.styleID++)}},{key:"letterSpacing",get:function(){return this._letterSpacing},set:function(t){this._letterSpacing!==t&&(this._letterSpacing=t,this.styleID++)}},{key:"lineHeight",get:function(){return this._lineHeight},set:function(t){this._lineHeight!==t&&(this._lineHeight=t,this.styleID++)}},{key:"leading",get:function(){return this._leading},set:function(t){this._leading!==t&&(this._leading=t,this.styleID++)}},{key:"lineJoin",get:function(){return this._lineJoin},set:function(t){this._lineJoin!==t&&(this._lineJoin=t,this.styleID++)}},{key:"miterLimit",get:function(){return this._miterLimit},set:function(t){this._miterLimit!==t&&(this._miterLimit=t,this.styleID++)}},{key:"padding",get:function(){return this._padding},set:function(t){this._padding!==t&&(this._padding=t,this.styleID++)}},{key:"stroke",get:function(){return this._stroke},set:function(t){var e=o(t);this._stroke!==e&&(this._stroke=e,this.styleID++)}},{key:"strokeThickness",get:function(){return this._strokeThickness},set:function(t){this._strokeThickness!==t&&(this._strokeThickness=t,this.styleID++)}},{key:"textBaseline",get:function(){return this._textBaseline},set:function(t){this._textBaseline!==t&&(this._textBaseline=t,this.styleID++)}},{key:"trim",get:function(){return this._trim},set:function(t){this._trim!==t&&(this._trim=t,this.styleID++)}},{key:"whiteSpace",get:function(){return this._whiteSpace},set:function(t){this._whiteSpace!==t&&(this._whiteSpace=t,this.styleID++)}},{key:"wordWrap",get:function(){return this._wordWrap},set:function(t){this._wordWrap!==t&&(this._wordWrap=t,this.styleID++)}},{key:"wordWrapWidth",get:function(){return this._wordWrapWidth},set:function(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this.styleID++)}}]),t}();r.default=f},{"../const":46,"../utils":125}],111:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("./BaseTexture"),u=n(a),h=t("../settings"),l=n(h),c=function(t){function e(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,s=arguments[2],a=arguments[3];i(this,e);var u=o(this,t.call(this,null,s));return u.resolution=a||l.default.RESOLUTION,u.width=Math.ceil(r),u.height=Math.ceil(n),u.realWidth=u.width*u.resolution,u.realHeight=u.height*u.resolution,u.scaleMode=void 0!==s?s:l.default.SCALE_MODE,u.hasLoaded=!0,u._glRenderTargets={},u._canvasRenderTarget=null,u.valid=!1,u}return s(e,t),e.prototype.resize=function(t,e){t=Math.ceil(t),e=Math.ceil(e),t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.realWidth=this.width*this.resolution,this.realHeight=this.height*this.resolution,this.valid&&this.emit("update",this))},e.prototype.destroy=function(){t.prototype.destroy.call(this,!0),this.renderer=null},e}(u.default);r.default=c},{"../settings":101,"./BaseTexture":112}],112:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=t("../utils"),u=t("../settings"),h=n(u),l=t("eventemitter3"),c=n(l),d=t("../utils/determineCrossOrigin"),f=n(d),p=t("bit-twiddle"),v=n(p),g=function(t){function e(r,n,s){i(this,e);var u=o(this,t.call(this));return u.uid=(0,a.uid)(),u.touched=0,u.resolution=s||h.default.RESOLUTION,u.width=100,u.height=100,u.realWidth=100,u.realHeight=100,u.scaleMode=void 0!==n?n:h.default.SCALE_MODE,u.hasLoaded=!1,u.isLoading=!1,u.source=null,u.origSource=null,u.imageType=null,u.sourceScale=1,u.premultipliedAlpha=!0,u.imageUrl=null,u.isPowerOfTwo=!1,u.mipmap=h.default.MIPMAP_TEXTURES,u.wrapMode=h.default.WRAP_MODE,u._glTextures={},u._enabled=0,u._virtalBoundId=-1,u._destroyed=!1,u.textureCacheIds=[],r&&u.loadSource(r),u}return s(e,t),e.prototype.update=function(){"svg"!==this.imageType&&(this.realWidth=this.source.naturalWidth||this.source.videoWidth||this.source.width,this.realHeight=this.source.naturalHeight||this.source.videoHeight||this.source.height,this._updateDimensions()),this.emit("update",this)},e.prototype._updateDimensions=function(){this.width=this.realWidth/this.resolution,this.height=this.realHeight/this.resolution,this.isPowerOfTwo=v.default.isPow2(this.realWidth)&&v.default.isPow2(this.realHeight)},e.prototype.loadSource=function(t){var e=this.isLoading;this.hasLoaded=!1,this.isLoading=!1,e&&this.source&&(this.source.onload=null,this.source.onerror=null);var r=!this.source;if(this.source=t,(t.src&&t.complete||t.getContext)&&t.width&&t.height)this._updateImageType(),"svg"===this.imageType?this._loadSvgSource():this._sourceLoaded(),r&&this.emit("loaded",this);else if(!t.getContext){this.isLoading=!0;var n=this;if(t.onload=function(){if(n._updateImageType(),t.onload=null,t.onerror=null,n.isLoading){if(n.isLoading=!1,n._sourceLoaded(),"svg"===n.imageType)return void n._loadSvgSource();n.emit("loaded",n)}},t.onerror=function(){t.onload=null,t.onerror=null,n.isLoading&&(n.isLoading=!1,n.emit("error",n))},t.complete&&t.src){if(t.onload=null,t.onerror=null,"svg"===n.imageType)return void n._loadSvgSource();this.isLoading=!1,t.width&&t.height?(this._sourceLoaded(),e&&this.emit("loaded",this)):e&&this.emit("error",this)}}},e.prototype._updateImageType=function(){if(this.imageUrl){var t=(0,a.decomposeDataUri)(this.imageUrl),e=void 0;if(t&&"image"===t.mediaType){var r=t.subType.split("+")[0];if(!(e=(0,a.getUrlFileExtension)("."+r)))throw new Error("Invalid image type in data URI.")}else(e=(0,a.getUrlFileExtension)(this.imageUrl))||(e="png");this.imageType=e}},e.prototype._loadSvgSource=function(){if("svg"===this.imageType){var t=(0,a.decomposeDataUri)(this.imageUrl);t?this._loadSvgSourceUsingDataUri(t):this._loadSvgSourceUsingXhr()}},e.prototype._loadSvgSourceUsingDataUri=function(t){var e=void 0;if("base64"===t.encoding){if(!atob)throw new Error("Your browser doesn't support base64 conversions.");e=atob(t.data)}else e=t.data;this._loadSvgSourceUsingString(e)},e.prototype._loadSvgSourceUsingXhr=function(){var t=this,e=new XMLHttpRequest;e.onload=function(){if(e.readyState!==e.DONE||200!==e.status)throw new Error("Failed to load SVG using XHR.");t._loadSvgSourceUsingString(e.response)},e.onerror=function(){return t.emit("error",t)},e.open("GET",this.imageUrl,!0),e.send()},e.prototype._loadSvgSourceUsingString=function(t){var r=(0,a.getSvgSize)(t),n=r.width,i=r.height;if(!n||!i)throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them.");this.realWidth=Math.round(n*this.sourceScale),this.realHeight=Math.round(i*this.sourceScale),this._updateDimensions();var o=document.createElement("canvas");o.width=this.realWidth,o.height=this.realHeight,o._pixiId="canvas_"+(0,a.uid)(),o.getContext("2d").drawImage(this.source,0,0,n,i,0,0,this.realWidth,this.realHeight),this.origSource=this.source,this.source=o,e.addToCache(this,o._pixiId),this.isLoading=!1,this._sourceLoaded(),this.emit("loaded",this)},e.prototype._sourceLoaded=function(){this.hasLoaded=!0,this.update()},e.prototype.destroy=function(){this.imageUrl&&(delete a.TextureCache[this.imageUrl],this.imageUrl=null,navigator.isCocoonJS||(this.source.src="")),this.source=null,this.dispose(),e.removeFromCache(this),this.textureCacheIds=null,this._destroyed=!0},e.prototype.dispose=function(){this.emit("dispose",this)},e.prototype.updateSourceImage=function(t){this.source.src=t,this.loadSource(this.source)},e.fromImage=function(t,r,n,i){var o=a.BaseTextureCache[t];if(!o){var s=new Image;void 0===r&&0!==t.indexOf("data:")?s.crossOrigin=(0,f.default)(t):r&&(s.crossOrigin="string"==typeof r?r:"anonymous"),o=new e(s,n),o.imageUrl=t,i&&(o.sourceScale=i),o.resolution=(0,a.getResolutionOfUrl)(t),s.src=t,e.addToCache(o,t)}return o},e.fromCanvas=function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"canvas";t._pixiId||(t._pixiId=n+"_"+(0,a.uid)());var i=a.BaseTextureCache[t._pixiId];return i||(i=new e(t,r),e.addToCache(i,t._pixiId)),i},e.from=function(t,r,n){if("string"==typeof t)return e.fromImage(t,void 0,r,n);if(t instanceof HTMLImageElement){var i=t.src,o=a.BaseTextureCache[i];return o||(o=new e(t,r),o.imageUrl=i,n&&(o.sourceScale=n),o.resolution=(0,a.getResolutionOfUrl)(i),e.addToCache(o,i)),o}return t instanceof HTMLCanvasElement?e.fromCanvas(t,r):t},e.addToCache=function(t,e){e&&(-1===t.textureCacheIds.indexOf(e)&&t.textureCacheIds.push(e),a.BaseTextureCache[e]=t)},e.removeFromCache=function(t){if("string"==typeof t){var e=a.BaseTextureCache[t];if(e){var r=e.textureCacheIds.indexOf(t);return r>-1&&e.textureCacheIds.splice(r,1),delete a.BaseTextureCache[t],e}}else if(t&&t.textureCacheIds){for(var n=0;n0&&e>0,this._frame.width=this.orig.width=t,this._frame.height=this.orig.height=e,r||this.baseTexture.resize(t,e),this._updateUvs()},e.create=function(t,r,n,i){return new e(new u.default(t,r,n,i))},e}(l.default);r.default=c},{"./BaseRenderTexture":111,"./Texture":115}],114:[function(t,e,r){"use strict";function n(t,e){ +if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:null;n(this,t),this.baseTexture=e,this.textures={},this.animations={},this.data=r,this.resolution=this._updateResolution(i||this.baseTexture.imageUrl),this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}return i(t,null,[{key:"BATCH_SIZE",get:function(){return 1e3}}]),t.prototype._updateResolution=function(t){var e=this.data.meta.scale,r=(0,s.getResolutionOfUrl)(t,null);return null===r&&(r=void 0!==e?parseFloat(e):1),1!==r&&(this.baseTexture.resolution=r,this.baseTexture.update()),r},t.prototype.parse=function(e){this._batchIndex=0,this._callback=e,this._frameKeys.length<=t.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()},t.prototype._processFrames=function(e){for(var r=e,n=t.BATCH_SIZE,i=this.baseTexture.sourceScale;r-e=r.length)break;o=r[i++]}else{if(i=r.next(),i.done)break;o=i.value}var s=o;this.animations[e].push(this.textures[s])}}},t.prototype._parseComplete=function(){var t=this._callback;this._callback=null,this._batchIndex=0,t.call(this,this.textures)},t.prototype._nextBatch=function(){var e=this;this._processFrames(this._batchIndex*t.BATCH_SIZE),this._batchIndex++,setTimeout(function(){e._batchIndex*t.BATCH_SIZE0&&void 0!==arguments[0]&&arguments[0];for(var e in this.textures)this.textures[e].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,t&&this.baseTexture.destroy(),this.baseTexture=null},t}();r.default=a},{"../":65,"../utils":125}],115:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function a(t){t.destroy=function(){},t.on=function(){},t.once=function(){},t.emit=function(){}}r.__esModule=!0;var u=function(){function t(t,e){for(var r=0;r2&&void 0!==arguments[2]?arguments[2]:"canvas";return new e(l.default.fromCanvas(t,r,n))},e.fromVideo=function(t,r){return"string"==typeof t?e.fromVideoUrl(t,r):new e(d.default.fromVideo(t,r))},e.fromVideoUrl=function(t,r){return new e(d.default.fromUrl(t,r))},e.from=function(t){if("string"==typeof t){var r=m.TextureCache[t];if(!r){return null!==t.match(/\.(mp4|webm|ogg|h264|avi|mov)$/)?e.fromVideoUrl(t):e.fromImage(t)}return r}return t instanceof HTMLImageElement?new e(l.default.from(t)):t instanceof HTMLCanvasElement?e.fromCanvas(t,b.default.SCALE_MODE,"HTMLCanvasElement"):t instanceof HTMLVideoElement?e.fromVideo(t):t instanceof l.default?new e(t):t},e.fromLoader=function(t,r,n){var i=new l.default(t,void 0,(0,m.getResolutionOfUrl)(r)),o=new e(i);return i.imageUrl=r,n||(n=r),l.default.addToCache(o.baseTexture,n),e.addToCache(o,n),n!==r&&(l.default.addToCache(o.baseTexture,r),e.addToCache(o,r)),o},e.addToCache=function(t,e){e&&(-1===t.textureCacheIds.indexOf(e)&&t.textureCacheIds.push(e),m.TextureCache[e]=t)},e.removeFromCache=function(t){if("string"==typeof t){var e=m.TextureCache[t];if(e){var r=e.textureCacheIds.indexOf(t);return r>-1&&e.textureCacheIds.splice(r,1),delete m.TextureCache[t],e}}else if(t&&t.textureCacheIds){for(var n=0;nthis.baseTexture.width,s=r+i>this.baseTexture.height;if(o||s){var a=o&&s?"and":"or",u="X: "+e+" + "+n+" = "+(e+n)+" > "+this.baseTexture.width,h="Y: "+r+" + "+i+" = "+(r+i)+" > "+this.baseTexture.height;throw new Error("Texture Error: frame does not fit inside the base Texture dimensions: "+u+" "+a+" "+h)}this.valid=n&&i&&this.baseTexture.hasLoaded,this.trim||this.rotate||(this.orig=t),this.valid&&this._updateUvs()}},{key:"rotate",get:function(){return this._rotate},set:function(t){this._rotate=t,this.valid&&this._updateUvs()}},{key:"width",get:function(){return this.orig.width}},{key:"height",get:function(){return this.orig.height}}]),e}(g.default);r.default=x,x.EMPTY=new x(new l.default),a(x.EMPTY),a(x.EMPTY.baseTexture),x.WHITE=function(){var t=document.createElement("canvas");t.width=10,t.height=10;var e=t.getContext("2d");return e.fillStyle="white",e.fillRect(0,0,10,10),new x(new l.default(t))}(),a(x.WHITE),a(x.WHITE.baseTexture)},{"../math":70,"../settings":101,"../utils":125,"./BaseTexture":112,"./TextureUvs":117,"./VideoBaseTexture":118,eventemitter3:3}],116:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r0&&!1===t.paused&&!1===t.ended&&t.readyState>2},e.prototype._isSourceReady=function(){return 3===this.source.readyState||4===this.source.readyState},e.prototype._onPlayStart=function(){this.hasLoaded||this._onCanPlay(),!this._isAutoUpdating&&this.autoUpdate&&(d.shared.add(this.update,this,f.UPDATE_PRIORITY.HIGH),this._isAutoUpdating=!0)},e.prototype._onPlayStop=function(){this._isAutoUpdating&&(d.shared.remove(this.update,this),this._isAutoUpdating=!1)},e.prototype._onCanPlay=function(){this.hasLoaded=!0,this.source&&(this.source.removeEventListener("canplay",this._onCanPlay),this.source.removeEventListener("canplaythrough",this._onCanPlay),this.width=this.source.videoWidth,this.height=this.source.videoHeight,this.__loaded||(this.__loaded=!0,this.emit("loaded",this)),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.source.play())},e.prototype.destroy=function(){this._isAutoUpdating&&d.shared.remove(this.update,this),this.source&&this.source._pixiId&&(l.default.removeFromCache(this.source._pixiId),delete this.source._pixiId,this.source.pause(),this.source.src="",this.source.load()),t.prototype.destroy.call(this)},e.fromVideo=function(t,r){t._pixiId||(t._pixiId="video_"+(0,c.uid)());var n=c.BaseTextureCache[t._pixiId];return n||(n=new e(t,r),l.default.addToCache(n,t._pixiId)),n},e.fromUrl=function(t,r,n){var i=document.createElement("video");i.setAttribute("webkit-playsinline",""),i.setAttribute("playsinline","");var o=Array.isArray(t)?t[0].src||t[0]:t.src||t;if(void 0===n&&0!==o.indexOf("data:")?i.crossOrigin=(0,v.default)(o):n&&(i.crossOrigin="string"==typeof n?n:"anonymous"),Array.isArray(t))for(var s=0;s2&&void 0!==arguments[2]?arguments[2]:u.UPDATE_PRIORITY.NORMAL;return this._addListener(new l.default(t,e,r))},t.prototype.addOnce=function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:u.UPDATE_PRIORITY.NORMAL;return this._addListener(new l.default(t,e,r,!0))},t.prototype._addListener=function(t){var e=this._head.next,r=this._head;if(e){for(;e;){if(t.priority>e.priority){t.connect(r);break}r=e,e=e.next}t.previous||t.connect(r)}else t.connect(r);return this._startIfPossible(),this},t.prototype.remove=function(t,e){for(var r=this._head.next;r;)r=r.match(t,e)?r.destroy():r.next;return this._head.next||this._cancelIfNeeded(),this},t.prototype.start=function(){this.started||(this.started=!0,this._requestIfNeeded())},t.prototype.stop=function(){this.started&&(this.started=!1,this._cancelIfNeeded())},t.prototype.destroy=function(){this.stop();for(var t=this._head.next;t;)t=t.destroy(!0);this._head.destroy(),this._head=null},t.prototype.update=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:performance.now(),e=void 0;if(t>this.lastTime){e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),this.deltaTime=e*a.default.TARGET_FPMS*this.speed;for(var r=this._head,n=r.next;n;)n=n.emit(this.deltaTime);r.next||this._cancelIfNeeded()}else this.deltaTime=this.elapsedMS=0;this.lastTime=t},o(t,[{key:"FPS",get:function(){return 1e3/this.elapsedMS}},{key:"minFPS",get:function(){return 1e3/this._maxElapsedMS},set:function(t){var e=Math.min(Math.max(0,t)/1e3,a.default.TARGET_FPMS);this._maxElapsedMS=1/e}}]),t}();r.default=c},{"../const":46,"../settings":101,"./TickerListener":120}],120:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];n(this,t),this.fn=e,this.context=r,this.priority=i,this.once=o,this.next=null,this.previous=null,this._destroyed=!1}return t.prototype.match=function(t,e){return e=e||null,this.fn===t&&this.context===e},t.prototype.emit=function(t){this.fn&&(this.context?this.fn.call(this.context,t):this.fn(t));var e=this.next;return this.once&&this.destroy(!0),this._destroyed&&(this.next=null),e},t.prototype.connect=function(t){this.previous=t,t.next&&(t.next.previous=this),this.next=t.next,t.next=this},t.prototype.destroy=function(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._destroyed=!0,this.fn=null,this.context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);var e=this.next;return this.next=t?null:e,this.previous=null,e},t}();r.default=i},{}],121:[function(t,e,r){"use strict";r.__esModule=!0,r.Ticker=r.shared=void 0;var n=t("./Ticker"),i=function(t){return t&&t.__esModule?t:{default:t}}(n),o=new i.default;o.autoStart=!0,o.destroy=function(){},r.shared=o,r.Ticker=i.default},{"./Ticker":119}],122:[function(t,e,r){"use strict";function n(){return!(!!navigator.platform&&/iPad|iPhone|iPod/.test(navigator.platform))}r.__esModule=!0,r.default=n},{}],123:[function(t,e,r){"use strict";function n(t){for(var e=6*t,r=new Uint16Array(e),n=0,i=0;n1&&void 0!==arguments[1]?arguments[1]:window.location;if(0===t.indexOf("data:"))return"";e=e||window.location,s||(s=document.createElement("a")),s.href=t,t=o.default.parse(s.href);var r=!t.port&&""===e.port||t.port===e.port;return t.hostname===e.hostname&&r&&t.protocol===e.protocol?"":"anonymous"}r.__esModule=!0,r.default=n;var i=t("url"),o=function(t){return t&&t.__esModule?t:{default:t}}(i),s=void 0},{url:38}],125:[function(t,e,r){"use strict";function n(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function i(t){return t&&t.__esModule?t:{default:t}}function o(){return++U}function s(t,e){return e=e||[],e[0]=(t>>16&255)/255,e[1]=(t>>8&255)/255,e[2]=(255&t)/255,e}function a(t){return t=t.toString(16),"#"+(t="000000".substr(0,6-t.length)+t)}function u(t){return(255*t[0]<<16)+(255*t[1]<<8)+(255*t[2]|0)}function h(t,e){var r=S.default.RETINA_PREFIX.exec(t);return r?parseFloat(r[1]):void 0!==e?e:1}function l(t){var e=w.DATA_URI.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,charset:e[3]?e[3].toLowerCase():void 0,encoding:e[4]?e[4].toLowerCase():void 0,data:e[5]}}function c(t){var e=w.URL_FILE_EXTENSION.exec(t);if(e)return e[1].toLowerCase()}function d(t){var e=w.SVG_SIZE.exec(t),r={};return e&&(r[e[1]]=Math.round(parseFloat(e[3])),r[e[5]]=Math.round(parseFloat(e[7]))),r}function f(){X=!0}function p(t){if(!X){if(navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var e=["\n %c %c %c PixiJS "+w.VERSION+" - ✰ "+t+" ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n","background: #ff66a5; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff66a5; background: #030307; padding:5px 0;","background: #ff66a5; padding:5px 0;","background: #ffc3dc; padding:5px 0;","background: #ff66a5; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;","color: #ff2424; background: #fff; padding:5px 0;"];window.console.log.apply(console,e)}else window.console&&window.console.log("PixiJS "+w.VERSION+" - "+t+" - http://www.pixijs.com/");X=!0}}function v(){var t={stencil:!0,failIfMajorPerformanceCaveat:!0};try{if(!window.WebGLRenderingContext)return!1;var e=document.createElement("canvas"),r=e.getContext("webgl",t)||e.getContext("experimental-webgl",t),n=!(!r||!r.getContextAttributes().stencil);if(r){var i=r.getExtension("WEBGL_lose_context");i&&i.loseContext()}return r=null,n}catch(t){return!1}}function g(t){return 0===t?0:t<0?-1:1}function y(){var t=void 0;for(t in G)G[t].destroy();for(t in W)W[t].destroy()}function m(){var t=void 0;for(t in G)delete G[t];for(t in W)delete W[t]}function _(t,e){return H[e?1:0][t]}function b(t,e){if(1===e)return(255*e<<24)+t;if(0===e)return 0;var r=t>>16&255,n=t>>8&255,i=255&t;return r=r*e+.5|0,n=n*e+.5|0,i=i*e+.5|0,(255*e<<24)+(r<<16)+(n<<8)+i}function x(t,e,r,n){return r=r||new Float32Array(4),n||void 0===n?(r[0]=t[0]*e,r[1]=t[1]*e,r[2]=t[2]*e):(r[0]=t[0],r[1]=t[1],r[2]=t[2]),r[3]=e,r}function T(t,e,r,n){return r=r||new Float32Array(4),r[0]=(t>>16&255)/255,r[1]=(t>>8&255)/255,r[2]=(255&t)/255,(n||void 0===n)&&(r[0]*=e,r[1]*=e,r[2]*=e),r[3]=e,r}r.__esModule=!0,r.premultiplyBlendMode=r.BaseTextureCache=r.TextureCache=r.earcut=r.mixins=r.pluginTarget=r.EventEmitter=r.removeItems=r.isMobile=void 0,r.uid=o,r.hex2rgb=s,r.hex2string=a,r.rgb2hex=u,r.getResolutionOfUrl=h,r.decomposeDataUri=l,r.getUrlFileExtension=c,r.getSvgSize=d,r.skipHello=f,r.sayHello=p,r.isWebGLSupported=v,r.sign=g,r.destroyTextureCache=y,r.clearTextureCache=m,r.correctBlendMode=_,r.premultiplyTint=b,r.premultiplyRgba=x,r.premultiplyTintToRgba=T;var w=t("../const"),E=t("../settings"),S=i(E),O=t("eventemitter3"),M=i(O),P=t("./pluginTarget"),C=i(P),R=t("./mixin"),A=n(R),I=t("ismobilejs"),D=n(I),L=t("remove-array-items"),N=i(L),B=t("./mapPremultipliedBlendModes"),F=i(B),k=t("earcut"),j=i(k),U=0,X=!1;r.isMobile=D,r.removeItems=N.default,r.EventEmitter=M.default,r.pluginTarget=C.default,r.mixins=A,r.earcut=j.default;var G=r.TextureCache=Object.create(null),W=r.BaseTextureCache=Object.create(null),H=r.premultiplyBlendMode=(0,F.default)()},{"../const":46,"../settings":101,"./mapPremultipliedBlendModes":126,"./mixin":128,"./pluginTarget":129,earcut:2,eventemitter3:3,ismobilejs:4,"remove-array-items":31}],126:[function(t,e,r){"use strict";function n(){for(var t=[],e=[],r=0;r<32;r++)t[r]=r,e[r]=r;t[i.BLEND_MODES.NORMAL_NPM]=i.BLEND_MODES.NORMAL,t[i.BLEND_MODES.ADD_NPM]=i.BLEND_MODES.ADD,t[i.BLEND_MODES.SCREEN_NPM]=i.BLEND_MODES.SCREEN,e[i.BLEND_MODES.NORMAL]=i.BLEND_MODES.NORMAL_NPM,e[i.BLEND_MODES.ADD]=i.BLEND_MODES.ADD_NPM,e[i.BLEND_MODES.SCREEN]=i.BLEND_MODES.SCREEN_NPM;var n=[];return n.push(e),n.push(t),n}r.__esModule=!0,r.default=n;var i=t("../const")},{"../const":46}],127:[function(t,e,r){"use strict";function n(t){return o.default.tablet||o.default.phone?4:t}r.__esModule=!0,r.default=n;var i=t("ismobilejs"),o=function(t){return t&&t.__esModule?t:{default:t}}(i)},{ismobilejs:4}],128:[function(t,e,r){"use strict";function n(t,e){if(t&&e)for(var r=Object.keys(e),n=0;n1?this._fontStyle="italic":t.indexOf("oblique")>-1?this._fontStyle="oblique":this._fontStyle="normal",t.indexOf("small-caps")>-1?this._fontVariant="small-caps":this._fontVariant="normal";var e=t.split(" "),r=-1;this._fontSize=26;for(var i=0;i-1&&r=this._durations[this.currentFrame];)n-=this._durations[this.currentFrame]*i,this._currentTime+=i;this._currentTime+=n/this._durations[this.currentFrame]}else this._currentTime+=e;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):r!==this.currentFrame&&(this.loop&&this.onLoop&&(this.animationSpeed>0&&this.currentFramer&&this.onLoop()),this.updateTexture())},e.prototype.updateTexture=function(){this._texture=this._textures[this.currentFrame],this._textureID=-1,this.cachedTint=16777215,this.onFrameChange&&this.onFrameChange(this.currentFrame)},e.prototype.destroy=function(e){this.stop(),t.prototype.destroy.call(this,e)},e.fromFrames=function(t){for(var r=[],n=0;n1&&void 0!==arguments[1]?arguments[1]:{};i(this,e);var s=o(this,t.call(this));return s._textWidth=0,s._textHeight=0,s._glyphs=[],s._font={tint:void 0!==n.tint?n.tint:16777215,align:n.align||"left",name:null,size:0},s.font=n.font,s._text=r,s._maxWidth=0,s._maxLineHeight=0,s._letterSpacing=0,s._anchor=new c.default(function(){s.dirty=!0},s,0,0),s.dirty=!1,s.updateText(),s}return s(e,t),e.prototype.updateText=function(){for(var t=e.fonts[this._font.name],r=this._font.size/t.size,n=new h.Point,i=[],o=[],s=this.text.replace(/(?:\r\n|\r)/g,"\n"),a=s.length,u=this._maxWidth*t.size/this._font.size,l=null,c=0,d=0,f=0,p=-1,v=0,g=0,y=0,m=0;m0&&n.x>u&&(++g,h.utils.removeItems(i,1+p-g,1+m-p),m=p,p=-1,o.push(v),d=Math.max(d,v),f++,n.x=0,n.y+=t.lineHeight,l=null))}else o.push(c),d=Math.max(d,c),++f,++g,n.x=0,n.y+=t.lineHeight,l=null}var T=s.charAt(s.length-1);"\r"!==T&&"\n"!==T&&(/(?:\s)/.test(T)&&(c=v),o.push(c),d=Math.max(d,c));for(var w=[],E=0;E<=f;E++){var S=0;"right"===this._font.align?S=d-o[E]:"center"===this._font.align&&(S=(d-o[E])/2),w.push(S)}for(var O=i.length,M=this.tint,P=0;P=0?t:16777215,this.dirty=!0}},{key:"align",get:function(){return this._font.align},set:function(t){this._font.align=t||"left",this.dirty=!0}},{key:"anchor",get:function(){return this._anchor},set:function(t){"number"==typeof t?this._anchor.set(t):this._anchor.copy(t)}},{key:"font",get:function(){return this._font},set:function(t){t&&("string"==typeof t?(t=t.split(" "),this._font.name=1===t.length?t[0]:t.slice(1).join(" "),this._font.size=t.length>=2?parseInt(t[0],10):e.fonts[this._font.name].size):(this._font.name=t.name,this._font.size="number"==typeof t.size?t.size:parseInt(t.size,10)),this.dirty=!0)}},{key:"text",get:function(){return this._text},set:function(t){t=t.toString()||" ",this._text!==t&&(this._text=t,this.dirty=!0)}},{key:"maxWidth",get:function(){return this._maxWidth},set:function(t){this._maxWidth!==t&&(this._maxWidth=t,this.dirty=!0)}},{key:"maxLineHeight",get:function(){return this.validate(),this._maxLineHeight}},{key:"textWidth",get:function(){return this.validate(),this._textWidth}},{key:"letterSpacing",get:function(){return this._letterSpacing},set:function(t){this._letterSpacing!==t&&(this._letterSpacing=t,this.dirty=!0)}},{key:"textHeight",get:function(){return this.validate(),this._textHeight}}]),e}(h.Container);r.default=v,v.fonts={}},{"../core":65,"../core/math/ObservablePoint":68,"../core/settings":101,"../core/utils":125}],137:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:100,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:100;n(this,e);var a=i(this,t.call(this,r));return a.tileTransform=new u.TransformStatic,a._width=o,a._height=s,a._canvasPattern=null,a.uvTransform=r.transform||new u.TextureMatrix(r),a.pluginName="tilingSprite",a.uvRespectAnchor=!1,a}return o(e,t),e.prototype._onTextureUpdate=function(){this.uvTransform&&(this.uvTransform.texture=this._texture),this.cachedTint=16777215},e.prototype._renderWebGL=function(t){var e=this._texture;e&&e.valid&&(this.tileTransform.updateLocalTransform(),this.uvTransform.update(),t.setObjectRenderer(t.plugins[this.pluginName]),t.plugins[this.pluginName].render(this))},e.prototype._renderCanvas=function(t){var e=this._texture;if(e.baseTexture.hasLoaded){var r=t.context,n=this.worldTransform,i=t.resolution,o=e.baseTexture,s=o.resolution,a=this.tilePosition.x/this.tileScale.x%e._frame.width*s,h=this.tilePosition.y/this.tileScale.y%e._frame.height*s;if(this._textureID!==this._texture._updateID||this.cachedTint!==this.tint){this._textureID=this._texture._updateID;var c=new u.CanvasRenderTarget(e._frame.width,e._frame.height,s);16777215!==this.tint?(this.tintedTexture=l.default.getTintedTexture(this,this.tint),c.context.drawImage(this.tintedTexture,0,0)):c.context.drawImage(o.source,-e._frame.x*s,-e._frame.y*s),this.cachedTint=this.tint,this._canvasPattern=c.context.createPattern(c.canvas,"repeat")}r.globalAlpha=this.worldAlpha,r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),t.setBlendMode(this.blendMode),r.fillStyle=this._canvasPattern,r.scale(this.tileScale.x/s,this.tileScale.y/s);var d=this.anchor.x*-this._width,f=this.anchor.y*-this._height;this.uvRespectAnchor?(r.translate(a,h),r.fillRect(-a+d,-h+f,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s)):(r.translate(a+d,h+f),r.fillRect(-a,-h,this._width/this.tileScale.x*s,this._height/this.tileScale.y*s))}},e.prototype._calculateBounds=function(){var t=this._width*-this._anchor._x,e=this._height*-this._anchor._y,r=this._width*(1-this._anchor._x),n=this._height*(1-this._anchor._y);this._bounds.addFrame(this.transform,t,e,r,n)},e.prototype.getLocalBounds=function(e){return 0===this.children.length?(this._bounds.minX=this._width*-this._anchor._x,this._bounds.minY=this._height*-this._anchor._y,this._bounds.maxX=this._width*(1-this._anchor._x),this._bounds.maxY=this._height*(1-this._anchor._y),e||(this._localBoundsRect||(this._localBoundsRect=new u.Rectangle),e=this._localBoundsRect),this._bounds.getRectangle(e)):t.prototype.getLocalBounds.call(this,e)},e.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,c);var e=this._width,r=this._height,n=-e*this.anchor._x;if(c.x>=n&&c.x=i&&c.y0&&void 0!==arguments[0]?arguments[0]:new i.Point,e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.parent?this.parent.toGlobal(this.position,t,e):(t.x=this.position.x,t.y=this.position.y),t}},{"../core":65}],141:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0,r.BitmapText=r.TilingSpriteRenderer=r.TilingSprite=r.AnimatedSprite=void 0;var i=t("./AnimatedSprite");Object.defineProperty(r,"AnimatedSprite",{enumerable:!0,get:function(){return n(i).default}});var o=t("./TilingSprite");Object.defineProperty(r,"TilingSprite",{enumerable:!0,get:function(){return n(o).default}});var s=t("./webgl/TilingSpriteRenderer");Object.defineProperty(r,"TilingSpriteRenderer",{enumerable:!0,get:function(){return n(s).default}});var a=t("./BitmapText");Object.defineProperty(r,"BitmapText",{enumerable:!0,get:function(){return n(a).default}}),t("./cacheAsBitmap"),t("./getChildByName"),t("./getGlobalPosition")},{"./AnimatedSprite":135,"./BitmapText":136,"./TilingSprite":137,"./cacheAsBitmap":138,"./getChildByName":139,"./getGlobalPosition":140,"./webgl/TilingSpriteRenderer":142}],142:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=t("../../core"),a=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(s),u=t("../../core/const"),h=(t("path"),new a.Matrix),l=function(t){function e(r){n(this,e);var o=i(this,t.call(this,r));return o.shader=null,o.simpleShader=null,o.quad=null,o}return o(e,t),e.prototype.onContextChange=function(){var t=this.renderer.gl;this.shader=new a.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n gl_FragColor = sample * uColor;\n}\n"),this.simpleShader=new a.Shader(t,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = sample * uColor;\n}\n"),this.renderer.bindVao(null),this.quad=new a.Quad(t,this.renderer.state.attribState),this.quad.initVao(this.shader)},e.prototype.render=function(t){var e=this.renderer,r=this.quad;e.bindVao(r.vao);var n=r.vertices;n[0]=n[6]=t._width*-t.anchor.x,n[1]=n[3]=t._height*-t.anchor.y,n[2]=n[4]=t._width*(1-t.anchor.x),n[5]=n[7]=t._height*(1-t.anchor.y),t.uvRespectAnchor&&(n=r.uvs,n[0]=n[6]=-t.anchor.x,n[1]=n[3]=-t.anchor.y,n[2]=n[4]=1-t.anchor.x,n[5]=n[7]=1-t.anchor.y),r.upload();var i=t._texture,o=i.baseTexture,s=t.tileTransform.localTransform,l=t.uvTransform,c=o.isPowerOfTwo&&i.frame.width===o.width&&i.frame.height===o.height;c&&(o._glTextures[e.CONTEXT_UID]?c=o.wrapMode!==u.WRAP_MODES.CLAMP:o.wrapMode===u.WRAP_MODES.CLAMP&&(o.wrapMode=u.WRAP_MODES.REPEAT));var d=c?this.simpleShader:this.shader;e.bindShader(d);var f=i.width,p=i.height,v=t._width,g=t._height;h.set(s.a*f/v,s.b*f/g,s.c*p/v,s.d*p/g,s.tx/v,s.ty/g),h.invert(),c?h.prepend(l.mapCoord):(d.uniforms.uMapCoord=l.mapCoord.toArray(!0),d.uniforms.uClampFrame=l.uClampFrame,d.uniforms.uClampOffset=l.uClampOffset),d.uniforms.uTransform=h.toArray(!0),d.uniforms.uColor=a.utils.premultiplyTintToRgba(t.tint,t.worldAlpha,d.uniforms.uColor,o.premultipliedAlpha),d.uniforms.translationMatrix=t.transform.worldTransform.toArray(!0),d.uniforms.uSampler=e.bindTexture(i),e.setBlendMode(a.utils.correctBlendMode(t.blendMode,o.premultipliedAlpha)),r.vao.draw(this.renderer.gl.TRIANGLES,6,0)},e}(a.ObjectRenderer);r.default=l,a.WebGLRenderer.registerPlugin("tilingSprite",l)},{"../../core":65,"../../core/const":46,path:8}],143:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:1;n(this,e);var o=i(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n"));return o.alpha=r,o.glShaderKey="alpha",o}return o(e,t),s(e,[{key:"alpha",get:function(){return this.uniforms.uAlpha},set:function(t){this.uniforms.uAlpha=t}}]),e}(u.Filter));r.default=h},{"../../core":65,path:8}],144:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r=r&&(u=t-h-1),l=l.replace("%value%",e[u]),s+=l,s+="\n"}return n=n.replace("%blur%",s),n=n.replace("%size%",t)}r.__esModule=!0,r.default=n;var i={5:[.153388,.221461,.250301],7:[.071303,.131514,.189879,.214607],9:[.028532,.067234,.124009,.179044,.20236],11:[.0093,.028002,.065984,.121703,.175713,.198596],13:[.002406,.009255,.027867,.065666,.121117,.174868,.197641],15:[489e-6,.002403,.009246,.02784,.065602,.120999,.174697,.197448]},o=["varying vec2 vBlurTexCoords[%size%];","uniform sampler2D uSampler;","void main(void)","{"," gl_FragColor = vec4(0.0);"," %blur%","}"].join("\n")},{}],148:[function(t,e,r){"use strict";function n(t,e){var r=Math.ceil(t/2),n=i,o="",s=void 0;s=e?"vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);":"vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);";for(var a=0;ae;)r-=2;return r}r.__esModule=!0,r.default=n},{}],150:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n"));return r.uniforms.m=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],r.alpha=1,r}return o(e,t),e.prototype._loadMatrix=function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=t;e&&(this._multiply(r,this.uniforms.m,t),r=this._colorMatrix(r)),this.uniforms.m=r},e.prototype._multiply=function(t,e,r){return t[0]=e[0]*r[0]+e[1]*r[5]+e[2]*r[10]+e[3]*r[15],t[1]=e[0]*r[1]+e[1]*r[6]+e[2]*r[11]+e[3]*r[16],t[2]=e[0]*r[2]+e[1]*r[7]+e[2]*r[12]+e[3]*r[17],t[3]=e[0]*r[3]+e[1]*r[8]+e[2]*r[13]+e[3]*r[18],t[4]=e[0]*r[4]+e[1]*r[9]+e[2]*r[14]+e[3]*r[19]+e[4],t[5]=e[5]*r[0]+e[6]*r[5]+e[7]*r[10]+e[8]*r[15],t[6]=e[5]*r[1]+e[6]*r[6]+e[7]*r[11]+e[8]*r[16],t[7]=e[5]*r[2]+e[6]*r[7]+e[7]*r[12]+e[8]*r[17],t[8]=e[5]*r[3]+e[6]*r[8]+e[7]*r[13]+e[8]*r[18],t[9]=e[5]*r[4]+e[6]*r[9]+e[7]*r[14]+e[8]*r[19]+e[9],t[10]=e[10]*r[0]+e[11]*r[5]+e[12]*r[10]+e[13]*r[15],t[11]=e[10]*r[1]+e[11]*r[6]+e[12]*r[11]+e[13]*r[16],t[12]=e[10]*r[2]+e[11]*r[7]+e[12]*r[12]+e[13]*r[17],t[13]=e[10]*r[3]+e[11]*r[8]+e[12]*r[13]+e[13]*r[18],t[14]=e[10]*r[4]+e[11]*r[9]+e[12]*r[14]+e[13]*r[19]+e[14],t[15]=e[15]*r[0]+e[16]*r[5]+e[17]*r[10]+e[18]*r[15],t[16]=e[15]*r[1]+e[16]*r[6]+e[17]*r[11]+e[18]*r[16],t[17]=e[15]*r[2]+e[16]*r[7]+e[17]*r[12]+e[18]*r[17],t[18]=e[15]*r[3]+e[16]*r[8]+e[17]*r[13]+e[18]*r[18],t[19]=e[15]*r[4]+e[16]*r[9]+e[17]*r[14]+e[18]*r[19]+e[19],t},e.prototype._colorMatrix=function(t){var e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e},e.prototype.brightness=function(t,e){var r=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.greyscale=function(t,e){var r=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.blackAndWhite=function(t){var e=[.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.hue=function(t,e){t=(t||0)/180*Math.PI;var r=Math.cos(t),n=Math.sin(t),i=Math.sqrt,o=1/3,s=i(o),a=r+(1-r)*o,u=o*(1-r)-s*n,h=o*(1-r)+s*n,l=o*(1-r)+s*n,c=r+o*(1-r),d=o*(1-r)-s*n,f=o*(1-r)-s*n,p=o*(1-r)+s*n,v=r+o*(1-r),g=[a,u,h,0,0,l,c,d,0,0,f,p,v,0,0,0,0,0,1,0];this._loadMatrix(g,e)},e.prototype.contrast=function(t,e){var r=(t||0)+1,n=-.5*(r-1),i=[r,0,0,0,n,0,r,0,0,n,0,0,r,0,n,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.saturate=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments[1],r=2*t/3+1,n=-.5*(r-1),i=[r,n,n,0,0,n,r,n,0,0,n,n,r,0,0,0,0,0,1,0];this._loadMatrix(i,e)},e.prototype.desaturate=function(){this.saturate(-1)},e.prototype.negative=function(t){var e=[-1,0,0,1,0,0,-1,0,1,0,0,0,-1,1,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.sepia=function(t){var e=[.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.technicolor=function(t){var e=[1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.polaroid=function(t){var e=[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.toBGR=function(t){var e=[0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.kodachrome=function(t){var e=[1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.browni=function(t){var e=[.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.vintage=function(t){var e=[.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.colorTone=function(t,e,r,n,i){t=t||.2,e=e||.15,r=r||16770432,n=n||3375104;var o=(r>>16&255)/255,s=(r>>8&255)/255,a=(255&r)/255,u=(n>>16&255)/255,h=(n>>8&255)/255,l=(255&n)/255,c=[.3,.59,.11,0,0,o,s,a,t,0,u,h,l,e,0,o-u,s-h,a-l,0,0];this._loadMatrix(c,i)},e.prototype.night=function(t,e){t=t||.1;var r=[-2*t,-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.predator=function(t,e){var r=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(r,e)},e.prototype.lsd=function(t){var e=[2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0];this._loadMatrix(e,t)},e.prototype.reset=function(){var t=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0];this._loadMatrix(t,!1)},s(e,[{key:"matrix",get:function(){return this.uniforms.m},set:function(t){this.uniforms.m=t}},{key:"alpha",get:function(){return this.uniforms.uAlpha},set:function(t){this.uniforms.uAlpha=t}}]),e}(u.Filter));r.default=h,h.prototype.grayscale=h.prototype.greyscale},{"../../core":65,path:8}],151:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n'))}return o(e,t),e}(a.Filter));r.default=u},{"../../core":65,path:8}],153:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./fxaa/FXAAFilter");Object.defineProperty(r,"FXAAFilter",{enumerable:!0,get:function(){return n(i).default}});var o=t("./noise/NoiseFilter");Object.defineProperty(r,"NoiseFilter",{enumerable:!0,get:function(){return n(o).default}});var s=t("./displacement/DisplacementFilter");Object.defineProperty(r,"DisplacementFilter",{enumerable:!0,get:function(){return n(s).default}});var a=t("./blur/BlurFilter");Object.defineProperty(r,"BlurFilter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./blur/BlurXFilter");Object.defineProperty(r,"BlurXFilter",{enumerable:!0,get:function(){return n(u).default}});var h=t("./blur/BlurYFilter");Object.defineProperty(r,"BlurYFilter",{enumerable:!0,get:function(){return n(h).default}});var l=t("./colormatrix/ColorMatrixFilter");Object.defineProperty(r,"ColorMatrixFilter",{enumerable:!0,get:function(){return n(l).default}});var c=t("./alpha/AlphaFilter");Object.defineProperty(r,"AlphaFilter",{enumerable:!0,get:function(){return n(c).default}})},{"./alpha/AlphaFilter":143,"./blur/BlurFilter":144,"./blur/BlurXFilter":145,"./blur/BlurYFilter":146,"./colormatrix/ColorMatrixFilter":150,"./displacement/DisplacementFilter":151,"./fxaa/FXAAFilter":152,"./noise/NoiseFilter":154}],154:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:.5,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Math.random();n(this,e);var s=i(this,t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n"));return s.noise=r,s.seed=o,s}return o(e,t),s(e,[{key:"noise",get:function(){return this.uniforms.uNoise},set:function(t){this.uniforms.uNoise=t}},{key:"seed",get:function(){return this.uniforms.uSeed},set:function(t){this.uniforms.uSeed=t}}]),e}(u.Filter));r.default=h},{"../../core":65,path:8}],155:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(t,e){for(var r=0;r1&&void 0!==arguments[1]?arguments[1]:1;this.removeEvents(),this.interactionDOMElement=t,this.resolution=e,this.addEvents()},e.prototype.addEvents=function(){this.interactionDOMElement&&(h.ticker.shared.add(this.update,this,h.UPDATE_PRIORITY.INTERACTION),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="none",this.interactionDOMElement.style["-ms-touch-action"]="none"):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]="none"),this.supportsPointerEvents?(window.document.addEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("pointerover",this.onPointerOver,!0),window.addEventListener("pointercancel",this.onPointerCancel,!0),window.addEventListener("pointerup",this.onPointerUp,!0)):(window.document.addEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.addEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.addEventListener("mouseover",this.onPointerOver,!0),window.addEventListener("mouseup",this.onPointerUp,!0)),this.supportsTouchEvents&&(this.interactionDOMElement.addEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.addEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.addEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.addEventListener("touchmove",this.onPointerMove,!0)),this.eventsAdded=!0)},e.prototype.removeEvents=function(){this.interactionDOMElement&&(h.ticker.shared.remove(this.update,this),window.navigator.msPointerEnabled?(this.interactionDOMElement.style["-ms-content-zooming"]="",this.interactionDOMElement.style["-ms-touch-action"]=""):this.supportsPointerEvents&&(this.interactionDOMElement.style["touch-action"]=""),this.supportsPointerEvents?(window.document.removeEventListener("pointermove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("pointerdown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("pointerleave",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("pointerover",this.onPointerOver,!0),window.removeEventListener("pointercancel",this.onPointerCancel,!0),window.removeEventListener("pointerup",this.onPointerUp,!0)):(window.document.removeEventListener("mousemove",this.onPointerMove,!0),this.interactionDOMElement.removeEventListener("mousedown",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("mouseout",this.onPointerOut,!0),this.interactionDOMElement.removeEventListener("mouseover",this.onPointerOver,!0),window.removeEventListener("mouseup",this.onPointerUp,!0)),this.supportsTouchEvents&&(this.interactionDOMElement.removeEventListener("touchstart",this.onPointerDown,!0),this.interactionDOMElement.removeEventListener("touchcancel",this.onPointerCancel,!0),this.interactionDOMElement.removeEventListener("touchend",this.onPointerUp,!0),this.interactionDOMElement.removeEventListener("touchmove",this.onPointerMove,!0)),this.interactionDOMElement=null,this.eventsAdded=!1)},e.prototype.update=function(t){if(this._deltaTime+=t,!(this._deltaTime=0;l--){var c=h[l],d=this.processInteractive(t,c,r,n,a);if(d){if(!c.parent)continue;a=!1,d&&(t.target&&(n=!1),s=!0)}}return i&&(n&&!t.target&&!e.hitArea&&e.containsPoint&&e.containsPoint(o)&&(s=!0),e.interactive&&(s&&!t.target&&(t.target=e),r&&r(t,e,!!s))),s},e.prototype.onPointerDown=function(t){if(!this.supportsTouchEvents||"touch"!==t.pointerType){var e=this.normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&t.preventDefault();for(var r=e.length,n=0;ne?1:this._height/e;t[9]=t[11]=t[13]=t[15]=this._topHeight*r,t[17]=t[19]=t[21]=t[23]=this._height-this._bottomHeight*r,t[25]=t[27]=t[29]=t[31]=this._height},e.prototype.updateVerticalVertices=function(){var t=this.vertices,e=this._leftWidth+this._rightWidth,r=this._width>e?1:this._width/e;t[2]=t[10]=t[18]=t[26]=this._leftWidth*r,t[4]=t[12]=t[20]=t[28]=this._width-this._rightWidth*r,t[6]=t[14]=t[22]=t[30]=this._width},e.prototype._renderCanvas=function(t){var e=t.context;e.globalAlpha=this.worldAlpha,t.setBlendMode(this.blendMode);var r=this.worldTransform,n=t.resolution;t.roundPixels?e.setTransform(r.a*n,r.b*n,r.c*n,r.d*n,r.tx*n|0,r.ty*n|0):e.setTransform(r.a*n,r.b*n,r.c*n,r.d*n,r.tx*n,r.ty*n);var i=this._texture.baseTexture,o=i.source,s=i.width*i.resolution,a=i.height*i.resolution;this.drawSegment(e,o,s,a,0,1,10,11),this.drawSegment(e,o,s,a,2,3,12,13),this.drawSegment(e,o,s,a,4,5,14,15),this.drawSegment(e,o,s,a,8,9,18,19),this.drawSegment(e,o,s,a,10,11,20,21),this.drawSegment(e,o,s,a,12,13,22,23),this.drawSegment(e,o,s,a,16,17,26,27),this.drawSegment(e,o,s,a,18,19,28,29),this.drawSegment(e,o,s,a,20,21,30,31)},e.prototype.drawSegment=function(t,e,r,n,i,o,s,a){var u=this.uvs,h=this.vertices,l=(u[s]-u[i])*r,c=(u[a]-u[o])*n,d=h[s]-h[i],f=h[a]-h[o];l<1&&(l=1),c<1&&(c=1),d<1&&(d=1),f<1&&(f=1),t.drawImage(e,u[i]*r,u[o]*n,l,c,h[i],h[o],d,f)},e.prototype._refresh=function(){t.prototype._refresh.call(this);var e=this.uvs,r=this._texture;this._origWidth=r.orig.width,this._origHeight=r.orig.height;var n=1/this._origWidth,i=1/this._origHeight;e[0]=e[8]=e[16]=e[24]=0,e[1]=e[3]=e[5]=e[7]=0,e[6]=e[14]=e[22]=e[30]=1,e[25]=e[27]=e[29]=e[31]=1,e[2]=e[10]=e[18]=e[26]=n*this._leftWidth,e[4]=e[12]=e[20]=e[28]=1-n*this._rightWidth,e[9]=e[11]=e[13]=e[15]=i*this._topHeight,e[17]=e[19]=e[21]=e[23]=1-i*this._bottomHeight,this.updateHorizontalVertices(),this.updateVerticalVertices(),this.dirty++,this.multiplyUvs()},s(e,[{key:"width",get:function(){return this._width},set:function(t){this._width=t,this._refresh()}},{key:"height",get:function(){return this._height},set:function(t){this._height=t,this._refresh()}},{key:"leftWidth",get:function(){return this._leftWidth},set:function(t){this._leftWidth=t,this._refresh()}},{key:"rightWidth",get:function(){return this._rightWidth},set:function(t){this._rightWidth=t,this._refresh()}},{key:"topHeight",get:function(){return this._topHeight},set:function(t){this._topHeight=t,this._refresh()}},{key:"bottomHeight",get:function(){return this._bottomHeight},set:function(t){this._bottomHeight=t,this._refresh()}}]),e}(u.default);r.default=l},{"./Plane":168}],168:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}r.__esModule=!0;var s=t("./Mesh"),a=function(t){return t&&t.__esModule?t:{default:t}}(s),u=function(t){function e(r,o,s){n(this,e);var u=i(this,t.call(this,r));return u._ready=!0,u.verticesX=o||10,u.verticesY=s||10,u.drawMode=a.default.DRAW_MODES.TRIANGLES,u.refresh(),u}return o(e,t),e.prototype._refresh=function(){for(var t=this._texture,e=this.verticesX*this.verticesY,r=[],n=[],i=[],o=[],s=this.verticesX-1,a=this.verticesY-1,u=t.width/s,h=t.height/a,l=0;l1&&(l=1);var c=Math.sqrt(n*n+i*i),d=this._texture.height/2;n/=c,i/=c,n*=d,i*=d,o[h]=u.x+n,o[h+1]=u.y+i,o[h+2]=u.x-n,o[h+3]=u.y-i,e=u}},e.prototype.updateTransform=function(){this.autoUpdate&&this.refreshVertices(),this.containerUpdateTransform()},e}(a.default);r.default=u},{"./Mesh":166}],170:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=t("../../core"),o=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(i),s=t("../Mesh"),a=function(t){return t&&t.__esModule?t:{default:t}}(s),u=function(){function t(e){n(this,t),this.renderer=e}return t.prototype.render=function(t){var e=this.renderer,r=e.context,n=t.worldTransform,i=e.resolution;e.roundPixels?r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i|0,n.ty*i|0):r.setTransform(n.a*i,n.b*i,n.c*i,n.d*i,n.tx*i,n.ty*i),e.context.globalAlpha=t.worldAlpha,e.setBlendMode(t.blendMode),t.drawMode===a.default.DRAW_MODES.TRIANGLE_MESH?this._renderTriangleMesh(t):this._renderTriangles(t)},t.prototype._renderTriangleMesh=function(t){for(var e=t.vertices.length/2,r=0;r0){var O=S/Math.abs(t.worldTransform.a),M=S/Math.abs(t.worldTransform.d),P=(_+b+x)/3,C=(T+w+E)/3,R=_-P,A=T-C,I=Math.sqrt(R*R+A*A);_=P+R/I*(I+O),T=C+A/I*(I+M),R=b-P,A=w-C,I=Math.sqrt(R*R+A*A),b=P+R/I*(I+O),w=C+A/I*(I+M),R=x-P,A=E-C,I=Math.sqrt(R*R+A*A),x=P+R/I*(I+O),E=C+A/I*(I+M)}i.save(),i.beginPath(),i.moveTo(_,T),i.lineTo(b,w),i.lineTo(x,E),i.closePath(),i.clip();var D=d*g+v*p+f*y-g*p-v*f-d*y,L=_*g+v*x+b*y-g*x-v*b-_*y,N=d*b+_*p+f*x-b*p-_*f-d*x,B=d*g*x+v*b*p+_*f*y-_*g*p-v*f*x-d*b*y,F=T*g+v*E+w*y-g*E-v*w-T*y,k=d*w+T*p+f*E-w*p-T*f-d*E,j=d*g*E+v*w*p+T*f*y-T*g*p-v*f*E-d*w*y;i.transform(L/D,F/D,N/D,k/D,B/D,j/D),i.drawImage(h,0,0,l*u.resolution,c*u.resolution,0,0,l,c),i.restore(),this.renderer.invalidateBlendMode()}},t.prototype.renderMeshFlat=function(t){var e=this.renderer.context,r=t.vertices,n=r.length/2;e.beginPath();for(var i=1;i0&&void 0!==arguments[0]?arguments[0]:1500,o=arguments[1],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:16384,a=arguments.length>3&&void 0!==arguments[3]&&arguments[3];n(this,e);var h=i(this,t.call(this));return s>16384&&(s=16384),s>r&&(s=r),h._properties=[!1,!0,!1,!1,!1],h._maxSize=r,h._batchSize=s,h._glBuffers={},h._bufferUpdateIDs=[],h._updateID=0,h.interactiveChildren=!1,h.blendMode=u.BLEND_MODES.NORMAL,h.autoResize=a,h.roundPixels=!0,h.baseTexture=null,h.setProperties(o),h._tint=0,h.tintRgb=new Float32Array(4),h.tint=16777215,h}return o(e,t),e.prototype.setProperties=function(t){t&&(this._properties[0]="vertices"in t||"scale"in t?!!t.vertices||!!t.scale:this._properties[0],this._properties[1]="position"in t?!!t.position:this._properties[1],this._properties[2]="rotation"in t?!!t.rotation:this._properties[2],this._properties[3]="uvs"in t?!!t.uvs:this._properties[3],this._properties[4]="tint"in t||"alpha"in t?!!t.tint||!!t.alpha:this._properties[4])},e.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},e.prototype.renderWebGL=function(t){var e=this;this.visible&&!(this.worldAlpha<=0)&&this.children.length&&this.renderable&&(this.baseTexture||(this.baseTexture=this.children[0]._texture.baseTexture,this.baseTexture.hasLoaded||this.baseTexture.once("update",function(){return e.onChildrenChange(0)})),t.setObjectRenderer(t.plugins.particle),t.plugins.particle.render(this))},e.prototype.onChildrenChange=function(t){for(var e=Math.floor(t/this._batchSize);this._bufferUpdateIDs.lengthr&&(o=r);var s=t._glBuffers[i.CONTEXT_UID];s||(s=t._glBuffers[i.CONTEXT_UID]=this.generateBuffers(t));var a=e[0]._texture.baseTexture;this.renderer.setBlendMode(u.utils.correctBlendMode(t.blendMode,a.premultipliedAlpha));var h=i.gl,l=t.worldTransform.copy(this.tempMatrix);l.prepend(i._activeRenderTarget.projectionMatrix),this.shader.uniforms.projectionMatrix=l.toArray(!0),this.shader.uniforms.uColor=u.utils.premultiplyRgba(t.tintRgb,t.worldAlpha,this.shader.uniforms.uColor,a.premultipliedAlpha),this.shader.uniforms.uSampler=i.bindTexture(a);for(var c=!1,d=0,f=0;dn&&(p=n),f>=s.length){if(!t.autoResize)break;s.push(this._generateOneMoreBuffer(t))}var v=s[f];v.uploadDynamic(e,d,p);var g=t._bufferUpdateIDs[f]||0;c=c||v._updateID0?1:-1})},{}],179:[function(t,e,r){"use strict";Number.isInteger||(Number.isInteger=function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t})},{}],180:[function(t,e,r){"use strict";var n=t("object-assign"),i=function(t){return t&&t.__esModule?t:{default:t}}(n);Object.assign||(Object.assign=i.default)},{"object-assign":6}],181:[function(t,e,r){"use strict";t("./Object.assign"),t("./requestAnimationFrame"),t("./Math.sign"),t("./Number.isInteger"),window.ArrayBuffer||(window.ArrayBuffer=Array),window.Float32Array||(window.Float32Array=Array),window.Uint32Array||(window.Uint32Array=Array),window.Uint16Array||(window.Uint16Array=Array)},{"./Math.sign":178,"./Number.isInteger":179,"./Object.assign":180,"./requestAnimationFrame":182}],182:[function(t,e,r){(function(t){"use strict";if(Date.now&&Date.prototype.getTime||(Date.now=function(){return(new Date).getTime()}),!t.performance||!t.performance.now){var e=Date.now();t.performance||(t.performance={}),t.performance.now=function(){return Date.now()-e}}for(var r=Date.now(),n=["ms","moz","webkit","o"],i=0;i=0;n--)this.add(t.children[n]);return this},t.prototype.destroy=function(){this.ticking&&v.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null,this.limiter=null,this.uploadHookHelper=null},t}();r.default=g},{"../core":65,"./limiters/CountLimiter":186}],184:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function s(t,e){if(e instanceof u.BaseTexture){var r=e.source,n=0===r.width?t.canvas.width:Math.min(t.canvas.width,r.width),i=0===r.height?t.canvas.height:Math.min(t.canvas.height,r.height);return t.ctx.drawImage(r,0,0,n,i,0,0,t.canvas.width,t.canvas.height),!0}return!1}r.__esModule=!0;var a=t("../../core"),u=function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}(a),h=t("../BasePrepare"),l=function(t){return t&&t.__esModule?t:{default:t}}(h),c=16,d=function(t){function e(r){n(this,e);var o=i(this,t.call(this,r));return o.uploadHookHelper=o,o.canvas=document.createElement("canvas"),o.canvas.width=c,o.canvas.height=c,o.ctx=o.canvas.getContext("2d"),o.registerUploadHook(s),o}return o(e,t),e.prototype.destroy=function(){t.prototype.destroy.call(this),this.ctx=null,this.canvas=null},e}(l.default);r.default=d,u.CanvasRenderer.registerPlugin("prepare",d)},{"../../core":65,"../BasePrepare":183}],185:[function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}r.__esModule=!0;var i=t("./webgl/WebGLPrepare");Object.defineProperty(r,"webgl",{enumerable:!0,get:function(){return n(i).default}});var o=t("./canvas/CanvasPrepare");Object.defineProperty(r,"canvas",{enumerable:!0,get:function(){return n(o).default}});var s=t("./BasePrepare");Object.defineProperty(r,"BasePrepare",{enumerable:!0,get:function(){return n(s).default}});var a=t("./limiters/CountLimiter");Object.defineProperty(r,"CountLimiter",{enumerable:!0,get:function(){return n(a).default}});var u=t("./limiters/TimeLimiter");Object.defineProperty(r,"TimeLimiter",{enumerable:!0,get:function(){return n(u).default}})},{"./BasePrepare":183,"./canvas/CanvasPrepare":184,"./limiters/CountLimiter":186,"./limiters/TimeLimiter":187,"./webgl/WebGLPrepare":188}],186:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxItemsPerFrame=e,this.itemsLeft=0}return t.prototype.beginFrame=function(){this.itemsLeft=this.maxItemsPerFrame},t.prototype.allowedToUpload=function(){return this.itemsLeft-- >0},t}();r.default=i},{}],187:[function(t,e,r){"use strict";function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}r.__esModule=!0;var i=function(){function t(e){n(this,t),this.maxMilliseconds=e,this.frameStart=0}return t.prototype.beginFrame=function(){this.frameStart=Date.now()},t.prototype.allowedToUpload=function(){return Date.now()-this.frameStart 0) - (v < 0); +} + +//Computes absolute value of integer +exports.abs = function(v) { + var mask = v >> (INT_BITS-1); + return (v ^ mask) - mask; +} + +//Computes minimum of integers x and y +exports.min = function(x, y) { + return y ^ ((x ^ y) & -(x < y)); +} + +//Computes maximum of integers x and y +exports.max = function(x, y) { + return x ^ ((x ^ y) & -(x < y)); +} + +//Checks if a number is a power of two +exports.isPow2 = function(v) { + return !(v & (v-1)) && (!!v); +} + +//Computes log base 2 of v +exports.log2 = function(v) { + var r, shift; + r = (v > 0xFFFF) << 4; v >>>= r; + shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift; + shift = (v > 0xF ) << 2; v >>>= shift; r |= shift; + shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift; + return r | (v >> 1); +} + +//Computes log base 10 of v +exports.log10 = function(v) { + return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : + (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : + (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0; +} + +//Counts number of bits +exports.popCount = function(v) { + v = v - ((v >>> 1) & 0x55555555); + v = (v & 0x33333333) + ((v >>> 2) & 0x33333333); + return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24; +} + +//Counts number of trailing zeros +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 0x0000FFFF) c -= 16; + if (v & 0x00FF00FF) c -= 8; + if (v & 0x0F0F0F0F) c -= 4; + if (v & 0x33333333) c -= 2; + if (v & 0x55555555) c -= 1; + return c; +} +exports.countTrailingZeros = countTrailingZeros; + +//Rounds to next power of 2 +exports.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +} + +//Rounds down to previous power of 2 +exports.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v>>>1); +} + +//Computes parity of word +exports.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 0xf; + return (0x6996 >>> v) & 1; +} + +var REVERSE_TABLE = new Array(256); + +(function(tab) { + for(var i=0; i<256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = (r << s) & 0xff; + } +})(REVERSE_TABLE); + +//Reverse bits in a 32 bit word +exports.reverse = function(v) { + return (REVERSE_TABLE[ v & 0xff] << 24) | + (REVERSE_TABLE[(v >>> 8) & 0xff] << 16) | + (REVERSE_TABLE[(v >>> 16) & 0xff] << 8) | + REVERSE_TABLE[(v >>> 24) & 0xff]; +} + +//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes +exports.interleave2 = function(x, y) { + x &= 0xFFFF; + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y &= 0xFFFF; + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +//Extracts the nth interleaved component +exports.deinterleave2 = function(v, n) { + v = (v >>> n) & 0x55555555; + v = (v | (v >>> 1)) & 0x33333333; + v = (v | (v >>> 2)) & 0x0F0F0F0F; + v = (v | (v >>> 4)) & 0x00FF00FF; + v = (v | (v >>> 16)) & 0x000FFFF; + return (v << 16) >> 16; +} + + +//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes +exports.interleave3 = function(x, y, z) { + x &= 0x3FF; + x = (x | (x<<16)) & 4278190335; + x = (x | (x<<8)) & 251719695; + x = (x | (x<<4)) & 3272356035; + x = (x | (x<<2)) & 1227133513; + + y &= 0x3FF; + y = (y | (y<<16)) & 4278190335; + y = (y | (y<<8)) & 251719695; + y = (y | (y<<4)) & 3272356035; + y = (y | (y<<2)) & 1227133513; + x |= (y << 1); + + z &= 0x3FF; + z = (z | (z<<16)) & 4278190335; + z = (z | (z<<8)) & 251719695; + z = (z | (z<<4)) & 3272356035; + z = (z | (z<<2)) & 1227133513; + + return x | (z << 2); +} + +//Extracts nth interleaved component of a 3-tuple +exports.deinterleave3 = function(v, n) { + v = (v >>> n) & 1227133513; + v = (v | (v>>>2)) & 3272356035; + v = (v | (v>>>4)) & 251719695; + v = (v | (v>>>8)) & 4278190335; + v = (v | (v>>>16)) & 0x3FF; + return (v<<22)>>22; +} + +//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page) +exports.nextCombination = function(v) { + var t = v | (v - 1); + return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1)); +} + + +},{}],2:[function(require,module,exports){ +'use strict'; + +module.exports = earcut; +module.exports.default = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode || outerNode.next === outerNode.prev) return triangles; + + var minX, minY, maxX, maxY, x, y, invSize; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 1 / invSize : 0; + } + + earcutLinked(outerNode, triangles, dim, minX, minY, invSize); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, invSize) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, invSize), + maxZ = zOrder(maxTX, maxTY, minX, minY, invSize); + + var p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + + if (n !== ear.prev && n !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && + area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + // look for remaining points in decreasing z-order + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + // look for remaining points in increasing z-order + while (n && n.z <= maxZ) { + if (n !== ear.prev && n !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && + area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize); + earcutLinked(c, triangles, dim, minX, minY, invSize); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, invSize) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and inverse of the longer side of data bbox +function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) * invSize; + y = 32767 * (y - minY) * invSize; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertex index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertex nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; + +},{}],3:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @api private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {Mixed} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @api public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @api public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Boolean} exists Only check if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {String|Symbol} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Add a one-time listener for a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn The listener function. + * @param {Mixed} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++; + else if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [this._events[evt], listener]; + + return this; +}; + +/** + * Remove the listeners of a given event. + * + * @param {String|Symbol} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {Mixed} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn + && (!once || listeners.once) + && (!context || listeners.context === context) + ) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {String|Symbol} [event] The event name. + * @returns {EventEmitter} `this`. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { + if (--this._eventsCount === 0) this._events = new Events(); + else delete this._events[evt]; + } + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],4:[function(require,module,exports){ +!function(e){var n=/iPhone/i,t=/iPod/i,r=/iPad/i,a=/\bAndroid(?:.+)Mobile\b/i,p=/Android/i,l=/\bAndroid(?:.+)SD4930UR\b/i,b=/\bAndroid(?:.+)(?:KF[A-Z]{2,4})\b/i,f=/Windows Phone/i,u=/\bWindows(?:.+)ARM\b/i,c=/BlackBerry/i,s=/BB10/i,v=/Opera Mini/i,h=/\b(CriOS|Chrome)(?:.+)Mobile/i,w=/\Mobile(?:.+)Firefox\b/i;function m(e,i){return e.test(i)}function i(e){var i=e||("undefined"!=typeof navigator?navigator.userAgent:""),o=i.split("[FBAN");void 0!==o[1]&&(i=o[0]),void 0!==(o=i.split("Twitter"))[1]&&(i=o[0]);var d={apple:{phone:m(n,i)&&!m(f,i),ipod:m(t,i),tablet:!m(n,i)&&m(r,i)&&!m(f,i),device:(m(n,i)||m(t,i)||m(r,i))&&!m(f,i)},amazon:{phone:m(l,i),tablet:!m(l,i)&&m(b,i),device:m(l,i)||m(b,i)},android:{phone:!m(f,i)&&m(l,i)||!m(f,i)&&m(a,i),tablet:!m(f,i)&&!m(l,i)&&!m(a,i)&&(m(b,i)||m(p,i)),device:!m(f,i)&&(m(l,i)||m(b,i)||m(a,i)||m(p,i))},windows:{phone:m(f,i),tablet:m(u,i),device:m(f,i)||m(u,i)},other:{blackberry:m(c,i),blackberry10:m(s,i),opera:m(v,i),firefox:m(w,i),chrome:m(h,i),device:m(c,i)||m(s,i)||m(v,i)||m(w,i)||m(h,i)}};return d.any=d.apple.device||d.android.device||d.windows.device||d.other.device,d.phone=d.apple.phone||d.android.phone||d.windows.phone,d.tablet=d.apple.tablet||d.android.tablet||d.windows.tablet,d}"undefined"!=typeof module&&module.exports&&"undefined"==typeof window?module.exports=i:"undefined"!=typeof module&&module.exports&&"undefined"!=typeof window?module.exports=i():"function"==typeof define&&define.amd?define([],e.isMobile=i()):e.isMobile=i()}(this); +},{}],5:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + +var MiniSignalBinding = (function () { + function MiniSignalBinding(fn, once, thisArg) { + if (once === undefined) once = false; + + _classCallCheck(this, MiniSignalBinding); + + this._fn = fn; + this._once = once; + this._thisArg = thisArg; + this._next = this._prev = this._owner = null; + } + + _createClass(MiniSignalBinding, [{ + key: 'detach', + value: function detach() { + if (this._owner === null) return false; + this._owner.detach(this); + return true; + } + }]); + + return MiniSignalBinding; +})(); + +function _addMiniSignalBinding(self, node) { + if (!self._head) { + self._head = node; + self._tail = node; + } else { + self._tail._next = node; + node._prev = self._tail; + self._tail = node; + } + + node._owner = self; + + return node; +} + +var MiniSignal = (function () { + function MiniSignal() { + _classCallCheck(this, MiniSignal); + + this._head = this._tail = undefined; + } + + _createClass(MiniSignal, [{ + key: 'handlers', + value: function handlers() { + var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; + + var node = this._head; + + if (exists) return !!node; + + var ee = []; + + while (node) { + ee.push(node); + node = node._next; + } + + return ee; + } + }, { + key: 'has', + value: function has(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.'); + } + + return node._owner === this; + } + }, { + key: 'dispatch', + value: function dispatch() { + var node = this._head; + + if (!node) return false; + + while (node) { + if (node._once) this.detach(node); + node._fn.apply(node._thisArg, arguments); + node = node._next; + } + + return true; + } + }, { + key: 'add', + value: function add(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#add(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg)); + } + }, { + key: 'once', + value: function once(fn) { + var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + if (typeof fn !== 'function') { + throw new Error('MiniSignal#once(): First arg must be a Function.'); + } + return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg)); + } + }, { + key: 'detach', + value: function detach(node) { + if (!(node instanceof MiniSignalBinding)) { + throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.'); + } + if (node._owner !== this) return this; + + if (node._prev) node._prev._next = node._next; + if (node._next) node._next._prev = node._prev; + + if (node === this._head) { + this._head = node._next; + if (node._next === null) { + this._tail = null; + } + } else if (node === this._tail) { + this._tail = node._prev; + this._tail._next = null; + } + + node._owner = null; + return this; + } + }, { + key: 'detachAll', + value: function detachAll() { + var node = this._head; + if (!node) return this; + + this._head = this._tail = null; + + while (node) { + node._owner = null; + node = node._next; + } + return this; + } + }]); + + return MiniSignal; +})(); + +MiniSignal.MiniSignalBinding = MiniSignalBinding; + +exports['default'] = MiniSignal; +module.exports = exports['default']; + +},{}],6:[function(require,module,exports){ +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + +'use strict'; +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + +},{}],7:[function(require,module,exports){ +'use strict' + +module.exports = function parseURI (str, opts) { + opts = opts || {} + + var o = { + key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], + q: { + name: 'queryKey', + parser: /(?:^|&)([^&=]*)=?([^&]*)/g + }, + parser: { + strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, + loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ + } + } + + var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str) + var uri = {} + var i = 14 + + while (i--) uri[o.key[i]] = m[i] || '' + + uri[o.q.name] = {} + uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { + if ($1) uri[o.q.name][$1] = $2 + }) + + return uri +} + +},{}],8:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) + +},{"_process":26}],9:[function(require,module,exports){ +var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); + +/** + * Helper class to create a webGL buffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ +var Buffer = function(gl, type, data, drawType) +{ + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The WebGL buffer, created upon instantiation + * + * @member {WebGLBuffer} + */ + this.buffer = gl.createBuffer(); + + /** + * The type of the buffer + * + * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} + */ + this.type = type || gl.ARRAY_BUFFER; + + /** + * The draw type of the buffer + * + * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} + */ + this.drawType = drawType || gl.STATIC_DRAW; + + /** + * The data in the buffer, as a typed array + * + * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} + */ + this.data = EMPTY_ARRAY_BUFFER; + + if(data) + { + this.upload(data); + } + + this._updateID = 0; +}; + +/** + * Uploads the buffer to the GPU + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload + * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract + * @param dontBind {Boolean} whether to bind the buffer before uploading it + */ +Buffer.prototype.upload = function(data, offset, dontBind) +{ + // todo - needed? + if(!dontBind) this.bind(); + + var gl = this.gl; + + data = data || this.data; + offset = offset || 0; + + if(this.data.byteLength >= data.byteLength) + { + gl.bufferSubData(this.type, offset, data); + } + else + { + gl.bufferData(this.type, data, this.drawType); + } + + this.data = data; +}; +/** + * Binds the buffer + * + */ +Buffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindBuffer(this.type, this.buffer); +}; + +Buffer.createVertexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); +}; + +Buffer.createIndexBuffer = function(gl, data, drawType) +{ + return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); +}; + +Buffer.create = function(gl, type, data, drawType) +{ + return new Buffer(gl, type, data, drawType); +}; + +/** + * Destroys the buffer + * + */ +Buffer.prototype.destroy = function(){ + this.gl.deleteBuffer(this.buffer); +}; + +module.exports = Buffer; + +},{}],10:[function(require,module,exports){ + +var Texture = require('./GLTexture'); + +/** + * Helper class to create a webGL Framebuffer + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + */ +var Framebuffer = function(gl, width, height) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The frame buffer + * + * @member {WebGLFramebuffer} + */ + this.framebuffer = gl.createFramebuffer(); + + /** + * The stencil buffer + * + * @member {WebGLRenderbuffer} + */ + this.stencil = null; + + /** + * The stencil buffer + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The width of the drawing area of the buffer + * + * @member {Number} + */ + this.width = width || 100; + /** + * The height of the drawing area of the buffer + * + * @member {Number} + */ + this.height = height || 100; +}; + +/** + * Adds a texture to the frame buffer + * @param texture {PIXI.glCore.GLTexture} + */ +Framebuffer.prototype.enableTexture = function(texture) +{ + var gl = this.gl; + + this.texture = texture || new Texture(gl); + + this.texture.bind(); + + //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + this.bind(); + + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture.texture, 0); +}; + +/** + * Initialises the stencil buffer + */ +Framebuffer.prototype.enableStencil = function() +{ + if(this.stencil)return; + + var gl = this.gl; + + this.stencil = gl.createRenderbuffer(); + + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + + // TODO.. this is depth AND stencil? + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width , this.height ); + + +}; + +/** + * Erases the drawing area and fills it with a colour + * @param r {Number} the red value of the clearing colour + * @param g {Number} the green value of the clearing colour + * @param b {Number} the blue value of the clearing colour + * @param a {Number} the alpha value of the clearing colour + */ +Framebuffer.prototype.clear = function( r, g, b, a ) +{ + this.bind(); + + var gl = this.gl; + + gl.clearColor(r, g, b, a); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); +}; + +/** + * Binds the frame buffer to the WebGL context + */ +Framebuffer.prototype.bind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); +}; + +/** + * Unbinds the frame buffer to the WebGL context + */ +Framebuffer.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindFramebuffer(gl.FRAMEBUFFER, null ); +}; +/** + * Resizes the drawing area of the buffer to the given width and height + * @param width {Number} the new width + * @param height {Number} the new height + */ +Framebuffer.prototype.resize = function(width, height) +{ + var gl = this.gl; + + this.width = width; + this.height = height; + + if ( this.texture ) + { + this.texture.uploadData(null, width, height); + } + + if ( this.stencil ) + { + // update the stencil buffer width and height + gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height); + } +}; + +/** + * Destroys this buffer + */ +Framebuffer.prototype.destroy = function() +{ + var gl = this.gl; + + //TODO + if(this.texture) + { + this.texture.destroy(); + } + + gl.deleteFramebuffer(this.framebuffer); + + this.gl = null; + + this.stencil = null; + this.texture = null; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createRGBA = function(gl, width, height, data) +{ + var texture = Texture.fromData(gl, null, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + //fbo.enableStencil(); // get this back on soon! + + //fbo.enableStencil(); // get this back on soon! + + fbo.unbind(); + + return fbo; +}; + +/** + * Creates a frame buffer with a texture containing the given data + * @static + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param width {Number} the width of the drawing area of the frame buffer + * @param height {Number} the height of the drawing area of the frame buffer + * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data + */ +Framebuffer.createFloat32 = function(gl, width, height, data) +{ + // create a new texture.. + var texture = new Texture.fromData(gl, data, width, height); + texture.enableNearestScaling(); + texture.enableWrapClamp(); + + //now create the framebuffer object and attach the texture to it. + var fbo = new Framebuffer(gl, width, height); + fbo.enableTexture(texture); + + fbo.unbind(); + + return fbo; +}; + +module.exports = Framebuffer; + +},{"./GLTexture":12}],11:[function(require,module,exports){ + +var compileProgram = require('./shader/compileProgram'), + extractAttributes = require('./shader/extractAttributes'), + extractUniforms = require('./shader/extractUniforms'), + setPrecision = require('./shader/setPrecision'), + generateUniformAccessObject = require('./shader/generateUniformAccessObject'); + +/** + * Helper class to create a webGL Shader + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + */ +var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + if(precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } + + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); + + this.uniformData = extractUniforms(gl, this.program); + + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + +}; +/** + * Uses this shader + * + * @return {PIXI.glCore.GLShader} Returns itself. + */ +Shader.prototype.bind = function() +{ + this.gl.useProgram(this.program); + return this; +}; + +/** + * Destroys this shader + * TODO + */ +Shader.prototype.destroy = function() +{ + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + + var gl = this.gl; + gl.deleteProgram(this.program); +}; + + +module.exports = Shader; + +},{"./shader/compileProgram":17,"./shader/extractAttributes":19,"./shader/extractUniforms":20,"./shader/generateUniformAccessObject":21,"./shader/setPrecision":25}],12:[function(require,module,exports){ + +/** + * Helper class to create a WebGL Texture + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL context + * @param width {number} the width of the texture + * @param height {number} the height of the texture + * @param format {number} the pixel format of the texture. defaults to gl.RGBA + * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE + */ +var Texture = function(gl, width, height, format, type) +{ + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); + + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; + + + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; + + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; + + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + + +}; + +/** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ +Texture.prototype.upload = function(source) +{ + this.bind(); + + var gl = this.gl; + + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + var newWidth = source.videoWidth || source.width; + var newHeight = source.videoHeight || source.height; + + if(newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } + + // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + +}; + +var FLOATING_POINT_AVAILABLE = false; + +/** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.prototype.uploadData = function(data, width, height) +{ + this.bind(); + + var gl = this.gl; + + + if(data instanceof Float32Array) + { + if(!FLOATING_POINT_AVAILABLE) + { + var ext = gl.getExtension("OES_texture_float"); + + if(ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } + + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } + + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + + + if(width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } + + this.width = width; + this.height = height; + + +// texSubImage2D +}; + +/** + * Binds the texture + * @param location + */ +Texture.prototype.bind = function(location) +{ + var gl = this.gl; + + if(location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } + + gl.bindTexture(gl.TEXTURE_2D, this.texture); +}; + +/** + * Unbinds the texture + */ +Texture.prototype.unbind = function() +{ + var gl = this.gl; + gl.bindTexture(gl.TEXTURE_2D, null); +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.minFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + if(this.mipmap) + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } +}; + +/** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ +Texture.prototype.magFilter = function( linear ) +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); +}; + +/** + * Enables mipmapping + */ +Texture.prototype.enableMipmap = function() +{ + var gl = this.gl; + + this.bind(); + + this.mipmap = true; + + gl.generateMipmap(gl.TEXTURE_2D); +}; + +/** + * Enables linear filtering + */ +Texture.prototype.enableLinearScaling = function() +{ + this.minFilter(true); + this.magFilter(true); +}; + +/** + * Enables nearest neighbour interpolation + */ +Texture.prototype.enableNearestScaling = function() +{ + this.minFilter(false); + this.magFilter(false); +}; + +/** + * Enables clamping on the texture so WebGL will not repeat it + */ +Texture.prototype.enableWrapClamp = function() +{ + var gl = this.gl; + + this.bind(); + + 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); +}; + +/** + * Enable tiling on the texture + */ +Texture.prototype.enableWrapRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); +}; + +Texture.prototype.enableWrapMirrorRepeat = function() +{ + var gl = this.gl; + + this.bind(); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); +}; + + +/** + * Destroys this texture + */ +Texture.prototype.destroy = function() +{ + var gl = this.gl; + //TODO + gl.deleteTexture(this.texture); +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ +Texture.fromSource = function(gl, source, premultiplyAlpha) +{ + var texture = new Texture(gl); + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); + + return texture; +}; + +/** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ +Texture.fromData = function(gl, data, width, height) +{ + //console.log(data, width, height); + var texture = new Texture(gl); + texture.uploadData(data, width, height); + + return texture; +}; + + +module.exports = Texture; + +},{}],13:[function(require,module,exports){ + +// state object// +var setVertexAttribArrays = require( './setVertexAttribArrays' ); + +/** + * Helper class to work with WebGL VertexArrayObjects (vaos) + * Only works if WebGL extensions are enabled (they usually are) + * + * @class + * @memberof PIXI.glCore + * @param gl {WebGLRenderingContext} The current WebGL rendering context + */ +function VertexArrayObject(gl, state) +{ + this.nativeVaoExtension = null; + + if(!VertexArrayObject.FORCE_NATIVE) + { + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + this.nativeState = state; + + if(this.nativeVaoExtension) + { + this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); + + var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + // VAO - overwrite the state.. + this.nativeState = { + tempAttribState: new Array(maxAttribs), + attribState: new Array(maxAttribs) + }; + } + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of attributes + * + * @member {Array} + */ + this.attributes = []; + + /** + * @member {PIXI.glCore.GLBuffer} + */ + this.indexBuffer = null; + + /** + * A boolean flag + * + * @member {Boolean} + */ + this.dirty = false; +} + +VertexArrayObject.prototype.constructor = VertexArrayObject; +module.exports = VertexArrayObject; + +/** +* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) +* If you find on older devices that things have gone a bit weird then set this to true. +*/ +/** + * Lets the VAO know if you should use the WebGL extension or the native methods. + * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) + * If you find on older devices that things have gone a bit weird then set this to true. + * @static + * @property {Boolean} FORCE_NATIVE + */ +VertexArrayObject.FORCE_NATIVE = false; + +/** + * Binds the buffer + */ +VertexArrayObject.prototype.bind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + + if(this.dirty) + { + this.dirty = false; + this.activate(); + return this; + } + if (this.indexBuffer) + { + this.indexBuffer.bind(); + } + } + else + { + this.activate(); + } + + return this; +}; + +/** + * Unbinds the buffer + */ +VertexArrayObject.prototype.unbind = function() +{ + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + return this; +}; + +/** + * Uses this vao + */ +VertexArrayObject.prototype.activate = function() +{ + + var gl = this.gl; + var lastBuffer = null; + + for (var i = 0; i < this.attributes.length; i++) + { + var attrib = this.attributes[i]; + + if(lastBuffer !== attrib.buffer) + { + attrib.buffer.bind(); + lastBuffer = attrib.buffer; + } + + gl.vertexAttribPointer(attrib.attribute.location, + attrib.attribute.size, + attrib.type || gl.FLOAT, + attrib.normalized || false, + attrib.stride || 0, + attrib.start || 0); + } + + setVertexAttribArrays(gl, this.attributes, this.nativeState); + + if(this.indexBuffer) + { + this.indexBuffer.bind(); + } + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + * @param attribute {*} + * @param type {String} + * @param normalized {Boolean} + * @param stride {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start) +{ + this.attributes.push({ + buffer: buffer, + attribute: attribute, + + location: attribute.location, + type: type || this.gl.FLOAT, + normalized: normalized || false, + stride: stride || 0, + start: start || 0 + }); + + this.dirty = true; + + return this; +}; + +/** + * + * @param buffer {PIXI.gl.GLBuffer} + */ +VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) +{ + this.indexBuffer = buffer; + + this.dirty = true; + + return this; +}; + +/** + * Unbinds this vao and disables it + */ +VertexArrayObject.prototype.clear = function() +{ + // var gl = this.gl; + + // TODO - should this function unbind after clear? + // for now, no but lets see what happens in the real world! + if(this.nativeVao) + { + this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); + } + + this.attributes.length = 0; + this.indexBuffer = null; + + return this; +}; + +/** + * @param type {Number} + * @param size {Number} + * @param start {Number} + */ +VertexArrayObject.prototype.draw = function(type, size, start) +{ + var gl = this.gl; + + if(this.indexBuffer) + { + gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + } + else + { + // TODO need a better way to calculate size.. + gl.drawArrays(type, start, size || this.getSize()); + } + + return this; +}; + +/** + * Destroy this vao + */ +VertexArrayObject.prototype.destroy = function() +{ + // lose references + this.gl = null; + this.indexBuffer = null; + this.attributes = null; + this.nativeState = null; + + if(this.nativeVao) + { + this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); + } + + this.nativeVaoExtension = null; + this.nativeVao = null; +}; + +VertexArrayObject.prototype.getSize = function() +{ + var attrib = this.attributes[0]; + return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); +}; + +},{"./setVertexAttribArrays":16}],14:[function(require,module,exports){ + +/** + * Helper class to create a webGL Context + * + * @class + * @memberof PIXI.glCore + * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from + * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * @return {WebGLRenderingContext} the WebGL context + */ +var createContext = function(canvas, options) +{ + var gl = canvas.getContext('webgl', options) || + canvas.getContext('experimental-webgl', options); + + if (!gl) + { + // fail, not able to get a context + throw new Error('This browser does not support webGL. Try using the canvas renderer'); + } + + return gl; +}; + +module.exports = createContext; + +},{}],15:[function(require,module,exports){ +var gl = { + createContext: require('./createContext'), + setVertexAttribArrays: require('./setVertexAttribArrays'), + GLBuffer: require('./GLBuffer'), + GLFramebuffer: require('./GLFramebuffer'), + GLShader: require('./GLShader'), + GLTexture: require('./GLTexture'), + VertexArrayObject: require('./VertexArrayObject'), + shader: require('./shader') +}; + +// Export for Node-compatible environments +if (typeof module !== 'undefined' && module.exports) +{ + // Export the module + module.exports = gl; +} + +// Add to the browser window pixi.gl +if (typeof window !== 'undefined') +{ + // add the window object + window.PIXI = window.PIXI || {}; + window.PIXI.glCore = gl; +} + +},{"./GLBuffer":9,"./GLFramebuffer":10,"./GLShader":11,"./GLTexture":12,"./VertexArrayObject":13,"./createContext":14,"./setVertexAttribArrays":16,"./shader":22}],16:[function(require,module,exports){ +// var GL_MAP = {}; + +/** + * @param gl {WebGLRenderingContext} The current WebGL context + * @param attribs {*} + * @param state {*} + */ +var setVertexAttribArrays = function (gl, attribs, state) +{ + var i; + if(state) + { + var tempAttribState = state.tempAttribState, + attribState = state.attribState; + + for (i = 0; i < tempAttribState.length; i++) + { + tempAttribState[i] = false; + } + + // set the new attribs + for (i = 0; i < attribs.length; i++) + { + tempAttribState[attribs[i].attribute.location] = true; + } + + for (i = 0; i < attribState.length; i++) + { + if (attribState[i] !== tempAttribState[i]) + { + attribState[i] = tempAttribState[i]; + + if (state.attribState[i]) + { + gl.enableVertexAttribArray(i); + } + else + { + gl.disableVertexAttribArray(i); + } + } + } + + } + else + { + for (i = 0; i < attribs.length; i++) + { + var attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); + } + } +}; + +module.exports = setVertexAttribArrays; + +},{}],17:[function(require,module,exports){ + +/** + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. + * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations + * @return {WebGLProgram} the shader program + */ +var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +{ + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + + var program = gl.createProgram(); + + gl.attachShader(program, glVertShader); + gl.attachShader(program, glFragShader); + + // optionally, set the attributes manually for the program rather than letting WebGL decide.. + if(attributeLocations) + { + for(var i in attributeLocations) + { + gl.bindAttribLocation(program, attributeLocations[i], i); + } + } + + + gl.linkProgram(program); + + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) + { + console.error('Pixi.js Error: Could not initialize shader.'); + console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); + console.error('gl.getError()', gl.getError()); + + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') + { + console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + + gl.deleteProgram(program); + program = null; + } + + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + + return program; +}; + +/** + * @private + * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} + * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. + * @return {WebGLShader} the shader + */ +var compileShader = function (gl, type, src) +{ + var shader = gl.createShader(type); + + gl.shaderSource(shader, src); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) + { + console.log(gl.getShaderInfoLog(shader)); + return null; + } + + return shader; +}; + +module.exports = compileProgram; + +},{}],18:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} Type of value + * @param size {Number} + */ +var defaultValue = function(type, size) +{ + switch (type) + { + case 'float': + return 0; + + case 'vec2': + return new Float32Array(2 * size); + + case 'vec3': + return new Float32Array(3 * size); + + case 'vec4': + return new Float32Array(4 * size); + + case 'int': + case 'sampler2D': + return 0; + + case 'ivec2': + return new Int32Array(2 * size); + + case 'ivec3': + return new Int32Array(3 * size); + + case 'ivec4': + return new Int32Array(4 * size); + + case 'bool': + return false; + + case 'bvec2': + + return booleanArray( 2 * size); + + case 'bvec3': + return booleanArray(3 * size); + + case 'bvec4': + return booleanArray(4 * size); + + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } +}; + +var booleanArray = function(size) +{ + var array = new Array(size); + + for (var i = 0; i < array.length; i++) + { + array[i] = false; + } + + return array; +}; + +module.exports = defaultValue; + +},{}],19:[function(require,module,exports){ + +var mapType = require('./mapType'); +var mapSize = require('./mapSize'); + +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the attributes from + * @return attributes {Object} + */ +var extractAttributes = function(gl, program) +{ + var attributes = {}; + + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + + for (var i = 0; i < totalAttributes; i++) + { + var attribData = gl.getActiveAttrib(program, i); + var type = mapType(gl, attribData.type); + + attributes[attribData.name] = { + type:type, + size:mapSize(type), + location:gl.getAttribLocation(program, attribData.name), + //TODO - make an attribute object + pointer: pointer + }; + } + + return attributes; +}; + +var pointer = function(type, normalized, stride, start){ + // console.log(this.location) + gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +}; + +module.exports = extractAttributes; + +},{"./mapSize":23,"./mapType":24}],20:[function(require,module,exports){ +var mapType = require('./mapType'); +var defaultValue = require('./defaultValue'); + +/** + * Extracts the uniforms + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param program {WebGLProgram} The shader program to get the uniforms from + * @return uniforms {Object} + */ +var extractUniforms = function(gl, program) +{ + var uniforms = {}; + + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + + for (var i = 0; i < totalUniforms; i++) + { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]/, ""); + var type = mapType(gl, uniformData.type ); + + uniforms[name] = { + type:type, + size:uniformData.size, + location:gl.getUniformLocation(program, name), + value:defaultValue(type, uniformData.size) + }; + } + + return uniforms; +}; + +module.exports = extractUniforms; + +},{"./defaultValue":18,"./mapType":24}],21:[function(require,module,exports){ +/** + * Extracts the attributes + * @class + * @memberof PIXI.glCore.shader + * @param gl {WebGLRenderingContext} The current WebGL rendering context + * @param uniforms {Array} @mat ? + * @return attributes {Object} + */ +var generateUniformAccessObject = function(gl, uniformData) +{ + // this is the object we will be sending back. + // an object hierachy will be created for structs + var uniforms = {data:{}}; + + uniforms.gl = gl; + + var uniformKeys= Object.keys(uniformData); + + for (var i = 0; i < uniformKeys.length; i++) + { + var fullName = uniformKeys[i]; + + var nameTokens = fullName.split('.'); + var name = nameTokens[nameTokens.length - 1]; + + + var uniformGroup = getUniformGroup(nameTokens, uniforms); + + var uniform = uniformData[fullName]; + uniformGroup.data[name] = uniform; + + uniformGroup.gl = gl; + + Object.defineProperty(uniformGroup, name, { + get: generateGetter(name), + set: generateSetter(name, uniform) + }); + } + + return uniforms; +}; + +var generateGetter = function(name) +{ + return function() { + return this.data[name].value; + }; +}; + +var GLSL_SINGLE_SETTERS = { + float: function setSingleFloat(gl, location, value) { gl.uniform1f(location, value); }, + vec2: function setSingleVec2(gl, location, value) { gl.uniform2f(location, value[0], value[1]); }, + vec3: function setSingleVec3(gl, location, value) { gl.uniform3f(location, value[0], value[1], value[2]); }, + vec4: function setSingleVec4(gl, location, value) { gl.uniform4f(location, value[0], value[1], value[2], value[3]); }, + + int: function setSingleInt(gl, location, value) { gl.uniform1i(location, value); }, + ivec2: function setSingleIvec2(gl, location, value) { gl.uniform2i(location, value[0], value[1]); }, + ivec3: function setSingleIvec3(gl, location, value) { gl.uniform3i(location, value[0], value[1], value[2]); }, + ivec4: function setSingleIvec4(gl, location, value) { gl.uniform4i(location, value[0], value[1], value[2], value[3]); }, + + bool: function setSingleBool(gl, location, value) { gl.uniform1i(location, value); }, + bvec2: function setSingleBvec2(gl, location, value) { gl.uniform2i(location, value[0], value[1]); }, + bvec3: function setSingleBvec3(gl, location, value) { gl.uniform3i(location, value[0], value[1], value[2]); }, + bvec4: function setSingleBvec4(gl, location, value) { gl.uniform4i(location, value[0], value[1], value[2], value[3]); }, + + mat2: function setSingleMat2(gl, location, value) { gl.uniformMatrix2fv(location, false, value); }, + mat3: function setSingleMat3(gl, location, value) { gl.uniformMatrix3fv(location, false, value); }, + mat4: function setSingleMat4(gl, location, value) { gl.uniformMatrix4fv(location, false, value); }, + + sampler2D: function setSingleSampler2D(gl, location, value) { gl.uniform1i(location, value); }, +}; + +var GLSL_ARRAY_SETTERS = { + float: function setFloatArray(gl, location, value) { gl.uniform1fv(location, value); }, + vec2: function setVec2Array(gl, location, value) { gl.uniform2fv(location, value); }, + vec3: function setVec3Array(gl, location, value) { gl.uniform3fv(location, value); }, + vec4: function setVec4Array(gl, location, value) { gl.uniform4fv(location, value); }, + int: function setIntArray(gl, location, value) { gl.uniform1iv(location, value); }, + ivec2: function setIvec2Array(gl, location, value) { gl.uniform2iv(location, value); }, + ivec3: function setIvec3Array(gl, location, value) { gl.uniform3iv(location, value); }, + ivec4: function setIvec4Array(gl, location, value) { gl.uniform4iv(location, value); }, + bool: function setBoolArray(gl, location, value) { gl.uniform1iv(location, value); }, + bvec2: function setBvec2Array(gl, location, value) { gl.uniform2iv(location, value); }, + bvec3: function setBvec3Array(gl, location, value) { gl.uniform3iv(location, value); }, + bvec4: function setBvec4Array(gl, location, value) { gl.uniform4iv(location, value); }, + sampler2D: function setSampler2DArray(gl, location, value) { gl.uniform1iv(location, value); }, +}; + +function generateSetter(name, uniform) +{ + return function(value) { + this.data[name].value = value; + var location = this.data[name].location; + if (uniform.size === 1) + { + GLSL_SINGLE_SETTERS[uniform.type](this.gl, location, value); + } + else + { + // glslSetArray(gl, location, type, value) { + GLSL_ARRAY_SETTERS[uniform.type](this.gl, location, value); + } + }; +} + +function getUniformGroup(nameTokens, uniform) +{ + var cur = uniform; + + for (var i = 0; i < nameTokens.length - 1; i++) + { + var o = cur[nameTokens[i]] || {data:{}}; + cur[nameTokens[i]] = o; + cur = o; + } + + return cur; +} + + +module.exports = generateUniformAccessObject; + +},{}],22:[function(require,module,exports){ +module.exports = { + compileProgram: require('./compileProgram'), + defaultValue: require('./defaultValue'), + extractAttributes: require('./extractAttributes'), + extractUniforms: require('./extractUniforms'), + generateUniformAccessObject: require('./generateUniformAccessObject'), + setPrecision: require('./setPrecision'), + mapSize: require('./mapSize'), + mapType: require('./mapType') +}; +},{"./compileProgram":17,"./defaultValue":18,"./extractAttributes":19,"./extractUniforms":20,"./generateUniformAccessObject":21,"./mapSize":23,"./mapType":24,"./setPrecision":25}],23:[function(require,module,exports){ +/** + * @class + * @memberof PIXI.glCore.shader + * @param type {String} + * @return {Number} + */ +var mapSize = function(type) +{ + return GLSL_TO_SIZE[type]; +}; + + +var GLSL_TO_SIZE = { + 'float': 1, + 'vec2': 2, + 'vec3': 3, + 'vec4': 4, + + 'int': 1, + 'ivec2': 2, + 'ivec3': 3, + 'ivec4': 4, + + 'bool': 1, + 'bvec2': 2, + 'bvec3': 3, + 'bvec4': 4, + + 'mat2': 4, + 'mat3': 9, + 'mat4': 16, + + 'sampler2D': 1 +}; + +module.exports = mapSize; + +},{}],24:[function(require,module,exports){ + + +var mapType = function(gl, type) +{ + if(!GL_TABLE) + { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + + GL_TABLE = {}; + + for(var i = 0; i < typeNames.length; ++i) + { + var tn = typeNames[i]; + GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + } + } + + return GL_TABLE[type]; +}; + +var GL_TABLE = null; + +var GL_TO_GLSL_TYPES = { + 'FLOAT': 'float', + 'FLOAT_VEC2': 'vec2', + 'FLOAT_VEC3': 'vec3', + 'FLOAT_VEC4': 'vec4', + + 'INT': 'int', + 'INT_VEC2': 'ivec2', + 'INT_VEC3': 'ivec3', + 'INT_VEC4': 'ivec4', + + 'BOOL': 'bool', + 'BOOL_VEC2': 'bvec2', + 'BOOL_VEC3': 'bvec3', + 'BOOL_VEC4': 'bvec4', + + 'FLOAT_MAT2': 'mat2', + 'FLOAT_MAT3': 'mat3', + 'FLOAT_MAT4': 'mat4', + + 'SAMPLER_2D': 'sampler2D' +}; + +module.exports = mapType; + +},{}],25:[function(require,module,exports){ +/** + * Sets the float precision on the shader. If the precision is already present this function will do nothing + * @param {string} src the shader source + * @param {string} precision The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + * + * @return {string} modified shader source + */ +var setPrecision = function(src, precision) +{ + if(src.substring(0, 9) !== 'precision') + { + return 'precision ' + precision + ' float;\n' + src; + } + + return src; +}; + +module.exports = setPrecision; + +},{}],26:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],27:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],28:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +},{}],29:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } +}; + +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; +} + +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; + +},{}],30:[function(require,module,exports){ +'use strict'; + +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); + +},{"./decode":28,"./encode":29}],31:[function(require,module,exports){ +'use strict' + +/** + * Remove a range of items from an array + * + * @function removeItems + * @param {Array<*>} arr The target array + * @param {number} startIdx The index to begin removing from (inclusive) + * @param {number} removeCount How many items to remove + */ +module.exports = function removeItems(arr, startIdx, removeCount) +{ + var i, length = arr.length + + if (startIdx >= length || removeCount === 0) { + return + } + + removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount) + + var len = length - removeCount + + for (i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount] + } + + arr.length = len +} + +},{}],32:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Loader = undefined; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _async = require('./async'); + +var async = _interopRequireWildcard(_async); + +var _Resource = require('./Resource'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// some constants +var MAX_PROGRESS = 100; +var rgxExtractUrlHash = /(#[\w-]+)?$/; + +/** + * Manages the state and loading of multiple resources to load. + * + * @class + */ + +var Loader = exports.Loader = function () { + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader() { + var _this = this; + + var baseUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + var concurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; + + _classCallCheck(this, Loader); + + /** + * The base url for all resources loaded by this loader. + * + * @member {string} + */ + this.baseUrl = baseUrl; + + /** + * The progress percent of the loader going through the queue. + * + * @member {number} + */ + this.progress = 0; + + /** + * Loading state of the loader, true if it is currently loading resources. + * + * @member {boolean} + */ + this.loading = false; + + /** + * A querystring to append to every URL added to the loader. + * + * This should be a valid query string *without* the question-mark (`?`). The loader will + * also *not* escape values for you. Make sure to escape your parameters with + * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. + * + * @example + * const loader = new Loader(); + * + * loader.defaultQueryString = 'user=me&password=secret'; + * + * // This will request 'image.png?user=me&password=secret' + * loader.add('image.png').load(); + * + * loader.reset(); + * + * // This will request 'image.png?v=1&user=me&password=secret' + * loader.add('iamge.png?v=1').load(); + * + * @member {string} + */ + this.defaultQueryString = ''; + + /** + * The middleware to run before loading each resource. + * + * @private + * @member {function[]} + */ + this._beforeMiddleware = []; + + /** + * The middleware to run after loading each resource. + * + * @private + * @member {function[]} + */ + this._afterMiddleware = []; + + /** + * The tracks the resources we are currently completing parsing for. + * + * @private + * @member {Resource[]} + */ + this._resourcesParsing = []; + + /** + * The `_loadResource` function bound with this object context. + * + * @private + * @member {function} + * @param {Resource} r - The resource to load + * @param {Function} d - The dequeue function + * @return {undefined} + */ + this._boundLoadResource = function (r, d) { + return _this._loadResource(r, d); + }; + + /** + * The resources waiting to be loaded. + * + * @private + * @member {Resource[]} + */ + this._queue = async.queue(this._boundLoadResource, concurrency); + + this._queue.pause(); + + /** + * All the resources for this loader keyed by name. + * + * @member {object} + */ + this.resources = {}; + + /** + * Dispatched once per loaded or errored resource. + * + * The callback looks like {@link Loader.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once per errored resource. + * + * The callback looks like {@link Loader.OnErrorSignal}. + * + * @member {Signal} + */ + this.onError = new _miniSignals2.default(); + + /** + * Dispatched once per loaded resource. + * + * The callback looks like {@link Loader.OnLoadSignal}. + * + * @member {Signal} + */ + this.onLoad = new _miniSignals2.default(); + + /** + * Dispatched when the loader begins to process the queue. + * + * The callback looks like {@link Loader.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched when the queued resources all load. + * + * The callback looks like {@link Loader.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + // Add default before middleware + for (var i = 0; i < Loader._defaultBeforeMiddleware.length; ++i) { + this.pre(Loader._defaultBeforeMiddleware[i]); + } + + // Add default after middleware + for (var _i = 0; _i < Loader._defaultAfterMiddleware.length; ++_i) { + this.use(Loader._defaultAfterMiddleware[_i]); + } + } + + /** + * When the progress changes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnProgressSignal + * @param {Loader} loader - The loader the progress is advancing on. + * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance. + */ + + /** + * When an error occurrs the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnErrorSignal + * @param {Loader} loader - The loader the error happened in. + * @param {Resource} resource - The resource that caused the error. + */ + + /** + * When a load completes the loader and resource are disaptched. + * + * @memberof Loader + * @callback OnLoadSignal + * @param {Loader} loader - The loader that laoded the resource. + * @param {Resource} resource - The resource that has completed loading. + */ + + /** + * When the loader starts loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnStartSignal + * @param {Loader} loader - The loader that has started loading resources. + */ + + /** + * When the loader completes loading resources it dispatches this callback. + * + * @memberof Loader + * @callback OnCompleteSignal + * @param {Loader} loader - The loader that has finished loading resources. + */ + + /** + * Options for a call to `.add()`. + * + * @see Loader#add + * + * @typedef {object} IAddOptions + * @property {string} [name] - The name of the resource to load, if not passed the url is used. + * @property {string} [key] - Alias for `name`. + * @property {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @property {string|boolean} [crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @property {number} [timeout=0] - A timeout in milliseconds for the load. If the load takes + * longer than this time it is cancelled and the load is considered a failure. If this value is + * set to `0` then there is no explicit timeout. + * @property {Resource.LOAD_TYPE} [loadType=Resource.LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @property {Resource.XHR_RESPONSE_TYPE} [xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @property {Loader.OnCompleteSignal} [onComplete] - Callback to add an an onComplete signal istener. + * @property {Loader.OnCompleteSignal} [callback] - Alias for `onComplete`. + * @property {Resource.IMetadata} [metadata] - Extra configuration for middleware and the Resource object. + */ + + /** + * Adds a resource (or multiple resources) to the loader queue. + * + * This function can take a wide variety of different parameters. The only thing that is always + * required the url to load. All the following will work: + * + * ```js + * loader + * // normal param syntax + * .add('key', 'http://...', function () {}) + * .add('http://...', function () {}) + * .add('http://...') + * + * // object syntax + * .add({ + * name: 'key2', + * url: 'http://...' + * }, function () {}) + * .add({ + * url: 'http://...' + * }, function () {}) + * .add({ + * name: 'key3', + * url: 'http://...' + * onComplete: function () {} + * }) + * .add({ + * url: 'https://...', + * onComplete: function () {}, + * crossOrigin: true + * }) + * + * // you can also pass an array of objects or urls or both + * .add([ + * { name: 'key4', url: 'http://...', onComplete: function () {} }, + * { url: 'http://...', onComplete: function () {} }, + * 'http://...' + * ]) + * + * // and you can use both params and options + * .add('key', 'http://...', { crossOrigin: true }, function () {}) + * .add('http://...', { crossOrigin: true }, function () {}); + * ``` + * + * @param {string|IAddOptions} [name] - The name of the resource to load, if not passed the url is used. + * @param {string} [url] - The url for this resource, relative to the baseUrl of this loader. + * @param {IAddOptions} [options] - The options for the load. + * @param {Loader.OnCompleteSignal} [cb] - Function to call when this specific resource completes loading. + * @return {this} Returns itself. + */ + + + Loader.prototype.add = function add(name, url, options, cb) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + + return this; + } + + // if an object is passed instead of params + if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') { + cb = url || name.callback || name.onComplete; + options = name; + url = name.url; + name = name.name || name.key || name.url; + } + + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + cb = options; + options = url; + url = name; + } + + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + cb = options; + options = null; + } + + // if loading already you can only add resources that have a parent. + if (this.loading && (!options || !options.parentResource)) { + throw new Error('Cannot add resources while the loader is running.'); + } + + // check if resource already exists. + if (this.resources[name]) { + throw new Error('Resource named "' + name + '" already exists.'); + } + + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + + // create the store the resource + this.resources[name] = new _Resource.Resource(name, url, options); + + if (typeof cb === 'function') { + this.resources[name].onAfterMiddleware.once(cb); + } + + // if actively loading, make sure to adjust progress chunks for that parent and its children + if (this.loading) { + var parent = options.parentResource; + var incompleteChildren = []; + + for (var _i2 = 0; _i2 < parent.children.length; ++_i2) { + if (!parent.children[_i2].isComplete) { + incompleteChildren.push(parent.children[_i2]); + } + } + + var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent + var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child + + parent.children.push(this.resources[name]); + parent.progressChunk = eachChunk; + + for (var _i3 = 0; _i3 < incompleteChildren.length; ++_i3) { + incompleteChildren[_i3].progressChunk = eachChunk; + } + + this.resources[name].progressChunk = eachChunk; + } + + // add the resource to the queue + this._queue.push(this.resources[name]); + + return this; + }; + + /** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * + * @param {function} fn - The middleware function to register. + * @return {this} Returns itself. + */ + + + Loader.prototype.pre = function pre(fn) { + this._beforeMiddleware.push(fn); + + return this; + }; + + /** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * + * @param {function} fn - The middleware function to register. + * @return {this} Returns itself. + */ + + + Loader.prototype.use = function use(fn) { + this._afterMiddleware.push(fn); + + return this; + }; + + /** + * Resets the queue of the loader to prepare for a new load. + * + * @return {this} Returns itself. + */ + + + Loader.prototype.reset = function reset() { + this.progress = 0; + this.loading = false; + + this._queue.kill(); + this._queue.pause(); + + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + + if (res._onLoadBinding) { + res._onLoadBinding.detach(); + } + + if (res.isLoading) { + res.abort(); + } + } + + this.resources = {}; + + return this; + }; + + /** + * Starts loading the queued resources. + * + * @param {function} [cb] - Optional callback that will be bound to the `complete` event. + * @return {this} Returns itself. + */ + + + Loader.prototype.load = function load(cb) { + // register complete callback if they pass one + if (typeof cb === 'function') { + this.onComplete.once(cb); + } + + // if the queue has already started we are done here + if (this.loading) { + return this; + } + + if (this._queue.idle()) { + this._onStart(); + this._onComplete(); + } else { + // distribute progress chunks + var numTasks = this._queue._tasks.length; + var chunk = MAX_PROGRESS / numTasks; + + for (var i = 0; i < this._queue._tasks.length; ++i) { + this._queue._tasks[i].data.progressChunk = chunk; + } + + // notify we are starting + this._onStart(); + + // start loading + this._queue.resume(); + } + + return this; + }; + + /** + * The number of resources to load concurrently. + * + * @member {number} + * @default 10 + */ + + + /** + * Prepares a url for usage based on the configuration of this object + * + * @private + * @param {string} url - The url to prepare. + * @return {string} The prepared url. + */ + Loader.prototype._prepareUrl = function _prepareUrl(url) { + var parsedUrl = (0, _parseUri2.default)(url, { strictMode: true }); + var result = void 0; + + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { + result = url; + } + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + else if (this.baseUrl.length && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 && url.charAt(0) !== '/') { + result = this.baseUrl + '/' + url; + } else { + result = this.baseUrl + url; + } + + // if we need to add a default querystring, there is a bit more work + if (this.defaultQueryString) { + var hash = rgxExtractUrlHash.exec(result)[0]; + + result = result.substr(0, result.length - hash.length); + + if (result.indexOf('?') !== -1) { + result += '&' + this.defaultQueryString; + } else { + result += '?' + this.defaultQueryString; + } + + result += hash; + } + + return result; + }; + + /** + * Loads a single resource. + * + * @private + * @param {Resource} resource - The resource to load. + * @param {function} dequeue - The function to call when we need to dequeue this item. + */ + + + Loader.prototype._loadResource = function _loadResource(resource, dequeue) { + var _this2 = this; + + resource._dequeue = dequeue; + + // run before middleware + async.eachSeries(this._beforeMiddleware, function (fn, next) { + fn.call(_this2, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, function () { + if (resource.isComplete) { + _this2._onLoad(resource); + } else { + resource._onLoadBinding = resource.onComplete.once(_this2._onLoad, _this2); + resource.load(); + } + }, true); + }; + + /** + * Called once loading has started. + * + * @private + */ + + + Loader.prototype._onStart = function _onStart() { + this.progress = 0; + this.loading = true; + this.onStart.dispatch(this); + }; + + /** + * Called once each resource has loaded. + * + * @private + */ + + + Loader.prototype._onComplete = function _onComplete() { + this.progress = MAX_PROGRESS; + this.loading = false; + this.onComplete.dispatch(this, this.resources); + }; + + /** + * Called each time a resources is loaded. + * + * @private + * @param {Resource} resource - The resource that was loaded + */ + + + Loader.prototype._onLoad = function _onLoad(resource) { + var _this3 = this; + + resource._onLoadBinding = null; + + // remove this resource from the async queue, and add it to our list of resources that are being parsed + this._resourcesParsing.push(resource); + resource._dequeue(); + + // run all the after middleware for this resource + async.eachSeries(this._afterMiddleware, function (fn, next) { + fn.call(_this3, resource, next); + }, function () { + resource.onAfterMiddleware.dispatch(resource); + + _this3.progress = Math.min(MAX_PROGRESS, _this3.progress + resource.progressChunk); + _this3.onProgress.dispatch(_this3, resource); + + if (resource.error) { + _this3.onError.dispatch(resource.error, _this3, resource); + } else { + _this3.onLoad.dispatch(_this3, resource); + } + + _this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1); + + // do completion check + if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) { + _this3._onComplete(); + } + }, true); + }; + + _createClass(Loader, [{ + key: 'concurrency', + get: function get() { + return this._queue.concurrency; + } + // eslint-disable-next-line require-jsdoc + , + set: function set(concurrency) { + this._queue.concurrency = concurrency; + } + }]); + + return Loader; +}(); + +/** + * A default array of middleware to run before loading each resource. + * Each of these middlewares are added to any new Loader instances when they are created. + * + * @private + * @member {function[]} + */ + + +Loader._defaultBeforeMiddleware = []; + +/** + * A default array of middleware to run after loading each resource. + * Each of these middlewares are added to any new Loader instances when they are created. + * + * @private + * @member {function[]} + */ +Loader._defaultAfterMiddleware = []; + +/** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * + * @static + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ +Loader.pre = function LoaderPreStatic(fn) { + Loader._defaultBeforeMiddleware.push(fn); + + return Loader; +}; + +/** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * + * @static + * @param {function} fn - The middleware function to register. + * @return {Loader} Returns itself. + */ +Loader.use = function LoaderUseStatic(fn) { + Loader._defaultAfterMiddleware.push(fn); + + return Loader; +}; + +},{"./Resource":33,"./async":34,"mini-signals":5,"parse-uri":7}],33:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Resource = undefined; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _parseUri = require('parse-uri'); + +var _parseUri2 = _interopRequireDefault(_parseUri); + +var _miniSignals = require('mini-signals'); + +var _miniSignals2 = _interopRequireDefault(_miniSignals); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// tests if CORS is supported in XHR, if not we need to use XDR +var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest())); +var tempAnchor = null; + +// some status constants +var STATUS_NONE = 0; +var STATUS_OK = 200; +var STATUS_EMPTY = 204; +var STATUS_IE_BUG_EMPTY = 1223; +var STATUS_TYPE_OK = 2; + +// noop +function _noop() {} /* empty */ + +/** + * Manages the state and loading of a resource and all child resources. + * + * @class + */ + +var Resource = exports.Resource = function () { + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. + */ + Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) { + setExtMap(Resource._loadTypeMap, extname, loadType); + }; + + /** + * Sets the load type to be used for a specific extension. + * + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ + + + Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) { + setExtMap(Resource._xhrTypeMap, extname, xhrType); + }; + + /** + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass + * an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @param {number} [options.timeout=0] - A timeout in milliseconds for the load. If the load takes + * longer than this time it is cancelled and the load is considered a failure. If this value is + * set to `0` then there is no explicit timeout. + * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @param {Resource.IMetadata} [options.metadata] - Extra configuration for middleware and the Resource object. + */ + + + function Resource(name, url, options) { + _classCallCheck(this, Resource); + + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + + options = options || {}; + + /** + * The state flags of this resource. + * + * @private + * @member {number} + */ + this._flags = 0; + + // set data url flag, needs to be set early for some _determineX checks to work. + this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); + + /** + * The name of this resource. + * + * @readonly + * @member {string} + */ + this.name = name; + + /** + * The url used to load this resource. + * + * @readonly + * @member {string} + */ + this.url = url; + + /** + * The extension used to load this resource. + * + * @readonly + * @member {string} + */ + this.extension = this._getExtension(); + + /** + * The data that was loaded by the resource. + * + * @member {any} + */ + this.data = null; + + /** + * Is this request cross-origin? If unset, determined automatically. + * + * @member {string} + */ + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + + /** + * A timeout in milliseconds for the load. If the load takes longer than this time + * it is cancelled and the load is considered a failure. If this value is set to `0` + * then there is no explicit timeout. + * + * @member {number} + */ + this.timeout = options.timeout || 0; + + /** + * The method of loading to use for this resource. + * + * @member {Resource.LOAD_TYPE} + */ + this.loadType = options.loadType || this._determineLoadType(); + + /** + * The type used to load the resource via XHR. If unset, determined automatically. + * + * @member {string} + */ + this.xhrType = options.xhrType; + + /** + * Extra info for middleware, and controlling specifics about how the resource loads. + * + * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + * Meaning it will modify it as it sees fit. + * + * @member {Resource.IMetadata} + */ + this.metadata = options.metadata || {}; + + /** + * The error that occurred while loading (if any). + * + * @readonly + * @member {Error} + */ + this.error = null; + + /** + * The XHR object that was used to load this resource. This is only set + * when `loadType` is `Resource.LOAD_TYPE.XHR`. + * + * @readonly + * @member {XMLHttpRequest} + */ + this.xhr = null; + + /** + * The child resources this resource owns. + * + * @readonly + * @member {Resource[]} + */ + this.children = []; + + /** + * The resource type. + * + * @readonly + * @member {Resource.TYPE} + */ + this.type = Resource.TYPE.UNKNOWN; + + /** + * The progress chunk owned by this resource. + * + * @readonly + * @member {number} + */ + this.progressChunk = 0; + + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * + * @private + * @member {function} + */ + this._dequeue = _noop; + + /** + * Used a storage place for the on load binding used privately by the loader. + * + * @private + * @member {function} + */ + this._onLoadBinding = null; + + /** + * The timer for element loads to check if they timeout. + * + * @private + * @member {number} + */ + this._elementTimer = 0; + + /** + * The `complete` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundComplete = this.complete.bind(this); + + /** + * The `_onError` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnError = this._onError.bind(this); + + /** + * The `_onProgress` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnProgress = this._onProgress.bind(this); + + /** + * The `_onTimeout` function bound to this resource's context. + * + * @private + * @member {function} + */ + this._boundOnTimeout = this._onTimeout.bind(this); + + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnTimeout = this._xhrOnTimeout.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + + /** + * Dispatched when the resource beings to load. + * + * The callback looks like {@link Resource.OnStartSignal}. + * + * @member {Signal} + */ + this.onStart = new _miniSignals2.default(); + + /** + * Dispatched each time progress of this resource load updates. + * Not all resources types and loader systems can support this event + * so sometimes it may not be available. If the resource + * is being loaded on a modern browser, using XHR, and the remote server + * properly sets Content-Length headers, then this will be available. + * + * The callback looks like {@link Resource.OnProgressSignal}. + * + * @member {Signal} + */ + this.onProgress = new _miniSignals2.default(); + + /** + * Dispatched once this resource has loaded, if there was an error it will + * be in the `error` property. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onComplete = new _miniSignals2.default(); + + /** + * Dispatched after this resource has had all the *after* middleware run on it. + * + * The callback looks like {@link Resource.OnCompleteSignal}. + * + * @member {Signal} + */ + this.onAfterMiddleware = new _miniSignals2.default(); + } + + /** + * When the resource starts to load. + * + * @memberof Resource + * @callback OnStartSignal + * @param {Resource} resource - The resource that the event happened on. + */ + + /** + * When the resource reports loading progress. + * + * @memberof Resource + * @callback OnProgressSignal + * @param {Resource} resource - The resource that the event happened on. + * @param {number} percentage - The progress of the load in the range [0, 1]. + */ + + /** + * When the resource finishes loading. + * + * @memberof Resource + * @callback OnCompleteSignal + * @param {Resource} resource - The resource that the event happened on. + */ + + /** + * @memberof Resource + * @typedef {object} IMetadata + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @property {string|string[]} [mimeType] - The mime type to use for the source element + * of a video/audio elment. If the urls are an array, you can pass this as an array as well + * where each index is the mime type to use for the corresponding url index. + */ + + /** + * Stores whether or not this url is a data url. + * + * @readonly + * @member {boolean} + */ + + + /** + * Marks the resource as complete. + * + */ + Resource.prototype.complete = function complete() { + this._clearEvents(); + this._finish(); + }; + + /** + * Aborts the loading of this resource, with an optional message. + * + * @param {string} message - The message to use for the error + */ + + + Resource.prototype.abort = function abort(message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + + // store error + this.error = new Error(message); + + // clear events before calling aborts + this._clearEvents(); + + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } else if (this.xdr) { + this.xdr.abort(); + } else if (this.data) { + // single source + if (this.data.src) { + this.data.src = Resource.EMPTY_GIF; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + + // done now. + this._finish(); + }; + + /** + * Kicks off loading of this resource. This method is asynchronous. + * + * @param {Resource.OnCompleteSignal} [cb] - Optional callback to call once the resource is loaded. + */ + + + Resource.prototype.load = function load(cb) { + var _this = this; + + if (this.isLoading) { + return; + } + + if (this.isComplete) { + if (cb) { + setTimeout(function () { + return cb(_this); + }, 1); + } + + return; + } else if (cb) { + this.onComplete.once(cb); + } + + this._setFlag(Resource.STATUS_FLAGS.LOADING, true); + + this.onStart.dispatch(this); + + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + + switch (this.loadType) { + case Resource.LOAD_TYPE.IMAGE: + this.type = Resource.TYPE.IMAGE; + this._loadElement('image'); + break; + + case Resource.LOAD_TYPE.AUDIO: + this.type = Resource.TYPE.AUDIO; + this._loadSourceElement('audio'); + break; + + case Resource.LOAD_TYPE.VIDEO: + this.type = Resource.TYPE.VIDEO; + this._loadSourceElement('video'); + break; + + case Resource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } else { + this._loadXhr(); + } + break; + } + }; + + /** + * Checks if the flag is set. + * + * @private + * @param {number} flag - The flag to check. + * @return {boolean} True if the flag is set. + */ + + + Resource.prototype._hasFlag = function _hasFlag(flag) { + return (this._flags & flag) !== 0; + }; + + /** + * (Un)Sets the flag. + * + * @private + * @param {number} flag - The flag to (un)set. + * @param {boolean} value - Whether to set or (un)set the flag. + */ + + + Resource.prototype._setFlag = function _setFlag(flag, value) { + this._flags = value ? this._flags | flag : this._flags & ~flag; + }; + + /** + * Clears all the events from the underlying loading source. + * + * @private + */ + + + Resource.prototype._clearEvents = function _clearEvents() { + clearTimeout(this._elementTimer); + + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('timeout', this._boundXhrOnTimeout, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + }; + + /** + * Finalizes the load. + * + * @private + */ + + + Resource.prototype._finish = function _finish() { + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + + this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true); + this._setFlag(Resource.STATUS_FLAGS.LOADING, false); + + this.onComplete.dispatch(this); + }; + + /** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadElement = function _loadElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'image' && typeof window.Image !== 'undefined') { + this.data = new Image(); + } else { + this.data = document.createElement(type); + } + + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + + if (this.timeout) { + this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout); + } + }; + + /** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * + * @private + * @param {string} type - The type of element to use. + */ + + + Resource.prototype._loadSourceElement = function _loadSourceElement(type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } else if (type === 'audio' && typeof window.Audio !== 'undefined') { + this.data = new Audio(); + } else { + this.data = document.createElement(type); + } + + if (this.data === null) { + this.abort('Unsupported element: ' + type); + + return; + } + + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } else if (Array.isArray(this.url)) { + var mimeTypes = this.metadata.mimeType; + + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes)); + } + } else { + var _mimeTypes = this.metadata.mimeType; + + this.data.appendChild(this._createSource(type, this.url, Array.isArray(_mimeTypes) ? _mimeTypes[0] : _mimeTypes)); + } + } + + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + + this.data.load(); + + if (this.timeout) { + this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout); + } + }; + + /** + * Loads this resources using an XMLHttpRequest. + * + * @private + */ + + + Resource.prototype._loadXhr = function _loadXhr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xhr = this.xhr = new XMLHttpRequest(); + + // set the request type and url + xhr.open('GET', this.url, true); + + xhr.timeout = this.timeout; + + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; + } else { + xhr.responseType = this.xhrType; + } + + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('timeout', this._boundXhrOnTimeout, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + + xhr.send(); + }; + + /** + * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). + * + * @private + */ + + + Resource.prototype._loadXdr = function _loadXdr() { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + + var xdr = this.xhr = new XDomainRequest(); // eslint-disable-line no-undef + + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = this.timeout || 5000; // XDR needs a timeout value or it breaks in IE9 + + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXhrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + + xdr.open('GET', this.url, true); + + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { + return xdr.send(); + }, 1); + }; + + /** + * Creates a source used in loading via an element. + * + * @private + * @param {string} type - The element type (video or audio). + * @param {string} url - The source URL to load from. + * @param {string} [mime] - The mime type of the video + * @return {HTMLSourceElement} The source element. + */ + + + Resource.prototype._createSource = function _createSource(type, url, mime) { + if (!mime) { + mime = type + '/' + this._getExtension(url); + } + + var source = document.createElement('source'); + + source.src = url; + source.type = mime; + + return source; + }; + + /** + * Called if a load errors out. + * + * @param {Event} event - The error event from the element that emits it. + * @private + */ + + + Resource.prototype._onError = function _onError(event) { + this.abort('Failed to load element using: ' + event.target.nodeName); + }; + + /** + * Called if a load progress event fires for an element or xhr/xdr. + * + * @private + * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. + */ + + + Resource.prototype._onProgress = function _onProgress(event) { + if (event && event.lengthComputable) { + this.onProgress.dispatch(this, event.loaded / event.total); + } + }; + + /** + * Called if a timeout event fires for an element. + * + * @private + */ + + + Resource.prototype._onTimeout = function _onTimeout() { + this.abort('Load timed out.'); + }; + + /** + * Called if an error event fires for xhr/xdr. + * + * @private + */ + + + Resource.prototype._xhrOnError = function _xhrOnError() { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"'); + }; + + /** + * Called if an error event fires for xhr/xdr. + * + * @private + */ + + + Resource.prototype._xhrOnTimeout = function _xhrOnTimeout() { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request timed out.'); + }; + + /** + * Called if an abort event fires for xhr/xdr. + * + * @private + */ + + + Resource.prototype._xhrOnAbort = function _xhrOnAbort() { + var xhr = this.xhr; + + this.abort(reqType(xhr) + ' Request was aborted by the user.'); + }; + + /** + * Called when data successfully loads from an xhr/xdr request. + * + * @private + * @param {XMLHttpRequestLoadEvent|Event} event - Load event + */ + + + Resource.prototype._xhrOnLoad = function _xhrOnLoad() { + var xhr = this.xhr; + var text = ''; + var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200. + + // responseText is accessible only if responseType is '' or 'text' and on older browsers + if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') { + text = xhr.responseText; + } + + // status can be 0 when using the `file://` protocol so we also check if a response is set. + // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request. + if (status === STATUS_NONE && (text.length > 0 || xhr.responseType === Resource.XHR_RESPONSE_TYPE.BUFFER)) { + status = STATUS_OK; + } + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + else if (status === STATUS_IE_BUG_EMPTY) { + status = STATUS_EMPTY; + } + + var statusType = status / 100 | 0; + + if (statusType === STATUS_TYPE_OK) { + // if text, just return it + if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { + this.data = text; + this.type = Resource.TYPE.TEXT; + } + // if json, parse into json object + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(text); + this.type = Resource.TYPE.JSON; + } catch (e) { + this.abort('Error trying to parse loaded json: ' + e); + + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (window.DOMParser) { + var domparser = new DOMParser(); + + this.data = domparser.parseFromString(text, 'text/xml'); + } else { + var div = document.createElement('div'); + + div.innerHTML = text; + + this.data = div; + } + + this.type = Resource.TYPE.XML; + } catch (e) { + this.abort('Error trying to parse loaded xml: ' + e); + + return; + } + } + // other types just return the response + else { + this.data = xhr.response || text; + } + } else { + this.abort('[' + xhr.status + '] ' + xhr.statusText + ': ' + xhr.responseURL); + + return; + } + + this.complete(); + }; + + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * + * @private + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ + + + Resource.prototype._determineCrossOrigin = function _determineCrossOrigin(url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // A sandboxed iframe without the 'allow-same-origin' attribute will have a special + // origin designed not to match window.location.origin, and will always require + // crossOrigin requests regardless of whether the location matches. + if (window.origin !== window.location.origin) { + return 'anonymous'; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = (0, _parseUri2.default)(tempAnchor.href, { strictMode: true }); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + var protocol = url.protocol ? url.protocol + ':' : ''; + + // if cross origin + if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; + }; + + /** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. + */ + + + Resource.prototype._determineXhrType = function _determineXhrType() { + return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT; + }; + + /** + * Determines the loadType of a resource based on the extension of the + * resource being loaded. + * + * @private + * @return {Resource.LOAD_TYPE} The loadType to use. + */ + + + Resource.prototype._determineLoadType = function _determineLoadType() { + return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR; + }; + + /** + * Extracts the extension (sans '.') of the file being loaded by the resource. + * + * @private + * @return {string} The extension. + */ + + + Resource.prototype._getExtension = function _getExtension() { + var url = this.url; + var ext = ''; + + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } else { + var queryStart = url.indexOf('?'); + var hashStart = url.indexOf('#'); + var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length); + + url = url.substring(0, index); + ext = url.substring(url.lastIndexOf('.') + 1); + } + + return ext.toLowerCase(); + }; + + /** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * + * @private + * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. + * @return {string} The mime type to use. + */ + + + Resource.prototype._getMimeFromXhrType = function _getMimeFromXhrType(type) { + switch (type) { + case Resource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + + case Resource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + + case Resource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + + case Resource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + + case Resource.XHR_RESPONSE_TYPE.DEFAULT: + case Resource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + } + }; + + _createClass(Resource, [{ + key: 'isDataUrl', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL); + } + + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * + * @readonly + * @member {boolean} + */ + + }, { + key: 'isComplete', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE); + } + + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * + * @readonly + * @member {boolean} + */ + + }, { + key: 'isLoading', + get: function get() { + return this._hasFlag(Resource.STATUS_FLAGS.LOADING); + } + }]); + + return Resource; +}(); + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ + + +Resource.STATUS_FLAGS = { + NONE: 0, + DATA_URL: 1 << 0, + COMPLETE: 1 << 1, + LOADING: 1 << 2 +}; + +/** + * The types of resources a resource could represent. + * + * @static + * @readonly + * @enum {number} + */ +Resource.TYPE = { + UNKNOWN: 0, + JSON: 1, + XML: 2, + IMAGE: 3, + AUDIO: 4, + VIDEO: 5, + TEXT: 6 +}; + +/** + * The types of loading a resource can use. + * + * @static + * @readonly + * @enum {number} + */ +Resource.LOAD_TYPE = { + /** Uses XMLHttpRequest to load the resource. */ + XHR: 1, + /** Uses an `Image` object to load the resource. */ + IMAGE: 2, + /** Uses an `Audio` object to load the resource. */ + AUDIO: 3, + /** Uses a `Video` object to load the resource. */ + VIDEO: 4 +}; + +/** + * The XHR ready states, used internally. + * + * @static + * @readonly + * @enum {string} + */ +Resource.XHR_RESPONSE_TYPE = { + /** string */ + DEFAULT: 'text', + /** ArrayBuffer */ + BUFFER: 'arraybuffer', + /** Blob */ + BLOB: 'blob', + /** Document */ + DOCUMENT: 'document', + /** Object */ + JSON: 'json', + /** String */ + TEXT: 'text' +}; + +Resource._loadTypeMap = { + // images + gif: Resource.LOAD_TYPE.IMAGE, + png: Resource.LOAD_TYPE.IMAGE, + bmp: Resource.LOAD_TYPE.IMAGE, + jpg: Resource.LOAD_TYPE.IMAGE, + jpeg: Resource.LOAD_TYPE.IMAGE, + tif: Resource.LOAD_TYPE.IMAGE, + tiff: Resource.LOAD_TYPE.IMAGE, + webp: Resource.LOAD_TYPE.IMAGE, + tga: Resource.LOAD_TYPE.IMAGE, + svg: Resource.LOAD_TYPE.IMAGE, + 'svg+xml': Resource.LOAD_TYPE.IMAGE, // for SVG data urls + + // audio + mp3: Resource.LOAD_TYPE.AUDIO, + ogg: Resource.LOAD_TYPE.AUDIO, + wav: Resource.LOAD_TYPE.AUDIO, + + // videos + mp4: Resource.LOAD_TYPE.VIDEO, + webm: Resource.LOAD_TYPE.VIDEO +}; + +Resource._xhrTypeMap = { + // xml + xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + html: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. + // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, + // this should probably be fine. + tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT, + + // images + gif: Resource.XHR_RESPONSE_TYPE.BLOB, + png: Resource.XHR_RESPONSE_TYPE.BLOB, + bmp: Resource.XHR_RESPONSE_TYPE.BLOB, + jpg: Resource.XHR_RESPONSE_TYPE.BLOB, + jpeg: Resource.XHR_RESPONSE_TYPE.BLOB, + tif: Resource.XHR_RESPONSE_TYPE.BLOB, + tiff: Resource.XHR_RESPONSE_TYPE.BLOB, + webp: Resource.XHR_RESPONSE_TYPE.BLOB, + tga: Resource.XHR_RESPONSE_TYPE.BLOB, + + // json + json: Resource.XHR_RESPONSE_TYPE.JSON, + + // text + text: Resource.XHR_RESPONSE_TYPE.TEXT, + txt: Resource.XHR_RESPONSE_TYPE.TEXT, + + // fonts + ttf: Resource.XHR_RESPONSE_TYPE.BUFFER, + otf: Resource.XHR_RESPONSE_TYPE.BUFFER +}; + +// We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif +Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; + +/** + * Quick helper to set a value on one of the extension maps. Ensures there is no + * dot at the start of the extension. + * + * @ignore + * @param {object} map - The map to set on. + * @param {string} extname - The extension (or key) to set. + * @param {number} val - The value to set. + */ +function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + + if (!extname) { + return; + } + + map[extname] = val; +} + +/** + * Quick helper to get string xhr type. + * + * @ignore + * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. + * @return {string} The type. + */ +function reqType(xhr) { + return xhr.toString().replace('object ', ''); +} + +// Backwards compat +if (typeof module !== 'undefined') { + module.exports.default = Resource; // eslint-disable-line no-undef +} + +},{"mini-signals":5,"parse-uri":7}],34:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.eachSeries = eachSeries; +exports.queue = queue; +/** + * Smaller version of the async library constructs. + * + * @namespace async + */ + +/** + * Noop function + * + * @ignore + * @function + * @memberof async + */ +function _noop() {} /* empty */ + +/** + * Iterates an array in series. + * + * @memberof async + * @param {Array.<*>} array - Array to iterate. + * @param {function} iterator - Function to call for each element. + * @param {function} callback - Function to call when done, or on error. + * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1. + */ +function eachSeries(array, iterator, callback, deferNext) { + var i = 0; + var len = array.length; + + (function next(err) { + if (err || i === len) { + if (callback) { + callback(err); + } + + return; + } + + if (deferNext) { + setTimeout(function () { + iterator(array[i++], next); + }, 1); + } else { + iterator(array[i++], next); + } + })(); +} + +/** + * Ensures a function is only called once. + * + * @ignore + * @memberof async + * @param {function} fn - The function to wrap. + * @return {function} The wrapping function. + */ +function onlyOnce(fn) { + return function onceWrapper() { + if (fn === null) { + throw new Error('Callback was already called.'); + } + + var callFn = fn; + + fn = null; + callFn.apply(this, arguments); + }; +} + +/** + * Async queue implementation, + * + * @memberof async + * @param {function} worker - The worker function to call for each task. + * @param {number} concurrency - How many workers to run in parrallel. + * @return {*} The async queue object. + */ +function queue(worker, concurrency) { + if (concurrency == null) { + // eslint-disable-line no-eq-null,eqeqeq + concurrency = 1; + } else if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + + var workers = 0; + var q = { + _tasks: [], + concurrency: concurrency, + saturated: _noop, + unsaturated: _noop, + buffer: concurrency / 4, + empty: _noop, + drain: _noop, + error: _noop, + started: false, + paused: false, + push: function push(data, callback) { + _insert(data, false, callback); + }, + kill: function kill() { + workers = 0; + q.drain = _noop; + q.started = false; + q._tasks = []; + }, + unshift: function unshift(data, callback) { + _insert(data, true, callback); + }, + process: function process() { + while (!q.paused && workers < q.concurrency && q._tasks.length) { + var task = q._tasks.shift(); + + if (q._tasks.length === 0) { + q.empty(); + } + + workers += 1; + + if (workers === q.concurrency) { + q.saturated(); + } + + worker(task.data, onlyOnce(_next(task))); + } + }, + length: function length() { + return q._tasks.length; + }, + running: function running() { + return workers; + }, + idle: function idle() { + return q._tasks.length + workers === 0; + }, + pause: function pause() { + if (q.paused === true) { + return; + } + + q.paused = true; + }, + resume: function resume() { + if (q.paused === false) { + return; + } + + q.paused = false; + + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= q.concurrency; w++) { + q.process(); + } + } + }; + + function _insert(data, insertAtFront, callback) { + if (callback != null && typeof callback !== 'function') { + // eslint-disable-line no-eq-null,eqeqeq + throw new Error('task callback must be a function'); + } + + q.started = true; + + if (data == null && q.idle()) { + // eslint-disable-line no-eq-null,eqeqeq + // call drain immediately if there are no tasks + setTimeout(function () { + return q.drain(); + }, 1); + + return; + } + + var item = { + data: data, + callback: typeof callback === 'function' ? callback : _noop + }; + + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } + + setTimeout(function () { + return q.process(); + }, 1); + } + + function _next(task) { + return function next() { + workers -= 1; + + task.callback.apply(task, arguments); + + if (arguments[0] != null) { + // eslint-disable-line no-eq-null,eqeqeq + q.error(arguments[0], task.data); + } + + if (workers <= q.concurrency - q.buffer) { + q.unsaturated(); + } + + if (q.idle()) { + q.drain(); + } + + q.process(); + }; + } + + return q; +} + +},{}],35:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.encodeBinary = encodeBinary; +var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + +/** + * Encodes binary into base64. + * + * @param {string} input The input data to encode. + * @returns {string} The encoded base64 string + */ +function encodeBinary(input) { + var output = ''; + var inx = 0; + + while (inx < input.length) { + // Fill byte buffer array + var bytebuffer = [0, 0, 0]; + var encodedCharIndexes = [0, 0, 0, 0]; + + for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } else { + bytebuffer[jnx] = 0; + } + } + + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4; + + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6; + + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + + // Determine whether padding happened, and adjust accordingly + var paddingBytes = inx - (input.length - 1); + + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + + default: + break; // No padding - proceed + } + + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) { + output += _keyStr.charAt(encodedCharIndexes[_jnx]); + } + } + + return output; +} + +// Backwards compat +if (typeof module !== 'undefined') { + module.exports.default = encodeBinary; // eslint-disable-line no-undef +} + +},{}],36:[function(require,module,exports){ +'use strict'; + +// import Loader from './Loader'; +// import Resource from './Resource'; +// import * as async from './async'; +// import * as b64 from './b64'; + +/* eslint-disable no-undef */ + +var Loader = require('./Loader').Loader; +var Resource = require('./Resource').Resource; +var async = require('./async'); +var b64 = require('./b64'); + +/** + * + * @static + * @memberof Loader + * @member {Class} + */ +Loader.Resource = Resource; + +/** + * + * @static + * @memberof Loader + * @member {Class} + */ +Loader.async = async; + +/** + * + * @static + * @memberof Loader + * @member {Class} + */ +Loader.encodeBinary = b64; + +/** + * + * @deprecated + * @see Loader.encodeBinary + * + * @static + * @memberof Loader + * @member {Class} + */ +Loader.base64 = b64; + +// export manually, and also as default +module.exports = Loader; + +// default & named export +module.exports.Loader = Loader; +module.exports.default = Loader; + +},{"./Loader":32,"./Resource":33,"./async":34,"./b64":35}],37:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.blobMiddlewareFactory = blobMiddlewareFactory; + +var _Resource = require('../../Resource'); + +var _b = require('../../b64'); + +var Url = window.URL || window.webkitURL; + +// a middleware for transforming XHR loaded Blobs into more useful objects +function blobMiddlewareFactory() { + return function blobMiddleware(resource, next) { + if (!resource.data) { + next(); + + return; + } + + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === _Resource.Resource.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!window.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = 'data:' + type + ';base64,' + (0, _b.encodeBinary)(resource.xhr.responseText); + + resource.type = _Resource.Resource.TYPE.IMAGE; + + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + + next(); + }; + + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var src = Url.createObjectURL(resource.data); + + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src; + + resource.type = _Resource.Resource.TYPE.IMAGE; + + // cleanup the no longer used blob after the image loads + // TODO: Is this correct? Will the image be invalid after revoking? + resource.data.onload = function () { + Url.revokeObjectURL(src); + resource.data.onload = null; + + next(); + }; + + // next will be called on load. + return; + } + } + + next(); + }; +} + +},{"../../Resource":33,"../../b64":35}],38:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +var punycode = require('punycode'); +var util = require('./util'); + +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; + +exports.Url = Url; + +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; +} + +// Reference: RFC 3986, RFC 1808, RFC 2396 + +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); + +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} + +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; +}; + +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); +} + +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; +}; + +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} + +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; + +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} + +Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; +}; + +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) this.hostname = host; +}; + +},{"./util":39,"punycode":27,"querystring":30}],39:[function(require,module,exports){ +'use strict'; + +module.exports = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } +}; + +},{}],40:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +var _accessibleTarget = require('./accessibleTarget'); + +var _accessibleTarget2 = _interopRequireDefault(_accessibleTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// add some extra variables to the container.. +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _accessibleTarget2.default); + +var KEY_CODE_TAB = 9; + +var DIV_TOUCH_SIZE = 100; +var DIV_TOUCH_POS_X = 0; +var DIV_TOUCH_POS_Y = 0; +var DIV_TOUCH_ZINDEX = 2; + +var DIV_HOOK_SIZE = 1; +var DIV_HOOK_POS_X = -1000; +var DIV_HOOK_POS_Y = -1000; +var DIV_HOOK_ZINDEX = 2; + +/** + * The Accessibility manager recreates the ability to tab and have content read by screen + * readers. This is very important as it can possibly help people with disabilities access pixi + * content. + * + * Much like interaction any DisplayObject can be made accessible. This manager will map the + * events as if the mouse was being used, minimizing the effort required to implement. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.accessibility + * + * @class + * @memberof PIXI.accessibility + */ + +var AccessibilityManager = function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + _classCallCheck(this, AccessibilityManager); + + if ((_ismobilejs2.default.tablet || _ismobilejs2.default.phone) && !navigator.isCocoonJS) { + this.createTouchHook(); + } + + // first we create a div that will sit over the PixiJS element. This is where the div overlays will go. + var div = document.createElement('div'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + 'px'; + div.style.left = DIV_TOUCH_POS_Y + 'px'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + + /** + * This is the dom element that will sit over the PixiJS element. This is where the div overlays will go. + * + * @type {HTMLElement} + * @private + */ + this.div = div; + + /** + * A simple pool for storing divs. + * + * @type {*} + * @private + */ + this.pool = []; + + /** + * This is a tick used to check if an object is no longer being rendered. + * + * @type {Number} + * @private + */ + this.renderId = 0; + + /** + * Setting this to true will visually show the divs. + * + * @type {boolean} + */ + this.debug = false; + + /** + * The renderer this accessibility manager works for. + * + * @member {PIXI.SystemRenderer} + */ + this.renderer = renderer; + + /** + * The array of currently active accessible items. + * + * @member {Array<*>} + * @private + */ + this.children = []; + + /** + * pre-bind the functions + * + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + this._onMouseMove = this._onMouseMove.bind(this); + + /** + * stores the state of the manager. If there are no accessible objects or the mouse is moving, this will be false. + * + * @member {Array<*>} + * @private + */ + this.isActive = false; + this.isMobileAccessabillity = false; + + // let listen for tab.. once pressed we can fire up and show the accessibility layer + window.addEventListener('keydown', this._onKeyDown, false); + } + + /** + * Creates the touch hooks. + * + */ + + + AccessibilityManager.prototype.createTouchHook = function createTouchHook() { + var _this = this; + + var hookDiv = document.createElement('button'); + + hookDiv.style.width = DIV_HOOK_SIZE + 'px'; + hookDiv.style.height = DIV_HOOK_SIZE + 'px'; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + 'px'; + hookDiv.style.left = DIV_HOOK_POS_Y + 'px'; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX; + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'HOOK DIV'; + + hookDiv.addEventListener('focus', function () { + _this.isMobileAccessabillity = true; + _this.activate(); + document.body.removeChild(hookDiv); + }); + + document.body.appendChild(hookDiv); + }; + + /** + * Activating will cause the Accessibility layer to be shown. This is called when a user + * preses the tab key. + * + * @private + */ + + + AccessibilityManager.prototype.activate = function activate() { + if (this.isActive) { + return; + } + + this.isActive = true; + + window.document.addEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown, false); + + this.renderer.on('postrender', this.update, this); + + if (this.renderer.view.parentNode) { + this.renderer.view.parentNode.appendChild(this.div); + } + }; + + /** + * Deactivating will cause the Accessibility layer to be hidden. This is called when a user moves + * the mouse. + * + * @private + */ + + + AccessibilityManager.prototype.deactivate = function deactivate() { + if (!this.isActive || this.isMobileAccessabillity) { + return; + } + + this.isActive = false; + + window.document.removeEventListener('mousemove', this._onMouseMove, true); + window.addEventListener('keydown', this._onKeyDown, false); + + this.renderer.off('postrender', this.update); + + if (this.div.parentNode) { + this.div.parentNode.removeChild(this.div); + } + }; + + /** + * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. + * + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + + + AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects(displayObject) { + if (!displayObject.visible) { + return; + } + + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + + displayObject.renderId = this.renderId; + } + + var children = displayObject.children; + + for (var i = 0; i < children.length; i++) { + this.updateAccessibleObjects(children[i]); + } + }; + + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * + * @private + */ + + + AccessibilityManager.prototype.update = function update() { + if (!this.renderer.renderingToScreen) { + return; + } + + // update children... + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + + var rect = this.renderer.view.getBoundingClientRect(); + var sx = rect.width / this.renderer.width; + var sy = rect.height / this.renderer.height; + + var div = this.div; + + div.style.left = rect.left + 'px'; + div.style.top = rect.top + 'px'; + div.style.width = this.renderer.width + 'px'; + div.style.height = this.renderer.height + 'px'; + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + + core.utils.removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + + i--; + + if (this.children.length === 0) { + this.deactivate(); + } + } else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + + if (child.hitArea) { + div.style.left = (wt.tx + hitArea.x * wt.a) * sx + 'px'; + div.style.top = (wt.ty + hitArea.y * wt.d) * sy + 'px'; + + div.style.width = hitArea.width * wt.a * sx + 'px'; + div.style.height = hitArea.height * wt.d * sy + 'px'; + } else { + hitArea = child.getBounds(); + + this.capHitArea(hitArea); + + div.style.left = hitArea.x * sx + 'px'; + div.style.top = hitArea.y * sy + 'px'; + + div.style.width = hitArea.width * sx + 'px'; + div.style.height = hitArea.height * sy + 'px'; + + // update button titles and hints if they exist and they've changed + if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) { + div.title = child.accessibleTitle; + } + if (div.getAttribute('aria-label') !== child.accessibleHint && child.accessibleHint !== null) { + div.setAttribute('aria-label', child.accessibleHint); + } + } + } + } + + // increment the render id.. + this.renderId++; + }; + + /** + * TODO: docs. + * + * @param {Rectangle} hitArea - TODO docs + */ + + + AccessibilityManager.prototype.capHitArea = function capHitArea(hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + + if (hitArea.x + hitArea.width > this.renderer.width) { + hitArea.width = this.renderer.width - hitArea.x; + } + + if (hitArea.y + hitArea.height > this.renderer.height) { + hitArea.height = this.renderer.height - hitArea.y; + } + }; + + /** + * Adds a DisplayObject to the accessibility manager + * + * @private + * @param {DisplayObject} displayObject - The child to make accessible. + */ + + + AccessibilityManager.prototype.addChild = function addChild(displayObject) { + // this.activate(); + + var div = this.pool.pop(); + + if (!div) { + div = document.createElement('button'); + + div.style.width = DIV_TOUCH_SIZE + 'px'; + div.style.height = DIV_TOUCH_SIZE + 'px'; + div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX; + div.style.borderStyle = 'none'; + + // ARIA attributes ensure that button title and hint updates are announced properly + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + // Chrome doesn't need aria-live to work as intended; in fact it just gets more confused. + div.setAttribute('aria-live', 'off'); + } else { + div.setAttribute('aria-live', 'polite'); + } + + if (navigator.userAgent.match(/rv:.*Gecko\//)) { + // FireFox needs this to announce only the new button name + div.setAttribute('aria-relevant', 'additions'); + } else { + // required by IE, other browsers don't much care + div.setAttribute('aria-relevant', 'text'); + } + + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + + if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) { + div.title = displayObject.accessibleTitle; + } else if (!displayObject.accessibleHint || displayObject.accessibleHint === null) { + div.title = 'displayObject ' + displayObject.tabIndex; + } + + if (displayObject.accessibleHint && displayObject.accessibleHint !== null) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + + // + + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + + /** + * Maps the div button press to pixi's InteractionManager (click) + * + * @private + * @param {MouseEvent} e - The click event. + */ + + + AccessibilityManager.prototype._onClick = function _onClick(e) { + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixi's InteractionManager (mouseover) + * + * @private + * @param {FocusEvent} e - The focus event. + */ + + + AccessibilityManager.prototype._onFocus = function _onFocus(e) { + if (!e.target.getAttribute('aria-live', 'off')) { + e.target.setAttribute('aria-live', 'assertive'); + } + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); + }; + + /** + * Maps the div focus events to pixi's InteractionManager (mouseout) + * + * @private + * @param {FocusEvent} e - The focusout event. + */ + + + AccessibilityManager.prototype._onFocusOut = function _onFocusOut(e) { + if (!e.target.getAttribute('aria-live', 'off')) { + e.target.setAttribute('aria-live', 'polite'); + } + var interactionManager = this.renderer.plugins.interaction; + + interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); + }; + + /** + * Is called when a key is pressed + * + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + + + AccessibilityManager.prototype._onKeyDown = function _onKeyDown(e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + + this.activate(); + }; + + /** + * Is called when the mouse moves across the renderer element + * + * @private + * @param {MouseEvent} e - The mouse event. + */ + + + AccessibilityManager.prototype._onMouseMove = function _onMouseMove(e) { + if (e.movementX === 0 && e.movementY === 0) { + return; + } + + this.deactivate(); + }; + + /** + * Destroys the accessibility manager + * + */ + + + AccessibilityManager.prototype.destroy = function destroy() { + this.div = null; + + for (var i = 0; i < this.children.length; i++) { + this.children[i].div = null; + } + + window.document.removeEventListener('mousemove', this._onMouseMove, true); + window.removeEventListener('keydown', this._onKeyDown); + + this.pool = null; + this.children = null; + this.renderer = null; + }; + + return AccessibilityManager; +}(); + +exports.default = AccessibilityManager; + + +core.WebGLRenderer.registerPlugin('accessibility', AccessibilityManager); +core.CanvasRenderer.registerPlugin('accessibility', AccessibilityManager); + +},{"../core":65,"./accessibleTarget":41,"ismobilejs":4}],41:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Default property values of accessible objects + * used by {@link PIXI.accessibility.AccessibilityManager}. + * + * @function accessibleTarget + * @memberof PIXI.accessibility + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibility.accessibleTarget + * ); + */ +exports.default = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * + * @member {boolean} + */ + accessible: false, + + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * + * @member {string} + */ + accessibleTitle: null, + + /** + * Sets the aria-label attribute of the shadow div + * + * @member {string} + */ + accessibleHint: null, + + /** + * @todo Needs docs. + */ + tabIndex: 0, + + /** + * @todo Needs docs. + */ + _accessibleActive: false, + + /** + * @todo Needs docs. + */ + _accessibleDiv: false +}; + +},{}],42:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _accessibleTarget = require('./accessibleTarget'); + +Object.defineProperty(exports, 'accessibleTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_accessibleTarget).default; + } +}); + +var _AccessibilityManager = require('./AccessibilityManager'); + +Object.defineProperty(exports, 'AccessibilityManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AccessibilityManager).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./AccessibilityManager":40,"./accessibleTarget":41}],43:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +var _Container = require('./display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _ticker = require('./ticker'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _const = require('./const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Convenience class to create a new PIXI application. + * This class automatically creates the renderer, ticker + * and root container. + * + * @example + * // Create the application + * const app = new PIXI.Application(); + * + * // Add the view to the DOM + * document.body.appendChild(app.view); + * + * // ex, add display objects + * app.stage.addChild(PIXI.Sprite.fromImage('something.png')); + * + * @class + * @memberof PIXI + */ +var Application = function () { + // eslint-disable-next-line valid-jsdoc + /** + * @param {object} [options] - The optional renderer parameters + * @param {boolean} [options.autoStart=true] - automatically starts the rendering after the construction. + * Note that setting this parameter to false does NOT stop the shared ticker even if you set + * options.sharedTicker to true in case that it is already started. Stop it by your own. + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great **webgl only** + * @param {boolean} [options.legacy=false] - `true` to ensure compatibility with older / less advanced devices. + * If you experience unexplained flickering try setting this to true. **webgl only** + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card **webgl only** + * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.ticker.shared, `false` to create new ticker. + * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.loaders.shared, `false` to create new Loader. + */ + function Application(options, arg2, arg3, arg4, arg5) { + _classCallCheck(this, Application); + + // Support for constructor(width, height, options, noWebGL, useSharedTicker) + if (typeof options === 'number') { + options = Object.assign({ + width: options, + height: arg2 || _settings2.default.RENDER_OPTIONS.height, + forceCanvas: !!arg4, + sharedTicker: !!arg5 + }, arg3); + } + + /** + * The default options, so we mixin functionality later. + * @member {object} + * @protected + */ + this._options = options = Object.assign({ + autoStart: true, + sharedTicker: false, + forceCanvas: false, + sharedLoader: false + }, options); + + /** + * WebGL renderer if available, otherwise CanvasRenderer + * @member {PIXI.WebGLRenderer|PIXI.CanvasRenderer} + */ + this.renderer = (0, _autoDetectRenderer.autoDetectRenderer)(options); + + /** + * The root display container that's rendered. + * @member {PIXI.Container} + */ + this.stage = new _Container2.default(); + + /** + * Internal reference to the ticker + * @member {PIXI.ticker.Ticker} + * @private + */ + this._ticker = null; + + /** + * Ticker for doing render updates. + * @member {PIXI.ticker.Ticker} + * @default PIXI.ticker.shared + */ + this.ticker = options.sharedTicker ? _ticker.shared : new _ticker.Ticker(); + + // Start the rendering + if (options.autoStart) { + this.start(); + } + } + + /** + * Render the current stage. + */ + Application.prototype.render = function render() { + this.renderer.render(this.stage); + }; + + /** + * Convenience method for stopping the render. + */ + + + Application.prototype.stop = function stop() { + this._ticker.stop(); + }; + + /** + * Convenience method for starting the render. + */ + + + Application.prototype.start = function start() { + this._ticker.start(); + }; + + /** + * Reference to the renderer's canvas element. + * @member {HTMLCanvasElement} + * @readonly + */ + + + /** + * Destroy and don't use after this. + * @param {Boolean} [removeView=false] Automatically remove canvas from DOM. + * @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy + * method called as well. 'stageOptions' will be passed on to those calls. + * @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set + * to true. Should it destroy the texture of the child sprite + * @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set + * to true. Should it destroy the base texture of the child sprite + */ + Application.prototype.destroy = function destroy(removeView, stageOptions) { + if (this._ticker) { + var oldTicker = this._ticker; + + this.ticker = null; + oldTicker.destroy(); + } + + this.stage.destroy(stageOptions); + this.stage = null; + + this.renderer.destroy(removeView); + this.renderer = null; + + this._options = null; + }; + + _createClass(Application, [{ + key: 'ticker', + set: function set(ticker) // eslint-disable-line require-jsdoc + { + if (this._ticker) { + this._ticker.remove(this.render, this); + } + this._ticker = ticker; + if (ticker) { + ticker.add(this.render, this, _const.UPDATE_PRIORITY.LOW); + } + }, + get: function get() // eslint-disable-line require-jsdoc + { + return this._ticker; + } + }, { + key: 'view', + get: function get() { + return this.renderer.view; + } + + /** + * Reference to the renderer's screen rectangle. Its safe to use as filterArea or hitArea for whole screen + * @member {PIXI.Rectangle} + * @readonly + */ + + }, { + key: 'screen', + get: function get() { + return this.renderer.screen; + } + }]); + + return Application; +}(); + +exports.default = Application; + +},{"./autoDetectRenderer":45,"./const":46,"./display/Container":48,"./settings":101,"./ticker":121}],44:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function checkPrecision(src, def) { + if (src instanceof Array) { + if (src[0].substring(0, 9) !== 'precision') { + var copy = src.slice(0); + + copy.unshift('precision ' + def + ' float;'); + + return copy; + } + } else if (src.trim().substring(0, 9) !== 'precision') { + return 'precision ' + def + ' float;\n' + src; + } + + return src; +} + +/** + * Wrapper class, webGL Shader for Pixi. + * Adds precision string if vertexSrc or fragmentSrc have no mention of it. + * + * @class + * @extends GLShader + * @memberof PIXI + */ + +var Shader = function (_GLShader) { + _inherits(Shader, _GLShader); + + /** + * + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + * @param {string|string[]} vertexSrc - The vertex shader source as an array of strings. + * @param {string|string[]} fragmentSrc - The fragment shader source as an array of strings. + * @param {object} [attributeLocations] - A key value pair showing which location eact attribute should sit. + e.g. {position:0, uvs:1}. + * @param {string} [precision] - The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. + */ + function Shader(gl, vertexSrc, fragmentSrc, attributeLocations, precision) { + _classCallCheck(this, Shader); + + return _possibleConstructorReturn(this, _GLShader.call(this, gl, checkPrecision(vertexSrc, precision || _settings2.default.PRECISION_VERTEX), checkPrecision(fragmentSrc, precision || _settings2.default.PRECISION_FRAGMENT), undefined, attributeLocations)); + } + + return Shader; +}(_pixiGlCore.GLShader); + +exports.default = Shader; + +},{"./settings":101,"pixi-gl-core":15}],45:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = autoDetectRenderer; + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +// eslint-disable-next-line valid-jsdoc +/** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by + * the browser then this function will return a canvas renderer + * + * @memberof PIXI + * @function autoDetectRenderer + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great **webgl only** + * @param {boolean} [options.legacy=false] - `true` to ensure compatibility with older / less advanced devices. + * If you experience unexplained flickering try setting this to true. **webgl only** + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card **webgl only** + * @return {PIXI.WebGLRenderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ +function autoDetectRenderer(options, arg1, arg2, arg3) { + // Backward-compatible support for noWebGL option + var forceCanvas = options && options.forceCanvas; + + if (arg3 !== undefined) { + forceCanvas = arg3; + } + + if (!forceCanvas && utils.isWebGLSupported()) { + return new _WebGLRenderer2.default(options, arg1, arg2); + } + + return new _CanvasRenderer2.default(options, arg1, arg2); +} + +},{"./renderers/canvas/CanvasRenderer":77,"./renderers/webgl/WebGLRenderer":84,"./utils":125}],46:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * String of the current PIXI version. + * + * @static + * @constant + * @memberof PIXI + * @name VERSION + * @type {string} + */ +var VERSION = exports.VERSION = '4.8.9'; + +/** + * Two Pi. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var PI_2 = exports.PI_2 = Math.PI * 2; + +/** + * Conversion factor for converting radians to degrees. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var RAD_TO_DEG = exports.RAD_TO_DEG = 180 / Math.PI; + +/** + * Conversion factor for converting degrees to radians. + * + * @static + * @constant + * @memberof PIXI + * @type {number} + */ +var DEG_TO_RAD = exports.DEG_TO_RAD = Math.PI / 180; + +/** + * Constant to identify the Renderer Type. + * + * @static + * @constant + * @memberof PIXI + * @name RENDERER_TYPE + * @type {object} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ +var RENDERER_TYPE = exports.RENDERER_TYPE = { + UNKNOWN: 0, + WEBGL: 1, + CANVAS: 2 +}; + +/** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * + * @static + * @constant + * @memberof PIXI + * @name BLEND_MODES + * @type {object} + * @property {number} NORMAL + * @property {number} ADD + * @property {number} MULTIPLY + * @property {number} SCREEN + * @property {number} OVERLAY + * @property {number} DARKEN + * @property {number} LIGHTEN + * @property {number} COLOR_DODGE + * @property {number} COLOR_BURN + * @property {number} HARD_LIGHT + * @property {number} SOFT_LIGHT + * @property {number} DIFFERENCE + * @property {number} EXCLUSION + * @property {number} HUE + * @property {number} SATURATION + * @property {number} COLOR + * @property {number} LUMINOSITY + */ +var BLEND_MODES = exports.BLEND_MODES = { + NORMAL: 0, + ADD: 1, + MULTIPLY: 2, + SCREEN: 3, + OVERLAY: 4, + DARKEN: 5, + LIGHTEN: 6, + COLOR_DODGE: 7, + COLOR_BURN: 8, + HARD_LIGHT: 9, + SOFT_LIGHT: 10, + DIFFERENCE: 11, + EXCLUSION: 12, + HUE: 13, + SATURATION: 14, + COLOR: 15, + LUMINOSITY: 16, + NORMAL_NPM: 17, + ADD_NPM: 18, + SCREEN_NPM: 19 +}; + +/** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * + * @static + * @constant + * @memberof PIXI + * @name DRAW_MODES + * @type {object} + * @property {number} POINTS + * @property {number} LINES + * @property {number} LINE_LOOP + * @property {number} LINE_STRIP + * @property {number} TRIANGLES + * @property {number} TRIANGLE_STRIP + * @property {number} TRIANGLE_FAN + */ +var DRAW_MODES = exports.DRAW_MODES = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6 +}; + +/** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * + * @static + * @constant + * @memberof PIXI + * @name SCALE_MODES + * @type {object} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ +var SCALE_MODES = exports.SCALE_MODES = { + LINEAR: 0, + NEAREST: 1 +}; + +/** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as webGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * + * @static + * @constant + * @name WRAP_MODES + * @memberof PIXI + * @type {object} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ +var WRAP_MODES = exports.WRAP_MODES = { + CLAMP: 0, + REPEAT: 1, + MIRRORED_REPEAT: 2 +}; + +/** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * + * @static + * @constant + * @name GC_MODES + * @memberof PIXI + * @type {object} + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ +var GC_MODES = exports.GC_MODES = { + AUTO: 0, + MANUAL: 1 +}; + +/** + * Regexp for image type by extension. + * + * @static + * @constant + * @memberof PIXI + * @type {RegExp|string} + * @example `image.png` + */ +var URL_FILE_EXTENSION = exports.URL_FILE_EXTENSION = /\.(\w{3,4})(?:$|\?|#)/i; + +/** + * Regexp for data URI. + * Based on: {@link https://github.com/ragingwind/data-uri-regex} + * + * @static + * @constant + * @name DATA_URI + * @memberof PIXI + * @type {RegExp|string} + * @example data:image/png;base64 + */ +var DATA_URI = exports.DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i; + +/** + * Regexp for SVG size. + * + * @static + * @constant + * @name SVG_SIZE + * @memberof PIXI + * @type {RegExp|string} + * @example <svg width="100" height="100"></svg> + */ +var SVG_SIZE = exports.SVG_SIZE = /]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len + +/** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * + * @static + * @constant + * @name SHAPES + * @memberof PIXI + * @type {object} + * @property {number} POLY Polygon + * @property {number} RECT Rectangle + * @property {number} CIRC Circle + * @property {number} ELIP Ellipse + * @property {number} RREC Rounded Rectangle + */ +var SHAPES = exports.SHAPES = { + POLY: 0, + RECT: 1, + CIRC: 2, + ELIP: 3, + RREC: 4 +}; + +/** + * Constants that specify float precision in shaders. + * + * @static + * @constant + * @name PRECISION + * @memberof PIXI + * @type {object} + * @property {string} LOW='lowp' + * @property {string} MEDIUM='mediump' + * @property {string} HIGH='highp' + */ +var PRECISION = exports.PRECISION = { + LOW: 'lowp', + MEDIUM: 'mediump', + HIGH: 'highp' +}; + +/** + * Constants that specify the transform type. + * + * @static + * @constant + * @name TRANSFORM_MODE + * @memberof PIXI + * @type {object} + * @property {number} STATIC + * @property {number} DYNAMIC + */ +var TRANSFORM_MODE = exports.TRANSFORM_MODE = { + STATIC: 0, + DYNAMIC: 1 +}; + +/** + * Constants that define the type of gradient on text. + * + * @static + * @constant + * @name TEXT_GRADIENT + * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL Vertical gradient + * @property {number} LINEAR_HORIZONTAL Linear gradient + */ +var TEXT_GRADIENT = exports.TEXT_GRADIENT = { + LINEAR_VERTICAL: 0, + LINEAR_HORIZONTAL: 1 +}; + +/** + * Represents the update priorities used by internal PIXI classes when registered with + * the {@link PIXI.ticker.Ticker} object. Higher priority items are updated first and lower + * priority items, such as render, should go later. + * + * @static + * @constant + * @name UPDATE_PRIORITY + * @memberof PIXI + * @type {object} + * @property {number} INTERACTION=50 Highest priority, used for {@link PIXI.interaction.InteractionManager} + * @property {number} HIGH=25 High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.extras.AnimatedSprite} + * @property {number} NORMAL=0 Default priority for ticker events, see {@link PIXI.ticker.Ticker#add}. + * @property {number} LOW=-25 Low priority used for {@link PIXI.Application} rendering. + * @property {number} UTILITY=-50 Lowest priority used for {@link PIXI.prepare.BasePrepare} utility. + */ +var UPDATE_PRIORITY = exports.UPDATE_PRIORITY = { + INTERACTION: 50, + HIGH: 25, + NORMAL: 0, + LOW: -25, + UTILITY: -50 +}; + +},{}],47:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * 'Builder' pattern for bounds rectangles + * Axis-Aligned Bounding Box + * It is not a shape! Its mutable thing, no 'EMPTY' or that kind of problems + * + * @class + * @memberof PIXI + */ +var Bounds = function () { + /** + * + */ + function Bounds() { + _classCallCheck(this, Bounds); + + /** + * @member {number} + * @default 0 + */ + this.minX = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.minY = Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxX = -Infinity; + + /** + * @member {number} + * @default 0 + */ + this.maxY = -Infinity; + + this.rect = null; + } + + /** + * Checks if bounds are empty. + * + * @return {boolean} True if empty. + */ + + + Bounds.prototype.isEmpty = function isEmpty() { + return this.minX > this.maxX || this.minY > this.maxY; + }; + + /** + * Clears the bounds and resets. + * + */ + + + Bounds.prototype.clear = function clear() { + this.updateID++; + + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * + * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty + * @returns {PIXI.Rectangle} A rectangle of the bounds + */ + + + Bounds.prototype.getRectangle = function getRectangle(rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return _math.Rectangle.EMPTY; + } + + rect = rect || new _math.Rectangle(0, 0, 1, 1); + + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + + return rect; + }; + + /** + * This function should be inlined when its possible. + * + * @param {PIXI.Point} point - The point to add. + */ + + + Bounds.prototype.addPoint = function addPoint(point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + }; + + /** + * Adds a quad, not transformed + * + * @param {Float32Array} vertices - The verts to add. + */ + + + Bounds.prototype.addQuad = function addQuad(vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = vertices[0]; + var y = vertices[1]; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds sprite frame, transformed. + * + * @param {PIXI.TransformBase} transform - TODO + * @param {number} x0 - TODO + * @param {number} y0 - TODO + * @param {number} x1 - TODO + * @param {number} y1 - TODO + */ + + + Bounds.prototype.addFrame = function addFrame(transform, x0, y0, x1, y1) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + var x = a * x0 + c * y0 + tx; + var y = b * x0 + d * y0 + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y0 + tx; + y = b * x1 + d * y0 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x0 + c * y1 + tx; + y = b * x0 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + x = a * x1 + c * y1 + tx; + y = b * x1 + d * y1 + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Add an array of vertices + * + * @param {PIXI.TransformBase} transform - TODO + * @param {Float32Array} vertices - TODO + * @param {number} beginOffset - TODO + * @param {number} endOffset - TODO + */ + + + Bounds.prototype.addVertices = function addVertices(transform, vertices, beginOffset, endOffset) { + var matrix = transform.worldTransform; + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = a * rawX + c * rawY + tx; + var y = d * rawY + b * rawX + ty; + + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + + /** + * Adds other Bounds + * + * @param {PIXI.Bounds} bounds - TODO + */ + + + Bounds.prototype.addBounds = function addBounds(bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + }; + + /** + * Adds other Bounds, masked with Bounds + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Bounds} mask - TODO + */ + + + Bounds.prototype.addBoundsMask = function addBoundsMask(bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + /** + * Adds other Bounds, masked with Rectangle + * + * @param {PIXI.Bounds} bounds - TODO + * @param {PIXI.Rectangle} area - TODO + */ + + + Bounds.prototype.addBoundsArea = function addBoundsArea(bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : area.x + area.width; + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : area.y + area.height; + + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + + return Bounds; +}(); + +exports.default = Bounds; + +},{"../math":70}],48:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _DisplayObject2 = require('./DisplayObject'); + +var _DisplayObject3 = _interopRequireDefault(_DisplayObject2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A Container represents a collection of display objects. + * It is the base class of all display objects that act as a container for other objects. + * + *```js + * let container = new PIXI.Container(); + * container.addChild(sprite); + * ``` + * + * @class + * @extends PIXI.DisplayObject + * @memberof PIXI + */ +var Container = function (_DisplayObject) { + _inherits(Container, _DisplayObject); + + /** + * + */ + function Container() { + _classCallCheck(this, Container); + + /** + * The array of children of this container. + * + * @member {PIXI.DisplayObject[]} + * @readonly + */ + var _this = _possibleConstructorReturn(this, _DisplayObject.call(this)); + + _this.children = []; + return _this; + } + + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified + * + * @private + */ + + + Container.prototype.onChildrenChange = function onChildrenChange() {} + /* empty */ + + + /** + * Adds one or more children to the container. + * + * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container + * @return {PIXI.DisplayObject} The first child that was added. + */ + ; + + Container.prototype.addChild = function addChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.addChild(arguments[i]); + } + } else { + // if the child has a parent then lets remove it as PixiJS objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.push(child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + child.emit('added', this); + } + + return child; + }; + + /** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @return {PIXI.DisplayObject} The child that was added. + */ + + + Container.prototype.addChildAt = function addChildAt(child, index) { + if (index < 0 || index > this.children.length) { + throw new Error(child + 'addChildAt: The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + if (child.parent) { + child.parent.removeChild(child); + } + + child.parent = this; + // ensure child transform will be recalculated + child.transform._parentID = -1; + + this.children.splice(index, 0, child); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + + return child; + }; + + /** + * Swaps the position of 2 Display Objects within this container. + * + * @param {PIXI.DisplayObject} child - First display object to swap + * @param {PIXI.DisplayObject} child2 - Second display object to swap + */ + + + Container.prototype.swapChildren = function swapChildren(child, child2) { + if (child === child2) { + return; + } + + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; + + /** + * Returns the index position of a child DisplayObject instance + * + * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify + * @return {number} The index position of the child display object to identify + */ + + + Container.prototype.getChildIndex = function getChildIndex(child) { + var index = this.children.indexOf(child); + + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + + return index; + }; + + /** + * Changes the position of an existing child in the display object container + * + * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number + * @param {number} index - The resulting index number for the child display object + */ + + + Container.prototype.setChildIndex = function setChildIndex(child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error('The index ' + index + ' supplied is out of bounds ' + this.children.length); + } + + var currentIndex = this.getChildIndex(child); + + (0, _utils.removeItems)(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + + this.onChildrenChange(index); + }; + + /** + * Returns the child at the specified index + * + * @param {number} index - The index to get the child at + * @return {PIXI.DisplayObject} The child at the given index, if any. + */ + + + Container.prototype.getChildAt = function getChildAt(index) { + if (index < 0 || index >= this.children.length) { + throw new Error('getChildAt: Index (' + index + ') does not exist.'); + } + + return this.children[index]; + }; + + /** + * Removes one or more children from the container. + * + * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove + * @return {PIXI.DisplayObject} The first child that was removed. + */ + + + Container.prototype.removeChild = function removeChild(child) { + var argumentsLength = arguments.length; + + // if there is only one argument we can bypass looping through the them + if (argumentsLength > 1) { + // loop through the arguments property and add all children + // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes + for (var i = 0; i < argumentsLength; i++) { + this.removeChild(arguments[i]); + } + } else { + var index = this.children.indexOf(child); + + if (index === -1) return null; + + child.parent = null; + // ensure child transform will be recalculated + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + } + + return child; + }; + + /** + * Removes a child from the specified index position. + * + * @param {number} index - The index to get the child from + * @return {PIXI.DisplayObject} The child that was removed. + */ + + + Container.prototype.removeChildAt = function removeChildAt(index) { + var child = this.getChildAt(index); + + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + (0, _utils.removeItems)(this.children, index, 1); + + // ensure bounds will be recalculated + this._boundsID++; + + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + + return child; + }; + + /** + * Removes all children from this container that are within the begin and end indexes. + * + * @param {number} [beginIndex=0] - The beginning position. + * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. + * @returns {DisplayObject[]} List of removed children + */ + + + Container.prototype.removeChildren = function removeChildren() { + var beginIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var endIndex = arguments[1]; + + var begin = beginIndex; + var end = typeof endIndex === 'number' ? endIndex : this.children.length; + var range = end - begin; + var removed = void 0; + + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } + + this._boundsID++; + + this.onChildrenChange(beginIndex); + + for (var _i = 0; _i < removed.length; ++_i) { + removed[_i].emit('removed', this); + } + + return removed; + } else if (range === 0 && this.children.length === 0) { + return []; + } + + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + }; + + /** + * Updates the transform on all children of this container for rendering + */ + + + Container.prototype.updateTransform = function updateTransform() { + this._boundsID++; + + this.transform.updateTransform(this.parent.transform); + + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + + if (child.visible) { + child.updateTransform(); + } + } + }; + + /** + * Recalculates the bounds of the container. + * + */ + + + Container.prototype.calculateBounds = function calculateBounds() { + this._bounds.clear(); + + this._calculateBounds(); + + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + + if (!child.visible || !child.renderable) { + continue; + } + + child.calculateBounds(); + + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + child._mask.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, child._mask._bounds); + } else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } else { + this._bounds.addBounds(child._bounds); + } + } + + this._lastBoundsID = this._boundsID; + }; + + /** + * Recalculates the bounds of the object. Override this to + * calculate the bounds of the specific object (not including children). + * + */ + + + Container.prototype._calculateBounds = function _calculateBounds() {} + // FILL IN// + + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderWebGL = function renderWebGL(renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + // do a quick check to see if this element has a mask or a filter. + if (this._mask || this.filters && this.filters.length) { + this.renderAdvancedWebGL(renderer); + } else { + this._renderWebGL(renderer); + + // simple render children! + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderWebGL(renderer); + } + } + }; + + /** + * Render the object using the WebGL renderer and advanced features. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { + renderer.flush(); + + var filters = this._filters; + var mask = this._mask; + + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + + this._enabledFilters.length = 0; + + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + + if (this._enabledFilters.length) { + renderer.filterManager.pushFilter(this, this._enabledFilters); + } + } + + if (mask) { + renderer.maskManager.pushMask(this, this._mask); + } + + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); + + // now loop through the children and make sure they get rendered + for (var _i2 = 0, j = this.children.length; _i2 < j; _i2++) { + this.children[_i2].renderWebGL(renderer); + } + + renderer.flush(); + + if (mask) { + renderer.maskManager.popMask(this, this._mask); + } + + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filterManager.popFilter(); + } + }; + + /** + * To be overridden by the subclasses. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Container.prototype._renderWebGL = function _renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * To be overridden by the subclass + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype._renderCanvas = function _renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // this is where content itself gets rendered... + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + Container.prototype.renderCanvas = function renderCanvas(renderer) { + // if not visible or the alpha is 0 then no need to render this + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + if (this._mask) { + renderer.maskManager.pushMask(this._mask); + } + + this._renderCanvas(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].renderCanvas(renderer); + } + + if (this._mask) { + renderer.maskManager.popMask(renderer); + } + }; + + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Container.prototype.destroy = function destroy(options) { + _DisplayObject.prototype.destroy.call(this); + + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + + var oldChildren = this.removeChildren(0, this.children.length); + + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + }; + + /** + * The width of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Container, [{ + key: 'width', + get: function get() { + return this.scale.x * this.getLocalBounds().width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var width = this.getLocalBounds().width; + + if (width !== 0) { + this.scale.x = value / width; + } else { + this.scale.x = 1; + } + + this._width = value; + } + + /** + * The height of the Container, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.scale.y * this.getLocalBounds().height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var height = this.getLocalBounds().height; + + if (height !== 0) { + this.scale.y = value / height; + } else { + this.scale.y = 1; + } + + this._height = value; + } + }]); + + return Container; +}(_DisplayObject3.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = Container; +Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + +},{"../utils":125,"./DisplayObject":49}],49:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TransformStatic = require('./TransformStatic'); + +var _TransformStatic2 = _interopRequireDefault(_TransformStatic); + +var _Transform = require('./Transform'); + +var _Transform2 = _interopRequireDefault(_Transform); + +var _Bounds = require('./Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _math = require('../math'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// _tempDisplayObjectParent = new DisplayObject(); + +/** + * The base class for all objects that are rendered on the screen. + * This is an abstract class and should not be used on its own rather it should be extended. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var DisplayObject = function (_EventEmitter) { + _inherits(DisplayObject, _EventEmitter); + + /** + * + */ + function DisplayObject() { + _classCallCheck(this, DisplayObject); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + var TransformClass = _settings2.default.TRANSFORM_MODE === _const.TRANSFORM_MODE.STATIC ? _TransformStatic2.default : _Transform2.default; + + _this.tempDisplayObjectParent = null; + + // TODO: need to create Transform from factory + /** + * World transform and local transform of this object. + * This will become read-only later, please do not assign anything there unless you know what are you doing + * + * @member {PIXI.TransformBase} + */ + _this.transform = new TransformClass(); + + /** + * The opacity of the object. + * + * @member {number} + */ + _this.alpha = 1; + + /** + * The visibility of the object. If false the object will not be drawn, and + * the updateTransform function will not be called. + * + * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually + * + * @member {boolean} + */ + _this.visible = true; + + /** + * Can this object be rendered, if false the object will not be drawn but the updateTransform + * methods will still be called. + * + * Only affects recursive calls from parent. You can ask for bounds manually + * + * @member {boolean} + */ + _this.renderable = true; + + /** + * The display object container that contains this display object. + * + * @member {PIXI.Container} + * @readonly + */ + _this.parent = null; + + /** + * The multiplied alpha of the displayObject + * + * @member {number} + * @readonly + */ + _this.worldAlpha = 1; + + /** + * The area the filter is applied to. This is used as more of an optimisation + * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle + * + * Also works as an interaction mask + * + * @member {PIXI.Rectangle} + */ + _this.filterArea = null; + + _this._filters = null; + _this._enabledFilters = null; + + /** + * The bounds object, this is used to calculate and store the bounds of the displayObject + * + * @member {PIXI.Rectangle} + * @private + */ + _this._bounds = new _Bounds2.default(); + _this._boundsID = 0; + _this._lastBoundsID = -1; + _this._boundsRect = null; + _this._localBoundsRect = null; + + /** + * The original, cached mask of the object + * + * @member {PIXI.Graphics|PIXI.Sprite} + * @private + */ + _this._mask = null; + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + + /** + * Fired when this DisplayObject is added to a Container. + * + * @event PIXI.DisplayObject#added + * @param {PIXI.Container} container - The container added to. + */ + + /** + * Fired when this DisplayObject is removed from a Container. + * + * @event PIXI.DisplayObject#removed + * @param {PIXI.Container} container - The container removed from. + */ + return _this; + } + + /** + * @private + * @member {PIXI.DisplayObject} + */ + + + /** + * Updates the object transform for rendering + * + * TODO - Optimization pass! + */ + DisplayObject.prototype.updateTransform = function updateTransform() { + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + + this._bounds.updateID++; + }; + + /** + * recursively updates transform of all objects from the root to this one + * internal function for toLocal() + */ + + + DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform() { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + }; + + /** + * Retrieves the bounds of the displayObject as a rectangle object. + * + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @param {PIXI.Rectangle} rect - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getBounds = function getBounds(skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + + if (this._boundsID !== this._lastBoundsID) { + this.calculateBounds(); + } + + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new _math.Rectangle(); + } + + rect = this._boundsRect; + } + + return this._bounds.getRectangle(rect); + }; + + /** + * Retrieves the local bounds of the displayObject as a rectangle object + * + * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation + * @return {PIXI.Rectangle} the rectangular bounding area + */ + + + DisplayObject.prototype.getLocalBounds = function getLocalBounds(rect) { + var transformRef = this.transform; + var parentRef = this.parent; + + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + var bounds = this.getBounds(false, rect); + + this.parent = parentRef; + this.transform = transformRef; + + return bounds; + }; + + /** + * Calculates the global position of the display object + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform. + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toGlobal = function toGlobal(position, point) { + var skipUpdate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; + + /** + * Calculates the local position of the display object relative to another point + * + * @param {PIXI.Point} position - The world origin to calculate from + * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional + * (otherwise will create a new Point) + * @param {boolean} [skipUpdate=false] - Should we skip the update transform + * @return {PIXI.Point} A point object representing the position of this object + */ + + + DisplayObject.prototype.toLocal = function toLocal(position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } else { + this.displayObjectUpdateTransform(); + } + } + + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Renders the object using the Canvas renderer + * + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + ; + + DisplayObject.prototype.renderCanvas = function renderCanvas(renderer) // eslint-disable-line no-unused-vars + {} + // OVERWRITE; + + + /** + * Set the parent Container of this DisplayObject + * + * @param {PIXI.Container} container - The Container to add this DisplayObject to + * @return {PIXI.Container} The Container that this DisplayObject was added to + */ + ; + + DisplayObject.prototype.setParent = function setParent(container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); + } + + container.addChild(this); + + return container; + }; + + /** + * Convenience function to set the position, scale, skew and pivot at once. + * + * @param {number} [x=0] - The X position + * @param {number} [y=0] - The Y position + * @param {number} [scaleX=1] - The X scale value + * @param {number} [scaleY=1] - The Y scale value + * @param {number} [rotation=0] - The rotation + * @param {number} [skewX=0] - The X skew value + * @param {number} [skewY=0] - The Y skew value + * @param {number} [pivotX=0] - The X pivot value + * @param {number} [pivotY=0] - The Y pivot value + * @return {PIXI.DisplayObject} The DisplayObject instance + */ + + + DisplayObject.prototype.setTransform = function setTransform() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var scaleX = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var scaleY = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var rotation = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var skewX = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + var skewY = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + var pivotX = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0; + var pivotY = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0; + + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + + return this; + }; + + /** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy`. + * + */ + + + DisplayObject.prototype.destroy = function destroy() { + this.removeAllListeners(); + if (this.parent) { + this.parent.removeChild(this); + } + this.transform = null; + + this.parent = null; + + this._bounds = null; + this._currentBounds = null; + this._mask = null; + + this.filterArea = null; + + this.interactive = false; + this.interactiveChildren = false; + + this._destroyed = true; + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + * + * @member {number} + */ + + + _createClass(DisplayObject, [{ + key: '_tempDisplayObjectParent', + get: function get() { + if (this.tempDisplayObjectParent === null) { + this.tempDisplayObjectParent = new DisplayObject(); + } + + return this.tempDisplayObjectParent; + } + }, { + key: 'x', + get: function get() { + return this.position.x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.x = value; + } + + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + * + * @member {number} + */ + + }, { + key: 'y', + get: function get() { + return this.position.y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.y = value; + } + + /** + * Current transform of the object based on world (parent) factors + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'worldTransform', + get: function get() { + return this.transform.worldTransform; + } + + /** + * Current transform of the object based on local factors: position, scale, other stuff + * + * @member {PIXI.Matrix} + * @readonly + */ + + }, { + key: 'localTransform', + get: function get() { + return this.transform.localTransform; + } + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'position', + get: function get() { + return this.transform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.position.copy(value); + } + + /** + * The scale factor of the object. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'scale', + get: function get() { + return this.transform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.scale.copy(value); + } + + /** + * The pivot point of the displayObject that it rotates around. + * Assignment by value since pixi-v4. + * + * @member {PIXI.Point|PIXI.ObservablePoint} + */ + + }, { + key: 'pivot', + get: function get() { + return this.transform.pivot; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.pivot.copy(value); + } + + /** + * The skew factor for the object in radians. + * Assignment by value since pixi-v4. + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'skew', + get: function get() { + return this.transform.skew; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.skew.copy(value); + } + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + }, { + key: 'rotation', + get: function get() { + return this.transform.rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.transform.rotation = value; + } + + /** + * Indicates if the object is globally visible. + * + * @member {boolean} + * @readonly + */ + + }, { + key: 'worldVisible', + get: function get() { + var item = this; + + do { + if (!item.visible) { + return false; + } + + item = item.parent; + } while (item); + + return true; + } + + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PIXI a regular mask must be a + * PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it + * utilises shape clipping. To remove a mask, set this property to null. + * + * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + * + * @member {PIXI.Graphics|PIXI.Sprite} + */ + + }, { + key: 'mask', + get: function get() { + return this._mask; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._mask) { + this._mask.renderable = true; + this._mask.isMask = false; + } + + this._mask = value; + + if (this._mask) { + this._mask.renderable = false; + this._mask.isMask = true; + } + } + + /** + * Sets the filters for the displayObject. + * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * To remove filters simply set this property to 'null' + * + * @member {PIXI.Filter[]} + */ + + }, { + key: 'filters', + get: function get() { + return this._filters && this._filters.slice(); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._filters = value && value.slice(); + } + }]); + + return DisplayObject; +}(_eventemitter2.default); + +// performance increase to avoid using call.. (10x faster) + + +exports.default = DisplayObject; +DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + +},{"../const":46,"../math":70,"../settings":101,"./Bounds":47,"./Transform":50,"./TransformStatic":52,"eventemitter3":3}],50:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Generic class to deal with traditional 2D matrix transforms + * local transformation is calculated from position,scale,skew and rotation + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var Transform = function (_TransformBase) { + _inherits(Transform, _TransformBase); + + /** + * + */ + function Transform() { + _classCallCheck(this, Transform); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.Point} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.Point(0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.Point} + */ + _this.scale = new _math.Point(1, 1); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + /** + * The pivot point of the displayObject that it rotates around. + * + * @member {PIXI.Point} + */ + _this.pivot = new _math.Point(0, 0); + + /** + * The rotation value of the object, in radians + * + * @member {Number} + * @private + */ + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + return _this; + } + + /** + * Updates the skew values when the skew or rotation changes. + * + * @private + */ + + + Transform.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + }; + + /** + * Updates only local matrix + */ + + + Transform.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + Transform.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + + lt.tx = this.position.x - (this.pivot.x * lt.a + this.pivot.y * lt.c); + lt.ty = this.position.y - (this.pivot.x * lt.b + this.pivot.y * lt.d); + + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + Transform.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(Transform, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rotation = value; + this.updateSkew(); + } + }]); + + return Transform; +}(_TransformBase3.default); + +exports.default = Transform; + +},{"../math":70,"./TransformBase":51}],51:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../math'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Generic class to deal with traditional 2D matrix transforms + * + * @class + * @memberof PIXI + */ +var TransformBase = function () { + /** + * + */ + function TransformBase() { + _classCallCheck(this, TransformBase); + + /** + * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds() + * + * @member {PIXI.Matrix} + */ + this.worldTransform = new _math.Matrix(); + + /** + * The local matrix transform + * + * @member {PIXI.Matrix} + */ + this.localTransform = new _math.Matrix(); + + this._worldID = 0; + this._parentID = 0; + } + + /** + * TransformBase does not have decomposition, so this function wont do anything + */ + + + TransformBase.prototype.updateLocalTransform = function updateLocalTransform() {} + // empty + + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.TransformBase} parentTransform - The transform of the parent of this object + */ + ; + + TransformBase.prototype.updateTransform = function updateTransform(parentTransform) { + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + var lt = this.localTransform; + + // concat the parent matrix with the objects transform. + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._worldID++; + }; + + return TransformBase; +}(); + +/** + * Updates the values of the object and applies the parent's transform. + * @param parentTransform {PIXI.Transform} The transform of the parent of this object + * + */ + + +exports.default = TransformBase; +TransformBase.prototype.updateWorldTransform = TransformBase.prototype.updateTransform; + +TransformBase.IDENTITY = new TransformBase(); + +},{"../math":70}],52:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _TransformBase2 = require('./TransformBase'); + +var _TransformBase3 = _interopRequireDefault(_TransformBase2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Transform that takes care about its versions + * + * @class + * @extends PIXI.TransformBase + * @memberof PIXI + */ +var TransformStatic = function (_TransformBase) { + _inherits(TransformStatic, _TransformBase); + + /** + * + */ + function TransformStatic() { + _classCallCheck(this, TransformStatic); + + /** + * The coordinate of the object relative to the local coordinates of the parent. + * + * @member {PIXI.ObservablePoint} + */ + var _this = _possibleConstructorReturn(this, _TransformBase.call(this)); + + _this.position = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The scale factor of the object. + * + * @member {PIXI.ObservablePoint} + */ + _this.scale = new _math.ObservablePoint(_this.onChange, _this, 1, 1); + + /** + * The pivot point of the displayObject that it rotates around. + * + * @member {PIXI.ObservablePoint} + */ + _this.pivot = new _math.ObservablePoint(_this.onChange, _this, 0, 0); + + /** + * The skew amount, on the x and y axis. + * + * @member {PIXI.ObservablePoint} + */ + _this.skew = new _math.ObservablePoint(_this.updateSkew, _this, 0, 0); + + _this._rotation = 0; + + _this._cx = 1; // cos rotation + skewY; + _this._sx = 0; // sin rotation + skewY; + _this._cy = 0; // cos rotation + Math.PI/2 - skewX; + _this._sy = 1; // sin rotation + Math.PI/2 - skewX; + + _this._localID = 0; + _this._currentLocalID = 0; + return _this; + } + + /** + * Called when a value changes. + * + * @private + */ + + + TransformStatic.prototype.onChange = function onChange() { + this._localID++; + }; + + /** + * Called when skew or rotation changes + * + * @private + */ + + + TransformStatic.prototype.updateSkew = function updateSkew() { + this._cx = Math.cos(this._rotation + this.skew._y); + this._sx = Math.sin(this._rotation + this.skew._y); + this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2 + + this._localID++; + }; + + /** + * Updates only local matrix + */ + + + TransformStatic.prototype.updateLocalTransform = function updateLocalTransform() { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + }; + + /** + * Updates the values of the object and applies the parent's transform. + * + * @param {PIXI.Transform} parentTransform - The transform of the parent of this object + */ + + + TransformStatic.prototype.updateTransform = function updateTransform(parentTransform) { + var lt = this.localTransform; + + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale._x; + lt.b = this._sx * this.scale._x; + lt.c = this._cy * this.scale._y; + lt.d = this._sy * this.scale._y; + + lt.tx = this.position._x - (this.pivot._x * lt.a + this.pivot._y * lt.c); + lt.ty = this.position._y - (this.pivot._x * lt.b + this.pivot._y * lt.d); + this._currentLocalID = this._localID; + + // force an update.. + this._parentID = -1; + } + + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + + wt.a = lt.a * pt.a + lt.b * pt.c; + wt.b = lt.a * pt.b + lt.b * pt.d; + wt.c = lt.c * pt.a + lt.d * pt.c; + wt.d = lt.c * pt.b + lt.d * pt.d; + wt.tx = lt.tx * pt.a + lt.ty * pt.c + pt.tx; + wt.ty = lt.tx * pt.b + lt.ty * pt.d + pt.ty; + + this._parentID = parentTransform._worldID; + + // update the id of the transform.. + this._worldID++; + } + }; + + /** + * Decomposes a matrix and sets the transforms properties based on it. + * + * @param {PIXI.Matrix} matrix - The matrix to decompose + */ + + + TransformStatic.prototype.setFromMatrix = function setFromMatrix(matrix) { + matrix.decompose(this); + this._localID++; + }; + + /** + * The rotation of the object in radians. + * + * @member {number} + */ + + + _createClass(TransformStatic, [{ + key: 'rotation', + get: function get() { + return this._rotation; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._rotation !== value) { + this._rotation = value; + this.updateSkew(); + } + } + }]); + + return TransformStatic; +}(_TransformBase3.default); + +exports.default = TransformStatic; + +},{"../math":70,"./TransformBase":51}],53:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _GraphicsData = require('./GraphicsData'); + +var _GraphicsData2 = _interopRequireDefault(_GraphicsData); + +var _Sprite = require('../sprites/Sprite'); + +var _Sprite2 = _interopRequireDefault(_Sprite); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Bounds = require('../display/Bounds'); + +var _Bounds2 = _interopRequireDefault(_Bounds); + +var _bezierCurveTo2 = require('./utils/bezierCurveTo'); + +var _bezierCurveTo3 = _interopRequireDefault(_bezierCurveTo2); + +var _CanvasRenderer = require('../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var canvasRenderer = void 0; +var tempMatrix = new _math.Matrix(); +var tempPoint = new _math.Point(); +var tempColor1 = new Float32Array(4); +var tempColor2 = new Float32Array(4); + +/** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Graphics = function (_Container) { + _inherits(Graphics, _Container); + + /** + * + * @param {boolean} [nativeLines=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + */ + function Graphics() { + var nativeLines = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + _classCallCheck(this, Graphics); + + /** + * The alpha value used when filling the Graphics object. + * + * @member {number} + * @default 1 + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this.fillAlpha = 1; + + /** + * The width (thickness) of any lines drawn. + * + * @member {number} + * @default 0 + */ + _this.lineWidth = 0; + + /** + * If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * + * @member {boolean} + */ + _this.nativeLines = nativeLines; + + /** + * The color of any lines drawn. + * + * @member {string} + * @default 0 + */ + _this.lineColor = 0; + + /** + * The alignment of any lines drawn (0.5 = middle, 1 = outter, 0 = inner). + * + * @member {number} + * @default 0.5 + */ + _this.lineAlignment = 0.5; + + /** + * Graphics data + * + * @member {PIXI.GraphicsData[]} + * @private + */ + _this.graphicsData = []; + + /** + * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to + * reset the tint. + * + * @member {number} + * @default 0xFFFFFF + */ + _this.tint = 0xFFFFFF; + + /** + * The previous tint applied to the graphic shape. Used to compare to the current tint and + * check if theres change. + * + * @member {number} + * @private + * @default 0xFFFFFF + */ + _this._prevTint = 0xFFFFFF; + + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL; + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * Current path + * + * @member {PIXI.GraphicsData} + * @private + */ + _this.currentPath = null; + + /** + * Array containing some WebGL-related properties used by the WebGL renderer. + * + * @member {object} + * @private + */ + // TODO - _webgl should use a prototype object, not a random undocumented object... + _this._webGL = {}; + + /** + * Whether this shape is being used as a mask. + * + * @member {boolean} + */ + _this.isMask = false; + + /** + * The bounds' padding used for bounds calculation. + * + * @member {number} + */ + _this.boundsPadding = 0; + + /** + * A cache of the local bounds to prevent recalculation. + * + * @member {PIXI.Rectangle} + * @private + */ + _this._localBounds = new _Bounds2.default(); + + /** + * Used to detect if the graphics object has changed. If this is set to true then the graphics + * object will be recalculated. + * + * @member {boolean} + * @private + */ + _this.dirty = 0; + + /** + * Used to detect if we need to do a fast rect check using the id compare method + * @type {Number} + */ + _this.fastRectDirty = -1; + + /** + * Used to detect if we clear the graphics webGL data + * @type {Number} + */ + _this.clearDirty = 0; + + /** + * Used to detect if we we need to recalculate local bounds + * @type {Number} + */ + _this.boundsDirty = -1; + + /** + * Used to detect if the cached sprite object needs to be updated. + * + * @member {boolean} + * @private + */ + _this.cachedSpriteDirty = false; + + _this._spriteRect = null; + _this._fastRect = false; + + _this._prevRectTint = null; + _this._prevRectFillColor = null; + + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ + return _this; + } + + /** + * Creates a new Graphics object with the same values as this one. + * Note that the only the properties of the object are cloned, not its transform (position,scale,etc) + * + * @return {PIXI.Graphics} A clone of the graphics object + */ + + + Graphics.prototype.clone = function clone() { + var clone = new Graphics(); + + clone.renderable = this.renderable; + clone.fillAlpha = this.fillAlpha; + clone.lineWidth = this.lineWidth; + clone.lineColor = this.lineColor; + clone.lineAlignment = this.lineAlignment; + clone.tint = this.tint; + clone.blendMode = this.blendMode; + clone.isMask = this.isMask; + clone.boundsPadding = this.boundsPadding; + clone.dirty = 0; + clone.cachedSpriteDirty = this.cachedSpriteDirty; + + // copy graphics data + for (var i = 0; i < this.graphicsData.length; ++i) { + clone.graphicsData.push(this.graphicsData[i].clone()); + } + + clone.currentPath = clone.graphicsData[clone.graphicsData.length - 1]; + + clone.updateLocalBounds(); + + return clone; + }; + + /** + * Calculate length of quadratic curve + * @see {@link http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/} + * for the detailed explanation of math behind this. + * + * @private + * @param {number} fromX - x-coordinate of curve start point + * @param {number} fromY - y-coordinate of curve start point + * @param {number} cpX - x-coordinate of curve control point + * @param {number} cpY - y-coordinate of curve control point + * @param {number} toX - x-coordinate of curve end point + * @param {number} toY - y-coordinate of curve end point + * @return {number} Length of quadratic curve + */ + + + Graphics.prototype._quadraticCurveLength = function _quadraticCurveLength(fromX, fromY, cpX, cpY, toX, toY) { + var ax = fromX - 2.0 * cpX + toX; + var ay = fromY - 2.0 * cpY + toY; + var bx = 2.0 * cpX - 2.0 * fromX; + var by = 2.0 * cpY - 2.0 * fromY; + var a = 4.0 * (ax * ax + ay * ay); + var b = 4.0 * (ax * bx + ay * by); + var c = bx * bx + by * by; + + var s = 2.0 * Math.sqrt(a + b + c); + var a2 = Math.sqrt(a); + var a32 = 2.0 * a * a2; + var c2 = 2.0 * Math.sqrt(c); + var ba = b / a2; + + return (a32 * s + a2 * b * (s - c2) + (4.0 * c * a - b * b) * Math.log((2.0 * a2 + ba + s) / (ba + c2))) / (4.0 * a32); + }; + + /** + * Calculate length of bezier curve. + * Analytical solution is impossible, since it involves an integral that does not integrate in general. + * Therefore numerical solution is used. + * + * @private + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {number} Length of bezier curve + */ + + + Graphics.prototype._bezierCurveLength = function _bezierCurveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var n = 10; + var result = 0.0; + var t = 0.0; + var t2 = 0.0; + var t3 = 0.0; + var nt = 0.0; + var nt2 = 0.0; + var nt3 = 0.0; + var x = 0.0; + var y = 0.0; + var dx = 0.0; + var dy = 0.0; + var prevX = fromX; + var prevY = fromY; + + for (var i = 1; i <= n; ++i) { + t = i / n; + t2 = t * t; + t3 = t2 * t; + nt = 1.0 - t; + nt2 = nt * nt; + nt3 = nt2 * nt; + + x = nt3 * fromX + 3.0 * nt2 * t * cpX + 3.0 * nt * t2 * cpX2 + t3 * toX; + y = nt3 * fromY + 3.0 * nt2 * t * cpY + 3 * nt * t2 * cpY2 + t3 * toY; + dx = prevX - x; + dy = prevY - y; + prevX = x; + prevY = y; + + result += Math.sqrt(dx * dx + dy * dy); + } + + return result; + }; + + /** + * Calculate number of segments for the curve based on its length to ensure its smoothness. + * + * @private + * @param {number} length - length of curve + * @return {number} Number of segments + */ + + + Graphics.prototype._segmentsCount = function _segmentsCount(length) { + var result = Math.ceil(length / Graphics.CURVES.maxLength); + + if (result < Graphics.CURVES.minSegments) { + result = Graphics.CURVES.minSegments; + } else if (result > Graphics.CURVES.maxSegments) { + result = Graphics.CURVES.maxSegments; + } + + return result; + }; + + /** + * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() + * method or the drawCircle() method. + * + * @param {number} [lineWidth=0] - width of the line to draw, will update the objects stored style + * @param {number} [color=0] - color of the line to draw, will update the objects stored style + * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style + * @param {number} [alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineStyle = function lineStyle() { + var lineWidth = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var alpha = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + var alignment = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0.5; + + this.lineWidth = lineWidth; + this.lineColor = color; + this.lineAlpha = alpha; + this.lineAlignment = alignment; + + if (this.currentPath) { + if (this.currentPath.shape.points.length) { + // halfway through a line? start a new one! + var shape = new _math.Polygon(this.currentPath.shape.points.slice(-2)); + + shape.closed = false; + + this.drawShape(shape); + } else { + // otherwise its empty so lets just set the line properties + this.currentPath.lineWidth = this.lineWidth; + this.currentPath.lineColor = this.lineColor; + this.currentPath.lineAlpha = this.lineAlpha; + this.currentPath.lineAlignment = this.lineAlignment; + } + } + + return this; + }; + + /** + * Moves the current drawing position to x, y. + * + * @param {number} x - the X coordinate to move to + * @param {number} y - the Y coordinate to move to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.moveTo = function moveTo(x, y) { + var shape = new _math.Polygon([x, y]); + + shape.closed = false; + this.drawShape(shape); + + return this; + }; + + /** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * + * @param {number} x - the X coordinate to draw to + * @param {number} y - the Y coordinate to draw to + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.lineTo = function lineTo(x, y) { + var points = this.currentPath.shape.points; + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + if (fromX !== x || fromY !== y) { + points.push(x, y); + this.dirty++; + } + + return this; + }; + + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.quadraticCurveTo = function quadraticCurveTo(cpX, cpY, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + var xa = 0; + var ya = 0; + + if (points.length === 0) { + this.moveTo(0, 0); + } + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var n = Graphics.CURVES.adaptive ? this._segmentsCount(this._quadraticCurveLength(fromX, fromY, cpX, cpY, toX, toY)) : 20; + + for (var i = 1; i <= n; ++i) { + var j = i / n; + + xa = fromX + (cpX - fromX) * j; + ya = fromY + (cpY - fromY) * j; + + points.push(xa + (cpX + (toX - cpX) * j - xa) * j, ya + (cpY + (toY - cpY) * j - ya) * j); + } + + this.dirty++; + + return this; + }; + + /** + * Calculate the points for a bezier curve and then draws it. + * + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.bezierCurveTo = function bezierCurveTo(cpX, cpY, cpX2, cpY2, toX, toY) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points = [0, 0]; + } + } else { + this.moveTo(0, 0); + } + + var points = this.currentPath.shape.points; + + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + + points.length -= 2; + + var n = Graphics.CURVES.adaptive ? this._segmentsCount(this._bezierCurveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY)) : 20; + + (0, _bezierCurveTo3.default)(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, n, points); + + this.dirty++; + + return this; + }; + + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * + * @param {number} x1 - The x-coordinate of the beginning of the arc + * @param {number} y1 - The y-coordinate of the beginning of the arc + * @param {number} x2 - The x-coordinate of the end of the arc + * @param {number} y2 - The y-coordinate of the end of the arc + * @param {number} radius - The radius of the arc + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arcTo = function arcTo(x1, y1, x2, y2, radius) { + if (this.currentPath) { + if (this.currentPath.shape.points.length === 0) { + this.currentPath.shape.points.push(x1, y1); + } + } else { + this.moveTo(x1, y1); + } + + var points = this.currentPath.shape.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs(a1 * b2 - b1 * a2); + + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + } else { + var dd = a1 * a1 + b1 * b1; + var cc = a2 * a2 + b2 * b2; + var tt = a1 * a2 + b1 * b2; + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = k1 * b2 + k2 * b1; + var cy = k1 * a2 + k2 * a1; + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + + this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1); + } + + this.dirty++; + + return this; + }; + + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * + * @param {number} cx - The x-coordinate of the center of the circle + * @param {number} cy - The y-coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param {number} endAngle - The ending angle, in radians + * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.arc = function arc(cx, cy, radius, startAngle, endAngle) { + var anticlockwise = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; + + if (startAngle === endAngle) { + return this; + } + + if (!anticlockwise && endAngle <= startAngle) { + endAngle += _const.PI_2; + } else if (anticlockwise && startAngle <= endAngle) { + startAngle += _const.PI_2; + } + + var sweep = endAngle - startAngle; + var segs = Graphics.CURVES.adaptive ? this._segmentsCount(Math.abs(sweep) * radius) : Math.ceil(Math.abs(sweep) / _const.PI_2) * 40; + + if (sweep === 0) { + return this; + } + + var startX = cx + Math.cos(startAngle) * radius; + var startY = cy + Math.sin(startAngle) * radius; + + // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. + var points = this.currentPath ? this.currentPath.shape.points : null; + + if (points) { + // We check how far our start is from the last existing point + var xDiff = Math.abs(points[points.length - 2] - startX); + var yDiff = Math.abs(points[points.length - 1] - startY); + + if (xDiff < 0.001 && yDiff < 0.001) { + // If the point is very close, we don't add it, since this would lead to artifacts + // during tesselation due to floating point imprecision. + } else { + points.push(startX, startY); + } + } else { + this.moveTo(startX, startY); + points = this.currentPath.shape.points; + } + + var theta = sweep / (segs * 2); + var theta2 = theta * 2; + + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + + var segMinus = segs - 1; + + var remainder = segMinus % 1 / segMinus; + + for (var i = 0; i <= segMinus; ++i) { + var real = i + remainder * i; + + var angle = theta + startAngle + theta2 * real; + + var c = Math.cos(angle); + var s = -Math.sin(angle); + + points.push((cTheta * c + sTheta * s) * radius + cx, (cTheta * -s + sTheta * c) * radius + cy); + } + + this.dirty++; + + return this; + }; + + /** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * + * @param {number} [color=0] - the color of the fill + * @param {number} [alpha=1] - the alpha of the fill + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.beginFill = function beginFill() { + var color = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var alpha = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.filling = true; + this.fillColor = color; + this.fillAlpha = alpha; + + if (this.currentPath) { + if (this.currentPath.shape.points.length <= 2) { + this.currentPath.fill = this.filling; + this.currentPath.fillColor = this.fillColor; + this.currentPath.fillAlpha = this.fillAlpha; + } + } + + return this; + }; + + /** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.endFill = function endFill() { + this.filling = false; + this.fillColor = null; + this.fillAlpha = 1; + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRect = function drawRect(x, y, width, height) { + this.drawShape(new _math.Rectangle(x, y, width, height)); + + return this; + }; + + /** + * + * @param {number} x - The X coord of the top-left of the rectangle + * @param {number} y - The Y coord of the top-left of the rectangle + * @param {number} width - The width of the rectangle + * @param {number} height - The height of the rectangle + * @param {number} radius - Radius of the rectangle corners + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawRoundedRect = function drawRoundedRect(x, y, width, height, radius) { + this.drawShape(new _math.RoundedRectangle(x, y, width, height, radius)); + + return this; + }; + + /** + * Draws a circle. + * + * @param {number} x - The X coordinate of the center of the circle + * @param {number} y - The Y coordinate of the center of the circle + * @param {number} radius - The radius of the circle + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawCircle = function drawCircle(x, y, radius) { + this.drawShape(new _math.Circle(x, y, radius)); + + return this; + }; + + /** + * Draws an ellipse. + * + * @param {number} x - The X coordinate of the center of the ellipse + * @param {number} y - The Y coordinate of the center of the ellipse + * @param {number} width - The half width of the ellipse + * @param {number} height - The half height of the ellipse + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawEllipse = function drawEllipse(x, y, width, height) { + this.drawShape(new _math.Ellipse(x, y, width, height)); + + return this; + }; + + /** + * Draws a polygon using the given path. + * + * @param {number[]|PIXI.Point[]|PIXI.Polygon} path - The path data used to construct the polygon. + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawPolygon = function drawPolygon(path) { + // prevents an argument assignment deopt + // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var points = path; + + var closed = true; + + if (points instanceof _math.Polygon) { + closed = points.closed; + points = points.points; + } + + if (!Array.isArray(points)) { + // prevents an argument leak deopt + // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + points = new Array(arguments.length); + + for (var i = 0; i < points.length; ++i) { + points[i] = arguments[i]; // eslint-disable-line prefer-rest-params + } + } + + var shape = new _math.Polygon(points); + + shape.closed = closed; + + this.drawShape(shape); + + return this; + }; + + /** + * Draw a star shape with an abitrary number of points. + * + * @param {number} x - Center X position of the star + * @param {number} y - Center Y position of the star + * @param {number} points - The number of points of the star, must be > 1 + * @param {number} radius - The outer radius of the star + * @param {number} [innerRadius] - The inner radius between points, default half `radius` + * @param {number} [rotation=0] - The rotation of the star in radians, where 0 is vertical + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.drawStar = function drawStar(x, y, points, radius, innerRadius) { + var rotation = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + + innerRadius = innerRadius || radius / 2; + + var startAngle = -1 * Math.PI / 2 + rotation; + var len = points * 2; + var delta = _const.PI_2 / len; + var polygon = []; + + for (var i = 0; i < len; i++) { + var r = i % 2 ? innerRadius : radius; + var angle = i * delta + startAngle; + + polygon.push(x + r * Math.cos(angle), y + r * Math.sin(angle)); + } + + return this.drawPolygon(polygon); + }; + + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * + * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + + + Graphics.prototype.clear = function clear() { + if (this.lineWidth || this.filling || this.graphicsData.length > 0) { + this.lineWidth = 0; + this.lineAlignment = 0.5; + + this.filling = false; + + this.boundsDirty = -1; + this.canvasTintDirty = -1; + this.dirty++; + this.clearDirty++; + this.graphicsData.length = 0; + } + + this.currentPath = null; + this._spriteRect = null; + + return this; + }; + + /** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. + * + * @returns {boolean} True if only 1 rect. + */ + + + Graphics.prototype.isFastRect = function isFastRect() { + return this.graphicsData.length === 1 && this.graphicsData[0].shape.type === _const.SHAPES.RECT && !this.graphicsData[0].lineWidth; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderWebGL = function _renderWebGL(renderer) { + // if the sprite is not visible or the alpha is 0 then no need to render this element + if (this.dirty !== this.fastRectDirty) { + this.fastRectDirty = this.dirty; + this._fastRect = this.isFastRect(); + } + + // TODO this check can be moved to dirty? + if (this._fastRect) { + this._renderSpriteRect(renderer); + } else { + renderer.setObjectRenderer(renderer.plugins.graphics); + renderer.plugins.graphics.render(this); + } + }; + + /** + * Renders a sprite rectangle. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderSpriteRect = function _renderSpriteRect(renderer) { + var rect = this.graphicsData[0].shape; + + if (!this._spriteRect) { + this._spriteRect = new _Sprite2.default(new _Texture2.default(_Texture2.default.WHITE)); + } + + var sprite = this._spriteRect; + var fillColor = this.graphicsData[0].fillColor; + + if (this.tint === 0xffffff) { + sprite.tint = fillColor; + } else if (this.tint !== this._prevRectTint || fillColor !== this._prevRectFillColor) { + var t1 = tempColor1; + var t2 = tempColor2; + + (0, _utils.hex2rgb)(fillColor, t1); + (0, _utils.hex2rgb)(this.tint, t2); + + t1[0] *= t2[0]; + t1[1] *= t2[1]; + t1[2] *= t2[2]; + + sprite.tint = (0, _utils.rgb2hex)(t1); + + this._prevRectTint = this.tint; + this._prevRectFillColor = fillColor; + } + + sprite.alpha = this.graphicsData[0].fillAlpha; + sprite.worldAlpha = this.worldAlpha * sprite.alpha; + sprite.blendMode = this.blendMode; + + sprite._texture._frame.width = rect.width; + sprite._texture._frame.height = rect.height; + + sprite.transform.worldTransform = this.transform.worldTransform; + + sprite.anchor.set(-rect.x / rect.width, -rect.y / rect.height); + sprite._onAnchorUpdate(); + + sprite._renderWebGL(renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Graphics.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.isMask === true) { + return; + } + + renderer.plugins.graphics.render(this); + }; + + /** + * Retrieves the bounds of the graphic shape as a rectangle object + * + * @private + */ + + + Graphics.prototype._calculateBounds = function _calculateBounds() { + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.updateLocalBounds(); + + this.cachedSpriteDirty = true; + } + + var lb = this._localBounds; + + this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY); + }; + + /** + * Tests if a point is inside this graphics object + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Graphics.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var graphicsData = this.graphicsData; + + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + + if (!data.fill) { + continue; + } + + // only deal with fills.. + if (data.shape) { + if (data.shape.contains(tempPoint.x, tempPoint.y)) { + var hitHole = false; + + if (data.holes) { + for (var _i = 0; _i < data.holes.length; _i++) { + var hole = data.holes[_i]; + + if (hole.contains(tempPoint.x, tempPoint.y)) { + hitHole = true; + break; + } + } + } + + if (!hitHole) { + return true; + } + } + } + } + + return false; + }; + + /** + * Update the bounds of the object + * + */ + + + Graphics.prototype.updateLocalBounds = function updateLocalBounds() { + var minX = Infinity; + var maxX = -Infinity; + + var minY = Infinity; + var maxY = -Infinity; + + if (this.graphicsData.length) { + var shape = 0; + var x = 0; + var y = 0; + var w = 0; + var h = 0; + + for (var i = 0; i < this.graphicsData.length; i++) { + var data = this.graphicsData[i]; + var type = data.type; + var lineWidth = data.lineWidth; + var lineAlignment = data.lineAlignment; + + var lineOffset = lineWidth * lineAlignment; + + shape = data.shape; + + if (type === _const.SHAPES.RECT || type === _const.SHAPES.RREC) { + x = shape.x - lineOffset; + y = shape.y - lineOffset; + w = shape.width + lineOffset * 2; + h = shape.height + lineOffset * 2; + + minX = x < minX ? x : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y < minY ? y : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.CIRC) { + x = shape.x; + y = shape.y; + w = shape.radius + lineOffset; + h = shape.radius + lineOffset; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else if (type === _const.SHAPES.ELIP) { + x = shape.x; + y = shape.y; + w = shape.width + lineOffset; + h = shape.height + lineOffset; + + minX = x - w < minX ? x - w : minX; + maxX = x + w > maxX ? x + w : maxX; + + minY = y - h < minY ? y - h : minY; + maxY = y + h > maxY ? y + h : maxY; + } else { + // POLY + var points = shape.points; + var x2 = 0; + var y2 = 0; + var dx = 0; + var dy = 0; + var rw = 0; + var rh = 0; + var cx = 0; + var cy = 0; + + for (var j = 0; j + 2 < points.length; j += 2) { + x = points[j]; + y = points[j + 1]; + x2 = points[j + 2]; + y2 = points[j + 3]; + dx = Math.abs(x2 - x); + dy = Math.abs(y2 - y); + h = lineOffset * 2; + w = Math.sqrt(dx * dx + dy * dy); + + if (w < 1e-9) { + continue; + } + + rw = (h / w * dy + dx) / 2; + rh = (h / w * dx + dy) / 2; + cx = (x2 + x) / 2; + cy = (y2 + y) / 2; + + minX = cx - rw < minX ? cx - rw : minX; + maxX = cx + rw > maxX ? cx + rw : maxX; + + minY = cy - rh < minY ? cy - rh : minY; + maxY = cy + rh > maxY ? cy + rh : maxY; + } + } + } + } else { + minX = 0; + maxX = 0; + minY = 0; + maxY = 0; + } + + var padding = this.boundsPadding; + + this._localBounds.minX = minX - padding; + this._localBounds.maxX = maxX + padding; + + this._localBounds.minY = minY - padding; + this._localBounds.maxY = maxY + padding; + }; + + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @return {PIXI.GraphicsData} The generated GraphicsData object. + */ + + + Graphics.prototype.drawShape = function drawShape(shape) { + if (this.currentPath) { + // check current path! + if (this.currentPath.shape.points.length <= 2) { + this.graphicsData.pop(); + } + } + + this.currentPath = null; + + var data = new _GraphicsData2.default(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, this.nativeLines, shape, this.lineAlignment); + + this.graphicsData.push(data); + + if (data.type === _const.SHAPES.POLY) { + data.shape.closed = data.shape.closed; + this.currentPath = data; + } + + this.dirty++; + + return data; + }; + + /** + * Generates a canvas texture. + * + * @param {number} scaleMode - The scale mode of the texture. + * @param {number} resolution - The resolution of the texture. + * @return {PIXI.Texture} The new texture. + */ + + + Graphics.prototype.generateCanvasTexture = function generateCanvasTexture(scaleMode) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + var bounds = this.getLocalBounds(); + + var canvasBuffer = _RenderTexture2.default.create(bounds.width, bounds.height, scaleMode, resolution); + + if (!canvasRenderer) { + canvasRenderer = new _CanvasRenderer2.default(); + } + + this.transform.updateLocalTransform(); + this.transform.localTransform.copy(tempMatrix); + + tempMatrix.invert(); + + tempMatrix.tx -= bounds.x; + tempMatrix.ty -= bounds.y; + + canvasRenderer.render(this, canvasBuffer, true, tempMatrix); + + var texture = _Texture2.default.fromCanvas(canvasBuffer.baseTexture._canvasRenderTarget.canvas, scaleMode, 'graphics'); + + texture.baseTexture.resolution = resolution; + texture.baseTexture.update(); + + return texture; + }; + + /** + * Closes the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.closePath = function closePath() { + // ok so close path assumes next one is a hole! + var currentPath = this.currentPath; + + if (currentPath && currentPath.shape) { + currentPath.shape.close(); + } + + return this; + }; + + /** + * Adds a hole in the current path. + * + * @return {PIXI.Graphics} Returns itself. + */ + + + Graphics.prototype.addHole = function addHole() { + // this is a hole! + var hole = this.graphicsData.pop(); + + this.currentPath = this.graphicsData[this.graphicsData.length - 1]; + + this.currentPath.addHole(hole.shape); + this.currentPath = null; + + return this; + }; + + /** + * Destroys the Graphics object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + Graphics.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._webGL) { + for (var j = 0; j < this._webGL[id].data.length; ++j) { + this._webGL[id].data[j].destroy(); + } + } + + if (this._spriteRect) { + this._spriteRect.destroy(); + } + + this.graphicsData = null; + + this.currentPath = null; + this._webGL = null; + this._localBounds = null; + }; + + return Graphics; +}(_Container3.default); + +exports.default = Graphics; + + +Graphics._SPRITE_TEXTURE = null; + +/** + * Graphics curves resolution settings. If `adaptive` flag is set to `true`, + * the resolution is calculated based on the curve's length to ensure better visual quality. + * Adaptive draw works with `bezierCurveTo` and `quadraticCurveTo`. + * + * @static + * @constant + * @memberof PIXI.Graphics + * @name CURVES + * @type {object} + * @property {boolean} adaptive=false - flag indicating if the resolution should be adaptive + * @property {number} maxLength=10 - maximal length of a single segment of the curve (if adaptive = false, ignored) + * @property {number} minSegments=8 - minimal number of segments in the curve (if adaptive = false, ignored) + * @property {number} maxSegments=2048 - maximal number of segments in the curve (if adaptive = false, ignored) + */ +Graphics.CURVES = { + adaptive: false, + maxLength: 10, + minSegments: 8, + maxSegments: 2048 +}; + +},{"../const":46,"../display/Bounds":47,"../display/Container":48,"../math":70,"../renderers/canvas/CanvasRenderer":77,"../sprites/Sprite":102,"../textures/RenderTexture":113,"../textures/Texture":115,"../utils":125,"./GraphicsData":54,"./utils/bezierCurveTo":56}],54:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A GraphicsData object. + * + * @class + * @memberof PIXI + */ +var GraphicsData = function () { + /** + * + * @param {number} lineWidth - the width of the line to draw + * @param {number} lineColor - the color of the line to draw + * @param {number} lineAlpha - the alpha of the line to draw + * @param {number} fillColor - the color of the fill + * @param {number} fillAlpha - the alpha of the fill + * @param {boolean} fill - whether or not the shape is filled with a colour + * @param {boolean} nativeLines - the method for drawing lines + * @param {PIXI.Circle|PIXI.Rectangle|PIXI.Ellipse|PIXI.Polygon} shape - The shape object to draw. + * @param {number} lineAlignment - the alignment of the line. + */ + function GraphicsData(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, nativeLines, shape, lineAlignment) { + _classCallCheck(this, GraphicsData); + + /** + * the width of the line to draw + * @member {number} + */ + this.lineWidth = lineWidth; + + /** + * The alignment of any lines drawn (0.5 = middle, 1 = outter, 0 = inner). + * + * @member {number} + * @default 0 + */ + this.lineAlignment = lineAlignment; + + /** + * if true the liens will be draw using LINES instead of TRIANGLE_STRIP + * @member {boolean} + */ + this.nativeLines = nativeLines; + + /** + * the color of the line to draw + * @member {number} + */ + this.lineColor = lineColor; + + /** + * the alpha of the line to draw + * @member {number} + */ + this.lineAlpha = lineAlpha; + + /** + * cached tint of the line to draw + * @member {number} + * @private + */ + this._lineTint = lineColor; + + /** + * the color of the fill + * @member {number} + */ + this.fillColor = fillColor; + + /** + * the alpha of the fill + * @member {number} + */ + this.fillAlpha = fillAlpha; + + /** + * cached tint of the fill + * @member {number} + * @private + */ + this._fillTint = fillColor; + + /** + * whether or not the shape is filled with a colour + * @member {boolean} + */ + this.fill = fill; + + this.holes = []; + + /** + * The shape object to draw. + * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} + */ + this.shape = shape; + + /** + * The type of the shape, see the Const.Shapes file for all the existing types, + * @member {number} + */ + this.type = shape.type; + } + + /** + * Creates a new GraphicsData object with the same values as this one. + * + * @return {PIXI.GraphicsData} Cloned GraphicsData object + */ + + + GraphicsData.prototype.clone = function clone() { + return new GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.fill, this.nativeLines, this.shape, this.lineAlignment); + }; + + /** + * Adds a hole to the shape. + * + * @param {PIXI.Rectangle|PIXI.Circle} shape - The shape of the hole. + */ + + + GraphicsData.prototype.addHole = function addHole(shape) { + this.holes.push(shape); + }; + + /** + * Destroys the Graphics data. + */ + + + GraphicsData.prototype.destroy = function destroy() { + this.shape = null; + this.holes = null; + }; + + return GraphicsData; +}(); + +exports.default = GraphicsData; + +},{}],55:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they + * now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasGraphicsRenderer: + * https://github.com/libgdx/libgdx/blob/1.0.0/gdx/src/com/badlogic/gdx/graphics/glutils/ShapeRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching graphics objects. + * + * @class + * @private + * @memberof PIXI + */ +var CanvasGraphicsRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The current PIXI renderer. + */ + function CanvasGraphicsRenderer(renderer) { + _classCallCheck(this, CanvasGraphicsRenderer); + + this.renderer = renderer; + } + + /** + * Renders a Graphics object to a canvas. + * + * @param {PIXI.Graphics} graphics - the actual graphics object to render + */ + + + CanvasGraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var context = renderer.context; + var worldAlpha = graphics.worldAlpha; + var transform = graphics.transform.worldTransform; + var resolution = renderer.resolution; + + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // update tint if graphics was dirty + if (graphics.canvasTintDirty !== graphics.dirty || graphics._prevTint !== graphics.tint) { + this.updateGraphicsTint(graphics); + } + + renderer.setBlendMode(graphics.blendMode); + + for (var i = 0; i < graphics.graphicsData.length; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + var fillColor = data._fillTint; + var lineColor = data._lineTint; + + context.lineWidth = data.lineWidth; + + if (data.type === _const.SHAPES.POLY) { + context.beginPath(); + + var points = shape.points; + var holes = data.holes; + var outerArea = void 0; + var innerArea = void 0; + var px = void 0; + var py = void 0; + + context.moveTo(points[0], points[1]); + + for (var j = 2; j < points.length; j += 2) { + context.lineTo(points[j], points[j + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (shape.closed) { + context.closePath(); + } + + if (holes.length > 0) { + outerArea = 0; + px = points[0]; + py = points[1]; + for (var _j = 2; _j + 2 < points.length; _j += 2) { + outerArea += (points[_j] - px) * (points[_j + 3] - py) - (points[_j + 2] - px) * (points[_j + 1] - py); + } + + for (var k = 0; k < holes.length; k++) { + points = holes[k].points; + + if (!points) { + continue; + } + + innerArea = 0; + px = points[0]; + py = points[1]; + for (var _j2 = 2; _j2 + 2 < points.length; _j2 += 2) { + innerArea += (points[_j2] - px) * (points[_j2 + 3] - py) - (points[_j2 + 2] - px) * (points[_j2 + 1] - py); + } + + if (innerArea * outerArea < 0) { + context.moveTo(points[0], points[1]); + + for (var _j3 = 2; _j3 < points.length; _j3 += 2) { + context.lineTo(points[_j3], points[_j3 + 1]); + } + } else { + context.moveTo(points[points.length - 2], points[points.length - 1]); + + for (var _j4 = points.length - 4; _j4 >= 0; _j4 -= 2) { + context.lineTo(points[_j4], points[_j4 + 1]); + } + } + + if (holes[k].close) { + context.closePath(); + } + } + } + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RECT) { + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fillRect(shape.x, shape.y, shape.width, shape.height); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.strokeRect(shape.x, shape.y, shape.width, shape.height); + } + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.beginPath(); + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + context.beginPath(); + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + + context.closePath(); + + if (data.fill) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.beginPath(); + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + + if (data.fillColor || data.fillColor === 0) { + context.globalAlpha = data.fillAlpha * worldAlpha; + context.fillStyle = '#' + ('00000' + (fillColor | 0).toString(16)).substr(-6); + context.fill(); + } + + if (data.lineWidth) { + context.globalAlpha = data.lineAlpha * worldAlpha; + context.strokeStyle = '#' + ('00000' + (lineColor | 0).toString(16)).substr(-6); + context.stroke(); + } + } + } + }; + + /** + * Updates the tint of a graphics object + * + * @private + * @param {PIXI.Graphics} graphics - the graphics that will have its tint updated + */ + + + CanvasGraphicsRenderer.prototype.updateGraphicsTint = function updateGraphicsTint(graphics) { + graphics._prevTint = graphics.tint; + graphics.canvasTintDirty = graphics.dirty; + + var tintR = (graphics.tint >> 16 & 0xFF) / 255; + var tintG = (graphics.tint >> 8 & 0xFF) / 255; + var tintB = (graphics.tint & 0xFF) / 255; + + for (var i = 0; i < graphics.graphicsData.length; ++i) { + var data = graphics.graphicsData[i]; + + var fillColor = data.fillColor | 0; + var lineColor = data.lineColor | 0; + + // super inline, cos optimization :) + data._fillTint = ((fillColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (fillColor & 0xFF) / 255 * tintB * 255; + + data._lineTint = ((lineColor >> 16 & 0xFF) / 255 * tintR * 255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG * 255 << 8) + (lineColor & 0xFF) / 255 * tintB * 255; + } + }; + + /** + * Renders a polygon. + * + * @param {PIXI.Point[]} points - The points to render + * @param {boolean} close - Should the polygon be closed + * @param {CanvasRenderingContext2D} context - The rendering context to use + */ + + + CanvasGraphicsRenderer.prototype.renderPolygon = function renderPolygon(points, close, context) { + context.moveTo(points[0], points[1]); + + for (var j = 1; j < points.length / 2; ++j) { + context.lineTo(points[j * 2], points[j * 2 + 1]); + } + + if (close) { + context.closePath(); + } + }; + + /** + * destroy graphics object + * + */ + + + CanvasGraphicsRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasGraphicsRenderer; +}(); + +exports.default = CanvasGraphicsRenderer; + + +_CanvasRenderer2.default.registerPlugin('graphics', CanvasGraphicsRenderer); + +},{"../../const":46,"../../renderers/canvas/CanvasRenderer":77}],56:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = bezierCurveTo; +/** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @param {number} fromX - Starting point x + * @param {number} fromY - Starting point y + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} cpX2 - Second Control point x + * @param {number} cpY2 - Second Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number} n - Number of segments approximating the bezier curve + * @param {number[]} [path=[]] - Path array to push points into + * @return {number[]} Array of points of the curve + */ +function bezierCurveTo(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY, n) { + var path = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : []; + + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + + path.push(fromX, fromY); + + for (var i = 1, j = 0; i <= n; ++i) { + j = i / n; + + dt = 1 - j; + dt2 = dt * dt; + dt3 = dt2 * dt; + + t2 = j * j; + t3 = t2 * j; + + path.push(dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX, dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY); + } + + return path; +} + +},{}],57:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _WebGLGraphicsData = require('./WebGLGraphicsData'); + +var _WebGLGraphicsData2 = _interopRequireDefault(_WebGLGraphicsData); + +var _PrimitiveShader = require('./shaders/PrimitiveShader'); + +var _PrimitiveShader2 = _interopRequireDefault(_PrimitiveShader); + +var _buildPoly = require('./utils/buildPoly'); + +var _buildPoly2 = _interopRequireDefault(_buildPoly); + +var _buildRectangle = require('./utils/buildRectangle'); + +var _buildRectangle2 = _interopRequireDefault(_buildRectangle); + +var _buildRoundedRectangle = require('./utils/buildRoundedRectangle'); + +var _buildRoundedRectangle2 = _interopRequireDefault(_buildRoundedRectangle); + +var _buildCircle = require('./utils/buildCircle'); + +var _buildCircle2 = _interopRequireDefault(_buildCircle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Renders the graphics object. + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ +var GraphicsRenderer = function (_ObjectRenderer) { + _inherits(GraphicsRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this object renderer works for. + */ + function GraphicsRenderer(renderer) { + _classCallCheck(this, GraphicsRenderer); + + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.graphicsDataPool = []; + + _this.primitiveShader = null; + + _this.gl = renderer.gl; + + // easy access! + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * Called when there is a WebGL context change + * + * @private + * + */ + + + GraphicsRenderer.prototype.onContextChange = function onContextChange() { + this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.primitiveShader = new _PrimitiveShader2.default(this.gl); + }; + + /** + * Destroys this renderer. + * + */ + + + GraphicsRenderer.prototype.destroy = function destroy() { + _ObjectRenderer3.default.prototype.destroy.call(this); + + for (var i = 0; i < this.graphicsDataPool.length; ++i) { + this.graphicsDataPool[i].destroy(); + } + + this.graphicsDataPool = null; + }; + + /** + * Renders a graphics object. + * + * @param {PIXI.Graphics} graphics - The graphics object to render. + */ + + + GraphicsRenderer.prototype.render = function render(graphics) { + var renderer = this.renderer; + var gl = renderer.gl; + + var webGLData = void 0; + var webGL = graphics._webGL[this.CONTEXT_UID]; + + if (!webGL || graphics.dirty !== webGL.dirty) { + this.updateGraphics(graphics); + + webGL = graphics._webGL[this.CONTEXT_UID]; + } + + // This could be speeded up for sure! + var shader = this.primitiveShader; + + renderer.bindShader(shader); + renderer.state.setBlendMode(graphics.blendMode); + + for (var i = 0, n = webGL.data.length; i < n; i++) { + webGLData = webGL.data[i]; + var shaderTemp = webGLData.shader; + + renderer.bindShader(shaderTemp); + shaderTemp.uniforms.translationMatrix = graphics.transform.worldTransform.toArray(true); + shaderTemp.uniforms.tint = (0, _utils.hex2rgb)(graphics.tint); + shaderTemp.uniforms.alpha = graphics.worldAlpha; + + renderer.bindVao(webGLData.vao); + + if (webGLData.nativeLines) { + gl.drawArrays(gl.LINES, 0, webGLData.points.length / 6); + } else { + webGLData.vao.draw(gl.TRIANGLE_STRIP, webGLData.indices.length); + } + } + }; + + /** + * Updates the graphics object + * + * @private + * @param {PIXI.Graphics} graphics - The graphics object to update + */ + + + GraphicsRenderer.prototype.updateGraphics = function updateGraphics(graphics) { + var gl = this.renderer.gl; + + // get the contexts graphics object + var webGL = graphics._webGL[this.CONTEXT_UID]; + + // if the graphics object does not exist in the webGL context time to create it! + if (!webGL) { + webGL = graphics._webGL[this.CONTEXT_UID] = { lastIndex: 0, data: [], gl: gl, clearDirty: -1, dirty: -1 }; + } + + // flag the graphics as not dirty as we are about to update it... + webGL.dirty = graphics.dirty; + + // if the user cleared the graphics object we will need to clear every object + if (graphics.clearDirty !== webGL.clearDirty) { + webGL.clearDirty = graphics.clearDirty; + + // loop through and return all the webGLDatas to the object pool so than can be reused later on + for (var i = 0; i < webGL.data.length; i++) { + this.graphicsDataPool.push(webGL.data[i]); + } + + // clear the array and reset the index.. + webGL.data.length = 0; + webGL.lastIndex = 0; + } + + var webGLData = void 0; + var webGLDataNativeLines = void 0; + + // loop through the graphics datas and construct each one.. + // if the object is a complex fill then the new stencil buffer technique will be used + // other wise graphics objects will be pushed into a batch.. + for (var _i = webGL.lastIndex; _i < graphics.graphicsData.length; _i++) { + var data = graphics.graphicsData[_i]; + + // TODO - this can be simplified + webGLData = this.getWebGLData(webGL, 0); + + if (data.nativeLines && data.lineWidth) { + webGLDataNativeLines = this.getWebGLData(webGL, 0, true); + webGL.lastIndex++; + } + + if (data.type === _const.SHAPES.POLY) { + (0, _buildPoly2.default)(data, webGLData, webGLDataNativeLines); + } + if (data.type === _const.SHAPES.RECT) { + (0, _buildRectangle2.default)(data, webGLData, webGLDataNativeLines); + } else if (data.type === _const.SHAPES.CIRC || data.type === _const.SHAPES.ELIP) { + (0, _buildCircle2.default)(data, webGLData, webGLDataNativeLines); + } else if (data.type === _const.SHAPES.RREC) { + (0, _buildRoundedRectangle2.default)(data, webGLData, webGLDataNativeLines); + } + + webGL.lastIndex++; + } + + this.renderer.bindVao(null); + + // upload all the dirty data... + for (var _i2 = 0; _i2 < webGL.data.length; _i2++) { + webGLData = webGL.data[_i2]; + + if (webGLData.dirty) { + webGLData.upload(); + } + } + }; + + /** + * + * @private + * @param {WebGLRenderingContext} gl - the current WebGL drawing context + * @param {number} type - TODO @Alvin + * @param {number} nativeLines - indicate whether the webGLData use for nativeLines. + * @return {*} TODO + */ + + + GraphicsRenderer.prototype.getWebGLData = function getWebGLData(gl, type, nativeLines) { + var webGLData = gl.data[gl.data.length - 1]; + + if (!webGLData || webGLData.nativeLines !== nativeLines || webGLData.points.length > 320000) { + webGLData = this.graphicsDataPool.pop() || new _WebGLGraphicsData2.default(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData.nativeLines = nativeLines; + webGLData.reset(type); + gl.data.push(webGLData); + } + + webGLData.dirty = true; + + return webGLData; + }; + + return GraphicsRenderer; +}(_ObjectRenderer3.default); + +exports.default = GraphicsRenderer; + + +_WebGLRenderer2.default.registerPlugin('graphics', GraphicsRenderer); + +},{"../../const":46,"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../utils":125,"./WebGLGraphicsData":58,"./shaders/PrimitiveShader":59,"./utils/buildCircle":60,"./utils/buildPoly":62,"./utils/buildRectangle":63,"./utils/buildRoundedRectangle":64}],58:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * An object containing WebGL specific properties to be used by the WebGL renderer + * + * @class + * @private + * @memberof PIXI + */ +var WebGLGraphicsData = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {PIXI.Shader} shader - The shader + * @param {object} attribsState - The state for the VAO + */ + function WebGLGraphicsData(gl, shader, attribsState) { + _classCallCheck(this, WebGLGraphicsData); + + /** + * The current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // TODO does this need to be split before uploading?? + /** + * An array of color components (r,g,b) + * @member {number[]} + */ + this.color = [0, 0, 0]; // color split! + + /** + * An array of points to draw + * @member {PIXI.Point[]} + */ + this.points = []; + + /** + * The indices of the vertices + * @member {number[]} + */ + this.indices = []; + /** + * The main buffer + * @member {WebGLBuffer} + */ + this.buffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl); + + /** + * The index buffer + * @member {WebGLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl); + + /** + * Whether this graphics is dirty or not + * @member {boolean} + */ + this.dirty = true; + + /** + * Whether this graphics is nativeLines or not + * @member {boolean} + */ + this.nativeLines = false; + + this.glPoints = null; + this.glIndices = null; + + /** + * + * @member {PIXI.Shader} + */ + this.shader = shader; + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, attribsState).addIndex(this.indexBuffer).addAttribute(this.buffer, shader.attributes.aVertexPosition, gl.FLOAT, false, 4 * 6, 0).addAttribute(this.buffer, shader.attributes.aColor, gl.FLOAT, false, 4 * 6, 2 * 4); + } + + /** + * Resets the vertices and the indices + */ + + + WebGLGraphicsData.prototype.reset = function reset() { + this.points.length = 0; + this.indices.length = 0; + }; + + /** + * Binds the buffers and uploads the data + */ + + + WebGLGraphicsData.prototype.upload = function upload() { + this.glPoints = new Float32Array(this.points); + this.buffer.upload(this.glPoints); + + this.glIndices = new Uint16Array(this.indices); + this.indexBuffer.upload(this.glIndices); + + this.dirty = false; + }; + + /** + * Empties all the data + */ + + + WebGLGraphicsData.prototype.destroy = function destroy() { + this.color = null; + this.points = null; + this.indices = null; + + this.vao.destroy(); + this.buffer.destroy(); + this.indexBuffer.destroy(); + + this.gl = null; + + this.buffer = null; + this.indexBuffer = null; + + this.glPoints = null; + this.glIndices = null; + }; + + return WebGLGraphicsData; +}(); + +exports.default = WebGLGraphicsData; + +},{"pixi-gl-core":15}],59:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../../Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. + * + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ +var PrimitiveShader = function (_Shader) { + _inherits(PrimitiveShader, _Shader); + + /** + * @param {WebGLRenderingContext} gl - The webgl shader manager this shader works for. + */ + function PrimitiveShader(gl) { + _classCallCheck(this, PrimitiveShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec4 aColor;', 'uniform mat3 translationMatrix;', 'uniform mat3 projectionMatrix;', 'uniform float alpha;', 'uniform vec3 tint;', 'varying vec4 vColor;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vColor = aColor * vec4(tint * alpha, alpha);', '}'].join('\n'), + // fragment shader + ['varying vec4 vColor;', 'void main(void){', ' gl_FragColor = vColor;', '}'].join('\n'))); + } + + return PrimitiveShader; +}(_Shader3.default); + +exports.default = PrimitiveShader; + +},{"../../../Shader":44}],60:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildCircle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _const = require('../../../const'); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildCircle(graphicsData, webGLData, webGLDataNativeLines) { + // need to convert points to a nice regular data + var circleData = graphicsData.shape; + var x = circleData.x; + var y = circleData.y; + var width = void 0; + var height = void 0; + + // TODO - bit hacky?? + if (graphicsData.type === _const.SHAPES.CIRC) { + width = circleData.radius; + height = circleData.radius; + } else { + width = circleData.width; + height = circleData.height; + } + + if (width === 0 || height === 0) { + return; + } + + var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) || Math.floor(15 * Math.sqrt(circleData.width + circleData.height)); + + var seg = Math.PI * 2 / totalSegs; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + indices.push(vecPos); + + for (var i = 0; i < totalSegs + 1; i++) { + verts.push(x, y, r, g, b, alpha); + + verts.push(x + Math.sin(seg * i) * width, y + Math.cos(seg * i) * height, r, g, b, alpha); + + indices.push(vecPos++, vecPos++); + } + + indices.push(vecPos - 1); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = []; + + for (var _i = 0; _i < totalSegs; _i++) { + graphicsData.points.push(x + Math.sin(seg * -_i) * width, y + Math.cos(seg * -_i) * height); + } + + graphicsData.points.push(graphicsData.points[0], graphicsData.points[1]); + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +},{"../../../const":46,"../../../utils":125,"./buildLine":61}],61:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function (graphicsData, webGLData, webGLDataNativeLines) { + if (graphicsData.nativeLines) { + buildNativeLine(graphicsData, webGLDataNativeLines); + } else { + buildLine(graphicsData, webGLData); + } +}; + +var _math = require('../../../math'); + +var _utils = require('../../../utils'); + +/** + * Builds a line to draw using the poligon method. + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ +function buildLine(graphicsData, webGLData) { + // TODO OPTIMISE! + var points = graphicsData.points; + + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + + // get first and last point.. figure out the middle! + var firstPoint = new _math.Point(points[0], points[1]); + var lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + // if the first point is the last point - gonna have issues :) + if (firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + + points.pop(); + points.pop(); + + lastPoint = new _math.Point(points[points.length - 2], points[points.length - 1]); + + var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) * 0.5; + var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) * 0.5; + + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + + var verts = webGLData.points; + var indices = webGLData.indices; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 6; + + // DRAW the Line + var width = graphicsData.lineWidth / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var p1x = points[0]; + var p1y = points[1]; + var p2x = points[2]; + var p2y = points[3]; + var p3x = 0; + var p3y = 0; + + var perpx = -(p1y - p2y); + var perpy = p1x - p2x; + var perp2x = 0; + var perp2y = 0; + var perp3x = 0; + var perp3y = 0; + + var dist = Math.sqrt(perpx * perpx + perpy * perpy); + + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + var ratio = graphicsData.lineAlignment; // 0.5; + var r1 = (1 - ratio) * 2; + var r2 = ratio * 2; + + // start + verts.push(p1x - perpx * r1, p1y - perpy * r1, r, g, b, alpha); + + verts.push(p1x + perpx * r2, p1y + perpy * r2, r, g, b, alpha); + + for (var i = 1; i < length - 1; ++i) { + p1x = points[(i - 1) * 2]; + p1y = points[(i - 1) * 2 + 1]; + + p2x = points[i * 2]; + p2y = points[i * 2 + 1]; + + p3x = points[(i + 1) * 2]; + p3y = points[(i + 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + perp2x = -(p2y - p3y); + perp2y = p2x - p3x; + + dist = Math.sqrt(perp2x * perp2x + perp2y * perp2y); + perp2x /= dist; + perp2y /= dist; + perp2x *= width; + perp2y *= width; + + var a1 = -perpy + p1y - (-perpy + p2y); + var b1 = -perpx + p2x - (-perpx + p1x); + var c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); + var a2 = -perp2y + p3y - (-perp2y + p2y); + var b2 = -perp2x + p2x - (-perp2x + p3x); + var c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); + + var denom = a1 * b2 - a2 * b1; + + if (Math.abs(denom) < 0.1) { + denom += 10.1; + verts.push(p2x - perpx * r1, p2y - perpy * r1, r, g, b, alpha); + + verts.push(p2x + perpx * r2, p2y + perpy * r2, r, g, b, alpha); + + continue; + } + + var px = (b1 * c2 - b2 * c1) / denom; + var py = (a2 * c1 - a1 * c2) / denom; + var pdist = (px - p2x) * (px - p2x) + (py - p2y) * (py - p2y); + + if (pdist > 196 * width * width) { + perp3x = perpx - perp2x; + perp3y = perpy - perp2y; + + dist = Math.sqrt(perp3x * perp3x + perp3y * perp3y); + perp3x /= dist; + perp3y /= dist; + perp3x *= width; + perp3y *= width; + + verts.push(p2x - perp3x * r1, p2y - perp3y * r1); + verts.push(r, g, b, alpha); + + verts.push(p2x + perp3x * r2, p2y + perp3y * r2); + verts.push(r, g, b, alpha); + + verts.push(p2x - perp3x * r2 * r1, p2y - perp3y * r1); + verts.push(r, g, b, alpha); + + indexCount++; + } else { + verts.push(p2x + (px - p2x) * r1, p2y + (py - p2y) * r1); + verts.push(r, g, b, alpha); + + verts.push(p2x - (px - p2x) * r2, p2y - (py - p2y) * r2); + verts.push(r, g, b, alpha); + } + } + + p1x = points[(length - 2) * 2]; + p1y = points[(length - 2) * 2 + 1]; + + p2x = points[(length - 1) * 2]; + p2y = points[(length - 1) * 2 + 1]; + + perpx = -(p1y - p2y); + perpy = p1x - p2x; + + dist = Math.sqrt(perpx * perpx + perpy * perpy); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + + verts.push(p2x - perpx * r1, p2y - perpy * r1); + verts.push(r, g, b, alpha); + + verts.push(p2x + perpx * r2, p2y + perpy * r2); + verts.push(r, g, b, alpha); + + indices.push(indexStart); + + for (var _i = 0; _i < indexCount; ++_i) { + indices.push(indexStart++); + } + + indices.push(indexStart - 1); +} + +/** + * Builds a line to draw using the gl.drawArrays(gl.LINES) method + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + */ + + +/** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildNativeLine(graphicsData, webGLData) { + var i = 0; + var points = graphicsData.points; + + if (points.length === 0) return; + + var verts = webGLData.points; + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.lineColor); + var alpha = graphicsData.lineAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + for (i = 1; i < length; i++) { + var p1x = points[(i - 1) * 2]; + var p1y = points[(i - 1) * 2 + 1]; + + var p2x = points[i * 2]; + var p2y = points[i * 2 + 1]; + + verts.push(p1x, p1y); + verts.push(r, g, b, alpha); + + verts.push(p2x, p2y); + verts.push(r, g, b, alpha); + } +} + +},{"../../../math":70,"../../../utils":125}],62:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildPoly; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildPoly(graphicsData, webGLData, webGLDataNativeLines) { + graphicsData.points = graphicsData.shape.points.slice(); + + var points = graphicsData.points; + + if (graphicsData.fill && points.length >= 6) { + var holeArray = []; + // Process holes.. + var holes = graphicsData.holes; + + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + + holeArray.push(points.length / 2); + + points = points.concat(hole.points); + } + + // get first and last point.. figure out the middle! + var verts = webGLData.points; + var indices = webGLData.indices; + + var length = points.length / 2; + + // sort color + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var triangles = (0, _earcut2.default)(points, holeArray, 2); + + if (!triangles) { + return; + } + + var vertPos = verts.length / 6; + + for (var _i = 0; _i < triangles.length; _i += 3) { + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i] + vertPos); + indices.push(triangles[_i + 1] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + indices.push(triangles[_i + 2] + vertPos); + } + + for (var _i2 = 0; _i2 < length; _i2++) { + verts.push(points[_i2 * 2], points[_i2 * 2 + 1], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth > 0) { + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + } +} + +},{"../../../utils":125,"./buildLine":61,"earcut":2}],63:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRectangle; + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildRectangle(graphicsData, webGLData, webGLDataNativeLines) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vertPos = verts.length / 6; + + // start + verts.push(x, y); + verts.push(r, g, b, alpha); + + verts.push(x + width, y); + verts.push(r, g, b, alpha); + + verts.push(x, y + height); + verts.push(r, g, b, alpha); + + verts.push(x + width, y + height); + verts.push(r, g, b, alpha); + + // insert 2 dead triangles.. + indices.push(vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3); + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = [x, y, x + width, y, x + width, y + height, x, y + height, x, y]; + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +},{"../../../utils":125,"./buildLine":61}],64:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = buildRoundedRectangle; + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +var _buildLine = require('./buildLine'); + +var _buildLine2 = _interopRequireDefault(_buildLine); + +var _utils = require('../../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the webGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the webGL-specific information to create nativeLines + */ +function buildRoundedRectangle(graphicsData, webGLData, webGLDataNativeLines) { + var rrectData = graphicsData.shape; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + + var radius = rrectData.radius; + + var recPoints = []; + + recPoints.push(x + radius, y); + quadraticBezierCurve(x + width - radius, y, x + width, y, x + width, y + radius, recPoints); + quadraticBezierCurve(x + width, y + height - radius, x + width, y + height, x + width - radius, y + height, recPoints); + quadraticBezierCurve(x + radius, y + height, x, y + height, x, y + height - radius, recPoints); + quadraticBezierCurve(x, y + radius, x, y, x + radius + 0.0000000001, y, recPoints); + + // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. + // TODO - fix this properly, this is not very elegant.. but it works for now. + + if (graphicsData.fill) { + var color = (0, _utils.hex2rgb)(graphicsData.fillColor); + var alpha = graphicsData.fillAlpha; + + var r = color[0] * alpha; + var g = color[1] * alpha; + var b = color[2] * alpha; + + var verts = webGLData.points; + var indices = webGLData.indices; + + var vecPos = verts.length / 6; + + var triangles = (0, _earcut2.default)(recPoints, null, 2); + + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + + for (var _i = 0, _j = recPoints.length; _i < _j; _i++) { + verts.push(recPoints[_i], recPoints[++_i], r, g, b, alpha); + } + } + + if (graphicsData.lineWidth) { + var tempPoints = graphicsData.points; + + graphicsData.points = recPoints; + + (0, _buildLine2.default)(graphicsData, webGLData, webGLDataNativeLines); + + graphicsData.points = tempPoints; + } +} + +/** + * Calculate a single point for a quadratic bezier curve. + * Utility function used by quadraticBezierCurve. + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} n1 - first number + * @param {number} n2 - second number + * @param {number} perc - percentage + * @return {number} the result + * + */ +function getPt(n1, n2, perc) { + var diff = n2 - n1; + + return n1 + diff * perc; +} + +/** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @return {number[]} an array of points + */ +function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY) { + var out = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : []; + + var n = 20; + var points = out; + + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + + points.push(x, y); + } + + return points; +} + +},{"../../../utils":125,"./buildLine":61,"earcut":2}],65:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.autoDetectRenderer = exports.Application = exports.Filter = exports.SpriteMaskFilter = exports.Quad = exports.RenderTarget = exports.ObjectRenderer = exports.WebGLManager = exports.Shader = exports.CanvasRenderTarget = exports.TextureUvs = exports.VideoBaseTexture = exports.BaseRenderTexture = exports.RenderTexture = exports.BaseTexture = exports.TextureMatrix = exports.Texture = exports.Spritesheet = exports.CanvasGraphicsRenderer = exports.GraphicsRenderer = exports.GraphicsData = exports.Graphics = exports.TextMetrics = exports.TextStyle = exports.Text = exports.SpriteRenderer = exports.CanvasTinter = exports.CanvasSpriteRenderer = exports.Sprite = exports.TransformBase = exports.TransformStatic = exports.Transform = exports.Container = exports.DisplayObject = exports.Bounds = exports.glCore = exports.WebGLRenderer = exports.CanvasRenderer = exports.ticker = exports.utils = exports.settings = undefined; + +var _const = require('./const'); + +Object.keys(_const).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _const[key]; + } + }); +}); + +var _math = require('./math'); + +Object.keys(_math).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _math[key]; + } + }); +}); + +var _pixiGlCore = require('pixi-gl-core'); + +Object.defineProperty(exports, 'glCore', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_pixiGlCore).default; + } +}); + +var _Bounds = require('./display/Bounds'); + +Object.defineProperty(exports, 'Bounds', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Bounds).default; + } +}); + +var _DisplayObject = require('./display/DisplayObject'); + +Object.defineProperty(exports, 'DisplayObject', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplayObject).default; + } +}); + +var _Container = require('./display/Container'); + +Object.defineProperty(exports, 'Container', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Container).default; + } +}); + +var _Transform = require('./display/Transform'); + +Object.defineProperty(exports, 'Transform', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Transform).default; + } +}); + +var _TransformStatic = require('./display/TransformStatic'); + +Object.defineProperty(exports, 'TransformStatic', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformStatic).default; + } +}); + +var _TransformBase = require('./display/TransformBase'); + +Object.defineProperty(exports, 'TransformBase', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TransformBase).default; + } +}); + +var _Sprite = require('./sprites/Sprite'); + +Object.defineProperty(exports, 'Sprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Sprite).default; + } +}); + +var _CanvasSpriteRenderer = require('./sprites/canvas/CanvasSpriteRenderer'); + +Object.defineProperty(exports, 'CanvasSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasSpriteRenderer).default; + } +}); + +var _CanvasTinter = require('./sprites/canvas/CanvasTinter'); + +Object.defineProperty(exports, 'CanvasTinter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasTinter).default; + } +}); + +var _SpriteRenderer = require('./sprites/webgl/SpriteRenderer'); + +Object.defineProperty(exports, 'SpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteRenderer).default; + } +}); + +var _Text = require('./text/Text'); + +Object.defineProperty(exports, 'Text', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Text).default; + } +}); + +var _TextStyle = require('./text/TextStyle'); + +Object.defineProperty(exports, 'TextStyle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextStyle).default; + } +}); + +var _TextMetrics = require('./text/TextMetrics'); + +Object.defineProperty(exports, 'TextMetrics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextMetrics).default; + } +}); + +var _Graphics = require('./graphics/Graphics'); + +Object.defineProperty(exports, 'Graphics', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Graphics).default; + } +}); + +var _GraphicsData = require('./graphics/GraphicsData'); + +Object.defineProperty(exports, 'GraphicsData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsData).default; + } +}); + +var _GraphicsRenderer = require('./graphics/webgl/GraphicsRenderer'); + +Object.defineProperty(exports, 'GraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GraphicsRenderer).default; + } +}); + +var _CanvasGraphicsRenderer = require('./graphics/canvas/CanvasGraphicsRenderer'); + +Object.defineProperty(exports, 'CanvasGraphicsRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasGraphicsRenderer).default; + } +}); + +var _Spritesheet = require('./textures/Spritesheet'); + +Object.defineProperty(exports, 'Spritesheet', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Spritesheet).default; + } +}); + +var _Texture = require('./textures/Texture'); + +Object.defineProperty(exports, 'Texture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Texture).default; + } +}); + +var _TextureMatrix = require('./textures/TextureMatrix'); + +Object.defineProperty(exports, 'TextureMatrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureMatrix).default; + } +}); + +var _BaseTexture = require('./textures/BaseTexture'); + +Object.defineProperty(exports, 'BaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseTexture).default; + } +}); + +var _RenderTexture = require('./textures/RenderTexture'); + +Object.defineProperty(exports, 'RenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTexture).default; + } +}); + +var _BaseRenderTexture = require('./textures/BaseRenderTexture'); + +Object.defineProperty(exports, 'BaseRenderTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BaseRenderTexture).default; + } +}); + +var _VideoBaseTexture = require('./textures/VideoBaseTexture'); + +Object.defineProperty(exports, 'VideoBaseTexture', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_VideoBaseTexture).default; + } +}); + +var _TextureUvs = require('./textures/TextureUvs'); + +Object.defineProperty(exports, 'TextureUvs', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TextureUvs).default; + } +}); + +var _CanvasRenderTarget = require('./renderers/canvas/utils/CanvasRenderTarget'); + +Object.defineProperty(exports, 'CanvasRenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasRenderTarget).default; + } +}); + +var _Shader = require('./Shader'); + +Object.defineProperty(exports, 'Shader', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Shader).default; + } +}); + +var _WebGLManager = require('./renderers/webgl/managers/WebGLManager'); + +Object.defineProperty(exports, 'WebGLManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLManager).default; + } +}); + +var _ObjectRenderer = require('./renderers/webgl/utils/ObjectRenderer'); + +Object.defineProperty(exports, 'ObjectRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObjectRenderer).default; + } +}); + +var _RenderTarget = require('./renderers/webgl/utils/RenderTarget'); + +Object.defineProperty(exports, 'RenderTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RenderTarget).default; + } +}); + +var _Quad = require('./renderers/webgl/utils/Quad'); + +Object.defineProperty(exports, 'Quad', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Quad).default; + } +}); + +var _SpriteMaskFilter = require('./renderers/webgl/filters/spriteMask/SpriteMaskFilter'); + +Object.defineProperty(exports, 'SpriteMaskFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_SpriteMaskFilter).default; + } +}); + +var _Filter = require('./renderers/webgl/filters/Filter'); + +Object.defineProperty(exports, 'Filter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Filter).default; + } +}); + +var _Application = require('./Application'); + +Object.defineProperty(exports, 'Application', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Application).default; + } +}); + +var _autoDetectRenderer = require('./autoDetectRenderer'); + +Object.defineProperty(exports, 'autoDetectRenderer', { + enumerable: true, + get: function get() { + return _autoDetectRenderer.autoDetectRenderer; + } +}); + +var _utils = require('./utils'); + +var utils = _interopRequireWildcard(_utils); + +var _ticker = require('./ticker'); + +var ticker = _interopRequireWildcard(_ticker); + +var _settings = require('./settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _CanvasRenderer = require('./renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _WebGLRenderer = require('./renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.settings = _settings2.default; +exports.utils = utils; +exports.ticker = ticker; +exports.CanvasRenderer = _CanvasRenderer2.default; +exports.WebGLRenderer = _WebGLRenderer2.default; /** + * @namespace PIXI + */ + +},{"./Application":43,"./Shader":44,"./autoDetectRenderer":45,"./const":46,"./display/Bounds":47,"./display/Container":48,"./display/DisplayObject":49,"./display/Transform":50,"./display/TransformBase":51,"./display/TransformStatic":52,"./graphics/Graphics":53,"./graphics/GraphicsData":54,"./graphics/canvas/CanvasGraphicsRenderer":55,"./graphics/webgl/GraphicsRenderer":57,"./math":70,"./renderers/canvas/CanvasRenderer":77,"./renderers/canvas/utils/CanvasRenderTarget":79,"./renderers/webgl/WebGLRenderer":84,"./renderers/webgl/filters/Filter":86,"./renderers/webgl/filters/spriteMask/SpriteMaskFilter":89,"./renderers/webgl/managers/WebGLManager":93,"./renderers/webgl/utils/ObjectRenderer":94,"./renderers/webgl/utils/Quad":95,"./renderers/webgl/utils/RenderTarget":96,"./settings":101,"./sprites/Sprite":102,"./sprites/canvas/CanvasSpriteRenderer":103,"./sprites/canvas/CanvasTinter":104,"./sprites/webgl/SpriteRenderer":106,"./text/Text":108,"./text/TextMetrics":109,"./text/TextStyle":110,"./textures/BaseRenderTexture":111,"./textures/BaseTexture":112,"./textures/RenderTexture":113,"./textures/Spritesheet":114,"./textures/Texture":115,"./textures/TextureMatrix":116,"./textures/TextureUvs":117,"./textures/VideoBaseTexture":118,"./ticker":121,"./utils":125,"pixi-gl-core":15}],66:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Matrix = require('./Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16 + +var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; +var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; +var tempMatrices = []; + +var mul = []; + +function signum(x) { + if (x < 0) { + return -1; + } + if (x > 0) { + return 1; + } + + return 0; +} + +function init() { + for (var i = 0; i < 16; i++) { + var row = []; + + mul.push(row); + + for (var j = 0; j < 16; j++) { + var _ux = signum(ux[i] * ux[j] + vx[i] * uy[j]); + var _uy = signum(uy[i] * ux[j] + vy[i] * uy[j]); + var _vx = signum(ux[i] * vx[j] + vx[i] * vy[j]); + var _vy = signum(uy[i] * vx[j] + vy[i] * vy[j]); + + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + + for (var _i = 0; _i < 16; _i++) { + var mat = new _Matrix2.default(); + + mat.set(ux[_i], uy[_i], vx[_i], vy[_i], 0, 0); + tempMatrices.push(mat); + } +} + +init(); + +/** + * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}, + * D8 is the same but with diagonals. Used for texture rotations. + * + * Vector xX(i), xY(i) is U-axis of sprite with rotation i + * Vector yY(i), yY(i) is V-axis of sprite with rotation i + * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6) + * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14) + * This is the small part of gameofbombs.com portal system. It works. + * + * @author Ivan @ivanpopelyshev + * @class + * @memberof PIXI + */ +var GroupD8 = { + E: 0, + SE: 1, + S: 2, + SW: 3, + W: 4, + NW: 5, + N: 6, + NE: 7, + MIRROR_VERTICAL: 8, + MIRROR_HORIZONTAL: 12, + uX: function uX(ind) { + return ux[ind]; + }, + uY: function uY(ind) { + return uy[ind]; + }, + vX: function vX(ind) { + return vx[ind]; + }, + vY: function vY(ind) { + return vy[ind]; + }, + inv: function inv(rotation) { + if (rotation & 8) { + return rotation & 15; + } + + return -rotation & 7; + }, + add: function add(rotationSecond, rotationFirst) { + return mul[rotationSecond][rotationFirst]; + }, + sub: function sub(rotationSecond, rotationFirst) { + return mul[rotationSecond][GroupD8.inv(rotationFirst)]; + }, + + /** + * Adds 180 degrees to rotation. Commutative operation. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to rotate. + * @returns {number} rotated number + */ + rotate180: function rotate180(rotation) { + return rotation ^ 4; + }, + + /** + * Direction of main vector can be horizontal, vertical or diagonal. + * Some objects work with vertical directions different. + * + * @memberof PIXI.GroupD8 + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the direction is vertical + */ + isVertical: function isVertical(rotation) { + return (rotation & 3) === 2; + }, + + /** + * @memberof PIXI.GroupD8 + * @param {number} dx - TODO + * @param {number} dy - TODO + * + * @return {number} TODO + */ + byDirection: function byDirection(dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return GroupD8.S; + } + + return GroupD8.N; + } else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return GroupD8.E; + } + + return GroupD8.W; + } else if (dy > 0) { + if (dx > 0) { + return GroupD8.SE; + } + + return GroupD8.SW; + } else if (dx > 0) { + return GroupD8.NE; + } + + return GroupD8.NW; + }, + + /** + * Helps sprite to compensate texture packer rotation. + * + * @memberof PIXI.GroupD8 + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {number} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function matrixAppendRotationInv(matrix, rotation) { + var tx = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var ty = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + // Packer used "rotation", we use "inv(rotation)" + var mat = tempMatrices[GroupD8.inv(rotation)]; + + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + } +}; + +exports.default = GroupD8; + +},{"./Matrix":67}],67:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Point = require('./Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The PixiJS Matrix class as an object, which makes it a lot faster, + * here is a representation of it : + * | a | c | tx| + * | b | d | ty| + * | 0 | 0 | 1 | + * + * @class + * @memberof PIXI + */ +var Matrix = function () { + /** + * @param {number} [a=1] - x scale + * @param {number} [b=0] - x skew + * @param {number} [c=0] - y skew + * @param {number} [d=1] - y scale + * @param {number} [tx=0] - x translation + * @param {number} [ty=0] - y translation + */ + function Matrix() { + var a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + var b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var c = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var d = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; + var tx = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; + var ty = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + + _classCallCheck(this, Matrix); + + /** + * @member {number} + * @default 1 + */ + this.a = a; + + /** + * @member {number} + * @default 0 + */ + this.b = b; + + /** + * @member {number} + * @default 0 + */ + this.c = c; + + /** + * @member {number} + * @default 1 + */ + this.d = d; + + /** + * @member {number} + * @default 0 + */ + this.tx = tx; + + /** + * @member {number} + * @default 0 + */ + this.ty = ty; + + this.array = null; + } + + /** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * + * @param {number[]} array - The array that the matrix will be populated from. + */ + + + Matrix.prototype.fromArray = function fromArray(array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + }; + + /** + * sets the matrix properties + * + * @param {number} a - Matrix component + * @param {number} b - Matrix component + * @param {number} c - Matrix component + * @param {number} d - Matrix component + * @param {number} tx - Matrix component + * @param {number} ty - Matrix component + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.set = function set(a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + + return this; + }; + + /** + * Creates an array from the current Matrix object. + * + * @param {boolean} transpose - Whether we need to transpose the matrix or not + * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out + * @return {number[]} the newly created array which contains the matrix + */ + + + Matrix.prototype.toArray = function toArray(transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + + var array = out || this.array; + + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + + return array; + }; + + /** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, transformed through this matrix + */ + + + Matrix.prototype.apply = function apply(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.a * x + this.c * y + this.tx; + newPos.y = this.b * x + this.d * y + this.ty; + + return newPos; + }; + + /** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * + * @param {PIXI.Point} pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @return {PIXI.Point} The new point, inverse-transformed through this matrix + */ + + + Matrix.prototype.applyInverse = function applyInverse(pos, newPos) { + newPos = newPos || new _Point2.default(); + + var id = 1 / (this.a * this.d + this.c * -this.b); + + var x = pos.x; + var y = pos.y; + + newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id; + newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id; + + return newPos; + }; + + /** + * Translates the matrix on the x and y. + * + * @param {number} x How much to translate x by + * @param {number} y How much to translate y by + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.translate = function translate(x, y) { + this.tx += x; + this.ty += y; + + return this; + }; + + /** + * Applies a scale transformation to the matrix. + * + * @param {number} x The amount to scale horizontally + * @param {number} y The amount to scale vertically + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.scale = function scale(x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + + return this; + }; + + /** + * Applies a rotation transformation to the matrix. + * + * @param {number} angle - The angle in radians. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.rotate = function rotate(angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + + this.a = a1 * cos - this.b * sin; + this.b = a1 * sin + this.b * cos; + this.c = c1 * cos - this.d * sin; + this.d = c1 * sin + this.d * cos; + this.tx = tx1 * cos - this.ty * sin; + this.ty = tx1 * sin + this.ty * cos; + + return this; + }; + + /** + * Appends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to append. + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.append = function append(matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + + this.a = matrix.a * a1 + matrix.b * c1; + this.b = matrix.a * b1 + matrix.b * d1; + this.c = matrix.c * a1 + matrix.d * c1; + this.d = matrix.c * b1 + matrix.d * d1; + + this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx; + this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty; + + return this; + }; + + /** + * Sets the matrix based on all the available properties + * + * @param {number} x - Position on the x axis + * @param {number} y - Position on the y axis + * @param {number} pivotX - Pivot on the x axis + * @param {number} pivotY - Pivot on the y axis + * @param {number} scaleX - Scale on the x axis + * @param {number} scaleY - Scale on the y axis + * @param {number} rotation - Rotation in radians + * @param {number} skewX - Skew on the x axis + * @param {number} skewY - Skew on the y axis + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.setTransform = function setTransform(x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + this.a = Math.cos(rotation + skewY) * scaleX; + this.b = Math.sin(rotation + skewY) * scaleX; + this.c = -Math.sin(rotation - skewX) * scaleY; + this.d = Math.cos(rotation - skewX) * scaleY; + + this.tx = x - (pivotX * this.a + pivotY * this.c); + this.ty = y - (pivotX * this.b + pivotY * this.d); + + return this; + }; + + /** + * Prepends the given Matrix to this Matrix. + * + * @param {PIXI.Matrix} matrix - The matrix to prepend + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.prepend = function prepend(matrix) { + var tx1 = this.tx; + + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + + this.a = a1 * matrix.a + this.b * matrix.c; + this.b = a1 * matrix.b + this.b * matrix.d; + this.c = c1 * matrix.a + this.d * matrix.c; + this.d = c1 * matrix.b + this.d * matrix.d; + } + + this.tx = tx1 * matrix.a + this.ty * matrix.c + matrix.tx; + this.ty = tx1 * matrix.b + this.ty * matrix.d + matrix.ty; + + return this; + }; + + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * + * @param {PIXI.Transform|PIXI.TransformStatic} transform - The transform to apply the properties to. + * @return {PIXI.Transform|PIXI.TransformStatic} The transform with the newly applied properties + */ + + + Matrix.prototype.decompose = function decompose(transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + + var skewX = -Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + + var delta = Math.abs(skewX + skewY); + + if (delta < 0.00001 || Math.abs(_const.PI_2 - delta) < 0.00001) { + transform.rotation = skewY; + transform.skew.x = transform.skew.y = 0; + } else { + transform.rotation = 0; + transform.skew.x = skewX; + transform.skew.y = skewY; + } + + // next set scale + transform.scale.x = Math.sqrt(a * a + b * b); + transform.scale.y = Math.sqrt(c * c + d * d); + + // next set position + transform.position.x = this.tx; + transform.position.y = this.ty; + + return transform; + }; + + /** + * Inverts this matrix + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.invert = function invert() { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = a1 * d1 - b1 * c1; + + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = (c1 * this.ty - d1 * tx1) / n; + this.ty = -(a1 * this.ty - b1 * tx1) / n; + + return this; + }; + + /** + * Resets this Matix to an identity (default) matrix. + * + * @return {PIXI.Matrix} This matrix. Good for chaining method calls. + */ + + + Matrix.prototype.identity = function identity() { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + + return this; + }; + + /** + * Creates a new Matrix object with the same values as this one. + * + * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. + */ + + + Matrix.prototype.clone = function clone() { + var matrix = new Matrix(); + + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * Changes the values of the given matrix to be the same as the ones in this matrix + * + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @return {PIXI.Matrix} The matrix given in parameter with its values updated. + */ + + + Matrix.prototype.copy = function copy(matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + + return matrix; + }; + + /** + * A default (identity) matrix + * + * @static + * @const + */ + + + _createClass(Matrix, null, [{ + key: 'IDENTITY', + get: function get() { + return new Matrix(); + } + + /** + * A temp matrix + * + * @static + * @const + */ + + }, { + key: 'TEMP_MATRIX', + get: function get() { + return new Matrix(); + } + }]); + + return Matrix; +}(); + +exports.default = Matrix; + +},{"../const":46,"./Point":69}],68:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * An observable point is a point that triggers a callback when the point's position is changed. + * + * @class + * @memberof PIXI + */ +var ObservablePoint = function () { + /** + * @param {Function} cb - callback when changed + * @param {object} scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope) { + var x = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var y = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, ObservablePoint); + + this._x = x; + this._y = y; + + this.cb = cb; + this.scope = scope; + } + + /** + * Creates a clone of this point. + * The callback and scope params can be overidden otherwise they will default + * to the clone object's values. + * + * @override + * @param {Function} [cb=null] - callback when changed + * @param {object} [scope=null] - owner of callback + * @return {PIXI.ObservablePoint} a copy of the point + */ + + + ObservablePoint.prototype.clone = function clone() { + var cb = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + + var _cb = cb || this.cb; + var _scope = scope || this.scope; + + return new ObservablePoint(_cb, _scope, this._x, this._y); + }; + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + ObservablePoint.prototype.set = function set(x, y) { + var _x = x || 0; + var _y = y || (y !== 0 ? _x : 0); + + if (this._x !== _x || this._y !== _y) { + this._x = _x; + this._y = _y; + this.cb.call(this.scope); + } + }; + + /** + * Copies the data from another point + * + * @param {PIXI.Point|PIXI.ObservablePoint} point - point to copy from + */ + + + ObservablePoint.prototype.copy = function copy(point) { + if (this._x !== point.x || this._y !== point.y) { + this._x = point.x; + this._y = point.y; + this.cb.call(this.scope); + } + }; + + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.Point|PIXI.ObservablePoint} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + + + ObservablePoint.prototype.equals = function equals(p) { + return p.x === this._x && p.y === this._y; + }; + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + + _createClass(ObservablePoint, [{ + key: "x", + get: function get() { + return this._x; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + } + + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * + * @member {number} + */ + + }, { + key: "y", + get: function get() { + return this._y; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + } + }]); + + return ObservablePoint; +}(); + +exports.default = ObservablePoint; + +},{}],69:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Point object represents a location in a two-dimensional coordinate system, where x represents + * the horizontal axis and y represents the vertical axis. + * + * @class + * @memberof PIXI + */ +var Point = function () { + /** + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function Point() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + + _classCallCheck(this, Point); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + } + + /** + * Creates a clone of this point + * + * @return {PIXI.Point} a copy of the point + */ + + + Point.prototype.clone = function clone() { + return new Point(this.x, this.y); + }; + + /** + * Copies x and y from the given point + * + * @param {PIXI.Point} p - The point to copy. + */ + + + Point.prototype.copy = function copy(p) { + this.set(p.x, p.y); + }; + + /** + * Returns true if the given point is equal to this point + * + * @param {PIXI.Point} p - The point to check + * @returns {boolean} Whether the given point equal to this point + */ + + + Point.prototype.equals = function equals(p) { + return p.x === this.x && p.y === this.y; + }; + + /** + * Sets the point to a new x and y position. + * If y is omitted, both x and y will be set to x. + * + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + + + Point.prototype.set = function set(x, y) { + this.x = x || 0; + this.y = y || (y !== 0 ? this.x : 0); + }; + + return Point; +}(); + +exports.default = Point; + +},{}],70:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('./Point'); + +Object.defineProperty(exports, 'Point', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Point).default; + } +}); + +var _ObservablePoint = require('./ObservablePoint'); + +Object.defineProperty(exports, 'ObservablePoint', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ObservablePoint).default; + } +}); + +var _Matrix = require('./Matrix'); + +Object.defineProperty(exports, 'Matrix', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Matrix).default; + } +}); + +var _GroupD = require('./GroupD8'); + +Object.defineProperty(exports, 'GroupD8', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_GroupD).default; + } +}); + +var _Circle = require('./shapes/Circle'); + +Object.defineProperty(exports, 'Circle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Circle).default; + } +}); + +var _Ellipse = require('./shapes/Ellipse'); + +Object.defineProperty(exports, 'Ellipse', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Ellipse).default; + } +}); + +var _Polygon = require('./shapes/Polygon'); + +Object.defineProperty(exports, 'Polygon', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Polygon).default; + } +}); + +var _Rectangle = require('./shapes/Rectangle'); + +Object.defineProperty(exports, 'Rectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rectangle).default; + } +}); + +var _RoundedRectangle = require('./shapes/RoundedRectangle'); + +Object.defineProperty(exports, 'RoundedRectangle', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_RoundedRectangle).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./GroupD8":66,"./Matrix":67,"./ObservablePoint":68,"./Point":69,"./shapes/Circle":71,"./shapes/Ellipse":72,"./shapes/Polygon":73,"./shapes/Rectangle":74,"./shapes/RoundedRectangle":75}],71:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Circle object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Circle = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this circle + * @param {number} [y=0] - The Y coordinate of the center of this circle + * @param {number} [radius=0] - The radius of the circle + */ + function Circle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var radius = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + _classCallCheck(this, Circle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.CIRC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.CIRC; + } + + /** + * Creates a clone of this Circle instance + * + * @return {PIXI.Circle} a copy of the Circle + */ + + + Circle.prototype.clone = function clone() { + return new Circle(this.x, this.y, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this circle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Circle + */ + + + Circle.prototype.contains = function contains(x, y) { + if (this.radius <= 0) { + return false; + } + + var r2 = this.radius * this.radius; + var dx = this.x - x; + var dy = this.y - y; + + dx *= dx; + dy *= dy; + + return dx + dy <= r2; + }; + + /** + * Returns the framing rectangle of the circle as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Circle.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + + return Circle; +}(); + +exports.default = Circle; + +},{"../../const":46,"./Rectangle":74}],72:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Rectangle = require('./Rectangle'); + +var _Rectangle2 = _interopRequireDefault(_Rectangle); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Ellipse object can be used to specify a hit area for displayObjects + * + * @class + * @memberof PIXI + */ +var Ellipse = function () { + /** + * @param {number} [x=0] - The X coordinate of the center of this ellipse + * @param {number} [y=0] - The Y coordinate of the center of this ellipse + * @param {number} [halfWidth=0] - The half width of this ellipse + * @param {number} [halfHeight=0] - The half height of this ellipse + */ + function Ellipse() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var halfWidth = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var halfHeight = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Ellipse); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = halfWidth; + + /** + * @member {number} + * @default 0 + */ + this.height = halfHeight; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.ELIP + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.ELIP; + } + + /** + * Creates a clone of this Ellipse instance + * + * @return {PIXI.Ellipse} a copy of the ellipse + */ + + + Ellipse.prototype.clone = function clone() { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coords are within this ellipse + */ + + + Ellipse.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + // normalize the coords to an ellipse with center 0,0 + var normx = (x - this.x) / this.width; + var normy = (y - this.y) / this.height; + + normx *= normx; + normy *= normy; + + return normx + normy <= 1; + }; + + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * + * @return {PIXI.Rectangle} the framing rectangle + */ + + + Ellipse.prototype.getBounds = function getBounds() { + return new _Rectangle2.default(this.x - this.width, this.y - this.height, this.width, this.height); + }; + + return Ellipse; +}(); + +exports.default = Ellipse; + +},{"../../const":46,"./Rectangle":74}],73:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Point = require('../Point'); + +var _Point2 = _interopRequireDefault(_Point); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Polygon = function () { + /** + * @param {PIXI.Point[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + for (var _len = arguments.length, points = Array(_len), _key = 0; _key < _len; _key++) { + points[_key] = arguments[_key]; + } + + _classCallCheck(this, Polygon); + + if (Array.isArray(points[0])) { + points = points[0]; + } + + // if this is an array of points, convert it to a flat array of numbers + if (points[0] instanceof _Point2.default) { + var p = []; + + for (var i = 0, il = points.length; i < il; i++) { + p.push(points[i].x, points[i].y); + } + + points = p; + } + + this.closed = true; + + /** + * An array of the points of this polygon + * + * @member {number[]} + */ + this.points = points; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.POLY + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.POLY; + } + + /** + * Creates a clone of this polygon + * + * @return {PIXI.Polygon} a copy of the polygon + */ + + + Polygon.prototype.clone = function clone() { + return new Polygon(this.points.slice()); + }; + + /** + * Closes the polygon, adding points if necessary. + * + */ + + + Polygon.prototype.close = function close() { + var points = this.points; + + // close the poly if the value is true! + if (points[0] !== points[points.length - 2] || points[1] !== points[points.length - 1]) { + points.push(points[0], points[1]); + } + }; + + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this polygon + */ + + + Polygon.prototype.contains = function contains(x, y) { + var inside = false; + + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + + for (var i = 0, j = length - 1; i < length; j = i++) { + var xi = this.points[i * 2]; + var yi = this.points[i * 2 + 1]; + var xj = this.points[j * 2]; + var yj = this.points[j * 2 + 1]; + var intersect = yi > y !== yj > y && x < (xj - xi) * ((y - yi) / (yj - yi)) + xi; + + if (intersect) { + inside = !inside; + } + } + + return inside; + }; + + return Polygon; +}(); + +exports.default = Polygon; + +},{"../../const":46,"../Point":69}],74:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * + * @class + * @memberof PIXI + */ +var Rectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle + * @param {number} [width=0] - The overall width of this rectangle + * @param {number} [height=0] - The overall height of this rectangle + */ + function Rectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + + _classCallCheck(this, Rectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = Number(x); + + /** + * @member {number} + * @default 0 + */ + this.y = Number(y); + + /** + * @member {number} + * @default 0 + */ + this.width = Number(width); + + /** + * @member {number} + * @default 0 + */ + this.height = Number(height); + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readOnly + * @default PIXI.SHAPES.RECT + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RECT; + } + + /** + * returns the left edge of the rectangle + * + * @member {number} + */ + + + /** + * Creates a clone of this Rectangle + * + * @return {PIXI.Rectangle} a copy of the rectangle + */ + Rectangle.prototype.clone = function clone() { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + + /** + * Copies another rectangle to this one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to copy. + * @return {PIXI.Rectangle} Returns itself. + */ + + + Rectangle.prototype.copy = function copy(rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + + return this; + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rectangle + */ + + + Rectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + + return false; + }; + + /** + * Pads the rectangle making it grow in all directions. + * + * @param {number} paddingX - The horizontal padding amount. + * @param {number} [paddingY] - The vertical padding amount. + */ + + + Rectangle.prototype.pad = function pad(paddingX, paddingY) { + paddingX = paddingX || 0; + paddingY = paddingY || (paddingY !== 0 ? paddingX : 0); + + this.x -= paddingX; + this.y -= paddingY; + + this.width += paddingX * 2; + this.height += paddingY * 2; + }; + + /** + * Fits this rectangle around the passed one. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to fit. + */ + + + Rectangle.prototype.fit = function fit(rectangle) { + var x1 = Math.max(this.x, rectangle.x); + var x2 = Math.min(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.max(this.y, rectangle.y); + var y2 = Math.min(this.y + this.height, rectangle.y + rectangle.height); + + this.x = x1; + this.width = Math.max(x2 - x1, 0); + this.y = y1; + this.height = Math.max(y2 - y1, 0); + }; + + /** + * Enlarges this rectangle to include the passed rectangle. + * + * @param {PIXI.Rectangle} rectangle - The rectangle to include. + */ + + + Rectangle.prototype.enlarge = function enlarge(rectangle) { + var x1 = Math.min(this.x, rectangle.x); + var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.min(this.y, rectangle.y); + var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); + + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + }; + + /** + * Enlarges rectangle that way its corners lie on grid + * + * @param {number} [resolution=1] resolution + * @param {number} [eps=0.001] precision + */ + + + Rectangle.prototype.ceil = function ceil() { + var resolution = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; + var eps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.001; + + var x2 = Math.ceil((this.x + this.width - eps) * resolution) / resolution; + var y2 = Math.ceil((this.y + this.height - eps) * resolution) / resolution; + + this.x = Math.floor((this.x + eps) * resolution) / resolution; + this.y = Math.floor((this.y + eps) * resolution) / resolution; + + this.width = x2 - this.x; + this.height = y2 - this.y; + }; + + _createClass(Rectangle, [{ + key: 'left', + get: function get() { + return this.x; + } + + /** + * returns the right edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'right', + get: function get() { + return this.x + this.width; + } + + /** + * returns the top edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'top', + get: function get() { + return this.y; + } + + /** + * returns the bottom edge of the rectangle + * + * @member {number} + */ + + }, { + key: 'bottom', + get: function get() { + return this.y + this.height; + } + + /** + * A constant empty rectangle. + * + * @static + * @constant + */ + + }], [{ + key: 'EMPTY', + get: function get() { + return new Rectangle(0, 0, 0, 0); + } + }]); + + return Rectangle; +}(); + +exports.default = Rectangle; + +},{"../../const":46}],75:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. + * + * @class + * @memberof PIXI + */ +var RoundedRectangle = function () { + /** + * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle + * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle + * @param {number} [width=0] - The overall width of this rounded rectangle + * @param {number} [height=0] - The overall height of this rounded rectangle + * @param {number} [radius=20] - Controls the radius of the rounded corners + */ + function RoundedRectangle() { + var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + var width = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var height = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var radius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 20; + + _classCallCheck(this, RoundedRectangle); + + /** + * @member {number} + * @default 0 + */ + this.x = x; + + /** + * @member {number} + * @default 0 + */ + this.y = y; + + /** + * @member {number} + * @default 0 + */ + this.width = width; + + /** + * @member {number} + * @default 0 + */ + this.height = height; + + /** + * @member {number} + * @default 20 + */ + this.radius = radius; + + /** + * The type of the object, mainly used to avoid `instanceof` checks + * + * @member {number} + * @readonly + * @default PIXI.SHAPES.RREC + * @see PIXI.SHAPES + */ + this.type = _const.SHAPES.RREC; + } + + /** + * Creates a clone of this Rounded Rectangle + * + * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle + */ + + + RoundedRectangle.prototype.clone = function clone() { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle + */ + + + RoundedRectangle.prototype.contains = function contains(x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + if (y >= this.y + this.radius && y <= this.y + this.height - this.radius || x >= this.x + this.radius && x <= this.x + this.width - this.radius) { + return true; + } + var dx = x - (this.x + this.radius); + var dy = y - (this.y + this.radius); + var radius2 = this.radius * this.radius; + + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.width - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dy = y - (this.y + this.height - this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + dx = x - (this.x + this.radius); + if (dx * dx + dy * dy <= radius2) { + return true; + } + } + } + + return false; + }; + + return RoundedRectangle; +}(); + +exports.default = RoundedRectangle; + +},{"../../const":46}],76:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _utils = require('../utils'); + +var _math = require('../math'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _Container = require('../display/Container'); + +var _Container2 = _interopRequireDefault(_Container); + +var _RenderTexture = require('../textures/RenderTexture'); + +var _RenderTexture2 = _interopRequireDefault(_RenderTexture); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMatrix = new _math.Matrix(); + +/** + * The SystemRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.WebGLRenderer} which can be used for rendering a PixiJS scene. + * + * @abstract + * @class + * @extends EventEmitter + * @memberof PIXI + */ + +var SystemRenderer = function (_EventEmitter) { + _inherits(SystemRenderer, _EventEmitter); + + // eslint-disable-next-line valid-jsdoc + /** + * @param {string} system - The name of the system this renderer is for. + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function SystemRenderer(system, options, arg2, arg3) { + _classCallCheck(this, SystemRenderer); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + (0, _utils.sayHello)(system); + + // Support for constructor(system, screenWidth, screenHeight, options) + if (typeof options === 'number') { + options = Object.assign({ + width: options, + height: arg2 || _settings2.default.RENDER_OPTIONS.height + }, arg3); + } + + // Add the default render options + options = Object.assign({}, _settings2.default.RENDER_OPTIONS, options); + + /** + * The supplied constructor options. + * + * @member {Object} + * @readOnly + */ + _this.options = options; + + /** + * The type of the renderer. + * + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.UNKNOWN; + + /** + * Measurements of the screen. (0, 0, screenWidth, screenHeight) + * + * Its safe to use as filterArea or hitArea for whole stage + * + * @member {PIXI.Rectangle} + */ + _this.screen = new _math.Rectangle(0, 0, options.width, options.height); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.view = options.view || document.createElement('canvas'); + + /** + * The resolution / device pixel ratio of the renderer + * + * @member {number} + * @default 1 + */ + _this.resolution = options.resolution || _settings2.default.RESOLUTION; + + /** + * Whether the render view is transparent + * + * @member {boolean} + */ + _this.transparent = options.transparent; + + /** + * Whether css dimensions of canvas view should be resized to screen dimensions automatically + * + * @member {boolean} + */ + _this.autoResize = options.autoResize || false; + + /** + * Tracks the blend modes useful for this renderer. + * + * @member {object} + */ + _this.blendModes = null; + + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example if + * your game has a canvas filling background image you often don't need this set. + * + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Handy for crisp pixel art and speed on legacy devices. + * + * @member {boolean} + */ + _this.roundPixels = options.roundPixels; + + /** + * The background color as a number. + * + * @member {number} + * @private + */ + _this._backgroundColor = 0x000000; + + /** + * The background color as an [R, G, B] array. + * + * @member {number[]} + * @private + */ + _this._backgroundColorRgba = [0, 0, 0, 0]; + + /** + * The background color as a string. + * + * @member {string} + * @private + */ + _this._backgroundColorString = '#000000'; + + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + + /** + * This temporary display object used as the parent of the currently being rendered item + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._tempDisplayObjectParent = new _Container2.default(); + + /** + * The last root object that the renderer tried to render. + * + * @member {PIXI.DisplayObject} + * @private + */ + _this._lastObjectRendered = _this._tempDisplayObjectParent; + return _this; + } + + /** + * Same as view.width, actual number of pixels in the canvas by horizontal + * + * @member {number} + * @readonly + * @default 800 + */ + + + /** + * Resizes the screen and canvas to the specified width and height + * Canvas dimensions are multiplied by resolution + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + SystemRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + this.screen.width = screenWidth; + this.screen.height = screenHeight; + + this.view.width = screenWidth * this.resolution; + this.view.height = screenHeight * this.resolution; + + if (this.autoResize) { + this.view.style.width = screenWidth + 'px'; + this.view.style.height = screenHeight + 'px'; + } + }; + + /** + * Useful function that returns a texture of the display object that can then be used to create sprites + * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. + * + * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from + * @param {number} scaleMode - Should be one of the scaleMode consts + * @param {number} resolution - The resolution / device pixel ratio of the texture being generated + * @param {PIXI.Rectangle} [region] - The region of the displayObject, that shall be rendered, + * if no region is specified, defaults to the local bounds of the displayObject. + * @return {PIXI.Texture} a texture of the graphics object + */ + + + SystemRenderer.prototype.generateTexture = function generateTexture(displayObject, scaleMode, resolution, region) { + region = region || displayObject.getLocalBounds(); + + var renderTexture = _RenderTexture2.default.create(region.width | 0, region.height | 0, scaleMode, resolution); + + tempMatrix.tx = -region.x; + tempMatrix.ty = -region.y; + + this.render(displayObject, renderTexture, false, tempMatrix, !!displayObject.parent); + + return renderTexture; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + SystemRenderer.prototype.destroy = function destroy(removeView) { + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } + + this.type = _const.RENDERER_TYPE.UNKNOWN; + + this.view = null; + + this.screen = null; + + this.resolution = 0; + + this.transparent = false; + + this.autoResize = false; + + this.blendModes = null; + + this.options = null; + + this.preserveDrawingBuffer = false; + this.clearBeforeRender = false; + + this.roundPixels = false; + + this._backgroundColor = 0; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + + this._tempDisplayObjectParent = null; + this._lastObjectRendered = null; + }; + + /** + * The background color to fill if not transparent + * + * @member {number} + */ + + + _createClass(SystemRenderer, [{ + key: 'width', + get: function get() { + return this.view.width; + } + + /** + * Same as view.height, actual number of pixels in the canvas by vertical + * + * @member {number} + * @readonly + * @default 600 + */ + + }, { + key: 'height', + get: function get() { + return this.view.height; + } + }, { + key: 'backgroundColor', + get: function get() { + return this._backgroundColor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._backgroundColor = value; + this._backgroundColorString = (0, _utils.hex2string)(value); + (0, _utils.hex2rgb)(value, this._backgroundColorRgba); + } + }]); + + return SystemRenderer; +}(_eventemitter2.default); + +exports.default = SystemRenderer; + +},{"../const":46,"../display/Container":48,"../math":70,"../settings":101,"../textures/RenderTexture":113,"../utils":125,"eventemitter3":3}],77:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _CanvasMaskManager = require('./utils/CanvasMaskManager'); + +var _CanvasMaskManager2 = _interopRequireDefault(_CanvasMaskManager); + +var _CanvasRenderTarget = require('./utils/CanvasRenderTarget'); + +var _CanvasRenderTarget2 = _interopRequireDefault(_CanvasRenderTarget); + +var _mapCanvasBlendModesToPixi = require('./utils/mapCanvasBlendModesToPixi'); + +var _mapCanvasBlendModesToPixi2 = _interopRequireDefault(_mapCanvasBlendModesToPixi); + +var _utils = require('../../utils'); + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The CanvasRenderer draws the scene and all its content onto a 2d canvas. This renderer should + * be used for browsers that do not support WebGL. Don't forget to add the CanvasRenderer.view to + * your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ +var CanvasRenderer = function (_SystemRenderer) { + _inherits(CanvasRenderer, _SystemRenderer); + + // eslint-disable-next-line valid-jsdoc + /** + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The + * resolution of the renderer retina would be 2. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when rendering, + * stopping pixel interpolation. + */ + function CanvasRenderer(options, arg2, arg3) { + _classCallCheck(this, CanvasRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'Canvas', options, arg2, arg3)); + + _this.type = _const.RENDERER_TYPE.CANVAS; + + /** + * The root canvas 2d context that everything is drawn with. + * + * @member {CanvasRenderingContext2D} + */ + _this.rootContext = _this.view.getContext('2d', { alpha: _this.transparent }); + + /** + * The currently active canvas 2d context (could change with renderTextures) + * + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.rootContext; + + /** + * Boolean flag controlling canvas refresh. + * + * @member {boolean} + */ + _this.refresh = true; + + /** + * Instance of a CanvasMaskManager, handles masking when using the canvas renderer. + * + * @member {PIXI.CanvasMaskManager} + */ + _this.maskManager = new _CanvasMaskManager2.default(_this); + + /** + * The canvas property used to set the canvas smoothing property. + * + * @member {string} + */ + _this.smoothProperty = 'imageSmoothingEnabled'; + + if (!_this.rootContext.imageSmoothingEnabled) { + if (_this.rootContext.webkitImageSmoothingEnabled) { + _this.smoothProperty = 'webkitImageSmoothingEnabled'; + } else if (_this.rootContext.mozImageSmoothingEnabled) { + _this.smoothProperty = 'mozImageSmoothingEnabled'; + } else if (_this.rootContext.oImageSmoothingEnabled) { + _this.smoothProperty = 'oImageSmoothingEnabled'; + } else if (_this.rootContext.msImageSmoothingEnabled) { + _this.smoothProperty = 'msImageSmoothingEnabled'; + } + } + + _this.initPlugins(); + + _this.blendModes = (0, _mapCanvasBlendModesToPixi2.default)(); + _this._activeBlendMode = null; + + _this.renderingToScreen = false; + + _this.resize(_this.options.width, _this.options.height); + + /** + * Fired after rendering finishes. + * + * @event PIXI.CanvasRenderer#postrender + */ + + /** + * Fired before rendering starts. + * + * @event PIXI.CanvasRenderer#prerender + */ + return _this; + } + + /** + * Renders the object to this canvas view + * + * @param {PIXI.DisplayObject} displayObject - The object to be rendered + * @param {PIXI.RenderTexture} [renderTexture] - A render texture to be rendered to. + * If unset, it will render to the root context. + * @param {boolean} [clear=false] - Whether to clear the canvas before drawing + * @param {PIXI.Matrix} [transform] - A transformation to be applied + * @param {boolean} [skipUpdateTransform=false] - Whether to skip the update transform + */ + + + CanvasRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + if (!this.view) { + return; + } + + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + var rootResolution = this.resolution; + + if (renderTexture) { + renderTexture = renderTexture.baseTexture || renderTexture; + + if (!renderTexture._canvasRenderTarget) { + renderTexture._canvasRenderTarget = new _CanvasRenderTarget2.default(renderTexture.width, renderTexture.height, renderTexture.resolution); + renderTexture.source = renderTexture._canvasRenderTarget.canvas; + renderTexture.valid = true; + } + + this.context = renderTexture._canvasRenderTarget.context; + this.resolution = renderTexture._canvasRenderTarget.resolution; + } else { + this.context = this.rootContext; + } + + var context = this.context; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + var tempWt = this._tempDisplayObjectParent.transform.worldTransform; + + if (transform) { + transform.copy(tempWt); + + // lets not forget to flag the parent transform as dirty... + this._tempDisplayObjectParent.transform._worldID = -1; + } else { + tempWt.identity(); + } + + displayObject.parent = this._tempDisplayObjectParent; + + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + context.save(); + context.setTransform(1, 0, 0, 1, 0, 0); + context.globalAlpha = 1; + this._activeBlendMode = _const.BLEND_MODES.NORMAL; + context.globalCompositeOperation = this.blendModes[_const.BLEND_MODES.NORMAL]; + + if (navigator.isCocoonJS && this.view.screencanvas) { + context.fillStyle = 'black'; + context.clear(); + } + + if (clear !== undefined ? clear : this.clearBeforeRender) { + if (this.renderingToScreen) { + if (this.transparent) { + context.clearRect(0, 0, this.width, this.height); + } else { + context.fillStyle = this._backgroundColorString; + context.fillRect(0, 0, this.width, this.height); + } + } // else { + // TODO: implement background for CanvasRenderTarget or RenderTexture? + // } + } + + // TODO RENDER TARGET STUFF HERE.. + var tempContext = this.context; + + this.context = context; + displayObject.renderCanvas(this); + this.context = tempContext; + + context.restore(); + + this.resolution = rootResolution; + + this.emit('postrender'); + }; + + /** + * Clear the canvas of renderer. + * + * @param {string} [clearColor] - Clear the canvas with this color, except the canvas is transparent. + */ + + + CanvasRenderer.prototype.clear = function clear(clearColor) { + var context = this.context; + + clearColor = clearColor || this._backgroundColorString; + + if (!this.transparent && clearColor) { + context.fillStyle = clearColor; + context.fillRect(0, 0, this.width, this.height); + } else { + context.clearRect(0, 0, this.width, this.height); + } + }; + + /** + * Sets the blend mode of the renderer. + * + * @param {number} blendMode - See {@link PIXI.BLEND_MODES} for valid values. + */ + + + CanvasRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + if (this._activeBlendMode === blendMode) { + return; + } + + this._activeBlendMode = blendMode; + this.context.globalCompositeOperation = this.blendModes[blendMode]; + }; + + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + */ + + + CanvasRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // call the base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.context = null; + + this.refresh = true; + + this.maskManager.destroy(); + this.maskManager = null; + + this.smoothProperty = null; + }; + + /** + * Resizes the canvas view to the specified width and height. + * + * @extends PIXI.SystemRenderer#resize + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + CanvasRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + _SystemRenderer.prototype.resize.call(this, screenWidth, screenHeight); + + // reset the scale mode.. oddly this seems to be reset when the canvas is resized. + // surely a browser bug?? Let PixiJS fix that for you.. + if (this.smoothProperty) { + this.rootContext[this.smoothProperty] = _settings2.default.SCALE_MODE === _const.SCALE_MODES.LINEAR; + } + }; + + /** + * Checks if blend mode has changed. + */ + + + CanvasRenderer.prototype.invalidateBlendMode = function invalidateBlendMode() { + this._activeBlendMode = this.blendModes.indexOf(this.context.globalCompositeOperation); + }; + + return CanvasRenderer; +}(_SystemRenderer3.default); + +/** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @name PIXI.CanvasRenderer#plugins + * @type {object} + * @readonly + * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.extract.CanvasExtract} extract Extract image data from renderer. + * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.prepare.CanvasPrepare} prepare Pre-render display objects. + */ + +/** + * Adds a plugin to the renderer. + * + * @method PIXI.CanvasRenderer#registerPlugin + * @param {string} pluginName - The name of the plugin. + * @param {Function} ctor - The constructor function or class for the plugin. + */ + +exports.default = CanvasRenderer; +_utils.pluginTarget.mixin(CanvasRenderer); + +},{"../../const":46,"../../settings":101,"../../utils":125,"../SystemRenderer":76,"./utils/CanvasMaskManager":78,"./utils/CanvasRenderTarget":79,"./utils/mapCanvasBlendModesToPixi":81}],78:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../../const'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A set of functions used to handle masking. + * + * @class + * @memberof PIXI + */ +var CanvasMaskManager = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + function CanvasMaskManager(renderer) { + _classCallCheck(this, CanvasMaskManager); + + this.renderer = renderer; + } + + /** + * This method adds it to the current stack of masks. + * + * @param {object} maskData - the maskData that will be pushed + */ + + + CanvasMaskManager.prototype.pushMask = function pushMask(maskData) { + var renderer = this.renderer; + + renderer.context.save(); + + var cacheAlpha = maskData.alpha; + var transform = maskData.transform.worldTransform; + var resolution = renderer.resolution; + + renderer.context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + // TODO suport sprite alpha masks?? + // lots of effort required. If demand is great enough.. + if (!maskData._texture) { + this.renderGraphicsShape(maskData); + renderer.context.clip(); + } + + maskData.worldAlpha = cacheAlpha; + }; + + /** + * Renders a PIXI.Graphics shape. + * + * @param {PIXI.Graphics} graphics - The object to render. + */ + + + CanvasMaskManager.prototype.renderGraphicsShape = function renderGraphicsShape(graphics) { + var context = this.renderer.context; + var len = graphics.graphicsData.length; + + if (len === 0) { + return; + } + + context.beginPath(); + + for (var i = 0; i < len; i++) { + var data = graphics.graphicsData[i]; + var shape = data.shape; + + if (data.type === _const.SHAPES.POLY) { + var points = shape.points; + var holes = data.holes; + var outerArea = void 0; + var innerArea = void 0; + + context.moveTo(points[0], points[1]); + + for (var j = 2; j < points.length; j += 2) { + context.lineTo(points[j], points[j + 1]); + } + + // if the first and last point are the same close the path - much neater :) + if (points[0] === points[points.length - 2] && points[1] === points[points.length - 1]) { + context.closePath(); + } + + if (holes.length > 0) { + outerArea = 0; + for (var _j = 0; _j < points.length; _j += 2) { + outerArea += points[_j] * points[_j + 3] - points[_j + 1] * points[_j + 2]; + } + + for (var k = 0; k < holes.length; k++) { + points = holes[k].points; + + innerArea = 0; + for (var _j2 = 0; _j2 < points.length; _j2 += 2) { + innerArea += points[_j2] * points[_j2 + 3] - points[_j2 + 1] * points[_j2 + 2]; + } + + context.moveTo(points[0], points[1]); + + if (innerArea * outerArea < 0) { + for (var _j3 = 2; _j3 < points.length; _j3 += 2) { + context.lineTo(points[_j3], points[_j3 + 1]); + } + } else { + for (var _j4 = points.length - 2; _j4 >= 2; _j4 -= 2) { + context.lineTo(points[_j4], points[_j4 + 1]); + } + } + } + } + } else if (data.type === _const.SHAPES.RECT) { + context.rect(shape.x, shape.y, shape.width, shape.height); + context.closePath(); + } else if (data.type === _const.SHAPES.CIRC) { + // TODO - need to be Undefined! + context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI); + context.closePath(); + } else if (data.type === _const.SHAPES.ELIP) { + // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas + + var w = shape.width * 2; + var h = shape.height * 2; + + var x = shape.x - w / 2; + var y = shape.y - h / 2; + + var kappa = 0.5522848; + var ox = w / 2 * kappa; // control point offset horizontal + var oy = h / 2 * kappa; // control point offset vertical + var xe = x + w; // x-end + var ye = y + h; // y-end + var xm = x + w / 2; // x-middle + var ym = y + h / 2; // y-middle + + context.moveTo(x, ym); + context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); + context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); + context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); + context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); + context.closePath(); + } else if (data.type === _const.SHAPES.RREC) { + var rx = shape.x; + var ry = shape.y; + var width = shape.width; + var height = shape.height; + var radius = shape.radius; + + var maxRadius = Math.min(width, height) / 2 | 0; + + radius = radius > maxRadius ? maxRadius : radius; + + context.moveTo(rx, ry + radius); + context.lineTo(rx, ry + height - radius); + context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height); + context.lineTo(rx + width - radius, ry + height); + context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius); + context.lineTo(rx + width, ry + radius); + context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry); + context.lineTo(rx + radius, ry); + context.quadraticCurveTo(rx, ry, rx, ry + radius); + context.closePath(); + } + } + }; + + /** + * Restores the current drawing context to the state it was before the mask was applied. + * + * @param {PIXI.CanvasRenderer} renderer - The renderer context to use. + */ + + + CanvasMaskManager.prototype.popMask = function popMask(renderer) { + renderer.context.restore(); + renderer.invalidateBlendMode(); + }; + + /** + * Destroys this canvas mask manager. + * + */ + + + CanvasMaskManager.prototype.destroy = function destroy() { + /* empty */ + }; + + return CanvasMaskManager; +}(); + +exports.default = CanvasMaskManager; + +},{"../../../const":46}],79:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Creates a Canvas element of the given size. + * + * @class + * @memberof PIXI + */ +var CanvasRenderTarget = function () { + /** + * @param {number} width - the width for the newly created canvas + * @param {number} height - the height for the newly created canvas + * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + _classCallCheck(this, CanvasRenderTarget); + + /** + * The Canvas object that belongs to this CanvasRenderTarget. + * + * @member {HTMLCanvasElement} + */ + this.canvas = document.createElement('canvas'); + + /** + * A CanvasRenderingContext2D object representing a two-dimensional rendering context. + * + * @member {CanvasRenderingContext2D} + */ + this.context = this.canvas.getContext('2d'); + + this.resolution = resolution || _settings2.default.RESOLUTION; + + this.resize(width, height); + } + + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * + * @private + */ + + + CanvasRenderTarget.prototype.clear = function clear() { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + + /** + * Resizes the canvas to the specified width and height. + * + * @param {number} width - the new width of the canvas + * @param {number} height - the new height of the canvas + */ + + + CanvasRenderTarget.prototype.resize = function resize(width, height) { + this.canvas.width = width * this.resolution; + this.canvas.height = height * this.resolution; + }; + + /** + * Destroys this canvas. + * + */ + + + CanvasRenderTarget.prototype.destroy = function destroy() { + this.context = null; + this.canvas = null; + }; + + /** + * The width of the canvas buffer in pixels. + * + * @member {number} + */ + + + _createClass(CanvasRenderTarget, [{ + key: 'width', + get: function get() { + return this.canvas.width; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.width = val; + } + + /** + * The height of the canvas buffer in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.canvas.height; + }, + set: function set(val) // eslint-disable-line require-jsdoc + { + this.canvas.height = val; + } + }]); + + return CanvasRenderTarget; +}(); + +exports.default = CanvasRenderTarget; + +},{"../../../settings":101}],80:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = canUseNewCanvasBlendModes; +/** + * Creates a little colored canvas + * + * @ignore + * @param {string} color - The color to make the canvas + * @return {canvas} a small canvas element + */ +function createColoredCanvas(color) { + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.fillStyle = color; + context.fillRect(0, 0, 6, 1); + + return canvas; +} + +/** + * Checks whether the Canvas BlendModes are supported by the current browser + * + * @return {boolean} whether they are supported + */ +function canUseNewCanvasBlendModes() { + if (typeof document === 'undefined') { + return false; + } + + var magenta = createColoredCanvas('#ff00ff'); + var yellow = createColoredCanvas('#ffff00'); + + var canvas = document.createElement('canvas'); + + canvas.width = 6; + canvas.height = 1; + + var context = canvas.getContext('2d'); + + context.globalCompositeOperation = 'multiply'; + context.drawImage(magenta, 0, 0); + context.drawImage(yellow, 2, 0); + + var imageData = context.getImageData(2, 0, 1, 1); + + if (!imageData) { + return false; + } + + var data = imageData.data; + + return data[0] === 255 && data[1] === 0 && data[2] === 0; +} + +},{}],81:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapCanvasBlendModesToPixi; + +var _const = require('../../../const'); + +var _canUseNewCanvasBlendModes = require('./canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Maps blend combinations to Canvas. + * + * @memberof PIXI + * @function mapCanvasBlendModesToPixi + * @private + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapCanvasBlendModesToPixi() { + var array = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + + if ((0, _canUseNewCanvasBlendModes2.default)()) { + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'multiply'; + array[_const.BLEND_MODES.SCREEN] = 'screen'; + array[_const.BLEND_MODES.OVERLAY] = 'overlay'; + array[_const.BLEND_MODES.DARKEN] = 'darken'; + array[_const.BLEND_MODES.LIGHTEN] = 'lighten'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'color-dodge'; + array[_const.BLEND_MODES.COLOR_BURN] = 'color-burn'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'hard-light'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'soft-light'; + array[_const.BLEND_MODES.DIFFERENCE] = 'difference'; + array[_const.BLEND_MODES.EXCLUSION] = 'exclusion'; + array[_const.BLEND_MODES.HUE] = 'hue'; + array[_const.BLEND_MODES.SATURATION] = 'saturate'; + array[_const.BLEND_MODES.COLOR] = 'color'; + array[_const.BLEND_MODES.LUMINOSITY] = 'luminosity'; + } else { + // this means that the browser does not support the cool new blend modes in canvas 'cough' ie 'cough' + array[_const.BLEND_MODES.NORMAL] = 'source-over'; + array[_const.BLEND_MODES.ADD] = 'lighter'; // IS THIS OK??? + array[_const.BLEND_MODES.MULTIPLY] = 'source-over'; + array[_const.BLEND_MODES.SCREEN] = 'source-over'; + array[_const.BLEND_MODES.OVERLAY] = 'source-over'; + array[_const.BLEND_MODES.DARKEN] = 'source-over'; + array[_const.BLEND_MODES.LIGHTEN] = 'source-over'; + array[_const.BLEND_MODES.COLOR_DODGE] = 'source-over'; + array[_const.BLEND_MODES.COLOR_BURN] = 'source-over'; + array[_const.BLEND_MODES.HARD_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.SOFT_LIGHT] = 'source-over'; + array[_const.BLEND_MODES.DIFFERENCE] = 'source-over'; + array[_const.BLEND_MODES.EXCLUSION] = 'source-over'; + array[_const.BLEND_MODES.HUE] = 'source-over'; + array[_const.BLEND_MODES.SATURATION] = 'source-over'; + array[_const.BLEND_MODES.COLOR] = 'source-over'; + array[_const.BLEND_MODES.LUMINOSITY] = 'source-over'; + } + // not-premultiplied, only for webgl + array[_const.BLEND_MODES.NORMAL_NPM] = array[_const.BLEND_MODES.NORMAL]; + array[_const.BLEND_MODES.ADD_NPM] = array[_const.BLEND_MODES.ADD]; + array[_const.BLEND_MODES.SCREEN_NPM] = array[_const.BLEND_MODES.SCREEN]; + + return array; +} + +},{"../../../const":46,"./canUseNewCanvasBlendModes":80}],82:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _const = require('../../const'); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TextureGarbageCollector. This class manages the GPU and ensures that it does not get clogged + * up with textures that are no longer being used. + * + * @class + * @memberof PIXI + */ +var TextureGarbageCollector = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function TextureGarbageCollector(renderer) { + _classCallCheck(this, TextureGarbageCollector); + + this.renderer = renderer; + + this.count = 0; + this.checkCount = 0; + this.maxIdle = _settings2.default.GC_MAX_IDLE; + this.checkCountMax = _settings2.default.GC_MAX_CHECK_COUNT; + this.mode = _settings2.default.GC_MODE; + } + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.update = function update() { + this.count++; + + if (this.mode === _const.GC_MODES.MANUAL) { + return; + } + + this.checkCount++; + + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + + this.run(); + } + }; + + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + + + TextureGarbageCollector.prototype.run = function run() { + var tm = this.renderer.textureManager; + var managedTextures = tm._managedTextures; + var wasRemoved = false; + + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + + // only supports non generated textures at the moment! + if (!texture._glRenderTargets && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + + if (wasRemoved) { + var j = 0; + + for (var _i = 0; _i < managedTextures.length; _i++) { + if (managedTextures[_i] !== null) { + managedTextures[j++] = managedTextures[_i]; + } + } + + managedTextures.length = j; + } + }; + + /** + * Removes all the textures within the specified displayObject and its children from the GPU + * + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + */ + + + TextureGarbageCollector.prototype.unload = function unload(displayObject) { + var tm = this.renderer.textureManager; + + // only destroy non generated textures + if (displayObject._texture && displayObject._texture._glRenderTargets) { + tm.destroyTexture(displayObject._texture, true); + } + + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + + return TextureGarbageCollector; +}(); + +exports.default = TextureGarbageCollector; + +},{"../../const":46,"../../settings":101}],83:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _const = require('../../const'); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _utils = require('../../utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a webGL Texture + * + * @class + * @memberof PIXI + */ +var TextureManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function TextureManager(renderer) { + _classCallCheck(this, TextureManager); + + /** + * A reference to the current renderer + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = renderer.gl; + + /** + * Track textures in the renderer so we can no longer listen to them on destruction. + * + * @member {Array<*>} + * @private + */ + this._managedTextures = []; + } + + /** + * Binds a texture. + * + */ + + + TextureManager.prototype.bindTexture = function bindTexture() {} + // empty + + + /** + * Gets a texture. + * + */ + ; + + TextureManager.prototype.getTexture = function getTexture() {} + // empty + + + /** + * Updates and/or Creates a WebGL texture for the renderer's context. + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to update + * @param {number} location - the location the texture will be bound to. + * @return {GLTexture} The gl texture. + */ + ; + + TextureManager.prototype.updateTexture = function updateTexture(texture, location) { + // assume it good! + // texture = texture.baseTexture || texture; + + var gl = this.gl; + + var isRenderTexture = !!texture._glRenderTargets; + + if (!texture.hasLoaded) { + return null; + } + + var boundTextures = this.renderer.boundTextures; + + // if the location is undefined then this may have been called by n event. + // this being the case the texture may already be bound to a slot. As a texture can only be bound once + // we need to find its current location if it exists. + if (location === undefined) { + location = 0; + + // TODO maybe we can use texture bound ids later on... + // check if texture is already bound.. + for (var i = 0; i < boundTextures.length; ++i) { + if (boundTextures[i] === texture) { + location = i; + break; + } + } + } + + boundTextures[location] = texture; + + gl.activeTexture(gl.TEXTURE0 + location); + + var glTexture = texture._glTextures[this.renderer.CONTEXT_UID]; + + if (!glTexture) { + if (isRenderTexture) { + var renderTarget = new _RenderTarget2.default(this.gl, texture.width, texture.height, texture.scaleMode, texture.resolution); + + renderTarget.resize(texture.width, texture.height); + texture._glRenderTargets[this.renderer.CONTEXT_UID] = renderTarget; + glTexture = renderTarget.texture; + + // framebuffer constructor disactivates current framebuffer + if (!this.renderer._activeRenderTarget.root) { + this.renderer._activeRenderTarget.frameBuffer.bind(); + } + } else { + glTexture = new _pixiGlCore.GLTexture(this.gl, null, null, null, null); + glTexture.bind(location); + glTexture.premultiplyAlpha = true; + glTexture.upload(texture.source); + } + + texture._glTextures[this.renderer.CONTEXT_UID] = glTexture; + + texture.on('update', this.updateTexture, this); + texture.on('dispose', this.destroyTexture, this); + + this._managedTextures.push(texture); + + if (texture.isPowerOfTwo) { + if (texture.mipmap) { + glTexture.enableMipmap(); + } + + if (texture.wrapMode === _const.WRAP_MODES.CLAMP) { + glTexture.enableWrapClamp(); + } else if (texture.wrapMode === _const.WRAP_MODES.REPEAT) { + glTexture.enableWrapRepeat(); + } else { + glTexture.enableWrapMirrorRepeat(); + } + } else { + glTexture.enableWrapClamp(); + } + + if (texture.scaleMode === _const.SCALE_MODES.NEAREST) { + glTexture.enableNearestScaling(); + } else { + glTexture.enableLinearScaling(); + } + } + // the texture already exists so we only need to update it.. + else if (isRenderTexture) { + texture._glRenderTargets[this.renderer.CONTEXT_UID].resize(texture.width, texture.height); + } else { + glTexture.upload(texture.source); + } + + return glTexture; + }; + + /** + * Deletes the texture from WebGL + * + * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy + * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. + */ + + + TextureManager.prototype.destroyTexture = function destroyTexture(texture, skipRemove) { + texture = texture.baseTexture || texture; + + if (!texture.hasLoaded) { + return; + } + + var renderer = this.renderer; + var uid = renderer.CONTEXT_UID; + var glTextures = texture._glTextures; + var glRenderTargets = texture._glRenderTargets; + + if (glTextures[uid]) { + renderer.unbindTexture(texture); + + glTextures[uid].destroy(); + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + + delete glTextures[uid]; + + if (!skipRemove) { + var i = this._managedTextures.indexOf(texture); + + if (i !== -1) { + (0, _utils.removeItems)(this._managedTextures, i, 1); + } + } + } + + if (glRenderTargets && glRenderTargets[uid]) { + if (renderer._activeRenderTarget === glRenderTargets[uid]) { + renderer.bindRenderTarget(renderer.rootRenderTarget); + } + + glRenderTargets[uid].destroy(); + delete glRenderTargets[uid]; + } + }; + + /** + * Deletes all the textures from WebGL + */ + + + TextureManager.prototype.removeAll = function removeAll() { + // empty all the old gl textures as they are useless now + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + if (texture._glTextures[this.renderer.CONTEXT_UID]) { + delete texture._glTextures[this.renderer.CONTEXT_UID]; + } + } + }; + + /** + * Destroys this manager and removes all its textures + */ + + + TextureManager.prototype.destroy = function destroy() { + // destroy managed textures + for (var i = 0; i < this._managedTextures.length; ++i) { + var texture = this._managedTextures[i]; + + this.destroyTexture(texture, true); + + texture.off('update', this.updateTexture, this); + texture.off('dispose', this.destroyTexture, this); + } + + this._managedTextures = null; + }; + + return TextureManager; +}(); + +exports.default = TextureManager; + +},{"../../const":46,"../../utils":125,"./utils/RenderTarget":96,"pixi-gl-core":15}],84:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _SystemRenderer2 = require('../SystemRenderer'); + +var _SystemRenderer3 = _interopRequireDefault(_SystemRenderer2); + +var _MaskManager = require('./managers/MaskManager'); + +var _MaskManager2 = _interopRequireDefault(_MaskManager); + +var _StencilManager = require('./managers/StencilManager'); + +var _StencilManager2 = _interopRequireDefault(_StencilManager); + +var _FilterManager = require('./managers/FilterManager'); + +var _FilterManager2 = _interopRequireDefault(_FilterManager); + +var _RenderTarget = require('./utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _ObjectRenderer = require('./utils/ObjectRenderer'); + +var _ObjectRenderer2 = _interopRequireDefault(_ObjectRenderer); + +var _TextureManager = require('./TextureManager'); + +var _TextureManager2 = _interopRequireDefault(_TextureManager); + +var _BaseTexture = require('../../textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _TextureGarbageCollector = require('./TextureGarbageCollector'); + +var _TextureGarbageCollector2 = _interopRequireDefault(_TextureGarbageCollector); + +var _WebGLState = require('./WebGLState'); + +var _WebGLState2 = _interopRequireDefault(_WebGLState); + +var _mapWebGLDrawModesToPixi = require('./utils/mapWebGLDrawModesToPixi'); + +var _mapWebGLDrawModesToPixi2 = _interopRequireDefault(_mapWebGLDrawModesToPixi); + +var _validateContext = require('./utils/validateContext'); + +var _validateContext2 = _interopRequireDefault(_validateContext); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _const = require('../../const'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CONTEXT_UID = 0; + +/** + * The WebGLRenderer draws the scene and all its content onto a webGL enabled canvas. This renderer + * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs. + * So no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything :) + * + * @class + * @memberof PIXI + * @extends PIXI.SystemRenderer + */ + +var WebGLRenderer = function (_SystemRenderer) { + _inherits(WebGLRenderer, _SystemRenderer); + + // eslint-disable-next-line valid-jsdoc + /** + * + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the screen + * @param {number} [options.height=600] - the height of the screen + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.transparent=false] - If the render view is transparent, default false + * @param {boolean} [options.autoResize=false] - If the render view is automatically resized, default false + * @param {boolean} [options.antialias=false] - sets antialias. If not available natively then FXAA + * antialiasing is used + * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native. + * FXAA is faster, but may not always look as great + * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. + * The resolution of the renderer retina would be 2. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear + * the canvas or not before the new render pass. If you wish to set this to false, you *must* set + * preserveDrawingBuffer to `true`. + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the webgl context. + * @param {boolean} [options.roundPixels=false] - If true PixiJS will Math.floor() x/y values when + * rendering, stopping pixel interpolation. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {boolean} [options.legacy=false] - If true PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering try setting this to true. + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card + */ + function WebGLRenderer(options, arg2, arg3) { + _classCallCheck(this, WebGLRenderer); + + var _this = _possibleConstructorReturn(this, _SystemRenderer.call(this, 'WebGL', options, arg2, arg3)); + + _this.legacy = _this.options.legacy; + + if (_this.legacy) { + _pixiGlCore2.default.VertexArrayObject.FORCE_NATIVE = true; + } + + /** + * The type of this renderer as a standardised const + * + * @member {number} + * @see PIXI.RENDERER_TYPE + */ + _this.type = _const.RENDERER_TYPE.WEBGL; + + _this.handleContextLost = _this.handleContextLost.bind(_this); + _this.handleContextRestored = _this.handleContextRestored.bind(_this); + + _this.view.addEventListener('webglcontextlost', _this.handleContextLost, false); + _this.view.addEventListener('webglcontextrestored', _this.handleContextRestored, false); + + /** + * The options passed in to create a new webgl context. + * + * @member {object} + * @private + */ + _this._contextOptions = { + alpha: _this.transparent, + antialias: _this.options.antialias, + premultipliedAlpha: _this.transparent && _this.transparent !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: _this.options.preserveDrawingBuffer, + powerPreference: _this.options.powerPreference + }; + + _this._backgroundColorRgba[3] = _this.transparent ? 0 : 1; + + /** + * Manages the masks using the stencil buffer. + * + * @member {PIXI.MaskManager} + */ + _this.maskManager = new _MaskManager2.default(_this); + + /** + * Manages the stencil buffer. + * + * @member {PIXI.StencilManager} + */ + _this.stencilManager = new _StencilManager2.default(_this); + + /** + * An empty renderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.emptyRenderer = new _ObjectRenderer2.default(_this); + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.ObjectRenderer} + */ + _this.currentRenderer = _this.emptyRenderer; + + /** + * Manages textures + * @member {PIXI.TextureManager} + */ + _this.textureManager = null; + + /** + * Manages the filters. + * + * @member {PIXI.FilterManager} + */ + _this.filterManager = null; + + _this.initPlugins(); + + /** + * The current WebGL rendering context, it is created here + * + * @member {WebGLRenderingContext} + */ + // initialize the context so it is ready for the managers. + if (_this.options.context) { + // checks to see if a context is valid.. + (0, _validateContext2.default)(_this.options.context); + } + + _this.gl = _this.options.context || _pixiGlCore2.default.createContext(_this.view, _this._contextOptions); + + _this.CONTEXT_UID = CONTEXT_UID++; + + /** + * The currently active ObjectRenderer. + * + * @member {PIXI.WebGLState} + */ + _this.state = new _WebGLState2.default(_this.gl); + + _this.renderingToScreen = true; + + /** + * Holds the current state of textures bound to the GPU. + * @type {Array} + */ + _this.boundTextures = null; + + /** + * Holds the current shader + * + * @member {PIXI.Shader} + */ + _this._activeShader = null; + + _this._activeVao = null; + + /** + * Holds the current render target + * + * @member {PIXI.RenderTarget} + */ + _this._activeRenderTarget = null; + + _this._initContext(); + + // map some webGL blend and drawmodes.. + _this.drawModes = (0, _mapWebGLDrawModesToPixi2.default)(_this.gl); + + _this._nextTextureLocation = 0; + + _this.setBlendMode(0); + + /** + * Fired after rendering finishes. + * + * @event PIXI.WebGLRenderer#postrender + */ + + /** + * Fired before rendering starts. + * + * @event PIXI.WebGLRenderer#prerender + */ + + /** + * Fired when the WebGL context is set. + * + * @event PIXI.WebGLRenderer#context + * @param {WebGLRenderingContext} gl - WebGL context. + */ + return _this; + } + + /** + * Creates the WebGL context + * + * @private + */ + + + WebGLRenderer.prototype._initContext = function _initContext() { + var gl = this.gl; + + // restore a context if it was previously lost + if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').restoreContext(); + } + + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + + this._activeShader = null; + this._activeVao = null; + + this.boundTextures = new Array(maxTextures); + this.emptyTextures = new Array(maxTextures); + + /** + * Did someone temper with textures state? We'll overwrite them when we need to unbind something. + * @member {boolean} + * @private + */ + this._unknownBoundTextures = false; + + // create a texture manager... + this.textureManager = new _TextureManager2.default(this); + this.filterManager = new _FilterManager2.default(this); + this.textureGC = new _TextureGarbageCollector2.default(this); + + this.state.resetToDefault(); + + this.rootRenderTarget = new _RenderTarget2.default(gl, this.width, this.height, null, this.resolution, true); + this.rootRenderTarget.clearColor = this._backgroundColorRgba; + + this.bindRenderTarget(this.rootRenderTarget); + + // now lets fill up the textures with empty ones! + var emptyGLTexture = new _pixiGlCore2.default.GLTexture.fromData(gl, null, 1, 1); + + var tempObj = { _glTextures: {} }; + + tempObj._glTextures[this.CONTEXT_UID] = {}; + + for (var i = 0; i < maxTextures; i++) { + var empty = new _BaseTexture2.default(); + + empty._glTextures[this.CONTEXT_UID] = emptyGLTexture; + + this.boundTextures[i] = tempObj; + this.emptyTextures[i] = empty; + this.bindTexture(null, i); + } + + this.emit('context', gl); + + // setup the width/height properties and gl viewport + this.resize(this.screen.width, this.screen.height); + }; + + /** + * Renders the object to its webGL view + * + * @param {PIXI.DisplayObject} displayObject - the object to be rendered + * @param {PIXI.RenderTexture} renderTexture - The render texture to render to. + * @param {boolean} [clear] - Should the canvas be cleared before the new render + * @param {PIXI.Matrix} [transform] - A transform to apply to the render texture before rendering. + * @param {boolean} [skipUpdateTransform] - Should we skip the update transform pass? + */ + + + WebGLRenderer.prototype.render = function render(displayObject, renderTexture, clear, transform, skipUpdateTransform) { + // can be handy to know! + this.renderingToScreen = !renderTexture; + + this.emit('prerender'); + + // no point rendering if our context has been blown up! + if (!this.gl || this.gl.isContextLost()) { + return; + } + + this._nextTextureLocation = 0; + + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.parent; + + displayObject.parent = this._tempDisplayObjectParent; + displayObject.updateTransform(); + displayObject.parent = cacheParent; + // displayObject.hitArea = //TODO add a temp hit area + } + + this.bindRenderTexture(renderTexture, transform); + + this.currentRenderer.start(); + + if (clear !== undefined ? clear : this.clearBeforeRender) { + this._activeRenderTarget.clear(); + } + + displayObject.renderWebGL(this); + + // apply transform.. + this.currentRenderer.flush(); + + // this.setObjectRenderer(this.emptyRenderer); + + this.textureGC.update(); + + this.emit('postrender'); + }; + + /** + * Changes the current renderer to the one given in parameter + * + * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. + */ + + + WebGLRenderer.prototype.setObjectRenderer = function setObjectRenderer(objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; + + /** + * This should be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + * + */ + + + WebGLRenderer.prototype.flush = function flush() { + this.setObjectRenderer(this.emptyRenderer); + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} screenWidth - the new width of the screen + * @param {number} screenHeight - the new height of the screen + */ + + + WebGLRenderer.prototype.resize = function resize(screenWidth, screenHeight) { + // if(width * this.resolution === this.width && height * this.resolution === this.height)return; + + _SystemRenderer3.default.prototype.resize.call(this, screenWidth, screenHeight); + + this.rootRenderTarget.resize(screenWidth, screenHeight); + + if (this._activeRenderTarget === this.rootRenderTarget) { + this.rootRenderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = this.rootRenderTarget.projectionMatrix.toArray(true); + } + } + }; + + /** + * Resizes the webGL view to the specified width and height. + * + * @param {number} blendMode - the desired blend mode + */ + + + WebGLRenderer.prototype.setBlendMode = function setBlendMode(blendMode) { + this.state.setBlendMode(blendMode); + }; + + /** + * Erases the active render target and fills the drawing area with a colour + * + * @param {number} [clearColor] - The colour + */ + + + WebGLRenderer.prototype.clear = function clear(clearColor) { + this._activeRenderTarget.clear(clearColor); + }; + + /** + * Sets the transform of the active render target to the given matrix + * + * @param {PIXI.Matrix} matrix - The transformation matrix + */ + + + WebGLRenderer.prototype.setTransform = function setTransform(matrix) { + this._activeRenderTarget.transform = matrix; + }; + + /** + * Erases the render texture and fills the drawing area with a colour + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to clear + * @param {number} [clearColor] - The colour + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.clearRenderTexture = function clearRenderTexture(renderTexture, clearColor) { + var baseTexture = renderTexture.baseTexture; + var renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + + if (renderTarget) { + renderTarget.clear(clearColor); + } + + return this; + }; + + /** + * Binds a render texture for rendering + * + * @param {PIXI.RenderTexture} renderTexture - The render texture to render + * @param {PIXI.Matrix} transform - The transform to be applied to the render texture + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTexture = function bindRenderTexture(renderTexture, transform) { + var renderTarget = void 0; + + if (renderTexture) { + var baseTexture = renderTexture.baseTexture; + + if (!baseTexture._glRenderTargets[this.CONTEXT_UID]) { + // bind the current texture + this.textureManager.updateTexture(baseTexture, 0); + } + + this.unbindTexture(baseTexture); + + renderTarget = baseTexture._glRenderTargets[this.CONTEXT_UID]; + renderTarget.setFrame(renderTexture.frame); + } else { + renderTarget = this.rootRenderTarget; + } + + renderTarget.transform = transform; + this.bindRenderTarget(renderTarget); + + return this; + }; + + /** + * Changes the current render target to the one given in parameter + * + * @param {PIXI.RenderTarget} renderTarget - the new render target + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindRenderTarget = function bindRenderTarget(renderTarget) { + if (renderTarget !== this._activeRenderTarget) { + this._activeRenderTarget = renderTarget; + renderTarget.activate(); + + if (this._activeShader) { + this._activeShader.uniforms.projectionMatrix = renderTarget.projectionMatrix.toArray(true); + } + + this.stencilManager.setMaskStack(renderTarget.stencilMaskStack); + } + + return this; + }; + + /** + * Changes the current shader to the one given in parameter + * + * @param {PIXI.Shader} shader - the new shader + * @param {boolean} [autoProject=true] - Whether automatically set the projection matrix + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindShader = function bindShader(shader, autoProject) { + // TODO cache + if (this._activeShader !== shader) { + this._activeShader = shader; + shader.bind(); + + // `autoProject` normally would be a default parameter set to true + // but because of how Babel transpiles default parameters + // it hinders the performance of this method. + if (autoProject !== false) { + // automatically set the projection matrix + shader.uniforms.projectionMatrix = this._activeRenderTarget.projectionMatrix.toArray(true); + } + } + + return this; + }; + + /** + * Binds the texture. This will return the location of the bound texture. + * It may not be the same as the one you pass in. This is due to optimisation that prevents + * needless binding of textures. For example if the texture is already bound it will return the + * current location of the texture instead of the one provided. To bypass this use force location + * + * @param {PIXI.Texture} texture - the new texture + * @param {number} location - the suggested texture location + * @param {boolean} forceLocation - force the location + * @return {number} bound texture location + */ + + + WebGLRenderer.prototype.bindTexture = function bindTexture(texture, location, forceLocation) { + texture = texture || this.emptyTextures[location]; + texture = texture.baseTexture || texture; + texture.touched = this.textureGC.count; + + if (!forceLocation) { + // TODO - maybe look into adding boundIds.. save us the loop? + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === texture) { + return i; + } + } + + if (location === undefined) { + this._nextTextureLocation++; + this._nextTextureLocation %= this.boundTextures.length; + location = this.boundTextures.length - this._nextTextureLocation - 1; + } + } else { + location = location || 0; + } + + var gl = this.gl; + var glTexture = texture._glTextures[this.CONTEXT_UID]; + + if (!glTexture) { + // this will also bind the texture.. + this.textureManager.updateTexture(texture, location); + } else { + // bind the current texture + this.boundTextures[location] = texture; + gl.activeTexture(gl.TEXTURE0 + location); + gl.bindTexture(gl.TEXTURE_2D, glTexture.texture); + } + + return location; + }; + + /** + * unbinds the texture ... + * + * @param {PIXI.Texture} texture - the texture to unbind + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.unbindTexture = function unbindTexture(texture) { + var gl = this.gl; + + texture = texture.baseTexture || texture; + + if (this._unknownBoundTextures) { + this._unknownBoundTextures = false; + // someone changed webGL state, + // we have to be sure that our texture does not appear in multitexture renderer samplers + + for (var i = 0; i < this.boundTextures.length; i++) { + if (this.boundTextures[i] === this.emptyTextures[i]) { + gl.activeTexture(gl.TEXTURE0 + i); + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[i]._glTextures[this.CONTEXT_UID].texture); + } + } + } + + for (var _i = 0; _i < this.boundTextures.length; _i++) { + if (this.boundTextures[_i] === texture) { + this.boundTextures[_i] = this.emptyTextures[_i]; + + gl.activeTexture(gl.TEXTURE0 + _i); + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[_i]._glTextures[this.CONTEXT_UID].texture); + } + } + + return this; + }; + + /** + * Creates a new VAO from this renderer's context and state. + * + * @return {VertexArrayObject} The new VAO. + */ + + + WebGLRenderer.prototype.createVao = function createVao() { + return new _pixiGlCore2.default.VertexArrayObject(this.gl, this.state.attribState); + }; + + /** + * Changes the current Vao to the one given in parameter + * + * @param {PIXI.VertexArrayObject} vao - the new Vao + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.bindVao = function bindVao(vao) { + if (this._activeVao === vao) { + return this; + } + + if (vao) { + vao.bind(); + } else if (this._activeVao) { + // TODO this should always be true i think? + this._activeVao.unbind(); + } + + this._activeVao = vao; + + return this; + }; + + /** + * Resets the WebGL state so you can render things however you fancy! + * + * @return {PIXI.WebGLRenderer} Returns itself. + */ + + + WebGLRenderer.prototype.reset = function reset() { + this.setObjectRenderer(this.emptyRenderer); + + this.bindVao(null); + this._activeShader = null; + this._activeRenderTarget = this.rootRenderTarget; + + this._unknownBoundTextures = true; + + for (var i = 0; i < this.boundTextures.length; i++) { + this.boundTextures[i] = this.emptyTextures[i]; + } + + // bind the main frame buffer (the screen); + this.rootRenderTarget.activate(); + + this.state.resetToDefault(); + + return this; + }; + + /** + * Handles a lost webgl context + * + * @private + * @param {WebGLContextEvent} event - The context lost event. + */ + + + WebGLRenderer.prototype.handleContextLost = function handleContextLost(event) { + event.preventDefault(); + }; + + /** + * Handles a restored webgl context + * + * @private + */ + + + WebGLRenderer.prototype.handleContextRestored = function handleContextRestored() { + this.textureManager.removeAll(); + this.filterManager.destroy(true); + this._initContext(); + }; + + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * + * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + + + WebGLRenderer.prototype.destroy = function destroy(removeView) { + this.destroyPlugins(); + + // remove listeners + this.view.removeEventListener('webglcontextlost', this.handleContextLost); + this.view.removeEventListener('webglcontextrestored', this.handleContextRestored); + + this.textureManager.destroy(); + + // call base destroy + _SystemRenderer.prototype.destroy.call(this, removeView); + + this.uid = 0; + + // destroy the managers + this.maskManager.destroy(); + this.stencilManager.destroy(); + this.filterManager.destroy(); + + this.maskManager = null; + this.filterManager = null; + this.textureManager = null; + this.currentRenderer = null; + + this.handleContextLost = null; + this.handleContextRestored = null; + + this._contextOptions = null; + this.gl.useProgram(null); + + if (this.gl.getExtension('WEBGL_lose_context')) { + this.gl.getExtension('WEBGL_lose_context').loseContext(); + } + + this.gl = null; + + // this = null; + }; + + return WebGLRenderer; +}(_SystemRenderer3.default); + +/** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @name PIXI.WebGLRenderer#plugins + * @type {object} + * @readonly + * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.extract.WebGLExtract} extract Extract image data from renderer. + * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.prepare.WebGLPrepare} prepare Pre-render display objects. + */ + +/** + * Adds a plugin to the renderer. + * + * @method PIXI.WebGLRenderer#registerPlugin + * @param {string} pluginName - The name of the plugin. + * @param {Function} ctor - The constructor function or class for the plugin. + */ + +exports.default = WebGLRenderer; +_utils.pluginTarget.mixin(WebGLRenderer); + +},{"../../const":46,"../../textures/BaseTexture":112,"../../utils":125,"../SystemRenderer":76,"./TextureGarbageCollector":82,"./TextureManager":83,"./WebGLState":85,"./managers/FilterManager":90,"./managers/MaskManager":91,"./managers/StencilManager":92,"./utils/ObjectRenderer":94,"./utils/RenderTarget":96,"./utils/mapWebGLDrawModesToPixi":99,"./utils/validateContext":100,"pixi-gl-core":15}],85:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _mapWebGLBlendModesToPixi = require('./utils/mapWebGLBlendModesToPixi'); + +var _mapWebGLBlendModesToPixi2 = _interopRequireDefault(_mapWebGLBlendModesToPixi); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var BLEND = 0; +var DEPTH_TEST = 1; +var FRONT_FACE = 2; +var CULL_FACE = 3; +var BLEND_FUNC = 4; + +/** + * A WebGL state machines + * + * @memberof PIXI + * @class + */ + +var WebGLState = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL rendering context + */ + function WebGLState(gl) { + _classCallCheck(this, WebGLState); + + /** + * The current active state + * + * @member {Uint8Array} + */ + this.activeState = new Uint8Array(16); + + /** + * The default state + * + * @member {Uint8Array} + */ + this.defaultState = new Uint8Array(16); + + // default blend mode.. + this.defaultState[0] = 1; + + /** + * The current state index in the stack + * + * @member {number} + * @private + */ + this.stackIndex = 0; + + /** + * The stack holding all the different states + * + * @member {Array<*>} + * @private + */ + this.stack = []; + + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + this.maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + + this.attribState = { + tempAttribState: new Array(this.maxAttribs), + attribState: new Array(this.maxAttribs) + }; + + this.blendModes = (0, _mapWebGLBlendModesToPixi2.default)(gl); + + // check we have vao.. + this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || gl.getExtension('MOZ_OES_vertex_array_object') || gl.getExtension('WEBKIT_OES_vertex_array_object'); + } + + /** + * Pushes a new active state + */ + + + WebGLState.prototype.push = function push() { + // next state.. + var state = this.stack[this.stackIndex]; + + if (!state) { + state = this.stack[this.stackIndex] = new Uint8Array(16); + } + + ++this.stackIndex; + + // copy state.. + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; i++) { + state[i] = this.activeState[i]; + } + }; + + /** + * Pops a state out + */ + + + WebGLState.prototype.pop = function pop() { + var state = this.stack[--this.stackIndex]; + + this.setState(state); + }; + + /** + * Sets the current state + * + * @param {*} state - The state to set. + */ + + + WebGLState.prototype.setState = function setState(state) { + this.setBlend(state[BLEND]); + this.setDepthTest(state[DEPTH_TEST]); + this.setFrontFace(state[FRONT_FACE]); + this.setCullFace(state[CULL_FACE]); + this.setBlendMode(state[BLEND_FUNC]); + }; + + /** + * Enables or disabled blending. + * + * @param {boolean} value - Turn on or off webgl blending. + */ + + + WebGLState.prototype.setBlend = function setBlend(value) { + value = value ? 1 : 0; + + if (this.activeState[BLEND] === value) { + return; + } + + this.activeState[BLEND] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + }; + + /** + * Sets the blend mode. + * + * @param {number} value - The blend mode to set to. + */ + + + WebGLState.prototype.setBlendMode = function setBlendMode(value) { + if (value === this.activeState[BLEND_FUNC]) { + return; + } + + this.activeState[BLEND_FUNC] = value; + + var mode = this.blendModes[value]; + + if (mode.length === 2) { + this.gl.blendFunc(mode[0], mode[1]); + } else { + this.gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); + } + }; + + /** + * Sets whether to enable or disable depth test. + * + * @param {boolean} value - Turn on or off webgl depth testing. + */ + + + WebGLState.prototype.setDepthTest = function setDepthTest(value) { + value = value ? 1 : 0; + + if (this.activeState[DEPTH_TEST] === value) { + return; + } + + this.activeState[DEPTH_TEST] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + }; + + /** + * Sets whether to enable or disable cull face. + * + * @param {boolean} value - Turn on or off webgl cull face. + */ + + + WebGLState.prototype.setCullFace = function setCullFace(value) { + value = value ? 1 : 0; + + if (this.activeState[CULL_FACE] === value) { + return; + } + + this.activeState[CULL_FACE] = value; + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + }; + + /** + * Sets the gl front face. + * + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ + + + WebGLState.prototype.setFrontFace = function setFrontFace(value) { + value = value ? 1 : 0; + + if (this.activeState[FRONT_FACE] === value) { + return; + } + + this.activeState[FRONT_FACE] = value; + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); + }; + + /** + * Disables all the vaos in use + * + */ + + + WebGLState.prototype.resetAttributes = function resetAttributes() { + for (var i = 0; i < this.attribState.tempAttribState.length; i++) { + this.attribState.tempAttribState[i] = 0; + } + + for (var _i = 0; _i < this.attribState.attribState.length; _i++) { + this.attribState.attribState[_i] = 0; + } + + // im going to assume one is always active for performance reasons. + for (var _i2 = 1; _i2 < this.maxAttribs; _i2++) { + this.gl.disableVertexAttribArray(_i2); + } + }; + + // used + /** + * Resets all the logic and disables the vaos + */ + + + WebGLState.prototype.resetToDefault = function resetToDefault() { + // unbind any VAO if they exist.. + if (this.nativeVaoExtension) { + this.nativeVaoExtension.bindVertexArrayOES(null); + } + + // reset all attributes.. + this.resetAttributes(); + + // set active state so we can force overrides of gl state + for (var i = 0; i < this.activeState.length; ++i) { + this.activeState[i] = 32; + } + + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + + this.setState(this.defaultState); + }; + + return WebGLState; +}(); + +exports.default = WebGLState; + +},{"./utils/mapWebGLBlendModesToPixi":98}],86:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _extractUniformsFromSrc = require('./extractUniformsFromSrc'); + +var _extractUniformsFromSrc2 = _interopRequireDefault(_extractUniformsFromSrc); + +var _utils = require('../../../utils'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SOURCE_KEY_MAP = {}; + +// let math = require('../../../math'); +/** + * @class + * @memberof PIXI + * @extends PIXI.Shader + */ + +var Filter = function () { + /** + * @param {string} [vertexSrc] - The source of the vertex shader. + * @param {string} [fragmentSrc] - The source of the fragment shader. + * @param {object} [uniformData] - Custom uniforms to use to augment the built-in ones. + */ + function Filter(vertexSrc, fragmentSrc, uniformData) { + _classCallCheck(this, Filter); + + /** + * The vertex shader. + * + * @member {string} + */ + this.vertexSrc = vertexSrc || Filter.defaultVertexSrc; + + /** + * The fragment shader. + * + * @member {string} + */ + this.fragmentSrc = fragmentSrc || Filter.defaultFragmentSrc; + + this._blendMode = _const.BLEND_MODES.NORMAL; + + this.uniformData = uniformData || (0, _extractUniformsFromSrc2.default)(this.vertexSrc, this.fragmentSrc, 'projectionMatrix|uSampler'); + + /** + * An object containing the current values of custom uniforms. + * @example Updating the value of a custom uniform + * filter.uniforms.time = performance.now(); + * + * @member {object} + */ + this.uniforms = {}; + + for (var i in this.uniformData) { + this.uniforms[i] = this.uniformData[i].value; + if (this.uniformData[i].type) { + this.uniformData[i].type = this.uniformData[i].type.toLowerCase(); + } + } + + // this is where we store shader references.. + // TODO we could cache this! + this.glShaders = {}; + + // used for caching.. sure there is a better way! + if (!SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]) { + SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc] = (0, _utils.uid)(); + } + + this.glShaderKey = SOURCE_KEY_MAP[this.vertexSrc + this.fragmentSrc]; + + /** + * The padding of the filter. Some filters require extra space to breath such as a blur. + * Increasing this will add extra width and height to the bounds of the object that the + * filter is applied to. + * + * @member {number} + */ + this.padding = 4; + + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + * + * @member {number} + */ + this.resolution = _settings2.default.FILTER_RESOLUTION; + + /** + * If enabled is true the filter is applied, if false it will not. + * + * @member {boolean} + */ + this.enabled = true; + + /** + * If enabled, PixiJS will fit the filter area into boundaries for better performance. + * Switch it off if it does not work for specific shader. + * + * @member {boolean} + */ + this.autoFit = true; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + * @param {object} [currentState] - It's current state of filter. + * There are some useful properties in the currentState : + * target, filters, sourceFrame, destinationFrame, renderTarget, resolution + */ + + + Filter.prototype.apply = function apply(filterManager, input, output, clear, currentState) // eslint-disable-line no-unused-vars + { + // --- // + // this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(tempMatrix, window.panda ); + + // do as you please! + + filterManager.applyFilter(this, input, output, clear); + + // or just do a regular render.. + }; + + /** + * Sets the blendmode of the filter + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + */ + + + _createClass(Filter, [{ + key: 'blendMode', + get: function get() { + return this._blendMode; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._blendMode = value; + } + + /** + * The default vertex shader source + * + * @static + * @constant + */ + + }], [{ + key: 'defaultVertexSrc', + get: function get() { + return ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform mat3 projectionMatrix;', 'uniform mat3 filterMatrix;', 'varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'void main(void){', ' gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', ' vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;', ' vTextureCoord = aTextureCoord ;', '}'].join('\n'); + } + + /** + * The default fragment shader source + * + * @static + * @constant + */ + + }, { + key: 'defaultFragmentSrc', + get: function get() { + return ['varying vec2 vTextureCoord;', 'varying vec2 vFilterCoord;', 'uniform sampler2D uSampler;', 'uniform sampler2D filterSampler;', 'void main(void){', ' vec4 masky = texture2D(filterSampler, vFilterCoord);', ' vec4 sample = texture2D(uSampler, vTextureCoord);', ' vec4 color;', ' if(mod(vFilterCoord.x, 1.0) > 0.5)', ' {', ' color = vec4(1.0, 0.0, 0.0, 1.0);', ' }', ' else', ' {', ' color = vec4(0.0, 1.0, 0.0, 1.0);', ' }', + // ' gl_FragColor = vec4(mod(vFilterCoord.x, 1.5), vFilterCoord.y,0.0,1.0);', + ' gl_FragColor = mix(sample, masky, 0.5);', ' gl_FragColor *= sample.a;', '}'].join('\n'); + } + }]); + + return Filter; +}(); + +exports.default = Filter; + +},{"../../../const":46,"../../../settings":101,"../../../utils":125,"./extractUniformsFromSrc":87}],87:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = extractUniformsFromSrc; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var defaultValue = _pixiGlCore2.default.shader.defaultValue; + +function extractUniformsFromSrc(vertexSrc, fragmentSrc, mask) { + var vertUniforms = extractUniformsFromString(vertexSrc, mask); + var fragUniforms = extractUniformsFromString(fragmentSrc, mask); + + return Object.assign(vertUniforms, fragUniforms); +} + +function extractUniformsFromString(string) { + var maskRegex = new RegExp('^(projectionMatrix|uSampler|filterArea|filterClamp)$'); + + var uniforms = {}; + var nameSplit = void 0; + + // clean the lines a little - remove extra spaces / tabs etc + // then split along ';' + var lines = string.replace(/\s+/g, ' ').split(/\s*;\s*/); + + // loop through.. + for (var i = 0; i < lines.length; i++) { + var line = lines[i].trim(); + + if (line.indexOf('uniform') > -1) { + var splitLine = line.split(' '); + var type = splitLine[1]; + + var name = splitLine[2]; + var size = 1; + + if (name.indexOf('[') > -1) { + // array! + nameSplit = name.split(/\[|]/); + name = nameSplit[0]; + size *= Number(nameSplit[1]); + } + + if (!name.match(maskRegex)) { + uniforms[name] = { + value: defaultValue(type, size), + name: name, + type: type + }; + } + } + } + + return uniforms; +} + +},{"pixi-gl-core":15}],88:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.calculateScreenSpaceMatrix = calculateScreenSpaceMatrix; +exports.calculateNormalizedScreenSpaceMatrix = calculateNormalizedScreenSpaceMatrix; +exports.calculateSpriteMatrix = calculateSpriteMatrix; + +var _math = require('../../../math'); + +/** + * Calculates the mapped matrix + * @param filterArea {Rectangle} The filter area + * @param sprite {Sprite} the target sprite + * @param outputMatrix {Matrix} @alvin + * @private + */ +// TODO playing around here.. this is temporary - (will end up in the shader) +// this returns a matrix that will normalise map filter cords in the filter to screen space +function calculateScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + // let worldTransform = sprite.worldTransform.copy(Matrix.TEMP_MATRIX), + // let texture = {width:1136, height:700};//sprite._texture.baseTexture; + + // TODO unwrap? + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + mappedMatrix.scale(textureSize.width, textureSize.height); + + return mappedMatrix; +} + +function calculateNormalizedScreenSpaceMatrix(outputMatrix, filterArea, textureSize) { + var mappedMatrix = outputMatrix.identity(); + + mappedMatrix.translate(filterArea.x / textureSize.width, filterArea.y / textureSize.height); + + var translateScaleX = textureSize.width / filterArea.width; + var translateScaleY = textureSize.height / filterArea.height; + + mappedMatrix.scale(translateScaleX, translateScaleY); + + return mappedMatrix; +} + +// this will map the filter coord so that a texture can be used based on the transform of a sprite +function calculateSpriteMatrix(outputMatrix, filterArea, textureSize, sprite) { + var orig = sprite._texture.orig; + var mappedMatrix = outputMatrix.set(textureSize.width, 0, 0, textureSize.height, filterArea.x, filterArea.y); + var worldTransform = sprite.worldTransform.copy(_math.Matrix.TEMP_MATRIX); + + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height); + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; +} + +},{"../../../math":70}],89:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Filter2 = require('../Filter'); + +var _Filter3 = _interopRequireDefault(_Filter2); + +var _math = require('../../../../math'); + +var _path = require('path'); + +var _TextureMatrix = require('../../../../textures/TextureMatrix'); + +var _TextureMatrix2 = _interopRequireDefault(_TextureMatrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The SpriteMaskFilter class + * + * @class + * @extends PIXI.Filter + * @memberof PIXI + */ +var SpriteMaskFilter = function (_Filter) { + _inherits(SpriteMaskFilter, _Filter); + + /** + * @param {PIXI.Sprite} sprite - the target sprite + */ + function SpriteMaskFilter(sprite) { + _classCallCheck(this, SpriteMaskFilter); + + var maskMatrix = new _math.Matrix(); + + var _this = _possibleConstructorReturn(this, _Filter.call(this, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n', 'varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n\n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n')); + + sprite.renderable = false; + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + return _this; + } + + /** + * Applies the filter + * + * @param {PIXI.FilterManager} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + SpriteMaskFilter.prototype.apply = function apply(filterManager, input, output, clear) { + var maskSprite = this.maskSprite; + var tex = this.maskSprite.texture; + + if (!tex.valid) { + return; + } + if (!tex.transform) { + // margin = 0.0, let it bleed a bit, shader code becomes easier + // assuming that atlas textures were made with 1-pixel padding + tex.transform = new _TextureMatrix2.default(tex, 0.0); + } + tex.transform.update(); + + this.uniforms.mask = tex; + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite).prepend(tex.transform.mapCoord); + this.uniforms.alpha = maskSprite.worldAlpha; + this.uniforms.maskClamp = tex.transform.uClampFrame; + + filterManager.applyFilter(this, input, output, clear); + }; + + return SpriteMaskFilter; +}(_Filter3.default); + +exports.default = SpriteMaskFilter; + +},{"../../../../math":70,"../../../../textures/TextureMatrix":116,"../Filter":86,"path":8}],90:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _RenderTarget = require('../utils/RenderTarget'); + +var _RenderTarget2 = _interopRequireDefault(_RenderTarget); + +var _Quad = require('../utils/Quad'); + +var _Quad2 = _interopRequireDefault(_Quad); + +var _math = require('../../../math'); + +var _Shader = require('../../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _filterTransforms = require('../filters/filterTransforms'); + +var filterTransforms = _interopRequireWildcard(_filterTransforms); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @ignore + * @class + */ +var FilterState = function () { + /** + * + */ + function FilterState() { + _classCallCheck(this, FilterState); + + this.renderTarget = null; + this.target = null; + this.resolution = 1; + + // those three objects are used only for root + // re-assigned for everything else + this.sourceFrame = new _math.Rectangle(); + this.destinationFrame = new _math.Rectangle(); + this.filters = []; + } + + /** + * clears the state + */ + + + FilterState.prototype.clear = function clear() { + this.filters = null; + this.target = null; + this.renderTarget = null; + }; + + return FilterState; +}(); + +var screenKey = 'screen'; + +/** + * @class + * @memberof PIXI + * @extends PIXI.WebGLManager + */ + +var FilterManager = function (_WebGLManager) { + _inherits(FilterManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function FilterManager(renderer) { + _classCallCheck(this, FilterManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.gl = _this.renderer.gl; + // know about sprites! + _this.quad = new _Quad2.default(_this.gl, renderer.state.attribState); + + _this.shaderCache = {}; + // todo add default! + _this.pool = {}; + + _this.filterData = null; + + _this.managedFilters = []; + + _this.renderer.on('prerender', _this.onPrerender, _this); + + _this._screenWidth = renderer.view.width; + _this._screenHeight = renderer.view.height; + return _this; + } + + /** + * Adds a new filter to the manager. + * + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param {PIXI.Filter[]} filters - The filters to apply. + */ + + + FilterManager.prototype.pushFilter = function pushFilter(target, filters) { + var renderer = this.renderer; + + var filterData = this.filterData; + + if (!filterData) { + filterData = this.renderer._activeRenderTarget.filterStack; + + // add new stack + var filterState = new FilterState(); + + filterState.sourceFrame = filterState.destinationFrame = this.renderer._activeRenderTarget.size; + filterState.renderTarget = renderer._activeRenderTarget; + + this.renderer._activeRenderTarget.filterData = filterData = { + index: 0, + stack: [filterState] + }; + + this.filterData = filterData; + } + + // get the current filter state.. + var currentState = filterData.stack[++filterData.index]; + var renderTargetFrame = filterData.stack[0].destinationFrame; + + if (!currentState) { + currentState = filterData.stack[filterData.index] = new FilterState(); + } + + var fullScreen = target.filterArea && target.filterArea.x === 0 && target.filterArea.y === 0 && target.filterArea.width === renderer.screen.width && target.filterArea.height === renderer.screen.height; + + // for now we go off the filter of the first resolution.. + var resolution = filters[0].resolution; + var padding = filters[0].padding | 0; + var targetBounds = fullScreen ? renderer.screen : target.filterArea || target.getBounds(true); + var sourceFrame = currentState.sourceFrame; + var destinationFrame = currentState.destinationFrame; + + sourceFrame.x = (targetBounds.x * resolution | 0) / resolution; + sourceFrame.y = (targetBounds.y * resolution | 0) / resolution; + sourceFrame.width = (targetBounds.width * resolution | 0) / resolution; + sourceFrame.height = (targetBounds.height * resolution | 0) / resolution; + + if (!fullScreen) { + if (filterData.stack[0].renderTarget.transform) {// + + // TODO we should fit the rect around the transform.. + } else if (filters[0].autoFit) { + sourceFrame.fit(renderTargetFrame); + } + + // lets apply the padding After we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + sourceFrame.pad(padding); + } + + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + + // lets play the padding after we fit the element to the screen. + // this should stop the strange side effects that can occur when cropping to the edges + + var renderTarget = this.getPotRenderTarget(renderer.gl, sourceFrame.width, sourceFrame.height, resolution); + + currentState.target = target; + currentState.filters = filters; + currentState.resolution = resolution; + currentState.renderTarget = renderTarget; + + // bind the render target to draw the shape in the top corner.. + + renderTarget.setFrame(destinationFrame, sourceFrame); + + // bind the render target + renderer.bindRenderTarget(renderTarget); + renderTarget.clear(); + }; + + /** + * Pops off the filter and applies it. + * + */ + + + FilterManager.prototype.popFilter = function popFilter() { + var filterData = this.filterData; + + var lastState = filterData.stack[filterData.index - 1]; + var currentState = filterData.stack[filterData.index]; + + this.quad.map(currentState.renderTarget.size, currentState.sourceFrame).upload(); + + var filters = currentState.filters; + + if (filters.length === 1) { + filters[0].apply(this, currentState.renderTarget, lastState.renderTarget, false, currentState); + this.freePotRenderTarget(currentState.renderTarget); + } else { + var flip = currentState.renderTarget; + var flop = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, currentState.resolution); + + flop.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + // finally lets clear the render target before drawing to it.. + flop.clear(); + + var i = 0; + + for (i = 0; i < filters.length - 1; ++i) { + filters[i].apply(this, flip, flop, true, currentState); + + var t = flip; + + flip = flop; + flop = t; + } + + filters[i].apply(this, flip, lastState.renderTarget, false, currentState); + + this.freePotRenderTarget(flip); + this.freePotRenderTarget(flop); + } + + currentState.clear(); + filterData.index--; + + if (filterData.index === 0) { + this.filterData = null; + } + }; + + /** + * Draws a filter. + * + * @param {PIXI.Filter} filter - The filter to draw. + * @param {PIXI.RenderTarget} input - The input render target. + * @param {PIXI.RenderTarget} output - The target to output to. + * @param {boolean} clear - Should the output be cleared before rendering to it + */ + + + FilterManager.prototype.applyFilter = function applyFilter(filter, input, output, clear) { + var renderer = this.renderer; + var gl = renderer.gl; + + var shader = filter.glShaders[renderer.CONTEXT_UID]; + + // caching.. + if (!shader) { + if (filter.glShaderKey) { + shader = this.shaderCache[filter.glShaderKey]; + + if (!shader) { + shader = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + + filter.glShaders[renderer.CONTEXT_UID] = this.shaderCache[filter.glShaderKey] = shader; + this.managedFilters.push(filter); + } + } else { + shader = filter.glShaders[renderer.CONTEXT_UID] = new _Shader2.default(this.gl, filter.vertexSrc, filter.fragmentSrc); + this.managedFilters.push(filter); + } + + // TODO - this only needs to be done once? + renderer.bindVao(null); + + this.quad.initVao(shader); + } + + renderer.bindVao(this.quad.vao); + + renderer.bindRenderTarget(output); + + if (clear) { + gl.disable(gl.SCISSOR_TEST); + renderer.clear(); // [1, 1, 1, 1]); + gl.enable(gl.SCISSOR_TEST); + } + + // in case the render target is being masked using a scissor rect + if (output === renderer.maskManager.scissorRenderTarget) { + renderer.maskManager.pushScissorMask(null, renderer.maskManager.scissorData); + } + + renderer.bindShader(shader); + + // free unit 0 for us, doesn't matter what was there + // don't try to restore it, because syncUniforms can upload it to another slot + // and it'll be a problem + var tex = this.renderer.emptyTextures[0]; + + this.renderer.boundTextures[0] = tex; + // this syncs the PixiJS filters uniforms with glsl uniforms + this.syncUniforms(shader, filter); + + renderer.state.setBlendMode(filter.blendMode); + + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, input.texture.texture); + + this.quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + }; + + /** + * Uploads the uniforms of the filter. + * + * @param {GLShader} shader - The underlying gl shader. + * @param {PIXI.Filter} filter - The filter we are synchronizing. + */ + + + FilterManager.prototype.syncUniforms = function syncUniforms(shader, filter) { + var uniformData = filter.uniformData; + var uniforms = filter.uniforms; + + // 0 is reserved for the PixiJS texture so we start at 1! + var textureCount = 1; + var currentState = void 0; + + // filterArea and filterClamp that are handled by FilterManager directly + // they must not appear in uniformData + + if (shader.uniforms.filterArea) { + currentState = this.filterData.stack[this.filterData.index]; + + var filterArea = shader.uniforms.filterArea; + + filterArea[0] = currentState.renderTarget.size.width; + filterArea[1] = currentState.renderTarget.size.height; + filterArea[2] = currentState.sourceFrame.x; + filterArea[3] = currentState.sourceFrame.y; + + shader.uniforms.filterArea = filterArea; + } + + // use this to clamp displaced texture coords so they belong to filterArea + // see displacementFilter fragment shader for an example + if (shader.uniforms.filterClamp) { + currentState = currentState || this.filterData.stack[this.filterData.index]; + + var filterClamp = shader.uniforms.filterClamp; + + filterClamp[0] = 0; + filterClamp[1] = 0; + filterClamp[2] = (currentState.sourceFrame.width - 1) / currentState.renderTarget.size.width; + filterClamp[3] = (currentState.sourceFrame.height - 1) / currentState.renderTarget.size.height; + + shader.uniforms.filterClamp = filterClamp; + } + + // TODO Caching layer.. + for (var i in uniformData) { + if (!shader.uniforms.data[i]) { + continue; + } + + var type = uniformData[i].type; + + if (type === 'sampler2d' && uniforms[i] !== 0) { + if (uniforms[i].baseTexture) { + shader.uniforms[i] = this.renderer.bindTexture(uniforms[i].baseTexture, textureCount); + } else { + shader.uniforms[i] = textureCount; + + // TODO + // this is helpful as renderTargets can also be set. + // Although thinking about it, we could probably + // make the filter texture cache return a RenderTexture + // rather than a renderTarget + var gl = this.renderer.gl; + + this.renderer.boundTextures[textureCount] = this.renderer.emptyTextures[textureCount]; + gl.activeTexture(gl.TEXTURE0 + textureCount); + + uniforms[i].texture.bind(); + } + + textureCount++; + } else if (type === 'mat3') { + // check if its PixiJS matrix.. + if (uniforms[i].a !== undefined) { + shader.uniforms[i] = uniforms[i].toArray(true); + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (type === 'vec2') { + // check if its a point.. + if (uniforms[i].x !== undefined) { + var val = shader.uniforms[i] || new Float32Array(2); + + val[0] = uniforms[i].x; + val[1] = uniforms[i].y; + shader.uniforms[i] = val; + } else { + shader.uniforms[i] = uniforms[i]; + } + } else if (type === 'float') { + if (shader.uniforms.data[i].value !== uniformData[i]) { + shader.uniforms[i] = uniforms[i]; + } + } else { + shader.uniforms[i] = uniforms[i]; + } + } + }; + + /** + * Gets a render target from the pool, or creates a new one. + * + * @param {boolean} clear - Should we clear the render texture when we get it? + * @param {number} resolution - The resolution of the target. + * @return {PIXI.RenderTarget} The new render target + */ + + + FilterManager.prototype.getRenderTarget = function getRenderTarget(clear, resolution) { + var currentState = this.filterData.stack[this.filterData.index]; + var renderTarget = this.getPotRenderTarget(this.renderer.gl, currentState.sourceFrame.width, currentState.sourceFrame.height, resolution || currentState.resolution); + + renderTarget.setFrame(currentState.destinationFrame, currentState.sourceFrame); + + return renderTarget; + }; + + /** + * Returns a render target to the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The render target to return. + */ + + + FilterManager.prototype.returnRenderTarget = function returnRenderTarget(renderTarget) { + this.freePotRenderTarget(renderTarget); + }; + + /** + * Calculates the mapped matrix. + * + * TODO playing around here.. this is temporary - (will end up in the shader) + * this returns a matrix that will normalise map filter cords in the filter to screen space + * + * @param {PIXI.Matrix} outputMatrix - the matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateScreenSpaceMatrix = function calculateScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size); + }; + + /** + * Multiply vTextureCoord to this matrix to achieve (0,0,1,1) for filterArea + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateNormalizedScreenSpaceMatrix = function calculateNormalizedScreenSpaceMatrix(outputMatrix) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateNormalizedScreenSpaceMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, currentState.destinationFrame); + }; + + /** + * This will map the filter coord so that a texture can be used based on the transform of a sprite + * + * @param {PIXI.Matrix} outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @return {PIXI.Matrix} The mapped matrix. + */ + + + FilterManager.prototype.calculateSpriteMatrix = function calculateSpriteMatrix(outputMatrix, sprite) { + var currentState = this.filterData.stack[this.filterData.index]; + + return filterTransforms.calculateSpriteMatrix(outputMatrix, currentState.sourceFrame, currentState.renderTarget.size, sprite); + }; + + /** + * Destroys this Filter Manager. + * + * @param {boolean} [contextLost=false] context was lost, do not free shaders + * + */ + + + FilterManager.prototype.destroy = function destroy() { + var contextLost = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + var renderer = this.renderer; + var filters = this.managedFilters; + + renderer.off('prerender', this.onPrerender, this); + + for (var i = 0; i < filters.length; i++) { + if (!contextLost) { + filters[i].glShaders[renderer.CONTEXT_UID].destroy(); + } + delete filters[i].glShaders[renderer.CONTEXT_UID]; + } + + this.shaderCache = {}; + if (!contextLost) { + this.emptyPool(); + } else { + this.pool = {}; + } + }; + + /** + * Gets a Power-of-Two render texture. + * + * TODO move to a separate class could be on renderer? + * also - could cause issue with multiple contexts? + * + * @private + * @param {WebGLRenderingContext} gl - The webgl rendering context + * @param {number} minWidth - The minimum width of the render target. + * @param {number} minHeight - The minimum height of the render target. + * @param {number} resolution - The resolution of the render target. + * @return {PIXI.RenderTarget} The new render target. + */ + + + FilterManager.prototype.getPotRenderTarget = function getPotRenderTarget(gl, minWidth, minHeight, resolution) { + var key = screenKey; + + minWidth *= resolution; + minHeight *= resolution; + + if (minWidth !== this._screenWidth || minHeight !== this._screenHeight) { + // TODO you could return a bigger texture if there is not one in the pool? + minWidth = _bitTwiddle2.default.nextPow2(minWidth); + minHeight = _bitTwiddle2.default.nextPow2(minHeight); + key = (minWidth & 0xFFFF) << 16 | minHeight & 0xFFFF; + } + + if (!this.pool[key]) { + this.pool[key] = []; + } + + var renderTarget = this.pool[key].pop(); + + // creating render target will cause texture to be bound! + if (!renderTarget) { + // temporary bypass cache.. + var tex = this.renderer.boundTextures[0]; + + gl.activeTexture(gl.TEXTURE0); + + // internally - this will cause a texture to be bound.. + renderTarget = new _RenderTarget2.default(gl, minWidth, minHeight, null, 1); + + // set the current one back + gl.bindTexture(gl.TEXTURE_2D, tex._glTextures[this.renderer.CONTEXT_UID].texture); + } + + // manually tweak the resolution... + // this will not modify the size of the frame buffer, just its resolution. + renderTarget.resolution = resolution; + renderTarget.defaultFrame.width = renderTarget.size.width = minWidth / resolution; + renderTarget.defaultFrame.height = renderTarget.size.height = minHeight / resolution; + renderTarget.filterPoolKey = key; + + return renderTarget; + }; + + /** + * Empties the texture pool. + * + */ + + + FilterManager.prototype.emptyPool = function emptyPool() { + for (var i in this.pool) { + var textures = this.pool[i]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + + this.pool = {}; + }; + + /** + * Frees a render target back into the pool. + * + * @param {PIXI.RenderTarget} renderTarget - The renderTarget to free + */ + + + FilterManager.prototype.freePotRenderTarget = function freePotRenderTarget(renderTarget) { + this.pool[renderTarget.filterPoolKey].push(renderTarget); + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + FilterManager.prototype.onPrerender = function onPrerender() { + if (this._screenWidth !== this.renderer.view.width || this._screenHeight !== this.renderer.view.height) { + this._screenWidth = this.renderer.view.width; + this._screenHeight = this.renderer.view.height; + + var textures = this.pool[screenKey]; + + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + this.pool[screenKey] = []; + } + }; + + return FilterManager; +}(_WebGLManager3.default); + +exports.default = FilterManager; + +},{"../../../Shader":44,"../../../math":70,"../filters/filterTransforms":88,"../utils/Quad":95,"../utils/RenderTarget":96,"./WebGLManager":93,"bit-twiddle":1}],91:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +var _SpriteMaskFilter = require('../filters/spriteMask/SpriteMaskFilter'); + +var _SpriteMaskFilter2 = _interopRequireDefault(_SpriteMaskFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var MaskManager = function (_WebGLManager) { + _inherits(MaskManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function MaskManager(renderer) { + _classCallCheck(this, MaskManager); + + // TODO - we don't need both! + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.scissor = false; + _this.scissorData = null; + _this.scissorRenderTarget = null; + + _this.enableScissor = true; + + _this.alphaMaskPool = []; + _this.alphaMaskIndex = 0; + return _this; + } + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushMask = function pushMask(target, maskData) { + // TODO the root check means scissor rect will not + // be used on render textures more info here: + // https://github.com/pixijs/pixi.js/pull/3545 + + if (maskData.texture) { + this.pushSpriteMask(target, maskData); + } else if (this.enableScissor && !this.scissor && this.renderer._activeRenderTarget.root && !this.renderer.stencilManager.stencilMaskStack.length && maskData.isFastRect()) { + var matrix = maskData.worldTransform; + + var rot = Math.atan2(matrix.b, matrix.a); + + // use the nearest degree! + rot = Math.round(rot * (180 / Math.PI)); + + if (rot % 90) { + this.pushStencilMask(maskData); + } else { + this.pushScissorMask(target, maskData); + } + } else { + this.pushStencilMask(maskData); + } + }; + + /** + * Removes the last mask from the mask stack and doesn't return it. + * + * @param {PIXI.DisplayObject} target - Display Object to pop the mask from + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.popMask = function popMask(target, maskData) { + if (maskData.texture) { + this.popSpriteMask(target, maskData); + } else if (this.enableScissor && !this.renderer.stencilManager.stencilMaskStack.length) { + this.popScissorMask(target, maskData); + } else { + this.popStencilMask(target, maskData); + } + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.RenderTarget} target - Display Object to push the sprite mask to + * @param {PIXI.Sprite} maskData - Sprite to be used as the mask + */ + + + MaskManager.prototype.pushSpriteMask = function pushSpriteMask(target, maskData) { + var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new _SpriteMaskFilter2.default(maskData)]; + } + + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskData; + + var stashFilterArea = target.filterArea; + + target.filterArea = maskData.getBounds(true); + this.renderer.filterManager.pushFilter(target, alphaMaskFilter); + target.filterArea = stashFilterArea; + + this.alphaMaskIndex++; + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popSpriteMask = function popSpriteMask() { + this.renderer.filterManager.popFilter(); + this.alphaMaskIndex--; + }; + + /** + * Applies the Mask and adds it to the current filter stack. + * + * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushStencilMask = function pushStencilMask(maskData) { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.pushStencil(maskData); + }; + + /** + * Removes the last filter from the filter stack and doesn't return it. + * + */ + + + MaskManager.prototype.popStencilMask = function popStencilMask() { + this.renderer.currentRenderer.stop(); + this.renderer.stencilManager.popStencil(); + }; + + /** + * + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.Graphics} maskData - The masking data. + */ + + + MaskManager.prototype.pushScissorMask = function pushScissorMask(target, maskData) { + maskData.renderable = true; + + var renderTarget = this.renderer._activeRenderTarget; + + var bounds = maskData.getBounds(); + + bounds.fit(renderTarget.size); + maskData.renderable = false; + + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + + var resolution = this.renderer.resolution; + + this.renderer.gl.scissor(bounds.x * resolution, (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution, bounds.width * resolution, bounds.height * resolution); + + this.scissorRenderTarget = renderTarget; + this.scissorData = maskData; + this.scissor = true; + }; + + /** + * + * + */ + + + MaskManager.prototype.popScissorMask = function popScissorMask() { + this.scissorRenderTarget = null; + this.scissorData = null; + this.scissor = false; + + // must be scissor! + var gl = this.renderer.gl; + + gl.disable(gl.SCISSOR_TEST); + }; + + return MaskManager; +}(_WebGLManager3.default); + +exports.default = MaskManager; + +},{"../filters/spriteMask/SpriteMaskFilter":89,"./WebGLManager":93}],92:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('./WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var StencilManager = function (_WebGLManager) { + _inherits(StencilManager, _WebGLManager); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function StencilManager(renderer) { + _classCallCheck(this, StencilManager); + + var _this = _possibleConstructorReturn(this, _WebGLManager.call(this, renderer)); + + _this.stencilMaskStack = null; + return _this; + } + + /** + * Changes the mask stack that is used by this manager. + * + * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack + */ + + + StencilManager.prototype.setMaskStack = function setMaskStack(stencilMaskStack) { + this.stencilMaskStack = stencilMaskStack; + + var gl = this.renderer.gl; + + if (stencilMaskStack.length === 0) { + gl.disable(gl.STENCIL_TEST); + } else { + gl.enable(gl.STENCIL_TEST); + } + }; + + /** + * Applies the Mask and adds it to the current stencil stack. @alvin + * + * @param {PIXI.Graphics} graphics - The mask + */ + + + StencilManager.prototype.pushStencil = function pushStencil(graphics) { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + this.renderer._activeRenderTarget.attachStencilBuffer(); + + var gl = this.renderer.gl; + var prevMaskCount = this.stencilMaskStack.length; + + if (prevMaskCount === 0) { + gl.enable(gl.STENCIL_TEST); + } + + this.stencilMaskStack.push(graphics); + + // Increment the reference stencil value where the new mask overlaps with the old ones. + gl.colorMask(false, false, false, false); + gl.stencilFunc(gl.EQUAL, prevMaskCount, this._getBitwiseMask()); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + this.renderer.plugins.graphics.render(graphics); + + this._useCurrent(); + }; + + /** + * Removes the last mask from the stencil stack. @alvin + */ + + + StencilManager.prototype.popStencil = function popStencil() { + this.renderer.setObjectRenderer(this.renderer.plugins.graphics); + + var gl = this.renderer.gl; + var graphics = this.stencilMaskStack.pop(); + + if (this.stencilMaskStack.length === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.clearStencil(0); + } else { + // Decrement the reference stencil value where the popped mask overlaps with the other ones + gl.colorMask(false, false, false, false); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + this.renderer.plugins.graphics.render(graphics); + + this._useCurrent(); + } + }; + + /** + * Setup renderer to use the current stencil data. + */ + + + StencilManager.prototype._useCurrent = function _useCurrent() { + var gl = this.renderer.gl; + + gl.colorMask(true, true, true, true); + gl.stencilFunc(gl.EQUAL, this.stencilMaskStack.length, this._getBitwiseMask()); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; + + /** + * Fill 1s equal to the number of acitve stencil masks. + * + * @return {number} The bitwise mask. + */ + + + StencilManager.prototype._getBitwiseMask = function _getBitwiseMask() { + return (1 << this.stencilMaskStack.length) - 1; + }; + + /** + * Destroys the mask stack. + * + */ + + + StencilManager.prototype.destroy = function destroy() { + _WebGLManager3.default.prototype.destroy.call(this); + + this.stencilMaskStack.stencilStack = null; + }; + + return StencilManager; +}(_WebGLManager3.default); + +exports.default = StencilManager; + +},{"./WebGLManager":93}],93:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var WebGLManager = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this manager works for. + */ + function WebGLManager(renderer) { + _classCallCheck(this, WebGLManager); + + /** + * The renderer this manager works for. + * + * @member {PIXI.WebGLRenderer} + */ + this.renderer = renderer; + + this.renderer.on('context', this.onContextChange, this); + } + + /** + * Generic method called when there is a WebGL context change. + * + */ + + + WebGLManager.prototype.onContextChange = function onContextChange() {} + // do some codes init! + + + /** + * Generic destroy methods to be overridden by the subclass + * + */ + ; + + WebGLManager.prototype.destroy = function destroy() { + this.renderer.off('context', this.onContextChange, this); + + this.renderer = null; + }; + + return WebGLManager; +}(); + +exports.default = WebGLManager; + +},{}],94:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLManager2 = require('../managers/WebGLManager'); + +var _WebGLManager3 = _interopRequireDefault(_WebGLManager2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Base for a common object renderer that can be used as a system renderer plugin. + * + * @class + * @extends PIXI.WebGLManager + * @memberof PIXI + */ +var ObjectRenderer = function (_WebGLManager) { + _inherits(ObjectRenderer, _WebGLManager); + + function ObjectRenderer() { + _classCallCheck(this, ObjectRenderer); + + return _possibleConstructorReturn(this, _WebGLManager.apply(this, arguments)); + } + + /** + * Starts the renderer and sets the shader + * + */ + ObjectRenderer.prototype.start = function start() {} + // set the shader.. + + + /** + * Stops the renderer + * + */ + ; + + ObjectRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Stub method for rendering content and emptying the current batch. + * + */ + + + ObjectRenderer.prototype.flush = function flush() {} + // flush! + + + /** + * Renders an object + * + * @param {PIXI.DisplayObject} object - The object to render. + */ + ; + + ObjectRenderer.prototype.render = function render(object) // eslint-disable-line no-unused-vars + { + // render the object + }; + + return ObjectRenderer; +}(_WebGLManager3.default); + +exports.default = ObjectRenderer; + +},{"../managers/WebGLManager":93}],95:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Helper class to create a quad + * + * @class + * @memberof PIXI + */ +var Quad = function () { + /** + * @param {WebGLRenderingContext} gl - The gl context for this quad to use. + * @param {object} state - TODO: Description + */ + function Quad(gl, state) { + _classCallCheck(this, Quad); + + /** + * the current WebGL drawing context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * An array of vertices + * + * @member {Float32Array} + */ + this.vertices = new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]); + + /** + * The Uvs of the quad + * + * @member {Float32Array} + */ + this.uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + this.interleaved = new Float32Array(8 * 2); + + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(1); + + /** + * The vertex buffer + * + * @member {glCore.GLBuffer} + */ + this.vertexBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, this.interleaved, gl.STATIC_DRAW); + + /** + * The index buffer + * + * @member {glCore.GLBuffer} + */ + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + /** + * The vertex array object + * + * @member {glCore.VertexArrayObject} + */ + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl, state); + } + + /** + * Initialises the vaos and uses the shader. + * + * @param {PIXI.Shader} shader - the shader to use + */ + + + Quad.prototype.initVao = function initVao(shader) { + this.vao.clear().addIndex(this.indexBuffer).addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0).addAttribute(this.vertexBuffer, shader.attributes.aTextureCoord, this.gl.FLOAT, false, 4 * 4, 2 * 4); + }; + + /** + * Maps two Rectangle to the quad. + * + * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle + * @param {PIXI.Rectangle} destinationFrame - the second rectangle + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.map = function map(targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + + this.uvs[0] = x; + this.uvs[1] = y; + + this.uvs[2] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[3] = y; + + this.uvs[4] = x + destinationFrame.width / targetTextureFrame.width; + this.uvs[5] = y + destinationFrame.height / targetTextureFrame.height; + + this.uvs[6] = x; + this.uvs[7] = y + destinationFrame.height / targetTextureFrame.height; + + x = destinationFrame.x; + y = destinationFrame.y; + + this.vertices[0] = x; + this.vertices[1] = y; + + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + + return this; + }; + + /** + * Binds the buffer and uploads the data + * + * @return {PIXI.Quad} Returns itself. + */ + + + Quad.prototype.upload = function upload() { + for (var i = 0; i < 4; i++) { + this.interleaved[i * 4] = this.vertices[i * 2]; + this.interleaved[i * 4 + 1] = this.vertices[i * 2 + 1]; + this.interleaved[i * 4 + 2] = this.uvs[i * 2]; + this.interleaved[i * 4 + 3] = this.uvs[i * 2 + 1]; + } + + this.vertexBuffer.upload(this.interleaved); + + return this; + }; + + /** + * Removes this quad from WebGL + */ + + + Quad.prototype.destroy = function destroy() { + var gl = this.gl; + + gl.deleteBuffer(this.vertexBuffer); + gl.deleteBuffer(this.indexBuffer); + }; + + return Quad; +}(); + +exports.default = Quad; + +},{"../../../utils/createIndicesForQuads":123,"pixi-gl-core":15}],96:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _math = require('../../../math'); + +var _const = require('../../../const'); + +var _settings = require('../../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _pixiGlCore = require('pixi-gl-core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var RenderTarget = function () { + /** + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {number} [width=0] - the horizontal range of the filter + * @param {number} [height=0] - the vertical range of the filter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The current resolution / device pixel ratio + * @param {boolean} [root=false] - Whether this object is the root element or not + */ + function RenderTarget(gl, width, height, scaleMode, resolution, root) { + _classCallCheck(this, RenderTarget); + + // TODO Resolution could go here ( eg low res blurs ) + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + // next time to create a frame buffer and texture + + /** + * A frame buffer + * + * @member {PIXI.glCore.GLFramebuffer} + */ + this.frameBuffer = null; + + /** + * The texture + * + * @member {PIXI.glCore.GLTexture} + */ + this.texture = null; + + /** + * The background colour of this render target, as an array of [r,g,b,a] values + * + * @member {number[]} + */ + this.clearColor = [0, 0, 0, 0]; + + /** + * The size of the object as a rectangle + * + * @member {PIXI.Rectangle} + */ + this.size = new _math.Rectangle(0, 0, 1, 1); + + /** + * The current resolution / device pixel ratio + * + * @member {number} + * @default 1 + */ + this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The projection matrix + * + * @member {PIXI.Matrix} + */ + this.projectionMatrix = new _math.Matrix(); + + /** + * The object's transform + * + * @member {PIXI.Matrix} + */ + this.transform = null; + + /** + * The frame. + * + * @member {PIXI.Rectangle} + */ + this.frame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.defaultFrame = new _math.Rectangle(); + this.destinationFrame = null; + this.sourceFrame = null; + + /** + * The stencil buffer stores masking data for the render target + * + * @member {glCore.GLBuffer} + */ + this.stencilBuffer = null; + + /** + * The data structure for the stencil masks + * + * @member {PIXI.Graphics[]} + */ + this.stencilMaskStack = []; + + /** + * Stores filter data for the render target + * + * @member {object[]} + */ + this.filterData = null; + + /** + * The key for pooled texture of FilterSystem + * @private + * @member {string} + */ + this.filterPoolKey = ''; + + /** + * The scale mode. + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Whether this object is the root element or not + * + * @member {boolean} + * @default false + */ + this.root = root || false; + + if (!this.root) { + this.frameBuffer = _pixiGlCore.GLFramebuffer.createRGBA(gl, 100, 100); + + if (this.scaleMode === _const.SCALE_MODES.NEAREST) { + this.frameBuffer.texture.enableNearestScaling(); + } else { + this.frameBuffer.texture.enableLinearScaling(); + } + /* + A frame buffer needs a target to render to.. + create a texture and bind it attach it to the framebuffer.. + */ + + // this is used by the base texture + this.texture = this.frameBuffer.texture; + } else { + // make it a null framebuffer.. + this.frameBuffer = new _pixiGlCore.GLFramebuffer(gl, 100, 100); + this.frameBuffer.framebuffer = null; + } + + this.setFrame(); + + this.resize(width, height); + } + + /** + * Clears the filter texture. + * + * @param {number[]} [clearColor=this.clearColor] - Array of [r,g,b,a] to clear the framebuffer + */ + + + RenderTarget.prototype.clear = function clear(clearColor) { + var cc = clearColor || this.clearColor; + + this.frameBuffer.clear(cc[0], cc[1], cc[2], cc[3]); // r,g,b,a); + }; + + /** + * Binds the stencil buffer. + * + */ + + + RenderTarget.prototype.attachStencilBuffer = function attachStencilBuffer() { + // TODO check if stencil is done? + /** + * The stencil buffer is used for masking in pixi + * lets create one and then add attach it to the framebuffer.. + */ + if (!this.root) { + this.frameBuffer.enableStencil(); + } + }; + + /** + * Sets the frame of the render target. + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.setFrame = function setFrame(destinationFrame, sourceFrame) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || this.destinationFrame; + }; + + /** + * Binds the buffers and initialises the viewport. + * + */ + + + RenderTarget.prototype.activate = function activate() { + // TODO refactor usage of frame.. + var gl = this.gl; + + // make sure the texture is unbound! + this.frameBuffer.bind(); + + this.calculateProjection(this.destinationFrame, this.sourceFrame); + + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + + // TODO add a check as them may be the same! + if (this.destinationFrame !== this.sourceFrame) { + gl.enable(gl.SCISSOR_TEST); + gl.scissor(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + } else { + gl.disable(gl.SCISSOR_TEST); + } + + // TODO - does not need to be updated all the time?? + gl.viewport(this.destinationFrame.x | 0, this.destinationFrame.y | 0, this.destinationFrame.width * this.resolution | 0, this.destinationFrame.height * this.resolution | 0); + }; + + /** + * Updates the projection matrix based on a projection frame (which is a rectangle) + * + * @param {Rectangle} destinationFrame - The destination frame. + * @param {Rectangle} sourceFrame - The source frame. + */ + + + RenderTarget.prototype.calculateProjection = function calculateProjection(destinationFrame, sourceFrame) { + var pm = this.projectionMatrix; + + sourceFrame = sourceFrame || destinationFrame; + + pm.identity(); + + // TODO: make dest scale source + if (!this.root) { + pm.a = 1 / destinationFrame.width * 2; + pm.d = 1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = -1 - sourceFrame.y * pm.d; + } else { + pm.a = 1 / destinationFrame.width * 2; + pm.d = -1 / destinationFrame.height * 2; + + pm.tx = -1 - sourceFrame.x * pm.a; + pm.ty = 1 - sourceFrame.y * pm.d; + } + }; + + /** + * Resizes the texture to the specified width and height + * + * @param {number} width - the new width of the texture + * @param {number} height - the new height of the texture + */ + + + RenderTarget.prototype.resize = function resize(width, height) { + width = width | 0; + height = height | 0; + + if (this.size.width === width && this.size.height === height) { + return; + } + + this.size.width = width; + this.size.height = height; + + this.defaultFrame.width = width; + this.defaultFrame.height = height; + + this.frameBuffer.resize(width * this.resolution, height * this.resolution); + + var projectionFrame = this.frame || this.size; + + this.calculateProjection(projectionFrame); + }; + + /** + * Destroys the render target. + * + */ + + + RenderTarget.prototype.destroy = function destroy() { + if (this.frameBuffer.stencil) { + this.gl.deleteRenderbuffer(this.frameBuffer.stencil); + } + this.frameBuffer.destroy(); + + this.frameBuffer = null; + this.texture = null; + }; + + return RenderTarget; +}(); + +exports.default = RenderTarget; + +},{"../../../const":46,"../../../math":70,"../../../settings":101,"pixi-gl-core":15}],97:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = checkMaxIfStatmentsInShader; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['precision mediump float;', 'void main(void){', 'float test = 0.1;', '%forloop%', 'gl_FragColor = vec4(0.0);', '}'].join('\n'); + +function checkMaxIfStatmentsInShader(maxIfs, gl) { + var createTempContext = !gl; + + if (maxIfs === 0) { + throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); + } + + if (createTempContext) { + var tinyCanvas = document.createElement('canvas'); + + tinyCanvas.width = 1; + tinyCanvas.height = 1; + + gl = _pixiGlCore2.default.createContext(tinyCanvas); + } + + var shader = gl.createShader(gl.FRAGMENT_SHADER); + + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = maxIfs / 2 | 0; + } else { + // valid! + break; + } + } + + if (createTempContext) { + // get rid of context + if (gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').loseContext(); + } + } + + return maxIfs; +} + +function generateIfTestSrc(maxIfs) { + var src = ''; + + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxIfs - 1) { + src += 'if(test == ' + i + '.0){}'; + } + } + + return src; +} + +},{"pixi-gl-core":15}],98:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLBlendModesToPixi; + +var _const = require('../../../const'); + +/** + * Maps gl blend combinations to WebGL. + * + * @memberof PIXI + * @function mapWebGLBlendModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {string[]} [array=[]] - The array to output into. + * @return {string[]} Mapped modes. + */ +function mapWebGLBlendModesToPixi(gl) { + var array = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[_const.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD] = [gl.ONE, gl.ONE]; + array[_const.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + // not-premultiplied blend modes + array[_const.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[_const.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE]; + array[_const.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + + return array; +} + +},{"../../../const":46}],99:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapWebGLDrawModesToPixi; + +var _const = require('../../../const'); + +/** + * Generic Mask Stack data structure. + * + * @memberof PIXI + * @function mapWebGLDrawModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The current WebGL drawing context + * @param {object} [object={}] - The object to map into + * @return {object} The mapped draw modes. + */ +function mapWebGLDrawModesToPixi(gl) { + var object = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + object[_const.DRAW_MODES.POINTS] = gl.POINTS; + object[_const.DRAW_MODES.LINES] = gl.LINES; + object[_const.DRAW_MODES.LINE_LOOP] = gl.LINE_LOOP; + object[_const.DRAW_MODES.LINE_STRIP] = gl.LINE_STRIP; + object[_const.DRAW_MODES.TRIANGLES] = gl.TRIANGLES; + object[_const.DRAW_MODES.TRIANGLE_STRIP] = gl.TRIANGLE_STRIP; + object[_const.DRAW_MODES.TRIANGLE_FAN] = gl.TRIANGLE_FAN; + + return object; +} + +},{"../../../const":46}],100:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = validateContext; +function validateContext(gl) { + var attributes = gl.getContextAttributes(); + + // this is going to be fairly simple for now.. but at least we have room to grow! + if (!attributes.stencil) { + /* eslint-disable no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable no-console */ + } +} + +},{}],101:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _maxRecommendedTextures = require('./utils/maxRecommendedTextures'); + +var _maxRecommendedTextures2 = _interopRequireDefault(_maxRecommendedTextures); + +var _canUploadSameBuffer = require('./utils/canUploadSameBuffer'); + +var _canUploadSameBuffer2 = _interopRequireDefault(_canUploadSameBuffer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * User's customizable globals for overriding the default PIXI settings, such + * as a renderer's default resolution, framerate, float percision, etc. + * @example + * // Use the native window resolution as the default resolution + * // will support high-density displays when rendering + * PIXI.settings.RESOLUTION = window.devicePixelRatio. + * + * // Disable interpolation when scaling, will make texture be pixelated + * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; + * @namespace PIXI.settings + */ +exports.default = { + + /** + * Target frames per millisecond. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 0.06 + */ + TARGET_FPMS: 0.06, + + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * + * @static + * @memberof PIXI.settings + * @type {boolean} + * @default true + */ + MIPMAP_TEXTURES: true, + + /** + * Default resolution / device pixel ratio of the renderer. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + RESOLUTION: 1, + + /** + * Default filter resolution. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + FILTER_RESOLUTION: 1, + + /** + * The maximum textures that this device supports. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 32 + */ + SPRITE_MAX_TEXTURES: (0, _maxRecommendedTextures2.default)(32), + + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + + /** + * The prefix that denotes a URL is for a retina asset. + * + * @static + * @memberof PIXI.settings + * @type {RegExp} + * @example `@2x` + * @default /@([0-9\.]+)x/ + */ + RETINA_PREFIX: /@([0-9\.]+)x/, + + /** + * The default render options if none are supplied to {@link PIXI.WebGLRenderer} + * or {@link PIXI.CanvasRenderer}. + * + * @static + * @constant + * @memberof PIXI.settings + * @type {object} + * @property {HTMLCanvasElement} view=null + * @property {number} resolution=1 + * @property {boolean} antialias=false + * @property {boolean} forceFXAA=false + * @property {boolean} autoResize=false + * @property {boolean} transparent=false + * @property {number} backgroundColor=0x000000 + * @property {boolean} clearBeforeRender=true + * @property {boolean} preserveDrawingBuffer=false + * @property {boolean} roundPixels=false + * @property {number} width=800 + * @property {number} height=600 + * @property {boolean} legacy=false + */ + RENDER_OPTIONS: { + view: null, + antialias: false, + forceFXAA: false, + autoResize: false, + transparent: false, + backgroundColor: 0x000000, + clearBeforeRender: true, + preserveDrawingBuffer: false, + roundPixels: false, + width: 800, + height: 600, + legacy: false + }, + + /** + * Default transform type. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.TRANSFORM_MODE} + * @default PIXI.TRANSFORM_MODE.STATIC + */ + TRANSFORM_MODE: 0, + + /** + * Default Garbage Collection mode. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO + */ + GC_MODE: 0, + + /** + * Default Garbage Collection max idle. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 3600 + */ + GC_MAX_IDLE: 60 * 60, + + /** + * Default Garbage Collection maximum check count. + * + * @static + * @memberof PIXI.settings + * @type {number} + * @default 600 + */ + GC_MAX_CHECK_COUNT: 60 * 10, + + /** + * Default wrap modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP + */ + WRAP_MODE: 0, + + /** + * The scale modes that are supported by pixi. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR + */ + SCALE_MODE: 0, + + /** + * Default specify float precision in vertex shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.HIGH + */ + PRECISION_VERTEX: 'highp', + + /** + * Default specify float precision in fragment shader. + * + * @static + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM + */ + PRECISION_FRAGMENT: 'mediump', + + /** + * Can we upload the same buffer in a single frame? + * + * @static + * @constant + * @memberof PIXI.settings + * @type {boolean} + */ + CAN_UPLOAD_SAME_BUFFER: (0, _canUploadSameBuffer2.default)(), + + /** + * Default Mesh `canvasPadding`. + * + * @see PIXI.mesh.Mesh#canvasPadding + * @static + * @constant + * @memberof PIXI.settings + * @type {number} + */ + MESH_CANVAS_PADDING: 0 +}; + +},{"./utils/canUploadSameBuffer":122,"./utils/maxRecommendedTextures":127}],102:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _Container2 = require('../display/Container'); + +var _Container3 = _interopRequireDefault(_Container2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new _math.Point(); + +/** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = new PIXI.Sprite.fromImage('assets/image.png'); + * ``` + * + * The more efficient way to create sprites is using a {@link PIXI.Spritesheet}: + * + * ```js + * PIXI.loader.add("assets/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.loader.resources["assets/spritesheet.json"].spritesheet; + * let sprite = new PIXI.Sprite(sheet.textures["image.png"]); + * ... + * } + * ``` + * + * @class + * @extends PIXI.Container + * @memberof PIXI + */ + +var Sprite = function (_Container) { + _inherits(Sprite, _Container); + + /** + * @param {PIXI.Texture} texture - The texture for this sprite + */ + function Sprite(texture) { + _classCallCheck(this, Sprite); + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 or taken from the {@link PIXI.Texture#defaultAnchor|Texture} + * passed to the constructor. A value of 0,0 means the texture's origin is the top left. + * Setting the anchor to 0.5,0.5 means the texture's origin is centered. + * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner. + * Note: Updating the {@link PIXI.Texture#defaultAnchor} after a Texture is + * created does _not_ update the Sprite's anchor values. + * + * @member {PIXI.ObservablePoint} + * @private + */ + var _this = _possibleConstructorReturn(this, _Container.call(this)); + + _this._anchor = new _math.ObservablePoint(_this._onAnchorUpdate, _this, texture ? texture.defaultAnchor.x : 0, texture ? texture.defaultAnchor.y : 0); + + /** + * The texture that the sprite is using + * + * @private + * @member {PIXI.Texture} + */ + _this._texture = null; + + /** + * The width of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._width = 0; + + /** + * The height of the sprite (this is initially set by the texture) + * + * @private + * @member {number} + */ + _this._height = 0; + + /** + * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = null; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = _const.BLEND_MODES.NORMAL; + + /** + * The shader that will be used to render the sprite. Set to null to remove a current shader. + * + * @member {PIXI.Filter|PIXI.Shader} + */ + _this.shader = null; + + /** + * An internal cached value of the tint. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this.cachedTint = 0xFFFFFF; + + // call texture setter + _this.texture = texture || _Texture2.default.EMPTY; + + /** + * this is used to store the vertex data of the sprite (basically a quad) + * + * @private + * @member {Float32Array} + */ + _this.vertexData = new Float32Array(8); + + /** + * This is used to calculate the bounds of the object IF it is a trimmed sprite + * + * @private + * @member {Float32Array} + */ + _this.vertexTrimmedData = null; + + _this._transformID = -1; + _this._textureID = -1; + + _this._transformTrimmedID = -1; + _this._textureTrimmedID = -1; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * + * @member {string} + * @default 'sprite' + */ + _this.pluginName = 'sprite'; + return _this; + } + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Sprite.prototype._onTextureUpdate = function _onTextureUpdate() { + this._textureID = -1; + this._textureTrimmedID = -1; + this.cachedTint = 0xFFFFFF; + + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = (0, _utils.sign)(this.scale.x) * this._width / this._texture.orig.width; + } + + if (this._height) { + this.scale.y = (0, _utils.sign)(this.scale.y) * this._height / this._texture.orig.height; + } + }; + + /** + * Called when the anchor position updates. + * + * @private + */ + + + Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate() { + this._transformID = -1; + this._transformTrimmedID = -1; + }; + + /** + * calculates worldTransform * vertices, store it in vertexData + */ + + + Sprite.prototype.calculateVertices = function calculateVertices() { + if (this._transformID === this.transform._worldID && this._textureID === this._texture._updateID) { + return; + } + + this._transformID = this.transform._worldID; + this._textureID = this._texture._updateID; + + // set the vertex data + + var texture = this._texture; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var anchor = this._anchor; + + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - anchor._x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - anchor._y * orig.height; + h0 = h1 + trim.height; + } else { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData + * This is used to ensure that the true width and height of a trimmed texture is respected + */ + + + Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices() { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { + return; + } + + this._transformTrimmedID = this.transform._worldID; + this._textureTrimmedID = this._texture._updateID; + + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + var anchor = this._anchor; + + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + + var w1 = -anchor._x * orig.width; + var w0 = w1 + orig.width; + + var h1 = -anchor._y * orig.height; + var h0 = h1 + orig.height; + + // xy + vertexData[0] = a * w1 + c * h1 + tx; + vertexData[1] = d * h1 + b * w1 + ty; + + // xy + vertexData[2] = a * w0 + c * h1 + tx; + vertexData[3] = d * h1 + b * w0 + ty; + + // xy + vertexData[4] = a * w0 + c * h0 + tx; + vertexData[5] = d * h0 + b * w0 + ty; + + // xy + vertexData[6] = a * w1 + c * h0 + tx; + vertexData[7] = d * h0 + b * w1 + ty; + }; + + /** + * + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer to use. + */ + + + Sprite.prototype._renderWebGL = function _renderWebGL(renderer) { + this.calculateVertices(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Sprite.prototype._renderCanvas = function _renderCanvas(renderer) { + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Updates the bounds of the sprite. + * + * @private + */ + + + Sprite.prototype._calculateBounds = function _calculateBounds() { + var trim = this._texture.trim; + var orig = this._texture.orig; + + // First lets check to see if the current texture has a trim.. + if (!trim || trim.width === orig.width && trim.height === orig.height) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + Sprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._texture.orig.width * -this._anchor._x; + this._bounds.minY = this._texture.orig.height * -this._anchor._y; + this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x); + this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._y); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new _math.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _Container.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Tests if a point is inside this sprite + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Sprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + y1 = -height * this.anchor.y; + + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + Sprite.prototype.destroy = function destroy(options) { + _Container.prototype.destroy.call(this, options); + + this._texture.off('update', this._onTextureUpdate, this); + + this._anchor = null; + + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + + this._texture.destroy(!!destroyBaseTexture); + } + + this._texture = null; + this.shader = null; + }; + + // some helper functions.. + + /** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from + * @return {PIXI.Sprite} The newly created sprite + */ + + + Sprite.from = function from(source) { + return new Sprite(_Texture2.default.from(source)); + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the frameId + */ + + + Sprite.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return new Sprite(texture); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.Sprite} A new Sprite using a texture from the texture cache matching the image id + */ + + + Sprite.fromImage = function fromImage(imageId, crossorigin, scaleMode) { + return new Sprite(_Texture2.default.fromImage(imageId, crossorigin, scaleMode)); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Sprite, [{ + key: 'width', + get: function get() { + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * The anchor sets the origin point of the texture. + * The default is 0,0 or taken from the {@link PIXI.Texture|Texture} passed to the constructor. + * Setting the texture at a later point of time does not change the anchor. + * + * 0,0 means the texture's origin is the top left, 0.5,0.5 is the center, 1,1 the bottom right corner. + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._anchor.copy(value); + } + + /** + * The tint applied to the sprite. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + } + + /** + * The texture that the sprite is using + * + * @member {PIXI.Texture} + */ + + }, { + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value || _Texture2.default.EMPTY; + this.cachedTint = 0xFFFFFF; + + this._textureID = -1; + this._textureTrimmedID = -1; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + }]); + + return Sprite; +}(_Container3.default); + +exports.default = Sprite; + +},{"../const":46,"../display/Container":48,"../math":70,"../textures/Texture":115,"../utils":125}],103:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _CanvasRenderer = require('../../renderers/canvas/CanvasRenderer'); + +var _CanvasRenderer2 = _interopRequireDefault(_CanvasRenderer); + +var _const = require('../../const'); + +var _math = require('../../math'); + +var _CanvasTinter = require('./CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var canvasRenderWorldTransform = new _math.Matrix(); + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's CanvasSpriteRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/CanvasSpriteRenderer.java + */ + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + */ + +var CanvasSpriteRenderer = function () { + /** + * @param {PIXI.WebGLRenderer} renderer -The renderer sprite this batch works for. + */ + function CanvasSpriteRenderer(renderer) { + _classCallCheck(this, CanvasSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + CanvasSpriteRenderer.prototype.render = function render(sprite) { + var texture = sprite._texture; + var renderer = this.renderer; + + var width = texture._frame.width; + var height = texture._frame.height; + + var wt = sprite.transform.worldTransform; + var dx = 0; + var dy = 0; + + if (texture.orig.width <= 0 || texture.orig.height <= 0 || !texture.baseTexture.source) { + return; + } + + renderer.setBlendMode(sprite.blendMode); + + // Ignore null sources + if (texture.valid) { + renderer.context.globalAlpha = sprite.worldAlpha; + + // If smoothingEnabled is supported and we need to change the smoothing property for sprite texture + var smoothingEnabled = texture.baseTexture.scaleMode === _const.SCALE_MODES.LINEAR; + + if (renderer.smoothProperty && renderer.context[renderer.smoothProperty] !== smoothingEnabled) { + renderer.context[renderer.smoothProperty] = smoothingEnabled; + } + + if (texture.trim) { + dx = texture.trim.width / 2 + texture.trim.x - sprite.anchor.x * texture.orig.width; + dy = texture.trim.height / 2 + texture.trim.y - sprite.anchor.y * texture.orig.height; + } else { + dx = (0.5 - sprite.anchor.x) * texture.orig.width; + dy = (0.5 - sprite.anchor.y) * texture.orig.height; + } + + if (texture.rotate) { + wt.copy(canvasRenderWorldTransform); + wt = canvasRenderWorldTransform; + _math.GroupD8.matrixAppendRotationInv(wt, texture.rotate, dx, dy); + // the anchor has already been applied above, so lets set it to zero + dx = 0; + dy = 0; + } + + dx -= width / 2; + dy -= height / 2; + + // Allow for pixel rounding + if (renderer.roundPixels || sprite.roundPixels) { // #CUSTOM + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution | 0, wt.ty * renderer.resolution | 0); + + dx = dx | 0; + dy = dy | 0; + } else { + renderer.context.setTransform(wt.a, wt.b, wt.c, wt.d, wt.tx * renderer.resolution, wt.ty * renderer.resolution); + } + + var resolution = texture.baseTexture.resolution; + + if (sprite.tint !== 0xFFFFFF) { + if (sprite.cachedTint !== sprite.tint || sprite.tintedTexture.tintId !== sprite._texture._updateID) { + sprite.cachedTint = sprite.tint; + + // TODO clean up caching - how to clean up the caches? + sprite.tintedTexture = _CanvasTinter2.default.getTintedTexture(sprite, sprite.tint); + } + + renderer.context.drawImage(sprite.tintedTexture, 0, 0, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } else { + renderer.context.drawImage(texture.baseTexture.source, texture._frame.x * resolution, texture._frame.y * resolution, width * resolution, height * resolution, dx * renderer.resolution, dy * renderer.resolution, width * renderer.resolution, height * renderer.resolution); + } + } + }; + + /** + * destroy the sprite object. + * + */ + + + CanvasSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return CanvasSpriteRenderer; +}(); + +exports.default = CanvasSpriteRenderer; + + +_CanvasRenderer2.default.registerPlugin('sprite', CanvasSpriteRenderer); + +},{"../../const":46,"../../math":70,"../../renderers/canvas/CanvasRenderer":77,"./CanvasTinter":104}],104:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../../utils'); + +var _canUseNewCanvasBlendModes = require('../../renderers/canvas/utils/canUseNewCanvasBlendModes'); + +var _canUseNewCanvasBlendModes2 = _interopRequireDefault(_canUseNewCanvasBlendModes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Utility methods for Sprite/Texture tinting. + * + * @class + * @memberof PIXI + */ +var CanvasTinter = { + /** + * Basically this method just needs a sprite and a color and tints the sprite with the given color. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Sprite} sprite - the sprite to tint + * @param {number} color - the color to use to tint the sprite with + * @return {HTMLCanvasElement} The tinted canvas + */ + getTintedTexture: function getTintedTexture(sprite, color) { + var texture = sprite._texture; + + color = CanvasTinter.roundColor(color); + + var stringColor = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + texture.tintCache = texture.tintCache || {}; + + var cachedTexture = texture.tintCache[stringColor]; + + var canvas = void 0; + + if (cachedTexture) { + if (cachedTexture.tintId === texture._updateID) { + return texture.tintCache[stringColor]; + } + + canvas = texture.tintCache[stringColor]; + } else { + canvas = CanvasTinter.canvas || document.createElement('canvas'); + } + + CanvasTinter.tintMethod(texture, color, canvas); + + canvas.tintId = texture._updateID; + + if (CanvasTinter.convertTintToImage) { + // is this better? + var tintImage = new Image(); + + tintImage.src = canvas.toDataURL(); + + texture.tintCache[stringColor] = tintImage; + } else { + texture.tintCache[stringColor] = canvas; + // if we are not converting the texture to an image then we need to lose the reference to the canvas + CanvasTinter.canvas = null; + } + + return canvas; + }, + + /** + * Tint a texture using the 'multiply' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithMultiply: function tintWithMultiply(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.save(); + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'multiply'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + context.restore(); + }, + + /** + * Tint a texture using the 'overlay' operation. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithOverlay: function tintWithOverlay(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.save(); + context.globalCompositeOperation = 'copy'; + context.fillStyle = '#' + ('00000' + (color | 0).toString(16)).substr(-6); + context.fillRect(0, 0, crop.width, crop.height); + + context.globalCompositeOperation = 'destination-atop'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + + // context.globalCompositeOperation = 'copy'; + context.restore(); + }, + + + /** + * Tint a texture pixel per pixel. + * + * @memberof PIXI.CanvasTinter + * @param {PIXI.Texture} texture - the texture to tint + * @param {number} color - the color to use to tint the sprite with + * @param {HTMLCanvasElement} canvas - the current canvas + */ + tintWithPerPixel: function tintWithPerPixel(texture, color, canvas) { + var context = canvas.getContext('2d'); + var crop = texture._frame.clone(); + var resolution = texture.baseTexture.resolution; + + crop.x *= resolution; + crop.y *= resolution; + crop.width *= resolution; + crop.height *= resolution; + + canvas.width = Math.ceil(crop.width); + canvas.height = Math.ceil(crop.height); + + context.save(); + context.globalCompositeOperation = 'copy'; + context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height); + context.restore(); + + var rgbValues = (0, _utils.hex2rgb)(color); + var r = rgbValues[0]; + var g = rgbValues[1]; + var b = rgbValues[2]; + + var pixelData = context.getImageData(0, 0, crop.width, crop.height); + + var pixels = pixelData.data; + + for (var i = 0; i < pixels.length; i += 4) { + pixels[i + 0] *= r; + pixels[i + 1] *= g; + pixels[i + 2] *= b; + } + + context.putImageData(pixelData, 0, 0); + }, + + /** + * Rounds the specified color according to the CanvasTinter.cacheStepsPerColorChannel. + * + * @memberof PIXI.CanvasTinter + * @param {number} color - the color to round, should be a hex color + * @return {number} The rounded color. + */ + roundColor: function roundColor(color) { + var step = CanvasTinter.cacheStepsPerColorChannel; + + var rgbValues = (0, _utils.hex2rgb)(color); + + rgbValues[0] = Math.min(255, rgbValues[0] / step * step); + rgbValues[1] = Math.min(255, rgbValues[1] / step * step); + rgbValues[2] = Math.min(255, rgbValues[2] / step * step); + + return (0, _utils.rgb2hex)(rgbValues); + }, + + /** + * Number of steps which will be used as a cap when rounding colors. + * + * @memberof PIXI.CanvasTinter + * @type {number} + */ + cacheStepsPerColorChannel: 8, + + /** + * Tint cache boolean flag. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + convertTintToImage: false, + + /** + * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method. + * + * @memberof PIXI.CanvasTinter + * @type {boolean} + */ + canUseMultiply: (0, _canUseNewCanvasBlendModes2.default)(), + + /** + * The tinting method that will be used. + * + * @memberof PIXI.CanvasTinter + * @type {tintMethodFunctionType} + */ + tintMethod: 0 +}; + +CanvasTinter.tintMethod = CanvasTinter.canUseMultiply ? CanvasTinter.tintWithMultiply : CanvasTinter.tintWithPerPixel; + +/** + * The tintMethod type. + * + * @memberof PIXI.CanvasTinter + * @callback tintMethodFunctionType + * @param texture {PIXI.Texture} the texture to tint + * @param color {number} the color to use to tint the sprite with + * @param canvas {HTMLCanvasElement} the current canvas + */ + +exports.default = CanvasTinter; + +},{"../../renderers/canvas/utils/canUseNewCanvasBlendModes":80,"../../utils":125}],105:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @class + * @memberof PIXI + */ +var Buffer = function () { + /** + * @param {number} size - The size of the buffer in bytes. + */ + function Buffer(size) { + _classCallCheck(this, Buffer); + + this.vertices = new ArrayBuffer(size); + + /** + * View on the vertices as a Float32Array for positions + * + * @member {Float32Array} + */ + this.float32View = new Float32Array(this.vertices); + + /** + * View on the vertices as a Uint32Array for uvs + * + * @member {Float32Array} + */ + this.uint32View = new Uint32Array(this.vertices); + } + + /** + * Destroys the buffer. + * + */ + + + Buffer.prototype.destroy = function destroy() { + this.vertices = null; + this.positions = null; + this.uvs = null; + this.colors = null; + }; + + return Buffer; +}(); + +exports.default = Buffer; + +},{}],106:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ObjectRenderer2 = require('../../renderers/webgl/utils/ObjectRenderer'); + +var _ObjectRenderer3 = _interopRequireDefault(_ObjectRenderer2); + +var _WebGLRenderer = require('../../renderers/webgl/WebGLRenderer'); + +var _WebGLRenderer2 = _interopRequireDefault(_WebGLRenderer); + +var _createIndicesForQuads = require('../../utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +var _generateMultiTextureShader = require('./generateMultiTextureShader'); + +var _generateMultiTextureShader2 = _interopRequireDefault(_generateMultiTextureShader); + +var _checkMaxIfStatmentsInShader = require('../../renderers/webgl/utils/checkMaxIfStatmentsInShader'); + +var _checkMaxIfStatmentsInShader2 = _interopRequireDefault(_checkMaxIfStatmentsInShader); + +var _BatchBuffer = require('./BatchBuffer'); + +var _BatchBuffer2 = _interopRequireDefault(_BatchBuffer); + +var _settings = require('../../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _utils = require('../../utils'); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var TICK = 0; +var TEXTURE_TICK = 0; + +/** + * Renderer dedicated to drawing and batching sprites. + * + * @class + * @private + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var SpriteRenderer = function (_ObjectRenderer) { + _inherits(SpriteRenderer, _ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function SpriteRenderer(renderer) { + _classCallCheck(this, SpriteRenderer); + + /** + * Number of values sent in the vertex buffer. + * aVertexPosition(2), aTextureCoord(1), aColor(1), aTextureId(1) = 5 + * + * @member {number} + */ + var _this = _possibleConstructorReturn(this, _ObjectRenderer.call(this, renderer)); + + _this.vertSize = 5; + + /** + * The size of the vertex information in bytes. + * + * @member {number} + */ + _this.vertByteSize = _this.vertSize * 4; + + /** + * The number of images in the SpriteRenderer before it flushes. + * + * @member {number} + */ + _this.size = _settings2.default.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop + + // the total number of bytes in our batch + // let numVerts = this.size * 4 * this.vertByteSize; + + _this.buffers = []; + for (var i = 1; i <= _bitTwiddle2.default.nextPow2(_this.size); i *= 2) { + _this.buffers.push(new _BatchBuffer2.default(i * 4 * _this.vertByteSize)); + } + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + _this.indices = (0, _createIndicesForQuads2.default)(_this.size); + + /** + * The default shaders that is used if a sprite doesn't have a more specific one. + * there is a shader for each number of textures that can be rendererd. + * These shaders will also be generated on the fly as required. + * @member {PIXI.Shader[]} + */ + _this.shader = null; + + _this.currentIndex = 0; + _this.groups = []; + + for (var k = 0; k < _this.size; k++) { + _this.groups[k] = { textures: [], textureCount: 0, ids: [], size: 0, start: 0, blend: 0 }; + } + + _this.sprites = []; + + _this.vertexBuffers = []; + _this.vaos = []; + + _this.vaoMax = 2; + _this.vertexCount = 0; + + _this.renderer.on('prerender', _this.onPrerender, _this); + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + SpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + if (this.renderer.legacy) { + this.MAX_TEXTURES = 1; + } else { + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), _settings2.default.SPRITE_MAX_TEXTURES); + + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = (0, _checkMaxIfStatmentsInShader2.default)(this.MAX_TEXTURES, gl); + } + + this.shader = (0, _generateMultiTextureShader2.default)(gl, this.MAX_TEXTURES); + + // create a couple of buffers + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + // we use the second shader as the first one depending on your browser may omit aTextureId + // as it is not used by the shader so is optimized out. + + this.renderer.bindVao(null); + + var attrs = this.shader.attributes; + + for (var i = 0; i < this.vaoMax; i++) { + /* eslint-disable max-len */ + var vertexBuffer = this.vertexBuffers[i] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + /* eslint-enable max-len */ + + // build the vao object that will render.. + var vao = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (attrs.aTextureId) { + vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vaos[i] = vao; + } + + this.vao = this.vaos[0]; + this.currentBlendMode = 99999; + + this.boundTextures = new Array(this.MAX_TEXTURES); + }; + + /** + * Called before the renderer starts rendering. + * + */ + + + SpriteRenderer.prototype.onPrerender = function onPrerender() { + this.vertexCount = 0; + }; + + /** + * Renders the sprite object. + * + * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch + */ + + + SpriteRenderer.prototype.render = function render(sprite) { + // TODO set blend modes.. + // check texture.. + if (this.currentIndex >= this.size) { + this.flush(); + } + + // get the uvs for the texture + + // if the uvs have not updated then no point rendering just yet! + if (!sprite._texture._uvs) { + return; + } + + // push a texture. + // increment the batchsize + this.sprites[this.currentIndex++] = sprite; + }; + + /** + * Renders the content and empties the current batch. + * + */ + + + SpriteRenderer.prototype.flush = function flush() { + if (this.currentIndex === 0) { + return; + } + + var gl = this.renderer.gl; + var MAX_TEXTURES = this.MAX_TEXTURES; + + var np2 = _bitTwiddle2.default.nextPow2(this.currentIndex); + var log2 = _bitTwiddle2.default.log2(np2); + var buffer = this.buffers[log2]; + + var sprites = this.sprites; + var groups = this.groups; + + var float32View = buffer.float32View; + var uint32View = buffer.uint32View; + + var boundTextures = this.boundTextures; + var rendererBoundTextures = this.renderer.boundTextures; + var touch = this.renderer.textureGC.count; + + var index = 0; + var nextTexture = void 0; + var currentTexture = void 0; + var groupCount = 1; + var textureCount = 0; + var currentGroup = groups[0]; + var vertexData = void 0; + var uvs = void 0; + var blendMode = _utils.premultiplyBlendMode[sprites[0]._texture.baseTexture.premultipliedAlpha ? 1 : 0][sprites[0].blendMode]; + + currentGroup.textureCount = 0; + currentGroup.start = 0; + currentGroup.blend = blendMode; + + TICK++; + + var i = void 0; + + // copy textures.. + for (i = 0; i < MAX_TEXTURES; ++i) { + var bt = rendererBoundTextures[i]; + + if (bt._enabled === TICK) { + boundTextures[i] = this.renderer.emptyTextures[i]; + continue; + } + + boundTextures[i] = bt; + bt._virtalBoundId = i; + bt._enabled = TICK; + } + TICK++; + + for (i = 0; i < this.currentIndex; ++i) { + // upload the sprite elemetns... + // they have all ready been calculated so we just need to push them into the buffer. + var sprite = sprites[i]; + + sprites[i] = null; + + nextTexture = sprite._texture.baseTexture; + + var spriteBlendMode = _utils.premultiplyBlendMode[Number(nextTexture.premultipliedAlpha)][sprite.blendMode]; + + if (blendMode !== spriteBlendMode) { + // finish a group.. + blendMode = spriteBlendMode; + + // force the batch to break! + currentTexture = null; + textureCount = MAX_TEXTURES; + TICK++; + } + + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + + if (nextTexture._enabled !== TICK) { + if (textureCount === MAX_TEXTURES) { + TICK++; + + currentGroup.size = i - currentGroup.start; + + textureCount = 0; + + currentGroup = groups[groupCount++]; + currentGroup.blend = blendMode; + currentGroup.textureCount = 0; + currentGroup.start = i; + } + + nextTexture.touched = touch; + + if (nextTexture._virtalBoundId === -1) { + for (var j = 0; j < MAX_TEXTURES; ++j) { + var tIndex = (j + TEXTURE_TICK) % MAX_TEXTURES; + + var t = boundTextures[tIndex]; + + if (t._enabled !== TICK) { + TEXTURE_TICK++; + + t._virtalBoundId = -1; + + nextTexture._virtalBoundId = tIndex; + + boundTextures[tIndex] = nextTexture; + break; + } + } + } + + nextTexture._enabled = TICK; + + currentGroup.textureCount++; + currentGroup.ids[textureCount] = nextTexture._virtalBoundId; + currentGroup.textures[textureCount++] = nextTexture; + } + } + + vertexData = sprite.vertexData; + + // TODO this sum does not need to be set each frame.. + uvs = sprite._texture._uvs.uvsUint32; + + if (this.renderer.roundPixels || sprite.roundPixels) { // #CUSTOM + var resolution = this.renderer.resolution; + + // xy + float32View[index] = (vertexData[0] * resolution | 0) / resolution; + float32View[index + 1] = (vertexData[1] * resolution | 0) / resolution; + + // xy + float32View[index + 5] = (vertexData[2] * resolution | 0) / resolution; + float32View[index + 6] = (vertexData[3] * resolution | 0) / resolution; + + // xy + float32View[index + 10] = (vertexData[4] * resolution | 0) / resolution; + float32View[index + 11] = (vertexData[5] * resolution | 0) / resolution; + + // xy + float32View[index + 15] = (vertexData[6] * resolution | 0) / resolution; + float32View[index + 16] = (vertexData[7] * resolution | 0) / resolution; + } else { + // xy + float32View[index] = vertexData[0]; + float32View[index + 1] = vertexData[1]; + + // xy + float32View[index + 5] = vertexData[2]; + float32View[index + 6] = vertexData[3]; + + // xy + float32View[index + 10] = vertexData[4]; + float32View[index + 11] = vertexData[5]; + + // xy + float32View[index + 15] = vertexData[6]; + float32View[index + 16] = vertexData[7]; + } + + uint32View[index + 2] = uvs[0]; + uint32View[index + 7] = uvs[1]; + uint32View[index + 12] = uvs[2]; + uint32View[index + 17] = uvs[3]; + /* eslint-disable max-len */ + var alpha = Math.min(sprite.worldAlpha, 1.0); + // we dont call extra function if alpha is 1.0, that's faster + var argb = alpha < 1.0 && nextTexture.premultipliedAlpha ? (0, _utils.premultiplyTint)(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); + + uint32View[index + 3] = uint32View[index + 8] = uint32View[index + 13] = uint32View[index + 18] = argb; + float32View[index + 4] = float32View[index + 9] = float32View[index + 14] = float32View[index + 19] = nextTexture._virtalBoundId; + /* eslint-enable max-len */ + + index += 20; + } + + currentGroup.size = i - currentGroup.start; + + if (!_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // this is still needed for IOS performance.. + // it really does not like uploading to the same buffer in a single frame! + if (this.vaoMax <= this.vertexCount) { + this.vaoMax++; + + var attrs = this.shader.attributes; + + /* eslint-disable max-len */ + var vertexBuffer = this.vertexBuffers[this.vertexCount] = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, null, gl.STREAM_DRAW); + /* eslint-enable max-len */ + + // build the vao object that will render.. + var vao = this.renderer.createVao().addIndex(this.indexBuffer).addAttribute(vertexBuffer, attrs.aVertexPosition, gl.FLOAT, false, this.vertByteSize, 0).addAttribute(vertexBuffer, attrs.aTextureCoord, gl.UNSIGNED_SHORT, true, this.vertByteSize, 2 * 4).addAttribute(vertexBuffer, attrs.aColor, gl.UNSIGNED_BYTE, true, this.vertByteSize, 3 * 4); + + if (attrs.aTextureId) { + vao.addAttribute(vertexBuffer, attrs.aTextureId, gl.FLOAT, false, this.vertByteSize, 4 * 4); + } + + this.vaos[this.vertexCount] = vao; + } + + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, false); + + this.vertexCount++; + } else { + // lets use the faster option, always use buffer number 0 + this.vertexBuffers[this.vertexCount].upload(buffer.vertices, 0, true); + } + + for (i = 0; i < MAX_TEXTURES; ++i) { + rendererBoundTextures[i]._virtalBoundId = -1; + } + + // render the groups.. + for (i = 0; i < groupCount; ++i) { + var group = groups[i]; + var groupTextureCount = group.textureCount; + + for (var _j = 0; _j < groupTextureCount; _j++) { + currentTexture = group.textures[_j]; + + // reset virtual ids.. + // lets do a quick check.. + if (rendererBoundTextures[group.ids[_j]] !== currentTexture) { + this.renderer.bindTexture(currentTexture, group.ids[_j], true); + } + + // reset the virtualId.. + currentTexture._virtalBoundId = -1; + } + + // set the blend mode.. + this.renderer.state.setBlendMode(group.blend); + + gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); + } + + // reset elements for the next flush + this.currentIndex = 0; + }; + + /** + * Starts a new sprite batch. + */ + + + SpriteRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + + if (_settings2.default.CAN_UPLOAD_SAME_BUFFER) { + // bind buffer #0, we don't need others + this.renderer.bindVao(this.vaos[this.vertexCount]); + + this.vertexBuffers[this.vertexCount].bind(); + } + }; + + /** + * Stops and flushes the current batch. + * + */ + + + SpriteRenderer.prototype.stop = function stop() { + this.flush(); + }; + + /** + * Destroys the SpriteRenderer. + * + */ + + + SpriteRenderer.prototype.destroy = function destroy() { + for (var i = 0; i < this.vaoMax; i++) { + if (this.vertexBuffers[i]) { + this.vertexBuffers[i].destroy(); + } + if (this.vaos[i]) { + this.vaos[i].destroy(); + } + } + + if (this.indexBuffer) { + this.indexBuffer.destroy(); + } + + this.renderer.off('prerender', this.onPrerender, this); + + _ObjectRenderer.prototype.destroy.call(this); + + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } + + this.vertexBuffers = null; + this.vaos = null; + this.indexBuffer = null; + this.indices = null; + + this.sprites = null; + + for (var _i = 0; _i < this.buffers.length; ++_i) { + this.buffers[_i].destroy(); + } + }; + + return SpriteRenderer; +}(_ObjectRenderer3.default); + +exports.default = SpriteRenderer; + + +_WebGLRenderer2.default.registerPlugin('sprite', SpriteRenderer); + +},{"../../renderers/webgl/WebGLRenderer":84,"../../renderers/webgl/utils/ObjectRenderer":94,"../../renderers/webgl/utils/checkMaxIfStatmentsInShader":97,"../../settings":101,"../../utils":125,"../../utils/createIndicesForQuads":123,"./BatchBuffer":105,"./generateMultiTextureShader":107,"bit-twiddle":1,"pixi-gl-core":15}],107:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateMultiTextureShader; + +var _Shader = require('../../Shader'); + +var _Shader2 = _interopRequireDefault(_Shader); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var fragTemplate = ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'varying float vTextureId;', 'uniform sampler2D uSamplers[%count%];', 'void main(void){', 'vec4 color;', '%forloop%', 'gl_FragColor = color * vColor;', '}'].join('\n'); + +function generateMultiTextureShader(gl, maxTextures) { + var vertexSrc = 'precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor;\n}\n'; + var fragmentSrc = fragTemplate; + + fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); + + var shader = new _Shader2.default(gl, vertexSrc, fragmentSrc); + + var sampleValues = []; + + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + + shader.bind(); + shader.uniforms.uSamplers = sampleValues; + + return shader; +} + +function generateSampleSrc(maxTextures) { + var src = ''; + + src += '\n'; + src += '\n'; + + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + + if (i < maxTextures - 1) { + src += 'if(vTextureId < ' + i + '.5)'; + } + + src += '\n{'; + src += '\n\tcolor = texture2D(uSamplers[' + i + '], vTextureCoord);'; + src += '\n}'; + } + + src += '\n'; + src += '\n'; + + return src; +} + +},{"../../Shader":44,"path":8}],108:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Sprite2 = require('../sprites/Sprite'); + +var _Sprite3 = _interopRequireDefault(_Sprite2); + +var _Texture = require('../textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _TextStyle = require('./TextStyle'); + +var _TextStyle2 = _interopRequireDefault(_TextStyle); + +var _TextMetrics = require('./TextMetrics'); + +var _TextMetrics2 = _interopRequireDefault(_TextMetrics); + +var _trimCanvas = require('../utils/trimCanvas'); + +var _trimCanvas2 = _interopRequireDefault(_trimCanvas); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint max-depth: [2, 8] */ + + +var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true +}; + +/** + * A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string, + * or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object. + * + * A Text can be created directly from a string and a style object, + * which can be generated [here](https://pixijs.io/pixi-text-style). + * + * ```js + * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI + */ + +var Text = function (_Sprite) { + _inherits(Text, _Sprite); + + /** + * @param {string} text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + * @param {HTMLCanvasElement} [canvas] - The canvas element for drawing text + */ + function Text(text, style, canvas) { + _classCallCheck(this, Text); + + canvas = canvas || document.createElement('canvas'); + + canvas.width = 3; + canvas.height = 3; + + var texture = _Texture2.default.fromCanvas(canvas, _settings2.default.SCALE_MODE, 'text'); + + texture.orig = new _math.Rectangle(); + texture.trim = new _math.Rectangle(); + + // base texture is already automatically added to the cache, now adding the actual texture + var _this = _possibleConstructorReturn(this, _Sprite.call(this, texture)); + + _Texture2.default.addToCache(_this._texture, _this._texture.baseTexture.textureCacheIds[0]); + + /** + * The canvas element that everything is drawn to + * + * @member {HTMLCanvasElement} + */ + _this.canvas = canvas; + + /** + * The canvas 2d context that everything is drawn with + * @member {CanvasRenderingContext2D} + */ + _this.context = _this.canvas.getContext('2d'); + + /** + * The resolution / device pixel ratio of the canvas. This is set automatically by the renderer. + * @member {number} + * @default 1 + */ + _this.resolution = _settings2.default.RESOLUTION; + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = null; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._style = null; + /** + * Private listener to track style changes. + * + * @member {Function} + * @private + */ + _this._styleListener = null; + + /** + * Private tracker for the current font. + * + * @member {string} + * @private + */ + _this._font = ''; + + _this.text = text; + _this.style = style; + + _this.localStyleID = -1; + return _this; + } + + /** + * Renders text and updates it when needed. + * + * @private + * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. + */ + + + Text.prototype.updateText = function updateText(respectDirty) { + var style = this._style; + + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + + if (!this.dirty && respectDirty) { + return; + } + + this._font = this._style.toFontString(); + + var context = this.context; + var measured = _TextMetrics2.default.measureText(this._text, this._style, this._style.wordWrap, this.canvas); + var width = measured.width; + var height = measured.height; + var lines = measured.lines; + var lineHeight = measured.lineHeight; + var lineWidths = measured.lineWidths; + var maxLineWidth = measured.maxLineWidth; + var fontProperties = measured.fontProperties; + + this.canvas.width = Math.ceil((Math.max(1, width) + style.padding * 2) * this.resolution); + this.canvas.height = Math.ceil((Math.max(1, height) + style.padding * 2) * this.resolution); + + context.scale(this.resolution, this.resolution); + + context.clearRect(0, 0, this.canvas.width, this.canvas.height); + + context.font = this._font; + context.strokeStyle = style.stroke; + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + + var linePositionX = void 0; + var linePositionY = void 0; + + if (style.dropShadow) { + context.fillStyle = style.dropShadowColor; + context.globalAlpha = style.dropShadowAlpha; + context.shadowBlur = style.dropShadowBlur; + + if (style.dropShadowBlur > 0) { + context.shadowColor = style.dropShadowColor; + } + + var xShadowOffset = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; + var yShadowOffset = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; + + for (var i = 0; i < lines.length; i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[i]) / 2; + } + + if (style.fill) { + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding); + + if (style.stroke && style.strokeThickness) { + context.strokeStyle = style.dropShadowColor; + this.drawLetterSpacing(lines[i], linePositionX + xShadowOffset + style.padding, linePositionY + yShadowOffset + style.padding, true); + context.strokeStyle = style.stroke; + } + } + } + } + + // reset the shadow blur and alpha that was set by the drop shadow, for the regular text + context.shadowBlur = 0; + context.globalAlpha = 1; + + // set canvas text styles + context.fillStyle = this._generateFillStyle(style, lines); + + // draw lines line by line + for (var _i = 0; _i < lines.length; _i++) { + linePositionX = style.strokeThickness / 2; + linePositionY = style.strokeThickness / 2 + _i * lineHeight + fontProperties.ascent; + + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[_i]; + } else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[_i]) / 2; + } + + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding, true); + } + + if (style.fill) { + this.drawLetterSpacing(lines[_i], linePositionX + style.padding, linePositionY + style.padding); + } + } + + this.updateTexture(); + }; + + /** + * Render the text with letter-spacing. + * @param {string} text - The text to draw + * @param {number} x - Horizontal position to draw the text + * @param {number} y - Vertical position to draw the text + * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + * @private + */ + + + Text.prototype.drawLetterSpacing = function drawLetterSpacing(text, x, y) { + var isStroke = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + var style = this._style; + + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + + if (letterSpacing === 0) { + if (isStroke) { + this.context.strokeText(text, x, y); + } else { + this.context.fillText(text, x, y); + } + + return; + } + + var characters = String.prototype.split.call(text, ''); + var currentPosition = x; + var index = 0; + var current = ''; + var previousWidth = this.context.measureText(text).width; + var currentWidth = 0; + + while (index < text.length) { + current = characters[index++]; + if (isStroke) { + this.context.strokeText(current, currentPosition, y); + } else { + this.context.fillText(current, currentPosition, y); + } + currentWidth = this.context.measureText(text.substring(index)).width; + currentPosition += previousWidth - currentWidth + letterSpacing; + previousWidth = currentWidth; + } + }; + + /** + * Updates texture size based on canvas size + * + * @private + */ + + + Text.prototype.updateTexture = function updateTexture() { + var canvas = this.canvas; + + if (this._style.trim) { + var trimmed = (0, _trimCanvas2.default)(canvas); + + if (trimmed.data) { + canvas.width = trimmed.width; + canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } + } + + var texture = this._texture; + var style = this._style; + var padding = style.trim ? 0 : style.padding; + var baseTexture = texture.baseTexture; + + baseTexture.hasLoaded = true; + baseTexture.resolution = this.resolution; + + baseTexture.realWidth = canvas.width; + baseTexture.realHeight = canvas.height; + baseTexture.width = canvas.width / this.resolution; + baseTexture.height = canvas.height / this.resolution; + + texture.trim.width = texture._frame.width = canvas.width / this.resolution; + texture.trim.height = texture._frame.height = canvas.height / this.resolution; + texture.trim.x = -padding; + texture.trim.y = -padding; + + texture.orig.width = texture._frame.width - padding * 2; + texture.orig.height = texture._frame.height - padding * 2; + + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + + baseTexture.emit('update', baseTexture); + + this.dirty = false; + }; + + /** + * Renders the object using the WebGL renderer + * + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + Text.prototype.renderWebGL = function renderWebGL(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype.renderWebGL.call(this, renderer); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The renderer + */ + + + Text.prototype._renderCanvas = function _renderCanvas(renderer) { + if (this.resolution !== renderer.resolution) { + this.resolution = renderer.resolution; + this.dirty = true; + } + + this.updateText(true); + + _Sprite.prototype._renderCanvas.call(this, renderer); + }; + + /** + * Gets the local bounds of the text object. + * + * @param {Rectangle} rect - The output rectangle. + * @return {Rectangle} The bounds. + */ + + + Text.prototype.getLocalBounds = function getLocalBounds(rect) { + this.updateText(true); + + return _Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. + */ + + + Text.prototype._calculateBounds = function _calculateBounds() { + this.updateText(true); + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; + + /** + * Method to be called upon a TextStyle change. + * @private + */ + + + Text.prototype._onStyleChange = function _onStyleChange() { + this.dirty = true; + }; + + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * + * @private + * @param {object} style - The style. + * @param {string[]} lines - The lines of text. + * @return {string|number|CanvasGradient} The fill style + */ + + + Text.prototype._generateFillStyle = function _generateFillStyle(style, lines) { + if (!Array.isArray(style.fill)) { + return style.fill; + } + + // cocoon on canvas+ cannot generate textures, so use the first colour instead + if (navigator.isCocoonJS) { + return style.fill[0]; + } + + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient = void 0; + var totalIterations = void 0; + var currentIteration = void 0; + var stop = void 0; + + var width = this.canvas.width / this.resolution; + var height = this.canvas.height / this.resolution; + + // make a copy of the style settings, so we can manipulate them later + var fill = style.fill.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(style.fill[0]); + fillGradientStops.unshift(0); + + fill.push(style.fill[style.fill.length - 1]); + fillGradientStops.push(1); + + if (style.fillGradientType === _const.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height); + + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + totalIterations = (fill.length + 1) * lines.length; + currentIteration = 0; + for (var _i2 = 0; _i2 < lines.length; _i2++) { + currentIteration += 1; + for (var j = 0; j < fill.length; j++) { + if (typeof fillGradientStops[j] === 'number') { + stop = fillGradientStops[j] / lines.length + _i2 / lines.length; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[j]); + currentIteration++; + } + } + } else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(0, height / 2, width, height / 2); + + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + totalIterations = fill.length + 1; + currentIteration = 1; + + for (var _i3 = 0; _i3 < fill.length; _i3++) { + if (typeof fillGradientStops[_i3] === 'number') { + stop = fillGradientStops[_i3]; + } else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[_i3]); + currentIteration++; + } + } + + return gradient; + }; + + /** + * Destroys this text object. + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majority of the time the texture will not be shared with any other Sprites. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well + */ + + + Text.prototype.destroy = function destroy(options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + + options = Object.assign({}, defaultDestroyOptions, options); + + _Sprite.prototype.destroy.call(this, options); + + // make sure to reset the the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + + this._style = null; + }; + + /** + * The width of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(Text, [{ + key: 'width', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.x) || 1; + + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + } + + /** + * The height of the Text, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + this.updateText(true); + + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.updateText(true); + + var s = (0, _utils.sign)(this.scale.y) || 1; + + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + } + + /** + * Set the style of the text. Set up an event listener to listen for changes on the style + * object and mark the text as dirty. + * + * @member {object|PIXI.TextStyle} + */ + + }, { + key: 'style', + get: function get() { + return this._style; + }, + set: function set(style) // eslint-disable-line require-jsdoc + { + style = style || {}; + + if (style instanceof _TextStyle2.default) { + this._style = style; + } else { + this._style = new _TextStyle2.default(style); + } + + this.localStyleID = -1; + this.dirty = true; + } + + /** + * Set the copy for the text object. To split a line you can use '\n'. + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(text) // eslint-disable-line require-jsdoc + { + text = String(text === '' || text === null || text === undefined ? ' ' : text); + + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + } + }]); + + return Text; +}(_Sprite3.default); + +exports.default = Text; + +},{"../const":46,"../math":70,"../settings":101,"../sprites/Sprite":102,"../textures/Texture":115,"../utils":125,"../utils/trimCanvas":130,"./TextMetrics":109,"./TextStyle":110}],109:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * The TextMetrics object represents the measurement of a block of text with a specified style. + * + * ```js + * let style = new PIXI.TextStyle({fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}) + * let textMetrics = PIXI.TextMetrics.measureText('Your text', style) + * ``` + * + * @class + * @memberOf PIXI + */ +var TextMetrics = function () { + /** + * @param {string} text - the text that was measured + * @param {PIXI.TextStyle} style - the style that was measured + * @param {number} width - the measured width of the text + * @param {number} height - the measured height of the text + * @param {array} lines - an array of the lines of text broken by new lines and wrapping if specified in style + * @param {array} lineWidths - an array of the line widths for each line matched to `lines` + * @param {number} lineHeight - the measured line height for this style + * @param {number} maxLineWidth - the maximum line width for all measured lines + * @param {Object} fontProperties - the font properties object from TextMetrics.measureFont + */ + function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) { + _classCallCheck(this, TextMetrics); + + this.text = text; + this.style = style; + this.width = width; + this.height = height; + this.lines = lines; + this.lineWidths = lineWidths; + this.lineHeight = lineHeight; + this.maxLineWidth = maxLineWidth; + this.fontProperties = fontProperties; + } + + /** + * Measures the supplied string of text and returns a Rectangle. + * + * @param {string} text - the text to measure. + * @param {PIXI.TextStyle} style - the text style to use for measuring + * @param {boolean} [wordWrap] - optional override for if word-wrap should be applied to the text. + * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. + * @return {PIXI.TextMetrics} measured width and height of the text. + */ + + + TextMetrics.measureText = function measureText(text, style, wordWrap) { + var canvas = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : TextMetrics._canvas; + + wordWrap = wordWrap === undefined || wordWrap === null ? style.wordWrap : wordWrap; + var font = style.toFontString(); + var fontProperties = TextMetrics.measureFont(font); + var context = canvas.getContext('2d'); + + context.font = font; + + var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text; + var lines = outputText.split(/(?:\r\n|\r|\n)/); + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + + for (var i = 0; i < lines.length; i++) { + var lineWidth = context.measureText(lines[i]).width + (lines[i].length - 1) * style.letterSpacing; + + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + var width = maxLineWidth + style.strokeThickness; + + if (style.dropShadow) { + width += style.dropShadowDistance; + } + + var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + (lines.length - 1) * (lineHeight + style.leading); + + if (style.dropShadow) { + height += style.dropShadowDistance; + } + + return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties); + }; + + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @private + * @param {string} text - String to apply word wrapping to + * @param {PIXI.TextStyle} style - the style to use when wrapping + * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. + * @return {string} New string with new lines applied where required + */ + + + TextMetrics.wordWrap = function wordWrap(text, style) { + var canvas = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : TextMetrics._canvas; + + var context = canvas.getContext('2d'); + + var width = 0; + var line = ''; + var lines = ''; + + var cache = {}; + var letterSpacing = style.letterSpacing, + whiteSpace = style.whiteSpace; + + // How to handle whitespaces + + var collapseSpaces = TextMetrics.collapseSpaces(whiteSpace); + var collapseNewlines = TextMetrics.collapseNewlines(whiteSpace); + + // whether or not spaces may be added to the beginning of lines + var canPrependSpaces = !collapseSpaces; + + // There is letterSpacing after every char except the last one + // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_! + // so for convenience the above needs to be compared to width + 1 extra letterSpace + // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_ + // ________________________________________________ + // And then the final space is simply no appended to each line + var wordWrapWidth = style.wordWrapWidth + letterSpacing; + + // break text into words, spaces and newline chars + var tokens = TextMetrics.tokenize(text); + + for (var i = 0; i < tokens.length; i++) { + // get the word, space or newlineChar + var token = tokens[i]; + + // if word is a new line + if (TextMetrics.isNewline(token)) { + // keep the new line + if (!collapseNewlines) { + lines += TextMetrics.addLine(line); + canPrependSpaces = !collapseSpaces; + line = ''; + width = 0; + continue; + } + + // if we should collapse new lines + // we simply convert it into a space + token = ' '; + } + + // if we should collapse repeated whitespaces + if (collapseSpaces) { + // check both this and the last tokens for spaces + var currIsBreakingSpace = TextMetrics.isBreakingSpace(token); + var lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]); + + if (currIsBreakingSpace && lastIsBreakingSpace) { + continue; + } + } + + // get word width from cache if possible + var tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context); + + // word is longer than desired bounds + if (tokenWidth > wordWrapWidth) { + // if we are not already at the beginning of a line + if (line !== '') { + // start newlines for overflow words + lines += TextMetrics.addLine(line); + line = ''; + width = 0; + } + + // break large word over multiple lines + if (TextMetrics.canBreakWords(token, style.breakWords)) { + // break word into characters + var characters = token.split(''); + + // loop the characters + for (var j = 0; j < characters.length; j++) { + var char = characters[j]; + + var k = 1; + // we are not at the end of the token + + while (characters[j + k]) { + var nextChar = characters[j + k]; + var lastChar = char[char.length - 1]; + + // should not split chars + if (!TextMetrics.canBreakChars(lastChar, nextChar, token, j, style.breakWords)) { + // combine chars & move forward one + char += nextChar; + } else { + break; + } + + k++; + } + + j += char.length - 1; + + var characterWidth = TextMetrics.getFromCache(char, letterSpacing, cache, context); + + if (characterWidth + width > wordWrapWidth) { + lines += TextMetrics.addLine(line); + canPrependSpaces = false; + line = ''; + width = 0; + } + + line += char; + width += characterWidth; + } + } + + // run word out of the bounds + else { + // if there are words in this line already + // finish that line and start a new one + if (line.length > 0) { + lines += TextMetrics.addLine(line); + line = ''; + width = 0; + } + + var isLastToken = i === tokens.length - 1; + + // give it its own line if it's not the end + lines += TextMetrics.addLine(token, !isLastToken); + canPrependSpaces = false; + line = ''; + width = 0; + } + } + + // word could fit + else { + // word won't fit because of existing words + // start a new line + if (tokenWidth + width > wordWrapWidth) { + // if its a space we don't want it + canPrependSpaces = false; + + // add a new line + lines += TextMetrics.addLine(line); + + // start a new line + line = ''; + width = 0; + } + + // don't add spaces to the beginning of lines + if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces) { + // add the word to the current line + line += token; + + // update width counter + width += tokenWidth; + } + } + } + + lines += TextMetrics.addLine(line, false); + + return lines; + }; + + /** + * Convienience function for logging each line added during the wordWrap + * method + * + * @private + * @param {string} line - The line of text to add + * @param {boolean} newLine - Add new line character to end + * @return {string} A formatted line + */ + + + TextMetrics.addLine = function addLine(line) { + var newLine = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + + line = TextMetrics.trimRight(line); + + line = newLine ? line + '\n' : line; + + return line; + }; + + /** + * Gets & sets the widths of calculated characters in a cache object + * + * @private + * @param {string} key The key + * @param {number} letterSpacing The letter spacing + * @param {object} cache The cache + * @param {CanvasRenderingContext2D} context The canvas context + * @return {number} The from cache. + */ + + + TextMetrics.getFromCache = function getFromCache(key, letterSpacing, cache, context) { + var width = cache[key]; + + if (width === undefined) { + var spacing = key.length * letterSpacing; + + width = context.measureText(key).width + spacing; + cache[key] = width; + } + + return width; + }; + + /** + * Determines whether we should collapse breaking spaces + * + * @private + * @param {string} whiteSpace The TextStyle property whiteSpace + * @return {boolean} should collapse + */ + + + TextMetrics.collapseSpaces = function collapseSpaces(whiteSpace) { + return whiteSpace === 'normal' || whiteSpace === 'pre-line'; + }; + + /** + * Determines whether we should collapse newLine chars + * + * @private + * @param {string} whiteSpace The white space + * @return {boolean} should collapse + */ + + + TextMetrics.collapseNewlines = function collapseNewlines(whiteSpace) { + return whiteSpace === 'normal'; + }; + + /** + * trims breaking whitespaces from string + * + * @private + * @param {string} text The text + * @return {string} trimmed string + */ + + + TextMetrics.trimRight = function trimRight(text) { + if (typeof text !== 'string') { + return ''; + } + + for (var i = text.length - 1; i >= 0; i--) { + var char = text[i]; + + if (!TextMetrics.isBreakingSpace(char)) { + break; + } + + text = text.slice(0, -1); + } + + return text; + }; + + /** + * Determines if char is a newline. + * + * @private + * @param {string} char The character + * @return {boolean} True if newline, False otherwise. + */ + + + TextMetrics.isNewline = function isNewline(char) { + if (typeof char !== 'string') { + return false; + } + + return TextMetrics._newlines.indexOf(char.charCodeAt(0)) >= 0; + }; + + /** + * Determines if char is a breaking whitespace. + * + * @private + * @param {string} char The character + * @return {boolean} True if whitespace, False otherwise. + */ + + + TextMetrics.isBreakingSpace = function isBreakingSpace(char) { + if (typeof char !== 'string') { + return false; + } + + return TextMetrics._breakingSpaces.indexOf(char.charCodeAt(0)) >= 0; + }; + + /** + * Splits a string into words, breaking-spaces and newLine characters + * + * @private + * @param {string} text The text + * @return {array} A tokenized array + */ + + + TextMetrics.tokenize = function tokenize(text) { + var tokens = []; + var token = ''; + + if (typeof text !== 'string') { + return tokens; + } + + for (var i = 0; i < text.length; i++) { + var char = text[i]; + + if (TextMetrics.isBreakingSpace(char) || TextMetrics.isNewline(char)) { + if (token !== '') { + tokens.push(token); + token = ''; + } + + tokens.push(char); + + continue; + } + + token += char; + } + + if (token !== '') { + tokens.push(token); + } + + return tokens; + }; + + /** + * This method exists to be easily overridden + * It allows one to customise which words should break + * Examples are if the token is CJK or numbers. + * It must return a boolean. + * + * @private + * @param {string} token The token + * @param {boolean} breakWords The style attr break words + * @return {boolean} whether to break word or not + */ + + + TextMetrics.canBreakWords = function canBreakWords(token, breakWords) { + return breakWords; + }; + + /** + * This method exists to be easily overridden + * It allows one to determine whether a pair of characters + * should be broken by newlines + * For example certain characters in CJK langs or numbers. + * It must return a boolean. + * + * @private + * @param {string} char The character + * @param {string} nextChar The next character + * @param {string} token The token/word the characters are from + * @param {number} index The index in the token of the char + * @param {boolean} breakWords The style attr break words + * @return {boolean} whether to break word or not + */ + + + TextMetrics.canBreakChars = function canBreakChars(char, nextChar, token, index, breakWords) // eslint-disable-line no-unused-vars + { + return true; + }; + + /** + * Calculates the ascent, descent and fontSize of a given font-style + * + * @static + * @param {string} font - String representing the style of the font + * @return {PIXI.TextMetrics~FontMetrics} Font properties object + */ + + + TextMetrics.measureFont = function measureFont(font) { + // as this method is used for preparing assets, don't recalculate things if we don't need to + if (TextMetrics._fonts[font]) { + return TextMetrics._fonts[font]; + } + + var properties = {}; + + var canvas = TextMetrics._canvas; + var context = TextMetrics._context; + + context.font = font; + + var metricsString = TextMetrics.METRICS_STRING + TextMetrics.BASELINE_SYMBOL; + var width = Math.ceil(context.measureText(metricsString).width); + var baseline = Math.ceil(context.measureText(TextMetrics.BASELINE_SYMBOL).width); + var height = 2 * baseline; + + baseline = baseline * TextMetrics.BASELINE_MULTIPLIER | 0; + + canvas.width = width; + canvas.height = height; + + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + + context.font = font; + + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText(metricsString, 0, baseline); + + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + + var i = 0; + var idx = 0; + var stop = false; + + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } else { + break; + } + } + + properties.ascent = baseline - i; + + idx = pixels - line; + stop = false; + + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var _j = 0; _j < line; _j += 4) { + if (imagedata[idx + _j] !== 255) { + stop = true; + break; + } + } + + if (!stop) { + idx -= line; + } else { + break; + } + } + + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + + TextMetrics._fonts[font] = properties; + + return properties; + }; + + /** + * Clear font metrics in metrics cache. + * + * @static + * @param {string} [font] - font name. If font name not set then clear cache for all fonts. + */ + + + TextMetrics.clearMetrics = function clearMetrics() { + var font = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; + + if (font) { + delete TextMetrics._fonts[font]; + } else { + TextMetrics._fonts = {}; + } + }; + + return TextMetrics; +}(); + +/** + * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}. + * @class FontMetrics + * @memberof PIXI.TextMetrics~ + * @property {number} ascent - The ascent distance + * @property {number} descent - The descent distance + * @property {number} fontSize - Font size from ascent to descent + */ + +exports.default = TextMetrics; +var canvas = document.createElement('canvas'); + +canvas.width = canvas.height = 10; + +/** + * Cached canvas element for measuring text + * @memberof PIXI.TextMetrics + * @type {HTMLCanvasElement} + * @private + */ +TextMetrics._canvas = canvas; + +/** + * Cache for context to use. + * @memberof PIXI.TextMetrics + * @type {CanvasRenderingContext2D} + * @private + */ +TextMetrics._context = canvas.getContext('2d'); + +/** + * Cache of PIXI.TextMetrics~FontMetrics objects. + * @memberof PIXI.TextMetrics + * @type {Object} + * @private + */ +TextMetrics._fonts = {}; + +/** + * String used for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name METRICS_STRING + * @type {string} + * @default |Éq + */ +TextMetrics.METRICS_STRING = '|Éq'; + +/** + * Baseline symbol for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name BASELINE_SYMBOL + * @type {string} + * @default M + */ +TextMetrics.BASELINE_SYMBOL = 'M'; + +/** + * Baseline multiplier for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name BASELINE_MULTIPLIER + * @type {number} + * @default 1.4 + */ +TextMetrics.BASELINE_MULTIPLIER = 1.4; + +/** + * Cache of new line chars. + * @memberof PIXI.TextMetrics + * @type {number[]} + * @private + */ +TextMetrics._newlines = [0x000A, // line feed +0x000D]; + +/** + * Cache of breaking spaces. + * @memberof PIXI.TextMetrics + * @type {number[]} + * @private + */ +TextMetrics._breakingSpaces = [0x0009, // character tabulation +0x0020, // space +0x2000, // en quad +0x2001, // em quad +0x2002, // en space +0x2003, // em space +0x2004, // three-per-em space +0x2005, // four-per-em space +0x2006, // six-per-em space +0x2008, // punctuation space +0x2009, // thin space +0x200A, // hair space +0x205F, // medium mathematical space +0x3000]; + +},{}],110:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // disabling eslint for now, going to rewrite this in v5 +/* eslint-disable */ + +var _const = require('../const'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: 'black', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: _const.TEXT_GRADIENT.LINEAR_VERTICAL, + fillGradientStops: [], + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + trim: false, + whiteSpace: 'pre', + wordWrap: false, + wordWrapWidth: 100, + leading: 0 +}; + +var genericFontFamilies = ['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui']; + +/** + * A TextStyle Object decorates a Text Object. It can be shared between + * multiple Text objects. Changing the style will update all text objects using it. + * It can be generated [here](https://pixijs.io/pixi-text-style). + * + * @class + * @memberof PIXI + */ + +var TextStyle = function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string|number} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours + * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} + * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set + * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * @param {string|string[]} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', 800' or '900') + * @param {number} [style.leading=0] - The space between lines + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Possible values "miter" (creates a sharp corner), "round" (creates a round corner) or "bevel" + * (creates a squared corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {boolean} [style.trim=false] - Trim transparent borders + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {boolean} [style.whiteSpace='pre'] - Determines whether newlines & spaces are collapsed or preserved "normal" + * (collapse, collapse), "pre" (preserve, preserve) | "pre-line" (preserve, collapse). It needs wordWrap to be set to true + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + _classCallCheck(this, TextStyle); + + this.styleID = 0; + + this.reset(); + + deepCopyProperties(this, style, style); + } + + /** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return {PIXI.TextStyle} New cloned TextStyle object + */ + + + TextStyle.prototype.clone = function clone() { + var clonedProperties = {}; + + deepCopyProperties(clonedProperties, this, defaultStyle); + + return new TextStyle(clonedProperties); + }; + + /** + * Resets all properties to the defaults specified in TextStyle.prototype._default + */ + + + TextStyle.prototype.reset = function reset() { + deepCopyProperties(this, defaultStyle, defaultStyle); + }; + + /** + * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text + * + * @member {string} + */ + + + /** + * Generates a font style string to use for `TextMetrics.measureFont()`. + * + * @return {string} Font style string, for passing to `TextMetrics.measureFont()` + */ + TextStyle.prototype.toFontString = function toFontString() { + // build canvas api font setting from individual components. Convert a numeric this.fontSize to px + var fontSizeString = typeof this.fontSize === 'number' ? this.fontSize + 'px' : this.fontSize; + + // Clean-up fontFamily property by quoting each font name + // this will support font names with spaces + var fontFamilies = this.fontFamily; + + if (!Array.isArray(this.fontFamily)) { + fontFamilies = this.fontFamily.split(','); + } + + for (var i = fontFamilies.length - 1; i >= 0; i--) { + // Trim any extra white-space + var fontFamily = fontFamilies[i].trim(); + + // Check if font is already escaped in quotes except for CSS generic fonts + if (!/([\"\'])[^\'\"]+\1/.test(fontFamily) && genericFontFamilies.indexOf(fontFamily) < 0) { + fontFamily = '"' + fontFamily + '"'; + } + fontFamilies[i] = fontFamily; + } + + return this.fontStyle + ' ' + this.fontVariant + ' ' + this.fontWeight + ' ' + fontSizeString + ' ' + fontFamilies.join(','); + }; + + _createClass(TextStyle, [{ + key: 'align', + get: function get() { + return this._align; + }, + set: function set(align) // eslint-disable-line require-jsdoc + { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + } + + /** + * Indicates if lines can be wrapped within words, it needs wordWrap to be set to true + * + * @member {boolean} + */ + + }, { + key: 'breakWords', + get: function get() { + return this._breakWords; + }, + set: function set(breakWords) // eslint-disable-line require-jsdoc + { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + } + + /** + * Set a drop shadow for the text + * + * @member {boolean} + */ + + }, { + key: 'dropShadow', + get: function get() { + return this._dropShadow; + }, + set: function set(dropShadow) // eslint-disable-line require-jsdoc + { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + } + + /** + * Set alpha for the drop shadow + * + * @member {number} + */ + + }, { + key: 'dropShadowAlpha', + get: function get() { + return this._dropShadowAlpha; + }, + set: function set(dropShadowAlpha) // eslint-disable-line require-jsdoc + { + if (this._dropShadowAlpha !== dropShadowAlpha) { + this._dropShadowAlpha = dropShadowAlpha; + this.styleID++; + } + } + + /** + * Set a angle of the drop shadow + * + * @member {number} + */ + + }, { + key: 'dropShadowAngle', + get: function get() { + return this._dropShadowAngle; + }, + set: function set(dropShadowAngle) // eslint-disable-line require-jsdoc + { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + } + + /** + * Set a shadow blur radius + * + * @member {number} + */ + + }, { + key: 'dropShadowBlur', + get: function get() { + return this._dropShadowBlur; + }, + set: function set(dropShadowBlur) // eslint-disable-line require-jsdoc + { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + } + + /** + * A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * + * @member {string|number} + */ + + }, { + key: 'dropShadowColor', + get: function get() { + return this._dropShadowColor; + }, + set: function set(dropShadowColor) // eslint-disable-line require-jsdoc + { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + } + + /** + * Set a distance of the drop shadow + * + * @member {number} + */ + + }, { + key: 'dropShadowDistance', + get: function get() { + return this._dropShadowDistance; + }, + set: function set(dropShadowDistance) // eslint-disable-line require-jsdoc + { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + } + + /** + * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'. + * Can be an array to create a gradient eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * + * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern} + */ + + }, { + key: 'fill', + get: function get() { + return this._fill; + }, + set: function set(fill) // eslint-disable-line require-jsdoc + { + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + } + + /** + * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient. + * See {@link PIXI.TEXT_GRADIENT} + * + * @member {number} + */ + + }, { + key: 'fillGradientType', + get: function get() { + return this._fillGradientType; + }, + set: function set(fillGradientType) // eslint-disable-line require-jsdoc + { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + } + + /** + * If fill is an array of colours to create a gradient, this array can set the stop points + * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * + * @member {number[]} + */ + + }, { + key: 'fillGradientStops', + get: function get() { + return this._fillGradientStops; + }, + set: function set(fillGradientStops) // eslint-disable-line require-jsdoc + { + if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { + this._fillGradientStops = fillGradientStops; + this.styleID++; + } + } + + /** + * The font family + * + * @member {string|string[]} + */ + + }, { + key: 'fontFamily', + get: function get() { + return this._fontFamily; + }, + set: function set(fontFamily) // eslint-disable-line require-jsdoc + { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + } + + /** + * The font size + * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em') + * + * @member {number|string} + */ + + }, { + key: 'fontSize', + get: function get() { + return this._fontSize; + }, + set: function set(fontSize) // eslint-disable-line require-jsdoc + { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + } + + /** + * The font style + * ('normal', 'italic' or 'oblique') + * + * @member {string} + */ + + }, { + key: 'fontStyle', + get: function get() { + return this._fontStyle; + }, + set: function set(fontStyle) // eslint-disable-line require-jsdoc + { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + } + + /** + * The font variant + * ('normal' or 'small-caps') + * + * @member {string} + */ + + }, { + key: 'fontVariant', + get: function get() { + return this._fontVariant; + }, + set: function set(fontVariant) // eslint-disable-line require-jsdoc + { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + } + + /** + * The font weight + * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900') + * + * @member {string} + */ + + }, { + key: 'fontWeight', + get: function get() { + return this._fontWeight; + }, + set: function set(fontWeight) // eslint-disable-line require-jsdoc + { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + } + + /** + * The amount of spacing between letters, default is 0 + * + * @member {number} + */ + + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(letterSpacing) // eslint-disable-line require-jsdoc + { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + } + + /** + * The line height, a number that represents the vertical space that a letter uses + * + * @member {number} + */ + + }, { + key: 'lineHeight', + get: function get() { + return this._lineHeight; + }, + set: function set(lineHeight) // eslint-disable-line require-jsdoc + { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + } + + /** + * The space between lines + * + * @member {number} + */ + + }, { + key: 'leading', + get: function get() { + return this._leading; + }, + set: function set(leading) // eslint-disable-line require-jsdoc + { + if (this._leading !== leading) { + this._leading = leading; + this.styleID++; + } + } + + /** + * The lineJoin property sets the type of corner created, it can resolve spiked text issues. + * Default is 'miter' (creates a sharp corner). + * + * @member {string} + */ + + }, { + key: 'lineJoin', + get: function get() { + return this._lineJoin; + }, + set: function set(lineJoin) // eslint-disable-line require-jsdoc + { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + } + + /** + * The miter limit to use when using the 'miter' lineJoin mode + * This can reduce or increase the spikiness of rendered text. + * + * @member {number} + */ + + }, { + key: 'miterLimit', + get: function get() { + return this._miterLimit; + }, + set: function set(miterLimit) // eslint-disable-line require-jsdoc + { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + } + + /** + * Occasionally some fonts are cropped. Adding some padding will prevent this from happening + * by adding padding to all sides of the text. + * + * @member {number} + */ + + }, { + key: 'padding', + get: function get() { + return this._padding; + }, + set: function set(padding) // eslint-disable-line require-jsdoc + { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + } + + /** + * A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * + * @member {string|number} + */ + + }, { + key: 'stroke', + get: function get() { + return this._stroke; + }, + set: function set(stroke) // eslint-disable-line require-jsdoc + { + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + } + + /** + * A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * + * @member {number} + */ + + }, { + key: 'strokeThickness', + get: function get() { + return this._strokeThickness; + }, + set: function set(strokeThickness) // eslint-disable-line require-jsdoc + { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + } + + /** + * The baseline of the text that is rendered. + * + * @member {string} + */ + + }, { + key: 'textBaseline', + get: function get() { + return this._textBaseline; + }, + set: function set(textBaseline) // eslint-disable-line require-jsdoc + { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + } + + /** + * Trim transparent borders + * + * @member {boolean} + */ + + }, { + key: 'trim', + get: function get() { + return this._trim; + }, + set: function set(trim) // eslint-disable-line require-jsdoc + { + if (this._trim !== trim) { + this._trim = trim; + this.styleID++; + } + } + + /** + * How newlines and spaces should be handled. + * Default is 'pre' (preserve, preserve). + * + * value | New lines | Spaces + * --- | --- | --- + * 'normal' | Collapse | Collapse + * 'pre' | Preserve | Preserve + * 'pre-line' | Preserve | Collapse + * + * @member {string} + */ + + }, { + key: 'whiteSpace', + get: function get() { + return this._whiteSpace; + }, + set: function set(whiteSpace) // eslint-disable-line require-jsdoc + { + if (this._whiteSpace !== whiteSpace) { + this._whiteSpace = whiteSpace; + this.styleID++; + } + } + + /** + * Indicates if word wrap should be used + * + * @member {boolean} + */ + + }, { + key: 'wordWrap', + get: function get() { + return this._wordWrap; + }, + set: function set(wordWrap) // eslint-disable-line require-jsdoc + { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + } + + /** + * The width at which text will wrap, it needs wordWrap to be set to true + * + * @member {number} + */ + + }, { + key: 'wordWrapWidth', + get: function get() { + return this._wordWrapWidth; + }, + set: function set(wordWrapWidth) // eslint-disable-line require-jsdoc + { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + } + }]); + + return TextStyle; +}(); + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * @private + * @param {number|number[]} color + * @return {string} The color as a string. + */ + + +exports.default = TextStyle; +function getSingleColor(color) { + if (typeof color === 'number') { + return (0, _utils.hex2string)(color); + } else if (typeof color === 'string') { + if (color.indexOf('0x') === 0) { + color = color.replace('0x', '#'); + } + } + + return color; +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * @private + * @param {number|number[]} color + * @return {string} The color as a string. + */ +function getColor(color) { + if (!Array.isArray(color)) { + return getSingleColor(color); + } else { + for (var i = 0; i < color.length; ++i) { + color[i] = getSingleColor(color[i]); + } + + return color; + } +} + +/** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * @private + * @param {Array} array1 First array to compare + * @param {Array} array2 Second array to compare + * @return {boolean} Do the arrays contain the same values in the same order + */ +function areArraysEqual(array1, array2) { + if (!Array.isArray(array1) || !Array.isArray(array2)) { + return false; + } + + if (array1.length !== array2.length) { + return false; + } + + for (var i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } + + return true; +} + +/** + * Utility function to ensure that object properties are copied by value, and not by reference + * @private + * @param {Object} target Target object to copy properties into + * @param {Object} source Source object for the proporties to copy + * @param {string} propertyObj Object containing properties names we want to loop over + */ +function deepCopyProperties(target, source, propertyObj) { + for (var prop in propertyObj) { + if (Array.isArray(source[prop])) { + target[prop] = source[prop].slice(); + } else { + target[prop] = source[prop]; + } + } +} + +},{"../const":46,"../utils":125}],111:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024); + * let baseRenderTexture = new PIXI.BaseRenderTexture(800, 600); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let baseRenderTexture = new PIXI.BaseRenderTexture(100, 100); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var BaseRenderTexture = function (_BaseTexture) { + _inherits(BaseRenderTexture, _BaseTexture); + + /** + * @param {number} [width=100] - The width of the base render texture + * @param {number} [height=100] - The height of the base render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + */ + function BaseRenderTexture() { + var width = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100; + var height = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + + _classCallCheck(this, BaseRenderTexture); + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, null, scaleMode)); + + _this.resolution = resolution || _settings2.default.RESOLUTION; + + _this.width = Math.ceil(width); + _this.height = Math.ceil(height); + + _this.realWidth = _this.width * _this.resolution; + _this.realHeight = _this.height * _this.resolution; + + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + _this.hasLoaded = true; + + /** + * A map of renderer IDs to webgl renderTargets + * + * @private + * @member {object} + */ + _this._glRenderTargets = {}; + + /** + * A reference to the canvas render target (we only need one as this can be shared across renderers) + * + * @private + * @member {object} + */ + _this._canvasRenderTarget = null; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + return _this; + } + + /** + * Resizes the BaseRenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + */ + + + BaseRenderTexture.prototype.resize = function resize(width, height) { + width = Math.ceil(width); + height = Math.ceil(height); + + if (width === this.width && height === this.height) { + return; + } + + this.valid = width > 0 && height > 0; + + this.width = width; + this.height = height; + + this.realWidth = this.width * this.resolution; + this.realHeight = this.height * this.resolution; + + if (!this.valid) { + return; + } + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + */ + + + BaseRenderTexture.prototype.destroy = function destroy() { + _BaseTexture.prototype.destroy.call(this, true); + this.renderer = null; + }; + + return BaseRenderTexture; +}(_BaseTexture3.default); + +exports.default = BaseRenderTexture; + +},{"../settings":101,"./BaseTexture":112}],112:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +var _bitTwiddle = require('bit-twiddle'); + +var _bitTwiddle2 = _interopRequireDefault(_bitTwiddle); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image. All textures have a base texture. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var BaseTexture = function (_EventEmitter) { + _inherits(BaseTexture, _EventEmitter); + + /** + * @param {HTMLImageElement|HTMLCanvasElement} [source] - the source object of the texture. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture + */ + function BaseTexture(source, scaleMode, resolution) { + _classCallCheck(this, BaseTexture); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.uid = (0, _utils.uid)(); + + _this.touched = 0; + + /** + * The resolution / device pixel ratio of the texture + * + * @member {number} + * @default 1 + */ + _this.resolution = resolution || _settings2.default.RESOLUTION; + + /** + * The width of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.width = 100; + + /** + * The height of the base texture set when the image has loaded + * + * @readonly + * @member {number} + */ + _this.height = 100; + + // TODO docs + // used to store the actual dimensions of the source + /** + * Used to store the actual width of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realWidth = 100; + /** + * Used to store the actual height of the source of this texture + * + * @readonly + * @member {number} + */ + _this.realHeight = 100; + + /** + * The scale mode to apply when scaling this texture + * + * @member {number} + * @default PIXI.settings.SCALE_MODE + * @see PIXI.SCALE_MODES + */ + _this.scaleMode = scaleMode !== undefined ? scaleMode : _settings2.default.SCALE_MODE; + + /** + * Set to true once the base texture has successfully loaded. + * + * This is never true if the underlying source fails to load or has no texture data. + * + * @readonly + * @member {boolean} + */ + _this.hasLoaded = false; + + /** + * Set to true if the source is currently loading. + * + * If an Image source is loading the 'loaded' or 'error' event will be + * dispatched when the operation ends. An underyling source that is + * immediately-available bypasses loading entirely. + * + * @readonly + * @member {boolean} + */ + _this.isLoading = false; + + /** + * The image source that is used to create the texture. + * + * TODO: Make this a setter that calls loadSource(); + * + * @readonly + * @member {HTMLImageElement|HTMLCanvasElement} + */ + _this.source = null; // set in loadSource, if at all + + /** + * The image source that is used to create the texture. This is used to + * store the original Svg source when it is replaced with a canvas element. + * + * TODO: Currently not in use but could be used when re-scaling svg. + * + * @readonly + * @member {Image} + */ + _this.origSource = null; // set in loadSvg, if at all + + /** + * Type of image defined in source, eg. `png` or `svg` + * + * @readonly + * @member {string} + */ + _this.imageType = null; // set in updateImageType + + /** + * Scale for source image. Used with Svg images to scale them before rasterization. + * + * @readonly + * @member {number} + */ + _this.sourceScale = 1.0; + + /** + * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only) + * All blend modes, and shaders written for default value. Change it on your own risk. + * + * @member {boolean} + * @default true + */ + _this.premultipliedAlpha = true; + + /** + * The image url of the texture + * + * @member {string} + */ + _this.imageUrl = null; + + /** + * Whether or not the texture is a power of two, try to use power of two textures as much + * as you can + * + * @private + * @member {boolean} + */ + _this.isPowerOfTwo = false; + + // used for webGL + + /** + * + * Set this to true if a mipmap of this texture needs to be generated. This value needs + * to be set before the texture is used + * Also the texture must be a power of two size to work + * + * @member {boolean} + * @see PIXI.MIPMAP_TEXTURES + */ + _this.mipmap = _settings2.default.MIPMAP_TEXTURES; + + /** + * + * WebGL Texture wrap mode + * + * @member {number} + * @see PIXI.WRAP_MODES + */ + _this.wrapMode = _settings2.default.WRAP_MODE; + + /** + * A map of renderer IDs to webgl textures + * + * @private + * @member {object} + */ + _this._glTextures = {}; + + _this._enabled = 0; + _this._virtalBoundId = -1; + + /** + * If the object has been destroyed via destroy(). If true, it should not be used. + * + * @member {boolean} + * @private + * @readonly + */ + _this._destroyed = false; + + /** + * The ids under which this BaseTexture has been added to the base texture cache. This is + * automatically set as long as BaseTexture.addToCache is used, but may not be set if a + * BaseTexture is added directly to the BaseTextureCache array. + * + * @member {string[]} + */ + _this.textureCacheIds = []; + + // if no source passed don't try to load + if (source) { + _this.loadSource(source); + } + + /** + * Fired when a not-immediately-available source finishes loading. + * + * @protected + * @event PIXI.BaseTexture#loaded + * @param {PIXI.BaseTexture} baseTexture - Resource loaded. + */ + + /** + * Fired when a not-immediately-available source fails to load. + * + * @protected + * @event PIXI.BaseTexture#error + * @param {PIXI.BaseTexture} baseTexture - Resource errored. + */ + + /** + * Fired when BaseTexture is updated. + * + * @protected + * @event PIXI.BaseTexture#update + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. + */ + + /** + * Fired when BaseTexture is destroyed. + * + * @protected + * @event PIXI.BaseTexture#dispose + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. + */ + return _this; + } + + /** + * Updates the texture on all the webgl renderers, this also assumes the src has changed. + * + * @fires PIXI.BaseTexture#update + */ + + + BaseTexture.prototype.update = function update() { + // Svg size is handled during load + if (this.imageType !== 'svg') { + this.realWidth = this.source.naturalWidth || this.source.videoWidth || this.source.width; + this.realHeight = this.source.naturalHeight || this.source.videoHeight || this.source.height; + + this._updateDimensions(); + } + + this.emit('update', this); + }; + + /** + * Update dimensions from real values + */ + + + BaseTexture.prototype._updateDimensions = function _updateDimensions() { + this.width = this.realWidth / this.resolution; + this.height = this.realHeight / this.resolution; + + this.isPowerOfTwo = _bitTwiddle2.default.isPow2(this.realWidth) && _bitTwiddle2.default.isPow2(this.realHeight); + }; + + /** + * Load a source. + * + * If the source is not-immediately-available, such as an image that needs to be + * downloaded, then the 'loaded' or 'error' event will be dispatched in the future + * and `hasLoaded` will remain false after this call. + * + * The logic state after calling `loadSource` directly or indirectly (eg. `fromImage`, `new BaseTexture`) is: + * + * if (texture.hasLoaded) { + * // texture ready for use + * } else if (texture.isLoading) { + * // listen to 'loaded' and/or 'error' events on texture + * } else { + * // not loading, not going to load UNLESS the source is reloaded + * // (it may still make sense to listen to the events) + * } + * + * @protected + * @param {HTMLImageElement|HTMLCanvasElement} source - the source object of the texture. + */ + + + BaseTexture.prototype.loadSource = function loadSource(source) { + var wasLoading = this.isLoading; + + this.hasLoaded = false; + this.isLoading = false; + + if (wasLoading && this.source) { + this.source.onload = null; + this.source.onerror = null; + } + + var firstSourceLoaded = !this.source; + + this.source = source; + + // Apply source if loaded. Otherwise setup appropriate loading monitors. + if ((source.src && source.complete || source.getContext) && source.width && source.height) { + this._updateImageType(); + + if (this.imageType === 'svg') { + this._loadSvgSource(); + } else { + this._sourceLoaded(); + } + + if (firstSourceLoaded) { + // send loaded event if previous source was null and we have been passed a pre-loaded IMG element + this.emit('loaded', this); + } + } else if (!source.getContext) { + // Image fail / not ready + this.isLoading = true; + + var scope = this; + + source.onload = function () { + scope._updateImageType(); + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope._sourceLoaded(); + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + scope.emit('loaded', scope); + }; + + source.onerror = function () { + source.onload = null; + source.onerror = null; + + if (!scope.isLoading) { + return; + } + + scope.isLoading = false; + scope.emit('error', scope); + }; + + // Per http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element + // "The value of `complete` can thus change while a script is executing." + // So complete needs to be re-checked after the callbacks have been added.. + // NOTE: complete will be true if the image has no src so best to check if the src is set. + if (source.complete && source.src) { + // ..and if we're complete now, no need for callbacks + source.onload = null; + source.onerror = null; + + if (scope.imageType === 'svg') { + scope._loadSvgSource(); + + return; + } + + this.isLoading = false; + + if (source.width && source.height) { + this._sourceLoaded(); + + // If any previous subscribers possible + if (wasLoading) { + this.emit('loaded', this); + } + } + // If any previous subscribers possible + else if (wasLoading) { + this.emit('error', this); + } + } + } + }; + + /** + * Updates type of the source image. + */ + + + BaseTexture.prototype._updateImageType = function _updateImageType() { + if (!this.imageUrl) { + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + var imageType = void 0; + + if (dataUri && dataUri.mediaType === 'image') { + // Check for subType validity + var firstSubType = dataUri.subType.split('+')[0]; + + imageType = (0, _utils.getUrlFileExtension)('.' + firstSubType); + + if (!imageType) { + throw new Error('Invalid image type in data URI.'); + } + } else { + imageType = (0, _utils.getUrlFileExtension)(this.imageUrl); + + if (!imageType) { + imageType = 'png'; + } + } + + this.imageType = imageType; + }; + + /** + * Checks if `source` is an SVG image and whether it's loaded via a URL or a data URI. Then calls + * `_loadSvgSourceUsingDataUri` or `_loadSvgSourceUsingXhr`. + */ + + + BaseTexture.prototype._loadSvgSource = function _loadSvgSource() { + if (this.imageType !== 'svg') { + // Do nothing if source is not svg + return; + } + + var dataUri = (0, _utils.decomposeDataUri)(this.imageUrl); + + if (dataUri) { + this._loadSvgSourceUsingDataUri(dataUri); + } else { + // We got an URL, so we need to do an XHR to check the svg size + this._loadSvgSourceUsingXhr(); + } + }; + + /** + * Reads an SVG string from data URI and then calls `_loadSvgSourceUsingString`. + * + * @param {string} dataUri - The data uri to load from. + */ + + + BaseTexture.prototype._loadSvgSourceUsingDataUri = function _loadSvgSourceUsingDataUri(dataUri) { + var svgString = void 0; + + if (dataUri.encoding === 'base64') { + if (!atob) { + throw new Error('Your browser doesn\'t support base64 conversions.'); + } + svgString = atob(dataUri.data); + } else { + svgString = dataUri.data; + } + + this._loadSvgSourceUsingString(svgString); + }; + + /** + * Loads an SVG string from `imageUrl` using XHR and then calls `_loadSvgSourceUsingString`. + */ + + + BaseTexture.prototype._loadSvgSourceUsingXhr = function _loadSvgSourceUsingXhr() { + var _this2 = this; + + var svgXhr = new XMLHttpRequest(); + + // This throws error on IE, so SVG Document can't be used + // svgXhr.responseType = 'document'; + + // This is not needed since we load the svg as string (breaks IE too) + // but overrideMimeType() can be used to force the response to be parsed as XML + // svgXhr.overrideMimeType('image/svg+xml'); + + svgXhr.onload = function () { + if (svgXhr.readyState !== svgXhr.DONE || svgXhr.status !== 200) { + throw new Error('Failed to load SVG using XHR.'); + } + + _this2._loadSvgSourceUsingString(svgXhr.response); + }; + + svgXhr.onerror = function () { + return _this2.emit('error', _this2); + }; + + svgXhr.open('GET', this.imageUrl, true); + svgXhr.send(); + }; + + /** + * Loads texture using an SVG string. The original SVG Image is stored as `origSource` and the + * created canvas is the new `source`. The SVG is scaled using `sourceScale`. Called by + * `_loadSvgSourceUsingXhr` or `_loadSvgSourceUsingDataUri`. + * + * @param {string} svgString SVG source as string + * + * @fires PIXI.BaseTexture#loaded + */ + + + BaseTexture.prototype._loadSvgSourceUsingString = function _loadSvgSourceUsingString(svgString) { + var svgSize = (0, _utils.getSvgSize)(svgString); + + var svgWidth = svgSize.width; + var svgHeight = svgSize.height; + + if (!svgWidth || !svgHeight) { + throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); + } + + // Scale realWidth and realHeight + this.realWidth = Math.round(svgWidth * this.sourceScale); + this.realHeight = Math.round(svgHeight * this.sourceScale); + + this._updateDimensions(); + + // Create a canvas element + var canvas = document.createElement('canvas'); + + canvas.width = this.realWidth; + canvas.height = this.realHeight; + canvas._pixiId = 'canvas_' + (0, _utils.uid)(); + + // Draw the Svg to the canvas + canvas.getContext('2d').drawImage(this.source, 0, 0, svgWidth, svgHeight, 0, 0, this.realWidth, this.realHeight); + + // Replace the original source image with the canvas + this.origSource = this.source; + this.source = canvas; + + // Add also the canvas in cache (destroy clears by `imageUrl` and `source._pixiId`) + BaseTexture.addToCache(this, canvas._pixiId); + + this.isLoading = false; + this._sourceLoaded(); + this.emit('loaded', this); + }; + + /** + * Used internally to update the width, height, and some other tracking vars once + * a source has successfully loaded. + * + * @private + */ + + + BaseTexture.prototype._sourceLoaded = function _sourceLoaded() { + this.hasLoaded = true; + this.update(); + }; + + /** + * Destroys this base texture + * + */ + + + BaseTexture.prototype.destroy = function destroy() { + if (this.imageUrl) { + delete _utils.TextureCache[this.imageUrl]; + + this.imageUrl = null; + + if (!navigator.isCocoonJS) { + this.source.src = ''; + } + } + + this.source = null; + + this.dispose(); + + BaseTexture.removeFromCache(this); + this.textureCacheIds = null; + + this._destroyed = true; + }; + + /** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * + * @fires PIXI.BaseTexture#dispose + */ + + + BaseTexture.prototype.dispose = function dispose() { + this.emit('dispose', this); + }; + + /** + * Changes the source image of the texture. + * The original source must be an Image element. + * + * @param {string} newSrc - the path of the image + */ + + + BaseTexture.prototype.updateSourceImage = function updateSourceImage(newSrc) { + this.source.src = newSrc; + + this.loadSource(this.source); + }; + + /** + * Helper function that creates a base texture from the given image url. + * If the image is not in the base texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + // new Image() breaks tex loading in some versions of Chrome. + // See https://code.google.com/p/chromium/issues/detail?id=238071 + var image = new Image(); // document.createElement('img'); + + if (crossorigin === undefined && imageUrl.indexOf('data:') !== 0) { + image.crossOrigin = (0, _determineCrossOrigin2.default)(imageUrl); + } else if (crossorigin) { + image.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; + } + + baseTexture = new BaseTexture(image, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + image.src = imageUrl; // Setting this triggers load + + BaseTexture.addToCache(baseTexture, imageUrl); + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture from the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @param {string} [origin='canvas'] - A string origin of who created the base texture + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode) { + var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; + + if (!canvas._pixiId) { + canvas._pixiId = origin + '_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[canvas._pixiId]; + + if (!baseTexture) { + baseTexture = new BaseTexture(canvas, scaleMode); + BaseTexture.addToCache(baseTexture, canvas._pixiId); + } + + return baseTexture; + }; + + /** + * Helper function that creates a base texture based on the source you provide. + * The source can be - image url, image element, canvas element. If the + * source is an image url or an image element and not in the base texture + * cache, it will be created and loaded. + * + * @static + * @param {string|HTMLImageElement|HTMLCanvasElement} source - The source to create base texture from. + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. + * @return {PIXI.BaseTexture} The new base texture. + */ + + + BaseTexture.from = function from(source, scaleMode, sourceScale) { + if (typeof source === 'string') { + return BaseTexture.fromImage(source, undefined, scaleMode, sourceScale); + } else if (source instanceof HTMLImageElement) { + var imageUrl = source.src; + var baseTexture = _utils.BaseTextureCache[imageUrl]; + + if (!baseTexture) { + baseTexture = new BaseTexture(source, scaleMode); + baseTexture.imageUrl = imageUrl; + + if (sourceScale) { + baseTexture.sourceScale = sourceScale; + } + + // if there is an @2x at the end of the url we are going to assume its a highres image + baseTexture.resolution = (0, _utils.getResolutionOfUrl)(imageUrl); + + BaseTexture.addToCache(baseTexture, imageUrl); + } + + return baseTexture; + } else if (source instanceof HTMLCanvasElement) { + return BaseTexture.fromCanvas(source, scaleMode); + } + + // lets assume its a base texture! + return source; + }; + + /** + * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache. + * @param {string} id - The id that the BaseTexture will be stored against. + */ + + + BaseTexture.addToCache = function addToCache(baseTexture, id) { + if (id) { + if (baseTexture.textureCacheIds.indexOf(id) === -1) { + baseTexture.textureCacheIds.push(id); + } + + /* eslint-disable no-console */ + if (_utils.BaseTextureCache[id]) { + console.warn('BaseTexture added to the cache with an id [' + id + '] that already had an entry'); + } + /* eslint-enable no-console */ + + _utils.BaseTextureCache[id] = baseTexture; + } + }; + + /** + * Remove a BaseTexture from the global BaseTextureCache. + * + * @static + * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself. + * @return {PIXI.BaseTexture|null} The BaseTexture that was removed. + */ + + + BaseTexture.removeFromCache = function removeFromCache(baseTexture) { + if (typeof baseTexture === 'string') { + var baseTextureFromCache = _utils.BaseTextureCache[baseTexture]; + + if (baseTextureFromCache) { + var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); + + if (index > -1) { + baseTextureFromCache.textureCacheIds.splice(index, 1); + } + + delete _utils.BaseTextureCache[baseTexture]; + + return baseTextureFromCache; + } + } else if (baseTexture && baseTexture.textureCacheIds) { + for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { + delete _utils.BaseTextureCache[baseTexture.textureCacheIds[i]]; + } + + baseTexture.textureCacheIds.length = 0; + + return baseTexture; + } + + return null; + }; + + return BaseTexture; +}(_eventemitter2.default); + +exports.default = BaseTexture; + +},{"../settings":101,"../utils":125,"../utils/determineCrossOrigin":124,"bit-twiddle":1,"eventemitter3":3}],113:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _BaseRenderTexture = require('./BaseRenderTexture'); + +var _BaseRenderTexture2 = _interopRequireDefault(_BaseRenderTexture); + +var _Texture2 = require('./Texture'); + +var _Texture3 = _interopRequireDefault(_Texture2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(1024, 1024); + * let renderTexture = PIXI.RenderTexture.create(800, 600); + * let sprite = PIXI.Sprite.fromImage("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, renderTexture); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let renderTexture = new PIXI.RenderTexture.create(100, 100); + * + * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture + * ``` + * + * @class + * @extends PIXI.Texture + * @memberof PIXI + */ +var RenderTexture = function (_Texture) { + _inherits(RenderTexture, _Texture); + + /** + * @param {PIXI.BaseRenderTexture} baseRenderTexture - The renderer used for this RenderTexture + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + */ + function RenderTexture(baseRenderTexture, frame) { + _classCallCheck(this, RenderTexture); + + // support for legacy.. + var _legacyRenderer = null; + + if (!(baseRenderTexture instanceof _BaseRenderTexture2.default)) { + /* eslint-disable prefer-rest-params, no-console */ + var width = arguments[1]; + var height = arguments[2]; + var scaleMode = arguments[3]; + var resolution = arguments[4]; + + // we have an old render texture.. + console.warn('Please use RenderTexture.create(' + width + ', ' + height + ') instead of the ctor directly.'); + _legacyRenderer = arguments[0]; + /* eslint-enable prefer-rest-params, no-console */ + + frame = null; + baseRenderTexture = new _BaseRenderTexture2.default(width, height, scaleMode, resolution); + } + + /** + * The base texture object that this texture uses + * + * @member {BaseTexture} + */ + + var _this = _possibleConstructorReturn(this, _Texture.call(this, baseRenderTexture, frame)); + + _this.legacyRenderer = _legacyRenderer; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = true; + + _this._updateUvs(); + return _this; + } + + /** + * Resizes the RenderTexture. + * + * @param {number} width - The width to resize to. + * @param {number} height - The height to resize to. + * @param {boolean} doNotResizeBaseTexture - Should the baseTexture.width and height values be resized as well? + */ + + + RenderTexture.prototype.resize = function resize(width, height, doNotResizeBaseTexture) { + width = Math.ceil(width); + height = Math.ceil(height); + + // TODO - could be not required.. + this.valid = width > 0 && height > 0; + + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + + if (!doNotResizeBaseTexture) { + this.baseTexture.resize(width, height); + } + + this._updateUvs(); + }; + + /** + * A short hand way of creating a render texture. + * + * @param {number} [width=100] - The width of the render texture + * @param {number} [height=100] - The height of the render texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [resolution=1] - The resolution / device pixel ratio of the texture being generated + * @return {PIXI.RenderTexture} The new render texture + */ + + + RenderTexture.create = function create(width, height, scaleMode, resolution) { + return new RenderTexture(new _BaseRenderTexture2.default(width, height, scaleMode, resolution)); + }; + + return RenderTexture; +}(_Texture3.default); + +exports.default = RenderTexture; + +},{"./BaseRenderTexture":111,"./Texture":115}],114:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _ = require('../'); + +var _utils = require('../utils'); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Utility class for maintaining reference to a collection + * of Textures on a single Spritesheet. + * + * To access a sprite sheet from your code pass its JSON data file to Pixi's loader: + * + * ```js + * PIXI.loader.add("images/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.loader.resources["images/spritesheet.json"].spritesheet; + * ... + * } + * ``` + * With the `sheet.textures` you can create Sprite objects,`sheet.animations` can be used to create an AnimatedSprite. + * + * Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker}, + * {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}. + * Default anchor points (see {@link PIXI.Texture#defaultAnchor}) and grouping of animation sprites are currently only + * supported by TexturePacker. + * + * @class + * @memberof PIXI + */ +var Spritesheet = function () { + _createClass(Spritesheet, null, [{ + key: 'BATCH_SIZE', + + /** + * The maximum number of Textures to build per process. + * + * @type {number} + * @default 1000 + */ + get: function get() { + return 1000; + } + + /** + * @param {PIXI.BaseTexture} baseTexture Reference to the source BaseTexture object. + * @param {Object} data - Spritesheet image data. + * @param {string} [resolutionFilename] - The filename to consider when determining + * the resolution of the spritesheet. If not provided, the imageUrl will + * be used on the BaseTexture. + */ + + }]); + + function Spritesheet(baseTexture, data) { + var resolutionFilename = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + _classCallCheck(this, Spritesheet); + + /** + * Reference to ths source texture + * @type {PIXI.BaseTexture} + */ + this.baseTexture = baseTexture; + + /** + * A map containing all textures of the sprite sheet. + * Can be used to create a {@link PIXI.Sprite|Sprite}: + * ```js + * new PIXI.Sprite(sheet.textures["image.png"]); + * ``` + * @member {Object} + */ + this.textures = {}; + + /** + * A map containing the textures for each animation. + * Can be used to create an {@link PIXI.extras.AnimatedSprite|AnimatedSprite}: + * ```js + * new PIXI.extras.AnimatedSprite(sheet.animations["anim_name"]) + * ``` + * @member {Object} + */ + this.animations = {}; + + /** + * Reference to the original JSON data. + * @type {Object} + */ + this.data = data; + + /** + * The resolution of the spritesheet. + * @type {number} + */ + this.resolution = this._updateResolution(resolutionFilename || this.baseTexture.imageUrl); + + /** + * Map of spritesheet frames. + * @type {Object} + * @private + */ + this._frames = this.data.frames; + + /** + * Collection of frame names. + * @type {string[]} + * @private + */ + this._frameKeys = Object.keys(this._frames); + + /** + * Current batch index being processed. + * @type {number} + * @private + */ + this._batchIndex = 0; + + /** + * Callback when parse is completed. + * @type {Function} + * @private + */ + this._callback = null; + } + + /** + * Generate the resolution from the filename or fallback + * to the meta.scale field of the JSON data. + * + * @private + * @param {string} resolutionFilename - The filename to use for resolving + * the default resolution. + * @return {number} Resolution to use for spritesheet. + */ + + + Spritesheet.prototype._updateResolution = function _updateResolution(resolutionFilename) { + var scale = this.data.meta.scale; + + // Use a defaultValue of `null` to check if a url-based resolution is set + var resolution = (0, _utils.getResolutionOfUrl)(resolutionFilename, null); + + // No resolution found via URL + if (resolution === null) { + // Use the scale value or default to 1 + resolution = scale !== undefined ? parseFloat(scale) : 1; + } + + // For non-1 resolutions, update baseTexture + if (resolution !== 1) { + this.baseTexture.resolution = resolution; + this.baseTexture.update(); + } + + return resolution; + }; + + /** + * Parser spritesheet from loaded data. This is done asynchronously + * to prevent creating too many Texture within a single process. + * + * @param {Function} callback - Callback when complete returns + * a map of the Textures for this spritesheet. + */ + + + Spritesheet.prototype.parse = function parse(callback) { + this._batchIndex = 0; + this._callback = callback; + + if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) { + this._processFrames(0); + this._processAnimations(); + this._parseComplete(); + } else { + this._nextBatch(); + } + }; + + /** + * Process a batch of frames + * + * @private + * @param {number} initialFrameIndex - The index of frame to start. + */ + + + Spritesheet.prototype._processFrames = function _processFrames(initialFrameIndex) { + var frameIndex = initialFrameIndex; + var maxFrames = Spritesheet.BATCH_SIZE; + var sourceScale = this.baseTexture.sourceScale; + + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { + var i = this._frameKeys[frameIndex]; + var data = this._frames[i]; + var rect = data.frame; + + if (rect) { + var frame = null; + var trim = null; + var sourceSize = data.trimmed !== false && data.sourceSize ? data.sourceSize : data.frame; + + var orig = new _.Rectangle(0, 0, Math.floor(sourceSize.w * sourceScale) / this.resolution, Math.floor(sourceSize.h * sourceScale) / this.resolution); + + if (data.rotated) { + frame = new _.Rectangle(Math.floor(rect.x * sourceScale) / this.resolution, Math.floor(rect.y * sourceScale) / this.resolution, Math.floor(rect.h * sourceScale) / this.resolution, Math.floor(rect.w * sourceScale) / this.resolution); + } else { + frame = new _.Rectangle(Math.floor(rect.x * sourceScale) / this.resolution, Math.floor(rect.y * sourceScale) / this.resolution, Math.floor(rect.w * sourceScale) / this.resolution, Math.floor(rect.h * sourceScale) / this.resolution); + } + + // Check to see if the sprite is trimmed + if (data.trimmed !== false && data.spriteSourceSize) { + trim = new _.Rectangle(Math.floor(data.spriteSourceSize.x * sourceScale) / this.resolution, Math.floor(data.spriteSourceSize.y * sourceScale) / this.resolution, Math.floor(rect.w * sourceScale) / this.resolution, Math.floor(rect.h * sourceScale) / this.resolution); + } + + this.textures[i] = new _.Texture(this.baseTexture, frame, orig, trim, data.rotated ? 2 : 0, data.anchor); + + // lets also add the frame to pixi's global cache for fromFrame and fromImage functions + _.Texture.addToCache(this.textures[i], i); + } + + frameIndex++; + } + }; + + /** + * Parse animations config + * + * @private + */ + + + Spritesheet.prototype._processAnimations = function _processAnimations() { + var animations = this.data.animations || {}; + + for (var animName in animations) { + this.animations[animName] = []; + for (var _iterator = animations[animName], _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var frameName = _ref; + + this.animations[animName].push(this.textures[frameName]); + } + } + }; + + /** + * The parse has completed. + * + * @private + */ + + + Spritesheet.prototype._parseComplete = function _parseComplete() { + var callback = this._callback; + + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); + }; + + /** + * Begin the next batch of textures. + * + * @private + */ + + + Spritesheet.prototype._nextBatch = function _nextBatch() { + var _this = this; + + this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); + this._batchIndex++; + setTimeout(function () { + if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { + _this._nextBatch(); + } else { + _this._processAnimations(); + _this._parseComplete(); + } + }, 0); + }; + + /** + * Destroy Spritesheet and don't use after this. + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Spritesheet.prototype.destroy = function destroy() { + var destroyBase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + for (var i in this.textures) { + this.textures[i].destroy(); + } + this._frames = null; + this._frameKeys = null; + this.data = null; + this.textures = null; + if (destroyBase) { + this.baseTexture.destroy(); + } + this.baseTexture = null; + }; + + return Spritesheet; +}(); + +exports.default = Spritesheet; + +},{"../":65,"../utils":125}],115:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture = require('./BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _VideoBaseTexture = require('./VideoBaseTexture'); + +var _VideoBaseTexture2 = _interopRequireDefault(_VideoBaseTexture); + +var _TextureUvs = require('./TextureUvs'); + +var _TextureUvs2 = _interopRequireDefault(_TextureUvs); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _math = require('../math'); + +var _utils = require('../utils'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture stores the information that represents an image or part of an image. It cannot be added + * to the display list directly. Instead use it as the texture for a Sprite. If no frame is provided + * then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * let texture = PIXI.Texture.fromImage('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` + * + * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. + * You can check for this by checking the sprite's _textureID property. + * ```js + * var texture = PIXI.Texture.fromImage('assets/image.svg'); + * var sprite1 = new PIXI.Sprite(texture); + * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file + * ``` + * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. + * + * @class + * @extends EventEmitter + * @memberof PIXI + */ +var Texture = function (_EventEmitter) { + _inherits(Texture, _EventEmitter); + + /** + * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from + * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show + * @param {PIXI.Rectangle} [orig] - The area of original texture + * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture + * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.GroupD8} + * @param {PIXI.Point} [anchor] - Default anchor point used for sprite placement / rotation + */ + function Texture(baseTexture, frame, orig, trim, rotate, anchor) { + _classCallCheck(this, Texture); + + /** + * Does this Texture have any frame data assigned to it? + * + * @member {boolean} + */ + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + _this.noFrame = false; + + if (!frame) { + _this.noFrame = true; + frame = new _math.Rectangle(0, 0, 1, 1); + } + + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + + /** + * The base texture that this texture uses. + * + * @member {PIXI.BaseTexture} + */ + _this.baseTexture = baseTexture; + + /** + * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, + * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) + * + * @member {PIXI.Rectangle} + */ + _this._frame = frame; + + /** + * This is the trimmed area of original texture, before it was put in atlas + * Please call `_updateUvs()` after you change coordinates of `trim` manually. + * + * @member {PIXI.Rectangle} + */ + _this.trim = trim; + + /** + * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. + * + * @member {boolean} + */ + _this.valid = false; + + /** + * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates) + * + * @member {boolean} + */ + _this.requiresUpdate = false; + + /** + * The WebGL UV data cache. + * + * @member {PIXI.TextureUvs} + * @private + */ + _this._uvs = null; + + /** + * This is the area of original texture, before it was put in atlas + * + * @member {PIXI.Rectangle} + */ + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + + _this._rotate = Number(rotate || 0); + + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); + } + + if (baseTexture.hasLoaded) { + if (_this.noFrame) { + frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + + // if there is no frame we should monitor for any base texture changes.. + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + _this.frame = frame; + } else { + baseTexture.once('loaded', _this.onBaseTextureLoaded, _this); + } + + /** + * Anchor point that is used as default if sprite is created with this texture. + * Changing the `defaultAnchor` at a later point of time will not update Sprite's anchor point. + * @member {PIXI.Point} + * @default {0,0} + */ + _this.defaultAnchor = anchor ? new _math.Point(anchor.x, anchor.y) : new _math.Point(0, 0); + + /** + * Fired when the texture is updated. This happens if the frame or the baseTexture is updated. + * + * @event PIXI.Texture#update + * @protected + * @param {PIXI.Texture} texture - Instance of texture being updated. + */ + + _this._updateID = 0; + + /** + * Contains data for uvs. May contain clamp settings and some matrices. + * Its a bit heavy, so by default that object is not created. + * @member {PIXI.TextureMatrix} + * @default null + */ + _this.transform = null; + + /** + * The ids under which this Texture has been added to the texture cache. This is + * automatically set as long as Texture.addToCache is used, but may not be set if a + * Texture is added directly to the TextureCache array. + * + * @member {string[]} + */ + _this.textureCacheIds = []; + return _this; + } + + /** + * Updates this texture on the gpu. + * + */ + + + Texture.prototype.update = function update() { + this.baseTexture.update(); + }; + + /** + * Called when the base texture is loaded + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureLoaded = function onBaseTextureLoaded(baseTexture) { + this._updateID++; + + // TODO this code looks confusing.. boo to abusing getters and setters! + if (this.noFrame) { + this.frame = new _math.Rectangle(0, 0, baseTexture.width, baseTexture.height); + } else { + this.frame = this._frame; + } + + this.baseTexture.on('update', this.onBaseTextureUpdated, this); + this.emit('update', this); + }; + + /** + * Called when the base texture is updated + * + * @private + * @param {PIXI.BaseTexture} baseTexture - The base texture. + */ + + + Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated(baseTexture) { + this._updateID++; + + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + + this.emit('update', this); + }; + + /** + * Destroys this texture + * + * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well + */ + + + Texture.prototype.destroy = function destroy(destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destroyed too.. + if (_utils.TextureCache[this.baseTexture.imageUrl]) { + Texture.removeFromCache(this.baseTexture.imageUrl); + } + + this.baseTexture.destroy(); + } + + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture.off('loaded', this.onBaseTextureLoaded, this); + + this.baseTexture = null; + } + + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + + this.valid = false; + + Texture.removeFromCache(this); + this.textureCacheIds = null; + }; + + /** + * Creates a new texture object that acts the same as this one. + * + * @return {PIXI.Texture} The new texture + */ + + + Texture.prototype.clone = function clone() { + return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate, this.defaultAnchor); + }; + + /** + * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture. + */ + + + Texture.prototype._updateUvs = function _updateUvs() { + if (!this._uvs) { + this._uvs = new _TextureUvs2.default(); + } + + this._uvs.set(this._frame, this.baseTexture, this.rotate); + + this._updateID++; + }; + + /** + * Helper function that creates a Texture object from the given image url. + * If the image is not in the texture cache it will be created and loaded. + * + * @static + * @param {string} imageUrl - The image url of the texture + * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromImage = function fromImage(imageUrl, crossorigin, scaleMode, sourceScale) { + var texture = _utils.TextureCache[imageUrl]; + + if (!texture) { + texture = new Texture(_BaseTexture2.default.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); + Texture.addToCache(texture, imageUrl); + } + + return texture; + }; + + /** + * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromFrame = function fromFrame(frameId) { + var texture = _utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache'); + } + + return texture; + }; + + /** + * Helper function that creates a new Texture based on the given canvas element. + * + * @static + * @param {HTMLCanvasElement} canvas - The canvas element source of the texture + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {string} [origin='canvas'] - A string origin of who created the base texture + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromCanvas = function fromCanvas(canvas, scaleMode) { + var origin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'canvas'; + + return new Texture(_BaseTexture2.default.fromCanvas(canvas, scaleMode, origin)); + }; + + /** + * Helper function that creates a new Texture based on the given video element. + * + * @static + * @param {HTMLVideoElement|string} video - The URL or actual element of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param {boolean} [autoPlay=true] - Start playing video as soon as it is loaded + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideo = function fromVideo(video, scaleMode, crossorigin, autoPlay) { + if (typeof video === 'string') { + return Texture.fromVideoUrl(video, scaleMode, crossorigin, autoPlay); + } + + return new Texture(_VideoBaseTexture2.default.fromVideo(video, scaleMode, autoPlay)); + }; + + /** + * Helper function that creates a new Texture based on the video url. + * + * @static + * @param {string} videoUrl - URL of the video + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param {boolean} [autoPlay=true] - Start playing video as soon as it is loaded + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.fromVideoUrl = function fromVideoUrl(videoUrl, scaleMode, crossorigin, autoPlay) { + return new Texture(_VideoBaseTexture2.default.fromUrl(videoUrl, scaleMode, crossorigin, autoPlay)); + }; + + /** + * Helper function that creates a new Texture based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} + * source - Source to create texture from + * @return {PIXI.Texture} The newly created texture + */ + + + Texture.from = function from(source) { + // TODO auto detect cross origin.. + // TODO pass in scale mode? + if (typeof source === 'string') { + var texture = _utils.TextureCache[source]; + + if (!texture) { + // check if its a video.. + var isVideo = source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/) !== null; + + if (isVideo) { + return Texture.fromVideoUrl(source); + } + + return Texture.fromImage(source); + } + + return texture; + } else if (source instanceof HTMLImageElement) { + return new Texture(_BaseTexture2.default.from(source)); + } else if (source instanceof HTMLCanvasElement) { + return Texture.fromCanvas(source, _settings2.default.SCALE_MODE, 'HTMLCanvasElement'); + } else if (source instanceof HTMLVideoElement) { + return Texture.fromVideo(source); + } else if (source instanceof _BaseTexture2.default) { + return new Texture(source); + } + + // lets assume its a texture! + return source; + }; + + /** + * Create a texture from a source and add to the cache. + * + * @static + * @param {HTMLImageElement|HTMLCanvasElement} source - The input source. + * @param {String} imageUrl - File name of texture, for cache and resolving resolution. + * @param {String} [name] - Human readible name for the texture cache. If no name is + * specified, only `imageUrl` will be used as the cache ID. + * @return {PIXI.Texture} Output texture + */ + + + Texture.fromLoader = function fromLoader(source, imageUrl, name) { + var baseTexture = new _BaseTexture2.default(source, undefined, (0, _utils.getResolutionOfUrl)(imageUrl)); + var texture = new Texture(baseTexture); + + baseTexture.imageUrl = imageUrl; + + // No name, use imageUrl instead + if (!name) { + name = imageUrl; + } + + // lets also add the frame to pixi's global cache for fromFrame and fromImage fucntions + _BaseTexture2.default.addToCache(texture.baseTexture, name); + Texture.addToCache(texture, name); + + // also add references by url if they are different. + if (name !== imageUrl) { + _BaseTexture2.default.addToCache(texture.baseTexture, imageUrl); + Texture.addToCache(texture, imageUrl); + } + + return texture; + }; + + /** + * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object. + * + * @static + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the Texture will be stored against. + */ + + + Texture.addToCache = function addToCache(texture, id) { + if (id) { + if (texture.textureCacheIds.indexOf(id) === -1) { + texture.textureCacheIds.push(id); + } + + /* eslint-disable no-console */ + if (_utils.TextureCache[id]) { + console.warn('Texture added to the cache with an id [' + id + '] that already had an entry'); + } + /* eslint-enable no-console */ + + _utils.TextureCache[id] = texture; + } + }; + + /** + * Remove a Texture from the global TextureCache. + * + * @static + * @param {string|PIXI.Texture} texture - id of a Texture to be removed, or a Texture instance itself + * @return {PIXI.Texture|null} The Texture that was removed + */ + + + Texture.removeFromCache = function removeFromCache(texture) { + if (typeof texture === 'string') { + var textureFromCache = _utils.TextureCache[texture]; + + if (textureFromCache) { + var index = textureFromCache.textureCacheIds.indexOf(texture); + + if (index > -1) { + textureFromCache.textureCacheIds.splice(index, 1); + } + + delete _utils.TextureCache[texture]; + + return textureFromCache; + } + } else if (texture && texture.textureCacheIds) { + for (var i = 0; i < texture.textureCacheIds.length; ++i) { + // Check that texture matches the one being passed in before deleting it from the cache. + if (_utils.TextureCache[texture.textureCacheIds[i]] === texture) { + delete _utils.TextureCache[texture.textureCacheIds[i]]; + } + } + + texture.textureCacheIds.length = 0; + + return texture; + } + + return null; + }; + + /** + * The frame specifies the region of the base texture that this texture uses. + * Please call `_updateUvs()` after you change coordinates of `frame` manually. + * + * @member {PIXI.Rectangle} + */ + + + _createClass(Texture, [{ + key: 'frame', + get: function get() { + return this._frame; + }, + set: function set(frame) // eslint-disable-line require-jsdoc + { + this._frame = frame; + + this.noFrame = false; + + var x = frame.x, + y = frame.y, + width = frame.width, + height = frame.height; + + var xNotFit = x + width > this.baseTexture.width; + var yNotFit = y + height > this.baseTexture.height; + + if (xNotFit || yNotFit) { + var relationship = xNotFit && yNotFit ? 'and' : 'or'; + var errorX = 'X: ' + x + ' + ' + width + ' = ' + (x + width) + ' > ' + this.baseTexture.width; + var errorY = 'Y: ' + y + ' + ' + height + ' = ' + (y + height) + ' > ' + this.baseTexture.height; + + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + (errorX + ' ' + relationship + ' ' + errorY)); + } + + // this.valid = width && height && this.baseTexture.source && this.baseTexture.hasLoaded; + this.valid = width && height && this.baseTexture.hasLoaded; + + if (!this.trim && !this.rotate) { + this.orig = frame; + } + + if (this.valid) { + this._updateUvs(); + } + } + + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.GroupD8} for explanation + * + * @member {number} + */ + + }, { + key: 'rotate', + get: function get() { + return this._rotate; + }, + set: function set(rotate) // eslint-disable-line require-jsdoc + { + this._rotate = rotate; + if (this.valid) { + this._updateUvs(); + } + } + + /** + * The width of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'width', + get: function get() { + return this.orig.width; + } + + /** + * The height of the Texture in pixels. + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this.orig.height; + } + }]); + + return Texture; +}(_eventemitter2.default); + +exports.default = Texture; + + +function createWhiteTexture() { + var canvas = document.createElement('canvas'); + + canvas.width = 10; + canvas.height = 10; + + var context = canvas.getContext('2d'); + + context.fillStyle = 'white'; + context.fillRect(0, 0, 10, 10); + + return new Texture(new _BaseTexture2.default(canvas)); +} + +function removeAllHandlers(tex) { + tex.destroy = function _emptyDestroy() {/* empty */}; + tex.on = function _emptyOn() {/* empty */}; + tex.once = function _emptyOnce() {/* empty */}; + tex.emit = function _emptyEmit() {/* empty */}; +} + +/** + * An empty texture, used often to not have to create multiple empty textures. + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.EMPTY = new Texture(new _BaseTexture2.default()); +removeAllHandlers(Texture.EMPTY); +removeAllHandlers(Texture.EMPTY.baseTexture); + +/** + * A white texture of 10x10 size, used for graphics and other things + * Can not be destroyed. + * + * @static + * @constant + */ +Texture.WHITE = createWhiteTexture(); +removeAllHandlers(Texture.WHITE); +removeAllHandlers(Texture.WHITE.baseTexture); + +},{"../math":70,"../settings":101,"../utils":125,"./BaseTexture":112,"./TextureUvs":117,"./VideoBaseTexture":118,"eventemitter3":3}],116:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Matrix = require('../math/Matrix'); + +var _Matrix2 = _interopRequireDefault(_Matrix); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var tempMat = new _Matrix2.default(); + +/** + * Class controls uv transform and frame clamp for texture + * Can be used in Texture "transform" field, or separately, you can use different clamp settings on the same texture. + * If you want to add support for texture region of certain feature or filter, that's what you're looking for. + * + * @see PIXI.Texture + * @see PIXI.mesh.Mesh + * @see PIXI.extras.TilingSprite + * @class + * @memberof PIXI + */ + +var TextureMatrix = function () { + /** + * + * @param {PIXI.Texture} texture observed texture + * @param {number} [clampMargin] Changes frame clamping, 0.5 by default. Use -0.5 for extra border. + * @constructor + */ + function TextureMatrix(texture, clampMargin) { + _classCallCheck(this, TextureMatrix); + + this._texture = texture; + + this.mapCoord = new _Matrix2.default(); + + this.uClampFrame = new Float32Array(4); + + this.uClampOffset = new Float32Array(2); + + this._lastTextureID = -1; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders + * + * @default 0 + * @member {number} + */ + this.clampOffset = 0; + + /** + * Changes frame clamping + * Works with TilingSprite and Mesh + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + this.clampMargin = typeof clampMargin === 'undefined' ? 0.5 : clampMargin; + } + + /** + * texture property + * @member {PIXI.Texture} + */ + + + /** + * Multiplies uvs array to transform + * @param {Float32Array} uvs mesh uvs + * @param {Float32Array} [out=uvs] output + * @returns {Float32Array} output + */ + TextureMatrix.prototype.multiplyUvs = function multiplyUvs(uvs, out) { + if (out === undefined) { + out = uvs; + } + + var mat = this.mapCoord; + + for (var i = 0; i < uvs.length; i += 2) { + var x = uvs[i]; + var y = uvs[i + 1]; + + out[i] = x * mat.a + y * mat.c + mat.tx; + out[i + 1] = x * mat.b + y * mat.d + mat.ty; + } + + return out; + }; + + /** + * updates matrices if texture was changed + * @param {boolean} forceUpdate if true, matrices will be updated any case + * @returns {boolean} whether or not it was updated + */ + + + TextureMatrix.prototype.update = function update(forceUpdate) { + var tex = this._texture; + + if (!tex || !tex.valid) { + return false; + } + + if (!forceUpdate && this._lastTextureID === tex._updateID) { + return false; + } + + this._lastTextureID = tex._updateID; + + var uvs = tex._uvs; + + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + + var orig = tex.orig; + var trim = tex.trim; + + if (trim) { + tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat); + } + + var texBase = tex.baseTexture; + var frame = this.uClampFrame; + var margin = this.clampMargin / texBase.resolution; + var offset = this.clampOffset; + + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.uClampOffset[0] = offset / texBase.realWidth; + this.uClampOffset[1] = offset / texBase.realHeight; + + return true; + }; + + _createClass(TextureMatrix, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._texture = value; + this._lastTextureID = -1; + } + }]); + + return TextureMatrix; +}(); + +exports.default = TextureMatrix; + +},{"../math/Matrix":67}],117:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _GroupD = require('../math/GroupD8'); + +var _GroupD2 = _interopRequireDefault(_GroupD); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A standard object to store the Uvs of a texture + * + * @class + * @private + * @memberof PIXI + */ +var TextureUvs = function () { + /** + * + */ + function TextureUvs() { + _classCallCheck(this, TextureUvs); + + this.x0 = 0; + this.y0 = 0; + + this.x1 = 1; + this.y1 = 0; + + this.x2 = 1; + this.y2 = 1; + + this.x3 = 0; + this.y3 = 1; + + this.uvsUint32 = new Uint32Array(4); + } + + /** + * Sets the texture Uvs based on the given frame information. + * + * @private + * @param {PIXI.Rectangle} frame - The frame of the texture + * @param {PIXI.Rectangle} baseFrame - The base frame of the texture + * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8} + */ + + + TextureUvs.prototype.set = function set(frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + + // coordinates of center + var cX = frame.x / tw + w2; + var cY = frame.y / th + h2; + + rotate = _GroupD2.default.add(rotate, _GroupD2.default.NW); // NW is top-left corner + this.x0 = cX + w2 * _GroupD2.default.uX(rotate); + this.y0 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + w2 * _GroupD2.default.uX(rotate); + this.y1 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x2 = cX + w2 * _GroupD2.default.uX(rotate); + this.y2 = cY + h2 * _GroupD2.default.uY(rotate); + + rotate = _GroupD2.default.add(rotate, 2); + this.x3 = cX + w2 * _GroupD2.default.uX(rotate); + this.y3 = cY + h2 * _GroupD2.default.uY(rotate); + } else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + + this.uvsUint32[0] = (Math.round(this.y0 * 65535) & 0xFFFF) << 16 | Math.round(this.x0 * 65535) & 0xFFFF; + this.uvsUint32[1] = (Math.round(this.y1 * 65535) & 0xFFFF) << 16 | Math.round(this.x1 * 65535) & 0xFFFF; + this.uvsUint32[2] = (Math.round(this.y2 * 65535) & 0xFFFF) << 16 | Math.round(this.x2 * 65535) & 0xFFFF; + this.uvsUint32[3] = (Math.round(this.y3 * 65535) & 0xFFFF) << 16 | Math.round(this.x3 * 65535) & 0xFFFF; + }; + + return TextureUvs; +}(); + +exports.default = TextureUvs; + +},{"../math/GroupD8":66}],118:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _BaseTexture2 = require('./BaseTexture'); + +var _BaseTexture3 = _interopRequireDefault(_BaseTexture2); + +var _utils = require('../utils'); + +var _ticker = require('../ticker'); + +var _const = require('../const'); + +var _determineCrossOrigin = require('../utils/determineCrossOrigin'); + +var _determineCrossOrigin2 = _interopRequireDefault(_determineCrossOrigin); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A texture of a [playing] Video. + * + * Video base textures mimic PixiJS BaseTexture.from.... method in their creation process. + * + * This can be used in several ways, such as: + * + * ```js + * let texture = PIXI.VideoBaseTexture.fromUrl('http://mydomain.com/video.mp4'); + * + * let texture = PIXI.VideoBaseTexture.fromUrl({ src: 'http://mydomain.com/video.mp4', mime: 'video/mp4' }); + * + * let texture = PIXI.VideoBaseTexture.fromUrls(['/video.webm', '/video.mp4']); + * + * let texture = PIXI.VideoBaseTexture.fromUrls([ + * { src: '/video.webm', mime: 'video/webm' }, + * { src: '/video.mp4', mime: 'video/mp4' } + * ]); + * ``` + * + * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/). + * + * @class + * @extends PIXI.BaseTexture + * @memberof PIXI + */ +var VideoBaseTexture = function (_BaseTexture) { + _inherits(VideoBaseTexture, _BaseTexture); + + /** + * @param {HTMLVideoElement} source - Video source + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {boolean} [autoPlay=true] - Start playing video as soon as it is loaded + */ + function VideoBaseTexture(source, scaleMode) { + var autoPlay = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + + _classCallCheck(this, VideoBaseTexture); + + if (!source) { + throw new Error('No video source element specified.'); + } + + // hook in here to check if video is already available. + // BaseTexture looks for a source.complete boolean, plus width & height. + + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) && source.width && source.height) { + source.complete = true; + } + + var _this = _possibleConstructorReturn(this, _BaseTexture.call(this, source, scaleMode)); + + _this.width = source.videoWidth; + _this.height = source.videoHeight; + + _this._autoUpdate = true; + _this._isAutoUpdating = false; + + /** + * When set to true will automatically play videos used by this texture once + * they are loaded. If false, it will not modify the playing state. + * + * @member {boolean} + * @default true + */ + _this.autoPlay = autoPlay; + + _this.update = _this.update.bind(_this); + _this._onCanPlay = _this._onCanPlay.bind(_this); + + source.addEventListener('play', _this._onPlayStart.bind(_this)); + source.addEventListener('pause', _this._onPlayStop.bind(_this)); + _this.hasLoaded = false; + _this.__loaded = false; + + if (!_this._isSourceReady()) { + source.addEventListener('canplay', _this._onCanPlay); + source.addEventListener('canplaythrough', _this._onCanPlay); + } else { + _this._onCanPlay(); + } + return _this; + } + + /** + * Returns true if the underlying source is playing. + * + * @private + * @return {boolean} True if playing. + */ + + + VideoBaseTexture.prototype._isSourcePlaying = function _isSourcePlaying() { + var source = this.source; + + return source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2; + }; + + /** + * Returns true if the underlying source is ready for playing. + * + * @private + * @return {boolean} True if ready. + */ + + + VideoBaseTexture.prototype._isSourceReady = function _isSourceReady() { + return this.source.readyState === 3 || this.source.readyState === 4; + }; + + /** + * Runs the update loop when the video is ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStart = function _onPlayStart() { + // Just in case the video has not received its can play even yet.. + if (!this.hasLoaded) { + this._onCanPlay(); + } + + if (!this._isAutoUpdating && this.autoUpdate) { + _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); + this._isAutoUpdating = true; + } + }; + + /** + * Fired when a pause event is triggered, stops the update loop + * + * @private + */ + + + VideoBaseTexture.prototype._onPlayStop = function _onPlayStop() { + if (this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } + }; + + /** + * Fired when the video is loaded and ready to play + * + * @private + */ + + + VideoBaseTexture.prototype._onCanPlay = function _onCanPlay() { + this.hasLoaded = true; + + if (this.source) { + this.source.removeEventListener('canplay', this._onCanPlay); + this.source.removeEventListener('canplaythrough', this._onCanPlay); + + this.width = this.source.videoWidth; + this.height = this.source.videoHeight; + + // prevent multiple loaded dispatches.. + if (!this.__loaded) { + this.__loaded = true; + this.emit('loaded', this); + } + + if (this._isSourcePlaying()) { + this._onPlayStart(); + } else if (this.autoPlay) { + this.source.play(); + } + } + }; + + /** + * Destroys this texture + * + */ + + + VideoBaseTexture.prototype.destroy = function destroy() { + if (this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + } + + if (this.source && this.source._pixiId) { + _BaseTexture3.default.removeFromCache(this.source._pixiId); + delete this.source._pixiId; + + this.source.pause(); + this.source.src = ''; + this.source.load(); + } + + _BaseTexture.prototype.destroy.call(this); + }; + + /** + * Mimic PixiJS BaseTexture.from.... method. + * + * @static + * @param {HTMLVideoElement} video - Video to create texture from + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values + * @param {boolean} [autoPlay=true] - Start playing video as soon as it is loaded + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromVideo = function fromVideo(video, scaleMode, autoPlay) { + if (!video._pixiId) { + video._pixiId = 'video_' + (0, _utils.uid)(); + } + + var baseTexture = _utils.BaseTextureCache[video._pixiId]; + + if (!baseTexture) { + baseTexture = new VideoBaseTexture(video, scaleMode, autoPlay); + _BaseTexture3.default.addToCache(baseTexture, video._pixiId); + } + + return baseTexture; + }; + + /** + * Helper function that creates a new BaseTexture based on the given video element. + * This BaseTexture can then be used to create a texture + * + * @static + * @param {string|object|string[]|object[]} videoSrc - The URL(s) for the video. + * @param {string} [videoSrc.src] - One of the source urls for the video + * @param {string} [videoSrc.mime] - The mimetype of the video (e.g. 'video/mp4'). If not specified + * the url's extension will be used as the second part of the mime type. + * @param {number} scaleMode - See {@link PIXI.SCALE_MODES} for possible values + * @param {boolean} [crossorigin=(auto)] - Should use anonymous CORS? Defaults to true if the URL is not a data-URI. + * @param {boolean} [autoPlay=true] - Start playing video as soon as it is loaded + * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture + */ + + + VideoBaseTexture.fromUrl = function fromUrl(videoSrc, scaleMode, crossorigin, autoPlay) { + var video = document.createElement('video'); + + video.setAttribute('webkit-playsinline', ''); + video.setAttribute('playsinline', ''); + + var url = Array.isArray(videoSrc) ? videoSrc[0].src || videoSrc[0] : videoSrc.src || videoSrc; + + if (crossorigin === undefined && url.indexOf('data:') !== 0) { + video.crossOrigin = (0, _determineCrossOrigin2.default)(url); + } else if (crossorigin) { + video.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; + } + + // array of objects or strings + if (Array.isArray(videoSrc)) { + for (var i = 0; i < videoSrc.length; ++i) { + video.appendChild(createSource(videoSrc[i].src || videoSrc[i], videoSrc[i].mime)); + } + } + // single object or string + else { + video.appendChild(createSource(url, videoSrc.mime)); + } + + video.load(); + + return VideoBaseTexture.fromVideo(video, scaleMode, autoPlay); + }; + + /** + * Should the base texture automatically update itself, set to true by default + * + * @member {boolean} + */ + + + _createClass(VideoBaseTexture, [{ + key: 'autoUpdate', + get: function get() { + return this._autoUpdate; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + + if (!this._autoUpdate && this._isAutoUpdating) { + _ticker.shared.remove(this.update, this); + this._isAutoUpdating = false; + } else if (this._autoUpdate && !this._isAutoUpdating) { + _ticker.shared.add(this.update, this, _const.UPDATE_PRIORITY.HIGH); + this._isAutoUpdating = true; + } + } + } + }]); + + return VideoBaseTexture; +}(_BaseTexture3.default); + +exports.default = VideoBaseTexture; + + +VideoBaseTexture.fromUrls = VideoBaseTexture.fromUrl; + +function createSource(path, type) { + if (!type) { + var purePath = path.split('?').shift().toLowerCase(); + + type = 'video/' + purePath.substr(purePath.lastIndexOf('.') + 1); + } + + var source = document.createElement('source'); + + source.src = path; + source.type = type; + + return source; +} + +},{"../const":46,"../ticker":121,"../utils":125,"../utils/determineCrossOrigin":124,"./BaseTexture":112}],119:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _const = require('../const'); + +var _TickerListener = require('./TickerListener'); + +var _TickerListener2 = _interopRequireDefault(_TickerListener); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * A Ticker class that runs an update loop that other objects listen to. + * This class is composed around listeners + * meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, + * e.g. When the ticker is started and the emitter has listeners. + * + * @class + * @memberof PIXI.ticker + */ +var Ticker = function () { + /** + * + */ + function Ticker() { + var _this = this; + + _classCallCheck(this, Ticker); + + /** + * The first listener. All new listeners added are chained on this. + * @private + * @type {TickerListener} + */ + this._head = new _TickerListener2.default(null, null, Infinity); + + /** + * Internal current frame request ID + * @private + */ + this._requestId = null; + + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + * @private + */ + this._maxElapsedMS = 100; + + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.ticker.Ticker#start} automatically + * when a listener is added. + * + * @member {boolean} + * @default false + */ + this.autoStart = false; + + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.ticker.Ticker#minFPS} + * and is scaled with {@link PIXI.ticker.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + * + * @member {number} + * @default 1 + */ + this.deltaTime = 1; + + /** + * Time elapsed in milliseconds from last frame to this frame. + * Opposed to what the scalar {@link PIXI.ticker.Ticker#deltaTime} + * is based, this value is neither capped nor scaled. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * Defaults to target frame time + * + * @member {number} + * @default 16.66 + */ + this.elapsedMS = 1 / _settings2.default.TARGET_FPMS; + + /** + * The last time {@link PIXI.ticker.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + * + * @member {number} + * @default -1 + */ + this.lastTime = -1; + + /** + * Factor of current {@link PIXI.ticker.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + * + * @member {number} + * @default 1 + */ + this.speed = 1; + + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.ticker.Ticker#start} has been called. + * `false` if {@link PIXI.ticker.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.ticker.Ticker#autoStart} being `true` + * and a listener is added. + * + * @member {boolean} + * @default false + */ + this.started = false; + + /** + * Internal tick method bound to ticker instance. + * This is because in early 2015, Function.bind + * is still 60% slower in high performance scenarios. + * Also separating frame requests from update method + * so listeners may be called at any time and with + * any animation API, just invoke ticker.update(time). + * + * @private + * @param {number} time - Time since last tick. + */ + this._tick = function (time) { + _this._requestId = null; + + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._head.next) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * + * @private + */ + + + Ticker.prototype._requestIfNeeded = function _requestIfNeeded() { + if (this._requestId === null && this._head.next) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._requestId = requestAnimationFrame(this._tick); + } + }; + + /** + * Conditionally cancels a pending animation frame. + * + * @private + */ + + + Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded() { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; + + /** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * + * @private + */ + + + Ticker.prototype._startIfPossible = function _startIfPossible() { + if (this.started) { + this._requestIfNeeded(); + } else if (this.autoStart) { + this.start(); + } + }; + + /** + * Register a handler for tick events. Calls continuously unless + * it is removed or the ticker is stopped. + * + * @param {Function} fn - The listener function to be added for updates + * @param {Function} [context] - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.add = function add(fn, context) { + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _const.UPDATE_PRIORITY.NORMAL; + + return this._addListener(new _TickerListener2.default(fn, context, priority)); + }; + + /** + * Add a handler for the tick event which is only execute once. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context] - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.addOnce = function addOnce(fn, context) { + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _const.UPDATE_PRIORITY.NORMAL; + + return this._addListener(new _TickerListener2.default(fn, context, priority, true)); + }; + + /** + * Internally adds the event handler so that it can be sorted by priority. + * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run + * before the rendering. + * + * @private + * @param {TickerListener} listener - Current listener being added. + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype._addListener = function _addListener(listener) { + // For attaching to head + var current = this._head.next; + var previous = this._head; + + // Add the first item + if (!current) { + listener.connect(previous); + } else { + // Go from highest to lowest priority + while (current) { + if (listener.priority > current.priority) { + listener.connect(previous); + break; + } + previous = current; + current = current.next; + } + + // Not yet connected + if (!listener.previous) { + listener.connect(previous); + } + } + + this._startIfPossible(); + + return this; + }; + + /** + * Removes any handlers matching the function and context parameters. + * If no handlers are left after removing, then it cancels the animation frame. + * + * @param {Function} fn - The listener function to be removed + * @param {Function} [context] - The listener context to be removed + * @returns {PIXI.ticker.Ticker} This instance of a ticker + */ + + + Ticker.prototype.remove = function remove(fn, context) { + var listener = this._head.next; + + while (listener) { + // We found a match, lets remove it + // no break to delete all possible matches + // incase a listener was added 2+ times + if (listener.match(fn, context)) { + listener = listener.destroy(); + } else { + listener = listener.next; + } + } + + if (!this._head.next) { + this._cancelIfNeeded(); + } + + return this; + }; + + /** + * Starts the ticker. If the ticker has listeners + * a new animation frame is requested at this point. + */ + + + Ticker.prototype.start = function start() { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + }; + + /** + * Stops the ticker. If the ticker has requested + * an animation frame it is canceled at this point. + */ + + + Ticker.prototype.stop = function stop() { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; + + /** + * Destroy the ticker and don't use after this. Calling + * this method removes all references to internal events. + */ + + + Ticker.prototype.destroy = function destroy() { + this.stop(); + + var listener = this._head.next; + + while (listener) { + listener = listener.destroy(true); + } + + this._head.destroy(); + this._head = null; + }; + + /** + * Triggers an update. An update entails setting the + * current {@link PIXI.ticker.Ticker#elapsedMS}, + * the current {@link PIXI.ticker.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.ticker.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + + + Ticker.prototype.update = function update() { + var currentTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : performance.now(); + + var elapsedMS = void 0; + + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + + this.deltaTime = elapsedMS * _settings2.default.TARGET_FPMS * this.speed; + + // Cache a local reference, in-case ticker is destroyed + // during the emit, we can still check for head.next + var head = this._head; + + // Invoke listeners added to internal emitter + var listener = head.next; + + while (listener) { + listener = listener.emit(this.deltaTime); + } + + if (!head.next) { + this._cancelIfNeeded(); + } + } else { + this.deltaTime = this.elapsedMS = 0; + } + + this.lastTime = currentTime; + }; + + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.ticker.Ticker#speed}, which is specific + * to scaling {@link PIXI.ticker.Ticker#deltaTime}. + * + * @member {number} + * @readonly + */ + + + _createClass(Ticker, [{ + key: 'FPS', + get: function get() { + return 1000 / this.elapsedMS; + } + + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.ticker.Ticker#update}. + * This value is used to cap {@link PIXI.ticker.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.ticker.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.settings.TARGET_FPMS * 1000`. + * + * @member {number} + * @default 10 + */ + + }, { + key: 'minFPS', + get: function get() { + return 1000 / this._maxElapsedMS; + }, + set: function set(fps) // eslint-disable-line require-jsdoc + { + // Clamp: 0 to TARGET_FPMS + var minFPMS = Math.min(Math.max(0, fps) / 1000, _settings2.default.TARGET_FPMS); + + this._maxElapsedMS = 1 / minFPMS; + } + }]); + + return Ticker; +}(); + +exports.default = Ticker; + +},{"../const":46,"../settings":101,"./TickerListener":120}],120:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Internal class for handling the priority sorting of ticker handlers. + * + * @private + * @class + * @memberof PIXI.ticker + */ +var TickerListener = function () { + /** + * Constructor + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} [context=null] - The listener context + * @param {number} [priority=0] - The priority for emitting + * @param {boolean} [once=false] - If the handler should fire once + */ + function TickerListener(fn) { + var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + var once = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + _classCallCheck(this, TickerListener); + + /** + * The handler function to execute. + * @member {Function} + */ + this.fn = fn; + + /** + * The calling to execute. + * @member {Function} + */ + this.context = context; + + /** + * The current priority. + * @member {number} + */ + this.priority = priority; + + /** + * If this should only execute once. + * @member {boolean} + */ + this.once = once; + + /** + * The next item in chain. + * @member {TickerListener} + */ + this.next = null; + + /** + * The previous item in chain. + * @member {TickerListener} + */ + this.previous = null; + + /** + * `true` if this listener has been destroyed already. + * @member {boolean} + * @private + */ + this._destroyed = false; + } + + /** + * Simple compare function to figure out if a function and context match. + * + * @param {Function} fn - The listener function to be added for one update + * @param {Function} context - The listener context + * @return {boolean} `true` if the listener match the arguments + */ + + + TickerListener.prototype.match = function match(fn, context) { + context = context || null; + + return this.fn === fn && this.context === context; + }; + + /** + * Emit by calling the current function. + * @param {number} deltaTime - time since the last emit. + * @return {TickerListener} Next ticker + */ + + + TickerListener.prototype.emit = function emit(deltaTime) { + if (this.fn) { + if (this.context) { + this.fn.call(this.context, deltaTime); + } else { + this.fn(deltaTime); + } + } + + var redirect = this.next; + + if (this.once) { + this.destroy(true); + } + + // Soft-destroying should remove + // the next reference + if (this._destroyed) { + this.next = null; + } + + return redirect; + }; + + /** + * Connect to the list. + * @param {TickerListener} previous - Input node, previous listener + */ + + + TickerListener.prototype.connect = function connect(previous) { + this.previous = previous; + if (previous.next) { + previous.next.previous = this; + } + this.next = previous.next; + previous.next = this; + }; + + /** + * Destroy and don't use after this. + * @param {boolean} [hard = false] `true` to remove the `next` reference, this + * is considered a hard destroy. Soft destroy maintains the next reference. + * @return {TickerListener} The listener to redirect while emitting or removing. + */ + + + TickerListener.prototype.destroy = function destroy() { + var hard = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + + this._destroyed = true; + this.fn = null; + this.context = null; + + // Disconnect, hook up next and previous + if (this.previous) { + this.previous.next = this.next; + } + + if (this.next) { + this.next.previous = this.previous; + } + + // Redirect to the next item + var redirect = this.next; + + // Remove references + this.next = hard ? null : redirect; + this.previous = null; + + return redirect; + }; + + return TickerListener; +}(); + +exports.default = TickerListener; + +},{}],121:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.Ticker = exports.shared = undefined; + +var _Ticker = require('./Ticker'); + +var _Ticker2 = _interopRequireDefault(_Ticker); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The shared ticker instance used by {@link PIXI.extras.AnimatedSprite}. + * and by {@link PIXI.interaction.InteractionManager}. + * The property {@link PIXI.ticker.Ticker#autoStart} is set to `true` + * for this instance. Please follow the examples for usage, including + * how to opt-out of auto-starting the shared ticker. + * + * @example + * let ticker = PIXI.ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(800, 600); + * let stage = new PIXI.Container(); + * let interactionManager = PIXI.interaction.InteractionManager(renderer); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * + * @type {PIXI.ticker.Ticker} + * @memberof PIXI.ticker + */ +var shared = new _Ticker2.default(); + +shared.autoStart = true; +shared.destroy = function () { + // protect destroying shared ticker + // this is used by other internal systems + // like AnimatedSprite and InteractionManager +}; + +/** + * This namespace contains an API for interacting with PIXI's internal global update loop. + * + * This ticker is used for rendering, {@link PIXI.extras.AnimatedSprite AnimatedSprite}, + * {@link PIXI.interaction.InteractionManager InteractionManager} and many other time-based PIXI systems. + * @example + * const ticker = new PIXI.ticker.Ticker(); + * ticker.stop(); + * ticker.add((deltaTime) => { + * // do something every frame + * }); + * ticker.start(); + * @namespace PIXI.ticker + */ +exports.shared = shared; +exports.Ticker = _Ticker2.default; + +},{"./Ticker":119}],122:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = canUploadSameBuffer; +function canUploadSameBuffer() { + // Uploading the same buffer multiple times in a single frame can cause perf issues. + // Apparent on IOS so only check for that at the moment + // this check may become more complex if this issue pops up elsewhere. + var ios = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform); + + return !ios; +} + +},{}],123:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = createIndicesForQuads; +/** + * Generic Mask Stack data structure + * + * @memberof PIXI + * @function createIndicesForQuads + * @private + * @param {number} size - Number of quads + * @return {Uint16Array} indices + */ +function createIndicesForQuads(size) { + // the total number of indices in our array, there are 6 points per quad. + + var totalIndices = size * 6; + + var indices = new Uint16Array(totalIndices); + + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + indices[i + 0] = j + 0; + indices[i + 1] = j + 1; + indices[i + 2] = j + 2; + indices[i + 3] = j + 0; + indices[i + 4] = j + 2; + indices[i + 5] = j + 3; + } + + return indices; +} + +},{}],124:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = determineCrossOrigin; + +var _url2 = require('url'); + +var _url3 = _interopRequireDefault(_url2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var tempAnchor = void 0; + +/** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @return {string} The crossOrigin value to use (or empty string for none). + */ +function determineCrossOrigin(url) { + var loc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location; + + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + + // default is window.location + loc = loc || window.location; + + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + url = _url3.default.parse(tempAnchor.href); + + var samePort = !url.port && loc.port === '' || url.port === loc.port; + + // if cross origin + if (url.hostname !== loc.hostname || !samePort || url.protocol !== loc.protocol) { + return 'anonymous'; + } + + return ''; +} + +},{"url":38}],125:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.premultiplyBlendMode = exports.BaseTextureCache = exports.TextureCache = exports.earcut = exports.mixins = exports.pluginTarget = exports.EventEmitter = exports.removeItems = exports.isMobile = undefined; +exports.uid = uid; +exports.hex2rgb = hex2rgb; +exports.hex2string = hex2string; +exports.rgb2hex = rgb2hex; +exports.getResolutionOfUrl = getResolutionOfUrl; +exports.decomposeDataUri = decomposeDataUri; +exports.getUrlFileExtension = getUrlFileExtension; +exports.getSvgSize = getSvgSize; +exports.skipHello = skipHello; +exports.sayHello = sayHello; +exports.isWebGLSupported = isWebGLSupported; +exports.sign = sign; +exports.destroyTextureCache = destroyTextureCache; +exports.clearTextureCache = clearTextureCache; +exports.correctBlendMode = correctBlendMode; +exports.premultiplyTint = premultiplyTint; +exports.premultiplyRgba = premultiplyRgba; +exports.premultiplyTintToRgba = premultiplyTintToRgba; + +var _const = require('../const'); + +var _settings = require('../settings'); + +var _settings2 = _interopRequireDefault(_settings); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _pluginTarget = require('./pluginTarget'); + +var _pluginTarget2 = _interopRequireDefault(_pluginTarget); + +var _mixin = require('./mixin'); + +var mixins = _interopRequireWildcard(_mixin); + +var _ismobilejs = require('ismobilejs'); + +var isMobile = _interopRequireWildcard(_ismobilejs); + +var _removeArrayItems = require('remove-array-items'); + +var _removeArrayItems2 = _interopRequireDefault(_removeArrayItems); + +var _mapPremultipliedBlendModes = require('./mapPremultipliedBlendModes'); + +var _mapPremultipliedBlendModes2 = _interopRequireDefault(_mapPremultipliedBlendModes); + +var _earcut = require('earcut'); + +var _earcut2 = _interopRequireDefault(_earcut); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var nextUid = 0; +var saidHello = false; + +/** + * Generalized convenience utilities for PIXI. + * @example + * // Extend PIXI's internal Event Emitter. + * class MyEmitter extends PIXI.utils.EventEmitter { + * constructor() { + * super(); + * console.log("Emitter created!"); + * } + * } + * + * // Get info on current device + * console.log(PIXI.utils.isMobile); + * + * // Convert hex color to string + * console.log(PIXI.utils.hex2string(0xff00ff)); // returns: "#ff00ff" + * @namespace PIXI.utils + */ +exports.isMobile = isMobile; +exports.removeItems = _removeArrayItems2.default; +exports.EventEmitter = _eventemitter2.default; +exports.pluginTarget = _pluginTarget2.default; +exports.mixins = mixins; +exports.earcut = _earcut2.default; + +/** + * Gets the next unique identifier + * + * @memberof PIXI.utils + * @function uid + * @return {number} The next unique identifier to use. + */ + +function uid() { + return ++nextUid; +} + +/** + * Converts a hex color number to an [R, G, B] array + * + * @memberof PIXI.utils + * @function hex2rgb + * @param {number} hex - The number to convert + * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one + * @return {number[]} An array representing the [R, G, B] of the color. + */ +function hex2rgb(hex, out) { + out = out || []; + + out[0] = (hex >> 16 & 0xFF) / 255; + out[1] = (hex >> 8 & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + + return out; +} + +/** + * Converts a hex color number to a string. + * + * @memberof PIXI.utils + * @function hex2string + * @param {number} hex - Number in hex + * @return {string} The string color. + */ +function hex2string(hex) { + hex = hex.toString(16); + hex = '000000'.substr(0, 6 - hex.length) + hex; + + return '#' + hex; +} + +/** + * Converts a color as an [R, G, B] array to a hex number + * + * @memberof PIXI.utils + * @function rgb2hex + * @param {number[]} rgb - rgb array + * @return {number} The color number + */ +function rgb2hex(rgb) { + return (rgb[0] * 255 << 16) + (rgb[1] * 255 << 8) + (rgb[2] * 255 | 0); +} + +/** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * + * @memberof PIXI.utils + * @function getResolutionOfUrl + * @param {string} url - the image path + * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. + * @return {number} resolution / device pixel ratio of an asset + */ +function getResolutionOfUrl(url, defaultValue) { + var resolution = _settings2.default.RETINA_PREFIX.exec(url); + + if (resolution) { + return parseFloat(resolution[1]); + } + + return defaultValue !== undefined ? defaultValue : 1; +} + +/** + * Typedef for decomposeDataUri return object. + * + * @typedef {object} PIXI.utils~DecomposedDataUri + * @property {mediaType} Media type, eg. `image` + * @property {subType} Sub type, eg. `png` + * @property {encoding} Data encoding, eg. `base64` + * @property {data} The actual data + */ + +/** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. + * + * @memberof PIXI.utils + * @function decomposeDataUri + * @param {string} dataUri - the data URI to check + * @return {PIXI.utils~DecomposedDataUri|undefined} The decomposed data uri or undefined + */ +function decomposeDataUri(dataUri) { + var dataUriMatch = _const.DATA_URI.exec(dataUri); + + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : undefined, + data: dataUriMatch[5] + }; + } + + return undefined; +} + +/** + * Get type of the image by regexp for extension. Returns undefined for unknown extensions. + * + * @memberof PIXI.utils + * @function getUrlFileExtension + * @param {string} url - the image path + * @return {string|undefined} image extension + */ +function getUrlFileExtension(url) { + var extension = _const.URL_FILE_EXTENSION.exec(url); + + if (extension) { + return extension[1].toLowerCase(); + } + + return undefined; +} + +/** + * Typedef for Size object. + * + * @typedef {object} PIXI.utils~Size + * @property {width} Width component + * @property {height} Height component + */ + +/** + * Get size from an svg string using regexp. + * + * @memberof PIXI.utils + * @function getSvgSize + * @param {string} svgString - a serialized svg element + * @return {PIXI.utils~Size|undefined} image extension + */ +function getSvgSize(svgString) { + var sizeMatch = _const.SVG_SIZE.exec(svgString); + var size = {}; + + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); + size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); + } + + return size; +} + +/** + * Skips the hello message of renderers that are created after this is run. + * + * @function skipHello + * @memberof PIXI.utils + */ +function skipHello() { + saidHello = true; +} + +/** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever makes you a jerk face. + * + * @static + * @function sayHello + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ +function sayHello(type) { + if (saidHello) { + return; + } + + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = ['\n %c %c %c PixiJS ' + _const.VERSION + ' - \u2730 ' + type + ' \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n', 'background: #ff66a5; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff66a5; background: #030307; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'background: #ffc3dc; padding:5px 0;', 'background: #ff66a5; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;', 'color: #ff2424; background: #fff; padding:5px 0;']; + + window.console.log.apply(console, args); + } else if (window.console) { + window.console.log('PixiJS ' + _const.VERSION + ' - ' + type + ' - http://www.pixijs.com/'); + } + + saidHello = true; +} + +/** + * Helper for checking for webgl support + * + * @memberof PIXI.utils + * @function isWebGLSupported + * @return {boolean} is webgl supported + */ +function isWebGLSupported() { + var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true }; + + try { + if (!window.WebGLRenderingContext) { + return false; + } + + var canvas = document.createElement('canvas'); + var gl = canvas.getContext('webgl', contextOptions) || canvas.getContext('experimental-webgl', contextOptions); + + var success = !!(gl && gl.getContextAttributes().stencil); + + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + + if (loseContext) { + loseContext.loseContext(); + } + } + + gl = null; + + return success; + } catch (e) { + return false; + } +} + +/** + * Returns sign of number + * + * @memberof PIXI.utils + * @function sign + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ +function sign(n) { + if (n === 0) return 0; + + return n < 0 ? -1 : 1; +} + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var TextureCache = exports.TextureCache = Object.create(null); + +/** + * @todo Describe property usage + * + * @memberof PIXI.utils + * @private + */ +var BaseTextureCache = exports.BaseTextureCache = Object.create(null); + +/** + * Destroys all texture in the cache + * + * @memberof PIXI.utils + * @function destroyTextureCache + */ +function destroyTextureCache() { + var key = void 0; + + for (key in TextureCache) { + TextureCache[key].destroy(); + } + for (key in BaseTextureCache) { + BaseTextureCache[key].destroy(); + } +} + +/** + * Removes all textures from cache, but does not destroy them + * + * @memberof PIXI.utils + * @function clearTextureCache + */ +function clearTextureCache() { + var key = void 0; + + for (key in TextureCache) { + delete TextureCache[key]; + } + for (key in BaseTextureCache) { + delete BaseTextureCache[key]; + } +} + +/** + * maps premultiply flag and blendMode to adjusted blendMode + * @memberof PIXI.utils + * @const premultiplyBlendMode + * @type {Array} + */ +var premultiplyBlendMode = exports.premultiplyBlendMode = (0, _mapPremultipliedBlendModes2.default)(); + +/** + * changes blendMode according to texture format + * + * @memberof PIXI.utils + * @function correctBlendMode + * @param {number} blendMode supposed blend mode + * @param {boolean} premultiplied whether source is premultiplied + * @returns {number} true blend mode for this texture + */ +function correctBlendMode(blendMode, premultiplied) { + return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; +} + +/** + * premultiplies tint + * + * @memberof PIXI.utils + * @param {number} tint integet RGB + * @param {number} alpha floating point alpha (0.0-1.0) + * @returns {number} tint multiplied by alpha + */ +function premultiplyTint(tint, alpha) { + if (alpha === 1.0) { + return (alpha * 255 << 24) + tint; + } + if (alpha === 0.0) { + return 0; + } + var R = tint >> 16 & 0xFF; + var G = tint >> 8 & 0xFF; + var B = tint & 0xFF; + + R = R * alpha + 0.5 | 0; + G = G * alpha + 0.5 | 0; + B = B * alpha + 0.5 | 0; + + return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; +} + +/** + * combines rgb and alpha to out array + * + * @memberof PIXI.utils + * @param {Float32Array|number[]} rgb input rgb + * @param {number} alpha alpha param + * @param {Float32Array} [out] output + * @param {boolean} [premultiply=true] do premultiply it + * @returns {Float32Array} vec4 rgba + */ +function premultiplyRgba(rgb, alpha, out, premultiply) { + out = out || new Float32Array(4); + if (premultiply || premultiply === undefined) { + out[0] = rgb[0] * alpha; + out[1] = rgb[1] * alpha; + out[2] = rgb[2] * alpha; + } else { + out[0] = rgb[0]; + out[1] = rgb[1]; + out[2] = rgb[2]; + } + out[3] = alpha; + + return out; +} + +/** + * converts integer tint and float alpha to vec4 form, premultiplies by default + * + * @memberof PIXI.utils + * @param {number} tint input tint + * @param {number} alpha alpha param + * @param {Float32Array} [out] output + * @param {boolean} [premultiply=true] do premultiply it + * @returns {Float32Array} vec4 rgba + */ +function premultiplyTintToRgba(tint, alpha, out, premultiply) { + out = out || new Float32Array(4); + out[0] = (tint >> 16 & 0xFF) / 255.0; + out[1] = (tint >> 8 & 0xFF) / 255.0; + out[2] = (tint & 0xFF) / 255.0; + if (premultiply || premultiply === undefined) { + out[0] *= alpha; + out[1] *= alpha; + out[2] *= alpha; + } + out[3] = alpha; + + return out; +} + +},{"../const":46,"../settings":101,"./mapPremultipliedBlendModes":126,"./mixin":128,"./pluginTarget":129,"earcut":2,"eventemitter3":3,"ismobilejs":4,"remove-array-items":31}],126:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = mapPremultipliedBlendModes; + +var _const = require('../const'); + +/** + * Corrects PixiJS blend, takes premultiplied alpha into account + * + * @memberof PIXI + * @function mapPremultipliedBlendModes + * @private + * @param {Array} [array] - The array to output into. + * @return {Array} Mapped modes. + */ + +function mapPremultipliedBlendModes() { + var pm = []; + var npm = []; + + for (var i = 0; i < 32; i++) { + pm[i] = i; + npm[i] = i; + } + + pm[_const.BLEND_MODES.NORMAL_NPM] = _const.BLEND_MODES.NORMAL; + pm[_const.BLEND_MODES.ADD_NPM] = _const.BLEND_MODES.ADD; + pm[_const.BLEND_MODES.SCREEN_NPM] = _const.BLEND_MODES.SCREEN; + + npm[_const.BLEND_MODES.NORMAL] = _const.BLEND_MODES.NORMAL_NPM; + npm[_const.BLEND_MODES.ADD] = _const.BLEND_MODES.ADD_NPM; + npm[_const.BLEND_MODES.SCREEN] = _const.BLEND_MODES.SCREEN_NPM; + + var array = []; + + array.push(npm); + array.push(pm); + + return array; +} + +},{"../const":46}],127:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = maxRecommendedTextures; + +var _ismobilejs = require('ismobilejs'); + +var _ismobilejs2 = _interopRequireDefault(_ismobilejs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function maxRecommendedTextures(max) { + if (_ismobilejs2.default.tablet || _ismobilejs2.default.phone) { + // check if the res is iphone 6 or higher.. + return 4; + } + + // desktop should be ok + return max; +} + +},{"ismobilejs":4}],128:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.mixin = mixin; +exports.delayMixin = delayMixin; +exports.performMixins = performMixins; +/** + * Mixes all enumerable properties and methods from a source object to a target object. + * + * @memberof PIXI.utils.mixins + * @function mixin + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function mixin(target, source) { + if (!target || !source) return; + // in ES8/ES2017, this would be really easy: + // Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + + // get all the enumerable property keys + var keys = Object.keys(source); + + // loop through properties + for (var i = 0; i < keys.length; ++i) { + var propertyName = keys[i]; + + // Set the property using the property descriptor - this works for accessors and normal value properties + Object.defineProperty(target, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); + } +} + +var mixins = []; + +/** + * Queues a mixin to be handled towards the end of the initialization of PIXI, so that deprecation + * can take effect. + * + * @memberof PIXI.utils.mixins + * @function delayMixin + * @private + * @param {object} target The prototype or instance that properties and methods should be added to. + * @param {object} source The source of properties and methods to mix in. + */ +function delayMixin(target, source) { + mixins.push(target, source); +} + +/** + * Handles all mixins queued via delayMixin(). + * + * @memberof PIXI.utils.mixins + * @function performMixins + * @private + */ +function performMixins() { + for (var i = 0; i < mixins.length; i += 2) { + mixin(mixins[i], mixins[i + 1]); + } + mixins.length = 0; +} + +},{}],129:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +/** + * Mixins functionality to make an object have "plugins". + * + * @example + * function MyObject() {} + * + * pluginTarget.mixin(MyObject); + * + * @mixin + * @memberof PIXI.utils + * @param {object} obj - The object to mix into. + */ +function pluginTarget(obj) { + obj.__plugins = {}; + + /** + * Adds a plugin to an object + * + * @param {string} pluginName - The events that should be listed. + * @param {Function} ctor - The constructor function for the plugin. + */ + obj.registerPlugin = function registerPlugin(pluginName, ctor) { + obj.__plugins[pluginName] = ctor; + }; + + /** + * Instantiates all the plugins of this object + * + */ + obj.prototype.initPlugins = function initPlugins() { + this.plugins = this.plugins || {}; + + for (var o in obj.__plugins) { + this.plugins[o] = new obj.__plugins[o](this); + } + }; + + /** + * Removes all the plugins of this object + * + */ + obj.prototype.destroyPlugins = function destroyPlugins() { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + + this.plugins = null; + }; +} + +exports.default = { + /** + * Mixes in the properties of the pluginTarget into another object + * + * @param {object} obj - The obj to mix into + */ + mixin: function mixin(obj) { + pluginTarget(obj); + } +}; + +},{}],130:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = trimCanvas; +/** + * Trim transparent borders from a canvas + * + * @memberof PIXI + * @function trimCanvas + * @private + * @param {HTMLCanvasElement} canvas - the canvas to trim + * @returns {object} Trim data + */ +function trimCanvas(canvas) { + // https://gist.github.com/remy/784508 + + var width = canvas.width; + var height = canvas.height; + + var context = canvas.getContext('2d'); + var imageData = context.getImageData(0, 0, width, height); + var pixels = imageData.data; + var len = pixels.length; + + var bound = { + top: null, + left: null, + right: null, + bottom: null + }; + var data = null; + var i = void 0; + var x = void 0; + var y = void 0; + + for (i = 0; i < len; i += 4) { + if (pixels[i + 3] !== 0) { + x = i / 4 % width; + y = ~~(i / 4 / width); + + if (bound.top === null) { + bound.top = y; + } + + if (bound.left === null) { + bound.left = x; + } else if (x < bound.left) { + bound.left = x; + } + + if (bound.right === null) { + bound.right = x + 1; + } else if (bound.right < x) { + bound.right = x + 1; + } + + if (bound.bottom === null) { + bound.bottom = y; + } else if (bound.bottom < y) { + bound.bottom = y; + } + } + } + + if (bound.top !== null) { + width = bound.right - bound.left; + height = bound.bottom - bound.top + 1; + data = context.getImageData(bound.left, bound.top, width, height); + } + + return { + height: height, + width: width, + data: data + }; +} + +},{}],131:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = deprecation; +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code + +// A map of warning messages already fired +var warnings = {}; + +// provide method to give a stack track for warnings +// useful for tracking-down where deprecated methods/properties/classes +// are being used within the code +function warn(msg) { + // Ignore duplicat + if (warnings[msg]) { + return; + } + + /* eslint-disable no-console */ + var stack = new Error().stack; + + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('Deprecation Warning: ', msg); + } else { + // chop off the stack trace which includes pixi.js internal calls + stack = stack.split('\n').splice(3).join('\n'); + + if (console.groupCollapsed) { + console.groupCollapsed('%cDeprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', msg); + console.warn(stack); + console.groupEnd(); + } else { + console.warn('Deprecation Warning: ', msg); + console.warn(stack); + } + } + /* eslint-enable no-console */ + + warnings[msg] = true; +} + +function deprecation(core) { + var mesh = core.mesh, + particles = core.particles, + extras = core.extras, + filters = core.filters, + prepare = core.prepare, + loaders = core.loaders, + interaction = core.interaction; + + + Object.defineProperties(core, { + + /** + * @class + * @private + * @name SpriteBatch + * @memberof PIXI + * @see PIXI.ParticleContainer + * @throws {ReferenceError} SpriteBatch does not exist any more, please use the new ParticleContainer instead. + * @deprecated since version 3.0.0 + */ + SpriteBatch: { + get: function get() { + throw new ReferenceError('SpriteBatch does not exist any more, ' + 'please use the new ParticleContainer instead.'); + } + }, + + /** + * @class + * @private + * @name AssetLoader + * @memberof PIXI + * @see PIXI.loaders.Loader + * @throws {ReferenceError} The loader system was overhauled in PixiJS v3, + * please see the new PIXI.loaders.Loader class. + * @deprecated since version 3.0.0 + */ + AssetLoader: { + get: function get() { + throw new ReferenceError('The loader system was overhauled in PixiJS v3, ' + 'please see the new PIXI.loaders.Loader class.'); + } + }, + + /** + * @class + * @private + * @name Stage + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + Stage: { + get: function get() { + warn('You do not need to use a PIXI Stage any more, you can simply render any container.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name DisplayObjectContainer + * @memberof PIXI + * @see PIXI.Container + * @deprecated since version 3.0.0 + */ + DisplayObjectContainer: { + get: function get() { + warn('DisplayObjectContainer has been shortened to Container, please use Container from now on.'); + + return core.Container; + } + }, + + /** + * @class + * @private + * @name Strip + * @memberof PIXI + * @see PIXI.mesh.Mesh + * @deprecated since version 3.0.0 + */ + Strip: { + get: function get() { + warn('The Strip class has been renamed to Mesh and moved to mesh.Mesh, please use mesh.Mesh from now on.'); + + return mesh.Mesh; + } + }, + + /** + * @class + * @private + * @name Rope + * @memberof PIXI + * @see PIXI.mesh.Rope + * @deprecated since version 3.0.0 + */ + Rope: { + get: function get() { + warn('The Rope class has been moved to mesh.Rope, please use mesh.Rope from now on.'); + + return mesh.Rope; + } + }, + + /** + * @class + * @private + * @name ParticleContainer + * @memberof PIXI + * @see PIXI.particles.ParticleContainer + * @deprecated since version 4.0.0 + */ + ParticleContainer: { + get: function get() { + warn('The ParticleContainer class has been moved to particles.ParticleContainer, ' + 'please use particles.ParticleContainer from now on.'); + + return particles.ParticleContainer; + } + }, + + /** + * @class + * @private + * @name MovieClip + * @memberof PIXI + * @see PIXI.extras.MovieClip + * @deprecated since version 3.0.0 + */ + MovieClip: { + get: function get() { + warn('The MovieClip class has been moved to extras.AnimatedSprite, please use extras.AnimatedSprite.'); + + return extras.AnimatedSprite; + } + }, + + /** + * @class + * @private + * @name TilingSprite + * @memberof PIXI + * @see PIXI.extras.TilingSprite + * @deprecated since version 3.0.0 + */ + TilingSprite: { + get: function get() { + warn('The TilingSprite class has been moved to extras.TilingSprite, ' + 'please use extras.TilingSprite from now on.'); + + return extras.TilingSprite; + } + }, + + /** + * @class + * @private + * @name BitmapText + * @memberof PIXI + * @see PIXI.extras.BitmapText + * @deprecated since version 3.0.0 + */ + BitmapText: { + get: function get() { + warn('The BitmapText class has been moved to extras.BitmapText, ' + 'please use extras.BitmapText from now on.'); + + return extras.BitmapText; + } + }, + + /** + * @class + * @private + * @name blendModes + * @memberof PIXI + * @see PIXI.BLEND_MODES + * @deprecated since version 3.0.0 + */ + blendModes: { + get: function get() { + warn('The blendModes has been moved to BLEND_MODES, please use BLEND_MODES from now on.'); + + return core.BLEND_MODES; + } + }, + + /** + * @class + * @private + * @name scaleModes + * @memberof PIXI + * @see PIXI.SCALE_MODES + * @deprecated since version 3.0.0 + */ + scaleModes: { + get: function get() { + warn('The scaleModes has been moved to SCALE_MODES, please use SCALE_MODES from now on.'); + + return core.SCALE_MODES; + } + }, + + /** + * @class + * @private + * @name BaseTextureCache + * @memberof PIXI + * @see PIXI.utils.BaseTextureCache + * @deprecated since version 3.0.0 + */ + BaseTextureCache: { + get: function get() { + warn('The BaseTextureCache class has been moved to utils.BaseTextureCache, ' + 'please use utils.BaseTextureCache from now on.'); + + return core.utils.BaseTextureCache; + } + }, + + /** + * @class + * @private + * @name TextureCache + * @memberof PIXI + * @see PIXI.utils.TextureCache + * @deprecated since version 3.0.0 + */ + TextureCache: { + get: function get() { + warn('The TextureCache class has been moved to utils.TextureCache, ' + 'please use utils.TextureCache from now on.'); + + return core.utils.TextureCache; + } + }, + + /** + * @namespace + * @private + * @name math + * @memberof PIXI + * @see PIXI + * @deprecated since version 3.0.6 + */ + math: { + get: function get() { + warn('The math namespace is deprecated, please access members already accessible on PIXI.'); + + return core; + } + }, + + /** + * @class + * @private + * @name PIXI.AbstractFilter + * @see PIXI.Filter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.Filter; + } + }, + + /** + * @class + * @private + * @name PIXI.TransformManual + * @see PIXI.TransformBase + * @deprecated since version 4.0.0 + */ + TransformManual: { + get: function get() { + warn('TransformManual has been renamed to TransformBase, please update your pixi-spine'); + + return core.TransformBase; + } + }, + + /** + * @static + * @constant + * @name PIXI.TARGET_FPMS + * @see PIXI.settings.TARGET_FPMS + * @deprecated since version 4.2.0 + */ + TARGET_FPMS: { + get: function get() { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + return core.settings.TARGET_FPMS; + }, + set: function set(value) { + warn('PIXI.TARGET_FPMS has been deprecated, please use PIXI.settings.TARGET_FPMS'); + + core.settings.TARGET_FPMS = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.FILTER_RESOLUTION + * @see PIXI.settings.FILTER_RESOLUTION + * @deprecated since version 4.2.0 + */ + FILTER_RESOLUTION: { + get: function get() { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + return core.settings.FILTER_RESOLUTION; + }, + set: function set(value) { + warn('PIXI.FILTER_RESOLUTION has been deprecated, please use PIXI.settings.FILTER_RESOLUTION'); + + core.settings.FILTER_RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RESOLUTION + * @see PIXI.settings.RESOLUTION + * @deprecated since version 4.2.0 + */ + RESOLUTION: { + get: function get() { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + return core.settings.RESOLUTION; + }, + set: function set(value) { + warn('PIXI.RESOLUTION has been deprecated, please use PIXI.settings.RESOLUTION'); + + core.settings.RESOLUTION = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.MIPMAP_TEXTURES + * @see PIXI.settings.MIPMAP_TEXTURES + * @deprecated since version 4.2.0 + */ + MIPMAP_TEXTURES: { + get: function get() { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + return core.settings.MIPMAP_TEXTURES; + }, + set: function set(value) { + warn('PIXI.MIPMAP_TEXTURES has been deprecated, please use PIXI.settings.MIPMAP_TEXTURES'); + + core.settings.MIPMAP_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_BATCH_SIZE + * @see PIXI.settings.SPRITE_BATCH_SIZE + * @deprecated since version 4.2.0 + */ + SPRITE_BATCH_SIZE: { + get: function get() { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + return core.settings.SPRITE_BATCH_SIZE; + }, + set: function set(value) { + warn('PIXI.SPRITE_BATCH_SIZE has been deprecated, please use PIXI.settings.SPRITE_BATCH_SIZE'); + + core.settings.SPRITE_BATCH_SIZE = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.SPRITE_MAX_TEXTURES + * @see PIXI.settings.SPRITE_MAX_TEXTURES + * @deprecated since version 4.2.0 + */ + SPRITE_MAX_TEXTURES: { + get: function get() { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + return core.settings.SPRITE_MAX_TEXTURES; + }, + set: function set(value) { + warn('PIXI.SPRITE_MAX_TEXTURES has been deprecated, please use PIXI.settings.SPRITE_MAX_TEXTURES'); + + core.settings.SPRITE_MAX_TEXTURES = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.RETINA_PREFIX + * @see PIXI.settings.RETINA_PREFIX + * @deprecated since version 4.2.0 + */ + RETINA_PREFIX: { + get: function get() { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + return core.settings.RETINA_PREFIX; + }, + set: function set(value) { + warn('PIXI.RETINA_PREFIX has been deprecated, please use PIXI.settings.RETINA_PREFIX'); + + core.settings.RETINA_PREFIX = value; + } + }, + + /** + * @static + * @constant + * @name PIXI.DEFAULT_RENDER_OPTIONS + * @see PIXI.settings.RENDER_OPTIONS + * @deprecated since version 4.2.0 + */ + DEFAULT_RENDER_OPTIONS: { + get: function get() { + warn('PIXI.DEFAULT_RENDER_OPTIONS has been deprecated, please use PIXI.settings.DEFAULT_RENDER_OPTIONS'); + + return core.settings.RENDER_OPTIONS; + } + } + }); + + // Move the default properties to settings + var defaults = [{ parent: 'TRANSFORM_MODE', target: 'TRANSFORM_MODE' }, { parent: 'GC_MODES', target: 'GC_MODE' }, { parent: 'WRAP_MODES', target: 'WRAP_MODE' }, { parent: 'SCALE_MODES', target: 'SCALE_MODE' }, { parent: 'PRECISION', target: 'PRECISION_FRAGMENT' }]; + + var _loop = function _loop(i) { + var deprecation = defaults[i]; + + Object.defineProperty(core[deprecation.parent], 'DEFAULT', { + get: function get() { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); + + return core.settings[deprecation.target]; + }, + set: function set(value) { + warn('PIXI.' + deprecation.parent + '.DEFAULT has been deprecated, ' + ('please use PIXI.settings.' + deprecation.target)); + + core.settings[deprecation.target] = value; + } + }); + }; + + for (var i = 0; i < defaults.length; i++) { + _loop(i); + } + + Object.defineProperties(core.settings, { + + /** + * @static + * @name PRECISION + * @memberof PIXI.settings + * @see PIXI.PRECISION + * @deprecated since version 4.4.0 + */ + PRECISION: { + get: function get() { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + return core.settings.PRECISION_FRAGMENT; + }, + set: function set(value) { + warn('PIXI.settings.PRECISION has been deprecated, please use PIXI.settings.PRECISION_FRAGMENT'); + + core.settings.PRECISION_FRAGMENT = value; + } + } + }); + + if (extras.AnimatedSprite) { + Object.defineProperties(extras, { + + /** + * @class + * @name MovieClip + * @memberof PIXI.extras + * @see PIXI.extras.AnimatedSprite + * @deprecated since version 4.2.0 + */ + MovieClip: { + get: function get() { + warn('The MovieClip class has been renamed to AnimatedSprite, please use AnimatedSprite from now on.'); + + return extras.AnimatedSprite; + } + } + }); + } + + if (extras) { + Object.defineProperties(extras, { + /** + * @class + * @name TextureTransform + * @memberof PIXI.extras + * @see PIXI.TextureMatrix + * @deprecated since version 4.6.0 + */ + TextureTransform: { + get: function get() { + warn('The TextureTransform class has been renamed to TextureMatrix, ' + 'please use PIXI.TextureMatrix from now on.'); + + return core.TextureMatrix; + } + } + }); + } + + core.DisplayObject.prototype.generateTexture = function generateTexture(renderer, scaleMode, resolution) { + warn('generateTexture has moved to the renderer, please use renderer.generateTexture(displayObject)'); + + return renderer.generateTexture(this, scaleMode, resolution); + }; + + core.Graphics.prototype.generateTexture = function generateTexture(scaleMode, resolution) { + warn('graphics generate texture has moved to the renderer. ' + 'Or to render a graphics to a texture using canvas please use generateCanvasTexture'); + + return this.generateCanvasTexture(scaleMode, resolution); + }; + + /** + * @method + * @name PIXI.GroupD8.isSwapWidthHeight + * @see PIXI.GroupD8.isVertical + * @param {number} rotation - The number to check. + * @returns {boolean} Whether or not the direction is vertical + * @deprecated since version 4.6.0 + */ + core.GroupD8.isSwapWidthHeight = function isSwapWidthHeight(rotation) { + warn('GroupD8.isSwapWidthHeight was renamed to GroupD8.isVertical'); + + return core.GroupD8.isVertical(rotation); + }; + + core.RenderTexture.prototype.render = function render(displayObject, matrix, clear, updateTransform) { + this.legacyRenderer.render(displayObject, this, clear, matrix, !updateTransform); + warn('RenderTexture.render is now deprecated, please use renderer.render(displayObject, renderTexture)'); + }; + + core.RenderTexture.prototype.getImage = function getImage(target) { + warn('RenderTexture.getImage is now deprecated, please use renderer.extract.image(target)'); + + return this.legacyRenderer.extract.image(target); + }; + + core.RenderTexture.prototype.getBase64 = function getBase64(target) { + warn('RenderTexture.getBase64 is now deprecated, please use renderer.extract.base64(target)'); + + return this.legacyRenderer.extract.base64(target); + }; + + core.RenderTexture.prototype.getCanvas = function getCanvas(target) { + warn('RenderTexture.getCanvas is now deprecated, please use renderer.extract.canvas(target)'); + + return this.legacyRenderer.extract.canvas(target); + }; + + core.RenderTexture.prototype.getPixels = function getPixels(target) { + warn('RenderTexture.getPixels is now deprecated, please use renderer.extract.pixels(target)'); + + return this.legacyRenderer.pixels(target); + }; + + /** + * @method + * @private + * @name PIXI.Sprite#setTexture + * @see PIXI.Sprite#texture + * @deprecated since version 3.0.0 + * @param {PIXI.Texture} texture - The texture to set to. + */ + core.Sprite.prototype.setTexture = function setTexture(texture) { + this.texture = texture; + warn('setTexture is now deprecated, please use the texture property, e.g : sprite.texture = texture;'); + }; + + if (extras.BitmapText) { + /** + * @method + * @name PIXI.extras.BitmapText#setText + * @see PIXI.extras.BitmapText#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ + extras.BitmapText.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myBitmapText.text = \'my text\';'); + }; + } + + /** + * @method + * @name PIXI.Text#setText + * @see PIXI.Text#text + * @deprecated since version 3.0.0 + * @param {string} text - The text to set to. + */ + core.Text.prototype.setText = function setText(text) { + this.text = text; + warn('setText is now deprecated, please use the text property, e.g : myText.text = \'my text\';'); + }; + + /** + * Calculates the ascent, descent and fontSize of a given fontStyle + * + * @name PIXI.Text.calculateFontProperties + * @see PIXI.TextMetrics.measureFont + * @deprecated since version 4.5.0 + * @param {string} font - String representing the style of the font + * @return {Object} Font properties object + */ + core.Text.calculateFontProperties = function calculateFontProperties(font) { + warn('Text.calculateFontProperties is now deprecated, please use the TextMetrics.measureFont'); + + return core.TextMetrics.measureFont(font); + }; + + Object.defineProperties(core.Text, { + fontPropertiesCache: { + get: function get() { + warn('Text.fontPropertiesCache is deprecated'); + + return core.TextMetrics._fonts; + } + }, + fontPropertiesCanvas: { + get: function get() { + warn('Text.fontPropertiesCanvas is deprecated'); + + return core.TextMetrics._canvas; + } + }, + fontPropertiesContext: { + get: function get() { + warn('Text.fontPropertiesContext is deprecated'); + + return core.TextMetrics._context; + } + } + }); + + /** + * @method + * @name PIXI.Text#setStyle + * @see PIXI.Text#style + * @deprecated since version 3.0.0 + * @param {*} style - The style to set to. + */ + core.Text.prototype.setStyle = function setStyle(style) { + this.style = style; + warn('setStyle is now deprecated, please use the style property, e.g : myText.style = style;'); + }; + + /** + * @method + * @name PIXI.Text#determineFontProperties + * @see PIXI.Text#measureFontProperties + * @deprecated since version 4.2.0 + * @private + * @param {string} fontStyle - String representing the style of the font + * @return {Object} Font properties object + */ + core.Text.prototype.determineFontProperties = function determineFontProperties(fontStyle) { + warn('determineFontProperties is now deprecated, please use TextMetrics.measureFont method'); + + return core.TextMetrics.measureFont(fontStyle); + }; + + /** + * @method + * @name PIXI.Text.getFontStyle + * @see PIXI.TextMetrics.getFontStyle + * @deprecated since version 4.5.0 + * @param {PIXI.TextStyle} style - The style to use. + * @return {string} Font string + */ + core.Text.getFontStyle = function getFontStyle(style) { + warn('getFontStyle is now deprecated, please use TextStyle.toFontString() instead'); + + style = style || {}; + + if (!(style instanceof core.TextStyle)) { + style = new core.TextStyle(style); + } + + return style.toFontString(); + }; + + Object.defineProperties(core.TextStyle.prototype, { + /** + * Set all properties of a font as a single string + * + * @name PIXI.TextStyle#font + * @deprecated since version 4.0.0 + */ + font: { + get: function get() { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\', \'fontSize\', \'fontStyle\', \'fontVariant\' and \'fontWeight\' properties from now on'); + + var fontSizeString = typeof this._fontSize === 'number' ? this._fontSize + 'px' : this._fontSize; + + return this._fontStyle + ' ' + this._fontVariant + ' ' + this._fontWeight + ' ' + fontSizeString + ' ' + this._fontFamily; + }, + set: function set(font) { + warn('text style property \'font\' is now deprecated, please use the ' + '\'fontFamily\',\'fontSize\',fontStyle\',\'fontVariant\' and \'fontWeight\' properties from now on'); + + // can work out fontStyle from search of whole string + if (font.indexOf('italic') > 1) { + this._fontStyle = 'italic'; + } else if (font.indexOf('oblique') > -1) { + this._fontStyle = 'oblique'; + } else { + this._fontStyle = 'normal'; + } + + // can work out fontVariant from search of whole string + if (font.indexOf('small-caps') > -1) { + this._fontVariant = 'small-caps'; + } else { + this._fontVariant = 'normal'; + } + + // fontWeight and fontFamily are tricker to find, but it's easier to find the fontSize due to it's units + var splits = font.split(' '); + var fontSizeIndex = -1; + + this._fontSize = 26; + for (var i = 0; i < splits.length; ++i) { + if (splits[i].match(/(px|pt|em|%)/)) { + fontSizeIndex = i; + this._fontSize = splits[i]; + break; + } + } + + // we can now search for fontWeight as we know it must occur before the fontSize + this._fontWeight = 'normal'; + for (var _i = 0; _i < fontSizeIndex; ++_i) { + if (splits[_i].match(/(bold|bolder|lighter|100|200|300|400|500|600|700|800|900)/)) { + this._fontWeight = splits[_i]; + break; + } + } + + // and finally join everything together after the fontSize in case the font family has multiple words + if (fontSizeIndex > -1 && fontSizeIndex < splits.length - 1) { + this._fontFamily = ''; + for (var _i2 = fontSizeIndex + 1; _i2 < splits.length; ++_i2) { + this._fontFamily += splits[_i2] + ' '; + } + + this._fontFamily = this._fontFamily.slice(0, -1); + } else { + this._fontFamily = 'Arial'; + } + + this.styleID++; + } + } + }); + + /** + * @method + * @name PIXI.Texture#setFrame + * @see PIXI.Texture#setFrame + * @deprecated since version 3.0.0 + * @param {PIXI.Rectangle} frame - The frame to set. + */ + core.Texture.prototype.setFrame = function setFrame(frame) { + this.frame = frame; + warn('setFrame is now deprecated, please use the frame property, e.g: myTexture.frame = frame;'); + }; + + /** + * @static + * @function + * @name PIXI.Texture.addTextureToCache + * @see PIXI.Texture.addToCache + * @deprecated since 4.5.0 + * @param {PIXI.Texture} texture - The Texture to add to the cache. + * @param {string} id - The id that the texture will be stored against. + */ + core.Texture.addTextureToCache = function addTextureToCache(texture, id) { + core.Texture.addToCache(texture, id); + warn('Texture.addTextureToCache is deprecated, please use Texture.addToCache from now on.'); + }; + + /** + * @static + * @function + * @name PIXI.Texture.removeTextureFromCache + * @see PIXI.Texture.removeFromCache + * @deprecated since 4.5.0 + * @param {string} id - The id of the texture to be removed + * @return {PIXI.Texture|null} The texture that was removed + */ + core.Texture.removeTextureFromCache = function removeTextureFromCache(id) { + warn('Texture.removeTextureFromCache is deprecated, please use Texture.removeFromCache from now on. ' + 'Be aware that Texture.removeFromCache does not automatically its BaseTexture from the BaseTextureCache. ' + 'For that, use BaseTexture.removeFromCache'); + + core.BaseTexture.removeFromCache(id); + + return core.Texture.removeFromCache(id); + }; + + Object.defineProperties(filters, { + + /** + * @class + * @private + * @name PIXI.filters.AbstractFilter + * @see PIXI.AbstractFilter + * @deprecated since version 3.0.6 + */ + AbstractFilter: { + get: function get() { + warn('AstractFilter has been renamed to Filter, please use PIXI.Filter'); + + return core.AbstractFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.SpriteMaskFilter + * @see PIXI.SpriteMaskFilter + * @deprecated since version 3.0.6 + */ + SpriteMaskFilter: { + get: function get() { + warn('filters.SpriteMaskFilter is an undocumented alias, please use SpriteMaskFilter from now on.'); + + return core.SpriteMaskFilter; + } + }, + + /** + * @class + * @private + * @name PIXI.filters.VoidFilter + * @see PIXI.filters.AlphaFilter + * @deprecated since version 4.5.7 + */ + VoidFilter: { + get: function get() { + warn('VoidFilter has been renamed to AlphaFilter, please use PIXI.filters.AlphaFilter'); + + return filters.AlphaFilter; + } + } + }); + + /** + * @method + * @name PIXI.utils.uuid + * @see PIXI.utils.uid + * @deprecated since version 3.0.6 + * @return {number} The uid + */ + core.utils.uuid = function () { + warn('utils.uuid() is deprecated, please use utils.uid() from now on.'); + + return core.utils.uid(); + }; + + /** + * @method + * @name PIXI.utils.canUseNewCanvasBlendModes + * @see PIXI.CanvasTinter + * @deprecated + * @return {boolean} Can use blend modes. + */ + core.utils.canUseNewCanvasBlendModes = function () { + warn('utils.canUseNewCanvasBlendModes() is deprecated, please use CanvasTinter.canUseMultiply from now on'); + + return core.CanvasTinter.canUseMultiply; + }; + + var saidHello = true; + + /** + * @name PIXI.utils._saidHello + * @type {boolean} + * @see PIXI.utils.skipHello + * @deprecated since 4.1.0 + */ + Object.defineProperty(core.utils, '_saidHello', { + set: function set(bool) { + if (bool) { + warn('PIXI.utils._saidHello is deprecated, please use PIXI.utils.skipHello()'); + this.skipHello(); + } + saidHello = bool; + }, + get: function get() { + return saidHello; + } + }); + + if (prepare.BasePrepare) { + /** + * @method + * @name PIXI.prepare.BasePrepare#register + * @see PIXI.prepare.BasePrepare#registerFindHook + * @deprecated since version 4.4.2 + * @param {Function} [addHook] - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @param {Function} [uploadHook] - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + prepare.BasePrepare.prototype.register = function register(addHook, uploadHook) { + warn('renderer.plugins.prepare.register is now deprecated, ' + 'please use renderer.plugins.prepare.registerFindHook & renderer.plugins.prepare.registerUploadHook'); + + if (addHook) { + this.registerFindHook(addHook); + } + + if (uploadHook) { + this.registerUploadHook(uploadHook); + } + + return this; + }; + } + + if (prepare.canvas) { + /** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.canvas.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ + Object.defineProperty(prepare.canvas, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.CanvasPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } + }); + } + + if (prepare.webgl) { + /** + * The number of graphics or textures to upload to the GPU. + * + * @name PIXI.prepare.webgl.UPLOADS_PER_FRAME + * @static + * @type {number} + * @see PIXI.prepare.BasePrepare.limiter + * @deprecated since 4.2.0 + */ + Object.defineProperty(prepare.webgl, 'UPLOADS_PER_FRAME', { + set: function set() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please set ' + 'renderer.plugins.prepare.limiter.maxItemsPerFrame on your renderer'); + // because we don't have a reference to the renderer, we can't actually set + // the uploads per frame, so we'll have to stick with the warning. + }, + get: function get() { + warn('PIXI.WebGLPrepare.UPLOADS_PER_FRAME has been removed. Please use ' + 'renderer.plugins.prepare.limiter'); + + return NaN; + } + }); + } + + if (loaders.Loader) { + var Resource = loaders.Resource; + var Loader = loaders.Loader; + + Object.defineProperties(Resource.prototype, { + isJson: { + get: function get() { + warn('The isJson property is deprecated, please use `resource.type === Resource.TYPE.JSON`.'); + + return this.type === Resource.TYPE.JSON; + } + }, + isXml: { + get: function get() { + warn('The isXml property is deprecated, please use `resource.type === Resource.TYPE.XML`.'); + + return this.type === Resource.TYPE.XML; + } + }, + isImage: { + get: function get() { + warn('The isImage property is deprecated, please use `resource.type === Resource.TYPE.IMAGE`.'); + + return this.type === Resource.TYPE.IMAGE; + } + }, + isAudio: { + get: function get() { + warn('The isAudio property is deprecated, please use `resource.type === Resource.TYPE.AUDIO`.'); + + return this.type === Resource.TYPE.AUDIO; + } + }, + isVideo: { + get: function get() { + warn('The isVideo property is deprecated, please use `resource.type === Resource.TYPE.VIDEO`.'); + + return this.type === Resource.TYPE.VIDEO; + } + } + }); + + Object.defineProperties(Loader.prototype, { + before: { + get: function get() { + warn('The before() method is deprecated, please use pre().'); + + return this.pre; + } + }, + after: { + get: function get() { + warn('The after() method is deprecated, please use use().'); + + return this.use; + } + } + }); + } + + if (interaction.interactiveTarget) { + /** + * @name PIXI.interaction.interactiveTarget#defaultCursor + * @static + * @type {number} + * @see PIXI.interaction.interactiveTarget#cursor + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.interactiveTarget, 'defaultCursor', { + set: function set(value) { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + this.cursor = value; + }, + get: function get() { + warn('Property defaultCursor has been replaced with \'cursor\'. '); + + return this.cursor; + } + }); + } + + if (interaction.InteractionManager) { + /** + * @name PIXI.interaction.InteractionManager#defaultCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.InteractionManager, 'defaultCursorStyle', { + set: function set(value) { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + this.cursorStyles.default = value; + }, + get: function get() { + warn('Property defaultCursorStyle has been replaced with \'cursorStyles.default\'. '); + + return this.cursorStyles.default; + } + }); + + /** + * @name PIXI.interaction.InteractionManager#currentCursorStyle + * @static + * @type {string} + * @see PIXI.interaction.InteractionManager#cursorStyles + * @deprecated since 4.3.0 + */ + Object.defineProperty(interaction.InteractionManager, 'currentCursorStyle', { + set: function set(value) { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + this.currentCursorMode = value; + }, + get: function get() { + warn('Property currentCursorStyle has been removed.' + 'See the currentCursorMode property, which works differently.'); + + return this.currentCursorMode; + } + }); + } +} + +},{}],132:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI.extract + */ + +var CanvasExtract = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasExtract(renderer) { + _classCallCheck(this, CanvasExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.extract.CanvasExtract} extract + * @memberof PIXI.CanvasRenderer# + * @see PIXI.extract.CanvasExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + CanvasExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `CanvasExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + CanvasExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + CanvasExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + resolution = renderer.resolution; + frame = TEMP_RECT; + frame.width = this.renderer.width; + frame.height = this.renderer.height; + } + + var width = Math.floor(frame.width * resolution + 1e-4); + var height = Math.floor(frame.height * resolution + 1e-4); + + var canvasBuffer = new core.CanvasRenderTarget(width, height, 1); + var canvasData = context.getImageData(frame.x * resolution, frame.y * resolution, width, height); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // send the canvas back.. + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + CanvasExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var context = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = renderer.generateTexture(target); + } + } + + if (renderTexture) { + context = renderTexture.baseTexture._canvasRenderTarget.context; + resolution = renderTexture.baseTexture._canvasRenderTarget.resolution; + frame = renderTexture.frame; + } else { + context = renderer.rootContext; + + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + + return context.getImageData(0, 0, frame.width * resolution, frame.height * resolution).data; + }; + + /** + * Destroys the extract + * + */ + + + CanvasExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return CanvasExtract; +}(); + +exports.default = CanvasExtract; + + +core.CanvasRenderer.registerPlugin('extract', CanvasExtract); + +},{"../../core":65}],133:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLExtract = require('./webgl/WebGLExtract'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLExtract).default; + } +}); + +var _CanvasExtract = require('./canvas/CanvasExtract'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasExtract).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./canvas/CanvasExtract":132,"./webgl/WebGLExtract":134}],134:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TEMP_RECT = new core.Rectangle(); +var BYTES_PER_PIXEL = 4; + +/** + * The extract manager provides functionality to export content from the renderers. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.extract + * + * @class + * @memberof PIXI.extract + */ + +var WebGLExtract = function () { + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLExtract(renderer) { + _classCallCheck(this, WebGLExtract); + + this.renderer = renderer; + /** + * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture + * + * @member {PIXI.extract.WebGLExtract} extract + * @memberof PIXI.WebGLRenderer# + * @see PIXI.extract.WebGLExtract + */ + renderer.extract = this; + } + + /** + * Will return a HTML Image of the target + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLImageElement} HTML Image of the target + */ + + + WebGLExtract.prototype.image = function image(target) { + var image = new Image(); + + image.src = this.base64(target); + + return image; + }; + + /** + * Will return a a base64 encoded string of this target. It works by calling + * `WebGLExtract.getCanvas` and then running toDataURL on that. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {string} A base64 encoded string of the texture. + */ + + + WebGLExtract.prototype.base64 = function base64(target) { + return this.canvas(target).toDataURL(); + }; + + /** + * Creates a Canvas element, renders this target to it and then returns it. + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. + */ + + + WebGLExtract.prototype.canvas = function canvas(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var flipY = false; + var renderTexture = void 0; + var generated = false; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + generated = true; + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + flipY = false; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + flipY = true; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = Math.floor(frame.width * resolution + 1e-4); + var height = Math.floor(frame.height * resolution + 1e-4); + + var canvasBuffer = new core.CanvasRenderTarget(width, height, 1); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + + // set up an array of pixels + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + + canvasData.data.set(webglPixels); + + canvasBuffer.context.putImageData(canvasData, 0, 0); + + // pulling pixels + if (flipY) { + canvasBuffer.context.scale(1, -1); + canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height); + } + } + + if (generated) { + renderTexture.destroy(true); + } + // send the canvas back.. + + return canvasBuffer.canvas; + }; + + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * + * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture + * to convert. If left empty will use use the main renderer + * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture + */ + + + WebGLExtract.prototype.pixels = function pixels(target) { + var renderer = this.renderer; + var textureBuffer = void 0; + var resolution = void 0; + var frame = void 0; + var renderTexture = void 0; + var generated = false; + + if (target) { + if (target instanceof core.RenderTexture) { + renderTexture = target; + } else { + renderTexture = this.renderer.generateTexture(target); + generated = true; + } + } + + if (renderTexture) { + textureBuffer = renderTexture.baseTexture._glRenderTargets[this.renderer.CONTEXT_UID]; + resolution = textureBuffer.resolution; + frame = renderTexture.frame; + } else { + textureBuffer = this.renderer.rootRenderTarget; + resolution = textureBuffer.resolution; + + frame = TEMP_RECT; + frame.width = textureBuffer.size.width; + frame.height = textureBuffer.size.height; + } + + var width = frame.width * resolution; + var height = frame.height * resolution; + + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + + if (textureBuffer) { + // bind the buffer + renderer.bindRenderTarget(textureBuffer); + // read pixels to the array + var gl = renderer.gl; + + gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + } + + if (generated) { + renderTexture.destroy(true); + } + + return webglPixels; + }; + + /** + * Destroys the extract + * + */ + + + WebGLExtract.prototype.destroy = function destroy() { + this.renderer.extract = null; + this.renderer = null; + }; + + return WebGLExtract; +}(); + +exports.default = WebGLExtract; + + +core.WebGLRenderer.registerPlugin('extract', WebGLExtract); + +},{"../../core":65}],135:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @typedef PIXI.extras.AnimatedSprite~FrameObject + * @type {object} + * @property {PIXI.Texture} texture - The {@link PIXI.Texture} of the frame + * @property {number} time - the duration of the frame in ms + */ + +/** + * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. + * + * ```js + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; + * + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.fromImage(alienImages[i]); + * textureArray.push(texture); + * }; + * + * let animatedSprite = new PIXI.extras.AnimatedSprite(textureArray); + * ``` + * + * The more efficient and simpler way to create an animated sprite is using a {@link PIXI.Spritesheet} + * containing the animation definitions: + * + * ```js + * PIXI.loader.add("assets/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.loader.resources["assets/spritesheet.json"].spritesheet; + * animatedSprite = new PIXI.extras.AnimatedSprite(sheet.animations["image_sequence"]); + * ... + * } + * ``` + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ +var AnimatedSprite = function (_core$Sprite) { + _inherits(AnimatedSprite, _core$Sprite); + + /** + * @param {PIXI.Texture[]|PIXI.extras.AnimatedSprite~FrameObject[]} textures - an array of {@link PIXI.Texture} or frame + * objects that make up the animation + * @param {boolean} [autoUpdate=true] - Whether to use PIXI.ticker.shared to auto update animation time. + */ + function AnimatedSprite(textures, autoUpdate) { + _classCallCheck(this, AnimatedSprite); + + /** + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, textures[0] instanceof core.Texture ? textures[0] : textures[0].texture)); + + _this._textures = null; + + /** + * @private + */ + _this._durations = null; + + _this.textures = textures; + + /** + * `true` uses PIXI.ticker.shared to auto update animation time. + * @type {boolean} + * @default true + * @private + */ + _this._autoUpdate = autoUpdate !== false; + + /** + * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower + * + * @member {number} + * @default 1 + */ + _this.animationSpeed = 1; + + /** + * Whether or not the animate sprite repeats after playing. + * + * @member {boolean} + * @default true + */ + _this.loop = true; + + /** + * Update anchor to [Texture's defaultAnchor]{@link PIXI.Texture#defaultAnchor} when frame changes. + * + * Useful with [sprite sheet animations]{@link PIXI.Spritesheet#animations} created with tools. + * Changing anchor for each frame allows to pin sprite origin to certain moving feature + * of the frame (e.g. left foot). + * + * Note: Enabling this will override any previously set `anchor` on each frame change. + * + * @member {boolean} + * @default false + */ + _this.updateAnchor = false; + + /** + * Function to call when a AnimatedSprite finishes playing + * + * @member {Function} + */ + _this.onComplete = null; + + /** + * Function to call when a AnimatedSprite changes which texture is being rendered + * + * @member {Function} + */ + _this.onFrameChange = null; + + /** + * Function to call when 'loop' is true, and an AnimatedSprite is played and loops around to start again + * + * @member {Function} + */ + _this.onLoop = null; + + /** + * Elapsed time since animation has been started, used internally to display current texture + * + * @member {number} + * @private + */ + _this._currentTime = 0; + + /** + * Indicates if the AnimatedSprite is currently playing + * + * @member {boolean} + * @readonly + */ + _this.playing = false; + return _this; + } + + /** + * Stops the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.stop = function stop() { + if (!this.playing) { + return; + } + + this.playing = false; + if (this._autoUpdate) { + core.ticker.shared.remove(this.update, this); + } + }; + + /** + * Plays the AnimatedSprite + * + */ + + + AnimatedSprite.prototype.play = function play() { + if (this.playing) { + return; + } + + this.playing = true; + if (this._autoUpdate) { + core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.HIGH); + } + }; + + /** + * Stops the AnimatedSprite and goes to a specific frame + * + * @param {number} frameNumber - frame index to stop at + */ + + + AnimatedSprite.prototype.gotoAndStop = function gotoAndStop(frameNumber) { + this.stop(); + + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + + /** + * Goes to a specific frame and begins playing the AnimatedSprite + * + * @param {number} frameNumber - frame index to start at + */ + + + AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay(frameNumber) { + var previousFrame = this.currentFrame; + + this._currentTime = frameNumber; + + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + + this.play(); + }; + + /** + * Updates the object transform for rendering. + * + * @private + * @param {number} deltaTime - Time since last tick. + */ + + + AnimatedSprite.prototype.update = function update(deltaTime) { + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + + lag += elapsed / 60 * 1000; + + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + + var sign = Math.sign(this.animationSpeed * deltaTime); + + this._currentTime = Math.floor(this._currentTime); + + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + + this._currentTime += lag / this._durations[this.currentFrame]; + } else { + this._currentTime += elapsed; + } + + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + + if (this.onComplete) { + this.onComplete(); + } + } else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + + if (this.onComplete) { + this.onComplete(); + } + } else if (previousFrame !== this.currentFrame) { + if (this.loop && this.onLoop) { + if (this.animationSpeed > 0 && this.currentFrame < previousFrame) { + this.onLoop(); + } else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) { + this.onLoop(); + } + } + + this.updateTexture(); + } + }; + + /** + * Updates the displayed texture to match the current frame index + * + * @private + */ + + + AnimatedSprite.prototype.updateTexture = function updateTexture() { + this._texture = this._textures[this.currentFrame]; + this._textureID = -1; + this.cachedTint = 0xFFFFFF; + + if (this.updateAnchor) { + this._anchor.copy(this._texture.defaultAnchor); + } + + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + }; + + /** + * Stops the AnimatedSprite and destroys it + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + AnimatedSprite.prototype.destroy = function destroy(options) { + this.stop(); + _core$Sprite.prototype.destroy.call(this, options); + }; + + /** + * A short hand way of creating a movieclip from an array of frame ids + * + * @static + * @param {string[]} frames - The array of frames ids the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animated sprite with the specified frames. + */ + + + AnimatedSprite.fromFrames = function fromFrames(frames) { + var textures = []; + + for (var i = 0; i < frames.length; ++i) { + textures.push(core.Texture.fromFrame(frames[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * A short hand way of creating a movieclip from an array of image ids + * + * @static + * @param {string[]} images - the array of image urls the movieclip will use as its texture frames + * @return {AnimatedSprite} The new animate sprite with the specified images as frames. + */ + + + AnimatedSprite.fromImages = function fromImages(images) { + var textures = []; + + for (var i = 0; i < images.length; ++i) { + textures.push(core.Texture.fromImage(images[i])); + } + + return new AnimatedSprite(textures); + }; + + /** + * totalFrames is the total number of frames in the AnimatedSprite. This is the same as number of textures + * assigned to the AnimatedSprite. + * + * @readonly + * @member {number} + * @default 0 + */ + + + _createClass(AnimatedSprite, [{ + key: 'totalFrames', + get: function get() { + return this._textures.length; + } + + /** + * The array of textures used for this AnimatedSprite + * + * @member {PIXI.Texture[]} + */ + + }, { + key: 'textures', + get: function get() { + return this._textures; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (value[0] instanceof core.Texture) { + this._textures = value; + this._durations = null; + } else { + this._textures = []; + this._durations = []; + + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + this.gotoAndStop(0); + this.updateTexture(); + } + + /** + * The AnimatedSprites current frame index + * + * @member {number} + * @readonly + */ + + }, { + key: 'currentFrame', + get: function get() { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + + return currentFrame; + } + }]); + + return AnimatedSprite; +}(core.Sprite); + +exports.default = AnimatedSprite; + +},{"../core":65}],136:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _ObservablePoint = require('../core/math/ObservablePoint'); + +var _ObservablePoint2 = _interopRequireDefault(_ObservablePoint); + +var _utils = require('../core/utils'); + +var _settings = require('../core/settings'); + +var _settings2 = _interopRequireDefault(_settings); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * A BitmapText object will create a line or multiple lines of text using bitmap font. To + * split a line you can use '\n', '\r' or '\r\n' in your string. You can generate the fnt files using: + * + * A BitmapText can only be created when the font is loaded + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.extras.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); + * ``` + * + * http://www.angelcode.com/products/bmfont/ for windows or + * http://www.bmglyph.com/ for mac. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.extras + */ +var BitmapText = function (_core$Container) { + _inherits(BitmapText, _core$Container); + + /** + * @param {string} text - The copy that you would like the text to display + * @param {object} style - The style parameters + * @param {string|object} style.font - The font descriptor for the object, can be passed as a string of form + * "24px FontName" or "FontName" or as an object with explicit name/size properties. + * @param {string} [style.font.name] - The bitmap font id + * @param {number} [style.font.size] - The size of the font in pixels, e.g. 24 + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), does not affect + * single line text + * @param {number} [style.tint=0xFFFFFF] - The tint color + */ + function BitmapText(text) { + var style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _classCallCheck(this, BitmapText); + + /** + * Private tracker for the width of the overall text + * + * @member {number} + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._textWidth = 0; + + /** + * Private tracker for the height of the overall text + * + * @member {number} + * @private + */ + _this._textHeight = 0; + + /** + * Private tracker for the letter sprite pool. + * + * @member {PIXI.Sprite[]} + * @private + */ + _this._glyphs = []; + + /** + * Private tracker for the current style. + * + * @member {object} + * @private + */ + _this._font = { + tint: style.tint !== undefined ? style.tint : 0xFFFFFF, + align: style.align || 'left', + name: null, + size: 0 + }; + + /** + * Private tracker for the current font. + * + * @member {object} + * @private + */ + _this.font = style.font; // run font setter + + /** + * Private tracker for the current text. + * + * @member {string} + * @private + */ + _this._text = text; + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + * @private + */ + _this._maxWidth = 0; + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + * @private + */ + _this._maxLineHeight = 0; + + /** + * Letter spacing. This is useful for setting the space between characters. + * @member {number} + * @private + */ + _this._letterSpacing = 0; + + /** + * Text anchor. read-only + * + * @member {PIXI.ObservablePoint} + * @private + */ + _this._anchor = new _ObservablePoint2.default(function () { + _this.dirty = true; + }, _this, 0, 0); + + /** + * The dirty state of this object. + * + * @member {boolean} + */ + _this.dirty = false; + + _this.updateText(); + return _this; + } + + /** + * Renders text and updates it when needed + * + * @private + */ + + + BitmapText.prototype.updateText = function updateText() { + var data = BitmapText.fonts[this._font.name]; + var scale = this._font.size / data.size; + var pos = new core.Point(); + var chars = []; + var lineWidths = []; + var text = this.text.replace(/(?:\r\n|\r)/g, '\n'); + var textLength = text.length; + var maxWidth = this._maxWidth * data.size / this._font.size; + + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastBreakPos = -1; + var lastBreakWidth = 0; + var spacesRemoved = 0; + var maxLineHeight = 0; + + for (var i = 0; i < textLength; i++) { + var charCode = text.charCodeAt(i); + var char = text.charAt(i); + + if (/(?:\s)/.test(char)) { + lastBreakPos = i; + lastBreakWidth = lastLineWidth; + } + + if (char === '\r' || char === '\n') { + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + ++line; + ++spacesRemoved; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + continue; + } + + var charData = data.chars[charCode]; + + if (!charData) { + continue; + } + + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + + chars.push({ + texture: charData.texture, + line: line, + charCode: charCode, + position: new core.Point(pos.x + charData.xOffset + this._letterSpacing / 2, pos.y + charData.yOffset) + }); + pos.x += charData.xAdvance + this._letterSpacing; + lastLineWidth = pos.x; + maxLineHeight = Math.max(maxLineHeight, charData.yOffset + charData.texture.height); + prevCharCode = charCode; + + if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth) { + ++spacesRemoved; + core.utils.removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos); + i = lastBreakPos; + lastBreakPos = -1; + + lineWidths.push(lastBreakWidth); + maxLineWidth = Math.max(maxLineWidth, lastBreakWidth); + line++; + + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + } + } + + var lastChar = text.charAt(text.length - 1); + + if (lastChar !== '\r' && lastChar !== '\n') { + if (/(?:\s)/.test(lastChar)) { + lastLineWidth = lastBreakWidth; + } + + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + } + + var lineAlignOffsets = []; + + for (var _i = 0; _i <= line; _i++) { + var alignOffset = 0; + + if (this._font.align === 'right') { + alignOffset = maxLineWidth - lineWidths[_i]; + } else if (this._font.align === 'center') { + alignOffset = (maxLineWidth - lineWidths[_i]) / 2; + } + + lineAlignOffsets.push(alignOffset); + } + + var lenChars = chars.length; + var tint = this.tint; + + for (var _i2 = 0; _i2 < lenChars; _i2++) { + var c = this._glyphs[_i2]; // get the next glyph sprite + + if (c) { + c.texture = chars[_i2].texture; + } else { + c = new core.Sprite(chars[_i2].texture); + this._glyphs.push(c); + } + + c.position.x = (chars[_i2].position.x + lineAlignOffsets[chars[_i2].line]) * scale; + c.position.y = chars[_i2].position.y * scale; + c.scale.x = c.scale.y = scale; + c.tint = tint; + + if (!c.parent) { + this.addChild(c); + } + } + + // remove unnecessary children. + for (var _i3 = lenChars; _i3 < this._glyphs.length; ++_i3) { + this.removeChild(this._glyphs[_i3]); + } + + this._textWidth = maxLineWidth * scale; + this._textHeight = (pos.y + data.lineHeight) * scale; + + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + for (var _i4 = 0; _i4 < lenChars; _i4++) { + this._glyphs[_i4].x -= this._textWidth * this.anchor.x; + this._glyphs[_i4].y -= this._textHeight * this.anchor.y; + } + } + this._maxLineHeight = maxLineHeight * scale; + }; + + /** + * Updates the transform of this object + * + * @private + */ + + + BitmapText.prototype.updateTransform = function updateTransform() { + this.validate(); + this.containerUpdateTransform(); + }; + + /** + * Validates text before calling parent's getLocalBounds + * + * @return {PIXI.Rectangle} The rectangular bounding area + */ + + + BitmapText.prototype.getLocalBounds = function getLocalBounds() { + this.validate(); + + return _core$Container.prototype.getLocalBounds.call(this); + }; + + /** + * Updates text when needed + * + * @private + */ + + + BitmapText.prototype.validate = function validate() { + if (this.dirty) { + this.updateText(); + this.dirty = false; + } + }; + + /** + * The tint of the BitmapText object + * + * @member {number} + */ + + + /** + * Register a bitmap font with data and a texture. + * + * @static + * @param {XMLDocument} xml - The XML document data. + * @param {Object.|PIXI.Texture|PIXI.Texture[]} textures - List of textures for each page. + * If providing an object, the key is the `` element's `file` attribute in the FNT file. + * @return {Object} Result font object with font, size, lineHeight and char fields. + */ + BitmapText.registerFont = function registerFont(xml, textures) { + var data = {}; + var info = xml.getElementsByTagName('info')[0]; + var common = xml.getElementsByTagName('common')[0]; + var pages = xml.getElementsByTagName('page'); + var res = (0, _utils.getResolutionOfUrl)(pages[0].getAttribute('file'), _settings2.default.RESOLUTION); + var pagesTextures = {}; + + data.font = info.getAttribute('face'); + data.size = parseInt(info.getAttribute('size'), 10); + data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) / res; + data.chars = {}; + + // Single texture, convert to list + if (textures instanceof core.Texture) { + textures = [textures]; + } + + // Convert the input Texture, Textures or object + // into a page Texture lookup by "id" + for (var i = 0; i < pages.length; i++) { + var id = pages[i].getAttribute('id'); + var file = pages[i].getAttribute('file'); + + pagesTextures[id] = textures instanceof Array ? textures[i] : textures[file]; + } + + // parse letters + var letters = xml.getElementsByTagName('char'); + + for (var _i5 = 0; _i5 < letters.length; _i5++) { + var letter = letters[_i5]; + var charCode = parseInt(letter.getAttribute('id'), 10); + var page = letter.getAttribute('page') || 0; + var textureRect = new core.Rectangle(parseInt(letter.getAttribute('x'), 10) / res + pagesTextures[page].frame.x / res, parseInt(letter.getAttribute('y'), 10) / res + pagesTextures[page].frame.y / res, parseInt(letter.getAttribute('width'), 10) / res, parseInt(letter.getAttribute('height'), 10) / res); + + data.chars[charCode] = { + xOffset: parseInt(letter.getAttribute('xoffset'), 10) / res, + yOffset: parseInt(letter.getAttribute('yoffset'), 10) / res, + xAdvance: parseInt(letter.getAttribute('xadvance'), 10) / res, + kerning: {}, + texture: new core.Texture(pagesTextures[page].baseTexture, textureRect), + page: page + }; + } + + // parse kernings + var kernings = xml.getElementsByTagName('kerning'); + + for (var _i6 = 0; _i6 < kernings.length; _i6++) { + var kerning = kernings[_i6]; + var first = parseInt(kerning.getAttribute('first'), 10) / res; + var second = parseInt(kerning.getAttribute('second'), 10) / res; + var amount = parseInt(kerning.getAttribute('amount'), 10) / res; + + if (data.chars[second]) { + data.chars[second].kerning[first] = amount; + } + } + + // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3 + // but it's very likely to change + BitmapText.fonts[data.font] = data; + + return data; + }; + + _createClass(BitmapText, [{ + key: 'tint', + get: function get() { + return this._font.tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.tint = typeof value === 'number' && value >= 0 ? value : 0xFFFFFF; + + this.dirty = true; + } + + /** + * The alignment of the BitmapText object + * + * @member {string} + * @default 'left' + */ + + }, { + key: 'align', + get: function get() { + return this._font.align; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._font.align = value || 'left'; + + this.dirty = true; + } + + /** + * The anchor sets the origin point of the text. + * The default is 0,0 this means the text's origin is the top left + * Setting the anchor to 0.5,0.5 means the text's origin is centered + * Setting the anchor to 1,1 would mean the text's origin point will be the bottom right corner + * + * @member {PIXI.Point | number} + */ + + }, { + key: 'anchor', + get: function get() { + return this._anchor; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (typeof value === 'number') { + this._anchor.set(value); + } else { + this._anchor.copy(value); + } + } + + /** + * The font descriptor of the BitmapText object + * + * @member {string|object} + */ + + }, { + key: 'font', + get: function get() { + return this._font; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (!value) { + return; + } + + if (typeof value === 'string') { + value = value.split(' '); + + this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' '); + this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size; + } else { + this._font.name = value.name; + this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10); + } + + this.dirty = true; + } + + /** + * The text of the BitmapText object + * + * @member {string} + */ + + }, { + key: 'text', + get: function get() { + return this._text; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + value = value.toString() || ' '; + if (this._text === value) { + return; + } + this._text = value; + this.dirty = true; + } + + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting value to 0 + * + * @member {number} + */ + + }, { + key: 'maxWidth', + get: function get() { + return this._maxWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._maxWidth === value) { + return; + } + this._maxWidth = value; + this.dirty = true; + } + + /** + * The max line height. This is useful when trying to use the total height of the Text, + * ie: when trying to vertically align. + * + * @member {number} + * @readonly + */ + + }, { + key: 'maxLineHeight', + get: function get() { + this.validate(); + + return this._maxLineHeight; + } + + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textWidth', + get: function get() { + this.validate(); + + return this._textWidth; + } + + /** + * Additional space between characters. + * + * @member {number} + */ + + }, { + key: 'letterSpacing', + get: function get() { + return this._letterSpacing; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._letterSpacing !== value) { + this._letterSpacing = value; + this.dirty = true; + } + } + + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object + * + * @member {number} + * @readonly + */ + + }, { + key: 'textHeight', + get: function get() { + this.validate(); + + return this._textHeight; + } + }]); + + return BitmapText; +}(core.Container); + +exports.default = BitmapText; + + +BitmapText.fonts = {}; + +},{"../core":65,"../core/math/ObservablePoint":68,"../core/settings":101,"../core/utils":125}],137:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CanvasTinter = require('../core/sprites/canvas/CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); + +/** + * A tiling sprite is a fast way of rendering a tiling image + * + * @class + * @extends PIXI.Sprite + * @memberof PIXI.extras + */ + +var TilingSprite = function (_core$Sprite) { + _inherits(TilingSprite, _core$Sprite); + + /** + * @param {PIXI.Texture} texture - the texture of the tiling sprite + * @param {number} [width=100] - the width of the tiling sprite + * @param {number} [height=100] - the height of the tiling sprite + */ + function TilingSprite(texture) { + var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; + var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 100; + + _classCallCheck(this, TilingSprite); + + /** + * Tile transform + * + * @member {PIXI.TransformStatic} + */ + var _this = _possibleConstructorReturn(this, _core$Sprite.call(this, texture)); + + _this.tileTransform = new core.TransformStatic(); + + // /// private + + /** + * The with of the tiling sprite + * + * @member {number} + * @private + */ + _this._width = width; + + /** + * The height of the tiling sprite + * + * @member {number} + * @private + */ + _this._height = height; + + /** + * Canvas pattern + * + * @type {CanvasPattern} + * @private + */ + _this._canvasPattern = null; + + /** + * transform that is applied to UV to get the texture coords + * + * @member {PIXI.TextureMatrix} + */ + _this.uvTransform = texture.transform || new core.TextureMatrix(texture); + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' method. + * + * @member {string} + * @default 'tilingSprite' + */ + _this.pluginName = 'tilingSprite'; + + /** + * Whether or not anchor affects uvs + * + * @member {boolean} + * @default false + */ + _this.uvRespectAnchor = false; + return _this; + } + /** + * Changes frame clamping in corresponding textureTransform, shortcut + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * + * @default 0.5 + * @member {number} + */ + + + /** + * @private + */ + TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate() { + if (this.uvTransform) { + this.uvTransform.texture = this._texture; + } + this.cachedTint = 0xFFFFFF; + }; + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The renderer + */ + + + TilingSprite.prototype._renderWebGL = function _renderWebGL(renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + + if (!texture || !texture.valid) { + return; + } + + this.tileTransform.updateLocalTransform(); + this.uvTransform.update(); + + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - a reference to the canvas renderer + */ + + + TilingSprite.prototype._renderCanvas = function _renderCanvas(renderer) { + var texture = this._texture; + + if (!texture.baseTexture.hasLoaded) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var resolution = renderer.resolution; + var isTextureRotated = texture.rotate === 2; + var baseTexture = texture.baseTexture; + var baseTextureResolution = baseTexture.resolution; + var modX = this.tilePosition.x / this.tileScale.x % texture.orig.width * baseTextureResolution; + var modY = this.tilePosition.y / this.tileScale.y % texture.orig.height * baseTextureResolution; + + // create a nice shiny pattern! + if (this._textureID !== this._texture._updateID || this.cachedTint !== this.tint) { + this._textureID = this._texture._updateID; + // cut an object from a spritesheet.. + var tempCanvas = new core.CanvasRenderTarget(texture.orig.width, texture.orig.height, baseTextureResolution); + + // Tint the tiling sprite + if (this.tint !== 0xFFFFFF) { + this.tintedTexture = _CanvasTinter2.default.getTintedTexture(this, this.tint); + tempCanvas.context.drawImage(this.tintedTexture, 0, 0); + } else { + var sx = texture._frame.x * baseTextureResolution; + var sy = texture._frame.y * baseTextureResolution; + var sWidth = texture._frame.width * baseTextureResolution; + var sHeight = texture._frame.height * baseTextureResolution; + var dWidth = (texture.trim ? texture.trim.width : texture.orig.width) * baseTextureResolution; + var dHeight = (texture.trim ? texture.trim.height : texture.orig.height) * baseTextureResolution; + var dx = (texture.trim ? texture.trim.x : 0) * baseTextureResolution; + var dy = (texture.trim ? texture.trim.y : 0) * baseTextureResolution; + + if (isTextureRotated) { + // Apply rotation and transform + tempCanvas.context.rotate(-Math.PI / 2); + tempCanvas.context.translate(-dHeight, 0); + tempCanvas.context.drawImage(baseTexture.source, sx, sy, sWidth, sHeight, -dy, dx, dHeight, dWidth); + } else { + tempCanvas.context.drawImage(baseTexture.source, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight); + } + } + + this.cachedTint = this.tint; + this._canvasPattern = tempCanvas.context.createPattern(tempCanvas.canvas, 'repeat'); + } + + // set context state.. + context.globalAlpha = this.worldAlpha; + context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); + + renderer.setBlendMode(this.blendMode); + + // fill the pattern! + context.fillStyle = this._canvasPattern; + + // TODO - this should be rolled into the setTransform above.. + context.scale(this.tileScale.x / baseTextureResolution, this.tileScale.y / baseTextureResolution); + + var anchorX = this.anchor.x * -this._width * baseTextureResolution; + var anchorY = this.anchor.y * -this._height * baseTextureResolution; + + if (this.uvRespectAnchor) { + context.translate(modX, modY); + + context.fillRect(-modX + anchorX, -modY + anchorY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } else { + context.translate(modX + anchorX, modY + anchorY); + + context.fillRect(-modX, -modY, this._width / this.tileScale.x * baseTextureResolution, this._height / this.tileScale.y * baseTextureResolution); + } + }; + + /** + * Updates the bounds of the tiling sprite. + * + * @private + */ + + + TilingSprite.prototype._calculateBounds = function _calculateBounds() { + var minX = this._width * -this._anchor._x; + var minY = this._height * -this._anchor._y; + var maxX = this._width * (1 - this._anchor._x); + var maxY = this._height * (1 - this._anchor._y); + + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + + /** + * Gets the local bounds of the sprite object. + * + * @param {PIXI.Rectangle} rect - The output rectangle. + * @return {PIXI.Rectangle} The bounds. + */ + + + TilingSprite.prototype.getLocalBounds = function getLocalBounds(rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._width * -this._anchor._x; + this._bounds.minY = this._height * -this._anchor._y; + this._bounds.maxX = this._width * (1 - this._anchor._x); + this._bounds.maxY = this._height * (1 - this._anchor._y); + + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new core.Rectangle(); + } + + rect = this._localBoundsRect; + } + + return this._bounds.getRectangle(rect); + } + + return _core$Sprite.prototype.getLocalBounds.call(this, rect); + }; + + /** + * Checks if a point is inside this tiling sprite. + * + * @param {PIXI.Point} point - the point to check + * @return {boolean} Whether or not the sprite contains the point. + */ + + + TilingSprite.prototype.containsPoint = function containsPoint(point) { + this.worldTransform.applyInverse(point, tempPoint); + + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor._x; + + if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { + var y1 = -height * this.anchor._y; + + if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { + return true; + } + } + + return false; + }; + + /** + * Destroys this sprite and optionally its texture and children + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + + + TilingSprite.prototype.destroy = function destroy(options) { + _core$Sprite.prototype.destroy.call(this, options); + + this.tileTransform = null; + this.uvTransform = null; + }; + + /** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * + * @static + * @param {number|string|PIXI.BaseTexture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.Texture} The newly created texture + */ + + + TilingSprite.from = function from(source, width, height) { + return new TilingSprite(core.Texture.from(source), width, height); + }; + + /** + * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId + * The frame ids are created when a Texture packer file has been loaded + * + * @static + * @param {string} frameId - The frame Id of the texture in the cache + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId + */ + + + TilingSprite.fromFrame = function fromFrame(frameId, width, height) { + var texture = core.utils.TextureCache[frameId]; + + if (!texture) { + throw new Error('The frameId "' + frameId + '" does not exist in the texture cache ' + this); + } + + return new TilingSprite(texture, width, height); + }; + + /** + * Helper function that creates a sprite that will contain a texture based on an image url + * If the image is not in the texture cache it will be loaded + * + * @static + * @param {string} imageId - The image url of the texture + * @param {number} width - the width of the tiling sprite + * @param {number} height - the height of the tiling sprite + * @param {boolean} [crossorigin] - if you want to specify the cross-origin parameter + * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - if you want to specify the scale mode, + * see {@link PIXI.SCALE_MODES} for possible values + * @return {PIXI.extras.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id + */ + + + TilingSprite.fromImage = function fromImage(imageId, width, height, crossorigin, scaleMode) { + return new TilingSprite(core.Texture.fromImage(imageId, crossorigin, scaleMode), width, height); + }; + + /** + * The width of the sprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + + _createClass(TilingSprite, [{ + key: 'clampMargin', + get: function get() { + return this.uvTransform.clampMargin; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uvTransform.clampMargin = value; + this.uvTransform.update(true); + } + + /** + * The scaling of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tileScale', + get: function get() { + return this.tileTransform.scale; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.scale.copy(value); + } + + /** + * The offset of the image that is being tiled + * + * @member {PIXI.ObservablePoint} + */ + + }, { + key: 'tilePosition', + get: function get() { + return this.tileTransform.position; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tileTransform.position.copy(value); + } + }, { + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + } + + /** + * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + } + }]); + + return TilingSprite; +}(core.Sprite); + +exports.default = TilingSprite; + +},{"../core":65,"../core/sprites/canvas/CanvasTinter":104}],138:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +var _BaseTexture = require('../core/textures/BaseTexture'); + +var _BaseTexture2 = _interopRequireDefault(_BaseTexture); + +var _utils = require('../core/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var DisplayObject = core.DisplayObject; +var _tempMatrix = new core.Matrix(); + +DisplayObject.prototype._cacheAsBitmap = false; +DisplayObject.prototype._cacheData = false; + +// figured theres no point adding ALL the extra variables to prototype. +// this model can hold the information needed. This can also be generated on demand as +// most objects are not cached as bitmaps. +/** + * @class + * @ignore + */ + +var CacheData = +/** + * + */ +function CacheData() { + _classCallCheck(this, CacheData); + + this.textureCacheId = null; + + this.originalRenderWebGL = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + + this.originalUpdateTransform = null; + this.originalHitTest = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.sprite = null; +}; + +Object.defineProperties(DisplayObject.prototype, { + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to 'false' + * + * IMPORTANT GOTCHA - make sure that all your textures are preloaded BEFORE setting this property to true + * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. + * + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function get() { + return this._cacheAsBitmap; + }, + set: function set(value) { + if (this._cacheAsBitmap === value) { + return; + } + + this._cacheAsBitmap = value; + + var data = void 0; + + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + + data = this._cacheData; + + data.originalRenderWebGL = this.renderWebGL; + data.originalRenderCanvas = this.renderCanvas; + + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this.calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + + data.originalDestroy = this.destroy; + + data.originalContainsPoint = this.containsPoint; + + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + + this.renderWebGL = this._renderCachedWebGL; + this.renderCanvas = this._renderCachedCanvas; + + this.destroy = this._cacheAsBitmapDestroy; + } else { + data = this._cacheData; + + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + + this.renderWebGL = data.originalRenderWebGL; + this.renderCanvas = data.originalRenderCanvas; + this.calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + + this.destroy = data.originalDestroy; + + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + } + } +}); + +/** + * Renders a cached version of the sprite with WebGL + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedWebGL = function _renderCachedWebGL(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObject(renderer); + + this._cacheData.sprite.transform._worldID = this.transform._worldID; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderWebGL(renderer); +}; + +/** + * Prepares the WebGL renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + + this.alpha = 1; + + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.currentRenderer.flush(); + // this.filters= []; + + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds().clone(); + + // add some padding! + if (this._filters && this._filters.length) { + var padding = this._filters[0].padding; + + bounds.pad(padding); + } + + bounds.ceil(core.settings.RESOLUTION); + + // for now we cache the current renderTarget that the webGL renderer is currently using. + // this could be more elegent.. + var cachedRenderTarget = renderer._activeRenderTarget; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + var stack = renderer.filterManager.filterStack; + + // this renderTexture will be used to store the cached DisplayObject + + var renderTexture = core.RenderTexture.create(bounds.width, bounds.height); + + var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); + + this._cacheData.textureCacheId = textureCacheId; + + _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); + _Texture2.default.addToCache(renderTexture, textureCacheId); + + // need to set // + var m = _tempMatrix; + + m.tx = -bounds.x; + m.ty = -bounds.y; + + // reset + this.transform.worldTransform.identity(); + + // set all properties to there original so we can render to a texture + this.renderWebGL = this._cacheData.originalRenderWebGL; + + renderer.render(this, renderTexture, true, m, true); + // now restore the state be setting the new properties + + renderer.bindRenderTarget(cachedRenderTarget); + + renderer.filterManager.filterStack = stack; + + this.renderWebGL = this._renderCachedWebGL; + // the rest is the same as for Canvas + this.updateTransform = this.displayObjectUpdateTransform; + this.calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + + this._cacheData.sprite = cachedSprite; + + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this.updateTransform(); + } + + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Renders a cached version of the sprite with canvas + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + + this._initCachedDisplayObjectCanvas(renderer); + + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderCanvas(renderer); +}; + +// TODO this can be the same as the webGL verison.. will need to do a little tweaking first though.. +/** + * Prepares the Canvas renderer to cache the sprite + * + * @private + * @memberof PIXI.DisplayObject# + * @param {PIXI.WebGLRenderer} renderer - the WebGL renderer + */ +DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(); + + var cacheAlpha = this.alpha; + + this.alpha = 1; + + var cachedRenderTarget = renderer.context; + + bounds.ceil(core.settings.RESOLUTION); + + var renderTexture = core.RenderTexture.create(bounds.width, bounds.height); + + var textureCacheId = 'cacheAsBitmap_' + (0, _utils.uid)(); + + this._cacheData.textureCacheId = textureCacheId; + + _BaseTexture2.default.addToCache(renderTexture.baseTexture, textureCacheId); + _Texture2.default.addToCache(renderTexture, textureCacheId); + + // need to set // + var m = _tempMatrix; + + this.transform.localTransform.copy(m); + m.invert(); + + m.tx -= bounds.x; + m.ty -= bounds.y; + + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + + // renderTexture.render(this, m, true); + renderer.render(this, renderTexture, true, m, false); + + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + + this.renderCanvas = this._renderCachedCanvas; + // the rest is the same as for WebGL + this.updateTransform = this.displayObjectUpdateTransform; + this.calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + + this._mask = null; + this.filterArea = null; + + // create our cached sprite + var cachedSprite = new core.Sprite(renderTexture); + + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + + this._cacheData.sprite = cachedSprite; + + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } else { + this.updateTransform(); + } + + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); +}; + +/** + * Calculates the bounds of the cached sprite + * + * @private + */ +DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._bounds.clear(); + this._cacheData.sprite.transform._worldID = this.transform._worldID; + this._cacheData.sprite._calculateBounds(); + this._lastBoundsID = this._boundsID; +}; + +/** + * Gets the bounds of the cached sprite. + * + * @private + * @return {Rectangle} The local bounds. + */ +DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(); +}; + +/** + * Destroys the cached sprite. + * + * @private + */ +DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; + + _BaseTexture2.default.removeFromCache(this._cacheData.textureCacheId); + _Texture2.default.removeFromCache(this._cacheData.textureCacheId); + + this._cacheData.textureCacheId = null; +}; + +/** + * Destroys the cached object. + * + * @private + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * Used when destroying containers, see the Container.destroy method. + */ +DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { + this.cacheAsBitmap = false; + this.destroy(options); +}; + +},{"../core":65,"../core/textures/BaseTexture":112,"../core/textures/Texture":115,"../core/utils":125}],139:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * The instance name of the object. + * + * @memberof PIXI.DisplayObject# + * @member {string} name + */ +core.DisplayObject.prototype.name = null; + +/** + * Returns the display object in the container + * + * @method getChildByName + * @memberof PIXI.Container# + * @param {string} name - instance name + * @return {PIXI.DisplayObject} The child with the specified name. + */ +core.Container.prototype.getChildByName = function getChildByName(name) { + for (var i = 0; i < this.children.length; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + + return null; +}; + +},{"../core":65}],140:[function(require,module,exports){ +'use strict'; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. + * + * @method getGlobalPosition + * @memberof PIXI.DisplayObject# + * @param {Point} point - the point to write the global value to. If null a new point will be returned + * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost + * @return {Point} The updated point + */ +core.DisplayObject.prototype.getGlobalPosition = function getGlobalPosition() { + var point = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new core.Point(); + var skipUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (this.parent) { + this.parent.toGlobal(this.position, point, skipUpdate); + } else { + point.x = this.position.x; + point.y = this.position.y; + } + + return point; +}; + +},{"../core":65}],141:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.BitmapText = exports.TilingSpriteRenderer = exports.TilingSprite = exports.AnimatedSprite = undefined; + +var _AnimatedSprite = require('./AnimatedSprite'); + +Object.defineProperty(exports, 'AnimatedSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AnimatedSprite).default; + } +}); + +var _TilingSprite = require('./TilingSprite'); + +Object.defineProperty(exports, 'TilingSprite', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSprite).default; + } +}); + +var _TilingSpriteRenderer = require('./webgl/TilingSpriteRenderer'); + +Object.defineProperty(exports, 'TilingSpriteRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TilingSpriteRenderer).default; + } +}); + +var _BitmapText = require('./BitmapText'); + +Object.defineProperty(exports, 'BitmapText', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BitmapText).default; + } +}); + +require('./cacheAsBitmap'); + +require('./getChildByName'); + +require('./getGlobalPosition'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// imported for side effect of extending the prototype only, contains no exports + +},{"./AnimatedSprite":135,"./BitmapText":136,"./TilingSprite":137,"./cacheAsBitmap":138,"./getChildByName":139,"./getGlobalPosition":140,"./webgl/TilingSpriteRenderer":142}],142:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _const = require('../../core/const'); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempMat = new core.Matrix(); + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI.extras + * @extends PIXI.ObjectRenderer + */ + +var TilingSpriteRenderer = function (_core$ObjectRenderer) { + _inherits(TilingSpriteRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function TilingSpriteRenderer(renderer) { + _classCallCheck(this, TilingSpriteRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + _this.simpleShader = null; + _this.quad = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + TilingSpriteRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n gl_FragColor = sample * uColor;\n}\n'); + this.simpleShader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = sample * uColor;\n}\n'); + + this.renderer.bindVao(null); + this.quad = new core.Quad(gl, this.renderer.state.attribState); + this.quad.initVao(this.shader); + }; + + /** + * + * @param {PIXI.extras.TilingSprite} ts tilingSprite to be rendered + */ + + + TilingSpriteRenderer.prototype.render = function render(ts) { + var renderer = this.renderer; + var quad = this.quad; + + renderer.bindVao(quad.vao); + + var vertices = quad.vertices; + + vertices[0] = vertices[6] = ts._width * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + + vertices[2] = vertices[4] = ts._width * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + + if (ts.uvRespectAnchor) { + vertices = quad.uvs; + + vertices[0] = vertices[6] = -ts.anchor.x; + vertices[1] = vertices[3] = -ts.anchor.y; + + vertices[2] = vertices[4] = 1.0 - ts.anchor.x; + vertices[5] = vertices[7] = 1.0 - ts.anchor.y; + } + + quad.upload(); + + var tex = ts._texture; + var baseTex = tex.baseTexture; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvTransform; + var isSimple = baseTex.isPowerOfTwo && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === _const.WRAP_MODES.CLAMP) { + baseTex.wrapMode = _const.WRAP_MODES.REPEAT; + } + } else { + isSimple = baseTex.wrapMode !== _const.WRAP_MODES.CLAMP; + } + } + + var shader = isSimple ? this.simpleShader : this.shader; + + renderer.bindShader(shader); + + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + + tempMat.invert(); + if (isSimple) { + tempMat.prepend(uv.mapCoord); + } else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + + shader.uniforms.uTransform = tempMat.toArray(true); + shader.uniforms.uColor = core.utils.premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, baseTex.premultipliedAlpha); + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + + shader.uniforms.uSampler = renderer.bindTexture(tex); + + renderer.setBlendMode(core.utils.correctBlendMode(ts.blendMode, baseTex.premultipliedAlpha)); + + quad.vao.draw(this.renderer.gl.TRIANGLES, 6, 0); + }; + + return TilingSpriteRenderer; +}(core.ObjectRenderer); + +exports.default = TilingSpriteRenderer; + + +core.WebGLRenderer.registerPlugin('tilingSprite', TilingSpriteRenderer); + +},{"../../core":65,"../../core/const":46,"path":8}],143:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * Simplest filter - applies alpha + * + * Use this instead of Container's alpha property to avoid visual layering of individual elements. + * AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains. + * If elements are not opaque, they will blend with each other anyway. + * + * Very handy if you want to use common features of all filters: + * + * 1. Assign a blendMode to this filter, blend all elements inside display object with background. + * + * 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var AlphaFilter = function (_core$Filter) { + _inherits(AlphaFilter, _core$Filter); + + /** + * @param {number} [alpha=1] Amount of alpha from 0 to 1, where 0 is transparent + */ + function AlphaFilter() { + var alpha = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1.0; + + _classCallCheck(this, AlphaFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n')); + + _this.alpha = alpha; + _this.glShaderKey = 'alpha'; + return _this; + } + + /** + * Coefficient for alpha multiplication + * + * @member {number} + * @default 1 + */ + + + _createClass(AlphaFilter, [{ + key: 'alpha', + get: function get() { + return this.uniforms.uAlpha; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uAlpha = value; + } + }]); + + return AlphaFilter; +}(core.Filter); + +exports.default = AlphaFilter; + +},{"../../core":65,"path":8}],144:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BlurXFilter = require('./BlurXFilter'); + +var _BlurXFilter2 = _interopRequireDefault(_BlurXFilter); + +var _BlurYFilter = require('./BlurYFilter'); + +var _BlurYFilter2 = _interopRequireDefault(_BlurYFilter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurFilter applies a Gaussian blur to an object. + * The strength of the blur can be set for x- and y-axis separately. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurFilter = function (_core$Filter) { + _inherits(BlurFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this)); + + _this.blurXFilter = new _BlurXFilter2.default(strength, quality, resolution, kernelSize); + _this.blurYFilter = new _BlurYFilter2.default(strength, quality, resolution, kernelSize); + + _this.padding = 0; + _this.resolution = resolution || core.settings.RESOLUTION; + _this.quality = quality || 4; + _this.blur = strength || 8; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + BlurFilter.prototype.apply = function apply(filterManager, input, output) { + var renderTarget = filterManager.getRenderTarget(true); + + this.blurXFilter.apply(filterManager, input, renderTarget, true); + this.blurYFilter.apply(filterManager, renderTarget, output, false); + + filterManager.returnRenderTarget(renderTarget); + }; + + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurFilter, [{ + key: 'blur', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the number of passes for blur. More passes means higher quaility bluring. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'quality', + get: function get() { + return this.blurXFilter.quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.quality = this.blurYFilter.quality = value; + } + + /** + * Sets the strength of the blurX property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurX', + get: function get() { + return this.blurXFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurXFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the strength of the blurY property + * + * @member {number} + * @default 2 + */ + + }, { + key: 'blurY', + get: function get() { + return this.blurYFilter.blur; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter.blur = value; + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + + /** + * Sets the blendmode of the filter + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + */ + + }, { + key: 'blendMode', + get: function get() { + return this.blurYFilter._blendMode; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.blurYFilter._blendMode = value; + } + }]); + + return BlurFilter; +}(core.Filter); + +exports.default = BlurFilter; + +},{"../../core":65,"./BlurXFilter":145,"./BlurYFilter":146}],145:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurXFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurXFilter = function (_core$Filter) { + _inherits(BlurXFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurXFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurXFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurXFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, true); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.width * (output.size.width / input.size.width); + + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; // / this.passes//Math.pow(1, this.passes); + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 16 + */ + + + _createClass(BlurXFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurXFilter; +}(core.Filter); + +exports.default = BlurXFilter; + +},{"../../core":65,"./generateBlurFragSource":147,"./generateBlurVertSource":148,"./getMaxBlurKernelSize":149}],146:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _generateBlurVertSource = require('./generateBlurVertSource'); + +var _generateBlurVertSource2 = _interopRequireDefault(_generateBlurVertSource); + +var _generateBlurFragSource = require('./generateBlurFragSource'); + +var _generateBlurFragSource2 = _interopRequireDefault(_generateBlurFragSource); + +var _getMaxBlurKernelSize = require('./getMaxBlurKernelSize'); + +var _getMaxBlurKernelSize2 = _interopRequireDefault(_getMaxBlurKernelSize); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The BlurYFilter applies a horizontal Gaussian blur to an object. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var BlurYFilter = function (_core$Filter) { + _inherits(BlurYFilter, _core$Filter); + + /** + * @param {number} strength - The strength of the blur filter. + * @param {number} quality - The quality of the blur filter. + * @param {number} resolution - The resolution of the blur filter. + * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurYFilter(strength, quality, resolution, kernelSize) { + _classCallCheck(this, BlurYFilter); + + kernelSize = kernelSize || 5; + var vertSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + var fragSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc)); + + _this.resolution = resolution || core.settings.RESOLUTION; + + _this._quality = 0; + + _this.quality = quality || 4; + _this.strength = strength || 8; + + _this.firstRun = true; + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + * @param {boolean} clear - Should the output be cleared before rendering? + */ + + + BlurYFilter.prototype.apply = function apply(filterManager, input, output, clear) { + if (this.firstRun) { + var gl = filterManager.renderer.gl; + var kernelSize = (0, _getMaxBlurKernelSize2.default)(gl); + + this.vertexSrc = (0, _generateBlurVertSource2.default)(kernelSize, false); + this.fragmentSrc = (0, _generateBlurFragSource2.default)(kernelSize); + + this.firstRun = false; + } + + this.uniforms.strength = 1 / output.size.height * (output.size.height / input.size.height); + + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clear); + } else { + var renderTarget = filterManager.getRenderTarget(true); + var flip = input; + var flop = renderTarget; + + for (var i = 0; i < this.passes - 1; i++) { + filterManager.applyFilter(this, flip, flop, true); + + var temp = flop; + + flop = flip; + flip = temp; + } + + filterManager.applyFilter(this, flip, output, clear); + + filterManager.returnRenderTarget(renderTarget); + } + }; + + /** + * Sets the strength of both the blur. + * + * @member {number} + * @default 2 + */ + + + _createClass(BlurYFilter, [{ + key: 'blur', + get: function get() { + return this.strength; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.padding = Math.abs(value) * 2; + this.strength = value; + } + + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quaility bluring but the lower the performance. + * + * @member {number} + * @default 4 + */ + + }, { + key: 'quality', + get: function get() { + return this._quality; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._quality = value; + this.passes = value; + } + }]); + + return BlurYFilter; +}(core.Filter); + +exports.default = BlurYFilter; + +},{"../../core":65,"./generateBlurFragSource":147,"./generateBlurVertSource":148,"./getMaxBlurKernelSize":149}],147:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateFragBlurSource; +var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448] +}; + +var fragTemplate = ['varying vec2 vBlurTexCoords[%size%];', 'uniform sampler2D uSampler;', 'void main(void)', '{', ' gl_FragColor = vec4(0.0);', ' %blur%', '}'].join('\n'); + +function generateFragBlurSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + + var fragSource = fragTemplate; + + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value = void 0; + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + value = i; + + if (i >= halfLength) { + value = kernelSize - i - 1; + } + + blur = blur.replace('%value%', kernel[value]); + + blurLoop += blur; + blurLoop += '\n'; + } + + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize); + + return fragSource; +} + +},{}],148:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = generateVertBlurSource; +var vertTemplate = ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'uniform float strength;', 'uniform mat3 projectionMatrix;', 'varying vec2 vBlurTexCoords[%size%];', 'void main(void)', '{', 'gl_Position = vec4((projectionMatrix * vec3((aVertexPosition), 1.0)).xy, 0.0, 1.0);', '%blur%', '}'].join('\n'); + +function generateVertBlurSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + + var vertSource = vertTemplate; + + var blurLoop = ''; + var template = void 0; + // let value; + + if (x) { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } else { + template = 'vBlurTexCoords[%index%] = aTextureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i); + + // value = i; + + // if(i >= halfLength) + // { + // value = kernelSize - i - 1; + // } + + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + '.0'); + + blurLoop += blur; + blurLoop += '\n'; + } + + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize); + + return vertSource; +} + +},{}],149:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = getMaxKernelSize; +function getMaxKernelSize(gl) { + var maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + var kernelSize = 15; + + while (kernelSize > maxVaryings) { + kernelSize -= 2; + } + + return kernelSize; +} + +},{}],150:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.filters.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var ColorMatrixFilter = function (_core$Filter) { + _inherits(ColorMatrixFilter, _core$Filter); + + /** + * + */ + function ColorMatrixFilter() { + _classCallCheck(this, ColorMatrixFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n')); + + _this.uniforms.m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + _this.alpha = 1; + return _this; + } + + /** + * Transforms current matrix and set the new one + * + * @param {number[]} matrix - 5x4 matrix + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix(matrix) { + var multiply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + var newMatrix = matrix; + + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + + // set the new matrix + this.uniforms.m = newMatrix; + }; + + /** + * Multiplies two mat5's + * + * @private + * @param {number[]} out - 5x4 matrix the receiving matrix + * @param {number[]} a - 5x4 matrix the first operand + * @param {number[]} b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix + */ + + + ColorMatrixFilter.prototype._multiply = function _multiply(out, a, b) { + // Red Channel + out[0] = a[0] * b[0] + a[1] * b[5] + a[2] * b[10] + a[3] * b[15]; + out[1] = a[0] * b[1] + a[1] * b[6] + a[2] * b[11] + a[3] * b[16]; + out[2] = a[0] * b[2] + a[1] * b[7] + a[2] * b[12] + a[3] * b[17]; + out[3] = a[0] * b[3] + a[1] * b[8] + a[2] * b[13] + a[3] * b[18]; + out[4] = a[0] * b[4] + a[1] * b[9] + a[2] * b[14] + a[3] * b[19] + a[4]; + + // Green Channel + out[5] = a[5] * b[0] + a[6] * b[5] + a[7] * b[10] + a[8] * b[15]; + out[6] = a[5] * b[1] + a[6] * b[6] + a[7] * b[11] + a[8] * b[16]; + out[7] = a[5] * b[2] + a[6] * b[7] + a[7] * b[12] + a[8] * b[17]; + out[8] = a[5] * b[3] + a[6] * b[8] + a[7] * b[13] + a[8] * b[18]; + out[9] = a[5] * b[4] + a[6] * b[9] + a[7] * b[14] + a[8] * b[19] + a[9]; + + // Blue Channel + out[10] = a[10] * b[0] + a[11] * b[5] + a[12] * b[10] + a[13] * b[15]; + out[11] = a[10] * b[1] + a[11] * b[6] + a[12] * b[11] + a[13] * b[16]; + out[12] = a[10] * b[2] + a[11] * b[7] + a[12] * b[12] + a[13] * b[17]; + out[13] = a[10] * b[3] + a[11] * b[8] + a[12] * b[13] + a[13] * b[18]; + out[14] = a[10] * b[4] + a[11] * b[9] + a[12] * b[14] + a[13] * b[19] + a[14]; + + // Alpha Channel + out[15] = a[15] * b[0] + a[16] * b[5] + a[17] * b[10] + a[18] * b[15]; + out[16] = a[15] * b[1] + a[16] * b[6] + a[17] * b[11] + a[18] * b[16]; + out[17] = a[15] * b[2] + a[16] * b[7] + a[17] * b[12] + a[18] * b[17]; + out[18] = a[15] * b[3] + a[16] * b[8] + a[17] * b[13] + a[18] * b[18]; + out[19] = a[15] * b[4] + a[16] * b[9] + a[17] * b[14] + a[18] * b[19] + a[19]; + + return out; + }; + + /** + * Create a Float32 Array and normalize the offset component to 0-1 + * + * @private + * @param {number[]} matrix - 5x4 matrix + * @return {number[]} 5x4 matrix with all values between 0-1 + */ + + + ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix(matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + + return m; + }; + + /** + * Adjusts brightness + * + * @param {number} b - value of the brigthness (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.brightness = function brightness(b, multiply) { + var matrix = [b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, b, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the matrices in grey scales + * + * @param {number} scale - value of the grey (0-1, where 0 is black) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.greyscale = function greyscale(scale, multiply) { + var matrix = [scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, scale, scale, scale, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the black and white matrice. + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite(multiply) { + var matrix = [0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0.3, 0.6, 0.1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the hue property of the color + * + * @param {number} rotation - in degrees + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.hue = function hue(rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + + var a00 = cosR + (1.0 - cosR) * w; + var a01 = w * (1.0 - cosR) - sqrW * sinR; + var a02 = w * (1.0 - cosR) + sqrW * sinR; + + var a10 = w * (1.0 - cosR) + sqrW * sinR; + var a11 = cosR + w * (1.0 - cosR); + var a12 = w * (1.0 - cosR) - sqrW * sinR; + + var a20 = w * (1.0 - cosR) - sqrW * sinR; + var a21 = w * (1.0 - cosR) + sqrW * sinR; + var a22 = cosR + w * (1.0 - cosR); + + var matrix = [a00, a01, a02, 0, 0, a10, a11, a12, 0, 0, a20, a21, a22, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * + * @param {number} amount - value of the contrast (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.contrast = function contrast(amount, multiply) { + var v = (amount || 0) + 1; + var o = -0.5 * (v - 1); + + var matrix = [v, 0, 0, 0, o, 0, v, 0, 0, o, 0, 0, v, 0, o, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * + * @param {number} amount - The saturation amount (0-1) + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.saturate = function saturate() { + var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var multiply = arguments[1]; + + var x = amount * 2 / 3 + 1; + var y = (x - 1) * -0.5; + + var matrix = [x, y, y, 0, 0, y, x, y, 0, 0, y, y, x, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Desaturate image (remove color) + * + * Call the saturate function + * + */ + + + ColorMatrixFilter.prototype.desaturate = function desaturate() // eslint-disable-line no-unused-vars + { + this.saturate(-1); + }; + + /** + * Negative image (inverse of classic rgb matrix) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.negative = function negative(multiply) { + var matrix = [-1, 0, 0, 1, 0, 0, -1, 0, 1, 0, 0, 0, -1, 1, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Sepia image + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.sepia = function sepia(multiply) { + var matrix = [0.393, 0.7689999, 0.18899999, 0, 0, 0.349, 0.6859999, 0.16799999, 0, 0, 0.272, 0.5339999, 0.13099999, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.technicolor = function technicolor(multiply) { + var matrix = [1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Polaroid filter + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.polaroid = function polaroid(multiply) { + var matrix = [1.438, -0.062, -0.062, 0, 0, -0.122, 1.378, -0.122, 0, 0, -0.016, -0.016, 1.483, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Filter who transforms : Red -> Blue and Blue -> Red + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.toBGR = function toBGR(multiply) { + var matrix = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.kodachrome = function kodachrome(multiply) { + var matrix = [1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Brown delicious browni filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.browni = function browni(multiply) { + var matrix = [0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Vintage filter (thanks Dominic Szablewski) + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.vintage = function vintage(multiply) { + var matrix = [0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * + * @param {number} desaturation - Tone values. + * @param {number} toned - Tone values. + * @param {string} lightColor - Tone values, example: `0xFFE580` + * @param {string} darkColor - Tone values, example: `0xFFE580` + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.colorTone = function colorTone(desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + + var lR = (lightColor >> 16 & 0xFF) / 255; + var lG = (lightColor >> 8 & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + + var dR = (darkColor >> 16 & 0xFF) / 255; + var dG = (darkColor >> 8 & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + + var matrix = [0.3, 0.59, 0.11, 0, 0, lR, lG, lB, desaturation, 0, dR, dG, dB, toned, 0, lR - dR, lG - dG, lB - dB, 0, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Night effect + * + * @param {number} intensity - The intensity of the night effect. + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.night = function night(intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [intensity * -2.0, -intensity, 0, 0, 0, -intensity, 0, intensity, 0, 0, 0, intensity, intensity * 2.0, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * + * @param {number} amount - how much the predator feels his future victim + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.predator = function predator(amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, -4.794486999511719 * amount, -2.8746118545532227 * amount, 0 * amount, 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, 9.193157196044922 * amount, -2.951810836791992 * amount, 0 * amount, -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, -4.2375030517578125 * amount, 7.476448059082031 * amount, 0 * amount, 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * LSD effect + * + * Multiply the current matrix + * + * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + + + ColorMatrixFilter.prototype.lsd = function lsd(multiply) { + var matrix = [2, -0.4, 0.5, 0, 0, -0.5, 2, -0.4, 0, 0, -0.4, -0.5, 3, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, multiply); + }; + + /** + * Erase the current matrix by setting the default one + * + */ + + + ColorMatrixFilter.prototype.reset = function reset() { + var matrix = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]; + + this._loadMatrix(matrix, false); + }; + + /** + * The matrix of the color matrix filter + * + * @member {number[]} + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + + + _createClass(ColorMatrixFilter, [{ + key: 'matrix', + get: function get() { + return this.uniforms.m; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.m = value; + } + + /** + * The opacity value to use when mixing the original and resultant colors. + * + * When the value is 0, the original color is used without modification. + * When the value is 1, the result color is used. + * When in the range (0, 1) the color is interpolated between the original and result by this amount. + * + * @member {number} + * @default 1 + */ + + }, { + key: 'alpha', + get: function get() { + return this.uniforms.uAlpha; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uAlpha = value; + } + }]); + + return ColorMatrixFilter; +}(core.Filter); + +// Americanized alias + + +exports.default = ColorMatrixFilter; +ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + +},{"../../core":65,"path":8}],151:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. You can + * use this filter to apply all manor of crazy warping effects. Currently the r + * property of the texture is used to offset the x and the g property of the texture + * is used to offset the y. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var DisplacementFilter = function (_core$Filter) { + _inherits(DisplacementFilter, _core$Filter); + + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param {number} scale - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + _classCallCheck(this, DisplacementFilter); + + var maskMatrix = new core.Matrix(); + + sprite.renderable = false; + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vFilterCoord = ( filterMatrix * vec3( aTextureCoord, 1.0) ).xy;\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\n\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy *= scale / filterArea.xy;\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), filterClamp.xy, filterClamp.zw));\n}\n')); + + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + + _this.uniforms.mapSampler = sprite._texture; + _this.uniforms.filterMatrix = maskMatrix; + _this.uniforms.scale = { x: 1, y: 1 }; + + if (scale === null || scale === undefined) { + scale = 20; + } + + _this.scale = new core.Point(scale, scale); + return _this; + } + + /** + * Applies the filter. + * + * @param {PIXI.FilterManager} filterManager - The manager. + * @param {PIXI.RenderTarget} input - The input target. + * @param {PIXI.RenderTarget} output - The output target. + */ + + + DisplacementFilter.prototype.apply = function apply(filterManager, input, output) { + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x; + this.uniforms.scale.y = this.scale.y; + + // draw the filter... + filterManager.applyFilter(this, input, output); + }; + + /** + * The texture used for the displacement map. Must be power of 2 sized texture. + * + * @member {PIXI.Texture} + */ + + + _createClass(DisplacementFilter, [{ + key: 'map', + get: function get() { + return this.uniforms.mapSampler; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.mapSampler = value; + } + }]); + + return DisplacementFilter; +}(core.Filter); + +exports.default = DisplacementFilter; + +},{"../../core":65,"path":8}],152:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * Basic FXAA implementation based on the code on geeks3d.com with the + * modification that the texture2DLod stuff was removed since it's + * unsupported by WebGL. + * + * @see https://github.com/mitsuhiko/webgl-meincraft + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + * + */ +var FXAAFilter = function (_core$Filter) { + _inherits(FXAAFilter, _core$Filter); + + /** + * + */ + function FXAAFilter() { + _classCallCheck(this, FXAAFilter); + + // TODO - needs work + return _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + '\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nuniform vec4 filterArea;\n\nvarying vec2 vTextureCoord;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvoid texcoords(vec2 fragCoord, vec2 resolution,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n vec2 inverseVP = 1.0 / resolution.xy;\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n texcoords(fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}', + // fragment shader + 'varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n \n --\n \n From:\n https://github.com/mitsuhiko/webgl-meincraft\n \n Copyright (c) 2011 by Armin Ronacher.\n \n Some rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n \n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n \n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n \n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n \n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n \n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n \n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n \n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n')); + } + + return FXAAFilter; +}(core.Filter); + +exports.default = FXAAFilter; + +},{"../../core":65,"path":8}],153:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _FXAAFilter = require('./fxaa/FXAAFilter'); + +Object.defineProperty(exports, 'FXAAFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_FXAAFilter).default; + } +}); + +var _NoiseFilter = require('./noise/NoiseFilter'); + +Object.defineProperty(exports, 'NoiseFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NoiseFilter).default; + } +}); + +var _DisplacementFilter = require('./displacement/DisplacementFilter'); + +Object.defineProperty(exports, 'DisplacementFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_DisplacementFilter).default; + } +}); + +var _BlurFilter = require('./blur/BlurFilter'); + +Object.defineProperty(exports, 'BlurFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurFilter).default; + } +}); + +var _BlurXFilter = require('./blur/BlurXFilter'); + +Object.defineProperty(exports, 'BlurXFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurXFilter).default; + } +}); + +var _BlurYFilter = require('./blur/BlurYFilter'); + +Object.defineProperty(exports, 'BlurYFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BlurYFilter).default; + } +}); + +var _ColorMatrixFilter = require('./colormatrix/ColorMatrixFilter'); + +Object.defineProperty(exports, 'ColorMatrixFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ColorMatrixFilter).default; + } +}); + +var _AlphaFilter = require('./alpha/AlphaFilter'); + +Object.defineProperty(exports, 'AlphaFilter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_AlphaFilter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./alpha/AlphaFilter":143,"./blur/BlurFilter":144,"./blur/BlurXFilter":145,"./blur/BlurYFilter":146,"./colormatrix/ColorMatrixFilter":150,"./displacement/DisplacementFilter":151,"./fxaa/FXAAFilter":152,"./noise/NoiseFilter":154}],154:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _path = require('path'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Vico @vicocotea + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + */ + +/** + * A Noise effect filter. + * + * @class + * @extends PIXI.Filter + * @memberof PIXI.filters + */ +var NoiseFilter = function (_core$Filter) { + _inherits(NoiseFilter, _core$Filter); + + /** + * @param {number} noise - The noise intensity, should be a normalized value in the range [0, 1]. + * @param {number} seed - A random seed for the noise generation. Default is `Math.random()`. + */ + function NoiseFilter() { + var noise = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0.5; + var seed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Math.random(); + + _classCallCheck(this, NoiseFilter); + + var _this = _possibleConstructorReturn(this, _core$Filter.call(this, + // vertex shader + 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}', + // fragment shader + 'precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n')); + + _this.noise = noise; + _this.seed = seed; + return _this; + } + + /** + * The amount of noise to apply, this value should be in the range (0, 1]. + * + * @member {number} + * @default 0.5 + */ + + + _createClass(NoiseFilter, [{ + key: 'noise', + get: function get() { + return this.uniforms.uNoise; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uNoise = value; + } + + /** + * A seed value to apply to the random noise generation. `Math.random()` is a good value to use. + * + * @member {number} + */ + + }, { + key: 'seed', + get: function get() { + return this.uniforms.uSeed; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.uniforms.uSeed = value; + } + }]); + + return NoiseFilter; +}(core.Filter); + +exports.default = NoiseFilter; + +},{"../../core":65,"path":8}],155:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Holds all information related to an Interaction event + * + * @class + * @memberof PIXI.interaction + */ +var InteractionData = function () { + /** + * + */ + function InteractionData() { + _classCallCheck(this, InteractionData); + + /** + * This point stores the global coords of where the touch/mouse event happened + * + * @member {PIXI.Point} + */ + this.global = new core.Point(); + + /** + * The target DisplayObject that was interacted with + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * When passed to an event handler, this will be the original DOM Event that was captured + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent + * @see https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent + * @member {MouseEvent|TouchEvent|PointerEvent} + */ + this.originalEvent = null; + + /** + * Unique identifier for this interaction + * + * @member {number} + */ + this.identifier = null; + + /** + * Indicates whether or not the pointer device that created the event is the primary pointer. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary + * @type {Boolean} + */ + this.isPrimary = false; + + /** + * Indicates which button was pressed on the mouse or pointer device to trigger the event. + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button + * @type {number} + */ + this.button = 0; + + /** + * Indicates which buttons are pressed on the mouse or pointer device when the event is triggered. + * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons + * @type {number} + */ + this.buttons = 0; + + /** + * The width of the pointer's contact along the x-axis, measured in CSS pixels. + * radiusX of TouchEvents will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width + * @type {number} + */ + this.width = 0; + + /** + * The height of the pointer's contact along the y-axis, measured in CSS pixels. + * radiusY of TouchEvents will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height + * @type {number} + */ + this.height = 0; + + /** + * The angle, in degrees, between the pointer device and the screen. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX + * @type {number} + */ + this.tiltX = 0; + + /** + * The angle, in degrees, between the pointer device and the screen. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY + * @type {number} + */ + this.tiltY = 0; + + /** + * The type of pointer that triggered the event. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType + * @type {string} + */ + this.pointerType = null; + + /** + * Pressure applied by the pointing device during the event. A Touch's force property + * will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure + * @type {number} + */ + this.pressure = 0; + + /** + * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch. + * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle + * @type {number} + */ + this.rotationAngle = 0; + + /** + * Twist of a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + * @type {number} + */ + this.twist = 0; + + /** + * Barrel pressure on a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + * @type {number} + */ + this.tangentialPressure = 0; + } + + /** + * The unique identifier of the pointer. It will be the same as `identifier`. + * @readonly + * @member {number} + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId + */ + + + /** + * This will return the local coordinates of the specified displayObject for this InteractionData + * + * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local + * coords off + * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative + * to the DisplayObject + */ + InteractionData.prototype.getLocalPosition = function getLocalPosition(displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + + /** + * Copies properties from normalized event data. + * + * @param {Touch|MouseEvent|PointerEvent} event The normalized event data + */ + + + InteractionData.prototype.copyEvent = function copyEvent(event) { + // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite + // it with "false" on later events when our shim for it on touch events might not be + // accurate + if (event.isPrimary) { + this.isPrimary = true; + } + this.button = event.button; + // event.buttons is not available in all browsers (ie. Safari), but it does have a non-standard + // event.which property instead, which conveys the same information. + this.buttons = Number.isInteger(event.buttons) ? event.buttons : event.which; + this.width = event.width; + this.height = event.height; + this.tiltX = event.tiltX; + this.tiltY = event.tiltY; + this.pointerType = event.pointerType; + this.pressure = event.pressure; + this.rotationAngle = event.rotationAngle; + this.twist = event.twist || 0; + this.tangentialPressure = event.tangentialPressure || 0; + }; + + /** + * Resets the data for pooling. + */ + + + InteractionData.prototype.reset = function reset() { + // isPrimary is the only property that we really need to reset - everything else is + // guaranteed to be overwritten + this.isPrimary = false; + }; + + _createClass(InteractionData, [{ + key: 'pointerId', + get: function get() { + return this.identifier; + } + }]); + + return InteractionData; +}(); + +exports.default = InteractionData; + +},{"../core":65}],156:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Event class that mimics native DOM events. + * + * @class + * @memberof PIXI.interaction + */ +var InteractionEvent = function () { + /** + * + */ + function InteractionEvent() { + _classCallCheck(this, InteractionEvent); + + /** + * Whether this event will continue propagating in the tree + * + * @member {boolean} + */ + this.stopped = false; + + /** + * The object which caused this event to be dispatched. + * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}. + * + * @member {PIXI.DisplayObject} + */ + this.target = null; + + /** + * The object whose event listener’s callback is currently being invoked. + * + * @member {PIXI.DisplayObject} + */ + this.currentTarget = null; + + /** + * Type of the event + * + * @member {string} + */ + this.type = null; + + /** + * InteractionData related to this event + * + * @member {PIXI.interaction.InteractionData} + */ + this.data = null; + } + + /** + * Prevents event from reaching any objects other than the current object. + * + */ + + + InteractionEvent.prototype.stopPropagation = function stopPropagation() { + this.stopped = true; + }; + + /** + * Resets the event. + */ + + + InteractionEvent.prototype.reset = function reset() { + this.stopped = false; + this.currentTarget = null; + this.target = null; + }; + + return InteractionEvent; +}(); + +exports.default = InteractionEvent; + +},{}],157:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _InteractionData = require('./InteractionData'); + +var _InteractionData2 = _interopRequireDefault(_InteractionData); + +var _InteractionEvent = require('./InteractionEvent'); + +var _InteractionEvent2 = _interopRequireDefault(_InteractionEvent); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +var _InteractionTrackingData2 = _interopRequireDefault(_InteractionTrackingData); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _interactiveTarget = require('./interactiveTarget'); + +var _interactiveTarget2 = _interopRequireDefault(_interactiveTarget); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +// Mix interactiveTarget into core.DisplayObject.prototype, after deprecation has been handled +core.utils.mixins.delayMixin(core.DisplayObject.prototype, _interactiveTarget2.default); + +var MOUSE_POINTER_ID = 1; + +// helpers for hitTest() - only used inside hitTest() +var hitTestEvent = { + target: null, + data: { + global: null + } +}; + +/** + * The interaction manager deals with mouse, touch and pointer events. Any DisplayObject can be interactive + * if its interactive parameter is set to true + * This manager also supports multitouch. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.interaction + * + * @class + * @extends EventEmitter + * @memberof PIXI.interaction + */ + +var InteractionManager = function (_EventEmitter) { + _inherits(InteractionManager, _EventEmitter); + + /** + * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - A reference to the current renderer + * @param {object} [options] - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Frequency increases the interaction events will be checked. + */ + function InteractionManager(renderer, options) { + _classCallCheck(this, InteractionManager); + + var _this = _possibleConstructorReturn(this, _EventEmitter.call(this)); + + options = options || {}; + + /** + * The renderer this interaction manager works for. + * + * @member {PIXI.SystemRenderer} + */ + _this.renderer = renderer; + + /** + * Should default browser actions automatically be prevented. + * Does not apply to pointer events for backwards compatibility + * preventDefault on pointer events stops mouse events from firing + * Thus, for every pointer event, there will always be either a mouse of touch event alongside it. + * + * @member {boolean} + * @default true + */ + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + + /** + * Frequency in milliseconds that the mousemove, moveover & mouseout interaction events will be checked. + * + * @member {number} + * @default 10 + */ + _this.interactionFrequency = options.interactionFrequency || 10; + + /** + * The mouse data + * + * @member {PIXI.interaction.InteractionData} + */ + _this.mouse = new _InteractionData2.default(); + _this.mouse.identifier = MOUSE_POINTER_ID; + + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + + /** + * Actively tracked InteractionData + * + * @private + * @member {Object.} + */ + _this.activeInteractionData = {}; + _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; + + /** + * Pool of unused InteractionData + * + * @private + * @member {PIXI.interation.InteractionData[]} + */ + _this.interactionDataPool = []; + + /** + * An event data object to handle all the event tracking/dispatching + * + * @member {object} + */ + _this.eventData = new _InteractionEvent2.default(); + + /** + * The DOM element to bind to. + * + * @private + * @member {HTMLElement} + */ + _this.interactionDOMElement = null; + + /** + * This property determines if mousemove and touchmove events are fired only when the cursor + * is over the object. + * Setting to true will make things work more in line with how the DOM verison works. + * Setting to false can make things easier for things like dragging + * It is currently set to false as this is how PixiJS used to work. This will be set to true in + * future versions of pixi. + * + * @member {boolean} + * @default false + */ + _this.moveWhenInside = false; + + /** + * Have events been attached to the dom element? + * + * @private + * @member {boolean} + */ + _this.eventsAdded = false; + + /** + * Is the mouse hovering over the renderer? + * + * @private + * @member {boolean} + */ + _this.mouseOverRenderer = false; + + /** + * Does the device support touch events + * https://www.w3.org/TR/touch-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsTouchEvents = 'ontouchstart' in window; + + /** + * Does the device support pointer events + * https://www.w3.org/Submission/pointer-events/ + * + * @readonly + * @member {boolean} + */ + _this.supportsPointerEvents = !!window.PointerEvent; + + // this will make it so that you don't have to call bind all the time + + /** + * @private + * @member {Function} + */ + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerCancel = _this.onPointerCancel.bind(_this); + _this.processPointerCancel = _this.processPointerCancel.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + + /** + * @private + * @member {Function} + */ + _this.onPointerOver = _this.onPointerOver.bind(_this); + + /** + * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor + * values, objects are handled as dictionaries of CSS values for interactionDOMElement, + * and functions are called instead of changing the CSS. + * Default CSS cursor values are provided for 'default' and 'pointer' modes. + * @member {Object.)>} + */ + _this.cursorStyles = { + default: 'inherit', + pointer: 'pointer' + }; + + /** + * The mode of the cursor that is being used. + * The value of this is a key from the cursorStyles dictionary. + * + * @member {string} + */ + _this.currentCursorMode = null; + + /** + * Internal cached let. + * + * @private + * @member {string} + */ + _this.cursor = null; + + /** + * Internal cached let. + * + * @private + * @member {PIXI.Point} + */ + _this._tempPoint = new core.Point(); + + /** + * The current resolution / device pixel ratio. + * + * @member {number} + * @default 1 + */ + _this.resolution = 1; + + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display + * object. + * + * @event PIXI.interaction.InteractionManager#mousedown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * + * @event PIXI.interaction.InteractionManager#rightdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. + * + * @event PIXI.interaction.InteractionManager#mouseup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * + * @event PIXI.interaction.InteractionManager#rightup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. + * + * @event PIXI.interaction.InteractionManager#click + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * + * @event PIXI.interaction.InteractionManager#rightclick + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}. + * + * @event PIXI.interaction.InteractionManager#mouseupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}. + * + * @event PIXI.interaction.InteractionManager#rightupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * + * @event PIXI.interaction.InteractionManager#mousemove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * + * @event PIXI.interaction.InteractionManager#mouseover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * + * @event PIXI.interaction.InteractionManager#mouseout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * + * @event PIXI.interaction.InteractionManager#pointerdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released over the display object. + * Not always fired when some buttons are held down while others are released. In those cases, + * use [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown} and + * [mouseup]{@link PIXI.interaction.InteractionManager#event:mouseup} instead. + * + * @event PIXI.interaction.InteractionManager#pointerup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a pointer event + * + * @event PIXI.interaction.InteractionManager#pointercancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * + * @event PIXI.interaction.InteractionManager#pointertap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}. + * + * @event PIXI.interaction.InteractionManager#pointerupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved while over the display object + * + * @event PIXI.interaction.InteractionManager#pointermove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved onto the display object + * + * @event PIXI.interaction.InteractionManager#pointerover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved off the display object + * + * @event PIXI.interaction.InteractionManager#pointerout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed on the display object. + * + * @event PIXI.interaction.InteractionManager#touchstart + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed from the display object. + * + * @event PIXI.interaction.InteractionManager#touchend + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a touch + * + * @event PIXI.interaction.InteractionManager#touchcancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * + * @event PIXI.interaction.InteractionManager#tap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}. + * + * @event PIXI.interaction.InteractionManager#touchendoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is moved along the display object. + * + * @event PIXI.interaction.InteractionManager#touchmove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display. + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mousedown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#click + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightclick + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.DisplayObject#event:mousedown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.DisplayObject#event:rightdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#rightupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mousemove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device (usually a mouse) is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#mouseout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerdown + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerup + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a pointer event. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointercancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is pressed and released on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointertap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerupoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointermove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerover + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a pointer device is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#pointerout + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchstart + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchend + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when the operating system cancels a touch. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchcancel + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is placed and removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#tap + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchendoutside + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + + /** + * Fired when a touch point is moved along the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * @event PIXI.DisplayObject#touchmove + * @param {PIXI.interaction.InteractionEvent} event - Interaction event + */ + return _this; + } + + /** + * Hit tests a point against the display tree, returning the first interactive object that is hit. + * + * @param {PIXI.Point} globalPoint - A point to hit test with, in global space. + * @param {PIXI.Container} [root] - The root display object to start from. If omitted, defaults + * to the last rendered root of the associated renderer. + * @return {PIXI.DisplayObject} The hit display object, if any. + */ + + + InteractionManager.prototype.hitTest = function hitTest(globalPoint, root) { + // clear the target for our hit test + hitTestEvent.target = null; + // assign the global point + hitTestEvent.data.global = globalPoint; + // ensure safety of the root + if (!root) { + root = this.renderer._lastObjectRendered; + } + // run the hit test + this.processInteractive(hitTestEvent, root, null, true); + // return our found object - it'll be null if we didn't hit anything + + return hitTestEvent.target; + }; + + /** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to deletegate + * another DOM element to receive those events. + * + * @param {HTMLCanvasElement} element - the DOM element which will receive mouse and touch events. + * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). + */ + + + InteractionManager.prototype.setTargetElement = function setTargetElement(element) { + var resolution = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + + this.removeEvents(); + + this.interactionDOMElement = element; + + this.resolution = resolution; + + this.addEvents(); + }; + + /** + * Registers all the DOM events + * + * @private + */ + + + InteractionManager.prototype.addEvents = function addEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.add(this.update, this, core.UPDATE_PRIORITY.INTERACTION); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = 'none'; + this.interactionDOMElement.style['-ms-touch-action'] = 'none'; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = 'none'; + } + + /** + * These events are added first, so that if pointer events are normalised, they are fired + * in the same order as non-normalised events. ie. pointer event 1st, mouse / touch 2nd + */ + if (this.supportsPointerEvents) { + window.document.addEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); + // pointerout is fired in addition to pointerup (for touch events) and pointercancel + // we already handle those, so for the purposes of what we do in onPointerOut, we only + // care about the pointerleave event + this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); + window.addEventListener('pointercancel', this.onPointerCancel, true); + window.addEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.addEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); + window.addEventListener('mouseup', this.onPointerUp, true); + } + + // always look directly for touch events so that we can provide original data + // In a future version we should change this to being just a fallback and rely solely on + // PointerEvents whenever available + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); + } + + this.eventsAdded = true; + }; + + /** + * Removes all the DOM events that were previously registered + * + * @private + */ + + + InteractionManager.prototype.removeEvents = function removeEvents() { + if (!this.interactionDOMElement) { + return; + } + + core.ticker.shared.remove(this.update, this); + + if (window.navigator.msPointerEnabled) { + this.interactionDOMElement.style['-ms-content-zooming'] = ''; + this.interactionDOMElement.style['-ms-touch-action'] = ''; + } else if (this.supportsPointerEvents) { + this.interactionDOMElement.style['touch-action'] = ''; + } + + if (this.supportsPointerEvents) { + window.document.removeEventListener('pointermove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); + window.removeEventListener('pointercancel', this.onPointerCancel, true); + window.removeEventListener('pointerup', this.onPointerUp, true); + } else { + window.document.removeEventListener('mousemove', this.onPointerMove, true); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); + this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true); + window.removeEventListener('mouseup', this.onPointerUp, true); + } + + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); + this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); + } + + this.interactionDOMElement = null; + + this.eventsAdded = false; + }; + + /** + * Updates the state of interactive objects. + * Invoked by a throttled ticker update from {@link PIXI.ticker.shared}. + * + * @param {number} deltaTime - time delta since last tick + */ + + + InteractionManager.prototype.update = function update(deltaTime) { + this._deltaTime += deltaTime; + + if (this._deltaTime < this.interactionFrequency) { + return; + } + + this._deltaTime = 0; + + if (!this.interactionDOMElement) { + return; + } + + // if the user move the mouse this check has already been done using the mouse move! + if (this.didMove) { + this.didMove = false; + + return; + } + + this.cursor = null; + + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + for (var k in this.activeInteractionData) { + // eslint-disable-next-line no-prototype-builtins + if (this.activeInteractionData.hasOwnProperty(k)) { + var interactionData = this.activeInteractionData[k]; + + if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, true); + } + } + } + + this.setCursorMode(this.cursor); + + // TODO + }; + + /** + * Sets the current cursor mode, handling any callbacks or CSS style changes. + * + * @param {string} mode - cursor mode, a key from the cursorStyles dictionary + */ + + + InteractionManager.prototype.setCursorMode = function setCursorMode(mode) { + mode = mode || 'default'; + // if the mode didn't actually change, bail early + if (this.currentCursorMode === mode) { + return; + } + this.currentCursorMode = mode; + var style = this.cursorStyles[mode]; + + // only do things if there is a cursor style for it + if (style) { + switch (typeof style === 'undefined' ? 'undefined' : _typeof(style)) { + case 'string': + // string styles are handled as cursor CSS + this.interactionDOMElement.style.cursor = style; + break; + case 'function': + // functions are just called, and passed the cursor mode + style(mode); + break; + case 'object': + // if it is an object, assume that it is a dictionary of CSS styles, + // apply it to the interactionDOMElement + Object.assign(this.interactionDOMElement.style, style); + break; + } + } else if (typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) { + // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry + // for the mode, then assume that the dev wants it to be CSS for the cursor. + this.interactionDOMElement.style.cursor = mode; + } + }; + + /** + * Dispatches an event on the display object that was interacted with + * + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the display object in question + * @param {string} eventString - the name of the event (e.g, mousedown) + * @param {object} eventData - the event data object + * @private + */ + + + InteractionManager.prototype.dispatchEvent = function dispatchEvent(displayObject, eventString, eventData) { + if (!eventData.stopped) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + + displayObject.emit(eventString, eventData); + + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } + }; + + /** + * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. + * + * @param {PIXI.Point} point - the point that the result will be stored in + * @param {number} x - the x coord of the position to map + * @param {number} y - the y coord of the position to map + */ + + + InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint(point, x, y) { + var rect = void 0; + + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { x: 0, y: 0, width: 0, height: 0 }; + } else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + + var resolutionMultiplier = navigator.isCocoonJS ? this.resolution : 1.0 / this.resolution; + + point.x = (x - rect.left) * (this.interactionDOMElement.width / rect.width) * resolutionMultiplier; + point.y = (y - rect.top) * (this.interactionDOMElement.height / rect.height) * resolutionMultiplier; + }; + + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that + * is tested for collision + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param {Function} [func] - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point + * @param {boolean} [interactive] - Whether the displayObject is interactive + * @return {boolean} returns true if the displayObject hit the point + */ + + + InteractionManager.prototype.processInteractive = function processInteractive(interactionEvent, displayObject, func, hitTest, interactive) { + if (!displayObject || !displayObject.visible) { + return false; + } + + var point = interactionEvent.data.global; + + // Took a little while to rework this function correctly! But now it is done and nice and optimised. ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimisation once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimisation is that an object is not hit test directly if a child has already been hit. + + interactive = displayObject.interactive || interactive; + + var hit = false; + var interactiveParent = interactive; + + // Flag here can set to false if the event is outside the parents hitArea or mask + var hitTestChildren = true; + + // If there is a hitArea, no need to test against anything else if the pointer is not within the hitArea + // There is also no longer a need to hitTest children. + if (displayObject.hitArea) { + if (hitTest) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (!displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hitTest = false; + hitTestChildren = false; + } else { + hit = true; + } + } + interactiveParent = false; + } + // If there is a mask, no need to test against anything else if the pointer is not within the mask + else if (displayObject._mask) { + if (hitTest) { + if (!displayObject._mask.containsPoint(point)) { + hitTest = false; + hitTestChildren = false; + } + } + } + + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow PixiJS to completely ignore and bypass checking the displayObjects children. + if (hitTestChildren && displayObject.interactiveChildren && displayObject.children) { + var children = displayObject.children; + + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + + // time to get recursive.. if this function will return if something is hit.. + var childHit = this.processInteractive(interactionEvent, child, func, hitTest, interactiveParent); + + if (childHit) { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if (!child.parent) { + continue; + } + + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + + if (childHit) { + if (interactionEvent.target) { + hitTest = false; + } + hit = true; + } + } + } + } + + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit - but only if it was interactive, otherwise we need to keep + // looking for an interactive child, just in case we hit one + if (hitTest && !interactionEvent.target) { + // already tested against hitArea if it is defined + if (!displayObject.hitArea && displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = true; + } + } + } + + if (displayObject.interactive) { + if (hit && !interactionEvent.target) { + interactionEvent.target = displayObject; + } + + if (func) { + func(interactionEvent, displayObject, !!hit); + } + } + } + + return hit; + }; + + /** + * Is called when the pointer button is pressed down on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down + */ + + + InteractionManager.prototype.onPointerDown = function onPointerDown(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + /** + * No need to prevent default on natural pointer events, as there are no side effects + * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, + * so still need to be prevented. + */ + + // Guaranteed that there will be at least one event in events, and all events must have the same pointer type + + if (this.autoPreventDefault && events[0].isNormalized) { + originalEvent.preventDefault(); + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerDown, true); + + this.emit('pointerdown', interactionEvent); + if (event.pointerType === 'touch') { + this.emit('touchstart', interactionEvent); + } + // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event + else if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + } + }; + + /** + * Processes the result of the pointer down check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerDown = function processPointerDown(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + + if (hit) { + if (!displayObject.trackedPointers[id]) { + displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchstart', interactionEvent); + } else if (data.pointerType === 'mouse' || data.pointerType === 'pen') { + var isRightButton = data.button === 2; + + if (isRightButton) { + displayObject.trackedPointers[id].rightDown = true; + } else { + displayObject.trackedPointers[id].leftDown = true; + } + + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released + * @param {boolean} cancelled - true if the pointer is cancelled + * @param {Function} func - Function passed to {@link processInteractive} + */ + + + InteractionManager.prototype.onPointerComplete = function onPointerComplete(originalEvent, cancelled, func) { + var events = this.normalizeToPointerData(originalEvent); + + var eventLen = events.length; + + // if the event wasn't targeting our canvas, then consider it to be pointerupoutside + // in all cases (unless it was a pointercancel) + var eventAppend = originalEvent.target !== this.interactionDOMElement ? 'outside' : ''; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + // perform hit testing for events targeting our canvas or cancel events + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, func, cancelled || !eventAppend); + + this.emit(cancelled ? 'pointercancel' : 'pointerup' + eventAppend, interactionEvent); + + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + + this.emit(isRightButton ? 'rightup' + eventAppend : 'mouseup' + eventAppend, interactionEvent); + } else if (event.pointerType === 'touch') { + this.emit(cancelled ? 'touchcancel' : 'touchend' + eventAppend, interactionEvent); + this.releaseInteractionDataForPointerId(event.pointerId, interactionData); + } + } + }; + + /** + * Is called when the pointer button is cancelled + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerCancel = function onPointerCancel(event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') return; + + this.onPointerComplete(event, true, this.processPointerCancel); + }; + + /** + * Processes the result of the pointer cancel check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + */ + + + InteractionManager.prototype.processPointerCancel = function processPointerCancel(interactionEvent, displayObject) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + if (displayObject.trackedPointers[id] !== undefined) { + delete displayObject.trackedPointers[id]; + this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); + + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); + } + } + }; + + /** + * Is called when the pointer button is released on the renderer element + * + * @private + * @param {PointerEvent} event - The DOM event of a pointer button being released + */ + + + InteractionManager.prototype.onPointerUp = function onPointerUp(event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') return; + + this.onPointerComplete(event, false, this.processPointerUp); + }; + + /** + * Processes the result of the pointer up check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerUp = function processPointerUp(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + var trackingData = displayObject.trackedPointers[id]; + + var isTouch = data.pointerType === 'touch'; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + // need to track mouse down status in the mouse block so that we can emit + // event in a later block + var isMouseTap = false; + + // Mouse only + if (isMouse) { + var isRightButton = data.button === 2; + + var flags = _InteractionTrackingData2.default.FLAGS; + + var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; + + var isDown = trackingData !== undefined && trackingData.flags & test; + + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); + + if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); + // because we can confirm that the mousedown happened on this object, flag for later emit of pointertap + isMouseTap = true; + } + } else if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); + } + // update the down state of the tracking data + if (trackingData) { + if (isRightButton) { + trackingData.rightDown = false; + } else { + trackingData.leftDown = false; + } + } + } + + // Pointers and Touches, and Mouse + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchend', interactionEvent); + + if (trackingData) { + // emit pointertap if not a mouse, or if the mouse block decided it was a tap + if (!isMouse || isMouseTap) { + this.dispatchEvent(displayObject, 'pointertap', interactionEvent); + } + if (isTouch) { + this.dispatchEvent(displayObject, 'tap', interactionEvent); + // touches are no longer over (if they ever were) when we get the touchend + // so we should ensure that we don't keep pretending that they are + trackingData.over = false; + } + } + } else if (trackingData) { + this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); + } + // Only remove the tracking data if there is no over/down state still associated with it + if (trackingData && trackingData.none) { + delete displayObject.trackedPointers[id]; + } + }; + + /** + * Is called when the pointer moves across the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer moving + */ + + + InteractionManager.prototype.onPointerMove = function onPointerMove(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + if (events[0].pointerType === 'mouse' || events[0].pointerType === 'pen') { + this.didMove = true; + + this.cursor = null; + } + + var eventLen = events.length; + + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = originalEvent; + + var interactive = event.pointerType === 'touch' ? this.moveWhenInside : true; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerMove, interactive); + this.emit('pointermove', interactionEvent); + if (event.pointerType === 'touch') this.emit('touchmove', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') this.emit('mousemove', interactionEvent); + } + + if (events[0].pointerType === 'mouse') { + this.setCursorMode(this.cursor); + + // TODO BUG for parents interactive object (border order issue) + } + }; + + /** + * Processes the result of the pointer move check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerMove = function processPointerMove(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var isTouch = data.pointerType === 'touch'; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + if (isMouse) { + this.processPointerOverOut(interactionEvent, displayObject, hit); + } + + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', interactionEvent); + if (isTouch) this.dispatchEvent(displayObject, 'touchmove', interactionEvent); + if (isMouse) this.dispatchEvent(displayObject, 'mousemove', interactionEvent); + } + }; + + /** + * Is called when the pointer is moved out of the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out + */ + + + InteractionManager.prototype.onPointerOut = function onPointerOut(originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') return; + + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOut, so events will always be length 1 + var event = events[0]; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = false; + this.setCursorMode(null); + } + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, false); + + this.emit('pointerout', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseout', interactionEvent); + } else { + // we can get touchleave events after touchend, so we want to make sure we don't + // introduce memory leaks + this.releaseInteractionDataForPointerId(interactionData.identifier); + } + }; + + /** + * Processes the result of the pointer over/out check and dispatches the event if need be + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event + * @param {PIXI.Container|PIXI.Sprite|PIXI.extras.TilingSprite} displayObject - The display object that was tested + * @param {boolean} hit - the result of the hit test on the display object + */ + + + InteractionManager.prototype.processPointerOverOut = function processPointerOverOut(interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + + var id = interactionEvent.data.identifier; + + var isMouse = data.pointerType === 'mouse' || data.pointerType === 'pen'; + + var trackingData = displayObject.trackedPointers[id]; + + // if we just moused over the display object, then we need to track that state + if (hit && !trackingData) { + trackingData = displayObject.trackedPointers[id] = new _InteractionTrackingData2.default(id); + } + + if (trackingData === undefined) return; + + if (hit && this.mouseOverRenderer) { + if (!trackingData.over) { + trackingData.over = true; + this.dispatchEvent(displayObject, 'pointerover', interactionEvent); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseover', interactionEvent); + } + } + + // only change the cursor if it has not already been changed (by something deeper in the + // display tree) + if (isMouse && this.cursor === null) { + this.cursor = displayObject.cursor; + } + } else if (trackingData.over) { + trackingData.over = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseout', interactionEvent); + } + // if there is no mouse down information for the pointer, then it is safe to delete + if (trackingData.none) { + delete displayObject.trackedPointers[id]; + } + } + }; + + /** + * Is called when the pointer is moved into the renderer element + * + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view + */ + + + InteractionManager.prototype.onPointerOver = function onPointerOver(originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + + // Only mouse and pointer can call onPointerOver, so events will always be length 1 + var event = events[0]; + + var interactionData = this.getInteractionDataForPointerId(event); + + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + + interactionEvent.data.originalEvent = event; + + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = true; + } + + this.emit('pointerover', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseover', interactionEvent); + } + }; + + /** + * Get InteractionData for a given pointerId. Store that data as well + * + * @private + * @param {PointerEvent} event - Normalized pointer event, output from normalizeToPointerData + * @return {PIXI.interaction.InteractionData} - Interaction data for the given pointer identifier + */ + + + InteractionManager.prototype.getInteractionDataForPointerId = function getInteractionDataForPointerId(event) { + var pointerId = event.pointerId; + + var interactionData = void 0; + + if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { + interactionData = this.mouse; + } else if (this.activeInteractionData[pointerId]) { + interactionData = this.activeInteractionData[pointerId]; + } else { + interactionData = this.interactionDataPool.pop() || new _InteractionData2.default(); + interactionData.identifier = pointerId; + this.activeInteractionData[pointerId] = interactionData; + } + // copy properties from the event, so that we can make sure that touch/pointer specific + // data is available + interactionData.copyEvent(event); + + return interactionData; + }; + + /** + * Return unused InteractionData to the pool, for a given pointerId + * + * @private + * @param {number} pointerId - Identifier from a pointer event + */ + + + InteractionManager.prototype.releaseInteractionDataForPointerId = function releaseInteractionDataForPointerId(pointerId) { + var interactionData = this.activeInteractionData[pointerId]; + + if (interactionData) { + delete this.activeInteractionData[pointerId]; + interactionData.reset(); + this.interactionDataPool.push(interactionData); + } + }; + + /** + * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData + * + * @private + * @param {PIXI.interaction.InteractionEvent} interactionEvent - The event to be configured + * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent + * @param {PIXI.interaction.InteractionData} interactionData - The InteractionData that will be paired + * with the InteractionEvent + * @return {PIXI.interaction.InteractionEvent} the interaction event that was passed in + */ + + + InteractionManager.prototype.configureInteractionEventForDOMEvent = function configureInteractionEventForDOMEvent(interactionEvent, pointerEvent, interactionData) { + interactionEvent.data = interactionData; + + this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); + + // This is the way InteractionManager processed touch events before the refactoring, so I've kept + // it here. But it doesn't make that much sense to me, since mapPositionToPoint already factors + // in this.resolution, so this just divides by this.resolution twice for touch events... + if (navigator.isCocoonJS && pointerEvent.pointerType === 'touch') { + interactionData.global.x = interactionData.global.x / this.resolution; + interactionData.global.y = interactionData.global.y / this.resolution; + } + + // Not really sure why this is happening, but it's how a previous version handled things + if (pointerEvent.pointerType === 'touch') { + pointerEvent.globalX = interactionData.global.x; + pointerEvent.globalY = interactionData.global.y; + } + + interactionData.originalEvent = pointerEvent; + interactionEvent.reset(); + + return interactionEvent; + }; + + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * + * @private + * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event + * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer + * or mouse event, or a multiple normalized pointer events if there are multiple changed touches + */ + + + InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData(event) { + var normalizedEvents = []; + + if (this.supportsTouchEvents && event instanceof TouchEvent) { + for (var i = 0, li = event.changedTouches.length; i < li; i++) { + var touch = event.changedTouches[i]; + + if (typeof touch.button === 'undefined') touch.button = event.touches.length ? 1 : 0; + if (typeof touch.buttons === 'undefined') touch.buttons = event.touches.length ? 1 : 0; + if (typeof touch.isPrimary === 'undefined') { + touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart'; + } + if (typeof touch.width === 'undefined') touch.width = touch.radiusX || 1; + if (typeof touch.height === 'undefined') touch.height = touch.radiusY || 1; + if (typeof touch.tiltX === 'undefined') touch.tiltX = 0; + if (typeof touch.tiltY === 'undefined') touch.tiltY = 0; + if (typeof touch.pointerType === 'undefined') touch.pointerType = 'touch'; + if (typeof touch.pointerId === 'undefined') touch.pointerId = touch.identifier || 0; + if (typeof touch.pressure === 'undefined') touch.pressure = touch.force || 0.5; + if (typeof touch.twist === 'undefined') touch.twist = 0; + if (typeof touch.tangentialPressure === 'undefined') touch.tangentialPressure = 0; + // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven + // support, and the fill ins are not quite the same + // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top + // left is not 0,0 on the page + if (typeof touch.layerX === 'undefined') touch.layerX = touch.offsetX = touch.clientX; + if (typeof touch.layerY === 'undefined') touch.layerY = touch.offsetY = touch.clientY; + + // mark the touch as normalized, just so that we know we did it + touch.isNormalized = true; + + normalizedEvents.push(touch); + } + } + // apparently PointerEvent subclasses MouseEvent, so yay + else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent))) { + if (typeof event.isPrimary === 'undefined') event.isPrimary = true; + if (typeof event.width === 'undefined') event.width = 1; + if (typeof event.height === 'undefined') event.height = 1; + if (typeof event.tiltX === 'undefined') event.tiltX = 0; + if (typeof event.tiltY === 'undefined') event.tiltY = 0; + if (typeof event.pointerType === 'undefined') event.pointerType = 'mouse'; + if (typeof event.pointerId === 'undefined') event.pointerId = MOUSE_POINTER_ID; + if (typeof event.pressure === 'undefined') event.pressure = 0.5; + if (typeof event.twist === 'undefined') event.twist = 0; + if (typeof event.tangentialPressure === 'undefined') event.tangentialPressure = 0; + + // mark the mouse event as normalized, just so that we know we did it + event.isNormalized = true; + + normalizedEvents.push(event); + } else { + normalizedEvents.push(event); + } + + return normalizedEvents; + }; + + /** + * Destroys the interaction manager + * + */ + + + InteractionManager.prototype.destroy = function destroy() { + this.removeEvents(); + + this.removeAllListeners(); + + this.renderer = null; + + this.mouse = null; + + this.eventData = null; + + this.interactionDOMElement = null; + + this.onPointerDown = null; + this.processPointerDown = null; + + this.onPointerUp = null; + this.processPointerUp = null; + + this.onPointerCancel = null; + this.processPointerCancel = null; + + this.onPointerMove = null; + this.processPointerMove = null; + + this.onPointerOut = null; + this.processPointerOverOut = null; + + this.onPointerOver = null; + + this._tempPoint = null; + }; + + return InteractionManager; +}(_eventemitter2.default); + +exports.default = InteractionManager; + + +core.WebGLRenderer.registerPlugin('interaction', InteractionManager); +core.CanvasRenderer.registerPlugin('interaction', InteractionManager); + +},{"../core":65,"./InteractionData":155,"./InteractionEvent":156,"./InteractionTrackingData":158,"./interactiveTarget":160,"eventemitter3":3}],158:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * DisplayObjects with the {@link PIXI.interaction.interactiveTarget} mixin use this class to track interactions + * + * @class + * @private + * @memberof PIXI.interaction + */ +var InteractionTrackingData = function () { + /** + * @param {number} pointerId - Unique pointer id of the event + */ + function InteractionTrackingData(pointerId) { + _classCallCheck(this, InteractionTrackingData); + + this._pointerId = pointerId; + this._flags = InteractionTrackingData.FLAGS.NONE; + } + + /** + * + * @private + * @param {number} flag - The interaction flag to set + * @param {boolean} yn - Should the flag be set or unset + */ + + + InteractionTrackingData.prototype._doSet = function _doSet(flag, yn) { + if (yn) { + this._flags = this._flags | flag; + } else { + this._flags = this._flags & ~flag; + } + }; + + /** + * Unique pointer id of the event + * + * @readonly + * @member {number} + */ + + + _createClass(InteractionTrackingData, [{ + key: "pointerId", + get: function get() { + return this._pointerId; + } + + /** + * State of the tracking data, expressed as bit flags + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "flags", + get: function get() { + return this._flags; + } + + /** + * Set the flags for the tracking data + * + * @param {number} flags - Flags to set + */ + , + set: function set(flags) { + this._flags = flags; + } + + /** + * Is the tracked event inactive (not over or down)? + * + * @member {number} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "none", + get: function get() { + return this._flags === this.constructor.FLAGS.NONE; + } + + /** + * Is the tracked event over the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "over", + get: function get() { + return (this._flags & this.constructor.FLAGS.OVER) !== 0; + } + + /** + * Set the over flag + * + * @param {boolean} yn - Is the event over? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.OVER, yn); + } + + /** + * Did the right mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "rightDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.RIGHT_DOWN) !== 0; + } + + /** + * Set the right down flag + * + * @param {boolean} yn - Is the right mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.RIGHT_DOWN, yn); + } + + /** + * Did the left mouse button come down in the DisplayObject? + * + * @member {boolean} + * @memberof PIXI.interaction.InteractionTrackingData# + */ + + }, { + key: "leftDown", + get: function get() { + return (this._flags & this.constructor.FLAGS.LEFT_DOWN) !== 0; + } + + /** + * Set the left down flag + * + * @param {boolean} yn - Is the left mouse button down? + */ + , + set: function set(yn) { + this._doSet(this.constructor.FLAGS.LEFT_DOWN, yn); + } + }]); + + return InteractionTrackingData; +}(); + +exports.default = InteractionTrackingData; + + +InteractionTrackingData.FLAGS = Object.freeze({ + NONE: 0, + OVER: 1 << 0, + LEFT_DOWN: 1 << 1, + RIGHT_DOWN: 1 << 2 +}); + +},{}],159:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _InteractionData = require('./InteractionData'); + +Object.defineProperty(exports, 'InteractionData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionData).default; + } +}); + +var _InteractionManager = require('./InteractionManager'); + +Object.defineProperty(exports, 'InteractionManager', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionManager).default; + } +}); + +var _interactiveTarget = require('./interactiveTarget'); + +Object.defineProperty(exports, 'interactiveTarget', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_interactiveTarget).default; + } +}); + +var _InteractionTrackingData = require('./InteractionTrackingData'); + +Object.defineProperty(exports, 'InteractionTrackingData', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionTrackingData).default; + } +}); + +var _InteractionEvent = require('./InteractionEvent'); + +Object.defineProperty(exports, 'InteractionEvent', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_InteractionEvent).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./InteractionData":155,"./InteractionEvent":156,"./InteractionManager":157,"./InteractionTrackingData":158,"./interactiveTarget":160}],160:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +/** + * Default property values of interactive objects + * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties + * + * @private + * @name interactiveTarget + * @memberof PIXI.interaction + * @example + * function MyObject() {} + * + * Object.assign( + * core.DisplayObject.prototype, + * PIXI.interaction.interactiveTarget + * ); + */ +exports.default = { + + /** + * Enable interaction events for the DisplayObject. Touch, pointer and mouse + * events will not be emitted unless `interactive` is set to `true`. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.on('tap', (event) => { + * //handle event + * }); + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + interactive: false, + + /** + * Determines if the children to the displayObject can be clicked/touched + * Setting this to false allows PixiJS to bypass a recursive `hitTest` function + * + * @member {boolean} + * @memberof PIXI.Container# + */ + interactiveChildren: true, + + /** + * Interaction shape. Children will be hit first, then this shape will be checked. + * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.hitArea = new PIXI.Rectangle(0, 0, 100, 100); + * @member {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle} + * @memberof PIXI.DisplayObject# + */ + hitArea: null, + + /** + * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive + * Setting this changes the 'cursor' property to `'pointer'`. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.buttonMode = true; + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + get buttonMode() { + return this.cursor === 'pointer'; + }, + set buttonMode(value) { + if (value) { + this.cursor = 'pointer'; + } else if (this.cursor === 'pointer') { + this.cursor = null; + } + }, + + /** + * This defines what cursor mode is used when the mouse cursor + * is hovered over the displayObject. + * + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.cursor = 'wait'; + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * + * @member {string} + * @memberof PIXI.DisplayObject# + */ + cursor: null, + + /** + * Internal set of all active pointers, by identifier + * + * @member {Map} + * @memberof PIXI.DisplayObject# + * @private + */ + get trackedPointers() { + if (this._trackedPointers === undefined) this._trackedPointers = {}; + + return this._trackedPointers; + }, + + /** + * Map of all tracked pointers, by identifier. Use trackedPointers to access. + * + * @private + * @type {Map} + */ + _trackedPointers: undefined +}; + +},{}],161:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.parse = parse; + +exports.default = function () { + return function bitmapFontParser(resource, next) { + // skip if no data or not xml data + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.XML) { + next(); + + return; + } + + // skip if not bitmap font data, using some silly duck-typing + if (resource.data.getElementsByTagName('page').length === 0 || resource.data.getElementsByTagName('info').length === 0 || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null) { + next(); + + return; + } + + var xmlUrl = !resource.isDataUrl ? path.dirname(resource.url) : ''; + + if (resource.isDataUrl) { + if (xmlUrl === '.') { + xmlUrl = ''; + } + + if (this.baseUrl && xmlUrl) { + // if baseurl has a trailing slash then add one to xmlUrl so the replace works below + if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/') { + xmlUrl += '/'; + } + } + } + + // remove baseUrl from xmlUrl + xmlUrl = xmlUrl.replace(this.baseUrl, ''); + + // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/') { + xmlUrl += '/'; + } + + var pages = resource.data.getElementsByTagName('page'); + var textures = {}; + + // Handle completed, when the number of textures + // load is the same number as references in the fnt file + var completed = function completed(page) { + textures[page.metadata.pageFile] = page.texture; + + if (Object.keys(textures).length === pages.length) { + parse(resource, textures); + next(); + } + }; + + for (var i = 0; i < pages.length; ++i) { + var pageFile = pages[i].getAttribute('file'); + var url = xmlUrl + pageFile; + var exists = false; + + // incase the image is loaded outside + // using the same loader, resource will be available + for (var name in this.resources) { + var bitmapResource = this.resources[name]; + + if (bitmapResource.url === url) { + bitmapResource.metadata.pageFile = pageFile; + if (bitmapResource.texture) { + completed(bitmapResource); + } else { + bitmapResource.onAfterMiddleware.add(completed); + } + exists = true; + break; + } + } + + // texture is not loaded, we'll attempt to add + // it to the load and add the texture to the list + if (!exists) { + // Standard loading options for images + var options = { + crossOrigin: resource.crossOrigin, + loadType: _resourceLoader.Resource.LOAD_TYPE.IMAGE, + metadata: Object.assign({ pageFile: pageFile }, resource.metadata.imageMetadata), + parentResource: resource + }; + + this.add(url, options, completed); + } + } + }; +}; + +var _path = require('path'); + +var path = _interopRequireWildcard(_path); + +var _resourceLoader = require('resource-loader'); + +var _extras = require('../extras'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Register a BitmapText font from loader resource. + * + * @function parseBitmapFontData + * @memberof PIXI.loaders + * @param {PIXI.loaders.Resource} resource - Loader resource. + * @param {PIXI.Texture|PIXI.Texture[]} textures - List of textures for each page. + */ +function parse(resource, textures) { + resource.bitmapFont = _extras.BitmapText.registerFont(resource.data, textures); +} + +},{"../extras":141,"path":8,"resource-loader":36}],162:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.shared = exports.Resource = exports.textureParser = exports.getResourcePath = exports.spritesheetParser = exports.parseBitmapFontData = exports.bitmapFontParser = exports.Loader = undefined; + +var _bitmapFontParser = require('./bitmapFontParser'); + +Object.defineProperty(exports, 'bitmapFontParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_bitmapFontParser).default; + } +}); +Object.defineProperty(exports, 'parseBitmapFontData', { + enumerable: true, + get: function get() { + return _bitmapFontParser.parse; + } +}); + +var _spritesheetParser = require('./spritesheetParser'); + +Object.defineProperty(exports, 'spritesheetParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_spritesheetParser).default; + } +}); +Object.defineProperty(exports, 'getResourcePath', { + enumerable: true, + get: function get() { + return _spritesheetParser.getResourcePath; + } +}); + +var _textureParser = require('./textureParser'); + +Object.defineProperty(exports, 'textureParser', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_textureParser).default; + } +}); + +var _resourceLoader = require('resource-loader'); + +Object.defineProperty(exports, 'Resource', { + enumerable: true, + get: function get() { + return _resourceLoader.Resource; + } +}); + +var _Application = require('../core/Application'); + +var _Application2 = _interopRequireDefault(_Application); + +var _loader = require('./loader'); + +var _loader2 = _interopRequireDefault(_loader); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * This namespace contains APIs which extends the {@link https://github.com/englercj/resource-loader resource-loader} module + * for loading assets, data, and other resources dynamically. + * @example + * const loader = new PIXI.loaders.Loader(); + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.load((loader, resources) => { + * // resources.bunny + * // resources.spaceship + * }); + * @namespace PIXI.loaders + */ +exports.Loader = _loader2.default; + + +/** + * A premade instance of the loader that can be used to load resources. + * @name shared + * @memberof PIXI.loaders + * @type {PIXI.loaders.Loader} + */ +var shared = new _loader2.default(); + +shared.destroy = function () { + // protect destroying shared loader +}; + +exports.shared = shared; + +// Mixin the loader construction + +var AppPrototype = _Application2.default.prototype; + +AppPrototype._loader = null; + +/** + * Loader instance to help with asset loading. + * @name PIXI.Application#loader + * @type {PIXI.loaders.Loader} + */ +Object.defineProperty(AppPrototype, 'loader', { + get: function get() { + if (!this._loader) { + var sharedLoader = this._options.sharedLoader; + + this._loader = sharedLoader ? shared : new _loader2.default(); + } + + return this._loader; + } +}); + +// Override the destroy function +// making sure to destroy the current Loader +AppPrototype._parentDestroy = AppPrototype.destroy; +AppPrototype.destroy = function destroy(removeView, stageOptions) { + if (this._loader) { + this._loader.destroy(); + this._loader = null; + } + this._parentDestroy(removeView, stageOptions); +}; + +},{"../core/Application":43,"./bitmapFontParser":161,"./loader":163,"./spritesheetParser":164,"./textureParser":165,"resource-loader":36}],163:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _resourceLoader = require('resource-loader'); + +var _resourceLoader2 = _interopRequireDefault(_resourceLoader); + +var _blob = require('resource-loader/lib/middlewares/parsing/blob'); + +var _eventemitter = require('eventemitter3'); + +var _eventemitter2 = _interopRequireDefault(_eventemitter); + +var _textureParser = require('./textureParser'); + +var _textureParser2 = _interopRequireDefault(_textureParser); + +var _spritesheetParser = require('./spritesheetParser'); + +var _spritesheetParser2 = _interopRequireDefault(_spritesheetParser); + +var _bitmapFontParser = require('./bitmapFontParser'); + +var _bitmapFontParser2 = _interopRequireDefault(_bitmapFontParser); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * + * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader + * + * ```js + * const loader = PIXI.loader; // PixiJS exposes a premade instance for you to use. + * //or + * const loader = new PIXI.loaders.Loader(); // you can also create your own if you want + * + * const sprites = {}; + * + * // Chainable `add` to enqueue a resource + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.add('scoreFont', 'assets/score.fnt'); + * + * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. + * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). + * loader.pre(cachingMiddleware); + * + * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. + * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). + * loader.use(parsingMiddleware); + * + * // The `load` method loads the queue of resources, and calls the passed in callback called once all + * // resources have loaded. + * loader.load((loader, resources) => { + * // resources is an object where the key is the name of the resource loaded and the value is the resource object. + * // They have a couple default properties: + * // - `url`: The URL that the resource was loaded from + * // - `error`: The error that happened when trying to load (if any) + * // - `data`: The raw data that was loaded + * // also may contain other properties based on the middleware that runs. + * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); + * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); + * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); + * }); + * + * // throughout the process multiple signals can be dispatched. + * loader.onProgress.add(() => {}); // called once per loaded/errored file + * loader.onError.add(() => {}); // called once per errored file + * loader.onLoad.add(() => {}); // called once per loaded file + * loader.onComplete.add(() => {}); // called once when the queued resources all load. + * ``` + * + * @see https://github.com/englercj/resource-loader + * + * @class + * @extends module:resource-loader.ResourceLoader + * @memberof PIXI.loaders + */ +var Loader = function (_ResourceLoader) { + _inherits(Loader, _ResourceLoader); + + /** + * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. + * @param {number} [concurrency=10] - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + _classCallCheck(this, Loader); + + var _this = _possibleConstructorReturn(this, _ResourceLoader.call(this, baseUrl, concurrency)); + + _eventemitter2.default.call(_this); + + for (var i = 0; i < Loader._pixiMiddleware.length; ++i) { + _this.use(Loader._pixiMiddleware[i]()); + } + + // Compat layer, translate the new v2 signals into old v1 events. + _this.onStart.add(function (l) { + return _this.emit('start', l); + }); + _this.onProgress.add(function (l, r) { + return _this.emit('progress', l, r); + }); + _this.onError.add(function (e, l, r) { + return _this.emit('error', e, l, r); + }); + _this.onLoad.add(function (l, r) { + return _this.emit('load', l, r); + }); + _this.onComplete.add(function (l, r) { + return _this.emit('complete', l, r); + }); + return _this; + } + + /** + * Adds a default middleware to the PixiJS loader. + * + * @static + * @param {Function} fn - The middleware to add. + */ + + + Loader.addPixiMiddleware = function addPixiMiddleware(fn) { + Loader._pixiMiddleware.push(fn); + }; + + /** + * Destroy the loader, removes references. + */ + + + Loader.prototype.destroy = function destroy() { + this.removeAllListeners(); + this.reset(); + }; + + return Loader; +}(_resourceLoader2.default); + +// Copy EE3 prototype (mixin) + + +exports.default = Loader; +for (var k in _eventemitter2.default.prototype) { + Loader.prototype[k] = _eventemitter2.default.prototype[k]; +} + +Loader._pixiMiddleware = [ +// parse any blob into more usable objects (e.g. Image) +_blob.blobMiddlewareFactory, +// parse any Image objects into textures +_textureParser2.default, +// parse any spritesheet data into multiple textures +_spritesheetParser2.default, +// parse bitmap font data into multiple textures +_bitmapFontParser2.default]; + +// Add custom extentions +var Resource = _resourceLoader2.default.Resource; + +Resource.setExtensionXhrType('fnt', Resource.XHR_RESPONSE_TYPE.DOCUMENT); + +},{"./bitmapFontParser":161,"./spritesheetParser":164,"./textureParser":165,"eventemitter3":3,"resource-loader":36,"resource-loader/lib/middlewares/parsing/blob":37}],164:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function spritesheetParser(resource, next) { + var imageResourceName = resource.name + '_image'; + + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data || resource.type !== _resourceLoader.Resource.TYPE.JSON || !resource.data.frames || this.resources[imageResourceName]) { + next(); + + return; + } + + var loadOptions = { + crossOrigin: resource.crossOrigin, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + + var resourcePath = getResourcePath(resource, this.baseUrl); + + // load the image for this sheet + this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + if (res.error) { + next(res.error); + + return; + } + + var spritesheet = new _core.Spritesheet(res.texture.baseTexture, resource.data, resource.url); + + spritesheet.parse(function () { + resource.spritesheet = spritesheet; + resource.textures = spritesheet.textures; + next(); + }); + }); + }; +}; + +exports.getResourcePath = getResourcePath; + +var _resourceLoader = require('resource-loader'); + +var _url = require('url'); + +var _url2 = _interopRequireDefault(_url); + +var _core = require('../core'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function getResourcePath(resource, baseUrl) { + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + return resource.data.meta.image; + } + + return _url2.default.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); +} + +},{"../core":65,"resource-loader":36,"url":38}],165:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +exports.default = function () { + return function textureParser(resource, next) { + // create a new texture if the data is an Image object + if (resource.data && resource.type === _resourceLoader.Resource.TYPE.IMAGE) { + resource.texture = _Texture2.default.fromLoader(resource.data, resource.url, resource.name); + } + next(); + }; +}; + +var _resourceLoader = require('resource-loader'); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"../core/textures/Texture":115,"resource-loader":36}],166:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _Texture = require('../core/textures/Texture'); + +var _Texture2 = _interopRequireDefault(_Texture); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var tempPoint = new core.Point(); +var tempPolygon = new core.Polygon(); + +/** + * Base mesh class + * @class + * @extends PIXI.Container + * @memberof PIXI.mesh + */ + +var Mesh = function (_core$Container) { + _inherits(Mesh, _core$Container); + + /** + * @param {PIXI.Texture} texture - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts + */ + function Mesh(texture, vertices, uvs, indices, drawMode) { + _classCallCheck(this, Mesh); + + /** + * The texture of the Mesh + * + * @member {PIXI.Texture} + * @default PIXI.Texture.EMPTY + * @private + */ + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + _this._texture = texture || _Texture2.default.EMPTY; + + /** + * The Uvs of the Mesh + * + * @member {Float32Array} + */ + _this.uvs = uvs || new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]); + + /** + * An array of vertices + * + * @member {Float32Array} + */ + _this.vertices = vertices || new Float32Array([0, 0, 100, 0, 100, 100, 0, 100]); + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + // TODO auto generate this based on draw mode! + _this.indices = indices || new Uint16Array([0, 1, 3, 2]); + + /** + * Version of mesh uvs are dirty or not + * + * @member {number} + */ + _this.dirty = 0; + + /** + * Version of mesh indices + * + * @member {number} + */ + _this.indexDirty = 0; + + /** + * Version of mesh verticies array + * + * @member {number} + */ + _this.vertexDirty = 0; + + /** + * For backwards compatibility the default is to re-upload verticies each render call. + * Set this to `false` and increase `vertexDirty` to manually re-upload the buffer. + * + * @member {boolean} + */ + _this.autoUpdate = true; + + /** + * The blend mode to be applied to the sprite. Set to `PIXI.BLEND_MODES.NORMAL` to remove + * any blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * Triangles in canvas mode are automatically antialiased, use this value to force triangles + * to overlap a bit with each other. + * + * @member {number} + */ + _this.canvasPadding = core.settings.MESH_CANVAS_PADDING; + + /** + * The way the Mesh should be drawn, can be any of the {@link PIXI.mesh.Mesh.DRAW_MODES} consts + * + * @member {number} + * @see PIXI.mesh.Mesh.DRAW_MODES + */ + _this.drawMode = drawMode || Mesh.DRAW_MODES.TRIANGLE_MESH; + + /** + * The default shader that is used if a mesh doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + _this.shader = null; + + /** + * The tint applied to the mesh. This is a [r,g,b] value. A value of [1,1,1] will remove any + * tint effect. + * + * @member {number} + */ + _this.tintRgb = new Float32Array([1, 1, 1]); + + /** + * A map of renderer IDs to webgl render data + * + * @private + * @member {object} + */ + _this._glDatas = {}; + + /** + * transform that is applied to UV to get the texture coords + * its updated independently from texture uvTransform + * updates of uvs are tied to that thing + * + * @member {PIXI.TextureMatrix} + * @private + */ + _this._uvTransform = new core.TextureMatrix(_this._texture); + + /** + * whether or not upload uvTransform to shader + * if its false, then uvs should be pre-multiplied + * if you change it for generated mesh, please call 'refresh(true)' + * @member {boolean} + * @default false + */ + _this.uploadUvTransform = false; + + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_renderWebGL' & '_renderCanvas' methods. + * @member {string} + * @default 'mesh' + */ + _this.pluginName = 'mesh'; + return _this; + } + + /** + * Renders the object using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - a reference to the WebGL renderer + */ + + + Mesh.prototype._renderWebGL = function _renderWebGL(renderer) { + this.refresh(); + renderer.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer. + */ + + + Mesh.prototype._renderCanvas = function _renderCanvas(renderer) { + this.refresh(); + renderer.plugins[this.pluginName].render(this); + }; + + /** + * When the texture is updated, this event will fire to update the scale and frame + * + * @private + */ + + + Mesh.prototype._onTextureUpdate = function _onTextureUpdate() { + this._uvTransform.texture = this._texture; + this.refresh(); + }; + + /** + * multiplies uvs only if uploadUvTransform is false + * call it after you change uvs manually + * make sure that texture is valid + */ + + + Mesh.prototype.multiplyUvs = function multiplyUvs() { + if (!this.uploadUvTransform) { + this._uvTransform.multiplyUvs(this.uvs); + } + }; + + /** + * Refreshes uvs for generated meshes (rope, plane) + * sometimes refreshes vertices too + * + * @param {boolean} [forceUpdate=false] if true, matrices will be updated any case + */ + + + Mesh.prototype.refresh = function refresh(forceUpdate) { + if (this.autoUpdate) { + this.vertexDirty++; + } + if (this._uvTransform.update(forceUpdate)) { + this._refresh(); + } + }; + + /** + * re-calculates mesh coords + * @protected + */ + + + Mesh.prototype._refresh = function _refresh() {} + /* empty */ + + + /** + * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * + */ + ; + + Mesh.prototype._calculateBounds = function _calculateBounds() { + // TODO - we can cache local bounds and use them if they are dirty (like graphics) + this._bounds.addVertices(this.transform, this.vertices, 0, this.vertices.length); + }; + + /** + * Tests if a point is inside this mesh. Works only for TRIANGLE_MESH + * + * @param {PIXI.Point} point - the point to test + * @return {boolean} the result of the test + */ + + + Mesh.prototype.containsPoint = function containsPoint(point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + + this.worldTransform.applyInverse(point, tempPoint); + + var vertices = this.vertices; + var points = tempPolygon.points; + var indices = this.indices; + var len = this.indices.length; + var step = this.drawMode === Mesh.DRAW_MODES.TRIANGLES ? 3 : 1; + + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + + return false; + }; + + /** + * The texture that the mesh uses. + * + * @member {PIXI.Texture} + */ + + + /** + * Destroys the Mesh object. + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + Mesh.prototype.destroy = function destroy(options) { + // for each webgl data entry, destroy the WebGLGraphicsData + for (var id in this._glDatas) { + var data = this._glDatas[id]; + + if (data.destroy) { + data.destroy(); + } else { + if (data.vertexBuffer) { + data.vertexBuffer.destroy(); + data.vertexBuffer = null; + } + if (data.indexBuffer) { + data.indexBuffer.destroy(); + data.indexBuffer = null; + } + if (data.uvBuffer) { + data.uvBuffer.destroy(); + data.uvBuffer = null; + } + if (data.vao) { + data.vao.destroy(); + data.vao = null; + } + } + } + + this._glDatas = null; + + _core$Container.prototype.destroy.call(this, options); + }; + + _createClass(Mesh, [{ + key: 'texture', + get: function get() { + return this._texture; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + if (this._texture === value) { + return; + } + + this._texture = value; + + if (value) { + // wait for the texture to load + if (value.baseTexture.hasLoaded) { + this._onTextureUpdate(); + } else { + value.once('update', this._onTextureUpdate, this); + } + } + } + + /** + * The tint applied to the mesh. This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @member {number} + * @default 0xFFFFFF + */ + + }, { + key: 'tint', + get: function get() { + return core.utils.rgb2hex(this.tintRgb); + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this.tintRgb = core.utils.hex2rgb(value, this.tintRgb); + } + }]); + + return Mesh; +}(core.Container); + +/** + * Different drawing buffer modes supported + * + * @static + * @constant + * @type {object} + * @property {number} TRIANGLE_MESH + * @property {number} TRIANGLES + */ + + +exports.default = Mesh; +Mesh.DRAW_MODES = { + TRIANGLE_MESH: 0, + TRIANGLES: 1 +}; + +},{"../core":65,"../core/textures/Texture":115}],167:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _Plane2 = require('./Plane'); + +var _Plane3 = _interopRequireDefault(_Plane2); + +var _CanvasTinter = require('../core/sprites/canvas/CanvasTinter'); + +var _CanvasTinter2 = _interopRequireDefault(_CanvasTinter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var DEFAULT_BORDER_SIZE = 10; + +/** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.fromImage('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
+ *      A                          B
+ *    +---+----------------------+---+
+ *  C | 1 |          2           | 3 |
+ *    +---+----------------------+---+
+ *    |   |                      |   |
+ *    | 4 |          5           | 6 |
+ *    |   |                      |   |
+ *    +---+----------------------+---+
+ *  D | 7 |          8           | 9 |
+ *    +---+----------------------+---+
+
+ *  When changing this objects width and/or height:
+ *     areas 1 3 7 and 9 will remain unscaled.
+ *     areas 2 and 8 will be stretched horizontally
+ *     areas 4 and 6 will be stretched vertically
+ *     area 5 will be stretched both horizontally and vertically
+ * 
+ * + * @class + * @extends PIXI.mesh.Plane + * @memberof PIXI.mesh + * + */ + +var NineSlicePlane = function (_Plane) { + _inherits(NineSlicePlane, _Plane); + + /** + * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. + * @param {int} [leftWidth=10] size of the left vertical bar (A) + * @param {int} [topHeight=10] size of the top horizontal bar (C) + * @param {int} [rightWidth=10] size of the right vertical bar (B) + * @param {int} [bottomHeight=10] size of the bottom horizontal bar (D) + */ + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + _classCallCheck(this, NineSlicePlane); + + var _this = _possibleConstructorReturn(this, _Plane.call(this, texture, 4, 4)); + + _this._origWidth = texture.orig.width; + _this._origHeight = texture.orig.height; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._width = _this._origWidth; + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._height = _this._origHeight; + + /** + * The width of the left column (a) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE; + + /** + * The width of the right column (b) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE; + + /** + * The height of the top row (c) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE; + + /** + * The height of the bottom row (d) + * + * @member {number} + * @memberof PIXI.NineSlicePlane# + * @override + */ + _this._bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE; + + /** + * Cached tint value so we can tell when the tint is changed. + * + * @member {number} + * @protected + */ + _this._cachedTint = 0xFFFFFF; + + /** + * Cached tinted texture. + * + * @member {HTMLCanvasElement} + * @protected + */ + _this._tintedTexture = null; + + /** + * Temporary storage for canvas source coords + * + * @member {number[]} + * @private + */ + _this._canvasUvs = null; + + _this.refresh(true); + return _this; + } + + /** + * Updates the horizontal vertices. + * + */ + + + NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices() { + var vertices = this.vertices; + + var h = this._topHeight + this._bottomHeight; + var scale = this._height > h ? 1.0 : this._height / h; + + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - this._bottomHeight * scale; + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + }; + + /** + * Updates the vertical vertices. + * + */ + + + NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices() { + var vertices = this.vertices; + + var w = this._leftWidth + this._rightWidth; + var scale = this._width > w ? 1.0 : this._width / w; + + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - this._rightWidth * scale; + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer to render with. + */ + + + NineSlicePlane.prototype._renderCanvas = function _renderCanvas(renderer) { + var context = renderer.context; + var transform = this.worldTransform; + var res = renderer.resolution; + var isTinted = this.tint !== 0xFFFFFF; + var texture = this._texture; + + // Work out tinting + if (isTinted) { + if (this._cachedTint !== this.tint) { + // Tint has changed, need to update the tinted texture and use that instead + + this._cachedTint = this.tint; + + this._tintedTexture = _CanvasTinter2.default.getTintedTexture(this, this.tint); + } + } + + var textureSource = !isTinted ? texture.baseTexture.source : this._tintedTexture; + + if (!this._canvasUvs) { + this._canvasUvs = [0, 0, 0, 0, 0, 0, 0, 0]; + } + + var vertices = this.vertices; + var uvs = this._canvasUvs; + var u0 = isTinted ? 0 : texture.frame.x; + var v0 = isTinted ? 0 : texture.frame.y; + var u1 = u0 + texture.frame.width; + var v1 = v0 + texture.frame.height; + + uvs[0] = u0; + uvs[1] = u0 + this._leftWidth; + uvs[2] = u1 - this._rightWidth; + uvs[3] = u1; + uvs[4] = v0; + uvs[5] = v0 + this._topHeight; + uvs[6] = v1 - this._bottomHeight; + uvs[7] = v1; + + for (var i = 0; i < 8; i++) { + uvs[i] *= texture.baseTexture.resolution; + } + + context.globalAlpha = this.worldAlpha; + renderer.setBlendMode(this.blendMode); + + if (renderer.roundPixels || this.roundPixels) { // #CUSTOM + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + for (var row = 0; row < 3; row++) { + for (var col = 0; col < 3; col++) { + var ind = col * 2 + row * 8; + var sw = Math.max(1, uvs[col + 1] - uvs[col]); + var sh = Math.max(1, uvs[row + 5] - uvs[row + 4]); + var dw = Math.max(1, vertices[ind + 10] - vertices[ind]); + var dh = Math.max(1, vertices[ind + 11] - vertices[ind + 1]); + + context.drawImage(textureSource, uvs[col], uvs[row + 4], sw, sh, vertices[ind], vertices[ind + 1], dw, dh); + } + } + }; + + /** + * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + + /** + * Refreshes NineSlicePlane coords. All of them. + */ + NineSlicePlane.prototype._refresh = function _refresh() { + _Plane.prototype._refresh.call(this); + + var uvs = this.uvs; + var texture = this._texture; + + this._origWidth = texture.orig.width; + this._origHeight = texture.orig.height; + + var _uvw = 1.0 / this._origWidth; + var _uvh = 1.0 / this._origHeight; + + uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; + uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - _uvw * this._rightWidth; + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - _uvh * this._bottomHeight; + + this.updateHorizontalVertices(); + this.updateVerticalVertices(); + + this.dirty++; + + this.multiplyUvs(); + }; + + _createClass(NineSlicePlane, [{ + key: 'width', + get: function get() { + return this._width; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._width = value; + this._refresh(); + } + + /** + * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane + * + * @member {number} + */ + + }, { + key: 'height', + get: function get() { + return this._height; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._height = value; + this._refresh(); + } + + /** + * The width of the left column + * + * @member {number} + */ + + }, { + key: 'leftWidth', + get: function get() { + return this._leftWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._leftWidth = value; + this._refresh(); + } + + /** + * The width of the right column + * + * @member {number} + */ + + }, { + key: 'rightWidth', + get: function get() { + return this._rightWidth; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._rightWidth = value; + this._refresh(); + } + + /** + * The height of the top row + * + * @member {number} + */ + + }, { + key: 'topHeight', + get: function get() { + return this._topHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._topHeight = value; + this._refresh(); + } + + /** + * The height of the bottom row + * + * @member {number} + */ + + }, { + key: 'bottomHeight', + get: function get() { + return this._bottomHeight; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._bottomHeight = value; + this._refresh(); + } + }]); + + return NineSlicePlane; +}(_Plane3.default); + +exports.default = NineSlicePlane; + +},{"../core/sprites/canvas/CanvasTinter":104,"./Plane":168}],168:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The Plane allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Plane = function (_Mesh) { + _inherits(Plane, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the Plane. + * @param {number} [verticesX=10] - The number of vertices in the x-axis + * @param {number} [verticesY=10] - The number of vertices in the y-axis + */ + function Plane(texture, verticesX, verticesY) { + _classCallCheck(this, Plane); + + /** + * Tracker for if the Plane is ready to be drawn. Needed because Mesh ctor can + * call _onTextureUpdated which could call refresh too early. + * + * @member {boolean} + * @private + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this._ready = true; + + _this.verticesX = verticesX || 10; + _this.verticesY = verticesY || 10; + + _this.drawMode = _Mesh3.default.DRAW_MODES.TRIANGLES; + _this.refresh(); + return _this; + } + + /** + * Refreshes plane coordinates + * + */ + + + Plane.prototype._refresh = function _refresh() { + var texture = this._texture; + var total = this.verticesX * this.verticesY; + var verts = []; + var colors = []; + var uvs = []; + var indices = []; + + var segmentsX = this.verticesX - 1; + var segmentsY = this.verticesY - 1; + + var sizeX = texture.width / segmentsX; + var sizeY = texture.height / segmentsY; + + for (var i = 0; i < total; i++) { + var x = i % this.verticesX; + var y = i / this.verticesX | 0; + + verts.push(x * sizeX, y * sizeY); + + uvs.push(x / segmentsX, y / segmentsY); + } + + // cons + + var totalSub = segmentsX * segmentsY; + + for (var _i = 0; _i < totalSub; _i++) { + var xpos = _i % segmentsX; + var ypos = _i / segmentsX | 0; + + var value = ypos * this.verticesX + xpos; + var value2 = ypos * this.verticesX + xpos + 1; + var value3 = (ypos + 1) * this.verticesX + xpos; + var value4 = (ypos + 1) * this.verticesX + xpos + 1; + + indices.push(value, value2, value3); + indices.push(value2, value4, value3); + } + + // console.log(indices) + this.vertices = new Float32Array(verts); + this.uvs = new Float32Array(uvs); + this.colors = new Float32Array(colors); + this.indices = new Uint16Array(indices); + + this.dirty++; + this.indexDirty++; + + this.multiplyUvs(); + }; + + /** + * Clear texture UVs when new texture is set + * + * @private + */ + + + Plane.prototype._onTextureUpdate = function _onTextureUpdate() { + _Mesh3.default.prototype._onTextureUpdate.call(this); + + // wait for the Plane ctor to finish before calling refresh + if (this._ready) { + this.refresh(); + } + }; + + return Plane; +}(_Mesh3.default); + +exports.default = Plane; + +},{"./Mesh":166}],169:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh2 = require('./Mesh'); + +var _Mesh3 = _interopRequireDefault(_Mesh2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The rope allows you to draw a texture across several points and them manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points); + * ``` + * + * @class + * @extends PIXI.mesh.Mesh + * @memberof PIXI.mesh + * + */ +var Rope = function (_Mesh) { + _inherits(Rope, _Mesh); + + /** + * @param {PIXI.Texture} texture - The texture to use on the rope. + * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. + */ + function Rope(texture, points) { + _classCallCheck(this, Rope); + + /** + * An array of points that determine the rope + * + * @member {PIXI.Point[]} + */ + var _this = _possibleConstructorReturn(this, _Mesh.call(this, texture)); + + _this.points = points; + + /** + * An array of vertices used to construct this rope. + * + * @member {Float32Array} + */ + _this.vertices = new Float32Array(points.length * 4); + + /** + * The WebGL Uvs of the rope. + * + * @member {Float32Array} + */ + _this.uvs = new Float32Array(points.length * 4); + + /** + * An array containing the color components + * + * @member {Float32Array} + */ + _this.colors = new Float32Array(points.length * 2); + + /** + * An array containing the indices of the vertices + * + * @member {Uint16Array} + */ + _this.indices = new Uint16Array(points.length * 2); + + /** + * refreshes vertices on every updateTransform + * @member {boolean} + * @default true + */ + _this.autoUpdate = true; + + _this.refresh(); + return _this; + } + + /** + * Refreshes + * + */ + + + Rope.prototype._refresh = function _refresh() { + var points = this.points; + + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1 || !this._texture._uvs) { + return; + } + + // if the number of points has changed we will need to recreate the arraybuffers + if (this.vertices.length / 4 !== points.length) { + this.vertices = new Float32Array(points.length * 4); + this.uvs = new Float32Array(points.length * 4); + this.colors = new Float32Array(points.length * 2); + this.indices = new Uint16Array(points.length * 2); + } + + var uvs = this.uvs; + + var indices = this.indices; + var colors = this.colors; + + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + + colors[0] = 1; + colors[1] = 1; + + indices[0] = 0; + indices[1] = 1; + + var total = points.length; + + for (var i = 1; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + var amount = i / (total - 1); + + uvs[index] = amount; + uvs[index + 1] = 0; + + uvs[index + 2] = amount; + uvs[index + 3] = 1; + + index = i * 2; + colors[index] = 1; + colors[index + 1] = 1; + + index = i * 2; + indices[index] = index; + indices[index + 1] = index + 1; + } + + // ensure that the changes are uploaded + this.dirty++; + this.indexDirty++; + + this.multiplyUvs(); + this.refreshVertices(); + }; + + /** + * refreshes vertices of Rope mesh + */ + + + Rope.prototype.refreshVertices = function refreshVertices() { + var points = this.points; + + if (points.length < 1) { + return; + } + + var lastPoint = points[0]; + var nextPoint = void 0; + var perpX = 0; + var perpY = 0; + + // this.count -= 0.2; + + var vertices = this.vertices; + var total = points.length; + + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } else { + nextPoint = point; + } + + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + + var ratio = (1 - i / (total - 1)) * 10; + + if (ratio > 1) { + ratio = 1; + } + + var perpLength = Math.sqrt(perpX * perpX + perpY * perpY); + var num = this._texture.height / 2; // (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; + + perpX /= perpLength; + perpY /= perpLength; + + perpX *= num; + perpY *= num; + + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + + lastPoint = point; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + Rope.prototype.updateTransform = function updateTransform() { + if (this.autoUpdate) { + this.refreshVertices(); + } + this.containerUpdateTransform(); + }; + + return Rope; +}(_Mesh3.default); + +exports.default = Rope; + +},{"./Mesh":166}],170:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * Renderer dedicated to meshes. + * + * @class + * @private + * @memberof PIXI + */ +var MeshSpriteRenderer = function () { + /** + * @param {PIXI.CanvasRenderer} renderer - The renderer this downport works for + */ + function MeshSpriteRenderer(renderer) { + _classCallCheck(this, MeshSpriteRenderer); + + this.renderer = renderer; + } + + /** + * Renders the Mesh + * + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var context = renderer.context; + + var transform = mesh.worldTransform; + var res = renderer.resolution; + + if (renderer.roundPixels || this.roundPixels) { // #CUSTOM + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res | 0, transform.ty * res | 0); + } else { + context.setTransform(transform.a * res, transform.b * res, transform.c * res, transform.d * res, transform.tx * res, transform.ty * res); + } + + renderer.context.globalAlpha = mesh.worldAlpha; + renderer.setBlendMode(mesh.blendMode); + + if (mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH) { + this._renderTriangleMesh(mesh); + } else { + this._renderTriangles(mesh); + } + }; + + /** + * Draws the object in Triangle Mesh mode + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the Mesh to render + */ + + + MeshSpriteRenderer.prototype._renderTriangleMesh = function _renderTriangleMesh(mesh) { + // draw triangles!! + var length = mesh.vertices.length / 2; + + for (var i = 0; i < length - 2; i++) { + // draw some triangles! + var index = i * 2; + + this._renderDrawTriangle(mesh, index, index + 2, index + 4); + } + }; + + /** + * Draws the object in triangle mode using canvas + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + */ + + + MeshSpriteRenderer.prototype._renderTriangles = function _renderTriangles(mesh) { + // draw triangles!! + var indices = mesh.indices; + var length = indices.length; + + for (var i = 0; i < length; i += 3) { + // draw some triangles! + var index0 = indices[i] * 2; + var index1 = indices[i + 1] * 2; + var index2 = indices[i + 2] * 2; + + this._renderDrawTriangle(mesh, index0, index1, index2); + } + }; + + /** + * Draws one of the triangles that from the Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - the current mesh + * @param {number} index0 - the index of the first vertex + * @param {number} index1 - the index of the second vertex + * @param {number} index2 - the index of the third vertex + */ + + + MeshSpriteRenderer.prototype._renderDrawTriangle = function _renderDrawTriangle(mesh, index0, index1, index2) { + var context = this.renderer.context; + var uvs = mesh.uvs; + var vertices = mesh.vertices; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var base = texture.baseTexture; + var textureSource = base.source; + var textureWidth = base.width; + var textureHeight = base.height; + + var u0 = void 0; + var u1 = void 0; + var u2 = void 0; + var v0 = void 0; + var v1 = void 0; + var v2 = void 0; + + if (mesh.uploadUvTransform) { + var ut = mesh._uvTransform.mapCoord; + + u0 = (uvs[index0] * ut.a + uvs[index0 + 1] * ut.c + ut.tx) * base.width; + u1 = (uvs[index1] * ut.a + uvs[index1 + 1] * ut.c + ut.tx) * base.width; + u2 = (uvs[index2] * ut.a + uvs[index2 + 1] * ut.c + ut.tx) * base.width; + v0 = (uvs[index0] * ut.b + uvs[index0 + 1] * ut.d + ut.ty) * base.height; + v1 = (uvs[index1] * ut.b + uvs[index1 + 1] * ut.d + ut.ty) * base.height; + v2 = (uvs[index2] * ut.b + uvs[index2 + 1] * ut.d + ut.ty) * base.height; + } else { + u0 = uvs[index0] * base.width; + u1 = uvs[index1] * base.width; + u2 = uvs[index2] * base.width; + v0 = uvs[index0 + 1] * base.height; + v1 = uvs[index1 + 1] * base.height; + v2 = uvs[index2 + 1] * base.height; + } + + var x0 = vertices[index0]; + var x1 = vertices[index1]; + var x2 = vertices[index2]; + var y0 = vertices[index0 + 1]; + var y1 = vertices[index1 + 1]; + var y2 = vertices[index2 + 1]; + + var canvasPadding = mesh.canvasPadding / this.renderer.resolution; + + if (canvasPadding > 0) { + var paddingX = canvasPadding / Math.abs(mesh.worldTransform.a); + var paddingY = canvasPadding / Math.abs(mesh.worldTransform.d); + var centerX = (x0 + x1 + x2) / 3; + var centerY = (y0 + y1 + y2) / 3; + + var normX = x0 - centerX; + var normY = y0 - centerY; + + var dist = Math.sqrt(normX * normX + normY * normY); + + x0 = centerX + normX / dist * (dist + paddingX); + y0 = centerY + normY / dist * (dist + paddingY); + + // + + normX = x1 - centerX; + normY = y1 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x1 = centerX + normX / dist * (dist + paddingX); + y1 = centerY + normY / dist * (dist + paddingY); + + normX = x2 - centerX; + normY = y2 - centerY; + + dist = Math.sqrt(normX * normX + normY * normY); + x2 = centerX + normX / dist * (dist + paddingX); + y2 = centerY + normY / dist * (dist + paddingY); + } + + context.save(); + context.beginPath(); + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + + context.closePath(); + + context.clip(); + + // Compute matrix transform + var delta = u0 * v1 + v0 * u2 + u1 * v2 - v1 * u2 - v0 * u1 - u0 * v2; + var deltaA = x0 * v1 + v0 * x2 + x1 * v2 - v1 * x2 - v0 * x1 - x0 * v2; + var deltaB = u0 * x1 + x0 * u2 + u1 * x2 - x1 * u2 - x0 * u1 - u0 * x2; + var deltaC = u0 * v1 * x2 + v0 * x1 * u2 + x0 * u1 * v2 - x0 * v1 * u2 - v0 * u1 * x2 - u0 * x1 * v2; + var deltaD = y0 * v1 + v0 * y2 + y1 * v2 - v1 * y2 - v0 * y1 - y0 * v2; + var deltaE = u0 * y1 + y0 * u2 + u1 * y2 - y1 * u2 - y0 * u1 - u0 * y2; + var deltaF = u0 * v1 * y2 + v0 * y1 * u2 + y0 * u1 * v2 - y0 * v1 * u2 - v0 * u1 * y2 - u0 * y1 * v2; + + context.transform(deltaA / delta, deltaD / delta, deltaB / delta, deltaE / delta, deltaC / delta, deltaF / delta); + + context.drawImage(textureSource, 0, 0, textureWidth * base.resolution, textureHeight * base.resolution, 0, 0, textureWidth, textureHeight); + + context.restore(); + this.renderer.invalidateBlendMode(); + }; + + /** + * Renders a flat Mesh + * + * @private + * @param {PIXI.mesh.Mesh} mesh - The Mesh to render + */ + + + MeshSpriteRenderer.prototype.renderMeshFlat = function renderMeshFlat(mesh) { + var context = this.renderer.context; + var vertices = mesh.vertices; + var length = vertices.length / 2; + + // this.count++; + + context.beginPath(); + + for (var i = 1; i < length - 2; ++i) { + // draw some triangles! + var index = i * 2; + + var x0 = vertices[index]; + var y0 = vertices[index + 1]; + + var x1 = vertices[index + 2]; + var y1 = vertices[index + 3]; + + var x2 = vertices[index + 4]; + var y2 = vertices[index + 5]; + + context.moveTo(x0, y0); + context.lineTo(x1, y1); + context.lineTo(x2, y2); + } + + context.fillStyle = '#FF0000'; + context.fill(); + context.closePath(); + }; + + /** + * destroy the the renderer. + * + */ + + + MeshSpriteRenderer.prototype.destroy = function destroy() { + this.renderer = null; + }; + + return MeshSpriteRenderer; +}(); + +exports.default = MeshSpriteRenderer; + + +core.CanvasRenderer.registerPlugin('mesh', MeshSpriteRenderer); + +},{"../../core":65,"../Mesh":166}],171:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Mesh = require('./Mesh'); + +Object.defineProperty(exports, 'Mesh', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Mesh).default; + } +}); + +var _MeshRenderer = require('./webgl/MeshRenderer'); + +Object.defineProperty(exports, 'MeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_MeshRenderer).default; + } +}); + +var _CanvasMeshRenderer = require('./canvas/CanvasMeshRenderer'); + +Object.defineProperty(exports, 'CanvasMeshRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasMeshRenderer).default; + } +}); + +var _Plane = require('./Plane'); + +Object.defineProperty(exports, 'Plane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Plane).default; + } +}); + +var _NineSlicePlane = require('./NineSlicePlane'); + +Object.defineProperty(exports, 'NineSlicePlane', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_NineSlicePlane).default; + } +}); + +var _Rope = require('./Rope'); + +Object.defineProperty(exports, 'Rope', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_Rope).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./Mesh":166,"./NineSlicePlane":167,"./Plane":168,"./Rope":169,"./canvas/CanvasMeshRenderer":170,"./webgl/MeshRenderer":172}],172:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _Mesh = require('../Mesh'); + +var _Mesh2 = _interopRequireDefault(_Mesh); + +var _path = require('path'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var matrixIdentity = core.Matrix.IDENTITY; + +/** + * WebGL renderer plugin for tiling sprites + * + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + +var MeshRenderer = function (_core$ObjectRenderer) { + _inherits(MeshRenderer, _core$ObjectRenderer); + + /** + * constructor for renderer + * + * @param {WebGLRenderer} renderer The renderer this tiling awesomeness works for. + */ + function MeshRenderer(renderer) { + _classCallCheck(this, MeshRenderer); + + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + return _this; + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + MeshRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.shader = new core.Shader(gl, 'attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n', 'varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n'); + }; + + /** + * renders mesh + * + * @param {PIXI.mesh.Mesh} mesh mesh instance + */ + + + MeshRenderer.prototype.render = function render(mesh) { + var renderer = this.renderer; + var gl = renderer.gl; + var texture = mesh._texture; + + if (!texture.valid) { + return; + } + + var glData = mesh._glDatas[renderer.CONTEXT_UID]; + + if (!glData) { + renderer.bindVao(null); + + glData = { + shader: this.shader, + vertexBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.vertices, gl.STREAM_DRAW), + uvBuffer: _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, mesh.uvs, gl.STREAM_DRAW), + indexBuffer: _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, mesh.indices, gl.STATIC_DRAW), + // build the vao object that will render.. + vao: null, + dirty: mesh.dirty, + indexDirty: mesh.indexDirty, + vertexDirty: mesh.vertexDirty + }; + + // build the vao object that will render.. + glData.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(glData.indexBuffer).addAttribute(glData.vertexBuffer, glData.shader.attributes.aVertexPosition, gl.FLOAT, false, 2 * 4, 0).addAttribute(glData.uvBuffer, glData.shader.attributes.aTextureCoord, gl.FLOAT, false, 2 * 4, 0); + + mesh._glDatas[renderer.CONTEXT_UID] = glData; + } + + renderer.bindVao(glData.vao); + + if (mesh.dirty !== glData.dirty) { + glData.dirty = mesh.dirty; + glData.uvBuffer.upload(mesh.uvs); + } + + if (mesh.indexDirty !== glData.indexDirty) { + glData.indexDirty = mesh.indexDirty; + glData.indexBuffer.upload(mesh.indices); + } + + if (mesh.vertexDirty !== glData.vertexDirty) { + glData.vertexDirty = mesh.vertexDirty; + glData.vertexBuffer.upload(mesh.vertices); + } + + renderer.bindShader(glData.shader); + + glData.shader.uniforms.uSampler = renderer.bindTexture(texture); + + renderer.state.setBlendMode(core.utils.correctBlendMode(mesh.blendMode, texture.baseTexture.premultipliedAlpha)); + + if (glData.shader.uniforms.uTransform) { + if (mesh.uploadUvTransform) { + glData.shader.uniforms.uTransform = mesh._uvTransform.mapCoord.toArray(true); + } else { + glData.shader.uniforms.uTransform = matrixIdentity.toArray(true); + } + } + glData.shader.uniforms.translationMatrix = mesh.worldTransform.toArray(true); + + glData.shader.uniforms.uColor = core.utils.premultiplyRgba(mesh.tintRgb, mesh.worldAlpha, glData.shader.uniforms.uColor, texture.baseTexture.premultipliedAlpha); + + var drawMode = mesh.drawMode === _Mesh2.default.DRAW_MODES.TRIANGLE_MESH ? gl.TRIANGLE_STRIP : gl.TRIANGLES; + + glData.vao.draw(drawMode, mesh.indices.length, 0); + }; + + return MeshRenderer; +}(core.ObjectRenderer); + +exports.default = MeshRenderer; + + +core.WebGLRenderer.registerPlugin('mesh', MeshRenderer); + +},{"../../core":65,"../Mesh":166,"path":8,"pixi-gl-core":15}],173:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _utils = require('../core/utils'); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. The tradeoff of the ParticleContainer is that most advanced + * functionality will not work. ParticleContainer implements the basic object transform (position, scale, rotation) + * and some advanced functionality like tint (as of v4.5.6). + * Other more advanced functionality like masking, children, filters, etc will not work on sprites in this batch. + * + * It's extremely easy to use : + * + * ```js + * let container = new ParticleContainer(); + * + * for (let i = 0; i < 100; ++i) + * { + * let sprite = new PIXI.Sprite.fromImage("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be rendered at the speed of light. + * + * @class + * @extends PIXI.Container + * @memberof PIXI.particles + */ +var ParticleContainer = function (_core$Container) { + _inherits(ParticleContainer, _core$Container); + + /** + * @param {number} [maxSize=1500] - The maximum number of particles that can be rendered by the container. + * Affects size of allocated buffers. + * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.vertices=false] - When true, vertices be uploaded and applied. + * if sprite's ` scale/anchor/trim/frame/orig` is dynamic, please set `true`. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.tint=false] - When true, alpha and tint be uploaded and applied. + * @param {number} [batchSize=16384] - Number of particles per batch. If less than maxSize, it uses maxSize instead. + * @param {boolean} [autoResize=false] If true, container allocates more batches in case + * there are more than `maxSize` particles. + */ + function ParticleContainer() { + var maxSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1500; + var properties = arguments[1]; + var batchSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 16384; + var autoResize = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + + _classCallCheck(this, ParticleContainer); + + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var _this = _possibleConstructorReturn(this, _core$Container.call(this)); + + var maxBatchSize = 16384; + + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + + if (batchSize > maxSize) { + batchSize = maxSize; + } + + /** + * Set properties to be dynamic (true) / static (false) + * + * @member {boolean[]} + * @private + */ + _this._properties = [false, true, false, false, false]; + + /** + * @member {number} + * @private + */ + _this._maxSize = maxSize; + + /** + * @member {number} + * @private + */ + _this._batchSize = batchSize; + + /** + * @member {object} + * @private + */ + _this._glBuffers = {}; + + /** + * for every batch stores _updateID corresponding to the last change in that batch + * @member {number[]} + * @private + */ + _this._bufferUpdateIDs = []; + + /** + * when child inserted, removed or changes position this number goes up + * @member {number[]} + * @private + */ + _this._updateID = 0; + + /** + * @member {boolean} + * + */ + _this.interactiveChildren = false; + + /** + * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` + * to reset the blend mode. + * + * @member {number} + * @default PIXI.BLEND_MODES.NORMAL + * @see PIXI.BLEND_MODES + */ + _this.blendMode = core.BLEND_MODES.NORMAL; + + /** + * If true, container allocates more batches in case there are more than `maxSize` particles. + * @member {boolean} + * @default false + */ + _this.autoResize = autoResize; + + /** + * Used for canvas renderering. If true then the elements will be positioned at the + * nearest pixel. This provides a nice speed boost. + * + * @member {boolean} + * @default true; + */ + _this.roundPixels = true; + + /** + * The texture used to render the children. + * + * @readonly + * @member {BaseTexture} + */ + _this.baseTexture = null; + + _this.setProperties(properties); + + /** + * The tint applied to the container. + * This is a hex value. A value of 0xFFFFFF will remove any tint effect. + * + * @private + * @member {number} + * @default 0xFFFFFF + */ + _this._tint = 0; + _this.tintRgb = new Float32Array(4); + _this.tint = 0xFFFFFF; + return _this; + } + + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * + * @param {object} properties - The properties to be uploaded + */ + + + ParticleContainer.prototype.setProperties = function setProperties(properties) { + if (properties) { + this._properties[0] = 'vertices' in properties || 'scale' in properties ? !!properties.vertices || !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'tint' in properties || 'alpha' in properties ? !!properties.tint || !!properties.alpha : this._properties[4]; + } + }; + + /** + * Updates the object transform for rendering + * + * @private + */ + + + ParticleContainer.prototype.updateTransform = function updateTransform() { + // TODO don't need to! + this.displayObjectUpdateTransform(); + // PIXI.Container.prototype.updateTransform.call( this ); + }; + + /** + * The tint applied to the container. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + ** IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. + * @member {number} + * @default 0xFFFFFF + */ + + + /** + * Renders the container using the WebGL renderer + * + * @private + * @param {PIXI.WebGLRenderer} renderer - The webgl renderer + */ + ParticleContainer.prototype.renderWebGL = function renderWebGL(renderer) { + var _this2 = this; + + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.hasLoaded) { + this.baseTexture.once('update', function () { + return _this2.onChildrenChange(0); + }); + } + } + + renderer.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + + /** + * Set the flag that static data should be updated to true + * + * @private + * @param {number} smallestChildIndex - The smallest child index + */ + + + ParticleContainer.prototype.onChildrenChange = function onChildrenChange(smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + + while (this._bufferUpdateIDs.length < bufferIndex) { + this._bufferUpdateIDs.push(0); + } + this._bufferUpdateIDs[bufferIndex] = ++this._updateID; + }; + + /** + * Renders the object using the Canvas renderer + * + * @private + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + + + ParticleContainer.prototype.renderCanvas = function renderCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + + var context = renderer.context; + var transform = this.worldTransform; + var isRotated = true; + + var positionX = 0; + var positionY = 0; + + var finalWidth = 0; + var finalHeight = 0; + + renderer.setBlendMode(this.blendMode); + + context.globalAlpha = this.worldAlpha; + + this.displayObjectUpdateTransform(); + + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i]; + + if (!child.visible) { + continue; + } + + var frame = child._texture.frame; + + context.globalAlpha = this.worldAlpha * child.alpha; + + if (child.rotation % (Math.PI * 2) === 0) { + // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call + if (isRotated) { + context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx * renderer.resolution, transform.ty * renderer.resolution); + + isRotated = false; + } + + positionX = child.anchor.x * (-frame.width * child.scale.x) + child.position.x + 0.5; + positionY = child.anchor.y * (-frame.height * child.scale.y) + child.position.y + 0.5; + + finalWidth = frame.width * child.scale.x; + finalHeight = frame.height * child.scale.y; + } else { + if (!isRotated) { + isRotated = true; + } + + child.displayObjectUpdateTransform(); + + var childTransform = child.worldTransform; + + if (renderer.roundPixels || this.roundPixels) { // #CUSTOM + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution | 0, childTransform.ty * renderer.resolution | 0); + } else { + context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, childTransform.tx * renderer.resolution, childTransform.ty * renderer.resolution); + } + + positionX = child.anchor.x * -frame.width + 0.5; + positionY = child.anchor.y * -frame.height + 0.5; + + finalWidth = frame.width; + finalHeight = frame.height; + } + + var resolution = child._texture.baseTexture.resolution; + + context.drawImage(child._texture.baseTexture.source, frame.x * resolution, frame.y * resolution, frame.width * resolution, frame.height * resolution, positionX * renderer.resolution, positionY * renderer.resolution, finalWidth * renderer.resolution, finalHeight * renderer.resolution); + } + }; + + /** + * Destroys the container + * + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + + + ParticleContainer.prototype.destroy = function destroy(options) { + _core$Container.prototype.destroy.call(this, options); + + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + } + + this._properties = null; + this._buffers = null; + this._bufferUpdateIDs = null; + }; + + _createClass(ParticleContainer, [{ + key: 'tint', + get: function get() { + return this._tint; + }, + set: function set(value) // eslint-disable-line require-jsdoc + { + this._tint = value; + (0, _utils.hex2rgb)(value, this.tintRgb); + } + }]); + + return ParticleContainer; +}(core.Container); + +exports.default = ParticleContainer; + +},{"../core":65,"../core/utils":125}],174:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _ParticleContainer = require('./ParticleContainer'); + +Object.defineProperty(exports, 'ParticleContainer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleContainer).default; + } +}); + +var _ParticleRenderer = require('./webgl/ParticleRenderer'); + +Object.defineProperty(exports, 'ParticleRenderer', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_ParticleRenderer).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./ParticleContainer":173,"./webgl/ParticleRenderer":176}],175:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _pixiGlCore = require('pixi-gl-core'); + +var _pixiGlCore2 = _interopRequireDefault(_pixiGlCore); + +var _createIndicesForQuads = require('../../core/utils/createIndicesForQuads'); + +var _createIndicesForQuads2 = _interopRequireDefault(_createIndicesForQuads); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + +/** + * The particle buffer manages the static and dynamic buffers for a particle container. + * + * @class + * @private + * @memberof PIXI + */ +var ParticleBuffer = function () { + /** + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(gl, properties, dynamicPropertyFlags, size) { + _classCallCheck(this, ParticleBuffer); + + /** + * The current WebGL drawing context. + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + + /** + * The number of particles the buffer can hold + * + * @member {number} + */ + this.size = size; + + /** + * A list of the properties that are dynamic. + * + * @member {object[]} + */ + this.dynamicProperties = []; + + /** + * A list of the properties that are static. + * + * @member {object[]} + */ + this.staticProperties = []; + + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attribute: property.attribute, + size: property.size, + uploadFunction: property.uploadFunction, + unsignedByte: property.unsignedByte, + offset: property.offset + }; + + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } else { + this.staticProperties.push(property); + } + } + + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + + this._updateID = 0; + + this.initBuffers(); + } + + /** + * Sets up the renderer context and necessary buffers. + * + * @private + */ + + + ParticleBuffer.prototype.initBuffers = function initBuffers() { + var gl = this.gl; + var dynamicOffset = 0; + + /** + * Holds the indices of the geometry (quads) to draw + * + * @member {Uint16Array} + */ + this.indices = (0, _createIndicesForQuads2.default)(this.size); + this.indexBuffer = _pixiGlCore2.default.GLBuffer.createIndexBuffer(gl, this.indices, gl.STATIC_DRAW); + + this.dynamicStride = 0; + + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + + var dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4); + + this.dynamicData = new Float32Array(dynBuffer); + this.dynamicDataUint32 = new Uint32Array(dynBuffer); + this.dynamicBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, dynBuffer, gl.STREAM_DRAW); + + // static // + var staticOffset = 0; + + this.staticStride = 0; + + for (var _i = 0; _i < this.staticProperties.length; ++_i) { + var _property = this.staticProperties[_i]; + + _property.offset = staticOffset; + staticOffset += _property.size; + this.staticStride += _property.size; + } + + var statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4); + + this.staticData = new Float32Array(statBuffer); + this.staticDataUint32 = new Uint32Array(statBuffer); + this.staticBuffer = _pixiGlCore2.default.GLBuffer.createVertexBuffer(gl, statBuffer, gl.STATIC_DRAW); + + this.vao = new _pixiGlCore2.default.VertexArrayObject(gl).addIndex(this.indexBuffer); + + for (var _i2 = 0; _i2 < this.dynamicProperties.length; ++_i2) { + var _property2 = this.dynamicProperties[_i2]; + + if (_property2.unsignedByte) { + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.UNSIGNED_BYTE, true, this.dynamicStride * 4, _property2.offset * 4); + } else { + this.vao.addAttribute(this.dynamicBuffer, _property2.attribute, gl.FLOAT, false, this.dynamicStride * 4, _property2.offset * 4); + } + } + + for (var _i3 = 0; _i3 < this.staticProperties.length; ++_i3) { + var _property3 = this.staticProperties[_i3]; + + if (_property3.unsignedByte) { + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.UNSIGNED_BYTE, true, this.staticStride * 4, _property3.offset * 4); + } else { + this.vao.addAttribute(this.staticBuffer, _property3.attribute, gl.FLOAT, false, this.staticStride * 4, _property3.offset * 4); + } + } + }; + + /** + * Uploads the dynamic properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadDynamic = function uploadDynamic(children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + + property.uploadFunction(children, startIndex, amount, property.unsignedByte ? this.dynamicDataUint32 : this.dynamicData, this.dynamicStride, property.offset); + } + + this.dynamicBuffer.upload(); + }; + + /** + * Uploads the static properties. + * + * @param {PIXI.DisplayObject[]} children - The children to upload. + * @param {number} startIndex - The index to start at. + * @param {number} amount - The number to upload. + */ + + + ParticleBuffer.prototype.uploadStatic = function uploadStatic(children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + + property.uploadFunction(children, startIndex, amount, property.unsignedByte ? this.staticDataUint32 : this.staticData, this.staticStride, property.offset); + } + + this.staticBuffer.upload(); + }; + + /** + * Destroys the ParticleBuffer. + * + */ + + + ParticleBuffer.prototype.destroy = function destroy() { + this.dynamicProperties = null; + this.dynamicBuffer.destroy(); + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + + this.staticProperties = null; + this.staticBuffer.destroy(); + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + }; + + return ParticleBuffer; +}(); + +exports.default = ParticleBuffer; + +},{"../../core/utils/createIndicesForQuads":123,"pixi-gl-core":15}],176:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _ParticleShader = require('./ParticleShader'); + +var _ParticleShader2 = _interopRequireDefault(_ParticleShader); + +var _ParticleBuffer = require('./ParticleBuffer'); + +var _ParticleBuffer2 = _interopRequireDefault(_ParticleBuffer); + +var _utils = require('../../core/utils'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + +/** + * + * @class + * @private + * @memberof PIXI + */ +var ParticleRenderer = function (_core$ObjectRenderer) { + _inherits(ParticleRenderer, _core$ObjectRenderer); + + /** + * @param {PIXI.WebGLRenderer} renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + _classCallCheck(this, ParticleRenderer); + + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; + + /** + * The default shader that is used if a sprite doesn't have a more specific one. + * + * @member {PIXI.Shader} + */ + var _this = _possibleConstructorReturn(this, _core$ObjectRenderer.call(this, renderer)); + + _this.shader = null; + + _this.indexBuffer = null; + + _this.properties = null; + + _this.tempMatrix = new core.Matrix(); + + _this.CONTEXT_UID = 0; + return _this; + } + + /** + * When there is a WebGL context change + * + * @private + */ + + + ParticleRenderer.prototype.onContextChange = function onContextChange() { + var gl = this.renderer.gl; + + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + + // setup default shader + this.shader = new _ParticleShader2.default(gl); + + this.properties = [ + // verticesData + { + attribute: this.shader.attributes.aVertexPosition, + size: 2, + uploadFunction: this.uploadVertices, + offset: 0 + }, + // positionData + { + attribute: this.shader.attributes.aPositionCoord, + size: 2, + uploadFunction: this.uploadPosition, + offset: 0 + }, + // rotationData + { + attribute: this.shader.attributes.aRotation, + size: 1, + uploadFunction: this.uploadRotation, + offset: 0 + }, + // uvsData + { + attribute: this.shader.attributes.aTextureCoord, + size: 2, + uploadFunction: this.uploadUvs, + offset: 0 + }, + // tintData + { + attribute: this.shader.attributes.aColor, + size: 1, + unsignedByte: true, + uploadFunction: this.uploadTint, + offset: 0 + }]; + }; + + /** + * Starts a new particle batch. + * + */ + + + ParticleRenderer.prototype.start = function start() { + this.renderer.bindShader(this.shader); + }; + + /** + * Renders the particle container object. + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + */ + + + ParticleRenderer.prototype.render = function render(container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var renderer = this.renderer; + var totalChildren = children.length; + + if (totalChildren === 0) { + return; + } else if (totalChildren > maxSize) { + totalChildren = maxSize; + } + + var buffers = container._glBuffers[renderer.CONTEXT_UID]; + + if (!buffers) { + buffers = container._glBuffers[renderer.CONTEXT_UID] = this.generateBuffers(container); + } + + var baseTexture = children[0]._texture.baseTexture; + + // if the uvs have not updated then no point rendering just yet! + this.renderer.setBlendMode(core.utils.correctBlendMode(container.blendMode, baseTexture.premultipliedAlpha)); + + var gl = renderer.gl; + + var m = container.worldTransform.copy(this.tempMatrix); + + m.prepend(renderer._activeRenderTarget.projectionMatrix); + + this.shader.uniforms.projectionMatrix = m.toArray(true); + + this.shader.uniforms.uColor = core.utils.premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, baseTexture.premultipliedAlpha); + + // make sure the texture is bound.. + this.shader.uniforms.uSampler = renderer.bindTexture(baseTexture); + + var updateStatic = false; + + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = totalChildren - i; + + if (amount > batchSize) { + amount = batchSize; + } + + if (j >= buffers.length) { + if (!container.autoResize) { + break; + } + buffers.push(this._generateOneMoreBuffer(container)); + } + + var buffer = buffers[j]; + + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + + var bid = container._bufferUpdateIDs[j] || 0; + + updateStatic = updateStatic || buffer._updateID < bid; + // we only upload the static content when we have to! + if (updateStatic) { + buffer._updateID = container._updateID; + buffer.uploadStatic(children, i, amount); + } + + // bind the buffer + renderer.bindVao(buffer.vao); + buffer.vao.draw(gl.TRIANGLES, amount * 6); + } + }; + + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer[]} The buffers + */ + + + ParticleRenderer.prototype.generateBuffers = function generateBuffers(container) { + var gl = this.renderer.gl; + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + for (var i = 0; i < size; i += batchSize) { + buffers.push(new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize)); + } + + return buffers; + }; + + /** + * Creates one more particle buffer, because container has autoResize feature + * + * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer + * @return {PIXI.ParticleBuffer} generated buffer + * @private + */ + + + ParticleRenderer.prototype._generateOneMoreBuffer = function _generateOneMoreBuffer(container) { + var gl = this.renderer.gl; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + + return new _ParticleBuffer2.default(gl, this.properties, dynamicPropertyFlags, batchSize); + }; + + /** + * Uploads the verticies. + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their vertices uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadVertices = function uploadVertices(children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - sprite.anchor.x * orig.width; + w0 = w1 + trim.width; + + h1 = trim.y - sprite.anchor.y * orig.height; + h0 = h1 + trim.height; + } else { + w0 = orig.width * (1 - sprite.anchor.x); + w1 = orig.width * -sprite.anchor.x; + + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + + array[offset + stride * 2] = w0 * sx; + array[offset + stride * 2 + 1] = h0 * sy; + + array[offset + stride * 3] = w1 * sx; + array[offset + stride * 3 + 1] = h0 * sy; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their positions uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadPosition = function uploadPosition(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + + array[offset + stride * 2] = spritePosition.x; + array[offset + stride * 2 + 1] = spritePosition.y; + + array[offset + stride * 3] = spritePosition.x; + array[offset + stride * 3 + 1] = spritePosition.y; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadRotation = function uploadRotation(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + stride * 2] = spriteRotation; + array[offset + stride * 3] = spriteRotation; + + offset += stride * 4; + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadUvs = function uploadUvs(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + + array[offset + stride * 2] = textureUvs.x2; + array[offset + stride * 2 + 1] = textureUvs.y2; + + array[offset + stride * 3] = textureUvs.x3; + array[offset + stride * 3 + 1] = textureUvs.y3; + + offset += stride * 4; + } else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + + array[offset + stride * 2] = 0; + array[offset + stride * 2 + 1] = 0; + + array[offset + stride * 3] = 0; + array[offset + stride * 3 + 1] = 0; + + offset += stride * 4; + } + } + }; + + /** + * + * @param {PIXI.DisplayObject[]} children - the array of display objects to render + * @param {number} startIndex - the index to start from in the children array + * @param {number} amount - the amount of children that will have their rotation uploaded + * @param {number[]} array - The vertices to upload. + * @param {number} stride - Stride to use for iteration. + * @param {number} offset - Offset to start at. + */ + + + ParticleRenderer.prototype.uploadTint = function uploadTint(children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var premultiplied = sprite._texture.baseTexture.premultipliedAlpha; + var alpha = sprite.alpha; + // we dont call extra function if alpha is 1.0, that's faster + var argb = alpha < 1.0 && premultiplied ? (0, _utils.premultiplyTint)(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); + + array[offset] = argb; + array[offset + stride] = argb; + array[offset + stride * 2] = argb; + array[offset + stride * 3] = argb; + + offset += stride * 4; + } + }; + + /** + * Destroys the ParticleRenderer. + * + */ + + + ParticleRenderer.prototype.destroy = function destroy() { + if (this.renderer.gl) { + this.renderer.gl.deleteBuffer(this.indexBuffer); + } + + _core$ObjectRenderer.prototype.destroy.call(this); + + this.shader.destroy(); + + this.indices = null; + this.tempMatrix = null; + }; + + return ParticleRenderer; +}(core.ObjectRenderer); + +exports.default = ParticleRenderer; + + +core.WebGLRenderer.registerPlugin('particle', ParticleRenderer); + +},{"../../core":65,"../../core/utils":125,"./ParticleBuffer":175,"./ParticleShader":177}],177:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _Shader2 = require('../../core/Shader'); + +var _Shader3 = _interopRequireDefault(_Shader2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * @class + * @extends PIXI.Shader + * @memberof PIXI + */ +var ParticleShader = function (_Shader) { + _inherits(ParticleShader, _Shader); + + /** + * @param {PIXI.Shader} gl - The webgl shader manager this shader works for. + */ + function ParticleShader(gl) { + _classCallCheck(this, ParticleShader); + + return _possibleConstructorReturn(this, _Shader.call(this, gl, + // vertex shader + ['attribute vec2 aVertexPosition;', 'attribute vec2 aTextureCoord;', 'attribute vec4 aColor;', 'attribute vec2 aPositionCoord;', 'attribute float aRotation;', 'uniform mat3 projectionMatrix;', 'uniform vec4 uColor;', 'varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'void main(void){', ' float x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);', ' float y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);', ' vec2 v = vec2(x, y);', ' v = v + aPositionCoord;', ' gl_Position = vec4((projectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);', ' vTextureCoord = aTextureCoord;', ' vColor = aColor * uColor;', '}'].join('\n'), + // hello + ['varying vec2 vTextureCoord;', 'varying vec4 vColor;', 'uniform sampler2D uSampler;', 'void main(void){', ' vec4 color = texture2D(uSampler, vTextureCoord) * vColor;', ' gl_FragColor = color;', '}'].join('\n'))); + } + + return ParticleShader; +}(_Shader3.default); + +exports.default = ParticleShader; + +},{"../../core/Shader":44}],178:[function(require,module,exports){ +"use strict"; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + +if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + + if (x === 0 || isNaN(x)) { + return x; + } + + return x > 0 ? 1 : -1; + }; +} + +},{}],179:[function(require,module,exports){ +'use strict'; + +// References: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger + +if (!Number.isInteger) { + Number.isInteger = function numberIsInteger(value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; + }; +} + +},{}],180:[function(require,module,exports){ +'use strict'; + +var _objectAssign = require('object-assign'); + +var _objectAssign2 = _interopRequireDefault(_objectAssign); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +if (!Object.assign) { + Object.assign = _objectAssign2.default; +} // References: +// https://github.com/sindresorhus/object-assign +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + +},{"object-assign":6}],181:[function(require,module,exports){ +'use strict'; + +require('./Object.assign'); + +require('./requestAnimationFrame'); + +require('./Math.sign'); + +require('./Number.isInteger'); + +if (!window.ArrayBuffer) { + window.ArrayBuffer = Array; +} + +if (!window.Float32Array) { + window.Float32Array = Array; +} + +if (!window.Uint32Array) { + window.Uint32Array = Array; +} + +if (!window.Uint16Array) { + window.Uint16Array = Array; +} + +},{"./Math.sign":178,"./Number.isInteger":179,"./Object.assign":180,"./requestAnimationFrame":182}],182:[function(require,module,exports){ +(function (global){ +'use strict'; + +// References: +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// https://gist.github.com/1579671 +// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision +// https://gist.github.com/timhall/4078614 +// https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + +// Expected to be used with Browserfiy +// Browserify automatically detects the use of `global` and passes the +// correct reference of `global`, `self`, and finally `window` + +var ONE_FRAME_TIME = 16; + +// Date.now +if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; +} + +// performance.now +if (!(global.performance && global.performance.now)) { + var startTime = Date.now(); + + if (!global.performance) { + global.performance = {}; + } + + global.performance.now = function () { + return Date.now() - startTime; + }; +} + +// requestAnimationFrame +var lastTime = Date.now(); +var vendors = ['ms', 'moz', 'webkit', 'o']; + +for (var x = 0; x < vendors.length && !global.requestAnimationFrame; ++x) { + var p = vendors[x]; + + global.requestAnimationFrame = global[p + 'RequestAnimationFrame']; + global.cancelAnimationFrame = global[p + 'CancelAnimationFrame'] || global[p + 'CancelRequestAnimationFrame']; +} + +if (!global.requestAnimationFrame) { + global.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + 'is not a function'); + } + + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + + if (delay < 0) { + delay = 0; + } + + lastTime = currentTime; + + return setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; +} + +if (!global.cancelAnimationFrame) { + global.cancelAnimationFrame = function (id) { + return clearTimeout(id); + }; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],183:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../core'); + +var core = _interopRequireWildcard(_core); + +var _CountLimiter = require('./limiters/CountLimiter'); + +var _CountLimiter2 = _interopRequireDefault(_CountLimiter); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var SharedTicker = core.ticker.shared; + +/** + * Default number of uploads per frame using prepare plugin. + * + * @static + * @memberof PIXI.settings + * @name UPLOADS_PER_FRAME + * @type {number} + * @default 4 + */ +core.settings.UPLOADS_PER_FRAME = 4; + +/** + * The prepare manager provides functionality to upload content to the GPU. BasePrepare handles + * basic queuing functionality and is extended by {@link PIXI.prepare.WebGLPrepare} and {@link PIXI.prepare.CanvasPrepare} + * to provide preparation capabilities specific to their respective renderers. + * + * @example + * // Create a sprite + * const sprite = new PIXI.Sprite.fromImage('something.png'); + * + * // Load object into GPU + * app.renderer.plugins.prepare.upload(sprite, () => { + * + * //Texture(s) has been uploaded to GPU + * app.stage.addChild(sprite); + * + * }) + * + * @abstract + * @class + * @memberof PIXI.prepare + */ + +var BasePrepare = function () { + /** + * @param {PIXI.SystemRenderer} renderer - A reference to the current renderer + */ + function BasePrepare(renderer) { + var _this = this; + + _classCallCheck(this, BasePrepare); + + /** + * The limiter to be used to control how quickly items are prepared. + * @type {PIXI.prepare.CountLimiter|PIXI.prepare.TimeLimiter} + */ + this.limiter = new _CountLimiter2.default(core.settings.UPLOADS_PER_FRAME); + + /** + * Reference to the renderer. + * @type {PIXI.SystemRenderer} + * @protected + */ + this.renderer = renderer; + + /** + * The only real difference between CanvasPrepare and WebGLPrepare is what they pass + * to upload hooks. That different parameter is stored here. + * @type {PIXI.prepare.CanvasPrepare|PIXI.WebGLRenderer} + * @protected + */ + this.uploadHookHelper = null; + + /** + * Collection of items to uploads at once. + * @type {Array<*>} + * @private + */ + this.queue = []; + + /** + * Collection of additional hooks for finding assets. + * @type {Array} + * @private + */ + this.addHooks = []; + + /** + * Collection of additional hooks for processing assets. + * @type {Array} + * @private + */ + this.uploadHooks = []; + + /** + * Callback to call after completed. + * @type {Array} + * @private + */ + this.completes = []; + + /** + * If prepare is ticking (running). + * @type {boolean} + * @private + */ + this.ticking = false; + + /** + * 'bound' call for prepareItems(). + * @type {Function} + * @private + */ + this.delayedTick = function () { + // unlikely, but in case we were destroyed between tick() and delayedTick() + if (!_this.queue) { + return; + } + _this.prepareItems(); + }; + + // hooks to find the correct texture + this.registerFindHook(findText); + this.registerFindHook(findTextStyle); + this.registerFindHook(findMultipleBaseTextures); + this.registerFindHook(findBaseTexture); + this.registerFindHook(findTexture); + + // upload hooks + this.registerUploadHook(drawText); + this.registerUploadHook(calculateTextStyle); + } + + /** + * Upload all the textures and graphics to the GPU. + * + * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item - + * Either the container or display object to search for items to upload, the items to upload themselves, + * or the callback function, if items have been added using `prepare.add`. + * @param {Function} [done] - Optional callback when all queued uploads have completed + */ + + + BasePrepare.prototype.upload = function upload(item, done) { + if (typeof item === 'function') { + done = item; + item = null; + } + + // If a display object, search for items + // that we could upload + if (item) { + this.add(item); + } + + // Get the items for upload from the display + if (this.queue.length) { + if (done) { + this.completes.push(done); + } + + if (!this.ticking) { + this.ticking = true; + SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); + } + } else if (done) { + done(); + } + }; + + /** + * Handle tick update + * + * @private + */ + + + BasePrepare.prototype.tick = function tick() { + setTimeout(this.delayedTick, 0); + }; + + /** + * Actually prepare items. This is handled outside of the tick because it will take a while + * and we do NOT want to block the current animation frame from rendering. + * + * @private + */ + + + BasePrepare.prototype.prepareItems = function prepareItems() { + this.limiter.beginFrame(); + // Upload the graphics + while (this.queue.length && this.limiter.allowedToUpload()) { + var item = this.queue[0]; + var uploaded = false; + + if (item && !item._destroyed) { + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.uploadHookHelper, item)) { + this.queue.shift(); + uploaded = true; + break; + } + } + } + + if (!uploaded) { + this.queue.shift(); + } + } + + // We're finished + if (!this.queue.length) { + this.ticking = false; + + var completes = this.completes.slice(0); + + this.completes.length = 0; + + for (var _i = 0, _len = completes.length; _i < _len; _i++) { + completes[_i](); + } + } else { + // if we are not finished, on the next rAF do this again + SharedTicker.addOnce(this.tick, this, core.UPDATE_PRIORITY.UTILITY); + } + }; + + /** + * Adds hooks for finding items. + * + * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.registerFindHook = function registerFindHook(addHook) { + if (addHook) { + this.addHooks.push(addHook); + } + + return this; + }; + + /** + * Adds hooks for uploading items. + * + * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @return {PIXI.BasePrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.registerUploadHook = function registerUploadHook(uploadHook) { + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + + return this; + }; + + /** + * Manually add an item to the uploading queue. + * + * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to + * add to the queue + * @return {PIXI.CanvasPrepare} Instance of plugin for chaining. + */ + + + BasePrepare.prototype.add = function add(item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + + // Get childen recursively + if (item instanceof core.Container) { + for (var _i2 = item.children.length - 1; _i2 >= 0; _i2--) { + this.add(item.children[_i2]); + } + } + + return this; + }; + + /** + * Destroys the plugin, don't use after this. + * + */ + + + BasePrepare.prototype.destroy = function destroy() { + if (this.ticking) { + SharedTicker.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.limiter = null; + this.uploadHookHelper = null; + }; + + return BasePrepare; +}(); + +/** + * Built-in hook to find multiple textures from objects like AnimatedSprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ + + +exports.default = BasePrepare; +function findMultipleBaseTextures(item, queue) { + var result = false; + + // Objects with mutliple textures + if (item && item._textures && item._textures.length) { + for (var i = 0; i < item._textures.length; i++) { + if (item._textures[i] instanceof core.Texture) { + var baseTexture = item._textures[i].baseTexture; + + if (queue.indexOf(baseTexture) === -1) { + queue.push(baseTexture); + result = true; + } + } + } + } + + return result; +} + +/** + * Built-in hook to find BaseTextures from Sprites. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findBaseTexture(item, queue) { + // Objects with textures, like Sprites/Text + if (item instanceof core.BaseTexture) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find textures from objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Texture object was found. + */ +function findTexture(item, queue) { + if (item._texture && item._texture instanceof core.Texture) { + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to draw PIXI.Text to its texture. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function drawText(helper, item) { + if (item instanceof core.Text) { + // updating text will return early if it is not dirty + item.updateText(true); + + return true; + } + + return false; +} + +/** + * Built-in hook to calculate a text style for a PIXI.Text object. + * + * @private + * @param {PIXI.WebGLRenderer|PIXI.CanvasPrepare} helper - Not used by this upload handler + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function calculateTextStyle(helper, item) { + if (item instanceof core.TextStyle) { + var font = item.toFontString(); + + core.TextMetrics.measureFont(font); + + return true; + } + + return false; +} + +/** + * Built-in hook to find Text objects. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Text object was found. + */ +function findText(item, queue) { + if (item instanceof core.Text) { + // push the text style to prepare it - this can be really expensive + if (queue.indexOf(item.style) === -1) { + queue.push(item.style); + } + // also push the text object so that we can render it (to canvas/texture) if needed + if (queue.indexOf(item) === -1) { + queue.push(item); + } + // also push the Text's texture for upload to GPU + var texture = item._texture.baseTexture; + + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find TextStyle objects. + * + * @private + * @param {PIXI.TextStyle} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.TextStyle object was found. + */ +function findTextStyle(item, queue) { + if (item instanceof core.TextStyle) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + + return true; + } + + return false; +} + +},{"../core":65,"./limiters/CountLimiter":186}],184:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var CANVAS_START_SIZE = 16; + +/** + * The prepare manager provides functionality to upload content to the GPU + * This cannot be done directly for Canvas like in WebGL, but the effect can be achieved by drawing + * textures to an offline canvas. + * This draw call will force the texture to be moved onto the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ + +var CanvasPrepare = function (_BasePrepare) { + _inherits(CanvasPrepare, _BasePrepare); + + /** + * @param {PIXI.CanvasRenderer} renderer - A reference to the current renderer + */ + function CanvasPrepare(renderer) { + _classCallCheck(this, CanvasPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this; + + /** + * An offline canvas to render textures to + * @type {HTMLCanvasElement} + * @private + */ + _this.canvas = document.createElement('canvas'); + _this.canvas.width = CANVAS_START_SIZE; + _this.canvas.height = CANVAS_START_SIZE; + + /** + * The context to the canvas + * @type {CanvasRenderingContext2D} + * @private + */ + _this.ctx = _this.canvas.getContext('2d'); + + // Add textures to upload + _this.registerUploadHook(uploadBaseTextures); + return _this; + } + + /** + * Destroys the plugin, don't use after this. + * + */ + + + CanvasPrepare.prototype.destroy = function destroy() { + _BasePrepare.prototype.destroy.call(this); + this.ctx = null; + this.canvas = null; + }; + + return CanvasPrepare; +}(_BasePrepare3.default); + +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {*} prepare - Instance of CanvasPrepare + * @param {*} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = CanvasPrepare; +function uploadBaseTextures(prepare, item) { + if (item instanceof core.BaseTexture) { + var image = item.source; + + // Sometimes images (like atlas images) report a size of zero, causing errors on windows phone. + // So if the width or height is equal to zero then use the canvas size + // Otherwise use whatever is smaller, the image dimensions or the canvas dimensions. + var imageWidth = image.width === 0 ? prepare.canvas.width : Math.min(prepare.canvas.width, image.width); + var imageHeight = image.height === 0 ? prepare.canvas.height : Math.min(prepare.canvas.height, image.height); + + // Only a small subsections is required to be drawn to have the whole texture uploaded to the GPU + // A smaller draw can be faster. + prepare.ctx.drawImage(image, 0, 0, imageWidth, imageHeight, 0, 0, prepare.canvas.width, prepare.canvas.height); + + return true; + } + + return false; +} + +core.CanvasRenderer.registerPlugin('prepare', CanvasPrepare); + +},{"../../core":65,"../BasePrepare":183}],185:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _WebGLPrepare = require('./webgl/WebGLPrepare'); + +Object.defineProperty(exports, 'webgl', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_WebGLPrepare).default; + } +}); + +var _CanvasPrepare = require('./canvas/CanvasPrepare'); + +Object.defineProperty(exports, 'canvas', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CanvasPrepare).default; + } +}); + +var _BasePrepare = require('./BasePrepare'); + +Object.defineProperty(exports, 'BasePrepare', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_BasePrepare).default; + } +}); + +var _CountLimiter = require('./limiters/CountLimiter'); + +Object.defineProperty(exports, 'CountLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_CountLimiter).default; + } +}); + +var _TimeLimiter = require('./limiters/TimeLimiter'); + +Object.defineProperty(exports, 'TimeLimiter', { + enumerable: true, + get: function get() { + return _interopRequireDefault(_TimeLimiter).default; + } +}); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +},{"./BasePrepare":183,"./canvas/CanvasPrepare":184,"./limiters/CountLimiter":186,"./limiters/TimeLimiter":187,"./webgl/WebGLPrepare":188}],186:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * CountLimiter limits the number of items handled by a {@link PIXI.prepare.BasePrepare} to a specified + * number of items per frame. + * + * @class + * @memberof PIXI + */ +var CountLimiter = function () { + /** + * @param {number} maxItemsPerFrame - The maximum number of items that can be prepared each frame. + */ + function CountLimiter(maxItemsPerFrame) { + _classCallCheck(this, CountLimiter); + + /** + * The maximum number of items that can be prepared each frame. + * @private + */ + this.maxItemsPerFrame = maxItemsPerFrame; + /** + * The number of items that can be prepared in the current frame. + * @type {number} + * @private + */ + this.itemsLeft = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + CountLimiter.prototype.beginFrame = function beginFrame() { + this.itemsLeft = this.maxItemsPerFrame; + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + CountLimiter.prototype.allowedToUpload = function allowedToUpload() { + return this.itemsLeft-- > 0; + }; + + return CountLimiter; +}(); + +exports.default = CountLimiter; + +},{}],187:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +/** + * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of milliseconds per frame. + * + * @class + * @memberof PIXI + */ +var TimeLimiter = function () { + /** + * @param {number} maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. + */ + function TimeLimiter(maxMilliseconds) { + _classCallCheck(this, TimeLimiter); + + /** + * The maximum milliseconds that can be spent preparing items each frame. + * @private + */ + this.maxMilliseconds = maxMilliseconds; + /** + * The start time of the current frame. + * @type {number} + * @private + */ + this.frameStart = 0; + } + + /** + * Resets any counting properties to start fresh on a new frame. + */ + + + TimeLimiter.prototype.beginFrame = function beginFrame() { + this.frameStart = Date.now(); + }; + + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @return {boolean} If the item is allowed to be uploaded. + */ + + + TimeLimiter.prototype.allowedToUpload = function allowedToUpload() { + return Date.now() - this.frameStart < this.maxMilliseconds; + }; + + return TimeLimiter; +}(); + +exports.default = TimeLimiter; + +},{}],188:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; + +var _core = require('../../core'); + +var core = _interopRequireWildcard(_core); + +var _BasePrepare2 = require('../BasePrepare'); + +var _BasePrepare3 = _interopRequireDefault(_BasePrepare2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +/** + * The prepare manager provides functionality to upload content to the GPU. + * + * An instance of this class is automatically created by default, and can be found at renderer.plugins.prepare + * + * @class + * @extends PIXI.prepare.BasePrepare + * @memberof PIXI.prepare + */ +var WebGLPrepare = function (_BasePrepare) { + _inherits(WebGLPrepare, _BasePrepare); + + /** + * @param {PIXI.WebGLRenderer} renderer - A reference to the current renderer + */ + function WebGLPrepare(renderer) { + _classCallCheck(this, WebGLPrepare); + + var _this = _possibleConstructorReturn(this, _BasePrepare.call(this, renderer)); + + _this.uploadHookHelper = _this.renderer; + + // Add textures and graphics to upload + _this.registerFindHook(findGraphics); + _this.registerUploadHook(uploadBaseTextures); + _this.registerUploadHook(uploadGraphics); + return _this; + } + + return WebGLPrepare; +}(_BasePrepare3.default); +/** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ + + +exports.default = WebGLPrepare; +function uploadBaseTextures(renderer, item) { + if (item instanceof core.BaseTexture) { + // if the texture already has a GL texture, then the texture has been prepared or rendered + // before now. If the texture changed, then the changer should be calling texture.update() which + // reuploads the texture without need for preparing it again + if (!item._glTextures[renderer.CONTEXT_UID]) { + renderer.textureManager.updateTexture(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to upload PIXI.Graphics to the GPU. + * + * @private + * @param {PIXI.WebGLRenderer} renderer - instance of the webgl renderer + * @param {PIXI.DisplayObject} item - Item to check + * @return {boolean} If item was uploaded. + */ +function uploadGraphics(renderer, item) { + if (item instanceof core.Graphics) { + // if the item is not dirty and already has webgl data, then it got prepared or rendered + // before now and we shouldn't waste time updating it again + if (item.dirty || item.clearDirty || !item._webGL[renderer.plugins.graphics.CONTEXT_UID]) { + renderer.plugins.graphics.updateGraphics(item); + } + + return true; + } + + return false; +} + +/** + * Built-in hook to find graphics. + * + * @private + * @param {PIXI.DisplayObject} item - Display object to check + * @param {Array<*>} queue - Collection of items to upload + * @return {boolean} if a PIXI.Graphics object was found. + */ +function findGraphics(item, queue) { + if (item instanceof core.Graphics) { + queue.push(item); + + return true; + } + + return false; +} + +core.WebGLRenderer.registerPlugin('prepare', WebGLPrepare); + +},{"../../core":65,"../BasePrepare":183}],189:[function(require,module,exports){ +(function (global){ +'use strict'; + +exports.__esModule = true; +exports.loader = exports.prepare = exports.particles = exports.mesh = exports.loaders = exports.interaction = exports.filters = exports.extras = exports.extract = exports.accessibility = undefined; + +var _polyfill = require('./polyfill'); + +Object.keys(_polyfill).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _polyfill[key]; + } + }); +}); + +var _core = require('./core'); + +Object.keys(_core).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _core[key]; + } + }); +}); + +var _deprecation = require('./deprecation'); + +var _deprecation2 = _interopRequireDefault(_deprecation); + +var _accessibility = require('./accessibility'); + +var accessibility = _interopRequireWildcard(_accessibility); + +var _extract = require('./extract'); + +var extract = _interopRequireWildcard(_extract); + +var _extras = require('./extras'); + +var extras = _interopRequireWildcard(_extras); + +var _filters = require('./filters'); + +var filters = _interopRequireWildcard(_filters); + +var _interaction = require('./interaction'); + +var interaction = _interopRequireWildcard(_interaction); + +var _loaders = require('./loaders'); + +var loaders = _interopRequireWildcard(_loaders); + +var _mesh = require('./mesh'); + +var mesh = _interopRequireWildcard(_mesh); + +var _particles = require('./particles'); + +var particles = _interopRequireWildcard(_particles); + +var _prepare = require('./prepare'); + +var prepare = _interopRequireWildcard(_prepare); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// export core +_core.utils.mixins.performMixins(); + +/** + * Alias for {@link PIXI.loaders.shared}. + * @name loader + * @memberof PIXI + * @type {PIXI.loader.Loader} + */ + + +// handle mixins now, after all code has been added, including deprecation + + +// export libs +// import polyfills. Done as an export to make sure polyfills are imported first +var loader = loaders.shared || null; + +exports.accessibility = accessibility; +exports.extract = extract; +exports.extras = extras; +exports.filters = filters; +exports.interaction = interaction; +exports.loaders = loaders; +exports.mesh = mesh; +exports.particles = particles; +exports.prepare = prepare; +exports.loader = loader; + +// Apply the deprecations + +if (typeof _deprecation2.default === 'function') { + (0, _deprecation2.default)(exports); +} + +// Always export PixiJS globally. +global.PIXI = exports; // eslint-disable-line + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"./accessibility":42,"./core":65,"./deprecation":131,"./extract":133,"./extras":141,"./filters":153,"./interaction":159,"./loaders":162,"./mesh":171,"./particles":174,"./polyfill":181,"./prepare":185}]},{},[189])(189) +}); + + +//# sourceMappingURL=pixi.js.map diff --git a/js/pixi/4.8.9-custom/pixi.min.js b/js/pixi/4.8.9-custom/pixi.min.js new file mode 100644 index 0000000..889bdf5 --- /dev/null +++ b/js/pixi/4.8.9-custom/pixi.min.js @@ -0,0 +1 @@ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).PIXI=t()}}(function(){return function o(s,a,u){function h(r,t){if(!a[r]){if(!s[r]){var e="function"==typeof require&&require;if(!t&&e)return e(r,!0);if(l)return l(r,!0);var i=new Error("Cannot find module '"+r+"'");throw i.code="MODULE_NOT_FOUND",i}var n=a[r]={exports:{}};s[r][0].call(n.exports,function(t){var e=s[r][1][t];return h(e||t)},n,n.exports,o,s,a,u)}return a[r].exports}for(var l="function"==typeof require&&require,t=0;t>31;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(t>>=e))<<3,e|=r=(15<(t>>>=r))<<2,(e|=r=(3<(t>>>=r))<<1)|(t>>>=r)>>1},r.log10=function(t){return 1e9<=t?9:1e8<=t?8:1e7<=t?7:1e6<=t?6:1e5<=t?5:1e4<=t?4:1e3<=t?3:100<=t?2:10<=t?1:0},r.popCount=function(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24},r.countTrailingZeros=i,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,27030>>>(t&=15)&1};var n=new Array(256);!function(t){for(var e=0;e<256;++e){var r=e,i=e,n=7;for(r>>>=1;r;r>>>=1)i<<=1,i|=1&r,--n;t[e]=i<>>8&255]<<16|n[t>>>16&255]<<8|n[t>>>24&255]},r.interleave2=function(t,e){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t&=65535)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e&=65535)|e<<8))|e<<4))|e<<2))|e<<1))<<1},r.deinterleave2=function(t,e){return(t=65535&((t=16711935&((t=252645135&((t=858993459&((t=t>>>e&1431655765)|t>>>1))|t>>>2))|t>>>4))|t>>>16))<<16>>16},r.interleave3=function(t,e,r){return t=1227133513&((t=3272356035&((t=251719695&((t=4278190335&((t&=1023)|t<<16))|t<<8))|t<<4))|t<<2),(t|=(e=1227133513&((e=3272356035&((e=251719695&((e=4278190335&((e&=1023)|e<<16))|e<<8))|e<<4))|e<<2))<<1)|(r=1227133513&((r=3272356035&((r=251719695&((r=4278190335&((r&=1023)|r<<16))|r<<8))|r<<4))|r<<2))<<2},r.deinterleave3=function(t,e){return(t=1023&((t=4278190335&((t=251719695&((t=3272356035&((t=t>>>e&1227133513)|t>>>2))|t>>>4))|t>>>8))|t>>>16))<<22>>22},r.nextCombination=function(t){var e=t|t-1;return 1+e|(~e&-~e)-1>>>i(t)+1}},{}],2:[function(t,e,r){"use strict";function i(t,e,r){r=r||2;var i,n,o,s,a,u,h,l=e&&e.length,c=l?e[0]*r:t.length,d=v(t,0,c,r,!0),f=[];if(!d||d.next===d.prev)return f;if(l&&(d=function(t,e,r,i){var n,o,s,a,u,h=[];for(n=0,o=e.length;n80*r){i=o=t[0],n=s=t[1];for(var p=r;po.x?n.x>s.x?n.x:s.x:o.x>s.x?o.x:s.x,l=n.y>o.y?n.y>s.y?n.y:s.y:o.y>s.y?o.y:s.y,c=x(a,u,e,r,i),d=x(h,l,e,r,i),f=t.prevZ,p=t.nextZ;f&&f.z>=c&&p&&p.z<=d;){if(f!==t.prev&&f!==t.next&&T(n.x,n.y,o.x,o.y,s.x,s.y,f.x,f.y)&&0<=w(f.prev,f,f.next))return;if(f=f.prevZ,p!==t.prev&&p!==t.next&&T(n.x,n.y,o.x,o.y,s.x,s.y,p.x,p.y)&&0<=w(p.prev,p,p.next))return;p=p.nextZ}for(;f&&f.z>=c;){if(f!==t.prev&&f!==t.next&&T(n.x,n.y,o.x,o.y,s.x,s.y,f.x,f.y)&&0<=w(f.prev,f,f.next))return;f=f.prevZ}for(;p&&p.z<=d;){if(p!==t.prev&&p!==t.next&&T(n.x,n.y,o.x,o.y,s.x,s.y,p.x,p.y)&&0<=w(p.prev,p,p.next))return;p=p.nextZ}return 1}}function d(t,e,r){var i=t;do{var n=i.prev,o=i.next.next;!a(n,o)&&p(n,i,i.next,o)&&E(n,o)&&E(o,n)&&(e.push(n.i/r),e.push(i.i/r),e.push(o.i/r),O(i),O(i.next),i=t=o),i=i.next}while(i!==t);return i}function f(t,e,r,i,n,o){var s,a,u=t;do{for(var h=u.next.next;h!==u.prev;){if(u.i!==h.i&&(a=h,(s=u).next.i!==a.i&&s.prev.i!==a.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&p(r,r.next,t,e))return 1;r=r.next}while(r!==t);return}(s,a)&&E(s,a)&&E(a,s)&&function(t,e){var r=t,i=!1,n=(t.x+e.x)/2,o=(t.y+e.y)/2;for(;r.y>o!=r.next.y>o&&r.next.y!==r.y&&n<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(i=!i),r=r.next,r!==t;);return i}(s,a))){var l=S(u,h);return u=g(u,u.next),l=g(l,l.next),y(u,e,r,i,n,o),void y(l,e,r,i,n,o)}h=h.next}u=u.next}while(u!==t)}function m(t,e){return t.x-e.x}function _(t,e){if(e=function(t,e){var r,i=e,n=t.x,o=t.y,s=-1/0;do{if(o<=i.y&&o>=i.next.y&&i.next.y!==i.y){var a=i.x+(o-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(a<=n&&s=i.x&&i.x>=l&&n!==i.x&&T(or.x)&&E(i,t)&&(r=i,d=u),i=i.next;return r}(t,e)){var r=S(e,t);g(r,r.next)}}function x(t,e,r,i,n){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*n)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-i)*n)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function b(t){for(var e=t,r=t;e.x=t.byteLength?i.bufferSubData(this.type,e,t):i.bufferData(this.type,t,this.drawType),this.data=t},n.prototype.bind=function(){this.gl.bindBuffer(this.type,this.buffer)},n.createVertexBuffer=function(t,e,r){return new n(t,t.ARRAY_BUFFER,e,r)},n.createIndexBuffer=function(t,e,r){return new n(t,t.ELEMENT_ARRAY_BUFFER,e,r)},n.create=function(t,e,r,i){return new n(t,e,r,i)},n.prototype.destroy=function(){this.gl.deleteBuffer(this.buffer)},e.exports=n},{}],10:[function(t,e,r){function s(t,e,r){this.gl=t,this.framebuffer=t.createFramebuffer(),this.stencil=null,this.texture=null,this.width=e||100,this.height=r||100}var a=t("./GLTexture");s.prototype.enableTexture=function(t){var e=this.gl;this.texture=t||new a(e),this.texture.bind(),this.bind(),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture.texture,0)},s.prototype.enableStencil=function(){if(!this.stencil){var t=this.gl;this.stencil=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.stencil),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.stencil),t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,this.width,this.height)}},s.prototype.clear=function(t,e,r,i){this.bind();var n=this.gl;n.clearColor(t,e,r,i),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT)},s.prototype.bind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.framebuffer)},s.prototype.unbind=function(){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null)},s.prototype.resize=function(t,e){var r=this.gl;this.width=t,this.height=e,this.texture&&this.texture.uploadData(null,t,e),this.stencil&&(r.bindRenderbuffer(r.RENDERBUFFER,this.stencil),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,t,e))},s.prototype.destroy=function(){var t=this.gl;this.texture&&this.texture.destroy(),t.deleteFramebuffer(this.framebuffer),this.gl=null,this.stencil=null,this.texture=null},s.createRGBA=function(t,e,r,i){var n=a.fromData(t,null,e,r);n.enableNearestScaling(),n.enableWrapClamp();var o=new s(t,e,r);return o.enableTexture(n),o.unbind(),o},s.createFloat32=function(t,e,r,i){var n=new a.fromData(t,i,e,r);n.enableNearestScaling(),n.enableWrapClamp();var o=new s(t,e,r);return o.enableTexture(n),o.unbind(),o},e.exports=s},{"./GLTexture":12}],11:[function(t,e,r){function i(t,e,r,i,n){this.gl=t,i&&(e=u(e,i),r=u(r,i)),this.program=o(t,e,r,n),this.attributes=s(t,this.program),this.uniformData=a(t,this.program),this.uniforms=h(t,this.uniformData)}var o=t("./shader/compileProgram"),s=t("./shader/extractAttributes"),a=t("./shader/extractUniforms"),u=t("./shader/setPrecision"),h=t("./shader/generateUniformAccessObject");i.prototype.bind=function(){return this.gl.useProgram(this.program),this},i.prototype.destroy=function(){this.attributes=null,this.uniformData=null,this.uniforms=null,this.gl.deleteProgram(this.program)},e.exports=i},{"./shader/compileProgram":17,"./shader/extractAttributes":19,"./shader/extractUniforms":20,"./shader/generateUniformAccessObject":21,"./shader/setPrecision":25}],12:[function(t,e,r){function o(t,e,r,i,n){this.gl=t,this.texture=t.createTexture(),this.mipmap=!1,this.premultiplyAlpha=!1,this.width=e||-1,this.height=r||-1,this.format=i||t.RGBA,this.type=n||t.UNSIGNED_BYTE}var n=!(o.prototype.upload=function(t){this.bind();var e=this.gl;e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var r=t.videoWidth||t.width,i=t.videoHeight||t.height;i!==this.height||r!==this.width?e.texImage2D(e.TEXTURE_2D,0,this.format,this.format,this.type,t):e.texSubImage2D(e.TEXTURE_2D,0,0,0,this.format,this.type,t),this.width=r,this.height=i});o.prototype.uploadData=function(t,e,r){this.bind();var i=this.gl;if(t instanceof Float32Array){if(!n){if(!i.getExtension("OES_texture_float"))throw new Error("floating point textures not available");n=!0}this.type=i.FLOAT}else this.type=this.type||i.UNSIGNED_BYTE;i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),e!==this.width||r!==this.height?i.texImage2D(i.TEXTURE_2D,0,this.format,e,r,0,this.format,this.type,t||null):i.texSubImage2D(i.TEXTURE_2D,0,0,0,e,r,this.format,this.type,t||null),this.width=e,this.height=r},o.prototype.bind=function(t){var e=this.gl;void 0!==t&&e.activeTexture(e.TEXTURE0+t),e.bindTexture(e.TEXTURE_2D,this.texture)},o.prototype.unbind=function(){var t=this.gl;t.bindTexture(t.TEXTURE_2D,null)},o.prototype.minFilter=function(t){var e=this.gl;this.bind(),this.mipmap?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t?e.LINEAR:e.NEAREST)},o.prototype.magFilter=function(t){var e=this.gl;this.bind(),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t?e.LINEAR:e.NEAREST)},o.prototype.enableMipmap=function(){var t=this.gl;this.bind(),this.mipmap=!0,t.generateMipmap(t.TEXTURE_2D)},o.prototype.enableLinearScaling=function(){this.minFilter(!0),this.magFilter(!0)},o.prototype.enableNearestScaling=function(){this.minFilter(!1),this.magFilter(!1)},o.prototype.enableWrapClamp=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)},o.prototype.enableWrapRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.REPEAT)},o.prototype.enableWrapMirrorRepeat=function(){var t=this.gl;this.bind(),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.MIRRORED_REPEAT),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.MIRRORED_REPEAT)},o.prototype.destroy=function(){this.gl.deleteTexture(this.texture)},o.fromSource=function(t,e,r){var i=new o(t);return i.premultiplyAlpha=r||!1,i.upload(e),i},o.fromData=function(t,e,r,i){var n=new o(t);return n.uploadData(e,r,i),n},e.exports=o},{}],13:[function(t,e,r){var n=t("./setVertexAttribArrays");function i(t,e){if(this.nativeVaoExtension=null,i.FORCE_NATIVE||(this.nativeVaoExtension=t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object")),this.nativeState=e,this.nativeVaoExtension){this.nativeVao=this.nativeVaoExtension.createVertexArrayOES();var r=t.getParameter(t.MAX_VERTEX_ATTRIBS);this.nativeState={tempAttribState:new Array(r),attribState:new Array(r)}}this.gl=t,this.attributes=[],this.indexBuffer=null,this.dirty=!1}i.prototype.constructor=i,(e.exports=i).FORCE_NATIVE=!1,i.prototype.bind=function(){if(this.nativeVao){if(this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao),this.dirty)return this.dirty=!1,this.activate(),this;this.indexBuffer&&this.indexBuffer.bind()}else this.activate();return this},i.prototype.unbind=function(){return this.nativeVao&&this.nativeVaoExtension.bindVertexArrayOES(null),this},i.prototype.activate=function(){for(var t=this.gl,e=null,r=0;r= 0x80 (not a basic code point)","invalid-input":"Invalid input"},d=m-_,E=Math.floor,S=String.fromCharCode;function O(t){throw new RangeError(c[t])}function f(t,e){for(var r=t.length,i=[];r--;)i[r]=e(t[r]);return i}function p(t,e){var r=t.split("@"),i="";return 1>>10&1023|55296),t=56320|1023&t),e+=S(t)}).join("")}function C(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function R(t,e,r){var i=0;for(t=r?E(t/a):t>>1,t+=E(t/e);d*x>>1E((y-p)/s))&&O("overflow"),p+=u*s,!(u<(h=a<=g?_:g+x<=a?x:a-g));a+=m)s>E(y/(l=m-h))&&O("overflow"),s*=l;g=R(p-o,e=d.length+1,0==o),E(p/e)>y-v&&O("overflow"),v+=E(p/e),p%=e,d.splice(p++,0,v)}return P(d)}function g(t){var e,r,i,n,o,s,a,u,h,l,c,d,f,p,v,g=[];for(d=(t=M(t)).length,e=T,o=b,s=r=0;sE((y-r)/(f=i+1))&&O("overflow"),r+=(a-e)*f,e=a,s=0;sy&&O("overflow"),c==e){for(u=r,h=m;!(u<(l=h<=o?_:o+x<=h?x:h-o));h+=m)v=u-l,p=m-l,g.push(S(C(l+v%p,0))),u=E(v/p);g.push(S(C(u,0))),o=R(r,f,i==n),r=0,++i}++r,++e}return g.join("")}if(n={version:"1.4.1",ucs2:{decode:M,encode:P},decode:v,encode:g,toASCII:function(t){return p(t,function(t){return h.test(t)?"xn--"+g(t):t})},toUnicode:function(t){return p(t,function(t){return u.test(t)?v(t.slice(4).toLowerCase()):t})}},0,e&&r)if(I.exports==e)r.exports=n;else for(o in n)n.hasOwnProperty(o)&&(e[o]=n[o]);else t.punycode=n}(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],28:[function(t,e,r){"use strict";e.exports=function(t,e,r,i){e=e||"&",r=r||"=";var n={};if("string"!=typeof t||0===t.length)return n;var o=/\+/g;t=t.split(e);var s=1e3;i&&"number"==typeof i.maxKeys&&(s=i.maxKeys);var a,u,h=t.length;0>2,n[1]=(3&i[0])<<4|i[1]>>4,n[2]=(15&i[1])<<2|i[2]>>6,n[3]=63&i[2],r-(t.length-1)){case 2:n[3]=64,n[2]=64;break;case 1:n[3]=64}for(var s=0;s",'"',"`"," ","\r","\n","\t"]),k=["'"].concat(n),F=["%","/","?",";","#"].concat(k),j=["/","?","#"],U=/^[+a-z0-9A-Z_-]{0,63}$/,X=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,G={javascript:!0,"javascript:":!0},W={javascript:!0,"javascript:":!0},H={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},Y=t("querystring");function o(t,e,r){if(t&&L.isObject(t)&&t instanceof M)return t;var i=new M;return i.parse(t,e,r),i}M.prototype.parse=function(t,e,r){if(!L.isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var i=t.indexOf("?"),n=-1!==i&&ithis.renderer.width&&(t.width=this.renderer.width-t.x),t.y+t.height>this.renderer.height&&(t.height=this.renderer.height-t.y)},a.prototype.addChild=function(t){var e=this.pool.pop();e||((e=document.createElement("button")).style.width="100px",e.style.height="100px",e.style.backgroundColor=this.debug?"rgba(255,0,0,0.5)":"transparent",e.style.position="absolute",e.style.zIndex=2,e.style.borderStyle="none",-1]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i,r.SHAPES={POLY:0,RECT:1,CIRC:2,ELIP:3,RREC:4},r.PRECISION={LOW:"lowp",MEDIUM:"mediump",HIGH:"highp"},r.TRANSFORM_MODE={STATIC:0,DYNAMIC:1},r.TEXT_GRADIENT={LINEAR_VERTICAL:0,LINEAR_HORIZONTAL:1},r.UPDATE_PRIORITY={INTERACTION:50,HIGH:25,NORMAL:0,LOW:-25,UTILITY:-50}},{}],47:[function(t,e,r){"use strict";r.__esModule=!0;var i=t("../math");var n=(o.prototype.isEmpty=function(){return this.minX>this.maxX||this.minY>this.maxY},o.prototype.clear=function(){this.updateID++,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0},o.prototype.getRectangle=function(t){return this.minX>this.maxX||this.minY>this.maxY?i.Rectangle.EMPTY:((t=t||new i.Rectangle(0,0,1,1)).x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)},o.prototype.addPoint=function(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)},o.prototype.addQuad=function(t){var e=this.minX,r=this.minY,i=this.maxX,n=this.maxY,o=t[0],s=t[1];e=oi?t.maxX:i,this.maxY=t.maxY>n?t.maxY:n},o.prototype.addBoundsMask=function(t,e){var r=t.minX>e.minX?t.minX:e.minX,i=t.minY>e.minY?t.minY:e.minY,n=t.maxXe.x?t.minX:e.x,i=t.minY>e.y?t.minY:e.y,n=t.maxXthis.children.length)throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length);return t.parent&&t.parent.removeChild(t),t.parent=this,t.transform._parentID=-1,this.children.splice(e,0,t),this._boundsID++,this.onChildrenChange(e),t.emit("added",this),t},c.prototype.swapChildren=function(t,e){if(t!==e){var r=this.getChildIndex(t),i=this.getChildIndex(e);this.children[r]=e,this.children[i]=t,this.onChildrenChange(r=this.children.length)throw new Error("The index "+e+" supplied is out of bounds "+this.children.length);var r=this.getChildIndex(t);(0,s.removeItems)(this.children,r,1),this.children.splice(e,0,t),this.onChildrenChange(e)},c.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Index ("+t+") does not exist.");return this.children[t]},c.prototype.removeChild=function(t){var e=arguments.length;if(1S.CURVES.maxSegments&&(e=S.CURVES.maxSegments),e},S.prototype.lineStyle=function(t,e,r,i){var n=0>16&255)/255,r=(t.tint>>8&255)/255,i=(255&t.tint)/255,n=0;n>16&255)/255*e*255<<16)+((s>>8&255)/255*r*255<<8)+(255&s)/255*i*255,o._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*r*255<<8)+(255&a)/255*i*255}},a.prototype.renderPolygon=function(t,e,r){r.moveTo(t[0],t[1]);for(var i=1;i=this.x&&t=this.y&&e=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){if(e>=this.y+this.radius&&e<=this.y+this.height-this.radius||t>=this.x+this.radius&&t<=this.x+this.width-this.radius)return!0;var r=t-(this.x+this.radius),i=e-(this.y+this.radius),n=this.radius*this.radius;if(r*r+i*i<=n)return!0;if((r=t-(this.x+this.width-this.radius))*r+i*i<=n)return!0;if(r*r+(i=e-(this.y+this.height-this.radius))*i<=n)return!0;if((r=t-(this.x+this.radius))*r+i*i<=n)return!0}return!1},s);function s(){var t=0this.checkCountMax&&(this.checkCount=0,this.run()))},u.prototype.run=function(){for(var t=this.renderer.textureManager,e=t._managedTextures,r=!1,i=0;ithis.maxIdle&&(t.destroyTexture(n,!0),r=!(e[i]=null))}if(r){for(var o=0,s=0;s 0.5)"," {"," color = vec4(1.0, 0.0, 0.0, 1.0);"," }"," else"," {"," color = vec4(0.0, 1.0, 0.0, 1.0);"," }"," gl_FragColor = mix(sample, masky, 0.5);"," gl_FragColor *= sample.a;","}"].join("\n")}}]),d);function d(t,e,r){for(var i in!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,d),this.vertexSrc=t||d.defaultVertexSrc,this.fragmentSrc=e||d.defaultFragmentSrc,this._blendMode=a.BLEND_MODES.NORMAL,this.uniformData=r||(0,o.default)(this.vertexSrc,this.fragmentSrc,"projectionMatrix|uSampler"),this.uniforms={},this.uniformData)this.uniforms[i]=this.uniformData[i].value,this.uniformData[i].type&&(this.uniformData[i].type=this.uniformData[i].type.toLowerCase());this.glShaders={},l[this.vertexSrc+this.fragmentSrc]||(l[this.vertexSrc+this.fragmentSrc]=(0,s.uid)()),this.glShaderKey=l[this.vertexSrc+this.fragmentSrc],this.padding=4,this.resolution=u.default.FILTER_RESOLUTION,this.enabled=!0,this.autoFit=!0}r.default=c},{"../../../const":46,"../../../settings":101,"../../../utils":125,"./extractUniformsFromSrc":87}],87:[function(t,e,r){"use strict";r.__esModule=!0,r.default=function(t,e,r){var i=o(t),n=o(e);return Object.assign(i,n)};var i,n=t("pixi-gl-core");var c=((i=n)&&i.__esModule?i:{default:i}).default.shader.defaultValue;function o(t){for(var e=new RegExp("^(projectionMatrix|uSampler|filterArea|filterClamp)$"),r={},i=void 0,n=t.replace(/\s+/g," ").split(/\s*;\s*/),o=0;o=i&&d.x=n&&d.y>16)+(65280&t)+((255&t)<<16)}},{key:"texture",get:function(){return this._texture},set:function(t){this._texture!==t&&(this._texture=t||u.default.EMPTY,this.cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,t&&(t.baseTexture.hasLoaded?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}]),p);function p(t){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,p);var e=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,c.call(this));return e._anchor=new o.ObservablePoint(e._onAnchorUpdate,e,t?t.defaultAnchor.x:0,t?t.defaultAnchor.y:0),e._texture=null,e._width=0,e._height=0,e._tint=null,e._tintRGB=null,e.tint=16777215,e.blendMode=a.BLEND_MODES.NORMAL,e.shader=null,e.cachedTint=16777215,e.texture=t||u.default.EMPTY,e.vertexData=new Float32Array(8),e.vertexTrimmedData=null,e._transformID=-1,e._textureID=-1,e._transformTrimmedID=-1,e._textureTrimmedID=-1,e.pluginName="sprite",e}r.default=f},{"../const":46,"../display/Container":48,"../math":70,"../textures/Texture":115,"../utils":125}],103:[function(t,e,r){"use strict";r.__esModule=!0;var i=n(t("../../renderers/canvas/CanvasRenderer")),l=t("../../const"),c=t("../../math"),d=n(t("./CanvasTinter"));function n(t){return t&&t.__esModule?t:{default:t}}var f=new c.Matrix,o=(s.prototype.render=function(t){var e=t._texture,r=this.renderer,i=e._frame.width,n=e._frame.height,o=t.transform.worldTransform,s=0,a=0;if(!(e.orig.width<=0||e.orig.height<=0)&&e.baseTexture.source&&(r.setBlendMode(t.blendMode),e.valid)){r.context.globalAlpha=t.worldAlpha;var u=e.baseTexture.scaleMode===l.SCALE_MODES.LINEAR;r.smoothProperty&&r.context[r.smoothProperty]!==u&&(r.context[r.smoothProperty]=u),a=e.trim?(s=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(s=(.5-t.anchor.x)*e.orig.width,(.5-t.anchor.y)*e.orig.height),e.rotate&&(o.copy(f),o=f,c.GroupD8.matrixAppendRotationInv(o,e.rotate,s,a),a=s=0),s-=i/2,a-=n/2,r.roundPixels||t.roundPixels?(r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution|0,o.ty*r.resolution|0),s|=0,a|=0):r.context.setTransform(o.a,o.b,o.c,o.d,o.tx*r.resolution,o.ty*r.resolution);var h=e.baseTexture.resolution;16777215!==t.tint?(t.cachedTint===t.tint&&t.tintedTexture.tintId===t._texture._updateID||(t.cachedTint=t.tint,t.tintedTexture=d.default.getTintedTexture(t,t.tint)),r.context.drawImage(t.tintedTexture,0,0,i*h,n*h,s*r.resolution,a*r.resolution,i*r.resolution,n*r.resolution)):r.context.drawImage(e.baseTexture.source,e._frame.x*h,e._frame.y*h,i*h,n*h,s*r.resolution,a*r.resolution,i*r.resolution,n*r.resolution)}},s.prototype.destroy=function(){this.renderer=null},s);function s(t){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,s),this.renderer=t}r.default=o,i.default.registerPlugin("sprite",o)},{"../../const":46,"../../math":70,"../../renderers/canvas/CanvasRenderer":77,"./CanvasTinter":104}],104:[function(t,e,r){"use strict";r.__esModule=!0;var i,f=t("../../utils"),n=t("../../renderers/canvas/utils/canUseNewCanvasBlendModes");var a={getTintedTexture:function(t,e){var r=t._texture,i="#"+("00000"+(0|(e=a.roundColor(e))).toString(16)).substr(-6);r.tintCache=r.tintCache||{};var n=r.tintCache[i],o=void 0;if(n){if(n.tintId===r._updateID)return r.tintCache[i];o=r.tintCache[i]}else o=a.canvas||document.createElement("canvas");if(a.tintMethod(r,e,o),o.tintId=r._updateID,a.convertTintToImage){var s=new Image;s.src=o.toDataURL(),r.tintCache[i]=s}else r.tintCache[i]=o,a.canvas=null;return o},tintWithMultiply:function(t,e,r){var i=r.getContext("2d"),n=t._frame.clone(),o=t.baseTexture.resolution;n.x*=o,n.y*=o,n.width*=o,n.height*=o,r.width=Math.ceil(n.width),r.height=Math.ceil(n.height),i.save(),i.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),i.fillRect(0,0,n.width,n.height),i.globalCompositeOperation="multiply",i.drawImage(t.baseTexture.source,n.x,n.y,n.width,n.height,0,0,n.width,n.height),i.globalCompositeOperation="destination-atop",i.drawImage(t.baseTexture.source,n.x,n.y,n.width,n.height,0,0,n.width,n.height),i.restore()},tintWithOverlay:function(t,e,r){var i=r.getContext("2d"),n=t._frame.clone(),o=t.baseTexture.resolution;n.x*=o,n.y*=o,n.width*=o,n.height*=o,r.width=Math.ceil(n.width),r.height=Math.ceil(n.height),i.save(),i.globalCompositeOperation="copy",i.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),i.fillRect(0,0,n.width,n.height),i.globalCompositeOperation="destination-atop",i.drawImage(t.baseTexture.source,n.x,n.y,n.width,n.height,0,0,n.width,n.height),i.restore()},tintWithPerPixel:function(t,e,r){var i=r.getContext("2d"),n=t._frame.clone(),o=t.baseTexture.resolution;n.x*=o,n.y*=o,n.width*=o,n.height*=o,r.width=Math.ceil(n.width),r.height=Math.ceil(n.height),i.save(),i.globalCompositeOperation="copy",i.drawImage(t.baseTexture.source,n.x,n.y,n.width,n.height,0,0,n.width,n.height),i.restore();for(var s=(0,f.hex2rgb)(e),a=s[0],u=s[1],h=s[2],l=i.getImageData(0,0,n.width,n.height),c=l.data,d=0;d=this.size&&this.flush(),t._texture._uvs&&(this.sprites[this.currentIndex++]=t)},d.prototype.flush=function(){if(0!==this.currentIndex){var t=this.renderer.gl,e=this.MAX_TEXTURES,r=U.default.nextPow2(this.currentIndex),i=U.default.log2(r),n=this.buffers[i],o=this.sprites,s=this.groups,a=n.float32View,u=n.uint32View,h=this.boundTextures,l=this.renderer.boundTextures,c=this.renderer.textureGC.count,d=0,f=void 0,p=void 0,v=1,g=0,y=s[0],m=void 0,_=void 0,x=F.premultiplyBlendMode[o[0]._texture.baseTexture.premultipliedAlpha?1:0][o[0].blendMode];y.textureCount=0,y.start=0,y.blend=x,X++;var b=void 0;for(b=0;b=r.length)break;o=r[n++]}else{if((n=r.next()).done)break;o=n.value}var s=o;this.animations[e].push(this.textures[s])}}},d.prototype._parseComplete=function(){var t=this._callback;this._callback=null,this._batchIndex=0,t.call(this,this.textures)},d.prototype._nextBatch=function(){var t=this;this._processFrames(this._batchIndex*d.BATCH_SIZE),this._batchIndex++,setTimeout(function(){t._batchIndex*d.BATCH_SIZEthis.baseTexture.width,s=r+n>this.baseTexture.height;if(o||s){var a=o&&s?"and":"or",u="X: "+e+" + "+i+" = "+(e+i)+" > "+this.baseTexture.width,h="Y: "+r+" + "+n+" = "+(r+n)+" > "+this.baseTexture.height;throw new Error("Texture Error: frame does not fit inside the base Texture dimensions: "+u+" "+a+" "+h)}this.valid=i&&n&&this.baseTexture.hasLoaded,this.trim||this.rotate||(this.orig=t),this.valid&&this._updateUvs()}},{key:"rotate",get:function(){return this._rotate},set:function(t){this._rotate=t,this.valid&&this._updateUvs()}},{key:"width",get:function(){return this.orig.width}},{key:"height",get:function(){return this.orig.height}}]),v);function v(t,e,r,i,n,o){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,v);var s=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,f.call(this));if(s.noFrame=!1,e||(s.noFrame=!0,e=new h.Rectangle(0,0,1,1)),t instanceof v&&(t=t.baseTexture),s.baseTexture=t,s._frame=e,s.trim=i,s.valid=!1,s.requiresUpdate=!1,s._uvs=null,s.orig=r||e,s._rotate=Number(n||0),!0===n)s._rotate=2;else if(s._rotate%2!=0)throw new Error("attempt to use diamond-shaped UVs. If you are sure, set rotation manually");return t.hasLoaded?(s.noFrame&&(e=new h.Rectangle(0,0,t.width,t.height),t.on("update",s.onBaseTextureUpdated,s)),s.frame=e):t.once("loaded",s.onBaseTextureLoaded,s),s.defaultAnchor=o?new h.Point(o.x,o.y):new h.Point(0,0),s._updateID=0,s.transform=null,s.textureCacheIds=[],s}function g(t){t.destroy=function(){},t.on=function(){},t.once=function(){},t.emit=function(){}}(r.default=p).EMPTY=new p(new o.default),g(p.EMPTY),g(p.EMPTY.baseTexture),p.WHITE=function(){var t=document.createElement("canvas");t.width=10,t.height=10;var e=t.getContext("2d");return e.fillStyle="white",e.fillRect(0,0,10,10),new p(new o.default(t))}(),g(p.WHITE),g(p.WHITE.baseTexture)},{"../math":70,"../settings":101,"../utils":125,"./BaseTexture":112,"./TextureUvs":117,"./VideoBaseTexture":118,eventemitter3:3}],116:[function(t,e,r){"use strict";r.__esModule=!0;var i=function(t,e,r){return e&&n(t.prototype,e),r&&n(t,r),t};function n(t,e){for(var r=0;re.priority){t.connect(r);break}e=(r=e).next}t.previous||t.connect(r)}else t.connect(r);return this._startIfPossible(),this},l.prototype.remove=function(t,e){for(var r=this._head.next;r;)r=r.match(t,e)?r.destroy():r.next;return this._head.next||this._cancelIfNeeded(),this},l.prototype.start=function(){this.started||(this.started=!0,this._requestIfNeeded())},l.prototype.stop=function(){this.started&&(this.started=!1,this._cancelIfNeeded())},l.prototype.destroy=function(){this.stop();for(var t=this._head.next;t;)t=t.destroy(!0);this._head.destroy(),this._head=null},l.prototype.update=function(t){var e=0this.lastTime){(r=this.elapsedMS=e-this.lastTime)>this._maxElapsedMS&&(r=this._maxElapsedMS),this.deltaTime=r*o.default.TARGET_FPMS*this.speed;for(var i=this._head,n=i.next;n;)n=n.emit(this.deltaTime);i.next||this._cancelIfNeeded()}else this.deltaTime=this.elapsedMS=0;this.lastTime=e},i(l,[{key:"FPS",get:function(){return 1e3/this.elapsedMS}},{key:"minFPS",get:function(){return 1e3/this._maxElapsedMS},set:function(t){var e=Math.min(Math.max(0,t)/1e3,o.default.TARGET_FPMS);this._maxElapsedMS=1/e}}]),l);function l(){var e=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,l),this._head=new a.default(null,null,1/0),this._requestId=null,this._maxElapsedMS=100,this.autoStart=!1,this.deltaTime=1,this.elapsedMS=1/o.default.TARGET_FPMS,this.lastTime=-1,this.speed=1,this.started=!1,this._tick=function(t){e._requestId=null,e.started&&(e.update(t),e.started&&null===e._requestId&&e._head.next&&(e._requestId=requestAnimationFrame(e._tick)))}}r.default=h},{"../const":46,"../settings":101,"./TickerListener":120}],120:[function(t,e,r){"use strict";r.__esModule=!0;var i=(n.prototype.match=function(t,e){return e=e||null,this.fn===t&&this.context===e},n.prototype.emit=function(t){this.fn&&(this.context?this.fn.call(this.context,t):this.fn(t));var e=this.next;return this.once&&this.destroy(!0),this._destroyed&&(this.next=null),e},n.prototype.connect=function(t){(this.previous=t).next&&(t.next.previous=this),this.next=t.next,t.next=this},n.prototype.destroy=function(t){var e=0>16&255)/255,e[1]=(t>>8&255)/255,e[2]=(255&t)/255,e},r.hex2string=function(t){return t=t.toString(16),"#"+(t="000000".substr(0,6-t.length)+t)},r.rgb2hex=function(t){return(255*t[0]<<16)+(255*t[1]<<8)+(255*t[2]|0)},r.getResolutionOfUrl=function(t,e){var r=n.default.RETINA_PREFIX.exec(t);if(r)return parseFloat(r[1]);return void 0!==e?e:1},r.decomposeDataUri=function(t){var e=i.DATA_URI.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,charset:e[3]?e[3].toLowerCase():void 0,encoding:e[4]?e[4].toLowerCase():void 0,data:e[5]};return},r.getUrlFileExtension=function(t){var e=i.URL_FILE_EXTENSION.exec(t);if(e)return e[1].toLowerCase();return},r.getSvgSize=function(t){var e=i.SVG_SIZE.exec(t),r={};e&&(r[e[1]]=Math.round(parseFloat(e[3])),r[e[5]]=Math.round(parseFloat(e[7])));return r},r.skipHello=function(){v=!0},r.sayHello=function(t){if(v)return;if(-1>16&255,i=t>>8&255,n=255&t;return(255*e<<24)+((r=r*e+.5|0)<<16)+((i=i*e+.5|0)<<8)+(n=n*e+.5|0)},r.premultiplyRgba=function(t,e,r,i){r=r||new Float32Array(4),i||void 0===i?(r[0]=t[0]*e,r[1]=t[1]*e,r[2]=t[2]*e):(r[0]=t[0],r[1]=t[1],r[2]=t[2]);return r[3]=e,r},r.premultiplyTintToRgba=function(t,e,r,i){(r=r||new Float32Array(4))[0]=(t>>16&255)/255,r[1]=(t>>8&255)/255,r[2]=(255&t)/255,!i&&void 0!==i||(r[0]*=e,r[1]*=e,r[2]*=e);return r[3]=e,r};var i=t("../const"),n=f(t("../settings")),o=f(t("eventemitter3")),s=f(t("./pluginTarget")),a=d(t("./mixin")),u=d(t("ismobilejs")),h=f(t("remove-array-items")),l=f(t("./mapPremultipliedBlendModes")),c=f(t("earcut"));function d(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function f(t){return t&&t.__esModule?t:{default:t}}var p=0,v=!1;r.isMobile=u,r.removeItems=h.default,r.EventEmitter=o.default,r.pluginTarget=s.default,r.mixins=a,r.earcut=c.default;var g=r.TextureCache=Object.create(null),y=r.BaseTextureCache=Object.create(null);var m=r.premultiplyBlendMode=(0,l.default)()},{"../const":46,"../settings":101,"./mapPremultipliedBlendModes":126,"./mixin":128,"./pluginTarget":129,earcut:2,eventemitter3:3,ismobilejs:4,"remove-array-items":31}],126:[function(t,e,r){"use strict";r.__esModule=!0,r.default=function(){for(var t=[],e=[],r=0;r<32;r++)t[r]=r,e[r]=r;t[n.BLEND_MODES.NORMAL_NPM]=n.BLEND_MODES.NORMAL,t[n.BLEND_MODES.ADD_NPM]=n.BLEND_MODES.ADD,t[n.BLEND_MODES.SCREEN_NPM]=n.BLEND_MODES.SCREEN,e[n.BLEND_MODES.NORMAL]=n.BLEND_MODES.NORMAL_NPM,e[n.BLEND_MODES.ADD]=n.BLEND_MODES.ADD_NPM,e[n.BLEND_MODES.SCREEN]=n.BLEND_MODES.SCREEN_NPM;var i=[];return i.push(e),i.push(t),i};var n=t("../const")},{"../const":46}],127:[function(t,e,r){"use strict";r.__esModule=!0,r.default=function(t){if(o.default.tablet||o.default.phone)return 4;return t};var i,n=t("ismobilejs"),o=(i=n)&&i.__esModule?i:{default:i}},{ismobilejs:4}],128:[function(t,e,r){"use strict";function i(t,e){if(t&&e)for(var r=Object.keys(e),i=0;i=this._durations[this.currentFrame];)i-=this._durations[this.currentFrame]*n,this._currentTime+=n;this._currentTime+=i/this._durations[this.currentFrame]}else this._currentTime+=e;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):r!==this.currentFrame&&(this.loop&&this.onLoop&&(0r&&this.onLoop()),this.updateTexture())},u.prototype.updateTexture=function(){this._texture=this._textures[this.currentFrame],this._textureID=-1,this.cachedTint=16777215,this.updateAnchor&&this._anchor.copy(this._texture.defaultAnchor),this.onFrameChange&&this.onFrameChange(this.currentFrame)},u.prototype.destroy=function(t){this.stop(),s.prototype.destroy.call(this,t)},u.fromFrames=function(t){for(var e=[],r=0;ra&&(++p,R.utils.removeItems(i,1+d-p,1+g-d),g=d,d=-1,n.push(f),l=Math.max(l,f),c++,r.x=0,r.y+=t.lineHeight,u=null))}else n.push(h),l=Math.max(l,h),++c,++p,r.x=0,r.y+=t.lineHeight,u=null}var x=o.charAt(o.length-1);"\r"!==x&&"\n"!==x&&(/(?:\s)/.test(x)&&(h=f),n.push(h),l=Math.max(l,h));for(var b=[],T=0;T<=c;T++){var w=0;"right"===this._font.align?w=l-n[T]:"center"===this._font.align&&(w=(l-n[T])/2),b.push(w)}for(var E=i.length,S=this.tint,O=0;O=i&&u.x=n&&u.y>16&255)/255,s=(r>>8&255)/255,a=(255&r)/255,u=((i=i||3375104)>>16&255)/255,h=(i>>8&255)/255,l=(255&i)/255,c=[.3,.59,.11,0,0,o,s,a,t=t||.2,0,u,h,l,e=e||.15,0,o-u,s-h,a-l,0,0];this._loadMatrix(c,n)},u.prototype.night=function(t,e){var r=[-2*(t=t||.1),-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(r,e)},u.prototype.predator=function(t,e){var r=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(r,e)},u.prototype.lsd=function(t){this._loadMatrix([2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0],t)},u.prototype.reset=function(){this._loadMatrix([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],!1)},i(u,[{key:"matrix",get:function(){return this.uniforms.m},set:function(t){this.uniforms.m=t}},{key:"alpha",get:function(){return this.uniforms.uAlpha},set:function(t){this.uniforms.uAlpha=t}}]),u);function u(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,u);var t=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,s.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n"));return t.uniforms.m=[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],t.alpha=1,t}(r.default=a).prototype.grayscale=a.prototype.greyscale},{"../../core":65,path:8}],151:[function(t,e,r){"use strict";r.__esModule=!0;var i=function(t,e,r){return e&&n(t.prototype,e),r&&n(t,r),t};function n(t,e){for(var r=0;r lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec2 fragCoord = vTextureCoord * filterArea.xy;\n\n vec4 color;\n\n color = fxaa(uSampler, fragCoord, filterArea.xy, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n'))}r.default=o},{"../../core":65,path:8}],153:[function(t,e,r){"use strict";r.__esModule=!0;var i=t("./fxaa/FXAAFilter");Object.defineProperty(r,"FXAAFilter",{enumerable:!0,get:function(){return c(i).default}});var n=t("./noise/NoiseFilter");Object.defineProperty(r,"NoiseFilter",{enumerable:!0,get:function(){return c(n).default}});var o=t("./displacement/DisplacementFilter");Object.defineProperty(r,"DisplacementFilter",{enumerable:!0,get:function(){return c(o).default}});var s=t("./blur/BlurFilter");Object.defineProperty(r,"BlurFilter",{enumerable:!0,get:function(){return c(s).default}});var a=t("./blur/BlurXFilter");Object.defineProperty(r,"BlurXFilter",{enumerable:!0,get:function(){return c(a).default}});var u=t("./blur/BlurYFilter");Object.defineProperty(r,"BlurYFilter",{enumerable:!0,get:function(){return c(u).default}});var h=t("./colormatrix/ColorMatrixFilter");Object.defineProperty(r,"ColorMatrixFilter",{enumerable:!0,get:function(){return c(h).default}});var l=t("./alpha/AlphaFilter");function c(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(r,"AlphaFilter",{enumerable:!0,get:function(){return c(l).default}})},{"./alpha/AlphaFilter":143,"./blur/BlurFilter":144,"./blur/BlurXFilter":145,"./blur/BlurYFilter":146,"./colormatrix/ColorMatrixFilter":150,"./displacement/DisplacementFilter":151,"./fxaa/FXAAFilter":152,"./noise/NoiseFilter":154}],154:[function(t,e,r){"use strict";r.__esModule=!0;var i=function(t,e,r){return e&&n(t.prototype,e),r&&n(t,r),t};function n(t,e){for(var r=0;r 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n"));return r.noise=t,r.seed=e,r}r.default=a},{"../../core":65,path:8}],155:[function(t,e,r){"use strict";r.__esModule=!0;var i=function(t,e,r){return e&&n(t.prototype,e),r&&n(t,r),t};function n(t,e){for(var r=0;re?1:this._height/e;t[9]=t[11]=t[13]=t[15]=this._topHeight*r,t[17]=t[19]=t[21]=t[23]=this._height-this._bottomHeight*r,t[25]=t[27]=t[29]=t[31]=this._height},h.prototype.updateVerticalVertices=function(){var t=this.vertices,e=this._leftWidth+this._rightWidth,r=this._width>e?1:this._width/e;t[2]=t[10]=t[18]=t[26]=this._leftWidth*r,t[4]=t[12]=t[20]=t[28]=this._width-this._rightWidth*r,t[6]=t[14]=t[22]=t[30]=this._width},h.prototype._renderCanvas=function(t){var e=t.context,r=this.worldTransform,i=t.resolution,n=16777215!==this.tint,o=this._texture;n&&this._cachedTint!==this.tint&&(this._cachedTint=this.tint,this._tintedTexture=b.default.getTintedTexture(this,this.tint));var s=n?this._tintedTexture:o.baseTexture.source;this._canvasUvs||(this._canvasUvs=[0,0,0,0,0,0,0,0]);var a=this.vertices,u=this._canvasUvs,h=n?0:o.frame.x,l=n?0:o.frame.y,c=h+o.frame.width,d=l+o.frame.height;u[0]=h,u[1]=h+this._leftWidth,u[2]=c-this._rightWidth,u[3]=c,u[4]=l,u[5]=l+this._topHeight,u[6]=d-this._bottomHeight,u[7]=d;for(var f=0;f<8;f++)u[f]*=o.baseTexture.resolution;e.globalAlpha=this.worldAlpha,t.setBlendMode(this.blendMode),t.roundPixels||this.roundPixels?e.setTransform(r.a*i,r.b*i,r.c*i,r.d*i,r.tx*i|0,r.ty*i|0):e.setTransform(r.a*i,r.b*i,r.c*i,r.d*i,r.tx*i,r.ty*i);for(var p=0;p<3;p++)for(var v=0;v<3;v++){var g=2*v+8*p,y=Math.max(1,u[v+1]-u[v]),m=Math.max(1,u[p+5]-u[p+4]),_=Math.max(1,a[10+g]-a[g]),x=Math.max(1,a[11+g]-a[1+g]);e.drawImage(s,u[v],u[p+4],y,m,a[g],a[1+g],_,x)}},h.prototype._refresh=function(){a.prototype._refresh.call(this);var t=this.uvs,e=this._texture;this._origWidth=e.orig.width,this._origHeight=e.orig.height;var r=1/this._origWidth,i=1/this._origHeight;t[0]=t[8]=t[16]=t[24]=0,t[1]=t[3]=t[5]=t[7]=0,t[6]=t[14]=t[22]=t[30]=1,t[25]=t[27]=t[29]=t[31]=1,t[2]=t[10]=t[18]=t[26]=r*this._leftWidth,t[4]=t[12]=t[20]=t[28]=1-r*this._rightWidth,t[9]=t[11]=t[13]=t[15]=i*this._topHeight,t[17]=t[19]=t[21]=t[23]=1-i*this._bottomHeight,this.updateHorizontalVertices(),this.updateVerticalVertices(),this.dirty++,this.multiplyUvs()},i(h,[{key:"width",get:function(){return this._width},set:function(t){this._width=t,this._refresh()}},{key:"height",get:function(){return this._height},set:function(t){this._height=t,this._refresh()}},{key:"leftWidth",get:function(){return this._leftWidth},set:function(t){this._leftWidth=t,this._refresh()}},{key:"rightWidth",get:function(){return this._rightWidth},set:function(t){this._rightWidth=t,this._refresh()}},{key:"topHeight",get:function(){return this._topHeight},set:function(t){this._topHeight=t,this._refresh()}},{key:"bottomHeight",get:function(){return this._bottomHeight},set:function(t){this._bottomHeight=t,this._refresh()}}]),h);function h(t,e,r,i,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,h);var o=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,a.call(this,t,4,4));return o._origWidth=t.orig.width,o._origHeight=t.orig.height,o._width=o._origWidth,o._height=o._origHeight,o._leftWidth=void 0!==e?e:10,o._rightWidth=void 0!==i?i:10,o._topHeight=void 0!==r?r:10,o._bottomHeight=void 0!==n?n:10,o._cachedTint=16777215,o._tintedTexture=null,o._canvasUvs=null,o.refresh(!0),o}r.default=u},{"../core/sprites/canvas/CanvasTinter":104,"./Plane":168}],168:[function(t,e,r){"use strict";r.__esModule=!0;var i,n=t("./Mesh"),o=(i=n)&&i.__esModule?i:{default:i};var s,a=(function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(u,s=o.default),u.prototype._refresh=function(){for(var t=this._texture,e=this.verticesX*this.verticesY,r=[],i=[],n=[],o=this.verticesX-1,s=this.verticesY-1,a=t.width/o,u=t.height/s,h=0;h=s.length){if(!t.autoResize)break;s.push(this._generateOneMoreBuffer(t))}var p=s[d];p.uploadDynamic(e,c,f);var v=t._bufferUpdateIDs[d]||0;(l=l||p._updateID 0) { + this.extraHeaders = opts.extraHeaders; + } + } + + this.open(); +} + +Socket.priorWebsocketSuccess = false; + +/** + * Mix in `Emitter`. + */ + +Emitter(Socket.prototype); + +/** + * Protocol version. + * + * @api public + */ + +Socket.protocol = parser.protocol; // this is an int + +/** + * Expose deps for legacy compatibility + * and standalone browser access. + */ + +Socket.Socket = Socket; +Socket.Transport = _dereq_('./transport'); +Socket.transports = _dereq_('./transports'); +Socket.parser = _dereq_('engine.io-parser'); + +/** + * Creates transport of the given type. + * + * @param {String} transport name + * @return {Transport} + * @api private + */ + +Socket.prototype.createTransport = function (name) { + debug('creating transport "%s"', name); + var query = clone(this.query); + + // append engine.io protocol identifier + query.EIO = parser.protocol; + + // transport name + query.transport = name; + + // session id if we already have one + if (this.id) query.sid = this.id; + + var transport = new transports[name]({ + agent: this.agent, + hostname: this.hostname, + port: this.port, + secure: this.secure, + path: this.path, + query: query, + forceJSONP: this.forceJSONP, + jsonp: this.jsonp, + forceBase64: this.forceBase64, + enablesXDR: this.enablesXDR, + timestampRequests: this.timestampRequests, + timestampParam: this.timestampParam, + policyPort: this.policyPort, + socket: this, + pfx: this.pfx, + key: this.key, + passphrase: this.passphrase, + cert: this.cert, + ca: this.ca, + ciphers: this.ciphers, + rejectUnauthorized: this.rejectUnauthorized, + perMessageDeflate: this.perMessageDeflate, + extraHeaders: this.extraHeaders + }); + + return transport; +}; + +function clone (obj) { + var o = {}; + for (var i in obj) { + if (obj.hasOwnProperty(i)) { + o[i] = obj[i]; + } + } + return o; +} + +/** + * Initializes transport to use and starts probe. + * + * @api private + */ +Socket.prototype.open = function () { + var transport; + if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) { + transport = 'websocket'; + } else if (0 === this.transports.length) { + // Emit error on next tick so it can be listened to + var self = this; + setTimeout(function() { + self.emit('error', 'No transports available'); + }, 0); + return; + } else { + transport = this.transports[0]; + } + this.readyState = 'opening'; + + // Retry with the next transport if the transport is disabled (jsonp: false) + try { + transport = this.createTransport(transport); + } catch (e) { + this.transports.shift(); + this.open(); + return; + } + + transport.open(); + this.setTransport(transport); +}; + +/** + * Sets the current transport. Disables the existing one (if any). + * + * @api private + */ + +Socket.prototype.setTransport = function(transport){ + debug('setting transport %s', transport.name); + var self = this; + + if (this.transport) { + debug('clearing existing transport %s', this.transport.name); + this.transport.removeAllListeners(); + } + + // set up transport + this.transport = transport; + + // set up transport listeners + transport + .on('drain', function(){ + self.onDrain(); + }) + .on('packet', function(packet){ + self.onPacket(packet); + }) + .on('error', function(e){ + self.onError(e); + }) + .on('close', function(){ + self.onClose('transport close'); + }); +}; + +/** + * Probes a transport. + * + * @param {String} transport name + * @api private + */ + +Socket.prototype.probe = function (name) { + debug('probing transport "%s"', name); + var transport = this.createTransport(name, { probe: 1 }) + , failed = false + , self = this; + + Socket.priorWebsocketSuccess = false; + + function onTransportOpen(){ + if (self.onlyBinaryUpgrades) { + var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary; + failed = failed || upgradeLosesBinary; + } + if (failed) return; + + debug('probe transport "%s" opened', name); + transport.send([{ type: 'ping', data: 'probe' }]); + transport.once('packet', function (msg) { + if (failed) return; + if ('pong' == msg.type && 'probe' == msg.data) { + debug('probe transport "%s" pong', name); + self.upgrading = true; + self.emit('upgrading', transport); + if (!transport) return; + Socket.priorWebsocketSuccess = 'websocket' == transport.name; + + debug('pausing current transport "%s"', self.transport.name); + self.transport.pause(function () { + if (failed) return; + if ('closed' == self.readyState) return; + debug('changing transport and sending upgrade packet'); + + cleanup(); + + self.setTransport(transport); + transport.send([{ type: 'upgrade' }]); + self.emit('upgrade', transport); + transport = null; + self.upgrading = false; + self.flush(); + }); + } else { + debug('probe transport "%s" failed', name); + var err = new Error('probe error'); + err.transport = transport.name; + self.emit('upgradeError', err); + } + }); + } + + function freezeTransport() { + if (failed) return; + + // Any callback called by transport should be ignored since now + failed = true; + + cleanup(); + + transport.close(); + transport = null; + } + + //Handle any error that happens while probing + function onerror(err) { + var error = new Error('probe error: ' + err); + error.transport = transport.name; + + freezeTransport(); + + debug('probe transport "%s" failed because of error: %s', name, err); + + self.emit('upgradeError', error); + } + + function onTransportClose(){ + onerror("transport closed"); + } + + //When the socket is closed while we're probing + function onclose(){ + onerror("socket closed"); + } + + //When the socket is upgraded while we're probing + function onupgrade(to){ + if (transport && to.name != transport.name) { + debug('"%s" works - aborting "%s"', to.name, transport.name); + freezeTransport(); + } + } + + //Remove all listeners on the transport and on self + function cleanup(){ + transport.removeListener('open', onTransportOpen); + transport.removeListener('error', onerror); + transport.removeListener('close', onTransportClose); + self.removeListener('close', onclose); + self.removeListener('upgrading', onupgrade); + } + + transport.once('open', onTransportOpen); + transport.once('error', onerror); + transport.once('close', onTransportClose); + + this.once('close', onclose); + this.once('upgrading', onupgrade); + + transport.open(); + +}; + +/** + * Called when connection is deemed open. + * + * @api public + */ + +Socket.prototype.onOpen = function () { + debug('socket open'); + this.readyState = 'open'; + Socket.priorWebsocketSuccess = 'websocket' == this.transport.name; + this.emit('open'); + this.flush(); + + // we check for `readyState` in case an `open` + // listener already closed the socket + if ('open' == this.readyState && this.upgrade && this.transport.pause) { + debug('starting upgrade probes'); + for (var i = 0, l = this.upgrades.length; i < l; i++) { + this.probe(this.upgrades[i]); + } + } +}; + +/** + * Handles a packet. + * + * @api private + */ + +Socket.prototype.onPacket = function (packet) { + if ('opening' == this.readyState || 'open' == this.readyState) { + debug('socket receive: type "%s", data "%s"', packet.type, packet.data); + + this.emit('packet', packet); + + // Socket is live - any packet counts + this.emit('heartbeat'); + + switch (packet.type) { + case 'open': + this.onHandshake(parsejson(packet.data)); + break; + + case 'pong': + this.setPing(); + this.emit('pong'); + break; + + case 'error': + var err = new Error('server error'); + err.code = packet.data; + this.onError(err); + break; + + case 'message': + this.emit('data', packet.data); + this.emit('message', packet.data); + break; + } + } else { + debug('packet received with socket readyState "%s"', this.readyState); + } +}; + +/** + * Called upon handshake completion. + * + * @param {Object} handshake obj + * @api private + */ + +Socket.prototype.onHandshake = function (data) { + this.emit('handshake', data); + this.id = data.sid; + this.transport.query.sid = data.sid; + this.upgrades = this.filterUpgrades(data.upgrades); + this.pingInterval = data.pingInterval; + this.pingTimeout = data.pingTimeout; + this.onOpen(); + // In case open handler closes socket + if ('closed' == this.readyState) return; + this.setPing(); + + // Prolong liveness of socket on heartbeat + this.removeListener('heartbeat', this.onHeartbeat); + this.on('heartbeat', this.onHeartbeat); +}; + +/** + * Resets ping timeout. + * + * @api private + */ + +Socket.prototype.onHeartbeat = function (timeout) { + clearTimeout(this.pingTimeoutTimer); + var self = this; + self.pingTimeoutTimer = setTimeout(function () { + if ('closed' == self.readyState) return; + self.onClose('ping timeout'); + }, timeout || (self.pingInterval + self.pingTimeout)); +}; + +/** + * Pings server every `this.pingInterval` and expects response + * within `this.pingTimeout` or closes connection. + * + * @api private + */ + +Socket.prototype.setPing = function () { + var self = this; + clearTimeout(self.pingIntervalTimer); + self.pingIntervalTimer = setTimeout(function () { + debug('writing ping packet - expecting pong within %sms', self.pingTimeout); + self.ping(); + self.onHeartbeat(self.pingTimeout); + }, self.pingInterval); +}; + +/** +* Sends a ping packet. +* +* @api private +*/ + +Socket.prototype.ping = function () { + var self = this; + this.sendPacket('ping', function(){ + self.emit('ping'); + }); +}; + +/** + * Called on `drain` event + * + * @api private + */ + +Socket.prototype.onDrain = function() { + this.writeBuffer.splice(0, this.prevBufferLen); + + // setting prevBufferLen = 0 is very important + // for example, when upgrading, upgrade packet is sent over, + // and a nonzero prevBufferLen could cause problems on `drain` + this.prevBufferLen = 0; + + if (0 === this.writeBuffer.length) { + this.emit('drain'); + } else { + this.flush(); + } +}; + +/** + * Flush write buffers. + * + * @api private + */ + +Socket.prototype.flush = function () { + if ('closed' != this.readyState && this.transport.writable && + !this.upgrading && this.writeBuffer.length) { + debug('flushing %d packets in socket', this.writeBuffer.length); + this.transport.send(this.writeBuffer); + // keep track of current length of writeBuffer + // splice writeBuffer and callbackBuffer on `drain` + this.prevBufferLen = this.writeBuffer.length; + this.emit('flush'); + } +}; + +/** + * Sends a message. + * + * @param {String} message. + * @param {Function} callback function. + * @param {Object} options. + * @return {Socket} for chaining. + * @api public + */ + +Socket.prototype.write = +Socket.prototype.send = function (msg, options, fn) { + this.sendPacket('message', msg, options, fn); + return this; +}; + +/** + * Sends a packet. + * + * @param {String} packet type. + * @param {String} data. + * @param {Object} options. + * @param {Function} callback function. + * @api private + */ + +Socket.prototype.sendPacket = function (type, data, options, fn) { + if('function' == typeof data) { + fn = data; + data = undefined; + } + + if ('function' == typeof options) { + fn = options; + options = null; + } + + if ('closing' == this.readyState || 'closed' == this.readyState) { + return; + } + + options = options || {}; + options.compress = false !== options.compress; + + var packet = { + type: type, + data: data, + options: options + }; + this.emit('packetCreate', packet); + this.writeBuffer.push(packet); + if (fn) this.once('flush', fn); + this.flush(); +}; + +/** + * Closes the connection. + * + * @api private + */ + +Socket.prototype.close = function () { + if ('opening' == this.readyState || 'open' == this.readyState) { + this.readyState = 'closing'; + + var self = this; + + if (this.writeBuffer.length) { + this.once('drain', function() { + if (this.upgrading) { + waitForUpgrade(); + } else { + close(); + } + }); + } else if (this.upgrading) { + waitForUpgrade(); + } else { + close(); + } + } + + function close() { + self.onClose('forced close'); + debug('socket closing - telling transport to close'); + self.transport.close(); + } + + function cleanupAndClose() { + self.removeListener('upgrade', cleanupAndClose); + self.removeListener('upgradeError', cleanupAndClose); + close(); + } + + function waitForUpgrade() { + // wait for upgrade to finish since we can't send packets while pausing a transport + self.once('upgrade', cleanupAndClose); + self.once('upgradeError', cleanupAndClose); + } + + return this; +}; + +/** + * Called upon transport error + * + * @api private + */ + +Socket.prototype.onError = function (err) { + debug('socket error %j', err); + Socket.priorWebsocketSuccess = false; + this.emit('error', err); + this.onClose('transport error', err); +}; + +/** + * Called upon transport close. + * + * @api private + */ + +Socket.prototype.onClose = function (reason, desc) { + if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) { + debug('socket close with reason: "%s"', reason); + var self = this; + + // clear timers + clearTimeout(this.pingIntervalTimer); + clearTimeout(this.pingTimeoutTimer); + + // stop event from firing again for transport + this.transport.removeAllListeners('close'); + + // ensure transport won't stay open + this.transport.close(); + + // ignore further transport communication + this.transport.removeAllListeners(); + + // set ready state + this.readyState = 'closed'; + + // clear session id + this.id = null; + + // emit close event + this.emit('close', reason, desc); + + // clean buffers after, so users can still + // grab the buffers on `close` event + self.writeBuffer = []; + self.prevBufferLen = 0; + } +}; + +/** + * Filters upgrades, returning only those matching client transports. + * + * @param {Array} server upgrades + * @api private + * + */ + +Socket.prototype.filterUpgrades = function (upgrades) { + var filteredUpgrades = []; + for (var i = 0, j = upgrades.length; i